Compare commits

...
53 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
52 changed files with 1455 additions and 415 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: .
+3 -3
View File
@@ -15,12 +15,12 @@ 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 ./...
+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
+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:
+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/
+1 -1
View File
@@ -2,7 +2,7 @@
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:
+101 -31
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,24 +23,17 @@
[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]
[![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`. 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
@@ -61,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).
@@ -85,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
@@ -141,10 +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
dir scan directories or files for secrets
git scan git repositories for secrets
help Help about any command
@@ -160,16 +139,16 @@ 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 (comma-separated list: cpu,mem,trace). cpu=CPU profiling, mem=memory profiling, trace=execution tracing
--diagnostics-dir string directory to store diagnostics output files (defaults to current directory)
--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-decode-depth int allow recursive decoding up to this depth (default "0", no decoding is done)
--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
@@ -177,6 +156,7 @@ Flags:
-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
@@ -415,6 +395,94 @@ Refer to the default [gitleaks config](https://github.com/gitleaks/gitleaks/blob
### 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
@@ -558,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).
+5 -8
View File
@@ -19,7 +19,6 @@
package cmd
import (
"context"
"os"
"time"
@@ -66,18 +65,16 @@ func runDetect(cmd *cobra.Command, args []string) {
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 (
err error
findings []report.Finding
ctx = context.Background()
)
if noGit {
findings, err = detector.DetectSource(
ctx, &sources.Files{
cmd.Context(), &sources.Files{
Config: &cfg,
FollowSymlinks: detector.FollowSymlinks,
MaxFileSize: detector.MaxTargetMegaBytes * 1_000_000,
@@ -93,7 +90,7 @@ func runDetect(cmd *cobra.Command, args []string) {
}
} else if fromPipe {
findings, err = detector.DetectSource(
ctx, &sources.File{
cmd.Context(), &sources.File{
Content: os.Stdin,
MaxArchiveDepth: detector.MaxArchiveDepth,
},
@@ -111,7 +108,7 @@ func runDetect(cmd *cobra.Command, args []string) {
)
logOpts := mustGetStringFlag(cmd, "log-opts")
if gitCmd, err = sources.NewGitLogCmd(sourcePath, logOpts); err != nil {
if gitCmd, err = sources.NewGitLogCmdContext(cmd.Context(), sourcePath, logOpts); err != nil {
logging.Fatal().Err(err).Msg("could not create Git cmd")
}
@@ -120,10 +117,10 @@ func runDetect(cmd *cobra.Command, args []string) {
}
findings, err = detector.DetectSource(
ctx, &sources.Git{
cmd.Context(), &sources.Git{
Cmd: gitCmd,
Config: &detector.Config,
Remote: sources.NewRemoteInfo(scmPlatform, sourcePath),
Remote: sources.NewRemoteInfoContext(cmd.Context(), scmPlatform, sourcePath),
Sema: detector.Sema,
MaxArchiveDepth: detector.MaxArchiveDepth,
},
+1 -2
View File
@@ -1,7 +1,6 @@
package cmd
import (
"context"
"time"
"github.com/spf13/cobra"
@@ -56,7 +55,7 @@ func runDirectory(cmd *cobra.Command, args []string) {
}
findings, err := detector.DetectSource(
context.Background(),
cmd.Context(),
&sources.Files{
Config: &cfg,
FollowSymlinks: detector.FollowSymlinks,
+10 -1
View File
@@ -31,10 +31,17 @@ func main() {
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(),
@@ -146,6 +153,8 @@ func main() {
rules.LinkedinClientSecret(),
rules.LobAPIToken(),
rules.LobPubAPIToken(),
rules.LookerClientID(),
rules.LookerClientSecret(),
rules.MailChimp(),
rules.MailGunPubAPIToken(),
rules.MailGunPrivateAPIToken(),
+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)
}
+60
View File
@@ -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)
}
+5
View File
@@ -13,6 +13,11 @@
title = "{{.Title}}"
# 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 }}
+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)
}
+19 -19
View File
@@ -6,34 +6,34 @@ import (
)
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,
}
// Define the identifiers that match the Keywords
identifiers := []string{"ntn_"}
// validate
// 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{
fps := []string{
"ntn_12345678901",
"ntn_123456789012345678901234567890123456789012345678901234567890",
"ntn_12345678901abc",
}
return utils.Validate(r, tps, fps)
}
return utils.Validate(r, tps, fps)
}
+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)
}
+4 -5
View File
@@ -1,7 +1,6 @@
package cmd
import (
"context"
"time"
"github.com/spf13/cobra"
@@ -63,13 +62,13 @@ func runGit(cmd *cobra.Command, args []string) {
)
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.
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 {
@@ -78,11 +77,11 @@ func runGit(cmd *cobra.Command, args []string) {
}
findings, err = detector.DetectSource(
context.Background(),
cmd.Context(),
&sources.Git{
Cmd: gitCmd,
Config: &detector.Config,
Remote: sources.NewRemoteInfo(scmPlatform, source),
Remote: sources.NewRemoteInfoContext(cmd.Context(), scmPlatform, source),
Sema: detector.Sema,
MaxArchiveDepth: detector.MaxArchiveDepth,
},
+1 -1
View File
@@ -53,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}
+19 -10
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 = `
@@ -42,7 +44,18 @@ var (
rootCmd = &cobra.Command{
Use: "gitleaks",
Short: "Gitleaks scans code, past or present, for secrets",
Version: Version,
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
@@ -61,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")
@@ -75,9 +88,9 @@ 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().BoolP("experimental-optimizations", "", false, "enables experimental allowlist optimizations, increasing performance at the cost of startup time")
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")
@@ -223,11 +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")
}
// set experimental feature flag(s)
if mustGetBoolFlag(cmd, "experimental-optimizations") {
logging.Warn().Msgf("using experimental allowlist optimizations, updates may contain breaking changes!")
vc.EnableExperimentalAllowlistOptimizations = true
}
cfg, err := vc.Translate()
if err != nil {
logging.Fatal().Err(err).Msg("Failed to load config")
@@ -241,7 +250,7 @@ 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).Send()
+1 -2
View File
@@ -1,7 +1,6 @@
package cmd
import (
"context"
"os"
"time"
@@ -38,7 +37,7 @@ func runStdIn(cmd *cobra.Command, _ []string) {
exitCode := mustGetIntFlag(cmd, "exit-code")
findings, err := detector.DetectSource(
context.Background(),
cmd.Context(),
&sources.File{
Content: os.Stdin,
MaxArchiveDepth: detector.MaxArchiveDepth,
+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)
}
+9 -22
View File
@@ -59,11 +59,6 @@ type Allowlist struct {
// validated is an internal flag to track whether `Validate()` has been called.
validated bool
// EnableExperimentalOptimizations must be set prior to calling `Validate()`.
// See: https://github.com/gitleaks/gitleaks/pull/1731
//
// NOTE: This flag may be removed in the future.
EnableExperimentalOptimizations 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{}
@@ -92,11 +87,8 @@ func (a *Allowlist) Validate() error {
// Commits are case-insensitive.
uniqueCommits[strings.TrimSpace(strings.ToLower(commit))] = struct{}{}
}
if a.EnableExperimentalOptimizations {
a.commitMap = uniqueCommits
} else {
a.Commits = maps.Keys(uniqueCommits)
}
a.Commits = maps.Keys(uniqueCommits)
a.commitMap = uniqueCommits
}
if len(a.StopWords) > 0 {
uniqueStopwords := make(map[string]struct{})
@@ -105,21 +97,16 @@ func (a *Allowlist) Validate() error {
}
values := maps.Keys(uniqueStopwords)
if a.EnableExperimentalOptimizations {
a.stopwordTrie = ahocorasick.NewTrieBuilder().AddStrings(values).Build()
} else {
a.StopWords = values
}
a.StopWords = values
a.stopwordTrie = ahocorasick.NewTrieBuilder().AddStrings(values).Build()
}
// Combine patterns into a single expression.
if a.EnableExperimentalOptimizations {
if len(a.Paths) > 0 {
a.pathPat = joinRegexOr(a.Paths)
}
if len(a.Regexes) > 0 {
a.regexPat = joinRegexOr(a.Regexes)
}
if len(a.Paths) > 0 {
a.pathPat = joinRegexOr(a.Paths)
}
if len(a.Regexes) > 0 {
a.regexPat = joinRegexOr(a.Regexes)
}
a.validated = true
+1 -1
View File
@@ -151,7 +151,7 @@ func TestValidate(t *testing.T) {
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)
}
}
+109 -24
View File
@@ -7,10 +7,12 @@ import (
"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"
)
var (
@@ -43,19 +45,27 @@ type ViperConfig struct {
// Deprecated: this is a shim for backwards-compatibility.
// TODO: Remove this in 9.x.
AllowList *viperRuleAllowlist
AllowList *viperRuleAllowlist
Allowlists []*viperRuleAllowlist
Required []*viperRequired
SkipReport bool
}
// Deprecated: this is a shim for backwards-compatibility.
// TODO: Remove this in 9.x.
AllowList *viperGlobalAllowlist
AllowList *viperGlobalAllowlist
Allowlists []*viperGlobalAllowlist
// EnableExperimentalAllowlistOptimizations enables a preview feature.
// See: https://github.com/gitleaks/gitleaks/pull/1731
//
// NOTE: This flag may be removed in the future.
EnableExperimentalAllowlistOptimizations bool
MinVersion string
configPath string
}
type viperRequired struct {
ID string
WithinLines *int `mapstructure:"withinLines"`
WithinColumns *int `mapstructure:"withinColumns"`
}
type viperRuleAllowlist struct {
@@ -84,6 +94,7 @@ type Config 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
@@ -136,6 +147,7 @@ func (vc *ViperConfig) Translate() (Config, error) {
Path: pathPat,
Keywords: vr.Keywords,
Tags: vr.Tags,
SkipReport: vr.SkipReport,
}
// Parse the rule allowlists, including the older format for backwards compatibility.
@@ -153,10 +165,34 @@ func (vc *ViperConfig) Translate() (Config, error) {
}
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
}
// 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{
Title: vc.Title,
@@ -165,7 +201,22 @@ func (vc *ViperConfig) Translate() (Config, error) {
Rules: rulesMap,
Keywords: keywords,
OrderedRules: orderedRules,
MinVersion: vc.MinVersion,
}
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.
@@ -190,7 +241,8 @@ func (vc *ViperConfig) Translate() (Config, error) {
}
}
if maxExtendDepth != extendDepth {
currentExtendDepth := extendDepth
if maxExtendDepth != currentExtendDepth {
// disallow both usedefault and path from being set
if c.Extend.Path != "" && c.Extend.UseDefault {
return Config{}, errors.New("unable to load config due to extend.path and extend.useDefault being set")
@@ -207,7 +259,7 @@ func (vc *ViperConfig) Translate() (Config, error) {
}
// Validate the rules after everything has been assembled (including extended configs).
if extendDepth == 0 {
if currentExtendDepth == 0 {
for _, rule := range c.Rules {
if err := rule.Validate(); err != nil {
return Config{}, err
@@ -228,6 +280,41 @@ func (vc *ViperConfig) Translate() (Config, error) {
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) {
@@ -261,14 +348,13 @@ func (vc *ViperConfig) parseAllowlist(a *viperRuleAllowlist) (*Allowlist, error)
}
allowlist := &Allowlist{
Description: a.Description,
MatchCondition: matchCondition,
Commits: a.Commits,
Paths: allowlistPaths,
RegexTarget: regexTarget,
Regexes: allowlistRegexes,
StopWords: a.StopWords,
EnableExperimentalOptimizations: vc.EnableExperimentalAllowlistOptimizations,
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
@@ -292,9 +378,7 @@ func (c *Config) extendDefault(parent *ViperConfig) error {
if err := viper.ReadConfig(strings.NewReader(DefaultConfig)); err != nil {
return fmt.Errorf("failed to load extended default config, err: %w", err)
}
defaultViperConfig := ViperConfig{
EnableExperimentalAllowlistOptimizations: parent.EnableExperimentalAllowlistOptimizations,
}
defaultViperConfig := ViperConfig{}
if err := viper.Unmarshal(&defaultViperConfig); err != nil {
return fmt.Errorf("failed to load extended default config, err: %w", err)
}
@@ -314,17 +398,17 @@ func (c *Config) extendPath(parent *ViperConfig) error {
if err := viper.ReadInConfig(); err != nil {
return fmt.Errorf("failed to load extended config, err: %w", err)
}
extensionViperConfig := ViperConfig{
EnableExperimentalAllowlistOptimizations: parent.EnableExperimentalAllowlistOptimizations,
}
extensionViperConfig := ViperConfig{}
if err := viper.Unmarshal(&extensionViperConfig); err != nil {
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 {
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
}
@@ -404,4 +488,5 @@ func (c *Config) extend(extensionConfig Config) {
// sort to keep extended rules in order
sort.Strings(c.OrderedRules)
return
}
+17 -4
View File
@@ -93,7 +93,7 @@ func TestTranslate(t *testing.T) {
{
cfgName: "invalid/rule_missing_id",
cfg: Config{},
wantError: errors.New("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: "invalid/rule_no_regex_or_path",
@@ -449,7 +449,7 @@ func TestTranslateExtend(t *testing.T) {
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:a)(?:a)"),
Regex: regexp.MustCompile("(a)(a)"),
SecretGroup: 2,
Keywords: []string{},
Tags: []string{"key", "AWS"},
@@ -563,6 +563,10 @@ func TestTranslateExtend(t *testing.T) {
},
// Invalid
{
cfgName: "invalid/extend_invalid_ruleid",
wantError: errors.New("rule |id| is missing or empty"),
},
}
for _, tt := range tests {
@@ -589,8 +593,17 @@ func testTranslate(t *testing.T, test translateCase) {
err = viper.Unmarshal(&vc)
require.NoError(t, err)
cfg, err := vc.Translate()
if err != nil && !assert.EqualError(t, err, test.wantError.Error()) {
return
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 {
+65 -1
View File
@@ -13,6 +13,11 @@
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"
@@ -109,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."
@@ -129,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."
@@ -182,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"
@@ -2478,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."
@@ -2980,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]]
+22 -8
View File
@@ -46,6 +46,18 @@ type Rule struct {
// 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.
@@ -57,15 +69,17 @@ func (r *Rule) Validate() error {
// 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 errors.New("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.
+2 -1
View File
@@ -3,8 +3,9 @@ package codec
import (
"fmt"
"math"
"regexp"
"strings"
"github.com/zricethezav/gitleaks/v8/regexp"
)
var (
+2 -1
View File
@@ -2,10 +2,11 @@ package codec
import (
"bytes"
"regexp"
"strconv"
"strings"
"unicode/utf8"
"github.com/zricethezav/gitleaks/v8/regexp"
)
var (
+208 -38
View File
@@ -113,6 +113,12 @@ 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{}),
@@ -121,7 +127,7 @@ func NewDetector(cfg config.Config) *Detector {
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),
}
}
@@ -240,7 +246,7 @@ func (d *Detector) DetectSource(ctx context.Context, source sources.Source) ([]r
})
}
for _, finding := range d.Detect(Fragment(fragment)) {
for _, finding := range d.DetectContext(ctx, Fragment(fragment)) {
d.AddFinding(finding)
}
@@ -262,6 +268,12 @@ func (d *Detector) DetectSource(ctx context.Context, source sources.Source) ([]r
// 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)))
}
@@ -292,55 +304,63 @@ func (d *Detector) Detect(fragment Fragment) []report.Finding {
return findings
}
// add newline indices for location calculation in detectRule
newlineIndices := newLineRegexp.FindAllStringIndex(fragment.Raw, -1)
// setup variables to handle different decoding passes
currentRaw := fragment.Raw
encodedSegments := []*codec.EncodedSegment{}
currentDecodeDepth := 0
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, newlineIndices, 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, newlineIndices, 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
}
}
}
@@ -348,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, newlineIndices [][]int, currentRaw string, r config.Rule, encodedSegments []*codec.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 {
@@ -360,6 +380,10 @@ func (d *Detector) detectRule(fragment Fragment, newlineIndices [][]int, current
}()
)
if r.SkipReport && !fragment.InheritedFromFinding {
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")
@@ -415,6 +439,14 @@ func (d *Detector) detectRule(fragment Fragment, newlineIndices [][]int, current
}
}
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
for _, matchIndex := range r.Regex.FindAllStringIndex(currentRaw, -1) {
@@ -534,7 +566,145 @@ func (d *Detector) detectRule(fragment Fragment, newlineIndices [][]int, current
}
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)
}
// 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 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
+156 -31
View File
@@ -1,8 +1,10 @@
package detect
import (
"bytes"
"context"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
@@ -10,6 +12,7 @@ import (
"testing"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/rs/zerolog"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
@@ -86,6 +89,46 @@ secret=%25%35%61%25%34%37%25%35%36jb2RlZC1zZWNyZXQtdmFsdWU%25%32%35%25%33%33%25%
secret%3D%25%35%61%25%34%37%25%35%36jb2RlZC1zZWNyZXQtdmFsdWU%25%32%35%25%33%33%25%36%34
`
var multili = `
username = "admin"
password = "secret123"
`
func compare(t *testing.T, a, b []report.Finding) {
if diff := cmp.Diff(a, b,
cmpopts.SortSlices(func(a, b report.Finding) bool {
if a.File != b.File {
return a.File < b.File
}
if a.StartLine != b.StartLine {
return a.StartLine < b.StartLine
}
if a.StartColumn != b.StartColumn {
return a.StartColumn < b.StartColumn
}
if a.EndLine != b.EndLine {
return a.EndLine < b.EndLine
}
if a.EndColumn != b.EndColumn {
return a.EndColumn < b.EndColumn
}
if a.RuleID != b.RuleID {
return a.RuleID < b.RuleID
}
return a.Secret < b.Secret
}),
cmpopts.IgnoreFields(report.Finding{},
"Fingerprint", "Author", "Email", "Date", "Message", "Commit", "requiredFindings"),
cmpopts.EquateApprox(0.0001, 0), // For floating point Entropy comparison
); diff != "" {
t.Errorf("findings mismatch (-want +got):\n%s", diff)
}
}
func TestDetect(t *testing.T) {
logging.Logger = logging.Logger.Level(zerolog.TraceLevel)
tests := map[string]struct {
@@ -97,8 +140,9 @@ func TestDetect(t *testing.T) {
// I.e., if the finding is from a --no-git file, the line number will be
// increase by 1 in DetectFromFiles(). If the finding is from git,
// the line number will be increased by the patch delta.
expectedFindings []report.Finding
wantError error
expectedFindings []report.Finding
wantError error
expectedAuxOutput string
}{
// General
"valid allow comment (1)": {
@@ -424,6 +468,28 @@ const token = "mockSecret";
FilePath: "tmp.go",
},
},
"fragment level composite": {
cfgName: "composite",
fragment: Fragment{
Raw: multili,
},
expectedFindings: []report.Finding{
{
Description: "Primary rule",
RuleID: "primary-rule",
StartLine: 5,
EndLine: 5,
StartColumn: 5,
EndColumn: 26,
Line: "\n\t\t\tpassword = \"secret123\"",
Match: `password = "secret123"`,
Secret: "secret123",
Entropy: 2.9477028846740723,
Tags: []string{},
},
},
expectedAuxOutput: "Required: username-rule:1:admin\n",
},
// Decoding
"detect encoded": {
cfgName: "encoded",
@@ -736,11 +802,50 @@ const token = "mockSecret";
d.baselinePath = tt.baselinePath
findings := d.Detect(tt.fragment)
assert.ElementsMatch(t, tt.expectedFindings, findings)
compare(t, findings, tt.expectedFindings)
// extremely goofy way to test auxiliary findings
// capture stdout and print that sonabitch
// TODO
if tt.expectedAuxOutput != "" {
capturedOutput := captureStdout(func() {
for _, finding := range findings {
finding.PrintRequiredFindings()
}
})
// Clean up the output for comparison (remove ANSI color codes)
cleanOutput := stripANSI(capturedOutput)
expectedClean := stripANSI(tt.expectedAuxOutput)
assert.Equal(t, expectedClean, cleanOutput, "Auxiliary output should match")
}
})
}
}
func stripANSI(s string) string {
ansiRegex := regexp.MustCompile(`\x1b\[[0-9;]*m`)
return ansiRegex.ReplaceAllString(s, "")
}
func captureStdout(f func()) string {
oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
f()
w.Close()
os.Stdout = oldStdout
var buf bytes.Buffer
io.Copy(&buf, r)
return buf.String()
}
// TestFromGit tests the FromGit function
func TestFromGit(t *testing.T) {
// TODO: Fix this test on windows.
@@ -1425,6 +1530,7 @@ func TestDetectWithArchives(t *testing.T) {
tests := []struct {
cfgName string
source string
expireContext bool
expectedFindings []report.Finding
}{
{
@@ -1954,6 +2060,12 @@ func TestDetectWithArchives(t *testing.T) {
},
},
},
{
source: filepath.Join(archivesBasePath, "nested.tar.gz"),
cfgName: "archives",
expireContext: true,
expectedFindings: []report.Finding{},
},
}
for _, tt := range tests {
@@ -1968,13 +2080,17 @@ func TestDetectWithArchives(t *testing.T) {
err = viper.Unmarshal(&vc)
require.NoError(t, err)
ctx, cancel := context.WithCancel(context.Background())
if tt.expireContext {
cancel()
}
cfg, _ := vc.Translate()
detector := NewDetector(cfg)
detector := NewDetectorContext(ctx, cfg)
detector.MaxArchiveDepth = 8
findings, err := detector.DetectSource(
context.Background(),
&sources.Files{
ctx, &sources.Files{
Path: tt.source,
Sema: detector.Sema,
Config: &cfg,
@@ -1982,7 +2098,13 @@ func TestDetectWithArchives(t *testing.T) {
},
)
require.NoError(t, err)
if tt.expireContext {
require.EqualError(t, err, "context canceled")
} else {
cancel()
require.NoError(t, err)
}
// TODO: Temporary mitigation.
// https://github.com/gitleaks/gitleaks/issues/1641
normalizedFindings := make([]report.Finding, len(findings))
@@ -2107,8 +2229,10 @@ func TestDetectRuleAllowlist(t *testing.T) {
},
expected: []report.Finding{
{
StartColumn: 50,
EndColumn: 60,
StartLine: 1,
EndLine: 1,
StartColumn: 18,
EndColumn: 28,
Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
Match: "Summer2024!",
Secret: "Summer2024!",
@@ -2132,8 +2256,10 @@ func TestDetectRuleAllowlist(t *testing.T) {
},
expected: []report.Finding{
{
StartColumn: 50,
EndColumn: 60,
StartLine: 1,
EndLine: 1,
StartColumn: 18,
EndColumn: 28,
Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
Match: "Summer2024!",
Secret: "Summer2024!",
@@ -2203,8 +2329,10 @@ func TestDetectRuleAllowlist(t *testing.T) {
},
expected: []report.Finding{
{
StartColumn: 50,
EndColumn: 60,
StartLine: 1,
EndLine: 1,
StartColumn: 18,
EndColumn: 28,
Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
Match: "Summer2024!",
Secret: "Summer2024!",
@@ -2225,8 +2353,10 @@ func TestDetectRuleAllowlist(t *testing.T) {
},
expected: []report.Finding{
{
StartColumn: 50,
EndColumn: 60,
StartLine: 1,
EndLine: 1,
StartColumn: 18,
EndColumn: 28,
Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
Match: "Summer2024!",
Secret: "Summer2024!",
@@ -2249,8 +2379,10 @@ func TestDetectRuleAllowlist(t *testing.T) {
},
expected: []report.Finding{
{
StartColumn: 50,
EndColumn: 60,
StartLine: 1,
EndLine: 1,
StartColumn: 18,
EndColumn: 28,
Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
Match: "Summer2024!",
Secret: "Summer2024!",
@@ -2290,10 +2422,9 @@ let password = 'Summer2024!';`
f := tc.fragment
f.Raw = raw
actual := d.detectRule(f, [][]int{}, raw, rule, []*codec.EncodedSegment{})
if diff := cmp.Diff(tc.expected, actual); diff != "" {
t.Errorf("diff: (-want +got)\n%s", diff)
}
actual := d.detectRule(f, raw, rule, []*codec.EncodedSegment{})
compare(t, tc.expected, actual)
})
}
}
@@ -2451,10 +2582,8 @@ func TestWindowsFileSeparator_RulePath(t *testing.T) {
require.NoError(t, err)
for name, test := range tests {
t.Run(name, func(t *testing.T) {
actual := d.detectRule(test.fragment, [][]int{}, test.fragment.Raw, test.rule, []*codec.EncodedSegment{})
if diff := cmp.Diff(test.expected, actual); diff != "" {
t.Errorf("diff: (-want +got)\n%s", diff)
}
actual := d.detectRule(test.fragment, test.fragment.Raw, test.rule, []*codec.EncodedSegment{})
compare(t, test.expected, actual)
})
}
}
@@ -2637,12 +2766,8 @@ func TestWindowsFileSeparator_RuleAllowlistPaths(t *testing.T) {
require.NoError(t, err)
for name, test := range tests {
t.Run(name, func(t *testing.T) {
actual := d.detectRule(test.fragment, [][]int{}, test.fragment.Raw, test.rule, []*codec.EncodedSegment{})
if diff := cmp.Diff(test.expected, actual); diff != "" {
t.Errorf("diff: (-want +got)\n%s", diff)
}
actual := d.detectRule(test.fragment, test.fragment.Raw, test.rule, []*codec.EncodedSegment{})
compare(t, test.expected, actual)
})
}
}
//endregion
+5
View File
@@ -232,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
}
@@ -243,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
}
@@ -254,5 +257,7 @@ func printFinding(f report.Finding, noColor bool) {
if f.Link != "" {
fmt.Printf("%-12s %s\n", "Link:", f.Link)
}
f.PrintRequiredFindings()
fmt.Println("")
}
+18 -21
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,9 +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/mholt/archives v0.1.2
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
@@ -24,45 +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.1 // indirect
github.com/andybalholm/brotli v1.1.2-0.20250424173009-453214e765f3 // 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.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/errwrap v1.1.0 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/huandu/xstrings v1.5.0 // indirect
github.com/klauspost/compress v1.17.11 // 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/minio/minlz v1.0.0 // 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.1.0 // 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.21 // 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.5 // 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/therootcompany/xz v1.0.1 // indirect
github.com/ulikunitz/xz v0.5.12 // 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
go4.org v0.0.0-20230225012048-214862532bf5 // indirect
golang.org/x/crypto v0.32.0 // indirect
golang.org/x/crypto v0.35.0 // indirect
)
require (
@@ -74,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
)
+36 -37
View File
@@ -27,16 +27,16 @@ github.com/Masterminds/semver/v3 v3.3.0 h1:B8LGeaivUe71a5qox1ICM/JLl0NqZSW5CHyL+
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.1 h1:pWBd4tuSGm3wtpoqRZZ2EAwOmcHK6XFf7bU9qcJXyFg=
github.com/STARRY-S/zip v0.2.1/go.mod h1:xNvshLODWtC4EJ702g7cTYn13G53o1+X9BWnPFpcWV4=
github.com/andybalholm/brotli v1.1.2-0.20250424173009-453214e765f3 h1:8PmGpDEZl9yDpcdEr6Odf23feCxK3LNUNMxjXg41pZQ=
github.com/andybalholm/brotli v1.1.2-0.20250424173009-453214e765f3/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
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.0 h1:a4R0Wu6/P1o1pP/3VV++aEOcyeBxeO/xE2Y9NSTrr6A=
github.com/bodgit/sevenzip v1.6.0/go.mod h1:zOBh9nJUof7tcrlqJFv1koWRrhz3LbDbUNngkuZxLMc=
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=
@@ -87,8 +87,8 @@ github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw
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.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
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=
@@ -100,11 +100,8 @@ github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+
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/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
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=
@@ -120,8 +117,8 @@ github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1
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.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
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=
@@ -150,10 +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.2 h1:UBSe5NfYKHI1sy+S5dJsEsG9jsKKk8NJA4HCC+xTI4A=
github.com/mholt/archives v0.1.2/go.mod h1:D7QzTHgw3ctfS6wgOO9dN+MFgdZpbksGCxprUOwZWDs=
github.com/minio/minlz v1.0.0 h1:Kj7aJZ1//LlTP1DM8Jm7lNKvvJS2m74gyyXXn3+uJWQ=
github.com/minio/minlz v1.0.0/go.mod h1:qT0aEB35q79LLornSzeDH75LBf3aH1MV+jB5w9Wasec=
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=
@@ -165,12 +164,12 @@ 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.1.0 h1:JQl9ZoBPDy+nIZGb1mx8+anfHp/LV3NE2MjMiv0ct/U=
github.com/nwaples/rardecode/v2 v2.1.0/go.mod h1:7uz379lSxPe6j9nvzxUZ+n7mnJNgjsRNb6IbvGVHRmw=
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.21 h1:yOVMLb6qSIDP67pl/5F7RepeKYu/VmTyEXvuMI5d9mQ=
github.com/pierrec/lz4/v4 v4.1.21/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
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=
@@ -193,12 +192,12 @@ github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6g
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.5 h1:ms5Xri9o1JBIWvOFAorYtUNik6HI3HgBTkISiqu0Cwg=
github.com/sorairolake/lzip-go v0.3.5/go.mod h1:N0KYq5iWrMXI0ZEXKXaS9hCyOjZUQdBDEIbXfoUwbdk=
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=
@@ -210,6 +209,8 @@ github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+
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=
@@ -220,11 +221,9 @@ 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/therootcompany/xz v1.0.1 h1:CmOtsn1CbtmyYiusbfmhmkpAAETj0wBIH6kCYaX+xzw=
github.com/therootcompany/xz v1.0.1/go.mod h1:3K3UH1yCKgBneZYhuQUvJ9HPD19UEXEI0BWbMn8qNMY=
github.com/ulikunitz/xz v0.5.8/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
github.com/ulikunitz/xz v0.5.12 h1:37Nm15o69RwBkXM0J6A5OlE67RZTfzUxTj8fB3dfcsc=
github.com/ulikunitz/xz v0.5.12/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=
@@ -245,8 +244,8 @@ golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8U
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.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc=
golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc=
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=
@@ -303,8 +302,8 @@ golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJ
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.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w=
golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
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=
@@ -338,8 +337,8 @@ 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.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
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=
+60 -4
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.
@@ -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))
}
}
}
+7 -1
View File
@@ -29,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 -67
View File
@@ -12,6 +12,7 @@ import (
"github.com/h2non/filetype"
"github.com/mholt/archives"
"github.com/rs/zerolog"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/logging"
@@ -56,26 +57,33 @@ func (s *File) Fragments(ctx context.Context, yield FragmentsFunc) error {
// decide what to do with it.
if err == nil && format != nil {
if s.archiveDepth+1 > s.MaxArchiveDepth {
// Only warn when the feature is enabled
var event *zerolog.Event
// Warn if the feature is enabled; else emit a trace log.
if s.MaxArchiveDepth != 0 {
logging.Warn().Str(
"path", s.FullPath(),
).Int(
"max_archive_depth", s.MaxArchiveDepth,
).Msg("skipping archive: exceeds max archive depth")
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(decompressor, s.Content, yield)
return s.decompressorFragments(ctx, decompressor, s.Content, yield)
}
logging.Warn().Str("path", s.FullPath()).Msg("skipping unknown archive type")
}
return s.fileFragments(bufio.NewReader(s.Content), yield)
return s.fileFragments(ctx, bufio.NewReader(s.Content), yield)
}
// extractorFragments recursively crawls archives and yields fragments
@@ -139,14 +147,14 @@ func (s *File) extractorFragments(ctx context.Context, extractor archives.Extrac
}
// decompressorFragments recursively crawls archives and yields fragments
func (s *File) decompressorFragments(decompressor archives.Decompressor, reader io.Reader, yield FragmentsFunc) error {
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(bufio.NewReader(innerReader), yield); err != nil {
if err := s.fileFragments(ctx, bufio.NewReader(innerReader), yield); err != nil {
_ = innerReader.Close()
return err
}
@@ -156,7 +164,7 @@ func (s *File) decompressorFragments(decompressor archives.Decompressor, reader
}
// fileFragments reads the file into fragments to yield
func (s *File) fileFragments(reader *bufio.Reader, yield FragmentsFunc) error {
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)
@@ -164,75 +172,80 @@ func (s *File) fileFragments(reader *bufio.Reader, yield FragmentsFunc) error {
totalLines := 0
for {
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))
select {
case <-ctx.Done():
return ctx.Err()
default:
fragment := Fragment{
FilePath: s.FullPath(),
}
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")
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
}
}
// 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),
)
}
// 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")
fragment.Raw = peekBuf.String()
fragment.Bytes = peekBuf.Bytes()
fragment.StartLine = totalLines + 1
return nil
}
}
// Count the number of newlines in this chunk
totalLines += strings.Count(fragment.Raw, "\n")
// 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),
)
}
if len(s.Symlink) > 0 {
fragment.SymlinkFile = s.Symlink
}
fragment.Raw = peekBuf.String()
fragment.Bytes = peekBuf.Bytes()
fragment.StartLine = totalLines + 1
if isWindows {
fragment.FilePath = filepath.ToSlash(fragment.FilePath)
fragment.SymlinkFile = filepath.ToSlash(s.Symlink)
fragment.WindowsFilePath = s.FullPath()
}
// Count the number of newlines in this chunk
totalLines += strings.Count(fragment.Raw, "\n")
// log errors but continue since there's content
if err != nil && err != io.EOF {
logging.Warn().Err(err).Msgf("issue reading file")
}
if len(s.Symlink) > 0 {
fragment.SymlinkFile = s.Symlink
}
// Done with the file!
if err == io.EOF {
return yield(fragment, nil)
}
if isWindows {
fragment.FilePath = filepath.ToSlash(fragment.FilePath)
fragment.SymlinkFile = filepath.ToSlash(s.Symlink)
fragment.WindowsFilePath = s.FullPath()
}
if err := yield(fragment, err); err != nil {
return err
// 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
}
}
}
}
+43 -32
View File
@@ -34,7 +34,8 @@ func DirectoryTargets(sourcePath string, s *semgroup.Group, followSymlinks bool,
}
s.Go(func() error {
err := files.scanTargets(func(scanTarget ScanTarget, err error) error {
ctx := context.Background()
err := files.scanTargets(ctx, func(scanTarget ScanTarget, err error) error {
paths <- scanTarget
return nil
})
@@ -56,7 +57,7 @@ type Files struct {
}
// scanTargets yields scan targets to a callback func
func (s *Files) scanTargets(yield func(ScanTarget, error) error) error {
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()
@@ -141,40 +142,50 @@ func (s *Files) scanTargets(yield func(ScanTarget, error) error) error {
func (s *Files) Fragments(ctx context.Context, yield FragmentsFunc) error {
var wg sync.WaitGroup
err := s.scanTargets(func(scanTarget ScanTarget, err error) error {
wg.Add(1)
s.Sema.Go(func() error {
logger := logging.With().Str("path", scanTarget.Path).Logger()
logger.Trace().Msg("scanning path")
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")
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 nil
}
return err
})
// 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
return nil
}
})
wg.Wait()
return err
select {
case <-ctx.Done():
return ctx.Err()
default:
wg.Wait()
return err
}
}
+2
View File
@@ -23,4 +23,6 @@ type Fragment struct {
// CommitInfo captures additional information about the git commit if applicable
CommitInfo *CommitInfo
InheritedFromFinding bool // Indicates if this fragment is inherited from a finding
}
+51 -13
View File
@@ -63,6 +63,12 @@ func (br *blobReader) Close() 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 != "" {
@@ -82,9 +88,9 @@ 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",
cmd = exec.CommandContext(ctx, "git", "-C", sourceClean, "log", "-p", "-U0",
"--full-history", "--all", "--diff-filter=tuxdb")
}
@@ -122,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())
@@ -177,13 +189,24 @@ 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.Command("git", gitArgs...)
cmd := exec.CommandContext(ctx, "git", gitArgs...)
cmd.Stderr = io.Discard
stdout, err := cmd.StdoutPipe()
if err != nil {
@@ -275,7 +298,9 @@ type CommitInfo struct {
// Fragments yields fragments from a git repo
func (s *Git) Fragments(ctx context.Context, yield FragmentsFunc) error {
defer func() {
_ = s.Cmd.Wait()
if err := s.Cmd.Wait(); err != nil {
logging.Debug().Err(err).Str("cmd", s.Cmd.String()).Msg("command aborted")
}
}()
var (
@@ -287,6 +312,8 @@ func (s *Git) Fragments(ctx context.Context, yield FragmentsFunc) error {
// 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
@@ -336,7 +363,7 @@ func (s *Git) Fragments(ctx context.Context, yield FragmentsFunc) error {
defer wg.Done()
if yieldAsArchive {
blob, err := s.Cmd.NewBlobReader(commitSHA, gitdiffFile.NewName)
blob, err := s.Cmd.NewBlobReaderContext(ctx, commitSHA, gitdiffFile.NewName)
if err != nil {
logging.Error().Err(err).Msg("could not read archive blob")
return nil
@@ -394,17 +421,28 @@ func (s *Git) Fragments(ctx context.Context, yield FragmentsFunc) error {
}
}
wg.Wait()
return nil
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(source)
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.")
@@ -440,11 +478,11 @@ End:
}
}
var sshUrlpat = regexp.MustCompile(`^git@([a-zA-Z0-9.-]+):([\w/.-]+?)(?:\.git)?$`)
var sshUrlpat = regexp.MustCompile(`^git@([a-zA-Z0-9.-]+):(?:\d{1,5}/)?([\w/.-]+?)(?:\.git)?$`)
func getRemoteUrl(source string) (*url.URL, error) {
func getRemoteUrl(ctx context.Context, source string) (*url.URL, error) {
// This will return the first remote — typically, "origin".
cmd := exec.Command("git", "ls-remote", "--quiet", "--get-url")
cmd := exec.CommandContext(ctx, "git", "ls-remote", "--quiet", "--get-url")
if source != "." {
cmd.Dir = source
}
+14
View File
@@ -0,0 +1,14 @@
title = "Fragment level composite rule"
[[rules]]
id = "primary-rule"
description = "Primary rule"
regex = 'password\s*=\s*"([^"]+)"'
[[rules.required]]
id = "username-rule"
[[rules]]
id = "username-rule"
description = "Username rule"
regex = 'username\s*=\s*"([^"]+)"'
skipReport = true
+7
View File
@@ -0,0 +1,7 @@
[extend]
useDefault = true
[[rules]]
[[rules.allowlists]]
paths = ['^.*\.(xml|log|json)$']
@@ -5,5 +5,5 @@ path = "../testdata/config/simple.toml"
[[rules]]
id = "aws-access-key"
regex = '''(?:a)(?:a)'''
regex = '''(a)(a)'''
secretGroup = 2
+5
View File
@@ -0,0 +1,5 @@
package version
// these two gotta be the same
var DefaultMsg = "version is set by build process"
var Version = "version is set by build process"