Compare commits

...
84 Commits
Author SHA1 Message Date
Bryan Beverly 5f6ec56cfa Merge pull request #2283 from gitleaks/dependabot/github_actions/actions-b1afc76d04
build(deps): bump the actions group across 1 directory with 4 updates
2026-10-23 15:44:59 -05:00
dependabot[bot] 4695bdb828 build(deps): bump the actions group across 1 directory with 4 updates
Bumps the actions group with 4 updates in the / directory: [docker/setup-qemu-action](https://github.com/docker/setup-qemu-action), [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action), [docker/login-action](https://github.com/docker/login-action) and [docker/build-push-action](https://github.com/docker/build-push-action).


Updates `docker/setup-qemu-action` from 4.2.0 to 4.4.0
- [Release notes](https://github.com/docker/setup-qemu-action/releases)
- [Commits](https://github.com/docker/setup-qemu-action/compare/96fe6ef7f33517b61c61be40b68a1882f3264fb8...99012661954931238ded8c8b007157a8430204e1)

Updates `docker/setup-buildx-action` from 4.2.0 to 4.4.1
- [Release notes](https://github.com/docker/setup-buildx-action/releases)
- [Commits](https://github.com/docker/setup-buildx-action/compare/bb05f3f5519dd87d3ba754cc423b652a5edd6d2c...f87e5991a6d7451dcb8d9637bfbc97413f497069)

Updates `docker/login-action` from 4.4.0 to 4.6.0
- [Release notes](https://github.com/docker/login-action/releases)
- [Commits](https://github.com/docker/login-action/compare/af1e73f918a031802d376d3c8bbc3fe56130a9b0...dbcb813823bdd20940b903addbd779551569679f)

Updates `docker/build-push-action` from 7.3.0 to 7.4.0
- [Release notes](https://github.com/docker/build-push-action/releases)
- [Commits](https://github.com/docker/build-push-action/compare/53b7df96c91f9c12dcc8a07bcb9ccacbed38856a...c3c9e263c25d99ce0380d002d59b67737d91b0dc)

---
updated-dependencies:
- dependency-name: docker/setup-qemu-action
  dependency-version: 4.4.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
- dependency-name: docker/setup-buildx-action
  dependency-version: 4.4.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
- dependency-name: docker/login-action
  dependency-version: 4.6.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
- dependency-name: docker/build-push-action
  dependency-version: 7.4.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-23 04:13:59 +00:00
Bryan Beverly b58d3f102c Merge pull request #2197 from gitleaks/dependabot/github_actions/actions-26c4f860fb
build(deps): bump the actions group with 2 updates
2026-07-22 09:50:33 -07:00
dependabot[bot] e18d0da14b build(deps): bump the actions group with 2 updates
Bumps the actions group with 2 updates: [actions/checkout](https://github.com/actions/checkout) and [actions/setup-go](https://github.com/actions/setup-go).


Updates `actions/checkout` from 7.0.0 to 7.0.1
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0...3d3c42e5aac5ba805825da76410c181273ba90b1)

Updates `actions/setup-go` from 6.5.0 to 7.0.0
- [Release notes](https://github.com/actions/setup-go/releases)
- [Commits](https://github.com/actions/setup-go/compare/924ae3a1cded613372ab5595356fb5720e22ba16...b7ad1dad31e06c5925ef5d2fc7ad053ef454303e)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: 7.0.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: actions
- dependency-name: actions/setup-go
  dependency-version: 7.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-22 04:15:03 +00:00
Bryan Beverly c33331503a Merge pull request #2189 from gitleaks/dependabot/github_actions/actions-c4a6c7cd8e
build(deps): bump the actions group with 5 updates
2026-07-20 09:05:23 -07:00
dependabot[bot] d68f282a94 build(deps): bump the actions group with 5 updates
Bumps the actions group with 5 updates:

| Package | From | To |
| --- | --- | --- |
| [docker/setup-qemu-action](https://github.com/docker/setup-qemu-action) | `4.1.0` | `4.2.0` |
| [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) | `4.1.0` | `4.2.0` |
| [docker/login-action](https://github.com/docker/login-action) | `4.2.0` | `4.4.0` |
| [docker/metadata-action](https://github.com/docker/metadata-action) | `6.1.0` | `6.2.0` |
| [docker/build-push-action](https://github.com/docker/build-push-action) | `7.2.0` | `7.3.0` |


Updates `docker/setup-qemu-action` from 4.1.0 to 4.2.0
- [Release notes](https://github.com/docker/setup-qemu-action/releases)
- [Commits](https://github.com/docker/setup-qemu-action/compare/06116385d9baf250c9f4dcb4858b16962ea869c3...96fe6ef7f33517b61c61be40b68a1882f3264fb8)

Updates `docker/setup-buildx-action` from 4.1.0 to 4.2.0
- [Release notes](https://github.com/docker/setup-buildx-action/releases)
- [Commits](https://github.com/docker/setup-buildx-action/compare/d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5...bb05f3f5519dd87d3ba754cc423b652a5edd6d2c)

Updates `docker/login-action` from 4.2.0 to 4.4.0
- [Release notes](https://github.com/docker/login-action/releases)
- [Commits](https://github.com/docker/login-action/compare/650006c6eb7dba73a995cc03b0b2d7f5ca915bee...af1e73f918a031802d376d3c8bbc3fe56130a9b0)

Updates `docker/metadata-action` from 6.1.0 to 6.2.0
- [Release notes](https://github.com/docker/metadata-action/releases)
- [Commits](https://github.com/docker/metadata-action/compare/80c7e94dd9b9319bd5eb7a0e0fe9291e23a2a2e9...dc802804100637a589fabce1cb79ff13a1411302)

Updates `docker/build-push-action` from 7.2.0 to 7.3.0
- [Release notes](https://github.com/docker/build-push-action/releases)
- [Commits](https://github.com/docker/build-push-action/compare/f9f3042f7e2789586610d6e8b85c8f03e5195baf...53b7df96c91f9c12dcc8a07bcb9ccacbed38856a)

---
updated-dependencies:
- dependency-name: docker/setup-qemu-action
  dependency-version: 4.2.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
- dependency-name: docker/setup-buildx-action
  dependency-version: 4.2.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
- dependency-name: docker/login-action
  dependency-version: 4.4.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
- dependency-name: docker/metadata-action
  dependency-version: 6.2.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
- dependency-name: docker/build-push-action
  dependency-version: 7.3.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-08 04:13:09 +00:00
Bryan Beverly 4c232b5014 Merge pull request #2179 from gitleaks/dependabot/github_actions/actions-9e904a7c11
build(deps): bump the actions group with 2 updates
2026-07-01 16:33:03 -07:00
dependabot[bot] 652f743b43 build(deps): bump the actions group with 2 updates
Bumps the actions group with 2 updates: [actions/checkout](https://github.com/actions/checkout) and [actions/setup-go](https://github.com/actions/setup-go).


Updates `actions/checkout` from 6.0.3 to 7.0.0
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/df4cb1c069e1874edd31b4311f1884172cec0e10...9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0)

Updates `actions/setup-go` from 6.4.0 to 6.5.0
- [Release notes](https://github.com/actions/setup-go/releases)
- [Commits](https://github.com/actions/setup-go/compare/4a3601121dd01d1626a1e23e37211e3254c1c06c...924ae3a1cded613372ab5595356fb5720e22ba16)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: 7.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: actions/setup-go
  dependency-version: 6.5.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-24 04:11:57 +00:00
Bryan Beverly 8ad8470035 Merge pull request #2157 from gitleaks/dependabot/github_actions/actions-6a98abd9ac
build(deps): bump actions/checkout from 6.0.2 to 6.0.3 in the actions group
2026-06-13 10:33:47 -07:00
dependabot[bot] ad138e213f build(deps): bump actions/checkout in the actions group
Bumps the actions group with 1 update: [actions/checkout](https://github.com/actions/checkout).


Updates `actions/checkout` from 6.0.2 to 6.0.3
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/de0fac2e4500dabe0009e67214ff5f5447ce83dd...df4cb1c069e1874edd31b4311f1884172cec0e10)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: 6.0.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-04 01:09:53 +00:00
Bryan Beverly 81fc7f93b7 Merge pull request #2142 from gitleaks/dependabot/github_actions/actions-738cee76bf
build(deps): bump the actions group across 1 directory with 5 updates
2026-06-01 13:05:36 -07:00
Bryan Beverly c63f9c6f61 Merge pull request #2146 from gitleaks/dependabot/go_modules/github.com/mholt/archives-0.1.5
build(deps): bump github.com/mholt/archives from 0.1.2 to 0.1.5
2026-06-01 13:02:10 -07:00
dependabot[bot] dfcab34362 build(deps): bump the actions group across 1 directory with 5 updates
Bumps the actions group with 5 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [docker/setup-qemu-action](https://github.com/docker/setup-qemu-action) | `3.7.0` | `4.1.0` |
| [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) | `3.12.0` | `4.1.0` |
| [docker/login-action](https://github.com/docker/login-action) | `3.7.0` | `4.2.0` |
| [docker/metadata-action](https://github.com/docker/metadata-action) | `5.10.0` | `6.1.0` |
| [docker/build-push-action](https://github.com/docker/build-push-action) | `6.19.2` | `7.2.0` |



Updates `docker/setup-qemu-action` from 3.7.0 to 4.1.0
- [Release notes](https://github.com/docker/setup-qemu-action/releases)
- [Commits](https://github.com/docker/setup-qemu-action/compare/c7c53464625b32c7a7e944ae62b3e17d2b600130...06116385d9baf250c9f4dcb4858b16962ea869c3)

Updates `docker/setup-buildx-action` from 3.12.0 to 4.1.0
- [Release notes](https://github.com/docker/setup-buildx-action/releases)
- [Commits](https://github.com/docker/setup-buildx-action/compare/8d2750c68a42422c14e847fe6c8ac0403b4cbd6f...d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5)

Updates `docker/login-action` from 3.7.0 to 4.2.0
- [Release notes](https://github.com/docker/login-action/releases)
- [Commits](https://github.com/docker/login-action/compare/c94ce9fb468520275223c153574b00df6fe4bcc9...650006c6eb7dba73a995cc03b0b2d7f5ca915bee)

Updates `docker/metadata-action` from 5.10.0 to 6.1.0
- [Release notes](https://github.com/docker/metadata-action/releases)
- [Commits](https://github.com/docker/metadata-action/compare/c299e40c65443455700f0fdfc63efafe5b349051...80c7e94dd9b9319bd5eb7a0e0fe9291e23a2a2e9)

Updates `docker/build-push-action` from 6.19.2 to 7.2.0
- [Release notes](https://github.com/docker/build-push-action/releases)
- [Commits](https://github.com/docker/build-push-action/compare/10e90e3645eae34f1e60eeb005ba3a3d33f178e8...f9f3042f7e2789586610d6e8b85c8f03e5195baf)

---
updated-dependencies:
- dependency-name: docker/build-push-action
  dependency-version: 7.2.0
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: docker/login-action
  dependency-version: 4.2.0
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: docker/metadata-action
  dependency-version: 6.1.0
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: docker/setup-buildx-action
  dependency-version: 4.1.0
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: docker/setup-qemu-action
  dependency-version: 4.1.0
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-01 19:30:12 +00:00
dependabot[bot] d8fafb2396 build(deps): bump github.com/mholt/archives from 0.1.2 to 0.1.5
Bumps [github.com/mholt/archives](https://github.com/mholt/archives) from 0.1.2 to 0.1.5.
- [Release notes](https://github.com/mholt/archives/releases)
- [Commits](https://github.com/mholt/archives/compare/v0.1.2...v0.1.5)

---
updated-dependencies:
- dependency-name: github.com/mholt/archives
  dependency-version: 0.1.5
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-01 19:30:09 +00:00
Bryan Beverly 5454f7bdec Merge pull request #2138 from gitleaks/chore/supply-chain-hardening 2026-05-31 18:30:34 -07:00
Bryan Beverly 7900fbae49 Merge pull request #2137 from gitleaks/chore/node24-bumps 2026-05-31 18:28:39 -07:00
Bryan BeverlyandCursor 2719f0e001 trigger CI
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-30 15:59:09 -07:00
Bryan BeverlyandCursor 9ea08626dc trigger CI after enabling Actions
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-30 15:53:58 -07:00
Bryan BeverlyandCursor 22e600ebe3 trigger CI
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-30 15:45:47 -07:00
Bryan BeverlyandCursor 1207d58159 chore: supply-chain hardening
- Add CODEOWNERS with default owner and release-critical path protection
- Add SECURITY.md with vulnerability disclosure policy
- Add .github/dependabot.yml for Go modules + GitHub Actions updates

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-30 15:35:44 -07:00
Bryan BeverlyandCursor db3bc42b83 chore: bump GitHub Actions to Node 24
- gitleaks.yml: gitleaks-action v2 -> v3 (Node 24)
- test.yml: setup-go v5 -> v6
- release.yml: Docker actions to latest (setup-qemu v3,
  setup-buildx v3, login v3, metadata v5, build-push v6)
- Add version comments to all SHA-pinned references

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-30 15:34:47 -07:00
Zachary Rice 80093b8a7b Update Readme 2026-05-21 07:29:43 -05:00
Zachary Rice 9febafb621 broken link
Removed Gitleaks Playground badge and link from README.
2026-05-13 08:53:48 -05:00
Zachary Rice b5cb8ad01b Update README.md
Removed GitHub Action section from README.md.
2026-05-13 08:53:02 -05:00
Zachary Rice 8863af47d6 bruh (#2067) 2026-03-25 08:57:43 -05:00
Zachary Rice 67fcd836b3 Update README.md 2026-03-20 21:23:42 -05:00
Fatih Çelik 8d1f98c796 Removed unnecessary functions from report template (#2040) 2026-02-21 07:30:12 -06:00
Zachary Rice ca20267a84 its the simple things (#2020) 2026-01-08 14:48:47 -06:00
Richard Gomez b66ac75e4f build: switch to Go 1.24 (#2002) 2025-12-09 09:15:58 -06:00
Zachary Rice 6eaad03960 0 to 5 - notes on recursive decoding (#1994) 2025-11-26 10:25:37 -06:00
Chris 09242ce9c8 Add new Looker client ID and client secret rules (#1947) 2025-11-20 09:12:31 -06:00
Samuel Gaist c98e5e0d27 feat: add Airtable Personnal Access Token detection (#1952) 2025-11-20 08:29:19 -06:00
4ed0ca4902 build: upgrade Go & alpine version (#1989)
Co-authored-by: Michel Tu <michel.tu@databricks.com>
Co-authored-by: Jiri Stary <72435227+Jiri-Stary@users.noreply.github.com>
2025-11-20 07:29:50 -06:00
Zach fb5d707e08 thats a paddlin 2025-11-19 15:11:04 -06:00
Richard Gomez 50493dbe1f feat: document stdout report path (#1990) 2025-11-17 10:57:25 -06:00
bplaxco ed65b65095 Add trace log for skipped archive file when not enabled (#1961)
rh-pre-commit.version: 2.3.2
rh-pre-commit.check-secrets: ENABLED
2025-10-24 12:30:33 -05:00
bplaxco c5ccbb9468 Respect contexts with timeouts (#1948)
rh-pre-commit.version: 2.3.2
rh-pre-commit.check-secrets: ENABLED
2025-10-24 12:30:13 -05:00
Zachary Rice 3821f30b06 Config min version (#1955)
* init

* minVersion set

* sigh

* addressed some comments, fixed double validate bug
2025-10-16 13:53:00 -05:00
Richard Gomez d22371873b fix(config): validate rules when [extend] is used (#1592) 2025-10-16 10:54:59 -05:00
Darran BoydandDarran Boyd 87d96295d6 feat: add Amazon Bedrock API key detection (#1935)
Co-authored-by: Darran Boyd <drboyd@example.com>
2025-09-25 07:35:30 -05:00
Zachary Rice 228396b37b Add GitHub Sponsors section and Discord link
Updated README to add GitHub Sponsors section and reintroduced Discord link.
2025-09-16 19:00:16 -05:00
Bruno Guimarães a82bc53d89 feat: improve regex to detect Sonar tokens with prefixes (#1931)
Since Sonar 9.5, a prefix was added to the tokens.

See: https://www.sonarsource.com/products/sonarqube/whats-new/sonarqube-9-5/
2025-08-14 12:49:28 -05:00
Zachary Rice 4fb43823ef cant count 2025-07-20 11:14:25 -05:00
Zachary Rice b1c9c7ecbe Composite rules (#1905)
* composite rules

* add test config

* tests

* taking care of some pr comments

* naming
2025-07-20 11:13:38 -05:00
Hasnain Lakhani 72977e41b6 feat: add Anthropic API key detection (#1910)
Add detection rules for Anthropic API keys:
- anthropic-api-key: detects sk-ant-api03-... keys
- anthropic-admin-api-key: detects sk-ant-admin01-... keys

Both key types follow the pattern sk-ant-{type}-{93 chars}AA
and are detected as separate rules to align with gitleaks
patterns for multi-token providers.

The base regex patterns are aligned with what TruffleHog uses here: https://github.com/trufflesecurity/trufflehog/blob/main/pkg/detectors/anthropic/anthropic.go
2025-07-15 09:21:58 -05:00
Richard Gomez 7b02c98eb4 fix(git): handle port (#1912)
This fixes #1911
2025-07-14 19:00:48 -05:00
Zachary Rice 2a7bcffd7c dont prematurely calculate fragment newlines (#1909) 2025-07-08 20:48:55 -05:00
Richard Gomez bd79c3eaca feat(allowlist): promote optimizations (#1908) 2025-07-08 19:34:24 -05:00
Christophe Goessen 7fb4eda723 Fix: CVEs on go and go crypto (#1868)
* fix(CVE-2025-22871): update go to 1.23.8

* fix(CVE-2025-22869): update go crypto to 0.35.0
2025-07-08 09:13:33 -05:00
Christophe Goessen a044b815b3 feat: add artifactory reference token and api key detection (#1906)
* feat: add artifactory reference token and api key detection

* fix: match word boundary, add false positive tests

* fix: increase minimum entropy and fix tests
2025-07-07 20:11:05 -05:00
Zachary Rice bf380d4767 silly 2025-07-07 20:10:18 -05:00
Zachary Rice f487f85378 Update gitleaks.yml 2025-06-16 09:37:32 -05:00
Zach 958f55ac62 add just like that, no leaks 2025-06-08 19:51:04 -05:00
Zach c7acf33d96 Merge branch 'master' of github.com:gitleaks/gitleaks 2025-06-08 19:31:25 -05:00
Richard Gomez 9faaa4a09c Add experimental allowlist optimizations (#1731)
* feat(allowlist): optimization experiments

* refactor(allowlist): remove useOptimizations flag

* refactor(allowlist): simplify Validate() with helper func

* refactor(config): replace global feature flag
2025-06-08 10:33:05 -05:00
Lisa LinandRichard Gomez 79068b35e5 Detect Notion Public API Keys #1889 (#1890)
* add notion api rule

* Update cmd/generate/config/rules/notion.go

Co-authored-by: Richard Gomez <32133502+rgmz@users.noreply.github.com>

* Update cmd/generate/config/rules/notion.go

Co-authored-by: Richard Gomez <32133502+rgmz@users.noreply.github.com>

* change gitleaks toml

---------

Co-authored-by: Richard Gomez <32133502+rgmz@users.noreply.github.com>
2025-06-08 07:07:00 -05:00
Zach 80468eff1d Merge branch 'master' of github.com:gitleaks/gitleaks 2025-06-07 20:53:32 -05:00
Richard Gomez ef8223700a fix(atlassian): reduce false-positives for v1 pattern (#1892) 2025-06-07 20:33:34 -05:00
bplaxco 2463f11e71 Fix log suppresion issue (#1887)
The check for log suppresion enables archive scanning by default with no
max depth.
2025-06-05 08:26:06 -05:00
Kashif Khan 6f251eef65 Added Heroku API Key New Version (#1883)
* Added Heroku API Key New Version

* updated rule
2025-06-04 19:47:19 -05:00
Tilo Brueckner 20f9a1d4eb Add Platform Bitbucket (#1886) 2025-06-04 19:46:01 -05:00
Tilo Brueckner 722ce8213a Add Platform Gitea (#1884) 2025-06-04 09:15:06 -05:00
Zach 79780b884d Merge branch 'master' of github.com:gitleaks/gitleaks 2025-06-02 10:22:51 -05:00
Zachary Rice c5683ca6a3 prevent default warn message when max-archive-depth not set (#1881) 2025-06-01 12:10:45 -05:00
Zach 0357c3cbf6 prevent default warn message when max-archive-depth not set 2025-06-01 12:07:47 -05:00
bplaxcoandAlex Layne 782f310478 Archive support (#1872)
* Start Files Source

* Keep cmd the same for now

* Get tests to pass

* s.MaxTargetMegaBytes -> s.MaxFileSize

* Tweak some log messages & use q semgroup for files

* Just call yield inside the semgroup

* Refactor a check and revert some log lines

* Move mg && misc tuning

* Add `make profile`

(Benchmark results are only added if tools are installed)

Example output:

```
========================================================================
generating profile data
------------------------------------------------------------------------
- mode: dir
  benchmark:
    tool: hyperfine
    path: profile/1748019612/dir/benchmark.json
    results:
      mean: 1.12852930166
      stddev: 0.12163775966037399
      median: 1.07242928416
      user: 3.9699382799999996
      system: 0.04382341999999999
      min: 1.03207673016
      max: 1.3913475181600001
  profile:
    - mode: cpu
      path: profile/1748019612/dir/cpu.pprof
      view: go tool pprof -http=localhost: ./gitleaks profile/1748019612/dir/cpu.pprof
    - mode: mem
      path: profile/1748019612/dir/mem.pprof
      view: go tool pprof -http=localhost: ./gitleaks profile/1748019612/dir/mem.pprof
    - mode: trace
      path: profile/1748019612/dir/trace.out
      view: go tool trace profile/1748019612/dir/trace.out
- mode: git
  ...snip...
```

* Archive support for File based sources

* Move Git to Source interface

* Scan archives in git

* Misc linter fixes

* Exclude certain diffs: --diff-filter=tuxdb

* Add git archives tests

* Log error instead of fatal

* Fix spacing in test config

* Refine source comments/wording

* Make MB conversions more readable

* Format cmd

* Adjust DetectSource logging

* MiB -> MB in logs

* Add testdata/repos/archives/dotGit/refs/.gitkeep

Without it the refs folder gets deleted and the
and then it isn't detected as a git repo ¯\_(ツ)_/¯

So then the test starts scanning the whole gitleaks
repo instead :D

* Handle finding links for archives

* Working on archive depth

* Fixes from failfast test

* cmd max-archive-depth

* added comments, fixed warnings

* removed test print

* Update README.md

* Set archive depth for DetectFiles

* Tweak logs & pass max archive for readers

* Pass ctx to Fragments

* Add make lint target and address some issues

* Fix compat issue

* Report path in fragment errors

* Apply PR suggestions & misc changes

- Update blobReader.Close() to discard the buffer
- Misc logger issues & uses
- Tweak .golangci.yaml to default to none
- Discard remaining blobReader data on close
- Undo a De Morgan's Law suggestion (and disable QF1001)

* Add http mode for diagnostics

gitleaks --diagnostics=http ...
-----

From the net/http/pprof docs:

Use the pprof tool to look at the heap profile:
```
go tool pprof http://localhost:6060/debug/pprof/heap
```

Or to look at a 30-second CPU profile:
```
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
```

Or to look at the goroutine blocking profile, after calling runtime.SetBlockProfileRate in your program:
```
go tool pprof http://localhost:6060/debug/pprof/block
```

Or to look at the holders of contended mutexes, after calling runtime.SetMutexProfileFraction in your program:
```
go tool pprof http://localhost:6060/debug/pprof/mutex
```

(For more info see https://pkg.go.dev/net/http/pprof)

---------

Co-authored-by: Alex Layne <alayne@redhat.com>
2025-06-01 11:29:34 -05:00
Zachary Rice 489d13c14e Update README.md 2025-05-31 14:12:05 -05:00
bplaxco d29ee55171 Reduce aws-access-token false positives (#1876)
* Adjust aws-access-token regex

AWS Access Key IDs are [base32 encoded][1] so the numerical values here
will [only be 2-7][2]

[1]: https://medium.com/@TalBeerySec/a-short-note-on-aws-key-id-f88cc4317489
[2]: https://en.wikipedia.org/wiki/Base32#Base_32_Encoding_with_Extended_Hex_Alphabet_per_%C2%A77:~:text=It%20uses%20an%20alphabet%20of%20A%E2%80%93Z%2C%20followed%20by%202%E2%80%937

* Update config/gitleaks.toml during build and test

Summary:

- Add `config/gitleaks.toml` make target
- Make it a dep of `build` and `test`
- Update CONTRIBUTING.md to reference the new target

Reason: Makes dev easier because you can just tweak the code and run
`make test` without an extra step.

* Resolve lint issues in cmd/diagnostics.go

```
$ golangci-lint run cmd/
cmd/diagnostics.go:128:10: Error return value of `f.Close` is not checked (errcheck)
                f.Close()
                       ^
cmd/diagnostics.go:191:10: Error return value of `f.Close` is not checked (errcheck)
                f.Close()
                       ^
2 issues:
* errcheck: 2
```
2025-05-27 09:37:52 -05:00
Jordan Bradford 611db6579b Set pass_filenames to false for Docker hook (#1850) 2025-05-15 13:07:29 -05:00
Zachary Rice 0589ae0298 unicode decoding (#1854) 2025-05-14 10:14:31 -05:00
Zachary Rice 82f7e32b71 Diagnostics (#1856)
* init diagnostics

* update usage readme
2025-05-13 09:22:20 -05:00
Richard Gomez f97a9ee872 chore: include decoder in debug log (#1853) 2025-05-12 21:54:55 -05:00
bplaxco 78eebaca9d Percent/URL Decoding Support (#1831)
* Add initial percent decoding support

* Refactor multi encoding support

* Add detect tests to confirm positions

* Avoid a few extra passes during decoding

* Do multiple passes for finding encodings re

* Fix issue with overlapping encodings when doing separate passes
2025-05-12 11:22:36 -05:00
Richard Gomez 6f967cad68 fix(kubernetes): remove slow element from pat (#1848) 2025-05-02 20:16:30 -05:00
Richard Gomez 88f56d3695 feat: identify slow file (#1479) 2025-05-01 07:39:13 -05:00
Zach 9609928c02 rm 1password detect test since we test it in cfg gen 2025-04-30 09:57:28 -05:00
Jordan BradfordandRichard Gomez 23cb69fba4 feat(rules): Add 1Password secret key detection (#1834)
* Add `1password-secret-key` detection

* Document key details

* Update cmd/generate/config/rules/1password.go

Co-authored-by: Richard Gomez <32133502+rgmz@users.noreply.github.com>

* Generate new `.toml`

* Use `GenerateSampleSecrets` to test more scenarios

* Comment lowercase `fps`

* Decrease entropy

---------

Co-authored-by: Richard Gomez <32133502+rgmz@users.noreply.github.com>
2025-04-30 09:30:58 -05:00
Richard Gomez d1c77598da fix(detect): test all allowlists (#1845) 2025-04-30 08:29:57 -05:00
Richard Gomez 4451b455f3 feat(config): define multiple global allowlists (#1777) 2025-04-29 08:49:04 -05:00
7fb21a4e61 feat(rules): Add Perplexity AI API key detection (#1825)
* feat(rules): Add Perplexity AI API key detection

* Fix generation

* Fix imports

* Update cmd/generate/config/rules/perplexity.go

Co-authored-by: Richard Gomez <32133502+rgmz@users.noreply.github.com>

* Update cmd/generate/config/rules/perplexity.go

Co-authored-by: Richard Gomez <32133502+rgmz@users.noreply.github.com>

* Update cmd/generate/config/rules/perplexity.go

Co-authored-by: Richard Gomez <32133502+rgmz@users.noreply.github.com>

* Adjust regex, add imports

* Generate config

---------

Co-authored-by: vno <vno@serity.io>
Co-authored-by: Richard Gomez <32133502+rgmz@users.noreply.github.com>
2025-04-28 14:06:48 -05:00
Richard Gomez f6193bc92c feat(gcp): increase rule entropy (#1840) 2025-04-26 19:28:32 -05:00
San Tran 9bc725786d Adding clickhouse scanner (#1826)
* Adding clickhouse scanner

* removing mention of aws as i used it as template
2025-04-16 16:10:47 -05:00
Richard Gomez b6cc71aa3a fix(baseline): work with --redact (#1741) 2025-04-13 09:40:15 -05:00
Richard Gomez cfdeb0d7e0 feat(rule): validate & sort rule when generating (#1817) 2025-04-12 10:09:19 -05:00
175 changed files with 7799 additions and 2268 deletions

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
# Default — every PR requires at least one org member review.
* @bryanbeverly @dustin-decker @dxa4481 @zricethezav
# Release-critical paths
/.github/ @bryanbeverly @dustin-decker @dxa4481 @zricethezav
/.goreleaser.yml @bryanbeverly @dustin-decker @dxa4481 @zricethezav
/go.mod @bryanbeverly @dustin-decker @dxa4481 @zricethezav
/go.sum @bryanbeverly @dustin-decker @dxa4481 @zricethezav
+17
View File
@@ -0,0 +1,17 @@
version: 2
updates:
- package-ecosystem: "gomod"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 10
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 5
groups:
actions:
patterns:
- "*"
+5 -3
View File
@@ -1,15 +1,17 @@
name: gitleaks
on: [push, workflow_dispatch]
on:
push:
workflow_dispatch:
jobs:
scan:
name: gitleaks
runs-on: ubuntu-latest
if: ${{ github.repository == 'gitleaks/gitleaks' }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
- uses: gitleaks/gitleaks-action@v2
- uses: gitleaks/gitleaks-action@e0c47f4f8be36e29cdc102c57e68cb5cbf0e8d1e # v3
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE}}
+7 -7
View File
@@ -17,23 +17,23 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v2
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Set up QEMU
uses: docker/setup-qemu-action@8b122486cedac8393e77aa9734c3528886e4a1a8
uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0
- name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@dc7b9719a96d48369863986a06765841d7ea23f6
uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
- name: Log in to Docker Hub
uses: docker/login-action@49ed152c8eca782a232dede0303416e8f356c37b
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
with:
username: ${{ github.actor }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Log in to the Container registry
uses: docker/login-action@49ed152c8eca782a232dede0303416e8f356c37b
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
@@ -41,14 +41,14 @@ jobs:
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38
uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0
with:
images: |
zricethezav/gitleaks
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
- name: Build and push Docker image
uses: docker/build-push-action@e551b19e49efd4e98792db7592c17c09b89db8d8
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
with:
platforms: linux/amd64,linux/arm64
context: .
+4 -4
View File
@@ -15,15 +15,15 @@ jobs:
platform: [ ubuntu-latest, windows-latest ]
runs-on: ${{ matrix.platform }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Set up Go
uses: actions/setup-go@v2
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: 1.23
go-version: 1.25
- name: Build
run: go build -v ./...
run: go build ./...
- name: Set up gotestsum
run: |
+1
View File
@@ -9,6 +9,7 @@
*.got
gitleaks
build
profile
# configs
.gitleaks.toml
+3 -1
View File
@@ -1,4 +1,4 @@
# This is NOT the default gitleaks config. The default gitleaks config is located
# This is NOT the default gitleaks config. The default gitleaks config is located
# here: https://github.com/gitleaks/gitleaks/blob/master/config/gitleaks.toml
# This gitleaks config extends the default config and ignores secrets located in the `cmd/generate/config/rules`
@@ -9,4 +9,6 @@ useDefault = true
[allowlist]
paths = [
'''(^|/)cmd/generate/config/rules''',
'''.*test\.go''',
'''testdata'''
]
+2
View File
@@ -940,3 +940,5 @@ e56870aecf8ac2733affc82e1ac25e3be9092db3:cmd/generate/config/rules/curl.go:gener
239e6323639b18ba8a1081f17788a658da075dd7:cmd/generate/config/rules/databricks.go:generic-api-key:22
c24a3a654b18d689732ec3199f0a19a254505b04:detect/detect_test.go:generic-api-key:52
c08cb1dc9aee87186dba4eebbc13b8aaa2351f0c:detect/detect_test.go:generic-api-key:52
ee0da5c7fa5f3c9a7f1617e162497199cac3537f:README.md:generic-api-key:480
782f3104786efdce0f809bce8a9ff31f2fa1c9ed:README.md:generic-api-key:481
+86
View File
@@ -0,0 +1,86 @@
version: '2'
linters:
default: none
# It might be worth going through some of the disabled linters and enabling
# them and fixing the items they call out e.g.: cyclop, prealloc,
# paralleltest, prealloc, errcheck, dupl, unused, testifylint, gosec,
# gocritic, perfsprint, exptostd, intrange, perfsprint (maybe others?)
disable:
- cyclop
- depguard
- dupl
- err113
- errcheck
- exhaustive
- exhaustruct
- exptostd
- forbidigo
- funcorder
- funlen
- gochecknoglobals
- gochecknoinits
- gocognit
- goconst
- gocritic
- gocyclo
- godot
- godox
- gosec
- gosmopolitan
- intrange
- lll
- maintidx
- mnd
- musttag
- nestif
- nilerr
- nlreturn
- nonamedreturns
- paralleltest
- perfsprint
- prealloc
- predeclared
- tagliatelle
- testifylint
- testpackage
- tparallel
- unparam
- unused
- varnamelen
- wastedassign
- whitespace
- wrapcheck
- wsl
- zerologlint # doesn't seem to catch gitleaks/v8/logging mistakes
enable:
- inamedparam
- misspell
- revive
- misspell
- inamedparam
- exhaustruct
- inamedparam
- misspell
- nonamedreturns
- staticcheck
- unconvert
exclusions:
rules:
- linters:
- staticcheck
source: 'detector\.Detect\w+\(|sources\.DirectoryTargets\(|detect\.(?:Fragment|RemoteInfo)'
- linters:
- misspell
source: '"(?:addres|busines|clas)",'
settings:
staticcheck:
checks:
- all
- '-QF1001'
- '-ST1000'
- '-ST1003'
- '-ST1018'
- '-ST1020'
- '-ST1021'
revive:
severity: error
+1 -1
View File
@@ -18,7 +18,7 @@ builds:
tags:
- gore2regex
ldflags:
- -s -w -X=github.com/zricethezav/gitleaks/v8/cmd.Version={{.Version}}
- -s -w -X=github.com/zricethezav/gitleaks/v8/version.Version={{.Version}}
archives:
- builds: [gitleaks]
format_overrides:
+2 -1
View File
@@ -9,8 +9,9 @@
description: Detect hardcoded secrets using Gitleaks
entry: zricethezav/gitleaks git --pre-commit --redact --staged --verbose
language: docker_image
pass_filenames: false
- id: gitleaks-system
name: Detect hardcoded secrets
description: Detect hardcoded secrets using Gitleaks
entry: gitleaks git --pre-commit --redact --staged --verbose
entry: gitleaks git --pre-commit --redact --staged --verbose
language: system
+2 -2
View File
@@ -35,7 +35,7 @@ If you want to add a new rule to the [default Gitleaks configuration](https://gi
RuleID: "beamer-api-token",
// Regex capture group for the actual secret
// Regex used for detecting secrets. See regex section below for more details
@@ -95,7 +95,7 @@ If you want to add a new rule to the [default Gitleaks configuration](https://gi
the `rules.Beamer(),` in `main()`. Try and keep
this alphabetically pretty please.
1. Run `go generate ./...`
1. Run `make config/gitleaks.toml`
1. Check out your new rules in `config/gitleaks.toml` and see if everything looks good.
+3 -3
View File
@@ -1,10 +1,10 @@
FROM golang:1.23 AS build
FROM golang:1.24 AS build
WORKDIR /go/src/github.com/zricethezav/gitleaks
COPY . .
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}"
CGO_ENABLED=0 go build -o bin/gitleaks -ldflags "-X=github.com/zricethezav/gitleaks/v8/version.Version=${VERSION}"
FROM alpine:3.19
FROM alpine:3.22
RUN apk add --no-cache bash git openssh-client
COPY --from=build /go/src/github.com/zricethezav/gitleaks/bin/* /usr/bin/
+17 -4
View File
@@ -1,8 +1,8 @@
.PHONY: test test-cover
.PHONY: test test-cover failfast profile clean format build
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)"
LDFLAGS=-ldflags "-X=github.com/zricethezav/gitleaks/v8/version.Version=$(VERSION)"
COVER=--cover --coverprofile=cover.out
test-cover:
@@ -12,13 +12,26 @@ test-cover:
format:
go fmt ./...
test: format
test: config/gitleaks.toml format
go test -v ./... --race $(PKG)
build: format
failfast: format
go test -failfast ./...
build: config/gitleaks.toml format
go mod tidy
go build $(LDFLAGS)
lint:
golangci-lint run
clean:
rm -rf profile
find . -type f -name '*.got.*' -delete
find . -type f -name '*.out' -delete
profile: build
./scripts/profile.sh './gitleaks' '.'
config/gitleaks.toml: $(wildcard cmd/generate/config/**/*)
go generate ./...
+165 -39
View File
@@ -8,6 +8,9 @@
└─░───┘
```
> [!WARNING]
> Gitleaks is feature complete. I'm not merging new features into Gitleaks. Future releases will be security patches only. I'm shifting my focus to [Betterleaks](https://github.com/betterleaks/betterleaks)
[license]: ./LICENSE
[badge-license]: https://img.shields.io/github/license/gitleaks/gitleaks.svg
[go-docs-badge]: https://pkg.go.dev/badge/github.com/gitleaks/gitleaks/v8?status
@@ -20,22 +23,16 @@
[dockerhub-badge]: https://img.shields.io/docker/pulls/zricethezav/gitleaks.svg
[gitleaks-action]: https://github.com/gitleaks/gitleaks-action
[gitleaks-badge]: https://img.shields.io/badge/protected%20by-gitleaks-blue
[gitleaks-playground-badge]: https://img.shields.io/badge/gitleaks%20-playground-blue
[gitleaks-playground]: https://gitleaks.io/playground
[![Github Action Test][badge-build]][build]
[![GitHub Action Test][badge-build]][build]
[![Docker Hub][dockerhub-badge]][dockerhub]
[![Gitleaks Playground][gitleaks-playground-badge]][gitleaks-playground]
[![Gitleaks Action][gitleaks-badge]][gitleaks-action]
[![GoDoc][go-docs-badge]][go-docs]
[![GoReportCard][go-report-card-badge]][go-report-card]
[![License][badge-license]][license]
### Join our Discord! [![Discord](https://img.shields.io/discord/1102689410522284044.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/8Hzbrnkr7E)
Gitleaks is a tool for **detecting** secrets like passwords, API keys, and tokens in git repos, files, and whatever else you wanna throw at it via `stdin`.
Gitleaks is a tool for **detecting** secrets like passwords, API keys, and tokens in git repos, files, and whatever else you wanna throw at it via `stdin`. If you wanna learn more about how the detection engine works check out this blog: [Regex is (almost) all you need](https://lookingatcomputer.substack.com/p/regex-is-almost-all-you-need).
```
➜ ~/code(master) gitleaks git -v
@@ -60,6 +57,7 @@ Date: 2022-08-03T12:31:40Z
Fingerprint: cd5226711335c68be1e720b318b7bc3135a30eb2:cmd/generate/config/rules/sidekiq.go:sidekiq-secret:23
```
## 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/gitleaks/gitleaks/releases). In addition, Gitleaks can be implemented as a pre-commit hook directly in your repo or as a GitHub action using [Gitleaks-Action](https://github.com/gitleaks/gitleaks-action).
@@ -84,27 +82,6 @@ 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
@@ -118,7 +95,7 @@ jobs:
- id: gitleaks
```
for a [native execution of GitLeaks](https://github.com/gitleaks/gitleaks/releases) or use the [`gitleaks-docker` pre-commit ID](https://github.com/gitleaks/gitleaks/blob/master/.pre-commit-hooks.yaml) for executing GitLeaks using the [official Docker images](#docker)
for a [native execution of gitleaks](https://github.com/gitleaks/gitleaks/releases) or use the [`gitleaks-docker` pre-commit ID](https://github.com/gitleaks/gitleaks/blob/master/.pre-commit-hooks.yaml) for executing gitleaks using the [official Docker images](#docker)
3. Auto-update the config to the latest repos' versions by executing `pre-commit autoupdate`
4. Install with `pre-commit install`
@@ -140,11 +117,13 @@ Detect hardcoded secrets................................................Skipped
## Usage
```
Gitleaks scans code, past or present, for secrets
Usage:
gitleaks [command]
Available Commands:
completion generate the autocompletion script for the specified shell
completion Generate the autocompletion script for the specified shell
dir scan directories or files for secrets
git scan git repositories for secrets
help Help about any command
@@ -160,20 +139,24 @@ Flags:
3. env var GITLEAKS_CONFIG_TOML with the file content
4. (target path)/.gitleaks.toml
If none of the four options are used, then gitleaks will use the default config
--diagnostics string enable diagnostics (http OR comma-separated list: cpu,mem,trace). cpu=CPU prof, mem=memory prof, trace=exec tracing, http=serve via net/http/pprof
--diagnostics-dir string directory to store diagnostics output files when not using http mode (defaults to current directory)
--enable-rule strings only enable specific rules by id
--exit-code int exit code when leaks have been encountered (default 1)
-i, --gitleaks-ignore-path string path to .gitleaksignore file or folder containing one (default ".")
-h, --help help for gitleaks
--ignore-gitleaks-allow ignore gitleaks:allow comments
-l, --log-level string log level (trace, debug, info, warn, error, fatal) (default "info")
--max-archive-depth int allow scanning into nested archives up to this depth (default "0", no archive traversal is done)
--max-decode-depth int allow recursive decoding up to this depth (default "0", no decoding is done)
--max-target-megabytes int files larger than this will be skipped
--no-banner suppress banner
--no-color turn off color for verbose output
--redact uint[=100] redact secrets from logs and stdout. To redact only parts of the secret just apply a percent value from 0..100. For example --redact=20 (default 100%)
-f, --report-format string output format (json, csv, junit, sarif) (default "json")
-f, --report-format string output format (json, csv, junit, sarif, template)
-r, --report-path string report file
--report-template string template file used to generate the report (implies --report-format=template)
--timeout int set a timeout for gitleaks commands in seconds (default "0", no timeout is set)
-v, --verbose show verbose output from scan
--version version for gitleaks
@@ -189,6 +172,7 @@ If you find v8.19.0 broke an existing command (`detect`/`protect`), please open
There are three scanning modes: `git`, `dir`, and `stdin`.
#### Git
The `git` command lets you scan local git repos. Under the hood, gitleaks uses the `git log -p` command to scan patches.
You can configure the behavior of `git log -p` with the `log-opts` option.
For example, if you wanted to run gitleaks on a range of commits you could use the following
@@ -196,10 +180,12 @@ command: `gitleaks git -v --log-opts="--all commitA..commitB" path_to_repo`. See
If there is no target specified as a positional argument, then gitleaks will attempt to scan the current working directory as a git repo.
#### Dir
The `dir` (aliases include `files`, `directory`) command lets you scan directories and files. Example: `gitleaks dir -v path_to_directory_or_file`.
If there is no target specified as a positional argument, then gitleaks will scan the current working directory.
#### Stdin
You can also stream data to gitleaks with the `stdin` command. Example: `cat some_file | gitleaks -v stdin`
### Creating a baseline
@@ -290,11 +276,10 @@ disabledRules = [ "generic-api-key"]
# 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.
# Short human-readable description of the rule.
description = "awesome rule 1"
# Golang regular expression used to detect secrets. Note Golang's regex engine
@@ -368,19 +353,20 @@ id = "gitlab-pat"
regexTarget = "line"
regexes = [ '''MY-glpat-''' ]
# This is a global allowlist which has a higher order of precedence than rule-specific allowlists.
# ⚠️ In v8.25.0 `[allowlist]` was replaced with `[[allowlists]]`.
#
# Global allowlists have 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]
[[allowlists]]
description = "global allow list"
commits = [ "commit-A", "commit-B", "commit-C"]
paths = [
'''gitleaks\.toml''',
'''(.*?)(jpg|gif|doc)'''
]
# note: (global) regexTarget defaults to check the _Secret_ in the finding.
# if regexTarget is not specified then _Secret_ will be used.
# Acceptable values for regexTarget are "match" and "line"
regexTarget = "match"
regexes = [
@@ -394,12 +380,109 @@ stopwords = [
'''client''',
'''endpoint''',
]
# ⚠️ In v8.25.0, `[[allowlists]]` have a new field called |targetRules|.
#
# Common allowlists can be defined once and assigned to multiple rules using |targetRules|.
# This will only run on the specified rules, not globally.
[[allowlists]]
targetRules = ["awesome-rule-1", "awesome-rule-2"]
description = "Our test assets trigger false-positives in a couple rules."
paths = ['''tests/expected/._\.json$''']
```
Refer to the default [gitleaks config](https://github.com/gitleaks/gitleaks/blob/master/config/gitleaks.toml) for examples or follow the [contributing guidelines](https://github.com/gitleaks/gitleaks/blob/master/CONTRIBUTING.md) if you would like to contribute to the default configuration. Additionally, you can check out [this gitleaks blog post](https://blog.gitleaks.io/stop-leaking-secrets-configuration-2-3-aeed293b1fbf) which covers advanced configuration setups.
### Additional Configuration
#### Composite Rules (Multi-part or `required` Rules)
In v8.28.0 Gitleaks introduced composite rules, which are made up of a single "primary" rule and one or more auxiliary or `required` rules. To create a composite rule, add a `[[rules.required]]` table to the primary rule specifying an `id` and optionally `withinLines` and/or `withinColumns` proximity constraints. A fragment is a chunk of content that Gitleaks processes at once (typically a file, part of a file, or git diff), and proximity matching instructs the primary rule to only report a finding if the auxiliary `required` rules also find matches within the specified area of the fragment.
**Proximity matching:** Using the `withinLines` and `withinColumns` fields instructs the primary rule to only report a finding if the auxiliary `required` rules also find matches within the specified proximity. You can set:
- **`withinLines: N`** - required findings must be within N lines (vertically)
- **`withinColumns: N`** - required findings must be within N characters (horizontally)
- **Both** - creates a rectangular search area (both constraints must be satisfied)
- **Neither** - fragment-level matching (required findings can be anywhere in the same fragment)
Here are diagrams illustrating each proximity behavior:
```
p = primary captured secret
a = auxiliary (required) captured secret
fragment = section of data gitleaks is looking at
*Fragment-level proximity*
Any required finding in the fragment
┌────────┐
┌──────┤fragment├─────┐
│ └──────┬─┤ │ ┌───────┐
│ │a│◀────┼─│✓ MATCH│
│ ┌─┐└─┘ │ └───────┘
│┌─┐ │p│ │
││a│ ┌─┐└─┘ │ ┌───────┐
│└─┘ │a│◀──────────┼─│✓ MATCH│
└─▲─────┴─┴───────────┘ └───────┘
│ ┌───────┐
└────│✓ MATCH│
└───────┘
*Column bounded proximity*
`withinColumns = 3`
┌────────┐
┌────┬─┤fragment├─┬───┐
│ └──────┬─┤ │ ┌───────────┐
│ │ │a│◀┼───┼─│+1C ✓ MATCH│
│ ┌─┐└─┘ │ └───────────┘
│┌─┐ │ │p│ │ │
┌──▶│a│ ┌─┐ └─┘ │ ┌───────────┐
│ │└─┘ ││a│◀────────┼───┼─│-2C ✓ MATCH│
│ │ ┘ │ └───────────┘
│ └── -3C ───0C─── +3C ─┘
│ ┌─────────┐
│ │ -4C ✗ NO│
└──│ MATCH │
└─────────┘
*Line bounded proximity*
`withinLines = 4`
┌────────┐
┌─────┤fragment├─────┐
+4L─ ─ ┴────────┘─ ─ ─│
│ │
│ ┌─┐ │ ┌────────────┐
│ ┌─┐ │a│◀──┼─│+1L ✓ MATCH │
0L ┌─┐ │p│ └─┘ │ ├────────────┤
│ │a│◀──┴─┴────────┼─│-1L ✓ MATCH │
│ └─┘ │ └────────────┘
│ │ ┌─────────┐
-4L─ ─ ─ ─ ─ ─ ─ ─┌─┐─│ │-5L ✗ NO │
│ │a│◀┼─│ MATCH │
└────────────────┴─┴─┘ └─────────┘
*Line and column bounded proximity*
`withinLines = 4`
`withinColumns = 3`
┌────────┐
┌─────┤fragment├─────┐
+4L ┌└────────┴ ┐ │
│ ┌─┐ │ ┌───────────────┐
│ │ │a│◀┼───┼─│+2L/+1C ✓ MATCH│
│ ┌─┐└─┘ │ └───────────────┘
0L │ │p│ │ │
│ └─┘ │
│ │ │ │ ┌────────────┐
-4L ─ ─ ─ ─ ─ ─┌─┐ │ │-5L/+3C ✗ NO│
│ │a│◀┼─│ MATCH │
└───-3C────0L───+3C┴─┘ └────────────┘
```
<details><summary>Some final quick thoughts on composite rules.</summary>This is an experimental feature! It's subject to change so don't go sellin' a new B2B SaaS feature built ontop of this feature. Scan type (git vs dir) based context is interesting. I'm monitoring the situation. Composite rules might not be super useful for git scans because gitleaks only looks at additions in the git history. It could be useful to scan non-additions in git history for `required` rules. Oh, right this is a readme, I'll shut up now.</details>
#### gitleaks:allow
If you are knowingly committing a test secret that gitleaks will catch you can add a `gitleaks:allow` comment to that line which will instruct gitleaks
@@ -440,7 +523,48 @@ ways:
Currently supported encodings:
- `base64` (both standard and base64url)
- **percent** - Any printable ASCII percent encoded values
- **hex** - Any printable ASCII hex encoded values >= 32 characters
- **base64** - Any printable ASCII base64 encoded values >= 16 characters
#### Archive Scanning
Sometimes secrets are packaged within archive files like zip files or tarballs,
making them difficult to discover. Now you can tell gitleaks to automatically
extract and scan the contents of archives. The flag `--max-archive-depth`
enables this feature for both `dir` and `git` scan types. The default value of
"0" means this feature is disabled by default.
Recursive scanning is supported since archives can also contain other archives.
The `--max-archive-depth` flag sets the recursion limit. Recursion stops when
there are no new archives to extract, so setting a very high max depth just
sets the potential to go that deep. It will only go as deep as it needs to.
The findings for secrets located within an archive will include the path to the
file inside the archive. Inner paths are separated with `!`.
Example finding (shortened for brevity):
```
Finding: DB_PASSWORD=8ae31cacf141669ddfb5da
...
File: testdata/archives/nested.tar.gz!archives/files.tar!files/.env.prod
Line: 4
Commit: 6e6ee6596d337bb656496425fb98644eb62b4a82
...
Fingerprint: 6e6ee6596d337bb656496425fb98644eb62b4a82:testdata/archives/nested.tar.gz!archives/files.tar!files/.env.prod:generic-api-key:4
Link: https://github.com/leaktk/gitleaks/blob/6e6ee6596d337bb656496425fb98644eb62b4a82/testdata/archives/nested.tar.gz
```
This means a secret was detected on line 4 of `files/.env.prod.` which is in
`archives/files.tar` which is in `testdata/archives/nested.tar.gz`.
Currently supported formats:
The [compression](https://github.com/mholt/archives?tab=readme-ov-file#supported-compression-formats)
and [archive](https://github.com/mholt/archives?tab=readme-ov-file#supported-archive-formats)
formats supported by mholt's [archives package](https://github.com/mholt/archives)
are supported.
#### Reporting
@@ -502,3 +626,5 @@ You can always set the exit code when leaks are encountered with the --exit-code
1 - leaks or error encountered
126 - unknown flag
```
### Join the Discord! [![Discord](https://img.shields.io/discord/1102689410522284044.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/8Hzbrnkr7E)
+19
View File
@@ -0,0 +1,19 @@
# Security Policy
## Supported Versions
| Version | Supported |
|---------|-----------|
| Latest | Yes |
## Reporting a Vulnerability
If you discover a security vulnerability in gitleaks, please report it responsibly:
1. **Do not open a public issue.**
2. Use [GitHub's private vulnerability reporting](https://github.com/gitleaks/gitleaks/security/advisories/new) to submit your report directly.
3. Include a description of the vulnerability, steps to reproduce, and any relevant logs or screenshots.
## Scope
This policy covers `gitleaks` (this repository). For vulnerabilities in `gitleaks-action`, please report them at [gitleaks/gitleaks-action](https://github.com/gitleaks/gitleaks-action/security/advisories/new).
+39 -22
View File
@@ -25,7 +25,6 @@ import (
"github.com/spf13/cobra"
"github.com/zricethezav/gitleaks/v8/cmd/scm"
"github.com/zricethezav/gitleaks/v8/detect"
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
@@ -51,65 +50,83 @@ var detectCmd = &cobra.Command{
func runDetect(cmd *cobra.Command, args []string) {
// start timer
start := time.Now()
source := mustGetStringFlag(cmd, "source")
sourcePath := mustGetStringFlag(cmd, "source")
// setup config (aka, the thing that defines rules)
initConfig(source)
initConfig(sourcePath)
initDiagnostics()
cfg := Config(cmd)
// create detector
detector := Detector(cmd, cfg, source)
detector := Detector(cmd, cfg, sourcePath)
// parse flags
detector.FollowSymlinks = mustGetBoolFlag(cmd, "follow-symlinks")
exitCode := mustGetIntFlag(cmd, "exit-code")
noGit := mustGetBoolFlag(cmd, "no-git")
fromPipe := mustGetBoolFlag(cmd, "pipe")
// determine what type of scan:
// - git: scan the history of the repo
// - no-git: scan files by treating the repo as a plain directory
var (
findings []report.Finding
err error
findings []report.Finding
)
if noGit {
paths, err := sources.DirectoryTargets(
source,
detector.Sema,
detector.FollowSymlinks,
detector.Config.Allowlist.PathAllowed,
findings, err = detector.DetectSource(
cmd.Context(), &sources.Files{
Config: &cfg,
FollowSymlinks: detector.FollowSymlinks,
MaxFileSize: detector.MaxTargetMegaBytes * 1_000_000,
Path: sourcePath,
Sema: detector.Sema,
MaxArchiveDepth: detector.MaxArchiveDepth,
},
)
if err != nil {
logging.Fatal().Err(err).Send()
}
if findings, err = detector.DetectFiles(paths); err != nil {
if err != nil {
// don't exit on error, just log it
logging.Error().Err(err).Msg("failed scan directory")
logging.Error().Err(err).Msg("failed to scan directory")
}
} else if fromPipe {
if findings, err = detector.DetectReader(os.Stdin, 10); err != nil {
findings, err = detector.DetectSource(
cmd.Context(), &sources.File{
Content: os.Stdin,
MaxArchiveDepth: detector.MaxArchiveDepth,
},
)
if err != nil {
// log fatal to exit, no need to continue since a report
// will not be generated when scanning from a pipe...for now
logging.Fatal().Err(err).Msg("failed scan input from stdin")
}
} else {
var (
logOpts = mustGetStringFlag(cmd, "log-opts")
gitCmd *sources.GitCmd
scmPlatform scm.Platform
remote *detect.RemoteInfo
)
if gitCmd, err = sources.NewGitLogCmd(source, logOpts); err != nil {
logOpts := mustGetStringFlag(cmd, "log-opts")
if gitCmd, err = sources.NewGitLogCmdContext(cmd.Context(), sourcePath, logOpts); err != nil {
logging.Fatal().Err(err).Msg("could not create Git cmd")
}
if scmPlatform, err = scm.PlatformFromString(mustGetStringFlag(cmd, "platform")); err != nil {
logging.Fatal().Err(err).Send()
}
remote = detect.NewRemoteInfo(scmPlatform, source)
if findings, err = detector.DetectGit(gitCmd, remote); err != nil {
findings, err = detector.DetectSource(
cmd.Context(), &sources.Git{
Cmd: gitCmd,
Config: &detector.Config,
Remote: sources.NewRemoteInfoContext(cmd.Context(), scmPlatform, sourcePath),
Sema: detector.Sema,
MaxArchiveDepth: detector.MaxArchiveDepth,
},
)
if err != nil {
// don't exit on error, just log it
logging.Error().Err(err).Msg("failed to scan Git repository")
}
+239
View File
@@ -0,0 +1,239 @@
package cmd
import (
"errors"
"fmt"
"net/http"
_ "net/http/pprof"
"os"
"path/filepath"
"runtime"
"runtime/pprof"
"runtime/trace"
"strings"
"github.com/zricethezav/gitleaks/v8/logging"
)
// DiagnosticsManager manages various types of diagnostics
type DiagnosticsManager struct {
Enabled bool
DiagTypes []string
OutputDir string
cpuProfile *os.File
memProfile string
traceProfile *os.File
}
// NewDiagnosticsManager creates a new DiagnosticsManager instance
func NewDiagnosticsManager(diagnosticsFlag string, diagnosticsDir string) (*DiagnosticsManager, error) {
if diagnosticsFlag == "" {
return &DiagnosticsManager{Enabled: false}, nil
}
dm := &DiagnosticsManager{
Enabled: true,
DiagTypes: strings.Split(diagnosticsFlag, ","),
OutputDir: diagnosticsDir,
}
if diagnosticsFlag == "http" {
if len(diagnosticsDir) != 0 {
return nil, errors.New("the diagnostics directory should not be set in http mode")
}
return dm, nil
}
// If no output directory is specified, use the current directory
if dm.OutputDir == "" {
var err error
dm.OutputDir, err = os.Getwd()
if err != nil {
return nil, fmt.Errorf("failed to get current directory: %w", err)
}
logging.Debug().Msgf("No diagnostics directory specified, using current directory: %s", dm.OutputDir)
}
// Create the output directory if it doesn't exist
if err := os.MkdirAll(dm.OutputDir, 0755); err != nil {
return nil, fmt.Errorf("failed to create diagnostics directory: %w", err)
}
// Make sure the output directory is absolute
if !filepath.IsAbs(dm.OutputDir) {
absPath, err := filepath.Abs(dm.OutputDir)
if err != nil {
return nil, fmt.Errorf("failed to get absolute path for diagnostics directory: %w", err)
}
dm.OutputDir = absPath
}
logging.Debug().Msgf("Diagnostics enabled: %s", strings.Join(dm.DiagTypes, ","))
logging.Debug().Msgf("Diagnostics output directory: %s", dm.OutputDir)
return dm, nil
}
// StartDiagnostics starts all enabled diagnostics
func (dm *DiagnosticsManager) StartDiagnostics() error {
if !dm.Enabled {
return nil
}
var err error
for _, diagType := range dm.DiagTypes {
diagType = strings.TrimSpace(diagType)
switch diagType {
case "cpu":
if err = dm.StartCPUProfile(); err != nil {
return err
}
case "mem":
if err = dm.SetupMemoryProfile(); err != nil {
return err
}
case "trace":
if err = dm.StartTraceProfile(); err != nil {
return err
}
case "http":
if err = dm.StartHttpHandler(); err != nil {
return err
}
default:
logging.Warn().Msgf("Unknown diagnostics type: %s", diagType)
}
}
return nil
}
// StopDiagnostics stops all started diagnostics
func (dm *DiagnosticsManager) StopDiagnostics() {
if !dm.Enabled {
return
}
logging.Debug().Msg("Stopping diagnostics and writing profiling data...")
for _, diagType := range dm.DiagTypes {
diagType = strings.TrimSpace(diagType)
switch diagType {
case "cpu":
dm.StopCPUProfile()
case "mem":
dm.WriteMemoryProfile()
case "trace":
dm.StopTraceProfile()
case "http":
// No need to stop the http one
}
}
}
func (dm *DiagnosticsManager) StartHttpHandler() error {
if len(dm.DiagTypes) > 1 {
return errors.New("other diagnostics modes should not be enabled when http mode is enabled")
}
go func() {
logging.Error().Err(http.ListenAndServe("localhost:6060", nil)).Send()
}()
logging.Info().Str("url", "http://localhost:6060/debug/pprof/").Msg("Diagnostics server started")
return nil
}
// StartCPUProfile starts CPU profiling
func (dm *DiagnosticsManager) StartCPUProfile() error {
cpuProfilePath := filepath.Join(dm.OutputDir, "cpu.pprof")
f, err := os.Create(cpuProfilePath)
if err != nil {
return fmt.Errorf("could not create CPU profile at %s: %w", cpuProfilePath, err)
}
if err := pprof.StartCPUProfile(f); err != nil {
_ = f.Close()
return fmt.Errorf("could not start CPU profile: %w", err)
}
dm.cpuProfile = f
return nil
}
// StopCPUProfile stops CPU profiling
func (dm *DiagnosticsManager) StopCPUProfile() {
if dm.cpuProfile != nil {
pprof.StopCPUProfile()
if err := dm.cpuProfile.Close(); err != nil {
logging.Error().Err(err).Msg("Error closing CPU profile file")
}
logging.Info().Msgf("CPU profile written to: %s", dm.cpuProfile.Name())
dm.cpuProfile = nil
}
}
// SetupMemoryProfile sets up memory profiling to be written when StopDiagnostics is called
func (dm *DiagnosticsManager) SetupMemoryProfile() error {
memProfilePath := filepath.Join(dm.OutputDir, "mem.pprof")
dm.memProfile = memProfilePath
return nil
}
// WriteMemoryProfile writes the memory profile to disk
func (dm *DiagnosticsManager) WriteMemoryProfile() {
if dm.memProfile == "" {
return
}
f, err := os.Create(dm.memProfile)
if err != nil {
logging.Error().Err(err).Msgf("Could not create memory profile at %s", dm.memProfile)
return
}
// Get memory profile
runtime.GC() // Run GC before taking the memory profile
if err := pprof.WriteHeapProfile(f); err != nil {
logging.Error().Err(err).Msg("Could not write memory profile")
} else {
logging.Info().Msgf("Memory profile written to: %s", dm.memProfile)
}
if err := f.Close(); err != nil {
logging.Error().Err(err).Msg("Error closing memory profile file")
}
dm.memProfile = ""
}
// StartTraceProfile starts execution tracing
func (dm *DiagnosticsManager) StartTraceProfile() error {
traceProfilePath := filepath.Join(dm.OutputDir, "trace.out")
f, err := os.Create(traceProfilePath)
if err != nil {
return fmt.Errorf("could not create trace profile at %s: %w", traceProfilePath, err)
}
if err := trace.Start(f); err != nil {
_ = f.Close()
return fmt.Errorf("could not start trace profile: %w", err)
}
dm.traceProfile = f
return nil
}
// StopTraceProfile stops execution tracing
func (dm *DiagnosticsManager) StopTraceProfile() {
if dm.traceProfile != nil {
trace.Stop()
if err := dm.traceProfile.Close(); err != nil {
logging.Error().Err(err).Msg("Error closing trace profile file")
}
logging.Info().Msgf("Trace profile written to: %s", dm.traceProfile.Name())
dm.traceProfile = nil
}
}
+15 -17
View File
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra"
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
)
@@ -31,11 +30,10 @@ func runDirectory(cmd *cobra.Command, args []string) {
source = "."
}
}
initConfig(source)
var (
findings []report.Finding
err error
)
initDiagnostics()
var err error
// setup config (aka, the thing that defines rules)
cfg := Config(cmd)
@@ -47,28 +45,28 @@ func runDirectory(cmd *cobra.Command, args []string) {
// set follow symlinks flag
if detector.FollowSymlinks, err = cmd.Flags().GetBool("follow-symlinks"); err != nil {
logging.Fatal().Err(err).Msg("")
logging.Fatal().Err(err).Send()
}
// set exit code
exitCode, err := cmd.Flags().GetInt("exit-code")
if err != nil {
logging.Fatal().Err(err).Msg("could not get exit code")
}
var paths <-chan sources.ScanTarget
paths, err = sources.DirectoryTargets(
source,
detector.Sema,
detector.FollowSymlinks,
detector.Config.Allowlist.PathAllowed,
findings, err := detector.DetectSource(
cmd.Context(),
&sources.Files{
Config: &cfg,
FollowSymlinks: detector.FollowSymlinks,
MaxFileSize: detector.MaxTargetMegaBytes * 1_000_000,
Path: source,
Sema: detector.Sema,
MaxArchiveDepth: detector.MaxArchiveDepth,
},
)
if err != nil {
logging.Fatal().Err(err)
}
findings, err = detector.DetectFiles(paths)
if err != nil {
// don't exit on error, just log it
logging.Error().Err(err).Msg("failed scan directory")
}
+93 -89
View File
@@ -11,106 +11,110 @@ import (
func CreateGlobalConfig() config.Config {
return config.Config{
Title: "gitleaks config",
Allowlist: config.Allowlist{
Description: "global allow lists",
Regexes: []*regexp.Regexp{
// ----------- General placeholders -----------
regexp.MustCompile(`(?i)^true|false|null$`),
// Awkward workaround to detect repeated characters.
func() *regexp.Regexp {
var (
letters = "abcdefghijklmnopqrstuvwxyz*."
patterns []string
)
for _, char := range letters {
if char == '*' || char == '.' {
patterns = append(patterns, fmt.Sprintf("\\%c+", char))
} else {
patterns = append(patterns, fmt.Sprintf("%c+", char))
Allowlists: []*config.Allowlist{
{
Description: "global allow lists",
Regexes: []*regexp.Regexp{
// ----------- General placeholders -----------
regexp.MustCompile(`(?i)^true|false|null$`),
// Awkward workaround to detect repeated characters.
func() *regexp.Regexp {
var (
letters = "abcdefghijklmnopqrstuvwxyz*."
patterns []string
)
for _, char := range letters {
if char == '*' || char == '.' {
patterns = append(patterns, fmt.Sprintf("\\%c+", char))
} else {
patterns = append(patterns, fmt.Sprintf("%c+", char))
}
}
}
return regexp.MustCompile("^(?i:" + strings.Join(patterns, "|") + ")$")
}(),
return regexp.MustCompile("^(?i:" + strings.Join(patterns, "|") + ")$")
}(),
// ----------- Environment Variables -----------
regexp.MustCompile(`^\$(?:\d+|{\d+})$`),
regexp.MustCompile(`^\$(?:[A-Z_]+|[a-z_]+)$`),
regexp.MustCompile(`^\${(?:[A-Z_]+|[a-z_]+)}$`),
// ----------- Environment Variables -----------
regexp.MustCompile(`^\$(?:\d+|{\d+})$`),
regexp.MustCompile(`^\$(?:[A-Z_]+|[a-z_]+)$`),
regexp.MustCompile(`^\${(?:[A-Z_]+|[a-z_]+)}$`),
// ----------- Interpolated Variables -----------
// Ansible (https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_variables.html)
regexp.MustCompile(`^\{\{[ \t]*[\w ().|]+[ \t]*}}$`),
// GitHub Actions
// https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/store-information-in-variables
// https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions
regexp.MustCompile(`^\$\{\{[ \t]*(?:(?:env|github|secrets|vars)(?:\.[A-Za-z]\w+)+[\w "'&./=|]*)[ \t]*}}$`),
// NuGet (https://learn.microsoft.com/en-us/nuget/reference/nuget-config-file#using-environment-variables)
regexp.MustCompile(`^%(?:[A-Z_]+|[a-z_]+)%$`),
// String formatting.
regexp.MustCompile(`^%[+\-# 0]?[bcdeEfFgGoOpqstTUvxX]$`), // Golang (https://pkg.go.dev/fmt)
regexp.MustCompile(`^\{\d{0,2}}$`), // Python (https://docs.python.org/3/tutorial/inputoutput.html)
// Urban Code Deploy (https://www.ibm.com/support/pages/replace-token-step-replaces-replacement-values-windows-variables)
regexp.MustCompile(`^@(?:[A-Z_]+|[a-z_]+)@$`),
// ----------- Interpolated Variables -----------
// Ansible (https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_variables.html)
regexp.MustCompile(`^\{\{[ \t]*[\w ().|]+[ \t]*}}$`),
// GitHub Actions
// https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/store-information-in-variables
// https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions
regexp.MustCompile(`^\$\{\{[ \t]*(?:(?:env|github|secrets|vars)(?:\.[A-Za-z]\w+)+[\w "'&./=|]*)[ \t]*}}$`),
// NuGet (https://learn.microsoft.com/en-us/nuget/reference/nuget-config-file#using-environment-variables)
regexp.MustCompile(`^%(?:[A-Z_]+|[a-z_]+)%$`),
// String formatting.
regexp.MustCompile(`^%[+\-# 0]?[bcdeEfFgGoOpqstTUvxX]$`), // Golang (https://pkg.go.dev/fmt)
regexp.MustCompile(`^\{\d{0,2}}$`), // Python (https://docs.python.org/3/tutorial/inputoutput.html)
// Urban Code Deploy (https://www.ibm.com/support/pages/replace-token-step-replaces-replacement-values-windows-variables)
regexp.MustCompile(`^@(?:[A-Z_]+|[a-z_]+)@$`),
// ----------- Miscellaneous -----------
// File paths
regexp.MustCompile(`^/Users/(?i)[a-z0-9]+/[\w .-/]+$`), // MacOS
regexp.MustCompile(`^/(?:bin|etc|home|opt|tmp|usr|var)/[\w ./-]+$`), // Linux
// 11980 Jps -Dapplication.home=D:\develop_tools\jdk\jdk1.8.0_131 -Xms8m
//regexp.MustCompile(`^$`), // Windows
},
Paths: []*regexp.Regexp{
regexp.MustCompile(`gitleaks\.toml`),
// ----------- Miscellaneous -----------
// File paths
regexp.MustCompile(`^/Users/(?i)[a-z0-9]+/[\w .-/]+$`), // MacOS
regexp.MustCompile(`^/(?:bin|etc|home|opt|tmp|usr|var)/[\w ./-]+$`), // Linux
// 11980 Jps -Dapplication.home=D:\develop_tools\jdk\jdk1.8.0_131 -Xms8m
//regexp.MustCompile(`^$`), // Windows
},
Paths: []*regexp.Regexp{
regexp.MustCompile(`gitleaks\.toml`),
// ----------- Documents and media -----------
regexp.MustCompile(`(?i)\.(?:bmp|gif|jpe?g|png|svg|tiff?)$`), // Images
regexp.MustCompile(`(?i)\.(?:eot|[ot]tf|woff2?)$`), // Fonts
regexp.MustCompile(`(?i)\.(?:docx?|xlsx?|pdf|bin|socket|vsidx|v2|suo|wsuo|.dll|pdb|exe|gltf|zip)$`),
// ----------- Documents and media -----------
regexp.MustCompile(`(?i)\.(?:bmp|gif|jpe?g|png|svg|tiff?)$`), // Images
regexp.MustCompile(`(?i)\.(?:eot|[ot]tf|woff2?)$`), // Fonts
regexp.MustCompile(`(?i)\.(?:docx?|xlsx?|pdf|bin|socket|vsidx|v2|suo|wsuo|.dll|pdb|exe|gltf)$`),
// ----------- Golang files -----------
regexp.MustCompile(`go\.(?:mod|sum|work(?:\.sum)?)$`),
regexp.MustCompile(`(?:^|/)vendor/modules\.txt$`),
regexp.MustCompile(`(?:^|/)vendor/(?:github\.com|golang\.org/x|google\.golang\.org|gopkg\.in|istio\.io|k8s\.io|sigs\.k8s\.io)(?:/.*)?$`),
// ----------- Golang files -----------
regexp.MustCompile(`go\.(?:mod|sum|work(?:\.sum)?)$`),
regexp.MustCompile(`(?:^|/)vendor/modules\.txt$`),
regexp.MustCompile(`(?:^|/)vendor/(?:github\.com|golang\.org/x|google\.golang\.org|gopkg\.in|istio\.io|k8s\.io|sigs\.k8s\.io)(?:/.*)?$`),
// ----------- Java files -----------
// Gradle
regexp.MustCompile(`(?:^|/)gradlew(?:\.bat)?$`),
regexp.MustCompile(`(?:^|/)gradle\.lockfile$`),
regexp.MustCompile(`(?:^|/)mvnw(?:\.cmd)?$`),
regexp.MustCompile(`(?:^|/)\.mvn/wrapper/MavenWrapperDownloader\.java$`),
// ----------- Java files -----------
// Gradle
regexp.MustCompile(`(?:^|/)gradlew(?:\.bat)?$`),
regexp.MustCompile(`(?:^|/)gradle\.lockfile$`),
regexp.MustCompile(`(?:^|/)mvnw(?:\.cmd)?$`),
regexp.MustCompile(`(?:^|/)\.mvn/wrapper/MavenWrapperDownloader\.java$`),
// ----------- JavaScript files -----------
// Dependencies and lock files.
regexp.MustCompile(`(?:^|/)node_modules(?:/.*)?$`),
regexp.MustCompile(`(?:^|/)(?:deno\.lock|npm-shrinkwrap\.json|package-lock\.json|pnpm-lock\.yaml|yarn\.lock)$`),
regexp.MustCompile(`(?:^|/)bower_components(?:/.*)?$`),
// TODO: Add more common static assets, such as swagger-ui.
regexp.MustCompile(`(?:^|/)(?:angular|bootstrap|jquery(?:-?ui)?|plotly|swagger-?ui)[a-zA-Z0-9.-]*(?:\.min)?\.js(?:\.map)?$`),
regexp.MustCompile(`(?:^|/)javascript\.json$`),
// ----------- JavaScript files -----------
// Dependencies and lock files.
regexp.MustCompile(`(?:^|/)node_modules(?:/.*)?$`),
regexp.MustCompile(`(?:^|/)(?:deno\.lock|npm-shrinkwrap\.json|package-lock\.json|pnpm-lock\.yaml|yarn\.lock)$`),
regexp.MustCompile(`(?:^|/)bower_components(?:/.*)?$`),
// TODO: Add more common static assets, such as swagger-ui.
regexp.MustCompile(`(?:^|/)(?:angular|bootstrap|jquery(?:-?ui)?|plotly|swagger-?ui)[a-zA-Z0-9.-]*(?:\.min)?\.js(?:\.map)?$`),
regexp.MustCompile(`(?:^|/)javascript\.json$`),
// ----------- Python files -----------
// Dependencies and lock files.
regexp.MustCompile(`(?:^|/)(?:Pipfile|poetry)\.lock$`),
// Virtual environments
regexp.MustCompile(`(?i)(?:^|/)(?:v?env|virtualenv)/lib(?:64)?(?:/.*)?$`),
regexp.MustCompile(`(?i)(?:^|/)(?:lib(?:64)?/python[23](?:\.\d{1,2})+|python/[23](?:\.\d{1,2})+/lib(?:64)?)(?:/.*)?$`),
// dist-info directory (https://py-pkgs.org/04-package-structure.html#building-sdists-and-wheels)
regexp.MustCompile(`(?i)(?:^|/)[a-z0-9_.]+-[0-9.]+\.dist-info(?:/.+)?$`),
// ----------- Python files -----------
// Dependencies and lock files.
regexp.MustCompile(`(?:^|/)(?:Pipfile|poetry)\.lock$`),
// Virtual environments
regexp.MustCompile(`(?i)(?:^|/)(?:v?env|virtualenv)/lib(?:64)?(?:/.*)?$`),
regexp.MustCompile(`(?i)(?:^|/)(?:lib(?:64)?/python[23](?:\.\d{1,2})+|python/[23](?:\.\d{1,2})+/lib(?:64)?)(?:/.*)?$`),
// dist-info directory (https://py-pkgs.org/04-package-structure.html#building-sdists-and-wheels)
regexp.MustCompile(`(?i)(?:^|/)[a-z0-9_.]+-[0-9.]+\.dist-info(?:/.+)?$`),
// ----------- Ruby files -----------
regexp.MustCompile(`(?:^|/)vendor/(?:bundle|ruby)(?:/.*?)?$`),
regexp.MustCompile(`\.gem$`), // tar archive
// ----------- Ruby files -----------
regexp.MustCompile(`(?:^|/)vendor/(?:bundle|ruby)(?:/.*?)?$`),
regexp.MustCompile(`\.gem$`), // tar archive
// Misc
regexp.MustCompile(`verification-metadata\.xml`),
regexp.MustCompile(`Database.refactorlog`),
// regexp.MustCompile(`vendor`),
},
StopWords: []string{
"abcdefghijklmnopqrstuvwxyz", // character range
// ----------- Secrets -----------
// Checkmarx client secret. (https://github.com/checkmarx-ts/checkmarx-python-sdk/blob/86560f6e2a3e46d16322101294da10d5d190312d/README.md?plain=1#L56)
"014df517-39d1-4453-b7b3-9930c563627c",
// Misc
regexp.MustCompile(`verification-metadata\.xml`),
regexp.MustCompile(`Database.refactorlog`),
// ----------- Git files ------------
regexp.MustCompile(`(?:^|/)\.git$`),
},
StopWords: []string{
"abcdefghijklmnopqrstuvwxyz", // character range
// ----------- Secrets -----------
// Checkmarx client secret. (https://github.com/checkmarx-ts/checkmarx-python-sdk/blob/86560f6e2a3e46d16322101294da10d5d190312d/README.md?plain=1#L56)
"014df517-39d1-4453-b7b3-9930c563627c",
},
},
},
}
+32 -16
View File
@@ -75,18 +75,22 @@ var allowlistRegexTests = map[string]struct {
func TestConfigAllowlistRegexes(t *testing.T) {
cfg := CreateGlobalConfig()
allowlist := cfg.Allowlist
allowlists := cfg.Allowlists
for name, cases := range allowlistRegexTests {
t.Run(name, func(t *testing.T) {
for _, c := range cases.invalid {
if !allowlist.RegexAllowed(c) {
t.Errorf("invalid value not marked as allowed: %s", c)
for _, a := range allowlists {
if !a.RegexAllowed(c) {
t.Errorf("invalid value not marked as allowed: %s", c)
}
}
}
for _, c := range cases.valid {
if allowlist.RegexAllowed(c) {
t.Errorf("valid value marked as allowed: %s", c)
for _, a := range allowlists {
if a.RegexAllowed(c) {
t.Errorf("valid value marked as allowed: %s", c)
}
}
}
})
@@ -95,15 +99,19 @@ func TestConfigAllowlistRegexes(t *testing.T) {
func BenchmarkConfigAllowlistRegexes(b *testing.B) {
cfg := CreateGlobalConfig()
allowlist := cfg.Allowlist
allowlists := cfg.Allowlists
for n := 0; n < b.N; n++ {
for _, cases := range allowlistRegexTests {
for _, c := range cases.invalid {
allowlist.RegexAllowed(c)
for _, a := range allowlists {
a.RegexAllowed(c)
}
}
for _, c := range cases.valid {
allowlist.RegexAllowed(c)
for _, a := range allowlists {
a.RegexAllowed(c)
}
}
}
}
@@ -152,18 +160,22 @@ var allowlistPathsTests = map[string]struct {
func TestConfigAllowlistPaths(t *testing.T) {
cfg := CreateGlobalConfig()
allowlist := cfg.Allowlist
allowlists := cfg.Allowlists
for name, cases := range allowlistPathsTests {
t.Run(name, func(t *testing.T) {
for _, c := range cases.invalid {
if !allowlist.PathAllowed(c) {
t.Errorf("invalid path not marked as allowed: %s", c)
for _, a := range allowlists {
if !a.PathAllowed(c) {
t.Errorf("invalid path not marked as allowed: %s", c)
}
}
}
for _, c := range cases.valid {
if allowlist.PathAllowed(c) {
t.Errorf("valid path marked as allowed: %s", c)
for _, a := range allowlists {
if a.PathAllowed(c) {
t.Errorf("valid path marked as allowed: %s", c)
}
}
}
})
@@ -172,15 +184,19 @@ func TestConfigAllowlistPaths(t *testing.T) {
func BenchmarkConfigAllowlistPaths(b *testing.B) {
cfg := CreateGlobalConfig()
allowlist := cfg.Allowlist
allowlists := cfg.Allowlists
for n := 0; n < b.N; n++ {
for _, cases := range allowlistPathsTests {
for _, c := range cases.invalid {
allowlist.PathAllowed(c)
for _, a := range allowlists {
a.PathAllowed(c)
}
}
for _, c := range cases.valid {
allowlist.PathAllowed(c)
for _, a := range allowlists {
a.PathAllowed(c)
}
}
}
}
+38 -3
View File
@@ -2,6 +2,7 @@ package main
import (
"os"
"slices"
"text/template"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/base"
@@ -18,21 +19,29 @@ const (
func main() {
if len(os.Args) < 2 {
os.Stderr.WriteString("Specify path to the gitleaks.toml config\n")
_, _ = os.Stderr.WriteString("Specify path to the gitleaks.toml config\n")
os.Exit(2)
}
gitleaksConfigPath := os.Args[1]
configRules := []*config.Rule{
rules.OnePasswordSecretKey(),
rules.OnePasswordServiceAccountToken(),
rules.AdafruitAPIKey(),
rules.AdobeClientID(),
rules.AdobeClientSecret(),
rules.AgeSecretKey(),
rules.Airtable(),
rules.AirtableApiKey(),
rules.AirtablePersonalAccessToken(),
rules.AlgoliaApiKey(),
rules.AlibabaAccessKey(),
rules.AlibabaSecretKey(),
rules.AmazonBedrockAPIKeyLongLived(),
rules.AmazonBedrockAPIKeyShortLived(),
rules.AnthropicAdminApiKey(),
rules.AnthropicApiKey(),
rules.ArtifactoryApiKey(),
rules.ArtifactoryReferenceToken(),
rules.AsanaClientID(),
rules.AsanaClientSecret(),
rules.Atlassian(),
@@ -46,6 +55,7 @@ func main() {
rules.Beamer(),
rules.CodecovAccessToken(),
rules.CoinbaseAccessToken(),
rules.ClickHouseCloud(),
rules.Clojars(),
rules.CloudflareAPIKey(),
rules.CloudflareGlobalAPIKey(),
@@ -122,6 +132,7 @@ func main() {
rules.HashiCorpTerraform(),
rules.HashicorpField(),
rules.Heroku(),
rules.HerokuV2(),
rules.HubSpot(),
rules.HuggingFaceAccessToken(),
rules.HuggingFaceOrganizationApiToken(),
@@ -142,6 +153,8 @@ func main() {
rules.LinkedinClientSecret(),
rules.LobAPIToken(),
rules.LobPubAPIToken(),
rules.LookerClientID(),
rules.LookerClientSecret(),
rules.MailChimp(),
rules.MailGunPubAPIToken(),
rules.MailGunPrivateAPIToken(),
@@ -157,6 +170,7 @@ func main() {
rules.NewRelicUserKey(),
rules.NewRelicBrowserAPIKey(),
rules.NewRelicInsertKey(),
rules.Notion(),
rules.NPM(),
rules.NugetConfigPassword(),
rules.NytimesAccessToken(),
@@ -164,6 +178,7 @@ func main() {
rules.OktaAccessToken(),
rules.OpenAI(),
rules.OpenshiftUserToken(),
rules.PerplexityAPIKey(),
rules.PlaidAccessID(),
rules.PlaidSecretKey(),
rules.PlaidAccessToken(),
@@ -239,13 +254,28 @@ func main() {
// ensure rules have unique ids
ruleLookUp := make(map[string]config.Rule, len(configRules))
for _, rule := range configRules {
if err := rule.Validate(); err != nil {
logging.Fatal().Err(err).
Str("rule-id", rule.RuleID).
Msg("Failed to validate rule")
}
// check if rule is in ruleLookUp
if _, ok := ruleLookUp[rule.RuleID]; ok {
logging.Fatal().Msgf("rule id %s is not unique", rule.RuleID)
logging.Fatal().
Str("rule-id", rule.RuleID).
Msg("rule id is not unique")
}
// TODO: eventually change all the signatures to get ride of this
// nasty dereferencing.
ruleLookUp[rule.RuleID] = *rule
// Slices are de-duplicated with a map, every iteration has a different order.
// This is an awkward workaround.
for _, allowlist := range rule.Allowlists {
slices.Sort(allowlist.Commits)
slices.Sort(allowlist.StopWords)
}
}
tmpl, err := template.ParseFiles(templatePath)
@@ -257,9 +287,14 @@ func main() {
if err != nil {
logging.Fatal().Err(err).Msg("Failed to create rules.toml")
}
defer f.Close()
cfg := base.CreateGlobalConfig()
cfg.Rules = ruleLookUp
for _, allowlist := range cfg.Allowlists {
slices.Sort(allowlist.Commits)
slices.Sort(allowlist.StopWords)
}
if err = tmpl.Execute(f, cfg); err != nil {
logging.Fatal().Err(err).Msg("could not execute template")
}
+40 -1
View File
@@ -33,10 +33,49 @@ export OP_SERVICE_ACCOUNT_TOKEN=ops_eyJzaWduSW5BZGRyZXNzIjoibXkuMXBhc3N3b3JkLmNv
serviceAccountToken:
fn::secret: ops_eyJzaWduSW5B..[Redacted]`,
`: To start using this service account, run the following command:
:
:
: export OP_SERVICE_ACCOUNT_TOKEN=ops_eyJzaWduSW5BZGRyZXNzIjoiaHR0cHM6...`,
// Low entropy.
`ops_eyJxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`,
}
return utils.Validate(r, tps, fps)
}
// Reference:
// - https://1passwordstatic.com/files/security/1password-white-paper.pdf
func OnePasswordSecretKey() *config.Rule {
// 1Password secret keys include several hyphens but these are only for readability
// and are stripped during 1Password login. This means that the following are technically
// the same valid key:
// - A3ASWWYB798JRYLJVD423DC286TVMH43EB
// - A-3-A-S-W-W-Y-B-7-9-8-J-R-Y-L-J-V-D-4-2-3-D-C-2-8-6-T-V-M-H-4-3-E-B
// But in practice, when these keys are added to a vault, exported in an emergency kit, or
// copied, they have hyphens that follow one of two patterns I can find:
// - A3-ASWWYB-798JRY-LJVD4-23DC2-86TVM-H43EB (every key I've generated has this pattern)
// - A3-ASWWYB-798JRYLJVD4-23DC2-86TVM-H43EB (the whitepaper includes this example, which could just be a typo)
// To avoid a complicated regex that checks for every possible situation it's probably best
// to scan for the these two patterns.
r := config.Rule{
Description: "Uncovered a possible 1Password secret key, potentially compromising access to secrets in vaults.",
RuleID: "1password-secret-key",
Regex: regexp.MustCompile(`\bA3-[A-Z0-9]{6}-(?:(?:[A-Z0-9]{11})|(?:[A-Z0-9]{6}-[A-Z0-9]{5}))-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}\b`),
Entropy: 3.8,
Keywords: []string{"A3-"},
}
// validate
tps := utils.GenerateSampleSecrets("1password", secrets.NewSecret(`A3-[A-Z0-9]{6}-[A-Z0-9]{11}-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}`))
tps = append(tps, utils.GenerateSampleSecrets("1password", secrets.NewSecret(`A3-[A-Z0-9]{6}-[A-Z0-9]{6}-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}`))...)
tps = append(tps,
// from whitepaper
`A3-ASWWYB-798JRYLJVD4-23DC2-86TVM-H43EB`,
`A3-ASWWYB-798JRY-LJVD4-23DC2-86TVM-H43EB`,
)
fps := []string{
// low entropy
`A3-XXXXXX-XXXXXXXXXXX-XXXXX-XXXXX-XXXXX`,
// lowercase
`A3-xXXXXX-XXXXXX-XXXXX-XXXXX-XXXXX-XXXXX`,
}
return utils.Validate(r, tps, fps)
}
+17 -1
View File
@@ -1,12 +1,14 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Airtable() *config.Rule {
func AirtableApiKey() *config.Rule {
// define rule
r := config.Rule{
Description: "Uncovered a possible Airtable API Key, potentially compromising database access and leading to data leakage or alteration.",
@@ -19,3 +21,17 @@ func Airtable() *config.Rule {
tps := utils.GenerateSampleSecrets("airtable", secrets.NewSecret(utils.AlphaNumeric("17")))
return utils.Validate(r, tps, nil)
}
func AirtablePersonalAccessToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Uncovered a possible Airtable Personal AccessToken, potentially compromising database access and leading to data leakage or alteration.",
RuleID: "airtable-personnal-access-token",
Regex: regexp.MustCompile(`\b(pat[[:alnum:]]{14}\.[a-f0-9]{64})\b`),
Keywords: []string{"airtable"},
}
// validate
tps := utils.GenerateSampleSecrets("airtable", "pat"+secrets.NewSecret(utils.AlphaNumeric("14")+"\\."+utils.Hex("64")))
return utils.Validate(r, tps, nil)
}
+69
View File
@@ -0,0 +1,69 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func AnthropicApiKey() *config.Rule {
// define rule
r := config.Rule{
RuleID: "anthropic-api-key",
Description: "Identified an Anthropic API Key, which may compromise AI assistant integrations and expose sensitive data to unauthorized access.",
Regex: utils.GenerateUniqueTokenRegex(`sk-ant-api03-[a-zA-Z0-9_\-]{93}AA`, false),
Keywords: []string{
"sk-ant-api03",
},
}
// validate
tps := []string{
// Valid API key example
"sk-ant-api03-abc123xyz-456def789ghij-klmnopqrstuvwx-3456yza789bcde-1234fghijklmnopby56aaaogaopaaaabc123xyzAA",
// Generate additional random test keys
utils.GenerateSampleSecret("anthropic", "sk-ant-api03-"+secrets.NewSecret(utils.AlphaNumericExtendedShort("93"))+"AA"),
}
fps := []string{
// Too short key (missing characters)
"sk-ant-api03-abc123xyz-456de-klMnopqrstuvwx-3456yza789bcde-1234fghijklmnopAA",
// Wrong suffix
"sk-ant-api03-abc123xyz-456def789ghij-klmnopqrstuvwx-3456yza789bcde-1234fghijklmnopby56aaaogaopaaaabc123xyzBB",
// Wrong prefix (admin key, not API key)
"sk-ant-admin01-abc123xyz-456def789ghij-klmnopqrstuvwx-3456yza789bcde-1234fghijklmnopby56aaaogaopaaaabc123xyzAA",
}
return utils.Validate(r, tps, fps)
}
func AnthropicAdminApiKey() *config.Rule {
// define rule
r := config.Rule{
RuleID: "anthropic-admin-api-key",
Description: "Detected an Anthropic Admin API Key, risking unauthorized access to administrative functions and sensitive AI model configurations.",
Regex: utils.GenerateUniqueTokenRegex(`sk-ant-admin01-[a-zA-Z0-9_\-]{93}AA`, false),
Keywords: []string{
"sk-ant-admin01",
},
}
// validate
tps := []string{
// Valid admin key example
"sk-ant-admin01-abc12fake-456def789ghij-klmnopqrstuvwx-3456yza789bcde-12fakehijklmnopby56aaaogaopaaaabc123xyzAA",
// Generate additional random test keys
utils.GenerateSampleSecret("anthropic", "sk-ant-admin01-"+secrets.NewSecret(utils.AlphaNumericExtendedShort("93"))+"AA"),
}
fps := []string{
// Too short key (missing characters)
"sk-ant-admin01-abc123xyz-456de-klMnopqrstuvwx-3456yza789bcde-1234fghijklmnopAA",
// Wrong suffix
"sk-ant-admin01-abc123xyz-456def789ghij-klmnopqrstuvwx-3456yza789bcde-1234fghijklmnopby56aaaogaopaaaabc123xyzBB",
// Wrong prefix (API key, not admin key)
"sk-ant-api03-abc123xyz-456def789ghij-klmnopqrstuvwx-3456yza789bcde-1234fghijklmnopby56aaaogaopaaaabc123xyzAA",
}
return utils.Validate(r, tps, fps)
}
+58
View File
@@ -0,0 +1,58 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/regexp"
)
func ArtifactoryApiKey() *config.Rule {
// define rule
r := config.Rule{
RuleID: "artifactory-api-key",
Description: "Detected an Artifactory api key, posing a risk unauthorized access to the central repository.",
Regex: regexp.MustCompile(`\bAKCp[A-Za-z0-9]{69}\b`),
Entropy: 4.5,
Keywords: []string{"AKCp"},
}
// validate
tps := []string{
"artifactoryApiKey := \"AKCp" + secrets.NewSecret(utils.AlphaNumeric("69")) + "\"",
}
// false positives
fps := []string{
`lowEntropy := AKCpXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`,
"wrongStart := \"AkCp" + secrets.NewSecret(utils.AlphaNumeric("69")) + "\"",
"wrongLength := \"AkCp" + secrets.NewSecret(utils.AlphaNumeric("59")) + "\"",
"partOfAlongUnrelatedBlob gYnkgAkCp" + secrets.NewSecret(utils.AlphaNumeric("69")) + "VyZSB2",
}
return utils.Validate(r, tps, fps)
}
func ArtifactoryReferenceToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "artifactory-reference-token",
Description: "Detected an Artifactory reference token, posing a risk of impersonation and unauthorized access to the central repository.",
Regex: regexp.MustCompile(`\bcmVmd[A-Za-z0-9]{59}\b`),
Entropy: 4.5,
Keywords: []string{"cmVmd"},
}
// validate
tps := []string{
"artifactoryRefToken := \"cmVmd" + secrets.NewSecret(utils.AlphaNumeric("59")) + "\"",
}
// false positives
fps := []string{
`lowEntropy := cmVmdXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`,
"wrongStart := \"cmVMd" + secrets.NewSecret(utils.AlphaNumeric("59")) + "\"",
"wrongLength := \"cmVmd" + secrets.NewSecret(utils.AlphaNumeric("49")) + "\"",
"partOfAlongUnrelatedBlob gYnkgcmVmd" + secrets.NewSecret(utils.AlphaNumeric("59")) + "VyZSB2",
}
return utils.Validate(r, tps, fps)
}
+10 -7
View File
@@ -13,9 +13,9 @@ func Atlassian() *config.Rule {
RuleID: "atlassian-api-token",
Regex: utils.MergeRegexps(
utils.GenerateSemiGenericRegex(
[]string{"atlassian", "confluence", "jira"},
`[a-zA-Z0-9]{24}`,
false,
[]string{"(?-i:ATLASSIAN|[Aa]tlassian)", "(?-i:CONFLUENCE|[Cc]onfluence)", "(?-i:JIRA|[Jj]ira)"},
`[a-z0-9]{20}[a-f0-9]{4}`, // The last 4 characters are an MD5 hash.
true,
),
utils.GenerateUniqueTokenRegex(`ATATT3[A-Za-z0-9_\-=]{186}`, false),
),
@@ -24,10 +24,13 @@ func Atlassian() *config.Rule {
}
// validate
tps := utils.GenerateSampleSecrets("atlassian", secrets.NewSecret(utils.AlphaNumeric("24")))
tps = append(tps, utils.GenerateSampleSecrets("confluence", secrets.NewSecret(utils.AlphaNumeric("24")))...)
tps = append(tps, utils.GenerateSampleSecrets("jira", secrets.NewSecret(utils.AlphaNumeric("24")))...)
tps := utils.GenerateSampleSecrets("atlassian", secrets.NewSecret(utils.AlphaNumeric("20")+"[a-f0-9]{4}"))
tps = append(tps, utils.GenerateSampleSecrets("confluence", secrets.NewSecret(utils.AlphaNumeric("20")+"[a-f0-9]{4}"))...)
tps = append(tps, utils.GenerateSampleSecrets("jira", secrets.NewSecret(utils.AlphaNumeric("20")+"[a-f0-9]{4}"))...)
tps = append(tps, `JIRA_API_TOKEN=HXe8DGg1iJd2AopzyxkFB7F2`)
tps = append(tps, utils.GenerateSampleSecrets("jira", "ATATT3xFfGF0K3irG5tKKi-6u-wwaXQFeGwZ-IHR-hQ3CulkKtMSuteRQFfLZ6jihHThzZCg_UjnDt-4Wl_gIRf4zrZJs5JqaeuBhsfJ4W5GD6yGg3W7903gbvaxZPBjxIQQ7BgFDSkPS8oPispw4KLz56mdK-G6CIvLO6hHRrZHY0Q3tvJ6JxE=C63992E6")...)
return utils.Validate(r, tps, nil)
fps := []string{"getPagesInConfluenceSpace,searchConfluenceUsingCql"}
return utils.Validate(r, tps, fps)
}
+62 -2
View File
@@ -12,7 +12,7 @@ func AWS() *config.Rule {
r := config.Rule{
RuleID: "aws-access-token",
Description: "Identified a pattern that may indicate AWS credentials, risking unauthorized cloud resource access and data breaches on AWS platforms.",
Regex: regexp.MustCompile(`\b((?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16})\b`),
Regex: regexp.MustCompile(`\b((?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z2-7]{16})\b`),
Entropy: 3,
Keywords: []string{
// https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids
@@ -22,7 +22,7 @@ func AWS() *config.Rule {
"ABIA", // AWS STS service bearer token
"ACCA", // Context-specific credential
},
Allowlists: []config.Allowlist{
Allowlists: []*config.Allowlist{
{
Regexes: []*regexp.Regexp{
regexp.MustCompile(`.+EXAMPLE$`),
@@ -47,3 +47,63 @@ func AWS() *config.Rule {
}
return utils.Validate(r, tps, fps)
}
func AmazonBedrockAPIKeyLongLived() *config.Rule {
// https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys-how.html
// https://medium.com/@adan.alvarez/api-keys-for-bedrock-a-brief-security-overview-2133ed9a2b3f
r := config.Rule{
RuleID: "aws-amazon-bedrock-api-key-long-lived",
Description: "Identified a pattern that may indicate long-lived Amazon Bedrock API keys, risking unauthorized Amazon Bedrock usage",
Regex: utils.GenerateUniqueTokenRegex(`ABSK[A-Za-z0-9+/]{109,269}={0,2}`, false),
Entropy: 3,
Keywords: []string{
"ABSK", // Amazon Bedrock API Key (long-lived)
},
}
// validate
tps := []string{
// Valid API key example
"ABSKQmVkcm9ja0FQSUtleS1EXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXM=",
// Generate additional random test keys
utils.GenerateSampleSecret("bedrock", "ABSKQmVkcm9ja0FQSUtleS1"+secrets.NewSecret(utils.AlphaNumeric("108"))+"="),
utils.GenerateSampleSecret("bedrock", "ABSKQmVkcm9ja0FQSUtleS1"+secrets.NewSecret(utils.AlphaNumeric("246"))),
}
fps := []string{
// Too short key (missing characters)
"ABSKQmVkcm9ja0FQSUtleS1EXAMPLE",
// Too long
"ABSKQmVkcm9ja0FQSUtleS1EXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLE=",
// Wrong prefix
"AXSKQmVkcm9ja0FQSUtleS1EXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXM=",
}
return utils.Validate(r, tps, fps)
}
func AmazonBedrockAPIKeyShortLived() *config.Rule {
// https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys-how.html
// https://github.com/aws/aws-bedrock-token-generator-js/blob/86277e1489354192c64ffc8f995601daacc1f715/src/token.ts#L21
r := config.Rule{
RuleID: "aws-amazon-bedrock-api-key-short-lived",
Description: "Identified a pattern that may indicate short-lived Amazon Bedrock API keys, risking unauthorized Amazon Bedrock usage",
Regex: regexp.MustCompile(`bedrock-api-key-YmVkcm9jay5hbWF6b25hd3MuY29t`),
Entropy: 3,
Keywords: []string{
"bedrock-api-key-", // Amazon Bedrock API Key (short lived)
},
}
// validate
tps := utils.GenerateSampleSecrets("AmazonBedrockAPIKeyShortLived", `bedrock-api-key-YmVkcm9jay5hbWF6b25hd3MuY29t`)
fps := []string{
// Too short key (missing characters)
"bedrock-api-key-",
// Wrong prefix
"bedrock-api-key-YmVkcm9jay5hbWF6b25hd3MuY29x",
}
return utils.Validate(r, tps, fps)
}
+30
View File
@@ -0,0 +1,30 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/regexp"
)
func ClickHouseCloud() *config.Rule {
// define rule
r := config.Rule{
RuleID: "clickhouse-cloud-api-secret-key",
Description: "Identified a pattern that may indicate clickhouse cloud API secret key, risking unauthorized clickhouse cloud api access and data breaches on ClickHouse Cloud platforms.",
Regex: regexp.MustCompile(`\b(4b1d[A-Za-z0-9]{38})\b`),
Entropy: 3,
Keywords: []string{
"4b1d", // Prefix
},
}
// validate
tps := utils.GenerateSampleSecrets("ClickHouse", "4b1dbRdW3rOcB7xLthrM4BTBGK1qPLkHigpN1bXD6z")
tps = append(tps, utils.GenerateSampleSecrets("ClickHouse", "4b1d"+secrets.NewSecret("[A-Za-z0-9]{38}"))...)
fps := []string{
`key = 4b1dXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`, // Low entropy
`key = adf4b1dbRdW3rOcB7xLthrM4BTBGK1qPLkHigpN1bXD6z`, // Not start of a word
}
return utils.Validate(r, tps, fps)
}
+18 -11
View File
@@ -13,21 +13,27 @@
title = "{{.Title}}"
[allowlist]
description = "{{.Allowlist.Description}}"
{{- with .Allowlist.RegexTarget }}
regexTarget = "{{ . }}"{{ end -}}
{{- with .Allowlist.Regexes }}
regexes = [{{ range $i, $regex := . }}
'''{{ $regex }}''',{{ end }}
# minVersion indicates the minimum Gitleaks version required to use this config.
# If the running version is older, a warning will be logged and not all
# config-enabled features are guaranteed to work.
minVersion = "v8.25.0"
{{ with .Allowlists }}{{ range $i, $allowlist := . }}{{ if or $allowlist.Regexes $allowlist.Paths $allowlist.Commits $allowlist.StopWords }}# TODO: change to [[allowlists]]{{println}}[allowlist]
{{- with .Description }}{{println}}description = "{{ . }}"{{ end }}
{{- with .MatchCondition }}{{println}}condition = "{{ .String }}"{{ end }}
{{- with .Commits -}}{{println}}commits = [
{{ range $j, $commit := . }}"{{ $commit }}",{{ end }}
]{{ end }}
{{- with .Allowlist.Paths }}
paths = [{{ range $i, $path := . }}
{{- with .Paths }}{{println}}paths = [{{ range $j, $path := . }}
'''{{ $path }}''',{{ end }}
]{{ end }}
{{- with .Allowlist.StopWords }}{{println}}stopwords = [{{ range $j, $stopword := . }}
{{- if and .RegexTarget .Regexes }}{{println}}regexTarget = "{{ .RegexTarget }}"{{ end -}}
{{- with .Regexes }}{{println}}regexes = [{{ range $i, $regex := . }}
'''{{ $regex }}''',{{ end }}
]{{ end }}
{{- with .StopWords }}{{println}}stopwords = [{{ range $j, $stopword := . }}
"{{ $stopword }}",{{ end }}
]{{ end }}{{println}}
]{{ end }}{{ end }}{{ end }}{{ end }}{{println}}
{{- range $i, $rule := .Rules }}{{println}}[[rules]]
id = "{{$rule.RuleID}}"
@@ -51,6 +57,7 @@ tags = [
{{ range $j, $tag := . }}"{{ $tag }}",{{ end }}
]{{ end }}
{{- with $rule.Allowlists }}{{ range $i, $allowlist := . }}{{ if or $allowlist.Regexes $allowlist.Paths $allowlist.Commits $allowlist.StopWords }}{{println}}[[rules.allowlists]]
{{- with .Description }}{{println}}description = "{{ . }}"{{ end }}
{{- with .MatchCondition }}{{println}}condition = "{{ .String }}"{{ end }}
{{- with .Commits -}}{{println}}commits = [
{{ range $j, $commit := . }}"{{ $commit }}",{{ end }}
+2 -2
View File
@@ -16,7 +16,7 @@ func CurlBasicAuth() *config.Rule {
Regex: regexp.MustCompile(`\bcurl\b(?:.*|.*(?:[\r\n]{1,2}.*){1,5})[ \t\n\r](?:-u|--user)(?:=|[ \t]{0,5})("(:[^"]{3,}|[^:"]{3,}:|[^:"]{3,}:[^"]{3,})"|'([^:']{3,}:[^']{3,})'|((?:"[^"]{3,}"|'[^']{3,}'|[\w$@.-]+):(?:"[^"]{3,}"|'[^']{3,}'|[\w${}@.-]+)))(?:\s|\z)`),
Keywords: []string{"curl"},
Entropy: 2,
Allowlists: []config.Allowlist{
Allowlists: []*config.Allowlist{
{
Regexes: []*regexp.Regexp{
regexp.MustCompile(`[^:]+:(?:change(?:it|me)|pass(?:word)?|pwd|test|token|\*+|x+)`), // common placeholder passwords
@@ -109,7 +109,7 @@ func CurlHeaderAuth() *config.Rule {
fmt.Sprintf(`\bcurl\b(?:.*?|.*?(?:[\r\n]{1,2}.*?){1,5})[ \t\n\r](?:-H|--header)(?:=|[ \t]{0,5})(?:"%s"|'%s')(?:\B|\s|\z)`, authPat, authPat)),
Entropy: 2.75,
Keywords: []string{"curl"},
//Allowlists: []config.Allowlist{
//Allowlists: []*config.Allowlist{
// {
// Regexes: []*regexp.Regexp{},
// },
+3 -5
View File
@@ -30,11 +30,9 @@ func GCPAPIKey() *config.Rule {
RuleID: "gcp-api-key",
Description: "Uncovered a GCP API key, which could lead to unauthorized access to Google Cloud services and data breaches.",
Regex: utils.GenerateUniqueTokenRegex(`AIza[\w-]{35}`, false),
Entropy: 3.0,
Keywords: []string{
"AIza",
},
Allowlists: []config.Allowlist{
Entropy: 4,
Keywords: []string{"AIza"},
Allowlists: []*config.Allowlist{
{
Regexes: []*regexp.Regexp{
// example keys from https://github.com/firebase/firebase-android-sdk
+3 -3
View File
@@ -36,7 +36,7 @@ func GenericCredential() *config.Rule {
"token",
},
Entropy: 3.5,
Allowlists: []config.Allowlist{
Allowlists: []*config.Allowlist{
{
// 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 ensure the secret contains both numbers and alphabetical characters, not just alphabetical characters.
@@ -79,7 +79,7 @@ func GenericCredential() *config.Rule {
// Token
`|(?:csrf)[_.-]?token` +
`|(?:io\.jsonwebtoken[ \t]?:[ \t]?[\w-]+)` + // Maven library coordinats. (e.g., https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt)
`|(?:io\.jsonwebtoken[ \t]?:[ \t]?[\w-]+)` + // Maven library coordinates. (e.g., https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt)
// General
`|(?:api|credentials|token)[_.-]?(?:endpoint|ur[il])` +
@@ -281,7 +281,7 @@ jdbc.snowflake.url=`,
}
func newPlausibleSecret(regex string) string {
allowList := config.Allowlist{StopWords: DefaultStopWords}
allowList := &config.Allowlist{StopWords: DefaultStopWords}
// attempt to generate a random secret,
// retrying until it contains at least one digit and no stop words
// TODO: currently the DefaultStopWords list contains many short words,
+1 -1
View File
@@ -7,7 +7,7 @@ import (
"github.com/zricethezav/gitleaks/v8/regexp"
)
var githubAllowlist = []config.Allowlist{
var githubAllowlist = []*config.Allowlist{
{
Paths: []*regexp.Regexp{
// https://github.com/octokit/auth-token.js/?tab=readme-ov-file#createtokenauthtoken-options
+1 -1
View File
@@ -15,7 +15,7 @@ func VaultServiceToken() *config.Rule {
Regex: utils.GenerateUniqueTokenRegex(`(?:hvs\.[\w-]{90,120}|s\.(?i:[a-z0-9]{24}))`, false),
Entropy: 3.5,
Keywords: []string{"hvs.", "s."},
Allowlists: []config.Allowlist{
Allowlists: []*config.Allowlist{
{
Regexes: []*regexp.Regexp{
// https://github.com/gitleaks/gitleaks/issues/1490#issuecomment-2334166357
+19
View File
@@ -24,3 +24,22 @@ func Heroku() *config.Rule {
)
return utils.Validate(r, tps, nil)
}
func HerokuV2() *config.Rule {
// define rule
r := config.Rule{
Description: "Detected a Heroku API Key, potentially compromising cloud application deployments and operational security.",
RuleID: "heroku-api-key-v2",
Regex: utils.GenerateUniqueTokenRegex(`(HRKU-AA[0-9a-zA-Z_-]{58})`, false),
Entropy: 4,
Keywords: []string{"HRKU-AA"},
}
// validate
tps := utils.GenerateSampleSecrets("heroku", secrets.NewSecret(`\b(HRKU-AA[0-9a-zA-Z_-]{58})\b`))
tps = append(tps,
`const KEY = "HRKU-AAlQ1aVoHDujJ9QsDHdHlHO0hbzhoERRSO45ZQusSYHg_____w4_hLrAym_u""`,
`API_Key = "HRKU-AAy9Ppr_HD2pPuTyIiTYInO0hbzhoERRSO93ZQusSYHgaD7_WQ07FnF7L9FX"`,
)
return utils.Validate(r, tps, nil)
}
+4 -4
View File
@@ -17,7 +17,7 @@ func KubernetesSecret() *config.Rule {
// - valid base64 characters
// - longer than 10 characters (no "YmFyCg==")
//language=regexp
dataPat := `\bdata:(?:.|\s){0,100}?\s+([\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:["']?[a-z0-9+/]{10,}={0,3}["']?|\{\{[ \t\w"|$:=,.-]+}}|""|''))`
dataPat := `\bdata:(?s:.){0,100}?\s+([\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:["']?[a-z0-9+/]{10,}={0,3}["']?|\{\{[ \t\w"|$:=,.-]+}}|""|''))`
// define rule
r := config.Rule{
@@ -25,13 +25,13 @@ func KubernetesSecret() *config.Rule {
Description: "Possible Kubernetes Secret detected, posing a risk of leaking credentials/tokens from your deployments",
Regex: regexp.MustCompile(fmt.Sprintf(
//language=regexp
`(?i)(?:%s(?:.|\s){0,200}?%s|%s(?:.|\s){0,200}?%s)`, kindPat, dataPat, dataPat, kindPat)),
`(?i)(?:%s(?s:.){0,200}?%s|%s(?s:.){0,200}?%s)`, kindPat, dataPat, dataPat, kindPat)),
Keywords: []string{
"secret",
},
// Kubernetes secrets are usually yaml files.
Path: regexp.MustCompile(`(?i)\.ya?ml$`),
Allowlists: []config.Allowlist{
Allowlists: []*config.Allowlist{
{
Regexes: []*regexp.Regexp{
// Ignore empty or placeholder values.
@@ -45,7 +45,7 @@ func KubernetesSecret() *config.Rule {
// Avoid overreach between directives.
RegexTarget: "match",
Regexes: []*regexp.Regexp{
regexp.MustCompile(`(kind:(?:.|\s)+\n---\n(?:.|\s)+\bdata:|data:(?:.|\s)+\n---\n(?:.|\s)+\bkind:)`),
regexp.MustCompile(`(kind:(?s:.)+\n---\n(?s:.)+\bdata:|data:(?s:.)+\n---\n(?s:.)+\bkind:)`),
},
},
},
+35
View File
@@ -0,0 +1,35 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func LookerClientID() *config.Rule {
// define rule
r := config.Rule{
Description: "Found a Looker Client ID, risking unauthorized access to a Looker account and exposing sensitive data.",
RuleID: "looker-client-id",
Regex: utils.GenerateSemiGenericRegex([]string{"looker"}, utils.AlphaNumeric("20"), true),
Keywords: []string{"looker"},
}
// validate
tps := utils.GenerateSampleSecrets("looker", secrets.NewSecret(utils.AlphaNumeric("20")))
return utils.Validate(r, tps, nil)
}
func LookerClientSecret() *config.Rule {
// define rule
r := config.Rule{
Description: "Found a Looker Client Secret, risking unauthorized access to a Looker account and exposing sensitive data.",
RuleID: "looker-client-secret",
Regex: utils.GenerateSemiGenericRegex([]string{"looker"}, utils.AlphaNumeric("24"), true),
Keywords: []string{"looker"},
}
// validate
tps := utils.GenerateSampleSecrets("looker", secrets.NewSecret(utils.AlphaNumeric("24")))
return utils.Validate(r, tps, nil)
}
+39
View File
@@ -0,0 +1,39 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/config"
)
func Notion() *config.Rule {
// Define the identifiers that match the Keywords
identifiers := []string{"ntn_"}
// Define the regex pattern for Notion API token
secretRegex := `ntn_[0-9]{11}[A-Za-z0-9]{32}[A-Za-z0-9]{3}`
regex := utils.GenerateUniqueTokenRegex(secretRegex, false)
r := config.Rule{
Description: "Notion API token",
RuleID: "notion-api-token",
Regex: regex,
Entropy: 4,
Keywords: identifiers,
}
// validate
tps := []string{
"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",
"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",
"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",
}
fps := []string{
"ntn_12345678901",
"ntn_123456789012345678901234567890123456789012345678901234567890",
"ntn_12345678901abc",
}
return utils.Validate(r, tps, fps)
}
+1 -1
View File
@@ -14,7 +14,7 @@ func NugetConfigPassword() *config.Rule {
Path: regexp.MustCompile(`(?i)nuget\.config$`),
Keywords: []string{"<add key="},
Entropy: 1,
Allowlists: []config.Allowlist{
Allowlists: []*config.Allowlist{
{
Regexes: []*regexp.Regexp{
// samples from https://learn.microsoft.com/en-us/nuget/reference/nuget-config-file
+27
View File
@@ -0,0 +1,27 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/config"
)
func PerplexityAPIKey() *config.Rule {
// Define Rule
r := config.Rule{
RuleID: "perplexity-api-key",
Description: "Detected a Perplexity API key, which could lead to unauthorized access to Perplexity AI services and data exposure.",
Regex: regexp.MustCompile(`\b(pplx-[a-zA-Z0-9]{48})(?:[\x60'"\s;]|\\[nr]|$|\b)`),
Keywords: []string{"pplx-"},
Entropy: 4.0,
}
// validate
tps := utils.GenerateSampleSecrets("perplexity", "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'")
fps := []string{
"PERPLEXITY_API_KEY=pplx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
}
return utils.Validate(r, tps, fps)
}
+2 -4
View File
@@ -1,8 +1,6 @@
package rules
import (
"fmt"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
@@ -50,7 +48,7 @@ func PlaidAccessToken() *config.Rule {
RuleID: "plaid-api-token",
Description: "Discovered a Plaid API Token, potentially compromising financial data aggregation and banking services.",
Regex: utils.GenerateSemiGenericRegex([]string{"plaid"},
fmt.Sprintf("access-(?:sandbox|development|production)-%s", utils.Hex8_4_4_4_12()), true),
"access-(?:sandbox|development|production)-"+utils.Hex8_4_4_4_12(), true),
Keywords: []string{
"plaid",
@@ -58,6 +56,6 @@ func PlaidAccessToken() *config.Rule {
}
// validate
tps := utils.GenerateSampleSecrets("plaid", secrets.NewSecret(fmt.Sprintf("access-(?:sandbox|development|production)-%s", utils.Hex8_4_4_4_12())))
tps := utils.GenerateSampleSecrets("plaid", secrets.NewSecret("access-(?:sandbox|development|production)-"+utils.Hex8_4_4_4_12()))
return utils.Validate(r, tps, nil)
}
+10 -6
View File
@@ -10,18 +10,22 @@ func Sonar() *config.Rule {
r := config.Rule{
Description: "Uncovered a Sonar API token, potentially compromising software vulnerability scanning and code security.",
RuleID: "sonar-api-token",
Regex: utils.GenerateSemiGenericRegex([]string{"sonar[_.-]?(login|token)"}, utils.AlphaNumericExtended("40"), true),
Regex: utils.GenerateSemiGenericRegex([]string{"sonar[_.-]?(login|token)"}, "(?:squ_|sqp_|sqa_)?"+utils.AlphaNumericExtended("40"), true),
Keywords: []string{"sonar"},
SecretGroup: 2,
}
// validate
tps := utils.GenerateSampleSecrets("sonar", "12345678ABCDEFH1234567890ABCDEFH12345678")
tps = append(tps,
`const SONAR_LOGIN = "12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
`SONAR_LOGIN := "12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
`SONAR.LOGIN ::= "12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
`SONAR.LOGIN :::= "12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
`SONAR.LOGIN ?= "12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
`const SONAR_LOGIN = "12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
`SONAR_LOGIN := "12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
`SONAR.LOGIN ::= "12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
`SONAR.LOGIN :::= "12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
`SONAR.LOGIN ?= "12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
`const SONAR_TOKEN = "squ_12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
`SONAR_LOGIN := "sqp_12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
`SONAR.TOKEN = "sqa_12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
)
return utils.Validate(r, tps, nil)
}
+5
View File
@@ -88,5 +88,10 @@ func createSingleRuleDetector(r *config.Rule) *detect.Detector {
cfg := base.CreateGlobalConfig()
cfg.Rules = rules
cfg.Keywords = uniqueKeywords
for _, a := range cfg.Allowlists {
if err := a.Validate(); err != nil {
logging.Fatal().Err(err).Msg("invalid global allowlist")
}
}
return detect.NewDetector(cfg)
}
+19 -10
View File
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra"
"github.com/zricethezav/gitleaks/v8/cmd/scm"
"github.com/zricethezav/gitleaks/v8/detect"
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
@@ -42,6 +41,8 @@ func runGit(cmd *cobra.Command, args []string) {
// setup config (aka, the thing that defines rules)
initConfig(source)
initDiagnostics()
cfg := Config(cmd)
// create detector
@@ -54,30 +55,38 @@ func runGit(cmd *cobra.Command, args []string) {
preCommit := mustGetBoolFlag(cmd, "pre-commit")
var (
findings []report.Finding
err error
findings []report.Finding
err error
gitCmd *sources.GitCmd
scmPlatform scm.Platform
remote *detect.RemoteInfo
)
if preCommit || staged {
if gitCmd, err = sources.NewGitDiffCmd(source, staged); err != nil {
if gitCmd, err = sources.NewGitDiffCmdContext(cmd.Context(), source, staged); err != nil {
logging.Fatal().Err(err).Msg("could not create Git diff cmd")
}
// Remote info + links are irrelevant for staged changes.
remote = &detect.RemoteInfo{Platform: scm.NoPlatform}
scmPlatform = scm.NoPlatform
} else {
if gitCmd, err = sources.NewGitLogCmd(source, logOpts); err != nil {
if gitCmd, err = sources.NewGitLogCmdContext(cmd.Context(), source, logOpts); err != nil {
logging.Fatal().Err(err).Msg("could not create Git log cmd")
}
if scmPlatform, err = scm.PlatformFromString(mustGetStringFlag(cmd, "platform")); err != nil {
logging.Fatal().Err(err).Send()
}
remote = detect.NewRemoteInfo(scmPlatform, source)
}
findings, err = detector.DetectGit(gitCmd, remote)
findings, err = detector.DetectSource(
cmd.Context(),
&sources.Git{
Cmd: gitCmd,
Config: &detector.Config,
Remote: sources.NewRemoteInfoContext(cmd.Context(), scmPlatform, source),
Sema: detector.Sema,
MaxArchiveDepth: detector.MaxArchiveDepth,
},
)
if err != nil {
// don't exit on error, just log it
logging.Error().Err(err).Msg("failed to scan Git repository")
+3 -1
View File
@@ -33,6 +33,8 @@ func runProtect(cmd *cobra.Command, args []string) {
// setup config (aka, the thing that defines rules)
initConfig(source)
initDiagnostics()
cfg := Config(cmd)
// create detector
@@ -51,7 +53,7 @@ func runProtect(cmd *cobra.Command, args []string) {
remote *detect.RemoteInfo
)
if gitCmd, err = sources.NewGitDiffCmd(source, staged); err != nil {
if gitCmd, err = sources.NewGitDiffCmdContext(cmd.Context(), source, staged); err != nil {
logging.Fatal().Err(err).Msg("could not create Git diff cmd")
}
remote = &detect.RemoteInfo{Platform: scm.NoPlatform}
+77 -15
View File
@@ -2,6 +2,7 @@ package cmd
import (
"bytes"
"context"
"fmt"
"io"
"os"
@@ -19,6 +20,7 @@ import (
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/regexp"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/version"
)
const banner = `
@@ -38,11 +40,28 @@ order of precedence:
4. (target path)/.gitleaks.toml
If none of the four 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",
Version: Version,
}
var (
rootCmd = &cobra.Command{
Use: "gitleaks",
Short: "Gitleaks scans code, past or present, for secrets",
Version: version.Version,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
// Set the timeout for all the commands
if timeout, err := cmd.Flags().GetInt("timeout"); err != nil {
return err
} else if timeout > 0 {
ctx, cancel := context.WithTimeout(cmd.Context(), time.Duration(timeout)*time.Second)
cmd.SetContext(ctx)
cobra.OnFinalize(cancel)
}
return nil
},
}
// diagnostics manager is global to ensure it can be started before a scan begins
// and stopped after a scan completes
diagnosticsManager *DiagnosticsManager
)
const (
BYTE = 1.0
@@ -55,7 +74,7 @@ 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("report-path", "r", "", "report file")
rootCmd.PersistentFlags().StringP("report-path", "r", "", "report file (use \"-\" for stdout)")
rootCmd.PersistentFlags().StringP("report-format", "f", "", "output format (json, csv, junit, sarif, template)")
rootCmd.PersistentFlags().StringP("report-template", "", "", "template file used to generate the report (implies --report-format=template)")
rootCmd.PersistentFlags().StringP("baseline-path", "b", "", "path to baseline with issues that can be ignored")
@@ -69,7 +88,13 @@ func init() {
rootCmd.PersistentFlags().Bool("no-banner", false, "suppress banner")
rootCmd.PersistentFlags().StringSlice("enable-rule", []string{}, "only enable specific rules by id")
rootCmd.PersistentFlags().StringP("gitleaks-ignore-path", "i", ".", "path to .gitleaksignore file or folder containing one")
rootCmd.PersistentFlags().Int("max-decode-depth", 0, "allow recursive decoding up to this depth (default \"0\", no decoding is done)")
rootCmd.PersistentFlags().Int("max-decode-depth", 5, "allow recursive decoding up to this depth")
rootCmd.PersistentFlags().Int("max-archive-depth", 0, "allow scanning into nested archives up to this depth (default \"0\", no archive traversal is done)")
rootCmd.PersistentFlags().Int("timeout", 0, "set a timeout for gitleaks commands in seconds (default \"0\", no timeout is set)")
// Add diagnostics flags
rootCmd.PersistentFlags().String("diagnostics", "", "enable diagnostics (http OR comma-separated list: cpu,mem,trace). cpu=CPU prof, mem=memory prof, trace=exec tracing, http=serve via net/http/pprof")
rootCmd.PersistentFlags().String("diagnostics-dir", "", "directory to store diagnostics output files when not using http mode (defaults to current directory)")
err := viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config"))
if err != nil {
@@ -169,6 +194,33 @@ func initConfig(source string) {
}
}
func initDiagnostics() {
// Initialize diagnostics manager
diagnosticsFlag, err := rootCmd.PersistentFlags().GetString("diagnostics")
if err != nil {
logging.Fatal().Err(err).Msg("Error getting diagnostics flag")
}
diagnosticsDir, err := rootCmd.PersistentFlags().GetString("diagnostics-dir")
if err != nil {
logging.Fatal().Err(err).Msg("Error getting diagnostics-dir flag")
}
var diagErr error
diagnosticsManager, diagErr = NewDiagnosticsManager(diagnosticsFlag, diagnosticsDir)
if diagErr != nil {
logging.Fatal().Err(diagErr).Msg("Error initializing diagnostics")
}
if diagnosticsManager.Enabled {
logging.Info().Msg("Starting diagnostics...")
if diagErr := diagnosticsManager.StartDiagnostics(); diagErr != nil {
logging.Fatal().Err(diagErr).Msg("Failed to start diagnostics")
}
}
}
func Execute() {
if err := rootCmd.Execute(); err != nil {
if strings.Contains(err.Error(), "unknown flag") {
@@ -184,6 +236,7 @@ func Config(cmd *cobra.Command) config.Config {
if err := viper.Unmarshal(&vc); err != nil {
logging.Fatal().Err(err).Msg("Failed to load config")
}
cfg, err := vc.Translate()
if err != nil {
logging.Fatal().Err(err).Msg("Failed to load config")
@@ -197,15 +250,19 @@ func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Dete
var err error
// Setup common detector
detector := detect.NewDetector(cfg)
detector := detect.NewDetectorContext(cmd.Context(), cfg)
if detector.MaxDecodeDepth, err = cmd.Flags().GetInt("max-decode-depth"); err != nil {
logging.Fatal().Err(err).Msg("")
logging.Fatal().Err(err).Send()
}
if detector.MaxArchiveDepth, err = cmd.Flags().GetInt("max-archive-depth"); err != nil {
logging.Fatal().Err(err).Send()
}
// set color flag at first
if detector.NoColor, err = cmd.Flags().GetBool("no-color"); err != nil {
logging.Fatal().Err(err).Msg("")
logging.Fatal().Err(err).Send()
}
// also init logger again without color
if detector.NoColor {
@@ -216,7 +273,7 @@ func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Dete
}
detector.Config.Path, err = cmd.Flags().GetString("config")
if err != nil {
logging.Fatal().Err(err).Msg("")
logging.Fatal().Err(err).Send()
}
// if config path is not set, then use the {source}/.gitleaks.toml path.
@@ -226,18 +283,18 @@ func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Dete
}
// set verbose flag
if detector.Verbose, err = cmd.Flags().GetBool("verbose"); err != nil {
logging.Fatal().Err(err).Msg("")
logging.Fatal().Err(err).Send()
}
// set redact flag
if detector.Redact, err = cmd.Flags().GetUint("redact"); err != nil {
logging.Fatal().Err(err).Msg("")
logging.Fatal().Err(err).Send()
}
if detector.MaxTargetMegaBytes, err = cmd.Flags().GetInt("max-target-megabytes"); err != nil {
logging.Fatal().Err(err).Msg("")
logging.Fatal().Err(err).Send()
}
// set ignore gitleaks:allow flag
if detector.IgnoreGitleaksAllow, err = cmd.Flags().GetBool("ignore-gitleaks-allow"); err != nil {
logging.Fatal().Err(err).Msg("")
logging.Fatal().Err(err).Send()
}
gitleaksIgnorePath, err := cmd.Flags().GetString("gitleaks-ignore-path")
@@ -379,6 +436,11 @@ func bytesConvert(bytes uint64) string {
}
func findingSummaryAndExit(detector *detect.Detector, findings []report.Finding, exitCode int, start time.Time, err error) {
if diagnosticsManager.Enabled {
logging.Debug().Msg("Finalizing diagnostics...")
diagnosticsManager.StopDiagnostics()
}
totalBytes := detector.TotalBytes.Load()
bytesMsg := fmt.Sprintf("scanned ~%d bytes (%s)", totalBytes, bytesConvert(totalBytes))
if err == nil {
+8
View File
@@ -13,6 +13,8 @@ const (
GitHubPlatform
GitLabPlatform
AzureDevOpsPlatform
GiteaPlatform
BitbucketPlatform
// TODO: Add others.
)
@@ -23,6 +25,8 @@ func (p Platform) String() string {
"github",
"gitlab",
"azuredevops",
"gitea",
"bitbucket",
}[p]
}
@@ -38,6 +42,10 @@ func PlatformFromString(s string) (Platform, error) {
return GitLabPlatform, nil
case "azuredevops":
return AzureDevOpsPlatform, nil
case "gitea":
return GiteaPlatform, nil
case "bitbucket":
return BitbucketPlatform, nil
default:
return UnknownPlatform, fmt.Errorf("invalid scm platform value: %s", s)
}
+13 -3
View File
@@ -7,6 +7,7 @@ import (
"github.com/spf13/cobra"
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/sources"
)
func init() {
@@ -25,6 +26,8 @@ func runStdIn(cmd *cobra.Command, _ []string) {
// setup config (aka, the thing that defines rules)
initConfig(".")
initDiagnostics()
cfg := Config(cmd)
// create detector
@@ -33,10 +36,17 @@ func runStdIn(cmd *cobra.Command, _ []string) {
// parse flag(s)
exitCode := mustGetIntFlag(cmd, "exit-code")
findings, err := detector.DetectReader(os.Stdin, 10)
findings, err := detector.DetectSource(
cmd.Context(),
&sources.File{
Content: os.Stdin,
MaxArchiveDepth: detector.MaxArchiveDepth,
},
)
if err != nil {
// log fatal to exit, no need to continue since a report
// will not be generated when scanning from a pipe...for now
// log fatal to exit, no need to continue since a report will not be
// generated when scanning from a pipe...for now
logging.Fatal().Err(err).Msg("failed scan input from stdin")
}
+2 -3
View File
@@ -4,10 +4,9 @@ import (
"fmt"
"github.com/spf13/cobra"
"github.com/zricethezav/gitleaks/v8/version"
)
var Version = "version is set by build process"
func init() {
rootCmd.AddCommand(versionCmd)
}
@@ -19,5 +18,5 @@ var versionCmd = &cobra.Command{
}
func runVersion(cmd *cobra.Command, args []string) {
fmt.Println(Version)
fmt.Println(version.Version)
}
+104 -45
View File
@@ -1,9 +1,10 @@
package config
import (
"fmt"
"errors"
"strings"
ahocorasick "github.com/BobuSumisu/aho-corasick"
"golang.org/x/exp/maps"
"github.com/zricethezav/gitleaks/v8/regexp"
@@ -29,18 +30,15 @@ type Allowlist struct {
// Short human readable description of the allowlist.
Description string
// MatchCondition determines whether all criteria must match.
// MatchCondition determines whether all criteria must match. Defaults to "OR".
MatchCondition AllowlistMatchCondition
// Commits is a slice of commit SHAs that are allowed to be ignored. Defaults to "OR".
// Commits is a slice of commit SHAs that are allowed to be ignored.
Commits []string
// Paths is a slice of path regular expressions that are allowed to be ignored.
Paths []*regexp.Regexp
// Regexes is slice of content regular expressions that are allowed to be ignored.
Regexes []*regexp.Regexp
// Can be `match` or `line`.
//
// If `match` the _Regexes_ will be tested against the match of the _Rule.Regex_.
@@ -50,21 +48,85 @@ type Allowlist struct {
// If RegexTarget is empty, it will be tested against the found secret.
RegexTarget string
// Regexes is slice of content regular expressions that are allowed to be ignored.
Regexes []*regexp.Regexp
// 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
// validated is an internal flag to track whether `Validate()` has been called.
validated bool
// commitMap is a normalized version of Commits, used for efficiency purposes.
// TODO: possible optimizations so that both short and long hashes work.
commitMap map[string]struct{}
regexPat *regexp.Regexp
pathPat *regexp.Regexp
stopwordTrie *ahocorasick.Trie
}
func (a *Allowlist) Validate() error {
if a.validated {
return nil
}
// Disallow empty allowlists.
if len(a.Commits) == 0 &&
len(a.Paths) == 0 &&
len(a.Regexes) == 0 &&
len(a.StopWords) == 0 {
return errors.New("must contain at least one check for: commits, paths, regexes, or stopwords")
}
// Deduplicate commits and stopwords.
if len(a.Commits) > 0 {
uniqueCommits := make(map[string]struct{})
for _, commit := range a.Commits {
// Commits are case-insensitive.
uniqueCommits[strings.TrimSpace(strings.ToLower(commit))] = struct{}{}
}
a.Commits = maps.Keys(uniqueCommits)
a.commitMap = uniqueCommits
}
if len(a.StopWords) > 0 {
uniqueStopwords := make(map[string]struct{})
for _, stopWord := range a.StopWords {
uniqueStopwords[strings.ToLower(stopWord)] = struct{}{}
}
values := maps.Keys(uniqueStopwords)
a.StopWords = values
a.stopwordTrie = ahocorasick.NewTrieBuilder().AddStrings(values).Build()
}
// Combine patterns into a single expression.
if len(a.Paths) > 0 {
a.pathPat = joinRegexOr(a.Paths)
}
if len(a.Regexes) > 0 {
a.regexPat = joinRegexOr(a.Regexes)
}
a.validated = true
return nil
}
// CommitAllowed returns true if the commit is allowed to be ignored.
func (a *Allowlist) CommitAllowed(c string) (bool, string) {
if c == "" {
if a == nil || c == "" {
return false, ""
}
for _, commit := range a.Commits {
if commit == c {
return true, c
if a.commitMap != nil {
if _, ok := a.commitMap[strings.ToLower(c)]; ok {
return true, ""
}
} else if len(a.Commits) > 0 {
for _, commit := range a.Commits {
if commit == c {
return true, c
}
}
}
return false, ""
@@ -72,49 +134,46 @@ func (a *Allowlist) CommitAllowed(c string) (bool, string) {
// PathAllowed returns true if the path is allowed to be ignored.
func (a *Allowlist) PathAllowed(path string) bool {
return anyRegexMatch(path, a.Paths)
if a == nil || path == "" {
return false
}
if a.pathPat != nil {
return a.pathPat.MatchString(path)
} else if len(a.Paths) > 0 {
return anyRegexMatch(path, a.Paths)
}
return false
}
// RegexAllowed returns true if the regex is allowed to be ignored.
func (a *Allowlist) RegexAllowed(secret string) bool {
return anyRegexMatch(secret, a.Regexes)
if a == nil || secret == "" {
return false
}
if a.regexPat != nil {
return a.regexPat.MatchString(secret)
} else if len(a.Regexes) > 0 {
return anyRegexMatch(secret, a.Regexes)
}
return false
}
func (a *Allowlist) ContainsStopWord(s string) (bool, string) {
if a == nil || s == "" {
return false, ""
}
s = strings.ToLower(s)
for _, stopWord := range a.StopWords {
if strings.Contains(s, strings.ToLower(stopWord)) {
return true, stopWord
if a.stopwordTrie != nil {
if m := a.stopwordTrie.MatchFirstString(s); m != nil {
return true, m.MatchString()
}
} else if len(a.StopWords) > 0 {
for _, stopWord := range a.StopWords {
if strings.Contains(s, stopWord) {
return true, stopWord
}
}
}
return false, ""
}
func (a *Allowlist) Validate() error {
// Disallow empty allowlists.
if len(a.Commits) == 0 &&
len(a.Paths) == 0 &&
len(a.Regexes) == 0 &&
len(a.StopWords) == 0 {
return fmt.Errorf("[[rules.allowlists]] must contain at least one check for: commits, paths, regexes, or stopwords")
}
// Deduplicate commits and stopwords.
if len(a.Commits) > 0 {
uniqueCommits := make(map[string]struct{})
for _, commit := range a.Commits {
uniqueCommits[commit] = struct{}{}
}
a.Commits = maps.Keys(uniqueCommits)
}
if len(a.StopWords) > 0 {
uniqueStopwords := make(map[string]struct{})
for _, stopWord := range a.StopWords {
uniqueStopwords[stopWord] = struct{}{}
}
a.StopWords = maps.Keys(uniqueStopwords)
}
return nil
}
+227 -4
View File
@@ -105,7 +105,7 @@ func TestValidate(t *testing.T) {
}{
"empty conditions": {
input: Allowlist{},
wantErr: errors.New("[[rules.allowlists]] must contain at least one check for: commits, paths, regexes, or stopwords"),
wantErr: errors.New("must contain at least one check for: commits, paths, regexes, or stopwords"),
},
"deduplicated commits and stopwords": {
input: Allowlist{
@@ -113,8 +113,8 @@ func TestValidate(t *testing.T) {
StopWords: []string{"stopwordA", "stopwordB", "stopwordA"},
},
expected: Allowlist{
Commits: []string{"commitA", "commitB"},
StopWords: []string{"stopwordA", "stopwordB"},
Commits: []string{"commita", "commitb"},
StopWords: []string{"stopworda", "stopwordb"},
},
},
}
@@ -148,10 +148,233 @@ func TestValidate(t *testing.T) {
opts = cmp.Options{
cmp.Comparer(regexComparer),
cmpopts.SortSlices(arrayComparer),
cmpopts.IgnoreUnexported(Allowlist{}),
}
)
if diff := cmp.Diff(tt.input, tt.expected, opts); diff != "" {
if diff := cmp.Diff(tt.expected, tt.input, opts); diff != "" {
t.Errorf("diff: (-want +got)\n%s", diff)
}
}
}
var benchCommitAllowlist = func() *Allowlist {
allowlist := Allowlist{
Commits: []string{
"ba1beca8ac634d8b202e0daffebecceeb6dda2fc",
"74b19abcd33ff3a6cac8aebdcfccacde9ad40f5c",
"11ed23ff2df37b2c114ac13dbd902e3bdb8b9c63",
"d39bcd0ebd3c9fb8d2f1bfbc98fc92bceeb3eed3",
"faf321cf8f9f2cf654fab12f72ef64e6ffb7237e",
"5486ce1abcdfcc862efeb6f5071a1ddef0fb3926",
"fbcfdbdffdabf1c0f627ecdfcda91ca8c1b533ce",
"3db86dce50f1d99fe820a4bf42ffedaefedb1bcf",
"18ccec6cb316ce1abed9e8ec262ecd3dd4a3e222",
"20f1cc29eaa028e7e6bcdc82f2103c1af3899c5c",
"d90b5572e9bdb0cebf5edc3ad412c38ecd6b8ca6",
"a0c7a0addf82d2a84babdd8be1f3cee887cb69cf",
"0c3c967d21bca179e2d60b738fab848be9a65a45",
"85cb3ac8817afad5ffde45a29036f4a1fa8af2eb",
"cb9c19a9dcb05bebca7dacbed9b8afefeb2dc5ad",
"4bac7b9fbdc851caf3c5f0cece85acaa3ebb7fd2",
"ad2bfd0c271bbb1ac991fdfefcabb6dcc43cb3f5",
"0c522c2750ec2fdf134721ea6000841fed5ffdd1",
"fedbf91dddc017f9994edc7f3a75dcd9eabfdd2c",
"9e5205bdeb080d84bfb25dfcc86dccc3fe5be499",
"b5476d7901b105c2fdb5fc87a9f4fabdb40daf81",
"f8fdbc509fb3c3ef1c1cbe8e70ac933ac4109cc3",
"92727ea97463cd55eed3069ab54483ba20b94f3c",
"e4a01ce6fdb6f6a39d2c781f7dcba3ae37973d0b",
"dcdd273bdf8159faf60bfca6b2a20a98a9985cf3",
"3f1efb9b7705cc1cae9ebeafa8eaf95ab79d6bea",
"20831ce7da9e2cb78ad8cd2a73ca693d8ffaee9c",
"edffec40aa85fbf947b20b3ffcfe6e7f6a94d017",
"cfbbc60acefdc1f04ad26e022fba21f72ce5c25b",
"3beac0da108cbb4fac1ebcd060ba2b67aafbefdd",
"21a87495e1f1f4ee9d9dfab1c3e5ffbe4b6e7dba",
"a2a3e8ba9dcae74d7bc1267f07fec3a44a0c9b08",
"abe2c2ff0a9befc1cbae77ea6aebf8d3a46ee68f",
"9f9e4cea3bee21deb769f830bcf76185eba76ab6",
"48e2f92ccdd1cb33e10eba117386cb054e06f2e0",
"4e10cc0ae797adce6cec0beda8782b28ba2dcf8c",
"7d6eb5bc7bbee783ab012ee290f8b9acabe38367",
"bc5d1b99fd2cbacb225e574fd05c57a3f44ca35c",
"9a3ea6fd3dcfd135ea3b9bc63ab6494f5c54faaf",
"fc62eec1f10e646ec9a8dacaddf1becae7e31823",
"fd01d7f4dab422fba5b9abfeacee14aad6db0dee",
"d7a2bcbcab6a4f4af02dde8ceeef5b6ab0fd6ca5",
"0b1bf0ebfc1cca19eeb029cfb8e4abd8e72d82df",
"a1ea3f771dfbae1cadbc67c803b8b07081f3fdd0",
"78dfa84c70545f295b3b8fa3f8bd53d316ff682e",
"ca595eebf56ad6f118be2c5ddbeadac675a588ad",
"faadceaec7d0bb9cbef7e7f6cddc3a0fdb8e33b8",
"0b006e37964c7b1e3cdbafd21fe8e887886cb909",
"dffb3dfb72fa42ed49a69dae3838eaaf2a957ee0",
"2d927ebda284a25fb2cd8fc0dd42c9b7d333db5a",
"ffca0cdcbe9e33fd18a3bf692ea0f2a62d685aa4",
"ac0d9a8adbe32cbe7f99fdeccf22b5bf767d06fa",
"f4a2a0a2833f4cbcc2db2accd7cc4feacdeeeaed",
"5f4a1e0dcbd49ed99eadf4bf837f1efafea663c1",
"3e69fb30ea6761771f877d82ef8ee799eb1f56a0",
"2e13cb4dec42ca80918e2bdefb5df96bf9b1eebc",
"d480ed3e25cb82782bb6b3f0fffce8f7c3d9840b",
"7bd34bf663bd5900f0be9accb2091e3dc4a378bc",
"a9fdc3ccc7cfd3b2a73b55b957bbe73beedba2ea",
"b7ca933acc3ef5c8c5bfaede6bfc4f9acc7f4f39",
"248a04fea1bfc38f4a1b76ea4ce399ef0affe4cb",
"8ae496b4fb06c46ae5bfcdceda5e9773ca9ce25b",
"0ac468471f71e8d17c21eb9fe4d922549e13bc3a",
"db082f214cdbff93cdaefebabae455f2ed994730",
"df0c6eabe5ccffed0bf840f3c45a8fdf39c04f9b",
"aacaadfd5bd1e9efd6fc8a9b7ad8fe93ec3bbf23",
"4e9cbeaabc66d01da99cd85cbaf8db5bfaccf5c4",
"28b39fd14b2c8dbeab86aea69de0b5ccdf4ff7b2",
"a20ebfbef4c75e906a114eaad6a67deadb810ed9",
"f8fd3b4cd75b6fc28e21289e6d4ef7c4c7f22f68",
"ccf7e03c5f5c7d6fdbd9fbde2fd342ae15cbbe4e",
"cdcbcfe7c6d4cee31a27f338d1ff66d3cad4bbd5",
"d7c03aba693ba8de8aaea7fa9d8d46a733cd5989",
"48e3f4abb26eb44eefcaf3f188cea00cce46ddc1",
"c1a9c25e5e29804abbc8a0fccf1faf384fea28a5",
"f9e090c6b2af0ee3bde57f4a0352f5b02e675d35",
"1df2354e9eee4934c34dcbd2de0b1df9b5dcadac",
"7da5ad4d8fa965ea4aa4613a9dc4eabdc3406eeb",
"fe33bfb676572e7fafd8ae9ea88e0efa3c109bdd",
"fefeea80b187eefce0a9c184cb76976c2fcef98a",
"eea8efae44ab9eb43a5954df7fa63bb55fa1d8dc",
"f559c7bbe6b6bfba56e7f362604c721c2fee6d0d",
"bf1dbe006b93fb443aebbe77a2c9cfdfc3f6a6a0",
"cfd00d87f7bc44ed7bdcebbf493869a495ebfef8",
"7ca45a388fd9aaeb8ed7701c2af2beff9e52eebb",
"ca47c2fdb73b2d39a1eab115dffa1ef7a5ffacd0",
"cc0954dfddaabb996abc78c28dff83f7e3edb828",
"ad4adc1195dabcfaf0f7eaac4f3f3f6b152d7fd4",
"ab3e6b6ed2eb6dcd4ae4fd0db76efdecd72ecfaa",
"d16ccd31d433f7a41eceb7d544081c72b4d9bf3e",
"d0dbe09bb150bbd5bb4b85adc273df87350e7e6c",
"492bbbcaf6edd864dd3ca0aee5d4d60b1cd4214b",
"d73dbbe7a9effb828793a3adad04cecb1843ccbd",
"89b12dcbfc40e30ddecd7a19e0cf1e32a29ebccb",
"1cd815bd965ee0fd2e15bbe28c94688f15ebb3ad",
"a7f9b3babda7abfe0316bf7aeded7df7cfcf7bdf",
"9e832d5ebecc2e5aead9b5cdcdd6d2ba4dfeaee7",
"43fa54761faa5f8beffe9acfd402fcd24dfede71",
"dada4b08ae4aa37cff754b4ca29ebc134c54bac1",
"1b708f1fad29cc62bc39ae5dda8e9124acc00d2d",
},
}
_ = allowlist.Validate()
return &allowlist
}()
func BenchmarkCommitAllowed(b *testing.B) {
for n := 0; n < b.N; n++ {
ok, _ := benchCommitAllowlist.CommitAllowed("d0dbe09bb150bbd5bb4b85adc273df87350e7e6c")
assert.True(b, ok)
}
}
func BenchmarkCommitNotAllowed(b *testing.B) {
for n := 0; n < b.N; n++ {
ok, _ := benchCommitAllowlist.CommitAllowed("5fe58bf0b0be1735ad27aa6053b56323a905c223")
assert.False(b, ok)
}
}
var benchRegexAllowlist = func() *Allowlist {
a := Allowlist{
RegexTarget: "match",
Regexes: []*regexp.Regexp{
// Based on patterns from `generic.go`
regexp.MustCompile(`(?i)access(ibility|or)`),
regexp.MustCompile(`(?i)access[_.-]?id`),
regexp.MustCompile(`(?i)random[_.-]?access`),
regexp.MustCompile(`(?i)api[_.-]?(id|name|version)`),
regexp.MustCompile(`(?i)rapid|capital`),
regexp.MustCompile(`(?i)[a-z0-9-]*?api[a-z0-9-]*?:jar:`),
regexp.MustCompile(`(?i)author`),
regexp.MustCompile(`(?i)X-MS-Exchange-Organization-Auth`),
regexp.MustCompile(`(?i)Authentication-Results`),
regexp.MustCompile(`(?i)(credentials?[_.-]?id|withCredentials)`),
regexp.MustCompile(`(?i)(bucket|foreign|hot|idx|natural|primary|pub(lic)?|schema|sequence)[_.-]?key`),
regexp.MustCompile(`(?i)key[_.-]?(alias|board|code|frame|id|length|mesh|name|pair|ring|selector|signature|size|stone|storetype|word|up|down|left|right)`),
regexp.MustCompile(`(?i)key[_.-]?vault[_.-]?(id|name)|keyVaultToStoreSecrets`),
regexp.MustCompile(`(?i)key(store|tab)[_.-]?(file|path)`),
regexp.MustCompile(`(?i)issuerkeyhash`),
regexp.MustCompile(`(?i)(?-i:[DdMm]onkey|[DM]ONKEY)|keying`),
regexp.MustCompile(`(?i)(secret)[_.-]?(length|name|size)`),
regexp.MustCompile(`(?i)UserSecretsId`),
regexp.MustCompile(`(?i)(io\.jsonwebtoken[ \t]?:[ \t]?[\w-]+)`),
regexp.MustCompile(`(?i)(api|credentials|token)[_.-]?(endpoint|ur[il])`),
regexp.MustCompile(`(?i)public[_.-]?token`),
regexp.MustCompile(`(?i)(key|token)[_.-]?file`),
regexp.MustCompile(`([A-Z_]+=\n[A-Z_]+=|[a-z_]+=\n[a-z_]+=)(\n|\z)`),
regexp.MustCompile(`([A-Z.]+=\n[A-Z.]+=|[a-z.]+=\n[a-z.]+=)(\n|\z)`),
},
}
_ = a.Validate()
return &a
}()
func BenchmarkRegexAllowed(b *testing.B) {
for n := 0; n < b.N; n++ {
ok := benchRegexAllowlist.RegexAllowed(`environment {
CREDENTIALS_ID = "K8S_CRED"
}`)
assert.True(b, ok)
}
}
func BenchmarkRegexNotAllowed(b *testing.B) {
for n := 0; n < b.N; n++ {
ok := benchRegexAllowlist.RegexAllowed(`"credentials" : "0afae57f3ccfd9d7f5767067bc48b30f719e271ba470488056e37ab35d4b6506"`)
assert.False(b, ok)
}
}
var benchPathAllowlist = func() *Allowlist {
a := Allowlist{
Paths: []*regexp.Regexp{
// Copied from `base/config.go`
regexp.MustCompile(`gitleaks\.toml`),
regexp.MustCompile(`(?i)\.(bmp|gif|jpe?g|svg|tiff?)$`),
regexp.MustCompile(`\.(eot|[ot]tf|woff2?)$`),
regexp.MustCompile(`(.*?)(doc|docx|zip|xls|pdf|bin|socket|vsidx|v2|suo|wsuo|.dll|pdb|exe|gltf)$`),
regexp.MustCompile(`go\.(mod|sum|work(\.sum)?)$`),
regexp.MustCompile(`(^|/)vendor/modules\.txt$`),
regexp.MustCompile(`(^|/)vendor/(github\.com|golang\.org/x|google\.golang\.org|gopkg\.in|istio\.io|k8s\.io|sigs\.k8s\.io)(/.*)?$`),
regexp.MustCompile(`(^|/)gradlew(\.bat)?$`),
regexp.MustCompile(`(^|/)gradle\.lockfile$`),
regexp.MustCompile(`(^|/)mvnw(\.cmd)?$`),
regexp.MustCompile(`(^|/)\.mvn/wrapper/MavenWrapperDownloader\.java$`),
regexp.MustCompile(`(^|/)node_modules(/.*)?$`),
regexp.MustCompile(`(^|/)(npm-shrinkwrap\.json|package-lock\.json|pnpm-lock\.yaml|yarn\.lock)$`),
regexp.MustCompile(`(^|/)bower_components(/.*)?$`),
regexp.MustCompile(`(^|/)(angular|bootstrap|jquery(-?ui)?|plotly|swagger-?ui)[a-zA-Z0-9.-]*(\.min)?\.js(\.map)?$`),
regexp.MustCompile(`(^|/)javascript\.json$`),
regexp.MustCompile(`(^|/)(Pipfile|poetry)\.lock$`),
regexp.MustCompile(`(?i)/?(v?env|virtualenv)/lib(64)?(/.*)?$`),
regexp.MustCompile(`(?i)(^|/)(lib(64)?/python[23](\.\d{1,2})+|python/[23](\.\d{1,2})+/lib(64)?)(/.*)?$`),
regexp.MustCompile(`(?i)(^|/)[a-z0-9_.]+-[0-9.]+\.dist-info(/.+)?$`),
regexp.MustCompile(`(^|/)vendor/(bundle|ruby)(/.*?)?$`),
regexp.MustCompile(`\.gem$`),
regexp.MustCompile(`verification-metadata\.xml`),
regexp.MustCompile(`Database.refactorlog`),
},
}
_ = a.Validate()
return &a
}()
func BenchmarkPathAllowed(b *testing.B) {
for n := 0; n < b.N; n++ {
ok := benchPathAllowlist.PathAllowed(`src/main/resources/static/js/jquery-ui-1.10.4.min.js`)
assert.True(b, ok)
}
}
func BenchmarkPathNotAllowed(b *testing.B) {
for n := 0; n < b.N; n++ {
ok := benchPathAllowlist.PathAllowed(`azure_scale_templates/sub_modules/vpc_template/inputs.auto.tfvars.json_backup`)
assert.False(b, ok)
}
}
+257 -130
View File
@@ -2,22 +2,27 @@ package config
import (
_ "embed"
"errors"
"fmt"
"sort"
"strings"
gv "github.com/hashicorp/go-version"
"github.com/spf13/viper"
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/regexp"
"github.com/zricethezav/gitleaks/v8/version"
)
//go:embed gitleaks.toml
var DefaultConfig string
var (
//go:embed gitleaks.toml
DefaultConfig string
// use to keep track of how many configs we can extend
// yea I know, globals bad
var extendDepth int
// use to keep track of how many configs we can extend
// yea I know, globals bad
extendDepth int
)
const maxExtendDepth = 2
@@ -25,29 +30,42 @@ const maxExtendDepth = 2
// 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 {
Title string
Description string
Extend Extend
Rules []struct {
ID string
Description string
Path string
Regex string
SecretGroup int
Entropy float64
Keywords []string
Path string
Tags []string
// Deprecated: this is a shim for backwards-compatibility. It should be removed in 9.x.
AllowList *viperRuleAllowlist
Allowlists []viperRuleAllowlist
}
Allowlist struct {
Commits []string
Paths []string
RegexTarget string
Regexes []string
StopWords []string
// Deprecated: this is a shim for backwards-compatibility.
// TODO: Remove this in 9.x.
AllowList *viperRuleAllowlist
Allowlists []*viperRuleAllowlist
Required []*viperRequired
SkipReport bool
}
// Deprecated: this is a shim for backwards-compatibility.
// TODO: Remove this in 9.x.
AllowList *viperGlobalAllowlist
Allowlists []*viperGlobalAllowlist
MinVersion string
configPath string
}
type viperRequired struct {
ID string
WithinLines *int `mapstructure:"withinLines"`
WithinColumns *int `mapstructure:"withinColumns"`
}
type viperRuleAllowlist struct {
@@ -60,6 +78,11 @@ type viperRuleAllowlist struct {
StopWords []string
}
type viperGlobalAllowlist struct {
TargetRules []string
viperRuleAllowlist `mapstructure:",squash"`
}
// Config is a configuration struct that contains rules and an allowlist if present.
type Config struct {
Title string
@@ -67,11 +90,11 @@ type Config struct {
Path string
Description string
Rules map[string]Rule
Allowlist Allowlist
Keywords map[string]struct{}
// used to keep sarif results consistent
OrderedRules []string
Allowlists []*Allowlist
MinVersion string
}
// Extend is a struct that allows users to define how they want their
@@ -85,13 +108,24 @@ type Extend struct {
func (vc *ViperConfig) Translate() (Config, error) {
var (
keywords = make(map[string]struct{})
orderedRules []string
rulesMap = make(map[string]Rule)
keywords = make(map[string]struct{})
orderedRules []string
rulesMap = make(map[string]Rule)
ruleAllowlists = make(map[string][]*Allowlist)
)
// Validate individual rules.
for _, vr := range vc.Rules {
var (
pathPat *regexp.Regexp
regexPat *regexp.Regexp
)
if vr.Path != "" {
pathPat = regexp.MustCompile(vr.Path)
}
if vr.Regex != "" {
regexPat = regexp.MustCompile(vr.Regex)
}
if vr.Keywords == nil {
vr.Keywords = []string{}
} else {
@@ -101,132 +135,233 @@ func (vc *ViperConfig) Translate() (Config, error) {
vr.Keywords[i] = keyword
}
}
if vr.Tags == nil {
vr.Tags = []string{}
}
var configRegex *regexp.Regexp
var configPathRegex *regexp.Regexp
if vr.Regex != "" {
configRegex = regexp.MustCompile(vr.Regex)
}
if vr.Path != "" {
configPathRegex = regexp.MustCompile(vr.Path)
}
cr := Rule{
RuleID: vr.ID,
Description: vr.Description,
Regex: configRegex,
Regex: regexPat,
SecretGroup: vr.SecretGroup,
Entropy: vr.Entropy,
Path: configPathRegex,
Path: pathPat,
Keywords: vr.Keywords,
Tags: vr.Tags,
SkipReport: vr.SkipReport,
}
// Parse the allowlist, including the older format for backwards compatibility.
// Parse the rule allowlists, including the older format for backwards compatibility.
if vr.AllowList != nil {
// TODO: Remove this in v9.
if len(vr.Allowlists) > 0 {
return Config{}, fmt.Errorf("%s: [rules.allowlist] is deprecated, it cannot be used alongside [[rules.allowlist]]", cr.RuleID)
}
vr.Allowlists = append(vr.Allowlists, *vr.AllowList)
vr.Allowlists = append(vr.Allowlists, vr.AllowList)
}
for _, a := range vr.Allowlists {
var condition AllowlistMatchCondition
c := strings.ToUpper(a.Condition)
switch c {
case "AND", "&&":
condition = AllowlistMatchAnd
case "", "OR", "||":
condition = AllowlistMatchOr
default:
return Config{}, fmt.Errorf("%s: unknown allowlist condition '%s' (expected 'and', 'or')", cr.RuleID, c)
}
// Validate the target.
if a.RegexTarget != "" {
switch a.RegexTarget {
case "secret":
a.RegexTarget = ""
case "match", "line":
// do nothing
default:
return Config{}, fmt.Errorf("%s: unknown allowlist |regexTarget| '%s' (expected 'match', 'line')", cr.RuleID, a.RegexTarget)
}
}
var allowlistRegexes []*regexp.Regexp
for _, a := range a.Regexes {
allowlistRegexes = append(allowlistRegexes, regexp.MustCompile(a))
}
var allowlistPaths []*regexp.Regexp
for _, a := range a.Paths {
allowlistPaths = append(allowlistPaths, regexp.MustCompile(a))
}
allowlist := Allowlist{
MatchCondition: condition,
RegexTarget: a.RegexTarget,
Regexes: allowlistRegexes,
Paths: allowlistPaths,
Commits: a.Commits,
StopWords: a.StopWords,
}
if err := allowlist.Validate(); err != nil {
return Config{}, fmt.Errorf("%s: %w", cr.RuleID, err)
allowlist, err := vc.parseAllowlist(a)
if err != nil {
return Config{}, fmt.Errorf("%s: [[rules.allowlists]] %w", cr.RuleID, err)
}
cr.Allowlists = append(cr.Allowlists, allowlist)
}
for _, r := range vr.Required {
if r.ID == "" {
return Config{}, fmt.Errorf("%s: [[rules.required]] rule ID is empty", cr.RuleID)
}
requiredRule := Required{
RuleID: r.ID,
WithinLines: r.WithinLines,
WithinColumns: r.WithinColumns,
// Distance: r.Distance,
}
cr.RequiredRules = append(cr.RequiredRules, &requiredRule)
}
orderedRules = append(orderedRules, cr.RuleID)
rulesMap[cr.RuleID] = cr
}
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))
// after all the rules have been processed, let's ensure the required rules
// actually exist.
for _, r := range rulesMap {
for _, rr := range r.RequiredRules {
if _, ok := rulesMap[rr.RuleID]; !ok {
return Config{}, fmt.Errorf("%s: [[rules.required]] rule ID '%s' does not exist", r.RuleID, rr.RuleID)
}
}
}
// Assemble the config.
c := Config{
Description: vc.Description,
Extend: vc.Extend,
Rules: rulesMap,
Allowlist: Allowlist{
RegexTarget: vc.Allowlist.RegexTarget,
Regexes: allowlistRegexes,
Paths: allowlistPaths,
Commits: vc.Allowlist.Commits,
StopWords: vc.Allowlist.StopWords,
},
Title: vc.Title,
Description: vc.Description,
Extend: vc.Extend,
Rules: rulesMap,
Keywords: keywords,
OrderedRules: orderedRules,
MinVersion: vc.MinVersion,
}
if maxExtendDepth != extendDepth {
if extendDepth > 0 {
// annoying hack to set the current config with the extended path
// since if extendDepth > 0 we are operating an extended config.
c.Path = vc.configPath
} else {
// I don't love this
c.Path = viper.ConfigFileUsed()
}
if err := validateMinVersion(c.MinVersion, c.Path); err != nil {
return Config{}, err
}
// Parse the config allowlists, including the older format for backwards compatibility.
if vc.AllowList != nil {
// TODO: Remove this in v9.
if len(vc.Allowlists) > 0 {
return Config{}, errors.New("[allowlist] is deprecated, it cannot be used alongside [[allowlists]]")
}
vc.Allowlists = append(vc.Allowlists, vc.AllowList)
}
for _, a := range vc.Allowlists {
allowlist, err := vc.parseAllowlist(&a.viperRuleAllowlist)
if err != nil {
return Config{}, fmt.Errorf("[[allowlists]] %w", err)
}
// Allowlists with |targetRules| aren't added to the global list.
if len(a.TargetRules) > 0 {
for _, ruleID := range a.TargetRules {
// It's not possible to validate |ruleID| until after extend.
ruleAllowlists[ruleID] = append(ruleAllowlists[ruleID], allowlist)
}
} else {
c.Allowlists = append(c.Allowlists, allowlist)
}
}
currentExtendDepth := extendDepth
if maxExtendDepth != currentExtendDepth {
// disallow both usedefault and path from being set
if c.Extend.Path != "" && c.Extend.UseDefault {
logging.Fatal().Msg("unable to load config due to extend.path and extend.useDefault being set")
return Config{}, errors.New("unable to load config due to extend.path and extend.useDefault being set")
}
if c.Extend.UseDefault {
c.extendDefault()
if err := c.extendDefault(vc); err != nil {
return Config{}, err
}
} else if c.Extend.Path != "" {
c.extendPath()
}
}
// Validate the rules after everything has been assembled (including extended configs).
if extendDepth == 0 {
for _, rule := range c.Rules {
if err := rule.Validate(); err != nil {
if err := c.extendPath(vc); err != nil {
return Config{}, err
}
}
}
// Validate the rules after everything has been assembled (including extended configs).
if currentExtendDepth == 0 {
for _, rule := range c.Rules {
if err := rule.Validate(); err != nil {
return Config{}, err
}
}
// Populate targeted configs.
for ruleID, allowlists := range ruleAllowlists {
rule, ok := c.Rules[ruleID]
if !ok {
return Config{}, fmt.Errorf("[[allowlists]] target rule ID '%s' does not exist", ruleID)
}
rule.Allowlists = append(rule.Allowlists, allowlists...)
c.Rules[ruleID] = rule
}
}
return c, nil
}
func validateMinVersion(minVer string, configPath string) error {
if minVer == "" {
logging.Debug().Str("config path", configPath).
Msg("no minVersion specified in config... consider adding minVersion to ensure compatibility.")
return nil
}
if version.Version == version.DefaultMsg {
logging.Debug().
Str("required", minVer).
Msg("dev build, skipping config version check.")
return nil
}
minSemVer, err := gv.NewSemver(minVer)
if err != nil {
return fmt.Errorf("invalid minVersion '%s': %w", minVer, err)
}
currentSemVer, err := gv.NewSemver(version.Version)
if err != nil {
return fmt.Errorf("unable to parse current version: %w", err)
}
if currentSemVer.LessThan(minSemVer) {
logging.Warn().
Str("required", minVer).
Str("current", version.Version).
Str("config path", configPath).
Msg("config requires a newer Gitleaks version...")
}
return nil
}
func (vc *ViperConfig) parseAllowlist(a *viperRuleAllowlist) (*Allowlist, error) {
var matchCondition AllowlistMatchCondition
switch strings.ToUpper(a.Condition) {
case "AND", "&&":
matchCondition = AllowlistMatchAnd
case "", "OR", "||":
matchCondition = AllowlistMatchOr
default:
return nil, fmt.Errorf("unknown allowlist |condition| '%s' (expected 'and', 'or')", a.Condition)
}
// Validate the target.
regexTarget := a.RegexTarget
if regexTarget != "" {
switch regexTarget {
case "secret":
regexTarget = ""
case "match", "line":
// do nothing
default:
return nil, fmt.Errorf("unknown allowlist |regexTarget| '%s' (expected 'match', 'line')", regexTarget)
}
}
var allowlistRegexes []*regexp.Regexp
for _, a := range a.Regexes {
allowlistRegexes = append(allowlistRegexes, regexp.MustCompile(a))
}
var allowlistPaths []*regexp.Regexp
for _, a := range a.Paths {
allowlistPaths = append(allowlistPaths, regexp.MustCompile(a))
}
allowlist := &Allowlist{
Description: a.Description,
MatchCondition: matchCondition,
Commits: a.Commits,
Paths: allowlistPaths,
RegexTarget: regexTarget,
Regexes: allowlistRegexes,
StopWords: a.StopWords,
}
if err := allowlist.Validate(); err != nil {
return nil, err
}
return allowlist, nil
}
func (c *Config) GetOrderedRules() []Rule {
var orderedRules []Rule
for _, id := range c.OrderedRules {
@@ -237,47 +372,45 @@ func (c *Config) GetOrderedRules() []Rule {
return orderedRules
}
func (c *Config) extendDefault() {
func (c *Config) extendDefault(parent *ViperConfig) error {
extendDepth++
viper.SetConfigType("toml")
if err := viper.ReadConfig(strings.NewReader(DefaultConfig)); err != nil {
logging.Fatal().Msgf("failed to load extended config, err: %s", err)
return
return fmt.Errorf("failed to load extended default config, err: %w", err)
}
defaultViperConfig := ViperConfig{}
if err := viper.Unmarshal(&defaultViperConfig); err != nil {
logging.Fatal().Msgf("failed to load extended config, err: %s", err)
return
return fmt.Errorf("failed to load extended default config, err: %w", err)
}
cfg, err := defaultViperConfig.Translate()
if err != nil {
logging.Fatal().Msgf("failed to load extended config, err: %s", err)
return
return fmt.Errorf("failed to load extended default config, err: %w", err)
}
logging.Debug().Msg("extending config with default config")
c.extend(cfg)
return nil
}
func (c *Config) extendPath() {
func (c *Config) extendPath(parent *ViperConfig) error {
extendDepth++
viper.SetConfigFile(c.Extend.Path)
if err := viper.ReadInConfig(); err != nil {
logging.Fatal().Msgf("failed to load extended config, err: %s", err)
return
return fmt.Errorf("failed to load extended config, err: %w", err)
}
extensionViperConfig := ViperConfig{}
if err := viper.Unmarshal(&extensionViperConfig); err != nil {
logging.Fatal().Msgf("failed to load extended config, err: %s", err)
return
return fmt.Errorf("failed to load extended config, err: %w", err)
}
extensionViperConfig.configPath = c.Extend.Path
logging.Debug().Msgf("extending config with %s", c.Extend.Path)
cfg, err := extensionViperConfig.Translate()
if err != nil {
logging.Fatal().Msgf("failed to load extended config, err: %s", err)
return
return fmt.Errorf("failed to load extended config, err: %w", err)
}
logging.Debug().Msgf("extending config with %s", c.Extend.Path)
c.extend(cfg)
return nil
}
func (c *Config) extendURL() {
@@ -341,9 +474,7 @@ func (c *Config) extend(extensionConfig Config) {
}
baseRule.Tags = append(baseRule.Tags, currentRule.Tags...)
baseRule.Keywords = append(baseRule.Keywords, currentRule.Keywords...)
for _, a := range currentRule.Allowlists {
baseRule.Allowlists = append(baseRule.Allowlists, a)
}
baseRule.Allowlists = append(baseRule.Allowlists, currentRule.Allowlists...)
// The keywords from the base rule and the extended rule must be merged into the global keywords list
for _, k := range baseRule.Keywords {
c.Keywords[k] = struct{}{}
@@ -353,13 +484,9 @@ func (c *Config) extend(extensionConfig Config) {
}
// append allowlists, not attempting to merge
c.Allowlist.Commits = append(c.Allowlist.Commits,
extensionConfig.Allowlist.Commits...)
c.Allowlist.Paths = append(c.Allowlist.Paths,
extensionConfig.Allowlist.Paths...)
c.Allowlist.Regexes = append(c.Allowlist.Regexes,
extensionConfig.Allowlist.Regexes...)
c.Allowlists = append(c.Allowlists, extensionConfig.Allowlists...)
// sort to keep extended rules in order
sort.Strings(c.OrderedRules)
return
}
+489 -269
View File
@@ -1,10 +1,11 @@
package config
import (
"fmt"
"errors"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -14,105 +15,67 @@ import (
const configPath = "../testdata/config/"
var regexComparer = func(x, y *regexp.Regexp) bool {
if x == nil || y == nil {
return x == y
}
return x.String() == y.String()
}
type translateCase struct {
// Configuration file basename to load, from `../testdata/config/`.
cfgName string
// Expected result.
cfg Config
// Rules to compare.
rules []string
// Error to expect.
wantError error
}
func TestTranslate(t *testing.T) {
tests := []struct {
// Configuration file basename to load, from `../testdata/config/`.
cfgName string
// Expected result.
cfg Config
// Rules to compare.
rules []string
// Error to expect.
wantError error
}{
tests := []translateCase{
// Valid
{
cfgName: "allowlist_old_compat",
cfgName: "generic",
cfg: Config{
Rules: map[string]Rule{"example": {
RuleID: "example",
Regex: regexp.MustCompile(`example\d+`),
Tags: []string{},
Keywords: []string{},
Allowlists: []Allowlist{
{
MatchCondition: AllowlistMatchOr,
Regexes: []*regexp.Regexp{regexp.MustCompile("123")},
},
},
Title: "gitleaks config",
Rules: map[string]Rule{"generic-api-key": {
RuleID: "generic-api-key",
Description: "Generic API Key",
Regex: regexp.MustCompile(`(?i)(?:key|api|token|secret|client|passwd|password|auth|access)(?:[0-9a-z\-_\t .]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:{1,3}=|\|\|:|<=|=>|:|\?=)(?:'|\"|\s|=|\x60){0,5}([0-9a-z\-_.=]{10,150})(?:['|\"|\n|\r|\s|\x60|;]|$)`),
Entropy: 3.5,
Keywords: []string{"key", "api", "token", "secret", "client", "passwd", "password", "auth", "access"},
Tags: []string{},
}},
},
},
{
cfgName: "allowlist_invalid_empty",
cfg: Config{},
wantError: fmt.Errorf("example: [[rules.allowlists]] must contain at least one check for: commits, paths, regexes, or stopwords"),
},
{
cfgName: "allowlist_invalid_old_and_new",
cfg: Config{},
wantError: fmt.Errorf("example: [rules.allowlist] is deprecated, it cannot be used alongside [[rules.allowlist]]"),
},
{
cfgName: "allowlist_invalid_regextarget",
cfg: Config{},
wantError: fmt.Errorf("example: unknown allowlist |regexTarget| 'mtach' (expected 'match', 'line')"),
},
{
cfgName: "allow_aws_re",
cfgName: "valid/rule_path_only",
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Rules: map[string]Rule{"python-files-only": {
RuleID: "python-files-only",
Description: "Python Files",
Path: regexp.MustCompile(`.py`),
Keywords: []string{},
Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{
{
MatchCondition: AllowlistMatchOr,
Regexes: []*regexp.Regexp{regexp.MustCompile("AKIALALEMEL33243OLIA")},
},
},
Tags: []string{},
}},
},
},
{
cfgName: "allow_commit",
cfgName: "valid/rule_regex_escaped_character_group",
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Rules: map[string]Rule{"pypi-upload-token": {
RuleID: "pypi-upload-token",
Description: "PyPI upload token",
Regex: regexp.MustCompile(`pypi-AgEIcHlwaS5vcmc[A-Za-z0-9\-_]{50,1000}`),
Keywords: []string{},
Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{
{
MatchCondition: AllowlistMatchOr,
Commits: []string{"allowthiscommit"},
},
},
Tags: []string{"key", "pypi"},
}},
},
},
{
cfgName: "allow_path",
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{},
Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{
{
MatchCondition: AllowlistMatchOr,
Paths: []*regexp.Regexp{regexp.MustCompile(".go")},
},
},
}},
},
},
{
cfgName: "entropy_group",
cfgName: "valid/rule_entropy_group",
cfg: Config{
Rules: map[string]Rule{"discord-api-key": {
RuleID: "discord-api-key",
@@ -125,23 +88,246 @@ func TestTranslate(t *testing.T) {
}},
},
},
// Invalid
{
cfgName: "missing_id",
cfgName: "invalid/rule_missing_id",
cfg: Config{},
wantError: fmt.Errorf("rule |id| is missing or empty, regex: (?i)(discord[a-z0-9_ .\\-,]{0,25})(=|>|:=|\\|\\|:|<=|=>|:).{0,5}['\\\"]([a-h0-9]{64})['\\\"]"),
wantError: errors.New("rule |id| is missing or empty, description: Discord API key, regex: (?i)(discord[a-z0-9_ .\\-,]{0,25})(=|>|:=|\\|\\|:|<=|=>|:).{0,5}['\\\"]([a-h0-9]{64})['\\\"]"),
},
{
cfgName: "no_regex_or_path",
cfgName: "invalid/rule_no_regex_or_path",
cfg: Config{},
wantError: fmt.Errorf("discord-api-key: both |regex| and |path| are empty, this rule will have no effect"),
wantError: errors.New("discord-api-key: both |regex| and |path| are empty, this rule will have no effect"),
},
{
cfgName: "bad_entropy_group",
cfgName: "invalid/rule_bad_entropy_group",
cfg: Config{},
wantError: fmt.Errorf("discord-api-key: invalid regex secret group 5, max regex secret group 3"),
wantError: errors.New("discord-api-key: invalid regex secret group 5, max regex secret group 3"),
},
}
for _, tt := range tests {
t.Run(tt.cfgName, func(t *testing.T) {
testTranslate(t, tt)
})
}
}
func TestTranslateAllowlists(t *testing.T) {
tests := []translateCase{
// Global
{
cfgName: "valid/allowlist_global_old_compat",
cfg: Config{
Rules: map[string]Rule{},
Allowlists: []*Allowlist{
{
StopWords: []string{"0989c462-69c9-49fa-b7d2-30dc5c576a97"},
},
},
},
},
{
cfgName: "base",
cfgName: "valid/allowlist_global_multiple",
cfg: Config{
Rules: map[string]Rule{
"test": {
RuleID: "test",
Regex: regexp.MustCompile(`token = "(.+)"`),
Keywords: []string{},
Tags: []string{},
},
},
Allowlists: []*Allowlist{
{
Regexes: []*regexp.Regexp{regexp.MustCompile("^changeit$")},
},
{
MatchCondition: AllowlistMatchAnd,
Paths: []*regexp.Regexp{regexp.MustCompile("^node_modules/.*")},
StopWords: []string{"mock"},
},
},
},
},
{
cfgName: "valid/allowlist_global_target_rules",
cfg: Config{
Rules: map[string]Rule{
"github-app-token": {
RuleID: "github-app-token",
Regex: regexp.MustCompile(`(?:ghu|ghs)_[0-9a-zA-Z]{36}`),
Tags: []string{},
Keywords: []string{},
Allowlists: []*Allowlist{
{
Paths: []*regexp.Regexp{regexp.MustCompile(`(?:^|/)@octokit/auth-token/README\.md$`)},
},
},
},
"github-oauth": {
RuleID: "github-oauth",
Regex: regexp.MustCompile(`gho_[0-9a-zA-Z]{36}`),
Tags: []string{},
Keywords: []string{},
Allowlists: nil,
},
"github-pat": {
RuleID: "github-pat",
Regex: regexp.MustCompile(`ghp_[0-9a-zA-Z]{36}`),
Tags: []string{},
Keywords: []string{},
Allowlists: []*Allowlist{
{
Paths: []*regexp.Regexp{regexp.MustCompile(`(?:^|/)@octokit/auth-token/README\.md$`)},
},
},
},
},
Allowlists: []*Allowlist{
{
Regexes: []*regexp.Regexp{regexp.MustCompile(".*fake.*")},
},
},
},
},
{
cfgName: "valid/allowlist_global_regex",
cfg: Config{
Rules: map[string]Rule{},
Allowlists: []*Allowlist{
{
MatchCondition: AllowlistMatchOr,
Regexes: []*regexp.Regexp{regexp.MustCompile("AKIALALEM.L33243OLIA")},
},
},
},
},
{
cfgName: "invalid/allowlist_global_empty",
cfg: Config{},
wantError: errors.New("[[allowlists]] must contain at least one check for: commits, paths, regexes, or stopwords"),
},
{
cfgName: "invalid/allowlist_global_old_and_new",
cfg: Config{},
wantError: errors.New("[allowlist] is deprecated, it cannot be used alongside [[allowlists]]"),
},
{
cfgName: "invalid/allowlist_global_target_rule_id",
cfg: Config{},
wantError: errors.New("[[allowlists]] target rule ID 'github-pat' does not exist"),
},
{
cfgName: "invalid/allowlist_global_regextarget",
cfg: Config{},
wantError: errors.New("[[allowlists]] unknown allowlist |regexTarget| 'mtach' (expected 'match', 'line')"),
},
// Rule
{
cfgName: "valid/allowlist_rule_old_compat",
cfg: Config{
Rules: map[string]Rule{"example": {
RuleID: "example",
Regex: regexp.MustCompile(`example\d+`),
Tags: []string{},
Keywords: []string{},
Allowlists: []*Allowlist{
{
MatchCondition: AllowlistMatchOr,
Regexes: []*regexp.Regexp{regexp.MustCompile("123")},
},
},
}},
},
},
{
cfgName: "valid/allowlist_rule_regex",
cfg: Config{
Title: "simple config with allowlist for aws",
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{},
Tags: []string{"key", "AWS"},
Allowlists: []*Allowlist{
{
MatchCondition: AllowlistMatchOr,
Regexes: []*regexp.Regexp{regexp.MustCompile("AKIALALEMEL33243OLIA")},
},
},
}},
},
},
{
cfgName: "valid/allowlist_rule_commit",
cfg: Config{
Title: "simple config with allowlist for a specific commit",
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{},
Tags: []string{"key", "AWS"},
Allowlists: []*Allowlist{
{
MatchCondition: AllowlistMatchOr,
Commits: []string{"allowthiscommit"},
},
},
}},
},
},
{
cfgName: "valid/allowlist_rule_path",
cfg: Config{
Title: "simple config with allowlist for .go files",
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{},
Tags: []string{"key", "AWS"},
Allowlists: []*Allowlist{
{
MatchCondition: AllowlistMatchOr,
Paths: []*regexp.Regexp{regexp.MustCompile(".go")},
},
},
}},
},
},
{
cfgName: "invalid/allowlist_rule_empty",
cfg: Config{},
wantError: errors.New("example: [[rules.allowlists]] must contain at least one check for: commits, paths, regexes, or stopwords"),
},
{
cfgName: "invalid/allowlist_rule_old_and_new",
cfg: Config{},
wantError: errors.New("example: [rules.allowlist] is deprecated, it cannot be used alongside [[rules.allowlist]]"),
},
{
cfgName: "invalid/allowlist_rule_regextarget",
cfg: Config{},
wantError: errors.New("example: [[rules.allowlists]] unknown allowlist |regexTarget| 'mtach' (expected 'match', 'line')"),
},
}
for _, tt := range tests {
t.Run(tt.cfgName, func(t *testing.T) {
testTranslate(t, tt)
})
}
}
func TestTranslateExtend(t *testing.T) {
tests := []translateCase{
// Valid
{
cfgName: "valid/extend",
cfg: Config{
Rules: map[string]Rule{
"aws-access-key": {
@@ -169,7 +355,27 @@ func TestTranslate(t *testing.T) {
},
},
{
cfgName: "extend_rule_allowlist_or",
cfgName: "valid/extend_disabled",
cfg: Config{
Title: "gitleaks extend disable",
Rules: map[string]Rule{
"aws-secret-key": {
RuleID: "aws-secret-key",
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Tags: []string{"key", "AWS"},
Keywords: []string{},
},
"pypi-upload-token": {
RuleID: "pypi-upload-token",
Regex: regexp.MustCompile(`pypi-AgEIcHlwaS5vcmc[A-Za-z0-9\-_]{50,1000}`),
Tags: []string{},
Keywords: []string{},
},
},
},
},
{
cfgName: "valid/extend_rule_no_regexpath",
cfg: Config{
Rules: map[string]Rule{
"aws-secret-key-again-again": {
@@ -178,7 +384,137 @@ func TestTranslate(t *testing.T) {
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Keywords: []string{},
Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{
Allowlists: []*Allowlist{
{
Description: "False positive. Keys used for colors match the rule, and should be excluded.",
MatchCondition: AllowlistMatchOr,
Paths: []*regexp.Regexp{regexp.MustCompile(`something.py`)},
},
},
},
},
},
},
{
cfgName: "valid/extend_rule_override_description",
rules: []string{"aws-access-key"},
cfg: Config{
Title: "override a built-in rule's description",
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "Puppy Doggy",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "valid/extend_rule_override_path",
rules: []string{"aws-access-key"},
cfg: Config{
Title: "override a built-in rule's path",
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Path: regexp.MustCompile("(?:puppy)"),
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "valid/extend_rule_override_regex",
rules: []string{"aws-access-key"},
cfg: Config{
Title: "override a built-in rule's regex",
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:a)"),
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "valid/extend_rule_override_secret_group",
rules: []string{"aws-access-key"},
cfg: Config{
Title: "override a built-in rule's secretGroup",
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(a)(a)"),
SecretGroup: 2,
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "valid/extend_rule_override_entropy",
rules: []string{"aws-access-key"},
cfg: Config{
Title: "override a built-in rule's entropy",
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Entropy: 999.0,
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "valid/extend_rule_override_keywords",
rules: []string{"aws-access-key"},
cfg: Config{
Title: "override a built-in rule's keywords",
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{"puppy"},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "valid/extend_rule_override_tags",
rules: []string{"aws-access-key"},
cfg: Config{
Title: "override a built-in rule's tags",
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{},
Tags: []string{"key", "AWS", "puppy"},
},
},
},
},
{
cfgName: "valid/extend_rule_allowlist_or",
cfg: Config{
Title: "gitleaks extended 3",
Rules: map[string]Rule{
"aws-secret-key-again-again": {
RuleID: "aws-secret-key-again-again",
Description: "AWS Secret Key",
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Keywords: []string{},
Tags: []string{"key", "AWS"},
Allowlists: []*Allowlist{
{
MatchCondition: AllowlistMatchOr,
StopWords: []string{"fake"},
@@ -197,8 +533,9 @@ func TestTranslate(t *testing.T) {
},
},
{
cfgName: "extend_rule_allowlist_and",
cfgName: "valid/extend_rule_allowlist_and",
cfg: Config{
Title: "gitleaks extended 3",
Rules: map[string]Rule{
"aws-secret-key-again-again": {
RuleID: "aws-secret-key-again-again",
@@ -206,7 +543,7 @@ func TestTranslate(t *testing.T) {
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Keywords: []string{},
Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{
Allowlists: []*Allowlist{
{
MatchCondition: AllowlistMatchOr,
StopWords: []string{"fake"},
@@ -224,191 +561,74 @@ func TestTranslate(t *testing.T) {
},
},
},
// Invalid
{
cfgName: "extend_empty_regexpath",
cfg: Config{
Rules: map[string]Rule{
"aws-secret-key-again-again": {
RuleID: "aws-secret-key-again-again",
Description: "AWS Secret Key",
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Keywords: []string{},
Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{
{
MatchCondition: AllowlistMatchOr,
Paths: []*regexp.Regexp{regexp.MustCompile(`something.py`)},
},
},
},
},
},
},
{
cfgName: "override_description",
rules: []string{"aws-access-key"},
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "Puppy Doggy",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "override_entropy",
rules: []string{"aws-access-key"},
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Entropy: 999.0,
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "override_secret_group",
rules: []string{"aws-access-key"},
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:a)(?:a)"),
SecretGroup: 2,
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "override_regex",
rules: []string{"aws-access-key"},
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:a)"),
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "override_path",
rules: []string{"aws-access-key"},
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Path: regexp.MustCompile("(?:puppy)"),
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "override_tags",
rules: []string{"aws-access-key"},
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{},
Tags: []string{"key", "AWS", "puppy"},
},
},
},
},
{
cfgName: "override_keywords",
rules: []string{"aws-access-key"},
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{"puppy"},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "extend_disabled",
cfg: Config{
Rules: map[string]Rule{
"aws-secret-key": {
RuleID: "aws-secret-key",
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Tags: []string{"key", "AWS"},
Keywords: []string{},
},
"pypi-upload-token": {
RuleID: "pypi-upload-token",
Regex: regexp.MustCompile(`pypi-AgEIcHlwaS5vcmc[A-Za-z0-9\-_]{50,1000}`),
Tags: []string{},
Keywords: []string{},
},
},
},
cfgName: "invalid/extend_invalid_ruleid",
wantError: errors.New("rule |id| is missing or empty"),
},
}
for _, tt := range tests {
t.Run(tt.cfgName, func(t *testing.T) {
t.Cleanup(func() {
extendDepth = 0
viper.Reset()
})
viper.AddConfigPath(configPath)
viper.SetConfigName(tt.cfgName)
viper.SetConfigType("toml")
err := viper.ReadInConfig()
require.NoError(t, err)
var vc ViperConfig
err = viper.Unmarshal(&vc)
require.NoError(t, err)
cfg, err := vc.Translate()
if err != nil && !assert.EqualError(t, tt.wantError, err.Error()) {
return
}
if len(tt.rules) > 0 {
rules := make(map[string]Rule)
for _, name := range tt.rules {
rules[name] = cfg.Rules[name]
}
cfg.Rules = rules
}
var regexComparer = func(x, y *regexp.Regexp) bool {
if x == nil || y == nil {
return x == y
}
return x.String() == y.String()
}
opts := cmp.Options{cmp.Comparer(regexComparer)}
if diff := cmp.Diff(tt.cfg.Rules, cfg.Rules, opts); diff != "" {
t.Errorf("%s diff: (-want +got)\n%s", tt.cfgName, diff)
}
testTranslate(t, tt)
})
}
}
func testTranslate(t *testing.T, test translateCase) {
t.Helper()
t.Cleanup(func() {
extendDepth = 0
viper.Reset()
})
viper.AddConfigPath(configPath)
viper.SetConfigName(test.cfgName)
viper.SetConfigType("toml")
err := viper.ReadInConfig()
require.NoError(t, err)
var vc ViperConfig
err = viper.Unmarshal(&vc)
require.NoError(t, err)
cfg, err := vc.Translate()
if err != nil {
if test.wantError != nil {
assert.EqualError(t, err, test.wantError.Error())
} else {
require.NoError(t, err)
}
} else {
if test.wantError != nil {
t.Fatalf("expected error but got none: %v", test.wantError)
return
}
}
if len(test.rules) > 0 {
rules := make(map[string]Rule)
for _, name := range test.rules {
rules[name] = cfg.Rules[name]
}
cfg.Rules = rules
}
opts := cmp.Options{
cmp.Comparer(regexComparer),
cmpopts.IgnoreUnexported(Rule{}, Allowlist{}),
}
if diff := cmp.Diff(test.cfg.Title, cfg.Title); diff != "" {
t.Errorf("%s diff: (-want +got)\n%s", test.cfgName, diff)
}
if diff := cmp.Diff(test.cfg.Rules, cfg.Rules, opts); diff != "" {
t.Errorf("%s diff: (-want +got)\n%s", test.cfgName, diff)
}
if diff := cmp.Diff(test.cfg.Allowlists, cfg.Allowlists, opts); diff != "" {
t.Errorf("%s diff: (-want +got)\n%s", test.cfgName, diff)
}
}
func TestExtendedRuleKeywordsAreDowncase(t *testing.T) {
tests := []struct {
name string
@@ -417,12 +637,12 @@ func TestExtendedRuleKeywordsAreDowncase(t *testing.T) {
}{
{
name: "Extend base rule that includes AWS keyword with new attribute",
cfgName: "extend_base_rule_including_keysword_with_attribute",
cfgName: "valid/extend_base_rule_including_keywords_with_attribute",
expectedKeywords: "aws",
},
{
name: "Extend base with a new rule with CMS keyword",
cfgName: "extend_with_new_rule",
cfgName: "valid/extend_rule_new",
expectedKeywords: "cms",
},
}
+130 -59
View File
@@ -13,28 +13,19 @@
title = "gitleaks config"
# minVersion indicates the minimum Gitleaks version required to use this config.
# If the running version is older, a warning will be logged and not all
# config-enabled features are guaranteed to work.
minVersion = "v8.25.0"
# TODO: change to [[allowlists]]
[allowlist]
description = "global allow lists"
regexes = [
'''(?i)^true|false|null$''',
'''^(?i:a+|b+|c+|d+|e+|f+|g+|h+|i+|j+|k+|l+|m+|n+|o+|p+|q+|r+|s+|t+|u+|v+|w+|x+|y+|z+|\*+|\.+)$''',
'''^\$(?:\d+|{\d+})$''',
'''^\$(?:[A-Z_]+|[a-z_]+)$''',
'''^\${(?:[A-Z_]+|[a-z_]+)}$''',
'''^\{\{[ \t]*[\w ().|]+[ \t]*}}$''',
'''^\$\{\{[ \t]*(?:(?:env|github|secrets|vars)(?:\.[A-Za-z]\w+)+[\w "'&./=|]*)[ \t]*}}$''',
'''^%(?:[A-Z_]+|[a-z_]+)%$''',
'''^%[+\-# 0]?[bcdeEfFgGoOpqstTUvxX]$''',
'''^\{\d{0,2}}$''',
'''^@(?:[A-Z_]+|[a-z_]+)@$''',
'''^/Users/(?i)[a-z0-9]+/[\w .-/]+$''',
'''^/(?:bin|etc|home|opt|tmp|usr|var)/[\w ./-]+$''',
]
paths = [
'''gitleaks\.toml''',
'''(?i)\.(?:bmp|gif|jpe?g|png|svg|tiff?)$''',
'''(?i)\.(?:eot|[ot]tf|woff2?)$''',
'''(?i)\.(?:docx?|xlsx?|pdf|bin|socket|vsidx|v2|suo|wsuo|.dll|pdb|exe|gltf|zip)$''',
'''(?i)\.(?:docx?|xlsx?|pdf|bin|socket|vsidx|v2|suo|wsuo|.dll|pdb|exe|gltf)$''',
'''go\.(?:mod|sum|work(?:\.sum)?)$''',
'''(?:^|/)vendor/modules\.txt$''',
'''(?:^|/)vendor/(?:github\.com|golang\.org/x|google\.golang\.org|gopkg\.in|istio\.io|k8s\.io|sigs\.k8s\.io)(?:/.*)?$''',
@@ -55,12 +46,35 @@ paths = [
'''\.gem$''',
'''verification-metadata\.xml''',
'''Database.refactorlog''',
'''(?:^|/)\.git$''',
]
regexes = [
'''(?i)^true|false|null$''',
'''^(?i:a+|b+|c+|d+|e+|f+|g+|h+|i+|j+|k+|l+|m+|n+|o+|p+|q+|r+|s+|t+|u+|v+|w+|x+|y+|z+|\*+|\.+)$''',
'''^\$(?:\d+|{\d+})$''',
'''^\$(?:[A-Z_]+|[a-z_]+)$''',
'''^\${(?:[A-Z_]+|[a-z_]+)}$''',
'''^\{\{[ \t]*[\w ().|]+[ \t]*}}$''',
'''^\$\{\{[ \t]*(?:(?:env|github|secrets|vars)(?:\.[A-Za-z]\w+)+[\w "'&./=|]*)[ \t]*}}$''',
'''^%(?:[A-Z_]+|[a-z_]+)%$''',
'''^%[+\-# 0]?[bcdeEfFgGoOpqstTUvxX]$''',
'''^\{\d{0,2}}$''',
'''^@(?:[A-Z_]+|[a-z_]+)@$''',
'''^/Users/(?i)[a-z0-9]+/[\w .-/]+$''',
'''^/(?:bin|etc|home|opt|tmp|usr|var)/[\w ./-]+$''',
]
stopwords = [
"abcdefghijklmnopqrstuvwxyz",
"014df517-39d1-4453-b7b3-9930c563627c",
"abcdefghijklmnopqrstuvwxyz",
]
[[rules]]
id = "1password-secret-key"
description = "Uncovered a possible 1Password secret key, potentially compromising access to secrets in vaults."
regex = '''\bA3-[A-Z0-9]{6}-(?:(?:[A-Z0-9]{11})|(?:[A-Z0-9]{6}-[A-Z0-9]{5}))-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}\b'''
entropy = 3.8
keywords = ["a3-"]
[[rules]]
id = "1password-service-account-token"
description = "Uncovered a possible 1Password service account token, potentially compromising access to secrets in vaults."
@@ -100,6 +114,12 @@ description = "Uncovered a possible Airtable API Key, potentially compromising d
regex = '''(?i)[\w.-]{0,50}?(?:airtable)(?:[ \t\w.-]{0,20})[\s'"]{0,3}(?:=|>|:{1,3}=|\|\||:|=>|\?=|,)[\x60'"\s=]{0,5}([a-z0-9]{17})(?:[\x60'"\s;]|\\[nr]|$)'''
keywords = ["airtable"]
[[rules]]
id = "airtable-personnal-access-token"
description = "Uncovered a possible Airtable Personal AccessToken, potentially compromising database access and leading to data leakage or alteration."
regex = '''\b(pat[[:alnum:]]{14}\.[a-f0-9]{64})\b'''
keywords = ["airtable"]
[[rules]]
id = "algolia-api-key"
description = "Identified an Algolia API Key, which could result in unauthorized search operations and data exposure on Algolia-managed platforms."
@@ -120,6 +140,32 @@ regex = '''(?i)[\w.-]{0,50}?(?:alibaba)(?:[ \t\w.-]{0,20})[\s'"]{0,3}(?:=|>|:{1,
entropy = 2
keywords = ["alibaba"]
[[rules]]
id = "anthropic-admin-api-key"
description = "Detected an Anthropic Admin API Key, risking unauthorized access to administrative functions and sensitive AI model configurations."
regex = '''\b(sk-ant-admin01-[a-zA-Z0-9_\-]{93}AA)(?:[\x60'"\s;]|\\[nr]|$)'''
keywords = ["sk-ant-admin01"]
[[rules]]
id = "anthropic-api-key"
description = "Identified an Anthropic API Key, which may compromise AI assistant integrations and expose sensitive data to unauthorized access."
regex = '''\b(sk-ant-api03-[a-zA-Z0-9_\-]{93}AA)(?:[\x60'"\s;]|\\[nr]|$)'''
keywords = ["sk-ant-api03"]
[[rules]]
id = "artifactory-api-key"
description = "Detected an Artifactory api key, posing a risk unauthorized access to the central repository."
regex = '''\bAKCp[A-Za-z0-9]{69}\b'''
entropy = 4.5
keywords = ["akcp"]
[[rules]]
id = "artifactory-reference-token"
description = "Detected an Artifactory reference token, posing a risk of impersonation and unauthorized access to the central repository."
regex = '''\bcmVmd[A-Za-z0-9]{59}\b'''
entropy = 4.5
keywords = ["cmvmd"]
[[rules]]
id = "asana-client-id"
description = "Discovered a potential Asana Client ID, risking unauthorized access to Asana projects and sensitive task information."
@@ -135,7 +181,7 @@ keywords = ["asana"]
[[rules]]
id = "atlassian-api-token"
description = "Detected an Atlassian API token, posing a threat to project management and collaboration tool security and data confidentiality."
regex = '''[\w.-]{0,50}?(?i:[\w.-]{0,50}?(?:atlassian|confluence|jira)(?:[ \t\w.-]{0,20})[\s'"]{0,3})(?:=|>|:{1,3}=|\|\||:|=>|\?=|,)[\x60'"\s=]{0,5}([a-zA-Z0-9]{24})(?:[\x60'"\s;]|\\[nr]|$)|\b(ATATT3[A-Za-z0-9_\-=]{186})(?:[\x60'"\s;]|\\[nr]|$)'''
regex = '''(?i)[\w.-]{0,50}?(?:(?-i:ATLASSIAN|[Aa]tlassian)|(?-i:CONFLUENCE|[Cc]onfluence)|(?-i:JIRA|[Jj]ira))(?:[ \t\w.-]{0,20})[\s'"]{0,3}(?:=|>|:{1,3}=|\|\||:|=>|\?=|,)[\x60'"\s=]{0,5}([a-z0-9]{20}[a-f0-9]{4})(?:[\x60'"\s;]|\\[nr]|$)|\b(ATATT3[A-Za-z0-9_\-=]{186})(?:[\x60'"\s;]|\\[nr]|$)'''
entropy = 3.5
keywords = [
"atlassian",
@@ -159,7 +205,7 @@ keywords = [
[[rules]]
id = "aws-access-token"
description = "Identified a pattern that may indicate AWS credentials, risking unauthorized cloud resource access and data breaches on AWS platforms."
regex = '''\b((?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16})\b'''
regex = '''\b((?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z2-7]{16})\b'''
entropy = 3
keywords = [
"a3t",
@@ -173,6 +219,20 @@ regexes = [
'''.+EXAMPLE$''',
]
[[rules]]
id = "aws-amazon-bedrock-api-key-long-lived"
description = "Identified a pattern that may indicate long-lived Amazon Bedrock API keys, risking unauthorized Amazon Bedrock usage"
regex = '''\b(ABSK[A-Za-z0-9+/]{109,269}={0,2})(?:[\x60'"\s;]|\\[nr]|$)'''
entropy = 3
keywords = ["absk"]
[[rules]]
id = "aws-amazon-bedrock-api-key-short-lived"
description = "Identified a pattern that may indicate short-lived Amazon Bedrock API keys, risking unauthorized Amazon Bedrock usage"
regex = '''bedrock-api-key-YmVkcm9jay5hbWF6b25hd3MuY29t'''
entropy = 3
keywords = ["bedrock-api-key-"]
[[rules]]
id = "azure-ad-client-secret"
description = "Azure AD Client Secret"
@@ -217,6 +277,13 @@ regex = '''[\w.-]{0,50}?(?i:[\w.-]{0,50}?(?:(?-i:[Mm]eraki|MERAKI))(?:[ \t\w.-]{
entropy = 3
keywords = ["meraki"]
[[rules]]
id = "clickhouse-cloud-api-secret-key"
description = "Identified a pattern that may indicate clickhouse cloud API secret key, risking unauthorized clickhouse cloud api access and data breaches on ClickHouse Cloud platforms."
regex = '''\b(4b1d[A-Za-z0-9]{38})\b'''
entropy = 3
keywords = ["4b1d"]
[[rules]]
id = "clojars-api-token"
description = "Uncovered a possible Clojars API token, risking unauthorized access to Clojure libraries and potential code manipulation."
@@ -545,7 +612,7 @@ keywords = ["freshbooks"]
id = "gcp-api-key"
description = "Uncovered a GCP API key, which could lead to unauthorized access to Google Cloud services and data breaches."
regex = '''\b(AIza[\w-]{35})(?:[\x60'"\s;]|\\[nr]|$)'''
entropy = 3
entropy = 4
keywords = ["aiza"]
[[rules.allowlists]]
regexes = [
@@ -589,12 +656,15 @@ regexes = [
'''^[a-zA-Z_.-]+$''',
]
[[rules.allowlists]]
description = "Allowlist for Generic API Keys"
regexTarget = "match"
regexes = [
'''(?i)(?:access(?:ibility|or)|access[_.-]?id|random[_.-]?access|api[_.-]?(?:id|name|version)|rapid|capital|[a-z0-9-]*?api[a-z0-9-]*?:jar:|author|X-MS-Exchange-Organization-Auth|Authentication-Results|(?:credentials?[_.-]?id|withCredentials)|(?:bucket|foreign|hot|idx|natural|primary|pub(?:lic)?|schema|sequence)[_.-]?key|(?:turkey)|key[_.-]?(?:alias|board|code|frame|id|length|mesh|name|pair|press(?:ed)?|ring|selector|signature|size|stone|storetype|word|up|down|left|right)|key[_.-]?vault[_.-]?(?:id|name)|keyVaultToStoreSecrets|key(?:store|tab)[_.-]?(?:file|path)|issuerkeyhash|(?-i:[DdMm]onkey|[DM]ONKEY)|keying|(?:secret)[_.-]?(?:length|name|size)|UserSecretsId|(?:csrf)[_.-]?token|(?:io\.jsonwebtoken[ \t]?:[ \t]?[\w-]+)|(?:api|credentials|token)[_.-]?(?:endpoint|ur[il])|public[_.-]?token|(?:key|token)[_.-]?file|(?-i:(?:[A-Z_]+=\n[A-Z_]+=|[a-z_]+=\n[a-z_]+=)(?:\n|\z))|(?-i:(?:[A-Z.]+=\n[A-Z.]+=|[a-z.]+=\n[a-z.]+=)(?:\n|\z)))''',
]
stopwords = [
"000000",
"6fe4476ee5a1832882e326b506d14126",
"_ec2_",
"aaaaaa",
"about",
"abstract",
@@ -610,9 +680,9 @@ stopwords = [
"activity",
"adapter",
"add-",
"add-on",
"add.",
"add_",
"add-on",
"addon",
"addres",
"admin",
@@ -655,10 +725,7 @@ stopwords = [
"any_",
"apache",
"app-",
"app-",
"app.",
"app.",
"app_",
"app_",
"apple",
"arch",
@@ -682,7 +749,6 @@ stopwords = [
"aura",
"auth",
"author",
"author",
"authorize",
"auto",
"automated",
@@ -803,7 +869,6 @@ stopwords = [
"cli.",
"cli_",
"client",
"client",
"clojure",
"clone",
"closure",
@@ -838,7 +903,6 @@ stopwords = [
"concept",
"conf",
"config",
"config",
"connect",
"connector",
"console",
@@ -897,7 +961,6 @@ stopwords = [
"dead",
"debian",
"debug",
"debug",
"debugger",
"deck",
"define",
@@ -929,10 +992,7 @@ stopwords = [
"dns-",
"dns_",
"doc-",
"doc-",
"doc.",
"doc.",
"doc_",
"doc_",
"docker",
"docpad",
@@ -946,8 +1006,8 @@ stopwords = [
"dom.",
"dom_",
"domain",
"done",
"don't",
"done",
"dot-",
"dot.",
"dot_",
@@ -967,7 +1027,6 @@ stopwords = [
"dsl_",
"dynamic",
"easy",
"_ec2_",
"ecdsa",
"eclipse",
"edit",
@@ -997,7 +1056,6 @@ stopwords = [
"event",
"evented",
"example",
"example",
"exchange",
"exercise",
"experiment",
@@ -1245,10 +1303,7 @@ stopwords = [
"koan",
"kohana",
"lab-",
"lab-",
"lab.",
"lab.",
"lab_",
"lab_",
"lambda",
"lamp",
@@ -1333,10 +1388,7 @@ stopwords = [
"manifest",
"manual",
"map-",
"map-",
"map.",
"map.",
"map_",
"map_",
"mapper",
"mapping",
@@ -1422,10 +1474,7 @@ stopwords = [
"nette",
"network",
"new-",
"new-",
"new.",
"new.",
"new_",
"new_",
"next",
"nginx",
@@ -1494,7 +1543,6 @@ stopwords = [
"package",
"packet",
"page",
"page",
"panel",
"paper",
"paperclip",
@@ -1611,8 +1659,8 @@ stopwords = [
"readme",
"ready",
"real",
"reality",
"real-time",
"reality",
"realtime",
"recipe",
"recorder",
@@ -1678,7 +1726,6 @@ stopwords = [
"rvm_",
"salt",
"sample",
"sample",
"sandbox",
"sas-",
"sas.",
@@ -1729,7 +1776,6 @@ stopwords = [
"set.",
"set_",
"setting",
"setting",
"setup",
"sha1",
"sha2",
@@ -1852,19 +1898,12 @@ stopwords = [
"synopsi",
"syntax",
"system",
"system",
"tab-",
"tab-",
"tab.",
"tab.",
"tab_",
"tab_",
"table",
"tag-",
"tag-",
"tag.",
"tag.",
"tag_",
"tag_",
"talk",
"target",
@@ -2003,7 +2042,6 @@ stopwords = [
"website",
"websocket",
"welcome",
"welcome",
"what",
"what'",
"when",
@@ -2070,7 +2108,6 @@ stopwords = [
"zsh-",
"zsh.",
"zsh_",
"6fe4476ee5a1832882e326b506d14126",
]
[[rules.allowlists]]
regexTarget = "line"
@@ -2310,6 +2347,13 @@ description = "Detected a Heroku API Key, potentially compromising cloud applica
regex = '''(?i)[\w.-]{0,50}?(?:heroku)(?:[ \t\w.-]{0,20})[\s'"]{0,3}(?:=|>|:{1,3}=|\|\||:|=>|\?=|,)[\x60'"\s=]{0,5}([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[\x60'"\s;]|\\[nr]|$)'''
keywords = ["heroku"]
[[rules]]
id = "heroku-api-key-v2"
description = "Detected a Heroku API Key, potentially compromising cloud application deployments and operational security."
regex = '''\b((HRKU-AA[0-9a-zA-Z_-]{58}))(?:[\x60'"\s;]|\\[nr]|$)'''
entropy = 4
keywords = ["hrku-aa"]
[[rules]]
id = "hubspot-api-key"
description = "Found a HubSpot API Token, posing a risk to CRM data integrity and unauthorized marketing operations."
@@ -2399,7 +2443,7 @@ keywords = ["kraken"]
[[rules]]
id = "kubernetes-secret-yaml"
description = "Possible Kubernetes Secret detected, posing a risk of leaking credentials/tokens from your deployments"
regex = '''(?i)(?:\bkind:[ \t]*["']?\bsecret\b["']?(?:.|\s){0,200}?\bdata:(?:.|\s){0,100}?\s+([\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:["']?[a-z0-9+/]{10,}={0,3}["']?|\{\{[ \t\w"|$:=,.-]+}}|""|''))|\bdata:(?:.|\s){0,100}?\s+([\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:["']?[a-z0-9+/]{10,}={0,3}["']?|\{\{[ \t\w"|$:=,.-]+}}|""|''))(?:.|\s){0,200}?\bkind:[ \t]*["']?\bsecret\b["']?)'''
regex = '''(?i)(?:\bkind:[ \t]*["']?\bsecret\b["']?(?s:.){0,200}?\bdata:(?s:.){0,100}?\s+([\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:["']?[a-z0-9+/]{10,}={0,3}["']?|\{\{[ \t\w"|$:=,.-]+}}|""|''))|\bdata:(?s:.){0,100}?\s+([\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:["']?[a-z0-9+/]{10,}={0,3}["']?|\{\{[ \t\w"|$:=,.-]+}}|""|''))(?s:.){0,200}?\bkind:[ \t]*["']?\bsecret\b["']?)'''
path = '''(?i)\.ya?ml$'''
keywords = ["secret"]
[[rules.allowlists]]
@@ -2409,7 +2453,7 @@ regexes = [
[[rules.allowlists]]
regexTarget = "match"
regexes = [
'''(kind:(?:.|\s)+\n---\n(?:.|\s)+\bdata:|data:(?:.|\s)+\n---\n(?:.|\s)+\bkind:)''',
'''(kind:(?s:.)+\n---\n(?s:.)+\bdata:|data:(?s:.)+\n---\n(?s:.)+\bkind:)''',
]
[[rules]]
@@ -2485,6 +2529,18 @@ keywords = [
"_pub",
]
[[rules]]
id = "looker-client-id"
description = "Found a Looker Client ID, risking unauthorized access to a Looker account and exposing sensitive data."
regex = '''(?i)[\w.-]{0,50}?(?:looker)(?:[ \t\w.-]{0,20})[\s'"]{0,3}(?:=|>|:{1,3}=|\|\||:|=>|\?=|,)[\x60'"\s=]{0,5}([a-z0-9]{20})(?:[\x60'"\s;]|\\[nr]|$)'''
keywords = ["looker"]
[[rules]]
id = "looker-client-secret"
description = "Found a Looker Client Secret, risking unauthorized access to a Looker account and exposing sensitive data."
regex = '''(?i)[\w.-]{0,50}?(?:looker)(?:[ \t\w.-]{0,20})[\s'"]{0,3}(?:=|>|:{1,3}=|\|\||:|=>|\?=|,)[\x60'"\s=]{0,5}([a-z0-9]{24})(?:[\x60'"\s;]|\\[nr]|$)'''
keywords = ["looker"]
[[rules]]
id = "mailchimp-api-key"
description = "Identified a Mailchimp API key, potentially compromising email marketing campaigns and subscriber data."
@@ -2592,6 +2648,13 @@ description = "Discovered a New Relic user API Key, which could lead to compromi
regex = '''(?i)[\w.-]{0,50}?(?:new-relic|newrelic|new_relic)(?:[ \t\w.-]{0,20})[\s'"]{0,3}(?:=|>|:{1,3}=|\|\||:|=>|\?=|,)[\x60'"\s=]{0,5}(NRAK-[a-z0-9]{27})(?:[\x60'"\s;]|\\[nr]|$)'''
keywords = ["nrak"]
[[rules]]
id = "notion-api-token"
description = "Notion API token"
regex = '''\b(ntn_[0-9]{11}[A-Za-z0-9]{32}[A-Za-z0-9]{3})(?:[\x60'"\s;]|\\[nr]|$)'''
entropy = 4
keywords = ["ntn_"]
[[rules]]
id = "npm-access-token"
description = "Uncovered an npm access token, potentially compromising package management and code repository access."
@@ -2651,6 +2714,13 @@ regex = '''\b(sha256~[\w-]{43})(?:[^\w-]|\z)'''
entropy = 3.5
keywords = ["sha256~"]
[[rules]]
id = "perplexity-api-key"
description = "Detected a Perplexity API key, which could lead to unauthorized access to Perplexity AI services and data exposure."
regex = '''\b(pplx-[a-zA-Z0-9]{48})(?:[\x60'"\s;]|\\[nr]|$|\b)'''
entropy = 4
keywords = ["pplx-"]
[[rules]]
id = "pkcs12-file"
description = "Found a PKCS #12 file, which commonly contain bundled private keys."
@@ -2973,7 +3043,8 @@ keywords = ["snyk"]
[[rules]]
id = "sonar-api-token"
description = "Uncovered a Sonar API token, potentially compromising software vulnerability scanning and code security."
regex = '''(?i)[\w.-]{0,50}?(?:sonar[_.-]?(login|token))(?:[ \t\w.-]{0,20})[\s'"]{0,3}(?:=|>|:{1,3}=|\|\||:|=>|\?=|,)[\x60'"\s=]{0,5}([a-z0-9=_\-]{40})(?:[\x60'"\s;]|\\[nr]|$)'''
regex = '''(?i)[\w.-]{0,50}?(?:sonar[_.-]?(login|token))(?:[ \t\w.-]{0,20})[\s'"]{0,3}(?:=|>|:{1,3}=|\|\||:|=>|\?=|,)[\x60'"\s=]{0,5}((?:squ_|sqp_|sqa_)?[a-z0-9=_\-]{40})(?:[\x60'"\s;]|\\[nr]|$)'''
secretGroup = 2
keywords = ["sonar"]
[[rules]]
+44 -11
View File
@@ -1,6 +1,7 @@
package config
import (
"errors"
"fmt"
"strings"
@@ -41,28 +42,49 @@ type Rule struct {
Keywords []string
// Allowlists allows a rule to be ignored for specific commits, paths, regexes, and/or stopwords.
Allowlists []Allowlist
Allowlists []*Allowlist
// validated is an internal flag to track whether `Validate()` has been called.
validated bool
// If a rule has RequiredRules, it makes the rule dependent on the RequiredRules.
// In otherwords, this rule is now a composite rule.
RequiredRules []*Required
SkipReport bool
}
type Required struct {
RuleID string
WithinLines *int
WithinColumns *int
}
// Validate guards against common misconfigurations.
func (r Rule) Validate() error {
func (r *Rule) Validate() error {
if r.validated {
return nil
}
// Ensure |id| is present.
if strings.TrimSpace(r.RuleID) == "" {
// Try to provide helpful context, since |id| is empty.
var context string
if r.Regex != nil {
context = ", regex: " + r.Regex.String()
} else if r.Path != nil {
context = ", path: " + r.Path.String()
} else if r.Description != "" {
context = ", description: " + r.Description
var sb strings.Builder
if r.Description != "" {
sb.WriteString(", description: " + r.Description)
}
return fmt.Errorf("rule |id| is missing or empty" + context)
if r.Regex != nil {
sb.WriteString(", regex: " + r.Regex.String())
}
if r.Path != nil {
sb.WriteString(", path: " + r.Path.String())
}
return errors.New("rule |id| is missing or empty" + sb.String())
}
// Ensure the rule actually matches something.
if r.Regex == nil && r.Path == nil {
return fmt.Errorf("%s: both |regex| and |path| are empty, this rule will have no effect", r.RuleID)
return errors.New(r.RuleID + ": both |regex| and |path| are empty, this rule will have no effect")
}
// Ensure |secretGroup| works.
@@ -70,5 +92,16 @@ func (r Rule) Validate() error {
return fmt.Errorf("%s: invalid regex secret group %d, max regex secret group %d", r.RuleID, r.SecretGroup, r.Regex.NumSubexp())
}
for _, allowlist := range r.Allowlists {
// This will probably never happen.
if allowlist == nil {
continue
}
if err := allowlist.Validate(); err != nil {
return fmt.Errorf("%s: %w", r.RuleID, err)
}
}
r.validated = true
return nil
}
+16
View File
@@ -1,6 +1,8 @@
package config
import (
"strings"
"github.com/zricethezav/gitleaks/v8/regexp"
)
@@ -22,3 +24,17 @@ func regexMatched(f string, re *regexp.Regexp) bool {
}
return false
}
// joinRegexOr combines multiple |patterns| into a single *regexp.Regexp.
func joinRegexOr(patterns []*regexp.Regexp) *regexp.Regexp {
var sb strings.Builder
sb.WriteString("(?:")
for i, pat := range patterns {
sb.WriteString(pat.String())
if i != len(patterns)-1 {
sb.WriteString("|")
}
}
sb.WriteString(")")
return regexp.MustCompile(sb.String())
}
+13 -15
View File
@@ -9,27 +9,25 @@ import (
"github.com/zricethezav/gitleaks/v8/report"
)
func IsNew(finding report.Finding, baseline []report.Finding) bool {
func IsNew(finding report.Finding, redact uint, baseline []report.Finding) bool {
// Explicitly testing each property as it gives significantly better performance in comparison to cmp.Equal(). Drawback is that
// the code requires maintenance if/when the Finding struct changes
for _, b := range baseline {
if finding.Author == b.Author &&
finding.Commit == b.Commit &&
finding.Date == b.Date &&
if finding.RuleID == b.RuleID &&
finding.Description == b.Description &&
finding.Email == b.Email &&
finding.EndColumn == b.EndColumn &&
finding.StartLine == b.StartLine &&
finding.EndLine == b.EndLine &&
finding.Entropy == b.Entropy &&
finding.File == b.File &&
// Omit checking finding.Fingerprint - if the format of the fingerprint changes, the users will see unexpected behaviour
finding.Match == b.Match &&
finding.Message == b.Message &&
finding.RuleID == b.RuleID &&
finding.Secret == b.Secret &&
finding.StartColumn == b.StartColumn &&
finding.StartLine == b.StartLine {
finding.EndColumn == b.EndColumn &&
(redact > 0 || (finding.Match == b.Match && finding.Secret == b.Secret)) &&
finding.File == b.File &&
finding.Commit == b.Commit &&
finding.Author == b.Author &&
finding.Email == b.Email &&
finding.Date == b.Date &&
finding.Message == b.Message &&
// Omit checking finding.Fingerprint - if the format of the fingerprint changes, the users will see unexpected behaviour
finding.Entropy == b.Entropy {
return false
}
}
+114 -22
View File
@@ -11,59 +11,150 @@ import (
)
func TestIsNew(t *testing.T) {
tests := []struct {
t.Parallel()
tests := map[string]struct {
findings report.Finding
redact uint
baseline []report.Finding
expect bool
}{
{
// new
"new - commit doesn't match baseline": {
findings: report.Finding{
Author: "a",
Commit: "0000",
Author: "a",
},
baseline: []report.Finding{
{
Author: "a",
Commit: "0000",
},
},
expect: false,
},
{
findings: report.Finding{
Author: "a",
Commit: "0000",
},
baseline: []report.Finding{
{
Author: "a",
Commit: "0002",
Author: "a",
},
},
expect: true,
},
{
"new - redacted, different baseline": {
findings: report.Finding{
RuleID: "private-key",
Description: "Identified a Private Key, which may compromise cryptographic security and sensitive data encryption.",
StartLine: 1,
EndLine: 15,
StartColumn: 1,
EndColumn: 30,
Match: "REDACTED",
Secret: "REDACTED",
File: "key.txt",
Commit: "6d3ba1f7653822c0f8ac9a9af56daaa2cd8bbcad",
Entropy: 5.9834013,
Author: "James Bond",
Email: "jbond@gov.co.uk",
Date: "2025-03-02T15:10:40Z",
Message: "init",
Fingerprint: "6d3ba1f7653822c0f8ac9a9af56daaa2cd8bbcad:key.txt:private-key:1",
},
baseline: []report.Finding{
{
RuleID: "private-key",
Description: "Identified a Private Key, which may compromise cryptographic security and sensitive data encryption.",
StartLine: 1,
EndLine: 15,
StartColumn: 1,
EndColumn: 30,
Match: "-----BEGIN RSA PRIVATE KEY-----\nMIICWgIBAAKBgFIckgeuo80H6skLd1FKYfJC75/tnmtDWO4Rf2AFqrYZdu71VKGR\noGfEVl7AmvxTd9u6tnPtWjAeu9k2VMQcOtXEwgU0A6H09EBcS1EVN/I8pcNw1qjO\nkJ7ZA8AhZk/OpVAK7665CEny7ISRNZnx1nPaHjlb8lebPzlWOvxX9wjbAgMBAAEC\ngYBN6wqv+4s4juC/cwAAxeL4L4iQbL497yS+lSAYEIiUUMnJrEhpIXXjwi5rr73i\n35oHisCEdaF1tFRxpNr/VgKFsM1KqQUZvCVRE9Rokfe23QkQDvcxh9CI/Ah9Eofp\nx/m5DjSsRKrbIpOOAC3J3B/s02HRmxy8tRYnQVqWXzAH8QJBAJdBgXi62KI1eytU\n7l3Q8ymkS1OHzSOGBEYPpZZQ7WRpZlv/06cKfJBT/dGgA4z9i9ySs8cWUoh+FGYX\nlkDB4c0CQQCK+TwfAFvrkSWorZ9Gjb6y2LZQPUufTzJNhzhK5XObCDbwyMXEM/Vs\newiyUFljlI/A9PjcrmkgrDLUMD4+og1HAkAs2t01W1uhBvEm0YH6yltCDxnThKM+\nFKEx0bQOVqN/so4LXFt83uw/tNjBkI1dA1e1qr+rm6AQICuWdwo03ApFAkBktes4\nuCTk2GHHFFM5aN0KdHviOBlGULkub9B+jjsx3UkbQxP2dITlYV/TAOFWhcGLXru+\nCPKMR93p4TAqaXtfAkA+ZZDb0mA9rtaetJlSoo6XgwI/+kqltADch9dcyqYBHwjr\nAEkzUKvmCxNAK4GEPA79FZFp30kDx+buysyeX9qY\n-----END RSA PRIVATE KEY-----",
Secret: "-----BEGIN RSA PRIVATE KEY-----\nMIICWgIBAAKBgFIckgeuo80H6skLd1FKYfJC75/tnmtDWO4Rf2AFqrYZdu71VKGR\noGfEVl7AmvxTd9u6tnPtWjAeu9k2VMQcOtXEwgU0A6H09EBcS1EVN/I8pcNw1qjO\nkJ7ZA8AhZk/OpVAK7665CEny7ISRNZnx1nPaHjlb8lebPzlWOvxX9wjbAgMBAAEC\ngYBN6wqv+4s4juC/cwAAxeL4L4iQbL497yS+lSAYEIiUUMnJrEhpIXXjwi5rr73i\n35oHisCEdaF1tFRxpNr/VgKFsM1KqQUZvCVRE9Rokfe23QkQDvcxh9CI/Ah9Eofp\nx/m5DjSsRKrbIpOOAC3J3B/s02HRmxy8tRYnQVqWXzAH8QJBAJdBgXi62KI1eytU\n7l3Q8ymkS1OHzSOGBEYPpZZQ7WRpZlv/06cKfJBT/dGgA4z9i9ySs8cWUoh+FGYX\nlkDB4c0CQQCK+TwfAFvrkSWorZ9Gjb6y2LZQPUufTzJNhzhK5XObCDbwyMXEM/Vs\newiyUFljlI/A9PjcrmkgrDLUMD4+og1HAkAs2t01W1uhBvEm0YH6yltCDxnThKM+\nFKEx0bQOVqN/so4LXFt83uw/tNjBkI1dA1e1qr+rm6AQICuWdwo03ApFAkBktes4\nuCTk2GHHFFM5aN0KdHviOBlGULkub9B+jjsx3UkbQxP2dITlYV/TAOFWhcGLXru+\nCPKMR93p4TAqaXtfAkA+ZZDb0mA9rtaetJlSoo6XgwI/+kqltADch9dcyqYBHwjr\nAEkzUKvmCxNAK4GEPA79FZFp30kDx+buysyeX9qY\n-----END RSA PRIVATE KEY-----",
File: "key.txt",
Commit: "e55e00ca1690a6b5b612d28b3d9ada3fd1775ac4",
Entropy: 5.9834013,
Author: "James Bond",
Email: "jbond@gov.co.uk",
Date: "2025-02-02T17:45:30Z",
Message: "init",
Fingerprint: "e55e00ca1690a6b5b612d28b3d9ada3fd1775ac4:key.txt:private-key:1",
},
},
expect: true,
},
// not new
"not new - commit+author matches": {
findings: report.Finding{
Author: "a",
Commit: "0000",
Author: "a",
},
baseline: []report.Finding{
{
Commit: "0000",
Author: "a",
},
},
expect: false,
},
"not new - commit+author matches, tags ignored": {
findings: report.Finding{
Commit: "0000",
Author: "a",
Tags: []string{"a", "b"},
},
baseline: []report.Finding{
{
Author: "a",
Commit: "0000",
Author: "a",
Tags: []string{"a", "c"},
},
},
expect: false, // Updated tags doesn't make it a new finding
},
"not new - redacted, everything else matches": {
findings: report.Finding{
RuleID: "private-key",
Description: "Identified a Private Key, which may compromise cryptographic security and sensitive data encryption.",
StartLine: 1,
EndLine: 15,
StartColumn: 1,
EndColumn: 30,
Match: "REDACTED",
Secret: "REDACTED",
File: "key.txt",
Commit: "e55e00ca1690a6b5b612d28b3d9ada3fd1775ac4",
Entropy: 5.9834013,
Author: "James Bond",
Email: "jbond@gov.co.uk",
Date: "2025-02-02T17:45:30Z",
Message: "init",
Fingerprint: "e55e00ca1690a6b5b612d28b3d9ada3fd1775ac4:key.txt:private-key:1",
},
redact: 100,
baseline: []report.Finding{
{
RuleID: "private-key",
Description: "Identified a Private Key, which may compromise cryptographic security and sensitive data encryption.",
StartLine: 1,
EndLine: 15,
StartColumn: 1,
EndColumn: 30,
Match: "-----BEGIN RSA PRIVATE KEY-----\nMIICWgIBAAKBgFIckgeuo80H6skLd1FKYfJC75/tnmtDWO4Rf2AFqrYZdu71VKGR\noGfEVl7AmvxTd9u6tnPtWjAeu9k2VMQcOtXEwgU0A6H09EBcS1EVN/I8pcNw1qjO\nkJ7ZA8AhZk/OpVAK7665CEny7ISRNZnx1nPaHjlb8lebPzlWOvxX9wjbAgMBAAEC\ngYBN6wqv+4s4juC/cwAAxeL4L4iQbL497yS+lSAYEIiUUMnJrEhpIXXjwi5rr73i\n35oHisCEdaF1tFRxpNr/VgKFsM1KqQUZvCVRE9Rokfe23QkQDvcxh9CI/Ah9Eofp\nx/m5DjSsRKrbIpOOAC3J3B/s02HRmxy8tRYnQVqWXzAH8QJBAJdBgXi62KI1eytU\n7l3Q8ymkS1OHzSOGBEYPpZZQ7WRpZlv/06cKfJBT/dGgA4z9i9ySs8cWUoh+FGYX\nlkDB4c0CQQCK+TwfAFvrkSWorZ9Gjb6y2LZQPUufTzJNhzhK5XObCDbwyMXEM/Vs\newiyUFljlI/A9PjcrmkgrDLUMD4+og1HAkAs2t01W1uhBvEm0YH6yltCDxnThKM+\nFKEx0bQOVqN/so4LXFt83uw/tNjBkI1dA1e1qr+rm6AQICuWdwo03ApFAkBktes4\nuCTk2GHHFFM5aN0KdHviOBlGULkub9B+jjsx3UkbQxP2dITlYV/TAOFWhcGLXru+\nCPKMR93p4TAqaXtfAkA+ZZDb0mA9rtaetJlSoo6XgwI/+kqltADch9dcyqYBHwjr\nAEkzUKvmCxNAK4GEPA79FZFp30kDx+buysyeX9qY\n-----END RSA PRIVATE KEY-----",
Secret: "-----BEGIN RSA PRIVATE KEY-----\nMIICWgIBAAKBgFIckgeuo80H6skLd1FKYfJC75/tnmtDWO4Rf2AFqrYZdu71VKGR\noGfEVl7AmvxTd9u6tnPtWjAeu9k2VMQcOtXEwgU0A6H09EBcS1EVN/I8pcNw1qjO\nkJ7ZA8AhZk/OpVAK7665CEny7ISRNZnx1nPaHjlb8lebPzlWOvxX9wjbAgMBAAEC\ngYBN6wqv+4s4juC/cwAAxeL4L4iQbL497yS+lSAYEIiUUMnJrEhpIXXjwi5rr73i\n35oHisCEdaF1tFRxpNr/VgKFsM1KqQUZvCVRE9Rokfe23QkQDvcxh9CI/Ah9Eofp\nx/m5DjSsRKrbIpOOAC3J3B/s02HRmxy8tRYnQVqWXzAH8QJBAJdBgXi62KI1eytU\n7l3Q8ymkS1OHzSOGBEYPpZZQ7WRpZlv/06cKfJBT/dGgA4z9i9ySs8cWUoh+FGYX\nlkDB4c0CQQCK+TwfAFvrkSWorZ9Gjb6y2LZQPUufTzJNhzhK5XObCDbwyMXEM/Vs\newiyUFljlI/A9PjcrmkgrDLUMD4+og1HAkAs2t01W1uhBvEm0YH6yltCDxnThKM+\nFKEx0bQOVqN/so4LXFt83uw/tNjBkI1dA1e1qr+rm6AQICuWdwo03ApFAkBktes4\nuCTk2GHHFFM5aN0KdHviOBlGULkub9B+jjsx3UkbQxP2dITlYV/TAOFWhcGLXru+\nCPKMR93p4TAqaXtfAkA+ZZDb0mA9rtaetJlSoo6XgwI/+kqltADch9dcyqYBHwjr\nAEkzUKvmCxNAK4GEPA79FZFp30kDx+buysyeX9qY\n-----END RSA PRIVATE KEY-----",
File: "key.txt",
Commit: "e55e00ca1690a6b5b612d28b3d9ada3fd1775ac4",
Entropy: 5.9834013,
Author: "James Bond",
Email: "jbond@gov.co.uk",
Date: "2025-02-02T17:45:30Z",
Message: "init",
Fingerprint: "e55e00ca1690a6b5b612d28b3d9ada3fd1775ac4:key.txt:private-key:1",
},
},
expect: false,
},
}
for _, test := range tests {
assert.Equal(t, test.expect, IsNew(test.findings, test.baseline))
for name, test := range tests {
t.Run(name, func(t *testing.T) {
assert.Equal(t, test.expect, IsNew(test.findings, test.redact, test.baseline))
})
}
}
func TestFileLoadBaseline(t *testing.T) {
t.Parallel()
tests := []struct {
Filename string
ExpectedError error
@@ -89,6 +180,7 @@ func TestFileLoadBaseline(t *testing.T) {
}
func TestIgnoreIssuesInBaseline(t *testing.T) {
t.Parallel()
tests := []struct {
findings []report.Finding
baseline []report.Finding
+34
View File
@@ -0,0 +1,34 @@
package codec
var printableASCII [256]bool
func init() {
for b := 0; b < len(printableASCII); b++ {
if '\x08' < b && b < '\x7f' {
printableASCII[b] = true
}
}
}
// isPrintableASCII returns true if all bytes are printable ASCII
func isPrintableASCII(b []byte) bool {
for _, c := range b {
if !printableASCII[c] {
return false
}
}
return true
}
// hasByte can be used to check if a string has at least one of the provided
// bytes. Note: make sure byteset is long enough to handle the largest byte in
// the string.
func hasByte(data string, byteset []bool) bool {
for i := 0; i < len(data); i++ {
if byteset[data[i]] {
return true
}
}
return false
}
+39
View File
@@ -0,0 +1,39 @@
package codec
import (
"encoding/base64"
)
// likelyBase64Chars is a set of characters that you would expect to find at
// least one of in base64 encoded data. This risks missing about 1% of
// base64 encoded data that doesn't contain these characters, but gives you
// the performance gain of not trying to decode a lot of long symbols in code.
var likelyBase64Chars = make([]bool, 256)
func init() {
for _, c := range `0123456789+/-_` {
likelyBase64Chars[c] = true
}
}
// decodeBase64 decodes base64 encoded printable ASCII characters
func decodeBase64(encodedValue string) string {
// Exit early if it doesn't seem like base64
if !hasByte(encodedValue, likelyBase64Chars) {
return ""
}
// Try standard base64 decoding
decodedValue, err := base64.StdEncoding.DecodeString(encodedValue)
if err == nil && isPrintableASCII(decodedValue) {
return string(decodedValue)
}
// Try base64url decoding
decodedValue, err = base64.RawURLEncoding.DecodeString(encodedValue)
if err == nil && isPrintableASCII(decodedValue) {
return string(decodedValue)
}
return ""
}
+105
View File
@@ -0,0 +1,105 @@
package codec
import (
"bytes"
"github.com/zricethezav/gitleaks/v8/logging"
)
// Decoder decodes various types of data in place
type Decoder struct {
decodedMap map[string]string
}
// NewDecoder creates a default decoder struct
func NewDecoder() *Decoder {
return &Decoder{
decodedMap: make(map[string]string),
}
}
// Decode returns the data with the values decoded in place along with the
// encoded segment meta data for the next pass of decoding
func (d *Decoder) Decode(data string, predecessors []*EncodedSegment) (string, []*EncodedSegment) {
segments := d.findEncodedSegments(data, predecessors)
if len(segments) > 0 {
result := bytes.NewBuffer(make([]byte, 0, len(data)))
encodedStart := 0
for _, segment := range segments {
result.WriteString(data[encodedStart:segment.encoded.start])
result.WriteString(segment.decodedValue)
encodedStart = segment.encoded.end
}
result.WriteString(data[encodedStart:])
return result.String(), segments
}
return data, segments
}
// findEncodedSegments finds the encoded segments in the data
func (d *Decoder) findEncodedSegments(data string, predecessors []*EncodedSegment) []*EncodedSegment {
if len(data) == 0 {
return []*EncodedSegment{}
}
decodedShift := 0
encodingMatches := findEncodingMatches(data)
segments := make([]*EncodedSegment, 0, len(encodingMatches))
for _, m := range encodingMatches {
encodedValue := data[m.start:m.end]
decodedValue, alreadyDecoded := d.decodedMap[encodedValue]
if !alreadyDecoded {
decodedValue = m.encoding.decode(encodedValue)
d.decodedMap[encodedValue] = decodedValue
}
if len(decodedValue) == 0 {
continue
}
segment := &EncodedSegment{
predecessors: predecessors,
original: toOriginal(predecessors, m.startEnd),
encoded: m.startEnd,
decoded: startEnd{
m.start + decodedShift,
m.start + decodedShift + len(decodedValue),
},
decodedValue: decodedValue,
encodings: m.encoding.kind,
depth: 1,
}
// Shift decoded start and ends based on size changes
decodedShift += len(decodedValue) - len(encodedValue)
// Adjust depth and encoding if applicable
if len(segment.predecessors) != 0 {
// Set the depth based on the predecessors' depth in the previous pass
segment.depth = 1 + segment.predecessors[0].depth
// Adjust encodings
for _, p := range segment.predecessors {
if segment.encoded.overlaps(p.decoded) {
segment.encodings |= p.encodings
}
}
}
segments = append(segments, segment)
logging.Debug().
Str("decoder", m.encoding.kind.String()).
Msgf(
"segment found: original=%s pos=%s: %q -> %q",
segment.original,
segment.encoded,
encodedValue,
segment.decodedValue,
)
}
return segments
}
@@ -1,6 +1,8 @@
package detect
package codec
import (
"encoding/hex"
"net/url"
"testing"
"github.com/stretchr/testify/assert"
@@ -66,8 +68,8 @@ func TestDecode(t *testing.T) {
},
{
name: "b64-url-safe: hyphen url b64",
chunk: `dHJ1ZmZsZWhvZz4-ZmluZHMtc2VjcmV0cw`,
expected: `trufflehog>>finds-secrets`,
chunk: `Z2l0bGVha3M-PmZpbmRzLXNlY3JldHM`,
expected: `gitleaks>>finds-secrets`,
},
{
name: "b64-url-safe: underscore url b64",
@@ -79,13 +81,64 @@ func TestDecode(t *testing.T) {
chunk: `a3d3fa7c2bb99e469ba55e5834ce79ee4853a8a3`,
expected: `a3d3fa7c2bb99e469ba55e5834ce79ee4853a8a3`,
},
{
name: "url encoded value",
chunk: `secret%3D%22q%24%21%40%23%24%25%5E%26%2A%28%20asdf%22`,
expected: `secret="q$!@#$%^&*( asdf"`,
},
{
name: "hex encoded value",
chunk: `secret="466973684D617048756E6B79212121363334"`,
expected: `secret="FishMapHunky!!!634"`,
},
{
name: "unicode encoded value",
chunk: `secret=U+0061 U+0062 U+0063 U+0064 U+0065 U+0066`,
expected: "secret=abcdef",
},
{
name: "unicode encoded value backslashed",
chunk: `secret=\\u0068\\u0065\\u006c\\u006c\\u006f\\u0020\\u0077\\u006f\\u0072\\u006c\\u0064\\u0020\\u0064\\u0075\\u0064\\u0065`,
expected: "secret=hello world dude",
},
{
name: "unicode encoded value backslashed mixed w/ hex",
chunk: `secret=\u0068\u0065\u006c\u006c\u006f\u0020\u0077\u006f\u0072\u006c\u0064 6C6F76656C792070656F706C65206F66206561727468`,
expected: "secret=hello world lovely people of earth",
},
}
decoder := NewDecoder()
fullDecode := func(data string) string {
segments := []*EncodedSegment{}
for {
data, segments = decoder.Decode(data, segments)
if len(segments) == 0 {
return data
}
}
}
// Test value decoding
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
decoded, _ := decoder.decode(tt.chunk, []EncodedSegment{})
assert.Equal(t, tt.expected, decoded)
assert.Equal(t, tt.expected, fullDecode(tt.chunk))
})
}
// Percent encode the values to test percent decoding
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
encodedChunk := url.PathEscape(tt.chunk)
assert.Equal(t, tt.expected, fullDecode(encodedChunk))
})
}
// Hex encode the values to test hex decoding
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
encodedChunk := hex.EncodeToString([]byte(tt.chunk))
assert.Equal(t, tt.expected, fullDecode(encodedChunk))
})
}
}
+161
View File
@@ -0,0 +1,161 @@
package codec
import (
"fmt"
"math"
"strings"
"github.com/zricethezav/gitleaks/v8/regexp"
)
var (
// encodingsRe is a regex built by combining all the encoding patterns
// into named capture groups so that a single pass can detect multiple
// encodings
encodingsRe *regexp.Regexp
// encodings contains all the encoding configurations for the detector.
// The precedence is important. You want more specific encodings to
// have a higher precedence or encodings that partially encode the
// values (e.g. percent) unlike encodings that fully encode the string
// (e.g. base64). If two encoding matches overlap the decoder will use
// this order to determine which encoding should wait till the next pass.
encodings = []*encoding{
{
kind: percentKind,
pattern: `%[0-9A-Fa-f]{2}(?:.*%[0-9A-Fa-f]{2})?`,
decode: decodePercent,
},
{
kind: unicodeKind,
pattern: `(?:(?:U\+[a-fA-F0-9]{4}(?:\s|$))+|(?i)(?:\\{1,2}u[a-fA-F0-9]{4})+)`,
decode: decodeUnicode,
},
{
kind: hexKind,
pattern: `[0-9A-Fa-f]{32,}`,
decode: decodeHex,
},
{
kind: base64Kind,
pattern: `[\w\/+-]{16,}={0,2}`,
decode: decodeBase64,
},
}
)
// encodingNames is used to map the encodingKinds to their name
var encodingNames = []string{
"percent",
"unicode",
"hex",
"base64",
}
// encodingKind can be or'd together to capture all of the unique encodings
// that were present in a segment
type encodingKind int
var (
// make sure these go up by powers of 2
percentKind = encodingKind(1)
unicodeKind = encodingKind(2)
hexKind = encodingKind(4)
base64Kind = encodingKind(8)
)
func (e encodingKind) String() string {
i := int(math.Log2(float64(e)))
if i >= len(encodingNames) {
return ""
}
return encodingNames[i]
}
// kinds returns a list of encodingKinds combined in this one
func (e encodingKind) kinds() []encodingKind {
kinds := []encodingKind{}
for i := 0; i < len(encodingNames); i++ {
if kind := int(e) & int(math.Pow(2, float64(i))); kind != 0 {
kinds = append(kinds, encodingKind(kind))
}
}
return kinds
}
// encodingMatch represents a match of an encoding in the text
type encodingMatch struct {
encoding *encoding
startEnd
}
// encoding represent a type of coding supported by the decoder.
type encoding struct {
// the kind of decoding (e.g. base64, etc)
kind encodingKind
// the regex pattern that matches the encoding format
pattern string
// take the match and return the decoded value
decode func(string) string
// determine which encoding should win out when two overlap
precedence int
}
func init() {
count := len(encodings)
namedPatterns := make([]string, count)
for i, encoding := range encodings {
encoding.precedence = count - i
namedPatterns[i] = fmt.Sprintf(
"(?P<%s>%s)",
encoding.kind,
encoding.pattern,
)
}
encodingsRe = regexp.MustCompile(strings.Join(namedPatterns, "|"))
}
// findEncodingMatches finds as many encodings as it can for this pass
func findEncodingMatches(data string) []encodingMatch {
var all []encodingMatch
for _, matchIndex := range encodingsRe.FindAllStringSubmatchIndex(data, -1) {
// Add the encodingMatch with its proper encoding
for i, j := 2, 0; i < len(matchIndex); i, j = i+2, j+1 {
if matchIndex[i] > -1 {
all = append(all, encodingMatch{
encoding: encodings[j],
startEnd: startEnd{
start: matchIndex[i],
end: matchIndex[i+1],
},
})
}
}
}
totalMatches := len(all)
if totalMatches == 1 {
return all
}
// filter out lower precedence ones that overlap their neigbors
filtered := make([]encodingMatch, 0, len(all))
for i, m := range all {
if i > 0 {
prev := all[i-1]
if m.overlaps(prev.startEnd) && prev.encoding.precedence > m.encoding.precedence {
continue // skip this one
}
}
if i+1 < totalMatches {
next := all[i+1]
if m.overlaps(next.startEnd) && next.encoding.precedence > m.encoding.precedence {
continue // skip this one
}
}
filtered = append(filtered, m)
}
return filtered
}
+60
View File
@@ -0,0 +1,60 @@
package codec
// hexMap is a precalculated map of hex nibbles
const hexMap = "" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\xff\xff\xff\xff\xff\xff" +
"\xff\x0a\x0b\x0c\x0d\x0e\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\x0a\x0b\x0c\x0d\x0e\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff"
// likelyHexChars is a set of characters that you would expect to find at
// least one of in hex encoded data. This risks missing some hex data that
// doesn't contain these characters, but gives you the performance gain of not
// trying to decode a lot of long symbols in code.
var likelyHexChars = make([]bool, 256)
func init() {
for _, c := range `0123456789` {
likelyHexChars[c] = true
}
}
// decodeHex decodes hex data
func decodeHex(encodedValue string) string {
size := len(encodedValue)
// hex should have two characters per byte
if size%2 != 0 {
return ""
}
if !hasByte(encodedValue, likelyHexChars) {
return ""
}
decodedValue := make([]byte, size/2)
for i := 0; i < size; i += 2 {
n1 := hexMap[encodedValue[i]]
n2 := hexMap[encodedValue[i+1]]
if n1|n2 == '\xff' {
return ""
}
b := n1<<4 | n2
if !printableASCII[b] {
return ""
}
decodedValue[i/2] = b
}
return string(decodedValue)
}
+34
View File
@@ -0,0 +1,34 @@
package codec
// decodePercent decodes percent encoded strings
func decodePercent(encodedValue string) string {
encLen := len(encodedValue)
decodedValue := make([]byte, encLen)
decIndex := 0
encIndex := 0
for encIndex < encLen {
if encodedValue[encIndex] == '%' && encIndex+2 < encLen {
n1 := hexMap[encodedValue[encIndex+1]]
n2 := hexMap[encodedValue[encIndex+2]]
// Make sure they're hex characters
if n1|n2 != '\xff' {
b := n1<<4 | n2
if !printableASCII[b] {
return ""
}
decodedValue[decIndex] = b
encIndex += 3
decIndex += 1
continue
}
}
decodedValue[decIndex] = encodedValue[encIndex]
encIndex += 1
decIndex += 1
}
return string(decodedValue[:decIndex])
}
+173
View File
@@ -0,0 +1,173 @@
package codec
import (
"fmt"
)
// EncodedSegment represents a portion of text that is encoded in some way.
type EncodedSegment struct {
// predecessors are all of the segments from the previous decoding pass
predecessors []*EncodedSegment
// original start/end indices before decoding
original startEnd
// encoded start/end indices relative to the previous decoding pass.
// If it's a top level segment, original and encoded will be the
// same.
encoded startEnd
// decoded start/end indices in this pass after decoding
decoded startEnd
// decodedValue contains the decoded string for this segment
decodedValue string
// encodings is the encodings that make up this segment. encodingKind
// can be or'd together to hold multiple encodings
encodings encodingKind
// depth is how many decoding passes it took to decode this segment
depth int
}
// Tags returns additional meta data tags related to the types of segments
func Tags(segments []*EncodedSegment) []string {
// Return an empty list if we don't have any segments
if len(segments) == 0 {
return []string{}
}
// Since decoding is done in passes, the depth of all the segments
// should be the same
depth := segments[0].depth
// Collect the encodings from the segments
encodings := segments[0].encodings
for i := 1; i < len(segments); i++ {
encodings |= segments[i].encodings
}
kinds := encodings.kinds()
tags := make([]string, len(kinds)+1)
tags[len(tags)-1] = fmt.Sprintf("decode-depth:%d", depth)
for i, kind := range kinds {
tags[i] = fmt.Sprintf("decoded:%s", kind)
}
return tags
}
// CurrentLine returns from the start of the line containing the segments
// to the end of the line where the segment ends.
func CurrentLine(segments []*EncodedSegment, currentRaw string) string {
// Return the whole thing if no segments are provided
if len(segments) == 0 {
return currentRaw
}
start := 0
end := len(currentRaw)
// Merge the ranges together into a single decoded value
decoded := segments[0].decoded
for i := 1; i < len(segments); i++ {
decoded = decoded.merge(segments[i].decoded)
}
// Find the start of the range
for i := decoded.start; i > -1; i-- {
c := currentRaw[i]
if c == '\n' {
start = i
break
}
}
// Find the end of the range
for i := decoded.end; i < end; i++ {
c := currentRaw[i]
if c == '\n' {
end = i
break
}
}
return currentRaw[start:end]
}
// AdjustMatchIndex maps a match index from the current decode pass back to
// its location in the original text
func AdjustMatchIndex(segments []*EncodedSegment, matchIndex []int) []int {
// Don't adjust if we're not provided any segments
if len(segments) == 0 {
return matchIndex
}
// Map the match to the location in the original text
match := startEnd{matchIndex[0], matchIndex[1]}
// Map the match to its orignal location
adjusted := toOriginal(segments, match)
// Return the adjusted match index
return []int{
adjusted.start,
adjusted.end,
}
}
// SegmentsWithDecodedOverlap the segments where the start and end overlap its
// decoded range
func SegmentsWithDecodedOverlap(segments []*EncodedSegment, start, end int) []*EncodedSegment {
se := startEnd{start, end}
overlaps := []*EncodedSegment{}
for _, segment := range segments {
if segment.decoded.overlaps(se) {
overlaps = append(overlaps, segment)
}
}
return overlaps
}
// toOriginal maps a start/end to its start/end in the original text
// the provided start/end should be relative to the segment's decoded value
func toOriginal(predecessors []*EncodedSegment, decoded startEnd) startEnd {
if len(predecessors) == 0 {
return decoded
}
// Map the decoded value one level up where it was encoded
encoded := startEnd{}
for _, p := range predecessors {
if !p.decoded.overlaps(decoded) {
continue // Not in scope
}
// If fully contained, return the segments original start/end
if p.decoded.contains(decoded) {
return p.original
}
// Map the value to be relative to the predecessors's decoded values
if encoded.end == 0 {
encoded = p.encoded.add(p.decoded.overflow(decoded))
} else {
encoded = encoded.merge(p.encoded.add(p.decoded.overflow(decoded)))
}
}
// Should only get here if the thing passed in wasn't in a decoded
// value. This shouldn't be the case
if encoded.end == 0 {
return decoded
}
// Climb up another level
// (NOTE: each segment references all the predecessors)
return toOriginal(predecessors[0].predecessors, encoded)
}
+57
View File
@@ -0,0 +1,57 @@
package codec
import (
"fmt"
)
// startEnd represents the start and end of some data. It mainly exists as a
// helper when referencing the values
type startEnd struct {
start int
end int
}
// sub subtracts the values of two startEnds
func (s startEnd) sub(o startEnd) startEnd {
return startEnd{
s.start - o.start,
s.end - o.end,
}
}
// add adds the values of two startEnds
func (s startEnd) add(o startEnd) startEnd {
return startEnd{
s.start + o.start,
s.end + o.end,
}
}
// overlaps returns true if two startEnds overlap
func (s startEnd) overlaps(o startEnd) bool {
return o.start <= s.end && o.end >= s.start
}
// contains returns true if the other is fully contained within this one
func (s startEnd) contains(o startEnd) bool {
return s.start <= o.start && o.end <= s.end
}
// overflow returns a startEnd that tells how much the other goes outside the
// bounds of this one
func (s startEnd) overflow(o startEnd) startEnd {
return s.merge(o).sub(s)
}
// merge takes two start/ends and returns a single one that encompasses both
func (s startEnd) merge(o startEnd) startEnd {
return startEnd{
min(s.start, o.start),
max(s.end, o.end),
}
}
// String returns a string representation for clearer debugging
func (s startEnd) String() string {
return fmt.Sprintf("[%d,%d]", s.start, s.end)
}
+261
View File
@@ -0,0 +1,261 @@
package codec
import (
"bytes"
"strconv"
"strings"
"unicode/utf8"
"github.com/zricethezav/gitleaks/v8/regexp"
)
var (
// Standard Unicode notation (e.g., U+1234)
unicodeCodePointPat = regexp.MustCompile(`U\+([a-fA-F0-9]{4}).?`)
// Multiple code points pattern - used for continuous sequences like "U+0074 U+006F U+006B..."
unicodeMultiCodePointPat = regexp.MustCompile(`(?:U\+[a-fA-F0-9]{4}(?:\s|$))+`)
// Common escape sequence used in programming languages (e.g., \u1234)
unicodeEscapePat = regexp.MustCompile(`(?i)\\{1,2}u([a-fA-F0-9]{4})`)
// Multiple escape sequences pattern - used for continuous sequences like "\u0074\u006F\u006B..."
unicodeMultiEscapePat = regexp.MustCompile(`(?i)(?:\\{1,2}u[a-fA-F0-9]{4})+`)
)
// Unicode characters are encoded as 1 to 4 bytes per rune.
const maxBytesPerRune = 4
// decodeUnicode decodes Unicode escape sequences in the given string
func decodeUnicode(encodedValue string) string {
// First, check if we have a continuous sequence of Unicode code points
if matches := unicodeMultiCodePointPat.FindAllString(encodedValue, -1); len(matches) > 0 {
// For each detected sequence of code points
for _, match := range matches {
// Decode the entire sequence at once
decodedSequence := decodeMultiCodePoint(match)
// If we successfully decoded something, replace it in the original string
if decodedSequence != "" && decodedSequence != match {
encodedValue = strings.Replace(encodedValue, match, decodedSequence, 1)
}
}
return encodedValue
}
// Next, check if we have a continuous sequence of escape sequences
if matches := unicodeMultiEscapePat.FindAllString(encodedValue, -1); len(matches) > 0 {
// For each detected sequence of escape sequences
for _, match := range matches {
// Decode the entire sequence at once
decodedSequence := decodeMultiEscape(match)
// If we successfully decoded something, replace it in the original string
if decodedSequence != "" && decodedSequence != match {
encodedValue = strings.Replace(encodedValue, match, decodedSequence, 1)
}
}
return encodedValue
}
// If no multi-patterns were matched, fall back to the original implementation
// for individual code points and escape sequences
// Create a copy of the input to work with
data := []byte(encodedValue)
// Store the result
var result []byte
// Check and decode Unicode code points (U+1234 format)
if unicodeCodePointPat.Match(data) {
result = decodeIndividualCodePoints(data)
}
// If no code points were found or we have a mix of formats,
// also check for Unicode escape sequences (\u1234 format)
if len(result) == 0 || unicodeEscapePat.Match(data) {
// If we already have some result from code point decoding,
// continue decoding escape sequences on that result
if len(result) > 0 {
result = decodeIndividualEscapes(result)
} else {
result = decodeIndividualEscapes(data)
}
}
// If nothing was decoded, return original string
if len(result) == 0 || bytes.Equal(result, data) {
return encodedValue
}
return string(result)
}
// decodeMultiCodePoint decodes a continuous sequence of Unicode code points (U+XXXX format)
func decodeMultiCodePoint(sequence string) string {
// If the sequence is empty, return empty string
if sequence == "" {
return ""
}
// Split the sequence by whitespace to get individual code points
codePoints := strings.Fields(sequence)
if len(codePoints) == 0 {
return sequence
}
// Decode each code point and build the result
var decodedRunes []rune
for _, cp := range codePoints {
// Check if it follows the U+XXXX pattern
if !strings.HasPrefix(cp, "U+") || len(cp) < 6 {
continue
}
// Extract the hexadecimal value
hexValue := cp[2:]
// Parse the hexadecimal value to an integer
unicodeInt, err := strconv.ParseInt(hexValue, 16, 32)
if err != nil {
continue
}
// Convert to rune and add to result
decodedRunes = append(decodedRunes, rune(unicodeInt))
}
// If we didn't decode anything, return the original sequence
if len(decodedRunes) == 0 {
return sequence
}
// Return the decoded string
return string(decodedRunes)
}
// decodeMultiEscape decodes a continuous sequence of Unicode escape sequences (\uXXXX format)
func decodeMultiEscape(sequence string) string {
// If the sequence is empty, return empty string
if sequence == "" {
return ""
}
// Find all escape sequences
escapes := unicodeEscapePat.FindAllStringSubmatch(sequence, -1)
if len(escapes) == 0 {
return sequence
}
// Decode each escape sequence and build the result
var decodedRunes []rune
for _, esc := range escapes {
// Extract the hexadecimal value
hexValue := esc[1]
// Parse the hexadecimal value to an integer
unicodeInt, err := strconv.ParseInt(hexValue, 16, 32)
if err != nil {
continue
}
// Convert to rune and add to result
decodedRunes = append(decodedRunes, rune(unicodeInt))
}
// If we didn't decode anything, return the original sequence
if len(decodedRunes) == 0 {
return sequence
}
// Return the decoded string
return string(decodedRunes)
}
// decodeIndividualCodePoints decodes individual Unicode code points (U+1234 format)
// This is a fallback for when we don't have a continuous sequence of code points
func decodeIndividualCodePoints(input []byte) []byte {
// Find all Unicode code point sequences in the input byte slice
indices := unicodeCodePointPat.FindAllSubmatchIndex(input, -1)
// If none found, return original input
if len(indices) == 0 {
return input
}
// Iterate over found indices in reverse order to avoid modifying the slice length
utf8Bytes := make([]byte, maxBytesPerRune)
for i := len(indices) - 1; i >= 0; i-- {
matches := indices[i]
startIndex := matches[0]
endIndex := matches[1]
hexStartIndex := matches[2]
hexEndIndex := matches[3]
// If the input is like `U+1234 U+5678` we should replace `U+1234 `.
// Otherwise, we should only replace `U+1234`.
if endIndex != hexEndIndex && endIndex < len(input) && input[endIndex-1] == ' ' {
endIndex = endIndex - 1
}
// Extract the hexadecimal value from the escape sequence
hexValue := string(input[hexStartIndex:hexEndIndex])
// Parse the hexadecimal value to an integer
unicodeInt, err := strconv.ParseInt(hexValue, 16, 32)
if err != nil {
// If there's an error, continue to the next escape sequence
continue
}
// Convert the Unicode code point to a UTF-8 representation
utf8Len := utf8.EncodeRune(utf8Bytes, rune(unicodeInt))
// Replace the escape sequence with the UTF-8 representation
input = append(input[:startIndex], append(utf8Bytes[:utf8Len], input[endIndex:]...)...)
}
return input
}
// decodeIndividualEscapes decodes individual Unicode escape sequences (\u1234 format)
// This is a fallback for when we don't have a continuous sequence of escape sequences
func decodeIndividualEscapes(input []byte) []byte {
// Find all Unicode escape sequences in the input byte slice
indices := unicodeEscapePat.FindAllSubmatchIndex(input, -1)
// If none found, return original input
if len(indices) == 0 {
return input
}
// Iterate over found indices in reverse order to avoid modifying the slice length
utf8Bytes := make([]byte, maxBytesPerRune)
for i := len(indices) - 1; i >= 0; i-- {
matches := indices[i]
startIndex := matches[0]
hexStartIndex := matches[2]
endIndex := matches[3]
// Extract the hexadecimal value from the escape sequence
hexValue := string(input[hexStartIndex:endIndex])
// Parse the hexadecimal value to an integer
unicodeInt, err := strconv.ParseInt(hexValue, 16, 32)
if err != nil {
// If there's an error, continue to the next escape sequence
continue
}
// Convert the Unicode code point to a UTF-8 representation
utf8Len := utf8.EncodeRune(utf8Bytes, rune(unicodeInt))
// Replace the escape sequence with the UTF-8 representation
input = append(input[:startIndex], append(utf8Bytes[:utf8Len], input[endIndex:]...)...)
}
return input
}
-306
View File
@@ -1,306 +0,0 @@
package detect
import (
"bytes"
"encoding/base64"
"fmt"
"regexp"
"unicode"
"github.com/zricethezav/gitleaks/v8/logging"
)
var b64LikelyChars [128]byte
var b64Regexp = regexp.MustCompile(`[\w/+-]{16,}={0,3}`)
var decoders = []func(string) ([]byte, error){
base64.StdEncoding.DecodeString,
base64.RawURLEncoding.DecodeString,
}
func init() {
// Basically look for anything that isn't just letters
for _, c := range `0123456789+/-_` {
b64LikelyChars[c] = 1
}
}
// EncodedSegment represents a portion of text that is encoded in some way.
// `decode` supports recusive decoding and can result in "segment trees".
// There can be multiple segments in the original text, so each can be thought
// of as its own tree with the root being the original segment.
type EncodedSegment struct {
// The parent segment in a segment tree. If nil, it is a root segment
parent *EncodedSegment
// Relative start/end are the bounds of the encoded value in the current pass.
relativeStart int
relativeEnd int
// Absolute start/end refer to the bounds of the root segment in this segment
// tree
absoluteStart int
absoluteEnd int
// Decoded start/end refer to the bounds of the decoded value in the current
// pass. These can differ from relative values because decoding can shrink
// or grow the size of the segment.
decodedStart int
decodedEnd int
// This is the actual decoded content in the segment
decodedValue string
// This is the type of encoding
encoding string
}
// isChildOf inspects the bounds of two segments to determine
// if one should be the child of another
func (s EncodedSegment) isChildOf(parent EncodedSegment) bool {
return parent.decodedStart <= s.relativeStart && parent.decodedEnd >= s.relativeEnd
}
// decodedOverlaps checks if the decoded bounds of the segment overlaps a range
func (s EncodedSegment) decodedOverlaps(start, end int) bool {
return start <= s.decodedEnd && end >= s.decodedStart
}
// adjustMatchIndex takes the matchIndex from the current decoding pass and
// updates it to match the absolute matchIndex in the original text.
func (s EncodedSegment) adjustMatchIndex(matchIndex []int) []int {
// The match is within the bounds of the segment so we just return
// the absolute start and end of the root segment.
if s.decodedStart <= matchIndex[0] && matchIndex[1] <= s.decodedEnd {
return []int{
s.absoluteStart,
s.absoluteEnd,
}
}
// Since it overlaps one side and/or the other, we're going to have to adjust
// and climb parents until we're either at the root or we've determined
// we're fully inside one of the parent segments.
adjustedMatchIndex := make([]int, 2)
if matchIndex[0] < s.decodedStart {
// It starts before the encoded segment so adjust the start to match
// the location before it was decoded
matchStartDelta := s.decodedStart - matchIndex[0]
adjustedMatchIndex[0] = s.relativeStart - matchStartDelta
} else {
// It starts within the encoded segment so set the bound to the
// relative start
adjustedMatchIndex[0] = s.relativeStart
}
if matchIndex[1] > s.decodedEnd {
// It ends after the encoded segment so adjust the end to match
// the location before it was decoded
matchEndDelta := matchIndex[1] - s.decodedEnd
adjustedMatchIndex[1] = s.relativeEnd + matchEndDelta
} else {
// It ends within the encoded segment so set the bound to the relative end
adjustedMatchIndex[1] = s.relativeEnd
}
// We're still not at a root segment so we'll need to keep on adjusting
if s.parent != nil {
return s.parent.adjustMatchIndex(adjustedMatchIndex)
}
return adjustedMatchIndex
}
// depth reports how many levels of decoding needed to be done (default is 1)
func (s EncodedSegment) depth() int {
depth := 1
// Climb the tree and increment the depth
for current := &s; current.parent != nil; current = current.parent {
depth++
}
return depth
}
// tags returns additional meta data tags related to the types of segments
func (s EncodedSegment) tags() []string {
return []string{
fmt.Sprintf("decoded:%s", s.encoding),
fmt.Sprintf("decode-depth:%d", s.depth()),
}
}
// Decoder decodes various types of data in place
type Decoder struct {
decodedMap map[string]string
}
// NewDecoder creates a default decoder struct
func NewDecoder() *Decoder {
return &Decoder{
decodedMap: make(map[string]string),
}
}
// decode returns the data with the values decoded in-place
func (d *Decoder) decode(data string, parentSegments []EncodedSegment) (string, []EncodedSegment) {
segments := d.findEncodedSegments(data, parentSegments)
if len(segments) > 0 {
result := bytes.NewBuffer(make([]byte, 0, len(data)))
relativeStart := 0
for _, segment := range segments {
result.WriteString(data[relativeStart:segment.relativeStart])
result.WriteString(segment.decodedValue)
relativeStart = segment.relativeEnd
}
result.WriteString(data[relativeStart:])
return result.String(), segments
}
return data, segments
}
// findEncodedSegments finds the encoded segments in the data and updates the
// segment tree for this pass
func (d *Decoder) findEncodedSegments(data string, parentSegments []EncodedSegment) []EncodedSegment {
if len(data) == 0 {
return []EncodedSegment{}
}
matchIndices := b64Regexp.FindAllStringIndex(data, -1)
if matchIndices == nil {
return []EncodedSegment{}
}
segments := make([]EncodedSegment, 0, len(matchIndices))
// Keeps up with offsets from the text changing size as things are decoded
decodedShift := 0
for _, matchIndex := range matchIndices {
encodedValue := data[matchIndex[0]:matchIndex[1]]
if !isLikelyB64(encodedValue) {
d.decodedMap[encodedValue] = ""
continue
}
decodedValue, alreadyDecoded := d.decodedMap[encodedValue]
// We haven't decoded this yet, so go ahead and decode it
if !alreadyDecoded {
decodedValue = decodeValue(encodedValue)
d.decodedMap[encodedValue] = decodedValue
}
// Skip this segment because there was nothing to check
if len(decodedValue) == 0 {
continue
}
// Create a segment for the encoded data
segment := EncodedSegment{
relativeStart: matchIndex[0],
relativeEnd: matchIndex[1],
absoluteStart: matchIndex[0],
absoluteEnd: matchIndex[1],
decodedStart: matchIndex[0] + decodedShift,
decodedEnd: matchIndex[0] + decodedShift + len(decodedValue),
decodedValue: decodedValue,
encoding: "base64",
}
// Shift decoded start and ends based on size changes
decodedShift += len(decodedValue) - len(encodedValue)
// Adjust the absolute position of segments contained in parent segments
for _, parentSegment := range parentSegments {
if segment.isChildOf(parentSegment) {
segment.absoluteStart = parentSegment.absoluteStart
segment.absoluteEnd = parentSegment.absoluteEnd
segment.parent = &parentSegment
break
}
}
logging.Debug().Msgf("segment found: %#v", segment)
segments = append(segments, segment)
}
return segments
}
// decoders tries a list of decoders and returns the first successful one
func decodeValue(encodedValue string) string {
for _, decoder := range decoders {
decodedValue, err := decoder(encodedValue)
if err == nil && len(decodedValue) > 0 && isASCII(decodedValue) {
return string(decodedValue)
}
}
return ""
}
func isASCII(b []byte) bool {
for i := 0; i < len(b); i++ {
if b[i] > unicode.MaxASCII || b[i] < '\t' {
return false
}
}
return true
}
// Skip a lot of method signatures and things at the risk of missing about
// 1% of base64
func isLikelyB64(s string) bool {
for _, c := range s {
if b64LikelyChars[c] != 0 {
return true
}
}
return false
}
// Find a segment where the decoded bounds overlaps a range
func segmentWithDecodedOverlap(encodedSegments []EncodedSegment, start, end int) *EncodedSegment {
for _, segment := range encodedSegments {
if segment.decodedOverlaps(start, end) {
return &segment
}
}
return nil
}
func (s EncodedSegment) currentLine(currentRaw string) string {
start := 0
end := len(currentRaw)
// Find the start of the range
for i := s.decodedStart; i > -1; i-- {
c := currentRaw[i]
if c == '\n' {
start = i
break
}
}
// Find the end of the range
for i := s.decodedEnd; i < end; i++ {
c := currentRaw[i]
if c == '\n' {
end = i
break
}
}
return currentRaw[start:end]
}
+483 -209
View File
@@ -5,15 +5,17 @@ import (
"context"
"fmt"
"os"
"runtime"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/detect/codec"
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/regexp"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
ahocorasick "github.com/BobuSumisu/aho-corasick"
"github.com/fatih/semgroup"
@@ -24,12 +26,13 @@ import (
const (
gitleaksAllowSignature = "gitleaks:allow"
chunkSize = 100 * 1_000 // 100kb
// SlowWarningThreshold is the amount of time to wait before logging that a file is slow.
// This is useful for identifying problematic files and tuning the allowlist.
SlowWarningThreshold = 5 * time.Second
)
var (
newLineRegexp = regexp.MustCompile("\n")
isWindows = runtime.GOOS == "windows"
)
// Detector is the main detector struct
@@ -48,6 +51,9 @@ type Detector struct {
// MaxDecodeDepths limits how many recursive decoding passes are allowed
MaxDecodeDepth int
// MaxArchiveDepth limits how deep the sources will explore nested archives
MaxArchiveDepth int
// files larger than this will be skipped
MaxTargetMegaBytes int
@@ -60,6 +66,10 @@ type Detector struct {
// IgnoreGitleaksAllow is a flag to ignore gitleaks:allow comments.
IgnoreGitleaksAllow bool
// commitMutex is to prevent concurrent access to the
// commit map when adding commits
commitMutex *sync.Mutex
// 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
@@ -96,39 +106,28 @@ type Detector struct {
TotalBytes atomic.Uint64
}
// Fragment contains the data to be scanned
type Fragment struct {
// Raw is the raw content of the fragment
Raw string
Bytes []byte
// FilePath is the path to the file, if applicable.
// The path separator MUST be normalized to `/`.
FilePath string
SymlinkFile string
// WindowsFilePath is the path with the original separator.
// This provides a backwards-compatible solution to https://github.com/gitleaks/gitleaks/issues/1565.
WindowsFilePath string `json:"-"` // TODO: remove this in v9.
// 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
}
// Fragment is an alias for sources.Fragment for backwards compatibility
//
// Deprecated: This will be replaced with sources.Fragment in v9
type Fragment sources.Fragment
// NewDetector creates a new detector with the given config
func NewDetector(cfg config.Config) *Detector {
return NewDetectorContext(context.Background(), cfg)
}
// NewDetectorContext is the same as NewDetector but supports passing in a
// context to use for timeouts
func NewDetectorContext(ctx context.Context, cfg config.Config) *Detector {
return &Detector{
commitMap: make(map[string]bool),
gitleaksIgnore: make(map[string]struct{}),
findingMutex: &sync.Mutex{},
commitMutex: &sync.Mutex{},
findings: make([]report.Finding, 0),
Config: cfg,
prefilter: *ahocorasick.NewTrieBuilder().AddStrings(maps.Keys(cfg.Keywords)).Build(),
Sema: semgroup.NewGroup(context.Background(), 40),
Sema: semgroup.NewGroup(ctx, 40),
}
}
@@ -152,7 +151,7 @@ func NewDetectorDefaultConfig() (*Detector, error) {
}
func (d *Detector) AddGitleaksIgnore(gitleaksIgnorePath string) error {
logging.Debug().Msgf("found .gitleaksignore file: %s", gitleaksIgnorePath)
logging.Debug().Str("path", gitleaksIgnorePath).Msgf("found .gitleaksignore file")
file, err := os.Open(gitleaksIgnorePath)
if err != nil {
return err
@@ -160,7 +159,7 @@ func (d *Detector) AddGitleaksIgnore(gitleaksIgnorePath string) error {
defer func() {
// https://github.com/securego/gosec/issues/512
if err := file.Close(); err != nil {
logging.Warn().Msgf("Error closing .gitleaksignore file: %s\n", err)
logging.Warn().Err(err).Msgf("Error closing .gitleaksignore file")
}
}()
@@ -205,74 +204,163 @@ func (d *Detector) DetectString(content string) []report.Finding {
})
}
// DetectSource scans the given source and returns a list of findings
func (d *Detector) DetectSource(ctx context.Context, source sources.Source) ([]report.Finding, error) {
err := source.Fragments(ctx, func(fragment sources.Fragment, err error) error {
logContext := logging.With()
if len(fragment.FilePath) > 0 {
logContext = logContext.Str("path", fragment.FilePath)
}
if len(fragment.CommitSHA) > 6 {
logContext = logContext.Str("commit", fragment.CommitSHA[:7])
d.addCommit(fragment.CommitSHA)
} else if len(fragment.CommitSHA) > 0 {
logContext = logContext.Str("commit", fragment.CommitSHA)
d.addCommit(fragment.CommitSHA)
logger := logContext.Logger()
logger.Warn().Msg("commit SHAs should be >= 7 characters long")
}
logger := logContext.Logger()
if err != nil {
// Log the error and move on to the next fragment
logger.Error().Err(err).Send()
return nil
}
// both the fragment's content and path should be empty for it to be
// considered empty at this point because of path based matches
if len(fragment.Raw) == 0 && len(fragment.FilePath) == 0 {
logger.Trace().Msg("skipping empty fragment")
return nil
}
var timer *time.Timer
// Only start the timer in debug mode
if logger.GetLevel() <= zerolog.DebugLevel {
timer = time.AfterFunc(SlowWarningThreshold, func() {
logger.Debug().Msgf("Taking longer than %s to inspect fragment", SlowWarningThreshold.String())
})
}
for _, finding := range d.DetectContext(ctx, Fragment(fragment)) {
d.AddFinding(finding)
}
// Stop the timer if it was created
if timer != nil {
timer.Stop()
}
return nil
})
if _, isGit := source.(*sources.Git); isGit {
logging.Info().Msgf("%d commits scanned.", len(d.commitMap))
logging.Debug().Msg("Note: this number might be smaller than expected due to commits with no additions")
}
return d.Findings(), err
}
// Detect scans the given fragment and returns a list of findings
func (d *Detector) Detect(fragment Fragment) []report.Finding {
return d.DetectContext(context.Background(), fragment)
}
// DetectContext is the same as Detect but supports passing in a
// context to use for timeouts
func (d *Detector) DetectContext(ctx context.Context, fragment Fragment) []report.Finding {
if fragment.Bytes == nil {
d.TotalBytes.Add(uint64(len(fragment.Raw)))
}
d.TotalBytes.Add(uint64(len(fragment.Bytes)))
var findings []report.Finding
var (
findings []report.Finding
logger = func() zerolog.Logger {
l := logging.With().Str("path", fragment.FilePath)
if fragment.CommitSHA != "" {
l = l.Str("commit", fragment.CommitSHA)
}
return l.Logger()
}()
)
// check if filepath is allowed
if fragment.FilePath != "" {
// is the path our config or baseline file?
if fragment.FilePath == d.Config.Path || (d.baselinePath != "" && fragment.FilePath == d.baselinePath) ||
// is the path excluded by the global allowlist?
(d.Config.Allowlist.PathAllowed(fragment.FilePath) || (fragment.WindowsFilePath != "" && d.Config.Allowlist.PathAllowed(fragment.WindowsFilePath))) {
if fragment.FilePath == d.Config.Path || (d.baselinePath != "" && fragment.FilePath == d.baselinePath) {
logging.Trace().Msg("skipping file: matches config or baseline path")
return findings
}
}
// add newline indices for location calculation in detectRule
fragment.newlineIndices = newLineRegexp.FindAllStringIndex(fragment.Raw, -1)
// check if commit or filepath is allowed.
if isAllowed, event := checkCommitOrPathAllowed(logger, fragment, d.Config.Allowlists); isAllowed {
event.Msg("skipping file: global allowlist")
return findings
}
// setup variables to handle different decoding passes
currentRaw := fragment.Raw
encodedSegments := []EncodedSegment{}
encodedSegments := []*codec.EncodedSegment{}
currentDecodeDepth := 0
decoder := NewDecoder()
decoder := codec.NewDecoder()
ScanLoop:
for {
// build keyword map for prefiltering rules
keywords := make(map[string]bool)
normalizedRaw := strings.ToLower(currentRaw)
matches := d.prefilter.MatchString(normalizedRaw)
for _, m := range matches {
keywords[normalizedRaw[m.Pos():int(m.Pos())+len(m.Match())]] = true
}
for _, rule := range d.Config.Rules {
if len(rule.Keywords) == 0 {
// if no keywords are associated with the rule always scan the
// fragment using the rule
findings = append(findings, d.detectRule(fragment, currentRaw, rule, encodedSegments)...)
continue
select {
case <-ctx.Done():
break ScanLoop
default:
// build keyword map for prefiltering rules
keywords := make(map[string]bool)
normalizedRaw := strings.ToLower(currentRaw)
matches := d.prefilter.MatchString(normalizedRaw)
for _, m := range matches {
keywords[normalizedRaw[m.Pos():int(m.Pos())+len(m.Match())]] = true
}
// check if keywords are in the fragment
for _, k := range rule.Keywords {
if _, ok := keywords[strings.ToLower(k)]; ok {
findings = append(findings, d.detectRule(fragment, currentRaw, rule, encodedSegments)...)
break
for _, rule := range d.Config.Rules {
select {
case <-ctx.Done():
break ScanLoop
default:
if len(rule.Keywords) == 0 {
// if no keywords are associated with the rule always scan the
// fragment using the rule
findings = append(findings, d.detectRule(fragment, currentRaw, rule, encodedSegments)...)
continue
}
// check if keywords are in the fragment
for _, k := range rule.Keywords {
if _, ok := keywords[strings.ToLower(k)]; ok {
findings = append(findings, d.detectRule(fragment, currentRaw, rule, encodedSegments)...)
break
}
}
}
}
}
// increment the depth by 1 as we start our decoding pass
currentDecodeDepth++
// increment the depth by 1 as we start our decoding pass
currentDecodeDepth++
// stop the loop if we've hit our max decoding depth
if currentDecodeDepth > d.MaxDecodeDepth {
break
}
// stop the loop if we've hit our max decoding depth
if currentDecodeDepth > d.MaxDecodeDepth {
break ScanLoop
}
// decode the currentRaw for the next pass
currentRaw, encodedSegments = decoder.decode(currentRaw, encodedSegments)
// decode the currentRaw for the next pass
currentRaw, encodedSegments = decoder.Decode(currentRaw, encodedSegments)
// stop the loop when there's nothing else to decode
if len(encodedSegments) == 0 {
break
// stop the loop when there's nothing else to decode
if len(encodedSegments) == 0 {
break ScanLoop
}
}
}
@@ -280,7 +368,7 @@ func (d *Detector) Detect(fragment Fragment) []report.Finding {
}
// detectRule scans the given fragment for the given rule and returns a list of findings
func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rule, encodedSegments []EncodedSegment) []report.Finding {
func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rule, encodedSegments []*codec.EncodedSegment) []report.Finding {
var (
findings []report.Finding
logger = func() zerolog.Logger {
@@ -292,46 +380,14 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rul
}()
)
// check if filepath or commit is allowed for this rule
for _, a := range r.Allowlists {
var (
isAllowed bool
commitAllowed, commit = a.CommitAllowed(fragment.CommitSHA)
pathAllowed = a.PathAllowed(fragment.FilePath) || (fragment.WindowsFilePath != "" && a.PathAllowed(fragment.WindowsFilePath))
)
if a.MatchCondition == config.AllowlistMatchAnd {
// Determine applicable checks.
var allowlistChecks []bool
if len(a.Commits) > 0 {
allowlistChecks = append(allowlistChecks, commitAllowed)
}
if len(a.Paths) > 0 {
allowlistChecks = append(allowlistChecks, pathAllowed)
}
// These will be checked later.
if len(a.Regexes) > 0 {
allowlistChecks = append(allowlistChecks, false)
}
if len(a.StopWords) > 0 {
allowlistChecks = append(allowlistChecks, false)
}
if r.SkipReport && !fragment.InheritedFromFinding {
return findings
}
// Check if allowed.
isAllowed = allTrue(allowlistChecks)
} else {
isAllowed = commitAllowed || pathAllowed
}
if isAllowed {
event := logger.Trace().Str("condition", a.MatchCondition.String())
if commitAllowed {
event.Str("allowed-commit", commit)
}
if pathAllowed {
event.Bool("allowed-path", pathAllowed)
}
event.Msg("skipping file: rule allowlist")
return findings
}
// check if commit or file is allowed for this rule.
if isAllowed, event := checkCommitOrPathAllowed(logger, fragment, r.Allowlists); isAllowed {
event.Msg("skipping file: rule allowlist")
return findings
}
if r.Path != nil {
@@ -339,13 +395,21 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rul
// Path _only_ rule
if r.Path.MatchString(fragment.FilePath) || (fragment.WindowsFilePath != "" && r.Path.MatchString(fragment.WindowsFilePath)) {
finding := report.Finding{
Commit: fragment.CommitSHA,
RuleID: r.RuleID,
Description: r.Description,
File: fragment.FilePath,
SymlinkFile: fragment.SymlinkFile,
Match: fmt.Sprintf("file detected: %s", fragment.FilePath),
Match: "file detected: " + fragment.FilePath,
Tags: r.Tags,
}
if fragment.CommitInfo != nil {
finding.Author = fragment.CommitInfo.AuthorName
finding.Date = fragment.CommitInfo.Date
finding.Email = fragment.CommitInfo.AuthorEmail
finding.Link = createScmLink(fragment.CommitInfo.Remote, finding)
finding.Message = fragment.CommitInfo.Message
}
return append(findings, finding)
}
} else {
@@ -365,7 +429,7 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rul
// if flag configure and raw data size bigger then the flag
if d.MaxTargetMegaBytes > 0 {
rawLength := len(currentRaw) / 1000000
rawLength := len(currentRaw) / 1_000_000
if rawLength > d.MaxTargetMegaBytes {
logger.Debug().
Int("size", rawLength).
@@ -375,9 +439,16 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rul
}
}
matches := r.Regex.FindAllStringIndex(currentRaw, -1)
if len(matches) == 0 {
return findings
}
// TODO profile this, probably should replace with something more efficient
newlineIndices := newLineRegexp.FindAllStringIndex(fragment.Raw, -1)
// use currentRaw instead of fragment.Raw since this represents the current
// decoding pass on the text
MatchLoop:
for _, matchIndex := range r.Regex.FindAllStringIndex(currentRaw, -1) {
// Extract secret from match
secret := strings.Trim(currentRaw[matchIndex[0]:matchIndex[1]], "\n")
@@ -389,14 +460,15 @@ MatchLoop:
// Check if the decoded portions of the segment overlap with the match
// to see if its potentially a new match
if len(encodedSegments) > 0 {
if segment := segmentWithDecodedOverlap(encodedSegments, matchIndex[0], matchIndex[1]); segment != nil {
matchIndex = segment.adjustMatchIndex(matchIndex)
metaTags = append(metaTags, segment.tags()...)
currentLine = segment.currentLine(currentRaw)
} else {
segments := codec.SegmentsWithDecodedOverlap(encodedSegments, matchIndex[0], matchIndex[1])
if len(segments) == 0 {
// This item has already been added to a finding
continue
}
matchIndex = codec.AdjustMatchIndex(segments, matchIndex)
metaTags = append(metaTags, codec.Tags(segments)...)
currentLine = codec.CurrentLine(segments, currentRaw)
} else {
// Fixes: https://github.com/gitleaks/gitleaks/issues/1352
// removes the incorrectly following line that was detected by regex expression '\n'
@@ -407,17 +479,18 @@ MatchLoop:
// 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)
loc := location(newlineIndices, fragment.Raw, matchIndex)
if matchIndex[1] > loc.endLineIndex {
loc.endLineIndex = matchIndex[1]
}
finding := report.Finding{
Commit: fragment.CommitSHA,
RuleID: r.RuleID,
Description: r.Description,
StartLine: loc.startLine,
EndLine: loc.endLine,
StartLine: fragment.StartLine + loc.startLine,
EndLine: fragment.StartLine + loc.endLine,
StartColumn: loc.startColumn,
EndColumn: loc.endColumn,
Line: fragment.Raw[loc.startLineIndex:loc.endLineIndex],
@@ -427,7 +500,13 @@ MatchLoop:
SymlinkFile: fragment.SymlinkFile,
Tags: append(r.Tags, metaTags...),
}
if fragment.CommitInfo != nil {
finding.Author = fragment.CommitInfo.AuthorName
finding.Date = fragment.CommitInfo.Date
finding.Email = fragment.CommitInfo.AuthorEmail
finding.Link = createScmLink(fragment.CommitInfo.Remote, finding)
finding.Message = fragment.CommitInfo.Message
}
if !d.IgnoreGitleaksAllow && strings.Contains(finding.Line, gitleaksAllowSignature) {
logger.Trace().
Str("finding", finding.Secret).
@@ -473,105 +552,159 @@ MatchLoop:
continue
}
}
// check if the regexTarget is defined in the allowlist "regexes" entry
// or if the secret is in the list of stopwords
globalAllowlistTarget := finding.Secret
switch d.Config.Allowlist.RegexTarget {
case "match":
globalAllowlistTarget = finding.Match
case "line":
globalAllowlistTarget = currentLine
}
if d.Config.Allowlist.RegexAllowed(globalAllowlistTarget) {
logger.Trace().
Str("finding", globalAllowlistTarget).
Msg("skipping finding: global allowlist regex")
continue
} else if ok, word := d.Config.Allowlist.ContainsStopWord(finding.Secret); ok {
logger.Trace().
Str("finding", finding.Secret).
Str("allowed-stopword", word).
Msg("skipping finding: global allowlist stopword")
// check if the result matches any of the global allowlists.
if isAllowed, event := checkFindingAllowed(logger, finding, fragment, currentLine, d.Config.Allowlists); isAllowed {
event.Msg("skipping finding: global allowlist")
continue
}
// check if the result matches any of the rule allowlists.
for _, a := range r.Allowlists {
allowlistTarget := finding.Secret
switch a.RegexTarget {
case "match":
allowlistTarget = finding.Match
case "line":
allowlistTarget = currentLine
}
var (
isAllowed bool
commitAllowed bool
commit string
pathAllowed bool
regexAllowed = a.RegexAllowed(allowlistTarget)
containsStopword, word = a.ContainsStopWord(finding.Secret)
)
// check if the secret is in the list of stopwords
if a.MatchCondition == config.AllowlistMatchAnd {
// Determine applicable checks.
var allowlistChecks []bool
if len(a.Commits) > 0 {
commitAllowed, commit = a.CommitAllowed(fragment.CommitSHA)
allowlistChecks = append(allowlistChecks, commitAllowed)
}
if len(a.Paths) > 0 {
pathAllowed = a.PathAllowed(fragment.FilePath) || (fragment.WindowsFilePath != "" && a.PathAllowed(fragment.WindowsFilePath))
allowlistChecks = append(allowlistChecks, pathAllowed)
}
if len(a.Regexes) > 0 {
allowlistChecks = append(allowlistChecks, regexAllowed)
}
if len(a.StopWords) > 0 {
allowlistChecks = append(allowlistChecks, containsStopword)
}
// Check if allowed.
isAllowed = allTrue(allowlistChecks)
} else {
isAllowed = regexAllowed || containsStopword
}
if isAllowed {
event := logger.Trace().
Str("finding", finding.Secret).
Str("condition", a.MatchCondition.String())
if commitAllowed {
event.Str("allowed-commit", commit)
}
if pathAllowed {
event.Bool("allowed-path", pathAllowed)
}
if regexAllowed {
event.Bool("allowed-regex", regexAllowed)
}
if containsStopword {
event.Str("allowed-stopword", word)
}
event.Msg("skipping finding: rule allowlist")
continue MatchLoop
}
if isAllowed, event := checkFindingAllowed(logger, finding, fragment, currentLine, r.Allowlists); isAllowed {
event.Msg("skipping finding: rule allowlist")
continue
}
findings = append(findings, finding)
}
return findings
// Handle required rules (multi-part rules)
if fragment.InheritedFromFinding || len(r.RequiredRules) == 0 {
return findings
}
// Process required rules and create findings with auxiliary findings
return d.processRequiredRules(fragment, currentRaw, r, encodedSegments, findings, logger)
}
func allTrue(bools []bool) bool {
allMatch := true
for _, check := range bools {
if !check {
allMatch = false
break
// processRequiredRules handles the logic for multi-part rules with auxiliary findings
func (d *Detector) processRequiredRules(fragment Fragment, currentRaw string, r config.Rule, encodedSegments []*codec.EncodedSegment, primaryFindings []report.Finding, logger zerolog.Logger) []report.Finding {
if len(primaryFindings) == 0 {
logger.Debug().Msg("no primary findings to process for required rules")
return primaryFindings
}
// Pre-collect all required rule findings once
allRequiredFindings := make(map[string][]report.Finding)
for _, requiredRule := range r.RequiredRules {
rule, ok := d.Config.Rules[requiredRule.RuleID]
if !ok {
logger.Error().Str("rule-id", requiredRule.RuleID).Msg("required rule not found in config")
continue
}
// Mark fragment as inherited to prevent infinite recursion
inheritedFragment := fragment
inheritedFragment.InheritedFromFinding = true
// Call detectRule once for each required rule
requiredFindings := d.detectRule(inheritedFragment, currentRaw, rule, encodedSegments)
allRequiredFindings[requiredRule.RuleID] = requiredFindings
logger.Debug().
Str("rule-id", requiredRule.RuleID).
Int("findings", len(requiredFindings)).
Msg("collected required rule findings")
}
var finalFindings []report.Finding
// Now process each primary finding against the pre-collected required findings
for _, primaryFinding := range primaryFindings {
var requiredFindings []*report.RequiredFinding
for _, requiredRule := range r.RequiredRules {
foundRequiredFindings, exists := allRequiredFindings[requiredRule.RuleID]
if !exists {
continue // Rule wasn't found earlier, skip
}
// Filter findings that are within proximity of the primary finding
for _, requiredFinding := range foundRequiredFindings {
if d.withinProximity(primaryFinding, requiredFinding, requiredRule) {
req := &report.RequiredFinding{
RuleID: requiredFinding.RuleID,
StartLine: requiredFinding.StartLine,
EndLine: requiredFinding.EndLine,
StartColumn: requiredFinding.StartColumn,
EndColumn: requiredFinding.EndColumn,
Line: requiredFinding.Line,
Match: requiredFinding.Match,
Secret: requiredFinding.Secret,
}
requiredFindings = append(requiredFindings, req)
}
}
}
// Check if we have at least one auxiliary finding for each required rule
if len(requiredFindings) > 0 && d.hasAllRequiredRules(requiredFindings, r.RequiredRules) {
// Create a finding with auxiliary findings
newFinding := primaryFinding // Copy the primary finding
newFinding.AddRequiredFindings(requiredFindings)
finalFindings = append(finalFindings, newFinding)
logger.Debug().
Str("primary-rule", r.RuleID).
Int("primary-line", primaryFinding.StartLine).
Int("auxiliary-count", len(requiredFindings)).
Msg("multi-part rule satisfied")
}
}
return allMatch
return finalFindings
}
// hasAllRequiredRules checks if we have at least one auxiliary finding for each required rule
func (d *Detector) hasAllRequiredRules(auxiliaryFindings []*report.RequiredFinding, requiredRules []*config.Required) bool {
foundRules := make(map[string]bool)
// AuxiliaryFinding
for _, aux := range auxiliaryFindings {
foundRules[aux.RuleID] = true
}
for _, required := range requiredRules {
if !foundRules[required.RuleID] {
return false
}
}
return true
}
func (d *Detector) withinProximity(primary, required report.Finding, requiredRule *config.Required) bool {
// fmt.Println(requiredRule.WithinLines)
// If neither within_lines nor within_columns is set, findings just need to be in the same fragment
if requiredRule.WithinLines == nil && requiredRule.WithinColumns == nil {
return true
}
// Check line proximity (vertical distance)
if requiredRule.WithinLines != nil {
lineDiff := abs(primary.StartLine - required.StartLine)
if lineDiff > *requiredRule.WithinLines {
return false
}
}
// Check column proximity (horizontal distance)
if requiredRule.WithinColumns != nil {
// Use the start column of each finding for proximity calculation
colDiff := abs(primary.StartColumn - required.StartColumn)
if colDiff > *requiredRule.WithinColumns {
return false
}
}
return true
}
// abs returns the absolute value of an integer
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
// AddFinding synchronously adds a finding to the findings slice
@@ -600,7 +733,7 @@ func (d *Detector) AddFinding(finding report.Finding) {
}
}
if d.baseline != nil && !IsNew(finding, d.baseline) {
if d.baseline != nil && !IsNew(finding, d.Redact, d.baseline) {
logger.Debug().
Str("fingerprint", finding.Fingerprint).
Msgf("skipping finding: baseline")
@@ -622,5 +755,146 @@ func (d *Detector) Findings() []report.Finding {
// AddCommit synchronously adds a commit to the commit slice
func (d *Detector) addCommit(commit string) {
d.commitMutex.Lock()
d.commitMap[commit] = true
d.commitMutex.Unlock()
}
// checkCommitOrPathAllowed evaluates |fragment| against all provided |allowlists|.
//
// If the match condition is "OR", only commit and path are checked.
// Otherwise, if regexes or stopwords are defined this will fail.
func checkCommitOrPathAllowed(
logger zerolog.Logger,
fragment Fragment,
allowlists []*config.Allowlist,
) (bool, *zerolog.Event) {
if fragment.FilePath == "" && fragment.CommitSHA == "" {
return false, nil
}
for _, a := range allowlists {
var (
isAllowed bool
allowlistChecks []bool
commitAllowed, _ = a.CommitAllowed(fragment.CommitSHA)
pathAllowed = a.PathAllowed(fragment.FilePath) || (fragment.WindowsFilePath != "" && a.PathAllowed(fragment.WindowsFilePath))
)
// If the condition is "AND" we need to check all conditions.
if a.MatchCondition == config.AllowlistMatchAnd {
if len(a.Commits) > 0 {
allowlistChecks = append(allowlistChecks, commitAllowed)
}
if len(a.Paths) > 0 {
allowlistChecks = append(allowlistChecks, pathAllowed)
}
// These will be checked later.
if len(a.Regexes) > 0 {
continue
}
if len(a.StopWords) > 0 {
continue
}
isAllowed = allTrue(allowlistChecks)
} else {
isAllowed = commitAllowed || pathAllowed
}
if isAllowed {
event := logger.Trace().Str("condition", a.MatchCondition.String())
if commitAllowed {
event.Bool("allowed-commit", commitAllowed)
}
if pathAllowed {
event.Bool("allowed-path", pathAllowed)
}
return true, event
}
}
return false, nil
}
// checkFindingAllowed evaluates |finding| against all provided |allowlists|.
//
// If the match condition is "OR", only regex and stopwords are run. (Commit and path should be handled separately).
// Otherwise, all conditions are checked.
//
// TODO: The method signature is awkward. I can't think of a better way to log helpful info.
func checkFindingAllowed(
logger zerolog.Logger,
finding report.Finding,
fragment Fragment,
currentLine string,
allowlists []*config.Allowlist,
) (bool, *zerolog.Event) {
for _, a := range allowlists {
allowlistTarget := finding.Secret
switch a.RegexTarget {
case "match":
allowlistTarget = finding.Match
case "line":
allowlistTarget = currentLine
}
var (
checks []bool
isAllowed bool
commitAllowed bool
commit string
pathAllowed bool
regexAllowed = a.RegexAllowed(allowlistTarget)
containsStopword, word = a.ContainsStopWord(finding.Secret)
)
// If the condition is "AND" we need to check all conditions.
if a.MatchCondition == config.AllowlistMatchAnd {
// Determine applicable checks.
if len(a.Commits) > 0 {
commitAllowed, commit = a.CommitAllowed(fragment.CommitSHA)
checks = append(checks, commitAllowed)
}
if len(a.Paths) > 0 {
pathAllowed = a.PathAllowed(fragment.FilePath) || (fragment.WindowsFilePath != "" && a.PathAllowed(fragment.WindowsFilePath))
checks = append(checks, pathAllowed)
}
if len(a.Regexes) > 0 {
checks = append(checks, regexAllowed)
}
if len(a.StopWords) > 0 {
checks = append(checks, containsStopword)
}
isAllowed = allTrue(checks)
} else {
isAllowed = regexAllowed || containsStopword
}
if isAllowed {
event := logger.Trace().
Str("finding", finding.Secret).
Str("condition", a.MatchCondition.String())
if commitAllowed {
event.Str("allowed-commit", commit)
}
if pathAllowed {
event.Bool("allowed-path", pathAllowed)
}
if regexAllowed {
event.Bool("allowed-regex", regexAllowed)
}
if containsStopword {
event.Str("allowed-stopword", word)
}
return true, event
}
}
return false, nil
}
func allTrue(bools []bool) bool {
for _, check := range bools {
if !check {
return false
}
}
return true
}
+1505 -226
View File
File diff suppressed because it is too large. Load diff
-194
View File
@@ -1,194 +0,0 @@
package detect
import (
"bufio"
"bytes"
"io"
"os"
"path/filepath"
"strings"
"github.com/h2non/filetype"
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
)
const maxPeekSize = 25 * 1_000 // 10kb
func (d *Detector) DetectFiles(paths <-chan sources.ScanTarget) ([]report.Finding, error) {
for pa := range paths {
d.Sema.Go(func() error {
logger := logging.With().Str("path", pa.Path).Logger()
logger.Trace().Msg("Scanning path")
f, err := os.Open(pa.Path)
if err != nil {
if os.IsPermission(err) {
logger.Warn().Msg("Skipping file: permission denied")
return nil
}
return err
}
defer func() {
_ = f.Close()
}()
// Get file size
fileInfo, err := f.Stat()
if err != nil {
return err
}
fileSize := fileInfo.Size()
if d.MaxTargetMegaBytes > 0 {
rawLength := fileSize / 1000000
if rawLength > int64(d.MaxTargetMegaBytes) {
logger.Debug().
Int64("size", rawLength).
Msg("Skipping file: exceeds --max-target-megabytes")
return nil
}
}
var (
// Buffer to hold file chunks
reader = bufio.NewReaderSize(f, chunkSize)
buf = make([]byte, chunkSize)
totalLines = 0
)
for {
n, err := reader.Read(buf)
// "Callers should always process the n > 0 bytes returned before considering the error err."
// https://pkg.go.dev/io#Reader
if n > 0 {
// Only check the filetype at the start of file.
if totalLines == 0 {
// TODO: could other optimizations be introduced here?
if mimetype, err := filetype.Match(buf[:n]); err != nil {
return nil
} else if mimetype.MIME.Type == "application" {
return nil // skip binary files
}
}
// Try to split chunks across large areas of whitespace, if possible.
peekBuf := bytes.NewBuffer(buf[:n])
if readErr := readUntilSafeBoundary(reader, n, maxPeekSize, peekBuf); readErr != nil {
return readErr
}
// Count the number of newlines in this chunk
chunk := peekBuf.String()
linesInChunk := strings.Count(chunk, "\n")
totalLines += linesInChunk
fragment := Fragment{
Raw: chunk,
Bytes: peekBuf.Bytes(),
}
if pa.Symlink != "" {
fragment.SymlinkFile = pa.Symlink
}
if isWindows {
fragment.FilePath = filepath.ToSlash(pa.Path)
fragment.SymlinkFile = filepath.ToSlash(fragment.SymlinkFile)
fragment.WindowsFilePath = pa.Path
} else {
fragment.FilePath = pa.Path
}
for _, finding := range d.Detect(fragment) {
// need to add 1 since line counting starts at 1
finding.StartLine += (totalLines - linesInChunk) + 1
finding.EndLine += (totalLines - linesInChunk) + 1
d.AddFinding(finding)
}
}
if err != nil {
if err == io.EOF {
return nil
}
return err
}
}
})
}
if err := d.Sema.Wait(); err != nil {
return d.findings, err
}
return d.findings, nil
}
// readUntilSafeBoundary consumes |f| until it finds two consecutive `\n` characters, up to |maxPeekSize|.
// This hopefully avoids splitting. (https://github.com/gitleaks/gitleaks/issues/1651)
func readUntilSafeBoundary(r *bufio.Reader, n int, maxPeekSize int, peekBuf *bytes.Buffer) error {
if peekBuf.Len() == 0 {
return nil
}
// Does the buffer end in consecutive newlines?
var (
data = peekBuf.Bytes()
lastChar = data[len(data)-1]
newlineCount = 0 // Tracks consecutive newlines
)
if isWhitespace(lastChar) {
for i := len(data) - 1; i >= 0; i-- {
lastChar = data[i]
if lastChar == '\n' {
newlineCount++
// Stop if two consecutive newlines are found
if newlineCount >= 2 {
return nil
}
} else if lastChar == '\r' || lastChar == ' ' || lastChar == '\t' {
// The presence of other whitespace characters (`\r`, ` `, `\t`) shouldn't reset the count.
// (Intentionally do nothing.)
} else {
break
}
}
}
// If not, read ahead until we (hopefully) find some.
newlineCount = 0
for {
data = peekBuf.Bytes()
// Check if the last character is a newline.
lastChar = data[len(data)-1]
if lastChar == '\n' {
newlineCount++
// Stop if two consecutive newlines are found
if newlineCount >= 2 {
break
}
} else if lastChar == '\r' || lastChar == ' ' || lastChar == '\t' {
// The presence of other whitespace characters (`\r`, ` `, `\t`) shouldn't reset the count.
// (Intentionally do nothing.)
} else {
newlineCount = 0 // Reset if a non-newline character is found
}
// Stop growing the buffer if it reaches maxSize
if (peekBuf.Len() - n) >= maxPeekSize {
break
}
// Read additional data into a temporary buffer
b, err := r.ReadByte()
if err != nil {
if err == io.EOF {
break
}
return err
}
peekBuf.WriteByte(b)
}
return nil
}
+92
View File
@@ -0,0 +1,92 @@
package detect
import (
"context"
"errors"
"os"
"sync"
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
)
// DetectFiles runs detections against a chanel of scan targets
//
// Deprecated: Use sources.Files and Detector.DetectSource instead
func (d *Detector) DetectFiles(scanTargets <-chan sources.ScanTarget) ([]report.Finding, error) {
var wg sync.WaitGroup
for scanTarget := range scanTargets {
wg.Add(1)
d.Sema.Go(func() error {
defer wg.Done()
logger := logging.With().Str("path", scanTarget.Path).Logger()
logger.Trace().Msg("scanning path")
f, err := os.Open(scanTarget.Path)
if err != nil {
if os.IsPermission(err) {
err = errors.New("permission denied")
}
logger.Warn().Err(err).Msg("skipping file")
return nil
}
defer func() {
_ = f.Close()
}()
info, err := f.Stat()
if err != nil {
logger.Error().Err(err).Msg("skipping file: could not get info")
return nil
}
// Empty; nothing to do here.
if info.Size() == 0 {
logger.Debug().Msg("skipping empty file")
return nil
}
// Too large; nothing to do here.
if d.MaxTargetMegaBytes > 0 {
rawLength := info.Size() / 1_000_000
if rawLength > int64(d.MaxTargetMegaBytes) {
logger.Warn().Msgf(
"skipping file: too large max_size=%dMB, size=%dMB",
d.MaxTargetMegaBytes, rawLength,
)
return nil
}
}
// Convert this to a file source
file := sources.File{
Content: f,
Path: scanTarget.Path,
Symlink: scanTarget.Symlink,
Config: &d.Config,
MaxArchiveDepth: d.MaxArchiveDepth,
}
ctx := context.Background()
return file.Fragments(ctx, func(fragment sources.Fragment, err error) error {
if err != nil {
logging.Error().Err(err)
return nil
}
for _, finding := range d.Detect(Fragment(fragment)) {
d.AddFinding(finding)
}
return nil
})
})
}
wg.Wait()
return d.findings, nil
}
+20 -164
View File
@@ -1,179 +1,35 @@
package detect
import (
"bytes"
"errors"
"fmt"
"net/url"
"os/exec"
"regexp"
"strings"
"github.com/gitleaks/go-gitdiff/gitdiff"
"context"
"github.com/zricethezav/gitleaks/v8/cmd/scm"
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
)
// RemoteInfo is an alias for sources.RemoteInfo for backwards compatibility
//
// Deprecated: This will be replaced with sources.RemoteInfo in v9
type RemoteInfo sources.RemoteInfo
// DetectGit runs detections against a GitCmd with its remote info
//
// Deprecated: Use sources.Git and detector.DetectSource instead
func (d *Detector) DetectGit(cmd *sources.GitCmd, remote *RemoteInfo) ([]report.Finding, error) {
defer cmd.Wait()
var (
diffFilesCh = cmd.DiffFilesCh()
errCh = cmd.ErrCh()
return d.DetectSource(
context.Background(),
&sources.Git{
Cmd: cmd,
Config: &d.Config,
Remote: (*sources.RemoteInfo)(remote),
Sema: d.Sema,
MaxArchiveDepth: d.MaxArchiveDepth,
},
)
// loop to range over both DiffFiles (stdout) and ErrCh (stderr)
for diffFilesCh != nil || errCh != nil {
select {
case gitdiffFile, open := <-diffFilesCh:
if !open {
diffFilesCh = nil
break
}
// skip binary files
if gitdiffFile.IsBinary || gitdiffFile.IsDelete {
continue
}
// Check if commit is allowed
commitSHA := ""
if gitdiffFile.PatchHeader != nil {
commitSHA = gitdiffFile.PatchHeader.SHA
if ok, c := d.Config.Allowlist.CommitAllowed(gitdiffFile.PatchHeader.SHA); ok {
logging.Trace().Str("allowed-commit", c).Msg("skipping commit: global allowlist")
continue
}
}
d.addCommit(commitSHA)
d.Sema.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(remote, finding, textFragment, gitdiffFile))
}
}
return nil
})
case err, open := <-errCh:
if !open {
errCh = nil
break
}
return d.findings, err
}
}
if err := d.Sema.Wait(); err != nil {
return d.findings, err
}
logging.Info().Msgf("%d commits scanned.", len(d.commitMap))
logging.Debug().Msg("Note: this number might be smaller than expected due to commits with no additions")
return d.findings, nil
}
type RemoteInfo struct {
Platform scm.Platform
Url string
}
// Deprecated: use sources.NewRemoteInfo instead
func NewRemoteInfo(platform scm.Platform, source string) *RemoteInfo {
if platform == scm.NoPlatform {
return &RemoteInfo{Platform: platform}
}
remoteUrl, err := getRemoteUrl(source)
if err != nil {
if strings.Contains(err.Error(), "No remote configured") {
logging.Debug().Msg("skipping finding links: repository has no configured remote.")
platform = scm.NoPlatform
} else {
logging.Error().Err(err).Msg("skipping finding links: unable to parse remote URL")
}
goto End
}
if platform == scm.UnknownPlatform {
platform = platformFromHost(remoteUrl)
if platform == scm.UnknownPlatform {
logging.Info().
Str("host", remoteUrl.Hostname()).
Msg("Unknown SCM platform. Use --platform to include links in findings.")
} else {
logging.Debug().
Str("host", remoteUrl.Hostname()).
Str("platform", platform.String()).
Msg("SCM platform parsed from host")
}
}
End:
var rUrl string
if remoteUrl != nil {
rUrl = remoteUrl.String()
}
return &RemoteInfo{
Platform: platform,
Url: rUrl,
}
}
var sshUrlpat = regexp.MustCompile(`^git@([a-zA-Z0-9.-]+):([\w/.-]+?)(?:\.git)?$`)
func getRemoteUrl(source string) (*url.URL, error) {
// This will return the first remote — typically, "origin".
cmd := exec.Command("git", "ls-remote", "--quiet", "--get-url")
if source != "." {
cmd.Dir = source
}
stdout, err := cmd.Output()
if err != nil {
var exitError *exec.ExitError
if errors.As(err, &exitError) {
return nil, fmt.Errorf("command failed (%d): %w, stderr: %s", exitError.ExitCode(), err, string(bytes.TrimSpace(exitError.Stderr)))
}
return nil, err
}
remoteUrl := string(bytes.TrimSpace(stdout))
if matches := sshUrlpat.FindStringSubmatch(remoteUrl); matches != nil {
remoteUrl = fmt.Sprintf("https://%s/%s", matches[1], matches[2])
}
remoteUrl = strings.TrimSuffix(remoteUrl, ".git")
parsedUrl, err := url.Parse(remoteUrl)
if err != nil {
return nil, fmt.Errorf("unable to parse remote URL: %w", err)
}
// Remove any user info.
parsedUrl.User = nil
return parsedUrl, nil
}
func platformFromHost(u *url.URL) scm.Platform {
switch strings.ToLower(u.Hostname()) {
case "github.com":
return scm.GitHubPlatform
case "gitlab.com":
return scm.GitLabPlatform
case "dev.azure.com", "visualstudio.com":
return scm.AzureDevOpsPlatform
default:
return scm.UnknownPlatform
}
return (*RemoteInfo)(sources.NewRemoteInfo(platform, source))
}
+8 -8
View File
@@ -10,7 +10,7 @@ type Location struct {
endLineIndex int
}
func location(fragment Fragment, matchIndex []int) Location {
func location(newlineIndices [][]int, raw string, matchIndex []int) Location {
var (
prevNewLine int
location Location
@@ -28,13 +28,13 @@ func location(fragment Fragment, matchIndex []int) Location {
// When a fragment does NOT have any newlines, a default "newline"
// will be counted to make the subsequent location calculation logic work
// for fragments will no newlines.
if len(fragment.newlineIndices) == 0 {
fragment.newlineIndices = [][]int{
{len(fragment.Raw), len(fragment.Raw) + 1},
if len(newlineIndices) == 0 {
newlineIndices = [][]int{
{len(raw), len(raw) + 1},
}
}
for lineNum, pair := range fragment.newlineIndices {
for lineNum, pair := range newlineIndices {
_lineNum = lineNum
newLineByteIndex := pair[0]
if prevNewLine <= start && start < newLineByteIndex {
@@ -65,11 +65,11 @@ func location(fragment Fragment, matchIndex []int) Location {
// search for new line byte index
i := 0
for end+i < len(fragment.Raw) {
if fragment.Raw[end+i] == '\n' {
for end+i < len(raw) {
if raw[end+i] == '\n' {
break
}
if fragment.Raw[end+i] == '\r' {
if raw[end+i] == '\r' {
break
}
i++
+1 -1
View File
@@ -51,7 +51,7 @@ func TestGetLocation(t *testing.T) {
}
for _, test := range tests {
loc := location(Fragment{newlineIndices: test.linePairs}, []int{test.start, test.end})
loc := location(test.linePairs, "", []int{test.start, test.end})
assert.Equal(t, test.wantLocation, loc)
}
}
+47 -66
View File
@@ -1,52 +1,41 @@
package detect
import (
"bufio"
"bytes"
"errors"
"context"
"io"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
)
// DetectReader accepts an io.Reader and a buffer size for the reader in KB
//
// Deprecated: Use sources.File with no path defined and Detector.DetectSource instead
func (d *Detector) DetectReader(r io.Reader, bufSize int) ([]report.Finding, error) {
reader := bufio.NewReader(r)
buf := make([]byte, 1000*bufSize)
findings := []report.Finding{}
for {
n, err := reader.Read(buf)
// "Callers should always process the n > 0 bytes returned before considering the error err."
// https://pkg.go.dev/io#Reader
if n > 0 {
// Try to split chunks across large areas of whitespace, if possible.
peekBuf := bytes.NewBuffer(buf[:n])
if readErr := readUntilSafeBoundary(reader, n, maxPeekSize, peekBuf); readErr != nil {
return findings, readErr
}
fragment := Fragment{
Raw: peekBuf.String(),
}
for _, finding := range d.Detect(fragment) {
findings = append(findings, finding)
if d.Verbose {
printFinding(finding, d.NoColor)
}
}
}
if err != nil {
if err == io.EOF {
break
}
return findings, err
}
var findings []report.Finding
file := sources.File{
Content: r,
Buffer: make([]byte, 1000*bufSize),
MaxArchiveDepth: d.MaxArchiveDepth,
}
return findings, nil
ctx := context.Background()
err := file.Fragments(ctx, func(fragment sources.Fragment, err error) error {
if err != nil {
return err
}
for _, finding := range d.Detect(Fragment(fragment)) {
findings = append(findings, finding)
if d.Verbose {
printFinding(finding, d.NoColor)
}
}
return nil
})
return findings, err
}
// StreamDetectReader streams the detection results from the provided io.Reader.
@@ -82,45 +71,37 @@ func (d *Detector) DetectReader(r io.Reader, bufSize int) ([]report.Finding, err
// } else {
// fmt.Println("Scanning completed successfully.")
// }
//
// Deprecated: Use sources.File.Fragments(context.Context, FragmentsFunc) instead
func (d *Detector) StreamDetectReader(r io.Reader, bufSize int) (<-chan report.Finding, <-chan error) {
findingsCh := make(chan report.Finding, 1)
errCh := make(chan error, 1)
file := sources.File{
Content: r,
Buffer: make([]byte, 1000*bufSize),
MaxArchiveDepth: d.MaxArchiveDepth,
}
go func() {
defer close(findingsCh)
defer close(errCh)
reader := bufio.NewReader(r)
buf := make([]byte, 1000*bufSize)
for {
n, err := reader.Read(buf)
if n > 0 {
peekBuf := bytes.NewBuffer(buf[:n])
if readErr := readUntilSafeBoundary(reader, n, maxPeekSize, peekBuf); readErr != nil {
errCh <- readErr
return
}
fragment := Fragment{Raw: peekBuf.String()}
for _, finding := range d.Detect(fragment) {
findingsCh <- finding
if d.Verbose {
printFinding(finding, d.NoColor)
}
}
}
ctx := context.Background()
errCh <- file.Fragments(ctx, func(fragment sources.Fragment, err error) error {
if err != nil {
if errors.Is(err, io.EOF) {
errCh <- nil
return
}
errCh <- err
return
return err
}
}
for _, finding := range d.Detect(Fragment(fragment)) {
findingsCh <- finding
if d.Verbose {
printFinding(finding, d.NoColor)
}
}
return nil
})
}()
return findingsCh, errCh
+56 -42
View File
@@ -6,59 +6,38 @@ import (
"math"
"path/filepath"
"strings"
"time"
"github.com/zricethezav/gitleaks/v8/cmd/scm"
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
"github.com/charmbracelet/lipgloss"
"github.com/gitleaks/go-gitdiff/gitdiff"
)
// augmentGitFinding updates the start and end line numbers of a finding to include the
// delta from the git diff
func augmentGitFinding(remote *RemoteInfo, 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
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)
finding.Message = f.PatchHeader.Message()
// Results from `git diff` shouldn't have a link.
if finding.Commit != "" {
finding.Link = createScmLink(remote.Platform, remote.Url, finding)
}
}
return finding
}
var linkCleaner = strings.NewReplacer(
" ", "%20",
"%", "%25",
)
func createScmLink(scmPlatform scm.Platform, remoteUrl string, finding report.Finding) string {
if scmPlatform == scm.UnknownPlatform || scmPlatform == scm.NoPlatform {
func createScmLink(remote *sources.RemoteInfo, finding report.Finding) string {
if remote.Platform == scm.UnknownPlatform ||
remote.Platform == scm.NoPlatform ||
finding.Commit == "" {
return ""
}
// Clean the path.
var (
filePath = linkCleaner.Replace(finding.File)
ext = strings.ToLower(filepath.Ext(filePath))
)
filePath, _, hasInnerPath := strings.Cut(finding.File, sources.InnerPathSeparator)
filePath = linkCleaner.Replace(filePath)
switch scmPlatform {
switch remote.Platform {
case scm.GitHubPlatform:
link := fmt.Sprintf("%s/blob/%s/%s", remoteUrl, finding.Commit, filePath)
link := fmt.Sprintf("%s/blob/%s/%s", remote.Url, finding.Commit, filePath)
if hasInnerPath {
return link
}
ext := strings.ToLower(filepath.Ext(filePath))
if ext == ".ipynb" || ext == ".md" {
link += "?plain=1"
}
@@ -70,7 +49,10 @@ func createScmLink(scmPlatform scm.Platform, remoteUrl string, finding report.Fi
}
return link
case scm.GitLabPlatform:
link := fmt.Sprintf("%s/blob/%s/%s", remoteUrl, finding.Commit, filePath)
link := fmt.Sprintf("%s/blob/%s/%s", remote.Url, finding.Commit, filePath)
if hasInnerPath {
return link
}
if finding.StartLine != 0 {
link += fmt.Sprintf("#L%d", finding.StartLine)
}
@@ -79,8 +61,11 @@ func createScmLink(scmPlatform scm.Platform, remoteUrl string, finding report.Fi
}
return link
case scm.AzureDevOpsPlatform:
link := fmt.Sprintf("%s/commit/%s?path=/%s", remoteUrl, finding.Commit, filePath)
link := fmt.Sprintf("%s/commit/%s?path=/%s", remote.Url, finding.Commit, filePath)
// Add line information if applicable
if hasInnerPath {
return link
}
if finding.StartLine != 0 {
link += fmt.Sprintf("&line=%d", finding.StartLine)
}
@@ -90,6 +75,34 @@ func createScmLink(scmPlatform scm.Platform, remoteUrl string, finding report.Fi
// This is a bit dirty, but Azure DevOps does not highlight the line when the lineStartColumn and lineEndColumn are not provided
link += "&lineStartColumn=1&lineEndColumn=10000000&type=2&lineStyle=plain&_a=files"
return link
case scm.GiteaPlatform:
link := fmt.Sprintf("%s/src/commit/%s/%s", remote.Url, finding.Commit, filePath)
if hasInnerPath {
return link
}
ext := strings.ToLower(filepath.Ext(filePath))
if ext == ".ipynb" || ext == ".md" {
link += "?display=source"
}
if finding.StartLine != 0 {
link += fmt.Sprintf("#L%d", finding.StartLine)
}
if finding.EndLine != finding.StartLine {
link += fmt.Sprintf("-L%d", finding.EndLine)
}
return link
case scm.BitbucketPlatform:
link := fmt.Sprintf("%s/src/%s/%s", remote.Url, finding.Commit, filePath)
if hasInnerPath {
return link
}
if finding.StartLine != 0 {
link += fmt.Sprintf("#lines-%d", finding.StartLine)
}
if finding.EndLine != finding.StartLine {
link += fmt.Sprintf(":%d", finding.EndLine)
}
return link
default:
// This should never happen.
return ""
@@ -133,8 +146,8 @@ func filter(findings []report.Finding, redact uint) []report.Finding {
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)
genericMatch := strings.ReplaceAll(f.Match, f.Secret, "REDACTED")
betterMatch := strings.ReplaceAll(fPrime.Match, fPrime.Secret, "REDACTED")
logging.Trace().Msgf("skipping %s finding (%s), %s rule takes precedence (%s)", f.RuleID, genericMatch, fPrime.RuleID, betterMatch)
include = false
break
@@ -219,7 +232,9 @@ func printFinding(f report.Finding, noColor bool) {
fmt.Printf("%-12s %s\n", "RuleID:", f.RuleID)
fmt.Printf("%-12s %f\n", "Entropy:", f.Entropy)
if f.File == "" {
f.PrintRequiredFindings()
fmt.Println("")
return
}
@@ -230,6 +245,7 @@ func printFinding(f report.Finding, noColor bool) {
fmt.Printf("%-12s %d\n", "Line:", f.StartLine)
if f.Commit == "" {
fmt.Printf("%-12s %s\n", "Fingerprint:", f.Fingerprint)
f.PrintRequiredFindings()
fmt.Println("")
return
}
@@ -241,9 +257,7 @@ func printFinding(f report.Finding, noColor bool) {
if f.Link != "" {
fmt.Printf("%-12s %s\n", "Link:", f.Link)
}
f.PrintRequiredFindings()
fmt.Println("")
}
func isWhitespace(ch byte) bool {
return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'
}
+110 -23
View File
@@ -7,25 +7,30 @@ import (
"github.com/zricethezav/gitleaks/v8/cmd/scm"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
)
func Test_createScmLink(t *testing.T) {
tests := map[string]struct {
platform scm.Platform
url string
finding report.Finding
want string
remote *sources.RemoteInfo
finding report.Finding
want string
}{
// None
"no platform": {
platform: scm.NoPlatform,
want: "",
remote: &sources.RemoteInfo{
Platform: scm.NoPlatform,
Url: "",
},
want: "",
},
// GitHub
"github - single line": {
platform: scm.GitHubPlatform,
url: "https://github.com/gitleaks/test",
remote: &sources.RemoteInfo{
Platform: scm.GitHubPlatform,
Url: "https://github.com/gitleaks/test",
},
finding: report.Finding{
Commit: "20553ad96a4a080c94a54d677db97eed8ce2560d",
File: "metrics/% of sales/.env",
@@ -35,8 +40,10 @@ func Test_createScmLink(t *testing.T) {
want: "https://github.com/gitleaks/test/blob/20553ad96a4a080c94a54d677db97eed8ce2560d/metrics/%25%20of%20sales/.env#L25",
},
"github - multi line": {
platform: scm.GitHubPlatform,
url: "https://github.com/gitleaks/test",
remote: &sources.RemoteInfo{
Platform: scm.GitHubPlatform,
Url: "https://github.com/gitleaks/test",
},
finding: report.Finding{
Commit: "7bad9f7654cf9701b62400281748c0e8efd97666",
File: "config.json",
@@ -46,8 +53,10 @@ func Test_createScmLink(t *testing.T) {
want: "https://github.com/gitleaks/test/blob/7bad9f7654cf9701b62400281748c0e8efd97666/config.json#L235-L238",
},
"github - markdown": {
platform: scm.GitHubPlatform,
url: "https://github.com/gitleaks/test",
remote: &sources.RemoteInfo{
Platform: scm.GitHubPlatform,
Url: "https://github.com/gitleaks/test",
},
finding: report.Finding{
Commit: "1fc8961d172f39ffb671766e472aa76f8d713e87",
File: "docs/guides/ecosystem/discordjs.MD",
@@ -57,8 +66,10 @@ func Test_createScmLink(t *testing.T) {
want: "https://github.com/gitleaks/test/blob/1fc8961d172f39ffb671766e472aa76f8d713e87/docs/guides/ecosystem/discordjs.MD?plain=1#L34",
},
"github - jupyter notebook": {
platform: scm.GitHubPlatform,
url: "https://github.com/gitleaks/test",
remote: &sources.RemoteInfo{
Platform: scm.GitHubPlatform,
Url: "https://github.com/gitleaks/test",
},
finding: report.Finding{
Commit: "8f56bd2369595bcadbb007e88ba294630fb05c7b",
File: "Cloud/IPYNB/Overlapping Recommendation algorithm _OCuLaR_.ipynb",
@@ -70,8 +81,10 @@ func Test_createScmLink(t *testing.T) {
// GitLab
"gitlab - single line": {
platform: scm.GitLabPlatform,
url: "https://gitlab.com/example-org/example-group/gitleaks",
remote: &sources.RemoteInfo{
Platform: scm.GitLabPlatform,
Url: "https://gitlab.com/example-org/example-group/gitleaks",
},
finding: report.Finding{
Commit: "213ffd1c9bfa906eb4c7731771132c58a4ca0139",
File: ".gitlab-ci.yml",
@@ -81,8 +94,10 @@ func Test_createScmLink(t *testing.T) {
want: "https://gitlab.com/example-org/example-group/gitleaks/blob/213ffd1c9bfa906eb4c7731771132c58a4ca0139/.gitlab-ci.yml#L41",
},
"gitlab - multi line": {
platform: scm.GitLabPlatform,
url: "https://gitlab.com/example-org/example-group/gitleaks",
remote: &sources.RemoteInfo{
Platform: scm.GitLabPlatform,
Url: "https://gitlab.com/example-org/example-group/gitleaks",
},
finding: report.Finding{
Commit: "63410f74e23a4e51e1f60b9feb073b5d325af878",
File: ".vscode/launchSettings.json",
@@ -94,8 +109,10 @@ func Test_createScmLink(t *testing.T) {
// Azure DevOps
"azuredevops - single line": {
platform: scm.AzureDevOpsPlatform,
url: "https://dev.azure.com/exampleorganisation/exampleproject/_git/exampleRepository",
remote: &sources.RemoteInfo{
Platform: scm.AzureDevOpsPlatform,
Url: "https://dev.azure.com/exampleorganisation/exampleproject/_git/exampleRepository",
},
finding: report.Finding{
Commit: "20553ad96a4a080c94a54d677db97eed8ce2560d",
File: "examplefile.json",
@@ -107,8 +124,10 @@ func Test_createScmLink(t *testing.T) {
// Azure DevOps
"azuredevops - multi line": {
platform: scm.AzureDevOpsPlatform,
url: "https://dev.azure.com/exampleorganisation/exampleproject/_git/exampleRepository",
remote: &sources.RemoteInfo{
Platform: scm.AzureDevOpsPlatform,
Url: "https://dev.azure.com/exampleorganisation/exampleproject/_git/exampleRepository",
},
finding: report.Finding{
Commit: "20553ad96a4a080c94a54d677db97eed8ce2560d",
File: "examplefile.json",
@@ -117,10 +136,78 @@ func Test_createScmLink(t *testing.T) {
},
want: "https://dev.azure.com/exampleorganisation/exampleproject/_git/exampleRepository/commit/20553ad96a4a080c94a54d677db97eed8ce2560d?path=/examplefile.json&line=25&lineEnd=30&lineStartColumn=1&lineEndColumn=10000000&type=2&lineStyle=plain&_a=files",
},
// Gitea
"gitea - single line": {
remote: &sources.RemoteInfo{
Platform: scm.GiteaPlatform,
Url: "https://gitea.com/exampleorganisation/exampleproject",
},
finding: report.Finding{
Commit: "20553ad96a4a080c94a54d677db97eed8ce2560d",
File: "examplefile.json",
StartLine: 25,
EndLine: 25,
},
want: "https://gitea.com/exampleorganisation/exampleproject/src/commit/20553ad96a4a080c94a54d677db97eed8ce2560d/examplefile.json#L25",
},
"gitea- multi line": {
remote: &sources.RemoteInfo{
Platform: scm.GiteaPlatform,
Url: "https://gitea.com/exampleorganisation/exampleproject",
},
finding: report.Finding{
Commit: "20553ad96a4a080c94a54d677db97eed8ce2560d",
File: "examplefile.json",
StartLine: 25,
EndLine: 30,
},
want: "https://gitea.com/exampleorganisation/exampleproject/src/commit/20553ad96a4a080c94a54d677db97eed8ce2560d/examplefile.json#L25-L30",
},
"gitea - markdown": {
remote: &sources.RemoteInfo{
Platform: scm.GiteaPlatform,
Url: "https://gitea.com/exampleorganisation/exampleproject",
},
finding: report.Finding{
Commit: "20553ad96a4a080c94a54d677db97eed8ce2560d",
File: "Readme.md",
StartLine: 34,
EndLine: 34,
},
want: "https://gitea.com/exampleorganisation/exampleproject/src/commit/20553ad96a4a080c94a54d677db97eed8ce2560d/Readme.md?display=source#L34",
},
// bitbucket
"bitbucket - single line": {
remote: &sources.RemoteInfo{
Platform: scm.BitbucketPlatform,
Url: "https://bitbucket.org/exampleorganisation/exampleproject",
},
finding: report.Finding{
Commit: "20553ad96a4a080c94a54d677db97eed8ce2560d",
File: "examplefile.json",
StartLine: 25,
EndLine: 25,
},
want: "https://bitbucket.org/exampleorganisation/exampleproject/src/20553ad96a4a080c94a54d677db97eed8ce2560d/examplefile.json#lines-25",
},
"bitbucket- multi line": {
remote: &sources.RemoteInfo{
Platform: scm.BitbucketPlatform,
Url: "https://bitbucket.org/exampleorganisation/exampleproject",
},
finding: report.Finding{
Commit: "20553ad96a4a080c94a54d677db97eed8ce2560d",
File: "examplefile.json",
StartLine: 25,
EndLine: 30,
},
want: "https://bitbucket.org/exampleorganisation/exampleproject/src/20553ad96a4a080c94a54d677db97eed8ce2560d/examplefile.json#lines-25:30",
},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
actual := createScmLink(tt.platform, tt.url, tt.finding)
actual := createScmLink(tt.remote, tt.finding)
assert.Equal(t, tt.want, actual)
})
}
+24 -8
View File
@@ -1,8 +1,6 @@
module github.com/zricethezav/gitleaks/v8
go 1.23.0
toolchain go1.23.4
go 1.24.11
require (
github.com/BobuSumisu/aho-corasick v1.0.3
@@ -10,8 +8,10 @@ require (
github.com/charmbracelet/lipgloss v0.5.0
github.com/fatih/semgroup v1.2.0
github.com/gitleaks/go-gitdiff v0.9.1
github.com/google/go-cmp v0.6.0
github.com/google/go-cmp v0.7.0
github.com/h2non/filetype v1.1.3
github.com/hashicorp/go-version v1.7.0
github.com/mholt/archives v0.1.5
github.com/rs/zerolog v1.33.0
github.com/spf13/cobra v1.9.1
github.com/spf13/viper v1.19.0
@@ -23,27 +23,43 @@ require (
dario.cat/mergo v1.0.1 // indirect
github.com/Masterminds/goutils v1.1.1 // indirect
github.com/Masterminds/semver/v3 v3.3.0 // indirect
github.com/STARRY-S/zip v0.2.3 // indirect
github.com/andybalholm/brotli v1.2.0 // indirect
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/bodgit/plumbing v1.3.0 // indirect
github.com/bodgit/sevenzip v1.6.1 // indirect
github.com/bodgit/windows v1.0.1 // indirect
github.com/dsnet/compress v0.0.2-0.20230904184137-39efe44ab707 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/huandu/xstrings v1.5.0 // indirect
github.com/klauspost/compress v1.18.0 // indirect
github.com/klauspost/pgzip v1.2.6 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.14 // indirect
github.com/mikelolasagasti/xz v1.0.1 // indirect
github.com/minio/minlz v1.0.1 // indirect
github.com/mitchellh/copystructure v1.2.0 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/muesli/reflow v0.2.1-0.20210115123740-9e1d0d53df68 // indirect
github.com/muesli/termenv v0.15.1 // indirect
github.com/nwaples/rardecode/v2 v2.2.0 // indirect
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
github.com/pierrec/lz4/v4 v4.1.22 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
github.com/sagikazarmark/locafero v0.7.0 // indirect
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
github.com/shopspring/decimal v1.4.0 // indirect
github.com/sorairolake/lzip-go v0.3.8 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
github.com/tetratelabs/wazero v1.9.0 // indirect
github.com/ulikunitz/xz v0.5.15 // indirect
github.com/wasilibs/wazero-helpers v0.0.0-20240620070341-3dff1577cd52 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/crypto v0.32.0 // indirect
go4.org v0.0.0-20230225012048-214862532bf5 // indirect
golang.org/x/crypto v0.35.0 // indirect
)
require (
@@ -55,14 +71,14 @@ require (
github.com/magiconair/properties v1.8.9 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/spf13/afero v1.12.0 // indirect
github.com/spf13/afero v1.15.0 // indirect
github.com/spf13/cast v1.7.1 // indirect
github.com/spf13/pflag v1.0.6 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/wasilibs/go-re2 v1.9.0
golang.org/x/sync v0.11.0 // indirect
golang.org/x/sync v0.17.0 // indirect
golang.org/x/sys v0.30.0 // indirect
golang.org/x/text v0.22.0 // indirect
golang.org/x/text v0.29.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
+295 -10
View File
@@ -1,22 +1,62 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU=
cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU=
cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY=
cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc=
cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0=
cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To=
cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M=
cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o=
cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE=
cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE=
cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I=
cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw=
cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw=
cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos=
dario.cat/mergo v1.0.1 h1:Ra4+bf83h2ztPIQYNP99R6m+Y7KfnARDfID+a+vLl4s=
dario.cat/mergo v1.0.1/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk=
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
github.com/BobuSumisu/aho-corasick v1.0.3 h1:uuf+JHwU9CHP2Vx+wAy6jcksJThhJS9ehR8a+4nPE9g=
github.com/BobuSumisu/aho-corasick v1.0.3/go.mod h1:hm4jLcvZKI2vRF2WDU1N4p/jpWtpOzp3nLmi9AzX/XE=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI=
github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU=
github.com/Masterminds/semver/v3 v3.3.0 h1:B8LGeaivUe71a5qox1ICM/JLl0NqZSW5CHyL+hmvYS0=
github.com/Masterminds/semver/v3 v3.3.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
github.com/Masterminds/sprig/v3 v3.3.0 h1:mQh0Yrg1XPo6vjYXgtf5OtijNAKJRNcTdOOGZe3tPhs=
github.com/Masterminds/sprig/v3 v3.3.0/go.mod h1:Zy1iXRYNqNLUolqCpL4uhk6SHUMAOSCzdgBfDb35Lz0=
github.com/STARRY-S/zip v0.2.3 h1:luE4dMvRPDOWQdeDdUxUoZkzUIpTccdKdhHHsQJ1fm4=
github.com/STARRY-S/zip v0.2.3/go.mod h1:lqJ9JdeRipyOQJrYSOtpNAiaesFO6zVDsE8GIGFaoSk=
github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ=
github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
github.com/bodgit/plumbing v1.3.0 h1:pf9Itz1JOQgn7vEOE7v7nlEfBykYqvUYioC61TwWCFU=
github.com/bodgit/plumbing v1.3.0/go.mod h1:JOTb4XiRu5xfnmdnDJo6GmSbSbtSyufrsyZFByMtKEs=
github.com/bodgit/sevenzip v1.6.1 h1:kikg2pUMYC9ljU7W9SaqHXhym5HyKm8/M/jd31fYan4=
github.com/bodgit/sevenzip v1.6.1/go.mod h1:GVoYQbEVbOGT8n2pfqCIMRUaRjQ8F9oSqoBEqZh5fQ8=
github.com/bodgit/windows v1.0.1 h1:tF7K6KOluPYygXa3Z2594zxlkbKPAOvqr97etrGNIz4=
github.com/bodgit/windows v1.0.1/go.mod h1:a6JLwrB4KrTR5hBpp8FI9/9W9jJfeQ2h4XDXU74ZCdM=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/charmbracelet/lipgloss v0.5.0 h1:lulQHuVeodSgDez+3rGiuxlPVXSnhth442DATR2/8t8=
github.com/charmbracelet/lipgloss v0.5.0/go.mod h1:EZLha/HbzEt7cYqdFPovlqy5FZPj0xFhg5SaqxScmgs=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dsnet/compress v0.0.2-0.20230904184137-39efe44ab707 h1:2tV76y6Q9BB+NEBasnqvs7e49aEBFI8ejC89PSnWH+4=
github.com/dsnet/compress v0.0.2-0.20230904184137-39efe44ab707/go.mod h1:qssHWj60/X5sZFNxpG4HBPDHVqxNm4DfnCKgrbZOT+s=
github.com/dsnet/golib v0.0.0-20171103203638-1ea166775780/go.mod h1:Lj+Z9rebOhdfkVLjJ8T6VcRQv3SXugXy999NBtR9aFY=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/fatih/semgroup v1.2.0 h1:h/OLXwEM+3NNyAdZEpMiH1OzfplU09i2qXPVThGZvyg=
github.com/fatih/semgroup v1.2.0/go.mod h1:1KAD4iIYfXjE4U13B48VM4z9QUwV5Tt8O4rS879kgm8=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
@@ -25,21 +65,68 @@ github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/
github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/gitleaks/go-gitdiff v0.9.1 h1:ni6z6/3i9ODT685OLCTf+s/ERlWUNWQF4x1pvoNICw0=
github.com/gitleaks/go-gitdiff v0.9.1/go.mod h1:pKz0X4YzCKZs30BL+weqBIG7mx0jl4tF1uXV9ZyNvrA=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y=
github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
github.com/h2non/filetype v1.1.3 h1:FKkx9QbD7HR/zjK1Ia5XiBsq9zdLi5Kf3zGyFTAFkGg=
github.com/h2non/filetype v1.1.3/go.mod h1:319b3zT68BvV+WRj7cwy856M2ehB3HqNOt6sy1HndBY=
github.com/hashicorp/go-version v1.7.0 h1:5tqGy27NaOTB8yJKUZELlFAS/LTKJkrmONwQKeRZfjY=
github.com/hashicorp/go-version v1.7.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/huandu/xstrings v1.5.0 h1:2ag3IFq9ZDANvthTwTiqSSZLjDc+BedvHPAp5tJy2TI=
github.com/huandu/xstrings v1.5.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/klauspost/compress v1.4.1/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/klauspost/cpuid v1.2.0/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek=
github.com/klauspost/pgzip v1.2.6 h1:8RXeL5crjEUFnR2/Sn6GJNWtSQ3Dk8pq4CL3jvdDyjU=
github.com/klauspost/pgzip v1.2.6/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
@@ -60,6 +147,12 @@ github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRC
github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=
github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mholt/archives v0.1.5 h1:Fh2hl1j7VEhc6DZs2DLMgiBNChUux154a1G+2esNvzQ=
github.com/mholt/archives v0.1.5/go.mod h1:3TPMmBLPsgszL+1As5zECTuKwKvIfj6YcwWPpeTAXF4=
github.com/mikelolasagasti/xz v1.0.1 h1:Q2F2jX0RYJUG3+WsM+FJknv+6eVjsjXNDV0KJXZzkD0=
github.com/mikelolasagasti/xz v1.0.1/go.mod h1:muAirjiOUxPRXwm9HdDtB3uoRPrGnL85XHtokL9Hcgc=
github.com/minio/minlz v1.0.1 h1:OUZUzXcib8diiX+JYxyRLIdomyZYzHct6EShOKtQY2A=
github.com/minio/minlz v1.0.1/go.mod h1:qT0aEB35q79LLornSzeDH75LBf3aH1MV+jB5w9Wasec=
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
@@ -71,30 +164,40 @@ github.com/muesli/reflow v0.2.1-0.20210115123740-9e1d0d53df68/go.mod h1:Xk+z4oIW
github.com/muesli/termenv v0.11.1-0.20220204035834-5ac8409525e0/go.mod h1:Bd5NYQ7pd+SrtBSrSNoBBmXlcY8+Xj4BMJgh8qcZrvs=
github.com/muesli/termenv v0.15.1 h1:UzuTb/+hhlBugQz28rpzey4ZuKcZ03MeKsoG7IJZIxs=
github.com/muesli/termenv v0.15.1/go.mod h1:HeAQPTzpfs016yGtA4g00CsdYnVLJvxsS4ANqrZs2sQ=
github.com/nwaples/rardecode/v2 v2.2.0 h1:4ufPGHiNe1rYJxYfehALLjup4Ls3ck42CWwjKiOqu0A=
github.com/nwaples/rardecode/v2 v2.2.0/go.mod h1:7uz379lSxPe6j9nvzxUZ+n7mnJNgjsRNb6IbvGVHRmw=
github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
github.com/pierrec/lz4/v4 v4.1.22 h1:cKFw6uJDK+/gfw5BcDL0JL5aBsAFdsIT18eRtLj7VIU=
github.com/pierrec/lz4/v4 v4.1.22/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8=
github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd/go.mod h1:hPqNNc0+uJM6H+SuU8sEs5K5IQeKccPqeSjfgcKGgPk=
github.com/sagikazarmark/locafero v0.7.0 h1:5MqpDsTGNDhY8sGp0Aowyf0qKsPrhewaLSsFaodPcyo=
github.com/sagikazarmark/locafero v0.7.0/go.mod h1:2za3Cg5rMaTMoG/2Ulr9AwtFaIppKXTRYnozin4aB5k=
github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE=
github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ=
github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=
github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
github.com/sorairolake/lzip-go v0.3.8 h1:j5Q2313INdTA80ureWYRhX+1K78mUXfMoPZCw/ivWik=
github.com/sorairolake/lzip-go v0.3.8/go.mod h1:JcBqGMV0frlxwrsE9sMWXDjqn3EeVf0/54YPsw66qkU=
github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
github.com/spf13/afero v1.12.0 h1:UcOPyRBYczmFn6yvphxkn9ZEOY65cpwGKb5mL36mrqs=
github.com/spf13/afero v1.12.0/go.mod h1:ZTlWwG4/ahT8W7T0WQ5uYmjI9duaLQGy3Q2OAl4sk/4=
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y=
github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo=
@@ -103,36 +206,218 @@ github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI=
github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+Ntkg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
github.com/tetratelabs/wazero v1.9.0 h1:IcZ56OuxrtaEz8UYNRHBrUa9bYeX9oVY93KspZZBf/I=
github.com/tetratelabs/wazero v1.9.0/go.mod h1:TSbcXCfFP0L2FGkRPxHphadXPjo1T6W+CseNNY7EkjM=
github.com/ulikunitz/xz v0.5.8/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
github.com/ulikunitz/xz v0.5.15 h1:9DNdB5s+SgV3bQ2ApL10xRc35ck0DuIX/isZvIk+ubY=
github.com/ulikunitz/xz v0.5.15/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
github.com/wasilibs/go-re2 v1.9.0 h1:kjAd8qbNvV4Ve2Uf+zrpTCrDHtqH4dlsRXktywo73JQ=
github.com/wasilibs/go-re2 v1.9.0/go.mod h1:0sRtscWgpUdNA137bmr1IUgrRX0Su4dcn9AEe61y+yI=
github.com/wasilibs/wazero-helpers v0.0.0-20240620070341-3dff1577cd52 h1:OvLBa8SqJnZ6P+mjlzc2K7PM22rRUPE1x32G9DTPrC4=
github.com/wasilibs/wazero-helpers v0.0.0-20240620070341-3dff1577cd52/go.mod h1:jMeV4Vpbi8osrE/pKUxRZkVaA0EX7NZN0A9/oRzgpgY=
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc=
golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc=
go4.org v0.0.0-20230225012048-214862532bf5 h1:nifaUDeh+rPaBCMPMQHZmvJf+QdpLFnuQPwx+LxVmtc=
go4.org v0.0.0-20230225012048-214862532bf5/go.mod h1:F57wTi5Lrj6WLyswp5EYV1ncrEbFGHD4hhz6S1ZYeaU=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.35.0 h1:b15kiHdrGCHrP6LvwaQ3c03kgNhhiMgvlhxHQhmg2Xs=
golang.org/x/crypto v0.35.0/go.mod h1:dy7dXNW32cAb/6/PRuTNsix8T+vJAqvuIy5Bli/x0YQ=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek=
golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY=
golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM=
golang.org/x/exp v0.0.0-20250218142911-aa4b98e5adaa h1:t2QcU6V556bFjYgu4L6C+6VrCPyJZ+eyRsABUPs1mz4=
golang.org/x/exp v0.0.0-20250218142911-aa4b98e5adaa/go.mod h1:BHOTPb3L19zxehTsLoJXVaTktb06DFgmdW6Wb9s8jqk=
golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w=
golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs=
golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE=
golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o=
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY=
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE=
google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M=
google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg=
google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg=
google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI=
google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI=
google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI=
google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0=
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8=
google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8=
rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0=
rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA=
+62 -6
View File
@@ -1,12 +1,16 @@
package report
import (
"fmt"
"math"
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/zricethezav/gitleaks/v8/sources"
)
// Finding contains information about strings that
// have been captured by a tree-sitter query.
// Finding contains a whole bunch of information about a secret finding.
// Plenty of real estate in this bad boy so fillerup as needed.
type Finding struct {
// Rule is the name of the rule that was matched
RuleID string
@@ -21,8 +25,7 @@ type Finding struct {
Match string
// Secret contains the full content of what is matched in
// the tree-sitter query.
// Captured secret
Secret string
// File is the name of the file containing the finding
@@ -42,6 +45,33 @@ type Finding struct {
// unique identifier
Fingerprint string
// Fragment used for multi-part rule checking, CEL filtering,
// and eventually ML validation
Fragment *sources.Fragment `json:",omitempty"`
// TODO keeping private for now to during experimental phase
requiredFindings []*RequiredFinding
}
type RequiredFinding struct {
// contains a subset of the Finding fields
// only used for reporting
RuleID string
StartLine int
EndLine int
StartColumn int
EndColumn int
Line string `json:"-"`
Match string
Secret string
}
func (f *Finding) AddRequiredFindings(afs []*RequiredFinding) {
if f.requiredFindings == nil {
f.requiredFindings = make([]*RequiredFinding, 0)
}
f.requiredFindings = append(f.requiredFindings, afs...)
}
// Redact removes sensitive information from a finding.
@@ -50,8 +80,8 @@ func (f *Finding) Redact(percent uint) {
if percent >= 100 {
secret = "REDACTED"
}
f.Line = strings.Replace(f.Line, f.Secret, secret, -1)
f.Match = strings.Replace(f.Match, f.Secret, secret, -1)
f.Line = strings.ReplaceAll(f.Line, f.Secret, secret)
f.Match = strings.ReplaceAll(f.Match, f.Secret, secret)
f.Secret = secret
}
@@ -68,3 +98,29 @@ func maskSecret(secret string, percent uint) string {
return secret[:lth] + "..."
}
func (f *Finding) PrintRequiredFindings() {
if len(f.requiredFindings) == 0 {
return
}
fmt.Printf("%-12s ", "Required:")
// Create orange style for secrets
orangeStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("#bf9478"))
for i, aux := range f.requiredFindings {
auxSecret := strings.TrimSpace(aux.Secret)
// Truncate long secrets for readability
if len(auxSecret) > 40 {
auxSecret = auxSecret[:37] + "..."
}
// Format: rule-id:line:secret
if i == 0 {
fmt.Printf("%s:%d:%s\n", aux.RuleID, aux.StartLine, orangeStyle.Render(auxSecret))
} else {
fmt.Printf("%-12s %s:%d:%s\n", "", aux.RuleID, aux.StartLine, orangeStyle.Render(auxSecret))
}
}
}
+9 -2
View File
@@ -1,6 +1,7 @@
package report
import (
"errors"
"fmt"
"io"
"os"
@@ -17,7 +18,7 @@ var _ Reporter = (*TemplateReporter)(nil)
func NewTemplateReporter(templatePath string) (*TemplateReporter, error) {
if templatePath == "" {
return nil, fmt.Errorf("template path cannot be empty")
return nil, errors.New("template path cannot be empty")
}
file, err := os.ReadFile(templatePath)
@@ -28,7 +29,13 @@ func NewTemplateReporter(templatePath string) (*TemplateReporter, error) {
// TODO: Add helper functions like escaping for JSON, XML, etc.
t := template.New("custom")
t = t.Funcs(sprig.TxtFuncMap())
funcMap := sprig.TxtFuncMap()
delete(funcMap, "env")
delete(funcMap, "expandenv")
delete(funcMap, "getHostByName")
t = t.Funcs(funcMap)
t, err = t.Parse(templateText)
if err != nil {
return nil, fmt.Errorf("error parsing file: %w", err)
+49
View File
@@ -96,3 +96,52 @@ func TestWriteTemplate(t *testing.T) {
})
}
}
func TestTemplateDangerousFunctions(t *testing.T) {
tests := []struct {
name string
template string
wantErr string
}{
{
name: "env is blocked",
template: `{{ env "SECRET" }}`,
wantErr: `function "env" not defined`,
},
{
name: "expandenv is blocked",
template: `{{ expandenv "$SECRET" }}`,
wantErr: `function "expandenv" not defined`,
},
{
name: "getHostByName is blocked",
template: `{{ getHostByName "localhost" }}`,
wantErr: `function "getHostByName" not defined`,
},
{
name: "now is allowed (benign)",
template: `{{ now | date "2006-01-02" }}`,
wantErr: "", // should not error on parse
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tmpfile, err := os.CreateTemp(t.TempDir(), "test*.tmpl")
require.NoError(t, err)
defer os.Remove(tmpfile.Name())
_, err = tmpfile.WriteString(tt.template)
require.NoError(t, err)
tmpfile.Close()
_, err = NewTemplateReporter(tmpfile.Name())
if tt.wantErr != "" {
assert.Error(t, err)
assert.Contains(t, err.Error(), tt.wantErr)
} else {
assert.NoError(t, err)
}
})
}
}
+80
View File
@@ -0,0 +1,80 @@
#! /usr/bin/env bash
# NAME
# profile.sh - generate gitleaks profile data
#
# USAGE
# profile.sh <gitleaks-path> <benchmark-repo-path>
#
# DESCRIPTION
# Generates profile data for tuning gitleaks performance under ./profile/<timestamp>
#
# Options:
# <gitleaks-path> - gitleaks binary to profile
# <benchmark-repo-path> - git repo to run profile against
#
# SEE ALSO
# Dave Cheney GopherCon 2019 talk on go profiling:
#
# https://www.youtube.com/watch?v=nok0aYiGiYA
#
set -euo pipefail
gitleaks_path="$1"
test_repo_path="$2"
base_scan_cmd="${gitleaks_path} --exit-code=0 --max-decode-depth 8"
base_profile_dir="profile/$(date +%s)"
log() {
echo >&2 "$@"
}
log '========================================================================'
log 'generating profile data'
log '------------------------------------------------------------------------'
# Warm up the fs and also get benchmark data
for scan_mode in dir git
do
profile_dir="${base_profile_dir}/${scan_mode}"
scan_cmd="${base_scan_cmd} ${scan_mode} ${test_repo_path}"
mkdir -p "${profile_dir}"
echo "- mode: ${scan_mode}"
# include hyperfine benchmrak results if hyperfine is installed
if command -v hyperfine > /dev/null
then
export_path="${profile_dir}/benchmark.json"
echo " benchmark:"
echo " tool: hyperfine"
hyperfine -w 3 --export-json "${export_path}" "${scan_cmd}" &> /dev/null
echo " path: ${export_path}"
# Show the results if we can :D
if command -v yq > /dev/null
then
echo " results:"
yq -P -oy \
'.results[] | pick(["mean","stddev","median","user","system","min","max"])' \
${export_path} | sed 's/^/ /g'
else
echo " view: ${PAGER:-less} ${export_path}"
fi
fi
# generate profile data
echo " profile:"
for profile_mode in cpu mem trace
do
# Generate diagnostics data
${scan_cmd} --diagnostics=$profile_mode --diagnostics-dir="${profile_dir}" &> /dev/null
profile_file="$(find "${profile_dir}" -type f -name "${profile_mode}*")"
echo " - mode: ${profile_mode}"
echo " path: ${profile_file}"
if [[ "${profile_mode}" = "trace" ]]
then
echo " view: go tool trace ${profile_file}"
else
echo " view: go tool pprof -http=localhost: ${gitleaks_path} ${profile_file}"
fi
done
done
log '------------------------------------------------------------------------'
log "results in: ${base_profile_dir}"
log '========================================================================'
+125
View File
@@ -0,0 +1,125 @@
package sources
import (
"bufio"
"bytes"
"context"
"io"
"path/filepath"
"runtime"
"github.com/mholt/archives"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/logging"
)
const maxPeekSize = 25 * 1_000 // 10kb
var isWhitespace [256]bool
var isWindows = runtime.GOOS == "windows"
func init() {
// define whitespace characters
isWhitespace[' '] = true
isWhitespace['\t'] = true
isWhitespace['\n'] = true
isWhitespace['\r'] = true
}
// isArchive does a light check to see if the provided path is an archive or
// compressed file. The File source already does this, so this exists mainly
// to avoid expensive calls before sending things to the File source
func isArchive(ctx context.Context, path string) bool {
format, _, err := archives.Identify(ctx, path, nil)
return err == nil && format != nil
}
// shouldSkipPath checks a path against all the allowlists to see if it can
// be skipped
func shouldSkipPath(cfg *config.Config, path string) bool {
if cfg == nil {
logging.Trace().Str("path", path).Msg("not skipping path because config is nil")
return false
}
for _, a := range cfg.Allowlists {
if a.PathAllowed(path) ||
// TODO: Remove this in v9.
// This is an awkward hack to mitigate https://github.com/gitleaks/gitleaks/issues/1641.
(isWindows && a.PathAllowed(filepath.ToSlash(path))) {
return true
}
}
return false
}
// readUntilSafeBoundary consumes |f| until it finds two consecutive `\n` characters, up to |maxPeekSize|.
// This hopefully avoids splitting. (https://github.com/gitleaks/gitleaks/issues/1651)
func readUntilSafeBoundary(r *bufio.Reader, n int, maxPeekSize int, peekBuf *bytes.Buffer) error {
if peekBuf.Len() == 0 {
return nil
}
// Does the buffer end in consecutive newlines?
var (
data = peekBuf.Bytes()
lastChar = data[len(data)-1]
newlineCount = 0 // Tracks consecutive newlines
)
if isWhitespace[lastChar] {
for i := len(data) - 1; i >= 0; i-- {
lastChar = data[i]
if lastChar == '\n' {
newlineCount++
// Stop if two consecutive newlines are found
if newlineCount >= 2 {
return nil
}
} else if isWhitespace[lastChar] {
// The presence of other whitespace characters (`\r`, ` `, `\t`) shouldn't reset the count.
// (Intentionally do nothing.)
} else {
break
}
}
}
// If not, read ahead until we (hopefully) find some.
newlineCount = 0
for {
data = peekBuf.Bytes()
// Check if the last character is a newline.
lastChar = data[len(data)-1]
if lastChar == '\n' {
newlineCount++
// Stop if two consecutive newlines are found
if newlineCount >= 2 {
break
}
} else if isWhitespace[lastChar] {
// The presence of other whitespace characters (`\r`, ` `, `\t`) shouldn't reset the count.
// (Intentionally do nothing.)
} else {
newlineCount = 0 // Reset if a non-newline character is found
}
// Stop growing the buffer if it reaches maxSize
if (peekBuf.Len() - n) >= maxPeekSize {
break
}
// Read additional data into a temporary buffer
b, err := r.ReadByte()
if err != nil {
if err == io.EOF {
break
}
return err
}
peekBuf.WriteByte(b)
}
return nil
}
@@ -1,4 +1,4 @@
package detect
package sources
import (
"bufio"
@@ -65,8 +65,8 @@ func Test_readUntilSafeBoundary(t *testing.T) {
require.NoError(t, err)
// Assert
t.Logf(peekBuf.String())
require.Equal(t, c.expected, string(peekBuf.Bytes()))
t.Log(peekBuf.String())
require.Equal(t, c.expected, peekBuf.String())
})
}
}
-98
View File
@@ -1,98 +0,0 @@
package sources
import (
"io/fs"
"os"
"path/filepath"
"runtime"
"github.com/fatih/semgroup"
"github.com/zricethezav/gitleaks/v8/logging"
)
type ScanTarget struct {
Path string
Symlink string
}
var isWindows = runtime.GOOS == "windows"
func DirectoryTargets(source string, s *semgroup.Group, followSymlinks bool, shouldSkip func(string) bool) (<-chan ScanTarget, error) {
paths := make(chan ScanTarget)
s.Go(func() error {
defer close(paths)
return filepath.Walk(source,
func(path string, fInfo os.FileInfo, err error) error {
logger := logging.With().Str("path", path).Logger()
if err != nil {
if os.IsPermission(err) {
// This seems to only fail on directories at this stage.
logger.Warn().Msg("Skipping directory: permission denied")
return filepath.SkipDir
}
return err
}
// Empty; nothing to do here.
if fInfo.Size() == 0 {
return nil
}
// Unwrap symlinks, if |followSymlinks| is set.
scanTarget := ScanTarget{
Path: path,
}
if fInfo.Mode().Type() == fs.ModeSymlink {
if !followSymlinks {
logger.Debug().Msg("Skipping symlink")
return nil
}
realPath, err := filepath.EvalSymlinks(path)
if err != nil {
return err
}
realPathFileInfo, _ := os.Stat(realPath)
if realPathFileInfo.IsDir() {
logger.Warn().Str("target", realPath).Msg("Skipping symlinked directory")
return nil
}
scanTarget.Path = realPath
scanTarget.Symlink = path
}
// TODO: Also run this check against the resolved symlink?
skip := shouldSkip(path) ||
// TODO: Remove this in v9.
// This is an awkward hack to mitigate https://github.com/gitleaks/gitleaks/issues/1641.
(isWindows && shouldSkip(filepath.ToSlash(path)))
if fInfo.IsDir() {
// Directory
if skip {
logger.Debug().Msg("Skipping directory due to global allowlist")
return filepath.SkipDir
}
if fInfo.Name() == ".git" {
// Don't scan .git directories.
// TODO: Add this to the config allowlist, instead of hard-coding it.
return filepath.SkipDir
}
} else {
// File
if skip {
logger.Debug().Msg("Skipping file due to global allowlist")
return nil
}
paths <- scanTarget
}
return nil
})
})
return paths, nil
}
+264
View File
@@ -0,0 +1,264 @@
package sources
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/h2non/filetype"
"github.com/mholt/archives"
"github.com/rs/zerolog"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/logging"
)
const defaultBufferSize = 100 * 1_000 // 100kb
const InnerPathSeparator = "!"
type seekReaderAt interface {
io.ReaderAt
io.Seeker
}
// File is a source for yielding fragments from a file or other reader
type File struct {
// Content provides a reader to the file's content
Content io.Reader
// Path is the resolved real path of the file
Path string
// Symlink represents a symlink to the file if that's how it was discovered
Symlink string
// Buffer is used for reading the content in chunks
Buffer []byte
// Config is the gitleaks config used for shouldSkipPath. If not set, then
// shouldSkipPath is ignored
Config *config.Config
// outerPaths is the list of container paths (e.g. archives) that lead to
// this file
outerPaths []string
// MaxArchiveDepth limits how deep the sources will explore nested archives
MaxArchiveDepth int
// archiveDepth is the current archive nesting depth
archiveDepth int
}
// Fragments yields fragments for the this source
func (s *File) Fragments(ctx context.Context, yield FragmentsFunc) error {
format, _, err := archives.Identify(ctx, s.Path, nil)
// Process the file as an archive if there's no error && Identify returns
// a format; but if there's an error or no format, just swallow the error
// and fall back on treating it like a normal file and let fileFragments
// decide what to do with it.
if err == nil && format != nil {
if s.archiveDepth+1 > s.MaxArchiveDepth {
var event *zerolog.Event
// Warn if the feature is enabled; else emit a trace log.
if s.MaxArchiveDepth != 0 {
event = logging.Warn()
} else {
event = logging.Trace()
}
event.Str(
"path", s.FullPath(),
).Int(
"max_archive_depth", s.MaxArchiveDepth,
).Msg("skipping archive: exceeds max archive depth")
return nil
}
if extractor, ok := format.(archives.Extractor); ok {
return s.extractorFragments(ctx, extractor, s.Content, yield)
}
if decompressor, ok := format.(archives.Decompressor); ok {
return s.decompressorFragments(ctx, decompressor, s.Content, yield)
}
logging.Warn().Str("path", s.FullPath()).Msg("skipping unknown archive type")
}
return s.fileFragments(ctx, bufio.NewReader(s.Content), yield)
}
// extractorFragments recursively crawls archives and yields fragments
func (s *File) extractorFragments(ctx context.Context, extractor archives.Extractor, reader io.Reader, yield FragmentsFunc) error {
if _, isSeekReaderAt := reader.(seekReaderAt); !isSeekReaderAt {
switch extractor.(type) {
case archives.SevenZip, archives.Zip:
tmpfile, err := os.CreateTemp("", "gitleaks-archive-")
if err != nil {
logging.Error().Str("path", s.FullPath()).Msg("could not create tmp file")
return nil
}
defer func() {
_ = tmpfile.Close()
_ = os.Remove(tmpfile.Name())
}()
_, err = io.Copy(tmpfile, reader)
if err != nil {
logging.Error().Str("path", s.FullPath()).Msg("could not copy archive file")
return nil
}
reader = tmpfile
}
}
return extractor.Extract(ctx, reader, func(_ context.Context, d archives.FileInfo) error {
if d.IsDir() {
return nil
}
innerReader, err := d.Open()
if err != nil {
logging.Error().Err(err).Str("path", s.FullPath()).Msg("could not open archive inner file")
return nil
}
defer innerReader.Close()
path := filepath.Clean(d.NameInArchive)
if s.Config != nil && shouldSkipPath(s.Config, path) {
logging.Debug().Str("path", s.FullPath()).Msg("skipping file: global allowlist")
return nil
}
file := &File{
Content: innerReader,
Path: path,
Symlink: s.Symlink,
outerPaths: append(s.outerPaths, filepath.ToSlash(s.Path)),
MaxArchiveDepth: s.MaxArchiveDepth,
archiveDepth: s.archiveDepth + 1,
}
if err := file.Fragments(ctx, yield); err != nil {
return err
}
return nil
})
}
// decompressorFragments recursively crawls archives and yields fragments
func (s *File) decompressorFragments(ctx context.Context, decompressor archives.Decompressor, reader io.Reader, yield FragmentsFunc) error {
innerReader, err := decompressor.OpenReader(reader)
if err != nil {
logging.Error().Str("path", s.FullPath()).Msg("could read compressed file")
return nil
}
if err := s.fileFragments(ctx, bufio.NewReader(innerReader), yield); err != nil {
_ = innerReader.Close()
return err
}
_ = innerReader.Close()
return nil
}
// fileFragments reads the file into fragments to yield
func (s *File) fileFragments(ctx context.Context, reader *bufio.Reader, yield FragmentsFunc) error {
// Create a buffer if the caller hasn't provided one
if s.Buffer == nil {
s.Buffer = make([]byte, defaultBufferSize)
}
totalLines := 0
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
fragment := Fragment{
FilePath: s.FullPath(),
}
n, err := reader.Read(s.Buffer)
if n == 0 {
if err != nil && err != io.EOF {
return yield(fragment, fmt.Errorf("could not read file: %w", err))
}
return nil
}
// Only check the filetype at the start of file.
if totalLines == 0 {
// TODO: could other optimizations be introduced here?
if mimetype, err := filetype.Match(s.Buffer[:n]); err != nil {
return yield(
fragment,
fmt.Errorf("could not read file: could not determine type: %w", err),
)
} else if mimetype.MIME.Type == "application" {
logging.Debug().
Str("mime_type", mimetype.MIME.Value).
Str("path", s.FullPath()).
Msgf("skipping binary file")
return nil
}
}
// Try to split chunks across large areas of whitespace, if possible.
peekBuf := bytes.NewBuffer(s.Buffer[:n])
if err := readUntilSafeBoundary(reader, n, maxPeekSize, peekBuf); err != nil {
return yield(
fragment,
fmt.Errorf("could not read file: could not read until safe boundary: %w", err),
)
}
fragment.Raw = peekBuf.String()
fragment.Bytes = peekBuf.Bytes()
fragment.StartLine = totalLines + 1
// Count the number of newlines in this chunk
totalLines += strings.Count(fragment.Raw, "\n")
if len(s.Symlink) > 0 {
fragment.SymlinkFile = s.Symlink
}
if isWindows {
fragment.FilePath = filepath.ToSlash(fragment.FilePath)
fragment.SymlinkFile = filepath.ToSlash(s.Symlink)
fragment.WindowsFilePath = s.FullPath()
}
// log errors but continue since there's content
if err != nil && err != io.EOF {
logging.Warn().Err(err).Msgf("issue reading file")
}
// Done with the file!
if err == io.EOF {
return yield(fragment, nil)
}
if err := yield(fragment, err); err != nil {
return err
}
}
}
}
// FullPath returns the File.Path with any preceding outer paths
func (s *File) FullPath() string {
if len(s.outerPaths) > 0 {
return strings.Join(
// outerPaths have already been normalized to slash
append(s.outerPaths, s.Path),
InnerPathSeparator,
)
}
return s.Path
}
+191
View File
@@ -0,0 +1,191 @@
package sources
import (
"context"
"errors"
"io/fs"
"os"
"path/filepath"
"sync"
"github.com/fatih/semgroup"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/logging"
)
// TODO: remove this in v9 and have scanTargets yield file sources
type ScanTarget struct {
Path string
Symlink string
}
// Deprecated: Use Files and detector.DetectSource instead
func DirectoryTargets(sourcePath string, s *semgroup.Group, followSymlinks bool, allowlists []*config.Allowlist) (<-chan ScanTarget, error) {
paths := make(chan ScanTarget)
// create a Files source
files := Files{
FollowSymlinks: followSymlinks,
Path: sourcePath,
Sema: s,
Config: &config.Config{
Allowlists: allowlists,
},
}
s.Go(func() error {
ctx := context.Background()
err := files.scanTargets(ctx, func(scanTarget ScanTarget, err error) error {
paths <- scanTarget
return nil
})
close(paths)
return err
})
return paths, nil
}
// Files is a source for yielding fragments from a collection of files
type Files struct {
Config *config.Config
FollowSymlinks bool
MaxFileSize int
Path string
Sema *semgroup.Group
MaxArchiveDepth int
}
// scanTargets yields scan targets to a callback func
func (s *Files) scanTargets(ctx context.Context, yield func(ScanTarget, error) error) error {
return filepath.WalkDir(s.Path, func(path string, d fs.DirEntry, err error) error {
scanTarget := ScanTarget{Path: path}
logger := logging.With().Str("path", path).Logger()
if err != nil {
if os.IsPermission(err) {
// This seems to only fail on directories at this stage.
logger.Warn().Err(errors.New("permission denied")).Msg("skipping directory")
return filepath.SkipDir
}
logger.Warn().Err(err).Msg("skipping")
return nil
}
info, err := d.Info()
if err != nil {
if d.IsDir() {
logger.Error().Err(err).Msg("skipping directory: could not get info")
return filepath.SkipDir
}
logger.Error().Err(err).Msg("skipping file: could not get info")
return nil
}
if !d.IsDir() {
// Empty; nothing to do here.
if info.Size() == 0 {
logger.Debug().Msg("skipping empty file")
return nil
}
// Too large; nothing to do here.
if s.MaxFileSize > 0 && info.Size() > int64(s.MaxFileSize) {
logger.Warn().Msgf(
"skipping file: too large max_size=%dMB, size=%dMB",
s.MaxFileSize/1_000_000, info.Size()/1_000_000,
)
return nil
}
}
// set the initial scan target values
if d.Type() == fs.ModeSymlink {
if !s.FollowSymlinks {
logger.Debug().Msg("skipping symlink: follow symlinks disabled")
return nil
}
realPath, err := filepath.EvalSymlinks(path)
if err != nil {
logger.Error().Err(err).Msg("skipping symlink: could not evaluate")
return nil
}
if realPathFileInfo, _ := os.Stat(realPath); realPathFileInfo.IsDir() {
logger.Debug().Str("target", realPath).Msgf("skipping symlink: target is directory")
return nil
}
scanTarget = ScanTarget{
Path: realPath,
Symlink: path,
}
}
// handle dir cases (mainly just see if it should be skipped
if info.IsDir() {
if shouldSkipPath(s.Config, path) {
logger.Debug().Msg("skipping directory: global allowlist")
return filepath.SkipDir
}
return nil
}
if shouldSkipPath(s.Config, path) {
logger.Debug().Msg("skipping file: global allowlist")
return nil
}
return yield(scanTarget, nil)
})
}
// Fragments yields fragments from files discovered under the path
func (s *Files) Fragments(ctx context.Context, yield FragmentsFunc) error {
var wg sync.WaitGroup
err := s.scanTargets(ctx, func(scanTarget ScanTarget, err error) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
wg.Add(1)
s.Sema.Go(func() error {
logger := logging.With().Str("path", scanTarget.Path).Logger()
logger.Trace().Msg("scanning path")
f, err := os.Open(scanTarget.Path)
if err != nil {
if os.IsPermission(err) {
logger.Warn().Msg("skipping file: permission denied")
}
wg.Done()
return nil
}
// Convert this to a file source
file := File{
Content: f,
Path: scanTarget.Path,
Symlink: scanTarget.Symlink,
Config: s.Config,
MaxArchiveDepth: s.MaxArchiveDepth,
}
err = file.Fragments(ctx, yield)
// Avoiding a defer in a hot loop
_ = f.Close()
wg.Done()
return err
})
return nil
}
})
select {
case <-ctx.Done():
return ctx.Err()
default:
wg.Wait()
return err
}
}
+28
View File
@@ -0,0 +1,28 @@
package sources
// Fragment represents a fragment of a source with its meta data
type Fragment struct {
// Raw is the raw content of the fragment
Raw string
Bytes []byte
// FilePath is the path to the file if applicable.
// The path separator MUST be normalized to `/`.
FilePath string
SymlinkFile string
// WindowsFilePath is the path with the original separator.
// This provides a backwards-compatible solution to https://github.com/gitleaks/gitleaks/issues/1565.
WindowsFilePath string `json:"-"` // TODO: remove this in v9.
// CommitSHA is the SHA of the commit if applicable
CommitSHA string // TODO: remove this in v9 and use CommitInfo instead
// StartLine is the line number this fragment starts on
StartLine int
// CommitInfo captures additional information about the git commit if applicable
CommitInfo *CommitInfo
InheritedFromFinding bool // Indicates if this fragment is inherited from a finding
}
+347 -6
View File
@@ -2,15 +2,24 @@ package sources
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io"
"net/url"
"os/exec"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
"github.com/fatih/semgroup"
"github.com/gitleaks/go-gitdiff/gitdiff"
"github.com/zricethezav/gitleaks/v8/cmd/scm"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/logging"
)
@@ -21,12 +30,45 @@ type GitCmd struct {
cmd *exec.Cmd
diffFilesCh <-chan *gitdiff.File
errCh <-chan error
repoPath string
}
// blobReader provides a ReadCloser interface git cat-file blob to fetch
// a blob from a repo
type blobReader struct {
io.ReadCloser
cmd *exec.Cmd
}
// Close closes the underlying reader and then waits for the command to complete,
// releasing its resources.
func (br *blobReader) Close() error {
// Discard the remaining data from the pipe to avoid blocking
_, drainErr := io.Copy(io.Discard, br)
// Close the pipe (should signal the command to stop if it hasn't already)
closeErr := br.ReadCloser.Close()
// Wait to prevent zombie processes.
waitErr := br.cmd.Wait()
// Return the first error encountered
if drainErr != nil {
return drainErr
}
if closeErr != nil {
return closeErr
}
return waitErr
}
// NewGitLogCmd returns `*DiffFilesCmd` with two channels: `<-chan *gitdiff.File` and `<-chan error`.
// Caller should read everything from channels until receiving a signal about their closure and call
// the `func (*DiffFilesCmd) Wait()` error in order to release resources.
func NewGitLogCmd(source string, logOpts string) (*GitCmd, error) {
return NewGitLogCmdContext(context.Background(), source, logOpts)
}
// NewGitLogCmdContext is the same as NewGitLogCmd but supports passing in a
// context to use for timeouts
func NewGitLogCmdContext(ctx context.Context, source string, logOpts string) (*GitCmd, error) {
sourceClean := filepath.Clean(source)
var cmd *exec.Cmd
if logOpts != "" {
@@ -46,10 +88,10 @@ func NewGitLogCmd(source string, logOpts string) (*GitCmd, error) {
}
args = append(args, userArgs...)
cmd = exec.Command("git", args...)
cmd = exec.CommandContext(ctx, "git", args...)
} else {
cmd = exec.Command("git", "-C", sourceClean, "log", "-p", "-U0",
"--full-history", "--all")
cmd = exec.CommandContext(ctx, "git", "-C", sourceClean, "log", "-p", "-U0",
"--full-history", "--all", "--diff-filter=tuxdb")
}
logging.Debug().Msgf("executing: %s", cmd.String())
@@ -78,6 +120,7 @@ func NewGitLogCmd(source string, logOpts string) (*GitCmd, error) {
cmd: cmd,
diffFilesCh: gitdiffFiles,
errCh: errCh,
repoPath: sourceClean,
}, nil
}
@@ -85,11 +128,17 @@ func NewGitLogCmd(source string, logOpts string) (*GitCmd, error) {
// Caller should read everything from channels until receiving a signal about their closure and call
// the `func (*DiffFilesCmd) Wait()` error in order to release resources.
func NewGitDiffCmd(source string, staged bool) (*GitCmd, error) {
return NewGitDiffCmdContext(context.Background(), source, staged)
}
// NewGitDiffCmdContext is the same as NewGitDiffCmd but supports passing in a
// context to use for timeouts
func NewGitDiffCmdContext(ctx context.Context, source string, staged bool) (*GitCmd, error) {
sourceClean := filepath.Clean(source)
var cmd *exec.Cmd
cmd = exec.Command("git", "-C", sourceClean, "diff", "-U0", "--no-ext-diff", ".")
cmd = exec.CommandContext(ctx, "git", "-C", sourceClean, "diff", "-U0", "--no-ext-diff", ".")
if staged {
cmd = exec.Command("git", "-C", sourceClean, "diff", "-U0", "--no-ext-diff",
cmd = exec.CommandContext(ctx, "git", "-C", sourceClean, "diff", "-U0", "--no-ext-diff",
"--staged", ".")
}
logging.Debug().Msgf("executing: %s", cmd.String())
@@ -118,6 +167,7 @@ func NewGitDiffCmd(source string, staged bool) (*GitCmd, error) {
cmd: cmd,
diffFilesCh: gitdiffFiles,
errCh: errCh,
repoPath: sourceClean,
}, nil
}
@@ -135,10 +185,42 @@ func (c *GitCmd) ErrCh() <-chan error {
// stdin or copying from stdout or stderr to complete.
//
// Wait also closes underlying stdout and stderr.
func (c *GitCmd) Wait() (err error) {
func (c *GitCmd) Wait() error {
return c.cmd.Wait()
}
// String displays the command used for GitCmd
func (c *GitCmd) String() string {
return c.cmd.String()
}
// NewBlobReader returns an io.ReadCloser that can be used to read a blob
// within the git repo used to create the GitCmd.
//
// The caller is responsible for closing the reader.
func (c *GitCmd) NewBlobReader(commit, path string) (io.ReadCloser, error) {
return c.NewBlobReaderContext(context.Background(), commit, path)
}
// NewBlobReaderContext is the same as NewBlobReader but supports passing in a
// context to use for timeouts
func (c *GitCmd) NewBlobReaderContext(ctx context.Context, commit, path string) (io.ReadCloser, error) {
gitArgs := []string{"-C", c.repoPath, "cat-file", "blob", commit + ":" + path}
cmd := exec.CommandContext(ctx, "git", gitArgs...)
cmd.Stderr = io.Discard
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, fmt.Errorf("failed to get stdout pipe: %w", err)
}
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("failed to start git command: %w", err)
}
return &blobReader{
ReadCloser: stdout,
cmd: cmd,
}, nil
}
// listenForStdErr listens for stderr output from git, prints it to stdout,
// sends to errCh and closes it.
func listenForStdErr(stderr io.ReadCloser, errCh chan<- error) {
@@ -187,3 +269,262 @@ func listenForStdErr(stderr io.ReadCloser, errCh chan<- error) {
return
}
}
// RemoteInfo provides the info needed for reconstructing links from findings
type RemoteInfo struct {
Platform scm.Platform
Url string
}
// Git is a source for yielding fragments from a git repo
type Git struct {
Cmd *GitCmd
Config *config.Config
Remote *RemoteInfo
Sema *semgroup.Group
MaxArchiveDepth int
}
// CommitInfo captures metadata about the commit
type CommitInfo struct {
AuthorEmail string
AuthorName string
Date string
Message string
Remote *RemoteInfo
SHA string
}
// Fragments yields fragments from a git repo
func (s *Git) Fragments(ctx context.Context, yield FragmentsFunc) error {
defer func() {
if err := s.Cmd.Wait(); err != nil {
logging.Debug().Err(err).Str("cmd", s.Cmd.String()).Msg("command aborted")
}
}()
var (
diffFilesCh = s.Cmd.DiffFilesCh()
errCh = s.Cmd.ErrCh()
wg sync.WaitGroup
)
// loop to range over both DiffFiles (stdout) and ErrCh (stderr)
for diffFilesCh != nil || errCh != nil {
select {
case <-ctx.Done():
return ctx.Err()
case gitdiffFile, open := <-diffFilesCh:
if !open {
diffFilesCh = nil
break
}
if gitdiffFile.IsDelete {
continue
}
// skip non-archive binary files
yieldAsArchive := false
if gitdiffFile.IsBinary {
if !isArchive(ctx, gitdiffFile.NewName) {
continue
}
yieldAsArchive = true
}
// Check if commit is allowed
commitSHA := ""
var commitInfo *CommitInfo
if gitdiffFile.PatchHeader != nil {
commitSHA = gitdiffFile.PatchHeader.SHA
for _, a := range s.Config.Allowlists {
if ok, c := a.CommitAllowed(gitdiffFile.PatchHeader.SHA); ok {
logging.Trace().Str("allowed-commit", c).Msg("skipping commit: global allowlist")
continue
}
}
commitInfo = &CommitInfo{
Date: gitdiffFile.PatchHeader.AuthorDate.UTC().Format(time.RFC3339),
Message: gitdiffFile.PatchHeader.Message(),
Remote: s.Remote,
SHA: commitSHA,
}
if gitdiffFile.PatchHeader.Author != nil {
commitInfo.AuthorName = gitdiffFile.PatchHeader.Author.Name
commitInfo.AuthorEmail = gitdiffFile.PatchHeader.Author.Email
}
}
wg.Add(1)
s.Sema.Go(func() error {
defer wg.Done()
if yieldAsArchive {
blob, err := s.Cmd.NewBlobReaderContext(ctx, commitSHA, gitdiffFile.NewName)
if err != nil {
logging.Error().Err(err).Msg("could not read archive blob")
return nil
}
file := File{
Content: blob,
Path: gitdiffFile.NewName,
MaxArchiveDepth: s.MaxArchiveDepth,
Config: s.Config,
}
// enrich and yield fragments
err = file.Fragments(ctx, func(fragment Fragment, err error) error {
fragment.CommitSHA = commitSHA
fragment.CommitInfo = commitInfo
return yield(fragment, err)
})
// Close the blob reader and log any issues
if err := blob.Close(); err != nil {
logging.Debug().Err(err).Msg("blobReader.Close() returned an error")
}
return err
}
for _, textFragment := range gitdiffFile.TextFragments {
if textFragment == nil {
return nil
}
fragment := Fragment{
CommitSHA: commitSHA,
FilePath: gitdiffFile.NewName,
Raw: textFragment.Raw(gitdiff.OpAdd),
StartLine: int(textFragment.NewPosition),
CommitInfo: commitInfo,
}
if err := yield(fragment, nil); err != nil {
return err
}
}
return nil
})
case err, open := <-errCh:
if !open {
errCh = nil
break
}
return yield(Fragment{}, err)
}
}
select {
case <-ctx.Done():
return ctx.Err()
default:
wg.Wait()
return nil
}
}
// NewRemoteInfo builds a new RemoteInfo for generating finding links
func NewRemoteInfo(platform scm.Platform, source string) *RemoteInfo {
return NewRemoteInfoContext(context.Background(), platform, source)
}
// NewRemoteInfoContext is the same as NewRemoteInfo but supports passing in a
// context to use for timeouts
func NewRemoteInfoContext(ctx context.Context, platform scm.Platform, source string) *RemoteInfo {
if platform == scm.NoPlatform {
return &RemoteInfo{Platform: platform}
}
remoteUrl, err := getRemoteUrl(ctx, source)
if err != nil {
if strings.Contains(err.Error(), "No remote configured") {
logging.Debug().Msg("skipping finding links: repository has no configured remote.")
platform = scm.NoPlatform
} else {
logging.Error().Err(err).Msg("skipping finding links: unable to parse remote URL")
}
goto End
}
if platform == scm.UnknownPlatform {
platform = platformFromHost(remoteUrl)
if platform == scm.UnknownPlatform {
logging.Info().
Str("host", remoteUrl.Hostname()).
Msg("Unknown SCM platform. Use --platform to include links in findings.")
} else {
logging.Debug().
Str("host", remoteUrl.Hostname()).
Str("platform", platform.String()).
Msg("SCM platform parsed from host")
}
}
End:
var rUrl string
if remoteUrl != nil {
rUrl = remoteUrl.String()
}
return &RemoteInfo{
Platform: platform,
Url: rUrl,
}
}
var sshUrlpat = regexp.MustCompile(`^git@([a-zA-Z0-9.-]+):(?:\d{1,5}/)?([\w/.-]+?)(?:\.git)?$`)
func getRemoteUrl(ctx context.Context, source string) (*url.URL, error) {
// This will return the first remote — typically, "origin".
cmd := exec.CommandContext(ctx, "git", "ls-remote", "--quiet", "--get-url")
if source != "." {
cmd.Dir = source
}
stdout, err := cmd.Output()
if err != nil {
var exitError *exec.ExitError
if errors.As(err, &exitError) {
return nil, fmt.Errorf("command failed (%d): %w, stderr: %s", exitError.ExitCode(), err, string(bytes.TrimSpace(exitError.Stderr)))
}
return nil, err
}
remoteUrl := string(bytes.TrimSpace(stdout))
if matches := sshUrlpat.FindStringSubmatch(remoteUrl); matches != nil {
remoteUrl = fmt.Sprintf("https://%s/%s", matches[1], matches[2])
}
remoteUrl = strings.TrimSuffix(remoteUrl, ".git")
parsedUrl, err := url.Parse(remoteUrl)
if err != nil {
return nil, fmt.Errorf("unable to parse remote URL: %w", err)
}
// Remove any user info.
parsedUrl.User = nil
return parsedUrl, nil
}
func platformFromHost(u *url.URL) scm.Platform {
switch strings.ToLower(u.Hostname()) {
case "github.com":
return scm.GitHubPlatform
case "gitlab.com":
return scm.GitLabPlatform
case "dev.azure.com", "visualstudio.com":
return scm.AzureDevOpsPlatform
case "gitea.com", "code.forgejo.org", "codeberg.org":
return scm.GiteaPlatform
case "bitbucket.org":
return scm.BitbucketPlatform
default:
return scm.UnknownPlatform
}
}
+16
View File
@@ -0,0 +1,16 @@
package sources
import (
"context"
)
// FragmentsFunc is the type of function called by Fragments to yield the next
// fragment
type FragmentsFunc func(fragment Fragment, err error) error
// Source is a thing that can yield fragments
type Source interface {
// Fragments provides a filepath.WalkDir like interface for scanning the
// fragments in the source
Fragments(ctx context.Context, yield FragmentsFunc) error
}
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+6
View File
@@ -0,0 +1,6 @@
DB_HOST=example.com
DB_PORT=443
DB_USERNAME=postgres
DB_PASSWORD=8ae31cacf141669ddfb5da
DB_NAME=best_db
DB_SSL=true
Loaded 100 of 175 files, more files were not shown because too many files have changed in this diff. Show more