Compare commits

..
16 Commits
Author SHA1 Message Date
Zach Rice 6f6ebd454f fix off by one line number for --no-git 2021-12-08 15:04:32 -06:00
Zachary Rice ce42947cae fix deduplication issue caused by clobbered findings (#742)
* fix deduplication issue caused by clobbered findings

* fix index

* remove indexing, slow is better than wrong
2021-12-07 19:11:37 -06:00
Zach Rice 84e285e4ce ignore gitleaks.toml by default 2021-12-06 10:43:21 -06:00
Ben Randall 928c6a6043 Update pre-commit step to run gitleaks checks (#729)
* Fix pre-commit config.

* Debug output

* No debug and use redacted.

* Typo

* Add back staged.

* Update .pre-commit-hooks.yaml

* Update .pre-commit-hooks.yaml
2021-12-03 16:09:05 -06:00
Florian Greinacher 106897fdf0 fix: format dates in log in a portable way (#735)
The output of time.String() depends on the runtime environment and should only be used for debugging.

This commit ensures that a well-defined UTC time is written to the report.
2021-12-03 09:34:57 -06:00
Zachary Rice 98d5648f6e introducing secretGroup, the best group (#734)
* working on deduping

* my eyes... oh god my poor eyes

* more readme

* more readme

* more readme

* more readme and formatting
2021-12-02 20:04:36 -06:00
zricethezav 9358e84588 fix typo in readme 2021-12-02 13:55:43 -06:00
zricethezav 958c18f0b7 fix typo in config help 2021-12-02 13:44:39 -06:00
Zachary Rice 089639e9fb bump go-gitdiff (#731) 2021-12-02 08:29:38 -06:00
Zachary Rice 85afd767f7 Update README.md 2021-12-01 18:38:22 -06:00
Zachary Rice 38006fb93b Update README.md 2021-11-30 14:31:08 -06:00
Zachary Rice 9ae1def963 lil hack to avoid scans 'finishing' when git errors are present (#726) 2021-11-30 12:31:25 -06:00
Zachary Rice 6517900e5a Update README.md 2021-11-30 12:24:10 -06:00
Zachary Rice 5e51da600b use exit code 126 on 'unknown-flag' errors (#723) 2021-11-30 09:47:00 -06:00
Zachary Rice f0b8d26c99 Update README.md 2021-11-27 10:40:00 -06:00
Zachary Rice 1724591029 remove generic api key from default gitleaks config (#719) 2021-11-27 10:01:52 -06:00
35 changed files with 417 additions and 190 deletions

No files matched your search

+6
View File
@@ -9,6 +9,12 @@ builds:
- windows
goarch:
- amd64
- "386"
- arm
- arm64
goarm:
- "6"
- "7"
ldflags:
- -s -w -X=github.com/zricethezav/gitleaks/v8/cmd.Version={{.Version}}
archives:
+1 -1
View File
@@ -1,6 +1,6 @@
- id: gitleaks
name: Detect hardcoded secrets
description: Detect hardcoded secrets using Gitleaks
entry: gitleaks
entry: gitleaks protect --verbose --redact --staged
language: golang
pass_filenames: false
+64 -6
View File
@@ -24,6 +24,10 @@
Gitleaks is a SAST tool for detecting hardcoded secrets like passwords, api keys, and tokens in git repos. Gitleaks is an **easy-to-use, all-in-one solution** for detecting secrets, past or present, in your code.
#### 💫⭐✨ Temporary README message 💫⭐✨
It would be so great if you could fill out this quick gitleaks [user survey](https://docs.google.com/forms/d/1poUqZfEamDY1kCp8v8hU6N3fUj8C5_lVNBD_cDe-GT4).
<3
## Getting Started
Gitleaks can be installed using Homebrew, Docker, or Go. Gitleaks is also available in binary form for many popular platforms and OS types on the [releases page](https://github.com/zricethezav/gitleaks/releases). In addition, Gitleaks can be implemented as a pre-commit hook directly in your repo.
@@ -75,7 +79,7 @@ Flags:
order of precedence:
1. --config/-c
2. (--source/-s)/.gitleaks.toml
if --config/-c is not set and no .gitleaks.toml/gitleaks.toml present
if --config/-c is not set and no (--source/-s)/.gitleaks.toml present
then .gitleaks.toml will be written to (--source/-s)/.gitleaks.toml for future use
--exit-code string exit code when leaks have been encountered (default: 1)
-h, --help help for gitleaks
@@ -106,7 +110,7 @@ You can scan files and directories by using the `--no-git` option.
#### Protect
The `protect` command is used to uncommitted changes in a git repo. This command should be used on developer machines in accordance with
[shifting left on security](https://cloud.google.com/architecture/devops/devops-tech-shifting-left-on-security).
When running `detect` on a git repository, gitleaks will parse the output of a `git diff` command (you can see how this executed
When running `protect` on a git repository, gitleaks will parse the output of a `git diff` command (you can see how this executed
[here](https://github.com/zricethezav/gitleaks/blob/7240e16769b92d2a1b137c17d6bf9d55a8562899/git/git.go#L48-L49)). You can set the
`--staged` flag to check for changes in commits that have been `git add`ed. The `--staged` flag should be used when running Gitleaks
as a pre-commit.
@@ -123,7 +127,7 @@ Example output:
"EndLine": 37,
"StartColumn": 19,
"EndColumn": 38,
"Context": "\t\t\"aws_secret= \\\"AKIAIMNOJVGFDXXXE4OA\\\"\": true,",
"Match": "\t\t\"aws_secret= \\\"AKIAIMNOJVGFDXXXE4OA\\\"\": true,",
"Secret": "AKIAIMNOJVGFDXXXE4OA",
"File": "checks_test.go",
"Commit": "ec2fc9d6cb0954fb3b57201cf6133c48d8ca0d29",
@@ -188,8 +192,9 @@ regex = '''one-go-style-regex-for-this-rule'''
path = '''a-file-path-regex'''
# Array of strings used for metadata and reporting purposes.
tags = ["tag","another tag"]
# Int used to check shannon entropy of a specific group in a regex match.
entropyGroup = 3
# 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
# You can include an allowlist table for a single rule to reduce false positives or ignore commits
@@ -209,7 +214,59 @@ commits = [ "commit-A", "commit-B"]
paths = ['''one-file-path-regex''']
regexes = ['''one-regex-within-the-already-matched-regex''']
```
Refer to the default [gitleaks config](https://github.com/zricethezav/gitleaks/blob/v8/config/gitleaks.toml) for examples and advice on writing regular expressions for secret detection.
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.
## Exit Codes
@@ -217,4 +274,5 @@ You can always set the exit code when leaks are encountered with the --exit-code
```
0 - no leaks present
1 - leaks or error encountered
126 - unknown flag
```
+1 -1
View File
@@ -31,7 +31,7 @@ func runDetect(cmd *cobra.Command, args []string) {
initConfig()
var (
vc config.ViperConfig
findings []*report.Finding
findings []report.Finding
err error
)
+23 -6
View File
@@ -27,7 +27,7 @@ const configDescription = `config file path
order of precedence:
1. --config/-c
2. (--source/-s)/.gitleaks.toml
if --config/-c is not set and no .gitleaks.toml/gitleaks.toml present
if --config/-c is not set and no (--source/s)/.gitleaks.toml is present
then .gitleaks.toml will be written to (--source/-s)/.gitleaks.toml for future use`
var rootCmd = &cobra.Command{
@@ -52,7 +52,7 @@ func initLog() {
zerolog.SetGlobalLevel(zerolog.InfoLevel)
ll, err := rootCmd.Flags().GetString("log-level")
if err != nil {
log.Fatal().Err(err)
log.Fatal().Msg(err.Error())
}
switch strings.ToLower(ll) {
case "debug":
@@ -74,7 +74,7 @@ func initConfig() {
fmt.Fprintf(os.Stderr, banner)
cfgPath, err := rootCmd.Flags().GetString("config")
if err != nil {
log.Fatal().Err(err)
log.Fatal().Msg(err.Error())
}
if cfgPath != "" {
viper.SetConfigFile(cfgPath)
@@ -82,12 +82,25 @@ func initConfig() {
} else {
source, err := rootCmd.Flags().GetString("source")
if err != nil {
log.Fatal().Err(err)
log.Fatal().Msg(err.Error())
}
fileInfo, err := os.Stat(source)
if err != nil {
log.Fatal().Msg(err.Error())
}
if !fileInfo.IsDir() {
log.Debug().Msgf("Unable to write default gitleaks config to %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))
return
}
if _, err := os.Stat(filepath.Join(source, ".gitleaks.toml")); os.IsNotExist(err) {
log.Debug().Msgf("No gitleaks config found, writing default gitleaks config to %s", filepath.Join(source, ".gitleaks.toml"))
if err := os.WriteFile(filepath.Join(source, ".gitleaks.toml"), []byte(config.DefaultConfig), os.ModePerm); err != nil {
log.Debug().Msgf("Unable to write default gitleaks config to %s", filepath.Join(source, ".gitleaks.toml, using default config"))
log.Debug().Msgf("Unable to write default gitleaks config to %s, using default config", filepath.Join(source, ".gitleaks.toml"))
viper.SetConfigType("toml")
viper.ReadConfig(strings.NewReader(config.DefaultConfig))
return
@@ -107,6 +120,10 @@ func initConfig() {
func Execute() {
if err := rootCmd.Execute(); err != nil {
log.Fatal().Err(err)
if strings.Contains(err.Error(), "unknown flag") {
// exit code 126: Command invoked cannot execute
os.Exit(126)
}
log.Fatal().Msg(err.Error())
}
}
+16 -16
View File
@@ -15,13 +15,13 @@ var DefaultConfig string
type ViperConfig struct {
Description string
Rules []struct {
ID string
Description string
Entropy float64
EntropyGroup int
Regex string
Path string
Tags []string
ID string
Description string
Entropy float64
SecretGroup int
Regex string
Path string
Tags []string
Allowlist struct {
Regexes []string
@@ -73,21 +73,21 @@ func (vc *ViperConfig) Translate() (Config, error) {
configPathRegex = regexp.MustCompile(r.Path)
}
r := &Rule{
Description: r.Description,
RuleID: r.ID,
Regex: configRegex,
Path: configPathRegex,
EntropyReGroup: r.EntropyGroup,
Entropy: r.Entropy,
Tags: r.Tags,
Description: r.Description,
RuleID: r.ID,
Regex: configRegex,
Path: configPathRegex,
SecretGroup: r.SecretGroup,
Entropy: r.Entropy,
Tags: r.Tags,
Allowlist: Allowlist{
Regexes: allowlistRegexes,
Paths: allowlistPaths,
Commits: r.Allowlist.Commits,
},
}
if r.Regex != nil && r.EntropyReGroup > r.Regex.NumSubexp() {
return Config{}, fmt.Errorf("%s invalid regex entropy group %d, max regex entropy group %d", r.Description, r.EntropyReGroup, r.Regex.NumSubexp())
if r.Regex != nil && r.SecretGroup > r.Regex.NumSubexp() {
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)
+23 -34
View File
@@ -74,13 +74,13 @@ func TestTranslate(t *testing.T) {
cfg: Config{
Rules: []*Rule{
{
Description: "Discord API key",
Regex: regexp.MustCompile(`(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-h0-9]{64})['\"]`),
RuleID: "discord-api-key",
Allowlist: Allowlist{},
Entropy: 3.5,
EntropyReGroup: 3,
Tags: []string{},
Description: "Discord API key",
Regex: regexp.MustCompile(`(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-h0-9]{64})['\"]`),
RuleID: "discord-api-key",
Allowlist: Allowlist{},
Entropy: 3.5,
SecretGroup: 3,
Tags: []string{},
},
},
},
@@ -88,7 +88,7 @@ func TestTranslate(t *testing.T) {
{
cfgName: "bad_entropy_group",
cfg: Config{},
wantError: fmt.Errorf("Discord API key invalid regex entropy group 5, max regex entropy group 3"),
wantError: fmt.Errorf("Discord API key invalid regex secret group 5, max regex secret group 3"),
},
}
@@ -125,45 +125,34 @@ func TestIncludeEntropy(t *testing.T) {
}{
{
rule: Rule{
RuleID: "generic-api-key",
EntropyReGroup: 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})['\"]`),
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: `Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
secret: `e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5`,
entropy: 3.7906235872459746,
include: true,
},
{
rule: Rule{
RuleID: "generic-api-key",
EntropyReGroup: 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})['\"]`),
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: `Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
secret: `e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5`,
entropy: 3.7906235872459746,
include: false,
},
{
rule: Rule{
RuleID: "generic-api-key",
EntropyReGroup: 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})['\"]`),
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: `KeyboardInteractiveName = "ssh-keyboard-interactive"`,
entropy: 0,
include: false,
},
{
rule: Rule{
RuleID: "generic-api-key",
EntropyReGroup: 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: `KeyboardInteractiveName = "ssh-keyboard-interactive"`,
secret: `ssh-keyboard-interactive`,
entropy: 0,
include: false,
},
+111 -10
View File
@@ -126,14 +126,6 @@ id = "pypi-upload-token"
description = "PyPI upload token"
regex = '''pypi-AgEIcHlwaS5vcmc[A-Za-z0-9-_]{50,1000}'''
[[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
entropyGroup = 4
# ➜ ~/code/gitleaks (v8) git show ec2fc9d6cb0954fb3b57201cf6133c48d8ca0d29 -- checks_test.go
[[rules]]
id = "gcp-service-account"
description = "Google (GCP) Service-account"
@@ -143,6 +135,7 @@ regex = '''\"type\": \"service_account\"'''
id = "heroku-api-key"
description = "Heroku API Key"
regex = ''' (?i)(heroku[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12})['\"]'''
secretGroup = 3
[[rules]]
id = "slack-web-hook"
@@ -163,16 +156,19 @@ regex = '''AGE-SECRET-KEY-1[QPZRY9X8GF2TVDW0S3JN54KHCE6MUA7L]{58}'''
id = "facebook-token"
description = "Facebook token"
regex = '''(?i)(facebook[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-f0-9]{32})['\"]'''
secretGroup = 3
[[rules]]
id = "twitter-token"
description = "Twitter token"
regex = '''(?i)(twitter[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-f0-9]{35,44})['\"]'''
secretGroup = 3
[[rules]]
id = "adobe-client-id"
description = "Adobe Client ID (Oauth Web)"
regex = '''(?i)(adobe[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-f0-9]{32})['\"]'''
secretGroup = 3
[[rules]]
id = "adobe-client-secret"
@@ -188,261 +184,366 @@ regex = '''(LTAI)(?i)[a-z0-9]{20}'''
id = "alibaba-secret-key"
description = "Alibaba Secret Key"
regex = '''(?i)(alibaba[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{30})['\"]'''
secretGroup = 3
[[rules]]
id = "asana-client-id"
description = "Asana Client ID"
regex = '''(?i)(asana[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([0-9]{16})['\"]'''
secretGroup = 3
[[rules]]
id = "asana-client-secret"
description = "Asana Client Secret"
regex = '''(?i)(asana[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{32})['\"]'''
secretGroup = 3
[[rules]]
id = "atlassian-api-token"
description = "Atlassian API token"
regex = '''(?i)(atlassian[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{24})['\"]'''
secretGroup = 3
[[rules]]
id = "bitbucket-client-id"
description = "Bitbucket client ID"
regex = '''(?i)(bitbucket[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{32})['\"]'''
secretGroup = 3
[[rules]]
id = "bitbucket-client-secret"
description = "Bitbucket client secret"
regex = '''(?i)(bitbucket[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9_\-]{64})['\"]'''
secretGroup = 3
[[rules]]
id = "beamer-api-token"
description = "Beamer API token"
regex = '''(?i)(beamer[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"](b_[a-z0-9=_\-]{44})['\"]'''
secretGroup = 3
[[rules]]
id = "clojars-api-token"
description = "Clojars API token"
regex = '''(CLOJARS_)(?i)[a-z0-9]{60}'''
[[rules]]
id = "contentful-delivery-api-token"
description = "Contentful delivery API token"
regex = '''(?i)(contentful[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9\-=_]{43})['\"]'''
secretGroup = 3
[[rules]]
id = "contentful-preview-api-token"
description = "Contentful preview API token"
regex = '''(?i)(contentful[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9\-=_]{43})['\"]'''
secretGroup = 3
[[rules]]
id = "databricks-api-token"
description = "Databricks API token"
regex = '''dapi[a-h0-9]{32}'''
[[rules]]
id = "discord-api-token"
description = "Discord API key"
regex = '''(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-h0-9]{64})['\"]'''
secretGroup = 3
[[rules]]
id = "discord-client-id"
description = "Discord client ID"
regex = '''(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([0-9]{18})['\"]'''
secretGroup = 3
[[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 = "doppler-api-token"
description = "Doppler API token"
regex = '''['\"](dp\.pt\.)(?i)[a-z0-9]{43}['\"]'''
[[rules]]
id = "dropbox-api-secret"
description = "Dropbox API secret/key"
regex = '''(?i)(dropbox[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{15})['\"]'''
[[rules]]
id = "dropbox--api-key"
description = "Dropbox API secret/key"
regex = '''(?i)(dropbox[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{15})['\"]'''
[[rules]]
id = "dropbox-short-lived-api-token"
description = "Dropbox short lived API token"
regex = '''(?i)(dropbox[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"](sl\.[a-z0-9\-=_]{135})['\"]'''
[[rules]]
id = "dropbox-long-lived-api-token"
description = "Dropbox long lived API token"
regex = '''(?i)(dropbox)(.{0,20})['\"](?i)[a-z0-9]{11}(AAAAAAAAAA)[a-z0-9-_=]{43}['\"]'''
regex = '''(?i)(dropbox[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"][a-z0-9]{11}(AAAAAAAAAA)[a-z0-9\-_=]{43}['\"]'''
[[rules]]
id = "duffel-api-token"
description = "Duffel API token"
regex = '''['\"]duffel_(test|live)_(?i)[a-z0-9_-]{43}['\"]'''
[[rules]]
id = "dynatrace-api-token"
description = "Dynatrace API token"
regex = '''['\"]dt0c01\.(?i)[a-z0-9]{24}\.[a-z0-9]{64}['\"]'''
[[rules]]
id = "easypost-api-token"
description = "EasyPost API token"
regex = '''['\"]EZAK(?i)[a-z0-9]{54}['\"]'''
[[rules]]
id = "easypost-test-api-token"
description = "EasyPost test API token"
regex = '''['\"]EZTK(?i)[a-z0-9]{54}['\"]'''
[[rules]]
id = "fastly-api-token"
description = "Fastly API token"
regex = '''(?i)(fastly[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9\-=_]{32})['\"]'''
secretGroup = 3
[[rules]]
id = "finicity-client-secret"
description = "Finicity client secret"
regex = '''(?i)(finicity[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{20})['\"]'''
secretGroup = 3
[[rules]]
id = "finicity-api-token"
description = "Finicity API token"
regex = '''(?i)(finicity[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-f0-9]{32})['\"]'''
secretGroup = 3
[[rules]]
id = "flutterweave-public-key"
description = "Flutterweave public key"
regex = '''FLWPUBK_TEST-(?i)[a-h0-9]{32}-X'''
[[rules]]
id = "flutterweave-secret-key"
description = "Flutterweave secret key"
regex = '''FLWSECK_TEST-(?i)[a-h0-9]{32}-X'''
[[rules]]
id = "flutterweave-enc-key"
description = "Flutterweave encrypted key"
regex = '''FLWSECK_TEST[a-h0-9]{12}'''
[[rules]]
id = "frameio-api-token"
description = "Frame.io API token"
regex = '''fio-u-(?i)[a-z0-9-_=]{64}'''
[[rules]]
id = "gocardless-api-token"
description = "GoCardless API token"
regex = '''['\"]live_(?i)[a-z0-9-_=]{40}['\"]'''
[[rules]]
id = "grafana-api-token"
description = "Grafana API token"
regex = '''['\"]eyJrIjoi(?i)[a-z0-9-_=]{72,92}['\"]'''
[[rules]]
id = "hashicorp-tf-api-token"
description = "Hashicorp Terraform user/org API token"
regex = '''['\"](?i)[a-z0-9]{14}\.atlasv1\.[a-z0-9-_=]{60,70}['\"]'''
[[rules]]
id = "hubspot-api-token"
description = "Hubspot API token"
regex = '''(?i)(hubspot[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-h0-9]{8}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{12})['\"]'''
secretGroup = 3
[[rules]]
id = "intercom-api-token"
description = "Intercom API token"
regex = '''(?i)(intercom[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9=_]{60})['\"]'''
secretGroup = 3
[[rules]]
id = "intercom-client-secret"
description = "Intercom client secret/ID"
regex = '''(?i)(intercom[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-h0-9]{8}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{12})['\"]'''
secretGroup = 3
[[rules]]
id = "ionic-api-token"
description = "Ionic API token"
regex = '''ion_(?i)[a-z0-9]{42}'''
[[rules]]
id = "linear-api-token"
description = "Linear API token"
regex = '''lin_api_(?i)[a-z0-9]{40}'''
[[rules]]
id = "linear-client-secret"
description = "Linear client secret/ID"
regex = '''(?i)(linear[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-f0-9]{32})['\"]'''
secretGroup = 3
[[rules]]
id = "lob-api-key"
description = "Lob API Key"
regex = '''(?i)(lob[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]((live|test)_[a-f0-9]{35})['\"]'''
secretGroup = 3
[[rules]]
id = "lob-pub-api-key"
description = "Lob Publishable API Key"
regex = '''(?i)(lob[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]((test|live)_pub_[a-f0-9]{31})['\"]'''
secretGroup = 3
[[rules]]
id = "mailchimp-api-key"
description = "Mailchimp API key"
regex = '''(?i)(mailchimp[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-f0-9]{32}-us20)['\"]'''
secretGroup = 3
[[rules]]
id = "mailgun-private-api-token"
description = "Mailgun private API token"
regex = '''(?i)(mailgun[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"](key-[a-f0-9]{32})['\"]'''
secretGroup = 3
[[rules]]
id = "mailgun-pub-key"
description = "Mailgun public validation key"
regex = '''(?i)(mailgun[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"](pubkey-[a-f0-9]{32})['\"]'''
secretGroup = 3
[[rules]]
id = "mailgun-signing-key"
description = "Mailgun webhook signing key"
regex = '''(?i)(mailgun[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-h0-9]{32}-[a-h0-9]{8}-[a-h0-9]{8})['\"]'''
secretGroup = 3
[[rules]]
id = "mapbox-api-token"
description = "Mapbox API token"
regex = '''(?i)(pk\.[a-z0-9]{60}\.[a-z0-9]{22})'''
[[rules]]
id = "messagebird-api-token"
description = "MessageBird API token"
regex = '''(?i)(messagebird[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{25})['\"]'''
secretGroup = 3
[[rules]]
id = "messagebird-client-id"
description = "MessageBird API client ID"
regex = '''(?i)(messagebird[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-h0-9]{8}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{12})['\"]'''
secretGroup = 3
[[rules]]
id = "new-relic-user-api-key"
description = "New Relic user API Key"
regex = '''['\"](NRAK-[A-Z0-9]{27})['\"]'''
[[rules]]
id = "new-relic-user-api-id"
description = "New Relic user API ID"
regex = '''(?i)(newrelic[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([A-Z0-9]{64})['\"]'''
secretGroup = 3
[[rules]]
id = "new-relic-browser-api-token"
description = "New Relic ingest browser API token"
regex = '''['\"](NRJS-[a-f0-9]{19})['\"]'''
[[rules]]
id = "npm-access-token"
description = "npm access token"
regex = '''['\"](npm_(?i)[a-z0-9]{36})['\"]'''
[[rules]]
id = "planetscale-password"
description = "Planetscale password"
regex = '''pscale_pw_(?i)[a-z0-9\-_\.]{43}'''
[[rules]]
id = "planetscale-api-token"
description = "Planetscale API token"
regex = '''pscale_tkn_(?i)[a-z0-9\-_\.]{43}'''
[[rules]]
id = "postman-api-token"
description = "Postman API token"
regex = '''PMAK-(?i)[a-f0-9]{24}\-[a-f0-9]{34}'''
[[rules]]
id = "pulumi-api-token"
description = "Pulumi API token"
regex = '''pul-[a-f0-9]{40}'''
[[rules]]
id = "rubygems-api-token"
description = "Rubygem API token"
regex = '''rubygems_[a-f0-9]{48}'''
[[rules]]
id = "sendgrid-api-token"
description = "Sendgrid API token"
regex = '''SG\.(?i)[a-z0-9_\-\.]{66}'''
[[rules]]
id = "sendinblue-api-token"
description = "Sendinblue API token"
regex = '''xkeysib-[a-f0-9]{64}\-(?i)[a-z0-9]{16}'''
[[rules]]
id = "shippo-api-token"
description = "Shippo API token"
regex = '''shippo_(live|test)_[a-f0-9]{40}'''
[[rules]]
id = "linedin-client-secret"
description = "Linkedin Client secret"
regex = '''(?i)(linkedin[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z]{16})['\"]'''
secretGroup = 3
[[rules]]
id = "linedin-client-id"
description = "Linkedin Client ID"
regex = '''(?i)(linkedin[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{14})['\"]'''
secretGroup = 3
[[rules]]
id = "twitch-api-token"
description = "Twitch API token"
regex = '''(?i)(twitch[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{30})['\"]'''
secretGroup = 3
[[rules]]
id = "typeform-api-token"
description = "Typeform API token"
regex = '''(?i)(typeform[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}(tfp_[a-z0-9\-_\.=]{59})'''
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
[allowlist]
description = "global allow lists"
regexes = ['''219-09-9999''', '''078-05-1120''', '''(9[0-9]{2}|666)-\d{2}-\d{4}''']
paths = ['''(.*?)(jpg|gif|doc|pdf|bin|svg|socket)$''']
paths = [
'''gitleaks.toml''',
'''(.*?)(jpg|gif|doc|pdf|bin|svg|socket)$'''
]
+10 -16
View File
@@ -6,23 +6,17 @@ import (
)
type Rule struct {
Description string
RuleID string
Entropy float64
EntropyReGroup int
Regex *regexp.Regexp
Path *regexp.Regexp
Tags []string
Allowlist Allowlist
Description string
RuleID string
Entropy float64
SecretGroup int
Regex *regexp.Regexp
Path *regexp.Regexp
Tags []string
Allowlist Allowlist
}
func (r *Rule) IncludeEntropy(secret string) (bool, float64) {
groups := r.Regex.FindStringSubmatch(secret)
if len(groups)-1 > r.EntropyReGroup || len(groups) == 0 {
// Config validation should prevent this
return false, 0.0
}
// 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
@@ -30,12 +24,12 @@ func (r *Rule) IncludeEntropy(secret string) (bool, float64) {
// 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(groups[r.EntropyReGroup]) {
if !containsDigit(secret) {
return false, 0.0
}
}
// group = 0 will check the entropy of the whole regex match
e := shannonEntropy(groups[r.EntropyReGroup])
e := shannonEntropy(secret)
if e > r.Entropy {
return true, e
}
+49 -5
View File
@@ -6,6 +6,8 @@ import (
"regexp"
"strings"
"github.com/rs/zerolog/log"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/report"
)
@@ -42,7 +44,7 @@ func DetectFindings(cfg config.Config, b []byte, filePath string, commit string)
Description: r.Description,
File: filePath,
RuleID: r.RuleID,
Context: fmt.Sprintf("file detected: %s", filePath),
Match: fmt.Sprintf("file detected: %s", filePath),
Tags: r.Tags,
}
findings = append(findings, f)
@@ -59,6 +61,7 @@ func DetectFindings(cfg config.Config, b []byte, filePath string, commit string)
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,
@@ -67,8 +70,8 @@ func DetectFindings(cfg config.Config, b []byte, filePath string, commit string)
EndLine: location.endLine,
StartColumn: location.startColumn,
EndColumn: location.endColumn,
Secret: strings.Trim(string(b[m[0]:m[1]]), "\n"),
Context: limit(strings.Trim(string(b[location.startLineIndex:location.endLineIndex]), "\n")),
Secret: secret,
Match: secret,
Tags: r.Tags,
}
@@ -76,8 +79,20 @@ func DetectFindings(cfg config.Config, b []byte, filePath string, commit string)
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(strings.Trim(string(b[m[0]:m[1]]), "\n"))
include, entropy := r.IncludeEntropy(secret)
if include {
f.Entropy = float32(entropy)
findings = append(findings, f)
@@ -88,7 +103,7 @@ func DetectFindings(cfg config.Config, b []byte, filePath string, commit string)
}
}
return findings
return dedupe(findings)
}
func limit(s string) string {
@@ -103,3 +118,32 @@ func printFinding(f report.Finding) {
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
}
}
}
if include {
retFindings = append(retFindings, f)
}
}
return retFindings
}
+7 -8
View File
@@ -30,6 +30,7 @@ func TestDetectFindings(t *testing.T) {
{
Description: "AWS Access Key",
Secret: "AKIALALEMEL33243OLIA",
Match: "AKIALALEMEL33243OLIA",
File: "tmp.go",
RuleID: "aws-access-key",
Tags: []string{"key", "AWS"},
@@ -62,7 +63,8 @@ func TestDetectFindings(t *testing.T) {
expectedFindings: []report.Finding{
{
Description: "Discord API key",
Secret: "Discord_Public_Key = \"e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5\"",
Match: "Discord_Public_Key = \"e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5\"",
Secret: "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5",
File: "tmp.go",
RuleID: "discord-api-key",
Tags: []string{},
@@ -83,7 +85,8 @@ func TestDetectFindings(t *testing.T) {
expectedFindings: []report.Finding{
{
Description: "Generic API Key",
Secret: "Key = \"e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5\"",
Match: "Key = \"e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5\"",
Secret: "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5",
File: "tmp.py",
RuleID: "generic-api-key",
Tags: []string{},
@@ -98,7 +101,7 @@ func TestDetectFindings(t *testing.T) {
expectedFindings: []report.Finding{
{
Description: "Python Files",
Context: "file detected: tmp.py",
Match: "file detected: tmp.py",
File: "tmp.py",
RuleID: "python-files-only",
Tags: []string{},
@@ -110,7 +113,7 @@ func TestDetectFindings(t *testing.T) {
bytes: []byte(`const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`),
filePath: "tmp.go",
expectedFindings: []report.Finding{},
wantError: fmt.Errorf("Discord API key invalid regex entropy group 5, max regex entropy group 3"),
wantError: fmt.Errorf("Discord API key invalid regex secret group 5, max regex secret group 3"),
},
{
cfgName: "simple",
@@ -148,10 +151,6 @@ func TestDetectFindings(t *testing.T) {
}
findings := DetectFindings(cfg, tt.bytes, tt.filePath, tt.commit)
for _, f := range findings {
f.Context = "" // remove lines cause copying and pasting them has some wack formatting
f.Date = ""
}
assert.ElementsMatch(t, tt.expectedFindings, findings)
}
}
+7 -4
View File
@@ -15,9 +15,9 @@ import (
// 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) {
func FromFiles(source string, cfg config.Config, outputOptions Options) ([]report.Finding, error) {
var (
findings []*report.Finding
findings []report.Finding
mu sync.Mutex
)
g, _ := errgroup.WithContext(context.Background())
@@ -51,7 +51,10 @@ func FromFiles(source string, cfg config.Config, outputOptions Options) ([]*repo
}
fis := DetectFindings(cfg, b, p, "")
for _, fi := range fis {
fi.File = p
// need to add 1 since line counting starts at 1
fi.StartLine++
fi.EndLine++
if outputOptions.Redact {
fi.Redact()
}
@@ -59,7 +62,7 @@ func FromFiles(source string, cfg config.Config, outputOptions Options) ([]*repo
printFinding(fi)
}
mu.Lock()
findings = append(findings, &fi)
findings = append(findings, fi)
mu.Unlock()
}
return nil
+9 -9
View File
@@ -17,19 +17,19 @@ func TestFromFiles(t *testing.T) {
cfgName string
opts Options
source string
expectedFindings []*report.Finding
expectedFindings []report.Finding
}{
{
source: filepath.Join(repoBasePath, "nogit"),
cfgName: "simple",
expectedFindings: []*report.Finding{
expectedFindings: []report.Finding{
{
Description: "AWS Access Key",
StartLine: 19,
EndLine: 19,
StartLine: 20,
EndLine: 20,
StartColumn: 16,
EndColumn: 35,
Context: "\tawsToken := \"AKIALALEMEL33243OLIA\"",
Match: "AKIALALEMEL33243OLIA",
Secret: "AKIALALEMEL33243OLIA",
File: "../testdata/repos/nogit/main.go",
RuleID: "aws-access-key",
@@ -40,14 +40,14 @@ func TestFromFiles(t *testing.T) {
{
source: filepath.Join(repoBasePath, "nogit", "main.go"),
cfgName: "simple",
expectedFindings: []*report.Finding{
expectedFindings: []report.Finding{
{
Description: "AWS Access Key",
StartLine: 19,
EndLine: 19,
StartLine: 20,
EndLine: 20,
StartColumn: 16,
EndColumn: 35,
Context: "\tawsToken := \"AKIALALEMEL33243OLIA\"",
Match: "AKIALALEMEL33243OLIA",
Secret: "AKIALALEMEL33243OLIA",
File: "../testdata/repos/nogit/main.go",
RuleID: "aws-access-key",
+6 -5
View File
@@ -3,6 +3,7 @@ package detect
import (
"strings"
"sync"
"time"
"github.com/gitleaks/go-gitdiff/gitdiff"
"github.com/rs/zerolog/log"
@@ -14,8 +15,8 @@ import (
// 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
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)
@@ -59,7 +60,7 @@ func FromGit(files <-chan *gitdiff.File, cfg config.Config, outputOptions Option
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.Context, "file detected") {
if !strings.HasPrefix(fi.Match, "file detected") {
fi.StartLine += int(tf.NewPosition)
fi.EndLine += int(tf.NewPosition)
}
@@ -70,7 +71,7 @@ func FromGit(files <-chan *gitdiff.File, cfg config.Config, outputOptions Option
fi.Author = f.PatchHeader.Author.Name
fi.Email = f.PatchHeader.Author.Email
}
fi.Date = f.PatchHeader.AuthorDate.String()
fi.Date = f.PatchHeader.AuthorDate.UTC().Format(time.RFC3339)
}
if outputOptions.Redact {
@@ -81,7 +82,7 @@ func FromGit(files <-chan *gitdiff.File, cfg config.Config, outputOptions Option
printFinding(fi)
}
mu.Lock()
findings = append(findings, &fi)
findings = append(findings, fi)
mu.Unlock()
}
+29 -27
View File
@@ -26,13 +26,13 @@ func TestFromGit(t *testing.T) {
source string
logOpts string
expected string
expectedFindings []*report.Finding
expectedFindings []report.Finding
}{
{
source: filepath.Join(repoBasePath, "small"),
expected: filepath.Join(expectPath, "git", "small.txt"),
cfgName: "simple",
expectedFindings: []*report.Finding{
expectedFindings: []report.Finding{
{
Description: "AWS Access Key",
StartLine: 20,
@@ -40,14 +40,15 @@ func TestFromGit(t *testing.T) {
StartColumn: 19,
EndColumn: 38,
Secret: "AKIALALEMEL33243OLIA",
Match: "AKIALALEMEL33243OLIA",
File: "main.go",
// Line: "\tawsToken := \"AKIALALEMEL33243OLIA\"",
Commit: "1b6da43b82b22e4eaa10bcf8ee591e91abbfc587",
Author: "Zachary Rice",
Email: "zricer@protonmail.com",
Message: "Accidentally add a secret",
RuleID: "aws-access-key",
Tags: []string{"key", "AWS"},
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",
@@ -56,14 +57,15 @@ func TestFromGit(t *testing.T) {
StartColumn: 17,
EndColumn: 36,
Secret: "AKIALALEMEL33243OLIA",
Match: "AKIALALEMEL33243OLIA",
File: "foo/foo.go",
// Line: "\taws_token := \"AKIALALEMEL33243OLIA\"",
Commit: "491504d5a31946ce75e22554cc34203d8e5ff3ca",
Author: "Zach Rice",
Email: "zricer@protonmail.com",
Message: "adding foo package with secret",
RuleID: "aws-access-key",
Tags: []string{"key", "AWS"},
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"},
},
},
},
@@ -72,7 +74,7 @@ func TestFromGit(t *testing.T) {
expected: filepath.Join(expectPath, "git", "small-branch-foo.txt"),
logOpts: "--all foo...",
cfgName: "simple",
expectedFindings: []*report.Finding{
expectedFindings: []report.Finding{
{
Description: "AWS Access Key",
StartLine: 9,
@@ -80,14 +82,15 @@ func TestFromGit(t *testing.T) {
StartColumn: 17,
EndColumn: 36,
Secret: "AKIALALEMEL33243OLIA",
// Line: "\taws_token := \"AKIALALEMEL33243OLIA\"",
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"},
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"},
},
},
},
@@ -119,8 +122,7 @@ func TestFromGit(t *testing.T) {
findings := FromGit(files, cfg, tt.opts)
for _, f := range findings {
f.Context = "" // remove lines cause copying and pasting them has some wack formatting
f.Date = ""
f.Match = "" // remove lines cause copying and pasting them has some wack formatting
}
assert.ElementsMatch(t, tt.expectedFindings, findings)
}
+3
View File
@@ -7,6 +7,7 @@ import (
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/gitleaks/go-gitdiff/gitdiff"
"github.com/rs/zerolog/log"
@@ -39,6 +40,7 @@ func GitLog(source string, logOpts string) (<-chan *gitdiff.File, error) {
}
go listenForStdErr(stderr)
time.Sleep(50 * time.Millisecond) // HACK: to avoid https://github.com/zricethezav/gitleaks/issues/722
return gitdiff.Parse(stdout)
}
@@ -66,6 +68,7 @@ func GitDiff(source string, staged bool) (<-chan *gitdiff.File, error) {
}
go listenForStdErr(stderr)
time.Sleep(50 * time.Millisecond) // HACK: to avoid https://github.com/zricethezav/gitleaks/issues/722
return gitdiff.Parse(stdout)
}
+1 -1
View File
@@ -3,7 +3,7 @@ module github.com/zricethezav/gitleaks/v8
go 1.16
require (
github.com/gitleaks/go-gitdiff v0.7.2
github.com/gitleaks/go-gitdiff v0.7.3
github.com/rs/zerolog v1.25.0
github.com/spf13/cobra v1.2.1
github.com/spf13/viper v1.8.1
+2 -2
View File
@@ -70,8 +70,8 @@ github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5Kwzbycv
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.2 h1:V9a22yhh7BTrJZZCM77EaMbmCSDNEcHGNwqB+lC/6v0=
github.com/gitleaks/go-gitdiff v0.7.2/go.mod h1:pKz0X4YzCKZs30BL+weqBIG7mx0jl4tF1uXV9ZyNvrA=
github.com/gitleaks/go-gitdiff v0.7.3 h1:VA9MyNEI0/NGukCztbfyJzf1MmFTVHBByBGIDW0F+a0=
github.com/gitleaks/go-gitdiff v0.7.3/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=
+3 -3
View File
@@ -7,7 +7,7 @@ import (
)
// writeCsv writes the list of findings to a writeCloser.
func writeCsv(f []*Finding, w io.WriteCloser) error {
func writeCsv(f []Finding, w io.WriteCloser) error {
if len(f) == 0 {
return nil
}
@@ -17,7 +17,7 @@ func writeCsv(f []*Finding, w io.WriteCloser) error {
"Commit",
"File",
"Secret",
"Context",
"Match",
"StartLine",
"EndLine",
"StartColumn",
@@ -35,7 +35,7 @@ func writeCsv(f []*Finding, w io.WriteCloser) error {
f.Commit,
f.File,
f.Secret,
f.Context,
f.Match,
strconv.Itoa(f.StartLine),
strconv.Itoa(f.EndLine),
strconv.Itoa(f.StartColumn),
+4 -4
View File
@@ -9,7 +9,7 @@ import (
func TestWriteCSV(t *testing.T) {
tests := []struct {
findings []*Finding
findings []Finding
testReportName string
expected string
wantEmpty bool
@@ -17,10 +17,10 @@ func TestWriteCSV(t *testing.T) {
{
testReportName: "simple",
expected: filepath.Join(expectPath, "report", "csv_simple.csv"),
findings: []*Finding{
findings: []Finding{
{
RuleID: "test-rule",
Context: "line containing secret",
Match: "line containing secret",
Secret: "a secret",
StartLine: 1,
EndLine: 2,
@@ -39,7 +39,7 @@ func TestWriteCSV(t *testing.T) {
wantEmpty: true,
testReportName: "empty",
expected: filepath.Join(expectPath, "report", "this_should_not_exist.csv"),
findings: []*Finding{}},
findings: []Finding{}},
}
for _, test := range tests {
+13 -3
View File
@@ -1,6 +1,9 @@
package report
import "strings"
import (
"strconv"
"strings"
)
// Finding contains information about strings that
// have been captured by a tree-sitter query.
@@ -11,7 +14,7 @@ type Finding struct {
StartColumn int
EndColumn int
Context string
Match string
// Secret contains the full content of what is matched in
// the tree-sitter query.
@@ -37,6 +40,13 @@ type Finding struct {
// Redact removes sensitive information from a finding.
func (f *Finding) Redact() {
f.Context = strings.Replace(f.Context, f.Secret, "REDACTED", -1)
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)
}
+2 -2
View File
@@ -11,8 +11,8 @@ func TestRedact(t *testing.T) {
redact: true,
findings: []Finding{
{
Secret: "line containing secret",
Context: "secret",
Secret: "line containing secret",
Match: "secret",
},
}},
}
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"io"
)
func writeJson(findings []*Finding, w io.WriteCloser) error {
func writeJson(findings []Finding, w io.WriteCloser) error {
if len(findings) == 0 {
return nil
}
+4 -4
View File
@@ -9,7 +9,7 @@ import (
func TestWriteJSON(t *testing.T) {
tests := []struct {
findings []*Finding
findings []Finding
testReportName string
expected string
wantEmpty bool
@@ -17,12 +17,12 @@ func TestWriteJSON(t *testing.T) {
{
testReportName: "simple",
expected: filepath.Join(expectPath, "report", "json_simple.json"),
findings: []*Finding{
findings: []Finding{
{
Description: "",
RuleID: "test-rule",
Context: "line containing secret",
Match: "line containing secret",
Secret: "a secret",
StartLine: 1,
EndLine: 2,
@@ -42,7 +42,7 @@ func TestWriteJSON(t *testing.T) {
wantEmpty: true,
testReportName: "empty",
expected: filepath.Join(expectPath, "report", "this_should_not_exist.json"),
findings: []*Finding{}},
findings: []Finding{}},
}
for _, test := range tests {
+1 -1
View File
@@ -13,7 +13,7 @@ const (
CWE_DESCRIPTION = "Use of Hard-coded Credentials"
)
func Write(findings []*Finding, cfg config.Config, ext string, reportPath string) error {
func Write(findings []Finding, cfg config.Config, ext string, reportPath string) error {
if len(findings) == 0 {
return nil
}
+7 -7
View File
@@ -16,13 +16,13 @@ const (
func TestReport(t *testing.T) {
tests := []struct {
findings []*Finding
findings []Finding
ext string
wantEmpty bool
}{
{
ext: "json",
findings: []*Finding{
findings: []Finding{
{
RuleID: "test-rule",
},
@@ -30,7 +30,7 @@ func TestReport(t *testing.T) {
},
{
ext: ".json",
findings: []*Finding{
findings: []Finding{
{
RuleID: "test-rule",
},
@@ -38,7 +38,7 @@ func TestReport(t *testing.T) {
},
{
ext: ".jsonj",
findings: []*Finding{
findings: []Finding{
{
RuleID: "test-rule",
},
@@ -47,7 +47,7 @@ func TestReport(t *testing.T) {
},
{
ext: ".csv",
findings: []*Finding{
findings: []Finding{
{
RuleID: "test-rule",
},
@@ -55,7 +55,7 @@ func TestReport(t *testing.T) {
},
{
ext: "csv",
findings: []*Finding{
findings: []Finding{
{
RuleID: "test-rule",
},
@@ -63,7 +63,7 @@ func TestReport(t *testing.T) {
},
{
ext: "CSV",
findings: []*Finding{
findings: []Finding{
{
RuleID: "test-rule",
},
+5 -5
View File
@@ -8,7 +8,7 @@ import (
"github.com/zricethezav/gitleaks/v8/config"
)
func writeSarif(cfg config.Config, findings []*Finding, w io.WriteCloser) error {
func writeSarif(cfg config.Config, findings []Finding, w io.WriteCloser) error {
sarif := Sarif{
Schema: "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0-rtm.5.json",
Version: "2.1.0",
@@ -20,7 +20,7 @@ func writeSarif(cfg config.Config, findings []*Finding, w io.WriteCloser) error
return encoder.Encode(sarif)
}
func getRuns(cfg config.Config, findings []*Finding) []Runs {
func getRuns(cfg config.Config, findings []Finding) []Runs {
return []Runs{
{
Tool: getTool(cfg),
@@ -54,7 +54,7 @@ func getRules(cfg config.Config) []Rules {
return rules
}
func messageText(f *Finding) string {
func messageText(f Finding) string {
if f.Commit == "" {
return fmt.Sprintf("%s has detected secret for file %s.", f.RuleID, f.File)
}
@@ -63,7 +63,7 @@ func messageText(f *Finding) string {
}
func getResults(findings []*Finding) []Results {
func getResults(findings []Finding) []Results {
var results []Results
for _, f := range findings {
r := Results{
@@ -87,7 +87,7 @@ func getResults(findings []*Finding) []Results {
return results
}
func getLocation(f *Finding) []Locations {
func getLocation(f Finding) []Locations {
return []Locations{
{
PhysicalLocation: PhysicalLocation{
+3 -3
View File
@@ -14,7 +14,7 @@ const configPath = "../testdata/config/"
func TestWriteSarif(t *testing.T) {
tests := []struct {
findings []*Finding
findings []Finding
testReportName string
expected string
wantEmpty bool
@@ -24,12 +24,12 @@ func TestWriteSarif(t *testing.T) {
cfgName: "simple",
testReportName: "simple",
expected: filepath.Join(expectPath, "report", "sarif_simple.sarif"),
findings: []*Finding{
findings: []Finding{
{
Description: "",
RuleID: "test-rule",
Context: "line containing secret",
Match: "line containing secret",
Secret: "a secret",
StartLine: 1,
EndLine: 2,
+1 -1
View File
@@ -4,5 +4,5 @@ title = "gitleaks config"
id = "discord-api-key"
description = "Discord API key"
regex = '''(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-h0-9]{64})['\"]'''
entropyGroup = 5
secretGroup = 5
entropy = 3.5
+1 -1
View File
@@ -4,5 +4,5 @@ title = "gitleaks config"
id = "discord-api-key"
description = "Discord API key"
regex = '''(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-h0-9]{64})['\"]'''
entropyGroup = 3
secretGroup = 3
entropy = 3.5
+1 -1
View File
@@ -5,4 +5,4 @@ description = "Generic API Key"
id = "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
entropyGroup = 4
secretGroup = 4
+1 -1
View File
@@ -6,4 +6,4 @@ id = "generic-api-key"
regex = '''(?i)((key|api|token|secret|password)[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([0-9a-zA-Z\-_=]{8,64})['\"]'''
path = '''.py'''
entropy = 3.7
entropyGroup = 4
secretGroup = 4
+1 -1
View File
@@ -1,2 +1,2 @@
RuleID,Commit,File,Secret,Context,StartLine,EndLine,StartColumn,EndColumn,Author,Message,Date,Email
RuleID,Commit,File,Secret,Match,StartLine,EndLine,StartColumn,EndColumn,Author,Message,Date,Email
test-rule,0000000000000000,auth.py,a secret,line containing secret,1,2,1,2,John Doe,opps,10-19-2003,johndoe@gmail.com
1 RuleID Commit File Secret Context Match StartLine EndLine StartColumn EndColumn Author Message Date Email
2 test-rule 0000000000000000 auth.py a secret line containing secret line containing secret 1 2 1 2 John Doe opps 10-19-2003 johndoe@gmail.com
+1 -1
View File
@@ -5,7 +5,7 @@
"EndLine": 2,
"StartColumn": 1,
"EndColumn": 2,
"Context": "line containing secret",
"Match": "line containing secret",
"Secret": "a secret",
"File": "auth.py",
"Commit": "0000000000000000",
Binary file not shown.