Compare commits

...
32 Commits
Author SHA1 Message Date
Zachary Rice 36779df3bb stricter ionic regex for less fps (#757) 2021-12-17 10:13:44 -06:00
Zachary Rice 3d3d801729 fixing eof location bug (#756) 2021-12-17 09:49:12 -06:00
Zachary Rice 0f2ffee6f9 Adding Tines sponsorship to readme 2021-12-16 10:39:45 -06:00
Andrzej Amghar f4d37a2c0d fix regexp for aws_key and slack_webhook (#754) 2021-12-16 07:48:18 -06:00
Zachary Rice be5596df1d Update README.md 2021-12-12 13:38:43 -06:00
Zachary Rice e97f26bb5f better asciinema 2021-12-12 13:36:57 -06:00
Zachary Rice ae13c96df8 Update README.md 2021-12-12 13:19:58 -06:00
Zachary Rice d15dfdc387 Update README.md 2021-12-12 13:19:06 -06:00
Zach Rice 631d8dcf03 bump go-gitdiff 2021-12-12 12:23:59 -06:00
Zachary Rice 192b96289f do not fail on git rename warning (#750) 2021-12-12 11:43:03 -06:00
Zachary Rice b8141713e8 add pre-commit instructions (#749) 2021-12-10 18:08:31 -06:00
Zachary Rice 3fedf6f8e7 remove writing default config, introduce GITLEAKS_CONFIG (#746)
* remove writing default config, introduce GITLEAKS_CONFIG

* setting report format default to json, update readme
2021-12-09 09:21:17 -06:00
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
Zachary Rice 80d29764a0 add global regex check (#717) 2021-11-25 11:17:03 -06:00
Zachary Rice f498b1d308 Commit debug log (#716)
* adding debug log for number of commits scanned

* change debug text

* readd commitsha
2021-11-25 10:46:47 -06:00
Joost Voskuil 8eabfd614e Update sarif.go (#713)
* Update sarif.go

Provide correct version information for Sarif Reports

* Update test

Set version to correct Sarif version
2021-11-25 10:46:31 -06:00
Zachary Rice 4acd7a3c8d adding logic to ignore gitleaks config during scans (#710) 2021-11-24 20:27:19 -06:00
39 changed files with 594 additions and 255 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
+107 -25
View File
@@ -22,7 +22,9 @@
</p>
</p>
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.
Gitleaks is a SAST tool for **detecting** and **preventing** 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.
[![asciicast](https://asciinema.org/a/455683.svg)](https://asciinema.org/a/455683)
## 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.
@@ -57,6 +59,28 @@ cd gitleaks
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
```
3. Install with `pre-commit install`
4. Now you're all set!
```
➜ git commit -m "this commit contains a secret"
Detect hardcoded secrets.................................................Failed
```
Note: to disable the gitleaks pre-commit hook you can prepend `SKIP=gitleaks` to the commit command
and it will skip running gitleaks
```
➜ SKIP=gitleaks git commit -m "skip gitleaks check"
Detect hardcoded secrets................................................Skipped
```
## Usage
```
@@ -74,9 +98,9 @@ Flags:
-c, --config string 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
then .gitleaks.toml will be written to (--source/-s)/.gitleaks.toml for future use
2. env var GITLEAKS_CONFIG
3. (--source/-s)/.gitleaks.toml
If none of the three options are used, then gitleaks will use the default config
--exit-code string exit code when leaks have been encountered (default: 1)
-h, --help help for gitleaks
-l, --log-level string log level (debug, info, warn, error, fatal) (default "info")
@@ -92,22 +116,22 @@ 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 comand 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)).
[`git log -p` generates patches](https://git-scm.com/docs/git-log#_generating_patch_text_with_p) which gitleaks will use to detect secrets.
You can configure what commits `git log` will range over by using the `--log-opts` flag. `--log-opts` accepts any option for `git log -p`.
For example, if you wanted to run gitleaks on a range of commits you could use the following command: `gitleaks --source . --log-opts="--all commitA..commitB"`.
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)).
[`git log -p` generates patches](https://git-scm.com/docs/git-log#_generating_patch_text_with_p) which gitleaks will use to detect secrets.
You can configure what commits `git log` will range over by using the `--log-opts` flag. `--log-opts` accepts any option for `git log -p`.
For example, if you wanted to run gitleaks on a range of commits you could use the following command: `gitleaks --source . --log-opts="--all commitA..commitB"`.
See the `git log` [documentation](https://git-scm.com/docs/git-log) for more information.
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
[here](https://github.com/zricethezav/gitleaks/blob/7240e16769b92d2a1b137c17d6bf9d55a8562899/git/git.go#L48-L49)). You can set the
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 `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 +147,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",
@@ -164,33 +188,34 @@ diff --git a/checks_test.go b/checks_test.go
```
## Pre-Commit hook
You can run Gitleaks as a pre-commit hook by copying the example `pre-commit.py` script into
You can run Gitleaks as a pre-commit hook by copying the example `pre-commit.py` script into
your `.git/hooks/` directory.
## Configuration
Gitleaks offers a configuration format you can follow to write your own secret detection rules:
```toml
# Title for the gitleaks configuration file.
# Title for the gitleaks configuration file.
title = "Gitleaks title"
# An array of tables that contain information that define instructions
# on how to detect secrets
# 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 = "awsome 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'''
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 check shannon entropy of a specific group in a regex match.
entropyGroup = 3
# Float representing the minimum shannon entropy a regex group must have to be considered a secret.
# 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
# with known/rotated secrets
@@ -201,7 +226,7 @@ paths = ['''one-file-path-regex''']
regexes = ['''one-regex-within-the-already-matched-regex''']
# This is a global allowlist which has a higher order of precendence than rule-specific allowlists.
# If a commit listed in the `commits` field below is encountered then that commit will be skipped and no
# 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"
@@ -209,7 +234,63 @@ 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.
## 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)
## Exit Codes
@@ -217,4 +298,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
```
+6 -1
View File
@@ -2,6 +2,7 @@ package cmd
import (
"os"
"path/filepath"
"time"
"github.com/rs/zerolog/log"
@@ -30,7 +31,7 @@ func runDetect(cmd *cobra.Command, args []string) {
initConfig()
var (
vc config.ViperConfig
findings []*report.Finding
findings []report.Finding
err error
)
@@ -40,12 +41,16 @@ func runDetect(cmd *cobra.Command, args []string) {
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 := time.Now()
if noGit {
+5
View File
@@ -2,6 +2,7 @@ package cmd
import (
"os"
"path/filepath"
"time"
"github.com/rs/zerolog/log"
@@ -35,11 +36,15 @@ func runProtect(cmd *cobra.Command, args []string) {
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)
+36 -18
View File
@@ -26,9 +26,9 @@ const banner = `
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
then .gitleaks.toml will be written to (--source/-s)/.gitleaks.toml for future use`
2. env var GITLEAKS_CONFIG
3. (--source/-s)/.gitleaks.toml
If none of the three options are used, then gitleaks will use the default config`
var rootCmd = &cobra.Command{
Use: "gitleaks",
@@ -38,10 +38,10 @@ var rootCmd = &cobra.Command{
func init() {
cobra.OnInitialize(initLog)
rootCmd.PersistentFlags().StringP("config", "c", "", configDescription)
rootCmd.PersistentFlags().Int("exit-code", 1, "exit code when leaks have been encountered (default: 1)")
rootCmd.PersistentFlags().Int("exit-code", 1, "exit code when leaks have been encountered")
rootCmd.PersistentFlags().StringP("source", "s", ".", "path to source (default: $PWD)")
rootCmd.PersistentFlags().StringP("report-path", "r", "", "report file")
rootCmd.PersistentFlags().StringP("report-format", "f", "", "output format (json, csv, sarif)")
rootCmd.PersistentFlags().StringP("report-format", "f", "json", "output format (json, csv, sarif)")
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")
@@ -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,26 +74,40 @@ 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)
log.Debug().Msgf("Using gitleaks config %s", cfgPath)
log.Debug().Msgf("Using gitleaks config %s from `--config`", cfgPath)
} else if os.Getenv("GITLEAKS_CONFIG") != "" {
envPath := os.Getenv("GITLEAKS_CONFIG")
viper.SetConfigFile(envPath)
log.Debug().Msgf("Using gitleaks config from GITLEAKS_CONFIG env var: %s", envPath)
} 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 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))
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"))
viper.SetConfigType("toml")
viper.ReadConfig(strings.NewReader(config.DefaultConfig))
return
}
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))
return
} else {
log.Debug().Msgf("Using existing gitleaks config %s", filepath.Join(source, ".gitleaks.toml"))
log.Debug().Msgf("Using existing gitleaks config %s from `(--source)/.gitleaks.toml`", filepath.Join(source, ".gitleaks.toml"))
}
viper.AddConfigPath(source)
@@ -107,6 +121,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())
}
}
+17 -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
@@ -38,6 +38,7 @@ type ViperConfig struct {
// Config is a configuration struct that contains rules and an allowlist if present.
type Config struct {
Path string
Description string
Rules []*Rule
Allowlist Allowlist
@@ -72,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,
},
+132 -31
View File
@@ -2,33 +2,33 @@ title = "gitleaks config"
# 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.
# 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),
#
# 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
#
# Beginning string
# quotation
# │ End string quotation
# │ │
# ▼ ▼
# (?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9=_\-]{32})['\"]
#
# ▲ ▲ ▲
# │ │ │
# │ │ │
# identifier assignment symbol
# Secret
#
[[rules]]
id = "gitlab-pat"
description = "GitLab Personal Access Token"
@@ -37,7 +37,7 @@ regex = '''glpat-[0-9a-zA-Z\-]{20}'''
[[rules]]
id = "aws-access-token"
description = "AWS"
regex = '''AKIA[0-9A-Z]{16}'''
regex = '''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
# Cryptographic keys
[[rules]]
@@ -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,11 +135,12 @@ 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"
description = "Slack Webhook"
regex = '''https://hooks.slack.com/services/T[a-zA-Z0-9_]{8}/B[a-zA-Z0-9_]{8}/[a-zA-Z0-9_]{24}'''
regex = '''https://hooks.slack.com/services/T[a-zA-Z0-9_]{8}/B[a-zA-Z0-9_]{8,12}/[a-zA-Z0-9_]{24}'''
[[rules]]
id = "twilio-api-key"
@@ -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}'''
regex = '''(?i)(ionic[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"](ion_[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}''']
files = ['''(.*?)(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
}
+52 -8
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"
)
@@ -19,8 +21,8 @@ func DetectFindings(cfg config.Config, b []byte, filePath string, commit string)
var findings []report.Finding
linePairs := regexp.MustCompile("\n").FindAllIndex(b, -1)
// check if we should skip file based on the global allowlist
if cfg.Allowlist.PathAllowed(filePath) {
// 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 {
return findings
}
@@ -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,17 +70,29 @@ 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,
}
if r.Allowlist.RegexAllowed(f.Secret) {
if r.Allowlist.RegexAllowed(f.Secret) || cfg.Allowlist.RegexAllowed(f.Secret) {
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
}
+33 -8
View File
@@ -2,6 +2,7 @@ package detect
import (
"fmt"
"path/filepath"
"testing"
"github.com/spf13/viper"
@@ -29,9 +30,14 @@ func TestDetectFindings(t *testing.T) {
{
Description: "AWS Access Key",
Secret: "AKIALALEMEL33243OLIA",
Match: "AKIALALEMEL33243OLIA",
File: "tmp.go",
RuleID: "aws-access-key",
Tags: []string{"key", "AWS"},
StartLine: 1,
EndLine: 1,
StartColumn: 15,
EndColumn: 34,
},
},
},
@@ -61,11 +67,16 @@ 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{},
Entropy: 3.7906237,
StartLine: 1,
EndLine: 1,
StartColumn: 7,
EndColumn: 93,
},
},
},
@@ -82,11 +93,16 @@ 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{},
Entropy: 3.7906237,
StartLine: 1,
EndLine: 1,
StartColumn: 22,
EndColumn: 93,
},
},
},
@@ -97,7 +113,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{},
@@ -109,7 +125,19 @@ 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",
bytes: []byte(`awsToken := \"AKIALALEMEL33243OLIA\"`),
filePath: filepath.Join(configPath, "simple.toml"),
expectedFindings: []report.Finding{},
},
{
cfgName: "allow_global_aws_re",
bytes: []byte(`awsToken := \"AKIALALEMEL33243OLIA\"`),
filePath: "tmp.go",
expectedFindings: []report.Finding{},
},
}
@@ -126,6 +154,7 @@ func TestDetectFindings(t *testing.T) {
var vc config.ViperConfig
viper.Unmarshal(&vc)
cfg, err := vc.Translate()
cfg.Path = filepath.Join(configPath, tt.cfgName+".toml")
if tt.wantError != nil {
if err == nil {
t.Errorf("expected error")
@@ -134,10 +163,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",
+13 -6
View File
@@ -3,8 +3,10 @@ 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"
@@ -13,11 +15,16 @@ 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)
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) {
@@ -35,7 +42,6 @@ func FromGit(files <-chan *gitdiff.File, cfg config.Config, outputOptions Option
// Check if commit is allowed
if f.PatchHeader != nil {
commitSHA = f.PatchHeader.SHA
if cfg.Allowlist.CommitAllowed(f.PatchHeader.SHA) {
return
}
@@ -54,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)
}
@@ -65,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 {
@@ -76,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()
}
@@ -85,5 +91,6 @@ func FromGit(files <-chan *gitdiff.File, cfg config.Config, outputOptions Option
}
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
}
+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)
}
+13 -1
View File
@@ -14,11 +14,15 @@ func getLocation(linePairs [][]int, start int, end int) Location {
var (
prevNewLine int
location Location
lineSet bool
_lineNum int
)
for lineNum, pair := range linePairs {
_lineNum = lineNum
newLineByteIndex := pair[0]
if prevNewLine <= start && start < newLineByteIndex {
lineSet = true
location.startLine = lineNum
location.endLine = lineNum
location.startColumn = (start - prevNewLine) + 1 // +1 because counting starts at 1
@@ -30,9 +34,17 @@ func getLocation(linePairs [][]int, start int, end int) Location {
location.endColumn = (end - prevNewLine)
location.endLineIndex = newLineByteIndex
}
prevNewLine = pair[0]
}
if !lineSet {
// if lines never get set then that means the secret is most likely
// on the last line of the diff output and the diff output does not have
// a newline
location.startColumn = (start - prevNewLine) + 1 // +1 because counting starts at 1
location.endColumn = (end - prevNewLine)
location.startLine = _lineNum + 1
location.endLine = _lineNum + 1
}
return location
}
+33 -6
View File
@@ -7,12 +7,14 @@ import (
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/gitleaks/go-gitdiff/gitdiff"
"github.com/rs/zerolog/log"
)
// GitLog returns a channel of gitdiff.File objects from the git log -p command for the given source.
// GitLog returns a channel of gitdiff.File objects from the
// git log -p command for the given source.
func GitLog(source string, logOpts string) (<-chan *gitdiff.File, error) {
sourceClean := filepath.Clean(source)
var cmd *exec.Cmd
@@ -21,7 +23,8 @@ func GitLog(source string, logOpts string) (<-chan *gitdiff.File, error) {
args = append(args, strings.Split(logOpts, " ")...)
cmd = exec.Command("git", args...)
} else {
cmd = exec.Command("git", "-C", sourceClean, "log", "-p", "-U0", "--full-history", "--all")
cmd = exec.Command("git", "-C", sourceClean, "log", "-p", "-U0",
"--full-history", "--all")
}
log.Debug().Msgf("executing: %s", cmd.String())
@@ -39,17 +42,21 @@ func GitLog(source string, logOpts string) (<-chan *gitdiff.File, error) {
}
go listenForStdErr(stderr)
// HACK: to avoid https://github.com/zricethezav/gitleaks/issues/722
time.Sleep(50 * time.Millisecond)
return gitdiff.Parse(stdout)
}
// GitDiff returns a channel of gitdiff.File objects from the git diff command for the given source.
// GitDiff returns a channel of gitdiff.File objects from
// the git diff command for the given source.
func GitDiff(source string, staged bool) (<-chan *gitdiff.File, error) {
sourceClean := filepath.Clean(source)
var cmd *exec.Cmd
cmd = exec.Command("git", "-C", sourceClean, "diff", "-U0", ".")
if staged {
cmd = exec.Command("git", "-C", sourceClean, "diff", "-U0", "--staged", ".")
cmd = exec.Command("git", "-C", sourceClean, "diff", "-U0",
"--staged", ".")
}
log.Debug().Msgf("executing: %s", cmd.String())
@@ -66,6 +73,8 @@ func GitDiff(source string, staged bool) (<-chan *gitdiff.File, error) {
}
go listenForStdErr(stderr)
// HACK: to avoid https://github.com/zricethezav/gitleaks/issues/722
time.Sleep(50 * time.Millisecond)
return gitdiff.Parse(stdout)
}
@@ -76,8 +85,26 @@ func listenForStdErr(stderr io.ReadCloser) {
scanner := bufio.NewScanner(stderr)
errEncountered := false
for scanner.Scan() {
log.Error().Msg(scanner.Text())
errEncountered = true
// if git throws the following error:
//
// exhaustive rename detection was skipped due to too many files.
// you may want to set your diff.renameLimit variable to at least
// (some large number) and retry the command.
//
// we skip exiting the program as git log -p/git diff will continue
// to send data to stdout and finish executing. This next bit of
// code prevents gitleaks from stopping mid scan if this error is
// encountered
if strings.Contains(scanner.Text(),
"exhaustive rename detection was skipped") ||
strings.Contains(scanner.Text(),
"you may want to set your diff.renameLimit") {
log.Warn().Msg(scanner.Text())
} else {
log.Error().Msg(scanner.Text())
errEncountered = true
}
}
if errEncountered {
os.Exit(1)
+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.4
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.4 h1:8vICc4moyRR2poklblThdQ0ckMet22mEvFJSxPsiDlk=
github.com/gitleaks/go-gitdiff v0.7.4/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",
},
+6 -6
View File
@@ -8,10 +8,10 @@ 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: version,
Version: "2.1.0",
Runs: getRuns(cfg, findings),
}
@@ -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,
+8
View File
@@ -0,0 +1,8 @@
[[rules]]
description = "AWS Access Key"
id = "aws-access-key"
regex = '''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
tags = ["key", "AWS"]
[allowlist]
regexes = ['''AKIALALEMEL33243OLIA''']
+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",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"$schema": "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0-rtm.5.json",
"version": "v8.0.0",
"version": "2.1.0",
"runs": [
{
"tool": {
Binary file not shown.