Compare commits

...
145 Commits
Author SHA1 Message Date
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
zricethezav 81b3a6e279 Update readme 2020-12-02 17:11:47 -05:00
Zachary Rice c50906373c update to V7 (#469) 2020-12-02 17:07:31 -05:00
Zachary Rice 40545fb680 Need to include offender in line extraction memoization (#466) 2020-11-21 15:49:59 -05:00
Daniel Paul SearlesandDaniel Paul Searles 2acc34dfdf Add support for reportGroup (#456)
Why:

* There are times where it would be nice to have a group from the regex
  reported rather than the complete match.

This change addresses the need by:

* Add the reportGroup configuration option for a rule.
* Update scan.CheckRules to return the reportGroup if set.

Co-authored-by: Daniel Paul Searles <dsearles@gitlab.com>
2020-11-03 15:15:48 -05:00
zricethezav ede68fd95d fix off by one 2020-09-02 08:36:19 -04:00
Zachary Rice 6c60c3dde3 Adding some logic to fix line number extractor when there are multipl… (#436)
* Adding some logic to fix line number extractor when there are multiple secrets of the same offender within the same patch

* formatting some consts
2020-09-01 20:48:43 -04:00
Zachary Rice ad505754fc Add commits and commits-file option (#433) 2020-08-31 10:29:04 -04:00
Zachary Rice 21d81879e2 Update README.md 2020-08-27 14:11:11 -04:00
Lars Lehtonen b5ca2ba614 scan: fix dropped errors (#424) 2020-08-20 15:42:42 -04:00
Zachary Rice ef4655fcf1 Sarif (#421)
* init

* more work

* more sarif work

* mergin
2020-08-12 18:07:24 -04:00
Zachary Rice 01b553a75d Update Makefile 2020-08-12 17:51:56 -04:00
Zachary Rice fae366a404 Global allowlist regex (#422)
* work in progress

* Update test configs

* adding test

* golint and change to allowlist

* fix race condition, this mistakenly got committed

* Updating tests and examples

* bump to v6 as this is a breaking change to the config

* More consistent variables
2020-08-12 17:18:25 -04:00
Lars Lehtonen 6129b1a15d hosts: dropped error (#417) 2020-07-31 08:45:47 -04:00
Manuel Jeckelmann 31d03a1146 Clean up 'uncommitted' diff. (#416) 2020-07-28 08:55:33 -04:00
Zachary Rice eabc7b5c12 Fixing merge commit scans and large patch rule checking (#414)
* Fixing merge commit scans and large patch rule checking

* Adding tests for merge request scans
2020-07-25 14:55:59 -04:00
zricethezav 1dc7569f95 removing extra log import... 2020-07-24 14:42:54 -04:00
zricethezav 1797e9c966 Merge branch 'master' of github.com:zricethezav/gitleaks 2020-07-24 14:07:25 -04:00
zricethezav e2eaceb4cd rm bad example config 2020-07-24 14:07:00 -04:00
Zachary Rice c637b129ec Validate config (#412)
* validate config

* fix import fmt

* cleaning
2020-07-24 14:02:48 -04:00
zricethezav 8470e43d7f validate config 2020-07-24 13:54:01 -04:00
Zachary Rice 94f5950d68 Use allowlist (#411) 2020-07-24 11:58:43 -04:00
Zachary Rice fe69a17c9c Change remaining audits to scan (#410) 2020-07-24 11:30:33 -04:00
Zachary Rice 6ca7a11d88 Add line number to report plus some other things (#409)
* Init refactor

* think i got it working

* we got em

* Updating tests

* fixing tests

* Better comments, more test fixing

* Bumping to v5

* Fixing golint messages

* Replacing usage of audit with scan in comments

* bumping go-git

* Updating to v5 in some other spots
2020-07-24 10:49:03 -04:00
Zachary Rice cfbb600fcb Fixing patch direction and making additions the default (#408)
* Fixing patch direction and making additions the default

* adding test
2020-07-22 13:32:46 -04:00
Zachary Rice e36b550851 adding go mod/sum to ignore, adding quotes to aws secret rule (#397)
* adding go mod/sum to ignore, adding quotes to aws secret rule

* lil nicer formatting
2020-06-14 15:41:04 -04:00
zricethezav 2232dc191c removing bad options guard 2020-06-03 08:51:11 -04:00
Zachary Rice bdc688dd53 fix whitelist commits, added test (#390) 2020-05-31 10:25:58 -04:00
Steeve Barbeau e0f6399d5c Audit commits based on date/time parameters (#385)
* time based audit

* fixing SIGSEGV

* adding options for date and time format + tests

* Update repo.go

* Update github.go

* rebase + tests update
2020-05-24 18:03:47 -04:00
Zachary Rice 3e88ac6726 Update README.md 2020-05-20 15:48:53 -04:00
Zeyshi d0088f6c7c Update default.go (#382) 2020-05-14 17:27:35 -04:00
zricethezav 0d7c18cb39 fixing whitelist repo tests 2020-05-09 11:37:08 -04:00
zricethezav d0e98416b9 Merge branch 'master' of github.com:zricethezav/gitleaks 2020-05-09 11:24:06 -04:00
Zachary Rice b7438011b4 Rm generic from default (#379)
* fixing commit latest bug

* remove generic rule from default to reduce false positives
2020-05-09 11:21:17 -04:00
zricethezav 4e59d3bf19 Merge branch 'master' of github.com:zricethezav/gitleaks 2020-05-09 10:54:35 -04:00
Steeve Barbeau e4b26aea4a fixing issue #367 (#368) 2020-05-09 10:49:00 -04:00
Zachary Rice 473d0d55a7 Whitelist repo (#378)
* fixing commit latest bug

* bumping go-git and adding repo whitelist

* adding tests
2020-05-09 10:38:02 -04:00
Zachary Rice 8bd4649b01 Update leaky-repo.toml 2020-05-09 08:53:43 -04:00
zricethezav a69df84325 Merge branch 'master' of github.com:zricethezav/gitleaks 2020-05-09 08:51:58 -04:00
Marlon Pina Tojal 0faebdefea Whitelist files not being parsed (#375)
It seems that there is a typo on the default rules.
2020-05-04 10:56:27 -04:00
Zachary Rice a728e3abf3 Documentation upgrade (#374)
* fixing commit latest bug

* updating readme

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md
2020-04-28 17:43:01 -04:00
zricethezav e87c62fe72 Merge branch 'master' of github.com:zricethezav/gitleaks 2020-04-23 11:23:46 -04:00
Zachary Rice 4801818e3d fixing commit latest bug (#365) 2020-04-05 11:36:37 -04:00
zricethezav b4a0577786 fixing commit latest bug 2020-04-05 11:31:22 -04:00
Zachary Rice 212232f80a Empty repo audit (#364)
* bump to go 1.14 and alpine to 3.11

* audit before commit

* adding test

* rm hooks in test repo
2020-04-05 11:18:33 -04:00
Zachary Rice 11dcb44e41 bump to go 1.14 and alpine to 3.11 (#363) 2020-04-05 09:38:27 -04:00
Prabhu Subramanian af0df6ea2c Added gosec scan (#311) 2020-04-05 09:38:10 -04:00
Zachary Rice 9db91442b3 ignoring config when using custom config (#362) 2020-04-04 14:49:54 -04:00
Zachary Rice 9d76070806 Update README.md 2020-03-25 11:22:32 -04:00
Zachary Rice 2fa580f1bb fix the empty repo org scan error (#358) 2020-03-20 22:44:17 -04:00
Zach Stone c6f15b768e Improve default pattern configuration (#356)
* Add GCP, fix Mailgun format, and loosen format for other keys (don't require quotes)

* Add more match cases to generic credential pattern

* Fix quotation for valid toml

* Update tests
2020-03-20 21:14:30 -04:00
Zachary Rice 779937ca87 Update README.md 2020-03-06 18:59:03 -05:00
Zachary Rice 731856e974 Update README.md 2020-03-06 18:55:24 -05:00
Zachary Rice baf54631c7 Update README.md 2020-03-06 18:43:40 -05:00
zricethezav 3e760d7fed updating help message 2020-03-02 20:24:22 -05:00
Noel Algora 679f00dc9c Scan files at latest commit (#348)
* Inspect files at latest commit

Added option to scan files at latest commit

* Files at latest commit test
2020-03-02 20:22:14 -05:00
Zachary Rice dae5c142d7 Fix host clone auth (#350)
* trying auth fix

* fixing github private user auth and donate msg

* formatting

* go fmt...
2020-02-29 13:30:08 -05:00
Zachary Rice 8e8873286e Update leaky-repo.toml 2020-02-29 13:19:55 -05:00
Zachary Rice 6693cbdde3 Update README.md 2020-02-27 09:29:52 -05:00
Zachary Rice 8b3ce2cb1e forgot to bump in code... (#347) 2020-02-26 20:41:54 -05:00
Zachary Rice 94cae90d1e duplicate leak logic includes the line in hash (#345) 2020-02-26 17:38:16 -05:00
Noel Algora c4b07f5113 Add file regex support (#340)
* Modified Entropy to be able to apply it on regex match or specific capture group

* Config tests

* Small fixes on entropy ranges

* Fix toml configs
Fix tests

* Start adding support for rules with filename regex

Changed how config is parsed
Created new functions to inspect files and content

* File regex working

* Fixing tests and configs

* Implemented different regex for filename and filepath

* Fix comments

* Audit tests

* Config rename vars

* Fix audit tests

* Filename offender

* Indents and code styles

* Indents and code styles

* Removing bad test repo

* Adding test repo 6 for filename and filepath tests

* global whitelist path and fixes

* Fixes on tests and new test for global whitelisting paths

* Removing unused test

* Fix comment
2020-02-26 15:33:14 -05:00
Alexander Curtiss 01d73028f8 Fixed bug where the repo name was removed on a user or org audit. (#344) 2020-02-26 14:42:44 -05:00
Dmitry Ivanov 862f1203ed Minor formatting fix (#330) 2020-02-25 18:24:27 -05:00
Zachary Rice 581e81c16e Update README.md 2020-02-25 17:39:41 -05:00
Zachary Rice 6c166c9530 Update README.md 2020-02-25 17:32:40 -05:00
Zachary Rice 4181ede6cd Update FUNDING.yml 2020-02-25 11:55:18 -05:00
Zachary Rice 10745be661 fixing commit counts (#342)
* fixing commit counts

* fixing commit to test
2020-02-25 10:28:03 -05:00
Noel Algora ee2d73c740 Enhance entropy (#333)
* Modified Entropy to be able to apply it on regex match or specific capture group

* Config tests

* Small fixes on entropy ranges

* Fix toml configs
Fix tests

* Indents and code styles
2020-02-24 13:44:38 -05:00
zricethezav e7fbcf5333 updating readme and comments 2020-02-01 16:48:05 -05:00
Zachary Rice 2810eccc82 Merge pull request #329 from zricethezav/bug/commit-scan
Bug/commit scan
2020-02-01 11:38:02 -05:00
zricethezav baff419091 removing hooks 2020-02-01 11:23:11 -05:00
zricethezav d13e0fdfde adding more tests 2020-02-01 11:18:27 -05:00
zricethezav 5a300c3c64 fixing --commit bug, adding --files-at-commit option 2020-01-30 20:08:01 -05:00
Zachary Rice d8ddb9630a Merge pull request #327 from zricethezav/bug/timeoutcancel
Adding timeout check in context select so we dont log erroneously
2020-01-24 18:16:59 -05:00
zricethezav 1537eeb5fa Adding timeout check in context select so we dont log erroneously 2020-01-24 18:07:16 -05:00
Zachary Rice 1a492537dd Merge pull request #325 from zricethezav/bug/timeoutcancel
defer cancel in audit
2020-01-23 18:52:56 -05:00
zricethezav bd4107b002 ensuring cancel is called after audit is complete so context can be dropped 2020-01-23 18:47:37 -05:00
Zach Rice 7b48cadf6d fixing version loading in makefile 2020-01-22 20:42:14 -05:00
Zachary Rice 6eab8a7a0a Update README.md 2020-01-22 20:00:27 -05:00
Zachary Rice c6d14e5b7d Merge pull request #323 from zricethezav/bug/fix-go-module
fixing modules, adding v3 in path
2020-01-22 18:10:23 -05:00
zricethezav ce95cafd54 fixing modules, adding v3 in path 2020-01-22 10:21:00 -05:00
Zachary Rice 4024faceab Merge pull request #322 from zricethezav/exclude-forks
exclude-forks gitlab and github
2020-01-19 12:41:07 -05:00
zricethezav 1afa931248 exclude-forks gitlab and github 2020-01-19 12:35:52 -05:00
Zachary Rice 2474c39311 Merge pull request #321 from zricethezav/depth
reimplementing depth feature
2020-01-19 12:17:42 -05:00
zricethezav f6460a7365 reimplementing depth feature 2020-01-19 12:14:14 -05:00
Zachary Rice b47e00858e Merge pull request #320 from zricethezav/bug/manager-ptr
bug/manager-ptr
2020-01-19 11:56:29 -05:00
zricethezav b200a13c8d bug fix: use manager pointers instead of value for gitleaks hosts... this was causing an issue with metadata logging 2020-01-19 11:51:52 -05:00
Zachary Rice e6fabdbb31 Merge pull request #319 from zricethezav/repo-timeout
Repo timeout
2020-01-19 11:48:57 -05:00
Zachary Rice cdd654eab7 pr template 2020-01-19 10:17:08 -05:00
zricethezav 2f07b96333 adding test, cancelfunc (for go vet) 2020-01-19 10:07:01 -05:00
zricethezav 62e74b2b18 let the repo handle timeouts... better for automating audits anyway 2020-01-19 09:26:06 -05:00
Zachary Rice e75693b131 Update feature_request.md 2020-01-12 12:22:54 -05:00
Zachary Rice 3cd14d4696 Update bug_report.md 2020-01-12 12:22:14 -05:00
Zachary Rice d29cc9892c Update bug_report.md 2020-01-12 12:21:33 -05:00
Zachary Rice d996882f4e Update bug_report.md 2020-01-12 12:20:44 -05:00
Zachary Rice 17b6aa856d Update issue templates 2020-01-12 11:07:45 -05:00
Zachary Rice c21a9cf121 Merge pull request #317 from zricethezav/feature/commit-range
Adding commit range feature via 'commit-to' and 'commit-from' options
2020-01-11 17:01:53 -05:00
zricethezav d3c4342c15 Updating README 2020-01-11 16:58:59 -05:00
zricethezav b4c2f8e69c cleaning up some comments 2020-01-11 16:54:09 -05:00
Zach Rice a0f72a4e35 Adding commit range feature via 'commit-to' and 'commit-from' options 2020-01-11 16:46:58 -05:00
Zachary Rice 24844002de Update README.md 2020-01-03 16:15:54 -05:00
Zachary Rice 593edeae21 Update README.md 2019-12-24 10:03:02 -06:00
Zachary Rice 6df770d261 Merge pull request #313 from zricethezav/bug/docker-update
adding docker push support again to Make and fixed a go vet nit
2019-12-24 09:13:01 -06:00
zach rice 4f0c9dcede adding docker push support again to Make and fixed a go vet nit 2019-12-17 20:44:20 -05:00
Zachary Rice 52425a8ca9 Merge pull request #307 from pegasd/add_pkcs8_key_support
Add support for PKCS8 key
2019-12-07 19:33:54 -05:00
Zachary Rice 454acebe5a Merge pull request #303 from petegallagher/host-base-url
Adding baseurl flag to allow self-hosted GitLab/GitHub servers
2019-12-05 10:32:52 -05:00
Peter Gallagher 6fcf91e934 Removing logging of git client errors as these are now returned in main.go 2019-12-05 15:22:18 +00:00
Peter Gallagher f89b8f2b29 Return errors for failed host clients 2019-12-05 12:11:46 +00:00
Zachary Rice 648a7ba577 Merge pull request #304 from chapeupreto/patch-1
fix typo
2019-12-04 14:47:12 -05:00
Zachary Rice 7c5594c39d Merge pull request #305 from zricethezav/limit-leak-len
Limit leak len
2019-12-04 14:46:36 -05:00
Zachary Rice 274e8212a6 adding license 2019-12-04 08:48:37 -05:00
Eugene Piven 36c6ddaf86 Add support for PKCS8 key 2019-12-03 20:24:33 +03:00
zach rice 15ed72bc09 updating test data 2019-12-01 21:33:40 -05:00
zach rice ace8de93a9 limit leak len to 200 characters 2019-12-01 21:30:40 -05:00
Rod Elias 45a4c0a284 fix typo 2019-12-01 17:10:26 -03:00
Peter Gallagher c5e1e8abc0 Adding baseurl flag to allow self-hosted GitLab/GitHub servers 2019-12-01 10:49:32 +00:00
Zachary Rice ef38b69c39 Merge pull request #302 from petegallagher/whitelist-gitleaks.toml
Update default whitelist to include gitleaks.toml
2019-11-30 09:44:23 -06:00
Zachary Rice ac6bde9996 Merge pull request #296 from petegallagher/private-key
Update asymmetric private key regex
2019-11-30 09:41:35 -06:00
Zachary Rice 23568cc0ba Merge pull request #295 from petegallagher/sendgrid
Adding regex for SendGrid API keys
2019-11-30 09:41:10 -06:00
Zachary Rice e61c2cfae7 Merge pull request #301 from petegallagher/AuditUncommitted
Fix repo-config and file whitelist for AuditUncommitted function
2019-11-30 09:40:24 -06:00
Peter Gallagher 38e0b11995 Fix test data for AuditUncommitted 2019-11-29 10:22:02 +00:00
Peter Gallagher 31903d1a80 Update default whitelist to include gitleaks.toml 2019-11-29 10:14:03 +00:00
Peter Gallagher 3655284b57 Fix test data for AuditUncommitted 2019-11-29 10:07:56 +00:00
Peter Gallagher db79a96118 Use Unix Epoch time for staged commit time 2019-11-29 10:07:27 +00:00
Peter Gallagher999 5152e1fc63 Reset commit values when auditing uncommitted changes 2019-11-28 23:13:59 +00:00
Peter Gallagher c04e137b28 Adding global file regex to AuditUncommitted 2019-11-28 22:53:08 +00:00
Peter Gallagher 9b3342fbff Allow use of --repo-config for AuditUncommitted function 2019-11-28 13:53:52 +00:00
Peter Gallagher d9a060a12d Honour file whitelist for AuditUncommitted function 2019-11-28 13:53:18 +00:00
Peter Gallagher 77f2fdd09a Update asymmetric private key regex 2019-11-25 15:59:40 +00:00
Peter Gallagher dba1ef6104 Adding regex for SendGrid API keys 2019-11-25 15:49:47 +00:00
300 changed files with 6037 additions and 2887 deletions

No files matched your search

+1
View File
@@ -1,3 +1,4 @@
# These are supported funding model platforms
github: [zricethezav]
custom: ["https://www.paypal.me/zricethezav"]
+29
View File
@@ -0,0 +1,29 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Basic Info (please complete the following information):**
- OS:
- Gitleaks Version:
**Additional context**
Add any other context about the problem here.
cc @zricethezav
+22
View File
@@ -0,0 +1,22 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: enhancement
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
cc @zricethezav
+8
View File
@@ -0,0 +1,8 @@
### Description:
Explain the purpose of the PR.
### Checklist:
* [ ] Does your PR pass tests?
* [ ] Have you written new tests for your changes?
* [ ] Have you lint your code locally prior to submission?
+1
View File
@@ -7,6 +7,7 @@
*.DS_STORE
*.idea
gitleaks
build
# Test binary
*.out
+2 -1
View File
@@ -1,7 +1,8 @@
language: go
go:
- 1.13.x
- 1.14.x
services:
- docker
script:
- make test
- make security-scan
+4 -3
View File
@@ -1,9 +1,10 @@
FROM golang:1.13.4 AS build
FROM golang:1.15.5 AS build
WORKDIR /go/src/github.com/zricethezav/gitleaks
ARG ldflags
COPY . .
RUN GO111MODULE=on CGO_ENABLED=0 go build -o bin/gitleaks *.go
RUN GO111MODULE=on CGO_ENABLED=0 go build -o bin/gitleaks -ldflags "-X="${ldflags} *.go
FROM alpine:3.10
FROM alpine:3.11
RUN apk add --no-cache bash git openssh
COPY --from=build /go/src/github.com/zricethezav/gitleaks/bin/* /usr/bin/
ENTRYPOINT ["gitleaks"]
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 Zachary Rice
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+14 -7
View File
@@ -2,7 +2,8 @@
VERSION := `git fetch --tags && git tag | sort -V | tail -1`
PKG=github.com/zricethezav/gitleaks
LDFLAGS=-ldflags "-X=github.com/zricethezav/gitleaks/version.Version=$(VERSION)"
LDFLAGS=-ldflags "-X=github.com/zricethezav/gitleaks/v7/version.Version=$(VERSION)"
_LDFLAGS="github.com/zricethezav/gitleaks/v7/version.Version=$(VERSION)"
COVER=--cover --coverprofile=cover.out
test-cover:
@@ -12,18 +13,21 @@ test-cover:
test:
go get golang.org/x/lint/golint
go fmt ./...
go vet ./...
golint ./...
go test ./... --race $(PKG) -v
test-integration:
go test github.com/zricethezav/gitleaks/hosts -v -integration
build:
go fmt ./...
golint ./...
go vet ./...
go mod tidy
go build $(LDFLAGS)
security-scan:
go get github.com/securego/gosec/cmd/gosec
gosec -no-fail ./...
release-builds:
rm -rf build
mkdir build
@@ -37,6 +41,9 @@ release-builds:
deploy:
@echo "$(DOCKER_PASSWORD)" | docker login -u "$(DOCKER_USERNAME)" --password-stdin
docker build -f Dockerfile -t $(REPO):$(TAG) .
echo "Pushing $(REPO):$(COMMIT) $(REPO):$(TAG)"
docker push $(REPO)
docker build --build-arg ldflags=$(_LDFLAGS) -f Dockerfile -t zricethezav/gitleaks:latest -t zricethezav/gitleaks:$(VERSION) .
echo "Pushing zricethezav/gitleaks:$(VERSION) and zricethezav/gitleaks:latest"
docker push zricethezav/gitleaks
dockerbuild:
docker build --build-arg ldflags=$(_LDFLAGS) -f Dockerfile -t zricethezav/gitleaks:latest -t zricethezav/gitleaks:$(VERSION) .
+225 -83
View File
@@ -1,123 +1,265 @@
Gitleaks
--------
<p align="left">
<p align="center">
<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>
</p>
</p>
Audit git repos for secrets. Gitleaks provides a way for you to find unencrypted secrets and other unwanted data types in git repositories. As part of it's core functionality, it provides:
* Audits for uncommitted changes
* Github and Gitlab support including support for bulk organization and repository owner (user) repository scans, as well as pull/merge request scanning for use in common CI workflows.
* Support for private repository scans, and repositories that require key based authentication
* Output in JSON formats for consumption in other reporting tools and frameworks
* Externalised configuration for environment specific customisation including regex rules
* High performance through the use of src-d's [go-git](https://github.com/src-d/go-git) framework
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.
### Features:
- Scan for [commited](https://github.com/zricethezav/gitleaks#Scanning) secrets
- Scan for [unstaged](https://github.com/zricethezav/gitleaks#scan-unstaged-changes) secrets as part of shifting security left
- Scan [directories and files](https://github.com/zricethezav/gitleaks#scan-local-directory)
- Available [Github Action](https://github.com/marketplace/actions/gitleaks)
- [Custom rules](https://github.com/zricethezav/gitleaks#configuration) via toml configuration
- High 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.
| `repo scan` |
|---|
| <p align="left"><img src="https://raw.githubusercontent.com/zricethezav/gifs/master/repo-scan.gif"></p> | <p align="left"><img src="https://raw.githubusercontent.com/zricethezav/gifs/master/repo-scan.gif"></p> |
| `pre commit scan` |
|---|
| <p align="left"><img src="https://raw.githubusercontent.com/zricethezav/gifs/master/pre-commit-1.gif"></p> |
## Getting Started
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
docker pull zricethezav/gitleaks
```
#### Go
##### Go
```bash
go get -u github.com/zricethezav/gitleaks
GO111MODULE=on go get github.com/zricethezav/gitleaks/v7
```
## Usage
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
```
Usage:
gitleaks [OPTIONS]
Application Options:
-v, --verbose Show verbose output from audit
-r, --repo= Target repository
--config= config path
--disk Clones repo(s) to disk
--version version number
--timeout= Timeout (s)
--username= Username for git repo
--password= Password for git repo
--access-token= Access token for git repo
--commit= sha of commit to audit
--threads= Maximum number of threads gitleaks spawns
--ssh-key= path to ssh key used for auth
--uncommitted run gitleaks on uncommitted code
--repo-path= Path to repo
--owner-path= Path to owner directory (repos discovered)
--branch= Branch to audit
--report= path to write json leaks file
--redact redact secrets from log messages and leaks
--debug log debug messages
--repo-config Load config from target repo. Config file must be ".gitleaks.toml" or "gitleaks.toml"
--pretty Pretty print json if leaks are present
--host= git hosting service like gitlab or github. Supported hosts include: Github, Gitlab
--org= organization to audit
--user= user to audit
--pr= pull/merge request url
-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
--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
--leaks-exit-code= Exit code when leaks have been encountered (default: 1)
--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
Help Options:
-h, --help Show this help message
-h, --help Show this help message
```
### Docker usage examples
Run gitleaks against:
### [Scanning](https://www.youtube.com/watch?v=WUzpRL8mKCk)
###### Public repository
```bash
docker run --rm --name=gitleaks zricethezav/gitleaks -v -r https://github.com/zricethezav/gitleaks.git
#### 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
```
###### Local repository already cloned into /tmp/
```bash
docker run --rm --name=gitleaks -v /tmp/:/code/ zricethezav/gitleaks -v --repo-path=/code/gitleaks
#### Basic repo-url scan output to a report:
If we want the report in sarif or csv we can set the `-f/--format` option
```
gitleaks --repo-url=https://github.com/my-insecure/repo -v --report=my-report.json
```
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` threads at your instance CPU.
## Exit Codes
Gitleaks provides consistent exist codes to assist in automation workflows such as CICD platforms and bulk scanning.
#### Scan specific commit:
```
0: no leaks
1: leaks present
2: error encountered
gitleaks --repo-url=https://github.com/my-insecure/repo --commit=commit-sha -v
```
### Give Thanks
#### Scan local repo:
```
gitleaks --path=path/to/local/repo -v
```
If using gitleaks has made you job easier consider donating to one of [Sam](https://www.flickr.com/photos/146541520@N08/albums/72157710121716312)'s favorite places, the Japan House on the University of Illinois at Urbana-Champaign's campus: https://japanhouse.illinois.edu/make-a-gift
#### Scan repos contain in a parent directory:
If we had `repo1`, `repo2`, `repo3` all under `path/to/local`, gitleaks will discover and scan those repos.
```
gitleaks --path=path/to/local/ -v
```
#### Scan local directory:
You might 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 you might 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`. The difference between the two is `--config-path` loads a local gitleaks config whereas `--repo-config-path` will load a configuration present 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 contain a few different toml tables which will be explained 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)
Gamma proactively detects and remediates data leaks across cloud apps. Scan your public repos for secret leaks with [Gamma](https://gammanet.com/github-demo?utm_source=gitleaks&utm_medium=homepage&utm_campaign=gitleaks_promotion)
#### 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) |
---|
----
#### Logo Attribution
The Gitleaks logo uses the Git Logo created <a href="https://twitter.com/jasonlong">Jason Long</a> is licensed under the <a href="https://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0 Unported License</a>.
-56
View File
@@ -1,56 +0,0 @@
package audit
import (
"fmt"
"io/ioutil"
"path"
"github.com/zricethezav/gitleaks/manager"
log "github.com/sirupsen/logrus"
)
// Run accepts a manager and begins an audit based on the options/configs set in the manager.
func Run(m *manager.Manager) error {
if m.Opts.OwnerPath != "" {
files, err := ioutil.ReadDir(m.Opts.OwnerPath)
if err != nil {
return err
}
for _, f := range files {
if !f.IsDir() {
continue
}
m.Opts.RepoPath = fmt.Sprintf("%s/%s", m.Opts.OwnerPath, f.Name())
if err := runHelper(NewRepo(m)); err != nil {
log.Warnf("%s is not a git repo, skipping", f.Name())
}
}
return nil
}
return runHelper(NewRepo(m))
}
func runHelper(r *Repo) error {
if r.Manager.Opts.OpenLocal() {
r.Name = path.Base(r.Manager.Opts.RepoPath)
if err := r.Open(); err != nil {
return err
}
// Check if we are checking uncommitted files. This is the default behavior
// for a "$gitleaks" command with no options set
if r.Manager.Opts.CheckUncommitted() {
if err := r.AuditUncommitted(); err != nil {
return err
}
return nil
}
} else {
if err := r.Clone(nil); err != nil {
return err
}
}
return r.Audit()
}
-352
View File
@@ -1,352 +0,0 @@
package audit
import (
"fmt"
"github.com/sergi/go-diff/diffmatchpatch"
"github.com/zricethezav/gitleaks/config"
"github.com/zricethezav/gitleaks/manager"
"github.com/zricethezav/gitleaks/options"
"io/ioutil"
"os"
"runtime"
"strings"
"testing"
)
const testRepoBase = "../test_data/test_repos/"
func TestAudit(t *testing.T) {
moveDotGit("dotGit", ".git")
defer moveDotGit(".git", "dotGit")
tests := []struct {
description string
opts options.Options
wantPath string
wantErr error
emptyRepo bool
wantEmpty bool
}{
{
description: "test local repo one aws leak",
opts: options.Options{
RepoPath: "../test_data/test_repos/test_repo_1",
Report: "../test_data/test_local_repo_one_aws_leak.json.got",
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_one_aws_leak.json",
},
{
description: "test local repo one aws leak threaded",
opts: options.Options{
Threads: runtime.GOMAXPROCS(0),
RepoPath: "../test_data/test_repos/test_repo_1",
Report: "../test_data/test_local_repo_one_aws_leak.json.got",
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_one_aws_leak.json",
},
{
description: "test non existent repo",
opts: options.Options{
RepoPath: "../test_data/test_repos/no_repo_here",
ReportFormat: "json",
},
emptyRepo: true,
},
{
description: "test local repo one aws leak whitelisted",
opts: options.Options{
RepoPath: "../test_data/test_repos/test_repo_1",
ReportFormat: "json",
Config: "../test_data/test_configs/aws_key_whitelist_python_files.toml",
},
wantEmpty: true,
},
{
description: "test local repo two leaks",
opts: options.Options{
RepoPath: "../test_data/test_repos/test_repo_2",
Report: "../test_data/test_local_repo_two_leaks.json.got",
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_two_leaks.json",
},
{
description: "test local repo two leaks globally whitelisted",
opts: options.Options{
RepoPath: "../test_data/test_repos/test_repo_2",
Config: "../test_data/test_configs/aws_key_global_whitelist_file.toml",
ReportFormat: "json",
},
wantEmpty: true,
},
{
description: "test local repo two leaks whitelisted",
opts: options.Options{
RepoPath: "../test_data/test_repos/test_repo_2",
Config: "../test_data/test_configs/aws_key_whitelist_files.toml",
ReportFormat: "json",
},
wantEmpty: true,
},
{
description: "test local repo three leaks dev branch",
opts: options.Options{
RepoPath: "../test_data/test_repos/test_repo_3",
Report: "../test_data/test_local_repo_three_leaks.json.got",
Config: "../test_data/test_configs/aws_key.toml",
Branch: "dev",
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_three_leaks.json",
},
{
description: "test local repo branch does not exist",
opts: options.Options{
RepoPath: "../test_data/test_repos/test_repo_3",
Branch: "nobranch",
ReportFormat: "json",
},
wantEmpty: true,
},
{
description: "test local repo one aws leak single commit",
opts: options.Options{
RepoPath: "../test_data/test_repos/test_repo_1",
Report: "../test_data/test_local_repo_one_aws_leak_commit.json.got",
Commit: "6557c92612d3b35979bd426d429255b3bf9fab74",
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_one_aws_leak_commit.json",
},
{
description: "test local repo one aws leak AND leak on python files",
opts: options.Options{
RepoPath: "../test_data/test_repos/test_repo_1",
Report: "../test_data/test_local_repo_one_aws_leak_and_file_leak.json.got",
Config: "../test_data/test_configs/aws_key_file_regex.toml",
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_one_aws_leak_and_file_leak.json",
},
{
description: "test owner path",
opts: options.Options{
OwnerPath: "../test_data/test_repos/",
Report: "../test_data/test_local_owner_aws_leak.json.got",
ReportFormat: "json",
},
wantPath: "../test_data/test_local_owner_aws_leak.json",
},
{
description: "test entropy",
opts: options.Options{
RepoPath: "../test_data/test_repos/test_repo_1",
Report: "../test_data/test_entropy.json.got",
Config: "../test_data/test_configs/entropy.toml",
ReportFormat: "json",
},
wantPath: "../test_data/test_entropy.json",
},
{
description: "test entropy and regex",
opts: options.Options{
RepoPath: "../test_data/test_repos/test_repo_1",
Report: "../test_data/test_regex_entropy.json.got",
Config: "../test_data/test_configs/regex_entropy.toml",
ReportFormat: "json",
},
wantPath: "../test_data/test_regex_entropy.json",
},
{
description: "test local repo four entropy alternative config",
opts: options.Options{
RepoPath: "../test_data/test_repos/test_repo_4",
Report: "../test_data/test_local_repo_four_alt_config_entropy.json.got",
RepoConfig: true,
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_four_alt_config_entropy.json",
},
{
description: "test local repo four entropy alternative config",
opts: options.Options{
RepoPath: "../test_data/test_repos/test_repo_1",
Report: "../test_data/test_regex_whitelist.json.got",
Config: "../test_data/test_configs/aws_key_aws_whitelisted.toml",
ReportFormat: "json",
},
wantEmpty: true,
},
}
for _, test := range tests {
fmt.Println(test.description)
cfg, err := config.NewConfig(test.opts)
if err != nil {
t.Error(err)
}
m, err := manager.NewManager(test.opts, cfg)
if err != nil {
t.Error(err)
}
err = Run(m)
if test.wantErr != nil {
if err == nil {
t.Errorf("did not receive wantErr: %v", test.wantErr)
}
if err.Error() != test.wantErr.Error() {
t.Errorf("wantErr does not equal err received: %v", err.Error())
}
continue
}
err = m.Report()
if test.wantEmpty {
if len(m.GetLeaks()) != 0 {
t.Errorf("wanted no leaks but got some instead: %+v", m.GetLeaks())
}
continue
}
if test.wantPath != "" {
err := fileCheck(test.wantPath, test.opts.Report)
if err != nil {
t.Error(err)
}
}
}
}
func TestAuditUncommited(t *testing.T) {
moveDotGit("dotGit", ".git")
defer moveDotGit(".git", "dotGit")
tests := []struct {
description string
opts options.Options
wantPath string
wantErr error
emptyRepo bool
wantEmpty bool
fileToChange string
addition string
}{
{
description: "test audit local one leak",
opts: options.Options{
RepoPath: "../test_data/test_repos/test_repo_1",
Report: "../test_data/test_local_repo_one_aws_leak_uncommitted.json.got",
Uncommited: true,
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_one_aws_leak_uncommitted.json",
fileToChange: "server.test.py",
addition: " aws_access_key_id='AKIAIO5FODNN7DXAMPLE'\n\n",
},
{
description: "test audit local no leak",
opts: options.Options{
RepoPath: "../test_data/test_repos/test_repo_1",
Uncommited: true,
ReportFormat: "json",
},
wantEmpty: true,
fileToChange: "server.test.py",
addition: "nothing bad",
},
}
for _, test := range tests {
fmt.Println(test.description)
old, err := ioutil.ReadFile(fmt.Sprintf("%s/%s", test.opts.RepoPath, test.fileToChange))
if err != nil {
t.Error(err)
}
altered, err := os.OpenFile(fmt.Sprintf("%s/%s", test.opts.RepoPath, test.fileToChange),
os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
t.Error(err)
}
_, err = altered.WriteString(test.addition)
if err != nil {
t.Error(err)
}
cfg, err := config.NewConfig(test.opts)
if err != nil {
t.Error(err)
}
m, err := manager.NewManager(test.opts, cfg)
if err != nil {
t.Error(err)
}
if err := Run(m); err != nil {
t.Error(err)
}
if err := m.Report(); err != nil {
t.Error(err)
}
err = ioutil.WriteFile(fmt.Sprintf("%s/%s", test.opts.RepoPath, test.fileToChange), old, 0)
if err != nil {
t.Error(err)
}
if test.wantEmpty {
continue
}
if test.wantPath != "" {
err := fileCheck(test.wantPath, test.opts.Report)
if err != nil {
t.Error(err)
}
}
}
}
func fileCheck(wantPath, gotPath string) error {
want, err := ioutil.ReadFile(wantPath)
if err != nil {
return err
}
got, err := ioutil.ReadFile(gotPath)
if err != nil {
return err
}
if strings.Trim(string(want), "\n") != strings.Trim(string(got), "\n") {
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(string(want), string(got), false)
return fmt.Errorf("does not equal: %s", dmp.DiffPrettyText(diffs))
}
if err := os.Remove(gotPath); err != nil {
return err
}
return nil
}
func moveDotGit(from, to string) error {
repoDirs, err := ioutil.ReadDir("../test_data/test_repos")
if err != nil {
return err
}
for _, dir := range repoDirs {
if !dir.IsDir() {
continue
}
err = os.Rename(fmt.Sprintf("%s/%s/%s", testRepoBase, dir.Name(), from),
fmt.Sprintf("%s/%s/%s", testRepoBase, dir.Name(), to))
if err != nil {
return err
}
}
return nil
}
-314
View File
@@ -1,314 +0,0 @@
package audit
import (
"bytes"
"crypto/md5"
"fmt"
"io"
"os"
"path"
"path/filepath"
"sync"
"time"
"github.com/zricethezav/gitleaks/config"
"github.com/zricethezav/gitleaks/manager"
"github.com/BurntSushi/toml"
"github.com/sergi/go-diff/diffmatchpatch"
log "github.com/sirupsen/logrus"
"gopkg.in/src-d/go-billy.v4"
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing"
"gopkg.in/src-d/go-git.v4/plumbing/object"
"gopkg.in/src-d/go-git.v4/plumbing/storer"
"gopkg.in/src-d/go-git.v4/storage/memory"
)
// Repo wraps a *git.Repository object in addition to a manager object and the name of the repo.
// Commits are inspected from the *git.Repository object. If a commit is found then we send it
// via the manager LeakChan where the manager receives and keeps track of all leaks.
type Repo struct {
*git.Repository
// config is used when the --repo-config option is set.
// This allows users to load up configs specific to their repos.
// Imagine the scenario where you are doing an audit of a large organization
// and you want certain repos to look for specific rules. If those specific repos
// have a gitleaks.toml or .gitleaks.toml config then those configs will be used specifically
// for those repo audits.
config config.Config
Name string
Manager *manager.Manager
}
// NewRepo initializes and returns a Repo struct.
func NewRepo(m *manager.Manager) *Repo {
return &Repo{
Manager: m,
config: m.Config,
}
}
// Clone will clone a repo and return a Repo struct which contains a go-git repo. The clone method
// is determined by the clone options set in Manager.metadata.cloneOptions
func (repo *Repo) Clone(cloneOption *git.CloneOptions) error {
var (
repository *git.Repository
err error
)
if cloneOption == nil {
cloneOption = repo.Manager.CloneOptions
}
log.Infof("cloning... %s", cloneOption.URL)
start := time.Now()
if repo.Manager.CloneDir != "" {
clonePath := fmt.Sprintf("%s/%x", repo.Manager.CloneDir, md5.Sum([]byte(time.Now().String())))
repository, err = git.PlainClone(clonePath, false, cloneOption)
} else {
repository, err = git.Clone(memory.NewStorage(), nil, cloneOption)
}
if err != nil {
return err
}
repo.Name = filepath.Base(repo.Manager.Opts.Repo)
repo.Repository = repository
repo.Manager.RecordTime(manager.CloneTime(howLong(start)))
return nil
}
// AuditUncommitted will do a `git diff` and scan changed files that are being tracked. This is useful functionality
// for a pre-commit hook so you can make sure your code does not have any leaks before committing.
func (repo *Repo) AuditUncommitted() error {
auditTimeStart := time.Now()
r, err := repo.Head()
if err != nil {
return err
}
c, err := repo.CommitObject(r.Hash())
if err != nil {
return err
}
prevTree, err := c.Tree()
if err != nil {
return err
}
wt, err := repo.Worktree()
if err != nil {
return err
}
status, err := wt.Status()
for fn, state := range status {
var (
prevFileContents string
currFileContents string
filename string
)
if state.Staging != git.Untracked {
if state.Staging == git.Deleted {
// file in staging has been deleted, aka it is not on the filesystem
// so the contents of the file are ""
currFileContents = ""
} else {
workTreeBuf := bytes.NewBuffer(nil)
workTreeFile, err := wt.Filesystem.Open(fn)
if err != nil {
continue
}
if _, err := io.Copy(workTreeBuf, workTreeFile); err != nil {
return err
}
currFileContents = workTreeBuf.String()
filename = workTreeFile.Name()
}
// get files at HEAD state
prevFile, err := prevTree.File(fn)
if err != nil {
prevFileContents = ""
} else {
prevFileContents, err = prevFile.Contents()
if err != nil {
return err
}
if filename == "" {
filename = prevFile.Name
}
}
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(prevFileContents, currFileContents, false)
var diffContents string
for _, d := range diffs {
switch d.Type {
case diffmatchpatch.DiffInsert:
diffContents += fmt.Sprintf("%s\n", d.Text)
case diffmatchpatch.DiffDelete:
diffContents += fmt.Sprintf("%s\n", d.Text)
}
}
InspectString(diffContents, c, repo, filename)
}
}
if err != nil {
return err
}
repo.Manager.RecordTime(manager.AuditTime(howLong(auditTimeStart)))
return nil
}
// Audit is responsible for scanning the entire history (default behavior) of a
// git repo. Options that can change the behavior of this function include: --commit, --depth, --branch.
// See options/options.go for an explanation on these options.
func (repo *Repo) Audit() error {
if repo.Repository == nil {
return fmt.Errorf("%s repo is empty", repo.Name)
}
// load up alternative config if possible, if not use manager's config
if repo.Manager.Opts.RepoConfig {
cfg, err := repo.loadRepoConfig()
if err != nil {
return err
}
repo.config = cfg
}
auditTimeStart := time.Now()
// audit single Commit
if repo.Manager.Opts.Commit != "" {
h := plumbing.NewHash(repo.Manager.Opts.Commit)
c, err := repo.CommitObject(h)
if err != nil {
return err
}
err = inspectCommit(c, repo)
if err != nil {
return err
}
return nil
}
logOpts, err := getLogOptions(repo)
if err != nil {
return err
}
cIter, err := repo.Log(logOpts)
if err != nil {
return err
}
cc := 0
semaphore := make(chan bool, howManyThreads(repo.Manager.Opts.Threads))
wg := sync.WaitGroup{}
err = cIter.ForEach(func(c *object.Commit) error {
if c == nil {
return storer.ErrStop
}
if len(c.ParentHashes) == 0 {
cc++
err = inspectCommit(c, repo)
if err != nil {
return err
}
return nil
}
if isCommitWhiteListed(c.Hash.String(), repo.config.Whitelist.Commits) {
return nil
}
cc++
err = c.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
}
}()
start := time.Now()
patch, err := c.Patch(parent)
if err != nil {
return fmt.Errorf("could not generate patch")
}
repo.Manager.RecordTime(manager.PatchTime(howLong(start)))
wg.Add(1)
semaphore <- true
go func(c *object.Commit, patch *object.Patch) {
defer func() {
<-semaphore
wg.Done()
}()
inspectPatch(patch, c, repo)
}(c, patch)
return nil
})
return nil
})
wg.Wait()
repo.Manager.RecordTime(manager.AuditTime(howLong(auditTimeStart)))
repo.Manager.IncrementCommits(cc)
return nil
}
// Open opens a local repo either from repo-path or $PWD
func (repo *Repo) Open() error {
if repo.Manager.Opts.RepoPath != "" {
// open git repo from repo path
repository, err := git.PlainOpen(repo.Manager.Opts.RepoPath)
if err != nil {
return err
}
repo.Repository = repository
} else {
// open git repo from PWD
dir, err := os.Getwd()
if err != nil {
return err
}
repository, err := git.PlainOpen(dir)
if err != nil {
return err
}
repo.Repository = repository
repo.Name = path.Base(dir)
}
return nil
}
func (repo *Repo) loadRepoConfig() (config.Config, error) {
wt, err := repo.Repository.Worktree()
if err != nil {
return config.Config{}, err
}
var f billy.File
f, _ = wt.Filesystem.Open(".gitleaks.toml")
if f == nil {
f, err = wt.Filesystem.Open("gitleaks.toml")
if err != nil {
return config.Config{}, fmt.Errorf("problem loading repo config: %v", err)
}
}
defer f.Close()
var tomlLoader config.TomlLoader
_, err = toml.DecodeReader(f, &tomlLoader)
return tomlLoader.Parse()
}
-383
View File
@@ -1,383 +0,0 @@
package audit
import (
"fmt"
"math"
"regexp"
"runtime"
"strings"
"time"
"github.com/zricethezav/gitleaks/config"
"github.com/zricethezav/gitleaks/manager"
log "github.com/sirupsen/logrus"
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing"
fdiff "gopkg.in/src-d/go-git.v4/plumbing/format/diff"
"gopkg.in/src-d/go-git.v4/plumbing/object"
)
const maxLineLen = 200
// Inspect patch accepts a patch, commit, and repo. If the patches contains files that are
// binary, then gitleaks will skip auditing that file OR if a file is matched on
// whitelisted files set in the configuration. If a global rule for files is defined and a filename
// matches said global rule, then a laek is sent to the manager.
// After that, file chunks are created which are then inspected by InspectString()
func inspectPatch(patch *object.Patch, c *object.Commit, repo *Repo) {
for _, f := range patch.FilePatches() {
if f.IsBinary() {
continue
}
if fileMatched(getFileName(f), repo.config.Whitelist.File) {
log.Debugf("whitelisted file found, skipping audit of file: %s", getFileName(f))
continue
}
if fileMatched(getFileName(f), repo.config.FileRegex) {
repo.Manager.SendLeaks(manager.Leak{
Line: "N/A",
Offender: getFileName(f),
Commit: c.Hash.String(),
Repo: repo.Name,
Rule: "file regex matched" + repo.config.FileRegex.String(),
Author: c.Author.Name,
Email: c.Author.Email,
Date: c.Author.When,
File: getFileName(f),
})
}
for _, chunk := range f.Chunks() {
if chunk.Type() == fdiff.Delete || chunk.Type() == fdiff.Add {
InspectString(chunk.Content(), c, repo, getFileName(f))
}
}
}
}
// getFileName accepts a file patch and returns the filename
func getFileName(f fdiff.FilePatch) string {
fn := "???"
from, to := f.Files()
if from != nil {
return from.Path()
} else if to != nil {
return to.Path()
}
return fn
}
// getShannonEntropy https://en.wiktionary.org/wiki/Shannon_entropy
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
}
// aws_access_key_id='AKIAIO5FODNN7EXAMPLE',
// trippedEntropy checks if a given line falls in between entropy ranges supplied
// by a custom gitleaks configuration. Gitleaks do not check entropy by default.
func trippedEntropy(line string, rule config.Rule) bool {
for _, e := range rule.Entropy {
entropy := shannonEntropy(line)
if entropy > e.P1 && entropy < e.P2 {
return true
}
}
return false
}
func ruleContainRegex(rule config.Rule) bool {
if rule.Regex == nil {
return false
}
if rule.Regex.String() == "" {
return false
}
return true
}
// InspectString accepts a string, commit object, repo, and filename. This function iterates over
// all the rules set by the gitleaks config. If the rule contains entropy checks then entropy will be checked first.
// Next, if the rule contains a regular expression then that will be checked.
func InspectString(content string, c *object.Commit, repo *Repo, filename string) {
for _, rule := range repo.config.Rules {
// check entropy
if len(rule.Entropy) != 0 {
// an optimization would be to switch the regex from FindAllIndex to FindString
// since we are iterating on the lines if entropy rules exist...
for _, line := range strings.Split(content, "\n") {
entropyTripped := trippedEntropy(line, rule)
if entropyTripped && !ruleContainRegex(rule) {
_line := line
if len(_line) > maxLineLen {
_line = line[0 : maxLineLen-1]
}
repo.Manager.SendLeaks(manager.Leak{
Line: _line,
Offender: fmt.Sprintf("Entropy range %+v", rule.Entropy),
Commit: c.Hash.String(),
Repo: repo.Name,
Message: c.Message,
Rule: rule.Description,
Author: c.Author.Name,
Email: c.Author.Email,
Date: c.Author.When,
Tags: strings.Join(rule.Tags, ", "),
File: filename,
})
} else if entropyTripped {
// entropy has been tripped which means if there is a regex specified in the same
// rule, we need to inspect the line for a regex match. In otherwords, the current rule has
// both entropy and regex set which work in combination. This helps narrow down false positives
// on searches for generic passwords in code.
match := rule.Regex.FindString(line)
// check if any rules are whitelisting this leak
if len(rule.Whitelist) != 0 {
for _, wl := range rule.Whitelist {
if fileMatched(filename, wl.File) {
// if matched, go to next rule
goto NEXTLINE
}
if wl.Regex.FindString(line) != "" {
goto NEXTLINE
}
}
}
if match != "" {
// both the regex and entropy in this rule have been tripped which means this line
// contains a leak
repo.Manager.SendLeaks(manager.Leak{
Line: line,
Offender: match,
Commit: c.Hash.String(),
Message: c.Message,
Repo: repo.Name,
Rule: rule.Description,
Author: c.Author.Name,
Email: c.Author.Email,
Date: c.Author.When,
Tags: strings.Join(rule.Tags, ", "),
File: filename,
})
}
}
NEXTLINE:
}
return
}
if rule.Regex.String() == "" {
continue
}
start := time.Now()
locs := rule.Regex.FindAllIndex([]byte(content), -1)
if len(locs) != 0 {
// check if any rules are whitelisting this leak
if len(rule.Whitelist) != 0 {
for _, wl := range rule.Whitelist {
if fileMatched(filename, wl.File) {
// if matched, go to next rule
goto NEXT
}
}
}
for _, loc := range locs {
start := loc[0]
end := loc[1]
for start != 0 && content[start] != '\n' {
start = start - 1
}
if start != 0 {
// skip newline
start = start + 1
}
for end < len(content)-1 && content[end] != '\n' {
end = end + 1
}
offender := content[loc[0]:loc[1]]
line := content[start:end]
if len(rule.Whitelist) != 0 {
for _, wl := range rule.Whitelist {
if wl.Regex.FindString(line) != "" {
goto NEXT
}
}
}
if repo.Manager.Opts.Redact {
line = strings.ReplaceAll(line, offender, "REDACTED")
offender = "REDACTED"
}
repo.Manager.SendLeaks(manager.Leak{
Line: line,
Offender: offender,
Commit: c.Hash.String(),
Message: c.Message,
Repo: repo.Name,
Rule: rule.Description,
Author: c.Author.Name,
Email: c.Author.Email,
Date: c.Author.When,
Tags: strings.Join(rule.Tags, ", "),
File: filename,
})
}
}
repo.Manager.RecordTime(manager.RegexTime{
Time: time.Now().Sub(start).Nanoseconds(),
Regex: rule.Regex.String(),
})
NEXT:
}
}
// inspectCommit accepts a commit object and a repo. This function is only called when the --commit=
// option has been set. That option tells gitleaks to look only at a single commit and check the contents
// of said commit. Similar to inspectPatch(), if the files contained in the commit are a binaries or if they are
// whitelisted then those files will be skipped.
func inspectCommit(c *object.Commit, repo *Repo) error {
fIter, err := c.Files()
if err != nil {
return err
}
err = fIter.ForEach(func(f *object.File) error {
bin, err := f.IsBinary()
if bin {
return nil
} else if err != nil {
return err
}
if fileMatched(f, repo.config.Whitelist.File) {
log.Debugf("whitelisted file found, skipping audit of file: %s", f.Name)
return nil
}
if fileMatched(f.Name, repo.config.FileRegex) {
repo.Manager.SendLeaks(manager.Leak{
Line: "N/A",
Offender: f.Name,
Commit: c.Hash.String(),
Repo: repo.Name,
Rule: "file regex matched" + repo.config.FileRegex.String(),
Author: c.Author.Name,
Email: c.Author.Email,
Date: c.Author.When,
File: f.Name,
})
}
content, err := f.Contents()
if err != nil {
return err
}
InspectString(content, c, repo, f.Name)
return nil
})
return err
}
// howManyThreads will return a number 1-GOMAXPROCS which is the number
// of goroutines that will spawn during gitleaks execution
func howManyThreads(threads int) int {
maxThreads := runtime.GOMAXPROCS(0)
if threads == 0 {
return 1
} else if threads > maxThreads {
log.Warnf("%d threads set too high, setting to system max, %d", threads, maxThreads)
return maxThreads
}
return threads
}
func isCommitWhiteListed(commitHash string, whitelistedCommits []string) bool {
for _, hash := range whitelistedCommits {
if commitHash == hash {
return true
}
}
return false
}
func fileMatched(f interface{}, re *regexp.Regexp) bool {
if re == nil {
return false
}
switch f.(type) {
case nil:
return false
case string:
if re.FindString(f.(string)) != "" {
return true
}
return false
case *object.File:
if re.FindString(f.(*object.File).Name) != "" {
return true
}
return false
}
return false
}
// 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.
func getLogOptions(repo *Repo) (*git.LogOptions, error) {
if repo.Manager.Opts.Branch != "" {
var logOpts git.LogOptions
refs, err := repo.Storer.IterReferences()
if err != nil {
return nil, err
}
err = refs.ForEach(func(ref *plumbing.Reference) error {
if ref.Name().IsTag() {
return nil
}
// check heads first
if ref.Name().String() == "refs/heads/"+repo.Manager.Opts.Branch {
logOpts = git.LogOptions{
From: ref.Hash(),
}
return nil
} else if ref.Name().String() == "refs/remotes/origin/"+repo.Manager.Opts.Branch {
logOpts = git.LogOptions{
From: ref.Hash(),
}
return nil
}
return nil
})
if logOpts.From.IsZero() {
return nil, fmt.Errorf("could not find branch %s", repo.Manager.Opts.Branch)
}
return &logOpts, nil
}
return &git.LogOptions{All: true}, nil
}
// howLong accepts a time.Time object which is subtracted from time.Now() and
// converted to nanoseconds which is returned
func howLong(t time.Time) int64 {
return time.Now().Sub(t).Nanoseconds()
}
+56
View File
@@ -0,0 +1,56 @@
package config
import (
"regexp"
)
// 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(".git")
if err != nil {
return err
}
a.Paths = append(a.Paths, re)
return nil
}
+208 -120
View File
@@ -2,82 +2,65 @@ package config
import (
"fmt"
"path"
"regexp"
"strconv"
"strings"
"github.com/zricethezav/gitleaks/options"
"github.com/zricethezav/gitleaks/v7/options"
"github.com/BurntSushi/toml"
"github.com/go-git/go-git/v5"
log "github.com/sirupsen/logrus"
)
// Whitelist is struct containing items that if encountered will whitelist
// a commit/line of code that would be considered a leak.
type Whitelist struct {
Description string
Regex *regexp.Regexp
File *regexp.Regexp
}
// entropy represents an entropy range
type entropy struct {
P1, P2 float64
}
// 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 audit. Each rule will be checked. If a regex match is found AND
// that match is not whitelisted (globally or locally), then a leak will be appended
// to the final audit report.
type Rule struct {
Description string
Regex *regexp.Regexp
Tags []string
Whitelist []Whitelist
Entropy []entropy
}
// Config is a composite struct of Rules and Whitelists
// Each Rule contains a description, regular expression, tags, and whitelists if available
// Config is a composite struct of Rules and Allowlists
// Each Rule contains a description, regular expression, tags, and allowlists if available
type Config struct {
FileRegex *regexp.Regexp
Message *regexp.Regexp
Rules []Rule
Whitelist struct {
Description string
Commits []string
File *regexp.Regexp
}
Allowlist AllowList
}
// Entropy represents an entropy range
type Entropy struct {
Min float64
Max float64
Group int
}
// 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 {
Description string
Regexes []string
Commits []string
Files []string
Paths []string
Repos []string
}
// TomlLoader gets loaded with the values from a gitleaks toml config
// see the config in config/defaults.go for an example. TomlLoader is used
// to generate Config values (compiling regexes, etc).
type TomlLoader struct {
Global struct {
File string
Message string
}
Whitelist struct {
Description string
Commits []string
File string
}
Rules []struct {
AllowList TomlAllowList
Rules []struct {
Description string
Regex string
File string
Path string
ReportGroup int
Tags []string
Entropies []string
Whitelist []struct {
Description string
Regex string
File string
Entropies []struct {
Min string
Max string
Group string
}
AllowList TomlAllowList
}
}
// NewConfig will create a new config struct which contains
// rules on how gitleaks will proceed with its audit.
// rules on how gitleaks will proceed with its scan.
// If no options are passed via cli then NewConfig will return
// a default config which can be seen in config.go
func NewConfig(options options.Options) (Config, error) {
@@ -85,8 +68,10 @@ func NewConfig(options options.Options) (Config, error) {
tomlLoader := TomlLoader{}
var err error
if options.Config != "" {
_, err = toml.DecodeFile(options.Config, &tomlLoader)
if options.ConfigPath != "" {
_, err = toml.DecodeFile(options.ConfigPath, &tomlLoader)
// append a allowlist rule for allowlisting the config
tomlLoader.AllowList.Files = append(tomlLoader.AllowList.Files, path.Base(options.ConfigPath))
} else {
_, err = toml.Decode(DefaultConfig, &tomlLoader)
}
@@ -103,98 +88,201 @@ func NewConfig(options options.Options) (Config, error) {
}
// Parse will parse the values set in a TomlLoader and use those values
// to create compiled regular expressions and rules used in audits
// to create compiled regular expressions and rules used in scans
func (tomlLoader TomlLoader) Parse() (Config, error) {
var cfg Config
for _, rule := range tomlLoader.Rules {
// check and make sure the rule is valid
if rule.Regex == "" && rule.Path == "" && rule.File == "" && len(rule.Entropies) == 0 {
log.Warnf("Rule %s does not define any actionable data", rule.Description)
continue
}
re, err := regexp.Compile(rule.Regex)
if err != nil {
return cfg, fmt.Errorf("problem loading config: %v", err)
}
// rule specific whitelists
var whitelists []Whitelist
for _, wl := range rule.Whitelist {
re, err := regexp.Compile(wl.Regex)
if err != nil {
return cfg, fmt.Errorf("problem loading config: %v", err)
}
fileRe, err := regexp.Compile(wl.File)
if err != nil {
return cfg, fmt.Errorf("problem loading config: %v", err)
}
whitelists = append(whitelists, Whitelist{
Description: wl.Description,
File: fileRe,
Regex: re,
})
}
entropies, err := getEntropy(rule.Entropies)
fileNameRe, err := regexp.Compile(rule.File)
if err != nil {
return cfg, err
return cfg, fmt.Errorf("problem loading config: %v", err)
}
filePathRe, err := regexp.Compile(rule.Path)
if err != nil {
return cfg, fmt.Errorf("problem loading config: %v", err)
}
cfg.Rules = append(cfg.Rules, Rule{
// rule specific allowlists
var allowList AllowList
allowList.Description = rule.AllowList.Description
// rule specific regexes
for _, re := range rule.AllowList.Regexes {
allowListedRegex, err := regexp.Compile(re)
if err != nil {
return cfg, fmt.Errorf("problem loading config: %v", err)
}
allowList.Regexes = append(allowList.Regexes, allowListedRegex)
}
// rule specific filenames
for _, re := range rule.AllowList.Files {
allowListedRegex, err := regexp.Compile(re)
if err != nil {
return cfg, fmt.Errorf("problem loading config: %v", err)
}
allowList.Files = append(allowList.Files, allowListedRegex)
}
// rule specific paths
for _, re := range rule.AllowList.Paths {
allowListedRegex, err := regexp.Compile(re)
if err != nil {
return cfg, fmt.Errorf("problem loading config: %v", err)
}
allowList.Paths = append(allowList.Paths, allowListedRegex)
}
// rule specific commits
allowList.Commits = rule.AllowList.Commits
var entropies []Entropy
for _, e := range rule.Entropies {
min, err := strconv.ParseFloat(e.Min, 64)
if err != nil {
return cfg, err
}
max, err := strconv.ParseFloat(e.Max, 64)
if err != nil {
return cfg, err
}
if e.Group == "" {
e.Group = "0"
}
group, err := strconv.ParseInt(e.Group, 10, 64)
if err != nil {
return cfg, err
} else if int(group) >= len(re.SubexpNames()) {
return cfg, fmt.Errorf("problem loading config: group cannot be higher than number of groups in regexp")
} else if group < 0 {
return cfg, fmt.Errorf("problem loading config: group cannot be lower than 0")
} else if min > 8.0 || min < 0.0 || max > 8.0 || max < 0.0 {
return cfg, fmt.Errorf("problem loading config: invalid entropy ranges, must be within 0.0-8.0")
} else if min > max {
return cfg, fmt.Errorf("problem loading config: entropy Min value cannot be higher than Max value")
}
entropies = append(entropies, Entropy{Min: min, Max: max, Group: int(group)})
}
r := Rule{
Description: rule.Description,
Regex: re,
File: fileNameRe,
Path: filePathRe,
ReportGroup: rule.ReportGroup,
Tags: rule.Tags,
Whitelist: whitelists,
Entropy: entropies,
})
AllowList: allowList,
Entropies: entropies,
}
cfg.Rules = append(cfg.Rules, r)
}
// global leaks
if tomlLoader.Global.File != "" {
re, err := regexp.Compile(tomlLoader.Global.File)
// global regex allowLists
for _, allowListRegex := range tomlLoader.AllowList.Regexes {
re, err := regexp.Compile(allowListRegex)
if err != nil {
return cfg, fmt.Errorf("problem loading config: %v", err)
}
cfg.FileRegex = re
}
if tomlLoader.Global.Message != "" {
re, err := regexp.Compile(tomlLoader.Global.Message)
if err != nil {
return cfg, fmt.Errorf("problem loading config: %v", err)
}
cfg.Message = re
cfg.Allowlist.Regexes = append(cfg.Allowlist.Regexes, re)
}
// global whitelists
if tomlLoader.Whitelist.File != "" {
re, err := regexp.Compile(tomlLoader.Whitelist.File)
// global file name allowLists
for _, allowListFileName := range tomlLoader.AllowList.Files {
re, err := regexp.Compile(allowListFileName)
if err != nil {
return cfg, fmt.Errorf("problem loading config: %v", err)
}
cfg.Whitelist.File = re
cfg.Allowlist.Files = append(cfg.Allowlist.Files, re)
}
cfg.Whitelist.Commits = tomlLoader.Whitelist.Commits
cfg.Whitelist.Description = tomlLoader.Whitelist.Description
// global file path allowLists
for _, allowListFilePath := range tomlLoader.AllowList.Paths {
re, err := regexp.Compile(allowListFilePath)
if err != nil {
return cfg, fmt.Errorf("problem loading config: %v", err)
}
cfg.Allowlist.Paths = append(cfg.Allowlist.Paths, re)
}
// global repo allowLists
for _, allowListRepo := range tomlLoader.AllowList.Repos {
re, err := regexp.Compile(allowListRepo)
if err != nil {
return cfg, fmt.Errorf("problem loading config: %v", err)
}
cfg.Allowlist.Repos = append(cfg.Allowlist.Repos, re)
}
cfg.Allowlist.Commits = tomlLoader.AllowList.Commits
cfg.Allowlist.Description = tomlLoader.AllowList.Description
return cfg, nil
}
// getEntropy
func getEntropy(entropyStr []string) ([]entropy, error) {
var ranges []entropy
for _, span := range entropyStr {
split := strings.Split(span, "-")
v1, err := strconv.ParseFloat(split[0], 64)
if err != nil {
return nil, err
}
v2, err := strconv.ParseFloat(split[1], 64)
if err != nil {
return nil, err
}
if v1 > v2 {
return nil, fmt.Errorf("entropy range must be ascending")
}
r := entropy{P1: v1, P2: v2}
if r.P1 > 8.0 || r.P1 < 0.0 || r.P2 > 8.0 || r.P2 < 0.0 {
return nil, fmt.Errorf("invalid entropy ranges, must be within 0.0-8.0")
}
ranges = append(ranges, r)
// LoadRepoConfig accepts a repo and config path related to the target repo's root.
func LoadRepoConfig(repo *git.Repository, repoConfig string) (Config, error) {
gitRepoConfig, err := repo.Config()
if err != nil {
return Config{}, err
}
return ranges, nil
if !gitRepoConfig.Core.IsBare {
wt, err := repo.Worktree()
if err != nil {
return Config{}, err
}
_, err = wt.Filesystem.Stat(repoConfig)
if err != nil {
return Config{}, err
}
r, err := wt.Filesystem.Open(repoConfig)
if err != nil {
return Config{}, err
}
var tomlLoader TomlLoader
_, err = toml.DecodeReader(r, &tomlLoader)
if err != nil {
return Config{}, err
}
return tomlLoader.Parse()
}
log.Debug("attempting to load repo config from bare worktree, this may use an old config")
ref, err := repo.Head()
if err != nil {
return Config{}, err
}
c, err := repo.CommitObject(ref.Hash())
if err != nil {
return Config{}, err
}
f, err := c.File(repoConfig)
if err != nil {
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 tomlLoader.Parse()
}
+124 -27
View File
@@ -2,9 +2,12 @@ package config
import (
"fmt"
"github.com/zricethezav/gitleaks/options"
"io/ioutil"
"os"
"regexp"
"testing"
"github.com/zricethezav/gitleaks/v7/options"
)
func TestParse(t *testing.T) {
@@ -14,7 +17,7 @@ func TestParse(t *testing.T) {
wantErr error
wantFileRegex *regexp.Regexp
wantMessages *regexp.Regexp
wantWhitelist Whitelist
wantAllowlist AllowList
}{
{
description: "default config",
@@ -23,83 +26,97 @@ func TestParse(t *testing.T) {
{
description: "test successful load",
opts: options.Options{
Config: "../test_data/test_configs/aws_key.toml",
ConfigPath: "../test_data/test_configs/aws_key.toml",
},
},
{
description: "test bad toml",
opts: options.Options{
Config: "../test_data/test_configs/bad_aws_key.toml",
ConfigPath: "../test_data/test_configs/bad_aws_key.toml",
},
wantErr: fmt.Errorf("Near line 7 (last key parsed 'rules.description'): expected value but found \"AWS\" instead"),
},
{
description: "test bad regex",
opts: options.Options{
Config: "../test_data/test_configs/bad_regex_aws_key.toml",
ConfigPath: "../test_data/test_configs/bad_regex_aws_key.toml",
},
wantErr: fmt.Errorf("problem loading config: error parsing regexp: invalid nested repetition operator: `???`"),
},
{
description: "test bad global whitelist file regex",
description: "test bad global allowlist file regex",
opts: options.Options{
Config: "../test_data/test_configs/bad_aws_key_global_whitelist_file.toml",
ConfigPath: "../test_data/test_configs/bad_aws_key_global_allowlist_file.toml",
},
wantErr: fmt.Errorf("problem loading config: error parsing regexp: missing argument to repetition operator: `??`"),
},
{
description: "test bad global file regex",
opts: options.Options{
Config: "../test_data/test_configs/bad_aws_key_file_regex.toml",
},
wantErr: fmt.Errorf("problem loading config: error parsing regexp: missing argument to repetition operator: `??`"),
},
{
description: "test bad global message regex",
opts: options.Options{
Config: "../test_data/test_configs/bad_aws_key_message_regex.toml",
ConfigPath: "../test_data/test_configs/bad_aws_key_file_regex.toml",
},
wantErr: fmt.Errorf("problem loading config: error parsing regexp: missing argument to repetition operator: `??`"),
},
{
description: "test successful load big ol thing",
opts: options.Options{
Config: "../test_data/test_configs/large.toml",
ConfigPath: "../test_data/test_configs/large.toml",
},
},
{
description: "test load entropy",
opts: options.Options{
Config: "../test_data/test_configs/entropy.toml",
ConfigPath: "../test_data/test_configs/entropy.toml",
},
},
{
description: "test entropy bad range",
opts: options.Options{
Config: "../test_data/test_configs/bad_entropy_1.toml",
ConfigPath: "../test_data/test_configs/bad_entropy_1.toml",
},
wantErr: fmt.Errorf("entropy range must be ascending"),
wantErr: fmt.Errorf("problem loading config: entropy Min value cannot be higher than Max value"),
},
{
description: "test entropy value p2",
description: "test entropy value max",
opts: options.Options{
Config: "../test_data/test_configs/bad_entropy_2.toml",
ConfigPath: "../test_data/test_configs/bad_entropy_2.toml",
},
wantErr: fmt.Errorf("strconv.ParseFloat: parsing \"x\": invalid syntax"),
},
{
description: "test entropy value p1",
description: "test entropy value min",
opts: options.Options{
Config: "../test_data/test_configs/bad_entropy_3.toml",
ConfigPath: "../test_data/test_configs/bad_entropy_3.toml",
},
wantErr: fmt.Errorf("strconv.ParseFloat: parsing \"x\": invalid syntax"),
},
{
description: "test entropy value p1",
description: "test entropy value group",
opts: options.Options{
Config: "../test_data/test_configs/bad_entropy_4.toml",
ConfigPath: "../test_data/test_configs/bad_entropy_4.toml",
},
wantErr: fmt.Errorf("invalid entropy ranges, must be within 0.0-8.0"),
wantErr: fmt.Errorf("strconv.ParseInt: parsing \"x\": invalid syntax"),
},
{
description: "test entropy value group",
opts: options.Options{
ConfigPath: "../test_data/test_configs/bad_entropy_5.toml",
},
wantErr: fmt.Errorf("problem loading config: group cannot be lower than 0"),
},
{
description: "test entropy value group",
opts: options.Options{
ConfigPath: "../test_data/test_configs/bad_entropy_6.toml",
},
wantErr: fmt.Errorf("problem loading config: group cannot be higher than number of groups in regexp"),
},
{
description: "test entropy range limits",
opts: options.Options{
ConfigPath: "../test_data/test_configs/bad_entropy_7.toml",
},
wantErr: fmt.Errorf("problem loading config: invalid entropy ranges, must be within 0.0-8.0"),
},
}
@@ -107,10 +124,90 @@ func TestParse(t *testing.T) {
_, err := NewConfig(test.opts)
if err != nil {
if test.wantErr == nil {
t.Error(err)
t.Error(test.description, err)
} else if test.wantErr.Error() != err.Error() {
t.Errorf("expected err: %s, got %s", test.wantErr, err)
}
}
}
}
// TestParseFields will test that fields are properly parsed from a config. As fields are added, then please
// add tests here.
func TestParseFields(t *testing.T) {
tomlConfig := `
[[rules]]
description = "Some Groups without a reportGroup"
regex = '(.)(.)'
[[rules]]
description = "Some Groups"
regex = '(.)(.)'
reportGroup = 1
`
configPath, err := writeTestConfig(tomlConfig)
defer os.Remove(configPath)
if err != nil {
t.Fatal(err)
}
config, err := NewConfig(options.Options{ConfigPath: configPath})
if err != nil {
t.Fatalf("Couldn't parse config: %v", err)
}
expectedRuleFields := []struct {
Description string
ReportGroup int
}{
{
Description: "Some Groups without a reportGroup",
ReportGroup: 0,
},
{
Description: "Some Groups",
ReportGroup: 1,
},
}
if len(config.Rules) != len(expectedRuleFields) {
t.Fatalf("expected %v rules", len(expectedRuleFields))
}
for _, expected := range expectedRuleFields {
rule, err := findRuleByDescription(config.Rules, expected.Description)
if err != nil {
t.Fatal(err)
}
if rule.ReportGroup != expected.ReportGroup {
t.Errorf("expected the rule with description '%v' to have a ReportGroup of %v", expected.Description, expected.ReportGroup)
}
}
}
func findRuleByDescription(rules []Rule, description string) (*Rule, error) {
for _, rule := range rules {
if rule.Description == description {
return &rule, nil
}
}
return nil, fmt.Errorf("Couldn't find rule with the description: %s", description)
}
func writeTestConfig(toml string) (string, error) {
tmpfile, err := ioutil.TempFile("", "testConfig")
if err != nil {
return "", fmt.Errorf("Couldn't create test config got: %w", err)
}
if _, err := tmpfile.Write([]byte(toml)); err != nil {
return "", fmt.Errorf("Couldn't create test config got: %w", err)
}
if err := tmpfile.Close(); err != nil {
return "", fmt.Errorf("Couldn't create test config got: %w", err)
}
return tmpfile.Name(), nil
}
+53 -22
View File
@@ -7,7 +7,7 @@ const DefaultConfig = `
title = "gitleaks config"
[[rules]]
description = "AWS Manager ID"
description = "AWS Access Key"
regex = '''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
tags = ["key", "AWS"]
@@ -33,27 +33,27 @@ title = "gitleaks config"
[[rules]]
description = "Twitter Secret Key"
regex = '''(?i)twitter(.{0,20})?['\"][0-9a-z]{35,44}['\"]'''
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}['\"]'''
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}['\"]'''
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}['\"]'''
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}['\"]'''
regex = '''(?i)linkedin(.{0,20})?[0-9a-z]{16}'''
tags = ["secret", "LinkedIn"]
[[rules]]
@@ -62,34 +62,33 @@ title = "gitleaks config"
tags = ["key", "Slack"]
[[rules]]
description = "EC"
regex = '''-----BEGIN EC PRIVATE KEY-----'''
tags = ["key", "EC"]
[[rules]]
description = "Generic Credential"
regex = '''(?i)(api_key|apikey|secret)(.{0,20})?['|"][0-9a-zA-Z]{16,45}['|"]'''
tags = ["key", "API", "generic"]
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"]
[[rules]]
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}['"]'''
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}['"]'''
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}['"]'''
regex = '''((?i)(mailgun|mg)(.{0,20})?)?key-[0-9a-z]{32}'''
tags = ["key", "Mailgun"]
[[rules]]
@@ -102,6 +101,11 @@ title = "gitleaks config"
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"]
[[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}'''
@@ -109,7 +113,7 @@ title = "gitleaks config"
[[rules]]
description = "Stripe API key"
regex = '''(?i)stripe(.{0,20})?['\"][sk|rk]_live_[0-9a-zA-Z]{24}'''
regex = '''(?i)stripe(.{0,20})?[sr]k_live_[0-9a-zA-Z]{24}'''
tags = ["key", "Stripe"]
[[rules]]
@@ -124,10 +128,37 @@ title = "gitleaks config"
[[rules]]
description = "Twilio API key"
regex = '''(?i)twilio(.{0,20})?['\"][0-9a-f]{32}['\"]'''
regex = '''(?i)twilio(.{0,20})?SK[0-9a-f]{32}'''
tags = ["key", "twilio"]
[whitelist]
description = "image whitelists"
file = '''(.*?)(jpg|gif|doc|pdf|bin)$'''
[[rules]]
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"]
[[rules]]
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"]
[[rules]]
description = "Shopify private app access token"
regex = '''shppa_[a-fA-F0-9]{32}'''
tags = ["key", "Shopify"]
[allowlist]
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
}
+47 -21
View File
@@ -1,7 +1,7 @@
title = "gitleaks config"
[[rules]]
description = "AWS Manager ID"
description = "AWS Access Key"
regex = '''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
tags = ["key", "AWS"]
@@ -124,46 +124,72 @@ title = "gitleaks config"
[[rules]]
description = "Env Var"
regex = '''(?i)(api_key|apikey|secret|key|api|password|pw|host)=[0-9a-zA-Z-_{}]{4,120}'''
regex = '''(?i)(apikey|secret|key|api|password|pass|pw|host)=[0-9a-zA-Z-_.{}]{4,120}'''
[[rules]]
description = "Port"
regex = '''(?i)port(.{0,4})?[0-9]{1,10}'''
[rules.allowlist]
regexes = ['''(?i)port ''']
description = "ignore export "
[[rules]]
description = "Email"
regex = '''[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}'''
tags = ["email"]
[rules.allowlist]
files = ['''(?i)bashrc''']
description = "ignore bashrc emails"
[[rules]]
description = "Generic Credential"
regex = '''(?i)(dbpasswd|dbuser|dbname|dbhost|api_key|apikey|secret|key|api|password|user|guid|hostname|pw|auth)(.{0,20})?['|"][0-9a-zA-Z-_!{}/=]{4,120}['|"]'''
regex = '''(?i)(dbpasswd|dbuser|dbname|dbhost|api_key|apikey|secret|key|api|password|user|guid|hostname|pw|auth)(.{0,20})?['|"]([0-9a-zA-Z-_\/+!{}/=]{4,120})['|"]'''
tags = ["key", "API", "generic"]
# ignore leaks with specific identifiers like slack and aws
[rules.allowlist]
description = "ignore slack, mailchimp, aws"
regexes = [
'''xox[baprs]-([0-9a-zA-Z]{10,48})''',
'''(?i)(.{0,20})?['"][0-9a-f]{32}-us[0-9]{1,2}['"]''',
'''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
]
[[rules]]
description = "High Entropy"
regex = '''[0-9a-zA-Z-_!{}/=]{4,120}'''
file = '''(?i)(dump.sql|high-entropy-misc.txt)$'''
tags = ["entropy"]
[[rules.Entropies]]
Min = "4.3"
Max = "7.0"
[rules.allowlist]
description = "ignore ssh key and pems"
files = ['''(pem|ppk|env)$''']
paths = ['''(.*)?ssh''']
[[rules]]
description = "Potential bash var"
regex='''(?i)(=)([0-9a-zA-Z-_!{}=]{4,120})'''
tags = ["key", "bash", "API", "generic"]
[[rules.Entropies]]
Min = "3.5"
Max = "4.5"
Group = "1"
[[rules]]
description = "WP-Config"
regex='''define(.{0,20})?(DB_CHARSET|NONCE_SALT|LOGGED_IN_SALT|AUTH_SALT|NONCE_KEY|DB_HOST|DB_PASSWORD|AUTH_KEY|SECURE_AUTH_KEY|LOGGED_IN_KEY|DB_NAME|DB_USER)(.{0,20})?['|"].{10,120}['|"]'''
tags = ["key", "API", "generic"]
[[rules]]
description = "Pure Entropy"
regex = '''['|"][0-9a-zA-Z-._{}$\/=]{40,120}['|"]'''
entropies = [
"5.0-5.6"
]
[[rules]]
description = "Entropy plus Generic Credential"
regex = '''(?i)(api_key|apikey|secret|key|api|password|pw)'''
entropies = [
"5.2-5.5"
]
[Global]
description = "Files with keys and credentials"
file = '''(?i)(id_rsa|passwd|id_rsa.pub|pgpass|pem|key|shadow)'''
[whitelist]
description = "image whitelists"
file = '''(.*?)(jpg|gif|doc|pdf|bin)$'''
# Global allowlist
[allowlist]
description = "image allowlists"
files = ['''(.*?)(jpg|gif|doc|pdf|bin)$''']
+7 -5
View File
@@ -1,5 +1,5 @@
# This config contains a single rule which defines a regex and a range of entropy values. If a rule has
# both regex and entropy then that rule uses BOTH the regex and entropy in combination when performing an audit.
# both regex and entropy then that rule uses BOTH the regex and entropy in combination when performing an scan.
# In other words, if a line of code has an entropy value that is within the range of the entropies defined and
# a regex match is found then that line of code contains a leak.
@@ -8,8 +8,10 @@
[[rules]]
description = "entropy and regex"
regex = '''(?i)key(.{0,20})?['|"][0-9a-zA-Z]{16,45}['|"]'''
entropies = [
"4.5-4.7",
"5.5-6.3",
]
tags = ["entropy"]
[[rules.Entropies]]
Min = "4.5"
Max = "5.7"
[[rules.Entropies]]
Min = "5.5"
Max = "6.3"
-10
View File
@@ -1,10 +0,0 @@
# This is a simple gitleaks config that contains one rule which checks for AWS keys and a file check that will trigger
# a leak if a .pem file is found
[[rules]]
description = "AWS Manager ID"
regex = '''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
tags = ["key", "AWS"]
[Global]
file = '''(.*)?pem$'''
@@ -1,13 +1,13 @@
# This config contains a single rule that checks for AWS keys. However, it also contains a whitelist table
# where you can define one or more whitelists. What this means is that if you have an example AWS key as part of your
# code (in a test for example), then you can whitelist that specific key so gitleaks will not label it as a leak.
# This config contains a single rule that checks for AWS keys. However, it also contains a allowlist table
# where you can define one or more allowlists. What this means is that if you have an example AWS key as part of your
# code (in a test for example), then you can allowlist that specific key so gitleaks will not label it as a leak.
# If this line was present in a git history: `aws_access_key_id='AKIAIO5FODNN7EXAMPLE``, gitleaks would match this line
# with the rule below, but since we have a whitelist against that specific key, it would be ignored.
# with the rule below, but since we have a allowlist against that specific key, it would be ignored.
[[rules]]
description = "AWS Manager ID"
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.whitelist]]
regex = '''AKIAIO5FODNN7EXAMPLE.*'''
description = "ignore example aws key"
[rules.allowlist]
regexes = ['''AKIAIO5FODNN7EXAMPLE.*''']
description = "ignore example aws key"
+1 -1
View File
@@ -1,6 +1,6 @@
# This is a simple gitleaks config that contains one rule which checks for AWS keys.
[[rules]]
description = "AWS Manager ID"
description = "AWS Access Key"
regex = '''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
tags = ["key", "AWS"]
+9 -9
View File
@@ -1,17 +1,17 @@
module github.com/zricethezav/gitleaks
module github.com/zricethezav/gitleaks/v7
go 1.13
go 1.15
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
github.com/google/go-github v17.0.0+incompatible
github.com/go-git/go-git/v5 v5.2.0
github.com/google/go-cmp v0.4.0 // indirect
github.com/hako/durafmt v0.0.0-20191009132224-3f39dc1ed9f4
github.com/jessevdk/go-flags v1.4.0
github.com/mattn/go-colorable v0.1.2
github.com/sergi/go-diff v1.0.0
github.com/sergi/go-diff v1.1.0
github.com/sirupsen/logrus v1.4.2
github.com/xanzy/go-gitlab v0.21.0
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45
gopkg.in/src-d/go-billy.v4 v4.3.2
gopkg.in/src-d/go-git.v4 v4.13.1
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9
gopkg.in/yaml.v2 v2.2.8 // indirect
)
+42 -54
View File
@@ -1,4 +1,3 @@
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/alcortesm/tgz v0.0.0-20161220082320-9c5fe88206d7 h1:uSoVVbwJiQipAclBbw+8quDsfcvFjOpI5iCf4p/cqCs=
@@ -7,7 +6,7 @@ github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239 h1:kFOfPq6dUM1hTo
github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c=
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=
github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -17,16 +16,22 @@ github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 h1:BHsljHzVlRcyQhjr
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc=
github.com/gliderlabs/ssh v0.2.2 h1:6zsha5zo/TWhRhwqCD3+EarCAgZ2yN28ipRnGPnwkI0=
github.com/gliderlabs/ssh v0.2.2/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0=
github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/go-git/gcfg v1.5.0 h1:Q5ViNfGF8zFgyJWPqYwA7qGFoMTEiBmdlkcfRmpIMa4=
github.com/go-git/gcfg v1.5.0/go.mod h1:5m20vg6GwYabIxaOonVkTdrILxQMpEShl1xiMF4ua+E=
github.com/go-git/go-billy/v5 v5.0.0 h1:7NQHvd9FVid8VL4qVUMm8XifBK+2xCoZ2lSk0agRrHM=
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-github v17.0.0+incompatible h1:N0LgJ1j65A7kfXrZnUDaYCs/Sf4rEjNlfyDHW9dolSY=
github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ=
github.com/google/go-querystring v1.0.0 h1:Xkwi/a1rcvNg1PPYe5vI8GbeBY/jrVuDX5ASuANWTrk=
github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck=
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=
github.com/hako/durafmt v0.0.0-20191009132224-3f39dc1ed9f4 h1:60gBOooTSmNtrqNaRvrDbi8VAne0REaek2agjnITKSw=
github.com/hako/durafmt v0.0.0-20191009132224-3f39dc1ed9f4/go.mod h1:5Scbynm8dF1XAPwIwkGPqzkM/shndPm79Jd1003hTjE=
github.com/imdario/mergo v0.3.9 h1:UauaLniWCFHWd+Jp9oCEkTBj8VO/9DKg3PV3VCNMDIg=
github.com/imdario/mergo v0.3.9/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA=
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A=
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo=
github.com/jessevdk/go-flags v1.4.0 h1:4IU2WS7AumrZ/40jfhf4QVDMsQwqA7VEHozFRrGARJA=
@@ -38,82 +43,65 @@ github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxv
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/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw=
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/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/pelletier/go-buffruneio v0.2.0/go.mod h1:JkE26KsDizTr40EUHkXVtNPvgGtbSNq5BcowyYOWdKo=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ=
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=
github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/src-d/gcfg v1.4.0 h1:xXbNR5AlLSA315x2UO+fTSSAXCDf+Ar38/6oyGbDKQ4=
github.com/src-d/gcfg v1.4.0/go.mod h1:p/UMsR43ujA89BJY9duynAwIpvqEujIH/jFlfL7jWoI=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/xanzy/go-gitlab v0.21.0 h1:Ru55sR4TBoDNsAKwCOpzeaGtbiWj7xTksVmzBJbLu6c=
github.com/xanzy/go-gitlab v0.21.0/go.mod h1:t4Bmvnxj7k37S4Y17lfLx+nLqkf/oQwT2HagfWKv5Og=
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.1 h1:snaoKv8ksDSz7NfBRXsBr9Yr8IKEKWRWf1zdhFmcFvI=
github.com/zricethezav/go-git/v5 v5.2.1/go.mod h1:kh02eMX+wdqqxgNMEyq8YgwlIOsDOa9homkUq1PoTMs=
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-20190701094942-4def268fd1a4 h1:HuIa8hRrWRSrqYzx1qI49NNxhdi2PrY7gxVSq1JjLDc=
golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181108082009-03003ca0c849/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
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/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-20190724013045-ca1201d0de80 h1:Ao/3l156eZf2AW5wK8a7/smtodRU+gha3+BeqJ69lRk=
golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/oauth2 v0.0.0-20181106182150-f42d05182288/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 h1:SVwTIAaPC2U/AvvLNZ2a7OVsmBpC8L5BlwK1whH3hm0=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
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-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=
golang.org/x/sys v0.0.0-20190221075227-b4e8571b14e0/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc=
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e h1:D5TXcfTk7xF7hvieo4QErS3qqCB4teTffacDWr7CI+0=
golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527 h1:uYVVQ9WP/Ds2ROhcaGPeIdVq0RIXVLwsHlnvJ+cT1So=
golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
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-20190729092621-ff9f1409240a h1:mEQZbbaBjWyLNy0tmZmgEuQAR8XOQ3hL8GYi3J/NG64=
golang.org/x/tools v0.0.0-20190729092621-ff9f1409240a/go.mod h1:jcCCGcm9btYwXyDqrUWc6MKQKKGJCWEQ3AfLSRIbEuI=
google.golang.org/appengine v1.3.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
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=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/src-d/go-billy.v4 v4.3.2 h1:0SQA1pRztfTFx2miS8sA97XvooFeNOmvUenF4o0EcVg=
gopkg.in/src-d/go-billy.v4 v4.3.2/go.mod h1:nDjArDMp+XMs1aFAESLRjfGSgfvoYN0hDfzEk0GjC98=
gopkg.in/src-d/go-git-fixtures.v3 v3.5.0 h1:ivZFOIltbce2Mo8IjzUHAFoq/IylO9WHhNOAJK+LsJg=
gopkg.in/src-d/go-git-fixtures.v3 v3.5.0/go.mod h1:dLBcvytrw/TYZsNTWCnkNF2DSIlzWYqTe3rJR56Ac7g=
gopkg.in/src-d/go-git.v4 v4.13.1 h1:SRtFyV8Kxc0UP7aCHcijOMQGPxHSmMOPrzulQWolkYE=
gopkg.in/src-d/go-git.v4 v4.13.1/go.mod h1:nx5NYcxdKxq5fpltdHnPa2Exj4Sx0EclMWZQbYDu2z8=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU=
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=
-155
View File
@@ -1,155 +0,0 @@
package hosts
import (
"context"
"strconv"
"strings"
"sync"
"github.com/zricethezav/gitleaks/audit"
"github.com/zricethezav/gitleaks/manager"
"github.com/zricethezav/gitleaks/options"
"github.com/google/go-github/github"
log "github.com/sirupsen/logrus"
"golang.org/x/oauth2"
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing"
"gopkg.in/src-d/go-git.v4/plumbing/object"
)
// Github wraps a github client and manager. This struct implements what the Host interface defines.
type Github struct {
client *github.Client
manager manager.Manager
wg sync.WaitGroup
}
// NewGithubClient accepts a manager struct and returns a Github host pointer which will be used to
// perform a github audit on an organization, user, or PR.
func NewGithubClient(m manager.Manager) *Github {
ctx := context.Background()
token := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: options.GetAccessToken(m.Opts)},
)
return &Github{
manager: m,
client: github.NewClient(oauth2.NewClient(ctx, token)),
}
}
// Audit will audit a github user or organization's repos.
func (g *Github) Audit() {
ctx := context.Background()
listOptions := github.ListOptions{
PerPage: 100,
Page: 1,
}
var githubRepos []*github.Repository
for {
var (
_githubRepos []*github.Repository
resp *github.Response
err error
)
if g.manager.Opts.User != "" {
_githubRepos, resp, err = g.client.Repositories.List(ctx, g.manager.Opts.User,
&github.RepositoryListOptions{ListOptions: listOptions})
} else if g.manager.Opts.Organization != "" {
_githubRepos, resp, err = g.client.Repositories.ListByOrg(ctx, g.manager.Opts.Organization,
&github.RepositoryListByOrgOptions{ListOptions: listOptions})
}
githubRepos = append(githubRepos, _githubRepos...)
if resp == nil {
break
}
if resp.LastPage != 0 {
log.Infof("gathering github repos... progress: page %d of %d", listOptions.Page, resp.LastPage)
} else {
log.Infof("gathering github repos... progress: page %d of %d", listOptions.Page, listOptions.Page)
}
listOptions.Page = resp.NextPage
if err != nil || listOptions.Page == 0 {
break
}
}
for _, repo := range githubRepos {
r := audit.NewRepo(&g.manager)
r.Name = *repo.Name
err := r.Clone(&git.CloneOptions{
URL: *repo.CloneURL,
})
if err != nil {
log.Warn("unable to clone via https and access token, attempting with ssh now")
auth, err := options.SSHAuth(g.manager.Opts)
if err != nil {
log.Warnf("unable to get ssh auth, skipping clone and audit for repo %s: %+v\n", *repo.CloneURL, err)
}
err = r.Clone(&git.CloneOptions{
URL: *repo.SSHURL,
Auth: auth,
})
if err != nil {
log.Warnf("err cloning %s, skipping clone and audit: %+v\n", *repo.SSHURL, err)
}
}
if err = r.Audit(); err != nil {
log.Warn(err)
}
}
}
// AuditPR audits a single github PR
func (g *Github) AuditPR() {
ctx := context.Background()
splits := strings.Split(g.manager.Opts.PullRequest, "/")
owner := splits[len(splits)-4]
repoName := splits[len(splits)-3]
prNum, err := strconv.Atoi(splits[len(splits)-1])
repo := audit.NewRepo(&g.manager)
repo.Name = repoName
log.Infof("auditing pr %s\n", g.manager.Opts.PullRequest)
if err != nil {
return
}
page := 1
for {
commits, resp, err := g.client.PullRequests.ListCommits(ctx, owner, repoName, prNum, &github.ListOptions{
PerPage: 100, Page: page})
if err != nil {
return
}
for _, c := range commits {
c, _, err := g.client.Repositories.GetCommit(ctx, owner, repo.Name, *c.SHA)
if err != nil {
continue
}
commitObj := object.Commit{
Hash: plumbing.NewHash(*c.SHA),
Author: object.Signature{
Name: *c.Commit.Author.Name,
Email: *c.Commit.Author.Email,
When: *c.Commit.Author.Date,
},
}
for _, f := range c.Files {
if f.Patch == nil {
continue
}
audit.InspectString(*f.Patch, &commitObj, repo, *f.Filename)
}
}
page = resp.NextPage
if resp.LastPage == 0 {
break
}
}
}
-93
View File
@@ -1,93 +0,0 @@
package hosts
import (
"context"
"sync"
"github.com/zricethezav/gitleaks/audit"
"github.com/zricethezav/gitleaks/manager"
"github.com/zricethezav/gitleaks/options"
log "github.com/sirupsen/logrus"
"github.com/xanzy/go-gitlab"
)
// Gitlab wraps a gitlab client and manager. This struct implements what the Host interface defines.
type Gitlab struct {
client *gitlab.Client
manager manager.Manager
ctx context.Context
wg sync.WaitGroup
}
// NewGitlabClient accepts a manager struct and returns a Gitlab host pointer which will be used to
// perform a gitlab audit on an group or user.
func NewGitlabClient(m manager.Manager) *Gitlab {
return &Gitlab{
manager: m,
ctx: context.Background(),
client: gitlab.NewClient(nil, options.GetAccessToken(m.Opts)),
}
}
// Audit will audit a github user or organization's repos.
func (g *Gitlab) Audit() {
var (
projects []*gitlab.Project
resp *gitlab.Response
err error
)
page := 1
listOpts := gitlab.ListOptions{
PerPage: 100,
Page: page,
}
for {
var _projects []*gitlab.Project
if g.manager.Opts.User != "" {
glOpts := &gitlab.ListProjectsOptions{
ListOptions: listOpts,
}
projects, resp, err = g.client.Projects.ListUserProjects(g.manager.Opts.User, glOpts)
} else if g.manager.Opts.Organization != "" {
glOpts := &gitlab.ListGroupProjectsOptions{
ListOptions: listOpts,
}
projects, resp, err = g.client.Groups.ListGroupProjects(g.manager.Opts.Organization, glOpts)
}
if err != nil {
log.Error(err)
}
projects = append(projects, _projects...)
if resp == nil {
break
}
if page >= resp.TotalPages {
// exit when we've seen all pages
break
}
page = resp.NextPage
}
// iterate of gitlab projects
for _, p := range projects {
r := audit.NewRepo(&g.manager)
cloneOpts := g.manager.CloneOptions
cloneOpts.URL = p.HTTPURLToRepo
err := r.Clone(cloneOpts)
// TODO handle clone retry with ssh like github host
r.Name = p.Name
if err = r.Audit(); err != nil {
log.Error(err)
}
}
}
// AuditPR TODO not implemented
func (g *Gitlab) AuditPR() {
log.Error("AuditPR is not implemented in Gitlab host yet...")
}
-47
View File
@@ -1,47 +0,0 @@
package hosts
import (
"github.com/zricethezav/gitleaks/manager"
"strings"
)
const (
_github int = iota + 1
_gitlab
)
// Host is an interface used for defining external git hosting providers like github and gitlab.
// TODO add bitbucket
type Host interface {
Audit()
AuditPR()
}
// Run kicks off a host audit. This function accepts a manager and determines what host it should audit
func Run(m *manager.Manager) error {
var host Host
switch getHost(m.Opts.Host) {
case _github:
host = NewGithubClient(*m)
case _gitlab:
host = NewGitlabClient(*m)
default:
return nil
}
if m.Opts.PullRequest != "" {
host.AuditPR()
} else {
host.Audit()
}
return nil
}
func getHost(host string) int {
if strings.ToLower(host) == "github" {
return _github
} else if strings.ToLower(host) == "gitlab" {
return _gitlab
}
return -1
}
-115
View File
@@ -1,115 +0,0 @@
package hosts
import (
"flag"
"fmt"
"github.com/zricethezav/gitleaks/config"
"github.com/zricethezav/gitleaks/manager"
"github.com/zricethezav/gitleaks/options"
"os"
"testing"
)
var (
integration = flag.Bool("integration", false, "run github/gitlab integration test")
)
func TestGithub(t *testing.T) {
flag.Parse()
if !*integration {
fmt.Println("skipping github integration tests")
return
}
if os.Getenv("GITHUB_TOKEN") == "" {
t.Log("skipping github integration tests, need env var GITLAB_TOKEN")
return
}
tests := []struct {
opts options.Options
desiredLeaks int
}{
{
opts: options.Options{
Host: "github",
User: "gitleakstest",
AccessToken: os.Getenv("GITHUB_TOKEN"),
},
desiredLeaks: 2,
},
{
opts: options.Options{
Host: "github",
PullRequest: "https://github.com/gitleakstest/gronit/pull/1",
AccessToken: os.Getenv("GITHUB_TOKEN"),
},
desiredLeaks: 4,
},
}
for _, test := range tests {
cfg, err := config.NewConfig(test.opts)
if err != nil {
t.Error(err)
}
m, err := manager.NewManager(test.opts, cfg)
if err != nil {
t.Error(err)
}
err = Run(m)
if err != nil {
t.Fatal(err)
}
if test.desiredLeaks != len(m.GetLeaks()) {
t.Errorf("got %d leaks, want %d", len(m.GetLeaks()), test.desiredLeaks)
}
}
}
func TestGitlab(t *testing.T) {
flag.Parse()
if !*integration {
fmt.Println("skipping gitlab integration tests")
return
}
if os.Getenv("GITLAB_TOKEN") == "" {
t.Log("skipping github integration tests, need env var GITLAB_TOKEN")
return
}
tests := []struct {
opts options.Options
desiredLeaks int
}{
{
opts: options.Options{
Host: "gitlab",
User: "gitleakstest",
AccessToken: os.Getenv("GITLAB_TOKEN"),
},
desiredLeaks: 2,
},
}
for _, test := range tests {
cfg, err := config.NewConfig(test.opts)
if err != nil {
t.Error(err)
}
m, err := manager.NewManager(test.opts, cfg)
if err != nil {
t.Error(err)
}
err = Run(m)
if err != nil {
t.Fatal(err)
}
if test.desiredLeaks != len(m.GetLeaks()) {
t.Errorf("got %d leaks, want %d", len(m.GetLeaks()), test.desiredLeaks)
}
}
}
+34 -57
View File
@@ -1,97 +1,74 @@
package main
import (
"io/ioutil"
"os"
"os/signal"
"time"
"github.com/zricethezav/gitleaks/audit"
"github.com/zricethezav/gitleaks/config"
"github.com/zricethezav/gitleaks/hosts"
"github.com/zricethezav/gitleaks/manager"
"github.com/zricethezav/gitleaks/options"
"github.com/zricethezav/gitleaks/v7/config"
"github.com/zricethezav/gitleaks/v7/options"
"github.com/zricethezav/gitleaks/v7/scan"
"github.com/hako/durafmt"
log "github.com/sirupsen/logrus"
)
func main() {
// this block sets up a go routine to listen for an interrupt signal
// which will immediately exit gitleaks
stopChan := make(chan os.Signal, 1)
signal.Notify(stopChan, os.Interrupt)
go listenForInterrupt(stopChan)
// setup options
opts, err := options.ParseOptions()
if err != nil {
log.Error(err)
os.Exit(options.ErrorEncountered)
os.Exit(1)
}
err = opts.Guard()
if err != nil {
log.Error(err)
os.Exit(options.ErrorEncountered)
os.Exit(1)
}
// setup configs
cfg, err := config.NewConfig(opts)
if err != nil {
log.Error(err)
os.Exit(options.ErrorEncountered)
os.Exit(1)
}
m, err := manager.NewManager(opts, cfg)
// setup scanner
scanner, err := scan.NewScanner(opts, cfg)
if err != nil {
log.Error(err)
os.Exit(options.ErrorEncountered)
os.Exit(1)
}
err = Run(m)
// run and time the scan
start := time.Now()
scannerReport, err := scanner.Scan()
log.Info("scan time: ", durafmt.Parse(time.Now().Sub(start)))
if err != nil {
log.Error(err)
os.Exit(options.ErrorEncountered)
os.Exit(1)
}
leaks := m.GetLeaks()
metadata := m.GetMetadata()
// report scan
if err := scan.WriteReport(scannerReport, opts, cfg); err != nil {
log.Error(err)
os.Exit(1)
}
if len(m.GetLeaks()) != 0 {
if m.Opts.CheckUncommitted() {
log.Warnf("%d leaks detected in staged changes", len(leaks))
} else {
log.Warnf("%d leaks detected. %d commits audited in %s", len(leaks),
metadata.Commits, durafmt.Parse(time.Duration(metadata.AuditTime)*time.Nanosecond))
}
os.Exit(options.LeaksPresent)
} else {
if m.Opts.CheckUncommitted() {
log.Infof("No leaks detected in staged changes")
} else {
log.Infof("No leaks detected. %d commits audited in %s",
metadata.Commits, durafmt.Parse(time.Duration(metadata.AuditTime)*time.Nanosecond))
}
os.Exit(options.Success)
if len(scannerReport.Leaks) != 0 {
os.Exit(opts.CodeOnLeak)
}
}
// Run begins the program and contains some basic logic on how to continue with the audit. If any external git host
// options are set (like auditing a gitlab or github user) then a specific host client will be created and
// then Audit() and Report() will be called. Otherwise, gitleaks will create a new repo and an audit will proceed.
// If no options or the uncommitted option is set then a pre-commit audit will
// take place -- this is similar to running `git diff` on all the tracked files.
func Run(m *manager.Manager) error {
if m.Opts.Disk {
dir, err := ioutil.TempDir("", "gitleaks")
defer os.RemoveAll(dir)
if err != nil {
return err
}
m.CloneDir = dir
}
var err error
if m.Opts.Host != "" {
err = hosts.Run(m)
} else {
err = audit.Run(m)
}
if err != nil {
return err
}
return m.Report()
func listenForInterrupt(stopScan chan os.Signal) {
<-stopScan
log.Warn("halting gitleaks scan")
os.Exit(1)
}
-299
View File
@@ -1,299 +0,0 @@
package manager
import (
"crypto/sha1"
"encoding/csv"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"os/signal"
"runtime"
"sync"
"text/tabwriter"
"time"
"github.com/zricethezav/gitleaks/config"
"github.com/zricethezav/gitleaks/options"
"github.com/hako/durafmt"
"github.com/mattn/go-colorable"
log "github.com/sirupsen/logrus"
"gopkg.in/src-d/go-git.v4"
)
// Manager is a struct containing options and configs as well CloneOptions and CloneDir.
// This struct is passed into each NewRepo so we are not passing around the manager in func params.
type Manager struct {
Opts options.Options
Config config.Config
CloneOptions *git.CloneOptions
CloneDir string
leaks []Leak
leakChan chan Leak
leakWG *sync.WaitGroup
leakCache map[string]bool
stopChan chan os.Signal
metadata Metadata
metaWG *sync.WaitGroup
}
// 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"`
Offender string `json:"offender"`
Commit string `json:"commit"`
Repo string `json:"repo"`
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"`
lookupHash string
}
// AuditTime is a type used to determine total audit time
type AuditTime int64
// PatchTime is a type used to determine total patch time during an audit
type PatchTime int64
// CloneTime is a type used to determine total clone time
type CloneTime int64
// RegexTime is a type used to determine the time each rules' regex takes. This is especially useful
// if you notice that gitleaks is taking a long time. You can use --debug to see the output of the regexTime
// so you can determine which regex is not performing well.
type RegexTime struct {
Time int64
Regex string
}
// Metadata is a struct used to communicate metadata about an audit like timings and total commit counts.
type Metadata struct {
mux sync.Mutex
data map[string]interface{}
timings chan interface{}
RegexTime map[string]int64
Commits int
AuditTime int64
patchTime int64
cloneTime int64
}
func init() {
log.SetOutput(os.Stdout)
log.SetFormatter(&log.TextFormatter{
ForceColors: true,
FullTimestamp: true,
})
// Fix colors on Windows
if runtime.GOOS == "windows" {
log.SetOutput(colorable.NewColorableStdout())
}
}
// GetLeaks returns all available leaks
func (manager *Manager) GetLeaks() []Leak {
// need to wait for any straggling leaks
manager.leakWG.Wait()
return manager.leaks
}
// SendLeaks accepts a leak and is used by the audit pkg. This is the public function
// that allows other packages to send leaks to the manager.
func (manager *Manager) SendLeaks(l Leak) {
h := sha1.New()
h.Write([]byte(l.Commit + l.Offender + l.File))
l.lookupHash = hex.EncodeToString(h.Sum(nil))
manager.leakWG.Add(1)
manager.leakChan <- l
}
func (manager *Manager) alreadySeen(leak Leak) bool {
if _, ok := manager.leakCache[leak.lookupHash]; ok {
return true
}
manager.leakCache[leak.lookupHash] = true
return false
}
// receiveLeaks listens to leakChan for incoming leaks. If any are received, they are appended to the
// manager's leaks for future reporting. If the -v/--verbose option is set the leaks will marshaled into
// json and printed out.
func (manager *Manager) receiveLeaks() {
for leak := range manager.leakChan {
if manager.alreadySeen(leak) {
manager.leakWG.Done()
continue
}
manager.leaks = append(manager.leaks, leak)
if manager.Opts.Verbose {
var b []byte
if manager.Opts.PrettyPrint {
b, _ = json.MarshalIndent(leak, "", " ")
} else {
b, _ = json.Marshal(leak)
}
fmt.Println(string(b))
}
manager.leakWG.Done()
}
}
// GetMetadata returns the metadata. TODO this may not need to be private
func (manager *Manager) GetMetadata() Metadata {
manager.metaWG.Wait()
return manager.metadata
}
// receiveMetadata is where the messages sent to the metadata channel get consumed. You can view metadata
// by running gitleaks with the --debug option set. This is extremely useful when trying to optimize regular
// expressions as that what gitleaks spends most of its cycles on.
func (manager *Manager) receiveMetadata() {
for t := range manager.metadata.timings {
switch ti := t.(type) {
case CloneTime:
manager.metadata.cloneTime += int64(ti)
case AuditTime:
manager.metadata.AuditTime += int64(ti)
case PatchTime:
manager.metadata.patchTime += int64(ti)
case RegexTime:
manager.metadata.RegexTime[ti.Regex] = manager.metadata.RegexTime[ti.Regex] + ti.Time
}
manager.metaWG.Done()
}
}
// IncrementCommits increments total commits during an audit by i.
func (manager *Manager) IncrementCommits(i int) {
manager.metadata.mux.Lock()
manager.metadata.Commits += i
manager.metadata.mux.Unlock()
}
// RecordTime accepts an interface and sends it to the manager's time channel
func (manager *Manager) RecordTime(t interface{}) {
manager.metaWG.Add(1)
manager.metadata.timings <- t
}
// NewManager accepts options and returns a manager struct. The manager is a container for gitleaks configurations,
// options and channel receivers.
func NewManager(opts options.Options, cfg config.Config) (*Manager, error) {
cloneOpts, err := opts.CloneOptions()
if err != nil {
return nil, err
}
m := &Manager{
Opts: opts,
Config: cfg,
CloneOptions: cloneOpts,
stopChan: make(chan os.Signal, 1),
leakChan: make(chan Leak),
leakWG: &sync.WaitGroup{},
leakCache: make(map[string]bool),
metaWG: &sync.WaitGroup{},
metadata: Metadata{
RegexTime: make(map[string]int64),
timings: make(chan interface{}),
data: make(map[string]interface{}),
},
}
signal.Notify(m.stopChan, os.Interrupt)
// start receiving leaks and metadata
go m.receiveLeaks()
go m.receiveMetadata()
go m.receiveInterrupt()
return m, nil
}
// DebugOutput logs metadata and other messages that occurred during a gitleaks audit
func (manager *Manager) DebugOutput() {
log.Debugf("-------------------------\n")
log.Debugf("| Times and Commit Counts|\n")
log.Debugf("-------------------------\n")
fmt.Println("totalAuditTime: ", durafmt.Parse(time.Duration(manager.metadata.AuditTime)*time.Nanosecond))
fmt.Println("totalPatchTime: ", durafmt.Parse(time.Duration(manager.metadata.patchTime)*time.Nanosecond))
fmt.Println("totalCloneTime: ", durafmt.Parse(time.Duration(manager.metadata.cloneTime)*time.Nanosecond))
fmt.Println("totalCommits: ", manager.metadata.Commits)
const padding = 6
w := tabwriter.NewWriter(os.Stdout, 0, 0, padding, '.', 0)
log.Debugf("--------------------------\n")
log.Debugf("| Individual Regex Times |\n")
log.Debugf("--------------------------\n")
for k, v := range manager.metadata.RegexTime {
fmt.Fprintf(w, "%s\t%s\n", k, durafmt.Parse(time.Duration(v)*time.Nanosecond))
}
w.Flush()
}
// Report saves gitleaks leaks to a json specified by --report={report.json}
func (manager *Manager) Report() error {
close(manager.leakChan)
close(manager.metadata.timings)
if log.IsLevelEnabled(log.DebugLevel) {
manager.DebugOutput()
}
if manager.Opts.Report != "" {
if len(manager.GetLeaks()) == 0 {
log.Infof("no leaks found, skipping writing report")
return nil
}
file, err := os.Create(manager.Opts.Report)
if err != nil {
return err
}
if manager.Opts.ReportFormat == "json" {
encoder := json.NewEncoder(file)
encoder.SetIndent("", " ")
err = encoder.Encode(manager.leaks)
if err != nil {
return err
}
} else {
w := csv.NewWriter(file)
w.Write([]string{"repo", "line", "commit", "offender", "rule", "tags", "commitMsg", "author", "email", "file", "date"})
for _, leak := range manager.GetLeaks() {
w.Write([]string{leak.Repo, leak.Line, leak.Commit, leak.Offender, leak.Rule, leak.Tags, leak.Message, leak.Author, leak.Email, leak.File, leak.Date.Format(time.RFC3339)})
}
w.Flush()
}
file.Close()
log.Infof("report written to %s", manager.Opts.Report)
}
return nil
}
func (manager *Manager) receiveInterrupt() {
<-manager.stopChan
if manager.Opts.Report != "" {
err := manager.Report()
if err != nil {
log.Error(err)
}
}
log.Info("gitleaks received interrupt, stopping audit")
os.Exit(options.ErrorEncountered)
}
-106
View File
@@ -1,106 +0,0 @@
package manager
import (
"crypto/rand"
"fmt"
"github.com/zricethezav/gitleaks/config"
"github.com/zricethezav/gitleaks/options"
"io"
"testing"
)
// TODO
// add more substantial tests... but since literally every pkg uses manager
// these tests are kind of redundant
func TestSendReceiveLeaks(t *testing.T) {
tests := []struct {
leaksToAdd int
goRoutines int
}{
{
leaksToAdd: 10,
},
{
leaksToAdd: 1000,
},
}
for _, test := range tests {
opts := options.Options{}
cfg, _ := config.NewConfig(opts)
m, _ := NewManager(opts, cfg)
for i := 0; i < test.leaksToAdd; i++ {
// we are testing the sync of sending/receiving leaks so we need
// the hash generation in sendLeaks to be unique for each iteration
// so I'm just setting the offender string as a uuid
m.SendLeaks(Leak{Offender: newUUID()})
}
got := m.GetLeaks()
if len(got) != test.leaksToAdd {
t.Errorf("got %d, wanted %d leaks", len(got), test.leaksToAdd)
}
}
}
func TestSendReceiveMeta(t *testing.T) {
tests := []struct {
auditTime int64
patchTime int64
cloneTime int64
regexTime int64
iterations int
}{
{
auditTime: 1000,
patchTime: 1000,
cloneTime: 1000,
regexTime: 1000,
iterations: 100,
},
}
for _, test := range tests {
opts := options.Options{}
cfg, _ := config.NewConfig(opts)
m, _ := NewManager(opts, cfg)
for i := 0; i < test.iterations; i++ {
m.RecordTime(AuditTime(test.auditTime))
m.RecordTime(PatchTime(test.patchTime))
m.RecordTime(CloneTime(test.cloneTime))
m.RecordTime(RegexTime{
Regex: "regex",
Time: test.regexTime,
})
m.RecordTime(RegexTime{
Regex: "regex2",
Time: test.regexTime,
})
}
md := m.GetMetadata()
if md.cloneTime != test.cloneTime*int64(test.iterations) {
t.Errorf("clone time mismatch, got %d, wanted %d",
md.cloneTime, test.cloneTime*int64(test.iterations))
}
if md.AuditTime != test.auditTime*int64(test.iterations) {
t.Errorf("audit time mismatch, got %d, wanted %d",
md.AuditTime, test.auditTime*int64(test.iterations))
}
if md.patchTime != test.patchTime*int64(test.iterations) {
t.Errorf("clone time mismatch, got %d, wanted %d",
md.patchTime, test.patchTime*int64(test.iterations))
}
}
}
// newUUID generates a random UUID according to RFC 4122
// Ripped from https://play.golang.org/p/4FkNSiUDMg
func newUUID() string {
uuid := make([]byte, 16)
io.ReadFull(rand.Reader, uuid)
// variant bits; see section 4.1.1
uuid[8] = uuid[8]&^0xc0 | 0x80
// version 4 (pseudo-random); see section 4.1.3
uuid[6] = uuid[6]&^0xf0 | 0x40
return fmt.Sprintf("%x-%x-%x-%x-%x", uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:])
}
+78 -107
View File
@@ -7,54 +7,52 @@ import (
"os/user"
"strings"
"github.com/zricethezav/gitleaks/version"
"github.com/zricethezav/gitleaks/v7/version"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/transport"
"github.com/go-git/go-git/v5/plumbing/transport/http"
"github.com/go-git/go-git/v5/plumbing/transport/ssh"
"github.com/jessevdk/go-flags"
log "github.com/sirupsen/logrus"
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing/transport/http"
"gopkg.in/src-d/go-git.v4/plumbing/transport/ssh"
)
// No leaks or early exit due to invalid options
// This block defines the exit codes. Success
const (
// No leaks or early exit due to invalid options
Success = 0
LeaksPresent = 1
ErrorEncountered = 2
)
// Options stores values of command line options
type Options struct {
Verbose bool `short:"v" long:"verbose" description:"Show verbose output from audit"`
Repo string `short:"r" long:"repo" description:"Target repository"`
Config string `long:"config" description:"config path"`
Disk bool `long:"disk" description:"Clones repo(s) to disk"`
Version bool `long:"version" description:"version number"`
Timeout int `long:"timeout" description:"Timeout (s)"`
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"`
Commit string `long:"commit" description:"sha of commit to audit"`
Threads int `long:"threads" description:"Maximum number of threads gitleaks spawns"`
SSH string `long:"ssh-key" description:"path to ssh key used for auth"`
Uncommited bool `long:"uncommitted" description:"run gitleaks on uncommitted code"`
RepoPath string `long:"repo-path" description:"Path to repo"`
OwnerPath string `long:"owner-path" description:"Path to owner directory (repos discovered)"`
Branch string `long:"branch" description:"Branch to audit"`
Report string `long:"report" description:"path to write json leaks file"`
ReportFormat string `long:"report-format" default:"json" description:"json or csv"`
Redact bool `long:"redact" description:"redact secrets from log messages and leaks"`
Debug bool `long:"debug" description:"log debug messages"`
RepoConfig bool `long:"repo-config" description:"Load config from target repo. Config file must be \".gitleaks.toml\" or \"gitleaks.toml\""`
PrettyPrint bool `long:"pretty" description:"Pretty print json if leaks are present"`
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"`
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"`
// Hosts
Host string `long:"host" description:"git hosting service like gitlab or github. Supported hosts include: Github, Gitlab"`
Organization string `long:"org" description:"organization to audit"`
User string `long:"user" description:"user to audit"` //work
PullRequest string `long:"pr" description:"pull/merge request url"`
// Report Options
Report string `short:"o" long:"report" description:"Report output path"`
ReportFormat string `short:"f" long:"format" default:"json" description:"JSON, CSV, SARIF"`
// Commit Options
FilesAtCommit string `long:"files-at-commit" description:"Sha of commit to scan all files at commit"`
Commit string `long:"commit" description:"Sha of commit to scan or \"latest\" to scan the last commit of the repository"`
Commits string `long:"commits" description:"Comma separated list of a commits to scan"`
CommitsFile string `long:"commits-file" description:"Path to file of line separated list of commits to scan"`
CommitFrom string `long:"commit-from" description:"Commit to start scan from"`
CommitTo string `long:"commit-to" description:"Commit to stop scan"`
CommitSince string `long:"commit-since" description:"Scan commits more recent than a specific date. Ex: '2006-01-02' or '2006-01-02T15:04:05-0700' format."`
CommitUntil string `long:"commit-until" description:"Scan commits older than a specific date. Ex: '2006-01-02' or '2006-01-02T15:04:05-0700' format."`
Depth int `long:"depth" description:"Number of commits to scan"`
}
// ParseOptions is responsible for parsing options passed in by cli. An Options struct
@@ -79,7 +77,7 @@ func ParseOptions() (Options, error) {
} else {
fmt.Printf("%s\n", version.Version)
}
os.Exit(Success)
os.Exit(0)
}
if opts.Debug {
@@ -93,10 +91,7 @@ func ParseOptions() (Options, error) {
// If invalid sets of options are present, a descriptive error will return
// else nil is returned
func (opts Options) Guard() error {
if !oneOrNoneSet(opts.Repo, opts.OwnerPath, opts.RepoPath, opts.Host) {
return fmt.Errorf("only one target option must can be set. target options: repo, owner-path, repo-path, host")
}
if !oneOrNoneSet(opts.Organization, opts.User, opts.PullRequest) {
if !oneOrNoneSet(opts.RepoURL, opts.Path) {
return fmt.Errorf("only one target option must can be set. target options: repo, owner-path, repo-path, host")
}
if !oneOrNoneSet(opts.AccessToken, opts.Password) {
@@ -124,60 +119,52 @@ func oneOrNoneSet(optStr ...string) bool {
// Username/PW or AccessToken is available and the repo target is not using the
// git protocol then the repo must be a available via no auth.
func (opts Options) CloneOptions() (*git.CloneOptions, error) {
var err error
progress := ioutil.Discard
if opts.Verbose {
progress = os.Stdout
}
if strings.HasPrefix(opts.Repo, "git") {
cloneOpts := &git.CloneOptions{
URL: opts.RepoURL,
Progress: progress,
}
if opts.Depth != 0 {
cloneOpts.Depth = opts.Depth
}
if opts.Branch != "" {
cloneOpts.ReferenceName = plumbing.NewBranchReferenceName(opts.Branch)
}
var auth transport.AuthMethod
if strings.HasPrefix(opts.RepoURL, "git") {
// using git protocol so needs ssh auth
auth, err := SSHAuth(opts)
auth, err = SSHAuth(opts)
if err != nil {
return nil, err
}
return &git.CloneOptions{
URL: opts.Repo,
Auth: auth,
Progress: progress,
}, nil
}
if opts.Password != "" && opts.Username != "" {
} else if opts.Password != "" && opts.Username != "" {
// auth using username and password
return &git.CloneOptions{
URL: opts.Repo,
Auth: &http.BasicAuth{
Username: opts.Username,
Password: opts.Password,
},
Progress: progress,
}, nil
auth = &http.BasicAuth{
Username: opts.Username,
Password: opts.Password,
}
} else if opts.AccessToken != "" {
auth = &http.BasicAuth{
Username: "gitleaks_user",
Password: opts.AccessToken,
}
} else if os.Getenv("GITLEAKS_ACCESS_TOKEN") != "" {
auth = &http.BasicAuth{
Username: "gitleaks_user",
Password: os.Getenv("GITLEAKS_ACCESS_TOKEN"),
}
}
if opts.AccessToken != "" {
return &git.CloneOptions{
URL: opts.Repo,
Auth: &http.BasicAuth{
Username: "gitleaks_user",
Password: opts.AccessToken,
},
Progress: progress,
}, nil
if auth != nil {
cloneOpts.Auth = auth
}
if os.Getenv("GITLEAKS_ACCESS_TOKEN") != "" {
return &git.CloneOptions{
URL: opts.Repo,
Auth: &http.BasicAuth{
Username: "gitleaks_user",
Password: os.Getenv("GITLEAKS_ACCESS_TOKEN"),
},
Progress: progress,
}, nil
}
// No Auth, publicly available
return &git.CloneOptions{
URL: opts.Repo,
Progress: progress,
}, nil
return cloneOpts, nil
}
// SSHAuth tried to generate ssh public keys based on what was passed via cli. If no
@@ -199,7 +186,7 @@ func SSHAuth(opts Options) (*ssh.PublicKeys, error) {
// OpenLocal checks what options are set, if no remote targets are set
// then return true
func (opts Options) OpenLocal() bool {
if opts.Uncommited || opts.RepoPath != "" || opts.Repo == "" {
if opts.Unstaged || opts.Path != "" || opts.RepoURL == "" {
return true
}
return false
@@ -209,33 +196,17 @@ func (opts Options) OpenLocal() bool {
// or if gitleaks should check the entire git history
func (opts Options) CheckUncommitted() bool {
// check to make sure no remote shit is set
if opts.Uncommited {
if opts.Unstaged {
return true
}
if opts == (Options{}) {
return true
}
if opts.Repo != "" {
if opts.RepoURL != "" {
return false
}
if opts.RepoPath != "" {
return false
}
if opts.OwnerPath != "" {
return false
}
if opts.Host != "" {
if opts.Path != "" {
return false
}
return true
}
// GetAccessToken accepts options and returns a string which is the access token to a git host.
// Setting this option or environment var is necessary if performing an audit with any of the git hosting providers
// in the host pkg. The access token set by cli options takes precedence over env vars.
func GetAccessToken(opts Options) string {
if opts.AccessToken != "" {
return opts.AccessToken
}
return os.Getenv("GITLEAKS_ACCESS_TOKEN")
}
+151
View File
@@ -0,0 +1,151 @@
package scan
import (
"fmt"
"path/filepath"
"strings"
"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"
)
// CommitScanner is a commit scanner
type CommitScanner struct {
cfg config.Config
opts options.Options
repo *git.Repository
repoName string
commit *object.Commit
}
// NewCommitScanner creates and returns a commit scanner
func NewCommitScanner(opts options.Options, cfg config.Config, repo *git.Repository, commit *object.Commit) *CommitScanner {
cs := &CommitScanner{
cfg: cfg,
opts: opts,
repo: repo,
commit: commit,
repoName: getRepoName(opts),
}
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, error) {
var scannerReport Report
if cs.cfg.Allowlist.CommitAllowed(cs.commit.Hash.String()) {
return scannerReport, nil
}
if len(cs.commit.ParentHashes) == 0 {
facScanner := NewFilesAtCommitScanner(cs.opts, cs.cfg, cs.repo, cs.commit)
return facScanner.Scan()
}
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 {
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
}
// Check individual file path ONLY rules
for _, rule := range cs.cfg.Rules {
if rule.CommitAllowed(cs.commit.Hash.String()) {
continue
}
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, ", ")
if cs.opts.Verbose {
leak.Log(cs.opts.Redact)
}
scannerReport.Leaks = append(scannerReport.Leaks, leak)
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, ", ")
if cs.opts.Verbose {
leak.Log(cs.opts.Redact)
}
scannerReport.Leaks = append(scannerReport.Leaks, leak)
}
}
}
}
}
scannerReport.Commits = 1
return scannerReport, nil
}
+47
View File
@@ -0,0 +1,47 @@
package scan
import (
"github.com/go-git/go-git/v5"
"github.com/zricethezav/gitleaks/v7/config"
"github.com/zricethezav/gitleaks/v7/options"
)
// CommitsScanner is a commit scanner
type CommitsScanner struct {
opts options.Options
cfg config.Config
repo *git.Repository
repoName string
commits []string
}
// NewCommitsScanner creates and returns a commits scanner, notice the 's' in commits
func NewCommitsScanner(opts options.Options, cfg config.Config, repo *git.Repository, commits []string) *CommitsScanner {
return &CommitsScanner{
opts: opts,
cfg: cfg,
repo: repo,
commits: commits,
repoName: getRepoName(opts),
}
}
// Scan kicks off a CommitsScanner Scan
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.opts, css.cfg, css.repo, c)
commitReport, err := cs.Scan()
if err != nil {
return scannerReport, err
}
scannerReport.Leaks = append(scannerReport.Leaks, commitReport.Leaks...)
scannerReport.Commits++
}
return scannerReport, nil
}
+137
View File
@@ -0,0 +1,137 @@
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"
)
// FilesAtCommitScanner is a files at commit scanner. This differs from CommitScanner
// as CommitScanner generates patches that are scanned. FilesAtCommitScanner instead looks at
// files available at a commit's worktree and scans the entire content of said files.
// Apologies for the awful struct name...
type FilesAtCommitScanner struct {
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(opts options.Options, cfg config.Config, repo *git.Repository, commit *object.Commit) *FilesAtCommitScanner {
fs := &FilesAtCommitScanner{
opts: opts,
cfg: cfg,
repo: repo,
commit: commit,
repoName: getRepoName(opts),
}
return fs
}
// Scan kicks off a FilesAtCommitScanner Scan
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
}
err = fIter.ForEach(func(f *object.File) error {
bin, err := f.IsBinary()
if bin {
return nil
} else if err != nil {
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
}
// 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, ", ")
if fs.opts.Verbose {
leak.Log(fs.opts.Redact)
}
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, ", ")
if fs.opts.Verbose {
leak.Log(fs.opts.Redact)
}
scannerReport.Leaks = append(scannerReport.Leaks, leak)
}
}
return nil
})
scannerReport.Commits = 1
return scannerReport, err
}
+74
View File
@@ -0,0 +1,74 @@
package scan
import (
"encoding/json"
"fmt"
"strings"
"time"
"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(redact bool) {
if redact {
leak = RedactLeak(leak)
}
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 ""
}
+143
View File
@@ -0,0 +1,143 @@
package scan
import (
"bufio"
"context"
"os"
"path/filepath"
"strings"
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 {
opts options.Options
cfg config.Config
}
// NewNoGitScanner creates and returns a nogit scanner. This is used for scanning files and directories
func NewNoGitScanner(opts options.Options, cfg config.Config) *NoGitScanner {
ngs := &NoGitScanner{
opts: opts,
cfg: cfg,
}
// 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, error) {
var scannerReport Report
g, _ := errgroup.WithContext(context.Background())
paths := make(chan string, 100)
g.Go(func() error {
defer close(paths)
return filepath.Walk(ngs.opts.Path,
func(path string, fInfo os.FileInfo, err error) error {
if err != nil {
return err
}
if fInfo.Mode().IsRegular() {
paths <- path
}
return nil
})
})
leaks := make(chan Leak, 100)
for path := range paths {
p := path
g.Go(func() error {
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)
leak.File = p
leak.Rule = rule.Description
leak.Tags = strings.Join(rule.Tags, ", ")
if ngs.opts.Verbose {
leak.Log(ngs.opts.Redact)
}
leaks <- leak
}
}
f, err := os.Open(p)
if err != nil {
return err
}
scanner := bufio.NewScanner(f)
lineNumber := 0
for scanner.Scan() {
lineNumber++
for _, rule := range ngs.cfg.Rules {
line := scanner.Text()
if rule.AllowList.FileAllowed(filepath.Base(p)) ||
rule.AllowList.PathAllowed(p) {
continue
}
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)
leak.File = p
leak.LineNumber = lineNumber
leak.Rule = rule.Description
leak.Tags = strings.Join(rule.Tags, ", ")
if ngs.opts.Verbose {
leak.Log(ngs.opts.Redact)
}
leaks <- leak
}
}
return f.Close()
})
}
go func() {
g.Wait()
close(leaks)
}()
for leak := range leaks {
scannerReport.Leaks = append(scannerReport.Leaks, leak)
}
return scannerReport, g.Wait()
}
+75
View File
@@ -0,0 +1,75 @@
package scan
import (
"io/ioutil"
"path/filepath"
"github.com/zricethezav/gitleaks/v7/options"
"github.com/zricethezav/gitleaks/v7/config"
"github.com/go-git/go-git/v5"
log "github.com/sirupsen/logrus"
)
// ParentScanner is a parent directory scanner
type ParentScanner struct {
cfg config.Config
opts options.Options
}
// NewParentScanner creates and returns a directory scanner
func NewParentScanner(opts options.Options, cfg config.Config) *ParentScanner {
ds := &ParentScanner{
opts: opts,
cfg: cfg,
}
return ds
}
// Scan kicks off a ParentScanner scan. This uses the directory from --path to discovery repos
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)
if err != nil {
return scannerReport, err
}
for _, f := range files {
if !f.IsDir() {
continue
}
repo, err := git.PlainOpen(filepath.Join(ds.opts.Path, f.Name()))
if err != nil {
if err.Error() == "repository does not exist" {
log.Debugf("%s is not a git repository", f.Name())
continue
}
return scannerReport, err
}
if ds.cfg.Allowlist.RepoAllowed(f.Name()) {
continue
}
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 {
return scannerReport, err
}
scannerReport.Leaks = append(scannerReport.Leaks, repoReport.Leaks...)
scannerReport.Commits += repoReport.Commits
}
return scannerReport, nil
}
+116
View File
@@ -0,0 +1,116 @@
package scan
import (
"context"
"golang.org/x/sync/errgroup"
"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/go-git/go-git/v5/plumbing/storer"
log "github.com/sirupsen/logrus"
)
// RepoScanner is a repo scanner
type RepoScanner struct {
opts options.Options
cfg config.Config
repo *git.Repository
throttle *Throttle
repoName string
}
// NewRepoScanner returns a new repo scanner (go figure). This function also
// sets up the leak listener for multi-threaded awesomeness.
func NewRepoScanner(opts options.Options, cfg config.Config, repo *git.Repository) *RepoScanner {
rs := &RepoScanner{
opts: opts,
cfg: cfg,
repo: repo,
throttle: NewThrottle(opts),
repoName: getRepoName(opts),
}
return rs
}
// Scan kicks of a repo scan
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
}
cIter, err := rs.repo.Log(logOpts)
if err != nil {
return scannerReport, err
}
g, _ := errgroup.WithContext(context.Background())
commits = make(chan *object.Commit)
leaks := make(chan Leak)
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
}
if rs.cfg.Allowlist.CommitAllowed(c.Hash.String()) {
return nil
}
commitNum++
commits <- c
if c.Hash.String() == rs.opts.CommitTo {
return storer.ErrStop
}
return err
})
cIter.Close()
return 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() {
g.Wait()
close(leaks)
}()
for leak := range leaks {
scannerReport.Leaks = append(scannerReport.Leaks, leak)
}
scannerReport.Commits = commitNum
return scannerReport, g.Wait()
}
// SetRepoName sets the repo name
func (rs *RepoScanner) SetRepoName(repoName string) {
rs.repoName = repoName
}
+94
View File
@@ -0,0 +1,94 @@
package scan
import (
"encoding/csv"
"encoding/json"
"os"
"time"
"github.com/sirupsen/logrus"
"github.com/zricethezav/gitleaks/v7/config"
"github.com/zricethezav/gitleaks/v7/options"
"github.com/zricethezav/gitleaks/v7/version"
)
// Report is a container for leaks and number of commits scanned
type Report struct {
Leaks []Leak
Commits int
}
// 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()) {
logrus.Info("commits scanned: ", report.Commits)
}
if len(report.Leaks) != 0 {
logrus.Warn("leaks found: ", len(report.Leaks))
} else {
logrus.Info("No leaks found")
return nil
}
if opts.Report == "" {
return nil
}
if opts.Redact {
var redactedLeaks []Leak
for _, leak := range report.Leaks {
redactedLeaks = append(redactedLeaks, RedactLeak(leak))
}
report.Leaks = redactedLeaks
}
file, err := os.Create(opts.Report)
if err != nil {
return err
}
defer file.Close()
if opts.Report != "" {
switch opts.ReportFormat {
case "json":
encoder := json.NewEncoder(file)
encoder.SetIndent("", " ")
err = encoder.Encode(report.Leaks)
if err != nil {
return err
}
case "csv":
w := csv.NewWriter(file)
_ = w.Write([]string{"repo", "line", "commit", "offender", "leakURL", "rule", "tags", "commitMsg", "author", "email", "file", "date"})
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)})
}
w.Flush()
case "sarif":
s := Sarif{
Schema: "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0-rtm.5.json",
Version: "2.1.0",
Runs: []Runs{
{
Tool: Tool{
Driver: Driver{
Name: "Gitleaks",
SemanticVersion: version.Version,
Rules: configToRules(cfg),
},
},
Results: leaksToResults(report.Leaks),
},
},
}
encoder := json.NewEncoder(file)
encoder.SetIndent("", " ")
err = encoder.Encode(s)
if err != nil {
return err
}
}
}
return nil
}
+155
View File
@@ -0,0 +1,155 @@
package scan
import (
"fmt"
"time"
"github.com/zricethezav/gitleaks/v7/config"
)
//Sarif ...
type Sarif struct {
Schema string `json:"$schema"`
Version string `json:"version"`
Runs []Runs `json:"runs"`
}
//ShortDescription ...
type ShortDescription struct {
Text string `json:"text"`
}
//FullDescription ...
type FullDescription struct {
Text string `json:"text"`
}
//Rules ...
type Rules struct {
ID string `json:"id"`
Name string `json:"name"`
}
//Driver ...
type Driver struct {
Name string `json:"name"`
SemanticVersion string `json:"semanticVersion"`
Rules []Rules `json:"rules"`
}
//Tool ...
type Tool struct {
Driver Driver `json:"driver"`
}
//Message ...
type Message struct {
Text string `json:"text"`
}
//ArtifactLocation ...
type ArtifactLocation struct {
URI string `json:"uri"`
}
//Region ...
type Region struct {
StartLine int `json:"startLine"`
Snippet Snippet `json:"snippet"`
}
//Snippet ...
type Snippet struct {
Text string `json:"text"`
}
//PhysicalLocation ...
type PhysicalLocation struct {
ArtifactLocation ArtifactLocation `json:"artifactLocation"`
Region Region `json:"region"`
}
//Locations ...
type Locations struct {
PhysicalLocation PhysicalLocation `json:"physicalLocation"`
}
//Results ...
type Results struct {
Message Message `json:"message"`
Properties ResultProperties `json:"properties"`
Locations []Locations `json:"locations"`
}
//ResultProperties ...
type ResultProperties struct {
Commit string `json:"commit"`
Offender string `json:"offender"`
Date time.Time `json:"date"`
Author string `json:"author"`
Email string `json:"email"`
CommitMessage string `json:"commitMessage"`
Repo string `json:"repo"`
}
//Runs ...
type Runs struct {
Tool Tool `json:"tool"`
Results []Results `json:"results"`
}
func configToRules(cfg config.Config) []Rules {
var rules []Rules
for _, rule := range cfg.Rules {
rules = append(rules, Rules{
ID: rule.Description,
Name: rule.Description,
})
}
return rules
}
func leaksToResults(leaks []Leak) []Results {
var results []Results
for _, leak := range leaks {
results = append(results, Results{
Message: Message{
Text: fmt.Sprintf("%s secret detected", leak.Rule),
},
Properties: ResultProperties{
Commit: leak.Commit,
Offender: leak.Offender,
Date: leak.Date,
Author: leak.Author,
Email: leak.Email,
CommitMessage: leak.Message,
Repo: leak.Repo,
},
Locations: leakToLocation(leak),
})
}
return results
}
func leakToLocation(leak Leak) []Locations {
uri := leak.File
if leak.LeakURL != "" {
uri = leak.LeakURL
}
return []Locations{
{
PhysicalLocation: PhysicalLocation{
ArtifactLocation: ArtifactLocation{
URI: uri,
},
Region: Region{
StartLine: leak.LineNumber,
Snippet: Snippet{
Text: leak.Line,
},
},
},
},
}
}
+143
View File
@@ -0,0 +1,143 @@
package scan
import (
"os"
"path/filepath"
"github.com/go-git/go-git/v5"
"github.com/zricethezav/gitleaks/v7/config"
"github.com/zricethezav/gitleaks/v7/options"
)
// Scanner abstracts unique scanner internals while exposing the Scan function which
// returns a report.
type Scanner interface {
Scan() (Report, error)
}
// ScannerType is the scanner type which is determined based on program arguments
type ScannerType int
const (
typeRepoScanner ScannerType = iota + 1
typeDirScanner
typeCommitScanner
typeCommitsScanner
typeUnstagedScanner
typeFilesAtCommitScanner
typeNoGitScanner
typeEmpty
)
// NewScanner accepts options and a config which will be used to determine and create a
// new scanner which is then returned.
func NewScanner(opts options.Options, cfg config.Config) (Scanner, error) {
var (
repo *git.Repository
err error
)
// 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
st, err := scanType(opts)
if err != nil {
return nil, err
}
if st == typeDirScanner {
return NewParentScanner(opts, cfg), nil
}
// Clone or open a repo if we need it
if needsRepo(st) {
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 != "" && !opts.NoGit {
cfg, err = config.LoadRepoConfig(repo, opts.RepoConfigPath)
if err != nil {
return nil, err
}
}
switch st {
case typeCommitScanner:
c, err := obtainCommit(repo, opts.Commit)
if err != nil {
return nil, err
}
return NewCommitScanner(opts, cfg, repo, c), nil
case typeCommitsScanner:
commits, err := optsToCommits(opts)
if err != nil {
return nil, err
}
return NewCommitsScanner(opts, cfg, repo, commits), nil
case typeFilesAtCommitScanner:
c, err := obtainCommit(repo, opts.FilesAtCommit)
if err != nil {
return nil, err
}
return NewFilesAtCommitScanner(opts, cfg, repo, c), nil
case typeUnstagedScanner:
return NewUnstagedScanner(opts, cfg, repo), nil
case typeDirScanner:
return NewParentScanner(opts, cfg), nil
case typeNoGitScanner:
return NewNoGitScanner(opts, cfg), nil
default:
return NewRepoScanner(opts, cfg, repo), nil
}
}
func scanType(opts options.Options) (ScannerType, error) {
if opts.Commit != "" {
return typeCommitScanner, nil
}
if opts.Commits != "" || opts.CommitsFile != "" {
return typeCommitsScanner, nil
}
if opts.FilesAtCommit != "" {
return typeFilesAtCommitScanner, nil
}
if opts.Path != "" && !opts.NoGit {
if opts.CheckUncommitted() {
return typeUnstagedScanner, nil
}
_, err := os.Stat(filepath.Join(opts.Path))
if err != nil {
return typeEmpty, err
}
// check if path/.git exists, if it does, this is a repo scan
// if not this is a multi-repo scan
_, err = os.Stat(filepath.Join(opts.Path, ".git"))
if os.IsNotExist(err) {
return typeDirScanner, nil
}
return typeRepoScanner, nil
}
if opts.Path != "" && opts.NoGit {
_, err := os.Stat(filepath.Join(opts.Path))
if err != nil {
return typeEmpty, err
}
return typeNoGitScanner, nil
}
if opts.CheckUncommitted() {
return typeUnstagedScanner, nil
}
// default to the most commonly used scanner, RepoScanner
return typeRepoScanner, nil
}
func needsRepo(st ScannerType) bool {
if !(st == typeDirScanner || st == typeNoGitScanner) {
return true
}
return false
}
+797
View File
@@ -0,0 +1,797 @@
package scan
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"runtime"
"testing"
"github.com/zricethezav/gitleaks/v7/config"
"github.com/zricethezav/gitleaks/v7/options"
)
const testRepoBase = "../test_data/test_repos/"
func TestScan(t *testing.T) {
err := moveDotGit("dotGit", ".git")
if err != nil {
t.Fatal(err)
}
defer moveDotGit(".git", "dotGit")
tests := []struct {
description string
opts options.Options
wantPath string
wantErr error
wantScanErr error
emptyRepo bool
wantEmpty bool
}{
{
description: "test local repo one aws leak",
opts: options.Options{
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",
},
{
description: "test local repo one aws leak threaded",
opts: options.Options{
Threads: runtime.GOMAXPROCS(0),
Path: "../test_data/test_repos/test_repo_1",
Report: "../test_data/test_local_repo_one_aws_leak.json.got",
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_one_aws_leak.json",
},
{
description: "test non existent repo",
opts: options.Options{
Path: "../test_data/test_repos/no_repo_here",
ReportFormat: "json",
},
wantErr: fmt.Errorf("stat ../test_data/test_repos/no_repo_here: no such file or directory"),
emptyRepo: true,
},
{
description: "test local repo one aws leak allowlisted",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_1",
ReportFormat: "json",
ConfigPath: "../test_data/test_configs/aws_key_allowlist_python_files.toml",
},
wantEmpty: true,
},
{
description: "test local repo two leaks",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_2",
Report: "../test_data/test_local_repo_two_leaks.json.got",
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_two_leaks.json",
},
{
description: "test local repo two leaks from Commit",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_2",
Report: "../test_data/test_local_repo_two_leaks_commit_from.json.got",
ReportFormat: "json",
CommitFrom: "996865bb912f3bc45898a370a13aadb315014b55",
},
wantPath: "../test_data/test_local_repo_two_leaks_commit_from.json",
},
{
description: "test local repo two leaks to Commit",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_2",
Report: "../test_data/test_local_repo_two_leaks_commit_to.json.got",
ReportFormat: "json",
CommitTo: "996865bb912f3bc45898a370a13aadb315014b55",
},
wantPath: "../test_data/test_local_repo_two_leaks_commit_to.json",
},
{
description: "test local repo two leaks to from Commit",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_2",
Report: "../test_data/test_local_repo_two_leaks_commit_to_from.json.got",
ReportFormat: "json",
CommitFrom: "d8ac0b73aeeb45843319cdc5ce506516eb49bf7a",
CommitTo: "51f6dcf6b89b93f4075ba92c400b075631a6cc93",
},
wantPath: "../test_data/test_local_repo_two_leaks_commit_to_from.json",
},
{
description: "test local repo two leaks list Commits",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_2",
Report: "../test_data/test_local_repo_two_leaks_commit_range.json.got",
ReportFormat: "json",
Commits: "d8ac0b73aeeb45843319cdc5ce506516eb49bf7a,996865bb912f3bc45898a370a13aadb315014b55,17471a5fda722a9e423f1a0d3f0d267ea009d41c,51f6dcf6b89b93f4075ba92c400b075631a6cc93,b10b3e2cb320a8c211fda94c4567299d37de7776",
},
wantPath: "../test_data/test_local_repo_two_leaks_commit_range.json",
},
{
description: "test local repo two leaks file list commits",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_2",
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",
},
{
description: "test local repo two leaks globally allowlisted",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_2",
ConfigPath: "../test_data/test_configs/aws_key_global_allowlist_file.toml",
ReportFormat: "json",
},
wantEmpty: true,
},
{
description: "test local repo two leaks allowlisted",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_2",
ConfigPath: "../test_data/test_configs/aws_key_allowlist_files.toml",
ReportFormat: "json",
},
wantEmpty: true,
},
{
description: "test local repo three leaks dev branch with reportGroup set",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_3",
Report: "../test_data/test_local_repo_three_leaks_with_report_groups.json.got",
ConfigPath: "../test_data/test_configs/aws_key_with_report_groups.toml",
Branch: "dev",
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_three_leaks_with_report_groups.json",
},
{
description: "test local repo three leaks dev branch",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_3",
Report: "../test_data/test_local_repo_three_leaks.json.got",
ConfigPath: "../test_data/test_configs/aws_key.toml",
Branch: "dev",
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_three_leaks.json",
},
{
description: "test local repo branch does not exist",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_3",
Branch: "nobranch",
ReportFormat: "json",
},
wantScanErr: fmt.Errorf("could not find branch nobranch"),
},
{
description: "test local repo one aws leak single Commit",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_1",
Report: "../test_data/test_local_repo_one_aws_leak_commit.json.got",
Commit: "6557c92612d3b35979bd426d429255b3bf9fab74",
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_one_aws_leak_commit.json",
},
{
description: "test local repo one aws leak AND leak on python files",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_1",
Report: "../test_data/test_local_repo_one_aws_leak_and_file_leak.json.got",
ConfigPath: "../test_data/test_configs/aws_key_file_regex.toml",
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_one_aws_leak_and_file_leak.json",
},
{
description: "test owner path",
opts: options.Options{
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",
},
{
description: "test owner path allowlist repo",
opts: options.Options{
Path: "../test_data/test_repos/",
Report: "../test_data/test_local_owner_aws_leak_allowlist_repo.json.got",
ReportFormat: "json",
ConfigPath: "../test_data/test_configs/aws_key_local_owner_allowlist_repo.toml",
},
wantPath: "../test_data/test_local_owner_aws_leak_allowlist_repo.json",
},
{
description: "test entropy and regex",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_1",
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",
},
{
description: "test local repo four entropy alternative config",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_4",
Report: "../test_data/test_local_repo_four_alt_config_entropy.json.got",
RepoConfigPath: "gitleaks.toml",
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_four_alt_config_entropy.json",
},
{
description: "test local repo four entropy alternative config",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_1",
Report: "../test_data/test_regex_allowlist.json.got",
ConfigPath: "../test_data/test_configs/aws_key_aws_allowlisted.toml",
ReportFormat: "json",
},
wantEmpty: true,
},
{
description: "test owner path depth=2",
opts: options.Options{
Path: "../test_data/test_repos/",
Report: "../test_data/test_local_owner_aws_leak_depth_2.json.got",
ReportFormat: "json",
Depth: 2,
},
wantPath: "../test_data/test_local_owner_aws_leak_depth_2.json",
},
{
description: "test local repo five files at Commit",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_5",
Report: "../test_data/test_local_repo_five_files_at_commit.json.got",
FilesAtCommit: "a4c9fb737d5552fd96fce5cc7eedb23353ba9ed0",
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_five_files_at_commit.json",
},
{
description: "test local repo five files at latest Commit",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_5",
Report: "../test_data/test_local_repo_five_files_at_latest_commit.json.got",
FilesAtCommit: "latest",
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_five_files_at_commit.json",
},
{
description: "test local repo five at Commit",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_5",
Report: "../test_data/test_local_repo_five_commit.json.got",
Commit: "a4c9fb737d5552fd96fce5cc7eedb23353ba9ed0",
ReportFormat: "json",
ConfigPath: "../test_data/test_configs/generic.toml",
},
wantPath: "../test_data/test_local_repo_five_commit.json",
},
{
description: "test local repo five at latest Commit",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_5",
Report: "../test_data/test_local_repo_five_at_latest_commit.json.got",
Commit: "latest",
ReportFormat: "json",
ConfigPath: "../test_data/test_configs/generic.toml",
},
wantPath: "../test_data/test_local_repo_five_at_latest_commit.json",
},
{
description: "test local repo six filename",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_6",
Report: "../test_data/test_local_repo_six_filename.json.got",
ConfigPath: "../test_data/test_configs/regex_filename.toml",
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_six_filename.json",
},
{
description: "test local repo six filepath",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_6",
Report: "../test_data/test_local_repo_six_filepath.json.got",
ConfigPath: "../test_data/test_configs/regex_filepath.toml",
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_six_filepath.json",
},
{
description: "test local repo six filename and filepath",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_6",
Report: "../test_data/test_local_repo_six_filepath_filename.json.got",
ConfigPath: "../test_data/test_configs/regex_filepath_filename.toml",
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_six_filepath_filename.json",
},
{
description: "test local repo six path globally allowlisted",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_6",
Report: "../test_data/test_local_repo_six_path_globally_allowlisted.json.got",
ConfigPath: "../test_data/test_configs/aws_key_global_allowlist_path.toml",
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_six_path_globally_allowlisted.json",
},
{
description: "test local repo six leaks since date",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_6",
Report: "../test_data/test_local_repo_six_leaks_since_date.json.got",
ReportFormat: "json",
CommitSince: "2019-10-25",
},
wantPath: "../test_data/test_local_repo_six_leaks_since_date.json",
},
{
description: "test local repo two leaks until date",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_6",
Report: "../test_data/test_local_repo_six_leaks_until_date.json.got",
ReportFormat: "json",
CommitUntil: "2019-10-25",
},
wantPath: "../test_data/test_local_repo_six_leaks_until_date.json",
},
{
description: "test local repo four leaks timerange Commit",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_4",
Report: "../test_data/test_local_repo_four_leaks_commit_timerange.json.got",
ReportFormat: "json",
CommitSince: "2019-10-25T13:01:27-0400",
CommitUntil: "2019-10-25T13:12:32-0400",
},
wantPath: "../test_data/test_local_repo_four_leaks_commit_timerange.json",
},
{
description: "test local repo two allowlist Commit config",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_2",
Report: "../test_data/test_local_repo_two_allowlist_commits.json.got",
ConfigPath: "../test_data/test_configs/allowlist_commit.toml",
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_two_allowlist_commits.json",
},
{
description: "test local repo eight (merges)",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_8",
Report: "../test_data/test_local_repo_eight.json.got",
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_eight.json",
},
{
description: "test local repo nine",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_9",
Report: "../test_data/test_local_repo_nine_aws_leak.json.got",
ConfigPath: "../test_data/test_configs/large_with_global_allowlist_regex.toml",
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_nine_aws_leak.json",
},
{
description: "test dir one no git",
opts: options.Options{
Path: "../test_data/test_repos/test_dir_1",
Report: "../test_data/test_dir1_aws_leak.json.got",
ReportFormat: "json",
NoGit: true,
},
wantPath: "../test_data/test_dir1_aws_leak.json",
},
{
description: "test file with leak no git",
opts: options.Options{
Path: "../test_data/test_repos/test_dir_1/server.test.py",
Report: "../test_data/test_file1_aws_leak.json.got",
ReportFormat: "json",
NoGit: true,
},
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 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 local repo two allowlist Commit config",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_2",
Report: "../test_data/test_local_repo_two_allowlist_commits_files_at_commit.json.got",
ConfigPath: "../test_data/test_configs/allowlist_commit.toml",
ReportFormat: "json",
FilesAtCommit: "17471a5fda722a9e423f1a0d3f0d267ea009d41c",
},
wantPath: "../test_data/test_local_repo_two_allowlist_commits_files_at_commit.json",
wantEmpty: true,
},
{
description: "test local repo two global allowlist commit config",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_2",
Report: "../test_data/test_local_repo_two_global_allowlist_files_at_commit.json.got",
ConfigPath: "../test_data/test_configs/allowlist_global_files.toml",
ReportFormat: "json",
FilesAtCommit: "17471a5fda722a9e423f1a0d3f0d267ea009d41c",
},
wantPath: "../test_data/test_local_repo_two_global_allowlist_files_at_commit.json",
wantEmpty: true,
},
}
for _, test := range tests {
fmt.Println(test.description)
cfg, err := config.NewConfig(test.opts)
if err != nil {
t.Error(err)
}
scanner, err := NewScanner(test.opts, cfg)
if test.wantErr != nil {
if err == nil {
t.Fatalf("did not receive wantErr: %v", test.wantErr)
}
if err.Error() != test.wantErr.Error() {
t.Fatalf("wantErr does not equal err received: %v", err.Error())
}
continue
}
if err != nil {
t.Fatal(err)
}
scannerReport, err := scanner.Scan()
if test.wantScanErr != nil {
if err == nil {
t.Fatalf("did not receive wantErr: %v", test.wantScanErr)
}
if err.Error() != test.wantScanErr.Error() {
t.Fatalf("wantErr does not equal err received: %v", err.Error())
}
continue
}
if err != nil {
t.Fatal(err)
}
err = WriteReport(scannerReport, test.opts, cfg)
if err != nil {
t.Error(err)
}
if test.wantEmpty {
if len(scannerReport.Leaks) != 0 {
t.Errorf("wanted no leaks but got some instead: %+v", scannerReport.Leaks)
}
continue
}
if test.wantPath != "" {
err := fileCheck(test.wantPath, test.opts.Report)
if err != nil {
t.Error(err)
}
}
}
}
//
func TestScanUncommited(t *testing.T) {
moveDotGit("dotGit", ".git")
defer moveDotGit(".git", "dotGit")
tests := []struct {
description string
opts options.Options
wantPath string
wantErr error
wantScanErr error
emptyRepo bool
wantEmpty bool
fileToChange string
addition string
}{
{
description: "test scan local one leak",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_1",
Report: "../test_data/test_local_repo_one_aws_leak_uncommitted.json.got",
Unstaged: true,
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_one_aws_leak_uncommitted.json",
fileToChange: "server.test.py",
addition: " aws_access_key_id='AKIAIO5FODNN7DXAMPLE'\n\n",
},
{
description: "test scan local no leak",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_1",
Unstaged: true,
ReportFormat: "json",
},
wantEmpty: true,
fileToChange: "server.test.py",
addition: "nothing bad",
},
{
description: "test scan repo with no commits",
opts: options.Options{
Path: "../test_data/test_repos/test_repo_7",
Report: "../test_data/test_local_repo_seven_aws_leak_uncommitted.json.got",
Unstaged: true,
ReportFormat: "json",
},
wantPath: "../test_data/test_local_repo_seven_aws_leak_uncommitted.json",
},
}
for _, test := range tests {
var (
old []byte
err error
)
fmt.Println(test.description)
if test.fileToChange != "" {
old, err = ioutil.ReadFile(fmt.Sprintf("%s/%s", test.opts.Path, test.fileToChange))
if err != nil {
t.Error(err)
}
altered, err := os.OpenFile(fmt.Sprintf("%s/%s", test.opts.Path, test.fileToChange),
os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
t.Error(err)
}
_, err = altered.WriteString(test.addition)
if err != nil {
t.Error(err)
}
}
cfg, err := config.NewConfig(test.opts)
if err != nil {
t.Error(err)
}
scanner, err := NewScanner(test.opts, cfg)
if test.wantErr != nil {
if err == nil {
t.Fatalf("did not receive wantErr: %v", test.wantErr)
}
if err.Error() != test.wantErr.Error() {
t.Fatalf("wantErr does not equal err received: %v", err.Error())
}
continue
}
if err != nil {
t.Fatal(err)
}
scannerReport, err := scanner.Scan()
if test.wantScanErr != nil {
if err == nil {
t.Fatalf("did not receive wantErr: %v", test.wantScanErr)
}
if err.Error() != test.wantScanErr.Error() {
t.Fatalf("wantErr does not equal err received: %v", err.Error())
}
continue
}
if err != nil {
t.Fatal(err)
}
err = WriteReport(scannerReport, test.opts, cfg)
if err != nil {
t.Error(err)
}
if test.fileToChange != "" {
err = ioutil.WriteFile(fmt.Sprintf("%s/%s", test.opts.Path, test.fileToChange), old, 0)
if err != nil {
t.Error(err)
}
}
if test.wantEmpty {
continue
}
if test.wantPath != "" {
err := fileCheck(test.wantPath, test.opts.Report)
if err != nil {
t.Error(err)
}
}
}
}
func fileCheck(wantPath, gotPath string) error {
var (
gotLeaks []Leak
wantLeaks []Leak
)
want, err := ioutil.ReadFile(wantPath)
if err != nil {
return err
}
got, err := ioutil.ReadFile(gotPath)
if err != nil {
return err
}
err = json.Unmarshal(got, &gotLeaks)
if err != nil {
return err
}
err = json.Unmarshal(want, &wantLeaks)
if err != nil {
return err
}
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
}
_, err := os.Stat(fmt.Sprintf("%s/%s/%s", testRepoBase, dir.Name(), from))
if os.IsNotExist(err) {
continue
}
err = os.Rename(fmt.Sprintf("%s/%s/%s", testRepoBase, dir.Name(), from),
fmt.Sprintf("%s/%s/%s", testRepoBase, dir.Name(), to))
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
}
+264
View File
@@ -0,0 +1,264 @@
package scan
import (
"bytes"
"fmt"
"io"
"os/exec"
"path/filepath"
"strings"
"time"
"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"
"github.com/sergi/go-diff/diffmatchpatch"
)
// 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 {
opts options.Options
cfg config.Config
repo *git.Repository
repoName string
}
// NewUnstagedScanner returns an unstaged scanner
func NewUnstagedScanner(opts options.Options, cfg config.Config, repo *git.Repository) *UnstagedScanner {
us := &UnstagedScanner{
opts: opts,
cfg: cfg,
repo: repo,
repoName: getRepoName(opts),
}
return us
}
// Scan kicks off an unstaged scan. This will attempt to determine unstaged changes which are then scanned.
func (us *UnstagedScanner) Scan() (Report, error) {
var scannerReport Report
r, err := us.repo.Head()
if err == plumbing.ErrReferenceNotFound {
wt, err := us.repo.Worktree()
if err != nil {
return scannerReport, err
}
status, err := wt.Status()
if err != nil {
return scannerReport, err
}
for fn := range status {
workTreeBuf := bytes.NewBuffer(nil)
workTreeFile, err := wt.Filesystem.Open(fn)
if err != nil {
continue
}
if _, err := io.Copy(workTreeBuf, workTreeFile); err != nil {
return scannerReport, err
}
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.Redact)
}
scannerReport.Leaks = append(scannerReport.Leaks, leak)
}
}
}
return scannerReport, nil
} else if err != nil {
return scannerReport, err
}
c, err := us.repo.CommitObject(r.Hash())
if err != nil {
return scannerReport, err
}
// Staged change so the Commit details do not yet exist. Insert empty defaults.
c.Hash = plumbing.Hash{}
c.Message = ""
c.Author.Name = ""
c.Author.Email = ""
c.Author.When = time.Unix(0, 0).UTC()
prevTree, err := c.Tree()
if err != nil {
return scannerReport, err
}
wt, err := us.repo.Worktree()
if err != nil {
return scannerReport, err
}
status, err := gitStatus(wt)
if err != nil {
return scannerReport, err
}
for fn, state := range status {
var (
prevFileContents string
currFileContents string
filename string
)
if state.Staging != git.Untracked {
if state.Staging == git.Deleted {
// file in staging has been deleted, aka it is not on the filesystem
// so the contents of the file are ""
currFileContents = ""
} else {
workTreeBuf := bytes.NewBuffer(nil)
workTreeFile, err := wt.Filesystem.Open(fn)
if err != nil {
continue
}
if _, err := io.Copy(workTreeBuf, workTreeFile); err != nil {
return scannerReport, err
}
currFileContents = workTreeBuf.String()
filename = workTreeFile.Name()
}
// get files at HEAD state
prevFile, err := prevTree.File(fn)
if err != nil {
prevFileContents = ""
} else {
prevFileContents, err = prevFile.Contents()
if err != nil {
return scannerReport, err
}
if filename == "" {
filename = prevFile.Name
}
}
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(prevFileContents, currFileContents, false)
prettyDiff := diffPrettyText(diffs)
var diffContents string
for _, d := range diffs {
if d.Type == diffmatchpatch.DiffInsert {
diffContents += fmt.Sprintf("%s\n", d.Text)
}
}
lineLookup := make(map[string]bool)
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, ", ")
if us.opts.Verbose {
leak.Log(us.opts.Redact)
}
scannerReport.Leaks = append(scannerReport.Leaks, leak)
}
}
}
}
return scannerReport, err
}
// DiffPrettyText converts a []Diff into a colored text report.
// TODO open PR for this
func diffPrettyText(diffs []diffmatchpatch.Diff) string {
var buff bytes.Buffer
for _, diff := range diffs {
text := diff.Text
switch diff.Type {
case diffmatchpatch.DiffInsert:
_, _ = buff.WriteString("+")
_, _ = buff.WriteString(text)
case diffmatchpatch.DiffDelete:
_, _ = 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
}
+220
View File
@@ -0,0 +1,220 @@
package scan
import (
"bufio"
"fmt"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"github.com/zricethezav/gitleaks/v7/options"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/storage/memory"
log "github.com/sirupsen/logrus"
)
const (
diffAddPrefix = "+"
diffDelPrefix = "-"
diffLineSignature = " @@"
defaultLineNumber = 1
)
func obtainCommit(repo *git.Repository, commitSha string) (*object.Commit, error) {
if commitSha == "latest" {
ref, err := repo.Head()
if err != nil {
return nil, err
}
commitSha = ref.Hash().String()
}
return repo.CommitObject(plumbing.NewHash(commitSha))
}
func getRepoName(opts options.Options) string {
if opts.RepoURL != "" {
return filepath.Base(opts.RepoURL)
}
if opts.Path != "" {
return filepath.Base(opts.Path)
}
if opts.CheckUncommitted() {
dir, _ := os.Getwd()
return filepath.Base(dir)
}
return ""
}
func getRepo(opts options.Options) (*git.Repository, error) {
if opts.OpenLocal() {
if opts.Path != "" {
log.Infof("opening %s\n", opts.Path)
} else {
log.Info("opening .")
}
return git.PlainOpen(opts.Path)
}
if opts.CheckUncommitted() {
// open git repo from PWD
dir, err := os.Getwd()
if err != nil {
return nil, err
}
log.Debugf("opening %s as a repo\n", dir)
return git.PlainOpen(dir)
}
return cloneRepo(opts)
}
func cloneRepo(opts options.Options) (*git.Repository, error) {
cloneOpts, err := opts.CloneOptions()
if err != nil {
return nil, err
}
if opts.ClonePath != "" {
log.Infof("cloning... %s to %s", cloneOpts.URL, opts.ClonePath)
return git.PlainClone(opts.ClonePath, false, cloneOpts)
}
log.Infof("cloning... %s", cloneOpts.URL)
return git.Clone(memory.NewStorage(), nil, cloneOpts)
}
// depthReached checks if i meets the depth (--depth=) if set
func depthReached(i int, opts options.Options) bool {
if opts.Depth != 0 && opts.Depth == i {
log.Warnf("Exceeded depth limit (%d)", i)
return true
}
return false
}
// emptyCommit generates an empty commit used for scanning uncommitted changes
func emptyCommit() *object.Commit {
return &object.Commit{
Hash: plumbing.Hash{},
Message: "",
Author: object.Signature{
Name: "",
Email: "",
When: time.Unix(0, 0).UTC(),
},
}
}
// howManyThreads will return a number 1-GOMAXPROCS which is the number
// of goroutines that will spawn during gitleaks execution
func howManyThreads(threads int) int {
maxThreads := runtime.GOMAXPROCS(0)
if threads == 0 {
return 1
} else if threads > maxThreads {
log.Warnf("%d threads set too high, setting to system max, %d", threads, maxThreads)
return maxThreads
}
return threads
}
// 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.
func logOptions(repo *git.Repository, opts options.Options) (*git.LogOptions, error) {
var logOpts git.LogOptions
const dateformat string = "2006-01-02"
const timeformat string = "2006-01-02T15:04:05-0700"
if opts.CommitFrom != "" {
logOpts.From = plumbing.NewHash(opts.CommitFrom)
}
if opts.CommitSince != "" {
if t, err := time.Parse(timeformat, opts.CommitSince); err == nil {
logOpts.Since = &t
} else if t, err := time.Parse(dateformat, opts.CommitSince); err == nil {
logOpts.Since = &t
} else {
return nil, err
}
logOpts.All = true
}
if opts.CommitUntil != "" {
if t, err := time.Parse(timeformat, opts.CommitUntil); err == nil {
logOpts.Until = &t
} else if t, err := time.Parse(dateformat, opts.CommitUntil); err == nil {
logOpts.Until = &t
} else {
return nil, err
}
logOpts.All = true
}
if opts.Branch != "" {
ref, err := repo.Storer.Reference(plumbing.NewBranchReferenceName(opts.Branch))
if err != nil {
return nil, fmt.Errorf("could not find branch %s", opts.Branch)
}
logOpts = git.LogOptions{
From: ref.Hash(),
}
if logOpts.From.IsZero() {
return nil, fmt.Errorf("could not find branch %s", opts.Branch)
}
return &logOpts, nil
}
if !logOpts.From.IsZero() || logOpts.Since != nil || logOpts.Until != nil {
return &logOpts, nil
}
return &git.LogOptions{All: true}, nil
}
func optsToCommits(opts options.Options) ([]string, error) {
if opts.Commits != "" {
return strings.Split(opts.Commits, ","), nil
}
file, err := os.Open(opts.CommitsFile)
if err != nil {
return []string{}, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
var commits []string
for scanner.Scan() {
commits = append(commits, scanner.Text())
}
return commits, nil
}
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")
if i != -1 {
filePatchContent = filePatchContent[:i]
}
chunkStartLine := 0
currLine := 0
for _, patchLine := range strings.Split(filePatchContent, "\n") {
if strings.HasPrefix(patchLine, "@@") {
i := strings.Index(patchLine, diffAddPrefix)
pairs := strings.Split(strings.Split(patchLine[i+1:], diffLineSignature)[0], ",")
chunkStartLine, _ = strconv.Atoi(pairs[0])
currLine = -1
}
if strings.HasPrefix(patchLine, diffDelPrefix) {
currLine--
}
if strings.HasPrefix(patchLine, diffAddPrefix) && strings.Contains(patchLine, leak.Line) {
lineNumber := chunkStartLine + currLine
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
return lineNumber
}
}
currLine++
}
return defaultLineNumber
}
@@ -0,0 +1,18 @@
[
{
"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"
}
]
+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,18 @@
[
{
"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"
}
]
@@ -0,0 +1,15 @@
[[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"]
[rules.allowlist]
description = "if we encounter this commit for this rule, skip it"
commits = ["b10b3e2cb320a8c211fda94c4567299d37de7776"]
[allowlist]
commits = [
"17471a5fda722a9e423f1a0d3f0d267ea009d41c",
"996865bb912f3bc45898a370a13aadb315014b55"
]
@@ -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 = ['''.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$''']
+1 -1
View File
@@ -4,6 +4,6 @@
tags = ["key", "AWS"]
[[rules]]
description = "AWS Manager ID"
description = "AWS Access Key"
regex = '''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
tags = ["key", "AWS"]
@@ -0,0 +1,8 @@
[[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"]
[rules.allowlist]
description = "ignore sample regex md files"
files = ['''(.*)?md$''']
regexes = ['''ignore$''']
@@ -1,7 +1,7 @@
[[rules]]
description = "AWS Manager ID"
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.whitelist]]
[rules.allowlist]
description = "ignore python files"
file = '''(.*)?py$'''
files = ['''(.*)?py$''']
@@ -1,7 +1,7 @@
[[rules]]
description = "AWS Manager ID"
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.whitelist]]
regex = '''AKIAIO5FODNN7EXAMPLE.*'''
[rules.allowlist]
description = "ignore aws key"
regexes = ['''AKIAIO5FODNN7EXAMPLE.*''']
@@ -4,10 +4,11 @@
tags = ["key", "AWS"]
[[rules]]
description = "AWS Manager ID"
description = "AWS Access Key"
regex = '''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
tags = ["key", "AWS"]
[Global]
file = '''(.*)?py$'''
## this is an example of a rule that won't work
[[rules]]
description = "Python files"
fileRegex = "(?i)*.py"
@@ -1,8 +1,10 @@
[[rules]]
description = "AWS Manager ID"
description = "AWS Access Key"
regex = '''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
tags = ["key", "AWS"]
[whitelist]
[allowlist]
description = "ignore md files"
file = '''(.*)?md$'''
files = [
'''(.*)?md$'''
]
@@ -0,0 +1,10 @@
[[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 = "ignore config folders"
paths = [
'''config(uration)?'''
]
@@ -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 = "allowlist repo"
repos = [
'''test_repo_1'''
]
@@ -1,14 +0,0 @@
[[rules]]
description = "AWS Manager ID"
regex = '''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
tags = ["key", "AWS"]
[[rules.whitelist]]
description = "ignore md files"
file = '''(.*)?md$'''
[[rules.whitelist]]
description = "ignore this regex"
regex = '''ignore$'''
[[rules.whitelist]]
description = "ignore regex and md files"
regex = '''ignore$'''
file = '''(.*)?md$'''
@@ -4,10 +4,7 @@
tags = ["key", "AWS"]
[[rules]]
description = "AWS Manager ID"
regex = '''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
description = "AWS Access Key"
regex = '''AWS secret: ("?)((A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16})("?)'''
tags = ["key", "AWS"]
[Global]
message = '''?????????????'''
reportGroup = 2
+1 -1
View File
@@ -4,6 +4,6 @@
tags = ["key", "AWS"]
[[rules]]
description = AWS Manager ID"
description = AWS Access Key"
regex = '''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
tags = ["key", "AWS"]
@@ -4,7 +4,7 @@
tags = ["key", "AWS"]
[[rules]]
description = "AWS Manager ID"
description = "AWS Access Key"
regex = '''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
tags = ["key", "AWS"]
@@ -1,8 +1,8 @@
[[rules]]
description = "AWS Manager ID"
description = "AWS Access Key"
regex = '''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
tags = ["key", "AWS"]
[whitelist]
[allowlist]
description = "ignore md files"
file = '''???????'''
files = ['''???????''']
+4 -3
View File
@@ -1,7 +1,8 @@
[[rules]]
description = "entropy"
entropies = [
"4.3-4.1",
]
regex = '''['|"]([0-9a-zA-Z-._{}$\/\+=]{20,120})['|"]'''
tags = ["entropy"]
[[rules.Entropies]]
Min = "4.3"
Max = "4.1"
+4 -3
View File
@@ -1,7 +1,8 @@
[[rules]]
description = "entropy"
entropies = [
"4.3-x",
]
regex = '''['|"]([0-9a-zA-Z-._{}$\/\+=]{20,120})['|"]'''
tags = ["entropy"]
[[rules.Entropies]]
Min = "4.3"
Max = "x"
+4 -3
View File
@@ -1,7 +1,8 @@
[[rules]]
description = "entropy"
entropies = [
"x-4.3",
]
regex = '''['|"]([0-9a-zA-Z-._{}$\/\+=]{20,120})['|"]'''
tags = ["entropy"]
[[rules.Entropies]]
Min = "x"
Max = "4.1"
+5 -3
View File
@@ -1,7 +1,9 @@
[[rules]]
description = "entropy"
entropies = [
"1-8.9",
]
regex = '''['|"]([0-9a-zA-Z-._{}$\/\+=]{20,120})['|"]'''
tags = ["entropy"]
[[rules.Entropies]]
Min = "1.0"
Max = "8"
Group = "x"
@@ -0,0 +1,9 @@
[[rules]]
description = "entropy"
regex = '''['|"]([0-9a-zA-Z-._{}$\/\+=]{20,120})['|"]'''
tags = ["entropy"]
[[rules.Entropies]]
Min = "1.0"
Max = "8.5"
Group = "-2"
@@ -0,0 +1,9 @@
[[rules]]
description = "entropy"
regex = '''['|"]([0-9a-zA-Z-._{}$\/\+=]{20,120})['|"]'''
tags = ["entropy"]
[[rules.Entropies]]
Min = "1.0"
Max = "8.5"
Group = "2"
@@ -0,0 +1,9 @@
[[rules]]
description = "entropy"
regex = '''['|"]([0-9a-zA-Z-._{}$\/\+=]{20,120})['|"]'''
tags = ["entropy"]
[[rules.Entropies]]
Min = "1.0"
Max = "8.5"
Group = "0"
@@ -4,6 +4,6 @@
tags = ["key", "AWS"]
[[rules]]
description = "AWS Manager ID"
description = "AWS Access Key"
regex = '''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
tags = ["key", "AWS"]
+16
View File
@@ -0,0 +1,16 @@
title = "gitleaks config"
[[rules]]
description = "Asymmetric Private Key"
regex = '''-----BEGIN ((EC|PGP|DSA|RSA|OPENSSH) )?PRIVATE KEY( BLOCK)?-----'''
tags = ["key", "AsymmetricPrivateKey"]
[[rules]]
description = "Passwords"
regex = '''(?i)password=(?i)'''
tags = ["key", "Generic"]
[[rules]]
description = "secret secret.com"
regex = '''(?i)secret\.com'''
tags = ["key", "custom"]
+7 -4
View File
@@ -1,8 +1,11 @@
[[rules]]
description = "entropy"
entropies = [
"4.5-4.7",
"5.5-6.3",
]
regex = '''['|"]([0-9a-zA-Z-._{}$\/\+=]{40,120})['|"]'''
tags = ["entropy"]
[[rules.Entropies]]
Min = "4.5"
Max = "4.7"
[[rules.Entropies]]
Min = "5.5"
Max = "6.3"
+4
View File
@@ -0,0 +1,4 @@
[[rules]]
description = "Generic Credential"
regex = '''(?i)(api_key|apikey|secret|password|pass|pw|key)(.{0,20})?[0-9a-zA-Z]{16,45}'''
tags = ["key", "API", "generic"]
+16 -13
View File
@@ -122,24 +122,27 @@ title = "gitleaks config"
tags = ["key", "twilio"]
[[rules]]
description = "AWS Manager ID"
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.whitelist]]
[rules.allowlist]
description = "ignore common jenkins functions"
regex = '''whitelistme'''
file = '''(.*)?Jenkinsfile$'''
[[rules.whitelist]]
description = "ignore common jenkins functions2"
regex = '''whitelistme'''
file = '''(.*)?Jenkinsfile$'''
regexes = [
'''allowlistme'''
]
files = [
'''(.*)?Jenkinsfile$'''
]
# Global rules. This instructs gitleaks to ignore all .pem files or if a message with
[Global]
[[rules]]
description = "Files with keys and credentials"
file = '''(.*?)(pem)'''
message = '''somethingbad'''
[whitelist]
description = "image whitelists"
file = '''(.*?)(jpg|gif|doc|pdf|bin)$'''
[allowlist]
description = "File allowlists"
files = [
'''(.*?)(jpg|gif)$''',
'''(.*?)(doc|pdf|bin)$'''
]
@@ -0,0 +1,151 @@
title = "gitleaks config"
[[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 = "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 = "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", "LinkedIn"]
[[rules]]
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"]
[[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 = "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 = "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"]
[[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"]
[rules.allowlist]
description = "ignore common jenkins functions"
regexes = [
'''allowlistme'''
]
files = [
'''(.*)?Jenkinsfile$'''
]
[[rules]]
description = "Files with keys and credentials"
file = '''(.*?)(pem)'''
# Global allowlist
[allowlist]
description = "global allowlists"
files = [
'''(.*?)(jpg|gif)$''',
'''(.*?)(doc|pdf|bin)$'''
]
regexes = [
'''(.*?)gitleaks:allow'''
]
+4
View File
@@ -0,0 +1,4 @@
[[rules]]
description = "flag go"
file = '''(.*?)(md)$'''
tags = ["key", "extensions"]
+10 -5
View File
@@ -1,9 +1,14 @@
[[rules]]
description = "entropy and regex"
regex = '''(?i)key(.{0,20})?['|"][0-9a-zA-Z]{16,45}['|"]'''
entropies = [
"4.5-4.7",
"5.5-6.3",
]
regex = '''['|"]([0-9a-zA-Z-._{}$\/\+=]{20,120})['|"]'''
tags = ["entropy"]
[[rules.Entropies]]
Min = "4.5"
Max = "4.7"
Group = "1"
[[rules.Entropies]]
Min = "5.5"
Max = "6.3"
Group = "1"
@@ -0,0 +1,6 @@
[[rules]]
description = "Generic password"
regex = '''(?i)(password|token).{0,20}?\s*[:|=]\s*?(?-i)([0-9a-zA-Z\/+]{4,40})'''
file = '''.*\.ya?ml'''
tags = ["key", "Yml", "Yaml"]
@@ -0,0 +1,6 @@
[[rules]]
description = "AWS Access Key"
regex = '''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
path = '''config(guration)?'''
tags = ["key", "AWS"]
@@ -0,0 +1,7 @@
[[rules]]
description = "Generic password"
regex = '''(?i)(password|token).{0,20}?\s*[:|=]\s*?(?-i)([0-9a-zA-Z\/+]{4,40})'''
file = '''.*\.properties'''
path = '''config(guration)?'''
tags = ["key", "Yml", "Yaml"]
+34
View File
@@ -0,0 +1,34 @@
[
{
"line": " aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
"lineNumber": 5,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "",
"repo": "",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "",
"author": "",
"email": "",
"file": "../test_data/test_repos/test_dir_1/server.test.py",
"date": "0001-01-01T00:00:00Z",
"tags": "key, AWS"
},
{
"line": " aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
"lineNumber": 5,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "",
"repo": "",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "",
"author": "",
"email": "",
"file": "../test_data/test_repos/test_dir_1/server.test2.py",
"date": "0001-01-01T00:00:00Z",
"tags": "key, AWS"
}
]
+18
View File
@@ -0,0 +1,18 @@
[
{
"line": " aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
"lineNumber": 5,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "",
"repo": "",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "",
"author": "",
"email": "",
"file": "../test_data/test_repos/test_dir_1/server.test.py",
"date": "0001-01-01T00:00:00Z",
"tags": "key, AWS"
}
]
+308 -174
View File
@@ -1,10 +1,13 @@
[
{
"line": " aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
"lineNumber": 5,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "6557c92612d3b35979bd426d429255b3bf9fab74",
"repo": "test_repo_1",
"rule": "AWS Manager ID",
"repo": "test_repos",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "commit 1 with secrets\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
@@ -12,90 +15,15 @@
"date": "2019-10-24T09:29:27-04:00",
"tags": "key, AWS"
},
{
"line": " const AWSKEY = \"AKIALALEMEL33243OLIBE\"",
"offender": "AKIALALEMEL33243OLIB",
"commit": "f61cd8587b7ac1d75a89a0c9af870a2f24c60263",
"repo": "test_repo_2",
"rule": "AWS Manager ID",
"commitMessage": "rm secrets again\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"date": "2019-10-25T13:12:32-04:00",
"tags": "key, AWS"
},
{
"line": " const AWSSECRET = \"99432bfewaf823ec3294e231\"",
"offender": "SECRET = \"99432bfewaf823ec3294e231\"",
"commit": "f61cd8587b7ac1d75a89a0c9af870a2f24c60263",
"repo": "test_repo_2",
"rule": "Generic Credential",
"commitMessage": "rm secrets again\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"date": "2019-10-25T13:12:32-04:00",
"tags": "key, API, generic"
},
{
"line": " const AWSKEY = \"AKIALALEMEL33243OLIBE\"",
"offender": "AKIALALEMEL33243OLIB",
"commit": "b2eb34a61c988afd9b4aaa9dd58c8dd7d5f14dba",
"repo": "test_repo_2",
"rule": "AWS Manager ID",
"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": " const AWSSECRET = \"99432bfewaf823ec3294e231\"",
"offender": "SECRET = \"99432bfewaf823ec3294e231\"",
"commit": "b2eb34a61c988afd9b4aaa9dd58c8dd7d5f14dba",
"repo": "test_repo_2",
"rule": "Generic Credential",
"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, API, generic"
},
{
"line": "Here's an AWS secret: \"AKIALALEMEL33243OLIAE\"",
"offender": "AKIALALEMEL33243OLIA",
"commit": "996865bb912f3bc45898a370a13aadb315014b55",
"repo": "test_repo_2",
"rule": "AWS Manager ID",
"commitMessage": "committing pem\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"date": "2019-10-25T13:07:41-04:00",
"tags": "key, AWS"
},
{
"line": "Here's an AWS secret: \"AKIALALEMEL33243OLIAE\"",
"offender": "secret: \"AKIALALEMEL33243OLIAE\"",
"commit": "996865bb912f3bc45898a370a13aadb315014b55",
"repo": "test_repo_2",
"rule": "Generic Credential",
"commitMessage": "committing pem\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"date": "2019-10-25T13:07:41-04:00",
"tags": "key, API, generic"
},
{
"line": "Here's an AWS secret: \"AKIALALEMEL33243OLIAE\"",
"lineNumber": 3,
"offender": "AKIALALEMEL33243OLIA",
"commit": "17471a5fda722a9e423f1a0d3f0d267ea009d41c",
"repo": "test_repo_2",
"rule": "AWS Manager ID",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "wait this is actually adding an aws secret\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
@@ -104,24 +32,30 @@
"tags": "key, AWS"
},
{
"line": "Here's an AWS secret: \"AKIALALEMEL33243OLIAE\"",
"offender": "secret: \"AKIALALEMEL33243OLIAE\"",
"commit": "17471a5fda722a9e423f1a0d3f0d267ea009d41c",
"line": " const AWSKEY = \"AKIALALEMEL33243OLIBE\"",
"lineNumber": 4,
"offender": "AKIALALEMEL33243OLIB",
"commit": "b2eb34a61c988afd9b4aaa9dd58c8dd7d5f14dba",
"repo": "test_repo_2",
"rule": "Generic Credential",
"commitMessage": "wait this is actually adding an aws secret\n",
"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:01:27-04:00",
"tags": "key, API, generic"
"date": "2019-10-25T13:12:08-04:00",
"tags": "key, AWS"
},
{
"line": "\nHere's an AWS secret: AKIALALEMEL33243OLIAE",
"line": "Here's an AWS secret: AKIALALEMEL33243OLIAE",
"lineNumber": 3,
"offender": "AKIALALEMEL33243OLIA",
"commit": "b10b3e2cb320a8c211fda94c4567299d37de7776",
"repo": "test_repo_2",
"rule": "AWS Manager ID",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "adding aws key\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
@@ -129,90 +63,15 @@
"date": "2019-10-25T12:58:39-04:00",
"tags": "key, AWS"
},
{
"line": "const AWSKEY = \"AKIALALEMEL33243OLIAE\"",
"offender": "AKIALALEMEL33243OLIA",
"commit": "cd5eb8bef855f73c46b97b4c088badffdc40ebe9",
"repo": "test_repo_3",
"rule": "AWS Manager ID",
"commitMessage": "rm secrets\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"date": "2019-10-25T13:54:26-04:00",
"tags": "key, AWS"
},
{
"line": "const AWSSECRET = \"99432bfewaf823ec3294e231\"",
"offender": "SECRET = \"99432bfewaf823ec3294e231\"",
"commit": "cd5eb8bef855f73c46b97b4c088badffdc40ebe9",
"repo": "test_repo_3",
"rule": "Generic Credential",
"commitMessage": "rm secrets\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"date": "2019-10-25T13:54:26-04:00",
"tags": "key, API, generic"
},
{
"line": "const AWSKEY = \"AKIALALEMEL33243OLIAE\"",
"offender": "AKIALALEMEL33243OLIA",
"commit": "84ac4e80d4dbf2c968b64e9d4005f5079795bb81",
"repo": "test_repo_3",
"rule": "AWS Manager ID",
"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": "const AWSSECRET = \"99432bfewaf823ec3294e231\"",
"offender": "SECRET = \"99432bfewaf823ec3294e231\"",
"commit": "84ac4e80d4dbf2c968b64e9d4005f5079795bb81",
"repo": "test_repo_3",
"rule": "Generic Credential",
"commitMessage": "more secrets\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"date": "2019-10-25T13:54:08-04:00",
"tags": "key, API, generic"
},
{
"line": "AWS secret: \"AKIALALEMEL33243OLIAE\"",
"offender": "AKIALALEMEL33243OLIA",
"commit": "64cfcee9aad1c84581631636bfc54f2050718d1a",
"repo": "test_repo_3",
"rule": "AWS Manager ID",
"commitMessage": "rm secrets\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"date": "2019-10-25T13:36:22-04:00",
"tags": "key, AWS"
},
{
"line": "AWS secret: \"AKIALALEMEL33243OLIAE\"",
"offender": "secret: \"AKIALALEMEL33243OLIAE\"",
"commit": "64cfcee9aad1c84581631636bfc54f2050718d1a",
"repo": "test_repo_3",
"rule": "Generic Credential",
"commitMessage": "rm secrets\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"date": "2019-10-25T13:36:22-04:00",
"tags": "key, API, generic"
},
{
"line": "AWS secret: \"AKIALALEMEL33243OLIAE\"",
"lineNumber": 5,
"offender": "AKIALALEMEL33243OLIA",
"commit": "deea550dd6c7acaf0e59432600593533984a2125",
"repo": "test_repo_3",
"rule": "AWS Manager ID",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "dev branch\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
@@ -221,16 +80,291 @@
"tags": "key, AWS"
},
{
"line": "AWS secret: \"AKIALALEMEL33243OLIAE\"",
"offender": "secret: \"AKIALALEMEL33243OLIAE\"",
"commit": "deea550dd6c7acaf0e59432600593533984a2125",
"line": "const AWSKEY = \"AKIALALEMEL33243OLIAE\"",
"lineNumber": 3,
"offender": "AKIALALEMEL33243OLIA",
"commit": "84ac4e80d4dbf2c968b64e9d4005f5079795bb81",
"repo": "test_repo_3",
"rule": "Generic Credential",
"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": "17471a5fda722a9e423f1a0d3f0d267ea009d41c",
"repo": "test_repo_3",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "wait this is actually adding an aws secret\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"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_3",
"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,
"offender": "AKIALALEMEL33243OLIB",
"commit": "b2eb34a61c988afd9b4aaa9dd58c8dd7d5f14dba",
"repo": "test_repo_3",
"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": "AWS secret: \"AKIALALEMEL33243OLIAE\"",
"lineNumber": 5,
"offender": "AKIALALEMEL33243OLIA",
"commit": "deea550dd6c7acaf0e59432600593533984a2125",
"repo": "test_repo_4",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "dev branch\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"date": "2019-10-25T13:35:03-04:00",
"tags": "key, API, generic"
"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,
"offender": "AKIALALEMEL33243OLIB",
"commit": "b2eb34a61c988afd9b4aaa9dd58c8dd7d5f14dba",
"repo": "test_repo_4",
"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,
"offender": "AKIALALEMEL33243OLIA",
"commit": "17471a5fda722a9e423f1a0d3f0d267ea009d41c",
"repo": "test_repo_4",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "wait this is actually adding an aws secret\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"date": "2019-10-25T13:01:27-04:00",
"tags": "key, AWS"
},
{
"line": "aws_access_key_id='AKIAIO5FODNN7EXAMPLE'",
"lineNumber": 1,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "1f2a4abc47dabf991e6af6f9770867ce0ac1f360",
"repo": "test_repo_5",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "introduce secrets\n",
"author": "Zach Rice",
"email": "zrice@gitlab.com",
"file": "secrets.py",
"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_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": 3,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "98b6c7cb3fb29a5993c4c95c56a2dc53050b9247",
"repo": "test_repo_6",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "Adding some secrets in config folder\n\n",
"author": "Noel Algora",
"email": "noealgigu@gmail.com",
"file": "config/application.properties",
"date": "2020-02-24T14:13:15-05:00",
"tags": "key, AWS"
},
{
"line": "aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
"lineNumber": 2,
"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"
},
{
"line": "aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
"lineNumber": 6,
"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"
},
{
"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', #gitleaks:allow",
"lineNumber": 5,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "8d1fb60d2d80f0590f191ed5ace1e45ef780909a",
"repo": "test_repo_9",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "gitleaks allow secret\n",
"author": "Zach Rice",
"email": "zrice@gitlab.com",
"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"
}
]
@@ -0,0 +1,354 @@
[
{
"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,
"offender": "AKIALALEMEL33243OLIA",
"commit": "17471a5fda722a9e423f1a0d3f0d267ea009d41c",
"repo": "test_repo_2",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "wait this is actually adding an aws secret\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"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_2",
"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 = \"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,
"offender": "AKIALALEMEL33243OLIA",
"commit": "deea550dd6c7acaf0e59432600593533984a2125",
"repo": "test_repo_3",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "dev branch\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"date": "2019-10-25T13:35:03-04:00",
"tags": "key, AWS"
},
{
"line": " const AWSKEY = \"AKIALALEMEL33243OLIBE\"",
"lineNumber": 4,
"offender": "AKIALALEMEL33243OLIB",
"commit": "b2eb34a61c988afd9b4aaa9dd58c8dd7d5f14dba",
"repo": "test_repo_3",
"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,
"offender": "AKIALALEMEL33243OLIA",
"commit": "17471a5fda722a9e423f1a0d3f0d267ea009d41c",
"repo": "test_repo_3",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "wait this is actually adding an aws secret\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"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_3",
"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 = \"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": "AWS secret: \"AKIALALEMEL33243OLIAE\"",
"lineNumber": 5,
"offender": "AKIALALEMEL33243OLIA",
"commit": "deea550dd6c7acaf0e59432600593533984a2125",
"repo": "test_repo_4",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "dev branch\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"date": "2019-10-25T13:35:03-04:00",
"tags": "key, AWS"
},
{
"line": " const AWSKEY = \"AKIALALEMEL33243OLIBE\"",
"lineNumber": 4,
"offender": "AKIALALEMEL33243OLIB",
"commit": "b2eb34a61c988afd9b4aaa9dd58c8dd7d5f14dba",
"repo": "test_repo_4",
"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,
"offender": "AKIALALEMEL33243OLIA",
"commit": "17471a5fda722a9e423f1a0d3f0d267ea009d41c",
"repo": "test_repo_4",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "wait this is actually adding an aws secret\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"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,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "1f2a4abc47dabf991e6af6f9770867ce0ac1f360",
"repo": "test_repo_5",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "introduce secrets\n",
"author": "Zach Rice",
"email": "zrice@gitlab.com",
"file": "secrets.py",
"date": "2020-02-01T10:07:34-05:00",
"tags": "key, AWS"
},
{
"line": "aws_access_key_id=AKIAIO5FODNN7EXAMPLE",
"lineNumber": 3,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "98b6c7cb3fb29a5993c4c95c56a2dc53050b9247",
"repo": "test_repo_6",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "Adding some secrets in config folder\n\n",
"author": "Noel Algora",
"email": "noealgigu@gmail.com",
"file": "config/application.properties",
"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,
"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,
"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"
},
{
"line": "aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
"lineNumber": 6,
"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"
},
{
"line": " aws_access_key_id='AKIAIO5FODNN7EXAMPLE', #gitleaks:allow",
"lineNumber": 5,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "8d1fb60d2d80f0590f191ed5ace1e45ef780909a",
"repo": "test_repo_9",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "gitleaks allow secret\n",
"author": "Zach Rice",
"email": "zrice@gitlab.com",
"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"
}
]
@@ -0,0 +1,114 @@
[
{
"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": " 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": "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_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": 3,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "98b6c7cb3fb29a5993c4c95c56a2dc53050b9247",
"repo": "test_repo_6",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "Adding some secrets in config folder\n\n",
"author": "Noel Algora",
"email": "noealgigu@gmail.com",
"file": "config/application.properties",
"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', #gitleaks:allow",
"lineNumber": 5,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "8d1fb60d2d80f0590f191ed5ace1e45ef780909a",
"repo": "test_repo_9",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "gitleaks allow secret\n",
"author": "Zach Rice",
"email": "zrice@gitlab.com",
"file": "server.test.py",
"date": "2020-08-12T13:36:20-04:00",
"tags": "key, AWS"
}
]
+50
View File
@@ -0,0 +1,50 @@
[
{
"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,
"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"
},
{
"line": "aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
"lineNumber": 6,
"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"
}
]
@@ -0,0 +1,17 @@
[
{
"line": "more_secrets = '99432bfewaf823ec3294e231'",
"lineNumber": 7,
"offender": "secrets = '99432bfewaf823ec3294e231",
"commit": "a4c9fb737d5552fd96fce5cc7eedb23353ba9ed0",
"repo": "test_repo_5",
"rule": "Generic Credential",
"commitMessage": "even more secrets\n",
"author": "Zach Rice",
"email": "zrice@gitlab.com",
"file": "secrets.py",
"date": "2020-02-01T10:30:22-05:00",
"tags": "key, API, generic",
"operation": "addition"
}
]
@@ -0,0 +1,17 @@
[
{
"line": "more_secrets = '99432bfewaf823ec3294e231'",
"lineNumber": 7,
"offender": "secrets = '99432bfewaf823ec3294e231",
"commit": "a4c9fb737d5552fd96fce5cc7eedb23353ba9ed0",
"repo": "test_repo_5",
"rule": "Generic Credential",
"commitMessage": "even more secrets\n",
"author": "Zach Rice",
"email": "zrice@gitlab.com",
"file": "secrets.py",
"date": "2020-02-01T10:30:22-05:00",
"tags": "key, API, generic",
"operation": "addition"
}
]
@@ -0,0 +1,32 @@
[
{
"line": "aws_access_key_id='AKIAIO5FODNN7EXAMPLE'",
"lineNumber": 1,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "a4c9fb737d5552fd96fce5cc7eedb23353ba9ed0",
"repo": "test_repo_5",
"rule": "AWS Access Key",
"commitMessage": "even more secrets\n",
"author": "Zach Rice",
"email": "zrice@gitlab.com",
"file": "secrets.py",
"date": "2020-02-01T10:30:22-05:00",
"tags": "key, AWS",
"operation": "addition"
},
{
"line": "aws_access_key_id='AKIAIO5FODNN7EXAMPL2'",
"lineNumber": 4,
"offender": "AKIAIO5FODNN7EXAMPL2",
"commit": "a4c9fb737d5552fd96fce5cc7eedb23353ba9ed0",
"repo": "test_repo_5",
"rule": "AWS Access Key",
"commitMessage": "even more secrets\n",
"author": "Zach Rice",
"email": "zrice@gitlab.com",
"file": "secrets.py",
"date": "2020-02-01T10:30:22-05:00",
"tags": "key, AWS",
"operation": "addition"
}
]
@@ -0,0 +1,32 @@
[
{
"line": "aws_access_key_id='AKIAIO5FODNN7EXAMPLE'",
"lineNumber": 1,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "a4c9fb737d5552fd96fce5cc7eedb23353ba9ed0",
"repo": "test_repo_5",
"rule": "AWS Access Key",
"commitMessage": "even more secrets\n",
"author": "Zach Rice",
"email": "zrice@gitlab.com",
"file": "secrets.py",
"date": "2020-02-01T10:30:22-05:00",
"tags": "key, AWS",
"operation": "addition"
},
{
"line": "aws_access_key_id='AKIAIO5FODNN7EXAMPL2'",
"lineNumber": 4,
"offender": "AKIAIO5FODNN7EXAMPL2",
"commit": "a4c9fb737d5552fd96fce5cc7eedb23353ba9ed0",
"repo": "test_repo_5",
"rule": "AWS Access Key",
"commitMessage": "even more secrets\n",
"author": "Zach Rice",
"email": "zrice@gitlab.com",
"file": "secrets.py",
"date": "2020-02-01T10:30:22-05:00",
"tags": "key, AWS",
"operation": "addition"
}
]
@@ -1,28 +1,34 @@
[
{
"line": " Just moments after the Cessna's inquiry, a Twin Beech piped up on frequency, in a rather superior tone, asking for his ground speed. \"I have you at one hundred and twenty-five knots of ground spe",
"offender": "Entropy range [{P1:4.5 P2:4.7}]",
"commit": "d8ac0b73aeeb45843319cdc5ce506516eb49bf7a",
"line": "const AWSSECRET = \"99432bfewaf823ec3294e231\"",
"lineNumber": 4,
"offender": "\"99432bfewaf823ec3294e231\"",
"commit": "84ac4e80d4dbf2c968b64e9d4005f5079795bb81",
"repo": "test_repo_4",
"repoURL": "",
"leakURL": "",
"rule": "entropy",
"commitMessage": "removing secret.pem\n",
"commitMessage": "more secrets\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secret.pem",
"date": "2019-10-25T13:08:39-04:00",
"file": "secrets.md",
"date": "2019-10-25T13:54:08-04:00",
"tags": "entropy"
},
{
"line": " Just moments after the Cessna's inquiry, a Twin Beech piped up on frequency, in a rather superior tone, asking for his ground speed. \"I have you at one hundred and twenty-five knots of ground spe",
"offender": "Entropy range [{P1:4.5 P2:4.7}]",
"commit": "996865bb912f3bc45898a370a13aadb315014b55",
"line": " const AWSSECRET = \"99432bfewaf823ec3294e231\"",
"lineNumber": 5,
"offender": "\"99432bfewaf823ec3294e231\"",
"commit": "b2eb34a61c988afd9b4aaa9dd58c8dd7d5f14dba",
"repo": "test_repo_4",
"repoURL": "",
"leakURL": "",
"rule": "entropy",
"commitMessage": "committing pem\n",
"commitMessage": "adding another one\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secret.pem",
"date": "2019-10-25T13:07:41-04:00",
"file": "secrets.md",
"date": "2019-10-25T13:12:08-04:00",
"tags": "entropy"
}
]
@@ -0,0 +1,34 @@
[
{
"line": " const AWSKEY = \"AKIALALEMEL33243OLIBE\"",
"lineNumber": 4,
"offender": "AKIALALEMEL33243OLIB",
"commit": "b2eb34a61c988afd9b4aaa9dd58c8dd7d5f14dba",
"repo": "test_repo_4",
"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,
"offender": "AKIALALEMEL33243OLIA",
"commit": "17471a5fda722a9e423f1a0d3f0d267ea009d41c",
"repo": "test_repo_4",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "wait this is actually adding an aws secret\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
"file": "secrets.md",
"date": "2019-10-25T13:01:27-04:00",
"tags": "key, AWS"
}
]
@@ -1,15 +1,17 @@
[
{
"line": " aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
"lineNumber": 5,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "6557c92612d3b35979bd426d429255b3bf9fab74",
"repo": "test_repo_1",
"rule": "AWS Manager ID",
"repo": "test_repo_9",
"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"
"tags": "key, AWS",
"operation": "addition"
}
]
+4 -1
View File
@@ -1,10 +1,13 @@
[
{
"line": " aws_access_key_id='AKIAIO5FODNN7EXAMPLE',",
"lineNumber": 5,
"offender": "AKIAIO5FODNN7EXAMPLE",
"commit": "6557c92612d3b35979bd426d429255b3bf9fab74",
"repo": "test_repo_1",
"rule": "AWS Manager ID",
"repoURL": "",
"leakURL": "",
"rule": "AWS Access Key",
"commitMessage": "commit 1 with secrets\n",
"author": "zach rice",
"email": "zricer@protonmail.com",
Loaded 100 of 300 files, more files were not shown because too many files have changed in this diff. Show more