Compare commits

...
50 Commits
Author SHA1 Message Date
zach rice 5bd59b0d8c bump 2019-08-01 17:39:09 -05:00
zach rice 464e152783 rm vendor and changelog 2019-08-01 17:15:28 -05:00
Zachary Rice 91406b0c4c Merge pull request #184 from JCofman/feature/gitlabTokenSupport
Feature/gitlab token support
2019-08-01 17:13:44 -05:00
Zachary Rice 04e81270cb Merge pull request #244 from cfzlp/non-zero-exit-for-leaks
Return exit code 1 when leaks are found
2019-08-01 09:50:24 -05:00
Ixl123 69c6695765 resolve merge conflicts 2019-08-01 13:46:51 +02:00
Carlos Pereira 9e0e050f92 Return exit code 1 when leaks are found 2019-07-31 23:21:30 +02:00
Zachary Rice b2efcf36c8 Merge pull request #241 from manasmbellani/enhance_apikey_rule
constants.go(enhance): added an enhancement to include apikey without…
2019-07-15 21:54:16 -05:00
Manas Bellani ba39abfb19 constants.go(enhance): added an enhancement to include apikey without underscore as another detection for api keys that might be present in source code 2019-07-16 12:31:49 +10:00
zricethezav f47e1f71ee cleaner and bounded regex for generic keys and secrets 2019-07-14 15:16:46 -05:00
Zachary Rice 6d980b4eab Code cleaning (#240) 2019-07-10 10:32:51 -05:00
Zachary Rice ca18e8e2f6 Merge pull request #239 from cfzlp/fix-repo-config
Fix updating config from repo-config
2019-07-09 16:52:08 -05:00
Zachary Rice ec436d7b33 Merge pull request #230 from eargollo/windows-log
Fixed Windows output to be consistent with Linux output (colors)
2019-07-09 16:48:54 -05:00
Zachary Rice 38a511f6ba Merge pull request #236 from dorneanu/fix-commit-option
Implemented right way to scan for files in a commit (by using --commit)
2019-07-09 16:42:31 -05:00
Carlos Pereira 15ac1ffdd1 Fix updating config from repo-config 2019-07-07 14:57:57 +02:00
Victor Dorneanu eb977ba237 Differentiate between commits with parents and commits w/o parents 2019-06-19 14:28:10 +02:00
Victor Dorneanu 9a6b1c3bbb Implemented right way to scan for files in a commit (by using --commit) 2019-06-18 19:03:54 +02:00
Zachary Rice 95443e742c Merge pull request #231 from jesmg/master
Add new default rules
2019-06-18 07:56:55 -05:00
Jesús Marín 0c94db2d6b Improve rules 2019-06-18 10:27:50 +02:00
Jesús Marín 9808551eed Add new default rules 2019-06-17 15:04:33 +02:00
Eduardo Argollo b6fe5b08d3 Added colors to Windows output making it consistent with Linux one 2019-06-06 11:30:33 -07:00
Eduardo Argollo 5309811a09 Merge remote-tracking branch 'upstream/master' 2019-06-06 11:13:51 -07:00
zach rice 3b6c198715 fixing test 2019-06-02 20:55:24 -05:00
Zachary Rice 57bfa41b33 Merge pull request #224 from eargollo/overwrite-error
Solved bug on error being overwritten and not passed to postAudit, closes #223
2019-06-02 17:53:05 -05:00
Zachary Rice 474266c0b5 Merge pull request #226 from eargollo/windows-test
Adapt test message to run tests in Windows
2019-06-02 17:49:26 -05:00
Eduardo Argollo c891470344 Merge pull request #1 from eargollo/windows-test
Adapt test message to run tests in Windows
2019-05-31 09:56:44 -07:00
Eduardo Argollo e6004da801 Adapt test message to run tests in Windows 2019-05-31 09:52:21 -07:00
Eduardo Argollo e18b1a884a Updating expected error message 2019-05-30 15:11:37 -07:00
Eduardo Argollo faeb0914b2 Solving error on authentication 2019-05-30 15:09:45 -07:00
Eduardo Argollo d6578df998 Solved bug on error being overwritten and not passed to postAudit, closes #223 2019-05-28 15:35:10 -07:00
Zachary Rice f010513d17 Merge pull request #222 from martelo/modify-single-commit-audit
Modify single commit audit
2019-05-28 17:00:13 -05:00
Cassio Berra d4be9602e3 Removing other unnecessary references to opts.Commit 2019-05-18 01:24:18 +00:00
Cassio Berra 7676690697 Audit single commit without iterating through all commits 2019-05-18 01:02:46 +00:00
Zachary Rice f4b9b6d0b3 Merge pull request #204 from luispollo/fix-repo-path-logging
Fix logging of repo paths
2019-05-06 10:00:27 -05:00
Luis Pollo 7a3d155675 Fix logging of repo paths 2019-05-06 08:53:02 -05:00
Zachary Rice 68b6388ef7 Merge pull request #202 from MaxymVlasov/docs/improve_examples
Add more examples and improve README structure
2019-04-30 11:30:31 -05:00
MaxymVlasov 547e9768ec Add more examples and improve README structure 2019-04-30 18:08:58 +03:00
Zachary Rice 8608cf5b48 Merge pull request #198 from theoretick/patch-1
Update README - formatting fixes
2019-04-19 10:34:46 -05:00
Lucas Charles a08ddedb88 Update README - formatting fixes 2019-04-19 08:28:33 -07:00
Zachary Rice 398366a615 Merge pull request #196 from zricethezav/v2.0.0
V2.0.0
2019-04-16 19:00:12 -05:00
zach rice 7dfa3f2b48 last updates? 2019-04-16 18:13:24 -05:00
zach rice 2e7325ce03 adding some more tests during lunch 2019-04-16 12:04:00 -05:00
zach rice cb74386ef0 working on filetype filtering 2019-04-13 16:48:57 -05:00
zach rice 87d6c588a6 removing validating config, already handled 2019-04-13 14:09:16 -05:00
zach rice df8a2d35a8 cleaning up 2019-04-13 13:50:14 -05:00
zach rice c4da547503 fmt 2019-04-13 13:12:58 -05:00
zach rice 7bd55e33b5 working tests out 2019-04-13 12:30:00 -05:00
zach rice 256ace38d7 workin on new filters 2019-04-11 18:06:18 -05:00
Ixl123 4bc7c13310 Merge branch 'master' of https://github.com/zricethezav/gitleaks 2019-03-08 14:44:56 +01:00
Ixl123 771055fd59 add changelog and format go code 2019-03-08 14:38:47 +01:00
Jacob Cofman 75c70bf804 try this 2019-03-06 23:31:15 +01:00
19 changed files with 1176 additions and 579 deletions

No files matched your search

+2 -1
View File
@@ -9,4 +9,5 @@
*.test
*.out
tmp
examples
src/gitleaksConfig
+17
View File
@@ -1,5 +1,22 @@
CHANGELOG
=========
2.1.0
- `--commit` does not iterate on commit history. Now it directly accesses the commit object. https://github.com/zricethezav/gitleaks/pull/236
- Fixing logging local repo path https://github.com/zricethezav/gitleaks/pull/204
- Better README examples https://github.com/zricethezav/gitleaks/pull/202
- Better logging on Windows https://github.com/zricethezav/gitleaks/pull/230
- Better error messaging
- Bunch new default rules https://github.com/zricethezav/gitleaks/pull/231 https://github.com/zricethezav/gitleaks/pull/241
- `--repo-config` works on orgs and users now https://github.com/zricethezav/gitleaks/pull/239
- Proper exit codes https://github.com/zricethezav/gitleaks/pull/244
- Gitlab Token support https://github.com/zricethezav/gitleaks/pull/184
2.0.0
----
- rules introduced in the gitleaks configurationn
- removing `--entropy` option
- removing `--single-search` option
1.25.1
----
- Fixing #188
-5
View File
@@ -20,8 +20,3 @@ build-all:
env GOOS="linux" GOARCH="mips" go build -o "build/gitleaks-linux-mips"
env GOOS="linux" GOARCH="mips" go build -o "build/gitleaks-linux-mips"
env GOOS="darwin" GOARCH="amd64" go build -o "build/gitleaks-darwin-amd64"
benchmark:
go test -run=Benchmark -bench=. -benchtime=5s
benchmark-fast:
go test -bench=BenchmarkAuditLeakRepo -run=BenchmarkAuditLeakRepo$
+90 -25
View File
@@ -1,62 +1,59 @@
Gitleaks
--------
<p align="left">
<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>
</p>
Audit git repos for secrets. Gitleaks provides a way for you to find unencrypted secrets and other unwanted data types in git source code repositories. As part of it's core functionality, it provides;
</p>
Audit git repos for secrets. Gitleaks provides a way for you to find unencrypted secrets and other unwanted data types in git source code repositories. As part of it's core functionality, it provides:
* Github and Gitlab support including support for bulk organization and repository owner (user) repository scans, as well as pull request scanning for use in common CI workflows.
* Support for private repository scans, and repositories that require key based authentication
* Output in CSV and JSON formats for consumption in other reporting tools and frameworks
* Externalised configuration for environment specific customisation including regex rules
* Customizable repository name, file type, commit ID, branchname and regex whitelisting to reduce false positives
* Customizable repository name, file type, commit ID, branch name and regex whitelisting to reduce false positives
* High performance through the use of src-d's [go-git](https://github.com/src-d/go-git) framework
It has been successfully used in a number of different scenarios, including:
It has been sucessfully used in a number of different scenarios, including;
* Adhoc scans of local and remote repositories by filesystem path or clone URL
* Automated scans of github users and organizations (Both public and enterprise platforms)
* As part of a CICD workflow to identify secrets before they make it deeper into your codebase
* As part of a wider secrets auditing automation capability for git data in large environments
### Example execution
## Example execution
<p align="left">
<img src="https://cdn.rawgit.com/zricethezav/5bf8259b7fea0170becffc06b8588edb/raw/f762769fe20ef3669bff34612b1bede6457631e6/termtosvg_je8bp82s.svg">
</p>
#### Installation
## 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, as per the below;
##### MacOS
#### MacOS
```
brew install gitleaks
```
##### Docker
#### Docker
```bash
# Run gitleaks against a public repository
docker run --rm --name=gitleaks zricethezav/gitleaks -v -r https://github.com/zricethezav/gitleaks.git
# Run gitleaks against a local repository already cloned into /tmp/
docker run --rm --name=gitleaks -v /tmp/:/code/ zricethezav/gitleaks -v --repo-path=/code/gitleaks
# Run gitleaks against a specific Github Pull request
docker run --rm --name=gitleaks -e GITHUB_TOKEN={your token} zricethezav/gitleaks --github-pr=https://github.com/owner/repo/pull/9000
docker pull zricethezav/gitleaks
```
##### Go
#### Go
```bash
go get -u github.com/zricethezav/gitleaks
```
#### Usage and Options
gitleaks has a wide range of configuration options that can be adjusted at runtime or via a configuration file based on your specific requirements.
## Usage and Options
gitleaks has a wide range of configuration options that can be adjusted at runtime or via a configuration file based on your specific requirements.
```
Usage:
@@ -77,12 +74,9 @@ Application Options:
--owner-path= Path to owner directory (repos discovered)
--threads= Maximum number of threads gitleaks spawns
--disk Clones repo(s) to disk
--single-search= single regular expression to search for
--config= path to gitleaks config
--ssh-key= path to ssh key
--exclude-forks exclude forks for organization/user audits
-e, --entropy= Include entropy checks during audit. Entropy scale: 0.0(no entropy) - 8.0(max entropy)
--noise-reduction Reduce the number of finds when entropy checks are enabled
--repo-config Load config from target repo. Config file must be ".gitleaks.toml"
--branch= Branch to audit
-l, --log= log level
@@ -96,7 +90,76 @@ Help Options:
-h, --help Show this help message
```
#### Exit Codes
### Docker usage examples
Run gitleaks against:
###### Public repository
```bash
docker run --rm --name=gitleaks zricethezav/gitleaks -v -r https://github.com/zricethezav/gitleaks.git
```
###### Local repository already cloned into /tmp/
```bash
docker run --rm --name=gitleaks -v /tmp/:/code/ zricethezav/gitleaks -v --repo-path=/code/gitleaks
```
###### Specific Github Pull request
You need GitHub token with `repo` access. [How create token](https://help.github.com/en/articles/creating-a-personal-access-token-for-the-command-line).
```bash
export GITHUB_TOKEN=""
docker run --rm --name=gitleaks \
-e GITHUB_TOKEN=${GITHUB_TOKEN} \
zricethezav/gitleaks \
--github-pr=https://github.com/owner/repo/pull/9000
```
###### Private repository
You need private SSH key associated with user which have pull access to private repo.
```bash
export SSH_KEY_DIR=$(echo $HOME)/.ssh
export SSH_KEY_NAME=id_rsa
export REPO="git@github.com:zricethezav/gitleaks.git"
docker run --rm --name=gitleaks \
--mount type=bind,src=${SSH_KEY_DIR},dst=/root/.ssh,readonly \
zricethezav/gitleaks \
--ssh-key=/root/.ssh/${SSH_KEY_NAME} \
--verbose \
--repo=${REPO}
```
###### Specific Github organization with private repos
You need GitHub token with `repo` access. [How create token](https://help.github.com/en/articles/creating-a-personal-access-token-for-the-command-line).
```bash
export GITHUB_TOKEN=""
export ORG="github_org_name" # "git" in "https://github.com/git/", for instance.
docker run --rm --name=gitleaks \
-e GITHUB_TOKEN=${GITHUB_TOKEN} \
zricethezav/gitleaks \
--verbose \
--disk \
--threads=$(($(nproc --all) - 1)) \
--github-org=${ORG}
```
By default repos cloned to memory. Using `--disk` for clone to disk or you can quickly out of memory.
For speed up analyze operation using `--threads` parameter, which set to `ALL - 1` treads at your instance CPU.
## Exit Codes
Gitleaks provides consistent exist codes to assist in automation workflows such as CICD platforms and bulk scanning.
These can be effectively used in conjunction with the report output file to detect and return meaningful data back to the user or external system about if leaks have been detected, and where they reside.
@@ -109,7 +172,8 @@ The code return codes are:
2: error encountered
```
### Additional information
## Additional information
* Additional documentation about how gitleaks functions can be found on the [wiki page](https://github.com/zricethezav/gitleaks/wiki)
* The below links detail the various approaches to remediating unwanted data in git repos
* [Removing sensitive data from a repository (github.com)](https://help.github.com/articles/removing-sensitive-data-from-a-repository/)
@@ -122,7 +186,8 @@ The code return codes are:
* How does gitleaks differ to Github token scanning?
* [Github recently announced](https://blog.github.com/2018-10-16-future-of-software/#github-token-scanning-for-public-repositories-public-beta) a new capability to their cloud platform that detects exposed credentials for a number of common services and platforms and automatically notifies the provider for revocation or similar action. Gitleaks provides a similar detection capability for non-Github cloud users, in which repositories can be easily audited and results provided in a number of formats.
### Give Thanks
## Give Thanks
If using gitleaks has made you job easier consider donating to an organization, C-U at Home, that does vital work for those who most need it in the community of Champaign-Urbana, IL (my home).
Donate: https://www.cuathome.us/give/
+207 -27
View File
@@ -1,39 +1,219 @@
title = "gitleaks config"
[[regexes]]
description = "AWS"
regex = '''AKIA[0-9A-Z]{16}'''
[[regexes]]
description = "RKCS8"
title = "sample gitleaks config"
# This is a sample config file for gitleaks. You can configure gitleaks what to search for and what to whitelist.
# The output you are seeing here is the default gitleaks config. If GITLEAKS_CONFIG environment variable
# is set, gitleaks will load configurations from that path. If option --config-path is set, gitleaks will load
# configurations from that path. Gitleaks does not whitelist anything by default.
# - https://www.ndss-symposium.org/wp-content/uploads/2019/02/ndss2019_04B-3_Meli_paper.pdf
# - https://github.com/dxa4481/truffleHogRegexes/blob/master/truffleHogRegexes/regexes.json
[[rules]]
description = "AWS Client ID"
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"]
[[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"]
[[rules]]
description = "PKCS8"
regex = '''-----BEGIN PRIVATE KEY-----'''
[[regexes]]
tags = ["key", "PKCS8"]
[[rules]]
description = "RSA"
regex = '''-----BEGIN RSA PRIVATE KEY-----'''
[[regexes]]
description = "Github"
regex = '''(?i)github.*['\"][0-9a-zA-Z]{35,40}['\"]'''
[[regexes]]
tags = ["key", "RSA"]
[[rules]]
description = "SSH"
regex = '''-----BEGIN OPENSSH PRIVATE KEY-----'''
[[regexes]]
description = "Facebook"
regex = '''(?i)facebook.*['\"][0-9a-f]{32}['\"]'''
[[regexes]]
description = "Twitter"
regex = '''(?i)twitter.*['\"][0-9a-zA-Z]{35,44}['\"]'''
[[regexes]]
tags = ["key", "SSH"]
[[rules]]
description = "PGP"
regex = '''-----BEGIN PGP PRIVATE KEY BLOCK-----'''
[[regexes]]
description = "Slack token"
regex = '''xox[baprs]-.*'''
[[regexes]]
description = "Strip API Key"
regex = '''(?i)(sk|pk)_(test|live)_[0-9a-zA-Z]{10,32}'''
tags = ["key", "PGP"]
[[rules]]
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"]
[[rules]]
description = "Facebook access token"
regex = '''EAACEdEose0cBA[0-9A-Za-z]+'''
tags = ["key", "Facebook"]
[[rules]]
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"]
[[rules]]
description = "Github"
regex = '''(?i)github(.{0,20})?(?-i)['\"][0-9a-zA-Z]{35,40}['\"]'''
tags = ["key", "Github"]
[[rules]]
description = "LinkedIn Client ID"
regex = '''(?i)linkedin(.{0,20})?(?-i)['\"][0-9a-z]{12}['\"]'''
tags = ["client", "Twitter"]
[[rules]]
description = "LinkedIn Secret Key"
regex = '''(?i)linkedin(.{0,20})?['\"][0-9a-z]{16}['\"]'''
tags = ["secret", "Twitter"]
[[rules]]
description = "Slack"
regex = '''xox[baprs]-([0-9a-zA-Z]{10,48})?'''
tags = ["key", "Slack"]
[[rules]]
description = "EC"
regex = '''-----BEGIN EC PRIVATE KEY-----'''
tags = ["key", "EC"]
[[rules]]
description = "Generic API key"
regex = '''(?i)api_key(.{0,20})?['|"][0-9a-zA-Z]{32,45}['|"]'''
tags = ["key", "API", "generic"]
[[rules]]
description = "Generic Secret"
regex = '''(?i)secret(.{0,20})?['|"][0-9a-zA-Z]{32,45}['|"]'''
tags = ["key", "Secret", "generic"]
[[rules]]
description = "Google API key"
regex = '''AIza[0-9A-Za-z\\-_]{35}'''
tags = ["key", "Google"]
[[rules]]
description = "Google Cloud Platform API key"
regex = '''(?i)(google|gcp|youtube|drive|yt)(.{0,20})?['\"][AIza[0-9a-z\\-_]{35}]['\"]'''
tags = ["key", "Google", "GCP"]
[[rules]]
description = "Google OAuth"
regex = '''(?i)(google|gcp|auth)(.{0,20})?['"][0-9]+-[0-9a-z_]{32}\.apps\.googleusercontent\.com['"]'''
tags = ["key", "Google", "OAuth"]
[[rules]]
description = "Google OAuth access token"
regex = '''ya29\.[0-9A-Za-z\-_]+'''
tags = ["key", "Google", "OAuth"]
[[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"]
[[rules]]
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})?['"][0-9a-z]{32}['"]'''
tags = ["key", "Mailgun"]
[[rules]]
description = "Password in URL"
regex = '''[a-zA-Z]{3,10}:\/\/[^\/\s:@]{3,20}:[^\/\s:@]{3,20}@.{1,100}\/?.?'''
tags = ["key", "URL", "generic"]
[[rules]]
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"]
[[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"]
[[rules]]
description = "Stripe API key"
regex = '''(?i)stripe(.{0,20})?['\"][sk|rk]_live_[0-9a-zA-Z]{24}'''
tags = ["key", "Stripe"]
[[rules]]
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"]
[[rules]]
description = "Twilio API key"
regex = '''(?i)twilio(.{0,20})?['\"][0-9a-f]{32}['\"]'''
tags = ["key", "twilio"]
[whitelist]
regexes = [
# "AKIA.*EXAMPLE",
]
files = [
"(.*?)(jpg|gif|doc|pdf|bin)$"
]
#commits = [
# "whitelisted-commit1",
# "whitelisted-commit2",
#]
#repos = [
# "whitelisted-repo"
#]
# Additional Examples
# [[rules]]
# description = "Generic Key"
# regex = '''(?i)key(.{0,6})?(:|=|=>|:=)'''
# entropies = [
# "4.1-4.3",
# "5.5-6.3",
# ]
# entropyROI = "line"
# filetypes = [".go", ".py", ".c"]
# tags = ["key"]
# severity = "8"
#
#
# [[rules]]
# description = "Generic Key"
# regex = '''(?i)key(.{0,6})?(:|=|=>|:=)'''
# entropies = ["4.1-4.3"]
# filetypes = [".gee"]
# entropyROI = "line"
# tags = ["key"]
# severity = "medium"
# [[rules]]
# description = "Any pem file"
# filetypes = [".key"]
# tags = ["pem"]
# severity = "high"
+2 -3
View File
@@ -9,15 +9,14 @@ require (
github.com/hako/durafmt v0.0.0-20180520121703-7b7ae1e72ead
github.com/ipfs/go-ipfs v0.4.19 // indirect
github.com/jessevdk/go-flags v1.4.0
github.com/mattn/go-colorable v0.1.2
github.com/onsi/ginkgo v1.8.0 // indirect
github.com/onsi/gomega v1.5.0 // indirect
github.com/sirupsen/logrus v1.0.6
github.com/xanzy/go-gitlab v0.11.3
golang.org/x/crypto v0.0.0-20180910181607-0e37d006457b // indirect
golang.org/x/net v0.0.0-20180925072008-f04abc6bdfa7 // indirect
golang.org/x/lint v0.0.0-20190409202823-959b441ac422 // indirect
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6 // indirect
golang.org/x/sys v0.0.0-20180925112736-b09afc3d579e // indirect
google.golang.org/appengine v1.2.0 // indirect
gopkg.in/airbrake/gobrake.v2 v2.0.9 // indirect
gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2 // indirect
+15
View File
@@ -42,6 +42,10 @@ github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORN
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/mattn/go-colorable v0.1.2 h1:/bC9yWikZXAL9uJdulbSfyVNIR3n3trXl+v8+1sx8mU=
github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-isatty v0.0.8 h1:HLtExJ+uU2HOZ+wI0Tt5DtUDrx8yhUqDcp7fYERX4CE=
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mitchellh/go-homedir v1.0.0 h1:vKb8ShqSby24Yrqr/yDYkuFz8d0WUjys40rvnGC8aR0=
github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
@@ -70,10 +74,16 @@ github.com/xanzy/ssh-agent v0.2.0/go.mod h1:0NyE30eGUDliuLEHJgYte/zncp2zdTStcOnW
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20180910181607-0e37d006457b h1:2b9XGzhjiYsYPnKXoEfL7klWZQIt8IfyRCz62gCqqlQ=
golang.org/x/crypto v0.0.0-20180910181607-0e37d006457b/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/lint v0.0.0-20190409202823-959b441ac422 h1:QzoH/1pFpZguR8NrRHLcO6jKqfv2zpuSqZLgdm7ZmjI=
golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180925072008-f04abc6bdfa7 h1:zKzVgSQ8WOSHzD7I4k8LQjrHUUCNOlBsgc0PcYLVNnY=
golang.org/x/net v0.0.0-20180925072008-f04abc6bdfa7/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a h1:oWX7TPOiFAMXLq8o0ikBYfCJVlRHBcsciT5bXOrH628=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be h1:vEDujvNQGv4jgYKudGeI/+DAX4Jffq6hpD55MmoEvKs=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -83,8 +93,13 @@ golang.org/x/sys v0.0.0-20180903190138-2b024373dcd9/go.mod h1:STP8DvDyc/dI5b8T5h
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180925112736-b09afc3d579e h1:LSlw/Dbj0MkNvPYAAkGinYmGliq+aqS7eKPYlE4oWC4=
golang.org/x/sys v0.0.0-20180925112736-b09afc3d579e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223 h1:DH4skfRX4EBpamg7iV4ZlCpblAHI6s6TDM39bFZumv8=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd h1:/e+gpKk9r3dJobndpTytxS2gOy6m5uvpg+ISQoEcusQ=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
google.golang.org/appengine v1.2.0 h1:S0iUepdCWODXRvtE+gcRDd15L+k+k1AiHlMiMjefH24=
google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
gopkg.in/airbrake/gobrake.v2 v2.0.9 h1:7z2uVWwn7oVeeugY1DtlPAy5H+KYgB1KeKTnqjNatLo=
+9 -5
View File
@@ -2,22 +2,26 @@ package main
import (
"os"
"strings"
log "github.com/sirupsen/logrus"
"github.com/zricethezav/gitleaks/src"
)
func main() {
report, err := gitleaks.Run(gitleaks.ParseOpts())
leakCount, err := gitleaks.Run(gitleaks.ParseOpts())
if err != nil {
if strings.Contains(err.Error(), "whitelisted") {
log.Info(err.Error())
os.Exit(0)
}
log.Error(err)
os.Exit(gitleaks.ErrExit)
}
if len(report.Leaks) != 0 {
log.Warnf("%d leaks detected. %d commits inspected in %s", len(report.Leaks), report.Commits, report.Duration)
os.Exit(gitleaks.LeakExit)
if leakCount == 0 {
os.Exit(gitleaks.NoLeaks)
} else {
log.Infof("%d leaks detected. %d commits inspected in %s", len(report.Leaks), report.Commits, report.Duration)
os.Exit(gitleaks.LeakExit)
}
}
+55 -45
View File
@@ -9,6 +9,7 @@ import (
"strings"
"github.com/BurntSushi/toml"
log "github.com/sirupsen/logrus"
"gopkg.in/src-d/go-git.v4/plumbing/transport/ssh"
)
@@ -17,20 +18,27 @@ type entropyRange struct {
v2 float64
}
type Regex struct {
// Rule instructs how gitleaks should audit each line of code
type Rule struct {
description string
regex *regexp.Regexp
severity string
tags []string
entropies []*entropyRange
entropyROI string
fileTypes []*regexp.Regexp
}
// TomlConfig is used for loading gitleaks configs from a toml file
type TomlConfig struct {
Regexes []struct {
Rules []struct {
Description string
Regex string
}
Entropy struct {
LineRegexes []string
Ranges []string
Entropies []string
Tags []string
Severity string
EntropyROI string
FileTypes []string
}
Whitelist struct {
Files []string
@@ -42,18 +50,15 @@ type TomlConfig struct {
// Config contains gitleaks config
type Config struct {
Regexes []Regex
Rules []*Rule
WhiteList struct {
regexes []*regexp.Regexp
files []*regexp.Regexp
commits map[string]bool
repos []*regexp.Regexp
}
Entropy struct {
entropyRanges []*entropyRange
regexes []*regexp.Regexp
}
sshAuth *ssh.PublicKeys
FileRules []*Rule
sshAuth *ssh.PublicKeys
}
// loadToml loads of the toml config containing regexes and whitelists.
@@ -104,31 +109,37 @@ func newConfig() (*Config, error) {
// updateConfig will update a the global config values
func (config *Config) update(tomlConfig TomlConfig) error {
if len(tomlConfig.Entropy.Ranges) != 0 {
err := config.updateEntropyRanges(tomlConfig.Entropy.Ranges)
for _, rule := range tomlConfig.Rules {
re := regexp.MustCompile(rule.Regex)
ranges, err := getEntropyRanges(rule.Entropies)
var fileTypes = []*regexp.Regexp{}
for _, regex := range rule.FileTypes {
fileTypes = append(fileTypes, regexp.MustCompile(regex))
}
if err != nil {
return err
log.Errorf("could not create entropy range for %s, skipping rule", rule.Description)
continue
}
}
for _, regex := range tomlConfig.Entropy.LineRegexes {
config.Entropy.regexes = append(config.Entropy.regexes, regexp.MustCompile(regex))
}
if singleSearchRegex != nil {
config.Regexes = append(config.Regexes, Regex{
description: "single search",
regex: singleSearchRegex,
})
} else {
for _, regex := range tomlConfig.Regexes {
config.Regexes = append(config.Regexes, Regex{
description: regex.Description,
regex: regexp.MustCompile(regex.Regex),
})
r := &Rule{
description: rule.Description,
regex: re,
severity: rule.Severity,
tags: rule.Tags,
entropies: ranges,
entropyROI: rule.EntropyROI,
fileTypes: fileTypes,
}
if len(rule.Entropies) == 0 && rule.Regex == "" && len(fileTypes) != 0 {
config.FileRules = append(config.FileRules, r)
}
config.Rules = append(config.Rules, r)
}
// set whitelists
config.WhiteList.commits = make(map[string]bool)
for _, commit := range tomlConfig.Whitelist.Commits {
config.WhiteList.commits[commit] = true
@@ -147,51 +158,50 @@ func (config *Config) update(tomlConfig TomlConfig) error {
}
// entropyRanges hydrates entropyRanges which allows for fine tuning entropy checking
func (config *Config) updateEntropyRanges(entropyLimitStr []string) error {
func getEntropyRanges(entropyLimitStr []string) ([]*entropyRange, error) {
var ranges []*entropyRange
for _, span := range entropyLimitStr {
split := strings.Split(span, "-")
v1, err := strconv.ParseFloat(split[0], 64)
if err != nil {
return err
return nil, err
}
v2, err := strconv.ParseFloat(split[1], 64)
if err != nil {
return err
return nil, err
}
if v1 > v2 {
return fmt.Errorf("entropy range must be ascending")
return nil, fmt.Errorf("entropy range must be ascending")
}
r := &entropyRange{
v1: v1,
v2: v2,
}
if r.v1 > 8.0 || r.v1 < 0.0 || r.v2 > 8.0 || r.v2 < 0.0 {
return fmt.Errorf("invalid entropy ranges, must be within 0.0-8.0")
return nil, fmt.Errorf("invalid entropy ranges, must be within 0.0-8.0")
}
config.Entropy.entropyRanges = append(config.Entropy.entropyRanges, r)
ranges = append(ranges, r)
}
return nil
return ranges, nil
}
// externalConfig will attempt to load a pinned ".gitleaks.toml" configuration file
// from a remote or local repo. Use the --repo-config option to trigger this.
func (config *Config) updateFromRepo(repo *RepoInfo) error {
func (config *Config) updateFromRepo(repo *Repo) error {
var tomlConfig TomlConfig
wt, err := repo.repository.Worktree()
if err != nil {
return err
}
f, err := wt.Filesystem.Open(".gitleaks.toml")
defer f.Close()
if err != nil {
return err
}
if _, err := toml.DecodeReader(f, &config); err != nil {
return fmt.Errorf("problem loading config: %v", err)
}
f.Close()
if err != nil {
return err
if _, err := toml.DecodeReader(f, &tomlConfig); err != nil {
return fmt.Errorf("problem loading config: %v", err)
}
return config.update(tomlConfig)
}
+171 -41
View File
@@ -1,77 +1,207 @@
package gitleaks
const version = "1.25.1"
const version = "2.1.0"
const NoLeaks = 0
const defaultGithubURL = "https://api.github.com/"
const defaultThreadNum = 1
// ErrExit used to signal an error during gitleaks execution
const ErrExit = 2
// LeakExit used to signal leaks present in audit
const LeakExit = 1
const defaultConfig = `
# This is a sample config file for gitleaks. You can configure gitleaks what to search for and what to whitelist.
# The output you are seeing here is the default gitleaks config. If GITLEAKS_CONFIG environment variable
# is set, gitleaks will load configurations from that path. If option --config-path is set, gitleaks will load
# is set, gitleaks will load configurations from that path. If option --config is set, gitleaks will load
# configurations from that path. Gitleaks does not whitelist anything by default.
# - https://www.ndss-symposium.org/wp-content/uploads/2019/02/ndss2019_04B-3_Meli_paper.pdf
# - https://github.com/dxa4481/truffleHogRegexes/blob/master/truffleHogRegexes/regexes.json
title = "gitleaks config"
# add regexes to the regex table
[[regexes]]
description = "AWS"
regex = '''AKIA[0-9A-Z]{16}'''
[[regexes]]
[[rules]]
description = "AWS Client ID"
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"]
[[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"]
[[rules]]
description = "PKCS8"
regex = '''-----BEGIN PRIVATE KEY-----'''
[[regexes]]
tags = ["key", "PKCS8"]
[[rules]]
description = "RSA"
regex = '''-----BEGIN RSA PRIVATE KEY-----'''
[[regexes]]
tags = ["key", "RSA"]
[[rules]]
description = "SSH"
regex = '''-----BEGIN OPENSSH PRIVATE KEY-----'''
[[regexes]]
tags = ["key", "SSH"]
[[rules]]
description = "PGP"
regex = '''-----BEGIN PGP PRIVATE KEY BLOCK-----'''
[[regexes]]
description = "Facebook"
regex = '''(?i)facebook(.{0,4})?['\"][0-9a-f]{32}['\"]'''
[[regexes]]
description = "Twitter"
regex = '''(?i)twitter(.{0,4})?['\"][0-9a-zA-Z]{35,44}['\"]'''
[[regexes]]
tags = ["key", "PGP"]
[[rules]]
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"]
[[rules]]
description = "Facebook access token"
regex = '''EAACEdEose0cBA[0-9A-Za-z]+'''
tags = ["key", "Facebook"]
[[rules]]
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"]
[[rules]]
description = "Github"
regex = '''(?i)github(.{0,4})?['\"][0-9a-zA-Z]{35,40}['\"]'''
[[regexes]]
regex = '''(?i)github(.{0,20})?(?-i)['\"][0-9a-zA-Z]{35,40}['\"]'''
tags = ["key", "Github"]
[[rules]]
description = "LinkedIn Client ID"
regex = '''(?i)linkedin(.{0,20})?(?-i)['\"][0-9a-z]{12}['\"]'''
tags = ["client", "Twitter"]
[[rules]]
description = "LinkedIn Secret Key"
regex = '''(?i)linkedin(.{0,20})?['\"][0-9a-z]{16}['\"]'''
tags = ["secret", "Twitter"]
[[rules]]
description = "Slack"
regex = '''xox[baprs]-([0-9a-zA-Z]{10,48})?'''
tags = ["key", "Slack"]
[entropy]
lineregexes = [
"api",
"key",
"signature",
"secret",
"password",
"pass",
"pwd",
"token",
"curl",
"wget",
"https?",
]
[[rules]]
description = "EC"
regex = '''-----BEGIN EC PRIVATE KEY-----'''
tags = ["key", "EC"]
[[rules]]
description = "Generic API key"
regex = '''(?i)(api_key|apikey)(.{0,20})?['|"][0-9a-zA-Z]{32,45}['|"]'''
tags = ["key", "API", "generic"]
[[rules]]
description = "Generic Secret"
regex = '''(?i)secret(.{0,20})?['|"][0-9a-zA-Z]{32,45}['|"]'''
tags = ["key", "Secret", "generic"]
[[rules]]
description = "Google API key"
regex = '''AIza[0-9A-Za-z\\-_]{35}'''
tags = ["key", "Google"]
[[rules]]
description = "Google Cloud Platform API key"
regex = '''(?i)(google|gcp|youtube|drive|yt)(.{0,20})?['\"][AIza[0-9a-z\\-_]{35}]['\"]'''
tags = ["key", "Google", "GCP"]
[[rules]]
description = "Google OAuth"
regex = '''(?i)(google|gcp|auth)(.{0,20})?['"][0-9]+-[0-9a-z_]{32}\.apps\.googleusercontent\.com['"]'''
tags = ["key", "Google", "OAuth"]
[[rules]]
description = "Google OAuth access token"
regex = '''ya29\.[0-9A-Za-z\-_]+'''
tags = ["key", "Google", "OAuth"]
[[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"]
[[rules]]
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})?['"][0-9a-z]{32}['"]'''
tags = ["key", "Mailgun"]
[[rules]]
description = "Password in URL"
regex = '''[a-zA-Z]{3,10}:\/\/[^\/\s:@]{3,20}:[^\/\s:@]{3,20}@.{1,100}\/?.?'''
tags = ["key", "URL", "generic"]
[[rules]]
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"]
[[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"]
[[rules]]
description = "Stripe API key"
regex = '''(?i)stripe(.{0,20})?['\"][sk|rk]_live_[0-9a-zA-Z]{24}'''
tags = ["key", "Stripe"]
[[rules]]
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"]
[[rules]]
description = "Twilio API key"
regex = '''(?i)twilio(.{0,20})?['\"][0-9a-f]{32}['\"]'''
tags = ["key", "twilio"]
[whitelist]
files = [
"(.*?)(jpg|gif|doc|pdf|bin)$"
]
#commits = [
# "BADHA5H1",
# "BADHA5H2",
# "whitelisted-commit1",
# "whitelisted-commit2",
#]
#repos = [
# "mygoodrepo"
#]
[misc]
#entropy = [
# "3.3-4.30"
# "6.0-8.0
# "whitelisted-repo"
#]
`
+123
View File
@@ -0,0 +1,123 @@
package gitleaks
import (
"io/ioutil"
"path"
)
const testWhitelistCommit = `
[[rules]]
description = "AWS"
regex = '''AKIA[0-9A-Z]{16}'''
[whitelist]
commits = [
"eaeffdc65b4c73ccb67e75d96bd8743be2c85973",
]
`
const testWhitelistFile = `
[[rules]]
description = "AWS"
regex = '''AKIA[0-9A-Z]{16}'''
[whitelist]
files = [
".go",
]
`
const testWhitelistRegex = `
[[rules]]
description = "AWS"
regex = '''AKIA[0-9A-Z]{16}'''
[whitelist]
regexes= [
"AKIA",
]
`
const testWhitelistRepo = `
[[rules]]
description = "AWS"
regex = '''AKIA[0-9A-Z]{16}'''
[whitelist]
repos = [
"gronit",
]
`
const testEntropyRange = `
[[rules]]
description = "Entropy ranges"
entropies = [
"7.5-8.0",
"3.2-3.4",
]
`
const testBadEntropyRange = `
[[rules]]
description = "Bad entropy ranges"
entropies = [
"8.0-3.0",
]
`
const testBadEntropyRange2 = `
[[rules]]
description = "Bad entropy ranges"
entropies = [
"8.0-8.9",
]
`
const testEntropyWordRegexRange = `
[[rules]]
description = "test entropy regex ranges"
regex = '''(?i)key(.{0,6})?(:|=|=>|:=)'''
entropies = [
"4.1-4.3",
]
entropyROI="word"
`
const testEntropyRegexRange = `
[[rules]]
description = "test entropy regex ranges"
regex = '''(?i)key(.{0,6})?(:|=|=>|:=)'''
entropies = [
"4.1-4.3",
]
`
const testMDFileType = `
[[rules]]
description = "test only markdown"
filetypes = [".md"]
`
const testEntropyRegexRangeGoFilter = `
[[rules]]
description = "test entropy regex ranges"
regex = '''(?i)key(.{0,6})?(:|=|=>|:=)'''
entropies = [
"4.1-4.3",
]
filetypes = [".go"]
`
func testTomlLoader() string {
tmpDir, _ := ioutil.TempDir("", "whiteListConfigs")
ioutil.WriteFile(path.Join(tmpDir, "regex"), []byte(testWhitelistRegex), 0644)
ioutil.WriteFile(path.Join(tmpDir, "entropyWordRegex"), []byte(testEntropyWordRegexRange), 0644)
ioutil.WriteFile(path.Join(tmpDir, "entropyRegex"), []byte(testEntropyRegexRange), 0644)
ioutil.WriteFile(path.Join(tmpDir, "commit"), []byte(testWhitelistCommit), 0644)
ioutil.WriteFile(path.Join(tmpDir, "file"), []byte(testWhitelistFile), 0644)
ioutil.WriteFile(path.Join(tmpDir, "repo"), []byte(testWhitelistRepo), 0644)
ioutil.WriteFile(path.Join(tmpDir, "entropy"), []byte(testEntropyRange), 0644)
ioutil.WriteFile(path.Join(tmpDir, "badEntropy"), []byte(testBadEntropyRange), 0644)
ioutil.WriteFile(path.Join(tmpDir, "badEntropy2"), []byte(testBadEntropyRange2), 0644)
ioutil.WriteFile(path.Join(tmpDir, "mdFiles"), []byte(testMDFileType), 0644)
ioutil.WriteFile(path.Join(tmpDir, "entropyRegexGo"), []byte(testEntropyRegexRangeGoFilter), 0644)
return tmpDir
}
+43 -53
View File
@@ -1,27 +1,19 @@
package gitleaks
import (
log "github.com/sirupsen/logrus"
"io/ioutil"
"os"
"regexp"
"strings"
"sync"
"time"
"github.com/hako/durafmt"
log "github.com/sirupsen/logrus"
)
var (
opts *Options
config *Config
singleSearchRegex *regexp.Regexp
dir string
threads int
totalCommits int64
commitMap = make(map[string]bool)
auditDone bool
mutex = &sync.Mutex{}
opts *Options
config *Config
dir string
threads int
totalCommits int64
mutex = &sync.Mutex{}
)
func init() {
@@ -29,7 +21,8 @@ func init() {
threads = defaultThreadNum
}
// Report is
// Report can be exported as a json or csv. Used for logging informationn
// about the audit, (duration and # of commits)
type Report struct {
Leaks []Leak
Duration string
@@ -37,17 +30,16 @@ type Report struct {
}
// Run is the entry point for gitleaks
func Run(optsL *Options) (*Report, error) {
func Run(optsL *Options) (int, error) {
var (
leaks []Leak
err error
leaks []Leak
)
now := time.Now()
opts = optsL
config, err = newConfig()
if err != nil {
return nil, err
return NoLeaks, err
}
if opts.Disk {
@@ -55,63 +47,61 @@ func Run(optsL *Options) (*Report, error) {
dir, err = ioutil.TempDir("", "gitleaks")
defer os.RemoveAll(dir)
if err != nil {
goto postAudit
return NoLeaks, err
}
}
// start audits
if opts.Repo != "" || opts.RepoPath != "" {
repoInfo, err := newRepoInfo()
var repo *Repo
repo, err = newRepo()
if err != nil {
goto postAudit
return NoLeaks, err
}
err = repoInfo.clone()
err = repo.clone()
if err != nil {
goto postAudit
return NoLeaks, err
}
leaks, err = repoInfo.audit()
err = repo.audit()
if err != nil {
return NoLeaks, err
}
repo.report()
leaks = repo.leaks
} else if opts.OwnerPath != "" {
repoDs, err := discoverRepos(opts.OwnerPath)
var repos []*Repo
repos, err = discoverRepos(opts.OwnerPath)
if err != nil {
goto postAudit
return NoLeaks, err
}
for _, repoInfo := range repoDs {
err = repoInfo.clone()
for _, repo := range repos {
err = repo.clone()
if err != nil {
log.Warnf("error occurred cloning repo: %s, continuing to next repo", repo.name)
continue
}
leaksFromRepo, err := repoInfo.audit()
err = repo.audit()
if err != nil {
log.Warnf("error occured auditing repo: %s, continuing", repoInfo.name)
log.Warnf("error occurred auditing repo: %s, continuing to next repo", repo.name)
continue
}
leaks = append(leaksFromRepo, leaks...)
repo.report()
leaks = append(leaks, repo.leaks...)
}
} else if opts.GithubOrg != "" || opts.GithubUser != "" {
leaks, err = auditGithubRepos()
return auditGithubRepos()
} else if opts.GitLabOrg != "" || opts.GitLabUser != "" {
leaks, err = auditGitlabRepos()
return auditGitlabRepos()
} else if opts.GithubPR != "" {
leaks, err = auditGithubPR()
}
postAudit:
if err != nil {
if strings.Contains(err.Error(), "whitelisted") {
log.Info(err.Error())
os.Exit(0)
}
log.Error(err)
os.Exit(ErrExit)
return auditGithubPR()
}
if opts.Report != "" {
writeReport(leaks)
err = writeReport(leaks)
if err != nil {
return NoLeaks, err
}
}
return &Report{
Leaks: leaks,
Duration: durafmt.Parse(time.Now().Sub(now)).String(),
Commits: totalCommits,
}, err
return len(leaks), nil
}
-27
View File
@@ -23,30 +23,3 @@ func getShannonEntropy(data string) (entropy float64) {
return entropy
}
func entropyIsHighEnough(entropy float64) bool {
if entropy >= opts.Entropy && len(config.Entropy.entropyRanges) == 0 {
return true
}
for _, eR := range config.Entropy.entropyRanges {
if entropy > eR.v1 && entropy < eR.v2 {
return true
}
}
return false
}
func highEntropyLineIsALeak(line string) bool {
if !opts.NoiseReduction {
return true
}
for _, re := range config.Entropy.regexes {
if re.FindString(line) != "" {
return true
}
}
return false
}
+39 -22
View File
@@ -13,7 +13,7 @@ import (
"github.com/google/go-github/github"
log "github.com/sirupsen/logrus"
"golang.org/x/oauth2"
git "gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4"
gitHttp "gopkg.in/src-d/go-git.v4/plumbing/transport/http"
"gopkg.in/src-d/go-git.v4/storage/memory"
)
@@ -21,7 +21,7 @@ import (
var githubPages = 100
// auditPR audits a single github PR
func auditGithubPR() ([]Leak, error) {
func auditGithubPR() (int, error) {
var leaks []Leak
ctx := context.Background()
githubClient := github.NewClient(githubToken())
@@ -30,7 +30,7 @@ func auditGithubPR() ([]Leak, error) {
repo := splits[len(splits)-3]
prNum, err := strconv.Atoi(splits[len(splits)-1])
if err != nil {
return nil, err
return NoLeaks, err
}
page := 1
@@ -40,7 +40,7 @@ func auditGithubPR() ([]Leak, error) {
Page: page,
})
if err != nil {
return leaks, err
return NoLeaks, err
}
for _, c := range commits {
@@ -66,7 +66,7 @@ func auditGithubPR() ([]Leak, error) {
continue
}
commit := commitInfo{
commit := &Commit{
sha: c.GetSHA(),
content: *f.Patch,
filePath: *f.Filename,
@@ -84,14 +84,25 @@ func auditGithubPR() ([]Leak, error) {
}
}
return leaks, nil
if len(leaks) != 0 {
log.Warnf("%d leaks detected. %d commits inspected for PR: %s", len(leaks), totalCommits, opts.GithubPR)
}
if opts.Report != "" {
err = writeReport(leaks)
if err != nil {
return NoLeaks, err
}
}
return len(leaks), nil
}
// auditGithubRepos kicks off audits if --github-user or --github-org options are set.
// First, we gather all the github repositories from the github api (this doesnt actually clone the repo).
// After all the repos have been pulled from github's api we proceed to audit the repos by calling auditGithubRepo.
// If an error occurs during an audit of a repo, that error is logged but won't break the execution cycle.
func auditGithubRepos() ([]Leak, error) {
func auditGithubRepos() (int, error) {
var (
err error
githubRepos []*github.Repository
@@ -100,8 +111,8 @@ func auditGithubRepos() ([]Leak, error) {
githubOrgOptions *github.RepositoryListByOrgOptions
githubOptions *github.RepositoryListOptions
done bool
leaks []Leak
ownerDir string
leaks []Leak
)
ctx := context.Background()
githubClient := github.NewClient(githubToken())
@@ -163,31 +174,37 @@ func auditGithubRepos() ([]Leak, error) {
ownerDir, _ = ioutil.TempDir(dir, opts.GithubUser)
}
for _, githubRepo := range githubRepos {
repoD, err := cloneGithubRepo(githubRepo)
repo, err := cloneGithubRepo(githubRepo)
if err != nil {
log.Warn(err)
continue
}
leaksFromRepo, err := repoD.audit()
err = repo.audit()
if err != nil {
log.Warnf("error occurred during audit of repo: %s, err: %v, continuing github audit", repo.name, err)
}
if opts.Disk {
os.RemoveAll(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name))
}
if len(leaksFromRepo) == 0 {
log.Infof("no leaks found for repo %s", *githubRepo.Name)
} else {
log.Warnf("leaks found for repo %s", *githubRepo.Name)
}
if err != nil {
log.Warn(err)
}
leaks = append(leaks, leaksFromRepo...)
repo.report()
leaks = append(leaks, repo.leaks...)
}
return leaks, nil
if opts.Report != "" {
err = writeReport(leaks)
if err != nil {
return NoLeaks, err
}
}
return len(leaks), nil
}
// cloneGithubRepo clones a repo from the url parsed from a github repo. The repo
// will be cloned to disk if --disk is set.
func cloneGithubRepo(githubRepo *github.Repository) (*RepoInfo, error) {
func cloneGithubRepo(githubRepo *github.Repository) (*Repo, error) {
var (
repo *git.Repository
err error
@@ -248,7 +265,7 @@ func cloneGithubRepo(githubRepo *github.Repository) (*RepoInfo, error) {
if err != nil {
return nil, err
}
return &RepoInfo{
return &Repo{
repository: repo,
name: *githubRepo.Name,
}, nil
+27 -15
View File
@@ -8,6 +8,7 @@ import (
log "github.com/sirupsen/logrus"
"github.com/xanzy/go-gitlab"
"gopkg.in/src-d/go-git.v4"
gitHttp "gopkg.in/src-d/go-git.v4/plumbing/transport/http"
"gopkg.in/src-d/go-git.v4/storage/memory"
)
@@ -17,13 +18,13 @@ const gitlabPages = 100
// auditGitlabRepos kicks off audits if --gitlab-user or --gitlab-org options are set.
// Getting all repositories from the GitLab API and run audit. If an error occurs during an audit of a repo,
// that error is logged.
func auditGitlabRepos() ([]Leak, error) {
func auditGitlabRepos() (int, error) {
var (
ps []*gitlab.Project
resp *gitlab.Response
leaks []Leak
tempDir string
err error
leaks []Leak
)
repos := make([]*gitlab.Project, 0, gitlabPages)
@@ -80,31 +81,34 @@ func auditGitlabRepos() ([]Leak, error) {
}
for _, p := range repos {
repoInfo, err := cloneGitlabRepo(tempDir, p)
repo, err := cloneGitlabRepo(tempDir, p)
if err != nil {
log.Warn(err)
continue
}
leaksFromRepo, err := repoInfo.audit()
err = repo.audit()
if err != nil {
log.Warn(err)
continue
}
if opts.Disk {
os.RemoveAll(fmt.Sprintf("%s/%d", tempDir, p.ID))
}
if len(leaksFromRepo) == 0 {
log.Infof("no leaks found for repo %s", p.Name)
} else {
log.Warnf("leaks found for repo %s", p.Name)
}
leaks = append(leaks, leaksFromRepo...)
repo.report()
leaks = append(leaks, repo.leaks...)
}
return leaks, nil
if opts.Report != "" {
err = writeReport(leaks)
if err != nil {
return NoLeaks, err
}
}
return len(leaks), nil
}
func createGitlabTempDir() (string, error) {
@@ -123,11 +127,14 @@ func createGitlabTempDir() (string, error) {
return ownerDir, nil
}
func cloneGitlabRepo(tempDir string, p *gitlab.Project) (*RepoInfo, error) {
func cloneGitlabRepo(tempDir string, p *gitlab.Project) (*Repo, error) {
var (
repo *git.Repository
err error
)
gitLabToken := os.Getenv("GITLAB_TOKEN")
if opts.ExcludeForks && p.ForkedFromProject != nil {
return nil, fmt.Errorf("skipping %s, excluding forks", p.Name)
}
@@ -142,9 +149,14 @@ func cloneGitlabRepo(tempDir string, p *gitlab.Project) (*RepoInfo, error) {
URL: p.HTTPURLToRepo,
}
if config.sshAuth != nil {
if config.sshAuth != nil && gitLabToken == "" {
opt.URL = p.SSHURLToRepo
opt.Auth = config.sshAuth
} else if gitLabToken != "" {
opt.Auth = &gitHttp.BasicAuth{
Username: "fakeUsername", // yes, this can be anything except an empty string
Password: gitLabToken,
}
}
log.Infof("cloning: %s", p.Name)
@@ -159,7 +171,7 @@ func cloneGitlabRepo(tempDir string, p *gitlab.Project) (*RepoInfo, error) {
return nil, err
}
return &RepoInfo{
return &Repo{
repository: repo,
name: p.Name,
}, nil
+59 -170
View File
@@ -6,6 +6,7 @@ import (
"os"
"path"
"regexp"
"runtime"
"strings"
"testing"
"time"
@@ -16,82 +17,6 @@ import (
"gopkg.in/src-d/go-git.v4/storage/memory"
)
const testWhitelistCommit = `
[[regexes]]
description = "AWS"
regex = '''AKIA[0-9A-Z]{16}'''
[whitelist]
commits = [
"eaeffdc65b4c73ccb67e75d96bd8743be2c85973",
]
`
const testWhitelistFile = `
[[regexes]]
description = "AWS"
regex = '''AKIA[0-9A-Z]{16}'''
[whitelist]
files = [
".go",
]
`
const testWhitelistRegex = `
[[regexes]]
description = "AWS"
regex = '''AKIA[0-9A-Z]{16}'''
[whitelist]
regexes= [
"AKIA",
]
`
const testWhitelistRepo = `
[[regexes]]
description = "AWS"
regex = '''AKIA[0-9A-Z]{16}'''
[whitelist]
repos = [
"gronit",
]
`
const testEntropyRange = `
[entropy]
ranges = [
"7.5-8.0",
"3.2-3.4",
]
lineregexes = [
"(?i)api",
"(?i)key",
"signature",
"secret",
"password",
"pass",
"pwd",
"token",
"curl",
"wget",
"https?",
]
`
const testBadEntropyRange = `
[entropy]
ranges = [
"8.0-3.0",
]
`
const testBadEntropyRange2 = `
[entropy]
ranges = [
"8.0-8.9",
]
`
func TestGetRepo(t *testing.T) {
var err error
dir, err = ioutil.TempDir("", "gitleaksTestRepo")
@@ -139,22 +64,22 @@ func TestGetRepo(t *testing.T) {
Repo: "https://github.com/gitleakstest/nope",
},
description: "test no repo",
expectedErrMsg: "authentication required",
expectedErrMsg: "repository not found",
},
{
testOpts: &Options{
Repo: "https://github.com/gitleakstest/private",
},
description: "test private repo",
expectedErrMsg: "authentication required",
expectedErrMsg: "repository not found",
},
{
testOpts: &Options{
Repo: "https://github.com/gitleakstest/private",
Disk: true,
},
description: "test private repo",
expectedErrMsg: "authentication required",
description: "test private repo disk",
expectedErrMsg: "repository not found",
},
}
g := goblin.Goblin(t)
@@ -166,7 +91,7 @@ func TestGetRepo(t *testing.T) {
if err != nil {
log.Fatal(err)
}
repo, _ := newRepoInfo()
repo, _ := newRepo()
err := repo.clone()
if err != nil {
g.Assert(err.Error()).Equal(test.expectedErrMsg)
@@ -201,6 +126,14 @@ func TestRun(t *testing.T) {
configPath string
commitPerPage int
}{
{
testOpts: &Options{
Repo: "https://github.com/gitleakstest/gronit.git",
},
description: "test leak",
numLeaks: 2,
expectedErrMsg: "",
},
{
testOpts: &Options{
GitLabUser: "gitleakstest",
@@ -258,7 +191,7 @@ func TestRun(t *testing.T) {
},
description: "test leak",
numLeaks: 0,
expectedErrMsg: "unable to generate ssh key: open trash: no such file or directory",
expectedErrMsg: fmt.Sprintf("unable to generate ssh key: open trash: %s", noSuchFileMessage()),
},
{
testOpts: &Options{
@@ -282,7 +215,7 @@ func TestRun(t *testing.T) {
},
description: "test empty",
numLeaks: 0,
expectedErrMsg: "reference not found",
expectedErrMsg: "repository not found",
},
{
testOpts: &Options{
@@ -349,11 +282,11 @@ func TestRun(t *testing.T) {
if test.commitPerPage != 0 {
githubPages = test.commitPerPage
}
report, err := Run(test.testOpts)
numLeaks, err := Run(test.testOpts)
if err != nil {
g.Assert(err.Error()).Equal(test.expectedErrMsg)
} else {
g.Assert(len(report.Leaks)).Equal(test.numLeaks)
g.Assert(numLeaks).Equal(test.numLeaks)
}
githubPages = 100
})
@@ -373,7 +306,7 @@ func TestWriteReport(t *testing.T) {
Line: "eat",
Commit: "your",
Offender: "veggies",
Type: "and",
Rule: "and",
Message: "get",
Author: "some",
File: "sleep",
@@ -447,20 +380,7 @@ func TestWriteReport(t *testing.T) {
}
func testTomlLoader() string {
tmpDir, _ := ioutil.TempDir("", "whiteListConfigs")
ioutil.WriteFile(path.Join(tmpDir, "regex"), []byte(testWhitelistRegex), 0644)
ioutil.WriteFile(path.Join(tmpDir, "commit"), []byte(testWhitelistCommit), 0644)
ioutil.WriteFile(path.Join(tmpDir, "file"), []byte(testWhitelistFile), 0644)
ioutil.WriteFile(path.Join(tmpDir, "repo"), []byte(testWhitelistRepo), 0644)
ioutil.WriteFile(path.Join(tmpDir, "entropy"), []byte(testEntropyRange), 0644)
ioutil.WriteFile(path.Join(tmpDir, "badEntropy"), []byte(testBadEntropyRange), 0644)
ioutil.WriteFile(path.Join(tmpDir, "badEntropy2"), []byte(testBadEntropyRange2), 0644)
return tmpDir
}
func TestAuditRepo(t *testing.T) {
var leaks []Leak
configsDir := testTomlLoader()
defer os.RemoveAll(configsDir)
@@ -470,7 +390,7 @@ func TestAuditRepo(t *testing.T) {
if err != nil {
panic(err)
}
leaksRepo := &RepoInfo{
leaksRepo := &Repo{
repository: leaksR,
name: "gronit",
}
@@ -481,7 +401,7 @@ func TestAuditRepo(t *testing.T) {
if err != nil {
panic(err)
}
cleanRepo := &RepoInfo{
cleanRepo := &Repo{
repository: cleanR,
name: "h1domains",
}
@@ -491,7 +411,7 @@ func TestAuditRepo(t *testing.T) {
description string
expectedErrMsg string
numLeaks int
repo *RepoInfo
repo *Repo
whiteListFiles []*regexp.Regexp
whiteListCommits map[string]bool
whiteListRepos []*regexp.Regexp
@@ -630,23 +550,6 @@ func TestAuditRepo(t *testing.T) {
testOpts: &Options{},
configPath: path.Join(configsDir, "repo"),
},
{
repo: leaksRepo,
description: "leaks present with entropy",
testOpts: &Options{
Entropy: 4.7,
},
numLeaks: 6,
},
{
repo: leaksRepo,
description: "leaks present with entropy",
testOpts: &Options{
Entropy: 4.7,
NoiseReduction: true,
},
numLeaks: 2,
},
{
repo: leaksRepo,
description: "Audit until specific commit",
@@ -666,26 +569,24 @@ func TestAuditRepo(t *testing.T) {
{
repo: leaksRepo,
description: "toml entropy range from opts",
numLeaks: 454,
numLeaks: 266,
testOpts: &Options{
ConfigPath: path.Join(configsDir, "entropy"),
},
},
{
repo: leaksRepo,
description: "toml entropy range",
numLeaks: 454,
description: "toml entropy regex word range",
numLeaks: 0,
testOpts: &Options{},
configPath: path.Join(configsDir, "entropy"),
configPath: path.Join(configsDir, "entropyWordRegex"),
},
{
repo: leaksRepo,
testOpts: &Options{
NoiseReduction: true,
},
description: "toml entropy noise reduction range",
numLeaks: 64,
configPath: path.Join(configsDir, "entropy"),
repo: leaksRepo,
description: "toml entropy regex range",
numLeaks: 2,
testOpts: &Options{},
configPath: path.Join(configsDir, "entropyRegex"),
},
{
repo: leaksRepo,
@@ -703,14 +604,26 @@ func TestAuditRepo(t *testing.T) {
configPath: path.Join(configsDir, "badEntropy2"),
expectedErrMsg: "invalid entropy ranges, must be within 0.0-8.0",
},
{
repo: leaksRepo,
description: "toml md files",
numLeaks: 5,
testOpts: &Options{},
configPath: path.Join(configsDir, "mdFiles"),
},
{
repo: leaksRepo,
description: "toml entropys line regex go",
numLeaks: 2,
testOpts: &Options{},
configPath: path.Join(configsDir, "entropyRegexGo"),
},
}
g := goblin.Goblin(t)
for _, test := range tests {
g.Describe("TestAuditRepo", func() {
g.It(test.description, func() {
auditDone = false
opts = test.testOpts
totalCommits = 0
config, err = newConfig()
// config paths
@@ -722,17 +635,14 @@ func TestAuditRepo(t *testing.T) {
goto next
}
}
leaks, err = test.repo.audit()
if test.testOpts.Depth != 0 {
g.Assert(totalCommits).Equal(test.testOpts.Depth)
} else {
if opts.Redact {
g.Assert(leaks[0].Offender).Equal("REDACTED")
}
g.Assert(len(leaks)).Equal(test.numLeaks)
err = test.repo.audit()
if opts.Redact {
g.Assert(test.repo.leaks[0].Offender).Equal("REDACTED")
}
g.Assert(len(test.repo.leaks)).Equal(test.numLeaks)
next:
os.Setenv("GITLEAKS_CONFIG", "")
test.repo.leaks = []Leak{}
})
})
}
@@ -775,30 +685,6 @@ func TestOptionGuard(t *testing.T) {
description: "local and remote target",
expectedErrMsg: "github user set and local owner path",
},
{
testOpts: &Options{
GithubUser: "fakeUser",
SingleSearch: "*/./....",
},
description: "single search invalid regex gaurd",
expectedErrMsgFuzzy: "unable to compile regex: */./...., ",
},
{
testOpts: &Options{
GithubUser: "fakeUser",
SingleSearch: "mystring",
},
description: "single search regex gaurd",
expectedErrMsg: "",
},
{
testOpts: &Options{
GithubOrg: "fakeOrg",
Entropy: 9,
},
description: "Invalid entropy level guard",
expectedErrMsg: "The maximum level of entropy is 8",
},
}
g := goblin.Goblin(t)
for _, test := range tests {
@@ -871,7 +757,7 @@ func TestLoadToml(t *testing.T) {
testOpts: &Options{},
description: "env var path to no config",
configPath: noConfigPath,
expectedErrMsg: fmt.Sprintf("problem loading config: open %s: no such file or directory", noConfigPath),
expectedErrMsg: fmt.Sprintf("problem loading config: open %s: %s", noConfigPath, noSuchFileMessage()),
},
}
@@ -880,11 +766,6 @@ func TestLoadToml(t *testing.T) {
g.Describe("TestLoadToml", func() {
g.It(test.description, func() {
opts = test.testOpts
if test.singleSearch {
singleSearchRegex = regexp.MustCompile("test")
} else {
singleSearchRegex = nil
}
if test.configPath != "" {
os.Setenv("GITLEAKS_CONFIG", test.configPath)
} else {
@@ -900,3 +781,11 @@ func TestLoadToml(t *testing.T) {
})
}
}
func noSuchFileMessage() string {
if runtime.GOOS == "windows" {
// Adapt to Windws
return "The system cannot find the file specified."
}
return "no such file or directory"
}
+16 -25
View File
@@ -6,12 +6,12 @@ import (
"net/url"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
"github.com/jessevdk/go-flags"
colorable "github.com/mattn/go-colorable"
log "github.com/sirupsen/logrus"
)
@@ -36,16 +36,13 @@ type Options struct {
OwnerPath string `long:"owner-path" description:"Path to owner directory (repos discovered)"`
// Process options
Threads int `long:"threads" description:"Maximum number of threads gitleaks spawns"`
Disk bool `long:"disk" description:"Clones repo(s) to disk"`
SingleSearch string `long:"single-search" description:"single regular expression to search for"`
ConfigPath string `long:"config" description:"path to gitleaks config"`
SSHKey string `long:"ssh-key" description:"path to ssh key"`
ExcludeForks bool `long:"exclude-forks" description:"exclude forks for organization/user audits"`
Entropy float64 `long:"entropy" short:"e" description:"Include entropy checks during audit. Entropy scale: 0.0(no entropy) - 8.0(max entropy)"`
NoiseReduction bool `long:"noise-reduction" description:"Reduce the number of finds when entropy checks are enabled"`
RepoConfig bool `long:"repo-config" description:"Load config from target repo. Config file must be \".gitleaks.toml\""`
Branch string `long:"branch" description:"Branch to audit"`
Threads int `long:"threads" description:"Maximum number of threads gitleaks spawns"`
Disk bool `long:"disk" description:"Clones repo(s) to disk"`
ConfigPath string `long:"config" description:"path to gitleaks config"`
SSHKey string `long:"ssh-key" description:"path to ssh key"`
ExcludeForks bool `long:"exclude-forks" description:"exclude forks for organization/user audits"`
RepoConfig bool `long:"repo-config" description:"Load config from target repo. Config file must be \".gitleaks.toml\""`
Branch string `long:"branch" description:"Branch to audit"`
// TODO: IncludeMessages string `long:"messages" description:"include commit messages in audit"`
// Output options
@@ -64,13 +61,13 @@ func ParseOpts() *Options {
_, err := parser.Parse()
if err != nil {
if flagsErr, ok := err.(*flags.Error); ok && flagsErr.Type == flags.ErrHelp {
os.Exit(0)
if flagsErr, ok := err.(*flags.Error); ok && flagsErr.Type != flags.ErrHelp {
parser.WriteHelp(os.Stdout)
}
os.Exit(0)
}
if len(os.Args) == 1 {
// TODO: this will be a feature, check locally
parser.WriteHelp(os.Stdout)
os.Exit(0)
}
@@ -95,7 +92,6 @@ func ParseOpts() *Options {
// optsGuard prevents invalid options
func (opts *Options) guard() error {
var err error
if opts.GithubOrg != "" && opts.GithubUser != "" {
return fmt.Errorf("github user and organization set")
} else if opts.GithubOrg != "" && opts.OwnerPath != "" {
@@ -129,16 +125,6 @@ func (opts *Options) guard() error {
}
}
if opts.SingleSearch != "" {
singleSearchRegex, err = regexp.Compile(opts.SingleSearch)
if err != nil {
return fmt.Errorf("unable to compile regex: %s, %v", opts.SingleSearch, err)
}
}
if opts.Entropy > 8 {
return fmt.Errorf("The maximum level of entropy is 8")
}
if opts.Report != "" {
if !strings.HasSuffix(opts.Report, ".json") && !strings.HasSuffix(opts.Report, ".csv") {
return fmt.Errorf("Report should be a .json or .csv file")
@@ -165,6 +151,11 @@ func (opts *Options) setLogs() {
log.SetLevel(log.InfoLevel)
}
log.SetFormatter(&log.TextFormatter{
ForceColors: true,
FullTimestamp: true,
})
// Fix colors on Windows
if runtime.GOOS == "windows" {
log.SetOutput(colorable.NewColorableStdout())
}
}
+221 -60
View File
@@ -3,6 +3,7 @@ package gitleaks
import (
"crypto/md5"
"fmt"
"github.com/hako/durafmt"
"os"
"path/filepath"
"strings"
@@ -10,44 +11,66 @@ import (
"time"
log "github.com/sirupsen/logrus"
git "gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing"
diffType "gopkg.in/src-d/go-git.v4/plumbing/format/diff"
"gopkg.in/src-d/go-git.v4/plumbing/object"
"gopkg.in/src-d/go-git.v4/plumbing/storer"
gitHttp "gopkg.in/src-d/go-git.v4/plumbing/transport/http"
"gopkg.in/src-d/go-git.v4/storage/memory"
"gopkg.in/src-d/go-git.v4/utils/merkletrie"
)
// Commit represents a git commit
type Commit struct {
content string
commit *object.Commit
filePath string
repoName string
sha string
message string
author string
email string
date time.Time
}
// Leak represents a leaked secret or regex match.
type Leak struct {
Line string `json:"line"`
Commit string `json:"commit"`
Offender string `json:"offender"`
Type string `json:"reason"`
Rule string `json:"rule"`
Info string `json:"info"`
Message string `json:"commitMsg"`
Author string `json:"author"`
Email string `json:"email"`
File string `json:"file"`
Repo string `json:"repo"`
Date time.Time `json:"date"`
Tags string `json:"tags"`
Severity string `json:"severity"`
}
// RepoInfo contains a src-d git repository and other data about the repo
type RepoInfo struct {
path string
url string
name string
repository *git.Repository
err error
// Repo contains a src-d git repository and other data about the repo
type Repo struct {
leaks []Leak
path string
url string
name string
repository *git.Repository
err error
auditDuration string
numCommits int64
}
func newRepoInfo() (*RepoInfo, error) {
func newRepo() (*Repo, error) {
for _, re := range config.WhiteList.repos {
if re.FindString(opts.Repo) != "" {
return nil, fmt.Errorf("skipping %s, whitelisted", opts.Repo)
}
}
return &RepoInfo{
return &Repo{
path: opts.RepoPath,
url: opts.Repo,
name: filepath.Base(opts.Repo),
@@ -55,10 +78,10 @@ func newRepoInfo() (*RepoInfo, error) {
}
// clone will clone a repo
func (repoInfo *RepoInfo) clone() error {
func (repo *Repo) clone() error {
var (
err error
repo *git.Repository
err error
repository *git.Repository
)
// check if cloning to disk
@@ -67,70 +90,98 @@ func (repoInfo *RepoInfo) clone() error {
cloneTarget := fmt.Sprintf("%s/%x", dir, md5.Sum([]byte(fmt.Sprintf("%s%s", opts.GithubUser, opts.Repo))))
if strings.HasPrefix(opts.Repo, "git") {
// private
repo, err = git.PlainClone(cloneTarget, false, &git.CloneOptions{
repository, err = git.PlainClone(cloneTarget, false, &git.CloneOptions{
URL: opts.Repo,
Progress: os.Stdout,
Auth: config.sshAuth,
})
} else {
// public
repo, err = git.PlainClone(cloneTarget, false, &git.CloneOptions{
options := &git.CloneOptions{
URL: opts.Repo,
Progress: os.Stdout,
})
}
if os.Getenv("GITHUB_TOKEN") != "" {
options.Auth = &gitHttp.BasicAuth{
Username: "fakeUsername", // yes, this can be anything except an empty string
Password: os.Getenv("GITHUB_TOKEN"),
}
}
repository, err = git.PlainClone(cloneTarget, false, options)
}
} else if repo.path != "" {
log.Infof("opening %s", repo.path)
repository, err = git.PlainOpen(repo.path)
if err != nil {
log.Errorf("unable to open %s", repo.path)
}
} else if repoInfo.path != "" {
log.Infof("opening %s", opts.RepoPath)
repo, err = git.PlainOpen(repoInfo.path)
} else {
// cloning to memory
log.Infof("cloning %s", opts.Repo)
if strings.HasPrefix(opts.Repo, "git") {
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
repository, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: opts.Repo,
Progress: os.Stdout,
Auth: config.sshAuth,
})
} else {
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
options := &git.CloneOptions{
URL: opts.Repo,
Progress: os.Stdout,
})
}
if os.Getenv("GITHUB_TOKEN") != "" {
options.Auth = &gitHttp.BasicAuth{
Username: "fakeUsername", // yes, this can be anything except an empty string
Password: os.Getenv("GITHUB_TOKEN"),
}
}
repository, err = git.Clone(memory.NewStorage(), nil, options)
}
}
repoInfo.repository = repo
repoInfo.err = err
repo.repository = repository
repo.err = err
return err
}
// audit performs an audit
func (repoInfo *RepoInfo) audit() ([]Leak, error) {
func (repo *Repo) audit() error {
var (
err error
leaks []Leak
commitCount int64
commitWg sync.WaitGroup
semaphore chan bool
logOpts git.LogOptions
)
for _, re := range config.WhiteList.repos {
if re.FindString(repoInfo.name) != "" {
return leaks, fmt.Errorf("skipping %s, whitelisted", repoInfo.name)
if re.FindString(repo.name) != "" {
return fmt.Errorf("skipping %s, whitelisted", repo.name)
}
}
start := time.Now()
// check if target contains an external gitleaks toml
if opts.RepoConfig {
err := config.updateFromRepo(repoInfo)
err := config.updateFromRepo(repo)
if err != nil {
return leaks, nil
return err
}
}
if opts.Branch != "" {
refs, err := repoInfo.repository.Storer.IterReferences()
if opts.Commit != "" {
h := plumbing.NewHash(opts.Commit)
c, err := repo.repository.CommitObject(h)
if err != nil {
return leaks, err
return err
}
totalCommits = totalCommits + 1
repo.numCommits = 1
return repo.auditSingleCommit(c)
} else if opts.Branch != "" {
refs, err := repo.repository.Storer.IterReferences()
if err != nil {
return err
}
err = refs.ForEach(func(ref *plumbing.Reference) error {
if ref.Name().IsTag() {
@@ -157,10 +208,9 @@ func (repoInfo *RepoInfo) audit() ([]Leak, error) {
}
// iterate all through commits
cIter, err := repoInfo.repository.Log(&logOpts)
cIter, err := repo.repository.Log(&logOpts)
if err != nil {
return leaks, nil
return err
}
if opts.Threads != 0 {
@@ -181,24 +231,17 @@ func (repoInfo *RepoInfo) audit() ([]Leak, error) {
return nil
}
// commits w/o parent (root of git the git ref) or option for single commit is not empty str
if (len(c.ParentHashes) == 0 && opts.Commit == "") || (len(c.ParentHashes) == 0 && opts.Commit == c.Hash.String()) {
// commits w/o parent (root of git the git ref)
if len(c.ParentHashes) == 0 {
commitCount = commitCount + 1
totalCommits = totalCommits + 1
leaksFromSingleCommit := repoInfo.auditSingleCommit(c)
mutex.Lock()
leaks = append(leaksFromSingleCommit, leaks...)
mutex.Unlock()
if opts.Commit == c.Hash.String() {
return storer.ErrStop
err := repo.auditSingleCommit(c)
if err != nil {
return err
}
return nil
}
if opts.Commit != "" && opts.Commit != c.Hash.String() {
return nil
}
commitCount = commitCount + 1
totalCommits = totalCommits + 1
@@ -235,6 +278,27 @@ func (repoInfo *RepoInfo) audit() ([]Leak, error) {
} else if to != nil {
filePath = to.Path()
}
for _, fr := range config.FileRules {
for _, r := range fr.fileTypes {
if r.FindString(filePath) != "" {
commitInfo := &Commit{
repoName: repo.name,
filePath: filePath,
sha: c.Hash.String(),
author: c.Author.Name,
email: c.Author.Email,
message: strings.Replace(c.Message, "\n", " ", -1),
date: c.Author.When,
}
leak := *newLeak("N/A", fmt.Sprintf("filetype %s found", r.String()), r.String(), fr, commitInfo)
mutex.Lock()
repo.leaks = append(repo.leaks, leak)
mutex.Unlock()
}
}
}
for _, re := range config.WhiteList.files {
if re.FindString(filePath) != "" {
log.Debugf("skipping whitelisted file (matched regex '%s'): %s", re.String(), filePath)
@@ -248,8 +312,8 @@ func (repoInfo *RepoInfo) audit() ([]Leak, error) {
chunks := f.Chunks()
for _, chunk := range chunks {
if chunk.Type() == diffType.Add || chunk.Type() == diffType.Delete {
diff := commitInfo{
repoName: repoInfo.name,
diff := &Commit{
repoName: repo.name,
filePath: filePath,
content: chunk.Content(),
sha: c.Hash.String(),
@@ -261,7 +325,7 @@ func (repoInfo *RepoInfo) audit() ([]Leak, error) {
chunkLeaks := inspect(diff)
for _, leak := range chunkLeaks {
mutex.Lock()
leaks = append(leaks, leak)
repo.leaks = append(repo.leaks, leak)
mutex.Unlock()
}
}
@@ -276,15 +340,29 @@ func (repoInfo *RepoInfo) audit() ([]Leak, error) {
})
commitWg.Wait()
return leaks, nil
repo.numCommits = commitCount
repo.auditDuration = durafmt.Parse(time.Now().Sub(start)).String()
return nil
}
func (repoInfo *RepoInfo) auditSingleCommit(c *object.Commit) []Leak {
var leaks []Leak
func (repo *Repo) auditSingleCommit(c *object.Commit) error {
fIter, err := c.Files()
if err != nil {
return nil
return err
}
// If current commit has parents then search for leaks in tree change,
// that means scan in changed/modified files from one commit to another.
if len(c.ParentHashes) > 0 {
prevCommitObject, err := c.Parents().Next()
if err != nil {
return err
}
return repo.auditTreeChange(prevCommitObject, c)
}
// Scan for leaks in files related to current commit
err = fIter.ForEach(func(f *object.File) error {
bin, err := f.IsBinary()
if bin || err != nil {
@@ -300,8 +378,8 @@ func (repoInfo *RepoInfo) auditSingleCommit(c *object.Commit) []Leak {
if err != nil {
return nil
}
diff := commitInfo{
repoName: repoInfo.name,
diff := &Commit{
repoName: repo.name,
filePath: f.Name,
content: content,
sha: c.Hash.String(),
@@ -312,9 +390,92 @@ func (repoInfo *RepoInfo) auditSingleCommit(c *object.Commit) []Leak {
}
fileLeaks := inspect(diff)
mutex.Lock()
leaks = append(leaks, fileLeaks...)
repo.leaks = append(repo.leaks, fileLeaks...)
mutex.Unlock()
return nil
})
return leaks
return err
}
func (repo *Repo) report() {
if len(repo.leaks) != 0 {
log.Warnf("%d leaks detected. %d commits inspected in %s", len(repo.leaks), repo.numCommits, repo.auditDuration)
} else {
log.Infof("No leaks detected. %d commits inspected in %s", repo.numCommits, repo.auditDuration)
}
}
// auditTreeChange will search for leaks in changed/modified files from one
// commit to another
func (repo *Repo) auditTreeChange(src, dst *object.Commit) error {
var (
skip bool
)
// Get state of src commit
srcState, err := src.Tree()
if err != nil {
return err
}
// Get state of destination commit
dstState, err := dst.Tree()
if err != nil {
return err
}
changes, err := srcState.Diff(dstState)
// Run through each change
for _, change := range changes {
// Ignore deleted files
action, err := change.Action()
if err != nil {
return err
}
if action == merkletrie.Delete {
continue
}
// Get list of involved files
_, to, err := change.Files()
bin, err := to.IsBinary()
if bin || err != nil {
continue
}
for _, re := range config.WhiteList.files {
if re.FindString(to.Name) != "" {
log.Debugf("skipping whitelisted file (matched regex '%s'): %s", re.String(), to.Name)
skip = true
}
}
if skip {
skip = false
continue
}
content, err := to.Contents()
if err != nil {
return err
}
diff := &Commit{
repoName: repo.name,
filePath: to.Name,
content: content,
sha: dst.Hash.String(),
author: dst.Author.Name,
email: dst.Author.Email,
message: strings.Replace(dst.Message, "\n", " ", -1),
date: dst.Author.When,
}
fileLeaks := inspect(diff)
mutex.Lock()
repo.leaks = append(repo.leaks, fileLeaks...)
mutex.Unlock()
}
return nil
}
+80 -55
View File
@@ -11,21 +11,8 @@ import (
"time"
log "github.com/sirupsen/logrus"
"gopkg.in/src-d/go-git.v4/plumbing/object"
)
type commitInfo struct {
content string
commit *object.Commit
filePath string
repoName string
sha string
message string
author string
email string
date time.Time
}
// writeReport writes a report to a file specified in the --report= option.
// Default format for report is JSON. You can use the --csv option to write the report as a csv
func writeReport(leaks []Leak) error {
@@ -41,9 +28,9 @@ func writeReport(leaks []Leak) error {
}
defer f.Close()
w := csv.NewWriter(f)
w.Write([]string{"repo", "line", "commit", "offender", "reason", "commitMsg", "author", "email", "file", "date"})
w.Write([]string{"repo", "line", "commit", "offender", "rule", "info", "tags", "severity", "commitMsg", "author", "email", "file", "date"})
for _, leak := range leaks {
w.Write([]string{leak.Repo, leak.Line, leak.Commit, leak.Offender, leak.Type, leak.Message, leak.Author, leak.Email, leak.File, leak.Date.Format(time.RFC3339)})
w.Write([]string{leak.Repo, leak.Line, leak.Commit, leak.Offender, leak.Rule, leak.Info, leak.Tags, leak.Severity, leak.Message, leak.Author, leak.Email, leak.File, leak.Date.Format(time.RFC3339)})
}
w.Flush()
} else {
@@ -82,46 +69,84 @@ func writeReport(leaks []Leak) error {
return nil
}
// check rule will inspect a single line and return a leak if it encounters one
func (rule *Rule) check(line string, commit *Commit) (*Leak, error) {
var (
match string
fileMatch string
entropy float64
entropyWord string
)
for _, f := range rule.fileTypes {
fileMatch = f.FindString(commit.filePath)
if fileMatch != "" {
break
}
}
if fileMatch == "" && len(rule.fileTypes) != 0 {
return nil, nil
}
if rule.entropies != nil {
if rule.entropyROI == "word" {
words := strings.Fields(line)
for _, word := range words {
_entropy := getShannonEntropy(word)
for _, e := range rule.entropies {
if _entropy > e.v1 && _entropy < e.v2 {
entropy = _entropy
entropyWord = word
goto postEntropy
}
}
}
} else {
_entropy := getShannonEntropy(line)
for _, e := range rule.entropies {
if _entropy > e.v1 && _entropy < e.v2 {
entropy = _entropy
entropyWord = line
goto postEntropy
}
}
}
}
postEntropy:
if rule.regex != nil {
match = rule.regex.FindString(line)
}
if match != "" && entropy != 0.0 {
return newLeak(line, fmt.Sprintf("%s regex match and entropy met at %.2f", rule.regex.String(), entropy), entropyWord, rule, commit), nil
} else if match != "" && rule.entropies == nil {
return newLeak(line, fmt.Sprintf("%s regex match", rule.regex.String()), match, rule, commit), nil
} else if entropy != 0.0 && rule.regex.String() == "" {
return newLeak(line, fmt.Sprintf("entropy met at %.2f", entropy), entropyWord, rule, commit), nil
}
return nil, nil
}
// inspect will parse each line of the git diff's content against a set of regexes or
// a set of regexes set by the config (see gitleaks.toml for example). This function
// will skip lines that include a whitelisted regex. A list of leaks is returned.
// If verbose mode (-v/--verbose) is set, then checkDiff will log leaks as they are discovered.
func inspect(commit commitInfo) []Leak {
var (
leaks []Leak
skipLine bool
)
func inspect(commit *Commit) []Leak {
var leaks []Leak
lines := strings.Split(commit.content, "\n")
for _, line := range lines {
skipLine = false
for _, re := range config.Regexes {
match := re.regex.FindString(line)
if match == "" {
continue
}
if skipLine = isLineWhitelisted(line); skipLine {
for _, rule := range config.Rules {
if isLineWhitelisted(line) {
break
}
leaks = addLeak(leaks, line, match, re.description, commit)
}
if !skipLine && (opts.Entropy > 0 || len(config.Entropy.entropyRanges) != 0) {
words := strings.Fields(line)
for _, word := range words {
entropy := getShannonEntropy(word)
// Only check entropyRegexes and whiteListRegexes once per line, and only if an entropy leak type
// was found above, since regex checks are expensive.
if !entropyIsHighEnough(entropy) {
continue
}
// If either the line is whitelisted or the line fails the noiseReduction check (when enabled),
// then we can skip checking the rest of the line for high entropy words.
if skipLine = !highEntropyLineIsALeak(line) || isLineWhitelisted(line); skipLine {
break
}
leaks = addLeak(leaks, line, word, fmt.Sprintf("Entropy: %.2f", entropy), commit)
leak, err := rule.check(line, commit)
if err != nil || leak == nil {
continue
}
leaks = append(leaks, *leak)
}
}
return leaks
@@ -138,19 +163,21 @@ func isLineWhitelisted(line string) bool {
return false
}
// addLeak is helper for func inspect() to append leaks if found during a diff check.
func addLeak(leaks []Leak, line string, offender string, leakType string, commit commitInfo) []Leak {
leak := Leak{
func newLeak(line string, info string, offender string, rule *Rule, commit *Commit) *Leak {
leak := &Leak{
Line: line,
Commit: commit.sha,
Offender: offender,
Type: leakType,
Rule: rule.description,
Info: info,
Author: commit.author,
Email: commit.email,
File: commit.filePath,
Repo: commit.repoName,
Message: commit.message,
Date: commit.date,
Tags: strings.Join(rule.tags, ", "),
Severity: rule.severity,
}
if opts.Redact {
leak.Offender = "REDACTED"
@@ -160,17 +187,15 @@ func addLeak(leaks []Leak, line string, offender string, leakType string, commit
if opts.Verbose {
leak.log()
}
leaks = append(leaks, leak)
return leaks
return leak
}
// discoverRepos walks all the children of `path`. If a child directory
// contain a .git subdirectory then that repo will be added to the list of repos returned
func discoverRepos(ownerPath string) ([]*RepoInfo, error) {
func discoverRepos(ownerPath string) ([]*Repo, error) {
var (
err error
repoDs []*RepoInfo
repoDs []*Repo
)
files, err := ioutil.ReadDir(ownerPath)
if err != nil {
@@ -179,7 +204,7 @@ func discoverRepos(ownerPath string) ([]*RepoInfo, error) {
for _, f := range files {
repoPath := path.Join(ownerPath, f.Name())
if f.IsDir() && containsGit(repoPath) {
repoDs = append(repoDs, &RepoInfo{
repoDs = append(repoDs, &Repo{
name: f.Name(),
path: repoPath,
})