Compare commits

..
Author SHA1 Message Date
Zach 4a1ce8d02f Follow-up azure 2023-06-15 07:38:22 -05:00
12 changed files with 798 additions and 416 deletions

No files matched your search

+1 -1
View File
@@ -20,4 +20,4 @@ testdata/expected/report/*.got.*
# Test binary
*.out
dist/
dist/
+27 -2
View File
@@ -24,11 +24,38 @@ func main() {
configRules = append(configRules, rules.AlgoliaApiKey())
configRules = append(configRules, rules.AlibabaAccessKey())
configRules = append(configRules, rules.AlibabaSecretKey())
configRules = append(configRules, rules.AnsibleVaultToken())
configRules = append(configRules, rules.AsanaClientID())
configRules = append(configRules, rules.AsanaClientSecret())
configRules = append(configRules, rules.Atlassian())
configRules = append(configRules, rules.Authress())
configRules = append(configRules, rules.AWS())
configRules = append(configRules, rules.AzureAppServiceDeploymentSecrets())
// configRules = append(configRules, rules.AzureDevTFVCSecrets())
// configRules = append(configRules, rules.AzureDevopsPAT())
// configRules = append(configRules, rules.AzureNetworkCredential())
// configRules = append(configRules, rules.AzureNetworkCredentialSchtasks())
// configRules = append(configRules, rules.AzureNetworkCredentialDotNet())
// configRules = append(configRules, rules.AzurePasswordDecryptionkey())
// configRules = append(configRules, rules.AzurePasswordAddKey())
// configRules = append(configRules, rules.AzurePasswordConnString())
// configRules = append(configRules, rules.AzurePasswordValueString())
// configRules = append(configRules, rules.AzurePassworduidpw())
// configRules = append(configRules, rules.AzureStorageCredential43char())
// configRules = append(configRules, rules.AzureStorageCredential86char())
// configRules = append(configRules, rules.AzureStorageCredentialAccountKey())
// configRules = append(configRules, rules.AzureStorageCredentialBlobURL())
// configRules = append(configRules, rules.AzureStorageCredentialMonikerKey())
// configRules = append(configRules, rules.AzureStorageCredentialServiceBus())
// configRules = append(configRules, rules.AzureStorageCredentialSig53())
// configRules = append(configRules, rules.AzureStorageCredentialUserIDPW())
// configRules = append(configRules, rules.AzureStorageCredentialXStore())
// Below work on Regex.com but something about the internal conversion to generateUniqueTokenRegex is breaking them
//configRules = append(configRules, rules.AzurePowershellTokenCache())
//configRules = append(configRules, rules.AzurePasswordXMLCredential())
//configRules = append(configRules, rules.AzurePasswordXMLValue())
//configRules = append(configRules, rules.AzurePasswordSSISProperty())
configRules = append(configRules, rules.BitBucketClientID())
configRules = append(configRules, rules.BitBucketClientSecret())
configRules = append(configRules, rules.BittrexAccessKey())
@@ -90,8 +117,6 @@ func main() {
configRules = append(configRules, rules.Heroku())
configRules = append(configRules, rules.HubSpot())
configRules = append(configRules, rules.Intercom())
configRules = append(configRules, rules.JFrogAPIKey())
configRules = append(configRules, rules.JFrogIdentityToken())
configRules = append(configRules, rules.JWT())
configRules = append(configRules, rules.KrakenAccessToken())
configRules = append(configRules, rules.KucoinAccessToken())
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func AnsibleVaultToken() *config.Rule {
// define rule
r := config.Rule{
Description: "CSCAN0270 - Found Azure Subscription Token Cache.",
RuleID: "ansible-vault-token",
SecretGroup: 1,
Regex: generateUniqueTokenRegex(`ANSIBLE_VAULT;[0-9]\.[0-9];AES256;[\r\n]+[0-9]+`),
Keywords: []string{"ANSIBLE_VAULT;", "AES256;"},
}
// validate
tps := []string{
generateSampleSecret("ansible-vault-token",
"ANSIBLE_VAULT;1.0;AES256;\n" + secrets.NewSecret(numeric("32"))),
}
return validate(r, tps, nil)
}
+456
View File
@@ -0,0 +1,456 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
// Rules come from https://www.powershellgallery.com/packages/AzSK.AzureDevOps/0.9.8/Content/Framework%5CConfigurations%5CSVT%5CAzureDevOps%5CCredentialPatterns.xml
// Only rules with 'ContentSearchPatterns' have been used.
// CSCAN0110, CSCAN0111, CSCAN0140, CSCAN0220 searches for generic passwords - covered elsewhere
// CSCAN0120 searches for Twilio keys - covered in twilio.go
// CSCAN0210 checks for Git repo credentials - covered elsewhere
// CSCAN0230 checks for Slack tokens - covered in slack.go
// CSCAN0250 - covered in jwt.go
func AzureAppServiceDeploymentSecrets() *config.Rule {
// define rule
r := config.Rule{
Description: "CSCAN0020, CSCAN0030 - Found Azure app service deployment secrets in publish settings file.",
RuleID: "azure-app-service-deployment-secrets",
SecretGroup: 1,
Regex: generateUniqueTokenRegex(`MII[a-z0-9=_\-]{200}`),
Keywords: []string{"MII"},
}
// validate
tps := []string{
generateSampleSecret("azure-app-service-deployment-secrets",
"MII"+secrets.NewSecret(alphaNumeric("200"))),
}
return validate(r, tps, nil)
}
// TODO (zrice) needs keyword
// func AzureStorageCredential86char() *config.Rule {
// // define rule
// r := config.Rule{
// Description: "CSCAN0030, CSCAN0090, CSCAN0150 - Found Azure storage credential in source code file.",
// RuleID: "azure-storage-credential-86char",
// SecretGroup: 1,
// Regex: generateUniqueTokenRegex(`[ \t]{0,10}[a-zA-Z0-9/+]{86}==`),
// }
// // validate
// tps := []string{
// generateSampleSecret("azure-storage-credential-86char",
// secrets.NewSecret(alphaNumeric("86") + "==")),
// }
// return validate(r, tps, nil)
// }
// TODO (zrice) needs keyword
// func AzureStorageCredential43char() *config.Rule {
// // define rule
// r := config.Rule{
// Description: "CSCAN0030, CSCAN0090, CSCAN0150 - Found Azure storage credential in source code file.",
// RuleID: "azure-storage-credential-43char",
// SecretGroup: 1,
// Regex: generateUniqueTokenRegex(`[a-zA-Z0-9/+]{43}=[^{@\d%]`),
// }
// // validate
// tps := []string{
// generateSampleSecret("azure-storage-credential-43char",
// secrets.NewSecret(alphaNumeric("43") + "=a")),
// }
// return validate(r, tps, nil)
// }
// TODO (zrice) needs keyword
// func AzureStorageCredentialSig53() *config.Rule {
// // define rule
// r := config.Rule{
// Description: "CSCAN0030, CSCAN0090, CSCAN0150 - Found Azure storage credential in source code file.",
// RuleID: "azure-storage-credential-sig53",
// SecretGroup: 1,
// Regex: generateUniqueTokenRegex(`((sig|sas|password)=|>)[a-zA-Z0-9%]{43,53}%3d[^{a-zA-Z0-9%]`),
// }
// // validate
// tps := []string{
// generateSampleSecret("azure-storage-credential-sig53",
// "sig=" + secrets.NewSecret(alphaNumeric("53") + "%3D")),
// }
// return validate(r, tps, nil)
// }
// TODO (zrice) needs keyword
// func AzureStorageCredentialUserIDPW() *config.Rule {
// // define rule
// r := config.Rule{
// Description: "CSCAN0030 - Found Azure storage credential in source code file.",
// RuleID: "azure-storage-credential-useridpw",
// SecretGroup: 1,
// Regex: generateUniqueTokenRegex(`((user) ?(id|name)|uid)=.{2,128}?\s*?;\s*?((password)|(pwd))=[^'$%>@'";\[\{][^;"']{2,350}?(;|"|')`),
// }
// // validate
// tps := []string{
// generateSampleSecret("azure-storage-credential-useridpw",
// "userid=" + secrets.NewSecret(alphaNumeric("128")) + ";password=" + secrets.NewSecret(alphaNumeric("200")) + ";"),
// }
// return validate(r, tps, nil)
// }
// TODO (zrice) needs keyword
// func AzureStorageCredentialAccountKey() *config.Rule {
// // define rule
// r := config.Rule{
// Description: "CSCAN0030 - Found Azure storage credential in source code file.",
// RuleID: "azure-storage-credential-accountkey",
// SecretGroup: 1,
// Regex: generateUniqueTokenRegex(`AccountKey\s*=\s*MII[a-zA-Z0-9/+]{43,}?={0,2}`),
// }
// // validate
// tps := []string{
// generateSampleSecret("azure-storage-credential-accountkey",
// "AccountKey = MII" + secrets.NewSecret(alphaNumeric("43") + "=")),
// }
// return validate(r, tps, nil)
// }
// TODO (zrice) needs keyword
// func AzureStorageCredentialXStore() *config.Rule {
// // define rule
// r := config.Rule{
// Description: "CSCAN0100 - Found Azure storage credential in source code file.",
// RuleID: "azure-storage-credential-xstore",
// SecretGroup: 1,
// Regex: generateUniqueTokenRegex(`[<XstoreAccountInfo].*accountSharedKey\s*=\s*['"].*['"]`),
// }
// // validate
// tps := []string{
// generateSampleSecret("azure-storage-credential-xstore",
// "<XstoreAccountInfo accountName = 'John Doe' accountSharedKey='" + secrets.NewSecret(alphaNumeric("43")) + "' />"),
// }
// return validate(r, tps, nil)
// }
// TODO (zrice) needs keyword
// func AzureStorageCredentialServiceBus() *config.Rule {
// // define rule
// r := config.Rule{
// Description: "CSCAN0100 - Found Azure storage credential in source code file.",
// RuleID: "azure-storage-credential-servicebus",
// SecretGroup: 1,
// Regex: generateUniqueTokenRegex(`[<ServiceBusAccountInfo].*SharedAccessKey\s*=\s*[a-zA-Z0-9/+]{10,}['"]`),
// }
// // validate
// tps := []string{
// generateSampleSecret("azure-storage-credential-servicebus",
// "<ServiceBusAccountInfo accountName='name' connectionString='Endpoint=sb://foo.net/;SharedAccessKeyName=bar;SharedAccessKey=" + secrets.NewSecret(alphaNumeric("43")) + "' />"),
// }
// return validate(r, tps, nil)
// }
// TODO (zrice) needs keyword
// func AzureStorageCredentialMonikerKey() *config.Rule {
// // define rule
// r := config.Rule{
// Description: "CSCAN0130 - Found Azure storage credential in MonitoringAgent config file.",
// RuleID: "azure-storage-credential-monikerkey",
// SecretGroup: 1,
// Regex: generateUniqueTokenRegex(`Account moniker\s?=.*key\s?=.*`),
// }
// // validate
// tps := []string{
// generateSampleSecret("azure-storage-credential-monikerkey",
// "Account Moniker = 'John Doe' Key = '" + secrets.NewSecret(alphaNumeric("200") + "'")),
// }
// return validate(r, tps, nil)
// }
// TODO (zrice) needs keyword
// func AzureStorageCredentialBlobURL() *config.Rule {
// // define rule
// r := config.Rule{
// Description: "CSCAN0110 - Found Azure storage credential in source code file.",
// RuleID: "azure-storage-credential-bloburl",
// SecretGroup: 1,
// Regex: generateUniqueTokenRegex(`(?i)https://[a-zA-Z0-9-]+.(blob|file|queue|table|dfs|z8.web).core.windows.net/.*?sig=[a-zA-Z0-9%]{30,}`),
// }
// // validate
// tps := []string{
// generateSampleSecret("azure-storage-credential-bloburl",
// "https://myacct.blob.core.windows.net/a?sp=r&sr=b&sig=" + secrets.NewSecret(alphaNumeric("43"))),
// }
// return validate(r, tps, nil)
// }
// CSCAN0050, CSCAN0060, CSCAN0070 - covered in PrivateKey.go
// CSCAN0080 looks for 'Password' in XML file
// TODO (zrice) needs keyword
// func AzurePasswordDecryptionkey() *config.Rule {
// // define rule
// r := config.Rule{
// Description: "CSCAN0090 - Found Azure password, symmetric key or storage credential in source file.",
// RuleID: "azure-password-machinekey",
// SecretGroup: 1,
// Regex: generateUniqueTokenRegex(`(decryptionKey\s*\=\s*['"].*['"]|validationKey\s*\=\s*['"].*['"])`),
// }
// // validate
// tps := []string{
// generateSampleSecret("azure-password-machinekey",
// "<machineKey decryptionKey='" + secrets.NewSecret(alphaNumeric("43")) + "' validationKey='" + secrets.NewSecret(alphaNumeric("43")) + "' useMachineContainer='true'>"),
// }
// return validate(r, tps, nil)
// }
// TODO (zrice) needs keyword
// func AzurePasswordAddKey() *config.Rule {
// // define rule
// r := config.Rule{
// Description: "CSCAN0090 - Found Azure password, symmetric key or storage credential in source file.",
// RuleID: "azure-password-addkey",
// SecretGroup: 1,
// Regex: generateUniqueTokenRegex(`[<add].*([key](s|[0-9])?|(credential)s?|(secret)(s|S|[0-9])?|[password|token|key](primary|secondary|orsas|sas|encrypted))['"]\s*value\s*=['"].*['"]`),
// }
// // validate
// tps := []string{
// generateSampleSecret("azure-password-addkey",
// "<add key='primary' value='" + secrets.NewSecret(alphaNumeric("200") + "' >")),
// }
// return validate(r, tps, nil)
// }
// TODO (zrice) needs keyword
// func AzurePasswordConnString() *config.Rule {
// // define rule
// r := config.Rule{
// Description: "CSCAN0090 - Found Azure password, symmetric key or storage credential in source file.",
// RuleID: "azure-password-connstring",
// SecretGroup: 1,
// Regex: generateUniqueTokenRegex(`(connectionstring|connstring)[^=]*?=["'][^"']*?(password)=[^\$\s;][^"'\s]*?(;|['"])`),
// }
// // validate
// tps := []string{
// generateSampleSecret("azure-password-connstring",
// //connstring='password=secret123;Server=localhost;'
// "connstring='Server=localhost;password=" + secrets.NewSecret(alphaNumeric("23") + "'")),
// }
// return validate(r, tps, nil)
// }
// TODO (zrice) needs keyword
// func AzurePasswordValueString() *config.Rule {
// // define rule
// r := config.Rule{
// Description: "CSCAN0090 - Found Azure password, symmetric key or storage credential in source file.",
// RuleID: "azure-password-value-string",
// SecretGroup: 1,
// Regex: generateUniqueTokenRegex(`value\s?=\s?['"]((([A-Za-z0-9+/]){4}){1,200})==['"]`),
// }
// // validate
// tps := []string{
// generateSampleSecret("azure-password-value-string",
// "Value='" + secrets.NewSecret(alphaNumeric("20") + "=='")),
// }
// return validate(r, tps, nil)
// }
// TODO (zrice) needs keyword
// func AzurePassworduidpw() *config.Rule {
// // define rule
// r := config.Rule{
// Description: "CSCAN0090, CSCAN0150 - Found Azure password, symmetric key or storage credential in source file.",
// RuleID: "azure-password-uidpw",
// SecretGroup: 1,
// Regex: generateUniqueTokenRegex(`((user) ?(id|name)|uid)=.{2,128}?\s*?;\s*?((password|(pwd))=[^'$%@'";\[\{][^;"']{2,350}?(;|"|'))`),
// }
// // validate
// tps := []string{
// generateSampleSecret("azure-password-uidpw",
// `uid=testuser;pwd=` + secrets.NewSecret(alphaNumeric("86") + ";")),
// }
// return validate(r, tps, nil)
// }
// TODO: Come back to the two XML passwords below
// func AzurePasswordXMLCredential() *config.Rule {
// // define rule
// r := config.Rule{
// Description: "CSCAN0090, CSCAN0150 - Found Azure password, symmetric key or storage credential in source file.",
// RuleID: "azure-password-xml-credential",
// SecretGroup: 1,
// Regex: generateUniqueTokenRegex(`<credential>\s?name=['"][^"]*(key(s|[0-9])?|credential(s)?|secret(s|[0-9])?|password|token|key(primary|secondary|orsas|encrypted))['"](\s*value\s*=['"][^"]+['"].*?</credential>)`),
// }
// // validate
// tps := []string{
// generateSampleSecret("azure-password-xml-credential",
// "<credential>name='primary_key' value='" + secrets.NewSecret(alphaNumeric("86") + "'</credential>")),
// }
// return validate(r, tps, nil)
// }
// func AzurePasswordXMLValue() *config.Rule {
// // define rule
// r := config.Rule{
// Description: "CSCAN0090, CSCAN0150 - Found Azure password, symmetric key or storage credential in source file.",
// RuleID: "azure-password-xml-value",
// SecretGroup: 1,
// Regex: generateUniqueTokenRegex(`<setting\sname=.?password.?>.*<value>.+</value>`),
// }
// // validate
// tps := []string{
// generateSampleSecret("azure-password-xml-value",
// //<setting name='password'><value>testpassword123</value>
// "<setting name='password'><value>" + secrets.NewSecret(alphaNumeric("86") + "</value>")),
// }
// return validate(r, tps, nil)
// }
// func AzurePasswordSSISProperty() *config.Rule {
// // define rule
// r := config.Rule{
// Description: "CSCAN0090 - Found Azure password, symmetric key or storage credential in source file.",
// RuleID: "azure-password-ssis",
// SecretGroup: 1,
// Regex: generateUniqueTokenRegex(`(?s)<SSIS:Parameter\n?\s*SSIS:Name="password">.*?<SSIS:Property\n?\s*SSIS:Name="value">[^><#$\[\{\(]+</SSIS:Property>`),
// }
// // validate
// tps := []string{
// generateSampleSecret("azure-password-ssis",
// `
// This is a random text string that contains some characters>
// ` + secrets.NewSecret(alphaNumeric("86") + "==")),
// }
// return validate(r, tps, nil)
// }
// TODO (zrice) needs keyword
// func AzureNetworkCredential() *config.Rule {
// // define rule
// r := config.Rule{
// Description: "CSCAN0160 - Found Azure domain credential in source file.",
// RuleID: "azure-network-credential",
// SecretGroup: 1,
// Regex: generateUniqueTokenRegex(`NetworkCredential\((\s*).*,(\s*).*,(\s*)(corp|europe|middleeast|northamerica|southpacific|southamerica|fareast|africa|redmond|exchange|extranet|partners|extranettest|parttest|noe|ntdev|ntwksta|sys-wingroup|windeploy|wingroup|winse|segroup|xcorp|xrep|phx|gme|usme|cdocidm|mslpa)\)`),
// }
// // validate
// tps := []string{
// generateSampleSecret("azure-network-credential",
// "NetworkCredential(username, password, europe)"),
// }
// return validate(r, tps, nil)
// }
// TODO (zrice) needs keyword
// func AzureNetworkCredentialSchtasks() *config.Rule {
// // define rule
// r := config.Rule{
// Description: "CSCAN0160 - Found Azure domain credential in source file.",
// RuleID: "azure-network-credential-schtasks",
// SecretGroup: 1,
// Regex: generateUniqueTokenRegex(`schtasks.*/ru\s(corp|europe|middleeast|northamerica|southpacific|southamerica|fareast|africa|redmond|exchange|extranet|partners|extranettest|parttest|noe|ntdev|ntwksta|sys\-wingroup|windeploy|wingroup|winse|segroup|xcorp|xrep|phx|gme|usme|cdocidm|mslpa).*/rp.*`),
// }
// // validate
// tps := []string{
// generateSampleSecret("azure-network-credential-schtasks",
// `Schtasks /create /tn corp-daily-backup /tr \corp\backup.bat /ru corp\admin /rp password /sc daily`),
// }
// return validate(r, tps, nil)
// }
// TODO (zrice) needs keyword
// func AzureNetworkCredentialDotNet() *config.Rule {
// // define rule
// r := config.Rule{
// Description: "CSCAN0160 - Found Azure domain credential in source file.",
// RuleID: "azure-network-credential-dotnet",
// SecretGroup: 1,
// Regex: generateUniqueTokenRegex(`new-object\s*System.Net.NetworkCredential\(.*?,\s*['"][^"]+['"]`),
// }
// // validate
// tps := []string{
// generateSampleSecret("azure-network-credential-dotnet",
// "New-Object System.Net.NetworkCredential(username, '" + secrets.NewSecret(alphaNumeric("86")) + "')"),
// }
// return validate(r, tps, nil)
// }
// TODO (zrice) needs keyword
// func AzureDevTFVCSecrets() *config.Rule {
// // define rule
// r := config.Rule{
// Description: "CSCAN0200 - Found Azure DevDiv TFVC repo secrets.",
// RuleID: "azure-devtfvc-secrets",
// SecretGroup: 1,
// Regex: generateUniqueTokenRegex(`enc_username=.+[\n\r\s]+enc_password=.{3,}`),
// }
// // validate
// tps := []string{
// generateSampleSecret("azure-devtfvc-secrets",
// "enc_username=myusername enc_password=" + secrets.NewSecret(alphaNumeric("86"))),
// }
// return validate(r, tps, nil)
// }
// func AzureDevopsPAT() *config.Rule {
// // define rule
// r := config.Rule{
// Description: "CSCAN0240 - Found Azure Devops personal access token in source file.",
// RuleID: "azure-devops-pat",
// SecretGroup: 1,
// Regex: generateUniqueTokenRegex(`(access_token).*?['="][a-zA-Z0-9/+]{10,99}['"]`),
// }
// // validate
// tps := []string{
// generateSampleSecret("azure-devops-pat",
// "Access_token=='" + secrets.NewSecret(hex("52")) + "'"),
// }
// return validate(r, tps, nil)
// }
// func AzurePowershellTokenCache() *config.Rule {
// // define rule
// r := config.Rule{
// Description: "CSCAN0270 - Found Azure Subscription Token Cache.",
// RuleID: "azure-powershell-tokencache",
// SecretGroup: 1,
// // Below finds the example on Regex101.com! So not sure what's happening here.
// Regex: generateUniqueTokenRegex(`["']TokenCache["']\s*:\s*\{\s*["']CacheData["']\s*:\s*["'][a-zA-Z0-9/\+]{86}`),
// }
// // validate
// tps := []string{
// generateSampleSecret("azure-powershell-tokencache",
// "'TokenCache': { 'CacheData': '" + secrets.NewSecret(alphaNumeric("86")) + "'"),
// }
// return validate(r, tps, nil)
// }
+33 -32
View File
@@ -25,39 +25,40 @@ paths = [
]
{{ range $i, $rule := .Rules }}[[rules]]
{{ if and $rule.SecretGroup $rule.Entropy $rule.Allowlist.StopWords }}description = "{{$rule.Description}}"
id = "{{$rule.RuleID}}"
description = "{{$rule.Description}}"
regex = '''{{$rule.Regex}}'''
{{- with $rule.Path }}
path = '''{{ . }}'''{{ end -}}
{{- with $rule.SecretGroup }}
secretGroup = {{ . }}{{ end -}}
{{- with $rule.Entropy }}
entropy = {{ . }}{{ end -}}
{{- with $rule.Keywords }}
secretGroup = {{ $rule.SecretGroup }}
entropy = {{ $rule.Entropy}}
keywords = [
{{ range $j, $keyword := . }}"{{ $keyword }}",{{ end }}
]{{ end }}
{{- with $rule.Tags }}
tags = [
{{ range $j, $tag := . }}"{{ $tag }}",{{ end }}
]{{ end }}
{{ if or $rule.Allowlist.Regexes $rule.Allowlist.Paths $rule.Allowlist.Commits $rule.Allowlist.StopWords }}
{{ range $j, $keyword := $rule.Keywords }}"{{$keyword}}",{{end}}
]
[rules.allowlist]
{{ with $rule.Allowlist.RegexTarget }}
regexTarget = "{{ . }}"{{ end -}}
{{- with $rule.Allowlist.Regexes }}
regexes = [
{{ range $j, $regex := . }}"{{ $regex }}",{{ end }}
]{{ end }}
{{- with $rule.Allowlist.Paths }}paths = [
{{ range $j, $path := . }}"{{ $path }}",{{ end }}
]{{ end }}
{{- with $rule.Allowlist.Commits }}commits = [
{{ range $j, $commit := . }}"{{ $commit }}",{{ end }}
]{{ end }}
{{- with $rule.Allowlist.StopWords }}stopwords = [{{ range $j, $stopword := . }}
"{{ $stopword }}",{{ end }}
]{{ end }}
{{ end }}
{{ end }}
stopwords= [{{ range $j, $stopword := $rule.Allowlist.StopWords }}
"{{$stopword}}",{{end}}
]
{{ else if and $rule.SecretGroup $rule.Entropy }}description = "{{$rule.Description}}"
id = "{{$rule.RuleID}}"
regex = '''{{$rule.Regex}}'''
secretGroup = {{ $rule.SecretGroup }}
entropy = {{ $rule.Entropy}}
keywords = [
{{ range $j, $keyword := $rule.Keywords }}"{{$keyword}}",{{end}}
]
{{ else if $rule.SecretGroup }}description = "{{$rule.Description}}"
id = "{{$rule.RuleID}}"
regex = '''{{$rule.Regex}}'''
secretGroup = {{ $rule.SecretGroup }}
keywords = [
{{ range $j, $keyword := $rule.Keywords }}"{{$keyword}}",{{end}}
]
{{ else }}description = "{{$rule.Description}}"
id = "{{$rule.RuleID}}"
regex = '''{{$rule.Regex}}'''
keywords = [
{{ range $j, $keyword := $rule.Keywords }}"{{$keyword}}",{{end}}
]
{{end}}{{end}}
-67
View File
@@ -1,67 +0,0 @@
package rules
import (
"fmt"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func JFrogAPIKey() *config.Rule {
keywords := []string{"jfrog", "artifactory", "bintray", "xray"}
// Define Rule
r := config.Rule{
// Human readable description of the rule
Description: "JFrog API Key",
// Unique ID for the rule
RuleID: "jfrog-api-key",
// Regex capture group for the actual secret
SecretGroup: 1,
// Regex used for detecting secrets. See regex section below for more details
Regex: generateSemiGenericRegex(keywords, alphaNumeric("73")),
// Keywords used for string matching on fragments (think of this as a prefilter)
Keywords: keywords,
}
// validate
tps := []string{
fmt.Sprintf("--set imagePullSecretJfrog.password=%s", secrets.NewSecret(alphaNumeric("73"))),
}
return validate(r, tps, nil)
}
func JFrogIdentityToken() *config.Rule {
keywords := []string{"jfrog", "artifactory", "bintray", "xray"}
// Define Rule
r := config.Rule{
// Human readable description of the rule
Description: "JFrog Identity Token",
// Unique ID for the rule
RuleID: "jfrog-identity-token",
// Regex capture group for the actual secret
SecretGroup: 1,
// Regex used for detecting secrets. See regex section below for more details
Regex: generateSemiGenericRegex(keywords, alphaNumeric("64")),
// Keywords used for string matching on fragments (think of this as a prefilter)
Keywords: keywords,
}
// validate
tps := []string{
generateSampleSecret("jfrog", secrets.NewSecret(alphaNumeric("64"))),
generateSampleSecret("artifactory", secrets.NewSecret(alphaNumeric("64"))),
generateSampleSecret("bintray", secrets.NewSecret(alphaNumeric("64"))),
generateSampleSecret("xray", secrets.NewSecret(alphaNumeric("64"))),
}
return validate(r, tps, nil)
}
-2
View File
@@ -14,7 +14,6 @@ func PlaidAccessID() *config.Rule {
Description: "Plaid Client ID",
Regex: generateSemiGenericRegex([]string{"plaid"}, alphaNumeric("24")),
SecretGroup: 1,
Entropy: 3.5,
Keywords: []string{
"plaid",
},
@@ -34,7 +33,6 @@ func PlaidSecretKey() *config.Rule {
Description: "Plaid Secret key",
Regex: generateSemiGenericRegex([]string{"plaid"}, alphaNumeric("30")),
SecretGroup: 1,
Entropy: 3.5,
Keywords: []string{
"plaid",
},
+177 -181
View File
File diff suppressed because it is too large. Load diff
+42 -54
View File
@@ -357,85 +357,70 @@ func (d *Detector) detectRule(fragment Fragment, rule config.Rule) []report.Find
return findings
}
// DetectGit accepts source directory, log opts and GitScanType and returns a slice of report.Finding.
// GitScan accepts a *gitdiff.File channel which contents a git history generated from
// the output of `git log -p ...`. startGitScan will look at each file (patch) in the history
// and determine if the patch contains any findings.
func (d *Detector) DetectGit(source string, logOpts string, gitScanType GitScanType) ([]report.Finding, error) {
var (
diffFilesCmd *git.DiffFilesCmd
gitdiffFiles <-chan *gitdiff.File
err error
)
switch gitScanType {
case DetectType:
diffFilesCmd, err = git.NewGitLogCmd(source, logOpts)
gitdiffFiles, err = git.GitLog(source, logOpts)
if err != nil {
return d.findings, err
}
case ProtectType:
diffFilesCmd, err = git.NewGitDiffCmd(source, false)
gitdiffFiles, err = git.GitDiff(source, false)
if err != nil {
return d.findings, err
}
case ProtectStagedType:
diffFilesCmd, err = git.NewGitDiffCmd(source, true)
gitdiffFiles, err = git.GitDiff(source, true)
if err != nil {
return d.findings, err
}
}
defer diffFilesCmd.Wait()
diffFilesCh := diffFilesCmd.DiffFilesCh()
errCh := diffFilesCmd.ErrCh()
s := semgroup.NewGroup(context.Background(), 4)
// loop to range over both DiffFiles (stdout) and ErrCh (stderr)
for diffFilesCh != nil || errCh != nil {
select {
case gitdiffFile, open := <-diffFilesCh:
if !open {
diffFilesCh = nil
break
}
for gitdiffFile := range gitdiffFiles {
gitdiffFile := gitdiffFile
// skip binary files
if gitdiffFile.IsBinary || gitdiffFile.IsDelete {
// skip binary files
if gitdiffFile.IsBinary || gitdiffFile.IsDelete {
continue
}
// Check if commit is allowed
commitSHA := ""
if gitdiffFile.PatchHeader != nil {
commitSHA = gitdiffFile.PatchHeader.SHA
if d.Config.Allowlist.CommitAllowed(gitdiffFile.PatchHeader.SHA) {
continue
}
// Check if commit is allowed
commitSHA := ""
if gitdiffFile.PatchHeader != nil {
commitSHA = gitdiffFile.PatchHeader.SHA
if d.Config.Allowlist.CommitAllowed(gitdiffFile.PatchHeader.SHA) {
continue
}
}
d.addCommit(commitSHA)
s.Go(func() error {
for _, textFragment := range gitdiffFile.TextFragments {
if textFragment == nil {
return nil
}
fragment := Fragment{
Raw: textFragment.Raw(gitdiff.OpAdd),
CommitSHA: commitSHA,
FilePath: gitdiffFile.NewName,
}
for _, finding := range d.Detect(fragment) {
d.addFinding(augmentGitFinding(finding, textFragment, gitdiffFile))
}
}
return nil
})
case err, open := <-errCh:
if !open {
errCh = nil
break
}
return d.findings, err
}
d.addCommit(commitSHA)
s.Go(func() error {
for _, textFragment := range gitdiffFile.TextFragments {
if textFragment == nil {
return nil
}
fragment := Fragment{
Raw: textFragment.Raw(gitdiff.OpAdd),
CommitSHA: commitSHA,
FilePath: gitdiffFile.NewName,
}
for _, finding := range d.Detect(fragment) {
d.addFinding(augmentGitFinding(finding, textFragment, gitdiffFile))
}
}
return nil
})
}
if err := s.Wait(); err != nil {
@@ -443,6 +428,9 @@ func (d *Detector) DetectGit(source string, logOpts string, gitScanType GitScanT
}
log.Info().Msgf("%d commits scanned.", len(d.commitMap))
log.Debug().Msg("Note: this number might be smaller than expected due to commits with no additions")
if git.ErrEncountered {
return d.findings, fmt.Errorf("%s", "git error encountered, see logs")
}
return d.findings, nil
}
+30 -74
View File
@@ -2,30 +2,23 @@ package git
import (
"bufio"
"errors"
"io"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/gitleaks/go-gitdiff/gitdiff"
"github.com/rs/zerolog/log"
)
var ErrEncountered bool
// GitLog returns a channel of gitdiff.File objects from the
// git log -p command for the given source.
var quotedOptPattern = regexp.MustCompile(`^(?:"[^"]+"|'[^']+')$`)
// DiffFilesCmd helps to work with Git's output.
type DiffFilesCmd struct {
cmd *exec.Cmd
diffFilesCh <-chan *gitdiff.File
errCh <-chan error
}
// NewGitLogCmd returns `*DiffFilesCmd` with two channels: `<-chan *gitdiff.File` and `<-chan error`.
// Caller should read everything from channels until receiving a signal about their closure and call
// the `func (*DiffFilesCmd) Wait()` error in order to release resources.
func NewGitLogCmd(source string, logOpts string) (*DiffFilesCmd, error) {
func GitLog(source string, logOpts string) (<-chan *gitdiff.File, error) {
sourceClean := filepath.Clean(source)
var cmd *exec.Cmd
if logOpts != "" {
@@ -61,29 +54,21 @@ func NewGitLogCmd(source string, logOpts string) (*DiffFilesCmd, error) {
if err != nil {
return nil, err
}
go listenForStdErr(stderr)
if err := cmd.Start(); err != nil {
return nil, err
}
// HACK: to avoid https://github.com/zricethezav/gitleaks/issues/722
time.Sleep(50 * time.Millisecond)
errCh := make(chan error)
go listenForStdErr(stderr, errCh)
gitdiffFiles, err := gitdiff.Parse(stdout)
if err != nil {
return nil, err
}
return &DiffFilesCmd{
cmd: cmd,
diffFilesCh: gitdiffFiles,
errCh: errCh,
}, nil
return gitdiff.Parse(cmd, stdout)
}
// NewGitDiffCmd returns `*DiffFilesCmd` with two channels: `<-chan *gitdiff.File` and `<-chan error`.
// Caller should read everything from channels until receiving a signal about their closure and call
// the `func (*DiffFilesCmd) Wait()` error in order to release resources.
func NewGitDiffCmd(source string, staged bool) (*DiffFilesCmd, error) {
// GitDiff returns a channel of gitdiff.File objects from
// the git diff command for the given source.
func GitDiff(source string, staged bool) (<-chan *gitdiff.File, error) {
sourceClean := filepath.Clean(source)
var cmd *exec.Cmd
cmd = exec.Command("git", "-C", sourceClean, "diff", "-U0", ".")
@@ -101,50 +86,21 @@ func NewGitDiffCmd(source string, staged bool) (*DiffFilesCmd, error) {
if err != nil {
return nil, err
}
go listenForStdErr(stderr)
if err := cmd.Start(); err != nil {
return nil, err
}
// HACK: to avoid https://github.com/zricethezav/gitleaks/issues/722
time.Sleep(50 * time.Millisecond)
errCh := make(chan error)
go listenForStdErr(stderr, errCh)
gitdiffFiles, err := gitdiff.Parse(stdout)
if err != nil {
return nil, err
}
return &DiffFilesCmd{
cmd: cmd,
diffFilesCh: gitdiffFiles,
errCh: errCh,
}, nil
return gitdiff.Parse(cmd, stdout)
}
// DiffFilesCh returns a channel with *gitdiff.File.
func (c *DiffFilesCmd) DiffFilesCh() <-chan *gitdiff.File {
return c.diffFilesCh
}
// ErrCh returns a channel that could produce an error if there is something in stderr.
func (c *DiffFilesCmd) ErrCh() <-chan error {
return c.errCh
}
// Wait waits for the command to exit and waits for any copying to
// stdin or copying from stdout or stderr to complete.
//
// Wait also closes underlying stdout and stderr.
func (c *DiffFilesCmd) Wait() (err error) {
return c.cmd.Wait()
}
// listenForStdErr listens for stderr output from git, prints it to stdout,
// sends to errCh and closes it.
func listenForStdErr(stderr io.ReadCloser, errCh chan<- error) {
defer close(errCh)
var errEncountered bool
// listenForStdErr listens for stderr output from git and prints it to stdout
// then exits with exit code 1
func listenForStdErr(stderr io.ReadCloser) {
scanner := bufio.NewScanner(stderr)
for scanner.Scan() {
// if git throws one of the following errors:
@@ -170,12 +126,12 @@ func listenForStdErr(stderr io.ReadCloser, errCh chan<- error) {
log.Warn().Msg(scanner.Text())
} else {
log.Error().Msgf("[git] %s", scanner.Text())
errEncountered = true
// asynchronously set this error flag to true so that we can
// capture a log message and exit with a non-zero exit code
// This value should get set before the `git` command exits so it's
// safe-ish, although I know I know, bad practice.
ErrEncountered = true
}
}
if errEncountered {
errCh <- errors.New("stderr is not empty")
return
}
}
+1 -1
View File
@@ -5,7 +5,7 @@ go 1.19
require (
github.com/charmbracelet/lipgloss v0.5.0
github.com/fatih/semgroup v1.2.0
github.com/gitleaks/go-gitdiff v0.9.0
github.com/gitleaks/go-gitdiff v0.8.0
github.com/h2non/filetype v1.1.3
github.com/rs/zerolog v1.26.1
github.com/spf13/cobra v1.2.1
+7 -2
View File
@@ -76,8 +76,8 @@ github.com/fatih/semgroup v1.2.0/go.mod h1:1KAD4iIYfXjE4U13B48VM4z9QUwV5Tt8O4rS8
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/gitleaks/go-gitdiff v0.9.0 h1:SHAU2l0ZBEo8g82EeFewhVy81sb7JCxW76oSPtR/Nqg=
github.com/gitleaks/go-gitdiff v0.9.0/go.mod h1:pKz0X4YzCKZs30BL+weqBIG7mx0jl4tF1uXV9ZyNvrA=
github.com/gitleaks/go-gitdiff v0.8.0 h1:7aExTZm+K/M/EQKOyYcub8rIAdWK6ONxPGuRzxmWW+0=
github.com/gitleaks/go-gitdiff v0.8.0/go.mod h1:pKz0X4YzCKZs30BL+weqBIG7mx0jl4tF1uXV9ZyNvrA=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
@@ -195,10 +195,12 @@ github.com/magiconair/properties v1.8.5 h1:b6kJs+EmPFMYGkow9GiUyCyOvIwYetYJ3fSaW
github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60=
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng=
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
github.com/mattn/go-runewidth v0.0.13 h1:lTGmDsbAYt5DmK6OnoV7EuIF1wEIFAcxld6ypU4OSgU=
github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=
github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
@@ -217,6 +219,7 @@ github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lN
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/muesli/reflow v0.2.1-0.20210115123740-9e1d0d53df68 h1:y1p/ycavWjGT9FnmSjdbWUlLGvcxrY0Rw3ATltrxOhk=
github.com/muesli/reflow v0.2.1-0.20210115123740-9e1d0d53df68/go.mod h1:Xk+z4oIWdQqJzsxyjgl3P22oYZnHdZ8FFTHAQQt5BMQ=
github.com/muesli/termenv v0.11.1-0.20220204035834-5ac8409525e0 h1:STjmj0uFfRryL9fzRA/OupNppeAID6QJYPMavTL7jtY=
github.com/muesli/termenv v0.11.1-0.20220204035834-5ac8409525e0/go.mod h1:Bd5NYQ7pd+SrtBSrSNoBBmXlcY8+Xj4BMJgh8qcZrvs=
github.com/muesli/termenv v0.15.1 h1:UzuTb/+hhlBugQz28rpzey4ZuKcZ03MeKsoG7IJZIxs=
github.com/muesli/termenv v0.15.1/go.mod h1:HeAQPTzpfs016yGtA4g00CsdYnVLJvxsS4ANqrZs2sQ=
@@ -437,6 +440,8 @@ golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
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-20211110154304-99a53858aa08 h1:WecRHqgE09JBkh/584XIE6PMz5KKE/vER4izNUi30AQ=
golang.org/x/sys v0.0.0-20211110154304-99a53858aa08/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=