Compare commits

...
7 Commits
13 changed files with 164 additions and 45 deletions

No files matched your search

+1 -1
View File
@@ -2,7 +2,7 @@ FROM golang:1.23 AS build
WORKDIR /go/src/github.com/zricethezav/gitleaks
COPY . .
RUN VERSION=$(git describe --tags --abbrev=0) && \
CGO_ENABLED=0 go build -o bin/gitleaks -ldflags "-X="github.com/zricethezav/gitleaks/v8/cmd.Version=${VERSION}
CGO_ENABLED=0 go build -o bin/gitleaks -ldflags "-X=github.com/zricethezav/gitleaks/v8/cmd.Version=${VERSION}"
FROM alpine:3.19
RUN apk add --no-cache bash git openssh-client
+2
View File
@@ -235,6 +235,8 @@ useDefault = true
# or you can supply a path to a configuration. Path is relative to where gitleaks
# was invoked, not the location of the base config.
path = "common_config.toml"
# If there are any rules you don't want to inherit, they can be specified here.
disabledRules = [ "generic-api-key"]
# An array of tables that contain information that define instructions
# on how to detect secrets
+40
View File
@@ -36,6 +36,29 @@ func GCPAPIKey() *config.Rule {
Keywords: []string{
"AIza",
},
Allowlists: []config.Allowlist{
{
Regexes: []*regexp.Regexp{
// example keys from https://github.com/firebase/firebase-android-sdk
regexp.MustCompile(`AIzaSyabcdefghijklmnopqrstuvwxyz1234567`),
regexp.MustCompile(`AIzaSyAnLA7NfeLquW1tJFpx_eQCxoX-oo6YyIs`),
regexp.MustCompile(`AIzaSyCkEhVjf3pduRDt6d1yKOMitrUEke8agEM`),
regexp.MustCompile(`AIzaSyDMAScliyLx7F0NPDEJi1QmyCgHIAODrlU`),
regexp.MustCompile(`AIzaSyD3asb-2pEZVqMkmL6M9N6nHZRR_znhrh0`),
regexp.MustCompile(`AIzayDNSXIbFmlXbIE6mCzDLQAqITYefhixbX4A`),
regexp.MustCompile(`AIzaSyAdOS2zB6NCsk1pCdZ4-P6GBdi_UUPwX7c`),
regexp.MustCompile(`AIzaSyASWm6HmTMdYWpgMnjRBjxcQ9CKctWmLd4`),
regexp.MustCompile(`AIzaSyANUvH9H9BsUccjsu2pCmEkOPjjaXeDQgY`),
regexp.MustCompile(`AIzaSyA5_iVawFQ8ABuTZNUdcwERLJv_a_p4wtM`),
regexp.MustCompile(`AIzaSyA4UrcGxgwQFTfaI3no3t7Lt1sjmdnP5sQ`),
regexp.MustCompile(`AIzaSyDSb51JiIcB6OJpwwMicseKRhhrOq1cS7g`),
regexp.MustCompile(`AIzaSyBF2RrAIm4a0mO64EShQfqfd2AFnzAvvuU`),
regexp.MustCompile(`AIzaSyBcE-OOIbhjyR83gm4r2MFCu4MJmprNXsw`),
regexp.MustCompile(`AIzaSyB8qGxt4ec15vitgn44duC5ucxaOi4FmqE`),
regexp.MustCompile(`AIzaSyA8vmApnrHNFE0bApF4hoZ11srVL_n0nvY`),
},
},
},
}
// validate
@@ -49,6 +72,23 @@ func GCPAPIKey() *config.Rule {
`AIzaTesb6Tscfcni8vIpWZqNCXFDFslJtVSvFDqabcd123`, // text boundary end
`apiKey: "AIzaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"`, // not enough entropy
`AIZASYCO2CXRMC9ELSKLHLHRMBSWDEVEDZTLO2O`, // incorrect case
// example keys from https://github.com/firebase/firebase-android-sdk
`AIzaSyabcdefghijklmnopqrstuvwxyz1234567`,
`AIzaSyAnLA7NfeLquW1tJFpx_eQCxoX-oo6YyIs`,
`AIzaSyCkEhVjf3pduRDt6d1yKOMitrUEke8agEM`,
`AIzaSyDMAScliyLx7F0NPDEJi1QmyCgHIAODrlU`,
`AIzaSyD3asb-2pEZVqMkmL6M9N6nHZRR_znhrh0`,
`AIzayDNSXIbFmlXbIE6mCzDLQAqITYefhixbX4A`,
`AIzaSyAdOS2zB6NCsk1pCdZ4-P6GBdi_UUPwX7c`,
`AIzaSyASWm6HmTMdYWpgMnjRBjxcQ9CKctWmLd4`,
`AIzaSyANUvH9H9BsUccjsu2pCmEkOPjjaXeDQgY`,
`AIzaSyA5_iVawFQ8ABuTZNUdcwERLJv_a_p4wtM`,
`AIzaSyA4UrcGxgwQFTfaI3no3t7Lt1sjmdnP5sQ`,
`AIzaSyDSb51JiIcB6OJpwwMicseKRhhrOq1cS7g`,
`AIzaSyBF2RrAIm4a0mO64EShQfqfd2AFnzAvvuU`,
`AIzaSyBcE-OOIbhjyR83gm4r2MFCu4MJmprNXsw`,
`AIzaSyB8qGxt4ec15vitgn44duC5ucxaOi4FmqE`,
`AIzaSyA8vmApnrHNFE0bApF4hoZ11srVL_n0nvY`,
}
return utils.Validate(r, tps, fps)
}
+7
View File
@@ -39,6 +39,13 @@ func GenericCredential() *config.Rule {
},
Entropy: 3.5,
Allowlists: []config.Allowlist{
{
// NOTE: this is a goofy hack to get around the fact there golang's regex engine does not support positive lookaheads.
// Ideally we would want to ensure the secret contains both numbers and alphabetical characters, not just alphabetical characters.
Regexes: []*regexp.Regexp{
regexp.MustCompile(`^[a-zA-Z_.-]+$`),
},
},
{
Description: "Allowlist for Generic API Keys",
MatchCondition: config.AllowlistMatchOr,
+7 -1
View File
@@ -131,6 +131,8 @@ func GenerateSampleSecrets(identifier string, secret string) []string {
// TODO: "comment - hashtag": "#{s} is the password",
// TODO: "comment - semicolon": ";{s} is the password",
// TODO: "csv - unquoted": `{i}Token,{s},`,
"misc - comma operator": `System.setProperty("{I}_TOKEN", "{s}")`,
// TODO: "misc - comma suffix": `environmentVariables = {PATH=/usr/local/bin, ENV=/etc/bashrc, {I}_PASSWORD={s}, LC_CTYPE=en_CA.UTF-8},`, // Spotted in `./Library/Logs/gradle-kotlin-dsl-resolver-xxxx.log`
"logstash": " \"{i}Token\" => \"{s}\"",
// TODO: "sql - tabular": "|{s}|",
// TODO: "sql": "",
@@ -147,7 +149,11 @@ func GenerateSampleSecrets(identifier string, secret string) []string {
// "": "",
}
replacer := strings.NewReplacer("{i}", identifier, "{s}", secret)
replacer := strings.NewReplacer(
"{i}", identifier,
"{I}", strings.ToUpper(identifier),
"{s}", secret,
)
cases := make([]string, 0, len(samples))
for _, v := range samples {
cases = append(cases, replacer.Replace(v))
+1 -2
View File
@@ -6,7 +6,6 @@ import (
"os"
"path/filepath"
"strings"
"sync/atomic"
"time"
"github.com/rs/zerolog"
@@ -362,7 +361,7 @@ func bytesConvert(bytes uint64) string {
}
func findingSummaryAndExit(detector *detect.Detector, findings []report.Finding, exitCode int, start time.Time, err error) {
totalBytes := atomic.LoadUint64(&detector.TotalBytes)
totalBytes := detector.TotalBytes.Load()
bytesMsg := fmt.Sprintf("scanned ~%d bytes (%s)", totalBytes, bytesConvert(totalBytes))
if err == nil {
logging.Info().Msgf("%s in %s", bytesMsg, FormatDuration(time.Since(start)))
+33 -4
View File
@@ -77,9 +77,10 @@ type Config struct {
// Extend is a struct that allows users to define how they want their
// configuration extended by other configuration files.
type Extend struct {
Path string
URL string
UseDefault bool
Path string
URL string
UseDefault bool
DisabledRules []string
}
func (vc *ViperConfig) Translate() (Config, error) {
@@ -216,7 +217,7 @@ func (vc *ViperConfig) Translate() (Config, error) {
// Validate the rules after everything has been assembled (including extended configs).
if extendDepth == 0 {
for _, rule := range rulesMap {
for _, rule := range c.Rules {
if err := rule.Validate(); err != nil {
return Config{}, err
}
@@ -284,7 +285,35 @@ func (c *Config) extendURL() {
}
func (c *Config) extend(extensionConfig Config) {
// Get config name for helpful log messages.
var configName string
if c.Extend.Path != "" {
configName = c.Extend.Path
} else {
configName = "default"
}
// Convert |Config.DisabledRules| into a map for ease of access.
disabledRuleIDs := map[string]struct{}{}
for _, id := range c.Extend.DisabledRules {
if _, ok := extensionConfig.Rules[id]; !ok {
logging.Warn().
Str("rule-id", id).
Str("config", configName).
Msg("Disabled rule doesn't exist in extended config.")
}
disabledRuleIDs[id] = struct{}{}
}
for ruleID, baseRule := range extensionConfig.Rules {
// Skip the rule.
if _, ok := disabledRuleIDs[ruleID]; ok {
logging.Debug().
Str("rule-id", ruleID).
Str("config", configName).
Msg("Ignoring rule from extended config.")
continue
}
currentRule, ok := c.Rules[ruleID]
if !ok {
// Rule doesn't exist, add it to the config.
+25 -11
View File
@@ -39,8 +39,7 @@ func TestTranslate(t *testing.T) {
Regexes: []*regexp.Regexp{regexp.MustCompile("123")},
},
},
},
},
}},
},
},
{
@@ -73,8 +72,7 @@ func TestTranslate(t *testing.T) {
Regexes: []*regexp.Regexp{regexp.MustCompile("AKIALALEMEL33243OLIA")},
},
},
},
},
}},
},
},
{
@@ -92,8 +90,7 @@ func TestTranslate(t *testing.T) {
Commits: []string{"allowthiscommit"},
},
},
},
},
}},
},
},
{
@@ -111,8 +108,7 @@ func TestTranslate(t *testing.T) {
Paths: []*regexp.Regexp{regexp.MustCompile(".go")},
},
},
},
},
}},
},
},
{
@@ -122,12 +118,11 @@ func TestTranslate(t *testing.T) {
RuleID: "discord-api-key",
Description: "Discord API key",
Regex: regexp.MustCompile(`(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-h0-9]{64})['\"]`),
Keywords: []string{},
Entropy: 3.5,
SecretGroup: 3,
Keywords: []string{},
Tags: []string{},
},
},
}},
},
},
{
@@ -350,6 +345,25 @@ func TestTranslate(t *testing.T) {
},
},
},
{
cfgName: "extend_disabled",
cfg: Config{
Rules: map[string]Rule{
"aws-secret-key": {
RuleID: "aws-secret-key",
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Tags: []string{"key", "AWS"},
Keywords: []string{},
},
"pypi-upload-token": {
RuleID: "pypi-upload-token",
Regex: regexp.MustCompile(`pypi-AgEIcHlwaS5vcmc[A-Za-z0-9\-_]{50,1000}`),
Tags: []string{},
Keywords: []string{},
},
},
},
},
}
for _, tt := range tests {
+23
View File
@@ -532,6 +532,25 @@ description = "Uncovered a GCP API key, which could lead to unauthorized access
regex = '''\b(AIza[\w-]{35})(?:['|\"|\n|\r|\s|\x60|;]|$)'''
entropy = 3
keywords = ["aiza"]
[[rules.allowlists]]
regexes = [
'''AIzaSyabcdefghijklmnopqrstuvwxyz1234567''',
'''AIzaSyAnLA7NfeLquW1tJFpx_eQCxoX-oo6YyIs''',
'''AIzaSyCkEhVjf3pduRDt6d1yKOMitrUEke8agEM''',
'''AIzaSyDMAScliyLx7F0NPDEJi1QmyCgHIAODrlU''',
'''AIzaSyD3asb-2pEZVqMkmL6M9N6nHZRR_znhrh0''',
'''AIzayDNSXIbFmlXbIE6mCzDLQAqITYefhixbX4A''',
'''AIzaSyAdOS2zB6NCsk1pCdZ4-P6GBdi_UUPwX7c''',
'''AIzaSyASWm6HmTMdYWpgMnjRBjxcQ9CKctWmLd4''',
'''AIzaSyANUvH9H9BsUccjsu2pCmEkOPjjaXeDQgY''',
'''AIzaSyA5_iVawFQ8ABuTZNUdcwERLJv_a_p4wtM''',
'''AIzaSyA4UrcGxgwQFTfaI3no3t7Lt1sjmdnP5sQ''',
'''AIzaSyDSb51JiIcB6OJpwwMicseKRhhrOq1cS7g''',
'''AIzaSyBF2RrAIm4a0mO64EShQfqfd2AFnzAvvuU''',
'''AIzaSyBcE-OOIbhjyR83gm4r2MFCu4MJmprNXsw''',
'''AIzaSyB8qGxt4ec15vitgn44duC5ucxaOi4FmqE''',
'''AIzaSyA8vmApnrHNFE0bApF4hoZ11srVL_n0nvY''',
]
[[rules]]
id = "generic-api-key"
@@ -551,6 +570,10 @@ keywords = [
"token",
]
[[rules.allowlists]]
regexes = [
'''^[a-zA-Z_.-]+$''',
]
[[rules.allowlists]]
regexTarget = "match"
regexes = [
'''(?i)(accessor|access[_.-]?id|api[_.-]?(version|id)|rapid|capital|[a-z0-9-]*?api[a-z0-9-]*?:jar:|author|X-MS-Exchange-Organization-Auth|Authentication-Results|(credentials?[_.-]?id|withCredentials)|(bucket|foreign|hot|natural|primary|schema|sequence)[_.-]?key|key[_.-]?(alias|board|code|ring|selector|size|stone|storetype|word|up|down|left|right)|key(store|tab)[_.-]?(file|path)|issuerkeyhash|(?-i:[DdMm]onkey|[DM]ONKEY)|keying|(secret)[_.-]?name|UserSecretsId|(api|credentials|token)[_.-]?(endpoint|ur[il])|public[_.-]?(key|token)|(key|token)[_.-]?file)''',
+3 -15
View File
@@ -89,7 +89,7 @@ type Detector struct {
ReportPath string
Reporter report.Reporter
TotalBytes uint64
TotalBytes atomic.Uint64
}
// Fragment contains the data to be scanned
@@ -184,9 +184,9 @@ 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)))
d.TotalBytes.Add(uint64(len(fragment.Raw)))
}
atomic.AddUint64(&d.TotalBytes, uint64(len(fragment.Bytes)))
d.TotalBytes.Add(uint64(len(fragment.Bytes)))
var findings []report.Finding
@@ -431,18 +431,6 @@ MatchLoop:
// entropy is too low, skip this finding
continue
}
// NOTE: this is a goofy hack to get around the fact there golang's regex engine
// does not support positive lookaheads. Ideally we would want to add a
// restriction on generic rules regex that requires the secret match group
// contains both numbers and alphabetical characters, not just alphabetical characters.
// 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(r.RuleID, "generic") {
if !containsDigit(finding.Secret) {
continue
}
}
}
// check if the regexTarget is defined in the allowlist "regexes" entry
// or if the secret is in the list of stopwords
-11
View File
@@ -180,17 +180,6 @@ func printFinding(f report.Finding, noColor bool) {
fmt.Println("")
}
func containsDigit(s string) bool {
for _, c := range s {
switch c {
case '1', '2', '3', '4', '5', '6', '7', '8', '9':
return true
}
}
return false
}
func isWhitespace(ch byte) bool {
return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'
}
+11
View File
@@ -0,0 +1,11 @@
title = "gitleaks extend disable"
[extend]
path = "../testdata/config/extend_disabled_base.toml"
disabledRules = [
'custom-rule1'
]
[[rules]]
id = "pypi-upload-token"
regex = '''pypi-AgEIcHlwaS5vcmc[A-Za-z0-9\-_]{50,1000}'''
+11
View File
@@ -0,0 +1,11 @@
title = "gitleaks extended 3"
[[rules]]
id = "aws-secret-key"
regex = '''(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}'''
tags = ["key", "AWS"]
[[rules]]
id = "custom-rule1"
regex = '''[Cc]ustom!'''