Compare commits

..
664 Commits
Author SHA1 Message Date
Zachary Rice 70028079b4 Update generate (#892)
* maintain parity with recent changes... need to create rule contributing guidelines

* missed on, ensure uniqueness in rule-id
2022-06-20 14:57:48 -05:00
Zachary Rice c14af5ffdf maintain parity with recent changes... need to create rule contributing guidelines (#891) 2022-06-20 14:14:14 -05:00
Craig SmithandCraig Smith 06b1396a2a Fix duplicate TOML Rules and IDs (#889)
* Remove duplicate rule

* Fix duplicate rule IDs

Co-authored-by: Craig Smith <5344211-craigmsmith@users.noreply.gitlab.com>
2022-06-20 08:49:47 -05:00
Zachary Rice 5d3f247d7d Update README.md 2022-06-16 08:11:20 -05:00
Zachary Rice 404dd8e0c0 Update gitleaks.yml 2022-06-15 17:20:08 -05:00
Zachary Rice 3a1ab48818 Update README.md 2022-06-12 13:25:03 -05:00
Zachary Rice f5c2b636f3 user accounts don't need gitleaks license 2022-06-07 11:48:43 -05:00
Zachary Rice b5ed7ff1b2 Update README.md 2022-06-02 17:47:36 -05:00
Zachary Rice 09007da395 Add gitleaks badge 2022-06-02 17:46:47 -05:00
Zachary Rice d51ce47d86 Create gitleaks.yml (#884) 2022-06-02 17:40:57 -05:00
Zachary Rice 6919447094 add link to gitleaks.io 2022-06-02 17:21:08 -05:00
fooliooandx c3b7932544 fix git unsafe directory (#883)
* fix git unsafe directory

fixes https://github.com/zricethezav/gitleaks/issues/846

* Update Dockerfile

Co-authored-by: x <>
2022-06-02 14:22:03 -05:00
Zachary Rice 82e409a434 Limit newlines regex (#881)
* improve regex to reduce fps with newlines

* remove version from regex and rely on stopwords instead

* add false positive for validation
2022-05-30 12:07:06 -05:00
Zachary 0eb57cbe4d add combo to stopwords, update cmd/generate 2022-05-28 11:47:17 -05:00
Don C. Bigler 3531887941 Fix generic-api-key detected erroneously (zricethezav#877) (#878) 2022-05-28 11:44:49 -05:00
Zachary Rice e9ebde73bc ignore end line when comparing generic rules (#879) 2022-05-28 09:49:27 -05:00
Zachary Rice 469cd22f61 updating generic regex and algoia regex (#875) 2022-05-25 08:00:10 -05:00
SimonGurney 93e72c215d feat: add algolia key support (#866)
* feat: add algolia key support

* feat: add algolia key to generator

* chore: update algolia regex to match gen
2022-05-25 07:39:20 -05:00
Dirkjan Bussink 865478bcdc Improve PlanetScale token detection (#874)
This improves the PlanetScale token detection. It add some flexibility
in length. There is no guarantee that the length is always 43 characters
(in fact, it's very likely to change a bit soon).

Additionally, it adds support for detecting oauth tokens as well.
2022-05-24 22:15:36 -05:00
Zachary Rice d6c0de7c85 Update README.md 2022-05-16 19:08:06 -05:00
Zachary Rice 0266ab8958 Adding JIT Security messages 2022-05-10 11:21:04 -05:00
Zachary Rice 6b7ab73a52 Update README.md 2022-05-02 10:21:40 -05:00
Zachary Rice 61ee7c58cc fix no-git bug (#859) 2022-04-27 21:48:56 -05:00
Zachary Rice ad7509e3b4 Removing private keyword from private key rule (#858) 2022-04-27 07:29:09 -05:00
Zachary Rice a62cc52aba nasty little bug (#853) 2022-04-23 11:18:56 -05:00
Zachary Rice f93e5dc844 adding a ton of stopwords to the generic rule only as that is the loudest rule (#851) 2022-04-21 17:01:21 -05:00
Zachary Rice 8481f0e9cd adding stopwords (#849)
* adding stopwords

* format readme, update default config
2022-04-21 08:31:58 -05:00
Zachary Rice 82f7d61593 Update dockerfile (#848)
* bump alpine and add default safe dir for git

* comment out safe dir fix

* update deps
2022-04-20 18:19:33 -05:00
Zachary Rice a42b32bdf1 fix EOL in secret suffix (#847)
* fix EOL in secret suffix

* allow quoted key value syntax
2022-04-20 17:55:07 -05:00
foolioo 79638b080c unpin docker version in pre-commit hook (#832)
eliminating inconsistency. e.g. for version 8.6.1, pre-commit hooks points to outdated version https://github.com/zricethezav/gitleaks/blob/c33ee3f25215635c0afbb210672779e7efb6f1d2/.pre-commit-hooks.yaml#L10
2022-04-19 21:33:23 -05:00
Zachary Rice 3474c58c9e Generate tps (#845)
* WIP

* simplify tp generation
2022-04-18 21:59:38 -05:00
Zachary Rice d8cd93cabe maybe fix out of bounds (#843) 2022-04-18 14:57:40 -05:00
Zachary Rice 48b79facfa optimize keywords (#841)
* optimize keywords

* use defaults for concurrency again
2022-04-16 17:41:40 -05:00
0xn3va e23f7f58f3 Update detect.go (#839) 2022-04-12 21:44:00 -05:00
Zachary Rice 606bb1a13b Standardize/alphabetize rules, add cmd/generate/config package (#840) 2022-04-12 21:40:48 -05:00
aeongdesu e784980515 fix ghcr.io typo in README.md (#835) 2022-04-08 08:05:06 -05:00
Zachary Rice c33ee3f252 normalize keyword check (#830) 2022-04-06 09:55:36 -05:00
Zachary Rice b0a958f55e Keyword (#825)
* wip keywords optimization

* update readme

* limit concurrency to 4

* update readme
2022-04-05 11:50:50 -05:00
foolioo 237b03af18 doc gitleaks-docker pre-commit hook (#819)
relates to #818
2022-03-29 20:05:28 -05:00
Zach Rice f348991d21 Merge branch 'master' of github.com:zricethezav/gitleaks 2022-03-29 11:54:05 -05:00
Zach Rice e0745adbd2 skip content checks for path only rules 2022-03-29 11:53:48 -05:00
foolioo 1ddc924a67 use official docker image as pre-commit hook (#818)
* use official docker image as pre-commit hook

* Update .pre-commit-hooks.yaml

* Update .pre-commit-hooks.yaml

* Update .pre-commit-hooks.yaml

* Update .pre-commit-hooks.yaml

* Update .pre-commit-hooks.yaml
2022-03-28 17:18:12 -05:00
Zach Rice 0b07625567 remove stopwords from global allowlist 2022-03-28 08:03:16 -05:00
Adam Shannon 0cabbf8ca8 detect: skip binary files with --no-git (#810) 2022-03-22 14:32:47 -05:00
Zachary Rice ba9e089e35 fixing a location off by one edge case for --no-git (#812) 2022-03-22 14:22:46 -05:00
Zachary Rice 31ff8677dd Update README.md 2022-03-21 13:36:29 -05:00
Zachary Rice 3e5e63956e Allow tag (#809)
* gitleaks:allow signature

* readd all tests

* fixing tests
2022-03-19 10:32:04 -05:00
Zachary Rice 57f9bc83d1 Stop words (#808)
* use regex for stopwords

* fix up regex

* rm stopwords
2022-03-19 09:31:38 -05:00
Zachary Rice 6e72472b60 Refactor detect, add entropy to all findings (#804)
Refactor `detect`, add `entropy` to all findings
2022-03-12 11:50:01 -06:00
Isaac Dawson 9326f35380 Escape - character in regex character groups (#802)
* fix char escape

* add test

* fix verbosity in make test
2022-03-07 08:33:06 -06:00
jetexe 19555579c8 adding go mod/sum to ignore (#797) 2022-03-01 10:16:17 -06:00
Greg JohnsonandGreg Johnson 60dd607312 GitLab pats may contain underscores as well as dashes (#794)
* gitlab pats may contain underscores as well as dashes

* include testdata index binary

Co-authored-by: Greg Johnson (codeEmitter) <gjohnson@gitlab.com>
2022-02-28 08:03:09 -06:00
Andrzej Amghar c3b799ec63 ignore k8s apiVersion in generic-api-key pattern (#760) 2022-02-22 17:00:20 -06:00
rui 4b6f4d0de5 build: updates for go1.17 (#769)
* build: remove `GO111MODULE` as it turned on by default

Signed-off-by: Rui Chen <rui@chenrui.dev>

* build: update for go1.17

* run test

Signed-off-by: Rui Chen <rui@chenrui.dev>

* lint: remove unused code
2022-02-22 16:49:45 -06:00
Zachary Rice fbfb3f591e allow non-last-element secret groups (#792) 2022-02-22 16:34:56 -06:00
Zachary Rice b91799aa18 fixing segfault when using a rule with only a path (#791)
* fixing segfault when using a rule with only a path

* DRYing
2022-02-22 15:58:03 -06:00
Luca Regne db1b54bf9f Fix: Typo in LinkedIn id (#789) 2022-02-22 09:49:55 -06:00
Ian Mckay e9529744f8 Fix vendor name casing, Flutterwave typo (#785) 2022-02-19 10:24:47 -06:00
Chris Wolf d1f642a9df Sarif results with empty rules now represents as [] instead of null/nil (#786) 2022-02-19 10:20:35 -06:00
Greg Myers 9261f1c47f Fix typos in README.md (#780)
comand ==> command
awsome ==> awesome
precendence ==> precedence
2022-01-29 12:08:55 -06:00
Zachary Rice 991223abab remove godoc text filtering (#763) 2022-01-07 10:59:51 -06:00
Zachary Rice 801d44a6e4 limit number of goroutines for historic scanning as well (#761) 2022-01-07 08:58:47 -06:00
Zach Rice 44d7d89e19 always write sarif results 2021-12-28 19:13:26 -06:00
Zachary Rice aae23acff3 limit goroutines on file scanning to avoid pegging them cores (#759) 2021-12-21 18:10:29 -06:00
Zachary Rice 705595aaf6 Adding Typeform to sponsorships 2021-12-21 08:26:47 -06:00
Zachary Rice 43ec22429f write a report regardless if leaks are present (#758) 2021-12-17 17:26:14 -06:00
Zachary Rice 36779df3bb stricter ionic regex for less fps (#757) 2021-12-17 10:13:44 -06:00
Zachary Rice 3d3d801729 fixing eof location bug (#756) 2021-12-17 09:49:12 -06:00
Zachary Rice 0f2ffee6f9 Adding Tines sponsorship to readme 2021-12-16 10:39:45 -06:00
Andrzej Amghar f4d37a2c0d fix regexp for aws_key and slack_webhook (#754) 2021-12-16 07:48:18 -06:00
Zachary Rice be5596df1d Update README.md 2021-12-12 13:38:43 -06:00
Zachary Rice e97f26bb5f better asciinema 2021-12-12 13:36:57 -06:00
Zachary Rice ae13c96df8 Update README.md 2021-12-12 13:19:58 -06:00
Zachary Rice d15dfdc387 Update README.md 2021-12-12 13:19:06 -06:00
Zach Rice 631d8dcf03 bump go-gitdiff 2021-12-12 12:23:59 -06:00
Zachary Rice 192b96289f do not fail on git rename warning (#750) 2021-12-12 11:43:03 -06:00
Zachary Rice b8141713e8 add pre-commit instructions (#749) 2021-12-10 18:08:31 -06:00
Zachary Rice 3fedf6f8e7 remove writing default config, introduce GITLEAKS_CONFIG (#746)
* remove writing default config, introduce GITLEAKS_CONFIG

* setting report format default to json, update readme
2021-12-09 09:21:17 -06:00
Zach Rice 6f6ebd454f fix off by one line number for --no-git 2021-12-08 15:04:32 -06:00
Zachary Rice ce42947cae fix deduplication issue caused by clobbered findings (#742)
* fix deduplication issue caused by clobbered findings

* fix index

* remove indexing, slow is better than wrong
2021-12-07 19:11:37 -06:00
Zach Rice 84e285e4ce ignore gitleaks.toml by default 2021-12-06 10:43:21 -06:00
Ben Randall 928c6a6043 Update pre-commit step to run gitleaks checks (#729)
* Fix pre-commit config.

* Debug output

* No debug and use redacted.

* Typo

* Add back staged.

* Update .pre-commit-hooks.yaml

* Update .pre-commit-hooks.yaml
2021-12-03 16:09:05 -06:00
Florian Greinacher 106897fdf0 fix: format dates in log in a portable way (#735)
The output of time.String() depends on the runtime environment and should only be used for debugging.

This commit ensures that a well-defined UTC time is written to the report.
2021-12-03 09:34:57 -06:00
Zachary Rice 98d5648f6e introducing secretGroup, the best group (#734)
* working on deduping

* my eyes... oh god my poor eyes

* more readme

* more readme

* more readme

* more readme and formatting
2021-12-02 20:04:36 -06:00
zricethezav 9358e84588 fix typo in readme 2021-12-02 13:55:43 -06:00
zricethezav 958c18f0b7 fix typo in config help 2021-12-02 13:44:39 -06:00
Zachary Rice 089639e9fb bump go-gitdiff (#731) 2021-12-02 08:29:38 -06:00
Zachary Rice 85afd767f7 Update README.md 2021-12-01 18:38:22 -06:00
Zachary Rice 38006fb93b Update README.md 2021-11-30 14:31:08 -06:00
Zachary Rice 9ae1def963 lil hack to avoid scans 'finishing' when git errors are present (#726) 2021-11-30 12:31:25 -06:00
Zachary Rice 6517900e5a Update README.md 2021-11-30 12:24:10 -06:00
Zachary Rice 5e51da600b use exit code 126 on 'unknown-flag' errors (#723) 2021-11-30 09:47:00 -06:00
Zachary Rice f0b8d26c99 Update README.md 2021-11-27 10:40:00 -06:00
Zachary Rice 1724591029 remove generic api key from default gitleaks config (#719) 2021-11-27 10:01:52 -06:00
Zachary Rice 80d29764a0 add global regex check (#717) 2021-11-25 11:17:03 -06:00
Zachary Rice f498b1d308 Commit debug log (#716)
* adding debug log for number of commits scanned

* change debug text

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

Provide correct version information for Sarif Reports

* Update test

Set version to correct Sarif version
2021-11-25 10:46:31 -06:00
Zachary Rice 4acd7a3c8d adding logic to ignore gitleaks config during scans (#710) 2021-11-24 20:27:19 -06:00
zricethezav a37822dffd remove --show-pulls from git log 2021-11-24 08:06:13 -06:00
Zachary Rice 1c6b28aa61 removing --simplify-merges and --show-pulls (#707) 2021-11-24 07:30:59 -06:00
Zachary Rice f15b4e408b Update README.md 2021-11-22 14:25:42 -06:00
Zachary Rice d5f9d2b5d2 Update README.md 2021-11-22 14:25:06 -06:00
zricethezav 67a7069bb8 trying again 2021-11-22 12:15:31 -06:00
zricethezav fd5d786538 override version in goreleaser 2021-11-22 12:11:02 -06:00
zricethezav c017b763f3 actually we gonna use git describe for docker build 2021-11-22 11:46:24 -06:00
zricethezav e796458763 remove sorting tags 2021-11-22 11:29:31 -06:00
zricethezav 2a9fbbc64d remove git fetch tag from docker build process, already available 2021-11-22 11:21:55 -06:00
zricethezav d6081d0cc4 actually use github.actor 2021-11-22 11:09:08 -06:00
zricethezav e6c3a495ce hardcode username to avoid redaction in action 2021-11-22 11:07:40 -06:00
Zachary Rice 93f292c3df Introducing v8.0.0 changes (#701)
* Introducing v8.0.0 changes
2021-11-22 10:43:51 -06:00
Ramon 780fb4a8f1 Merge pull request #653 from w0rmr1d3r/document_issue_638
Updating documentation on how to build the docker image (issue #638)
2021-10-28 08:50:04 +02:00
Ramon 0d9ab37ba4 Merge pull request #678 from ihassanyousaf/patch-1
fix possible typo in README.md `leaves` had been written instead of `leaks`
2021-10-28 08:48:52 +02:00
Ramon acffe44440 Merge pull request #658 from w0rmr1d3r/update_pre-commit_example
Update readme
2021-10-28 08:48:37 +02:00
M.Hassan Yousaf 178f78fa14 fix possible typo in README.md 2021-10-27 19:07:21 +02:00
Ramon 1ab1ae0e70 Merge pull request #673 from dirkaholic/fix/issue-672
Update regex for AWS secret key (issue #672)
2021-10-26 15:43:47 +02:00
Dirk Pahl 9f8ca91b8b Adjust AWS secret key rule 2021-10-26 15:09:42 +02:00
Dirk Pahl eec6c5a391 Fix tests with existing AWS secret keys 2021-10-26 13:29:36 +02:00
Dirk Pahl 714c0bef1e Update regex for AWS secret key 2021-10-26 12:35:35 +02:00
Ramon e9b699dda1 Merge branch 'master' of https://github.com/w0rmr1d3r/gitleaks into update_pre-commit_example
 Conflicts:
	README.md
2021-10-19 14:57:53 +02:00
Ramon 5afe59d2fa Merge pull request #662 from lucas-apd/patch-1
ADD_installation_from_bin
2021-10-19 14:54:11 +02:00
Lucas Alcântara 8adf27b1ea Update README.md 2021-10-19 09:50:39 -03:00
Ramon aecd32075e Merge pull request #665 from krsche/feature/fix-typo-in-readme
fix: typo in readme
2021-10-19 09:44:36 +02:00
Fabian Kirschner 290118cbbe fix: typo in readme 2021-10-14 22:12:24 +02:00
Lucas Alcântara d2e1e43a25 ADD_installation_from_bin
ADD_installation_from_bin
2021-10-13 16:41:36 -03:00
Ramon 2161ff358b Merge pull request #654 from nickrussler/master
Bump alpine to v3.14.2
2021-10-11 08:19:22 +02:00
Ramon f338bc584f Merge pull request #558 from AmitHofree/fix_default_config
Removed unnecessary backslashes in default config
2021-10-11 08:17:17 +02:00
Ramon e6a132bf4f Merge pull request #660 from GrahlmanMatthew/master
Fixed bug in extractLine function which was returning incorrect line # …
2021-10-11 08:16:57 +02:00
Ramon 8625cc30db Merge pull request #661 from danielorihuela/fix/loading-csv-reports-in-excel-with-commits-with-new-lines-characters
fix: csv report in excel
2021-10-11 08:16:33 +02:00
Matthew E. Grahlman 7cc3d7e467 Fix for Windows OS 2021-10-10 17:27:45 -04:00
Matthew E. Grahlman b8ff5eec73 Had to re-add testdata/ folder to project in order to get scan tests passing on Windows 2021-10-10 16:40:13 -04:00
Matthew E. Grahlman 36a4871585 Made changes to add support for cross-platform (os) testing as tests would pass on MacOS but no Windows 2021-10-10 16:38:24 -04:00
amith-legit c85ebbb2ba Try to revert index file 2021-10-10 22:51:54 +03:00
amith-legit 3a3e13c3b5 Added EOL to sample file 2021-10-10 22:51:44 +03:00
dani 14a00e1ffd chore: lint code 2021-10-10 12:47:46 +02:00
Ramon bd707fa9c4 fix: csv report in excel 2021-10-10 12:45:35 +02:00
Ramon 5e6b1840df Merge pull request #659 from chenrui333/add-apple-m1-support
build: add apple m1 support
2021-10-10 11:41:37 +02:00
Matthew E. Grahlman d8e3a694f2 Fixed bug in extractLine function which was returning incorrect line # when the line contains multiple vuln types 2021-10-09 10:55:39 -04:00
Rui Chen 05e3462025 build: add apple m1 support
Signed-off-by: Rui Chen <rui@chenrui.dev>
2021-10-08 16:53:52 -04:00
AmitHofree b83fe80968 Merge branch 'master' into fix_default_config 2021-10-08 22:26:35 +03:00
Ramon 5db0159c52 update readme 2021-10-08 15:05:34 +02:00
Nick Russler 5f87c4137c Bump alpine to v3.14.2
This alpine release includes fixes for openssl CVE-2021-3711 and CVE-2021-3712
2021-10-04 21:51:59 +02:00
Ramon ea94318ba3 updating documentation on how to build the docker image 2021-10-04 12:48:15 +02:00
Dustin Shimonoanddustin 3128789777 Add clarification in README.md that Go 1.16+ required. (#651)
* fix: fix the multiple scan executions from pre-commit hook

* docs: add clarification note about Go version required\

Ref 646

Co-authored-by: dustin <dustinshimono@gmail.com>
2021-09-30 11:00:21 -05:00
Dustin Shimonoanddustin 270207e5eb fix: fix the multiple scan executions from pre-commit hook (#649)
Co-authored-by: dustin <dustinshimono@gmail.com>
2021-09-30 09:49:09 -05:00
Ramon efe96640fc Merge pull request #645 from b-abderrahmane/patch-1
Fixed minor typo in Readme.md
2021-09-26 18:59:43 +02:00
b-abderrahmane 0137637c2c Fixed typo in Readme.md
Fixed description of main example rule
2021-09-25 11:14:52 +02:00
Zachary Rice 6adc045580 Simplify tests and continue on object not found errors (#633)
* adding files

* init better tests

* add basic .git

* more tests and test data

* nogit, unstaged tests

* removing unused testdata

* adding empty testdata

* rm gitmodules

* fixing tests

* remove with config

* adding with_config

* removing old test_data, updating config tests

* removing hooks in testdata repos
2021-09-09 11:46:31 -05:00
amith-legit 45c898c5ea Added a test for fixed Google and Square config 2021-09-09 11:29:34 +03:00
Ramon 95f8bd0daa Merge pull request #631 from EliSchleifer/elischleifer/fix-readme
Fix README link
2021-09-09 09:54:48 +02:00
Eli Schleifer 2cc2519302 Fix README link
Fix up readme link
2021-09-09 00:06:48 -07:00
amith-legit be13bba64c Merge branch 'master' into fix_default_config 2021-09-09 10:02:53 +03:00
Ramon 7111a698c0 Merge pull request #621 from Ido-DY/master
fix(git-symlink-new-repo): fix handling symbolic links in new git repo
2021-09-08 11:00:58 +02:00
Zachary Rice 8b9092a248 Create README.md 2021-09-07 15:29:56 -05:00
Ramon 0aa05133a9 Merge pull request #627 from w0rmr1d3r/update_documentation
Update documentation
2021-09-07 15:32:37 +02:00
Ramon 2952df5432 update documentation 2021-09-07 08:44:46 +02:00
Zachary Rice 541e26b067 Update FUNDING.yml 2021-09-06 16:51:38 -05:00
Eddie Austinandeddie-northcutt-wfp0 6018a6bb70 No longer generate empty reports (#577)
* return nil when no leaks found and lowercase report format option (#3)

* lowercase format options for consistency

* lowercase report format description

Co-authored-by: eddie-northcutt-wfp0 <eddie.northcutt.wfp0@statefarm.com>
2021-09-06 16:39:50 -05:00
Zachary Rice ca987b3842 Update README.md 2021-09-04 19:27:44 -05:00
Ido Markovitz 67f8d28d7f fix(git-symlink-files): fix handling symbolic links in unstaged changes 2021-09-04 11:10:53 +03:00
Ido-DY f88abe99d7 Merge branch 'zricethezav:master' into master 2021-09-04 10:36:26 +03:00
Zachary Rice 6ddf27c5c3 Fix premature exit for nogit scans, limit goroutines (#619)
* fix premature exit on nogit scan, actually limit concurreny for nogit

* removing files scanned log
2021-09-03 19:32:33 -05:00
Zachary Rice aadd9387b2 Create maintenance.md 2021-09-03 11:01:05 -05:00
Zachary Rice 0fd68c901d GitHub test (#617)
* drop travis

* remove travis

* rename, use example

* typo

* different syntax

* rename to test

* split test and build into two jobs

* add gosec job

* drop gosec for now
2021-09-03 08:41:17 -05:00
zricethezav 17a3943afe bump golang docker version 2021-09-02 14:44:58 -05:00
Zachary Rice abc73e2443 use embed pkg for default config, update deps (#616) 2021-09-02 14:42:14 -05:00
Zachary Rice 3c1751e5c4 Update alpine, use gitleaks user instead of root (#615)
* Updating alpine, use gitleaks user instead of root

* remove comments
2021-09-02 10:21:22 -05:00
Ido-DY a32ef6afc4 fix(git-symlink-commits): fix handling symbolic links in a git repository (#612) 2021-09-02 09:35:38 -05:00
rotem-cider 127df8a6f0 Updated RuleId in Sarif (#613) 2021-09-02 09:34:45 -05:00
Ivan Kalita aa91fd3e5e Fix default twitter rules (#614)
Regexps for default Twitter rules ("Twitter Secret Key" and "Twitter Client
ID") have a small flaw that make the default configuration vulnerable to
some false-positives.

I believe these rules should detect the cases like (SOME_CLIENT_ID should
be longer):
```
"twitter_client_id": "SOME_CLIENT_ID"
```

However, currently the twitter rules also detect the false positives for the
cases like:
```
someObj := twitter.NewObjectWithALongName()
config.Twitter.DomainAccessToken
```

I'm trying to address this issue the similar way it's done for facebook client
ids and AWS secret keys, where the secret is expected to be quoted.
2021-09-02 09:26:01 -05:00
Ido Markovitz c8e97d97f9 fix(git-symlink-commits): fix handling symbolic links in a git repository 2021-08-29 15:02:37 +03:00
Emma Sax 67e3603ba4 Remove --commit-from and --commit-to from docs (#605) 2021-08-20 12:18:27 -05:00
Tomasz Wierzchowski f62617d7a6 Update type in config example (#597) 2021-08-13 08:42:31 -05:00
Zachary Rice 9324184c24 Update README.md 2021-08-13 08:29:42 -05:00
Zachary Rice a80ce0d251 Update README.md 2021-07-29 17:40:34 -05:00
Ramon c1c4a93f98 Fix issue #523 (#561)
* updating documentation regarding issue #523

* improving README.md file
2021-05-10 11:39:09 -05:00
Norman Ziegner e74e6292ee Fix example in leaky-repo.toml (#559)
Signed-off-by: Norman Ziegner <norman.ziegner@ufz.de>
2021-05-07 09:08:03 -04:00
Tomy Guichard 25c3e92c2a SSH auth: Add custom username support (#536)
* Add support for custom username when using SSH auth
Previously, the user "git" was hard-coded
This commit also adds support for ssh:// URLs

* Add comment to explain username parsing
2021-05-05 12:30:12 -04:00
Zachary Rice 9ab424172d Update README.md 2021-05-05 09:22:56 -04:00
zricethezav 28fd47e170 Bump version for pre-commit 2021-05-05 09:10:47 -04:00
bplaxco 8250e40a75 Include offenderEntropy in the JSON output (#549)
* Pass the entropy data back to the Leak struct

Do this to make it easier to tune entropy checks and make decisions in
systems consuming the output.

~ B'ezrat Hashem ~

* Return negative number when entropy not checked

That way you can tell the difference between not checking or an
actual entropy level of 0

~ B'ezrat Hashem ~

* Make sure to handle range checks properly

Make sure to show when something had an entropy returned but was outside
range, or didn't have a hit at all, etc...

~ B'zrat Hashem ~

* Add a few doc strings

Follow the project's conventiona add a comment above the methods

~ B'ezrat Hashem ~

* Update tests and get them to pass

~ B'ezrat Hashem ~

* Remove checked in `.got` files

~ B'ezrat Hashem ~

* Add `*.got` to the `.gitignore`

Make sure the test output files aren't checked-in

~ B'ezrat Hashem ~
2021-05-03 20:22:20 -04:00
AmitHofree f735c9a5c9 Removed unnecessary backslashes 2021-05-02 15:47:05 +03:00
Pavel Shklovsky e7553b0168 Add pre-commit support (#552)
* Add pre-commit support

* Update README.md
2021-04-22 18:37:28 -04:00
Zachary Rice 12d276acd7 Bug 553 global allowlist (#554)
* add global file check

* rm whitespace
2021-04-22 18:07:07 -04:00
Pavel Shklovsky e6934bf0a5 Docker-based pre-commit configuration example (#551)
* Docker-based pre-commit configuration example

* Docker-based pre-commit configuration example
2021-04-21 12:58:03 -04:00
Zachary Rice 6f5ad9dc0b Update README.md 2021-04-12 11:07:28 -04:00
Zachary Rice a2019a4782 Update README.md 2021-04-09 14:21:15 -04:00
zricethezav 5d7b7718ec splitting out github rules and retabbing 2021-04-09 14:07:23 -04:00
Zachary Rice 190877a24b Pypi GitHub rules (#546)
* adding pypi and basic azure rules

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

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

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

* Update README.md

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

* Revert accidentally modified files

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

* better description

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

* Adding new repo for testing allowlisting

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

* Adding new repo for testing allowlisting

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

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

* fix comment

* correct copy/rename handling

* use 'git status' for unstaged changes
2020-12-04 18:08:27 -05:00
Zachary Rice d5e431e7d4 Update README.md 2020-12-03 17:20:46 -05:00
Zachary Rice 54ba3ec377 Update README.md 2020-12-03 17:09:59 -05:00
Zachary Rice 656ef1c9a7 Update README.md 2020-12-03 16:56:16 -05:00
zricethezav b8accd7273 rm unimplemented cleanpath option 2020-12-03 15:43:06 -05:00
zricethezav 238c31beaa Merge branch 'master' of github.com:zricethezav/gitleaks into master 2020-12-03 10:08:41 -05:00
Zachary Rice eb31190f31 Removing limiting line/offender length (#470) 2020-12-03 09:32:57 -05:00
zricethezav 389d45e380 Removing limiting line/offender length 2020-12-03 09:28:30 -05:00
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
Zachary Rice 725da55905 Merge pull request #289 from zricethezav/fix/3.0.2
recover on panic in patch generation, full filepath for report, versi…
2019-11-23 09:56:27 -05:00
zach rice cfac551ab8 recover on panic in patch generation, full filepath for report, version message if not built with LDFLAGS 2019-11-23 09:50:16 -05:00
Zachary Rice c559fdbf04 Merge pull request #287 from chenrui333/go-1.13.4
Bump golang and alpine to latest
2019-11-17 13:41:43 -06:00
Rui Chen e2ac47cd06 Bump alpine to v3.10 2019-11-17 14:37:04 -05:00
Rui Chen 8ef16d9efb Bump golang to v1.13.4 2019-11-17 14:36:37 -05:00
Zachary Rice b6f726654e Merge pull request #286 from zricethezav/v3.0.1
V3.0.1
2019-11-17 12:12:54 -06:00
zach rice 8cbb84c50f fixing tests 2019-11-17 11:56:16 -06:00
zach rice f3eac0c958 adding report-format to tests since we dont parse flags 2019-11-17 11:34:15 -06:00
zach rice 3211cfbbb1 fixing a bug, adding csv report option and leak caching 2019-11-17 11:13:34 -06:00
zach rice c6934f5eab updating readme 2019-11-15 13:52:05 -06:00
zach rice f8c054b879 gotta log the reponame on cloned repos 2019-11-15 13:35:34 -06:00
Zachary Rice ad2a64c82b Merge pull request #285 from zricethezav/v3
metadata sync
2019-11-15 13:26:46 -06:00
zach rice 9e0028fe73 Merge branch 'master' of github.com:zricethezav/gitleaks into v3 2019-11-15 13:22:18 -06:00
zach rice dfbd01a980 sync bug w/ timings 2019-11-15 13:22:03 -06:00
Zachary Rice 86737955de Merge pull request #281 from zricethezav/v3
V3
2019-11-14 07:38:34 -05:00
zach rice 7f0b027486 changing ret err to warning for owner-path scan 2019-11-13 20:03:51 -05:00
zach rice 4d04ea079f fixing test data 2019-11-12 22:32:15 -05:00
zach rice 6e1c41b536 more examples 2019-11-12 22:17:56 -05:00
zach rice 275232f8c8 examples and more tests 2019-11-12 20:08:17 -05:00
zach rice c8f9560aa3 adding pretty print option 2019-11-12 18:18:51 -05:00
zach rice 315ee56024 opts guard and removing severity 2019-11-12 15:18:13 -05:00
zach rice e446ba0738 fixing all golint and adding some more tests 2019-11-11 21:50:50 -05:00
zach rice 2ccd40677d adding alt config test 2019-11-10 19:28:02 -05:00
zach rice 41ef2a8cd2 rm hooks from test repos 2019-11-10 18:35:07 -05:00
zach rice d8acd1354f no more automatic deploys... doing it manually from now on 2019-11-10 17:18:52 -05:00
zach rice e28cfd1ad5 audit test import 2019-11-10 17:08:56 -05:00
zach rice e5f5e64cdb fixing module name, updating gitignore and travis 2019-11-10 17:05:36 -05:00
zach rice b55d88dc15 v3 work... lots of things 2019-11-10 13:30:43 -05:00
Zachary Rice f3360cbf66 Create FUNDING.yml 2019-10-13 10:39:08 -04:00
Zachary Rice 065b621604 Merge pull request #262 from siemens/feat/relax-repo-config
feat(repo-config): do not fail if no repo-config is available
2019-09-08 16:59:01 -04:00
Roger Meier fd87df475c feat(repo-config): do not fail if no repo-config is available 2019-09-08 20:49:29 +02:00
Zachary Rice c7b6792956 Merge pull request #261 from siemens/fix/sigsegv-repo-config
fix(repo-config): avoid SIGSEGV if there is no .gitleaks.toml
2019-09-08 08:57:49 -04:00
Roger Meier 1f2d11003d fix(repo-config): avoid SIGSEGV if there is no .gitleaks.toml 2019-09-08 13:07:17 +02:00
Zachary Rice 6432f11a6b Merge pull request #249 from siemens/bufferoverflow-patch-1
fix(gitleaks.toml): LinkedIn had a Twitter tag
2019-08-14 10:04:27 -04:00
Roger Meier 7d53fb5951 fix(gitleaks.toml): LinkedIn had a Twitter tag 2019-08-14 11:22:19 +02:00
Zachary Rice b9aa3ef97d readme 2019-08-13 08:54:33 -04:00
zach rice c271497ecb more generic api key regex 2019-08-02 17:16:20 -05:00
Zachary Rice e05c4645ac Merge pull request #246 from hughsaunders/regexes_in_sample
Regex whitelist example in sample config
2019-08-02 17:10:28 -05:00
Hugh Saunders 63d8e6e21b Regex whitelist example in sample config
Users looking to the sample config to discover possible options may
not notice that its possible to whitelist by regex. This commit adds
an example to aid discovery.

Related: conjurinc/ops#246
2019-08-02 21:15:15 +01:00
zach rice 5bd59b0d8c bump 2019-08-01 17:39:09 -05:00
zach rice 464e152783 rm vendor and changelog 2019-08-01 17:15:28 -05:00
Zachary Rice 91406b0c4c Merge pull request #184 from JCofman/feature/gitlabTokenSupport
Feature/gitlab token support
2019-08-01 17:13:44 -05:00
Zachary Rice 04e81270cb Merge pull request #244 from cfzlp/non-zero-exit-for-leaks
Return exit code 1 when leaks are found
2019-08-01 09:50:24 -05:00
Ixl123 69c6695765 resolve merge conflicts 2019-08-01 13:46:51 +02:00
Carlos Pereira 9e0e050f92 Return exit code 1 when leaks are found 2019-07-31 23:21:30 +02:00
Zachary Rice b2efcf36c8 Merge pull request #241 from manasmbellani/enhance_apikey_rule
constants.go(enhance): added an enhancement to include apikey without…
2019-07-15 21:54:16 -05:00
Manas Bellani ba39abfb19 constants.go(enhance): added an enhancement to include apikey without underscore as another detection for api keys that might be present in source code 2019-07-16 12:31:49 +10:00
zricethezav f47e1f71ee cleaner and bounded regex for generic keys and secrets 2019-07-14 15:16:46 -05:00
Zachary Rice 6d980b4eab Code cleaning (#240) 2019-07-10 10:32:51 -05:00
Zachary Rice ca18e8e2f6 Merge pull request #239 from cfzlp/fix-repo-config
Fix updating config from repo-config
2019-07-09 16:52:08 -05:00
Zachary Rice ec436d7b33 Merge pull request #230 from eargollo/windows-log
Fixed Windows output to be consistent with Linux output (colors)
2019-07-09 16:48:54 -05:00
Zachary Rice 38a511f6ba Merge pull request #236 from dorneanu/fix-commit-option
Implemented right way to scan for files in a commit (by using --commit)
2019-07-09 16:42:31 -05:00
Carlos Pereira 15ac1ffdd1 Fix updating config from repo-config 2019-07-07 14:57:57 +02:00
Victor Dorneanu eb977ba237 Differentiate between commits with parents and commits w/o parents 2019-06-19 14:28:10 +02:00
Victor Dorneanu 9a6b1c3bbb Implemented right way to scan for files in a commit (by using --commit) 2019-06-18 19:03:54 +02:00
Zachary Rice 95443e742c Merge pull request #231 from jesmg/master
Add new default rules
2019-06-18 07:56:55 -05:00
Jesús Marín 0c94db2d6b Improve rules 2019-06-18 10:27:50 +02:00
Jesús Marín 9808551eed Add new default rules 2019-06-17 15:04:33 +02:00
Eduardo Argollo b6fe5b08d3 Added colors to Windows output making it consistent with Linux one 2019-06-06 11:30:33 -07:00
Eduardo Argollo 5309811a09 Merge remote-tracking branch 'upstream/master' 2019-06-06 11:13:51 -07:00
zach rice 3b6c198715 fixing test 2019-06-02 20:55:24 -05:00
Zachary Rice 57bfa41b33 Merge pull request #224 from eargollo/overwrite-error
Solved bug on error being overwritten and not passed to postAudit, closes #223
2019-06-02 17:53:05 -05:00
Zachary Rice 474266c0b5 Merge pull request #226 from eargollo/windows-test
Adapt test message to run tests in Windows
2019-06-02 17:49:26 -05:00
Eduardo Argollo c891470344 Merge pull request #1 from eargollo/windows-test
Adapt test message to run tests in Windows
2019-05-31 09:56:44 -07:00
Eduardo Argollo e6004da801 Adapt test message to run tests in Windows 2019-05-31 09:52:21 -07:00
Eduardo Argollo e18b1a884a Updating expected error message 2019-05-30 15:11:37 -07:00
Eduardo Argollo faeb0914b2 Solving error on authentication 2019-05-30 15:09:45 -07:00
Eduardo Argollo d6578df998 Solved bug on error being overwritten and not passed to postAudit, closes #223 2019-05-28 15:35:10 -07:00
Zachary Rice f010513d17 Merge pull request #222 from martelo/modify-single-commit-audit
Modify single commit audit
2019-05-28 17:00:13 -05:00
Cassio Berra d4be9602e3 Removing other unnecessary references to opts.Commit 2019-05-18 01:24:18 +00:00
Cassio Berra 7676690697 Audit single commit without iterating through all commits 2019-05-18 01:02:46 +00:00
Zachary Rice f4b9b6d0b3 Merge pull request #204 from luispollo/fix-repo-path-logging
Fix logging of repo paths
2019-05-06 10:00:27 -05:00
Luis Pollo 7a3d155675 Fix logging of repo paths 2019-05-06 08:53:02 -05:00
Zachary Rice 68b6388ef7 Merge pull request #202 from MaxymVlasov/docs/improve_examples
Add more examples and improve README structure
2019-04-30 11:30:31 -05:00
MaxymVlasov 547e9768ec Add more examples and improve README structure 2019-04-30 18:08:58 +03:00
Zachary Rice 8608cf5b48 Merge pull request #198 from theoretick/patch-1
Update README - formatting fixes
2019-04-19 10:34:46 -05:00
Lucas Charles a08ddedb88 Update README - formatting fixes 2019-04-19 08:28:33 -07:00
Zachary Rice 398366a615 Merge pull request #196 from zricethezav/v2.0.0
V2.0.0
2019-04-16 19:00:12 -05:00
zach rice 7dfa3f2b48 last updates? 2019-04-16 18:13:24 -05:00
zach rice 2e7325ce03 adding some more tests during lunch 2019-04-16 12:04:00 -05:00
zach rice cb74386ef0 working on filetype filtering 2019-04-13 16:48:57 -05:00
zach rice 87d6c588a6 removing validating config, already handled 2019-04-13 14:09:16 -05:00
zach rice df8a2d35a8 cleaning up 2019-04-13 13:50:14 -05:00
zach rice c4da547503 fmt 2019-04-13 13:12:58 -05:00
zach rice 7bd55e33b5 working tests out 2019-04-13 12:30:00 -05:00
zach rice 256ace38d7 workin on new filters 2019-04-11 18:06:18 -05:00
zach rice 4c20d5d85c bumping version 2019-03-30 15:29:52 -05:00
Zachary Rice ac43c67a47 Merge pull request #190 from zricethezav/bug/singleCommit
Bug/single commit
2019-03-30 15:24:42 -05:00
zach rice d2d68a7e44 fixing commit target bug 2019-03-30 15:19:31 -05:00
zach rice 27aee19a35 Merge branch 'master' of github.com:zricethezav/gitleaks 2019-03-29 19:41:33 -05:00
Zachary Rice 2a6bd1636f Merge pull request #189 from zricethezav/debt/breakout
Debt/breakout
2019-03-29 19:27:54 -05:00
zach rice 7b82e29e7e updating readme 2019-03-29 19:23:28 -05:00
zach rice 4fd2f06a0d rm vendor and updating dockerfile 2019-03-29 19:12:28 -05:00
zach rice 8016dffe18 more travis 2019-03-29 18:52:38 -05:00
zach rice 10004da36f travis version 2019-03-29 18:46:45 -05:00
zach rice 633e06a7c7 updating travis 2019-03-29 18:39:52 -05:00
zach rice 660350c9b1 gofmt 2019-03-29 18:11:01 -05:00
zach rice 9122aa6cf4 updating changelog 2019-03-29 18:09:34 -05:00
zach rice 56c89866a2 spliting up email and author 2019-03-29 18:04:49 -05:00
zach rice f9be4e543a working on coverage 2019-03-29 15:54:42 -05:00
zach rice 042b82e2af more test work 2019-03-29 15:02:25 -05:00
zach rice 9176896742 getting testing there 2019-03-29 13:02:59 -05:00
zach rice 4ea0c66bec making good progress on tests 2019-03-28 21:28:16 -05:00
zach rice ae4542abf0 working on tests now 2019-03-28 13:13:26 -05:00
zach rice ac14d347de more refactoring 2019-03-28 10:42:43 -05:00
zach rice c2143c5843 repoDescriptor->repoInfo 2019-03-28 08:06:38 -05:00
zach rice e79ffc6ae8 go mod and even more work 2019-03-27 17:26:27 -05:00
zach rice a56c2341cf Merge branch 'master' of github.com:zricethezav/gitleaks 2019-03-26 16:11:12 -05:00
zach rice 1c14586cde main.go, need to work on tests next 2019-03-26 16:06:43 -05:00
zach rice 2b995fda44 init 2019-03-26 13:57:55 -05:00
Zachary Rice 5d68b48af3 Update README.md 2019-03-21 19:31:26 -05:00
Zachary Rice f90a00b564 Update README.md 2019-03-20 20:36:11 -05:00
Ixl123 4bc7c13310 Merge branch 'master' of https://github.com/zricethezav/gitleaks 2019-03-08 14:44:56 +01:00
Ixl123 771055fd59 add changelog and format go code 2019-03-08 14:38:47 +01:00
Jacob Cofman 75c70bf804 try this 2019-03-06 23:31:15 +01:00
Zachary Rice c5f34a6704 Update README.md 2019-03-06 08:45:30 -06:00
Zachary Rice 463871a307 Update README.md 2019-03-06 08:43:45 -06:00
Zachary Rice fa1080d066 Update README.md 2019-02-16 10:31:27 -06:00
Zachary Rice 52cfad1d08 Update CHANGELOG.md 2019-02-06 20:06:20 -06:00
Zachary Rice 9e294f5910 Merge pull request #179 from zricethezav/single-commit
Single commit
2019-02-06 20:04:54 -06:00
zach rice 9f8326de56 updating changelog and readme 2019-02-06 19:56:02 -06:00
zach rice 79c3f99165 fixing tests 2019-02-06 19:48:17 -06:00
zach rice d4925443c8 workin on tests 2019-02-06 19:20:52 -06:00
zach rice fa27d32bfe ref is not ordered... so the depth option is wack 2019-02-06 18:36:05 -06:00
zach rice 230a52e3e3 reworking logic 2019-02-06 17:50:55 -06:00
zach rice 15dedda59a single commit and bumping go-git version 2019-02-06 09:26:41 -06:00
Zachary Rice 3b45fb91e3 Update README.md 2019-01-21 18:18:57 +01:00
Zachary Rice f378319395 Merge pull request #174 from zricethezav/revert-169-add_support_for_branch
Revert "Add support for scanning single branch"
2019-01-13 17:17:49 -06:00
Zachary Rice 98173b3aa6 Revert "Add support for scanning single branch" 2019-01-13 17:13:36 -06:00
Zachary Rice 36340c8f2f Merge pull request #169 from AdamKobi/add_support_for_branch
Add support for scanning single branch
2019-01-13 10:20:37 -06:00
Adam Kobi 77b6d90a16 Merge branch 'master' into add_support_for_branch 2019-01-13 13:58:07 +02:00
Adam Kobi 6b3bd46fa8 added tests for scanning single branch and non-existing branch 2019-01-13 13:55:01 +02:00
Zachary Rice 8485f88158 Update README.md 2019-01-11 15:35:29 -06:00
Zachary Rice d2baa9e675 jk i am prepared. no more games 2019-01-06 19:57:46 -06:00
Zachary Rice 7fa9c802f5 u r not prepared 2019-01-06 18:47:43 -06:00
zach rice 8f1bc74e26 new logo 2019-01-06 18:29:02 -06:00
zach rice 8de38be418 bump version 2019-01-06 17:48:08 -06:00
Zachary Rice ec1ebd4686 Merge pull request #171 from milo-minderbinder/bugfix/report-memory
fix memory issue when writing json report (#168)
2019-01-06 08:58:43 -06:00
zach rice 81ddfbed88 dupe code 2019-01-06 08:52:31 -06:00
Zachary Rice 63814f1eaf Merge pull request #172 from zricethezav/repo-config
Repo config
2019-01-05 21:35:51 -06:00
zach rice 38a36add57 typo 2019-01-05 20:51:59 -06:00
zach rice 9e39927ac6 turning down logging, adding test 2019-01-05 20:50:17 -06:00
Milo Minderbinder 0ba9dda0f0 fix memory issue when writing json report (#168)
Previously, gitleaks.writeReport used json.MarshallIndent on the entire
set of leaks when writing json reports, which would cause failures due
to excessive memory consumption when a large number of leaks were
identified.

This PR addresses the problem by doing incremental marshalling and
writing of leaks to the report file, and reduces the memory footprint by
several GB in tests with >30k leaks.
2019-01-04 18:49:25 -05:00
zach rice a24f9a2c92 working on getting pinned config working 2019-01-04 16:31:33 -06:00
Zachary Rice f57158a893 Merge pull request #170 from syk0saje/master
Fix typo in recovery message
2019-01-04 09:45:13 -06:00
Pepe Bawagan 1e3bf42464 Fix typo in recovery message 2019-01-04 15:23:26 +08:00
Zachary Rice 9d6a75fbab Merge pull request #163 from milo-minderbinder/bugfix/whitelist-checks
fix file (#162) & line (#161) whitelist checks
2019-01-01 11:09:54 -06:00
Milo Minderbinder 6fa52ae7cc Merge remote-tracking branch 'upstream/master' into bugfix/whitelist-checks 2018-12-31 16:54:53 -05:00
Milo Minderbinder bb9c459a1a check whiteListFiles for root commit & GitHub PRs
add missing checks against `whiteListFiles` regexes for files in the
root/initial commit and in GitHub PRs (in `auditGithubPR` function)
2018-12-31 12:49:49 -05:00
Adam Kobi 432c76a9d9 added support for scanning only single remote branch 2018-12-29 13:10:39 +02:00
Adam Kobi 1cdf315bfa Merge pull request #1 from zricethezav/master
update upstream
2018-12-29 02:24:01 +02:00
Zachary Rice 777601a0ea Merge pull request #165 from camaya/update-report-creation
Write report only when leaks are found
2018-12-27 16:16:24 -06:00
Zachary Rice 35d170018e Merge pull request #166 from arbazkiraak/patch-1
Adding Stripe API Regex
2018-12-27 16:15:38 -06:00
Arbaz Hussain af2e99ef45 Adding Strip API Regex
```
→ printf '  Stripe.api_key = "Sk_test_41u0zAKbiWmTVhvHcS6gAjp9"
  Stripe.api_key = "sk_live_VhYCleaZwuUBGSFYFc7WUboz"
  STRIPE_PUBLIC_KEY= "pk_live_8sCPFZoLtW5pXuVHGrRKrROs"' | grep -P "(?i)(sk|pk)_(test|live)_[0-9a-zA-Z]{10,32}"
  Stripe.api_key = "Sk_test_41u0zAKbiWmTVhvHcS6gAjp9"
  Stripe.api_key = "sk_live_VhYCleaZwuUBGSFYFc7WUboz"
  STRIPE_PUBLIC_KEY= "pk_live_8sCPFZoLtW5pXuVHGrRKrROs"
```
2018-12-27 21:45:39 +05:30
Zachary Rice 734befb555 bad cops bad cops 2018-12-25 09:31:58 -06:00
Milo Minderbinder 64c8d618a2 fix file (#162) & line (#161) whitelist checks
* only check entropyRegexes and whiteListRegexes once per line, and only
  if regex or entropy leak type was found, since regex checks are expensive
* check whiteListFiles once for each FilePatch, instead of for
  every Chunk
2018-12-13 13:14:54 -05:00
Cristhian Amaya 92bb4ea6fc Write report only when leaks are found 2018-12-11 18:33:11 +01:00
zach rice 98b025da72 bumping versions 2018-12-10 09:48:48 -06:00
Zachary Rice af7717412f Merge pull request #159 from camaya/reduce-entropy-noise
Reduce noise when running entropy checks
2018-12-10 09:40:05 -06:00
Cristhian Amaya 68c2a18f6f Update entropy noise reduction
Instead of reducing noise by default, there's a new flag called
`--noise-reduction` to enable that.
2018-12-10 16:24:53 +01:00
Cristhian Amaya ea49078ffd Reduce noise when running entropy checks
When there's a word on a line with high entropy, we check if the line
matches any of the regex configured on the `lineregexes` element of the
`entropy` section. If so, it's marked as a leaked.

This has reduced the number of leaks found with entropy enabled up to
80%
2018-12-04 10:23:42 +01:00
Zachary Rice b902d7310a Merge pull request #158 from camaya/redact-only-secret-on-line
Change redacted behaviour on the line information
2018-11-30 08:55:22 -06:00
Zachary Rice 3591560b34 Merge pull request #157 from camaya/add-commit-date-prs
Add commit date to Github PRs checks
2018-11-30 08:54:56 -06:00
Cristhian Amaya 949029ca89 Change redacted behaviour on the line information
The line information sometimes contains useful context information so
instead of redacting the whole line, this change redacts only the
secret
2018-11-30 14:13:18 +01:00
Cristhian Amaya cde0894711 Add commit date to Github PRs checks 2018-11-30 13:37:18 +01:00
Zachary Rice 342e9f80db Merge pull request #152 from camaya/fix-github-pr-nilcheck
Fix Github PR checks error
2018-11-29 09:10:36 -06:00
Zachary Rice 96b0f4aab7 Merge pull request #153 from madblobfish/patch-1
Fix releases link in readme
2018-11-26 12:03:40 -06:00
madblobfish 3af6a546ac fix releases link in readme 2018-11-26 11:20:17 +01:00
Cristhian Amaya 6e086c4297 Fix Github PR checks error
When a commit contained a file without patch information like an added
empty file, there was a nil pointer dereference.
2018-11-23 11:56:49 +01:00
zricethezav db08fc0564 actually bump version in code >.< 2018-11-18 08:43:05 -06:00
zricethezav dbb6d4cc5f including camayas changes in version bump 2018-11-18 08:42:32 -06:00
Zachary Rice d0f44da4c2 Merge pull request #151 from AdamKobi/add_support_for_tokens
Add support for tokens
2018-11-18 08:39:17 -06:00
Zachary Rice cb6b01cc5d Merge pull request #149 from camaya/fix-files-whitelist-github-prs
Fix files whitelisting when checking Github PRs
2018-11-18 08:36:47 -06:00
Adam Kobi 392d79b9e2 added changes to changelog 2018-11-15 19:04:51 +02:00
Adam Kobi f8e609d4bf added case for when using oauth token for both listing and cloning repos 2018-11-15 17:58:54 +02:00
Zachary Rice 573bf46fd1 grammar not my best subject 2018-11-13 20:01:44 -06:00
Zachary Rice d65592bbcc Update to readme 2018-11-13 19:57:52 -06:00
Cristhian Amaya 169a137e7f Fix files whitelisting when checking Github PRs
Files whitelisting code was not executed when running the tool against a
Github PR so the config was ignored.

To avoid duplication, the whitelist files check has been moved to the `inspect`
function which is always executed.
2018-11-13 11:54:25 +01:00
Zachary Rice bd61f2d2f7 Merge pull request #148 from zricethezav/gitlab-support
bumping version, format, changelog, uhhhhhh, test... a single test
2018-11-12 21:45:35 -06:00
zricethezav 793bbc793f bumping version, format, changelog, uhhhhhh, test... a single test 2018-11-12 21:42:45 -06:00
Zachary Rice 4aa7be2dbf Merge pull request #120 from denwwer/115-gitlab
115 gitlab
2018-11-12 21:30:06 -06:00
Zachary Rice 35531233d9 Merge pull request #147 from zricethezav/fix/first-commit
fixing commit count
2018-11-07 19:39:52 -06:00
zach rice 54949bd62a fixing commit count 2018-11-07 19:33:39 -06:00
Zachary Rice e95a8a7158 Merge pull request #146 from zricethezav/fix/first-commit
Fix/first commit
2018-11-06 22:35:26 -06:00
zach rice de0a70a835 changelog 2018-11-06 22:27:52 -06:00
zach rice 9f8feca926 gotta check the root 2018-11-06 22:20:42 -06:00
Zachary Rice c50187559b Merge pull request #145 from camaya/update-report-commit-message
Remove break lines in commit messages
2018-11-06 08:31:49 -06:00
boris c2cf6327c2 adjusted perPage; minor fixes 2018-11-06 15:29:10 +02:00
boris 1ea773ddfb support self hosted GitLab server 2018-11-06 15:10:12 +02:00
boris 79a8983bac support GitLab 2018-11-06 15:10:09 +02:00
Cristhian Amaya 7d5ed837a4 Remove break lines in commit messages
Breaklines in a csv report caused issues when importing the data to an
spreadsheet application like LibreOffice Calc or Microsoft Excel.
2018-11-06 11:41:38 +01:00
Zachary Rice 60267523e9 Merge pull request #144 from zricethezav/fix/files
readding default whitelist
2018-11-05 18:18:36 -06:00
zach rice 8153da6e9c readding default whitelist 2018-11-05 18:13:50 -06:00
Zachary Rice 5f6fb388ec Merge pull request #141 from zricethezav/feature/default-all
removing branch from report
2018-11-03 11:37:21 -05:00
zach rice ba49396755 updating tests 2018-11-03 11:34:07 -05:00
zach rice 40240cb5ee removing branch from report 2018-11-03 11:31:18 -05:00
Zachary Rice bba926693e Merge pull request #140 from zricethezav/feature/default-all
Feature/default all
2018-11-03 11:29:20 -05:00
zach rice 9103834503 tests, readme, bumping version 2018-11-03 11:11:50 -05:00
zach rice 7e3c740592 audit all branches by default, memoize commits, smarter regexes 2018-11-02 21:58:09 -05:00
Zachary Rice 35a59746df Merge pull request #135 from camaya/add-commit-date-to-leaks
Add commit date to leaks
2018-10-28 12:21:45 -05:00
Cristhian Amaya 23b5ce3264 Add commit date to leaks 2018-10-28 17:13:59 +01:00
zach rice 03c53d2978 version again, pushing to master because thats what we do here 2018-10-27 19:30:58 -05:00
Zachary Rice 695449d73d Merge pull request #134 from zricethezav/fix/threads
Fix/threads
2018-10-27 19:25:40 -05:00
zach rice 6bad1e7194 updating readme 2018-10-27 19:20:11 -05:00
zach rice 77dec1461b better language 2018-10-27 19:19:07 -05:00
Zachary Rice 14d77f59d4 Merge pull request #133 from akerl/fix/slack-tokens
fix slack token format
2018-10-27 16:13:17 -05:00
Les Aker afb598cf15 update defaultConfig with new Slack regex 2018-10-27 14:29:25 -04:00
Les Aker b4c6fe92e0 fix slack token format 2018-10-27 10:56:41 -04:00
Zachary Rice f50577be1c Merge pull request #131 from zricethezav/feature/default-regex
Feature/default regex
2018-10-26 14:04:15 -05:00
zach rice c358ae9310 changelog 2018-10-26 13:53:16 -05:00
zach rice 9554258d02 adding some more defaults 2018-10-26 13:48:14 -05:00
Zachary Rice 95ee2cc30e Merge pull request #128 from r--w/patch-1
Telegram bot API token
2018-10-26 13:26:08 -05:00
Zachary Rice 79a35f0c27 Merge branch 'master' into patch-1 2018-10-26 13:25:58 -05:00
Zachary Rice 7a021cda9e Merge pull request #129 from harston/patch-1
Add PGP header
2018-10-26 13:25:23 -05:00
Zachary Rice 447f7a04cb Merge branch 'master' into patch-1 2018-10-26 13:24:55 -05:00
Zachary Rice e5b62cbc7c Merge pull request #130 from harston/patch-2
Add slack token
2018-10-26 13:24:01 -05:00
Paweł Gawinek 6739a34f74 Add slack token
Add Slack token from https://api.slack.com/docs/token-types 

#hactoberfest #greywizard
2018-10-26 10:36:04 +02:00
Paweł Gawinek e502bf29de Add PGP header
Add PGP private key header 

#hactoberfest #greywizard
2018-10-26 10:23:26 +02:00
Radoslaw Wesolowski 51b504bf99 Telegram bot API token
Format is described here: https://core.telegram.org/bots/api#authorizing-your-bot

#hactoberfest #greywizard
2018-10-26 09:22:18 +02:00
Zachary Rice 107d582e7b Merge pull request #127 from zricethezav/fix/ssh-logic
fixing default ssh logic
2018-10-25 12:38:14 -05:00
zach rice ea42ed406f fixing default ssh logic 2018-10-25 12:27:50 -05:00
Zachary Rice c869812875 Merge pull request #125 from ziyaddin/patch-1
Fix typos in docs
2018-10-24 17:06:43 -05:00
Zachary Rice 4f7ce9c195 Merge pull request #126 from zricethezav/fix/concurrency
Fix/concurrency
2018-10-24 16:56:01 -05:00
zach rice 847687a637 fixing test. travis doesnt have rsa id 2018-10-24 16:48:34 -05:00
zach rice 94389137e8 removing private opts 2018-10-24 16:00:15 -05:00
zach rice 98e6ba9378 better ssh handling 2018-10-24 15:49:53 -05:00
zach rice e288db29a8 fixing tests 2018-10-24 12:40:05 -05:00
zach rice 98aeee9b1d fixing everything 2018-10-24 12:28:54 -05:00
Ziyaddin Sadigov 45a2aa8495 Fix typos in changelog 2018-10-24 21:19:40 +04:00
Ziyaddin Sadigov 4b350987a1 Fix typos in contributing.md 2018-10-24 21:11:29 +04:00
Ziyaddin Sadigov 3b2b754fe5 Fix typos in readme 2018-10-24 21:06:08 +04:00
zach rice 64e7afea98 updating version 2018-10-24 09:58:39 -05:00
zach rice 16765c19cf adding go routines does not help performance much.... posting benchmarks soon 2018-10-24 09:38:36 -05:00
Zachary Rice 87d916fc24 Merge pull request #123 from zricethezav/update/whitelist-repo
whitelist repo update
2018-10-23 16:38:17 -05:00
zach rice 21b59fab5d whitelist repo update 2018-10-23 16:34:36 -05:00
Zachary Rice 9272e1e556 Merge pull request #122 from zricethezav/feature/entropy-range
entropy ranges
2018-10-22 18:55:51 -05:00
zach rice 0a51dabb17 entropy ranges 2018-10-22 18:51:01 -05:00
Zachary Rice 8c1cee4e00 Merge pull request #116 from keirans/documentation_updates
Documentation enhancements
2018-10-21 10:23:48 -05:00
Keiran Sweet 4d5315e2ca Documentation updates 2018-10-21 17:12:00 +11:00
zach rice 88cc9bb363 committing to master nbd.... stupid version 2018-10-20 17:28:42 -05:00
Zachary Rice 80e41ee14c Merge pull request #118 from zricethezav/feature/github-pr
Feature/GitHub pr
2018-10-20 18:27:27 -04:00
zach rice 23489f3f18 updating changelog, readme, some other things 2018-10-20 17:16:35 -05:00
zach rice a998ddc9d4 adding github.go, pagination working 2018-10-20 16:31:52 -05:00
zach rice 833963c1c1 refactoring 2018-10-19 19:53:10 -05:00
zach rice 4b11f87f80 poc seems to work fine w token auth 2018-10-19 15:58:25 -04:00
Zachary Rice 923dcf0311 Merge pull request #117 from camaya/update-help-option
Update help option
2018-10-17 08:42:20 -04:00
Cristhian Amaya 8896cf66cd Update help option
* Show program usage when no arguments are provided
* Exit program after the -h or --help options are used
2018-10-15 17:10:44 +02:00
zach rice df133ccaf8 version boss strikes AGAIN 2018-10-12 19:01:42 -05:00
Zachary Rice 23cd693d71 Merge pull request #114 from zricethezav/report
report filetype enforcement, time to audit
2018-10-12 18:53:38 -05:00
zach rice 524d81fde9 durafmt 2018-10-12 18:43:03 -05:00
zach rice d387f528c4 update lint 2018-10-12 18:22:33 -05:00
zach rice dcda26578b report filetype enforcement, time to audit 2018-10-12 17:01:24 -05:00
Zachary Rice 28639d3a49 Merge pull request #112 from zricethezav/wl-commit
look at prev commit too
2018-10-10 12:19:21 -05:00
zach rice 19e23c9cbe look at prev commit too 2018-10-10 12:16:31 -05:00
Zachary Rice 160015b872 Merge pull request #111 from zricethezav/fix-wl-commit
rm commit count log
2018-10-10 09:50:28 -05:00
zach rice abdf2c47f0 cl update 2018-10-10 09:43:01 -05:00
zach rice 8536f16ceb rm commit count log 2018-10-10 09:41:49 -05:00
Zachary Rice 6862c13bf7 Merge pull request #109 from zricethezav/depth
Depth
2018-10-09 21:13:29 -05:00
zach rice 9939c638ec better log 2018-10-09 21:07:49 -05:00
zach rice ed3a512b4b commit depth option 2018-10-09 21:01:56 -05:00
Zachary Rice 7c988c927d Merge pull request #107 from camaya/feature/add-entropy-checks
Add option to check string entropy
2018-10-09 18:46:21 -05:00
zach rice bde9af44ea merging, adding comments, updating flag description 2018-10-09 18:42:09 -05:00
Zachary Rice eee4d05642 Merge pull request #108 from camaya/fix-commit-option
Fix commit option
2018-10-09 16:18:54 -05:00
Cristhian Amaya 9144594d77 Fix commit option
The --commit option was being ignored becase the Close() function doesn't stop
the iterator.
According to the documentation:
https://godoc.org/gopkg.in/src-d/go-git.v4/plumbing/object#FileIter.ForEach
an ErrStop error should be send to stop it.
2018-10-09 16:49:16 +02:00
Cristhian Amaya 1cb15242fd Add option to check string entropy
Strings with high entropy have a good probability of being a secret.
2018-10-08 16:08:04 +02:00
Zachary Rice 08498600d1 Merge pull request #106 from zricethezav/exclude-fork
exclude fork
2018-10-07 18:42:42 -05:00
zach rice 88c0c7779b exclude fork 2018-10-07 18:39:17 -05:00
Zachary Rice 67454d109e Merge pull request #105 from zricethezav/wlrepo
Wlrepo
2018-10-07 18:26:18 -05:00
zach rice ce603c73b4 sample config opt 2018-10-07 18:19:43 -05:00
zach rice 55218fc8f8 whitelist repos 2018-10-07 18:09:10 -05:00
Zachary Rice 5d81c650e8 Merge pull request #104 from zricethezav/comments
Comments
2018-10-06 19:31:14 -05:00
zach rice 0726209172 maintenance 2018-10-06 19:27:54 -05:00
zach rice bfec8aca51 working on better comments 2018-10-05 22:55:19 -05:00
Zachary Rice a9b30edb06 Resource fix (#103)
* bumping version
2018-10-04 10:11:52 -05:00
Zachary Rice cc6d698e63 Resource fix (#102)
* no more dangling goroutines
2018-10-04 09:47:18 -05:00
Zachary Rice 2ba97d0fa3 fixing audit repo bug (#101)
* fixing audit repo bug

* bumping version
2018-10-02 12:34:05 -05:00
Zachary Rice d299b5aa7f Exitcode (#100)
* additional exit code, some more cleaning

* bump version
2018-10-02 09:52:18 -05:00
Zachary Rice 0a209b60a5 typo 2018-10-02 07:59:11 -05:00
Zachary Rice fe8c6271f2 panic plan (#99) 2018-10-01 22:44:25 -05:00
zach rice 42fb085684 pls contribute 2018-10-01 21:54:31 -05:00
Zachary Rice 3faec00bf9 Max go (#98)
* default max go, cleaning up for orgs

* bump changelog

* bumping version
2018-10-01 21:21:19 -05:00
Zachary Rice 93669f1ee8 Csv (#96)
* refactoring github audits, adding csv support

* working on tests

* test passing

* bumping version

* updating readme
2018-09-29 22:11:40 -05:00
Zachary Rice fad98cbde2 Single commit repo (#95)
* supporting repos with one commit
2018-09-26 14:28:22 -05:00
Zachary Rice 8eb28cbb4c Merge pull request #91 from zricethezav/audit_branch
test branch opt, bump changelog
2018-09-12 19:33:46 -05:00
zach rice 9dc9a8e62a bump version 2018-09-12 19:23:20 -05:00
zach rice e6caef0d94 test branch opt, bump changelog 2018-09-12 19:17:04 -05:00
Zachary Rice 5e289ed0cc Merge pull request #88 from Fabse333/master
Added Support for branches
2018-09-12 12:41:00 -05:00
Fabian Helfert d99588fe19 Fixed failure when Branch option is ommited 2018-08-23 14:07:25 +02:00
Fabian Helfert a7ccb7a9d1 Added Support for branches 2018-08-23 13:50:32 +02:00
Zachary Rice f32abb921d Merge pull request #87 from nenadstojanovikj/patch-1
Update description to reflect regex
2018-08-22 09:41:28 -05:00
Nenad Stojanovikj e8851c1f99 Update description to reflect regex 2018-08-21 21:08:44 +02:00
Zachary Rice f3a8359ac0 Merge pull request #86 from zricethezav/patch-err-check
Patch err check
2018-08-11 15:33:39 -04:00
zach rice 829e8fed8c up check to warning msg 2018-08-11 14:30:34 -05:00
zach rice c7e3605bff bump patch 2018-08-11 14:29:23 -05:00
zach rice c1774b1596 err check on patch 2018-08-11 14:27:51 -05:00
Zachary Rice 35710a7428 Merge pull request #85 from eripa/github-enterprise-support
GitHub Enterprise support + improved error handling. Fixes #84
2018-08-10 15:59:52 -04:00
Eric Ripa c7ba4d8bbf Update README and CHANGELOG with GitHub URL/Enterprise support detailed 2018-08-10 06:59:04 -07:00
Eric Ripa 5585e10933 Change error handling in getRepo functions
Instead of returning an empty list of repositories
and an error if any cloning operation fails, simply
store the error in the Repo instance and always
return all repos.

Then later on check for errors during the audit step.

By having this approach we don't prematurely exit
the scanning if there are problems during cloning,
such as if a repository is empty and fails to clone.
2018-08-09 11:31:29 -07:00
Eric Ripa 23d5bf0b51 Add simply TCP check during optsGuard to verify the given github URL 2018-08-09 11:30:55 -07:00
Eric Ripa b1c7a84fae Add initial support for GitHub Enterprise custom URLs 2018-08-09 10:04:41 -07:00
Zachary Rice 60801b336a Opt version (#80)
* version opt

* change-log
2018-07-22 20:16:09 -05:00
Zachary Rice 851ea3df3c anime 2018-07-22 10:03:01 -05:00
Zachary Rice d482577e47 copyleft 2018-07-21 14:19:28 -05:00
zricethezav 94e7a25b5b removing log formatting 2018-07-21 14:01:39 -05:00
zricethezav 45d94fa013 fixing commit patch order and report commit 2018-07-21 14:00:33 -05:00
zricethezav b4e69ecd37 clone and results logs, some additional comments 2018-07-21 13:29:32 -05:00
zricethezav 1c2820b4f1 Merge branch 'master' of github.com:zricethezav/gitleaks 2018-07-21 11:15:19 -05:00
zricethezav 215c3f6623 Simple slogan 2018-07-21 11:15:05 -05:00
1047 changed files with 11136 additions and 323628 deletions

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
# These are supported funding model platforms
github: [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
+16
View File
@@ -0,0 +1,16 @@
---
name: Maintenance request
about: Suggest an idea for this project
title: ''
labels: enhancement
assignees: ''
---
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**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?
+13
View File
@@ -0,0 +1,13 @@
name: gitleaks
on: [pull_request, push, workflow_dispatch]
jobs:
scan:
name: gitleaks
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- uses: gitleaks/gitleaks-action@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+49
View File
@@ -0,0 +1,49 @@
name: Create and publish a Docker image
on:
release:
types: [published]
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
build-and-push-image:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Log in to Docker Hub
uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9
with:
username: ${{ github.actor }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Log in to the Container registry
uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38
with:
images: |
zricethezav/gitleaks
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
- name: Build and push Docker image
uses: docker/build-push-action@ad44023a93711e3deb337508980b4b5e9bcdc5dc
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
+36
View File
@@ -0,0 +1,36 @@
name: Test
on:
push:
branches:
- "*"
pull_request:
branches:
- "*"
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.17
- name: Build
run: go build -v ./...
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.17
- name: Test
run: make test
+20
View File
@@ -0,0 +1,20 @@
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
*.DS_STORE
*.idea
*.got
gitleaks
build
# configs
.gitleaks.toml
cmd/generate/config/gitleaks.toml
# Test binary
*.out
dist/
+29
View File
@@ -0,0 +1,29 @@
project_name: gitleaks
builds:
- main: main.go
binary: gitleaks
goos:
- darwin
- linux
- windows
goarch:
- amd64
- "386"
- arm
- arm64
goarm:
- "6"
- "7"
ldflags:
- -s -w -X=github.com/zricethezav/gitleaks/v8/cmd.Version={{.Version}}
archives:
- builds: [gitleaks]
format_overrides:
- goos: windows
format: zip
replacements:
amd64: x64
386: x32
release:
prerelease: true
+11
View File
@@ -0,0 +1,11 @@
- id: gitleaks
name: Detect hardcoded secrets
description: Detect hardcoded secrets using Gitleaks
entry: gitleaks protect --verbose --redact --staged
language: golang
pass_filenames: false
- id: gitleaks-docker
name: Detect hardcoded secrets
description: Detect hardcoded secrets using Gitleaks
entry: zricethezav/gitleaks protect --verbose --redact --staged
language: docker_image
-19
View File
@@ -1,19 +0,0 @@
sudo: required
language: go
go:
- 1.9
services:
- docker
script:
- make test
after_success:
- export REPO=zricethezav/gitleaks
- export TAG=`if [ "$TRAVIS_BRANCH" == "master" ]; then echo "latest"; else echo $TRAVIS_BRANCH;
fi`
- if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then make deploy; fi
env:
global:
- secure: kUjq6Jgnm57V+ikDoYJ4IrFu4bLMHkaBb9uLtbQj0A545zZt4Dbooarnwqbfz2efqqMDZ9TXP6kN6677yWm0DyvFOCYx/Xq2innnVbBJczQciEUb5PI/9fcmLOfTe/QgGNi0GZOCdIOGlki2sbKxob6tTOUsm52ugRSJU92cXkX8w+Gzc6pC6fAb4moLE2QpwK1xWDHm2sHiZYExpBOH8eidSH5VPGVdNE9QmUA/FwwJ9NFGsZ8BgWCJPy7IJreyixsv2nNpiZNHoj0UgKe4wylzceu4sG/yQDIYk3fLVWBXSm/nSA17QYIjVMzQFjSAVC5dRqzq8HzFYiAYLKzkoOtrbBqEGtXzYZMN6yC8zEedk9gX6P6mvGpWYBy280uumcpGl6eoKYj5ke2H6kfcCUhMNTGZP17nmnTa1KFLAz1nxB1jfJwwO6v1l+xdytju5yAhm049Af7VyDM5GmE2x5ha48uKvK7wHtv+IKiZbbcR9ExsXvm21+7NVjQvRPzAw4/Sor9SG/yjoA/Sf7e4evy1w3fALv4WlaSisj5Yalmv7mzeeFZaIB7EIq6OryeRld2Rr1MZwwhZgIs7+SWwpjKfwhkfLVEUvSWCdnS2tnTydK6R6OFxfG5TGfR/WHooXLHEv5gMuKhUu/CqnbLyvI+8IOH2ybz2AtZWjf5n7oY=
- secure: cIxKSkBNkPFAn243eHtwHJb8z6Uty1cZ43ZK/UABjwJoSrhu/roK4soqdZLwdVRA/0QswAlp6AC25Zs3ngLKGxxFHoeB8Tx6VLanE1zoi8OT0I2KbT92FdrLV4HlcRshKZtTFoTCfgVKPnWNKC+hil97CQzQPGRpZLBSfNefk5uCMnQiAzaJ5lyWPx+sjLHzpVlGA6aQx9ZeBQqngQJoDHKc0K3hKwug4h9mkkhyaYE3kgxtsdOYlHvOtQgVk+Zih5uW7ABOQCyAOaQVipXBC+uiuNf2DeAuGDaX69DTRKqPzuIasbhwyGqlfsr2JeofEWgZGmTaWGKMi03hnIY+U9+lHjygBW1qqVglODboouUrV3LwER9kqrT+ZFTM5Ca8VB+Gx5khkknbjWd06jpzRQxNXdukYN89kEaAHkBH844G99pMDqcZ32lHK7lpCu8n1H/Liz3ygoV6ScJXnYAP6y9rrd3bb9KEmnKhmFacVLRIAUw1vN/cgspJpl/Mk6s5rvGwsbQih1OxGyooOLxGjEGWqVDFgHFtyiwX9s9kT+hNTwKgbhp7Ragk/QuDYUPZ3Vum7HoiNPS9KpQNstLvDckdtd8h13JIw6nX+xdWbNKjjdYbAZRstJHUROQtNq3XdWNQ9YjqbCoybaxCOwOUTwOiTSWNKXjTFbFI5mR/ZO0=
- COMMIT=${TRAVIS_COMMIT::8}
- secure: o6uPX071qGRKgOQmitxiDr1j+KRW8W6ru0wmKNBFuUlZvQudwCUZMnVfk6OeofT1IgLCHmLS8ST81cTyeXqOQhYVZrlxTmEUpDHHRTu6dOj3eqRzdJow1LIWNpw5xfOaqXUdQ8+SQ47ZeSFapsmaY9oeRDvSJ8zLS4qUdgUylvZFJWjSrjzi2xemJa1l3MDdZRhEaNkfMliDGCv2vuUFp7tYz0QtyqBkBMORQl53dzgrcQcsRjDSE274WJl9CUg1l0pNMFsAbVCUGwUqCmKace9LXZ9JV00TRdg4EpryDsUCi23q0THnwstvRffwyJrw+xbhY/X3GKC4zOKqiCLJ4MTPQEIKlpVJQ9e9lWJ8FYhpUrl3QaHfEPINJ0taUfGhCyNzi5QBkSWbTcWVmRMmu+QIy7moW9crcz2xmVEUey7AaGwZT2Kk6JGw26w5q9IUy1Z9mwaljmHrUTqZrOX4Hj3UblpkHN+mGkoia/ipta5KhN5lTTIs4N3V+El7O2R2GggBrVHNiSualfydo+RX8k/S6PM1/C88IQO3Y2utoJrr415CznncvhF9Sc6tncZcShcNQj1iEOSsGxY2noW265eHzTMKJ/xuN6Bp9OXVK+8iOcUsz1T7F0UqwY3xnD8F7fBZ7IGG41DsXBDIcPmb+SIYbhv0uJjm3BEuv4TzIU0=
+10 -11
View File
@@ -1,16 +1,15 @@
FROM golang:1.10.3 AS build
FROM golang:1.18 AS build
WORKDIR /go/src/github.com/zricethezav/gitleaks
COPY . .
RUN CGO_ENABLED=0 go build -o bin/gitleaks *.go
RUN VERSION=$(git describe --tags --abbrev=0) && \
CGO_ENABLED=0 go build -o bin/gitleaks -ldflags "-X="github.com/zricethezav/gitleaks/v8/cmd.Version=${VERSION}
FROM alpine:3.7
RUN apk add --no-cache bash git openssh
FROM alpine:3.16
RUN adduser -D gitleaks && \
apk add --no-cache bash git openssh-client
COPY --from=build /go/src/github.com/zricethezav/gitleaks/bin/* /usr/bin/
USER gitleaks
RUN git config --global --add safe.directory '*'
ENTRYPOINT ["gitleaks"]
# How to use me :
# docker build -t gitleaks .
# docker run --rm --name=gitleaks gitleaks https://github.com/zricethezav/gitleaks
# This will check for secrets in https://github.com/zricethezav/gitleaks
Generated
-153
View File
@@ -1,153 +0,0 @@
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
[[projects]]
name = "github.com/BurntSushi/toml"
packages = ["."]
revision = "b26d9c308763d68093482582cea63d69be07a0f0"
version = "v0.3.0"
[[projects]]
name = "github.com/emirpasic/gods"
packages = ["containers","lists","lists/arraylist","trees","trees/binaryheap","utils"]
revision = "f6c17b524822278a87e3b3bd809fec33b51f5b46"
version = "v1.9.0"
[[projects]]
name = "github.com/franela/goblin"
packages = ["."]
revision = "cd5d08fb4ede9eaac1812fdb513552e7404eae2e"
version = "0.0.2"
[[projects]]
name = "github.com/golang/protobuf"
packages = ["proto"]
revision = "b4deda0973fb4c70b50d226b1af49f3da59f5265"
version = "v1.1.0"
[[projects]]
name = "github.com/google/go-github"
packages = ["github"]
revision = "e48060a28fac52d0f1cb758bc8b87c07bac4a87d"
version = "v15.0.0"
[[projects]]
branch = "master"
name = "github.com/google/go-querystring"
packages = ["query"]
revision = "53e6ce116135b80d037921a7fdd5138cf32d7a8a"
[[projects]]
branch = "master"
name = "github.com/jbenet/go-context"
packages = ["io"]
revision = "d14ea06fba99483203c19d92cfcd13ebe73135f4"
[[projects]]
name = "github.com/jessevdk/go-flags"
packages = ["."]
revision = "c6ca198ec95c841fdb89fc0de7496fed11ab854e"
version = "v1.4.0"
[[projects]]
name = "github.com/kevinburke/ssh_config"
packages = ["."]
revision = "9fc7bb800b555d63157c65a904c86a2cc7b4e795"
version = "0.4"
[[projects]]
branch = "master"
name = "github.com/mitchellh/go-homedir"
packages = ["."]
revision = "3864e76763d94a6df2f9960b16a20a33da9f9a66"
[[projects]]
name = "github.com/pelletier/go-buffruneio"
packages = ["."]
revision = "c37440a7cf42ac63b919c752ca73a85067e05992"
version = "v0.2.0"
[[projects]]
name = "github.com/sergi/go-diff"
packages = ["diffmatchpatch"]
revision = "1744e2970ca51c86172c8190fadad617561ed6e7"
version = "v1.0.0"
[[projects]]
name = "github.com/sirupsen/logrus"
packages = ["."]
revision = "c155da19408a8799da419ed3eeb0cb5db0ad5dbc"
version = "v1.0.5"
[[projects]]
name = "github.com/src-d/gcfg"
packages = [".","scanner","token","types"]
revision = "f187355171c936ac84a82793659ebb4936bc1c23"
version = "v1.3.0"
[[projects]]
name = "github.com/xanzy/ssh-agent"
packages = ["."]
revision = "640f0ab560aeb89d523bb6ac322b1244d5c3796c"
version = "v0.2.0"
[[projects]]
branch = "master"
name = "golang.org/x/crypto"
packages = ["cast5","curve25519","ed25519","ed25519/internal/edwards25519","internal/chacha20","internal/subtle","openpgp","openpgp/armor","openpgp/elgamal","openpgp/errors","openpgp/packet","openpgp/s2k","poly1305","ssh","ssh/agent","ssh/knownhosts","ssh/terminal"]
revision = "a49355c7e3f8fe157a85be2f77e6e269a0f89602"
[[projects]]
branch = "master"
name = "golang.org/x/net"
packages = ["context","context/ctxhttp"]
revision = "d0887baf81f4598189d4e12a37c6da86f0bba4d0"
[[projects]]
branch = "master"
name = "golang.org/x/oauth2"
packages = [".","internal"]
revision = "ef147856a6ddbb60760db74283d2424e98c87bff"
[[projects]]
branch = "master"
name = "golang.org/x/sys"
packages = ["unix","windows"]
revision = "ac767d655b305d4e9612f5f6e33120b9176c4ad4"
[[projects]]
name = "golang.org/x/text"
packages = ["internal/gen","internal/triegen","internal/ucd","transform","unicode/cldr","unicode/norm"]
revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0"
version = "v0.3.0"
[[projects]]
name = "google.golang.org/appengine"
packages = ["internal","internal/base","internal/datastore","internal/log","internal/remote_api","internal/urlfetch","urlfetch"]
revision = "b1f26356af11148e710935ed1ac8a7f5702c7612"
version = "v1.1.0"
[[projects]]
name = "gopkg.in/src-d/go-billy.v4"
packages = [".","helper/chroot","helper/polyfill","osfs","util"]
revision = "83cf655d40b15b427014d7875d10850f96edba14"
version = "v4.2.0"
[[projects]]
name = "gopkg.in/src-d/go-git.v4"
packages = [".","config","internal/revision","plumbing","plumbing/cache","plumbing/filemode","plumbing/format/config","plumbing/format/diff","plumbing/format/gitignore","plumbing/format/idxfile","plumbing/format/index","plumbing/format/objfile","plumbing/format/packfile","plumbing/format/pktline","plumbing/object","plumbing/protocol/packp","plumbing/protocol/packp/capability","plumbing/protocol/packp/sideband","plumbing/revlist","plumbing/storer","plumbing/transport","plumbing/transport/client","plumbing/transport/file","plumbing/transport/git","plumbing/transport/http","plumbing/transport/internal/common","plumbing/transport/server","plumbing/transport/ssh","storage","storage/filesystem","storage/filesystem/dotgit","storage/memory","utils/binary","utils/diff","utils/ioutil","utils/merkletrie","utils/merkletrie/filesystem","utils/merkletrie/index","utils/merkletrie/internal/frame","utils/merkletrie/noder"]
revision = "3bd5e82b2512d85becae9677fa06b5a973fd4cfb"
version = "v4.5.0"
[[projects]]
name = "gopkg.in/warnings.v0"
packages = ["."]
revision = "ec4a0fea49c7b46c2aeb0b51aac55779c607e52b"
version = "v0.1.2"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "5af7c639081bd99afc4a673e96079d2ed9e76d0e1bf0d2cc5ad9c71274beaa86"
solver-name = "gps-cdcl"
solver-version = 1
-58
View File
@@ -1,58 +0,0 @@
# Gopkg.toml example
#
# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
# for detailed Gopkg.toml documentation.
#
# required = ["github.com/user/thing/cmd/thing"]
# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
#
# [[constraint]]
# name = "github.com/user/project"
# version = "1.0.0"
#
# [[constraint]]
# name = "github.com/user/project2"
# branch = "dev"
# source = "github.com/myfork/project2"
#
# [[override]]
# name = "github.com/x/y"
# version = "2.4.0"
#
# [prune]
# non-go = false
# go-tests = true
# unused-packages = true
[[constraint]]
name = "github.com/BurntSushi/toml"
version = "0.3.0"
[[constraint]]
name = "github.com/franela/goblin"
version = "0.0.2"
[[constraint]]
name = "github.com/google/go-github"
version = "15.0.0"
[[constraint]]
name = "github.com/jessevdk/go-flags"
version = "1.4.0"
[[constraint]]
name = "github.com/sirupsen/logrus"
version = "1.0.5"
[[constraint]]
branch = "master"
name = "golang.org/x/oauth2"
[[constraint]]
name = "gopkg.in/src-d/go-git.v4"
version = "4.5.0"
[prune]
go-tests = true
unused-packages = true
@@ -1,6 +1,6 @@
The MIT License (MIT)
MIT License
Copyright (c) 2014 Simon Eskildsen
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
@@ -9,13 +9,13 @@ 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 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.
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+24 -20
View File
@@ -1,22 +1,26 @@
.PHONY: test build-all release
.PHONY: test test-cover
test:
go get github.com/golang/lint/golint
go fmt
golint
go test --race -cover
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)
PKG=github.com/zricethezav/gitleaks
VERSION := `git fetch --tags && git tag | sort -V | tail -1`
LDFLAGS=-ldflags "-X=github.com/zricethezav/gitleaks/v8/cmd.Version=$(VERSION)"
COVER=--cover --coverprofile=cover.out
build-all:
mkdir build
env GOOS="windows" GOARCH="amd64" go build -o "build/gitleaks-windows-amd64.exe"
env GOOS="windows" GOARCH="386" go build -o "build/gitleaks-windows-386.exe"
env GOOS="linux" GOARCH="amd64" go build -o "build/gitleaks-linux-amd64"
env GOOS="linux" GOARCH="arm" go build -o "build/gitleaks-linux-arm"
env GOOS="linux" GOARCH="mips" go build -o "build/gitleaks-linux-mips"
env GOOS="linux" GOARCH="mips" go build -o "build/gitleaks-linux-mips"
env GOOS="darwin" GOARCH="amd64" go build -o "build/gitleaks-darwin-amd64"
test-cover:
go test -v ./... --race $(COVER) $(PKG)
go tool cover -html=cover.out
format:
go fmt ./...
test: format
go vet ./...
go test -v ./... --race $(PKG)
build: format
go vet ./...
go mod tidy
go build $(LDFLAGS)
clean:
find . -type f -name '*.got.*' -delete
find . -type f -name '*.out' -delete
+314 -42
View File
@@ -1,59 +1,331 @@
<p align="center">
<img alt="gitleaks" src="https://raw.githubusercontent.com/zricethezav/gifs/master/gitleaks5.png" height="140" />
<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>
# gitleaks
```
┌─○───┐
│ │╲ │
│ │ ○ │
│ ○ ░ │
└─░───┘
```
<p align="left">
<p align="left">
<a href="https://github.com/zricethezav/gitleaks/actions/workflows/test.yml">
<img alt="Github Test" src="https://github.com/zricethezav/gitleaks/actions/workflows/test.yml/badge.svg">
</a>
<a href="https://hub.docker.com/r/zricethezav/gitleaks">
<img src="https://img.shields.io/docker/pulls/zricethezav/gitleaks.svg" />
</a>
<a href="https://www.jit.io/jit-open-source-gitleaks?utm_source=github&utm_medium=badge&utm_campaign=GitleaksReadme&utm_id=oss&items=item-secret-detection">
<img src="https://img.shields.io/badge/Secured%20by-Jit-B8287F?style=?style=plastic" />
</a>
<a href="https://github.com/zricethezav/gitleaks-action">
<img alt="gitleaks badge" src="https://img.shields.io/badge/protected%20by-gitleaks-blue">
</a>
<a href="https://twitter.com/intent/follow?screen_name=zricethezav">
<img src="https://img.shields.io/twitter/follow/zricethezav?label=Follow%20zricethezav&style=social&color=blue" alt="Follow @zricethezav" />
</a>
</p>
</p>
## Audit git repos for secrets, keys, and whatever.
### Powered by src-d's [go-git](https://github.com/src-d/go-git)
Gitleaks is a SAST tool for **detecting** and **preventing** hardcoded secrets like passwords, api keys, and tokens in git repos. Gitleaks is an **easy-to-use, all-in-one solution** for detecting secrets, past or present, in your code.
#### Installing
[![asciicast](https://asciinema.org/a/455683.svg)](https://asciinema.org/a/455683)
## Getting Started
Gitleaks can be installed using Homebrew, Docker, or Go. Gitleaks is also available in binary form for many popular platforms and OS types on the [releases page](https://github.com/zricethezav/gitleaks/releases). In addition, Gitleaks can be implemented as a pre-commit hook directly in your repo.
### MacOS
```bash
go get -u github.com/zricethezav/gitleaks
brew install gitleaks
```
Or download from release binaries [here](https://github.com/zricethezav/gitleaks/releases)
### Docker
#### DockerHub
```bash
docker pull zricethezav/gitleaks:latest
docker run -v ${path_to_host_folder_to_scan}:/path zricethezav/gitleaks:latest [COMMAND] --source="/path" [OPTIONS]
```
#### ghcr.io
```bash
docker pull ghcr.io/zricethezav/gitleaks:latest
docker run -v ${path_to_host_folder_to_scan}:/path zricethezav/gitleaks:latest [COMMAND] --source="/path" [OPTIONS]
```
#### Usage and Options
### From Source
1. Download and install Go from https://golang.org/dl/
2. Clone the repo
```bash
git clone https://github.com/zricethezav/gitleaks.git
```
3. Build the binary
```bash
cd gitleaks
make build
```
### Github Action
Check out the official [Gitleaks GitHub Action](https://github.com/gitleaks/gitleaks-action)
```
name: gitleaks
on: [pull_request, push, workflow_dispatch]
jobs:
scan:
name: gitleaks
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- uses: gitleaks/gitleaks-action@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE}} # Only required for Organizations, not personal accounts.
```
### Pre-Commit
1. Install pre-commit from https://pre-commit.com/#install
2. Create a `.pre-commit-config.yaml` file at the root of your repository with the following content:
```
repos:
- repo: https://github.com/zricethezav/gitleaks
rev: v8.2.0
hooks:
- id: gitleaks
```
for a [native execution of GitLeaks](https://github.com/zricethezav/gitleaks/releases) or use the [`gitleaks-docker` pre-commit ID](https://github.com/zricethezav/gitleaks/blob/master/.pre-commit-hooks.yaml) for executing GitLeaks using the [official Docker images](#docker)
3. Install with `pre-commit install`
4. Now you're all set!
```
➜ git commit -m "this commit contains a secret"
Detect hardcoded secrets.................................................Failed
```
Note: to disable the gitleaks pre-commit hook you can prepend `SKIP=gitleaks` to the commit command
and it will skip running gitleaks
```
➜ SKIP=gitleaks git commit -m "skip gitleaks check"
Detect hardcoded secrets................................................Skipped
```
## Usage
```
Usage:
gitleaks [OPTIONS]
gitleaks [command]
Application Options:
-r, --repo= Repo url to audit
--github-user= User url to audit
--github-org= Organization url to audit
-p, --private Include private repos in audit
-c, --commit= sha of commit to stop at
--repo-path= Path to repo
--owner-path= Path to owner directory (repos discovered)
--max-go= Maximum number of concurrent go-routines gitleaks spawns
--disk Clones repo(s) to disk
--all-refs run audit on all refs
--single-search= single regular expression to search for
--config= path to gitleaks config
--ssh-key= path to ssh key
-l, --log= log level
-v, --verbose Show verbose output from gitleaks audit
--report= path to write report file
--redact redact secrets from log messages and report
Available Commands:
completion generate the autocompletion script for the specified shell
detect Detect secrets in code
help Help about any command
protect Protect secrets in code
version Display gitleaks version
Help Options:
-h, --help Show this help message
```
#### Exit Codes
```
1: leaks present
0: no leaks
Flags:
-c, --config string config file path
order of precedence:
1. --config/-c
2. env var GITLEAKS_CONFIG
3. (--source/-s)/.gitleaks.toml
If none of the three options are used, then gitleaks will use the default config
--exit-code string exit code when leaks have been encountered (default: 1)
-h, --help help for gitleaks
-l, --log-level string log level (debug, info, warn, error, fatal) (default "info")
--redact redact secrets from logs and stdout
-f, --report-format string output format (json, csv, sarif)
-r, --report-path string report file
-s, --source string path to source (git repo, directory, file)
-v, --verbose show verbose output from scan
Use "gitleaks [command] --help" for more information about a command.
```
#### Additional Examples and Explanations
Check the wiki [here](https://github.com/zricethezav/gitleaks/wiki)
### Commands
There are two commands you will use to detect secrets; `detect` and `protect`.
#### Detect
The `detect` command is used to scan repos, directories, and files. This command can be used on developer machines and in CI environments.
### If you find a valid leak in a repo
Please read this [Github article on removing sensitive data from a repository](https://help.github.com/articles/removing-sensitive-data-from-a-repository/) to remove the sensitive information from your history.
When running `detect` on a git repository, gitleaks will parse the output of a `git log -p` command (you can see how this executed
[here](https://github.com/zricethezav/gitleaks/blob/7240e16769b92d2a1b137c17d6bf9d55a8562899/git/git.go#L17-L25)).
[`git log -p` generates patches](https://git-scm.com/docs/git-log#_generating_patch_text_with_p) which gitleaks will use to detect secrets.
You can configure what commits `git log` will range over by using the `--log-opts` flag. `--log-opts` accepts any option for `git log -p`.
For example, if you wanted to run gitleaks on a range of commits you could use the following command: `gitleaks detect --source . --log-opts="--all commitA..commitB"`.
See the `git log` [documentation](https://git-scm.com/docs/git-log) for more information.
### Run me with docker
Simply run `docker run --rm --name=gitleaks zricethezav/gitleaks --help`
You can scan files and directories by using the `--no-git` option.
#### Protect
The `protect` command is used to uncommitted changes in a git repo. This command should be used on developer machines in accordance with
[shifting left on security](https://cloud.google.com/architecture/devops/devops-tech-shifting-left-on-security).
When running `protect` on a git repository, gitleaks will parse the output of a `git diff` command (you can see how this executed
[here](https://github.com/zricethezav/gitleaks/blob/7240e16769b92d2a1b137c17d6bf9d55a8562899/git/git.go#L48-L49)). You can set the
`--staged` flag to check for changes in commits that have been `git add`ed. The `--staged` flag should be used when running Gitleaks
as a pre-commit.
**NOTE**: the `protect` command can only be used on git repos, running `protect` on files or directories will result in an error message.
### Verify Findings
You can verify a finding found by gitleaks using a `git log` command.
Example output:
```
{
"Description": "AWS",
"StartLine": 37,
"EndLine": 37,
"StartColumn": 19,
"EndColumn": 38,
"Match": "\t\t\"aws_secret= \\\"AKIAIMNOJVGFDXXXE4OA\\\"\": true,",
"Secret": "AKIAIMNOJVGFDXXXE4OA",
"File": "checks_test.go",
"Commit": "ec2fc9d6cb0954fb3b57201cf6133c48d8ca0d29",
"Entropy": 0,
"Author": "zricethezav",
"Email": "thisispublicanyways@gmail.com",
"Date": "2018-01-28 17:39:00 -0500 -0500",
"Message": "[update] entropy check",
"Tags": [],
"RuleID": "aws-access-token"
}
```
We can use the following format to verify the leak:
```
git log -L {StartLine,EndLine}:{File} {Commit}
```
So in this example it would look like:
```
git log -L 37,37:checks_test.go ec2fc9d6cb0954fb3b57201cf6133c48d8ca0d29
```
Which gives us:
```
commit ec2fc9d6cb0954fb3b57201cf6133c48d8ca0d29
Author: zricethezav <thisispublicanyways@gmail.com>
Date: Sun Jan 28 17:39:00 2018 -0500
[update] entropy check
diff --git a/checks_test.go b/checks_test.go
--- a/checks_test.go
+++ b/checks_test.go
@@ -28,0 +37,1 @@
+ "aws_secret= \"AKIAIMNOJVGFDXXXE4OA\"": true,
```
## Pre-Commit hook
You can run Gitleaks as a pre-commit hook by copying the example `pre-commit.py` script into
your `.git/hooks/` directory.
## Configuration
Gitleaks offers a configuration format you can follow to write your own secret detection rules:
```toml
# Title for the gitleaks configuration file.
title = "Gitleaks title"
# An array of tables that contain information that define instructions
# on how to detect secrets
[[rules]]
# Unique identifier for this rule
id = "awesome-rule-1"
# Short human readable description of the rule.
description = "awesome rule 1"
# Golang regular expression used to detect secrets. Note Golang's regex engine
# does not support lookaheads.
regex = '''one-go-style-regex-for-this-rule'''
# Golang regular expression used to match paths. This can be used as a standalone rule or it can be used
# in conjunction with a valid `regex` entry.
path = '''a-file-path-regex'''
# Array of strings used for metadata and reporting purposes.
tags = ["tag","another tag"]
# Int used to extract secret from regex match and used as the group that will have
# its entropy checked if `entropy` is set.
secretGroup = 3
# Float representing the minimum shannon entropy a regex group must have to be considered a secret.
entropy = 3.5
# Keywords are used for pre-regex check filtering. Rules that contain
# keywords will perform a quick string compare check to make sure the
# keyword(s) are in the content being scanned. Ideally these values should
# either be part of the idenitifer or unique strings specific to the rule's regex
# (introduced in v8.6.0)
keywords = [
"auth",
"password",
"token",
]
# You can include an allowlist table for a single rule to reduce false positives or ignore commits
# with known/rotated secrets
[rules.allowlist]
description = "ignore commit A"
commits = [ "commit-A", "commit-B"]
paths = [
'''go\.mod''',
'''go\.sum'''
]
regexes = [
'''process''',
'''getenv''',
]
# note: stopwords targets the extracted secret, not the entire regex match
# like 'regexes' does. (stopwords introduced in 8.8.0)
stopwords = [
'''client''',
'''endpoint''',
]
# This is a global allowlist which has a higher order of precedence than rule-specific allowlists.
# If a commit listed in the `commits` field below is encountered then that commit will be skipped and no
# secrets will be detected for said commit. The same logic applies for regexes and paths.
[allowlist]
description = "global allow list"
commits = [ "commit-A", "commit-B", "commit-C"]
paths = [
'''gitleaks\.toml''',
'''(.*?)(jpg|gif|doc)'''
]
regexes = [
'''219-09-9999''',
'''078-05-1120''',
'''(9[0-9]{2}|666)-\d{2}-\d{4}''',
]
# note: stopwords targets the extracted secret, not the entire regex match
# like 'regexes' does. (stopwords introduced in 8.8.0)
stopwords = [
'''client''',
'''endpoint''',
]
```
Refer to the default [gitleaks config](https://github.com/zricethezav/gitleaks/blob/master/config/gitleaks.toml) for examples and advice on writing regular expressions for secret detection.
## Secured by Jit
We use [Jit](https://www.jit.io/jit-open-source-gitleaks?utm_source=github&utm_medium=readme&utm_campaign=GitleaksReadme&utm_id=oss&items=item-secret-detection) to secure our codebase, to achieve fully automated, full-stack continuous security using the world's best OSS security tools.
## Sponsorships
<p align="left">
<a href="https://www.tines.com/?utm_source=oss&utm_medium=sponsorship&utm_campaign=gitleaks">
<img alt="Tines Sponsorship" src="https://user-images.githubusercontent.com/15034943/146411864-4878f936-b4f7-49a0-b625-f9f40c704bfa.png" width=200>
</a>
</p>
## Exit Codes
You can always set the exit code when leaks are encountered with the --exit-code flag. Default exit codes below:
```
0 - no leaks present
1 - leaks or error encountered
126 - unknown flag
```
+128
View File
@@ -0,0 +1,128 @@
package cmd
import (
"os"
"path/filepath"
"time"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/detect"
"github.com/zricethezav/gitleaks/v8/report"
)
func init() {
rootCmd.AddCommand(detectCmd)
detectCmd.Flags().String("log-opts", "", "git log options")
detectCmd.Flags().Bool("no-git", false, "treat git repo as a regular directory and scan those files, --log-opts has no effect on the scan when --no-git is set")
}
var detectCmd = &cobra.Command{
Use: "detect",
Short: "detect secrets in code",
Run: runDetect,
}
func runDetect(cmd *cobra.Command, args []string) {
initConfig()
var (
vc config.ViperConfig
findings []report.Finding
err error
)
// Load config
if err = viper.Unmarshal(&vc); err != nil {
log.Fatal().Err(err).Msg("Failed to load config")
}
cfg, err := vc.Translate()
if err != nil {
log.Fatal().Err(err).Msg("Failed to load config")
}
cfg.Path, _ = cmd.Flags().GetString("config")
// start timer
start := time.Now()
// Setup detector
detector := detect.NewDetector(cfg)
detector.Config.Path, err = cmd.Flags().GetString("config")
if err != nil {
log.Fatal().Err(err)
}
source, err := cmd.Flags().GetString("source")
if err != nil {
log.Fatal().Err(err)
}
// if config path is not set, then use the {source}/.gitleaks.toml path.
// note that there may not be a `{source}/.gitleaks.toml` file, this is ok.
if detector.Config.Path == "" {
detector.Config.Path = filepath.Join(source, ".gitleaks.toml")
}
// set verbose flag
if detector.Verbose, err = cmd.Flags().GetBool("verbose"); err != nil {
log.Fatal().Err(err)
}
// set redact flag
if detector.Redact, err = cmd.Flags().GetBool("redact"); err != nil {
log.Fatal().Err(err)
}
// set exit code
exitCode, err := cmd.Flags().GetInt("exit-code")
if err != nil {
log.Fatal().Err(err)
}
// determine what type of scan:
// - git: scan the history of the repo
// - no-git: scan files by treating the repo as a plain directory
noGit, err := cmd.Flags().GetBool("no-git")
if err != nil {
log.Fatal().Err(err)
}
// start the detector scan
if noGit {
findings, err = detector.DetectFiles(source)
if err != nil {
// don't exit on error, just log it
log.Error().Err(err)
}
} else {
logOpts, err := cmd.Flags().GetString("log-opts")
if err != nil {
log.Fatal().Err(err)
}
findings, err = detector.DetectGit(source, logOpts, detect.DetectType)
if err != nil {
// don't exit on error, just log it
log.Error().Err(err)
}
}
// log info about the scan
log.Info().Msgf("scan completed in %s", time.Since(start))
if len(findings) != 0 {
log.Warn().Msgf("leaks found: %d", len(findings))
} else {
log.Info().Msg("no leaks found")
}
// write report if desired
reportPath, _ := cmd.Flags().GetString("report-path")
ext, _ := cmd.Flags().GetString("report-format")
if reportPath != "" {
if err = report.Write(findings, cfg, ext, reportPath); err != nil {
log.Fatal().Err(err)
}
}
if len(findings) != 0 {
os.Exit(exitCode)
}
}
+130
View File
@@ -0,0 +1,130 @@
package main
import (
"os"
"text/template"
"github.com/rs/zerolog/log"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/rules"
"github.com/zricethezav/gitleaks/v8/config"
)
const (
templatePath = "rules/config.tmpl"
)
func main() {
configRules := []*config.Rule{}
configRules = append(configRules, rules.AdobeClientID())
configRules = append(configRules, rules.AdobeClientSecret())
configRules = append(configRules, rules.AgeSecretKey())
configRules = append(configRules, rules.AlgoliaApiKey())
configRules = append(configRules, rules.AlibabaAccessKey())
configRules = append(configRules, rules.AlibabaSecretKey())
configRules = append(configRules, rules.AsanaClientID())
configRules = append(configRules, rules.AsanaClientSecret())
configRules = append(configRules, rules.Atlassian())
configRules = append(configRules, rules.AWS())
configRules = append(configRules, rules.BitBucketClientID())
configRules = append(configRules, rules.BitBucketClientSecret())
configRules = append(configRules, rules.Beamer())
configRules = append(configRules, rules.Clojars())
configRules = append(configRules, rules.Contentful())
configRules = append(configRules, rules.Databricks())
configRules = append(configRules, rules.DiscordAPIToken())
configRules = append(configRules, rules.DiscordClientID())
configRules = append(configRules, rules.DiscordClientSecret())
configRules = append(configRules, rules.DropBoxAPISecret())
configRules = append(configRules, rules.DropBoxLongLivedAPIToken())
configRules = append(configRules, rules.DropBoxShortLivedAPIToken())
configRules = append(configRules, rules.Doppler())
configRules = append(configRules, rules.Duffel())
configRules = append(configRules, rules.Dynatrace())
configRules = append(configRules, rules.EasyPost())
configRules = append(configRules, rules.EasyPostTestAPI())
configRules = append(configRules, rules.Facebook())
configRules = append(configRules, rules.FastlyAPIToken())
configRules = append(configRules, rules.FinicityClientSecret())
configRules = append(configRules, rules.FinicityAPIToken())
configRules = append(configRules, rules.FlutterwavePublicKey())
configRules = append(configRules, rules.FlutterwaveSecretKey())
configRules = append(configRules, rules.FlutterwaveEncKey())
configRules = append(configRules, rules.FrameIO())
configRules = append(configRules, rules.GoCardless())
// TODO figure out what makes sense for GCP
// configRules = append(configRules, rules.GCPServiceAccount())
configRules = append(configRules, rules.GitHubPat())
configRules = append(configRules, rules.GitHubOauth())
configRules = append(configRules, rules.GitHubApp())
configRules = append(configRules, rules.GitHubRefresh())
configRules = append(configRules, rules.Gitlab())
configRules = append(configRules, rules.Hashicorp())
configRules = append(configRules, rules.Heroku())
configRules = append(configRules, rules.HubSpot())
configRules = append(configRules, rules.Intercom())
configRules = append(configRules, rules.LinearAPIToken())
configRules = append(configRules, rules.LinearClientSecret())
configRules = append(configRules, rules.LinkedinClientID())
configRules = append(configRules, rules.LinkedinClientSecret())
configRules = append(configRules, rules.LobAPIToken())
configRules = append(configRules, rules.LobPubAPIToken())
configRules = append(configRules, rules.MailChimp())
configRules = append(configRules, rules.MailGunPubAPIToken())
configRules = append(configRules, rules.MailGunPrivateAPIToken())
configRules = append(configRules, rules.MailGunSigningKey())
configRules = append(configRules, rules.MapBox())
configRules = append(configRules, rules.MessageBirdAPIToken())
configRules = append(configRules, rules.MessageBirdClientID())
configRules = append(configRules, rules.NewRelicUserID())
configRules = append(configRules, rules.NewRelicUserKey())
configRules = append(configRules, rules.NewRelicBrowserAPIKey())
configRules = append(configRules, rules.NPM())
configRules = append(configRules, rules.PlanetScalePassword())
configRules = append(configRules, rules.PlanetScaleAPIToken())
configRules = append(configRules, rules.PlanetScaleOAuthToken())
configRules = append(configRules, rules.PostManAPI())
configRules = append(configRules, rules.PrivateKey())
configRules = append(configRules, rules.PulumiAPIToken())
configRules = append(configRules, rules.PyPiUploadToken())
configRules = append(configRules, rules.RubyGemsAPIToken())
configRules = append(configRules, rules.SendGridAPIToken())
configRules = append(configRules, rules.SendInBlueAPIToken())
configRules = append(configRules, rules.ShippoAPIToken())
configRules = append(configRules, rules.ShopifyAccessToken())
configRules = append(configRules, rules.ShopifyCustomAccessToken())
configRules = append(configRules, rules.ShopifyPrivateAppAccessToken())
configRules = append(configRules, rules.ShopifySharedSecret())
configRules = append(configRules, rules.SlackAccessToken())
configRules = append(configRules, rules.SlackWebHook())
configRules = append(configRules, rules.StripeAccessToken())
configRules = append(configRules, rules.Twilio())
configRules = append(configRules, rules.TwitchAPIToken())
configRules = append(configRules, rules.Twitter())
configRules = append(configRules, rules.Typeform())
configRules = append(configRules, rules.GenericCredential())
// ensure rules have unique ids
ruleLookUp := make(map[string]bool)
for _, rule := range configRules {
// check if rule is in ruleLookUp
if _, ok := ruleLookUp[rule.RuleID]; ok {
log.Fatal().Msgf("rule id %s is not unique", rule.RuleID)
}
ruleLookUp[rule.RuleID] = true
}
config := config.Config{
Rules: configRules,
}
tmpl, err := template.ParseFiles(templatePath)
if err != nil {
log.Fatal().Err(err).Msg("Failed to parse template")
}
f, err := os.Create("../../../config/gitleaks.toml")
if err != nil {
log.Fatal().Err(err).Msg("Failed to create rules.toml")
}
tmpl.Execute(f, config)
}
+39
View File
@@ -0,0 +1,39 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func AdobeClientID() *config.Rule {
// define rule
r := config.Rule{
Description: "Adobe Client ID (Oauth Web)",
RuleID: "adobe-client-id",
Regex: generateSemiGenericRegex([]string{"adobe"}, hex("32")),
SecretGroup: 1,
Keywords: []string{"adobe"},
}
// validate
tps := []string{
generateSampleSecret("adobe", secrets.NewSecret(hex("32"))),
}
return validate(r, tps, nil)
}
func AdobeClientSecret() *config.Rule {
// define rule
r := config.Rule{
Description: "Adobe Client Secret",
RuleID: "adobe-client-secret",
Regex: generateUniqueTokenRegex(`(p8e-)(?i)[a-z0-9]{32}`),
Keywords: []string{"p8e-"},
}
// validate
tps := []string{
"adobeClient := \"p8e-" + secrets.NewSecret(hex("32")) + "\"",
}
return validate(r, tps, nil)
}
+23
View File
@@ -0,0 +1,23 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
)
func AgeSecretKey() *config.Rule {
// define rule
r := config.Rule{
Description: "Age secret key",
RuleID: "age secret key",
Regex: regexp.MustCompile(`AGE-SECRET-KEY-1[QPZRY9X8GF2TVDW0S3JN54KHCE6MUA7L]{58}`),
Keywords: []string{"AGE-SECRET-KEY-1"},
}
// validate
tps := []string{
`apiKey := "AGE-SECRET-KEY-1QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ`, // gitleaks:allow
}
return validate(r, tps, nil)
}
+22
View File
@@ -0,0 +1,22 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func AlgoliaApiKey() *config.Rule {
// define rule
r := config.Rule{
Description: "Algolia API Key",
RuleID: "algolia-api-key",
Regex: generateSemiGenericRegex([]string{"algolia"}, `[a-z0-9]{32}`),
Keywords: []string{"algolia"},
}
// validate
tps := []string{
"algolia_key := " + secrets.NewSecret(hex("32")),
}
return validate(r, tps, nil)
}
+41
View File
@@ -0,0 +1,41 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func AlibabaAccessKey() *config.Rule {
// define rule
r := config.Rule{
Description: "Alibaba AccessKey ID",
RuleID: "alibaba-access-key-id",
Regex: generateUniqueTokenRegex(`(LTAI)(?i)[a-z0-9]{20}`),
Keywords: []string{"LTAI"},
}
// validate
tps := []string{
"alibabaKey := \"LTAI" + secrets.NewSecret(hex("20")) + "\"",
}
return validate(r, tps, nil)
}
// TODO
func AlibabaSecretKey() *config.Rule {
// define rule
r := config.Rule{
Description: "Alibaba Secret Key",
RuleID: "alibaba-secret-key",
Regex: generateSemiGenericRegex([]string{"alibaba"},
alphaNumeric("30")),
SecretGroup: 1,
Keywords: []string{"alibaba"},
}
// validate
tps := []string{
generateSampleSecret("alibaba", secrets.NewSecret(alphaNumeric("30"))),
}
return validate(r, tps, nil)
}
+40
View File
@@ -0,0 +1,40 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func AsanaClientID() *config.Rule {
// define rule
r := config.Rule{
Description: "Asana Client ID",
RuleID: "asana-client-id",
Regex: generateSemiGenericRegex([]string{"asana"}, numeric("16")),
SecretGroup: 1,
Keywords: []string{"asana"},
}
// validate
tps := []string{
generateSampleSecret("asana", secrets.NewSecret(numeric("16"))),
}
return validate(r, tps, nil)
}
func AsanaClientSecret() *config.Rule {
// define rule
r := config.Rule{
Description: "Asana Client Secret",
RuleID: "asana-client-secret",
Regex: generateSemiGenericRegex([]string{"asana"}, alphaNumeric("32")),
SecretGroup: 1,
Keywords: []string{"asana"},
}
// validate
tps := []string{
generateSampleSecret("asana", secrets.NewSecret(alphaNumeric("32"))),
}
return validate(r, tps, nil)
}
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Atlassian() *config.Rule {
// define rule
r := config.Rule{
Description: "Atlassian API token",
RuleID: "atlassian-api-token",
Regex: generateSemiGenericRegex([]string{"atlassian", "confluence"}, alphaNumeric("24")),
SecretGroup: 1,
Keywords: []string{"atlassian", "confluence"},
}
// validate
tps := []string{
generateSampleSecret("atlassian", secrets.NewSecret(alphaNumeric("24"))),
generateSampleSecret("confluence", secrets.NewSecret(alphaNumeric("24"))),
}
return validate(r, tps, nil)
}
+31
View File
@@ -0,0 +1,31 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
)
func AWS() *config.Rule {
// define rule
r := config.Rule{
Description: "AWS",
RuleID: "aws-access-token",
Regex: regexp.MustCompile(
"(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}"),
Keywords: []string{
"AKIA",
"AGPA",
"AIDA",
"AROA",
"AIPA",
"ANPA",
"ANVA",
"ASIA",
},
}
// validate
tps := []string{generateSampleSecret("AWS", "AKIALALEMEL33243OLIB")} // gitleaks:allow
return validate(r, tps, nil)
}
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Beamer() *config.Rule {
// define rule
r := config.Rule{
Description: "Beamer API token",
RuleID: "beamer-api-token",
SecretGroup: 1,
Regex: generateSemiGenericRegex([]string{"beamer"},
`b_[a-z0-9=_\-]{44}`),
Keywords: []string{"beamer"},
}
// validate
tps := []string{
generateSampleSecret("beamer", "b_"+secrets.NewSecret(alphaNumericExtended("44"))),
}
return validate(r, tps, nil)
}
+40
View File
@@ -0,0 +1,40 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func BitBucketClientID() *config.Rule {
// define rule
r := config.Rule{
Description: "BitBucket Client ID",
RuleID: "bitbucket-client-id",
Regex: generateSemiGenericRegex([]string{"bitbucket"}, alphaNumeric("32")),
SecretGroup: 1,
Keywords: []string{"bitbucket"},
}
// validate
tps := []string{
generateSampleSecret("bitbucket", secrets.NewSecret(alphaNumeric("32"))),
}
return validate(r, tps, nil)
}
func BitBucketClientSecret() *config.Rule {
// define rule
r := config.Rule{
Description: "BitBucket Client Secret",
RuleID: "bitbucket-client-secret",
Regex: generateSemiGenericRegex([]string{"bitbucket"}, alphaNumericExtended("64")),
SecretGroup: 1,
Keywords: []string{"bitbucket"},
}
// validate
tps := []string{
generateSampleSecret("bitbucket", secrets.NewSecret(alphaNumeric("64"))),
}
return validate(r, tps, nil)
}
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Clojars() *config.Rule {
// define rule
r := config.Rule{
Description: "Clojars API token",
RuleID: "clojars-api-token",
Regex: regexp.MustCompile(`(?i)(CLOJARS_)[a-z0-9]{60}`),
Keywords: []string{"clojars"},
}
// validate
tps := []string{
generateSampleSecret("clojars", "CLOJARS_"+secrets.NewSecret(alphaNumeric("60"))),
}
return validate(r, tps, nil)
}
+57
View File
@@ -0,0 +1,57 @@
# This is the default gitleaks configuration file.
# Rules and allowlists are defined within this file.
# Rules instruct gitleaks on what should be considered a secret.
# Allowlists instruct gitleaks on what is allowed, i.e. not a secret.
title = "gitleaks config"
[allowlist]
description = "global allow lists"
regexes = [
'''219-09-9999''',
'''078-05-1120''',
'''(9[0-9]{2}|666)-\d{2}-\d{4}''',
]
paths = [
'''gitleaks.toml''',
'''(.*?)(jpg|gif|doc|pdf|bin|svg|socket)$''',
'''(go.mod|go.sum)$'''
]
{{ range $i, $rule := .Rules }}[[rules]]
{{ if and $rule.SecretGroup $rule.Entropy $rule.Allowlist.StopWords }}description = "{{$rule.Description}}"
id = "{{$rule.RuleID}}"
regex = '''{{$rule.Regex}}'''
secretGroup = {{ $rule.SecretGroup }}
entropy = {{ $rule.Entropy}}
keywords = [
{{ range $j, $keyword := $rule.Keywords }}"{{$keyword}}",{{end}}
]
[rules.allowlist]
stopwords= [{{ range $j, $stopword := $rule.Allowlist.StopWords }}
"{{$stopword}}",{{end}}
]
{{ else if and $rule.SecretGroup $rule.Entropy }}description = "{{$rule.Description}}"
id = "{{$rule.RuleID}}"
regex = '''{{$rule.Regex}}'''
secretGroup = {{ $rule.SecretGroup }}
entropy = {{ $rule.Entropy}}
keywords = [
{{ range $j, $keyword := $rule.Keywords }}"{{$keyword}}",{{end}}
]
{{ else if $rule.SecretGroup }}description = "{{$rule.Description}}"
id = "{{$rule.RuleID}}"
regex = '''{{$rule.Regex}}'''
secretGroup = {{ $rule.SecretGroup }}
keywords = [
{{ range $j, $keyword := $rule.Keywords }}"{{$keyword}}",{{end}}
]
{{ else }}description = "{{$rule.Description}}"
id = "{{$rule.RuleID}}"
regex = '''{{$rule.Regex}}'''
keywords = [
{{ range $j, $keyword := $rule.Keywords }}"{{$keyword}}",{{end}}
]
{{end}}{{end}}
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Contentful() *config.Rule {
// define rule
r := config.Rule{
Description: "Contentful delivery API token",
RuleID: "contentful-delivery-api-token",
Regex: generateSemiGenericRegex([]string{"contentful"},
alphaNumericExtended("43")),
SecretGroup: 1,
Keywords: []string{"contentful"},
}
// validate
tps := []string{
generateSampleSecret("contentful", secrets.NewSecret(alphaNumeric("43"))),
}
return validate(r, tps, nil)
}
+22
View File
@@ -0,0 +1,22 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Databricks() *config.Rule {
// define rule
r := config.Rule{
Description: "Databricks API token",
RuleID: "databricks-api-token",
Regex: generateUniqueTokenRegex(`dapi[a-h0-9]{32}`),
Keywords: []string{"dapi"},
}
// validate
tps := []string{
generateSampleSecret("databricks", "dapi"+secrets.NewSecret(hex("32"))),
}
return validate(r, tps, nil)
}
+57
View File
@@ -0,0 +1,57 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func DiscordAPIToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Discord API key",
RuleID: "discord-api-token",
Regex: generateSemiGenericRegex([]string{"discord"}, hex("64")),
SecretGroup: 1,
Keywords: []string{"discord"},
}
// validate
tps := []string{
generateSampleSecret("discord", secrets.NewSecret(hex("64"))),
}
return validate(r, tps, nil)
}
func DiscordClientID() *config.Rule {
// define rule
r := config.Rule{
Description: "Discord client ID",
RuleID: "discord-client-id",
Regex: generateSemiGenericRegex([]string{"discord"}, numeric("18")),
SecretGroup: 1,
Keywords: []string{"discord"},
}
// validate
tps := []string{
generateSampleSecret("discord", secrets.NewSecret(numeric("18"))),
}
return validate(r, tps, nil)
}
func DiscordClientSecret() *config.Rule {
// define rule
r := config.Rule{
Description: "Discord client secret",
RuleID: "discord-client-secret",
Regex: generateSemiGenericRegex([]string{"discord"}, alphaNumericExtended("32")),
SecretGroup: 1,
Keywords: []string{"discord"},
}
// validate
tps := []string{
generateSampleSecret("discord", secrets.NewSecret(numeric("32"))),
}
return validate(r, tps, nil)
}
+27
View File
@@ -0,0 +1,27 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Doppler() *config.Rule {
// define rule
r := config.Rule{
Description: "Doppler API token",
RuleID: "doppler-api-token",
Regex: regexp.MustCompile(`(dp\.pt\.)(?i)[a-z0-9]{43}`),
Keywords: []string{"doppler"},
}
// validate
tps := []string{
generateSampleSecret("doppler", "dp.pt."+secrets.NewSecret(alphaNumeric("43"))),
}
return validate(r, tps, nil)
}
// TODO add additional doppler formats:
// https://docs.doppler.com/reference/auth-token-formats
+49
View File
@@ -0,0 +1,49 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func DropBoxAPISecret() *config.Rule {
// define rule
r := config.Rule{
Description: "Dropbox API secret",
RuleID: "dropbox-api-token",
Regex: generateSemiGenericRegex([]string{"dropbox"}, alphaNumeric("15")),
SecretGroup: 1,
Keywords: []string{"dropbox"},
}
// validate
tps := []string{
generateSampleSecret("dropbox", secrets.NewSecret(alphaNumeric("15"))),
}
return validate(r, tps, nil)
}
func DropBoxShortLivedAPIToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "dropbox-short-lived-api-token",
Description: "Dropbox short lived API token",
Regex: generateSemiGenericRegex([]string{"dropbox"}, `sl\.[a-z0-9\-=_]{135}`),
Keywords: []string{"dropbox"},
}
// validate TODO
return &r
}
func DropBoxLongLivedAPIToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "dropbox-long-lived-api-token",
Description: "Dropbox long lived API token",
Regex: generateSemiGenericRegex([]string{"dropbox"}, `[a-z0-9]{11}(AAAAAAAAAA)[a-z0-9\-_=]{43}`),
Keywords: []string{"dropbox"},
}
// validate TODO
return &r
}
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Duffel() *config.Rule {
// define rule
r := config.Rule{
RuleID: "duffel-api-token",
Description: "Duffel API token",
Regex: regexp.MustCompile(`duffel_(test|live)_(?i)[a-z0-9_\-=]{43}`),
Keywords: []string{"duffel"},
}
// validate
tps := []string{
generateSampleSecret("duffel", "duffel_test_"+secrets.NewSecret(alphaNumericExtended("43"))),
}
return validate(r, tps, nil)
}
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Dynatrace() *config.Rule {
// define rule
r := config.Rule{
Description: "Dynatrace API token",
RuleID: "dynatrace-api-token",
Regex: regexp.MustCompile(`dt0c01\.(?i)[a-z0-9]{24}\.[a-z0-9]{64}`),
Keywords: []string{"dynatrace"},
}
// validate
tps := []string{
generateSampleSecret("dynatrace", "dt0c01."+secrets.NewSecret(alphaNumeric("24"))+"."+secrets.NewSecret(alphaNumeric("64"))),
}
return validate(r, tps, nil)
}
+40
View File
@@ -0,0 +1,40 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func EasyPost() *config.Rule {
// define rule
r := config.Rule{
Description: "EasyPost API token",
RuleID: "easypost-api-token",
Regex: regexp.MustCompile(`EZAK(?i)[a-z0-9]{54}`),
Keywords: []string{"EZAK"},
}
// validate
tps := []string{
generateSampleSecret("EZAK", "EZAK"+secrets.NewSecret(alphaNumeric("54"))),
}
return validate(r, tps, nil)
}
func EasyPostTestAPI() *config.Rule {
// define rule
r := config.Rule{
Description: "EasyPost test API token",
RuleID: "easypost-test-api-token",
Regex: regexp.MustCompile(`EZTK(?i)[a-z0-9]{54}`),
Keywords: []string{"EZTK"},
}
// validate
tps := []string{
generateSampleSecret("EZTK", "EZTK"+secrets.NewSecret(alphaNumeric("54"))),
}
return validate(r, tps, nil)
}
+23
View File
@@ -0,0 +1,23 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Facebook() *config.Rule {
// define rule
r := config.Rule{
Description: "facebook",
RuleID: "facebook",
Regex: generateSemiGenericRegex([]string{"facebook"}, hex("32")),
SecretGroup: 1,
Keywords: []string{"facebook"},
}
// validate
tps := []string{
generateSampleSecret("facebook", secrets.NewSecret(hex("32"))),
}
return validate(r, tps, nil)
}
+23
View File
@@ -0,0 +1,23 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func FastlyAPIToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Fastly API key",
RuleID: "fastly-api-token",
Regex: generateSemiGenericRegex([]string{"fastly"}, alphaNumericExtended("32")),
SecretGroup: 1,
Keywords: []string{"fastly"},
}
// validate
tps := []string{
generateSampleSecret("fastly", secrets.NewSecret(alphaNumericExtended("32"))),
}
return validate(r, tps, nil)
}
+40
View File
@@ -0,0 +1,40 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func FinicityClientSecret() *config.Rule {
// define rule
r := config.Rule{
Description: "Finicity Client Secret",
RuleID: "finicity-client-secret",
Regex: generateSemiGenericRegex([]string{"finicity"}, alphaNumeric("20")),
SecretGroup: 1,
Keywords: []string{"finicity"},
}
// validate
tps := []string{
generateSampleSecret("finicity", secrets.NewSecret(alphaNumeric("20"))),
}
return validate(r, tps, nil)
}
func FinicityAPIToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Finicity API token",
RuleID: "finicity-api-token",
Regex: generateSemiGenericRegex([]string{"finicity"}, hex("32")),
SecretGroup: 1,
Keywords: []string{"finicity"},
}
// validate
tps := []string{
generateSampleSecret("finicity", secrets.NewSecret(hex("32"))),
}
return validate(r, tps, nil)
}
+56
View File
@@ -0,0 +1,56 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func FlutterwavePublicKey() *config.Rule {
// define rule
r := config.Rule{
Description: "Finicity Public Key",
RuleID: "flutterwave-public-key",
Regex: regexp.MustCompile(`FLWPUBK_TEST-(?i)[a-h0-9]{32}-X`),
Keywords: []string{"FLWPUBK_TEST"},
}
// validate
tps := []string{
generateSampleSecret("flutterwavePubKey", "FLWPUBK_TEST-"+secrets.NewSecret(hex("32"))+"-X"),
}
return validate(r, tps, nil)
}
func FlutterwaveSecretKey() *config.Rule {
// define rule
r := config.Rule{
Description: "Flutterwave Secret Key",
RuleID: "flutterwave-secret-key",
Regex: regexp.MustCompile(`FLWSECK_TEST-(?i)[a-h0-9]{32}-X`),
Keywords: []string{"FLWSECK_TEST"},
}
// validate
tps := []string{
generateSampleSecret("flutterwavePubKey", "FLWSECK_TEST-"+secrets.NewSecret(hex("32"))+"-X"),
}
return validate(r, tps, nil)
}
func FlutterwaveEncKey() *config.Rule {
// define rule
r := config.Rule{
Description: "Flutterwave Encryption Key",
RuleID: "flutterwave-encryption-key",
Regex: regexp.MustCompile(`FLWSECK_TEST-(?i)[a-h0-9]{12}`),
Keywords: []string{"FLWSECK_TEST"},
}
// validate
tps := []string{
generateSampleSecret("flutterwavePubKey", "FLWSECK_TEST-"+secrets.NewSecret(hex("12"))),
}
return validate(r, tps, nil)
}
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func FrameIO() *config.Rule {
// define rule
r := config.Rule{
Description: "Frame.io API token",
RuleID: "frameio-api-token",
Regex: regexp.MustCompile(`fio-u-(?i)[a-z0-9\-_=]{64}`),
Keywords: []string{"fio-u-"},
}
// validate
tps := []string{
generateSampleSecret("frameio", "fio-u-"+secrets.NewSecret(alphaNumericExtended("64"))),
}
return validate(r, tps, nil)
}
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
)
// TODO this one could probably use some work
func GCPServiceAccount() *config.Rule {
// define rule
r := config.Rule{
Description: "Google (GCP) Service-account",
RuleID: "gcp-service-account",
Regex: regexp.MustCompile(`\"type\": \"service_account\"`),
Keywords: []string{`\"type\": \"service_account\"`},
}
// validate
tps := []string{
`"type": "service_account"`,
}
return validate(r, tps, nil)
}
+53
View File
@@ -0,0 +1,53 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/config"
)
func GenericCredential() *config.Rule {
// define rule
r := config.Rule{
RuleID: "generic-api-key",
Description: "Generic API Key",
Regex: generateSemiGenericRegex([]string{
"key",
"api",
"token",
"secret",
"client",
"passwd",
"password",
"auth",
}, `[0-9a-z\-_.=]{10,150}`),
SecretGroup: 1,
Keywords: []string{
"key",
"api",
"token",
"secret",
"client",
"passwd",
"password",
"auth",
},
Entropy: 3.5,
Allowlist: config.Allowlist{
StopWords: DefaultStopWords,
},
}
// validate
tps := []string{
generateSampleSecret("generic", "CLOJARS_34bf0e88955ff5a1c328d6a7491acc4f48e865a7b8dd4d70a70749037443"),
generateSampleSecret("generic", "Zf3D0LXCM3EIMbgJpUNnkRtOfOueHznB"),
`"client_id" : "0afae57f3ccfd9d7f5767067bc48b30f719e271ba470488056e37ab35d4b6506"`,
`"client_secret" : "6da89121079f83b2eb6acccf8219ea982c3d79bccc3e9c6a85856480661f8fde",`,
}
fps := []string{
`client_vpn_endpoint_id = aws_ec2_client_vpn_endpoint.client-vpn-endpoint.id`,
`password combination.
R5: Regulatory--21`,
}
return validate(r, tps, fps)
}
+73
View File
@@ -0,0 +1,73 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func GitHubPat() *config.Rule {
// define rule
r := config.Rule{
Description: "GitHub Personal Access Token",
RuleID: "github-pat",
Regex: regexp.MustCompile(`ghp_[0-9a-zA-Z]{36}`),
Keywords: []string{"ghp_"},
}
// validate
tps := []string{
generateSampleSecret("github", "ghp_"+secrets.NewSecret(alphaNumeric("36"))),
}
return validate(r, tps, nil)
}
func GitHubOauth() *config.Rule {
// define rule
r := config.Rule{
Description: "GitHub OAuth Access Token",
RuleID: "github-oauth",
Regex: regexp.MustCompile(`gho_[0-9a-zA-Z]{36}`),
Keywords: []string{"gho_"},
}
// validate
tps := []string{
generateSampleSecret("github", "gho_"+secrets.NewSecret(alphaNumeric("36"))),
}
return validate(r, tps, nil)
}
func GitHubApp() *config.Rule {
// define rule
r := config.Rule{
Description: "GitHub App Token",
RuleID: "github-app-token",
Regex: regexp.MustCompile(`(ghu|ghs)_[0-9a-zA-Z]{36}`),
Keywords: []string{"ghu_", "ghs_"},
}
// validate
tps := []string{
generateSampleSecret("github", "ghu_"+secrets.NewSecret(alphaNumeric("36"))),
generateSampleSecret("github", "ghs_"+secrets.NewSecret(alphaNumeric("36"))),
}
return validate(r, tps, nil)
}
func GitHubRefresh() *config.Rule {
// define rule
r := config.Rule{
Description: "GitHub Refresh Token",
RuleID: "github-refresh-token",
Regex: regexp.MustCompile(`ghr_[0-9a-zA-Z]{36}`),
Keywords: []string{"ghr_"},
}
// validate
tps := []string{
generateSampleSecret("github", "ghr_"+secrets.NewSecret(alphaNumeric("36"))),
}
return validate(r, tps, nil)
}
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Gitlab() *config.Rule {
// define rule
r := config.Rule{
Description: "Gitlab Personal Access Token",
RuleID: "gitlab-pat",
Regex: regexp.MustCompile(`glpat-[0-9a-zA-Z\-\_]{20}`),
Keywords: []string{"glpat-"},
}
// validate
tps := []string{
generateSampleSecret("gitlab", "glpat-"+secrets.NewSecret(alphaNumeric("20"))),
}
return validate(r, tps, nil)
}
+26
View File
@@ -0,0 +1,26 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func GoCardless() *config.Rule {
// define rule
r := config.Rule{
RuleID: "gocardless-api-token",
Description: "GoCardless API token",
Regex: generateSemiGenericRegex([]string{"gocardless"}, `live_(?i)[a-z0-9\-_=]{40}`),
SecretGroup: 1,
Keywords: []string{
"live_",
"gocardless",
},
}
// validate
tps := []string{
generateSampleSecret("gocardless", "live_"+secrets.NewSecret(alphaNumericExtended("40"))),
}
return validate(r, tps, nil)
}
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Hashicorp() *config.Rule {
// define rule
r := config.Rule{
Description: "HashiCorp Terraform user/org API token",
RuleID: "hashicorp-tf-api-token",
Regex: regexp.MustCompile(`(?i)[a-z0-9]{14}\.atlasv1\.[a-z0-9\-_=]{60,70}`),
Keywords: []string{"atlasv1"},
}
// validate
tps := []string{
generateSampleSecret("hashicorpToken", secrets.NewSecret(hex("14"))+".atlasv1."+secrets.NewSecret(alphaNumericExtended("60,70"))),
}
return validate(r, tps, nil)
}
+23
View File
@@ -0,0 +1,23 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/config"
)
func Heroku() *config.Rule {
// define rule
r := config.Rule{
Description: "Heroku API Key",
RuleID: "heroku-api-key",
Regex: generateSemiGenericRegex([]string{"heroku"},
`[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}`),
SecretGroup: 1,
Keywords: []string{"heroku"},
}
// validate
tps := []string{
`const HEROKU_KEY = "12345678-ABCD-ABCD-ABCD-1234567890AB"`, // gitleaks:allow
}
return validate(r, tps, nil)
}
+23
View File
@@ -0,0 +1,23 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/config"
)
func HubSpot() *config.Rule {
// define rule
r := config.Rule{
Description: "HubSpot API Token",
RuleID: "hubspot-api-key",
Regex: generateSemiGenericRegex([]string{"hubspot"},
`[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}`),
SecretGroup: 1,
Keywords: []string{"hubspot"},
}
// validate
tps := []string{
`const hubspotKey = "12345678-ABCD-ABCD-ABCD-1234567890AB"`, // gitleaks:allow
}
return validate(r, tps, nil)
}
+23
View File
@@ -0,0 +1,23 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Intercom() *config.Rule {
// define rule
r := config.Rule{
Description: "Intercom API Token",
RuleID: "intercom-api-key",
Regex: generateSemiGenericRegex([]string{"intercom"}, alphaNumericExtended("60")),
SecretGroup: 1,
Keywords: []string{"intercom"},
}
// validate
tps := []string{
generateSampleSecret("intercom", secrets.NewSecret(alphaNumericExtended("60"))),
}
return validate(r, tps, nil)
}
+41
View File
@@ -0,0 +1,41 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func LinearAPIToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Linear API Token",
RuleID: "linear-api-key",
Regex: regexp.MustCompile(`lin_api_(?i)[a-z0-9]{40}`),
Keywords: []string{"lin_api_"},
}
// validate
tps := []string{
generateSampleSecret("linear", "lin_api_"+secrets.NewSecret(alphaNumeric("40"))),
}
return validate(r, tps, nil)
}
func LinearClientSecret() *config.Rule {
// define rule
r := config.Rule{
Description: "Linear Client Secret",
RuleID: "linear-client-secret",
Regex: generateSemiGenericRegex([]string{"linear"}, hex("32")),
Keywords: []string{"linear"},
SecretGroup: 1,
}
// validate
tps := []string{
generateSampleSecret("linear", secrets.NewSecret(hex("32"))),
}
return validate(r, tps, nil)
}
+52
View File
@@ -0,0 +1,52 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func LinkedinClientSecret() *config.Rule {
// define rule
r := config.Rule{
RuleID: "linkedin-client-secret",
Description: "LinkedIn Client secret",
Regex: generateSemiGenericRegex([]string{
"linkedin",
"linked-in",
}, alphaNumeric("16")),
SecretGroup: 1,
Keywords: []string{
"linkedin",
"linked-in",
},
}
// validate
tps := []string{
generateSampleSecret("linkedin", secrets.NewSecret(alphaNumeric("16"))),
}
return validate(r, tps, nil)
}
func LinkedinClientID() *config.Rule {
// define rule
r := config.Rule{
RuleID: "linkedin-client-id",
Description: "LinkedIn Client ID",
Regex: generateSemiGenericRegex([]string{
"linkedin",
"linked-in",
}, alphaNumeric("14")),
SecretGroup: 1,
Keywords: []string{
"linkedin",
"linked-in",
},
}
// validate
tps := []string{
generateSampleSecret("linkedin", secrets.NewSecret(alphaNumeric("14"))),
}
return validate(r, tps, nil)
}
+47
View File
@@ -0,0 +1,47 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func LobPubAPIToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Lob Publishable API Key",
RuleID: "lob-pub-api-key",
Regex: generateSemiGenericRegex([]string{"lob"}, `(test|live)_pub_[a-f0-9]{31}`),
SecretGroup: 1,
Keywords: []string{
"test_pub",
"live_pub",
"_pub",
},
}
// validate
tps := []string{
generateSampleSecret("lob", "test_pub_"+secrets.NewSecret(hex("31"))),
}
return validate(r, tps, nil)
}
func LobAPIToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Lob API Key",
RuleID: "lob-api-key",
Regex: generateSemiGenericRegex([]string{"lob"}, `(live|test)_[a-f0-9]{35}`),
Keywords: []string{
"test_",
"live_",
},
SecretGroup: 1,
}
// validate
tps := []string{
generateSampleSecret("lob", "test_"+secrets.NewSecret(hex("35"))),
}
return validate(r, tps, nil)
}
+25
View File
@@ -0,0 +1,25 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func MailChimp() *config.Rule {
// define rule
r := config.Rule{
RuleID: "mailchimp-api-key",
Description: "Mailchimp API key",
Regex: generateSemiGenericRegex([]string{"mailchimp"}, `[a-f0-9]{32}-us20`),
SecretGroup: 1,
Keywords: []string{
"mailchimp",
},
}
// validate
tps := []string{
generateSampleSecret("mailchimp", secrets.NewSecret(hex("32"))+"-us20"),
}
return validate(r, tps, nil)
}
+63
View File
@@ -0,0 +1,63 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func MailGunPrivateAPIToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "mailgun-private-api-token",
Description: "Mailgun private API token",
Regex: generateSemiGenericRegex([]string{"mailgun"}, `key-[a-f0-9]{32}`),
SecretGroup: 1,
Keywords: []string{
"mailgun",
},
}
// validate
tps := []string{
generateSampleSecret("mailgun", "key-"+secrets.NewSecret(hex("32"))),
}
return validate(r, tps, nil)
}
func MailGunPubAPIToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "mailgun-pub-key",
Description: "Mailgun public validation key",
Regex: generateSemiGenericRegex([]string{"mailgun"}, `pubkey-[a-f0-9]{32}`),
SecretGroup: 1,
Keywords: []string{
"mailgun",
},
}
// validate
tps := []string{
generateSampleSecret("mailgun", "pubkey-"+secrets.NewSecret(hex("32"))),
}
return validate(r, tps, nil)
}
func MailGunSigningKey() *config.Rule {
// define rule
r := config.Rule{
RuleID: "mailgun-signing-key",
Description: "Mailgun webhook signing key",
Regex: generateSemiGenericRegex([]string{"mailgun"}, `[a-h0-9]{32}-[a-h0-9]{8}-[a-h0-9]{8}`),
SecretGroup: 1,
Keywords: []string{
"mailgun",
},
}
// validate
tps := []string{
generateSampleSecret("mailgun", secrets.NewSecret(hex("32"))+"-00001111-22223333"),
}
return validate(r, tps, nil)
}
+23
View File
@@ -0,0 +1,23 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func MapBox() *config.Rule {
// define rule
r := config.Rule{
Description: "MapBox API token",
RuleID: "mapbox-api-token",
Regex: generateSemiGenericRegex([]string{"mapbox"}, `pk\.[a-z0-9]{60}\.[a-z0-9]{22}`),
SecretGroup: 1,
Keywords: []string{"mapbox"},
}
// validate
tps := []string{
generateSampleSecret("mapbox", "pk."+secrets.NewSecret(alphaNumeric("60"))+"."+secrets.NewSecret(alphaNumeric("22"))),
}
return validate(r, tps, nil)
}
+58
View File
@@ -0,0 +1,58 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func MessageBirdAPIToken() *config.Rule {
// define rule
r := config.Rule{
Description: "MessageBird API token",
RuleID: "messagebird-api-token",
Regex: generateSemiGenericRegex([]string{
"messagebird",
"message-bird",
"message_bird",
}, alphaNumeric("25")),
SecretGroup: 1,
Keywords: []string{
"messagebird",
"message-bird",
"message_bird",
},
}
// validate
tps := []string{
generateSampleSecret("messagebird", secrets.NewSecret(alphaNumeric("25"))),
generateSampleSecret("message-bird", secrets.NewSecret(alphaNumeric("25"))),
generateSampleSecret("message_bird", secrets.NewSecret(alphaNumeric("25"))),
}
return validate(r, tps, nil)
}
func MessageBirdClientID() *config.Rule {
// define rule
r := config.Rule{
Description: "MessageBird client ID",
RuleID: "messagebird-client-id",
Regex: generateSemiGenericRegex([]string{
"messagebird",
"message-bird",
"message_bird",
}, `[a-h0-9]{8}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{12}`),
SecretGroup: 1,
Keywords: []string{
"messagebird",
"message-bird",
"message_bird",
},
}
// validate
tps := []string{
`const MessageBirdClientID = "12345678-ABCD-ABCD-ABCD-1234567890AB"`, // gitleaks:allow
}
return validate(r, tps, nil)
}
+77
View File
@@ -0,0 +1,77 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func NewRelicUserID() *config.Rule {
// define rule
r := config.Rule{
RuleID: "new-relic-user-api-key",
Description: "New Relic user API Key",
Regex: generateSemiGenericRegex([]string{
"new-relic",
"newrelic",
"new_relic",
}, `NRAK-[a-z0-9]{27}`),
SecretGroup: 1,
Keywords: []string{
"NRAK",
},
}
// validate
tps := []string{
generateSampleSecret("new-relic", "NRAK-"+secrets.NewSecret(alphaNumeric("27"))),
}
return validate(r, tps, nil)
}
func NewRelicUserKey() *config.Rule {
// define rule
r := config.Rule{
RuleID: "new-relic-user-api-id",
Description: "New Relic user API ID",
Regex: generateSemiGenericRegex([]string{
"new-relic",
"newrelic",
"new_relic",
}, alphaNumeric("64")),
SecretGroup: 1,
Keywords: []string{
"new-relic",
"newrelic",
"new_relic",
},
}
// validate
tps := []string{
generateSampleSecret("new-relic", secrets.NewSecret(alphaNumeric("64"))),
}
return validate(r, tps, nil)
}
func NewRelicBrowserAPIKey() *config.Rule {
// define rule
r := config.Rule{
RuleID: "new-relic-browser-api-token",
Description: "New Relic ingest browser API token",
Regex: generateSemiGenericRegex([]string{
"new-relic",
"newrelic",
"new_relic",
}, `NRJS-[a-f0-9]{19}`),
SecretGroup: 1,
Keywords: []string{
"NRJS-",
},
}
// validate
tps := []string{
generateSampleSecret("new-relic", "NRJS-"+secrets.NewSecret(hex("19"))),
}
return validate(r, tps, nil)
}
+25
View File
@@ -0,0 +1,25 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func NPM() *config.Rule {
// define rule
r := config.Rule{
RuleID: "npm-access-token",
Description: "npm access token",
Regex: generateUniqueTokenRegex(`npm_[a-z0-9]{36}`),
SecretGroup: 1,
Keywords: []string{
"npm_",
},
}
// validate
tps := []string{
generateSampleSecret("npmAccessToken", "npm_"+secrets.NewSecret(alphaNumeric("36"))),
}
return validate(r, tps, nil)
}
+69
View File
@@ -0,0 +1,69 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func PlanetScalePassword() *config.Rule {
// define rule
r := config.Rule{
RuleID: "planetscale-password",
Description: "PlanetScale password",
Regex: generateUniqueTokenRegex(`pscale_pw_(?i)[a-z0-9=\-_\.]{32,64}`),
SecretGroup: 1,
Keywords: []string{
"pscale_pw_",
},
}
// validate
tps := []string{
generateSampleSecret("planetScalePassword", "pscale_pw_"+secrets.NewSecret(alphaNumericExtended("32"))),
generateSampleSecret("planetScalePassword", "pscale_pw_"+secrets.NewSecret(alphaNumericExtended("43"))),
generateSampleSecret("planetScalePassword", "pscale_pw_"+secrets.NewSecret(alphaNumericExtended("64"))),
}
return validate(r, tps, nil)
}
func PlanetScaleAPIToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "planetscale-api-token",
Description: "PlanetScale API token",
Regex: generateUniqueTokenRegex(`pscale_tkn_(?i)[a-z0-9=\-_\.]{32,64}`),
SecretGroup: 1,
Keywords: []string{
"pscale_tkn_",
},
}
// validate
tps := []string{
generateSampleSecret("planetScalePassword", "pscale_tkn_"+secrets.NewSecret(alphaNumericExtended("32"))),
generateSampleSecret("planetScalePassword", "pscale_tkn_"+secrets.NewSecret(alphaNumericExtended("43"))),
generateSampleSecret("planetScalePassword", "pscale_tkn_"+secrets.NewSecret(alphaNumericExtended("64"))),
}
return validate(r, tps, nil)
}
func PlanetScaleOAuthToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "planetscale-oauth-token",
Description: "PlanetScale OAuth token",
Regex: generateUniqueTokenRegex(`pscale_oauth_(?i)[a-z0-9=\-_\.]{32,64}`),
SecretGroup: 1,
Keywords: []string{
"pscale_oauth_",
},
}
// validate
tps := []string{
generateSampleSecret("planetScalePassword", "pscale_oauth_"+secrets.NewSecret(alphaNumericExtended("32"))),
generateSampleSecret("planetScalePassword", "pscale_oauth_"+secrets.NewSecret(alphaNumericExtended("43"))),
generateSampleSecret("planetScalePassword", "pscale_oauth_"+secrets.NewSecret(alphaNumericExtended("64"))),
}
return validate(r, tps, nil)
}
+25
View File
@@ -0,0 +1,25 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func PostManAPI() *config.Rule {
// define rule
r := config.Rule{
RuleID: "postman-api-token",
Description: "Postman API token",
Regex: generateUniqueTokenRegex(`PMAK-(?i)[a-f0-9]{24}\-[a-f0-9]{34}`),
SecretGroup: 1,
Keywords: []string{
"PMAK-",
},
}
// validate
tps := []string{
generateSampleSecret("postmanAPItoken", "PMAK-"+secrets.NewSecret(hex("24"))+"-"+secrets.NewSecret(hex("34"))),
}
return validate(r, tps, nil)
}
+28
View File
@@ -0,0 +1,28 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
)
func PrivateKey() *config.Rule {
// define rule
r := config.Rule{
Description: "Private Key",
RuleID: "private-key",
Regex: regexp.MustCompile(`(?i)-----BEGIN[ A-Z0-9_-]{0,100}PRIVATE KEY-----[\s\S-]*KEY----`),
Keywords: []string{"-----BEGIN"},
}
// validate
tps := []string{`-----BEGIN PRIVATE KEY-----
anything
-----END PRIVATE KEY-----`,
`-----BEGIN RSA PRIVATE KEY-----
abcdefghijklmnopqrstuvwxyz
-----END RSA PRIVATE KEY-----
`,
} // gitleaks:allow
return validate(r, tps, nil)
}
+25
View File
@@ -0,0 +1,25 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func PulumiAPIToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "pulumi-api-token",
Description: "Pulumi API token",
Regex: generateUniqueTokenRegex(`pul-[a-f0-9]{40}`),
SecretGroup: 1,
Keywords: []string{
"pul-",
},
}
// validate
tps := []string{
generateSampleSecret("pulumi-api-token", "pul-"+secrets.NewSecret(hex("40"))),
}
return validate(r, tps, nil)
}
+26
View File
@@ -0,0 +1,26 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func PyPiUploadToken() *config.Rule {
// define rule
r := config.Rule{
Description: "PyPI upload token",
RuleID: "pypi-upload-token",
Regex: regexp.MustCompile(
`pypi-AgEIcHlwaS5vcmc[A-Za-z0-9\-_]{50,1000}`),
Keywords: []string{
"pypi-AgEIcHlwaS5vcmc",
},
}
// validate
tps := []string{"pypiToken := \"pypi-AgEIcHlwaS5vcmc" + secrets.NewSecret(hex("32")) +
secrets.NewSecret(hex("32")) + "\""}
return validate(r, tps, nil)
}
+25
View File
@@ -0,0 +1,25 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func RubyGemsAPIToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "rubygems-api-token",
Description: "Rubygem API token",
Regex: generateUniqueTokenRegex(`rubygems_[a-f0-9]{48}`),
SecretGroup: 1,
Keywords: []string{
"rubygems_",
},
}
// validate
tps := []string{
generateSampleSecret("rubygemsAPIToken", "rubygems_"+secrets.NewSecret(hex("48"))),
}
return validate(r, tps, nil)
}
+96
View File
@@ -0,0 +1,96 @@
package rules
import (
"fmt"
"regexp"
"strings"
"github.com/rs/zerolog/log"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/detect"
)
const (
// case insensitive prefix
caseInsensitive = `(?i)`
// identifier prefix (just an ignore group)
identifierPrefix = `(?:`
identifierSuffix = `)(?:[0-9a-z\-_\t .]{0,20})(?:[\s|']|[\s|"]){0,3}`
// commonly used assignment operators or function call
operator = `(?:=|>|:=|\|\|:|<=|=>|:)`
// boundaries for the secret
// \x60 = `
secretPrefixUnique = `\b(`
secretPrefix = `(?:'|\"|\s|=|\x60){0,5}(`
secretSuffix = `)(?:['|\"|\n|\r|\s|\x60]|$)`
)
func generateSemiGenericRegex(identifiers []string, secretRegex string) *regexp.Regexp {
var sb strings.Builder
sb.WriteString(caseInsensitive)
sb.WriteString(identifierPrefix)
sb.WriteString(strings.Join(identifiers, "|"))
sb.WriteString(identifierSuffix)
sb.WriteString(operator)
sb.WriteString(secretPrefix)
sb.WriteString(secretRegex)
sb.WriteString(secretSuffix)
return regexp.MustCompile(sb.String())
}
func generateUniqueTokenRegex(secretRegex string) *regexp.Regexp {
var sb strings.Builder
sb.WriteString(caseInsensitive)
sb.WriteString(secretPrefixUnique)
sb.WriteString(secretRegex)
sb.WriteString(secretSuffix)
return regexp.MustCompile(sb.String())
}
func generateSampleSecret(identifier string, secret string) string {
return fmt.Sprintf("%s_api_token = \"%s\"", identifier, secret)
}
func validate(r config.Rule, truePositives []string, falsePositives []string) *config.Rule {
// normalize keywords like in the config package
var keywords []string
for _, k := range r.Keywords {
keywords = append(keywords, strings.ToLower(k))
}
r.Keywords = keywords
d := detect.NewDetector(config.Config{
Rules: []*config.Rule{&r},
Keywords: keywords,
})
for _, tp := range truePositives {
if len(d.DetectString(tp)) != 1 {
log.Fatal().Msgf("Failed to validate (tp) %s %s", r.RuleID, tp)
}
}
for _, fp := range falsePositives {
if len(d.DetectString(fp)) != 0 {
log.Fatal().Msgf("Failed to validate (fp) %s", r.RuleID)
}
}
return &r
}
func numeric(size string) string {
return fmt.Sprintf(`[0-9]{%s}`, size)
}
func hex(size string) string {
return fmt.Sprintf(`[a-f0-9]{%s}`, size)
}
func alphaNumeric(size string) string {
return fmt.Sprintf(`[a-z0-9]{%s}`, size)
}
func alphaNumericExtended(size string) string {
return fmt.Sprintf(`[a-z0-9=_\-]{%s}`, size)
}
+25
View File
@@ -0,0 +1,25 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func SendGridAPIToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "sendgrid-api-token",
Description: "SendGrid API token",
Regex: generateUniqueTokenRegex(`SG\.(?i)[a-z0-9=_\-\.]{66}`),
SecretGroup: 1,
Keywords: []string{
"SG.",
},
}
// validate
tps := []string{
generateSampleSecret("sengridAPIToken", "SG."+secrets.NewSecret(alphaNumericExtended("66"))),
}
return validate(r, tps, nil)
}
+25
View File
@@ -0,0 +1,25 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func SendInBlueAPIToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "sendinblue-api-token",
Description: "Sendinblue API token",
Regex: generateUniqueTokenRegex(`xkeysib-[a-f0-9]{64}\-(?i)[a-z0-9]{16}`),
SecretGroup: 1,
Keywords: []string{
"xkeysib-",
},
}
// validate
tps := []string{
generateSampleSecret("sendinblue", "xkeysib-"+secrets.NewSecret(hex("64"))+"-"+secrets.NewSecret(alphaNumeric("16"))),
}
return validate(r, tps, nil)
}
+26
View File
@@ -0,0 +1,26 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func ShippoAPIToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "shippo-api-token",
Description: "Shippo API token",
Regex: generateUniqueTokenRegex(`shippo_(live|test)_[a-f0-9]{40}`),
SecretGroup: 1,
Keywords: []string{
"shippo_",
},
}
// validate
tps := []string{
generateSampleSecret("shippo", "shippo_live_"+secrets.NewSecret(hex("40"))),
generateSampleSecret("shippo", "shippo_test_"+secrets.NewSecret(hex("40"))),
}
return validate(r, tps, nil)
}
+64
View File
@@ -0,0 +1,64 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func ShopifySharedSecret() *config.Rule {
// define rule
r := config.Rule{
Description: "Shopify shared secret",
RuleID: "shopify-shared-secret",
Regex: regexp.MustCompile(`shpss_[a-fA-F0-9]{32}`),
Keywords: []string{"shpss_"},
}
// validate
tps := []string{"shopifySecret := \"shpss_" + secrets.NewSecret(hex("32")) + "\""}
return validate(r, tps, nil)
}
func ShopifyAccessToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Shopify access token",
RuleID: "shopify-access-token",
Regex: regexp.MustCompile(`shpat_[a-fA-F0-9]{32}`),
Keywords: []string{"shpat_"},
}
// validate
tps := []string{"shopifyToken := \"shpat_" + secrets.NewSecret(hex("32")) + "\""}
return validate(r, tps, nil)
}
func ShopifyCustomAccessToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Shopify custom access token",
RuleID: "shopify-custom-access-token",
Regex: regexp.MustCompile(`shpca_[a-fA-F0-9]{32}`),
Keywords: []string{"shpca_"},
}
// validate
tps := []string{"shopifyToken := \"shpca_" + secrets.NewSecret(hex("32")) + "\""}
return validate(r, tps, nil)
}
func ShopifyPrivateAppAccessToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Shopify private app access token",
RuleID: "shopify-private-app-access-token",
Regex: regexp.MustCompile(`shppa_[a-fA-F0-9]{32}`),
Keywords: []string{"shppa_"},
}
// validate
tps := []string{"shopifyToken := \"shppa_" + secrets.NewSecret(hex("32")) + "\""}
return validate(r, tps, nil)
}
+50
View File
@@ -0,0 +1,50 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func SlackAccessToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Slack token",
RuleID: "slack-access-token",
Regex: regexp.MustCompile(
"xox[baprs]-([0-9a-zA-Z]{10,48})"),
Keywords: []string{
"xoxb",
"xoxa",
"xoxp",
"xoxr",
"xoxs",
},
}
// validate
tps := []string{
"\"slackToken\": \"xoxb-" + secrets.NewSecret(alphaNumeric("30")) + "\"",
}
return validate(r, tps, nil)
}
func SlackWebHook() *config.Rule {
// define rule
r := config.Rule{
Description: "Slack Webhook",
RuleID: "slack-web-hook",
Regex: regexp.MustCompile(
`https:\/\/hooks.slack.com\/services\/[A-Za-z0-9+\/]{44,46}`),
Keywords: []string{
"hooks.slack.com",
},
}
// validate
tps := []string{
"https://hooks.slack.com/services/" + secrets.NewSecret(alphaNumeric("44")), // gitleaks:allow
}
return validate(r, tps, nil)
}
File diff suppressed because it is too large. Load diff
+27
View File
@@ -0,0 +1,27 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func StripeAccessToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Stripe",
RuleID: "stripe-access-token",
Regex: regexp.MustCompile(`(?i)(sk|pk)_(test|live)_[0-9a-z]{10,32}`),
Keywords: []string{
"sk_test",
"pk_test",
"sk_live",
"pk_live",
},
}
// validate
tps := []string{"stripeToken := \"sk_test_" + secrets.NewSecret(alphaNumeric("30")) + "\""}
return validate(r, tps, nil)
}
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Twilio() *config.Rule {
// define rule
r := config.Rule{
Description: "Twilio API Key",
RuleID: "twilio-api-key",
Regex: regexp.MustCompile(`SK[0-9a-fA-F]{32}`),
Keywords: []string{"twilio"},
}
// validate
tps := []string{
"twilioAPIKey := \"SK" + secrets.NewSecret(hex("32")) + "\"",
}
return validate(r, tps, nil)
}
+25
View File
@@ -0,0 +1,25 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func TwitchAPIToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "twitch-api-token",
Description: "Twitch API token",
Regex: generateSemiGenericRegex([]string{"twitch"}, alphaNumeric("30")),
SecretGroup: 1,
Keywords: []string{
"twitch",
},
}
// validate
tps := []string{
generateSampleSecret("twitch", secrets.NewSecret(alphaNumeric("30"))),
}
return validate(r, tps, nil)
}
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Twitter() *config.Rule {
// define rule
r := config.Rule{
Description: "twitter",
RuleID: "twitter",
Regex: generateSemiGenericRegex([]string{"twitter"}, hex("35,44")),
SecretGroup: 1,
Keywords: []string{"twitter"},
}
// validate
tps := []string{
"twitterToken := \"" + secrets.NewSecret(hex("36")) + "aaaa\"",
"twitterToken := `" + secrets.NewSecret(hex("36")) + "aaaa`",
}
return validate(r, tps, nil)
}
+26
View File
@@ -0,0 +1,26 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Typeform() *config.Rule {
// define rule
r := config.Rule{
RuleID: "typeform-api-token",
Description: "Typeform API token",
Regex: generateSemiGenericRegex([]string{"typeform"},
`tfp_[a-z0-9\-_\.=]{59}`),
SecretGroup: 1,
Keywords: []string{
"tfp_",
},
}
// validate
tps := []string{
generateSampleSecret("typeformAPIToken", "tfp_"+secrets.NewSecret(alphaNumericExtended("59"))),
}
return validate(r, tps, nil)
}
+15
View File
@@ -0,0 +1,15 @@
// Package reggen generates text based on regex definitions
// This is a slightly altered version of https://github.com/lucasjones/reggen
package secrets
import (
"github.com/lucasjones/reggen"
)
func NewSecret(regex string) string {
g, err := reggen.NewGenerator(regex)
if err != nil {
panic(err)
}
return g.Generate(1)
}
+105
View File
@@ -0,0 +1,105 @@
package cmd
import (
"os"
"path/filepath"
"time"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/detect"
"github.com/zricethezav/gitleaks/v8/report"
)
func init() {
protectCmd.Flags().Bool("staged", false, "detect secrets in a --staged state")
rootCmd.AddCommand(protectCmd)
}
var protectCmd = &cobra.Command{
Use: "protect",
Short: "protect secrets in code",
Run: runProtect,
}
func runProtect(cmd *cobra.Command, args []string) {
initConfig()
var vc config.ViperConfig
if err := viper.Unmarshal(&vc); err != nil {
log.Fatal().Err(err).Msg("Failed to load config")
}
cfg, err := vc.Translate()
if err != nil {
log.Fatal().Err(err).Msg("Failed to load config")
}
cfg.Path, _ = cmd.Flags().GetString("config")
exitCode, _ := cmd.Flags().GetInt("exit-code")
staged, _ := cmd.Flags().GetBool("staged")
start := time.Now()
// Setup detector
detector := detect.NewDetector(cfg)
detector.Config.Path, err = cmd.Flags().GetString("config")
if err != nil {
log.Fatal().Err(err)
}
source, err := cmd.Flags().GetString("source")
if err != nil {
log.Fatal().Err(err)
}
// if config path is not set, then use the {source}/.gitleaks.toml path.
// note that there may not be a `{source}/.gitleaks.toml` file, this is ok.
if detector.Config.Path == "" {
detector.Config.Path = filepath.Join(source, ".gitleaks.toml")
}
// set verbose flag
if detector.Verbose, err = cmd.Flags().GetBool("verbose"); err != nil {
log.Fatal().Err(err)
}
// set redact flag
if detector.Redact, err = cmd.Flags().GetBool("redact"); err != nil {
log.Fatal().Err(err)
}
// get log options for git scan
logOpts, err := cmd.Flags().GetString("log-opts")
if err != nil {
log.Fatal().Err(err)
}
// start git scan
var findings []report.Finding
if staged {
findings, err = detector.DetectGit(source, logOpts, detect.ProtectStagedType)
} else {
findings, err = detector.DetectGit(source, logOpts, detect.ProtectType)
}
if err != nil {
// don't exit on error, just log it
log.Error().Err(err)
}
// log info about the scan
log.Info().Msgf("scan completed in %s", time.Since(start))
if len(findings) != 0 {
log.Warn().Msgf("leaks found: %d", len(findings))
} else {
log.Info().Msg("no leaks found")
}
reportPath, _ := cmd.Flags().GetString("report-path")
ext, _ := cmd.Flags().GetString("report-format")
if reportPath != "" {
if err = report.Write(findings, cfg, ext, reportPath); err != nil {
log.Fatal().Err(err)
}
}
if len(findings) != 0 {
os.Exit(exitCode)
}
}
+137
View File
@@ -0,0 +1,137 @@
package cmd
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/zricethezav/gitleaks/v8/config"
)
const banner = `
○
│╲
│ ○
○ ░
░ gitleaks
`
const configDescription = `config file path
order of precedence:
1. --config/-c
2. env var GITLEAKS_CONFIG
3. (--source/-s)/.gitleaks.toml
If none of the three options are used, then gitleaks will use the default config`
var rootCmd = &cobra.Command{
Use: "gitleaks",
Short: "Gitleaks scans code, past or present, for secrets",
}
func init() {
cobra.OnInitialize(initLog)
rootCmd.PersistentFlags().StringP("config", "c", "", configDescription)
rootCmd.PersistentFlags().Int("exit-code", 1, "exit code when leaks have been encountered")
rootCmd.PersistentFlags().StringP("source", "s", ".", "path to source (default: $PWD)")
rootCmd.PersistentFlags().StringP("report-path", "r", "", "report file")
rootCmd.PersistentFlags().StringP("report-format", "f", "json", "output format (json, csv, sarif)")
rootCmd.PersistentFlags().StringP("log-level", "l", "info", "log level (debug, info, warn, error, fatal)")
rootCmd.PersistentFlags().BoolP("verbose", "v", false, "show verbose output from scan")
rootCmd.PersistentFlags().Bool("redact", false, "redact secrets from logs and stdout")
err := viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config"))
if err != nil {
log.Fatal().Msgf("err binding config %s", err.Error())
}
}
func initLog() {
zerolog.SetGlobalLevel(zerolog.InfoLevel)
ll, err := rootCmd.Flags().GetString("log-level")
if err != nil {
log.Fatal().Msg(err.Error())
}
switch strings.ToLower(ll) {
case "debug":
zerolog.SetGlobalLevel(zerolog.DebugLevel)
case "info":
zerolog.SetGlobalLevel(zerolog.InfoLevel)
case "warn":
zerolog.SetGlobalLevel(zerolog.WarnLevel)
case "err", "error":
zerolog.SetGlobalLevel(zerolog.ErrorLevel)
case "fatal":
zerolog.SetGlobalLevel(zerolog.FatalLevel)
default:
zerolog.SetGlobalLevel(zerolog.InfoLevel)
}
}
func initConfig() {
fmt.Fprint(os.Stderr, banner)
cfgPath, err := rootCmd.Flags().GetString("config")
if err != nil {
log.Fatal().Msg(err.Error())
}
if cfgPath != "" {
viper.SetConfigFile(cfgPath)
log.Debug().Msgf("Using gitleaks config %s from `--config`", cfgPath)
} else if os.Getenv("GITLEAKS_CONFIG") != "" {
envPath := os.Getenv("GITLEAKS_CONFIG")
viper.SetConfigFile(envPath)
log.Debug().Msgf("Using gitleaks config from GITLEAKS_CONFIG env var: %s", envPath)
} else {
source, err := rootCmd.Flags().GetString("source")
if err != nil {
log.Fatal().Msg(err.Error())
}
fileInfo, err := os.Stat(source)
if err != nil {
log.Fatal().Msg(err.Error())
}
if !fileInfo.IsDir() {
log.Debug().Msgf("Unable to load gitleaks config from %s since --source=%s is a file, using default config",
filepath.Join(source, ".gitleaks.toml"), source)
viper.SetConfigType("toml")
if err = viper.ReadConfig(strings.NewReader(config.DefaultConfig)); err != nil {
log.Fatal().Msgf("err reading toml %s", err.Error())
}
return
}
if _, err := os.Stat(filepath.Join(source, ".gitleaks.toml")); os.IsNotExist(err) {
log.Debug().Msgf("No gitleaks config found in path %s, using default gitleaks config", filepath.Join(source, ".gitleaks.toml"))
viper.SetConfigType("toml")
if err = viper.ReadConfig(strings.NewReader(config.DefaultConfig)); err != nil {
log.Fatal().Msgf("err reading default config toml %s", err.Error())
}
return
} else {
log.Debug().Msgf("Using existing gitleaks config %s from `(--source)/.gitleaks.toml`", filepath.Join(source, ".gitleaks.toml"))
}
viper.AddConfigPath(source)
viper.SetConfigName(".gitleaks")
viper.SetConfigType("toml")
}
if err := viper.ReadInConfig(); err != nil {
log.Fatal().Msgf("Unable to load gitleaks config, err: %s", err)
}
}
func Execute() {
if err := rootCmd.Execute(); err != nil {
if strings.Contains(err.Error(), "unknown flag") {
// exit code 126: Command invoked cannot execute
os.Exit(126)
}
log.Fatal().Msg(err.Error())
}
}
+23
View File
@@ -0,0 +1,23 @@
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
var Version = "version is set by build process"
func init() {
rootCmd.AddCommand(versionCmd)
}
var versionCmd = &cobra.Command{
Use: "version",
Short: "display gitleaks version",
Run: runVersion,
}
func runVersion(cmd *cobra.Command, args []string) {
fmt.Println(Version)
}
+60
View File
@@ -0,0 +1,60 @@
package config
import (
"regexp"
"strings"
)
// Allowlist allows a rule to be ignored for specific
// regexes, paths, and/or commits
type Allowlist struct {
// Short human readable description of the allowlist.
Description string
// Regexes is slice of content regular expressions that are allowed to be ignored.
Regexes []*regexp.Regexp
// Paths is a slice of path regular expressions that are allowed to be ignored.
Paths []*regexp.Regexp
// Commits is a slice of commit SHAs that are allowed to be ignored.
Commits []string
// StopWords is a slice of stop words that are allowed to be ignored.
// This targets the _secret_, not the content of the regex match like the
// Regexes slice.
StopWords []string
}
// CommitAllowed returns true if the commit is allowed to be ignored.
func (a *Allowlist) CommitAllowed(c string) bool {
if c == "" {
return false
}
for _, commit := range a.Commits {
if commit == c {
return true
}
}
return false
}
// PathAllowed returns true if the path is allowed to be ignored.
func (a *Allowlist) PathAllowed(path string) bool {
return anyRegexMatch(path, a.Paths)
}
// RegexAllowed returns true if the regex is allowed to be ignored.
func (a *Allowlist) RegexAllowed(s string) bool {
return anyRegexMatch(s, a.Regexes)
}
func (a *Allowlist) ContainsStopWord(s string) bool {
s = strings.ToLower(s)
for _, stopWord := range a.StopWords {
if strings.Contains(s, strings.ToLower(stopWord)) {
return true
}
}
return false
}
+93
View File
@@ -0,0 +1,93 @@
package config
import (
"regexp"
"testing"
"github.com/stretchr/testify/assert"
)
func TestCommitAllowed(t *testing.T) {
tests := []struct {
allowlist Allowlist
commit string
commitAllowed bool
}{
{
allowlist: Allowlist{
Commits: []string{"commitA"},
},
commit: "commitA",
commitAllowed: true,
},
{
allowlist: Allowlist{
Commits: []string{"commitB"},
},
commit: "commitA",
commitAllowed: false,
},
{
allowlist: Allowlist{
Commits: []string{"commitB"},
},
commit: "",
commitAllowed: false,
},
}
for _, tt := range tests {
assert.Equal(t, tt.commitAllowed, tt.allowlist.CommitAllowed(tt.commit))
}
}
func TestRegexAllowed(t *testing.T) {
tests := []struct {
allowlist Allowlist
secret string
regexAllowed bool
}{
{
allowlist: Allowlist{
Regexes: []*regexp.Regexp{regexp.MustCompile("matchthis")},
},
secret: "a secret: matchthis, done",
regexAllowed: true,
},
{
allowlist: Allowlist{
Regexes: []*regexp.Regexp{regexp.MustCompile("matchthis")},
},
secret: "a secret",
regexAllowed: false,
},
}
for _, tt := range tests {
assert.Equal(t, tt.regexAllowed, tt.allowlist.RegexAllowed(tt.secret))
}
}
func TestPathAllowed(t *testing.T) {
tests := []struct {
allowlist Allowlist
path string
pathAllowed bool
}{
{
allowlist: Allowlist{
Paths: []*regexp.Regexp{regexp.MustCompile("path")},
},
path: "a path",
pathAllowed: true,
},
{
allowlist: Allowlist{
Paths: []*regexp.Regexp{regexp.MustCompile("path")},
},
path: "a ???",
pathAllowed: false,
},
}
for _, tt := range tests {
assert.Equal(t, tt.pathAllowed, tt.allowlist.PathAllowed(tt.path))
}
}
+131
View File
@@ -0,0 +1,131 @@
package config
import (
_ "embed"
"fmt"
"regexp"
"strings"
)
//go:embed gitleaks.toml
var DefaultConfig string
// ViperConfig is the config struct used by the Viper config package
// to parse the config file. This struct does not include regular expressions.
// It is used as an intermediary to convert the Viper config to the Config struct.
type ViperConfig struct {
Description string
Rules []struct {
ID string
Description string
Entropy float64
SecretGroup int
Regex string
Keywords []string
Path string
Tags []string
Allowlist struct {
Regexes []string
Paths []string
Commits []string
StopWords []string
}
}
Allowlist struct {
Regexes []string
Paths []string
Commits []string
StopWords []string
}
}
// Config is a configuration struct that contains rules and an allowlist if present.
type Config struct {
Path string
Description string
Rules []*Rule
Allowlist Allowlist
Keywords []string
}
func (vc *ViperConfig) Translate() (Config, error) {
var (
rules []*Rule
keywords []string
)
for _, r := range vc.Rules {
var allowlistRegexes []*regexp.Regexp
for _, a := range r.Allowlist.Regexes {
allowlistRegexes = append(allowlistRegexes, regexp.MustCompile(a))
}
var allowlistPaths []*regexp.Regexp
for _, a := range r.Allowlist.Paths {
allowlistPaths = append(allowlistPaths, regexp.MustCompile(a))
}
if r.Keywords == nil {
r.Keywords = []string{}
} else {
for _, k := range r.Keywords {
keywords = append(keywords, strings.ToLower(k))
}
}
if r.Tags == nil {
r.Tags = []string{}
}
var configRegex *regexp.Regexp
var configPathRegex *regexp.Regexp
if r.Regex == "" {
configRegex = nil
} else {
configRegex = regexp.MustCompile(r.Regex)
}
if r.Path == "" {
configPathRegex = nil
} else {
configPathRegex = regexp.MustCompile(r.Path)
}
r := &Rule{
Description: r.Description,
RuleID: r.ID,
Regex: configRegex,
Path: configPathRegex,
SecretGroup: r.SecretGroup,
Entropy: r.Entropy,
Tags: r.Tags,
Keywords: r.Keywords,
Allowlist: Allowlist{
Regexes: allowlistRegexes,
Paths: allowlistPaths,
Commits: r.Allowlist.Commits,
StopWords: r.Allowlist.StopWords,
},
}
if r.Regex != nil && r.SecretGroup > r.Regex.NumSubexp() {
return Config{}, fmt.Errorf("%s invalid regex secret group %d, max regex secret group %d", r.Description, r.SecretGroup, r.Regex.NumSubexp())
}
rules = append(rules, r)
}
var allowlistRegexes []*regexp.Regexp
for _, a := range vc.Allowlist.Regexes {
allowlistRegexes = append(allowlistRegexes, regexp.MustCompile(a))
}
var allowlistPaths []*regexp.Regexp
for _, a := range vc.Allowlist.Paths {
allowlistPaths = append(allowlistPaths, regexp.MustCompile(a))
}
return Config{
Description: vc.Description,
Rules: rules,
Allowlist: Allowlist{
Regexes: allowlistRegexes,
Paths: allowlistPaths,
Commits: vc.Allowlist.Commits,
StopWords: vc.Allowlist.StopWords,
},
Keywords: keywords,
}, nil
}
+124
View File
@@ -0,0 +1,124 @@
package config
import (
"fmt"
"regexp"
"testing"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
)
const configPath = "../testdata/config/"
func TestTranslate(t *testing.T) {
tests := []struct {
cfgName string
cfg Config
wantError error
}{
{
cfgName: "allow_aws_re",
cfg: Config{
Rules: []*Rule{
{
Description: "AWS Access Key",
Regex: regexp.MustCompile("(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}"),
Tags: []string{"key", "AWS"},
Keywords: []string{},
RuleID: "aws-access-key",
Allowlist: Allowlist{
Regexes: []*regexp.Regexp{
regexp.MustCompile("AKIALALEMEL33243OLIA"),
},
},
},
},
},
},
{
cfgName: "allow_commit",
cfg: Config{
Rules: []*Rule{
{
Description: "AWS Access Key",
Regex: regexp.MustCompile("(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}"),
Tags: []string{"key", "AWS"},
Keywords: []string{},
RuleID: "aws-access-key",
Allowlist: Allowlist{
Commits: []string{"allowthiscommit"},
},
},
},
},
},
{
cfgName: "allow_path",
cfg: Config{
Rules: []*Rule{
{
Description: "AWS Access Key",
Regex: regexp.MustCompile("(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}"),
Tags: []string{"key", "AWS"},
Keywords: []string{},
RuleID: "aws-access-key",
Allowlist: Allowlist{
Paths: []*regexp.Regexp{
regexp.MustCompile(".go"),
},
},
},
},
},
},
{
cfgName: "entropy_group",
cfg: Config{
Rules: []*Rule{
{
Description: "Discord API key",
Regex: regexp.MustCompile(`(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-h0-9]{64})['\"]`),
RuleID: "discord-api-key",
Allowlist: Allowlist{},
Entropy: 3.5,
SecretGroup: 3,
Tags: []string{},
Keywords: []string{},
},
},
},
},
{
cfgName: "bad_entropy_group",
cfg: Config{},
wantError: fmt.Errorf("Discord API key invalid regex secret group 5, max regex secret group 3"),
},
}
for _, tt := range tests {
viper.Reset()
viper.AddConfigPath(configPath)
viper.SetConfigName(tt.cfgName)
viper.SetConfigType("toml")
err := viper.ReadInConfig()
if err != nil {
t.Error(err)
}
var vc ViperConfig
err = viper.Unmarshal(&vc)
if err != nil {
t.Error(err)
}
cfg, err := vc.Translate()
if tt.wantError != nil {
if err == nil {
t.Errorf("expected error")
}
assert.Equal(t, tt.wantError, err)
}
assert.Equal(t, cfg.Rules, tt.cfg.Rules)
}
}
+2226
View File
File diff suppressed because it is too large. Load diff
+43
View File
@@ -0,0 +1,43 @@
package config
import (
"regexp"
)
// Rules contain information that define details on how to detect secrets
type Rule struct {
// Description is the description of the rule.
Description string
// RuleID is a unique identifier for this rule
RuleID string
// Entropy is a float representing the minimum shannon
// entropy a regex group must have to be considered a secret.
Entropy float64
// SecretGroup is an int used to extract secret from regex
// match and used as the group that will have its entropy
// checked if `entropy` is set.
SecretGroup int
// Regex is a golang regular expression used to detect secrets.
Regex *regexp.Regexp
// Path is a golang regular expression used to
// filter secrets by path
Path *regexp.Regexp
// Tags is an array of strings used for metadata
// and reporting purposes.
Tags []string
// Keywords are used for pre-regex check filtering. Rules that contain
// keywords will perform a quick string compare check to make sure the
// keyword(s) are in the content being scanned.
Keywords []string
// Allowlist allows a rule to be ignored for specific
// regexes, paths, and/or commits
Allowlist Allowlist
}
+24
View File
@@ -0,0 +1,24 @@
package config
import (
"regexp"
)
func anyRegexMatch(f string, res []*regexp.Regexp) bool {
for _, re := range res {
if regexMatched(f, re) {
return true
}
}
return false
}
func regexMatched(f string, re *regexp.Regexp) bool {
if re == nil {
return false
}
if re.FindString(f) != "" {
return true
}
return false
}
+442
View File
@@ -0,0 +1,442 @@
package detect
import (
"context"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/detect/git"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/fatih/semgroup"
"github.com/gitleaks/go-gitdiff/gitdiff"
"github.com/h2non/filetype"
ahocorasick "github.com/petar-dambovaliev/aho-corasick"
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
)
// Type used to differentiate between git scan types:
// $ gitleaks detect
// $ gitleaks protect
// $ gitleaks protect staged
type GitScanType int
const (
DetectType GitScanType = iota
ProtectType
ProtectStagedType
gitleaksAllowSignature = "gitleaks:allow"
)
// Detector is the main detector struct
type Detector struct {
// Config is the configuration for the detector
Config config.Config
// Redact is a flag to redact findings. This is exported
// so users using gitleaks as a library can set this flag
// without calling `detector.Start(cmd *cobra.Command)`
Redact bool
// verbose is a flag to print findings
Verbose bool
// commitMap is used to keep track of commits that have been scanned.
// This is only used for logging purposes and git scans.
commitMap map[string]bool
// findingMutex is to prevent concurrent access to the
// findings slice when adding findings.
findingMutex *sync.Mutex
// findings is a slice of report.Findings. This is the result
// of the detector's scan which can then be used to generate a
// report.
findings []report.Finding
// prefilter is a ahocorasick struct used for doing efficient string
// matching given a set of words (keywords from the rules in the config)
prefilter ahocorasick.AhoCorasick
}
// Fragment contains the data to be scanned
type Fragment struct {
// Raw is the raw content of the fragment
Raw string
// FilePath is the path to the file if applicable
FilePath string
// CommitSHA is the SHA of the commit if applicable
CommitSHA string
// newlineIndices is a list of indices of newlines in the raw content.
// This is used to calculate the line location of a finding
newlineIndices [][]int
// keywords is a map of all the keywords contain within the contents
// of this fragment
keywords map[string]bool
}
// NewDetector creates a new detector with the given config
func NewDetector(cfg config.Config) *Detector {
builder := ahocorasick.NewAhoCorasickBuilder(ahocorasick.Opts{
AsciiCaseInsensitive: true,
MatchOnlyWholeWords: false,
MatchKind: ahocorasick.LeftMostLongestMatch,
DFA: true,
})
return &Detector{
commitMap: make(map[string]bool),
findingMutex: &sync.Mutex{},
findings: make([]report.Finding, 0),
Config: cfg,
prefilter: builder.Build(cfg.Keywords),
}
}
// NewDetectorDefaultConfig creates a new detector with the default config
func NewDetectorDefaultConfig() (*Detector, error) {
viper.SetConfigType("toml")
err := viper.ReadConfig(strings.NewReader(config.DefaultConfig))
if err != nil {
return nil, err
}
var vc config.ViperConfig
err = viper.Unmarshal(&vc)
if err != nil {
return nil, err
}
cfg, err := vc.Translate()
if err != nil {
return nil, err
}
return NewDetector(cfg), nil
}
// DetectBytes scans the given bytes and returns a list of findings
func (d *Detector) DetectBytes(content []byte) []report.Finding {
return d.DetectString(string(content))
}
// DetectString scans the given string and returns a list of findings
func (d *Detector) DetectString(content string) []report.Finding {
return d.Detect(Fragment{
Raw: content,
})
}
// detectRule scans the given fragment for the given rule and returns a list of findings
func (d *Detector) detectRule(fragment Fragment, rule *config.Rule) []report.Finding {
var findings []report.Finding
// check if filepath or commit is allowed for this rule
if rule.Allowlist.CommitAllowed(fragment.CommitSHA) ||
rule.Allowlist.PathAllowed(fragment.FilePath) {
return findings
}
if rule.Path != nil && rule.Regex == nil {
// Path _only_ rule
if rule.Path.Match([]byte(fragment.FilePath)) {
finding := report.Finding{
Description: rule.Description,
File: fragment.FilePath,
RuleID: rule.RuleID,
Match: fmt.Sprintf("file detected: %s", fragment.FilePath),
Tags: rule.Tags,
}
return append(findings, finding)
}
} else if rule.Path != nil {
// if path is set _and_ a regex is set, then we need to check both
// so if the path does not match, then we should return early and not
// consider the regex
if !rule.Path.Match([]byte(fragment.FilePath)) {
return findings
}
}
// if path only rule, skip content checks
if rule.Regex == nil {
return findings
}
matchIndices := rule.Regex.FindAllStringIndex(fragment.Raw, -1)
for _, matchIndex := range matchIndices {
// extract secret from match
secret := strings.Trim(fragment.Raw[matchIndex[0]:matchIndex[1]], "\n")
// determine location of match. Note that the location
// in the finding will be the line/column numbers of the _match_
// not the _secret_, which will be different if the secretGroup
// value is set for this rule
loc := location(fragment, matchIndex)
finding := report.Finding{
Description: rule.Description,
File: fragment.FilePath,
RuleID: rule.RuleID,
StartLine: loc.startLine,
EndLine: loc.endLine,
StartColumn: loc.startColumn,
EndColumn: loc.endColumn,
Secret: secret,
Match: secret,
Tags: rule.Tags,
}
if strings.Contains(fragment.Raw[loc.startLineIndex:loc.endLineIndex],
gitleaksAllowSignature) {
continue
}
// check if the secret is in the allowlist
if rule.Allowlist.RegexAllowed(finding.Secret) ||
d.Config.Allowlist.RegexAllowed(finding.Secret) {
continue
}
// extract secret from secret group if set
if rule.SecretGroup != 0 {
groups := rule.Regex.FindStringSubmatch(secret)
if len(groups) <= rule.SecretGroup || len(groups) == 0 {
// Config validation should prevent this
continue
}
secret = groups[rule.SecretGroup]
finding.Secret = secret
}
// check if the secret is in the list of stopwords
if rule.Allowlist.ContainsStopWord(finding.Secret) ||
d.Config.Allowlist.ContainsStopWord(finding.Secret) {
continue
}
// check entropy
entropy := shannonEntropy(finding.Secret)
finding.Entropy = float32(entropy)
if rule.Entropy != 0.0 {
if entropy <= rule.Entropy {
// entropy is too low, skip this finding
continue
}
// NOTE: this is a goofy hack to get around the fact there golang's regex engine
// does not support positive lookaheads. Ideally we would want to add a
// restriction on generic rules regex that requires the secret match group
// contains both numbers and alphabetical characters, not just alphabetical characters.
// What this bit of code does is check if the ruleid is prepended with "generic" and enforces the
// secret contains both digits and alphabetical characters.
// TODO: this should be replaced with stop words
if strings.HasPrefix(rule.RuleID, "generic") {
if !containsDigit(secret) {
continue
}
}
}
findings = append(findings, finding)
}
return findings
}
// GitScan accepts a *gitdiff.File channel which contents a git history generated from
// the output of `git log -p ...`. startGitScan will look at each file (patch) in the history
// and determine if the patch contains any findings.
func (d *Detector) DetectGit(source string, logOpts string, gitScanType GitScanType) ([]report.Finding, error) {
var (
gitdiffFiles <-chan *gitdiff.File
err error
)
switch gitScanType {
case DetectType:
gitdiffFiles, err = git.GitLog(source, logOpts)
if err != nil {
return d.findings, err
}
case ProtectType:
gitdiffFiles, err = git.GitDiff(source, false)
if err != nil {
return d.findings, err
}
case ProtectStagedType:
gitdiffFiles, err = git.GitDiff(source, true)
if err != nil {
return d.findings, err
}
}
s := semgroup.NewGroup(context.Background(), 4)
for gitdiffFile := range gitdiffFiles {
gitdiffFile := gitdiffFile
// skip binary files
if gitdiffFile.IsBinary || gitdiffFile.IsDelete {
continue
}
// Check if commit is allowed
commitSHA := ""
if gitdiffFile.PatchHeader != nil {
commitSHA = gitdiffFile.PatchHeader.SHA
if d.Config.Allowlist.CommitAllowed(gitdiffFile.PatchHeader.SHA) {
continue
}
}
d.addCommit(commitSHA)
s.Go(func() error {
for _, textFragment := range gitdiffFile.TextFragments {
if textFragment == nil {
return nil
}
fragment := Fragment{
Raw: textFragment.Raw(gitdiff.OpAdd),
CommitSHA: commitSHA,
FilePath: gitdiffFile.NewName,
}
for _, finding := range d.Detect(fragment) {
d.addFinding(augmentGitFinding(finding, textFragment, gitdiffFile))
}
}
return nil
})
}
if err := s.Wait(); err != nil {
return d.findings, err
}
log.Debug().Msgf("%d commits scanned. Note: this number might be smaller than expected due to commits with no additions", len(d.commitMap))
return d.findings, nil
}
// DetectFiles accepts a path to a source directory or file and begins a scan of the
// file or directory.
func (d *Detector) DetectFiles(source string) ([]report.Finding, error) {
s := semgroup.NewGroup(context.Background(), 4)
paths := make(chan string)
s.Go(func() error {
defer close(paths)
return filepath.Walk(source,
func(path string, fInfo os.FileInfo, err error) error {
if err != nil {
return err
}
if fInfo.Name() == ".git" && fInfo.IsDir() {
return filepath.SkipDir
}
if fInfo.Mode().IsRegular() {
paths <- path
}
return nil
})
})
for pa := range paths {
p := pa
s.Go(func() error {
b, err := os.ReadFile(p)
if err != nil {
return err
}
mimetype, err := filetype.Match(b)
if err != nil {
return err
}
if mimetype.MIME.Type == "application" {
return nil // skip binary files
}
fragment := Fragment{
Raw: string(b),
FilePath: p,
}
for _, finding := range d.Detect(fragment) {
// need to add 1 since line counting starts at 1
finding.EndLine++
finding.StartLine++
d.addFinding(finding)
}
return nil
})
}
if err := s.Wait(); err != nil {
return d.findings, err
}
return d.findings, nil
}
// Detect scans the given fragment and returns a list of findings
func (d *Detector) Detect(fragment Fragment) []report.Finding {
var findings []report.Finding
// initiate fragment keywords
fragment.keywords = make(map[string]bool)
// check if filepath is allowed
if fragment.FilePath != "" && (d.Config.Allowlist.PathAllowed(fragment.FilePath) ||
fragment.FilePath == d.Config.Path) {
return findings
}
// add newline indices for location calculation in detectRule
fragment.newlineIndices = regexp.MustCompile("\n").FindAllStringIndex(fragment.Raw, -1)
// build keyword map for prefiltering rules
normalizedRaw := strings.ToLower(fragment.Raw)
matches := d.prefilter.FindAll(normalizedRaw)
for _, m := range matches {
fragment.keywords[normalizedRaw[m.Start():m.End()]] = true
}
for _, rule := range d.Config.Rules {
if len(rule.Keywords) == 0 {
// if not keywords are associated with the rule always scan the
// fragment using the rule
findings = append(findings, d.detectRule(fragment, rule)...)
continue
}
fragmentContainsKeyword := false
// check if keywords are in the fragment
for _, k := range rule.Keywords {
if _, ok := fragment.keywords[strings.ToLower(k)]; ok {
fragmentContainsKeyword = true
}
}
if fragmentContainsKeyword {
findings = append(findings, d.detectRule(fragment, rule)...)
}
}
return filter(findings, d.Redact)
}
// addFinding synchronously adds a finding to the findings slice
func (d *Detector) addFinding(finding report.Finding) {
d.findingMutex.Lock()
d.findings = append(d.findings, finding)
if d.Verbose {
printFinding(finding)
}
d.findingMutex.Unlock()
}
// addCommit synchronously adds a commit to the commit slice
func (d *Detector) addCommit(commit string) {
d.commitMap[commit] = true
}
+495
View File
@@ -0,0 +1,495 @@
package detect
import (
"fmt"
"os"
"path/filepath"
"testing"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/report"
)
const configPath = "../testdata/config/"
const repoBasePath = "../testdata/repos/"
func TestDetect(t *testing.T) {
tests := []struct {
cfgName string
fragment Fragment
expectedFindings []report.Finding
wantError error
}{
{
cfgName: "simple",
fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OKIA\ // gitleaks:allow"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "simple",
fragment: Fragment{
Raw: `awsToken := \
\"AKIALALEMEL33243OKIA\ // gitleaks:allow"
`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "simple",
fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OKIA\"
// gitleaks:allow"
`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{
{
Description: "AWS Access Key",
Secret: "AKIALALEMEL33243OKIA",
Match: "AKIALALEMEL33243OKIA",
File: "tmp.go",
RuleID: "aws-access-key",
Tags: []string{"key", "AWS"},
StartLine: 0,
EndLine: 0,
StartColumn: 15,
EndColumn: 34,
Entropy: 3.1464393,
},
},
},
{
cfgName: "escaped_character_group",
fragment: Fragment{
Raw: `pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{
{
Description: "PyPI upload token",
Secret: "pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB",
Match: "pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB",
File: "tmp.go",
RuleID: "pypi-upload-token",
Tags: []string{"key", "pypi"},
StartLine: 1,
EndLine: 1,
StartColumn: 1,
EndColumn: 86,
Entropy: 1.9606875,
},
},
},
{
cfgName: "simple",
fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{
{
Description: "AWS Access Key",
Secret: "AKIALALEMEL33243OLIA",
Match: "AKIALALEMEL33243OLIA",
File: "tmp.go",
RuleID: "aws-access-key",
Tags: []string{"key", "AWS"},
StartLine: 1,
EndLine: 1,
StartColumn: 15,
EndColumn: 34,
Entropy: 3.0841837,
},
},
},
{
cfgName: "allow_aws_re",
fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "allow_path",
fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "allow_commit",
fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: "tmp.go",
CommitSHA: "allowthiscommit",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "entropy_group",
fragment: Fragment{
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{
{
Description: "Discord API key",
Match: "Discord_Public_Key = \"e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5\"",
Secret: "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5",
File: "tmp.go",
RuleID: "discord-api-key",
Tags: []string{},
Entropy: 3.7906237,
StartLine: 1,
EndLine: 1,
StartColumn: 7,
EndColumn: 93,
},
},
},
{
cfgName: "generic_with_py_path",
fragment: Fragment{
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "generic_with_py_path",
fragment: Fragment{
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: "tmp.py",
},
expectedFindings: []report.Finding{
{
Description: "Generic API Key",
Match: "Key = \"e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5\"",
Secret: "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5",
File: "tmp.py",
RuleID: "generic-api-key",
Tags: []string{},
Entropy: 3.7906237,
StartLine: 1,
EndLine: 1,
StartColumn: 22,
EndColumn: 93,
},
},
},
{
cfgName: "path_only",
fragment: Fragment{
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: "tmp.py",
},
expectedFindings: []report.Finding{
{
Description: "Python Files",
Match: "file detected: tmp.py",
File: "tmp.py",
RuleID: "python-files-only",
Tags: []string{},
},
},
},
{
cfgName: "bad_entropy_group",
fragment: Fragment{
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
wantError: fmt.Errorf("Discord API key invalid regex secret group 5, max regex secret group 3"),
},
{
cfgName: "simple",
fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: filepath.Join(configPath, "simple.toml"),
},
expectedFindings: []report.Finding{},
},
{
cfgName: "allow_global_aws_re",
fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "generic_with_py_path",
fragment: Fragment{
Raw: `const Discord_Public_Key = "load2523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: "tmp.py",
},
expectedFindings: []report.Finding{},
},
}
for _, tt := range tests {
viper.Reset()
viper.AddConfigPath(configPath)
viper.SetConfigName(tt.cfgName)
viper.SetConfigType("toml")
err := viper.ReadInConfig()
if err != nil {
t.Error(err)
}
var vc config.ViperConfig
err = viper.Unmarshal(&vc)
if err != nil {
t.Error(err)
}
cfg, err := vc.Translate()
cfg.Path = filepath.Join(configPath, tt.cfgName+".toml")
if tt.wantError != nil {
if err == nil {
t.Errorf("expected error")
}
assert.Equal(t, tt.wantError, err)
}
d := NewDetector(cfg)
findings := d.Detect(tt.fragment)
assert.ElementsMatch(t, tt.expectedFindings, findings)
}
}
// TestFromGit tests the FromGit function
func TestFromGit(t *testing.T) {
tests := []struct {
cfgName string
source string
logOpts string
expectedFindings []report.Finding
}{
{
source: filepath.Join(repoBasePath, "small"),
cfgName: "simple",
expectedFindings: []report.Finding{
{
Description: "AWS Access Key",
StartLine: 20,
EndLine: 20,
StartColumn: 19,
EndColumn: 38,
Secret: "AKIALALEMEL33243OLIA",
Match: "AKIALALEMEL33243OLIA",
File: "main.go",
Date: "2021-11-02T23:37:53Z",
Commit: "1b6da43b82b22e4eaa10bcf8ee591e91abbfc587",
Author: "Zachary Rice",
Email: "zricer@protonmail.com",
Message: "Accidentally add a secret",
RuleID: "aws-access-key",
Tags: []string{"key", "AWS"},
Entropy: 3.0841837,
},
{
Description: "AWS Access Key",
StartLine: 9,
EndLine: 9,
StartColumn: 17,
EndColumn: 36,
Secret: "AKIALALEMEL33243OLIA",
Match: "AKIALALEMEL33243OLIA",
File: "foo/foo.go",
Date: "2021-11-02T23:48:06Z",
Commit: "491504d5a31946ce75e22554cc34203d8e5ff3ca",
Author: "Zach Rice",
Email: "zricer@protonmail.com",
Message: "adding foo package with secret",
RuleID: "aws-access-key",
Tags: []string{"key", "AWS"},
Entropy: 3.0841837,
},
},
},
{
source: filepath.Join(repoBasePath, "small"),
logOpts: "--all foo...",
cfgName: "simple",
expectedFindings: []report.Finding{
{
Description: "AWS Access Key",
StartLine: 9,
EndLine: 9,
StartColumn: 17,
EndColumn: 36,
Secret: "AKIALALEMEL33243OLIA",
Match: "AKIALALEMEL33243OLIA",
Date: "2021-11-02T23:48:06Z",
File: "foo/foo.go",
Commit: "491504d5a31946ce75e22554cc34203d8e5ff3ca",
Author: "Zach Rice",
Email: "zricer@protonmail.com",
Message: "adding foo package with secret",
RuleID: "aws-access-key",
Tags: []string{"key", "AWS"},
Entropy: 3.0841837,
},
},
},
}
err := moveDotGit("dotGit", ".git")
if err != nil {
t.Fatal(err)
}
defer func() {
if err := moveDotGit(".git", "dotGit"); err != nil {
t.Error(err)
}
}()
for _, tt := range tests {
viper.AddConfigPath(configPath)
viper.SetConfigName("simple")
viper.SetConfigType("toml")
err = viper.ReadInConfig()
if err != nil {
t.Error(err)
}
var vc config.ViperConfig
err = viper.Unmarshal(&vc)
if err != nil {
t.Error(err)
}
cfg, err := vc.Translate()
if err != nil {
t.Error(err)
}
detector := NewDetector(cfg)
findings, err := detector.DetectGit(tt.source, tt.logOpts, DetectType)
if err != nil {
t.Error(err)
}
for _, f := range findings {
f.Match = "" // remove lines cause copying and pasting them has some wack formatting
}
assert.ElementsMatch(t, tt.expectedFindings, findings)
}
}
// TestFromGit tests the FromGit function
func TestFromFiles(t *testing.T) {
tests := []struct {
cfgName string
source string
expectedFindings []report.Finding
}{
{
source: filepath.Join(repoBasePath, "nogit"),
cfgName: "simple",
expectedFindings: []report.Finding{
{
Description: "AWS Access Key",
StartLine: 20,
EndLine: 20,
StartColumn: 16,
EndColumn: 35,
Match: "AKIALALEMEL33243OLIA",
Secret: "AKIALALEMEL33243OLIA",
File: "../testdata/repos/nogit/main.go",
RuleID: "aws-access-key",
Tags: []string{"key", "AWS"},
Entropy: 3.0841837,
},
},
},
{
source: filepath.Join(repoBasePath, "nogit", "main.go"),
cfgName: "simple",
expectedFindings: []report.Finding{
{
Description: "AWS Access Key",
StartLine: 20,
EndLine: 20,
StartColumn: 16,
EndColumn: 35,
Match: "AKIALALEMEL33243OLIA",
Secret: "AKIALALEMEL33243OLIA",
File: "../testdata/repos/nogit/main.go",
RuleID: "aws-access-key",
Tags: []string{"key", "AWS"},
Entropy: 3.0841837,
},
},
},
}
for _, tt := range tests {
viper.AddConfigPath(configPath)
viper.SetConfigName("simple")
viper.SetConfigType("toml")
err := viper.ReadInConfig()
if err != nil {
t.Error(err)
}
var vc config.ViperConfig
err = viper.Unmarshal(&vc)
if err != nil {
t.Error(err)
}
cfg, _ := vc.Translate()
detector := NewDetector(cfg)
findings, err := detector.DetectFiles(tt.source)
if err != nil {
t.Error(err)
}
assert.ElementsMatch(t, tt.expectedFindings, findings)
}
}
func moveDotGit(from, to string) error {
repoDirs, err := os.ReadDir("../testdata/repos")
if err != nil {
return err
}
for _, dir := range repoDirs {
if to == ".git" {
_, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), "dotGit"))
if os.IsNotExist(err) {
// dont want to delete the only copy of .git accidentally
continue
}
os.RemoveAll(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), ".git"))
}
if !dir.IsDir() {
continue
}
_, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from))
if os.IsNotExist(err) {
continue
}
err = os.Rename(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from),
fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), to))
if err != nil {
return err
}
}
return nil
}
+112
View File
@@ -0,0 +1,112 @@
package git
import (
"bufio"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/gitleaks/go-gitdiff/gitdiff"
"github.com/rs/zerolog/log"
)
// GitLog returns a channel of gitdiff.File objects from the
// git log -p command for the given source.
func GitLog(source string, logOpts string) (<-chan *gitdiff.File, error) {
sourceClean := filepath.Clean(source)
var cmd *exec.Cmd
if logOpts != "" {
args := []string{"-C", sourceClean, "log", "-p", "-U0"}
args = append(args, strings.Split(logOpts, " ")...)
cmd = exec.Command("git", args...)
} else {
cmd = exec.Command("git", "-C", sourceClean, "log", "-p", "-U0",
"--full-history", "--all")
}
log.Debug().Msgf("executing: %s", cmd.String())
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, err
}
if err := cmd.Start(); err != nil {
return nil, err
}
go listenForStdErr(stderr)
// HACK: to avoid https://github.com/zricethezav/gitleaks/issues/722
time.Sleep(50 * time.Millisecond)
return gitdiff.Parse(stdout)
}
// GitDiff returns a channel of gitdiff.File objects from
// the git diff command for the given source.
func GitDiff(source string, staged bool) (<-chan *gitdiff.File, error) {
sourceClean := filepath.Clean(source)
var cmd *exec.Cmd
cmd = exec.Command("git", "-C", sourceClean, "diff", "-U0", ".")
if staged {
cmd = exec.Command("git", "-C", sourceClean, "diff", "-U0",
"--staged", ".")
}
log.Debug().Msgf("executing: %s", cmd.String())
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, err
}
if err := cmd.Start(); err != nil {
return nil, err
}
go listenForStdErr(stderr)
// HACK: to avoid https://github.com/zricethezav/gitleaks/issues/722
time.Sleep(50 * time.Millisecond)
return gitdiff.Parse(stdout)
}
// listenForStdErr listens for stderr output from git and prints it to stdout
// then exits with exit code 1
func listenForStdErr(stderr io.ReadCloser) {
scanner := bufio.NewScanner(stderr)
errEncountered := false
for scanner.Scan() {
// if git throws the following error:
//
// exhaustive rename detection was skipped due to too many files.
// you may want to set your diff.renameLimit variable to at least
// (some large number) and retry the command.
//
// we skip exiting the program as git log -p/git diff will continue
// to send data to stdout and finish executing. This next bit of
// code prevents gitleaks from stopping mid scan if this error is
// encountered
if strings.Contains(scanner.Text(),
"exhaustive rename detection was skipped") ||
strings.Contains(scanner.Text(),
"you may want to set your diff.renameLimit") {
log.Warn().Msg(scanner.Text())
} else {
log.Error().Msg(scanner.Text())
errEncountered = true
}
}
if errEncountered {
os.Exit(1)
}
}
+158
View File
@@ -0,0 +1,158 @@
package git_test
// TODO: commenting out this test for now because it's flaky. Alternatives to consider to get this working:
// -- use `git stash` instead of `restore()`
// const repoBasePath = "../../testdata/repos/"
// const expectPath = "../../testdata/expected/"
// func TestGitLog(t *testing.T) {
// tests := []struct {
// source string
// logOpts string
// expected string
// }{
// {
// source: filepath.Join(repoBasePath, "small"),
// expected: filepath.Join(expectPath, "git", "small.txt"),
// },
// {
// source: filepath.Join(repoBasePath, "small"),
// expected: filepath.Join(expectPath, "git", "small-branch-foo.txt"),
// logOpts: "--all foo...",
// },
// }
// err := moveDotGit("dotGit", ".git")
// if err != nil {
// t.Fatal(err)
// }
// defer func() {
// if err = moveDotGit(".git", "dotGit"); err != nil {
// t.Fatal(err)
// }
// }()
// for _, tt := range tests {
// files, err := git.GitLog(tt.source, tt.logOpts)
// if err != nil {
// t.Error(err)
// }
// var diffSb strings.Builder
// for f := range files {
// for _, tf := range f.TextFragments {
// diffSb.WriteString(tf.Raw(gitdiff.OpAdd))
// }
// }
// expectedBytes, err := os.ReadFile(tt.expected)
// if err != nil {
// t.Error(err)
// }
// expected := string(expectedBytes)
// if expected != diffSb.String() {
// // write string builder to .got file using os.Create
// err = os.WriteFile(strings.Replace(tt.expected, ".txt", ".got.txt", 1), []byte(diffSb.String()), 0644)
// if err != nil {
// t.Error(err)
// }
// t.Error("expected: ", expected, "got: ", diffSb.String())
// }
// }
// }
// func TestGitDiff(t *testing.T) {
// tests := []struct {
// source string
// expected string
// additions string
// target string
// }{
// {
// source: filepath.Join(repoBasePath, "small"),
// expected: "this line is added\nand another one",
// additions: "this line is added\nand another one",
// target: filepath.Join(repoBasePath, "small", "main.go"),
// },
// }
// err := moveDotGit("dotGit", ".git")
// if err != nil {
// t.Fatal(err)
// }
// defer func() {
// if err = moveDotGit(".git", "dotGit"); err != nil {
// t.Fatal(err)
// }
// }()
// for _, tt := range tests {
// noChanges, err := os.ReadFile(tt.target)
// if err != nil {
// t.Error(err)
// }
// err = os.WriteFile(tt.target, []byte(tt.additions), 0644)
// if err != nil {
// restore(tt.target, noChanges, t)
// t.Error(err)
// }
// files, err := git.GitDiff(tt.source, false)
// if err != nil {
// restore(tt.target, noChanges, t)
// t.Error(err)
// }
// for f := range files {
// sb := strings.Builder{}
// for _, tf := range f.TextFragments {
// sb.WriteString(tf.Raw(gitdiff.OpAdd))
// }
// if sb.String() != tt.expected {
// restore(tt.target, noChanges, t)
// t.Error("expected: ", tt.expected, "got: ", sb.String())
// }
// }
// restore(tt.target, noChanges, t)
// }
// }
// func restore(path string, data []byte, t *testing.T) {
// err := os.WriteFile(path, data, 0644)
// if err != nil {
// t.Fatal(err)
// }
// }
// func moveDotGit(from, to string) error {
// repoDirs, err := os.ReadDir("../../testdata/repos")
// if err != nil {
// return err
// }
// for _, dir := range repoDirs {
// if to == ".git" {
// _, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), "dotGit"))
// if os.IsNotExist(err) {
// // dont want to delete the only copy of .git accidentally
// continue
// }
// os.RemoveAll(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), ".git"))
// }
// if !dir.IsDir() {
// continue
// }
// _, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from))
// if os.IsNotExist(err) {
// continue
// }
// err = os.Rename(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from),
// fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), to))
// if err != nil {
// return err
// }
// }
// return nil
// }
+67
View File
@@ -0,0 +1,67 @@
package detect
// Location represents a location in a file
type Location struct {
startLine int
endLine int
startColumn int
endColumn int
startLineIndex int
endLineIndex int
}
func location(fragment Fragment, matchIndex []int) Location {
var (
prevNewLine int
location Location
lineSet bool
_lineNum int
)
start := matchIndex[0]
end := matchIndex[1]
for lineNum, pair := range fragment.newlineIndices {
_lineNum = lineNum
newLineByteIndex := pair[0]
if prevNewLine <= start && start < newLineByteIndex {
lineSet = true
location.startLine = lineNum
location.endLine = lineNum
location.startColumn = (start - prevNewLine) + 1 // +1 because counting starts at 1
location.startLineIndex = prevNewLine
location.endLineIndex = newLineByteIndex
}
if prevNewLine < end && end <= newLineByteIndex {
location.endLine = lineNum
location.endColumn = (end - prevNewLine)
location.endLineIndex = newLineByteIndex
}
prevNewLine = pair[0]
}
if !lineSet {
// if lines never get set then that means the secret is most likely
// on the last line of the diff output and the diff output does not have
// a newline
location.startColumn = (start - prevNewLine) + 1 // +1 because counting starts at 1
location.endColumn = (end - prevNewLine)
location.startLine = _lineNum + 1
location.endLine = _lineNum + 1
location.startLineIndex = start
// search for new line byte index
i := 0
for end+i < len(fragment.Raw) {
if fragment.Raw[end+i] == '\n' {
break
}
if fragment.Raw[end+i] == '\r' {
break
}
i++
}
location.endLineIndex = end + i
}
return location
}
+60
View File
@@ -0,0 +1,60 @@
package detect
import (
"testing"
)
// TestGetLocation tests the getLocation function.
func TestGetLocation(t *testing.T) {
tests := []struct {
linePairs [][]int
start int
end int
wantLocation Location
}{
{
linePairs: [][]int{
{0, 39},
{40, 55},
{56, 57},
},
start: 35,
end: 38,
wantLocation: Location{
startLine: 1,
startColumn: 36,
endLine: 1,
endColumn: 38,
startLineIndex: 0,
endLineIndex: 40,
},
},
{
linePairs: [][]int{
{0, 39},
{40, 55},
{56, 57},
},
start: 40,
end: 44,
wantLocation: Location{
startLine: 2,
startColumn: 1,
endLine: 2,
endColumn: 4,
startLineIndex: 40,
endLineIndex: 56,
},
},
}
for _, test := range tests {
loc := location(Fragment{newlineIndices: test.linePairs}, []int{test.start, test.end})
if loc != test.wantLocation {
t.Errorf("\nstartLine %d\nstartColumn: %d\nendLine: %d\nendColumn: %d\nstartLineIndex: %d\nendlineIndex %d",
loc.startLine, loc.startColumn, loc.endLine, loc.endColumn, loc.startLineIndex, loc.endLineIndex)
t.Error("got", loc, "want", test.wantLocation)
}
}
}
+107
View File
@@ -0,0 +1,107 @@
package detect
import (
"encoding/json"
"fmt"
"math"
"strings"
"time"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/gitleaks/go-gitdiff/gitdiff"
"github.com/rs/zerolog/log"
)
// augmentGitFinding updates the start and end line numbers of a finding to include the
// delta from the git diff
func augmentGitFinding(finding report.Finding, textFragment *gitdiff.TextFragment, f *gitdiff.File) report.Finding {
if !strings.HasPrefix(finding.Match, "file detected") {
finding.StartLine += int(textFragment.NewPosition)
finding.EndLine += int(textFragment.NewPosition)
}
if f.PatchHeader != nil {
finding.Commit = f.PatchHeader.SHA
finding.Message = f.PatchHeader.Message()
if f.PatchHeader.Author != nil {
finding.Author = f.PatchHeader.Author.Name
finding.Email = f.PatchHeader.Author.Email
}
finding.Date = f.PatchHeader.AuthorDate.UTC().Format(time.RFC3339)
}
return finding
}
// shannonEntropy calculates the entropy of data using the formula defined here:
// https://en.wiktionary.org/wiki/Shannon_entropy
// Another way to think about what this is doing is calculating the number of bits
// needed to on average encode the data. So, the higher the entropy, the more random the data, the
// more bits needed to encode that data.
func shannonEntropy(data string) (entropy float64) {
if data == "" {
return 0
}
charCounts := make(map[rune]int)
for _, char := range data {
charCounts[char]++
}
invLength := 1.0 / float64(len(data))
for _, count := range charCounts {
freq := float64(count) * invLength
entropy -= freq * math.Log2(freq)
}
return entropy
}
// filter will dedupe and redact findings
func filter(findings []report.Finding, redact bool) []report.Finding {
var retFindings []report.Finding
for _, f := range findings {
include := true
if strings.Contains(strings.ToLower(f.RuleID), "generic") {
for _, fPrime := range findings {
if f.StartLine == fPrime.StartLine &&
f.Commit == fPrime.Commit &&
f.RuleID != fPrime.RuleID &&
strings.Contains(fPrime.Secret, f.Secret) &&
!strings.Contains(strings.ToLower(fPrime.RuleID), "generic") {
genericMatch := strings.Replace(f.Match, f.Secret, "REDACTED", -1)
betterMatch := strings.Replace(fPrime.Match, fPrime.Secret, "REDACTED", -1)
log.Debug().Msgf("skipping %s finding (%s), %s rule takes precendence (%s)", f.RuleID, genericMatch, fPrime.RuleID, betterMatch)
include = false
break
}
}
}
if redact {
f.Redact()
}
if include {
retFindings = append(retFindings, f)
}
}
return retFindings
}
func printFinding(f report.Finding) {
var b []byte
b, _ = json.MarshalIndent(f, "", " ")
fmt.Println(string(b))
}
func containsDigit(s string) bool {
for _, c := range s {
switch c {
case '1', '2', '3', '4', '5', '6', '7', '8', '9':
return true
}
}
return false
}
-30
View File
@@ -1,30 +0,0 @@
title = "gitleaks config"
[[regexes]]
description = "AWS"
regex = '''AKIA[0-9A-Z]{16}'''
[[regexes]]
description = "RKCS8"
regex = '''-----BEGIN PRIVATE KEY-----'''
[[regexes]]
description = "RSA"
regex = '''-----BEGIN RSA PRIVATE KEY-----'''
[[regexes]]
description = "Github"
regex = '''(?i)github.*['\"][0-9a-zA-Z]{35,40}['\"]'''
[[regexes]]
description = "SSH"
regex = '''-----BEGIN OPENSSH PRIVATE KEY-----'''
[[regexes]]
description = "Facebook"
regex = '''(?i)facebook.*['\"][0-9a-f]{32}['\"]'''
[[regexes]]
description = "Facebook"
regex = '''(?i)twitter.*['\"][0-9a-zA-Z]{35,44}['\"]'''
[whitelist]
regexes = [
"AKIA.*",
]
files = [
"(.*?)(jpg|gif|doc|pdf|bin|go)$"
]
-650
View File
@@ -1,650 +0,0 @@
package main
import (
"fmt"
"io/ioutil"
"os"
"path"
"regexp"
"strings"
"testing"
"github.com/franela/goblin"
git "gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/storage/memory"
)
const testWhitelistCommit = `
[[regexes]]
description = "AWS"
regex = '''AKIA[0-9A-Z]{16}'''
[whitelist]
commits = [
"eaeffdc65b4c73ccb67e75d96bd8743be2c85973",
]
`
const testWhitelistFile = `
[[regexes]]
description = "AWS"
regex = '''AKIA[0-9A-Z]{16}'''
[whitelist]
files = [
".go",
]
`
const testWhitelistBranch = `
[[regexes]]
description = "AWS"
regex = '''AKIA[0-9A-Z]{16}'''
[whitelist]
branches = [
"origin/master",
]
`
const testWhitelistRegex = `
[[regexes]]
description = "AWS"
regex = '''AKIA[0-9A-Z]{16}'''
[whitelist]
regexes= [
"AKIA",
]
`
func TestGetRepo(t *testing.T) {
var err error
dir, err = ioutil.TempDir("", "gitleaksTestRepo")
defer os.RemoveAll(dir)
if err != nil {
panic(err)
}
_, err = git.PlainClone(dir, false, &git.CloneOptions{
URL: "https://github.com/gitleakstest/gronit",
})
if err != nil {
panic(err)
}
var tests = []struct {
testOpts Options
description string
expectedErrMsg string
}{
{
testOpts: Options{
Repo: "https://github.com/gitleakstest/gronit",
},
description: "test plain clone remote repo",
expectedErrMsg: "",
},
{
testOpts: Options{
Repo: "https://github.com/gitleakstest/gronit",
Disk: true,
},
description: "test on disk clone remote repo",
expectedErrMsg: "",
},
{
testOpts: Options{
RepoPath: dir,
},
description: "test local clone repo",
expectedErrMsg: "",
},
{
testOpts: Options{
Repo: "https://github.com/gitleakstest/nope",
},
description: "test no repo",
expectedErrMsg: "authentication required",
},
{
testOpts: Options{
Repo: "https://github.com/gitleakstest/private",
IncludePrivate: true,
},
description: "test private repo",
expectedErrMsg: "invalid auth method",
},
{
testOpts: Options{
Repo: "https://github.com/gitleakstest/private",
IncludePrivate: true,
Disk: true,
},
description: "test private repo",
expectedErrMsg: "invalid auth method",
},
}
g := goblin.Goblin(t)
for _, test := range tests {
g.Describe("TestGetRepo", func() {
g.It(test.description, func() {
opts = test.testOpts
_, err := getRepo()
if err != nil {
g.Assert(err.Error()).Equal(test.expectedErrMsg)
}
})
})
}
}
func TestGetOwnerRepo(t *testing.T) {
var err error
dir, err = ioutil.TempDir("", "gitleaksTestOwner")
defer os.RemoveAll(dir)
if err != nil {
panic(err)
}
git.PlainClone(dir+"/gronit", false, &git.CloneOptions{
URL: "https://github.com/gitleakstest/gronit",
})
git.PlainClone(dir+"/h1domains", false, &git.CloneOptions{
URL: "https://github.com/gitleakstest/h1domains",
})
var tests = []struct {
testOpts Options
description string
expectedErrMsg string
numRepos int
}{
{
testOpts: Options{
GithubUser: "gitleakstest",
},
description: "test github user",
numRepos: 2,
expectedErrMsg: "",
},
{
testOpts: Options{
GithubUser: "gitleakstest",
Disk: true,
},
description: "test github user on disk ",
numRepos: 2,
expectedErrMsg: "",
},
{
testOpts: Options{
GithubOrg: "gitleakstestorg",
},
description: "test github org",
numRepos: 2,
expectedErrMsg: "",
},
{
testOpts: Options{
OwnerPath: dir,
},
description: "test plain clone remote repo",
numRepos: 2,
expectedErrMsg: "",
},
{
testOpts: Options{
GithubOrg: "gitleakstestorg",
IncludePrivate: true,
},
description: "test private org no ssh",
numRepos: 0,
expectedErrMsg: "no ssh auth available",
},
{
testOpts: Options{
GithubOrg: "gitleakstestorg",
Disk: true,
},
description: "test org on disk",
numRepos: 2,
expectedErrMsg: "",
},
{
testOpts: Options{
GithubOrg: "gitleakstestorg",
IncludePrivate: true,
Disk: true,
},
description: "test private org on disk no ssh",
numRepos: 0,
expectedErrMsg: "no ssh auth available",
},
}
g := goblin.Goblin(t)
for _, test := range tests {
g.Describe("TestGetOwnerRepo", func() {
g.It(test.description, func() {
opts = test.testOpts
repos, err := getOwnerRepos()
if err != nil {
g.Assert(err.Error()).Equal(test.expectedErrMsg)
}
g.Assert(len(repos)).Equal(test.numRepos)
})
})
}
}
func TestWriteReport(t *testing.T) {
tmpDir, _ := ioutil.TempDir("", "reportDir")
reportFile := path.Join(tmpDir, "report.json")
defer os.RemoveAll(tmpDir)
leaks := []Leak{
{
Line: "eat",
Commit: "your",
Offender: "veggies",
Type: "and",
Message: "get",
Author: "some",
File: "sleep",
Branch: "thxu",
},
}
var tests = []struct {
leaks []Leak
reportFile string
fileName string
description string
testOpts Options
}{
{
leaks: leaks,
reportFile: reportFile,
fileName: "report.json",
description: "can we write a file",
testOpts: Options{
Report: reportFile,
},
},
}
g := goblin.Goblin(t)
for _, test := range tests {
g.Describe("TestWriteReport", func() {
g.It(test.description, func() {
opts = test.testOpts
writeReport(test.leaks)
f, _ := os.Stat(test.reportFile)
g.Assert(f.Name()).Equal(test.fileName)
})
})
}
}
func testTomlLoader() string {
tmpDir, _ := ioutil.TempDir("", "whiteListConfigs")
ioutil.WriteFile(path.Join(tmpDir, "regex"), []byte(testWhitelistRegex), 0644)
ioutil.WriteFile(path.Join(tmpDir, "branch"), []byte(testWhitelistBranch), 0644)
ioutil.WriteFile(path.Join(tmpDir, "commit"), []byte(testWhitelistCommit), 0644)
ioutil.WriteFile(path.Join(tmpDir, "file"), []byte(testWhitelistFile), 0644)
return tmpDir
}
func TestAuditRepo(t *testing.T) {
var leaks []Leak
err := loadToml()
configsDir := testTomlLoader()
defer os.RemoveAll(configsDir)
if err != nil {
panic(err)
}
leaksRepo, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: "https://github.com/gitleakstest/gronit.git",
})
if err != nil {
panic(err)
}
cleanRepo, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: "https://github.com/gitleakstest/h1domains.git",
})
if err != nil {
panic(err)
}
var tests = []struct {
testOpts Options
description string
expectedErrMsg string
numLeaks int
repo *git.Repository
whiteListFiles []*regexp.Regexp
whiteListCommits map[string]bool
whiteListBranches []string
whiteListRegexes []*regexp.Regexp
configPath string
}{
{
repo: leaksRepo,
description: "two leaks present",
numLeaks: 2,
},
{
repo: leaksRepo,
description: "two leaks present limit goroutines",
numLeaks: 2,
testOpts: Options{
MaxGoRoutines: 2,
},
},
{
repo: leaksRepo,
description: "audit all branch",
numLeaks: 6,
testOpts: Options{
AuditAllRefs: true,
},
},
{
repo: leaksRepo,
description: "audit all branch whitelist 1",
numLeaks: 4,
testOpts: Options{
AuditAllRefs: true,
},
whiteListBranches: []string{
"origin/master",
},
},
{
repo: leaksRepo,
description: "two leaks present whitelist AWS.. no leaks",
whiteListRegexes: []*regexp.Regexp{
regexp.MustCompile("AKIA"),
},
numLeaks: 0,
},
{
repo: leaksRepo,
description: "two leaks present limit goroutines",
numLeaks: 2,
},
{
repo: cleanRepo,
description: "no leaks present",
numLeaks: 0,
},
{
repo: leaksRepo,
description: "two leaks present whitelist go files",
whiteListFiles: []*regexp.Regexp{
regexp.MustCompile(".go"),
},
numLeaks: 0,
},
{
repo: leaksRepo,
description: "two leaks present whitelist bad commit",
whiteListCommits: map[string]bool{
"eaeffdc65b4c73ccb67e75d96bd8743be2c85973": true,
},
numLeaks: 1,
},
{
repo: leaksRepo,
description: "redact",
testOpts: Options{
Redact: true,
},
numLeaks: 2,
},
{
repo: leaksRepo,
description: "toml whitelist regex",
configPath: path.Join(configsDir, "regex"),
numLeaks: 0,
},
{
repo: leaksRepo,
description: "toml whitelist branch",
configPath: path.Join(configsDir, "branch"),
testOpts: Options{
AuditAllRefs: true,
},
numLeaks: 4,
},
{
repo: leaksRepo,
description: "toml whitelist file",
configPath: path.Join(configsDir, "file"),
numLeaks: 0,
},
{
repo: leaksRepo,
description: "toml whitelist commit",
configPath: path.Join(configsDir, "commit"),
numLeaks: 1,
},
}
whiteListCommits = make(map[string]bool)
g := goblin.Goblin(t)
for _, test := range tests {
g.Describe("TestAuditRepo", func() {
g.It(test.description, func() {
opts = test.testOpts
// settin da globs
if test.whiteListFiles != nil {
whiteListFiles = test.whiteListFiles
} else {
whiteListFiles = nil
}
if test.whiteListCommits != nil {
whiteListCommits = test.whiteListCommits
} else {
whiteListCommits = nil
}
if test.whiteListBranches != nil {
whiteListBranches = test.whiteListBranches
} else {
whiteListBranches = nil
}
if test.whiteListRegexes != nil {
whiteListRegexes = test.whiteListRegexes
} else {
whiteListRegexes = nil
}
// config paths
if test.configPath != "" {
os.Setenv("GITLEAKS_CONFIG", test.configPath)
loadToml()
}
leaks, err = auditRepo(test.repo)
if opts.Redact {
g.Assert(leaks[0].Offender).Equal("REDACTED")
}
g.Assert(len(leaks)).Equal(test.numLeaks)
})
})
}
}
func TestOptionGuard(t *testing.T) {
var tests = []struct {
testOpts Options
githubToken bool
description string
expectedErrMsg string
expectedErrMsgFuzzy string
}{
{
testOpts: Options{},
description: "default no opts",
expectedErrMsg: "",
},
{
testOpts: Options{
IncludePrivate: true,
GithubOrg: "fakeOrg",
},
description: "private org no githubtoken",
expectedErrMsg: "user/organization private repos require env var GITHUB_TOKEN to be set",
githubToken: false,
},
{
testOpts: Options{
IncludePrivate: true,
GithubUser: "fakeUser",
},
description: "private user no githubtoken",
expectedErrMsg: "user/organization private repos require env var GITHUB_TOKEN to be set",
githubToken: false,
},
{
testOpts: Options{
IncludePrivate: true,
GithubUser: "fakeUser",
GithubOrg: "fakeOrg",
},
description: "double owner",
expectedErrMsg: "github user and organization set",
},
{
testOpts: Options{
IncludePrivate: true,
GithubOrg: "fakeOrg",
OwnerPath: "/dev/null",
},
description: "local and remote target",
expectedErrMsg: "github organization set and local owner path",
},
{
testOpts: Options{
IncludePrivate: true,
GithubUser: "fakeUser",
OwnerPath: "/dev/null",
},
description: "local and remote target",
expectedErrMsg: "github user set and local owner path",
},
{
testOpts: Options{
GithubUser: "fakeUser",
SingleSearch: "*/./....",
},
description: "single search invalid regex gaurd",
expectedErrMsgFuzzy: "unable to compile regex: */./...., ",
},
{
testOpts: Options{
GithubUser: "fakeUser",
SingleSearch: "mystring",
},
description: "single search regex gaurd",
expectedErrMsg: "",
},
}
g := goblin.Goblin(t)
for _, test := range tests {
g.Describe("Test Option Gaurd", func() {
g.It(test.description, func() {
os.Clearenv()
opts = test.testOpts
if test.githubToken {
os.Setenv("GITHUB_TOKEN", "fakeToken")
}
err := optsGuard()
if err != nil {
if test.expectedErrMsgFuzzy != "" {
g.Assert(strings.Contains(err.Error(), test.expectedErrMsgFuzzy)).Equal(true)
} else {
g.Assert(err.Error()).Equal(test.expectedErrMsg)
}
} else {
g.Assert("").Equal(test.expectedErrMsg)
}
})
})
}
}
func TestLoadToml(t *testing.T) {
tmpDir, _ := ioutil.TempDir("", "gitleaksTestConfigDir")
defer os.RemoveAll(tmpDir)
err := ioutil.WriteFile(path.Join(tmpDir, "gitleaksConfig"), []byte(defaultConfig), 0644)
if err != nil {
panic(err)
}
configPath := path.Join(tmpDir, "gitleaksConfig")
noConfigPath := path.Join(tmpDir, "gitleaksConfigNope")
var tests = []struct {
testOpts Options
description string
configPath string
expectedErrMsg string
singleSearch bool
}{
{
testOpts: Options{
ConfigPath: configPath,
},
description: "path to config",
},
{
testOpts: Options{},
description: "env var path to no config",
singleSearch: true,
},
{
testOpts: Options{
ConfigPath: noConfigPath,
},
description: "no path to config",
expectedErrMsg: fmt.Sprintf("no gitleaks config at %s", noConfigPath),
},
{
testOpts: Options{},
description: "env var path to config",
configPath: configPath,
expectedErrMsg: "",
},
{
testOpts: Options{},
description: "env var path to no config",
configPath: noConfigPath,
expectedErrMsg: fmt.Sprintf("problem loading config: open %s: no such file or directory", noConfigPath),
},
}
g := goblin.Goblin(t)
for _, test := range tests {
g.Describe("TestLoadToml", func() {
g.It(test.description, func() {
opts = test.testOpts
if test.singleSearch {
singleSearchRegex = regexp.MustCompile("test")
} else {
singleSearchRegex = nil
}
if test.configPath != "" {
os.Setenv("GITLEAKS_CONFIG", test.configPath)
} else {
os.Clearenv()
}
err := loadToml()
if err != nil {
g.Assert(err.Error()).Equal(test.expectedErrMsg)
} else {
g.Assert("").Equal(test.expectedErrMsg)
}
})
})
}
}
Loaded 100 of 1047 files, more files were not shown because too many files have changed in this diff. Show more