Compare commits

...
40 Commits
Author SHA1 Message Date
zricethezav 5d7b7718ec splitting out github rules and retabbing 2021-04-09 14:07:23 -04:00
Zachary Rice 190877a24b Pypi GitHub rules (#546)
* adding pypi and basic azure rules

* Adding new github format
2021-04-08 16:34:08 -04:00
mercurieteandmercuriete 144362b972 docs(Dockerfile): Fix example of usage on Dockerfile (#545)
* Closes #544

Co-authored-by: mercuriete <mercuriete@gmail.com>
2021-04-08 10:23:03 -04:00
Zachary Rice d353ac5108 Update README.md 2021-04-06 14:42:44 -04:00
Zachary Rice a27a08904a Update README.md 2021-03-05 16:40:07 -05:00
Zachary Rice 5ef4e336ce Update README.md 2021-03-05 16:39:23 -05:00
zricethezav 78f2c46517 Consistency in options 2021-03-05 16:19:24 -05:00
Kai bdcb9e33a8 Update SARIF output to return empty array if no results were found (#530) 2021-03-05 16:10:53 -05:00
Zachary Rice 6e4e9df55f stricter regex for github token (#535) 2021-03-05 16:10:04 -05:00
Zachary Rice b3bed5658d adding recover for patch generation (#534) 2021-03-05 16:00:41 -05:00
eddie-northcutt-wfp0 a10ae91ba7 v7.x Update - Add ability to append repo configurations, and user supplied configurations to the specified or default configuration (#487)
* Update merge configuration changes for  Gitleaks 7.x

* Change merge to append, and did some clean up
2021-03-05 15:09:10 -05:00
Zachary Rice a8dbc7f107 Update README.md 2021-02-25 16:33:24 -05:00
erikaweir 4544156b44 Copy edits to Readme.md (#529)
* Update README.md

* Update README.md

* Update README.md
2021-02-19 18:01:31 -05:00
Rahul sharma b52e8c9c7c Slack Webhook Match (#527) 2021-02-19 13:05:25 -05:00
rui 0ce1249b95 chore(deps): bump go to v1.16 (#525)
Signed-off-by: Rui Chen <rui@chenrui.dev>
2021-02-18 09:14:10 -05:00
Zachary Rice 3932ed6baf --no-git should report relative path to --path (#519) 2021-02-03 13:48:59 -05:00
Zachary Rice 981b636920 gitter chat 2021-02-02 17:27:24 -05:00
Kai c8e15c731a Always generate a report if --report is enabled (#508) 2021-01-26 07:59:51 -05:00
Zachary Rice 901f932a89 Add file type checking for unstaged commits (#512) 2021-01-22 11:49:21 -05:00
seb-elttamandSeb Elttam c0a9580a65 Fix dotgit regex again (#507)
* fix dotgit regex again

* Revert accidentally modified files

Co-authored-by: Seb Elttam <seb@elttam.com>
2021-01-21 15:31:21 -05:00
Paweł Kowalczyk 8be91eea5d Add exit code 1 on invalid usage, fixes #500 (#501) 2021-01-10 09:34:31 -05:00
Zachary Rice 1c6f2252b8 Update README.md 2020-12-11 20:55:32 -05:00
Zachary RiceandZach Rice 58d130c5f3 Quiet flag (#491)
* Adding a quiet option

* better description

Co-authored-by: Zach Rice <zrice@gitlab.com>
2020-12-11 09:56:09 -05:00
Zachary Rice 091ea81e68 nosec gosec (#490) 2020-12-10 22:32:32 -05:00
Zachary Rice f036dce6ab Dotgit bug (#488)
* fix allowlist bug

* Adding new repo for testing allowlisting

* adding additional constraints on the dotgit regex
2020-12-10 17:41:26 -05:00
Zachary Rice 2d58f1f94e Files at commit allow list bug (#485)
* fix allowlist bug

* Adding new repo for testing allowlisting

* Adding missing allowlist checks for commits and files/paths
2020-12-09 15:55:01 -05:00
Zachary Rice 86cfe0848b Allow list bugs (#484)
* fix allowlist bug
2020-12-09 13:21:15 -05:00
Zachary Rice 973d74e592 Update README.md 2020-12-08 20:55:53 -05:00
Zachary Rice 3909ebe03b Exit code update, introduce leaks-exit-code flag (#481) 2020-12-08 17:41:02 -05:00
Zachary Rice 65f42020af Go repo scan (#480)
* Real fast

* Addressing some golint stuff
2020-12-08 17:22:28 -05:00
Zachary Rice 65a91ae976 Removing base scanner (#477) 2020-12-08 09:24:38 -05:00
Zachary Rice 7db08bfd90 Bugs v7 (#475)
* fixing some v7 bugs
2020-12-05 11:57:43 -05:00
Matt Bartel af26553292 Performance improvement for uncommitted files (#463)
* attempt to use 'git status' when scanning uncommitted files

* fix comment

* correct copy/rename handling

* use 'git status' for unstaged changes
2020-12-04 18:08:27 -05:00
Zachary Rice d5e431e7d4 Update README.md 2020-12-03 17:20:46 -05:00
Zachary Rice 54ba3ec377 Update README.md 2020-12-03 17:09:59 -05:00
Zachary Rice 656ef1c9a7 Update README.md 2020-12-03 16:56:16 -05:00
zricethezav b8accd7273 rm unimplemented cleanpath option 2020-12-03 15:43:06 -05:00
zricethezav 238c31beaa Merge branch 'master' of github.com:zricethezav/gitleaks into master 2020-12-03 10:08:41 -05:00
Zachary Rice eb31190f31 Removing limiting line/offender length (#470) 2020-12-03 09:32:57 -05:00
zricethezav 389d45e380 Removing limiting line/offender length 2020-12-03 09:28:30 -05:00
70 changed files with 2156 additions and 1039 deletions

No files matched your search

+4 -4
View File
@@ -1,8 +1,8 @@
language: go
go:
- 1.14.x
- 1.16.x
services:
- docker
- docker
script:
- make test
- make security-scan
- make test
- make security-scan
+1 -1
View File
@@ -12,6 +12,6 @@ ENTRYPOINT ["gitleaks"]
# How to use me :
# docker build -t gitleaks .
# docker run --rm --name=gitleaks gitleaks --repo=https://github.com/zricethezav/gitleaks
# docker run --rm --name=gitleaks gitleaks --repo-url=https://github.com/zricethezav/gitleaks
# This will check for secrets in https://github.com/zricethezav/gitleaks
+215 -46
View File
@@ -2,24 +2,30 @@
<img alt="gitleaks" src="https://raw.githubusercontent.com/zricethezav/gifs/master/gitleakslogo.png" height="70" />
<p align="center">
<a href="https://travis-ci.org/zricethezav/gitleaks"><img alt="Travis" src="https://img.shields.io/travis/zricethezav/gitleaks/master.svg?style=flat-square"></a>
<a href="https://gitter.im/gitleaks/gitleaks"><img alt="Travis" src="https://badges.gitter.im/gitleaks/gitleaks.svg?style=flat-square"></a>
</p>
</p>
Gitleaks is a SAST tool for detecting hardcoded secrets like passwords, api keys, and tokens in git repos. Gitleaks aims to be the **easy-to-use, all-in-one solution** for finding secrets, past or present, in your code.
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 finding secrets, past or present, in your code.
### Introduction Video
<p align="left">
<a href="https://www.youtube.com/watch?v=VUq2eII20S4"><img alt="intro" src="https://img.youtube.com/vi/VUq2eII20S4/maxresdefault.jpg" height="200"></a>
</p>
### Features:
- Scan for [commited](https://github.com/zricethezav/gitleaks/wiki/Scanning) secrets
- Scan for [uncommitted](https://github.com/zricethezav/gitleaks/wiki/Scanning#uncommitted-changes-scan) secrets as part of shifting security left
- Scan for entire directories and files
- Available [Github Action](https://github.com/marketplace/actions/gitleaks)
- [Custom rules](https://github.com/zricethezav/gitleaks/wiki/Configuration) via toml configuration
- High performance using [go-git](https://github.com/go-git/go-git)
- Scan for [commited](https://github.com/zricethezav/gitleaks#Scanning) secrets
- Scan for [unstaged](https://github.com/zricethezav/gitleaks#scan-unstaged-changes) secrets to shift security left
- Scan [directories and files](https://github.com/zricethezav/gitleaks#scan-local-directory)
- Run [Gitleaks Action](https://github.com/marketplace/actions/gitleaks) in your CI/CD pipeline
- [Custom rules](https://github.com/zricethezav/gitleaks#configuration) via toml configuration
- Increased performance using [go-git](https://github.com/go-git/go-git)
- JSON, SARIF, and CSV reporting
- Private repo scans using key or password based authentication
### Installation
Written in Go, gitleaks is available in binary form for many popular platforms and OS types from the [releases page](https://github.com/zricethezav/gitleaks/releases). Alternatively, executed via Docker or it can be installed using Go directly.
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).
##### MacOS
@@ -44,45 +50,209 @@ Usage:
gitleaks [OPTIONS]
Application Options:
-v, --verbose Show verbose output from scan
-r, --repo-url= Repository URL
-p, --path= Path to directory (repo if contains .git) or file
-c, --config-path= Path to config
--repo-config-path= Path to gitleaks config relative to repo root
--clone-path= Path to clone repo to disk
--clone-cleanup= Deletes cloned repo after scan
--version Version number
--username= Username for git repo
--password= Password for git repo
--access-token= Access token for git repo
--threads= Maximum number of threads gitleaks spawns
--ssh-key= Path to ssh key used for auth
--unstaged Run gitleaks on unstaged code
--branch= Branch to scan
--redact Redact secrets from log messages and leaks
--debug Log debug messages
--no-git Treat git repos as plain directories and scan those
files
-o, --report= Report output path
-f, --format= JSON, CSV, SARIF (default: json)
--files-at-commit= Sha of commit to scan all files at commit
--commit= Sha of commit to scan or "latest" to scan the last
commit of the repository
--commits= Comma separated list of a commits to scan
--commits-file= Path to file of line separated list of commits to scan
--commit-from= Commit to start scan from
--commit-to= Commit to stop scan
--commit-since= Scan commits more recent than a specific date. Ex:
'2006-01-02' or '2006-01-02T15:04:05-0700' format.
--commit-until= Scan commits older than a specific date. Ex:
'2006-01-02' or '2006-01-02T15:04:05-0700' format.
--depth= Number of commits to scan
-v, --verbose Show verbose output from scan
-q, --quiet Sets log level to error and only output leaks, one json object per line
-r, --repo-url= Repository URL
-p, --path= Path to directory (repo if contains .git) or file
-c, --config-path= Path to config
--repo-config-path= Path to gitleaks config relative to repo root
--clone-path= Path to clone repo to disk
--version Version number
--username= Username for git repo
--password= Password for git repo
--access-token= Access token for git repo
--threads= Maximum number of threads gitleaks spawns
--ssh-key= Path to ssh key used for auth
--unstaged Run gitleaks on unstaged code
--branch= Branch to scan
--redact Redact secrets from log messages and leaks
--debug Log debug messages
--no-git Treat git repos as plain directories and scan those files
--leaks-exit-code= Exit code when leaks have been encountered (default: 1)
--append-repo-config Append the provided or default config with the repo config.
--additional-config= Path to an additional gitleaks config to append with an existing config. Can be used with --append-repo-config to append up to three configurations
-o, --report= Report output path
-f, --format= JSON, CSV, SARIF (default: json)
--files-at-commit= Sha of commit to scan all files at commit
--commit= Sha of commit to scan or "latest" to scan the last commit of the repository
--commits= Comma separated list of a commits to scan
--commits-file= Path to file of line separated list of commits to scan
--commit-from= Commit to start scan from
--commit-to= Commit to stop scan
--commit-since= Scan commits more recent than a specific date. Ex: '2006-01-02' or '2006-01-02T15:04:05-0700' format.
--commit-until= Scan commits older than a specific date. Ex: '2006-01-02' or '2006-01-02T15:04:05-0700' format.
--depth= Number of commits to scan
Help Options:
-h, --help Show this help message
-h, --help Show this help message
```
### [Scanning](https://www.youtube.com/watch?v=WUzpRL8mKCk)
#### Basic repo-url scan:
This scans the entire history of tests/secrets and logs leaks as they are encountered `-v`/`--verbose` being set.
```
gitleaks --repo-url=https://github.com/my-insecure/repo -v
```
#### Basic repo-url scan output to a report:
If you want the report in sarif or csv you can set the `-f/--format` option
```
gitleaks --repo-url=https://github.com/my-insecure/repo -v --report=my-report.json
```
#### Scan specific commit:
```
gitleaks --repo-url=https://github.com/my-insecure/repo --commit=commit-sha -v
```
#### Scan local repo:
```
gitleaks --path=path/to/local/repo -v
```
#### Scan repos contained in a parent directory:
If you have `repo1`, `repo2`, `repo3` all under `path/to/local`, gitleaks will discover and scan those repos.
```
gitleaks --path=path/to/local/ -v
```
#### Scan local directory:
If you want to scan the current contents of a repo, ignoring git alltogether. You can use the `--no-git` option to do this.
```
gitleaks --path=path/to/local/repo -v --no-git
```
#### Scan a file:
Or if you want to scan a single file using gitleaks rules. You can do this by specifying the file in `--path` and including the `--no-git` option.
```
gitleaks --path=path/to/local/repo/main.go -v --no-git
```
#### Scan unstaged changes:
If you have unstaged changes are are currently at the root of the repo, you can run `gitleaks` with no `--path` or `--repo-url` specified which will run a scan on your uncommitted changes. Or if you want to specify a
path, you can run:
```
gitleaks --path=path/to/local/repo -v --unstaged
```
### Configuration
Provide your own gitleaks configurations with `--config-path` or `--repo-config-path`. `--config-path` loads a local gitleaks configuration whereas `--repo-config-path` will load a configuration present just in the repo you want to scan. For example, `gitleaks --repo-config-path=".github/gitleaks.config"`.
The default configuration Gitleaks uses is located [here](https://github.com/zricethezav/gitleaks/blob/master/config/default.go). More configuration examples can be seen [here](https://github.com/zricethezav/gitleaks/tree/master/examples). Configuration files will contain a few different toml tables. Further explanation is provided below.
### Rules summary
The rules are written in [TOML](https://github.com/toml-lang/toml) as defined in [TomlLoader struct](https://github.com/zricethezav/gitleaks/blob/master/config/config.go#L57-L87), and can be summarized as:
```
[[rules]]
description = "a string describing one of many rule in this config"
regex = '''one-go-style-regex-for-this-rule'''
file = '''a-file-name-regex'''
path = '''a-file-path-regex'''
tags = ["tag","another tag"]
[[rules.entropies]] # note these are strings, not floats
Min = "3.5"
Max = "4.5"
Group = "1"
[rules.allowlist]
description = "a string"
files = ['''one-file-name-regex''']
commits = [ "commit-A", "commit-B"]
paths = ['''one-file-path-regex''']
regexes = ['''one-regex-within-the-already-matched-regex''']
[allowlist]
description = "a description string for a global allowlist config"
commits = [ "commit-A", "commit-B"]
files = [ '''file-regex-a''', '''file-regex-b''']
paths = [ '''path-regex-a''', '''path-regex-b''']
repos = [ '''repo-regex-a''', '''repo-regex-b''']
regexes = ['''one-regex-within-the-already-matched-regex''']
```
Regular expressions are _NOT_ the full Perl set, so there are no look-aheads or look-behinds.
### Examples
#### Example 1
The first and most commonly edited array of tables is `[[rules]]`. This is where you can define your own custom rules for Gitleaks to use while scanning repos. Example keys/values within the `[[rules]]` table:
```
[[rules]]
description = "generic secret regex"
regex = '''secret(.{0,20})([0-9a-zA-Z-._{}$\/\+=]{20,120})'''
tags = ["secret", "example"]
```
#### Example 2
We can also **combine** regular expressions AND entropy:
```
[[rules]]
description = "entropy and regex example"
regex = '''secret(.{0,20})['|"]([0-9a-zA-Z-._{}$\/\+=]{20,120})['|"]'''
[[rules.Entropies]]
Min = "4.5"
Max = "4.7"
```
Translating this rule to English, this rule states: "if we encounter a line of code that matches *regex* AND the line falls within the bounds of a [Shannon entropy](https://en.wikipedia.org/wiki/Entropy_(information_theory)) of 4.5 to 4.7, then the line must be a leak"
#### Example 3
Let's compare two lines of code:
```
aws_secret='ABCDEF+c2L7yXeGvUyrPgYsDnWRRC1AYEXAMPLE'
```
and
```
aws_secret=os.getenv('AWS_SECRET_ACCESS_KEY')
```
The first line of code is an example of a hardcoded secret being assigned to the variable `aws_secret`. The second line of code is an example of a secret being assigned via env variables to `aws_secret`. Both would be caught by the rule defined in *example 2* but only the first line is actually a leak. Let's define a new rule that will capture only the first line of code. We can do this by combining regular expression **groups** and entropy.
```
[[rules]]
description = "entropy and regex example"
regex = '''secret(.{0,20})['|"]([0-9a-zA-Z-._{}$\/\+=]{20,120})['|"]'''
[[rules.Entropies]]
Min = "4.5"
Max = "4.7"
Group = "2"
```
Notice how we added `Group = "2"` to this rule. We can translate this rule to English: "if we encounter a line of code that matches regex AND the entropy of the *second regex group* falls within the bounds of a [Shannon entropy](https://en.wikipedia.org/wiki/Entropy_(information_theory)) of 4.5 to 4.7, then the line must be a leak"
### Example 4: Using allowlist regex
The proper Perl regex for AWS secret keys is
`(?<![A-Za-z0-9\\+])[A-Za-z0-9\\+=]{40}(?![A-Za-z0-9\\+=])`
but the Go library doesn't do lookahead/lookbehind, so
we'll look for 40 base64 characters, then allowlist
if they're embedded in a string of 41 base64 characters, that is,
without any delimiters. This will make a false negative for, say:
```
foo=+awsSecretAccessKeyisBase64=40characters
```
So you can use the following to effectively create the proper Perl regex:
```
[[rules]]
description = "AWS secret key regardless of labeling"
regex = '''.?[A-Za-z0-9\\+=]{40}.?'''
[rules.allowlist]
description = "41 base64 characters is not an AWS secret key"
regexes = ['''[A-Za-z0-9\\+=]{41}''']
```
### Exit Codes
You can always set the exit code when leaves are encountered with the `--leaks-exit-code` flag. Default exit codes below:
```
0 - no leaks present
1 - leaks or error encountered
```
### Sponsors ❤️
#### Corporate Sponsors
[![gammanet](https://gammanet.com/assets/images/new-design/gamma-logo.png)](https://gammanet.com/?utm_source=gitleaks&utm_medium=homepage&utm_campaign=gitleaks_promotion)
@@ -92,9 +262,8 @@ Gamma proactively detects and remediates data leaks across cloud apps. Scan your
#### Individual Sponsors
These users are [sponsors](https://github.com/sponsors/zricethezav) of gitleaks:
[![Adam Shannon](https://github.com/adamdecaf.png?size=50)](https://github.com/adamdecaf) |
---|
----
- [Adam Shannon](https://github.com/adamdecaf)
- [ProjectDiscovery](https://projectdiscovery.io/#/)
#### Logo Attribution
+60
View File
@@ -0,0 +1,60 @@
package config
import (
"regexp"
)
// used for ignoring .git directories when the --no-git flag is set
// related issue: https://github.com/zricethezav/gitleaks/issues/486
const dotGit = `/\.git/`
// AllowList is struct containing items that if encountered will allowlist
// a commit/line of code that would be considered a leak.
type AllowList struct {
Description string
Regexes []*regexp.Regexp
Commits []string
Files []*regexp.Regexp
Paths []*regexp.Regexp
Repos []*regexp.Regexp
}
// CommitAllowed checks if a commit is allowlisted
func (a *AllowList) CommitAllowed(commit string) bool {
for _, hash := range a.Commits {
if commit == hash {
return true
}
}
return false
}
// FileAllowed checks if a file is allowlisted
func (a *AllowList) FileAllowed(fileName string) bool {
return anyRegexMatch(fileName, a.Files)
}
// PathAllowed checks if a path is allowlisted
func (a *AllowList) PathAllowed(filePath string) bool {
return anyRegexMatch(filePath, a.Paths)
}
// RegexAllowed checks if a regex is allowlisted
func (a *AllowList) RegexAllowed(content string) bool {
return anyRegexMatch(content, a.Regexes)
}
// RepoAllowed checks if a regex is allowlisted
func (a *AllowList) RepoAllowed(repo string) bool {
return anyRegexMatch(repo, a.Repos)
}
// IgnoreDotGit appends a `\.git` rule to ignore all .git paths. This is used for --no-git scans
func (a *AllowList) IgnoreDotGit() error {
re, err := regexp.Compile(dotGit)
if err != nil {
return err
}
a.Paths = append(a.Paths, re)
return nil
}
+48 -44
View File
@@ -2,7 +2,10 @@ package config
import (
"fmt"
"io"
"os"
"path"
"path/filepath"
"regexp"
"strconv"
@@ -13,15 +16,11 @@ import (
log "github.com/sirupsen/logrus"
)
// AllowList is struct containing items that if encountered will allowlist
// a commit/line of code that would be considered a leak.
type AllowList struct {
Description string
Regexes []*regexp.Regexp
Commits []string
Files []*regexp.Regexp
Paths []*regexp.Regexp
Repos []*regexp.Regexp
// Config is a composite struct of Rules and Allowlists
// Each Rule contains a description, regular expression, tags, and allowlists if available
type Config struct {
Rules []Rule
Allowlist AllowList
}
// Entropy represents an entropy range
@@ -31,29 +30,6 @@ type Entropy struct {
Group int
}
// Rule is a struct that contains information that is loaded from a gitleaks config.
// This struct is used in the Config struct as an array of Rules and is iterated
// over during an scan. Each rule will be checked. If a regex match is found AND
// that match is not allowlisted (globally or locally), then a leak will be appended
// to the final scan report.
type Rule struct {
Description string
Regex *regexp.Regexp
File *regexp.Regexp
Path *regexp.Regexp
ReportGroup int
Tags []string
AllowList AllowList
Entropies []Entropy
}
// Config is a composite struct of Rules and Allowlists
// Each Rule contains a description, regular expression, tags, and allowlists if available
type Config struct {
Rules []Rule
Allowlist AllowList
}
// TomlAllowList is a struct used in the TomlLoader that loads in allowlists from
// specific rules or globally at the top level config
type TomlAllowList struct {
@@ -276,13 +252,7 @@ func LoadRepoConfig(repo *git.Repository, repoConfig string) (Config, error) {
if err != nil {
return Config{}, err
}
var tomlLoader TomlLoader
_, err = toml.DecodeReader(r, &tomlLoader)
if err != nil {
return Config{}, err
}
return tomlLoader.Parse()
return parseTomlFile(r)
}
log.Debug("attempting to load repo config from bare worktree, this may use an old config")
@@ -301,15 +271,49 @@ func LoadRepoConfig(repo *git.Repository, repoConfig string) (Config, error) {
return Config{}, err
}
var tomlLoader TomlLoader
r, err := f.Reader()
if err != nil {
return Config{}, err
}
_, err = toml.DecodeReader(r, &tomlLoader)
if err != nil {
return Config{}, err
}
return parseTomlFile(r)
}
// LoadAdditionalConfig Accepts a path to a gitleaks config and returns a Config struct
func LoadAdditionalConfig(repoConfig string) (Config, error) {
file, err := os.Open(filepath.Clean(repoConfig))
if err != nil {
return Config{}, err
}
return parseTomlFile(file)
}
// AppendConfig Accepts a Config struct and will append those fields to this Config Struct's fields
func (config *Config) AppendConfig(configToBeAppended Config) Config {
newAllowList := AllowList{
Description: "Appended Configuration",
Commits: append(config.Allowlist.Commits, configToBeAppended.Allowlist.Commits...),
Files: append(config.Allowlist.Files, configToBeAppended.Allowlist.Files...),
Paths: append(config.Allowlist.Paths, configToBeAppended.Allowlist.Paths...),
Regexes: append(config.Allowlist.Regexes, configToBeAppended.Allowlist.Regexes...),
Repos: append(config.Allowlist.Repos, configToBeAppended.Allowlist.Repos...),
}
return Config{
Rules: append(config.Rules, configToBeAppended.Rules...),
Allowlist: newAllowList,
}
}
// takes a File, makes sure it is a valid config, and parses it
func parseTomlFile(f io.Reader) (Config, error) {
var tomlLoader TomlLoader
_, err := toml.DecodeReader(f, &tomlLoader)
if err != nil {
log.Errorf("Unable to read gitleaks config. Using defaults. Error: %s", err)
return Config{}, err
}
return tomlLoader.Parse()
}
+70
View File
@@ -211,3 +211,73 @@ func writeTestConfig(toml string) (string, error) {
return tmpfile.Name(), nil
}
func TestAppendingConfiguration(t *testing.T) {
testRegexA, _ := regexp.Compile("a")
testRegexB, _ := regexp.Compile("b")
allowListA := AllowList{
Description: "Test Description",
Commits: []string{"a"},
Files: []*regexp.Regexp{testRegexA},
Paths: []*regexp.Regexp{testRegexA},
Regexes: []*regexp.Regexp{testRegexA},
Repos: []*regexp.Regexp{testRegexA},
}
allowListB := AllowList{
Description: "Test Description",
Commits: []string{"b"},
Files: []*regexp.Regexp{testRegexB},
Paths: []*regexp.Regexp{testRegexB},
Regexes: []*regexp.Regexp{testRegexB},
Repos: []*regexp.Regexp{testRegexB},
}
ruleA := Rule{Description: "a"}
ruleB := Rule{Description: "b"}
rulesA := []Rule{ruleA}
rulesB := []Rule{ruleB}
cfgA := Config{
Rules: rulesA,
Allowlist: allowListA,
}
cfgB := Config{
Rules: rulesB,
Allowlist: allowListB,
}
cfgAppended := cfgA.AppendConfig(cfgB)
if !(len(cfgAppended.Rules) == 2) {
t.Errorf("Length of Appended Rules = %d; want 2", len(cfgAppended.Rules))
}
if !(len(cfgAppended.Allowlist.Commits) == 2) {
t.Errorf("Length of Appended Allowed Commits = %d; want 2", len(cfgAppended.Allowlist.Commits))
}
if !(len(cfgAppended.Allowlist.Files) == 2) {
t.Errorf("Length of Appended Allowed Files = %d; want 2", len(cfgAppended.Allowlist.Files))
}
if !(len(cfgAppended.Allowlist.Paths) == 2) {
t.Errorf("Length of Appended Allowed Paths = %d; want 2", len(cfgAppended.Allowlist.Paths))
}
if !(len(cfgAppended.Allowlist.Regexes) == 2) {
t.Errorf("Length of Appended Allowed Regexes = %d; want 2", len(cfgAppended.Allowlist.Regexes))
}
if !(len(cfgAppended.Allowlist.Repos) == 2) {
t.Errorf("Length of Appended Allowed Repos = %d; want 2", len(cfgAppended.Allowlist.Repos))
}
if cfgAppended.Allowlist.Description != "Appended Configuration" {
t.Errorf("Allow List Description is = \"%s\"; want \"Appended Configuration\"", cfgAppended.Allowlist.Description)
}
}
+111 -94
View File
@@ -7,158 +7,175 @@ const DefaultConfig = `
title = "gitleaks config"
[[rules]]
description = "AWS Access Key"
regex = '''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
tags = ["key", "AWS"]
description = "AWS Access Key"
regex = '''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
tags = ["key", "AWS"]
[[rules]]
description = "AWS Secret Key"
regex = '''(?i)aws(.{0,20})?(?-i)['\"][0-9a-zA-Z\/+]{40}['\"]'''
tags = ["key", "AWS"]
description = "AWS Secret Key"
regex = '''(?i)aws(.{0,20})?(?-i)['\"][0-9a-zA-Z\/+]{40}['\"]'''
tags = ["key", "AWS"]
[[rules]]
description = "AWS MWS key"
regex = '''amzn\.mws\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'''
tags = ["key", "AWS", "MWS"]
description = "AWS MWS key"
regex = '''amzn\.mws\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'''
tags = ["key", "AWS", "MWS"]
[[rules]]
description = "Facebook Secret Key"
regex = '''(?i)(facebook|fb)(.{0,20})?(?-i)['\"][0-9a-f]{32}['\"]'''
tags = ["key", "Facebook"]
description = "Facebook Secret Key"
regex = '''(?i)(facebook|fb)(.{0,20})?(?-i)['\"][0-9a-f]{32}['\"]'''
tags = ["key", "Facebook"]
[[rules]]
description = "Facebook Client ID"
regex = '''(?i)(facebook|fb)(.{0,20})?['\"][0-9]{13,17}['\"]'''
tags = ["key", "Facebook"]
description = "Facebook Client ID"
regex = '''(?i)(facebook|fb)(.{0,20})?['\"][0-9]{13,17}['\"]'''
tags = ["key", "Facebook"]
[[rules]]
description = "Twitter Secret Key"
regex = '''(?i)twitter(.{0,20})?[0-9a-z]{35,44}'''
tags = ["key", "Twitter"]
description = "Twitter Secret Key"
regex = '''(?i)twitter(.{0,20})?[0-9a-z]{35,44}'''
tags = ["key", "Twitter"]
[[rules]]
description = "Twitter Client ID"
regex = '''(?i)twitter(.{0,20})?[0-9a-z]{18,25}'''
tags = ["client", "Twitter"]
description = "Twitter Client ID"
regex = '''(?i)twitter(.{0,20})?[0-9a-z]{18,25}'''
tags = ["client", "Twitter"]
[[rules]]
description = "Github"
regex = '''(?i)github(.{0,20})?(?-i)[0-9a-zA-Z]{35,40}'''
tags = ["key", "Github"]
description = "Github Personal Access Token"
regex = '''ghp_[0-9a-zA-Z]{36}'''
tags = ["key", "Github"]
[[rules]]
description = "Github OAuth Access Token"
regex = '''gho_[0-9a-zA-Z]{36}'''
tags = ["key", "Github"]
[[rules]]
description = "Github App Token"
regex = '''(ghu|ghs)_[0-9a-zA-Z]{36}'''
tags = ["key", "Github"]
[[rules]]
description = "Github Refresh Token"
regex = '''ghr_[0-9a-zA-Z]{76}'''
tags = ["key", "Github"]
[[rules]]
description = "LinkedIn Client ID"
regex = '''(?i)linkedin(.{0,20})?(?-i)[0-9a-z]{12}'''
tags = ["client", "LinkedIn"]
description = "LinkedIn Client ID"
regex = '''(?i)linkedin(.{0,20})?(?-i)[0-9a-z]{12}'''
tags = ["client", "LinkedIn"]
[[rules]]
description = "LinkedIn Secret Key"
regex = '''(?i)linkedin(.{0,20})?[0-9a-z]{16}'''
tags = ["secret", "LinkedIn"]
description = "LinkedIn Secret Key"
regex = '''(?i)linkedin(.{0,20})?[0-9a-z]{16}'''
tags = ["secret", "LinkedIn"]
[[rules]]
description = "Slack"
regex = '''xox[baprs]-([0-9a-zA-Z]{10,48})?'''
tags = ["key", "Slack"]
description = "Slack"
regex = '''xox[baprs]-([0-9a-zA-Z]{10,48})?'''
tags = ["key", "Slack"]
[[rules]]
description = "Asymmetric Private Key"
regex = '''-----BEGIN ((EC|PGP|DSA|RSA|OPENSSH) )?PRIVATE KEY( BLOCK)?-----'''
tags = ["key", "AsymmetricPrivateKey"]
description = "Asymmetric Private Key"
regex = '''-----BEGIN ((EC|PGP|DSA|RSA|OPENSSH) )?PRIVATE KEY( BLOCK)?-----'''
tags = ["key", "AsymmetricPrivateKey"]
[[rules]]
description = "Google API key"
regex = '''AIza[0-9A-Za-z\\-_]{35}'''
tags = ["key", "Google"]
description = "Google API key"
regex = '''AIza[0-9A-Za-z\\-_]{35}'''
tags = ["key", "Google"]
[[rules]]
description = "Google (GCP) Service Account"
regex = '''"type": "service_account"'''
tags = ["key", "Google"]
description = "Google (GCP) Service Account"
regex = '''"type": "service_account"'''
tags = ["key", "Google"]
[[rules]]
description = "Heroku API key"
regex = '''(?i)heroku(.{0,20})?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'''
tags = ["key", "Heroku"]
description = "Heroku API key"
regex = '''(?i)heroku(.{0,20})?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'''
tags = ["key", "Heroku"]
[[rules]]
description = "MailChimp API key"
regex = '''(?i)(mailchimp|mc)(.{0,20})?[0-9a-f]{32}-us[0-9]{1,2}'''
tags = ["key", "Mailchimp"]
description = "MailChimp API key"
regex = '''(?i)(mailchimp|mc)(.{0,20})?[0-9a-f]{32}-us[0-9]{1,2}'''
tags = ["key", "Mailchimp"]
[[rules]]
description = "Mailgun API key"
regex = '''((?i)(mailgun|mg)(.{0,20})?)?key-[0-9a-z]{32}'''
tags = ["key", "Mailgun"]
description = "Mailgun API key"
regex = '''((?i)(mailgun|mg)(.{0,20})?)?key-[0-9a-z]{32}'''
tags = ["key", "Mailgun"]
[[rules]]
description = "PayPal Braintree access token"
regex = '''access_token\$production\$[0-9a-z]{16}\$[0-9a-f]{32}'''
tags = ["key", "Paypal"]
description = "PayPal Braintree access token"
regex = '''access_token\$production\$[0-9a-z]{16}\$[0-9a-f]{32}'''
tags = ["key", "Paypal"]
[[rules]]
description = "Picatic API key"
regex = '''sk_live_[0-9a-z]{32}'''
tags = ["key", "Picatic"]
description = "Picatic API key"
regex = '''sk_live_[0-9a-z]{32}'''
tags = ["key", "Picatic"]
[[rules]]
description = "SendGrid API Key"
regex = '''SG\.[\w_]{16,32}\.[\w_]{16,64}'''
tags = ["key", "SendGrid"]
description = "SendGrid API Key"
regex = '''SG\.[\w_]{16,32}\.[\w_]{16,64}'''
tags = ["key", "SendGrid"]
[[rules]]
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}'''
tags = ["key", "slack"]
description = "Slack Webhook"
regex = '''https://hooks.slack.com/services/T[a-zA-Z0-9_]{8}/B[a-zA-Z0-9_]{8,12}/[a-zA-Z0-9_]{24}'''
tags = ["key", "slack"]
[[rules]]
description = "Stripe API key"
regex = '''(?i)stripe(.{0,20})?[sr]k_live_[0-9a-zA-Z]{24}'''
tags = ["key", "Stripe"]
description = "Stripe API key"
regex = '''(?i)stripe(.{0,20})?[sr]k_live_[0-9a-zA-Z]{24}'''
tags = ["key", "Stripe"]
[[rules]]
description = "Square access token"
regex = '''sq0atp-[0-9A-Za-z\-_]{22}'''
tags = ["key", "square"]
description = "Square access token"
regex = '''sq0atp-[0-9A-Za-z\-_]{22}'''
tags = ["key", "square"]
[[rules]]
description = "Square OAuth secret"
regex = '''sq0csp-[0-9A-Za-z\\-_]{43}'''
tags = ["key", "square"]
description = "Square OAuth secret"
regex = '''sq0csp-[0-9A-Za-z\\-_]{43}'''
tags = ["key", "square"]
[[rules]]
description = "Twilio API key"
regex = '''(?i)twilio(.{0,20})?SK[0-9a-f]{32}'''
tags = ["key", "twilio"]
description = "Twilio API key"
regex = '''(?i)twilio(.{0,20})?SK[0-9a-f]{32}'''
tags = ["key", "twilio"]
[[rules]]
description = "Dynatrace ttoken"
regex = '''dt0[a-zA-Z]{1}[0-9]{2}\.[A-Z0-9]{24}\.[A-Z0-9]{64}'''
tags = ["key", "Dynatrace"]
description = "Dynatrace ttoken"
regex = '''dt0[a-zA-Z]{1}[0-9]{2}\.[A-Z0-9]{24}\.[A-Z0-9]{64}'''
tags = ["key", "Dynatrace"]
[[rules]]
description = "Shopify shared secret"
regex = '''shpss_[a-fA-F0-9]{32}'''
tags = ["key", "Shopify"]
description = "Shopify shared secret"
regex = '''shpss_[a-fA-F0-9]{32}'''
tags = ["key", "Shopify"]
[[rules]]
description = "Shopify access token"
regex = '''shpat_[a-fA-F0-9]{32}'''
tags = ["key", "Shopify"]
description = "Shopify access token"
regex = '''shpat_[a-fA-F0-9]{32}'''
tags = ["key", "Shopify"]
[[rules]]
description = "Shopify custom app access token"
regex = '''shpca_[a-fA-F0-9]{32}'''
tags = ["key", "Shopify"]
description = "Shopify custom app access token"
regex = '''shpca_[a-fA-F0-9]{32}'''
tags = ["key", "Shopify"]
[[rules]]
description = "Shopify private app access token"
regex = '''shppa_[a-fA-F0-9]{32}'''
tags = ["key", "Shopify"]
description = "Shopify private app access token"
regex = '''shppa_[a-fA-F0-9]{32}'''
tags = ["key", "Shopify"]
[[rules]]
description = "PyPI upload token"
regex = '''pypi-AgEIcHlwaS5vcmc[A-Za-z0-9-_]{50,1000}'''
tags = ["key", "pypi"]
[allowlist]
description = "Allowlisted files"
files = ['''^\.?gitleaks.toml$''',
'''(.*?)(jpg|gif|doc|pdf|bin)$''',
'''(go.mod|go.sum)$''']
description = "Allowlisted files"
files = ['''^\.?gitleaks.toml$''',
'''(.*?)(png|jpg|gif|doc|docx|pdf|bin|xls|pyc|zip)$''',
'''(go.mod|go.sum)$''']
`
+143
View File
@@ -0,0 +1,143 @@
package config
import (
"math"
"path/filepath"
"regexp"
)
// Rule is a struct that contains information that is loaded from a gitleaks config.
// This struct is used in the Config struct as an array of Rules and is iterated
// over during an scan. Each rule will be checked. If a regex match is found AND
// that match is not allowlisted (globally or locally), then a leak will be appended
// to the final scan report.
type Rule struct {
Description string
Regex *regexp.Regexp
File *regexp.Regexp
Path *regexp.Regexp
ReportGroup int
Tags []string
AllowList AllowList
Entropies []Entropy
}
// Inspect checks the content of a line for a leak
func (r *Rule) Inspect(line string) string {
offender := r.Regex.FindString(line)
if offender == "" {
return ""
}
// check if offender is allowed
if r.RegexAllowed(line) {
return ""
}
// check entropy
groups := r.Regex.FindStringSubmatch(offender)
if len(r.Entropies) != 0 && !r.ContainsEntropyLeak(groups) {
return ""
}
// 0 is a match for the full regex pattern
if 0 < r.ReportGroup && r.ReportGroup < len(groups) {
offender = groups[r.ReportGroup]
}
return offender
}
// RegexAllowed checks if the content is allowlisted
func (r *Rule) RegexAllowed(content string) bool {
return anyRegexMatch(content, r.AllowList.Regexes)
}
// CommitAllowed checks if a commit is allowlisted
func (r *Rule) CommitAllowed(commit string) bool {
return r.AllowList.CommitAllowed(commit)
}
// ContainsEntropyLeak checks if there is an entropy leak
func (r *Rule) ContainsEntropyLeak(groups []string) bool {
for _, e := range r.Entropies {
if len(groups) > e.Group {
entropy := shannonEntropy(groups[e.Group])
if entropy >= e.Min && entropy <= e.Max {
return true
}
}
}
return false
}
// HasFileOrPathLeakOnly first checks if there are no entropy/regex rules, then checks if
// there are any file/path leaks
func (r *Rule) HasFileOrPathLeakOnly(filePath string) bool {
if r.Regex.String() != "" {
return false
}
if len(r.Entropies) != 0 {
return false
}
if r.AllowList.FileAllowed(filepath.Base(filePath)) || r.AllowList.PathAllowed(filePath) {
return false
}
return r.HasFileLeak(filepath.Base(filePath)) || r.HasFilePathLeak(filePath)
}
// HasFileLeak checks if there is a file leak
func (r *Rule) HasFileLeak(fileName string) bool {
return regexMatched(fileName, r.File)
}
// HasFilePathLeak checks if there is a path leak
func (r *Rule) HasFilePathLeak(filePath string) bool {
return regexMatched(filePath, r.Path)
}
// 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
}
// regexMatched matched an interface to a regular expression. The interface f can
// be a string type or go-git *object.File type.
func regexMatched(f string, re *regexp.Regexp) bool {
if re == nil {
return false
}
if re.FindString(f) != "" {
return true
}
return false
}
// anyRegexMatch matched an interface to a regular expression. The interface f can
// be a string type or go-git *object.File type.
func anyRegexMatch(f string, res []*regexp.Regexp) bool {
for _, re := range res {
if regexMatched(f, re) {
return true
}
}
return false
}
+3 -2
View File
@@ -1,6 +1,8 @@
module github.com/zricethezav/gitleaks/v7
go 1.15
go 1.16
replace github.com/go-git/go-git/v5 => github.com/zricethezav/go-git/v5 v5.2.2
require (
github.com/BurntSushi/toml v0.3.1
@@ -10,7 +12,6 @@ require (
github.com/jessevdk/go-flags v1.4.0
github.com/sergi/go-diff v1.1.0
github.com/sirupsen/logrus v1.4.2
golang.org/x/lint v0.0.0-20200302205851-738671d3881b // indirect
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9
gopkg.in/yaml.v2 v2.2.8 // indirect
)
+2 -16
View File
@@ -22,9 +22,6 @@ github.com/go-git/go-billy/v5 v5.0.0 h1:7NQHvd9FVid8VL4qVUMm8XifBK+2xCoZ2lSk0agR
github.com/go-git/go-billy/v5 v5.0.0/go.mod h1:pmpqyWchKfYfrkb/UVH4otLvyi/5gJlGI4Hb3ZqZ3W0=
github.com/go-git/go-git-fixtures/v4 v4.0.2-0.20200613231340-f56387b50c12 h1:PbKy9zOy4aAKrJ5pibIRpVO2BXnK1Tlcg+caKI7Ox5M=
github.com/go-git/go-git-fixtures/v4 v4.0.2-0.20200613231340-f56387b50c12/go.mod h1:m+ICp2rF3jDhFgEZ/8yziagdT1C+ZpZcrJjappBCDSw=
github.com/go-git/go-git/v5 v5.2.0 h1:YPBLG/3UK1we1ohRkncLjaXWLW+HKp5QNM/jTli2JgI=
github.com/go-git/go-git/v5 v5.2.0/go.mod h1:kh02eMX+wdqqxgNMEyq8YgwlIOsDOa9homkUq1PoTMs=
github.com/google/go-cmp v0.3.0 h1:crn/baboCvb5fXaQ0IJ1SGTsTVrWpDsCWC8EGETZijY=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
@@ -40,10 +37,8 @@ github.com/kevinburke/ssh_config v0.0.0-20190725054713-01f96b0aa0cd h1:Coekwdh0v
github.com/kevinburke/ssh_config v0.0.0-20190725054713-01f96b0aa0cd/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM=
github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
@@ -66,19 +61,15 @@ github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJy
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/xanzy/ssh-agent v0.2.1 h1:TCbipTQL2JiiCprBWx9frJ2eJlCYT00NmctrHxVAr70=
github.com/xanzy/ssh-agent v0.2.1/go.mod h1:mLlQY/MoOhWBj+gOGMQkOeiEvkx+8pJSI+0Bx9h2kr4=
github.com/zricethezav/go-git/v5 v5.2.2 h1:VOVijF5OpIiHvFZXX94AJezdJ0b0kTyRyVNZ4yaqCRU=
github.com/zricethezav/go-git/v5 v5.2.2/go.mod h1:kh02eMX+wdqqxgNMEyq8YgwlIOsDOa9homkUq1PoTMs=
golang.org/x/crypto v0.0.0-20190219172222-a4c6cb3142f2/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073 h1:xMPOj6Pz6UipU1wXLkrtqpHbR0AVFnyPEQq/wRWz9lM=
golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/lint v0.0.0-20200302205851-738671d3881b h1:Wh+f8QHJXR411sJR8/vRBTZ7YapZaRvUcLFFJhusH0k=
golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200301022130-244492dfa37a h1:GuSPYbZzB5/dcLNCwLQLsg3obCJtX9IJhpXkvY7kzk0=
golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9 h1:SQFwaSi55rU7vdNs9Yr0Z324VNlrF+0wMqRXT4St8ck=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@@ -91,9 +82,6 @@ golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7 h1:EBZoQjiKKPaLbPrbpssUfuHtwM6KV/vb4U85g/cigFY=
golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
@@ -102,9 +90,7 @@ gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8X
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/warnings.v0 v0.1.2 h1:wFXVbFY8DY5/xOe1ECiWdKCzZlxgshcYVNkBHstARME=
gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
+5 -3
View File
@@ -5,8 +5,6 @@ import (
"os/signal"
"time"
"github.com/zricethezav/gitleaks/v7/report"
"github.com/zricethezav/gitleaks/v7/config"
"github.com/zricethezav/gitleaks/v7/options"
"github.com/zricethezav/gitleaks/v7/scan"
@@ -59,10 +57,14 @@ func main() {
}
// report scan
if err := report.WriteReport(scannerReport, opts, cfg); err != nil {
if err := scan.WriteReport(scannerReport, opts, cfg); err != nil {
log.Error(err)
os.Exit(1)
}
if len(scannerReport.Leaks) != 0 {
os.Exit(opts.CodeOnLeak)
}
}
func listenForInterrupt(stopScan chan os.Signal) {
+25 -19
View File
@@ -20,24 +20,27 @@ import (
// Options stores values of command line options
type Options struct {
Verbose bool `short:"v" long:"verbose" description:"Show verbose output from scan"`
RepoURL string `short:"r" long:"repo-url" description:"Repository URL"`
Path string `short:"p" long:"path" description:"Path to directory (repo if contains .git) or file"`
ConfigPath string `short:"c" long:"config-path" description:"Path to config"`
RepoConfigPath string `long:"repo-config-path" description:"Path to gitleaks config relative to repo root"`
ClonePath string `long:"clone-path" description:"Path to clone repo to disk"`
CleanUp string `long:"clone-cleanup" description:"Deletes cloned repo after scan"`
Version bool `long:"version" description:"Version number"`
Username string `long:"username" description:"Username for git repo"`
Password string `long:"password" description:"Password for git repo"`
AccessToken string `long:"access-token" description:"Access token for git repo"`
Threads int `long:"threads" description:"Maximum number of threads gitleaks spawns"`
SSH string `long:"ssh-key" description:"Path to ssh key used for auth"`
Unstaged bool `long:"unstaged" description:"Run gitleaks on unstaged code"`
Branch string `long:"branch" description:"Branch to scan"`
Redact bool `long:"redact" description:"Redact secrets from log messages and leaks"`
Debug bool `long:"debug" description:"Log debug messages"`
NoGit bool `long:"no-git" description:"Treat git repos as plain directories and scan those files"`
Verbose bool `short:"v" long:"verbose" description:"Show verbose output from scan"`
Quiet bool `short:"q" long:"quiet" description:"Sets log level to error and only output leaks, one json object per line"`
RepoURL string `short:"r" long:"repo-url" description:"Repository URL"`
Path string `short:"p" long:"path" description:"Path to directory (repo if contains .git) or file"`
ConfigPath string `short:"c" long:"config-path" description:"Path to config"`
RepoConfigPath string `long:"repo-config-path" description:"Path to gitleaks config relative to repo root"`
ClonePath string `long:"clone-path" description:"Path to clone repo to disk"`
Version bool `long:"version" description:"Version number"`
Username string `long:"username" description:"Username for git repo"`
Password string `long:"password" description:"Password for git repo"`
AccessToken string `long:"access-token" description:"Access token for git repo"`
Threads int `long:"threads" description:"Maximum number of threads gitleaks spawns"`
SSH string `long:"ssh-key" description:"Path to ssh key used for auth"`
Unstaged bool `long:"unstaged" description:"Run gitleaks on unstaged code"`
Branch string `long:"branch" description:"Branch to scan"`
Redact bool `long:"redact" description:"Redact secrets from log messages and leaks"`
Debug bool `long:"debug" description:"Log debug messages"`
NoGit bool `long:"no-git" description:"Treat git repos as plain directories and scan those files"`
CodeOnLeak int `long:"leaks-exit-code" default:"1" description:"Exit code when leaks have been encountered"`
AppendRepoConfig bool `long:"append-repo-config" description:"Append the provided or default config with the repo config."`
AdditionalConfig string `long:"additional-config" description:"Path to an additional gitleaks config to append with an existing config. Can be used with --append-repo-config to append up to three configurations"`
// Report Options
Report string `short:"o" long:"report" description:"Report output path"`
@@ -68,7 +71,7 @@ func ParseOptions() (Options, error) {
if flagsErr, ok := err.(*flags.Error); ok && flagsErr.Type != flags.ErrHelp {
parser.WriteHelp(os.Stdout)
}
os.Exit(0)
os.Exit(1)
}
if opts.Version {
@@ -83,6 +86,9 @@ func ParseOptions() (Options, error) {
if opts.Debug {
log.SetLevel(log.DebugLevel)
}
if opts.Quiet {
log.SetLevel(log.ErrorLevel)
}
return opts, nil
}
-33
View File
@@ -1,33 +0,0 @@
package report
import (
"strings"
"time"
)
// Leak is a struct that contains information about some line of code that contains
// sensitive information as determined by the rules set in a gitleaks config
type Leak struct {
Line string `json:"line"`
LineNumber int `json:"lineNumber"`
Offender string `json:"offender"`
Commit string `json:"commit"`
Repo string `json:"repo"`
RepoURL string `json:"repoURL"`
LeakURL string `json:"leakURL"`
Rule string `json:"rule"`
Message string `json:"commitMessage"`
Author string `json:"author"`
Email string `json:"email"`
File string `json:"file"`
Date time.Time `json:"date"`
Tags string `json:"tags"`
}
// RedactLeak will replace the offending string with "REDACTED" in both
// the offender and line field of the leak which.
func RedactLeak(leak Leak) Leak {
leak.Line = strings.Replace(leak.Line, leak.Offender, "REDACTED", -1)
leak.Offender = "REDACTED"
return leak
}
+116 -44
View File
@@ -2,8 +2,11 @@ package scan
import (
"fmt"
"path/filepath"
"strings"
"github.com/zricethezav/gitleaks/v7/report"
"github.com/zricethezav/gitleaks/v7/config"
"github.com/zricethezav/gitleaks/v7/options"
"github.com/go-git/go-git/v5"
fdiff "github.com/go-git/go-git/v5/plumbing/format/diff"
@@ -12,75 +15,144 @@ import (
// CommitScanner is a commit scanner
type CommitScanner struct {
BaseScanner
cfg config.Config
opts options.Options
repo *git.Repository
repoName string
commit *object.Commit
}
// NewCommitScanner creates and returns a commit scanner
func NewCommitScanner(base BaseScanner, repo *git.Repository, commit *object.Commit) *CommitScanner {
func NewCommitScanner(opts options.Options, cfg config.Config, repo *git.Repository, commit *object.Commit) *CommitScanner {
cs := &CommitScanner{
BaseScanner: base,
repo: repo,
commit: commit,
repoName: getRepoName(base.opts),
cfg: cfg,
opts: opts,
repo: repo,
commit: commit,
repoName: getRepoName(opts),
}
cs.scannerType = typeCommitScanner
return cs
}
// SetRepoName sets the repo name of the scanner.
func (cs *CommitScanner) SetRepoName(repoName string) {
cs.repoName = repoName
}
// Scan kicks off a CommitScanner Scan
func (cs *CommitScanner) Scan() (report.Report, error) {
var scannerReport report.Report
func (cs *CommitScanner) Scan() (Report, error) {
var scannerReport Report
defer func() {
if err := recover(); err != nil {
// sometimes the Patch generation will fail due to a known bug in
// sergi's go-diff: https://github.com/sergi/go-diff/issues/89.
return
}
}()
if cs.cfg.Allowlist.CommitAllowed(cs.commit.Hash.String()) {
return scannerReport, nil
}
if len(cs.commit.ParentHashes) == 0 {
facScanner := NewFilesAtCommitScanner(cs.BaseScanner, cs.repo, cs.commit)
facScanner := NewFilesAtCommitScanner(cs.opts, cs.cfg, cs.repo, cs.commit)
return facScanner.Scan()
}
err := cs.commit.Parents().ForEach(func(parent *object.Commit) error {
defer func() {
if err := recover(); err != nil {
// sometimes the Patch generation will fail due to a known bug in
// sergi's go-diff: https://github.com/sergi/go-diff/issues/89.
// Once a fix has been merged I will remove this recover.
return
}
}()
if parent == nil {
return nil
parent, err := cs.commit.Parent(0)
if err != nil {
return scannerReport, err
}
if parent == nil {
return scannerReport, nil
}
patch, err := parent.Patch(cs.commit)
if err != nil || patch == nil {
return scannerReport, fmt.Errorf("could not generate Patch")
}
patchContent := patch.String()
for _, f := range patch.FilePatches() {
if f.IsBinary() {
continue
}
for _, chunk := range f.Chunks() {
if chunk.Type() == fdiff.Add {
_, to := f.Files()
if cs.cfg.Allowlist.FileAllowed(filepath.Base(to.Path())) ||
cs.cfg.Allowlist.PathAllowed(to.Path()) {
continue
}
patch, err := parent.Patch(cs.commit)
if err != nil {
return fmt.Errorf("could not generate Patch")
}
// Check individual file path ONLY rules
for _, rule := range cs.cfg.Rules {
if rule.CommitAllowed(cs.commit.Hash.String()) {
continue
}
patchContent := patch.String()
if rule.HasFileOrPathLeakOnly(to.Path()) {
leak := NewLeak("", "Filename or path offender: "+to.Path(), defaultLineNumber).WithCommit(cs.commit)
leak.Repo = cs.repoName
leak.File = to.Path()
leak.RepoURL = cs.opts.RepoURL
leak.LeakURL = leak.URL()
leak.Rule = rule.Description
leak.Tags = strings.Join(rule.Tags, ", ")
for _, f := range patch.FilePatches() {
if f.IsBinary() {
continue
}
for _, chunk := range f.Chunks() {
if chunk.Type() == fdiff.Add {
_, to := f.Files()
leaks := checkRules(cs.BaseScanner, cs.commit, cs.repoName, to.Path(), chunk.Content())
leak.Log(cs.opts)
lineLookup := make(map[string]bool)
for _, leak := range leaks {
leak.LineNumber = extractLine(patchContent, leak, lineLookup)
leak.LeakURL = leakURL(leak)
scannerReport.Leaks = append(scannerReport.Leaks, leak)
if cs.opts.Verbose {
logLeak(leak, cs.opts.Redact)
continue
}
}
lineLookup := make(map[string]bool)
// Check the actual content
for _, line := range strings.Split(chunk.Content(), "\n") {
for _, rule := range cs.cfg.Rules {
if rule.AllowList.FileAllowed(filepath.Base(to.Path())) ||
rule.AllowList.PathAllowed(to.Path()) ||
rule.AllowList.CommitAllowed(cs.commit.Hash.String()) {
continue
}
offender := rule.Inspect(line)
if offender == "" {
continue
}
if cs.cfg.Allowlist.RegexAllowed(line) {
continue
}
if rule.File.String() != "" && !rule.HasFileLeak(filepath.Base(to.Path())) {
continue
}
if rule.Path.String() != "" && !rule.HasFilePathLeak(to.Path()) {
continue
}
leak := NewLeak(line, offender, defaultLineNumber).WithCommit(cs.commit)
leak.File = to.Path()
leak.LineNumber = extractLine(patchContent, leak, lineLookup)
leak.RepoURL = cs.opts.RepoURL
leak.Repo = cs.repoName
leak.LeakURL = leak.URL()
leak.Rule = rule.Description
leak.Tags = strings.Join(rule.Tags, ", ")
leak.Log(cs.opts)
scannerReport.Leaks = append(scannerReport.Leaks, leak)
}
}
}
}
return nil
})
}
scannerReport.Commits = 1
return scannerReport, err
return scannerReport, nil
}
+13 -10
View File
@@ -2,12 +2,14 @@ package scan
import (
"github.com/go-git/go-git/v5"
"github.com/zricethezav/gitleaks/v7/report"
"github.com/zricethezav/gitleaks/v7/config"
"github.com/zricethezav/gitleaks/v7/options"
)
// CommitsScanner is a commit scanner
type CommitsScanner struct {
BaseScanner
opts options.Options
cfg config.Config
repo *git.Repository
repoName string
@@ -15,24 +17,25 @@ type CommitsScanner struct {
}
// NewCommitsScanner creates and returns a commits scanner, notice the 's' in commits
func NewCommitsScanner(base BaseScanner, repo *git.Repository, commits []string) *CommitsScanner {
func NewCommitsScanner(opts options.Options, cfg config.Config, repo *git.Repository, commits []string) *CommitsScanner {
return &CommitsScanner{
BaseScanner: base,
repo: repo,
commits: commits,
repoName: getRepoName(base.opts),
opts: opts,
cfg: cfg,
repo: repo,
commits: commits,
repoName: getRepoName(opts),
}
}
// Scan kicks off a CommitsScanner Scan
func (css *CommitsScanner) Scan() (report.Report, error) {
var scannerReport report.Report
func (css *CommitsScanner) Scan() (Report, error) {
var scannerReport Report
for _, c := range css.commits {
c, err := obtainCommit(css.repo, c)
if err != nil {
return scannerReport, nil
}
cs := NewCommitScanner(css.BaseScanner, css.repo, c)
cs := NewCommitScanner(css.opts, css.cfg, css.repo, c)
commitReport, err := cs.Scan()
if err != nil {
return scannerReport, err
+88 -12
View File
@@ -1,9 +1,14 @@
package scan
import (
"path/filepath"
"strings"
"github.com/zricethezav/gitleaks/v7/config"
"github.com/zricethezav/gitleaks/v7/options"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/zricethezav/gitleaks/v7/report"
)
// FilesAtCommitScanner is a files at commit scanner. This differs from CommitScanner
@@ -11,28 +16,33 @@ import (
// files available at a commit's worktree and scans the entire content of said files.
// Apologies for the awful struct name...
type FilesAtCommitScanner struct {
BaseScanner
opts options.Options
cfg config.Config
repo *git.Repository
commit *object.Commit
repoName string
}
// NewFilesAtCommitScanner creates and returns a files at commit scanner
func NewFilesAtCommitScanner(base BaseScanner, repo *git.Repository, commit *object.Commit) *FilesAtCommitScanner {
func NewFilesAtCommitScanner(opts options.Options, cfg config.Config, repo *git.Repository, commit *object.Commit) *FilesAtCommitScanner {
fs := &FilesAtCommitScanner{
BaseScanner: base,
repo: repo,
commit: commit,
repoName: getRepoName(base.opts),
opts: opts,
cfg: cfg,
repo: repo,
commit: commit,
repoName: getRepoName(opts),
}
fs.scannerType = typeFilesAtCommitScanner
return fs
}
// Scan kicks off a FilesAtCommitScanner Scan
func (fs *FilesAtCommitScanner) Scan() (report.Report, error) {
var scannerReport report.Report
func (fs *FilesAtCommitScanner) Scan() (Report, error) {
var scannerReport Report
if fs.cfg.Allowlist.CommitAllowed(fs.commit.Hash.String()) {
return scannerReport, nil
}
fIter, err := fs.commit.Files()
if err != nil {
return scannerReport, err
@@ -46,12 +56,78 @@ func (fs *FilesAtCommitScanner) Scan() (report.Report, error) {
return err
}
if fs.cfg.Allowlist.FileAllowed(filepath.Base(f.Name)) ||
fs.cfg.Allowlist.PathAllowed(f.Name) {
return nil
}
content, err := f.Contents()
if err != nil {
return err
}
scannerReport.Leaks = append(scannerReport.Leaks, checkRules(fs.BaseScanner, fs.commit, fs.repoName, f.Name, content)...)
// Check individual file path ONLY rules
for _, rule := range fs.cfg.Rules {
if rule.CommitAllowed(fs.commit.Hash.String()) {
continue
}
if rule.HasFileOrPathLeakOnly(f.Name) {
leak := NewLeak("", "Filename or path offender: "+f.Name, defaultLineNumber).WithCommit(fs.commit)
leak.Repo = fs.repoName
leak.File = f.Name
leak.RepoURL = fs.opts.RepoURL
leak.LeakURL = leak.URL()
leak.Rule = rule.Description
leak.Tags = strings.Join(rule.Tags, ", ")
leak.Log(fs.opts)
scannerReport.Leaks = append(scannerReport.Leaks, leak)
continue
}
}
for i, line := range strings.Split(content, "\n") {
for _, rule := range fs.cfg.Rules {
if rule.AllowList.FileAllowed(filepath.Base(f.Name)) ||
rule.AllowList.PathAllowed(f.Name) ||
rule.AllowList.CommitAllowed(fs.commit.Hash.String()) {
continue
}
offender := rule.Inspect(line)
if offender == "" {
continue
}
if fs.cfg.Allowlist.RegexAllowed(line) {
continue
}
if rule.File.String() != "" && !rule.HasFileLeak(filepath.Base(f.Name)) {
continue
}
if rule.Path.String() != "" && !rule.HasFilePathLeak(f.Name) {
continue
}
leak := NewLeak(line, offender, defaultLineNumber).WithCommit(fs.commit)
leak.File = f.Name
leak.LineNumber = i + 1
leak.RepoURL = fs.opts.RepoURL
leak.Repo = fs.repoName
leak.LeakURL = leak.URL()
leak.Rule = rule.Description
leak.Tags = strings.Join(rule.Tags, ", ")
leak.Log(fs.opts)
scannerReport.Leaks = append(scannerReport.Leaks, leak)
}
}
return nil
})
+85
View File
@@ -0,0 +1,85 @@
package scan
import (
"encoding/json"
"fmt"
"strings"
"time"
"github.com/zricethezav/gitleaks/v7/options"
"github.com/go-git/go-git/v5/plumbing/object"
)
// Leak is a struct that contains information about some line of code that contains
// sensitive information as determined by the rules set in a gitleaks config
type Leak struct {
Line string `json:"line"`
LineNumber int `json:"lineNumber"`
Offender string `json:"offender"`
Commit string `json:"commit"`
Repo string `json:"repo"`
RepoURL string `json:"repoURL"`
LeakURL string `json:"leakURL"`
Rule string `json:"rule"`
Message string `json:"commitMessage"`
Author string `json:"author"`
Email string `json:"email"`
File string `json:"file"`
Date time.Time `json:"date"`
Tags string `json:"tags"`
}
// RedactLeak will replace the offending string with "REDACTED" in both
// the offender and line field of the leak which.
func RedactLeak(leak Leak) Leak {
leak.Line = strings.Replace(leak.Line, leak.Offender, "REDACTED", -1)
leak.Offender = "REDACTED"
return leak
}
// NewLeak creates a new leak from common data all leaks must have, line, offender, linenumber
func NewLeak(line string, offender string, lineNumber int) Leak {
return Leak{
Line: line,
Offender: offender,
LineNumber: lineNumber,
}
}
// WithCommit adds commit data to the leak
func (leak Leak) WithCommit(commit *object.Commit) Leak {
leak.Commit = commit.Hash.String()
leak.Author = commit.Author.Name
leak.Email = commit.Author.Email
leak.Message = commit.Message
leak.Date = commit.Author.When
return leak
}
// Log logs a leak and redacts if necessary
func (leak Leak) Log(opts options.Options) {
if !opts.Quiet && !opts.Verbose {
return
}
if opts.Redact {
leak = RedactLeak(leak)
}
if opts.Quiet {
var b []byte
b, _ = json.Marshal(leak)
fmt.Println(string(b))
} else {
var b []byte
b, _ = json.MarshalIndent(leak, "", " ")
fmt.Println(string(b))
}
}
// URL generates a url to the leak if leak.RepoURL is set
func (leak Leak) URL() string {
if leak.RepoURL != "" {
return fmt.Sprintf("%s/blob/%s/%s#L%d", leak.RepoURL, leak.Commit, leak.File, leak.LineNumber)
}
return ""
}
+95 -44
View File
@@ -5,44 +5,46 @@ import (
"context"
"os"
"path/filepath"
"sync"
"strings"
"github.com/zricethezav/gitleaks/v7/report"
log "github.com/sirupsen/logrus"
"github.com/zricethezav/gitleaks/v7/config"
"github.com/zricethezav/gitleaks/v7/options"
"golang.org/x/sync/errgroup"
)
// NoGitScanner is a scanner that absolutely despises git
type NoGitScanner struct {
BaseScanner
leakChan chan report.Leak
leakWG *sync.WaitGroup
leaks []report.Leak
opts options.Options
cfg config.Config
}
// NewNoGitScanner creates and returns a nogit scanner. This is used for scanning files and directories
func NewNoGitScanner(base BaseScanner) *NoGitScanner {
func NewNoGitScanner(opts options.Options, cfg config.Config) *NoGitScanner {
ngs := &NoGitScanner{
BaseScanner: base,
leakChan: make(chan report.Leak),
leakWG: &sync.WaitGroup{},
opts: opts,
cfg: cfg,
}
go ngs.receiveLeaks()
ngs.scannerType = typeNoGitScanner
// no-git scans should ignore .git folders by default
// issue: https://github.com/zricethezav/gitleaks/issues/474
// ngs.cfg.Allowlist
err := ngs.cfg.Allowlist.IgnoreDotGit()
if err != nil {
log.Error(err)
return nil
}
return ngs
}
// Scan kicks off a NoGitScanner Scan
func (ngs *NoGitScanner) Scan() (report.Report, error) {
var scannerReport report.Report
func (ngs *NoGitScanner) Scan() (Report, error) {
var scannerReport Report
g, _ := errgroup.WithContext(context.Background())
paths := make(chan string)
semaphore := make(chan bool, howManyThreads(ngs.opts.Threads))
wg := sync.WaitGroup{}
paths := make(chan string, 100)
g.Go(func() error {
defer close(paths)
@@ -58,46 +60,95 @@ func (ngs *NoGitScanner) Scan() (report.Report, error) {
})
})
leaks := make(chan Leak, 100)
for path := range paths {
p := path
wg.Add(1)
semaphore <- true
g.Go(func() error {
defer func() {
<-semaphore
wg.Done()
}()
f, err := os.Open(p)
if ngs.cfg.Allowlist.FileAllowed(filepath.Base(p)) ||
ngs.cfg.Allowlist.PathAllowed(p) {
return nil
}
for _, rule := range ngs.cfg.Rules {
if rule.HasFileOrPathLeakOnly(p) {
leak := NewLeak("", "Filename or path offender: "+p, defaultLineNumber)
relPath, err := filepath.Rel(ngs.opts.Path, p)
if err != nil {
leak.File = p
} else {
leak.File = relPath
}
leak.Rule = rule.Description
leak.Tags = strings.Join(rule.Tags, ", ")
leak.Log(ngs.opts)
leaks <- leak
}
}
f, err := os.Open(p) // #nosec
if err != nil {
return err
}
scanner := bufio.NewScanner(f)
line := 0
lineNumber := 0
for scanner.Scan() {
line++
leaks := checkRules(ngs.BaseScanner, emptyCommit(), "", f.Name(), scanner.Text())
for _, leak := range leaks {
leak.LineNumber = line
if ngs.opts.Verbose {
logLeak(leak, ngs.opts.Redact)
lineNumber++
for _, rule := range ngs.cfg.Rules {
line := scanner.Text()
if rule.AllowList.FileAllowed(filepath.Base(p)) ||
rule.AllowList.PathAllowed(p) {
continue
}
ngs.leakWG.Add(1)
ngs.leakChan <- leak
offender := rule.Inspect(line)
if offender == "" {
continue
}
if ngs.cfg.Allowlist.RegexAllowed(line) {
continue
}
if rule.File.String() != "" && !rule.HasFileLeak(filepath.Base(p)) {
continue
}
if rule.Path.String() != "" && !rule.HasFilePathLeak(p) {
continue
}
leak := NewLeak(line, offender, defaultLineNumber)
relPath, err := filepath.Rel(ngs.opts.Path, p)
if err != nil {
leak.File = p
} else {
leak.File = relPath
}
leak.LineNumber = lineNumber
leak.Rule = rule.Description
leak.Tags = strings.Join(rule.Tags, ", ")
leak.Log(ngs.opts)
leaks <- leak
}
}
return f.Close()
})
}
wg.Wait()
ngs.leakWG.Wait()
scannerReport.Leaks = ngs.leaks
return scannerReport, nil
}
go func() {
if err := g.Wait(); err != nil {
log.Error(err)
}
close(leaks)
}()
func (ngs *NoGitScanner) receiveLeaks() {
for leak := range ngs.leakChan {
ngs.leaks = append(ngs.leaks, leak)
ngs.leakWG.Done()
for leak := range leaks {
scannerReport.Leaks = append(scannerReport.Leaks, leak)
}
return scannerReport, g.Wait()
}
+21 -15
View File
@@ -4,7 +4,9 @@ import (
"io/ioutil"
"path/filepath"
"github.com/zricethezav/gitleaks/v7/report"
"github.com/zricethezav/gitleaks/v7/options"
"github.com/zricethezav/gitleaks/v7/config"
"github.com/go-git/go-git/v5"
log "github.com/sirupsen/logrus"
@@ -12,21 +14,22 @@ import (
// ParentScanner is a parent directory scanner
type ParentScanner struct {
BaseScanner
cfg config.Config
opts options.Options
}
// NewParentScanner creates and returns a directory scanner
func NewParentScanner(base BaseScanner) *ParentScanner {
func NewParentScanner(opts options.Options, cfg config.Config) *ParentScanner {
ds := &ParentScanner{
BaseScanner: base,
opts: opts,
cfg: cfg,
}
ds.scannerType = typeDirScanner
return ds
}
// Scan kicks off a ParentScanner scan. This uses the directory from --path to discovery repos
func (ds *ParentScanner) Scan() (report.Report, error) {
var scannerReport report.Report
func (ds *ParentScanner) Scan() (Report, error) {
var scannerReport Report
log.Debugf("scanning repos in %s\n", ds.opts.Path)
files, err := ioutil.ReadDir(ds.opts.Path)
@@ -46,17 +49,20 @@ func (ds *ParentScanner) Scan() (report.Report, error) {
}
return scannerReport, err
}
skip := false
for _, allowListedRepo := range ds.cfg.Allowlist.Repos {
if regexMatched(f.Name(), allowListedRepo) {
skip = true
}
}
if skip {
if ds.cfg.Allowlist.RepoAllowed(f.Name()) {
continue
}
rs := NewRepoScanner(ds.BaseScanner, repo)
if ds.opts.RepoConfigPath != "" {
cfg, err := config.LoadRepoConfig(repo, ds.opts.RepoConfigPath)
if err != nil {
log.Warn(err)
} else {
ds.cfg = cfg
}
}
rs := NewRepoScanner(ds.opts, ds.cfg, repo)
rs.repoName = f.Name()
repoReport, err := rs.Scan()
if err != nil {
+72 -117
View File
@@ -1,12 +1,14 @@
package scan
import (
"sync"
"context"
"github.com/zricethezav/gitleaks/v7/report"
"golang.org/x/sync/errgroup"
"github.com/zricethezav/gitleaks/v7/config"
"github.com/zricethezav/gitleaks/v7/options"
"github.com/go-git/go-git/v5"
fdiff "github.com/go-git/go-git/v5/plumbing/format/diff"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/plumbing/storer"
log "github.com/sirupsen/logrus"
@@ -14,38 +16,33 @@ import (
// RepoScanner is a repo scanner
type RepoScanner struct {
BaseScanner
opts options.Options
cfg config.Config
repo *git.Repository
throttle *Throttle
repoName string
leakChan chan report.Leak
leakWG *sync.WaitGroup
leakCache map[string]bool
leaks []report.Leak
}
// NewRepoScanner returns a new repo scanner (go figure). This function also
// sets up the leak listener for multi-threaded awesomeness.
func NewRepoScanner(base BaseScanner, repo *git.Repository) *RepoScanner {
func NewRepoScanner(opts options.Options, cfg config.Config, repo *git.Repository) *RepoScanner {
rs := &RepoScanner{
BaseScanner: base,
repo: repo,
leakChan: make(chan report.Leak),
leakWG: &sync.WaitGroup{},
leakCache: make(map[string]bool),
repoName: getRepoName(base.opts),
opts: opts,
cfg: cfg,
repo: repo,
throttle: NewThrottle(opts),
repoName: getRepoName(opts),
}
rs.scannerType = typeRepoScanner
go rs.receiveLeaks()
return rs
}
// Scan kicks of a repo scan
func (rs *RepoScanner) Scan() (report.Report, error) {
var scannerReport report.Report
func (rs *RepoScanner) Scan() (Report, error) {
var (
scannerReport Report
commits chan *object.Commit
)
logOpts, err := logOptions(rs.repo, rs.opts)
if err != nil {
return scannerReport, err
@@ -54,110 +51,68 @@ func (rs *RepoScanner) Scan() (report.Report, error) {
if err != nil {
return scannerReport, err
}
semaphore := make(chan bool, howManyThreads(rs.opts.Threads))
wg := sync.WaitGroup{}
err = cIter.ForEach(func(c *object.Commit) error {
if c == nil || depthReached(scannerReport.Commits, rs.opts) {
return storer.ErrStop
}
g, _ := errgroup.WithContext(context.Background())
commits = make(chan *object.Commit)
leaks := make(chan Leak)
// Check if Commit is allowlisted
if isCommitAllowListed(c.Hash.String(), rs.cfg.Allowlist.Commits) {
return nil
}
commitNum := 0
g.Go(func() error {
defer close(commits)
err = cIter.ForEach(func(c *object.Commit) error {
if c == nil || depthReached(commitNum, rs.opts) {
return storer.ErrStop
}
// Check if at root
if len(c.ParentHashes) == 0 {
scannerReport.Commits++
facScanner := NewFilesAtCommitScanner(rs.BaseScanner, rs.repo, c)
facScanner.repoName = rs.repoName
facReport, err := facScanner.Scan()
if err != nil {
return err
if rs.cfg.Allowlist.CommitAllowed(c.Hash.String()) {
return nil
}
commitNum++
commits <- c
if c.Hash.String() == rs.opts.CommitTo {
return storer.ErrStop
}
scannerReport.Leaks = append(scannerReport.Leaks, facReport.Leaks...)
return nil
}
// inspect first parent only as all other parents will be eventually reached
// (they exist as the tip of other branches, etc)
// See https://github.com/zricethezav/gitleaks/issues/413 for details
parent, err := c.Parent(0)
if err != nil {
return err
}
defer func() {
if err := recover(); err != nil {
// sometimes the Patch generation will fail due to a known bug in
// sergi's go-diff: https://github.com/sergi/go-diff/issues/89.
// Once a fix has been merged I will remove this recover.
return
}
}()
if parent == nil {
// shouldn't reach this point but just in case
return nil
}
// start := time.Now()
patch, err := parent.Patch(c)
if err != nil {
log.Errorf("could not generate Patch")
}
scannerReport.Commits++
wg.Add(1)
semaphore <- true
go func(c *object.Commit, patch *object.Patch) {
defer func() {
<-semaphore
wg.Done()
}()
// patchContent is used for searching for leak line number
patchContent := patch.String()
for _, f := range patch.FilePatches() {
if f.IsBinary() {
continue
}
for _, chunk := range f.Chunks() {
if chunk.Type() == fdiff.Add {
_, to := f.Files()
lineLookup := make(map[string]bool)
for _, leak := range checkRules(rs.BaseScanner, c, rs.repoName, to.Path(), chunk.Content()) {
leak.LineNumber = extractLine(patchContent, leak, lineLookup)
leak.LeakURL = leakURL(leak)
if rs.opts.Verbose {
logLeak(leak, rs.opts.Redact)
}
rs.leakWG.Add(1)
rs.leakChan <- leak
}
}
}
}
}(c, patch)
if c.Hash.String() == rs.opts.CommitTo {
return storer.ErrStop
}
})
cIter.Close()
return nil
})
wg.Wait()
rs.leakWG.Wait()
scannerReport.Leaks = append(scannerReport.Leaks, rs.leaks...)
return scannerReport, nil
for commit := range commits {
c := commit
rs.throttle.Limit()
g.Go(func() error {
commitScanner := NewCommitScanner(rs.opts, rs.cfg, rs.repo, c)
commitScanner.SetRepoName(rs.repoName)
report, err := commitScanner.Scan()
rs.throttle.Release()
if err != nil {
log.Error(err)
}
for _, leak := range report.Leaks {
leaks <- leak
}
return nil
})
}
go func() {
if err := g.Wait(); err != nil {
log.Error(err)
}
close(leaks)
}()
for leak := range leaks {
scannerReport.Leaks = append(scannerReport.Leaks, leak)
}
scannerReport.Commits = commitNum
return scannerReport, g.Wait()
}
func (rs *RepoScanner) receiveLeaks() {
for leak := range rs.leakChan {
rs.leaks = append(rs.leaks, leak)
rs.leakWG.Done()
}
// SetRepoName sets the repo name
func (rs *RepoScanner) SetRepoName(repoName string) {
rs.repoName = repoName
}
+14 -10
View File
@@ -1,4 +1,4 @@
package report
package scan
import (
"encoding/csv"
@@ -6,11 +6,10 @@ import (
"os"
"time"
"github.com/sirupsen/logrus"
"github.com/zricethezav/gitleaks/v7/config"
"github.com/zricethezav/gitleaks/v7/options"
"github.com/zricethezav/gitleaks/v7/version"
log "github.com/sirupsen/logrus"
)
// Report is a container for leaks and number of commits scanned
@@ -22,13 +21,12 @@ type Report struct {
// WriteReport accepts a report and options and will write a report if --report has been set
func WriteReport(report Report, opts options.Options, cfg config.Config) error {
if !(opts.NoGit || opts.CheckUncommitted()) {
log.Info("commits scanned: ", report.Commits)
logrus.Info("commits scanned: ", report.Commits)
}
if len(report.Leaks) != 0 {
log.Warn("leaks found: ", len(report.Leaks))
logrus.Warn("leaks found: ", len(report.Leaks))
} else {
log.Info("No leaks found")
return nil
logrus.Info("No leaks found")
}
if opts.Report == "" {
@@ -47,7 +45,7 @@ func WriteReport(report Report, opts options.Options, cfg config.Config) error {
if err != nil {
return err
}
defer file.Close()
defer rable(file.Close)
if opts.Report != "" {
switch opts.ReportFormat {
@@ -60,9 +58,15 @@ func WriteReport(report Report, opts options.Options, cfg config.Config) error {
}
case "csv":
w := csv.NewWriter(file)
_ = w.Write([]string{"repo", "line", "commit", "offender", "leakURL", "rule", "tags", "commitMsg", "author", "email", "file", "date"})
err = w.Write([]string{"repo", "line", "commit", "offender", "leakURL", "rule", "tags", "commitMsg", "author", "email", "file", "date"})
if err != nil {
return err
}
for _, leak := range report.Leaks {
w.Write([]string{leak.Repo, leak.Line, leak.Commit, leak.Offender, leak.LeakURL, leak.Rule, leak.Tags, leak.Message, leak.Author, leak.Email, leak.File, leak.Date.Format(time.RFC3339)})
err := w.Write([]string{leak.Repo, leak.Line, leak.Commit, leak.Offender, leak.LeakURL, leak.Rule, leak.Tags, leak.Message, leak.Author, leak.Email, leak.File, leak.Date.Format(time.RFC3339)})
if err != nil {
return err
}
}
w.Flush()
case "sarif":
+3 -2
View File
@@ -1,4 +1,4 @@
package report
package scan
import (
"fmt"
@@ -110,7 +110,8 @@ func configToRules(cfg config.Config) []Rules {
}
func leaksToResults(leaks []Leak) []Results {
var results []Results
results := make([]Results, 0)
for _, leak := range leaks {
results = append(results, Results{
Message: Message{
+34 -38
View File
@@ -8,21 +8,12 @@ import (
"github.com/zricethezav/gitleaks/v7/config"
"github.com/zricethezav/gitleaks/v7/options"
"github.com/zricethezav/gitleaks/v7/report"
)
// Scanner abstracts unique scanner internals while exposing the Scan function which
// returns a report.
type Scanner interface {
Scan() (report.Report, error)
}
// BaseScanner is a container for common data each scanner needs.
type BaseScanner struct {
opts options.Options
cfg config.Config
stopChan chan os.Signal
scannerType ScannerType
Scan() (Report, error)
}
// ScannerType is the scanner type which is determined based on program arguments
@@ -46,19 +37,6 @@ func NewScanner(opts options.Options, cfg config.Config) (Scanner, error) {
repo *git.Repository
err error
)
// TODO move this block to config parsing?
for _, allowListedRepo := range cfg.Allowlist.Repos {
if regexMatched(opts.Path, allowListedRepo) {
return nil, nil
}
if regexMatched(opts.RepoURL, allowListedRepo) {
return nil, nil
}
}
base := BaseScanner{
opts: opts,
cfg: cfg,
}
// We want to return a dir scanner immediately since if the scan type is a directory scan
// we don't want to clone/open a repo until inside ParentScanner.Scan
@@ -67,23 +45,44 @@ func NewScanner(opts options.Options, cfg config.Config) (Scanner, error) {
return nil, err
}
if st == typeDirScanner {
return NewParentScanner(base), nil
if opts.AdditionalConfig != "" {
additionalCfg, err := config.LoadAdditionalConfig(opts.AdditionalConfig)
if err != nil {
return nil, err
}
cfg = cfg.AppendConfig(additionalCfg)
}
return NewParentScanner(opts, cfg), nil
}
// Clone or open a repo if we need it
if needsRepo(st) {
repo, err = getRepo(base.opts)
repo, err = getRepo(opts)
if err != nil {
return nil, err
}
}
// load up alternative config if possible, if not use manager's config
if opts.RepoConfigPath != "" {
base.cfg, err = config.LoadRepoConfig(repo, opts.RepoConfigPath)
// load up alternative config if possible, if not use default/specified config. Will append if AppendRepoConfig is true
if opts.RepoConfigPath != "" && !opts.NoGit {
repoCfg, err := config.LoadRepoConfig(repo, opts.RepoConfigPath)
if err != nil {
return nil, err
}
if opts.AppendRepoConfig {
cfg = cfg.AppendConfig(repoCfg)
} else {
cfg = repoCfg
}
}
// append additional config with the rest of the config
if opts.AdditionalConfig != "" {
additionalCfg, err := config.LoadAdditionalConfig(opts.AdditionalConfig)
if err != nil {
return nil, err
}
cfg = cfg.AppendConfig(additionalCfg)
}
switch st {
@@ -92,34 +91,31 @@ func NewScanner(opts options.Options, cfg config.Config) (Scanner, error) {
if err != nil {
return nil, err
}
return NewCommitScanner(base, repo, c), nil
return NewCommitScanner(opts, cfg, repo, c), nil
case typeCommitsScanner:
commits, err := optsToCommits(opts)
if err != nil {
return nil, err
}
return NewCommitsScanner(base, repo, commits), nil
return NewCommitsScanner(opts, cfg, repo, commits), nil
case typeFilesAtCommitScanner:
c, err := obtainCommit(repo, opts.FilesAtCommit)
if err != nil {
return nil, err
}
return NewFilesAtCommitScanner(base, repo, c), nil
return NewFilesAtCommitScanner(opts, cfg, repo, c), nil
case typeUnstagedScanner:
return NewUnstagedScanner(base, repo), nil
return NewUnstagedScanner(opts, cfg, repo), nil
case typeDirScanner:
return NewParentScanner(base), nil
return NewParentScanner(opts, cfg), nil
case typeNoGitScanner:
return NewNoGitScanner(base), nil
return NewNoGitScanner(opts, cfg), nil
default:
return NewRepoScanner(base, repo), nil
return NewRepoScanner(opts, cfg, repo), nil
}
}
func scanType(opts options.Options) (ScannerType, error) {
//if opts.OwnerPath != "" {
// return typeDirScanner
//}
if opts.Commit != "" {
return typeCommitScanner, nil
}
+189 -18
View File
@@ -5,23 +5,20 @@ import (
"fmt"
"io/ioutil"
"os"
"reflect"
"runtime"
"sort"
"testing"
"github.com/zricethezav/gitleaks/v7/report"
"github.com/zricethezav/gitleaks/v7/config"
"github.com/zricethezav/gitleaks/v7/options"
"github.com/sergi/go-diff/diffmatchpatch"
)
const testRepoBase = "../test_data/test_repos/"
func TestScan(t *testing.T) {
moveDotGit("dotGit", ".git")
err := moveDotGit("dotGit", ".git")
if err != nil {
t.Fatal(err)
}
defer moveDotGit(".git", "dotGit")
tests := []struct {
description string
@@ -38,6 +35,7 @@ func TestScan(t *testing.T) {
Path: "../test_data/test_repos/test_repo_1",
Report: "../test_data/test_local_repo_one_aws_leak.json.got",
ReportFormat: "json",
Threads: runtime.GOMAXPROCS(0),
},
wantPath: "../test_data/test_local_repo_one_aws_leak.json",
},
@@ -126,6 +124,7 @@ func TestScan(t *testing.T) {
Report: "../test_data/test_local_repo_two_leaks_file_commit_range.json.got",
ReportFormat: "json",
CommitsFile: "../test_data/test_options/test_local_repo_commits.txt",
Threads: runtime.GOMAXPROCS(0),
},
wantPath: "../test_data/test_local_repo_two_leaks_file_commit_range.json",
},
@@ -204,6 +203,7 @@ func TestScan(t *testing.T) {
Path: "../test_data/test_repos/",
Report: "../test_data/test_local_owner_aws_leak.json.got",
ReportFormat: "json",
Threads: runtime.GOMAXPROCS(0),
},
wantPath: "../test_data/test_local_owner_aws_leak.json",
},
@@ -224,6 +224,7 @@ func TestScan(t *testing.T) {
Report: "../test_data/test_regex_entropy.json.got",
ConfigPath: "../test_data/test_configs/regex_entropy.toml",
ReportFormat: "json",
Threads: runtime.GOMAXPROCS(0),
},
wantPath: "../test_data/test_regex_entropy.json",
},
@@ -419,6 +420,119 @@ func TestScan(t *testing.T) {
},
wantPath: "../test_data/test_file1_aws_leak.json",
},
{
description: "test only md files no git",
opts: options.Options{
Path: "../test_data/test_repos/",
Report: "../test_data/test_only_files_no_git.json.got",
ReportFormat: "json",
ConfigPath: "../test_data/test_configs/onlyFiles.toml",
NoGit: true,
},
wantPath: "../test_data/test_only_files_no_git.json",
},
{
description: "test allowlist files",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_10",
Report: "../test_data/test_allow_list_file.json.got",
ReportFormat: "json",
ConfigPath: "../test_data/test_configs/allowlist_files.toml",
},
wantPath: "../test_data/test_allow_list_file.json",
},
{
description: "test allowlist files",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_10",
Report: "../test_data/test_allow_list_file.json.got",
ReportFormat: "json",
ConfigPath: "../test_data/test_configs/allowlist_files.toml",
},
wantPath: "../test_data/test_allow_list_file.json",
},
{
description: "test allowlist files no-git",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_10",
Report: "../test_data/test_allow_list_file_no_git.json.got",
ReportFormat: "json",
ConfigPath: "../test_data/test_configs/allowlist_files.toml",
NoGit: true,
},
wantPath: "../test_data/test_allow_list_file_no_git.json",
},
{
description: "test allowlist docx no-git",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_10",
Report: "../test_data/test_allow_list_docx_no_git.json.got",
ReportFormat: "json",
ConfigPath: "../test_data/test_configs/allowlist_docx.toml",
NoGit: true,
},
wantPath: "../test_data/test_allow_list_docx_no_git.json",
},
{
description: "test append repo config",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_10",
Report: "../test_data/test_append_repo.json.got",
ReportFormat: "json",
ConfigPath: "../test_data/test_configs/nozips.toml",
RepoConfigPath: ".gitleaks.toml",
AppendRepoConfig: true,
},
wantPath: "../test_data/test_append_repo.json",
},
{
description: "test additional config",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_10",
Report: "../test_data/test_additional_config.json.got",
ReportFormat: "json",
ConfigPath: "../test_data/test_configs/nozips.toml",
AdditionalConfig: "../test_data/test_repos/test_repo_10/.gitleaks.toml",
},
wantPath: "../test_data/test_additional_config.json",
},
{
description: "test append repo config with additional config",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_10",
Report: "../test_data/test_append_repo_additional_config.json.got",
ReportFormat: "json",
ConfigPath: "../test_data/test_configs/nozips.toml",
RepoConfigPath: ".gitleaks.toml",
AppendRepoConfig: true,
AdditionalConfig: "../test_data/test_configs/allowlist_bad_docx_10.toml",
},
wantEmpty: true,
},
{
description: "test append repo config with additional config",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_10",
Report: "../test_data/test_append_repo_additional_config.json.got",
ReportFormat: "json",
ConfigPath: "../test_data/test_configs/nozips.toml",
RepoConfigPath: ".gitleaks.toml",
AppendRepoConfig: true,
AdditionalConfig: "../test_data/test_configs/allowlist_bad_docx_10.toml",
},
wantEmpty: true,
},
{
description: "test file with no leak due to additional config no git",
opts: options.Options{
Path: "../test_data/test_repos/test_dir_1",
Report: "../test_data/fail.json.got",
ReportFormat: "json",
NoGit: false,
AdditionalConfig: "../test_data/test_configs/allowlist_allow_all_repo_1.toml",
},
wantEmpty: true,
},
}
for _, test := range tests {
@@ -457,7 +571,7 @@ func TestScan(t *testing.T) {
t.Fatal(err)
}
err = report.WriteReport(scannerReport, test.opts, cfg)
err = WriteReport(scannerReport, test.opts, cfg)
if err != nil {
t.Error(err)
}
@@ -584,7 +698,7 @@ func TestScanUncommited(t *testing.T) {
t.Fatal(err)
}
err = report.WriteReport(scannerReport, test.opts, cfg)
err = WriteReport(scannerReport, test.opts, cfg)
if err != nil {
t.Error(err)
}
@@ -611,8 +725,8 @@ func TestScanUncommited(t *testing.T) {
func fileCheck(wantPath, gotPath string) error {
var (
gotLeaks []report.Leak
wantLeaks []report.Leak
gotLeaks []Leak
wantLeaks []Leak
)
want, err := ioutil.ReadFile(wantPath)
if err != nil {
@@ -634,26 +748,82 @@ func fileCheck(wantPath, gotPath string) error {
return err
}
sort.Slice(gotLeaks, func(i, j int) bool { return (gotLeaks)[i].Commit < (gotLeaks)[j].Commit })
sort.Slice(wantLeaks, func(i, j int) bool { return (wantLeaks)[i].Commit < (wantLeaks)[j].Commit })
if !reflect.DeepEqual(gotLeaks, wantLeaks) {
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(string(want), string(got), false)
return fmt.Errorf("%s does not equal %s: %s", wantPath, gotPath, dmp.DiffPrettyText(diffs))
if len(wantLeaks) != len(gotLeaks) {
return fmt.Errorf("got %d leaks, want %d leaks", len(gotLeaks), len(wantLeaks))
}
for _, wantLeak := range wantLeaks {
found := false
for _, gotLeak := range gotLeaks {
if same(gotLeak, wantLeak) {
found = true
}
}
if !found {
return fmt.Errorf("unable to find %+v in got leaks", wantLeak)
}
}
if err := os.Remove(gotPath); err != nil {
return err
}
return nil
}
func same(l1, l2 Leak) bool {
if l1.Commit != l2.Commit {
return false
}
if l1.Offender != l2.Offender {
return false
}
if l1.Line != l2.Line {
return false
}
if l1.Tags != l2.Tags {
return false
}
if l1.LineNumber != l2.LineNumber {
return false
}
if l1.Author != l2.Author {
return false
}
if l1.LeakURL != l2.LeakURL {
return false
}
if l1.RepoURL != l2.RepoURL {
return false
}
if l1.Repo != l2.Repo {
return false
}
return true
}
func moveDotGit(from, to string) error {
repoDirs, err := ioutil.ReadDir("../test_data/test_repos")
if err != nil {
return err
}
for _, dir := range repoDirs {
if to == ".git" {
_, err := os.Stat(fmt.Sprintf("%s/%s/%s", testRepoBase, 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", testRepoBase, dir.Name(), ".git"))
}
if !dir.IsDir() {
continue
}
@@ -667,6 +837,7 @@ func moveDotGit(from, to string) error {
if err != nil {
return err
}
// fmt.Println("RENAMED")
}
return nil
}
+43
View File
@@ -0,0 +1,43 @@
package scan
import (
"runtime"
"github.com/zricethezav/gitleaks/v7/options"
)
const (
singleThreadCommitBuffer = 1
multiThreadCommitBufferMultiplier = 10
)
// Throttle is a struct that limits the number of concurrent goroutines and sets the
// number of threads available for gitleaks to use via GOMAXPROCS.
type Throttle struct {
throttle chan bool
}
// NewThrottle accepts some options and returns a throttle for scanners to use
func NewThrottle(opts options.Options) *Throttle {
t := Throttle{}
if opts.Threads <= 1 {
runtime.GOMAXPROCS(1)
t.throttle = make(chan bool, singleThreadCommitBuffer)
return &t
}
runtime.GOMAXPROCS(opts.Threads)
t.throttle = make(chan bool, multiThreadCommitBufferMultiplier*opts.Threads)
return &t
}
// Limit blocks new goroutines from spinning up if throttle is at capacity
func (t *Throttle) Limit() {
t.throttle <- true
}
// Release releases the hold on the throttle, allowing more goroutines to be spun up
func (t *Throttle) Release() {
<-t.throttle
}
+124 -28
View File
@@ -4,10 +4,13 @@ import (
"bytes"
"fmt"
"io"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/zricethezav/gitleaks/v7/report"
"github.com/zricethezav/gitleaks/v7/config"
"github.com/zricethezav/gitleaks/v7/options"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
@@ -17,25 +20,26 @@ import (
// UnstagedScanner is an unstaged scanner. This is the scanner used when you don't provide program arguments
// which will then scan your PWD. This scans unstaged changes in your repo.
type UnstagedScanner struct {
BaseScanner
opts options.Options
cfg config.Config
repo *git.Repository
repoName string
}
// NewUnstagedScanner returns an unstaged scanner
func NewUnstagedScanner(base BaseScanner, repo *git.Repository) *UnstagedScanner {
func NewUnstagedScanner(opts options.Options, cfg config.Config, repo *git.Repository) *UnstagedScanner {
us := &UnstagedScanner{
BaseScanner: base,
repo: repo,
repoName: getRepoName(base.opts),
opts: opts,
cfg: cfg,
repo: repo,
repoName: getRepoName(opts),
}
us.scannerType = typeUnstagedScanner
return us
}
// Scan kicks off an unstaged scan. This will attempt to determine unstaged changes which are then scanned.
func (us *UnstagedScanner) Scan() (report.Report, error) {
var scannerReport report.Report
func (us *UnstagedScanner) Scan() (Report, error) {
var scannerReport Report
r, err := us.repo.Head()
if err == plumbing.ErrReferenceNotFound {
wt, err := us.repo.Worktree()
@@ -53,15 +57,61 @@ func (us *UnstagedScanner) Scan() (report.Report, error) {
if err != nil {
continue
}
// Check if file is allow listed
if us.cfg.Allowlist.FileAllowed(filepath.Base(fn)) ||
us.cfg.Allowlist.PathAllowed(fn) {
continue
}
// Check individual file path ONLY rules
for _, rule := range us.cfg.Rules {
if rule.HasFileOrPathLeakOnly(fn) {
leak := NewLeak("", "Filename or path offender: "+fn, defaultLineNumber)
leak.Repo = us.repoName
leak.File = fn
leak.RepoURL = us.opts.RepoURL
leak.LeakURL = leak.URL()
leak.Rule = rule.Description
leak.Tags = strings.Join(rule.Tags, ", ")
leak.Log(us.opts)
scannerReport.Leaks = append(scannerReport.Leaks, leak)
continue
}
}
if _, err := io.Copy(workTreeBuf, workTreeFile); err != nil {
return scannerReport, err
}
leaks := checkRules(us.BaseScanner, emptyCommit(), us.repoName, workTreeFile.Name(), workTreeBuf.String())
for _, leak := range leaks {
if us.opts.Verbose {
logLeak(leak, us.opts.Redact)
lineNumber := 0
for _, line := range strings.Split(workTreeBuf.String(), "\n") {
lineNumber++
for _, rule := range us.cfg.Rules {
offender := rule.Inspect(line)
if offender == "" {
continue
}
if us.cfg.Allowlist.RegexAllowed(line) ||
rule.AllowList.FileAllowed(filepath.Base(workTreeFile.Name())) ||
rule.AllowList.PathAllowed(workTreeFile.Name()) {
continue
}
if rule.File.String() != "" && !rule.HasFileLeak(filepath.Base(workTreeFile.Name())) {
continue
}
if rule.Path.String() != "" && !rule.HasFilePathLeak(filepath.Base(workTreeFile.Name())) {
continue
}
leak := NewLeak(line, offender, defaultLineNumber).WithCommit(emptyCommit())
leak.File = workTreeFile.Name()
leak.LineNumber = lineNumber
leak.Repo = us.repoName
leak.Rule = rule.Description
leak.Tags = strings.Join(rule.Tags, ", ")
if us.opts.Verbose {
leak.Log(us.opts)
}
scannerReport.Leaks = append(scannerReport.Leaks, leak)
}
scannerReport.Leaks = append(scannerReport.Leaks, leak)
}
}
return scannerReport, nil
@@ -90,7 +140,7 @@ func (us *UnstagedScanner) Scan() (report.Report, error) {
return scannerReport, err
}
status, err := wt.Status()
status, err := gitStatus(wt)
if err != nil {
return scannerReport, err
}
@@ -144,22 +194,36 @@ func (us *UnstagedScanner) Scan() (report.Report, error) {
diffContents += fmt.Sprintf("%s\n", d.Text)
}
}
leaks := checkRules(us.BaseScanner, c, us.repoName, filename, diffContents)
lineLookup := make(map[string]bool)
for _, leak := range leaks {
for lineNumber, line := range strings.Split(prettyDiff, "\n") {
if strings.HasPrefix(line, diffAddPrefix) && strings.Contains(line, leak.Line) {
if _, ok := lineLookup[fmt.Sprintf("%s%s%d%s", leak.Offender, leak.Line, lineNumber, leak.File)]; !ok {
lineLookup[fmt.Sprintf("%s%s%d%s", leak.Offender, leak.Line, lineNumber, leak.File)] = true
leak.LineNumber = lineNumber + 1
if us.opts.Verbose {
logLeak(leak, us.opts.Redact)
}
scannerReport.Leaks = append(scannerReport.Leaks, leak)
break
}
for _, line := range strings.Split(diffContents, "\n") {
for _, rule := range us.cfg.Rules {
offender := rule.Inspect(line)
if offender == "" {
continue
}
if us.cfg.Allowlist.RegexAllowed(line) ||
rule.AllowList.FileAllowed(filepath.Base(filename)) ||
rule.AllowList.PathAllowed(filename) {
continue
}
if rule.File.String() != "" && !rule.HasFileLeak(filepath.Base(filename)) {
continue
}
if rule.Path.String() != "" && !rule.HasFilePathLeak(filepath.Base(filename)) {
continue
}
leak := NewLeak(line, offender, defaultLineNumber).WithCommit(emptyCommit())
leak.File = filename
leak.LineNumber = extractLine(prettyDiff, leak, lineLookup) + 1
leak.Repo = us.repoName
leak.Rule = rule.Description
leak.Tags = strings.Join(rule.Tags, ", ")
leak.Log(us.opts)
scannerReport.Leaks = append(scannerReport.Leaks, leak)
}
}
}
@@ -183,8 +247,40 @@ func diffPrettyText(diffs []diffmatchpatch.Diff) string {
_, _ = buff.WriteString("-")
_, _ = buff.WriteString(text)
case diffmatchpatch.DiffEqual:
_, _ = buff.WriteString(" ")
_, _ = buff.WriteString(text)
}
}
return buff.String()
}
// gitStatus returns the status of modified files in the worktree. It will attempt to execute 'git status'
// and will fall back to git.Worktree.Status() if that fails.
func gitStatus(wt *git.Worktree) (git.Status, error) {
c := exec.Command("git", "status", "--porcelain", "-z")
c.Dir = wt.Filesystem.Root()
output, err := c.Output()
if err != nil {
stat, err := wt.Status()
return stat, err
}
lines := strings.Split(string(output), "\000")
stat := make(map[string]*git.FileStatus, len(lines))
for _, line := range lines {
if len(line) == 0 {
continue
}
// For copy/rename the output looks like
// R destination\000source
// Which means we can split on space and ignore anything with only one result
parts := strings.SplitN(strings.TrimLeft(line, " "), " ", 2)
if len(parts) == 2 {
stat[strings.Trim(parts[1], " ")] = &git.FileStatus{
Staging: git.StatusCode([]byte(parts[0])[0]),
}
}
}
return stat, err
}
+6 -289
View File
@@ -2,20 +2,14 @@ package scan
import (
"bufio"
"encoding/json"
"fmt"
"math"
"os"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"time"
"github.com/zricethezav/gitleaks/v7/report"
"github.com/zricethezav/gitleaks/v7/config"
"github.com/zricethezav/gitleaks/v7/options"
"github.com/go-git/go-git/v5"
@@ -30,8 +24,6 @@ const (
diffDelPrefix = "-"
diffLineSignature = " @@"
defaultLineNumber = 1
maxLineLen = 200
)
func obtainCommit(repo *git.Repository, commitSha string) (*object.Commit, error) {
@@ -128,135 +120,6 @@ func howManyThreads(threads int) int {
return threads
}
func shouldLog(scanner BaseScanner) bool {
if scanner.opts.Verbose && scanner.scannerType != typeRepoScanner &&
scanner.scannerType != typeCommitScanner &&
scanner.scannerType != typeUnstagedScanner &&
scanner.scannerType != typeNoGitScanner {
return true
}
return false
}
func checkRules(scanner BaseScanner, commit *object.Commit, repoName, filePath, content string) []report.Leak {
filename := filepath.Base(filePath)
path := filepath.Dir(filePath)
var leaks []report.Leak
skipRuleLookup := make(map[string]bool)
// First do simple rule checks based on filename
if skipCheck(scanner.cfg, filename, path) {
return leaks
}
for _, rule := range scanner.cfg.Rules {
if isCommitAllowListed(commit.Hash.String(), rule.AllowList.Commits) {
continue
}
if skipRule(rule, filename, filePath, commit.Hash.String()) {
skipRuleLookup[rule.Description] = true
continue
}
// If it doesnt contain a Content regex then it is a filename regex match
if !ruleContainRegex(rule) {
leak := report.Leak{
LineNumber: defaultLineNumber,
Line: "",
Offender: limitLen("Filename/path offender: " + filename),
Commit: commit.Hash.String(),
Repo: repoName,
RepoURL: scanner.opts.RepoURL,
Message: limitLen(commit.Message),
Rule: rule.Description,
Author: commit.Author.Name,
Email: commit.Author.Email,
Date: commit.Author.When,
Tags: strings.Join(rule.Tags, ", "),
File: filePath,
// Operation: diffOpToString(bundle.Operation),
}
leak.LeakURL = leakURL(leak)
if shouldLog(scanner) {
logLeak(leak, scanner.opts.Redact)
}
leaks = append(leaks, leak)
}
}
lineNumber := 1
for _, line := range strings.Split(content, "\n") {
for _, rule := range scanner.cfg.Rules {
if isCommitAllowListed(commit.Hash.String(), rule.AllowList.Commits) {
break
}
if _, ok := skipRuleLookup[rule.Description]; ok {
continue
}
offender := rule.Regex.FindString(line)
if offender == "" {
continue
}
// check entropy
groups := rule.Regex.FindStringSubmatch(offender)
if isAllowListed(line, append(rule.AllowList.Regexes, scanner.cfg.Allowlist.Regexes...)) {
continue
}
if len(rule.Entropies) != 0 && !trippedEntropy(groups, rule) {
continue
}
// 0 is a match for the full regex pattern
if 0 < rule.ReportGroup && rule.ReportGroup < len(groups) {
offender = groups[rule.ReportGroup]
}
leak := report.Leak{
LineNumber: lineNumber,
Line: limitLen(line),
Offender: limitLen(offender),
Commit: commit.Hash.String(),
Repo: repoName,
RepoURL: scanner.opts.RepoURL,
Message: limitLen(commit.Message),
Rule: rule.Description,
Author: commit.Author.Name,
Email: commit.Author.Email,
Date: commit.Author.When,
Tags: strings.Join(rule.Tags, ", "),
File: filePath,
}
leak.LeakURL = leakURL(leak)
if shouldLog(scanner) {
logLeak(leak, scanner.opts.Redact)
}
leaks = append(leaks, leak)
}
lineNumber++
}
return leaks
}
func limitLen(str string) string {
if len(str) > 200 {
return str[0:maxLineLen-1] + "..."
}
return str
}
func logLeak(leak report.Leak, redact bool) {
if redact {
leak = report.RedactLeak(leak)
}
var b []byte
b, _ = json.MarshalIndent(leak, "", " ")
fmt.Println(string(b))
}
// getLogOptions determines what log options are used when iterating through commits.
// It is similar to `git log {branch}`. Default behavior is to log ALL branches so
// gitleaks gets the full git history.
@@ -307,152 +170,6 @@ func logOptions(repo *git.Repository, opts options.Options) (*git.LogOptions, er
return &git.LogOptions{All: true}, nil
}
func skipCheck(cfg config.Config, filename string, path string) bool {
// We want to check if there is a allowlist for this file
if len(cfg.Allowlist.Files) != 0 {
for _, reFileName := range cfg.Allowlist.Files {
if regexMatched(filename, reFileName) {
log.Debugf("allowlisted file found, skipping scan of file: %s", filename)
return true
}
}
}
// We want to check if there is a allowlist for this path
if len(cfg.Allowlist.Paths) != 0 {
for _, reFilePath := range cfg.Allowlist.Paths {
if regexMatched(path, reFilePath) {
log.Debugf("file in allowlisted path found, skipping scan of file: %s", filename)
return true
}
}
}
return false
}
func skipRule(rule config.Rule, filename, path, commitSha string) bool {
// For each rule we want to check filename allowlists
if isAllowListed(filename, rule.AllowList.Files) || isAllowListed(path, rule.AllowList.Paths) {
return true
}
// If it has fileNameRegex and it doesnt match we continue to next rule
if ruleContainFileRegex(rule) && !regexMatched(filename, rule.File) {
return true
}
// If it has filePathRegex and it doesnt match we continue to next rule
if ruleContainPathRegex(rule) && !regexMatched(path, rule.Path) {
return true
}
return false
}
// regexMatched matched an interface to a regular expression. The interface f can
// be a string type or go-git *object.File type.
func regexMatched(f string, re *regexp.Regexp) bool {
if re == nil {
return false
}
if re.FindString(f) != "" {
return true
}
return false
}
// trippedEntropy checks if a given capture group or offender falls in between entropy ranges
// supplied by a custom gitleaks configuration. Gitleaks do not check entropy by default.
func trippedEntropy(groups []string, rule config.Rule) bool {
for _, e := range rule.Entropies {
if len(groups) > e.Group {
entropy := shannonEntropy(groups[e.Group])
if entropy >= e.Min && entropy <= e.Max {
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
}
// Checks if the given rule has a regex
func ruleContainRegex(rule config.Rule) bool {
if rule.Regex == nil {
return false
}
if rule.Regex.String() == "" {
return false
}
return true
}
// Checks if the given rule has a file name regex
func ruleContainFileRegex(rule config.Rule) bool {
if rule.File == nil {
return false
}
if rule.File.String() == "" {
return false
}
return true
}
// Checks if the given rule has a file path regex
func ruleContainPathRegex(rule config.Rule) bool {
if rule.Path == nil {
return false
}
if rule.Path.String() == "" {
return false
}
return true
}
func isCommitAllowListed(commitHash string, allowlistedCommits []string) bool {
for _, hash := range allowlistedCommits {
if commitHash == hash {
return true
}
}
return false
}
func isAllowListed(target string, allowList []*regexp.Regexp) bool {
if len(allowList) != 0 {
for _, re := range allowList {
if re.FindString(target) != "" {
return true
}
}
}
return false
}
func optsToCommits(opts options.Options) ([]string, error) {
if opts.Commits != "" {
return strings.Split(opts.Commits, ","), nil
@@ -461,7 +178,7 @@ func optsToCommits(opts options.Options) ([]string, error) {
if err != nil {
return []string{}, err
}
defer file.Close()
defer rable(file.Close)
scanner := bufio.NewScanner(file)
var commits []string
@@ -471,7 +188,7 @@ func optsToCommits(opts options.Options) ([]string, error) {
return commits, nil
}
func extractLine(patchContent string, leak report.Leak, lineLookup map[string]bool) int {
func extractLine(patchContent string, leak Leak, lineLookup map[string]bool) int {
i := strings.Index(patchContent, fmt.Sprintf("\n+++ b/%s", leak.File))
filePatchContent := patchContent[i+1:]
i = strings.Index(filePatchContent, "diff --git")
@@ -502,9 +219,9 @@ func extractLine(patchContent string, leak report.Leak, lineLookup map[string]bo
return defaultLineNumber
}
func leakURL(leak report.Leak) string {
if leak.RepoURL != "" {
return fmt.Sprintf("%s/blob/%s/%s#L%d", leak.RepoURL, leak.Commit, leak.File, leak.LineNumber)
// rable is the second half of deferrable... mainly used for defer file.Close()
func rable(f func() error) {
if err := f(); err != nil {
log.Error(err)
}
return ""
}
+18
View File
@@ -0,0 +1,18 @@
[
{
"line": "",
"lineNumber": 1,
"offender": "Filename or path offender: tmp/bad.docx",
"commit": "b0f9b62dfe12e4e10de180359c6b9276472494f8",
"repo": "test_repo_10",
"repoURL": "",
"leakURL": "",
"rule": "Block dangerous filetypes",
"commitMessage": "Create bad.docx",
"author": "Zachary Rice",
"email": "zricer@protonmail.com",
"file": "tmp/bad.docx",
"date": "2020-12-09T11:02:10-05:00",
"tags": "key, extensions"
}
]
@@ -0,0 +1,82 @@
[
{
"line": "",
"lineNumber": 1,
"offender": "Filename or path offender: ../test_data/test_repos/test_repo_10/.gitignore",
"commit": "",
"repo": "",
"repoURL": "",
"leakURL": "",
"rule": "Block dangerous filetypes",
"commitMessage": "",
"author": "",
"email": "",
"file": "../test_data/test_repos/test_repo_10/.gitignore",
"date": "0001-01-01T00:00:00Z",
"tags": "key, extensions"
},
{
"line": "",
"lineNumber": 1,
"offender": "Filename or path offender: ../test_data/test_repos/test_repo_10/bad.zip",
"commit": "",
"repo": "",
"repoURL": "",
"leakURL": "",
"rule": "Block dangerous filetypes",
"commitMessage": "",
"author": "",
"email": "",
"file": "../test_data/test_repos/test_repo_10/bad.zip",
"date": "0001-01-01T00:00:00Z",
"tags": "key, extensions"
},
{
"line": "",
"lineNumber": 1,
"offender": "Filename or path offender: ../test_data/test_repos/test_repo_10/gitfile.txt",
"commit": "",
"repo": "",
"repoURL": "",
"leakURL": "",
"rule": "Block dangerous filetypes",
"commitMessage": "",
"author": "",
"email": "",
"file": "../test_data/test_repos/test_repo_10/gitfile.txt",
"date": "0001-01-01T00:00:00Z",
"tags": "key, extensions"
},
{
"line": "",
"lineNumber": 1,
"offender": "Filename or path offender: ../test_data/test_repos/test_repo_10/creds.git",
"commit": "",
"repo": "",
"repoURL": "",
"leakURL": "",
"rule": "Block dangerous filetypes",
"commitMessage": "",
"author": "",
"email": "",
"file": "../test_data/test_repos/test_repo_10/creds.git",
"date": "0001-01-01T00:00:00Z",
"tags": "key, extensions"
},
{
"line": "",
"lineNumber": 1,
"offender": "Filename or path offender: ../test_data/test_repos/test_repo_10/somedir.git/secret.key",
"commit": "",
"repo": "",
"repoURL": "",
"leakURL": "",
"rule": "Block dangerous filetypes",
"commitMessage": "",
"author": "",
"email": "",
"file": "../test_data/test_repos/test_repo_10/somedir.git/secret.key",
"date": "0001-01-01T00:00:00Z",
"tags": "key, extensions"
}
]
+18
View File
@@ -0,0 +1,18 @@
[
{
"line": "",
"lineNumber": 1,
"offender": "Filename or path offender: tmp/bad.docx",
"commit": "b0f9b62dfe12e4e10de180359c6b9276472494f8",
"repo": "test_repo_10",
"repoURL": "",
"leakURL": "",
"rule": "Block dangerous filetypes",
"commitMessage": "Create bad.docx",
"author": "Zachary Rice",
"email": "zricer@protonmail.com",
"file": "tmp/bad.docx",
"date": "2020-12-09T11:02:10-05:00",
"tags": "key, extensions"
}
]
@@ -0,0 +1,34 @@
[
{
"line": "",
"lineNumber": 1,
"offender": "Filename or path offender: ../test_data/test_repos/test_repo_10/somedir.git/secret.key",
"commit": "",
"repo": "",
"repoURL": "",
"leakURL": "",
"rule": "Block dangerous filetypes",
"commitMessage": "",
"author": "",
"email": "",
"file": "../test_data/test_repos/test_repo_10/somedir.git/secret.key",
"date": "0001-01-01T00:00:00Z",
"tags": "key, extensions"
},
{
"line": "",
"lineNumber": 1,
"offender": "Filename or path offender: ../test_data/test_repos/test_repo_10/tmp/bad.docx",
"commit": "",
"repo": "",
"repoURL": "",
"leakURL": "",
"rule": "Block dangerous filetypes",
"commitMessage": "",
"author": "",
"email": "",
"file": "../test_data/test_repos/test_repo_10/tmp/bad.docx",
"date": "0001-01-01T00:00:00Z",
"tags": "key, extensions"
}
]
+18
View File
@@ -0,0 +1,18 @@
[
{
"line": "",
"lineNumber": 1,
"offender": "Filename or path offender: tmp/bad.docx",
"commit": "b0f9b62dfe12e4e10de180359c6b9276472494f8",
"repo": "test_repo_10",
"repoURL": "",
"leakURL": "",
"rule": "Block dangerous filetypes",
"commitMessage": "Create bad.docx",
"author": "Zachary Rice",
"email": "zricer@protonmail.com",
"file": "tmp/bad.docx",
"date": "2020-12-09T11:02:10-05:00",
"tags": "key, extensions"
}
]
@@ -0,0 +1,3 @@
[allowlist]
description = "Allowlisted files"
files = [ '''server.test.py''','''server.test2.py''']
@@ -0,0 +1,3 @@
[allowlist]
description = "Allowlisted files"
files = [ '''bad.docx''']
@@ -0,0 +1,11 @@
[[rules]]
description = "Block dangerous filetypes"
file = '''(.*?)(creds.git|gitfile.txt|gitignore|pdf|doc|docx|zip|xls|tfplan|tfstate|tfvars|vault_pass|vagrant|pyc|key|cache)$'''
tags = ["key", "extensions"]
[rules.allowlist]
paths = ['''.docx''']
description = "ignore known locations and files"
#[allowlist]
# description = "Allowlisted files"
# paths = ['''.zip''']
@@ -0,0 +1,11 @@
[[rules]]
description = "Block dangerous filetypes"
file = '''(.*?)(pdf|doc|docx|zip|xls|tfplan|tfstate|tfvars|vault_pass|vagrant|pyc|key|cache)$'''
tags = ["key", "extensions"]
[rules.allowlist]
paths = ['''.zip''']
description = "ignore known locations and files"
#
#[allowlist]
# description = "Allowlisted files"
# paths = ['''.zip''']
@@ -0,0 +1,9 @@
[[rules]]
description = "AWS Access Key"
regex = '''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
tags = ["key", "AWS"]
[allowlist]
description = "Allowlisted files"
paths = ['''.py''']
files = ['''.md$''']
+4
View File
@@ -0,0 +1,4 @@
[[rules]]
description = "No Zips"
file = '''.*\.zip'''
+4
View File
@@ -0,0 +1,4 @@
[[rules]]
description = "flag go"
file = '''(.*?)(md)$'''
tags = ["key", "extensions"]
+8 -4
View File
@@ -3,28 +3,32 @@
"line": " aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
"lineNumber": 5,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "0000000000000000000000000000000000000000",
"commit": "",
"repo": "",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "",
"author": "",
"email": "",
"file": "../test_data/test_repos/test_dir_1/server.test.py",
"date": "1970-01-01T00:00:00Z",
"date": "0001-01-01T00:00:00Z",
"tags": "key, AWS"
},
{
"line": " aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
"lineNumber": 5,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "0000000000000000000000000000000000000000",
"commit": "",
"repo": "",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "",
"author": "",
"email": "",
"file": "../test_data/test_repos/test_dir_1/server.test2.py",
"date": "1970-01-01T00:00:00Z",
"date": "0001-01-01T00:00:00Z",
"tags": "key, AWS"
}
]
+4 -2
View File
@@ -3,14 +3,16 @@
"line": " aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
"lineNumber": 5,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "0000000000000000000000000000000000000000",
"commit": "",
"repo": "",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "",
"author": "",
"email": "",
"file": "../test_data/test_repos/test_dir_1/server.test.py",
"date": "1970-01-01T00:00:00Z",
"date": "0001-01-01T00:00:00Z",
"tags": "key, AWS"
}
]
+103 -103
View File
@@ -4,7 +4,7 @@
"lineNumber": 5,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "6557c92612d3b35979bd426d429255b3bf9fab74",
"repo": "test_repo_1",
"repo": "test_repos",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
@@ -15,22 +15,6 @@
"date": "2019-10-24T09:29:27-04:00",
"tags": "key, AWS"
},
{
"line": " const AWSKEY = \"AKIALALEMEL33243OLIBE\"",
"lineNumber": 4,
"offender": "AKIALALEMEL33243OLIB",
"commit": "b2eb34a61c988afd9b4aaa9dd58c8dd7d5f14dba",
"repo": "test_repo_2",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "adding another one\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"date": "2019-10-25T13:12:08-04:00",
"tags": "key, AWS"
},
{
"line": "Here's an AWS secret: \"AKIALALEMEL33243OLIAE\"",
"lineNumber": 3,
@@ -47,6 +31,22 @@
"date": "2019-10-25T13:01:27-04:00",
"tags": "key, AWS"
},
{
"line": " const AWSKEY = \"AKIALALEMEL33243OLIBE\"",
"lineNumber": 4,
"offender": "AKIALALEMEL33243OLIB",
"commit": "b2eb34a61c988afd9b4aaa9dd58c8dd7d5f14dba",
"repo": "test_repo_2",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "adding another one\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"date": "2019-10-25T13:12:08-04:00",
"tags": "key, AWS"
},
{
"line": "Here's an AWS secret: AKIALALEMEL33243OLIAE",
"lineNumber": 3,
@@ -63,22 +63,6 @@
"date": "2019-10-25T12:58:39-04:00",
"tags": "key, AWS"
},
{
"line": "const AWSKEY = \"AKIALALEMEL33243OLIAE\"",
"lineNumber": 3,
"offender": "AKIALALEMEL33243OLIA",
"commit": "84ac4e80d4dbf2c968b64e9d4005f5079795bb81",
"repo": "test_repo_3",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "more secrets\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"date": "2019-10-25T13:54:08-04:00",
"tags": "key, AWS"
},
{
"line": "AWS secret: \"AKIALALEMEL33243OLIAE\"",
"lineNumber": 5,
@@ -96,19 +80,19 @@
"tags": "key, AWS"
},
{
"line": " const AWSKEY = \"AKIALALEMEL33243OLIBE\"",
"lineNumber": 4,
"offender": "AKIALALEMEL33243OLIB",
"commit": "b2eb34a61c988afd9b4aaa9dd58c8dd7d5f14dba",
"line": "const AWSKEY = \"AKIALALEMEL33243OLIAE\"",
"lineNumber": 3,
"offender": "AKIALALEMEL33243OLIA",
"commit": "84ac4e80d4dbf2c968b64e9d4005f5079795bb81",
"repo": "test_repo_3",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "adding another one\n",
"commitMessage": "more secrets\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"date": "2019-10-25T13:12:08-04:00",
"date": "2019-10-25T13:54:08-04:00",
"tags": "key, AWS"
},
{
@@ -144,19 +128,19 @@
"tags": "key, AWS"
},
{
"line": "const AWSKEY = \"AKIALALEMEL33243OLIAE\"",
"lineNumber": 3,
"offender": "AKIALALEMEL33243OLIA",
"commit": "84ac4e80d4dbf2c968b64e9d4005f5079795bb81",
"repo": "test_repo_4",
"line": " const AWSKEY = \"AKIALALEMEL33243OLIBE\"",
"lineNumber": 4,
"offender": "AKIALALEMEL33243OLIB",
"commit": "b2eb34a61c988afd9b4aaa9dd58c8dd7d5f14dba",
"repo": "test_repo_3",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "more secrets\n",
"commitMessage": "adding another one\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"date": "2019-10-25T13:54:08-04:00",
"date": "2019-10-25T13:12:08-04:00",
"tags": "key, AWS"
},
{
@@ -175,6 +159,38 @@
"date": "2019-10-25T13:35:03-04:00",
"tags": "key, AWS"
},
{
"line": "const AWSKEY = \"AKIALALEMEL33243OLIAE\"",
"lineNumber": 3,
"offender": "AKIALALEMEL33243OLIA",
"commit": "84ac4e80d4dbf2c968b64e9d4005f5079795bb81",
"repo": "test_repo_4",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "more secrets\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"date": "2019-10-25T13:54:08-04:00",
"tags": "key, AWS"
},
{
"line": "Here's an AWS secret: AKIALALEMEL33243OLIAE",
"lineNumber": 3,
"offender": "AKIALALEMEL33243OLIA",
"commit": "b10b3e2cb320a8c211fda94c4567299d37de7776",
"repo": "test_repo_4",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "adding aws key\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"date": "2019-10-25T12:58:39-04:00",
"tags": "key, AWS"
},
{
"line": " const AWSKEY = \"AKIALALEMEL33243OLIBE\"",
"lineNumber": 4,
@@ -207,38 +223,6 @@
"date": "2019-10-25T13:01:27-04:00",
"tags": "key, AWS"
},
{
"line": "Here's an AWS secret: AKIALALEMEL33243OLIAE",
"lineNumber": 3,
"offender": "AKIALALEMEL33243OLIA",
"commit": "b10b3e2cb320a8c211fda94c4567299d37de7776",
"repo": "test_repo_4",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "adding aws key\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"date": "2019-10-25T12:58:39-04:00",
"tags": "key, AWS"
},
{
"line": "aws_access_key_id='AKIAIO5FODNN7EXAMPL2'",
"lineNumber": 4,
"offender": "AKIAIO5FODNN7EXAMPL2",
"commit": "ca71fcdeda15f25f0cc661d90e8785c255925c27",
"repo": "test_repo_5",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "introduce more secrets\n",
"author": "Zach Rice",
"email": "zrice@gitlab.com",
"file": "secrets.py",
"date": "2020-02-01T10:08:04-05:00",
"tags": "key, AWS"
},
{
"line": "aws_access_key_id='AKIAIO5FODNN7EXAMPLE'",
"lineNumber": 1,
@@ -255,12 +239,28 @@
"date": "2020-02-01T10:07:34-05:00",
"tags": "key, AWS"
},
{
"line": "aws_access_key_id='AKIAIO5FODNN7EXAMPL2'",
"lineNumber": 4,
"offender": "AKIAIO5FODNN7EXAMPL2",
"commit": "ca71fcdeda15f25f0cc661d90e8785c255925c27",
"repo": "test_repo_5",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "introduce more secrets\n",
"author": "Zach Rice",
"email": "zrice@gitlab.com",
"file": "secrets.py",
"date": "2020-02-01T10:08:04-05:00",
"tags": "key, AWS"
},
{
"line": " aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
"lineNumber": 5,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "6557c92612d3b35979bd426d429255b3bf9fab74",
"repo": "test_repo_6",
"repo": "test_repos",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
@@ -287,22 +287,6 @@
"date": "2020-02-24T14:13:15-05:00",
"tags": "key, AWS"
},
{
"line": "aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
"lineNumber": 6,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "748f11eaf2c38c3cf0ac6a22e44208777e79fa6f",
"repo": "test_repo_8",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "Merge pull request #1 from zricethezav/additional-secret-branch\n\nUpdate dummy.txt",
"author": "Zachary Rice",
"email": "zricer@protonmail.com",
"file": "dummy.txt",
"date": "2020-07-25T14:44:48-04:00",
"tags": "key, AWS"
},
{
"line": "aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
"lineNumber": 2,
@@ -336,19 +320,19 @@
"tags": "key, AWS"
},
{
"line": " aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
"lineNumber": 5,
"line": "aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
"lineNumber": 6,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "6557c92612d3b35979bd426d429255b3bf9fab74",
"repo": "test_repo_9",
"commit": "748f11eaf2c38c3cf0ac6a22e44208777e79fa6f",
"repo": "test_repo_8",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "commit 1 with secrets\n",
"author": "zach rice",
"commitMessage": "Merge pull request #1 from zricethezav/additional-secret-branch\n\nUpdate dummy.txt",
"author": "Zachary Rice",
"email": "zricer@protonmail.com",
"file": "server.test.py",
"date": "2019-10-24T09:29:27-04:00",
"file": "dummy.txt",
"date": "2020-07-25T14:44:48-04:00",
"tags": "key, AWS"
},
{
@@ -366,5 +350,21 @@
"file": "server.test.py",
"date": "2020-08-12T13:36:20-04:00",
"tags": "key, AWS"
},
{
"line": " aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
"lineNumber": 5,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "6557c92612d3b35979bd426d429255b3bf9fab74",
"repo": "test_repos",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "commit 1 with secrets\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "server.test.py",
"date": "2019-10-24T09:29:27-04:00",
"tags": "key, AWS"
}
]
@@ -239,22 +239,6 @@
"date": "2020-02-01T10:07:34-05:00",
"tags": "key, AWS"
},
{
"line": " aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
"lineNumber": 5,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "6557c92612d3b35979bd426d429255b3bf9fab74",
"repo": "test_repo_6",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "commit 1 with secrets\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "server.test.py",
"date": "2019-10-24T09:29:27-04:00",
"tags": "key, AWS"
},
{
"line": "aws_access_key_id=AKIAIO5FODNN7EXAMPLE",
"lineNumber": 3,
@@ -271,6 +255,22 @@
"date": "2020-02-24T14:13:15-05:00",
"tags": "key, AWS"
},
{
"line": " aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
"lineNumber": 5,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "6557c92612d3b35979bd426d429255b3bf9fab74",
"repo": "test_repos",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "commit 1 with secrets\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "server.test.py",
"date": "2019-10-24T09:29:27-04:00",
"tags": "key, AWS"
},
{
"line": "aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
"lineNumber": 6,
@@ -319,22 +319,6 @@
"date": "2020-07-25T14:41:11-04:00",
"tags": "key, AWS"
},
{
"line": " aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
"lineNumber": 5,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "6557c92612d3b35979bd426d429255b3bf9fab74",
"repo": "test_repo_9",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "commit 1 with secrets\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "server.test.py",
"date": "2019-10-24T09:29:27-04:00",
"tags": "key, AWS"
},
{
"line": " aws_access_key_id='AKIAIO5FODNN7EXAMPLE', #gitleaks:allow",
"lineNumber": 5,
@@ -350,5 +334,21 @@
"file": "server.test.py",
"date": "2020-08-12T13:36:20-04:00",
"tags": "key, AWS"
},
{
"line": " aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
"lineNumber": 5,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "6557c92612d3b35979bd426d429255b3bf9fab74",
"repo": "test_repos",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "commit 1 with secrets\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "server.test.py",
"date": "2019-10-24T09:29:27-04:00",
"tags": "key, AWS"
}
]
@@ -4,7 +4,7 @@
"lineNumber": 5,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "6557c92612d3b35979bd426d429255b3bf9fab74",
"repo": "test_repo_1",
"repo": "test_repos",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
+9 -6
View File
@@ -5,14 +5,15 @@
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "748f11eaf2c38c3cf0ac6a22e44208777e79fa6f",
"repo": "test_repo_8",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "Merge pull request #1 from zricethezav/additional-secret-branch\n\nUpdate dummy.txt",
"author": "Zachary Rice",
"email": "zricer@protonmail.com",
"file": "dummy.txt",
"date": "2020-07-25T14:44:48-04:00",
"tags": "key, AWS",
"operation": "addition"
"tags": "key, AWS"
},
{
"line": "aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
@@ -20,14 +21,15 @@
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "ce7e8177bbf8a172c06b6a1e370a374d5c19f660",
"repo": "test_repo_8",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "dummy.txt w/ text",
"author": "Zachary Rice",
"email": "zricer@protonmail.com",
"file": "dummy.txt",
"date": "2020-07-25T14:39:11-04:00",
"tags": "key, AWS",
"operation": "addition"
"tags": "key, AWS"
},
{
"line": "aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
@@ -35,13 +37,14 @@
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "9267bc86ec1497471cbc6f3308f3527f7ef34b9d",
"repo": "test_repo_8",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "Update dummy.txt",
"author": "Zachary Rice",
"email": "zricer@protonmail.com",
"file": "dummy.txt",
"date": "2020-07-25T14:41:11-04:00",
"tags": "key, AWS",
"operation": "addition"
"tags": "key, AWS"
}
]
+3 -2
View File
@@ -5,13 +5,14 @@
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "6557c92612d3b35979bd426d429255b3bf9fab74",
"repo": "test_repo_1",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "commit 1 with secrets\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "server.test.py",
"date": "2019-10-24T09:29:27-04:00",
"tags": "key, AWS",
"operation": "addition"
"tags": "key, AWS"
}
]
+146
View File
@@ -0,0 +1,146 @@
[
{
"line": "",
"lineNumber": 1,
"offender": "Filename or path offender: ../test_data/test_repos/test_repo_10/README.md",
"commit": "",
"repo": "",
"repoURL": "",
"leakURL": "",
"rule": "flag go",
"commitMessage": "",
"author": "",
"email": "",
"file": "../test_data/test_repos/test_repo_10/README.md",
"date": "0001-01-01T00:00:00Z",
"tags": "key, extensions"
},
{
"line": "",
"lineNumber": 1,
"offender": "Filename or path offender: ../test_data/test_repos/test_repo_2/secrets.md",
"commit": "",
"repo": "",
"repoURL": "",
"leakURL": "",
"rule": "flag go",
"commitMessage": "",
"author": "",
"email": "",
"file": "../test_data/test_repos/test_repo_2/secrets.md",
"date": "0001-01-01T00:00:00Z",
"tags": "key, extensions"
},
{
"line": "",
"lineNumber": 1,
"offender": "Filename or path offender: ../test_data/test_repos/test_repo_2/no_secrets.md",
"commit": "",
"repo": "",
"repoURL": "",
"leakURL": "",
"rule": "flag go",
"commitMessage": "",
"author": "",
"email": "",
"file": "../test_data/test_repos/test_repo_2/no_secrets.md",
"date": "0001-01-01T00:00:00Z",
"tags": "key, extensions"
},
{
"line": "",
"lineNumber": 1,
"offender": "Filename or path offender: ../test_data/test_repos/test_repo_3/no_secrets.md",
"commit": "",
"repo": "",
"repoURL": "",
"leakURL": "",
"rule": "flag go",
"commitMessage": "",
"author": "",
"email": "",
"file": "../test_data/test_repos/test_repo_3/no_secrets.md",
"date": "0001-01-01T00:00:00Z",
"tags": "key, extensions"
},
{
"line": "",
"lineNumber": 1,
"offender": "Filename or path offender: ../test_data/test_repos/test_repo_3/secrets.md",
"commit": "",
"repo": "",
"repoURL": "",
"leakURL": "",
"rule": "flag go",
"commitMessage": "",
"author": "",
"email": "",
"file": "../test_data/test_repos/test_repo_3/secrets.md",
"date": "0001-01-01T00:00:00Z",
"tags": "key, extensions"
},
{
"line": "",
"lineNumber": 1,
"offender": "Filename or path offender: ../test_data/test_repos/test_repo_4/secrets.md",
"commit": "",
"repo": "",
"repoURL": "",
"leakURL": "",
"rule": "flag go",
"commitMessage": "",
"author": "",
"email": "",
"file": "../test_data/test_repos/test_repo_4/secrets.md",
"date": "0001-01-01T00:00:00Z",
"tags": "key, extensions"
},
{
"line": "",
"lineNumber": 1,
"offender": "Filename or path offender: ../test_data/test_repos/test_repo_4/no_secrets.md",
"commit": "",
"repo": "",
"repoURL": "",
"leakURL": "",
"rule": "flag go",
"commitMessage": "",
"author": "",
"email": "",
"file": "../test_data/test_repos/test_repo_4/no_secrets.md",
"date": "0001-01-01T00:00:00Z",
"tags": "key, extensions"
},
{
"line": "",
"lineNumber": 1,
"offender": "Filename or path offender: ../test_data/test_repos/test_repo_5/notes.md",
"commit": "",
"repo": "",
"repoURL": "",
"leakURL": "",
"rule": "flag go",
"commitMessage": "",
"author": "",
"email": "",
"file": "../test_data/test_repos/test_repo_5/notes.md",
"date": "0001-01-01T00:00:00Z",
"tags": "key, extensions"
},
{
"line": "",
"lineNumber": 1,
"offender": "Filename or path offender: ../test_data/test_repos/test_repo_8/README.md",
"commit": "",
"repo": "",
"repoURL": "",
"leakURL": "",
"rule": "flag go",
"commitMessage": "",
"author": "",
"email": "",
"file": "../test_data/test_repos/test_repo_8/README.md",
"date": "0001-01-01T00:00:00Z",
"tags": "key, extensions"
}
]
File renamed without changes.
@@ -0,0 +1 @@
a dot git ignore file
@@ -0,0 +1,11 @@
[[rules]]
description = "Block dangerous filetypes"
file = '''(.*?)(pdf|doc|docx|zip|xls|tfplan|tfstate|tfvars|vault_pass|vagrant|pyc|key|cache)$'''
tags = ["key", "extensions"]
[rules.allowlist]
paths = ['''.git''', '''.zip''']
description = "ignore known locations and files"
[allowlist]
description = "Allowlisted files"
paths = ['''.zip''']
@@ -0,0 +1 @@
# test_repo_paths
@@ -0,0 +1 @@
this is a bad .zip
Whitespace-only changes.
@@ -0,0 +1 @@
ref: refs/heads/main
Whitespace-only changes.
@@ -0,0 +1,13 @@
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
precomposeunicode = true
[remote "origin"]
url = git@github.com:zricethezav/test_repo_paths.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "main"]
remote = origin
merge = refs/heads/main
@@ -0,0 +1 @@
Unnamed repository; edit this file 'description' to name the repository.
Binary file not shown.
@@ -0,0 +1,6 @@
# git ls-files --others --exclude-from=.git/info/exclude
# Lines that start with '#' are comments.
# For a project mostly in C, the following would be a good set of
# exclude patterns (uncomment them if you want to use them):
# *.[oa]
# *~
@@ -0,0 +1 @@
0000000000000000000000000000000000000000 5cd9652a24771400b4ce76beadbb2496a73341b8 Zach Rice <zrice@gitlab.com> 1607529853 -0500 clone: from github.com:zricethezav/test_repo_paths.git
@@ -0,0 +1 @@
0000000000000000000000000000000000000000 5cd9652a24771400b4ce76beadbb2496a73341b8 Zach Rice <zrice@gitlab.com> 1607529853 -0500 clone: from github.com:zricethezav/test_repo_paths.git
@@ -0,0 +1 @@
0000000000000000000000000000000000000000 5cd9652a24771400b4ce76beadbb2496a73341b8 Zach Rice <zrice@gitlab.com> 1607529853 -0500 clone: from github.com:zricethezav/test_repo_paths.git
@@ -0,0 +1,2 @@
# pack-refs with: peeled fully-peeled sorted
5cd9652a24771400b4ce76beadbb2496a73341b8 refs/remotes/origin/main
@@ -0,0 +1 @@
5cd9652a24771400b4ce76beadbb2496a73341b8
@@ -0,0 +1 @@
ref: refs/remotes/origin/main
@@ -0,0 +1 @@
a git file
@@ -0,0 +1 @@
hah
@@ -0,0 +1 @@
bad .docx