mirror of
https://github.com/gitleaks/gitleaks.git
synced 2026-11-29 04:34:46 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e5e63956e | ||
|
|
57f9bc83d1 | ||
|
|
6e72472b60 | ||
|
|
9326f35380 | ||
|
|
19555579c8 | ||
|
|
60dd607312 | ||
|
|
c3b799ec63 | ||
|
|
4b6f4d0de5 | ||
|
|
fbfb3f591e | ||
|
|
b91799aa18 | ||
|
|
db1b54bf9f | ||
|
|
e9529744f8 | ||
|
|
d1f642a9df | ||
|
|
9261f1c47f | ||
|
|
991223abab | ||
|
|
801d44a6e4 | ||
|
|
44d7d89e19 | ||
|
|
aae23acff3 | ||
|
|
705595aaf6 | ||
|
|
43ec22429f | ||
|
|
36779df3bb | ||
|
|
3d3d801729 | ||
|
|
0f2ffee6f9 | ||
|
|
f4d37a2c0d | ||
|
|
be5596df1d | ||
|
|
e97f26bb5f | ||
|
|
ae13c96df8 | ||
|
|
d15dfdc387 | ||
|
|
631d8dcf03 | ||
|
|
192b96289f | ||
|
|
b8141713e8 | ||
|
|
3fedf6f8e7 | ||
|
|
6f6ebd454f | ||
|
|
ce42947cae | ||
|
|
84e285e4ce | ||
|
|
928c6a6043 | ||
|
|
106897fdf0 | ||
|
|
98d5648f6e | ||
|
|
9358e84588 | ||
|
|
958c18f0b7 | ||
|
|
089639e9fb | ||
|
|
85afd767f7 | ||
|
|
38006fb93b | ||
|
|
9ae1def963 | ||
|
|
6517900e5a | ||
|
|
5e51da600b | ||
|
|
f0b8d26c99 | ||
|
|
1724591029 | ||
|
|
80d29764a0 | ||
|
|
f498b1d308 | ||
|
|
8eabfd614e | ||
|
|
4acd7a3c8d | ||
|
|
a37822dffd |
No files matched your search
@@ -11,8 +11,6 @@ on:
|
|||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
env:
|
|
||||||
GO111MODULE: on
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
|
|
||||||
@@ -26,8 +24,6 @@ jobs:
|
|||||||
|
|
||||||
test:
|
test:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
env:
|
|
||||||
GO111MODULE: on
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,12 @@ builds:
|
|||||||
- windows
|
- windows
|
||||||
goarch:
|
goarch:
|
||||||
- amd64
|
- amd64
|
||||||
|
- "386"
|
||||||
|
- arm
|
||||||
|
- arm64
|
||||||
|
goarm:
|
||||||
|
- "6"
|
||||||
|
- "7"
|
||||||
ldflags:
|
ldflags:
|
||||||
- -s -w -X=github.com/zricethezav/gitleaks/v8/cmd.Version={{.Version}}
|
- -s -w -X=github.com/zricethezav/gitleaks/v8/cmd.Version={{.Version}}
|
||||||
archives:
|
archives:
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
- id: gitleaks
|
- id: gitleaks
|
||||||
name: Detect hardcoded secrets
|
name: Detect hardcoded secrets
|
||||||
description: Detect hardcoded secrets using Gitleaks
|
description: Detect hardcoded secrets using Gitleaks
|
||||||
entry: gitleaks
|
entry: gitleaks protect --verbose --redact --staged
|
||||||
language: golang
|
language: golang
|
||||||
pass_filenames: false
|
pass_filenames: false
|
||||||
+1
-1
@@ -2,7 +2,7 @@ FROM golang:1.17 AS build
|
|||||||
WORKDIR /go/src/github.com/zricethezav/gitleaks
|
WORKDIR /go/src/github.com/zricethezav/gitleaks
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN VERSION=$(git describe --tags --abbrev=0) && \
|
RUN VERSION=$(git describe --tags --abbrev=0) && \
|
||||||
GO111MODULE=on CGO_ENABLED=0 go build -o bin/gitleaks -ldflags "-X="github.com/zricethezav/gitleaks/v8/cmd.Version=${VERSION}
|
CGO_ENABLED=0 go build -o bin/gitleaks -ldflags "-X="github.com/zricethezav/gitleaks/v8/cmd.Version=${VERSION}
|
||||||
|
|
||||||
FROM alpine:3.14.2
|
FROM alpine:3.14.2
|
||||||
RUN adduser -D gitleaks && \
|
RUN adduser -D gitleaks && \
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ LDFLAGS=-ldflags "-X=github.com/zricethezav/gitleaks/v8/cmd.Version=$(VERSION)"
|
|||||||
COVER=--cover --coverprofile=cover.out
|
COVER=--cover --coverprofile=cover.out
|
||||||
|
|
||||||
test-cover:
|
test-cover:
|
||||||
go test ./... --race $(COVER) $(PKG) -v
|
go test -v ./... --race $(COVER) $(PKG)
|
||||||
go tool cover -html=cover.out
|
go tool cover -html=cover.out
|
||||||
|
|
||||||
format:
|
format:
|
||||||
@@ -14,7 +14,7 @@ format:
|
|||||||
|
|
||||||
test: format
|
test: format
|
||||||
go vet ./...
|
go vet ./...
|
||||||
go test ./... --race $(PKG) -v
|
go test -v ./... --race $(PKG)
|
||||||
|
|
||||||
build: format
|
build: format
|
||||||
go vet ./...
|
go vet ./...
|
||||||
|
|||||||
@@ -22,7 +22,9 @@
|
|||||||
</p>
|
</p>
|
||||||
</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.
|
||||||
|
|
||||||
|
[](https://asciinema.org/a/455683)
|
||||||
|
|
||||||
## Getting Started
|
## 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.
|
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
|
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
|
## Usage
|
||||||
```
|
```
|
||||||
@@ -74,9 +98,9 @@ Flags:
|
|||||||
-c, --config string config file path
|
-c, --config string config file path
|
||||||
order of precedence:
|
order of precedence:
|
||||||
1. --config/-c
|
1. --config/-c
|
||||||
2. (--source/-s)/.gitleaks.toml
|
2. env var GITLEAKS_CONFIG
|
||||||
if --config/-c is not set and no .gitleaks.toml/gitleaks.toml present
|
3. (--source/-s)/.gitleaks.toml
|
||||||
then .gitleaks.toml will be written to (--source/-s)/.gitleaks.toml for future use
|
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)
|
--exit-code string exit code when leaks have been encountered (default: 1)
|
||||||
-h, --help help for gitleaks
|
-h, --help help for gitleaks
|
||||||
-l, --log-level string log level (debug, info, warn, error, fatal) (default "info")
|
-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
|
### Commands
|
||||||
There are two commands you will use to detect secrets; `detect` and `protect`.
|
There are two commands you will use to detect secrets; `detect` and `protect`.
|
||||||
#### Detect
|
#### Detect
|
||||||
The `detect` command is used to scan repos, directories, and files. This comand can be used on developer machines and in CI environments.
|
The `detect` command is used to scan repos, directories, and files. This command can be used on developer machines and in CI environments.
|
||||||
|
|
||||||
When running `detect` on a git repository, gitleaks will parse the output of a `git log -p` command (you can see how this executed
|
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)).
|
[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.
|
[`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`.
|
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"`.
|
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.
|
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.
|
You can scan files and directories by using the `--no-git` option.
|
||||||
|
|
||||||
#### Protect
|
#### Protect
|
||||||
The `protect` command is used to uncommitted changes in a git repo. This command should be used on developer machines in accordance with
|
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).
|
[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
|
[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
|
`--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.
|
as a pre-commit.
|
||||||
|
|
||||||
@@ -123,7 +147,7 @@ Example output:
|
|||||||
"EndLine": 37,
|
"EndLine": 37,
|
||||||
"StartColumn": 19,
|
"StartColumn": 19,
|
||||||
"EndColumn": 38,
|
"EndColumn": 38,
|
||||||
"Context": "\t\t\"aws_secret= \\\"AKIAIMNOJVGFDXXXE4OA\\\"\": true,",
|
"Match": "\t\t\"aws_secret= \\\"AKIAIMNOJVGFDXXXE4OA\\\"\": true,",
|
||||||
"Secret": "AKIAIMNOJVGFDXXXE4OA",
|
"Secret": "AKIAIMNOJVGFDXXXE4OA",
|
||||||
"File": "checks_test.go",
|
"File": "checks_test.go",
|
||||||
"Commit": "ec2fc9d6cb0954fb3b57201cf6133c48d8ca0d29",
|
"Commit": "ec2fc9d6cb0954fb3b57201cf6133c48d8ca0d29",
|
||||||
@@ -164,33 +188,34 @@ diff --git a/checks_test.go b/checks_test.go
|
|||||||
```
|
```
|
||||||
|
|
||||||
## Pre-Commit hook
|
## 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.
|
your `.git/hooks/` directory.
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
Gitleaks offers a configuration format you can follow to write your own secret detection rules:
|
Gitleaks offers a configuration format you can follow to write your own secret detection rules:
|
||||||
```toml
|
```toml
|
||||||
# Title for the gitleaks configuration file.
|
# Title for the gitleaks configuration file.
|
||||||
title = "Gitleaks title"
|
title = "Gitleaks title"
|
||||||
|
|
||||||
# An array of tables that contain information that define instructions
|
# An array of tables that contain information that define instructions
|
||||||
# on how to detect secrets
|
# on how to detect secrets
|
||||||
[[rules]]
|
[[rules]]
|
||||||
# Unique identifier for this rule
|
# Unique identifier for this rule
|
||||||
id = "awesome-rule-1"
|
id = "awesome-rule-1"
|
||||||
# Short human readable description of the rule.
|
# Short human readable description of the rule.
|
||||||
description = "awsome rule 1"
|
description = "awesome rule 1"
|
||||||
# Golang regular expression used to detect secrets. Note Golang's regex engine
|
# Golang regular expression used to detect secrets. Note Golang's regex engine
|
||||||
# does not support lookaheads.
|
# 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
|
# 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.
|
# in conjunction with a valid `regex` entry.
|
||||||
path = '''a-file-path-regex'''
|
path = '''a-file-path-regex'''
|
||||||
# Array of strings used for metadata and reporting purposes.
|
# Array of strings used for metadata and reporting purposes.
|
||||||
tags = ["tag","another tag"]
|
tags = ["tag","another tag"]
|
||||||
# Int used to check shannon entropy of a specific group in a regex match.
|
# Int used to extract secret from regex match and used as the group that will have
|
||||||
entropyGroup = 3
|
# its entropy checked if `entropy` is set.
|
||||||
# Float representing the minimum shannon entropy a regex group must have to be considered a secret.
|
secretGroup = 3
|
||||||
|
# Float representing the minimum shannon entropy a regex group must have to be considered a secret.
|
||||||
entropy = 3.5
|
entropy = 3.5
|
||||||
# You can include an allowlist table for a single rule to reduce false positives or ignore commits
|
# You can include an allowlist table for a single rule to reduce false positives or ignore commits
|
||||||
# with known/rotated secrets
|
# with known/rotated secrets
|
||||||
@@ -200,8 +225,8 @@ commits = [ "commit-A", "commit-B"]
|
|||||||
paths = ['''one-file-path-regex''']
|
paths = ['''one-file-path-regex''']
|
||||||
regexes = ['''one-regex-within-the-already-matched-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.
|
# This is a global allowlist which has a higher order of precedence than rule-specific allowlists.
|
||||||
# If a commit listed in the `commits` field below is encountered then that commit will be skipped and no
|
# 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.
|
# secrets will be detected for said commit. The same logic applies for regexes and paths.
|
||||||
[allowlist]
|
[allowlist]
|
||||||
description = "ignore commit A"
|
description = "ignore commit A"
|
||||||
@@ -209,7 +234,73 @@ commits = [ "commit-A", "commit-B"]
|
|||||||
paths = ['''one-file-path-regex''']
|
paths = ['''one-file-path-regex''']
|
||||||
regexes = ['''one-regex-within-the-already-matched-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
|
||||||
|
<p align="left">
|
||||||
|
<a href="https://www.tines.com/?utm_source=oss&utm_medium=sponsorship&utm_campaign=gitleaks">
|
||||||
|
<img alt="Tines Sponsorship" src="https://user-images.githubusercontent.com/15034943/146411864-4878f936-b4f7-49a0-b625-f9f40c704bfa.png" width=200>
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
<a href="https://www.typeform.com/">
|
||||||
|
<img src="https://user-images.githubusercontent.com/15034943/146945294-a6473d55-86b8-4f53-941e-7f185ad6b3d7.png" width=200/>
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Exit Codes
|
## Exit Codes
|
||||||
@@ -217,4 +308,5 @@ You can always set the exit code when leaks are encountered with the --exit-code
|
|||||||
```
|
```
|
||||||
0 - no leaks present
|
0 - no leaks present
|
||||||
1 - leaks or error encountered
|
1 - leaks or error encountered
|
||||||
|
126 - unknown flag
|
||||||
```
|
```
|
||||||
+70
-30
@@ -2,6 +2,7 @@ package cmd
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"os"
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/rs/zerolog/log"
|
"github.com/rs/zerolog/log"
|
||||||
@@ -10,7 +11,6 @@ import (
|
|||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
"github.com/zricethezav/gitleaks/v8/detect"
|
"github.com/zricethezav/gitleaks/v8/detect"
|
||||||
"github.com/zricethezav/gitleaks/v8/git"
|
|
||||||
"github.com/zricethezav/gitleaks/v8/report"
|
"github.com/zricethezav/gitleaks/v8/report"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -30,56 +30,96 @@ func runDetect(cmd *cobra.Command, args []string) {
|
|||||||
initConfig()
|
initConfig()
|
||||||
var (
|
var (
|
||||||
vc config.ViperConfig
|
vc config.ViperConfig
|
||||||
findings []*report.Finding
|
findings []report.Finding
|
||||||
err error
|
err error
|
||||||
)
|
)
|
||||||
|
|
||||||
viper.Unmarshal(&vc)
|
// Load config
|
||||||
|
if err = viper.Unmarshal(&vc); err != nil {
|
||||||
|
log.Fatal().Err(err).Msg("Failed to load config")
|
||||||
|
}
|
||||||
cfg, err := vc.Translate()
|
cfg, err := vc.Translate()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal().Err(err).Msg("Failed to load config")
|
log.Fatal().Err(err).Msg("Failed to load config")
|
||||||
}
|
}
|
||||||
|
cfg.Path, _ = cmd.Flags().GetString("config")
|
||||||
|
|
||||||
source, _ := cmd.Flags().GetString("source")
|
// start timer
|
||||||
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")
|
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
|
|
||||||
if noGit {
|
// Setup detector
|
||||||
if logOpts != "" {
|
detector := detect.NewDetector(cfg)
|
||||||
log.Fatal().Err(err).Msg("--log-opts cannot be used with --no-git")
|
detector.Config.Path, err = cmd.Flags().GetString("config")
|
||||||
}
|
if err != nil {
|
||||||
findings, err = detect.FromFiles(source, cfg, detect.Options{
|
log.Fatal().Err(err)
|
||||||
Verbose: verbose,
|
}
|
||||||
Redact: redact,
|
source, err := cmd.Flags().GetString("source")
|
||||||
})
|
if err != nil {
|
||||||
if err != nil {
|
log.Fatal().Err(err)
|
||||||
log.Fatal().Err(err).Msg("Failed to scan files")
|
}
|
||||||
}
|
// if config path is not set, then use the {source}/.gitleaks.toml path.
|
||||||
} else {
|
// note that there may not be a `{source}/.gitleaks.toml` file, this is ok.
|
||||||
files, err := git.GitLog(source, logOpts)
|
if detector.Config.Path == "" {
|
||||||
if err != nil {
|
detector.Config.Path = filepath.Join(source, ".gitleaks.toml")
|
||||||
log.Fatal().Err(err).Msg("Failed to get git log")
|
}
|
||||||
}
|
// set verbose flag
|
||||||
|
if detector.Verbose, err = cmd.Flags().GetBool("verbose"); err != nil {
|
||||||
findings = detect.FromGit(files, cfg, detect.Options{Verbose: verbose, Redact: redact})
|
log.Fatal().Err(err)
|
||||||
|
}
|
||||||
|
// set redact flag
|
||||||
|
if detector.Redact, err = cmd.Flags().GetBool("redact"); err != nil {
|
||||||
|
log.Fatal().Err(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// set exit code
|
||||||
|
exitCode, err := cmd.Flags().GetInt("exit-code")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal().Err(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// determine what type of scan:
|
||||||
|
// - git: scan the history of the repo
|
||||||
|
// - no-git: scan files by treating the repo as a plain directory
|
||||||
|
noGit, err := cmd.Flags().GetBool("no-git")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal().Err(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// start the detector scan
|
||||||
|
if noGit {
|
||||||
|
findings, err = detector.DetectFiles(source)
|
||||||
|
if err != nil {
|
||||||
|
// don't exit on error, just log it
|
||||||
|
log.Error().Err(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
logOpts, err := cmd.Flags().GetString("log-opts")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal().Err(err)
|
||||||
|
}
|
||||||
|
findings, err = detector.DetectGit(source, logOpts, detect.DetectType)
|
||||||
|
if err != nil {
|
||||||
|
// don't exit on error, just log it
|
||||||
|
log.Error().Err(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// log info about the scan
|
||||||
|
log.Info().Msgf("scan completed in %s", time.Since(start))
|
||||||
if len(findings) != 0 {
|
if len(findings) != 0 {
|
||||||
log.Warn().Msgf("leaks found: %d", len(findings))
|
log.Warn().Msgf("leaks found: %d", len(findings))
|
||||||
} else {
|
} else {
|
||||||
log.Info().Msg("no leaks found")
|
log.Info().Msg("no leaks found")
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Info().Msgf("scan completed in %s", time.Since(start))
|
// write report if desired
|
||||||
|
|
||||||
reportPath, _ := cmd.Flags().GetString("report-path")
|
reportPath, _ := cmd.Flags().GetString("report-path")
|
||||||
ext, _ := cmd.Flags().GetString("report-format")
|
ext, _ := cmd.Flags().GetString("report-format")
|
||||||
if reportPath != "" {
|
if reportPath != "" {
|
||||||
report.Write(findings, cfg, ext, reportPath)
|
if err = report.Write(findings, cfg, ext, reportPath); err != nil {
|
||||||
|
log.Fatal().Err(err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(findings) != 0 {
|
if len(findings) != 0 {
|
||||||
|
|||||||
+49
-11
@@ -2,6 +2,7 @@ package cmd
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"os"
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/rs/zerolog/log"
|
"github.com/rs/zerolog/log"
|
||||||
@@ -10,7 +11,6 @@ import (
|
|||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
"github.com/zricethezav/gitleaks/v8/detect"
|
"github.com/zricethezav/gitleaks/v8/detect"
|
||||||
"github.com/zricethezav/gitleaks/v8/git"
|
|
||||||
"github.com/zricethezav/gitleaks/v8/report"
|
"github.com/zricethezav/gitleaks/v8/report"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -29,37 +29,75 @@ func runProtect(cmd *cobra.Command, args []string) {
|
|||||||
initConfig()
|
initConfig()
|
||||||
var vc config.ViperConfig
|
var vc config.ViperConfig
|
||||||
|
|
||||||
viper.Unmarshal(&vc)
|
if err := viper.Unmarshal(&vc); err != nil {
|
||||||
|
log.Fatal().Err(err).Msg("Failed to load config")
|
||||||
|
}
|
||||||
cfg, err := vc.Translate()
|
cfg, err := vc.Translate()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal().Err(err).Msg("Failed to load config")
|
log.Fatal().Err(err).Msg("Failed to load config")
|
||||||
}
|
}
|
||||||
|
|
||||||
source, _ := cmd.Flags().GetString("source")
|
cfg.Path, _ = cmd.Flags().GetString("config")
|
||||||
verbose, _ := cmd.Flags().GetBool("verbose")
|
|
||||||
redact, _ := cmd.Flags().GetBool("redact")
|
|
||||||
exitCode, _ := cmd.Flags().GetInt("exit-code")
|
exitCode, _ := cmd.Flags().GetInt("exit-code")
|
||||||
staged, _ := cmd.Flags().GetBool("staged")
|
staged, _ := cmd.Flags().GetBool("staged")
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
|
|
||||||
files, err := git.GitDiff(source, staged)
|
// Setup detector
|
||||||
|
detector := detect.NewDetector(cfg)
|
||||||
|
detector.Config.Path, err = cmd.Flags().GetString("config")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal().Err(err).Msg("Failed to get git log")
|
log.Fatal().Err(err)
|
||||||
|
}
|
||||||
|
source, err := cmd.Flags().GetString("source")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal().Err(err)
|
||||||
|
}
|
||||||
|
// if config path is not set, then use the {source}/.gitleaks.toml path.
|
||||||
|
// note that there may not be a `{source}/.gitleaks.toml` file, this is ok.
|
||||||
|
if detector.Config.Path == "" {
|
||||||
|
detector.Config.Path = filepath.Join(source, ".gitleaks.toml")
|
||||||
|
}
|
||||||
|
// set verbose flag
|
||||||
|
if detector.Verbose, err = cmd.Flags().GetBool("verbose"); err != nil {
|
||||||
|
log.Fatal().Err(err)
|
||||||
|
}
|
||||||
|
// set redact flag
|
||||||
|
if detector.Redact, err = cmd.Flags().GetBool("redact"); err != nil {
|
||||||
|
log.Fatal().Err(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
findings := detect.FromGit(files, cfg, detect.Options{Verbose: verbose, Redact: redact})
|
// get log options for git scan
|
||||||
|
logOpts, err := cmd.Flags().GetString("log-opts")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal().Err(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// start git scan
|
||||||
|
var findings []report.Finding
|
||||||
|
if staged {
|
||||||
|
findings, err = detector.DetectGit(source, logOpts, detect.ProtectStagedType)
|
||||||
|
} else {
|
||||||
|
findings, err = detector.DetectGit(source, logOpts, detect.ProtectType)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
// don't exit on error, just log it
|
||||||
|
log.Error().Err(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// log info about the scan
|
||||||
|
log.Info().Msgf("scan completed in %s", time.Since(start))
|
||||||
if len(findings) != 0 {
|
if len(findings) != 0 {
|
||||||
log.Warn().Msgf("leaks found: %d", len(findings))
|
log.Warn().Msgf("leaks found: %d", len(findings))
|
||||||
} else {
|
} else {
|
||||||
log.Info().Msg("no leaks found")
|
log.Info().Msg("no leaks found")
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Info().Msgf("scan duration: %s", time.Since(start))
|
|
||||||
|
|
||||||
reportPath, _ := cmd.Flags().GetString("report-path")
|
reportPath, _ := cmd.Flags().GetString("report-path")
|
||||||
ext, _ := cmd.Flags().GetString("report-format")
|
ext, _ := cmd.Flags().GetString("report-format")
|
||||||
if reportPath != "" {
|
if reportPath != "" {
|
||||||
report.Write(findings, cfg, ext, reportPath)
|
if err = report.Write(findings, cfg, ext, reportPath); err != nil {
|
||||||
|
log.Fatal().Err(err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if len(findings) != 0 {
|
if len(findings) != 0 {
|
||||||
os.Exit(exitCode)
|
os.Exit(exitCode)
|
||||||
|
|||||||
+45
-20
@@ -26,9 +26,9 @@ const banner = `
|
|||||||
const configDescription = `config file path
|
const configDescription = `config file path
|
||||||
order of precedence:
|
order of precedence:
|
||||||
1. --config/-c
|
1. --config/-c
|
||||||
2. (--source/-s)/.gitleaks.toml
|
2. env var GITLEAKS_CONFIG
|
||||||
if --config/-c is not set and no .gitleaks.toml/gitleaks.toml present
|
3. (--source/-s)/.gitleaks.toml
|
||||||
then .gitleaks.toml will be written to (--source/-s)/.gitleaks.toml for future use`
|
If none of the three options are used, then gitleaks will use the default config`
|
||||||
|
|
||||||
var rootCmd = &cobra.Command{
|
var rootCmd = &cobra.Command{
|
||||||
Use: "gitleaks",
|
Use: "gitleaks",
|
||||||
@@ -38,21 +38,24 @@ var rootCmd = &cobra.Command{
|
|||||||
func init() {
|
func init() {
|
||||||
cobra.OnInitialize(initLog)
|
cobra.OnInitialize(initLog)
|
||||||
rootCmd.PersistentFlags().StringP("config", "c", "", configDescription)
|
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("source", "s", ".", "path to source (default: $PWD)")
|
||||||
rootCmd.PersistentFlags().StringP("report-path", "r", "", "report file")
|
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().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().BoolP("verbose", "v", false, "show verbose output from scan")
|
||||||
rootCmd.PersistentFlags().Bool("redact", false, "redact secrets from logs and stdout")
|
rootCmd.PersistentFlags().Bool("redact", false, "redact secrets from logs and stdout")
|
||||||
viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config"))
|
err := viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config"))
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal().Msgf("err binding config %s", err.Error())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func initLog() {
|
func initLog() {
|
||||||
zerolog.SetGlobalLevel(zerolog.InfoLevel)
|
zerolog.SetGlobalLevel(zerolog.InfoLevel)
|
||||||
ll, err := rootCmd.Flags().GetString("log-level")
|
ll, err := rootCmd.Flags().GetString("log-level")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal().Err(err)
|
log.Fatal().Msg(err.Error())
|
||||||
}
|
}
|
||||||
switch strings.ToLower(ll) {
|
switch strings.ToLower(ll) {
|
||||||
case "debug":
|
case "debug":
|
||||||
@@ -71,29 +74,47 @@ func initLog() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func initConfig() {
|
func initConfig() {
|
||||||
fmt.Fprintf(os.Stderr, banner)
|
fmt.Fprint(os.Stderr, banner)
|
||||||
cfgPath, err := rootCmd.Flags().GetString("config")
|
cfgPath, err := rootCmd.Flags().GetString("config")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal().Err(err)
|
log.Fatal().Msg(err.Error())
|
||||||
}
|
}
|
||||||
if cfgPath != "" {
|
if cfgPath != "" {
|
||||||
viper.SetConfigFile(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 {
|
} else {
|
||||||
source, err := rootCmd.Flags().GetString("source")
|
source, err := rootCmd.Flags().GetString("source")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal().Err(err)
|
log.Fatal().Msg(err.Error())
|
||||||
}
|
}
|
||||||
if _, err := os.Stat(filepath.Join(source, ".gitleaks.toml")); os.IsNotExist(err) {
|
fileInfo, err := os.Stat(source)
|
||||||
log.Debug().Msgf("No gitleaks config found, writing default gitleaks config to %s", filepath.Join(source, ".gitleaks.toml"))
|
if err != nil {
|
||||||
if err := os.WriteFile(filepath.Join(source, ".gitleaks.toml"), []byte(config.DefaultConfig), os.ModePerm); err != nil {
|
log.Fatal().Msg(err.Error())
|
||||||
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))
|
if !fileInfo.IsDir() {
|
||||||
return
|
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")
|
||||||
|
if err = viper.ReadConfig(strings.NewReader(config.DefaultConfig)); err != nil {
|
||||||
|
log.Fatal().Msgf("err reading toml %s", err.Error())
|
||||||
}
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := os.Stat(filepath.Join(source, ".gitleaks.toml")); os.IsNotExist(err) {
|
||||||
|
log.Debug().Msgf("No gitleaks config found in path %s, using default gitleaks config", filepath.Join(source, ".gitleaks.toml"))
|
||||||
|
viper.SetConfigType("toml")
|
||||||
|
if err = viper.ReadConfig(strings.NewReader(config.DefaultConfig)); err != nil {
|
||||||
|
log.Fatal().Msgf("err reading default config toml %s", err.Error())
|
||||||
|
}
|
||||||
|
return
|
||||||
} else {
|
} 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)
|
viper.AddConfigPath(source)
|
||||||
@@ -107,6 +128,10 @@ func initConfig() {
|
|||||||
|
|
||||||
func Execute() {
|
func Execute() {
|
||||||
if err := rootCmd.Execute(); err != nil {
|
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
-11
@@ -2,13 +2,23 @@ package config
|
|||||||
|
|
||||||
import "regexp"
|
import "regexp"
|
||||||
|
|
||||||
|
// Allowlist allows a rule to be ignored for specific
|
||||||
|
// regexes, paths, and/or commits
|
||||||
type Allowlist struct {
|
type Allowlist struct {
|
||||||
|
// Short human readable description of the allowlist.
|
||||||
Description string
|
Description string
|
||||||
Regexes []*regexp.Regexp
|
|
||||||
Paths []*regexp.Regexp
|
// Regexes is slice of content regular expressions that are allowed to be ignored.
|
||||||
Commits []string
|
Regexes []*regexp.Regexp
|
||||||
|
|
||||||
|
// Paths is a slice of path regular expressions that are allowed to be ignored.
|
||||||
|
Paths []*regexp.Regexp
|
||||||
|
|
||||||
|
// Commits is a slice of commit SHAs that are allowed to be ignored.
|
||||||
|
Commits []string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CommitAllowed returns true if the commit is allowed to be ignored.
|
||||||
func (a *Allowlist) CommitAllowed(c string) bool {
|
func (a *Allowlist) CommitAllowed(c string) bool {
|
||||||
if c == "" {
|
if c == "" {
|
||||||
return false
|
return false
|
||||||
@@ -21,16 +31,12 @@ func (a *Allowlist) CommitAllowed(c string) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PathAllowed returns true if the path is allowed to be ignored.
|
||||||
func (a *Allowlist) PathAllowed(path string) bool {
|
func (a *Allowlist) PathAllowed(path string) bool {
|
||||||
if anyRegexMatch(path, a.Paths) {
|
return anyRegexMatch(path, a.Paths)
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RegexAllowed returns true if the regex is allowed to be ignored.
|
||||||
func (a *Allowlist) RegexAllowed(s string) bool {
|
func (a *Allowlist) RegexAllowed(s string) bool {
|
||||||
if anyRegexMatch(s, a.Regexes) {
|
return anyRegexMatch(s, a.Regexes)
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
+17
-16
@@ -15,13 +15,13 @@ var DefaultConfig string
|
|||||||
type ViperConfig struct {
|
type ViperConfig struct {
|
||||||
Description string
|
Description string
|
||||||
Rules []struct {
|
Rules []struct {
|
||||||
ID string
|
ID string
|
||||||
Description string
|
Description string
|
||||||
Entropy float64
|
Entropy float64
|
||||||
EntropyGroup int
|
SecretGroup int
|
||||||
Regex string
|
Regex string
|
||||||
Path string
|
Path string
|
||||||
Tags []string
|
Tags []string
|
||||||
|
|
||||||
Allowlist struct {
|
Allowlist struct {
|
||||||
Regexes []string
|
Regexes []string
|
||||||
@@ -38,6 +38,7 @@ type ViperConfig struct {
|
|||||||
|
|
||||||
// Config is a configuration struct that contains rules and an allowlist if present.
|
// Config is a configuration struct that contains rules and an allowlist if present.
|
||||||
type Config struct {
|
type Config struct {
|
||||||
|
Path string
|
||||||
Description string
|
Description string
|
||||||
Rules []*Rule
|
Rules []*Rule
|
||||||
Allowlist Allowlist
|
Allowlist Allowlist
|
||||||
@@ -72,21 +73,21 @@ func (vc *ViperConfig) Translate() (Config, error) {
|
|||||||
configPathRegex = regexp.MustCompile(r.Path)
|
configPathRegex = regexp.MustCompile(r.Path)
|
||||||
}
|
}
|
||||||
r := &Rule{
|
r := &Rule{
|
||||||
Description: r.Description,
|
Description: r.Description,
|
||||||
RuleID: r.ID,
|
RuleID: r.ID,
|
||||||
Regex: configRegex,
|
Regex: configRegex,
|
||||||
Path: configPathRegex,
|
Path: configPathRegex,
|
||||||
EntropyReGroup: r.EntropyGroup,
|
SecretGroup: r.SecretGroup,
|
||||||
Entropy: r.Entropy,
|
Entropy: r.Entropy,
|
||||||
Tags: r.Tags,
|
Tags: r.Tags,
|
||||||
Allowlist: Allowlist{
|
Allowlist: Allowlist{
|
||||||
Regexes: allowlistRegexes,
|
Regexes: allowlistRegexes,
|
||||||
Paths: allowlistPaths,
|
Paths: allowlistPaths,
|
||||||
Commits: r.Allowlist.Commits,
|
Commits: r.Allowlist.Commits,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
if r.Regex != nil && r.EntropyReGroup > r.Regex.NumSubexp() {
|
if r.Regex != nil && r.SecretGroup > 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())
|
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)
|
rules = append(rules, r)
|
||||||
|
|
||||||
|
|||||||
+12
-70
@@ -74,13 +74,13 @@ func TestTranslate(t *testing.T) {
|
|||||||
cfg: Config{
|
cfg: Config{
|
||||||
Rules: []*Rule{
|
Rules: []*Rule{
|
||||||
{
|
{
|
||||||
Description: "Discord API key",
|
Description: "Discord API key",
|
||||||
Regex: regexp.MustCompile(`(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-h0-9]{64})['\"]`),
|
Regex: regexp.MustCompile(`(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-h0-9]{64})['\"]`),
|
||||||
RuleID: "discord-api-key",
|
RuleID: "discord-api-key",
|
||||||
Allowlist: Allowlist{},
|
Allowlist: Allowlist{},
|
||||||
Entropy: 3.5,
|
Entropy: 3.5,
|
||||||
EntropyReGroup: 3,
|
SecretGroup: 3,
|
||||||
Tags: []string{},
|
Tags: []string{},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -88,7 +88,7 @@ func TestTranslate(t *testing.T) {
|
|||||||
{
|
{
|
||||||
cfgName: "bad_entropy_group",
|
cfgName: "bad_entropy_group",
|
||||||
cfg: Config{},
|
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"),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,7 +103,10 @@ func TestTranslate(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var vc ViperConfig
|
var vc ViperConfig
|
||||||
viper.Unmarshal(&vc)
|
err = viper.Unmarshal(&vc)
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
cfg, err := vc.Translate()
|
cfg, err := vc.Translate()
|
||||||
if tt.wantError != nil {
|
if tt.wantError != nil {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
@@ -115,64 +118,3 @@ func TestTranslate(t *testing.T) {
|
|||||||
assert.Equal(t, cfg.Rules, tt.cfg.Rules)
|
assert.Equal(t, cfg.Rules, tt.cfg.Rules)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestIncludeEntropy(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
rule Rule
|
|
||||||
secret string
|
|
||||||
entropy float32
|
|
||||||
include bool
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
rule: Rule{
|
|
||||||
RuleID: "generic-api-key",
|
|
||||||
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})['\"]`),
|
|
||||||
},
|
|
||||||
secret: `Key = "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})['\"]`),
|
|
||||||
},
|
|
||||||
secret: `Key = "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})['\"]`),
|
|
||||||
},
|
|
||||||
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"`,
|
|
||||||
entropy: 0,
|
|
||||||
include: false,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
include, entropy := tt.rule.IncludeEntropy(tt.secret)
|
|
||||||
assert.Equal(t, true, tt.rule.EntropySet())
|
|
||||||
assert.Equal(t, tt.entropy, float32(entropy))
|
|
||||||
assert.Equal(t, tt.include, include)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+169
-56
@@ -2,42 +2,42 @@ title = "gitleaks config"
|
|||||||
|
|
||||||
# Gitleaks rules are defined by regular expressions and entropy ranges.
|
# Gitleaks rules are defined by regular expressions and entropy ranges.
|
||||||
# Some secrets have unique signatures which make detecting those secrets easy.
|
# 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.
|
# 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
|
# 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.
|
# that what we are matching is a secret.
|
||||||
#
|
#
|
||||||
# Here is an example of a semi-generic secret
|
# Here is an example of a semi-generic secret
|
||||||
#
|
#
|
||||||
# discord_client_secret = "8dyfuiRyq=vVc3RRr_edRk-fK__JItpZ"
|
# 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 assignment symbol (like '=' or ':='), and finally the actual secret.
|
||||||
# The structure of a rule to match this example secret is below:
|
# The structure of a rule to match this example secret is below:
|
||||||
#
|
#
|
||||||
# Beginning string
|
# Beginning string
|
||||||
# quotation
|
# quotation
|
||||||
# │ End string quotation
|
# │ End string quotation
|
||||||
# │ │
|
# │ │
|
||||||
# ▼ ▼
|
# ▼ ▼
|
||||||
# (?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9=_\-]{32})['\"]
|
# (?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9=_\-]{32})['\"]
|
||||||
#
|
#
|
||||||
# ▲ ▲ ▲
|
# ▲ ▲ ▲
|
||||||
# │ │ │
|
# │ │ │
|
||||||
# │ │ │
|
# │ │ │
|
||||||
# identifier assignment symbol
|
# identifier assignment symbol
|
||||||
# Secret
|
# Secret
|
||||||
#
|
#
|
||||||
[[rules]]
|
[[rules]]
|
||||||
id = "gitlab-pat"
|
id = "gitlab-pat"
|
||||||
description = "GitLab Personal Access Token"
|
description = "GitLab Personal Access Token"
|
||||||
regex = '''glpat-[0-9a-zA-Z\-]{20}'''
|
regex = '''glpat-[0-9a-zA-Z\-\_]{20}'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
id = "aws-access-token"
|
id = "aws-access-token"
|
||||||
description = "AWS"
|
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
|
# Cryptographic keys
|
||||||
[[rules]]
|
[[rules]]
|
||||||
@@ -62,12 +62,12 @@ regex = '''-----BEGIN PGP PRIVATE KEY BLOCK-----'''
|
|||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
id = "github-pat"
|
id = "github-pat"
|
||||||
description = "Github Personal Access Token"
|
description = "GitHub Personal Access Token"
|
||||||
regex = '''ghp_[0-9a-zA-Z]{36}'''
|
regex = '''ghp_[0-9a-zA-Z]{36}'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
id = "github-oauth"
|
id = "github-oauth"
|
||||||
description = "Github OAuth Access Token"
|
description = "GitHub OAuth Access Token"
|
||||||
regex = '''gho_[0-9a-zA-Z]{36}'''
|
regex = '''gho_[0-9a-zA-Z]{36}'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
@@ -83,12 +83,12 @@ regex = '''-----BEGIN EC PRIVATE KEY-----'''
|
|||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
id = "github-app-token"
|
id = "github-app-token"
|
||||||
description = "Github App Token"
|
description = "GitHub App Token"
|
||||||
regex = '''(ghu|ghs)_[0-9a-zA-Z]{36}'''
|
regex = '''(ghu|ghs)_[0-9a-zA-Z]{36}'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
id = "github-refresh-token"
|
id = "github-refresh-token"
|
||||||
description = "Github Refresh Token"
|
description = "GitHub Refresh Token"
|
||||||
regex = '''ghr_[0-9a-zA-Z]{76}'''
|
regex = '''ghr_[0-9a-zA-Z]{76}'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
@@ -124,16 +124,8 @@ regex = '''(?i)(sk|pk)_(test|live)_[0-9a-z]{10,32}'''
|
|||||||
[[rules]]
|
[[rules]]
|
||||||
id = "pypi-upload-token"
|
id = "pypi-upload-token"
|
||||||
description = "PyPI upload token"
|
description = "PyPI upload token"
|
||||||
regex = '''pypi-AgEIcHlwaS5vcmc[A-Za-z0-9-_]{50,1000}'''
|
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]]
|
[[rules]]
|
||||||
id = "gcp-service-account"
|
id = "gcp-service-account"
|
||||||
description = "Google (GCP) Service-account"
|
description = "Google (GCP) Service-account"
|
||||||
@@ -143,11 +135,12 @@ regex = '''\"type\": \"service_account\"'''
|
|||||||
id = "heroku-api-key"
|
id = "heroku-api-key"
|
||||||
description = "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})['\"]'''
|
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]]
|
[[rules]]
|
||||||
id = "slack-web-hook"
|
id = "slack-web-hook"
|
||||||
description = "Slack Webhook"
|
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]]
|
[[rules]]
|
||||||
id = "twilio-api-key"
|
id = "twilio-api-key"
|
||||||
@@ -163,16 +156,19 @@ regex = '''AGE-SECRET-KEY-1[QPZRY9X8GF2TVDW0S3JN54KHCE6MUA7L]{58}'''
|
|||||||
id = "facebook-token"
|
id = "facebook-token"
|
||||||
description = "Facebook token"
|
description = "Facebook token"
|
||||||
regex = '''(?i)(facebook[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-f0-9]{32})['\"]'''
|
regex = '''(?i)(facebook[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-f0-9]{32})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
id = "twitter-token"
|
id = "twitter-token"
|
||||||
description = "Twitter token"
|
description = "Twitter token"
|
||||||
regex = '''(?i)(twitter[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-f0-9]{35,44})['\"]'''
|
regex = '''(?i)(twitter[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-f0-9]{35,44})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
id = "adobe-client-id"
|
id = "adobe-client-id"
|
||||||
description = "Adobe Client ID (Oauth Web)"
|
description = "Adobe Client ID (Oauth Web)"
|
||||||
regex = '''(?i)(adobe[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-f0-9]{32})['\"]'''
|
regex = '''(?i)(adobe[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-f0-9]{32})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
id = "adobe-client-secret"
|
id = "adobe-client-secret"
|
||||||
@@ -188,261 +184,378 @@ regex = '''(LTAI)(?i)[a-z0-9]{20}'''
|
|||||||
id = "alibaba-secret-key"
|
id = "alibaba-secret-key"
|
||||||
description = "Alibaba Secret Key"
|
description = "Alibaba Secret Key"
|
||||||
regex = '''(?i)(alibaba[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{30})['\"]'''
|
regex = '''(?i)(alibaba[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{30})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
id = "asana-client-id"
|
id = "asana-client-id"
|
||||||
description = "Asana Client ID"
|
description = "Asana Client ID"
|
||||||
regex = '''(?i)(asana[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([0-9]{16})['\"]'''
|
regex = '''(?i)(asana[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([0-9]{16})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
id = "asana-client-secret"
|
id = "asana-client-secret"
|
||||||
description = "Asana Client Secret"
|
description = "Asana Client Secret"
|
||||||
regex = '''(?i)(asana[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{32})['\"]'''
|
regex = '''(?i)(asana[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{32})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
id = "atlassian-api-token"
|
id = "atlassian-api-token"
|
||||||
description = "Atlassian API token"
|
description = "Atlassian API token"
|
||||||
regex = '''(?i)(atlassian[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{24})['\"]'''
|
regex = '''(?i)(atlassian[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{24})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
id = "bitbucket-client-id"
|
id = "bitbucket-client-id"
|
||||||
description = "Bitbucket client ID"
|
description = "Bitbucket client ID"
|
||||||
regex = '''(?i)(bitbucket[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{32})['\"]'''
|
regex = '''(?i)(bitbucket[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{32})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "bitbucket-client-secret"
|
||||||
description = "Bitbucket client secret"
|
description = "Bitbucket client secret"
|
||||||
regex = '''(?i)(bitbucket[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9_\-]{64})['\"]'''
|
regex = '''(?i)(bitbucket[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9_\-]{64})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "beamer-api-token"
|
||||||
description = "Beamer API token"
|
description = "Beamer API token"
|
||||||
regex = '''(?i)(beamer[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"](b_[a-z0-9=_\-]{44})['\"]'''
|
regex = '''(?i)(beamer[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"](b_[a-z0-9=_\-]{44})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "clojars-api-token"
|
||||||
description = "Clojars API token"
|
description = "Clojars API token"
|
||||||
regex = '''(CLOJARS_)(?i)[a-z0-9]{60}'''
|
regex = '''(CLOJARS_)(?i)[a-z0-9]{60}'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "contentful-delivery-api-token"
|
||||||
description = "Contentful delivery API token"
|
description = "Contentful delivery API token"
|
||||||
regex = '''(?i)(contentful[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9\-=_]{43})['\"]'''
|
regex = '''(?i)(contentful[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9\-=_]{43})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
description = "Contentful preview API token"
|
id = "databricks-api-token"
|
||||||
regex = '''(?i)(contentful[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9\-=_]{43})['\"]'''
|
|
||||||
|
|
||||||
[[rules]]
|
|
||||||
description = "Databricks API token"
|
description = "Databricks API token"
|
||||||
regex = '''dapi[a-h0-9]{32}'''
|
regex = '''dapi[a-h0-9]{32}'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "discord-api-token"
|
||||||
description = "Discord API key"
|
description = "Discord API key"
|
||||||
regex = '''(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-h0-9]{64})['\"]'''
|
regex = '''(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-h0-9]{64})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "discord-client-id"
|
||||||
description = "Discord client ID"
|
description = "Discord client ID"
|
||||||
regex = '''(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([0-9]{18})['\"]'''
|
regex = '''(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([0-9]{18})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "discord-client-secret"
|
||||||
description = "Discord client secret"
|
description = "Discord client secret"
|
||||||
regex = '''(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9=_\-]{32})['\"]'''
|
regex = '''(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9=_\-]{32})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "doppler-api-token"
|
||||||
description = "Doppler API token"
|
description = "Doppler API token"
|
||||||
regex = '''['\"](dp\.pt\.)(?i)[a-z0-9]{43}['\"]'''
|
regex = '''['\"](dp\.pt\.)(?i)[a-z0-9]{43}['\"]'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "dropbox-api-secret"
|
||||||
description = "Dropbox API secret/key"
|
description = "Dropbox API secret/key"
|
||||||
regex = '''(?i)(dropbox[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{15})['\"]'''
|
regex = '''(?i)(dropbox[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{15})['\"]'''
|
||||||
|
|
||||||
[[rules]]
|
[[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"
|
description = "Dropbox short lived API token"
|
||||||
regex = '''(?i)(dropbox[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"](sl\.[a-z0-9\-=_]{135})['\"]'''
|
regex = '''(?i)(dropbox[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"](sl\.[a-z0-9\-=_]{135})['\"]'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "dropbox-long-lived-api-token"
|
||||||
description = "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]]
|
[[rules]]
|
||||||
|
id = "duffel-api-token"
|
||||||
description = "Duffel API token"
|
description = "Duffel API token"
|
||||||
regex = '''['\"]duffel_(test|live)_(?i)[a-z0-9_-]{43}['\"]'''
|
regex = '''['\"]duffel_(test|live)_(?i)[a-z0-9_-]{43}['\"]'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "dynatrace-api-token"
|
||||||
description = "Dynatrace API token"
|
description = "Dynatrace API token"
|
||||||
regex = '''['\"]dt0c01\.(?i)[a-z0-9]{24}\.[a-z0-9]{64}['\"]'''
|
regex = '''['\"]dt0c01\.(?i)[a-z0-9]{24}\.[a-z0-9]{64}['\"]'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "easypost-api-token"
|
||||||
description = "EasyPost API token"
|
description = "EasyPost API token"
|
||||||
regex = '''['\"]EZAK(?i)[a-z0-9]{54}['\"]'''
|
regex = '''['\"]EZAK(?i)[a-z0-9]{54}['\"]'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "easypost-test-api-token"
|
||||||
description = "EasyPost test API token"
|
description = "EasyPost test API token"
|
||||||
regex = '''['\"]EZTK(?i)[a-z0-9]{54}['\"]'''
|
regex = '''['\"]EZTK(?i)[a-z0-9]{54}['\"]'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "fastly-api-token"
|
||||||
description = "Fastly API token"
|
description = "Fastly API token"
|
||||||
regex = '''(?i)(fastly[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9\-=_]{32})['\"]'''
|
regex = '''(?i)(fastly[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9\-=_]{32})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "finicity-client-secret"
|
||||||
description = "Finicity client secret"
|
description = "Finicity client secret"
|
||||||
regex = '''(?i)(finicity[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{20})['\"]'''
|
regex = '''(?i)(finicity[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{20})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "finicity-api-token"
|
||||||
description = "Finicity API token"
|
description = "Finicity API token"
|
||||||
regex = '''(?i)(finicity[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-f0-9]{32})['\"]'''
|
regex = '''(?i)(finicity[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-f0-9]{32})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
description = "Flutterweave public key"
|
id = "flutterwave-public-key"
|
||||||
|
description = "Flutterwave public key"
|
||||||
regex = '''FLWPUBK_TEST-(?i)[a-h0-9]{32}-X'''
|
regex = '''FLWPUBK_TEST-(?i)[a-h0-9]{32}-X'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
description = "Flutterweave secret key"
|
id = "flutterwave-secret-key"
|
||||||
|
description = "Flutterwave secret key"
|
||||||
regex = '''FLWSECK_TEST-(?i)[a-h0-9]{32}-X'''
|
regex = '''FLWSECK_TEST-(?i)[a-h0-9]{32}-X'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
description = "Flutterweave encrypted key"
|
id = "flutterwave-enc-key"
|
||||||
|
description = "Flutterwave encrypted key"
|
||||||
regex = '''FLWSECK_TEST[a-h0-9]{12}'''
|
regex = '''FLWSECK_TEST[a-h0-9]{12}'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "frameio-api-token"
|
||||||
description = "Frame.io API token"
|
description = "Frame.io API token"
|
||||||
regex = '''fio-u-(?i)[a-z0-9-_=]{64}'''
|
regex = '''fio-u-(?i)[a-z0-9\-_=]{64}'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "gocardless-api-token"
|
||||||
description = "GoCardless API token"
|
description = "GoCardless API token"
|
||||||
regex = '''['\"]live_(?i)[a-z0-9-_=]{40}['\"]'''
|
regex = '''['\"]live_(?i)[a-z0-9\-_=]{40}['\"]'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "grafana-api-token"
|
||||||
description = "Grafana API token"
|
description = "Grafana API token"
|
||||||
regex = '''['\"]eyJrIjoi(?i)[a-z0-9-_=]{72,92}['\"]'''
|
regex = '''['\"]eyJrIjoi(?i)[a-z0-9\-_=]{72,92}['\"]'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
description = "Hashicorp Terraform user/org API token"
|
id = "hashicorp-tf-api-token"
|
||||||
regex = '''['\"](?i)[a-z0-9]{14}\.atlasv1\.[a-z0-9-_=]{60,70}['\"]'''
|
description = "HashiCorp Terraform user/org API token"
|
||||||
|
regex = '''['\"](?i)[a-z0-9]{14}\.atlasv1\.[a-z0-9\-_=]{60,70}['\"]'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
description = "Hubspot API token"
|
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})['\"]'''
|
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]]
|
[[rules]]
|
||||||
|
id = "intercom-api-token"
|
||||||
description = "Intercom API token"
|
description = "Intercom API token"
|
||||||
regex = '''(?i)(intercom[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9=_]{60})['\"]'''
|
regex = '''(?i)(intercom[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9=_]{60})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "intercom-client-secret"
|
||||||
description = "Intercom client secret/ID"
|
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})['\"]'''
|
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]]
|
[[rules]]
|
||||||
|
id = "ionic-api-token"
|
||||||
description = "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]]
|
[[rules]]
|
||||||
|
id = "linear-api-token"
|
||||||
description = "Linear API token"
|
description = "Linear API token"
|
||||||
regex = '''lin_api_(?i)[a-z0-9]{40}'''
|
regex = '''lin_api_(?i)[a-z0-9]{40}'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "linear-client-secret"
|
||||||
description = "Linear client secret/ID"
|
description = "Linear client secret/ID"
|
||||||
regex = '''(?i)(linear[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-f0-9]{32})['\"]'''
|
regex = '''(?i)(linear[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-f0-9]{32})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "lob-api-key"
|
||||||
description = "Lob API Key"
|
description = "Lob API Key"
|
||||||
regex = '''(?i)(lob[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]((live|test)_[a-f0-9]{35})['\"]'''
|
regex = '''(?i)(lob[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]((live|test)_[a-f0-9]{35})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "lob-pub-api-key"
|
||||||
description = "Lob Publishable API Key"
|
description = "Lob Publishable API Key"
|
||||||
regex = '''(?i)(lob[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]((test|live)_pub_[a-f0-9]{31})['\"]'''
|
regex = '''(?i)(lob[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]((test|live)_pub_[a-f0-9]{31})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "mailchimp-api-key"
|
||||||
description = "Mailchimp API key"
|
description = "Mailchimp API key"
|
||||||
regex = '''(?i)(mailchimp[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-f0-9]{32}-us20)['\"]'''
|
regex = '''(?i)(mailchimp[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-f0-9]{32}-us20)['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "mailgun-private-api-token"
|
||||||
description = "Mailgun private API token"
|
description = "Mailgun private API token"
|
||||||
regex = '''(?i)(mailgun[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"](key-[a-f0-9]{32})['\"]'''
|
regex = '''(?i)(mailgun[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"](key-[a-f0-9]{32})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "mailgun-pub-key"
|
||||||
description = "Mailgun public validation key"
|
description = "Mailgun public validation key"
|
||||||
regex = '''(?i)(mailgun[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"](pubkey-[a-f0-9]{32})['\"]'''
|
regex = '''(?i)(mailgun[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"](pubkey-[a-f0-9]{32})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "mailgun-signing-key"
|
||||||
description = "Mailgun webhook 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})['\"]'''
|
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]]
|
[[rules]]
|
||||||
|
id = "mapbox-api-token"
|
||||||
description = "Mapbox API token"
|
description = "Mapbox API token"
|
||||||
regex = '''(?i)(pk\.[a-z0-9]{60}\.[a-z0-9]{22})'''
|
regex = '''(?i)(pk\.[a-z0-9]{60}\.[a-z0-9]{22})'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "messagebird-api-token"
|
||||||
description = "MessageBird API token"
|
description = "MessageBird API token"
|
||||||
regex = '''(?i)(messagebird[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{25})['\"]'''
|
regex = '''(?i)(messagebird[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{25})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "messagebird-client-id"
|
||||||
description = "MessageBird API 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})['\"]'''
|
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]]
|
[[rules]]
|
||||||
|
id = "new-relic-user-api-key"
|
||||||
description = "New Relic user API Key"
|
description = "New Relic user API Key"
|
||||||
regex = '''['\"](NRAK-[A-Z0-9]{27})['\"]'''
|
regex = '''['\"](NRAK-[A-Z0-9]{27})['\"]'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "new-relic-user-api-id"
|
||||||
description = "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})['\"]'''
|
regex = '''(?i)(newrelic[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([A-Z0-9]{64})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "new-relic-browser-api-token"
|
||||||
description = "New Relic ingest browser API token"
|
description = "New Relic ingest browser API token"
|
||||||
regex = '''['\"](NRJS-[a-f0-9]{19})['\"]'''
|
regex = '''['\"](NRJS-[a-f0-9]{19})['\"]'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "npm-access-token"
|
||||||
description = "npm access token"
|
description = "npm access token"
|
||||||
regex = '''['\"](npm_(?i)[a-z0-9]{36})['\"]'''
|
regex = '''['\"](npm_(?i)[a-z0-9]{36})['\"]'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
description = "Planetscale password"
|
id = "planetscale-password"
|
||||||
|
description = "PlanetScale password"
|
||||||
regex = '''pscale_pw_(?i)[a-z0-9\-_\.]{43}'''
|
regex = '''pscale_pw_(?i)[a-z0-9\-_\.]{43}'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
description = "Planetscale API token"
|
id = "planetscale-api-token"
|
||||||
|
description = "PlanetScale API token"
|
||||||
regex = '''pscale_tkn_(?i)[a-z0-9\-_\.]{43}'''
|
regex = '''pscale_tkn_(?i)[a-z0-9\-_\.]{43}'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "postman-api-token"
|
||||||
description = "Postman API token"
|
description = "Postman API token"
|
||||||
regex = '''PMAK-(?i)[a-f0-9]{24}\-[a-f0-9]{34}'''
|
regex = '''PMAK-(?i)[a-f0-9]{24}\-[a-f0-9]{34}'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "pulumi-api-token"
|
||||||
description = "Pulumi API token"
|
description = "Pulumi API token"
|
||||||
regex = '''pul-[a-f0-9]{40}'''
|
regex = '''pul-[a-f0-9]{40}'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "rubygems-api-token"
|
||||||
description = "Rubygem API token"
|
description = "Rubygem API token"
|
||||||
regex = '''rubygems_[a-f0-9]{48}'''
|
regex = '''rubygems_[a-f0-9]{48}'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
description = "Sendgrid API token"
|
id = "sendgrid-api-token"
|
||||||
|
description = "SendGrid API token"
|
||||||
regex = '''SG\.(?i)[a-z0-9_\-\.]{66}'''
|
regex = '''SG\.(?i)[a-z0-9_\-\.]{66}'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "sendinblue-api-token"
|
||||||
description = "Sendinblue API token"
|
description = "Sendinblue API token"
|
||||||
regex = '''xkeysib-[a-f0-9]{64}\-(?i)[a-z0-9]{16}'''
|
regex = '''xkeysib-[a-f0-9]{64}\-(?i)[a-z0-9]{16}'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "shippo-api-token"
|
||||||
description = "Shippo API token"
|
description = "Shippo API token"
|
||||||
regex = '''shippo_(live|test)_[a-f0-9]{40}'''
|
regex = '''shippo_(live|test)_[a-f0-9]{40}'''
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
description = "Linkedin Client secret"
|
id = "linkedin-client-secret"
|
||||||
|
description = "LinkedIn Client secret"
|
||||||
regex = '''(?i)(linkedin[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z]{16})['\"]'''
|
regex = '''(?i)(linkedin[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z]{16})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
description = "Linkedin Client ID"
|
id = "linkedin-client-id"
|
||||||
|
description = "LinkedIn Client ID"
|
||||||
regex = '''(?i)(linkedin[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{14})['\"]'''
|
regex = '''(?i)(linkedin[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{14})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "twitch-api-token"
|
||||||
description = "Twitch API token"
|
description = "Twitch API token"
|
||||||
regex = '''(?i)(twitch[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{30})['\"]'''
|
regex = '''(?i)(twitch[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9]{30})['\"]'''
|
||||||
|
secretGroup = 3
|
||||||
|
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
id = "typeform-api-token"
|
||||||
description = "Typeform API token"
|
description = "Typeform API token"
|
||||||
regex = '''(?i)(typeform[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}(tfp_[a-z0-9\-_\.=]{59})'''
|
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[^Version]|token|secret|password)[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([0-9a-zA-Z\-_=]{8,64})['\"]'''
|
||||||
|
entropy = 3.7
|
||||||
|
secretGroup = 4
|
||||||
|
|
||||||
|
|
||||||
[allowlist]
|
[allowlist]
|
||||||
description = "global allow lists"
|
description = "global allow lists"
|
||||||
regexes = ['''219-09-9999''', '''078-05-1120''', '''(9[0-9]{2}|666)-\d{2}-\d{4}''']
|
regexes = [
|
||||||
files = ['''(.*?)(jpg|gif|doc|pdf|bin|svg|socket)$''']
|
'''219-09-9999''',
|
||||||
|
'''078-05-1120''',
|
||||||
|
'''(9[0-9]{2}|666)-\d{2}-\d{4}''',
|
||||||
|
'''process''',
|
||||||
|
'''getenv''',
|
||||||
|
'''\.env''',
|
||||||
|
'''env\(''',
|
||||||
|
'''env\.''',
|
||||||
|
'''setting''',
|
||||||
|
'''load''',
|
||||||
|
'''token''',
|
||||||
|
'''password''',
|
||||||
|
'''secret''',
|
||||||
|
'''api\_key''',
|
||||||
|
'''apikey''',
|
||||||
|
'''api\-key''',
|
||||||
|
]
|
||||||
|
paths = [
|
||||||
|
'''gitleaks.toml''',
|
||||||
|
'''(.*?)(jpg|gif|doc|pdf|bin|svg|socket)$''',
|
||||||
|
'''(go.mod|go.sum)$'''
|
||||||
|
]
|
||||||
+26
-39
@@ -2,50 +2,37 @@ package config
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Rules contain information that define details on how to detect secrets
|
||||||
type Rule struct {
|
type Rule struct {
|
||||||
Description string
|
// Description is the description of the rule.
|
||||||
RuleID string
|
Description string
|
||||||
Entropy float64
|
|
||||||
EntropyReGroup int
|
|
||||||
Regex *regexp.Regexp
|
|
||||||
Path *regexp.Regexp
|
|
||||||
Tags []string
|
|
||||||
Allowlist Allowlist
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Rule) IncludeEntropy(secret string) (bool, float64) {
|
// RuleID is a unique identifier for this rule
|
||||||
groups := r.Regex.FindStringSubmatch(secret)
|
RuleID string
|
||||||
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
|
// Entropy is a float representing the minimum shannon
|
||||||
// does not support positive lookaheads. Ideally we would want to add a
|
// entropy a regex group must have to be considered a secret.
|
||||||
// restriction on generic rules regex that requires the secret match group
|
Entropy float64
|
||||||
// contains both numbers and alphabetical characters. What this bit of code does is
|
|
||||||
// check if the ruleid is prepended with "generic" and enforces the
|
|
||||||
// secret contains both digits and alphabetical characters.
|
|
||||||
if strings.HasPrefix(r.RuleID, "generic") {
|
|
||||||
if !containsDigit(groups[r.EntropyReGroup]) {
|
|
||||||
return false, 0.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// group = 0 will check the entropy of the whole regex match
|
|
||||||
e := shannonEntropy(groups[r.EntropyReGroup])
|
|
||||||
if e > r.Entropy {
|
|
||||||
return true, e
|
|
||||||
}
|
|
||||||
|
|
||||||
return false, e
|
// SecretGroup is an int used to extract secret from regex
|
||||||
}
|
// match and used as the group that will have its entropy
|
||||||
|
// checked if `entropy` is set.
|
||||||
|
SecretGroup int
|
||||||
|
|
||||||
func (r *Rule) EntropySet() bool {
|
// Regex is a golang regular expression used to detect secrets.
|
||||||
if r.Entropy == 0.0 {
|
Regex *regexp.Regexp
|
||||||
return false
|
|
||||||
}
|
// Path is a golang regular expression used to
|
||||||
return true
|
// filter secrets by path
|
||||||
|
Path *regexp.Regexp
|
||||||
|
|
||||||
|
// Tags is an array of strings used for metadata
|
||||||
|
// and reporting purposes.
|
||||||
|
Tags []string
|
||||||
|
|
||||||
|
// Allowlist allows a rule to be ignored for specific
|
||||||
|
// regexes, paths, and/or commits
|
||||||
|
Allowlist Allowlist
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"math"
|
|
||||||
"regexp"
|
"regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -23,38 +22,3 @@ func regexMatched(f string, re *regexp.Regexp) bool {
|
|||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func containsDigit(s string) bool {
|
|
||||||
for _, c := range s {
|
|
||||||
switch c {
|
|
||||||
case '1', '2', '3', '4', '5', '6', '7', '8', '9':
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// shannonEntropy calculates the entropy of data using the formula defined here:
|
|
||||||
// https://en.wiktionary.org/wiki/Shannon_entropy
|
|
||||||
// Another way to think about what this is doing is calculating the number of bits
|
|
||||||
// needed to on average encode the data. So, the higher the entropy, the more random the data, the
|
|
||||||
// more bits needed to encode that data.
|
|
||||||
func shannonEntropy(data string) (entropy float64) {
|
|
||||||
if data == "" {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
charCounts := make(map[rune]int)
|
|
||||||
for _, char := range data {
|
|
||||||
charCounts[char]++
|
|
||||||
}
|
|
||||||
|
|
||||||
invLength := 1.0 / float64(len(data))
|
|
||||||
for _, count := range charCounts {
|
|
||||||
freq := float64(count) * invLength
|
|
||||||
entropy -= freq * math.Log2(freq)
|
|
||||||
}
|
|
||||||
|
|
||||||
return entropy
|
|
||||||
}
|
|
||||||
+349
-75
@@ -1,105 +1,379 @@
|
|||||||
package detect
|
package detect
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/detect/git"
|
||||||
"github.com/zricethezav/gitleaks/v8/report"
|
"github.com/zricethezav/gitleaks/v8/report"
|
||||||
|
|
||||||
|
"github.com/fatih/semgroup"
|
||||||
|
"github.com/gitleaks/go-gitdiff/gitdiff"
|
||||||
|
"github.com/rs/zerolog/log"
|
||||||
|
"github.com/spf13/viper"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Options struct {
|
// Type used to differentiate between git scan types:
|
||||||
|
// $ gitleaks detect
|
||||||
|
// $ gitleaks protect
|
||||||
|
// $ gitleaks protect staged
|
||||||
|
type GitScanType int
|
||||||
|
|
||||||
|
const (
|
||||||
|
DetectType GitScanType = iota
|
||||||
|
ProtectType
|
||||||
|
ProtectStagedType
|
||||||
|
|
||||||
|
gitleaksAllowSignature = "gitleaks:allow"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Detector is the main detector struct
|
||||||
|
type Detector struct {
|
||||||
|
// Config is the configuration for the detector
|
||||||
|
Config config.Config
|
||||||
|
|
||||||
|
// Redact is a flag to redact findings. This is exported
|
||||||
|
// so users using gitleaks as a library can set this flag
|
||||||
|
// without calling `detector.Start(cmd *cobra.Command)`
|
||||||
|
Redact bool
|
||||||
|
|
||||||
|
// verbose is a flag to print findings
|
||||||
Verbose bool
|
Verbose bool
|
||||||
Redact bool
|
|
||||||
|
// commitMap is used to keep track of commits that have been scanned.
|
||||||
|
// This is only used for logging purposes and git scans.
|
||||||
|
commitMap map[string]bool
|
||||||
|
|
||||||
|
// findingMutex is to prevent concurrent access to the
|
||||||
|
// findings slice when adding findings.
|
||||||
|
findingMutex *sync.Mutex
|
||||||
|
|
||||||
|
// findings is a slice of report.Findings. This is the result
|
||||||
|
// of the detector's scan which can then be used to generate a
|
||||||
|
// report.
|
||||||
|
findings []report.Finding
|
||||||
}
|
}
|
||||||
|
|
||||||
func DetectFindings(cfg config.Config, b []byte, filePath string, commit string) []report.Finding {
|
// Fragment contains the data to be scanned
|
||||||
var findings []report.Finding
|
type Fragment struct {
|
||||||
linePairs := regexp.MustCompile("\n").FindAllIndex(b, -1)
|
// Raw is the raw content of the fragment
|
||||||
|
Raw string
|
||||||
|
|
||||||
// check if we should skip file based on the global allowlist
|
// FilePath is the path to the file if applicable
|
||||||
if cfg.Allowlist.PathAllowed(filePath) {
|
FilePath string
|
||||||
|
|
||||||
|
// CommitSHA is the SHA of the commit if applicable
|
||||||
|
CommitSHA string
|
||||||
|
|
||||||
|
// newlineIndices is a list of indices of newlines in the raw content.
|
||||||
|
// This is used to calculate the line location of a finding
|
||||||
|
newlineIndices [][]int
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewDetector creates a new detector with the given config
|
||||||
|
func NewDetector(cfg config.Config) *Detector {
|
||||||
|
return &Detector{
|
||||||
|
commitMap: make(map[string]bool),
|
||||||
|
findingMutex: &sync.Mutex{},
|
||||||
|
findings: make([]report.Finding, 0),
|
||||||
|
Config: cfg,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewDetectorDefaultConfig creates a new detector with the default config
|
||||||
|
func NewDetectorDefaultConfig() (*Detector, error) {
|
||||||
|
viper.SetConfigType("toml")
|
||||||
|
err := viper.ReadConfig(strings.NewReader(config.DefaultConfig))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var vc config.ViperConfig
|
||||||
|
err = viper.Unmarshal(&vc)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
cfg, err := vc.Translate()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return NewDetector(cfg), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DetectBytes scans the given bytes and returns a list of findings
|
||||||
|
func (d *Detector) DetectBytes(content []byte) []report.Finding {
|
||||||
|
return d.DetectString(string(content))
|
||||||
|
}
|
||||||
|
|
||||||
|
// DetectString scans the given string and returns a list of findings
|
||||||
|
func (d *Detector) DetectString(content string) []report.Finding {
|
||||||
|
return d.Detect(Fragment{
|
||||||
|
Raw: content,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// detectRule scans the given fragment for the given rule and returns a list of findings
|
||||||
|
func (d *Detector) detectRule(fragment Fragment, rule *config.Rule) []report.Finding {
|
||||||
|
var findings []report.Finding
|
||||||
|
|
||||||
|
// check if filepath or commit is allowed for this rule
|
||||||
|
if rule.Allowlist.CommitAllowed(fragment.CommitSHA) ||
|
||||||
|
rule.Allowlist.PathAllowed(fragment.FilePath) {
|
||||||
return findings
|
return findings
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, r := range cfg.Rules {
|
if rule.Path != nil && rule.Regex == nil {
|
||||||
pathSkip := false
|
// Path _only_ rule
|
||||||
if r.Allowlist.CommitAllowed(commit) {
|
if rule.Path.Match([]byte(fragment.FilePath)) {
|
||||||
continue
|
finding := report.Finding{
|
||||||
}
|
Description: rule.Description,
|
||||||
if r.Allowlist.PathAllowed(filePath) {
|
File: fragment.FilePath,
|
||||||
continue
|
RuleID: rule.RuleID,
|
||||||
}
|
Match: fmt.Sprintf("file detected: %s", fragment.FilePath),
|
||||||
|
Tags: rule.Tags,
|
||||||
// Check if path should be considered
|
|
||||||
if r.Path != nil {
|
|
||||||
if r.Path.Match([]byte(filePath)) {
|
|
||||||
if r.Regex == nil {
|
|
||||||
// This is a path only rule
|
|
||||||
f := report.Finding{
|
|
||||||
Description: r.Description,
|
|
||||||
File: filePath,
|
|
||||||
RuleID: r.RuleID,
|
|
||||||
Context: fmt.Sprintf("file detected: %s", filePath),
|
|
||||||
Tags: r.Tags,
|
|
||||||
}
|
|
||||||
findings = append(findings, f)
|
|
||||||
pathSkip = true
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
pathSkip = true
|
|
||||||
}
|
}
|
||||||
|
return append(findings, finding)
|
||||||
}
|
}
|
||||||
if pathSkip {
|
} else if rule.Path != nil {
|
||||||
continue
|
// if path is set _and_ a regex is set, then we need to check both
|
||||||
}
|
// so if the path does not match, then we should return early and not
|
||||||
|
// consider the regex
|
||||||
matchIndices := r.Regex.FindAllIndex(b, -1)
|
if !rule.Path.Match([]byte(fragment.FilePath)) {
|
||||||
for _, m := range matchIndices {
|
return findings
|
||||||
location := getLocation(linePairs, m[0], m[1])
|
|
||||||
f := report.Finding{
|
|
||||||
Description: r.Description,
|
|
||||||
File: filePath,
|
|
||||||
RuleID: r.RuleID,
|
|
||||||
StartLine: location.startLine,
|
|
||||||
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")),
|
|
||||||
Tags: r.Tags,
|
|
||||||
}
|
|
||||||
|
|
||||||
if r.Allowlist.RegexAllowed(f.Secret) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if r.EntropySet() {
|
|
||||||
include, entropy := r.IncludeEntropy(strings.Trim(string(b[m[0]:m[1]]), "\n"))
|
|
||||||
if include {
|
|
||||||
f.Entropy = float32(entropy)
|
|
||||||
findings = append(findings, f)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
findings = append(findings, f)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
matchIndices := rule.Regex.FindAllStringIndex(fragment.Raw, -1)
|
||||||
|
for _, matchIndex := range matchIndices {
|
||||||
|
// extract secret from match
|
||||||
|
secret := strings.Trim(fragment.Raw[matchIndex[0]:matchIndex[1]], "\n")
|
||||||
|
|
||||||
|
// determine location of match. Note that the location
|
||||||
|
// in the finding will be the line/column numbers of the _match_
|
||||||
|
// not the _secret_, which will be different if the secretGroup
|
||||||
|
// value is set for this rule
|
||||||
|
loc := location(fragment, matchIndex)
|
||||||
|
|
||||||
|
finding := report.Finding{
|
||||||
|
Description: rule.Description,
|
||||||
|
File: fragment.FilePath,
|
||||||
|
RuleID: rule.RuleID,
|
||||||
|
StartLine: loc.startLine,
|
||||||
|
EndLine: loc.endLine,
|
||||||
|
StartColumn: loc.startColumn,
|
||||||
|
EndColumn: loc.endColumn,
|
||||||
|
Secret: secret,
|
||||||
|
Match: secret,
|
||||||
|
Tags: rule.Tags,
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.Contains(fragment.Raw[loc.startLineIndex:loc.endLineIndex],
|
||||||
|
gitleaksAllowSignature) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// extract secret from secret group if set
|
||||||
|
if rule.SecretGroup != 0 {
|
||||||
|
groups := rule.Regex.FindStringSubmatch(secret)
|
||||||
|
if len(groups) <= rule.SecretGroup || len(groups) == 0 {
|
||||||
|
// Config validation should prevent this
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
secret = groups[rule.SecretGroup]
|
||||||
|
finding.Secret = secret
|
||||||
|
}
|
||||||
|
|
||||||
|
// check if the secret is in the allowlist
|
||||||
|
if rule.Allowlist.RegexAllowed(finding.Secret) ||
|
||||||
|
d.Config.Allowlist.RegexAllowed(finding.Secret) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// check entropy
|
||||||
|
entropy := shannonEntropy(finding.Secret)
|
||||||
|
finding.Entropy = float32(entropy)
|
||||||
|
if rule.Entropy != 0.0 {
|
||||||
|
if entropy <= rule.Entropy {
|
||||||
|
// entropy is too low, skip this finding
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// NOTE: this is a goofy hack to get around the fact there golang's regex engine
|
||||||
|
// does not support positive lookaheads. Ideally we would want to add a
|
||||||
|
// restriction on generic rules regex that requires the secret match group
|
||||||
|
// contains both numbers and alphabetical characters, not just alphabetical characters.
|
||||||
|
// What this bit of code does is check if the ruleid is prepended with "generic" and enforces the
|
||||||
|
// secret contains both digits and alphabetical characters.
|
||||||
|
// TODO: this should be replaced with stop words
|
||||||
|
if strings.HasPrefix(rule.RuleID, "generic") {
|
||||||
|
if !containsDigit(secret) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
findings = append(findings, finding)
|
||||||
|
}
|
||||||
return findings
|
return findings
|
||||||
}
|
}
|
||||||
|
|
||||||
func limit(s string) string {
|
// GitScan accepts a *gitdiff.File channel which contents a git history generated from
|
||||||
if len(s) > 500 {
|
// the output of `git log -p ...`. startGitScan will look at each file (patch) in the history
|
||||||
return s[:500] + "..."
|
// and determine if the patch contains any findings.
|
||||||
|
func (d *Detector) DetectGit(source string, logOpts string, gitScanType GitScanType) ([]report.Finding, error) {
|
||||||
|
var (
|
||||||
|
gitdiffFiles <-chan *gitdiff.File
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
switch gitScanType {
|
||||||
|
case DetectType:
|
||||||
|
gitdiffFiles, err = git.GitLog(source, logOpts)
|
||||||
|
if err != nil {
|
||||||
|
return d.findings, err
|
||||||
|
}
|
||||||
|
case ProtectType:
|
||||||
|
gitdiffFiles, err = git.GitDiff(source, false)
|
||||||
|
if err != nil {
|
||||||
|
return d.findings, err
|
||||||
|
}
|
||||||
|
case ProtectStagedType:
|
||||||
|
gitdiffFiles, err = git.GitDiff(source, true)
|
||||||
|
if err != nil {
|
||||||
|
return d.findings, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return s
|
|
||||||
|
s := semgroup.NewGroup(context.Background(), 4)
|
||||||
|
|
||||||
|
for gitdiffFile := range gitdiffFiles {
|
||||||
|
gitdiffFile := gitdiffFile
|
||||||
|
|
||||||
|
// skip binary files
|
||||||
|
if gitdiffFile.IsBinary || gitdiffFile.IsDelete {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if commit is allowed
|
||||||
|
commitSHA := ""
|
||||||
|
if gitdiffFile.PatchHeader != nil {
|
||||||
|
commitSHA = gitdiffFile.PatchHeader.SHA
|
||||||
|
if d.Config.Allowlist.CommitAllowed(gitdiffFile.PatchHeader.SHA) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
d.addCommit(commitSHA)
|
||||||
|
|
||||||
|
s.Go(func() error {
|
||||||
|
for _, textFragment := range gitdiffFile.TextFragments {
|
||||||
|
if textFragment == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
fragment := Fragment{
|
||||||
|
Raw: textFragment.Raw(gitdiff.OpAdd),
|
||||||
|
CommitSHA: commitSHA,
|
||||||
|
FilePath: gitdiffFile.NewName,
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, finding := range d.Detect(fragment) {
|
||||||
|
d.addFinding(augmentGitFinding(finding, textFragment, gitdiffFile))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.Wait(); err != nil {
|
||||||
|
return d.findings, err
|
||||||
|
}
|
||||||
|
log.Debug().Msgf("%d commits scanned. Note: this number might be smaller than expected due to commits with no additions", len(d.commitMap))
|
||||||
|
return d.findings, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func printFinding(f report.Finding) {
|
// DetectFiles accepts a path to a source directory or file and begins a scan of the
|
||||||
var b []byte
|
// file or directory.
|
||||||
b, _ = json.MarshalIndent(f, "", " ")
|
func (d *Detector) DetectFiles(source string) ([]report.Finding, error) {
|
||||||
fmt.Println(string(b))
|
s := semgroup.NewGroup(context.Background(), 4)
|
||||||
|
paths := make(chan string)
|
||||||
|
s.Go(func() error {
|
||||||
|
defer close(paths)
|
||||||
|
return filepath.Walk(source,
|
||||||
|
func(path string, fInfo os.FileInfo, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if fInfo.Name() == ".git" {
|
||||||
|
return filepath.SkipDir
|
||||||
|
}
|
||||||
|
if fInfo.Mode().IsRegular() {
|
||||||
|
paths <- path
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
})
|
||||||
|
for pa := range paths {
|
||||||
|
p := pa
|
||||||
|
s.Go(func() error {
|
||||||
|
b, err := os.ReadFile(p)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fragment := Fragment{
|
||||||
|
Raw: string(b),
|
||||||
|
FilePath: p,
|
||||||
|
}
|
||||||
|
for _, finding := range d.Detect(fragment) {
|
||||||
|
// need to add 1 since line counting starts at 1
|
||||||
|
finding.EndLine++
|
||||||
|
finding.StartLine++
|
||||||
|
d.addFinding(finding)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.Wait(); err != nil {
|
||||||
|
return d.findings, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return d.findings, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Detect scans the given fragment and returns a list of findings
|
||||||
|
func (d *Detector) Detect(fragment Fragment) []report.Finding {
|
||||||
|
var findings []report.Finding
|
||||||
|
|
||||||
|
// check if filepath is allowed
|
||||||
|
if d.Config.Allowlist.PathAllowed(fragment.FilePath) ||
|
||||||
|
fragment.FilePath == d.Config.Path {
|
||||||
|
return findings
|
||||||
|
}
|
||||||
|
|
||||||
|
// add newline indices for location calculation in detectRule
|
||||||
|
fragment.newlineIndices = regexp.MustCompile("\n").FindAllStringIndex(fragment.Raw, -1)
|
||||||
|
|
||||||
|
for _, rule := range d.Config.Rules {
|
||||||
|
findings = append(findings, d.detectRule(fragment, rule)...)
|
||||||
|
}
|
||||||
|
return filter(findings, d.Redact)
|
||||||
|
}
|
||||||
|
|
||||||
|
// addFinding synchronously adds a finding to the findings slice
|
||||||
|
func (d *Detector) addFinding(finding report.Finding) {
|
||||||
|
d.findingMutex.Lock()
|
||||||
|
d.findings = append(d.findings, finding)
|
||||||
|
if d.Verbose {
|
||||||
|
printFinding(finding)
|
||||||
|
}
|
||||||
|
d.findingMutex.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
// addCommit synchronously adds a commit to the commit slice
|
||||||
|
func (d *Detector) addCommit(commit string) {
|
||||||
|
d.commitMap[commit] = true
|
||||||
}
|
}
|
||||||
+393
-41
@@ -2,6 +2,8 @@ package detect
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/spf13/viper"
|
"github.com/spf13/viper"
|
||||||
@@ -11,93 +13,194 @@ import (
|
|||||||
"github.com/zricethezav/gitleaks/v8/report"
|
"github.com/zricethezav/gitleaks/v8/report"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestDetectFindings(t *testing.T) {
|
const configPath = "../testdata/config/"
|
||||||
|
const repoBasePath = "../testdata/repos/"
|
||||||
|
|
||||||
|
func TestDetect(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
cfgName string
|
cfgName string
|
||||||
opts Options
|
fragment Fragment
|
||||||
filePath string
|
|
||||||
bytes []byte
|
|
||||||
commit string
|
|
||||||
expectedFindings []report.Finding
|
expectedFindings []report.Finding
|
||||||
wantError error
|
wantError error
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
cfgName: "simple",
|
cfgName: "simple",
|
||||||
bytes: []byte(`awsToken := \"AKIALALEMEL33243OLIA\"`),
|
fragment: Fragment{
|
||||||
filePath: "tmp.go",
|
Raw: `awsToken := \"AKIALALEMEL33243OKIA\ // gitleaks:allow"`,
|
||||||
|
FilePath: "tmp.go",
|
||||||
|
},
|
||||||
|
expectedFindings: []report.Finding{},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "simple",
|
||||||
|
fragment: Fragment{
|
||||||
|
Raw: `awsToken := \
|
||||||
|
|
||||||
|
\"AKIALALEMEL33243OKIA\ // gitleaks:allow"
|
||||||
|
|
||||||
|
|
||||||
|
`,
|
||||||
|
FilePath: "tmp.go",
|
||||||
|
},
|
||||||
|
expectedFindings: []report.Finding{},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "simple",
|
||||||
|
fragment: Fragment{
|
||||||
|
Raw: `awsToken := \"AKIALALEMEL33243OKIA\"
|
||||||
|
|
||||||
|
// gitleaks:allow"
|
||||||
|
|
||||||
|
`,
|
||||||
|
FilePath: "tmp.go",
|
||||||
|
},
|
||||||
|
expectedFindings: []report.Finding{
|
||||||
|
{
|
||||||
|
Description: "AWS Access Key",
|
||||||
|
Secret: "AKIALALEMEL33243OKIA",
|
||||||
|
Match: "AKIALALEMEL33243OKIA",
|
||||||
|
File: "tmp.go",
|
||||||
|
RuleID: "aws-access-key",
|
||||||
|
Tags: []string{"key", "AWS"},
|
||||||
|
StartLine: 0,
|
||||||
|
EndLine: 0,
|
||||||
|
StartColumn: 15,
|
||||||
|
EndColumn: 34,
|
||||||
|
Entropy: 3.1464393,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "escaped_character_group",
|
||||||
|
fragment: Fragment{
|
||||||
|
Raw: `pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB`,
|
||||||
|
FilePath: "tmp.go",
|
||||||
|
},
|
||||||
|
expectedFindings: []report.Finding{
|
||||||
|
{
|
||||||
|
Description: "PyPI upload token",
|
||||||
|
Secret: "pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB",
|
||||||
|
Match: "pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB",
|
||||||
|
File: "tmp.go",
|
||||||
|
RuleID: "pypi-upload-token",
|
||||||
|
Tags: []string{"key", "pypi"},
|
||||||
|
StartLine: 0,
|
||||||
|
EndLine: 0,
|
||||||
|
StartColumn: 1,
|
||||||
|
EndColumn: 86,
|
||||||
|
Entropy: 1.9606875,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "simple",
|
||||||
|
fragment: Fragment{
|
||||||
|
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
|
||||||
|
FilePath: "tmp.go",
|
||||||
|
},
|
||||||
expectedFindings: []report.Finding{
|
expectedFindings: []report.Finding{
|
||||||
{
|
{
|
||||||
Description: "AWS Access Key",
|
Description: "AWS Access Key",
|
||||||
Secret: "AKIALALEMEL33243OLIA",
|
Secret: "AKIALALEMEL33243OLIA",
|
||||||
|
Match: "AKIALALEMEL33243OLIA",
|
||||||
File: "tmp.go",
|
File: "tmp.go",
|
||||||
RuleID: "aws-access-key",
|
RuleID: "aws-access-key",
|
||||||
Tags: []string{"key", "AWS"},
|
Tags: []string{"key", "AWS"},
|
||||||
|
StartLine: 0,
|
||||||
|
EndLine: 0,
|
||||||
|
StartColumn: 15,
|
||||||
|
EndColumn: 34,
|
||||||
|
Entropy: 3.0841837,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
cfgName: "allow_aws_re",
|
cfgName: "allow_aws_re",
|
||||||
bytes: []byte(`awsToken := \"AKIALALEMEL33243OLIA\"`),
|
fragment: Fragment{
|
||||||
filePath: "tmp.go",
|
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
|
||||||
|
FilePath: "tmp.go",
|
||||||
|
},
|
||||||
expectedFindings: []report.Finding{},
|
expectedFindings: []report.Finding{},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
cfgName: "allow_path",
|
cfgName: "allow_path",
|
||||||
bytes: []byte(`awsToken := \"AKIALALEMEL33243OLIA\"`),
|
fragment: Fragment{
|
||||||
filePath: "tmp.go",
|
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
|
||||||
|
FilePath: "tmp.go",
|
||||||
|
},
|
||||||
expectedFindings: []report.Finding{},
|
expectedFindings: []report.Finding{},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
cfgName: "allow_commit",
|
cfgName: "allow_commit",
|
||||||
bytes: []byte(`awsToken := \"AKIALALEMEL33243OLIA\"`),
|
fragment: Fragment{
|
||||||
filePath: "tmp.go",
|
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
|
||||||
|
FilePath: "tmp.go",
|
||||||
|
CommitSHA: "allowthiscommit",
|
||||||
|
},
|
||||||
expectedFindings: []report.Finding{},
|
expectedFindings: []report.Finding{},
|
||||||
commit: "allowthiscommit",
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
cfgName: "entropy_group",
|
cfgName: "entropy_group",
|
||||||
bytes: []byte(`const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`),
|
fragment: Fragment{
|
||||||
filePath: "tmp.go",
|
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
|
||||||
|
FilePath: "tmp.go",
|
||||||
|
},
|
||||||
expectedFindings: []report.Finding{
|
expectedFindings: []report.Finding{
|
||||||
{
|
{
|
||||||
Description: "Discord API key",
|
Description: "Discord API key",
|
||||||
Secret: "Discord_Public_Key = \"e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5\"",
|
Match: "Discord_Public_Key = \"e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5\"",
|
||||||
|
Secret: "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5",
|
||||||
File: "tmp.go",
|
File: "tmp.go",
|
||||||
RuleID: "discord-api-key",
|
RuleID: "discord-api-key",
|
||||||
Tags: []string{},
|
Tags: []string{},
|
||||||
Entropy: 3.7906237,
|
Entropy: 3.7906237,
|
||||||
|
StartLine: 0,
|
||||||
|
EndLine: 0,
|
||||||
|
StartColumn: 7,
|
||||||
|
EndColumn: 93,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
cfgName: "generic_with_py_path",
|
cfgName: "generic_with_py_path",
|
||||||
bytes: []byte(`const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`),
|
fragment: Fragment{
|
||||||
filePath: "tmp.go",
|
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
|
||||||
|
FilePath: "tmp.go",
|
||||||
|
},
|
||||||
expectedFindings: []report.Finding{},
|
expectedFindings: []report.Finding{},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
cfgName: "generic_with_py_path",
|
cfgName: "generic_with_py_path",
|
||||||
bytes: []byte(`const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`),
|
fragment: Fragment{
|
||||||
filePath: "tmp.py",
|
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
|
||||||
|
FilePath: "tmp.py",
|
||||||
|
},
|
||||||
expectedFindings: []report.Finding{
|
expectedFindings: []report.Finding{
|
||||||
{
|
{
|
||||||
Description: "Generic API Key",
|
Description: "Generic API Key",
|
||||||
Secret: "Key = \"e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5\"",
|
Match: "Key = \"e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5\"",
|
||||||
|
Secret: "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5",
|
||||||
File: "tmp.py",
|
File: "tmp.py",
|
||||||
RuleID: "generic-api-key",
|
RuleID: "generic-api-key",
|
||||||
Tags: []string{},
|
Tags: []string{},
|
||||||
Entropy: 3.7906237,
|
Entropy: 3.7906237,
|
||||||
|
StartLine: 0,
|
||||||
|
EndLine: 0,
|
||||||
|
StartColumn: 22,
|
||||||
|
EndColumn: 93,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
cfgName: "path_only",
|
cfgName: "path_only",
|
||||||
bytes: []byte(`const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`),
|
fragment: Fragment{
|
||||||
filePath: "tmp.py",
|
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
|
||||||
|
FilePath: "tmp.py",
|
||||||
|
},
|
||||||
expectedFindings: []report.Finding{
|
expectedFindings: []report.Finding{
|
||||||
{
|
{
|
||||||
Description: "Python Files",
|
Description: "Python Files",
|
||||||
Context: "file detected: tmp.py",
|
Match: "file detected: tmp.py",
|
||||||
File: "tmp.py",
|
File: "tmp.py",
|
||||||
RuleID: "python-files-only",
|
RuleID: "python-files-only",
|
||||||
Tags: []string{},
|
Tags: []string{},
|
||||||
@@ -105,11 +208,37 @@ func TestDetectFindings(t *testing.T) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
cfgName: "bad_entropy_group",
|
cfgName: "bad_entropy_group",
|
||||||
bytes: []byte(`const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`),
|
fragment: Fragment{
|
||||||
filePath: "tmp.go",
|
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
|
||||||
|
FilePath: "tmp.go",
|
||||||
|
},
|
||||||
|
expectedFindings: []report.Finding{},
|
||||||
|
wantError: fmt.Errorf("Discord API key invalid regex secret group 5, max regex secret group 3"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "simple",
|
||||||
|
fragment: Fragment{
|
||||||
|
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
|
||||||
|
FilePath: filepath.Join(configPath, "simple.toml"),
|
||||||
|
},
|
||||||
|
expectedFindings: []report.Finding{},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "allow_global_aws_re",
|
||||||
|
fragment: Fragment{
|
||||||
|
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
|
||||||
|
FilePath: "tmp.go",
|
||||||
|
},
|
||||||
|
expectedFindings: []report.Finding{},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "generic_with_py_path",
|
||||||
|
fragment: Fragment{
|
||||||
|
Raw: `const Discord_Public_Key = "load2523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
|
||||||
|
FilePath: "tmp.py",
|
||||||
|
},
|
||||||
expectedFindings: []report.Finding{},
|
expectedFindings: []report.Finding{},
|
||||||
wantError: fmt.Errorf("Discord API key invalid regex entropy group 5, max regex entropy group 3"),
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -124,20 +253,243 @@ func TestDetectFindings(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var vc config.ViperConfig
|
var vc config.ViperConfig
|
||||||
viper.Unmarshal(&vc)
|
err = viper.Unmarshal(&vc)
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
cfg, err := vc.Translate()
|
cfg, err := vc.Translate()
|
||||||
|
cfg.Path = filepath.Join(configPath, tt.cfgName+".toml")
|
||||||
if tt.wantError != nil {
|
if tt.wantError != nil {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Errorf("expected error")
|
t.Errorf("expected error")
|
||||||
}
|
}
|
||||||
assert.Equal(t, tt.wantError, err)
|
assert.Equal(t, tt.wantError, err)
|
||||||
}
|
}
|
||||||
|
d := NewDetector(cfg)
|
||||||
|
|
||||||
|
findings := d.Detect(tt.fragment)
|
||||||
|
assert.ElementsMatch(t, tt.expectedFindings, findings)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestFromGit tests the FromGit function
|
||||||
|
func TestFromGit(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
cfgName string
|
||||||
|
source string
|
||||||
|
logOpts string
|
||||||
|
expectedFindings []report.Finding
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
source: filepath.Join(repoBasePath, "small"),
|
||||||
|
cfgName: "simple",
|
||||||
|
expectedFindings: []report.Finding{
|
||||||
|
{
|
||||||
|
Description: "AWS Access Key",
|
||||||
|
StartLine: 20,
|
||||||
|
EndLine: 20,
|
||||||
|
StartColumn: 19,
|
||||||
|
EndColumn: 38,
|
||||||
|
Secret: "AKIALALEMEL33243OLIA",
|
||||||
|
Match: "AKIALALEMEL33243OLIA",
|
||||||
|
File: "main.go",
|
||||||
|
Date: "2021-11-02T23:37:53Z",
|
||||||
|
Commit: "1b6da43b82b22e4eaa10bcf8ee591e91abbfc587",
|
||||||
|
Author: "Zachary Rice",
|
||||||
|
Email: "zricer@protonmail.com",
|
||||||
|
Message: "Accidentally add a secret",
|
||||||
|
RuleID: "aws-access-key",
|
||||||
|
Tags: []string{"key", "AWS"},
|
||||||
|
Entropy: 3.0841837,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Description: "AWS Access Key",
|
||||||
|
StartLine: 9,
|
||||||
|
EndLine: 9,
|
||||||
|
StartColumn: 17,
|
||||||
|
EndColumn: 36,
|
||||||
|
Secret: "AKIALALEMEL33243OLIA",
|
||||||
|
Match: "AKIALALEMEL33243OLIA",
|
||||||
|
File: "foo/foo.go",
|
||||||
|
Date: "2021-11-02T23:48:06Z",
|
||||||
|
Commit: "491504d5a31946ce75e22554cc34203d8e5ff3ca",
|
||||||
|
Author: "Zach Rice",
|
||||||
|
Email: "zricer@protonmail.com",
|
||||||
|
Message: "adding foo package with secret",
|
||||||
|
RuleID: "aws-access-key",
|
||||||
|
Tags: []string{"key", "AWS"},
|
||||||
|
Entropy: 3.0841837,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
source: filepath.Join(repoBasePath, "small"),
|
||||||
|
logOpts: "--all foo...",
|
||||||
|
cfgName: "simple",
|
||||||
|
expectedFindings: []report.Finding{
|
||||||
|
{
|
||||||
|
Description: "AWS Access Key",
|
||||||
|
StartLine: 9,
|
||||||
|
EndLine: 9,
|
||||||
|
StartColumn: 17,
|
||||||
|
EndColumn: 36,
|
||||||
|
Secret: "AKIALALEMEL33243OLIA",
|
||||||
|
Match: "AKIALALEMEL33243OLIA",
|
||||||
|
Date: "2021-11-02T23:48:06Z",
|
||||||
|
File: "foo/foo.go",
|
||||||
|
Commit: "491504d5a31946ce75e22554cc34203d8e5ff3ca",
|
||||||
|
Author: "Zach Rice",
|
||||||
|
Email: "zricer@protonmail.com",
|
||||||
|
Message: "adding foo package with secret",
|
||||||
|
RuleID: "aws-access-key",
|
||||||
|
Tags: []string{"key", "AWS"},
|
||||||
|
Entropy: 3.0841837,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
err := moveDotGit("dotGit", ".git")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
if err := moveDotGit(".git", "dotGit"); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
|
||||||
|
viper.AddConfigPath(configPath)
|
||||||
|
viper.SetConfigName("simple")
|
||||||
|
viper.SetConfigType("toml")
|
||||||
|
err = viper.ReadInConfig()
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var vc config.ViperConfig
|
||||||
|
err = viper.Unmarshal(&vc)
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
cfg, err := vc.Translate()
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
detector := NewDetector(cfg)
|
||||||
|
findings, err := detector.DetectGit(tt.source, tt.logOpts, DetectType)
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
|
||||||
findings := DetectFindings(cfg, tt.bytes, tt.filePath, tt.commit)
|
|
||||||
for _, f := range findings {
|
for _, f := range findings {
|
||||||
f.Context = "" // remove lines cause copying and pasting them has some wack formatting
|
f.Match = "" // remove lines cause copying and pasting them has some wack formatting
|
||||||
f.Date = ""
|
|
||||||
}
|
}
|
||||||
assert.ElementsMatch(t, tt.expectedFindings, findings)
|
assert.ElementsMatch(t, tt.expectedFindings, findings)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestFromGit tests the FromGit function
|
||||||
|
func TestFromFiles(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
cfgName string
|
||||||
|
source string
|
||||||
|
expectedFindings []report.Finding
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
source: filepath.Join(repoBasePath, "nogit"),
|
||||||
|
cfgName: "simple",
|
||||||
|
expectedFindings: []report.Finding{
|
||||||
|
{
|
||||||
|
Description: "AWS Access Key",
|
||||||
|
StartLine: 20,
|
||||||
|
EndLine: 20,
|
||||||
|
StartColumn: 16,
|
||||||
|
EndColumn: 35,
|
||||||
|
Match: "AKIALALEMEL33243OLIA",
|
||||||
|
Secret: "AKIALALEMEL33243OLIA",
|
||||||
|
File: "../testdata/repos/nogit/main.go",
|
||||||
|
RuleID: "aws-access-key",
|
||||||
|
Tags: []string{"key", "AWS"},
|
||||||
|
Entropy: 3.0841837,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
source: filepath.Join(repoBasePath, "nogit", "main.go"),
|
||||||
|
cfgName: "simple",
|
||||||
|
expectedFindings: []report.Finding{
|
||||||
|
{
|
||||||
|
Description: "AWS Access Key",
|
||||||
|
StartLine: 20,
|
||||||
|
EndLine: 20,
|
||||||
|
StartColumn: 16,
|
||||||
|
EndColumn: 35,
|
||||||
|
Match: "AKIALALEMEL33243OLIA",
|
||||||
|
Secret: "AKIALALEMEL33243OLIA",
|
||||||
|
File: "../testdata/repos/nogit/main.go",
|
||||||
|
RuleID: "aws-access-key",
|
||||||
|
Tags: []string{"key", "AWS"},
|
||||||
|
Entropy: 3.0841837,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
viper.AddConfigPath(configPath)
|
||||||
|
viper.SetConfigName("simple")
|
||||||
|
viper.SetConfigType("toml")
|
||||||
|
err := viper.ReadInConfig()
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var vc config.ViperConfig
|
||||||
|
err = viper.Unmarshal(&vc)
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
cfg, _ := vc.Translate()
|
||||||
|
detector := NewDetector(cfg)
|
||||||
|
findings, err := detector.DetectFiles(tt.source)
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.ElementsMatch(t, tt.expectedFindings, findings)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func moveDotGit(from, to string) error {
|
||||||
|
repoDirs, err := os.ReadDir("../testdata/repos")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, dir := range repoDirs {
|
||||||
|
if to == ".git" {
|
||||||
|
_, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), "dotGit"))
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
// dont want to delete the only copy of .git accidentally
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
os.RemoveAll(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), ".git"))
|
||||||
|
}
|
||||||
|
if !dir.IsDir() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
_, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from))
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
err = os.Rename(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from),
|
||||||
|
fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), to))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
package detect
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"golang.org/x/sync/errgroup"
|
|
||||||
godocutil "golang.org/x/tools/godoc/util"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
"github.com/zricethezav/gitleaks/v8/report"
|
|
||||||
)
|
|
||||||
|
|
||||||
// FromFiles opens the directory or file specified in source and checks each file against the rules
|
|
||||||
// from the configuration. If any secrets are found, they are added to the list of findings.
|
|
||||||
func FromFiles(source string, cfg config.Config, outputOptions Options) ([]*report.Finding, error) {
|
|
||||||
var (
|
|
||||||
findings []*report.Finding
|
|
||||||
mu sync.Mutex
|
|
||||||
)
|
|
||||||
g, _ := errgroup.WithContext(context.Background())
|
|
||||||
paths := make(chan string)
|
|
||||||
g.Go(func() error {
|
|
||||||
defer close(paths)
|
|
||||||
return filepath.Walk(source,
|
|
||||||
func(path string, fInfo os.FileInfo, err error) error {
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if fInfo.Name() == ".git" {
|
|
||||||
return filepath.SkipDir
|
|
||||||
}
|
|
||||||
if fInfo.Mode().IsRegular() {
|
|
||||||
paths <- path
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
})
|
|
||||||
for pa := range paths {
|
|
||||||
p := pa
|
|
||||||
g.Go(func() error {
|
|
||||||
b, err := os.ReadFile(p)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if !godocutil.IsText(b) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
fis := DetectFindings(cfg, b, p, "")
|
|
||||||
for _, fi := range fis {
|
|
||||||
fi.File = p
|
|
||||||
if outputOptions.Redact {
|
|
||||||
fi.Redact()
|
|
||||||
}
|
|
||||||
if outputOptions.Verbose {
|
|
||||||
printFinding(fi)
|
|
||||||
}
|
|
||||||
mu.Lock()
|
|
||||||
findings = append(findings, &fi)
|
|
||||||
mu.Unlock()
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := g.Wait(); err != nil {
|
|
||||||
return findings, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return findings, nil
|
|
||||||
}
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
package detect
|
|
||||||
|
|
||||||
import (
|
|
||||||
"path/filepath"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/spf13/viper"
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
"github.com/zricethezav/gitleaks/v8/report"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TestFromGit tests the FromGit function
|
|
||||||
func TestFromFiles(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
cfgName string
|
|
||||||
opts Options
|
|
||||||
source string
|
|
||||||
expectedFindings []*report.Finding
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
source: filepath.Join(repoBasePath, "nogit"),
|
|
||||||
cfgName: "simple",
|
|
||||||
expectedFindings: []*report.Finding{
|
|
||||||
{
|
|
||||||
Description: "AWS Access Key",
|
|
||||||
StartLine: 19,
|
|
||||||
EndLine: 19,
|
|
||||||
StartColumn: 16,
|
|
||||||
EndColumn: 35,
|
|
||||||
Context: "\tawsToken := \"AKIALALEMEL33243OLIA\"",
|
|
||||||
Secret: "AKIALALEMEL33243OLIA",
|
|
||||||
File: "../testdata/repos/nogit/main.go",
|
|
||||||
RuleID: "aws-access-key",
|
|
||||||
Tags: []string{"key", "AWS"},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
source: filepath.Join(repoBasePath, "nogit", "main.go"),
|
|
||||||
cfgName: "simple",
|
|
||||||
expectedFindings: []*report.Finding{
|
|
||||||
{
|
|
||||||
Description: "AWS Access Key",
|
|
||||||
StartLine: 19,
|
|
||||||
EndLine: 19,
|
|
||||||
StartColumn: 16,
|
|
||||||
EndColumn: 35,
|
|
||||||
Context: "\tawsToken := \"AKIALALEMEL33243OLIA\"",
|
|
||||||
Secret: "AKIALALEMEL33243OLIA",
|
|
||||||
File: "../testdata/repos/nogit/main.go",
|
|
||||||
RuleID: "aws-access-key",
|
|
||||||
Tags: []string{"key", "AWS"},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
viper.AddConfigPath(configPath)
|
|
||||||
viper.SetConfigName("simple")
|
|
||||||
viper.SetConfigType("toml")
|
|
||||||
err := viper.ReadInConfig()
|
|
||||||
if err != nil {
|
|
||||||
t.Error(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var vc config.ViperConfig
|
|
||||||
viper.Unmarshal(&vc)
|
|
||||||
cfg, _ := vc.Translate()
|
|
||||||
|
|
||||||
findings, err := FromFiles(tt.source, cfg, tt.opts)
|
|
||||||
if err != nil {
|
|
||||||
t.Error(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
assert.ElementsMatch(t, tt.expectedFindings, findings)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,89 +0,0 @@
|
|||||||
package detect
|
|
||||||
|
|
||||||
import (
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/gitleaks/go-gitdiff/gitdiff"
|
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
"github.com/zricethezav/gitleaks/v8/report"
|
|
||||||
godocutil "golang.org/x/tools/godoc/util"
|
|
||||||
)
|
|
||||||
|
|
||||||
// FromGit accepts a gitdiff.File channel (structure output from `git log -p`) and a configuration
|
|
||||||
// struct. Files from the gitdiff.File channel are then checked against each rule in the configuration to
|
|
||||||
// check for secrets. If any secrets are found, they are added to the list of findings.
|
|
||||||
func FromGit(files <-chan *gitdiff.File, cfg config.Config, outputOptions Options) []*report.Finding {
|
|
||||||
var findings []*report.Finding
|
|
||||||
mu := sync.Mutex{}
|
|
||||||
wg := sync.WaitGroup{}
|
|
||||||
for f := range files {
|
|
||||||
|
|
||||||
wg.Add(1)
|
|
||||||
go func(f *gitdiff.File) {
|
|
||||||
defer wg.Done()
|
|
||||||
if f.IsBinary {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if f.IsDelete {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
commitSHA := ""
|
|
||||||
|
|
||||||
// Check if commit is allowed
|
|
||||||
if f.PatchHeader != nil {
|
|
||||||
commitSHA = f.PatchHeader.SHA
|
|
||||||
|
|
||||||
if cfg.Allowlist.CommitAllowed(f.PatchHeader.SHA) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tf := range f.TextFragments {
|
|
||||||
if f.TextFragments == nil {
|
|
||||||
// TODO fix this in gitleaks gitdiff fork
|
|
||||||
// https://github.com/gitleaks/gitleaks/issues/11
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if !godocutil.IsText([]byte(tf.Raw(gitdiff.OpAdd))) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, fi := range DetectFindings(cfg, []byte(tf.Raw(gitdiff.OpAdd)), f.NewName, commitSHA) {
|
|
||||||
// don't add to start/end lines if finding is from a file only rule
|
|
||||||
if !strings.HasPrefix(fi.Context, "file detected") {
|
|
||||||
fi.StartLine += int(tf.NewPosition)
|
|
||||||
fi.EndLine += int(tf.NewPosition)
|
|
||||||
}
|
|
||||||
if f.PatchHeader != nil {
|
|
||||||
fi.Commit = f.PatchHeader.SHA
|
|
||||||
fi.Message = f.PatchHeader.Message()
|
|
||||||
if f.PatchHeader.Author != nil {
|
|
||||||
fi.Author = f.PatchHeader.Author.Name
|
|
||||||
fi.Email = f.PatchHeader.Author.Email
|
|
||||||
}
|
|
||||||
fi.Date = f.PatchHeader.AuthorDate.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
if outputOptions.Redact {
|
|
||||||
fi.Redact()
|
|
||||||
}
|
|
||||||
|
|
||||||
if outputOptions.Verbose {
|
|
||||||
printFinding(fi)
|
|
||||||
}
|
|
||||||
mu.Lock()
|
|
||||||
findings = append(findings, &fi)
|
|
||||||
mu.Unlock()
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}(f)
|
|
||||||
}
|
|
||||||
|
|
||||||
wg.Wait()
|
|
||||||
return findings
|
|
||||||
}
|
|
||||||
@@ -7,12 +7,14 @@ import (
|
|||||||
"os/exec"
|
"os/exec"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/gitleaks/go-gitdiff/gitdiff"
|
"github.com/gitleaks/go-gitdiff/gitdiff"
|
||||||
"github.com/rs/zerolog/log"
|
"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) {
|
func GitLog(source string, logOpts string) (<-chan *gitdiff.File, error) {
|
||||||
sourceClean := filepath.Clean(source)
|
sourceClean := filepath.Clean(source)
|
||||||
var cmd *exec.Cmd
|
var cmd *exec.Cmd
|
||||||
@@ -21,7 +23,8 @@ func GitLog(source string, logOpts string) (<-chan *gitdiff.File, error) {
|
|||||||
args = append(args, strings.Split(logOpts, " ")...)
|
args = append(args, strings.Split(logOpts, " ")...)
|
||||||
cmd = exec.Command("git", args...)
|
cmd = exec.Command("git", args...)
|
||||||
} else {
|
} else {
|
||||||
cmd = exec.Command("git", "-C", sourceClean, "log", "-p", "-U0", "--full-history", "--show-pulls", "--all")
|
cmd = exec.Command("git", "-C", sourceClean, "log", "-p", "-U0",
|
||||||
|
"--full-history", "--all")
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debug().Msgf("executing: %s", cmd.String())
|
log.Debug().Msgf("executing: %s", cmd.String())
|
||||||
@@ -39,17 +42,21 @@ func GitLog(source string, logOpts string) (<-chan *gitdiff.File, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
go listenForStdErr(stderr)
|
go listenForStdErr(stderr)
|
||||||
|
// HACK: to avoid https://github.com/zricethezav/gitleaks/issues/722
|
||||||
|
time.Sleep(50 * time.Millisecond)
|
||||||
|
|
||||||
return gitdiff.Parse(stdout)
|
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) {
|
func GitDiff(source string, staged bool) (<-chan *gitdiff.File, error) {
|
||||||
sourceClean := filepath.Clean(source)
|
sourceClean := filepath.Clean(source)
|
||||||
var cmd *exec.Cmd
|
var cmd *exec.Cmd
|
||||||
cmd = exec.Command("git", "-C", sourceClean, "diff", "-U0", ".")
|
cmd = exec.Command("git", "-C", sourceClean, "diff", "-U0", ".")
|
||||||
if staged {
|
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())
|
log.Debug().Msgf("executing: %s", cmd.String())
|
||||||
|
|
||||||
@@ -66,6 +73,8 @@ func GitDiff(source string, staged bool) (<-chan *gitdiff.File, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
go listenForStdErr(stderr)
|
go listenForStdErr(stderr)
|
||||||
|
// HACK: to avoid https://github.com/zricethezav/gitleaks/issues/722
|
||||||
|
time.Sleep(50 * time.Millisecond)
|
||||||
|
|
||||||
return gitdiff.Parse(stdout)
|
return gitdiff.Parse(stdout)
|
||||||
}
|
}
|
||||||
@@ -76,8 +85,26 @@ func listenForStdErr(stderr io.ReadCloser) {
|
|||||||
scanner := bufio.NewScanner(stderr)
|
scanner := bufio.NewScanner(stderr)
|
||||||
errEncountered := false
|
errEncountered := false
|
||||||
for scanner.Scan() {
|
for scanner.Scan() {
|
||||||
log.Error().Msg(scanner.Text())
|
// if git throws the following error:
|
||||||
errEncountered = true
|
//
|
||||||
|
// 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 {
|
if errEncountered {
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
package git_test
|
||||||
|
|
||||||
|
// TODO: commenting out this test for now because it's flaky. Alternatives to consider to get this working:
|
||||||
|
// -- use `git stash` instead of `restore()`
|
||||||
|
|
||||||
|
// const repoBasePath = "../../testdata/repos/"
|
||||||
|
|
||||||
|
// const expectPath = "../../testdata/expected/"
|
||||||
|
|
||||||
|
// func TestGitLog(t *testing.T) {
|
||||||
|
// tests := []struct {
|
||||||
|
// source string
|
||||||
|
// logOpts string
|
||||||
|
// expected string
|
||||||
|
// }{
|
||||||
|
// {
|
||||||
|
// source: filepath.Join(repoBasePath, "small"),
|
||||||
|
// expected: filepath.Join(expectPath, "git", "small.txt"),
|
||||||
|
// },
|
||||||
|
// {
|
||||||
|
// source: filepath.Join(repoBasePath, "small"),
|
||||||
|
// expected: filepath.Join(expectPath, "git", "small-branch-foo.txt"),
|
||||||
|
// logOpts: "--all foo...",
|
||||||
|
// },
|
||||||
|
// }
|
||||||
|
|
||||||
|
// err := moveDotGit("dotGit", ".git")
|
||||||
|
// if err != nil {
|
||||||
|
// t.Fatal(err)
|
||||||
|
// }
|
||||||
|
// defer func() {
|
||||||
|
// if err = moveDotGit(".git", "dotGit"); err != nil {
|
||||||
|
// t.Fatal(err)
|
||||||
|
// }
|
||||||
|
// }()
|
||||||
|
|
||||||
|
// for _, tt := range tests {
|
||||||
|
// files, err := git.GitLog(tt.source, tt.logOpts)
|
||||||
|
// if err != nil {
|
||||||
|
// t.Error(err)
|
||||||
|
// }
|
||||||
|
|
||||||
|
// var diffSb strings.Builder
|
||||||
|
// for f := range files {
|
||||||
|
// for _, tf := range f.TextFragments {
|
||||||
|
// diffSb.WriteString(tf.Raw(gitdiff.OpAdd))
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// expectedBytes, err := os.ReadFile(tt.expected)
|
||||||
|
// if err != nil {
|
||||||
|
// t.Error(err)
|
||||||
|
// }
|
||||||
|
// expected := string(expectedBytes)
|
||||||
|
// if expected != diffSb.String() {
|
||||||
|
// // write string builder to .got file using os.Create
|
||||||
|
// err = os.WriteFile(strings.Replace(tt.expected, ".txt", ".got.txt", 1), []byte(diffSb.String()), 0644)
|
||||||
|
// if err != nil {
|
||||||
|
// t.Error(err)
|
||||||
|
// }
|
||||||
|
// t.Error("expected: ", expected, "got: ", diffSb.String())
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// func TestGitDiff(t *testing.T) {
|
||||||
|
// tests := []struct {
|
||||||
|
// source string
|
||||||
|
// expected string
|
||||||
|
// additions string
|
||||||
|
// target string
|
||||||
|
// }{
|
||||||
|
// {
|
||||||
|
// source: filepath.Join(repoBasePath, "small"),
|
||||||
|
// expected: "this line is added\nand another one",
|
||||||
|
// additions: "this line is added\nand another one",
|
||||||
|
// target: filepath.Join(repoBasePath, "small", "main.go"),
|
||||||
|
// },
|
||||||
|
// }
|
||||||
|
|
||||||
|
// err := moveDotGit("dotGit", ".git")
|
||||||
|
// if err != nil {
|
||||||
|
// t.Fatal(err)
|
||||||
|
// }
|
||||||
|
// defer func() {
|
||||||
|
// if err = moveDotGit(".git", "dotGit"); err != nil {
|
||||||
|
// t.Fatal(err)
|
||||||
|
// }
|
||||||
|
// }()
|
||||||
|
|
||||||
|
// for _, tt := range tests {
|
||||||
|
// noChanges, err := os.ReadFile(tt.target)
|
||||||
|
// if err != nil {
|
||||||
|
// t.Error(err)
|
||||||
|
// }
|
||||||
|
// err = os.WriteFile(tt.target, []byte(tt.additions), 0644)
|
||||||
|
// if err != nil {
|
||||||
|
// restore(tt.target, noChanges, t)
|
||||||
|
// t.Error(err)
|
||||||
|
// }
|
||||||
|
|
||||||
|
// files, err := git.GitDiff(tt.source, false)
|
||||||
|
// if err != nil {
|
||||||
|
// restore(tt.target, noChanges, t)
|
||||||
|
// t.Error(err)
|
||||||
|
// }
|
||||||
|
|
||||||
|
// for f := range files {
|
||||||
|
// sb := strings.Builder{}
|
||||||
|
// for _, tf := range f.TextFragments {
|
||||||
|
// sb.WriteString(tf.Raw(gitdiff.OpAdd))
|
||||||
|
// }
|
||||||
|
// if sb.String() != tt.expected {
|
||||||
|
// restore(tt.target, noChanges, t)
|
||||||
|
// t.Error("expected: ", tt.expected, "got: ", sb.String())
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// restore(tt.target, noChanges, t)
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// func restore(path string, data []byte, t *testing.T) {
|
||||||
|
// err := os.WriteFile(path, data, 0644)
|
||||||
|
// if err != nil {
|
||||||
|
// t.Fatal(err)
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// func moveDotGit(from, to string) error {
|
||||||
|
// repoDirs, err := os.ReadDir("../../testdata/repos")
|
||||||
|
// if err != nil {
|
||||||
|
// return err
|
||||||
|
// }
|
||||||
|
// for _, dir := range repoDirs {
|
||||||
|
// if to == ".git" {
|
||||||
|
// _, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), "dotGit"))
|
||||||
|
// if os.IsNotExist(err) {
|
||||||
|
// // dont want to delete the only copy of .git accidentally
|
||||||
|
// continue
|
||||||
|
// }
|
||||||
|
// os.RemoveAll(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), ".git"))
|
||||||
|
// }
|
||||||
|
// if !dir.IsDir() {
|
||||||
|
// continue
|
||||||
|
// }
|
||||||
|
// _, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from))
|
||||||
|
// if os.IsNotExist(err) {
|
||||||
|
// continue
|
||||||
|
// }
|
||||||
|
|
||||||
|
// err = os.Rename(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from),
|
||||||
|
// fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), to))
|
||||||
|
// if err != nil {
|
||||||
|
// return err
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// return nil
|
||||||
|
// }
|
||||||
@@ -1,158 +0,0 @@
|
|||||||
package detect
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/spf13/viper"
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
"github.com/zricethezav/gitleaks/v8/git"
|
|
||||||
"github.com/zricethezav/gitleaks/v8/report"
|
|
||||||
)
|
|
||||||
|
|
||||||
const repoBasePath = "../testdata/repos/"
|
|
||||||
const expectPath = "../testdata/expected/"
|
|
||||||
const configPath = "../testdata/config/"
|
|
||||||
|
|
||||||
// TestFromGit tests the FromGit function
|
|
||||||
func TestFromGit(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
cfgName string
|
|
||||||
opts Options
|
|
||||||
source string
|
|
||||||
logOpts string
|
|
||||||
expected string
|
|
||||||
expectedFindings []*report.Finding
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
source: filepath.Join(repoBasePath, "small"),
|
|
||||||
expected: filepath.Join(expectPath, "git", "small.txt"),
|
|
||||||
cfgName: "simple",
|
|
||||||
expectedFindings: []*report.Finding{
|
|
||||||
{
|
|
||||||
Description: "AWS Access Key",
|
|
||||||
StartLine: 20,
|
|
||||||
EndLine: 20,
|
|
||||||
StartColumn: 19,
|
|
||||||
EndColumn: 38,
|
|
||||||
Secret: "AKIALALEMEL33243OLIA",
|
|
||||||
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"},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Description: "AWS Access Key",
|
|
||||||
StartLine: 9,
|
|
||||||
EndLine: 9,
|
|
||||||
StartColumn: 17,
|
|
||||||
EndColumn: 36,
|
|
||||||
Secret: "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"},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
source: filepath.Join(repoBasePath, "small"),
|
|
||||||
expected: filepath.Join(expectPath, "git", "small-branch-foo.txt"),
|
|
||||||
logOpts: "--all foo...",
|
|
||||||
cfgName: "simple",
|
|
||||||
expectedFindings: []*report.Finding{
|
|
||||||
{
|
|
||||||
Description: "AWS Access Key",
|
|
||||||
StartLine: 9,
|
|
||||||
EndLine: 9,
|
|
||||||
StartColumn: 17,
|
|
||||||
EndColumn: 36,
|
|
||||||
Secret: "AKIALALEMEL33243OLIA",
|
|
||||||
// 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"},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
err := moveDotGit("dotGit", ".git")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
defer moveDotGit(".git", "dotGit")
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
files, err := git.GitLog(tt.source, tt.logOpts)
|
|
||||||
if err != nil {
|
|
||||||
t.Error(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
viper.AddConfigPath(configPath)
|
|
||||||
viper.SetConfigName("simple")
|
|
||||||
viper.SetConfigType("toml")
|
|
||||||
err = viper.ReadInConfig()
|
|
||||||
if err != nil {
|
|
||||||
t.Error(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var vc config.ViperConfig
|
|
||||||
viper.Unmarshal(&vc)
|
|
||||||
cfg, _ := vc.Translate()
|
|
||||||
|
|
||||||
findings := FromGit(files, cfg, tt.opts)
|
|
||||||
for _, f := range findings {
|
|
||||||
f.Context = "" // remove lines cause copying and pasting them has some wack formatting
|
|
||||||
f.Date = ""
|
|
||||||
}
|
|
||||||
assert.ElementsMatch(t, tt.expectedFindings, findings)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func moveDotGit(from, to string) error {
|
|
||||||
repoDirs, err := os.ReadDir("../testdata/repos")
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
for _, dir := range repoDirs {
|
|
||||||
if to == ".git" {
|
|
||||||
_, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), "dotGit"))
|
|
||||||
if os.IsNotExist(err) {
|
|
||||||
// dont want to delete the only copy of .git accidentally
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
os.RemoveAll(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), ".git"))
|
|
||||||
}
|
|
||||||
if !dir.IsDir() {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
_, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from))
|
|
||||||
if os.IsNotExist(err) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
err = os.Rename(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from),
|
|
||||||
fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), to))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
+32
-3
@@ -10,15 +10,22 @@ type Location struct {
|
|||||||
endLineIndex int
|
endLineIndex int
|
||||||
}
|
}
|
||||||
|
|
||||||
func getLocation(linePairs [][]int, start int, end int) Location {
|
func location(fragment Fragment, matchIndex []int) Location {
|
||||||
var (
|
var (
|
||||||
prevNewLine int
|
prevNewLine int
|
||||||
location Location
|
location Location
|
||||||
|
lineSet bool
|
||||||
|
_lineNum int
|
||||||
)
|
)
|
||||||
|
|
||||||
for lineNum, pair := range linePairs {
|
start := matchIndex[0]
|
||||||
|
end := matchIndex[1]
|
||||||
|
|
||||||
|
for lineNum, pair := range fragment.newlineIndices {
|
||||||
|
_lineNum = lineNum
|
||||||
newLineByteIndex := pair[0]
|
newLineByteIndex := pair[0]
|
||||||
if prevNewLine <= start && start < newLineByteIndex {
|
if prevNewLine <= start && start < newLineByteIndex {
|
||||||
|
lineSet = true
|
||||||
location.startLine = lineNum
|
location.startLine = lineNum
|
||||||
location.endLine = lineNum
|
location.endLine = lineNum
|
||||||
location.startColumn = (start - prevNewLine) + 1 // +1 because counting starts at 1
|
location.startColumn = (start - prevNewLine) + 1 // +1 because counting starts at 1
|
||||||
@@ -30,9 +37,31 @@ func getLocation(linePairs [][]int, start int, end int) Location {
|
|||||||
location.endColumn = (end - prevNewLine)
|
location.endColumn = (end - prevNewLine)
|
||||||
location.endLineIndex = newLineByteIndex
|
location.endLineIndex = newLineByteIndex
|
||||||
}
|
}
|
||||||
|
|
||||||
prevNewLine = pair[0]
|
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
|
||||||
|
location.endLine = _lineNum
|
||||||
|
location.startLineIndex = start
|
||||||
|
|
||||||
|
// search for new line byte index
|
||||||
|
i := 0
|
||||||
|
for end+i < len(fragment.Raw) {
|
||||||
|
if fragment.Raw[end+i] == '\n' {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if fragment.Raw[end+i] == '\r' {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
location.endLineIndex = end + i
|
||||||
|
}
|
||||||
return location
|
return location
|
||||||
}
|
}
|
||||||
@@ -49,7 +49,7 @@ func TestGetLocation(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
loc := getLocation(test.linePairs, test.start, test.end)
|
loc := location(Fragment{newlineIndices: test.linePairs}, []int{test.start, test.end})
|
||||||
if loc != test.wantLocation {
|
if loc != test.wantLocation {
|
||||||
t.Errorf("\nstartLine %d\nstartColumn: %d\nendLine: %d\nendColumn: %d\nstartLineIndex: %d\nendlineIndex %d",
|
t.Errorf("\nstartLine %d\nstartColumn: %d\nendLine: %d\nendColumn: %d\nstartLineIndex: %d\nendlineIndex %d",
|
||||||
loc.startLine, loc.startColumn, loc.endLine, loc.endColumn, loc.startLineIndex, loc.endLineIndex)
|
loc.startLine, loc.startColumn, loc.endLine, loc.endColumn, loc.startLineIndex, loc.endLineIndex)
|
||||||
|
|||||||
+108
@@ -0,0 +1,108 @@
|
|||||||
|
package detect
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/zricethezav/gitleaks/v8/report"
|
||||||
|
|
||||||
|
"github.com/gitleaks/go-gitdiff/gitdiff"
|
||||||
|
"github.com/rs/zerolog/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
// augmentGitFinding updates the start and end line numbers of a finding to include the
|
||||||
|
// delta from the git diff
|
||||||
|
func augmentGitFinding(finding report.Finding, textFragment *gitdiff.TextFragment, f *gitdiff.File) report.Finding {
|
||||||
|
if !strings.HasPrefix(finding.Match, "file detected") {
|
||||||
|
finding.StartLine += int(textFragment.NewPosition)
|
||||||
|
finding.EndLine += int(textFragment.NewPosition)
|
||||||
|
}
|
||||||
|
|
||||||
|
if f.PatchHeader != nil {
|
||||||
|
finding.Commit = f.PatchHeader.SHA
|
||||||
|
finding.Message = f.PatchHeader.Message()
|
||||||
|
if f.PatchHeader.Author != nil {
|
||||||
|
finding.Author = f.PatchHeader.Author.Name
|
||||||
|
finding.Email = f.PatchHeader.Author.Email
|
||||||
|
}
|
||||||
|
finding.Date = f.PatchHeader.AuthorDate.UTC().Format(time.RFC3339)
|
||||||
|
}
|
||||||
|
return finding
|
||||||
|
}
|
||||||
|
|
||||||
|
// shannonEntropy calculates the entropy of data using the formula defined here:
|
||||||
|
// https://en.wiktionary.org/wiki/Shannon_entropy
|
||||||
|
// Another way to think about what this is doing is calculating the number of bits
|
||||||
|
// needed to on average encode the data. So, the higher the entropy, the more random the data, the
|
||||||
|
// more bits needed to encode that data.
|
||||||
|
func shannonEntropy(data string) (entropy float64) {
|
||||||
|
if data == "" {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
charCounts := make(map[rune]int)
|
||||||
|
for _, char := range data {
|
||||||
|
charCounts[char]++
|
||||||
|
}
|
||||||
|
|
||||||
|
invLength := 1.0 / float64(len(data))
|
||||||
|
for _, count := range charCounts {
|
||||||
|
freq := float64(count) * invLength
|
||||||
|
entropy -= freq * math.Log2(freq)
|
||||||
|
}
|
||||||
|
|
||||||
|
return entropy
|
||||||
|
}
|
||||||
|
|
||||||
|
// filter will dedupe and redact findings
|
||||||
|
func filter(findings []report.Finding, redact bool) []report.Finding {
|
||||||
|
var retFindings []report.Finding
|
||||||
|
for _, f := range findings {
|
||||||
|
include := true
|
||||||
|
if strings.Contains(strings.ToLower(f.RuleID), "generic") {
|
||||||
|
for _, fPrime := range findings {
|
||||||
|
if f.StartLine == fPrime.StartLine &&
|
||||||
|
f.EndLine == fPrime.EndLine &&
|
||||||
|
f.Commit == fPrime.Commit &&
|
||||||
|
f.RuleID != fPrime.RuleID &&
|
||||||
|
strings.Contains(fPrime.Secret, f.Secret) &&
|
||||||
|
!strings.Contains(strings.ToLower(fPrime.RuleID), "generic") {
|
||||||
|
|
||||||
|
genericMatch := strings.Replace(f.Match, f.Secret, "REDACTED", -1)
|
||||||
|
betterMatch := strings.Replace(fPrime.Match, fPrime.Secret, "REDACTED", -1)
|
||||||
|
log.Debug().Msgf("skipping %s finding (%s), %s rule takes precendence (%s)", f.RuleID, genericMatch, fPrime.RuleID, betterMatch)
|
||||||
|
include = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if redact {
|
||||||
|
f.Redact()
|
||||||
|
}
|
||||||
|
if include {
|
||||||
|
retFindings = append(retFindings, f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return retFindings
|
||||||
|
}
|
||||||
|
|
||||||
|
func printFinding(f report.Finding) {
|
||||||
|
var b []byte
|
||||||
|
b, _ = json.MarshalIndent(f, "", " ")
|
||||||
|
fmt.Println(string(b))
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsDigit(s string) bool {
|
||||||
|
for _, c := range s {
|
||||||
|
switch c {
|
||||||
|
case '1', '2', '3', '4', '5', '6', '7', '8', '9':
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
-157
@@ -1,157 +0,0 @@
|
|||||||
package git_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/gitleaks/go-gitdiff/gitdiff"
|
|
||||||
"github.com/zricethezav/gitleaks/v8/git"
|
|
||||||
)
|
|
||||||
|
|
||||||
const repoBasePath = "../testdata/repos/"
|
|
||||||
const expectPath = "../testdata/expected/"
|
|
||||||
|
|
||||||
func TestGitLog(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
source string
|
|
||||||
logOpts string
|
|
||||||
expected string
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
source: filepath.Join(repoBasePath, "small"),
|
|
||||||
expected: filepath.Join(expectPath, "git", "small.txt"),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
source: filepath.Join(repoBasePath, "small"),
|
|
||||||
expected: filepath.Join(expectPath, "git", "small-branch-foo.txt"),
|
|
||||||
logOpts: "--all foo...",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
err := moveDotGit("dotGit", ".git")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
defer moveDotGit(".git", "dotGit")
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
files, err := git.GitLog(tt.source, tt.logOpts)
|
|
||||||
if err != nil {
|
|
||||||
t.Error(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var diffSb strings.Builder
|
|
||||||
for f := range files {
|
|
||||||
for _, tf := range f.TextFragments {
|
|
||||||
diffSb.WriteString(tf.Raw(gitdiff.OpAdd))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
expectedBytes, err := os.ReadFile(tt.expected)
|
|
||||||
if err != nil {
|
|
||||||
t.Error(err)
|
|
||||||
}
|
|
||||||
expected := string(expectedBytes)
|
|
||||||
if expected != diffSb.String() {
|
|
||||||
// write string builder to .got file using os.Create
|
|
||||||
err = os.WriteFile(strings.Replace(tt.expected, ".txt", ".got.txt", 1), []byte(diffSb.String()), 0644)
|
|
||||||
if err != nil {
|
|
||||||
t.Error(err)
|
|
||||||
}
|
|
||||||
t.Error("expected: ", expected, "got: ", diffSb.String())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestGitDiff(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
source string
|
|
||||||
expected string
|
|
||||||
additions string
|
|
||||||
target string
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
source: filepath.Join(repoBasePath, "small"),
|
|
||||||
expected: "this line is added\nand another one",
|
|
||||||
additions: "this line is added\nand another one",
|
|
||||||
target: filepath.Join(repoBasePath, "small", "main.go"),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
err := moveDotGit("dotGit", ".git")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
defer moveDotGit(".git", "dotGit")
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
noChanges, err := os.ReadFile(tt.target)
|
|
||||||
if err != nil {
|
|
||||||
t.Error(err)
|
|
||||||
}
|
|
||||||
err = os.WriteFile(tt.target, []byte(tt.additions), 0644)
|
|
||||||
if err != nil {
|
|
||||||
restore(tt.target, noChanges, t)
|
|
||||||
t.Error(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
files, err := git.GitDiff(tt.source, false)
|
|
||||||
if err != nil {
|
|
||||||
restore(tt.target, noChanges, t)
|
|
||||||
t.Error(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
for f := range files {
|
|
||||||
sb := strings.Builder{}
|
|
||||||
for _, tf := range f.TextFragments {
|
|
||||||
sb.WriteString(tf.Raw(gitdiff.OpAdd))
|
|
||||||
}
|
|
||||||
if sb.String() != tt.expected {
|
|
||||||
restore(tt.target, noChanges, t)
|
|
||||||
t.Error("expected: ", tt.expected, "got: ", sb.String())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
restore(tt.target, noChanges, t)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func restore(path string, data []byte, t *testing.T) {
|
|
||||||
err := os.WriteFile(path, data, 0644)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func moveDotGit(from, to string) error {
|
|
||||||
repoDirs, err := os.ReadDir("../testdata/repos")
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
for _, dir := range repoDirs {
|
|
||||||
if to == ".git" {
|
|
||||||
_, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), "dotGit"))
|
|
||||||
if os.IsNotExist(err) {
|
|
||||||
// dont want to delete the only copy of .git accidentally
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
os.RemoveAll(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), ".git"))
|
|
||||||
}
|
|
||||||
if !dir.IsDir() {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
_, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from))
|
|
||||||
if os.IsNotExist(err) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
err = os.Rename(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from),
|
|
||||||
fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), to))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,15 +1,34 @@
|
|||||||
module github.com/zricethezav/gitleaks/v8
|
module github.com/zricethezav/gitleaks/v8
|
||||||
|
|
||||||
go 1.16
|
go 1.17
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/gitleaks/go-gitdiff v0.7.2
|
github.com/fatih/semgroup v1.2.0
|
||||||
github.com/rs/zerolog v1.25.0
|
github.com/gitleaks/go-gitdiff v0.7.4
|
||||||
|
github.com/rs/zerolog v1.26.1
|
||||||
github.com/spf13/cobra v1.2.1
|
github.com/spf13/cobra v1.2.1
|
||||||
github.com/spf13/viper v1.8.1
|
github.com/spf13/viper v1.8.1
|
||||||
github.com/stretchr/testify v1.7.0
|
github.com/stretchr/testify v1.7.0
|
||||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||||
|
github.com/fsnotify/fsnotify v1.4.9 // indirect
|
||||||
|
github.com/hashicorp/hcl v1.0.0 // indirect
|
||||||
|
github.com/inconshreveable/mousetrap v1.0.0 // indirect
|
||||||
|
github.com/magiconair/properties v1.8.5 // indirect
|
||||||
|
github.com/mitchellh/mapstructure v1.4.1 // indirect
|
||||||
|
github.com/pelletier/go-toml v1.9.3 // indirect
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||||
|
github.com/spf13/afero v1.6.0 // indirect
|
||||||
|
github.com/spf13/cast v1.3.1 // indirect
|
||||||
|
github.com/spf13/jwalterweatherman v1.1.0 // indirect
|
||||||
|
github.com/spf13/pflag v1.0.5 // indirect
|
||||||
|
github.com/subosito/gotenv v1.2.0 // indirect
|
||||||
|
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
|
||||||
golang.org/x/sys v0.0.0-20211110154304-99a53858aa08 // indirect
|
golang.org/x/sys v0.0.0-20211110154304-99a53858aa08 // indirect
|
||||||
golang.org/x/tools v0.1.5
|
golang.org/x/text v0.3.6 // indirect
|
||||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
|
gopkg.in/ini.v1 v1.62.0 // indirect
|
||||||
|
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
|
||||||
)
|
)
|
||||||
@@ -67,11 +67,13 @@ github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.m
|
|||||||
github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk=
|
github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk=
|
||||||
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
||||||
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
|
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
|
||||||
|
github.com/fatih/semgroup v1.2.0 h1:h/OLXwEM+3NNyAdZEpMiH1OzfplU09i2qXPVThGZvyg=
|
||||||
|
github.com/fatih/semgroup v1.2.0/go.mod h1:1KAD4iIYfXjE4U13B48VM4z9QUwV5Tt8O4rS879kgm8=
|
||||||
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
|
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
|
||||||
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
|
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/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.4 h1:8vICc4moyRR2poklblThdQ0ckMet22mEvFJSxPsiDlk=
|
||||||
github.com/gitleaks/go-gitdiff v0.7.2/go.mod h1:pKz0X4YzCKZs30BL+weqBIG7mx0jl4tF1uXV9ZyNvrA=
|
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 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-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
|
||||||
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
|
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
|
||||||
@@ -209,8 +211,8 @@ github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:
|
|||||||
github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
|
github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
|
||||||
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
||||||
github.com/rs/xid v1.3.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
|
github.com/rs/xid v1.3.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
|
||||||
github.com/rs/zerolog v1.25.0 h1:Rj7XygbUHKUlDPcVdoLyR91fJBsduXj5fRxyqIQj/II=
|
github.com/rs/zerolog v1.26.1 h1:/ihwxqH+4z8UxyI70wM1z9yCvkWcfz/a3mj48k/Zngc=
|
||||||
github.com/rs/zerolog v1.25.0/go.mod h1:7KHcEGe0QZPOm2IE4Kpb5rTh6n1h2hIgS5OOnu1rUaI=
|
github.com/rs/zerolog v1.26.1/go.mod h1:/wSSJWX7lVrsOwlbyTRSOJvqRlc+WjWlfes+CiJ+tmc=
|
||||||
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||||
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
|
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
|
||||||
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
|
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
|
||||||
@@ -246,6 +248,7 @@ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de
|
|||||||
github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||||
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||||
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
|
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
|
||||||
|
github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
|
||||||
go.etcd.io/etcd/api/v3 v3.5.0/go.mod h1:cbVKeC6lCfl7j/8jBhAK6aIYO9XOjdptoxU/nLQcPvs=
|
go.etcd.io/etcd/api/v3 v3.5.0/go.mod h1:cbVKeC6lCfl7j/8jBhAK6aIYO9XOjdptoxU/nLQcPvs=
|
||||||
go.etcd.io/etcd/client/pkg/v3 v3.5.0/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g=
|
go.etcd.io/etcd/client/pkg/v3 v3.5.0/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g=
|
||||||
go.etcd.io/etcd/client/v2 v2.305.0/go.mod h1:h9puh54ZTgAKtEbut2oe9P4L/oqKCVB6xsXlzd7alYQ=
|
go.etcd.io/etcd/client/v2 v2.305.0/go.mod h1:h9puh54ZTgAKtEbut2oe9P4L/oqKCVB6xsXlzd7alYQ=
|
||||||
@@ -266,6 +269,7 @@ golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8U
|
|||||||
golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||||
|
golang.org/x/crypto v0.0.0-20211215165025-cf75a172585e/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
|
||||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||||
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||||
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
|
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
|
||||||
@@ -337,6 +341,7 @@ golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v
|
|||||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||||
golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc=
|
golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc=
|
||||||
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
|
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
|
||||||
|
golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||||
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||||
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||||
@@ -401,7 +406,9 @@ golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7w
|
|||||||
golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20211110154304-99a53858aa08 h1:WecRHqgE09JBkh/584XIE6PMz5KKE/vER4izNUi30AQ=
|
golang.org/x/sys v0.0.0-20211110154304-99a53858aa08 h1:WecRHqgE09JBkh/584XIE6PMz5KKE/vER4izNUi30AQ=
|
||||||
golang.org/x/sys v0.0.0-20211110154304-99a53858aa08/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20211110154304-99a53858aa08/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
@@ -411,8 +418,9 @@ golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3
|
|||||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
golang.org/x/text v0.3.5 h1:i6eZZ+zk0SOf0xgBpEpPD18qWcJda6q1sxt3S0kzyUQ=
|
|
||||||
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M=
|
||||||
|
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||||
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||||
@@ -467,8 +475,7 @@ golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4f
|
|||||||
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||||
golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0=
|
golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0=
|
||||||
golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
|
golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
|
||||||
golang.org/x/tools v0.1.5 h1:ouewzE6p+/VEB31YYnTbEJdi8pFqKp4P4n85vwo3DHA=
|
golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo=
|
||||||
golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
|
|
||||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
@@ -576,9 +583,8 @@ google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlba
|
|||||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||||
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
|
||||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
|
|
||||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
|
||||||
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||||
gopkg.in/ini.v1 v1.62.0 h1:duBzk771uxoUuOlyRLkHsygud9+5lrlGjdFBb4mSKDU=
|
gopkg.in/ini.v1 v1.62.0 h1:duBzk771uxoUuOlyRLkHsygud9+5lrlGjdFBb4mSKDU=
|
||||||
gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
||||||
|
|||||||
@@ -2,4 +2,3 @@ package report
|
|||||||
|
|
||||||
const version = "v8.0.0"
|
const version = "v8.0.0"
|
||||||
const driver = "gitleaks"
|
const driver = "gitleaks"
|
||||||
const driverURL = "https://github.com/zricethezav/gitleaks"
|
|
||||||
+3
-3
@@ -7,7 +7,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// writeCsv writes the list of findings to a writeCloser.
|
// 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 {
|
if len(f) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -17,7 +17,7 @@ func writeCsv(f []*Finding, w io.WriteCloser) error {
|
|||||||
"Commit",
|
"Commit",
|
||||||
"File",
|
"File",
|
||||||
"Secret",
|
"Secret",
|
||||||
"Context",
|
"Match",
|
||||||
"StartLine",
|
"StartLine",
|
||||||
"EndLine",
|
"EndLine",
|
||||||
"StartColumn",
|
"StartColumn",
|
||||||
@@ -35,7 +35,7 @@ func writeCsv(f []*Finding, w io.WriteCloser) error {
|
|||||||
f.Commit,
|
f.Commit,
|
||||||
f.File,
|
f.File,
|
||||||
f.Secret,
|
f.Secret,
|
||||||
f.Context,
|
f.Match,
|
||||||
strconv.Itoa(f.StartLine),
|
strconv.Itoa(f.StartLine),
|
||||||
strconv.Itoa(f.EndLine),
|
strconv.Itoa(f.EndLine),
|
||||||
strconv.Itoa(f.StartColumn),
|
strconv.Itoa(f.StartColumn),
|
||||||
|
|||||||
+4
-4
@@ -9,7 +9,7 @@ import (
|
|||||||
|
|
||||||
func TestWriteCSV(t *testing.T) {
|
func TestWriteCSV(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
findings []*Finding
|
findings []Finding
|
||||||
testReportName string
|
testReportName string
|
||||||
expected string
|
expected string
|
||||||
wantEmpty bool
|
wantEmpty bool
|
||||||
@@ -17,10 +17,10 @@ func TestWriteCSV(t *testing.T) {
|
|||||||
{
|
{
|
||||||
testReportName: "simple",
|
testReportName: "simple",
|
||||||
expected: filepath.Join(expectPath, "report", "csv_simple.csv"),
|
expected: filepath.Join(expectPath, "report", "csv_simple.csv"),
|
||||||
findings: []*Finding{
|
findings: []Finding{
|
||||||
{
|
{
|
||||||
RuleID: "test-rule",
|
RuleID: "test-rule",
|
||||||
Context: "line containing secret",
|
Match: "line containing secret",
|
||||||
Secret: "a secret",
|
Secret: "a secret",
|
||||||
StartLine: 1,
|
StartLine: 1,
|
||||||
EndLine: 2,
|
EndLine: 2,
|
||||||
@@ -39,7 +39,7 @@ func TestWriteCSV(t *testing.T) {
|
|||||||
wantEmpty: true,
|
wantEmpty: true,
|
||||||
testReportName: "empty",
|
testReportName: "empty",
|
||||||
expected: filepath.Join(expectPath, "report", "this_should_not_exist.csv"),
|
expected: filepath.Join(expectPath, "report", "this_should_not_exist.csv"),
|
||||||
findings: []*Finding{}},
|
findings: []Finding{}},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
|
|||||||
+5
-3
@@ -1,6 +1,8 @@
|
|||||||
package report
|
package report
|
||||||
|
|
||||||
import "strings"
|
import (
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
// Finding contains information about strings that
|
// Finding contains information about strings that
|
||||||
// have been captured by a tree-sitter query.
|
// have been captured by a tree-sitter query.
|
||||||
@@ -11,7 +13,7 @@ type Finding struct {
|
|||||||
StartColumn int
|
StartColumn int
|
||||||
EndColumn int
|
EndColumn int
|
||||||
|
|
||||||
Context string
|
Match string
|
||||||
|
|
||||||
// Secret contains the full content of what is matched in
|
// Secret contains the full content of what is matched in
|
||||||
// the tree-sitter query.
|
// the tree-sitter query.
|
||||||
@@ -37,6 +39,6 @@ type Finding struct {
|
|||||||
|
|
||||||
// Redact removes sensitive information from a finding.
|
// Redact removes sensitive information from a finding.
|
||||||
func (f *Finding) Redact() {
|
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"
|
f.Secret = "REDACT"
|
||||||
}
|
}
|
||||||
@@ -11,8 +11,8 @@ func TestRedact(t *testing.T) {
|
|||||||
redact: true,
|
redact: true,
|
||||||
findings: []Finding{
|
findings: []Finding{
|
||||||
{
|
{
|
||||||
Secret: "line containing secret",
|
Secret: "line containing secret",
|
||||||
Context: "secret",
|
Match: "secret",
|
||||||
},
|
},
|
||||||
}},
|
}},
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -5,9 +5,9 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
func writeJson(findings []*Finding, w io.WriteCloser) error {
|
func writeJson(findings []Finding, w io.WriteCloser) error {
|
||||||
if len(findings) == 0 {
|
if len(findings) == 0 {
|
||||||
return nil
|
findings = []Finding{}
|
||||||
}
|
}
|
||||||
encoder := json.NewEncoder(w)
|
encoder := json.NewEncoder(w)
|
||||||
encoder.SetIndent("", " ")
|
encoder.SetIndent("", " ")
|
||||||
|
|||||||
+5
-6
@@ -9,7 +9,7 @@ import (
|
|||||||
|
|
||||||
func TestWriteJSON(t *testing.T) {
|
func TestWriteJSON(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
findings []*Finding
|
findings []Finding
|
||||||
testReportName string
|
testReportName string
|
||||||
expected string
|
expected string
|
||||||
wantEmpty bool
|
wantEmpty bool
|
||||||
@@ -17,12 +17,12 @@ func TestWriteJSON(t *testing.T) {
|
|||||||
{
|
{
|
||||||
testReportName: "simple",
|
testReportName: "simple",
|
||||||
expected: filepath.Join(expectPath, "report", "json_simple.json"),
|
expected: filepath.Join(expectPath, "report", "json_simple.json"),
|
||||||
findings: []*Finding{
|
findings: []Finding{
|
||||||
{
|
{
|
||||||
|
|
||||||
Description: "",
|
Description: "",
|
||||||
RuleID: "test-rule",
|
RuleID: "test-rule",
|
||||||
Context: "line containing secret",
|
Match: "line containing secret",
|
||||||
Secret: "a secret",
|
Secret: "a secret",
|
||||||
StartLine: 1,
|
StartLine: 1,
|
||||||
EndLine: 2,
|
EndLine: 2,
|
||||||
@@ -39,10 +39,9 @@ func TestWriteJSON(t *testing.T) {
|
|||||||
}},
|
}},
|
||||||
{
|
{
|
||||||
|
|
||||||
wantEmpty: true,
|
|
||||||
testReportName: "empty",
|
testReportName: "empty",
|
||||||
expected: filepath.Join(expectPath, "report", "this_should_not_exist.json"),
|
expected: filepath.Join(expectPath, "report", "empty.json"),
|
||||||
findings: []*Finding{}},
|
findings: []Finding{}},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
|
|||||||
+5
-9
@@ -13,10 +13,7 @@ const (
|
|||||||
CWE_DESCRIPTION = "Use of Hard-coded Credentials"
|
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
|
|
||||||
}
|
|
||||||
file, err := os.Create(reportPath)
|
file, err := os.Create(reportPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -24,13 +21,12 @@ func Write(findings []*Finding, cfg config.Config, ext string, reportPath string
|
|||||||
ext = strings.ToLower(ext)
|
ext = strings.ToLower(ext)
|
||||||
switch ext {
|
switch ext {
|
||||||
case ".json", "json":
|
case ".json", "json":
|
||||||
writeJson(findings, file)
|
err = writeJson(findings, file)
|
||||||
case ".csv", "csv":
|
case ".csv", "csv":
|
||||||
writeCsv(findings, file)
|
err = writeCsv(findings, file)
|
||||||
case ".sarif", "sarif":
|
case ".sarif", "sarif":
|
||||||
writeSarif(cfg, findings, file)
|
err = writeSarif(cfg, findings, file)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return err
|
||||||
}
|
}
|
||||||
@@ -16,13 +16,13 @@ const (
|
|||||||
|
|
||||||
func TestReport(t *testing.T) {
|
func TestReport(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
findings []*Finding
|
findings []Finding
|
||||||
ext string
|
ext string
|
||||||
wantEmpty bool
|
wantEmpty bool
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
ext: "json",
|
ext: "json",
|
||||||
findings: []*Finding{
|
findings: []Finding{
|
||||||
{
|
{
|
||||||
RuleID: "test-rule",
|
RuleID: "test-rule",
|
||||||
},
|
},
|
||||||
@@ -30,7 +30,7 @@ func TestReport(t *testing.T) {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
ext: ".json",
|
ext: ".json",
|
||||||
findings: []*Finding{
|
findings: []Finding{
|
||||||
{
|
{
|
||||||
RuleID: "test-rule",
|
RuleID: "test-rule",
|
||||||
},
|
},
|
||||||
@@ -38,7 +38,7 @@ func TestReport(t *testing.T) {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
ext: ".jsonj",
|
ext: ".jsonj",
|
||||||
findings: []*Finding{
|
findings: []Finding{
|
||||||
{
|
{
|
||||||
RuleID: "test-rule",
|
RuleID: "test-rule",
|
||||||
},
|
},
|
||||||
@@ -47,7 +47,7 @@ func TestReport(t *testing.T) {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
ext: ".csv",
|
ext: ".csv",
|
||||||
findings: []*Finding{
|
findings: []Finding{
|
||||||
{
|
{
|
||||||
RuleID: "test-rule",
|
RuleID: "test-rule",
|
||||||
},
|
},
|
||||||
@@ -55,7 +55,7 @@ func TestReport(t *testing.T) {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
ext: "csv",
|
ext: "csv",
|
||||||
findings: []*Finding{
|
findings: []Finding{
|
||||||
{
|
{
|
||||||
RuleID: "test-rule",
|
RuleID: "test-rule",
|
||||||
},
|
},
|
||||||
@@ -63,7 +63,7 @@ func TestReport(t *testing.T) {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
ext: "CSV",
|
ext: "CSV",
|
||||||
findings: []*Finding{
|
findings: []Finding{
|
||||||
{
|
{
|
||||||
RuleID: "test-rule",
|
RuleID: "test-rule",
|
||||||
},
|
},
|
||||||
|
|||||||
+34
-24
@@ -8,10 +8,10 @@ import (
|
|||||||
"github.com/zricethezav/gitleaks/v8/config"
|
"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{
|
sarif := Sarif{
|
||||||
Schema: "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0-rtm.5.json",
|
Schema: "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0-rtm.5.json",
|
||||||
Version: version,
|
Version: "2.1.0",
|
||||||
Runs: getRuns(cfg, findings),
|
Runs: getRuns(cfg, findings),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -20,7 +20,7 @@ func writeSarif(cfg config.Config, findings []*Finding, w io.WriteCloser) error
|
|||||||
return encoder.Encode(sarif)
|
return encoder.Encode(sarif)
|
||||||
}
|
}
|
||||||
|
|
||||||
func getRuns(cfg config.Config, findings []*Finding) []Runs {
|
func getRuns(cfg config.Config, findings []Finding) []Runs {
|
||||||
return []Runs{
|
return []Runs{
|
||||||
{
|
{
|
||||||
Tool: getTool(cfg),
|
Tool: getTool(cfg),
|
||||||
@@ -30,31 +30,52 @@ func getRuns(cfg config.Config, findings []*Finding) []Runs {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func getTool(cfg config.Config) Tool {
|
func getTool(cfg config.Config) Tool {
|
||||||
return Tool{
|
tool := Tool{
|
||||||
Driver: Driver{
|
Driver: Driver{
|
||||||
Name: driver,
|
Name: driver,
|
||||||
SemanticVersion: version,
|
SemanticVersion: version,
|
||||||
Rules: getRules(cfg),
|
Rules: getRules(cfg),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// if this tool has no rules, ensure that it is represented as [] instead of null/nil
|
||||||
|
if hasEmptyRules(tool) {
|
||||||
|
tool.Driver.Rules = make([]Rules, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
return tool
|
||||||
|
}
|
||||||
|
|
||||||
|
func hasEmptyRules(tool Tool) bool {
|
||||||
|
return len(tool.Driver.Rules) == 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func getRules(cfg config.Config) []Rules {
|
func getRules(cfg config.Config) []Rules {
|
||||||
// TODO for _, rule := range cfg.Rules {
|
// TODO for _, rule := range cfg.Rules {
|
||||||
var rules []Rules
|
var rules []Rules
|
||||||
for _, rule := range cfg.Rules {
|
for _, rule := range cfg.Rules {
|
||||||
rules = append(rules, Rules{
|
shortDescription := ShortDescription{
|
||||||
ID: rule.RuleID,
|
Text: rule.Description,
|
||||||
Name: rule.Description,
|
}
|
||||||
Description: ShortDescription{
|
if rule.Regex != nil {
|
||||||
|
shortDescription = ShortDescription{
|
||||||
Text: rule.Regex.String(),
|
Text: rule.Regex.String(),
|
||||||
},
|
}
|
||||||
|
} else if rule.Path != nil {
|
||||||
|
shortDescription = ShortDescription{
|
||||||
|
Text: rule.Path.String(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rules = append(rules, Rules{
|
||||||
|
ID: rule.RuleID,
|
||||||
|
Name: rule.Description,
|
||||||
|
Description: shortDescription,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
return rules
|
return rules
|
||||||
}
|
}
|
||||||
|
|
||||||
func messageText(f *Finding) string {
|
func messageText(f Finding) string {
|
||||||
if f.Commit == "" {
|
if f.Commit == "" {
|
||||||
return fmt.Sprintf("%s has detected secret for file %s.", f.RuleID, f.File)
|
return fmt.Sprintf("%s has detected secret for file %s.", f.RuleID, f.File)
|
||||||
}
|
}
|
||||||
@@ -63,8 +84,8 @@ func messageText(f *Finding) string {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func getResults(findings []*Finding) []Results {
|
func getResults(findings []Finding) []Results {
|
||||||
var results []Results
|
results := []Results{}
|
||||||
for _, f := range findings {
|
for _, f := range findings {
|
||||||
r := Results{
|
r := Results{
|
||||||
Message: Message{
|
Message: Message{
|
||||||
@@ -87,7 +108,7 @@ func getResults(findings []*Finding) []Results {
|
|||||||
return results
|
return results
|
||||||
}
|
}
|
||||||
|
|
||||||
func getLocation(f *Finding) []Locations {
|
func getLocation(f Finding) []Locations {
|
||||||
return []Locations{
|
return []Locations{
|
||||||
{
|
{
|
||||||
PhysicalLocation: PhysicalLocation{
|
PhysicalLocation: PhysicalLocation{
|
||||||
@@ -186,14 +207,3 @@ type Runs struct {
|
|||||||
Tool Tool `json:"tool"`
|
Tool Tool `json:"tool"`
|
||||||
Results []Results `json:"results"`
|
Results []Results `json:"results"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func configToRules(cfg config.Config) []Rules {
|
|
||||||
var rules []Rules
|
|
||||||
for _, rule := range cfg.Rules {
|
|
||||||
rules = append(rules, Rules{
|
|
||||||
ID: rule.RuleID,
|
|
||||||
Name: rule.Description,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return rules
|
|
||||||
}
|
|
||||||
@@ -14,7 +14,7 @@ const configPath = "../testdata/config/"
|
|||||||
|
|
||||||
func TestWriteSarif(t *testing.T) {
|
func TestWriteSarif(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
findings []*Finding
|
findings []Finding
|
||||||
testReportName string
|
testReportName string
|
||||||
expected string
|
expected string
|
||||||
wantEmpty bool
|
wantEmpty bool
|
||||||
@@ -24,12 +24,12 @@ func TestWriteSarif(t *testing.T) {
|
|||||||
cfgName: "simple",
|
cfgName: "simple",
|
||||||
testReportName: "simple",
|
testReportName: "simple",
|
||||||
expected: filepath.Join(expectPath, "report", "sarif_simple.sarif"),
|
expected: filepath.Join(expectPath, "report", "sarif_simple.sarif"),
|
||||||
findings: []*Finding{
|
findings: []Finding{
|
||||||
{
|
{
|
||||||
|
|
||||||
Description: "",
|
Description: "",
|
||||||
RuleID: "test-rule",
|
RuleID: "test-rule",
|
||||||
Context: "line containing secret",
|
Match: "line containing secret",
|
||||||
Secret: "a secret",
|
Secret: "a secret",
|
||||||
StartLine: 1,
|
StartLine: 1,
|
||||||
EndLine: 2,
|
EndLine: 2,
|
||||||
@@ -63,7 +63,11 @@ func TestWriteSarif(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var vc config.ViperConfig
|
var vc config.ViperConfig
|
||||||
viper.Unmarshal(&vc)
|
err = viper.Unmarshal(&vc)
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
|
||||||
cfg, err := vc.Translate()
|
cfg, err := vc.Translate()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Error(err)
|
t.Error(err)
|
||||||
|
|||||||
+8
@@ -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
@@ -4,5 +4,5 @@ title = "gitleaks config"
|
|||||||
id = "discord-api-key"
|
id = "discord-api-key"
|
||||||
description = "Discord API key"
|
description = "Discord API key"
|
||||||
regex = '''(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-h0-9]{64})['\"]'''
|
regex = '''(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-h0-9]{64})['\"]'''
|
||||||
entropyGroup = 5
|
secretGroup = 5
|
||||||
entropy = 3.5
|
entropy = 3.5
|
||||||
Vendored
+1
-1
@@ -4,5 +4,5 @@ title = "gitleaks config"
|
|||||||
id = "discord-api-key"
|
id = "discord-api-key"
|
||||||
description = "Discord API key"
|
description = "Discord API key"
|
||||||
regex = '''(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-h0-9]{64})['\"]'''
|
regex = '''(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-h0-9]{64})['\"]'''
|
||||||
entropyGroup = 3
|
secretGroup = 3
|
||||||
entropy = 3.5
|
entropy = 3.5
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
title = "gitleaks config"
|
||||||
|
# https://learnxinyminutes.com/docs/toml/ for toml reference
|
||||||
|
|
||||||
|
[[rules]]
|
||||||
|
id = "pypi-upload-token"
|
||||||
|
description = "PyPI upload token"
|
||||||
|
regex = '''pypi-AgEIcHlwaS5vcmc[A-Za-z0-9\-_]{50,1000}'''
|
||||||
|
tags = ["key", "pypi"]
|
||||||
Vendored
+1
-1
@@ -5,4 +5,4 @@ description = "Generic API Key"
|
|||||||
id = "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})['\"]'''
|
regex = '''(?i)((key|api|token|secret|password)[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([0-9a-zA-Z\-_=]{8,64})['\"]'''
|
||||||
entropy = 3.7
|
entropy = 3.7
|
||||||
entropyGroup = 4
|
secretGroup = 4
|
||||||
+28
-1
@@ -6,4 +6,31 @@ id = "generic-api-key"
|
|||||||
regex = '''(?i)((key|api|token|secret|password)[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([0-9a-zA-Z\-_=]{8,64})['\"]'''
|
regex = '''(?i)((key|api|token|secret|password)[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([0-9a-zA-Z\-_=]{8,64})['\"]'''
|
||||||
path = '''.py'''
|
path = '''.py'''
|
||||||
entropy = 3.7
|
entropy = 3.7
|
||||||
entropyGroup = 4
|
secretGroup = 4
|
||||||
|
|
||||||
|
[allowlist]
|
||||||
|
description = "global allow lists"
|
||||||
|
regexes = [
|
||||||
|
'''219-09-9999''',
|
||||||
|
'''078-05-1120''',
|
||||||
|
'''(9[0-9]{2}|666)-\d{2}-\d{4}''',
|
||||||
|
'''process''',
|
||||||
|
'''getenv''',
|
||||||
|
'''\.env''',
|
||||||
|
'''env\(''',
|
||||||
|
'''env\.''',
|
||||||
|
'''setting''',
|
||||||
|
'''load''',
|
||||||
|
'''token''',
|
||||||
|
'''password''',
|
||||||
|
'''secret''',
|
||||||
|
'''api\_key''',
|
||||||
|
'''apikey''',
|
||||||
|
'''api\-key''',
|
||||||
|
]
|
||||||
|
paths = [
|
||||||
|
'''gitleaks.toml''',
|
||||||
|
'''(.*?)(jpg|gif|doc|pdf|bin|svg|socket)$''',
|
||||||
|
'''(go.mod|go.sum)$'''
|
||||||
|
]
|
||||||
|
|
||||||
+1
-1
@@ -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
|
test-rule,0000000000000000,auth.py,a secret,line containing secret,1,2,1,2,John Doe,opps,10-19-2003,johndoe@gmail.com
|
||||||
|
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
[]
|
||||||
+1
-1
@@ -5,7 +5,7 @@
|
|||||||
"EndLine": 2,
|
"EndLine": 2,
|
||||||
"StartColumn": 1,
|
"StartColumn": 1,
|
||||||
"EndColumn": 2,
|
"EndColumn": 2,
|
||||||
"Context": "line containing secret",
|
"Match": "line containing secret",
|
||||||
"Secret": "a secret",
|
"Secret": "a secret",
|
||||||
"File": "auth.py",
|
"File": "auth.py",
|
||||||
"Commit": "0000000000000000",
|
"Commit": "0000000000000000",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0-rtm.5.json",
|
"$schema": "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0-rtm.5.json",
|
||||||
"version": "v8.0.0",
|
"version": "2.1.0",
|
||||||
"runs": [
|
"runs": [
|
||||||
{
|
{
|
||||||
"tool": {
|
"tool": {
|
||||||
|
|||||||
Vendored
BIN
Binary file not shown.
Reference in new issue
Block a user