mirror of
https://github.com/gitleaks/gitleaks.git
synced 2026-11-27 19:54:24 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6862c13bf7 | ||
|
|
9939c638ec | ||
|
|
ed3a512b4b | ||
|
|
7c988c927d | ||
|
|
bde9af44ea | ||
|
|
eee4d05642 | ||
|
|
9144594d77 | ||
|
|
1cb15242fd | ||
|
|
08498600d1 | ||
|
|
88c0c7779b | ||
|
|
67454d109e | ||
|
|
ce603c73b4 | ||
|
|
55218fc8f8 | ||
|
|
5d81c650e8 | ||
|
|
0726209172 | ||
|
|
bfec8aca51 | ||
|
|
a9b30edb06 | ||
|
|
cc6d698e63 | ||
|
|
2ba97d0fa3 | ||
|
|
d299b5aa7f | ||
|
|
0a209b60a5 | ||
|
|
fe8c6271f2 | ||
|
|
42fb085684 | ||
|
|
3faec00bf9 |
No files matched your search
@@ -1,6 +1,52 @@
|
||||
CHANGELOG
|
||||
=========
|
||||
|
||||
1.11.0
|
||||
-----
|
||||
- Commit depth option
|
||||
- Commit stats output
|
||||
|
||||
1.10.0
|
||||
-----
|
||||
- Add entropy option
|
||||
|
||||
1.9.0
|
||||
-----
|
||||
- exclude fork option
|
||||
|
||||
1.8.0
|
||||
-----
|
||||
- whitelist repos
|
||||
- sample config option
|
||||
|
||||
1.7.3
|
||||
-----
|
||||
- style points
|
||||
|
||||
1.7.2
|
||||
-----
|
||||
- Fixing dangling goroutines, removing channel messaging
|
||||
|
||||
1.7.1
|
||||
-----
|
||||
- Fixing bug where single repos were not being audited
|
||||
|
||||
1.7.0
|
||||
-----
|
||||
- Exit code == 2 on error
|
||||
- Cleaning up some logs
|
||||
- Removing some unreachable code
|
||||
|
||||
1.6.1
|
||||
-----
|
||||
- Recover from panic when diffing
|
||||
|
||||
1.6.0
|
||||
-----
|
||||
- Default maximum goroutines spawned is number of cores your cpu run with. See benchmarks in wiki.
|
||||
- Cleanup after each repo audit for organizations rather than waiting for the entire organization to complete. Eliminates risk of running out of disk space.
|
||||
|
||||
|
||||
1.5.0
|
||||
-----
|
||||
- Support for CSV reporting
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# Contributing Guidelines
|
||||
|
||||
The gitleaks project is under [GNU General Public License v3.0](LICENSE.md) and accepts
|
||||
contributions via GitHub pull requests.
|
||||
|
||||
## How to Contribute
|
||||
|
||||
Open a PR. Give the PR a descriptive title. Add some comments describing whats the purpose of the PR.
|
||||
|
||||
__BUT before you do that!__
|
||||
|
||||
Make sure you pass this list of requirements.
|
||||
|
||||
- You've ran `go fmt`.
|
||||
- You've ran `golint`.
|
||||
- Your Go changes are confined to `gitleaks_test.go` and `main.go`. This is subject to change as the project evolves. Stylistically, I like having a single go file considering the size of this project (its tiny).
|
||||
- You've added test cases for your changes.
|
||||
- You've updated [the changelog](CHANGELOG.md).
|
||||
- Your tests pass.
|
||||
|
||||
@@ -4,13 +4,12 @@ test:
|
||||
go get github.com/golang/lint/golint
|
||||
go fmt
|
||||
golint
|
||||
go test --race -cover
|
||||
go test --race --cover -run=Test$
|
||||
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)
|
||||
|
||||
build-all:
|
||||
rm -rf build
|
||||
mkdir build
|
||||
@@ -21,3 +20,8 @@ build-all:
|
||||
env GOOS="linux" GOARCH="mips" go build -o "build/gitleaks-linux-mips"
|
||||
env GOOS="linux" GOARCH="mips" go build -o "build/gitleaks-linux-mips"
|
||||
env GOOS="darwin" GOARCH="amd64" go build -o "build/gitleaks-darwin-amd64"
|
||||
benchmark:
|
||||
go test -run=Benchmark -bench=. -benchtime=5s
|
||||
benchmark-fast:
|
||||
go test -bench=BenchmarkAuditLeakRepo -run=BenchmarkAuditLeakRepo$
|
||||
|
||||
@@ -26,12 +26,13 @@ Usage:
|
||||
|
||||
Application Options:
|
||||
-r, --repo= Repo url to audit
|
||||
--github-user= User url to audit
|
||||
--github-org= Organization url to audit
|
||||
--github-user= Github user to audit
|
||||
--github-org= Github organization to audit
|
||||
--github-url= GitHub API Base URL, use for GitHub Enterprise. Example: https://github.example.com/api/v3/ (default: https://api.github.com/)
|
||||
-p, --private Include private repos in audit
|
||||
-b, --branch= branch name to audit (defaults to HEAD)
|
||||
-c, --commit= sha of commit to stop at
|
||||
--depth= maximum commit depth
|
||||
--repo-path= Path to repo
|
||||
--owner-path= Path to owner directory (repos discovered)
|
||||
--max-go= Maximum number of concurrent go-routines gitleaks spawns
|
||||
@@ -40,20 +41,24 @@ Application Options:
|
||||
--single-search= single regular expression to search for
|
||||
--config= path to gitleaks config
|
||||
--ssh-key= path to ssh key
|
||||
--exclude-forks exclude forks for organization/user audits
|
||||
-e, --entropy= Include entropy checks during audit. Entropy scale: 0.0(no entropy) - 8.0(max entropy)
|
||||
-l, --log= log level
|
||||
-v, --verbose Show verbose output from gitleaks audit
|
||||
--report= path to write report file
|
||||
--csv report output to csv
|
||||
--redact redact secrets from log messages and report
|
||||
--version version number
|
||||
--sample-config prints a sample config file
|
||||
|
||||
Help Options:
|
||||
-h, --help Show this help message
|
||||
```
|
||||
#### Exit Codes
|
||||
```
|
||||
1: leaks present
|
||||
0: no leaks
|
||||
1: leaks present
|
||||
2: error encountered
|
||||
```
|
||||
|
||||
#### Additional Examples and Explanations
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ regex = '''(?i)twitter.*['\"][0-9a-zA-Z]{35,44}['\"]'''
|
||||
|
||||
[whitelist]
|
||||
regexes = [
|
||||
"AKIA.*",
|
||||
# "AKIA.*EXAMPLE",
|
||||
]
|
||||
files = [
|
||||
"(.*?)(jpg|gif|doc|pdf|bin|go)$"
|
||||
|
||||
+291
-31
@@ -56,6 +56,46 @@ regexes= [
|
||||
]
|
||||
`
|
||||
|
||||
const testWhitelistRepo = `
|
||||
[[regexes]]
|
||||
description = "AWS"
|
||||
regex = '''AKIA[0-9A-Z]{16}'''
|
||||
|
||||
[whitelist]
|
||||
repos = [
|
||||
"gronit",
|
||||
]
|
||||
`
|
||||
|
||||
var benchmarkRepo *RepoDescriptor
|
||||
var benchmarkLeaksRepo *RepoDescriptor
|
||||
|
||||
func getBenchmarkLeaksRepo() *RepoDescriptor {
|
||||
if benchmarkLeaksRepo != nil {
|
||||
return benchmarkLeaksRepo
|
||||
}
|
||||
leaksR, _ := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
|
||||
URL: "https://github.com/gitleakstest/gronit.git",
|
||||
})
|
||||
benchmarkLeaksRepo = &RepoDescriptor{
|
||||
repository: leaksR,
|
||||
}
|
||||
return benchmarkLeaksRepo
|
||||
}
|
||||
|
||||
func getBenchmarkRepo() *RepoDescriptor {
|
||||
if benchmarkRepo != nil {
|
||||
return benchmarkRepo
|
||||
}
|
||||
bmRepo, _ := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
|
||||
URL: "https://github.com/apple/swift-package-manager.git",
|
||||
})
|
||||
benchmarkRepo = &RepoDescriptor{
|
||||
repository: bmRepo,
|
||||
}
|
||||
return benchmarkRepo
|
||||
}
|
||||
|
||||
func TestGetRepo(t *testing.T) {
|
||||
var err error
|
||||
dir, err = ioutil.TempDir("", "gitleaksTestRepo")
|
||||
@@ -128,7 +168,7 @@ func TestGetRepo(t *testing.T) {
|
||||
g.Describe("TestGetRepo", func() {
|
||||
g.It(test.description, func() {
|
||||
opts = test.testOpts
|
||||
_, err := getRepo()
|
||||
_, err := cloneRepo()
|
||||
if err != nil {
|
||||
g.Assert(err.Error()).Equal(test.expectedErrMsg)
|
||||
}
|
||||
@@ -136,11 +176,9 @@ func TestGetRepo(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartAudit(t *testing.T) {
|
||||
err := loadToml()
|
||||
func TestRun(t *testing.T) {
|
||||
var err error
|
||||
configsDir := testTomlLoader()
|
||||
defer os.RemoveAll(configsDir)
|
||||
|
||||
dir, err = ioutil.TempDir("", "gitleaksTestOwner")
|
||||
defer os.RemoveAll(dir)
|
||||
@@ -157,7 +195,9 @@ func TestStartAudit(t *testing.T) {
|
||||
testOpts Options
|
||||
description string
|
||||
expectedErrMsg string
|
||||
whiteListRepos []string
|
||||
numLeaks int
|
||||
configPath string
|
||||
}{
|
||||
{
|
||||
testOpts: Options{
|
||||
@@ -184,15 +224,6 @@ func TestStartAudit(t *testing.T) {
|
||||
numLeaks: 2,
|
||||
expectedErrMsg: "",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
GithubOrg: "gitleakstestorg",
|
||||
IncludePrivate: true,
|
||||
},
|
||||
description: "test private org no ssh",
|
||||
numLeaks: 0,
|
||||
expectedErrMsg: "no ssh auth available",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
GithubOrg: "gitleakstestorg",
|
||||
@@ -202,16 +233,6 @@ func TestStartAudit(t *testing.T) {
|
||||
numLeaks: 2,
|
||||
expectedErrMsg: "",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
GithubOrg: "gitleakstestorg",
|
||||
IncludePrivate: true,
|
||||
Disk: true,
|
||||
},
|
||||
description: "test private org on disk no ssh",
|
||||
numLeaks: 0,
|
||||
expectedErrMsg: "no ssh auth available",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
OwnerPath: dir,
|
||||
@@ -220,13 +241,68 @@ func TestStartAudit(t *testing.T) {
|
||||
numLeaks: 2,
|
||||
expectedErrMsg: "",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
GithubOrg: "gitleakstestorg",
|
||||
IncludePrivate: true,
|
||||
SSHKey: "reallyreallyreallyreallywrongpath",
|
||||
},
|
||||
description: "test private org no ssh",
|
||||
numLeaks: 0,
|
||||
expectedErrMsg: "unable to generate ssh key: open reallyreallyreallyreallywrongpath: no such file or directory",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
Repo: "https://github.com/gitleakstest/gronit.git",
|
||||
},
|
||||
description: "test leak",
|
||||
numLeaks: 2,
|
||||
expectedErrMsg: "",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
Repo: "https://github.com/gitleakstest/h1domains.git",
|
||||
},
|
||||
description: "test clean",
|
||||
numLeaks: 0,
|
||||
expectedErrMsg: "",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
Repo: "https://github.com/gitleakstest/empty.git",
|
||||
},
|
||||
description: "test empty",
|
||||
numLeaks: 0,
|
||||
expectedErrMsg: "reference not found",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
GithubOrg: "gitleakstestorg",
|
||||
},
|
||||
description: "test github org, whitelist repo",
|
||||
numLeaks: 0,
|
||||
expectedErrMsg: "",
|
||||
configPath: path.Join(configsDir, "repo"),
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
GithubOrg: "gitleakstestorg",
|
||||
ExcludeForks: true,
|
||||
},
|
||||
description: "test github org, exclude forks",
|
||||
numLeaks: 0,
|
||||
expectedErrMsg: "",
|
||||
},
|
||||
}
|
||||
g := goblin.Goblin(t)
|
||||
for _, test := range tests {
|
||||
g.Describe("TestStartAudit", func() {
|
||||
g.Describe("TestRun", func() {
|
||||
g.It(test.description, func() {
|
||||
if test.configPath != "" {
|
||||
os.Setenv("GITLEAKS_CONFIG", test.configPath)
|
||||
}
|
||||
opts = test.testOpts
|
||||
leaks, err := startAudits()
|
||||
leaks, err := run()
|
||||
if err != nil {
|
||||
g.Assert(err.Error()).Equal(test.expectedErrMsg)
|
||||
}
|
||||
@@ -301,6 +377,7 @@ func testTomlLoader() string {
|
||||
ioutil.WriteFile(path.Join(tmpDir, "branch"), []byte(testWhitelistBranch), 0644)
|
||||
ioutil.WriteFile(path.Join(tmpDir, "commit"), []byte(testWhitelistCommit), 0644)
|
||||
ioutil.WriteFile(path.Join(tmpDir, "file"), []byte(testWhitelistFile), 0644)
|
||||
ioutil.WriteFile(path.Join(tmpDir, "repo"), []byte(testWhitelistRepo), 0644)
|
||||
return tmpDir
|
||||
}
|
||||
|
||||
@@ -319,7 +396,7 @@ func TestAuditRepo(t *testing.T) {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
leaksRepo := Repo{
|
||||
leaksRepo := &RepoDescriptor{
|
||||
repository: leaksR,
|
||||
name: "gronit",
|
||||
}
|
||||
@@ -330,7 +407,7 @@ func TestAuditRepo(t *testing.T) {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
cleanRepo := Repo{
|
||||
cleanRepo := &RepoDescriptor{
|
||||
repository: cleanR,
|
||||
name: "h1domains",
|
||||
}
|
||||
@@ -340,10 +417,11 @@ func TestAuditRepo(t *testing.T) {
|
||||
description string
|
||||
expectedErrMsg string
|
||||
numLeaks int
|
||||
repo Repo
|
||||
repo *RepoDescriptor
|
||||
whiteListFiles []*regexp.Regexp
|
||||
whiteListCommits map[string]bool
|
||||
whiteListBranches []string
|
||||
whiteListRepos []string
|
||||
whiteListRegexes []*regexp.Regexp
|
||||
configPath string
|
||||
}{
|
||||
@@ -357,7 +435,7 @@ func TestAuditRepo(t *testing.T) {
|
||||
description: "two leaks present limit goroutines",
|
||||
numLeaks: 2,
|
||||
testOpts: Options{
|
||||
MaxGoRoutines: 2,
|
||||
MaxGoRoutines: 4,
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -468,6 +546,52 @@ func TestAuditRepo(t *testing.T) {
|
||||
configPath: path.Join(configsDir, "commit"),
|
||||
numLeaks: 2,
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "audit whitelist repo",
|
||||
numLeaks: 0,
|
||||
whiteListRepos: []string{
|
||||
"gronit",
|
||||
},
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "toml whitelist repo",
|
||||
numLeaks: 0,
|
||||
configPath: path.Join(configsDir, "repo"),
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "leaks present with entropy",
|
||||
testOpts: Options{
|
||||
Entropy: 4.7,
|
||||
},
|
||||
numLeaks: 7,
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "Audit until specific commit",
|
||||
numLeaks: 1,
|
||||
testOpts: Options{
|
||||
Commit: "f6839959b7bbdcd23008f1fb16f797f35bcd3a0c",
|
||||
},
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "commit depth = 1, no leaks",
|
||||
numLeaks: 0,
|
||||
testOpts: Options{
|
||||
Depth: 1,
|
||||
},
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "commit depth = 2, one leak",
|
||||
numLeaks: 1,
|
||||
testOpts: Options{
|
||||
Depth: 2,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
whiteListCommits = make(map[string]bool)
|
||||
@@ -497,6 +621,11 @@ func TestAuditRepo(t *testing.T) {
|
||||
} else {
|
||||
whiteListRegexes = nil
|
||||
}
|
||||
if test.whiteListRepos != nil {
|
||||
whiteListRepos = test.whiteListRepos
|
||||
} else {
|
||||
whiteListRepos = nil
|
||||
}
|
||||
|
||||
// config paths
|
||||
if test.configPath != "" {
|
||||
@@ -504,7 +633,7 @@ func TestAuditRepo(t *testing.T) {
|
||||
loadToml()
|
||||
}
|
||||
|
||||
leaks, err = auditRepo(test.repo)
|
||||
leaks, err = auditGitRepo(test.repo)
|
||||
|
||||
if opts.Redact {
|
||||
g.Assert(leaks[0].Offender).Equal("REDACTED")
|
||||
@@ -589,6 +718,14 @@ func TestOptionGuard(t *testing.T) {
|
||||
description: "single search regex gaurd",
|
||||
expectedErrMsg: "",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
GithubOrg: "fakeOrg",
|
||||
Entropy: 9,
|
||||
},
|
||||
description: "Invalid entropy level guard",
|
||||
expectedErrMsg: "The maximum level of entropy is 8",
|
||||
},
|
||||
}
|
||||
g := goblin.Goblin(t)
|
||||
for _, test := range tests {
|
||||
@@ -690,3 +827,126 @@ func TestLoadToml(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAuditRepo1Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 1
|
||||
benchmarkRepo = getBenchmarkRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAuditRepo2Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 2
|
||||
benchmarkRepo = getBenchmarkRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAuditRepo4Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 4
|
||||
benchmarkRepo = getBenchmarkRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAuditRepo8Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 8
|
||||
benchmarkRepo = getBenchmarkRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAuditRepo10Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 10
|
||||
benchmarkRepo = getBenchmarkRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAuditRepo100Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 100
|
||||
benchmarkRepo = getBenchmarkRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAuditRepo1000Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 1000
|
||||
benchmarkRepo = getBenchmarkRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
func BenchmarkAuditLeakRepo1Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 1
|
||||
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAuditLeakRepo2Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 2
|
||||
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAuditLeakRepo4Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 4
|
||||
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAuditLeakRepo8Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 8
|
||||
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAuditLeakRepo10Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 10
|
||||
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
func BenchmarkAuditLeakRepo100Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 100
|
||||
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
func BenchmarkAuditLeakRepo1000Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 1000
|
||||
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,10 @@ import (
|
||||
"crypto/md5"
|
||||
"encoding/csv"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -15,6 +17,7 @@ import (
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -33,7 +36,9 @@ import (
|
||||
git "gopkg.in/src-d/go-git.v4"
|
||||
)
|
||||
|
||||
// Leak represents a leaked secret or regex match. This will be output to stdout and/or the report
|
||||
// Leak represents a leaked secret or regex match.
|
||||
// Output to stdout as json if the --verbose option is set or
|
||||
// as a csv if the --csv and --report options are set.
|
||||
type Leak struct {
|
||||
Line string `json:"line"`
|
||||
Commit string `json:"commit"`
|
||||
@@ -46,23 +51,15 @@ type Leak struct {
|
||||
Repo string `json:"repo"`
|
||||
}
|
||||
|
||||
// Repo contains the actual git repository and meta data about the repo
|
||||
type Repo struct {
|
||||
// RepoDescriptor contains a src-d git repository and other data about the repo
|
||||
type RepoDescriptor struct {
|
||||
path string
|
||||
url string
|
||||
name string
|
||||
leaks []Leak
|
||||
repository *git.Repository
|
||||
err error
|
||||
}
|
||||
|
||||
// Owner contains a collection of repos. This could represent an org or user.
|
||||
type Owner struct {
|
||||
path string
|
||||
url string
|
||||
repos []Repo
|
||||
}
|
||||
|
||||
// Options for gitleaks
|
||||
type Options struct {
|
||||
// remote target options
|
||||
@@ -80,27 +77,31 @@ type Options struct {
|
||||
|
||||
Branch string `short:"b" long:"branch" description:"branch name to audit (defaults to HEAD)"`
|
||||
Commit string `short:"c" long:"commit" description:"sha of commit to stop at"`
|
||||
Depth int `long:"depth" description:"maximum commit depth"`
|
||||
|
||||
// local target option
|
||||
RepoPath string `long:"repo-path" description:"Path to repo"`
|
||||
OwnerPath string `long:"owner-path" description:"Path to owner directory (repos discovered)"`
|
||||
|
||||
// Process options
|
||||
MaxGoRoutines int `long:"max-go" description:"Maximum number of concurrent go-routines gitleaks spawns"`
|
||||
Disk bool `long:"disk" description:"Clones repo(s) to disk"`
|
||||
AuditAllRefs bool `long:"all-refs" description:"run audit on all refs"`
|
||||
SingleSearch string `long:"single-search" description:"single regular expression to search for"`
|
||||
ConfigPath string `long:"config" description:"path to gitleaks config"`
|
||||
SSHKey string `long:"ssh-key" description:"path to ssh key"`
|
||||
MaxGoRoutines int `long:"max-go" description:"Maximum number of concurrent go-routines gitleaks spawns"`
|
||||
Disk bool `long:"disk" description:"Clones repo(s) to disk"`
|
||||
AuditAllRefs bool `long:"all-refs" description:"run audit on all refs"`
|
||||
SingleSearch string `long:"single-search" description:"single regular expression to search for"`
|
||||
ConfigPath string `long:"config" description:"path to gitleaks config"`
|
||||
SSHKey string `long:"ssh-key" description:"path to ssh key"`
|
||||
ExcludeForks bool `long:"exclude-forks" description:"exclude forks for organization/user audits"`
|
||||
Entropy float64 `long:"entropy" short:"e" description:"Include entropy checks during audit. Entropy scale: 0.0(no entropy) - 8.0(max entropy)"`
|
||||
// TODO: IncludeMessages string `long:"messages" description:"include commit messages in audit"`
|
||||
|
||||
// Output options
|
||||
Log string `short:"l" long:"log" description:"log level"`
|
||||
Verbose bool `short:"v" long:"verbose" description:"Show verbose output from gitleaks audit"`
|
||||
Report string `long:"report" description:"path to write report file"`
|
||||
CSV bool `long:"csv" description:"report output to csv"`
|
||||
Redact bool `long:"redact" description:"redact secrets from log messages and report"`
|
||||
Version bool `long:"version" description:"version number"`
|
||||
Log string `short:"l" long:"log" description:"log level"`
|
||||
Verbose bool `short:"v" long:"verbose" description:"Show verbose output from gitleaks audit"`
|
||||
Report string `long:"report" description:"path to write report file"`
|
||||
CSV bool `long:"csv" description:"report output to csv"`
|
||||
Redact bool `long:"redact" description:"redact secrets from log messages and report"`
|
||||
Version bool `long:"version" description:"version number"`
|
||||
SampleConfig bool `long:"sample-config" description:"prints a sample config file"`
|
||||
}
|
||||
|
||||
// Config struct for regexes matching and whitelisting
|
||||
@@ -114,12 +115,29 @@ type Config struct {
|
||||
Regexes []string
|
||||
Commits []string
|
||||
Branches []string
|
||||
Repos []string
|
||||
}
|
||||
}
|
||||
|
||||
type gitDiff struct {
|
||||
content string
|
||||
commit *object.Commit
|
||||
filePath string
|
||||
branchName string
|
||||
repoName string
|
||||
}
|
||||
|
||||
const defaultGithubURL = "https://api.github.com/"
|
||||
const version = "1.5.0"
|
||||
const version = "1.11.0"
|
||||
const errExit = 2
|
||||
const leakExit = 1
|
||||
const defaultConfig = `
|
||||
# This is a sample config file for gitleaks. You can configure gitleaks what to search for and what to whitelist.
|
||||
# The output you are seeing here is the default gitleaks config. If GITLEAKS_CONFIG environment variable
|
||||
# is set, gitleaks will load configurations from that path. If option --config-path is set, gitleaks will load
|
||||
# configurations from that path. Gitleaks does not whitelist anything by default.
|
||||
|
||||
|
||||
title = "gitleaks config"
|
||||
# add regexes to the regex table
|
||||
[[regexes]]
|
||||
@@ -145,7 +163,6 @@ description = "Twitter"
|
||||
regex = '''(?i)twitter.*['\"][0-9a-zA-Z]{35,44}['\"]'''
|
||||
|
||||
[whitelist]
|
||||
|
||||
#regexes = [
|
||||
# "AKAIMYFAKEAWKKEY",
|
||||
#]
|
||||
@@ -162,6 +179,10 @@ regex = '''(?i)twitter.*['\"][0-9a-zA-Z]{35,44}['\"]'''
|
||||
#branches = [
|
||||
# "dev/STUPDIFKNFEATURE"
|
||||
#]
|
||||
|
||||
#repos = [
|
||||
# "someYugeRepoWeKnowIsCLEAR"
|
||||
#]
|
||||
`
|
||||
|
||||
var (
|
||||
@@ -172,115 +193,110 @@ var (
|
||||
whiteListFiles []*regexp.Regexp
|
||||
whiteListCommits map[string]bool
|
||||
whiteListBranches []string
|
||||
whiteListRepos []string
|
||||
fileDiffRegex *regexp.Regexp
|
||||
sshAuth *ssh.PublicKeys
|
||||
dir string
|
||||
maxGo int
|
||||
totalCommits int64
|
||||
)
|
||||
|
||||
func init() {
|
||||
log.SetOutput(os.Stdout)
|
||||
maxGo = runtime.GOMAXPROCS(0) / 2
|
||||
regexes = make(map[string]*regexp.Regexp)
|
||||
whiteListCommits = make(map[string]bool)
|
||||
}
|
||||
|
||||
func main() {
|
||||
var (
|
||||
leaks []Leak
|
||||
)
|
||||
_, err := flags.Parse(&opts)
|
||||
if opts.Version {
|
||||
fmt.Println(version)
|
||||
os.Exit(0)
|
||||
}
|
||||
if err != nil {
|
||||
os.Exit(1)
|
||||
if opts.SampleConfig {
|
||||
fmt.Println(defaultConfig)
|
||||
os.Exit(0)
|
||||
}
|
||||
leaks, err := run()
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
os.Exit(errExit)
|
||||
}
|
||||
if opts.Report != "" {
|
||||
writeReport(leaks)
|
||||
}
|
||||
|
||||
log.Infof("%d commits inspected", totalCommits)
|
||||
if len(leaks) != 0 {
|
||||
log.Warnf("%d leaks detected", len(leaks))
|
||||
os.Exit(leakExit)
|
||||
}
|
||||
}
|
||||
|
||||
// run parses options and kicks off the audit
|
||||
func run() ([]Leak, error) {
|
||||
var leaks []Leak
|
||||
setLogs()
|
||||
|
||||
err = optsGuard()
|
||||
err := optsGuard()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = loadToml()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if opts.IncludePrivate {
|
||||
// if including private repos use ssh as authentication
|
||||
sshAuth, err = getSSHAuth()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if opts.Disk {
|
||||
// temporary directory where all the gitleaks plain clones will reside
|
||||
dir, err = ioutil.TempDir("", "gitleaks")
|
||||
defer os.RemoveAll(dir)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
leaks, err = startAudits()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
if opts.Report != "" {
|
||||
writeReport(leaks)
|
||||
}
|
||||
|
||||
if len(leaks) != 0 {
|
||||
log.Errorf("leaks detected")
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func startAudits() ([]Leak, error) {
|
||||
var leaks []Leak
|
||||
// start audits
|
||||
if opts.Repo != "" || opts.RepoPath != "" {
|
||||
repo, err := getRepo()
|
||||
// Audit a single remote repo or a local repo.
|
||||
repo, err := cloneRepo()
|
||||
if err != nil {
|
||||
return leaks, err
|
||||
}
|
||||
return auditRepo(repo)
|
||||
return auditGitRepo(repo)
|
||||
} else if opts.OwnerPath != "" {
|
||||
// Audit local repos. Gitleaks will look for all child directories of OwnerPath for
|
||||
// git repos and perform an audit on said repos.
|
||||
repos, err := discoverRepos(opts.OwnerPath)
|
||||
if err != nil {
|
||||
return leaks, err
|
||||
}
|
||||
for _, repo := range repos {
|
||||
leaksFromRepo, err := auditRepo(repo)
|
||||
leaksFromRepo, err := auditGitRepo(repo)
|
||||
if err != nil {
|
||||
return leaks, err
|
||||
}
|
||||
leaks = append(leaksFromRepo, leaks...)
|
||||
}
|
||||
} else if opts.GithubOrg != "" || opts.GithubUser != "" {
|
||||
githubRepos, err := getGithubRepos()
|
||||
// Audit a github owner -- a user or organization. If you want to include
|
||||
// private repos you must pass a --private/-p option and have your ssh keys set
|
||||
leaks, err = auditGithubRepos()
|
||||
if err != nil {
|
||||
return leaks, err
|
||||
}
|
||||
for _, githubRepo := range githubRepos {
|
||||
leaksFromRepo, err := auditGithubRepo(githubRepo)
|
||||
if len(leaksFromRepo) == 0 {
|
||||
log.Infof("no leaks found for repo %s", *githubRepo.Name)
|
||||
} else {
|
||||
log.Warnf("leaks found for repo %s", *githubRepo.Name)
|
||||
}
|
||||
if err != nil {
|
||||
return leaks, err
|
||||
}
|
||||
leaks = append(leaks, leaksFromRepo...)
|
||||
}
|
||||
}
|
||||
return leaks, nil
|
||||
}
|
||||
|
||||
// writeReport writes a report to opts.Report in JSON.
|
||||
// writeReport writes a report to a file specified in the --report= option.
|
||||
// Default format for report is JSON. You can use the --csv option to write the report as a csv
|
||||
func writeReport(leaks []Leak) error {
|
||||
var err error
|
||||
log.Infof("writing report to %s", opts.Report)
|
||||
@@ -303,14 +319,14 @@ func writeReport(leaks []Leak) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// getRepo is responsible for cloning a repo in-memory or to disk, or opening a local repo and creating
|
||||
// a repo object
|
||||
func getRepo() (Repo, error) {
|
||||
// cloneRepo clones a repo to memory(default) or to disk if the --disk option is set. If you want to
|
||||
// clone a private repo you must set the --private/-p option, use a ssh target, and have your ssh keys
|
||||
// configured. If you want to audit a local repo, getRepo will load up a repo located at --repo-path
|
||||
func cloneRepo() (*RepoDescriptor, error) {
|
||||
var (
|
||||
err error
|
||||
repo *git.Repository
|
||||
)
|
||||
|
||||
if opts.Disk {
|
||||
log.Infof("cloning %s", opts.Repo)
|
||||
cloneTarget := fmt.Sprintf("%s/%x", dir, md5.Sum([]byte(fmt.Sprintf("%s%s", opts.GithubUser, opts.Repo))))
|
||||
@@ -327,7 +343,6 @@ func getRepo() (Repo, error) {
|
||||
})
|
||||
}
|
||||
} else if opts.RepoPath != "" {
|
||||
// use existing repo
|
||||
log.Infof("opening %s", opts.Repo)
|
||||
repo, err = git.PlainOpen(opts.RepoPath)
|
||||
} else {
|
||||
@@ -345,7 +360,7 @@ func getRepo() (Repo, error) {
|
||||
})
|
||||
}
|
||||
}
|
||||
return Repo{
|
||||
return &RepoDescriptor{
|
||||
repository: repo,
|
||||
path: opts.RepoPath,
|
||||
url: opts.Repo,
|
||||
@@ -354,131 +369,24 @@ func getRepo() (Repo, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
// auditRef audits a git reference
|
||||
// TODO: need to add a layer of parallelism here and a cache for parent+child commits so we don't
|
||||
// double dip
|
||||
func auditRef(repo Repo, ref *plumbing.Reference, commitWg *sync.WaitGroup, commitChan chan []Leak) error {
|
||||
// auditGitRepo beings an audit on a git repository by checking the default HEAD branch, all branches, or
|
||||
// a single branch depending on what gitleaks is configured to do. Note when I say branch I really
|
||||
// mean reference as these branches are read only.
|
||||
func auditGitRepo(repo *RepoDescriptor) ([]Leak, error) {
|
||||
var (
|
||||
err error
|
||||
prevCommit *object.Commit
|
||||
limitGoRoutines bool
|
||||
semaphore chan bool
|
||||
repoName string
|
||||
err error
|
||||
leaks []Leak
|
||||
)
|
||||
|
||||
repoName = repo.name
|
||||
|
||||
// goroutine limiting
|
||||
if opts.MaxGoRoutines != 0 {
|
||||
semaphore = make(chan bool, opts.MaxGoRoutines)
|
||||
limitGoRoutines = true
|
||||
for _, repoName := range whiteListRepos {
|
||||
if repoName == repo.name {
|
||||
return nil, fmt.Errorf("skipping %s, whitelisted", repoName)
|
||||
}
|
||||
}
|
||||
cIter, err := repo.repository.Log(&git.LogOptions{From: ref.Hash()})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = cIter.ForEach(func(c *object.Commit) error {
|
||||
if c.Hash.String() == opts.Commit {
|
||||
cIter.Close()
|
||||
}
|
||||
if whiteListCommits[c.Hash.String()] {
|
||||
log.Infof("skipping commit: %s\n", c.Hash.String())
|
||||
return nil
|
||||
}
|
||||
if limitGoRoutines {
|
||||
semaphore <- true
|
||||
}
|
||||
commitWg.Add(1)
|
||||
go func(c *object.Commit, prevCommit *object.Commit) {
|
||||
var (
|
||||
leaks []Leak
|
||||
filePath string
|
||||
skipFile bool
|
||||
)
|
||||
if prevCommit == nil {
|
||||
t, _ := c.Tree()
|
||||
files := t.Files()
|
||||
err := files.ForEach(func(file *object.File) error {
|
||||
content, err := file.Contents()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
leaks = append(leaks, checkDiff(content, c, file.Name, string(ref.Name()), repoName)...)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
log.Warnf("problem generating diff for commit: %s\n", c.Hash.String())
|
||||
if limitGoRoutines {
|
||||
<-semaphore
|
||||
}
|
||||
commitChan <- leaks
|
||||
return
|
||||
}
|
||||
} else {
|
||||
patch, err := c.Patch(prevCommit)
|
||||
if err != nil {
|
||||
log.Warnf("problem generating patch for commit: %s\n", c.Hash.String())
|
||||
if limitGoRoutines {
|
||||
<-semaphore
|
||||
}
|
||||
commitChan <- leaks
|
||||
return
|
||||
}
|
||||
for _, f := range patch.FilePatches() {
|
||||
skipFile = false
|
||||
from, to := f.Files()
|
||||
filePath = "???"
|
||||
if from != nil {
|
||||
filePath = from.Path()
|
||||
} else if to != nil {
|
||||
filePath = to.Path()
|
||||
}
|
||||
for _, re := range whiteListFiles {
|
||||
if re.FindString(filePath) != "" {
|
||||
skipFile = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if skipFile {
|
||||
continue
|
||||
}
|
||||
chunks := f.Chunks()
|
||||
for _, chunk := range chunks {
|
||||
if chunk.Type() == 1 || chunk.Type() == 2 {
|
||||
// only check if adding or removing
|
||||
leaks = append(leaks, checkDiff(chunk.Content(), prevCommit, filePath, string(ref.Name()), repoName)...)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if limitGoRoutines {
|
||||
<-semaphore
|
||||
}
|
||||
commitChan <- leaks
|
||||
}(c, prevCommit)
|
||||
prevCommit = c
|
||||
return nil
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// auditRepo performs an audit on a repository checking for regex matching and ignoring
|
||||
// files and regexes that are whitelisted
|
||||
func auditRepo(repo Repo) ([]Leak, error) {
|
||||
var (
|
||||
err error
|
||||
leaks []Leak
|
||||
commitWg sync.WaitGroup
|
||||
)
|
||||
|
||||
ref, err := repo.repository.Head()
|
||||
if err != nil {
|
||||
return leaks, err
|
||||
}
|
||||
|
||||
// leak messaging
|
||||
commitChan := make(chan []Leak, 1)
|
||||
|
||||
if opts.AuditAllRefs {
|
||||
skipBranch := false
|
||||
refs, err := repo.repository.Storer.IterReferences()
|
||||
@@ -495,7 +403,10 @@ func auditRepo(repo Repo) ([]Leak, error) {
|
||||
skipBranch = false
|
||||
return nil
|
||||
}
|
||||
auditRef(repo, ref, &commitWg, commitChan)
|
||||
branchLeaks := auditGitReference(repo, ref)
|
||||
for _, leak := range branchLeaks {
|
||||
leaks = append(leaks, leak)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
} else {
|
||||
@@ -511,33 +422,150 @@ func auditRepo(repo Repo) ([]Leak, error) {
|
||||
return nil
|
||||
})
|
||||
if foundBranch == false {
|
||||
log.Fatalf("No branch with name", opts.Branch)
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
auditRef(repo, ref, &commitWg, commitChan)
|
||||
leaks = auditGitReference(repo, ref)
|
||||
}
|
||||
|
||||
go func() {
|
||||
for commitLeaks := range commitChan {
|
||||
if commitLeaks != nil {
|
||||
for _, leak := range commitLeaks {
|
||||
leaks = append(leaks, leak)
|
||||
}
|
||||
|
||||
}
|
||||
commitWg.Done()
|
||||
}
|
||||
}()
|
||||
|
||||
commitWg.Wait()
|
||||
return leaks, err
|
||||
}
|
||||
|
||||
// checkDiff accepts a string diff and commit object then performs a
|
||||
// regex check
|
||||
func checkDiff(diff string, commit *object.Commit, filePath string, branch string, repo string) []Leak {
|
||||
lines := strings.Split(diff, "\n")
|
||||
// auditGitReference beings the audit for a git reference. This function will
|
||||
// traverse the git reference and audit each line of each diff. Set maximum concurrency with
|
||||
// the --max-go option (default is set to the number of cores on your cpu).
|
||||
func auditGitReference(repo *RepoDescriptor, ref *plumbing.Reference) []Leak {
|
||||
var (
|
||||
err error
|
||||
prevCommit *object.Commit
|
||||
semaphore chan bool
|
||||
repoName string
|
||||
leaks []Leak
|
||||
commitWg sync.WaitGroup
|
||||
mutex = &sync.Mutex{}
|
||||
commitCount int
|
||||
)
|
||||
repoName = repo.name
|
||||
if opts.MaxGoRoutines != 0 {
|
||||
maxGo = opts.MaxGoRoutines
|
||||
}
|
||||
|
||||
semaphore = make(chan bool, maxGo)
|
||||
cIter, err := repo.repository.Log(&git.LogOptions{From: ref.Hash()})
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
err = cIter.ForEach(func(c *object.Commit) error {
|
||||
if c.Hash.String() == opts.Commit || (opts.Depth != 0 && commitCount == opts.Depth) {
|
||||
cIter.Close()
|
||||
return errors.New("ErrStop")
|
||||
}
|
||||
commitCount = commitCount + 1
|
||||
totalCommits = totalCommits + 1
|
||||
if whiteListCommits[c.Hash.String()] {
|
||||
log.Infof("skipping commit: %s\n", c.Hash.String())
|
||||
return nil
|
||||
}
|
||||
commitWg.Add(1)
|
||||
semaphore <- true
|
||||
go func(c *object.Commit, prevCommit *object.Commit) {
|
||||
var (
|
||||
filePath string
|
||||
skipFile bool
|
||||
)
|
||||
defer func() {
|
||||
commitWg.Done()
|
||||
<-semaphore
|
||||
if r := recover(); r != nil {
|
||||
log.Warnf("recoverying from panic on commit %s, likely large diff causing panic", c.Hash.String())
|
||||
}
|
||||
}()
|
||||
diff := gitDiff{
|
||||
commit: prevCommit,
|
||||
branchName: string(ref.Name()),
|
||||
repoName: repoName,
|
||||
}
|
||||
|
||||
if prevCommit == nil {
|
||||
t, _ := c.Tree()
|
||||
files := t.Files()
|
||||
err := files.ForEach(func(file *object.File) error {
|
||||
content, err := file.Contents()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
diff.filePath = file.Name
|
||||
diff.content = content
|
||||
diff.commit = c
|
||||
chunkLeaks := inspect(diff)
|
||||
for _, leak := range chunkLeaks {
|
||||
mutex.Lock()
|
||||
leaks = append(leaks, leak)
|
||||
mutex.Unlock()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
log.Warnf("problem generating diff for commit: %s\n", c.Hash.String())
|
||||
return
|
||||
}
|
||||
} else {
|
||||
patch, err := c.Patch(prevCommit)
|
||||
if err != nil {
|
||||
log.Warnf("problem generating patch for commit: %s\n", c.Hash.String())
|
||||
return
|
||||
}
|
||||
for _, f := range patch.FilePatches() {
|
||||
skipFile = false
|
||||
from, to := f.Files()
|
||||
filePath = "???"
|
||||
if from != nil {
|
||||
filePath = from.Path()
|
||||
} else if to != nil {
|
||||
filePath = to.Path()
|
||||
}
|
||||
diff.filePath = filePath
|
||||
for _, re := range whiteListFiles {
|
||||
if re.FindString(filePath) != "" {
|
||||
skipFile = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if skipFile {
|
||||
continue
|
||||
}
|
||||
chunks := f.Chunks()
|
||||
for _, chunk := range chunks {
|
||||
if chunk.Type() == 1 || chunk.Type() == 2 {
|
||||
diff.content = chunk.Content()
|
||||
chunkLeaks := inspect(diff)
|
||||
for _, leak := range chunkLeaks {
|
||||
mutex.Lock()
|
||||
leaks = append(leaks, leak)
|
||||
mutex.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}(c, prevCommit)
|
||||
prevCommit = c
|
||||
return nil
|
||||
})
|
||||
commitWg.Wait()
|
||||
|
||||
if opts.Verbose {
|
||||
log.Infof("%d commits inspected for %s", commitCount, repo.name)
|
||||
}
|
||||
|
||||
return leaks
|
||||
}
|
||||
|
||||
// inspect will parse each line of the git diff's content against a set of regexes or
|
||||
// a set of regexes set by the config (see gitleaks.toml for example). This function
|
||||
// will skip lines that include a whitelisted regex. A list of leaks is returned.
|
||||
// If verbose mode (-v/--verbose) is set, then checkDiff will log leaks as they are discovered.
|
||||
func inspect(diff gitDiff) []Leak {
|
||||
lines := strings.Split(diff.content, "\n")
|
||||
var (
|
||||
leaks []Leak
|
||||
skipLine bool
|
||||
@@ -563,40 +591,84 @@ func checkDiff(diff string, commit *object.Commit, filePath string, branch strin
|
||||
break
|
||||
}
|
||||
|
||||
leak := Leak{
|
||||
Line: line,
|
||||
Commit: commit.Hash.String(),
|
||||
Offender: match,
|
||||
Type: leakType,
|
||||
Message: commit.Message,
|
||||
Author: commit.Author.String(),
|
||||
File: filePath,
|
||||
Branch: branch,
|
||||
Repo: repo,
|
||||
leaks = addLeak(leaks, line, match, leakType, diff)
|
||||
}
|
||||
|
||||
if opts.Entropy > 0 {
|
||||
words := strings.Fields(line)
|
||||
for _, word := range words {
|
||||
if getShannonEntropy(word) >= opts.Entropy {
|
||||
leaks = addLeak(leaks, line, word, "High Entropy", diff)
|
||||
}
|
||||
}
|
||||
if opts.Redact {
|
||||
leak.Offender = "REDACTED"
|
||||
leak.Line = "REDACTED"
|
||||
}
|
||||
if opts.Verbose {
|
||||
leak.log()
|
||||
}
|
||||
leaks = append(leaks, leak)
|
||||
}
|
||||
}
|
||||
return leaks
|
||||
}
|
||||
|
||||
// auditOwner audits all of the owner's(user or org) repos
|
||||
func getGithubRepos() ([]*github.Repository, error) {
|
||||
// getShannonEntropy https://en.wiktionary.org/wiki/Shannon_entropy
|
||||
func getShannonEntropy(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
|
||||
}
|
||||
|
||||
// addLeak is helper for func inspect() to append leaks if found during a diff check.
|
||||
func addLeak(leaks []Leak, line string, offender string, leakType string, diff gitDiff) []Leak {
|
||||
leak := Leak{
|
||||
Line: line,
|
||||
Commit: diff.commit.Hash.String(),
|
||||
Offender: offender,
|
||||
Type: leakType,
|
||||
Message: diff.commit.Message,
|
||||
Author: diff.commit.Author.String(),
|
||||
File: diff.filePath,
|
||||
Branch: diff.branchName,
|
||||
Repo: diff.repoName,
|
||||
}
|
||||
|
||||
if opts.Redact {
|
||||
leak.Offender = "REDACTED"
|
||||
leak.Line = "REDACTED"
|
||||
}
|
||||
|
||||
if opts.Verbose {
|
||||
leak.log()
|
||||
}
|
||||
|
||||
leaks = append(leaks, leak)
|
||||
return leaks
|
||||
}
|
||||
|
||||
// auditGithubRepos kicks off audits if --github-user or --github-org options are set.
|
||||
// First, we gather all the github repositories from the github api (this doesnt actually clone the repo).
|
||||
// After all the repos have been pulled from github's api we proceed to audit the repos by calling auditGithubRepo.
|
||||
// If an error occurs during an audit of a repo, that error is logged but won't break the execution cycle.
|
||||
func auditGithubRepos() ([]Leak, error) {
|
||||
var (
|
||||
err error
|
||||
githubRepos []*github.Repository
|
||||
rs []*github.Repository
|
||||
pagedGithubRepos []*github.Repository
|
||||
resp *github.Response
|
||||
githubClient *github.Client
|
||||
githubOrgOptions *github.RepositoryListByOrgOptions
|
||||
githubOptions *github.RepositoryListOptions
|
||||
done bool
|
||||
leaks []Leak
|
||||
ownerDir string
|
||||
)
|
||||
ctx := context.Background()
|
||||
|
||||
@@ -607,7 +679,7 @@ func getGithubRepos() ([]*github.Repository, error) {
|
||||
githubClient.BaseURL = ghURL
|
||||
}
|
||||
githubOrgOptions = &github.RepositoryListByOrgOptions{
|
||||
ListOptions: github.ListOptions{PerPage: 10},
|
||||
ListOptions: github.ListOptions{PerPage: 100},
|
||||
}
|
||||
} else if opts.GithubUser != "" {
|
||||
githubClient = github.NewClient(githubToken())
|
||||
@@ -619,59 +691,101 @@ func getGithubRepos() ([]*github.Repository, error) {
|
||||
githubOptions = &github.RepositoryListOptions{
|
||||
Affiliation: "owner",
|
||||
ListOptions: github.ListOptions{
|
||||
PerPage: 10,
|
||||
PerPage: 100,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
for {
|
||||
if done {
|
||||
break
|
||||
}
|
||||
if opts.GithubUser != "" {
|
||||
if opts.IncludePrivate {
|
||||
rs, resp, err = githubClient.Repositories.List(ctx, "", githubOptions)
|
||||
pagedGithubRepos, resp, err = githubClient.Repositories.List(ctx, "", githubOptions)
|
||||
} else {
|
||||
rs, resp, err = githubClient.Repositories.List(ctx, opts.GithubUser, githubOptions)
|
||||
pagedGithubRepos, resp, err = githubClient.Repositories.List(ctx, opts.GithubUser, githubOptions)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
done = true
|
||||
}
|
||||
githubOptions.Page = resp.NextPage
|
||||
githubRepos = append(githubRepos, rs...)
|
||||
githubRepos = append(githubRepos, pagedGithubRepos...)
|
||||
if resp.NextPage == 0 {
|
||||
return githubRepos, err
|
||||
done = true
|
||||
}
|
||||
} else if opts.GithubOrg != "" {
|
||||
rs, resp, err := githubClient.Repositories.ListByOrg(ctx, opts.GithubOrg, githubOrgOptions)
|
||||
pagedGithubRepos, resp, err = githubClient.Repositories.ListByOrg(ctx, opts.GithubOrg, githubOrgOptions)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
done = true
|
||||
}
|
||||
githubOrgOptions.Page = resp.NextPage
|
||||
githubRepos = append(githubRepos, rs...)
|
||||
githubRepos = append(githubRepos, pagedGithubRepos...)
|
||||
if resp.NextPage == 0 {
|
||||
return githubRepos, err
|
||||
done = true
|
||||
}
|
||||
}
|
||||
for _, githubRepo := range githubRepos {
|
||||
log.Infof("staging repo %s", *githubRepo.Name)
|
||||
if opts.Log == "Debug" || opts.Log == "debug" {
|
||||
for _, githubRepo := range pagedGithubRepos {
|
||||
log.Debugf("staging repos %s", *githubRepo.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if opts.Disk {
|
||||
ownerDir, err = ioutil.TempDir(dir, opts.GithubUser)
|
||||
os.RemoveAll(ownerDir)
|
||||
}
|
||||
for _, githubRepo := range githubRepos {
|
||||
repo, err := cloneGithubRepo(githubRepo)
|
||||
if err != nil {
|
||||
log.Warn(err)
|
||||
continue
|
||||
}
|
||||
leaksFromRepo, err := auditGitRepo(repo)
|
||||
if opts.Disk {
|
||||
os.RemoveAll(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name))
|
||||
}
|
||||
if len(leaksFromRepo) == 0 {
|
||||
log.Infof("no leaks found for repo %s", *githubRepo.Name)
|
||||
} else {
|
||||
log.Warnf("leaks found for repo %s", *githubRepo.Name)
|
||||
}
|
||||
if err != nil {
|
||||
log.Warn(err)
|
||||
}
|
||||
leaks = append(leaks, leaksFromRepo...)
|
||||
}
|
||||
return leaks, nil
|
||||
}
|
||||
|
||||
// auditGithubRepo clones repos from github
|
||||
func auditGithubRepo(githubRepo *github.Repository) ([]Leak, error) {
|
||||
// cloneGithubRepo clones a repo from the url parsed from a github repo. The repo
|
||||
// will be cloned to disk if --disk is set. If the repo is private, you must include the
|
||||
// --private/-p option. After the repo is clone, an audit will begin.
|
||||
func cloneGithubRepo(githubRepo *github.Repository) (*RepoDescriptor, error) {
|
||||
var (
|
||||
leaks []Leak
|
||||
repo *git.Repository
|
||||
err error
|
||||
repo *git.Repository
|
||||
err error
|
||||
)
|
||||
if opts.ExcludeForks && githubRepo.GetFork() {
|
||||
return nil, fmt.Errorf("skipping %s, excluding forks", *githubRepo.Name)
|
||||
}
|
||||
for _, repoName := range whiteListRepos {
|
||||
if repoName == *githubRepo.Name {
|
||||
return nil, fmt.Errorf("skipping %s, whitelisted", repoName)
|
||||
}
|
||||
}
|
||||
log.Infof("cloning: %s", *githubRepo.Name)
|
||||
if opts.Disk {
|
||||
ownerDir, err := ioutil.TempDir(dir, opts.GithubUser)
|
||||
if err != nil {
|
||||
return leaks, fmt.Errorf("unable to generater owner temp dir: %v", err)
|
||||
return nil, fmt.Errorf("unable to generater owner temp dir: %v", err)
|
||||
}
|
||||
if opts.IncludePrivate {
|
||||
if sshAuth == nil {
|
||||
return leaks, fmt.Errorf("no ssh auth available")
|
||||
return nil, fmt.Errorf("no ssh auth available")
|
||||
}
|
||||
repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
|
||||
URL: *githubRepo.SSHURL,
|
||||
@@ -685,7 +799,7 @@ func auditGithubRepo(githubRepo *github.Repository) ([]Leak, error) {
|
||||
} else {
|
||||
if opts.IncludePrivate {
|
||||
if sshAuth == nil {
|
||||
return leaks, fmt.Errorf("no ssh auth available")
|
||||
return nil, fmt.Errorf("no ssh auth available")
|
||||
}
|
||||
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
|
||||
URL: *githubRepo.SSHURL,
|
||||
@@ -698,15 +812,16 @@ func auditGithubRepo(githubRepo *github.Repository) ([]Leak, error) {
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return leaks, err
|
||||
return nil, err
|
||||
}
|
||||
return auditRepo(Repo{
|
||||
return &RepoDescriptor{
|
||||
repository: repo,
|
||||
name: *githubRepo.Name,
|
||||
})
|
||||
}, nil
|
||||
}
|
||||
|
||||
// githubToken returns a oauth2 client for the github api to consume
|
||||
// githubToken returns an oauth2 client for the github api to consume. This token is necessary
|
||||
// if you are running audits with --github-user or --github-org
|
||||
func githubToken() *http.Client {
|
||||
githubToken := os.Getenv("GITHUB_TOKEN")
|
||||
if githubToken == "" {
|
||||
@@ -719,11 +834,11 @@ func githubToken() *http.Client {
|
||||
}
|
||||
|
||||
// discoverRepos walks all the children of `path`. If a child directory
|
||||
// contain a .git file then that repo will be added
|
||||
func discoverRepos(ownerPath string) ([]Repo, error) {
|
||||
// contain a .git file then that repo will be added to the list of repos returned
|
||||
func discoverRepos(ownerPath string) ([]*RepoDescriptor, error) {
|
||||
var (
|
||||
err error
|
||||
repos []Repo
|
||||
repos []*RepoDescriptor
|
||||
)
|
||||
files, err := ioutil.ReadDir(ownerPath)
|
||||
if err != nil {
|
||||
@@ -736,7 +851,7 @@ func discoverRepos(ownerPath string) ([]Repo, error) {
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
repos = append(repos, Repo{
|
||||
repos = append(repos, &RepoDescriptor{
|
||||
repository: r,
|
||||
name: f.Name(),
|
||||
path: repoPath,
|
||||
@@ -804,12 +919,18 @@ func optsGuard() error {
|
||||
}
|
||||
}
|
||||
|
||||
if opts.Entropy > 8 {
|
||||
return fmt.Errorf("The maximum level of entropy is 8")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// loadToml loads of the toml config containing regexes and whitelists
|
||||
// 1. look for config path
|
||||
// 2. two, look for gitleaks config env var
|
||||
// loadToml loads of the toml config containing regexes and whitelists.
|
||||
// This function will first look if the configPath is set and load the config
|
||||
// from that file. Otherwise will then look for the path set by the GITHLEAKS_CONIFG
|
||||
// env var. If that is not set, then gitleaks will continue with the default configs
|
||||
// specified by the const var at the top `defaultConfig`
|
||||
func loadToml() error {
|
||||
var (
|
||||
config Config
|
||||
@@ -836,9 +957,7 @@ func loadToml() error {
|
||||
}
|
||||
}
|
||||
|
||||
// load up regexes
|
||||
if singleSearchRegex != nil {
|
||||
// single search takes precedence over default regex
|
||||
regexes["singleSearch"] = singleSearchRegex
|
||||
} else {
|
||||
for _, regex := range config.Regexes {
|
||||
@@ -846,6 +965,7 @@ func loadToml() error {
|
||||
}
|
||||
}
|
||||
whiteListBranches = config.Whitelist.Branches
|
||||
whiteListRepos = config.Whitelist.Repos
|
||||
whiteListCommits = make(map[string]bool)
|
||||
for _, commit := range config.Whitelist.Commits {
|
||||
whiteListCommits[commit] = true
|
||||
@@ -860,7 +980,9 @@ func loadToml() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// getSSHAuth generates ssh auth
|
||||
// getSSHAuth return an ssh auth use by go-git to clone repos behind authentication.
|
||||
// If --ssh-key is set then it will attempt to load the key from that path. If not,
|
||||
// gitleaks will use the default $HOME/.ssh/id_rsa key
|
||||
func getSSHAuth() (*ssh.PublicKeys, error) {
|
||||
var (
|
||||
sshKeyPath string
|
||||
@@ -878,7 +1000,7 @@ func getSSHAuth() (*ssh.PublicKeys, error) {
|
||||
return sshAuth, err
|
||||
}
|
||||
|
||||
func (leak *Leak) log() {
|
||||
func (leak Leak) log() {
|
||||
b, _ := json.MarshalIndent(leak, "", " ")
|
||||
fmt.Println(string(b))
|
||||
}
|
||||
Reference in new issue
Block a user