mirror of
https://github.com/gitleaks/gitleaks.git
synced 2026-11-26 19:30:55 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
82f7d61593 | ||
|
|
a42b32bdf1 | ||
|
|
79638b080c | ||
|
|
3474c58c9e | ||
|
|
d8cd93cabe | ||
|
|
48b79facfa | ||
|
|
e23f7f58f3 | ||
|
|
606bb1a13b | ||
|
|
e784980515 | ||
|
|
c33ee3f252 | ||
|
|
b0a958f55e | ||
|
|
237b03af18 | ||
|
|
f348991d21 | ||
|
|
e0745adbd2 | ||
|
|
1ddc924a67 | ||
|
|
0b07625567 | ||
|
|
0cabbf8ca8 | ||
|
|
ba9e089e35 | ||
|
|
31ff8677dd | ||
|
|
3e5e63956e | ||
|
|
57f9bc83d1 | ||
|
|
6e72472b60 | ||
|
|
9326f35380 | ||
|
|
19555579c8 | ||
|
|
60dd607312 | ||
|
|
c3b799ec63 | ||
|
|
4b6f4d0de5 | ||
|
|
fbfb3f591e | ||
|
|
b91799aa18 | ||
|
|
db1b54bf9f | ||
|
|
e9529744f8 | ||
|
|
d1f642a9df | ||
|
|
9261f1c47f | ||
|
|
991223abab | ||
|
|
801d44a6e4 | ||
|
|
44d7d89e19 | ||
|
|
aae23acff3 | ||
|
|
705595aaf6 | ||
|
|
43ec22429f | ||
|
|
36779df3bb | ||
|
|
3d3d801729 | ||
|
|
0f2ffee6f9 | ||
|
|
f4d37a2c0d | ||
|
|
be5596df1d | ||
|
|
e97f26bb5f | ||
|
|
ae13c96df8 | ||
|
|
d15dfdc387 | ||
|
|
631d8dcf03 | ||
|
|
192b96289f | ||
|
|
b8141713e8 | ||
|
|
3fedf6f8e7 | ||
|
|
6f6ebd454f | ||
|
|
ce42947cae | ||
|
|
84e285e4ce | ||
|
|
928c6a6043 | ||
|
|
106897fdf0 | ||
|
|
98d5648f6e | ||
|
|
9358e84588 | ||
|
|
958c18f0b7 | ||
|
|
089639e9fb | ||
|
|
85afd767f7 | ||
|
|
38006fb93b | ||
|
|
9ae1def963 | ||
|
|
6517900e5a | ||
|
|
5e51da600b | ||
|
|
f0b8d26c99 | ||
|
|
1724591029 | ||
|
|
80d29764a0 | ||
|
|
f498b1d308 | ||
|
|
8eabfd614e | ||
|
|
4acd7a3c8d | ||
|
|
a37822dffd | ||
|
|
1c6b28aa61 | ||
|
|
f15b4e408b | ||
|
|
d5f9d2b5d2 | ||
|
|
67a7069bb8 | ||
|
|
fd5d786538 | ||
|
|
c017b763f3 | ||
|
|
e796458763 | ||
|
|
2a9fbbc64d | ||
|
|
d6081d0cc4 | ||
|
|
e6c3a495ce | ||
|
|
93f292c3df | ||
|
|
780fb4a8f1 | ||
|
|
0d9ab37ba4 | ||
|
|
acffe44440 | ||
|
|
178f78fa14 | ||
|
|
1ab1ae0e70 | ||
|
|
9f8ca91b8b | ||
|
|
eec6c5a391 | ||
|
|
714c0bef1e | ||
|
|
e9b699dda1 | ||
|
|
5afe59d2fa | ||
|
|
8adf27b1ea | ||
|
|
aecd32075e | ||
|
|
290118cbbe | ||
|
|
d2e1e43a25 | ||
|
|
2161ff358b | ||
|
|
f338bc584f | ||
|
|
e6a132bf4f | ||
|
|
8625cc30db | ||
|
|
7cc3d7e467 | ||
|
|
b8ff5eec73 | ||
|
|
36a4871585 | ||
|
|
c85ebbb2ba | ||
|
|
3a3e13c3b5 | ||
|
|
14a00e1ffd | ||
|
|
bd707fa9c4 | ||
|
|
5e6b1840df | ||
|
|
d8e3a694f2 | ||
|
|
05e3462025 | ||
|
|
b83fe80968 | ||
|
|
5db0159c52 | ||
|
|
5f87c4137c | ||
|
|
ea94318ba3 | ||
|
|
3128789777 | ||
|
|
270207e5eb | ||
|
|
efe96640fc | ||
|
|
0137637c2c | ||
|
|
6adc045580 | ||
|
|
45c898c5ea | ||
|
|
95f8bd0daa | ||
|
|
2cc2519302 | ||
|
|
be13bba64c | ||
|
|
7111a698c0 | ||
|
|
8b9092a248 | ||
|
|
0aa05133a9 | ||
|
|
2952df5432 | ||
|
|
541e26b067 | ||
|
|
6018a6bb70 | ||
|
|
ca987b3842 | ||
|
|
67f8d28d7f | ||
|
|
f88abe99d7 | ||
|
|
6ddf27c5c3 | ||
|
|
aadd9387b2 | ||
|
|
0fd68c901d | ||
|
|
17a3943afe | ||
|
|
abc73e2443 | ||
|
|
3c1751e5c4 | ||
|
|
a32ef6afc4 | ||
|
|
127df8a6f0 | ||
|
|
aa91fd3e5e | ||
|
|
c8e97d97f9 | ||
|
|
67e3603ba4 | ||
|
|
f62617d7a6 | ||
|
|
9324184c24 | ||
|
|
a80ce0d251 | ||
|
|
c1c4a93f98 | ||
|
|
e74e6292ee | ||
|
|
25c3e92c2a | ||
|
|
9ab424172d | ||
|
|
28fd47e170 | ||
|
|
8250e40a75 | ||
|
|
f735c9a5c9 | ||
|
|
e7553b0168 | ||
|
|
12d276acd7 | ||
|
|
e6934bf0a5 | ||
|
|
6f5ad9dc0b | ||
|
|
a2019a4782 | ||
|
|
5d7b7718ec | ||
|
|
190877a24b | ||
|
|
144362b972 | ||
|
|
d353ac5108 | ||
|
|
a27a08904a | ||
|
|
5ef4e336ce | ||
|
|
78f2c46517 | ||
|
|
bdcb9e33a8 | ||
|
|
6e4e9df55f | ||
|
|
b3bed5658d | ||
|
|
a10ae91ba7 | ||
|
|
a8dbc7f107 | ||
|
|
4544156b44 | ||
|
|
b52e8c9c7c | ||
|
|
0ce1249b95 | ||
|
|
3932ed6baf | ||
|
|
981b636920 | ||
|
|
c8e15c731a | ||
|
|
901f932a89 | ||
|
|
c0a9580a65 | ||
|
|
8be91eea5d | ||
|
|
1c6f2252b8 | ||
|
|
58d130c5f3 | ||
|
|
091ea81e68 | ||
|
|
f036dce6ab | ||
|
|
2d58f1f94e | ||
|
|
86cfe0848b | ||
|
|
973d74e592 | ||
|
|
3909ebe03b | ||
|
|
65f42020af | ||
|
|
65a91ae976 | ||
|
|
7db08bfd90 | ||
|
|
af26553292 | ||
|
|
d5e431e7d4 | ||
|
|
54ba3ec377 | ||
|
|
656ef1c9a7 | ||
|
|
b8accd7273 | ||
|
|
238c31beaa | ||
|
|
eb31190f31 | ||
|
|
389d45e380 | ||
|
|
81b3a6e279 | ||
|
|
c50906373c | ||
|
|
40545fb680 | ||
|
|
2acc34dfdf | ||
|
|
ede68fd95d | ||
|
|
6c60c3dde3 | ||
|
|
ad505754fc | ||
|
|
21d81879e2 | ||
|
|
b5ca2ba614 | ||
|
|
ef4655fcf1 | ||
|
|
01b553a75d | ||
|
|
fae366a404 | ||
|
|
6129b1a15d | ||
|
|
31d03a1146 | ||
|
|
eabc7b5c12 | ||
|
|
1dc7569f95 | ||
|
|
1797e9c966 | ||
|
|
e2eaceb4cd | ||
|
|
c637b129ec | ||
|
|
8470e43d7f | ||
|
|
94f5950d68 | ||
|
|
fe69a17c9c | ||
|
|
6ca7a11d88 | ||
|
|
cfbb600fcb | ||
|
|
e36b550851 | ||
|
|
2232dc191c | ||
|
|
bdc688dd53 | ||
|
|
e0f6399d5c | ||
|
|
3e88ac6726 | ||
|
|
d0088f6c7c | ||
|
|
0d7c18cb39 | ||
|
|
d0e98416b9 | ||
|
|
b7438011b4 | ||
|
|
4e59d3bf19 | ||
|
|
e4b26aea4a | ||
|
|
473d0d55a7 | ||
|
|
8bd4649b01 | ||
|
|
a69df84325 | ||
|
|
0faebdefea | ||
|
|
a728e3abf3 | ||
|
|
e87c62fe72 | ||
|
|
4801818e3d | ||
|
|
b4a0577786 | ||
|
|
212232f80a | ||
|
|
11dcb44e41 | ||
|
|
af0df6ea2c | ||
|
|
9db91442b3 | ||
|
|
9d76070806 | ||
|
|
2fa580f1bb | ||
|
|
c6f15b768e | ||
|
|
779937ca87 | ||
|
|
731856e974 | ||
|
|
baf54631c7 | ||
|
|
3e760d7fed | ||
|
|
679f00dc9c | ||
|
|
dae5c142d7 | ||
|
|
8e8873286e | ||
|
|
6693cbdde3 | ||
|
|
8b3ce2cb1e | ||
|
|
94cae90d1e | ||
|
|
c4b07f5113 | ||
|
|
01d73028f8 | ||
|
|
862f1203ed | ||
|
|
581e81c16e | ||
|
|
6c166c9530 | ||
|
|
4181ede6cd | ||
|
|
10745be661 | ||
|
|
ee2d73c740 | ||
|
|
e7fbcf5333 | ||
|
|
2810eccc82 | ||
|
|
baff419091 | ||
|
|
d13e0fdfde | ||
|
|
5a300c3c64 | ||
|
|
d8ddb9630a | ||
|
|
1537eeb5fa | ||
|
|
1a492537dd | ||
|
|
bd4107b002 | ||
|
|
7b48cadf6d | ||
|
|
6eab8a7a0a | ||
|
|
c6d14e5b7d | ||
|
|
ce95cafd54 | ||
|
|
4024faceab | ||
|
|
1afa931248 | ||
|
|
2474c39311 | ||
|
|
f6460a7365 | ||
|
|
b47e00858e | ||
|
|
b200a13c8d | ||
|
|
e6fabdbb31 | ||
|
|
cdd654eab7 | ||
|
|
2f07b96333 | ||
|
|
62e74b2b18 | ||
|
|
e75693b131 | ||
|
|
3cd14d4696 | ||
|
|
d29cc9892c | ||
|
|
d996882f4e | ||
|
|
17b6aa856d | ||
|
|
c21a9cf121 | ||
|
|
d3c4342c15 | ||
|
|
b4c2f8e69c | ||
|
|
a0f72a4e35 | ||
|
|
24844002de | ||
|
|
593edeae21 | ||
|
|
6df770d261 | ||
|
|
4f0c9dcede | ||
|
|
52425a8ca9 | ||
|
|
454acebe5a | ||
|
|
6fcf91e934 | ||
|
|
f89b8f2b29 | ||
|
|
648a7ba577 | ||
|
|
7c5594c39d | ||
|
|
274e8212a6 | ||
|
|
36c6ddaf86 | ||
|
|
15ed72bc09 | ||
|
|
ace8de93a9 | ||
|
|
45a4c0a284 | ||
|
|
c5e1e8abc0 | ||
|
|
ef38b69c39 | ||
|
|
ac6bde9996 | ||
|
|
23568cc0ba | ||
|
|
e61c2cfae7 | ||
|
|
38e0b11995 | ||
|
|
31903d1a80 | ||
|
|
3655284b57 | ||
|
|
db79a96118 | ||
|
|
5152e1fc63 | ||
|
|
c04e137b28 | ||
|
|
9b3342fbff | ||
|
|
d9a060a12d | ||
|
|
77f2fdd09a | ||
|
|
dba1ef6104 |
No files matched your search
@@ -0,0 +1,29 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: bug
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Basic Info (please complete the following information):**
|
||||
- OS:
|
||||
- Gitleaks Version:
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
||||
|
||||
cc @zricethezav
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: ''
|
||||
labels: enhancement
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
|
||||
cc @zricethezav
|
||||
@@ -0,0 +1,16 @@
|
||||
---
|
||||
name: Maintenance request
|
||||
about: Suggest an idea for this project
|
||||
title: ''
|
||||
labels: enhancement
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
|
||||
cc @zricethezav
|
||||
@@ -0,0 +1,8 @@
|
||||
### Description:
|
||||
Explain the purpose of the PR.
|
||||
|
||||
### Checklist:
|
||||
|
||||
* [ ] Does your PR pass tests?
|
||||
* [ ] Have you written new tests for your changes?
|
||||
* [ ] Have you lint your code locally prior to submission?
|
||||
@@ -0,0 +1,49 @@
|
||||
name: Create and publish a Docker image
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
IMAGE_NAME: ${{ github.repository }}
|
||||
|
||||
jobs:
|
||||
build-and-push-image:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9
|
||||
with:
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38
|
||||
with:
|
||||
images: |
|
||||
zricethezav/gitleaks
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@ad44023a93711e3deb337508980b4b5e9bcdc5dc
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
@@ -0,0 +1,36 @@
|
||||
name: Test
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- "*"
|
||||
pull_request:
|
||||
branches:
|
||||
- "*"
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.17
|
||||
|
||||
- name: Build
|
||||
run: go build -v ./...
|
||||
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: 1.17
|
||||
|
||||
- name: Test
|
||||
run: make test
|
||||
@@ -6,7 +6,15 @@
|
||||
*.dylib
|
||||
*.DS_STORE
|
||||
*.idea
|
||||
*.got
|
||||
gitleaks
|
||||
build
|
||||
|
||||
# configs
|
||||
.gitleaks.toml
|
||||
cmd/generate/config/gitleaks.toml
|
||||
|
||||
# Test binary
|
||||
*.out
|
||||
|
||||
dist/
|
||||
@@ -0,0 +1,29 @@
|
||||
project_name: gitleaks
|
||||
|
||||
builds:
|
||||
- main: main.go
|
||||
binary: gitleaks
|
||||
goos:
|
||||
- darwin
|
||||
- linux
|
||||
- windows
|
||||
goarch:
|
||||
- amd64
|
||||
- "386"
|
||||
- arm
|
||||
- arm64
|
||||
goarm:
|
||||
- "6"
|
||||
- "7"
|
||||
ldflags:
|
||||
- -s -w -X=github.com/zricethezav/gitleaks/v8/cmd.Version={{.Version}}
|
||||
archives:
|
||||
- builds: [gitleaks]
|
||||
format_overrides:
|
||||
- goos: windows
|
||||
format: zip
|
||||
replacements:
|
||||
amd64: x64
|
||||
386: x32
|
||||
release:
|
||||
prerelease: true
|
||||
@@ -0,0 +1,11 @@
|
||||
- id: gitleaks
|
||||
name: Detect hardcoded secrets
|
||||
description: Detect hardcoded secrets using Gitleaks
|
||||
entry: gitleaks protect --verbose --redact --staged
|
||||
language: golang
|
||||
pass_filenames: false
|
||||
- id: gitleaks-docker
|
||||
name: Detect hardcoded secrets
|
||||
description: Detect hardcoded secrets using Gitleaks
|
||||
entry: zricethezav/gitleaks protect --verbose --redact --staged
|
||||
language: docker_image
|
||||
@@ -1,7 +0,0 @@
|
||||
language: go
|
||||
go:
|
||||
- 1.13.x
|
||||
services:
|
||||
- docker
|
||||
script:
|
||||
- make test
|
||||
+19
-11
@@ -1,16 +1,24 @@
|
||||
FROM golang:1.13.4 AS build
|
||||
FROM golang:1.18 AS build
|
||||
WORKDIR /go/src/github.com/zricethezav/gitleaks
|
||||
COPY . .
|
||||
RUN GO111MODULE=on CGO_ENABLED=0 go build -o bin/gitleaks *.go
|
||||
RUN VERSION=$(git describe --tags --abbrev=0) && \
|
||||
CGO_ENABLED=0 go build -o bin/gitleaks -ldflags "-X="github.com/zricethezav/gitleaks/v8/cmd.Version=${VERSION}
|
||||
|
||||
FROM alpine:3.10
|
||||
RUN apk add --no-cache bash git openssh
|
||||
FROM alpine:3.15.4
|
||||
RUN adduser -D gitleaks && \
|
||||
apk add --no-cache bash git openssh-client
|
||||
COPY --from=build /go/src/github.com/zricethezav/gitleaks/bin/* /usr/bin/
|
||||
USER gitleaks
|
||||
|
||||
# default to avoid the follow error:
|
||||
# 11:09PM ERR fatal: unsafe repository ('/path' is owned by someone else)
|
||||
# 11:09PM ERR To add an exception for this directory, call:
|
||||
# 11:09PM ERR
|
||||
# 11:09PM ERR git config --global --add safe.directory /path
|
||||
# This means that when you run gitleaks from docker you must mount to /path
|
||||
# in order to avoid this error.
|
||||
|
||||
# TODO waiting to push this until I've thought a bit more about it
|
||||
# RUN git config --global --add safe.directory /path
|
||||
|
||||
ENTRYPOINT ["gitleaks"]
|
||||
|
||||
# How to use me :
|
||||
|
||||
# docker build -t gitleaks .
|
||||
# docker run --rm --name=gitleaks gitleaks --repo=https://github.com/zricethezav/gitleaks
|
||||
|
||||
# This will check for secrets in https://github.com/zricethezav/gitleaks
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019 Zachary Rice
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,42 +1,26 @@
|
||||
.PHONY: test test-cover build release-builds
|
||||
.PHONY: test test-cover
|
||||
|
||||
VERSION := `git fetch --tags && git tag | sort -V | tail -1`
|
||||
PKG=github.com/zricethezav/gitleaks
|
||||
LDFLAGS=-ldflags "-X=github.com/zricethezav/gitleaks/version.Version=$(VERSION)"
|
||||
VERSION := `git fetch --tags && git tag | sort -V | tail -1`
|
||||
LDFLAGS=-ldflags "-X=github.com/zricethezav/gitleaks/v8/cmd.Version=$(VERSION)"
|
||||
COVER=--cover --coverprofile=cover.out
|
||||
|
||||
test-cover:
|
||||
go test ./... --race $(COVER) $(PKG) -v
|
||||
go test -v ./... --race $(COVER) $(PKG)
|
||||
go tool cover -html=cover.out
|
||||
|
||||
test:
|
||||
go get golang.org/x/lint/golint
|
||||
format:
|
||||
go fmt ./...
|
||||
golint ./...
|
||||
go test ./... --race $(PKG) -v
|
||||
|
||||
test-integration:
|
||||
go test github.com/zricethezav/gitleaks/hosts -v -integration
|
||||
test: format
|
||||
go vet ./...
|
||||
go test -v ./... --race $(PKG)
|
||||
|
||||
build:
|
||||
go fmt ./...
|
||||
golint ./...
|
||||
build: format
|
||||
go vet ./...
|
||||
go mod tidy
|
||||
go build $(LDFLAGS)
|
||||
|
||||
release-builds:
|
||||
rm -rf build
|
||||
mkdir build
|
||||
env GOOS="windows" GOARCH="amd64" go build -o "build/gitleaks-windows-amd64.exe" $(LDFLAGS)
|
||||
env GOOS="windows" GOARCH="386" go build -o "build/gitleaks-windows-386.exe" $(LDFLAGS)
|
||||
env GOOS="linux" GOARCH="amd64" go build -o "build/gitleaks-linux-amd64" $(LDFLAGS)
|
||||
env GOOS="linux" GOARCH="arm" go build -o "build/gitleaks-linux-arm" $(LDFLAGS)
|
||||
env GOOS="linux" GOARCH="mips" go build -o "build/gitleaks-linux-mips" $(LDFLAGS)
|
||||
env GOOS="linux" GOARCH="mips" go build -o "build/gitleaks-linux-mips" $(LDFLAGS)
|
||||
env GOOS="darwin" GOARCH="amd64" go build -o "build/gitleaks-darwin-amd64" $(LDFLAGS)
|
||||
|
||||
deploy:
|
||||
@echo "$(DOCKER_PASSWORD)" | docker login -u "$(DOCKER_USERNAME)" --password-stdin
|
||||
docker build -f Dockerfile -t $(REPO):$(TAG) .
|
||||
echo "Pushing $(REPO):$(COMMIT) $(REPO):$(TAG)"
|
||||
docker push $(REPO)
|
||||
clean:
|
||||
find . -type f -name '*.got.*' -delete
|
||||
find . -type f -name '*.out' -delete
|
||||
@@ -1,123 +1,295 @@
|
||||
Gitleaks
|
||||
--------
|
||||
# gitleaks
|
||||
```
|
||||
┌─○───┐
|
||||
│ │╲ │
|
||||
│ │ ○ │
|
||||
│ ○ ░ │
|
||||
└─░───┘
|
||||
```
|
||||
|
||||
|
||||
<p align="left">
|
||||
<a href="https://travis-ci.org/zricethezav/gitleaks"><img alt="Travis" src="https://img.shields.io/travis/zricethezav/gitleaks/master.svg?style=flat-square"></a>
|
||||
<p align="left">
|
||||
<a href="https://github.com/zricethezav/gitleaks/actions/workflows/test.yml">
|
||||
<img alt="Github Test" src="https://github.com/zricethezav/gitleaks/actions/workflows/test.yml/badge.svg">
|
||||
</a>
|
||||
<a href="https://hub.docker.com/r/zricethezav/gitleaks">
|
||||
<img src="https://img.shields.io/docker/pulls/zricethezav/gitleaks.svg" />
|
||||
</a>
|
||||
<a href="https://twitter.com/intent/follow?screen_name=zricethezav">
|
||||
<img src="https://img.shields.io/twitter/follow/zricethezav?label=Follow%20zricethezav&style=social&color=blue" alt="Follow @zricethezav" />
|
||||
</a>
|
||||
</p>
|
||||
</p>
|
||||
|
||||
Audit git repos for secrets. Gitleaks provides a way for you to find unencrypted secrets and other unwanted data types in git repositories. As part of it's core functionality, it provides:
|
||||
Gitleaks is a SAST tool for **detecting** and **preventing** hardcoded secrets like passwords, api keys, and tokens in git repos. Gitleaks is an **easy-to-use, all-in-one solution** for detecting secrets, past or present, in your code.
|
||||
|
||||
* Audits for uncommitted changes
|
||||
* Github and Gitlab support including support for bulk organization and repository owner (user) repository scans, as well as pull/merge request scanning for use in common CI workflows.
|
||||
* Support for private repository scans, and repositories that require key based authentication
|
||||
* Output in JSON formats for consumption in other reporting tools and frameworks
|
||||
* Externalised configuration for environment specific customisation including regex rules
|
||||
* High performance through the use of src-d's [go-git](https://github.com/src-d/go-git) framework
|
||||
|
||||
|
||||
|
||||
| `repo scan` |
|
||||
|---|
|
||||
| <p align="left"><img src="https://raw.githubusercontent.com/zricethezav/gifs/master/repo-scan.gif"></p> | <p align="left"><img src="https://raw.githubusercontent.com/zricethezav/gifs/master/repo-scan.gif"></p> |
|
||||
|
||||
| `pre commit scan` |
|
||||
|---|
|
||||
| <p align="left"><img src="https://raw.githubusercontent.com/zricethezav/gifs/master/pre-commit-1.gif"></p> |
|
||||
[](https://asciinema.org/a/455683)
|
||||
|
||||
## Getting Started
|
||||
Gitleaks can be installed using Homebrew, Docker, or Go. Gitleaks is also available in binary form for many popular platforms and OS types on the [releases page](https://github.com/zricethezav/gitleaks/releases). In addition, Gitleaks can be implemented as a pre-commit hook directly in your repo.
|
||||
|
||||
Written in Go, gitleaks is available in binary form for many popular platforms and OS types from the [releases page](https://github.com/zricethezav/gitleaks/releases). Alternatively, executed via Docker or it can be installed using Go directly, as per the below;
|
||||
### MacOS
|
||||
|
||||
#### MacOS
|
||||
|
||||
```
|
||||
```bash
|
||||
brew install gitleaks
|
||||
```
|
||||
|
||||
#### Docker
|
||||
|
||||
### Docker
|
||||
#### DockerHub
|
||||
```bash
|
||||
docker pull zricethezav/gitleaks
|
||||
docker pull zricethezav/gitleaks:latest
|
||||
docker run -v ${path_to_host_folder_to_scan}:/path zricethezav/gitleaks:latest [COMMAND] --source="/path" [OPTIONS]
|
||||
```
|
||||
#### ghcr.io
|
||||
```bash
|
||||
docker pull ghcr.io/zricethezav/gitleaks:latest
|
||||
docker run -v ${path_to_host_folder_to_scan}:/path zricethezav/gitleaks:latest [COMMAND] --source="/path" [OPTIONS]
|
||||
```
|
||||
|
||||
#### Go
|
||||
|
||||
### From Source
|
||||
1. Download and install Go from https://golang.org/dl/
|
||||
2. Clone the repo
|
||||
```bash
|
||||
go get -u github.com/zricethezav/gitleaks
|
||||
git clone https://github.com/zricethezav/gitleaks.git
|
||||
```
|
||||
3. Build the binary
|
||||
```bash
|
||||
cd gitleaks
|
||||
make build
|
||||
```
|
||||
|
||||
### Pre-Commit
|
||||
1. Install pre-commit from https://pre-commit.com/#install
|
||||
2. Create a `.pre-commit-config.yaml` file at the root of your repository with the following content:
|
||||
```
|
||||
repos:
|
||||
- repo: https://github.com/zricethezav/gitleaks
|
||||
rev: v8.2.0
|
||||
hooks:
|
||||
- id: gitleaks
|
||||
```
|
||||
for a [native execution of GitLeaks](https://github.com/zricethezav/gitleaks/releases) or use the [`gitleaks-docker` pre-commit ID](https://github.com/zricethezav/gitleaks/blob/master/.pre-commit-hooks.yaml) for executing GitLeaks using the [official Docker images](#docker)
|
||||
|
||||
3. Install with `pre-commit install`
|
||||
4. Now you're all set!
|
||||
```
|
||||
➜ git commit -m "this commit contains a secret"
|
||||
Detect hardcoded secrets.................................................Failed
|
||||
```
|
||||
Note: to disable the gitleaks pre-commit hook you can prepend `SKIP=gitleaks` to the commit command
|
||||
and it will skip running gitleaks
|
||||
```
|
||||
➜ SKIP=gitleaks git commit -m "skip gitleaks check"
|
||||
Detect hardcoded secrets................................................Skipped
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
gitleaks has a wide range of configuration options that can be adjusted at runtime or via a configuration file based on your specific requirements.
|
||||
|
||||
```
|
||||
Usage:
|
||||
gitleaks [OPTIONS]
|
||||
gitleaks [command]
|
||||
|
||||
Application Options:
|
||||
-v, --verbose Show verbose output from audit
|
||||
-r, --repo= Target repository
|
||||
--config= config path
|
||||
--disk Clones repo(s) to disk
|
||||
--version version number
|
||||
--timeout= Timeout (s)
|
||||
--username= Username for git repo
|
||||
--password= Password for git repo
|
||||
--access-token= Access token for git repo
|
||||
--commit= sha of commit to audit
|
||||
--threads= Maximum number of threads gitleaks spawns
|
||||
--ssh-key= path to ssh key used for auth
|
||||
--uncommitted run gitleaks on uncommitted code
|
||||
--repo-path= Path to repo
|
||||
--owner-path= Path to owner directory (repos discovered)
|
||||
--branch= Branch to audit
|
||||
--report= path to write json leaks file
|
||||
--redact redact secrets from log messages and leaks
|
||||
--debug log debug messages
|
||||
--repo-config Load config from target repo. Config file must be ".gitleaks.toml" or "gitleaks.toml"
|
||||
--pretty Pretty print json if leaks are present
|
||||
--host= git hosting service like gitlab or github. Supported hosts include: Github, Gitlab
|
||||
--org= organization to audit
|
||||
--user= user to audit
|
||||
--pr= pull/merge request url
|
||||
Available Commands:
|
||||
completion generate the autocompletion script for the specified shell
|
||||
detect Detect secrets in code
|
||||
help Help about any command
|
||||
protect Protect secrets in code
|
||||
version Display gitleaks version
|
||||
|
||||
Help Options:
|
||||
-h, --help Show this help message
|
||||
Flags:
|
||||
-c, --config string config file path
|
||||
order of precedence:
|
||||
1. --config/-c
|
||||
2. env var GITLEAKS_CONFIG
|
||||
3. (--source/-s)/.gitleaks.toml
|
||||
If none of the three options are used, then gitleaks will use the default config
|
||||
--exit-code string exit code when leaks have been encountered (default: 1)
|
||||
-h, --help help for gitleaks
|
||||
-l, --log-level string log level (debug, info, warn, error, fatal) (default "info")
|
||||
--redact redact secrets from logs and stdout
|
||||
-f, --report-format string output format (json, csv, sarif)
|
||||
-r, --report-path string report file
|
||||
-s, --source string path to source (git repo, directory, file)
|
||||
-v, --verbose show verbose output from scan
|
||||
|
||||
Use "gitleaks [command] --help" for more information about a command.
|
||||
```
|
||||
|
||||
### Docker usage examples
|
||||
### Commands
|
||||
There are two commands you will use to detect secrets; `detect` and `protect`.
|
||||
#### Detect
|
||||
The `detect` command is used to scan repos, directories, and files. This command can be used on developer machines and in CI environments.
|
||||
|
||||
Run gitleaks against:
|
||||
When running `detect` on a git repository, gitleaks will parse the output of a `git log -p` command (you can see how this executed
|
||||
[here](https://github.com/zricethezav/gitleaks/blob/7240e16769b92d2a1b137c17d6bf9d55a8562899/git/git.go#L17-L25)).
|
||||
[`git log -p` generates patches](https://git-scm.com/docs/git-log#_generating_patch_text_with_p) which gitleaks will use to detect secrets.
|
||||
You can configure what commits `git log` will range over by using the `--log-opts` flag. `--log-opts` accepts any option for `git log -p`.
|
||||
For example, if you wanted to run gitleaks on a range of commits you could use the following command: `gitleaks --source . --log-opts="--all commitA..commitB"`.
|
||||
See the `git log` [documentation](https://git-scm.com/docs/git-log) for more information.
|
||||
|
||||
###### Public repository
|
||||
You can scan files and directories by using the `--no-git` option.
|
||||
|
||||
#### Protect
|
||||
The `protect` command is used to uncommitted changes in a git repo. This command should be used on developer machines in accordance with
|
||||
[shifting left on security](https://cloud.google.com/architecture/devops/devops-tech-shifting-left-on-security).
|
||||
When running `protect` on a git repository, gitleaks will parse the output of a `git diff` command (you can see how this executed
|
||||
[here](https://github.com/zricethezav/gitleaks/blob/7240e16769b92d2a1b137c17d6bf9d55a8562899/git/git.go#L48-L49)). You can set the
|
||||
`--staged` flag to check for changes in commits that have been `git add`ed. The `--staged` flag should be used when running Gitleaks
|
||||
as a pre-commit.
|
||||
|
||||
**NOTE**: the `protect` command can only be used on git repos, running `protect` on files or directories will result in an error message.
|
||||
|
||||
### Verify Findings
|
||||
You can verify a finding found by gitleaks using a `git log` command.
|
||||
Example output:
|
||||
```
|
||||
{
|
||||
"Description": "AWS",
|
||||
"StartLine": 37,
|
||||
"EndLine": 37,
|
||||
"StartColumn": 19,
|
||||
"EndColumn": 38,
|
||||
"Match": "\t\t\"aws_secret= \\\"AKIAIMNOJVGFDXXXE4OA\\\"\": true,",
|
||||
"Secret": "AKIAIMNOJVGFDXXXE4OA",
|
||||
"File": "checks_test.go",
|
||||
"Commit": "ec2fc9d6cb0954fb3b57201cf6133c48d8ca0d29",
|
||||
"Entropy": 0,
|
||||
"Author": "zricethezav",
|
||||
"Email": "thisispublicanyways@gmail.com",
|
||||
"Date": "2018-01-28 17:39:00 -0500 -0500",
|
||||
"Message": "[update] entropy check",
|
||||
"Tags": [],
|
||||
"RuleID": "aws-access-token"
|
||||
}
|
||||
|
||||
```
|
||||
We can use the following format to verify the leak:
|
||||
|
||||
```
|
||||
git log -L {StartLine,EndLine}:{File} {Commit}
|
||||
```
|
||||
So in this example it would look like:
|
||||
```
|
||||
git log -L 37,37:checks_test.go ec2fc9d6cb0954fb3b57201cf6133c48d8ca0d29
|
||||
```
|
||||
Which gives us:
|
||||
|
||||
```
|
||||
commit ec2fc9d6cb0954fb3b57201cf6133c48d8ca0d29
|
||||
Author: zricethezav <thisispublicanyways@gmail.com>
|
||||
Date: Sun Jan 28 17:39:00 2018 -0500
|
||||
|
||||
[update] entropy check
|
||||
|
||||
diff --git a/checks_test.go b/checks_test.go
|
||||
--- a/checks_test.go
|
||||
+++ b/checks_test.go
|
||||
@@ -28,0 +37,1 @@
|
||||
+ "aws_secret= \"AKIAIMNOJVGFDXXXE4OA\"": true,
|
||||
|
||||
```bash
|
||||
docker run --rm --name=gitleaks zricethezav/gitleaks -v -r https://github.com/zricethezav/gitleaks.git
|
||||
```
|
||||
|
||||
###### Local repository already cloned into /tmp/
|
||||
## Pre-Commit hook
|
||||
You can run Gitleaks as a pre-commit hook by copying the example `pre-commit.py` script into
|
||||
your `.git/hooks/` directory.
|
||||
|
||||
```bash
|
||||
docker run --rm --name=gitleaks -v /tmp/:/code/ zricethezav/gitleaks -v --repo-path=/code/gitleaks
|
||||
## Configuration
|
||||
Gitleaks offers a configuration format you can follow to write your own secret detection rules:
|
||||
```toml
|
||||
# Title for the gitleaks configuration file.
|
||||
title = "Gitleaks title"
|
||||
|
||||
# An array of tables that contain information that define instructions
|
||||
# on how to detect secrets
|
||||
[[rules]]
|
||||
|
||||
# Unique identifier for this rule
|
||||
id = "awesome-rule-1"
|
||||
|
||||
# Short human readable description of the rule.
|
||||
description = "awesome rule 1"
|
||||
|
||||
# Golang regular expression used to detect secrets. Note Golang's regex engine
|
||||
# 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
|
||||
|
||||
# Float representing the minimum shannon entropy a regex group must have to be considered a secret.
|
||||
entropy = 3.5
|
||||
|
||||
# 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
|
||||
# (introduced in v8.6.0)
|
||||
keywords = [
|
||||
"auth",
|
||||
"password",
|
||||
"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'''
|
||||
]
|
||||
regexes = [
|
||||
'''process''',
|
||||
'''getenv''',
|
||||
]
|
||||
|
||||
# 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
|
||||
# secrets will be detected for said commit. The same logic applies for regexes and paths.
|
||||
[allowlist]
|
||||
description = "global allow list"
|
||||
commits = [ "commit-A", "commit-B", "commit-C"]
|
||||
paths = [
|
||||
'''gitleaks\.toml''',
|
||||
'''(.*?)(jpg|gif|doc)'''
|
||||
]
|
||||
regexes = [
|
||||
'''219-09-9999''',
|
||||
'''078-05-1120''',
|
||||
'''(9[0-9]{2}|666)-\d{2}-\d{4}''',
|
||||
]
|
||||
```
|
||||
Refer to the default [gitleaks config](https://github.com/zricethezav/gitleaks/blob/master/config/gitleaks.toml) for examples and advice on writing regular expressions for secret detection.
|
||||
|
||||
|
||||
|
||||
## Sponsorships
|
||||
<p align="left">
|
||||
<a href="https://www.tines.com/?utm_source=oss&utm_medium=sponsorship&utm_campaign=gitleaks">
|
||||
<img alt="Tines Sponsorship" src="https://user-images.githubusercontent.com/15034943/146411864-4878f936-b4f7-49a0-b625-f9f40c704bfa.png" width=200>
|
||||
</a>
|
||||
</p>
|
||||
<a href="https://www.typeform.com/">
|
||||
<img src="https://user-images.githubusercontent.com/15034943/146945294-a6473d55-86b8-4f53-941e-7f185ad6b3d7.png" width=200/>
|
||||
</a>
|
||||
</p>
|
||||
|
||||
By default repos cloned to memory. Using `--disk` for clone to disk or you can quickly out of memory.
|
||||
|
||||
For speed up analyze operation using `--threads` parameter, which set to `ALL - 1` threads at your instance CPU.
|
||||
|
||||
|
||||
## Exit Codes
|
||||
|
||||
Gitleaks provides consistent exist codes to assist in automation workflows such as CICD platforms and bulk scanning.
|
||||
|
||||
|
||||
You can always set the exit code when leaks are encountered with the --exit-code flag. Default exit codes below:
|
||||
```
|
||||
0: no leaks
|
||||
1: leaks present
|
||||
2: error encountered
|
||||
0 - no leaks present
|
||||
1 - leaks or error encountered
|
||||
126 - unknown flag
|
||||
```
|
||||
|
||||
### Give Thanks
|
||||
|
||||
If using gitleaks has made you job easier consider donating to one of [Sam](https://www.flickr.com/photos/146541520@N08/albums/72157710121716312)'s favorite places, the Japan House on the University of Illinois at Urbana-Champaign's campus: https://japanhouse.illinois.edu/make-a-gift
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"path"
|
||||
|
||||
"github.com/zricethezav/gitleaks/manager"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// Run accepts a manager and begins an audit based on the options/configs set in the manager.
|
||||
func Run(m *manager.Manager) error {
|
||||
if m.Opts.OwnerPath != "" {
|
||||
files, err := ioutil.ReadDir(m.Opts.OwnerPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, f := range files {
|
||||
if !f.IsDir() {
|
||||
continue
|
||||
}
|
||||
m.Opts.RepoPath = fmt.Sprintf("%s/%s", m.Opts.OwnerPath, f.Name())
|
||||
if err := runHelper(NewRepo(m)); err != nil {
|
||||
log.Warnf("%s is not a git repo, skipping", f.Name())
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
return runHelper(NewRepo(m))
|
||||
}
|
||||
|
||||
func runHelper(r *Repo) error {
|
||||
if r.Manager.Opts.OpenLocal() {
|
||||
r.Name = path.Base(r.Manager.Opts.RepoPath)
|
||||
if err := r.Open(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Check if we are checking uncommitted files. This is the default behavior
|
||||
// for a "$gitleaks" command with no options set
|
||||
if r.Manager.Opts.CheckUncommitted() {
|
||||
if err := r.AuditUncommitted(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
} else {
|
||||
if err := r.Clone(nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return r.Audit()
|
||||
}
|
||||
@@ -1,352 +0,0 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/sergi/go-diff/diffmatchpatch"
|
||||
"github.com/zricethezav/gitleaks/config"
|
||||
"github.com/zricethezav/gitleaks/manager"
|
||||
"github.com/zricethezav/gitleaks/options"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const testRepoBase = "../test_data/test_repos/"
|
||||
|
||||
func TestAudit(t *testing.T) {
|
||||
moveDotGit("dotGit", ".git")
|
||||
defer moveDotGit(".git", "dotGit")
|
||||
tests := []struct {
|
||||
description string
|
||||
opts options.Options
|
||||
wantPath string
|
||||
wantErr error
|
||||
emptyRepo bool
|
||||
wantEmpty bool
|
||||
}{
|
||||
{
|
||||
description: "test local repo one aws leak",
|
||||
opts: options.Options{
|
||||
RepoPath: "../test_data/test_repos/test_repo_1",
|
||||
Report: "../test_data/test_local_repo_one_aws_leak.json.got",
|
||||
ReportFormat: "json",
|
||||
},
|
||||
wantPath: "../test_data/test_local_repo_one_aws_leak.json",
|
||||
},
|
||||
{
|
||||
description: "test local repo one aws leak threaded",
|
||||
opts: options.Options{
|
||||
Threads: runtime.GOMAXPROCS(0),
|
||||
RepoPath: "../test_data/test_repos/test_repo_1",
|
||||
Report: "../test_data/test_local_repo_one_aws_leak.json.got",
|
||||
ReportFormat: "json",
|
||||
},
|
||||
wantPath: "../test_data/test_local_repo_one_aws_leak.json",
|
||||
},
|
||||
{
|
||||
description: "test non existent repo",
|
||||
opts: options.Options{
|
||||
RepoPath: "../test_data/test_repos/no_repo_here",
|
||||
ReportFormat: "json",
|
||||
},
|
||||
emptyRepo: true,
|
||||
},
|
||||
{
|
||||
description: "test local repo one aws leak whitelisted",
|
||||
opts: options.Options{
|
||||
RepoPath: "../test_data/test_repos/test_repo_1",
|
||||
ReportFormat: "json",
|
||||
Config: "../test_data/test_configs/aws_key_whitelist_python_files.toml",
|
||||
},
|
||||
wantEmpty: true,
|
||||
},
|
||||
{
|
||||
description: "test local repo two leaks",
|
||||
opts: options.Options{
|
||||
RepoPath: "../test_data/test_repos/test_repo_2",
|
||||
Report: "../test_data/test_local_repo_two_leaks.json.got",
|
||||
ReportFormat: "json",
|
||||
},
|
||||
wantPath: "../test_data/test_local_repo_two_leaks.json",
|
||||
},
|
||||
{
|
||||
description: "test local repo two leaks globally whitelisted",
|
||||
opts: options.Options{
|
||||
RepoPath: "../test_data/test_repos/test_repo_2",
|
||||
Config: "../test_data/test_configs/aws_key_global_whitelist_file.toml",
|
||||
ReportFormat: "json",
|
||||
},
|
||||
wantEmpty: true,
|
||||
},
|
||||
{
|
||||
description: "test local repo two leaks whitelisted",
|
||||
opts: options.Options{
|
||||
RepoPath: "../test_data/test_repos/test_repo_2",
|
||||
Config: "../test_data/test_configs/aws_key_whitelist_files.toml",
|
||||
ReportFormat: "json",
|
||||
},
|
||||
wantEmpty: true,
|
||||
},
|
||||
{
|
||||
description: "test local repo three leaks dev branch",
|
||||
opts: options.Options{
|
||||
RepoPath: "../test_data/test_repos/test_repo_3",
|
||||
Report: "../test_data/test_local_repo_three_leaks.json.got",
|
||||
Config: "../test_data/test_configs/aws_key.toml",
|
||||
Branch: "dev",
|
||||
ReportFormat: "json",
|
||||
},
|
||||
wantPath: "../test_data/test_local_repo_three_leaks.json",
|
||||
},
|
||||
{
|
||||
description: "test local repo branch does not exist",
|
||||
opts: options.Options{
|
||||
RepoPath: "../test_data/test_repos/test_repo_3",
|
||||
Branch: "nobranch",
|
||||
ReportFormat: "json",
|
||||
},
|
||||
wantEmpty: true,
|
||||
},
|
||||
{
|
||||
description: "test local repo one aws leak single commit",
|
||||
opts: options.Options{
|
||||
RepoPath: "../test_data/test_repos/test_repo_1",
|
||||
Report: "../test_data/test_local_repo_one_aws_leak_commit.json.got",
|
||||
Commit: "6557c92612d3b35979bd426d429255b3bf9fab74",
|
||||
ReportFormat: "json",
|
||||
},
|
||||
wantPath: "../test_data/test_local_repo_one_aws_leak_commit.json",
|
||||
},
|
||||
{
|
||||
description: "test local repo one aws leak AND leak on python files",
|
||||
opts: options.Options{
|
||||
RepoPath: "../test_data/test_repos/test_repo_1",
|
||||
Report: "../test_data/test_local_repo_one_aws_leak_and_file_leak.json.got",
|
||||
Config: "../test_data/test_configs/aws_key_file_regex.toml",
|
||||
ReportFormat: "json",
|
||||
},
|
||||
wantPath: "../test_data/test_local_repo_one_aws_leak_and_file_leak.json",
|
||||
},
|
||||
{
|
||||
description: "test owner path",
|
||||
opts: options.Options{
|
||||
OwnerPath: "../test_data/test_repos/",
|
||||
Report: "../test_data/test_local_owner_aws_leak.json.got",
|
||||
ReportFormat: "json",
|
||||
},
|
||||
wantPath: "../test_data/test_local_owner_aws_leak.json",
|
||||
},
|
||||
{
|
||||
description: "test entropy",
|
||||
opts: options.Options{
|
||||
RepoPath: "../test_data/test_repos/test_repo_1",
|
||||
Report: "../test_data/test_entropy.json.got",
|
||||
Config: "../test_data/test_configs/entropy.toml",
|
||||
ReportFormat: "json",
|
||||
},
|
||||
wantPath: "../test_data/test_entropy.json",
|
||||
},
|
||||
{
|
||||
description: "test entropy and regex",
|
||||
opts: options.Options{
|
||||
RepoPath: "../test_data/test_repos/test_repo_1",
|
||||
Report: "../test_data/test_regex_entropy.json.got",
|
||||
Config: "../test_data/test_configs/regex_entropy.toml",
|
||||
ReportFormat: "json",
|
||||
},
|
||||
wantPath: "../test_data/test_regex_entropy.json",
|
||||
},
|
||||
{
|
||||
description: "test local repo four entropy alternative config",
|
||||
opts: options.Options{
|
||||
RepoPath: "../test_data/test_repos/test_repo_4",
|
||||
Report: "../test_data/test_local_repo_four_alt_config_entropy.json.got",
|
||||
RepoConfig: true,
|
||||
ReportFormat: "json",
|
||||
},
|
||||
wantPath: "../test_data/test_local_repo_four_alt_config_entropy.json",
|
||||
},
|
||||
{
|
||||
description: "test local repo four entropy alternative config",
|
||||
opts: options.Options{
|
||||
RepoPath: "../test_data/test_repos/test_repo_1",
|
||||
Report: "../test_data/test_regex_whitelist.json.got",
|
||||
Config: "../test_data/test_configs/aws_key_aws_whitelisted.toml",
|
||||
ReportFormat: "json",
|
||||
},
|
||||
wantEmpty: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
fmt.Println(test.description)
|
||||
cfg, err := config.NewConfig(test.opts)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
m, err := manager.NewManager(test.opts, cfg)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
err = Run(m)
|
||||
|
||||
if test.wantErr != nil {
|
||||
if err == nil {
|
||||
t.Errorf("did not receive wantErr: %v", test.wantErr)
|
||||
}
|
||||
if err.Error() != test.wantErr.Error() {
|
||||
t.Errorf("wantErr does not equal err received: %v", err.Error())
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
err = m.Report()
|
||||
|
||||
if test.wantEmpty {
|
||||
if len(m.GetLeaks()) != 0 {
|
||||
t.Errorf("wanted no leaks but got some instead: %+v", m.GetLeaks())
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if test.wantPath != "" {
|
||||
err := fileCheck(test.wantPath, test.opts.Report)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditUncommited(t *testing.T) {
|
||||
moveDotGit("dotGit", ".git")
|
||||
defer moveDotGit(".git", "dotGit")
|
||||
tests := []struct {
|
||||
description string
|
||||
opts options.Options
|
||||
wantPath string
|
||||
wantErr error
|
||||
emptyRepo bool
|
||||
wantEmpty bool
|
||||
fileToChange string
|
||||
addition string
|
||||
}{
|
||||
{
|
||||
description: "test audit local one leak",
|
||||
opts: options.Options{
|
||||
RepoPath: "../test_data/test_repos/test_repo_1",
|
||||
Report: "../test_data/test_local_repo_one_aws_leak_uncommitted.json.got",
|
||||
Uncommited: true,
|
||||
ReportFormat: "json",
|
||||
},
|
||||
wantPath: "../test_data/test_local_repo_one_aws_leak_uncommitted.json",
|
||||
fileToChange: "server.test.py",
|
||||
addition: " aws_access_key_id='AKIAIO5FODNN7DXAMPLE'\n\n",
|
||||
},
|
||||
{
|
||||
description: "test audit local no leak",
|
||||
opts: options.Options{
|
||||
RepoPath: "../test_data/test_repos/test_repo_1",
|
||||
Uncommited: true,
|
||||
ReportFormat: "json",
|
||||
},
|
||||
wantEmpty: true,
|
||||
fileToChange: "server.test.py",
|
||||
addition: "nothing bad",
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
fmt.Println(test.description)
|
||||
old, err := ioutil.ReadFile(fmt.Sprintf("%s/%s", test.opts.RepoPath, test.fileToChange))
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
altered, err := os.OpenFile(fmt.Sprintf("%s/%s", test.opts.RepoPath, test.fileToChange),
|
||||
os.O_WRONLY|os.O_APPEND, 0644)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
_, err = altered.WriteString(test.addition)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
cfg, err := config.NewConfig(test.opts)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
m, err := manager.NewManager(test.opts, cfg)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
if err := Run(m); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
if err := m.Report(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
err = ioutil.WriteFile(fmt.Sprintf("%s/%s", test.opts.RepoPath, test.fileToChange), old, 0)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
if test.wantEmpty {
|
||||
continue
|
||||
}
|
||||
|
||||
if test.wantPath != "" {
|
||||
err := fileCheck(test.wantPath, test.opts.Report)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func fileCheck(wantPath, gotPath string) error {
|
||||
want, err := ioutil.ReadFile(wantPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
got, err := ioutil.ReadFile(gotPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if strings.Trim(string(want), "\n") != strings.Trim(string(got), "\n") {
|
||||
dmp := diffmatchpatch.New()
|
||||
diffs := dmp.DiffMain(string(want), string(got), false)
|
||||
return fmt.Errorf("does not equal: %s", dmp.DiffPrettyText(diffs))
|
||||
}
|
||||
if err := os.Remove(gotPath); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func moveDotGit(from, to string) error {
|
||||
repoDirs, err := ioutil.ReadDir("../test_data/test_repos")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, dir := range repoDirs {
|
||||
if !dir.IsDir() {
|
||||
continue
|
||||
}
|
||||
err = os.Rename(fmt.Sprintf("%s/%s/%s", testRepoBase, dir.Name(), from),
|
||||
fmt.Sprintf("%s/%s/%s", testRepoBase, dir.Name(), to))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
-314
@@ -1,314 +0,0 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/md5"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/zricethezav/gitleaks/config"
|
||||
"github.com/zricethezav/gitleaks/manager"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
"github.com/sergi/go-diff/diffmatchpatch"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gopkg.in/src-d/go-billy.v4"
|
||||
"gopkg.in/src-d/go-git.v4"
|
||||
"gopkg.in/src-d/go-git.v4/plumbing"
|
||||
"gopkg.in/src-d/go-git.v4/plumbing/object"
|
||||
"gopkg.in/src-d/go-git.v4/plumbing/storer"
|
||||
"gopkg.in/src-d/go-git.v4/storage/memory"
|
||||
)
|
||||
|
||||
// Repo wraps a *git.Repository object in addition to a manager object and the name of the repo.
|
||||
// Commits are inspected from the *git.Repository object. If a commit is found then we send it
|
||||
// via the manager LeakChan where the manager receives and keeps track of all leaks.
|
||||
type Repo struct {
|
||||
*git.Repository
|
||||
|
||||
// config is used when the --repo-config option is set.
|
||||
// This allows users to load up configs specific to their repos.
|
||||
// Imagine the scenario where you are doing an audit of a large organization
|
||||
// and you want certain repos to look for specific rules. If those specific repos
|
||||
// have a gitleaks.toml or .gitleaks.toml config then those configs will be used specifically
|
||||
// for those repo audits.
|
||||
config config.Config
|
||||
|
||||
Name string
|
||||
Manager *manager.Manager
|
||||
}
|
||||
|
||||
// NewRepo initializes and returns a Repo struct.
|
||||
func NewRepo(m *manager.Manager) *Repo {
|
||||
return &Repo{
|
||||
Manager: m,
|
||||
config: m.Config,
|
||||
}
|
||||
}
|
||||
|
||||
// Clone will clone a repo and return a Repo struct which contains a go-git repo. The clone method
|
||||
// is determined by the clone options set in Manager.metadata.cloneOptions
|
||||
func (repo *Repo) Clone(cloneOption *git.CloneOptions) error {
|
||||
var (
|
||||
repository *git.Repository
|
||||
err error
|
||||
)
|
||||
if cloneOption == nil {
|
||||
cloneOption = repo.Manager.CloneOptions
|
||||
}
|
||||
|
||||
log.Infof("cloning... %s", cloneOption.URL)
|
||||
start := time.Now()
|
||||
|
||||
if repo.Manager.CloneDir != "" {
|
||||
clonePath := fmt.Sprintf("%s/%x", repo.Manager.CloneDir, md5.Sum([]byte(time.Now().String())))
|
||||
repository, err = git.PlainClone(clonePath, false, cloneOption)
|
||||
} else {
|
||||
repository, err = git.Clone(memory.NewStorage(), nil, cloneOption)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
repo.Name = filepath.Base(repo.Manager.Opts.Repo)
|
||||
repo.Repository = repository
|
||||
repo.Manager.RecordTime(manager.CloneTime(howLong(start)))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// AuditUncommitted will do a `git diff` and scan changed files that are being tracked. This is useful functionality
|
||||
// for a pre-commit hook so you can make sure your code does not have any leaks before committing.
|
||||
func (repo *Repo) AuditUncommitted() error {
|
||||
auditTimeStart := time.Now()
|
||||
|
||||
r, err := repo.Head()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := repo.CommitObject(r.Hash())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
prevTree, err := c.Tree()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
wt, err := repo.Worktree()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
status, err := wt.Status()
|
||||
for fn, state := range status {
|
||||
var (
|
||||
prevFileContents string
|
||||
currFileContents string
|
||||
filename string
|
||||
)
|
||||
|
||||
if state.Staging != git.Untracked {
|
||||
if state.Staging == git.Deleted {
|
||||
// file in staging has been deleted, aka it is not on the filesystem
|
||||
// so the contents of the file are ""
|
||||
currFileContents = ""
|
||||
} else {
|
||||
workTreeBuf := bytes.NewBuffer(nil)
|
||||
workTreeFile, err := wt.Filesystem.Open(fn)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if _, err := io.Copy(workTreeBuf, workTreeFile); err != nil {
|
||||
return err
|
||||
}
|
||||
currFileContents = workTreeBuf.String()
|
||||
filename = workTreeFile.Name()
|
||||
}
|
||||
|
||||
// get files at HEAD state
|
||||
prevFile, err := prevTree.File(fn)
|
||||
if err != nil {
|
||||
prevFileContents = ""
|
||||
|
||||
} else {
|
||||
prevFileContents, err = prevFile.Contents()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if filename == "" {
|
||||
filename = prevFile.Name
|
||||
}
|
||||
}
|
||||
|
||||
dmp := diffmatchpatch.New()
|
||||
diffs := dmp.DiffMain(prevFileContents, currFileContents, false)
|
||||
var diffContents string
|
||||
for _, d := range diffs {
|
||||
switch d.Type {
|
||||
case diffmatchpatch.DiffInsert:
|
||||
diffContents += fmt.Sprintf("%s\n", d.Text)
|
||||
case diffmatchpatch.DiffDelete:
|
||||
diffContents += fmt.Sprintf("%s\n", d.Text)
|
||||
}
|
||||
}
|
||||
InspectString(diffContents, c, repo, filename)
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
repo.Manager.RecordTime(manager.AuditTime(howLong(auditTimeStart)))
|
||||
return nil
|
||||
}
|
||||
|
||||
// Audit is responsible for scanning the entire history (default behavior) of a
|
||||
// git repo. Options that can change the behavior of this function include: --commit, --depth, --branch.
|
||||
// See options/options.go for an explanation on these options.
|
||||
func (repo *Repo) Audit() error {
|
||||
if repo.Repository == nil {
|
||||
return fmt.Errorf("%s repo is empty", repo.Name)
|
||||
}
|
||||
|
||||
// load up alternative config if possible, if not use manager's config
|
||||
if repo.Manager.Opts.RepoConfig {
|
||||
cfg, err := repo.loadRepoConfig()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
repo.config = cfg
|
||||
}
|
||||
|
||||
auditTimeStart := time.Now()
|
||||
|
||||
// audit single Commit
|
||||
if repo.Manager.Opts.Commit != "" {
|
||||
h := plumbing.NewHash(repo.Manager.Opts.Commit)
|
||||
c, err := repo.CommitObject(h)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = inspectCommit(c, repo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
logOpts, err := getLogOptions(repo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cIter, err := repo.Log(logOpts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cc := 0
|
||||
semaphore := make(chan bool, howManyThreads(repo.Manager.Opts.Threads))
|
||||
wg := sync.WaitGroup{}
|
||||
err = cIter.ForEach(func(c *object.Commit) error {
|
||||
if c == nil {
|
||||
return storer.ErrStop
|
||||
}
|
||||
|
||||
if len(c.ParentHashes) == 0 {
|
||||
cc++
|
||||
err = inspectCommit(c, repo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if isCommitWhiteListed(c.Hash.String(), repo.config.Whitelist.Commits) {
|
||||
return nil
|
||||
}
|
||||
|
||||
cc++
|
||||
err = c.Parents().ForEach(func(parent *object.Commit) error {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
// sometimes the patch generation will fail due to a known bug in
|
||||
// sergi's go-diff: https://github.com/sergi/go-diff/issues/89.
|
||||
// Once a fix has been merged I will remove this recover.
|
||||
return
|
||||
}
|
||||
}()
|
||||
start := time.Now()
|
||||
patch, err := c.Patch(parent)
|
||||
if err != nil {
|
||||
return fmt.Errorf("could not generate patch")
|
||||
}
|
||||
repo.Manager.RecordTime(manager.PatchTime(howLong(start)))
|
||||
wg.Add(1)
|
||||
semaphore <- true
|
||||
go func(c *object.Commit, patch *object.Patch) {
|
||||
defer func() {
|
||||
<-semaphore
|
||||
wg.Done()
|
||||
}()
|
||||
inspectPatch(patch, c, repo)
|
||||
}(c, patch)
|
||||
|
||||
return nil
|
||||
})
|
||||
return nil
|
||||
})
|
||||
|
||||
wg.Wait()
|
||||
repo.Manager.RecordTime(manager.AuditTime(howLong(auditTimeStart)))
|
||||
repo.Manager.IncrementCommits(cc)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Open opens a local repo either from repo-path or $PWD
|
||||
func (repo *Repo) Open() error {
|
||||
if repo.Manager.Opts.RepoPath != "" {
|
||||
// open git repo from repo path
|
||||
repository, err := git.PlainOpen(repo.Manager.Opts.RepoPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
repo.Repository = repository
|
||||
} else {
|
||||
// open git repo from PWD
|
||||
dir, err := os.Getwd()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
repository, err := git.PlainOpen(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
repo.Repository = repository
|
||||
repo.Name = path.Base(dir)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repo *Repo) loadRepoConfig() (config.Config, error) {
|
||||
wt, err := repo.Repository.Worktree()
|
||||
if err != nil {
|
||||
return config.Config{}, err
|
||||
}
|
||||
var f billy.File
|
||||
f, _ = wt.Filesystem.Open(".gitleaks.toml")
|
||||
if f == nil {
|
||||
f, err = wt.Filesystem.Open("gitleaks.toml")
|
||||
if err != nil {
|
||||
return config.Config{}, fmt.Errorf("problem loading repo config: %v", err)
|
||||
}
|
||||
}
|
||||
defer f.Close()
|
||||
var tomlLoader config.TomlLoader
|
||||
_, err = toml.DecodeReader(f, &tomlLoader)
|
||||
return tomlLoader.Parse()
|
||||
}
|
||||
-383
@@ -1,383 +0,0 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/zricethezav/gitleaks/config"
|
||||
"github.com/zricethezav/gitleaks/manager"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gopkg.in/src-d/go-git.v4"
|
||||
"gopkg.in/src-d/go-git.v4/plumbing"
|
||||
fdiff "gopkg.in/src-d/go-git.v4/plumbing/format/diff"
|
||||
"gopkg.in/src-d/go-git.v4/plumbing/object"
|
||||
)
|
||||
|
||||
const maxLineLen = 200
|
||||
|
||||
// Inspect patch accepts a patch, commit, and repo. If the patches contains files that are
|
||||
// binary, then gitleaks will skip auditing that file OR if a file is matched on
|
||||
// whitelisted files set in the configuration. If a global rule for files is defined and a filename
|
||||
// matches said global rule, then a laek is sent to the manager.
|
||||
// After that, file chunks are created which are then inspected by InspectString()
|
||||
func inspectPatch(patch *object.Patch, c *object.Commit, repo *Repo) {
|
||||
for _, f := range patch.FilePatches() {
|
||||
if f.IsBinary() {
|
||||
continue
|
||||
}
|
||||
if fileMatched(getFileName(f), repo.config.Whitelist.File) {
|
||||
log.Debugf("whitelisted file found, skipping audit of file: %s", getFileName(f))
|
||||
continue
|
||||
}
|
||||
if fileMatched(getFileName(f), repo.config.FileRegex) {
|
||||
repo.Manager.SendLeaks(manager.Leak{
|
||||
Line: "N/A",
|
||||
Offender: getFileName(f),
|
||||
Commit: c.Hash.String(),
|
||||
Repo: repo.Name,
|
||||
Rule: "file regex matched" + repo.config.FileRegex.String(),
|
||||
Author: c.Author.Name,
|
||||
Email: c.Author.Email,
|
||||
Date: c.Author.When,
|
||||
File: getFileName(f),
|
||||
})
|
||||
}
|
||||
for _, chunk := range f.Chunks() {
|
||||
if chunk.Type() == fdiff.Delete || chunk.Type() == fdiff.Add {
|
||||
InspectString(chunk.Content(), c, repo, getFileName(f))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// getFileName accepts a file patch and returns the filename
|
||||
func getFileName(f fdiff.FilePatch) string {
|
||||
fn := "???"
|
||||
from, to := f.Files()
|
||||
if from != nil {
|
||||
return from.Path()
|
||||
} else if to != nil {
|
||||
return to.Path()
|
||||
}
|
||||
|
||||
return fn
|
||||
}
|
||||
|
||||
// getShannonEntropy https://en.wiktionary.org/wiki/Shannon_entropy
|
||||
func shannonEntropy(data string) (entropy float64) {
|
||||
if data == "" {
|
||||
return 0
|
||||
}
|
||||
|
||||
charCounts := make(map[rune]int)
|
||||
for _, char := range data {
|
||||
charCounts[char]++
|
||||
}
|
||||
|
||||
invLength := 1.0 / float64(len(data))
|
||||
for _, count := range charCounts {
|
||||
freq := float64(count) * invLength
|
||||
entropy -= freq * math.Log2(freq)
|
||||
}
|
||||
|
||||
return entropy
|
||||
}
|
||||
|
||||
// aws_access_key_id='AKIAIO5FODNN7EXAMPLE',
|
||||
// trippedEntropy checks if a given line falls in between entropy ranges supplied
|
||||
// by a custom gitleaks configuration. Gitleaks do not check entropy by default.
|
||||
func trippedEntropy(line string, rule config.Rule) bool {
|
||||
for _, e := range rule.Entropy {
|
||||
entropy := shannonEntropy(line)
|
||||
if entropy > e.P1 && entropy < e.P2 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func ruleContainRegex(rule config.Rule) bool {
|
||||
if rule.Regex == nil {
|
||||
return false
|
||||
}
|
||||
if rule.Regex.String() == "" {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// InspectString accepts a string, commit object, repo, and filename. This function iterates over
|
||||
// all the rules set by the gitleaks config. If the rule contains entropy checks then entropy will be checked first.
|
||||
// Next, if the rule contains a regular expression then that will be checked.
|
||||
func InspectString(content string, c *object.Commit, repo *Repo, filename string) {
|
||||
for _, rule := range repo.config.Rules {
|
||||
// check entropy
|
||||
if len(rule.Entropy) != 0 {
|
||||
// an optimization would be to switch the regex from FindAllIndex to FindString
|
||||
// since we are iterating on the lines if entropy rules exist...
|
||||
for _, line := range strings.Split(content, "\n") {
|
||||
entropyTripped := trippedEntropy(line, rule)
|
||||
if entropyTripped && !ruleContainRegex(rule) {
|
||||
_line := line
|
||||
if len(_line) > maxLineLen {
|
||||
_line = line[0 : maxLineLen-1]
|
||||
}
|
||||
repo.Manager.SendLeaks(manager.Leak{
|
||||
Line: _line,
|
||||
Offender: fmt.Sprintf("Entropy range %+v", rule.Entropy),
|
||||
Commit: c.Hash.String(),
|
||||
Repo: repo.Name,
|
||||
Message: c.Message,
|
||||
Rule: rule.Description,
|
||||
Author: c.Author.Name,
|
||||
Email: c.Author.Email,
|
||||
Date: c.Author.When,
|
||||
Tags: strings.Join(rule.Tags, ", "),
|
||||
File: filename,
|
||||
})
|
||||
} else if entropyTripped {
|
||||
// entropy has been tripped which means if there is a regex specified in the same
|
||||
// rule, we need to inspect the line for a regex match. In otherwords, the current rule has
|
||||
// both entropy and regex set which work in combination. This helps narrow down false positives
|
||||
// on searches for generic passwords in code.
|
||||
match := rule.Regex.FindString(line)
|
||||
|
||||
// check if any rules are whitelisting this leak
|
||||
if len(rule.Whitelist) != 0 {
|
||||
for _, wl := range rule.Whitelist {
|
||||
if fileMatched(filename, wl.File) {
|
||||
// if matched, go to next rule
|
||||
goto NEXTLINE
|
||||
}
|
||||
if wl.Regex.FindString(line) != "" {
|
||||
goto NEXTLINE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if match != "" {
|
||||
// both the regex and entropy in this rule have been tripped which means this line
|
||||
// contains a leak
|
||||
repo.Manager.SendLeaks(manager.Leak{
|
||||
Line: line,
|
||||
Offender: match,
|
||||
Commit: c.Hash.String(),
|
||||
Message: c.Message,
|
||||
Repo: repo.Name,
|
||||
Rule: rule.Description,
|
||||
Author: c.Author.Name,
|
||||
Email: c.Author.Email,
|
||||
Date: c.Author.When,
|
||||
Tags: strings.Join(rule.Tags, ", "),
|
||||
File: filename,
|
||||
})
|
||||
}
|
||||
}
|
||||
NEXTLINE:
|
||||
}
|
||||
return
|
||||
}
|
||||
if rule.Regex.String() == "" {
|
||||
continue
|
||||
}
|
||||
start := time.Now()
|
||||
locs := rule.Regex.FindAllIndex([]byte(content), -1)
|
||||
if len(locs) != 0 {
|
||||
// check if any rules are whitelisting this leak
|
||||
if len(rule.Whitelist) != 0 {
|
||||
for _, wl := range rule.Whitelist {
|
||||
if fileMatched(filename, wl.File) {
|
||||
// if matched, go to next rule
|
||||
goto NEXT
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, loc := range locs {
|
||||
start := loc[0]
|
||||
end := loc[1]
|
||||
for start != 0 && content[start] != '\n' {
|
||||
start = start - 1
|
||||
}
|
||||
if start != 0 {
|
||||
// skip newline
|
||||
start = start + 1
|
||||
}
|
||||
|
||||
for end < len(content)-1 && content[end] != '\n' {
|
||||
end = end + 1
|
||||
}
|
||||
|
||||
offender := content[loc[0]:loc[1]]
|
||||
line := content[start:end]
|
||||
|
||||
if len(rule.Whitelist) != 0 {
|
||||
for _, wl := range rule.Whitelist {
|
||||
if wl.Regex.FindString(line) != "" {
|
||||
goto NEXT
|
||||
}
|
||||
}
|
||||
}
|
||||
if repo.Manager.Opts.Redact {
|
||||
line = strings.ReplaceAll(line, offender, "REDACTED")
|
||||
offender = "REDACTED"
|
||||
}
|
||||
|
||||
repo.Manager.SendLeaks(manager.Leak{
|
||||
Line: line,
|
||||
Offender: offender,
|
||||
Commit: c.Hash.String(),
|
||||
Message: c.Message,
|
||||
Repo: repo.Name,
|
||||
Rule: rule.Description,
|
||||
Author: c.Author.Name,
|
||||
Email: c.Author.Email,
|
||||
Date: c.Author.When,
|
||||
Tags: strings.Join(rule.Tags, ", "),
|
||||
File: filename,
|
||||
})
|
||||
}
|
||||
}
|
||||
repo.Manager.RecordTime(manager.RegexTime{
|
||||
Time: time.Now().Sub(start).Nanoseconds(),
|
||||
Regex: rule.Regex.String(),
|
||||
})
|
||||
NEXT:
|
||||
}
|
||||
}
|
||||
|
||||
// inspectCommit accepts a commit object and a repo. This function is only called when the --commit=
|
||||
// option has been set. That option tells gitleaks to look only at a single commit and check the contents
|
||||
// of said commit. Similar to inspectPatch(), if the files contained in the commit are a binaries or if they are
|
||||
// whitelisted then those files will be skipped.
|
||||
func inspectCommit(c *object.Commit, repo *Repo) error {
|
||||
fIter, err := c.Files()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = fIter.ForEach(func(f *object.File) error {
|
||||
bin, err := f.IsBinary()
|
||||
if bin {
|
||||
return nil
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
if fileMatched(f, repo.config.Whitelist.File) {
|
||||
log.Debugf("whitelisted file found, skipping audit of file: %s", f.Name)
|
||||
return nil
|
||||
}
|
||||
|
||||
if fileMatched(f.Name, repo.config.FileRegex) {
|
||||
repo.Manager.SendLeaks(manager.Leak{
|
||||
Line: "N/A",
|
||||
Offender: f.Name,
|
||||
Commit: c.Hash.String(),
|
||||
Repo: repo.Name,
|
||||
Rule: "file regex matched" + repo.config.FileRegex.String(),
|
||||
Author: c.Author.Name,
|
||||
Email: c.Author.Email,
|
||||
Date: c.Author.When,
|
||||
File: f.Name,
|
||||
})
|
||||
}
|
||||
content, err := f.Contents()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
InspectString(content, c, repo, f.Name)
|
||||
|
||||
return nil
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// howManyThreads will return a number 1-GOMAXPROCS which is the number
|
||||
// of goroutines that will spawn during gitleaks execution
|
||||
func howManyThreads(threads int) int {
|
||||
maxThreads := runtime.GOMAXPROCS(0)
|
||||
if threads == 0 {
|
||||
return 1
|
||||
} else if threads > maxThreads {
|
||||
log.Warnf("%d threads set too high, setting to system max, %d", threads, maxThreads)
|
||||
return maxThreads
|
||||
}
|
||||
return threads
|
||||
}
|
||||
|
||||
func isCommitWhiteListed(commitHash string, whitelistedCommits []string) bool {
|
||||
for _, hash := range whitelistedCommits {
|
||||
if commitHash == hash {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func fileMatched(f interface{}, re *regexp.Regexp) bool {
|
||||
if re == nil {
|
||||
return false
|
||||
}
|
||||
switch f.(type) {
|
||||
case nil:
|
||||
return false
|
||||
case string:
|
||||
if re.FindString(f.(string)) != "" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
case *object.File:
|
||||
if re.FindString(f.(*object.File).Name) != "" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// getLogOptions determines what log options are used when iterating through commits.
|
||||
// It is similar to `git log {branch}`. Default behavior is to log ALL branches so
|
||||
// gitleaks gets the full git history.
|
||||
func getLogOptions(repo *Repo) (*git.LogOptions, error) {
|
||||
if repo.Manager.Opts.Branch != "" {
|
||||
var logOpts git.LogOptions
|
||||
refs, err := repo.Storer.IterReferences()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = refs.ForEach(func(ref *plumbing.Reference) error {
|
||||
if ref.Name().IsTag() {
|
||||
return nil
|
||||
}
|
||||
// check heads first
|
||||
if ref.Name().String() == "refs/heads/"+repo.Manager.Opts.Branch {
|
||||
logOpts = git.LogOptions{
|
||||
From: ref.Hash(),
|
||||
}
|
||||
return nil
|
||||
} else if ref.Name().String() == "refs/remotes/origin/"+repo.Manager.Opts.Branch {
|
||||
logOpts = git.LogOptions{
|
||||
From: ref.Hash(),
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if logOpts.From.IsZero() {
|
||||
return nil, fmt.Errorf("could not find branch %s", repo.Manager.Opts.Branch)
|
||||
}
|
||||
return &logOpts, nil
|
||||
}
|
||||
return &git.LogOptions{All: true}, nil
|
||||
}
|
||||
|
||||
// howLong accepts a time.Time object which is subtracted from time.Now() and
|
||||
// converted to nanoseconds which is returned
|
||||
func howLong(t time.Time) int64 {
|
||||
return time.Now().Sub(t).Nanoseconds()
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/detect"
|
||||
"github.com/zricethezav/gitleaks/v8/report"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(detectCmd)
|
||||
detectCmd.Flags().String("log-opts", "", "git log options")
|
||||
detectCmd.Flags().Bool("no-git", false, "treat git repo as a regular directory and scan those files, --log-opts has no effect on the scan when --no-git is set")
|
||||
}
|
||||
|
||||
var detectCmd = &cobra.Command{
|
||||
Use: "detect",
|
||||
Short: "detect secrets in code",
|
||||
Run: runDetect,
|
||||
}
|
||||
|
||||
func runDetect(cmd *cobra.Command, args []string) {
|
||||
initConfig()
|
||||
var (
|
||||
vc config.ViperConfig
|
||||
findings []report.Finding
|
||||
err error
|
||||
)
|
||||
|
||||
// Load config
|
||||
if err = viper.Unmarshal(&vc); err != nil {
|
||||
log.Fatal().Err(err).Msg("Failed to load config")
|
||||
}
|
||||
cfg, err := vc.Translate()
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("Failed to load config")
|
||||
}
|
||||
cfg.Path, _ = cmd.Flags().GetString("config")
|
||||
|
||||
// start timer
|
||||
start := time.Now()
|
||||
|
||||
// Setup detector
|
||||
detector := detect.NewDetector(cfg)
|
||||
detector.Config.Path, err = cmd.Flags().GetString("config")
|
||||
if err != nil {
|
||||
log.Fatal().Err(err)
|
||||
}
|
||||
source, err := cmd.Flags().GetString("source")
|
||||
if err != nil {
|
||||
log.Fatal().Err(err)
|
||||
}
|
||||
// if config path is not set, then use the {source}/.gitleaks.toml path.
|
||||
// note that there may not be a `{source}/.gitleaks.toml` file, this is ok.
|
||||
if detector.Config.Path == "" {
|
||||
detector.Config.Path = filepath.Join(source, ".gitleaks.toml")
|
||||
}
|
||||
// set verbose flag
|
||||
if detector.Verbose, err = cmd.Flags().GetBool("verbose"); err != nil {
|
||||
log.Fatal().Err(err)
|
||||
}
|
||||
// set redact flag
|
||||
if detector.Redact, err = cmd.Flags().GetBool("redact"); err != nil {
|
||||
log.Fatal().Err(err)
|
||||
}
|
||||
|
||||
// set exit code
|
||||
exitCode, err := cmd.Flags().GetInt("exit-code")
|
||||
if err != nil {
|
||||
log.Fatal().Err(err)
|
||||
}
|
||||
|
||||
// determine what type of scan:
|
||||
// - git: scan the history of the repo
|
||||
// - no-git: scan files by treating the repo as a plain directory
|
||||
noGit, err := cmd.Flags().GetBool("no-git")
|
||||
if err != nil {
|
||||
log.Fatal().Err(err)
|
||||
}
|
||||
|
||||
// start the detector scan
|
||||
if noGit {
|
||||
findings, err = detector.DetectFiles(source)
|
||||
if err != nil {
|
||||
// don't exit on error, just log it
|
||||
log.Error().Err(err)
|
||||
}
|
||||
|
||||
} else {
|
||||
logOpts, err := cmd.Flags().GetString("log-opts")
|
||||
if err != nil {
|
||||
log.Fatal().Err(err)
|
||||
}
|
||||
findings, err = detector.DetectGit(source, logOpts, detect.DetectType)
|
||||
if err != nil {
|
||||
// don't exit on error, just log it
|
||||
log.Error().Err(err)
|
||||
}
|
||||
}
|
||||
|
||||
// log info about the scan
|
||||
log.Info().Msgf("scan completed in %s", time.Since(start))
|
||||
if len(findings) != 0 {
|
||||
log.Warn().Msgf("leaks found: %d", len(findings))
|
||||
} else {
|
||||
log.Info().Msg("no leaks found")
|
||||
}
|
||||
|
||||
// write report if desired
|
||||
reportPath, _ := cmd.Flags().GetString("report-path")
|
||||
ext, _ := cmd.Flags().GetString("report-format")
|
||||
if reportPath != "" {
|
||||
if err = report.Write(findings, cfg, ext, reportPath); err != nil {
|
||||
log.Fatal().Err(err)
|
||||
}
|
||||
}
|
||||
|
||||
if len(findings) != 0 {
|
||||
os.Exit(exitCode)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"text/template"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/rules"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
const (
|
||||
templatePath = "rules/config.tmpl"
|
||||
)
|
||||
|
||||
func main() {
|
||||
configRules := []*config.Rule{}
|
||||
configRules = append(configRules, rules.AdobeClientID())
|
||||
configRules = append(configRules, rules.AdobeClientSecret())
|
||||
configRules = append(configRules, rules.AgeSecretKey())
|
||||
configRules = append(configRules, rules.AlibabaAccessKey())
|
||||
configRules = append(configRules, rules.AlibabaSecretKey())
|
||||
configRules = append(configRules, rules.AsanaClientID())
|
||||
configRules = append(configRules, rules.AsanaClientSecret())
|
||||
configRules = append(configRules, rules.Atlassian())
|
||||
configRules = append(configRules, rules.AWS())
|
||||
configRules = append(configRules, rules.BitBucketClientID())
|
||||
configRules = append(configRules, rules.BitBucketClientSecret())
|
||||
configRules = append(configRules, rules.Beamer())
|
||||
configRules = append(configRules, rules.Clojars())
|
||||
configRules = append(configRules, rules.Contentful())
|
||||
configRules = append(configRules, rules.Databricks())
|
||||
configRules = append(configRules, rules.DiscordAPIToken())
|
||||
configRules = append(configRules, rules.DiscordClientID())
|
||||
configRules = append(configRules, rules.DiscordClientSecret())
|
||||
configRules = append(configRules, rules.DropBoxAPISecret())
|
||||
configRules = append(configRules, rules.DropBoxLongLivedAPIToken())
|
||||
configRules = append(configRules, rules.DropBoxShortLivedAPIToken())
|
||||
configRules = append(configRules, rules.Doppler())
|
||||
configRules = append(configRules, rules.Duffel())
|
||||
configRules = append(configRules, rules.Dynatrace())
|
||||
configRules = append(configRules, rules.EasyPost())
|
||||
configRules = append(configRules, rules.EasyPostTestAPI())
|
||||
configRules = append(configRules, rules.Facebook())
|
||||
configRules = append(configRules, rules.FastlyAPIToken())
|
||||
configRules = append(configRules, rules.FinicityClientSecret())
|
||||
configRules = append(configRules, rules.FinicityAPIToken())
|
||||
configRules = append(configRules, rules.FlutterwavePublicKey())
|
||||
configRules = append(configRules, rules.FlutterwaveSecretKey())
|
||||
configRules = append(configRules, rules.FlutterwaveSecretKey())
|
||||
configRules = append(configRules, rules.FrameIO())
|
||||
configRules = append(configRules, rules.GenericCredential())
|
||||
configRules = append(configRules, rules.GoCardless())
|
||||
// TODO figure out what makes sense for GCP
|
||||
// configRules = append(configRules, rules.GCPServiceAccount())
|
||||
configRules = append(configRules, rules.GitHubPat())
|
||||
configRules = append(configRules, rules.GitHubOauth())
|
||||
configRules = append(configRules, rules.GitHubApp())
|
||||
configRules = append(configRules, rules.GitHubRefresh())
|
||||
configRules = append(configRules, rules.Gitlab())
|
||||
configRules = append(configRules, rules.Hashicorp())
|
||||
configRules = append(configRules, rules.Heroku())
|
||||
configRules = append(configRules, rules.HubSpot())
|
||||
configRules = append(configRules, rules.Intercom())
|
||||
configRules = append(configRules, rules.LinearAPIToken())
|
||||
configRules = append(configRules, rules.LinearClientSecret())
|
||||
configRules = append(configRules, rules.LinkedinClientID())
|
||||
configRules = append(configRules, rules.LinkedinClientSecret())
|
||||
configRules = append(configRules, rules.LobAPIToken())
|
||||
configRules = append(configRules, rules.LobPubAPIToken())
|
||||
configRules = append(configRules, rules.MailChimp())
|
||||
configRules = append(configRules, rules.MailGunPubAPIToken())
|
||||
configRules = append(configRules, rules.MailGunPrivateAPIToken())
|
||||
configRules = append(configRules, rules.MailGunSigningKey())
|
||||
configRules = append(configRules, rules.MapBox())
|
||||
configRules = append(configRules, rules.MessageBirdAPIToken())
|
||||
configRules = append(configRules, rules.MessageBirdClientID())
|
||||
configRules = append(configRules, rules.NewRelicUserID())
|
||||
configRules = append(configRules, rules.NewRelicUserKey())
|
||||
configRules = append(configRules, rules.NewRelicBrowserAPIKey())
|
||||
configRules = append(configRules, rules.NPM())
|
||||
configRules = append(configRules, rules.PlanetScalePassword())
|
||||
configRules = append(configRules, rules.PlanetScaleToken())
|
||||
configRules = append(configRules, rules.PostManAPI())
|
||||
configRules = append(configRules, rules.PrivateKey())
|
||||
configRules = append(configRules, rules.PulumiAPIToken())
|
||||
configRules = append(configRules, rules.PyPiUploadToken())
|
||||
configRules = append(configRules, rules.RubyGemsAPIToken())
|
||||
configRules = append(configRules, rules.SendGridAPIToken())
|
||||
configRules = append(configRules, rules.SendInBlueAPIToken())
|
||||
configRules = append(configRules, rules.ShippoAPIToken())
|
||||
configRules = append(configRules, rules.ShopifyAccessToken())
|
||||
configRules = append(configRules, rules.ShopifyCustomAccessToken())
|
||||
configRules = append(configRules, rules.ShopifyPrivateAppAccessToken())
|
||||
configRules = append(configRules, rules.ShopifySharedSecret())
|
||||
configRules = append(configRules, rules.SlackAccessToken())
|
||||
configRules = append(configRules, rules.SlackWebHook())
|
||||
configRules = append(configRules, rules.StripeAccessToken())
|
||||
configRules = append(configRules, rules.Twilio())
|
||||
configRules = append(configRules, rules.TwitchAPIToken())
|
||||
configRules = append(configRules, rules.Twitter())
|
||||
configRules = append(configRules, rules.Typeform())
|
||||
|
||||
config := config.Config{
|
||||
Rules: configRules,
|
||||
}
|
||||
tmpl, err := template.ParseFiles(templatePath)
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("Failed to parse template")
|
||||
}
|
||||
|
||||
f, err := os.Create("gitleaks.toml")
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("Failed to create rules.toml")
|
||||
}
|
||||
tmpl.Execute(f, config)
|
||||
|
||||
}
|
||||
|
||||
// TODO introduce skiplists:
|
||||
// https://github.com/danielmiessler/SecLists/blob/master/Miscellaneous/wordlist-skipfish.fuzz.txt
|
||||
@@ -0,0 +1,39 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func AdobeClientID() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Adobe Client ID (Oauth Web)",
|
||||
RuleID: "adobe-client-id",
|
||||
Regex: generateSemiGenericRegex([]string{"adobe"}, hex("32")),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{"adobe"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("adobe", secrets.NewSecret(hex("32"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func AdobeClientSecret() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Adobe Client Secret",
|
||||
RuleID: "adobe-client-secret",
|
||||
Regex: generateUniqueTokenRegex(`(p8e-)(?i)[a-z0-9]{32}`),
|
||||
Keywords: []string{"p8e-"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
"adobeClient := \"p8e-" + secrets.NewSecret(hex("32")) + "\"",
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func AgeSecretKey() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Age secret key",
|
||||
RuleID: "age secret key",
|
||||
Regex: regexp.MustCompile(`AGE-SECRET-KEY-1[QPZRY9X8GF2TVDW0S3JN54KHCE6MUA7L]{58}`),
|
||||
Keywords: []string{"AGE-SECRET-KEY-1"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
`apiKey := "AGE-SECRET-KEY-1QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ`, // gitleaks:allow
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func AlibabaAccessKey() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Alibaba AccessKey ID",
|
||||
RuleID: "alibaba-access-key-id",
|
||||
Regex: generateUniqueTokenRegex(`(LTAI)(?i)[a-z0-9]{20}`),
|
||||
Keywords: []string{"LTAI"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
"alibabaKey := \"LTAI" + secrets.NewSecret(hex("20")) + "\"",
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
// TODO
|
||||
func AlibabaSecretKey() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Alibaba Secret Key",
|
||||
RuleID: "alibaba-secret-key",
|
||||
Regex: generateSemiGenericRegex([]string{"alibaba"},
|
||||
alphaNumeric("30")),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{"alibaba"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("alibaba", secrets.NewSecret(alphaNumeric("30"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func AsanaClientID() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Asana Client ID",
|
||||
RuleID: "asana-client-id",
|
||||
Regex: generateSemiGenericRegex([]string{"asana"}, numeric("16")),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{"asana"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("asana", secrets.NewSecret(numeric("16"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func AsanaClientSecret() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Asana Client Secret",
|
||||
RuleID: "asana-client-secret",
|
||||
Regex: generateSemiGenericRegex([]string{"asana"}, alphaNumeric("32")),
|
||||
Keywords: []string{"asana"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("asana", secrets.NewSecret(alphaNumeric("32"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func Atlassian() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Atlassian API token",
|
||||
RuleID: "atlassian-api-token",
|
||||
Regex: generateSemiGenericRegex([]string{"atlassian", "confluence"}, alphaNumeric("24")),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{"atlassian", "confluence"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("atlassian", secrets.NewSecret(alphaNumeric("24"))),
|
||||
generateSampleSecret("confluence", secrets.NewSecret(alphaNumeric("24"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func AWS() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "AWS",
|
||||
RuleID: "aws-access-token",
|
||||
Regex: regexp.MustCompile(
|
||||
"(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}"),
|
||||
Keywords: []string{
|
||||
"AKIA",
|
||||
"AGPA",
|
||||
"AIDA",
|
||||
"AROA",
|
||||
"AIPA",
|
||||
"ANPA",
|
||||
"ANVA",
|
||||
"ASIA",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{generateSampleSecret("AWS", "AKIALALEMEL33243OLIB")} // gitleaks:allow
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func Beamer() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Beamer API token",
|
||||
RuleID: "beamer-api-token",
|
||||
SecretGroup: 1,
|
||||
Regex: generateSemiGenericRegex([]string{"beamer"},
|
||||
`b_[a-z0-9=_\-]{44}`),
|
||||
Keywords: []string{"beamer"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("beamer", "b_"+secrets.NewSecret(alphaNumericExtended("44"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func BitBucketClientID() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "BitBucket Client ID",
|
||||
RuleID: "bitbucket-client-id",
|
||||
Regex: generateSemiGenericRegex([]string{"bitbucket"}, alphaNumeric("32")),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{"bitbucket"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("bitbucket", secrets.NewSecret(alphaNumeric("32"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func BitBucketClientSecret() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "BitBucket Client Secret",
|
||||
RuleID: "bitbucket-client-secret",
|
||||
Regex: generateSemiGenericRegex([]string{"bitbucket"}, alphaNumericExtended("64")),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{"bitbucket"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("bitbucket", secrets.NewSecret(alphaNumeric("64"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func Clojars() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Clojars API token",
|
||||
RuleID: "clojars-api-token",
|
||||
Regex: regexp.MustCompile(`(?i)(CLOJARS_)[a-z0-9]{60}`),
|
||||
Keywords: []string{"clojars"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("clojars", "CLOJARS_"+secrets.NewSecret(alphaNumeric("60"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
# This is the default gitleaks configuration file.
|
||||
# Rules and allowlists are defined within this file.
|
||||
# Rules instruct gitleaks on what should be considered a secret.
|
||||
# Allowlists instruct gitleaks on what is allowed, i.e. not a secret.
|
||||
title = "gitleaks config"
|
||||
|
||||
[allowlist]
|
||||
description = "global allow lists"
|
||||
regexes = [
|
||||
'''219-09-9999''',
|
||||
'''078-05-1120''',
|
||||
'''(9[0-9]{2}|666)-\d{2}-\d{4}''',
|
||||
]
|
||||
paths = [
|
||||
'''gitleaks.toml''',
|
||||
'''(.*?)(jpg|gif|doc|pdf|bin|svg|socket)$''',
|
||||
'''(go.mod|go.sum)$'''
|
||||
]
|
||||
|
||||
{{ range $i, $rule := .Rules }}[[rules]]
|
||||
{{ if and $rule.SecretGroup $rule.Entropy }}description = "{{$rule.Description}}"
|
||||
id = "{{$rule.RuleID}}"
|
||||
regex = '''{{$rule.Regex}}'''
|
||||
secretGroup = {{ $rule.SecretGroup }}
|
||||
entropy = {{ $rule.Entropy}}
|
||||
keywords = [
|
||||
{{ range $j, $keyword := $rule.Keywords }}"{{$keyword}}",{{end}}
|
||||
]
|
||||
|
||||
{{ else if $rule.SecretGroup }}description = "{{$rule.Description}}"
|
||||
id = "{{$rule.RuleID}}"
|
||||
regex = '''{{$rule.Regex}}'''
|
||||
secretGroup = {{ $rule.SecretGroup }}
|
||||
keywords = [
|
||||
{{ range $j, $keyword := $rule.Keywords }}"{{$keyword}}",{{end}}
|
||||
]
|
||||
|
||||
{{ else }}description = "{{$rule.Description}}"
|
||||
id = "{{$rule.RuleID}}"
|
||||
regex = '''{{$rule.Regex}}'''
|
||||
keywords = [
|
||||
{{ range $j, $keyword := $rule.Keywords }}"{{$keyword}}",{{end}}
|
||||
]
|
||||
|
||||
{{end}}{{end}}
|
||||
@@ -0,0 +1,24 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func Contentful() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Contentful delivery API token",
|
||||
RuleID: "contentful-delivery-api-token",
|
||||
Regex: generateSemiGenericRegex([]string{"contentful"},
|
||||
alphaNumericExtended("43")),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{"contentful"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("contentful", secrets.NewSecret(alphaNumeric("43"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func Databricks() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Databricks API token",
|
||||
RuleID: "databricks-api-token",
|
||||
Regex: generateUniqueTokenRegex(`dapi[a-h0-9]{32}`),
|
||||
Keywords: []string{"dapi"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("databricks", "dapi"+secrets.NewSecret(hex("32"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func DiscordAPIToken() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Discord API key",
|
||||
RuleID: "discord-api-token",
|
||||
Regex: generateSemiGenericRegex([]string{"discord"}, hex("64")),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{"discord"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("discord", secrets.NewSecret(hex("64"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func DiscordClientID() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Discord client ID",
|
||||
RuleID: "discord-client-id",
|
||||
Regex: generateSemiGenericRegex([]string{"discord"}, numeric("18")),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{"discord"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("discord", secrets.NewSecret(numeric("18"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func DiscordClientSecret() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Discord client secret",
|
||||
RuleID: "discord-client-secret",
|
||||
Regex: generateSemiGenericRegex([]string{"discord"}, alphaNumericExtended("32")),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{"discord"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("discord", secrets.NewSecret(numeric("32"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func Doppler() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Doppler API token",
|
||||
RuleID: "doppler-api-token",
|
||||
Regex: regexp.MustCompile(`(dp\.pt\.)(?i)[a-z0-9]{43}`),
|
||||
Keywords: []string{"doppler"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("doppler", "dp.pt."+secrets.NewSecret(alphaNumeric("43"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
// TODO add additional doppler formats:
|
||||
// https://docs.doppler.com/reference/auth-token-formats
|
||||
@@ -0,0 +1,49 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func DropBoxAPISecret() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Dropbox API secret",
|
||||
RuleID: "doppler-api-token",
|
||||
Regex: generateSemiGenericRegex([]string{"dropbox"}, alphaNumeric("15")),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{"dropbox"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("dropbox", secrets.NewSecret(alphaNumeric("15"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func DropBoxShortLivedAPIToken() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "dropbox-short-lived-api-token",
|
||||
Description: "Dropbox short lived API token",
|
||||
Regex: generateSemiGenericRegex([]string{"dropbox"}, `sl\.[a-z0-9\-=_]{135}`),
|
||||
Keywords: []string{"dropbox"},
|
||||
}
|
||||
|
||||
// validate TODO
|
||||
return &r
|
||||
}
|
||||
|
||||
func DropBoxLongLivedAPIToken() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "dropbox-long-lived-api-token",
|
||||
Description: "Dropbox long lived API token",
|
||||
Regex: generateSemiGenericRegex([]string{"dropbox"}, `[a-z0-9]{11}(AAAAAAAAAA)[a-z0-9\-_=]{43}`),
|
||||
Keywords: []string{"dropbox"},
|
||||
}
|
||||
|
||||
// validate TODO
|
||||
return &r
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func Duffel() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "duffel-api-token",
|
||||
Description: "Duffel API token",
|
||||
Regex: regexp.MustCompile(`duffel_(test|live)_(?i)[a-z0-9_\-=]{43}`),
|
||||
Keywords: []string{"duffel"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("duffel", "duffel_test_"+secrets.NewSecret(alphaNumericExtended("43"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func Dynatrace() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Dynatrace API token",
|
||||
RuleID: "dynatrace-api-token",
|
||||
Regex: regexp.MustCompile(`dt0c01\.(?i)[a-z0-9]{24}\.[a-z0-9]{64}`),
|
||||
Keywords: []string{"dynatrace"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("dynatrace", "dt0c01."+secrets.NewSecret(alphaNumeric("24"))+"."+secrets.NewSecret(alphaNumeric("64"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func EasyPost() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "EasyPost API token",
|
||||
RuleID: "easypost-api-token",
|
||||
Regex: regexp.MustCompile(`EZAK(?i)[a-z0-9]{54}`),
|
||||
Keywords: []string{"EZAK"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("EZAK", "EZAK"+secrets.NewSecret(alphaNumeric("54"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func EasyPostTestAPI() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "EasyPost test API token",
|
||||
RuleID: "easypost-test-api-token",
|
||||
Regex: regexp.MustCompile(`EZTK(?i)[a-z0-9]{54}`),
|
||||
Keywords: []string{"EZTK"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("EZTK", "EZTK"+secrets.NewSecret(alphaNumeric("54"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func Facebook() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "facebook",
|
||||
RuleID: "facebook",
|
||||
Regex: generateSemiGenericRegex([]string{"facebook"}, hex("32")),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{"facebook"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("facebook", secrets.NewSecret(hex("32"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func FastlyAPIToken() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Fastly API key",
|
||||
RuleID: "fastly-api-token",
|
||||
Regex: generateSemiGenericRegex([]string{"fastly"}, alphaNumericExtended("32")),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{"fastly"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("fastly", secrets.NewSecret(alphaNumericExtended("32"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func FinicityClientSecret() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Finicity Client Secret",
|
||||
RuleID: "finicity-client-secret",
|
||||
Regex: generateSemiGenericRegex([]string{"finicity"}, alphaNumeric("20")),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{"finicity"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("finicity", secrets.NewSecret(alphaNumeric("20"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func FinicityAPIToken() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Finicity API token",
|
||||
RuleID: "finicity-api-token",
|
||||
Regex: generateSemiGenericRegex([]string{"finicity"}, hex("32")),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{"finicity"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("finicity", secrets.NewSecret(hex("32"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func FlutterwavePublicKey() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Finicity Public Key",
|
||||
RuleID: "flutterwave-public-key",
|
||||
Regex: regexp.MustCompile(`FLWPUBK_TEST-(?i)[a-h0-9]{32}-X`),
|
||||
Keywords: []string{"FLWPUBK_TEST"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("flutterwavePubKey", "FLWPUBK_TEST-"+secrets.NewSecret(hex("32"))+"-X"),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func FlutterwaveSecretKey() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Finicity Secret Key",
|
||||
RuleID: "flutterwave-public-key",
|
||||
Regex: regexp.MustCompile(`FLWSECK_TEST-(?i)[a-h0-9]{32}-X`),
|
||||
Keywords: []string{"FLWSECK_TEST"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("flutterwavePubKey", "FLWSECK_TEST-"+secrets.NewSecret(hex("32"))+"-X"),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func FlutterwaveEncKey() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Finicity Secret Key",
|
||||
RuleID: "flutterwave-public-key",
|
||||
Regex: regexp.MustCompile(`FLWSECK_TEST-(?i)[a-h0-9]{12}`),
|
||||
Keywords: []string{"FLWSECK_TEST"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("flutterwavePubKey", "FLWSECK_TEST-"+secrets.NewSecret(hex("12"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func FrameIO() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Frame.io API token",
|
||||
RuleID: "frameio-api-token",
|
||||
Regex: regexp.MustCompile(`fio-u-(?i)[a-z0-9\-_=]{64}`),
|
||||
Keywords: []string{"fio-u-"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("frameio", "fio-u-"+secrets.NewSecret(alphaNumericExtended("64"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
// TODO this one could probably use some work
|
||||
func GCPServiceAccount() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Google (GCP) Service-account",
|
||||
RuleID: "gcp-service-account",
|
||||
Regex: regexp.MustCompile(`\"type\": \"service_account\"`),
|
||||
Keywords: []string{`\"type\": \"service_account\"`},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
`"type": "service_account"`,
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func GenericCredential() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "generic-api-key",
|
||||
Description: "Generic API Key",
|
||||
Regex: generateSemiGenericRegex([]string{
|
||||
"key",
|
||||
"api[^Version]",
|
||||
"token",
|
||||
"pat",
|
||||
"secret",
|
||||
"client",
|
||||
"password",
|
||||
"auth",
|
||||
}, `[0-9a-z\-_.=]{10,150}`),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{
|
||||
"key",
|
||||
"api",
|
||||
"token",
|
||||
"secret",
|
||||
"client",
|
||||
"pat",
|
||||
"password",
|
||||
"auth",
|
||||
},
|
||||
Entropy: 3.7,
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("generic", "CLOJARS_34bf0e88955ff5a1c328d6a7491acc4f48e865a7b8dd4d70a70749037443"),
|
||||
generateSampleSecret("generic", "Zf3D0LXCM3EIMbgJpUNnkRtOfOueHznB"),
|
||||
`"client_id" : "0afae57f3ccfd9d7f5767067bc48b30f719e271ba470488056e37ab35d4b6506"`,
|
||||
`"client_secret" : "6da89121079f83b2eb6acccf8219ea982c3d79bccc3e9c6a85856480661f8fde",`,
|
||||
// TODO add more
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func GitHubPat() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "GitHub Personal Access Token",
|
||||
RuleID: "github-pat",
|
||||
Regex: regexp.MustCompile(`ghp_[0-9a-zA-Z]{36}`),
|
||||
Keywords: []string{"ghp_"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("github", "ghp_"+secrets.NewSecret(alphaNumeric("36"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func GitHubOauth() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "GitHub OAuth Access Token",
|
||||
RuleID: "github-oauth",
|
||||
Regex: regexp.MustCompile(`gho_[0-9a-zA-Z]{36}`),
|
||||
Keywords: []string{"gho_"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("github", "gho_"+secrets.NewSecret(alphaNumeric("36"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func GitHubApp() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "GitHub App Token",
|
||||
RuleID: "github-app-token",
|
||||
Regex: regexp.MustCompile(`(ghu|ghs)_[0-9a-zA-Z]{36}`),
|
||||
Keywords: []string{"ghu_", "ghs_"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("github", "ghu_"+secrets.NewSecret(alphaNumeric("36"))),
|
||||
generateSampleSecret("github", "ghs_"+secrets.NewSecret(alphaNumeric("36"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func GitHubRefresh() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "GitHub Refresh Token",
|
||||
RuleID: "github-refresh-token",
|
||||
Regex: regexp.MustCompile(`ghr_[0-9a-zA-Z]{36}`),
|
||||
Keywords: []string{"ghr_"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("github", "ghr_"+secrets.NewSecret(alphaNumeric("36"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func Gitlab() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Gitlab Personal Access Token",
|
||||
RuleID: "gitlab-pat",
|
||||
Regex: regexp.MustCompile(`glpat-[0-9a-zA-Z\-\_]{20}`),
|
||||
Keywords: []string{"glpat-"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("gitlab", "glpat-"+secrets.NewSecret(alphaNumeric("20"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func GoCardless() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "gocardless-api-token",
|
||||
Description: "GoCardless API token",
|
||||
Regex: generateSemiGenericRegex([]string{"gocardless"}, `live_(?i)[a-z0-9\-_=]{40}`),
|
||||
Keywords: []string{
|
||||
"live_",
|
||||
"gocardless",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("gocardless", "live_"+secrets.NewSecret(alphaNumericExtended("40"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func Hashicorp() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "HashiCorp Terraform user/org API token",
|
||||
RuleID: "hashicorp-tf-api-token",
|
||||
Regex: regexp.MustCompile(`(?i)[a-z0-9]{14}\.atlasv1\.[a-z0-9\-_=]{60,70}`),
|
||||
Keywords: []string{"atlasv1"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("hashicorpToken", secrets.NewSecret(hex("14"))+".atlasv1."+secrets.NewSecret(alphaNumericExtended("60,70"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func Heroku() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Heroku API Key",
|
||||
RuleID: "heroku-api-key",
|
||||
Regex: generateSemiGenericRegex([]string{"heroku"},
|
||||
`[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}`),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{"heroku"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
`const HEROKU_KEY = "12345678-ABCD-ABCD-ABCD-1234567890AB"`, // gitleaks:allow
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func HubSpot() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "HubSpot API Token",
|
||||
RuleID: "hubspot-api-key",
|
||||
Regex: generateSemiGenericRegex([]string{"hubspot"},
|
||||
`[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}`),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{"hubspot"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
`const hubspotKey = "12345678-ABCD-ABCD-ABCD-1234567890AB"`, // gitleaks:allow
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func Intercom() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Intercom API Token",
|
||||
RuleID: "intercom-api-key",
|
||||
Regex: generateSemiGenericRegex([]string{"intercom"}, alphaNumericExtended("60")),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{"intercom"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("intercom", secrets.NewSecret(alphaNumericExtended("60"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func LinearAPIToken() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Linear API Token",
|
||||
RuleID: "linear-api-key",
|
||||
Regex: regexp.MustCompile(`lin_api_(?i)[a-z0-9]{40}`),
|
||||
Keywords: []string{"lin_api_"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("linear", "lin_api_"+secrets.NewSecret(alphaNumeric("40"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func LinearClientSecret() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Linear Client Secret",
|
||||
RuleID: "linear-client-secret",
|
||||
Regex: generateSemiGenericRegex([]string{"linear"}, hex("32")),
|
||||
Keywords: []string{"linear"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("linear", secrets.NewSecret(hex("32"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func LinkedinClientSecret() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "linkedin-client-secret",
|
||||
Description: "LinkedIn Client secret",
|
||||
Regex: generateSemiGenericRegex([]string{
|
||||
"linkedin",
|
||||
"linked-in",
|
||||
}, alphaNumeric("16")),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{
|
||||
"linkedin",
|
||||
"linked-in",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("linkedin", secrets.NewSecret(alphaNumeric("16"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func LinkedinClientID() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "linkedin-client-id",
|
||||
Description: "LinkedIn Client ID",
|
||||
Regex: generateSemiGenericRegex([]string{
|
||||
"linkedin",
|
||||
"linked-in",
|
||||
}, alphaNumeric("14")),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{
|
||||
"linkedin",
|
||||
"linked-in",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("linkedin", secrets.NewSecret(alphaNumeric("14"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func LobPubAPIToken() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Lob Publishable API Key",
|
||||
RuleID: "lob-pub-api-key",
|
||||
Regex: generateSemiGenericRegex([]string{"lob"}, `(test|live)_pub_[a-f0-9]{31}`),
|
||||
Keywords: []string{
|
||||
"test_pub",
|
||||
"live_pub",
|
||||
"_pub",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("lob", "test_pub_"+secrets.NewSecret(hex("31"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func LobAPIToken() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Lob API Key",
|
||||
RuleID: "lob-api-key",
|
||||
Regex: generateSemiGenericRegex([]string{"lob"}, `(live|test)_[a-f0-9]{35}`),
|
||||
Keywords: []string{
|
||||
"test_",
|
||||
"live_",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("lob", "test_"+secrets.NewSecret(hex("35"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func MailChimp() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "mailchimp-api-key",
|
||||
Description: "Mailchimp API key",
|
||||
Regex: generateSemiGenericRegex([]string{"mailchimp"}, `[a-f0-9]{32}-us20`),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{
|
||||
"mailchimp",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("mailchimp", secrets.NewSecret(hex("32"))+"-us20"),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func MailGunPrivateAPIToken() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "mailgun-private-api-token",
|
||||
Description: "Mailgun private API token",
|
||||
Regex: generateSemiGenericRegex([]string{"mailgun"}, `key-[a-f0-9]{32}`),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{
|
||||
"mailgun",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("mailgun", "key-"+secrets.NewSecret(hex("32"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func MailGunPubAPIToken() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "mailgun-pub-key",
|
||||
Description: "Mailgun public validation key",
|
||||
Regex: generateSemiGenericRegex([]string{"mailgun"}, `pubkey-[a-f0-9]{32}`),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{
|
||||
"mailgun",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("mailgun", "pubkey-"+secrets.NewSecret(hex("32"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func MailGunSigningKey() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "mailgun-signing-key",
|
||||
Description: "Mailgun webhook signing key",
|
||||
Regex: generateSemiGenericRegex([]string{"mailgun"}, `[a-h0-9]{32}-[a-h0-9]{8}-[a-h0-9]{8}`),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{
|
||||
"mailgun",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("mailgun", secrets.NewSecret(hex("32"))+"-00001111-22223333"),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func MapBox() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "MapBox API token",
|
||||
RuleID: "mapbox-api-token",
|
||||
Regex: generateSemiGenericRegex([]string{"mapbox"}, `pk\.[a-z0-9]{60}\.[a-z0-9]{22}`),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{"mapbox"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("mapbox", "pk."+secrets.NewSecret(alphaNumeric("60"))+"."+secrets.NewSecret(alphaNumeric("22"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func MessageBirdAPIToken() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "MessageBird API token",
|
||||
RuleID: "messagebird-api-token",
|
||||
Regex: generateSemiGenericRegex([]string{
|
||||
"messagebird",
|
||||
"message-bird",
|
||||
"message_bird",
|
||||
}, alphaNumeric("25")),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{
|
||||
"messagebird",
|
||||
"message-bird",
|
||||
"message_bird",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("messagebird", secrets.NewSecret(alphaNumeric("25"))),
|
||||
generateSampleSecret("message-bird", secrets.NewSecret(alphaNumeric("25"))),
|
||||
generateSampleSecret("message_bird", secrets.NewSecret(alphaNumeric("25"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func MessageBirdClientID() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "MessageBird client ID",
|
||||
RuleID: "messagebird-client-id",
|
||||
Regex: generateSemiGenericRegex([]string{
|
||||
"messagebird",
|
||||
"message-bird",
|
||||
"message_bird",
|
||||
}, `[a-h0-9]{8}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{12}`),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{
|
||||
"messagebird",
|
||||
"message-bird",
|
||||
"message_bird",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
`const MessageBirdClientID = "12345678-ABCD-ABCD-ABCD-1234567890AB"`, // gitleaks:allow
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func NewRelicUserID() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "new-relic-user-api-key",
|
||||
Description: "New Relic user API Key",
|
||||
Regex: generateSemiGenericRegex([]string{
|
||||
"new-relic",
|
||||
"newrelic",
|
||||
"new_relic",
|
||||
}, `NRAK-[a-z0-9]{27}`),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{
|
||||
"NRAK",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("new-relic", "NRAK-"+secrets.NewSecret(alphaNumeric("27"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func NewRelicUserKey() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "new-relic-user-api-id",
|
||||
Description: "New Relic user API ID",
|
||||
Regex: generateSemiGenericRegex([]string{
|
||||
"new-relic",
|
||||
"newrelic",
|
||||
"new_relic",
|
||||
}, alphaNumeric("64")),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{
|
||||
"new-relic",
|
||||
"newrelic",
|
||||
"new_relic",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("new-relic", secrets.NewSecret(alphaNumeric("64"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func NewRelicBrowserAPIKey() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "new-relic-browser-api-token",
|
||||
Description: "New Relic ingest browser API token",
|
||||
Regex: generateSemiGenericRegex([]string{
|
||||
"new-relic",
|
||||
"newrelic",
|
||||
"new_relic",
|
||||
}, `NRJS-[a-f0-9]{19}`),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{
|
||||
"NRJS-",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("new-relic", "NRJS-"+secrets.NewSecret(hex("19"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func NPM() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "npm-access-token",
|
||||
Description: "npm access token",
|
||||
Regex: generateUniqueTokenRegex(`npm_[a-z0-9]{36}`),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{
|
||||
"npm_",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("npmAccessToken", "npm_"+secrets.NewSecret(alphaNumeric("36"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func PlanetScalePassword() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "planetscale-password",
|
||||
Description: "PlanetScale password",
|
||||
Regex: generateUniqueTokenRegex(`pscale_pw_(?i)[a-z0-9=\-_\.]{43}`),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{
|
||||
"pscale_pw_",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("planetScalePassword", "pscale_pw_"+secrets.NewSecret(alphaNumericExtended("43"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func PlanetScaleToken() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "planetscale-api-token",
|
||||
Description: "PlanetScale API token",
|
||||
Regex: generateUniqueTokenRegex(`pscale_tkn_(?i)[a-z0-9=\-_\.]{43}`),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{
|
||||
"pscale_tkn_",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("planetScalePassword", "pscale_tkn_"+secrets.NewSecret(alphaNumericExtended("43"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func PostManAPI() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "postman-api-token",
|
||||
Description: "Postman API token",
|
||||
Regex: generateUniqueTokenRegex(`PMAK-(?i)[a-f0-9]{24}\-[a-f0-9]{34}`),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{
|
||||
"PMAK-",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("postmanAPItoken", "PMAK-"+secrets.NewSecret(hex("24"))+"-"+secrets.NewSecret(hex("34"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func PrivateKey() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Private Key",
|
||||
RuleID: "private-key",
|
||||
Regex: regexp.MustCompile(`(?i)-----BEGIN[ A-Z0-9_-]{0,100}PRIVATE KEY-----[\s\S-]*KEY----`),
|
||||
Keywords: []string{"-----BEGIN PRIVATE"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{`-----BEGIN PRIVATE KEY-----
|
||||
anything
|
||||
-----END PRIVATE KEY-----`} // gitleaks:allow
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func PulumiAPIToken() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "pulumi-api-token",
|
||||
Description: "Pulumi API token",
|
||||
Regex: generateUniqueTokenRegex(`pul-[a-f0-9]{40}`),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{
|
||||
"pul-",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("pulumi-api-token", "pul-"+secrets.NewSecret(hex("40"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func PyPiUploadToken() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "PyPI upload token",
|
||||
RuleID: "pypi-upload-token",
|
||||
Regex: regexp.MustCompile(
|
||||
`pypi-AgEIcHlwaS5vcmc[A-Za-z0-9\-_]{50,1000}`),
|
||||
Keywords: []string{
|
||||
"pypi-AgEIcHlwaS5vcmc",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{"pypiToken := \"pypi-AgEIcHlwaS5vcmc" + secrets.NewSecret(hex("32")) +
|
||||
secrets.NewSecret(hex("32")) + "\""}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func RubyGemsAPIToken() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "rubygems-api-token",
|
||||
Description: "Rubygem API token",
|
||||
Regex: generateUniqueTokenRegex(`rubygems_[a-f0-9]{48}`),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{
|
||||
"rubygems_",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("rubygemsAPIToken", "rubygems_"+secrets.NewSecret(hex("48"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/detect"
|
||||
)
|
||||
|
||||
const (
|
||||
// case insensitive prefix
|
||||
caseInsensitive = `(?i)`
|
||||
|
||||
// identifier prefix (just an ignore group)
|
||||
identifierPrefix = `(?:`
|
||||
identifierSuffix = `)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}`
|
||||
|
||||
// commonly used assignment operators or function call
|
||||
operator = `(?:=|>|:=|\|\|:|<=|=>|:)`
|
||||
|
||||
// boundaries for the secret
|
||||
// \x60 = `
|
||||
secretPrefixUnique = `\b(`
|
||||
secretPrefix = `(?:'|\"|\s|=|\x60){0,5}(`
|
||||
secretSuffix = `)(?:['|\"|\n|\r|\s|\x60]|$)`
|
||||
)
|
||||
|
||||
func generateSemiGenericRegex(identifiers []string, secretRegex string) *regexp.Regexp {
|
||||
var sb strings.Builder
|
||||
sb.WriteString(caseInsensitive)
|
||||
sb.WriteString(identifierPrefix)
|
||||
sb.WriteString(strings.Join(identifiers, "|"))
|
||||
sb.WriteString(identifierSuffix)
|
||||
sb.WriteString(operator)
|
||||
sb.WriteString(secretPrefix)
|
||||
sb.WriteString(secretRegex)
|
||||
sb.WriteString(secretSuffix)
|
||||
return regexp.MustCompile(sb.String())
|
||||
}
|
||||
|
||||
func generateUniqueTokenRegex(secretRegex string) *regexp.Regexp {
|
||||
var sb strings.Builder
|
||||
sb.WriteString(caseInsensitive)
|
||||
sb.WriteString(secretPrefixUnique)
|
||||
sb.WriteString(secretRegex)
|
||||
sb.WriteString(secretSuffix)
|
||||
return regexp.MustCompile(sb.String())
|
||||
}
|
||||
|
||||
func generateSampleSecret(identifier string, secret string) string {
|
||||
return fmt.Sprintf("%s_api_token = \"%s\"", identifier, secret)
|
||||
}
|
||||
|
||||
func validate(r config.Rule, truePositives []string) *config.Rule {
|
||||
// normalize keywords like in the config package
|
||||
var keywords []string
|
||||
for _, k := range r.Keywords {
|
||||
keywords = append(keywords, strings.ToLower(k))
|
||||
}
|
||||
r.Keywords = keywords
|
||||
|
||||
d := detect.NewDetector(config.Config{
|
||||
Rules: []*config.Rule{&r},
|
||||
Keywords: keywords,
|
||||
})
|
||||
for _, tp := range truePositives {
|
||||
if len(d.DetectString(tp)) != 1 {
|
||||
log.Fatal().Msgf("Failed to validate %s", r.RuleID)
|
||||
}
|
||||
}
|
||||
return &r
|
||||
}
|
||||
|
||||
func numeric(size string) string {
|
||||
return fmt.Sprintf(`[0-9]{%s}`, size)
|
||||
}
|
||||
|
||||
func hex(size string) string {
|
||||
return fmt.Sprintf(`[a-f0-9]{%s}`, size)
|
||||
}
|
||||
|
||||
func alphaNumeric(size string) string {
|
||||
return fmt.Sprintf(`[a-z0-9]{%s}`, size)
|
||||
}
|
||||
|
||||
func alphaNumericExtended(size string) string {
|
||||
return fmt.Sprintf(`[a-z0-9=_\-]{%s}`, size)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func SendGridAPIToken() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "sendgrid-api-token",
|
||||
Description: "SendGrid API token",
|
||||
Regex: generateUniqueTokenRegex(`SG\.(?i)[a-z0-9=_\-\.]{66}`),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{
|
||||
"SG.",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("sengridAPIToken", "SG."+secrets.NewSecret(alphaNumericExtended("66"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func SendInBlueAPIToken() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "sendinblue-api-token",
|
||||
Description: "Sendinblue API token",
|
||||
Regex: generateUniqueTokenRegex(`xkeysib-[a-f0-9]{64}\-(?i)[a-z0-9]{16}`),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{
|
||||
"xkeysib-",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("sendinblue", "xkeysib-"+secrets.NewSecret(hex("64"))+"-"+secrets.NewSecret(alphaNumeric("16"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func ShippoAPIToken() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "shippo-api-token",
|
||||
Description: "Shippo API token",
|
||||
Regex: generateUniqueTokenRegex(`shippo_(live|test)_[a-f0-9]{40}`),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{
|
||||
"shippo_",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("shippo", "shippo_live_"+secrets.NewSecret(hex("40"))),
|
||||
generateSampleSecret("shippo", "shippo_test_"+secrets.NewSecret(hex("40"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func ShopifySharedSecret() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Shopify shared secret",
|
||||
RuleID: "shopify-shared-secret",
|
||||
Regex: regexp.MustCompile(`shpss_[a-fA-F0-9]{32}`),
|
||||
Keywords: []string{"shpss_"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{"shopifySecret := \"shpss_" + secrets.NewSecret(hex("32")) + "\""}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func ShopifyAccessToken() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Shopify access token",
|
||||
RuleID: "shopify-access-token",
|
||||
Regex: regexp.MustCompile(`shpat_[a-fA-F0-9]{32}`),
|
||||
Keywords: []string{"shpat_"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{"shopifyToken := \"shpat_" + secrets.NewSecret(hex("32")) + "\""}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func ShopifyCustomAccessToken() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Shopify custom access token",
|
||||
RuleID: "shopify-custom-access-token",
|
||||
Regex: regexp.MustCompile(`shpca_[a-fA-F0-9]{32}`),
|
||||
Keywords: []string{"shpca_"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{"shopifyToken := \"shpca_" + secrets.NewSecret(hex("32")) + "\""}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func ShopifyPrivateAppAccessToken() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Shopify private app access token",
|
||||
RuleID: "shopify-private-app-access-token",
|
||||
Regex: regexp.MustCompile(`shppa_[a-fA-F0-9]{32}`),
|
||||
Keywords: []string{"shppa_"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{"shopifyToken := \"shppa_" + secrets.NewSecret(hex("32")) + "\""}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func SlackAccessToken() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Slack token",
|
||||
RuleID: "slack-access-token",
|
||||
Regex: regexp.MustCompile(
|
||||
"xox[baprs]-([0-9a-zA-Z]{10,48})"),
|
||||
Keywords: []string{
|
||||
"xoxb",
|
||||
"xoxa",
|
||||
"xoxp",
|
||||
"xoxr",
|
||||
"xoxs",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
"\"slackToken\": \"xoxb-" + secrets.NewSecret(alphaNumeric("30")) + "\"",
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
|
||||
func SlackWebHook() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Slack Webhook",
|
||||
RuleID: "slack-web-hook",
|
||||
Regex: regexp.MustCompile(
|
||||
`https:\/\/hooks.slack.com\/services\/[A-Za-z0-9+\/]{44,46}`),
|
||||
Keywords: []string{
|
||||
"hooks.slack.com",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
"https://hooks.slack.com/services/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // gitleaks:allow
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func StripeAccessToken() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Stripe",
|
||||
RuleID: "stripe-access-token",
|
||||
Regex: regexp.MustCompile(`(?i)(sk|pk)_(test|live)_[0-9a-z]{10,32}`),
|
||||
Keywords: []string{
|
||||
"sk_test",
|
||||
"pk_test",
|
||||
"sk_live",
|
||||
"pk_live",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{"stripeToken := \"sk_test_" + secrets.NewSecret(alphaNumeric("30")) + "\""}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func Twilio() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "Twilio API Key",
|
||||
RuleID: "twilio-api-key",
|
||||
Regex: regexp.MustCompile(`SK[0-9a-fA-F]{32}`),
|
||||
Keywords: []string{"twilio"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
"twilioAPIKey := \"SK" + secrets.NewSecret(hex("32")) + "\"",
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func TwitchAPIToken() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "twitch-api-token",
|
||||
Description: "Twitch API token",
|
||||
Regex: generateSemiGenericRegex([]string{"twitch"}, alphaNumeric("30")),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{
|
||||
"twitch",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("twitch", secrets.NewSecret(alphaNumeric("30"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func Twitter() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
Description: "twitter",
|
||||
RuleID: "twitter",
|
||||
Regex: generateSemiGenericRegex([]string{"twitter"}, hex("35,44")),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{"twitter"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
"twitterToken := \"" + secrets.NewSecret(hex("36")) + "aaaa\"",
|
||||
"twitterToken := `" + secrets.NewSecret(hex("36")) + "aaaa`",
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func Typeform() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "typeform-api-token",
|
||||
Description: "Typeform API token",
|
||||
Regex: generateSemiGenericRegex([]string{"typeform"},
|
||||
`tfp_[a-z0-9\-_\.=]{59}`),
|
||||
SecretGroup: 1,
|
||||
Keywords: []string{
|
||||
"tfp_",
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
generateSampleSecret("typeformAPIToken", "tfp_"+secrets.NewSecret(alphaNumericExtended("59"))),
|
||||
}
|
||||
return validate(r, tps)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// Package reggen generates text based on regex definitions
|
||||
// This is a slightly altered version of https://github.com/lucasjones/reggen
|
||||
package secrets
|
||||
|
||||
import (
|
||||
"github.com/lucasjones/reggen"
|
||||
)
|
||||
|
||||
func NewSecret(regex string) string {
|
||||
g, err := reggen.NewGenerator(regex)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return g.Generate(1)
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/detect"
|
||||
"github.com/zricethezav/gitleaks/v8/report"
|
||||
)
|
||||
|
||||
func init() {
|
||||
protectCmd.Flags().Bool("staged", false, "detect secrets in a --staged state")
|
||||
rootCmd.AddCommand(protectCmd)
|
||||
}
|
||||
|
||||
var protectCmd = &cobra.Command{
|
||||
Use: "protect",
|
||||
Short: "protect secrets in code",
|
||||
Run: runProtect,
|
||||
}
|
||||
|
||||
func runProtect(cmd *cobra.Command, args []string) {
|
||||
initConfig()
|
||||
var vc config.ViperConfig
|
||||
|
||||
if err := viper.Unmarshal(&vc); err != nil {
|
||||
log.Fatal().Err(err).Msg("Failed to load config")
|
||||
}
|
||||
cfg, err := vc.Translate()
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("Failed to load config")
|
||||
}
|
||||
|
||||
cfg.Path, _ = cmd.Flags().GetString("config")
|
||||
exitCode, _ := cmd.Flags().GetInt("exit-code")
|
||||
staged, _ := cmd.Flags().GetBool("staged")
|
||||
start := time.Now()
|
||||
|
||||
// Setup detector
|
||||
detector := detect.NewDetector(cfg)
|
||||
detector.Config.Path, err = cmd.Flags().GetString("config")
|
||||
if err != nil {
|
||||
log.Fatal().Err(err)
|
||||
}
|
||||
source, err := cmd.Flags().GetString("source")
|
||||
if err != nil {
|
||||
log.Fatal().Err(err)
|
||||
}
|
||||
// if config path is not set, then use the {source}/.gitleaks.toml path.
|
||||
// note that there may not be a `{source}/.gitleaks.toml` file, this is ok.
|
||||
if detector.Config.Path == "" {
|
||||
detector.Config.Path = filepath.Join(source, ".gitleaks.toml")
|
||||
}
|
||||
// set verbose flag
|
||||
if detector.Verbose, err = cmd.Flags().GetBool("verbose"); err != nil {
|
||||
log.Fatal().Err(err)
|
||||
}
|
||||
// set redact flag
|
||||
if detector.Redact, err = cmd.Flags().GetBool("redact"); err != nil {
|
||||
log.Fatal().Err(err)
|
||||
}
|
||||
|
||||
// get log options for git scan
|
||||
logOpts, err := cmd.Flags().GetString("log-opts")
|
||||
if err != nil {
|
||||
log.Fatal().Err(err)
|
||||
}
|
||||
|
||||
// start git scan
|
||||
var findings []report.Finding
|
||||
if staged {
|
||||
findings, err = detector.DetectGit(source, logOpts, detect.ProtectStagedType)
|
||||
} else {
|
||||
findings, err = detector.DetectGit(source, logOpts, detect.ProtectType)
|
||||
}
|
||||
if err != nil {
|
||||
// don't exit on error, just log it
|
||||
log.Error().Err(err)
|
||||
}
|
||||
|
||||
// log info about the scan
|
||||
log.Info().Msgf("scan completed in %s", time.Since(start))
|
||||
if len(findings) != 0 {
|
||||
log.Warn().Msgf("leaks found: %d", len(findings))
|
||||
} else {
|
||||
log.Info().Msg("no leaks found")
|
||||
}
|
||||
|
||||
reportPath, _ := cmd.Flags().GetString("report-path")
|
||||
ext, _ := cmd.Flags().GetString("report-format")
|
||||
if reportPath != "" {
|
||||
if err = report.Write(findings, cfg, ext, reportPath); err != nil {
|
||||
log.Fatal().Err(err)
|
||||
}
|
||||
}
|
||||
if len(findings) != 0 {
|
||||
os.Exit(exitCode)
|
||||
}
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
const banner = `
|
||||
○
|
||||
│╲
|
||||
│ ○
|
||||
○ ░
|
||||
░ gitleaks
|
||||
|
||||
`
|
||||
|
||||
const configDescription = `config file path
|
||||
order of precedence:
|
||||
1. --config/-c
|
||||
2. env var GITLEAKS_CONFIG
|
||||
3. (--source/-s)/.gitleaks.toml
|
||||
If none of the three options are used, then gitleaks will use the default config`
|
||||
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "gitleaks",
|
||||
Short: "Gitleaks scans code, past or present, for secrets",
|
||||
}
|
||||
|
||||
func init() {
|
||||
cobra.OnInitialize(initLog)
|
||||
rootCmd.PersistentFlags().StringP("config", "c", "", configDescription)
|
||||
rootCmd.PersistentFlags().Int("exit-code", 1, "exit code when leaks have been encountered")
|
||||
rootCmd.PersistentFlags().StringP("source", "s", ".", "path to source (default: $PWD)")
|
||||
rootCmd.PersistentFlags().StringP("report-path", "r", "", "report file")
|
||||
rootCmd.PersistentFlags().StringP("report-format", "f", "json", "output format (json, csv, sarif)")
|
||||
rootCmd.PersistentFlags().StringP("log-level", "l", "info", "log level (debug, info, warn, error, fatal)")
|
||||
rootCmd.PersistentFlags().BoolP("verbose", "v", false, "show verbose output from scan")
|
||||
rootCmd.PersistentFlags().Bool("redact", false, "redact secrets from logs and stdout")
|
||||
err := viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config"))
|
||||
if err != nil {
|
||||
log.Fatal().Msgf("err binding config %s", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func initLog() {
|
||||
zerolog.SetGlobalLevel(zerolog.InfoLevel)
|
||||
ll, err := rootCmd.Flags().GetString("log-level")
|
||||
if err != nil {
|
||||
log.Fatal().Msg(err.Error())
|
||||
}
|
||||
switch strings.ToLower(ll) {
|
||||
case "debug":
|
||||
zerolog.SetGlobalLevel(zerolog.DebugLevel)
|
||||
case "info":
|
||||
zerolog.SetGlobalLevel(zerolog.InfoLevel)
|
||||
case "warn":
|
||||
zerolog.SetGlobalLevel(zerolog.WarnLevel)
|
||||
case "err", "error":
|
||||
zerolog.SetGlobalLevel(zerolog.ErrorLevel)
|
||||
case "fatal":
|
||||
zerolog.SetGlobalLevel(zerolog.FatalLevel)
|
||||
default:
|
||||
zerolog.SetGlobalLevel(zerolog.InfoLevel)
|
||||
}
|
||||
}
|
||||
|
||||
func initConfig() {
|
||||
fmt.Fprint(os.Stderr, banner)
|
||||
cfgPath, err := rootCmd.Flags().GetString("config")
|
||||
if err != nil {
|
||||
log.Fatal().Msg(err.Error())
|
||||
}
|
||||
if cfgPath != "" {
|
||||
viper.SetConfigFile(cfgPath)
|
||||
log.Debug().Msgf("Using gitleaks config %s from `--config`", cfgPath)
|
||||
} else if os.Getenv("GITLEAKS_CONFIG") != "" {
|
||||
envPath := os.Getenv("GITLEAKS_CONFIG")
|
||||
viper.SetConfigFile(envPath)
|
||||
log.Debug().Msgf("Using gitleaks config from GITLEAKS_CONFIG env var: %s", envPath)
|
||||
} else {
|
||||
source, err := rootCmd.Flags().GetString("source")
|
||||
if err != nil {
|
||||
log.Fatal().Msg(err.Error())
|
||||
}
|
||||
fileInfo, err := os.Stat(source)
|
||||
if err != nil {
|
||||
log.Fatal().Msg(err.Error())
|
||||
}
|
||||
|
||||
if !fileInfo.IsDir() {
|
||||
log.Debug().Msgf("Unable to load gitleaks config from %s since --source=%s is a file, using default config",
|
||||
filepath.Join(source, ".gitleaks.toml"), source)
|
||||
viper.SetConfigType("toml")
|
||||
if err = viper.ReadConfig(strings.NewReader(config.DefaultConfig)); err != nil {
|
||||
log.Fatal().Msgf("err reading toml %s", err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := os.Stat(filepath.Join(source, ".gitleaks.toml")); os.IsNotExist(err) {
|
||||
log.Debug().Msgf("No gitleaks config found in path %s, using default gitleaks config", filepath.Join(source, ".gitleaks.toml"))
|
||||
viper.SetConfigType("toml")
|
||||
if err = viper.ReadConfig(strings.NewReader(config.DefaultConfig)); err != nil {
|
||||
log.Fatal().Msgf("err reading default config toml %s", err.Error())
|
||||
}
|
||||
return
|
||||
} else {
|
||||
log.Debug().Msgf("Using existing gitleaks config %s from `(--source)/.gitleaks.toml`", filepath.Join(source, ".gitleaks.toml"))
|
||||
}
|
||||
|
||||
viper.AddConfigPath(source)
|
||||
viper.SetConfigName(".gitleaks")
|
||||
viper.SetConfigType("toml")
|
||||
}
|
||||
if err := viper.ReadInConfig(); err != nil {
|
||||
log.Fatal().Msgf("Unable to load gitleaks config, err: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
func Execute() {
|
||||
if err := rootCmd.Execute(); err != nil {
|
||||
if strings.Contains(err.Error(), "unknown flag") {
|
||||
// exit code 126: Command invoked cannot execute
|
||||
os.Exit(126)
|
||||
}
|
||||
log.Fatal().Msg(err.Error())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var Version = "version is set by build process"
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(versionCmd)
|
||||
}
|
||||
|
||||
var versionCmd = &cobra.Command{
|
||||
Use: "version",
|
||||
Short: "display gitleaks version",
|
||||
Run: runVersion,
|
||||
}
|
||||
|
||||
func runVersion(cmd *cobra.Command, args []string) {
|
||||
fmt.Println(Version)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package config
|
||||
|
||||
import "regexp"
|
||||
|
||||
// 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
|
||||
|
||||
// Regexes is slice of content regular expressions that are allowed to be ignored.
|
||||
Regexes []*regexp.Regexp
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// CommitAllowed returns true if the commit is allowed to be ignored.
|
||||
func (a *Allowlist) CommitAllowed(c string) bool {
|
||||
if c == "" {
|
||||
return false
|
||||
}
|
||||
for _, commit := range a.Commits {
|
||||
if commit == c {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// PathAllowed returns true if the path is allowed to be ignored.
|
||||
func (a *Allowlist) PathAllowed(path string) bool {
|
||||
return anyRegexMatch(path, a.Paths)
|
||||
}
|
||||
|
||||
// RegexAllowed returns true if the regex is allowed to be ignored.
|
||||
func (a *Allowlist) RegexAllowed(s string) bool {
|
||||
return anyRegexMatch(s, a.Regexes)
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestCommitAllowed(t *testing.T) {
|
||||
tests := []struct {
|
||||
allowlist Allowlist
|
||||
commit string
|
||||
commitAllowed bool
|
||||
}{
|
||||
{
|
||||
allowlist: Allowlist{
|
||||
Commits: []string{"commitA"},
|
||||
},
|
||||
commit: "commitA",
|
||||
commitAllowed: true,
|
||||
},
|
||||
{
|
||||
allowlist: Allowlist{
|
||||
Commits: []string{"commitB"},
|
||||
},
|
||||
commit: "commitA",
|
||||
commitAllowed: false,
|
||||
},
|
||||
{
|
||||
allowlist: Allowlist{
|
||||
Commits: []string{"commitB"},
|
||||
},
|
||||
commit: "",
|
||||
commitAllowed: false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
assert.Equal(t, tt.commitAllowed, tt.allowlist.CommitAllowed(tt.commit))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegexAllowed(t *testing.T) {
|
||||
tests := []struct {
|
||||
allowlist Allowlist
|
||||
secret string
|
||||
regexAllowed bool
|
||||
}{
|
||||
{
|
||||
allowlist: Allowlist{
|
||||
Regexes: []*regexp.Regexp{regexp.MustCompile("matchthis")},
|
||||
},
|
||||
secret: "a secret: matchthis, done",
|
||||
regexAllowed: true,
|
||||
},
|
||||
{
|
||||
allowlist: Allowlist{
|
||||
Regexes: []*regexp.Regexp{regexp.MustCompile("matchthis")},
|
||||
},
|
||||
secret: "a secret",
|
||||
regexAllowed: false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
assert.Equal(t, tt.regexAllowed, tt.allowlist.RegexAllowed(tt.secret))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPathAllowed(t *testing.T) {
|
||||
tests := []struct {
|
||||
allowlist Allowlist
|
||||
path string
|
||||
pathAllowed bool
|
||||
}{
|
||||
{
|
||||
allowlist: Allowlist{
|
||||
Paths: []*regexp.Regexp{regexp.MustCompile("path")},
|
||||
},
|
||||
path: "a path",
|
||||
pathAllowed: true,
|
||||
},
|
||||
{
|
||||
allowlist: Allowlist{
|
||||
Paths: []*regexp.Regexp{regexp.MustCompile("path")},
|
||||
},
|
||||
path: "a ???",
|
||||
pathAllowed: false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
assert.Equal(t, tt.pathAllowed, tt.allowlist.PathAllowed(tt.path))
|
||||
}
|
||||
}
|
||||
+98
-171
@@ -1,200 +1,127 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/zricethezav/gitleaks/options"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
)
|
||||
|
||||
// Whitelist is struct containing items that if encountered will whitelist
|
||||
// a commit/line of code that would be considered a leak.
|
||||
type Whitelist struct {
|
||||
//go:embed gitleaks.toml
|
||||
var DefaultConfig string
|
||||
|
||||
// ViperConfig is the config struct used by the Viper config package
|
||||
// to parse the config file. This struct does not include regular expressions.
|
||||
// It is used as an intermediary to convert the Viper config to the Config struct.
|
||||
type ViperConfig struct {
|
||||
Description string
|
||||
Regex *regexp.Regexp
|
||||
File *regexp.Regexp
|
||||
}
|
||||
|
||||
// entropy represents an entropy range
|
||||
type entropy struct {
|
||||
P1, P2 float64
|
||||
}
|
||||
|
||||
// Rule is a struct that contains information that is loaded from a gitleaks config.
|
||||
// This struct is used in the Config struct as an array of Rules and is iterated
|
||||
// over during an audit. Each rule will be checked. If a regex match is found AND
|
||||
// that match is not whitelisted (globally or locally), then a leak will be appended
|
||||
// to the final audit report.
|
||||
type Rule struct {
|
||||
Description string
|
||||
Regex *regexp.Regexp
|
||||
Tags []string
|
||||
Whitelist []Whitelist
|
||||
Entropy []entropy
|
||||
}
|
||||
|
||||
// Config is a composite struct of Rules and Whitelists
|
||||
// Each Rule contains a description, regular expression, tags, and whitelists if available
|
||||
type Config struct {
|
||||
FileRegex *regexp.Regexp
|
||||
Message *regexp.Regexp
|
||||
Rules []Rule
|
||||
Whitelist struct {
|
||||
Description string
|
||||
Commits []string
|
||||
File *regexp.Regexp
|
||||
}
|
||||
}
|
||||
|
||||
// TomlLoader gets loaded with the values from a gitleaks toml config
|
||||
// see the config in config/defaults.go for an example. TomlLoader is used
|
||||
// to generate Config values (compiling regexes, etc).
|
||||
type TomlLoader struct {
|
||||
Global struct {
|
||||
File string
|
||||
Message string
|
||||
}
|
||||
Whitelist struct {
|
||||
Description string
|
||||
Commits []string
|
||||
File string
|
||||
}
|
||||
Rules []struct {
|
||||
Rules []struct {
|
||||
ID string
|
||||
Description string
|
||||
Entropy float64
|
||||
SecretGroup int
|
||||
Regex string
|
||||
Keywords []string
|
||||
Path string
|
||||
Tags []string
|
||||
Entropies []string
|
||||
Whitelist []struct {
|
||||
Description string
|
||||
Regex string
|
||||
File string
|
||||
|
||||
Allowlist struct {
|
||||
Regexes []string
|
||||
Paths []string
|
||||
Commits []string
|
||||
}
|
||||
}
|
||||
Allowlist struct {
|
||||
Regexes []string
|
||||
Paths []string
|
||||
Commits []string
|
||||
}
|
||||
}
|
||||
|
||||
// NewConfig will create a new config struct which contains
|
||||
// rules on how gitleaks will proceed with its audit.
|
||||
// If no options are passed via cli then NewConfig will return
|
||||
// a default config which can be seen in config.go
|
||||
func NewConfig(options options.Options) (Config, error) {
|
||||
var cfg Config
|
||||
tomlLoader := TomlLoader{}
|
||||
|
||||
var err error
|
||||
if options.Config != "" {
|
||||
_, err = toml.DecodeFile(options.Config, &tomlLoader)
|
||||
} else {
|
||||
_, err = toml.Decode(DefaultConfig, &tomlLoader)
|
||||
}
|
||||
if err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
|
||||
cfg, err = tomlLoader.Parse()
|
||||
if err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
// Config is a configuration struct that contains rules and an allowlist if present.
|
||||
type Config struct {
|
||||
Path string
|
||||
Description string
|
||||
Rules []*Rule
|
||||
Allowlist Allowlist
|
||||
Keywords []string
|
||||
}
|
||||
|
||||
// Parse will parse the values set in a TomlLoader and use those values
|
||||
// to create compiled regular expressions and rules used in audits
|
||||
func (tomlLoader TomlLoader) Parse() (Config, error) {
|
||||
var cfg Config
|
||||
for _, rule := range tomlLoader.Rules {
|
||||
re, err := regexp.Compile(rule.Regex)
|
||||
if err != nil {
|
||||
return cfg, fmt.Errorf("problem loading config: %v", err)
|
||||
func (vc *ViperConfig) Translate() (Config, error) {
|
||||
var (
|
||||
rules []*Rule
|
||||
keywords []string
|
||||
)
|
||||
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))
|
||||
}
|
||||
|
||||
// rule specific whitelists
|
||||
var whitelists []Whitelist
|
||||
for _, wl := range rule.Whitelist {
|
||||
re, err := regexp.Compile(wl.Regex)
|
||||
if err != nil {
|
||||
return cfg, fmt.Errorf("problem loading config: %v", err)
|
||||
if r.Keywords == nil {
|
||||
r.Keywords = []string{}
|
||||
} else {
|
||||
for _, k := range r.Keywords {
|
||||
keywords = append(keywords, strings.ToLower(k))
|
||||
}
|
||||
fileRe, err := regexp.Compile(wl.File)
|
||||
if err != nil {
|
||||
return cfg, fmt.Errorf("problem loading config: %v", err)
|
||||
}
|
||||
whitelists = append(whitelists, Whitelist{
|
||||
Description: wl.Description,
|
||||
File: fileRe,
|
||||
Regex: re,
|
||||
})
|
||||
}
|
||||
|
||||
entropies, err := getEntropy(rule.Entropies)
|
||||
if err != nil {
|
||||
return cfg, err
|
||||
if r.Tags == nil {
|
||||
r.Tags = []string{}
|
||||
}
|
||||
|
||||
cfg.Rules = append(cfg.Rules, Rule{
|
||||
Description: rule.Description,
|
||||
Regex: re,
|
||||
Tags: rule.Tags,
|
||||
Whitelist: whitelists,
|
||||
Entropy: entropies,
|
||||
})
|
||||
var configRegex *regexp.Regexp
|
||||
var configPathRegex *regexp.Regexp
|
||||
if r.Regex == "" {
|
||||
configRegex = nil
|
||||
} else {
|
||||
configRegex = regexp.MustCompile(r.Regex)
|
||||
}
|
||||
if r.Path == "" {
|
||||
configPathRegex = nil
|
||||
} else {
|
||||
configPathRegex = regexp.MustCompile(r.Path)
|
||||
}
|
||||
r := &Rule{
|
||||
Description: r.Description,
|
||||
RuleID: r.ID,
|
||||
Regex: configRegex,
|
||||
Path: configPathRegex,
|
||||
SecretGroup: r.SecretGroup,
|
||||
Entropy: r.Entropy,
|
||||
Tags: r.Tags,
|
||||
Keywords: r.Keywords,
|
||||
Allowlist: Allowlist{
|
||||
Regexes: allowlistRegexes,
|
||||
Paths: allowlistPaths,
|
||||
Commits: r.Allowlist.Commits,
|
||||
},
|
||||
}
|
||||
if r.Regex != nil && r.SecretGroup > r.Regex.NumSubexp() {
|
||||
return Config{}, fmt.Errorf("%s invalid regex secret group %d, max regex secret group %d", r.Description, r.SecretGroup, r.Regex.NumSubexp())
|
||||
}
|
||||
rules = append(rules, r)
|
||||
}
|
||||
|
||||
// global leaks
|
||||
if tomlLoader.Global.File != "" {
|
||||
re, err := regexp.Compile(tomlLoader.Global.File)
|
||||
if err != nil {
|
||||
return cfg, fmt.Errorf("problem loading config: %v", err)
|
||||
}
|
||||
cfg.FileRegex = re
|
||||
var allowlistRegexes []*regexp.Regexp
|
||||
for _, a := range vc.Allowlist.Regexes {
|
||||
allowlistRegexes = append(allowlistRegexes, regexp.MustCompile(a))
|
||||
}
|
||||
if tomlLoader.Global.Message != "" {
|
||||
re, err := regexp.Compile(tomlLoader.Global.Message)
|
||||
if err != nil {
|
||||
return cfg, fmt.Errorf("problem loading config: %v", err)
|
||||
}
|
||||
cfg.Message = re
|
||||
var allowlistPaths []*regexp.Regexp
|
||||
for _, a := range vc.Allowlist.Paths {
|
||||
allowlistPaths = append(allowlistPaths, regexp.MustCompile(a))
|
||||
}
|
||||
|
||||
// global whitelists
|
||||
if tomlLoader.Whitelist.File != "" {
|
||||
re, err := regexp.Compile(tomlLoader.Whitelist.File)
|
||||
if err != nil {
|
||||
return cfg, fmt.Errorf("problem loading config: %v", err)
|
||||
}
|
||||
cfg.Whitelist.File = re
|
||||
}
|
||||
cfg.Whitelist.Commits = tomlLoader.Whitelist.Commits
|
||||
cfg.Whitelist.Description = tomlLoader.Whitelist.Description
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// getEntropy
|
||||
func getEntropy(entropyStr []string) ([]entropy, error) {
|
||||
var ranges []entropy
|
||||
for _, span := range entropyStr {
|
||||
split := strings.Split(span, "-")
|
||||
v1, err := strconv.ParseFloat(split[0], 64)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v2, err := strconv.ParseFloat(split[1], 64)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if v1 > v2 {
|
||||
return nil, fmt.Errorf("entropy range must be ascending")
|
||||
}
|
||||
r := entropy{P1: v1, P2: v2}
|
||||
if r.P1 > 8.0 || r.P1 < 0.0 || r.P2 > 8.0 || r.P2 < 0.0 {
|
||||
return nil, fmt.Errorf("invalid entropy ranges, must be within 0.0-8.0")
|
||||
}
|
||||
ranges = append(ranges, r)
|
||||
}
|
||||
return ranges, nil
|
||||
return Config{
|
||||
Description: vc.Description,
|
||||
Rules: rules,
|
||||
Allowlist: Allowlist{
|
||||
Regexes: allowlistRegexes,
|
||||
Paths: allowlistPaths,
|
||||
Commits: vc.Allowlist.Commits,
|
||||
},
|
||||
Keywords: keywords,
|
||||
}, nil
|
||||
}
|
||||
+94
-86
@@ -2,115 +2,123 @@ package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/zricethezav/gitleaks/options"
|
||||
"regexp"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestParse(t *testing.T) {
|
||||
const configPath = "../testdata/config/"
|
||||
|
||||
func TestTranslate(t *testing.T) {
|
||||
tests := []struct {
|
||||
description string
|
||||
opts options.Options
|
||||
wantErr error
|
||||
wantFileRegex *regexp.Regexp
|
||||
wantMessages *regexp.Regexp
|
||||
wantWhitelist Whitelist
|
||||
cfgName string
|
||||
cfg Config
|
||||
wantError error
|
||||
}{
|
||||
{
|
||||
description: "default config",
|
||||
opts: options.Options{},
|
||||
},
|
||||
{
|
||||
description: "test successful load",
|
||||
opts: options.Options{
|
||||
Config: "../test_data/test_configs/aws_key.toml",
|
||||
cfgName: "allow_aws_re",
|
||||
cfg: Config{
|
||||
Rules: []*Rule{
|
||||
{
|
||||
Description: "AWS Access Key",
|
||||
Regex: regexp.MustCompile("(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}"),
|
||||
Tags: []string{"key", "AWS"},
|
||||
Keywords: []string{},
|
||||
RuleID: "aws-access-key",
|
||||
Allowlist: Allowlist{
|
||||
Regexes: []*regexp.Regexp{
|
||||
regexp.MustCompile("AKIALALEMEL33243OLIA"),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "test bad toml",
|
||||
opts: options.Options{
|
||||
Config: "../test_data/test_configs/bad_aws_key.toml",
|
||||
},
|
||||
wantErr: fmt.Errorf("Near line 7 (last key parsed 'rules.description'): expected value but found \"AWS\" instead"),
|
||||
},
|
||||
{
|
||||
description: "test bad regex",
|
||||
opts: options.Options{
|
||||
Config: "../test_data/test_configs/bad_regex_aws_key.toml",
|
||||
},
|
||||
wantErr: fmt.Errorf("problem loading config: error parsing regexp: invalid nested repetition operator: `???`"),
|
||||
},
|
||||
{
|
||||
description: "test bad global whitelist file regex",
|
||||
opts: options.Options{
|
||||
Config: "../test_data/test_configs/bad_aws_key_global_whitelist_file.toml",
|
||||
},
|
||||
wantErr: fmt.Errorf("problem loading config: error parsing regexp: missing argument to repetition operator: `??`"),
|
||||
},
|
||||
{
|
||||
description: "test bad global file regex",
|
||||
opts: options.Options{
|
||||
Config: "../test_data/test_configs/bad_aws_key_file_regex.toml",
|
||||
},
|
||||
wantErr: fmt.Errorf("problem loading config: error parsing regexp: missing argument to repetition operator: `??`"),
|
||||
},
|
||||
{
|
||||
description: "test bad global message regex",
|
||||
opts: options.Options{
|
||||
Config: "../test_data/test_configs/bad_aws_key_message_regex.toml",
|
||||
},
|
||||
wantErr: fmt.Errorf("problem loading config: error parsing regexp: missing argument to repetition operator: `??`"),
|
||||
},
|
||||
{
|
||||
description: "test successful load big ol thing",
|
||||
opts: options.Options{
|
||||
Config: "../test_data/test_configs/large.toml",
|
||||
cfgName: "allow_commit",
|
||||
cfg: Config{
|
||||
Rules: []*Rule{
|
||||
{
|
||||
Description: "AWS Access Key",
|
||||
Regex: regexp.MustCompile("(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}"),
|
||||
Tags: []string{"key", "AWS"},
|
||||
Keywords: []string{},
|
||||
RuleID: "aws-access-key",
|
||||
Allowlist: Allowlist{
|
||||
Commits: []string{"allowthiscommit"},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "test load entropy",
|
||||
opts: options.Options{
|
||||
Config: "../test_data/test_configs/entropy.toml",
|
||||
cfgName: "allow_path",
|
||||
cfg: Config{
|
||||
Rules: []*Rule{
|
||||
{
|
||||
Description: "AWS Access Key",
|
||||
Regex: regexp.MustCompile("(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}"),
|
||||
Tags: []string{"key", "AWS"},
|
||||
Keywords: []string{},
|
||||
RuleID: "aws-access-key",
|
||||
Allowlist: Allowlist{
|
||||
Paths: []*regexp.Regexp{
|
||||
regexp.MustCompile(".go"),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "test entropy bad range",
|
||||
opts: options.Options{
|
||||
Config: "../test_data/test_configs/bad_entropy_1.toml",
|
||||
cfgName: "entropy_group",
|
||||
cfg: Config{
|
||||
Rules: []*Rule{
|
||||
{
|
||||
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{},
|
||||
Entropy: 3.5,
|
||||
SecretGroup: 3,
|
||||
Tags: []string{},
|
||||
Keywords: []string{},
|
||||
},
|
||||
},
|
||||
},
|
||||
wantErr: fmt.Errorf("entropy range must be ascending"),
|
||||
},
|
||||
{
|
||||
description: "test entropy value p2",
|
||||
opts: options.Options{
|
||||
Config: "../test_data/test_configs/bad_entropy_2.toml",
|
||||
},
|
||||
wantErr: fmt.Errorf("strconv.ParseFloat: parsing \"x\": invalid syntax"),
|
||||
},
|
||||
{
|
||||
description: "test entropy value p1",
|
||||
opts: options.Options{
|
||||
Config: "../test_data/test_configs/bad_entropy_3.toml",
|
||||
},
|
||||
wantErr: fmt.Errorf("strconv.ParseFloat: parsing \"x\": invalid syntax"),
|
||||
},
|
||||
{
|
||||
description: "test entropy value p1",
|
||||
opts: options.Options{
|
||||
Config: "../test_data/test_configs/bad_entropy_4.toml",
|
||||
},
|
||||
wantErr: fmt.Errorf("invalid entropy ranges, must be within 0.0-8.0"),
|
||||
cfgName: "bad_entropy_group",
|
||||
cfg: Config{},
|
||||
wantError: fmt.Errorf("Discord API key invalid regex secret group 5, max regex secret group 3"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
_, err := NewConfig(test.opts)
|
||||
for _, tt := range tests {
|
||||
viper.Reset()
|
||||
viper.AddConfigPath(configPath)
|
||||
viper.SetConfigName(tt.cfgName)
|
||||
viper.SetConfigType("toml")
|
||||
err := viper.ReadInConfig()
|
||||
if err != nil {
|
||||
if test.wantErr == nil {
|
||||
t.Error(err)
|
||||
} else if test.wantErr.Error() != err.Error() {
|
||||
t.Errorf("expected err: %s, got %s", test.wantErr, err)
|
||||
}
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
var vc ViperConfig
|
||||
err = viper.Unmarshal(&vc)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
cfg, err := vc.Translate()
|
||||
if tt.wantError != nil {
|
||||
if err == nil {
|
||||
t.Errorf("expected error")
|
||||
}
|
||||
assert.Equal(t, tt.wantError, err)
|
||||
}
|
||||
|
||||
assert.Equal(t, cfg.Rules, tt.cfg.Rules)
|
||||
}
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
package config
|
||||
|
||||
// DefaultConfig is the default gitleaks configuration. If --config={path-to-config} is set than the config located
|
||||
// at {path-to-config} will be used. Alternatively, if --repo-config is set then gitleaks will attempt to
|
||||
// use the config set in a gitleaks.toml or .gitleaks.toml file in the repo that is run with --repo-config set.
|
||||
const DefaultConfig = `
|
||||
title = "gitleaks config"
|
||||
|
||||
[[rules]]
|
||||
description = "AWS Manager ID"
|
||||
regex = '''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
|
||||
tags = ["key", "AWS"]
|
||||
|
||||
[[rules]]
|
||||
description = "AWS Secret Key"
|
||||
regex = '''(?i)aws(.{0,20})?(?-i)['\"][0-9a-zA-Z\/+]{40}['\"]'''
|
||||
tags = ["key", "AWS"]
|
||||
|
||||
[[rules]]
|
||||
description = "AWS MWS key"
|
||||
regex = '''amzn\.mws\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'''
|
||||
tags = ["key", "AWS", "MWS"]
|
||||
|
||||
[[rules]]
|
||||
description = "Facebook Secret Key"
|
||||
regex = '''(?i)(facebook|fb)(.{0,20})?(?-i)['\"][0-9a-f]{32}['\"]'''
|
||||
tags = ["key", "Facebook"]
|
||||
|
||||
[[rules]]
|
||||
description = "Facebook Client ID"
|
||||
regex = '''(?i)(facebook|fb)(.{0,20})?['\"][0-9]{13,17}['\"]'''
|
||||
tags = ["key", "Facebook"]
|
||||
|
||||
[[rules]]
|
||||
description = "Twitter Secret Key"
|
||||
regex = '''(?i)twitter(.{0,20})?['\"][0-9a-z]{35,44}['\"]'''
|
||||
tags = ["key", "Twitter"]
|
||||
|
||||
[[rules]]
|
||||
description = "Twitter Client ID"
|
||||
regex = '''(?i)twitter(.{0,20})?['\"][0-9a-z]{18,25}['\"]'''
|
||||
tags = ["client", "Twitter"]
|
||||
|
||||
[[rules]]
|
||||
description = "Github"
|
||||
regex = '''(?i)github(.{0,20})?(?-i)['\"][0-9a-zA-Z]{35,40}['\"]'''
|
||||
tags = ["key", "Github"]
|
||||
|
||||
[[rules]]
|
||||
description = "LinkedIn Client ID"
|
||||
regex = '''(?i)linkedin(.{0,20})?(?-i)['\"][0-9a-z]{12}['\"]'''
|
||||
tags = ["client", "LinkedIn"]
|
||||
|
||||
[[rules]]
|
||||
description = "LinkedIn Secret Key"
|
||||
regex = '''(?i)linkedin(.{0,20})?['\"][0-9a-z]{16}['\"]'''
|
||||
tags = ["secret", "LinkedIn"]
|
||||
|
||||
[[rules]]
|
||||
description = "Slack"
|
||||
regex = '''xox[baprs]-([0-9a-zA-Z]{10,48})?'''
|
||||
tags = ["key", "Slack"]
|
||||
|
||||
[[rules]]
|
||||
description = "EC"
|
||||
regex = '''-----BEGIN EC PRIVATE KEY-----'''
|
||||
tags = ["key", "EC"]
|
||||
|
||||
[[rules]]
|
||||
description = "Generic Credential"
|
||||
regex = '''(?i)(api_key|apikey|secret)(.{0,20})?['|"][0-9a-zA-Z]{16,45}['|"]'''
|
||||
tags = ["key", "API", "generic"]
|
||||
|
||||
[[rules]]
|
||||
description = "Google API key"
|
||||
regex = '''AIza[0-9A-Za-z\\-_]{35}'''
|
||||
tags = ["key", "Google"]
|
||||
|
||||
|
||||
[[rules]]
|
||||
description = "Heroku API key"
|
||||
regex = '''(?i)heroku(.{0,20})?['"][0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}['"]'''
|
||||
tags = ["key", "Heroku"]
|
||||
|
||||
[[rules]]
|
||||
description = "MailChimp API key"
|
||||
regex = '''(?i)(mailchimp|mc)(.{0,20})?['"][0-9a-f]{32}-us[0-9]{1,2}['"]'''
|
||||
tags = ["key", "Mailchimp"]
|
||||
|
||||
[[rules]]
|
||||
description = "Mailgun API key"
|
||||
regex = '''(?i)(mailgun|mg)(.{0,20})?['"][0-9a-z]{32}['"]'''
|
||||
tags = ["key", "Mailgun"]
|
||||
|
||||
[[rules]]
|
||||
description = "PayPal Braintree access token"
|
||||
regex = '''access_token\$production\$[0-9a-z]{16}\$[0-9a-f]{32}'''
|
||||
tags = ["key", "Paypal"]
|
||||
|
||||
[[rules]]
|
||||
description = "Picatic API key"
|
||||
regex = '''sk_live_[0-9a-z]{32}'''
|
||||
tags = ["key", "Picatic"]
|
||||
|
||||
[[rules]]
|
||||
description = "Slack Webhook"
|
||||
regex = '''https://hooks.slack.com/services/T[a-zA-Z0-9_]{8}/B[a-zA-Z0-9_]{8}/[a-zA-Z0-9_]{24}'''
|
||||
tags = ["key", "slack"]
|
||||
|
||||
[[rules]]
|
||||
description = "Stripe API key"
|
||||
regex = '''(?i)stripe(.{0,20})?['\"][sk|rk]_live_[0-9a-zA-Z]{24}'''
|
||||
tags = ["key", "Stripe"]
|
||||
|
||||
[[rules]]
|
||||
description = "Square access token"
|
||||
regex = '''sq0atp-[0-9A-Za-z\-_]{22}'''
|
||||
tags = ["key", "square"]
|
||||
|
||||
[[rules]]
|
||||
description = "Square OAuth secret"
|
||||
regex = '''sq0csp-[0-9A-Za-z\\-_]{43}'''
|
||||
tags = ["key", "square"]
|
||||
|
||||
[[rules]]
|
||||
description = "Twilio API key"
|
||||
regex = '''(?i)twilio(.{0,20})?['\"][0-9a-f]{32}['\"]'''
|
||||
tags = ["key", "twilio"]
|
||||
|
||||
[whitelist]
|
||||
description = "image whitelists"
|
||||
file = '''(.*?)(jpg|gif|doc|pdf|bin)$'''
|
||||
`
|
||||
@@ -0,0 +1,728 @@
|
||||
# This is the default gitleaks configuration file.
|
||||
# Rules and allowlists are defined within this file.
|
||||
# Rules instruct gitleaks on what should be considered a secret.
|
||||
# Allowlists instruct gitleaks on what is allowed, i.e. not a secret.
|
||||
title = "gitleaks config"
|
||||
|
||||
[allowlist]
|
||||
description = "global allow lists"
|
||||
regexes = [
|
||||
'''219-09-9999''',
|
||||
'''078-05-1120''',
|
||||
'''(9[0-9]{2}|666)-\d{2}-\d{4}''',
|
||||
]
|
||||
paths = [
|
||||
'''gitleaks.toml''',
|
||||
'''(.*?)(jpg|gif|doc|pdf|bin|svg|socket)$''',
|
||||
'''(go.mod|go.sum)$'''
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Adobe Client ID (Oauth Web)"
|
||||
id = "adobe-client-id"
|
||||
regex = '''(?i)(?:adobe)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-f0-9]{32})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"adobe",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Adobe Client Secret"
|
||||
id = "adobe-client-secret"
|
||||
regex = '''(?i)\b((p8e-)(?i)[a-z0-9]{32})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
keywords = [
|
||||
"p8e-",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Age secret key"
|
||||
id = "age secret key"
|
||||
regex = '''AGE-SECRET-KEY-1[QPZRY9X8GF2TVDW0S3JN54KHCE6MUA7L]{58}'''
|
||||
keywords = [
|
||||
"age-secret-key-1",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Alibaba AccessKey ID"
|
||||
id = "alibaba-access-key-id"
|
||||
regex = '''(?i)\b((LTAI)(?i)[a-z0-9]{20})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
keywords = [
|
||||
"ltai",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Alibaba Secret Key"
|
||||
id = "alibaba-secret-key"
|
||||
regex = '''(?i)(?:alibaba)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-z0-9]{30})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"alibaba",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Asana Client ID"
|
||||
id = "asana-client-id"
|
||||
regex = '''(?i)(?:asana)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([0-9]{16})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"asana",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Asana Client Secret"
|
||||
id = "asana-client-secret"
|
||||
regex = '''(?i)(?:asana)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-z0-9]{32})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
keywords = [
|
||||
"asana",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Atlassian API token"
|
||||
id = "atlassian-api-token"
|
||||
regex = '''(?i)(?:atlassian|confluence)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-z0-9]{24})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"atlassian","confluence",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "AWS"
|
||||
id = "aws-access-token"
|
||||
regex = '''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
|
||||
keywords = [
|
||||
"akia","agpa","aida","aroa","aipa","anpa","anva","asia",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "BitBucket Client ID"
|
||||
id = "bitbucket-client-id"
|
||||
regex = '''(?i)(?:bitbucket)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-z0-9]{32})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"bitbucket",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "BitBucket Client Secret"
|
||||
id = "bitbucket-client-secret"
|
||||
regex = '''(?i)(?:bitbucket)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-z0-9=_\-]{64})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"bitbucket",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Beamer API token"
|
||||
id = "beamer-api-token"
|
||||
regex = '''(?i)(?:beamer)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}(b_[a-z0-9=_\-]{44})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"beamer",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Clojars API token"
|
||||
id = "clojars-api-token"
|
||||
regex = '''(?i)(CLOJARS_)[a-z0-9]{60}'''
|
||||
keywords = [
|
||||
"clojars",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Contentful delivery API token"
|
||||
id = "contentful-delivery-api-token"
|
||||
regex = '''(?i)(?:contentful)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-z0-9=_\-]{43})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"contentful",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Databricks API token"
|
||||
id = "databricks-api-token"
|
||||
regex = '''(?i)\b(dapi[a-h0-9]{32})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
keywords = [
|
||||
"dapi",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Discord API key"
|
||||
id = "discord-api-token"
|
||||
regex = '''(?i)(?:discord)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-f0-9]{64})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"discord",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Discord client ID"
|
||||
id = "discord-client-id"
|
||||
regex = '''(?i)(?:discord)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([0-9]{18})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"discord",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Discord client secret"
|
||||
id = "discord-client-secret"
|
||||
regex = '''(?i)(?:discord)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-z0-9=_\-]{32})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"discord",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Dropbox API secret"
|
||||
id = "doppler-api-token"
|
||||
regex = '''(?i)(?:dropbox)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-z0-9]{15})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"dropbox",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Dropbox long lived API token"
|
||||
id = "dropbox-long-lived-api-token"
|
||||
regex = '''(?i)(?:dropbox)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-z0-9]{11}(AAAAAAAAAA)[a-z0-9\-_=]{43})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
keywords = [
|
||||
"dropbox",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Dropbox short lived API token"
|
||||
id = "dropbox-short-lived-api-token"
|
||||
regex = '''(?i)(?:dropbox)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}(sl\.[a-z0-9\-=_]{135})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
keywords = [
|
||||
"dropbox",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Doppler API token"
|
||||
id = "doppler-api-token"
|
||||
regex = '''(dp\.pt\.)(?i)[a-z0-9]{43}'''
|
||||
keywords = [
|
||||
"doppler",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Duffel API token"
|
||||
id = "duffel-api-token"
|
||||
regex = '''duffel_(test|live)_(?i)[a-z0-9_\-=]{43}'''
|
||||
keywords = [
|
||||
"duffel",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Dynatrace API token"
|
||||
id = "dynatrace-api-token"
|
||||
regex = '''dt0c01\.(?i)[a-z0-9]{24}\.[a-z0-9]{64}'''
|
||||
keywords = [
|
||||
"dynatrace",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "EasyPost API token"
|
||||
id = "easypost-api-token"
|
||||
regex = '''EZAK(?i)[a-z0-9]{54}'''
|
||||
keywords = [
|
||||
"ezak",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "EasyPost test API token"
|
||||
id = "easypost-test-api-token"
|
||||
regex = '''EZTK(?i)[a-z0-9]{54}'''
|
||||
keywords = [
|
||||
"eztk",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "facebook"
|
||||
id = "facebook"
|
||||
regex = '''(?i)(?:facebook)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-f0-9]{32})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"facebook",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Fastly API key"
|
||||
id = "fastly-api-token"
|
||||
regex = '''(?i)(?:fastly)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-z0-9=_\-]{32})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"fastly",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Finicity Client Secret"
|
||||
id = "finicity-client-secret"
|
||||
regex = '''(?i)(?:finicity)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-z0-9]{20})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"finicity",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Finicity API token"
|
||||
id = "finicity-api-token"
|
||||
regex = '''(?i)(?:finicity)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-f0-9]{32})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"finicity",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Finicity Public Key"
|
||||
id = "flutterwave-public-key"
|
||||
regex = '''FLWPUBK_TEST-(?i)[a-h0-9]{32}-X'''
|
||||
keywords = [
|
||||
"flwpubk_test",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Finicity Secret Key"
|
||||
id = "flutterwave-public-key"
|
||||
regex = '''FLWSECK_TEST-(?i)[a-h0-9]{32}-X'''
|
||||
keywords = [
|
||||
"flwseck_test",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Finicity Secret Key"
|
||||
id = "flutterwave-public-key"
|
||||
regex = '''FLWSECK_TEST-(?i)[a-h0-9]{32}-X'''
|
||||
keywords = [
|
||||
"flwseck_test",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Frame.io API token"
|
||||
id = "frameio-api-token"
|
||||
regex = '''fio-u-(?i)[a-z0-9\-_=]{64}'''
|
||||
keywords = [
|
||||
"fio-u-",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Generic API Key"
|
||||
id = "generic-api-key"
|
||||
regex = '''(?i)(?:key|api[^Version]|token|pat|secret|client|password|auth)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([0-9a-z\-_.=]{10,150})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
entropy = 3.7
|
||||
keywords = [
|
||||
"key","api","token","secret","client","pat","password","auth",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "GoCardless API token"
|
||||
id = "gocardless-api-token"
|
||||
regex = '''(?i)(?:gocardless)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}(live_(?i)[a-z0-9\-_=]{40})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
keywords = [
|
||||
"live_","gocardless",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "GitHub Personal Access Token"
|
||||
id = "github-pat"
|
||||
regex = '''ghp_[0-9a-zA-Z]{36}'''
|
||||
keywords = [
|
||||
"ghp_",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "GitHub OAuth Access Token"
|
||||
id = "github-oauth"
|
||||
regex = '''gho_[0-9a-zA-Z]{36}'''
|
||||
keywords = [
|
||||
"gho_",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "GitHub App Token"
|
||||
id = "github-app-token"
|
||||
regex = '''(ghu|ghs)_[0-9a-zA-Z]{36}'''
|
||||
keywords = [
|
||||
"ghu_","ghs_",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "GitHub Refresh Token"
|
||||
id = "github-refresh-token"
|
||||
regex = '''ghr_[0-9a-zA-Z]{36}'''
|
||||
keywords = [
|
||||
"ghr_",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Gitlab Personal Access Token"
|
||||
id = "gitlab-pat"
|
||||
regex = '''glpat-[0-9a-zA-Z\-\_]{20}'''
|
||||
keywords = [
|
||||
"glpat-",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "HashiCorp Terraform user/org API token"
|
||||
id = "hashicorp-tf-api-token"
|
||||
regex = '''(?i)[a-z0-9]{14}\.atlasv1\.[a-z0-9\-_=]{60,70}'''
|
||||
keywords = [
|
||||
"atlasv1",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Heroku API Key"
|
||||
id = "heroku-api-key"
|
||||
regex = '''(?i)(?:heroku)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"heroku",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "HubSpot API Token"
|
||||
id = "hubspot-api-key"
|
||||
regex = '''(?i)(?:hubspot)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"hubspot",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Intercom API Token"
|
||||
id = "intercom-api-key"
|
||||
regex = '''(?i)(?:intercom)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-z0-9=_\-]{60})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"intercom",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Linear API Token"
|
||||
id = "linear-api-key"
|
||||
regex = '''lin_api_(?i)[a-z0-9]{40}'''
|
||||
keywords = [
|
||||
"lin_api_",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Linear Client Secret"
|
||||
id = "linear-client-secret"
|
||||
regex = '''(?i)(?:linear)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-f0-9]{32})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
keywords = [
|
||||
"linear",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "LinkedIn Client ID"
|
||||
id = "linkedin-client-id"
|
||||
regex = '''(?i)(?:linkedin|linked-in)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-z0-9]{14})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"linkedin","linked-in",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "LinkedIn Client secret"
|
||||
id = "linkedin-client-secret"
|
||||
regex = '''(?i)(?:linkedin|linked-in)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-z0-9]{16})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"linkedin","linked-in",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Lob API Key"
|
||||
id = "lob-api-key"
|
||||
regex = '''(?i)(?:lob)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}((live|test)_[a-f0-9]{35})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
keywords = [
|
||||
"test_","live_",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Lob Publishable API Key"
|
||||
id = "lob-pub-api-key"
|
||||
regex = '''(?i)(?:lob)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}((test|live)_pub_[a-f0-9]{31})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
keywords = [
|
||||
"test_pub","live_pub","_pub",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Mailchimp API key"
|
||||
id = "mailchimp-api-key"
|
||||
regex = '''(?i)(?:mailchimp)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-f0-9]{32}-us20)(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"mailchimp",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Mailgun public validation key"
|
||||
id = "mailgun-pub-key"
|
||||
regex = '''(?i)(?:mailgun)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}(pubkey-[a-f0-9]{32})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"mailgun",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Mailgun private API token"
|
||||
id = "mailgun-private-api-token"
|
||||
regex = '''(?i)(?:mailgun)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}(key-[a-f0-9]{32})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"mailgun",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Mailgun webhook signing key"
|
||||
id = "mailgun-signing-key"
|
||||
regex = '''(?i)(?:mailgun)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-h0-9]{32}-[a-h0-9]{8}-[a-h0-9]{8})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"mailgun",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "MapBox API token"
|
||||
id = "mapbox-api-token"
|
||||
regex = '''(?i)(?:mapbox)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}(pk\.[a-z0-9]{60}\.[a-z0-9]{22})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"mapbox",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "MessageBird API token"
|
||||
id = "messagebird-api-token"
|
||||
regex = '''(?i)(?:messagebird|message-bird|message_bird)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-z0-9]{25})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"messagebird","message-bird","message_bird",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "MessageBird client ID"
|
||||
id = "messagebird-client-id"
|
||||
regex = '''(?i)(?:messagebird|message-bird|message_bird)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-h0-9]{8}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{12})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"messagebird","message-bird","message_bird",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "New Relic user API Key"
|
||||
id = "new-relic-user-api-key"
|
||||
regex = '''(?i)(?:new-relic|newrelic|new_relic)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}(NRAK-[a-z0-9]{27})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"nrak",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "New Relic user API ID"
|
||||
id = "new-relic-user-api-id"
|
||||
regex = '''(?i)(?:new-relic|newrelic|new_relic)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-z0-9]{64})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"new-relic","newrelic","new_relic",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "New Relic ingest browser API token"
|
||||
id = "new-relic-browser-api-token"
|
||||
regex = '''(?i)(?:new-relic|newrelic|new_relic)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}(NRJS-[a-f0-9]{19})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"nrjs-",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "npm access token"
|
||||
id = "npm-access-token"
|
||||
regex = '''(?i)\b(npm_[a-z0-9]{36})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"npm_",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "PlanetScale password"
|
||||
id = "planetscale-password"
|
||||
regex = '''(?i)\b(pscale_pw_(?i)[a-z0-9=\-_\.]{43})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"pscale_pw_",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "PlanetScale API token"
|
||||
id = "planetscale-api-token"
|
||||
regex = '''(?i)\b(pscale_tkn_(?i)[a-z0-9=\-_\.]{43})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"pscale_tkn_",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Postman API token"
|
||||
id = "postman-api-token"
|
||||
regex = '''(?i)\b(PMAK-(?i)[a-f0-9]{24}\-[a-f0-9]{34})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"pmak-",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Private Key"
|
||||
id = "private-key"
|
||||
regex = '''(?i)-----BEGIN[ A-Z0-9_-]{0,100}PRIVATE KEY-----[\s\S-]*KEY----'''
|
||||
keywords = [
|
||||
"-----begin private",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Pulumi API token"
|
||||
id = "pulumi-api-token"
|
||||
regex = '''(?i)\b(pul-[a-f0-9]{40})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"pul-",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "PyPI upload token"
|
||||
id = "pypi-upload-token"
|
||||
regex = '''pypi-AgEIcHlwaS5vcmc[A-Za-z0-9\-_]{50,1000}'''
|
||||
keywords = [
|
||||
"pypi-ageichlwas5vcmc",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Rubygem API token"
|
||||
id = "rubygems-api-token"
|
||||
regex = '''(?i)\b(rubygems_[a-f0-9]{48})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"rubygems_",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "SendGrid API token"
|
||||
id = "sendgrid-api-token"
|
||||
regex = '''(?i)\b(SG\.(?i)[a-z0-9=_\-\.]{66})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"sg.",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Sendinblue API token"
|
||||
id = "sendinblue-api-token"
|
||||
regex = '''(?i)\b(xkeysib-[a-f0-9]{64}\-(?i)[a-z0-9]{16})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"xkeysib-",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Shippo API token"
|
||||
id = "shippo-api-token"
|
||||
regex = '''(?i)\b(shippo_(live|test)_[a-f0-9]{40})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"shippo_",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Shopify access token"
|
||||
id = "shopify-access-token"
|
||||
regex = '''shpat_[a-fA-F0-9]{32}'''
|
||||
keywords = [
|
||||
"shpat_",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Shopify custom access token"
|
||||
id = "shopify-custom-access-token"
|
||||
regex = '''shpca_[a-fA-F0-9]{32}'''
|
||||
keywords = [
|
||||
"shpca_",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Shopify private app access token"
|
||||
id = "shopify-private-app-access-token"
|
||||
regex = '''shppa_[a-fA-F0-9]{32}'''
|
||||
keywords = [
|
||||
"shppa_",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Shopify shared secret"
|
||||
id = "shopify-shared-secret"
|
||||
regex = '''shpss_[a-fA-F0-9]{32}'''
|
||||
keywords = [
|
||||
"shpss_",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Slack token"
|
||||
id = "slack-access-token"
|
||||
regex = '''xox[baprs]-([0-9a-zA-Z]{10,48})'''
|
||||
keywords = [
|
||||
"xoxb","xoxa","xoxp","xoxr","xoxs",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Slack Webhook"
|
||||
id = "slack-web-hook"
|
||||
regex = '''https:\/\/hooks.slack.com\/services\/[A-Za-z0-9+\/]{44,46}'''
|
||||
keywords = [
|
||||
"hooks.slack.com",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Stripe"
|
||||
id = "stripe-access-token"
|
||||
regex = '''(?i)(sk|pk)_(test|live)_[0-9a-z]{10,32}'''
|
||||
keywords = [
|
||||
"sk_test","pk_test","sk_live","pk_live",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Twilio API Key"
|
||||
id = "twilio-api-key"
|
||||
regex = '''SK[0-9a-fA-F]{32}'''
|
||||
keywords = [
|
||||
"twilio",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Twitch API token"
|
||||
id = "twitch-api-token"
|
||||
regex = '''(?i)(?:twitch)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-z0-9]{30})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"twitch",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "twitter"
|
||||
id = "twitter"
|
||||
regex = '''(?i)(?:twitter)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}([a-f0-9]{35,44})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"twitter",
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Typeform API token"
|
||||
id = "typeform-api-token"
|
||||
regex = '''(?i)(?:typeform)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:=|\|\|:|<=|=>|:)(?:'|\"|\s|=|\x60){0,5}(tfp_[a-z0-9\-_\.=]{59})(?:['|\"|\n|\r|\s|\x60]|$)'''
|
||||
secretGroup = 1
|
||||
keywords = [
|
||||
"tfp_",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
)
|
||||
|
||||
// Rules contain information that define details on how to detect secrets
|
||||
type Rule struct {
|
||||
// Description is the description of the rule.
|
||||
Description string
|
||||
|
||||
// RuleID is a unique identifier for this rule
|
||||
RuleID string
|
||||
|
||||
// Entropy is a float representing the minimum shannon
|
||||
// entropy a regex group must have to be considered a secret.
|
||||
Entropy float64
|
||||
|
||||
// SecretGroup is an int used to extract secret from regex
|
||||
// match and used as the group that will have its entropy
|
||||
// checked if `entropy` is set.
|
||||
SecretGroup int
|
||||
|
||||
// Regex is a golang regular expression used to detect secrets.
|
||||
Regex *regexp.Regexp
|
||||
|
||||
// Path is a golang regular expression used to
|
||||
// filter secrets by path
|
||||
Path *regexp.Regexp
|
||||
|
||||
// Tags is an array of strings used for metadata
|
||||
// and reporting purposes.
|
||||
Tags []string
|
||||
|
||||
// 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.
|
||||
Keywords []string
|
||||
|
||||
// Allowlist allows a rule to be ignored for specific
|
||||
// regexes, paths, and/or commits
|
||||
Allowlist Allowlist
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
)
|
||||
|
||||
func anyRegexMatch(f string, res []*regexp.Regexp) bool {
|
||||
for _, re := range res {
|
||||
if regexMatched(f, re) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func regexMatched(f string, re *regexp.Regexp) bool {
|
||||
if re == nil {
|
||||
return false
|
||||
}
|
||||
if re.FindString(f) != "" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,436 @@
|
||||
package detect
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/detect/git"
|
||||
"github.com/zricethezav/gitleaks/v8/report"
|
||||
|
||||
"github.com/fatih/semgroup"
|
||||
"github.com/gitleaks/go-gitdiff/gitdiff"
|
||||
"github.com/h2non/filetype"
|
||||
ahocorasick "github.com/petar-dambovaliev/aho-corasick"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// Type used to differentiate between git scan types:
|
||||
// $ gitleaks detect
|
||||
// $ gitleaks protect
|
||||
// $ gitleaks protect staged
|
||||
type GitScanType int
|
||||
|
||||
const (
|
||||
DetectType GitScanType = iota
|
||||
ProtectType
|
||||
ProtectStagedType
|
||||
|
||||
gitleaksAllowSignature = "gitleaks:allow"
|
||||
)
|
||||
|
||||
// Detector is the main detector struct
|
||||
type Detector struct {
|
||||
// Config is the configuration for the detector
|
||||
Config config.Config
|
||||
|
||||
// Redact is a flag to redact findings. This is exported
|
||||
// so users using gitleaks as a library can set this flag
|
||||
// without calling `detector.Start(cmd *cobra.Command)`
|
||||
Redact bool
|
||||
|
||||
// verbose is a flag to print findings
|
||||
Verbose bool
|
||||
|
||||
// commitMap is used to keep track of commits that have been scanned.
|
||||
// This is only used for logging purposes and git scans.
|
||||
commitMap map[string]bool
|
||||
|
||||
// findingMutex is to prevent concurrent access to the
|
||||
// findings slice when adding findings.
|
||||
findingMutex *sync.Mutex
|
||||
|
||||
// findings is a slice of report.Findings. This is the result
|
||||
// of the detector's scan which can then be used to generate a
|
||||
// report.
|
||||
findings []report.Finding
|
||||
|
||||
// prefilter is a ahocorasick struct used for doing efficient string
|
||||
// matching given a set of words (keywords from the rules in the config)
|
||||
prefilter ahocorasick.AhoCorasick
|
||||
}
|
||||
|
||||
// Fragment contains the data to be scanned
|
||||
type Fragment struct {
|
||||
// Raw is the raw content of the fragment
|
||||
Raw string
|
||||
|
||||
// FilePath is the path to the file if applicable
|
||||
FilePath string
|
||||
|
||||
// CommitSHA is the SHA of the commit if applicable
|
||||
CommitSHA string
|
||||
|
||||
// newlineIndices is a list of indices of newlines in the raw content.
|
||||
// This is used to calculate the line location of a finding
|
||||
newlineIndices [][]int
|
||||
|
||||
// keywords is a map of all the keywords contain within the contents
|
||||
// of this fragment
|
||||
keywords map[string]bool
|
||||
}
|
||||
|
||||
// NewDetector creates a new detector with the given config
|
||||
func NewDetector(cfg config.Config) *Detector {
|
||||
builder := ahocorasick.NewAhoCorasickBuilder(ahocorasick.Opts{
|
||||
AsciiCaseInsensitive: true,
|
||||
MatchOnlyWholeWords: false,
|
||||
MatchKind: ahocorasick.LeftMostLongestMatch,
|
||||
DFA: true,
|
||||
})
|
||||
|
||||
return &Detector{
|
||||
commitMap: make(map[string]bool),
|
||||
findingMutex: &sync.Mutex{},
|
||||
findings: make([]report.Finding, 0),
|
||||
Config: cfg,
|
||||
prefilter: builder.Build(cfg.Keywords),
|
||||
}
|
||||
}
|
||||
|
||||
// NewDetectorDefaultConfig creates a new detector with the default config
|
||||
func NewDetectorDefaultConfig() (*Detector, error) {
|
||||
viper.SetConfigType("toml")
|
||||
err := viper.ReadConfig(strings.NewReader(config.DefaultConfig))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var vc config.ViperConfig
|
||||
err = viper.Unmarshal(&vc)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg, err := vc.Translate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewDetector(cfg), nil
|
||||
}
|
||||
|
||||
// DetectBytes scans the given bytes and returns a list of findings
|
||||
func (d *Detector) DetectBytes(content []byte) []report.Finding {
|
||||
return d.DetectString(string(content))
|
||||
}
|
||||
|
||||
// DetectString scans the given string and returns a list of findings
|
||||
func (d *Detector) DetectString(content string) []report.Finding {
|
||||
return d.Detect(Fragment{
|
||||
Raw: content,
|
||||
})
|
||||
}
|
||||
|
||||
// detectRule scans the given fragment for the given rule and returns a list of findings
|
||||
func (d *Detector) detectRule(fragment Fragment, rule *config.Rule) []report.Finding {
|
||||
var findings []report.Finding
|
||||
|
||||
// check if filepath or commit is allowed for this rule
|
||||
if rule.Allowlist.CommitAllowed(fragment.CommitSHA) ||
|
||||
rule.Allowlist.PathAllowed(fragment.FilePath) {
|
||||
return findings
|
||||
}
|
||||
|
||||
if rule.Path != nil && rule.Regex == nil {
|
||||
// Path _only_ rule
|
||||
if rule.Path.Match([]byte(fragment.FilePath)) {
|
||||
finding := report.Finding{
|
||||
Description: rule.Description,
|
||||
File: fragment.FilePath,
|
||||
RuleID: rule.RuleID,
|
||||
Match: fmt.Sprintf("file detected: %s", fragment.FilePath),
|
||||
Tags: rule.Tags,
|
||||
}
|
||||
return append(findings, finding)
|
||||
}
|
||||
} else if rule.Path != nil {
|
||||
// if path is set _and_ a regex is set, then we need to check both
|
||||
// so if the path does not match, then we should return early and not
|
||||
// consider the regex
|
||||
if !rule.Path.Match([]byte(fragment.FilePath)) {
|
||||
return findings
|
||||
}
|
||||
}
|
||||
|
||||
// if path only rule, skip content checks
|
||||
if rule.Regex == nil {
|
||||
return findings
|
||||
}
|
||||
|
||||
matchIndices := rule.Regex.FindAllStringIndex(fragment.Raw, -1)
|
||||
for _, matchIndex := range matchIndices {
|
||||
// extract secret from match
|
||||
secret := strings.Trim(fragment.Raw[matchIndex[0]:matchIndex[1]], "\n")
|
||||
|
||||
// determine location of match. Note that the location
|
||||
// in the finding will be the line/column numbers of the _match_
|
||||
// not the _secret_, which will be different if the secretGroup
|
||||
// value is set for this rule
|
||||
loc := location(fragment, matchIndex)
|
||||
|
||||
finding := report.Finding{
|
||||
Description: rule.Description,
|
||||
File: fragment.FilePath,
|
||||
RuleID: rule.RuleID,
|
||||
StartLine: loc.startLine,
|
||||
EndLine: loc.endLine,
|
||||
StartColumn: loc.startColumn,
|
||||
EndColumn: loc.endColumn,
|
||||
Secret: secret,
|
||||
Match: secret,
|
||||
Tags: rule.Tags,
|
||||
}
|
||||
|
||||
if strings.Contains(fragment.Raw[loc.startLineIndex:loc.endLineIndex],
|
||||
gitleaksAllowSignature) {
|
||||
continue
|
||||
}
|
||||
|
||||
// check if the secret is in the allowlist
|
||||
if rule.Allowlist.RegexAllowed(finding.Secret) ||
|
||||
d.Config.Allowlist.RegexAllowed(finding.Secret) {
|
||||
continue
|
||||
}
|
||||
|
||||
// extract secret from secret group if set
|
||||
if rule.SecretGroup != 0 {
|
||||
groups := rule.Regex.FindStringSubmatch(secret)
|
||||
if len(groups) <= rule.SecretGroup || len(groups) == 0 {
|
||||
// Config validation should prevent this
|
||||
continue
|
||||
}
|
||||
secret = groups[rule.SecretGroup]
|
||||
finding.Secret = secret
|
||||
}
|
||||
|
||||
// check entropy
|
||||
entropy := shannonEntropy(finding.Secret)
|
||||
finding.Entropy = float32(entropy)
|
||||
if rule.Entropy != 0.0 {
|
||||
if entropy <= rule.Entropy {
|
||||
// entropy is too low, skip this finding
|
||||
continue
|
||||
}
|
||||
// NOTE: this is a goofy hack to get around the fact there golang's regex engine
|
||||
// does not support positive lookaheads. Ideally we would want to add a
|
||||
// restriction on generic rules regex that requires the secret match group
|
||||
// contains both numbers and alphabetical characters, not just alphabetical characters.
|
||||
// What this bit of code does is check if the ruleid is prepended with "generic" and enforces the
|
||||
// secret contains both digits and alphabetical characters.
|
||||
// TODO: this should be replaced with stop words
|
||||
if strings.HasPrefix(rule.RuleID, "generic") {
|
||||
if !containsDigit(secret) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
findings = append(findings, finding)
|
||||
}
|
||||
return findings
|
||||
}
|
||||
|
||||
// GitScan accepts a *gitdiff.File channel which contents a git history generated from
|
||||
// the output of `git log -p ...`. startGitScan will look at each file (patch) in the history
|
||||
// and determine if the patch contains any findings.
|
||||
func (d *Detector) DetectGit(source string, logOpts string, gitScanType GitScanType) ([]report.Finding, error) {
|
||||
var (
|
||||
gitdiffFiles <-chan *gitdiff.File
|
||||
err error
|
||||
)
|
||||
switch gitScanType {
|
||||
case DetectType:
|
||||
gitdiffFiles, err = git.GitLog(source, logOpts)
|
||||
if err != nil {
|
||||
return d.findings, err
|
||||
}
|
||||
case ProtectType:
|
||||
gitdiffFiles, err = git.GitDiff(source, false)
|
||||
if err != nil {
|
||||
return d.findings, err
|
||||
}
|
||||
case ProtectStagedType:
|
||||
gitdiffFiles, err = git.GitDiff(source, true)
|
||||
if err != nil {
|
||||
return d.findings, err
|
||||
}
|
||||
}
|
||||
|
||||
s := semgroup.NewGroup(context.Background(), 4)
|
||||
|
||||
for gitdiffFile := range gitdiffFiles {
|
||||
gitdiffFile := gitdiffFile
|
||||
|
||||
// skip binary files
|
||||
if gitdiffFile.IsBinary || gitdiffFile.IsDelete {
|
||||
continue
|
||||
}
|
||||
|
||||
// Check if commit is allowed
|
||||
commitSHA := ""
|
||||
if gitdiffFile.PatchHeader != nil {
|
||||
commitSHA = gitdiffFile.PatchHeader.SHA
|
||||
if d.Config.Allowlist.CommitAllowed(gitdiffFile.PatchHeader.SHA) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
d.addCommit(commitSHA)
|
||||
|
||||
s.Go(func() error {
|
||||
for _, textFragment := range gitdiffFile.TextFragments {
|
||||
if textFragment == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
fragment := Fragment{
|
||||
Raw: textFragment.Raw(gitdiff.OpAdd),
|
||||
CommitSHA: commitSHA,
|
||||
FilePath: gitdiffFile.NewName,
|
||||
}
|
||||
|
||||
for _, finding := range d.Detect(fragment) {
|
||||
d.addFinding(augmentGitFinding(finding, textFragment, gitdiffFile))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
if err := s.Wait(); err != nil {
|
||||
return d.findings, err
|
||||
}
|
||||
log.Debug().Msgf("%d commits scanned. Note: this number might be smaller than expected due to commits with no additions", len(d.commitMap))
|
||||
return d.findings, nil
|
||||
}
|
||||
|
||||
// DetectFiles accepts a path to a source directory or file and begins a scan of the
|
||||
// file or directory.
|
||||
func (d *Detector) DetectFiles(source string) ([]report.Finding, error) {
|
||||
s := semgroup.NewGroup(context.Background(), 4)
|
||||
paths := make(chan string)
|
||||
s.Go(func() error {
|
||||
defer close(paths)
|
||||
return filepath.Walk(source,
|
||||
func(path string, fInfo os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if fInfo.Name() == ".git" {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
if fInfo.Mode().IsRegular() {
|
||||
paths <- path
|
||||
}
|
||||
return nil
|
||||
})
|
||||
})
|
||||
for pa := range paths {
|
||||
p := pa
|
||||
s.Go(func() error {
|
||||
b, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
mimetype, err := filetype.Match(b)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if mimetype.MIME.Type == "application" {
|
||||
return nil // skip binary files
|
||||
}
|
||||
|
||||
fragment := Fragment{
|
||||
Raw: string(b),
|
||||
FilePath: p,
|
||||
}
|
||||
for _, finding := range d.Detect(fragment) {
|
||||
// need to add 1 since line counting starts at 1
|
||||
finding.EndLine++
|
||||
finding.StartLine++
|
||||
d.addFinding(finding)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
if err := s.Wait(); err != nil {
|
||||
return d.findings, err
|
||||
}
|
||||
|
||||
return d.findings, nil
|
||||
}
|
||||
|
||||
// Detect scans the given fragment and returns a list of findings
|
||||
func (d *Detector) Detect(fragment Fragment) []report.Finding {
|
||||
var findings []report.Finding
|
||||
|
||||
// initiate fragment keywords
|
||||
fragment.keywords = make(map[string]bool)
|
||||
|
||||
// check if filepath is allowed
|
||||
if fragment.FilePath != "" && (d.Config.Allowlist.PathAllowed(fragment.FilePath) ||
|
||||
fragment.FilePath == d.Config.Path) {
|
||||
return findings
|
||||
}
|
||||
|
||||
// add newline indices for location calculation in detectRule
|
||||
fragment.newlineIndices = regexp.MustCompile("\n").FindAllStringIndex(fragment.Raw, -1)
|
||||
|
||||
// build keyword map for prefiltering rules
|
||||
normalizedRaw := strings.ToLower(fragment.Raw)
|
||||
matches := d.prefilter.FindAll(normalizedRaw)
|
||||
for _, m := range matches {
|
||||
fragment.keywords[normalizedRaw[m.Start():m.End()]] = true
|
||||
}
|
||||
|
||||
for _, rule := range d.Config.Rules {
|
||||
if len(rule.Keywords) == 0 {
|
||||
// if not keywords are associated with the rule always scan the
|
||||
// fragment using the rule
|
||||
findings = append(findings, d.detectRule(fragment, rule)...)
|
||||
continue
|
||||
}
|
||||
fragmentContainsKeyword := false
|
||||
// check if keywords are in the fragment
|
||||
for _, k := range rule.Keywords {
|
||||
if _, ok := fragment.keywords[strings.ToLower(k)]; ok {
|
||||
fragmentContainsKeyword = true
|
||||
}
|
||||
}
|
||||
if fragmentContainsKeyword {
|
||||
findings = append(findings, d.detectRule(fragment, rule)...)
|
||||
}
|
||||
}
|
||||
return filter(findings, d.Redact)
|
||||
}
|
||||
|
||||
// addFinding synchronously adds a finding to the findings slice
|
||||
func (d *Detector) addFinding(finding report.Finding) {
|
||||
d.findingMutex.Lock()
|
||||
d.findings = append(d.findings, finding)
|
||||
if d.Verbose {
|
||||
printFinding(finding)
|
||||
}
|
||||
d.findingMutex.Unlock()
|
||||
}
|
||||
|
||||
// addCommit synchronously adds a commit to the commit slice
|
||||
func (d *Detector) addCommit(commit string) {
|
||||
d.commitMap[commit] = true
|
||||
}
|
||||
@@ -0,0 +1,495 @@
|
||||
package detect
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/report"
|
||||
)
|
||||
|
||||
const configPath = "../testdata/config/"
|
||||
const repoBasePath = "../testdata/repos/"
|
||||
|
||||
func TestDetect(t *testing.T) {
|
||||
tests := []struct {
|
||||
cfgName string
|
||||
fragment Fragment
|
||||
expectedFindings []report.Finding
|
||||
wantError error
|
||||
}{
|
||||
{
|
||||
cfgName: "simple",
|
||||
fragment: Fragment{
|
||||
Raw: `awsToken := \"AKIALALEMEL33243OKIA\ // gitleaks:allow"`,
|
||||
FilePath: "tmp.go",
|
||||
},
|
||||
expectedFindings: []report.Finding{},
|
||||
},
|
||||
{
|
||||
cfgName: "simple",
|
||||
fragment: Fragment{
|
||||
Raw: `awsToken := \
|
||||
|
||||
\"AKIALALEMEL33243OKIA\ // gitleaks:allow"
|
||||
|
||||
|
||||
`,
|
||||
FilePath: "tmp.go",
|
||||
},
|
||||
expectedFindings: []report.Finding{},
|
||||
},
|
||||
{
|
||||
cfgName: "simple",
|
||||
fragment: Fragment{
|
||||
Raw: `awsToken := \"AKIALALEMEL33243OKIA\"
|
||||
|
||||
// gitleaks:allow"
|
||||
|
||||
`,
|
||||
FilePath: "tmp.go",
|
||||
},
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
Description: "AWS Access Key",
|
||||
Secret: "AKIALALEMEL33243OKIA",
|
||||
Match: "AKIALALEMEL33243OKIA",
|
||||
File: "tmp.go",
|
||||
RuleID: "aws-access-key",
|
||||
Tags: []string{"key", "AWS"},
|
||||
StartLine: 0,
|
||||
EndLine: 0,
|
||||
StartColumn: 15,
|
||||
EndColumn: 34,
|
||||
Entropy: 3.1464393,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
cfgName: "escaped_character_group",
|
||||
fragment: Fragment{
|
||||
Raw: `pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB`,
|
||||
FilePath: "tmp.go",
|
||||
},
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
Description: "PyPI upload token",
|
||||
Secret: "pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB",
|
||||
Match: "pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB",
|
||||
File: "tmp.go",
|
||||
RuleID: "pypi-upload-token",
|
||||
Tags: []string{"key", "pypi"},
|
||||
StartLine: 1,
|
||||
EndLine: 1,
|
||||
StartColumn: 1,
|
||||
EndColumn: 86,
|
||||
Entropy: 1.9606875,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
cfgName: "simple",
|
||||
fragment: Fragment{
|
||||
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
|
||||
FilePath: "tmp.go",
|
||||
},
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
Description: "AWS Access Key",
|
||||
Secret: "AKIALALEMEL33243OLIA",
|
||||
Match: "AKIALALEMEL33243OLIA",
|
||||
File: "tmp.go",
|
||||
RuleID: "aws-access-key",
|
||||
Tags: []string{"key", "AWS"},
|
||||
StartLine: 1,
|
||||
EndLine: 1,
|
||||
StartColumn: 15,
|
||||
EndColumn: 34,
|
||||
Entropy: 3.0841837,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
cfgName: "allow_aws_re",
|
||||
fragment: Fragment{
|
||||
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
|
||||
FilePath: "tmp.go",
|
||||
},
|
||||
expectedFindings: []report.Finding{},
|
||||
},
|
||||
{
|
||||
cfgName: "allow_path",
|
||||
fragment: Fragment{
|
||||
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
|
||||
FilePath: "tmp.go",
|
||||
},
|
||||
expectedFindings: []report.Finding{},
|
||||
},
|
||||
{
|
||||
cfgName: "allow_commit",
|
||||
fragment: Fragment{
|
||||
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
|
||||
FilePath: "tmp.go",
|
||||
CommitSHA: "allowthiscommit",
|
||||
},
|
||||
expectedFindings: []report.Finding{},
|
||||
},
|
||||
{
|
||||
cfgName: "entropy_group",
|
||||
fragment: Fragment{
|
||||
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
|
||||
FilePath: "tmp.go",
|
||||
},
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
Description: "Discord API key",
|
||||
Match: "Discord_Public_Key = \"e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5\"",
|
||||
Secret: "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5",
|
||||
File: "tmp.go",
|
||||
RuleID: "discord-api-key",
|
||||
Tags: []string{},
|
||||
Entropy: 3.7906237,
|
||||
StartLine: 1,
|
||||
EndLine: 1,
|
||||
StartColumn: 7,
|
||||
EndColumn: 93,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
cfgName: "generic_with_py_path",
|
||||
fragment: Fragment{
|
||||
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
|
||||
FilePath: "tmp.go",
|
||||
},
|
||||
expectedFindings: []report.Finding{},
|
||||
},
|
||||
{
|
||||
cfgName: "generic_with_py_path",
|
||||
fragment: Fragment{
|
||||
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
|
||||
FilePath: "tmp.py",
|
||||
},
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
Description: "Generic API Key",
|
||||
Match: "Key = \"e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5\"",
|
||||
Secret: "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5",
|
||||
File: "tmp.py",
|
||||
RuleID: "generic-api-key",
|
||||
Tags: []string{},
|
||||
Entropy: 3.7906237,
|
||||
StartLine: 1,
|
||||
EndLine: 1,
|
||||
StartColumn: 22,
|
||||
EndColumn: 93,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
cfgName: "path_only",
|
||||
fragment: Fragment{
|
||||
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
|
||||
FilePath: "tmp.py",
|
||||
},
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
Description: "Python Files",
|
||||
Match: "file detected: tmp.py",
|
||||
File: "tmp.py",
|
||||
RuleID: "python-files-only",
|
||||
Tags: []string{},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
cfgName: "bad_entropy_group",
|
||||
fragment: Fragment{
|
||||
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"),
|
||||
},
|
||||
{
|
||||
cfgName: "simple",
|
||||
fragment: Fragment{
|
||||
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
|
||||
FilePath: filepath.Join(configPath, "simple.toml"),
|
||||
},
|
||||
expectedFindings: []report.Finding{},
|
||||
},
|
||||
{
|
||||
cfgName: "allow_global_aws_re",
|
||||
fragment: Fragment{
|
||||
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
|
||||
FilePath: "tmp.go",
|
||||
},
|
||||
expectedFindings: []report.Finding{},
|
||||
},
|
||||
{
|
||||
cfgName: "generic_with_py_path",
|
||||
fragment: Fragment{
|
||||
Raw: `const Discord_Public_Key = "load2523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
|
||||
FilePath: "tmp.py",
|
||||
},
|
||||
expectedFindings: []report.Finding{},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
viper.Reset()
|
||||
viper.AddConfigPath(configPath)
|
||||
viper.SetConfigName(tt.cfgName)
|
||||
viper.SetConfigType("toml")
|
||||
err := viper.ReadInConfig()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
var vc config.ViperConfig
|
||||
err = viper.Unmarshal(&vc)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
cfg, err := vc.Translate()
|
||||
cfg.Path = filepath.Join(configPath, tt.cfgName+".toml")
|
||||
if tt.wantError != nil {
|
||||
if err == nil {
|
||||
t.Errorf("expected error")
|
||||
}
|
||||
assert.Equal(t, tt.wantError, err)
|
||||
}
|
||||
d := NewDetector(cfg)
|
||||
|
||||
findings := d.Detect(tt.fragment)
|
||||
assert.ElementsMatch(t, tt.expectedFindings, findings)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFromGit tests the FromGit function
|
||||
func TestFromGit(t *testing.T) {
|
||||
tests := []struct {
|
||||
cfgName string
|
||||
source string
|
||||
logOpts string
|
||||
expectedFindings []report.Finding
|
||||
}{
|
||||
{
|
||||
source: filepath.Join(repoBasePath, "small"),
|
||||
cfgName: "simple",
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
Description: "AWS Access Key",
|
||||
StartLine: 20,
|
||||
EndLine: 20,
|
||||
StartColumn: 19,
|
||||
EndColumn: 38,
|
||||
Secret: "AKIALALEMEL33243OLIA",
|
||||
Match: "AKIALALEMEL33243OLIA",
|
||||
File: "main.go",
|
||||
Date: "2021-11-02T23:37:53Z",
|
||||
Commit: "1b6da43b82b22e4eaa10bcf8ee591e91abbfc587",
|
||||
Author: "Zachary Rice",
|
||||
Email: "zricer@protonmail.com",
|
||||
Message: "Accidentally add a secret",
|
||||
RuleID: "aws-access-key",
|
||||
Tags: []string{"key", "AWS"},
|
||||
Entropy: 3.0841837,
|
||||
},
|
||||
{
|
||||
Description: "AWS Access Key",
|
||||
StartLine: 9,
|
||||
EndLine: 9,
|
||||
StartColumn: 17,
|
||||
EndColumn: 36,
|
||||
Secret: "AKIALALEMEL33243OLIA",
|
||||
Match: "AKIALALEMEL33243OLIA",
|
||||
File: "foo/foo.go",
|
||||
Date: "2021-11-02T23:48:06Z",
|
||||
Commit: "491504d5a31946ce75e22554cc34203d8e5ff3ca",
|
||||
Author: "Zach Rice",
|
||||
Email: "zricer@protonmail.com",
|
||||
Message: "adding foo package with secret",
|
||||
RuleID: "aws-access-key",
|
||||
Tags: []string{"key", "AWS"},
|
||||
Entropy: 3.0841837,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
source: filepath.Join(repoBasePath, "small"),
|
||||
logOpts: "--all foo...",
|
||||
cfgName: "simple",
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
Description: "AWS Access Key",
|
||||
StartLine: 9,
|
||||
EndLine: 9,
|
||||
StartColumn: 17,
|
||||
EndColumn: 36,
|
||||
Secret: "AKIALALEMEL33243OLIA",
|
||||
Match: "AKIALALEMEL33243OLIA",
|
||||
Date: "2021-11-02T23:48:06Z",
|
||||
File: "foo/foo.go",
|
||||
Commit: "491504d5a31946ce75e22554cc34203d8e5ff3ca",
|
||||
Author: "Zach Rice",
|
||||
Email: "zricer@protonmail.com",
|
||||
Message: "adding foo package with secret",
|
||||
RuleID: "aws-access-key",
|
||||
Tags: []string{"key", "AWS"},
|
||||
Entropy: 3.0841837,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
err := moveDotGit("dotGit", ".git")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
if err := moveDotGit(".git", "dotGit"); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}()
|
||||
|
||||
for _, tt := range tests {
|
||||
|
||||
viper.AddConfigPath(configPath)
|
||||
viper.SetConfigName("simple")
|
||||
viper.SetConfigType("toml")
|
||||
err = viper.ReadInConfig()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
var vc config.ViperConfig
|
||||
err = viper.Unmarshal(&vc)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
cfg, err := vc.Translate()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
detector := NewDetector(cfg)
|
||||
findings, err := detector.DetectGit(tt.source, tt.logOpts, DetectType)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
for _, f := range findings {
|
||||
f.Match = "" // remove lines cause copying and pasting them has some wack formatting
|
||||
}
|
||||
assert.ElementsMatch(t, tt.expectedFindings, findings)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFromGit tests the FromGit function
|
||||
func TestFromFiles(t *testing.T) {
|
||||
tests := []struct {
|
||||
cfgName string
|
||||
source string
|
||||
expectedFindings []report.Finding
|
||||
}{
|
||||
{
|
||||
source: filepath.Join(repoBasePath, "nogit"),
|
||||
cfgName: "simple",
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
Description: "AWS Access Key",
|
||||
StartLine: 20,
|
||||
EndLine: 20,
|
||||
StartColumn: 16,
|
||||
EndColumn: 35,
|
||||
Match: "AKIALALEMEL33243OLIA",
|
||||
Secret: "AKIALALEMEL33243OLIA",
|
||||
File: "../testdata/repos/nogit/main.go",
|
||||
RuleID: "aws-access-key",
|
||||
Tags: []string{"key", "AWS"},
|
||||
Entropy: 3.0841837,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
source: filepath.Join(repoBasePath, "nogit", "main.go"),
|
||||
cfgName: "simple",
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
Description: "AWS Access Key",
|
||||
StartLine: 20,
|
||||
EndLine: 20,
|
||||
StartColumn: 16,
|
||||
EndColumn: 35,
|
||||
Match: "AKIALALEMEL33243OLIA",
|
||||
Secret: "AKIALALEMEL33243OLIA",
|
||||
File: "../testdata/repos/nogit/main.go",
|
||||
RuleID: "aws-access-key",
|
||||
Tags: []string{"key", "AWS"},
|
||||
Entropy: 3.0841837,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
viper.AddConfigPath(configPath)
|
||||
viper.SetConfigName("simple")
|
||||
viper.SetConfigType("toml")
|
||||
err := viper.ReadInConfig()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
var vc config.ViperConfig
|
||||
err = viper.Unmarshal(&vc)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
cfg, _ := vc.Translate()
|
||||
detector := NewDetector(cfg)
|
||||
findings, err := detector.DetectFiles(tt.source)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
assert.ElementsMatch(t, tt.expectedFindings, findings)
|
||||
}
|
||||
}
|
||||
|
||||
func moveDotGit(from, to string) error {
|
||||
repoDirs, err := os.ReadDir("../testdata/repos")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, dir := range repoDirs {
|
||||
if to == ".git" {
|
||||
_, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), "dotGit"))
|
||||
if os.IsNotExist(err) {
|
||||
// dont want to delete the only copy of .git accidentally
|
||||
continue
|
||||
}
|
||||
os.RemoveAll(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), ".git"))
|
||||
}
|
||||
if !dir.IsDir() {
|
||||
continue
|
||||
}
|
||||
_, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from))
|
||||
if os.IsNotExist(err) {
|
||||
continue
|
||||
}
|
||||
|
||||
err = os.Rename(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from),
|
||||
fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), to))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gitleaks/go-gitdiff/gitdiff"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// GitLog returns a channel of gitdiff.File objects from the
|
||||
// git log -p command for the given source.
|
||||
func GitLog(source string, logOpts string) (<-chan *gitdiff.File, error) {
|
||||
sourceClean := filepath.Clean(source)
|
||||
var cmd *exec.Cmd
|
||||
if logOpts != "" {
|
||||
args := []string{"-C", sourceClean, "log", "-p", "-U0"}
|
||||
args = append(args, strings.Split(logOpts, " ")...)
|
||||
cmd = exec.Command("git", args...)
|
||||
} else {
|
||||
cmd = exec.Command("git", "-C", sourceClean, "log", "-p", "-U0",
|
||||
"--full-history", "--all")
|
||||
}
|
||||
|
||||
log.Debug().Msgf("executing: %s", cmd.String())
|
||||
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stderr, err := cmd.StderrPipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := cmd.Start(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
go listenForStdErr(stderr)
|
||||
// HACK: to avoid https://github.com/zricethezav/gitleaks/issues/722
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
|
||||
return gitdiff.Parse(stdout)
|
||||
}
|
||||
|
||||
// GitDiff returns a channel of gitdiff.File objects from
|
||||
// the git diff command for the given source.
|
||||
func GitDiff(source string, staged bool) (<-chan *gitdiff.File, error) {
|
||||
sourceClean := filepath.Clean(source)
|
||||
var cmd *exec.Cmd
|
||||
cmd = exec.Command("git", "-C", sourceClean, "diff", "-U0", ".")
|
||||
if staged {
|
||||
cmd = exec.Command("git", "-C", sourceClean, "diff", "-U0",
|
||||
"--staged", ".")
|
||||
}
|
||||
log.Debug().Msgf("executing: %s", cmd.String())
|
||||
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stderr, err := cmd.StderrPipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := cmd.Start(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
go listenForStdErr(stderr)
|
||||
// HACK: to avoid https://github.com/zricethezav/gitleaks/issues/722
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
|
||||
return gitdiff.Parse(stdout)
|
||||
}
|
||||
|
||||
// listenForStdErr listens for stderr output from git and prints it to stdout
|
||||
// then exits with exit code 1
|
||||
func listenForStdErr(stderr io.ReadCloser) {
|
||||
scanner := bufio.NewScanner(stderr)
|
||||
errEncountered := false
|
||||
for scanner.Scan() {
|
||||
// if git throws the following error:
|
||||
//
|
||||
// exhaustive rename detection was skipped due to too many files.
|
||||
// you may want to set your diff.renameLimit variable to at least
|
||||
// (some large number) and retry the command.
|
||||
//
|
||||
// we skip exiting the program as git log -p/git diff will continue
|
||||
// to send data to stdout and finish executing. This next bit of
|
||||
// code prevents gitleaks from stopping mid scan if this error is
|
||||
// encountered
|
||||
if strings.Contains(scanner.Text(),
|
||||
"exhaustive rename detection was skipped") ||
|
||||
strings.Contains(scanner.Text(),
|
||||
"you may want to set your diff.renameLimit") {
|
||||
|
||||
log.Warn().Msg(scanner.Text())
|
||||
} else {
|
||||
log.Error().Msg(scanner.Text())
|
||||
errEncountered = true
|
||||
}
|
||||
}
|
||||
if errEncountered {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package git_test
|
||||
|
||||
// TODO: commenting out this test for now because it's flaky. Alternatives to consider to get this working:
|
||||
// -- use `git stash` instead of `restore()`
|
||||
|
||||
// const repoBasePath = "../../testdata/repos/"
|
||||
|
||||
// const expectPath = "../../testdata/expected/"
|
||||
|
||||
// func TestGitLog(t *testing.T) {
|
||||
// tests := []struct {
|
||||
// source string
|
||||
// logOpts string
|
||||
// expected string
|
||||
// }{
|
||||
// {
|
||||
// source: filepath.Join(repoBasePath, "small"),
|
||||
// expected: filepath.Join(expectPath, "git", "small.txt"),
|
||||
// },
|
||||
// {
|
||||
// source: filepath.Join(repoBasePath, "small"),
|
||||
// expected: filepath.Join(expectPath, "git", "small-branch-foo.txt"),
|
||||
// logOpts: "--all foo...",
|
||||
// },
|
||||
// }
|
||||
|
||||
// err := moveDotGit("dotGit", ".git")
|
||||
// if err != nil {
|
||||
// t.Fatal(err)
|
||||
// }
|
||||
// defer func() {
|
||||
// if err = moveDotGit(".git", "dotGit"); err != nil {
|
||||
// t.Fatal(err)
|
||||
// }
|
||||
// }()
|
||||
|
||||
// for _, tt := range tests {
|
||||
// files, err := git.GitLog(tt.source, tt.logOpts)
|
||||
// if err != nil {
|
||||
// t.Error(err)
|
||||
// }
|
||||
|
||||
// var diffSb strings.Builder
|
||||
// for f := range files {
|
||||
// for _, tf := range f.TextFragments {
|
||||
// diffSb.WriteString(tf.Raw(gitdiff.OpAdd))
|
||||
// }
|
||||
// }
|
||||
|
||||
// expectedBytes, err := os.ReadFile(tt.expected)
|
||||
// if err != nil {
|
||||
// t.Error(err)
|
||||
// }
|
||||
// expected := string(expectedBytes)
|
||||
// if expected != diffSb.String() {
|
||||
// // write string builder to .got file using os.Create
|
||||
// err = os.WriteFile(strings.Replace(tt.expected, ".txt", ".got.txt", 1), []byte(diffSb.String()), 0644)
|
||||
// if err != nil {
|
||||
// t.Error(err)
|
||||
// }
|
||||
// t.Error("expected: ", expected, "got: ", diffSb.String())
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// func TestGitDiff(t *testing.T) {
|
||||
// tests := []struct {
|
||||
// source string
|
||||
// expected string
|
||||
// additions string
|
||||
// target string
|
||||
// }{
|
||||
// {
|
||||
// source: filepath.Join(repoBasePath, "small"),
|
||||
// expected: "this line is added\nand another one",
|
||||
// additions: "this line is added\nand another one",
|
||||
// target: filepath.Join(repoBasePath, "small", "main.go"),
|
||||
// },
|
||||
// }
|
||||
|
||||
// err := moveDotGit("dotGit", ".git")
|
||||
// if err != nil {
|
||||
// t.Fatal(err)
|
||||
// }
|
||||
// defer func() {
|
||||
// if err = moveDotGit(".git", "dotGit"); err != nil {
|
||||
// t.Fatal(err)
|
||||
// }
|
||||
// }()
|
||||
|
||||
// for _, tt := range tests {
|
||||
// noChanges, err := os.ReadFile(tt.target)
|
||||
// if err != nil {
|
||||
// t.Error(err)
|
||||
// }
|
||||
// err = os.WriteFile(tt.target, []byte(tt.additions), 0644)
|
||||
// if err != nil {
|
||||
// restore(tt.target, noChanges, t)
|
||||
// t.Error(err)
|
||||
// }
|
||||
|
||||
// files, err := git.GitDiff(tt.source, false)
|
||||
// if err != nil {
|
||||
// restore(tt.target, noChanges, t)
|
||||
// t.Error(err)
|
||||
// }
|
||||
|
||||
// for f := range files {
|
||||
// sb := strings.Builder{}
|
||||
// for _, tf := range f.TextFragments {
|
||||
// sb.WriteString(tf.Raw(gitdiff.OpAdd))
|
||||
// }
|
||||
// if sb.String() != tt.expected {
|
||||
// restore(tt.target, noChanges, t)
|
||||
// t.Error("expected: ", tt.expected, "got: ", sb.String())
|
||||
// }
|
||||
// }
|
||||
// restore(tt.target, noChanges, t)
|
||||
// }
|
||||
// }
|
||||
|
||||
// func restore(path string, data []byte, t *testing.T) {
|
||||
// err := os.WriteFile(path, data, 0644)
|
||||
// if err != nil {
|
||||
// t.Fatal(err)
|
||||
// }
|
||||
// }
|
||||
|
||||
// func moveDotGit(from, to string) error {
|
||||
// repoDirs, err := os.ReadDir("../../testdata/repos")
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// for _, dir := range repoDirs {
|
||||
// if to == ".git" {
|
||||
// _, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), "dotGit"))
|
||||
// if os.IsNotExist(err) {
|
||||
// // dont want to delete the only copy of .git accidentally
|
||||
// continue
|
||||
// }
|
||||
// os.RemoveAll(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), ".git"))
|
||||
// }
|
||||
// if !dir.IsDir() {
|
||||
// continue
|
||||
// }
|
||||
// _, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from))
|
||||
// if os.IsNotExist(err) {
|
||||
// continue
|
||||
// }
|
||||
|
||||
// err = os.Rename(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from),
|
||||
// fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), to))
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// }
|
||||
// return nil
|
||||
// }
|
||||
@@ -0,0 +1,66 @@
|
||||
package detect
|
||||
|
||||
// Location represents a location in a file
|
||||
type Location struct {
|
||||
startLine int
|
||||
endLine int
|
||||
startColumn int
|
||||
endColumn int
|
||||
startLineIndex int
|
||||
endLineIndex int
|
||||
}
|
||||
|
||||
func location(fragment Fragment, matchIndex []int) Location {
|
||||
var (
|
||||
prevNewLine int
|
||||
location Location
|
||||
lineSet bool
|
||||
_lineNum int
|
||||
)
|
||||
|
||||
start := matchIndex[0]
|
||||
end := matchIndex[1]
|
||||
|
||||
for lineNum, pair := range fragment.newlineIndices {
|
||||
newLineByteIndex := pair[0]
|
||||
if prevNewLine <= start && start < newLineByteIndex {
|
||||
lineSet = true
|
||||
location.startLine = lineNum
|
||||
location.endLine = lineNum
|
||||
location.startColumn = (start - prevNewLine) + 1 // +1 because counting starts at 1
|
||||
location.startLineIndex = prevNewLine
|
||||
location.endLineIndex = newLineByteIndex
|
||||
}
|
||||
if prevNewLine < end && end <= newLineByteIndex {
|
||||
location.endLine = lineNum
|
||||
location.endColumn = (end - prevNewLine)
|
||||
location.endLineIndex = newLineByteIndex
|
||||
}
|
||||
prevNewLine = pair[0]
|
||||
}
|
||||
|
||||
if !lineSet {
|
||||
// if lines never get set then that means the secret is most likely
|
||||
// on the last line of the diff output and the diff output does not have
|
||||
// a newline
|
||||
location.startColumn = (start - prevNewLine) + 1 // +1 because counting starts at 1
|
||||
location.endColumn = (end - prevNewLine)
|
||||
location.startLine = _lineNum + 1
|
||||
location.endLine = _lineNum + 1
|
||||
location.startLineIndex = start
|
||||
|
||||
// search for new line byte index
|
||||
i := 0
|
||||
for end+i < len(fragment.Raw) {
|
||||
if fragment.Raw[end+i] == '\n' {
|
||||
break
|
||||
}
|
||||
if fragment.Raw[end+i] == '\r' {
|
||||
break
|
||||
}
|
||||
i++
|
||||
}
|
||||
location.endLineIndex = end + i
|
||||
}
|
||||
return location
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package detect
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestGetLocation tests the getLocation function.
|
||||
func TestGetLocation(t *testing.T) {
|
||||
tests := []struct {
|
||||
linePairs [][]int
|
||||
start int
|
||||
end int
|
||||
wantLocation Location
|
||||
}{
|
||||
{
|
||||
linePairs: [][]int{
|
||||
{0, 39},
|
||||
{40, 55},
|
||||
{56, 57},
|
||||
},
|
||||
start: 35,
|
||||
end: 38,
|
||||
wantLocation: Location{
|
||||
startLine: 1,
|
||||
startColumn: 36,
|
||||
endLine: 1,
|
||||
endColumn: 38,
|
||||
startLineIndex: 0,
|
||||
endLineIndex: 40,
|
||||
},
|
||||
},
|
||||
{
|
||||
linePairs: [][]int{
|
||||
{0, 39},
|
||||
{40, 55},
|
||||
{56, 57},
|
||||
},
|
||||
start: 40,
|
||||
end: 44,
|
||||
wantLocation: Location{
|
||||
startLine: 2,
|
||||
startColumn: 1,
|
||||
endLine: 2,
|
||||
endColumn: 4,
|
||||
startLineIndex: 40,
|
||||
endLineIndex: 56,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
loc := location(Fragment{newlineIndices: test.linePairs}, []int{test.start, test.end})
|
||||
if loc != test.wantLocation {
|
||||
t.Errorf("\nstartLine %d\nstartColumn: %d\nendLine: %d\nendColumn: %d\nstartLineIndex: %d\nendlineIndex %d",
|
||||
loc.startLine, loc.startColumn, loc.endLine, loc.endColumn, loc.startLineIndex, loc.endLineIndex)
|
||||
|
||||
t.Error("got", loc, "want", test.wantLocation)
|
||||
}
|
||||
}
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
package detect
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/report"
|
||||
|
||||
"github.com/gitleaks/go-gitdiff/gitdiff"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// augmentGitFinding updates the start and end line numbers of a finding to include the
|
||||
// delta from the git diff
|
||||
func augmentGitFinding(finding report.Finding, textFragment *gitdiff.TextFragment, f *gitdiff.File) report.Finding {
|
||||
if !strings.HasPrefix(finding.Match, "file detected") {
|
||||
finding.StartLine += int(textFragment.NewPosition)
|
||||
finding.EndLine += int(textFragment.NewPosition)
|
||||
}
|
||||
|
||||
if f.PatchHeader != nil {
|
||||
finding.Commit = f.PatchHeader.SHA
|
||||
finding.Message = f.PatchHeader.Message()
|
||||
if f.PatchHeader.Author != nil {
|
||||
finding.Author = f.PatchHeader.Author.Name
|
||||
finding.Email = f.PatchHeader.Author.Email
|
||||
}
|
||||
finding.Date = f.PatchHeader.AuthorDate.UTC().Format(time.RFC3339)
|
||||
}
|
||||
return finding
|
||||
}
|
||||
|
||||
// shannonEntropy calculates the entropy of data using the formula defined here:
|
||||
// https://en.wiktionary.org/wiki/Shannon_entropy
|
||||
// Another way to think about what this is doing is calculating the number of bits
|
||||
// needed to on average encode the data. So, the higher the entropy, the more random the data, the
|
||||
// more bits needed to encode that data.
|
||||
func shannonEntropy(data string) (entropy float64) {
|
||||
if data == "" {
|
||||
return 0
|
||||
}
|
||||
|
||||
charCounts := make(map[rune]int)
|
||||
for _, char := range data {
|
||||
charCounts[char]++
|
||||
}
|
||||
|
||||
invLength := 1.0 / float64(len(data))
|
||||
for _, count := range charCounts {
|
||||
freq := float64(count) * invLength
|
||||
entropy -= freq * math.Log2(freq)
|
||||
}
|
||||
|
||||
return entropy
|
||||
}
|
||||
|
||||
// filter will dedupe and redact findings
|
||||
func filter(findings []report.Finding, redact bool) []report.Finding {
|
||||
var retFindings []report.Finding
|
||||
for _, f := range findings {
|
||||
include := true
|
||||
if strings.Contains(strings.ToLower(f.RuleID), "generic") {
|
||||
for _, fPrime := range findings {
|
||||
if f.StartLine == fPrime.StartLine &&
|
||||
f.EndLine == fPrime.EndLine &&
|
||||
f.Commit == fPrime.Commit &&
|
||||
f.RuleID != fPrime.RuleID &&
|
||||
strings.Contains(fPrime.Secret, f.Secret) &&
|
||||
!strings.Contains(strings.ToLower(fPrime.RuleID), "generic") {
|
||||
|
||||
genericMatch := strings.Replace(f.Match, f.Secret, "REDACTED", -1)
|
||||
betterMatch := strings.Replace(fPrime.Match, fPrime.Secret, "REDACTED", -1)
|
||||
log.Debug().Msgf("skipping %s finding (%s), %s rule takes precendence (%s)", f.RuleID, genericMatch, fPrime.RuleID, betterMatch)
|
||||
include = false
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if redact {
|
||||
f.Redact()
|
||||
}
|
||||
if include {
|
||||
retFindings = append(retFindings, f)
|
||||
}
|
||||
}
|
||||
return retFindings
|
||||
}
|
||||
|
||||
func printFinding(f report.Finding) {
|
||||
var b []byte
|
||||
b, _ = json.MarshalIndent(f, "", " ")
|
||||
fmt.Println(string(b))
|
||||
}
|
||||
|
||||
func containsDigit(s string) bool {
|
||||
for _, c := range s {
|
||||
switch c {
|
||||
case '1', '2', '3', '4', '5', '6', '7', '8', '9':
|
||||
return true
|
||||
}
|
||||
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -1,169 +0,0 @@
|
||||
title = "gitleaks config"
|
||||
|
||||
[[rules]]
|
||||
description = "AWS Manager ID"
|
||||
regex = '''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
|
||||
tags = ["key", "AWS"]
|
||||
|
||||
[[rules]]
|
||||
description = "AWS cred file info"
|
||||
regex = '''(?i)(aws_access_key_id|aws_secret_access_key)(.{0,20})?=.[0-9a-zA-Z\/+]{20,40}'''
|
||||
tags = ["AWS"]
|
||||
|
||||
[[rules]]
|
||||
description = "AWS Secret Key"
|
||||
regex = '''(?i)aws(.{0,20})?(?-i)['\"][0-9a-zA-Z\/+]{40}['\"]'''
|
||||
tags = ["key", "AWS"]
|
||||
|
||||
[[rules]]
|
||||
description = "AWS MWS key"
|
||||
regex = '''amzn\.mws\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'''
|
||||
tags = ["key", "AWS", "MWS"]
|
||||
|
||||
[[rules]]
|
||||
description = "Facebook Secret Key"
|
||||
regex = '''(?i)(facebook|fb)(.{0,20})?(?-i)['\"][0-9a-f]{32}['\"]'''
|
||||
tags = ["key", "Facebook"]
|
||||
|
||||
[[rules]]
|
||||
description = "Facebook Client ID"
|
||||
regex = '''(?i)(facebook|fb)(.{0,20})?['\"][0-9]{13,17}['\"]'''
|
||||
tags = ["key", "Facebook"]
|
||||
|
||||
[[rules]]
|
||||
description = "Twitter Secret Key"
|
||||
regex = '''(?i)twitter(.{0,20})?['\"][0-9a-z]{35,44}['\"]'''
|
||||
tags = ["key", "Twitter"]
|
||||
|
||||
[[rules]]
|
||||
description = "Twitter Client ID"
|
||||
regex = '''(?i)twitter(.{0,20})?['\"][0-9a-z]{18,25}['\"]'''
|
||||
tags = ["client", "Twitter"]
|
||||
|
||||
[[rules]]
|
||||
description = "Github"
|
||||
regex = '''(?i)github(.{0,20})?(?-i)['\"][0-9a-zA-Z]{35,40}['\"]'''
|
||||
tags = ["key", "Github"]
|
||||
|
||||
[[rules]]
|
||||
description = "LinkedIn Client ID"
|
||||
regex = '''(?i)linkedin(.{0,20})?(?-i)['\"][0-9a-z]{12}['\"]'''
|
||||
tags = ["client", "LinkedIn"]
|
||||
|
||||
[[rules]]
|
||||
description = "LinkedIn Secret Key"
|
||||
regex = '''(?i)linkedin(.{0,20})?['\"][0-9a-z]{16}['\"]'''
|
||||
tags = ["secret", "LinkedIn"]
|
||||
|
||||
[[rules]]
|
||||
description = "Slack"
|
||||
regex = '''xox[baprs]-([0-9a-zA-Z]{10,48})?'''
|
||||
tags = ["key", "Slack"]
|
||||
|
||||
[[rules]]
|
||||
description = "EC"
|
||||
regex = '''-----BEGIN EC PRIVATE KEY-----'''
|
||||
tags = ["key", "EC"]
|
||||
|
||||
|
||||
[[rules]]
|
||||
description = "Google API key"
|
||||
regex = '''AIza[0-9A-Za-z\\-_]{35}'''
|
||||
tags = ["key", "Google"]
|
||||
|
||||
|
||||
[[rules]]
|
||||
description = "Heroku API key"
|
||||
regex = '''(?i)heroku(.{0,20})?['"][0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}['"]'''
|
||||
tags = ["key", "Heroku"]
|
||||
|
||||
[[rules]]
|
||||
description = "MailChimp API key"
|
||||
regex = '''(?i)(mailchimp|mc)(.{0,20})?['"][0-9a-f]{32}-us[0-9]{1,2}['"]'''
|
||||
tags = ["key", "Mailchimp"]
|
||||
|
||||
[[rules]]
|
||||
description = "Mailgun API key"
|
||||
regex = '''(?i)(mailgun|mg)(.{0,20})?['"][0-9a-z]{32}['"]'''
|
||||
tags = ["key", "Mailgun"]
|
||||
|
||||
[[rules]]
|
||||
description = "PayPal Braintree access token"
|
||||
regex = '''access_token\$production\$[0-9a-z]{16}\$[0-9a-f]{32}'''
|
||||
tags = ["key", "Paypal"]
|
||||
|
||||
[[rules]]
|
||||
description = "Picatic API key"
|
||||
regex = '''sk_live_[0-9a-z]{32}'''
|
||||
tags = ["key", "Picatic"]
|
||||
|
||||
[[rules]]
|
||||
description = "Slack Webhook"
|
||||
regex = '''https://hooks.slack.com/services/T[a-zA-Z0-9_]{8}/B[a-zA-Z0-9_]{8}/[a-zA-Z0-9_]{24}'''
|
||||
tags = ["key", "slack"]
|
||||
|
||||
[[rules]]
|
||||
description = "Stripe API key"
|
||||
regex = '''(?i)stripe(.{0,20})?['\"][sk|rk]_live_[0-9a-zA-Z]{24}'''
|
||||
tags = ["key", "Stripe"]
|
||||
|
||||
[[rules]]
|
||||
description = "Square access token"
|
||||
regex = '''sq0atp-[0-9A-Za-z\-_]{22}'''
|
||||
tags = ["key", "square"]
|
||||
|
||||
[[rules]]
|
||||
description = "Square OAuth secret"
|
||||
regex = '''sq0csp-[0-9A-Za-z\\-_]{43}'''
|
||||
tags = ["key", "square"]
|
||||
|
||||
[[rules]]
|
||||
description = "Twilio API key"
|
||||
regex = '''(?i)twilio(.{0,20})?['\"][0-9a-f]{32}['\"]'''
|
||||
tags = ["key", "twilio"]
|
||||
|
||||
[[rules]]
|
||||
description = "Env Var"
|
||||
regex = '''(?i)(api_key|apikey|secret|key|api|password|pw|host)=[0-9a-zA-Z-_{}]{4,120}'''
|
||||
|
||||
[[rules]]
|
||||
description = "Port"
|
||||
regex = '''(?i)port(.{0,4})?[0-9]{1,10}'''
|
||||
|
||||
[[rules]]
|
||||
description = "Email"
|
||||
regex = '''[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}'''
|
||||
tags = ["email"]
|
||||
|
||||
[[rules]]
|
||||
description = "Generic Credential"
|
||||
regex = '''(?i)(dbpasswd|dbuser|dbname|dbhost|api_key|apikey|secret|key|api|password|user|guid|hostname|pw|auth)(.{0,20})?['|"][0-9a-zA-Z-_!{}/=]{4,120}['|"]'''
|
||||
tags = ["key", "API", "generic"]
|
||||
|
||||
[[rules]]
|
||||
description = "WP-Config"
|
||||
regex='''define(.{0,20})?(DB_CHARSET|NONCE_SALT|LOGGED_IN_SALT|AUTH_SALT|NONCE_KEY|DB_HOST|DB_PASSWORD|AUTH_KEY|SECURE_AUTH_KEY|LOGGED_IN_KEY|DB_NAME|DB_USER)(.{0,20})?['|"].{10,120}['|"]'''
|
||||
tags = ["key", "API", "generic"]
|
||||
|
||||
|
||||
[[rules]]
|
||||
description = "Pure Entropy"
|
||||
regex = '''['|"][0-9a-zA-Z-._{}$\/=]{40,120}['|"]'''
|
||||
entropies = [
|
||||
"5.0-5.6"
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
description = "Entropy plus Generic Credential"
|
||||
regex = '''(?i)(api_key|apikey|secret|key|api|password|pw)'''
|
||||
entropies = [
|
||||
"5.2-5.5"
|
||||
]
|
||||
|
||||
[Global]
|
||||
file = '''(?i)(id_rsa|passwd|id_rsa.pub|pgpass|pem|key|shadow)'''
|
||||
|
||||
[whitelist]
|
||||
description = "image whitelists"
|
||||
file = '''(.*?)(jpg|gif|doc|pdf|bin)$'''
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
#!/bin/sh
|
||||
|
||||
# This is an example of what adding gitleaks to a pre-commit hook would look like.
|
||||
|
||||
gitleaksEnabled=$(git config --bool hooks.gitleaks)
|
||||
cmd="/Users/zrice/go/src/github.com/zricethezav/gitleaks/gitleaks --verbose --redact --pretty"
|
||||
if [ $gitleaksEnabled == "true" ]; then
|
||||
$cmd
|
||||
if [ $? -eq 1 ]; then
|
||||
cat <<\EOF
|
||||
Error: gitleaks has detected sensitive information in your changes.
|
||||
If you know what you are doing you can disable this check using:
|
||||
|
||||
git config hooks.gitleaks false
|
||||
|
||||
EOF
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
@@ -1,15 +0,0 @@
|
||||
# This config contains a single rule which defines a regex and a range of entropy values. If a rule has
|
||||
# both regex and entropy then that rule uses BOTH the regex and entropy in combination when performing an audit.
|
||||
# In other words, if a line of code has an entropy value that is within the range of the entropies defined and
|
||||
# a regex match is found then that line of code contains a leak.
|
||||
|
||||
# So, for this example if a line of code has an entropy value of 4.6 AND matches the regex below then we got a leak.
|
||||
|
||||
[[rules]]
|
||||
description = "entropy and regex"
|
||||
regex = '''(?i)key(.{0,20})?['|"][0-9a-zA-Z]{16,45}['|"]'''
|
||||
entropies = [
|
||||
"4.5-4.7",
|
||||
"5.5-6.3",
|
||||
]
|
||||
tags = ["entropy"]
|
||||
Loaded 100 of 401 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user