Compare commits

...
Author SHA1 Message Date
ahrav a91c6717a0 replace std library regex engine with go-re2 (#1669) 2024-12-20 09:53:01 -06:00
David Mateo 906085fba6 Update golang version to 1.23 (#1672)
Because go mod 1.23 has been updated, the golang image needs it too
2024-12-20 08:38:11 -06:00
Zach d0ba52e2be bump go in dockerfile 2024-12-20 05:54:52 -06:00
Zachary Rice 8a8306288e log bytes (#1670) 2024-12-20 05:46:25 -06:00
Zach a9e6d8c9a7 go mod 1.23 2024-12-19 09:27:43 -06:00
Craig SmithandCraig Smith 2f73a3e3cf Ensure keywords are downcased (#1633)
* Ensure keywords are downcased

* Update tests

* Remove unnecessary code

* Add msg to test expectation

* Update the keywords as we iterate through them

* Remove unnecessary to lower

---------

Co-authored-by: Craig Smith <5344211-craigmsmith@users.noreply.gitlab.com>
2024-12-19 09:22:03 -06:00
Bert Coppens f6966057f5 feat: add settlemint api keys detection (#1663)
* feat: add settlemint api keys detection

* fix regex creation

* use GenerateUniqueTokenRegex

* trigger ci

* ensure tokens have min length of 12

* ensure to set minLength on settlemint token pattern

* set base entropy for settlemint detectors

* update settlemint token regexes to be more precise
2024-12-13 09:18:30 -06:00
Richard Gomez 0bf13fc25a feat(dir): better chunking (#1665) 2024-12-12 10:27:27 -06:00
Richard Gomez 83e99bacf1 feat(report): allow user-defined templates (#1650) 2024-12-10 18:56:11 -06:00
e393d299bc Add support for GitLab routable tokens (#1656)
* Add support for GitLab routable tokens #1655

This commit adds support for GitLabs routable tokens.

For the specification see:
https://handbook.gitlab.com/handbook/engineering/architecture/design-documents/cells/routable_tokens/#proposal

Issue: https://github.com/gitleaks/gitleaks/issues/1655

* Add support for GitLab routable tokens #1655

This commit adds increases the entropy.

For the specification see:
https://handbook.gitlab.com/handbook/engineering/architecture/design-documents/cells/routable_tokens/#proposal

Issue: https://github.com/gitleaks/gitleaks/issues/1655

* add word boundary to regex

Co-authored-by: Ben-grmbl <173737458+Ben-grmbl@users.noreply.github.com>

* chore: re-generate gitleaks.toml

Co-authored-by: Ben-grmbl <173737458+Ben-grmbl@users.noreply.github.com>

---------

Co-authored-by: Nicholas Wittstruck <1283061+nwittstruck@users.noreply.github.com>
Co-authored-by: Ben-grmbl <173737458+Ben-grmbl@users.noreply.github.com>
2024-12-06 07:41:41 -06:00
naveen 263ce82365 Add freemius secret key detection (#1611) 2024-12-05 10:37:53 -06:00
Richard Gomez 3c0e068b69 fix(kubernetes): only match 'kind: secret' (#1649) 2024-12-05 10:22:34 -06:00
Bryce Thuilot f3adda07ca feat: use STDOUT when report file not specified (#1642)
* feat: use STDOUT when report file not specified

Signed-off-by: Bryce Thuilot <bryce@thuilot.io>

* fix: update tests

Signed-off-by: Bryce Thuilot <bryce@thuilot.io>

* fix: use only '-' for stdout report

Signed-off-by: Bryce Thuilot <bryce@thuilot.io>

---------

Signed-off-by: Bryce Thuilot <bryce@thuilot.io>
2024-12-05 09:44:07 -06:00
Richard Gomez ed205a5f63 fix(dir): skip opening file&dir if allowlist matches (#1653) 2024-12-05 08:35:42 -06:00
Richard Gomez 6018012b7e fix: increase chunk size 10kb -> 100kb (#1652) 2024-12-01 19:42:40 -06:00
85 changed files with 1168 additions and 692 deletions

No files matched your search

+1 -1
View File
@@ -1,4 +1,4 @@
FROM golang:1.22 AS build
FROM golang:1.23 AS build
WORKDIR /go/src/github.com/zricethezav/gitleaks
COPY . .
RUN VERSION=$(git describe --tags --abbrev=0) && \
+43 -1
View File
@@ -162,8 +162,9 @@ Flags:
--no-banner suppress banner
--no-color turn off color for verbose output
--redact uint[=100] redact secrets from logs and stdout. To redact only parts of the secret just apply a percent value from 0..100. For example --redact=20 (default 100%)
-f, --report-format string output format (json, jsonextra, csv, junit, sarif) (default "json")
-f, --report-format string output format (json, csv, junit, sarif) (default "json")
-r, --report-path string report file
--report-template string template file used to generate the report (implies --report-format=template)
-v, --verbose show verbose output from scan
--version version for gitleaks
@@ -393,6 +394,47 @@ Currently supported encodings:
- `base64` (both standard and base64url)
#### Reporting
Gitleaks has built-in support for several report formats: [`json`](https://github.com/gitleaks/gitleaks/blob/master/testdata/expected/report/json_simple.json), [`csv`](https://github.com/gitleaks/gitleaks/blob/master/testdata/expected/report/csv_simple.csv?plain=1), [`junit`](https://github.com/gitleaks/gitleaks/blob/master/testdata/expected/report/junit_simple.xml), and [`sarif`](https://github.com/gitleaks/gitleaks/blob/master/testdata/expected/report/sarif_simple.sarif).
If none of these formats fit your need, you can create your own report format with a [Go `text/template` .tmpl file](https://www.digitalocean.com/community/tutorials/how-to-use-templates-in-go#step-4-writing-a-template) and the `--report-template` flag. The template can use [extended functionality from the `Masterminds/sprig` template library](https://masterminds.github.io/sprig/).
For example, the following template provides a custom JSON output:
```gotemplate
# jsonextra.tmpl
[{{ $lastFinding := (sub (len . ) 1) }}
{{- range $i, $finding := . }}{{with $finding}}
{
"Description": {{ quote .Description }},
"StartLine": {{ .StartLine }},
"EndLine": {{ .EndLine }},
"StartColumn": {{ .StartColumn }},
"EndColumn": {{ .EndColumn }},
"Line": {{ quote .Line }},
"Match": {{ quote .Match }},
"Secret": {{ quote .Secret }},
"File": "{{ .File }}",
"SymlinkFile": {{ quote .SymlinkFile }},
"Commit": {{ quote .Commit }},
"Entropy": {{ .Entropy }},
"Author": {{ quote .Author }},
"Email": {{ quote .Email }},
"Date": {{ quote .Date }},
"Message": {{ quote .Message }},
"Tags": [{{ $lastTag := (sub (len .Tags ) 1) }}{{ range $j, $tag := .Tags }}{{ quote . }}{{ if ne $j $lastTag }},{{ end }}{{ end }}],
"RuleID": {{ quote .RuleID }},
"Fingerprint": {{ quote .Fingerprint }}
}{{ if ne $i $lastFinding }},{{ end }}
{{- end}}{{ end }}
]
```
Usage:
```sh
$ gitleaks dir ~/leaky-repo/ --report-path "report.json" --report-format template --report-template testdata/report/jsonextra.tmpl
```
## Sponsorships
<p align="left">
+11 -7
View File
@@ -62,6 +62,10 @@ func runDetect(cmd *cobra.Command, args []string) {
detector := Detector(cmd, cfg, source)
// set follow symlinks flag
if detector.FollowSymlinks, err = cmd.Flags().GetBool("follow-symlinks"); err != nil {
log.Fatal().Err(err).Msg("")
}
// set exit code
exitCode, err := cmd.Flags().GetInt("exit-code")
if err != nil {
@@ -83,7 +87,12 @@ func runDetect(cmd *cobra.Command, args []string) {
// start the detector scan
if noGit {
var paths <-chan sources.ScanTarget
paths, err = sources.DirectoryTargets(source, detector.Sema, detector.FollowSymlinks)
paths, err = sources.DirectoryTargets(
source,
detector.Sema,
detector.FollowSymlinks,
detector.Config.Allowlist.PathAllowed,
)
if err != nil {
log.Fatal().Err(err)
}
@@ -120,10 +129,5 @@ func runDetect(cmd *cobra.Command, args []string) {
}
}
// set follow symlinks flag
if detector.FollowSymlinks, err = cmd.Flags().GetBool("follow-symlinks"); err != nil {
log.Fatal().Err(err).Msg("")
}
findingSummaryAndExit(findings, cmd, cfg, exitCode, start, err)
findingSummaryAndExit(detector, findings, exitCode, start, err)
}
+11 -2
View File
@@ -45,6 +45,10 @@ func runDirectory(cmd *cobra.Command, args []string) {
detector := Detector(cmd, cfg, source)
// set follow symlinks flag
if detector.FollowSymlinks, err = cmd.Flags().GetBool("follow-symlinks"); err != nil {
log.Fatal().Err(err).Msg("")
}
// set exit code
exitCode, err := cmd.Flags().GetInt("exit-code")
if err != nil {
@@ -52,7 +56,12 @@ func runDirectory(cmd *cobra.Command, args []string) {
}
var paths <-chan sources.ScanTarget
paths, err = sources.DirectoryTargets(source, detector.Sema, detector.FollowSymlinks)
paths, err = sources.DirectoryTargets(
source,
detector.Sema,
detector.FollowSymlinks,
detector.Config.Allowlist.PathAllowed,
)
if err != nil {
log.Fatal().Err(err)
}
@@ -63,5 +72,5 @@ func runDirectory(cmd *cobra.Command, args []string) {
log.Error().Err(err).Msg("failed scan directory")
}
findingSummaryAndExit(findings, cmd, cfg, exitCode, start, err)
findingSummaryAndExit(detector, findings, exitCode, start, err)
}
+12 -14
View File
@@ -2,9 +2,10 @@ package base
import (
"fmt"
"github.com/zricethezav/gitleaks/v8/config"
"regexp"
"strings"
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/config"
)
func CreateGlobalConfig() config.Config {
@@ -64,7 +65,7 @@ func CreateGlobalConfig() config.Config {
// ----------- 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)/.*$`),
regexp.MustCompile(`(^|/)vendor/(github\.com|golang\.org/x|google\.golang\.org|gopkg\.in|istio\.io|k8s\.io|sigs\.k8s\.io)(/.*)?$`),
// ----------- Java files -----------
// Gradle
@@ -75,12 +76,9 @@ func CreateGlobalConfig() config.Config {
// ----------- JavaScript 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/.*?$`),
regexp.MustCompile(`(^|/)node_modules(/.*)?$`),
regexp.MustCompile(`(^|/)(npm-shrinkwrap\.json|package-lock\.json|pnpm-lock\.yaml|yarn\.lock)$`),
regexp.MustCompile(`(^|/)bower_components(/.*)?$`),
// TODO: Add more common static assets, such as swagger-ui.
regexp.MustCompile(`(^|/)(angular|jquery(-?ui)?|plotly|swagger-?ui)[a-zA-Z0-9.-]*(\.min)?\.js(\.map)?$`),
@@ -88,17 +86,17 @@ func CreateGlobalConfig() config.Config {
// Dependencies and lock files.
regexp.MustCompile(`(^|/)(Pipfile|poetry)\.lock$`),
// Virtual environments
regexp.MustCompile(`(?i)/?(v?env|virtualenv)/lib(64)?/.+$`),
regexp.MustCompile(`(?i)(^|/)(lib(64)?/python[23](\.\d{1,2})+/|python/[23](\.\d{1,2})+/lib(64)?/).+$`),
regexp.MustCompile(`(?i)/?(v?env|virtualenv)/lib(64)?(/.*)?$`),
regexp.MustCompile(`(?i)(^|/)(lib(64)?/python[23](\.\d{1,2})+|python/[23](\.\d{1,2})+/lib(64)?)(/.*)?$`),
// dist-info directory (https://py-pkgs.org/04-package-structure.html#building-sdists-and-wheels)
regexp.MustCompile(`(?i)(^|/)[a-z0-9_.]+-[0-9.]+\.dist-info/.+$`),
regexp.MustCompile(`(?i)(^|/)[a-z0-9_.]+-[0-9.]+\.dist-info(/.+)?$`),
// ----------- Ruby files -----------
regexp.MustCompile(`(^|/)vendor/(bundle|ruby)/.*?$`),
regexp.MustCompile(`(^|/)vendor/(bundle|ruby)(/.*?)?$`),
regexp.MustCompile(`\.gem$`), // tar archive
// Misc
regexp.MustCompile(`verification-metadata.xml`),
regexp.MustCompile(`verification-metadata\.xml`),
regexp.MustCompile(`Database.refactorlog`),
//regexp.MustCompile(`vendor`),
},
+6 -2
View File
@@ -4,10 +4,9 @@ import (
"os"
"text/template"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/base"
"github.com/rs/zerolog/log"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/base"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/rules"
"github.com/zricethezav/gitleaks/v8/config"
)
@@ -90,6 +89,7 @@ func main() {
rules.FlutterwaveEncKey(),
rules.FlyIOAccessToken(),
rules.FrameIO(),
rules.Freemius(),
rules.FreshbooksAccessToken(),
rules.GoCardless(),
// TODO figure out what makes sense for GCP
@@ -108,6 +108,7 @@ func main() {
rules.GitlabKubernetesAgentToken(),
rules.GitlabOauthAppSecret(),
rules.GitlabPat(),
rules.GitlabPatRoutable(),
rules.GitlabPipelineTriggerToken(),
rules.GitlabRunnerRegistrationToken(),
rules.GitlabRunnerAuthenticationToken(),
@@ -184,6 +185,9 @@ func main() {
rules.SentryAccessToken(),
rules.SentryOrgToken(),
rules.SentryUserToken(),
rules.SettlemintApplicationAccessToken(),
rules.SettlemintPersonalAccessToken(),
rules.SettlemintServiceAccessToken(),
rules.ShippoAPIToken(),
rules.ShopifyAccessToken(),
rules.ShopifyCustomAccessToken(),
+2 -1
View File
@@ -1,10 +1,11 @@
package rules
import (
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
"regexp"
)
// https://developer.1password.com/docs/service-accounts/security/?token-example=encoded
+2 -2
View File
@@ -1,9 +1,9 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/config"
)
+1 -1
View File
@@ -2,8 +2,8 @@ package rules
import (
"fmt"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
+2 -2
View File
@@ -1,10 +1,10 @@
package rules
import (
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
)
+4 -2
View File
@@ -2,11 +2,13 @@ package rules
import (
"fmt"
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
// References:
+3 -2
View File
@@ -1,11 +1,12 @@
package rules
import (
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Clojars() *config.Rule {
+2 -2
View File
@@ -2,9 +2,9 @@ package rules
import (
"fmt"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/config"
)
+3 -2
View File
@@ -1,11 +1,12 @@
package rules
import (
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Doppler() *config.Rule {
+3 -2
View File
@@ -1,11 +1,12 @@
package rules
import (
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Duffel() *config.Rule {
+3 -2
View File
@@ -1,11 +1,12 @@
package rules
import (
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Dynatrace() *config.Rule {
+3 -2
View File
@@ -1,11 +1,12 @@
package rules
import (
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func EasyPost() *config.Rule {
+1
View File
@@ -2,6 +2,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"
+3 -2
View File
@@ -1,11 +1,12 @@
package rules
import (
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func FlutterwavePublicKey() *config.Rule {
+3 -2
View File
@@ -1,11 +1,12 @@
package rules
import (
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func FrameIO() *config.Rule {
+48
View File
@@ -0,0 +1,48 @@
package rules
import (
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/config"
)
func Freemius() *config.Rule {
// define rule
r := config.Rule{
RuleID: "freemius-secret-key",
Description: "Detected a Freemius secret key, potentially exposing sensitive information.",
Regex: regexp.MustCompile(`(?i)["']secret_key["']\s*=>\s*["'](sk_[\S]{29})["']`),
Keywords: []string{"secret_key"},
Path: regexp.MustCompile(`(?i)\.php$`),
}
// validate
tps := map[string]string{
"file.php": `$config = array(
"secret_key" => "sk_ubb4yN3mzqGR2x8#P7r5&@*xC$utE",
);`,
}
// It's only used in PHP SDK snippet.
// see https://freemius.com/help/documentation/wordpress-sdk/integrating-freemius-sdk/
fps := map[string]string{
// Invalid format: missing quotes around `secret_key`.
"foo.php": `$config = array(
secret_key => "sk_abcdefghijklmnopqrstuvwxyz123",
);`,
// Invalid format: missing quotes around the key value.
"bar.php": `$config = array(
"secret_key" => sk_abcdefghijklmnopqrstuvwxyz123,
);`,
// Invalid: different key name.
"baz.php": `$config = array(
"other_key" => "sk_abcdefghijklmnopqrstuvwxyz123",
);`,
// Invalid: file extension, should validate only .php files.
"foo.html": `$config = array(
"secret_key" => "sk_ubb4yN3mzqGR2x8#P7r5&@*xC$utE",
);`,
}
return utils.ValidateWithPaths(r, tps, fps)
}
+3 -2
View File
@@ -1,11 +1,12 @@
package rules
import (
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
// TODO this one could probably use some work
+9 -8
View File
@@ -1,10 +1,11 @@
package rules
import (
regexp "github.com/wasilibs/go-re2"
"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 GenericCredential() *config.Rule {
@@ -126,7 +127,7 @@ func GenericCredential() *config.Rule {
`[DEBUG] org.neo4j.neo4j-graphdb-api:jar:3.5.12:test`,
`apiUrl=apigee.corpint.com`,
// TODO: Jetbrains IML files (requires line-level allowlist).
//`<orderEntry type="library" scope="PROVIDED" name="Maven: org.apache.directory.api:api-asn1-api:1.0.0-M20" level="projcet" />`
// `<orderEntry type="library" scope="PROVIDED" name="Maven: org.apache.directory.api:api-asn1-api:1.0.0-M20" level="projcet" />`
// Auth
`author = "james.fake@ymail.com",`,
@@ -155,9 +156,9 @@ func GenericCredential() *config.Rule {
`minisat-master-keying:x64-uwp=fail`,
`IceSSL.KeyFile=s_rsa1024_priv.pem`,
`"bucket_key": "SalesResults-1.2"`,
//`<TAR key="REF_ID_923.properties" value="/opts/config/alias/"/>`,
// `<TAR key="REF_ID_923.properties" value="/opts/config/alias/"/>`,
`<key tag="SecurityIdentifier" name="SecurityIdentifier" type="STRING" />`,
//`packageKey":` + newPlausibleSecret(`[a-zA-Z0-9\-_.=]{30}`),
// `packageKey":` + newPlausibleSecret(`[a-zA-Z0-9\-_.=]{30}`),
`schemaKey = 'DOC_Vector_5_32'`,
`sequenceKey = "18"`,
`app.keystore.file=env/cert.p12`,
@@ -165,15 +166,15 @@ func GenericCredential() *config.Rule {
` doc.Security.KeySize = PdfEncryptionKeySize.Key128Bit;`,
`o.keySelector=n,o.haKey=!1,`,
// TODO: Requires line-level allowlists.
//`<add key="SchemaTable" value="G:\SchemaTable.xml" />`,
// `<add key="SchemaTable" value="G:\SchemaTable.xml" />`,
// `secret:
//secretName: app-decryption-secret
//items:
// secretName: app-decryption-secret
// items:
// - key: app-k8s.yml
// path: app-k8s.yml`,
// TODO: https://learn.microsoft.com/en-us/windows/apps/design/style/xaml-theme-resources
//`<Color x:Key="NormalBrushGradient1">#FFBAE4FF</Color>`,
// `<Color x:Key="NormalBrushGradient1">#FFBAE4FF</Color>`,
// Password
`password combination.
+3 -2
View File
@@ -1,11 +1,12 @@
package rules
import (
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
var githubAllowlist = []config.Allowlist{
+19 -2
View File
@@ -1,12 +1,12 @@
package rules
import (
"regexp"
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
// overview with all GitLab tokens:
@@ -115,6 +115,23 @@ func GitlabPat() *config.Rule {
return utils.Validate(r, tps, fps)
}
func GitlabPatRoutable() *config.Rule {
r := config.Rule{
RuleID: "gitlab-pat-routable",
Description: "Identified a GitLab Personal Access Token (routable), risking unauthorized access to GitLab repositories and codebase exposure.",
Regex: regexp.MustCompile(`\bglpat-[0-9a-zA-Z_-]{27,300}\.[0-9a-z]{2}[0-9a-z]{7}\b`),
Entropy: 4,
Keywords: []string{"glpat-"},
}
// validate
tps := utils.GenerateSampleSecrets("gitlab", "glpat-"+secrets.NewSecret(utils.AlphaNumeric("27"))+"."+secrets.NewSecret(utils.AlphaNumeric("2"))+secrets.NewSecret(utils.AlphaNumeric("7")))
fps := []string{
"glpat-xxxxxxxx-xxxxxxxxxxxxxxxxxx.xxxxxxxxx",
}
return utils.Validate(r, tps, fps)
}
func GitlabPipelineTriggerToken() *config.Rule {
r := config.Rule{
RuleID: "gitlab-ptt",
+3 -2
View File
@@ -1,12 +1,13 @@
package rules
import (
"regexp"
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func HarnessApiKey() *config.Rule {
+4 -2
View File
@@ -2,11 +2,13 @@ package rules
import (
"fmt"
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func HashiCorpTerraform() *config.Rule {
+3 -2
View File
@@ -1,11 +1,12 @@
package rules
import (
"regexp"
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func VaultServiceToken() *config.Rule {
+1 -1
View File
@@ -2,8 +2,8 @@ package rules
import (
"fmt"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
+2 -2
View File
@@ -3,10 +3,10 @@ package rules
import (
b64 "encoding/base64"
"fmt"
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
)
+45 -3
View File
@@ -2,17 +2,19 @@ package rules
import (
"fmt"
"regexp"
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/config"
)
// 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["']?`
kindPat := `\bkind:[ \t]*["']?\bsecret\b["']?`
// Only matches values (`key: value`) under `data:` that are:
// - valid base64 characters
// - longer than 10 characters (no "YmFyCg==")
@@ -39,6 +41,9 @@ func KubernetesSecret() *config.Rule {
// variable: ""
// variable: ''
regexp.MustCompile(`[\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:\{\{[ \t\w"|$:=,.-]+}}|""|'')`),
// TODO: Requires multiple allowlists to target match.
// Avoid overreach between directives.
// regexp.MustCompile(`(kind:(.|\s)+\n---\n(.|\s)+\bdata:|data:(.|\s)+\n---\n(.|\s)+\bkind:)`),
},
},
},
@@ -239,6 +244,43 @@ metadata:
name: kubernetes-dashboard-key-holder
namespace: kubernetes-dashboard
type: Opaque
`,
// TODO: Requires multiple allowlists.
// "overly-permissive3.yaml": ` kind: Secret
// target:
// name: mysecret
// creationPolicy: Owner
//
// ---
//
// kind: ConfigMap
// data:
// conversionStrategy: Default
// decodingStrategy: None
// key: secret/mysecret
// property: foo
// secretKey: foo`,
// https://github.com/gitleaks/gitleaks/issues/1644
"wrong-kind.yaml": `apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
name: example
namespace: example-ns
spec:
refreshInterval: 15s
secretStoreRef:
name: example
kind: SecretStore
target:
name: mysecret
creationPolicy: Owner
data:
- remoteRef:
conversionStrategy: Default
decodingStrategy: None
key: secret/mysecret
property: foo
secretKey: foo
`,
"sopssecret.yaml": `apiVersion: isindir.github.com/v1alpha3
kind: SopsSecret
+3 -2
View File
@@ -1,11 +1,12 @@
package rules
import (
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func LinearAPIToken() *config.Rule {
+3 -3
View File
@@ -1,11 +1,11 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
)
func NugetConfigPassword() *config.Rule {
+3 -2
View File
@@ -1,11 +1,12 @@
package rules
import (
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
// OpenShift 4 user tokens are prefixed with `sha256~`.
+1 -1
View File
@@ -2,8 +2,8 @@ package rules
import (
"fmt"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
+2 -2
View File
@@ -1,9 +1,9 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/config"
)
+3 -2
View File
@@ -1,11 +1,12 @@
package rules
import (
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func PyPiUploadToken() *config.Rule {
+2 -1
View File
@@ -2,10 +2,11 @@ package rules
import (
"encoding/base64"
regexp "github.com/wasilibs/go-re2"
"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 SentryAccessToken() *config.Rule {
+70
View File
@@ -0,0 +1,70 @@
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 SettlemintPersonalAccessToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Found a Settlemint Personal Access Token.",
RuleID: "settlemint-personal-access-token",
Regex: utils.GenerateUniqueTokenRegex(`sm_pat_[a-zA-Z0-9]{16}`, false),
Entropy: 3,
Keywords: []string{
"sm_pat",
},
}
// validate
tps := utils.GenerateSampleSecrets("settlemintToken", "sm_pat_"+secrets.NewSecret(utils.AlphaNumeric("16")))
fps := []string{
"nonMatchingToken := \"" + secrets.NewSecret(utils.AlphaNumeric("16")) + "\"",
"nonMatchingToken := \"sm_pat_" + secrets.NewSecret(utils.AlphaNumeric("10")) + "\"",
}
return utils.Validate(r, tps, fps)
}
func SettlemintApplicationAccessToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Found a Settlemint Application Access Token.",
RuleID: "settlemint-application-access-token",
Regex: utils.GenerateUniqueTokenRegex(`sm_aat_[a-zA-Z0-9]{16}`, false),
Entropy: 3,
Keywords: []string{
"sm_aat",
},
}
// validate
tps := utils.GenerateSampleSecrets("settlemintToken", "sm_aat_"+secrets.NewSecret(utils.AlphaNumeric("16")))
fps := []string{
"nonMatchingToken := \"" + secrets.NewSecret(utils.AlphaNumeric("16")) + "\"",
"nonMatchingToken := \"sm_aat_" + secrets.NewSecret(utils.AlphaNumeric("10")) + "\"",
}
return utils.Validate(r, tps, fps)
}
func SettlemintServiceAccessToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Found a Settlemint Service Access Token.",
RuleID: "settlemint-service-access-token",
Regex: utils.GenerateUniqueTokenRegex(`sm_sat_[a-zA-Z0-9]{16}`, false),
Entropy: 3,
Keywords: []string{
"sm_sat",
},
}
// validate
tps := utils.GenerateSampleSecrets("settlemintToken", "sm_sat_"+secrets.NewSecret(utils.AlphaNumeric("16")))
fps := []string{
"nonMatchingToken := \"" + secrets.NewSecret(utils.AlphaNumeric("16")) + "\"",
"nonMatchingToken := \"sm_sat_" + secrets.NewSecret(utils.AlphaNumeric("10")) + "\"",
}
return utils.Validate(r, tps, fps)
}
+3 -2
View File
@@ -1,11 +1,12 @@
package rules
import (
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func ShopifySharedSecret() *config.Rule {
+2 -2
View File
@@ -1,10 +1,10 @@
package rules
import (
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
)
+3 -2
View File
@@ -2,11 +2,12 @@ package rules
import (
"fmt"
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
// https://api.slack.com/authentication/token-types#bot
+3 -2
View File
@@ -1,11 +1,12 @@
package rules
import (
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func TeamsWebhook() *config.Rule {
+3 -2
View File
@@ -1,11 +1,12 @@
package rules
import (
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Twilio() *config.Rule {
+25 -24
View File
@@ -6,8 +6,9 @@ package utils
import (
"fmt"
"regexp"
"strings"
regexp "github.com/wasilibs/go-re2"
)
const (
@@ -92,20 +93,20 @@ func GenerateSampleSecrets(identifier string, secret string) []string {
"ini - unquoted2": "{i}Token = {s}",
// JSON
"json - string": "{\n \"{i}_token\": \"{s}\"\n}",
//TODO: "json - escaped string": "\\{\n \\\"{i}_token\\\": \\\"{s}\\\"\n\\}",
//TODO: "json - string key/value": "{\n \"name\": \"{i}_token\",\n \"value\": \"{s}\"\n}",
// TODO: "json - escaped string": "\\{\n \\\"{i}_token\\\": \\\"{s}\\\"\n\\}",
// TODO: "json - string key/value": "{\n \"name\": \"{i}_token\",\n \"value\": \"{s}\"\n}",
// XML
//TODO: "xml - element": "<{i}Token>{s}</{i}Token>",
// TODO: "xml - element": "<{i}Token>{s}</{i}Token>",
"xml - element multiline": "<{i}Token>\n {s}\n</{i}Token>",
//TODO: "xml - attribute": "<entry name=\"{i}Token\" value=\"{s}\" />",
//TODO: "xml - key/value elements": "<entry>\n <name=\"{i}Token\" />\n <value=\"{s}\" />\n</entry>",
// TODO: "xml - attribute": "<entry name=\"{i}Token\" value=\"{s}\" />",
// TODO: "xml - key/value elements": "<entry>\n <name=\"{i}Token\" />\n <value=\"{s}\" />\n</entry>",
// YAML
"yaml - singleline - unquoted": "{i}_token: {s}",
"yaml - singleline - single quote": "{i}_token: '{s}'",
"yaml - singleline - double quote": "{i}_token: \"{s}\"",
//TODO: "yaml - multiline - literal": "{i}_token: |\n {s}",
//TODO: "yaml - multiline - folding": "{i}_token: >\n {s}",
//"": "",
// TODO: "yaml - multiline - literal": "{i}_token: |\n {s}",
// TODO: "yaml - multiline - folding": "{i}_token: >\n {s}",
// "": "",
// Programming Languages
"C#": `string {i}Token = "{s}";`,
@@ -113,26 +114,26 @@ func GenerateSampleSecrets(identifier string, secret string) []string {
"go - short": `{i}Token := "{s}"`,
"go - backticks": "{i}Token := `{s}`",
"java": "String {i}Token = \"{s}\";",
//TODO: "java - escaped quotes": `config.put("sasl.jaas.config", "org.apache.kafka.common.security.plain.PlainLoginModule required username=\"JDOE35\" {i}Token=\"{s}\""`,
//TODO:"kotlin - type": "var {i}Token: string = \"{s}\"",
// TODO: "java - escaped quotes": `config.put("sasl.jaas.config", "org.apache.kafka.common.security.plain.PlainLoginModule required username=\"JDOE35\" {i}Token=\"{s}\""`,
// TODO:"kotlin - type": "var {i}Token: string = \"{s}\"",
"kotlin - notype": "var {i}Token = \"{s}\"",
"php - string concat": `${i}Token .= "{s}"`,
//TODO: "php - null coalesce": `${i}Token ??= "{s}"`,
// TODO: "php - null coalesce": `${i}Token ??= "{s}"`,
"python - single quote": "{i}Token = '{s}'",
"python - double quote": `{i}Token = "{s}"`,
//"": "",
// "": "",
// Miscellaneous
//TODO: "url - basic auth": `https://{i}:{s}@example.com/`,
//TODO: "url - query parameter": "https://example.com?{i}Token={s}&fooBar=baz",
//TODO: "comment - slash": "//{s} is the password",
//TODO: "comment - slash multiline": "/*{s} is the password",
//TODO: "comment - hashtag": "#{s} is the password",
//TODO: "comment - semicolon": ";{s} is the password",
//TODO: "csv - unquoted": `{i}Token,{s},`,
// TODO: "url - basic auth": `https://{i}:{s}@example.com/`,
// TODO: "url - query parameter": "https://example.com?{i}Token={s}&fooBar=baz",
// TODO: "comment - slash": "//{s} is the password",
// TODO: "comment - slash multiline": "/*{s} is the password",
// TODO: "comment - hashtag": "#{s} is the password",
// TODO: "comment - semicolon": ";{s} is the password",
// TODO: "csv - unquoted": `{i}Token,{s},`,
"logstash": " \"{i}Token\" => \"{s}\"",
//TODO: "sql - tabular": "|{s}|",
//TODO: "sql": "",
// TODO: "sql - tabular": "|{s}|",
// TODO: "sql": "",
// Makefile
// See: https://github.com/gitleaks/gitleaks/pull/1191
@@ -141,9 +142,9 @@ func GenerateSampleSecrets(identifier string, secret string) []string {
"make - shell assignment": "{i}_TOKEN ::= \"{s}\"",
"make - evaluated shell assignment": "{i}_TOKEN :::= \"{s}\"",
"make - conditional assignment": "{i}_TOKEN ?= \"{s}\"",
//TODO: "make - append": "{i}_TOKEN += \"{s}\"",
// TODO: "make - append": "{i}_TOKEN += \"{s}\"",
//"": "",
// "": "",
}
replacer := strings.NewReplacer("{i}", identifier, "{s}", secret)
+3 -1
View File
@@ -5,11 +5,13 @@
package utils
import (
"strings"
"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(rule config.Rule, truePositives []string, falsePositives []string) *config.Rule {
+1 -1
View File
@@ -93,5 +93,5 @@ func runGit(cmd *cobra.Command, args []string) {
log.Error().Err(err).Msg("failed to scan Git repository")
}
findingSummaryAndExit(findings, cmd, cfg, exitCode, start, err)
findingSummaryAndExit(detector, findings, exitCode, start, err)
}
+1 -1
View File
@@ -47,5 +47,5 @@ func runProtect(cmd *cobra.Command, args []string) {
}
findings, err = detector.DetectGit(gitCmd)
findingSummaryAndExit(findings, cmd, cfg, exitCode, start, err)
findingSummaryAndExit(detector, findings, exitCode, start, err)
}
+128 -11
View File
@@ -2,9 +2,11 @@ package cmd
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync/atomic"
"time"
"github.com/rs/zerolog"
@@ -39,12 +41,20 @@ var rootCmd = &cobra.Command{
Version: Version,
}
const (
BYTE = 1.0
KILOBYTE = BYTE * 1000
MEGABYTE = KILOBYTE * 1000
GIGABYTE = MEGABYTE * 1000
)
func init() {
cobra.OnInitialize(initLog)
rootCmd.PersistentFlags().StringP("config", "c", "", configDescription)
rootCmd.PersistentFlags().Int("exit-code", 1, "exit code when leaks have been encountered")
rootCmd.PersistentFlags().StringP("report-path", "r", "", "report file")
rootCmd.PersistentFlags().StringP("report-format", "f", "json", "output format (json, jsonextra, csv, junit, sarif)")
rootCmd.PersistentFlags().StringP("report-format", "f", "json", "output format (json, jsonextra, csv, junit, sarif, template)")
rootCmd.PersistentFlags().StringP("report-template", "", "", "template file used to generate the report (implies --report-format=template)")
rootCmd.PersistentFlags().StringP("baseline-path", "b", "", "path to baseline with issues that can be ignored")
rootCmd.PersistentFlags().StringP("log-level", "l", "info", "log level (trace, debug, info, warn, error, fatal)")
rootCmd.PersistentFlags().BoolP("verbose", "v", false, "show verbose output from scan")
@@ -57,6 +67,7 @@ func init() {
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())
@@ -95,6 +106,7 @@ func initConfig(source string) {
if !hideBanner {
_, _ = fmt.Fprint(os.Stderr, banner)
}
cfgPath, err := rootCmd.Flags().GetString("config")
if err != nil {
log.Fatal().Msg(err.Error())
@@ -251,8 +263,8 @@ func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Dete
log.Info().Msg("Overriding enabled rules: " + strings.Join(rules, ", "))
ruleOverride := make(map[string]config.Rule)
for _, ruleName := range rules {
if rule, ok := cfg.Rules[ruleName]; ok {
ruleOverride[ruleName] = rule
if r, ok := cfg.Rules[ruleName]; ok {
ruleOverride[ruleName] = r
} else {
log.Fatal().Msgf("Requested rule %s not found in rules", ruleName)
}
@@ -260,18 +272,103 @@ func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Dete
detector.Config.Rules = ruleOverride
}
// Validate report settings.
reportPath := mustGetStringFlag("report-path")
if reportPath != "" {
if reportPath != report.StdoutReportPath {
// Ensure the path is writable.
if f, err := os.Create(reportPath); err != nil {
log.Fatal().Err(err).Msgf("Report path is not writable: %s", reportPath)
} else {
_ = f.Close()
_ = os.Remove(reportPath)
}
}
// Build report writer.
var (
reporter report.Reporter
reportFormat = mustGetStringFlag("report-format")
reportTemplate = mustGetStringFlag("report-template")
)
switch strings.TrimSpace(strings.ToLower(reportFormat)) {
case "csv":
reporter = &report.CsvReporter{}
case "json":
reporter = &report.JsonReporter{}
case "junit":
reporter = &report.JunitReporter{}
case "sarif":
reporter = &report.SarifReporter{
OrderedRules: cfg.GetOrderedRules(),
}
case "template":
if reporter, err = report.NewTemplateReporter(reportTemplate); err != nil {
log.Fatal().Err(err).Msg("Invalid report template")
}
default:
log.Fatal().Msgf("unknown report format %s", reportFormat)
}
// Sanity check.
if reportTemplate != "" && reportFormat != "template" {
log.Fatal().Msgf("Report format must be 'template' if --report-template is specified")
}
detector.ReportPath = reportPath
detector.Reporter = reporter
}
return detector
}
func findingSummaryAndExit(findings []report.Finding, cmd *cobra.Command, cfg config.Config, exitCode int, start time.Time, err error) {
func mustGetStringFlag(name string) string {
reportPath, err := rootCmd.Flags().GetString(name)
if err != nil {
log.Fatal().Msg(err.Error())
}
return reportPath
}
func bytesConvert(bytes uint64) string {
unit := ""
value := float32(bytes)
switch {
case bytes >= GIGABYTE:
unit = "GB"
value = value / GIGABYTE
case bytes >= MEGABYTE:
unit = "MB"
value = value / MEGABYTE
case bytes >= KILOBYTE:
unit = "KB"
value = value / KILOBYTE
case bytes >= BYTE:
unit = "bytes"
case bytes == 0:
return "0"
}
stringValue := strings.TrimSuffix(
fmt.Sprintf("%.2f", value), ".00",
)
return fmt.Sprintf("%s %s", stringValue, unit)
}
func findingSummaryAndExit(detector *detect.Detector, findings []report.Finding, exitCode int, start time.Time, err error) {
totalBytes := atomic.LoadUint64(&detector.TotalBytes)
bytesMsg := fmt.Sprintf("scanned ~%d bytes (%s)", totalBytes, bytesConvert(totalBytes))
if err == nil {
log.Info().Msgf("scan completed in %s", FormatDuration(time.Since(start)))
log.Info().Msgf("%s in %s", bytesMsg, FormatDuration(time.Since(start)))
if len(findings) != 0 {
log.Warn().Msgf("leaks found: %d", len(findings))
} else {
log.Info().Msg("no leaks found")
}
} else {
log.Warn().Msg(bytesMsg)
log.Warn().Msgf("partial scan completed in %s", FormatDuration(time.Since(start)))
if len(findings) != 0 {
log.Warn().Msgf("%d leaks found in partial scan", len(findings))
@@ -281,11 +378,32 @@ func findingSummaryAndExit(findings []report.Finding, cmd *cobra.Command, cfg co
}
// write report if desired
reportPath, _ := cmd.Flags().GetString("report-path")
ext, _ := cmd.Flags().GetString("report-format")
if reportPath != "" {
if err := report.Write(findings, cfg, ext, reportPath); err != nil {
log.Fatal().Err(err).Msg("could not write")
if detector.Reporter != nil && len(findings) > 0 {
var (
file io.WriteCloser
reportErr error
)
if detector.ReportPath == report.StdoutReportPath {
file = os.Stdout
} else {
// Open the file.
if file, reportErr = os.Create(detector.ReportPath); reportErr != nil {
goto ReportEnd
}
defer func() {
_ = file.Close()
}()
}
// Write to the file.
if reportErr = detector.Reporter.Write(file, findings); reportErr != nil {
goto ReportEnd
}
ReportEnd:
if reportErr != nil {
log.Fatal().Err(reportErr).Msg("failed to write report")
}
}
@@ -296,7 +414,6 @@ func findingSummaryAndExit(findings []report.Finding, cmd *cobra.Command, cfg co
if len(findings) != 0 {
os.Exit(exitCode)
}
}
func fileExists(fileName string) bool {
+1 -1
View File
@@ -47,5 +47,5 @@ func runStdIn(cmd *cobra.Command, args []string) {
log.Fatal().Err(err).Msg("failed scan input from stdin")
}
findingSummaryAndExit(findings, cmd, cfg, exitCode, start, err)
findingSummaryAndExit(detector, findings, exitCode, start, err)
}
+1 -1
View File
@@ -2,9 +2,9 @@ package config
import (
"fmt"
"regexp"
"strings"
regexp "github.com/wasilibs/go-re2"
"golang.org/x/exp/maps"
)
+1 -1
View File
@@ -2,12 +2,12 @@ package config
import (
"errors"
"regexp"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/stretchr/testify/assert"
regexp "github.com/wasilibs/go-re2"
)
func TestCommitAllowed(t *testing.T) {
+13 -14
View File
@@ -3,12 +3,12 @@ package config
import (
_ "embed"
"fmt"
"regexp"
"sort"
"strings"
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
regexp "github.com/wasilibs/go-re2"
)
//go:embed gitleaks.toml
@@ -93,8 +93,10 @@ func (vc *ViperConfig) Translate() (Config, error) {
if vr.Keywords == nil {
vr.Keywords = []string{}
} else {
for _, k := range vr.Keywords {
keywords[strings.ToLower(k)] = struct{}{}
for i, k := range vr.Keywords {
keyword := strings.ToLower(k)
keywords[keyword] = struct{}{}
vr.Keywords[i] = keyword
}
}
@@ -111,7 +113,7 @@ func (vc *ViperConfig) Translate() (Config, error) {
configPathRegex = regexp.MustCompile(vr.Path)
}
rule := Rule{
cr := Rule{
RuleID: vr.ID,
Description: vr.Description,
Regex: configRegex,
@@ -124,7 +126,7 @@ func (vc *ViperConfig) Translate() (Config, error) {
// 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)
return Config{}, fmt.Errorf("%s: [rules.allowlist] is deprecated, it cannot be used alongside [[rules.allowlist]]", cr.RuleID)
}
vr.Allowlists = append(vr.Allowlists, *vr.AllowList)
}
@@ -137,7 +139,7 @@ func (vc *ViperConfig) Translate() (Config, error) {
case "", "OR", "||":
condition = AllowlistMatchOr
default:
return Config{}, fmt.Errorf("%s: unknown allowlist condition '%s' (expected 'and', 'or')", rule.RuleID, c)
return Config{}, fmt.Errorf("%s: unknown allowlist condition '%s' (expected 'and', 'or')", cr.RuleID, c)
}
// Validate the target.
@@ -148,7 +150,7 @@ func (vc *ViperConfig) Translate() (Config, error) {
case "match", "line":
// do nothing
default:
return Config{}, fmt.Errorf("%s: unknown allowlist |regexTarget| '%s' (expected 'match', 'line')", rule.RuleID, a.RegexTarget)
return Config{}, fmt.Errorf("%s: unknown allowlist |regexTarget| '%s' (expected 'match', 'line')", cr.RuleID, a.RegexTarget)
}
}
var allowlistRegexes []*regexp.Regexp
@@ -169,12 +171,12 @@ func (vc *ViperConfig) Translate() (Config, error) {
StopWords: a.StopWords,
}
if err := allowlist.Validate(); err != nil {
return Config{}, fmt.Errorf("%s: %w", rule.RuleID, err)
return Config{}, fmt.Errorf("%s: %w", cr.RuleID, err)
}
rule.Allowlists = append(rule.Allowlists, allowlist)
cr.Allowlists = append(cr.Allowlists, allowlist)
}
orderedRules = append(orderedRules, rule.RuleID)
rulesMap[rule.RuleID] = rule
orderedRules = append(orderedRules, cr.RuleID)
rulesMap[cr.RuleID] = cr
}
var allowlistRegexes []*regexp.Regexp
for _, a := range vc.Allowlist.Regexes {
@@ -316,9 +318,6 @@ func (c *Config) extend(extensionConfig Config) {
for _, k := range baseRule.Keywords {
c.Keywords[k] = struct{}{}
}
for _, k := range currentRule.Keywords {
c.Keywords[k] = struct{}{}
}
c.Rules[ruleID] = baseRule
}
}
+45 -2
View File
@@ -2,10 +2,11 @@ package config
import (
"fmt"
"github.com/google/go-cmp/cmp"
"regexp"
"testing"
"github.com/google/go-cmp/cmp"
regexp "github.com/wasilibs/go-re2"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -393,3 +394,45 @@ func TestTranslate(t *testing.T) {
})
}
}
func TestExtendedRuleKeywordsAreDowncase(t *testing.T) {
tests := []struct {
name string
cfgName string
expectedKeywords string
}{
{
name: "Extend base rule that includes AWS keyword with new attribute",
cfgName: "extend_base_rule_including_keysword_with_attribute",
expectedKeywords: "aws",
},
{
name: "Extend base with a new rule with CMS keyword",
cfgName: "extend_with_new_rule",
expectedKeywords: "cms",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Cleanup(func() {
viper.Reset()
})
viper.AddConfigPath(configPath)
viper.SetConfigName(tt.cfgName)
viper.SetConfigType("toml")
err := viper.ReadInConfig()
require.NoError(t, err)
var vc ViperConfig
err = viper.Unmarshal(&vc)
require.NoError(t, err)
cfg, err := vc.Translate()
require.NoError(t, err)
_, exists := cfg.Keywords[tt.expectedKeywords]
require.Truef(t, exists, "The expected keyword %s did not exist as a key of cfg.Keywords", tt.expectedKeywords)
})
}
}
+45 -13
View File
@@ -32,25 +32,22 @@ paths = [
'''(.*?)(doc|docx|zip|xls|pdf|bin|socket|vsidx|v2|suo|wsuo|.dll|pdb|exe|gltf)$''',
'''go\.(mod|sum|work(\.sum)?)$''',
'''(^|/)vendor/modules\.txt$''',
'''(^|/)vendor/(github\.com|golang\.org/x|google\.golang\.org|gopkg\.in|istio\.io|k8s\.io|sigs\.k8s\.io)/.*$''',
'''(^|/)vendor/(github\.com|golang\.org/x|google\.golang\.org|gopkg\.in|istio\.io|k8s\.io|sigs\.k8s\.io)(/.*)?$''',
'''(^|/)gradlew(\.bat)?$''',
'''(^|/)gradle\.lockfile$''',
'''(^|/)mvnw(\.cmd)?$''',
'''(^|/)\.mvn/wrapper/MavenWrapperDownloader\.java$''',
'''(^|/)node_modules/.*?$''',
'''(^|/)package-lock\.json$''',
'''(^|/)yarn\.lock$''',
'''(^|/)pnpm-lock\.yaml$''',
'''(^|/)npm-shrinkwrap\.json$''',
'''(^|/)bower_components/.*?$''',
'''(^|/)node_modules(/.*)?$''',
'''(^|/)(npm-shrinkwrap\.json|package-lock\.json|pnpm-lock\.yaml|yarn\.lock)$''',
'''(^|/)bower_components(/.*)?$''',
'''(^|/)(angular|jquery(-?ui)?|plotly|swagger-?ui)[a-zA-Z0-9.-]*(\.min)?\.js(\.map)?$''',
'''(^|/)(Pipfile|poetry)\.lock$''',
'''(?i)/?(v?env|virtualenv)/lib(64)?/.+$''',
'''(?i)(^|/)(lib(64)?/python[23](\.\d{1,2})+/|python/[23](\.\d{1,2})+/lib(64)?/).+$''',
'''(?i)(^|/)[a-z0-9_.]+-[0-9.]+\.dist-info/.+$''',
'''(^|/)vendor/(bundle|ruby)/.*?$''',
'''(?i)/?(v?env|virtualenv)/lib(64)?(/.*)?$''',
'''(?i)(^|/)(lib(64)?/python[23](\.\d{1,2})+|python/[23](\.\d{1,2})+/lib(64)?)(/.*)?$''',
'''(?i)(^|/)[a-z0-9_.]+-[0-9.]+\.dist-info(/.+)?$''',
'''(^|/)vendor/(bundle|ruby)(/.*?)?$''',
'''\.gem$''',
'''verification-metadata.xml''',
'''verification-metadata\.xml''',
'''Database.refactorlog''',
]
stopwords = [
@@ -518,6 +515,13 @@ description = "Found a Frame.io API token, potentially compromising video collab
regex = '''fio-u-(?i)[a-z0-9\-_=]{64}'''
keywords = ["fio-u-"]
[[rules]]
id = "freemius-secret-key"
description = "Detected a Freemius secret key, potentially exposing sensitive information."
regex = '''(?i)["']secret_key["']\s*=>\s*["'](sk_[\S]{29})["']'''
path = '''(?i)\.php$'''
keywords = ["secret_key"]
[[rules]]
id = "freshbooks-access-token"
description = "Discovered a Freshbooks Access Token, posing a risk to accounting software access and sensitive financial data exposure."
@@ -2137,6 +2141,13 @@ regex = '''glpat-[\w-]{20}'''
entropy = 3
keywords = ["glpat-"]
[[rules]]
id = "gitlab-pat-routable"
description = "Identified a GitLab Personal Access Token (routable), risking unauthorized access to GitLab repositories and codebase exposure."
regex = '''\bglpat-[0-9a-zA-Z_-]{27,300}\.[0-9a-z]{2}[0-9a-z]{7}\b'''
entropy = 4
keywords = ["glpat-"]
[[rules]]
id = "gitlab-ptt"
description = "Found a GitLab Pipeline Trigger Token, potentially compromising continuous integration workflows and project security."
@@ -2330,7 +2341,7 @@ keywords = ["kraken"]
[[rules]]
id = "kubernetes-secret-yaml"
description = "Possible Kubernetes Secret detected, posing a risk of leaking credentials/tokens from your deployments"
regex = '''(?i)(?:\bkind:[ \t]*["']?secret["']?(?:.|\s){0,200}?\bdata:(?:.|\s){0,100}?\s+([\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:["']?[a-z0-9+/]{10,}={0,3}["']?|\{\{[ \t\w"|$:=,.-]+}}|""|''))|\bdata:(?:.|\s){0,100}?\s+([\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:["']?[a-z0-9+/]{10,}={0,3}["']?|\{\{[ \t\w"|$:=,.-]+}}|""|''))(?:.|\s){0,200}?\bkind:[ \t]*["']?secret["']?)'''
regex = '''(?i)(?:\bkind:[ \t]*["']?\bsecret\b["']?(?:.|\s){0,200}?\bdata:(?:.|\s){0,100}?\s+([\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:["']?[a-z0-9+/]{10,}={0,3}["']?|\{\{[ \t\w"|$:=,.-]+}}|""|''))|\bdata:(?:.|\s){0,100}?\s+([\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:["']?[a-z0-9+/]{10,}={0,3}["']?|\{\{[ \t\w"|$:=,.-]+}}|""|''))(?:.|\s){0,200}?\bkind:[ \t]*["']?\bsecret\b["']?)'''
path = '''(?i)\.ya?ml$'''
keywords = ["secret"]
# NOTE: Gitleaks >= v8.21.0 should use [[rules.allowlists] instead.
@@ -2732,6 +2743,27 @@ regex = '''\b(sntryu_[a-f0-9]{64})(?:['|\"|\n|\r|\s|\x60|;]|$)'''
entropy = 3.5
keywords = ["sntryu_"]
[[rules]]
id = "settlemint-application-access-token"
description = "Found a Settlemint Application Access Token."
regex = '''\b(sm_aat_[a-zA-Z0-9]{16})(?:['|\"|\n|\r|\s|\x60|;]|$)'''
entropy = 3
keywords = ["sm_aat"]
[[rules]]
id = "settlemint-personal-access-token"
description = "Found a Settlemint Personal Access Token."
regex = '''\b(sm_pat_[a-zA-Z0-9]{16})(?:['|\"|\n|\r|\s|\x60|;]|$)'''
entropy = 3
keywords = ["sm_pat"]
[[rules]]
id = "settlemint-service-access-token"
description = "Found a Settlemint Service Access Token."
regex = '''\b(sm_sat_[a-zA-Z0-9]{16})(?:['|\"|\n|\r|\s|\x60|;]|$)'''
entropy = 3
keywords = ["sm_sat"]
[[rules]]
id = "shippo-api-token"
description = "Discovered a Shippo API token, potentially compromising shipping services and customer order data."
+2 -1
View File
@@ -2,8 +2,9 @@ package config
import (
"fmt"
"regexp"
"strings"
regexp "github.com/wasilibs/go-re2"
)
// Rules contain information that define details on how to detect secrets
+1 -1
View File
@@ -1,7 +1,7 @@
package config
import (
"regexp"
regexp "github.com/wasilibs/go-re2"
)
func anyRegexMatch(f string, res []*regexp.Regexp) bool {
+38 -24
View File
@@ -8,6 +8,7 @@ import (
"regexp"
"strings"
"sync"
"sync/atomic"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/report"
@@ -22,7 +23,7 @@ import (
const (
gitleaksAllowSignature = "gitleaks:allow"
chunkSize = 10 * 1_000 // 10kb
chunkSize = 100 * 1_000 // 100kb
)
var newLineRegexp = regexp.MustCompile("\n")
@@ -83,6 +84,12 @@ type Detector struct {
// Sema (https://github.com/fatih/semgroup) controls the concurrency
Sema *semgroup.Group
// report-related settings.
ReportPath string
Reporter report.Reporter
TotalBytes uint64
}
// Fragment contains the data to be scanned
@@ -90,6 +97,8 @@ type Fragment struct {
// Raw is the raw content of the fragment
Raw string
Bytes []byte
// FilePath is the path to the file if applicable
FilePath string
SymlinkFile string
@@ -174,6 +183,11 @@ func (d *Detector) DetectString(content string) []report.Finding {
// Detect scans the given fragment and returns a list of findings
func (d *Detector) Detect(fragment Fragment) []report.Finding {
if fragment.Bytes == nil {
atomic.AddUint64(&d.TotalBytes, uint64(len(fragment.Raw)))
}
atomic.AddUint64(&d.TotalBytes, uint64(len(fragment.Bytes)))
var findings []report.Finding
// check if filepath is allowed
@@ -238,11 +252,11 @@ func (d *Detector) Detect(fragment Fragment) []report.Finding {
}
// detectRule scans the given fragment for the given rule and returns a list of findings
func (d *Detector) detectRule(fragment Fragment, currentRaw string, rule config.Rule, encodedSegments []EncodedSegment) []report.Finding {
func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rule, encodedSegments []EncodedSegment) []report.Finding {
var (
findings []report.Finding
logger = func() zerolog.Logger {
l := log.With().Str("rule-id", rule.RuleID)
l := log.With().Str("rule-id", r.RuleID)
if fragment.CommitSHA != "" {
l = l.Str("commit", fragment.CommitSHA)
}
@@ -252,7 +266,7 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, rule config.
)
// check if filepath or commit is allowed for this rule
for _, a := range rule.Allowlists {
for _, a := range r.Allowlists {
var (
isAllowed bool
commitAllowed = a.CommitAllowed(fragment.CommitSHA)
@@ -290,30 +304,30 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, rule config.
}
}
if rule.Path != nil && rule.Regex == nil && len(encodedSegments) == 0 {
if r.Path != nil && r.Regex == nil && len(encodedSegments) == 0 {
// Path _only_ rule
if rule.Path.MatchString(fragment.FilePath) {
if r.Path.MatchString(fragment.FilePath) {
finding := report.Finding{
Description: rule.Description,
Description: r.Description,
File: fragment.FilePath,
SymlinkFile: fragment.SymlinkFile,
RuleID: rule.RuleID,
RuleID: r.RuleID,
Match: fmt.Sprintf("file detected: %s", fragment.FilePath),
Tags: rule.Tags,
Tags: r.Tags,
}
return append(findings, finding)
}
} else if rule.Path != nil {
} else if r.Path != nil {
// if path is set _and_ a regex is set, then we need to check both
// so if the path does not match, then we should return early and not
// consider the regex
if !rule.Path.MatchString(fragment.FilePath) {
if !r.Path.MatchString(fragment.FilePath) {
return findings
}
}
// if path only rule, skip content checks
if rule.Regex == nil {
if r.Regex == nil {
return findings
}
@@ -329,7 +343,7 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, rule config.
// 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) {
for _, matchIndex := range r.Regex.FindAllStringIndex(currentRaw, -1) {
// Extract secret from match
secret := strings.Trim(currentRaw[matchIndex[0]:matchIndex[1]], "\n")
@@ -363,17 +377,17 @@ MatchLoop:
}
finding := report.Finding{
Description: rule.Description,
Description: r.Description,
File: fragment.FilePath,
SymlinkFile: fragment.SymlinkFile,
RuleID: rule.RuleID,
RuleID: r.RuleID,
StartLine: loc.startLine,
EndLine: loc.endLine,
StartColumn: loc.startColumn,
EndColumn: loc.endColumn,
Secret: secret,
Match: secret,
Tags: append(rule.Tags, metaTags...),
Tags: append(r.Tags, metaTags...),
Line: fragment.Raw[loc.startLineIndex:loc.endLineIndex],
}
@@ -387,14 +401,14 @@ MatchLoop:
// Set the value of |secret|, if the pattern contains at least one capture group.
// (The first element is the full match, hence we check >= 2.)
groups := rule.Regex.FindStringSubmatch(finding.Secret)
groups := r.Regex.FindStringSubmatch(finding.Secret)
if len(groups) >= 2 {
if rule.SecretGroup > 0 {
if len(groups) <= rule.SecretGroup {
if r.SecretGroup > 0 {
if len(groups) <= r.SecretGroup {
// Config validation should prevent this
continue
}
finding.Secret = groups[rule.SecretGroup]
finding.Secret = groups[r.SecretGroup]
} else {
// If |secretGroup| is not set, we will use the first suitable capture group.
if len(groups) == 2 {
@@ -434,7 +448,7 @@ MatchLoop:
}
// check if the result matches any of the rule allowlists.
for _, a := range rule.Allowlists {
for _, a := range r.Allowlists {
allowlistTarget := finding.Secret
switch a.RegexTarget {
case "match":
@@ -485,8 +499,8 @@ MatchLoop:
// check entropy
entropy := shannonEntropy(finding.Secret)
finding.Entropy = float32(entropy)
if rule.Entropy != 0.0 {
if entropy <= rule.Entropy {
if r.Entropy != 0.0 {
if entropy <= r.Entropy {
// entropy is too low, skip this finding
continue
}
@@ -497,7 +511,7 @@ MatchLoop:
// What this bit of code does is check if the ruleid is prepended with "generic" and enforces the
// secret contains both digits and alphabetical characters.
// TODO: this should be replaced with stop words
if strings.HasPrefix(rule.RuleID, "generic") {
if strings.HasPrefix(r.RuleID, "generic") {
if !containsDigit(finding.Secret) {
continue
}
+5 -4
View File
@@ -2,15 +2,16 @@ package detect
import (
"fmt"
"github.com/google/go-cmp/cmp"
"os"
"path/filepath"
"regexp"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
regexp "github.com/wasilibs/go-re2"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/report"
@@ -789,7 +790,7 @@ func TestFromFiles(t *testing.T) {
err = detector.AddGitleaksIgnore(ignorePath)
require.NoError(t, err)
detector.FollowSymlinks = true
paths, err := sources.DirectoryTargets(tt.source, detector.Sema, true)
paths, err := sources.DirectoryTargets(tt.source, detector.Sema, true, cfg.Allowlist.PathAllowed)
require.NoError(t, err)
findings, err := detector.DetectFiles(paths)
require.NoError(t, err)
@@ -840,7 +841,7 @@ func TestDetectWithSymlinks(t *testing.T) {
cfg, _ := vc.Translate()
detector := NewDetector(cfg)
detector.FollowSymlinks = true
paths, err := sources.DirectoryTargets(tt.source, detector.Sema, true)
paths, err := sources.DirectoryTargets(tt.source, detector.Sema, true, cfg.Allowlist.PathAllowed)
require.NoError(t, err)
findings, err := detector.DetectFiles(paths)
require.NoError(t, err)
+85 -31
View File
@@ -1,21 +1,26 @@
package detect
import (
"bytes"
"io"
"os"
"strings"
"github.com/h2non/filetype"
"github.com/rs/zerolog/log"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
)
const maxPeekSize = 25 * 1_000 // 10kb
func (d *Detector) DetectFiles(paths <-chan sources.ScanTarget) ([]report.Finding, error) {
for pa := range paths {
d.Sema.Go(func() error {
logger := log.With().Str("path", pa.Path).Logger()
logger.Trace().Msg("Scanning path")
f, err := os.Open(pa.Path)
if err != nil {
if os.IsPermission(err) {
@@ -24,7 +29,9 @@ func (d *Detector) DetectFiles(paths <-chan sources.ScanTarget) ([]report.Findin
}
return err
}
defer f.Close()
defer func() {
_ = f.Close()
}()
// Get file size
fileInfo, err := f.Stat()
@@ -37,7 +44,7 @@ func (d *Detector) DetectFiles(paths <-chan sources.ScanTarget) ([]report.Findin
if rawLength > int64(d.MaxTargetMegaBytes) {
logger.Debug().
Int64("size", rawLength).
Msgf("Skipping file: exceeds --max-target-megabytes")
Msg("Skipping file: exceeds --max-target-megabytes")
return nil
}
}
@@ -47,41 +54,88 @@ func (d *Detector) DetectFiles(paths <-chan sources.ScanTarget) ([]report.Findin
totalLines := 0
for {
n, err := f.Read(buf)
if err != nil && err != io.EOF {
return err
}
if n == 0 {
break
if n > 0 {
// TODO: optimization could be introduced here
if mimetype, err := filetype.Match(buf[:n]); err != nil {
return nil
} else if mimetype.MIME.Type == "application" {
return nil // skip binary files
}
// If the chunk doesn't end in a newline, peek |maxPeekSize| until we find one.
// This hopefully avoids splitting
// See: https://github.com/gitleaks/gitleaks/issues/1651
var (
peekBuf = bytes.NewBuffer(buf[:n])
tempBuf = make([]byte, 1)
newlineCount = 0 // Tracks consecutive newlines
)
for {
data := peekBuf.Bytes()
if len(data) == 0 {
break
}
// Check if the last character is a newline.
lastChar := data[len(data)-1]
if lastChar == '\n' || lastChar == '\r' {
newlineCount++
// Stop if two consecutive newlines are found
if newlineCount >= 2 {
break
}
} else {
newlineCount = 0 // Reset if a non-newline character is found
}
// Stop growing the buffer if it reaches maxSize
if (peekBuf.Len() - n) >= maxPeekSize {
break
}
// Read additional data into a temporary buffer
m, readErr := f.Read(tempBuf)
if m > 0 {
peekBuf.Write(tempBuf[:m])
}
// Stop if EOF is reached
if readErr != nil {
if readErr == io.EOF {
break
}
return readErr
}
}
// Count the number of newlines in this chunk
chunk := peekBuf.String()
linesInChunk := strings.Count(chunk, "\n")
totalLines += linesInChunk
fragment := Fragment{
Raw: chunk,
Bytes: peekBuf.Bytes(),
FilePath: pa.Path,
}
if pa.Symlink != "" {
fragment.SymlinkFile = pa.Symlink
}
for _, finding := range d.Detect(fragment) {
// need to add 1 since line counting starts at 1
finding.StartLine += (totalLines - linesInChunk) + 1
finding.EndLine += (totalLines - linesInChunk) + 1
d.addFinding(finding)
}
}
// TODO: optimization could be introduced here
mimetype, err := filetype.Match(buf[:n])
if err != nil {
if err == io.EOF {
return nil
}
return err
}
if mimetype.MIME.Type == "application" {
return nil // skip binary files
}
// Count the number of newlines in this chunk
linesInChunk := strings.Count(string(buf[:n]), "\n")
totalLines += linesInChunk
fragment := Fragment{
Raw: string(buf[:n]),
FilePath: pa.Path,
}
if pa.Symlink != "" {
fragment.SymlinkFile = pa.Symlink
}
for _, finding := range d.Detect(fragment) {
// need to add 1 since line counting starts at 1
finding.StartLine += (totalLines - linesInChunk) + 1
finding.EndLine += (totalLines - linesInChunk) + 1
d.addFinding(finding)
}
}
return nil
})
}
+18 -8
View File
@@ -1,11 +1,10 @@
module github.com/zricethezav/gitleaks/v8
go 1.22.0
toolchain go1.22.5
go 1.23
require (
github.com/BobuSumisu/aho-corasick v1.0.3
github.com/Masterminds/sprig v2.22.0+incompatible
github.com/charmbracelet/lipgloss v0.5.0
github.com/fatih/semgroup v1.2.0
github.com/gitleaks/go-gitdiff v0.9.1
@@ -14,18 +13,28 @@ require (
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
github.com/stretchr/testify v1.9.0
golang.org/x/exp v0.0.0-20240909161429-701f63a606c0
)
require (
github.com/Masterminds/goutils v1.1.1 // indirect
github.com/Masterminds/semver v1.5.0 // indirect
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/huandu/xstrings v1.5.0 // indirect
github.com/imdario/mergo v0.3.16 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
github.com/mattn/go-runewidth v0.0.14 // indirect
github.com/mitchellh/copystructure v1.2.0 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/muesli/reflow v0.2.1-0.20210115123740-9e1d0d53df68 // indirect
github.com/muesli/termenv v0.15.1 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
github.com/tetratelabs/wazero v1.8.2 // indirect
github.com/wasilibs/wazero-helpers v0.0.0-20240620070341-3dff1577cd52 // indirect
golang.org/x/crypto v0.29.0 // indirect
)
require (
@@ -43,10 +52,11 @@ 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.8.0 // indirect
golang.org/x/sys v0.6.0 // indirect
golang.org/x/text v0.3.8 // indirect
github.com/wasilibs/go-re2 v1.8.0
golang.org/x/sync v0.9.0 // indirect
golang.org/x/sys v0.27.0 // indirect
golang.org/x/text v0.20.0 // indirect
gopkg.in/ini.v1 v1.62.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
+34 -8
View File
@@ -41,6 +41,12 @@ github.com/BobuSumisu/aho-corasick v1.0.3 h1:uuf+JHwU9CHP2Vx+wAy6jcksJThhJS9ehR8
github.com/BobuSumisu/aho-corasick v1.0.3/go.mod h1:hm4jLcvZKI2vRF2WDU1N4p/jpWtpOzp3nLmi9AzX/XE=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI=
github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU=
github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww=
github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y=
github.com/Masterminds/sprig v2.22.0+incompatible h1:z4yfnGrZ7netVz+0EDJ0Wi+5VZCSYp4Z0m2dk6cEM60=
github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o=
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o=
github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY=
@@ -146,6 +152,8 @@ github.com/google/pprof v0.0.0-20210122040257-d980be63207e/go.mod h1:kpwsk12EmLe
github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8=
@@ -174,8 +182,12 @@ github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO
github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ=
github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I=
github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc=
github.com/huandu/xstrings v1.5.0 h1:2ag3IFq9ZDANvthTwTiqSSZLjDc+BedvHPAp5tJy2TI=
github.com/huandu/xstrings v1.5.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/imdario/mergo v0.3.16 h1:wwQJbIsHYGMUyLSPrEq1CT16AhnhNJQ51+4fdHUnCl4=
github.com/imdario/mergo v0.3.16/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY=
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
@@ -208,6 +220,8 @@ github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWV
github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc=
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=
github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI=
github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg=
@@ -216,6 +230,8 @@ github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:F
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.4.1 h1:CpVNEelQCZBooIPDn+AR3NpivK/TIKU8bDxdASFVQag=
github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=
github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
@@ -268,10 +284,17 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s=
github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
github.com/tetratelabs/wazero v1.8.2 h1:yIgLR/b2bN31bjxwXHD8a3d+BogigR952csSDdLYEv4=
github.com/tetratelabs/wazero v1.8.2/go.mod h1:yAI0XTsMBhREkM/YDAK/zNou3GoiAce1P6+rp/wQhjs=
github.com/wasilibs/go-re2 v1.8.0 h1:6wpqZ31vdoJRSOM41bWEd1AbSmRe161yQkTzoihqwEg=
github.com/wasilibs/go-re2 v1.8.0/go.mod h1:RjA3Y/yW6xFL8Iyz8f5sVhttLq5b5DRF8baZ7Sh+elk=
github.com/wasilibs/wazero-helpers v0.0.0-20240620070341-3dff1577cd52 h1:OvLBa8SqJnZ6P+mjlzc2K7PM22rRUPE1x32G9DTPrC4=
github.com/wasilibs/wazero-helpers v0.0.0-20240620070341-3dff1577cd52/go.mod h1:jMeV4Vpbi8osrE/pKUxRZkVaA0EX7NZN0A9/oRzgpgY=
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
@@ -299,6 +322,8 @@ golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8U
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20211215165025-cf75a172585e/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
golang.org/x/crypto v0.29.0 h1:L5SG1JTTXupVV3n6sUqMTeWbjAyfPwoda2DLX8J8FrQ=
golang.org/x/crypto v0.29.0/go.mod h1:+F4F4N5hv6v38hfeYwTdx20oUvLLc+QfrE9Ax9HtgRg=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
@@ -396,8 +421,8 @@ golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJ
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/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/sync v0.9.0 h1:fEo0HyrW1GIgZdpbhCRO0PkJajUS5H9IFUztCgEo2jQ=
golang.org/x/sync v0.9.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=
@@ -443,8 +468,8 @@ golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.27.0 h1:wBqf8DvsY9Y/2P8gAfPDEYNuS30J4lPHJxXSb/nJZ+s=
golang.org/x/sys v0.27.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
@@ -454,8 +479,8 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY=
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug=
golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
@@ -629,8 +654,9 @@ gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
+9 -5
View File
@@ -7,12 +7,16 @@ import (
"strings"
)
// writeCsv writes the list of findings to a writeCloser.
func writeCsv(f []Finding, w io.WriteCloser) error {
if len(f) == 0 {
type CsvReporter struct {
}
var _ Reporter = (*CsvReporter)(nil)
func (r *CsvReporter) Write(w io.WriteCloser, findings []Finding) error {
if len(findings) == 0 {
return nil
}
defer w.Close()
cw := csv.NewWriter(w)
err := cw.Write([]string{"RuleID",
"Commit",
@@ -34,7 +38,7 @@ func writeCsv(f []Finding, w io.WriteCloser) error {
if err != nil {
return err
}
for _, f := range f {
for _, f := range findings {
err = cw.Write([]string{f.RuleID,
f.Commit,
f.File,
+6 -2
View File
@@ -48,22 +48,26 @@ func TestWriteCSV(t *testing.T) {
},
}
reporter := CsvReporter{}
for _, test := range tests {
t.Run(test.testReportName, func(t *testing.T) {
tmpfile, err := os.Create(filepath.Join(t.TempDir(), test.testReportName+".csv"))
require.NoError(t, err)
err = writeCsv(test.findings, tmpfile)
err = reporter.Write(tmpfile, test.findings)
require.NoError(t, err)
assert.FileExists(t, tmpfile.Name())
got, err := os.ReadFile(tmpfile.Name())
require.NoError(t, err)
if test.wantEmpty {
assert.Empty(t, got)
return
}
want, err := os.ReadFile(test.expected)
require.NoError(t, err)
assert.Equal(t, want, got)
assert.Equal(t, string(want), string(got))
})
}
}
+1 -1
View File
@@ -14,7 +14,7 @@ type Finding struct {
StartColumn int
EndColumn int
Line string `json:",omitempty"`
Line string `json:"-"`
Match string
+3 -14
View File
@@ -5,23 +5,12 @@ import (
"io"
)
func writeJson(findings []Finding, w io.WriteCloser) error {
if len(findings) == 0 {
findings = []Finding{}
}
for i := range findings {
// Remove `Line` from JSON output
findings[i].Line = ""
}
return writeJsonExtra(findings, w)
type JsonReporter struct {
}
func writeJsonExtra(findings []Finding, w io.WriteCloser) error {
if len(findings) == 0 {
findings = []Finding{}
}
defer w.Close()
var _ Reporter = (*JsonReporter)(nil)
func (t *JsonReporter) Write(w io.WriteCloser, findings []Finding) error {
encoder := json.NewEncoder(w)
encoder.SetIndent("", " ")
return encoder.Encode(findings)
+3 -23
View File
@@ -13,7 +13,6 @@ var simpleFinding = Finding{
Description: "",
RuleID: "test-rule",
Match: "line containing secret",
Line: "whole line containing secret",
Secret: "a secret",
StartLine: 1,
EndLine: 2,
@@ -49,11 +48,12 @@ func TestWriteJSON(t *testing.T) {
findings: []Finding{}},
}
reporter := JsonReporter{}
for _, test := range tests {
t.Run(test.testReportName, func(t *testing.T) {
tmpfile, err := os.Create(filepath.Join(t.TempDir(), test.testReportName+".json"))
require.NoError(t, err)
err = writeJson(test.findings, tmpfile)
err = reporter.Write(tmpfile, test.findings)
require.NoError(t, err)
assert.FileExists(t, tmpfile.Name())
got, err := os.ReadFile(tmpfile.Name())
@@ -64,27 +64,7 @@ func TestWriteJSON(t *testing.T) {
}
want, err := os.ReadFile(test.expected)
require.NoError(t, err)
assert.Equal(t, want, got)
assert.Equal(t, string(want), string(got))
})
}
}
func TestWriteJSONExtra(t *testing.T) {
findings := []Finding{
simpleFinding,
}
expected := filepath.Join(expectPath, "report", "json_extra_simple.json")
tmpfile, err := os.Create(filepath.Join(t.TempDir(), "simple_extra.json"))
require.NoError(t, err)
err = writeJsonExtra(findings, tmpfile)
require.NoError(t, err)
assert.FileExists(t, tmpfile.Name())
got, err := os.ReadFile(tmpfile.Name())
require.NoError(t, err)
want, err := os.ReadFile(expected)
require.NoError(t, err)
assert.Equal(t, want, got)
}
+6 -1
View File
@@ -8,7 +8,12 @@ import (
"strconv"
)
func writeJunit(findings []Finding, w io.WriteCloser) error {
type JunitReporter struct {
}
var _ Reporter = (*JunitReporter)(nil)
func (r *JunitReporter) Write(w io.WriteCloser, findings []Finding) error {
testSuites := TestSuites{
TestSuites: getTestSuites(findings),
}
+6 -2
View File
@@ -65,20 +65,24 @@ func TestWriteJunit(t *testing.T) {
},
}
reporter := JunitReporter{}
for _, test := range tests {
tmpfile, err := os.Create(filepath.Join(t.TempDir(), test.testReportName+".xml"))
require.NoError(t, err)
err = writeJunit(test.findings, tmpfile)
err = reporter.Write(tmpfile, test.findings)
require.NoError(t, err)
assert.FileExists(t, tmpfile.Name())
got, err := os.ReadFile(tmpfile.Name())
require.NoError(t, err)
if test.wantEmpty {
assert.Empty(t, got)
return
}
want, err := os.ReadFile(test.expected)
require.NoError(t, err)
assert.Equal(t, want, got)
assert.Equal(t, string(want), string(got))
}
}
+6 -26
View File
@@ -1,36 +1,16 @@
package report
import (
"os"
"strings"
"github.com/zricethezav/gitleaks/v8/config"
"io"
)
const (
// https://cwe.mitre.org/data/definitions/798.html
CWE = "CWE-798"
CWE_DESCRIPTION = "Use of Hard-coded Credentials"
CWE = "CWE-798"
CWE_DESCRIPTION = "Use of Hard-coded Credentials"
StdoutReportPath = "-"
)
func Write(findings []Finding, cfg config.Config, ext string, reportPath string) error {
file, err := os.Create(reportPath)
if err != nil {
return err
}
ext = strings.ToLower(ext)
switch ext {
case ".json", "json":
err = writeJson(findings, file)
case ".jsonextra", "jsonextra":
err = writeJsonExtra(findings, file)
case ".csv", "csv":
err = writeCsv(findings, file)
case ".xml", "junit":
err = writeJunit(findings, file)
case ".sarif", "sarif":
err = writeSarif(cfg, findings, file)
}
return err
type Reporter interface {
Write(w io.WriteCloser, findings []Finding) error
}
+27 -101
View File
@@ -1,116 +1,42 @@
package report
import (
"os"
"path/filepath"
"strconv"
"bytes"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/zricethezav/gitleaks/v8/config"
)
const (
expectPath = "../testdata/expected/"
)
const expectPath = "../testdata/expected/"
const configPath = "../testdata/config/"
const templatePath = "../testdata/report/"
func TestReport(t *testing.T) {
tests := []struct {
findings []Finding
ext string
wantEmpty bool
}{
func TestWriteStdout(t *testing.T) {
// Arrange
reporter := JsonReporter{}
buf := testWriter{
bytes.NewBuffer(nil),
}
findings := []Finding{
{
ext: "json",
findings: []Finding{
{
RuleID: "test-rule",
},
},
RuleID: "test-rule",
},
{
ext: ".json",
findings: []Finding{
{
RuleID: "test-rule",
},
},
},
{
ext: ".jsonj",
findings: []Finding{
{
RuleID: "test-rule",
},
},
wantEmpty: true,
},
{
ext: ".csv",
findings: []Finding{
{
RuleID: "test-rule",
},
},
},
{
ext: "csv",
findings: []Finding{
{
RuleID: "test-rule",
},
},
},
{
ext: "CSV",
findings: []Finding{
{
RuleID: "test-rule",
},
},
},
{
ext: ".xml",
findings: []Finding{
{
RuleID: "test-rule",
},
},
},
{
ext: "junit",
findings: []Finding{
{
RuleID: "test-rule",
},
},
},
// {
// ext: "SARIF",
// findings: []Finding{
// {
// RuleID: "test-rule",
// },
// },
// },
}
for i, test := range tests {
t.Run(test.ext, func(t *testing.T) {
tmpfile, err := os.Create(filepath.Join(t.TempDir(), strconv.Itoa(i)+test.ext))
require.NoError(t, err)
err = Write(test.findings, config.Config{}, test.ext, tmpfile.Name())
require.NoError(t, err)
got, err := os.ReadFile(tmpfile.Name())
require.NoError(t, err)
assert.FileExists(t, tmpfile.Name())
if test.wantEmpty {
assert.Empty(t, got)
return
}
assert.NotEmpty(t, got)
})
}
// Act
err := reporter.Write(buf, findings)
require.NoError(t, err)
got := buf.Bytes()
// Assert
assert.NotEmpty(t, got)
}
type testWriter struct {
*bytes.Buffer
}
func (t testWriter) Close() error {
return nil
}
+14 -9
View File
@@ -8,35 +8,40 @@ import (
"github.com/zricethezav/gitleaks/v8/config"
)
func writeSarif(cfg config.Config, findings []Finding, w io.WriteCloser) error {
type SarifReporter struct {
OrderedRules []config.Rule
}
var _ Reporter = (*SarifReporter)(nil)
func (r *SarifReporter) Write(w io.WriteCloser, findings []Finding) error {
sarif := Sarif{
Schema: "https://json.schemastore.org/sarif-2.1.0.json",
Version: "2.1.0",
Runs: getRuns(cfg, findings),
Runs: r.getRuns(findings),
}
defer w.Close()
encoder := json.NewEncoder(w)
encoder.SetIndent("", " ")
return encoder.Encode(sarif)
}
func getRuns(cfg config.Config, findings []Finding) []Runs {
func (r *SarifReporter) getRuns(findings []Finding) []Runs {
return []Runs{
{
Tool: getTool(cfg),
Tool: r.getTool(),
Results: getResults(findings),
},
}
}
func getTool(cfg config.Config) Tool {
func (r *SarifReporter) getTool() Tool {
tool := Tool{
Driver: Driver{
Name: driver,
SemanticVersion: version,
InformationUri: "https://github.com/gitleaks/gitleaks",
Rules: getRules(cfg),
Rules: r.getRules(),
},
}
@@ -52,10 +57,10 @@ func hasEmptyRules(tool Tool) bool {
return len(tool.Driver.Rules) == 0
}
func getRules(cfg config.Config) []Rules {
func (r *SarifReporter) getRules() []Rules {
// TODO for _, rule := range cfg.Rules {
var rules []Rules
for _, rule := range cfg.GetOrderedRules() {
for _, rule := range r.OrderedRules {
rules = append(rules, Rules{
ID: rule.RuleID,
Description: ShortDescription{
+19 -19
View File
@@ -5,15 +5,12 @@ import (
"path/filepath"
"testing"
"github.com/spf13/viper"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/zricethezav/gitleaks/v8/config"
)
const configPath = "../testdata/config/"
func TestWriteSarif(t *testing.T) {
tests := []struct {
findings []Finding
@@ -29,8 +26,8 @@ func TestWriteSarif(t *testing.T) {
findings: []Finding{
{
Description: "A test rule",
RuleID: "test-rule",
Description: "A test rule",
Match: "line containing secret",
Secret: "a secret",
StartLine: 1,
@@ -52,28 +49,31 @@ func TestWriteSarif(t *testing.T) {
t.Run(test.cfgName, func(t *testing.T) {
tmpfile, err := os.Create(filepath.Join(t.TempDir(), test.testReportName+".json"))
require.NoError(t, err)
viper.Reset()
viper.AddConfigPath(configPath)
viper.SetConfigName(test.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()
require.NoError(t, err)
err = writeSarif(cfg, test.findings, tmpfile)
reporter := SarifReporter{
OrderedRules: []config.Rule{
{
RuleID: "aws-access-key",
Description: "AWS Access Key",
},
{
RuleID: "pypi",
Description: "PyPI upload token",
},
},
}
err = reporter.Write(tmpfile, test.findings)
require.NoError(t, err)
assert.FileExists(t, tmpfile.Name())
got, err := os.ReadFile(tmpfile.Name())
require.NoError(t, err)
if test.wantEmpty {
assert.Empty(t, got)
return
}
want, err := os.ReadFile(test.expected)
require.NoError(t, err)
assert.Equal(t, string(want), string(got))
+46
View File
@@ -0,0 +1,46 @@
package report
import (
"fmt"
"io"
"os"
"text/template"
"github.com/Masterminds/sprig"
)
type TemplateReporter struct {
template *template.Template
}
var _ Reporter = (*TemplateReporter)(nil)
func NewTemplateReporter(templatePath string) (*TemplateReporter, error) {
if templatePath == "" {
return nil, fmt.Errorf("template path cannot be empty")
}
file, err := os.ReadFile(templatePath)
if err != nil {
return nil, fmt.Errorf("error reading file: %w", err)
}
templateText := string(file)
// TODO: Add helper functions like escaping for JSON, XML, etc.
t := template.New("custom")
t = t.Funcs(sprig.TxtFuncMap())
t, err = t.Parse(templateText)
if err != nil {
return nil, fmt.Errorf("error parsing file: %w", err)
}
return &TemplateReporter{template: t}, nil
}
// writeTemplate renders the findings using the user-provided template.
// https://www.digitalocean.com/community/tutorials/how-to-use-templates-in-go
func (t *TemplateReporter) Write(w io.WriteCloser, findings []Finding) error {
if err := t.template.Execute(w, findings); err != nil {
return err
}
return nil
}
+94
View File
@@ -0,0 +1,94 @@
package report
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestWriteTemplate(t *testing.T) {
tests := []struct {
findings []Finding
testReportName string
expected string
wantEmpty bool
}{
{
testReportName: "markdown",
expected: filepath.Join(expectPath, "report", "template_markdown.md"),
findings: []Finding{
{
RuleID: "test-rule",
Description: "A test rule",
Match: "line containing secret",
Secret: "a secret",
StartLine: 1,
EndLine: 2,
StartColumn: 1,
EndColumn: 2,
Message: "opps",
File: "auth.py",
Commit: "0000000000000000",
Author: "John Doe",
Email: "johndoe@gmail.com",
Date: "10-19-2003",
Tags: []string{"tag1", "tag2", "tag3"},
},
},
},
{
testReportName: "jsonextra",
expected: filepath.Join(expectPath, "report", "template_jsonextra.json"),
findings: []Finding{
{
RuleID: "test-rule",
Description: "A test rule",
Line: "whole line containing secret",
Match: "line containing secret",
Secret: "a secret",
StartLine: 1,
EndLine: 2,
StartColumn: 1,
EndColumn: 2,
Message: "opps",
File: "auth.py",
Commit: "0000000000000000",
Author: "John Doe",
Email: "johndoe@gmail.com",
Date: "10-19-2003",
Tags: []string{"tag1", "tag2", "tag3"},
},
},
},
}
for _, test := range tests {
t.Run(test.testReportName, func(t *testing.T) {
reporter, err := NewTemplateReporter(templatePath + test.testReportName + ".tmpl")
require.NoError(t, err)
tmpfile, err := os.Create(filepath.Join(t.TempDir(), test.testReportName+filepath.Ext(test.expected)))
require.NoError(t, err)
err = reporter.Write(tmpfile, test.findings)
require.NoError(t, err)
assert.FileExists(t, tmpfile.Name())
got, err := os.ReadFile(tmpfile.Name())
require.NoError(t, err)
if test.wantEmpty {
assert.Empty(t, got)
return
}
want, err := os.ReadFile(test.expected)
require.NoError(t, err)
assert.Equal(t, string(want), string(got))
})
}
}
+37 -15
View File
@@ -1,12 +1,12 @@
package sources
import (
"github.com/rs/zerolog/log"
"io/fs"
"os"
"path/filepath"
"github.com/fatih/semgroup"
"github.com/rs/zerolog/log"
)
type ScanTarget struct {
@@ -14,13 +14,14 @@ type ScanTarget struct {
Symlink string
}
func DirectoryTargets(source string, s *semgroup.Group, followSymlinks bool) (<-chan ScanTarget, error) {
func DirectoryTargets(source string, s *semgroup.Group, followSymlinks bool, shouldSkip func(string) bool) (<-chan ScanTarget, error) {
paths := make(chan ScanTarget)
s.Go(func() error {
defer close(paths)
return filepath.Walk(source,
func(path string, fInfo os.FileInfo, err error) error {
logger := log.With().Str("path", path).Logger()
if err != nil {
if os.IsPermission(err) {
// This seems to only fail on directories at this stage.
@@ -30,21 +31,18 @@ func DirectoryTargets(source string, s *semgroup.Group, followSymlinks bool) (<-
return err
}
if fInfo.Name() == ".git" && fInfo.IsDir() {
return filepath.SkipDir
}
// Empty; nothing to do here.
if fInfo.Size() == 0 {
return nil
}
if fInfo.Mode().IsRegular() {
paths <- ScanTarget{
Path: path,
Symlink: "",
}
// Unwrap symlinks, if |followSymlinks| is set.
scanTarget := ScanTarget{
Path: path,
}
if fInfo.Mode().Type() == fs.ModeSymlink {
if !followSymlinks {
log.Debug().Str("path", path).Msg("Skipping symlink")
logger.Debug().Msg("Skipping symlink")
return nil
}
@@ -52,15 +50,39 @@ func DirectoryTargets(source string, s *semgroup.Group, followSymlinks bool) (<-
if err != nil {
return err
}
realPathFileInfo, _ := os.Stat(realPath)
if realPathFileInfo.IsDir() {
log.Debug().Msgf("found symlinked directory: %s -> %s [skipping]", path, realPath)
logger.Warn().Str("target", realPath).Msg("Skipping symlinked directory")
return nil
}
paths <- ScanTarget{
Path: realPath,
Symlink: path,
scanTarget.Path = realPath
scanTarget.Symlink = path
}
// TODO: Also run this check against the resolved symlink?
skip := shouldSkip(path)
if fInfo.IsDir() {
// Directory
if skip {
logger.Debug().Msg("Skipping directory due to global allowlist")
return filepath.SkipDir
}
if fInfo.Name() == ".git" {
// Don't scan .git directories.
// TODO: Add this to the config allowlist, instead of hard-coding it.
return filepath.SkipDir
}
} else {
// File
if skip {
logger.Debug().Msg("Skipping file due to global allowlist")
return nil
}
paths <- scanTarget
}
return nil
})
@@ -0,0 +1,8 @@
title = "gitleaks extended 3"
[extend]
path="../testdata/config/extend_rule_keywords_base.toml"
[[rules]]
id = "aws-secret-key-again-again"
description = "A new description"
+12
View File
@@ -0,0 +1,12 @@
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"]
keywords = ["AWS"]
[[rules.allowlists]]
stopwords = ["fake"]
+8
View File
@@ -0,0 +1,8 @@
title = "gitleaks extended 3"
[extend]
path="../testdata/config/extend_rule_keywords_base.toml"
[[rules]]
id = "aws-rule-that-is-not-in-base"
keywords = ["CMS"]
-23
View File
@@ -1,23 +0,0 @@
[
{
"Description": "",
"StartLine": 1,
"EndLine": 2,
"StartColumn": 1,
"EndColumn": 2,
"Line": "whole line containing secret",
"Match": "line containing secret",
"Secret": "a secret",
"File": "auth.py",
"SymlinkFile": "",
"Commit": "0000000000000000",
"Entropy": 0,
"Author": "John Doe",
"Email": "johndoe@gmail.com",
"Date": "10-19-2003",
"Message": "opps",
"Tags": [],
"RuleID": "test-rule",
"Fingerprint": ""
}
]
-204
View File
@@ -15,210 +15,6 @@
"text": "AWS Access Key"
}
},
{
"id": "aws-secret-key",
"shortDescription": {
"text": "AWS Secret Key"
}
},
{
"id": "aws-mws-key",
"shortDescription": {
"text": "AWS MWS key"
}
},
{
"id": "facebook-secret-key",
"shortDescription": {
"text": "Facebook Secret Key"
}
},
{
"id": "facebook-client-id",
"shortDescription": {
"text": "Facebook Client ID"
}
},
{
"id": "twitter-secret-key",
"shortDescription": {
"text": "Twitter Secret Key"
}
},
{
"id": "twitter-client-id",
"shortDescription": {
"text": "Twitter Client ID"
}
},
{
"id": "github-pat",
"shortDescription": {
"text": "Github Personal Access Token"
}
},
{
"id": "github-oauth",
"shortDescription": {
"text": "Github OAuth Access Token"
}
},
{
"id": "github-app",
"shortDescription": {
"text": "Github App Token"
}
},
{
"id": "github-refresh",
"shortDescription": {
"text": "Github Refresh Token"
}
},
{
"id": "linkedin-client",
"shortDescription": {
"text": "LinkedIn Client ID"
}
},
{
"id": "linkedin-secret",
"shortDescription": {
"text": "LinkedIn Secret Key"
}
},
{
"id": "slack",
"shortDescription": {
"text": "Slack"
}
},
{
"id": "apkey",
"shortDescription": {
"text": "Asymmetric Private Key"
}
},
{
"id": "google",
"shortDescription": {
"text": "Google (GCP) Service Account"
}
},
{
"id": "google",
"shortDescription": {
"text": "Google (GCP) Service Account"
}
},
{
"id": "heroku",
"shortDescription": {
"text": "Heroku API key"
}
},
{
"id": "mailchimp",
"shortDescription": {
"text": "MailChimp API key"
}
},
{
"id": "mailgun",
"shortDescription": {
"text": "Mailgun API key"
}
},
{
"id": "paypal",
"shortDescription": {
"text": "PayPal Braintree access token"
}
},
{
"id": "piacatic",
"shortDescription": {
"text": "Picatic API key"
}
},
{
"id": "sendgrid",
"shortDescription": {
"text": "SendGrid API Key"
}
},
{
"id": "sidekiq-secret",
"shortDescription": {
"text": "Sidekiq Secret"
}
},
{
"id": "sidekiq-sensitive-url",
"shortDescription": {
"text": "Sidekiq Sensitive URL"
}
},
{
"id": "slack-webhook",
"shortDescription": {
"text": "Slack Webhook"
}
},
{
"id": "stripe",
"shortDescription": {
"text": "Stripe API key"
}
},
{
"id": "square",
"shortDescription": {
"text": "Square access token"
}
},
{
"id": "square-oauth",
"shortDescription": {
"text": "Square OAuth secret"
}
},
{
"id": "twilio",
"shortDescription": {
"text": "Twilio API key"
}
},
{
"id": "dynatrace",
"shortDescription": {
"text": "Dynatrace ttoken"
}
},
{
"id": "shopify",
"shortDescription": {
"text": "Shopify shared secret"
}
},
{
"id": "shopify-access",
"shortDescription": {
"text": "Shopify access token"
}
},
{
"id": "shopify-custom",
"shortDescription": {
"text": "Shopify custom app access token"
}
},
{
"id": "shopify-private",
"shortDescription": {
"text": "Shopify private app access token"
}
},
{
"id": "pypi",
"shortDescription": {
+23
View File
@@ -0,0 +1,23 @@
[
{
"Description": "A test rule",
"StartLine": 1,
"EndLine": 2,
"StartColumn": 1,
"EndColumn": 2,
"Line": "whole line containing secret",
"Match": "line containing secret",
"Secret": "a secret",
"File": "auth.py",
"SymlinkFile": "",
"Commit": "0000000000000000",
"Entropy": 0,
"Author": "John Doe",
"Email": "johndoe@gmail.com",
"Date": "10-19-2003",
"Message": "opps",
"Tags": ["tag1","tag2","tag3"],
"RuleID": "test-rule",
"Fingerprint": ""
}
]
+3
View File
@@ -0,0 +1,3 @@
| File | Line | Secret |
|:-----|-----:|--------|
| auth.py | 1 | "a secret" |
+25
View File
@@ -0,0 +1,25 @@
[{{ $lastFinding := (sub (len . ) 1) }}
{{- range $i, $finding := . }}{{with $finding}}
{
"Description": {{ quote .Description }},
"StartLine": {{ .StartLine }},
"EndLine": {{ .EndLine }},
"StartColumn": {{ .StartColumn }},
"EndColumn": {{ .EndColumn }},
"Line": {{ quote .Line }},
"Match": {{ quote .Match }},
"Secret": {{ quote .Secret }},
"File": "{{ .File }}",
"SymlinkFile": {{ quote .SymlinkFile }},
"Commit": {{ quote .Commit }},
"Entropy": {{ .Entropy }},
"Author": {{ quote .Author }},
"Email": {{ quote .Email }},
"Date": {{ quote .Date }},
"Message": {{ quote .Message }},
"Tags": [{{ $lastTag := (sub (len .Tags ) 1) }}{{ range $j, $tag := .Tags }}{{ quote . }}{{ if ne $j $lastTag }},{{ end }}{{ end }}],
"RuleID": {{ quote .RuleID }},
"Fingerprint": {{ quote .Fingerprint }}
}{{ if ne $i $lastFinding }},{{ end }}
{{- end}}{{ end }}
]
+5
View File
@@ -0,0 +1,5 @@
| File | Line | Secret |
|:-----|-----:|--------|
{{ range . -}}
| {{ .File }} | {{ .StartLine }} | {{ quote .Secret }} |
{{ end -}}