Compare commits

..
32 Commits
Author SHA1 Message Date
Richard Gomez aabe381539 Define multiple allowlists per rule (#1496)
* feat: multiple rule allowlists

* feat(config): add allowlist 'condition'
2024-10-14 19:17:37 -05:00
Richard Gomez 8ea608595c build: upgrade gitleaks/go-gitdiff to v0.9.1 (#1559) 2024-10-13 06:46:44 -05:00
Rebecca Turner be9d0f8930 Fix rule extension (#1556)
* Reimplement the ability to override built-in rules

PR #1524 broke the ability to specify a `[[rules]]` with the same ID as
a built-in rule in order to extend the default configuration.

This PR restores this ability, but merges the provided configuration
with the default rule instead of overwriting the default rule wholesale.

* Add tests

* Append keywords and tags
2024-10-10 16:50:29 -05:00
Richard Gomez 9988e5224c Update base config allowlist (#1555)
* feat(config): add String fmt placeholders

* feat(config): ignore font files

* feat(config): ignore repeated characters
2024-10-10 02:05:16 -05:00
Richard Gomez 8fb39ba8dc feat(azure): detect Azure AD client secrets (#1199) 2024-10-09 06:44:19 -05:00
Richard Gomez 14c924dd02 chore: match gitleaks.toml anywhere (#1553) 2024-10-08 09:39:44 -05:00
Richard Gomez b2fbaeb900 feat(config): add placeholder regexes to global allowlist (#1547) 2024-10-07 07:30:01 -05:00
Richard Gomez 00bb82153e feat: add PrivateAI rule (#1548) 2024-10-06 07:28:47 -05:00
Jannik Hollenbach 445abe356b Bump golang verion used in docker build to match version specified in go.mod (#1551)
Signed-off-by: Jannik Hollenbach <jannik.hollenbach@owasp.org>
2024-10-06 06:48:00 -05:00
Richard Gomez 1a2f656278 feat: add cohere rule (#1549) 2024-10-04 19:39:53 -05:00
Richard Gomez 82d737d851 feat(generate): generate global (#1546) 2024-10-04 10:28:34 -05:00
Roger Meier f6e549901c Feat/nuget config password rule (#1540)
* feat: add new rule nuget-config-password

* docs: correct function names within CONTRIBUTING.md
2024-10-04 08:19:15 -05:00
bplaxco bf8a49fc29 Make private key check less greedy and include fifth dash (#1440)
* Make private key check less greedy and include fifth dash

* Remove trailing space
2024-10-03 09:50:15 -05:00
Zach 9c354f51c3 print tags if they exist 2024-10-02 20:06:31 -05:00
bplaxcoandRichard Gomez 2278a2a97e Decode Base64 (#1488)
* Support base64 decoding during scans

rh-pre-commit.version: 2.3.1
rh-pre-commit.check-secrets: ENABLED

* Add failing tests for the case when the match starts outside the decoded value

* Align locations for overlapping, encoded matches

rh-pre-commit.version: 2.3.1
rh-pre-commit.check-secrets: ENABLED

* Add --max-decode-depth flag and update README help output

rh-pre-commit.version: 2.3.1
rh-pre-commit.check-secrets: ENABLED

* Move keywords off of fragment

rh-pre-commit.version: 2.3.1
rh-pre-commit.check-secrets: ENABLED

* Fix comment typo

rh-pre-commit.version: 2.3.1
rh-pre-commit.check-secrets: ENABLED

* Refactor how keywords are used in detect

rh-pre-commit.version: 2.3.1
rh-pre-commit.check-secrets: ENABLED

* Clarify comments and rename method to match

rh-pre-commit.version: 2.3.1
rh-pre-commit.check-secrets: ENABLED

* Improve performance

rh-pre-commit.version: 2.3.1
rh-pre-commit.check-secrets: ENABLED

* Fix issues after rebase

Only adjust matchIndex to fix the following line issue when not working
with encoded segments since they handle adjusting the index themselves.

rh-pre-commit.version: 2.3.1
rh-pre-commit.check-secrets: ENABLED

* Update detect/decoder.go

Don't escape characters that don't need escaping

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

* Update flag help text

rh-pre-commit.version: 2.3.1
rh-pre-commit.check-secrets: ENABLED

* Add meta data tags from decoding

rh-pre-commit.version: 2.3.1
rh-pre-commit.check-secrets: ENABLED

---------

Co-authored-by: Richard Gomez <32133502+rgmz@users.noreply.github.com>
2024-10-02 19:33:55 -05:00
Richard Gomez c5b15c9d74 refactor(config): keyword map (#1538) 2024-09-30 07:32:25 -05:00
Roger Meier a971a324fa fix: use regexTarget for extend config (#1536)
* fix: use regexTarget for extend config

* fix: add keywords from base and extended rule into global keywords list

* docs: add an example to extend default rules

* chore: update project URL references
2024-09-29 15:45:56 -05:00
Roger Meier a0f2f4671c feat: bump go to 1.22 (#1537)
support for 1.19 ended, see https://endoflife.date/go
2024-09-29 11:59:46 -05:00
Richard Gomez 4e8d7d3790 fix: handle pre-commit and staged (#1533) 2024-09-27 19:11:48 -05:00
recreator66 f8dcd838da Bugfix/1352 incorrect report multiple lines (#1501)
* fix: add logic to modify endline & endcolumn

* doc: update comment for #1352

* test: adding test file

* chore: updating generic rule

* test: adding test to TestFromFile #1352 & change static viper ConfigName

* chore: remove interim fix for #1352

* fix: adjust matchIndex[1] to fix #1352

* test: adjust expectedFinding in TestFromFiles

* chore: go fmt

* test: rm identification of start/endlineIndex

* fix: rm unused fmt pkg
2024-09-27 09:41:26 -05:00
Richard Gomez ed19c4e8b4 fix(config): extend allowlist & handle extend when validating (#1524) 2024-09-25 08:20:19 -05:00
Richard Gomez 989ef19fb0 refactor(kubernetes-secret): tweak variable chars (#1520) 2024-09-25 08:02:15 -05:00
Richard Gomez 191eb43841 Revert "remove validate config test temporarily" (#1529)
* Revert "remove validate config test temporarily"

This reverts commit 1a6d2b0a7a.

* style: fix lint error
2024-09-25 08:01:26 -05:00
Richard Gomez 78f7d3f5df feat: create fly.io rule (#1528) 2024-09-24 16:09:15 -05:00
Roger Meier 7098f6d958 fix: to many false-positive for gltf files, add gltf suffix to allowlist (#1527)
Closes #1526
2024-09-24 08:48:25 -05:00
97dbe1ef09 Add support in .gitleaksignore file comment strings (#1425) (#1502)
* Add support in .gitleaksignore file comment strings  (#1195)

* Apply suggestions from code review

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

---------

Co-authored-by: Zachary Rice <zricezrice@gmail.com>
Co-authored-by: Richard Gomez <32133502+rgmz@users.noreply.github.com>
2024-09-18 13:44:44 -05:00
Richard Gomez 9e06824372 Restrict Etsy keywords (#1491)
* feat(etsy): tweak keywords

* fix(etsy): make identifiers case sensitive
The prior commit didn't work because the identifiers are made intentionally case insensitive.
See: https://github.com/gitleaks/gitleaks/blob/4e43d1109303568509596ef5ef576fbdc0509891/cmd/generate/config/utils/generate.go#L35-L37
2024-09-18 10:24:41 -05:00
Richard Gomez db782603f7 feat(github): add entropy to rule (#1489) 2024-09-18 10:23:44 -05:00
Richard Gomez df126a7473 feat(gcp): update api key rule (#1481) 2024-09-18 10:23:18 -05:00
Richard Gomez 75dd70e59a fix(hashicorp): ignore common fps (#1498)
Based on discussion in https://github.com/gitleaks/gitleaks/issues/1490
2024-09-18 10:22:47 -05:00
Richard Gomez 8510d39ffe fix(square): make prefix case sensitive (#1469) 2024-09-18 10:22:25 -05:00
Richard Gomez 3698060a2b refactor(kubernetes-secret): collapse rules and update regex (#1462) 2024-09-18 10:22:10 -05:00
64 changed files with 3171 additions and 901 deletions

No files matched your search

+4 -1
View File
@@ -17,10 +17,13 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.19
go-version: 1.22
- name: Build
run: go build -v ./...
- name: Test
run: make test
- name: Validate Config
run: go generate ./... && git diff --exit-code
+11 -11
View File
@@ -39,7 +39,7 @@ If you want to add a new rule to the [default Gitleaks configuration](https://gi
// Regex used for detecting secrets. See regex section below for more details
Regex: generateSemiGenericRegex([]string{"beamer"}, `b_[a-z0-9=_\-]{44}`, true)
Regex: GenerateSemiGenericRegex([]string{"beamer"}, `b_[a-z0-9=_\-]{44}`, true)
// Keywords used for string matching on fragments (think of this as a prefilter)
Keywords: []string{"beamer"},
@@ -57,32 +57,32 @@ If you want to add a new rule to the [default Gitleaks configuration](https://gi
This file should be fairly self-explanatory except for a few items;
regex and secret generation. To help with maintence, _most_ rules should
be uniform. The functions,
[`generateSemiGenericRegex`](https://github.com/zricethezav/gitleaks/blob/master/cmd/generate/config/rules/rule.go#L31) and [`generateUniqueTokenRegex`](https://github.com/zricethezav/gitleaks/blob/master/cmd/generate/config/rules/rule.go#L44) will generate rules
[`GenerateSemiGenericRegex`](https://github.com/zricethezav/gitleaks/blob/master/cmd/generate/config/rules/rule.go#L31) and [`GenerateUniqueTokenRegex`](https://github.com/zricethezav/gitleaks/blob/master/cmd/generate/config/rules/rule.go#L44) will generate rules
that follow defined patterns.
The function signatures look like this:
```golang
func generateSemiGenericRegex(identifiers []string, secretRegex string, isCaseInsensitive bool) *regexp.Regexp
func GenerateSemiGenericRegex(identifiers []string, secretRegex string, isCaseInsensitive bool) *regexp.Regexp
func generateUniqueTokenRegex(secretRegex string, isCaseInsensitive bool) *regexp.Regexp
func GenerateUniqueTokenRegex(secretRegex string, isCaseInsensitive bool) *regexp.Regexp
```
`generateSemiGenericRegex` accepts a list of identifiers, a regex, and a boolean indicating whether the pattern should be case-insensitive.
`GenerateSemiGenericRegex` accepts a list of identifiers, a regex, and a boolean indicating whether the pattern should be case-insensitive.
The list of identifiers _should_ match the list of `Keywords` in the rule
definition above. Both `identifiers` in the `generateSemiGenericRegex`
definition above. Both `identifiers` in the `GenerateSemiGenericRegex`
function _and_ `Keywords` act as filters for Gitleaks telling the program
"_at least one of these strings must be present to be considered a leak_"
`generateUniqueToken` just accepts a regex and a boolean indicating whether the pattern should be case-insensitive. If you are writing a rule for a
`GenerateUniqueTokenRegex` just accepts a regex and a boolean indicating whether the pattern should be case-insensitive. If you are writing a rule for a
token that is unique enough not to require an identifier then you can use
this function. For example, Pulumi's API Token has the prefix `pul-` which is
unique enough to use `generateUniqueToken`. But something like Beamer's API
token that has a `b_` prefix is not unique enough to use `generateUniqueToken`,
so instead we use `generateSemiGenericRegex` and require a `beamer`
unique enough to use `GenerateUniqueTokenRegex`. But something like Beamer's API
token that has a `b_` prefix is not unique enough to use `GenerateUniqueTokenRegex`,
so instead we use `GenerateSemiGenericRegex` and require a `beamer`
identifier is part of the rule.
If a token's prefix has more than `3` characters then you could
probably get away with using `generateUniqueToken`.
probably get away with using `GenerateUniqueTokenRegex`.
Last thing you'll want to hit before we move on from this file is the
validation part. You can use `generateSampleSecret` to create a secret for the
+1 -1
View File
@@ -1,4 +1,4 @@
FROM golang:1.21 AS build
FROM golang:1.22 AS build
WORKDIR /go/src/github.com/zricethezav/gitleaks
COPY . .
RUN VERSION=$(git describe --tags --abbrev=0) && \
+1 -1
View File
@@ -13,7 +13,7 @@ format:
go fmt ./...
test: format
go test -v ./... --race $(PKG)
go test -v ./... --race $(PKG)
build: format
go mod tidy
+85 -40
View File
@@ -10,13 +10,13 @@
<p align="left">
<p align="left">
<a href="https://github.com/zricethezav/gitleaks/actions/workflows/test.yml">
<img alt="Github Test" src="https://github.com/zricethezav/gitleaks/actions/workflows/test.yml/badge.svg">
<a 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/zricethezav/gitleaks-action">
<a href="https://github.com/gitleaks/gitleaks-action">
<img alt="gitleaks badge" src="https://img.shields.io/badge/protected%20by-gitleaks-blue">
</a>
<a href="https://twitter.com/intent/follow?screen_name=zricethezav">
@@ -27,7 +27,7 @@
### Join our Discord! [![Discord](https://img.shields.io/discord/1102689410522284044.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/8Hzbrnkr7E)
Gitleaks is a SAST tool for **detecting** and **preventing** hardcoded secrets like passwords, api keys, and tokens in git repos. Gitleaks is an **easy-to-use, all-in-one solution** for detecting secrets, past or present, in your code.
Gitleaks is a SAST tool for **detecting** and **preventing** hardcoded secrets like passwords, API keys, and tokens in git repos. Gitleaks is an **easy-to-use, all-in-one solution** for detecting secrets, past or present, in your code.
```
➜ ~/code(master) gitleaks git -v
@@ -54,7 +54,7 @@ Fingerprint: cd5226711335c68be1e720b318b7bc3135a30eb2:cmd/generate/config/rules/
## Getting Started
Gitleaks can be installed using Homebrew, Docker, or Go. Gitleaks is also available in binary form for many popular platforms and OS types on the [releases page](https://github.com/zricethezav/gitleaks/releases). In addition, Gitleaks can be implemented as a pre-commit hook directly in your repo 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).
### Installing
@@ -110,7 +110,7 @@ jobs:
- id: gitleaks
```
for a [native execution of GitLeaks](https://github.com/zricethezav/gitleaks/releases) or use the [`gitleaks-docker` pre-commit ID](https://github.com/zricethezav/gitleaks/blob/master/.pre-commit-hooks.yaml) for executing GitLeaks using the [official Docker images](#docker)
for a [native execution of GitLeaks](https://github.com/gitleaks/gitleaks/releases) or use the [`gitleaks-docker` pre-commit ID](https://github.com/gitleaks/gitleaks/blob/master/.pre-commit-hooks.yaml) for executing GitLeaks using the [official Docker images](#docker)
3. Auto-update the config to the latest repos' versions by executing `pre-commit autoupdate`
4. Install with `pre-commit install`
@@ -157,6 +157,7 @@ Flags:
-h, --help help for gitleaks
--ignore-gitleaks-allow ignore gitleaks:allow comments
-l, --log-level string log level (trace, debug, info, warn, error, fatal) (default "info")
--max-decode-depth int allow recursive decoding up to this depth (default "0", no decoding is done)
--max-target-megabytes int files larger than this will be skipped
--no-banner suppress banner
--no-color turn off color for verbose output
@@ -231,7 +232,7 @@ title = "Gitleaks title"
# useDefault and path can NOT be used at the same time. Choose one.
[extend]
# useDefault will extend the base configuration with the default gitleaks config:
# https://github.com/zricethezav/gitleaks/blob/master/config/gitleaks.toml
# https://github.com/gitleaks/gitleaks/blob/master/config/gitleaks.toml
useDefault = true
# or you can supply a path to a configuration. Path is relative to where gitleaks
# was invoked, not the location of the base config.
@@ -251,13 +252,6 @@ description = "awesome rule 1"
# does not support lookaheads.
regex = '''one-go-style-regex-for-this-rule'''
# Golang regular expression used to match paths. This can be used as a standalone rule or it can be used
# in conjunction with a valid `regex` entry.
path = '''a-file-path-regex'''
# Array of strings used for metadata and reporting purposes.
tags = ["tag","another tag"]
# Int used to extract secret from regex match and used as the group that will have
# its entropy checked if `entropy` is set.
secretGroup = 3
@@ -265,6 +259,10 @@ secretGroup = 3
# Float representing the minimum shannon entropy a regex group must have to be considered a secret.
entropy = 3.5
# Golang regular expression used to match paths. This can be used as a standalone rule or it can be used
# in conjunction with a valid `regex` entry.
path = '''a-file-path-regex'''
# Keywords are used for pre-regex check filtering. Rules that contain
# keywords will perform a quick string compare check to make sure the
# keyword(s) are in the content being scanned. Ideally these values should
@@ -276,30 +274,50 @@ keywords = [
"token",
]
# You can include an allowlist table for a single rule to reduce false positives or ignore commits
# with known/rotated secrets
[rules.allowlist]
description = "ignore commit A"
commits = [ "commit-A", "commit-B"]
paths = [
'''go\.mod''',
'''go\.sum'''
]
# note: (rule) regexTarget defaults to check the _Secret_ in the finding.
# if regexTarget is not specified then _Secret_ will be used.
# Acceptable values for regexTarget are "match" and "line"
regexTarget = "match"
regexes = [
'''process''',
'''getenv''',
]
# note: stopwords targets the extracted secret, not the entire regex match
# like 'regexes' does. (stopwords introduced in 8.8.0)
stopwords = [
'''client''',
'''endpoint''',
]
# Array of strings used for metadata and reporting purposes.
tags = ["tag","another tag"]
# ⚠️ In v8.21.0 `[rules.allowlist]` was replaced with `[[rules.allowlists]]`.
# This change was backwards-compatible: instances of `[rules.allowlist]` still work.
#
# You can define multiple allowlists for a rule to reduce false positives.
# A finding will be ignored if _ANY_ `[[rules.allowlists]]` matches.
[[rules.allowlists]]
description = "ignore commit A"
# When multiple criteria are defined the default condition is "OR".
# e.g., this can match on |commits| OR |paths| OR |stopwords|.
condition = "OR"
commits = [ "commit-A", "commit-B"]
paths = [
'''go\.mod''',
'''go\.sum'''
]
# note: stopwords targets the extracted secret, not the entire regex match
# like 'regexes' does. (stopwords introduced in 8.8.0)
stopwords = [
'''client''',
'''endpoint''',
]
[[rules.allowlists]]
# The "AND" condition can be used to make sure all criteria match.
# e.g., this matches if |regexes| AND |paths| are satisified.
condition = "AND"
# note: |regexes| defaults to check the _Secret_ in the finding.
# Acceptable values for |regexTarget| are "secret" (default), "match", and "line".
regexTarget = "match"
regexes = [ '''(?i)parseur[il]''' ]
paths = [ '''package-lock\.json''' ]
# You can extend a particular rule from the default config. e.g., gitlab-pat
# if you have defined a custom token prefix on your GitLab instance
[[rules]]
id = "gitlab-pat"
# all the other attributes from the default rule are inherited
[[rules.allowlists]]
regexTarget = "line"
regexes = [ '''MY-glpat-''' ]
# This is a global allowlist which has a higher order of precedence than rule-specific allowlists.
# If a commit listed in the `commits` field below is encountered then that commit will be skipped and no
@@ -316,7 +334,6 @@ paths = [
# if regexTarget is not specified then _Secret_ will be used.
# Acceptable values for regexTarget are "match" and "line"
regexTarget = "match"
regexes = [
'''219-09-9999''',
'''078-05-1120''',
@@ -330,7 +347,7 @@ stopwords = [
]
```
Refer to the default [gitleaks config](https://github.com/zricethezav/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
@@ -347,9 +364,37 @@ class CustomClass:
#### .gitleaksignore
You can ignore specific findings by creating a `.gitleaksignore` file at the root of your repo. In release v8.10.0 Gitleaks added a `Fingerprint` value to the Gitleaks report. Each leak, or finding, has a Fingerprint that uniquely identifies a secret. Add this fingerprint to the `.gitleaksignore` file to ignore that specific secret. See Gitleaks' [.gitleaksignore](https://github.com/zricethezav/gitleaks/blob/master/.gitleaksignore) for an example. Note: this feature is experimental and is subject to change in the future.
You can ignore specific findings by creating a `.gitleaksignore` file at the root of your repo. In release v8.10.0 Gitleaks added a `Fingerprint` value to the Gitleaks report. Each leak, or finding, has a Fingerprint that uniquely identifies a secret. Add this fingerprint to the `.gitleaksignore` file to ignore that specific secret. See Gitleaks' [.gitleaksignore](https://github.com/gitleaks/gitleaks/blob/master/.gitleaksignore) for an example. Note: this feature is experimental and is subject to change in the future.
#### Decoding
Sometimes secrets are encoded in a way that can make them difficult to find
with just regex. Now you can tell gitleaks to automatically find and decode
encoded text. The flag `--max-decode-depth` enables this feature (the default
value "0" means the feature is disabled by default).
Recursive decoding is supported since decoded text can also contain encoded
text. The flag `--max-decode-depth` sets the recursion limit. Recursion stops
when there are no new segments of encoded text to decode, so setting a really
high max depth doesn't mean it will make that many passes. It will only make as
many as it needs to decode the text. Overall, decoding only minimally increases
scan times.
The findings for encoded text differ from normal findings in the following
ways:
- The location points the bounds of the encoded text
- If the rule matches outside the encoded text, the bounds are adjusted to
include that as well
- The match and secret contain the decoded value
- Two tags are added `decoded:<encoding>` and `decode-depth:<depth>`
Currently supported encodings:
- `base64` (both standard and base64url)
## Sponsorships
<p align="left">
<h3><a href="https://coderabbit.ai/?utm_source=oss&utm_medium=sponsorship&utm_campaign=gitleaks">coderabbit.ai</h3>
<a href="https://coderabbit.ai/?utm_source=oss&utm_medium=sponsorship&utm_campaign=gitleaks">
-1
View File
@@ -43,7 +43,6 @@ func runDirectory(cmd *cobra.Command, args []string) {
// start timer
start := time.Now()
detector := Detector(cmd, cfg, source)
// set exit code
+111
View File
@@ -0,0 +1,111 @@
package base
import (
"fmt"
"github.com/zricethezav/gitleaks/v8/config"
"regexp"
"strings"
)
func CreateGlobalConfig() config.Config {
return config.Config{
Title: "gitleaks config",
Allowlist: config.Allowlist{
Description: "global allow lists",
Regexes: []*regexp.Regexp{
// ----------- General placeholders -----------
regexp.MustCompile(`(?i)^true|false|null$`),
// Awkward workaround to detect repeated characters.
func() *regexp.Regexp {
var (
letters = "abcdefghijklmnopqrstuvwxyz*."
patterns []string
)
for _, char := range letters {
if char == '*' || char == '.' {
patterns = append(patterns, fmt.Sprintf("\\%c+", char))
} else {
patterns = append(patterns, fmt.Sprintf("%c+", char))
}
}
return regexp.MustCompile("^(?i:" + strings.Join(patterns, "|") + ")$")
}(),
// ----------- Environment Variables -----------
regexp.MustCompile(`^\$(\d+|{\d+})$`),
regexp.MustCompile(`^\$([A-Z_]+|[a-z_]+)$`),
regexp.MustCompile(`^\${([A-Z_]+|[a-z_]+)}$`),
// ----------- Interpolated Variables -----------
// Ansible (https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_variables.html)
regexp.MustCompile(`^\{\{[ \t]*[\w ().|]+[ \t]*}}$`),
// GitHub Actions
// https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/store-information-in-variables
// https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions
regexp.MustCompile(`^\$\{\{[ \t]*((env|github|secrets|vars)(\.[A-Za-z]\w+)+[\w "'&./=|]*)[ \t]*}}$`),
// NuGet (https://learn.microsoft.com/en-us/nuget/reference/nuget-config-file#using-environment-variables)
regexp.MustCompile(`^%([A-Z_]+|[a-z_]+)%$`),
// String formatting.
regexp.MustCompile(`^%[+\-# 0]?[bcdeEfFgGoOpqstTUvxX]$`), // Golang (https://pkg.go.dev/fmt)
regexp.MustCompile(`^\{\d{0,2}}$`), // Python (https://docs.python.org/3/tutorial/inputoutput.html)
// Urban Code Deploy (https://www.ibm.com/support/pages/replace-token-step-replaces-replacement-values-windows-variables)
regexp.MustCompile(`^@([A-Z_]+|[a-z_]+)@$`),
},
Paths: []*regexp.Regexp{
regexp.MustCompile(`gitleaks\.toml`),
// ----------- Documents and media -----------
regexp.MustCompile(`(?i)\.(bmp|gif|jpe?g|svg|tiff?)$`), // Images
regexp.MustCompile(`\.(eot|[ot]tf|woff2?)$`), // Fonts
regexp.MustCompile(`(.*?)(doc|docx|zip|xls|pdf|bin|socket|vsidx|v2|suo|wsuo|.dll|pdb|exe|gltf)$`),
// ----------- Golang files -----------
regexp.MustCompile(`go\.(mod|sum|work(\.sum)?)$`),
regexp.MustCompile(`(^|/)vendor/modules\.txt$`),
regexp.MustCompile(`(^|/)vendor/(github\.com|golang\.org/x|google\.golang\.org|gopkg\.in|istio\.io|k8s\.io|sigs\.k8s\.io)/.*$`),
// ----------- Java files -----------
// Gradle
regexp.MustCompile(`(^|/)gradlew(\.bat)?$`),
regexp.MustCompile(`(^|/)gradle\.lockfile$`),
regexp.MustCompile(`(^|/)mvnw(\.cmd)?$`),
regexp.MustCompile(`(^|/)\.mvn/wrapper/MavenWrapperDownloader\.java$`),
// ----------- Node.js files -----------
// Dependencies and lock files.
regexp.MustCompile(`(^|/)node_modules/.*?$`),
regexp.MustCompile(`(^|/)package-lock\.json$`),
regexp.MustCompile(`(^|/)yarn\.lock$`),
regexp.MustCompile(`(^|/)pnpm-lock\.yaml$`),
regexp.MustCompile(`(^|/)npm-shrinkwrap\.json$`),
regexp.MustCompile(`(^|/)bower_components/.*?$`),
// ----------- Python files -----------
// Dependencies and lock files.
regexp.MustCompile(`(^|/)Pipfile\.lock$`),
regexp.MustCompile(`(^|/)poetry\.lock$`),
// Virtual environments
// env/lib/python3.7/site-packages/urllib3/util/url.py
regexp.MustCompile(`(?i)/?(v?env|virtualenv)/lib/.+$`),
// /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
regexp.MustCompile(`(?i)/?python/[23](\.\d{1,2})+/lib/.+$`),
// python/lib/python3.8/site-packages/boto3/data/ec2/2016-04-01/resources-1.json
// python/lib/python3.8/site-packages/botocore/data/alexaforbusiness/2017-11-09/service-2.json
regexp.MustCompile(`(?i)/?python/lib/python[23](\.\d{1,2})+/.+$`),
// dist-info directory (https://py-pkgs.org/04-package-structure.html#building-sdists-and-wheels)
regexp.MustCompile(`(?i)(^|/)[a-z0-9_.]+-[0-9.]+\.dist-info/.+$`),
// ----------- Ruby files -----------
regexp.MustCompile(`(^|/)vendor/(bundle|ruby)/.*?$`),
regexp.MustCompile(`\.gem$`), // tar archive
// Misc
regexp.MustCompile(`verification-metadata.xml`),
regexp.MustCompile(`Database.refactorlog`),
//regexp.MustCompile(`vendor`),
},
},
}
}
+85
View File
@@ -0,0 +1,85 @@
package base
import (
"testing"
)
func TestConfigAllowlistRegexes(t *testing.T) {
tests := map[string]struct {
invalid []string
valid []string
}{
"general placeholders": {
invalid: []string{
`true`, `True`, `false`, `False`, `null`, `NULL`,
},
},
"general placeholders - repeated characters": {
invalid: []string{
`aaaaaaaaaaaaaaaaa`, `BBBBBBBBBBbBBBBBBBbBB`, `********************`,
},
valid: []string{`aaaaaaaaaaaaaaaaaaabaa`, `pas*************d`},
},
"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 - github actions": {
invalid: []string{
`${{ 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 - nuget": {
invalid: []string{
`%MY_PASSWORD%`, `%password%`,
},
},
"interpolated variables - string fmt - golang": {
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 - python": {
invalid: []string{
`{}`, `{0}`, `{10}`,
},
},
"interpolated variables - ucd": {
invalid: []string{`@password@`, `@LDAP_PASS@`},
valid: []string{`@username@mastodon.example`},
},
}
cfg := CreateGlobalConfig()
allowlist := cfg.Allowlist
for name, cases := range tests {
t.Run(name, func(t *testing.T) {
for _, c := range cases.invalid {
if !allowlist.RegexAllowed(c) {
t.Errorf("invalid value not marked as allowed: %s", c)
}
}
for _, c := range cases.valid {
if allowlist.RegexAllowed(c) {
t.Errorf("valid value marked as allowed: %s", c)
}
}
})
}
}
+10 -3
View File
@@ -1,6 +1,7 @@
package main
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/base"
"os"
"text/template"
@@ -37,6 +38,7 @@ func main() {
rules.Atlassian(),
rules.Authress(),
rules.AWS(),
rules.AzureActiveDirectoryClientSecret(),
rules.BitBucketClientID(),
rules.BitBucketClientSecret(),
rules.BittrexAccessKey(),
@@ -48,6 +50,7 @@ func main() {
rules.CloudflareAPIKey(),
rules.CloudflareGlobalAPIKey(),
rules.CloudflareOriginCAKey(),
rules.CohereAPIToken(),
rules.ConfluentAccessToken(),
rules.ConfluentSecretKey(),
rules.Contentful(),
@@ -81,6 +84,7 @@ func main() {
rules.FlutterwavePublicKey(),
rules.FlutterwaveSecretKey(),
rules.FlutterwaveEncKey(),
rules.FlyIOAccessToken(),
rules.FrameIO(),
rules.FreshbooksAccessToken(),
rules.GoCardless(),
@@ -113,8 +117,7 @@ func main() {
rules.JWT(),
rules.JWTBase64(),
rules.KrakenAccessToken(),
rules.KubernetesSecretWithDataAfter(),
rules.KubernetesSecretWithDataBefore(),
rules.KubernetesSecret(),
rules.KucoinAccessToken(),
rules.KucoinSecretKey(),
rules.LaunchDarklyAccessToken(),
@@ -138,6 +141,7 @@ func main() {
rules.NewRelicBrowserAPIKey(),
rules.NewRelicInsertKey(),
rules.NPM(),
rules.NugetConfigPassword(),
rules.NytimesAccessToken(),
rules.OktaAccessToken(),
rules.OpenAI(),
@@ -150,6 +154,7 @@ func main() {
rules.PlanetScaleOAuthToken(),
rules.PostManAPI(),
rules.Prefect(),
rules.PrivateAIToken(),
rules.PrivateKey(),
rules.PulumiAPIToken(),
rules.PyPiUploadToken(),
@@ -227,7 +232,9 @@ func main() {
log.Fatal().Err(err).Msg("Failed to create rules.toml")
}
if err = tmpl.Execute(f, config.Config{Rules: ruleLookUp}); err != nil {
cfg := base.CreateGlobalConfig()
cfg.Rules = ruleLookUp
if err = tmpl.Execute(f, cfg); err != nil {
log.Fatal().Err(err).Msg("could not execute template")
}
+65
View File
@@ -0,0 +1,65 @@
package rules
import (
"fmt"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
// References:
// - https://learn.microsoft.com/en-us/microsoft-365/compliance/sit-defn-azure-ad-client-secret
// - https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app#add-credentials
func AzureActiveDirectoryClientSecret() *config.Rule {
// define rule
r := config.Rule{
RuleID: "azure-ad-client-secret",
Description: "Azure AD Client Secret",
// After inspecting dozens of secrets, I'm fairly confident that they start with `xxx\dQ~`.
// However, this may not be (entirely) true, and this rule might need to be further refined in the future.
// Furthermore, it's possible that secrets have a checksum that could be used to further constrain this pattern.
Regex: regexp.MustCompile(`(?:^|[\\'"\x60\s>=:(,)])([a-zA-Z0-9_~.]{3}\dQ~[a-zA-Z0-9_~.-]{31,34})(?:$|[\\'"\x60\s<),])`), // wtf, Go? https://github.com/golang/go/issues/18221
Entropy: 3,
Keywords: []string{
"Q~",
},
}
// validate
tps := []string{
`client_secret=bP88Q~rcBcYjzzOhg1Hnn76Wm3jGgakZiZ.8vMgR`, // gitleaks:allow
`client_secret=bP88Q~rcBcYjzzOhg1Hnn76Wm3jGgakZiZ.8vMgR
`, // gitleaks:allow
`client_secret: .IQ8Q~79R7TOWOspFnWcEG-dYt4KXqFqxK16cxr`, // gitleaks:allow
`AUTH_CLIENTSECRET = _V28Q~IC8qxmlWNpHuDm34JlbKv9LXV5MvUR3a-P`, // gitleaks:allow
`<value xsi:type="xsd:string">~Gg8Q~nVhlLi2vpg_nXBGqFsbGK-t~Hus1JmTa0y</value>`, // gitleaks:allow
`"CLIENT_SECRET": "YYz7Q~Sudoqwap1PnzEBA3zqBK~i5uesDIv.C"`, // gitleaks:allow
`Set-PSUAuthenticationMethod -Type 'OpenIDConnect' -CallbackPath '/auth/oidc' -ClientId 'fake' -ClientSecret '2Vq7Q~q5VgKljZ7cb3.0sp0Apz.vOjRIPyeTr'`, // gitleaks:allow
`client-secret: "t028Q~-aLbmQuinnZtzbgtlEAYstnBWEmGPAoBm"`, // gitleaks:allow
`"cas.authn.azure-active-directory.client-secret=qHF8Q~PCM5HhMoyTFc5TYEomnzR6Kim9UJhe8a.P",`, // gitleaks:allow
`"line": "client_srt = \"qpF8Q~PCM5MhMoyTFc5TYEomnYRUKim9UJhe8a2P\";",`, // gitleaks:allow
`"client_secret": acctest.Representation{RepType: acctest.Required, Create: 'dO29Q~F5-VwnW.lZdd11xFF_t5NAXCaGwDl9NbT1'},`, // gitleaks:allow
`Example= GN.7Q~4AkLZBNEbz4Jxlm~O5G6SsyFxYg6zMR`, // gitleaks:allow
`"the_value": "QtT8Q~9C-_Ij~RouHVpD2Tuf3oHWGh.DQ3kcjbAn"`, // gitleaks:allow
`QtT8Q~9C-_Ij~RouHVpD2Tuf3oHWGh.DQ3kcjbAn`, // gitleaks:allow
`(use the client secret: QtT8Q~9C-_Ij~RouHVpD2Tuf3oHWGh.DQ3kcjbAn)`, // gitleaks:allow
`(QtT8Q~9C-_Ij~RouHVpD2Tuf3oHWGh.DQ3kcjbAn)`, // gitleaks:allow
`\"pass\": \"` + fmt.Sprintf("%s%sQ~%s", secrets.NewSecret(`[\w~.]{3}`), secrets.NewSecret(utils.Numeric("1")), secrets.NewSecret(`[\w~.-]{31,34}`)),
}
fps := []string{
`![图源:《深入拆解Tomcat & Jetty》](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/6a9e704af49b4380bb686f0c96d33b81~tplv-k3u1fbpfcp-watermark.image)`,
`~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`,
`~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`,
`.ui.visible.right.sidebar~.ui.visible.left.sidebar~.pusher{transform:translate3d(0,0,0)}`,
`buf.WriteString("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n::\n\n")`,
`'url': 'http://www.2doc.nl/speel~VARA_101375237~mh17-het-verdriet-van-nederland~.html',`,
`@ar = split("~", "965f1453~47~09414c93e4cef985416f472549220827da3ba6fed8ad28e29ef6ad170ad53a69051e9b06f439ef6da5df8670181f7eb2481650");`,
`'#!/registries/5/portainer.demo~2Fportainerregistrytesting~2Falpine',`,
`// CloudFront-Signature: Ixn4bF1LLrLcB8XG-t5bZbIB0vfwSF2s4gkef~PcNBdx73MVvZD3v8DZ5GzcqNrybMiqdYJY5KqK6vTsf5JXDgwFFz-h98wdsbV-izcuonPdzMHp4Ay4qyXM6Ed5jB9dUWYGwMkA6rsWXpftfX8xmk4tG1LwFuJV6nAsx4cfpuKwo4vU2Hyr2-fkA7MZG8AHkpDdVUnjm1q-Re9HdG0nCq-2lnBAdOchBpJt37narOj-Zg6cbx~6rzQLVQd8XIv-Bn7VTc1tkBAJVtGOHb0Q~PLzSRmtNGYTnpL0z~gp3tq8lhZc2HuvJW5-tZaYP9yufeIzk5bqsT6DT4iDuclKKw__, , , false`,
`+ "<Trust Comment=\"\" Identity=\"USK@u2vn3Lh6Kte2-TgBSNKorbsKkuAt34ckoLmgx0ndXO0,4~q8Q~3wIHjX9DT0yCNfQmr9oxmYrDZoQVLOdNg~yk0,AQACAAE/WebOfTrustRC2/2\" Value=\"100\"/>"`,
`client_secret=bP88Q~xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`,
}
return utils.Validate(r, tps, fps)
}
+32
View File
@@ -0,0 +1,32 @@
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 CohereAPIToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "cohere-api-token",
Description: "Identified a Cohere Token, posing a risk of unauthorized access to AI services and data manipulation.",
Regex: utils.GenerateSemiGenericRegex([]string{"cohere", "CO_API_KEY"}, `[a-zA-Z0-9]{40}`, false),
Entropy: 4,
Keywords: []string{
"cohere",
"CO_API_KEY",
},
}
// validate
tps := []string{
utils.GenerateSampleSecret("cohere", secrets.NewSecret(`[a-zA-Z0-9]{40}`)),
// https://github.com/cohere-ai/cohere-go/blob/abe8044073ed498ffbb206a602d03c2414b64512/client/client.go#L38C30-L38C40
`export CO_API_KEY=` + secrets.NewSecret(`[a-zA-Z0-9]{40}`),
}
fps := []string{
`CO_API_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`,
}
return utils.Validate(r, tps, fps)
}
+34 -35
View File
@@ -1,31 +1,27 @@
# This file has been auto-generated. Do not edit manually.
# If you would like to contribute new rules, please use
# cmd/generate/config/main.go and follow the contributing guidelines
# at https://github.com/zricethezav/gitleaks/blob/master/CONTRIBUTING.md
# at https://github.com/gitleaks/gitleaks/blob/master/CONTRIBUTING.md
# This is the default gitleaks configuration file.
# Rules and allowlists are defined within this file.
# Rules instruct gitleaks on what should be considered a secret.
# Allowlists instruct gitleaks on what is allowed, i.e. not a secret.
title = "gitleaks config"
title = "{{.Title}}"
[allowlist]
description = "global allow lists"
paths = [
'''gitleaks.toml''',
'''(.*?)(jpg|gif|doc|docx|zip|xls|pdf|bin|svg|socket|vsidx|v2|suo|wsuo|.dll|pdb|exe)$''',
'''(go.mod|go.sum|go.work|go.work.sum)$''',
'''gradle.lockfile''',
'''verification-metadata.xml''',
'''node_modules''',
'''package-lock.json''',
'''yarn.lock''',
'''pnpm-lock.yaml''',
'''poetry.lock''',
'''Database.refactorlog''',
'''vendor''',
]
description = "{{.Allowlist.Description}}"
{{- with .Allowlist.RegexTarget }}
regexTarget = "{{ . }}"{{ end -}}
{{- with .Allowlist.Regexes }}
regexes = [{{ range $i, $regex := . }}
'''{{ $regex }}''',{{ end }}
]{{ end }}
{{- with .Allowlist.Paths }}
paths = [{{ range $i, $path := . }}
'''{{ $path }}''',{{ end }}
]{{ end }}
{{ range $i, $rule := .Rules }}[[rules]]
id = "{{$rule.RuleID}}"
@@ -38,29 +34,32 @@ secretGroup = {{ . }}{{ end -}}
{{- with $rule.Entropy }}
entropy = {{ . }}{{ end -}}
{{- with $rule.Keywords }}
keywords = [
{{ range $j, $keyword := . }}"{{ $keyword }}",{{ end }}
]{{ end }}
{{- if gt (len .) 1}}
keywords = [{{ range $j, $keyword := . }}
"{{ $keyword }}",{{ end }}
]{{else}}
keywords = [{{ range $j, $keyword := . }}"{{ $keyword }}"{{ end }}]{{end}}{{ end }}
{{- with $rule.Tags }}
tags = [
{{ range $j, $tag := . }}"{{ $tag }}",{{ end }}
]{{ end }}
{{ if or $rule.Allowlist.Regexes $rule.Allowlist.Paths $rule.Allowlist.Commits $rule.Allowlist.StopWords }}
[rules.allowlist]
{{ with $rule.Allowlist.RegexTarget }}
regexTarget = "{{ . }}"{{ end -}}
{{- with $rule.Allowlist.Regexes }}
regexes = [
{{ range $j, $regex := . }}"{{ $regex }}",{{ end }}
]{{ end }}
{{- with $rule.Allowlist.Paths }}paths = [
{{ range $j, $path := . }}"{{ $path }}",{{ end }}
]{{ end }}
{{- with $rule.Allowlist.Commits }}commits = [
{{ with $rule.Allowlists }}{{ range $i, $allowlist := . }}{{ if or $allowlist.Regexes $allowlist.Paths $allowlist.Commits $allowlist.StopWords }}
[[rules.allowlists]]
{{ with $allowlist.MatchCondition }}condition = "{{ . }}"
{{ end -}}
{{- with $allowlist.Commits }}commits = [
{{ range $j, $commit := . }}"{{ $commit }}",{{ end }}
]{{ end }}
{{- with $rule.Allowlist.StopWords }}stopwords = [{{ range $j, $stopword := . }}
"{{ $stopword }}",{{ end }}
{{- with $allowlist.Paths }}paths = [
{{ range $j, $path := . }}'''{{ $path }}''',{{ end }}
]{{ end }}
{{- with $allowlist.RegexTarget }}regexTarget = "{{ . }}"
{{ end -}}
{{- with $allowlist.Regexes }}regexes = [{{ range $i, $regex := . }}
'''{{ $regex }}''',{{ end }}
]{{ end }}
{{- with $allowlist.StopWords }}stopwords = [{{ range $j, $stopword := . }}
"{{ $stopword }}",{{ end }}
]{{ end }}{{ end }}{{ end }}
{{ end }}
{{ end }}
{{ end -}}
+12 -3
View File
@@ -1,6 +1,7 @@
package rules
import (
"fmt"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
@@ -11,8 +12,8 @@ func EtsyAccessToken() *config.Rule {
r := config.Rule{
RuleID: "etsy-access-token",
Description: "Found an Etsy Access Token, potentially compromising Etsy shop management and customer data.",
Regex: utils.GenerateSemiGenericRegex([]string{"etsy"}, utils.AlphaNumeric("24"), true),
Regex: utils.GenerateSemiGenericRegex([]string{"(?-i:ETSY|[Ee]tsy)"}, utils.AlphaNumeric("24"), true),
Entropy: 3,
Keywords: []string{
"etsy",
},
@@ -20,7 +21,15 @@ func EtsyAccessToken() *config.Rule {
// validate
tps := []string{
utils.GenerateSampleSecret("ETSY", secrets.NewSecret(utils.AlphaNumeric("24"))),
utils.GenerateSampleSecret("etsy", secrets.NewSecret(utils.AlphaNumeric("24"))),
utils.GenerateSampleSecret("Etsy", secrets.NewSecret(utils.AlphaNumeric("24"))),
}
return utils.Validate(r, tps, nil)
fps := []string{
fmt.Sprintf(`SetSysctl = "%s"`, secrets.NewSecret(utils.AlphaNumeric("24"))),
` if err := sysctl.SetSysctl(sysctlBridgeCallIPTables); err != nil {`,
`g6Rib2R5hqhkZXRhY2hlZMOpaGFzaF90eXBlCqNrZXnEIwEgETSYcPQGcaAxl8vuQDLahSfhxkEEHu2flbF9ErAooEoKp3BheWxvYWTFAwB7ImJvZHkiOnsia2V5Ijp7ImVsZGVzdF9raWQiOiIwMTIwMTEzNDk4NzBmNDA2NzFhMDMxOTdjYmVlNDAzMmRhODUyN2UxYzY0MTA0MWVlZDlmOTViMTdkMTJiMDI4YTA0YTBhIiwiaG9zdCI6ImtleWJhc2UuaW8iLCJraWQiOiIwMTIwMTEzNDk4NzBmNDA2NzFhMDMxOTdjYmVlNDAzMmRhODUyN2UxYzY0MTA0MWVlZDlmOTViMTdkMTJiMDI4YTA0YTBhIiwidWlkIjoiYzUyZjc2M2MxNzYyNWZiMTI5YWU1ZDZmZThhMGUzMTkiLCJ1c2VybmFtZSI6ImttYXJla3NwYXJ0eiJ9LCJzZXJ2aWNlIjp7Imhvc3RuYW1lIjoia3lsZS5tYXJlay1zcGFydHoub3JnIiwicHJvdG9jb2wiOiJodHRwOiJ9LCJ0eXBlIjoid2ViX3NlcnZpY2VfYmluZGluZyIsInZlcnNpb24iOjF9LCJjbGllbnQiOnsibmFtZSI6ImtleWJhc2UuaW8gZ28gY2xpZW50IiwidmVyc2lvbiI6IjEuMC4xNCJ9LCJjdGltZSI6MTQ1ODU5MDYyMSwiZXhwaXJlX2luIjo1MDQ1NzYwMDAsIm1lcmtsZV9yb290Ijp7ImN0aW1lIjoxNDU4NTkwNTgzLCJoYXNoIjoiODQ0ZWRkNGU0OTQ3MWUzNWQxZTFkOTM5YTc0ZjUwMDc5Nzg3NzljMTAwYzY1NGE2OGI1NDNhYzY2Y2NlYTQ1MGFjNTllNmY3Yjc4ZGZiN2MyYzdjMmYwMzJiYTA2MzdjMzVjZDk1ZGYyZmRiNjFlNjgxMjVmNDkxNjVlZDkwNzMiLCJzZXFubyI6NDE3Mjk5fSwicHJldiI6IjdmNWFkMGZlZmQxNjM4ZjBlOTc1MTk3NzA5YTk2OTVkZmQ1NzU0MTA4NTYxZGUzMDM0ODc2NDcxODdhMDkyYzUiLCJzZXFubyI6OSwidGFnIjoic2lnbmF0dXJlIn2jc2lnxEDDVCB/SdOzo+BznIUCCa5DgISbH+0noUjyAJ4r0sH/tj8lYNpHw3WR93SBCufeElsl7KrxVdg5qU5ADYj26wgOqHNpZ190eXBlIKN0YWfNAgKndmVyc2lvbgE=`,
`in XCBuild.XCBBuildServiceSession.setSystemInfo(operatingSystemVersion: __C.NSOperatingSystemVersion, productBuildVersion: Swift.String, nativeArchitecture: Swift.String, completion: (Swift.Bool) -> ()) -> ()`,
}
return utils.Validate(r, tps, fps)
}
+54
View File
@@ -0,0 +1,54 @@
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"
)
// https://fly.io/docs/security/tokens/
// https://github.com/trufflesecurity/trufflehog/pull/2381/files#r1565860579
// https://github.com/superfly/macaroon-elixir/blob/8b42043b0a24aada5c8b8eb8505dbf1590557f1b/test/vectors.json#L7
func FlyIOAccessToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "flyio-access-token",
Description: "Uncovered a Fly.io API key", // TODO
Regex: utils.GenerateUniqueTokenRegex(`(?:fo1_[\w-]{43}|fm1[ar]_[a-zA-Z0-9+\/]{100,}={0,3}|fm2_[a-zA-Z0-9+\/]{100,}={0,3})`, false),
Entropy: 4,
Keywords: []string{"fo1_", "fm1", "fm2_"},
}
// validate
tps := []string{
// fo1_
utils.GenerateSampleSecret("fly", secrets.NewSecret(`fo1_[\w-]{43}`)),
`Fly access token: fo1_8rz-j7r2eqJ2U7affEOO3HJN0j63DInyog3eV-glQSc
`,
`=============================================================================================================
fo1_BtKlzvfztw0M2hlLgTdsfPgDFiwM2jJjQXXy6I2pjuQ
fly deploy`,
// fm1
utils.GenerateSampleSecret("fly", secrets.NewSecret(`fm1[ar]_[a-zA-Z0-9+\/]{100,}={0,3}`)),
`ENV FLY_API_TOKEN="FlyV1 fm1r_lJPECAAAAAAAAMqcxBBLMJKXYKJiT0CI58XmukX/wrVodHlwczovL2FwaS5mbHkuaW8vdjGWAJLOAAFmXh8Lk7lodHRwczovL2FwaS5mbHkuaW8vYWFhL3YxxDy5OfA2M6K6aLEoEDKxehojbj+8ZT9IrXCF5sL/r8m6/1gylwySsNxpD40wnpd/G2ZdjwVaQev1kEuFUgzERxPbtWHDNa+NYIZwbKN6b7/JxdbUprq0M10HI4fwtlxhqhdA/mMaMw70EC4TsfJyghIL98KP4ry5AaXiroRdjrSsFExc/xRCDZKUA5GBzgATuNsfBZGCp2J1aWxkZXIfondnHwHEIMa6NWc4b52S+UY7vjPdwKrz00Uzrc1830mOHzQNLun7,fm1a_lJPERxPbtWHDNa+NYIZwbKN6b7/JxdbUprq0M10HI4fwtlxhqhdA/mMaMw70EC4TsfJyghIL98KP4ry4AaXiroRdjrSsFExc/xRCxBCVlAoRzKV/+qYkxuipIbIcw7lodHRwczovL2FwaS5mbHkuaW8vYWFhL3YxlgSSzmS4Y7nPAAAAASCwgdcKkc4AAUktDMQQURck2h+upbiOrW66Nf5SA8QgrD03xlWju1WQi0AUhlk7YYFzOLDfhRyJ6nEziO37NUE="`,
// fm2
utils.GenerateSampleSecret("fly", secrets.NewSecret(`fm2_[a-zA-Z0-9+\/]{100,}={0,3}`)),
`# FLY_API_TOKEN: FlyV1 fm2_lJPECAAAAAAAAyZtxBD1hSZ7L5leXsj64ZbDlkm/wrVodHRwczovL2FwaS5mbHkuaW8vdjGWAJLOAAwMDB8Lk7lodHRwczovL2FwaS5mbHkuaW8vYWFhL3YxxDwDnhgJj/ML/nRKMiAYgnvXfNacrGWffj5TdfgGY2LU0ZetT7WzTLQQMO8cN2nRTztl/xLjnnZg5pBwFonETmhNA6Yl0X1tatt8ezA0UjVQiJr93VQ7qAmD5GG2Ce5txhbQv3tmIGsvaC7BOkIqAiR273bhZkO44AYsrCPr2XF8W6Twk7NyU+3UUeDwjw2SlAORgc4APu7vHwWRgqdidWlsZGVyH6J3Zx8BxCAlmLbu1HQDg8ZAGKKmEt4Mbnbqli6lbzBDHsawhcUF4A==,fm2_lJPETmhNA6Yl0X1tatt8ezA0UjVQiJr93VQ7qAmD5GG2Ce5txhbQv3tmIGsvaC7BOkIqAij273bhZkO44AYsrCPr2XF8W6Twk7NyU+3UUeDwj8QQbn07DOV+7SmoLj/uT+dbr8O5aHR0cHM6Ly9hcGkuZmx5LmlvL2FhYS92MZgEks5mqfbvzwAAAAE9PYz9F84AC7QACpHOAAu0AAzEEFfW3B+SzffV/KrAYa8qqpnEIIlD6DqZMZQ9Kt7fEenCCOLA+tUSJ+kmEFIUcc83npOI`,
`"BindToParentToken": "FlyV1 fm2_lJPEEKnzKy0lkwV3B+WIlmrdwejEEFv5qmevHU4fMs+2Gr6oOiPC2SAyOTc0NWI4ZmJlNjBlNjJmZTgzNTkxOThhZWE4MjY0M5IMxAMBAgPEIH7VG8u74KwO62hmx8SZO8WaU5o1g3W2IVc7QN6T1VTr",`,
}
fps := []string{
// fo1_
`resource "doppler_integration_flyio" "prod" {
name = "TF Fly.io"
api_key = "fo1_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}`, // https://github.com/DopplerHQ/terraform-provider-doppler/blob/a012e1a7903cce391be511b391850b29ebfdeb68/docs/resources/integration_flyio.md?plain=1#L17
`pub const MINIDUMP_SYSMEMINFO1_PERF_CCTOTALDIRTYPAGES_CCDIRTYPAGETHRESHOLD: u32 = 4u32;`, // https://github.com/microsoft/windows-rs/blob/0f7466c34e774e547d21c579b58b60168c4ee6bc/crates/libs/sys/src/Windows/Win32/System/Diagnostics/Debug/mod.rs#L1258
`<input type="hidden" name="authenticity_token" value="7SWa-Fo1_hsC6oovfBsJFLGPUl2EhkSWPbJhWANwgaJWBDl1vxd9VNqXTNAefsJqzIRYaZEfYZLffa31rw8zJA" autocomplete="off" />`,
// fm1
`signature":"I7l2ZXhw9ajjIE2w9tjHNvYjcHg7E2qldMMhoQKjborcWIj8c40rMj83venoy6gXsg6V6B7dlBWxUmzYJR3lJKGECtCSM5BqBvWhL6wX2CN2lZlvwNCyPjG4PCt5MAK1yV1Xv4fqfz8EfT_U49vOzfM1a_nfhXOzrvdg9XgLkAotWBI31vPKjMBrvPqiLcZ12MDNTSK7ubRpVaehSNxiGYHpLhWTkun9qm_APYYXJBjhJYkej50Qcp7Ou8fs3kH02prYIJt4JbWelr5vUDkgMH3AwEx1eYu5NI_8sESlqosl1nhSDx7zq3X1FV1iJlAYCNwGWzW1tjo8PCaJrIHVZZnhBPMN-6ahmOpKb8GViqd4fCQuNe4VUSOeJg8i97kMuk-4r7hwIubR0XfCGzxr7uGDQBdFANi3c4dLlzBAJNifa6b_hT4Xzqja6RCFSv6Cnalyx3hbSkjbyThnXFavJIiR7cvgTcdECg9VxkaxqqRhfAkLAS3hpXQAIYL_bw61M3LN37WHwdgxN_6yZhbSbOsYPmTxiWvdlDaCP_iaCgXgJNfdQ6kep_I89slynE9gdDZ6NSjFJH2Soml4pR6HnQKPjA3OpoTwPSmZjxXY5I78xvrRqRkjdnVzeufqG8LyA-sAEtC0G_312JOxV4GZINquPGk1qFx8WN59Rxw28Tg",`,
// fm2
`<p><span class="emoji">🗣️</span> Adobe illustrator软件基础精讲课程<br><br><span class="emoji">🏷️</span> <a href="https://t.me/abskoop/8565?q=%23%E8%AE%BE%E8%AE%A1%E5%B8%88">#设计师</a> <a href="https://t.me/abskoop/8565?q=%23%E8%B5%84%E6%BA%90">#资源</a> <a href="https://t.me/abskoop/8565?q=%23%E5%A4%B8%E5%85%8B%E7%BD%91%E7%9B%98">#夸克网盘</a><br><br><span class="emoji">👉</span> <a href="https://www.ahhhhfs.com/62409/" target="_blank" rel="noopener">https://www.ahhhhfs.com/62409/</a></p><img src="https://cdn5.cdn-telegram.org/file/uGoDMy0VXMbL1nki9OT0VbJYtfURvDNLurptsQVuhuzF45tNfm2_z5wgR7CnL7lTZ4bbotjXZtiLWvolNQqWBRFWkcidtzSyhWvta9yPB3E2uyvfJvGpditkaLVIiCCXt9BhFBEdgkXa8ODaM7geHK3pW0tmO_IViHBnG8VZqVfDpaQW0W9IRAUwGv2mPZWVRysPJyDSIuY9b-_3ElUml-Xlpm1r8EDcm9Q2WCTCOYur7Gmef4imQ5D-DLTviqmoONgQDLA10WVS3CApXBK4ADSjoIUeMck62owtjElSXnEYMaSGI_OE3B21QplsspPbPlXVUBScLfLOFb9tn-34tw.jpg" width="800" height="533" referrerpolicy="no-referrer">`,
}
return utils.Validate(r, tps, fps)
}
+12 -4
View File
@@ -30,8 +30,8 @@ func GCPAPIKey() *config.Rule {
r := config.Rule{
RuleID: "gcp-api-key",
Description: "Uncovered a GCP API key, which could lead to unauthorized access to Google Cloud services and data breaches.",
Regex: utils.GenerateUniqueTokenRegex(`AIza[0-9A-Za-z\\-_]{35}`, true),
Regex: utils.GenerateUniqueTokenRegex(`AIza[\w-]{35}`, false),
Entropy: 3.0,
Keywords: []string{
"AIza",
},
@@ -39,7 +39,15 @@ func GCPAPIKey() *config.Rule {
// validate
tps := []string{
utils.GenerateSampleSecret("gcp", secrets.NewSecret(`AIza[0-9A-Za-z\\-_]{35}`)),
utils.GenerateSampleSecret("gcp", secrets.NewSecret(`AIza[\w-]{35}`)),
// non-word character at end
`AIzaSyNHxIf32IQ1a1yjl3ZJIqKZqzLAK1XhDk-`, // gitleaks:allow
}
return utils.Validate(r, tps, nil)
fps := []string{
`GWw4hjABFzZCGiRpmlDyDdo87Jn9BN9THUA47muVRNunLxsa82tMAdvmrhOqNkRKiYMEAFbTJAIzaTesb6Tscfcni8vIpWZqNCXFDFslJtVSvFDq`, // text boundary start
`AIzaTesb6Tscfcni8vIpWZqNCXFDFslJtVSvFDqabcd123`, // text boundary end
`apiKey: "AIzaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"`, // not enough entropy
`AIZASYCO2CXRMC9ELSKLHLHRMBSWDEVEDZTLO2O`, // incorrect case
}
return utils.Validate(r, tps, fps)
}
+4 -2
View File
@@ -33,8 +33,10 @@ func GenericCredential() *config.Rule {
"access",
},
Entropy: 3.5,
Allowlist: config.Allowlist{
StopWords: DefaultStopWords,
Allowlists: []config.Allowlist{
{
StopWords: DefaultStopWords,
},
},
}
+27 -6
View File
@@ -14,6 +14,7 @@ func GitHubPat() *config.Rule {
Description: "Uncovered a GitHub Personal Access Token, potentially leading to unauthorized repository access and sensitive content exposure.",
RuleID: "github-pat",
Regex: regexp.MustCompile(`ghp_[0-9a-zA-Z]{36}`),
Entropy: 3,
Keywords: []string{"ghp_"},
}
@@ -21,7 +22,10 @@ func GitHubPat() *config.Rule {
tps := []string{
utils.GenerateSampleSecret("github", "ghp_"+secrets.NewSecret(utils.AlphaNumeric("36"))),
}
return utils.Validate(r, tps, nil)
fps := []string{
"ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
}
return utils.Validate(r, tps, fps)
}
func GitHubFineGrainedPat() *config.Rule {
@@ -29,7 +33,8 @@ func GitHubFineGrainedPat() *config.Rule {
r := config.Rule{
Description: "Found a GitHub Fine-Grained Personal Access Token, risking unauthorized repository access and code manipulation.",
RuleID: "github-fine-grained-pat",
Regex: regexp.MustCompile(`github_pat_[0-9a-zA-Z_]{82}`),
Regex: regexp.MustCompile(`github_pat_\w{82}`),
Entropy: 3,
Keywords: []string{"github_pat_"},
}
@@ -37,7 +42,10 @@ func GitHubFineGrainedPat() *config.Rule {
tps := []string{
utils.GenerateSampleSecret("github", "github_pat_"+secrets.NewSecret(utils.AlphaNumeric("82"))),
}
return utils.Validate(r, tps, nil)
fps := []string{
"github_pat_xxxxxxxxxxxxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
}
return utils.Validate(r, tps, fps)
}
func GitHubOauth() *config.Rule {
@@ -46,6 +54,7 @@ func GitHubOauth() *config.Rule {
Description: "Discovered a GitHub OAuth Access Token, posing a risk of compromised GitHub account integrations and data leaks.",
RuleID: "github-oauth",
Regex: regexp.MustCompile(`gho_[0-9a-zA-Z]{36}`),
Entropy: 3,
Keywords: []string{"gho_"},
}
@@ -53,7 +62,10 @@ func GitHubOauth() *config.Rule {
tps := []string{
utils.GenerateSampleSecret("github", "gho_"+secrets.NewSecret(utils.AlphaNumeric("36"))),
}
return utils.Validate(r, tps, nil)
fps := []string{
"gho_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
}
return utils.Validate(r, tps, fps)
}
func GitHubApp() *config.Rule {
@@ -62,6 +74,7 @@ func GitHubApp() *config.Rule {
Description: "Identified a GitHub App Token, which may compromise GitHub application integrations and source code security.",
RuleID: "github-app-token",
Regex: regexp.MustCompile(`(?:ghu|ghs)_[0-9a-zA-Z]{36}`),
Entropy: 3,
Keywords: []string{"ghu_", "ghs_"},
}
@@ -70,7 +83,11 @@ func GitHubApp() *config.Rule {
utils.GenerateSampleSecret("github", "ghu_"+secrets.NewSecret(utils.AlphaNumeric("36"))),
utils.GenerateSampleSecret("github", "ghs_"+secrets.NewSecret(utils.AlphaNumeric("36"))),
}
return utils.Validate(r, tps, nil)
fps := []string{
"ghu_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"ghs_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
}
return utils.Validate(r, tps, fps)
}
func GitHubRefresh() *config.Rule {
@@ -79,6 +96,7 @@ func GitHubRefresh() *config.Rule {
Description: "Detected a GitHub Refresh Token, which could allow prolonged unauthorized access to GitHub services.",
RuleID: "github-refresh-token",
Regex: regexp.MustCompile(`ghr_[0-9a-zA-Z]{36}`),
Entropy: 3,
Keywords: []string{"ghr_"},
}
@@ -86,5 +104,8 @@ func GitHubRefresh() *config.Rule {
tps := []string{
utils.GenerateSampleSecret("github", "ghr_"+secrets.NewSecret(utils.AlphaNumeric("36"))),
}
return utils.Validate(r, tps, nil)
fps := []string{
"ghr_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
}
return utils.Validate(r, tps, fps)
}
@@ -4,6 +4,7 @@ import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
"regexp"
)
func VaultServiceToken() *config.Rule {
@@ -14,6 +15,14 @@ func VaultServiceToken() *config.Rule {
Regex: utils.GenerateUniqueTokenRegex(`(?:hvs\.[\w-]{90,120}|s\.(?i:[a-z0-9]{24}))`, false),
Entropy: 3.5,
Keywords: []string{"hvs", "s."},
Allowlists: []config.Allowlist{
{
Regexes: []*regexp.Regexp{
// https://github.com/gitleaks/gitleaks/issues/1490#issuecomment-2334166357
regexp.MustCompile(`s\.[A-Za-z]{24}`),
},
},
},
}
// validate
@@ -29,7 +38,11 @@ func VaultServiceToken() *config.Rule {
// Old
` credentials: new AWS.SharedIniFileCredentials({ profile: '<YOUR_PROFILE>' })`, // word boundary start
`INFO 4 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean`, // word boundary end
`s.xxxxxxxxxxxxxxxxxxxxxxxx`, // low entropy
`s.xxxxxxxxxxxxxxxxxxxxxxxx`, // low entropy
`s.THISSTRINGISALLUPPERCASE`, // uppercase
`s.thisstringisalllowercase`, // lowercase
`s.AcceptanceTimeoutSeconds `, // pascal-case
`s.makeKubeConfigController = args`, // camel-case
// New
`hvs.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`, // low entropy
}
+389 -43
View File
@@ -1,69 +1,415 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"fmt"
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/config"
)
// The kubernetes rules are split into two functions to make the complex proximity matching of the data-key and the kind-identifier more readable and testable
// KubernetesSecret validates if we detected a kubernetes secret which contains data!
func KubernetesSecret() *config.Rule {
// Only match basic variations of `kind: secret`, we don't want things like `kind: ExternalSecret`.
//language=regexp
kindPat := `\bkind:[ \t]*["']?secret["']?`
// Only matches values (`key: value`) under `data:` that are:
// - valid base64 characters
// - longer than 10 characters (no "YmFyCg==")
//language=regexp
dataPat := `\bdata:(?:.|\s){0,100}?\s+([\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:["']?[a-z0-9]{10,}={0,3}["']?|\{\{[ \t\w"|$:=,.-]+}}|""|''))`
// KubernetesSecretWithDataBefore validates if we detected a kubernetes secret which contains data, before the resource identifier!
func KubernetesSecretWithDataBefore() *config.Rule {
// define rule
r := config.Rule{
RuleID: "kubernetes-secret-with-data-before",
RuleID: "kubernetes-secret-yaml",
Description: "Possible Kubernetes Secret detected, posing a risk of leaking credentials/tokens from your deployments",
// We try to match secrets by looking if we have the keyword
Regex: utils.GenerateUniqueTokenRegex(`(?i)(?:\b(?:data:))(\W+(?:\w+\W+){0,200}?)\bkind:.{0,10}Secret\b`, true),
Regex: regexp.MustCompile(fmt.Sprintf(
//language=regexp
`(?i)(?:%s(?:.|\s){0,200}?%s|%s(?:.|\s){0,200}?%s)`, kindPat, dataPat, dataPat, kindPat)),
Keywords: []string{
"Secret",
"secret",
},
// Kubernetes secrets are always yaml files, we limit to common yaml-endings to make this rule more safe!
// Kubernetes secrets are usually yaml files.
Path: regexp.MustCompile(`(?i)\.ya?ml$`),
Allowlists: []config.Allowlist{
{
Regexes: []*regexp.Regexp{
// Ignore empty or placeholder values.
// variable: {{ .Values.Example }} (https://helm.sh/docs/chart_template_guide/variables/)
// variable: ""
// variable: ''
regexp.MustCompile(`[\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:\{\{[ \t\w"|$:=,.-]+}}|""|'')`),
},
},
},
}
// validate
tps := map[string]string{
"comment.yaml": `
apiVersion: v1
kind: Secret
metadata:
name: heketi-secret
namespace: default
data:
# base64 encoded password. E.g.: echo -n "mypassword" | base64
key: bXlwYXNzd29yZA==`,
// The "data"-key is before the identifier "kind: Secret"
"before-kubernetes.yaml": `apiVersion: v1
data:
extra: YWRtaW46cGFzc3dvcmQ=
kind: secret
metadata:
name: secret-sa-sample
annotations:
kubernetes.io/service-account.name: 'sa-name'`,
"before-kubernetes.yml": `apiVersion: v1
data:
password: UyFCXCpkJHpEc2I9
username: YWRtaW4=
kind: Secret
metadata:
creationTimestamp: '2022-06-28T17:44:13Z'
name: db-user-pass
namespace: default
type: Opaque`,
"before-comment.yml": `apiVersion: v1
data:
# the data is abbreviated in this example
password: UyFCXCpkJHpEc2I9
username: YWRtaW4=
kind: Secret
metadata:
creationTimestamp: '2022-06-28T17:44:13Z'
name: db-user-pass
namespace: default
type: Opaque`,
"before-quoted-1.yaml": `apiVersion: 'v1'
data:
extra: 'YWRtaW46cGFzc3dvcmQ='
kind: 'Secret'
metadata:
name: 'secret-sa-sample'
annotations:
kubernetes.io/service-account.name: 'sa-name'`,
"before-quoted-2.yaml": `apiVersion: "v1"
data:
extra: "YWRtaW46cGFzc3dvcmQ="
kind: "secret"
metadata:
name: "secret-sa-sample"
annotations:
kubernetes.io/service-account.name: "sa-name"`,
"before-multiline-literal.yaml": `apiVersion: v1
data:
.dockercfg: |
eyJhdXRocyI6eyJodHRwczovL2V4YW1wbGUvdjEvIjp7ImF1dGgiOiJvcGVuc2VzYW1lIn19fQo=
metadata:
name: secret-dockercfg
type: kubernetes.io/dockercfg
kind: Secret
`,
"before-multiline-folded.yaml": `apiVersion: v1
data:
.dockercfg: >
eyJhdXRocyI6eyJodHRwczovL2V4YW1wbGUvdjEvIjp7ImF1dGgiOiJvcGVuc2VzYW1lIn19fQo=
metadata:
name: secret-dockercfg
type: kubernetes.io/dockercfg
kind: Secret`,
// Sample Kubernetes Secret from https://kubernetes.io/docs/concepts/configuration/secret/
// These secrets contain the "data"-key before the actual identifier "kind: Secret"
"kubernetes.yaml": "apiVersion: v1'\n' data:'\n' extra: YmFyCg=='\n' kind: secret'\n' metadata:'\n' name: secret-sa-sample'\n' annotations:'\n' kubernetes.io/service-account.name: 'sa-name'", // gitleaks:allow
"kubernetes.yml": "apiVersion: v1'\n' data:'\n' password: UyFCXCpkJHpEc2I9'\n' username: YWRtaW4='\n' kind: Secret'\n' metadata:'\n' creationTimestamp: '2022-06-28T17:44:13Z''\n' name: db-user-pass'\n' namespace: default'\n' type: Opaque", // gitleaks:allow
// Quoted Test Cases
"kubernetes-quoted-1.yaml": "apiVersion: v1'\n' data:'\n' extra: YmFyCg=='\n' kind: 'Secret''\n' metadata:'\n' name: 'secret-sa-sample''\n' annotations:'\n' kubernetes.io/service-account.name: 'sa-name'", // gitleaks:allow
"kubernetes-quoted-2.yaml": "apiVersion: v1'\n' data:'\n' extra: YmFyCg=='\n' kind: 'secret''\n' metadata:'\n' name: 'secret-sa-sample''\n' annotations:'\n' kubernetes.io/service-account.name: 'sa-name'", // gitleaks:allow
// The "data"-key is after the identifier "kind: Secret"
"after-kubernetes.yaml": `apiVersion: v1
kind: secret
data:
extra: YWRtaW46cGFzc3dvcmQ=
metadata:
name: secret-sa-sample
annotations:
kubernetes.io/service-account.name: 'sa-name'`,
"after-kubernetes.yml": `apiVersion: v1
kind: Secret
metadata:
name: ca-secret
type: Opaque
data:
ca.pem: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUR4RENDQXF5Z0F3SUJBZ0lVV3pqUDl5RUk0eHlRSnBzVHVERU4yV2ROaUFzd0RRWUpLb1pJaHZjTkFRRUwKQlFBd2FERUxNQWtHQTFVRUJoTUNWVk14RHpBTkJnTlZCQWdUQms5eVpXZHZiakVSTUE4R0ExVUVCeE1JVUc5eQpkR3hoYm1ReEV6QVJCZ05WQkFvVENrdDFZbVZ5Ym1WMFpYTXhDekFKQmdOVkJBc1RBa05CTVJNd0VRWURWUVFECkV3cExkV0psY201bGRHVnpNQjRYRFRFMk1EZ3hNVEUyTkRnd01Gb1hEVEl4TURneE1ERTJORGd3TUZvd2FERUwKTUFrR0ExVUVCaE1DVlZNeER6QU5CZ05WQkFnVEJrOXlaV2R2YmpFUk1BOEdBMVVFQnhNSVVHOXlkR3hoYm1ReApFekFSQmdOVkJBb1RDa3QxWW1WeWJtVjBaWE14Q3pBSkJnTlZCQXNUQWtOQk1STXdFUVlEVlFRREV3cExkV0psCmNtNWxkR1Z6TUlJQklqQU5CZ2txaGtpRzl3MEJBUUVGQUFPQ0FROEFNSUlCQ2dLQ0FRRUF3QkhNOGN6anc0Q1cKK05wbklhV012RzZlcVhtelNZT20vbHdaNUhOMnVLck9xaTNHYUUyTjFKd2tzcGRmMXNOUGFZMHdPR2xkbURIZgoxSnlyTW8rUFdLVUVjWko1WGE4Vm02d2I0MlpjczN3MEp5dlEzWFJjaDQyMFJRWGRKayszcmMybWRvSVRkL0lmCnZjWms0N0RzQTMrQU5QSUlSTzdWRmZpS1JNRFpTUDR1OThnVjI2eW1zbjc0TzFVKzNVUHR1TEFTVTFLck9FTk4KR01FWG0ydTJpdmVvbTJrbjFlZTZuM1hCR1o2bU52cUNPdWUxRXdza0gvWkhoUVh1UDgyV1U5dVk0aGVORnoyQwpBNmR0Q0Q0c3Z6eHc3ZFQ2cVhsV0ZIWUYrc3VLVDhXNkczd3NkOWxzV0ZVY0ZWL0lwaTVobEVaTWprNFNoY3RqCjdpYnlrRURKM1FJREFRQUJvMll3WkRBT0JnTlZIUThCQWY4RUJBTUNBUVl3RWdZRFZSMFRBUUgvQkFnd0JnRUIKL3dJQkFqQWRCZ05WSFE0RUZnUVVOdnhRZ3o5ZTNXS2VscU1KTmZXNE1KUHYzc0V3SHdZRFZSMGpCQmd3Rm9BVQpOdnhRZ3o5ZTNXS2VscU1KTmZXNE1KUHYzc0V3RFFZSktvWklodmNOQVFFTEJRQURnZ0VCQUp1TUhYUms1TEVyCmxET1p4Mm9aRUNQZ29reXMzSGJsM05oempXd2pncXdxNVN6a011V3QrUnVkdnRTK0FUQjFtTjRjYTN0eSt2bWcKT09heTkvaDZoditmSE5jZHpYdWR5dFZYZW1KN3F4ZFoxd25DUUcwdnpqOWRZY0xFSGpJWi94dU1jNlY3dnJ4YwpSc0preGp5aE01UXBmRHd0eVZKeGpkUmVBZ0huSyswTkNieHdtQ3cyRGIvOXpudm9LWGk4TEQwbkQzOFQxY3R3CmhmdGxwTmRoZXFNRlpEZXBuTUYwY2g2cHo5TFV5Mkh1cnhrV2dkWVNjY2VNU0hPTzBMcG4xeVVBMWczOTJhUjUKWk81Zm5KMW95Vm1LVWFCeDJCMndsSVlUSXlES1ZiMnY1UXNHbnYvRHVTMDZhcmVLTmsvTGpHRTRlMXlHOHJkcwpacnZHMzNvUmtEbz0KLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=
`,
"after-comment.yml": `apiVersion: v1
kind: Secret
metadata:
creationTimestamp: '2022-06-28T17:44:13Z'
name: db-user-pass
namespace: default
type: Opaque
data:
# the data is abbreviated in this example
password: UyFCXCpkJHpEc2I9
username: YWRtaW4=
`,
"after-quoted-1.yaml": `apiVersion: 'v1'
kind: 'Secret'
data:
password: 'UyFCXCpkJHpEc2I9'
username: 'YWRtaW4='
metadata:
name: 'db-user-pass'
namespace: 'default'
type: 'Opaque'`,
"after-quoted-2.yaml": `apiVersion: "v1"
kind: "Secret"
data:
password: "UyFCXCpkJHpEc2I9"
username: "YWRtaW4="
metadata:
name: "db-user-pass"
namespace: "default"
type: "Opaque"`,
"after-multiline-literal.yaml": `apiVersion: v1
kind: Secret
metadata:
name: secret-dockercfg
type: kubernetes.io/dockercfg
data:
.dockercfg: |
eyJhdXRocyI6eyJodHRwczovL2V4YW1wbGUvdjEvIjp7ImF1dGgiOiJvcGVuc2VzYW1lIn19fQo=
`,
"after-multiline-folded.yaml": `apiVersion: v1
kind: Secret
metadata:
name: secret-dockercfg
type: kubernetes.io/dockercfg
data:
.dockercfg: >
eyJhdXRocyI6eyJodHRwczovL2V4YW1wbGUvdjEvIjp7ImF1dGgiOiJvcGVuc2VzYW1lIn19fQo=`,
}
return utils.ValidateWithPaths(r, tps, nil)
}
fps := map[string]string{
"empty-quotes1.yml": `apiVersion: v1
kind: Secret
metadata:
name: registry-auth-data
type: Opaque
data:
htpasswd: ''
`,
"empty-quotes2.yml": `apiVersion: v1
kind: Secret
metadata:
name: registry-auth-data
type: Opaque
data:
htpasswd: ""
`,
"overly-permissive1.yaml": `apiVersion: v1
kind: Secret
metadata:
name: registry-auth-data
type: Opaque
data:
htpasswd: {{ htpasswd }}
---
apiVersion: v1
kind: ReplicationController`,
"overly-permissive2.yaml": `apiVersion: v1
kind: Secret
metadata:
labels:
k8s-app: kubernetes-dashboard
addonmanager.kubernetes.io/mode: EnsureExists
name: kubernetes-dashboard-csrf
namespace: kubernetes-dashboard
type: Opaque
data:
csrf: ""
// KubernetesSecretWithDataAfter validates if we detected a kubernetes secret which contains data, after the resource identifier!
func KubernetesSecretWithDataAfter() *config.Rule {
// define rule
r := config.Rule{
RuleID: "kubernetes-secret-with-data-after",
Description: "Possible Kubernetes Secret detected, posing a risk of leaking credentials/tokens from your deployments",
// We try to match secrets by looking if we have the keyword
Regex: utils.GenerateUniqueTokenRegex(`(?i)(?:\bkind:.{0,10}Secret\b)(?:.|\s){0,200}?\b(?:data:)\s*(.+)`, true),
---
Keywords: []string{
"Secret",
},
// Kubernetes secrets are always yaml files, we limit to common yaml-endings to make this rule more safe!
Path: regexp.MustCompile(`(?i)\.ya?ml$`),
}
apiVersion: v1
kind: Secret
metadata:
labels:
k8s-app: kubernetes-dashboard
addonmanager.kubernetes.io/mode: EnsureExists
name: kubernetes-dashboard-key-holder
namespace: kubernetes-dashboard
type: Opaque
`,
"sopssecret.yaml": `apiVersion: isindir.github.com/v1alpha3
kind: SopsSecret
metadata:
name: app1-sopssecret
namespace: test
spec:
suspend: false
secretTemplates:
- name: ENC[AES256_GCM,data:W3PiZ6lD6bpfAdI=,iv:2qF98ZkchgfWF4tZo8fok6zY0ZLNRV3wFpl8n2iyC7I=,tag:FzoL+CZHkLEqfWKniRApBA==,type:str]
labels:
app: ENC[AES256_GCM,data:t9ujIQ==,iv:slZBpmKF+DOg/wVBWmq5iTqkRBZUMao0a3MdoxzJs3s=,tag:xJyhdJ4rn/cB/4mxHzmGig==,type:str]
stringData:
db-password: ENC[AES256_GCM,data:O+5l4g==,iv:c/dS4BCBMbnKsXYuzBuCuVQt8RV9bOv5HgdpL+iwmns=,tag:KkQfh6OymvCt4uC13p318g==,type:str]
sops:
kms: []
gcp_kms: []
azure_kv: []
hc_vault: []
lastmodified: '2021-10-21T10:56:37Z'
mac: ENC[AES256_GCM,data:Tl1V1PuI5tZ0Hu3qxxzpDNeKQkuW0g/x/Mlp1yM6HaBqDr+r2FukLdYSYqjjJ3A8g+YkpvMib50M7j0V7zoX9sgCvMKEg86pRsWtThv8n/L+bsjClVTqnhJ9nfYlaPOMlvggbiMOE5hXPIuVz8WXYoVYJ2cVNCd/GfwOraUmj7I=,iv:n7HVI13okfbW3FS/ZsJ2GNmibudxc/TlkLa3umQQ+vc=,tag:R4ikep1wlxlDWlODJqFHHw==,type:str]
pgp:
- created_at: '2021-10-21T10:56:37Z'
enc: |
-----BEGIN PGP MESSAGE-----
// validate
tps := map[string]string{
// Sample Kubernetes Secret from https://kubernetes.io/docs/concepts/configuration/secret/
// These secrets contain the data after the actual identifier "kind: Secret"
"kubernetes.yaml": "apiVersion: v1'\n' kind: secret'\n' data:'\n' extra: YmFyCg=='\n' metadata:'\n' name: secret-sa-sample'\n' annotations:'\n' kubernetes.io/service-account.name: 'sa-name'", // gitleaks:allow
"kubernetes.yml": "apiVersion: v1'\n' kind: Secret'\n' data:'\n' password: UyFCXCpkJHpEc2I9'\n' username: YWRtaW4='\n' metadata:'\n' creationTimestamp: '2022-06-28T17:44:13Z''\n' name: db-user-pass'\n' namespace: default'\n' type: Opaque", // gitleaks:allow
// Quoted Test Cases
"kubernetes-quoted-1.yaml": "apiVersion: v1'\n' kind: 'Secret''\n' data:'\n' password: UyFCXCpkJHpEc2I9'\n' username: YWRtaW4='\n' metadata:'\n' name: db-user-pass'\n' namespace: default'\n' type: Opaque", // gitleaks:allow
"kubernetes-quoted-2.yaml": "apiVersion: v1'\n' kind: 'secret''\n' data:'\n' password: UyFCXCpkJHpEc2I9'\n' username: YWRtaW4='\n' metadata:'\n' name: db-user-pass'\n' namespace: default'\n' type: Opaque", // gitleaks:allow
hQGMA3muqimBu2IIAQwAkhR19/6roLq06oaD12vqDMes3/8FweAHxa6TLKg+LRjp
2/ntiRJHPBP9DYYFZbkTo8lAmIdVF7KfGIqWgPm5JiNhqfVRhyGPCRgBE7+I8qH6
EML9Vo/76kJLHtIjs5rOg7OXgwwitaibs1q6uyVY8TuaGXYIOO1iwL9xVtbayIry
NMQd1tFcNb6Vb86Plqm+T1VnSOJMUvryxrLelx89UNM0ctepyVu6YY9jpBjV0QLJ
NqNkKAGIMv3RNa9bZHTwveo9T0oXtFnk5H33BxH0ky/DGpD+5Ch1YgbzbqVnr+Bm
RX0R/GRhS9IDInd+eiyVX6y3LR5di0fc8TuK43+96wTG+2+ck+lbMrkHYsL2UJNv
bAjlOWmIcL4UwGlEOj4EzwcEx+xP3dq57pJ+DasfNwVqps2Kk+ofodR7d6gx7ELH
UQmLypCtkRic9v8fVSA2vEL8hAlg9bT8tpHLhHMOwe228cL5dTzFD60RoP+ovRar
jIU59Pnu1bnM4pXWEVA20l4BzJ8Fd6gj3TfAg/7Mat+dnTaUwnPgRSybFn0ZZHMW
RJDBPkMGFfSGRDfLeD37d61mI31360/w/61LaVp1sdDYodBJCRZFA1YzbqZcxnDl
YRjRmpcVRnO+o72CnU/P
=V4l4
-----END PGP MESSAGE-----
fp: 73019E949C1D3C3D1BE8B718C7CD51A565AB592C
encrypted_suffix: Templates
version: 3.6.1`, // https://github.com/luca-iachini/argocd-test/blob/af0c8eaba270bc918108c8bc3b909f26a4fe995d/kustomize/base/app1/secrets.enc.yaml#L4
// The "data"-key is before the identifier "kind: Secret"
"before-min-length.yaml": `apiVersion: v1
data:
extra: YmFyCg==
kind: secret
metadata:
name: secret-sa-sample
annotations:
kubernetes.io/service-account.name: 'sa-name'`,
"before-template.yaml": `apiVersion: v1
data:
password: {{ .Values.Password }}
kind: secret
metadata:
name: secret-sa-sample
annotations:
kubernetes.io/service-account.name: 'sa-name'`,
"before-externalsecret1.yml": `apiVersion: 'kubernetes-client.io/v1'
metadata:
name: actions-exporter
namespace: github-actions-exporter
spec:
backendType: secretsManager
data:
- key: MySecretManagerKey
name: github_token
property: github_token
kind: ExternalSecret
`,
"before-externalsecret2.yml": `apiVersion: external-secrets.io/v1beta1
spec:
secretStoreRef:
kind: ClusterSecretStore
name: aws-secretsmanager
refreshInterval: 1h
target:
creationPolicy: Owner
data:
- secretKey: api-key
remoteRef:
key: my-secrets-manager-secret
metadata:
name: api-key
namespace: my-namespace
kind: ExternalSecret
`,
"before-sopssecret.yml": `apiVersion: isindir.github.com/v1alpha3
spec:
secretTemplates:
- name: my-secret-name-1
labels:
label1: value1
annotations:
key1: value1
data:
data-name1: ZGF0YS12YWx1ZTE=
data-nameM: ZGF0YS12YWx1ZU0=
kind: SopsSecret
metadata:
name: sopssecret-sample
`, // https://github.com/isindir/sops-secrets-operator/blob/8aaf8bb368dc841a2d57f251bd839f08216a9328/config/samples/isindir_v1alpha3_sopssecret.yaml#L4
// The "data"-key is after the identifier "kind: Secret"
"after-min-length.yaml": `apiVersion: v1
kind: secret
data:
extra: YmFyCg==
metadata:
name: secret-sa-sample
annotations:
kubernetes.io/service-account.name: 'sa-name'`,
"after-externalsecret1.yml": `apiVersion: 'kubernetes-client.io/v1'
kind: ExternalSecret
metadata:
name: actions-exporter
namespace: github-actions-exporter
spec:
backendType: secretsManager
data:
- key: MySecretManagerKey
name: github_token
property: github_token
- key: MySecretManagerKey`,
"after-externalsecret2.yml": `apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
name: api-key
namespace: my-namespace
spec:
secretStoreRef:
kind: ClusterSecretStore
name: aws-secretsmanager
refreshInterval: 1h
target:
creationPolicy: Owner
data:
- secretKey: api-key
remoteRef:
key: my-secrets-manager-secret`,
"after-sopssecret.yml": `apiVersion: isindir.github.com/v1alpha3
kind: SopsSecret
metadata:
name: sopssecret-sample
spec:
secretTemplates:
- name: my-secret-name-0
labels:
label0: value0
labelK: valueK
annotations:
key0: value0
keyN: valueN
stringData:
data-name0: data-value0
data-nameL: data-valueL
- name: my-secret-name-1
labels:
label1: value1
annotations:
key1: value1
data:
data-name1: ZGF0YS12YWx1ZTE=
data-nameM: ZGF0YS12YWx1ZU0=`,
"after-empty-data.yaml": `apiVersion: v1
kind: Secret
metadata:
labels:
k8s-app: kubernetes-dashboard
addonmanager.kubernetes.io/mode: EnsureExists
name: kubernetes-dashboard-csrf
namespace: kubernetes-dashboard
type: Opaque
data:
csrf: ""
`,
}
return utils.ValidateWithPaths(r, tps, nil)
return utils.ValidateWithPaths(r, tps, fps)
}
+50
View File
@@ -0,0 +1,50 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/config"
)
func NugetConfigPassword() *config.Rule {
r := config.Rule{
Description: "Identified a password within a Nuget config file, potentially compromising package management access.",
RuleID: "nuget-config-password",
Regex: regexp.MustCompile(`(?i)<add key=\"(?:(?:ClearText)?Password)\"\s*value=\"(.{8,})\"\s*/>`),
Path: regexp.MustCompile(`(?i)nuget\.config$`),
Keywords: []string{"<add key="},
Entropy: 1,
Allowlists: []config.Allowlist{
{
Regexes: []*regexp.Regexp{
// samples from https://learn.microsoft.com/en-us/nuget/reference/nuget-config-file
regexp.MustCompile(`33f!!lloppa`),
regexp.MustCompile(`hal\+9ooo_da!sY`),
// exclude environment variables
regexp.MustCompile(`^\%\S.*\%$`),
},
},
},
}
tps := map[string]string{
"nuget.config": `<add key="Password" value="CleartextPassword1" />`,
"Nuget.config": `<add key="ClearTextPassword" value="CleartextPassword1" />`,
"Nuget.Config": `<add key="ClearTextPassword" value="TestSourcePassword" />`,
"Nuget.COnfig": `<add key="ClearTextPassword" value="TestSource-Password" />`,
"Nuget.CONfig": `<add key="ClearTextPassword" value="TestSource%Password" />`,
"Nuget.CONFig": `<add key="ClearTextPassword" value="TestSource%Password%" />`,
}
fps := map[string]string{
"some.xml": `<add key="Password" value="CleartextPassword1" />`, // wrong filename
"nuget.config": `<add key="ClearTextPassword" value="XXXXXXXXXXX" />`, // low entropy
"Nuget.config": `<add key="ClearTextPassword" value="abc" />`, // too short
"Nuget.Config": `<add key="ClearTextPassword" value="%TestSourcePassword%" />`, // environment variable
"NUget.Config": `<add key="ClearTextPassword" value="33f!!lloppa" />`, // known sample
"NUGet.Config": `<add key="ClearTextPassword" value="hal+9ooo_da!sY" />`, // known sample
}
return utils.ValidateWithPaths(r, tps, fps)
}
+31
View File
@@ -0,0 +1,31 @@
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 PrivateAIToken() *config.Rule {
// https://docs.private-ai.com/reference/latest/operation/metrics_metrics_get/
r := config.Rule{
RuleID: "privateai-api-token",
Description: "Identified a PrivateAI Token, posing a risk of unauthorized access to AI services and data manipulation.",
Regex: utils.GenerateSemiGenericRegex([]string{"private[_-]?ai"}, `[a-z0-9]{32}`, false),
Entropy: 3,
Keywords: []string{
"privateai",
"private_ai",
"private-ai",
},
}
// validate
tps := []string{
utils.GenerateSampleSecret("privateai", secrets.NewSecret(utils.AlphaNumeric("32"))),
}
fps := []string{
`const privateaiToken = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";`,
}
return utils.Validate(r, tps, fps)
}
+1 -1
View File
@@ -12,7 +12,7 @@ func PrivateKey() *config.Rule {
r := config.Rule{
Description: "Identified a Private Key, which may compromise cryptographic security and sensitive data encryption.",
RuleID: "private-key",
Regex: regexp.MustCompile(`(?i)-----BEGIN[ A-Z0-9_-]{0,100}PRIVATE KEY(?: BLOCK)?-----[\s\S-]*KEY(?: BLOCK)?----`),
Regex: regexp.MustCompile(`(?i)-----BEGIN[ A-Z0-9_-]{0,100}PRIVATE KEY(?: BLOCK)?-----[\s\S-]*?KEY(?: BLOCK)?-----`),
Keywords: []string{"-----BEGIN"},
}
+8 -5
View File
@@ -11,17 +11,20 @@ func SquareAccessToken() *config.Rule {
r := config.Rule{
RuleID: "square-access-token",
Description: "Detected a Square Access Token, risking unauthorized payment processing and financial transaction exposure.",
Regex: utils.GenerateUniqueTokenRegex(`(EAAA|sq0atp-)[0-9A-Za-z\-_]{22,60}`, true),
Regex: utils.GenerateUniqueTokenRegex(`(?:EAAA|sq0atp-)[\w-]{22,60}`, false),
Keywords: []string{"sq0atp-", "EAAA"},
}
// validate
tps := []string{
utils.GenerateSampleSecret("square", secrets.NewSecret(`sq0atp-[0-9A-Za-z\-_]{22}`)),
utils.GenerateSampleSecret("square", secrets.NewSecret(`(?:EAAA|sq0atp-)[\w-]{22,60}`)),
"ARG token=sq0atp-812erere3wewew45678901", // gitleaks:allow
"ARG token=EAAAlsBxkkVgvmr7FasTFbM6VUGZ31EJ4jZKTJZySgElBDJ_wyafHuBFquFexY7E", // gitleaks:allow",
}
return utils.Validate(r, tps, nil)
fps := []string{
`aws-cli@sha256:eaaa7b11777babe28e6133a8b19ff71cea687e0d7f05158dee95a71f76ce3d00`,
}
return utils.Validate(r, tps, fps)
}
func SquareSecret() *config.Rule {
@@ -29,13 +32,13 @@ func SquareSecret() *config.Rule {
r := config.Rule{
RuleID: "square-secret",
Description: "Square Secret",
Regex: utils.GenerateUniqueTokenRegex(`sq0csp-[0-9A-Za-z\\-_]{43}`, true),
Regex: utils.GenerateUniqueTokenRegex(`sq0csp-[\w-]{43}`, false),
Keywords: []string{"sq0csp-"},
}
// validate
tps := []string{
utils.GenerateSampleSecret("square", secrets.NewSecret(`sq0csp-[0-9A-Za-z\\-_]{43}`)),
utils.GenerateSampleSecret("square", secrets.NewSecret(`sq0csp-[\w-]{43}`)),
`value: "sq0csp-0p9h7g6f4s3s3s3-4a3ardgwa6ADRDJDDKUFYDYDYDY"`, // gitleaks:allow
}
return utils.Validate(r, tps, nil)
+7 -4
View File
@@ -21,10 +21,13 @@ func SumoLogicAccessID() *config.Rule {
Keywords: []string{
"sumo",
},
Allowlist: config.Allowlist{
RegexTarget: "line",
Regexes: []*regexp.Regexp{
regexp.MustCompile(`sumOf`),
Allowlists: []config.Allowlist{
{
RegexTarget: "line",
Regexes: []*regexp.Regexp{regexp.MustCompile(`sumOf`)},
},
{
Paths: []*regexp.Regexp{regexp.MustCompile(`tests/.+$`)},
},
},
}
+34 -29
View File
@@ -6,25 +6,15 @@ package utils
import (
"github.com/rs/zerolog/log"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/base"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/detect"
"strings"
)
func Validate(r config.Rule, truePositives []string, falsePositives []string) *config.Rule {
// normalize keywords like in the config package
var keywords []string
for _, k := range r.Keywords {
keywords = append(keywords, strings.ToLower(k))
}
r.Keywords = keywords
rules := make(map[string]config.Rule)
rules[r.RuleID] = r
d := detect.NewDetector(config.Config{
Rules: rules,
Keywords: keywords,
})
func Validate(rule config.Rule, truePositives []string, falsePositives []string) *config.Rule {
r := &rule
d := createSingleRuleDetector(r)
for _, tp := range truePositives {
if len(d.DetectString(tp)) != 1 {
log.Fatal().
@@ -43,22 +33,12 @@ func Validate(r config.Rule, truePositives []string, falsePositives []string) *c
Msg("Failed to Validate. False positive was detected by regex.")
}
}
return &r
return r
}
func ValidateWithPaths(r config.Rule, truePositives map[string]string, falsePositives map[string]string) *config.Rule {
var keywords []string
for _, k := range r.Keywords {
keywords = append(keywords, strings.ToLower(k))
}
r.Keywords = keywords
rules := make(map[string]config.Rule)
rules[r.RuleID] = r
d := detect.NewDetector(config.Config{
Rules: rules,
Keywords: keywords,
})
func ValidateWithPaths(rule config.Rule, truePositives map[string]string, falsePositives map[string]string) *config.Rule {
r := &rule
d := createSingleRuleDetector(r)
for path, tp := range truePositives {
f := detect.Fragment{Raw: tp, FilePath: path}
if len(d.Detect(f)) != 1 {
@@ -81,5 +61,30 @@ func ValidateWithPaths(r config.Rule, truePositives map[string]string, falsePosi
Msg("Failed to Validate. False positive was detected by regex and/or path.")
}
}
return &r
return r
}
func createSingleRuleDetector(r *config.Rule) *detect.Detector {
// normalize keywords like in the config package
var (
uniqueKeywords = make(map[string]struct{})
keywords []string
)
for _, keyword := range r.Keywords {
k := strings.ToLower(keyword)
if _, ok := uniqueKeywords[k]; ok {
continue
}
keywords = append(keywords, k)
uniqueKeywords[k] = struct{}{}
}
r.Keywords = keywords
rules := map[string]config.Rule{
r.RuleID: *r,
}
cfg := base.CreateGlobalConfig()
cfg.Rules = rules
cfg.Keywords = uniqueKeywords
return detect.NewDetector(cfg)
}
+29 -10
View File
@@ -31,13 +31,13 @@ func runGit(cmd *cobra.Command, args []string) {
)
// grab source
source := "."
if len(args) == 1 {
source = args[0]
if source == "" {
source = "."
source := "."
if len(args) == 1 {
source = args[0]
if source == "" {
source = "."
}
}
}
initConfig(source)
@@ -57,17 +57,36 @@ func runGit(cmd *cobra.Command, args []string) {
}
var (
gitCmd *sources.GitCmd
logOpts string
gitCmd *sources.GitCmd
logOpts string
preCommit bool
staged bool
)
logOpts, err = cmd.Flags().GetString("log-opts")
if err != nil {
log.Fatal().Err(err).Msg("could not call GetString() for log-opts")
}
gitCmd, err = sources.NewGitLogCmd(source, logOpts)
staged, err = cmd.Flags().GetBool("staged")
if err != nil {
log.Fatal().Err(err).Msg("could not create Git cmd")
log.Fatal().Err(err).Msg("could not call GetBool() for staged")
}
preCommit, err = cmd.Flags().GetBool("pre-commit")
if err != nil {
log.Fatal().Err(err).Msg("could not call GetBool() for pre-commit")
}
if preCommit || staged {
gitCmd, err = sources.NewGitDiffCmd(source, staged)
if err != nil {
log.Fatal().Err(err).Msg("could not create Git diff cmd")
}
} else {
gitCmd, err = sources.NewGitLogCmd(source, logOpts)
if err != nil {
log.Fatal().Err(err).Msg("could not create Git log cmd")
}
}
findings, err = detector.DetectGit(gitCmd)
if err != nil {
// don't exit on error, just log it
+6
View File
@@ -56,6 +56,7 @@ func init() {
rootCmd.PersistentFlags().Bool("no-banner", false, "suppress banner")
rootCmd.PersistentFlags().StringSlice("enable-rule", []string{}, "only enable specific rules by id")
rootCmd.PersistentFlags().StringP("gitleaks-ignore-path", "i", ".", "path to .gitleaksignore file or folder containing one")
rootCmd.PersistentFlags().Int("max-decode-depth", 0, "allow recursive decoding up to this depth (default \"0\", no decoding is done)")
err := viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config"))
if err != nil {
log.Fatal().Msgf("err binding config %s", err.Error())
@@ -170,6 +171,11 @@ func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Dete
// Setup common detector
detector := detect.NewDetector(cfg)
if detector.MaxDecodeDepth, err = cmd.Flags().GetInt("max-decode-depth"); err != nil {
log.Fatal().Err(err).Msg("")
}
// set color flag at first
if detector.NoColor, err = cmd.Flags().GetBool("no-color"); err != nil {
log.Fatal().Err(err).Msg("")
+31 -8
View File
@@ -1,16 +1,33 @@
package config
import (
"fmt"
"regexp"
"strings"
)
type AllowlistMatchCondition string
const (
AllowlistMatchOr AllowlistMatchCondition = "OR"
AllowlistMatchAnd = "AND"
)
// Allowlist allows a rule to be ignored for specific
// regexes, paths, and/or commits
type Allowlist struct {
// Short human readable description of the allowlist.
Description string
// MatchCondition determines whether all criteria must match.
MatchCondition AllowlistMatchCondition
// Commits is a slice of commit SHAs that are allowed to be ignored. Defaults to "OR".
Commits []string
// Paths is a slice of path regular expressions that are allowed to be ignored.
Paths []*regexp.Regexp
// Regexes is slice of content regular expressions that are allowed to be ignored.
Regexes []*regexp.Regexp
@@ -23,12 +40,6 @@ type Allowlist struct {
// If RegexTarget is empty, it will be tested against the found secret.
RegexTarget string
// Paths is a slice of path regular expressions that are allowed to be ignored.
Paths []*regexp.Regexp
// Commits is a slice of commit SHAs that are allowed to be ignored.
Commits []string
// StopWords is a slice of stop words that are allowed to be ignored.
// This targets the _secret_, not the content of the regex match like the
// Regexes slice.
@@ -54,8 +65,8 @@ func (a *Allowlist) PathAllowed(path string) bool {
}
// RegexAllowed returns true if the regex is allowed to be ignored.
func (a *Allowlist) RegexAllowed(s string) bool {
return anyRegexMatch(s, a.Regexes)
func (a *Allowlist) RegexAllowed(secret string) bool {
return anyRegexMatch(secret, a.Regexes)
}
func (a *Allowlist) ContainsStopWord(s string) bool {
@@ -67,3 +78,15 @@ func (a *Allowlist) ContainsStopWord(s string) bool {
}
return false
}
func (a *Allowlist) Validate() error {
// Disallow empty allowlists.
if len(a.Commits) == 0 &&
len(a.Paths) == 0 &&
len(a.Regexes) == 0 &&
len(a.StopWords) == 0 {
return fmt.Errorf("[[rules.allowlists]] must contain at least one check for: commits, paths, regexes, or stopwords")
}
return nil
}
+144 -65
View File
@@ -2,6 +2,7 @@ package config
import (
_ "embed"
"fmt"
"regexp"
"sort"
"strings"
@@ -28,38 +29,45 @@ type ViperConfig struct {
Rules []struct {
ID string
Description string
Entropy float64
SecretGroup int
Regex string
SecretGroup int
Entropy float64
Keywords []string
Path string
Tags []string
Allowlist struct {
RegexTarget string
Regexes []string
Paths []string
Commits []string
StopWords []string
}
// Deprecated: this is a shim for backwards-compatibility. It should be removed in 9.x.
AllowList *viperRuleAllowlist
Allowlists []viperRuleAllowlist
}
Allowlist struct {
Commits []string
Paths []string
RegexTarget string
Regexes []string
Paths []string
Commits []string
StopWords []string
}
}
type viperRuleAllowlist struct {
Description string
Condition string
Commits []string
Paths []string
RegexTarget string
Regexes []string
StopWords []string
}
// Config is a configuration struct that contains rules and an allowlist if present.
type Config struct {
Title string
Extend Extend
Path string
Description string
Rules map[string]Rule
Allowlist Allowlist
Keywords []string
Keywords map[string]struct{}
// used to keep sarif results consistent
OrderedRules []string
@@ -75,68 +83,98 @@ type Extend struct {
func (vc *ViperConfig) Translate() (Config, error) {
var (
keywords []string
keywords = make(map[string]struct{})
orderedRules []string
rulesMap = make(map[string]Rule)
)
rulesMap := make(map[string]Rule)
for _, r := range vc.Rules {
var allowlistRegexes []*regexp.Regexp
for _, a := range r.Allowlist.Regexes {
allowlistRegexes = append(allowlistRegexes, regexp.MustCompile(a))
}
var allowlistPaths []*regexp.Regexp
for _, a := range r.Allowlist.Paths {
allowlistPaths = append(allowlistPaths, regexp.MustCompile(a))
}
if r.Keywords == nil {
r.Keywords = []string{}
// Validate individual rules.
for _, vr := range vc.Rules {
if vr.Keywords == nil {
vr.Keywords = []string{}
} else {
for _, k := range r.Keywords {
keywords = append(keywords, strings.ToLower(k))
for _, k := range vr.Keywords {
keywords[strings.ToLower(k)] = struct{}{}
}
}
if r.Tags == nil {
r.Tags = []string{}
if vr.Tags == nil {
vr.Tags = []string{}
}
var configRegex *regexp.Regexp
var configPathRegex *regexp.Regexp
if r.Regex == "" {
configRegex = nil
} else {
configRegex = regexp.MustCompile(r.Regex)
if vr.Regex != "" {
configRegex = regexp.MustCompile(vr.Regex)
}
if r.Path == "" {
configPathRegex = nil
} else {
configPathRegex = regexp.MustCompile(r.Path)
}
r := Rule{
RuleID: r.ID,
Description: r.Description,
Regex: configRegex,
Path: configPathRegex,
SecretGroup: r.SecretGroup,
Entropy: r.Entropy,
Tags: r.Tags,
Keywords: r.Keywords,
Allowlist: Allowlist{
RegexTarget: r.Allowlist.RegexTarget,
Regexes: allowlistRegexes,
Paths: allowlistPaths,
Commits: r.Allowlist.Commits,
StopWords: r.Allowlist.StopWords,
},
}
if err := r.Validate(); err != nil {
return Config{}, err
if vr.Path != "" {
configPathRegex = regexp.MustCompile(vr.Path)
}
orderedRules = append(orderedRules, r.RuleID)
rulesMap[r.RuleID] = r
rule := Rule{
RuleID: vr.ID,
Description: vr.Description,
Regex: configRegex,
SecretGroup: vr.SecretGroup,
Entropy: vr.Entropy,
Path: configPathRegex,
Keywords: vr.Keywords,
Tags: vr.Tags,
}
// Parse the allowlist, including the older format for backwards compatibility.
if vr.AllowList != nil {
if len(vr.Allowlists) > 0 {
return Config{}, fmt.Errorf("%s: [rules.allowlist] is deprecated, it cannot be used alongside [[rules.allowlist]]", rule.RuleID)
}
vr.Allowlists = append(vr.Allowlists, *vr.AllowList)
}
for _, a := range vr.Allowlists {
var condition AllowlistMatchCondition
c := strings.ToUpper(a.Condition)
switch c {
case "AND", "&&":
condition = AllowlistMatchAnd
case "", "OR", "||":
condition = AllowlistMatchOr
default:
return Config{}, fmt.Errorf("%s: unknown allowlist condition '%s' (expected 'and', 'or')", rule.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')", rule.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", rule.RuleID, err)
}
rule.Allowlists = append(rule.Allowlists, allowlist)
}
orderedRules = append(orderedRules, rule.RuleID)
rulesMap[rule.RuleID] = rule
}
var allowlistRegexes []*regexp.Regexp
for _, a := range vc.Allowlist.Regexes {
@@ -171,7 +209,15 @@ func (vc *ViperConfig) Translate() (Config, error) {
} else if c.Extend.Path != "" {
c.extendPath()
}
}
// Validate the rules after everything has been assembled (including extended configs).
if extendDepth == 0 {
for _, rule := range rulesMap {
if err := rule.Validate(); err != nil {
return Config{}, err
}
}
}
return c, nil
@@ -235,12 +281,45 @@ func (c *Config) extendURL() {
}
func (c *Config) extend(extensionConfig Config) {
for ruleID, rule := range extensionConfig.Rules {
if _, ok := c.Rules[ruleID]; !ok {
log.Trace().Msgf("adding %s to base config", ruleID)
c.Rules[ruleID] = rule
c.Keywords = append(c.Keywords, rule.Keywords...)
for ruleID, baseRule := range extensionConfig.Rules {
currentRule, ok := c.Rules[ruleID]
if !ok {
// Rule doesn't exist, add it to the config.
c.Rules[ruleID] = baseRule
for _, k := range baseRule.Keywords {
c.Keywords[k] = struct{}{}
}
c.OrderedRules = append(c.OrderedRules, ruleID)
} else {
// Rule exists, merge our changes into the base.
if currentRule.Description != "" {
baseRule.Description = currentRule.Description
}
if currentRule.Entropy != 0 {
baseRule.Entropy = currentRule.Entropy
}
if currentRule.SecretGroup != 0 {
baseRule.SecretGroup = currentRule.SecretGroup
}
if currentRule.Regex != nil {
baseRule.Regex = currentRule.Regex
}
if currentRule.Path != nil {
baseRule.Path = currentRule.Path
}
baseRule.Tags = append(baseRule.Tags, currentRule.Tags...)
baseRule.Keywords = append(baseRule.Keywords, currentRule.Keywords...)
for _, a := range currentRule.Allowlists {
baseRule.Allowlists = append(baseRule.Allowlists, a)
}
// The keywords from the base rule and the extended rule must be merged into the global keywords list
for _, k := range baseRule.Keywords {
c.Keywords[k] = struct{}{}
}
for _, k := range currentRule.Keywords {
c.Keywords[k] = struct{}{}
}
c.Rules[ruleID] = baseRule
}
}
+278 -33
View File
@@ -2,6 +2,7 @@ package config
import (
"fmt"
"github.com/google/go-cmp/cmp"
"regexp"
"testing"
@@ -14,22 +15,61 @@ const configPath = "../testdata/config/"
func TestTranslate(t *testing.T) {
tests := []struct {
cfgName string
cfg Config
// Configuration file basename to load, from `../testdata/config/`.
cfgName string
// Expected result.
cfg Config
// Rules to compare.
rules []string
// Error to expect.
wantError error
}{
{
cfgName: "allowlist_old_compat",
cfg: Config{
Rules: map[string]Rule{"example": {
RuleID: "example",
Regex: regexp.MustCompile(`example\d+`),
Tags: []string{},
Keywords: []string{},
Allowlists: []Allowlist{
{
MatchCondition: "OR",
Regexes: []*regexp.Regexp{regexp.MustCompile("123")},
},
},
},
},
},
},
{
cfgName: "allowlist_invalid_empty",
cfg: Config{},
wantError: fmt.Errorf("example: [[rules.allowlists]] must contain at least one check for: commits, paths, regexes, or stopwords"),
},
{
cfgName: "allowlist_invalid_old_and_new",
cfg: Config{},
wantError: fmt.Errorf("example: [rules.allowlist] is deprecated, it cannot be used alongside [[rules.allowlist]]"),
},
{
cfgName: "allowlist_invalid_regextarget",
cfg: Config{},
wantError: fmt.Errorf("example: unknown allowlist |regexTarget| 'mtach' (expected 'match', 'line')"),
},
{
cfgName: "allow_aws_re",
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}"),
Tags: []string{"key", "AWS"},
Keywords: []string{},
RuleID: "aws-access-key",
Allowlist: Allowlist{
Regexes: []*regexp.Regexp{
regexp.MustCompile("AKIALALEMEL33243OLIA"),
Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{
{
MatchCondition: "OR",
Regexes: []*regexp.Regexp{regexp.MustCompile("AKIALALEMEL33243OLIA")},
},
},
},
@@ -40,13 +80,16 @@ func TestTranslate(t *testing.T) {
cfgName: "allow_commit",
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}"),
Tags: []string{"key", "AWS"},
Keywords: []string{},
RuleID: "aws-access-key",
Allowlist: Allowlist{
Commits: []string{"allowthiscommit"},
Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{
{
MatchCondition: "OR",
Commits: []string{"allowthiscommit"},
},
},
},
},
@@ -56,14 +99,15 @@ func TestTranslate(t *testing.T) {
cfgName: "allow_path",
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Tags: []string{"key", "AWS"},
Keywords: []string{},
RuleID: "aws-access-key",
Allowlist: Allowlist{
Paths: []*regexp.Regexp{
regexp.MustCompile(".go"),
Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{
{
MatchCondition: "OR",
Paths: []*regexp.Regexp{regexp.MustCompile(".go")},
},
},
},
@@ -74,14 +118,13 @@ func TestTranslate(t *testing.T) {
cfgName: "entropy_group",
cfg: Config{
Rules: map[string]Rule{"discord-api-key": {
RuleID: "discord-api-key",
Description: "Discord API key",
Regex: regexp.MustCompile(`(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-h0-9]{64})['\"]`),
RuleID: "discord-api-key",
Allowlist: Allowlist{},
Keywords: []string{},
Entropy: 3.5,
SecretGroup: 3,
Tags: []string{},
Keywords: []string{},
},
},
},
@@ -91,11 +134,11 @@ func TestTranslate(t *testing.T) {
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})['\\\"]"),
},
//{
// cfgName: "no_regex_or_path",
// cfg: Config{},
// wantError: fmt.Errorf("discord-api-key: both |regex| and |path| are empty, this rule will have no effect"),
//},
{
cfgName: "no_regex_or_path",
cfg: Config{},
wantError: fmt.Errorf("discord-api-key: both |regex| and |path| are empty, this rule will have no effect"),
},
{
cfgName: "bad_entropy_group",
cfg: Config{},
@@ -106,34 +149,215 @@ func TestTranslate(t *testing.T) {
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}"),
Tags: []string{"key", "AWS"},
Keywords: []string{},
RuleID: "aws-access-key",
Tags: []string{"key", "AWS"},
},
"aws-secret-key": {
RuleID: "aws-secret-key",
Description: "AWS Secret Key",
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Tags: []string{"key", "AWS"},
Keywords: []string{},
RuleID: "aws-secret-key",
Tags: []string{"key", "AWS"},
},
"aws-secret-key-again": {
RuleID: "aws-secret-key-again",
Description: "AWS Secret Key",
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Tags: []string{"key", "AWS"},
Keywords: []string{},
RuleID: "aws-secret-key-again",
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "extend_rule_allowlist_or",
cfg: Config{
Rules: map[string]Rule{
"aws-secret-key-again-again": {
RuleID: "aws-secret-key-again-again",
Description: "AWS Secret Key",
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Keywords: []string{},
Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{
{
MatchCondition: "OR",
StopWords: []string{"fake"},
},
{
MatchCondition: "OR",
Commits: []string{"abcdefg1"},
Paths: []*regexp.Regexp{regexp.MustCompile(`ignore\.xaml`)},
Regexes: []*regexp.Regexp{regexp.MustCompile(`foo.+bar`)},
RegexTarget: "line",
StopWords: []string{"example"},
},
},
},
},
},
},
{
cfgName: "extend_rule_allowlist_and",
cfg: Config{
Rules: map[string]Rule{
"aws-secret-key-again-again": {
RuleID: "aws-secret-key-again-again",
Description: "AWS Secret Key",
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Keywords: []string{},
Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{
{
MatchCondition: "OR",
StopWords: []string{"fake"},
},
{
MatchCondition: "AND",
Commits: []string{"abcdefg1"},
Paths: []*regexp.Regexp{regexp.MustCompile(`ignore\.xaml`)},
Regexes: []*regexp.Regexp{regexp.MustCompile(`foo.+bar`)},
RegexTarget: "line",
StopWords: []string{"example"},
},
},
},
},
},
},
{
cfgName: "extend_empty_regexpath",
cfg: Config{
Rules: map[string]Rule{
"aws-secret-key-again-again": {
RuleID: "aws-secret-key-again-again",
Description: "AWS Secret Key",
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Keywords: []string{},
Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{
{
MatchCondition: "OR",
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"},
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.cfgName, func(t *testing.T) {
viper.Reset()
t.Cleanup(func() {
extendDepth = 0
viper.Reset()
})
viper.AddConfigPath(configPath)
viper.SetConfigName(tt.cfgName)
viper.SetConfigType("toml")
@@ -144,8 +368,29 @@ func TestTranslate(t *testing.T) {
err = viper.Unmarshal(&vc)
require.NoError(t, err)
cfg, err := vc.Translate()
assert.Equal(t, tt.wantError, err)
assert.Equal(t, cfg.Rules, tt.cfg.Rules)
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 {
// Compare the string representation of the regex patterns.
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)
}
})
}
}
+352 -484
View File
File diff suppressed because it is too large. Load diff
+5 -8
View File
@@ -39,9 +39,8 @@ type Rule struct {
// keyword(s) are in the content being scanned.
Keywords []string
// Allowlist allows a rule to be ignored for specific
// regexes, paths, and/or commits
Allowlist Allowlist
// Allowlists allows a rule to be ignored for specific commits, paths, regexes, and/or stopwords.
Allowlists []Allowlist
}
// Validate guards against common misconfigurations.
@@ -60,12 +59,10 @@ func (r Rule) Validate() error {
return fmt.Errorf("rule |id| is missing or empty" + context)
}
// TODO: uncomment this once it works with |extend|.
// See: https://github.com/gitleaks/gitleaks/issues/1507#issuecomment-2352559213
// Ensure the rule actually matches something.
//if r.Regex == nil && r.Path == nil {
// return fmt.Errorf("%s: both |regex| and |path| are empty, this rule will have no effect", r.RuleID)
//}
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)
}
// Ensure |secretGroup| works.
if r.Regex != nil && r.SecretGroup > r.Regex.NumSubexp() {
+3 -1
View File
@@ -5,6 +5,7 @@ import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/zricethezav/gitleaks/v8/report"
)
@@ -128,7 +129,8 @@ func TestIgnoreIssuesInBaseline(t *testing.T) {
}
for _, test := range tests {
d, _ := NewDetectorDefaultConfig()
d, err := NewDetectorDefaultConfig()
require.NoError(t, err)
d.baseline = test.baseline
for _, finding := range test.findings {
d.addFinding(finding)
+281
View File
@@ -0,0 +1,281 @@
package detect
import (
"bytes"
"encoding/base64"
"fmt"
"regexp"
"unicode"
"github.com/rs/zerolog/log"
)
var b64LikelyChars [128]byte
var b64Regexp = regexp.MustCompile(`[\w/+-]{16,}={0,3}`)
var decoders = []func(string) ([]byte, error){
base64.StdEncoding.DecodeString,
base64.RawURLEncoding.DecodeString,
}
func init() {
// Basically look for anything that isn't just letters
for _, c := range `0123456789+/-_` {
b64LikelyChars[c] = 1
}
}
// EncodedSegment represents a portion of text that is encoded in some way.
// `decode` supports recusive decoding and can result in "segment trees".
// There can be multiple segments in the original text, so each can be thought
// of as its own tree with the root being the original segment.
type EncodedSegment struct {
// The parent segment in a segment tree. If nil, it is a root segment
parent *EncodedSegment
// Relative start/end are the bounds of the encoded value in the current pass.
relativeStart int
relativeEnd int
// Absolute start/end refer to the bounds of the root segment in this segment
// tree
absoluteStart int
absoluteEnd int
// Decoded start/end refer to the bounds of the decoded value in the current
// pass. These can differ from relative values because decoding can shrink
// or grow the size of the segment.
decodedStart int
decodedEnd int
// This is the actual decoded content in the segment
decodedValue string
// This is the type of encoding
encoding string
}
// isChildOf inspects the bounds of two segments to determine
// if one should be the child of another
func (s EncodedSegment) isChildOf(parent EncodedSegment) bool {
return parent.decodedStart <= s.relativeStart && parent.decodedEnd >= s.relativeEnd
}
// decodedOverlaps checks if the decoded bounds of the segment overlaps a range
func (s EncodedSegment) decodedOverlaps(start, end int) bool {
return start <= s.decodedEnd && end >= s.decodedStart
}
// adjustMatchIndex takes the matchIndex from the current decoding pass and
// updates it to match the absolute matchIndex in the original text.
func (s EncodedSegment) adjustMatchIndex(matchIndex []int) []int {
// The match is within the bounds of the segment so we just return
// the absolute start and end of the root segment.
if s.decodedStart <= matchIndex[0] && matchIndex[1] <= s.decodedEnd {
return []int{
s.absoluteStart,
s.absoluteEnd,
}
}
// Since it overlaps one side and/or the other, we're going to have to adjust
// and climb parents until we're either at the root or we've determined
// we're fully inside one of the parent segments.
adjustedMatchIndex := make([]int, 2)
if matchIndex[0] < s.decodedStart {
// It starts before the encoded segment so adjust the start to match
// the location before it was decoded
matchStartDelta := s.decodedStart - matchIndex[0]
adjustedMatchIndex[0] = s.relativeStart - matchStartDelta
} else {
// It starts within the encoded segment so set the bound to the
// relative start
adjustedMatchIndex[0] = s.relativeStart
}
if matchIndex[1] > s.decodedEnd {
// It ends after the encoded segment so adjust the end to match
// the location before it was decoded
matchEndDelta := matchIndex[1] - s.decodedEnd
adjustedMatchIndex[1] = s.relativeEnd + matchEndDelta
} else {
// It ends within the encoded segment so set the bound to the relative end
adjustedMatchIndex[1] = s.relativeEnd
}
// We're still not at a root segment so we'll need to keep on adjusting
if s.parent != nil {
return s.parent.adjustMatchIndex(adjustedMatchIndex)
}
return adjustedMatchIndex
}
// depth reports how many levels of decoding needed to be done (default is 1)
func (s EncodedSegment) depth() int {
depth := 1
// Climb the tree and increment the depth
for current := &s; current.parent != nil; current = current.parent {
depth++
}
return depth
}
// tags returns additional meta data tags related to the types of segments
func (s EncodedSegment) tags() []string {
return []string{
fmt.Sprintf("decoded:%s", s.encoding),
fmt.Sprintf("decode-depth:%d", s.depth()),
}
}
// Decoder decodes various types of data in place
type Decoder struct {
decodedMap map[string]string
}
// NewDecoder creates a default decoder struct
func NewDecoder() *Decoder {
return &Decoder{
decodedMap: make(map[string]string),
}
}
// decode returns the data with the values decoded in-place
func (d *Decoder) decode(data string, parentSegments []EncodedSegment) (string, []EncodedSegment) {
segments := d.findEncodedSegments(data, parentSegments)
if len(segments) > 0 {
result := bytes.NewBuffer(make([]byte, 0, len(data)))
relativeStart := 0
for _, segment := range segments {
result.WriteString(data[relativeStart:segment.relativeStart])
result.WriteString(segment.decodedValue)
relativeStart = segment.relativeEnd
}
result.WriteString(data[relativeStart:])
return result.String(), segments
}
return data, segments
}
// findEncodedSegments finds the encoded segments in the data and updates the
// segment tree for this pass
func (d *Decoder) findEncodedSegments(data string, parentSegments []EncodedSegment) []EncodedSegment {
if len(data) == 0 {
return []EncodedSegment{}
}
matchIndices := b64Regexp.FindAllStringIndex(data, -1)
if matchIndices == nil {
return []EncodedSegment{}
}
segments := make([]EncodedSegment, 0, len(matchIndices))
// Keeps up with offsets from the text changing size as things are decoded
decodedShift := 0
for _, matchIndex := range matchIndices {
encodedValue := data[matchIndex[0]:matchIndex[1]]
if !isLikelyB64(encodedValue) {
d.decodedMap[encodedValue] = ""
continue
}
decodedValue, alreadyDecoded := d.decodedMap[encodedValue]
// We haven't decoded this yet, so go ahead and decode it
if !alreadyDecoded {
decodedValue = decodeValue(encodedValue)
d.decodedMap[encodedValue] = decodedValue
}
// Skip this segment because there was nothing to check
if len(decodedValue) == 0 {
continue
}
// Create a segment for the encoded data
segment := EncodedSegment{
relativeStart: matchIndex[0],
relativeEnd: matchIndex[1],
absoluteStart: matchIndex[0],
absoluteEnd: matchIndex[1],
decodedStart: matchIndex[0] + decodedShift,
decodedEnd: matchIndex[0] + decodedShift + len(decodedValue),
decodedValue: decodedValue,
encoding: "base64",
}
// Shift decoded start and ends based on size changes
decodedShift += len(decodedValue) - len(encodedValue)
// Adjust the absolute position of segments contained in parent segments
for _, parentSegment := range parentSegments {
if segment.isChildOf(parentSegment) {
segment.absoluteStart = parentSegment.absoluteStart
segment.absoluteEnd = parentSegment.absoluteEnd
segment.parent = &parentSegment
break
}
}
log.Debug().Msgf("segment found: %#v", segment)
segments = append(segments, segment)
}
return segments
}
// decoders tries a list of decoders and returns the first successful one
func decodeValue(encodedValue string) string {
for _, decoder := range decoders {
decodedValue, err := decoder(encodedValue)
if err == nil && len(decodedValue) > 0 && isASCII(decodedValue) {
return string(decodedValue)
}
}
return ""
}
func isASCII(b []byte) bool {
for i := 0; i < len(b); i++ {
if b[i] > unicode.MaxASCII || b[i] < '\t' {
return false
}
}
return true
}
// Skip a lot of method signatures and things at the risk of missing about
// 1% of base64
func isLikelyB64(s string) bool {
for _, c := range s {
if b64LikelyChars[c] != 0 {
return true
}
}
return false
}
// Find a segment where the decoded bounds overlaps a range
func segmentWithDecodedOverlap(encodedSegments []EncodedSegment, start, end int) *EncodedSegment {
for _, segment := range encodedSegments {
if segment.decodedOverlaps(start, end) {
return &segment
}
}
return nil
}
+91
View File
@@ -0,0 +1,91 @@
package detect
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestDecode(t *testing.T) {
tests := []struct {
chunk string
expected string
name string
}{
{
name: "only b64 chunk",
chunk: `bG9uZ2VyLWVuY29kZWQtc2VjcmV0LXRlc3Q=`,
expected: `longer-encoded-secret-test`,
},
{
name: "mixed content",
chunk: `token: bG9uZ2VyLWVuY29kZWQtc2VjcmV0LXRlc3Q=`,
expected: `token: longer-encoded-secret-test`,
},
{
name: "no chunk",
chunk: ``,
expected: ``,
},
{
name: "env var (looks like all b64 decodable but has `=` in the middle)",
chunk: `some-encoded-secret=dGVzdC1zZWNyZXQtdmFsdWU=`,
expected: `some-encoded-secret=test-secret-value`,
},
{
name: "has longer b64 inside",
chunk: `some-encoded-secret="bG9uZ2VyLWVuY29kZWQtc2VjcmV0LXRlc3Q="`,
expected: `some-encoded-secret="longer-encoded-secret-test"`,
},
{
name: "many possible i := 0substrings",
chunk: `Many substrings in this slack message could be base64 decoded
but only dGhpcyBlbmNhcHN1bGF0ZWQgc2VjcmV0 should be decoded.`,
expected: `Many substrings in this slack message could be base64 decoded
but only this encapsulated secret should be decoded.`,
},
{
name: "b64-url-safe: only b64 chunk",
chunk: `bG9uZ2VyLWVuY29kZWQtc2VjcmV0LXRlc3Q`,
expected: `longer-encoded-secret-test`,
},
{
name: "b64-url-safe: mixed content",
chunk: `token: bG9uZ2VyLWVuY29kZWQtc2VjcmV0LXRlc3Q`,
expected: `token: longer-encoded-secret-test`,
},
{
name: "b64-url-safe: env var (looks like all b64 decodable but has `=` in the middle)",
chunk: `some-encoded-secret=dGVzdC1zZWNyZXQtdmFsdWU=`,
expected: `some-encoded-secret=test-secret-value`,
},
{
name: "b64-url-safe: has longer b64 inside",
chunk: `some-encoded-secret="bG9uZ2VyLWVuY29kZWQtc2VjcmV0LXRlc3Q"`,
expected: `some-encoded-secret="longer-encoded-secret-test"`,
},
{
name: "b64-url-safe: hyphen url b64",
chunk: `dHJ1ZmZsZWhvZz4-ZmluZHMtc2VjcmV0cw`,
expected: `trufflehog>>finds-secrets`,
},
{
name: "b64-url-safe: underscore url b64",
chunk: `YjY0dXJsc2FmZS10ZXN0LXNlY3JldC11bmRlcnNjb3Jlcz8_`,
expected: `b64urlsafe-test-secret-underscores??`,
},
{
name: "invalid base64 string",
chunk: `a3d3fa7c2bb99e469ba55e5834ce79ee4853a8a3`,
expected: `a3d3fa7c2bb99e469ba55e5834ce79ee4853a8a3`,
},
}
decoder := NewDecoder()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
decoded, _ := decoder.decode(tt.chunk, []EncodedSegment{})
assert.Equal(t, tt.expected, decoded)
})
}
}
+207 -59
View File
@@ -14,9 +14,10 @@ import (
ahocorasick "github.com/BobuSumisu/aho-corasick"
"github.com/fatih/semgroup"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
"golang.org/x/exp/maps"
)
const (
@@ -24,6 +25,8 @@ const (
chunkSize = 10 * 1_000 // 10kb
)
var newLineRegexp = regexp.MustCompile("\n")
// Detector is the main detector struct
type Detector struct {
// Config is the configuration for the detector
@@ -37,6 +40,9 @@ type Detector struct {
// verbose is a flag to print findings
Verbose bool
// MaxDecodeDepths limits how many recursive decoding passes are allowed
MaxDecodeDepth int
// files larger than this will be skipped
MaxTargetMegaBytes int
@@ -94,10 +100,6 @@ type Fragment struct {
// newlineIndices is a list of indices of newlines in the raw content.
// This is used to calculate the line location of a finding
newlineIndices [][]int
// keywords is a map of all the keywords contain within the contents
// of this fragment
keywords map[string]bool
}
// NewDetector creates a new detector with the given config
@@ -108,7 +110,7 @@ func NewDetector(cfg config.Config) *Detector {
findingMutex: &sync.Mutex{},
findings: make([]report.Finding, 0),
Config: cfg,
prefilter: *ahocorasick.NewTrieBuilder().AddStrings(cfg.Keywords).Build(),
prefilter: *ahocorasick.NewTrieBuilder().AddStrings(maps.Keys(cfg.Keywords)).Build(),
Sema: semgroup.NewGroup(context.Background(), 40),
}
}
@@ -149,7 +151,11 @@ func (d *Detector) AddGitleaksIgnore(gitleaksIgnorePath string) error {
scanner := bufio.NewScanner(file)
for scanner.Scan() {
d.gitleaksIgnore[scanner.Text()] = true
line := strings.TrimSpace(scanner.Text())
// Skip lines that start with a comment
if line != "" && !strings.HasPrefix(line, "#") {
d.gitleaksIgnore[line] = true
}
}
return nil
}
@@ -170,9 +176,6 @@ func (d *Detector) DetectString(content string) []report.Finding {
func (d *Detector) Detect(fragment Fragment) []report.Finding {
var findings []report.Finding
// initiate fragment keywords
fragment.keywords = make(map[string]bool)
// check if filepath is allowed
if fragment.FilePath != "" && (d.Config.Allowlist.PathAllowed(fragment.FilePath) ||
fragment.FilePath == d.Config.Path || (d.baselinePath != "" && fragment.FilePath == d.baselinePath)) {
@@ -180,47 +183,114 @@ func (d *Detector) Detect(fragment Fragment) []report.Finding {
}
// add newline indices for location calculation in detectRule
fragment.newlineIndices = regexp.MustCompile("\n").FindAllStringIndex(fragment.Raw, -1)
fragment.newlineIndices = newLineRegexp.FindAllStringIndex(fragment.Raw, -1)
// build keyword map for prefiltering rules
normalizedRaw := strings.ToLower(fragment.Raw)
matches := d.prefilter.MatchString(normalizedRaw)
for _, m := range matches {
fragment.keywords[normalizedRaw[m.Pos():int(m.Pos())+len(m.Match())]] = true
}
// setup variables to handle different decoding passes
currentRaw := fragment.Raw
encodedSegments := []EncodedSegment{}
currentDecodeDepth := 0
decoder := NewDecoder()
for _, rule := range d.Config.Rules {
if len(rule.Keywords) == 0 {
// if not keywords are associated with the rule always scan the
// fragment using the rule
findings = append(findings, d.detectRule(fragment, rule)...)
continue
for {
// build keyword map for prefiltering rules
keywords := make(map[string]bool)
normalizedRaw := strings.ToLower(currentRaw)
matches := d.prefilter.MatchString(normalizedRaw)
for _, m := range matches {
keywords[normalizedRaw[m.Pos():int(m.Pos())+len(m.Match())]] = true
}
fragmentContainsKeyword := false
// check if keywords are in the fragment
for _, k := range rule.Keywords {
if _, ok := fragment.keywords[strings.ToLower(k)]; ok {
fragmentContainsKeyword = true
for _, rule := range d.Config.Rules {
if len(rule.Keywords) == 0 {
// if no keywords are associated with the rule always scan the
// fragment using the rule
findings = append(findings, d.detectRule(fragment, currentRaw, rule, encodedSegments)...)
continue
}
// check if keywords are in the fragment
for _, k := range rule.Keywords {
if _, ok := keywords[strings.ToLower(k)]; ok {
findings = append(findings, d.detectRule(fragment, currentRaw, rule, encodedSegments)...)
break
}
}
}
if fragmentContainsKeyword {
findings = append(findings, d.detectRule(fragment, rule)...)
// increment the depth by 1 as we start our decoding pass
currentDecodeDepth++
// stop the loop if we've hit our max decoding depth
if currentDecodeDepth > d.MaxDecodeDepth {
break
}
// decode the currentRaw for the next pass
currentRaw, encodedSegments = decoder.decode(currentRaw, encodedSegments)
// stop the loop when there's nothing else to decode
if len(encodedSegments) == 0 {
break
}
}
return filter(findings, d.Redact)
}
// detectRule scans the given fragment for the given rule and returns a list of findings
func (d *Detector) detectRule(fragment Fragment, rule config.Rule) []report.Finding {
var findings []report.Finding
func (d *Detector) detectRule(fragment Fragment, currentRaw string, rule config.Rule, encodedSegments []EncodedSegment) []report.Finding {
var (
findings []report.Finding
logger = func() zerolog.Logger {
l := log.With().Str("rule-id", rule.RuleID)
if fragment.CommitSHA != "" {
l = l.Str("commit", fragment.CommitSHA)
}
l = l.Str("path", fragment.FilePath)
return l.Logger()
}()
)
// check if filepath or commit is allowed for this rule
if rule.Allowlist.CommitAllowed(fragment.CommitSHA) ||
rule.Allowlist.PathAllowed(fragment.FilePath) {
return findings
for _, a := range rule.Allowlists {
var (
isAllowed bool
commitAllowed = a.CommitAllowed(fragment.CommitSHA)
pathAllowed = a.PathAllowed(fragment.FilePath)
)
if a.MatchCondition == config.AllowlistMatchAnd {
// Determine applicable checks.
var allowlistChecks []bool
if len(a.Commits) > 0 {
allowlistChecks = append(allowlistChecks, commitAllowed)
}
if len(a.Paths) > 0 {
allowlistChecks = append(allowlistChecks, pathAllowed)
}
// These will be checked later.
if len(a.Regexes) > 0 {
allowlistChecks = append(allowlistChecks, false)
}
if len(a.StopWords) > 0 {
allowlistChecks = append(allowlistChecks, false)
}
// Check if allowed.
isAllowed = allTrue(allowlistChecks)
} else {
isAllowed = commitAllowed || pathAllowed
}
if isAllowed {
logger.Trace().
Str("condition", string(a.MatchCondition)).
Bool("commit-allowed", commitAllowed).
Bool("path-allowed", commitAllowed).
Msg("Skipping fragment due to rule allowlist")
return findings
}
}
if rule.Path != nil && rule.Regex == nil {
if rule.Path != nil && rule.Regex == nil && len(encodedSegments) == 0 {
// Path _only_ rule
if rule.Path.MatchString(fragment.FilePath) {
finding := report.Finding{
@@ -247,19 +317,40 @@ func (d *Detector) detectRule(fragment Fragment, rule config.Rule) []report.Find
return findings
}
// If flag configure and raw data size bigger then the flag
// if flag configure and raw data size bigger then the flag
if d.MaxTargetMegaBytes > 0 {
rawLength := len(fragment.Raw) / 1000000
rawLength := len(currentRaw) / 1000000
if rawLength > d.MaxTargetMegaBytes {
log.Debug().Msgf("skipping file: %s scan due to size: %d", fragment.FilePath, rawLength)
return findings
}
}
matchIndices := rule.Regex.FindAllStringIndex(fragment.Raw, -1)
for _, matchIndex := range matchIndices {
// extract secret from match
secret := strings.Trim(fragment.Raw[matchIndex[0]:matchIndex[1]], "\n")
// use currentRaw instead of fragment.Raw since this represents the current
// decoding pass on the text
MatchLoop:
for _, matchIndex := range rule.Regex.FindAllStringIndex(currentRaw, -1) {
// Extract secret from match
secret := strings.Trim(currentRaw[matchIndex[0]:matchIndex[1]], "\n")
// For any meta data from decoding
var metaTags []string
// Check if the decoded portions of the segment overlap with the match
// to see if its potentially a new match
if len(encodedSegments) > 0 {
if segment := segmentWithDecodedOverlap(encodedSegments, matchIndex[0], matchIndex[1]); segment != nil {
matchIndex = segment.adjustMatchIndex(matchIndex)
metaTags = append(metaTags, segment.tags()...)
} else {
// This item has already been added to a finding
continue
}
} else {
// Fixes: https://github.com/gitleaks/gitleaks/issues/1352
// removes the incorrectly following line that was detected by regex expression '\n'
matchIndex[1] = matchIndex[0] + len(secret)
}
// determine location of match. Note that the location
// in the finding will be the line/column numbers of the _match_
@@ -282,12 +373,15 @@ func (d *Detector) detectRule(fragment Fragment, rule config.Rule) []report.Find
EndColumn: loc.endColumn,
Secret: secret,
Match: secret,
Tags: rule.Tags,
Tags: append(rule.Tags, metaTags...),
Line: fragment.Raw[loc.startLineIndex:loc.endLineIndex],
}
if strings.Contains(fragment.Raw[loc.startLineIndex:loc.endLineIndex],
gitleaksAllowSignature) && !d.IgnoreGitleaksAllow {
if !d.IgnoreGitleaksAllow &&
strings.Contains(fragment.Raw[loc.startLineIndex:loc.endLineIndex], gitleaksAllowSignature) {
logger.Trace().
Str("finding", finding.Secret).
Msg("Skipping finding due to 'gitleaks:allow' signature")
continue
}
@@ -319,14 +413,7 @@ func (d *Detector) detectRule(fragment Fragment, rule config.Rule) []report.Find
}
// check if the regexTarget is defined in the allowlist "regexes" entry
allowlistTarget := finding.Secret
switch rule.Allowlist.RegexTarget {
case "match":
allowlistTarget = finding.Match
case "line":
allowlistTarget = finding.Line
}
// or if the secret is in the list of stopwords
globalAllowlistTarget := finding.Secret
switch d.Config.Allowlist.RegexTarget {
case "match":
@@ -334,15 +421,65 @@ func (d *Detector) detectRule(fragment Fragment, rule config.Rule) []report.Find
case "line":
globalAllowlistTarget = finding.Line
}
if rule.Allowlist.RegexAllowed(allowlistTarget) ||
d.Config.Allowlist.RegexAllowed(globalAllowlistTarget) {
if d.Config.Allowlist.RegexAllowed(globalAllowlistTarget) {
logger.Trace().
Str("finding", globalAllowlistTarget).
Msg("Skipping finding due to global allowlist regex")
continue
} else if d.Config.Allowlist.ContainsStopWord(finding.Secret) {
logger.Trace().
Str("finding", finding.Secret).
Msg("Skipping finding due to global allowlist stopword")
continue
}
// check if the secret is in the list of stopwords
if rule.Allowlist.ContainsStopWord(finding.Secret) ||
d.Config.Allowlist.ContainsStopWord(finding.Secret) {
continue
// check if the result matches any of the rule allowlists.
for _, a := range rule.Allowlists {
allowlistTarget := finding.Secret
switch a.RegexTarget {
case "match":
allowlistTarget = finding.Match
case "line":
allowlistTarget = finding.Line
}
var (
isAllowed bool
regexAllowed = a.RegexAllowed(allowlistTarget)
containsStopword = a.ContainsStopWord(finding.Secret)
)
// check if the secret is in the list of stopwords
if a.MatchCondition == config.AllowlistMatchAnd {
// Determine applicable checks.
var allowlistChecks []bool
if len(a.Commits) > 0 {
allowlistChecks = append(allowlistChecks, a.CommitAllowed(fragment.CommitSHA))
}
if len(a.Paths) > 0 {
allowlistChecks = append(allowlistChecks, a.PathAllowed(fragment.FilePath))
}
if len(a.Regexes) > 0 {
allowlistChecks = append(allowlistChecks, regexAllowed)
}
if len(a.StopWords) > 0 {
allowlistChecks = append(allowlistChecks, containsStopword)
}
// Check if allowed.
isAllowed = allTrue(allowlistChecks)
} else {
isAllowed = regexAllowed || containsStopword
}
if isAllowed {
logger.Trace().
Str("finding", finding.Secret).
Str("condition", string(a.MatchCondition)).
Bool("regex-allowed", regexAllowed).
Bool("contains-stopword", containsStopword).
Msg("Skipping finding due to rule allowlist")
continue MatchLoop
}
}
// check entropy
@@ -372,6 +509,17 @@ func (d *Detector) detectRule(fragment Fragment, rule config.Rule) []report.Find
return findings
}
func allTrue(bools []bool) bool {
allMatch := true
for _, check := range bools {
if !check {
allMatch = false
break
}
}
return allMatch
}
// addFinding synchronously adds a finding to the findings slice
func (d *Detector) addFinding(finding report.Finding) {
globalFingerprint := fmt.Sprintf("%s:%s:%d", finding.File, finding.RuleID, finding.StartLine)
+419 -29
View File
@@ -2,8 +2,10 @@ package detect
import (
"fmt"
"github.com/google/go-cmp/cmp"
"os"
"path/filepath"
"regexp"
"testing"
"github.com/spf13/viper"
@@ -15,8 +17,31 @@ import (
"github.com/zricethezav/gitleaks/v8/sources"
)
const maxDecodeDepth = 8
const configPath = "../testdata/config/"
const repoBasePath = "../testdata/repos/"
const b64TestValues = `
# Decoded
-----BEGIN PRIVATE KEY-----
135f/bRUBHrbHqLY/xS3I7Oth+8rgG+0tBwfMcbk05Sgxq6QUzSYIQAop+WvsTwk2sR+C38g0Mnb
u+QDkg0spw==
-----END PRIVATE KEY-----
# Encoded
private_key: 'LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCjQzNWYvYlJVQkhyYkhxTFkveFMzSTdPdGgrOHJnRyswdEJ3Zk1jYmswNVNneHE2UVV6U1lJUUFvcCtXdnNUd2syc1IrQzM4ZzBNbmIKdStRRGtnMHNwdz09Ci0tLS0tRU5EIFBSSVZBVEUgS0VZLS0tLS0K'
# Double Encoded: b64 encoded aws config inside a jwt
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiY29uZmlnIjoiVzJSbFptRjFiSFJkQ25KbFoybHZiaUE5SUhWekxXVmhjM1F0TWdwaGQzTmZZV05qWlhOelgydGxlVjlwWkNBOUlFRlRTVUZKVDFOR1QwUk9UamRNV0UweE1FcEpDbUYzYzE5elpXTnlaWFJmWVdOalpYTnpYMnRsZVNBOUlIZEtZV3h5V0ZWMGJrWkZUVWt2U3pkTlJFVk9SeTlpVUhoU1ptbERXVVZHVlVORWJFVllNVUVLIiwiaWF0IjoxNTE2MjM5MDIyfQ.8gxviXEOuIBQk2LvTYHSf-wXVhnEKC3h4yM5nlOF4zA
# A small secret at the end to make sure that as the other ones above shrink
# when decoded, the positions are taken into consideratoin for overlaps
c21hbGwtc2VjcmV0
# This tests how it handles when the match bounds go outside the decoded value
secret=ZGVjb2RlZC1zZWNyZXQtdmFsdWU=
# The above encoded again
c2VjcmV0PVpHVmpiMlJsWkMxelpXTnlaWFF0ZG1Gc2RXVT0=
`
func TestDetect(t *testing.T) {
tests := []struct {
@@ -37,7 +62,6 @@ func TestDetect(t *testing.T) {
Raw: `awsToken := \"AKIALALEMEL33243OKIA\ // gitleaks:allow"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "simple",
@@ -49,7 +73,6 @@ func TestDetect(t *testing.T) {
`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "simple",
@@ -199,7 +222,6 @@ func TestDetect(t *testing.T) {
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "allow_path",
@@ -207,7 +229,6 @@ func TestDetect(t *testing.T) {
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "allow_commit",
@@ -216,7 +237,6 @@ func TestDetect(t *testing.T) {
FilePath: "tmp.go",
CommitSHA: "allowthiscommit",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "entropy_group",
@@ -247,7 +267,6 @@ func TestDetect(t *testing.T) {
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "generic_with_py_path",
@@ -294,8 +313,7 @@ func TestDetect(t *testing.T) {
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
wantError: fmt.Errorf("discord-api-key: invalid regex secret group 5, max regex secret group 3"),
wantError: fmt.Errorf("discord-api-key: invalid regex secret group 5, max regex secret group 3"),
},
{
cfgName: "simple",
@@ -303,7 +321,6 @@ func TestDetect(t *testing.T) {
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: filepath.Join(configPath, "simple.toml"),
},
expectedFindings: []report.Finding{},
},
{
cfgName: "allow_global_aws_re",
@@ -311,7 +328,6 @@ func TestDetect(t *testing.T) {
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "generic_with_py_path",
@@ -319,7 +335,6 @@ func TestDetect(t *testing.T) {
Raw: `const Discord_Public_Key = "load2523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: "tmp.py",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "path_only",
@@ -328,29 +343,152 @@ func TestDetect(t *testing.T) {
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: ".baseline.json",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "base64_encoded",
fragment: Fragment{
Raw: b64TestValues,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{
{ // Plain text key captured by normal rule
Description: "Private Key",
Secret: "-----BEGIN PRIVATE KEY-----\n135f/bRUBHrbHqLY/xS3I7Oth+8rgG+0tBwfMcbk05Sgxq6QUzSYIQAop+WvsTwk2sR+C38g0Mnb\nu+QDkg0spw==\n-----END PRIVATE KEY-----",
Match: "-----BEGIN PRIVATE KEY-----\n135f/bRUBHrbHqLY/xS3I7Oth+8rgG+0tBwfMcbk05Sgxq6QUzSYIQAop+WvsTwk2sR+C38g0Mnb\nu+QDkg0spw==\n-----END PRIVATE KEY-----",
File: "tmp.go",
Line: "\n-----BEGIN PRIVATE KEY-----\n135f/bRUBHrbHqLY/xS3I7Oth+8rgG+0tBwfMcbk05Sgxq6QUzSYIQAop+WvsTwk2sR+C38g0Mnb\nu+QDkg0spw==\n-----END PRIVATE KEY-----",
RuleID: "private-key",
Tags: []string{"key", "private"},
StartLine: 2,
EndLine: 5,
StartColumn: 2,
EndColumn: 26,
Entropy: 5.350665,
},
{ // Encoded key captured by custom b64 regex rule
Description: "Private Key",
Secret: "LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCjQzNWYvYlJVQkhyYkhxTFkveFMzSTdPdGgrOHJnRyswdEJ3Zk1jYmswNVNneHE2UVV6U1lJUUFvcCtXdnNUd2syc1IrQzM4ZzBNbmIKdStRRGtnMHNwdz09Ci0tLS0tRU5EIFBSSVZBVEUgS0VZLS0tLS0K",
Match: "LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCjQzNWYvYlJVQkhyYkhxTFkveFMzSTdPdGgrOHJnRyswdEJ3Zk1jYmswNVNneHE2UVV6U1lJUUFvcCtXdnNUd2syc1IrQzM4ZzBNbmIKdStRRGtnMHNwdz09Ci0tLS0tRU5EIFBSSVZBVEUgS0VZLS0tLS0K",
File: "tmp.go",
Line: "\nprivate_key: 'LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCjQzNWYvYlJVQkhyYkhxTFkveFMzSTdPdGgrOHJnRyswdEJ3Zk1jYmswNVNneHE2UVV6U1lJUUFvcCtXdnNUd2syc1IrQzM4ZzBNbmIKdStRRGtnMHNwdz09Ci0tLS0tRU5EIFBSSVZBVEUgS0VZLS0tLS0K'",
RuleID: "b64-encoded-private-key",
Tags: []string{"key", "private"},
StartLine: 8,
EndLine: 8,
StartColumn: 16,
EndColumn: 207,
Entropy: 5.3861146,
},
{ // Encoded key captured by plain text rule using the decoder
Description: "Private Key",
Secret: "-----BEGIN PRIVATE KEY-----\n435f/bRUBHrbHqLY/xS3I7Oth+8rgG+0tBwfMcbk05Sgxq6QUzSYIQAop+WvsTwk2sR+C38g0Mnb\nu+QDkg0spw==\n-----END PRIVATE KEY-----",
Match: "-----BEGIN PRIVATE KEY-----\n435f/bRUBHrbHqLY/xS3I7Oth+8rgG+0tBwfMcbk05Sgxq6QUzSYIQAop+WvsTwk2sR+C38g0Mnb\nu+QDkg0spw==\n-----END PRIVATE KEY-----",
File: "tmp.go",
Line: "\nprivate_key: 'LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCjQzNWYvYlJVQkhyYkhxTFkveFMzSTdPdGgrOHJnRyswdEJ3Zk1jYmswNVNneHE2UVV6U1lJUUFvcCtXdnNUd2syc1IrQzM4ZzBNbmIKdStRRGtnMHNwdz09Ci0tLS0tRU5EIFBSSVZBVEUgS0VZLS0tLS0K'",
RuleID: "private-key",
Tags: []string{"key", "private", "decoded:base64", "decode-depth:1"},
StartLine: 8,
EndLine: 8,
StartColumn: 16,
EndColumn: 207,
Entropy: 5.350665,
},
{ // Encoded AWS config with a access key id inside a JWT
Description: "AWS IAM Unique Identifier",
Secret: "ASIAIOSFODNN7LXM10JI",
Match: " ASIAIOSFODNN7LXM10JI",
File: "tmp.go",
Line: "\neyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiY29uZmlnIjoiVzJSbFptRjFiSFJkQ25KbFoybHZiaUE5SUhWekxXVmhjM1F0TWdwaGQzTmZZV05qWlhOelgydGxlVjlwWkNBOUlFRlRTVUZKVDFOR1QwUk9UamRNV0UweE1FcEpDbUYzYzE5elpXTnlaWFJmWVdOalpYTnpYMnRsZVNBOUlIZEtZV3h5V0ZWMGJrWkZUVWt2U3pkTlJFVk9SeTlpVUhoU1ptbERXVVZHVlVORWJFVllNVUVLIiwiaWF0IjoxNTE2MjM5MDIyfQ.8gxviXEOuIBQk2LvTYHSf-wXVhnEKC3h4yM5nlOF4zA",
RuleID: "aws-iam-unique-identifier",
Tags: []string{"aws", "identifier", "decoded:base64", "decode-depth:2"},
StartLine: 11,
EndLine: 11,
StartColumn: 39,
EndColumn: 344,
Entropy: 3.6841838,
},
{ // Encoded AWS config with a secret access key inside a JWT
Description: "AWS Secret Access Key",
Secret: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEFUCDlEX1A",
Match: "aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEFUCDlEX1A",
File: "tmp.go",
Line: "\neyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiY29uZmlnIjoiVzJSbFptRjFiSFJkQ25KbFoybHZiaUE5SUhWekxXVmhjM1F0TWdwaGQzTmZZV05qWlhOelgydGxlVjlwWkNBOUlFRlRTVUZKVDFOR1QwUk9UamRNV0UweE1FcEpDbUYzYzE5elpXTnlaWFJmWVdOalpYTnpYMnRsZVNBOUlIZEtZV3h5V0ZWMGJrWkZUVWt2U3pkTlJFVk9SeTlpVUhoU1ptbERXVVZHVlVORWJFVllNVUVLIiwiaWF0IjoxNTE2MjM5MDIyfQ.8gxviXEOuIBQk2LvTYHSf-wXVhnEKC3h4yM5nlOF4zA",
RuleID: "aws-secret-access-key",
Tags: []string{"aws", "secret", "decoded:base64", "decode-depth:2"},
StartLine: 11,
EndLine: 11,
StartColumn: 39,
EndColumn: 344,
Entropy: 4.721928,
},
{ // Encoded Small secret at the end to make sure it's picked up by the decoding
Description: "Small Secret",
Secret: "small-secret",
Match: "small-secret",
File: "tmp.go",
Line: "\nc21hbGwtc2VjcmV0",
RuleID: "small-secret",
Tags: []string{"small", "secret", "decoded:base64", "decode-depth:1"},
StartLine: 15,
EndLine: 15,
StartColumn: 2,
EndColumn: 17,
Entropy: 3.0849626,
},
{ // Secret where the decoded match goes outside the encoded value
Description: "Overlapping",
Secret: "decoded-secret-value",
Match: "secret=decoded-secret-value",
File: "tmp.go",
Line: "\nsecret=ZGVjb2RlZC1zZWNyZXQtdmFsdWU=",
RuleID: "overlapping",
Tags: []string{"overlapping", "decoded:base64", "decode-depth:1"},
StartLine: 18,
EndLine: 18,
StartColumn: 2,
EndColumn: 36,
Entropy: 3.3037016,
},
{ // Secret where the decoded match goes outside the encoded value and then encoded again
Description: "Overlapping",
Secret: "decoded-secret-value",
Match: "secret=decoded-secret-value",
File: "tmp.go",
Line: "\nc2VjcmV0PVpHVmpiMlJsWkMxelpXTnlaWFF0ZG1Gc2RXVT0=",
RuleID: "overlapping",
Tags: []string{"overlapping", "decoded:base64", "decode-depth:2"},
StartLine: 20,
EndLine: 20,
StartColumn: 2,
EndColumn: 49,
Entropy: 3.3037016,
},
},
},
}
for _, tt := range tests {
viper.Reset()
viper.AddConfigPath(configPath)
viper.SetConfigName(tt.cfgName)
viper.SetConfigType("toml")
err := viper.ReadInConfig()
require.NoError(t, err)
t.Run(fmt.Sprintf("%s - %s", tt.cfgName, tt.fragment.FilePath), func(t *testing.T) {
viper.Reset()
viper.AddConfigPath(configPath)
viper.SetConfigName(tt.cfgName)
viper.SetConfigType("toml")
err := viper.ReadInConfig()
require.NoError(t, err)
var vc config.ViperConfig
err = viper.Unmarshal(&vc)
require.NoError(t, err)
cfg, err := vc.Translate()
cfg.Path = filepath.Join(configPath, tt.cfgName+".toml")
assert.Equal(t, tt.wantError, err)
d := NewDetector(cfg)
d.baselinePath = tt.baselinePath
var vc config.ViperConfig
err = viper.Unmarshal(&vc)
require.NoError(t, err)
cfg, err := vc.Translate()
cfg.Path = filepath.Join(configPath, tt.cfgName+".toml")
assert.Equal(t, tt.wantError, err)
d := NewDetector(cfg)
d.MaxDecodeDepth = maxDecodeDepth
d.baselinePath = tt.baselinePath
findings := d.Detect(tt.fragment)
assert.ElementsMatch(t, tt.expectedFindings, findings)
findings := d.Detect(tt.fragment)
assert.ElementsMatch(t, tt.expectedFindings, findings)
})
}
}
@@ -603,11 +741,32 @@ func TestFromFiles(t *testing.T) {
cfgName: "simple",
expectedFindings: []report.Finding{},
},
{
source: filepath.Join(repoBasePath, "nogit", ".env.prod"),
cfgName: "generic",
expectedFindings: []report.Finding{
{
Description: "Generic API Key",
StartLine: 4,
EndLine: 4,
StartColumn: 5,
EndColumn: 35,
Match: "PASSWORD=8ae31cacf141669ddfb5da",
Secret: "8ae31cacf141669ddfb5da",
Line: "\nDB_PASSWORD=8ae31cacf141669ddfb5da",
File: "../testdata/repos/nogit/.env.prod",
RuleID: "generic-api-key",
Tags: []string{},
Entropy: 3.5383105,
Fingerprint: "../testdata/repos/nogit/.env.prod:generic-api-key:4",
},
},
},
}
for _, tt := range tests {
viper.AddConfigPath(configPath)
viper.SetConfigName("simple")
viper.SetConfigName(tt.cfgName)
viper.SetConfigType("toml")
err := viper.ReadInConfig()
require.NoError(t, err)
@@ -689,6 +848,237 @@ func TestDetectWithSymlinks(t *testing.T) {
}
}
func TestDetectRuleAllowlist(t *testing.T) {
cases := map[string]struct {
fragment Fragment
allowlist config.Allowlist
expected []report.Finding
}{
// Commit / path
"commit allowed": {
fragment: Fragment{
CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
},
allowlist: config.Allowlist{
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
},
},
"path allowed": {
fragment: Fragment{
FilePath: "package-lock.json",
},
allowlist: config.Allowlist{
Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
},
},
"commit AND path allowed": {
fragment: Fragment{
CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
FilePath: "package-lock.json",
},
allowlist: config.Allowlist{
MatchCondition: config.AllowlistMatchAnd,
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
},
},
"commit AND path NOT allowed": {
fragment: Fragment{
CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
FilePath: "package.json",
},
allowlist: config.Allowlist{
MatchCondition: config.AllowlistMatchAnd,
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
},
expected: []report.Finding{
{
StartColumn: 50,
EndColumn: 60,
Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
Match: "Summer2024!",
Secret: "Summer2024!",
File: "package.json",
Entropy: 3.095795154571533,
RuleID: "test-rule",
},
},
},
"commit AND path NOT allowed - other conditions": {
fragment: Fragment{
CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
FilePath: "package-lock.json",
},
allowlist: config.Allowlist{
MatchCondition: config.AllowlistMatchAnd,
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
Regexes: []*regexp.Regexp{regexp.MustCompile("password")},
},
expected: []report.Finding{
{
StartColumn: 50,
EndColumn: 60,
Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
Match: "Summer2024!",
Secret: "Summer2024!",
File: "package-lock.json",
Entropy: 3.095795154571533,
RuleID: "test-rule",
},
},
},
"commit OR path allowed": {
fragment: Fragment{
CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
FilePath: "package-lock.json",
},
allowlist: config.Allowlist{
MatchCondition: config.AllowlistMatchOr,
Commits: []string{"704178e7dca77ff143778a31cff0fc192d59b030"},
Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
},
},
// Regex / stopwords
"regex allowed": {
fragment: Fragment{},
allowlist: config.Allowlist{
Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
},
},
"stopwords allowed": {
fragment: Fragment{},
allowlist: config.Allowlist{
StopWords: []string{"summer"},
},
},
"regex AND stopword allowed": {
fragment: Fragment{},
allowlist: config.Allowlist{
MatchCondition: config.AllowlistMatchAnd,
Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
StopWords: []string{"2024"},
},
},
"regex AND stopword allowed - other conditions": {
fragment: Fragment{
CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
FilePath: "config.js",
},
allowlist: config.Allowlist{
MatchCondition: config.AllowlistMatchAnd,
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
Paths: []*regexp.Regexp{regexp.MustCompile(`config.js`)},
Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
StopWords: []string{"2024"},
},
},
"regex AND stopword NOT allowed - non-git, other conditions": {
fragment: Fragment{
FilePath: "config.js",
},
allowlist: config.Allowlist{
MatchCondition: config.AllowlistMatchAnd,
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
Paths: []*regexp.Regexp{regexp.MustCompile(`config.js`)},
Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
StopWords: []string{"2024"},
},
expected: []report.Finding{
{
StartColumn: 50,
EndColumn: 60,
Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
Match: "Summer2024!",
Secret: "Summer2024!",
File: "config.js",
Entropy: 3.095795154571533,
RuleID: "test-rule",
},
},
},
"regex AND stopword NOT allowed": {
fragment: Fragment{},
allowlist: config.Allowlist{
MatchCondition: config.AllowlistMatchAnd,
Regexes: []*regexp.Regexp{
regexp.MustCompile(`(?i)winter.+`),
},
StopWords: []string{"2024"},
},
expected: []report.Finding{
{
StartColumn: 50,
EndColumn: 60,
Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
Match: "Summer2024!",
Secret: "Summer2024!",
Entropy: 3.095795154571533,
RuleID: "test-rule",
},
},
},
"regex AND stopword NOT allowed - other conditions": {
fragment: Fragment{
CommitSHA: "a060c9d2d5e90c992763f1bd4c3cd2a6f121241b",
FilePath: "config.js",
},
allowlist: config.Allowlist{
MatchCondition: config.AllowlistMatchAnd,
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)winter.+`)},
StopWords: []string{"2024"},
},
expected: []report.Finding{
{
StartColumn: 50,
EndColumn: 60,
Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
Match: "Summer2024!",
Secret: "Summer2024!",
File: "config.js",
Entropy: 3.095795154571533,
RuleID: "test-rule",
},
},
},
"regex OR stopword allowed": {
fragment: Fragment{},
allowlist: config.Allowlist{
MatchCondition: config.AllowlistMatchOr,
Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
StopWords: []string{"winter"},
},
},
}
raw := `let username = 'james@mail.com';
let password = 'Summer2024!';`
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
rule := config.Rule{
RuleID: "test-rule",
Regex: regexp.MustCompile(`Summer2024!`),
Allowlists: []config.Allowlist{
tc.allowlist,
},
}
d, err := NewDetectorDefaultConfig()
require.NoError(t, err)
f := tc.fragment
f.Raw = raw
actual := d.detectRule(f, raw, rule, []EncodedSegment{})
if diff := cmp.Diff(tc.expected, actual); diff != "" {
t.Errorf("diff: (-want +got)\n%s", diff)
}
})
}
}
func moveDotGit(t *testing.T, from, to string) {
t.Helper()
+1
View File
@@ -50,6 +50,7 @@ func location(fragment Fragment, matchIndex []int) Location {
location.endColumn = (end - prevNewLine)
location.endLineIndex = newLineByteIndex
}
prevNewLine = pair[0]
}
+3
View File
@@ -162,6 +162,9 @@ func printFinding(f report.Finding, noColor bool) {
fmt.Println("")
return
}
if len(f.Tags) > 0 {
fmt.Printf("%-12s %s\n", "Tags:", f.Tags)
}
fmt.Printf("%-12s %s\n", "File:", f.File)
fmt.Printf("%-12s %d\n", "Line:", f.StartLine)
if f.Commit == "" {
+7 -3
View File
@@ -1,17 +1,21 @@
module github.com/zricethezav/gitleaks/v8
go 1.19
go 1.22.0
toolchain go1.22.5
require (
github.com/BobuSumisu/aho-corasick v1.0.3
github.com/charmbracelet/lipgloss v0.5.0
github.com/fatih/semgroup v1.2.0
github.com/gitleaks/go-gitdiff v0.9.0
github.com/gitleaks/go-gitdiff v0.9.1
github.com/google/go-cmp v0.6.0
github.com/h2non/filetype v1.1.3
github.com/rs/zerolog v1.26.1
github.com/spf13/cobra v1.2.1
github.com/spf13/viper v1.8.1
github.com/stretchr/testify v1.7.0
golang.org/x/exp v0.0.0-20240909161429-701f63a606c0
)
require (
@@ -39,7 +43,7 @@ require (
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/subosito/gotenv v1.2.0 // indirect
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
golang.org/x/sync v0.8.0 // indirect
golang.org/x/sys v0.6.0 // indirect
golang.org/x/text v0.3.8 // indirect
gopkg.in/ini.v1 v1.62.0 // indirect
+8 -3
View File
@@ -78,8 +78,8 @@ github.com/fatih/semgroup v1.2.0/go.mod h1:1KAD4iIYfXjE4U13B48VM4z9QUwV5Tt8O4rS8
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/gitleaks/go-gitdiff v0.9.0 h1:SHAU2l0ZBEo8g82EeFewhVy81sb7JCxW76oSPtR/Nqg=
github.com/gitleaks/go-gitdiff v0.9.0/go.mod h1:pKz0X4YzCKZs30BL+weqBIG7mx0jl4tF1uXV9ZyNvrA=
github.com/gitleaks/go-gitdiff v0.9.1 h1:ni6z6/3i9ODT685OLCTf+s/ERlWUNWQF4x1pvoNICw0=
github.com/gitleaks/go-gitdiff v0.9.1/go.mod h1:pKz0X4YzCKZs30BL+weqBIG7mx0jl4tF1uXV9ZyNvrA=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
@@ -127,6 +127,8 @@ github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=
@@ -307,6 +309,8 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0
golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM=
golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU=
golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 h1:e66Fs6Z+fZTbFBAxKfP3PALWBtpfqks2bwGcexMxgtk=
golang.org/x/exp v0.0.0-20240909161429-701f63a606c0/go.mod h1:2TbTHSBQa924w8M6Xs1QcRcFwyucIwBGpK1p2f1YFFY=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
@@ -391,8 +395,9 @@ golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+1 -1
View File
@@ -5,5 +5,5 @@ title = "simple config with allowlist for aws"
id = "aws-access-key"
regex = '''(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}'''
tags = ["key", "AWS"]
[rules.allowlist]
[[rules.allowlists]]
regexes = ['''AKIALALEMEL33243OLIA''']
+1 -1
View File
@@ -5,5 +5,5 @@ title = "simple config with allowlist for a specific commit"
id = "aws-access-key"
regex = '''(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}'''
tags = ["key", "AWS"]
[rules.allowlist]
[[rules.allowlists]]
commits = ['''allowthiscommit''']
+1 -1
View File
@@ -5,5 +5,5 @@ title = "simple config with allowlist for .go files"
id = "aws-access-key"
regex = '''(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}'''
tags = ["key", "AWS"]
[rules.allowlist]
[[rules.allowlists]]
paths = ['''.go''']
+6
View File
@@ -0,0 +1,6 @@
title = "simple config with allowlist for aws"
[[rules]]
id = "example"
regex = '''example\d+'''
[[rules.allowlists]]
+9
View File
@@ -0,0 +1,9 @@
title = "simple config with allowlist for aws"
[[rules]]
id = "example"
regex = '''example\d+'''
[rules.allowlist]
regexes = ['''123''']
[[rules.allowlists]]
regexes = ['''456''']
+8
View File
@@ -0,0 +1,8 @@
title = "simple config with allowlist for aws"
[[rules]]
id = "example"
regex = '''example\d+'''
[[rules.allowlists]]
regexTarget = "mtach"
regexes = ['''456''']
+7
View File
@@ -0,0 +1,7 @@
title = "simple config with allowlist for aws"
[[rules]]
id = "example"
regex = '''example\d+'''
[rules.allowlist]
regexes = ['''123''']
+75
View File
@@ -0,0 +1,75 @@
# We want to be able to find this key regardless if it's b64 encoded or not
[[rules]]
id = 'private-key'
description = 'Private Key'
regex = '''(?i)-----BEGIN[ A-Z0-9_-]{0,100}PRIVATE KEY(?: BLOCK)?-----[\s\S-]*?-----END[ A-Z0-9_-]{0,100}PRIVATE KEY(?: BLOCK)?-----'''
tags = ['key', 'private']
keywords = [
'-----begin',
]
# This exists to test what would happen if a normal rule matched something that
# also gets decoded. We don't want to break anyone's existing rules that might
# be looking for specific segments of b64 encoded data.
[[rules]]
id = 'b64-encoded-private-key'
description = 'Private Key'
regex = '''(?:LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0t|0tLS0tQkVHSU4gUFJJVkFURSBLRVktLS0tL|tLS0tLUJFR0lOIFBSSVZBVEUgS0VZLS0tLS)[a-zA-Z0-9+\/]+={0,3}'''
tags = ['key', 'private']
keywords = [
'ls0tls1crudjtibquklwqvrfietfws0tls0t',
'0tls0tqkvhsu4gufjjvkfursblrvktls0tl',
'tls0tlujfr0loifbssvzbveugs0vzls0tls',
]
[[rules]]
id = 'aws-iam-unique-identifier'
description = 'AWS IAM Unique Identifier'
# The funky not group at the beginning consists of ascii ranges
regex = '''(?:^|[^!$-&\(-9<>-~])((?:A3T[A-Z0-9]|ACCA|ABIA|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16})\b'''
tags = ['aws', 'identifier']
entropy = 3.2
secretGroup = 1
keywords = [
'a3t',
'abia',
'acca',
'agpa',
'aida',
'aipa',
'akia',
'anpa',
'anva',
'aroa',
'asia',
]
[[rules]]
id = 'aws-secret-access-key'
description = 'AWS Secret Access Key'
regex = '''(?i)aws[\w\-]{0,32}[\'\"]?\s*?[:=\(]\s*?[\'\"]?([a-z0-9\/+]{40})\b'''
tags = ['aws', 'secret']
entropy = 4
secretGroup = 1
keywords = [
'aws',
]
[[rules]]
# Use a small one for making sure things shifting around are kept up with
# appropriately
id = 'small-secret'
description = 'Small Secret'
regex = '''\bsmall-secret\b'''
tags = ['small', 'secret']
[[rules]]
# When the example value is decoded this will overlap and this is here to
# test that the location information is reported accurately when the match
# goes outside the bounds of the encoded value
id = 'overlapping'
description = 'Overlapping'
regex = '''secret=(decoded-secret-value)'''
tags = ['overlapping']
secretGroup = 1
+1 -1
View File
@@ -3,7 +3,7 @@ title = "gitleaks extended 3"
## This should not be loaded since we can only extend configs to a depth of 3
[[rules]]
description = "AWS Secret Key"
id = "aws-secret-key-again-again"
description = "AWS Secret Key"
regex = '''(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}'''
tags = ["key", "AWS"]
+8
View File
@@ -0,0 +1,8 @@
[extend]
path="../testdata/config/extend_3.toml"
[[rules]]
id = "aws-secret-key-again-again"
[[rules.allowlists]]
description = "False positive. Keys used for colors match the rule, and should be excluded."
paths = ['''something.py''']
+14
View File
@@ -0,0 +1,14 @@
title = "gitleaks extended 3"
[extend]
path="../testdata/config/extend_rule_allowlist_base.toml"
[[rules]]
id = "aws-secret-key-again-again"
[[rules.allowlists]]
condition = "AND"
commits = ['''abcdefg1''']
regexes = ['''foo.+bar''']
regexTarget = "line"
paths = ['''ignore\.xaml''']
stopwords = ['''example''']
+11
View File
@@ -0,0 +1,11 @@
title = "gitleaks extended 3"
## This should not be loaded since we can only extend configs to a depth of 3
[[rules]]
id = "aws-secret-key-again-again"
description = "AWS Secret Key"
regex = '''(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}'''
tags = ["key", "AWS"]
[[rules.allowlists]]
stopwords = ["fake"]
+13
View File
@@ -0,0 +1,13 @@
title = "gitleaks extended 3"
[extend]
path="../testdata/config/extend_rule_allowlist_base.toml"
[[rules]]
id = "aws-secret-key-again-again"
[[rules.allowlists]]
commits = ['''abcdefg1''']
regexes = ['''foo.+bar''']
regexTarget = "line"
paths = ['''ignore\.xaml''']
stopwords = ['''example''']
+5 -3
View File
@@ -3,6 +3,8 @@ title = "gitleaks config"
[[rules]]
description = "Generic API Key"
id = "generic-api-key"
regex = '''(?i)((key|api|token|secret|password)[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([0-9a-zA-Z\-_=]{8,64})['\"]'''
entropy = 3.7
secretGroup = 4
regex = '''(?i)(?:key|api|token|secret|client|passwd|password|auth|access)(?:[0-9a-z\-_\t .]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:{1,3}=|\|\|:|<=|=>|:|\?=)(?:'|\"|\s|=|\x60){0,5}([0-9a-z\-_.=]{10,150})(?:['|\"|\n|\r|\s|\x60|;]|$)'''
entropy = 3.5
keywords = [
"key","api","token","secret","client","passwd","password","auth","access",
]
+8
View File
@@ -0,0 +1,8 @@
title = "override a built-in rule's description"
[extend]
path = "../testdata/config/simple.toml"
[[rules]]
id = "aws-access-key"
description = "Puppy Doggy"
+8
View File
@@ -0,0 +1,8 @@
title = "override a built-in rule's entropy"
[extend]
path = "../testdata/config/simple.toml"
[[rules]]
id = "aws-access-key"
entropy = 999
+8
View File
@@ -0,0 +1,8 @@
title = "override a built-in rule's keywords"
[extend]
path = "../testdata/config/simple.toml"
[[rules]]
id = "aws-access-key"
keywords = ["puppy"]
+8
View File
@@ -0,0 +1,8 @@
title = "override a built-in rule's path"
[extend]
path = "../testdata/config/simple.toml"
[[rules]]
id = "aws-access-key"
path = '''(?:puppy)'''
+8
View File
@@ -0,0 +1,8 @@
title = "override a built-in rule's regex"
[extend]
path = "../testdata/config/simple.toml"
[[rules]]
id = "aws-access-key"
regex = '''(?:a)'''
+9
View File
@@ -0,0 +1,9 @@
title = "override a built-in rule's secretGroup"
[extend]
path = "../testdata/config/simple.toml"
[[rules]]
id = "aws-access-key"
regex = '''(?:a)(?:a)'''
secretGroup = 2
+8
View File
@@ -0,0 +1,8 @@
title = "override a built-in rule's tags"
[extend]
path = "../testdata/config/simple.toml"
[[rules]]
id = "aws-access-key"
tags = ["puppy"]
+6
View File
@@ -0,0 +1,6 @@
DB_HOST=example.com
DB_PORT=443
DB_USERNAME=postgres
DB_PASSWORD=8ae31cacf141669ddfb5da
DB_NAME=best_db
DB_SSL=true
+1
View File
@@ -1,2 +1,3 @@
api/ignoreGlobal.go:aws-access-key:20
# test comment
53cd7a3c6eb4937f413e3c25e4a9f39289afa69e:api/ignoreCommit.go:aws-access-key:20