Compare commits

...
31 Commits
Author SHA1 Message Date
Richard Gomez 43fae355e6 feat(rules): create Octopus Deploy api key (#1602) 2024-10-28 08:25:25 -05:00
Ben-grmbl a158e4fc15 fix(aws-access-token): only match if correct length (#1584)
Previously, the rule matched for any long string
containing e.g. ASIA, ACCA somewhere,
as long as the next 16 chars were also uppercase letters.

This change checks for word boundaries before and after the secret.

Also the prefix (AKIA|ASIA|...) was moved from the non-capturing group
into the secret matching group,
since it is part of the token

fix(aws-access-token): non-capture for prefix

Review findings https://github.com/gitleaks/gitleaks/pull/1584/files#r1807793907
2024-10-28 08:19:48 -05:00
Richard Gomez b6e0eeeb0a fix(config): ignore jquery/swagger w/o version (#1607) 2024-10-28 08:18:42 -05:00
Roger Meier 722e7d8e73 feat: add new GitLab tokens (#1560)
Closes #1401
2024-10-28 08:15:36 -05:00
Richard Gomez 961f2e674f feat(generic-api-key): tune false positives (#1606) 2024-10-27 19:24:06 -05:00
Zachary Rice e734fcf01d Create .gitleaks.toml (#1605) 2024-10-27 08:01:40 -05:00
Richard Gomez 7206d6bc56 feat(curl): tweak tps and fps (#1603) 2024-10-27 07:43:55 -05:00
Richard Gomez 2db25f1367 feat(config): ignore swagger-ui assets (#1604)
also, ignore public known checkmarx secret
2024-10-27 07:43:14 -05:00
Ben-grmbl e97695b852 feat(generic-api-key): exclude keywords (#1587)
* fix(config.tmpl) missing \n for rules with regexes AND stopwords

patch provided by rgmx

fix(config.tmpl) omit `condition=OR`

* feat(generic-api-key): exclude keywords

prevent matching the rule generic-api-key on e.g.
- public_key
- api_version
- client_id
- client_name
- keyword
- monkey

feat(generic-api-key): review findings

- combine capture groups
- remove mapKey from allowList

fix(generic): make monkey, donkey, case-sensitive

avoids matching on e.g. pokemonKey=

* feat(generic) remove client, add credential

exclude more composite words with key
2024-10-25 15:26:00 -05:00
Richard Gomez 0afb525e59 feat(okta): bump entropy to 4 (#1599) 2024-10-25 08:00:59 -05:00
Richard Gomez 2068870c8d feat: update global allowlist (#1597) 2024-10-24 08:17:27 -05:00
Richard Gomez 8cf93b9ad5 refactor(allowlist): deduplicate commits & keywords (#1596) 2024-10-24 07:28:55 -05:00
Richard Gomez 50c2818167 feat(config): ignore jquery static assets (#1595) 2024-10-23 07:30:48 -05:00
Richard Gomez 455ae0aab7 More rule fixes (#1586)
* feat: tweak more rules

* fix(curl): update pattern & ignore more stuff

* chore: update .gitleaksignore
2024-10-22 08:23:47 -05:00
Richard Gomez 5407c44e0c chore: log skipped symlinks (#1591) 2024-10-22 08:23:10 -05:00
Richard Gomez d03d6c401b feat: match left side of identifier (#1585) 2024-10-20 09:38:18 -05:00
Zach 851c11ab1a what secrets? 2024-10-19 19:58:07 -05:00
Richard Gomez 8cfa6b2e43 fix(rules): add entropy (#1580) 2024-10-19 19:49:36 -05:00
Richard Gomez 9152eaa57a feat(aws): add entropy & allowlist (#1582) 2024-10-19 19:47:45 -05:00
Richard Gomez 93acc6e82a feat(rules): add 1password token (#1583) 2024-10-19 19:47:07 -05:00
Richard Gomez 83a57244cd feat(config): add curl header rule (#1576) 2024-10-18 20:06:31 -05:00
Richard Gomez cf5334fd61 feat: add curl basic auth rule (#1575) 2024-10-17 19:15:30 -05:00
ReRetriever d07b394b08 Update spelling in README.md (#1574) 2024-10-17 10:53:30 -05:00
Richard Gomez 5c03fa4a3e refactor(allowlist): use iota for condition (#1569) 2024-10-16 14:59:37 -05:00
Richard Gomez 12034a71c5 refactor(config): temporarily switch to [rules.allowlist] (#1573) 2024-10-16 14:49:34 -05:00
Richard Gomez aabe381539 Define multiple allowlists per rule (#1496)
* feat: multiple rule allowlists

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

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

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

* Add tests

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

* feat(config): ignore font files

* feat(config): ignore repeated characters
2024-10-10 02:05:16 -05:00
Richard Gomez 8fb39ba8dc feat(azure): detect Azure AD client secrets (#1199) 2024-10-09 06:44:19 -05:00
Richard Gomez 14c924dd02 chore: match gitleaks.toml anywhere (#1553) 2024-10-08 09:39:44 -05:00
95 changed files with 2742 additions and 665 deletions

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
# This is NOT the default gitleaks config. The default gitleaks config is located
# here: https://github.com/gitleaks/gitleaks/blob/master/config/gitleaks.toml
# This gitleaks config extends the default config and ignores secrets located in the `cmd/generate/config/rules`
title = "Gitleaks development"
[extend]
useDefault = true
[allowlist]
paths = [
'''(^|/)cmd/generate/config/rules''',
]
+171
View File
@@ -767,3 +767,174 @@ adf617b3b4628e1160fa3d135b4c3dfd45c05e15:testdata/repos/small/api/ignoreGlobal.g
adf617b3b4628e1160fa3d135b4c3dfd45c05e15:testdata/repos/small/api/ignoreCommit.go:aws-access-token:20
f361c5ef71853923277e3f284890083bc7825205:detect/reader_test.go:aws-access-token:12
8cfa6b2e43544895f52d2e37535ccfe29a6cdfd3:cmd/generate/config/rules/infracost.go:infracost-api-token:24
8cfa6b2e43544895f52d2e37535ccfe29a6cdfd3:cmd/generate/config/rules/infracost.go:generic-api-key:29
8cfa6b2e43544895f52d2e37535ccfe29a6cdfd3:cmd/generate/config/rules/discord.go:discord-client-secret:64
8cfa6b2e43544895f52d2e37535ccfe29a6cdfd3:cmd/generate/config/rules/grafana.go:grafana-cloud-api-token:42
8cfa6b2e43544895f52d2e37535ccfe29a6cdfd3:cmd/generate/config/rules/grafana.go:grafana-service-account-token:80
9152eaa57a91d7249bd0b3c3a86b9e837072a828:detect/reader_test.go:aws-access-token:12
9152eaa57a91d7249bd0b3c3a86b9e837072a828:cmd/generate/config/rules/aws.go:aws-access-token:42
93acc6e82adb46ef442fcb44bd9fd83489690ca3:cmd/generate/config/rules/1password.go:1password-service-account-token:25
93acc6e82adb46ef442fcb44bd9fd83489690ca3:cmd/generate/config/rules/1password.go:1password-service-account-token:27
93acc6e82adb46ef442fcb44bd9fd83489690ca3:cmd/generate/config/rules/1password.go:1password-service-account-token:28
93acc6e82adb46ef442fcb44bd9fd83489690ca3:cmd/generate/config/rules/1password.go:generic-api-key:37
83a57244cdd0bfe1634326ab04a29b9b139bf158:cmd/generate/config/rules/curl.go:openai-api-key:125
83a57244cdd0bfe1634326ab04a29b9b139bf158:cmd/generate/config/rules/curl.go:curl-auth-header:100
83a57244cdd0bfe1634326ab04a29b9b139bf158:cmd/generate/config/rules/curl.go:curl-auth-header:102
83a57244cdd0bfe1634326ab04a29b9b139bf158:cmd/generate/config/rules/curl.go:curl-auth-header:108
83a57244cdd0bfe1634326ab04a29b9b139bf158:cmd/generate/config/rules/curl.go:curl-auth-header:112
83a57244cdd0bfe1634326ab04a29b9b139bf158:cmd/generate/config/rules/curl.go:curl-auth-header:121
83a57244cdd0bfe1634326ab04a29b9b139bf158:cmd/generate/config/rules/curl.go:curl-auth-header:122
83a57244cdd0bfe1634326ab04a29b9b139bf158:cmd/generate/config/rules/curl.go:curl-auth-header:123
83a57244cdd0bfe1634326ab04a29b9b139bf158:cmd/generate/config/rules/curl.go:curl-auth-header:126
83a57244cdd0bfe1634326ab04a29b9b139bf158:cmd/generate/config/rules/curl.go:curl-auth-header:131
83a57244cdd0bfe1634326ab04a29b9b139bf158:cmd/generate/config/rules/curl.go:curl-auth-header:134
83a57244cdd0bfe1634326ab04a29b9b139bf158:cmd/generate/config/rules/curl.go:curl-auth-header:137
83a57244cdd0bfe1634326ab04a29b9b139bf158:cmd/generate/config/rules/curl.go:curl-auth-header:137
83a57244cdd0bfe1634326ab04a29b9b139bf158:cmd/generate/config/rules/curl.go:generic-api-key:139
83a57244cdd0bfe1634326ab04a29b9b139bf158:cmd/generate/config/rules/curl.go:jwt:134
83a57244cdd0bfe1634326ab04a29b9b139bf158:cmd/generate/config/rules/curl.go:jwt:170
cf5334fd61d16fb4af1362856ebfb98397c5d4b3:cmd/generate/config/rules/curl.go:curl-auth-user:32
cf5334fd61d16fb4af1362856ebfb98397c5d4b3:cmd/generate/config/rules/curl.go:curl-auth-user:33
cf5334fd61d16fb4af1362856ebfb98397c5d4b3:cmd/generate/config/rules/curl.go:curl-auth-user:40
cf5334fd61d16fb4af1362856ebfb98397c5d4b3:cmd/generate/config/rules/curl.go:curl-auth-user:42
cf5334fd61d16fb4af1362856ebfb98397c5d4b3:cmd/generate/config/rules/curl.go:curl-auth-user:43
cf5334fd61d16fb4af1362856ebfb98397c5d4b3:cmd/generate/config/rules/curl.go:curl-auth-user:44
cf5334fd61d16fb4af1362856ebfb98397c5d4b3:cmd/generate/config/rules/curl.go:curl-auth-user:45
aabe3815394d24d5b8198ba6068a99e0ba7601b1:config/config_test.go:aws-access-token:72
b9f7fdaacb9e3799a9b3e4f7f6181963b8931b73:config/config_test.go:aws-access-token:67
3ef444d24677c863bb724fa406dd12464b7f2362:config/config_test.go:aws-access-token:39
8fb39ba8dc9d872d57cc3151b3750e8234b9b980:cmd/generate/config/rules/azure.go:azure-ad-client-secret:33
2278a2a97e422c8075207d17195b29e7f4ff15e1:detect/decoder_test.go:generic-api-key:22
2278a2a97e422c8075207d17195b29e7f4ff15e1:detect/decoder_test.go:generic-api-key:32
2278a2a97e422c8075207d17195b29e7f4ff15e1:detect/decoder_test.go:generic-api-key:37
2278a2a97e422c8075207d17195b29e7f4ff15e1:detect/decoder_test.go:generic-api-key:54
2278a2a97e422c8075207d17195b29e7f4ff15e1:detect/decoder_test.go:generic-api-key:59
2278a2a97e422c8075207d17195b29e7f4ff15e1:detect/decoder_test.go:generic-api-key:64
2278a2a97e422c8075207d17195b29e7f4ff15e1:detect/detect_test.go:private-key:23
2278a2a97e422c8075207d17195b29e7f4ff15e1:detect/detect_test.go:generic-api-key:39
2278a2a97e422c8075207d17195b29e7f4ff15e1:detect/detect_test.go:jwt:32
2278a2a97e422c8075207d17195b29e7f4ff15e1:detect/detect_test.go:private-key:365
2278a2a97e422c8075207d17195b29e7f4ff15e1:detect/detect_test.go:private-key:366
2278a2a97e422c8075207d17195b29e7f4ff15e1:detect/detect_test.go:private-key:368
2278a2a97e422c8075207d17195b29e7f4ff15e1:detect/detect_test.go:private-key:393
2278a2a97e422c8075207d17195b29e7f4ff15e1:detect/detect_test.go:private-key:394
2278a2a97e422c8075207d17195b29e7f4ff15e1:detect/detect_test.go:aws-access-token:407
2278a2a97e422c8075207d17195b29e7f4ff15e1:detect/detect_test.go:aws-access-token:408
2278a2a97e422c8075207d17195b29e7f4ff15e1:detect/detect_test.go:generic-api-key:452
f8dcd838da26f591c70acbbc3dea8d8b4d1649c7:detect/detect_test.go:generic-api-key:616
f8dcd838da26f591c70acbbc3dea8d8b4d1649c7:detect/detect_test.go:generic-api-key:618
f8dcd838da26f591c70acbbc3dea8d8b4d1649c7:testdata/repos/nogit/.env.prod:generic-api-key:4
032c47e7e1ebfb745d3b66ef448697d4cbf6a406:detect/detect_test.go:generic-api-key:38
032c47e7e1ebfb745d3b66ef448697d4cbf6a406:detect/detect_test.go:generic-api-key:451
6c5e01c144b3d5e48422ab66a353f4cbdc14b24a:detect/detect_test.go:private-key:22
6c5e01c144b3d5e48422ab66a353f4cbdc14b24a:detect/detect_test.go:jwt:31
6c5e01c144b3d5e48422ab66a353f4cbdc14b24a:detect/decoder_test.go:generic-api-key:22
6c5e01c144b3d5e48422ab66a353f4cbdc14b24a:detect/decoder_test.go:generic-api-key:32
6c5e01c144b3d5e48422ab66a353f4cbdc14b24a:detect/decoder_test.go:generic-api-key:37
6c5e01c144b3d5e48422ab66a353f4cbdc14b24a:detect/decoder_test.go:generic-api-key:54
6c5e01c144b3d5e48422ab66a353f4cbdc14b24a:detect/decoder_test.go:generic-api-key:59
6c5e01c144b3d5e48422ab66a353f4cbdc14b24a:detect/decoder_test.go:generic-api-key:64
6c5e01c144b3d5e48422ab66a353f4cbdc14b24a:detect/detect_test.go:private-key:359
6c5e01c144b3d5e48422ab66a353f4cbdc14b24a:detect/detect_test.go:private-key:360
6c5e01c144b3d5e48422ab66a353f4cbdc14b24a:detect/detect_test.go:private-key:362
6c5e01c144b3d5e48422ab66a353f4cbdc14b24a:detect/detect_test.go:private-key:387
6c5e01c144b3d5e48422ab66a353f4cbdc14b24a:detect/detect_test.go:private-key:388
6c5e01c144b3d5e48422ab66a353f4cbdc14b24a:detect/detect_test.go:aws-access-token:401
6c5e01c144b3d5e48422ab66a353f4cbdc14b24a:detect/detect_test.go:aws-access-token:402
78f7d3f5dfba03f816418f987ff3a78643c1eda7:cmd/generate/config/rules/flyio.go:flyio-access-token:26
78f7d3f5dfba03f816418f987ff3a78643c1eda7:cmd/generate/config/rules/flyio.go:flyio-access-token:30
78f7d3f5dfba03f816418f987ff3a78643c1eda7:cmd/generate/config/rules/flyio.go:flyio-access-token:34
78f7d3f5dfba03f816418f987ff3a78643c1eda7:cmd/generate/config/rules/flyio.go:flyio-access-token:37
78f7d3f5dfba03f816418f987ff3a78643c1eda7:cmd/generate/config/rules/flyio.go:flyio-access-token:38
3698060a2bcf926b8ae459270d9bcb7b69339104:cmd/generate/config/rules/kubernetes.go:generic-api-key:56
3698060a2bcf926b8ae459270d9bcb7b69339104:cmd/generate/config/rules/kubernetes.go:generic-api-key:68
3698060a2bcf926b8ae459270d9bcb7b69339104:cmd/generate/config/rules/kubernetes.go:generic-api-key:79
3698060a2bcf926b8ae459270d9bcb7b69339104:cmd/generate/config/rules/kubernetes.go:generic-api-key:147
3698060a2bcf926b8ae459270d9bcb7b69339104:cmd/generate/config/rules/kubernetes.go:generic-api-key:153
3698060a2bcf926b8ae459270d9bcb7b69339104:cmd/generate/config/rules/kubernetes.go:generic-api-key:162
5740eddd75b2a1149374438afe80c7cf2535b35f:README.md:aws-access-token:221
5740eddd75b2a1149374438afe80c7cf2535b35f:README.md:aws-access-token:223
5740eddd75b2a1149374438afe80c7cf2535b35f:README.md:aws-access-token:259
5740eddd75b2a1149374438afe80c7cf2535b35f:cmd/generate/config/rules/generic.go:clojars-api-token:42
372d99cfdb92a1e177badbfc1cd65bd692df9025:cmd/generate/config/rules/hashicorp.go:hashicorp-tf-api-token:24
372d99cfdb92a1e177badbfc1cd65bd692df9025:cmd/generate/config/rules/vault.go:vault-service-token:22
372d99cfdb92a1e177badbfc1cd65bd692df9025:cmd/generate/config/rules/vault.go:vault-service-token:25
3be7faa1ffc80f1aa071192a09141d5e829e1af3:cmd/generate/config/rules/vault.go:vault-service-token:22
3be7faa1ffc80f1aa071192a09141d5e829e1af3:cmd/generate/config/rules/hashicorp.go:hashicorp-tf-api-token:24
3be7faa1ffc80f1aa071192a09141d5e829e1af3:cmd/generate/config/rules/vault.go:vault-service-token:25
840c3cb24dcf14bf3332793f0702e75085ff5de2:detect/verify_test.go:generic-api-key:39
840c3cb24dcf14bf3332793f0702e75085ff5de2:detect/verify_test.go:generic-api-key:47
840c3cb24dcf14bf3332793f0702e75085ff5de2:detect/verify_test.go:generic-api-key:88
c1345e1b2b63260d860637530ba4d17571d547d6:cmd/generate/config/rules/openshift.go:openshift-user-token:27
c1345e1b2b63260d860637530ba4d17571d547d6:cmd/generate/config/rules/openshift.go:openshift-user-token:28
821b2323940b1792d9001d0812a2a4f7480a69c0:cmd/generate/config/rules/cloudflare.go:cloudflare-origin-ca-key:20
821b2323940b1792d9001d0812a2a4f7480a69c0:cmd/generate/config/rules/cloudflare.go:cloudflare-origin-ca-key:21
e265bfbbc3b208a23f0e46dd4a96795817068b77:detect/validate_test.go:generic-api-key:93
9d06c40017ba6710032e9bc08ebbc056175629cf:detect/validate_test.go:github-pat:33
9d06c40017ba6710032e9bc08ebbc056175629cf:detect/validate_test.go:github-pat:36
9d06c40017ba6710032e9bc08ebbc056175629cf:detect/validate_test.go:generic-api-key:43
9d06c40017ba6710032e9bc08ebbc056175629cf:detect/validate_test.go:generic-api-key:49
9d06c40017ba6710032e9bc08ebbc056175629cf:detect/validate_test.go:generic-api-key:57
e9135cf0b598738b5fc63ca004db8ab30845393d:cmd/generate/config/rules/jwt.go:jwt:48
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-organization-api-token:85
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-organization-api-token:86
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-organization-api-token:87
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-organization-api-token:88
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-organization-api-token:89
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-organization-api-token:90
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-organization-api-token:91
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-organization-api-token:93
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-organization-api-token:95
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-organization-api-token:96
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-organization-api-token:97
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-access-token:30
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-access-token:31
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-access-token:32
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-access-token:33
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-access-token:34
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-access-token:35
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-access-token:36
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-access-token:37
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-access-token:38
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-access-token:39
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-access-token:40
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-access-token:41
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-access-token:42
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-access-token:43
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-access-token:45
9fb36b242d75aac1a2bf885724dfd9886db08ea7:cmd/generate/config/rules/huggingface.go:huggingface-access-token:46
463d24618fa42fc7629dc30c9744ebe36c5df1ab:cmd/generate/config/rules/slack.go:slack-user-token:66
463d24618fa42fc7629dc30c9744ebe36c5df1ab:cmd/generate/config/rules/slack.go:slack-config-access-token:115
463d24618fa42fc7629dc30c9744ebe36c5df1ab:cmd/generate/config/rules/slack.go:slack-legacy-workspace-token:210
025908808f2ad1ce244f9806b8dd593bd9afbab0:detect/detect_test.go:discord-api-token:326
e002920355ac91770a329cfa69d6359bd665ba66:cmd/generate/config/rules/privatekey.go:private-key:26
e890a8e8098ee8021d25a429315a6c153126db22:cmd/generate/config/rules/jwt.go:jwt:17
9326f35380636bcbe61e94b0584d1618c4b5c2c2:detect/detect_test.go:pypi-upload-token:27
9326f35380636bcbe61e94b0584d1618c4b5c2c2:detect/detect_test.go:pypi-upload-token:32
9326f35380636bcbe61e94b0584d1618c4b5c2c2:detect/detect_test.go:pypi-upload-token:33
3a3e13c3b5f85b0116cf2a0cd92529baf22d0ac9:testdata/repos/with_square_and_google/env:gcp-api-key:3
45c898c5ea56ee503a048c1bac1404cf63855edc:test_data/test_repos/test_dir_2/env:gcp-api-key:3
45c898c5ea56ee503a048c1bac1404cf63855edc:test_data/test_dir_one_google_leak_and_square_leak.json:gcp-api-key:20
45c898c5ea56ee503a048c1bac1404cf63855edc:test_data/test_dir_one_google_leak_and_square_leak.json:gcp-api-key:22
f6460a7365479a48581e0641b40147914542bb24:test_data/test_local_owner_aws_leak_depth_2.json:aws-access-token:16
f6460a7365479a48581e0641b40147914542bb24:test_data/test_local_owner_aws_leak_depth_2.json:aws-access-token:17
f6460a7365479a48581e0641b40147914542bb24:test_data/test_local_owner_aws_leak_depth_2.json:aws-access-token:42
f6460a7365479a48581e0641b40147914542bb24:test_data/test_local_owner_aws_leak_depth_2.json:aws-access-token:43
f6460a7365479a48581e0641b40147914542bb24:test_data/test_local_owner_aws_leak_depth_2.json:aws-access-token:68
f6460a7365479a48581e0641b40147914542bb24:test_data/test_local_owner_aws_leak_depth_2.json:aws-access-token:69
f6460a7365479a48581e0641b40147914542bb24:test_data/test_local_owner_aws_leak_depth_2.json:aws-access-token:94
f6460a7365479a48581e0641b40147914542bb24:test_data/test_local_owner_aws_leak_depth_2.json:aws-access-token:95
7bd55e33b504f76fc2aec27f4f479a5fb2606480:src/constants.go:private-key:42
e79ffc6ae8f66931d687407e07bc0632fb262091:src/constants.go:private-key:29
2b995fda446e03b7660c327fec41265f03199c71:config.go:private-key:34
ccef3680d5552443c999345567ea60909c863c0a:checks_test.go:aws-access-token:52
1cecd5e0908ab581f217ebb2cb58829204530c79:README.md:aws-access-token:25
1cecd5e0908ab581f217ebb2cb58829204530c79:README.md:aws-access-token:27
e56870aecf8ac2733affc82e1ac25e3be9092db3:cmd/generate/config/rules/curl.go:generic-api-key:116
239e6323639b18ba8a1081f17788a658da075dd7:cmd/generate/config/rules/sumologic.go:sumologic-access-token:72
239e6323639b18ba8a1081f17788a658da075dd7:cmd/generate/config/rules/sumologic.go:sumologic-access-id:40
239e6323639b18ba8a1081f17788a658da075dd7:cmd/generate/config/rules/readme.go:readme-api-token:26
239e6323639b18ba8a1081f17788a658da075dd7:cmd/generate/config/rules/prefect.go:prefect-api-token:26
239e6323639b18ba8a1081f17788a658da075dd7:cmd/generate/config/rules/databricks.go:databricks-api-token:25
239e6323639b18ba8a1081f17788a658da075dd7:cmd/generate/config/rules/databricks.go:generic-api-key:22
+42 -37
View File
@@ -252,13 +252,6 @@ description = "awesome rule 1"
# does not support lookaheads.
regex = '''one-go-style-regex-for-this-rule'''
# Golang regular expression used to match paths. This can be used as a standalone rule or it can be used
# in conjunction with a valid `regex` entry.
path = '''a-file-path-regex'''
# Array of strings used for metadata and reporting purposes.
tags = ["tag","another tag"]
# Int used to extract secret from regex match and used as the group that will have
# its entropy checked if `entropy` is set.
secretGroup = 3
@@ -266,10 +259,14 @@ secretGroup = 3
# Float representing the minimum shannon entropy a regex group must have to be considered a secret.
entropy = 3.5
# Golang regular expression used to match paths. This can be used as a standalone rule or it can be used
# in conjunction with a valid `regex` entry.
path = '''a-file-path-regex'''
# Keywords are used for pre-regex check filtering. Rules that contain
# keywords will perform a quick string compare check to make sure the
# keyword(s) are in the content being scanned. Ideally these values should
# either be part of the idenitifer or unique strings specific to the rule's regex
# either be part of the identiifer or unique strings specific to the rule's regex
# (introduced in v8.6.0)
keywords = [
"auth",
@@ -277,29 +274,40 @@ keywords = [
"token",
]
# You can include an allowlist table for a single rule to reduce false positives or ignore commits
# with known/rotated secrets
[rules.allowlist]
description = "ignore commit A"
commits = [ "commit-A", "commit-B"]
paths = [
'''go\.mod''',
'''go\.sum'''
]
# note: (rule) regexTarget defaults to check the _Secret_ in the finding.
# if regexTarget is not specified then _Secret_ will be used.
# Acceptable values for regexTarget are "match" and "line"
regexTarget = "match"
regexes = [
'''process''',
'''getenv''',
]
# note: stopwords targets the extracted secret, not the entire regex match
# like 'regexes' does. (stopwords introduced in 8.8.0)
stopwords = [
'''client''',
'''endpoint''',
]
# Array of strings used for metadata and reporting purposes.
tags = ["tag","another tag"]
# ⚠️ In v8.21.0 `[rules.allowlist]` was replaced with `[[rules.allowlists]]`.
# This change was backwards-compatible: instances of `[rules.allowlist]` still work.
#
# You can define multiple allowlists for a rule to reduce false positives.
# A finding will be ignored if _ANY_ `[[rules.allowlists]]` matches.
[[rules.allowlists]]
description = "ignore commit A"
# When multiple criteria are defined the default condition is "OR".
# e.g., this can match on |commits| OR |paths| OR |stopwords|.
condition = "OR"
commits = [ "commit-A", "commit-B"]
paths = [
'''go\.mod''',
'''go\.sum'''
]
# note: stopwords targets the extracted secret, not the entire regex match
# like 'regexes' does. (stopwords introduced in 8.8.0)
stopwords = [
'''client''',
'''endpoint''',
]
[[rules.allowlists]]
# The "AND" condition can be used to make sure all criteria match.
# e.g., this matches if |regexes| AND |paths| are satisfied.
condition = "AND"
# note: |regexes| defaults to check the _Secret_ in the finding.
# Acceptable values for |regexTarget| are "secret" (default), "match", and "line".
regexTarget = "match"
regexes = [ '''(?i)parseur[il]''' ]
paths = [ '''package-lock\.json''' ]
# You can extend a particular rule from the default config. e.g., gitlab-pat
# if you have defined a custom token prefix on your GitLab instance
@@ -307,11 +315,9 @@ stopwords = [
id = "gitlab-pat"
# all the other attributes from the default rule are inherited
[rules.allowlist]
regexTarget = "line"
regexes = [
'''MY-glpat-''',
]
[[rules.allowlists]]
regexTarget = "line"
regexes = [ '''MY-glpat-''' ]
# This is a global allowlist which has a higher order of precedence than rule-specific allowlists.
# If a commit listed in the `commits` field below is encountered then that commit will be skipped and no
@@ -328,7 +334,6 @@ paths = [
# if regexTarget is not specified then _Secret_ will be used.
# Acceptable values for regexTarget are "match" and "line"
regexTarget = "match"
regexes = [
'''219-09-9999''',
'''078-05-1120''',
+41 -18
View File
@@ -1,8 +1,10 @@
package base
import (
"fmt"
"github.com/zricethezav/gitleaks/v8/config"
"regexp"
"strings"
)
func CreateGlobalConfig() config.Config {
@@ -13,6 +15,27 @@ func CreateGlobalConfig() config.Config {
Regexes: []*regexp.Regexp{
// ----------- General placeholders -----------
regexp.MustCompile(`(?i)^true|false|null$`),
// Awkward workaround to detect repeated characters.
func() *regexp.Regexp {
var (
letters = "abcdefghijklmnopqrstuvwxyz*."
patterns []string
)
for _, char := range letters {
if char == '*' || char == '.' {
patterns = append(patterns, fmt.Sprintf("\\%c+", char))
} else {
patterns = append(patterns, fmt.Sprintf("%c+", char))
}
}
return regexp.MustCompile("^(?i:" + strings.Join(patterns, "|") + ")$")
}(),
// ----------- Environment Variables -----------
regexp.MustCompile(`^\$(\d+|{\d+})$`),
regexp.MustCompile(`^\$([A-Z_]+|[a-z_]+)$`),
regexp.MustCompile(`^\${([A-Z_]+|[a-z_]+)}$`),
// ----------- Interpolated Variables -----------
// Ansible (https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_variables.html)
regexp.MustCompile(`^\{\{[ \t]*[\w ().|]+[ \t]*}}$`),
@@ -22,19 +45,20 @@ func CreateGlobalConfig() config.Config {
regexp.MustCompile(`^\$\{\{[ \t]*((env|github|secrets|vars)(\.[A-Za-z]\w+)+[\w "'&./=|]*)[ \t]*}}$`),
// NuGet (https://learn.microsoft.com/en-us/nuget/reference/nuget-config-file#using-environment-variables)
regexp.MustCompile(`^%([A-Z_]+|[a-z_]+)%$`),
// String formatting.
regexp.MustCompile(`^%[+\-# 0]?[bcdeEfFgGoOpqstTUvxX]$`), // Golang (https://pkg.go.dev/fmt)
regexp.MustCompile(`^\{\d{0,2}}$`), // Python (https://docs.python.org/3/tutorial/inputoutput.html)
// Urban Code Deploy (https://www.ibm.com/support/pages/replace-token-step-replaces-replacement-values-windows-variables)
regexp.MustCompile(`^@([A-Z_]+|[a-z_]+)@$`),
// ----------- Environment Variables -----------
regexp.MustCompile(`^\$(\d+|{\d+})$`),
regexp.MustCompile(`^\$([A-Z_]+|[a-z_]+)$`),
regexp.MustCompile(`^\${([A-Z_]+|[a-z_]+)}$`),
// ----------- Miscellaneous -----------
},
Paths: []*regexp.Regexp{
regexp.MustCompile(`^gitleaks\.toml$`),
regexp.MustCompile(`gitleaks\.toml`),
// ----------- Documents and media -----------
regexp.MustCompile(`(?i)\.(bmp|gif|jpe?g|svg|tiff?)$`),
regexp.MustCompile(`(?i)\.(bmp|gif|jpe?g|svg|tiff?)$`), // Images
regexp.MustCompile(`\.(eot|[ot]tf|woff2?)$`), // Fonts
regexp.MustCompile(`(.*?)(doc|docx|zip|xls|pdf|bin|socket|vsidx|v2|suo|wsuo|.dll|pdb|exe|gltf)$`),
// ----------- Golang files -----------
@@ -49,7 +73,7 @@ func CreateGlobalConfig() config.Config {
regexp.MustCompile(`(^|/)mvnw(\.cmd)?$`),
regexp.MustCompile(`(^|/)\.mvn/wrapper/MavenWrapperDownloader\.java$`),
// ----------- Node.js files -----------
// ----------- JavaScript files -----------
// Dependencies and lock files.
regexp.MustCompile(`(^|/)node_modules/.*?$`),
regexp.MustCompile(`(^|/)package-lock\.json$`),
@@ -57,21 +81,15 @@ func CreateGlobalConfig() config.Config {
regexp.MustCompile(`(^|/)pnpm-lock\.yaml$`),
regexp.MustCompile(`(^|/)npm-shrinkwrap\.json$`),
regexp.MustCompile(`(^|/)bower_components/.*?$`),
// TODO: Add more common static assets, such as swagger-ui.
regexp.MustCompile(`(^|/)(jquery(-?ui)?|swagger-?ui)[a-zA-Z0-9.-]+\.js(\.map)?$`),
// ----------- Python files -----------
// Dependencies and lock files.
regexp.MustCompile(`(^|/)Pipfile\.lock$`),
regexp.MustCompile(`(^|/)poetry\.lock$`),
regexp.MustCompile(`(^|/)(Pipfile|poetry)\.lock$`),
// Virtual environments
// env/lib/python3.7/site-packages/urllib3/util/url.py
regexp.MustCompile(`(?i)/?(v?env|virtualenv)/lib/.+$`),
// /python/3.7.4/Lib/site-packages/dask/bytes/tests/test_bytes_utils.py
// python/3.7.4/Lib/site-packages/fsspec/utils.py
// python/2.7.16.32/Lib/bsddb/test/test_dbenv.py
regexp.MustCompile(`(?i)/?python/[23](\.\d{1,2})+/lib/.+$`),
// python/lib/python3.8/site-packages/boto3/data/ec2/2016-04-01/resources-1.json
// python/lib/python3.8/site-packages/botocore/data/alexaforbusiness/2017-11-09/service-2.json
regexp.MustCompile(`(?i)/?python/lib/python[23](\.\d{1,2})+/.+$`),
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/.+$`),
@@ -84,6 +102,11 @@ func CreateGlobalConfig() config.Config {
regexp.MustCompile(`Database.refactorlog`),
//regexp.MustCompile(`vendor`),
},
StopWords: []string{
// ----------- Secrets -----------
// Checkmarx client secret. (https://github.com/checkmarx-ts/checkmarx-python-sdk/blob/86560f6e2a3e46d16322101294da10d5d190312d/README.md?plain=1#L56)
"014df517-39d1-4453-b7b3-9930c563627c",
},
},
}
}
+77 -4
View File
@@ -14,6 +14,16 @@ func TestConfigAllowlistRegexes(t *testing.T) {
`true`, `True`, `false`, `False`, `null`, `NULL`,
},
},
"general placeholders - repeated characters": {
invalid: []string{
`aaaaaaaaaaaaaaaaa`, `BBBBBBBBBBbBBBBBBBbBB`, `********************`,
},
valid: []string{`aaaaaaaaaaaaaaaaaaabaa`, `pas*************d`},
},
"environment variables": {
invalid: []string{`$2`, `$GIT_PASSWORD`, `${GIT_PASSWORD}`, `$password`},
valid: []string{`$yP@R.@=ibxI`, `$2a6WCust9aE`, `${not_complete1`},
},
"interpolated variables - ansible": {
invalid: []string{
`{{ x }}`, `{{ password }}`, `{{password}}`, `{{ data.proxy_password }}`,
@@ -39,14 +49,20 @@ func TestConfigAllowlistRegexes(t *testing.T) {
`%MY_PASSWORD%`, `%password%`,
},
},
"interpolated variables - string fmt - golang": {
invalid: []string{
`%b`, `%c`, `%d`, `% d`, `%e`, `%E`, `%f`, `%F`, `%g`, `%G`, `%o`, `%O`, `%p`, `%q`, `%-s`, `%s`, `%t`, `%T`, `%U`, `%#U`, `%+v`, `%#v`, `%v`, `%x`, `%X`,
},
},
"interpolated variables - string fmt - python": {
invalid: []string{
`{}`, `{0}`, `{10}`,
},
},
"interpolated variables - ucd": {
invalid: []string{`@password@`, `@LDAP_PASS@`},
valid: []string{`@username@mastodon.example`},
},
"environment variables": {
invalid: []string{`$2`, `$GIT_PASSWORD`, `${GIT_PASSWORD}`, `$password`},
valid: []string{`$yP@R.@=ibxI`, `$2a6WCust9aE`, `${not_complete1`},
},
}
cfg := CreateGlobalConfig()
@@ -67,3 +83,60 @@ func TestConfigAllowlistRegexes(t *testing.T) {
})
}
}
func TestConfigAllowlistPaths(t *testing.T) {
tests := map[string]struct {
invalid []string
valid []string
}{
"javascript - common static assets": {
invalid: []string{
`src/main/resources/static/jquery-ui-1.12.1/jquery-ui-min.js`,
`src/main/resources/static/js/jquery-ui-1.10.4.min.js`,
`swagger/swaggerui/swagger-ui-bundle.js.map`,
`swagger/swaggerui/swagger-ui-es-bundle.js.map`,
`src/main/static/swagger-ui.min.js`,
},
},
"python": {
invalid: []string{
// lock files
`Pipfile.lock`, `poetry.lock`,
// virtual environments
"env/lib/python3.7/site-packages/urllib3/util/url.py",
"venv/Lib/site-packages/regex-2018.08.29.dist-info/DESCRIPTION.rst",
"venv/lib64/python3.5/site-packages/pynvml.py",
"python/python3/virtualenv/Lib/site-packages/pyphonetics/utils.py",
"virtualenv/lib64/python3.7/base64.py",
// packages
"cde-root/usr/lib64/python2.4/site-packages/Numeric.pth",
"lib/python3.9/site-packages/setuptools/_distutils/msvccompiler.py",
"lib/python3.8/site-packages/botocore/data/alexaforbusiness/2017-11-09/service-2.json",
"code/python/3.7.4/Lib/site-packages/dask/bytes/tests/test_bytes_utils.py",
"python/3.7.4/Lib/site-packages/fsspec/utils.py",
"python/2.7.16.32/Lib/bsddb/test/test_dbenv.py",
"python/lib/python3.8/site-packages/boto3/data/ec2/2016-04-01/resources-1.json",
// distinfo
"libs/PyX-0.15.dist-info/AUTHORS",
},
},
}
cfg := CreateGlobalConfig()
allowlist := cfg.Allowlist
for name, cases := range tests {
t.Run(name, func(t *testing.T) {
for _, c := range cases.invalid {
if !allowlist.PathAllowed(c) {
t.Errorf("invalid path not marked as allowed: %s", c)
}
}
for _, c := range cases.valid {
if allowlist.PathAllowed(c) {
t.Errorf("valid path marked as allowed: %s", c)
}
}
})
}
}
+17 -1
View File
@@ -1,10 +1,11 @@
package main
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/base"
"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/rules"
@@ -25,6 +26,7 @@ func main() {
gitleaksConfigPath := os.Args[1]
configRules := []*config.Rule{
rules.OnePasswordServiceAccountToken(),
rules.AdafruitAPIKey(),
rules.AdobeClientID(),
rules.AdobeClientSecret(),
@@ -38,6 +40,7 @@ func main() {
rules.Atlassian(),
rules.Authress(),
rules.AWS(),
rules.AzureActiveDirectoryClientSecret(),
rules.BitBucketClientID(),
rules.BitBucketClientSecret(),
rules.BittrexAccessKey(),
@@ -53,6 +56,8 @@ func main() {
rules.ConfluentAccessToken(),
rules.ConfluentSecretKey(),
rules.Contentful(),
rules.CurlHeaderAuth(),
rules.CurlBasicAuth(),
rules.Databricks(),
rules.DatadogtokenAccessToken(),
rules.DefinedNetworkingAPIToken(),
@@ -95,9 +100,19 @@ func main() {
rules.GitHubOauth(),
rules.GitHubApp(),
rules.GitHubRefresh(),
rules.GitlabCiCdJobToken(),
rules.GitlabDeployToken(),
rules.GitlabFeatureFlagClientToken(),
rules.GitlabFeedToken(),
rules.GitlabIncomingMailToken(),
rules.GitlabKubernetesAgentToken(),
rules.GitlabOauthAppSecret(),
rules.GitlabPat(),
rules.GitlabPipelineTriggerToken(),
rules.GitlabRunnerRegistrationToken(),
rules.GitlabRunnerAuthenticationToken(),
rules.GitlabScimToken(),
rules.GitlabSessionCookie(),
rules.GitterAccessToken(),
rules.GrafanaApiKey(),
rules.GrafanaCloudApiToken(),
@@ -142,6 +157,7 @@ func main() {
rules.NPM(),
rules.NugetConfigPassword(),
rules.NytimesAccessToken(),
rules.OctopusDeployApiKey(),
rules.OktaAccessToken(),
rules.OpenAI(),
rules.OpenshiftUserToken(),
+42
View File
@@ -0,0 +1,42 @@
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"
"regexp"
)
// https://developer.1password.com/docs/service-accounts/security/?token-example=encoded
func OnePasswordServiceAccountToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "1password-service-account-token",
Description: "Uncovered a possible 1Password service account token, potentially compromising access to secrets in vaults.",
Regex: regexp.MustCompile(`ops_eyJ[a-zA-Z0-9+/]{250,}={0,3}`),
Entropy: 4,
Keywords: []string{"ops_"},
}
// validate
tps := []string{
utils.GenerateSampleSecret("1password", secrets.NewSecret(`ops_eyJ[a-zA-Z0-9+/]{250,}={0,3}`)),
`### 1Password System Vault Name
export OP_SERVICE_ACCOUNT_TOKEN=ops_eyJzaWduSW5BZGRyZXNzIjoibXkuMXBhc3N3b3JkLmNvbSIsInVzZXJBdXRoIjp7Im1ldGhvZCI6IlNSUGctNDA5NiIsImFsZyI6IlBCRVMyZy1IUzI1NiIsIml0ZXJhdGlvbnMiOjY1MdAwMCwic2FsdCI6InE2dE0tYzNtRDhiNUp2OHh1YVzsUmcifSwiZW1haWwiOiJ5Z3hmcm0zb21oY3NtQDFwYXNzd29yZHNlcnZpY2VhY2NvdW50cy5jb20iLCJzcnBYIjoiM2E5NDdhZmZhMDQ5NTAxZjkxYzk5MGFiY2JiYWRlZjFjMjM5Y2Q3YTMxYmI1MmQyZjUzOTA2Y2UxOTA1OTYwYiIsIm11ayI6eyJhbGciOiJBMjU2R0NNIiwiZXh0Ijp0cnVlLCJrIjoiVVpleERsLVgyUWxpa0VqRjVUUjRoODhOd29ZcHRqSHptQmFTdlNrWGZmZyIsImtleV9vcHMiOlsiZW5jcnlwdCIsImRlY3J5cHQiXSwia3R5Ijoib2N0Iiwia2lkIjoibXAifSwic2VjcmV0S2V5IjoiQTMtNDZGUUVNLUVZS1hTQS1NUU0yUy04U0JSUS01QjZGUC1HS1k2ViIsInRocm90dGxlU2VjcmV0Ijp7InNlZWQiOiJjZmU2ZTU0NGUxZTlmY2NmZjJlYjBhYWZmYTEzNjZlMmE2ZmUwZDVlZGI2ZTUzOTVkZTljZmY0NDY3NDUxOGUxIiwidXVpZCI6IjNVMjRMNVdCNkpFQ0pEQlhJNFZOSTRCUzNRIn0sImRldmljZVV1aWQiOiJqaGVlY3F4cm41YTV6ZzRpMnlkbjRqd3U3dSJ9
`,
`PYTEST_SVC_ACCT_TOKEN=ops_eyJzaWduSW5BZGRyZXNzIjoiemFjaC1hbmQtbGVhbm5lLjFwYXNzd29yZC5jb20iLCJ1c2VyQXV0aCI6eyJtZXRob2QiOiJTUlBnLTQwOTYiLCJhbGciOiJQQkVLMmctSFMyNTYiLCJpdGVyYXRpb25zIjo2NTAwMDAsInNhbHQiOiJlYUZRQmNVemJyTHhnM2d4bHFQLVVBIn0sImVtYWlsIjoiMm9iNGRpeDdiNTdrYUAxcGFzc3dvcmRzZXJ2aWNlYWNjb3VudHMuY29tIiwic3JwWCI6ImVmZDY4YjNhZTkwMmRjZjRiMzEzYjE5MjYwZmY0OGUzMjU2ZDlhOGNkM2JmMmY3YzI2YzU1ZWJkNjZlZGU4NWEiLCJtdWsiOnsiYWxnIjoiQTI1NkdDTSIsImV4dCI6dHJ1ZSwiayI6IlMwaGE0SDhqbEhRblJCWmxvYnBmR1BneERmbS1pRGNkZWY0bFdYU0VSbmMiLCJrZXlfb3BzIjpbImRlY3J5cHQiLCJlbmNyeXB0Il0sImt0eSI6Im9jdCIsImtpZCI6Im1wIn0sInNlY3JldEtleSI6IkEzLUdHOUVRNi1LUzQ0QVctQU5QVkYtUkdQTDktQlNKUTMtR1NHR0giLCJ0aHJvdHRsZVNlY3JldCI6eyJzZWVkIjoiN2I0OTMxMmJiOTlkZTFiNjU5ODZkYzIzOWU4YWNmZWMxMTU0M2E2OGQxYmYwMjZmZTgzMjg3NWYxNmJlOWY2NiIsInV1aWQiOiJDV1RHQ0hMNlNWRkdSTlg0SzNENUJVSDZDSSJ9LCJkZXZpY2VVdWlkIjoiMnFld3JpaGtqbmt1Zmh6ZGdmZ2hnNmM1cGUifQ`,
` "sourceContent": "ops_eyJlbWFpbCI6ImVqd2U2NHFtbHhocmlAMXBhc3N3b3Jkc2VydmljZWFjY291bnRzLmxjbCIsIm11ayI6eyJhbGciOiJBMjU2R0NNIiwiZXh0Ijp0cnVlLCJrIjoiTThWUGZJYzhWRWZUaGNNWExhS0NLRjhzTWg1Sk1ac1BBdHU5MmZRTmItbyIsImtleV9vcHMiOlsiZW5jcnlwdCIsImRlY3J5cHQiXSwia3R5Ijoib2N0Iiwia2lkIjoibXAifSwic2VjcmV0S2V5IjoiQTMtQzRaSk1OLVBRVFpUTC1IR0w4NC1HNjRNNy1LVlpSTi00WlZQNiIsInNycFgiOiI4NzBkNjdhOWU2MjY2MjVkOWUzNjg1MDc4MDRjOWMzMmU2NjFjNTdlN2U1NTg3NzgyOTFiZjI5ZDVhMjc5YWUxIiwic2lnbkluQWRkcmVzcyI6ImdvdGhhbS5iNWxvY2FsLmNvbTo0MDAwIiwidXNlckF1dGgiOnsibWV0aG9kIjoiU1JQZy00MDk2IiwiYWxnIjoiUEJFUzJnLUhTMjU2IiwiaXRlcmF0aW9ucyI6MTAwMDAwLCJzYWx0IjoiRk1SVVBpeXJONFhmXzhIb2g2WVJYUSJ9fQ\n\nops_token is secret.\n",`,
}
fps := []string{
// Invalid
` login:
serviceAccountToken:
fn::secret: ops_eyJzaWduSW5B..[Redacted]`,
`: To start using this service account, run the following command:
:
: export OP_SERVICE_ACCOUNT_TOKEN=ops_eyJzaWduSW5BZGRyZXNzIjoiaHR0cHM6...`,
// Low entropy.
`ops_eyJxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`,
}
return utils.Validate(r, tps, fps)
}
+5 -3
View File
@@ -9,9 +9,10 @@ import (
func AdobeClientID() *config.Rule {
// define rule
r := config.Rule{
Description: "Detected a pattern that resembles an Adobe OAuth Web Client ID, posing a risk of compromised Adobe integrations and data breaches.",
RuleID: "adobe-client-id",
Description: "Detected a pattern that resembles an Adobe OAuth Web Client ID, posing a risk of compromised Adobe integrations and data breaches.",
Regex: utils.GenerateSemiGenericRegex([]string{"adobe"}, utils.Hex("32"), true),
Entropy: 2,
Keywords: []string{"adobe"},
}
@@ -25,9 +26,10 @@ func AdobeClientID() *config.Rule {
func AdobeClientSecret() *config.Rule {
// define rule
r := config.Rule{
Description: "Discovered a potential Adobe Client Secret, which, if exposed, could allow unauthorized Adobe service access and data manipulation.",
RuleID: "adobe-client-secret",
Regex: utils.GenerateUniqueTokenRegex(`(p8e-)(?i)[a-z0-9]{32}`, true),
Description: "Discovered a potential Adobe Client Secret, which, if exposed, could allow unauthorized Adobe service access and data manipulation.",
Regex: utils.GenerateUniqueTokenRegex(`p8e-(?i)[a-z0-9]{32}`, false),
Entropy: 2,
Keywords: []string{"p8e-"},
}
+7 -7
View File
@@ -9,9 +9,10 @@ import (
func AlibabaAccessKey() *config.Rule {
// define rule
r := config.Rule{
Description: "Detected an Alibaba Cloud AccessKey ID, posing a risk of unauthorized cloud resource access and potential data compromise.",
RuleID: "alibaba-access-key-id",
Regex: utils.GenerateUniqueTokenRegex(`(LTAI)(?i)[a-z0-9]{20}`, true),
Description: "Detected an Alibaba Cloud AccessKey ID, posing a risk of unauthorized cloud resource access and potential data compromise.",
Regex: utils.GenerateUniqueTokenRegex(`LTAI(?i)[a-z0-9]{20}`, false),
Entropy: 2,
Keywords: []string{"LTAI"},
}
@@ -26,12 +27,11 @@ func AlibabaAccessKey() *config.Rule {
func AlibabaSecretKey() *config.Rule {
// define rule
r := config.Rule{
Description: "Discovered a potential Alibaba Cloud Secret Key, potentially allowing unauthorized operations and data access within Alibaba Cloud.",
RuleID: "alibaba-secret-key",
Regex: utils.GenerateSemiGenericRegex([]string{"alibaba"},
utils.AlphaNumeric("30"), true),
Keywords: []string{"alibaba"},
Description: "Discovered a potential Alibaba Cloud Secret Key, potentially allowing unauthorized operations and data access within Alibaba Cloud.",
Regex: utils.GenerateSemiGenericRegex([]string{"alibaba"}, utils.AlphaNumeric("30"), true),
Entropy: 2,
Keywords: []string{"alibaba"},
}
// validate
+3 -2
View File
@@ -12,9 +12,10 @@ func Authress() *config.Rule {
// Rule Definition
// (Note: When changes are made to this, rerun `go generate ./...` and commit the config/gitleaks.toml file
r := config.Rule{
Description: "Uncovered a possible Authress Service Client Access Key, which may compromise access control services and sensitive data.",
RuleID: "authress-service-client-access-key",
Regex: utils.GenerateUniqueTokenRegex(`(?:sc|ext|scauth|authress)_[a-z0-9]{5,30}\.[a-z0-9]{4,6}\.acc[_-][a-z0-9-]{10,32}\.[a-z0-9+/_=-]{30,120}`, true),
Description: "Uncovered a possible Authress Service Client Access Key, which may compromise access control services and sensitive data.",
Regex: utils.GenerateUniqueTokenRegex(`(?:sc|ext|scauth|authress)_(?i)[a-z0-9]{5,30}\.[a-z0-9]{4,6}\.(?-i:acc)[_-][a-z0-9-]{10,32}\.[a-z0-9+/_=-]{30,120}`, false),
Entropy: 2,
Keywords: []string{"sc_", "ext_", "scauth_", "authress_"},
}
+32 -8
View File
@@ -2,6 +2,7 @@ package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
@@ -12,17 +13,40 @@ func AWS() *config.Rule {
r := config.Rule{
Description: "Identified a pattern that may indicate AWS credentials, risking unauthorized cloud resource access and data breaches on AWS platforms.",
RuleID: "aws-access-token",
Regex: regexp.MustCompile(
"(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Regex: utils.GenerateUniqueTokenRegex("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}", false),
Entropy: 3,
Keywords: []string{
"AKIA",
"ASIA",
"ABIA",
"ACCA",
// https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids
"A3T", // todo: might not be a valid AWS token
"AKIA", // Access key
"ASIA", // Temporary (AWS STS) access key
"ABIA", // AWS STS service bearer token
"ACCA", // Context-specific credential
},
Allowlists: []config.Allowlist{
{
Regexes: []*regexp.Regexp{
regexp.MustCompile(`.+EXAMPLE$`),
},
},
},
}
// validate
tps := []string{utils.GenerateSampleSecret("AWS", "AKIALALEMEL33243OLIB")} // gitleaks:allow
return utils.Validate(r, tps, nil)
tps := []string{
utils.GenerateSampleSecret("AWS", "AKIALALEMEL33243OLIB"), // gitleaks:allow
// current AWS tokens cannot contain [0,1,8,9], so their entropy is slightly lower than expected.
utils.GenerateSampleSecret("AWS", "AKIA"+secrets.NewSecret("[A-Z2-7]{16}")),
utils.GenerateSampleSecret("AWS", "ASIA"+secrets.NewSecret("[A-Z2-7]{16}")),
utils.GenerateSampleSecret("AWS", "ABIA"+secrets.NewSecret("[A-Z2-7]{16}")),
utils.GenerateSampleSecret("AWS", "ACCA"+secrets.NewSecret("[A-Z2-7]{16}")),
}
fps := []string{
`key = AKIAXXXXXXXXXXXXXXXX`, // Low entropy
`aws_access_key: AKIAIOSFODNN7EXAMPLE`, // Placeholder
`msgstr "Näytä asiakirjamallikansio."`, // Lowercase
`TODAYINASIAASACKOFRICEFELLOVER`, // wrong length
`CTTCATAGGGTTCACGCTGTGTAAT-ACG--CCTGAGGC-CACA-AGGGGACTTCAGCAACCGTCGGG-GATTC-ATTGCCA-A--TGGAAGCAATC-TA-TGGGTTA-TCGCGGAGTCCGCAAAGACGGCCAGTATG-AAGCAGATTTCGCAC-CAATGTGACTGCATTTCGTG-ATCGGGGTAAGTA-TC-GCCGATTC-GC--CCGTCCA-AGT-CGAAG-TA--GGCAATATAAAGCTGC-CATTGCCGAAGCTATCTCGCTA-TACTTGAT-AATCGGCGG-TAG-CACAG-GTCGCAGTATCG-AC-T--AGG-CCTCTCAAAAGTT-GGGTCCCGGCCTCTGGGAAAAACACCTCT-A-AGCGTCAATCAGCTCGGTTTCGCATATTA-TGATATCCCCCGTTGACCAATTGA--TAGTACCCGAGCTTACCGTCGG-ATTCTGGAGTCTT-ATGAGGTTACCGACGA-CGCAGTACCATAAGT-GCGCAATTTGACTGTTCCCGTCGAGTAACCA-AGCTTTGCTCA-CCGGGATGCGCGCCGATGTGACCAGGGGGCGCATGTTACATTGAC-A-GCTGGATCATGTTATGAC-GTGGGTC-ATGCTAAAAGCCTAAAGGACGGT-GCATTAGTAT-TACCGGGACCTCATATCAATGCGCTCGCTAGTTCCTCTTCTCTTGATAACGTATATGCGTCAGGCGCCCGTCCGCCTCCAATACGTG-ACAACGTC-AGTACTGAGCCTC--AA-ACATCGTCTTGTTCG-CC-TACAAAGGATCGGTAGAAAACTCAATATTCGGGTATAAGGTCGTAGGAAGTGTGTCGCCCAGGGCCG-CTAGA-AGCGCACACAAGCG-CTCCTGTCAAGGAGTTG-GTGAAAA-ATGAAC--GACT-ATTGCGTCAC--CTACCTCT-AAGTTTTT-GACAATTTCATGGACGAATTGA-AGCGTCCACAAGCATCTGCCGTAGATATGCGGTAGGTTTTTACATATG-TCACTGCAGAGTCACGGACA-CACATCGCTGTCAAAATGCTCGTACCTAGT-GT-TTGCGATCCCCC-GCGGCATTA-TCTTTTGAACCCTCGTCCCTGTGG-CTCTGATGATTGAG-GTCTGTA-TTCCCTCGTTGTGGGGGGATTGGACCTT-TGTATAGGTTCTTTAACCG-ATGGGGGGCCG--ATCGA-A-TA-TGCTCCTGTTTGCCCCGAACCTT-ACCTCGG-TCCAGACA-CTAAGAAAAACCCC-C-ACTGTAAGGTGCTGAGCCTTTGGATAGCC-CGCGAATGAT-CC-TAGTTGACAA-CTGAACGCGCTCGAACA-TGCCC-GCCCTCTGA--CTGCTGTCTG-GCACCTTTAGACACGCGTCGAC-CATATATT-AGCGCTGTCTGTGG-AGGT-TGTGTCTTGTTGCTCA-CT-CATTATCTGT-AACTGGCTCC-CTC-CCAT-TGGCGTCTTTACACCAACCGCTAGGTTACAGTGCA-TCTAGCGCCTATTATCAGGGCGT-TTGCAGCGGCGCGGTGGCTATGT-GTTAGACATATC-CTTACACTGTATGCTAG-AGCAAGCCAC-TCTGAATGGGTTGC-CGATGAATGA-TCTTGATC-GAGCTCGCA-AC---TACATGGAGTCCGAAGTGAACCTACGGATGATCGTATTCCAACACGAGGATC-TATACGTATAGG-A-GGCG-TAATCCACAATTTAGTAACTCTTGACGC---GGATGAAAAT-GTCGTTACACCTTCCAGAGGCTCGG-GTATATATATGACCT--TGTGATTGAGGACGATCTAGAATAA-CT-GT-G-CT-AAAGTACAGTAGTTTCTATGT-GGTAGGTGGAGAATACAGAGTAG-ATGATTC-GTGGGCCACA-C--T-ACTTTCAT-TAGAGCAGAGA-C-GTGAGTGAGTTTTACACTAGCCAGATGGACCG-GTGA-AGTCTAACAGCCACCGCTT-GTGAGGTCGTTTCCCAGTC-ACCCTACTACAGGCAAAAACTCAGTGT-CC-GTGA-GTGCGTTAGTGATATTCCCTAACGGTTAGGTAACT-CATGAATTCA-AT-TAAGCGTGTCC-CGGT-CACGCCCCCATGGGGGCCTTCTTGGGAGG--AGCATCTTAT--AT-GCTCACGTGGTT-GATAGG-A-T-AATACACTTTTAGTCAGTCCATCAATAAC-AAAGGAAC---CAGGTGGTCGCAGATA-TCCCGCTGATATAGCACTGTGTAAACTCAGGTGATA-CTAAGC--GCTCTAAT-ACG-CTTAATGGCAATGCCCAGTTC--ACGACTAGCTTATGAGGCCCAGCTATGGACTGCGGC-GGCATGTCGGC-GATGGTTGCCCTCGCCCTAAATTATGTACGA-T-ACCGCCT-CTTGTTCT-CCGCCCATAGGGT-C--AGCAGGCGATAGACTCCCAGAAATTTCCTCGTCGT-CCGAATAAGACTAACACGACTA-TT-CCTCTAC-GT-G-AA-CTTATCA-CAAATG-GCT-TACC-TAGGTGGTGGCAGATCACTTTCCGGTG-TATTACGAATTGACGCATACCGAC-A-CGC-GCTTGTTGGATAATCGACTCTAACCTCCTCTCTGGCACATGT-GCTGGATTACCTC-TATTTT-TCTCGCTTAG--GGAACG-T-CCTCTGTCGCGTGAG-GTACGTTTCACGGGAG-CGGCTTGTTCATGCCACGTCCATTATCGA-AGTG-C-GTAAGG-A-GAGCCCTA--GACTCTACACGGAAA-TC-AAC-GTAGAAGGCTC-A-CT`,
}
return utils.Validate(r, tps, fps)
}
+65
View File
@@ -0,0 +1,65 @@
package rules
import (
"fmt"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
// References:
// - https://learn.microsoft.com/en-us/microsoft-365/compliance/sit-defn-azure-ad-client-secret
// - https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app#add-credentials
func AzureActiveDirectoryClientSecret() *config.Rule {
// define rule
r := config.Rule{
RuleID: "azure-ad-client-secret",
Description: "Azure AD Client Secret",
// After inspecting dozens of secrets, I'm fairly confident that they start with `xxx\dQ~`.
// However, this may not be (entirely) true, and this rule might need to be further refined in the future.
// Furthermore, it's possible that secrets have a checksum that could be used to further constrain this pattern.
Regex: regexp.MustCompile(`(?:^|[\\'"\x60\s>=:(,)])([a-zA-Z0-9_~.]{3}\dQ~[a-zA-Z0-9_~.-]{31,34})(?:$|[\\'"\x60\s<),])`), // wtf, Go? https://github.com/golang/go/issues/18221
Entropy: 3,
Keywords: []string{
"Q~",
},
}
// validate
tps := []string{
`client_secret=bP88Q~rcBcYjzzOhg1Hnn76Wm3jGgakZiZ.8vMgR`, // gitleaks:allow
`client_secret=bP88Q~rcBcYjzzOhg1Hnn76Wm3jGgakZiZ.8vMgR
`, // gitleaks:allow
`client_secret: .IQ8Q~79R7TOWOspFnWcEG-dYt4KXqFqxK16cxr`, // gitleaks:allow
`AUTH_CLIENTSECRET = _V28Q~IC8qxmlWNpHuDm34JlbKv9LXV5MvUR3a-P`, // gitleaks:allow
`<value xsi:type="xsd:string">~Gg8Q~nVhlLi2vpg_nXBGqFsbGK-t~Hus1JmTa0y</value>`, // gitleaks:allow
`"CLIENT_SECRET": "YYz7Q~Sudoqwap1PnzEBA3zqBK~i5uesDIv.C"`, // gitleaks:allow
`Set-PSUAuthenticationMethod -Type 'OpenIDConnect' -CallbackPath '/auth/oidc' -ClientId 'fake' -ClientSecret '2Vq7Q~q5VgKljZ7cb3.0sp0Apz.vOjRIPyeTr'`, // gitleaks:allow
`client-secret: "t028Q~-aLbmQuinnZtzbgtlEAYstnBWEmGPAoBm"`, // gitleaks:allow
`"cas.authn.azure-active-directory.client-secret=qHF8Q~PCM5HhMoyTFc5TYEomnzR6Kim9UJhe8a.P",`, // gitleaks:allow
`"line": "client_srt = \"qpF8Q~PCM5MhMoyTFc5TYEomnYRUKim9UJhe8a2P\";",`, // gitleaks:allow
`"client_secret": acctest.Representation{RepType: acctest.Required, Create: 'dO29Q~F5-VwnW.lZdd11xFF_t5NAXCaGwDl9NbT1'},`, // gitleaks:allow
`Example= GN.7Q~4AkLZBNEbz4Jxlm~O5G6SsyFxYg6zMR`, // gitleaks:allow
`"the_value": "QtT8Q~9C-_Ij~RouHVpD2Tuf3oHWGh.DQ3kcjbAn"`, // gitleaks:allow
`QtT8Q~9C-_Ij~RouHVpD2Tuf3oHWGh.DQ3kcjbAn`, // gitleaks:allow
`(use the client secret: QtT8Q~9C-_Ij~RouHVpD2Tuf3oHWGh.DQ3kcjbAn)`, // gitleaks:allow
`(QtT8Q~9C-_Ij~RouHVpD2Tuf3oHWGh.DQ3kcjbAn)`, // gitleaks:allow
`\"pass\": \"` + fmt.Sprintf("%s%sQ~%s", secrets.NewSecret(`[\w~.]{3}`), secrets.NewSecret(utils.Numeric("1")), secrets.NewSecret(`[\w~.-]{31,34}`)),
}
fps := []string{
`![图源:《深入拆解Tomcat & Jetty》](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/6a9e704af49b4380bb686f0c96d33b81~tplv-k3u1fbpfcp-watermark.image)`,
`~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`,
`~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`,
`.ui.visible.right.sidebar~.ui.visible.left.sidebar~.pusher{transform:translate3d(0,0,0)}`,
`buf.WriteString("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n::\n\n")`,
`'url': 'http://www.2doc.nl/speel~VARA_101375237~mh17-het-verdriet-van-nederland~.html',`,
`@ar = split("~", "965f1453~47~09414c93e4cef985416f472549220827da3ba6fed8ad28e29ef6ad170ad53a69051e9b06f439ef6da5df8670181f7eb2481650");`,
`'#!/registries/5/portainer.demo~2Fportainerregistrytesting~2Falpine',`,
`// CloudFront-Signature: Ixn4bF1LLrLcB8XG-t5bZbIB0vfwSF2s4gkef~PcNBdx73MVvZD3v8DZ5GzcqNrybMiqdYJY5KqK6vTsf5JXDgwFFz-h98wdsbV-izcuonPdzMHp4Ay4qyXM6Ed5jB9dUWYGwMkA6rsWXpftfX8xmk4tG1LwFuJV6nAsx4cfpuKwo4vU2Hyr2-fkA7MZG8AHkpDdVUnjm1q-Re9HdG0nCq-2lnBAdOchBpJt37narOj-Zg6cbx~6rzQLVQd8XIv-Bn7VTc1tkBAJVtGOHb0Q~PLzSRmtNGYTnpL0z~gp3tq8lhZc2HuvJW5-tZaYP9yufeIzk5bqsT6DT4iDuclKKw__, , , false`,
`+ "<Trust Comment=\"\" Identity=\"USK@u2vn3Lh6Kte2-TgBSNKorbsKkuAt34ckoLmgx0ndXO0,4~q8Q~3wIHjX9DT0yCNfQmr9oxmYrDZoQVLOdNg~yk0,AQACAAE/WebOfTrustRC2/2\" Value=\"100\"/>"`,
`client_secret=bP88Q~xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`,
}
return utils.Validate(r, tps, fps)
}
+3 -2
View File
@@ -11,10 +11,11 @@ import (
func Clojars() *config.Rule {
// define rule
r := config.Rule{
Description: "Uncovered a possible Clojars API token, risking unauthorized access to Clojure libraries and potential code manipulation.",
RuleID: "clojars-api-token",
Description: "Uncovered a possible Clojars API token, risking unauthorized access to Clojure libraries and potential code manipulation.",
Regex: regexp.MustCompile(`(?i)CLOJARS_[a-z0-9]{60}`),
Keywords: []string{"clojars"},
Entropy: 2,
Keywords: []string{"clojars_"},
}
// validate
+8 -8
View File
@@ -27,11 +27,11 @@ var identifiers = []string{"cloudflare"}
func CloudflareGlobalAPIKey() *config.Rule {
// define rule
r := config.Rule{
Description: "Detected a Cloudflare Global API Key, potentially compromising cloud application deployments and operational security.",
RuleID: "cloudflare-global-api-key",
Description: "Detected a Cloudflare Global API Key, potentially compromising cloud application deployments and operational security.",
Regex: utils.GenerateSemiGenericRegex(identifiers, utils.Hex("37"), true),
Keywords: identifiers,
Entropy: 2,
Keywords: identifiers,
}
// validate
@@ -44,11 +44,11 @@ func CloudflareGlobalAPIKey() *config.Rule {
func CloudflareAPIKey() *config.Rule {
// define rule
r := config.Rule{
Description: "Detected a Cloudflare API Key, potentially compromising cloud application deployments and operational security.",
RuleID: "cloudflare-api-key",
Description: "Detected a Cloudflare API Key, potentially compromising cloud application deployments and operational security.",
Regex: utils.GenerateSemiGenericRegex(identifiers, utils.AlphaNumericExtendedShort("40"), true),
Keywords: identifiers,
Entropy: 2,
Keywords: identifiers,
}
// validate
@@ -65,8 +65,8 @@ func CloudflareOriginCAKey() *config.Rule {
Description: "Detected a Cloudflare Origin CA Key, potentially compromising cloud application deployments and operational security.",
RuleID: "cloudflare-origin-ca-key",
Regex: utils.GenerateUniqueTokenRegex(`v1\.0-`+utils.Hex("24")+"-"+utils.Hex("146"), false),
Keywords: ca_identifiers,
Entropy: 2,
Keywords: ca_identifiers,
}
// validate
+42 -15
View File
@@ -22,6 +22,9 @@ regexes = [{{ range $i, $regex := . }}
paths = [{{ range $i, $path := . }}
'''{{ $path }}''',{{ end }}
]{{ end }}
{{- with .Allowlist.StopWords }}{{println}}stopwords = [{{ range $j, $stopword := . }}
"{{ $stopword }}",{{ end }}
]{{ end }}
{{ range $i, $rule := .Rules }}[[rules]]
id = "{{$rule.RuleID}}"
@@ -43,23 +46,47 @@ keywords = [{{ range $j, $keyword := . }}"{{ $keyword }}"{{ end }}]{{end}}{{ end
tags = [
{{ range $j, $tag := . }}"{{ $tag }}",{{ end }}
]{{ end }}
{{ if or $rule.Allowlist.Regexes $rule.Allowlist.Paths $rule.Allowlist.Commits $rule.Allowlist.StopWords }}
{{- /*
* Use [rules.allowlist] for a while, allow people to catch up with the new syntax.
* TODO: Remove this a few major versions after 8.21.0
* https://github.com/gitleaks/gitleaks/issues/1571
*/}}
{{- if eq (len $rule.Allowlists) 1 }}{{ with index $rule.Allowlists 0}}{{ if or .Regexes .Paths .Commits .StopWords }}
# NOTE: Gitleaks >= v8.21.0 should use [[rules.allowlists] instead.
[rules.allowlist]
{{- with $rule.Allowlist.RegexTarget }}
regexTarget = "{{ . }}"{{ end -}}
{{- with $rule.Allowlist.Regexes }}
regexes = [{{ range $i, $regex := . }}
'''{{ $regex }}''',{{ end }}
]{{ end }}
{{- with $rule.Allowlist.Paths }}paths = [
{{ range $j, $path := . }}'''{{ $path }}''',{{ end }}
]{{ end }}
{{- with $rule.Allowlist.Commits }}commits = [
{{- with .MatchCondition }}{{println}}condition = "{{ .MatchCondition.String }}"{{ end }}
{{- with .Commits -}}{{println}}commits = [
{{ range $j, $commit := . }}"{{ $commit }}",{{ end }}
]{{ end }}
{{- with $rule.Allowlist.StopWords }}
stopwords = [{{ range $j, $stopword := . }}
"{{ $stopword }}",{{ end }}
{{- with .Paths }}{{println}}paths = [
{{ range $j, $path := . }}'''{{ $path }}''',{{ end }}
]{{ end }}
{{ end }}
{{- if and .RegexTarget .Regexes }}{{println}}regexTarget = "{{ .RegexTarget }}"{{ end -}}
{{- with .Regexes }}{{println}}regexes = [{{ range $i, $regex := . }}
'''{{ $regex }}''',{{ end }}
]{{ end }}
{{- with .StopWords }}{{println}}stopwords = [{{ range $j, $stopword := . }}
"{{ $stopword }}",{{ end }}
]{{ end }}{{ end }}{{ end }}
{{ else }}
{{ with $rule.Allowlists }}{{ range $i, $allowlist := . }}{{ if or $allowlist.Regexes $allowlist.Paths $allowlist.Commits $allowlist.StopWords }}
[[rules.allowlists]]
{{ with $allowlist.MatchCondition }}condition = "{{ .String }}"
{{ end -}}
{{- with $allowlist.Commits }}commits = [
{{ range $j, $commit := . }}"{{ $commit }}",{{ end }}
]{{ end }}
{{- with $allowlist.Paths }}paths = [
{{ range $j, $path := . }}'''{{ $path }}''',{{ end }}
]{{ end }}
{{- with $allowlist.RegexTarget }}regexTarget = "{{ . }}"
{{ end -}}
{{- with $allowlist.Regexes }}regexes = [{{ range $i, $regex := . }}
'''{{ $regex }}''',{{ end }}
]{{ end }}
{{ with $allowlist.StopWords }}stopwords = [{{ range $j, $stopword := . }}
"{{ $stopword }}",{{ end }}
]{{ end }}{{ end }}{{ end }}
{{ end }}{{ end }}
{{ end -}}
+198
View File
@@ -0,0 +1,198 @@
package rules
import (
"fmt"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
)
// https://curl.se/docs/manpage.html#-u
func CurlBasicAuth() *config.Rule {
r := config.Rule{
RuleID: "curl-auth-user",
// TODO: Description: "",
Regex: regexp.MustCompile(`\bcurl\b(?:.*|.*(?:[\r\n]{1,2}.*){1,5})[ \t\n\r](?:-u|--user)(?:=|[ \t]{0,5})(?:"([^:"]{3,}:[^"]{3,})"|'([^:']{3,}:[^']{3,})'|((?:"[^"]{3,}"|'[^']{3,}'|[\w$@.-]+):(?:"[^"]{3,}"|'[^']{3,}'|[\w${}@.-]+)))(?:\s|\z)`),
Keywords: []string{"curl"},
Entropy: 2,
Allowlists: []config.Allowlist{
{
Regexes: []*regexp.Regexp{
regexp.MustCompile(`[^:]+:(change(it|me)|pass(word)?|pwd|test|token|\*+|x+)`), // common placeholder passwords
regexp.MustCompile(`['"]?<[^>]+>['"]?:['"]?<[^>]+>|<[^:]+:[^>]+>['"]?`), // <placeholder>
regexp.MustCompile(`[^:]+:\[[^]]+]`), // [placeholder]
regexp.MustCompile(`['"]?[^:]+['"]?:['"]?\$(\d|\w+|\{(\d|\w+)})['"]?`), // $1 or $VARIABLE
regexp.MustCompile(`\$\([^)]+\):\$\([^)]+\)`), // $(cat login.txt)
regexp.MustCompile(`['"]?\$?{{[^}]+}}['"]?:['"]?\$?{{[^}]+}}['"]?`), // ${{ secrets.FOO }} or {{ .Values.foo }}
},
},
},
}
// validate
tps := []string{
// short
`curl --cacert ca.crt -u elastic:P@ssw0rd$1 https://localhost:9200`, // same lines, no quotes
`sh-5.0$ curl -k -X POST https://infinispan:11222/rest/v2/caches/default/hello \
-H 'Content-type: text/plain' \
-d 'world' \
-u developer:yqDVtkqPECriaLRi`, // different line
// long
`curl -sw '%{http_code}' -X POST --user 'johns:h0pk1ns~21s' $GItHUB_API_URL/$GIT_COMMIT --data`,
`curl --user roger23@gmail.com:pQ9wTxu4Fg https://www.dropbox.com/cli_link?host_id=abcdefg -v`, // same line, no quotes
`curl -s --user 'api:d2LkV78zLx!t' \
https://api.mailgun.net/v2/sandbox91d3515882ecfaa1c65be642.mailgun.org/messages`, // same line, single quotes
`curl -s -v --user "j.smith:dB2yF6@qL9vZm1P#4J" "https://api.contoso.org/user/me"`, // same line, double quotes
`curl -X POST --user "{acd3c08b-74e8-4f44-a2d0-80694le24f46}":"{ZqL5kVrX1n8tA2}" --header "Accept: application/json" --data "{\"text\":\"Hello, world\",\"source\":\"en\",\"target\":\"es\"}" https://gateway.watsonplatform.net/language-translator/api`,
`curl --user kevin:'pRf7vG2h1L8nQkW9' -iX PATCH -H "Content-Type: application/json" -d`, // same line, mixed quoting
`$ curl https://api.dropbox.com/oauth2/token \
--user c28wlsosanujy2z:qgsnai0xokrw4j1 --data grant_type=authorization_code`, // different line
// TODO
//` curl -s --insecure --url "imaps://whatever.imap.server" --user\
//"myuserid:mypassword" --request "STATUS INBOX (UNSEEN)"`,
}
fps := []string{
// short
`curl -i -u 'test:test'`,
` curl -sL --user "$1:$2" "$3" > "$4"`, // environment variable
`curl -u <user:password> https://test.com/endpoint`, // placeholder
`curl --user neo4j:[PASSWORD] http://[IP]:7474/db/data/`, // placeholder
`curl -u "myusername" http://localhost:15130/api/check_user/`, // no password
`curl -u username:token`,
`curl -u "${_username}:${_password}"`,
`curl -u "${username}":"${password}"`,
`curl -k -X POST -I -u "SRVC_JENKINS:${APPID}"`,
// long
`curl -sw '%{http_code}' -X POST --user '$USERNAME:$PASSWORD' $GItHUB_API_URL/$GIT_COMMIT --data`,
`curl --user "xxx:yyy"`,
` curl -sL --user "$GITHUB_USERNAME:$GITHUB_PASSWORD" "$GITHUB_URL" > "$TESTS_PATH"`, // environment variable
// variable interpolation
`curl --silent --fail {{- if and $.Values.username $.Values.password }} --user "{{ $.Values.username }}:{{ $.Values.password }}"`,
`curl -XGET -i -u "${{ env.ELK_ID }}:${{ build.env.ELK_PASS }}"`,
`curl -XGET -i -u "${{needs.vault.outputs.account_id}}:${{needs.vault.outputs.account_password}}"`,
`curl -XGET -i -u "${{ steps.vault.outputs.account_id }}:${{ steps.vault.outputs.account_password }}"`,
`curl -X POST --user "$(cat ./login.txt):$(cat ./password.txt)"`, // command
`curl http://127.0.0.1:5000/file --user user:pass --digest # digest auth`, // placeholder
` curl -X GET --insecure --user "username:password" \`, // placeholder
`curl --silent --insecure --user ${f5user}:${f5pass} \`, // placeholder
`curl --insecure --ssl-reqd "smtps://smtp.gmail.com" --mail-from "src@gmail.com" --mail-rcpt "dst@gmail.com" --user "src@gmail.com" --upload-file out.txt`, // no password
// different command
`#HTTP command line test
curl -X POST -H "Content-Type: application/json" -d '{"id":12345,"geo":{"latitude":28.50,"longitude":-81.14}}' http://<ip>:8080/serve
#UDP command line test
echo -n '{"type":"serve","channel":"/","data":{"site_id":8,"post_id":12345,"geo":{"lat":28.50,"long":-81.14}}}' >/dev/udp/127.0.0.1/41234
#UDP Listener (for confirmation)
nc -u -l 41234`,
}
return utils.Validate(r, tps, fps)
}
// https://curl.se/docs/manpage.html#-H
func CurlHeaderAuth() *config.Rule {
// language=regexp
authPat := `(?i)(?:Authorization:[ \t]{0,5}(?:Basic[ \t]([a-z0-9+/]{8,}={0,3})|(?:Bearer|(?:Api-)?Token)[ \t]([\w=~@.+/-]{8,})|([\w=~@.+/-]{8,}))|(?:(?:X-(?:[a-z]+-)?)?(?:Api-?)?(?:Key|Token)):[ \t]{0,5}([\w=~@.+/-]{8,}))`
r := config.Rule{
RuleID: "curl-auth-header",
// TODO: Description: "",
Regex: regexp.MustCompile(
// language=regexp
fmt.Sprintf(`\bcurl\b(?:.*?|.*?(?:[\r\n]{1,2}.*?){1,5})[ \t\n\r](?:-H|--header)(?:=|[ \t]{0,5})(?:"%s"|'%s')(?:\B|\s|\z)`, authPat, authPat)),
Entropy: 2.75,
Keywords: []string{"curl"},
//Allowlists: []config.Allowlist{
// {
// Regexes: []*regexp.Regexp{},
// },
//},
}
tps := []string{
`curl --header 'Authorization: 5eb4223e-5008-46e5-be67-c7b8f2732305'`,
// Short flag.
`curl -H 'Authorization: Basic YnJvd3Nlcjo=' \`, // same line, single quotes
// TODO: Handle short flags combined.
//`TOKEN=$(curl -sH "Authorization: Basic $BASIC_TOKEN" "https://$REGISTRY/oauth2/token?service=$REGISTRY&scope=repository:$REPO:pull" | jq -r .access_token)`,
// Long flag.
`curl -k -X POST --header "Authorization: Basic djJlNEpYa0NJUHZ5a2FWT0VRXzRqZmZUdDkwYTp2emNBZGFzZWpmlWZiUDc2VUJjNDNNVDExclVh" "https://api-qa.example.com:8243/token" -d "grant_type=client_credentials"`, // same line, double quotes
// Basic auth.
`curl -X POST -H "Content-Type: application/json" \
-H "Authorization: Basic MzUzYjMwMmM0NDU3NGY1NjUwNDU2ODdlNTM0ZTdkNmE6Mjg2OTI0Njk3ZTYxNWE2NzJhNjQ2YTQ5MzU0NTY0NmM=" \
-d '{"user":{"emailAddress":"test@example.com"}, "password":"password"}' \
'http://localhost:8080/oauth2-provider/v1.0/users'`, // different line, double quotes
`#curl -X POST \
# https://api.mailgun.net/v3/sandbox7dbcabccd4314c123e8b23599d35f5b6.mailgun.org/messages \
# -H 'Authorization: Basic YXBpOmtleS1hN2MzNDJ3MzNhNWQxLTU2M2U3MjlwLTZhYjI3YzYzNzM0Ng==' \
# -F from='Excited User <mailgun@sandbox7dbc123bccd4314c0aae8b23599d35f5b6.mailgun.org>' \
# -F to='joe@example.com' \
# -F subject='Hello' \
# -F text='Testing some Mailgun awesomness!'`, // different line, single quotes
// Bearer auth
`# curl -X GET "http://localhost:3000/api/cron/status" -H "Authorization: Bearer cfcabd11c7ed9a41b1a3e063c32d5114"`, // same line, double quotes
`curl -X PUT -H 'Authorization: Bearer jC+6TUUjCNHcVtAXpcqBCgxnA8r+qD6MatnYaf/+289y7HWpK0BWPyLHv/K4DMN32fufwmeVVjlo8zjgBh8kx3GfS6IqO70w1DVMSCTwX7fhEpiXaxzv0mhSMHDX9Kw63Q6DkavUWUV+MDNhCF5wGQrcdQNncVRF3YkuDHDT/xw2YWyZ/DX8k+gAYiC8gcD8Ueg0ljBVS1IDwPjuGoFPESJVxYr0MDPF2D8Pn2S5rq692U4D9ZLuluS46VA4DK6ig5P7QM5XVXi4V7vXM8qpN/zqneyz+w4PUh6NIX7QG6JczMhYd9maWRWVat5jDdyII63P6sNAy9QZjw+ClW211Q==' -d 'user={"account":"user@domain.com", "roles":["user"]}' http://127.0.0.1:8443/desks/1/occupy`, // same line, single quotes
`curl https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer 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" \`, // different line, double quotes
`curl -X GET "https://api.cloudflare.com/client/v4/user/tokens/verify" \
-H "Authorization: Bearer _FXNljbSRYMWx3TWrd7lgKhLtVZX6iskC8Wcbb4b" \
-H "Content-Type:application/json"`,
`curl -H "Authorization: Bearer sha256~bRLFnzd59Z3XpZH5_seJPHALOuvbWiKwbFKSsoALkgp"`,
// Token auth
`curl -H "Authorization: Api-Token 22cb987851bc5659l29114c62e60c79abd0d2c08" --request PUT https://appsecclass.report/api/use/635`, // token
`curl -H "Authorization: Token 22cb987851bc5659229114c62e60c79abd0d2c08" --request PUT https://appsecclass.report/api/use/635`, // token
// Nothing
`curl -L -H "Authorization:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjb25maWRlbmNlIjowLjh9.kvRPfjAhLhtRTczoRgctVGp7KY1QVH3UBZM-gM0x8ec" service1.local -> correct jwt `, // no prefix
`curl -L -H "Authorization: sha256~bRLFnzd5@=-.a+/hgdS"`, // no prefix
// Non-authorization headers.
`curl -X GET \
-H "apikey: c4ed6c21-9dd5-4a05-8e3f-c56d1151cce8" \
-H "Accept: application/json" \`, // apikey
`curl -X POST --header "Api-Token: Sk94HG7f6KB"`, // api-token
`curl -XPOST http://localhost:8080/api/tasks -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" -H "Token: 3fea6af1349166ea" -d "content=hello-curl"`, // token
`curl -X GET https://octopus.corp.net/
-H "X-Octopus-ApiKey: 3a16750d-d363-41a4-8ebd-035408f7730f" \`, // X-$thing-ApiKey
}
fps := []string{
// Placeholders
`curl https://example.com/micropub -d h=entry -d "content=Hello World" -H "Authorization: Bearer XXXXXXXXXXXX"`,
`curl -X POST https://accounts.spotify.com/api/token -d grant_type=client_credentials --header "Authorization: Basic ..."`,
`curl \
-H "Authorization: Bearer <Openverse API token>" \
"https://api.openverse.org/v1/audio/?q=test"`,
`curl -v -v -v -X POST https://domain/api/v1/authentication/sso/login-url/ \
-H 'Content-Type: application/json' \
-H "Authorization: Token **********" \
-d '{"username": "test", "next": "/luna/"}'`,
// Variables
`curl -XPOST http://localhost:8080/api/token -H "Authorization: basic {base64(email:password[\n])}" => token`, // same line, invalid base64
`curl -X GET \
-H "apikey: $API_KEY" \
-H "Accept: $FORMAT" \
"$API_URL/rest/v1/stats_derniere_labellisation"`, // API Key placeholder
`$ curl -X POST "http://localhost:8000/v1/chat/completions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $API_KEY" \
-d '{
"model": "chatglm3-6b-32k",
"messages": [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Hello!"}]
}'`, // different line, placeholder
`curl -X GET -H "Content-Type: application/json" -H "Authorization: Bearer $(gcloud auth print-access-token)" https://workflowexecutions.googleapis.com/v1/projects/244283331594/locations/us-central1/workflows/sample-workflow/executions/43c925aa-514a-44c1-a0a4-a9f8f26fd2cb/callbacks/1705791f-d446-4e92-a6d0-a13622422e80_31864a51-8c13-4b03-ad4d-945cdc8d0631`, // script
// Not valid BASIC
`curl -X POST -H "Content-Type: application/json" -H "Authorization: Basic eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjb25maWRlbmNlIjowLjh9.kvRPfjAhLhtRTczoRgctVGp7KY1QVH3UBZM-gM0x8ec" \`,
}
return utils.Validate(r, tps, fps)
}
+8 -3
View File
@@ -9,15 +9,20 @@ import (
func Databricks() *config.Rule {
// define rule
r := config.Rule{
Description: "Uncovered a Databricks API token, which may compromise big data analytics platforms and sensitive data processing.",
RuleID: "databricks-api-token",
Regex: utils.GenerateUniqueTokenRegex(`dapi[a-h0-9]{32}`, true),
Description: "Uncovered a Databricks API token, which may compromise big data analytics platforms and sensitive data processing.",
Regex: utils.GenerateUniqueTokenRegex(`dapi[a-f0-9]{32}(?:-\d)?`, false),
Entropy: 3,
Keywords: []string{"dapi"},
}
// validate
tps := []string{
utils.GenerateSampleSecret("databricks", "dapi"+secrets.NewSecret(utils.Hex("32"))),
`token = dapif13ac4b49d1cb31f69f678e39602e381-2`, // gitleaks:ignore
}
return utils.Validate(r, tps, nil)
fps := []string{
`DATABRICKS_TOKEN=dapi123456789012345678a9bc01234defg5`,
}
return utils.Validate(r, tps, fps)
}
+7 -6
View File
@@ -8,9 +8,10 @@ import (
func DigitalOceanPAT() *config.Rule {
r := config.Rule{
Description: "Discovered a DigitalOcean Personal Access Token, posing a threat to cloud infrastructure security and data privacy.",
RuleID: "digitalocean-pat",
Regex: utils.GenerateUniqueTokenRegex(`dop_v1_[a-f0-9]{64}`, true),
Description: "Discovered a DigitalOcean Personal Access Token, posing a threat to cloud infrastructure security and data privacy.",
Regex: utils.GenerateUniqueTokenRegex(`dop_v1_[a-f0-9]{64}`, false),
Entropy: 3,
Keywords: []string{"dop_v1_"},
}
@@ -22,11 +23,11 @@ func DigitalOceanPAT() *config.Rule {
func DigitalOceanOAuthToken() *config.Rule {
r := config.Rule{
Description: "Found a DigitalOcean OAuth Access Token, risking unauthorized cloud resource access and data compromise.",
RuleID: "digitalocean-access-token",
Regex: utils.GenerateUniqueTokenRegex(`doo_v1_[a-f0-9]{64}`, true),
Keywords: []string{"doo_v1_"},
Description: "Found a DigitalOcean OAuth Access Token, risking unauthorized cloud resource access and data compromise.",
Entropy: 3,
Regex: utils.GenerateUniqueTokenRegex(`doo_v1_[a-f0-9]{64}`, false),
Keywords: []string{"doo_v1_"},
}
tps := []string{
+17 -5
View File
@@ -9,8 +9,8 @@ import (
func DiscordAPIToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Detected a Discord API key, potentially compromising communication channels and user data privacy on Discord.",
RuleID: "discord-api-token",
Description: "Detected a Discord API key, potentially compromising communication channels and user data privacy on Discord.",
Regex: utils.GenerateSemiGenericRegex([]string{"discord"}, utils.Hex("64"), true),
Keywords: []string{"discord"},
}
@@ -25,9 +25,10 @@ func DiscordAPIToken() *config.Rule {
func DiscordClientID() *config.Rule {
// define rule
r := config.Rule{
Description: "Identified a Discord client ID, which may lead to unauthorized integrations and data exposure in Discord applications.",
RuleID: "discord-client-id",
Description: "Identified a Discord client ID, which may lead to unauthorized integrations and data exposure in Discord applications.",
Regex: utils.GenerateSemiGenericRegex([]string{"discord"}, utils.Numeric("18"), true),
Entropy: 2,
Keywords: []string{"discord"},
}
@@ -35,15 +36,20 @@ func DiscordClientID() *config.Rule {
tps := []string{
utils.GenerateSampleSecret("discord", secrets.NewSecret(utils.Numeric("18"))),
}
return utils.Validate(r, tps, nil)
fps := []string{
// Low entropy
`discord=000000000000000000`,
}
return utils.Validate(r, tps, fps)
}
func DiscordClientSecret() *config.Rule {
// define rule
r := config.Rule{
Description: "Discovered a potential Discord client secret, risking compromised Discord bot integrations and data leaks.",
RuleID: "discord-client-secret",
Description: "Discovered a potential Discord client secret, risking compromised Discord bot integrations and data leaks.",
Regex: utils.GenerateSemiGenericRegex([]string{"discord"}, utils.AlphaNumericExtended("32"), true),
Entropy: 2,
Keywords: []string{"discord"},
}
@@ -51,5 +57,11 @@ func DiscordClientSecret() *config.Rule {
tps := []string{
utils.GenerateSampleSecret("discord", secrets.NewSecret(utils.Numeric("32"))),
}
return utils.Validate(r, tps, nil)
fps := []string{
// Low entropy
`discord=00000000000000000000000000000000`,
// TODO:
//`discord=01234567890123456789012345678901`,
}
return utils.Validate(r, tps, fps)
}
+3 -2
View File
@@ -11,10 +11,11 @@ import (
func Doppler() *config.Rule {
// define rule
r := config.Rule{
Description: "Discovered a Doppler API token, posing a risk to environment and secrets management security.",
RuleID: "doppler-api-token",
Description: "Discovered a Doppler API token, posing a risk to environment and secrets management security.",
Regex: regexp.MustCompile(`dp\.pt\.(?i)[a-z0-9]{43}`),
Keywords: []string{"doppler"},
Entropy: 2,
Keywords: []string{`dp.pt.`},
}
// validate
+2 -1
View File
@@ -14,7 +14,8 @@ func Duffel() *config.Rule {
RuleID: "duffel-api-token",
Description: "Uncovered a Duffel API token, which may compromise travel platform integrations and sensitive customer data.",
Regex: regexp.MustCompile(`duffel_(?:test|live)_(?i)[a-z0-9_\-=]{43}`),
Keywords: []string{"duffel"},
Entropy: 2,
Keywords: []string{"duffel_"},
}
// validate
+3 -2
View File
@@ -11,10 +11,11 @@ import (
func Dynatrace() *config.Rule {
// define rule
r := config.Rule{
Description: "Detected a Dynatrace API token, potentially risking application performance monitoring and data exposure.",
RuleID: "dynatrace-api-token",
Description: "Detected a Dynatrace API token, potentially risking application performance monitoring and data exposure.",
Regex: regexp.MustCompile(`dt0c01\.(?i)[a-z0-9]{24}\.[a-z0-9]{64}`),
Keywords: []string{"dynatrace"},
Entropy: 4,
Keywords: []string{"dt0c01"},
}
// validate
+4 -2
View File
@@ -11,9 +11,10 @@ import (
func EasyPost() *config.Rule {
// define rule
r := config.Rule{
Description: "Identified an EasyPost API token, which could lead to unauthorized postal and shipment service access and data exposure.",
RuleID: "easypost-api-token",
Description: "Identified an EasyPost API token, which could lead to unauthorized postal and shipment service access and data exposure.",
Regex: regexp.MustCompile(`\bEZAK(?i)[a-z0-9]{54}`),
Entropy: 2,
Keywords: []string{"EZAK"},
}
@@ -27,9 +28,10 @@ func EasyPost() *config.Rule {
func EasyPostTestAPI() *config.Rule {
// define rule
r := config.Rule{
Description: "Detected an EasyPost test API token, risking exposure of test environments and potentially sensitive shipment data.",
RuleID: "easypost-test-api-token",
Description: "Detected an EasyPost test API token, risking exposure of test environments and potentially sensitive shipment data.",
Regex: regexp.MustCompile(`\bEZTK(?i)[a-z0-9]{54}`),
Entropy: 2,
Keywords: []string{"EZTK"},
}
+12 -7
View File
@@ -11,11 +11,11 @@ import (
func FacebookSecret() *config.Rule {
// define rule
r := config.Rule{
Description: "Discovered a Facebook Application secret, posing a risk of unauthorized access to Facebook accounts and personal data exposure.",
RuleID: "facebook-secret",
Description: "Discovered a Facebook Application secret, posing a risk of unauthorized access to Facebook accounts and personal data exposure.",
Regex: utils.GenerateSemiGenericRegex([]string{"facebook"}, utils.Hex("32"), true),
Keywords: []string{"facebook"},
Entropy: 3,
Keywords: []string{"facebook"},
}
// validate
@@ -31,9 +31,10 @@ func FacebookSecret() *config.Rule {
func FacebookAccessToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Discovered a Facebook Access Token, posing a risk of unauthorized access to Facebook accounts and personal data exposure.",
RuleID: "facebook-access-token",
Description: "Discovered a Facebook Access Token, posing a risk of unauthorized access to Facebook accounts and personal data exposure.",
Regex: utils.GenerateUniqueTokenRegex(`\d{15,16}(\||%)[0-9a-z\-_]{27,40}`, true),
Entropy: 3,
}
// validate
@@ -49,9 +50,10 @@ func FacebookAccessToken() *config.Rule {
func FacebookPageAccessToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Discovered a Facebook Page Access Token, posing a risk of unauthorized access to Facebook accounts and personal data exposure.",
RuleID: "facebook-page-access-token",
Regex: utils.GenerateUniqueTokenRegex("EAA[MC]"+utils.AlphaNumeric("20,"), true),
Description: "Discovered a Facebook Page Access Token, posing a risk of unauthorized access to Facebook accounts and personal data exposure.",
Regex: utils.GenerateUniqueTokenRegex("EAA[MC](?i)"+utils.AlphaNumeric("20,"), false),
Entropy: 3,
Keywords: []string{"EAAM", "EAAC"},
}
@@ -62,5 +64,8 @@ func FacebookPageAccessToken() *config.Rule {
`- name: FACEBOOK_TOKEN
value: "EAACEdEose0cBA1bad3afsf2aew"`, // gitleaks:allow
}
return utils.Validate(r, tps, nil)
fps := []string{
`eaaaC0b75a9329fded2ffa9a02b47e0117831b82`,
}
return utils.Validate(r, tps, fps)
}
+6 -3
View File
@@ -11,9 +11,10 @@ import (
func FlutterwavePublicKey() *config.Rule {
// define rule
r := config.Rule{
Description: "Detected a Finicity Public Key, potentially exposing public cryptographic operations and integrations.",
RuleID: "flutterwave-public-key",
Description: "Detected a Finicity Public Key, potentially exposing public cryptographic operations and integrations.",
Regex: regexp.MustCompile(`FLWPUBK_TEST-(?i)[a-h0-9]{32}-X`),
Entropy: 2,
Keywords: []string{"FLWPUBK_TEST"},
}
@@ -27,9 +28,10 @@ func FlutterwavePublicKey() *config.Rule {
func FlutterwaveSecretKey() *config.Rule {
// define rule
r := config.Rule{
Description: "Identified a Flutterwave Secret Key, risking unauthorized financial transactions and data breaches.",
RuleID: "flutterwave-secret-key",
Description: "Identified a Flutterwave Secret Key, risking unauthorized financial transactions and data breaches.",
Regex: regexp.MustCompile(`FLWSECK_TEST-(?i)[a-h0-9]{32}-X`),
Entropy: 2,
Keywords: []string{"FLWSECK_TEST"},
}
@@ -43,9 +45,10 @@ func FlutterwaveSecretKey() *config.Rule {
func FlutterwaveEncKey() *config.Rule {
// define rule
r := config.Rule{
Description: "Uncovered a Flutterwave Encryption Key, which may compromise payment processing and sensitive financial information.",
RuleID: "flutterwave-encryption-key",
Description: "Uncovered a Flutterwave Encryption Key, which may compromise payment processing and sensitive financial information.",
Regex: regexp.MustCompile(`FLWSECK_TEST-(?i)[a-h0-9]{12}`),
Entropy: 2,
Keywords: []string{"FLWSECK_TEST"},
}
+137 -18
View File
@@ -2,7 +2,9 @@ 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"
"regexp"
)
func GenericCredential() *config.Rule {
@@ -11,45 +13,162 @@ func GenericCredential() *config.Rule {
RuleID: "generic-api-key",
Description: "Detected a Generic API Key, potentially exposing access to various services and sensitive operations.",
Regex: utils.GenerateSemiGenericRegex([]string{
"access",
"auth",
`(?-i:[Aa]pi|API)`,
"credential",
"creds",
"key",
"api",
"token",
"secret",
"client",
"passwd",
"password",
"auth",
"access",
}, `[0-9a-z\-_.=]{10,150}`, true),
"secret",
"token",
}, `[\w.=-]{10,150}`, true),
Keywords: []string{
"key",
"access",
"api",
"token",
"secret",
"client",
"auth",
"key",
"credential",
"creds",
"passwd",
"password",
"auth",
"access",
"secret",
"token",
},
Entropy: 3.5,
Allowlist: config.Allowlist{
StopWords: DefaultStopWords,
Allowlists: []config.Allowlist{
{
Description: "Allowlist for Generic API Keys",
MatchCondition: config.AllowlistMatchOr,
Regexes: []*regexp.Regexp{
regexp.MustCompile(`(?i)(` +
// Access
`accessor` +
// API
`|api[_.-]?(version|id)` + // version/id -> not a secret
`|rapid|capital` + // common words containing "api"
// Auth
`|author` +
// Credentials
`|(?-i:(?:c|jobC)redentials?Id|withCredentials)` + // Jenkins plugins
// Key
`|key[_.-]?(alias|board|code|ring|stone|storetype|word|up|down|left|right)` +
`|issuerkeyhash` + // part of ssl cert
`|(bucket|primary|foreign|natural|hot)[_.-]?key` +
`|(?-i:[DdMm]onkey|[DM]ONKEY)|keying` + // common words containing "key"
// Secret
`|(secret)[_.-]?name` + // name of e.g. env variable
// Token
// General
`|public[_.-]?(key|token)` + // public key -> not a secret
`|(key|token)[_.-]?file` +
`)`),
},
RegexTarget: "match",
StopWords: DefaultStopWords,
},
},
}
// validate
tps := []string{
// Access
`'access_token': 'eyJ0eXAioiJKV1slS3oASx=='`,
// API
`some_api_token_123 = "` + newPlausibleSecret(`[a-zA-Z0-9]{60}`) + `"`,
// Auth
// Credentials
`"credentials" : "0afae57f3ccfd9d7f5767067bc48b30f719e271ba470488056e37ab35d4b6506"`,
`creds = ` + newPlausibleSecret(`[a-zA-Z0-9]{30}`),
// Key
`private-key: ` + newPlausibleSecret(`[a-zA-Z0-9\-_.=]{100}`),
// Password
`passwd = ` + newPlausibleSecret(`[a-zA-Z0-9\-_.=]{30}`),
// Secret
`"client_secret" : "6da89121079f83b2eb6acccf8219ea982c3d79bccc3e9c6a85856480661f8fde",`,
`mySecretString=` + newPlausibleSecret(`[a-zA-Z0-9]{30}`),
`todo_secret_do_not_commit = ` + newPlausibleSecret(`[a-zA-Z0-9]{30}`),
// Token
utils.GenerateSampleSecret("generic", "CLOJARS_34bf0e88955ff5a1c328d6a7491acc4f48e865a7b8dd4d70a70749037443"), //gitleaks:allow
utils.GenerateSampleSecret("generic", "Zf3D0LXCM3EIMbgJpUNnkRtOfOueHznB"),
`"client_id" : "0afae57f3ccfd9d7f5767067bc48b30f719e271ba470488056e37ab35d4b6506"`,
`"client_secret" : "6da89121079f83b2eb6acccf8219ea982c3d79bccc3e9c6a85856480661f8fde",`,
}
fps := []string{
`client_vpn_endpoint_id = aws_ec2_client_vpn_endpoint.client-vpn-endpoint.id`,
// Access
`"accessor":"rA1wk0Y45YCufyfq",`,
// API
`this.ultraPictureBox1.Name = "ultraPictureBox1";`,
`rapidstring:marm64-uwp=fail`,
`event-bus-message-api:rc0.15.0_20231217_1420-SNAPSHOT'`,
`COMMUNICATION_API_VERSION=rc0.13.0_20230412_0712-SNAPSHOT`,
`MantleAPI_version=9a038989604e8da62ecddbe2094b16ce1b778be1`,
// Auth
`author = "james.fake@ymail.com",`,
// Credentials
`withCredentials([usernamePassword(credentialsId: '29f63271-dc2f-4734-8221-5b31b5169bac', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {`,
`credentialsId: 'ff083f76-7804-4ef1-80e4-fe975bb9141b'`,
`jobCredentialsId: 'f4aeb6bc-2a25-458a-8111-9be9e502c0e7'`,
` "credentialId": "B9mTcFSck2LzJO2S3ols63",`,
// Key
`keyword: "Befaehigung_P2"`,
`public_key = "9Cnzj4p4WGeKLs1Pt8QuKUpRKfFLfRYC9AIKjbJTWit"`,
`monkeys-audio:mx64-uwp=fail`,
`primaryKey=` + newPlausibleSecret(`[a-zA-Z0-9\-_.=]{30}`),
`foreignKey=` + newPlausibleSecret(`[a-zA-Z0-9\-_.=]{30}`),
`key_down_event=` + newPlausibleSecret(`[a-zA-Z0-9\-_.=]{30}`),
`issuerKeyHash=` + newPlausibleSecret(`[a-zA-Z0-9\-_.=]{30}`),
`<entry key="jetbrains.mps.v8_elimination" value="executed" />`,
`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/"/>`,
`<key tag="SecurityIdentifier" name="SecurityIdentifier" type="STRING" />`,
//`packageKey":` + newPlausibleSecret(`[a-zA-Z0-9\-_.=]{30}`),
// Password
`password combination.
R5: Regulatory--21`,
`PuttyPassword=0`,
// Secret
`LLM_SECRET_NAME = "NEXUS-GPT4-API-KEY"`,
// Token
`publicToken = "9Cnzj4p4WGeKLs1Pt8QuKUpRKfFLfRYC9AIKjbJTWit"`,
`<SourceFile SourceLocation="F:\Extracts\" TokenFile="RTL_INST_CODE.cer">`,
// General
`clientId = "73082700-1f09-405b-80d0-3131bfd6272d"`,
}
return utils.Validate(r, tps, fps)
}
func newPlausibleSecret(regex string) string {
allowList := config.Allowlist{StopWords: DefaultStopWords}
// attempt to generate a random secret,
// retrying until it contains at least one digit and no stop words
// TODO: currently the DefaultStopWords list contains many short words,
// so there is a significant chance of generating a secret that contains a stop word
for {
secret := secrets.NewSecret(regex)
if !regexp.MustCompile(`[1-9]`).MatchString(secret) {
continue
}
if allowList.ContainsStopWord(secret) {
continue
}
return secret
}
}
+16 -5
View File
@@ -8,14 +8,24 @@ import (
"github.com/zricethezav/gitleaks/v8/config"
)
var githubAllowlist = []config.Allowlist{
{
Paths: []*regexp.Regexp{
// https://github.com/octokit/auth-token.js/?tab=readme-ov-file#createtokenauthtoken-options
regexp.MustCompile(`(^|/)@octokit/auth-token/README\.md$`),
},
},
}
func GitHubPat() *config.Rule {
// define rule
r := config.Rule{
Description: "Uncovered a GitHub Personal Access Token, potentially leading to unauthorized repository access and sensitive content exposure.",
RuleID: "github-pat",
Description: "Uncovered a GitHub Personal Access Token, potentially leading to unauthorized repository access and sensitive content exposure.",
Regex: regexp.MustCompile(`ghp_[0-9a-zA-Z]{36}`),
Entropy: 3,
Keywords: []string{"ghp_"},
Allowlists: githubAllowlist,
}
// validate
@@ -31,8 +41,8 @@ func GitHubPat() *config.Rule {
func GitHubFineGrainedPat() *config.Rule {
// define rule
r := config.Rule{
Description: "Found a GitHub Fine-Grained Personal Access Token, risking unauthorized repository access and code manipulation.",
RuleID: "github-fine-grained-pat",
Description: "Found a GitHub Fine-Grained Personal Access Token, risking unauthorized repository access and code manipulation.",
Regex: regexp.MustCompile(`github_pat_\w{82}`),
Entropy: 3,
Keywords: []string{"github_pat_"},
@@ -51,8 +61,8 @@ func GitHubFineGrainedPat() *config.Rule {
func GitHubOauth() *config.Rule {
// define rule
r := config.Rule{
Description: "Discovered a GitHub OAuth Access Token, posing a risk of compromised GitHub account integrations and data leaks.",
RuleID: "github-oauth",
Description: "Discovered a GitHub OAuth Access Token, posing a risk of compromised GitHub account integrations and data leaks.",
Regex: regexp.MustCompile(`gho_[0-9a-zA-Z]{36}`),
Entropy: 3,
Keywords: []string{"gho_"},
@@ -71,11 +81,12 @@ func GitHubOauth() *config.Rule {
func GitHubApp() *config.Rule {
// define rule
r := config.Rule{
Description: "Identified a GitHub App Token, which may compromise GitHub application integrations and source code security.",
RuleID: "github-app-token",
Description: "Identified a GitHub App Token, which may compromise GitHub application integrations and source code security.",
Regex: regexp.MustCompile(`(?:ghu|ghs)_[0-9a-zA-Z]{36}`),
Entropy: 3,
Keywords: []string{"ghu_", "ghs_"},
Allowlists: githubAllowlist,
}
// validate
@@ -93,8 +104,8 @@ func GitHubApp() *config.Rule {
func GitHubRefresh() *config.Rule {
// define rule
r := config.Rule{
Description: "Detected a GitHub Refresh Token, which could allow prolonged unauthorized access to GitHub services.",
RuleID: "github-refresh-token",
Description: "Detected a GitHub Refresh Token, which could allow prolonged unauthorized access to GitHub services.",
Regex: regexp.MustCompile(`ghr_[0-9a-zA-Z]{36}`),
Entropy: 3,
Keywords: []string{"ghr_"},
+168 -14
View File
@@ -1,57 +1,211 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
// overview with all GitLab tokens:
// https://docs.gitlab.com/ee/security/tokens/index.html#token-prefixes
func GitlabCiCdJobToken() *config.Rule {
r := config.Rule{
Description: "Identified a GitLab CI/CD Job Token, potential access to projects and some APIs on behalf of a user while the CI job is running.",
RuleID: "gitlab-cicd-job-token",
Regex: regexp.MustCompile(`glcbt-[0-9a-zA-Z]{1,5}_[0-9a-zA-Z_-]{20}`),
Entropy: 3,
Keywords: []string{"glcbt-"},
}
tps := []string{
utils.GenerateSampleSecret("gitlab", "glcbt-"+secrets.NewSecret(utils.AlphaNumeric("5"))+"_"+secrets.NewSecret(utils.AlphaNumeric("20"))),
}
return utils.Validate(r, tps, nil)
}
func GitlabDeployToken() *config.Rule {
r := config.Rule{
Description: "Identified a GitLab Deploy Token, risking access to repositories, packages and containers with write access.",
RuleID: "gitlab-deploy-token",
Regex: regexp.MustCompile(`gldt-[0-9a-zA-Z_\-]{20}`),
Entropy: 3,
Keywords: []string{"gldt-"},
}
tps := []string{
utils.GenerateSampleSecret("gitlab", "gldt-"+secrets.NewSecret(utils.AlphaNumeric("20"))),
}
return utils.Validate(r, tps, nil)
}
func GitlabFeatureFlagClientToken() *config.Rule {
r := config.Rule{
Description: "Identified a GitLab feature flag client token, risks exposing user lists and features flags used by an application.",
RuleID: "gitlab-feature-flag-client-token",
Regex: regexp.MustCompile(`glffct-[0-9a-zA-Z_\-]{20}`),
Entropy: 3,
Keywords: []string{"glffct-"},
}
tps := []string{
utils.GenerateSampleSecret("gitlab", "glffct-"+secrets.NewSecret(utils.AlphaNumeric("20"))),
}
return utils.Validate(r, tps, nil)
}
func GitlabFeedToken() *config.Rule {
r := config.Rule{
Description: "Identified a GitLab feed token, risking exposure of user data.",
RuleID: "gitlab-feed-token",
Regex: regexp.MustCompile(`glft-[0-9a-zA-Z_\-]{20}`),
Entropy: 3,
Keywords: []string{"glft-"},
}
tps := []string{
utils.GenerateSampleSecret("gitlab", "glft-"+secrets.NewSecret(utils.AlphaNumeric("20"))),
}
return utils.Validate(r, tps, nil)
}
func GitlabIncomingMailToken() *config.Rule {
r := config.Rule{
Description: "Identified a GitLab incoming mail token, risking manipulation of data sent by mail.",
RuleID: "gitlab-incoming-mail-token",
Regex: regexp.MustCompile(`glimt-[0-9a-zA-Z_\-]{25}`),
Entropy: 3,
Keywords: []string{"glimt-"},
}
tps := []string{
utils.GenerateSampleSecret("gitlab", "glimt-"+secrets.NewSecret(utils.AlphaNumeric("25"))),
}
return utils.Validate(r, tps, nil)
}
func GitlabKubernetesAgentToken() *config.Rule {
r := config.Rule{
Description: "Identified a GitLab Kubernetes Agent token, risking access to repos and registry of projects connected via agent.",
RuleID: "gitlab-kubernetes-agent-token",
Regex: regexp.MustCompile(`glagent-[0-9a-zA-Z_\-]{50}`),
Entropy: 3,
Keywords: []string{"glagent-"},
}
tps := []string{
utils.GenerateSampleSecret("gitlab", "glagent-"+secrets.NewSecret(utils.AlphaNumeric("50"))),
}
return utils.Validate(r, tps, nil)
}
func GitlabOauthAppSecret() *config.Rule {
r := config.Rule{
Description: "Identified a GitLab OIDC Application Secret, risking access to apps using GitLab as authentication provider.",
RuleID: "gitlab-oauth-app-secret",
Regex: regexp.MustCompile(`gloas-[0-9a-zA-Z_\-]{64}`),
Entropy: 3,
Keywords: []string{"gloas-"},
}
tps := []string{
utils.GenerateSampleSecret("gitlab", "gloas-"+secrets.NewSecret(utils.AlphaNumeric("64"))),
}
return utils.Validate(r, tps, nil)
}
func GitlabPat() *config.Rule {
// define rule
r := config.Rule{
Description: "Identified a GitLab Personal Access Token, risking unauthorized access to GitLab repositories and codebase exposure.",
RuleID: "gitlab-pat",
Regex: regexp.MustCompile(`glpat-[0-9a-zA-Z\-\_]{20}`),
Description: "Identified a GitLab Personal Access Token, risking unauthorized access to GitLab repositories and codebase exposure.",
Regex: regexp.MustCompile(`glpat-[\w-]{20}`),
Entropy: 3,
Keywords: []string{"glpat-"},
}
// validate
tps := []string{
utils.GenerateSampleSecret("gitlab", "glpat-"+secrets.NewSecret(utils.AlphaNumeric("20"))),
}
return utils.Validate(r, tps, nil)
fps := []string{
"glpat-XXXXXXXXXXX-XXXXXXXX",
}
return utils.Validate(r, tps, fps)
}
func GitlabPipelineTriggerToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Found a GitLab Pipeline Trigger Token, potentially compromising continuous integration workflows and project security.",
RuleID: "gitlab-ptt",
Description: "Found a GitLab Pipeline Trigger Token, potentially compromising continuous integration workflows and project security.",
Regex: regexp.MustCompile(`glptt-[0-9a-f]{40}`),
Entropy: 3,
Keywords: []string{"glptt-"},
}
// validate
tps := []string{
utils.GenerateSampleSecret("gitlab", "glptt-"+secrets.NewSecret(utils.Hex("40"))),
}
return utils.Validate(r, tps, nil)
fps := []string{
"glptt-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
}
return utils.Validate(r, tps, fps)
}
func GitlabRunnerRegistrationToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Discovered a GitLab Runner Registration Token, posing a risk to CI/CD pipeline integrity and unauthorized access.",
RuleID: "gitlab-rrt",
Regex: regexp.MustCompile(`GR1348941[0-9a-zA-Z\-\_]{20}`),
Description: "Discovered a GitLab Runner Registration Token, posing a risk to CI/CD pipeline integrity and unauthorized access.",
Regex: regexp.MustCompile(`GR1348941[\w-]{20}`),
Entropy: 3,
Keywords: []string{"GR1348941"},
}
// validate
tps := []string{
utils.GenerateSampleSecret("gitlab", "GR1348941"+secrets.NewSecret(utils.AlphaNumeric("20"))),
}
fps := []string{
"GR134894112312312312312312312",
"GR1348941XXXXXXXXXXXXXXXXXXXX",
}
return utils.Validate(r, tps, fps)
}
func GitlabRunnerAuthenticationToken() *config.Rule {
r := config.Rule{
Description: "Discovered a GitLab Runner Authentication Token, posing a risk to CI/CD pipeline integrity and unauthorized access.",
RuleID: "gitlab-runner-authentication-token",
Regex: regexp.MustCompile(`glrt-[0-9a-zA-Z_\-]{20}`),
Entropy: 3,
Keywords: []string{"glrt-"},
}
tps := []string{
utils.GenerateSampleSecret("gitlab", "glrt-"+secrets.NewSecret(utils.AlphaNumeric("20"))),
}
return utils.Validate(r, tps, nil)
}
func GitlabScimToken() *config.Rule {
r := config.Rule{
Description: "Discovered a GitLab SCIM Token, posing a risk to unauthorized access for a organization or instance.",
RuleID: "gitlab-scim-token",
Regex: regexp.MustCompile(`glsoat-[0-9a-zA-Z_\-]{20}`),
Entropy: 3,
Keywords: []string{"glsoat-"},
}
tps := []string{
utils.GenerateSampleSecret("gitlab", "glsoat-"+secrets.NewSecret(utils.AlphaNumeric("20"))),
}
return utils.Validate(r, tps, nil)
}
func GitlabSessionCookie() *config.Rule {
r := config.Rule{
Description: "Discovered a GitLab Session Cookie, posing a risk to unauthorized access to a user account.",
RuleID: "gitlab-session-cookie",
Regex: regexp.MustCompile(`_gitlab_session=[0-9a-z]{32}`),
Entropy: 3,
Keywords: []string{"_gitlab_session="},
}
tps := []string{
utils.GenerateSampleSecret("gitlab", "_gitlab_session="+secrets.NewSecret(utils.AlphaNumeric("32"))),
}
return utils.Validate(r, tps, nil)
}
+36 -17
View File
@@ -9,18 +9,16 @@ import (
func GrafanaApiKey() *config.Rule {
// define rule
r := config.Rule{
Description: "Identified a Grafana API key, which could compromise monitoring dashboards and sensitive data analytics.",
RuleID: "grafana-api-key",
Regex: utils.GenerateUniqueTokenRegex(`eyJrIjoi[A-Za-z0-9]{70,400}={0,2}`, true),
Keywords: []string{"eyJrIjoi"},
Description: "Identified a Grafana API key, which could compromise monitoring dashboards and sensitive data analytics.",
Regex: utils.GenerateUniqueTokenRegex(`eyJrIjoi[A-Za-z0-9]{70,400}={0,3}`, true),
Entropy: 3,
Keywords: []string{"eyJrIjoi"},
}
// validate
tps := []string{
utils.GenerateSampleSecret("grafana-api-key",
"eyJrIjoi"+
secrets.NewSecret(utils.AlphaNumeric("70"))),
utils.GenerateSampleSecret("grafana-api-key", "eyJrIjoi"+secrets.NewSecret(utils.AlphaNumeric("70"))),
}
return utils.Validate(r, tps, nil)
}
@@ -28,11 +26,11 @@ func GrafanaApiKey() *config.Rule {
func GrafanaCloudApiToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Found a Grafana cloud API token, risking unauthorized access to cloud-based monitoring services and data exposure.",
RuleID: "grafana-cloud-api-token",
Regex: utils.GenerateUniqueTokenRegex(`glc_[A-Za-z0-9+/]{32,400}={0,2}`, true),
Keywords: []string{"glc_"},
Description: "Found a Grafana cloud API token, risking unauthorized access to cloud-based monitoring services and data exposure.",
Regex: utils.GenerateUniqueTokenRegex(`glc_[A-Za-z0-9+/]{32,400}={0,3}`, true),
Entropy: 3,
Keywords: []string{"glc_"},
}
// validate
@@ -40,18 +38,35 @@ func GrafanaCloudApiToken() *config.Rule {
utils.GenerateSampleSecret("grafana-cloud-api-token",
"glc_"+
secrets.NewSecret(utils.AlphaNumeric("32"))),
`loki_key: glc_eyJvIjoiNzQ0NTg3IiwibiI7InN0YWlrLTQ3NTgzMC1obC13cml0ZS1oYW5kc29uJG9raSIsImsiOiI4M2w3cmdYUlBoMTUyMW1lMU023nl5UDUiLCJtIjp7IOIiOiJ1cyJ9fQ==`,
// TODO:
//` loki:
//endpoint: https://322137:glc_eyJvIjoiNzQ0NTg3IiwibiI7InN0YWlrLTQ3NTgzMC1obC13cml0ZS1oYW5kc29uJG9raSIsImsiOiI4M2w3cmdYUlBoMTUyMW1lMU023nl5UDUiLCJtIjp7IOIiOiJ1cyJ9fQ==@logs-prod4.grafana.net/loki/api/v1/push`,
}
return utils.Validate(r, tps, nil)
fps := []string{
// Low entropy.
`glc_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`,
` API_KEY="glc_111111111111111111111111111111111111111111="`,
// Invalid.
`static void GLC_CreateLightmapTextureArray(void);
static void GLC_CreateLightmapTexturesIndividual(void);
void GLC_UploadLightmap(int textureUnit, int lightmapnum);`,
`// Alias models
void GLC_StateBeginUnderwaterAliasModelCaustics(texture_ref base_texture, texture_ref caustics_texture)
{`,
}
return utils.Validate(r, tps, fps)
}
func GrafanaServiceAccountToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Discovered a Grafana service account token, posing a risk of compromised monitoring services and data integrity.",
RuleID: "grafana-service-account-token",
Regex: utils.GenerateUniqueTokenRegex(`glsa_[A-Za-z0-9]{32}_[A-Fa-f0-9]{8}`, true),
Keywords: []string{"glsa_"},
Description: "Discovered a Grafana service account token, posing a risk of compromised monitoring services and data integrity.",
Regex: utils.GenerateUniqueTokenRegex(`glsa_[A-Za-z0-9]{32}_[A-Fa-f0-9]{8}`, true),
Entropy: 3,
Keywords: []string{"glsa_"},
}
// validate
@@ -61,6 +76,10 @@ func GrafanaServiceAccountToken() *config.Rule {
secrets.NewSecret(utils.AlphaNumeric("32"))+
"_"+
secrets.NewSecret((utils.Hex("8")))),
`'Authorization': 'Bearer glsa_pITqMOBIfNH2KL4PkXJqmTyQl0D9QGxF_486f63e1'`,
}
return utils.Validate(r, tps, nil)
fps := []string{
"glsa_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX_AAAAAAAA",
}
return utils.Validate(r, tps, fps)
}
+4 -3
View File
@@ -12,8 +12,8 @@ import (
func HashiCorpTerraform() *config.Rule {
// define rule
r := config.Rule{
Description: "Uncovered a HashiCorp Terraform user/org API token, which may lead to unauthorized infrastructure management and security breaches.",
RuleID: "hashicorp-tf-api-token",
Description: "Uncovered a HashiCorp Terraform user/org API token, which may lead to unauthorized infrastructure management and security breaches.",
Regex: regexp.MustCompile(`(?i)[a-z0-9]{14}\.(?-i:atlasv1)\.[a-z0-9\-_=]{60,70}`),
Entropy: 3.5,
Keywords: []string{"atlasv1"},
@@ -34,11 +34,12 @@ func HashicorpField() *config.Rule {
keywords := []string{"administrator_login_password", "password"}
// define rule
r := config.Rule{
Description: "Identified a HashiCorp Terraform password field, risking unauthorized infrastructure configuration and security breaches.",
RuleID: "hashicorp-tf-password",
Description: "Identified a HashiCorp Terraform password field, risking unauthorized infrastructure configuration and security breaches.",
Regex: utils.GenerateSemiGenericRegex(keywords, fmt.Sprintf(`"%s"`, utils.AlphaNumericExtended("8,20")), true),
Keywords: keywords,
Entropy: 2,
Path: regexp.MustCompile(`(?i)\.(?:tf|hcl)$`),
Keywords: keywords,
}
tps := map[string]string{
+12 -8
View File
@@ -14,11 +14,13 @@ func VaultServiceToken() *config.Rule {
Description: "Identified a Vault Service Token, potentially compromising infrastructure security and access to sensitive credentials.",
Regex: utils.GenerateUniqueTokenRegex(`(?:hvs\.[\w-]{90,120}|s\.(?i:[a-z0-9]{24}))`, false),
Entropy: 3.5,
Keywords: []string{"hvs", "s."},
Allowlist: config.Allowlist{
Regexes: []*regexp.Regexp{
// https://github.com/gitleaks/gitleaks/issues/1490#issuecomment-2334166357
regexp.MustCompile(`s\.[A-Za-z]{24}`),
Keywords: []string{"hvs.", "s."},
Allowlists: []config.Allowlist{
{
Regexes: []*regexp.Regexp{
// https://github.com/gitleaks/gitleaks/issues/1490#issuecomment-2334166357
regexp.MustCompile(`s\.[A-Za-z]{24}`),
},
},
},
}
@@ -50,15 +52,17 @@ func VaultServiceToken() *config.Rule {
func VaultBatchToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Detected a Vault Batch Token, risking unauthorized access to secret management services and sensitive data.",
RuleID: "vault-batch-token",
Regex: utils.GenerateUniqueTokenRegex(`hvb\.[a-z0-9_-]{138,212}`, true),
Keywords: []string{"hvb"},
Description: "Detected a Vault Batch Token, risking unauthorized access to secret management services and sensitive data.",
Regex: utils.GenerateUniqueTokenRegex(`hvb\.[\w-]{138,300}`, false),
Entropy: 4,
Keywords: []string{"hvb."},
}
// validate
tps := []string{
utils.GenerateSampleSecret("vault", "hvb."+secrets.NewSecret(utils.AlphaNumericExtendedShort("138"))),
`hvb.AAAAAQJgxDgqsGNorpoOR7hPZ5SU-ynBvCl764jyRP_fnX7WvkdkDzGjbLNGdPdtlY33Als2P36yDZueqzfdGw9RsaTeaYXSH7E4RYSWuRoQ9YRKIw8o7mDDY2ZcT3KOB7RwtW1w1FN2eDqcy_sbCjXPaM1iBVH-mqMSYRmRd2nb5D1SJPeBzIYRqSglLc31wUGN7xEzyrKUczqOKsIcybQA`, // gitleaks:allow
}
return utils.Validate(r, tps, nil)
}
+1 -2
View File
@@ -19,8 +19,7 @@ func HuggingFaceAccessToken() *config.Rule {
RuleID: "huggingface-access-token",
Description: "Discovered a Hugging Face Access token, which could lead to unauthorized access to AI models and sensitive data.",
Regex: regexp.MustCompile(`(?:^|[\\'"` + "`" + ` >=:])(hf_[a-zA-Z]{34})(?:$|[\\'"` + "`" + ` <])`),
Entropy: 1,
Entropy: 2,
Keywords: []string{
"hf_",
},
+23 -13
View File
@@ -9,24 +9,34 @@ import (
func InfracostAPIToken() *config.Rule {
// define rule
r := config.Rule{
// Human readable description of the rule
RuleID: "infracost-api-token",
Description: "Detected an Infracost API Token, risking unauthorized access to cloud cost estimation tools and financial data.",
// Unique ID for the rule
RuleID: "infracost-api-token",
// Regex capture group for the actual secret
// Regex used for detecting secrets. See regex section below for more details
Regex: utils.GenerateUniqueTokenRegex(`ico-[a-zA-Z0-9]{32}`, true),
// Keywords used for string matching on fragments (think of this as a prefilter)
Keywords: []string{"ico-"},
Regex: utils.GenerateUniqueTokenRegex(`ico-[a-zA-Z0-9]{32}`, false),
Entropy: 3,
Keywords: []string{"ico-"},
}
// validate
tps := []string{
utils.GenerateSampleSecret("ico", "ico-"+secrets.NewSecret("[A-Za-z0-9]{32}")),
` variable {
name = "INFRACOST_API_KEY"
secret_value = "ico-mlCr1Mn3SRcRiZMObUZOTHLcgtH2Lpgt"
is_secret = true
}`,
// TODO: New format with longer keys?
// ` headers = {
//'X-Api-Key': 'ico-EeDdSfctrmjD14f45f45te5gJ7l6lw4o6M36sXT62a6',
//'Content-Type': 'application/json',
//}`,
}
return utils.Validate(r, tps, nil)
fps := []string{
// Low entropy
`ico-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`,
// Invalid
`http://assets.r7.com/assets/media_box_tv_tres_colunas/video_box.ico-7a388b69018576d24b59331fd60aab0c.png`,
`https://explosivelab.notion.site/Pianificazione-Nerdz-Ng-pubblico-1bc826ecc0994dd8915be97fc3489cde?pvs=74`,
`http://ece252-2.uwaterloo.ca:2540/image?q=gAAAAABdHkoqb9ZaJ3q4dlzEvTgG9WYwKcD9Aw7OUXeFicO-5M5IdNDjHBpKw7KBK3nCVqtuga4yzUaFEpJn8BqA1LzZprIJBw==`,
}
return utils.Validate(r, tps, fps)
}
+2 -1
View File
@@ -11,7 +11,8 @@ func Intra42ClientSecret() *config.Rule {
r := config.Rule{
Description: "Found a Intra42 client secret, which could lead to unauthorized access to the 42School API and sensitive data.",
RuleID: "intra42-client-secret",
Regex: utils.GenerateUniqueTokenRegex(`s-s4t2(?:ud|af)-[abcdef0123456789]{64}`, true),
Regex: utils.GenerateUniqueTokenRegex(`s-s4t2(?:ud|af)-(?i)[abcdef0123456789]{64}`, false),
Entropy: 3,
Keywords: []string{
"intra",
"s-s4t2ud-",
+2
View File
@@ -15,6 +15,7 @@ func JWT() *config.Rule {
Description: "Uncovered a JSON Web Token, which may lead to unauthorized access to web applications and sensitive user data.",
RuleID: "jwt",
Regex: utils.GenerateUniqueTokenRegex(`ey[a-zA-Z0-9]{17,}\.ey[a-zA-Z0-9\/\\_-]{17,}\.(?:[a-zA-Z0-9\/\\_-]{10,}={0,2})?`, false),
Entropy: 3,
Keywords: []string{"ey"},
}
@@ -72,6 +73,7 @@ func JWTBase64() *config.Rule {
Description: "Detected a Base64-encoded JSON Web Token, posing a risk of exposing encoded authentication and data exchange information.",
Regex: regexp.MustCompile(
`\bZXlK(?:(?P<alg>aGJHY2lPaU)|(?P<apu>aGNIVWlPaU)|(?P<apv>aGNIWWlPaU)|(?P<aud>aGRXUWlPaU)|(?P<b64>aU5qUWlP)|(?P<crit>amNtbDBJanBi)|(?P<cty>amRIa2lPaU)|(?P<epk>bGNHc2lPbn)|(?P<enc>bGJtTWlPaU)|(?P<jku>cWEzVWlPaU)|(?P<jwk>cWQyc2lPb)|(?P<iss>cGMzTWlPaU)|(?P<iv>cGRpSTZJ)|(?P<kid>cmFXUWlP)|(?P<key_ops>clpYbGZiM0J6SWpwY)|(?P<kty>cmRIa2lPaUp)|(?P<nonce>dWIyNWpaU0k2)|(?P<p2c>d01tTWlP)|(?P<p2s>d01uTWlPaU)|(?P<ppt>d2NIUWlPaU)|(?P<sub>emRXSWlPaU)|(?P<svt>emRuUWlP)|(?P<tag>MFlXY2lPaU)|(?P<typ>MGVYQWlPaUp)|(?P<url>MWNtd2l)|(?P<use>MWMyVWlPaUp)|(?P<ver>MlpYSWlPaU)|(?P<version>MlpYSnphVzl1SWpv)|(?P<x>NElqb2)|(?P<x5c>NE5XTWlP)|(?P<x5t>NE5YUWlPaU)|(?P<x5ts256>NE5YUWpVekkxTmlJNkl)|(?P<x5u>NE5YVWlPaU)|(?P<zip>NmFYQWlPaU))[a-zA-Z0-9\/\\_+\-\r\n]{40,}={0,2}`),
Entropy: 2,
Keywords: []string{"zxlk"},
}
+15 -8
View File
@@ -17,7 +17,7 @@ func KubernetesSecret() *config.Rule {
// - valid base64 characters
// - longer than 10 characters (no "YmFyCg==")
//language=regexp
dataPat := `\bdata:(?:.|\s){0,100}?\s+([\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:["']?[a-z0-9]{10,}={0,3}["']?|\{\{[ \t\w"|$:=,.-]+}}|""|''))`
dataPat := `\bdata:(?:.|\s){0,100}?\s+([\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:["']?[a-z0-9+/]{10,}={0,3}["']?|\{\{[ \t\w"|$:=,.-]+}}|""|''))`
// define rule
r := config.Rule{
@@ -31,19 +31,26 @@ func KubernetesSecret() *config.Rule {
},
// Kubernetes secrets are usually yaml files.
Path: regexp.MustCompile(`(?i)\.ya?ml$`),
Allowlist: config.Allowlist{
Regexes: []*regexp.Regexp{
// Ignore empty or placeholder values.
// variable: {{ .Values.Example }} (https://helm.sh/docs/chart_template_guide/variables/)
// variable: ""
// variable: ''
regexp.MustCompile(`[\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:\{\{[ \t\w"|$:=,.-]+}}|""|'')`),
Allowlists: []config.Allowlist{
{
Regexes: []*regexp.Regexp{
// Ignore empty or placeholder values.
// variable: {{ .Values.Example }} (https://helm.sh/docs/chart_template_guide/variables/)
// variable: ""
// variable: ''
regexp.MustCompile(`[\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:\{\{[ \t\w"|$:=,.-]+}}|""|'')`),
},
},
},
}
// validate
tps := map[string]string{
"base64-characters.yaml": `
apiVersion: v1
kind: Secret
data:
password: AAAAAAAAAAC7hjsA+H3owFygUv4w5B67lcSx14zff9FCPADiNbSwYWgE+O7Dhiy5tkRecs21ljjofvebe6xsYlA4cVmght0=`,
"comment.yaml": `
apiVersion: v1
kind: Secret
+4 -2
View File
@@ -11,9 +11,10 @@ import (
func LinearAPIToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Detected a Linear API Token, posing a risk to project management tools and sensitive task data.",
RuleID: "linear-api-key",
Description: "Detected a Linear API Token, posing a risk to project management tools and sensitive task data.",
Regex: regexp.MustCompile(`lin_api_(?i)[a-z0-9]{40}`),
Entropy: 2,
Keywords: []string{"lin_api_"},
}
@@ -27,9 +28,10 @@ func LinearAPIToken() *config.Rule {
func LinearClientSecret() *config.Rule {
// define rule
r := config.Rule{
Description: "Identified a Linear Client Secret, which may compromise secure integrations and sensitive project management data.",
RuleID: "linear-client-secret",
Description: "Identified a Linear Client Secret, which may compromise secure integrations and sensitive project management data.",
Regex: utils.GenerateSemiGenericRegex([]string{"linear"}, utils.Hex("32"), true),
Entropy: 2,
Keywords: []string{"linear"},
}
+1 -1
View File
@@ -12,7 +12,7 @@ func NPM() *config.Rule {
RuleID: "npm-access-token",
Description: "Uncovered an npm access token, potentially compromising package management and code repository access.",
Regex: utils.GenerateUniqueTokenRegex(`npm_[a-z0-9]{36}`, true),
Entropy: 2,
Keywords: []string{
"npm_",
},
+9 -7
View File
@@ -16,13 +16,15 @@ func NugetConfigPassword() *config.Rule {
Path: regexp.MustCompile(`(?i)nuget\.config$`),
Keywords: []string{"<add key="},
Entropy: 1,
Allowlist: config.Allowlist{
Regexes: []*regexp.Regexp{
// samples from https://learn.microsoft.com/en-us/nuget/reference/nuget-config-file
regexp.MustCompile(`33f!!lloppa`),
regexp.MustCompile(`hal\+9ooo_da!sY`),
// exclude environment variables
regexp.MustCompile(`^\%\S.*\%$`),
Allowlists: []config.Allowlist{
{
Regexes: []*regexp.Regexp{
// samples from https://learn.microsoft.com/en-us/nuget/reference/nuget-config-file
regexp.MustCompile(`33f!!lloppa`),
regexp.MustCompile(`hal\+9ooo_da!sY`),
// exclude environment variables
regexp.MustCompile(`^\%\S.*\%$`),
},
},
},
}
@@ -0,0 +1,32 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func OctopusDeployApiKey() *config.Rule {
// define rule
r := config.Rule{
RuleID: "octopus-deploy-api-key",
Description: "Discovered a potential Octopus Deploy API key, risking application deployments and operational security.",
Regex: utils.GenerateUniqueTokenRegex(`API-[A-Z0-9]{26}`, false),
Entropy: 3,
Keywords: []string{"api-"},
}
// validate
tps := []string{
utils.GenerateSampleSecret("octopus", secrets.NewSecret(`API-[A-Z0-9]{26}`)),
`set apikey="API-ZNRMR7SL6L3ATMOIK7GKJDKLPY"`, // gitleaks:allow
}
fps := []string{
// Invalid start
`msgstr "GSSAPI-VIRHEKAPSELOINTIMERKKIJONO."`,
`https://sonarcloud.io/api/project_badges/measure?project=Garden-Coin_API-CalculadoraDeInvestimentos&metric=alert_status`,
`https://fog-ringer-f42.notion.site/API-BD80F56CDC1441E6BF6011AB6D852875`, // Invalid end
`<iframe src="./archive/gifs/api-c99e353f761d318322c853c03e.gif"> </iframe>`, // Wrong case
}
return utils.Validate(r, tps, fps)
}
+12 -5
View File
@@ -11,9 +11,8 @@ func OktaAccessToken() *config.Rule {
r := config.Rule{
RuleID: "okta-access-token",
Description: "Identified an Okta Access Token, which may compromise identity management services and user authentication data.",
Regex: utils.GenerateSemiGenericRegex([]string{"okta"},
utils.AlphaNumericExtended("42"), true),
Regex: utils.GenerateSemiGenericRegex([]string{`(?-i:[Oo]kta|OKTA)`}, `00[\w=\-]{40}`, false),
Entropy: 4,
Keywords: []string{
"okta",
},
@@ -21,7 +20,15 @@ func OktaAccessToken() *config.Rule {
// validate
tps := []string{
utils.GenerateSampleSecret("okta", secrets.NewSecret(utils.AlphaNumeric("42"))),
utils.GenerateSampleSecret("okta", secrets.NewSecret(`00[\w=\-]{40}`)),
`"oktaApiToken": "00ebObu4zSNkyc6dimLvUwq4KpTEop-PCEnnfSTpD3",`, // gitleaks:allow
` var OktaApiToken = "00fWkOjwwL9xiFd-Vfgm_ePATIRxVj852Iblbb1DS_";`, // gitleaks:allow
}
return utils.Validate(r, tps, nil)
fps := []string{
`oktaKey = 00000000000000000000000000000000000TUVWXYZ`, // low entropy
`rookTable = 0023452Lllk2KqjLBvaxANWEgTd7bqjsxjo8aZj0wd`, // wrong case
}
return utils.Validate(r, tps, fps)
}
// TODO: Okta client secret?
+2 -2
View File
@@ -11,8 +11,8 @@ func OpenAI() *config.Rule {
r := config.Rule{
RuleID: "openai-api-key",
Description: "Found an OpenAI API Key, posing a risk of unauthorized access to AI services and data manipulation.",
Regex: utils.GenerateUniqueTokenRegex(`sk-[a-zA-Z0-9]{20}T3BlbkFJ[a-zA-Z0-9]{20}`, true),
Regex: utils.GenerateUniqueTokenRegex(`sk-[a-zA-Z0-9]{20}T3BlbkFJ[a-zA-Z0-9]{20}`, false),
Entropy: 3,
Keywords: []string{
"T3BlbkFJ",
},
+2 -3
View File
@@ -15,9 +15,8 @@ func OpenshiftUserToken() *config.Rule {
RuleID: "openshift-user-token",
Description: "Found an OpenShift user token, potentially compromising an OpenShift/Kubernetes cluster.",
// TODO: Do tokens vary in length or are they always 43?
Regex: regexp.MustCompile(`\b(sha256~[\w-]{43})(?:[^\w-]|\z)`),
Entropy: 3.5,
SecretGroup: 0,
Regex: regexp.MustCompile(`\b(sha256~[\w-]{43})(?:[^\w-]|\z)`),
Entropy: 3.5,
Keywords: []string{
"sha256~",
},
+6 -6
View File
@@ -11,8 +11,8 @@ func PlanetScalePassword() *config.Rule {
r := config.Rule{
RuleID: "planetscale-password",
Description: "Discovered a PlanetScale password, which could lead to unauthorized database operations and data breaches.",
Regex: utils.GenerateUniqueTokenRegex(`pscale_pw_(?i)[a-z0-9=\-_\.]{32,64}`, true),
Regex: utils.GenerateUniqueTokenRegex(`pscale_pw_(?i)[\w=\.-]{32,64}`, true),
Entropy: 3,
Keywords: []string{
"pscale_pw_",
},
@@ -32,8 +32,8 @@ func PlanetScaleAPIToken() *config.Rule {
r := config.Rule{
RuleID: "planetscale-api-token",
Description: "Identified a PlanetScale API token, potentially compromising database management and operations.",
Regex: utils.GenerateUniqueTokenRegex(`pscale_tkn_(?i)[a-z0-9=\-_\.]{32,64}`, true),
Regex: utils.GenerateUniqueTokenRegex(`pscale_tkn_(?i)[\w=\.-]{32,64}`, false),
Entropy: 3,
Keywords: []string{
"pscale_tkn_",
},
@@ -53,8 +53,8 @@ func PlanetScaleOAuthToken() *config.Rule {
r := config.Rule{
RuleID: "planetscale-oauth-token",
Description: "Found a PlanetScale OAuth token, posing a risk to database access control and sensitive data integrity.",
Regex: utils.GenerateUniqueTokenRegex(`pscale_oauth_(?i)[a-z0-9=\-_\.]{32,64}`, true),
Regex: utils.GenerateUniqueTokenRegex(`pscale_oauth_[\w=\.-]{32,64}`, false),
Entropy: 3,
Keywords: []string{
"pscale_oauth_",
},
+2 -2
View File
@@ -11,8 +11,8 @@ func PostManAPI() *config.Rule {
r := config.Rule{
RuleID: "postman-api-token",
Description: "Uncovered a Postman API token, potentially compromising API testing and development workflows.",
Regex: utils.GenerateUniqueTokenRegex(`PMAK-(?i)[a-f0-9]{24}\-[a-f0-9]{34}`, true),
Regex: utils.GenerateUniqueTokenRegex(`PMAK-(?i)[a-f0-9]{24}\-[a-f0-9]{34}`, false),
Entropy: 3,
Keywords: []string{
"PMAK-",
},
+6 -3
View File
@@ -11,8 +11,8 @@ func Prefect() *config.Rule {
r := config.Rule{
RuleID: "prefect-api-token",
Description: "Detected a Prefect API token, risking unauthorized access to workflow management and automation services.",
Regex: utils.GenerateUniqueTokenRegex(`pnu_[a-z0-9]{36}`, true),
Regex: utils.GenerateUniqueTokenRegex(`pnu_[a-zA-Z0-9]{36}`, false),
Entropy: 2,
Keywords: []string{
"pnu_",
},
@@ -22,5 +22,8 @@ func Prefect() *config.Rule {
tps := []string{
utils.GenerateSampleSecret("api-token", "pnu_"+secrets.NewSecret(utils.AlphaNumeric("36"))),
}
return utils.Validate(r, tps, nil)
fps := []string{
`PREFECT_API_KEY = "pnu_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"`,
}
return utils.Validate(r, tps, fps)
}
+6 -3
View File
@@ -11,8 +11,8 @@ func PulumiAPIToken() *config.Rule {
r := config.Rule{
RuleID: "pulumi-api-token",
Description: "Found a Pulumi API token, posing a risk to infrastructure as code services and cloud resource management.",
Regex: utils.GenerateUniqueTokenRegex(`pul-[a-f0-9]{40}`, true),
Regex: utils.GenerateUniqueTokenRegex(`pul-[a-f0-9]{40}`, false),
Entropy: 2,
Keywords: []string{
"pul-",
},
@@ -22,5 +22,8 @@ func PulumiAPIToken() *config.Rule {
tps := []string{
utils.GenerateSampleSecret("pulumi-api-token", "pul-"+secrets.NewSecret(utils.Hex("40"))),
}
return utils.Validate(r, tps, nil)
fps := []string{
` <img src="./assets/vipul-f0eb1acf0da84c06a50c5b2c59932001997786b176dec02bd16128ee9ea83628.png" alt="" class="w-16 h-16 rounded-full">`,
}
return utils.Validate(r, tps, fps)
}
+2 -2
View File
@@ -13,8 +13,8 @@ func PyPiUploadToken() *config.Rule {
r := config.Rule{
Description: "Discovered a PyPI upload token, potentially compromising Python package distribution and repository integrity.",
RuleID: "pypi-upload-token",
Regex: regexp.MustCompile(
`pypi-AgEIcHlwaS5vcmc[A-Za-z0-9\-_]{50,1000}`),
Regex: regexp.MustCompile(`pypi-AgEIcHlwaS5vcmc[\w-]{50,1000}`),
Entropy: 3,
Keywords: []string{
"pypi-AgEIcHlwaS5vcmc",
},
+6 -3
View File
@@ -11,8 +11,8 @@ func ReadMe() *config.Rule {
r := config.Rule{
RuleID: "readme-api-token",
Description: "Detected a Readme API token, risking unauthorized documentation management and content exposure.",
Regex: utils.GenerateUniqueTokenRegex(`rdme_[a-z0-9]{70}`, true),
Regex: utils.GenerateUniqueTokenRegex(`rdme_[a-z0-9]{70}`, false),
Entropy: 2,
Keywords: []string{
"rdme_",
},
@@ -22,5 +22,8 @@ func ReadMe() *config.Rule {
tps := []string{
utils.GenerateSampleSecret("api-token", "rdme_"+secrets.NewSecret(utils.AlphaNumeric("70"))),
}
return utils.Validate(r, tps, nil)
fps := []string{
`const API_KEY = 'rdme_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';`,
}
return utils.Validate(r, tps, fps)
}
+2 -2
View File
@@ -11,8 +11,8 @@ func RubyGemsAPIToken() *config.Rule {
r := config.Rule{
RuleID: "rubygems-api-token",
Description: "Identified a Rubygem API token, potentially compromising Ruby library distribution and package management.",
Regex: utils.GenerateUniqueTokenRegex(`rubygems_[a-f0-9]{48}`, true),
Regex: utils.GenerateUniqueTokenRegex(`rubygems_[a-f0-9]{48}`, false),
Entropy: 2,
Keywords: []string{
"rubygems_",
},
+2 -1
View File
@@ -11,7 +11,8 @@ func ScalingoAPIToken() *config.Rule {
r := config.Rule{
Description: "Found a Scalingo API token, posing a risk to cloud platform services and application deployment security.",
RuleID: "scalingo-api-token",
Regex: utils.GenerateUniqueTokenRegex(`tk-us-[a-zA-Z0-9-_]{48}`, false),
Regex: utils.GenerateUniqueTokenRegex(`tk-us-[\w-]{48}`, false),
Entropy: 2,
Keywords: []string{"tk-us-"},
}
+2 -2
View File
@@ -11,8 +11,8 @@ func SendGridAPIToken() *config.Rule {
r := config.Rule{
RuleID: "sendgrid-api-token",
Description: "Detected a SendGrid API token, posing a risk of unauthorized email service operations and data exposure.",
Regex: utils.GenerateUniqueTokenRegex(`SG\.(?i)[a-z0-9=_\-\.]{66}`, true),
Regex: utils.GenerateUniqueTokenRegex(`SG\.(?i)[a-z0-9=_\-\.]{66}`, false),
Entropy: 2,
Keywords: []string{
"SG.",
},
+2 -2
View File
@@ -11,8 +11,8 @@ func SendInBlueAPIToken() *config.Rule {
r := config.Rule{
RuleID: "sendinblue-api-token",
Description: "Identified a Sendinblue API token, which may compromise email marketing services and subscriber data privacy.",
Regex: utils.GenerateUniqueTokenRegex(`xkeysib-[a-f0-9]{64}\-(?i)[a-z0-9]{16}`, true),
Regex: utils.GenerateUniqueTokenRegex(`xkeysib-[a-f0-9]{64}\-(?i)[a-z0-9]{16}`, false),
Entropy: 2,
Keywords: []string{
"xkeysib-",
},
+2 -2
View File
@@ -11,8 +11,8 @@ func ShippoAPIToken() *config.Rule {
r := config.Rule{
RuleID: "shippo-api-token",
Description: "Discovered a Shippo API token, potentially compromising shipping services and customer order data.",
Regex: utils.GenerateUniqueTokenRegex(`shippo_(live|test)_[a-f0-9]{40}`, true),
Regex: utils.GenerateUniqueTokenRegex(`shippo_(?:live|test)_[a-fA-F0-9]{40}`, false),
Entropy: 2,
Keywords: []string{
"shippo_",
},
+8 -4
View File
@@ -11,9 +11,10 @@ import (
func ShopifySharedSecret() *config.Rule {
// define rule
r := config.Rule{
Description: "Found a Shopify shared secret, posing a risk to application authentication and e-commerce platform security.",
RuleID: "shopify-shared-secret",
Description: "Found a Shopify shared secret, posing a risk to application authentication and e-commerce platform security.",
Regex: regexp.MustCompile(`shpss_[a-fA-F0-9]{32}`),
Entropy: 2,
Keywords: []string{"shpss_"},
}
@@ -25,9 +26,10 @@ func ShopifySharedSecret() *config.Rule {
func ShopifyAccessToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Uncovered a Shopify access token, which could lead to unauthorized e-commerce platform access and data breaches.",
RuleID: "shopify-access-token",
Description: "Uncovered a Shopify access token, which could lead to unauthorized e-commerce platform access and data breaches.",
Regex: regexp.MustCompile(`shpat_[a-fA-F0-9]{32}`),
Entropy: 2,
Keywords: []string{"shpat_"},
}
@@ -39,9 +41,10 @@ func ShopifyAccessToken() *config.Rule {
func ShopifyCustomAccessToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Detected a Shopify custom access token, potentially compromising custom app integrations and e-commerce data security.",
RuleID: "shopify-custom-access-token",
Description: "Detected a Shopify custom access token, potentially compromising custom app integrations and e-commerce data security.",
Regex: regexp.MustCompile(`shpca_[a-fA-F0-9]{32}`),
Entropy: 2,
Keywords: []string{"shpca_"},
}
@@ -53,9 +56,10 @@ func ShopifyCustomAccessToken() *config.Rule {
func ShopifyPrivateAppAccessToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Identified a Shopify private app access token, risking unauthorized access to private app data and store operations.",
RuleID: "shopify-private-app-access-token",
Description: "Identified a Shopify private app access token, risking unauthorized access to private app data and store operations.",
Regex: regexp.MustCompile(`shppa_[a-fA-F0-9]{32}`),
Entropy: 2,
Keywords: []string{"shppa_"},
}
+21 -16
View File
@@ -13,10 +13,10 @@ import (
func SlackBotToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Identified a Slack Bot token, which may compromise bot integrations and communication channel security.",
RuleID: "slack-bot-token",
Regex: regexp.MustCompile(
`(xoxb-[0-9]{10,13}\-[0-9]{10,13}[a-zA-Z0-9-]*)`),
Description: "Identified a Slack Bot token, which may compromise bot integrations and communication channel security.",
Regex: regexp.MustCompile(`xoxb-[0-9]{10,13}-[0-9]{10,13}[a-zA-Z0-9-]*`),
Entropy: 3,
Keywords: []string{
"xoxb",
},
@@ -44,10 +44,11 @@ func SlackBotToken() *config.Rule {
func SlackUserToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Found a Slack User token, posing a risk of unauthorized user impersonation and data access within Slack workspaces.",
RuleID: "slack-user-token",
Description: "Found a Slack User token, posing a risk of unauthorized user impersonation and data access within Slack workspaces.",
// The last segment seems to be consistently 32 characters. I've made it 28-34 just in case.
Regex: regexp.MustCompile(`xox[pe](?:-[0-9]{10,13}){3}-[a-zA-Z0-9-]{28,34}`),
Entropy: 2,
Keywords: []string{"xoxp-", "xoxe-"},
}
@@ -82,10 +83,11 @@ func SlackUserToken() *config.Rule {
func SlackAppLevelToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Detected a Slack App-level token, risking unauthorized access to Slack applications and workspace data.",
RuleID: "slack-app-token",
Description: "Detected a Slack App-level token, risking unauthorized access to Slack applications and workspace data.",
// This regex is based on a limited number of examples and may not be 100% accurate.
Regex: regexp.MustCompile(`(?i)xapp-\d-[A-Z0-9]+-\d+-[a-z0-9]+`),
Entropy: 2,
Keywords: []string{"xapp"},
}
@@ -103,9 +105,10 @@ func SlackAppLevelToken() *config.Rule {
func SlackConfigurationToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Found a Slack Configuration access token, posing a risk to workspace configuration and sensitive data access.",
RuleID: "slack-config-access-token",
Description: "Found a Slack Configuration access token, posing a risk to workspace configuration and sensitive data access.",
Regex: regexp.MustCompile(`(?i)xoxe.xox[bp]-\d-[A-Z0-9]{163,166}`),
Entropy: 2,
Keywords: []string{"xoxe.xoxb-", "xoxe.xoxp-"},
}
@@ -128,9 +131,10 @@ func SlackConfigurationToken() *config.Rule {
func SlackConfigurationRefreshToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Discovered a Slack Configuration refresh token, potentially allowing prolonged unauthorized access to configuration settings.",
RuleID: "slack-config-refresh-token",
Description: "Discovered a Slack Configuration refresh token, potentially allowing prolonged unauthorized access to configuration settings.",
Regex: regexp.MustCompile(`(?i)xoxe-\d-[A-Z0-9]{146}`),
Entropy: 2,
Keywords: []string{"xoxe-"},
}
@@ -146,11 +150,11 @@ func SlackConfigurationRefreshToken() *config.Rule {
// Reference: https://api.slack.com/authentication/token-types#legacy_bot
func SlackLegacyBotToken() *config.Rule {
r := config.Rule{
Description: "Uncovered a Slack Legacy bot token, which could lead to compromised legacy bot operations and data exposure.",
RuleID: "slack-legacy-bot-token",
Description: "Uncovered a Slack Legacy bot token, which could lead to compromised legacy bot operations and data exposure.",
// This rule is based off the limited information I could find and may not be 100% accurate.
Regex: regexp.MustCompile(
`(xoxb-[0-9]{8,14}\-[a-zA-Z0-9]{18,26})`),
Regex: regexp.MustCompile(`xoxb-[0-9]{8,14}-[a-zA-Z0-9]{18,26}`),
Entropy: 2,
Keywords: []string{
"xoxb",
},
@@ -189,11 +193,11 @@ func SlackLegacyBotToken() *config.Rule {
// Reference: https://api.slack.com/authentication/token-types#workspace
func SlackLegacyWorkspaceToken() *config.Rule {
r := config.Rule{
Description: "Identified a Slack Legacy Workspace token, potentially compromising access to workspace data and legacy features.",
RuleID: "slack-legacy-workspace-token",
Description: "Identified a Slack Legacy Workspace token, potentially compromising access to workspace data and legacy features.",
// This is by far the least confident pattern.
Regex: regexp.MustCompile(
`(xox[ar]-(?:\d-)?[0-9a-zA-Z]{8,48})`),
Regex: regexp.MustCompile(`xox[ar]-(?:\d-)?[0-9a-zA-Z]{8,48}`),
Entropy: 2,
Keywords: []string{
"xoxa",
"xoxr",
@@ -224,9 +228,10 @@ func SlackLegacyWorkspaceToken() *config.Rule {
func SlackLegacyToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Detected a Slack Legacy token, risking unauthorized access to older Slack integrations and user data.",
RuleID: "slack-legacy-token",
Description: "Detected a Slack Legacy token, risking unauthorized access to older Slack integrations and user data.",
Regex: regexp.MustCompile(`xox[os]-\d+-\d+-\d+-[a-fA-F\d]+`),
Entropy: 2,
Keywords: []string{"xoxo", "xoxs"},
}
@@ -255,11 +260,11 @@ func SlackLegacyToken() *config.Rule {
func SlackWebHookUrl() *config.Rule {
// define rule
r := config.Rule{
Description: "Discovered a Slack Webhook, which could lead to unauthorized message posting and data leakage in Slack channels.",
RuleID: "slack-webhook-url",
Description: "Discovered a Slack Webhook, which could lead to unauthorized message posting and data leakage in Slack channels.",
// If this generates too many false-positives we should define an allowlist (e.g., "xxxx", "00000").
Regex: regexp.MustCompile(
`(https?:\/\/)?hooks.slack.com\/(services|workflows)\/[A-Za-z0-9+\/]{43,46}`),
`(?:https?://)?hooks.slack.com/(?:services|workflows)/[A-Za-z0-9+/]{43,46}`),
Keywords: []string{
"hooks.slack.com",
},
+2
View File
@@ -12,6 +12,7 @@ func SquareAccessToken() *config.Rule {
RuleID: "square-access-token",
Description: "Detected a Square Access Token, risking unauthorized payment processing and financial transaction exposure.",
Regex: utils.GenerateUniqueTokenRegex(`(?:EAAA|sq0atp-)[\w-]{22,60}`, false),
Entropy: 2,
Keywords: []string{"sq0atp-", "EAAA"},
}
@@ -33,6 +34,7 @@ func SquareSecret() *config.Rule {
RuleID: "square-secret",
Description: "Square Secret",
Regex: utils.GenerateUniqueTokenRegex(`sq0csp-[\w-]{43}`, false),
Entropy: 2,
Keywords: []string{"sq0csp-"},
}
+2
View File
@@ -638,6 +638,7 @@ var DefaultStopWords = []string{
"jbos",
"jekyll",
"jenkin",
"jetbrains",
"job-",
"job.",
"job_",
@@ -1181,6 +1182,7 @@ var DefaultStopWords = []string{
"smart",
"smtp",
"snake",
"snapshot",
"snippet",
"soap",
"social",
+3 -2
View File
@@ -9,9 +9,10 @@ import (
func StripeAccessToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Found a Stripe Access Token, posing a risk to payment processing services and sensitive financial data.",
RuleID: "stripe-access-token",
Regex: utils.GenerateUniqueTokenRegex(`(sk|rk)_(test|live|prod)_[0-9a-z]{10,99}`, true),
Description: "Found a Stripe Access Token, posing a risk to payment processing services and sensitive financial data.",
Regex: utils.GenerateUniqueTokenRegex(`(?:sk|rk)_(?:test|live|prod)_[a-zA-Z0-9]{10,99}`, false),
Entropy: 2,
Keywords: []string{
"sk_test",
"sk_live",
+5 -15
View File
@@ -2,8 +2,6 @@ package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
@@ -14,19 +12,11 @@ func SumoLogicAccessID() *config.Rule {
RuleID: "sumologic-access-id",
Description: "Discovered a SumoLogic Access ID, potentially compromising log management services and data analytics integrity.",
// TODO: Make 'su' case-sensitive.
Regex: utils.GenerateSemiGenericRegex([]string{"sumo"},
"su[a-zA-Z0-9]{12}", false),
Regex: utils.GenerateSemiGenericRegex([]string{"(?-i:[Ss]umo|SUMO)"}, "su[a-zA-Z0-9]{12}", false),
Entropy: 3,
Keywords: []string{
"sumo",
},
Allowlist: config.Allowlist{
RegexTarget: "line",
Regexes: []*regexp.Regexp{
regexp.MustCompile(`sumOf`),
},
},
}
// validate
@@ -47,6 +37,7 @@ func SumoLogicAccessID() *config.Rule {
`sumologic_access_id = ""`,
`SUMOLOGIC_ACCESSID: ${SUMOLOGIC_ACCESSID}`,
`export SUMOLOGIC_ACCESSID=XXXXXXXXXXXXXX`, // gitleaks:allow
`sumObj = suGyI5imvADdvU`,
}
return utils.Validate(r, tps, fps)
}
@@ -56,10 +47,8 @@ func SumoLogicAccessToken() *config.Rule {
r := config.Rule{
RuleID: "sumologic-access-token",
Description: "Uncovered a SumoLogic Access Token, which could lead to unauthorized access to log data and analytics insights.",
Regex: utils.GenerateSemiGenericRegex([]string{"sumo"},
utils.AlphaNumeric("64"), true),
Entropy: 3,
Regex: utils.GenerateSemiGenericRegex([]string{"(?-i:[Ss]umo|SUMO)"}, utils.AlphaNumeric("64"), true),
Entropy: 3,
Keywords: []string{
"sumo",
},
@@ -80,6 +69,7 @@ func SumoLogicAccessToken() *config.Rule {
`SUMO_ACCESS_KEY=${SUMO_ACCESS_KEY:=$2}`,
`sumo_access_key = "<SUMOLOGIC ACCESS KEY>"`,
`SUMO_ACCESS_KEY: AbCeFG123`,
`sumOfExposures = 3Kof2VffNQ0QgYIhXUPJosVlCaQKm2hfpWE6F1fT9YGY74blQBIPsrkCcf1TwKE5;`,
}
return utils.Validate(r, tps, fps)
}
+2 -2
View File
@@ -11,10 +11,10 @@ import (
func TeamsWebhook() *config.Rule {
// define rule
r := config.Rule{
Description: "Uncovered a Microsoft Teams Webhook, which could lead to unauthorized access to team collaboration tools and data leaks.",
RuleID: "microsoft-teams-webhook",
Description: "Uncovered a Microsoft Teams Webhook, which could lead to unauthorized access to team collaboration tools and data leaks.",
Regex: regexp.MustCompile(
`https:\/\/[a-z0-9]+\.webhook\.office\.com\/webhookb2\/[a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}@[a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}\/IncomingWebhook\/[a-z0-9]{32}\/[a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}`),
`https://[a-z0-9]+\.webhook\.office\.com/webhookb2/[a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}@[a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}/IncomingWebhook/[a-z0-9]{32}/[a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}`),
Keywords: []string{
"webhook.office.com",
"webhookb2",
+3 -2
View File
@@ -11,10 +11,11 @@ import (
func Twilio() *config.Rule {
// define rule
r := config.Rule{
Description: "Found a Twilio API Key, posing a risk to communication services and sensitive customer interaction data.",
RuleID: "twilio-api-key",
Description: "Found a Twilio API Key, posing a risk to communication services and sensitive customer interaction data.",
Regex: regexp.MustCompile(`SK[0-9a-fA-F]{32}`),
Keywords: []string{"twilio"},
Entropy: 3,
Keywords: []string{"SK"},
}
// validate
+3 -3
View File
@@ -15,10 +15,10 @@ const (
caseInsensitive = `(?i)`
// identifier prefix (just an ignore group)
identifierCaseInsensitivePrefix = `(?i:`
identifierCaseInsensitivePrefix = `[\w.-]{0,10}?(?i:`
identifierCaseInsensitiveSuffix = `)`
identifierPrefix = `(?:`
identifierSuffix = `)(?:[0-9a-z\-_\t .]{0,20})(?:[\s|']|[\s|"]){0,3}`
identifierPrefix = `[\w.-]{0,10}?(?:`
identifierSuffix = `)(?:[ \t\w.-]{0,20})(?:[\s|']|[\s|"]){0,3}`
// commonly used assignment operators or function call
operator = `(?:=|>|:{1,3}=|\|\|:|<=|=>|:|\?=)`
+57 -8
View File
@@ -1,16 +1,42 @@
package config
import (
"fmt"
"regexp"
"strings"
"golang.org/x/exp/maps"
)
type AllowlistMatchCondition int
const (
AllowlistMatchOr AllowlistMatchCondition = iota
AllowlistMatchAnd
)
func (a AllowlistMatchCondition) String() string {
return [...]string{
"OR",
"AND",
}[a]
}
// Allowlist allows a rule to be ignored for specific
// regexes, paths, and/or commits
type Allowlist struct {
// Short human readable description of the allowlist.
Description string
// MatchCondition determines whether all criteria must match.
MatchCondition AllowlistMatchCondition
// Commits is a slice of commit SHAs that are allowed to be ignored. Defaults to "OR".
Commits []string
// Paths is a slice of path regular expressions that are allowed to be ignored.
Paths []*regexp.Regexp
// Regexes is slice of content regular expressions that are allowed to be ignored.
Regexes []*regexp.Regexp
@@ -23,12 +49,6 @@ type Allowlist struct {
// If RegexTarget is empty, it will be tested against the found secret.
RegexTarget string
// Paths is a slice of path regular expressions that are allowed to be ignored.
Paths []*regexp.Regexp
// Commits is a slice of commit SHAs that are allowed to be ignored.
Commits []string
// StopWords is a slice of stop words that are allowed to be ignored.
// This targets the _secret_, not the content of the regex match like the
// Regexes slice.
@@ -54,8 +74,8 @@ func (a *Allowlist) PathAllowed(path string) bool {
}
// RegexAllowed returns true if the regex is allowed to be ignored.
func (a *Allowlist) RegexAllowed(s string) bool {
return anyRegexMatch(s, a.Regexes)
func (a *Allowlist) RegexAllowed(secret string) bool {
return anyRegexMatch(secret, a.Regexes)
}
func (a *Allowlist) ContainsStopWord(s string) bool {
@@ -67,3 +87,32 @@ func (a *Allowlist) ContainsStopWord(s string) bool {
}
return false
}
func (a *Allowlist) Validate() error {
// Disallow empty allowlists.
if len(a.Commits) == 0 &&
len(a.Paths) == 0 &&
len(a.Regexes) == 0 &&
len(a.StopWords) == 0 {
return fmt.Errorf("[[rules.allowlists]] must contain at least one check for: commits, paths, regexes, or stopwords")
}
// Deduplicate commits and stopwords.
if len(a.Commits) > 0 {
uniqueCommits := make(map[string]struct{})
for _, commit := range a.Commits {
uniqueCommits[commit] = struct{}{}
}
a.Commits = maps.Keys(uniqueCommits)
}
if len(a.StopWords) > 0 {
uniqueStopwords := make(map[string]struct{})
for _, stopWord := range a.StopWords {
uniqueStopwords[stopWord] = struct{}{}
}
a.StopWords = maps.Keys(uniqueStopwords)
}
return nil
}
+62
View File
@@ -1,9 +1,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"
)
@@ -91,3 +94,62 @@ func TestPathAllowed(t *testing.T) {
assert.Equal(t, tt.pathAllowed, tt.allowlist.PathAllowed(tt.path))
}
}
func TestValidate(t *testing.T) {
tests := map[string]struct {
input Allowlist
expected Allowlist
wantErr error
}{
"empty conditions": {
input: Allowlist{},
wantErr: errors.New("[[rules.allowlists]] must contain at least one check for: commits, paths, regexes, or stopwords"),
},
"deduplicated commits and stopwords": {
input: Allowlist{
Commits: []string{"commitA", "commitB", "commitA"},
StopWords: []string{"stopwordA", "stopwordB", "stopwordA"},
},
expected: Allowlist{
Commits: []string{"commitA", "commitB"},
StopWords: []string{"stopwordA", "stopwordB"},
},
},
}
for _, tt := range tests {
// Expected an error.
err := tt.input.Validate()
if err != nil {
if tt.wantErr == nil {
t.Fatalf("Received unexpected error: %v", err)
} else if !assert.EqualError(t, err, tt.wantErr.Error()) {
t.Fatalf("Received unexpected error, expected '%v', got '%v'", tt.wantErr, err)
}
} else {
if tt.wantErr != nil {
t.Fatalf("Did not receive expected error: %v", tt.wantErr)
}
}
var (
regexComparer = func(x, y *regexp.Regexp) bool {
// Compare the string representation of the regex patterns.
if x == nil || y == nil {
return x == y
}
return x.String() == y.String()
}
arrayComparer = func(a, b string) bool {
return a < b
}
opts = cmp.Options{
cmp.Comparer(regexComparer),
cmpopts.SortSlices(arrayComparer),
}
)
if diff := cmp.Diff(tt.input, tt.expected, opts); diff != "" {
t.Errorf("diff: (-want +got)\n%s", diff)
}
}
}
+113 -58
View File
@@ -2,6 +2,7 @@ package config
import (
_ "embed"
"fmt"
"regexp"
"sort"
"strings"
@@ -28,30 +29,36 @@ type ViperConfig struct {
Rules []struct {
ID string
Description string
Entropy float64
SecretGroup int
Regex string
SecretGroup int
Entropy float64
Keywords []string
Path string
Tags []string
Allowlist struct {
RegexTarget string
Regexes []string
Paths []string
Commits []string
StopWords []string
}
// Deprecated: this is a shim for backwards-compatibility. It should be removed in 9.x.
AllowList *viperRuleAllowlist
Allowlists []viperRuleAllowlist
}
Allowlist struct {
Commits []string
Paths []string
RegexTarget string
Regexes []string
Paths []string
Commits []string
StopWords []string
}
}
type viperRuleAllowlist struct {
Description string
Condition string
Commits []string
Paths []string
RegexTarget string
Regexes []string
StopWords []string
}
// Config is a configuration struct that contains rules and an allowlist if present.
type Config struct {
Title string
@@ -81,60 +88,93 @@ func (vc *ViperConfig) Translate() (Config, error) {
rulesMap = make(map[string]Rule)
)
for _, r := range vc.Rules {
var allowlistRegexes []*regexp.Regexp
for _, a := range r.Allowlist.Regexes {
allowlistRegexes = append(allowlistRegexes, regexp.MustCompile(a))
}
var allowlistPaths []*regexp.Regexp
for _, a := range r.Allowlist.Paths {
allowlistPaths = append(allowlistPaths, regexp.MustCompile(a))
}
if r.Keywords == nil {
r.Keywords = []string{}
// Validate individual rules.
for _, vr := range vc.Rules {
if vr.Keywords == nil {
vr.Keywords = []string{}
} else {
for _, k := range r.Keywords {
for _, k := range vr.Keywords {
keywords[strings.ToLower(k)] = struct{}{}
}
}
if r.Tags == nil {
r.Tags = []string{}
if vr.Tags == nil {
vr.Tags = []string{}
}
var configRegex *regexp.Regexp
var configPathRegex *regexp.Regexp
if r.Regex == "" {
configRegex = nil
} else {
configRegex = regexp.MustCompile(r.Regex)
if vr.Regex != "" {
configRegex = regexp.MustCompile(vr.Regex)
}
if r.Path == "" {
configPathRegex = nil
} else {
configPathRegex = regexp.MustCompile(r.Path)
}
r := Rule{
RuleID: r.ID,
Description: r.Description,
Regex: configRegex,
Path: configPathRegex,
SecretGroup: r.SecretGroup,
Entropy: r.Entropy,
Tags: r.Tags,
Keywords: r.Keywords,
Allowlist: Allowlist{
RegexTarget: r.Allowlist.RegexTarget,
Regexes: allowlistRegexes,
Paths: allowlistPaths,
Commits: r.Allowlist.Commits,
StopWords: r.Allowlist.StopWords,
},
if vr.Path != "" {
configPathRegex = regexp.MustCompile(vr.Path)
}
orderedRules = append(orderedRules, r.RuleID)
rulesMap[r.RuleID] = r
rule := Rule{
RuleID: vr.ID,
Description: vr.Description,
Regex: configRegex,
SecretGroup: vr.SecretGroup,
Entropy: vr.Entropy,
Path: configPathRegex,
Keywords: vr.Keywords,
Tags: vr.Tags,
}
// Parse the allowlist, including the older format for backwards compatibility.
if vr.AllowList != nil {
if len(vr.Allowlists) > 0 {
return Config{}, fmt.Errorf("%s: [rules.allowlist] is deprecated, it cannot be used alongside [[rules.allowlist]]", rule.RuleID)
}
vr.Allowlists = append(vr.Allowlists, *vr.AllowList)
}
for _, a := range vr.Allowlists {
var condition AllowlistMatchCondition
c := strings.ToUpper(a.Condition)
switch c {
case "AND", "&&":
condition = AllowlistMatchAnd
case "", "OR", "||":
condition = AllowlistMatchOr
default:
return Config{}, fmt.Errorf("%s: unknown allowlist condition '%s' (expected 'and', 'or')", rule.RuleID, c)
}
// Validate the target.
if a.RegexTarget != "" {
switch a.RegexTarget {
case "secret":
a.RegexTarget = ""
case "match", "line":
// do nothing
default:
return Config{}, fmt.Errorf("%s: unknown allowlist |regexTarget| '%s' (expected 'match', 'line')", rule.RuleID, a.RegexTarget)
}
}
var allowlistRegexes []*regexp.Regexp
for _, a := range a.Regexes {
allowlistRegexes = append(allowlistRegexes, regexp.MustCompile(a))
}
var allowlistPaths []*regexp.Regexp
for _, a := range a.Paths {
allowlistPaths = append(allowlistPaths, regexp.MustCompile(a))
}
allowlist := Allowlist{
MatchCondition: condition,
RegexTarget: a.RegexTarget,
Regexes: allowlistRegexes,
Paths: allowlistPaths,
Commits: a.Commits,
StopWords: a.StopWords,
}
if err := allowlist.Validate(); err != nil {
return Config{}, fmt.Errorf("%s: %w", rule.RuleID, err)
}
rule.Allowlists = append(rule.Allowlists, allowlist)
}
orderedRules = append(orderedRules, rule.RuleID)
rulesMap[rule.RuleID] = rule
}
var allowlistRegexes []*regexp.Regexp
for _, a := range vc.Allowlist.Regexes {
@@ -252,11 +292,26 @@ func (c *Config) extend(extensionConfig Config) {
c.OrderedRules = append(c.OrderedRules, ruleID)
} else {
// Rule exists, merge our changes into the base.
baseRule.Allowlist.Commits = append(baseRule.Allowlist.Commits, currentRule.Allowlist.Commits...)
baseRule.Allowlist.Paths = append(baseRule.Allowlist.Paths, currentRule.Allowlist.Paths...)
baseRule.Allowlist.Regexes = append(baseRule.Allowlist.Regexes, currentRule.Allowlist.Regexes...)
baseRule.Allowlist.RegexTarget = currentRule.Allowlist.RegexTarget
baseRule.Allowlist.StopWords = append(baseRule.Allowlist.StopWords, currentRule.Allowlist.StopWords...)
if currentRule.Description != "" {
baseRule.Description = currentRule.Description
}
if currentRule.Entropy != 0 {
baseRule.Entropy = currentRule.Entropy
}
if currentRule.SecretGroup != 0 {
baseRule.SecretGroup = currentRule.SecretGroup
}
if currentRule.Regex != nil {
baseRule.Regex = currentRule.Regex
}
if currentRule.Path != nil {
baseRule.Path = currentRule.Path
}
baseRule.Tags = append(baseRule.Tags, currentRule.Tags...)
baseRule.Keywords = append(baseRule.Keywords, currentRule.Keywords...)
for _, a := range currentRule.Allowlists {
baseRule.Allowlists = append(baseRule.Allowlists, a)
}
// The keywords from the base rule and the extended rule must be merged into the global keywords list
for _, k := range baseRule.Keywords {
c.Keywords[k] = struct{}{}
+223 -41
View File
@@ -15,22 +15,61 @@ const configPath = "../testdata/config/"
func TestTranslate(t *testing.T) {
tests := []struct {
cfgName string
cfg Config
// Configuration file basename to load, from `../testdata/config/`.
cfgName string
// Expected result.
cfg Config
// Rules to compare.
rules []string
// Error to expect.
wantError error
}{
{
cfgName: "allowlist_old_compat",
cfg: Config{
Rules: map[string]Rule{"example": {
RuleID: "example",
Regex: regexp.MustCompile(`example\d+`),
Tags: []string{},
Keywords: []string{},
Allowlists: []Allowlist{
{
MatchCondition: AllowlistMatchOr,
Regexes: []*regexp.Regexp{regexp.MustCompile("123")},
},
},
},
},
},
},
{
cfgName: "allowlist_invalid_empty",
cfg: Config{},
wantError: fmt.Errorf("example: [[rules.allowlists]] must contain at least one check for: commits, paths, regexes, or stopwords"),
},
{
cfgName: "allowlist_invalid_old_and_new",
cfg: Config{},
wantError: fmt.Errorf("example: [rules.allowlist] is deprecated, it cannot be used alongside [[rules.allowlist]]"),
},
{
cfgName: "allowlist_invalid_regextarget",
cfg: Config{},
wantError: fmt.Errorf("example: unknown allowlist |regexTarget| 'mtach' (expected 'match', 'line')"),
},
{
cfgName: "allow_aws_re",
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Tags: []string{"key", "AWS"},
Keywords: []string{},
RuleID: "aws-access-key",
Allowlist: Allowlist{
Regexes: []*regexp.Regexp{
regexp.MustCompile("AKIALALEMEL33243OLIA"),
Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{
{
MatchCondition: AllowlistMatchOr,
Regexes: []*regexp.Regexp{regexp.MustCompile("AKIALALEMEL33243OLIA")},
},
},
},
@@ -41,13 +80,16 @@ func TestTranslate(t *testing.T) {
cfgName: "allow_commit",
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Tags: []string{"key", "AWS"},
Keywords: []string{},
RuleID: "aws-access-key",
Allowlist: Allowlist{
Commits: []string{"allowthiscommit"},
Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{
{
MatchCondition: AllowlistMatchOr,
Commits: []string{"allowthiscommit"},
},
},
},
},
@@ -57,14 +99,15 @@ func TestTranslate(t *testing.T) {
cfgName: "allow_path",
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Tags: []string{"key", "AWS"},
Keywords: []string{},
RuleID: "aws-access-key",
Allowlist: Allowlist{
Paths: []*regexp.Regexp{
regexp.MustCompile(".go"),
Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{
{
MatchCondition: AllowlistMatchOr,
Paths: []*regexp.Regexp{regexp.MustCompile(".go")},
},
},
},
@@ -75,14 +118,13 @@ func TestTranslate(t *testing.T) {
cfgName: "entropy_group",
cfg: Config{
Rules: map[string]Rule{"discord-api-key": {
RuleID: "discord-api-key",
Description: "Discord API key",
Regex: regexp.MustCompile(`(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-h0-9]{64})['\"]`),
RuleID: "discord-api-key",
Allowlist: Allowlist{},
Keywords: []string{},
Entropy: 3.5,
SecretGroup: 3,
Tags: []string{},
Keywords: []string{},
},
},
},
@@ -107,49 +149,80 @@ func TestTranslate(t *testing.T) {
cfg: Config{
Rules: map[string]Rule{
"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Tags: []string{"key", "AWS"},
Keywords: []string{},
RuleID: "aws-access-key",
Tags: []string{"key", "AWS"},
},
"aws-secret-key": {
RuleID: "aws-secret-key",
Description: "AWS Secret Key",
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Tags: []string{"key", "AWS"},
Keywords: []string{},
RuleID: "aws-secret-key",
Tags: []string{"key", "AWS"},
},
"aws-secret-key-again": {
RuleID: "aws-secret-key-again",
Description: "AWS Secret Key",
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Tags: []string{"key", "AWS"},
Keywords: []string{},
RuleID: "aws-secret-key-again",
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "extend_rule_allowlist",
cfgName: "extend_rule_allowlist_or",
cfg: Config{
Rules: map[string]Rule{
"aws-secret-key-again-again": {
RuleID: "aws-secret-key-again-again",
Description: "AWS Secret Key",
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Tags: []string{"key", "AWS"},
Keywords: []string{},
Allowlist: Allowlist{
Commits: []string{"abcdefg1"},
Regexes: []*regexp.Regexp{
regexp.MustCompile(`foo.+bar`),
Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{
{
MatchCondition: AllowlistMatchOr,
StopWords: []string{"fake"},
},
RegexTarget: "line",
Paths: []*regexp.Regexp{
regexp.MustCompile(`ignore\.xaml`),
{
MatchCondition: AllowlistMatchOr,
Commits: []string{"abcdefg1"},
Paths: []*regexp.Regexp{regexp.MustCompile(`ignore\.xaml`)},
Regexes: []*regexp.Regexp{regexp.MustCompile(`foo.+bar`)},
RegexTarget: "line",
StopWords: []string{"example"},
},
},
},
},
},
},
{
cfgName: "extend_rule_allowlist_and",
cfg: Config{
Rules: map[string]Rule{
"aws-secret-key-again-again": {
RuleID: "aws-secret-key-again-again",
Description: "AWS Secret Key",
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Keywords: []string{},
Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{
{
MatchCondition: AllowlistMatchOr,
StopWords: []string{"fake"},
},
{
MatchCondition: AllowlistMatchAnd,
Commits: []string{"abcdefg1"},
Paths: []*regexp.Regexp{regexp.MustCompile(`ignore\.xaml`)},
Regexes: []*regexp.Regexp{regexp.MustCompile(`foo.+bar`)},
RegexTarget: "line",
StopWords: []string{"example"},
},
StopWords: []string{"example"},
},
},
},
@@ -163,17 +236,119 @@ func TestTranslate(t *testing.T) {
RuleID: "aws-secret-key-again-again",
Description: "AWS Secret Key",
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Tags: []string{"key", "AWS"},
Keywords: []string{},
Allowlist: Allowlist{
Paths: []*regexp.Regexp{
regexp.MustCompile(`something.py`),
Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{
{
MatchCondition: AllowlistMatchOr,
Paths: []*regexp.Regexp{regexp.MustCompile(`something.py`)},
},
},
},
},
},
},
{
cfgName: "override_description",
rules: []string{"aws-access-key"},
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "Puppy Doggy",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "override_entropy",
rules: []string{"aws-access-key"},
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Entropy: 999.0,
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "override_secret_group",
rules: []string{"aws-access-key"},
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:a)(?:a)"),
SecretGroup: 2,
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "override_regex",
rules: []string{"aws-access-key"},
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:a)"),
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "override_path",
rules: []string{"aws-access-key"},
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Path: regexp.MustCompile("(?:puppy)"),
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "override_tags",
rules: []string{"aws-access-key"},
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{},
Tags: []string{"key", "AWS", "puppy"},
},
},
},
},
{
cfgName: "override_keywords",
rules: []string{"aws-access-key"},
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{"puppy"},
Tags: []string{"key", "AWS"},
},
},
},
},
}
for _, tt := range tests {
@@ -193,12 +368,19 @@ func TestTranslate(t *testing.T) {
err = viper.Unmarshal(&vc)
require.NoError(t, err)
cfg, err := vc.Translate()
if !assert.Equal(t, tt.wantError, err) {
if err != nil && !assert.EqualError(t, tt.wantError, err.Error()) {
return
}
if len(tt.rules) > 0 {
rules := make(map[string]Rule)
for _, name := range tt.rules {
rules[name] = cfg.Rules[name]
}
cfg.Rules = rules
}
var regexComparer = func(x, y *regexp.Regexp) bool {
// Compare the string representation of the regex patterns.
if x == nil || y == nil {
return x == y
}
+375 -166
View File
File diff suppressed because it is too large. Load diff
+2 -3
View File
@@ -39,9 +39,8 @@ type Rule struct {
// keyword(s) are in the content being scanned.
Keywords []string
// Allowlist allows a rule to be ignored for specific
// regexes, paths, and/or commits
Allowlist Allowlist
// Allowlists allows a rule to be ignored for specific commits, paths, regexes, and/or stopwords.
Allowlists []Allowlist
}
// Validate guards against common misconfigurations.
+3 -1
View File
@@ -5,6 +5,7 @@ import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/zricethezav/gitleaks/v8/report"
)
@@ -128,7 +129,8 @@ func TestIgnoreIssuesInBaseline(t *testing.T) {
}
for _, test := range tests {
d, _ := NewDetectorDefaultConfig()
d, err := NewDetectorDefaultConfig()
require.NoError(t, err)
d.baseline = test.baseline
for _, finding := range test.findings {
d.addFinding(finding)
+124 -23
View File
@@ -14,7 +14,7 @@ import (
ahocorasick "github.com/BobuSumisu/aho-corasick"
"github.com/fatih/semgroup"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
"golang.org/x/exp/maps"
@@ -239,12 +239,55 @@ 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 {
var findings []report.Finding
var (
findings []report.Finding
logger = func() zerolog.Logger {
l := log.With().Str("rule-id", rule.RuleID)
if fragment.CommitSHA != "" {
l = l.Str("commit", fragment.CommitSHA)
}
l = l.Str("path", fragment.FilePath)
return l.Logger()
}()
)
// check if filepath or commit is allowed for this rule
if rule.Allowlist.CommitAllowed(fragment.CommitSHA) ||
rule.Allowlist.PathAllowed(fragment.FilePath) {
return findings
for _, a := range rule.Allowlists {
var (
isAllowed bool
commitAllowed = a.CommitAllowed(fragment.CommitSHA)
pathAllowed = a.PathAllowed(fragment.FilePath)
)
if a.MatchCondition == config.AllowlistMatchAnd {
// Determine applicable checks.
var allowlistChecks []bool
if len(a.Commits) > 0 {
allowlistChecks = append(allowlistChecks, commitAllowed)
}
if len(a.Paths) > 0 {
allowlistChecks = append(allowlistChecks, pathAllowed)
}
// These will be checked later.
if len(a.Regexes) > 0 {
allowlistChecks = append(allowlistChecks, false)
}
if len(a.StopWords) > 0 {
allowlistChecks = append(allowlistChecks, false)
}
// Check if allowed.
isAllowed = allTrue(allowlistChecks)
} else {
isAllowed = commitAllowed || pathAllowed
}
if isAllowed {
logger.Trace().
Str("condition", a.MatchCondition.String()).
Bool("commit-allowed", commitAllowed).
Bool("path-allowed", commitAllowed).
Msg("Skipping fragment due to rule allowlist")
return findings
}
}
if rule.Path != nil && rule.Regex == nil && len(encodedSegments) == 0 {
@@ -285,6 +328,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) {
// Extract secret from match
secret := strings.Trim(currentRaw[matchIndex[0]:matchIndex[1]], "\n")
@@ -333,8 +377,11 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, rule config.
Line: fragment.Raw[loc.startLineIndex:loc.endLineIndex],
}
if strings.Contains(fragment.Raw[loc.startLineIndex:loc.endLineIndex],
gitleaksAllowSignature) && !d.IgnoreGitleaksAllow {
if !d.IgnoreGitleaksAllow &&
strings.Contains(fragment.Raw[loc.startLineIndex:loc.endLineIndex], gitleaksAllowSignature) {
logger.Trace().
Str("finding", finding.Secret).
Msg("Skipping finding due to 'gitleaks:allow' signature")
continue
}
@@ -365,21 +412,8 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, rule config.
}
}
// check if the secret is in the list of stopwords
if rule.Allowlist.ContainsStopWord(finding.Secret) ||
d.Config.Allowlist.ContainsStopWord(finding.Secret) {
continue
}
// check if the regexTarget is defined in the allowlist "regexes" entry
allowlistTarget := finding.Secret
switch rule.Allowlist.RegexTarget {
case "match":
allowlistTarget = finding.Match
case "line":
allowlistTarget = finding.Line
}
// or if the secret is in the list of stopwords
globalAllowlistTarget := finding.Secret
switch d.Config.Allowlist.RegexTarget {
case "match":
@@ -387,9 +421,65 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, rule config.
case "line":
globalAllowlistTarget = finding.Line
}
if rule.Allowlist.RegexAllowed(allowlistTarget) ||
d.Config.Allowlist.RegexAllowed(globalAllowlistTarget) {
if d.Config.Allowlist.RegexAllowed(globalAllowlistTarget) {
logger.Trace().
Str("finding", globalAllowlistTarget).
Msg("Skipping finding due to global allowlist regex")
continue
} else if d.Config.Allowlist.ContainsStopWord(finding.Secret) {
logger.Trace().
Str("finding", finding.Secret).
Msg("Skipping finding due to global allowlist stopword")
continue
}
// check if the result matches any of the rule allowlists.
for _, a := range rule.Allowlists {
allowlistTarget := finding.Secret
switch a.RegexTarget {
case "match":
allowlistTarget = finding.Match
case "line":
allowlistTarget = finding.Line
}
var (
isAllowed bool
regexAllowed = a.RegexAllowed(allowlistTarget)
containsStopword = a.ContainsStopWord(finding.Secret)
)
// check if the secret is in the list of stopwords
if a.MatchCondition == config.AllowlistMatchAnd {
// Determine applicable checks.
var allowlistChecks []bool
if len(a.Commits) > 0 {
allowlistChecks = append(allowlistChecks, a.CommitAllowed(fragment.CommitSHA))
}
if len(a.Paths) > 0 {
allowlistChecks = append(allowlistChecks, a.PathAllowed(fragment.FilePath))
}
if len(a.Regexes) > 0 {
allowlistChecks = append(allowlistChecks, regexAllowed)
}
if len(a.StopWords) > 0 {
allowlistChecks = append(allowlistChecks, containsStopword)
}
// Check if allowed.
isAllowed = allTrue(allowlistChecks)
} else {
isAllowed = regexAllowed || containsStopword
}
if isAllowed {
logger.Trace().
Str("finding", finding.Secret).
Str("condition", a.MatchCondition.String()).
Bool("regex-allowed", regexAllowed).
Bool("contains-stopword", containsStopword).
Msg("Skipping finding due to rule allowlist")
continue MatchLoop
}
}
// check entropy
@@ -419,6 +509,17 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, rule config.
return findings
}
func allTrue(bools []bool) bool {
allMatch := true
for _, check := range bools {
if !check {
allMatch = false
break
}
}
return allMatch
}
// addFinding synchronously adds a finding to the findings slice
func (d *Detector) addFinding(finding report.Finding) {
globalFingerprint := fmt.Sprintf("%s:%s:%d", finding.File, finding.RuleID, finding.StartLine)
+253 -29
View File
@@ -2,8 +2,10 @@ package detect
import (
"fmt"
"github.com/google/go-cmp/cmp"
"os"
"path/filepath"
"regexp"
"testing"
"github.com/spf13/viper"
@@ -60,7 +62,6 @@ func TestDetect(t *testing.T) {
Raw: `awsToken := \"AKIALALEMEL33243OKIA\ // gitleaks:allow"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "simple",
@@ -72,7 +73,6 @@ func TestDetect(t *testing.T) {
`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "simple",
@@ -222,7 +222,6 @@ func TestDetect(t *testing.T) {
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "allow_path",
@@ -230,7 +229,6 @@ func TestDetect(t *testing.T) {
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "allow_commit",
@@ -239,7 +237,6 @@ func TestDetect(t *testing.T) {
FilePath: "tmp.go",
CommitSHA: "allowthiscommit",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "entropy_group",
@@ -270,7 +267,6 @@ func TestDetect(t *testing.T) {
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "generic_with_py_path",
@@ -317,8 +313,7 @@ func TestDetect(t *testing.T) {
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
wantError: fmt.Errorf("discord-api-key: invalid regex secret group 5, max regex secret group 3"),
wantError: fmt.Errorf("discord-api-key: invalid regex secret group 5, max regex secret group 3"),
},
{
cfgName: "simple",
@@ -326,7 +321,6 @@ func TestDetect(t *testing.T) {
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: filepath.Join(configPath, "simple.toml"),
},
expectedFindings: []report.Finding{},
},
{
cfgName: "allow_global_aws_re",
@@ -334,7 +328,6 @@ func TestDetect(t *testing.T) {
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "generic_with_py_path",
@@ -342,7 +335,6 @@ func TestDetect(t *testing.T) {
Raw: `const Discord_Public_Key = "load2523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: "tmp.py",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "path_only",
@@ -351,7 +343,6 @@ func TestDetect(t *testing.T) {
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: ".baseline.json",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "base64_encoded",
@@ -477,25 +468,27 @@ func TestDetect(t *testing.T) {
}
for _, tt := range tests {
viper.Reset()
viper.AddConfigPath(configPath)
viper.SetConfigName(tt.cfgName)
viper.SetConfigType("toml")
err := viper.ReadInConfig()
require.NoError(t, err)
t.Run(fmt.Sprintf("%s - %s", tt.cfgName, tt.fragment.FilePath), func(t *testing.T) {
viper.Reset()
viper.AddConfigPath(configPath)
viper.SetConfigName(tt.cfgName)
viper.SetConfigType("toml")
err := viper.ReadInConfig()
require.NoError(t, err)
var vc config.ViperConfig
err = viper.Unmarshal(&vc)
require.NoError(t, err)
cfg, err := vc.Translate()
cfg.Path = filepath.Join(configPath, tt.cfgName+".toml")
assert.Equal(t, tt.wantError, err)
d := NewDetector(cfg)
d.MaxDecodeDepth = maxDecodeDepth
d.baselinePath = tt.baselinePath
var vc config.ViperConfig
err = viper.Unmarshal(&vc)
require.NoError(t, err)
cfg, err := vc.Translate()
cfg.Path = filepath.Join(configPath, tt.cfgName+".toml")
assert.Equal(t, tt.wantError, err)
d := NewDetector(cfg)
d.MaxDecodeDepth = maxDecodeDepth
d.baselinePath = tt.baselinePath
findings := d.Detect(tt.fragment)
assert.ElementsMatch(t, tt.expectedFindings, findings)
findings := d.Detect(tt.fragment)
assert.ElementsMatch(t, tt.expectedFindings, findings)
})
}
}
@@ -855,6 +848,237 @@ func TestDetectWithSymlinks(t *testing.T) {
}
}
func TestDetectRuleAllowlist(t *testing.T) {
cases := map[string]struct {
fragment Fragment
allowlist config.Allowlist
expected []report.Finding
}{
// Commit / path
"commit allowed": {
fragment: Fragment{
CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
},
allowlist: config.Allowlist{
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
},
},
"path allowed": {
fragment: Fragment{
FilePath: "package-lock.json",
},
allowlist: config.Allowlist{
Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
},
},
"commit AND path allowed": {
fragment: Fragment{
CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
FilePath: "package-lock.json",
},
allowlist: config.Allowlist{
MatchCondition: config.AllowlistMatchAnd,
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
},
},
"commit AND path NOT allowed": {
fragment: Fragment{
CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
FilePath: "package.json",
},
allowlist: config.Allowlist{
MatchCondition: config.AllowlistMatchAnd,
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
},
expected: []report.Finding{
{
StartColumn: 50,
EndColumn: 60,
Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
Match: "Summer2024!",
Secret: "Summer2024!",
File: "package.json",
Entropy: 3.095795154571533,
RuleID: "test-rule",
},
},
},
"commit AND path NOT allowed - other conditions": {
fragment: Fragment{
CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
FilePath: "package-lock.json",
},
allowlist: config.Allowlist{
MatchCondition: config.AllowlistMatchAnd,
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
Regexes: []*regexp.Regexp{regexp.MustCompile("password")},
},
expected: []report.Finding{
{
StartColumn: 50,
EndColumn: 60,
Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
Match: "Summer2024!",
Secret: "Summer2024!",
File: "package-lock.json",
Entropy: 3.095795154571533,
RuleID: "test-rule",
},
},
},
"commit OR path allowed": {
fragment: Fragment{
CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
FilePath: "package-lock.json",
},
allowlist: config.Allowlist{
MatchCondition: config.AllowlistMatchOr,
Commits: []string{"704178e7dca77ff143778a31cff0fc192d59b030"},
Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
},
},
// Regex / stopwords
"regex allowed": {
fragment: Fragment{},
allowlist: config.Allowlist{
Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
},
},
"stopwords allowed": {
fragment: Fragment{},
allowlist: config.Allowlist{
StopWords: []string{"summer"},
},
},
"regex AND stopword allowed": {
fragment: Fragment{},
allowlist: config.Allowlist{
MatchCondition: config.AllowlistMatchAnd,
Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
StopWords: []string{"2024"},
},
},
"regex AND stopword allowed - other conditions": {
fragment: Fragment{
CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
FilePath: "config.js",
},
allowlist: config.Allowlist{
MatchCondition: config.AllowlistMatchAnd,
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
Paths: []*regexp.Regexp{regexp.MustCompile(`config.js`)},
Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
StopWords: []string{"2024"},
},
},
"regex AND stopword NOT allowed - non-git, other conditions": {
fragment: Fragment{
FilePath: "config.js",
},
allowlist: config.Allowlist{
MatchCondition: config.AllowlistMatchAnd,
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
Paths: []*regexp.Regexp{regexp.MustCompile(`config.js`)},
Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
StopWords: []string{"2024"},
},
expected: []report.Finding{
{
StartColumn: 50,
EndColumn: 60,
Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
Match: "Summer2024!",
Secret: "Summer2024!",
File: "config.js",
Entropy: 3.095795154571533,
RuleID: "test-rule",
},
},
},
"regex AND stopword NOT allowed": {
fragment: Fragment{},
allowlist: config.Allowlist{
MatchCondition: config.AllowlistMatchAnd,
Regexes: []*regexp.Regexp{
regexp.MustCompile(`(?i)winter.+`),
},
StopWords: []string{"2024"},
},
expected: []report.Finding{
{
StartColumn: 50,
EndColumn: 60,
Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
Match: "Summer2024!",
Secret: "Summer2024!",
Entropy: 3.095795154571533,
RuleID: "test-rule",
},
},
},
"regex AND stopword NOT allowed - other conditions": {
fragment: Fragment{
CommitSHA: "a060c9d2d5e90c992763f1bd4c3cd2a6f121241b",
FilePath: "config.js",
},
allowlist: config.Allowlist{
MatchCondition: config.AllowlistMatchAnd,
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)winter.+`)},
StopWords: []string{"2024"},
},
expected: []report.Finding{
{
StartColumn: 50,
EndColumn: 60,
Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
Match: "Summer2024!",
Secret: "Summer2024!",
File: "config.js",
Entropy: 3.095795154571533,
RuleID: "test-rule",
},
},
},
"regex OR stopword allowed": {
fragment: Fragment{},
allowlist: config.Allowlist{
MatchCondition: config.AllowlistMatchOr,
Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
StopWords: []string{"winter"},
},
},
}
raw := `let username = 'james@mail.com';
let password = 'Summer2024!';`
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
rule := config.Rule{
RuleID: "test-rule",
Regex: regexp.MustCompile(`Summer2024!`),
Allowlists: []config.Allowlist{
tc.allowlist,
},
}
d, err := NewDetectorDefaultConfig()
require.NoError(t, err)
f := tc.fragment
f.Raw = raw
actual := d.detectRule(f, raw, rule, []EncodedSegment{})
if diff := cmp.Diff(tc.expected, actual); diff != "" {
t.Errorf("diff: (-want +got)\n%s", diff)
}
})
}
}
func moveDotGit(t *testing.T, from, to string) {
t.Helper()
+9 -7
View File
@@ -13,10 +13,10 @@ import (
func (d *Detector) DetectFiles(paths <-chan sources.ScanTarget) ([]report.Finding, error) {
for pa := range paths {
p := pa
d.Sema.Go(func() error {
f, err := os.Open(p.Path)
logger := log.With().Str("path", pa.Path).Logger()
log.Trace().Msgf("Scanning path: %s", pa)
f, err := os.Open(pa.Path)
if err != nil {
return err
}
@@ -31,7 +31,9 @@ func (d *Detector) DetectFiles(paths <-chan sources.ScanTarget) ([]report.Findin
if d.MaxTargetMegaBytes > 0 {
rawLength := fileSize / 1000000
if rawLength > int64(d.MaxTargetMegaBytes) {
log.Debug().Msgf("skipping file: %s scan due to size: %d", p.Path, rawLength)
logger.Debug().
Int64("size", rawLength).
Msgf("Skipping file: exceeds --max-target-megabytes")
return nil
}
}
@@ -62,10 +64,10 @@ func (d *Detector) DetectFiles(paths <-chan sources.ScanTarget) ([]report.Findin
totalLines += linesInChunk
fragment := Fragment{
Raw: string(buf[:n]),
FilePath: p.Path,
FilePath: pa.Path,
}
if p.Symlink != "" {
fragment.SymlinkFile = p.Symlink
if pa.Symlink != "" {
fragment.SymlinkFile = pa.Symlink
}
for _, finding := range d.Detect(fragment) {
// need to add 1 since line counting starts at 1
+1 -1
View File
@@ -9,7 +9,7 @@ import (
"github.com/stretchr/testify/assert"
)
const secret = "AKIAIRYLJVKMPEXAMPLE"
const secret = "AKIAIRYLJVKMPEGZMPJS"
type mockReader struct {
data []byte
+1 -1
View File
@@ -8,7 +8,7 @@ require (
github.com/BobuSumisu/aho-corasick v1.0.3
github.com/charmbracelet/lipgloss v0.5.0
github.com/fatih/semgroup v1.2.0
github.com/gitleaks/go-gitdiff v0.9.0
github.com/gitleaks/go-gitdiff v0.9.1
github.com/google/go-cmp v0.6.0
github.com/h2non/filetype v1.1.3
github.com/rs/zerolog v1.26.1
+2 -2
View File
@@ -78,8 +78,8 @@ github.com/fatih/semgroup v1.2.0/go.mod h1:1KAD4iIYfXjE4U13B48VM4z9QUwV5Tt8O4rS8
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/gitleaks/go-gitdiff v0.9.0 h1:SHAU2l0ZBEo8g82EeFewhVy81sb7JCxW76oSPtR/Nqg=
github.com/gitleaks/go-gitdiff v0.9.0/go.mod h1:pKz0X4YzCKZs30BL+weqBIG7mx0jl4tF1uXV9ZyNvrA=
github.com/gitleaks/go-gitdiff v0.9.1 h1:ni6z6/3i9ODT685OLCTf+s/ERlWUNWQF4x1pvoNICw0=
github.com/gitleaks/go-gitdiff v0.9.1/go.mod h1:pKz0X4YzCKZs30BL+weqBIG7mx0jl4tF1uXV9ZyNvrA=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
+7 -2
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 {
@@ -35,7 +35,12 @@ func DirectoryTargets(source string, s *semgroup.Group, followSymlinks bool) (<-
Symlink: "",
}
}
if fInfo.Mode().Type() == fs.ModeSymlink && followSymlinks {
if fInfo.Mode().Type() == fs.ModeSymlink {
if !followSymlinks {
log.Debug().Str("path", path).Msg("Skipping symlink")
return nil
}
realPath, err := filepath.EvalSymlinks(path)
if err != nil {
return err
+1 -1
View File
@@ -5,5 +5,5 @@ title = "simple config with allowlist for aws"
id = "aws-access-key"
regex = '''(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}'''
tags = ["key", "AWS"]
[rules.allowlist]
[[rules.allowlists]]
regexes = ['''AKIALALEMEL33243OLIA''']
+1 -1
View File
@@ -5,5 +5,5 @@ title = "simple config with allowlist for a specific commit"
id = "aws-access-key"
regex = '''(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}'''
tags = ["key", "AWS"]
[rules.allowlist]
[[rules.allowlists]]
commits = ['''allowthiscommit''']
+1 -1
View File
@@ -5,5 +5,5 @@ title = "simple config with allowlist for .go files"
id = "aws-access-key"
regex = '''(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}'''
tags = ["key", "AWS"]
[rules.allowlist]
[[rules.allowlists]]
paths = ['''.go''']
+6
View File
@@ -0,0 +1,6 @@
title = "simple config with allowlist for aws"
[[rules]]
id = "example"
regex = '''example\d+'''
[[rules.allowlists]]
+9
View File
@@ -0,0 +1,9 @@
title = "simple config with allowlist for aws"
[[rules]]
id = "example"
regex = '''example\d+'''
[rules.allowlist]
regexes = ['''123''']
[[rules.allowlists]]
regexes = ['''456''']
+8
View File
@@ -0,0 +1,8 @@
title = "simple config with allowlist for aws"
[[rules]]
id = "example"
regex = '''example\d+'''
[[rules.allowlists]]
regexTarget = "mtach"
regexes = ['''456''']
+7
View File
@@ -0,0 +1,7 @@
title = "simple config with allowlist for aws"
[[rules]]
id = "example"
regex = '''example\d+'''
[rules.allowlist]
regexes = ['''123''']
+1 -1
View File
@@ -3,6 +3,6 @@ path="../testdata/config/extend_3.toml"
[[rules]]
id = "aws-secret-key-again-again"
[rules.allowlist]
[[rules.allowlists]]
description = "False positive. Keys used for colors match the rule, and should be excluded."
paths = ['''something.py''']
+14
View File
@@ -0,0 +1,14 @@
title = "gitleaks extended 3"
[extend]
path="../testdata/config/extend_rule_allowlist_base.toml"
[[rules]]
id = "aws-secret-key-again-again"
[[rules.allowlists]]
condition = "AND"
commits = ['''abcdefg1''']
regexes = ['''foo.+bar''']
regexTarget = "line"
paths = ['''ignore\.xaml''']
stopwords = ['''example''']
+11
View File
@@ -0,0 +1,11 @@
title = "gitleaks extended 3"
## This should not be loaded since we can only extend configs to a depth of 3
[[rules]]
id = "aws-secret-key-again-again"
description = "AWS Secret Key"
regex = '''(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}'''
tags = ["key", "AWS"]
[[rules.allowlists]]
stopwords = ["fake"]
@@ -1,11 +1,11 @@
title = "gitleaks extended 3"
[extend]
path="../testdata/config/extend_3.toml"
path="../testdata/config/extend_rule_allowlist_base.toml"
[[rules]]
id = "aws-secret-key-again-again"
[rules.allowlist]
[[rules.allowlists]]
commits = ['''abcdefg1''']
regexes = ['''foo.+bar''']
regexTarget = "line"
+8
View File
@@ -0,0 +1,8 @@
title = "override a built-in rule's description"
[extend]
path = "../testdata/config/simple.toml"
[[rules]]
id = "aws-access-key"
description = "Puppy Doggy"
+8
View File
@@ -0,0 +1,8 @@
title = "override a built-in rule's entropy"
[extend]
path = "../testdata/config/simple.toml"
[[rules]]
id = "aws-access-key"
entropy = 999
+8
View File
@@ -0,0 +1,8 @@
title = "override a built-in rule's keywords"
[extend]
path = "../testdata/config/simple.toml"
[[rules]]
id = "aws-access-key"
keywords = ["puppy"]
+8
View File
@@ -0,0 +1,8 @@
title = "override a built-in rule's path"
[extend]
path = "../testdata/config/simple.toml"
[[rules]]
id = "aws-access-key"
path = '''(?:puppy)'''
+8
View File
@@ -0,0 +1,8 @@
title = "override a built-in rule's regex"
[extend]
path = "../testdata/config/simple.toml"
[[rules]]
id = "aws-access-key"
regex = '''(?:a)'''
+9
View File
@@ -0,0 +1,9 @@
title = "override a built-in rule's secretGroup"
[extend]
path = "../testdata/config/simple.toml"
[[rules]]
id = "aws-access-key"
regex = '''(?:a)(?:a)'''
secretGroup = 2
+8
View File
@@ -0,0 +1,8 @@
title = "override a built-in rule's tags"
[extend]
path = "../testdata/config/simple.toml"
[[rules]]
id = "aws-access-key"
tags = ["puppy"]