mirror of
https://github.com/gitleaks/gitleaks.git
synced 2026-11-28 12:14:22 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5f6ec56cfa | ||
|
|
4695bdb828 | ||
|
|
b58d3f102c | ||
|
|
e18d0da14b | ||
|
|
c33331503a | ||
|
|
d68f282a94 | ||
|
|
4c232b5014 | ||
|
|
652f743b43 | ||
|
|
8ad8470035 | ||
|
|
ad138e213f | ||
|
|
81fc7f93b7 | ||
|
|
c63f9c6f61 | ||
|
|
dfcab34362 | ||
|
|
d8fafb2396 | ||
|
|
5454f7bdec | ||
|
|
7900fbae49 | ||
|
|
2719f0e001 | ||
|
|
9ea08626dc | ||
|
|
22e600ebe3 | ||
|
|
1207d58159 | ||
|
|
db3bc42b83 | ||
|
|
80093b8a7b | ||
|
|
9febafb621 | ||
|
|
b5cb8ad01b | ||
|
|
8863af47d6 | ||
|
|
67fcd836b3 | ||
|
|
8d1f98c796 | ||
|
|
ca20267a84 | ||
|
|
b66ac75e4f | ||
|
|
6eaad03960 | ||
|
|
09242ce9c8 | ||
|
|
c98e5e0d27 | ||
|
|
4ed0ca4902 | ||
|
|
fb5d707e08 | ||
|
|
50493dbe1f | ||
|
|
ed65b65095 | ||
|
|
c5ccbb9468 | ||
|
|
3821f30b06 | ||
|
|
d22371873b | ||
|
|
87d96295d6 | ||
|
|
228396b37b | ||
|
|
a82bc53d89 | ||
|
|
4fb43823ef | ||
|
|
b1c9c7ecbe | ||
|
|
72977e41b6 | ||
|
|
7b02c98eb4 | ||
|
|
2a7bcffd7c | ||
|
|
bd79c3eaca | ||
|
|
7fb4eda723 | ||
|
|
a044b815b3 | ||
|
|
bf380d4767 | ||
|
|
f487f85378 | ||
|
|
958f55ac62 | ||
|
|
c7acf33d96 | ||
|
|
9faaa4a09c | ||
|
|
79068b35e5 | ||
|
|
80468eff1d | ||
|
|
ef8223700a | ||
|
|
2463f11e71 | ||
|
|
6f251eef65 | ||
|
|
20f9a1d4eb | ||
|
|
722ce8213a | ||
|
|
79780b884d | ||
|
|
c5683ca6a3 | ||
|
|
0357c3cbf6 | ||
|
|
782f310478 | ||
|
|
489d13c14e | ||
|
|
d29ee55171 | ||
|
|
611db6579b | ||
|
|
0589ae0298 | ||
|
|
82f7e32b71 | ||
|
|
f97a9ee872 | ||
|
|
78eebaca9d | ||
|
|
6f967cad68 | ||
|
|
88f56d3695 | ||
|
|
9609928c02 | ||
|
|
23cb69fba4 | ||
|
|
d1c77598da | ||
|
|
4451b455f3 | ||
|
|
7fb21a4e61 | ||
|
|
f6193bc92c | ||
|
|
9bc725786d | ||
|
|
b6cc71aa3a | ||
|
|
cfdeb0d7e0 | ||
|
|
107a41827b | ||
|
|
7fac002325 | ||
|
|
4b541044e8 | ||
|
|
af7d5bcb83 | ||
|
|
3e8cd2d1ab | ||
|
|
ddcc75371f | ||
|
|
9708e65c25 | ||
|
|
198e41051e | ||
|
|
e273a970a4 | ||
|
|
a503b583ba | ||
|
|
d5c275d6b2 | ||
|
|
5361c7c917 | ||
|
|
6cc0e386ac | ||
|
|
b4df42364d | ||
|
|
4344b00934 | ||
|
|
f74ced7985 | ||
|
|
c08cb1dc9a | ||
|
|
991a940412 | ||
|
|
ade376ab77 | ||
|
|
1c81ae02fa | ||
|
|
e9b93c6033 | ||
|
|
de105fca6d | ||
|
|
a3be7222a6 | ||
|
|
b44958220e | ||
|
|
2f6b9f72d1 | ||
|
|
3fdc9c13d2 | ||
|
|
96b92c3d07 | ||
|
|
f6a7439306 | ||
|
|
59fdd904af | ||
|
|
c2afd56bbe | ||
|
|
818e32f7a4 | ||
|
|
3fa5a3a954 | ||
|
|
2020e6a9ab | ||
|
|
9122a2d359 | ||
|
|
398d0c46dd | ||
|
|
ae26eff464 | ||
|
|
c6424a6fc3 | ||
|
|
6411402d43 | ||
|
|
d71d95d65e | ||
|
|
3188ad6005 | ||
|
|
7fc11bb264 | ||
|
|
36c52c6b73 | ||
|
|
1f323d8b69 | ||
|
|
d88bc094f7 | ||
|
|
3fdaefdaa3 | ||
|
|
f3ae52e138 | ||
|
|
d6a828a530 | ||
|
|
d2ffffecbd | ||
|
|
a43dc0d3d0 | ||
|
|
69ed20e25e | ||
|
|
52b895a603 | ||
|
|
3f4d91fc22 | ||
|
|
049f5b2435 | ||
|
|
7a6183dab0 | ||
|
|
3c7f3f0e08 | ||
|
|
0e3f4f7abb | ||
|
|
3ed85671a4 | ||
|
|
e977850ab4 | ||
|
|
ad7a4fb4ea | ||
|
|
b2cf03c7e3 | ||
|
|
a3f623cc69 | ||
|
|
cc71bb1e9a |
No files matched your search
@@ -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
|
||||||
@@ -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:
|
||||||
|
- "*"
|
||||||
@@ -1,14 +1,17 @@
|
|||||||
name: gitleaks
|
name: gitleaks
|
||||||
on: [push, workflow_dispatch]
|
on:
|
||||||
|
push:
|
||||||
|
workflow_dispatch:
|
||||||
jobs:
|
jobs:
|
||||||
scan:
|
scan:
|
||||||
name: gitleaks
|
name: gitleaks
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
if: ${{ github.repository == 'gitleaks/gitleaks' }}
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
- uses: gitleaks/gitleaks-action@v2
|
- uses: gitleaks/gitleaks-action@e0c47f4f8be36e29cdc102c57e68cb5cbf0e8d1e # v3
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE}}
|
GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE}}
|
||||||
@@ -17,23 +17,23 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
|
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@8b122486cedac8393e77aa9734c3528886e4a1a8
|
uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0
|
||||||
|
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
id: buildx
|
id: buildx
|
||||||
uses: docker/setup-buildx-action@dc7b9719a96d48369863986a06765841d7ea23f6
|
uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
|
||||||
|
|
||||||
- name: Log in to Docker Hub
|
- name: Log in to Docker Hub
|
||||||
uses: docker/login-action@49ed152c8eca782a232dede0303416e8f356c37b
|
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
|
||||||
with:
|
with:
|
||||||
username: ${{ github.actor }}
|
username: ${{ github.actor }}
|
||||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
|
|
||||||
- name: Log in to the Container registry
|
- name: Log in to the Container registry
|
||||||
uses: docker/login-action@49ed152c8eca782a232dede0303416e8f356c37b
|
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
|
||||||
with:
|
with:
|
||||||
registry: ${{ env.REGISTRY }}
|
registry: ${{ env.REGISTRY }}
|
||||||
username: ${{ github.actor }}
|
username: ${{ github.actor }}
|
||||||
@@ -41,14 +41,14 @@ jobs:
|
|||||||
|
|
||||||
- name: Extract metadata (tags, labels) for Docker
|
- name: Extract metadata (tags, labels) for Docker
|
||||||
id: meta
|
id: meta
|
||||||
uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38
|
uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0
|
||||||
with:
|
with:
|
||||||
images: |
|
images: |
|
||||||
zricethezav/gitleaks
|
zricethezav/gitleaks
|
||||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||||
|
|
||||||
- name: Build and push Docker image
|
- name: Build and push Docker image
|
||||||
uses: docker/build-push-action@e551b19e49efd4e98792db7592c17c09b89db8d8
|
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
|
||||||
with:
|
with:
|
||||||
platforms: linux/amd64,linux/arm64
|
platforms: linux/amd64,linux/arm64
|
||||||
context: .
|
context: .
|
||||||
|
|||||||
@@ -10,20 +10,28 @@ on:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
runs-on: ubuntu-latest
|
strategy:
|
||||||
|
matrix:
|
||||||
|
platform: [ ubuntu-latest, windows-latest ]
|
||||||
|
runs-on: ${{ matrix.platform }}
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
|
|
||||||
- name: Set up Go
|
- name: Set up Go
|
||||||
uses: actions/setup-go@v2
|
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||||
with:
|
with:
|
||||||
go-version: 1.22
|
go-version: 1.25
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
run: go build -v ./...
|
run: go build ./...
|
||||||
|
|
||||||
|
- name: Set up gotestsum
|
||||||
|
run: |
|
||||||
|
go install gotest.tools/gotestsum@latest
|
||||||
|
|
||||||
- name: Test
|
- name: Test
|
||||||
run: make test
|
run: |
|
||||||
|
gotestsum --raw-command -- go test -json ./... --race
|
||||||
|
|
||||||
- name: Validate Config
|
- name: Validate Config
|
||||||
run: go generate ./... && git diff --exit-code
|
run: go generate ./... && git diff --exit-code
|
||||||
@@ -9,6 +9,7 @@
|
|||||||
*.got
|
*.got
|
||||||
gitleaks
|
gitleaks
|
||||||
build
|
build
|
||||||
|
profile
|
||||||
|
|
||||||
# configs
|
# configs
|
||||||
.gitleaks.toml
|
.gitleaks.toml
|
||||||
|
|||||||
+3
-1
@@ -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
|
# 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`
|
# This gitleaks config extends the default config and ignores secrets located in the `cmd/generate/config/rules`
|
||||||
|
|
||||||
@@ -9,4 +9,6 @@ useDefault = true
|
|||||||
[allowlist]
|
[allowlist]
|
||||||
paths = [
|
paths = [
|
||||||
'''(^|/)cmd/generate/config/rules''',
|
'''(^|/)cmd/generate/config/rules''',
|
||||||
|
'''.*test\.go''',
|
||||||
|
'''testdata'''
|
||||||
]
|
]
|
||||||
@@ -938,3 +938,7 @@ e56870aecf8ac2733affc82e1ac25e3be9092db3:cmd/generate/config/rules/curl.go:gener
|
|||||||
239e6323639b18ba8a1081f17788a658da075dd7:cmd/generate/config/rules/prefect.go:prefect-api-token:26
|
239e6323639b18ba8a1081f17788a658da075dd7:cmd/generate/config/rules/prefect.go:prefect-api-token:26
|
||||||
239e6323639b18ba8a1081f17788a658da075dd7:cmd/generate/config/rules/databricks.go:databricks-api-token:25
|
239e6323639b18ba8a1081f17788a658da075dd7:cmd/generate/config/rules/databricks.go:databricks-api-token:25
|
||||||
239e6323639b18ba8a1081f17788a658da075dd7:cmd/generate/config/rules/databricks.go:generic-api-key:22
|
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
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
version: '2'
|
||||||
|
linters:
|
||||||
|
default: none
|
||||||
|
# It might be worth going through some of the disabled linters and enabling
|
||||||
|
# them and fixing the items they call out e.g.: cyclop, prealloc,
|
||||||
|
# paralleltest, prealloc, errcheck, dupl, unused, testifylint, gosec,
|
||||||
|
# gocritic, perfsprint, exptostd, intrange, perfsprint (maybe others?)
|
||||||
|
disable:
|
||||||
|
- cyclop
|
||||||
|
- depguard
|
||||||
|
- dupl
|
||||||
|
- err113
|
||||||
|
- errcheck
|
||||||
|
- exhaustive
|
||||||
|
- exhaustruct
|
||||||
|
- exptostd
|
||||||
|
- forbidigo
|
||||||
|
- funcorder
|
||||||
|
- funlen
|
||||||
|
- gochecknoglobals
|
||||||
|
- gochecknoinits
|
||||||
|
- gocognit
|
||||||
|
- goconst
|
||||||
|
- gocritic
|
||||||
|
- gocyclo
|
||||||
|
- godot
|
||||||
|
- godox
|
||||||
|
- gosec
|
||||||
|
- gosmopolitan
|
||||||
|
- intrange
|
||||||
|
- lll
|
||||||
|
- maintidx
|
||||||
|
- mnd
|
||||||
|
- musttag
|
||||||
|
- nestif
|
||||||
|
- nilerr
|
||||||
|
- nlreturn
|
||||||
|
- nonamedreturns
|
||||||
|
- paralleltest
|
||||||
|
- perfsprint
|
||||||
|
- prealloc
|
||||||
|
- predeclared
|
||||||
|
- tagliatelle
|
||||||
|
- testifylint
|
||||||
|
- testpackage
|
||||||
|
- tparallel
|
||||||
|
- unparam
|
||||||
|
- unused
|
||||||
|
- varnamelen
|
||||||
|
- wastedassign
|
||||||
|
- whitespace
|
||||||
|
- wrapcheck
|
||||||
|
- wsl
|
||||||
|
- zerologlint # doesn't seem to catch gitleaks/v8/logging mistakes
|
||||||
|
enable:
|
||||||
|
- inamedparam
|
||||||
|
- misspell
|
||||||
|
- revive
|
||||||
|
- misspell
|
||||||
|
- inamedparam
|
||||||
|
- exhaustruct
|
||||||
|
- inamedparam
|
||||||
|
- misspell
|
||||||
|
- nonamedreturns
|
||||||
|
- staticcheck
|
||||||
|
- unconvert
|
||||||
|
exclusions:
|
||||||
|
rules:
|
||||||
|
- linters:
|
||||||
|
- staticcheck
|
||||||
|
source: 'detector\.Detect\w+\(|sources\.DirectoryTargets\(|detect\.(?:Fragment|RemoteInfo)'
|
||||||
|
- linters:
|
||||||
|
- misspell
|
||||||
|
source: '"(?:addres|busines|clas)",'
|
||||||
|
settings:
|
||||||
|
staticcheck:
|
||||||
|
checks:
|
||||||
|
- all
|
||||||
|
- '-QF1001'
|
||||||
|
- '-ST1000'
|
||||||
|
- '-ST1003'
|
||||||
|
- '-ST1018'
|
||||||
|
- '-ST1020'
|
||||||
|
- '-ST1021'
|
||||||
|
revive:
|
||||||
|
severity: error
|
||||||
+3
-1
@@ -15,8 +15,10 @@ builds:
|
|||||||
goarm:
|
goarm:
|
||||||
- "6"
|
- "6"
|
||||||
- "7"
|
- "7"
|
||||||
|
tags:
|
||||||
|
- gore2regex
|
||||||
ldflags:
|
ldflags:
|
||||||
- -s -w -X=github.com/zricethezav/gitleaks/v8/cmd.Version={{.Version}}
|
- -s -w -X=github.com/zricethezav/gitleaks/v8/version.Version={{.Version}}
|
||||||
archives:
|
archives:
|
||||||
- builds: [gitleaks]
|
- builds: [gitleaks]
|
||||||
format_overrides:
|
format_overrides:
|
||||||
|
|||||||
@@ -9,8 +9,9 @@
|
|||||||
description: Detect hardcoded secrets using Gitleaks
|
description: Detect hardcoded secrets using Gitleaks
|
||||||
entry: zricethezav/gitleaks git --pre-commit --redact --staged --verbose
|
entry: zricethezav/gitleaks git --pre-commit --redact --staged --verbose
|
||||||
language: docker_image
|
language: docker_image
|
||||||
|
pass_filenames: false
|
||||||
- id: gitleaks-system
|
- id: gitleaks-system
|
||||||
name: Detect hardcoded secrets
|
name: Detect hardcoded secrets
|
||||||
description: Detect hardcoded secrets using Gitleaks
|
description: Detect hardcoded secrets using Gitleaks
|
||||||
entry: gitleaks git --pre-commit --redact --staged --verbose
|
entry: gitleaks git --pre-commit --redact --staged --verbose
|
||||||
language: system
|
language: system
|
||||||
+2
-2
@@ -35,7 +35,7 @@ If you want to add a new rule to the [default Gitleaks configuration](https://gi
|
|||||||
RuleID: "beamer-api-token",
|
RuleID: "beamer-api-token",
|
||||||
|
|
||||||
// Regex capture group for the actual secret
|
// Regex capture group for the actual secret
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// Regex used for detecting secrets. See regex section below for more details
|
// Regex used for detecting secrets. See regex section below for more details
|
||||||
@@ -95,7 +95,7 @@ If you want to add a new rule to the [default Gitleaks configuration](https://gi
|
|||||||
the `rules.Beamer(),` in `main()`. Try and keep
|
the `rules.Beamer(),` in `main()`. Try and keep
|
||||||
this alphabetically pretty please.
|
this alphabetically pretty please.
|
||||||
|
|
||||||
1. Run `go generate ./...`
|
1. Run `make config/gitleaks.toml`
|
||||||
|
|
||||||
1. Check out your new rules in `config/gitleaks.toml` and see if everything looks good.
|
1. Check out your new rules in `config/gitleaks.toml` and see if everything looks good.
|
||||||
|
|
||||||
|
|||||||
+3
-3
@@ -1,10 +1,10 @@
|
|||||||
FROM golang:1.23 AS build
|
FROM golang:1.24 AS build
|
||||||
WORKDIR /go/src/github.com/zricethezav/gitleaks
|
WORKDIR /go/src/github.com/zricethezav/gitleaks
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN VERSION=$(git describe --tags --abbrev=0) && \
|
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
|
RUN apk add --no-cache bash git openssh-client
|
||||||
COPY --from=build /go/src/github.com/zricethezav/gitleaks/bin/* /usr/bin/
|
COPY --from=build /go/src/github.com/zricethezav/gitleaks/bin/* /usr/bin/
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
.PHONY: test test-cover
|
.PHONY: test test-cover failfast profile clean format build
|
||||||
|
|
||||||
PKG=github.com/zricethezav/gitleaks
|
PKG=github.com/zricethezav/gitleaks
|
||||||
VERSION := `git fetch --tags && git tag | sort -V | tail -1`
|
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
|
COVER=--cover --coverprofile=cover.out
|
||||||
|
|
||||||
test-cover:
|
test-cover:
|
||||||
@@ -12,13 +12,26 @@ test-cover:
|
|||||||
format:
|
format:
|
||||||
go fmt ./...
|
go fmt ./...
|
||||||
|
|
||||||
test: format
|
test: config/gitleaks.toml format
|
||||||
go test -v ./... --race $(PKG)
|
go test -v ./... --race $(PKG)
|
||||||
|
|
||||||
build: format
|
failfast: format
|
||||||
|
go test -failfast ./...
|
||||||
|
|
||||||
|
build: config/gitleaks.toml format
|
||||||
go mod tidy
|
go mod tidy
|
||||||
go build $(LDFLAGS)
|
go build $(LDFLAGS)
|
||||||
|
|
||||||
|
lint:
|
||||||
|
golangci-lint run
|
||||||
|
|
||||||
clean:
|
clean:
|
||||||
|
rm -rf profile
|
||||||
find . -type f -name '*.got.*' -delete
|
find . -type f -name '*.got.*' -delete
|
||||||
find . -type f -name '*.out' -delete
|
find . -type f -name '*.out' -delete
|
||||||
|
|
||||||
|
profile: build
|
||||||
|
./scripts/profile.sh './gitleaks' '.'
|
||||||
|
|
||||||
|
config/gitleaks.toml: $(wildcard cmd/generate/config/**/*)
|
||||||
|
go generate ./...
|
||||||
@@ -8,23 +8,31 @@
|
|||||||
└─░───┘
|
└─░───┘
|
||||||
```
|
```
|
||||||
|
|
||||||
<p align="left">
|
> [!WARNING]
|
||||||
<p align="left">
|
> 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)
|
||||||
<a href="https://github.com/gitleaks/gitleaks/actions/workflows/test.yml">
|
|
||||||
<img alt="Github Test" src="https://github.com/gitleaks/gitleaks/actions/workflows/test.yml/badge.svg">
|
|
||||||
</a>
|
|
||||||
<a href="https://hub.docker.com/r/zricethezav/gitleaks">
|
|
||||||
<img src="https://img.shields.io/docker/pulls/zricethezav/gitleaks.svg" />
|
|
||||||
</a>
|
|
||||||
<a href="https://github.com/gitleaks/gitleaks-action">
|
|
||||||
<img alt="gitleaks badge" src="https://img.shields.io/badge/protected%20by-gitleaks-blue">
|
|
||||||
</a>
|
|
||||||
</p>
|
|
||||||
</p>
|
|
||||||
|
|
||||||
### Join our Discord! [](https://discord.gg/8Hzbrnkr7E)
|
[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
|
||||||
|
[go-docs]: https://pkg.go.dev/github.com/zricethezav/gitleaks/v8
|
||||||
|
[badge-build]: https://github.com/gitleaks/gitleaks/actions/workflows/test.yml/badge.svg
|
||||||
|
[build]: https://github.com/gitleaks/gitleaks/actions/workflows/test.yml
|
||||||
|
[go-report-card-badge]: https://goreportcard.com/badge/github.com/gitleaks/gitleaks/v8
|
||||||
|
[go-report-card]: https://goreportcard.com/report/github.com/gitleaks/gitleaks/v8
|
||||||
|
[dockerhub]: https://hub.docker.com/r/zricethezav/gitleaks
|
||||||
|
[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 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`.
|
|
||||||
|
[![GitHub Action Test][badge-build]][build]
|
||||||
|
[![Docker Hub][dockerhub-badge]][dockerhub]
|
||||||
|
[![Gitleaks Action][gitleaks-badge]][gitleaks-action]
|
||||||
|
[![GoDoc][go-docs-badge]][go-docs]
|
||||||
|
[![GoReportCard][go-report-card-badge]][go-report-card]
|
||||||
|
[![License][badge-license]][license]
|
||||||
|
|
||||||
|
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
|
➜ ~/code(master) gitleaks git -v
|
||||||
@@ -49,6 +57,7 @@ Date: 2022-08-03T12:31:40Z
|
|||||||
Fingerprint: cd5226711335c68be1e720b318b7bc3135a30eb2:cmd/generate/config/rules/sidekiq.go:sidekiq-secret:23
|
Fingerprint: cd5226711335c68be1e720b318b7bc3135a30eb2:cmd/generate/config/rules/sidekiq.go:sidekiq-secret:23
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
## Getting Started
|
## 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).
|
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).
|
||||||
@@ -73,27 +82,6 @@ cd gitleaks
|
|||||||
make build
|
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
|
### Pre-Commit
|
||||||
|
|
||||||
1. Install pre-commit from https://pre-commit.com/#install
|
1. Install pre-commit from https://pre-commit.com/#install
|
||||||
@@ -102,12 +90,12 @@ jobs:
|
|||||||
```
|
```
|
||||||
repos:
|
repos:
|
||||||
- repo: https://github.com/gitleaks/gitleaks
|
- repo: https://github.com/gitleaks/gitleaks
|
||||||
rev: v8.19.0
|
rev: v8.24.2
|
||||||
hooks:
|
hooks:
|
||||||
- id: gitleaks
|
- id: gitleaks
|
||||||
```
|
```
|
||||||
|
|
||||||
for a [native execution of GitLeaks](https://github.com/gitleaks/gitleaks/releases) or use the [`gitleaks-docker` pre-commit ID](https://github.com/gitleaks/gitleaks/blob/master/.pre-commit-hooks.yaml) for executing GitLeaks using the [official Docker images](#docker)
|
for a [native execution of gitleaks](https://github.com/gitleaks/gitleaks/releases) or use the [`gitleaks-docker` pre-commit ID](https://github.com/gitleaks/gitleaks/blob/master/.pre-commit-hooks.yaml) for executing gitleaks using the [official Docker images](#docker)
|
||||||
|
|
||||||
3. Auto-update the config to the latest repos' versions by executing `pre-commit autoupdate`
|
3. Auto-update the config to the latest repos' versions by executing `pre-commit autoupdate`
|
||||||
4. Install with `pre-commit install`
|
4. Install with `pre-commit install`
|
||||||
@@ -129,11 +117,13 @@ Detect hardcoded secrets................................................Skipped
|
|||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
```
|
```
|
||||||
|
Gitleaks scans code, past or present, for secrets
|
||||||
|
|
||||||
Usage:
|
Usage:
|
||||||
gitleaks [command]
|
gitleaks [command]
|
||||||
|
|
||||||
Available Commands:
|
Available Commands:
|
||||||
completion generate the autocompletion script for the specified shell
|
completion Generate the autocompletion script for the specified shell
|
||||||
dir scan directories or files for secrets
|
dir scan directories or files for secrets
|
||||||
git scan git repositories for secrets
|
git scan git repositories for secrets
|
||||||
help Help about any command
|
help Help about any command
|
||||||
@@ -146,22 +136,27 @@ Flags:
|
|||||||
order of precedence:
|
order of precedence:
|
||||||
1. --config/-c
|
1. --config/-c
|
||||||
2. env var GITLEAKS_CONFIG
|
2. env var GITLEAKS_CONFIG
|
||||||
3. (target path)/.gitleaks.toml
|
3. env var GITLEAKS_CONFIG_TOML with the file content
|
||||||
If none of the three options are used, then gitleaks will use the default config
|
4. (target path)/.gitleaks.toml
|
||||||
|
If none of the four options are used, then gitleaks will use the default config
|
||||||
|
--diagnostics string enable diagnostics (http OR comma-separated list: cpu,mem,trace). cpu=CPU prof, mem=memory prof, trace=exec tracing, http=serve via net/http/pprof
|
||||||
|
--diagnostics-dir string directory to store diagnostics output files when not using http mode (defaults to current directory)
|
||||||
--enable-rule strings only enable specific rules by id
|
--enable-rule strings only enable specific rules by id
|
||||||
--exit-code int exit code when leaks have been encountered (default 1)
|
--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 ".")
|
-i, --gitleaks-ignore-path string path to .gitleaksignore file or folder containing one (default ".")
|
||||||
-h, --help help for gitleaks
|
-h, --help help for gitleaks
|
||||||
--ignore-gitleaks-allow ignore gitleaks:allow comments
|
--ignore-gitleaks-allow ignore gitleaks:allow comments
|
||||||
-l, --log-level string log level (trace, debug, info, warn, error, fatal) (default "info")
|
-l, --log-level string log level (trace, debug, info, warn, error, fatal) (default "info")
|
||||||
|
--max-archive-depth int allow scanning into nested archives up to this depth (default "0", no archive traversal is done)
|
||||||
--max-decode-depth int allow recursive decoding up to this depth (default "0", no decoding is done)
|
--max-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
|
--max-target-megabytes int files larger than this will be skipped
|
||||||
--no-banner suppress banner
|
--no-banner suppress banner
|
||||||
--no-color turn off color for verbose output
|
--no-color turn off color for verbose output
|
||||||
--redact uint[=100] redact secrets from logs and stdout. To redact only parts of the secret just apply a percent value from 0..100. For example --redact=20 (default 100%)
|
--redact uint[=100] redact secrets from logs and stdout. To redact only parts of the secret just apply a percent value from 0..100. For example --redact=20 (default 100%)
|
||||||
-f, --report-format string output format (json, csv, junit, sarif) (default "json")
|
-f, --report-format string output format (json, csv, junit, sarif, template)
|
||||||
-r, --report-path string report file
|
-r, --report-path string report file
|
||||||
--report-template string template file used to generate the report (implies --report-format=template)
|
--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
|
-v, --verbose show verbose output from scan
|
||||||
--version version for gitleaks
|
--version version for gitleaks
|
||||||
|
|
||||||
@@ -177,6 +172,7 @@ If you find v8.19.0 broke an existing command (`detect`/`protect`), please open
|
|||||||
There are three scanning modes: `git`, `dir`, and `stdin`.
|
There are three scanning modes: `git`, `dir`, and `stdin`.
|
||||||
|
|
||||||
#### Git
|
#### Git
|
||||||
|
|
||||||
The `git` command lets you scan local git repos. Under the hood, gitleaks uses the `git log -p` command to scan patches.
|
The `git` command lets you scan local git repos. Under the hood, gitleaks uses the `git log -p` command to scan patches.
|
||||||
You can configure the behavior of `git log -p` with the `log-opts` option.
|
You can configure the behavior of `git log -p` with the `log-opts` option.
|
||||||
For example, if you wanted to run gitleaks on a range of commits you could use the following
|
For example, if you wanted to run gitleaks on a range of commits you could use the following
|
||||||
@@ -184,10 +180,12 @@ command: `gitleaks git -v --log-opts="--all commitA..commitB" path_to_repo`. See
|
|||||||
If there is no target specified as a positional argument, then gitleaks will attempt to scan the current working directory as a git repo.
|
If there is no target specified as a positional argument, then gitleaks will attempt to scan the current working directory as a git repo.
|
||||||
|
|
||||||
#### Dir
|
#### Dir
|
||||||
|
|
||||||
The `dir` (aliases include `files`, `directory`) command lets you scan directories and files. Example: `gitleaks dir -v path_to_directory_or_file`.
|
The `dir` (aliases include `files`, `directory`) command lets you scan directories and files. Example: `gitleaks dir -v path_to_directory_or_file`.
|
||||||
If there is no target specified as a positional argument, then gitleaks will scan the current working directory.
|
If there is no target specified as a positional argument, then gitleaks will scan the current working directory.
|
||||||
|
|
||||||
#### Stdin
|
#### Stdin
|
||||||
|
|
||||||
You can also stream data to gitleaks with the `stdin` command. Example: `cat some_file | gitleaks -v stdin`
|
You can also stream data to gitleaks with the `stdin` command. Example: `cat some_file | gitleaks -v stdin`
|
||||||
|
|
||||||
### Creating a baseline
|
### Creating a baseline
|
||||||
@@ -212,40 +210,76 @@ After running the detect command with the --baseline-path parameter, report outp
|
|||||||
You can run Gitleaks as a pre-commit hook by copying the example `pre-commit.py` script into
|
You can run Gitleaks as a pre-commit hook by copying the example `pre-commit.py` script into
|
||||||
your `.git/hooks/` directory.
|
your `.git/hooks/` directory.
|
||||||
|
|
||||||
|
## Load Configuration
|
||||||
|
|
||||||
|
The order of precedence is:
|
||||||
|
|
||||||
|
1. `--config/-c` option:
|
||||||
|
```bash
|
||||||
|
gitleaks git --config /home/dev/customgitleaks.toml .
|
||||||
|
```
|
||||||
|
2. Environment variable `GITLEAKS_CONFIG` with the file path:
|
||||||
|
```bash
|
||||||
|
export GITLEAKS_CONFIG="/home/dev/customgitleaks.toml"
|
||||||
|
gitleaks git .
|
||||||
|
```
|
||||||
|
3. Environment variable `GITLEAKS_CONFIG_TOML` with the file content:
|
||||||
|
```bash
|
||||||
|
export GITLEAKS_CONFIG_TOML=`cat customgitleaks.toml`
|
||||||
|
gitleaks git .
|
||||||
|
```
|
||||||
|
4. A `.gitleaks.toml` file within the target path:
|
||||||
|
```bash
|
||||||
|
gitleaks git .
|
||||||
|
```
|
||||||
|
|
||||||
|
If none of the four options are used, then gitleaks will use the default config.
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
Gitleaks offers a configuration format you can follow to write your own secret detection rules:
|
Gitleaks offers a configuration format you can follow to write your own secret detection rules:
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
# Title for the gitleaks configuration file.
|
# Title for the gitleaks configuration file.
|
||||||
title = "Gitleaks title"
|
title = "Custom Gitleaks configuration"
|
||||||
|
|
||||||
|
# You have basically two options for your custom configuration:
|
||||||
|
#
|
||||||
|
# 1. define your own configuration, default rules do not apply
|
||||||
|
#
|
||||||
|
# use e.g., the default configuration as starting point:
|
||||||
|
# https://github.com/gitleaks/gitleaks/blob/master/config/gitleaks.toml
|
||||||
|
#
|
||||||
|
# 2. extend a configuration, the rules are overwritten or extended
|
||||||
|
#
|
||||||
|
# When you extend a configuration the extended rules take precedence over the
|
||||||
|
# default rules. I.e., if there are duplicate rules in both the extended
|
||||||
|
# configuration and the default configuration the extended rules or
|
||||||
|
# attributes of them will override the default rules.
|
||||||
|
# Another thing to know with extending configurations is you can chain
|
||||||
|
# together multiple configuration files to a depth of 2. Allowlist arrays are
|
||||||
|
# appended and can contain duplicates.
|
||||||
|
|
||||||
# Extend the base (this) configuration. When you extend a configuration
|
|
||||||
# the base rules take precedence over the extended rules. I.e., if there are
|
|
||||||
# duplicate rules in both the base configuration and the extended configuration
|
|
||||||
# the base rules will override the extended rules.
|
|
||||||
# Another thing to know with extending configurations is you can chain together
|
|
||||||
# multiple configuration files to a depth of 2. Allowlist arrays are appended
|
|
||||||
# and can contain duplicates.
|
|
||||||
# useDefault and path can NOT be used at the same time. Choose one.
|
# useDefault and path can NOT be used at the same time. Choose one.
|
||||||
[extend]
|
[extend]
|
||||||
# useDefault will extend the base configuration with the default gitleaks config:
|
# useDefault will extend the default gitleaks config built in to the binary
|
||||||
|
# the latest version is located at:
|
||||||
# https://github.com/gitleaks/gitleaks/blob/master/config/gitleaks.toml
|
# https://github.com/gitleaks/gitleaks/blob/master/config/gitleaks.toml
|
||||||
useDefault = true
|
useDefault = true
|
||||||
# or you can supply a path to a configuration. Path is relative to where gitleaks
|
# or you can provide a path to a configuration to extend from.
|
||||||
# was invoked, not the location of the base config.
|
# The path is relative to where gitleaks was invoked,
|
||||||
path = "common_config.toml"
|
# not the location of the base config.
|
||||||
|
# path = "common_config.toml"
|
||||||
# If there are any rules you don't want to inherit, they can be specified here.
|
# If there are any rules you don't want to inherit, they can be specified here.
|
||||||
disabledRules = [ "generic-api-key"]
|
disabledRules = [ "generic-api-key"]
|
||||||
|
|
||||||
# An array of tables that contain information that define instructions
|
# An array of tables that contain information that define instructions
|
||||||
# on how to detect secrets
|
# on how to detect secrets
|
||||||
[[rules]]
|
[[rules]]
|
||||||
|
|
||||||
# Unique identifier for this rule
|
# Unique identifier for this rule
|
||||||
id = "awesome-rule-1"
|
id = "awesome-rule-1"
|
||||||
|
|
||||||
# Short human readable description of the rule.
|
# Short human-readable description of the rule.
|
||||||
description = "awesome rule 1"
|
description = "awesome rule 1"
|
||||||
|
|
||||||
# Golang regular expression used to detect secrets. Note Golang's regex engine
|
# Golang regular expression used to detect secrets. Note Golang's regex engine
|
||||||
@@ -319,19 +353,20 @@ id = "gitlab-pat"
|
|||||||
regexTarget = "line"
|
regexTarget = "line"
|
||||||
regexes = [ '''MY-glpat-''' ]
|
regexes = [ '''MY-glpat-''' ]
|
||||||
|
|
||||||
# This is a global allowlist which has a higher order of precedence than rule-specific allowlists.
|
|
||||||
|
# ⚠️ In v8.25.0 `[allowlist]` was replaced with `[[allowlists]]`.
|
||||||
|
#
|
||||||
|
# Global allowlists have a higher order of precedence than rule-specific allowlists.
|
||||||
# If a commit listed in the `commits` field below is encountered then that commit will be skipped and no
|
# If a commit listed in the `commits` field below is encountered then that commit will be skipped and no
|
||||||
# secrets will be detected for said commit. The same logic applies for regexes and paths.
|
# secrets will be detected for said commit. The same logic applies for regexes and paths.
|
||||||
[allowlist]
|
[[allowlists]]
|
||||||
description = "global allow list"
|
description = "global allow list"
|
||||||
commits = [ "commit-A", "commit-B", "commit-C"]
|
commits = [ "commit-A", "commit-B", "commit-C"]
|
||||||
paths = [
|
paths = [
|
||||||
'''gitleaks\.toml''',
|
'''gitleaks\.toml''',
|
||||||
'''(.*?)(jpg|gif|doc)'''
|
'''(.*?)(jpg|gif|doc)'''
|
||||||
]
|
]
|
||||||
|
|
||||||
# note: (global) regexTarget defaults to check the _Secret_ in the finding.
|
# note: (global) regexTarget defaults to check the _Secret_ in the finding.
|
||||||
# if regexTarget is not specified then _Secret_ will be used.
|
|
||||||
# Acceptable values for regexTarget are "match" and "line"
|
# Acceptable values for regexTarget are "match" and "line"
|
||||||
regexTarget = "match"
|
regexTarget = "match"
|
||||||
regexes = [
|
regexes = [
|
||||||
@@ -345,12 +380,109 @@ stopwords = [
|
|||||||
'''client''',
|
'''client''',
|
||||||
'''endpoint''',
|
'''endpoint''',
|
||||||
]
|
]
|
||||||
|
|
||||||
|
# ⚠️ In v8.25.0, `[[allowlists]]` have a new field called |targetRules|.
|
||||||
|
#
|
||||||
|
# Common allowlists can be defined once and assigned to multiple rules using |targetRules|.
|
||||||
|
# This will only run on the specified rules, not globally.
|
||||||
|
[[allowlists]]
|
||||||
|
targetRules = ["awesome-rule-1", "awesome-rule-2"]
|
||||||
|
description = "Our test assets trigger false-positives in a couple rules."
|
||||||
|
paths = ['''tests/expected/._\.json$''']
|
||||||
```
|
```
|
||||||
|
|
||||||
Refer to the default [gitleaks config](https://github.com/gitleaks/gitleaks/blob/master/config/gitleaks.toml) for examples or follow the [contributing guidelines](https://github.com/gitleaks/gitleaks/blob/master/CONTRIBUTING.md) if you would like to contribute to the default configuration. Additionally, you can check out [this gitleaks blog post](https://blog.gitleaks.io/stop-leaking-secrets-configuration-2-3-aeed293b1fbf) which covers advanced configuration setups.
|
Refer to the default [gitleaks config](https://github.com/gitleaks/gitleaks/blob/master/config/gitleaks.toml) for examples or follow the [contributing guidelines](https://github.com/gitleaks/gitleaks/blob/master/CONTRIBUTING.md) if you would like to contribute to the default configuration. Additionally, you can check out [this gitleaks blog post](https://blog.gitleaks.io/stop-leaking-secrets-configuration-2-3-aeed293b1fbf) which covers advanced configuration setups.
|
||||||
|
|
||||||
### Additional Configuration
|
### 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
|
#### 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
|
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
|
||||||
@@ -391,7 +523,48 @@ ways:
|
|||||||
|
|
||||||
Currently supported encodings:
|
Currently supported encodings:
|
||||||
|
|
||||||
- `base64` (both standard and base64url)
|
- **percent** - Any printable ASCII percent encoded values
|
||||||
|
- **hex** - Any printable ASCII hex encoded values >= 32 characters
|
||||||
|
- **base64** - Any printable ASCII base64 encoded values >= 16 characters
|
||||||
|
|
||||||
|
#### Archive Scanning
|
||||||
|
|
||||||
|
Sometimes secrets are packaged within archive files like zip files or tarballs,
|
||||||
|
making them difficult to discover. Now you can tell gitleaks to automatically
|
||||||
|
extract and scan the contents of archives. The flag `--max-archive-depth`
|
||||||
|
enables this feature for both `dir` and `git` scan types. The default value of
|
||||||
|
"0" means this feature is disabled by default.
|
||||||
|
|
||||||
|
Recursive scanning is supported since archives can also contain other archives.
|
||||||
|
The `--max-archive-depth` flag sets the recursion limit. Recursion stops when
|
||||||
|
there are no new archives to extract, so setting a very high max depth just
|
||||||
|
sets the potential to go that deep. It will only go as deep as it needs to.
|
||||||
|
|
||||||
|
The findings for secrets located within an archive will include the path to the
|
||||||
|
file inside the archive. Inner paths are separated with `!`.
|
||||||
|
|
||||||
|
Example finding (shortened for brevity):
|
||||||
|
|
||||||
|
```
|
||||||
|
Finding: DB_PASSWORD=8ae31cacf141669ddfb5da
|
||||||
|
...
|
||||||
|
File: testdata/archives/nested.tar.gz!archives/files.tar!files/.env.prod
|
||||||
|
Line: 4
|
||||||
|
Commit: 6e6ee6596d337bb656496425fb98644eb62b4a82
|
||||||
|
...
|
||||||
|
Fingerprint: 6e6ee6596d337bb656496425fb98644eb62b4a82:testdata/archives/nested.tar.gz!archives/files.tar!files/.env.prod:generic-api-key:4
|
||||||
|
Link: https://github.com/leaktk/gitleaks/blob/6e6ee6596d337bb656496425fb98644eb62b4a82/testdata/archives/nested.tar.gz
|
||||||
|
```
|
||||||
|
|
||||||
|
This means a secret was detected on line 4 of `files/.env.prod.` which is in
|
||||||
|
`archives/files.tar` which is in `testdata/archives/nested.tar.gz`.
|
||||||
|
|
||||||
|
Currently supported formats:
|
||||||
|
|
||||||
|
The [compression](https://github.com/mholt/archives?tab=readme-ov-file#supported-compression-formats)
|
||||||
|
and [archive](https://github.com/mholt/archives?tab=readme-ov-file#supported-archive-formats)
|
||||||
|
formats supported by mholt's [archives package](https://github.com/mholt/archives)
|
||||||
|
are supported.
|
||||||
|
|
||||||
#### Reporting
|
#### Reporting
|
||||||
|
|
||||||
@@ -453,3 +626,5 @@ You can always set the exit code when leaks are encountered with the --exit-code
|
|||||||
1 - leaks or error encountered
|
1 - leaks or error encountered
|
||||||
126 - unknown flag
|
126 - unknown flag
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Join the Discord! [](https://discord.gg/8Hzbrnkr7E)
|
||||||
+19
@@ -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).
|
||||||
+55
-52
@@ -24,6 +24,7 @@ import (
|
|||||||
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
|
||||||
|
"github.com/zricethezav/gitleaks/v8/cmd/scm"
|
||||||
"github.com/zricethezav/gitleaks/v8/logging"
|
"github.com/zricethezav/gitleaks/v8/logging"
|
||||||
"github.com/zricethezav/gitleaks/v8/report"
|
"github.com/zricethezav/gitleaks/v8/report"
|
||||||
"github.com/zricethezav/gitleaks/v8/sources"
|
"github.com/zricethezav/gitleaks/v8/sources"
|
||||||
@@ -36,6 +37,7 @@ func init() {
|
|||||||
detectCmd.Flags().Bool("follow-symlinks", false, "scan files that are symlinks to other files")
|
detectCmd.Flags().Bool("follow-symlinks", false, "scan files that are symlinks to other files")
|
||||||
detectCmd.Flags().StringP("source", "s", ".", "path to source")
|
detectCmd.Flags().StringP("source", "s", ".", "path to source")
|
||||||
detectCmd.Flags().String("log-opts", "", "git log options")
|
detectCmd.Flags().String("log-opts", "", "git log options")
|
||||||
|
detectCmd.Flags().String("platform", "", "the target platform used to generate links (github, gitlab)")
|
||||||
}
|
}
|
||||||
|
|
||||||
var detectCmd = &cobra.Command{
|
var detectCmd = &cobra.Command{
|
||||||
@@ -46,64 +48,54 @@ var detectCmd = &cobra.Command{
|
|||||||
}
|
}
|
||||||
|
|
||||||
func runDetect(cmd *cobra.Command, args []string) {
|
func runDetect(cmd *cobra.Command, args []string) {
|
||||||
source, err := cmd.Flags().GetString("source")
|
|
||||||
if err != nil {
|
|
||||||
logging.Fatal().Err(err).Msg("could not get source")
|
|
||||||
}
|
|
||||||
initConfig(source)
|
|
||||||
|
|
||||||
var findings []report.Finding
|
|
||||||
|
|
||||||
// setup config (aka, the thing that defines rules)
|
|
||||||
cfg := Config(cmd)
|
|
||||||
|
|
||||||
// start timer
|
// start timer
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
|
sourcePath := mustGetStringFlag(cmd, "source")
|
||||||
|
|
||||||
detector := Detector(cmd, cfg, source)
|
// setup config (aka, the thing that defines rules)
|
||||||
|
initConfig(sourcePath)
|
||||||
|
initDiagnostics()
|
||||||
|
cfg := Config(cmd)
|
||||||
|
|
||||||
// set follow symlinks flag
|
// create detector
|
||||||
if detector.FollowSymlinks, err = cmd.Flags().GetBool("follow-symlinks"); err != nil {
|
detector := Detector(cmd, cfg, sourcePath)
|
||||||
logging.Fatal().Err(err).Msg("")
|
|
||||||
}
|
|
||||||
// set exit code
|
|
||||||
exitCode, err := cmd.Flags().GetInt("exit-code")
|
|
||||||
if err != nil {
|
|
||||||
logging.Fatal().Err(err).Msg("could not get exit code")
|
|
||||||
}
|
|
||||||
|
|
||||||
|
// parse flags
|
||||||
|
detector.FollowSymlinks = mustGetBoolFlag(cmd, "follow-symlinks")
|
||||||
|
exitCode := mustGetIntFlag(cmd, "exit-code")
|
||||||
|
noGit := mustGetBoolFlag(cmd, "no-git")
|
||||||
|
fromPipe := mustGetBoolFlag(cmd, "pipe")
|
||||||
// determine what type of scan:
|
// determine what type of scan:
|
||||||
// - git: scan the history of the repo
|
// - git: scan the history of the repo
|
||||||
// - no-git: scan files by treating the repo as a plain directory
|
// - no-git: scan files by treating the repo as a plain directory
|
||||||
noGit, err := cmd.Flags().GetBool("no-git")
|
var (
|
||||||
if err != nil {
|
err error
|
||||||
logging.Fatal().Err(err).Msg("could not call GetBool() for no-git")
|
findings []report.Finding
|
||||||
}
|
)
|
||||||
fromPipe, err := cmd.Flags().GetBool("pipe")
|
|
||||||
if err != nil {
|
|
||||||
logging.Fatal().Err(err).Msg("could not call GetBool() for pipe")
|
|
||||||
}
|
|
||||||
|
|
||||||
// start the detector scan
|
|
||||||
if noGit {
|
if noGit {
|
||||||
var paths <-chan sources.ScanTarget
|
findings, err = detector.DetectSource(
|
||||||
paths, err = sources.DirectoryTargets(
|
cmd.Context(), &sources.Files{
|
||||||
source,
|
Config: &cfg,
|
||||||
detector.Sema,
|
FollowSymlinks: detector.FollowSymlinks,
|
||||||
detector.FollowSymlinks,
|
MaxFileSize: detector.MaxTargetMegaBytes * 1_000_000,
|
||||||
detector.Config.Allowlist.PathAllowed,
|
Path: sourcePath,
|
||||||
|
Sema: detector.Sema,
|
||||||
|
MaxArchiveDepth: detector.MaxArchiveDepth,
|
||||||
|
},
|
||||||
)
|
)
|
||||||
if err != nil {
|
|
||||||
logging.Fatal().Err(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
findings, err = detector.DetectFiles(paths)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// don't exit on error, just log it
|
// don't exit on error, just log it
|
||||||
logging.Error().Err(err).Msg("failed scan directory")
|
logging.Error().Err(err).Msg("failed to scan directory")
|
||||||
}
|
}
|
||||||
} else if fromPipe {
|
} else if fromPipe {
|
||||||
findings, err = detector.DetectReader(os.Stdin, 10)
|
findings, err = detector.DetectSource(
|
||||||
|
cmd.Context(), &sources.File{
|
||||||
|
Content: os.Stdin,
|
||||||
|
MaxArchiveDepth: detector.MaxArchiveDepth,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// log fatal to exit, no need to continue since a report
|
// log fatal to exit, no need to continue since a report
|
||||||
// will not be generated when scanning from a pipe...for now
|
// will not be generated when scanning from a pipe...for now
|
||||||
@@ -111,18 +103,29 @@ func runDetect(cmd *cobra.Command, args []string) {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
var (
|
var (
|
||||||
gitCmd *sources.GitCmd
|
gitCmd *sources.GitCmd
|
||||||
logOpts string
|
scmPlatform scm.Platform
|
||||||
)
|
)
|
||||||
logOpts, err = cmd.Flags().GetString("log-opts")
|
|
||||||
if err != nil {
|
logOpts := mustGetStringFlag(cmd, "log-opts")
|
||||||
logging.Fatal().Err(err).Msg("could not call GetString() for log-opts")
|
if gitCmd, err = sources.NewGitLogCmdContext(cmd.Context(), sourcePath, logOpts); err != nil {
|
||||||
}
|
|
||||||
gitCmd, err = sources.NewGitLogCmd(source, logOpts)
|
|
||||||
if err != nil {
|
|
||||||
logging.Fatal().Err(err).Msg("could not create Git cmd")
|
logging.Fatal().Err(err).Msg("could not create Git cmd")
|
||||||
}
|
}
|
||||||
findings, err = detector.DetectGit(gitCmd)
|
|
||||||
|
if scmPlatform, err = scm.PlatformFromString(mustGetStringFlag(cmd, "platform")); err != nil {
|
||||||
|
logging.Fatal().Err(err).Send()
|
||||||
|
}
|
||||||
|
|
||||||
|
findings, err = detector.DetectSource(
|
||||||
|
cmd.Context(), &sources.Git{
|
||||||
|
Cmd: gitCmd,
|
||||||
|
Config: &detector.Config,
|
||||||
|
Remote: sources.NewRemoteInfoContext(cmd.Context(), scmPlatform, sourcePath),
|
||||||
|
Sema: detector.Sema,
|
||||||
|
MaxArchiveDepth: detector.MaxArchiveDepth,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// don't exit on error, just log it
|
// don't exit on error, just log it
|
||||||
logging.Error().Err(err).Msg("failed to scan Git repository")
|
logging.Error().Err(err).Msg("failed to scan Git repository")
|
||||||
|
|||||||
@@ -0,0 +1,239 @@
|
|||||||
|
package cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
_ "net/http/pprof"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"runtime/pprof"
|
||||||
|
"runtime/trace"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/zricethezav/gitleaks/v8/logging"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DiagnosticsManager manages various types of diagnostics
|
||||||
|
type DiagnosticsManager struct {
|
||||||
|
Enabled bool
|
||||||
|
DiagTypes []string
|
||||||
|
OutputDir string
|
||||||
|
cpuProfile *os.File
|
||||||
|
memProfile string
|
||||||
|
traceProfile *os.File
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewDiagnosticsManager creates a new DiagnosticsManager instance
|
||||||
|
func NewDiagnosticsManager(diagnosticsFlag string, diagnosticsDir string) (*DiagnosticsManager, error) {
|
||||||
|
if diagnosticsFlag == "" {
|
||||||
|
return &DiagnosticsManager{Enabled: false}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
dm := &DiagnosticsManager{
|
||||||
|
Enabled: true,
|
||||||
|
DiagTypes: strings.Split(diagnosticsFlag, ","),
|
||||||
|
OutputDir: diagnosticsDir,
|
||||||
|
}
|
||||||
|
|
||||||
|
if diagnosticsFlag == "http" {
|
||||||
|
if len(diagnosticsDir) != 0 {
|
||||||
|
return nil, errors.New("the diagnostics directory should not be set in http mode")
|
||||||
|
}
|
||||||
|
|
||||||
|
return dm, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no output directory is specified, use the current directory
|
||||||
|
if dm.OutputDir == "" {
|
||||||
|
var err error
|
||||||
|
dm.OutputDir, err = os.Getwd()
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to get current directory: %w", err)
|
||||||
|
}
|
||||||
|
logging.Debug().Msgf("No diagnostics directory specified, using current directory: %s", dm.OutputDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create the output directory if it doesn't exist
|
||||||
|
if err := os.MkdirAll(dm.OutputDir, 0755); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to create diagnostics directory: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make sure the output directory is absolute
|
||||||
|
if !filepath.IsAbs(dm.OutputDir) {
|
||||||
|
absPath, err := filepath.Abs(dm.OutputDir)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to get absolute path for diagnostics directory: %w", err)
|
||||||
|
}
|
||||||
|
dm.OutputDir = absPath
|
||||||
|
}
|
||||||
|
|
||||||
|
logging.Debug().Msgf("Diagnostics enabled: %s", strings.Join(dm.DiagTypes, ","))
|
||||||
|
logging.Debug().Msgf("Diagnostics output directory: %s", dm.OutputDir)
|
||||||
|
|
||||||
|
return dm, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// StartDiagnostics starts all enabled diagnostics
|
||||||
|
func (dm *DiagnosticsManager) StartDiagnostics() error {
|
||||||
|
if !dm.Enabled {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var err error
|
||||||
|
|
||||||
|
for _, diagType := range dm.DiagTypes {
|
||||||
|
diagType = strings.TrimSpace(diagType)
|
||||||
|
switch diagType {
|
||||||
|
case "cpu":
|
||||||
|
if err = dm.StartCPUProfile(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
case "mem":
|
||||||
|
if err = dm.SetupMemoryProfile(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
case "trace":
|
||||||
|
if err = dm.StartTraceProfile(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
case "http":
|
||||||
|
if err = dm.StartHttpHandler(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
logging.Warn().Msgf("Unknown diagnostics type: %s", diagType)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// StopDiagnostics stops all started diagnostics
|
||||||
|
func (dm *DiagnosticsManager) StopDiagnostics() {
|
||||||
|
if !dm.Enabled {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
logging.Debug().Msg("Stopping diagnostics and writing profiling data...")
|
||||||
|
|
||||||
|
for _, diagType := range dm.DiagTypes {
|
||||||
|
diagType = strings.TrimSpace(diagType)
|
||||||
|
switch diagType {
|
||||||
|
case "cpu":
|
||||||
|
dm.StopCPUProfile()
|
||||||
|
case "mem":
|
||||||
|
dm.WriteMemoryProfile()
|
||||||
|
case "trace":
|
||||||
|
dm.StopTraceProfile()
|
||||||
|
case "http":
|
||||||
|
// No need to stop the http one
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (dm *DiagnosticsManager) StartHttpHandler() error {
|
||||||
|
if len(dm.DiagTypes) > 1 {
|
||||||
|
return errors.New("other diagnostics modes should not be enabled when http mode is enabled")
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
logging.Error().Err(http.ListenAndServe("localhost:6060", nil)).Send()
|
||||||
|
}()
|
||||||
|
|
||||||
|
logging.Info().Str("url", "http://localhost:6060/debug/pprof/").Msg("Diagnostics server started")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// StartCPUProfile starts CPU profiling
|
||||||
|
func (dm *DiagnosticsManager) StartCPUProfile() error {
|
||||||
|
cpuProfilePath := filepath.Join(dm.OutputDir, "cpu.pprof")
|
||||||
|
f, err := os.Create(cpuProfilePath)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("could not create CPU profile at %s: %w", cpuProfilePath, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := pprof.StartCPUProfile(f); err != nil {
|
||||||
|
_ = f.Close()
|
||||||
|
return fmt.Errorf("could not start CPU profile: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
dm.cpuProfile = f
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// StopCPUProfile stops CPU profiling
|
||||||
|
func (dm *DiagnosticsManager) StopCPUProfile() {
|
||||||
|
if dm.cpuProfile != nil {
|
||||||
|
pprof.StopCPUProfile()
|
||||||
|
if err := dm.cpuProfile.Close(); err != nil {
|
||||||
|
logging.Error().Err(err).Msg("Error closing CPU profile file")
|
||||||
|
}
|
||||||
|
logging.Info().Msgf("CPU profile written to: %s", dm.cpuProfile.Name())
|
||||||
|
dm.cpuProfile = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetupMemoryProfile sets up memory profiling to be written when StopDiagnostics is called
|
||||||
|
func (dm *DiagnosticsManager) SetupMemoryProfile() error {
|
||||||
|
memProfilePath := filepath.Join(dm.OutputDir, "mem.pprof")
|
||||||
|
dm.memProfile = memProfilePath
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteMemoryProfile writes the memory profile to disk
|
||||||
|
func (dm *DiagnosticsManager) WriteMemoryProfile() {
|
||||||
|
if dm.memProfile == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
f, err := os.Create(dm.memProfile)
|
||||||
|
if err != nil {
|
||||||
|
logging.Error().Err(err).Msgf("Could not create memory profile at %s", dm.memProfile)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get memory profile
|
||||||
|
runtime.GC() // Run GC before taking the memory profile
|
||||||
|
if err := pprof.WriteHeapProfile(f); err != nil {
|
||||||
|
logging.Error().Err(err).Msg("Could not write memory profile")
|
||||||
|
} else {
|
||||||
|
logging.Info().Msgf("Memory profile written to: %s", dm.memProfile)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := f.Close(); err != nil {
|
||||||
|
logging.Error().Err(err).Msg("Error closing memory profile file")
|
||||||
|
}
|
||||||
|
|
||||||
|
dm.memProfile = ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// StartTraceProfile starts execution tracing
|
||||||
|
func (dm *DiagnosticsManager) StartTraceProfile() error {
|
||||||
|
traceProfilePath := filepath.Join(dm.OutputDir, "trace.out")
|
||||||
|
f, err := os.Create(traceProfilePath)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("could not create trace profile at %s: %w", traceProfilePath, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := trace.Start(f); err != nil {
|
||||||
|
_ = f.Close()
|
||||||
|
return fmt.Errorf("could not start trace profile: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
dm.traceProfile = f
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// StopTraceProfile stops execution tracing
|
||||||
|
func (dm *DiagnosticsManager) StopTraceProfile() {
|
||||||
|
if dm.traceProfile != nil {
|
||||||
|
trace.Stop()
|
||||||
|
if err := dm.traceProfile.Close(); err != nil {
|
||||||
|
logging.Error().Err(err).Msg("Error closing trace profile file")
|
||||||
|
}
|
||||||
|
logging.Info().Msgf("Trace profile written to: %s", dm.traceProfile.Name())
|
||||||
|
dm.traceProfile = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
+15
-17
@@ -6,7 +6,6 @@ import (
|
|||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/logging"
|
"github.com/zricethezav/gitleaks/v8/logging"
|
||||||
"github.com/zricethezav/gitleaks/v8/report"
|
|
||||||
"github.com/zricethezav/gitleaks/v8/sources"
|
"github.com/zricethezav/gitleaks/v8/sources"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -31,11 +30,10 @@ func runDirectory(cmd *cobra.Command, args []string) {
|
|||||||
source = "."
|
source = "."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
initConfig(source)
|
initConfig(source)
|
||||||
var (
|
initDiagnostics()
|
||||||
findings []report.Finding
|
var err error
|
||||||
err error
|
|
||||||
)
|
|
||||||
|
|
||||||
// setup config (aka, the thing that defines rules)
|
// setup config (aka, the thing that defines rules)
|
||||||
cfg := Config(cmd)
|
cfg := Config(cmd)
|
||||||
@@ -47,28 +45,28 @@ func runDirectory(cmd *cobra.Command, args []string) {
|
|||||||
|
|
||||||
// set follow symlinks flag
|
// set follow symlinks flag
|
||||||
if detector.FollowSymlinks, err = cmd.Flags().GetBool("follow-symlinks"); err != nil {
|
if detector.FollowSymlinks, err = cmd.Flags().GetBool("follow-symlinks"); err != nil {
|
||||||
logging.Fatal().Err(err).Msg("")
|
logging.Fatal().Err(err).Send()
|
||||||
}
|
}
|
||||||
|
|
||||||
// set exit code
|
// set exit code
|
||||||
exitCode, err := cmd.Flags().GetInt("exit-code")
|
exitCode, err := cmd.Flags().GetInt("exit-code")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logging.Fatal().Err(err).Msg("could not get exit code")
|
logging.Fatal().Err(err).Msg("could not get exit code")
|
||||||
}
|
}
|
||||||
|
|
||||||
var paths <-chan sources.ScanTarget
|
findings, err := detector.DetectSource(
|
||||||
paths, err = sources.DirectoryTargets(
|
cmd.Context(),
|
||||||
source,
|
&sources.Files{
|
||||||
detector.Sema,
|
Config: &cfg,
|
||||||
detector.FollowSymlinks,
|
FollowSymlinks: detector.FollowSymlinks,
|
||||||
detector.Config.Allowlist.PathAllowed,
|
MaxFileSize: detector.MaxTargetMegaBytes * 1_000_000,
|
||||||
|
Path: source,
|
||||||
|
Sema: detector.Sema,
|
||||||
|
MaxArchiveDepth: detector.MaxArchiveDepth,
|
||||||
|
},
|
||||||
)
|
)
|
||||||
if err != nil {
|
|
||||||
logging.Fatal().Err(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
findings, err = detector.DetectFiles(paths)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// don't exit on error, just log it
|
|
||||||
logging.Error().Err(err).Msg("failed scan directory")
|
logging.Error().Err(err).Msg("failed scan directory")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,106 +4,117 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func CreateGlobalConfig() config.Config {
|
func CreateGlobalConfig() config.Config {
|
||||||
return config.Config{
|
return config.Config{
|
||||||
Title: "gitleaks config",
|
Title: "gitleaks config",
|
||||||
Allowlist: config.Allowlist{
|
Allowlists: []*config.Allowlist{
|
||||||
Description: "global allow lists",
|
{
|
||||||
Regexes: []*regexp.Regexp{
|
Description: "global allow lists",
|
||||||
// ----------- General placeholders -----------
|
Regexes: []*regexp.Regexp{
|
||||||
regexp.MustCompile(`(?i)^true|false|null$`),
|
// ----------- General placeholders -----------
|
||||||
// Awkward workaround to detect repeated characters.
|
regexp.MustCompile(`(?i)^true|false|null$`),
|
||||||
func() *regexp.Regexp {
|
// Awkward workaround to detect repeated characters.
|
||||||
var (
|
func() *regexp.Regexp {
|
||||||
letters = "abcdefghijklmnopqrstuvwxyz*."
|
var (
|
||||||
patterns []string
|
letters = "abcdefghijklmnopqrstuvwxyz*."
|
||||||
)
|
patterns []string
|
||||||
for _, char := range letters {
|
)
|
||||||
if char == '*' || char == '.' {
|
for _, char := range letters {
|
||||||
patterns = append(patterns, fmt.Sprintf("\\%c+", char))
|
if char == '*' || char == '.' {
|
||||||
} else {
|
patterns = append(patterns, fmt.Sprintf("\\%c+", char))
|
||||||
patterns = append(patterns, fmt.Sprintf("%c+", char))
|
} else {
|
||||||
|
patterns = append(patterns, fmt.Sprintf("%c+", char))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
return regexp.MustCompile("^(?i:" + strings.Join(patterns, "|") + ")$")
|
||||||
return regexp.MustCompile("^(?i:" + strings.Join(patterns, "|") + ")$")
|
}(),
|
||||||
}(),
|
|
||||||
|
|
||||||
// ----------- Environment Variables -----------
|
// ----------- Environment Variables -----------
|
||||||
regexp.MustCompile(`^\$(\d+|{\d+})$`),
|
regexp.MustCompile(`^\$(?:\d+|{\d+})$`),
|
||||||
regexp.MustCompile(`^\$([A-Z_]+|[a-z_]+)$`),
|
regexp.MustCompile(`^\$(?:[A-Z_]+|[a-z_]+)$`),
|
||||||
regexp.MustCompile(`^\${([A-Z_]+|[a-z_]+)}$`),
|
regexp.MustCompile(`^\${(?:[A-Z_]+|[a-z_]+)}$`),
|
||||||
|
|
||||||
// ----------- Interpolated Variables -----------
|
// ----------- Interpolated Variables -----------
|
||||||
// Ansible (https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_variables.html)
|
// Ansible (https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_variables.html)
|
||||||
regexp.MustCompile(`^\{\{[ \t]*[\w ().|]+[ \t]*}}$`),
|
regexp.MustCompile(`^\{\{[ \t]*[\w ().|]+[ \t]*}}$`),
|
||||||
// GitHub Actions
|
// GitHub Actions
|
||||||
// https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/store-information-in-variables
|
// https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/store-information-in-variables
|
||||||
// https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions
|
// https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions
|
||||||
regexp.MustCompile(`^\$\{\{[ \t]*((env|github|secrets|vars)(\.[A-Za-z]\w+)+[\w "'&./=|]*)[ \t]*}}$`),
|
regexp.MustCompile(`^\$\{\{[ \t]*(?:(?:env|github|secrets|vars)(?:\.[A-Za-z]\w+)+[\w "'&./=|]*)[ \t]*}}$`),
|
||||||
// NuGet (https://learn.microsoft.com/en-us/nuget/reference/nuget-config-file#using-environment-variables)
|
// NuGet (https://learn.microsoft.com/en-us/nuget/reference/nuget-config-file#using-environment-variables)
|
||||||
regexp.MustCompile(`^%([A-Z_]+|[a-z_]+)%$`),
|
regexp.MustCompile(`^%(?:[A-Z_]+|[a-z_]+)%$`),
|
||||||
// String formatting.
|
// String formatting.
|
||||||
regexp.MustCompile(`^%[+\-# 0]?[bcdeEfFgGoOpqstTUvxX]$`), // Golang (https://pkg.go.dev/fmt)
|
regexp.MustCompile(`^%[+\-# 0]?[bcdeEfFgGoOpqstTUvxX]$`), // Golang (https://pkg.go.dev/fmt)
|
||||||
regexp.MustCompile(`^\{\d{0,2}}$`), // Python (https://docs.python.org/3/tutorial/inputoutput.html)
|
regexp.MustCompile(`^\{\d{0,2}}$`), // Python (https://docs.python.org/3/tutorial/inputoutput.html)
|
||||||
// Urban Code Deploy (https://www.ibm.com/support/pages/replace-token-step-replaces-replacement-values-windows-variables)
|
// Urban Code Deploy (https://www.ibm.com/support/pages/replace-token-step-replaces-replacement-values-windows-variables)
|
||||||
regexp.MustCompile(`^@([A-Z_]+|[a-z_]+)@$`),
|
regexp.MustCompile(`^@(?:[A-Z_]+|[a-z_]+)@$`),
|
||||||
|
|
||||||
// ----------- Miscellaneous -----------
|
// ----------- Miscellaneous -----------
|
||||||
},
|
// File paths
|
||||||
Paths: []*regexp.Regexp{
|
regexp.MustCompile(`^/Users/(?i)[a-z0-9]+/[\w .-/]+$`), // MacOS
|
||||||
regexp.MustCompile(`gitleaks\.toml`),
|
regexp.MustCompile(`^/(?:bin|etc|home|opt|tmp|usr|var)/[\w ./-]+$`), // Linux
|
||||||
|
// 11980 Jps -Dapplication.home=D:\develop_tools\jdk\jdk1.8.0_131 -Xms8m
|
||||||
|
//regexp.MustCompile(`^$`), // Windows
|
||||||
|
},
|
||||||
|
Paths: []*regexp.Regexp{
|
||||||
|
regexp.MustCompile(`gitleaks\.toml`),
|
||||||
|
|
||||||
// ----------- Documents and media -----------
|
// ----------- Documents and media -----------
|
||||||
regexp.MustCompile(`(?i)\.(bmp|gif|jpe?g|svg|tiff?)$`), // Images
|
regexp.MustCompile(`(?i)\.(?:bmp|gif|jpe?g|png|svg|tiff?)$`), // Images
|
||||||
regexp.MustCompile(`\.(eot|[ot]tf|woff2?)$`), // Fonts
|
regexp.MustCompile(`(?i)\.(?:eot|[ot]tf|woff2?)$`), // Fonts
|
||||||
regexp.MustCompile(`(.*?)(doc|docx|zip|xls|pdf|bin|socket|vsidx|v2|suo|wsuo|.dll|pdb|exe|gltf)$`),
|
regexp.MustCompile(`(?i)\.(?:docx?|xlsx?|pdf|bin|socket|vsidx|v2|suo|wsuo|.dll|pdb|exe|gltf)$`),
|
||||||
|
|
||||||
// ----------- Golang files -----------
|
// ----------- Golang files -----------
|
||||||
regexp.MustCompile(`go\.(mod|sum|work(\.sum)?)$`),
|
regexp.MustCompile(`go\.(?:mod|sum|work(?:\.sum)?)$`),
|
||||||
regexp.MustCompile(`(^|/)vendor/modules\.txt$`),
|
regexp.MustCompile(`(?:^|/)vendor/modules\.txt$`),
|
||||||
regexp.MustCompile(`(^|/)vendor/(github\.com|golang\.org/x|google\.golang\.org|gopkg\.in|istio\.io|k8s\.io|sigs\.k8s\.io)(/.*)?$`),
|
regexp.MustCompile(`(?:^|/)vendor/(?:github\.com|golang\.org/x|google\.golang\.org|gopkg\.in|istio\.io|k8s\.io|sigs\.k8s\.io)(?:/.*)?$`),
|
||||||
|
|
||||||
// ----------- Java files -----------
|
// ----------- Java files -----------
|
||||||
// Gradle
|
// Gradle
|
||||||
regexp.MustCompile(`(^|/)gradlew(\.bat)?$`),
|
regexp.MustCompile(`(?:^|/)gradlew(?:\.bat)?$`),
|
||||||
regexp.MustCompile(`(^|/)gradle\.lockfile$`),
|
regexp.MustCompile(`(?:^|/)gradle\.lockfile$`),
|
||||||
regexp.MustCompile(`(^|/)mvnw(\.cmd)?$`),
|
regexp.MustCompile(`(?:^|/)mvnw(?:\.cmd)?$`),
|
||||||
regexp.MustCompile(`(^|/)\.mvn/wrapper/MavenWrapperDownloader\.java$`),
|
regexp.MustCompile(`(?:^|/)\.mvn/wrapper/MavenWrapperDownloader\.java$`),
|
||||||
|
|
||||||
// ----------- JavaScript files -----------
|
// ----------- JavaScript files -----------
|
||||||
// Dependencies and lock files.
|
// Dependencies and lock files.
|
||||||
regexp.MustCompile(`(^|/)node_modules(/.*)?$`),
|
regexp.MustCompile(`(?:^|/)node_modules(?:/.*)?$`),
|
||||||
regexp.MustCompile(`(^|/)(npm-shrinkwrap\.json|package-lock\.json|pnpm-lock\.yaml|yarn\.lock)$`),
|
regexp.MustCompile(`(?:^|/)(?:deno\.lock|npm-shrinkwrap\.json|package-lock\.json|pnpm-lock\.yaml|yarn\.lock)$`),
|
||||||
regexp.MustCompile(`(^|/)bower_components(/.*)?$`),
|
regexp.MustCompile(`(?:^|/)bower_components(?:/.*)?$`),
|
||||||
// TODO: Add more common static assets, such as swagger-ui.
|
// TODO: Add more common static assets, such as swagger-ui.
|
||||||
regexp.MustCompile(`(^|/)(angular|jquery(-?ui)?|plotly|swagger-?ui)[a-zA-Z0-9.-]*(\.min)?\.js(\.map)?$`),
|
regexp.MustCompile(`(?:^|/)(?:angular|bootstrap|jquery(?:-?ui)?|plotly|swagger-?ui)[a-zA-Z0-9.-]*(?:\.min)?\.js(?:\.map)?$`),
|
||||||
|
regexp.MustCompile(`(?:^|/)javascript\.json$`),
|
||||||
|
|
||||||
// ----------- Python files -----------
|
// ----------- Python files -----------
|
||||||
// Dependencies and lock files.
|
// Dependencies and lock files.
|
||||||
regexp.MustCompile(`(^|/)(Pipfile|poetry)\.lock$`),
|
regexp.MustCompile(`(?:^|/)(?:Pipfile|poetry)\.lock$`),
|
||||||
// Virtual environments
|
// Virtual environments
|
||||||
regexp.MustCompile(`(?i)/?(v?env|virtualenv)/lib(64)?(/.*)?$`),
|
regexp.MustCompile(`(?i)(?:^|/)(?:v?env|virtualenv)/lib(?:64)?(?:/.*)?$`),
|
||||||
regexp.MustCompile(`(?i)(^|/)(lib(64)?/python[23](\.\d{1,2})+|python/[23](\.\d{1,2})+/lib(64)?)(/.*)?$`),
|
regexp.MustCompile(`(?i)(?:^|/)(?:lib(?:64)?/python[23](?:\.\d{1,2})+|python/[23](?:\.\d{1,2})+/lib(?:64)?)(?:/.*)?$`),
|
||||||
// dist-info directory (https://py-pkgs.org/04-package-structure.html#building-sdists-and-wheels)
|
// dist-info directory (https://py-pkgs.org/04-package-structure.html#building-sdists-and-wheels)
|
||||||
regexp.MustCompile(`(?i)(^|/)[a-z0-9_.]+-[0-9.]+\.dist-info(/.+)?$`),
|
regexp.MustCompile(`(?i)(?:^|/)[a-z0-9_.]+-[0-9.]+\.dist-info(?:/.+)?$`),
|
||||||
|
|
||||||
// ----------- Ruby files -----------
|
// ----------- Ruby files -----------
|
||||||
regexp.MustCompile(`(^|/)vendor/(bundle|ruby)(/.*?)?$`),
|
regexp.MustCompile(`(?:^|/)vendor/(?:bundle|ruby)(?:/.*?)?$`),
|
||||||
regexp.MustCompile(`\.gem$`), // tar archive
|
regexp.MustCompile(`\.gem$`), // tar archive
|
||||||
|
|
||||||
// Misc
|
// Misc
|
||||||
regexp.MustCompile(`verification-metadata\.xml`),
|
regexp.MustCompile(`verification-metadata\.xml`),
|
||||||
regexp.MustCompile(`Database.refactorlog`),
|
regexp.MustCompile(`Database.refactorlog`),
|
||||||
//regexp.MustCompile(`vendor`),
|
|
||||||
},
|
// ----------- Git files ------------
|
||||||
StopWords: []string{
|
regexp.MustCompile(`(?:^|/)\.git$`),
|
||||||
// ----------- Secrets -----------
|
},
|
||||||
// Checkmarx client secret. (https://github.com/checkmarx-ts/checkmarx-python-sdk/blob/86560f6e2a3e46d16322101294da10d5d190312d/README.md?plain=1#L56)
|
StopWords: []string{
|
||||||
"014df517-39d1-4453-b7b3-9930c563627c",
|
"abcdefghijklmnopqrstuvwxyz", // character range
|
||||||
|
// ----------- Secrets -----------
|
||||||
|
// Checkmarx client secret. (https://github.com/checkmarx-ts/checkmarx-python-sdk/blob/86560f6e2a3e46d16322101294da10d5d190312d/README.md?plain=1#L56)
|
||||||
|
"014df517-39d1-4453-b7b3-9930c563627c",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,142 +4,200 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestConfigAllowlistRegexes(t *testing.T) {
|
var allowlistRegexTests = map[string]struct {
|
||||||
tests := map[string]struct {
|
invalid []string
|
||||||
invalid []string
|
valid []string
|
||||||
valid []string
|
}{
|
||||||
}{
|
"general placeholders": {
|
||||||
"general placeholders": {
|
invalid: []string{
|
||||||
invalid: []string{
|
`true`, `True`, `false`, `False`, `null`, `NULL`,
|
||||||
`true`, `True`, `false`, `False`, `null`, `NULL`,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
"general placeholders - repeated characters": {
|
},
|
||||||
invalid: []string{
|
"general placeholders - repeated characters": {
|
||||||
`aaaaaaaaaaaaaaaaa`, `BBBBBBBBBBbBBBBBBBbBB`, `********************`,
|
invalid: []string{
|
||||||
},
|
`aaaaaaaaaaaaaaaaa`, `BBBBBBBBBBbBBBBBBBbBB`, `********************`,
|
||||||
valid: []string{`aaaaaaaaaaaaaaaaaaabaa`, `pas*************d`},
|
|
||||||
},
|
},
|
||||||
"environment variables": {
|
valid: []string{`aaaaaaaaaaaaaaaaaaabaa`, `pas*************d`},
|
||||||
invalid: []string{`$2`, `$GIT_PASSWORD`, `${GIT_PASSWORD}`, `$password`},
|
},
|
||||||
valid: []string{`$yP@R.@=ibxI`, `$2a6WCust9aE`, `${not_complete1`},
|
"environment variables": {
|
||||||
|
invalid: []string{`$2`, `$GIT_PASSWORD`, `${GIT_PASSWORD}`, `$password`},
|
||||||
|
valid: []string{`$yP@R.@=ibxI`, `$2a6WCust9aE`, `${not_complete1`},
|
||||||
|
},
|
||||||
|
"interpolated variables - ansible": {
|
||||||
|
invalid: []string{
|
||||||
|
`{{ x }}`, `{{ password }}`, `{{password}}`, `{{ data.proxy_password }}`,
|
||||||
|
`{{ dict1 | ansible.builtin.combine(dict2) }}`,
|
||||||
},
|
},
|
||||||
"interpolated variables - ansible": {
|
},
|
||||||
invalid: []string{
|
"interpolated variables - github actions": {
|
||||||
`{{ x }}`, `{{ password }}`, `{{password}}`, `{{ data.proxy_password }}`,
|
invalid: []string{
|
||||||
`{{ dict1 | ansible.builtin.combine(dict2) }}`,
|
`${{ env.First_Name }}`,
|
||||||
},
|
`${{ env.DAY_OF_WEEK == 'Monday' }}`,
|
||||||
|
`${{env.JAVA_VERSION}}`,
|
||||||
|
`${{ github.event.issue.title }}`,
|
||||||
|
`${{ github.repository == "Gattocrucco/lsqfitgp" }}`,
|
||||||
|
`${{ github.event.pull_request.number || github.ref }}`,
|
||||||
|
`${{ github.event_name == 'pull_request' && github.event.action == 'unassigned' }}`,
|
||||||
|
`${{ secrets.SuperSecret }}`,
|
||||||
|
`${{ vars.JOB_NAME }}`,
|
||||||
|
`${{ vars.USE_VARIABLES == 'true' }}`,
|
||||||
},
|
},
|
||||||
"interpolated variables - github actions": {
|
},
|
||||||
invalid: []string{
|
"interpolated variables - nuget": {
|
||||||
`${{ env.First_Name }}`,
|
invalid: []string{
|
||||||
`${{ env.DAY_OF_WEEK == 'Monday' }}`,
|
`%MY_PASSWORD%`, `%password%`,
|
||||||
`${{env.JAVA_VERSION}}`,
|
|
||||||
`${{ github.event.issue.title }}`,
|
|
||||||
`${{ github.repository == "Gattocrucco/lsqfitgp" }}`,
|
|
||||||
`${{ github.event.pull_request.number || github.ref }}`,
|
|
||||||
`${{ github.event_name == 'pull_request' && github.event.action == 'unassigned' }}`,
|
|
||||||
`${{ secrets.SuperSecret }}`,
|
|
||||||
`${{ vars.JOB_NAME }}`,
|
|
||||||
`${{ vars.USE_VARIABLES == 'true' }}`,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
"interpolated variables - nuget": {
|
},
|
||||||
invalid: []string{
|
"interpolated variables - string fmt - golang": {
|
||||||
`%MY_PASSWORD%`, `%password%`,
|
invalid: []string{
|
||||||
},
|
`%b`, `%c`, `%d`, `% d`, `%e`, `%E`, `%f`, `%F`, `%g`, `%G`, `%o`, `%O`, `%p`, `%q`, `%-s`, `%s`, `%t`, `%T`, `%U`, `%#U`, `%+v`, `%#v`, `%v`, `%x`, `%X`,
|
||||||
},
|
},
|
||||||
"interpolated variables - string fmt - golang": {
|
},
|
||||||
invalid: []string{
|
"interpolated variables - string fmt - python": {
|
||||||
`%b`, `%c`, `%d`, `% d`, `%e`, `%E`, `%f`, `%F`, `%g`, `%G`, `%o`, `%O`, `%p`, `%q`, `%-s`, `%s`, `%t`, `%T`, `%U`, `%#U`, `%+v`, `%#v`, `%v`, `%x`, `%X`,
|
invalid: []string{
|
||||||
},
|
`{}`, `{0}`, `{10}`,
|
||||||
},
|
},
|
||||||
"interpolated variables - string fmt - python": {
|
},
|
||||||
invalid: []string{
|
"interpolated variables - ucd": {
|
||||||
`{}`, `{0}`, `{10}`,
|
invalid: []string{`@password@`, `@LDAP_PASS@`},
|
||||||
},
|
valid: []string{`@username@mastodon.example`},
|
||||||
|
},
|
||||||
|
"miscellaneous - file paths": {
|
||||||
|
invalid: []string{
|
||||||
|
// MacOS
|
||||||
|
`/Users/james/Projects/SwiftCode/build/Release`,
|
||||||
|
// Linux
|
||||||
|
`/tmp/screen-exchange`,
|
||||||
},
|
},
|
||||||
"interpolated variables - ucd": {
|
valid: []string{},
|
||||||
invalid: []string{`@password@`, `@LDAP_PASS@`},
|
},
|
||||||
valid: []string{`@username@mastodon.example`},
|
}
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
|
func TestConfigAllowlistRegexes(t *testing.T) {
|
||||||
cfg := CreateGlobalConfig()
|
cfg := CreateGlobalConfig()
|
||||||
allowlist := cfg.Allowlist
|
allowlists := cfg.Allowlists
|
||||||
for name, cases := range tests {
|
for name, cases := range allowlistRegexTests {
|
||||||
t.Run(name, func(t *testing.T) {
|
t.Run(name, func(t *testing.T) {
|
||||||
for _, c := range cases.invalid {
|
for _, c := range cases.invalid {
|
||||||
if !allowlist.RegexAllowed(c) {
|
for _, a := range allowlists {
|
||||||
t.Errorf("invalid value not marked as allowed: %s", c)
|
if !a.RegexAllowed(c) {
|
||||||
|
t.Errorf("invalid value not marked as allowed: %s", c)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, c := range cases.valid {
|
for _, c := range cases.valid {
|
||||||
if allowlist.RegexAllowed(c) {
|
for _, a := range allowlists {
|
||||||
t.Errorf("valid value marked as allowed: %s", c)
|
if a.RegexAllowed(c) {
|
||||||
|
t.Errorf("valid value marked as allowed: %s", c)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func BenchmarkConfigAllowlistRegexes(b *testing.B) {
|
||||||
|
cfg := CreateGlobalConfig()
|
||||||
|
allowlists := cfg.Allowlists
|
||||||
|
for n := 0; n < b.N; n++ {
|
||||||
|
for _, cases := range allowlistRegexTests {
|
||||||
|
for _, c := range cases.invalid {
|
||||||
|
for _, a := range allowlists {
|
||||||
|
a.RegexAllowed(c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, c := range cases.valid {
|
||||||
|
for _, a := range allowlists {
|
||||||
|
a.RegexAllowed(c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var allowlistPathsTests = map[string]struct {
|
||||||
|
invalid []string
|
||||||
|
valid []string
|
||||||
|
}{
|
||||||
|
"javascript - common static assets": {
|
||||||
|
invalid: []string{
|
||||||
|
`tests/e2e/nuget/wwwroot/lib/bootstrap/dist/js/bootstrap.esm.min.js`,
|
||||||
|
`src/main/static/lib/angular.1.2.16.min.js`,
|
||||||
|
`src/main/resources/static/jquery-ui-1.12.1/jquery-ui-min.js`,
|
||||||
|
`src/main/resources/static/js/jquery-ui-1.10.4.min.js`,
|
||||||
|
`src-static/js/plotly.min.js`,
|
||||||
|
`swagger/swaggerui/swagger-ui-bundle.js.map`,
|
||||||
|
`swagger/swaggerui/swagger-ui-es-bundle.js.map`,
|
||||||
|
`src/main/static/swagger-ui.min.js`,
|
||||||
|
`swagger/swaggerui/swagger-ui.js`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"python": {
|
||||||
|
invalid: []string{
|
||||||
|
// lock files
|
||||||
|
`Pipfile.lock`, `poetry.lock`,
|
||||||
|
// virtual environments
|
||||||
|
"env/lib/python3.7/site-packages/urllib3/util/url.py",
|
||||||
|
"venv/Lib/site-packages/regex-2018.08.29.dist-info/DESCRIPTION.rst",
|
||||||
|
"venv/lib64/python3.5/site-packages/pynvml.py",
|
||||||
|
"python/python3/virtualenv/Lib/site-packages/pyphonetics/utils.py",
|
||||||
|
"virtualenv/lib64/python3.7/base64.py",
|
||||||
|
// packages
|
||||||
|
"cde-root/usr/lib64/python2.4/site-packages/Numeric.pth",
|
||||||
|
"lib/python3.9/site-packages/setuptools/_distutils/msvccompiler.py",
|
||||||
|
"lib/python3.8/site-packages/botocore/data/alexaforbusiness/2017-11-09/service-2.json",
|
||||||
|
"code/python/3.7.4/Lib/site-packages/dask/bytes/tests/test_bytes_utils.py",
|
||||||
|
"python/3.7.4/Lib/site-packages/fsspec/utils.py",
|
||||||
|
"python/2.7.16.32/Lib/bsddb/test/test_dbenv.py",
|
||||||
|
"python/lib/python3.8/site-packages/boto3/data/ec2/2016-04-01/resources-1.json",
|
||||||
|
// distinfo
|
||||||
|
"libs/PyX-0.15.dist-info/AUTHORS",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
func TestConfigAllowlistPaths(t *testing.T) {
|
func TestConfigAllowlistPaths(t *testing.T) {
|
||||||
tests := map[string]struct {
|
|
||||||
invalid []string
|
|
||||||
valid []string
|
|
||||||
}{
|
|
||||||
"javascript - common static assets": {
|
|
||||||
invalid: []string{
|
|
||||||
`src/main/static/lib/angular.1.2.16.min.js`,
|
|
||||||
`src/main/resources/static/jquery-ui-1.12.1/jquery-ui-min.js`,
|
|
||||||
`src/main/resources/static/js/jquery-ui-1.10.4.min.js`,
|
|
||||||
`src-static/js/plotly.min.js`,
|
|
||||||
`swagger/swaggerui/swagger-ui-bundle.js.map`,
|
|
||||||
`swagger/swaggerui/swagger-ui-es-bundle.js.map`,
|
|
||||||
`src/main/static/swagger-ui.min.js`,
|
|
||||||
`swagger/swaggerui/swagger-ui.js`,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
"python": {
|
|
||||||
invalid: []string{
|
|
||||||
// lock files
|
|
||||||
`Pipfile.lock`, `poetry.lock`,
|
|
||||||
// virtual environments
|
|
||||||
"env/lib/python3.7/site-packages/urllib3/util/url.py",
|
|
||||||
"venv/Lib/site-packages/regex-2018.08.29.dist-info/DESCRIPTION.rst",
|
|
||||||
"venv/lib64/python3.5/site-packages/pynvml.py",
|
|
||||||
"python/python3/virtualenv/Lib/site-packages/pyphonetics/utils.py",
|
|
||||||
"virtualenv/lib64/python3.7/base64.py",
|
|
||||||
// packages
|
|
||||||
"cde-root/usr/lib64/python2.4/site-packages/Numeric.pth",
|
|
||||||
"lib/python3.9/site-packages/setuptools/_distutils/msvccompiler.py",
|
|
||||||
"lib/python3.8/site-packages/botocore/data/alexaforbusiness/2017-11-09/service-2.json",
|
|
||||||
"code/python/3.7.4/Lib/site-packages/dask/bytes/tests/test_bytes_utils.py",
|
|
||||||
"python/3.7.4/Lib/site-packages/fsspec/utils.py",
|
|
||||||
"python/2.7.16.32/Lib/bsddb/test/test_dbenv.py",
|
|
||||||
"python/lib/python3.8/site-packages/boto3/data/ec2/2016-04-01/resources-1.json",
|
|
||||||
// distinfo
|
|
||||||
"libs/PyX-0.15.dist-info/AUTHORS",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
cfg := CreateGlobalConfig()
|
cfg := CreateGlobalConfig()
|
||||||
allowlist := cfg.Allowlist
|
allowlists := cfg.Allowlists
|
||||||
for name, cases := range tests {
|
for name, cases := range allowlistPathsTests {
|
||||||
t.Run(name, func(t *testing.T) {
|
t.Run(name, func(t *testing.T) {
|
||||||
for _, c := range cases.invalid {
|
for _, c := range cases.invalid {
|
||||||
if !allowlist.PathAllowed(c) {
|
for _, a := range allowlists {
|
||||||
t.Errorf("invalid path not marked as allowed: %s", c)
|
if !a.PathAllowed(c) {
|
||||||
|
t.Errorf("invalid path not marked as allowed: %s", c)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, c := range cases.valid {
|
for _, c := range cases.valid {
|
||||||
if allowlist.PathAllowed(c) {
|
for _, a := range allowlists {
|
||||||
t.Errorf("valid path marked as allowed: %s", c)
|
if a.PathAllowed(c) {
|
||||||
|
t.Errorf("valid path marked as allowed: %s", c)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func BenchmarkConfigAllowlistPaths(b *testing.B) {
|
||||||
|
cfg := CreateGlobalConfig()
|
||||||
|
allowlists := cfg.Allowlists
|
||||||
|
for n := 0; n < b.N; n++ {
|
||||||
|
for _, cases := range allowlistPathsTests {
|
||||||
|
for _, c := range cases.invalid {
|
||||||
|
for _, a := range allowlists {
|
||||||
|
a.PathAllowed(c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, c := range cases.valid {
|
||||||
|
for _, a := range allowlists {
|
||||||
|
a.PathAllowed(c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"os"
|
"os"
|
||||||
|
"slices"
|
||||||
"text/template"
|
"text/template"
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/base"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/base"
|
||||||
@@ -18,21 +19,29 @@ const (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
if len(os.Args) < 2 {
|
if len(os.Args) < 2 {
|
||||||
os.Stderr.WriteString("Specify path to the gitleaks.toml config\n")
|
_, _ = os.Stderr.WriteString("Specify path to the gitleaks.toml config\n")
|
||||||
os.Exit(2)
|
os.Exit(2)
|
||||||
}
|
}
|
||||||
gitleaksConfigPath := os.Args[1]
|
gitleaksConfigPath := os.Args[1]
|
||||||
|
|
||||||
configRules := []*config.Rule{
|
configRules := []*config.Rule{
|
||||||
|
rules.OnePasswordSecretKey(),
|
||||||
rules.OnePasswordServiceAccountToken(),
|
rules.OnePasswordServiceAccountToken(),
|
||||||
rules.AdafruitAPIKey(),
|
rules.AdafruitAPIKey(),
|
||||||
rules.AdobeClientID(),
|
rules.AdobeClientID(),
|
||||||
rules.AdobeClientSecret(),
|
rules.AdobeClientSecret(),
|
||||||
rules.AgeSecretKey(),
|
rules.AgeSecretKey(),
|
||||||
rules.Airtable(),
|
rules.AirtableApiKey(),
|
||||||
|
rules.AirtablePersonalAccessToken(),
|
||||||
rules.AlgoliaApiKey(),
|
rules.AlgoliaApiKey(),
|
||||||
rules.AlibabaAccessKey(),
|
rules.AlibabaAccessKey(),
|
||||||
rules.AlibabaSecretKey(),
|
rules.AlibabaSecretKey(),
|
||||||
|
rules.AmazonBedrockAPIKeyLongLived(),
|
||||||
|
rules.AmazonBedrockAPIKeyShortLived(),
|
||||||
|
rules.AnthropicAdminApiKey(),
|
||||||
|
rules.AnthropicApiKey(),
|
||||||
|
rules.ArtifactoryApiKey(),
|
||||||
|
rules.ArtifactoryReferenceToken(),
|
||||||
rules.AsanaClientID(),
|
rules.AsanaClientID(),
|
||||||
rules.AsanaClientSecret(),
|
rules.AsanaClientSecret(),
|
||||||
rules.Atlassian(),
|
rules.Atlassian(),
|
||||||
@@ -46,6 +55,7 @@ func main() {
|
|||||||
rules.Beamer(),
|
rules.Beamer(),
|
||||||
rules.CodecovAccessToken(),
|
rules.CodecovAccessToken(),
|
||||||
rules.CoinbaseAccessToken(),
|
rules.CoinbaseAccessToken(),
|
||||||
|
rules.ClickHouseCloud(),
|
||||||
rules.Clojars(),
|
rules.Clojars(),
|
||||||
rules.CloudflareAPIKey(),
|
rules.CloudflareAPIKey(),
|
||||||
rules.CloudflareGlobalAPIKey(),
|
rules.CloudflareGlobalAPIKey(),
|
||||||
@@ -111,6 +121,7 @@ func main() {
|
|||||||
rules.GitlabPipelineTriggerToken(),
|
rules.GitlabPipelineTriggerToken(),
|
||||||
rules.GitlabRunnerRegistrationToken(),
|
rules.GitlabRunnerRegistrationToken(),
|
||||||
rules.GitlabRunnerAuthenticationToken(),
|
rules.GitlabRunnerAuthenticationToken(),
|
||||||
|
rules.GitlabRunnerAuthenticationTokenRoutable(),
|
||||||
rules.GitlabScimToken(),
|
rules.GitlabScimToken(),
|
||||||
rules.GitlabSessionCookie(),
|
rules.GitlabSessionCookie(),
|
||||||
rules.GitterAccessToken(),
|
rules.GitterAccessToken(),
|
||||||
@@ -121,6 +132,7 @@ func main() {
|
|||||||
rules.HashiCorpTerraform(),
|
rules.HashiCorpTerraform(),
|
||||||
rules.HashicorpField(),
|
rules.HashicorpField(),
|
||||||
rules.Heroku(),
|
rules.Heroku(),
|
||||||
|
rules.HerokuV2(),
|
||||||
rules.HubSpot(),
|
rules.HubSpot(),
|
||||||
rules.HuggingFaceAccessToken(),
|
rules.HuggingFaceAccessToken(),
|
||||||
rules.HuggingFaceOrganizationApiToken(),
|
rules.HuggingFaceOrganizationApiToken(),
|
||||||
@@ -141,12 +153,16 @@ func main() {
|
|||||||
rules.LinkedinClientSecret(),
|
rules.LinkedinClientSecret(),
|
||||||
rules.LobAPIToken(),
|
rules.LobAPIToken(),
|
||||||
rules.LobPubAPIToken(),
|
rules.LobPubAPIToken(),
|
||||||
|
rules.LookerClientID(),
|
||||||
|
rules.LookerClientSecret(),
|
||||||
rules.MailChimp(),
|
rules.MailChimp(),
|
||||||
rules.MailGunPubAPIToken(),
|
rules.MailGunPubAPIToken(),
|
||||||
rules.MailGunPrivateAPIToken(),
|
rules.MailGunPrivateAPIToken(),
|
||||||
rules.MailGunSigningKey(),
|
rules.MailGunSigningKey(),
|
||||||
rules.MapBox(),
|
rules.MapBox(),
|
||||||
rules.MattermostAccessToken(),
|
rules.MattermostAccessToken(),
|
||||||
|
rules.MaxMindLicenseKey(),
|
||||||
|
rules.Meraki(),
|
||||||
rules.MessageBirdAPIToken(),
|
rules.MessageBirdAPIToken(),
|
||||||
rules.MessageBirdClientID(),
|
rules.MessageBirdClientID(),
|
||||||
rules.NetlifyAccessToken(),
|
rules.NetlifyAccessToken(),
|
||||||
@@ -154,6 +170,7 @@ func main() {
|
|||||||
rules.NewRelicUserKey(),
|
rules.NewRelicUserKey(),
|
||||||
rules.NewRelicBrowserAPIKey(),
|
rules.NewRelicBrowserAPIKey(),
|
||||||
rules.NewRelicInsertKey(),
|
rules.NewRelicInsertKey(),
|
||||||
|
rules.Notion(),
|
||||||
rules.NPM(),
|
rules.NPM(),
|
||||||
rules.NugetConfigPassword(),
|
rules.NugetConfigPassword(),
|
||||||
rules.NytimesAccessToken(),
|
rules.NytimesAccessToken(),
|
||||||
@@ -161,6 +178,7 @@ func main() {
|
|||||||
rules.OktaAccessToken(),
|
rules.OktaAccessToken(),
|
||||||
rules.OpenAI(),
|
rules.OpenAI(),
|
||||||
rules.OpenshiftUserToken(),
|
rules.OpenshiftUserToken(),
|
||||||
|
rules.PerplexityAPIKey(),
|
||||||
rules.PlaidAccessID(),
|
rules.PlaidAccessID(),
|
||||||
rules.PlaidSecretKey(),
|
rules.PlaidSecretKey(),
|
||||||
rules.PlaidAccessToken(),
|
rules.PlaidAccessToken(),
|
||||||
@@ -171,6 +189,7 @@ func main() {
|
|||||||
rules.Prefect(),
|
rules.Prefect(),
|
||||||
rules.PrivateAIToken(),
|
rules.PrivateAIToken(),
|
||||||
rules.PrivateKey(),
|
rules.PrivateKey(),
|
||||||
|
rules.PrivateKeyPKCS12File(),
|
||||||
rules.PulumiAPIToken(),
|
rules.PulumiAPIToken(),
|
||||||
rules.PyPiUploadToken(),
|
rules.PyPiUploadToken(),
|
||||||
rules.RapidAPIAccessToken(),
|
rules.RapidAPIAccessToken(),
|
||||||
@@ -204,6 +223,8 @@ func main() {
|
|||||||
rules.SlackLegacyToken(),
|
rules.SlackLegacyToken(),
|
||||||
rules.SlackWebHookUrl(),
|
rules.SlackWebHookUrl(),
|
||||||
rules.Snyk(),
|
rules.Snyk(),
|
||||||
|
rules.Sonar(),
|
||||||
|
rules.SourceGraph(),
|
||||||
rules.StripeAccessToken(),
|
rules.StripeAccessToken(),
|
||||||
rules.SquareAccessToken(),
|
rules.SquareAccessToken(),
|
||||||
rules.SquareSpaceAccessToken(),
|
rules.SquareSpaceAccessToken(),
|
||||||
@@ -233,13 +254,28 @@ func main() {
|
|||||||
// ensure rules have unique ids
|
// ensure rules have unique ids
|
||||||
ruleLookUp := make(map[string]config.Rule, len(configRules))
|
ruleLookUp := make(map[string]config.Rule, len(configRules))
|
||||||
for _, rule := range configRules {
|
for _, rule := range configRules {
|
||||||
|
if err := rule.Validate(); err != nil {
|
||||||
|
logging.Fatal().Err(err).
|
||||||
|
Str("rule-id", rule.RuleID).
|
||||||
|
Msg("Failed to validate rule")
|
||||||
|
}
|
||||||
|
|
||||||
// check if rule is in ruleLookUp
|
// check if rule is in ruleLookUp
|
||||||
if _, ok := ruleLookUp[rule.RuleID]; ok {
|
if _, ok := ruleLookUp[rule.RuleID]; ok {
|
||||||
logging.Fatal().Msgf("rule id %s is not unique", rule.RuleID)
|
logging.Fatal().
|
||||||
|
Str("rule-id", rule.RuleID).
|
||||||
|
Msg("rule id is not unique")
|
||||||
}
|
}
|
||||||
// TODO: eventually change all the signatures to get ride of this
|
// TODO: eventually change all the signatures to get ride of this
|
||||||
// nasty dereferencing.
|
// nasty dereferencing.
|
||||||
ruleLookUp[rule.RuleID] = *rule
|
ruleLookUp[rule.RuleID] = *rule
|
||||||
|
|
||||||
|
// Slices are de-duplicated with a map, every iteration has a different order.
|
||||||
|
// This is an awkward workaround.
|
||||||
|
for _, allowlist := range rule.Allowlists {
|
||||||
|
slices.Sort(allowlist.Commits)
|
||||||
|
slices.Sort(allowlist.StopWords)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
tmpl, err := template.ParseFiles(templatePath)
|
tmpl, err := template.ParseFiles(templatePath)
|
||||||
@@ -251,9 +287,14 @@ func main() {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
logging.Fatal().Err(err).Msg("Failed to create rules.toml")
|
logging.Fatal().Err(err).Msg("Failed to create rules.toml")
|
||||||
}
|
}
|
||||||
|
defer f.Close()
|
||||||
|
|
||||||
cfg := base.CreateGlobalConfig()
|
cfg := base.CreateGlobalConfig()
|
||||||
cfg.Rules = ruleLookUp
|
cfg.Rules = ruleLookUp
|
||||||
|
for _, allowlist := range cfg.Allowlists {
|
||||||
|
slices.Sort(allowlist.Commits)
|
||||||
|
slices.Sort(allowlist.StopWords)
|
||||||
|
}
|
||||||
if err = tmpl.Execute(f, cfg); err != nil {
|
if err = tmpl.Execute(f, cfg); err != nil {
|
||||||
logging.Fatal().Err(err).Msg("could not execute template")
|
logging.Fatal().Err(err).Msg("could not execute template")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
// https://developer.1password.com/docs/service-accounts/security/?token-example=encoded
|
// https://developer.1password.com/docs/service-accounts/security/?token-example=encoded
|
||||||
@@ -34,10 +33,49 @@ export OP_SERVICE_ACCOUNT_TOKEN=ops_eyJzaWduSW5BZGRyZXNzIjoibXkuMXBhc3N3b3JkLmNv
|
|||||||
serviceAccountToken:
|
serviceAccountToken:
|
||||||
fn::secret: ops_eyJzaWduSW5B..[Redacted]`,
|
fn::secret: ops_eyJzaWduSW5B..[Redacted]`,
|
||||||
`: To start using this service account, run the following command:
|
`: To start using this service account, run the following command:
|
||||||
:
|
:
|
||||||
: export OP_SERVICE_ACCOUNT_TOKEN=ops_eyJzaWduSW5BZGRyZXNzIjoiaHR0cHM6...`,
|
: export OP_SERVICE_ACCOUNT_TOKEN=ops_eyJzaWduSW5BZGRyZXNzIjoiaHR0cHM6...`,
|
||||||
// Low entropy.
|
// Low entropy.
|
||||||
`ops_eyJxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`,
|
`ops_eyJxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`,
|
||||||
}
|
}
|
||||||
return utils.Validate(r, tps, fps)
|
return utils.Validate(r, tps, fps)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Reference:
|
||||||
|
// - https://1passwordstatic.com/files/security/1password-white-paper.pdf
|
||||||
|
func OnePasswordSecretKey() *config.Rule {
|
||||||
|
// 1Password secret keys include several hyphens but these are only for readability
|
||||||
|
// and are stripped during 1Password login. This means that the following are technically
|
||||||
|
// the same valid key:
|
||||||
|
// - A3ASWWYB798JRYLJVD423DC286TVMH43EB
|
||||||
|
// - A-3-A-S-W-W-Y-B-7-9-8-J-R-Y-L-J-V-D-4-2-3-D-C-2-8-6-T-V-M-H-4-3-E-B
|
||||||
|
// But in practice, when these keys are added to a vault, exported in an emergency kit, or
|
||||||
|
// copied, they have hyphens that follow one of two patterns I can find:
|
||||||
|
// - A3-ASWWYB-798JRY-LJVD4-23DC2-86TVM-H43EB (every key I've generated has this pattern)
|
||||||
|
// - A3-ASWWYB-798JRYLJVD4-23DC2-86TVM-H43EB (the whitepaper includes this example, which could just be a typo)
|
||||||
|
// To avoid a complicated regex that checks for every possible situation it's probably best
|
||||||
|
// to scan for the these two patterns.
|
||||||
|
r := config.Rule{
|
||||||
|
Description: "Uncovered a possible 1Password secret key, potentially compromising access to secrets in vaults.",
|
||||||
|
RuleID: "1password-secret-key",
|
||||||
|
Regex: regexp.MustCompile(`\bA3-[A-Z0-9]{6}-(?:(?:[A-Z0-9]{11})|(?:[A-Z0-9]{6}-[A-Z0-9]{5}))-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}\b`),
|
||||||
|
Entropy: 3.8,
|
||||||
|
Keywords: []string{"A3-"},
|
||||||
|
}
|
||||||
|
|
||||||
|
// validate
|
||||||
|
tps := utils.GenerateSampleSecrets("1password", secrets.NewSecret(`A3-[A-Z0-9]{6}-[A-Z0-9]{11}-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}`))
|
||||||
|
tps = append(tps, utils.GenerateSampleSecrets("1password", secrets.NewSecret(`A3-[A-Z0-9]{6}-[A-Z0-9]{6}-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}`))...)
|
||||||
|
tps = append(tps,
|
||||||
|
// from whitepaper
|
||||||
|
`A3-ASWWYB-798JRYLJVD4-23DC2-86TVM-H43EB`,
|
||||||
|
`A3-ASWWYB-798JRY-LJVD4-23DC2-86TVM-H43EB`,
|
||||||
|
)
|
||||||
|
fps := []string{
|
||||||
|
// low entropy
|
||||||
|
`A3-XXXXXX-XXXXXXXXXXX-XXXXX-XXXXX-XXXXX`,
|
||||||
|
// lowercase
|
||||||
|
`A3-xXXXXX-XXXXXX-XXXXX-XXXXX-XXXXX-XXXXX`,
|
||||||
|
}
|
||||||
|
return utils.Validate(r, tps, fps)
|
||||||
|
}
|
||||||
@@ -1,10 +1,9 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func AgeSecretKey() *config.Rule {
|
func AgeSecretKey() *config.Rule {
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"regexp"
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Airtable() *config.Rule {
|
func AirtableApiKey() *config.Rule {
|
||||||
// define rule
|
// define rule
|
||||||
r := config.Rule{
|
r := config.Rule{
|
||||||
Description: "Uncovered a possible Airtable API Key, potentially compromising database access and leading to data leakage or alteration.",
|
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")))
|
tps := utils.GenerateSampleSecrets("airtable", secrets.NewSecret(utils.AlphaNumeric("17")))
|
||||||
return utils.Validate(r, tps, nil)
|
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)
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -13,9 +13,9 @@ func Atlassian() *config.Rule {
|
|||||||
RuleID: "atlassian-api-token",
|
RuleID: "atlassian-api-token",
|
||||||
Regex: utils.MergeRegexps(
|
Regex: utils.MergeRegexps(
|
||||||
utils.GenerateSemiGenericRegex(
|
utils.GenerateSemiGenericRegex(
|
||||||
[]string{"atlassian", "confluence", "jira"},
|
[]string{"(?-i:ATLASSIAN|[Aa]tlassian)", "(?-i:CONFLUENCE|[Cc]onfluence)", "(?-i:JIRA|[Jj]ira)"},
|
||||||
`[a-zA-Z0-9]{24}`,
|
`[a-z0-9]{20}[a-f0-9]{4}`, // The last 4 characters are an MD5 hash.
|
||||||
false,
|
true,
|
||||||
),
|
),
|
||||||
utils.GenerateUniqueTokenRegex(`ATATT3[A-Za-z0-9_\-=]{186}`, false),
|
utils.GenerateUniqueTokenRegex(`ATATT3[A-Za-z0-9_\-=]{186}`, false),
|
||||||
),
|
),
|
||||||
@@ -24,10 +24,13 @@ func Atlassian() *config.Rule {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// validate
|
// validate
|
||||||
tps := utils.GenerateSampleSecrets("atlassian", secrets.NewSecret(utils.AlphaNumeric("24")))
|
tps := utils.GenerateSampleSecrets("atlassian", secrets.NewSecret(utils.AlphaNumeric("20")+"[a-f0-9]{4}"))
|
||||||
tps = append(tps, utils.GenerateSampleSecrets("confluence", secrets.NewSecret(utils.AlphaNumeric("24")))...)
|
tps = append(tps, utils.GenerateSampleSecrets("confluence", secrets.NewSecret(utils.AlphaNumeric("20")+"[a-f0-9]{4}"))...)
|
||||||
tps = append(tps, utils.GenerateSampleSecrets("jira", secrets.NewSecret(utils.AlphaNumeric("24")))...)
|
tps = append(tps, utils.GenerateSampleSecrets("jira", secrets.NewSecret(utils.AlphaNumeric("20")+"[a-f0-9]{4}"))...)
|
||||||
|
tps = append(tps, `JIRA_API_TOKEN=HXe8DGg1iJd2AopzyxkFB7F2`)
|
||||||
tps = append(tps, utils.GenerateSampleSecrets("jira", "ATATT3xFfGF0K3irG5tKKi-6u-wwaXQFeGwZ-IHR-hQ3CulkKtMSuteRQFfLZ6jihHThzZCg_UjnDt-4Wl_gIRf4zrZJs5JqaeuBhsfJ4W5GD6yGg3W7903gbvaxZPBjxIQQ7BgFDSkPS8oPispw4KLz56mdK-G6CIvLO6hHRrZHY0Q3tvJ6JxE=C63992E6")...)
|
tps = append(tps, utils.GenerateSampleSecrets("jira", "ATATT3xFfGF0K3irG5tKKi-6u-wwaXQFeGwZ-IHR-hQ3CulkKtMSuteRQFfLZ6jihHThzZCg_UjnDt-4Wl_gIRf4zrZJs5JqaeuBhsfJ4W5GD6yGg3W7903gbvaxZPBjxIQQ7BgFDSkPS8oPispw4KLz56mdK-G6CIvLO6hHRrZHY0Q3tvJ6JxE=C63992E6")...)
|
||||||
|
|
||||||
return utils.Validate(r, tps, nil)
|
fps := []string{"getPagesInConfluenceSpace,searchConfluenceUsingCql"}
|
||||||
|
|
||||||
|
return utils.Validate(r, tps, fps)
|
||||||
}
|
}
|
||||||
@@ -1,11 +1,10 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func AWS() *config.Rule {
|
func AWS() *config.Rule {
|
||||||
@@ -13,7 +12,7 @@ func AWS() *config.Rule {
|
|||||||
r := config.Rule{
|
r := config.Rule{
|
||||||
RuleID: "aws-access-token",
|
RuleID: "aws-access-token",
|
||||||
Description: "Identified a pattern that may indicate AWS credentials, risking unauthorized cloud resource access and data breaches on AWS platforms.",
|
Description: "Identified a pattern that may indicate AWS credentials, risking unauthorized cloud resource access and data breaches on AWS platforms.",
|
||||||
Regex: regexp.MustCompile(`\b((?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16})\b`),
|
Regex: regexp.MustCompile(`\b((?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z2-7]{16})\b`),
|
||||||
Entropy: 3,
|
Entropy: 3,
|
||||||
Keywords: []string{
|
Keywords: []string{
|
||||||
// https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids
|
// https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids
|
||||||
@@ -23,7 +22,7 @@ func AWS() *config.Rule {
|
|||||||
"ABIA", // AWS STS service bearer token
|
"ABIA", // AWS STS service bearer token
|
||||||
"ACCA", // Context-specific credential
|
"ACCA", // Context-specific credential
|
||||||
},
|
},
|
||||||
Allowlists: []config.Allowlist{
|
Allowlists: []*config.Allowlist{
|
||||||
{
|
{
|
||||||
Regexes: []*regexp.Regexp{
|
Regexes: []*regexp.Regexp{
|
||||||
regexp.MustCompile(`.+EXAMPLE$`),
|
regexp.MustCompile(`.+EXAMPLE$`),
|
||||||
@@ -48,3 +47,63 @@ func AWS() *config.Rule {
|
|||||||
}
|
}
|
||||||
return utils.Validate(r, tps, fps)
|
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)
|
||||||
|
}
|
||||||
@@ -3,12 +3,10 @@ package rules
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
// References:
|
// References:
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package rules
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ClickHouseCloud() *config.Rule {
|
||||||
|
// define rule
|
||||||
|
r := config.Rule{
|
||||||
|
RuleID: "clickhouse-cloud-api-secret-key",
|
||||||
|
Description: "Identified a pattern that may indicate clickhouse cloud API secret key, risking unauthorized clickhouse cloud api access and data breaches on ClickHouse Cloud platforms.",
|
||||||
|
Regex: regexp.MustCompile(`\b(4b1d[A-Za-z0-9]{38})\b`),
|
||||||
|
Entropy: 3,
|
||||||
|
Keywords: []string{
|
||||||
|
"4b1d", // Prefix
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// validate
|
||||||
|
tps := utils.GenerateSampleSecrets("ClickHouse", "4b1dbRdW3rOcB7xLthrM4BTBGK1qPLkHigpN1bXD6z")
|
||||||
|
tps = append(tps, utils.GenerateSampleSecrets("ClickHouse", "4b1d"+secrets.NewSecret("[A-Za-z0-9]{38}"))...)
|
||||||
|
fps := []string{
|
||||||
|
`key = 4b1dXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`, // Low entropy
|
||||||
|
`key = adf4b1dbRdW3rOcB7xLthrM4BTBGK1qPLkHigpN1bXD6z`, // Not start of a word
|
||||||
|
}
|
||||||
|
return utils.Validate(r, tps, fps)
|
||||||
|
}
|
||||||
@@ -1,12 +1,10 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Clojars() *config.Rule {
|
func Clojars() *config.Rule {
|
||||||
|
|||||||
@@ -2,7 +2,10 @@
|
|||||||
# If you would like to contribute new rules, please use
|
# If you would like to contribute new rules, please use
|
||||||
# cmd/generate/config/main.go and follow the contributing guidelines
|
# cmd/generate/config/main.go and follow the contributing guidelines
|
||||||
# at https://github.com/gitleaks/gitleaks/blob/master/CONTRIBUTING.md
|
# at https://github.com/gitleaks/gitleaks/blob/master/CONTRIBUTING.md
|
||||||
|
#
|
||||||
|
# How the hell does secret scanning work? Read this:
|
||||||
|
# https://lookingatcomputer.substack.com/p/regex-is-almost-all-you-need
|
||||||
|
#
|
||||||
# This is the default gitleaks configuration file.
|
# This is the default gitleaks configuration file.
|
||||||
# Rules and allowlists are defined within this file.
|
# Rules and allowlists are defined within this file.
|
||||||
# Rules instruct gitleaks on what should be considered a secret.
|
# Rules instruct gitleaks on what should be considered a secret.
|
||||||
@@ -10,26 +13,33 @@
|
|||||||
|
|
||||||
title = "{{.Title}}"
|
title = "{{.Title}}"
|
||||||
|
|
||||||
[allowlist]
|
# minVersion indicates the minimum Gitleaks version required to use this config.
|
||||||
description = "{{.Allowlist.Description}}"
|
# If the running version is older, a warning will be logged and not all
|
||||||
{{- with .Allowlist.RegexTarget }}
|
# config-enabled features are guaranteed to work.
|
||||||
regexTarget = "{{ . }}"{{ end -}}
|
minVersion = "v8.25.0"
|
||||||
{{- with .Allowlist.Regexes }}
|
|
||||||
regexes = [{{ range $i, $regex := . }}
|
{{ with .Allowlists }}{{ range $i, $allowlist := . }}{{ if or $allowlist.Regexes $allowlist.Paths $allowlist.Commits $allowlist.StopWords }}# TODO: change to [[allowlists]]{{println}}[allowlist]
|
||||||
'''{{ $regex }}''',{{ end }}
|
{{- with .Description }}{{println}}description = "{{ . }}"{{ end }}
|
||||||
|
{{- with .MatchCondition }}{{println}}condition = "{{ .String }}"{{ end }}
|
||||||
|
{{- with .Commits -}}{{println}}commits = [
|
||||||
|
{{ range $j, $commit := . }}"{{ $commit }}",{{ end }}
|
||||||
]{{ end }}
|
]{{ end }}
|
||||||
{{- with .Allowlist.Paths }}
|
{{- with .Paths }}{{println}}paths = [{{ range $j, $path := . }}
|
||||||
paths = [{{ range $i, $path := . }}
|
|
||||||
'''{{ $path }}''',{{ end }}
|
'''{{ $path }}''',{{ end }}
|
||||||
]{{ end }}
|
]{{ end }}
|
||||||
{{- with .Allowlist.StopWords }}{{println}}stopwords = [{{ range $j, $stopword := . }}
|
{{- if and .RegexTarget .Regexes }}{{println}}regexTarget = "{{ .RegexTarget }}"{{ end -}}
|
||||||
|
{{- with .Regexes }}{{println}}regexes = [{{ range $i, $regex := . }}
|
||||||
|
'''{{ $regex }}''',{{ end }}
|
||||||
|
]{{ end }}
|
||||||
|
{{- with .StopWords }}{{println}}stopwords = [{{ range $j, $stopword := . }}
|
||||||
"{{ $stopword }}",{{ end }}
|
"{{ $stopword }}",{{ end }}
|
||||||
]{{ end }}{{println}}
|
]{{ end }}{{ end }}{{ end }}{{ end }}{{println}}
|
||||||
|
|
||||||
{{- range $i, $rule := .Rules }}{{println}}[[rules]]
|
{{- range $i, $rule := .Rules }}{{println}}[[rules]]
|
||||||
id = "{{$rule.RuleID}}"
|
id = "{{$rule.RuleID}}"
|
||||||
description = "{{$rule.Description}}"
|
description = "{{$rule.Description}}"
|
||||||
regex = '''{{$rule.Regex}}'''
|
{{- with $rule.Regex }}
|
||||||
|
regex = '''{{ . }}'''{{ end -}}
|
||||||
{{- with $rule.Path }}
|
{{- with $rule.Path }}
|
||||||
path = '''{{ . }}'''{{ end -}}
|
path = '''{{ . }}'''{{ end -}}
|
||||||
{{- with $rule.SecretGroup }}
|
{{- with $rule.SecretGroup }}
|
||||||
@@ -47,7 +57,8 @@ tags = [
|
|||||||
{{ range $j, $tag := . }}"{{ $tag }}",{{ end }}
|
{{ range $j, $tag := . }}"{{ $tag }}",{{ end }}
|
||||||
]{{ end }}
|
]{{ end }}
|
||||||
{{- with $rule.Allowlists }}{{ range $i, $allowlist := . }}{{ if or $allowlist.Regexes $allowlist.Paths $allowlist.Commits $allowlist.StopWords }}{{println}}[[rules.allowlists]]
|
{{- with $rule.Allowlists }}{{ range $i, $allowlist := . }}{{ if or $allowlist.Regexes $allowlist.Paths $allowlist.Commits $allowlist.StopWords }}{{println}}[[rules.allowlists]]
|
||||||
{{- with .MatchCondition }}{{println}}condition = "{{ .MatchCondition.String }}"{{ end }}
|
{{- with .Description }}{{println}}description = "{{ . }}"{{ end }}
|
||||||
|
{{- with .MatchCondition }}{{println}}condition = "{{ .String }}"{{ end }}
|
||||||
{{- with .Commits -}}{{println}}commits = [
|
{{- with .Commits -}}{{println}}commits = [
|
||||||
{{ range $j, $commit := . }}"{{ $commit }}",{{ end }}
|
{{ range $j, $commit := . }}"{{ $commit }}",{{ end }}
|
||||||
]{{ end }}
|
]{{ end }}
|
||||||
|
|||||||
@@ -2,10 +2,10 @@ package rules
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
// https://curl.se/docs/manpage.html#-u
|
// https://curl.se/docs/manpage.html#-u
|
||||||
@@ -13,18 +13,18 @@ func CurlBasicAuth() *config.Rule {
|
|||||||
r := config.Rule{
|
r := config.Rule{
|
||||||
RuleID: "curl-auth-user",
|
RuleID: "curl-auth-user",
|
||||||
Description: "Discovered a potential basic authorization token provided in a curl command, which could compromise the curl accessed resource.",
|
Description: "Discovered a potential basic authorization token provided in a curl command, which could compromise the curl accessed resource.",
|
||||||
Regex: regexp.MustCompile(`\bcurl\b(?:.*|.*(?:[\r\n]{1,2}.*){1,5})[ \t\n\r](?:-u|--user)(?:=|[ \t]{0,5})(?:"([^:"]{3,}:[^"]{3,})"|'([^:']{3,}:[^']{3,})'|((?:"[^"]{3,}"|'[^']{3,}'|[\w$@.-]+):(?:"[^"]{3,}"|'[^']{3,}'|[\w${}@.-]+)))(?:\s|\z)`),
|
Regex: regexp.MustCompile(`\bcurl\b(?:.*|.*(?:[\r\n]{1,2}.*){1,5})[ \t\n\r](?:-u|--user)(?:=|[ \t]{0,5})("(:[^"]{3,}|[^:"]{3,}:|[^:"]{3,}:[^"]{3,})"|'([^:']{3,}:[^']{3,})'|((?:"[^"]{3,}"|'[^']{3,}'|[\w$@.-]+):(?:"[^"]{3,}"|'[^']{3,}'|[\w${}@.-]+)))(?:\s|\z)`),
|
||||||
Keywords: []string{"curl"},
|
Keywords: []string{"curl"},
|
||||||
Entropy: 2,
|
Entropy: 2,
|
||||||
Allowlists: []config.Allowlist{
|
Allowlists: []*config.Allowlist{
|
||||||
{
|
{
|
||||||
Regexes: []*regexp.Regexp{
|
Regexes: []*regexp.Regexp{
|
||||||
regexp.MustCompile(`[^:]+:(change(it|me)|pass(word)?|pwd|test|token|\*+|x+)`), // common placeholder passwords
|
regexp.MustCompile(`[^:]+:(?:change(?:it|me)|pass(?:word)?|pwd|test|token|\*+|x+)`), // common placeholder passwords
|
||||||
regexp.MustCompile(`['"]?<[^>]+>['"]?:['"]?<[^>]+>|<[^:]+:[^>]+>['"]?`), // <placeholder>
|
regexp.MustCompile(`['"]?<[^>]+>['"]?:['"]?<[^>]+>|<[^:]+:[^>]+>['"]?`), // <placeholder>
|
||||||
regexp.MustCompile(`[^:]+:\[[^]]+]`), // [placeholder]
|
regexp.MustCompile(`[^:]+:\[[^]]+]`), // [placeholder]
|
||||||
regexp.MustCompile(`['"]?[^:]+['"]?:['"]?\$(\d|\w+|\{(\d|\w+)})['"]?`), // $1 or $VARIABLE
|
regexp.MustCompile(`['"]?[^:]+['"]?:['"]?\$(?:\d|\w+|\{(?:\d|\w+)})['"]?`), // $1 or $VARIABLE
|
||||||
regexp.MustCompile(`\$\([^)]+\):\$\([^)]+\)`), // $(cat login.txt)
|
regexp.MustCompile(`\$\([^)]+\):\$\([^)]+\)`), // $(cat login.txt)
|
||||||
regexp.MustCompile(`['"]?\$?{{[^}]+}}['"]?:['"]?\$?{{[^}]+}}['"]?`), // ${{ secrets.FOO }} or {{ .Values.foo }}
|
regexp.MustCompile(`['"]?\$?{{[^}]+}}['"]?:['"]?\$?{{[^}]+}}['"]?`), // ${{ secrets.FOO }} or {{ .Values.foo }}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -38,6 +38,8 @@ func CurlBasicAuth() *config.Rule {
|
|||||||
-H 'Content-type: text/plain' \
|
-H 'Content-type: text/plain' \
|
||||||
-d 'world' \
|
-d 'world' \
|
||||||
-u developer:yqDVtkqPECriaLRi`, // different line
|
-u developer:yqDVtkqPECriaLRi`, // different line
|
||||||
|
`curl -u ":d2LkV78zLx!t" https://localhost:9200`, // empty username
|
||||||
|
`curl -u "d2LkV78zLx!t:" https://localhost:9200`, // empty password
|
||||||
|
|
||||||
// long
|
// long
|
||||||
`curl -sw '%{http_code}' -X POST --user 'johns:h0pk1ns~21s' $GItHUB_API_URL/$GIT_COMMIT --data`,
|
`curl -sw '%{http_code}' -X POST --user 'johns:h0pk1ns~21s' $GItHUB_API_URL/$GIT_COMMIT --data`,
|
||||||
@@ -65,6 +67,7 @@ func CurlBasicAuth() *config.Rule {
|
|||||||
`curl -u "${_username}:${_password}"`,
|
`curl -u "${_username}:${_password}"`,
|
||||||
`curl -u "${username}":"${password}"`,
|
`curl -u "${username}":"${password}"`,
|
||||||
`curl -k -X POST -I -u "SRVC_JENKINS:${APPID}"`,
|
`curl -k -X POST -I -u "SRVC_JENKINS:${APPID}"`,
|
||||||
|
`curl -u ":" https://localhost:9200`, // empty username and password
|
||||||
|
|
||||||
// long
|
// long
|
||||||
`curl -sw '%{http_code}' -X POST --user '$USERNAME:$PASSWORD' $GItHUB_API_URL/$GIT_COMMIT --data`,
|
`curl -sw '%{http_code}' -X POST --user '$USERNAME:$PASSWORD' $GItHUB_API_URL/$GIT_COMMIT --data`,
|
||||||
@@ -106,7 +109,7 @@ func CurlHeaderAuth() *config.Rule {
|
|||||||
fmt.Sprintf(`\bcurl\b(?:.*?|.*?(?:[\r\n]{1,2}.*?){1,5})[ \t\n\r](?:-H|--header)(?:=|[ \t]{0,5})(?:"%s"|'%s')(?:\B|\s|\z)`, authPat, authPat)),
|
fmt.Sprintf(`\bcurl\b(?:.*?|.*?(?:[\r\n]{1,2}.*?){1,5})[ \t\n\r](?:-H|--header)(?:=|[ \t]{0,5})(?:"%s"|'%s')(?:\B|\s|\z)`, authPat, authPat)),
|
||||||
Entropy: 2.75,
|
Entropy: 2.75,
|
||||||
Keywords: []string{"curl"},
|
Keywords: []string{"curl"},
|
||||||
//Allowlists: []config.Allowlist{
|
//Allowlists: []*config.Allowlist{
|
||||||
// {
|
// {
|
||||||
// Regexes: []*regexp.Regexp{},
|
// Regexes: []*regexp.Regexp{},
|
||||||
// },
|
// },
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Doppler() *config.Rule {
|
func Doppler() *config.Rule {
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Duffel() *config.Rule {
|
func Duffel() *config.Rule {
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Dynatrace() *config.Rule {
|
func Dynatrace() *config.Rule {
|
||||||
@@ -16,7 +14,7 @@ func Dynatrace() *config.Rule {
|
|||||||
Description: "Detected a Dynatrace API token, potentially risking application performance monitoring and data exposure.",
|
Description: "Detected a Dynatrace API token, potentially risking application performance monitoring and data exposure.",
|
||||||
Regex: regexp.MustCompile(`dt0c01\.(?i)[a-z0-9]{24}\.[a-z0-9]{64}`),
|
Regex: regexp.MustCompile(`dt0c01\.(?i)[a-z0-9]{24}\.[a-z0-9]{64}`),
|
||||||
Entropy: 4,
|
Entropy: 4,
|
||||||
Keywords: []string{"dt0c01"},
|
Keywords: []string{"dt0c01."},
|
||||||
}
|
}
|
||||||
|
|
||||||
// validate
|
// validate
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func EasyPost() *config.Rule {
|
func EasyPost() *config.Rule {
|
||||||
|
|||||||
@@ -34,14 +34,15 @@ func FacebookAccessToken() *config.Rule {
|
|||||||
RuleID: "facebook-access-token",
|
RuleID: "facebook-access-token",
|
||||||
Description: "Discovered a Facebook Access Token, posing a risk of unauthorized access to Facebook accounts and personal data exposure.",
|
Description: "Discovered a Facebook Access Token, posing a risk of unauthorized access to Facebook accounts and personal data exposure.",
|
||||||
Regex: utils.GenerateUniqueTokenRegex(`\d{15,16}(\||%)[0-9a-z\-_]{27,40}`, true),
|
Regex: utils.GenerateUniqueTokenRegex(`\d{15,16}(\||%)[0-9a-z\-_]{27,40}`, true),
|
||||||
|
Keywords: []string{"facebook"},
|
||||||
Entropy: 3,
|
Entropy: 3,
|
||||||
}
|
}
|
||||||
|
|
||||||
// validate
|
// validate
|
||||||
tps := []string{
|
tps := []string{
|
||||||
`{"access_token":"911602140448729|AY-lRJZq9BoDLobvAiP25L7RcMg","token_type":"bearer"}`, // gitleaks:allow
|
`{"facebook access_token":"911602140448729|AY-lRJZq9BoDLobvAiP25L7RcMg","token_type":"bearer"}`, // gitleaks:allow
|
||||||
`1308742762612587|rhoK1cbv0DOU_RTX_87O4MkX7AI`, // gitleaks:allow
|
`facebook 1308742762612587|rhoK1cbv0DOU_RTX_87O4MkX7AI`, // gitleaks:allow
|
||||||
`1477036645700765|wRPf2v3mt2JfMqCLK8n7oltrEmc`, // gitleaks:allow
|
`facebook 1477036645700765|wRPf2v3mt2JfMqCLK8n7oltrEmc`, // gitleaks:allow
|
||||||
}
|
}
|
||||||
return utils.Validate(r, tps, nil)
|
return utils.Validate(r, tps, nil)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func FlutterwavePublicKey() *config.Rule {
|
func FlutterwavePublicKey() *config.Rule {
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func FrameIO() *config.Rule {
|
func FrameIO() *config.Rule {
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Freemius() *config.Rule {
|
func Freemius() *config.Rule {
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TODO this one could probably use some work
|
// TODO this one could probably use some work
|
||||||
@@ -32,11 +30,9 @@ func GCPAPIKey() *config.Rule {
|
|||||||
RuleID: "gcp-api-key",
|
RuleID: "gcp-api-key",
|
||||||
Description: "Uncovered a GCP API key, which could lead to unauthorized access to Google Cloud services and data breaches.",
|
Description: "Uncovered a GCP API key, which could lead to unauthorized access to Google Cloud services and data breaches.",
|
||||||
Regex: utils.GenerateUniqueTokenRegex(`AIza[\w-]{35}`, false),
|
Regex: utils.GenerateUniqueTokenRegex(`AIza[\w-]{35}`, false),
|
||||||
Entropy: 3.0,
|
Entropy: 4,
|
||||||
Keywords: []string{
|
Keywords: []string{"AIza"},
|
||||||
"AIza",
|
Allowlists: []*config.Allowlist{
|
||||||
},
|
|
||||||
Allowlists: []config.Allowlist{
|
|
||||||
{
|
{
|
||||||
Regexes: []*regexp.Regexp{
|
Regexes: []*regexp.Regexp{
|
||||||
// example keys from https://github.com/firebase/firebase-android-sdk
|
// example keys from https://github.com/firebase/firebase-android-sdk
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func GenericCredential() *config.Rule {
|
func GenericCredential() *config.Rule {
|
||||||
@@ -20,11 +19,10 @@ func GenericCredential() *config.Rule {
|
|||||||
"credential",
|
"credential",
|
||||||
"creds",
|
"creds",
|
||||||
"key",
|
"key",
|
||||||
"passwd",
|
"passw(?:or)?d",
|
||||||
"password",
|
|
||||||
"secret",
|
"secret",
|
||||||
"token",
|
"token",
|
||||||
}, `[\w.=-]{10,150}`, true),
|
}, `[\w.=-]{10,150}|[a-z0-9][a-z0-9+/]{11,}={0,3}`, true),
|
||||||
Keywords: []string{
|
Keywords: []string{
|
||||||
"access",
|
"access",
|
||||||
"api",
|
"api",
|
||||||
@@ -38,7 +36,7 @@ func GenericCredential() *config.Rule {
|
|||||||
"token",
|
"token",
|
||||||
},
|
},
|
||||||
Entropy: 3.5,
|
Entropy: 3.5,
|
||||||
Allowlists: []config.Allowlist{
|
Allowlists: []*config.Allowlist{
|
||||||
{
|
{
|
||||||
// NOTE: this is a goofy hack to get around the fact there golang's regex engine does not support positive lookaheads.
|
// NOTE: this is a goofy hack to get around the fact there golang's regex engine does not support positive lookaheads.
|
||||||
// Ideally we would want to ensure the secret contains both numbers and alphabetical characters, not just alphabetical characters.
|
// Ideally we would want to ensure the secret contains both numbers and alphabetical characters, not just alphabetical characters.
|
||||||
@@ -51,12 +49,13 @@ func GenericCredential() *config.Rule {
|
|||||||
MatchCondition: config.AllowlistMatchOr,
|
MatchCondition: config.AllowlistMatchOr,
|
||||||
RegexTarget: "match",
|
RegexTarget: "match",
|
||||||
Regexes: []*regexp.Regexp{
|
Regexes: []*regexp.Regexp{
|
||||||
regexp.MustCompile(`(?i)(` +
|
regexp.MustCompile(`(?i)(?:` +
|
||||||
// Access
|
// Access
|
||||||
`accessor` +
|
`access(?:ibility|or)` +
|
||||||
`|access[_.-]?id` +
|
`|access[_.-]?id` +
|
||||||
|
`|random[_.-]?access` +
|
||||||
// API
|
// API
|
||||||
`|api[_.-]?(version|id)` + // version/id -> not a secret
|
`|api[_.-]?(?:id|name|version)` + // id/name/version -> not a secret
|
||||||
`|rapid|capital` + // common words containing "api"
|
`|rapid|capital` + // common words containing "api"
|
||||||
`|[a-z0-9-]*?api[a-z0-9-]*?:jar:` + // Maven META-INF dependencies that contain "api" in the name.
|
`|[a-z0-9-]*?api[a-z0-9-]*?:jar:` + // Maven META-INF dependencies that contain "api" in the name.
|
||||||
// Auth
|
// Auth
|
||||||
@@ -64,26 +63,60 @@ func GenericCredential() *config.Rule {
|
|||||||
`|X-MS-Exchange-Organization-Auth` + // email header
|
`|X-MS-Exchange-Organization-Auth` + // email header
|
||||||
`|Authentication-Results` + // email header
|
`|Authentication-Results` + // email header
|
||||||
// Credentials
|
// Credentials
|
||||||
`|(credentials?[_.-]?id|withCredentials)` + // Jenkins plugins
|
`|(?:credentials?[_.-]?id|withCredentials)` + // Jenkins plugins
|
||||||
// Key
|
// Key
|
||||||
`|(bucket|foreign|hot|natural|primary|schema|sequence)[_.-]?key` +
|
`|(?:bucket|foreign|hot|idx|natural|primary|pub(?:lic)?|schema|sequence)[_.-]?key` +
|
||||||
`|key[_.-]?(alias|board|code|ring|selector|size|stone|storetype|word|up|down|left|right)` +
|
`|(?:turkey)` +
|
||||||
`|key(store|tab)[_.-]?(file|path)` +
|
`|key[_.-]?(?:alias|board|code|frame|id|length|mesh|name|pair|press(?:ed)?|ring|selector|signature|size|stone|storetype|word|up|down|left|right)` +
|
||||||
|
// Azure KeyVault
|
||||||
|
`|key[_.-]?vault[_.-]?(?:id|name)|keyVaultToStoreSecrets` +
|
||||||
|
`|key(?:store|tab)[_.-]?(?:file|path)` +
|
||||||
`|issuerkeyhash` + // part of ssl cert
|
`|issuerkeyhash` + // part of ssl cert
|
||||||
`|(?-i:[DdMm]onkey|[DM]ONKEY)|keying` + // common words containing "key"
|
`|(?-i:[DdMm]onkey|[DM]ONKEY)|keying` + // common words containing "key"
|
||||||
// Secret
|
// Secret
|
||||||
`|(secret)[_.-]?name` + // name of e.g. env variable
|
`|(?:secret)[_.-]?(?:length|name|size)` + // name of e.g. env variable
|
||||||
`|UserSecretsId` + // https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-8.0&tabs=linux
|
`|UserSecretsId` + // https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-8.0&tabs=linux
|
||||||
|
|
||||||
// Token
|
// Token
|
||||||
|
`|(?:csrf)[_.-]?token` +
|
||||||
|
`|(?:io\.jsonwebtoken[ \t]?:[ \t]?[\w-]+)` + // Maven library coordinates. (e.g., https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt)
|
||||||
|
|
||||||
// General
|
// General
|
||||||
`|(api|credentials|token)[_.-]?(endpoint|ur[il])` +
|
`|(?:api|credentials|token)[_.-]?(?:endpoint|ur[il])` +
|
||||||
`|public[_.-]?(key|token)` + // public key -> not a secret
|
`|public[_.-]?token` +
|
||||||
`|(key|token)[_.-]?file` +
|
`|(?:key|token)[_.-]?file` +
|
||||||
|
// Empty variables capturing the next line (e.g., .env files)
|
||||||
|
`|(?-i:(?:[A-Z_]+=\n[A-Z_]+=|[a-z_]+=\n[a-z_]+=)(?:\n|\z))` +
|
||||||
|
`|(?-i:(?:[A-Z.]+=\n[A-Z.]+=|[a-z.]+=\n[a-z.]+=)(?:\n|\z))` +
|
||||||
`)`),
|
`)`),
|
||||||
},
|
},
|
||||||
StopWords: DefaultStopWords,
|
StopWords: append(DefaultStopWords,
|
||||||
|
"6fe4476ee5a1832882e326b506d14126", // https://github.com/yarnpkg/berry/issues/6201
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
RegexTarget: "line",
|
||||||
|
Regexes: []*regexp.Regexp{
|
||||||
|
// Docker build secrets (https://docs.docker.com/build/building/secrets/#using-build-secrets).
|
||||||
|
regexp.MustCompile(`--mount=type=secret,`),
|
||||||
|
// https://github.com/gitleaks/gitleaks/issues/1800
|
||||||
|
regexp.MustCompile(`import[ \t]+{[ \t\w,]+}[ \t]+from[ \t]+['"][^'"]+['"]`),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
MatchCondition: config.AllowlistMatchAnd,
|
||||||
|
RegexTarget: "line",
|
||||||
|
Regexes: []*regexp.Regexp{
|
||||||
|
regexp.MustCompile(`LICENSE[^=]*=\s*"[^"]+`),
|
||||||
|
regexp.MustCompile(`LIC_FILES_CHKSUM[^=]*=\s*"[^"]+`),
|
||||||
|
regexp.MustCompile(`SRC[^=]*=\s*"[a-zA-Z0-9]+`),
|
||||||
|
},
|
||||||
|
Paths: []*regexp.Regexp{
|
||||||
|
regexp.MustCompile(`\.bb$`),
|
||||||
|
regexp.MustCompile(`\.bbappend$`),
|
||||||
|
regexp.MustCompile(`\.bbclass$`),
|
||||||
|
regexp.MustCompile(`\.inc$`),
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -99,6 +132,8 @@ func GenericCredential() *config.Rule {
|
|||||||
`some_api_token_123 = "`+newPlausibleSecret(`[a-zA-Z0-9]{60}`)+`"`,
|
`some_api_token_123 = "`+newPlausibleSecret(`[a-zA-Z0-9]{60}`)+`"`,
|
||||||
|
|
||||||
// Auth
|
// Auth
|
||||||
|
`"user_auth": "am9obmRvZTpkMDY5NGIxYi1jMTcxLTQ4ODYt+TMyYS0wMmUwOWQ1/mIwNjc="`,
|
||||||
|
|
||||||
// Credentials
|
// Credentials
|
||||||
`"credentials" : "0afae57f3ccfd9d7f5767067bc48b30f719e271ba470488056e37ab35d4b6506"`,
|
`"credentials" : "0afae57f3ccfd9d7f5767067bc48b30f719e271ba470488056e37ab35d4b6506"`,
|
||||||
`creds = `+newPlausibleSecret(`[a-zA-Z0-9]{30}`),
|
`creds = `+newPlausibleSecret(`[a-zA-Z0-9]{30}`),
|
||||||
@@ -116,13 +151,17 @@ func GenericCredential() *config.Rule {
|
|||||||
`todo_secret_do_not_commit = `+newPlausibleSecret(`[a-zA-Z0-9]{30}`),
|
`todo_secret_do_not_commit = `+newPlausibleSecret(`[a-zA-Z0-9]{30}`),
|
||||||
|
|
||||||
// Token
|
// Token
|
||||||
utils.GenerateSampleSecret("generic", "CLOJARS_34bf0e88955ff5a1c328d6a7491acc4f48e865a7b8dd4d70a70749037443"), //gitleaks:allow
|
` utils.GetEnvOrDefault("api_token", "dafa7817-e246-48f3-91a7-e87653d587b8")`,
|
||||||
utils.GenerateSampleSecret("generic", "Zf3D0LXCM3EIMbgJpUNnkRtOfOueHznB"),
|
// `"env": {
|
||||||
|
//"API_TOKEN": "Lj2^5O%xi214"`,
|
||||||
)
|
)
|
||||||
fps := []string{
|
fps := []string{
|
||||||
// Access
|
// Access
|
||||||
`"accessor":"rA1wk0Y45YCufyfq",`,
|
`"accessor":"rA1wk0Y45YCufyfq",`,
|
||||||
`report_access_id: e8e4df51-2054-49b0-ab1c-516ac95c691d`,
|
`report_access_id: e8e4df51-2054-49b0-ab1c-516ac95c691d`,
|
||||||
|
`accessibilityYesOptionId = "0736f5ef-7e88-499a-80cc-90c85d2a5180"`,
|
||||||
|
`_RandomAccessIterator>
|
||||||
|
_LIBCPP_CONSTEXPR_AFTER_CXX11 `,
|
||||||
|
|
||||||
// API
|
// API
|
||||||
`this.ultraPictureBox1.Name = "ultraPictureBox1";`,
|
`this.ultraPictureBox1.Name = "ultraPictureBox1";`,
|
||||||
@@ -133,6 +172,7 @@ func GenericCredential() *config.Rule {
|
|||||||
`[DEBUG] org.slf4j.slf4j-api:jar:1.7.8.:compile (version managed from default)`,
|
`[DEBUG] org.slf4j.slf4j-api:jar:1.7.8.:compile (version managed from default)`,
|
||||||
`[DEBUG] org.neo4j.neo4j-graphdb-api:jar:3.5.12:test`,
|
`[DEBUG] org.neo4j.neo4j-graphdb-api:jar:3.5.12:test`,
|
||||||
`apiUrl=apigee.corpint.com`,
|
`apiUrl=apigee.corpint.com`,
|
||||||
|
`X-API-Name": "NRG0-Hermes-INTERNAL-API",`,
|
||||||
// TODO: Jetbrains IML files (requires line-level allowlist).
|
// TODO: Jetbrains IML files (requires line-level allowlist).
|
||||||
// `<orderEntry type="library" scope="PROVIDED" name="Maven: org.apache.directory.api:api-asn1-api:1.0.0-M20" level="projcet" />`
|
// `<orderEntry type="library" scope="PROVIDED" name="Maven: org.apache.directory.api:api-asn1-api:1.0.0-M20" level="projcet" />`
|
||||||
|
|
||||||
@@ -154,6 +194,8 @@ func GenericCredential() *config.Rule {
|
|||||||
// Key
|
// Key
|
||||||
`keyword: "Befaehigung_P2"`,
|
`keyword: "Befaehigung_P2"`,
|
||||||
`public_key = "9Cnzj4p4WGeKLs1Pt8QuKUpRKfFLfRYC9AIKjbJTWit"`,
|
`public_key = "9Cnzj4p4WGeKLs1Pt8QuKUpRKfFLfRYC9AIKjbJTWit"`,
|
||||||
|
`pub const X509_pubkey_st = struct_X509_pubkey_st;`,
|
||||||
|
`|| pIdxKey->default_rc==0`,
|
||||||
`monkeys-audio:mx64-uwp=fail`,
|
`monkeys-audio:mx64-uwp=fail`,
|
||||||
`primaryKey=` + newPlausibleSecret(`[a-zA-Z0-9\-_.=]{30}`),
|
`primaryKey=` + newPlausibleSecret(`[a-zA-Z0-9\-_.=]{30}`),
|
||||||
`foreignKey=` + newPlausibleSecret(`[a-zA-Z0-9\-_.=]{30}`),
|
`foreignKey=` + newPlausibleSecret(`[a-zA-Z0-9\-_.=]{30}`),
|
||||||
@@ -163,7 +205,6 @@ func GenericCredential() *config.Rule {
|
|||||||
`minisat-master-keying:x64-uwp=fail`,
|
`minisat-master-keying:x64-uwp=fail`,
|
||||||
`IceSSL.KeyFile=s_rsa1024_priv.pem`,
|
`IceSSL.KeyFile=s_rsa1024_priv.pem`,
|
||||||
`"bucket_key": "SalesResults-1.2"`,
|
`"bucket_key": "SalesResults-1.2"`,
|
||||||
// `<TAR key="REF_ID_923.properties" value="/opts/config/alias/"/>`,
|
|
||||||
`<key tag="SecurityIdentifier" name="SecurityIdentifier" type="STRING" />`,
|
`<key tag="SecurityIdentifier" name="SecurityIdentifier" type="STRING" />`,
|
||||||
// `packageKey":` + newPlausibleSecret(`[a-zA-Z0-9\-_.=]{30}`),
|
// `packageKey":` + newPlausibleSecret(`[a-zA-Z0-9\-_.=]{30}`),
|
||||||
`schemaKey = 'DOC_Vector_5_32'`,
|
`schemaKey = 'DOC_Vector_5_32'`,
|
||||||
@@ -173,7 +214,25 @@ func GenericCredential() *config.Rule {
|
|||||||
` doc.Security.KeySize = PdfEncryptionKeySize.Key128Bit;`,
|
` doc.Security.KeySize = PdfEncryptionKeySize.Key128Bit;`,
|
||||||
`o.keySelector=n,o.haKey=!1,`,
|
`o.keySelector=n,o.haKey=!1,`,
|
||||||
// TODO: Requires line-level allowlists.
|
// TODO: Requires line-level allowlists.
|
||||||
|
` "key_name": "prod5zyxlmy-cmk",`,
|
||||||
|
` "kms_key_id": "555ea4a3-d53a-4412-9c66-3a7cb667b0d6",`,
|
||||||
|
` "key_vault_name": "web21prqodx24021",`,
|
||||||
|
` keyVaultToStoreSecrets: cmp2-qat-1208358310`, // e.g., https://github.com/2uasimojo/community-operators-prod/blob/9e51e4c8e0b5caaa3087e8e18e6fb918b2c36643/operators/azure-service-operator/1.0.59040/manifests/azure.microsoft.com_cosmosdbs.yaml#L50
|
||||||
|
`,apiKey:"6fe4476ee5a1832882e326b506d14126",`,
|
||||||
|
`const validKeyChars = "0123456789abcdefghijklmnopqrstuvwxyz_-."`,
|
||||||
|
`const keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"`,
|
||||||
|
`key_length = XSalsa20.key_length`,
|
||||||
|
`pub const SN_id_Gost28147_89_None_KeyMeshing = "id-Gost28147-89-None-KeyMeshing"`,
|
||||||
|
`KeyPair = X25519.KeyPair`,
|
||||||
|
`BlindKeySignatures = Ed25519.BlindKeySignatures`,
|
||||||
|
`AVEncVideoMaxKeyframeDistance, "2987123a-ba93-4704-b489-ec1e5f25292c"`,
|
||||||
|
` keyPressed = kVK_Return.u16`,
|
||||||
|
`timezone_mapping = {
|
||||||
|
"Turkey Standard Time": "Europe/Istanbul",
|
||||||
|
}`, // https://github.com/gitleaks/gitleaks/issues/1799
|
||||||
// `<add key="SchemaTable" value="G:\SchemaTable.xml" />`,
|
// `<add key="SchemaTable" value="G:\SchemaTable.xml" />`,
|
||||||
|
//` { key: '9df21e95-3848-409d-8f94-c675cdfee839', value: 'Americas' },`,
|
||||||
|
// `<TAR key="REF_ID_923.properties" value="/opts/config/alias/"/>`,
|
||||||
// `secret:
|
// `secret:
|
||||||
// secretName: app-decryption-secret
|
// secretName: app-decryption-secret
|
||||||
// items:
|
// items:
|
||||||
@@ -181,7 +240,7 @@ func GenericCredential() *config.Rule {
|
|||||||
// path: app-k8s.yml`,
|
// path: app-k8s.yml`,
|
||||||
|
|
||||||
// TODO: https://learn.microsoft.com/en-us/windows/apps/design/style/xaml-theme-resources
|
// TODO: https://learn.microsoft.com/en-us/windows/apps/design/style/xaml-theme-resources
|
||||||
// `<Color x:Key="NormalBrushGradient1">#FFBAE4FF</Color>`,
|
//`<Color x:Key="NormalBrushGradient1">#FFBAE4FF</Color>`,
|
||||||
|
|
||||||
// Password
|
// Password
|
||||||
`password combination.
|
`password combination.
|
||||||
@@ -192,21 +251,37 @@ R5: Regulatory--21`,
|
|||||||
// Secret
|
// Secret
|
||||||
`LLM_SECRET_NAME = "NEXUS-GPT4-API-KEY"`,
|
`LLM_SECRET_NAME = "NEXUS-GPT4-API-KEY"`,
|
||||||
` <UserSecretsId>79a3edd0-2092-40a2-a04d-dcb46d5ca9ed</UserSecretsId>`,
|
` <UserSecretsId>79a3edd0-2092-40a2-a04d-dcb46d5ca9ed</UserSecretsId>`,
|
||||||
|
`secret_length = X25519.secret_length`,
|
||||||
|
`secretSize must be >= XXH3_SECRET_SIZE_MIN`,
|
||||||
|
`# get build time secret for authentication
|
||||||
|
#RUN --mount=type=secret,id=jfrog_secret \
|
||||||
|
# JFROG_SECRET = $(cat /run/secrets/jfrog_secret) && \`,
|
||||||
|
|
||||||
// Token
|
// Token
|
||||||
` access_token_url='https://github.com/login/oauth/access_token',`,
|
` access_token_url='https://github.com/login/oauth/access_token',`,
|
||||||
`publicToken = "9Cnzj4p4WGeKLs1Pt8QuKUpRKfFLfRYC9AIKjbJTWit"`,
|
`publicToken = "9Cnzj4p4WGeKLs1Pt8QuKUpRKfFLfRYC9AIKjbJTWit"`,
|
||||||
`<SourceFile SourceLocation="F:\Extracts\" TokenFile="RTL_INST_CODE.cer">`,
|
`<SourceFile SourceLocation="F:\Extracts\" TokenFile="RTL_INST_CODE.cer">`,
|
||||||
|
`notes = "Maven - io.jsonwebtoken:jjwt-jackson-0.11.2"`,
|
||||||
|
`csrf-token=Mj2qykJO5rELyHgezQ69nzUX0i3OH67V7+V4eUrLfpuyOuxmiW9rhROG/Whikle15syazJOkrjJa3U2AbhIvUw==`,
|
||||||
// TODO: `TOKEN_AUDIENCE = "25872395-ed3a-4703-b647-22ec53f3683c"`,
|
// TODO: `TOKEN_AUDIENCE = "25872395-ed3a-4703-b647-22ec53f3683c"`,
|
||||||
|
|
||||||
// General
|
// General
|
||||||
`clientId = "73082700-1f09-405b-80d0-3131bfd6272d"`,
|
`clientId = "73082700-1f09-405b-80d0-3131bfd6272d"`,
|
||||||
|
`GITHUB_API_KEY=
|
||||||
|
DYNATRACE_API_KEY=`,
|
||||||
|
`snowflake.password=
|
||||||
|
jdbc.snowflake.url=`,
|
||||||
|
`import { chain_Anvil1_Key, chain_Anvil2_Key } from '../blockchain-tests/pallets/supported-chains/consts';`,
|
||||||
|
|
||||||
|
// Yocto/BitBake
|
||||||
|
`SRCREV_moby = "43fc912ef59a83054ea7f6706df4d53a7dea4d80"`,
|
||||||
|
`LIC_FILES_CHKSUM = "file://${WORKDIR}/license.html;md5=5c94767cedb5d6987c902ac850ded2c6"`,
|
||||||
}
|
}
|
||||||
return utils.Validate(r, tps, fps)
|
return utils.Validate(r, tps, fps)
|
||||||
}
|
}
|
||||||
|
|
||||||
func newPlausibleSecret(regex string) string {
|
func newPlausibleSecret(regex string) string {
|
||||||
allowList := config.Allowlist{StopWords: DefaultStopWords}
|
allowList := &config.Allowlist{StopWords: DefaultStopWords}
|
||||||
// attempt to generate a random secret,
|
// attempt to generate a random secret,
|
||||||
// retrying until it contains at least one digit and no stop words
|
// retrying until it contains at least one digit and no stop words
|
||||||
// TODO: currently the DefaultStopWords list contains many short words,
|
// TODO: currently the DefaultStopWords list contains many short words,
|
||||||
@@ -216,7 +291,7 @@ func newPlausibleSecret(regex string) string {
|
|||||||
if !regexp.MustCompile(`[1-9]`).MatchString(secret) {
|
if !regexp.MustCompile(`[1-9]`).MatchString(secret) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if allowList.ContainsStopWord(secret) {
|
if ok, _ := allowList.ContainsStopWord(secret); ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
return secret
|
return secret
|
||||||
|
|||||||
@@ -1,19 +1,17 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
var githubAllowlist = []config.Allowlist{
|
var githubAllowlist = []*config.Allowlist{
|
||||||
{
|
{
|
||||||
Paths: []*regexp.Regexp{
|
Paths: []*regexp.Regexp{
|
||||||
// https://github.com/octokit/auth-token.js/?tab=readme-ov-file#createtokenauthtoken-options
|
// https://github.com/octokit/auth-token.js/?tab=readme-ov-file#createtokenauthtoken-options
|
||||||
regexp.MustCompile(`(^|/)@octokit/auth-token/README\.md$`),
|
regexp.MustCompile(`(?:^|/)@octokit/auth-token/README\.md$`),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
// overview with all GitLab tokens:
|
// overview with all GitLab tokens:
|
||||||
@@ -179,6 +177,23 @@ func GitlabRunnerAuthenticationToken() *config.Rule {
|
|||||||
return utils.Validate(r, tps, nil)
|
return utils.Validate(r, tps, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func GitlabRunnerAuthenticationTokenRoutable() *config.Rule {
|
||||||
|
r := config.Rule{
|
||||||
|
RuleID: "gitlab-runner-authentication-token-routable",
|
||||||
|
Description: "Discovered a GitLab Runner Authentication Token (Routable), posing a risk to CI/CD pipeline integrity and unauthorized access.",
|
||||||
|
Regex: regexp.MustCompile(`\bglrt-t\d_[0-9a-zA-Z_\-]{27,300}\.[0-9a-z]{2}[0-9a-z]{7}\b`),
|
||||||
|
Entropy: 4,
|
||||||
|
Keywords: []string{"glrt-"},
|
||||||
|
}
|
||||||
|
|
||||||
|
tps := utils.GenerateSampleSecrets("gitlab", "glrt-t"+secrets.NewSecret(utils.Numeric("1"))+"_"+secrets.NewSecret(utils.AlphaNumeric("27"))+"."+secrets.NewSecret(utils.AlphaNumeric("2"))+secrets.NewSecret(utils.AlphaNumeric("7")))
|
||||||
|
fps := []string{
|
||||||
|
"glrt-tx_xxxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxx",
|
||||||
|
}
|
||||||
|
|
||||||
|
return utils.Validate(r, tps, fps)
|
||||||
|
}
|
||||||
|
|
||||||
func GitlabScimToken() *config.Rule {
|
func GitlabScimToken() *config.Rule {
|
||||||
r := config.Rule{
|
r := config.Rule{
|
||||||
RuleID: "gitlab-scim-token",
|
RuleID: "gitlab-scim-token",
|
||||||
|
|||||||
@@ -1,13 +1,10 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func HarnessApiKey() *config.Rule {
|
func HarnessApiKey() *config.Rule {
|
||||||
|
|||||||
@@ -3,12 +3,10 @@ package rules
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func HashiCorpTerraform() *config.Rule {
|
func HashiCorpTerraform() *config.Rule {
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func VaultServiceToken() *config.Rule {
|
func VaultServiceToken() *config.Rule {
|
||||||
@@ -17,7 +15,7 @@ func VaultServiceToken() *config.Rule {
|
|||||||
Regex: utils.GenerateUniqueTokenRegex(`(?:hvs\.[\w-]{90,120}|s\.(?i:[a-z0-9]{24}))`, false),
|
Regex: utils.GenerateUniqueTokenRegex(`(?:hvs\.[\w-]{90,120}|s\.(?i:[a-z0-9]{24}))`, false),
|
||||||
Entropy: 3.5,
|
Entropy: 3.5,
|
||||||
Keywords: []string{"hvs.", "s."},
|
Keywords: []string{"hvs.", "s."},
|
||||||
Allowlists: []config.Allowlist{
|
Allowlists: []*config.Allowlist{
|
||||||
{
|
{
|
||||||
Regexes: []*regexp.Regexp{
|
Regexes: []*regexp.Regexp{
|
||||||
// https://github.com/gitleaks/gitleaks/issues/1490#issuecomment-2334166357
|
// https://github.com/gitleaks/gitleaks/issues/1490#issuecomment-2334166357
|
||||||
|
|||||||
@@ -24,3 +24,22 @@ func Heroku() *config.Rule {
|
|||||||
)
|
)
|
||||||
return utils.Validate(r, tps, nil)
|
return utils.Validate(r, tps, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func HerokuV2() *config.Rule {
|
||||||
|
// define rule
|
||||||
|
r := config.Rule{
|
||||||
|
Description: "Detected a Heroku API Key, potentially compromising cloud application deployments and operational security.",
|
||||||
|
RuleID: "heroku-api-key-v2",
|
||||||
|
Regex: utils.GenerateUniqueTokenRegex(`(HRKU-AA[0-9a-zA-Z_-]{58})`, false),
|
||||||
|
Entropy: 4,
|
||||||
|
Keywords: []string{"HRKU-AA"},
|
||||||
|
}
|
||||||
|
|
||||||
|
// validate
|
||||||
|
tps := utils.GenerateSampleSecrets("heroku", secrets.NewSecret(`\b(HRKU-AA[0-9a-zA-Z_-]{58})\b`))
|
||||||
|
tps = append(tps,
|
||||||
|
`const KEY = "HRKU-AAlQ1aVoHDujJ9QsDHdHlHO0hbzhoERRSO45ZQusSYHg_____w4_hLrAym_u""`,
|
||||||
|
`API_Key = "HRKU-AAy9Ppr_HD2pPuTyIiTYInO0hbzhoERRSO93ZQusSYHgaD7_WQ07FnF7L9FX"`,
|
||||||
|
)
|
||||||
|
return utils.Validate(r, tps, nil)
|
||||||
|
}
|
||||||
@@ -4,10 +4,10 @@ import (
|
|||||||
b64 "encoding/base64"
|
b64 "encoding/base64"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func JWT() *config.Rule {
|
func JWT() *config.Rule {
|
||||||
|
|||||||
@@ -3,11 +3,9 @@ package rules
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
// KubernetesSecret validates if we detected a kubernetes secret which contains data!
|
// KubernetesSecret validates if we detected a kubernetes secret which contains data!
|
||||||
@@ -19,7 +17,7 @@ func KubernetesSecret() *config.Rule {
|
|||||||
// - valid base64 characters
|
// - valid base64 characters
|
||||||
// - longer than 10 characters (no "YmFyCg==")
|
// - longer than 10 characters (no "YmFyCg==")
|
||||||
//language=regexp
|
//language=regexp
|
||||||
dataPat := `\bdata:(?:.|\s){0,100}?\s+([\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:["']?[a-z0-9+/]{10,}={0,3}["']?|\{\{[ \t\w"|$:=,.-]+}}|""|''))`
|
dataPat := `\bdata:(?s:.){0,100}?\s+([\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:["']?[a-z0-9+/]{10,}={0,3}["']?|\{\{[ \t\w"|$:=,.-]+}}|""|''))`
|
||||||
|
|
||||||
// define rule
|
// define rule
|
||||||
r := config.Rule{
|
r := config.Rule{
|
||||||
@@ -27,13 +25,13 @@ func KubernetesSecret() *config.Rule {
|
|||||||
Description: "Possible Kubernetes Secret detected, posing a risk of leaking credentials/tokens from your deployments",
|
Description: "Possible Kubernetes Secret detected, posing a risk of leaking credentials/tokens from your deployments",
|
||||||
Regex: regexp.MustCompile(fmt.Sprintf(
|
Regex: regexp.MustCompile(fmt.Sprintf(
|
||||||
//language=regexp
|
//language=regexp
|
||||||
`(?i)(?:%s(?:.|\s){0,200}?%s|%s(?:.|\s){0,200}?%s)`, kindPat, dataPat, dataPat, kindPat)),
|
`(?i)(?:%s(?s:.){0,200}?%s|%s(?s:.){0,200}?%s)`, kindPat, dataPat, dataPat, kindPat)),
|
||||||
Keywords: []string{
|
Keywords: []string{
|
||||||
"secret",
|
"secret",
|
||||||
},
|
},
|
||||||
// Kubernetes secrets are usually yaml files.
|
// Kubernetes secrets are usually yaml files.
|
||||||
Path: regexp.MustCompile(`(?i)\.ya?ml$`),
|
Path: regexp.MustCompile(`(?i)\.ya?ml$`),
|
||||||
Allowlists: []config.Allowlist{
|
Allowlists: []*config.Allowlist{
|
||||||
{
|
{
|
||||||
Regexes: []*regexp.Regexp{
|
Regexes: []*regexp.Regexp{
|
||||||
// Ignore empty or placeholder values.
|
// Ignore empty or placeholder values.
|
||||||
@@ -47,7 +45,7 @@ func KubernetesSecret() *config.Rule {
|
|||||||
// Avoid overreach between directives.
|
// Avoid overreach between directives.
|
||||||
RegexTarget: "match",
|
RegexTarget: "match",
|
||||||
Regexes: []*regexp.Regexp{
|
Regexes: []*regexp.Regexp{
|
||||||
regexp.MustCompile(`(kind:(.|\s)+\n---\n(.|\s)+\bdata:|data:(.|\s)+\n---\n(.|\s)+\bkind:)`),
|
regexp.MustCompile(`(kind:(?s:.)+\n---\n(?s:.)+\bdata:|data:(?s:.)+\n---\n(?s:.)+\bkind:)`),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func LinearAPIToken() *config.Rule {
|
func LinearAPIToken() *config.Rule {
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package rules
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
func MaxMindLicenseKey() *config.Rule {
|
||||||
|
// define rule
|
||||||
|
r := config.Rule{
|
||||||
|
RuleID: "maxmind-license-key",
|
||||||
|
Description: "Discovered a potential MaxMind license key.",
|
||||||
|
Regex: utils.GenerateUniqueTokenRegex(`[A-Za-z0-9]{6}_[A-Za-z0-9]{29}_mmk`, false),
|
||||||
|
Entropy: 4,
|
||||||
|
Keywords: []string{"_mmk"},
|
||||||
|
}
|
||||||
|
|
||||||
|
// validate
|
||||||
|
tps := utils.GenerateSampleSecrets("maxmind", `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`) // gitleaks:allow
|
||||||
|
return utils.Validate(r, tps, nil)
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
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 Meraki() *config.Rule {
|
||||||
|
// define rule
|
||||||
|
r := config.Rule{
|
||||||
|
RuleID: "cisco-meraki-api-key",
|
||||||
|
Description: "Cisco Meraki is a cloud-managed IT solution that provides networking, security, and device management through an easy-to-use interface.",
|
||||||
|
Regex: utils.GenerateSemiGenericRegex([]string{`(?-i:[Mm]eraki|MERAKI)`}, `[0-9a-f]{40}`, false),
|
||||||
|
Entropy: 3,
|
||||||
|
Keywords: []string{"meraki"},
|
||||||
|
}
|
||||||
|
|
||||||
|
// validate
|
||||||
|
tps := utils.GenerateSampleSecrets("meraki", secrets.NewSecret(utils.Hex("40")))
|
||||||
|
fps := []string{
|
||||||
|
`meraki: aaaaaaaaaa1111111111bbbbbbbbbb2222222222`, // low entropy
|
||||||
|
`meraki-api-key: acdeFf05b1a6d4c890237bf08c5e6e8d2b4d0f2e`, // invalid case
|
||||||
|
`meraki: abdefghjk0123456789mnopqrstuvwx12345678`, // invalid character
|
||||||
|
`meraki_token = 5cb4a5f04cd412fe946667b17f0129ba17aeb2e0c7b5b7264efcebf7d022bfe2R21`, // invalid length
|
||||||
|
`ReactNativeCameraKit: f15a5a04b0f6dc6073e6db0296e6ef2d8b8d2522`,
|
||||||
|
}
|
||||||
|
return utils.Validate(r, tps, fps)
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package rules
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Notion() *config.Rule {
|
||||||
|
// Define the identifiers that match the Keywords
|
||||||
|
identifiers := []string{"ntn_"}
|
||||||
|
|
||||||
|
// Define the regex pattern for Notion API token
|
||||||
|
secretRegex := `ntn_[0-9]{11}[A-Za-z0-9]{32}[A-Za-z0-9]{3}`
|
||||||
|
|
||||||
|
regex := utils.GenerateUniqueTokenRegex(secretRegex, false)
|
||||||
|
|
||||||
|
r := config.Rule{
|
||||||
|
Description: "Notion API token",
|
||||||
|
RuleID: "notion-api-token",
|
||||||
|
Regex: regex,
|
||||||
|
Entropy: 4,
|
||||||
|
Keywords: identifiers,
|
||||||
|
}
|
||||||
|
|
||||||
|
// validate
|
||||||
|
tps := []string{
|
||||||
|
"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",
|
||||||
|
"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",
|
||||||
|
"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",
|
||||||
|
}
|
||||||
|
|
||||||
|
fps := []string{
|
||||||
|
"ntn_12345678901",
|
||||||
|
"ntn_123456789012345678901234567890123456789012345678901234567890",
|
||||||
|
"ntn_12345678901abc",
|
||||||
|
}
|
||||||
|
|
||||||
|
return utils.Validate(r, tps, fps)
|
||||||
|
}
|
||||||
@@ -1,11 +1,9 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func NugetConfigPassword() *config.Rule {
|
func NugetConfigPassword() *config.Rule {
|
||||||
@@ -16,7 +14,7 @@ func NugetConfigPassword() *config.Rule {
|
|||||||
Path: regexp.MustCompile(`(?i)nuget\.config$`),
|
Path: regexp.MustCompile(`(?i)nuget\.config$`),
|
||||||
Keywords: []string{"<add key="},
|
Keywords: []string{"<add key="},
|
||||||
Entropy: 1,
|
Entropy: 1,
|
||||||
Allowlists: []config.Allowlist{
|
Allowlists: []*config.Allowlist{
|
||||||
{
|
{
|
||||||
Regexes: []*regexp.Regexp{
|
Regexes: []*regexp.Regexp{
|
||||||
// samples from https://learn.microsoft.com/en-us/nuget/reference/nuget-config-file
|
// samples from https://learn.microsoft.com/en-us/nuget/reference/nuget-config-file
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ func OpenAI() *config.Rule {
|
|||||||
r := config.Rule{
|
r := config.Rule{
|
||||||
RuleID: "openai-api-key",
|
RuleID: "openai-api-key",
|
||||||
Description: "Found an OpenAI API Key, posing a risk of unauthorized access to AI services and data manipulation.",
|
Description: "Found an OpenAI API Key, posing a risk of unauthorized access to AI services and data manipulation.",
|
||||||
Regex: utils.GenerateUniqueTokenRegex(`sk-[a-zA-Z0-9]{20}T3BlbkFJ[a-zA-Z0-9]{20}`, false),
|
Regex: utils.GenerateUniqueTokenRegex(`sk-(?:proj|svcacct|admin)-(?:[A-Za-z0-9_-]{74}|[A-Za-z0-9_-]{58})T3BlbkFJ(?:[A-Za-z0-9_-]{74}|[A-Za-z0-9_-]{58})\b|sk-[a-zA-Z0-9]{20}T3BlbkFJ[a-zA-Z0-9]{20}`, false),
|
||||||
Entropy: 3,
|
Entropy: 3,
|
||||||
Keywords: []string{
|
Keywords: []string{
|
||||||
"T3BlbkFJ",
|
"T3BlbkFJ",
|
||||||
@@ -19,6 +19,19 @@ func OpenAI() *config.Rule {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// validate
|
// validate
|
||||||
tps := utils.GenerateSampleSecrets("openaiApiKey", "sk-"+secrets.NewSecret(utils.AlphaNumeric("20"))+"T3BlbkFJ"+secrets.NewSecret(utils.AlphaNumeric("20")))
|
tps := append(utils.GenerateSampleSecrets("openaiApiKey", "sk-"+secrets.NewSecret(utils.AlphaNumeric("20"))+"T3BlbkFJ"+secrets.NewSecret(utils.AlphaNumeric("20"))),
|
||||||
|
[]string{
|
||||||
|
"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",
|
||||||
|
"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",
|
||||||
|
"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",
|
||||||
|
|
||||||
|
"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",
|
||||||
|
"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",
|
||||||
|
"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",
|
||||||
|
|
||||||
|
"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",
|
||||||
|
"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",
|
||||||
|
"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",
|
||||||
|
}...)
|
||||||
return utils.Validate(r, tps, nil)
|
return utils.Validate(r, tps, nil)
|
||||||
}
|
}
|
||||||
@@ -1,12 +1,10 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
// OpenShift 4 user tokens are prefixed with `sha256~`.
|
// OpenShift 4 user tokens are prefixed with `sha256~`.
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package rules
|
||||||
|
|
||||||
|
import (
|
||||||
|
"regexp"
|
||||||
|
|
||||||
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
|
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
func PerplexityAPIKey() *config.Rule {
|
||||||
|
// Define Rule
|
||||||
|
r := config.Rule{
|
||||||
|
RuleID: "perplexity-api-key",
|
||||||
|
Description: "Detected a Perplexity API key, which could lead to unauthorized access to Perplexity AI services and data exposure.",
|
||||||
|
Regex: regexp.MustCompile(`\b(pplx-[a-zA-Z0-9]{48})(?:[\x60'"\s;]|\\[nr]|$|\b)`),
|
||||||
|
Keywords: []string{"pplx-"},
|
||||||
|
Entropy: 4.0,
|
||||||
|
}
|
||||||
|
|
||||||
|
// validate
|
||||||
|
tps := utils.GenerateSampleSecrets("perplexity", "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'")
|
||||||
|
fps := []string{
|
||||||
|
"PERPLEXITY_API_KEY=pplx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
|
||||||
|
}
|
||||||
|
return utils.Validate(r, tps, fps)
|
||||||
|
}
|
||||||
@@ -1,8 +1,6 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
@@ -50,7 +48,7 @@ func PlaidAccessToken() *config.Rule {
|
|||||||
RuleID: "plaid-api-token",
|
RuleID: "plaid-api-token",
|
||||||
Description: "Discovered a Plaid API Token, potentially compromising financial data aggregation and banking services.",
|
Description: "Discovered a Plaid API Token, potentially compromising financial data aggregation and banking services.",
|
||||||
Regex: utils.GenerateSemiGenericRegex([]string{"plaid"},
|
Regex: utils.GenerateSemiGenericRegex([]string{"plaid"},
|
||||||
fmt.Sprintf("access-(?:sandbox|development|production)-%s", utils.Hex8_4_4_4_12()), true),
|
"access-(?:sandbox|development|production)-"+utils.Hex8_4_4_4_12(), true),
|
||||||
|
|
||||||
Keywords: []string{
|
Keywords: []string{
|
||||||
"plaid",
|
"plaid",
|
||||||
@@ -58,6 +56,6 @@ func PlaidAccessToken() *config.Rule {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// validate
|
// validate
|
||||||
tps := utils.GenerateSampleSecrets("plaid", secrets.NewSecret(fmt.Sprintf("access-(?:sandbox|development|production)-%s", utils.Hex8_4_4_4_12())))
|
tps := utils.GenerateSampleSecrets("plaid", secrets.NewSecret("access-(?:sandbox|development|production)-"+utils.Hex8_4_4_4_12()))
|
||||||
return utils.Validate(r, tps, nil)
|
return utils.Validate(r, tps, nil)
|
||||||
}
|
}
|
||||||
@@ -1,32 +1,61 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func PrivateKey() *config.Rule {
|
func PrivateKey() *config.Rule {
|
||||||
// define rule
|
// define rule
|
||||||
r := config.Rule{
|
r := config.Rule{
|
||||||
Description: "Identified a Private Key, which may compromise cryptographic security and sensitive data encryption.",
|
|
||||||
RuleID: "private-key",
|
RuleID: "private-key",
|
||||||
Regex: regexp.MustCompile(`(?i)-----BEGIN[ A-Z0-9_-]{0,100}PRIVATE KEY(?: BLOCK)?-----[\s\S-]*?KEY(?: BLOCK)?-----`),
|
Description: "Identified a Private Key, which may compromise cryptographic security and sensitive data encryption.",
|
||||||
|
Regex: regexp.MustCompile(`(?i)-----BEGIN[ A-Z0-9_-]{0,100}PRIVATE KEY(?: BLOCK)?-----[\s\S-]{64,}?KEY(?: BLOCK)?-----`),
|
||||||
Keywords: []string{"-----BEGIN"},
|
Keywords: []string{"-----BEGIN"},
|
||||||
}
|
}
|
||||||
|
|
||||||
// validate
|
// validate
|
||||||
tps := []string{`-----BEGIN PRIVATE KEY-----
|
tps := []string{`-----BEGIN PRIVATE KEY-----
|
||||||
anything
|
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDAC4AWkdwKYSd8
|
||||||
|
Ks14IReLcYgADhoXk56ZzXI=
|
||||||
-----END PRIVATE KEY-----`,
|
-----END PRIVATE KEY-----`,
|
||||||
`-----BEGIN RSA PRIVATE KEY-----
|
`-----BEGIN RSA PRIVATE KEY-----
|
||||||
abcdefghijklmnopqrstuvwxyz
|
MIIEpQIBAAKCAQEAn6/O8li+SX4m98LLYt/PKSzEmQ++ZBD7Loh9P13f4yQ92EF3
|
||||||
|
yxR5MsXFu9PRsrYQA7/4UTPHiC4y2sAVCBg4C2yyBpUEtMQjyCESi6Y=
|
||||||
-----END RSA PRIVATE KEY-----
|
-----END RSA PRIVATE KEY-----
|
||||||
`,
|
`,
|
||||||
`-----BEGIN PRIVATE KEY BLOCK-----
|
`-----BEGIN PGP PRIVATE KEY BLOCK-----
|
||||||
anything
|
lQWGBGSVV4YBDAClvRnxezIRy2Yv7SFlzC0iFiRF/O/jePSw+XYhvcrTaqSYTGic
|
||||||
-----END PRIVATE KEY BLOCK-----`,
|
=8xQN
|
||||||
|
-----END PGP PRIVATE KEY BLOCK-----`,
|
||||||
} // gitleaks:allow
|
} // gitleaks:allow
|
||||||
return utils.Validate(r, tps, nil)
|
fps := []string{
|
||||||
|
`-----BEGIN PRIVATE KEY-----
|
||||||
|
anything
|
||||||
|
-----END PRIVATE KEY-----`,
|
||||||
|
`-----BEGIN OPENSSH PRIVATE KEY----------END OPENSSH PRIVATE KEY-----`,
|
||||||
|
}
|
||||||
|
return utils.Validate(r, tps, fps)
|
||||||
|
}
|
||||||
|
|
||||||
|
func PrivateKeyPKCS12File() *config.Rule {
|
||||||
|
// https://en.wikipedia.org/wiki/PKCS_12
|
||||||
|
r := config.Rule{
|
||||||
|
RuleID: "pkcs12-file",
|
||||||
|
Description: "Found a PKCS #12 file, which commonly contain bundled private keys.",
|
||||||
|
Path: regexp.MustCompile(`(?i)(?:^|\/)[^\/]+\.p(?:12|fx)$`),
|
||||||
|
}
|
||||||
|
|
||||||
|
// validate
|
||||||
|
tps := map[string]string{
|
||||||
|
"security/es_certificates/opensearch/es_kibana_client.p12": "",
|
||||||
|
"cagw_key.P12": "",
|
||||||
|
"ToDo/ToDo.UWP/ToDo.UWP_TemporaryKey.pfx": "",
|
||||||
|
}
|
||||||
|
fps := map[string]string{
|
||||||
|
"doc/typenum/type.P126.html": "",
|
||||||
|
"scripts/keeneland/syntest.p1200.sh": "",
|
||||||
|
}
|
||||||
|
return utils.ValidateWithPaths(r, tps, fps)
|
||||||
}
|
}
|
||||||
@@ -1,12 +1,10 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func PyPiUploadToken() *config.Rule {
|
func PyPiUploadToken() *config.Rule {
|
||||||
|
|||||||
@@ -2,11 +2,11 @@ package rules
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func SentryAccessToken() *config.Rule {
|
func SentryAccessToken() *config.Rule {
|
||||||
@@ -43,7 +43,7 @@ func SentryOrgToken() *config.Rule {
|
|||||||
r := config.Rule{
|
r := config.Rule{
|
||||||
RuleID: "sentry-org-token",
|
RuleID: "sentry-org-token",
|
||||||
Description: "Found a Sentry.io Organization Token, risking unauthorized access to error tracking services and sensitive application data.",
|
Description: "Found a Sentry.io Organization Token, risking unauthorized access to error tracking services and sensitive application data.",
|
||||||
Regex: regexp.MustCompile(`\bsntrys_eyJpYXQiO[a-zA-Z0-9+/]{10,200}(?:LCJyZWdpb25fdXJs|InJlZ2lvbl91cmwi|cmVnaW9uX3VybCI6)[a-zA-Z0-9+/]{10,200}={0,2}_[a-zA-Z0-9+/]{43}\b`),
|
Regex: regexp.MustCompile(`\bsntrys_eyJpYXQiO[a-zA-Z0-9+/]{10,200}(?:LCJyZWdpb25fdXJs|InJlZ2lvbl91cmwi|cmVnaW9uX3VybCI6)[a-zA-Z0-9+/]{10,200}={0,2}_[a-zA-Z0-9+/]{43}(?:[^a-zA-Z0-9+/]|\z)`),
|
||||||
Entropy: 4.5,
|
Entropy: 4.5,
|
||||||
Keywords: []string{"sntrys_eyJpYXQiO"},
|
Keywords: []string{"sntrys_eyJpYXQiO"},
|
||||||
}
|
}
|
||||||
@@ -52,6 +52,9 @@ func SentryOrgToken() *config.Rule {
|
|||||||
tps := utils.GenerateSampleSecrets("sentry",
|
tps := utils.GenerateSampleSecrets("sentry",
|
||||||
`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`, // gitleaks:allow
|
`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`, // gitleaks:allow
|
||||||
)
|
)
|
||||||
|
tps = append(tps, utils.GenerateSampleSecrets("sentry",
|
||||||
|
`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`, // gitleaks:allow
|
||||||
|
)...)
|
||||||
tps = append(tps,
|
tps = append(tps,
|
||||||
` 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`, // gitleaks:allow
|
` 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`, // gitleaks:allow
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func ShopifySharedSecret() *config.Rule {
|
func ShopifySharedSecret() *config.Rule {
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func SidekiqSecret() *config.Rule {
|
func SidekiqSecret() *config.Rule {
|
||||||
|
|||||||
@@ -2,12 +2,11 @@ package rules
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
// https://api.slack.com/authentication/token-types#bot
|
// https://api.slack.com/authentication/token-types#bot
|
||||||
@@ -273,7 +272,7 @@ func SlackWebHookUrl() *config.Rule {
|
|||||||
Description: "Discovered a Slack Webhook, which could lead to unauthorized message posting and data leakage in Slack channels.",
|
Description: "Discovered a Slack Webhook, which could lead to unauthorized message posting and data leakage in Slack channels.",
|
||||||
// If this generates too many false-positives we should define an allowlist (e.g., "xxxx", "00000").
|
// If this generates too many false-positives we should define an allowlist (e.g., "xxxx", "00000").
|
||||||
Regex: regexp.MustCompile(
|
Regex: regexp.MustCompile(
|
||||||
`(?:https?://)?hooks.slack.com/(?:services|workflows)/[A-Za-z0-9+/]{43,46}`),
|
`(?:https?://)?hooks.slack.com/(?:services|workflows|triggers)/[A-Za-z0-9+/]{43,56}`),
|
||||||
Keywords: []string{
|
Keywords: []string{
|
||||||
"hooks.slack.com",
|
"hooks.slack.com",
|
||||||
},
|
},
|
||||||
@@ -291,6 +290,7 @@ func SlackWebHookUrl() *config.Rule {
|
|||||||
"https://hooks.slack.com/workflows/" + secrets.NewSecret(utils.AlphaNumeric("46")),
|
"https://hooks.slack.com/workflows/" + secrets.NewSecret(utils.AlphaNumeric("46")),
|
||||||
"https://hooks.slack.com/workflows/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", // gitleaks:allow
|
"https://hooks.slack.com/workflows/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", // gitleaks:allow
|
||||||
"http://hooks.slack.com/workflows/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", // gitleaks:allow
|
"http://hooks.slack.com/workflows/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", // gitleaks:allow
|
||||||
|
"https://hooks.slack.com/triggers/" + secrets.NewSecret(utils.AlphaNumeric("56")),
|
||||||
}
|
}
|
||||||
return utils.Validate(r, tps, nil)
|
return utils.Validate(r, tps, nil)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package rules
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Sonar() *config.Rule {
|
||||||
|
// define 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)"}, "(?: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_TOKEN = "squ_12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
|
||||||
|
`SONAR_LOGIN := "sqp_12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
|
||||||
|
`SONAR.TOKEN = "sqa_12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
|
||||||
|
)
|
||||||
|
return utils.Validate(r, tps, nil)
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package rules
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
func SourceGraph() *config.Rule {
|
||||||
|
// define rule
|
||||||
|
r := config.Rule{
|
||||||
|
RuleID: "sourcegraph-access-token",
|
||||||
|
Description: "Sourcegraph is a code search and navigation engine.",
|
||||||
|
Regex: utils.GenerateUniqueTokenRegex(`\b(sgp_(?:[a-fA-F0-9]{16}|local)_[a-fA-F0-9]{40}|sgp_[a-fA-F0-9]{40}|[a-fA-F0-9]{40})\b`, true),
|
||||||
|
Entropy: 3,
|
||||||
|
Keywords: []string{"sgp_", "sourcegraph"},
|
||||||
|
}
|
||||||
|
|
||||||
|
// validate
|
||||||
|
tps := []string{
|
||||||
|
`sgp_AaD80dc6E02eCAE1_d3cba16CC0F18fA14A2EFB61CbDFceEBf9fAD16b`,
|
||||||
|
`sourcegraph: 6d2FabeB6ADd229Bc199FabA28fD3efb57dF0bD3`,
|
||||||
|
`sgp_0D697F54cb24238EefB29af05Abf1b505E90950F`,
|
||||||
|
`sgp_local_d7dfFD43cF2503B1da673EB560aAa3e80f16FA42`,
|
||||||
|
`sgp_local_bcD1DA18de0d6476Be0f3BD7Ef9Da4f09b479aE5`,
|
||||||
|
}
|
||||||
|
fps := []string{
|
||||||
|
`sgp_5555555dAAAAA7777777CcccCFaaaaaaaaaaaaaa`, // low entropy
|
||||||
|
`sgp_local_d45b6G86aBb0F2Cee943902dbaDBCFCFDD1dA089`, // invalid case
|
||||||
|
`sgp_652d9a2e48FC7E!FcDbEA1BC2E2A6CE23cFe7F7D`, // invalid character
|
||||||
|
`sgp_78Ad84a5B6e8A2fE5B_4085FB0ccaDDd29DB66Fd7FE9bA2C1cdCE8400CD`, // invalid length
|
||||||
|
`BcAeb6640ad7DAD46AD73687946Ce85047d5C9Bb`,
|
||||||
|
}
|
||||||
|
return utils.Validate(r, tps, fps)
|
||||||
|
}
|
||||||
@@ -1,12 +1,10 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TeamsWebhook() *config.Rule {
|
func TeamsWebhook() *config.Rule {
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
package rules
|
package rules
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||||
"github.com/zricethezav/gitleaks/v8/config"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Twilio() *config.Rule {
|
func Twilio() *config.Rule {
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
regexp "github.com/wasilibs/go-re2"
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -19,17 +19,16 @@ const (
|
|||||||
identifierCaseInsensitivePrefix = `[\w.-]{0,50}?(?i:`
|
identifierCaseInsensitivePrefix = `[\w.-]{0,50}?(?i:`
|
||||||
identifierCaseInsensitiveSuffix = `)`
|
identifierCaseInsensitiveSuffix = `)`
|
||||||
identifierPrefix = `[\w.-]{0,50}?(?:`
|
identifierPrefix = `[\w.-]{0,50}?(?:`
|
||||||
identifierSuffix = `)(?:[ \t\w.-]{0,20})(?:[\s|']|[\s|"]){0,3}`
|
identifierSuffix = `)(?:[ \t\w.-]{0,20})[\s'"]{0,3}`
|
||||||
|
|
||||||
// commonly used assignment operators or function call
|
// commonly used assignment operators or function call
|
||||||
//language=regexp
|
//language=regexp
|
||||||
operator = `(?:=|>|:{1,3}=|\|\|:|<=|=>|:|\?=|,)`
|
operator = `(?:=|>|:{1,3}=|\|\||:|=>|\?=|,)`
|
||||||
|
|
||||||
// boundaries for the secret
|
// boundaries for the secret
|
||||||
// \x60 = `
|
|
||||||
secretPrefixUnique = `\b(`
|
secretPrefixUnique = `\b(`
|
||||||
secretPrefix = `(?:'|\"|\s|=|\x60){0,5}(`
|
secretPrefix = `[\x60'"\s=]{0,5}(`
|
||||||
secretSuffix = `)(?:['|\"|\n|\r|\s|\x60|;]|$)`
|
secretSuffix = `)(?:[\x60'"\s;]|\\[nr]|$)`
|
||||||
)
|
)
|
||||||
|
|
||||||
func GenerateSemiGenericRegex(identifiers []string, secretRegex string, isCaseInsensitive bool) *regexp.Regexp {
|
func GenerateSemiGenericRegex(identifiers []string, secretRegex string, isCaseInsensitive bool) *regexp.Regexp {
|
||||||
@@ -95,6 +94,7 @@ func GenerateSampleSecrets(identifier string, secret string) []string {
|
|||||||
"json - string": "{\n \"{i}_token\": \"{s}\"\n}",
|
"json - string": "{\n \"{i}_token\": \"{s}\"\n}",
|
||||||
// TODO: "json - escaped string": "\\{\n \\\"{i}_token\\\": \\\"{s}\\\"\n\\}",
|
// TODO: "json - escaped string": "\\{\n \\\"{i}_token\\\": \\\"{s}\\\"\n\\}",
|
||||||
// TODO: "json - string key/value": "{\n \"name\": \"{i}_token\",\n \"value\": \"{s}\"\n}",
|
// TODO: "json - string key/value": "{\n \"name\": \"{i}_token\",\n \"value\": \"{s}\"\n}",
|
||||||
|
"json - escaped newline in string": `{"config.ini": "{I}_TOKEN={s}\nBACKUP_ENABLED=true"}`,
|
||||||
// XML
|
// XML
|
||||||
// TODO: "xml - element": "<{i}Token>{s}</{i}Token>",
|
// TODO: "xml - element": "<{i}Token>{s}</{i}Token>",
|
||||||
"xml - element multiline": "<{i}Token>\n {s}\n</{i}Token>",
|
"xml - element multiline": "<{i}Token>\n {s}\n</{i}Token>",
|
||||||
|
|||||||
@@ -68,7 +68,7 @@ func TestGenerateSemiGenericRegex(t *testing.T) {
|
|||||||
"api_key\t\t\t\t\t=xxx",
|
"api_key\t\t\t\t\t=xxx",
|
||||||
"api_key\n\n\n=xxx", // potentially invalid?,
|
"api_key\n\n\n=xxx", // potentially invalid?,
|
||||||
"api_key\r\n=xxx",
|
"api_key\r\n=xxx",
|
||||||
"api_key|||=xxx",
|
// "api_key|||=xxx",
|
||||||
},
|
},
|
||||||
invalidStrings: []string{
|
invalidStrings: []string{
|
||||||
"api_key&=xxx",
|
"api_key&=xxx",
|
||||||
@@ -89,8 +89,8 @@ func TestGenerateSemiGenericRegex(t *testing.T) {
|
|||||||
"<api_key>xxx",
|
"<api_key>xxx",
|
||||||
"api_key:=xxx",
|
"api_key:=xxx",
|
||||||
"api_key:::=xxx",
|
"api_key:::=xxx",
|
||||||
"api_key||:=xxx",
|
// "api_key||:=xxx", // this isn't anything
|
||||||
"api_key <= xxx",
|
// "api_key <= xxx",
|
||||||
"api_key => xxx",
|
"api_key => xxx",
|
||||||
"api_key ?= xxx",
|
"api_key ?= xxx",
|
||||||
"api_key, xxx",
|
"api_key, xxx",
|
||||||
|
|||||||
@@ -88,5 +88,10 @@ func createSingleRuleDetector(r *config.Rule) *detect.Detector {
|
|||||||
cfg := base.CreateGlobalConfig()
|
cfg := base.CreateGlobalConfig()
|
||||||
cfg.Rules = rules
|
cfg.Rules = rules
|
||||||
cfg.Keywords = uniqueKeywords
|
cfg.Keywords = uniqueKeywords
|
||||||
|
for _, a := range cfg.Allowlists {
|
||||||
|
if err := a.Validate(); err != nil {
|
||||||
|
logging.Fatal().Err(err).Msg("invalid global allowlist")
|
||||||
|
}
|
||||||
|
}
|
||||||
return detect.NewDetector(cfg)
|
return detect.NewDetector(cfg)
|
||||||
}
|
}
|
||||||
+35
-36
@@ -5,6 +5,7 @@ import (
|
|||||||
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
|
||||||
|
"github.com/zricethezav/gitleaks/v8/cmd/scm"
|
||||||
"github.com/zricethezav/gitleaks/v8/logging"
|
"github.com/zricethezav/gitleaks/v8/logging"
|
||||||
"github.com/zricethezav/gitleaks/v8/report"
|
"github.com/zricethezav/gitleaks/v8/report"
|
||||||
"github.com/zricethezav/gitleaks/v8/sources"
|
"github.com/zricethezav/gitleaks/v8/sources"
|
||||||
@@ -12,6 +13,7 @@ import (
|
|||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
rootCmd.AddCommand(gitCmd)
|
rootCmd.AddCommand(gitCmd)
|
||||||
|
gitCmd.Flags().String("platform", "", "the target platform used to generate links (github, gitlab)")
|
||||||
gitCmd.Flags().Bool("staged", false, "scan staged commits (good for pre-commit)")
|
gitCmd.Flags().Bool("staged", false, "scan staged commits (good for pre-commit)")
|
||||||
gitCmd.Flags().Bool("pre-commit", false, "scan using git diff")
|
gitCmd.Flags().Bool("pre-commit", false, "scan using git diff")
|
||||||
gitCmd.Flags().String("log-opts", "", "git log options")
|
gitCmd.Flags().String("log-opts", "", "git log options")
|
||||||
@@ -25,10 +27,8 @@ var gitCmd = &cobra.Command{
|
|||||||
}
|
}
|
||||||
|
|
||||||
func runGit(cmd *cobra.Command, args []string) {
|
func runGit(cmd *cobra.Command, args []string) {
|
||||||
var (
|
// start timer
|
||||||
findings []report.Finding
|
start := time.Now()
|
||||||
err error
|
|
||||||
)
|
|
||||||
|
|
||||||
// grab source
|
// grab source
|
||||||
source := "."
|
source := "."
|
||||||
@@ -39,55 +39,54 @@ func runGit(cmd *cobra.Command, args []string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
initConfig(source)
|
|
||||||
|
|
||||||
// setup config (aka, the thing that defines rules)
|
// setup config (aka, the thing that defines rules)
|
||||||
|
initConfig(source)
|
||||||
|
initDiagnostics()
|
||||||
|
|
||||||
cfg := Config(cmd)
|
cfg := Config(cmd)
|
||||||
|
|
||||||
// start timer
|
// create detector
|
||||||
start := time.Now()
|
|
||||||
|
|
||||||
// grab source
|
|
||||||
detector := Detector(cmd, cfg, source)
|
detector := Detector(cmd, cfg, source)
|
||||||
|
|
||||||
// set exit code
|
// parse flags
|
||||||
exitCode, err := cmd.Flags().GetInt("exit-code")
|
exitCode := mustGetIntFlag(cmd, "exit-code")
|
||||||
if err != nil {
|
logOpts := mustGetStringFlag(cmd, "log-opts")
|
||||||
logging.Fatal().Err(err).Msg("could not get exit code")
|
staged := mustGetBoolFlag(cmd, "staged")
|
||||||
}
|
preCommit := mustGetBoolFlag(cmd, "pre-commit")
|
||||||
|
|
||||||
var (
|
var (
|
||||||
gitCmd *sources.GitCmd
|
findings []report.Finding
|
||||||
logOpts string
|
err error
|
||||||
preCommit bool
|
gitCmd *sources.GitCmd
|
||||||
staged bool
|
scmPlatform scm.Platform
|
||||||
)
|
)
|
||||||
logOpts, err = cmd.Flags().GetString("log-opts")
|
|
||||||
if err != nil {
|
|
||||||
logging.Fatal().Err(err).Msg("could not call GetString() for log-opts")
|
|
||||||
}
|
|
||||||
staged, err = cmd.Flags().GetBool("staged")
|
|
||||||
if err != nil {
|
|
||||||
logging.Fatal().Err(err).Msg("could not call GetBool() for staged")
|
|
||||||
}
|
|
||||||
preCommit, err = cmd.Flags().GetBool("pre-commit")
|
|
||||||
if err != nil {
|
|
||||||
logging.Fatal().Err(err).Msg("could not call GetBool() for pre-commit")
|
|
||||||
}
|
|
||||||
|
|
||||||
if preCommit || staged {
|
if preCommit || staged {
|
||||||
gitCmd, err = sources.NewGitDiffCmd(source, staged)
|
if gitCmd, err = sources.NewGitDiffCmdContext(cmd.Context(), source, staged); err != nil {
|
||||||
if err != nil {
|
|
||||||
logging.Fatal().Err(err).Msg("could not create Git diff cmd")
|
logging.Fatal().Err(err).Msg("could not create Git diff cmd")
|
||||||
}
|
}
|
||||||
|
// Remote info + links are irrelevant for staged changes.
|
||||||
|
scmPlatform = scm.NoPlatform
|
||||||
} else {
|
} else {
|
||||||
gitCmd, err = sources.NewGitLogCmd(source, logOpts)
|
if gitCmd, err = sources.NewGitLogCmdContext(cmd.Context(), source, logOpts); err != nil {
|
||||||
if err != nil {
|
|
||||||
logging.Fatal().Err(err).Msg("could not create Git log cmd")
|
logging.Fatal().Err(err).Msg("could not create Git log cmd")
|
||||||
}
|
}
|
||||||
|
if scmPlatform, err = scm.PlatformFromString(mustGetStringFlag(cmd, "platform")); err != nil {
|
||||||
|
logging.Fatal().Err(err).Send()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
findings, err = detector.DetectGit(gitCmd)
|
findings, err = detector.DetectSource(
|
||||||
|
cmd.Context(),
|
||||||
|
&sources.Git{
|
||||||
|
Cmd: gitCmd,
|
||||||
|
Config: &detector.Config,
|
||||||
|
Remote: sources.NewRemoteInfoContext(cmd.Context(), scmPlatform, source),
|
||||||
|
Sema: detector.Sema,
|
||||||
|
MaxArchiveDepth: detector.MaxArchiveDepth,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// don't exit on error, just log it
|
// don't exit on error, just log it
|
||||||
logging.Error().Err(err).Msg("failed to scan Git repository")
|
logging.Error().Err(err).Msg("failed to scan Git repository")
|
||||||
|
|||||||
+30
-15
@@ -5,6 +5,8 @@ import (
|
|||||||
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
|
||||||
|
"github.com/zricethezav/gitleaks/v8/cmd/scm"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/detect"
|
||||||
"github.com/zricethezav/gitleaks/v8/logging"
|
"github.com/zricethezav/gitleaks/v8/logging"
|
||||||
"github.com/zricethezav/gitleaks/v8/report"
|
"github.com/zricethezav/gitleaks/v8/report"
|
||||||
"github.com/zricethezav/gitleaks/v8/sources"
|
"github.com/zricethezav/gitleaks/v8/sources"
|
||||||
@@ -25,27 +27,40 @@ var protectCmd = &cobra.Command{
|
|||||||
}
|
}
|
||||||
|
|
||||||
func runProtect(cmd *cobra.Command, args []string) {
|
func runProtect(cmd *cobra.Command, args []string) {
|
||||||
source, err := cmd.Flags().GetString("source")
|
// start timer
|
||||||
if err != nil {
|
start := time.Now()
|
||||||
logging.Fatal().Err(err).Msg("could not get source")
|
source := mustGetStringFlag(cmd, "source")
|
||||||
}
|
|
||||||
initConfig(source)
|
|
||||||
|
|
||||||
// setup config (aka, the thing that defines rules)
|
// setup config (aka, the thing that defines rules)
|
||||||
|
initConfig(source)
|
||||||
|
initDiagnostics()
|
||||||
|
|
||||||
cfg := Config(cmd)
|
cfg := Config(cmd)
|
||||||
|
|
||||||
exitCode, _ := cmd.Flags().GetInt("exit-code")
|
// create detector
|
||||||
staged, _ := cmd.Flags().GetBool("staged")
|
|
||||||
start := time.Now()
|
|
||||||
detector := Detector(cmd, cfg, source)
|
detector := Detector(cmd, cfg, source)
|
||||||
|
|
||||||
// start git scan
|
// parse flags
|
||||||
var findings []report.Finding
|
exitCode := mustGetIntFlag(cmd, "exit-code")
|
||||||
gitCmd, err := sources.NewGitDiffCmd(source, staged)
|
staged := mustGetBoolFlag(cmd, "staged")
|
||||||
if err != nil {
|
|
||||||
logging.Fatal().Err(err).Msg("")
|
|
||||||
}
|
|
||||||
findings, err = detector.DetectGit(gitCmd)
|
|
||||||
|
|
||||||
|
// start git scan
|
||||||
|
var (
|
||||||
|
findings []report.Finding
|
||||||
|
err error
|
||||||
|
|
||||||
|
gitCmd *sources.GitCmd
|
||||||
|
remote *detect.RemoteInfo
|
||||||
|
)
|
||||||
|
|
||||||
|
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}
|
||||||
|
|
||||||
|
if findings, err = detector.DetectGit(gitCmd, remote); err != nil {
|
||||||
|
// don't exit on error, just log it
|
||||||
|
logging.Error().Err(err).Msg("failed to scan Git repository")
|
||||||
|
}
|
||||||
findingSummaryAndExit(detector, findings, exitCode, start, err)
|
findingSummaryAndExit(detector, findings, exitCode, start, err)
|
||||||
}
|
}
|
||||||
+136
-32
@@ -1,6 +1,8 @@
|
|||||||
package cmd
|
package cmd
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
@@ -16,7 +18,9 @@ import (
|
|||||||
"github.com/zricethezav/gitleaks/v8/config"
|
"github.com/zricethezav/gitleaks/v8/config"
|
||||||
"github.com/zricethezav/gitleaks/v8/detect"
|
"github.com/zricethezav/gitleaks/v8/detect"
|
||||||
"github.com/zricethezav/gitleaks/v8/logging"
|
"github.com/zricethezav/gitleaks/v8/logging"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
"github.com/zricethezav/gitleaks/v8/report"
|
"github.com/zricethezav/gitleaks/v8/report"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/version"
|
||||||
)
|
)
|
||||||
|
|
||||||
const banner = `
|
const banner = `
|
||||||
@@ -32,14 +36,32 @@ const configDescription = `config file path
|
|||||||
order of precedence:
|
order of precedence:
|
||||||
1. --config/-c
|
1. --config/-c
|
||||||
2. env var GITLEAKS_CONFIG
|
2. env var GITLEAKS_CONFIG
|
||||||
3. (target path)/.gitleaks.toml
|
3. env var GITLEAKS_CONFIG_TOML with the file content
|
||||||
If none of the three options are used, then gitleaks will use the default config`
|
4. (target path)/.gitleaks.toml
|
||||||
|
If none of the four options are used, then gitleaks will use the default config`
|
||||||
|
|
||||||
var rootCmd = &cobra.Command{
|
var (
|
||||||
Use: "gitleaks",
|
rootCmd = &cobra.Command{
|
||||||
Short: "Gitleaks scans code, past or present, for secrets",
|
Use: "gitleaks",
|
||||||
Version: Version,
|
Short: "Gitleaks scans code, past or present, for secrets",
|
||||||
}
|
Version: version.Version,
|
||||||
|
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
// Set the timeout for all the commands
|
||||||
|
if timeout, err := cmd.Flags().GetInt("timeout"); err != nil {
|
||||||
|
return err
|
||||||
|
} else if timeout > 0 {
|
||||||
|
ctx, cancel := context.WithTimeout(cmd.Context(), time.Duration(timeout)*time.Second)
|
||||||
|
cmd.SetContext(ctx)
|
||||||
|
cobra.OnFinalize(cancel)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// diagnostics manager is global to ensure it can be started before a scan begins
|
||||||
|
// and stopped after a scan completes
|
||||||
|
diagnosticsManager *DiagnosticsManager
|
||||||
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
BYTE = 1.0
|
BYTE = 1.0
|
||||||
@@ -52,8 +74,8 @@ func init() {
|
|||||||
cobra.OnInitialize(initLog)
|
cobra.OnInitialize(initLog)
|
||||||
rootCmd.PersistentFlags().StringP("config", "c", "", configDescription)
|
rootCmd.PersistentFlags().StringP("config", "c", "", configDescription)
|
||||||
rootCmd.PersistentFlags().Int("exit-code", 1, "exit code when leaks have been encountered")
|
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", "json", "output format (json, jsonextra, csv, junit, sarif, template)")
|
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("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")
|
rootCmd.PersistentFlags().StringP("baseline-path", "b", "", "path to baseline with issues that can be ignored")
|
||||||
rootCmd.PersistentFlags().StringP("log-level", "l", "info", "log level (trace, debug, info, warn, error, fatal)")
|
rootCmd.PersistentFlags().StringP("log-level", "l", "info", "log level (trace, debug, info, warn, error, fatal)")
|
||||||
@@ -66,7 +88,13 @@ func init() {
|
|||||||
rootCmd.PersistentFlags().Bool("no-banner", false, "suppress banner")
|
rootCmd.PersistentFlags().Bool("no-banner", false, "suppress banner")
|
||||||
rootCmd.PersistentFlags().StringSlice("enable-rule", []string{}, "only enable specific rules by id")
|
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().StringP("gitleaks-ignore-path", "i", ".", "path to .gitleaksignore file or folder containing one")
|
||||||
rootCmd.PersistentFlags().Int("max-decode-depth", 0, "allow recursive decoding up to this depth (default \"0\", no decoding is done)")
|
rootCmd.PersistentFlags().Int("max-decode-depth", 5, "allow recursive decoding up to this depth")
|
||||||
|
rootCmd.PersistentFlags().Int("max-archive-depth", 0, "allow scanning into nested archives up to this depth (default \"0\", no archive traversal is done)")
|
||||||
|
rootCmd.PersistentFlags().Int("timeout", 0, "set a timeout for gitleaks commands in seconds (default \"0\", no timeout is set)")
|
||||||
|
|
||||||
|
// Add diagnostics flags
|
||||||
|
rootCmd.PersistentFlags().String("diagnostics", "", "enable diagnostics (http OR comma-separated list: cpu,mem,trace). cpu=CPU prof, mem=memory prof, trace=exec tracing, http=serve via net/http/pprof")
|
||||||
|
rootCmd.PersistentFlags().String("diagnostics-dir", "", "directory to store diagnostics output files when not using http mode (defaults to current directory)")
|
||||||
|
|
||||||
err := viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config"))
|
err := viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -103,6 +131,8 @@ func initLog() {
|
|||||||
|
|
||||||
func initConfig(source string) {
|
func initConfig(source string) {
|
||||||
hideBanner, err := rootCmd.Flags().GetBool("no-banner")
|
hideBanner, err := rootCmd.Flags().GetBool("no-banner")
|
||||||
|
viper.SetConfigType("toml")
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logging.Fatal().Msg(err.Error())
|
logging.Fatal().Msg(err.Error())
|
||||||
}
|
}
|
||||||
@@ -110,6 +140,8 @@ func initConfig(source string) {
|
|||||||
_, _ = fmt.Fprint(os.Stderr, banner)
|
_, _ = fmt.Fprint(os.Stderr, banner)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
logging.Debug().Msgf("using %s regex engine", regexp.Version)
|
||||||
|
|
||||||
cfgPath, err := rootCmd.Flags().GetString("config")
|
cfgPath, err := rootCmd.Flags().GetString("config")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logging.Fatal().Msg(err.Error())
|
logging.Fatal().Msg(err.Error())
|
||||||
@@ -121,6 +153,13 @@ func initConfig(source string) {
|
|||||||
envPath := os.Getenv("GITLEAKS_CONFIG")
|
envPath := os.Getenv("GITLEAKS_CONFIG")
|
||||||
viper.SetConfigFile(envPath)
|
viper.SetConfigFile(envPath)
|
||||||
logging.Debug().Msgf("using gitleaks config from GITLEAKS_CONFIG env var: %s", envPath)
|
logging.Debug().Msgf("using gitleaks config from GITLEAKS_CONFIG env var: %s", envPath)
|
||||||
|
} else if os.Getenv("GITLEAKS_CONFIG_TOML") != "" {
|
||||||
|
configContent := []byte(os.Getenv("GITLEAKS_CONFIG_TOML"))
|
||||||
|
if err := viper.ReadConfig(bytes.NewBuffer(configContent)); err != nil {
|
||||||
|
logging.Fatal().Err(err).Str("content", os.Getenv("GITLEAKS_CONFIG_TOML")).Msg("unable to load gitleaks config from GITLEAKS_CONFIG_TOML env var")
|
||||||
|
}
|
||||||
|
logging.Debug().Str("content", os.Getenv("GITLEAKS_CONFIG_TOML")).Msg("using gitleaks config from GITLEAKS_CONFIG_TOML env var content")
|
||||||
|
return
|
||||||
} else {
|
} else {
|
||||||
fileInfo, err := os.Stat(source)
|
fileInfo, err := os.Stat(source)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -130,7 +169,6 @@ func initConfig(source string) {
|
|||||||
if !fileInfo.IsDir() {
|
if !fileInfo.IsDir() {
|
||||||
logging.Debug().Msgf("unable to load gitleaks config from %s since --source=%s is a file, using default config",
|
logging.Debug().Msgf("unable to load gitleaks config from %s since --source=%s is a file, using default config",
|
||||||
filepath.Join(source, ".gitleaks.toml"), source)
|
filepath.Join(source, ".gitleaks.toml"), source)
|
||||||
viper.SetConfigType("toml")
|
|
||||||
if err = viper.ReadConfig(strings.NewReader(config.DefaultConfig)); err != nil {
|
if err = viper.ReadConfig(strings.NewReader(config.DefaultConfig)); err != nil {
|
||||||
logging.Fatal().Msgf("err reading toml %s", err.Error())
|
logging.Fatal().Msgf("err reading toml %s", err.Error())
|
||||||
}
|
}
|
||||||
@@ -139,7 +177,7 @@ func initConfig(source string) {
|
|||||||
|
|
||||||
if _, err := os.Stat(filepath.Join(source, ".gitleaks.toml")); os.IsNotExist(err) {
|
if _, err := os.Stat(filepath.Join(source, ".gitleaks.toml")); os.IsNotExist(err) {
|
||||||
logging.Debug().Msgf("no gitleaks config found in path %s, using default gitleaks config", filepath.Join(source, ".gitleaks.toml"))
|
logging.Debug().Msgf("no gitleaks config found in path %s, using default gitleaks config", filepath.Join(source, ".gitleaks.toml"))
|
||||||
viper.SetConfigType("toml")
|
|
||||||
if err = viper.ReadConfig(strings.NewReader(config.DefaultConfig)); err != nil {
|
if err = viper.ReadConfig(strings.NewReader(config.DefaultConfig)); err != nil {
|
||||||
logging.Fatal().Msgf("err reading default config toml %s", err.Error())
|
logging.Fatal().Msgf("err reading default config toml %s", err.Error())
|
||||||
}
|
}
|
||||||
@@ -150,13 +188,39 @@ func initConfig(source string) {
|
|||||||
|
|
||||||
viper.AddConfigPath(source)
|
viper.AddConfigPath(source)
|
||||||
viper.SetConfigName(".gitleaks")
|
viper.SetConfigName(".gitleaks")
|
||||||
viper.SetConfigType("toml")
|
|
||||||
}
|
}
|
||||||
if err := viper.ReadInConfig(); err != nil {
|
if err := viper.ReadInConfig(); err != nil {
|
||||||
logging.Fatal().Msgf("unable to load gitleaks config, err: %s", err)
|
logging.Fatal().Msgf("unable to load gitleaks config, err: %s", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func initDiagnostics() {
|
||||||
|
// Initialize diagnostics manager
|
||||||
|
diagnosticsFlag, err := rootCmd.PersistentFlags().GetString("diagnostics")
|
||||||
|
if err != nil {
|
||||||
|
logging.Fatal().Err(err).Msg("Error getting diagnostics flag")
|
||||||
|
}
|
||||||
|
|
||||||
|
diagnosticsDir, err := rootCmd.PersistentFlags().GetString("diagnostics-dir")
|
||||||
|
if err != nil {
|
||||||
|
logging.Fatal().Err(err).Msg("Error getting diagnostics-dir flag")
|
||||||
|
}
|
||||||
|
|
||||||
|
var diagErr error
|
||||||
|
diagnosticsManager, diagErr = NewDiagnosticsManager(diagnosticsFlag, diagnosticsDir)
|
||||||
|
if diagErr != nil {
|
||||||
|
logging.Fatal().Err(diagErr).Msg("Error initializing diagnostics")
|
||||||
|
}
|
||||||
|
|
||||||
|
if diagnosticsManager.Enabled {
|
||||||
|
logging.Info().Msg("Starting diagnostics...")
|
||||||
|
if diagErr := diagnosticsManager.StartDiagnostics(); diagErr != nil {
|
||||||
|
logging.Fatal().Err(diagErr).Msg("Failed to start diagnostics")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
func Execute() {
|
func Execute() {
|
||||||
if err := rootCmd.Execute(); err != nil {
|
if err := rootCmd.Execute(); err != nil {
|
||||||
if strings.Contains(err.Error(), "unknown flag") {
|
if strings.Contains(err.Error(), "unknown flag") {
|
||||||
@@ -172,6 +236,7 @@ func Config(cmd *cobra.Command) config.Config {
|
|||||||
if err := viper.Unmarshal(&vc); err != nil {
|
if err := viper.Unmarshal(&vc); err != nil {
|
||||||
logging.Fatal().Err(err).Msg("Failed to load config")
|
logging.Fatal().Err(err).Msg("Failed to load config")
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg, err := vc.Translate()
|
cfg, err := vc.Translate()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logging.Fatal().Err(err).Msg("Failed to load config")
|
logging.Fatal().Err(err).Msg("Failed to load config")
|
||||||
@@ -185,15 +250,19 @@ func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Dete
|
|||||||
var err error
|
var err error
|
||||||
|
|
||||||
// Setup common detector
|
// 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 {
|
if detector.MaxDecodeDepth, err = cmd.Flags().GetInt("max-decode-depth"); err != nil {
|
||||||
logging.Fatal().Err(err).Msg("")
|
logging.Fatal().Err(err).Send()
|
||||||
|
}
|
||||||
|
|
||||||
|
if detector.MaxArchiveDepth, err = cmd.Flags().GetInt("max-archive-depth"); err != nil {
|
||||||
|
logging.Fatal().Err(err).Send()
|
||||||
}
|
}
|
||||||
|
|
||||||
// set color flag at first
|
// set color flag at first
|
||||||
if detector.NoColor, err = cmd.Flags().GetBool("no-color"); err != nil {
|
if detector.NoColor, err = cmd.Flags().GetBool("no-color"); err != nil {
|
||||||
logging.Fatal().Err(err).Msg("")
|
logging.Fatal().Err(err).Send()
|
||||||
}
|
}
|
||||||
// also init logger again without color
|
// also init logger again without color
|
||||||
if detector.NoColor {
|
if detector.NoColor {
|
||||||
@@ -204,7 +273,7 @@ func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Dete
|
|||||||
}
|
}
|
||||||
detector.Config.Path, err = cmd.Flags().GetString("config")
|
detector.Config.Path, err = cmd.Flags().GetString("config")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logging.Fatal().Err(err).Msg("")
|
logging.Fatal().Err(err).Send()
|
||||||
}
|
}
|
||||||
|
|
||||||
// if config path is not set, then use the {source}/.gitleaks.toml path.
|
// if config path is not set, then use the {source}/.gitleaks.toml path.
|
||||||
@@ -214,18 +283,18 @@ func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Dete
|
|||||||
}
|
}
|
||||||
// set verbose flag
|
// set verbose flag
|
||||||
if detector.Verbose, err = cmd.Flags().GetBool("verbose"); err != nil {
|
if detector.Verbose, err = cmd.Flags().GetBool("verbose"); err != nil {
|
||||||
logging.Fatal().Err(err).Msg("")
|
logging.Fatal().Err(err).Send()
|
||||||
}
|
}
|
||||||
// set redact flag
|
// set redact flag
|
||||||
if detector.Redact, err = cmd.Flags().GetUint("redact"); err != nil {
|
if detector.Redact, err = cmd.Flags().GetUint("redact"); err != nil {
|
||||||
logging.Fatal().Err(err).Msg("")
|
logging.Fatal().Err(err).Send()
|
||||||
}
|
}
|
||||||
if detector.MaxTargetMegaBytes, err = cmd.Flags().GetInt("max-target-megabytes"); err != nil {
|
if detector.MaxTargetMegaBytes, err = cmd.Flags().GetInt("max-target-megabytes"); err != nil {
|
||||||
logging.Fatal().Err(err).Msg("")
|
logging.Fatal().Err(err).Send()
|
||||||
}
|
}
|
||||||
// set ignore gitleaks:allow flag
|
// set ignore gitleaks:allow flag
|
||||||
if detector.IgnoreGitleaksAllow, err = cmd.Flags().GetBool("ignore-gitleaks-allow"); err != nil {
|
if detector.IgnoreGitleaksAllow, err = cmd.Flags().GetBool("ignore-gitleaks-allow"); err != nil {
|
||||||
logging.Fatal().Err(err).Msg("")
|
logging.Fatal().Err(err).Send()
|
||||||
}
|
}
|
||||||
|
|
||||||
gitleaksIgnorePath, err := cmd.Flags().GetString("gitleaks-ignore-path")
|
gitleaksIgnorePath, err := cmd.Flags().GetString("gitleaks-ignore-path")
|
||||||
@@ -276,7 +345,7 @@ func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Dete
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Validate report settings.
|
// Validate report settings.
|
||||||
reportPath := mustGetStringFlag("report-path")
|
reportPath := mustGetStringFlag(cmd, "report-path")
|
||||||
if reportPath != "" {
|
if reportPath != "" {
|
||||||
if reportPath != report.StdoutReportPath {
|
if reportPath != report.StdoutReportPath {
|
||||||
// Ensure the path is writable.
|
// Ensure the path is writable.
|
||||||
@@ -291,9 +360,23 @@ func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Dete
|
|||||||
// Build report writer.
|
// Build report writer.
|
||||||
var (
|
var (
|
||||||
reporter report.Reporter
|
reporter report.Reporter
|
||||||
reportFormat = mustGetStringFlag("report-format")
|
reportFormat = mustGetStringFlag(cmd, "report-format")
|
||||||
reportTemplate = mustGetStringFlag("report-template")
|
reportTemplate = mustGetStringFlag(cmd, "report-template")
|
||||||
)
|
)
|
||||||
|
if reportFormat == "" {
|
||||||
|
ext := strings.ToLower(filepath.Ext(reportPath))
|
||||||
|
switch ext {
|
||||||
|
case ".csv":
|
||||||
|
reportFormat = "csv"
|
||||||
|
case ".json":
|
||||||
|
reportFormat = "json"
|
||||||
|
case ".sarif":
|
||||||
|
reportFormat = "sarif"
|
||||||
|
default:
|
||||||
|
logging.Fatal().Msgf("Unknown report format: %s", reportFormat)
|
||||||
|
}
|
||||||
|
logging.Debug().Msgf("No report format specified, inferred %q from %q", reportFormat, ext)
|
||||||
|
}
|
||||||
switch strings.TrimSpace(strings.ToLower(reportFormat)) {
|
switch strings.TrimSpace(strings.ToLower(reportFormat)) {
|
||||||
case "csv":
|
case "csv":
|
||||||
reporter = &report.CsvReporter{}
|
reporter = &report.CsvReporter{}
|
||||||
@@ -325,14 +408,6 @@ func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Dete
|
|||||||
return detector
|
return detector
|
||||||
}
|
}
|
||||||
|
|
||||||
func mustGetStringFlag(name string) string {
|
|
||||||
reportPath, err := rootCmd.Flags().GetString(name)
|
|
||||||
if err != nil {
|
|
||||||
logging.Fatal().Msg(err.Error())
|
|
||||||
}
|
|
||||||
return reportPath
|
|
||||||
}
|
|
||||||
|
|
||||||
func bytesConvert(bytes uint64) string {
|
func bytesConvert(bytes uint64) string {
|
||||||
unit := ""
|
unit := ""
|
||||||
value := float32(bytes)
|
value := float32(bytes)
|
||||||
@@ -361,6 +436,11 @@ func bytesConvert(bytes uint64) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func findingSummaryAndExit(detector *detect.Detector, findings []report.Finding, exitCode int, start time.Time, err error) {
|
func findingSummaryAndExit(detector *detect.Detector, findings []report.Finding, exitCode int, start time.Time, err error) {
|
||||||
|
if diagnosticsManager.Enabled {
|
||||||
|
logging.Debug().Msg("Finalizing diagnostics...")
|
||||||
|
diagnosticsManager.StopDiagnostics()
|
||||||
|
}
|
||||||
|
|
||||||
totalBytes := detector.TotalBytes.Load()
|
totalBytes := detector.TotalBytes.Load()
|
||||||
bytesMsg := fmt.Sprintf("scanned ~%d bytes (%s)", totalBytes, bytesConvert(totalBytes))
|
bytesMsg := fmt.Sprintf("scanned ~%d bytes (%s)", totalBytes, bytesConvert(totalBytes))
|
||||||
if err == nil {
|
if err == nil {
|
||||||
@@ -442,3 +522,27 @@ func FormatDuration(d time.Duration) string {
|
|||||||
}
|
}
|
||||||
return d.Round(scale / 100).String()
|
return d.Round(scale / 100).String()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func mustGetBoolFlag(cmd *cobra.Command, name string) bool {
|
||||||
|
value, err := cmd.Flags().GetBool(name)
|
||||||
|
if err != nil {
|
||||||
|
logging.Fatal().Err(err).Msgf("could not get flag: %s", name)
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustGetIntFlag(cmd *cobra.Command, name string) int {
|
||||||
|
value, err := cmd.Flags().GetInt(name)
|
||||||
|
if err != nil {
|
||||||
|
logging.Fatal().Err(err).Msgf("could not get flag: %s", name)
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustGetStringFlag(cmd *cobra.Command, name string) string {
|
||||||
|
value, err := cmd.Flags().GetString(name)
|
||||||
|
if err != nil {
|
||||||
|
logging.Fatal().Err(err).Msgf("could not get flag: %s", name)
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package scm
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Platform int
|
||||||
|
|
||||||
|
const (
|
||||||
|
UnknownPlatform Platform = iota
|
||||||
|
NoPlatform // Explicitly disable the feature
|
||||||
|
GitHubPlatform
|
||||||
|
GitLabPlatform
|
||||||
|
AzureDevOpsPlatform
|
||||||
|
GiteaPlatform
|
||||||
|
BitbucketPlatform
|
||||||
|
// TODO: Add others.
|
||||||
|
)
|
||||||
|
|
||||||
|
func (p Platform) String() string {
|
||||||
|
return [...]string{
|
||||||
|
"unknown",
|
||||||
|
"none",
|
||||||
|
"github",
|
||||||
|
"gitlab",
|
||||||
|
"azuredevops",
|
||||||
|
"gitea",
|
||||||
|
"bitbucket",
|
||||||
|
}[p]
|
||||||
|
}
|
||||||
|
|
||||||
|
func PlatformFromString(s string) (Platform, error) {
|
||||||
|
switch strings.ToLower(s) {
|
||||||
|
case "", "unknown":
|
||||||
|
return UnknownPlatform, nil
|
||||||
|
case "none":
|
||||||
|
return NoPlatform, nil
|
||||||
|
case "github":
|
||||||
|
return GitHubPlatform, nil
|
||||||
|
case "gitlab":
|
||||||
|
return GitLabPlatform, nil
|
||||||
|
case "azuredevops":
|
||||||
|
return AzureDevOpsPlatform, nil
|
||||||
|
case "gitea":
|
||||||
|
return GiteaPlatform, nil
|
||||||
|
case "bitbucket":
|
||||||
|
return BitbucketPlatform, nil
|
||||||
|
default:
|
||||||
|
return UnknownPlatform, fmt.Errorf("invalid scm platform value: %s", s)
|
||||||
|
}
|
||||||
|
}
|
||||||
+22
-19
@@ -7,7 +7,7 @@ import (
|
|||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/logging"
|
"github.com/zricethezav/gitleaks/v8/logging"
|
||||||
"github.com/zricethezav/gitleaks/v8/report"
|
"github.com/zricethezav/gitleaks/v8/sources"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
@@ -20,30 +20,33 @@ var stdInCmd = &cobra.Command{
|
|||||||
Run: runStdIn,
|
Run: runStdIn,
|
||||||
}
|
}
|
||||||
|
|
||||||
func runStdIn(cmd *cobra.Command, args []string) {
|
func runStdIn(cmd *cobra.Command, _ []string) {
|
||||||
initConfig(".")
|
|
||||||
var (
|
|
||||||
findings []report.Finding
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
|
|
||||||
// setup config (aka, the thing that defines rules)
|
|
||||||
cfg := Config(cmd)
|
|
||||||
|
|
||||||
// start timer
|
// start timer
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
|
|
||||||
|
// setup config (aka, the thing that defines rules)
|
||||||
|
initConfig(".")
|
||||||
|
initDiagnostics()
|
||||||
|
|
||||||
|
cfg := Config(cmd)
|
||||||
|
|
||||||
|
// create detector
|
||||||
detector := Detector(cmd, cfg, "")
|
detector := Detector(cmd, cfg, "")
|
||||||
|
|
||||||
// set exit code
|
// parse flag(s)
|
||||||
exitCode, err := cmd.Flags().GetInt("exit-code")
|
exitCode := mustGetIntFlag(cmd, "exit-code")
|
||||||
if err != nil {
|
|
||||||
logging.Fatal().Err(err).Msg("could not get exit code")
|
findings, err := detector.DetectSource(
|
||||||
}
|
cmd.Context(),
|
||||||
|
&sources.File{
|
||||||
|
Content: os.Stdin,
|
||||||
|
MaxArchiveDepth: detector.MaxArchiveDepth,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
findings, err = detector.DetectReader(os.Stdin, 10)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// log fatal to exit, no need to continue since a report
|
// log fatal to exit, no need to continue since a report will not be
|
||||||
// will not be generated when scanning from a pipe...for now
|
// generated when scanning from a pipe...for now
|
||||||
logging.Fatal().Err(err).Msg("failed scan input from stdin")
|
logging.Fatal().Err(err).Msg("failed scan input from stdin")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+2
-3
@@ -4,10 +4,9 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/version"
|
||||||
)
|
)
|
||||||
|
|
||||||
var Version = "version is set by build process"
|
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
rootCmd.AddCommand(versionCmd)
|
rootCmd.AddCommand(versionCmd)
|
||||||
}
|
}
|
||||||
@@ -19,5 +18,5 @@ var versionCmd = &cobra.Command{
|
|||||||
}
|
}
|
||||||
|
|
||||||
func runVersion(cmd *cobra.Command, args []string) {
|
func runVersion(cmd *cobra.Command, args []string) {
|
||||||
fmt.Println(Version)
|
fmt.Println(version.Version)
|
||||||
}
|
}
|
||||||
+104
-43
@@ -1,11 +1,13 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"errors"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
regexp "github.com/wasilibs/go-re2"
|
ahocorasick "github.com/BobuSumisu/aho-corasick"
|
||||||
"golang.org/x/exp/maps"
|
"golang.org/x/exp/maps"
|
||||||
|
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
type AllowlistMatchCondition int
|
type AllowlistMatchCondition int
|
||||||
@@ -28,18 +30,15 @@ type Allowlist struct {
|
|||||||
// Short human readable description of the allowlist.
|
// Short human readable description of the allowlist.
|
||||||
Description string
|
Description string
|
||||||
|
|
||||||
// MatchCondition determines whether all criteria must match.
|
// MatchCondition determines whether all criteria must match. Defaults to "OR".
|
||||||
MatchCondition AllowlistMatchCondition
|
MatchCondition AllowlistMatchCondition
|
||||||
|
|
||||||
// Commits is a slice of commit SHAs that are allowed to be ignored. Defaults to "OR".
|
// Commits is a slice of commit SHAs that are allowed to be ignored.
|
||||||
Commits []string
|
Commits []string
|
||||||
|
|
||||||
// Paths is a slice of path regular expressions that are allowed to be ignored.
|
// Paths is a slice of path regular expressions that are allowed to be ignored.
|
||||||
Paths []*regexp.Regexp
|
Paths []*regexp.Regexp
|
||||||
|
|
||||||
// Regexes is slice of content regular expressions that are allowed to be ignored.
|
|
||||||
Regexes []*regexp.Regexp
|
|
||||||
|
|
||||||
// Can be `match` or `line`.
|
// Can be `match` or `line`.
|
||||||
//
|
//
|
||||||
// If `match` the _Regexes_ will be tested against the match of the _Rule.Regex_.
|
// If `match` the _Regexes_ will be tested against the match of the _Rule.Regex_.
|
||||||
@@ -49,70 +48,132 @@ type Allowlist struct {
|
|||||||
// If RegexTarget is empty, it will be tested against the found secret.
|
// If RegexTarget is empty, it will be tested against the found secret.
|
||||||
RegexTarget string
|
RegexTarget string
|
||||||
|
|
||||||
|
// Regexes is slice of content regular expressions that are allowed to be ignored.
|
||||||
|
Regexes []*regexp.Regexp
|
||||||
|
|
||||||
// StopWords is a slice of stop words that are allowed to be ignored.
|
// StopWords is a slice of stop words that are allowed to be ignored.
|
||||||
// This targets the _secret_, not the content of the regex match like the
|
// This targets the _secret_, not the content of the regex match like the
|
||||||
// Regexes slice.
|
// Regexes slice.
|
||||||
StopWords []string
|
StopWords []string
|
||||||
}
|
|
||||||
|
|
||||||
// CommitAllowed returns true if the commit is allowed to be ignored.
|
// validated is an internal flag to track whether `Validate()` has been called.
|
||||||
func (a *Allowlist) CommitAllowed(c string) bool {
|
validated bool
|
||||||
if c == "" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
for _, commit := range a.Commits {
|
|
||||||
if commit == c {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// PathAllowed returns true if the path is allowed to be ignored.
|
// commitMap is a normalized version of Commits, used for efficiency purposes.
|
||||||
func (a *Allowlist) PathAllowed(path string) bool {
|
// TODO: possible optimizations so that both short and long hashes work.
|
||||||
return anyRegexMatch(path, a.Paths)
|
commitMap map[string]struct{}
|
||||||
}
|
regexPat *regexp.Regexp
|
||||||
|
pathPat *regexp.Regexp
|
||||||
// RegexAllowed returns true if the regex is allowed to be ignored.
|
stopwordTrie *ahocorasick.Trie
|
||||||
func (a *Allowlist) RegexAllowed(secret string) bool {
|
|
||||||
return anyRegexMatch(secret, a.Regexes)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *Allowlist) ContainsStopWord(s string) bool {
|
|
||||||
s = strings.ToLower(s)
|
|
||||||
for _, stopWord := range a.StopWords {
|
|
||||||
if strings.Contains(s, strings.ToLower(stopWord)) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *Allowlist) Validate() error {
|
func (a *Allowlist) Validate() error {
|
||||||
|
if a.validated {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// Disallow empty allowlists.
|
// Disallow empty allowlists.
|
||||||
if len(a.Commits) == 0 &&
|
if len(a.Commits) == 0 &&
|
||||||
len(a.Paths) == 0 &&
|
len(a.Paths) == 0 &&
|
||||||
len(a.Regexes) == 0 &&
|
len(a.Regexes) == 0 &&
|
||||||
len(a.StopWords) == 0 {
|
len(a.StopWords) == 0 {
|
||||||
return fmt.Errorf("[[rules.allowlists]] must contain at least one check for: commits, paths, regexes, or stopwords")
|
return errors.New("must contain at least one check for: commits, paths, regexes, or stopwords")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deduplicate commits and stopwords.
|
// Deduplicate commits and stopwords.
|
||||||
if len(a.Commits) > 0 {
|
if len(a.Commits) > 0 {
|
||||||
uniqueCommits := make(map[string]struct{})
|
uniqueCommits := make(map[string]struct{})
|
||||||
for _, commit := range a.Commits {
|
for _, commit := range a.Commits {
|
||||||
uniqueCommits[commit] = struct{}{}
|
// Commits are case-insensitive.
|
||||||
|
uniqueCommits[strings.TrimSpace(strings.ToLower(commit))] = struct{}{}
|
||||||
}
|
}
|
||||||
a.Commits = maps.Keys(uniqueCommits)
|
a.Commits = maps.Keys(uniqueCommits)
|
||||||
|
a.commitMap = uniqueCommits
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(a.StopWords) > 0 {
|
if len(a.StopWords) > 0 {
|
||||||
uniqueStopwords := make(map[string]struct{})
|
uniqueStopwords := make(map[string]struct{})
|
||||||
for _, stopWord := range a.StopWords {
|
for _, stopWord := range a.StopWords {
|
||||||
uniqueStopwords[stopWord] = struct{}{}
|
uniqueStopwords[strings.ToLower(stopWord)] = struct{}{}
|
||||||
}
|
}
|
||||||
a.StopWords = maps.Keys(uniqueStopwords)
|
|
||||||
|
values := maps.Keys(uniqueStopwords)
|
||||||
|
a.StopWords = values
|
||||||
|
a.stopwordTrie = ahocorasick.NewTrieBuilder().AddStrings(values).Build()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Combine patterns into a single expression.
|
||||||
|
if len(a.Paths) > 0 {
|
||||||
|
a.pathPat = joinRegexOr(a.Paths)
|
||||||
|
}
|
||||||
|
if len(a.Regexes) > 0 {
|
||||||
|
a.regexPat = joinRegexOr(a.Regexes)
|
||||||
|
}
|
||||||
|
|
||||||
|
a.validated = true
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CommitAllowed returns true if the commit is allowed to be ignored.
|
||||||
|
func (a *Allowlist) CommitAllowed(c string) (bool, string) {
|
||||||
|
if a == nil || c == "" {
|
||||||
|
return false, ""
|
||||||
|
}
|
||||||
|
if a.commitMap != nil {
|
||||||
|
if _, ok := a.commitMap[strings.ToLower(c)]; ok {
|
||||||
|
return true, ""
|
||||||
|
}
|
||||||
|
} else if len(a.Commits) > 0 {
|
||||||
|
for _, commit := range a.Commits {
|
||||||
|
if commit == c {
|
||||||
|
return true, c
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false, ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// PathAllowed returns true if the path is allowed to be ignored.
|
||||||
|
func (a *Allowlist) PathAllowed(path string) bool {
|
||||||
|
if a == nil || path == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if a.pathPat != nil {
|
||||||
|
return a.pathPat.MatchString(path)
|
||||||
|
} else if len(a.Paths) > 0 {
|
||||||
|
return anyRegexMatch(path, a.Paths)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// RegexAllowed returns true if the regex is allowed to be ignored.
|
||||||
|
func (a *Allowlist) RegexAllowed(secret string) bool {
|
||||||
|
if a == nil || secret == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if a.regexPat != nil {
|
||||||
|
return a.regexPat.MatchString(secret)
|
||||||
|
} else if len(a.Regexes) > 0 {
|
||||||
|
return anyRegexMatch(secret, a.Regexes)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Allowlist) ContainsStopWord(s string) (bool, string) {
|
||||||
|
if a == nil || s == "" {
|
||||||
|
return false, ""
|
||||||
|
}
|
||||||
|
|
||||||
|
s = strings.ToLower(s)
|
||||||
|
if a.stopwordTrie != nil {
|
||||||
|
if m := a.stopwordTrie.MatchFirstString(s); m != nil {
|
||||||
|
return true, m.MatchString()
|
||||||
|
}
|
||||||
|
} else if len(a.StopWords) > 0 {
|
||||||
|
for _, stopWord := range a.StopWords {
|
||||||
|
if strings.Contains(s, stopWord) {
|
||||||
|
return true, stopWord
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false, ""
|
||||||
|
}
|
||||||
+231
-6
@@ -7,7 +7,8 @@ import (
|
|||||||
"github.com/google/go-cmp/cmp"
|
"github.com/google/go-cmp/cmp"
|
||||||
"github.com/google/go-cmp/cmp/cmpopts"
|
"github.com/google/go-cmp/cmp/cmpopts"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestCommitAllowed(t *testing.T) {
|
func TestCommitAllowed(t *testing.T) {
|
||||||
@@ -39,7 +40,8 @@ func TestCommitAllowed(t *testing.T) {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
assert.Equal(t, tt.commitAllowed, tt.allowlist.CommitAllowed(tt.commit))
|
isAllowed, _ := tt.allowlist.CommitAllowed(tt.commit)
|
||||||
|
assert.Equal(t, tt.commitAllowed, isAllowed)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,7 +105,7 @@ func TestValidate(t *testing.T) {
|
|||||||
}{
|
}{
|
||||||
"empty conditions": {
|
"empty conditions": {
|
||||||
input: Allowlist{},
|
input: Allowlist{},
|
||||||
wantErr: errors.New("[[rules.allowlists]] must contain at least one check for: commits, paths, regexes, or stopwords"),
|
wantErr: errors.New("must contain at least one check for: commits, paths, regexes, or stopwords"),
|
||||||
},
|
},
|
||||||
"deduplicated commits and stopwords": {
|
"deduplicated commits and stopwords": {
|
||||||
input: Allowlist{
|
input: Allowlist{
|
||||||
@@ -111,8 +113,8 @@ func TestValidate(t *testing.T) {
|
|||||||
StopWords: []string{"stopwordA", "stopwordB", "stopwordA"},
|
StopWords: []string{"stopwordA", "stopwordB", "stopwordA"},
|
||||||
},
|
},
|
||||||
expected: Allowlist{
|
expected: Allowlist{
|
||||||
Commits: []string{"commitA", "commitB"},
|
Commits: []string{"commita", "commitb"},
|
||||||
StopWords: []string{"stopwordA", "stopwordB"},
|
StopWords: []string{"stopworda", "stopwordb"},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -146,10 +148,233 @@ func TestValidate(t *testing.T) {
|
|||||||
opts = cmp.Options{
|
opts = cmp.Options{
|
||||||
cmp.Comparer(regexComparer),
|
cmp.Comparer(regexComparer),
|
||||||
cmpopts.SortSlices(arrayComparer),
|
cmpopts.SortSlices(arrayComparer),
|
||||||
|
cmpopts.IgnoreUnexported(Allowlist{}),
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
if diff := cmp.Diff(tt.input, tt.expected, opts); diff != "" {
|
if diff := cmp.Diff(tt.expected, tt.input, opts); diff != "" {
|
||||||
t.Errorf("diff: (-want +got)\n%s", diff)
|
t.Errorf("diff: (-want +got)\n%s", diff)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var benchCommitAllowlist = func() *Allowlist {
|
||||||
|
allowlist := Allowlist{
|
||||||
|
Commits: []string{
|
||||||
|
"ba1beca8ac634d8b202e0daffebecceeb6dda2fc",
|
||||||
|
"74b19abcd33ff3a6cac8aebdcfccacde9ad40f5c",
|
||||||
|
"11ed23ff2df37b2c114ac13dbd902e3bdb8b9c63",
|
||||||
|
"d39bcd0ebd3c9fb8d2f1bfbc98fc92bceeb3eed3",
|
||||||
|
"faf321cf8f9f2cf654fab12f72ef64e6ffb7237e",
|
||||||
|
"5486ce1abcdfcc862efeb6f5071a1ddef0fb3926",
|
||||||
|
"fbcfdbdffdabf1c0f627ecdfcda91ca8c1b533ce",
|
||||||
|
"3db86dce50f1d99fe820a4bf42ffedaefedb1bcf",
|
||||||
|
"18ccec6cb316ce1abed9e8ec262ecd3dd4a3e222",
|
||||||
|
"20f1cc29eaa028e7e6bcdc82f2103c1af3899c5c",
|
||||||
|
"d90b5572e9bdb0cebf5edc3ad412c38ecd6b8ca6",
|
||||||
|
"a0c7a0addf82d2a84babdd8be1f3cee887cb69cf",
|
||||||
|
"0c3c967d21bca179e2d60b738fab848be9a65a45",
|
||||||
|
"85cb3ac8817afad5ffde45a29036f4a1fa8af2eb",
|
||||||
|
"cb9c19a9dcb05bebca7dacbed9b8afefeb2dc5ad",
|
||||||
|
"4bac7b9fbdc851caf3c5f0cece85acaa3ebb7fd2",
|
||||||
|
"ad2bfd0c271bbb1ac991fdfefcabb6dcc43cb3f5",
|
||||||
|
"0c522c2750ec2fdf134721ea6000841fed5ffdd1",
|
||||||
|
"fedbf91dddc017f9994edc7f3a75dcd9eabfdd2c",
|
||||||
|
"9e5205bdeb080d84bfb25dfcc86dccc3fe5be499",
|
||||||
|
"b5476d7901b105c2fdb5fc87a9f4fabdb40daf81",
|
||||||
|
"f8fdbc509fb3c3ef1c1cbe8e70ac933ac4109cc3",
|
||||||
|
"92727ea97463cd55eed3069ab54483ba20b94f3c",
|
||||||
|
"e4a01ce6fdb6f6a39d2c781f7dcba3ae37973d0b",
|
||||||
|
"dcdd273bdf8159faf60bfca6b2a20a98a9985cf3",
|
||||||
|
"3f1efb9b7705cc1cae9ebeafa8eaf95ab79d6bea",
|
||||||
|
"20831ce7da9e2cb78ad8cd2a73ca693d8ffaee9c",
|
||||||
|
"edffec40aa85fbf947b20b3ffcfe6e7f6a94d017",
|
||||||
|
"cfbbc60acefdc1f04ad26e022fba21f72ce5c25b",
|
||||||
|
"3beac0da108cbb4fac1ebcd060ba2b67aafbefdd",
|
||||||
|
"21a87495e1f1f4ee9d9dfab1c3e5ffbe4b6e7dba",
|
||||||
|
"a2a3e8ba9dcae74d7bc1267f07fec3a44a0c9b08",
|
||||||
|
"abe2c2ff0a9befc1cbae77ea6aebf8d3a46ee68f",
|
||||||
|
"9f9e4cea3bee21deb769f830bcf76185eba76ab6",
|
||||||
|
"48e2f92ccdd1cb33e10eba117386cb054e06f2e0",
|
||||||
|
"4e10cc0ae797adce6cec0beda8782b28ba2dcf8c",
|
||||||
|
"7d6eb5bc7bbee783ab012ee290f8b9acabe38367",
|
||||||
|
"bc5d1b99fd2cbacb225e574fd05c57a3f44ca35c",
|
||||||
|
"9a3ea6fd3dcfd135ea3b9bc63ab6494f5c54faaf",
|
||||||
|
"fc62eec1f10e646ec9a8dacaddf1becae7e31823",
|
||||||
|
"fd01d7f4dab422fba5b9abfeacee14aad6db0dee",
|
||||||
|
"d7a2bcbcab6a4f4af02dde8ceeef5b6ab0fd6ca5",
|
||||||
|
"0b1bf0ebfc1cca19eeb029cfb8e4abd8e72d82df",
|
||||||
|
"a1ea3f771dfbae1cadbc67c803b8b07081f3fdd0",
|
||||||
|
"78dfa84c70545f295b3b8fa3f8bd53d316ff682e",
|
||||||
|
"ca595eebf56ad6f118be2c5ddbeadac675a588ad",
|
||||||
|
"faadceaec7d0bb9cbef7e7f6cddc3a0fdb8e33b8",
|
||||||
|
"0b006e37964c7b1e3cdbafd21fe8e887886cb909",
|
||||||
|
"dffb3dfb72fa42ed49a69dae3838eaaf2a957ee0",
|
||||||
|
"2d927ebda284a25fb2cd8fc0dd42c9b7d333db5a",
|
||||||
|
"ffca0cdcbe9e33fd18a3bf692ea0f2a62d685aa4",
|
||||||
|
"ac0d9a8adbe32cbe7f99fdeccf22b5bf767d06fa",
|
||||||
|
"f4a2a0a2833f4cbcc2db2accd7cc4feacdeeeaed",
|
||||||
|
"5f4a1e0dcbd49ed99eadf4bf837f1efafea663c1",
|
||||||
|
"3e69fb30ea6761771f877d82ef8ee799eb1f56a0",
|
||||||
|
"2e13cb4dec42ca80918e2bdefb5df96bf9b1eebc",
|
||||||
|
"d480ed3e25cb82782bb6b3f0fffce8f7c3d9840b",
|
||||||
|
"7bd34bf663bd5900f0be9accb2091e3dc4a378bc",
|
||||||
|
"a9fdc3ccc7cfd3b2a73b55b957bbe73beedba2ea",
|
||||||
|
"b7ca933acc3ef5c8c5bfaede6bfc4f9acc7f4f39",
|
||||||
|
"248a04fea1bfc38f4a1b76ea4ce399ef0affe4cb",
|
||||||
|
"8ae496b4fb06c46ae5bfcdceda5e9773ca9ce25b",
|
||||||
|
"0ac468471f71e8d17c21eb9fe4d922549e13bc3a",
|
||||||
|
"db082f214cdbff93cdaefebabae455f2ed994730",
|
||||||
|
"df0c6eabe5ccffed0bf840f3c45a8fdf39c04f9b",
|
||||||
|
"aacaadfd5bd1e9efd6fc8a9b7ad8fe93ec3bbf23",
|
||||||
|
"4e9cbeaabc66d01da99cd85cbaf8db5bfaccf5c4",
|
||||||
|
"28b39fd14b2c8dbeab86aea69de0b5ccdf4ff7b2",
|
||||||
|
"a20ebfbef4c75e906a114eaad6a67deadb810ed9",
|
||||||
|
"f8fd3b4cd75b6fc28e21289e6d4ef7c4c7f22f68",
|
||||||
|
"ccf7e03c5f5c7d6fdbd9fbde2fd342ae15cbbe4e",
|
||||||
|
"cdcbcfe7c6d4cee31a27f338d1ff66d3cad4bbd5",
|
||||||
|
"d7c03aba693ba8de8aaea7fa9d8d46a733cd5989",
|
||||||
|
"48e3f4abb26eb44eefcaf3f188cea00cce46ddc1",
|
||||||
|
"c1a9c25e5e29804abbc8a0fccf1faf384fea28a5",
|
||||||
|
"f9e090c6b2af0ee3bde57f4a0352f5b02e675d35",
|
||||||
|
"1df2354e9eee4934c34dcbd2de0b1df9b5dcadac",
|
||||||
|
"7da5ad4d8fa965ea4aa4613a9dc4eabdc3406eeb",
|
||||||
|
"fe33bfb676572e7fafd8ae9ea88e0efa3c109bdd",
|
||||||
|
"fefeea80b187eefce0a9c184cb76976c2fcef98a",
|
||||||
|
"eea8efae44ab9eb43a5954df7fa63bb55fa1d8dc",
|
||||||
|
"f559c7bbe6b6bfba56e7f362604c721c2fee6d0d",
|
||||||
|
"bf1dbe006b93fb443aebbe77a2c9cfdfc3f6a6a0",
|
||||||
|
"cfd00d87f7bc44ed7bdcebbf493869a495ebfef8",
|
||||||
|
"7ca45a388fd9aaeb8ed7701c2af2beff9e52eebb",
|
||||||
|
"ca47c2fdb73b2d39a1eab115dffa1ef7a5ffacd0",
|
||||||
|
"cc0954dfddaabb996abc78c28dff83f7e3edb828",
|
||||||
|
"ad4adc1195dabcfaf0f7eaac4f3f3f6b152d7fd4",
|
||||||
|
"ab3e6b6ed2eb6dcd4ae4fd0db76efdecd72ecfaa",
|
||||||
|
"d16ccd31d433f7a41eceb7d544081c72b4d9bf3e",
|
||||||
|
"d0dbe09bb150bbd5bb4b85adc273df87350e7e6c",
|
||||||
|
"492bbbcaf6edd864dd3ca0aee5d4d60b1cd4214b",
|
||||||
|
"d73dbbe7a9effb828793a3adad04cecb1843ccbd",
|
||||||
|
"89b12dcbfc40e30ddecd7a19e0cf1e32a29ebccb",
|
||||||
|
"1cd815bd965ee0fd2e15bbe28c94688f15ebb3ad",
|
||||||
|
"a7f9b3babda7abfe0316bf7aeded7df7cfcf7bdf",
|
||||||
|
"9e832d5ebecc2e5aead9b5cdcdd6d2ba4dfeaee7",
|
||||||
|
"43fa54761faa5f8beffe9acfd402fcd24dfede71",
|
||||||
|
"dada4b08ae4aa37cff754b4ca29ebc134c54bac1",
|
||||||
|
"1b708f1fad29cc62bc39ae5dda8e9124acc00d2d",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
_ = allowlist.Validate()
|
||||||
|
return &allowlist
|
||||||
|
}()
|
||||||
|
|
||||||
|
func BenchmarkCommitAllowed(b *testing.B) {
|
||||||
|
for n := 0; n < b.N; n++ {
|
||||||
|
ok, _ := benchCommitAllowlist.CommitAllowed("d0dbe09bb150bbd5bb4b85adc273df87350e7e6c")
|
||||||
|
assert.True(b, ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkCommitNotAllowed(b *testing.B) {
|
||||||
|
for n := 0; n < b.N; n++ {
|
||||||
|
ok, _ := benchCommitAllowlist.CommitAllowed("5fe58bf0b0be1735ad27aa6053b56323a905c223")
|
||||||
|
assert.False(b, ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var benchRegexAllowlist = func() *Allowlist {
|
||||||
|
a := Allowlist{
|
||||||
|
RegexTarget: "match",
|
||||||
|
Regexes: []*regexp.Regexp{
|
||||||
|
// Based on patterns from `generic.go`
|
||||||
|
regexp.MustCompile(`(?i)access(ibility|or)`),
|
||||||
|
regexp.MustCompile(`(?i)access[_.-]?id`),
|
||||||
|
regexp.MustCompile(`(?i)random[_.-]?access`),
|
||||||
|
regexp.MustCompile(`(?i)api[_.-]?(id|name|version)`),
|
||||||
|
regexp.MustCompile(`(?i)rapid|capital`),
|
||||||
|
regexp.MustCompile(`(?i)[a-z0-9-]*?api[a-z0-9-]*?:jar:`),
|
||||||
|
regexp.MustCompile(`(?i)author`),
|
||||||
|
regexp.MustCompile(`(?i)X-MS-Exchange-Organization-Auth`),
|
||||||
|
regexp.MustCompile(`(?i)Authentication-Results`),
|
||||||
|
regexp.MustCompile(`(?i)(credentials?[_.-]?id|withCredentials)`),
|
||||||
|
regexp.MustCompile(`(?i)(bucket|foreign|hot|idx|natural|primary|pub(lic)?|schema|sequence)[_.-]?key`),
|
||||||
|
regexp.MustCompile(`(?i)key[_.-]?(alias|board|code|frame|id|length|mesh|name|pair|ring|selector|signature|size|stone|storetype|word|up|down|left|right)`),
|
||||||
|
regexp.MustCompile(`(?i)key[_.-]?vault[_.-]?(id|name)|keyVaultToStoreSecrets`),
|
||||||
|
regexp.MustCompile(`(?i)key(store|tab)[_.-]?(file|path)`),
|
||||||
|
regexp.MustCompile(`(?i)issuerkeyhash`),
|
||||||
|
regexp.MustCompile(`(?i)(?-i:[DdMm]onkey|[DM]ONKEY)|keying`),
|
||||||
|
regexp.MustCompile(`(?i)(secret)[_.-]?(length|name|size)`),
|
||||||
|
regexp.MustCompile(`(?i)UserSecretsId`),
|
||||||
|
regexp.MustCompile(`(?i)(io\.jsonwebtoken[ \t]?:[ \t]?[\w-]+)`),
|
||||||
|
regexp.MustCompile(`(?i)(api|credentials|token)[_.-]?(endpoint|ur[il])`),
|
||||||
|
regexp.MustCompile(`(?i)public[_.-]?token`),
|
||||||
|
regexp.MustCompile(`(?i)(key|token)[_.-]?file`),
|
||||||
|
regexp.MustCompile(`([A-Z_]+=\n[A-Z_]+=|[a-z_]+=\n[a-z_]+=)(\n|\z)`),
|
||||||
|
regexp.MustCompile(`([A-Z.]+=\n[A-Z.]+=|[a-z.]+=\n[a-z.]+=)(\n|\z)`),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
_ = a.Validate()
|
||||||
|
return &a
|
||||||
|
}()
|
||||||
|
|
||||||
|
func BenchmarkRegexAllowed(b *testing.B) {
|
||||||
|
for n := 0; n < b.N; n++ {
|
||||||
|
ok := benchRegexAllowlist.RegexAllowed(`environment {
|
||||||
|
CREDENTIALS_ID = "K8S_CRED"
|
||||||
|
}`)
|
||||||
|
assert.True(b, ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkRegexNotAllowed(b *testing.B) {
|
||||||
|
for n := 0; n < b.N; n++ {
|
||||||
|
ok := benchRegexAllowlist.RegexAllowed(`"credentials" : "0afae57f3ccfd9d7f5767067bc48b30f719e271ba470488056e37ab35d4b6506"`)
|
||||||
|
assert.False(b, ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var benchPathAllowlist = func() *Allowlist {
|
||||||
|
a := Allowlist{
|
||||||
|
Paths: []*regexp.Regexp{
|
||||||
|
// Copied from `base/config.go`
|
||||||
|
regexp.MustCompile(`gitleaks\.toml`),
|
||||||
|
regexp.MustCompile(`(?i)\.(bmp|gif|jpe?g|svg|tiff?)$`),
|
||||||
|
regexp.MustCompile(`\.(eot|[ot]tf|woff2?)$`),
|
||||||
|
regexp.MustCompile(`(.*?)(doc|docx|zip|xls|pdf|bin|socket|vsidx|v2|suo|wsuo|.dll|pdb|exe|gltf)$`),
|
||||||
|
regexp.MustCompile(`go\.(mod|sum|work(\.sum)?)$`),
|
||||||
|
regexp.MustCompile(`(^|/)vendor/modules\.txt$`),
|
||||||
|
regexp.MustCompile(`(^|/)vendor/(github\.com|golang\.org/x|google\.golang\.org|gopkg\.in|istio\.io|k8s\.io|sigs\.k8s\.io)(/.*)?$`),
|
||||||
|
regexp.MustCompile(`(^|/)gradlew(\.bat)?$`),
|
||||||
|
regexp.MustCompile(`(^|/)gradle\.lockfile$`),
|
||||||
|
regexp.MustCompile(`(^|/)mvnw(\.cmd)?$`),
|
||||||
|
regexp.MustCompile(`(^|/)\.mvn/wrapper/MavenWrapperDownloader\.java$`),
|
||||||
|
regexp.MustCompile(`(^|/)node_modules(/.*)?$`),
|
||||||
|
regexp.MustCompile(`(^|/)(npm-shrinkwrap\.json|package-lock\.json|pnpm-lock\.yaml|yarn\.lock)$`),
|
||||||
|
regexp.MustCompile(`(^|/)bower_components(/.*)?$`),
|
||||||
|
regexp.MustCompile(`(^|/)(angular|bootstrap|jquery(-?ui)?|plotly|swagger-?ui)[a-zA-Z0-9.-]*(\.min)?\.js(\.map)?$`),
|
||||||
|
regexp.MustCompile(`(^|/)javascript\.json$`),
|
||||||
|
regexp.MustCompile(`(^|/)(Pipfile|poetry)\.lock$`),
|
||||||
|
regexp.MustCompile(`(?i)/?(v?env|virtualenv)/lib(64)?(/.*)?$`),
|
||||||
|
regexp.MustCompile(`(?i)(^|/)(lib(64)?/python[23](\.\d{1,2})+|python/[23](\.\d{1,2})+/lib(64)?)(/.*)?$`),
|
||||||
|
regexp.MustCompile(`(?i)(^|/)[a-z0-9_.]+-[0-9.]+\.dist-info(/.+)?$`),
|
||||||
|
regexp.MustCompile(`(^|/)vendor/(bundle|ruby)(/.*?)?$`),
|
||||||
|
regexp.MustCompile(`\.gem$`),
|
||||||
|
regexp.MustCompile(`verification-metadata\.xml`),
|
||||||
|
regexp.MustCompile(`Database.refactorlog`),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
_ = a.Validate()
|
||||||
|
return &a
|
||||||
|
}()
|
||||||
|
|
||||||
|
func BenchmarkPathAllowed(b *testing.B) {
|
||||||
|
for n := 0; n < b.N; n++ {
|
||||||
|
ok := benchPathAllowlist.PathAllowed(`src/main/resources/static/js/jquery-ui-1.10.4.min.js`)
|
||||||
|
assert.True(b, ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkPathNotAllowed(b *testing.B) {
|
||||||
|
for n := 0; n < b.N; n++ {
|
||||||
|
ok := benchPathAllowlist.PathAllowed(`azure_scale_templates/sub_modules/vpc_template/inputs.auto.tfvars.json_backup`)
|
||||||
|
assert.False(b, ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
+258
-131
@@ -2,22 +2,27 @@ package config
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
_ "embed"
|
_ "embed"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
gv "github.com/hashicorp/go-version"
|
||||||
"github.com/spf13/viper"
|
"github.com/spf13/viper"
|
||||||
regexp "github.com/wasilibs/go-re2"
|
|
||||||
|
|
||||||
"github.com/zricethezav/gitleaks/v8/logging"
|
"github.com/zricethezav/gitleaks/v8/logging"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
|
"github.com/zricethezav/gitleaks/v8/version"
|
||||||
)
|
)
|
||||||
|
|
||||||
//go:embed gitleaks.toml
|
var (
|
||||||
var DefaultConfig string
|
//go:embed gitleaks.toml
|
||||||
|
DefaultConfig string
|
||||||
|
|
||||||
// use to keep track of how many configs we can extend
|
// use to keep track of how many configs we can extend
|
||||||
// yea I know, globals bad
|
// yea I know, globals bad
|
||||||
var extendDepth int
|
extendDepth int
|
||||||
|
)
|
||||||
|
|
||||||
const maxExtendDepth = 2
|
const maxExtendDepth = 2
|
||||||
|
|
||||||
@@ -25,29 +30,42 @@ const maxExtendDepth = 2
|
|||||||
// to parse the config file. This struct does not include regular expressions.
|
// to parse the config file. This struct does not include regular expressions.
|
||||||
// It is used as an intermediary to convert the Viper config to the Config struct.
|
// It is used as an intermediary to convert the Viper config to the Config struct.
|
||||||
type ViperConfig struct {
|
type ViperConfig struct {
|
||||||
|
Title string
|
||||||
Description string
|
Description string
|
||||||
Extend Extend
|
Extend Extend
|
||||||
Rules []struct {
|
Rules []struct {
|
||||||
ID string
|
ID string
|
||||||
Description string
|
Description string
|
||||||
|
Path string
|
||||||
Regex string
|
Regex string
|
||||||
SecretGroup int
|
SecretGroup int
|
||||||
Entropy float64
|
Entropy float64
|
||||||
Keywords []string
|
Keywords []string
|
||||||
Path string
|
|
||||||
Tags []string
|
Tags []string
|
||||||
|
|
||||||
// Deprecated: this is a shim for backwards-compatibility. It should be removed in 9.x.
|
// Deprecated: this is a shim for backwards-compatibility.
|
||||||
AllowList *viperRuleAllowlist
|
// TODO: Remove this in 9.x.
|
||||||
Allowlists []viperRuleAllowlist
|
AllowList *viperRuleAllowlist
|
||||||
}
|
|
||||||
Allowlist struct {
|
Allowlists []*viperRuleAllowlist
|
||||||
Commits []string
|
Required []*viperRequired
|
||||||
Paths []string
|
SkipReport bool
|
||||||
RegexTarget string
|
|
||||||
Regexes []string
|
|
||||||
StopWords []string
|
|
||||||
}
|
}
|
||||||
|
// Deprecated: this is a shim for backwards-compatibility.
|
||||||
|
// TODO: Remove this in 9.x.
|
||||||
|
AllowList *viperGlobalAllowlist
|
||||||
|
|
||||||
|
Allowlists []*viperGlobalAllowlist
|
||||||
|
|
||||||
|
MinVersion string
|
||||||
|
|
||||||
|
configPath string
|
||||||
|
}
|
||||||
|
|
||||||
|
type viperRequired struct {
|
||||||
|
ID string
|
||||||
|
WithinLines *int `mapstructure:"withinLines"`
|
||||||
|
WithinColumns *int `mapstructure:"withinColumns"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type viperRuleAllowlist struct {
|
type viperRuleAllowlist struct {
|
||||||
@@ -60,6 +78,11 @@ type viperRuleAllowlist struct {
|
|||||||
StopWords []string
|
StopWords []string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type viperGlobalAllowlist struct {
|
||||||
|
TargetRules []string
|
||||||
|
viperRuleAllowlist `mapstructure:",squash"`
|
||||||
|
}
|
||||||
|
|
||||||
// Config is a configuration struct that contains rules and an allowlist if present.
|
// Config is a configuration struct that contains rules and an allowlist if present.
|
||||||
type Config struct {
|
type Config struct {
|
||||||
Title string
|
Title string
|
||||||
@@ -67,11 +90,11 @@ type Config struct {
|
|||||||
Path string
|
Path string
|
||||||
Description string
|
Description string
|
||||||
Rules map[string]Rule
|
Rules map[string]Rule
|
||||||
Allowlist Allowlist
|
|
||||||
Keywords map[string]struct{}
|
Keywords map[string]struct{}
|
||||||
|
|
||||||
// used to keep sarif results consistent
|
// used to keep sarif results consistent
|
||||||
OrderedRules []string
|
OrderedRules []string
|
||||||
|
Allowlists []*Allowlist
|
||||||
|
MinVersion string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Extend is a struct that allows users to define how they want their
|
// Extend is a struct that allows users to define how they want their
|
||||||
@@ -85,13 +108,24 @@ type Extend struct {
|
|||||||
|
|
||||||
func (vc *ViperConfig) Translate() (Config, error) {
|
func (vc *ViperConfig) Translate() (Config, error) {
|
||||||
var (
|
var (
|
||||||
keywords = make(map[string]struct{})
|
keywords = make(map[string]struct{})
|
||||||
orderedRules []string
|
orderedRules []string
|
||||||
rulesMap = make(map[string]Rule)
|
rulesMap = make(map[string]Rule)
|
||||||
|
ruleAllowlists = make(map[string][]*Allowlist)
|
||||||
)
|
)
|
||||||
|
|
||||||
// Validate individual rules.
|
// Validate individual rules.
|
||||||
for _, vr := range vc.Rules {
|
for _, vr := range vc.Rules {
|
||||||
|
var (
|
||||||
|
pathPat *regexp.Regexp
|
||||||
|
regexPat *regexp.Regexp
|
||||||
|
)
|
||||||
|
if vr.Path != "" {
|
||||||
|
pathPat = regexp.MustCompile(vr.Path)
|
||||||
|
}
|
||||||
|
if vr.Regex != "" {
|
||||||
|
regexPat = regexp.MustCompile(vr.Regex)
|
||||||
|
}
|
||||||
if vr.Keywords == nil {
|
if vr.Keywords == nil {
|
||||||
vr.Keywords = []string{}
|
vr.Keywords = []string{}
|
||||||
} else {
|
} else {
|
||||||
@@ -101,132 +135,233 @@ func (vc *ViperConfig) Translate() (Config, error) {
|
|||||||
vr.Keywords[i] = keyword
|
vr.Keywords[i] = keyword
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if vr.Tags == nil {
|
if vr.Tags == nil {
|
||||||
vr.Tags = []string{}
|
vr.Tags = []string{}
|
||||||
}
|
}
|
||||||
|
|
||||||
var configRegex *regexp.Regexp
|
|
||||||
var configPathRegex *regexp.Regexp
|
|
||||||
if vr.Regex != "" {
|
|
||||||
configRegex = regexp.MustCompile(vr.Regex)
|
|
||||||
}
|
|
||||||
if vr.Path != "" {
|
|
||||||
configPathRegex = regexp.MustCompile(vr.Path)
|
|
||||||
}
|
|
||||||
|
|
||||||
cr := Rule{
|
cr := Rule{
|
||||||
RuleID: vr.ID,
|
RuleID: vr.ID,
|
||||||
Description: vr.Description,
|
Description: vr.Description,
|
||||||
Regex: configRegex,
|
Regex: regexPat,
|
||||||
SecretGroup: vr.SecretGroup,
|
SecretGroup: vr.SecretGroup,
|
||||||
Entropy: vr.Entropy,
|
Entropy: vr.Entropy,
|
||||||
Path: configPathRegex,
|
Path: pathPat,
|
||||||
Keywords: vr.Keywords,
|
Keywords: vr.Keywords,
|
||||||
Tags: vr.Tags,
|
Tags: vr.Tags,
|
||||||
|
SkipReport: vr.SkipReport,
|
||||||
}
|
}
|
||||||
// Parse the allowlist, including the older format for backwards compatibility.
|
|
||||||
|
// Parse the rule allowlists, including the older format for backwards compatibility.
|
||||||
if vr.AllowList != nil {
|
if vr.AllowList != nil {
|
||||||
|
// TODO: Remove this in v9.
|
||||||
if len(vr.Allowlists) > 0 {
|
if len(vr.Allowlists) > 0 {
|
||||||
return Config{}, fmt.Errorf("%s: [rules.allowlist] is deprecated, it cannot be used alongside [[rules.allowlist]]", cr.RuleID)
|
return Config{}, fmt.Errorf("%s: [rules.allowlist] is deprecated, it cannot be used alongside [[rules.allowlist]]", cr.RuleID)
|
||||||
}
|
}
|
||||||
vr.Allowlists = append(vr.Allowlists, *vr.AllowList)
|
vr.Allowlists = append(vr.Allowlists, vr.AllowList)
|
||||||
}
|
}
|
||||||
for _, a := range vr.Allowlists {
|
for _, a := range vr.Allowlists {
|
||||||
var condition AllowlistMatchCondition
|
allowlist, err := vc.parseAllowlist(a)
|
||||||
c := strings.ToUpper(a.Condition)
|
if err != nil {
|
||||||
switch c {
|
return Config{}, fmt.Errorf("%s: [[rules.allowlists]] %w", cr.RuleID, err)
|
||||||
case "AND", "&&":
|
|
||||||
condition = AllowlistMatchAnd
|
|
||||||
case "", "OR", "||":
|
|
||||||
condition = AllowlistMatchOr
|
|
||||||
default:
|
|
||||||
return Config{}, fmt.Errorf("%s: unknown allowlist condition '%s' (expected 'and', 'or')", cr.RuleID, c)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate the target.
|
|
||||||
if a.RegexTarget != "" {
|
|
||||||
switch a.RegexTarget {
|
|
||||||
case "secret":
|
|
||||||
a.RegexTarget = ""
|
|
||||||
case "match", "line":
|
|
||||||
// do nothing
|
|
||||||
default:
|
|
||||||
return Config{}, fmt.Errorf("%s: unknown allowlist |regexTarget| '%s' (expected 'match', 'line')", cr.RuleID, a.RegexTarget)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var allowlistRegexes []*regexp.Regexp
|
|
||||||
for _, a := range a.Regexes {
|
|
||||||
allowlistRegexes = append(allowlistRegexes, regexp.MustCompile(a))
|
|
||||||
}
|
|
||||||
var allowlistPaths []*regexp.Regexp
|
|
||||||
for _, a := range a.Paths {
|
|
||||||
allowlistPaths = append(allowlistPaths, regexp.MustCompile(a))
|
|
||||||
}
|
|
||||||
|
|
||||||
allowlist := Allowlist{
|
|
||||||
MatchCondition: condition,
|
|
||||||
RegexTarget: a.RegexTarget,
|
|
||||||
Regexes: allowlistRegexes,
|
|
||||||
Paths: allowlistPaths,
|
|
||||||
Commits: a.Commits,
|
|
||||||
StopWords: a.StopWords,
|
|
||||||
}
|
|
||||||
if err := allowlist.Validate(); err != nil {
|
|
||||||
return Config{}, fmt.Errorf("%s: %w", cr.RuleID, err)
|
|
||||||
}
|
}
|
||||||
cr.Allowlists = append(cr.Allowlists, allowlist)
|
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)
|
orderedRules = append(orderedRules, cr.RuleID)
|
||||||
rulesMap[cr.RuleID] = cr
|
rulesMap[cr.RuleID] = cr
|
||||||
}
|
}
|
||||||
var allowlistRegexes []*regexp.Regexp
|
|
||||||
for _, a := range vc.Allowlist.Regexes {
|
// after all the rules have been processed, let's ensure the required rules
|
||||||
allowlistRegexes = append(allowlistRegexes, regexp.MustCompile(a))
|
// actually exist.
|
||||||
}
|
for _, r := range rulesMap {
|
||||||
var allowlistPaths []*regexp.Regexp
|
for _, rr := range r.RequiredRules {
|
||||||
for _, a := range vc.Allowlist.Paths {
|
if _, ok := rulesMap[rr.RuleID]; !ok {
|
||||||
allowlistPaths = append(allowlistPaths, regexp.MustCompile(a))
|
return Config{}, fmt.Errorf("%s: [[rules.required]] rule ID '%s' does not exist", r.RuleID, rr.RuleID)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Assemble the config.
|
||||||
c := Config{
|
c := Config{
|
||||||
Description: vc.Description,
|
Title: vc.Title,
|
||||||
Extend: vc.Extend,
|
Description: vc.Description,
|
||||||
Rules: rulesMap,
|
Extend: vc.Extend,
|
||||||
Allowlist: Allowlist{
|
Rules: rulesMap,
|
||||||
RegexTarget: vc.Allowlist.RegexTarget,
|
|
||||||
Regexes: allowlistRegexes,
|
|
||||||
Paths: allowlistPaths,
|
|
||||||
Commits: vc.Allowlist.Commits,
|
|
||||||
StopWords: vc.Allowlist.StopWords,
|
|
||||||
},
|
|
||||||
Keywords: keywords,
|
Keywords: keywords,
|
||||||
OrderedRules: orderedRules,
|
OrderedRules: orderedRules,
|
||||||
|
MinVersion: vc.MinVersion,
|
||||||
}
|
}
|
||||||
|
|
||||||
if maxExtendDepth != extendDepth {
|
if extendDepth > 0 {
|
||||||
|
// annoying hack to set the current config with the extended path
|
||||||
|
// since if extendDepth > 0 we are operating an extended config.
|
||||||
|
c.Path = vc.configPath
|
||||||
|
} else {
|
||||||
|
// I don't love this
|
||||||
|
c.Path = viper.ConfigFileUsed()
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := validateMinVersion(c.MinVersion, c.Path); err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse the config allowlists, including the older format for backwards compatibility.
|
||||||
|
if vc.AllowList != nil {
|
||||||
|
// TODO: Remove this in v9.
|
||||||
|
if len(vc.Allowlists) > 0 {
|
||||||
|
return Config{}, errors.New("[allowlist] is deprecated, it cannot be used alongside [[allowlists]]")
|
||||||
|
}
|
||||||
|
vc.Allowlists = append(vc.Allowlists, vc.AllowList)
|
||||||
|
}
|
||||||
|
for _, a := range vc.Allowlists {
|
||||||
|
allowlist, err := vc.parseAllowlist(&a.viperRuleAllowlist)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, fmt.Errorf("[[allowlists]] %w", err)
|
||||||
|
}
|
||||||
|
// Allowlists with |targetRules| aren't added to the global list.
|
||||||
|
if len(a.TargetRules) > 0 {
|
||||||
|
for _, ruleID := range a.TargetRules {
|
||||||
|
// It's not possible to validate |ruleID| until after extend.
|
||||||
|
ruleAllowlists[ruleID] = append(ruleAllowlists[ruleID], allowlist)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
c.Allowlists = append(c.Allowlists, allowlist)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
currentExtendDepth := extendDepth
|
||||||
|
if maxExtendDepth != currentExtendDepth {
|
||||||
// disallow both usedefault and path from being set
|
// disallow both usedefault and path from being set
|
||||||
if c.Extend.Path != "" && c.Extend.UseDefault {
|
if c.Extend.Path != "" && c.Extend.UseDefault {
|
||||||
logging.Fatal().Msg("unable to load config due to extend.path and extend.useDefault being set")
|
return Config{}, errors.New("unable to load config due to extend.path and extend.useDefault being set")
|
||||||
}
|
}
|
||||||
if c.Extend.UseDefault {
|
if c.Extend.UseDefault {
|
||||||
c.extendDefault()
|
if err := c.extendDefault(vc); err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
} else if c.Extend.Path != "" {
|
} else if c.Extend.Path != "" {
|
||||||
c.extendPath()
|
if err := c.extendPath(vc); err != nil {
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate the rules after everything has been assembled (including extended configs).
|
|
||||||
if extendDepth == 0 {
|
|
||||||
for _, rule := range c.Rules {
|
|
||||||
if err := rule.Validate(); err != nil {
|
|
||||||
return Config{}, err
|
return Config{}, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Validate the rules after everything has been assembled (including extended configs).
|
||||||
|
if currentExtendDepth == 0 {
|
||||||
|
for _, rule := range c.Rules {
|
||||||
|
if err := rule.Validate(); err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Populate targeted configs.
|
||||||
|
for ruleID, allowlists := range ruleAllowlists {
|
||||||
|
rule, ok := c.Rules[ruleID]
|
||||||
|
if !ok {
|
||||||
|
return Config{}, fmt.Errorf("[[allowlists]] target rule ID '%s' does not exist", ruleID)
|
||||||
|
}
|
||||||
|
rule.Allowlists = append(rule.Allowlists, allowlists...)
|
||||||
|
c.Rules[ruleID] = rule
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return c, nil
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func validateMinVersion(minVer string, configPath string) error {
|
||||||
|
if minVer == "" {
|
||||||
|
logging.Debug().Str("config path", configPath).
|
||||||
|
Msg("no minVersion specified in config... consider adding minVersion to ensure compatibility.")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if version.Version == version.DefaultMsg {
|
||||||
|
logging.Debug().
|
||||||
|
Str("required", minVer).
|
||||||
|
Msg("dev build, skipping config version check.")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
minSemVer, err := gv.NewSemver(minVer)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("invalid minVersion '%s': %w", minVer, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
currentSemVer, err := gv.NewSemver(version.Version)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("unable to parse current version: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if currentSemVer.LessThan(minSemVer) {
|
||||||
|
logging.Warn().
|
||||||
|
Str("required", minVer).
|
||||||
|
Str("current", version.Version).
|
||||||
|
Str("config path", configPath).
|
||||||
|
Msg("config requires a newer Gitleaks version...")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (vc *ViperConfig) parseAllowlist(a *viperRuleAllowlist) (*Allowlist, error) {
|
||||||
|
var matchCondition AllowlistMatchCondition
|
||||||
|
switch strings.ToUpper(a.Condition) {
|
||||||
|
case "AND", "&&":
|
||||||
|
matchCondition = AllowlistMatchAnd
|
||||||
|
case "", "OR", "||":
|
||||||
|
matchCondition = AllowlistMatchOr
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unknown allowlist |condition| '%s' (expected 'and', 'or')", a.Condition)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate the target.
|
||||||
|
regexTarget := a.RegexTarget
|
||||||
|
if regexTarget != "" {
|
||||||
|
switch regexTarget {
|
||||||
|
case "secret":
|
||||||
|
regexTarget = ""
|
||||||
|
case "match", "line":
|
||||||
|
// do nothing
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unknown allowlist |regexTarget| '%s' (expected 'match', 'line')", regexTarget)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var allowlistRegexes []*regexp.Regexp
|
||||||
|
for _, a := range a.Regexes {
|
||||||
|
allowlistRegexes = append(allowlistRegexes, regexp.MustCompile(a))
|
||||||
|
}
|
||||||
|
var allowlistPaths []*regexp.Regexp
|
||||||
|
for _, a := range a.Paths {
|
||||||
|
allowlistPaths = append(allowlistPaths, regexp.MustCompile(a))
|
||||||
|
}
|
||||||
|
|
||||||
|
allowlist := &Allowlist{
|
||||||
|
Description: a.Description,
|
||||||
|
MatchCondition: matchCondition,
|
||||||
|
Commits: a.Commits,
|
||||||
|
Paths: allowlistPaths,
|
||||||
|
RegexTarget: regexTarget,
|
||||||
|
Regexes: allowlistRegexes,
|
||||||
|
StopWords: a.StopWords,
|
||||||
|
}
|
||||||
|
if err := allowlist.Validate(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return allowlist, nil
|
||||||
|
}
|
||||||
|
|
||||||
func (c *Config) GetOrderedRules() []Rule {
|
func (c *Config) GetOrderedRules() []Rule {
|
||||||
var orderedRules []Rule
|
var orderedRules []Rule
|
||||||
for _, id := range c.OrderedRules {
|
for _, id := range c.OrderedRules {
|
||||||
@@ -237,47 +372,45 @@ func (c *Config) GetOrderedRules() []Rule {
|
|||||||
return orderedRules
|
return orderedRules
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Config) extendDefault() {
|
func (c *Config) extendDefault(parent *ViperConfig) error {
|
||||||
extendDepth++
|
extendDepth++
|
||||||
viper.SetConfigType("toml")
|
viper.SetConfigType("toml")
|
||||||
if err := viper.ReadConfig(strings.NewReader(DefaultConfig)); err != nil {
|
if err := viper.ReadConfig(strings.NewReader(DefaultConfig)); err != nil {
|
||||||
logging.Fatal().Msgf("failed to load extended config, err: %s", err)
|
return fmt.Errorf("failed to load extended default config, err: %w", err)
|
||||||
return
|
|
||||||
}
|
}
|
||||||
defaultViperConfig := ViperConfig{}
|
defaultViperConfig := ViperConfig{}
|
||||||
if err := viper.Unmarshal(&defaultViperConfig); err != nil {
|
if err := viper.Unmarshal(&defaultViperConfig); err != nil {
|
||||||
logging.Fatal().Msgf("failed to load extended config, err: %s", err)
|
return fmt.Errorf("failed to load extended default config, err: %w", err)
|
||||||
return
|
|
||||||
}
|
}
|
||||||
cfg, err := defaultViperConfig.Translate()
|
cfg, err := defaultViperConfig.Translate()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logging.Fatal().Msgf("failed to load extended config, err: %s", err)
|
return fmt.Errorf("failed to load extended default config, err: %w", err)
|
||||||
return
|
|
||||||
}
|
}
|
||||||
logging.Debug().Msg("extending config with default config")
|
logging.Debug().Msg("extending config with default config")
|
||||||
c.extend(cfg)
|
c.extend(cfg)
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Config) extendPath() {
|
func (c *Config) extendPath(parent *ViperConfig) error {
|
||||||
extendDepth++
|
extendDepth++
|
||||||
viper.SetConfigFile(c.Extend.Path)
|
viper.SetConfigFile(c.Extend.Path)
|
||||||
if err := viper.ReadInConfig(); err != nil {
|
if err := viper.ReadInConfig(); err != nil {
|
||||||
logging.Fatal().Msgf("failed to load extended config, err: %s", err)
|
return fmt.Errorf("failed to load extended config, err: %w", err)
|
||||||
return
|
|
||||||
}
|
}
|
||||||
extensionViperConfig := ViperConfig{}
|
extensionViperConfig := ViperConfig{}
|
||||||
if err := viper.Unmarshal(&extensionViperConfig); err != nil {
|
if err := viper.Unmarshal(&extensionViperConfig); err != nil {
|
||||||
logging.Fatal().Msgf("failed to load extended config, err: %s", err)
|
return fmt.Errorf("failed to load extended config, err: %w", err)
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
extensionViperConfig.configPath = c.Extend.Path
|
||||||
|
logging.Debug().Msgf("extending config with %s", c.Extend.Path)
|
||||||
cfg, err := extensionViperConfig.Translate()
|
cfg, err := extensionViperConfig.Translate()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logging.Fatal().Msgf("failed to load extended config, err: %s", err)
|
return fmt.Errorf("failed to load extended config, err: %w", err)
|
||||||
return
|
|
||||||
}
|
}
|
||||||
logging.Debug().Msgf("extending config with %s", c.Extend.Path)
|
|
||||||
c.extend(cfg)
|
c.extend(cfg)
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Config) extendURL() {
|
func (c *Config) extendURL() {
|
||||||
@@ -341,9 +474,7 @@ func (c *Config) extend(extensionConfig Config) {
|
|||||||
}
|
}
|
||||||
baseRule.Tags = append(baseRule.Tags, currentRule.Tags...)
|
baseRule.Tags = append(baseRule.Tags, currentRule.Tags...)
|
||||||
baseRule.Keywords = append(baseRule.Keywords, currentRule.Keywords...)
|
baseRule.Keywords = append(baseRule.Keywords, currentRule.Keywords...)
|
||||||
for _, a := range currentRule.Allowlists {
|
baseRule.Allowlists = append(baseRule.Allowlists, currentRule.Allowlists...)
|
||||||
baseRule.Allowlists = append(baseRule.Allowlists, a)
|
|
||||||
}
|
|
||||||
// The keywords from the base rule and the extended rule must be merged into the global keywords list
|
// The keywords from the base rule and the extended rule must be merged into the global keywords list
|
||||||
for _, k := range baseRule.Keywords {
|
for _, k := range baseRule.Keywords {
|
||||||
c.Keywords[k] = struct{}{}
|
c.Keywords[k] = struct{}{}
|
||||||
@@ -353,13 +484,9 @@ func (c *Config) extend(extensionConfig Config) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// append allowlists, not attempting to merge
|
// append allowlists, not attempting to merge
|
||||||
c.Allowlist.Commits = append(c.Allowlist.Commits,
|
c.Allowlists = append(c.Allowlists, extensionConfig.Allowlists...)
|
||||||
extensionConfig.Allowlist.Commits...)
|
|
||||||
c.Allowlist.Paths = append(c.Allowlist.Paths,
|
|
||||||
extensionConfig.Allowlist.Paths...)
|
|
||||||
c.Allowlist.Regexes = append(c.Allowlist.Regexes,
|
|
||||||
extensionConfig.Allowlist.Regexes...)
|
|
||||||
|
|
||||||
// sort to keep extended rules in order
|
// sort to keep extended rules in order
|
||||||
sort.Strings(c.OrderedRules)
|
sort.Strings(c.OrderedRules)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
+491
-271
@@ -1,118 +1,81 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"errors"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/google/go-cmp/cmp"
|
"github.com/google/go-cmp/cmp"
|
||||||
regexp "github.com/wasilibs/go-re2"
|
"github.com/google/go-cmp/cmp/cmpopts"
|
||||||
|
|
||||||
"github.com/spf13/viper"
|
"github.com/spf13/viper"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
|
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
const configPath = "../testdata/config/"
|
const configPath = "../testdata/config/"
|
||||||
|
|
||||||
|
var regexComparer = func(x, y *regexp.Regexp) bool {
|
||||||
|
if x == nil || y == nil {
|
||||||
|
return x == y
|
||||||
|
}
|
||||||
|
return x.String() == y.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
type translateCase struct {
|
||||||
|
// Configuration file basename to load, from `../testdata/config/`.
|
||||||
|
cfgName string
|
||||||
|
// Expected result.
|
||||||
|
cfg Config
|
||||||
|
// Rules to compare.
|
||||||
|
rules []string
|
||||||
|
// Error to expect.
|
||||||
|
wantError error
|
||||||
|
}
|
||||||
|
|
||||||
func TestTranslate(t *testing.T) {
|
func TestTranslate(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []translateCase{
|
||||||
// Configuration file basename to load, from `../testdata/config/`.
|
// Valid
|
||||||
cfgName string
|
|
||||||
// Expected result.
|
|
||||||
cfg Config
|
|
||||||
// Rules to compare.
|
|
||||||
rules []string
|
|
||||||
// Error to expect.
|
|
||||||
wantError error
|
|
||||||
}{
|
|
||||||
{
|
{
|
||||||
cfgName: "allowlist_old_compat",
|
cfgName: "generic",
|
||||||
cfg: Config{
|
cfg: Config{
|
||||||
Rules: map[string]Rule{"example": {
|
Title: "gitleaks config",
|
||||||
RuleID: "example",
|
Rules: map[string]Rule{"generic-api-key": {
|
||||||
Regex: regexp.MustCompile(`example\d+`),
|
RuleID: "generic-api-key",
|
||||||
Tags: []string{},
|
Description: "Generic API Key",
|
||||||
Keywords: []string{},
|
Regex: regexp.MustCompile(`(?i)(?:key|api|token|secret|client|passwd|password|auth|access)(?:[0-9a-z\-_\t .]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:{1,3}=|\|\|:|<=|=>|:|\?=)(?:'|\"|\s|=|\x60){0,5}([0-9a-z\-_.=]{10,150})(?:['|\"|\n|\r|\s|\x60|;]|$)`),
|
||||||
Allowlists: []Allowlist{
|
Entropy: 3.5,
|
||||||
{
|
Keywords: []string{"key", "api", "token", "secret", "client", "passwd", "password", "auth", "access"},
|
||||||
MatchCondition: AllowlistMatchOr,
|
Tags: []string{},
|
||||||
Regexes: []*regexp.Regexp{regexp.MustCompile("123")},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}},
|
}},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
cfgName: "allowlist_invalid_empty",
|
cfgName: "valid/rule_path_only",
|
||||||
cfg: Config{},
|
|
||||||
wantError: fmt.Errorf("example: [[rules.allowlists]] must contain at least one check for: commits, paths, regexes, or stopwords"),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
cfgName: "allowlist_invalid_old_and_new",
|
|
||||||
cfg: Config{},
|
|
||||||
wantError: fmt.Errorf("example: [rules.allowlist] is deprecated, it cannot be used alongside [[rules.allowlist]]"),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
cfgName: "allowlist_invalid_regextarget",
|
|
||||||
cfg: Config{},
|
|
||||||
wantError: fmt.Errorf("example: unknown allowlist |regexTarget| 'mtach' (expected 'match', 'line')"),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
cfgName: "allow_aws_re",
|
|
||||||
cfg: Config{
|
cfg: Config{
|
||||||
Rules: map[string]Rule{"aws-access-key": {
|
Rules: map[string]Rule{"python-files-only": {
|
||||||
RuleID: "aws-access-key",
|
RuleID: "python-files-only",
|
||||||
Description: "AWS Access Key",
|
Description: "Python Files",
|
||||||
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
|
Path: regexp.MustCompile(`.py`),
|
||||||
Keywords: []string{},
|
Keywords: []string{},
|
||||||
Tags: []string{"key", "AWS"},
|
Tags: []string{},
|
||||||
Allowlists: []Allowlist{
|
|
||||||
{
|
|
||||||
MatchCondition: AllowlistMatchOr,
|
|
||||||
Regexes: []*regexp.Regexp{regexp.MustCompile("AKIALALEMEL33243OLIA")},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}},
|
}},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
cfgName: "allow_commit",
|
cfgName: "valid/rule_regex_escaped_character_group",
|
||||||
cfg: Config{
|
cfg: Config{
|
||||||
Rules: map[string]Rule{"aws-access-key": {
|
Rules: map[string]Rule{"pypi-upload-token": {
|
||||||
RuleID: "aws-access-key",
|
RuleID: "pypi-upload-token",
|
||||||
Description: "AWS Access Key",
|
Description: "PyPI upload token",
|
||||||
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
|
Regex: regexp.MustCompile(`pypi-AgEIcHlwaS5vcmc[A-Za-z0-9\-_]{50,1000}`),
|
||||||
Keywords: []string{},
|
Keywords: []string{},
|
||||||
Tags: []string{"key", "AWS"},
|
Tags: []string{"key", "pypi"},
|
||||||
Allowlists: []Allowlist{
|
|
||||||
{
|
|
||||||
MatchCondition: AllowlistMatchOr,
|
|
||||||
Commits: []string{"allowthiscommit"},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}},
|
}},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
cfgName: "allow_path",
|
cfgName: "valid/rule_entropy_group",
|
||||||
cfg: Config{
|
|
||||||
Rules: map[string]Rule{"aws-access-key": {
|
|
||||||
RuleID: "aws-access-key",
|
|
||||||
Description: "AWS Access Key",
|
|
||||||
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
|
|
||||||
Keywords: []string{},
|
|
||||||
Tags: []string{"key", "AWS"},
|
|
||||||
Allowlists: []Allowlist{
|
|
||||||
{
|
|
||||||
MatchCondition: AllowlistMatchOr,
|
|
||||||
Paths: []*regexp.Regexp{regexp.MustCompile(".go")},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
cfgName: "entropy_group",
|
|
||||||
cfg: Config{
|
cfg: Config{
|
||||||
Rules: map[string]Rule{"discord-api-key": {
|
Rules: map[string]Rule{"discord-api-key": {
|
||||||
RuleID: "discord-api-key",
|
RuleID: "discord-api-key",
|
||||||
@@ -125,23 +88,246 @@ func TestTranslate(t *testing.T) {
|
|||||||
}},
|
}},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// Invalid
|
||||||
{
|
{
|
||||||
cfgName: "missing_id",
|
cfgName: "invalid/rule_missing_id",
|
||||||
cfg: Config{},
|
cfg: Config{},
|
||||||
wantError: fmt.Errorf("rule |id| is missing or empty, regex: (?i)(discord[a-z0-9_ .\\-,]{0,25})(=|>|:=|\\|\\|:|<=|=>|:).{0,5}['\\\"]([a-h0-9]{64})['\\\"]"),
|
wantError: errors.New("rule |id| is missing or empty, description: Discord API key, regex: (?i)(discord[a-z0-9_ .\\-,]{0,25})(=|>|:=|\\|\\|:|<=|=>|:).{0,5}['\\\"]([a-h0-9]{64})['\\\"]"),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
cfgName: "no_regex_or_path",
|
cfgName: "invalid/rule_no_regex_or_path",
|
||||||
cfg: Config{},
|
cfg: Config{},
|
||||||
wantError: fmt.Errorf("discord-api-key: both |regex| and |path| are empty, this rule will have no effect"),
|
wantError: errors.New("discord-api-key: both |regex| and |path| are empty, this rule will have no effect"),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
cfgName: "bad_entropy_group",
|
cfgName: "invalid/rule_bad_entropy_group",
|
||||||
cfg: Config{},
|
cfg: Config{},
|
||||||
wantError: fmt.Errorf("discord-api-key: invalid regex secret group 5, max regex secret group 3"),
|
wantError: errors.New("discord-api-key: invalid regex secret group 5, max regex secret group 3"),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.cfgName, func(t *testing.T) {
|
||||||
|
testTranslate(t, tt)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTranslateAllowlists(t *testing.T) {
|
||||||
|
tests := []translateCase{
|
||||||
|
// Global
|
||||||
|
{
|
||||||
|
cfgName: "valid/allowlist_global_old_compat",
|
||||||
|
cfg: Config{
|
||||||
|
Rules: map[string]Rule{},
|
||||||
|
Allowlists: []*Allowlist{
|
||||||
|
{
|
||||||
|
StopWords: []string{"0989c462-69c9-49fa-b7d2-30dc5c576a97"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
cfgName: "base",
|
cfgName: "valid/allowlist_global_multiple",
|
||||||
|
cfg: Config{
|
||||||
|
Rules: map[string]Rule{
|
||||||
|
"test": {
|
||||||
|
RuleID: "test",
|
||||||
|
Regex: regexp.MustCompile(`token = "(.+)"`),
|
||||||
|
Keywords: []string{},
|
||||||
|
Tags: []string{},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Allowlists: []*Allowlist{
|
||||||
|
{
|
||||||
|
Regexes: []*regexp.Regexp{regexp.MustCompile("^changeit$")},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
MatchCondition: AllowlistMatchAnd,
|
||||||
|
Paths: []*regexp.Regexp{regexp.MustCompile("^node_modules/.*")},
|
||||||
|
StopWords: []string{"mock"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "valid/allowlist_global_target_rules",
|
||||||
|
cfg: Config{
|
||||||
|
Rules: map[string]Rule{
|
||||||
|
"github-app-token": {
|
||||||
|
RuleID: "github-app-token",
|
||||||
|
Regex: regexp.MustCompile(`(?:ghu|ghs)_[0-9a-zA-Z]{36}`),
|
||||||
|
Tags: []string{},
|
||||||
|
Keywords: []string{},
|
||||||
|
Allowlists: []*Allowlist{
|
||||||
|
{
|
||||||
|
Paths: []*regexp.Regexp{regexp.MustCompile(`(?:^|/)@octokit/auth-token/README\.md$`)},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"github-oauth": {
|
||||||
|
RuleID: "github-oauth",
|
||||||
|
Regex: regexp.MustCompile(`gho_[0-9a-zA-Z]{36}`),
|
||||||
|
Tags: []string{},
|
||||||
|
Keywords: []string{},
|
||||||
|
Allowlists: nil,
|
||||||
|
},
|
||||||
|
"github-pat": {
|
||||||
|
RuleID: "github-pat",
|
||||||
|
Regex: regexp.MustCompile(`ghp_[0-9a-zA-Z]{36}`),
|
||||||
|
Tags: []string{},
|
||||||
|
Keywords: []string{},
|
||||||
|
Allowlists: []*Allowlist{
|
||||||
|
{
|
||||||
|
Paths: []*regexp.Regexp{regexp.MustCompile(`(?:^|/)@octokit/auth-token/README\.md$`)},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Allowlists: []*Allowlist{
|
||||||
|
{
|
||||||
|
Regexes: []*regexp.Regexp{regexp.MustCompile(".*fake.*")},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "valid/allowlist_global_regex",
|
||||||
|
cfg: Config{
|
||||||
|
Rules: map[string]Rule{},
|
||||||
|
Allowlists: []*Allowlist{
|
||||||
|
{
|
||||||
|
MatchCondition: AllowlistMatchOr,
|
||||||
|
Regexes: []*regexp.Regexp{regexp.MustCompile("AKIALALEM.L33243OLIA")},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "invalid/allowlist_global_empty",
|
||||||
|
cfg: Config{},
|
||||||
|
wantError: errors.New("[[allowlists]] must contain at least one check for: commits, paths, regexes, or stopwords"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "invalid/allowlist_global_old_and_new",
|
||||||
|
cfg: Config{},
|
||||||
|
wantError: errors.New("[allowlist] is deprecated, it cannot be used alongside [[allowlists]]"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "invalid/allowlist_global_target_rule_id",
|
||||||
|
cfg: Config{},
|
||||||
|
wantError: errors.New("[[allowlists]] target rule ID 'github-pat' does not exist"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "invalid/allowlist_global_regextarget",
|
||||||
|
cfg: Config{},
|
||||||
|
wantError: errors.New("[[allowlists]] unknown allowlist |regexTarget| 'mtach' (expected 'match', 'line')"),
|
||||||
|
},
|
||||||
|
|
||||||
|
// Rule
|
||||||
|
{
|
||||||
|
cfgName: "valid/allowlist_rule_old_compat",
|
||||||
|
cfg: Config{
|
||||||
|
Rules: map[string]Rule{"example": {
|
||||||
|
RuleID: "example",
|
||||||
|
Regex: regexp.MustCompile(`example\d+`),
|
||||||
|
Tags: []string{},
|
||||||
|
Keywords: []string{},
|
||||||
|
Allowlists: []*Allowlist{
|
||||||
|
{
|
||||||
|
MatchCondition: AllowlistMatchOr,
|
||||||
|
Regexes: []*regexp.Regexp{regexp.MustCompile("123")},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "valid/allowlist_rule_regex",
|
||||||
|
cfg: Config{
|
||||||
|
Title: "simple config with allowlist for aws",
|
||||||
|
Rules: map[string]Rule{"aws-access-key": {
|
||||||
|
RuleID: "aws-access-key",
|
||||||
|
Description: "AWS Access Key",
|
||||||
|
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
|
||||||
|
Keywords: []string{},
|
||||||
|
Tags: []string{"key", "AWS"},
|
||||||
|
Allowlists: []*Allowlist{
|
||||||
|
{
|
||||||
|
MatchCondition: AllowlistMatchOr,
|
||||||
|
Regexes: []*regexp.Regexp{regexp.MustCompile("AKIALALEMEL33243OLIA")},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "valid/allowlist_rule_commit",
|
||||||
|
cfg: Config{
|
||||||
|
Title: "simple config with allowlist for a specific commit",
|
||||||
|
Rules: map[string]Rule{"aws-access-key": {
|
||||||
|
RuleID: "aws-access-key",
|
||||||
|
Description: "AWS Access Key",
|
||||||
|
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
|
||||||
|
Keywords: []string{},
|
||||||
|
Tags: []string{"key", "AWS"},
|
||||||
|
Allowlists: []*Allowlist{
|
||||||
|
{
|
||||||
|
MatchCondition: AllowlistMatchOr,
|
||||||
|
Commits: []string{"allowthiscommit"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "valid/allowlist_rule_path",
|
||||||
|
cfg: Config{
|
||||||
|
Title: "simple config with allowlist for .go files",
|
||||||
|
Rules: map[string]Rule{"aws-access-key": {
|
||||||
|
RuleID: "aws-access-key",
|
||||||
|
Description: "AWS Access Key",
|
||||||
|
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
|
||||||
|
Keywords: []string{},
|
||||||
|
Tags: []string{"key", "AWS"},
|
||||||
|
Allowlists: []*Allowlist{
|
||||||
|
{
|
||||||
|
MatchCondition: AllowlistMatchOr,
|
||||||
|
Paths: []*regexp.Regexp{regexp.MustCompile(".go")},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "invalid/allowlist_rule_empty",
|
||||||
|
cfg: Config{},
|
||||||
|
wantError: errors.New("example: [[rules.allowlists]] must contain at least one check for: commits, paths, regexes, or stopwords"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "invalid/allowlist_rule_old_and_new",
|
||||||
|
cfg: Config{},
|
||||||
|
wantError: errors.New("example: [rules.allowlist] is deprecated, it cannot be used alongside [[rules.allowlist]]"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "invalid/allowlist_rule_regextarget",
|
||||||
|
cfg: Config{},
|
||||||
|
wantError: errors.New("example: [[rules.allowlists]] unknown allowlist |regexTarget| 'mtach' (expected 'match', 'line')"),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.cfgName, func(t *testing.T) {
|
||||||
|
testTranslate(t, tt)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTranslateExtend(t *testing.T) {
|
||||||
|
tests := []translateCase{
|
||||||
|
// Valid
|
||||||
|
{
|
||||||
|
cfgName: "valid/extend",
|
||||||
cfg: Config{
|
cfg: Config{
|
||||||
Rules: map[string]Rule{
|
Rules: map[string]Rule{
|
||||||
"aws-access-key": {
|
"aws-access-key": {
|
||||||
@@ -169,7 +355,27 @@ func TestTranslate(t *testing.T) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
cfgName: "extend_rule_allowlist_or",
|
cfgName: "valid/extend_disabled",
|
||||||
|
cfg: Config{
|
||||||
|
Title: "gitleaks extend disable",
|
||||||
|
Rules: map[string]Rule{
|
||||||
|
"aws-secret-key": {
|
||||||
|
RuleID: "aws-secret-key",
|
||||||
|
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
|
||||||
|
Tags: []string{"key", "AWS"},
|
||||||
|
Keywords: []string{},
|
||||||
|
},
|
||||||
|
"pypi-upload-token": {
|
||||||
|
RuleID: "pypi-upload-token",
|
||||||
|
Regex: regexp.MustCompile(`pypi-AgEIcHlwaS5vcmc[A-Za-z0-9\-_]{50,1000}`),
|
||||||
|
Tags: []string{},
|
||||||
|
Keywords: []string{},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "valid/extend_rule_no_regexpath",
|
||||||
cfg: Config{
|
cfg: Config{
|
||||||
Rules: map[string]Rule{
|
Rules: map[string]Rule{
|
||||||
"aws-secret-key-again-again": {
|
"aws-secret-key-again-again": {
|
||||||
@@ -178,7 +384,137 @@ func TestTranslate(t *testing.T) {
|
|||||||
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
|
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
|
||||||
Keywords: []string{},
|
Keywords: []string{},
|
||||||
Tags: []string{"key", "AWS"},
|
Tags: []string{"key", "AWS"},
|
||||||
Allowlists: []Allowlist{
|
Allowlists: []*Allowlist{
|
||||||
|
{
|
||||||
|
Description: "False positive. Keys used for colors match the rule, and should be excluded.",
|
||||||
|
MatchCondition: AllowlistMatchOr,
|
||||||
|
Paths: []*regexp.Regexp{regexp.MustCompile(`something.py`)},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "valid/extend_rule_override_description",
|
||||||
|
rules: []string{"aws-access-key"},
|
||||||
|
cfg: Config{
|
||||||
|
Title: "override a built-in rule's description",
|
||||||
|
Rules: map[string]Rule{"aws-access-key": {
|
||||||
|
RuleID: "aws-access-key",
|
||||||
|
Description: "Puppy Doggy",
|
||||||
|
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
|
||||||
|
Keywords: []string{},
|
||||||
|
Tags: []string{"key", "AWS"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "valid/extend_rule_override_path",
|
||||||
|
rules: []string{"aws-access-key"},
|
||||||
|
cfg: Config{
|
||||||
|
Title: "override a built-in rule's path",
|
||||||
|
Rules: map[string]Rule{"aws-access-key": {
|
||||||
|
RuleID: "aws-access-key",
|
||||||
|
Description: "AWS Access Key",
|
||||||
|
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
|
||||||
|
Path: regexp.MustCompile("(?:puppy)"),
|
||||||
|
Keywords: []string{},
|
||||||
|
Tags: []string{"key", "AWS"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "valid/extend_rule_override_regex",
|
||||||
|
rules: []string{"aws-access-key"},
|
||||||
|
cfg: Config{
|
||||||
|
Title: "override a built-in rule's regex",
|
||||||
|
Rules: map[string]Rule{"aws-access-key": {
|
||||||
|
RuleID: "aws-access-key",
|
||||||
|
Description: "AWS Access Key",
|
||||||
|
Regex: regexp.MustCompile("(?:a)"),
|
||||||
|
Keywords: []string{},
|
||||||
|
Tags: []string{"key", "AWS"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "valid/extend_rule_override_secret_group",
|
||||||
|
rules: []string{"aws-access-key"},
|
||||||
|
cfg: Config{
|
||||||
|
Title: "override a built-in rule's secretGroup",
|
||||||
|
Rules: map[string]Rule{"aws-access-key": {
|
||||||
|
RuleID: "aws-access-key",
|
||||||
|
Description: "AWS Access Key",
|
||||||
|
Regex: regexp.MustCompile("(a)(a)"),
|
||||||
|
SecretGroup: 2,
|
||||||
|
Keywords: []string{},
|
||||||
|
Tags: []string{"key", "AWS"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "valid/extend_rule_override_entropy",
|
||||||
|
rules: []string{"aws-access-key"},
|
||||||
|
cfg: Config{
|
||||||
|
Title: "override a built-in rule's entropy",
|
||||||
|
Rules: map[string]Rule{"aws-access-key": {
|
||||||
|
RuleID: "aws-access-key",
|
||||||
|
Description: "AWS Access Key",
|
||||||
|
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
|
||||||
|
Entropy: 999.0,
|
||||||
|
Keywords: []string{},
|
||||||
|
Tags: []string{"key", "AWS"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "valid/extend_rule_override_keywords",
|
||||||
|
rules: []string{"aws-access-key"},
|
||||||
|
cfg: Config{
|
||||||
|
Title: "override a built-in rule's keywords",
|
||||||
|
Rules: map[string]Rule{"aws-access-key": {
|
||||||
|
RuleID: "aws-access-key",
|
||||||
|
Description: "AWS Access Key",
|
||||||
|
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
|
||||||
|
Keywords: []string{"puppy"},
|
||||||
|
Tags: []string{"key", "AWS"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "valid/extend_rule_override_tags",
|
||||||
|
rules: []string{"aws-access-key"},
|
||||||
|
cfg: Config{
|
||||||
|
Title: "override a built-in rule's tags",
|
||||||
|
Rules: map[string]Rule{"aws-access-key": {
|
||||||
|
RuleID: "aws-access-key",
|
||||||
|
Description: "AWS Access Key",
|
||||||
|
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
|
||||||
|
Keywords: []string{},
|
||||||
|
Tags: []string{"key", "AWS", "puppy"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
cfgName: "valid/extend_rule_allowlist_or",
|
||||||
|
cfg: Config{
|
||||||
|
Title: "gitleaks extended 3",
|
||||||
|
Rules: map[string]Rule{
|
||||||
|
"aws-secret-key-again-again": {
|
||||||
|
RuleID: "aws-secret-key-again-again",
|
||||||
|
Description: "AWS Secret Key",
|
||||||
|
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
|
||||||
|
Keywords: []string{},
|
||||||
|
Tags: []string{"key", "AWS"},
|
||||||
|
Allowlists: []*Allowlist{
|
||||||
{
|
{
|
||||||
MatchCondition: AllowlistMatchOr,
|
MatchCondition: AllowlistMatchOr,
|
||||||
StopWords: []string{"fake"},
|
StopWords: []string{"fake"},
|
||||||
@@ -197,8 +533,9 @@ func TestTranslate(t *testing.T) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
cfgName: "extend_rule_allowlist_and",
|
cfgName: "valid/extend_rule_allowlist_and",
|
||||||
cfg: Config{
|
cfg: Config{
|
||||||
|
Title: "gitleaks extended 3",
|
||||||
Rules: map[string]Rule{
|
Rules: map[string]Rule{
|
||||||
"aws-secret-key-again-again": {
|
"aws-secret-key-again-again": {
|
||||||
RuleID: "aws-secret-key-again-again",
|
RuleID: "aws-secret-key-again-again",
|
||||||
@@ -206,7 +543,7 @@ func TestTranslate(t *testing.T) {
|
|||||||
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
|
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
|
||||||
Keywords: []string{},
|
Keywords: []string{},
|
||||||
Tags: []string{"key", "AWS"},
|
Tags: []string{"key", "AWS"},
|
||||||
Allowlists: []Allowlist{
|
Allowlists: []*Allowlist{
|
||||||
{
|
{
|
||||||
MatchCondition: AllowlistMatchOr,
|
MatchCondition: AllowlistMatchOr,
|
||||||
StopWords: []string{"fake"},
|
StopWords: []string{"fake"},
|
||||||
@@ -224,191 +561,74 @@ func TestTranslate(t *testing.T) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// Invalid
|
||||||
{
|
{
|
||||||
cfgName: "extend_empty_regexpath",
|
cfgName: "invalid/extend_invalid_ruleid",
|
||||||
cfg: Config{
|
wantError: errors.New("rule |id| is missing or empty"),
|
||||||
Rules: map[string]Rule{
|
|
||||||
"aws-secret-key-again-again": {
|
|
||||||
RuleID: "aws-secret-key-again-again",
|
|
||||||
Description: "AWS Secret Key",
|
|
||||||
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
|
|
||||||
Keywords: []string{},
|
|
||||||
Tags: []string{"key", "AWS"},
|
|
||||||
Allowlists: []Allowlist{
|
|
||||||
{
|
|
||||||
MatchCondition: AllowlistMatchOr,
|
|
||||||
Paths: []*regexp.Regexp{regexp.MustCompile(`something.py`)},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
cfgName: "override_description",
|
|
||||||
rules: []string{"aws-access-key"},
|
|
||||||
cfg: Config{
|
|
||||||
Rules: map[string]Rule{"aws-access-key": {
|
|
||||||
RuleID: "aws-access-key",
|
|
||||||
Description: "Puppy Doggy",
|
|
||||||
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
|
|
||||||
Keywords: []string{},
|
|
||||||
Tags: []string{"key", "AWS"},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
cfgName: "override_entropy",
|
|
||||||
rules: []string{"aws-access-key"},
|
|
||||||
cfg: Config{
|
|
||||||
Rules: map[string]Rule{"aws-access-key": {
|
|
||||||
RuleID: "aws-access-key",
|
|
||||||
Description: "AWS Access Key",
|
|
||||||
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
|
|
||||||
Entropy: 999.0,
|
|
||||||
Keywords: []string{},
|
|
||||||
Tags: []string{"key", "AWS"},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
cfgName: "override_secret_group",
|
|
||||||
rules: []string{"aws-access-key"},
|
|
||||||
cfg: Config{
|
|
||||||
Rules: map[string]Rule{"aws-access-key": {
|
|
||||||
RuleID: "aws-access-key",
|
|
||||||
Description: "AWS Access Key",
|
|
||||||
Regex: regexp.MustCompile("(?:a)(?:a)"),
|
|
||||||
SecretGroup: 2,
|
|
||||||
Keywords: []string{},
|
|
||||||
Tags: []string{"key", "AWS"},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
cfgName: "override_regex",
|
|
||||||
rules: []string{"aws-access-key"},
|
|
||||||
cfg: Config{
|
|
||||||
Rules: map[string]Rule{"aws-access-key": {
|
|
||||||
RuleID: "aws-access-key",
|
|
||||||
Description: "AWS Access Key",
|
|
||||||
Regex: regexp.MustCompile("(?:a)"),
|
|
||||||
Keywords: []string{},
|
|
||||||
Tags: []string{"key", "AWS"},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
cfgName: "override_path",
|
|
||||||
rules: []string{"aws-access-key"},
|
|
||||||
cfg: Config{
|
|
||||||
Rules: map[string]Rule{"aws-access-key": {
|
|
||||||
RuleID: "aws-access-key",
|
|
||||||
Description: "AWS Access Key",
|
|
||||||
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
|
|
||||||
Path: regexp.MustCompile("(?:puppy)"),
|
|
||||||
Keywords: []string{},
|
|
||||||
Tags: []string{"key", "AWS"},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
cfgName: "override_tags",
|
|
||||||
rules: []string{"aws-access-key"},
|
|
||||||
cfg: Config{
|
|
||||||
Rules: map[string]Rule{"aws-access-key": {
|
|
||||||
RuleID: "aws-access-key",
|
|
||||||
Description: "AWS Access Key",
|
|
||||||
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
|
|
||||||
Keywords: []string{},
|
|
||||||
Tags: []string{"key", "AWS", "puppy"},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
cfgName: "override_keywords",
|
|
||||||
rules: []string{"aws-access-key"},
|
|
||||||
cfg: Config{
|
|
||||||
Rules: map[string]Rule{"aws-access-key": {
|
|
||||||
RuleID: "aws-access-key",
|
|
||||||
Description: "AWS Access Key",
|
|
||||||
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
|
|
||||||
Keywords: []string{"puppy"},
|
|
||||||
Tags: []string{"key", "AWS"},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
cfgName: "extend_disabled",
|
|
||||||
cfg: Config{
|
|
||||||
Rules: map[string]Rule{
|
|
||||||
"aws-secret-key": {
|
|
||||||
RuleID: "aws-secret-key",
|
|
||||||
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
|
|
||||||
Tags: []string{"key", "AWS"},
|
|
||||||
Keywords: []string{},
|
|
||||||
},
|
|
||||||
"pypi-upload-token": {
|
|
||||||
RuleID: "pypi-upload-token",
|
|
||||||
Regex: regexp.MustCompile(`pypi-AgEIcHlwaS5vcmc[A-Za-z0-9\-_]{50,1000}`),
|
|
||||||
Tags: []string{},
|
|
||||||
Keywords: []string{},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.cfgName, func(t *testing.T) {
|
t.Run(tt.cfgName, func(t *testing.T) {
|
||||||
t.Cleanup(func() {
|
testTranslate(t, tt)
|
||||||
extendDepth = 0
|
|
||||||
viper.Reset()
|
|
||||||
})
|
|
||||||
|
|
||||||
viper.AddConfigPath(configPath)
|
|
||||||
viper.SetConfigName(tt.cfgName)
|
|
||||||
viper.SetConfigType("toml")
|
|
||||||
err := viper.ReadInConfig()
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
var vc ViperConfig
|
|
||||||
err = viper.Unmarshal(&vc)
|
|
||||||
require.NoError(t, err)
|
|
||||||
cfg, err := vc.Translate()
|
|
||||||
if err != nil && !assert.EqualError(t, tt.wantError, err.Error()) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(tt.rules) > 0 {
|
|
||||||
rules := make(map[string]Rule)
|
|
||||||
for _, name := range tt.rules {
|
|
||||||
rules[name] = cfg.Rules[name]
|
|
||||||
}
|
|
||||||
cfg.Rules = rules
|
|
||||||
}
|
|
||||||
|
|
||||||
var regexComparer = func(x, y *regexp.Regexp) bool {
|
|
||||||
if x == nil || y == nil {
|
|
||||||
return x == y
|
|
||||||
}
|
|
||||||
return x.String() == y.String()
|
|
||||||
}
|
|
||||||
opts := cmp.Options{cmp.Comparer(regexComparer)}
|
|
||||||
if diff := cmp.Diff(tt.cfg.Rules, cfg.Rules, opts); diff != "" {
|
|
||||||
t.Errorf("%s diff: (-want +got)\n%s", tt.cfgName, diff)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func testTranslate(t *testing.T, test translateCase) {
|
||||||
|
t.Helper()
|
||||||
|
t.Cleanup(func() {
|
||||||
|
extendDepth = 0
|
||||||
|
viper.Reset()
|
||||||
|
})
|
||||||
|
|
||||||
|
viper.AddConfigPath(configPath)
|
||||||
|
viper.SetConfigName(test.cfgName)
|
||||||
|
viper.SetConfigType("toml")
|
||||||
|
err := viper.ReadInConfig()
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
var vc ViperConfig
|
||||||
|
err = viper.Unmarshal(&vc)
|
||||||
|
require.NoError(t, err)
|
||||||
|
cfg, err := vc.Translate()
|
||||||
|
if err != nil {
|
||||||
|
if test.wantError != nil {
|
||||||
|
assert.EqualError(t, err, test.wantError.Error())
|
||||||
|
} else {
|
||||||
|
require.NoError(t, err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if test.wantError != nil {
|
||||||
|
t.Fatalf("expected error but got none: %v", test.wantError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(test.rules) > 0 {
|
||||||
|
rules := make(map[string]Rule)
|
||||||
|
for _, name := range test.rules {
|
||||||
|
rules[name] = cfg.Rules[name]
|
||||||
|
}
|
||||||
|
cfg.Rules = rules
|
||||||
|
}
|
||||||
|
|
||||||
|
opts := cmp.Options{
|
||||||
|
cmp.Comparer(regexComparer),
|
||||||
|
cmpopts.IgnoreUnexported(Rule{}, Allowlist{}),
|
||||||
|
}
|
||||||
|
if diff := cmp.Diff(test.cfg.Title, cfg.Title); diff != "" {
|
||||||
|
t.Errorf("%s diff: (-want +got)\n%s", test.cfgName, diff)
|
||||||
|
}
|
||||||
|
if diff := cmp.Diff(test.cfg.Rules, cfg.Rules, opts); diff != "" {
|
||||||
|
t.Errorf("%s diff: (-want +got)\n%s", test.cfgName, diff)
|
||||||
|
}
|
||||||
|
if diff := cmp.Diff(test.cfg.Allowlists, cfg.Allowlists, opts); diff != "" {
|
||||||
|
t.Errorf("%s diff: (-want +got)\n%s", test.cfgName, diff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestExtendedRuleKeywordsAreDowncase(t *testing.T) {
|
func TestExtendedRuleKeywordsAreDowncase(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
@@ -417,12 +637,12 @@ func TestExtendedRuleKeywordsAreDowncase(t *testing.T) {
|
|||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
name: "Extend base rule that includes AWS keyword with new attribute",
|
name: "Extend base rule that includes AWS keyword with new attribute",
|
||||||
cfgName: "extend_base_rule_including_keysword_with_attribute",
|
cfgName: "valid/extend_base_rule_including_keywords_with_attribute",
|
||||||
expectedKeywords: "aws",
|
expectedKeywords: "aws",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Extend base with a new rule with CMS keyword",
|
name: "Extend base with a new rule with CMS keyword",
|
||||||
cfgName: "extend_with_new_rule",
|
cfgName: "valid/extend_rule_new",
|
||||||
expectedKeywords: "cms",
|
expectedKeywords: "cms",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
+361
-222
File diff suppressed because it is too large.
Load diff
+45
-12
@@ -1,10 +1,11 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
regexp "github.com/wasilibs/go-re2"
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Rules contain information that define details on how to detect secrets
|
// Rules contain information that define details on how to detect secrets
|
||||||
@@ -41,28 +42,49 @@ type Rule struct {
|
|||||||
Keywords []string
|
Keywords []string
|
||||||
|
|
||||||
// Allowlists allows a rule to be ignored for specific commits, paths, regexes, and/or stopwords.
|
// Allowlists allows a rule to be ignored for specific commits, paths, regexes, and/or stopwords.
|
||||||
Allowlists []Allowlist
|
Allowlists []*Allowlist
|
||||||
|
|
||||||
|
// validated is an internal flag to track whether `Validate()` has been called.
|
||||||
|
validated bool
|
||||||
|
|
||||||
|
// If a rule has RequiredRules, it makes the rule dependent on the RequiredRules.
|
||||||
|
// In otherwords, this rule is now a composite rule.
|
||||||
|
RequiredRules []*Required
|
||||||
|
|
||||||
|
SkipReport bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type Required struct {
|
||||||
|
RuleID string
|
||||||
|
WithinLines *int
|
||||||
|
WithinColumns *int
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate guards against common misconfigurations.
|
// Validate guards against common misconfigurations.
|
||||||
func (r Rule) Validate() error {
|
func (r *Rule) Validate() error {
|
||||||
|
if r.validated {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// Ensure |id| is present.
|
// Ensure |id| is present.
|
||||||
if strings.TrimSpace(r.RuleID) == "" {
|
if strings.TrimSpace(r.RuleID) == "" {
|
||||||
// Try to provide helpful context, since |id| is empty.
|
// Try to provide helpful context, since |id| is empty.
|
||||||
var context string
|
var sb strings.Builder
|
||||||
if r.Regex != nil {
|
if r.Description != "" {
|
||||||
context = ", regex: " + r.Regex.String()
|
sb.WriteString(", description: " + r.Description)
|
||||||
} else if r.Path != nil {
|
|
||||||
context = ", path: " + r.Path.String()
|
|
||||||
} else if r.Description != "" {
|
|
||||||
context = ", description: " + r.Description
|
|
||||||
}
|
}
|
||||||
return fmt.Errorf("rule |id| is missing or empty" + context)
|
if r.Regex != nil {
|
||||||
|
sb.WriteString(", regex: " + r.Regex.String())
|
||||||
|
}
|
||||||
|
if r.Path != nil {
|
||||||
|
sb.WriteString(", path: " + r.Path.String())
|
||||||
|
}
|
||||||
|
return errors.New("rule |id| is missing or empty" + sb.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ensure the rule actually matches something.
|
// Ensure the rule actually matches something.
|
||||||
if r.Regex == nil && r.Path == nil {
|
if r.Regex == nil && r.Path == nil {
|
||||||
return fmt.Errorf("%s: both |regex| and |path| are empty, this rule will have no effect", r.RuleID)
|
return errors.New(r.RuleID + ": both |regex| and |path| are empty, this rule will have no effect")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ensure |secretGroup| works.
|
// Ensure |secretGroup| works.
|
||||||
@@ -70,5 +92,16 @@ func (r Rule) Validate() error {
|
|||||||
return fmt.Errorf("%s: invalid regex secret group %d, max regex secret group %d", r.RuleID, r.SecretGroup, r.Regex.NumSubexp())
|
return fmt.Errorf("%s: invalid regex secret group %d, max regex secret group %d", r.RuleID, r.SecretGroup, r.Regex.NumSubexp())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for _, allowlist := range r.Allowlists {
|
||||||
|
// This will probably never happen.
|
||||||
|
if allowlist == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := allowlist.Validate(); err != nil {
|
||||||
|
return fmt.Errorf("%s: %w", r.RuleID, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
r.validated = true
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
+17
-1
@@ -1,7 +1,9 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
regexp "github.com/wasilibs/go-re2"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
)
|
)
|
||||||
|
|
||||||
func anyRegexMatch(f string, res []*regexp.Regexp) bool {
|
func anyRegexMatch(f string, res []*regexp.Regexp) bool {
|
||||||
@@ -22,3 +24,17 @@ func regexMatched(f string, re *regexp.Regexp) bool {
|
|||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// joinRegexOr combines multiple |patterns| into a single *regexp.Regexp.
|
||||||
|
func joinRegexOr(patterns []*regexp.Regexp) *regexp.Regexp {
|
||||||
|
var sb strings.Builder
|
||||||
|
sb.WriteString("(?:")
|
||||||
|
for i, pat := range patterns {
|
||||||
|
sb.WriteString(pat.String())
|
||||||
|
if i != len(patterns)-1 {
|
||||||
|
sb.WriteString("|")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sb.WriteString(")")
|
||||||
|
return regexp.MustCompile(sb.String())
|
||||||
|
}
|
||||||
+13
-15
@@ -9,27 +9,25 @@ import (
|
|||||||
"github.com/zricethezav/gitleaks/v8/report"
|
"github.com/zricethezav/gitleaks/v8/report"
|
||||||
)
|
)
|
||||||
|
|
||||||
func IsNew(finding report.Finding, baseline []report.Finding) bool {
|
func IsNew(finding report.Finding, redact uint, baseline []report.Finding) bool {
|
||||||
// Explicitly testing each property as it gives significantly better performance in comparison to cmp.Equal(). Drawback is that
|
// Explicitly testing each property as it gives significantly better performance in comparison to cmp.Equal(). Drawback is that
|
||||||
// the code requires maintenance if/when the Finding struct changes
|
// the code requires maintenance if/when the Finding struct changes
|
||||||
for _, b := range baseline {
|
for _, b := range baseline {
|
||||||
|
if finding.RuleID == b.RuleID &&
|
||||||
if finding.Author == b.Author &&
|
|
||||||
finding.Commit == b.Commit &&
|
|
||||||
finding.Date == b.Date &&
|
|
||||||
finding.Description == b.Description &&
|
finding.Description == b.Description &&
|
||||||
finding.Email == b.Email &&
|
finding.StartLine == b.StartLine &&
|
||||||
finding.EndColumn == b.EndColumn &&
|
|
||||||
finding.EndLine == b.EndLine &&
|
finding.EndLine == b.EndLine &&
|
||||||
finding.Entropy == b.Entropy &&
|
|
||||||
finding.File == b.File &&
|
|
||||||
// Omit checking finding.Fingerprint - if the format of the fingerprint changes, the users will see unexpected behaviour
|
|
||||||
finding.Match == b.Match &&
|
|
||||||
finding.Message == b.Message &&
|
|
||||||
finding.RuleID == b.RuleID &&
|
|
||||||
finding.Secret == b.Secret &&
|
|
||||||
finding.StartColumn == b.StartColumn &&
|
finding.StartColumn == b.StartColumn &&
|
||||||
finding.StartLine == b.StartLine {
|
finding.EndColumn == b.EndColumn &&
|
||||||
|
(redact > 0 || (finding.Match == b.Match && finding.Secret == b.Secret)) &&
|
||||||
|
finding.File == b.File &&
|
||||||
|
finding.Commit == b.Commit &&
|
||||||
|
finding.Author == b.Author &&
|
||||||
|
finding.Email == b.Email &&
|
||||||
|
finding.Date == b.Date &&
|
||||||
|
finding.Message == b.Message &&
|
||||||
|
// Omit checking finding.Fingerprint - if the format of the fingerprint changes, the users will see unexpected behaviour
|
||||||
|
finding.Entropy == b.Entropy {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+115
-23
@@ -11,59 +11,150 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestIsNew(t *testing.T) {
|
func TestIsNew(t *testing.T) {
|
||||||
tests := []struct {
|
t.Parallel()
|
||||||
|
tests := map[string]struct {
|
||||||
findings report.Finding
|
findings report.Finding
|
||||||
|
redact uint
|
||||||
baseline []report.Finding
|
baseline []report.Finding
|
||||||
expect bool
|
expect bool
|
||||||
}{
|
}{
|
||||||
{
|
// new
|
||||||
|
"new - commit doesn't match baseline": {
|
||||||
findings: report.Finding{
|
findings: report.Finding{
|
||||||
Author: "a",
|
|
||||||
Commit: "0000",
|
Commit: "0000",
|
||||||
|
Author: "a",
|
||||||
},
|
},
|
||||||
baseline: []report.Finding{
|
baseline: []report.Finding{
|
||||||
{
|
{
|
||||||
Author: "a",
|
|
||||||
Commit: "0000",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
expect: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
findings: report.Finding{
|
|
||||||
Author: "a",
|
|
||||||
Commit: "0000",
|
|
||||||
},
|
|
||||||
baseline: []report.Finding{
|
|
||||||
{
|
|
||||||
Author: "a",
|
|
||||||
Commit: "0002",
|
Commit: "0002",
|
||||||
|
Author: "a",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
expect: true,
|
expect: true,
|
||||||
},
|
},
|
||||||
{
|
"new - redacted, different baseline": {
|
||||||
|
findings: report.Finding{
|
||||||
|
RuleID: "private-key",
|
||||||
|
Description: "Identified a Private Key, which may compromise cryptographic security and sensitive data encryption.",
|
||||||
|
StartLine: 1,
|
||||||
|
EndLine: 15,
|
||||||
|
StartColumn: 1,
|
||||||
|
EndColumn: 30,
|
||||||
|
Match: "REDACTED",
|
||||||
|
Secret: "REDACTED",
|
||||||
|
File: "key.txt",
|
||||||
|
Commit: "6d3ba1f7653822c0f8ac9a9af56daaa2cd8bbcad",
|
||||||
|
Entropy: 5.9834013,
|
||||||
|
Author: "James Bond",
|
||||||
|
Email: "jbond@gov.co.uk",
|
||||||
|
Date: "2025-03-02T15:10:40Z",
|
||||||
|
Message: "init",
|
||||||
|
Fingerprint: "6d3ba1f7653822c0f8ac9a9af56daaa2cd8bbcad:key.txt:private-key:1",
|
||||||
|
},
|
||||||
|
baseline: []report.Finding{
|
||||||
|
{
|
||||||
|
RuleID: "private-key",
|
||||||
|
Description: "Identified a Private Key, which may compromise cryptographic security and sensitive data encryption.",
|
||||||
|
StartLine: 1,
|
||||||
|
EndLine: 15,
|
||||||
|
StartColumn: 1,
|
||||||
|
EndColumn: 30,
|
||||||
|
Match: "-----BEGIN RSA PRIVATE KEY-----\nMIICWgIBAAKBgFIckgeuo80H6skLd1FKYfJC75/tnmtDWO4Rf2AFqrYZdu71VKGR\noGfEVl7AmvxTd9u6tnPtWjAeu9k2VMQcOtXEwgU0A6H09EBcS1EVN/I8pcNw1qjO\nkJ7ZA8AhZk/OpVAK7665CEny7ISRNZnx1nPaHjlb8lebPzlWOvxX9wjbAgMBAAEC\ngYBN6wqv+4s4juC/cwAAxeL4L4iQbL497yS+lSAYEIiUUMnJrEhpIXXjwi5rr73i\n35oHisCEdaF1tFRxpNr/VgKFsM1KqQUZvCVRE9Rokfe23QkQDvcxh9CI/Ah9Eofp\nx/m5DjSsRKrbIpOOAC3J3B/s02HRmxy8tRYnQVqWXzAH8QJBAJdBgXi62KI1eytU\n7l3Q8ymkS1OHzSOGBEYPpZZQ7WRpZlv/06cKfJBT/dGgA4z9i9ySs8cWUoh+FGYX\nlkDB4c0CQQCK+TwfAFvrkSWorZ9Gjb6y2LZQPUufTzJNhzhK5XObCDbwyMXEM/Vs\newiyUFljlI/A9PjcrmkgrDLUMD4+og1HAkAs2t01W1uhBvEm0YH6yltCDxnThKM+\nFKEx0bQOVqN/so4LXFt83uw/tNjBkI1dA1e1qr+rm6AQICuWdwo03ApFAkBktes4\nuCTk2GHHFFM5aN0KdHviOBlGULkub9B+jjsx3UkbQxP2dITlYV/TAOFWhcGLXru+\nCPKMR93p4TAqaXtfAkA+ZZDb0mA9rtaetJlSoo6XgwI/+kqltADch9dcyqYBHwjr\nAEkzUKvmCxNAK4GEPA79FZFp30kDx+buysyeX9qY\n-----END RSA PRIVATE KEY-----",
|
||||||
|
Secret: "-----BEGIN RSA PRIVATE KEY-----\nMIICWgIBAAKBgFIckgeuo80H6skLd1FKYfJC75/tnmtDWO4Rf2AFqrYZdu71VKGR\noGfEVl7AmvxTd9u6tnPtWjAeu9k2VMQcOtXEwgU0A6H09EBcS1EVN/I8pcNw1qjO\nkJ7ZA8AhZk/OpVAK7665CEny7ISRNZnx1nPaHjlb8lebPzlWOvxX9wjbAgMBAAEC\ngYBN6wqv+4s4juC/cwAAxeL4L4iQbL497yS+lSAYEIiUUMnJrEhpIXXjwi5rr73i\n35oHisCEdaF1tFRxpNr/VgKFsM1KqQUZvCVRE9Rokfe23QkQDvcxh9CI/Ah9Eofp\nx/m5DjSsRKrbIpOOAC3J3B/s02HRmxy8tRYnQVqWXzAH8QJBAJdBgXi62KI1eytU\n7l3Q8ymkS1OHzSOGBEYPpZZQ7WRpZlv/06cKfJBT/dGgA4z9i9ySs8cWUoh+FGYX\nlkDB4c0CQQCK+TwfAFvrkSWorZ9Gjb6y2LZQPUufTzJNhzhK5XObCDbwyMXEM/Vs\newiyUFljlI/A9PjcrmkgrDLUMD4+og1HAkAs2t01W1uhBvEm0YH6yltCDxnThKM+\nFKEx0bQOVqN/so4LXFt83uw/tNjBkI1dA1e1qr+rm6AQICuWdwo03ApFAkBktes4\nuCTk2GHHFFM5aN0KdHviOBlGULkub9B+jjsx3UkbQxP2dITlYV/TAOFWhcGLXru+\nCPKMR93p4TAqaXtfAkA+ZZDb0mA9rtaetJlSoo6XgwI/+kqltADch9dcyqYBHwjr\nAEkzUKvmCxNAK4GEPA79FZFp30kDx+buysyeX9qY\n-----END RSA PRIVATE KEY-----",
|
||||||
|
File: "key.txt",
|
||||||
|
Commit: "e55e00ca1690a6b5b612d28b3d9ada3fd1775ac4",
|
||||||
|
Entropy: 5.9834013,
|
||||||
|
Author: "James Bond",
|
||||||
|
Email: "jbond@gov.co.uk",
|
||||||
|
Date: "2025-02-02T17:45:30Z",
|
||||||
|
Message: "init",
|
||||||
|
Fingerprint: "e55e00ca1690a6b5b612d28b3d9ada3fd1775ac4:key.txt:private-key:1",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
expect: true,
|
||||||
|
},
|
||||||
|
|
||||||
|
// not new
|
||||||
|
"not new - commit+author matches": {
|
||||||
findings: report.Finding{
|
findings: report.Finding{
|
||||||
Author: "a",
|
|
||||||
Commit: "0000",
|
Commit: "0000",
|
||||||
|
Author: "a",
|
||||||
|
},
|
||||||
|
baseline: []report.Finding{
|
||||||
|
{
|
||||||
|
Commit: "0000",
|
||||||
|
Author: "a",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
expect: false,
|
||||||
|
},
|
||||||
|
"not new - commit+author matches, tags ignored": {
|
||||||
|
findings: report.Finding{
|
||||||
|
Commit: "0000",
|
||||||
|
Author: "a",
|
||||||
Tags: []string{"a", "b"},
|
Tags: []string{"a", "b"},
|
||||||
},
|
},
|
||||||
baseline: []report.Finding{
|
baseline: []report.Finding{
|
||||||
{
|
{
|
||||||
Author: "a",
|
|
||||||
Commit: "0000",
|
Commit: "0000",
|
||||||
|
Author: "a",
|
||||||
Tags: []string{"a", "c"},
|
Tags: []string{"a", "c"},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
expect: false, // Updated tags doesn't make it a new finding
|
expect: false, // Updated tags doesn't make it a new finding
|
||||||
},
|
},
|
||||||
|
"not new - redacted, everything else matches": {
|
||||||
|
findings: report.Finding{
|
||||||
|
RuleID: "private-key",
|
||||||
|
Description: "Identified a Private Key, which may compromise cryptographic security and sensitive data encryption.",
|
||||||
|
StartLine: 1,
|
||||||
|
EndLine: 15,
|
||||||
|
StartColumn: 1,
|
||||||
|
EndColumn: 30,
|
||||||
|
Match: "REDACTED",
|
||||||
|
Secret: "REDACTED",
|
||||||
|
File: "key.txt",
|
||||||
|
Commit: "e55e00ca1690a6b5b612d28b3d9ada3fd1775ac4",
|
||||||
|
Entropy: 5.9834013,
|
||||||
|
Author: "James Bond",
|
||||||
|
Email: "jbond@gov.co.uk",
|
||||||
|
Date: "2025-02-02T17:45:30Z",
|
||||||
|
Message: "init",
|
||||||
|
Fingerprint: "e55e00ca1690a6b5b612d28b3d9ada3fd1775ac4:key.txt:private-key:1",
|
||||||
|
},
|
||||||
|
redact: 100,
|
||||||
|
baseline: []report.Finding{
|
||||||
|
{
|
||||||
|
RuleID: "private-key",
|
||||||
|
Description: "Identified a Private Key, which may compromise cryptographic security and sensitive data encryption.",
|
||||||
|
StartLine: 1,
|
||||||
|
EndLine: 15,
|
||||||
|
StartColumn: 1,
|
||||||
|
EndColumn: 30,
|
||||||
|
Match: "-----BEGIN RSA PRIVATE KEY-----\nMIICWgIBAAKBgFIckgeuo80H6skLd1FKYfJC75/tnmtDWO4Rf2AFqrYZdu71VKGR\noGfEVl7AmvxTd9u6tnPtWjAeu9k2VMQcOtXEwgU0A6H09EBcS1EVN/I8pcNw1qjO\nkJ7ZA8AhZk/OpVAK7665CEny7ISRNZnx1nPaHjlb8lebPzlWOvxX9wjbAgMBAAEC\ngYBN6wqv+4s4juC/cwAAxeL4L4iQbL497yS+lSAYEIiUUMnJrEhpIXXjwi5rr73i\n35oHisCEdaF1tFRxpNr/VgKFsM1KqQUZvCVRE9Rokfe23QkQDvcxh9CI/Ah9Eofp\nx/m5DjSsRKrbIpOOAC3J3B/s02HRmxy8tRYnQVqWXzAH8QJBAJdBgXi62KI1eytU\n7l3Q8ymkS1OHzSOGBEYPpZZQ7WRpZlv/06cKfJBT/dGgA4z9i9ySs8cWUoh+FGYX\nlkDB4c0CQQCK+TwfAFvrkSWorZ9Gjb6y2LZQPUufTzJNhzhK5XObCDbwyMXEM/Vs\newiyUFljlI/A9PjcrmkgrDLUMD4+og1HAkAs2t01W1uhBvEm0YH6yltCDxnThKM+\nFKEx0bQOVqN/so4LXFt83uw/tNjBkI1dA1e1qr+rm6AQICuWdwo03ApFAkBktes4\nuCTk2GHHFFM5aN0KdHviOBlGULkub9B+jjsx3UkbQxP2dITlYV/TAOFWhcGLXru+\nCPKMR93p4TAqaXtfAkA+ZZDb0mA9rtaetJlSoo6XgwI/+kqltADch9dcyqYBHwjr\nAEkzUKvmCxNAK4GEPA79FZFp30kDx+buysyeX9qY\n-----END RSA PRIVATE KEY-----",
|
||||||
|
Secret: "-----BEGIN RSA PRIVATE KEY-----\nMIICWgIBAAKBgFIckgeuo80H6skLd1FKYfJC75/tnmtDWO4Rf2AFqrYZdu71VKGR\noGfEVl7AmvxTd9u6tnPtWjAeu9k2VMQcOtXEwgU0A6H09EBcS1EVN/I8pcNw1qjO\nkJ7ZA8AhZk/OpVAK7665CEny7ISRNZnx1nPaHjlb8lebPzlWOvxX9wjbAgMBAAEC\ngYBN6wqv+4s4juC/cwAAxeL4L4iQbL497yS+lSAYEIiUUMnJrEhpIXXjwi5rr73i\n35oHisCEdaF1tFRxpNr/VgKFsM1KqQUZvCVRE9Rokfe23QkQDvcxh9CI/Ah9Eofp\nx/m5DjSsRKrbIpOOAC3J3B/s02HRmxy8tRYnQVqWXzAH8QJBAJdBgXi62KI1eytU\n7l3Q8ymkS1OHzSOGBEYPpZZQ7WRpZlv/06cKfJBT/dGgA4z9i9ySs8cWUoh+FGYX\nlkDB4c0CQQCK+TwfAFvrkSWorZ9Gjb6y2LZQPUufTzJNhzhK5XObCDbwyMXEM/Vs\newiyUFljlI/A9PjcrmkgrDLUMD4+og1HAkAs2t01W1uhBvEm0YH6yltCDxnThKM+\nFKEx0bQOVqN/so4LXFt83uw/tNjBkI1dA1e1qr+rm6AQICuWdwo03ApFAkBktes4\nuCTk2GHHFFM5aN0KdHviOBlGULkub9B+jjsx3UkbQxP2dITlYV/TAOFWhcGLXru+\nCPKMR93p4TAqaXtfAkA+ZZDb0mA9rtaetJlSoo6XgwI/+kqltADch9dcyqYBHwjr\nAEkzUKvmCxNAK4GEPA79FZFp30kDx+buysyeX9qY\n-----END RSA PRIVATE KEY-----",
|
||||||
|
File: "key.txt",
|
||||||
|
Commit: "e55e00ca1690a6b5b612d28b3d9ada3fd1775ac4",
|
||||||
|
Entropy: 5.9834013,
|
||||||
|
Author: "James Bond",
|
||||||
|
Email: "jbond@gov.co.uk",
|
||||||
|
Date: "2025-02-02T17:45:30Z",
|
||||||
|
Message: "init",
|
||||||
|
Fingerprint: "e55e00ca1690a6b5b612d28b3d9ada3fd1775ac4:key.txt:private-key:1",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
expect: false,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
for _, test := range tests {
|
for name, test := range tests {
|
||||||
assert.Equal(t, test.expect, IsNew(test.findings, test.baseline))
|
t.Run(name, func(t *testing.T) {
|
||||||
|
assert.Equal(t, test.expect, IsNew(test.findings, test.redact, test.baseline))
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFileLoadBaseline(t *testing.T) {
|
func TestFileLoadBaseline(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
Filename string
|
Filename string
|
||||||
ExpectedError error
|
ExpectedError error
|
||||||
@@ -89,6 +180,7 @@ func TestFileLoadBaseline(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestIgnoreIssuesInBaseline(t *testing.T) {
|
func TestIgnoreIssuesInBaseline(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
findings []report.Finding
|
findings []report.Finding
|
||||||
baseline []report.Finding
|
baseline []report.Finding
|
||||||
@@ -133,7 +225,7 @@ func TestIgnoreIssuesInBaseline(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
d.baseline = test.baseline
|
d.baseline = test.baseline
|
||||||
for _, finding := range test.findings {
|
for _, finding := range test.findings {
|
||||||
d.addFinding(finding)
|
d.AddFinding(finding)
|
||||||
}
|
}
|
||||||
assert.Len(t, d.findings, test.expectCount)
|
assert.Len(t, d.findings, test.expectCount)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package codec
|
||||||
|
|
||||||
|
var printableASCII [256]bool
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
for b := 0; b < len(printableASCII); b++ {
|
||||||
|
if '\x08' < b && b < '\x7f' {
|
||||||
|
printableASCII[b] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// isPrintableASCII returns true if all bytes are printable ASCII
|
||||||
|
func isPrintableASCII(b []byte) bool {
|
||||||
|
for _, c := range b {
|
||||||
|
if !printableASCII[c] {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// hasByte can be used to check if a string has at least one of the provided
|
||||||
|
// bytes. Note: make sure byteset is long enough to handle the largest byte in
|
||||||
|
// the string.
|
||||||
|
func hasByte(data string, byteset []bool) bool {
|
||||||
|
for i := 0; i < len(data); i++ {
|
||||||
|
if byteset[data[i]] {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package codec
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/base64"
|
||||||
|
)
|
||||||
|
|
||||||
|
// likelyBase64Chars is a set of characters that you would expect to find at
|
||||||
|
// least one of in base64 encoded data. This risks missing about 1% of
|
||||||
|
// base64 encoded data that doesn't contain these characters, but gives you
|
||||||
|
// the performance gain of not trying to decode a lot of long symbols in code.
|
||||||
|
var likelyBase64Chars = make([]bool, 256)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
for _, c := range `0123456789+/-_` {
|
||||||
|
likelyBase64Chars[c] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// decodeBase64 decodes base64 encoded printable ASCII characters
|
||||||
|
func decodeBase64(encodedValue string) string {
|
||||||
|
// Exit early if it doesn't seem like base64
|
||||||
|
if !hasByte(encodedValue, likelyBase64Chars) {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try standard base64 decoding
|
||||||
|
decodedValue, err := base64.StdEncoding.DecodeString(encodedValue)
|
||||||
|
if err == nil && isPrintableASCII(decodedValue) {
|
||||||
|
return string(decodedValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try base64url decoding
|
||||||
|
decodedValue, err = base64.RawURLEncoding.DecodeString(encodedValue)
|
||||||
|
if err == nil && isPrintableASCII(decodedValue) {
|
||||||
|
return string(decodedValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
return ""
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
package codec
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
|
||||||
|
"github.com/zricethezav/gitleaks/v8/logging"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Decoder decodes various types of data in place
|
||||||
|
type Decoder struct {
|
||||||
|
decodedMap map[string]string
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewDecoder creates a default decoder struct
|
||||||
|
func NewDecoder() *Decoder {
|
||||||
|
return &Decoder{
|
||||||
|
decodedMap: make(map[string]string),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decode returns the data with the values decoded in place along with the
|
||||||
|
// encoded segment meta data for the next pass of decoding
|
||||||
|
func (d *Decoder) Decode(data string, predecessors []*EncodedSegment) (string, []*EncodedSegment) {
|
||||||
|
segments := d.findEncodedSegments(data, predecessors)
|
||||||
|
|
||||||
|
if len(segments) > 0 {
|
||||||
|
result := bytes.NewBuffer(make([]byte, 0, len(data)))
|
||||||
|
encodedStart := 0
|
||||||
|
for _, segment := range segments {
|
||||||
|
result.WriteString(data[encodedStart:segment.encoded.start])
|
||||||
|
result.WriteString(segment.decodedValue)
|
||||||
|
encodedStart = segment.encoded.end
|
||||||
|
}
|
||||||
|
|
||||||
|
result.WriteString(data[encodedStart:])
|
||||||
|
return result.String(), segments
|
||||||
|
}
|
||||||
|
|
||||||
|
return data, segments
|
||||||
|
}
|
||||||
|
|
||||||
|
// findEncodedSegments finds the encoded segments in the data
|
||||||
|
func (d *Decoder) findEncodedSegments(data string, predecessors []*EncodedSegment) []*EncodedSegment {
|
||||||
|
if len(data) == 0 {
|
||||||
|
return []*EncodedSegment{}
|
||||||
|
}
|
||||||
|
|
||||||
|
decodedShift := 0
|
||||||
|
encodingMatches := findEncodingMatches(data)
|
||||||
|
segments := make([]*EncodedSegment, 0, len(encodingMatches))
|
||||||
|
for _, m := range encodingMatches {
|
||||||
|
encodedValue := data[m.start:m.end]
|
||||||
|
decodedValue, alreadyDecoded := d.decodedMap[encodedValue]
|
||||||
|
|
||||||
|
if !alreadyDecoded {
|
||||||
|
decodedValue = m.encoding.decode(encodedValue)
|
||||||
|
d.decodedMap[encodedValue] = decodedValue
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(decodedValue) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
segment := &EncodedSegment{
|
||||||
|
predecessors: predecessors,
|
||||||
|
original: toOriginal(predecessors, m.startEnd),
|
||||||
|
encoded: m.startEnd,
|
||||||
|
decoded: startEnd{
|
||||||
|
m.start + decodedShift,
|
||||||
|
m.start + decodedShift + len(decodedValue),
|
||||||
|
},
|
||||||
|
decodedValue: decodedValue,
|
||||||
|
encodings: m.encoding.kind,
|
||||||
|
depth: 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Shift decoded start and ends based on size changes
|
||||||
|
decodedShift += len(decodedValue) - len(encodedValue)
|
||||||
|
|
||||||
|
// Adjust depth and encoding if applicable
|
||||||
|
if len(segment.predecessors) != 0 {
|
||||||
|
// Set the depth based on the predecessors' depth in the previous pass
|
||||||
|
segment.depth = 1 + segment.predecessors[0].depth
|
||||||
|
// Adjust encodings
|
||||||
|
for _, p := range segment.predecessors {
|
||||||
|
if segment.encoded.overlaps(p.decoded) {
|
||||||
|
segment.encodings |= p.encodings
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
segments = append(segments, segment)
|
||||||
|
logging.Debug().
|
||||||
|
Str("decoder", m.encoding.kind.String()).
|
||||||
|
Msgf(
|
||||||
|
"segment found: original=%s pos=%s: %q -> %q",
|
||||||
|
segment.original,
|
||||||
|
segment.encoded,
|
||||||
|
encodedValue,
|
||||||
|
segment.decodedValue,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return segments
|
||||||
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
package detect
|
package codec
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/hex"
|
||||||
|
"net/url"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
@@ -66,8 +68,8 @@ func TestDecode(t *testing.T) {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "b64-url-safe: hyphen url b64",
|
name: "b64-url-safe: hyphen url b64",
|
||||||
chunk: `dHJ1ZmZsZWhvZz4-ZmluZHMtc2VjcmV0cw`,
|
chunk: `Z2l0bGVha3M-PmZpbmRzLXNlY3JldHM`,
|
||||||
expected: `trufflehog>>finds-secrets`,
|
expected: `gitleaks>>finds-secrets`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "b64-url-safe: underscore url b64",
|
name: "b64-url-safe: underscore url b64",
|
||||||
@@ -79,13 +81,64 @@ func TestDecode(t *testing.T) {
|
|||||||
chunk: `a3d3fa7c2bb99e469ba55e5834ce79ee4853a8a3`,
|
chunk: `a3d3fa7c2bb99e469ba55e5834ce79ee4853a8a3`,
|
||||||
expected: `a3d3fa7c2bb99e469ba55e5834ce79ee4853a8a3`,
|
expected: `a3d3fa7c2bb99e469ba55e5834ce79ee4853a8a3`,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "url encoded value",
|
||||||
|
chunk: `secret%3D%22q%24%21%40%23%24%25%5E%26%2A%28%20asdf%22`,
|
||||||
|
expected: `secret="q$!@#$%^&*( asdf"`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "hex encoded value",
|
||||||
|
chunk: `secret="466973684D617048756E6B79212121363334"`,
|
||||||
|
expected: `secret="FishMapHunky!!!634"`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "unicode encoded value",
|
||||||
|
chunk: `secret=U+0061 U+0062 U+0063 U+0064 U+0065 U+0066`,
|
||||||
|
expected: "secret=abcdef",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "unicode encoded value backslashed",
|
||||||
|
chunk: `secret=\\u0068\\u0065\\u006c\\u006c\\u006f\\u0020\\u0077\\u006f\\u0072\\u006c\\u0064\\u0020\\u0064\\u0075\\u0064\\u0065`,
|
||||||
|
expected: "secret=hello world dude",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "unicode encoded value backslashed mixed w/ hex",
|
||||||
|
chunk: `secret=\u0068\u0065\u006c\u006c\u006f\u0020\u0077\u006f\u0072\u006c\u0064 6C6F76656C792070656F706C65206F66206561727468`,
|
||||||
|
expected: "secret=hello world lovely people of earth",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
decoder := NewDecoder()
|
decoder := NewDecoder()
|
||||||
|
fullDecode := func(data string) string {
|
||||||
|
segments := []*EncodedSegment{}
|
||||||
|
for {
|
||||||
|
data, segments = decoder.Decode(data, segments)
|
||||||
|
if len(segments) == 0 {
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test value decoding
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
decoded, _ := decoder.decode(tt.chunk, []EncodedSegment{})
|
assert.Equal(t, tt.expected, fullDecode(tt.chunk))
|
||||||
assert.Equal(t, tt.expected, decoded)
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Percent encode the values to test percent decoding
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
encodedChunk := url.PathEscape(tt.chunk)
|
||||||
|
assert.Equal(t, tt.expected, fullDecode(encodedChunk))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hex encode the values to test hex decoding
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
encodedChunk := hex.EncodeToString([]byte(tt.chunk))
|
||||||
|
assert.Equal(t, tt.expected, fullDecode(encodedChunk))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
package codec
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// encodingsRe is a regex built by combining all the encoding patterns
|
||||||
|
// into named capture groups so that a single pass can detect multiple
|
||||||
|
// encodings
|
||||||
|
encodingsRe *regexp.Regexp
|
||||||
|
// encodings contains all the encoding configurations for the detector.
|
||||||
|
// The precedence is important. You want more specific encodings to
|
||||||
|
// have a higher precedence or encodings that partially encode the
|
||||||
|
// values (e.g. percent) unlike encodings that fully encode the string
|
||||||
|
// (e.g. base64). If two encoding matches overlap the decoder will use
|
||||||
|
// this order to determine which encoding should wait till the next pass.
|
||||||
|
encodings = []*encoding{
|
||||||
|
{
|
||||||
|
kind: percentKind,
|
||||||
|
pattern: `%[0-9A-Fa-f]{2}(?:.*%[0-9A-Fa-f]{2})?`,
|
||||||
|
decode: decodePercent,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kind: unicodeKind,
|
||||||
|
pattern: `(?:(?:U\+[a-fA-F0-9]{4}(?:\s|$))+|(?i)(?:\\{1,2}u[a-fA-F0-9]{4})+)`,
|
||||||
|
decode: decodeUnicode,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kind: hexKind,
|
||||||
|
pattern: `[0-9A-Fa-f]{32,}`,
|
||||||
|
decode: decodeHex,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
kind: base64Kind,
|
||||||
|
pattern: `[\w\/+-]{16,}={0,2}`,
|
||||||
|
decode: decodeBase64,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// encodingNames is used to map the encodingKinds to their name
|
||||||
|
var encodingNames = []string{
|
||||||
|
"percent",
|
||||||
|
"unicode",
|
||||||
|
"hex",
|
||||||
|
"base64",
|
||||||
|
}
|
||||||
|
|
||||||
|
// encodingKind can be or'd together to capture all of the unique encodings
|
||||||
|
// that were present in a segment
|
||||||
|
type encodingKind int
|
||||||
|
|
||||||
|
var (
|
||||||
|
// make sure these go up by powers of 2
|
||||||
|
percentKind = encodingKind(1)
|
||||||
|
unicodeKind = encodingKind(2)
|
||||||
|
hexKind = encodingKind(4)
|
||||||
|
base64Kind = encodingKind(8)
|
||||||
|
)
|
||||||
|
|
||||||
|
func (e encodingKind) String() string {
|
||||||
|
i := int(math.Log2(float64(e)))
|
||||||
|
if i >= len(encodingNames) {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return encodingNames[i]
|
||||||
|
}
|
||||||
|
|
||||||
|
// kinds returns a list of encodingKinds combined in this one
|
||||||
|
func (e encodingKind) kinds() []encodingKind {
|
||||||
|
kinds := []encodingKind{}
|
||||||
|
|
||||||
|
for i := 0; i < len(encodingNames); i++ {
|
||||||
|
if kind := int(e) & int(math.Pow(2, float64(i))); kind != 0 {
|
||||||
|
kinds = append(kinds, encodingKind(kind))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return kinds
|
||||||
|
}
|
||||||
|
|
||||||
|
// encodingMatch represents a match of an encoding in the text
|
||||||
|
type encodingMatch struct {
|
||||||
|
encoding *encoding
|
||||||
|
startEnd
|
||||||
|
}
|
||||||
|
|
||||||
|
// encoding represent a type of coding supported by the decoder.
|
||||||
|
type encoding struct {
|
||||||
|
// the kind of decoding (e.g. base64, etc)
|
||||||
|
kind encodingKind
|
||||||
|
// the regex pattern that matches the encoding format
|
||||||
|
pattern string
|
||||||
|
// take the match and return the decoded value
|
||||||
|
decode func(string) string
|
||||||
|
// determine which encoding should win out when two overlap
|
||||||
|
precedence int
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
count := len(encodings)
|
||||||
|
namedPatterns := make([]string, count)
|
||||||
|
for i, encoding := range encodings {
|
||||||
|
encoding.precedence = count - i
|
||||||
|
namedPatterns[i] = fmt.Sprintf(
|
||||||
|
"(?P<%s>%s)",
|
||||||
|
encoding.kind,
|
||||||
|
encoding.pattern,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
encodingsRe = regexp.MustCompile(strings.Join(namedPatterns, "|"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// findEncodingMatches finds as many encodings as it can for this pass
|
||||||
|
func findEncodingMatches(data string) []encodingMatch {
|
||||||
|
var all []encodingMatch
|
||||||
|
for _, matchIndex := range encodingsRe.FindAllStringSubmatchIndex(data, -1) {
|
||||||
|
// Add the encodingMatch with its proper encoding
|
||||||
|
for i, j := 2, 0; i < len(matchIndex); i, j = i+2, j+1 {
|
||||||
|
if matchIndex[i] > -1 {
|
||||||
|
all = append(all, encodingMatch{
|
||||||
|
encoding: encodings[j],
|
||||||
|
startEnd: startEnd{
|
||||||
|
start: matchIndex[i],
|
||||||
|
end: matchIndex[i+1],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
totalMatches := len(all)
|
||||||
|
if totalMatches == 1 {
|
||||||
|
return all
|
||||||
|
}
|
||||||
|
|
||||||
|
// filter out lower precedence ones that overlap their neigbors
|
||||||
|
filtered := make([]encodingMatch, 0, len(all))
|
||||||
|
for i, m := range all {
|
||||||
|
if i > 0 {
|
||||||
|
prev := all[i-1]
|
||||||
|
if m.overlaps(prev.startEnd) && prev.encoding.precedence > m.encoding.precedence {
|
||||||
|
continue // skip this one
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if i+1 < totalMatches {
|
||||||
|
next := all[i+1]
|
||||||
|
if m.overlaps(next.startEnd) && next.encoding.precedence > m.encoding.precedence {
|
||||||
|
continue // skip this one
|
||||||
|
}
|
||||||
|
}
|
||||||
|
filtered = append(filtered, m)
|
||||||
|
}
|
||||||
|
|
||||||
|
return filtered
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package codec
|
||||||
|
|
||||||
|
// hexMap is a precalculated map of hex nibbles
|
||||||
|
const hexMap = "" +
|
||||||
|
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||||
|
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||||
|
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||||
|
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\xff\xff\xff\xff\xff\xff" +
|
||||||
|
"\xff\x0a\x0b\x0c\x0d\x0e\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||||
|
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||||
|
"\xff\x0a\x0b\x0c\x0d\x0e\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||||
|
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||||
|
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||||
|
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||||
|
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||||
|
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||||
|
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||||
|
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||||
|
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||||
|
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff"
|
||||||
|
|
||||||
|
// likelyHexChars is a set of characters that you would expect to find at
|
||||||
|
// least one of in hex encoded data. This risks missing some hex data that
|
||||||
|
// doesn't contain these characters, but gives you the performance gain of not
|
||||||
|
// trying to decode a lot of long symbols in code.
|
||||||
|
var likelyHexChars = make([]bool, 256)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
for _, c := range `0123456789` {
|
||||||
|
likelyHexChars[c] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// decodeHex decodes hex data
|
||||||
|
func decodeHex(encodedValue string) string {
|
||||||
|
size := len(encodedValue)
|
||||||
|
// hex should have two characters per byte
|
||||||
|
if size%2 != 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if !hasByte(encodedValue, likelyHexChars) {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
decodedValue := make([]byte, size/2)
|
||||||
|
for i := 0; i < size; i += 2 {
|
||||||
|
n1 := hexMap[encodedValue[i]]
|
||||||
|
n2 := hexMap[encodedValue[i+1]]
|
||||||
|
if n1|n2 == '\xff' {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
b := n1<<4 | n2
|
||||||
|
if !printableASCII[b] {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
decodedValue[i/2] = b
|
||||||
|
}
|
||||||
|
|
||||||
|
return string(decodedValue)
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package codec
|
||||||
|
|
||||||
|
// decodePercent decodes percent encoded strings
|
||||||
|
func decodePercent(encodedValue string) string {
|
||||||
|
encLen := len(encodedValue)
|
||||||
|
decodedValue := make([]byte, encLen)
|
||||||
|
decIndex := 0
|
||||||
|
encIndex := 0
|
||||||
|
|
||||||
|
for encIndex < encLen {
|
||||||
|
if encodedValue[encIndex] == '%' && encIndex+2 < encLen {
|
||||||
|
n1 := hexMap[encodedValue[encIndex+1]]
|
||||||
|
n2 := hexMap[encodedValue[encIndex+2]]
|
||||||
|
// Make sure they're hex characters
|
||||||
|
if n1|n2 != '\xff' {
|
||||||
|
b := n1<<4 | n2
|
||||||
|
if !printableASCII[b] {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
decodedValue[decIndex] = b
|
||||||
|
encIndex += 3
|
||||||
|
decIndex += 1
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
decodedValue[decIndex] = encodedValue[encIndex]
|
||||||
|
encIndex += 1
|
||||||
|
decIndex += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
return string(decodedValue[:decIndex])
|
||||||
|
}
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
package codec
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// EncodedSegment represents a portion of text that is encoded in some way.
|
||||||
|
type EncodedSegment struct {
|
||||||
|
// predecessors are all of the segments from the previous decoding pass
|
||||||
|
predecessors []*EncodedSegment
|
||||||
|
|
||||||
|
// original start/end indices before decoding
|
||||||
|
original startEnd
|
||||||
|
|
||||||
|
// encoded start/end indices relative to the previous decoding pass.
|
||||||
|
// If it's a top level segment, original and encoded will be the
|
||||||
|
// same.
|
||||||
|
encoded startEnd
|
||||||
|
|
||||||
|
// decoded start/end indices in this pass after decoding
|
||||||
|
decoded startEnd
|
||||||
|
|
||||||
|
// decodedValue contains the decoded string for this segment
|
||||||
|
decodedValue string
|
||||||
|
|
||||||
|
// encodings is the encodings that make up this segment. encodingKind
|
||||||
|
// can be or'd together to hold multiple encodings
|
||||||
|
encodings encodingKind
|
||||||
|
|
||||||
|
// depth is how many decoding passes it took to decode this segment
|
||||||
|
depth int
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tags returns additional meta data tags related to the types of segments
|
||||||
|
func Tags(segments []*EncodedSegment) []string {
|
||||||
|
// Return an empty list if we don't have any segments
|
||||||
|
if len(segments) == 0 {
|
||||||
|
return []string{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Since decoding is done in passes, the depth of all the segments
|
||||||
|
// should be the same
|
||||||
|
depth := segments[0].depth
|
||||||
|
|
||||||
|
// Collect the encodings from the segments
|
||||||
|
encodings := segments[0].encodings
|
||||||
|
for i := 1; i < len(segments); i++ {
|
||||||
|
encodings |= segments[i].encodings
|
||||||
|
}
|
||||||
|
|
||||||
|
kinds := encodings.kinds()
|
||||||
|
tags := make([]string, len(kinds)+1)
|
||||||
|
|
||||||
|
tags[len(tags)-1] = fmt.Sprintf("decode-depth:%d", depth)
|
||||||
|
for i, kind := range kinds {
|
||||||
|
tags[i] = fmt.Sprintf("decoded:%s", kind)
|
||||||
|
}
|
||||||
|
|
||||||
|
return tags
|
||||||
|
}
|
||||||
|
|
||||||
|
// CurrentLine returns from the start of the line containing the segments
|
||||||
|
// to the end of the line where the segment ends.
|
||||||
|
func CurrentLine(segments []*EncodedSegment, currentRaw string) string {
|
||||||
|
// Return the whole thing if no segments are provided
|
||||||
|
if len(segments) == 0 {
|
||||||
|
return currentRaw
|
||||||
|
}
|
||||||
|
|
||||||
|
start := 0
|
||||||
|
end := len(currentRaw)
|
||||||
|
|
||||||
|
// Merge the ranges together into a single decoded value
|
||||||
|
decoded := segments[0].decoded
|
||||||
|
for i := 1; i < len(segments); i++ {
|
||||||
|
decoded = decoded.merge(segments[i].decoded)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find the start of the range
|
||||||
|
for i := decoded.start; i > -1; i-- {
|
||||||
|
c := currentRaw[i]
|
||||||
|
if c == '\n' {
|
||||||
|
start = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find the end of the range
|
||||||
|
for i := decoded.end; i < end; i++ {
|
||||||
|
c := currentRaw[i]
|
||||||
|
if c == '\n' {
|
||||||
|
end = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return currentRaw[start:end]
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdjustMatchIndex maps a match index from the current decode pass back to
|
||||||
|
// its location in the original text
|
||||||
|
func AdjustMatchIndex(segments []*EncodedSegment, matchIndex []int) []int {
|
||||||
|
// Don't adjust if we're not provided any segments
|
||||||
|
if len(segments) == 0 {
|
||||||
|
return matchIndex
|
||||||
|
}
|
||||||
|
|
||||||
|
// Map the match to the location in the original text
|
||||||
|
match := startEnd{matchIndex[0], matchIndex[1]}
|
||||||
|
|
||||||
|
// Map the match to its orignal location
|
||||||
|
adjusted := toOriginal(segments, match)
|
||||||
|
|
||||||
|
// Return the adjusted match index
|
||||||
|
return []int{
|
||||||
|
adjusted.start,
|
||||||
|
adjusted.end,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SegmentsWithDecodedOverlap the segments where the start and end overlap its
|
||||||
|
// decoded range
|
||||||
|
func SegmentsWithDecodedOverlap(segments []*EncodedSegment, start, end int) []*EncodedSegment {
|
||||||
|
se := startEnd{start, end}
|
||||||
|
overlaps := []*EncodedSegment{}
|
||||||
|
|
||||||
|
for _, segment := range segments {
|
||||||
|
if segment.decoded.overlaps(se) {
|
||||||
|
overlaps = append(overlaps, segment)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return overlaps
|
||||||
|
}
|
||||||
|
|
||||||
|
// toOriginal maps a start/end to its start/end in the original text
|
||||||
|
// the provided start/end should be relative to the segment's decoded value
|
||||||
|
func toOriginal(predecessors []*EncodedSegment, decoded startEnd) startEnd {
|
||||||
|
if len(predecessors) == 0 {
|
||||||
|
return decoded
|
||||||
|
}
|
||||||
|
|
||||||
|
// Map the decoded value one level up where it was encoded
|
||||||
|
encoded := startEnd{}
|
||||||
|
|
||||||
|
for _, p := range predecessors {
|
||||||
|
if !p.decoded.overlaps(decoded) {
|
||||||
|
continue // Not in scope
|
||||||
|
}
|
||||||
|
|
||||||
|
// If fully contained, return the segments original start/end
|
||||||
|
if p.decoded.contains(decoded) {
|
||||||
|
return p.original
|
||||||
|
}
|
||||||
|
|
||||||
|
// Map the value to be relative to the predecessors's decoded values
|
||||||
|
if encoded.end == 0 {
|
||||||
|
encoded = p.encoded.add(p.decoded.overflow(decoded))
|
||||||
|
} else {
|
||||||
|
encoded = encoded.merge(p.encoded.add(p.decoded.overflow(decoded)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Should only get here if the thing passed in wasn't in a decoded
|
||||||
|
// value. This shouldn't be the case
|
||||||
|
if encoded.end == 0 {
|
||||||
|
return decoded
|
||||||
|
}
|
||||||
|
|
||||||
|
// Climb up another level
|
||||||
|
// (NOTE: each segment references all the predecessors)
|
||||||
|
return toOriginal(predecessors[0].predecessors, encoded)
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package codec
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// startEnd represents the start and end of some data. It mainly exists as a
|
||||||
|
// helper when referencing the values
|
||||||
|
type startEnd struct {
|
||||||
|
start int
|
||||||
|
end int
|
||||||
|
}
|
||||||
|
|
||||||
|
// sub subtracts the values of two startEnds
|
||||||
|
func (s startEnd) sub(o startEnd) startEnd {
|
||||||
|
return startEnd{
|
||||||
|
s.start - o.start,
|
||||||
|
s.end - o.end,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// add adds the values of two startEnds
|
||||||
|
func (s startEnd) add(o startEnd) startEnd {
|
||||||
|
return startEnd{
|
||||||
|
s.start + o.start,
|
||||||
|
s.end + o.end,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// overlaps returns true if two startEnds overlap
|
||||||
|
func (s startEnd) overlaps(o startEnd) bool {
|
||||||
|
return o.start <= s.end && o.end >= s.start
|
||||||
|
}
|
||||||
|
|
||||||
|
// contains returns true if the other is fully contained within this one
|
||||||
|
func (s startEnd) contains(o startEnd) bool {
|
||||||
|
return s.start <= o.start && o.end <= s.end
|
||||||
|
}
|
||||||
|
|
||||||
|
// overflow returns a startEnd that tells how much the other goes outside the
|
||||||
|
// bounds of this one
|
||||||
|
func (s startEnd) overflow(o startEnd) startEnd {
|
||||||
|
return s.merge(o).sub(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
// merge takes two start/ends and returns a single one that encompasses both
|
||||||
|
func (s startEnd) merge(o startEnd) startEnd {
|
||||||
|
return startEnd{
|
||||||
|
min(s.start, o.start),
|
||||||
|
max(s.end, o.end),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// String returns a string representation for clearer debugging
|
||||||
|
func (s startEnd) String() string {
|
||||||
|
return fmt.Sprintf("[%d,%d]", s.start, s.end)
|
||||||
|
}
|
||||||
@@ -0,0 +1,261 @@
|
|||||||
|
package codec
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// Standard Unicode notation (e.g., U+1234)
|
||||||
|
unicodeCodePointPat = regexp.MustCompile(`U\+([a-fA-F0-9]{4}).?`)
|
||||||
|
|
||||||
|
// Multiple code points pattern - used for continuous sequences like "U+0074 U+006F U+006B..."
|
||||||
|
unicodeMultiCodePointPat = regexp.MustCompile(`(?:U\+[a-fA-F0-9]{4}(?:\s|$))+`)
|
||||||
|
|
||||||
|
// Common escape sequence used in programming languages (e.g., \u1234)
|
||||||
|
unicodeEscapePat = regexp.MustCompile(`(?i)\\{1,2}u([a-fA-F0-9]{4})`)
|
||||||
|
|
||||||
|
// Multiple escape sequences pattern - used for continuous sequences like "\u0074\u006F\u006B..."
|
||||||
|
unicodeMultiEscapePat = regexp.MustCompile(`(?i)(?:\\{1,2}u[a-fA-F0-9]{4})+`)
|
||||||
|
)
|
||||||
|
|
||||||
|
// Unicode characters are encoded as 1 to 4 bytes per rune.
|
||||||
|
const maxBytesPerRune = 4
|
||||||
|
|
||||||
|
// decodeUnicode decodes Unicode escape sequences in the given string
|
||||||
|
func decodeUnicode(encodedValue string) string {
|
||||||
|
// First, check if we have a continuous sequence of Unicode code points
|
||||||
|
if matches := unicodeMultiCodePointPat.FindAllString(encodedValue, -1); len(matches) > 0 {
|
||||||
|
// For each detected sequence of code points
|
||||||
|
for _, match := range matches {
|
||||||
|
// Decode the entire sequence at once
|
||||||
|
decodedSequence := decodeMultiCodePoint(match)
|
||||||
|
|
||||||
|
// If we successfully decoded something, replace it in the original string
|
||||||
|
if decodedSequence != "" && decodedSequence != match {
|
||||||
|
encodedValue = strings.Replace(encodedValue, match, decodedSequence, 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return encodedValue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Next, check if we have a continuous sequence of escape sequences
|
||||||
|
if matches := unicodeMultiEscapePat.FindAllString(encodedValue, -1); len(matches) > 0 {
|
||||||
|
// For each detected sequence of escape sequences
|
||||||
|
for _, match := range matches {
|
||||||
|
// Decode the entire sequence at once
|
||||||
|
decodedSequence := decodeMultiEscape(match)
|
||||||
|
|
||||||
|
// If we successfully decoded something, replace it in the original string
|
||||||
|
if decodedSequence != "" && decodedSequence != match {
|
||||||
|
encodedValue = strings.Replace(encodedValue, match, decodedSequence, 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return encodedValue
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no multi-patterns were matched, fall back to the original implementation
|
||||||
|
// for individual code points and escape sequences
|
||||||
|
|
||||||
|
// Create a copy of the input to work with
|
||||||
|
data := []byte(encodedValue)
|
||||||
|
|
||||||
|
// Store the result
|
||||||
|
var result []byte
|
||||||
|
|
||||||
|
// Check and decode Unicode code points (U+1234 format)
|
||||||
|
if unicodeCodePointPat.Match(data) {
|
||||||
|
result = decodeIndividualCodePoints(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no code points were found or we have a mix of formats,
|
||||||
|
// also check for Unicode escape sequences (\u1234 format)
|
||||||
|
if len(result) == 0 || unicodeEscapePat.Match(data) {
|
||||||
|
// If we already have some result from code point decoding,
|
||||||
|
// continue decoding escape sequences on that result
|
||||||
|
if len(result) > 0 {
|
||||||
|
result = decodeIndividualEscapes(result)
|
||||||
|
} else {
|
||||||
|
result = decodeIndividualEscapes(data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If nothing was decoded, return original string
|
||||||
|
if len(result) == 0 || bytes.Equal(result, data) {
|
||||||
|
return encodedValue
|
||||||
|
}
|
||||||
|
|
||||||
|
return string(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
// decodeMultiCodePoint decodes a continuous sequence of Unicode code points (U+XXXX format)
|
||||||
|
func decodeMultiCodePoint(sequence string) string {
|
||||||
|
// If the sequence is empty, return empty string
|
||||||
|
if sequence == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// Split the sequence by whitespace to get individual code points
|
||||||
|
codePoints := strings.Fields(sequence)
|
||||||
|
if len(codePoints) == 0 {
|
||||||
|
return sequence
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decode each code point and build the result
|
||||||
|
var decodedRunes []rune
|
||||||
|
for _, cp := range codePoints {
|
||||||
|
// Check if it follows the U+XXXX pattern
|
||||||
|
if !strings.HasPrefix(cp, "U+") || len(cp) < 6 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract the hexadecimal value
|
||||||
|
hexValue := cp[2:]
|
||||||
|
|
||||||
|
// Parse the hexadecimal value to an integer
|
||||||
|
unicodeInt, err := strconv.ParseInt(hexValue, 16, 32)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert to rune and add to result
|
||||||
|
decodedRunes = append(decodedRunes, rune(unicodeInt))
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we didn't decode anything, return the original sequence
|
||||||
|
if len(decodedRunes) == 0 {
|
||||||
|
return sequence
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return the decoded string
|
||||||
|
return string(decodedRunes)
|
||||||
|
}
|
||||||
|
|
||||||
|
// decodeMultiEscape decodes a continuous sequence of Unicode escape sequences (\uXXXX format)
|
||||||
|
func decodeMultiEscape(sequence string) string {
|
||||||
|
// If the sequence is empty, return empty string
|
||||||
|
if sequence == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find all escape sequences
|
||||||
|
escapes := unicodeEscapePat.FindAllStringSubmatch(sequence, -1)
|
||||||
|
if len(escapes) == 0 {
|
||||||
|
return sequence
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decode each escape sequence and build the result
|
||||||
|
var decodedRunes []rune
|
||||||
|
for _, esc := range escapes {
|
||||||
|
// Extract the hexadecimal value
|
||||||
|
hexValue := esc[1]
|
||||||
|
|
||||||
|
// Parse the hexadecimal value to an integer
|
||||||
|
unicodeInt, err := strconv.ParseInt(hexValue, 16, 32)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert to rune and add to result
|
||||||
|
decodedRunes = append(decodedRunes, rune(unicodeInt))
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we didn't decode anything, return the original sequence
|
||||||
|
if len(decodedRunes) == 0 {
|
||||||
|
return sequence
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return the decoded string
|
||||||
|
return string(decodedRunes)
|
||||||
|
}
|
||||||
|
|
||||||
|
// decodeIndividualCodePoints decodes individual Unicode code points (U+1234 format)
|
||||||
|
// This is a fallback for when we don't have a continuous sequence of code points
|
||||||
|
func decodeIndividualCodePoints(input []byte) []byte {
|
||||||
|
// Find all Unicode code point sequences in the input byte slice
|
||||||
|
indices := unicodeCodePointPat.FindAllSubmatchIndex(input, -1)
|
||||||
|
|
||||||
|
// If none found, return original input
|
||||||
|
if len(indices) == 0 {
|
||||||
|
return input
|
||||||
|
}
|
||||||
|
|
||||||
|
// Iterate over found indices in reverse order to avoid modifying the slice length
|
||||||
|
utf8Bytes := make([]byte, maxBytesPerRune)
|
||||||
|
for i := len(indices) - 1; i >= 0; i-- {
|
||||||
|
matches := indices[i]
|
||||||
|
|
||||||
|
startIndex := matches[0]
|
||||||
|
endIndex := matches[1]
|
||||||
|
hexStartIndex := matches[2]
|
||||||
|
hexEndIndex := matches[3]
|
||||||
|
|
||||||
|
// If the input is like `U+1234 U+5678` we should replace `U+1234 `.
|
||||||
|
// Otherwise, we should only replace `U+1234`.
|
||||||
|
if endIndex != hexEndIndex && endIndex < len(input) && input[endIndex-1] == ' ' {
|
||||||
|
endIndex = endIndex - 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract the hexadecimal value from the escape sequence
|
||||||
|
hexValue := string(input[hexStartIndex:hexEndIndex])
|
||||||
|
|
||||||
|
// Parse the hexadecimal value to an integer
|
||||||
|
unicodeInt, err := strconv.ParseInt(hexValue, 16, 32)
|
||||||
|
if err != nil {
|
||||||
|
// If there's an error, continue to the next escape sequence
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert the Unicode code point to a UTF-8 representation
|
||||||
|
utf8Len := utf8.EncodeRune(utf8Bytes, rune(unicodeInt))
|
||||||
|
|
||||||
|
// Replace the escape sequence with the UTF-8 representation
|
||||||
|
input = append(input[:startIndex], append(utf8Bytes[:utf8Len], input[endIndex:]...)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
return input
|
||||||
|
}
|
||||||
|
|
||||||
|
// decodeIndividualEscapes decodes individual Unicode escape sequences (\u1234 format)
|
||||||
|
// This is a fallback for when we don't have a continuous sequence of escape sequences
|
||||||
|
func decodeIndividualEscapes(input []byte) []byte {
|
||||||
|
// Find all Unicode escape sequences in the input byte slice
|
||||||
|
indices := unicodeEscapePat.FindAllSubmatchIndex(input, -1)
|
||||||
|
|
||||||
|
// If none found, return original input
|
||||||
|
if len(indices) == 0 {
|
||||||
|
return input
|
||||||
|
}
|
||||||
|
|
||||||
|
// Iterate over found indices in reverse order to avoid modifying the slice length
|
||||||
|
utf8Bytes := make([]byte, maxBytesPerRune)
|
||||||
|
for i := len(indices) - 1; i >= 0; i-- {
|
||||||
|
matches := indices[i]
|
||||||
|
|
||||||
|
startIndex := matches[0]
|
||||||
|
hexStartIndex := matches[2]
|
||||||
|
endIndex := matches[3]
|
||||||
|
|
||||||
|
// Extract the hexadecimal value from the escape sequence
|
||||||
|
hexValue := string(input[hexStartIndex:endIndex])
|
||||||
|
|
||||||
|
// Parse the hexadecimal value to an integer
|
||||||
|
unicodeInt, err := strconv.ParseInt(hexValue, 16, 32)
|
||||||
|
if err != nil {
|
||||||
|
// If there's an error, continue to the next escape sequence
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert the Unicode code point to a UTF-8 representation
|
||||||
|
utf8Len := utf8.EncodeRune(utf8Bytes, rune(unicodeInt))
|
||||||
|
|
||||||
|
// Replace the escape sequence with the UTF-8 representation
|
||||||
|
input = append(input[:startIndex], append(utf8Bytes[:utf8Len], input[endIndex:]...)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
return input
|
||||||
|
}
|
||||||
Loaded 100 of 225 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user