Compare commits

..
8 Commits
Author SHA1 Message Date
Zachary Rice cc6d698e63 Resource fix (#102)
* no more dangling goroutines
2018-10-04 09:47:18 -05:00
Zachary Rice 2ba97d0fa3 fixing audit repo bug (#101)
* fixing audit repo bug

* bumping version
2018-10-02 12:34:05 -05:00
Zachary Rice d299b5aa7f Exitcode (#100)
* additional exit code, some more cleaning

* bump version
2018-10-02 09:52:18 -05:00
Zachary Rice 0a209b60a5 typo 2018-10-02 07:59:11 -05:00
Zachary Rice fe8c6271f2 panic plan (#99) 2018-10-01 22:44:25 -05:00
zach rice 42fb085684 pls contribute 2018-10-01 21:54:31 -05:00
Zachary Rice 3faec00bf9 Max go (#98)
* default max go, cleaning up for orgs

* bump changelog

* bumping version
2018-10-01 21:21:19 -05:00
Zachary Rice 93669f1ee8 Csv (#96)
* refactoring github audits, adding csv support

* working on tests

* test passing

* bumping version

* updating readme
2018-09-29 22:11:40 -05:00
6 changed files with 649 additions and 301 deletions

No files matched your search

+29
View File
@@ -1,6 +1,35 @@
CHANGELOG CHANGELOG
========= =========
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
- Refactoring github user/owner audits
1.4.0 1.4.0
----- -----
- Support for single commit repos - Support for single commit repos
+20
View File
@@ -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.
+6 -2
View File
@@ -4,13 +4,12 @@ test:
go get github.com/golang/lint/golint go get github.com/golang/lint/golint
go fmt go fmt
golint golint
go test --race -cover go test --race --cover -run=Test$
deploy: deploy:
@echo "$(DOCKER_PASSWORD)" | docker login -u "$(DOCKER_USERNAME)" --password-stdin @echo "$(DOCKER_PASSWORD)" | docker login -u "$(DOCKER_USERNAME)" --password-stdin
docker build -f Dockerfile -t $(REPO):$(TAG) . docker build -f Dockerfile -t $(REPO):$(TAG) .
echo "Pushing $(REPO):$(COMMIT) $(REPO):$(TAG)" echo "Pushing $(REPO):$(COMMIT) $(REPO):$(TAG)"
docker push $(REPO) docker push $(REPO)
build-all: build-all:
rm -rf build rm -rf build
mkdir 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="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" 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$
+3 -1
View File
@@ -43,6 +43,7 @@ Application Options:
-l, --log= log level -l, --log= log level
-v, --verbose Show verbose output from gitleaks audit -v, --verbose Show verbose output from gitleaks audit
--report= path to write report file --report= path to write report file
--csv report output to csv
--redact redact secrets from log messages and report --redact redact secrets from log messages and report
--version version number --version version number
@@ -51,8 +52,9 @@ Help Options:
``` ```
#### Exit Codes #### Exit Codes
``` ```
1: leaks present
0: no leaks 0: no leaks
1: leaks present
2: error encountered
``` ```
#### Additional Examples and Explanations #### Additional Examples and Explanations
+342 -22
View File
@@ -56,6 +56,35 @@ regexes= [
] ]
` `
var benchmarkRepo *Repo
var benchmarkLeaksRepo *Repo
func getBenchmarkLeaksRepo() *Repo {
if benchmarkLeaksRepo != nil {
return benchmarkLeaksRepo
}
leaksR, _ := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: "https://github.com/gitleakstest/gronit.git",
})
benchmarkLeaksRepo = &Repo{
repository: leaksR,
}
return benchmarkLeaksRepo
}
func getBenchmarkRepo() *Repo {
if benchmarkRepo != nil {
return benchmarkRepo
}
bmRepo, _ := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: "https://github.com/apple/swift-package-manager.git",
})
benchmarkRepo = &Repo{
repository: bmRepo,
}
return benchmarkRepo
}
func TestGetRepo(t *testing.T) { func TestGetRepo(t *testing.T) {
var err error var err error
dir, err = ioutil.TempDir("", "gitleaksTestRepo") dir, err = ioutil.TempDir("", "gitleaksTestRepo")
@@ -136,9 +165,10 @@ func TestGetRepo(t *testing.T) {
}) })
} }
} }
func TestRunAudit(t *testing.T) {
func TestGetOwnerRepo(t *testing.T) { err := loadToml()
var err error configsDir := testTomlLoader()
defer os.RemoveAll(configsDir)
dir, err = ioutil.TempDir("", "gitleaksTestOwner") dir, err = ioutil.TempDir("", "gitleaksTestOwner")
defer os.RemoveAll(dir) defer os.RemoveAll(dir)
@@ -155,14 +185,14 @@ func TestGetOwnerRepo(t *testing.T) {
testOpts Options testOpts Options
description string description string
expectedErrMsg string expectedErrMsg string
numRepos int numLeaks int
}{ }{
{ {
testOpts: Options{ testOpts: Options{
GithubUser: "gitleakstest", GithubUser: "gitleakstest",
}, },
description: "test github user", description: "test github user",
numRepos: 2, numLeaks: 2,
expectedErrMsg: "", expectedErrMsg: "",
}, },
{ {
@@ -171,7 +201,7 @@ func TestGetOwnerRepo(t *testing.T) {
Disk: true, Disk: true,
}, },
description: "test github user on disk ", description: "test github user on disk ",
numRepos: 2, numLeaks: 2,
expectedErrMsg: "", expectedErrMsg: "",
}, },
{ {
@@ -179,15 +209,121 @@ func TestGetOwnerRepo(t *testing.T) {
GithubOrg: "gitleakstestorg", GithubOrg: "gitleakstestorg",
}, },
description: "test github org", description: "test github org",
numRepos: 2, numLeaks: 2,
expectedErrMsg: "",
},
{
testOpts: Options{
GithubOrg: "gitleakstestorg",
Disk: true,
},
description: "test org on disk",
numLeaks: 2,
expectedErrMsg: "", expectedErrMsg: "",
}, },
{ {
testOpts: Options{ testOpts: Options{
OwnerPath: dir, OwnerPath: dir,
}, },
description: "test plain clone remote repo", description: "test owner path",
numRepos: 2, 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",
},
}
g := goblin.Goblin(t)
for _, test := range tests {
g.Describe("TestRunAudit", func() {
g.It(test.description, func() {
opts = test.testOpts
leaks, err := run()
if err != nil {
g.Assert(err.Error()).Equal(test.expectedErrMsg)
}
g.Assert(len(leaks)).Equal(test.numLeaks)
})
})
}
}
func TestStartAudit(t *testing.T) {
err := loadToml()
configsDir := testTomlLoader()
defer os.RemoveAll(configsDir)
dir, err = ioutil.TempDir("", "gitleaksTestOwner")
defer os.RemoveAll(dir)
if err != nil {
panic(err)
}
git.PlainClone(dir+"/gronit", false, &git.CloneOptions{
URL: "https://github.com/gitleakstest/gronit",
})
git.PlainClone(dir+"/h1domains", false, &git.CloneOptions{
URL: "https://github.com/gitleakstest/h1domains",
})
var tests = []struct {
testOpts Options
description string
expectedErrMsg string
numLeaks int
}{
{
testOpts: Options{
GithubUser: "gitleakstest",
},
description: "test github user",
numLeaks: 2,
expectedErrMsg: "",
},
{
testOpts: Options{
GithubUser: "gitleakstest",
Disk: true,
},
description: "test github user on disk ",
numLeaks: 2,
expectedErrMsg: "",
},
{
testOpts: Options{
GithubOrg: "gitleakstestorg",
},
description: "test github org",
numLeaks: 2,
expectedErrMsg: "", expectedErrMsg: "",
}, },
{ {
@@ -196,7 +332,7 @@ func TestGetOwnerRepo(t *testing.T) {
IncludePrivate: true, IncludePrivate: true,
}, },
description: "test private org no ssh", description: "test private org no ssh",
numRepos: 0, numLeaks: 0,
expectedErrMsg: "no ssh auth available", expectedErrMsg: "no ssh auth available",
}, },
{ {
@@ -205,7 +341,7 @@ func TestGetOwnerRepo(t *testing.T) {
Disk: true, Disk: true,
}, },
description: "test org on disk", description: "test org on disk",
numRepos: 2, numLeaks: 2,
expectedErrMsg: "", expectedErrMsg: "",
}, },
{ {
@@ -215,20 +351,28 @@ func TestGetOwnerRepo(t *testing.T) {
Disk: true, Disk: true,
}, },
description: "test private org on disk no ssh", description: "test private org on disk no ssh",
numRepos: 0, numLeaks: 0,
expectedErrMsg: "no ssh auth available", expectedErrMsg: "no ssh auth available",
}, },
{
testOpts: Options{
OwnerPath: dir,
},
description: "test owner path",
numLeaks: 2,
expectedErrMsg: "",
},
} }
g := goblin.Goblin(t) g := goblin.Goblin(t)
for _, test := range tests { for _, test := range tests {
g.Describe("TestGetOwnerRepo", func() { g.Describe("TestStartAudit", func() {
g.It(test.description, func() { g.It(test.description, func() {
opts = test.testOpts opts = test.testOpts
repos, err := getOwnerRepos() leaks, err := startAudits()
if err != nil { if err != nil {
g.Assert(err.Error()).Equal(test.expectedErrMsg) g.Assert(err.Error()).Equal(test.expectedErrMsg)
} }
g.Assert(len(repos)).Equal(test.numRepos) g.Assert(len(leaks)).Equal(test.numLeaks)
}) })
}) })
} }
@@ -236,7 +380,8 @@ func TestGetOwnerRepo(t *testing.T) {
func TestWriteReport(t *testing.T) { func TestWriteReport(t *testing.T) {
tmpDir, _ := ioutil.TempDir("", "reportDir") tmpDir, _ := ioutil.TempDir("", "reportDir")
reportFile := path.Join(tmpDir, "report.json") reportJSON := path.Join(tmpDir, "report.json")
reportCSV := path.Join(tmpDir, "report.csv")
defer os.RemoveAll(tmpDir) defer os.RemoveAll(tmpDir)
leaks := []Leak{ leaks := []Leak{
{ {
@@ -260,11 +405,21 @@ func TestWriteReport(t *testing.T) {
}{ }{
{ {
leaks: leaks, leaks: leaks,
reportFile: reportFile, reportFile: reportJSON,
fileName: "report.json", fileName: "report.json",
description: "can we write a file", description: "can we write a file",
testOpts: Options{ testOpts: Options{
Report: reportFile, Report: reportJSON,
},
},
{
leaks: leaks,
reportFile: reportCSV,
fileName: "report.csv",
description: "can we write a file",
testOpts: Options{
Report: reportCSV,
CSV: true,
}, },
}, },
} }
@@ -300,26 +455,34 @@ func TestAuditRepo(t *testing.T) {
if err != nil { if err != nil {
panic(err) panic(err)
} }
leaksRepo, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{ leaksR, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: "https://github.com/gitleakstest/gronit.git", URL: "https://github.com/gitleakstest/gronit.git",
}) })
if err != nil { if err != nil {
panic(err) panic(err)
} }
leaksRepo := Repo{
repository: leaksR,
name: "gronit",
}
cleanRepo, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{ cleanR, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: "https://github.com/gitleakstest/h1domains.git", URL: "https://github.com/gitleakstest/h1domains.git",
}) })
if err != nil { if err != nil {
panic(err) panic(err)
} }
cleanRepo := Repo{
repository: cleanR,
name: "h1domains",
}
var tests = []struct { var tests = []struct {
testOpts Options testOpts Options
description string description string
expectedErrMsg string expectedErrMsg string
numLeaks int numLeaks int
repo *git.Repository repo Repo
whiteListFiles []*regexp.Regexp whiteListFiles []*regexp.Regexp
whiteListCommits map[string]bool whiteListCommits map[string]bool
whiteListBranches []string whiteListBranches []string
@@ -336,7 +499,7 @@ func TestAuditRepo(t *testing.T) {
description: "two leaks present limit goroutines", description: "two leaks present limit goroutines",
numLeaks: 2, numLeaks: 2,
testOpts: Options{ testOpts: Options{
MaxGoRoutines: 2, MaxGoRoutines: 4,
}, },
}, },
{ {
@@ -669,3 +832,160 @@ func TestLoadToml(t *testing.T) {
}) })
} }
} }
func BenchmarkAuditRepo1Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 1
benchmarkRepo = getBenchmarkRepo()
for n := 0; n < b.N; n++ {
auditRepo(*benchmarkRepo)
}
}
func BenchmarkAuditRepo2Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 2
benchmarkRepo = getBenchmarkRepo()
for n := 0; n < b.N; n++ {
auditRepo(*benchmarkRepo)
}
}
func BenchmarkAuditRepo4Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 4
benchmarkRepo = getBenchmarkRepo()
for n := 0; n < b.N; n++ {
auditRepo(*benchmarkRepo)
}
}
func BenchmarkAuditRepo8Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 8
benchmarkRepo = getBenchmarkRepo()
for n := 0; n < b.N; n++ {
auditRepo(*benchmarkRepo)
}
}
func BenchmarkAuditRepo10Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 10
benchmarkRepo = getBenchmarkRepo()
for n := 0; n < b.N; n++ {
auditRepo(*benchmarkRepo)
}
}
func BenchmarkAuditRepo100Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 100
benchmarkRepo = getBenchmarkRepo()
for n := 0; n < b.N; n++ {
auditRepo(*benchmarkRepo)
}
}
func BenchmarkAuditRepo1000Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 1000
benchmarkRepo = getBenchmarkRepo()
for n := 0; n < b.N; n++ {
auditRepo(*benchmarkRepo)
}
}
func BenchmarkAuditRepo10000Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 10000
benchmarkRepo = getBenchmarkRepo()
for n := 0; n < b.N; n++ {
auditRepo(*benchmarkRepo)
}
}
func BenchmarkAuditRepo100000Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 100000
benchmarkRepo = getBenchmarkRepo()
for n := 0; n < b.N; n++ {
auditRepo(*benchmarkRepo)
}
}
func BenchmarkAuditLeakRepo1Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 1
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
for n := 0; n < b.N; n++ {
auditRepo(*benchmarkLeaksRepo)
}
}
func BenchmarkAuditLeakRepo2Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 2
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
for n := 0; n < b.N; n++ {
auditRepo(*benchmarkLeaksRepo)
}
}
func BenchmarkAuditLeakRepo4Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 4
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
for n := 0; n < b.N; n++ {
auditRepo(*benchmarkLeaksRepo)
}
}
func BenchmarkAuditLeakRepo8Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 8
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
for n := 0; n < b.N; n++ {
auditRepo(*benchmarkLeaksRepo)
}
}
func BenchmarkAuditLeakRepo10Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 10
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
for n := 0; n < b.N; n++ {
auditRepo(*benchmarkLeaksRepo)
}
}
func BenchmarkAuditLeakRepo100Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 100
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
for n := 0; n < b.N; n++ {
auditRepo(*benchmarkLeaksRepo)
}
}
func BenchmarkAuditLeakRepo1000Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 1000
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
for n := 0; n < b.N; n++ {
auditRepo(*benchmarkLeaksRepo)
}
}
func BenchmarkAuditLeakRepo10000Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 10000
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
for n := 0; n < b.N; n++ {
auditRepo(*benchmarkLeaksRepo)
}
}
func BenchmarkAuditLeakRepo100000Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 100000
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
for n := 0; n < b.N; n++ {
auditRepo(*benchmarkLeaksRepo)
}
}
+249 -276
View File
@@ -3,6 +3,7 @@ package main
import ( import (
"context" "context"
"crypto/md5" "crypto/md5"
"encoding/csv"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
@@ -14,6 +15,7 @@ import (
"path" "path"
"path/filepath" "path/filepath"
"regexp" "regexp"
"runtime"
"strings" "strings"
"sync" "sync"
"time" "time"
@@ -42,6 +44,7 @@ type Leak struct {
Author string `json:"author"` Author string `json:"author"`
File string `json:"file"` File string `json:"file"`
Branch string `json:"branch"` Branch string `json:"branch"`
Repo string `json:"repo"`
} }
// Repo contains the actual git repository and meta data about the repo // Repo contains the actual git repository and meta data about the repo
@@ -65,8 +68,8 @@ type Owner struct {
type Options struct { type Options struct {
// remote target options // remote target options
Repo string `short:"r" long:"repo" description:"Repo url to audit"` Repo string `short:"r" long:"repo" description:"Repo url to audit"`
GithubUser string `long:"github-user" description:"User url to audit"` GithubUser string `long:"github-user" description:"Github user to audit"`
GithubOrg string `long:"github-org" description:"Organization url to audit"` GithubOrg string `long:"github-org" description:"Github organization to audit"`
GithubURL string `long:"github-url" default:"https://api.github.com/" description:"GitHub API Base URL, use for GitHub Enterprise. Example: https://github.example.com/api/v3/"` GithubURL string `long:"github-url" default:"https://api.github.com/" description:"GitHub API Base URL, use for GitHub Enterprise. Example: https://github.example.com/api/v3/"`
IncludePrivate bool `short:"p" long:"private" description:"Include private repos in audit"` IncludePrivate bool `short:"p" long:"private" description:"Include private repos in audit"`
@@ -96,6 +99,7 @@ type Options struct {
Log string `short:"l" long:"log" description:"log level"` Log string `short:"l" long:"log" description:"log level"`
Verbose bool `short:"v" long:"verbose" description:"Show verbose output from gitleaks audit"` Verbose bool `short:"v" long:"verbose" description:"Show verbose output from gitleaks audit"`
Report string `long:"report" description:"path to write report file"` 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"` Redact bool `long:"redact" description:"redact secrets from log messages and report"`
Version bool `long:"version" description:"version number"` Version bool `long:"version" description:"version number"`
} }
@@ -115,7 +119,9 @@ type Config struct {
} }
const defaultGithubURL = "https://api.github.com/" const defaultGithubURL = "https://api.github.com/"
const version = "1.3.0" const version = "1.7.1"
const errExit = 2
const leakExit = 1
const defaultConfig = ` const defaultConfig = `
title = "gitleaks config" title = "gitleaks config"
# add regexes to the regex table # add regexes to the regex table
@@ -172,99 +178,128 @@ var (
fileDiffRegex *regexp.Regexp fileDiffRegex *regexp.Regexp
sshAuth *ssh.PublicKeys sshAuth *ssh.PublicKeys
dir string dir string
maxGo int
) )
func init() { func init() {
log.SetOutput(os.Stdout) log.SetOutput(os.Stdout)
maxGo = runtime.GOMAXPROCS(0) / 2
regexes = make(map[string]*regexp.Regexp) regexes = make(map[string]*regexp.Regexp)
whiteListCommits = make(map[string]bool) whiteListCommits = make(map[string]bool)
} }
func main() { func main() {
var (
leaks []Leak
repos []Repo
)
_, err := flags.Parse(&opts) _, err := flags.Parse(&opts)
if opts.Version { if opts.Version {
fmt.Println(version) fmt.Println(version)
os.Exit(0) os.Exit(0)
} }
leaks, err := run()
if err != nil { if err != nil {
os.Exit(1) log.Error(err)
os.Exit(errExit)
} }
setLogs()
err = optsGuard()
if err != nil {
log.Fatal(err)
}
err = loadToml()
if err != nil {
log.Fatal(err)
}
if opts.IncludePrivate {
// if including private repos use ssh as authentication
sshAuth, err = getSSHAuth()
if err != nil {
log.Fatal(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)
}
}
// start audits
if opts.Repo != "" || opts.RepoPath != "" {
r, err := getRepo()
if err != nil {
log.Fatal(err)
}
repos = append(repos, r)
} else if ownerTarget() {
repos, err = getOwnerRepos()
}
for _, r := range repos {
if r.err != nil {
log.Warnf("skipping audit for repo %s due to cloning error: %s", r.name, r.err)
continue
}
l, err := auditRepo(r.repository)
if len(l) == 0 {
log.Infof("no leaks found for repo %s", r.name)
} else {
log.Warnf("leaks found for repo %s", r.name)
}
if err != nil {
log.Fatalf("error during audit: %s", err)
}
leaks = append(leaks, l...)
}
if opts.Report != "" { if opts.Report != "" {
writeReport(leaks) writeReport(leaks)
} }
if len(leaks) != 0 { if len(leaks) != 0 {
log.Errorf("leaks detected") log.Warnf("leaks detected")
os.Exit(1) os.Exit(leakExit)
} }
} }
// run parses options and kicks off the audit
func run() ([]Leak, error) {
setLogs()
err := optsGuard()
if err != nil {
return nil, err
}
err = loadToml()
if err != nil {
return nil, err
}
if opts.IncludePrivate {
// if including private repos use ssh as authentication
sshAuth, err = getSSHAuth()
if err != nil {
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 {
return nil, err
}
}
return startAudits()
}
func startAudits() ([]Leak, error) {
var leaks []Leak
// start audits
if opts.Repo != "" || opts.RepoPath != "" {
repo, err := getRepo()
if err != nil {
return leaks, err
}
return auditRepo(repo)
} else if opts.OwnerPath != "" {
repos, err := discoverRepos(opts.OwnerPath)
if err != nil {
return leaks, err
}
for _, repo := range repos {
leaksFromRepo, err := auditRepo(repo)
if err != nil {
return leaks, err
}
leaks = append(leaksFromRepo, leaks...)
}
} else if opts.GithubOrg != "" || opts.GithubUser != "" {
githubRepos, err := getGithubRepos()
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 {
log.Warn(err)
}
leaks = append(leaks, leaksFromRepo...)
}
}
return leaks, nil
}
// writeReport writes a report to opts.Report in JSON. // writeReport writes a report to opts.Report in JSON.
// TODO support yaml
func writeReport(leaks []Leak) error { func writeReport(leaks []Leak) error {
log.Info("writing report to %s", opts.Report) var err error
reportJSON, _ := json.MarshalIndent(leaks, "", "\t") log.Infof("writing report to %s", opts.Report)
err := ioutil.WriteFile(opts.Report, reportJSON, 0644) if opts.CSV {
f, err := os.Create(opts.Report)
if err != nil {
return err
}
defer f.Close()
w := csv.NewWriter(f)
w.Write([]string{"repo", "line", "commit", "offender", "reason", "commitMsg", "author", "file", "branch"})
for _, leak := range leaks {
w.Write([]string{leak.Repo, leak.Line, leak.Commit, leak.Offender, leak.Type, leak.Message, leak.Author, leak.File, leak.Branch})
}
w.Flush()
} else {
reportJSON, _ := json.MarshalIndent(leaks, "", "\t")
err = ioutil.WriteFile(opts.Report, reportJSON, 0644)
}
return err return err
} }
@@ -272,21 +307,20 @@ func writeReport(leaks []Leak) error {
// a repo object // a repo object
func getRepo() (Repo, error) { func getRepo() (Repo, error) {
var ( var (
err error err error
r *git.Repository repo *git.Repository
) )
if opts.Disk { if opts.Disk {
log.Infof("cloning %s", opts.Repo) log.Infof("cloning %s", opts.Repo)
cloneTarget := fmt.Sprintf("%s/%x", dir, md5.Sum([]byte(fmt.Sprintf("%s%s", opts.GithubUser, opts.Repo)))) cloneTarget := fmt.Sprintf("%s/%x", dir, md5.Sum([]byte(fmt.Sprintf("%s%s", opts.GithubUser, opts.Repo))))
if opts.IncludePrivate { if opts.IncludePrivate {
r, err = git.PlainClone(cloneTarget, false, &git.CloneOptions{ repo, err = git.PlainClone(cloneTarget, false, &git.CloneOptions{
URL: opts.Repo, URL: opts.Repo,
Progress: os.Stdout, Progress: os.Stdout,
Auth: sshAuth, Auth: sshAuth,
}) })
} else { } else {
r, err = git.PlainClone(cloneTarget, false, &git.CloneOptions{ repo, err = git.PlainClone(cloneTarget, false, &git.CloneOptions{
URL: opts.Repo, URL: opts.Repo,
Progress: os.Stdout, Progress: os.Stdout,
}) })
@@ -294,24 +328,24 @@ func getRepo() (Repo, error) {
} else if opts.RepoPath != "" { } else if opts.RepoPath != "" {
// use existing repo // use existing repo
log.Infof("opening %s", opts.Repo) log.Infof("opening %s", opts.Repo)
r, err = git.PlainOpen(opts.RepoPath) repo, err = git.PlainOpen(opts.RepoPath)
} else { } else {
log.Infof("cloning %s", opts.Repo) log.Infof("cloning %s", opts.Repo)
if opts.IncludePrivate { if opts.IncludePrivate {
r, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{ repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: opts.Repo, URL: opts.Repo,
Progress: os.Stdout, Progress: os.Stdout,
Auth: sshAuth, Auth: sshAuth,
}) })
} else { } else {
r, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{ repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: opts.Repo, URL: opts.Repo,
Progress: os.Stdout, Progress: os.Stdout,
}) })
} }
} }
return Repo{ return Repo{
repository: r, repository: repo,
path: opts.RepoPath, path: opts.RepoPath,
url: opts.Repo, url: opts.Repo,
name: filepath.Base(opts.Repo), name: filepath.Base(opts.Repo),
@@ -322,22 +356,25 @@ func getRepo() (Repo, error) {
// auditRef audits a git reference // 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 // TODO: need to add a layer of parallelism here and a cache for parent+child commits so we don't
// double dip // double dip
func auditRef(r *git.Repository, ref *plumbing.Reference, commitWg *sync.WaitGroup, commitChan chan []Leak) error { func auditRef(repo Repo, ref *plumbing.Reference) []Leak {
var ( var (
err error err error
prevCommit *object.Commit prevCommit *object.Commit
limitGoRoutines bool semaphore chan bool
semaphore chan bool repoName string
leaks []Leak
commitWg sync.WaitGroup
mutex = &sync.Mutex{}
) )
repoName = repo.name
// goroutine limiting
if opts.MaxGoRoutines != 0 { if opts.MaxGoRoutines != 0 {
semaphore = make(chan bool, opts.MaxGoRoutines) maxGo = opts.MaxGoRoutines
limitGoRoutines = true
} }
cIter, err := r.Log(&git.LogOptions{From: ref.Hash()})
semaphore = make(chan bool, maxGo)
cIter, err := repo.repository.Log(&git.LogOptions{From: ref.Hash()})
if err != nil { if err != nil {
return err return nil
} }
err = cIter.ForEach(func(c *object.Commit) error { err = cIter.ForEach(func(c *object.Commit) error {
if c.Hash.String() == opts.Commit { if c.Hash.String() == opts.Commit {
@@ -347,16 +384,21 @@ func auditRef(r *git.Repository, ref *plumbing.Reference, commitWg *sync.WaitGro
log.Infof("skipping commit: %s\n", c.Hash.String()) log.Infof("skipping commit: %s\n", c.Hash.String())
return nil return nil
} }
if limitGoRoutines {
semaphore <- true
}
commitWg.Add(1) commitWg.Add(1)
semaphore <- true
go func(c *object.Commit, prevCommit *object.Commit) { go func(c *object.Commit, prevCommit *object.Commit) {
var ( var (
leaks []Leak
filePath string filePath string
skipFile bool 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())
}
}()
if prevCommit == nil { if prevCommit == nil {
t, _ := c.Tree() t, _ := c.Tree()
files := t.Files() files := t.Files()
@@ -365,25 +407,22 @@ func auditRef(r *git.Repository, ref *plumbing.Reference, commitWg *sync.WaitGro
if err != nil { if err != nil {
return err return err
} }
leaks = append(leaks, checkDiff(content, c, file.Name, string(ref.Name()))...) chunkLeaks := checkDiff(content, c, file.Name, string(ref.Name()), repoName)
for _, leak := range chunkLeaks {
mutex.Lock()
leaks = append(leaks, leak)
mutex.Unlock()
}
return nil return nil
}) })
if err != nil { if err != nil {
log.Warnf("problem generating diff for commit: %s\n", c.Hash.String()) log.Warnf("problem generating diff for commit: %s\n", c.Hash.String())
if limitGoRoutines {
<-semaphore
}
commitChan <- leaks
return return
} }
} else { } else {
patch, err := c.Patch(prevCommit) patch, err := c.Patch(prevCommit)
if err != nil { if err != nil {
log.Warnf("problem generating patch for commit: %s\n", c.Hash.String()) log.Warnf("problem generating patch for commit: %s\n", c.Hash.String())
if limitGoRoutines {
<-semaphore
}
commitChan <- leaks
return return
} }
for _, f := range patch.FilePatches() { for _, f := range patch.FilePatches() {
@@ -408,42 +447,40 @@ func auditRef(r *git.Repository, ref *plumbing.Reference, commitWg *sync.WaitGro
for _, chunk := range chunks { for _, chunk := range chunks {
if chunk.Type() == 1 || chunk.Type() == 2 { if chunk.Type() == 1 || chunk.Type() == 2 {
// only check if adding or removing // only check if adding or removing
leaks = append(leaks, checkDiff(chunk.Content(), prevCommit, filePath, string(ref.Name()))...) chunkLeaks := checkDiff(chunk.Content(), prevCommit, filePath, string(ref.Name()), repoName)
for _, leak := range chunkLeaks {
mutex.Lock()
leaks = append(leaks, leak)
mutex.Unlock()
}
} }
} }
} }
} }
if limitGoRoutines {
<-semaphore
}
commitChan <- leaks
}(c, prevCommit) }(c, prevCommit)
prevCommit = c prevCommit = c
return nil return nil
}) })
return nil commitWg.Wait()
return leaks
} }
// auditRepo performs an audit on a repository checking for regex matching and ignoring // auditRepo performs an audit on a repository checking for regex matching and ignoring
// files and regexes that are whitelisted // files and regexes that are whitelisted
func auditRepo(r *git.Repository) ([]Leak, error) { func auditRepo(repo Repo) ([]Leak, error) {
var ( var (
err error err error
leaks []Leak leaks []Leak
commitWg sync.WaitGroup
) )
ref, err := r.Head() ref, err := repo.repository.Head()
if err != nil { if err != nil {
return leaks, err return leaks, err
} }
// leak messaging
commitChan := make(chan []Leak, 1)
if opts.AuditAllRefs { if opts.AuditAllRefs {
skipBranch := false skipBranch := false
refs, err := r.Storer.IterReferences() refs, err := repo.repository.Storer.IterReferences()
if err != nil { if err != nil {
return leaks, err return leaks, err
} }
@@ -457,13 +494,16 @@ func auditRepo(r *git.Repository) ([]Leak, error) {
skipBranch = false skipBranch = false
return nil return nil
} }
auditRef(r, ref, &commitWg, commitChan) branchLeaks := auditRef(repo, ref)
for _, leak := range branchLeaks {
leaks = append(leaks, leak)
}
return nil return nil
}) })
} else { } else {
if opts.Branch != "" { if opts.Branch != "" {
foundBranch := false foundBranch := false
refs, _ := r.Storer.IterReferences() refs, _ := repo.repository.Storer.IterReferences()
branch := strings.Split(opts.Branch, "/")[len(strings.Split(opts.Branch, "/"))-1] branch := strings.Split(opts.Branch, "/")[len(strings.Split(opts.Branch, "/"))-1]
err = refs.ForEach(func(refBranch *plumbing.Reference) error { err = refs.ForEach(func(refBranch *plumbing.Reference) error {
if strings.Split(refBranch.Name().String(), "/")[len(strings.Split(refBranch.Name().String(), "/"))-1] == branch { if strings.Split(refBranch.Name().String(), "/")[len(strings.Split(refBranch.Name().String(), "/"))-1] == branch {
@@ -473,32 +513,17 @@ func auditRepo(r *git.Repository) ([]Leak, error) {
return nil return nil
}) })
if foundBranch == false { if foundBranch == false {
log.Fatalf("No branch with name", opts.Branch)
return nil, nil return nil, nil
} }
} }
auditRef(r, ref, &commitWg, commitChan) leaks = auditRef(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 return leaks, err
} }
// checkDiff accepts a string diff and commit object then performs a // checkDiff accepts a string diff and commit object then performs a
// regex check // regex check
func checkDiff(diff string, commit *object.Commit, filePath string, branch string) []Leak { func checkDiff(diff string, commit *object.Commit, filePath string, branch string, repo string) []Leak {
lines := strings.Split(diff, "\n") lines := strings.Split(diff, "\n")
var ( var (
leaks []Leak leaks []Leak
@@ -534,6 +559,7 @@ func checkDiff(diff string, commit *object.Commit, filePath string, branch strin
Author: commit.Author.String(), Author: commit.Author.String(),
File: filePath, File: filePath,
Branch: branch, Branch: branch,
Repo: repo,
} }
if opts.Redact { if opts.Redact {
leak.Offender = "REDACTED" leak.Offender = "REDACTED"
@@ -549,168 +575,125 @@ func checkDiff(diff string, commit *object.Commit, filePath string, branch strin
} }
// auditOwner audits all of the owner's(user or org) repos // auditOwner audits all of the owner's(user or org) repos
func getOwnerRepos() ([]Repo, error) { func getGithubRepos() ([]*github.Repository, error) {
var ( var (
err error err error
repos []Repo githubRepos []*github.Repository
rs []*github.Repository
resp *github.Response
githubClient *github.Client
githubOrgOptions *github.RepositoryListByOrgOptions
githubOptions *github.RepositoryListOptions
) )
ctx := context.Background() ctx := context.Background()
if opts.OwnerPath != "" { if opts.GithubOrg != "" {
repos, err = discoverRepos(opts.OwnerPath) githubClient = github.NewClient(githubToken())
} else if opts.GithubOrg != "" {
githubClient := github.NewClient(githubToken())
if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL { if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
ghURL, _ := url.Parse(opts.GithubURL) ghURL, _ := url.Parse(opts.GithubURL)
githubClient.BaseURL = ghURL githubClient.BaseURL = ghURL
} }
githubOrgOptions = &github.RepositoryListByOrgOptions{
githubOptions := github.RepositoryListByOrgOptions{ ListOptions: github.ListOptions{PerPage: 100},
ListOptions: github.ListOptions{PerPage: 10},
} }
repos, err = getOrgGithubRepos(ctx, &githubOptions, githubClient)
} else if opts.GithubUser != "" { } else if opts.GithubUser != "" {
githubClient := github.NewClient(githubToken()) githubClient = github.NewClient(githubToken())
if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL { if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
ghURL, _ := url.Parse(opts.GithubURL) ghURL, _ := url.Parse(opts.GithubURL)
githubClient.BaseURL = ghURL githubClient.BaseURL = ghURL
} }
githubOptions := github.RepositoryListOptions{ githubOptions = &github.RepositoryListOptions{
Affiliation: "owner", Affiliation: "owner",
ListOptions: github.ListOptions{ ListOptions: github.ListOptions{
PerPage: 10, PerPage: 100,
}, },
} }
repos, err = getUserGithubRepos(ctx, &githubOptions, githubClient)
} }
return repos, err for {
if opts.GithubUser != "" {
if opts.IncludePrivate {
rs, resp, err = githubClient.Repositories.List(ctx, "", githubOptions)
} else {
rs, resp, err = githubClient.Repositories.List(ctx, opts.GithubUser, githubOptions)
}
if err != nil {
return nil, err
}
githubOptions.Page = resp.NextPage
githubRepos = append(githubRepos, rs...)
if resp.NextPage == 0 {
return githubRepos, err
}
} else if opts.GithubOrg != "" {
rs, resp, err = githubClient.Repositories.ListByOrg(ctx, opts.GithubOrg, githubOrgOptions)
if err != nil {
return nil, err
}
githubOrgOptions.Page = resp.NextPage
githubRepos = append(githubRepos, rs...)
if resp.NextPage == 0 {
return githubRepos, err
}
}
if opts.Log == "Debug" || opts.Log == "debug" {
for _, githubRepo := range rs {
log.Debugf("staging repos %s", *githubRepo.Name)
}
}
}
} }
// getUserGithubRepos grabs all github user's public and/or private repos // auditGithubRepo clones repos from github
func getUserGithubRepos(ctx context.Context, listOpts *github.RepositoryListOptions, client *github.Client) ([]Repo, error) { func auditGithubRepo(githubRepo *github.Repository) ([]Leak, error) {
var ( var (
leaks []Leak
repo *git.Repository
err error err error
repos []Repo
r *git.Repository
rs []*github.Repository
resp *github.Response
) )
log.Infof("cloning: %s", *githubRepo.Name)
for { if opts.Disk {
ownerDir, err := ioutil.TempDir(dir, opts.GithubUser)
defer os.RemoveAll(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name))
if err != nil {
return leaks, fmt.Errorf("unable to generater owner temp dir: %v", err)
}
if opts.IncludePrivate { if opts.IncludePrivate {
rs, resp, err = client.Repositories.List(ctx, "", listOpts) if sshAuth == nil {
return leaks, fmt.Errorf("no ssh auth available")
}
repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
URL: *githubRepo.SSHURL,
Auth: sshAuth,
})
} else { } else {
rs, resp, err = client.Repositories.List(ctx, opts.GithubUser, listOpts) repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
} URL: *githubRepo.CloneURL,
for _, rDesc := range rs {
log.Infof("cloning: %s", *rDesc.Name)
if opts.Disk {
ownerDir, err := ioutil.TempDir(dir, opts.GithubUser)
if err != nil {
return repos, fmt.Errorf("unable to generater owner temp dir: %v", err)
}
if opts.IncludePrivate {
r, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *rDesc.Name), false, &git.CloneOptions{
URL: *rDesc.SSHURL,
Auth: sshAuth,
})
} else {
r, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *rDesc.Name), false, &git.CloneOptions{
URL: *rDesc.CloneURL,
})
}
} else {
if opts.IncludePrivate {
r, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: *rDesc.SSHURL,
Auth: sshAuth,
})
} else {
r, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: *rDesc.CloneURL,
})
}
}
repos = append(repos, Repo{
name: *rDesc.Name,
url: *rDesc.SSHURL,
repository: r,
err: err,
}) })
} }
if resp.NextPage == 0 { } else {
break if opts.IncludePrivate {
} if sshAuth == nil {
listOpts.Page = resp.NextPage return leaks, fmt.Errorf("no ssh auth available")
}
return repos, err
}
// getOrgGithubRepos grabs all of org's public and/or private repos
func getOrgGithubRepos(ctx context.Context, listOpts *github.RepositoryListByOrgOptions, client *github.Client) ([]Repo, error) {
var (
err error
repos []Repo
r *git.Repository
ownerDir string
)
for {
rs, resp, err := client.Repositories.ListByOrg(ctx, opts.GithubOrg, listOpts)
for _, rDesc := range rs {
log.Infof("cloning: %s", *rDesc.Name)
if opts.Disk {
ownerDir, err = ioutil.TempDir(dir, opts.GithubUser)
if err != nil {
return repos, fmt.Errorf("unable to generater owner temp dir: %v", err)
}
if opts.IncludePrivate {
if sshAuth == nil {
return nil, fmt.Errorf("no ssh auth available")
}
r, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *rDesc.Name), false, &git.CloneOptions{
URL: *rDesc.SSHURL,
Auth: sshAuth,
})
} else {
r, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *rDesc.Name), false, &git.CloneOptions{
URL: *rDesc.CloneURL,
})
}
} else {
if opts.IncludePrivate {
if sshAuth == nil {
return nil, fmt.Errorf("no ssh auth available")
}
r, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: *rDesc.SSHURL,
Auth: sshAuth,
})
} else {
r, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: *rDesc.CloneURL,
})
}
} }
repos = append(repos, Repo{ repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
url: *rDesc.SSHURL, URL: *githubRepo.SSHURL,
name: *rDesc.Name, Auth: sshAuth,
repository: r, })
err: err, } else {
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: *githubRepo.CloneURL,
}) })
} }
if resp.NextPage == 0 {
break
}
listOpts.Page = resp.NextPage
} }
if err != nil {
return repos, err return leaks, err
}
return auditRepo(Repo{
repository: repo,
name: *githubRepo.Name,
})
} }
// githubToken returns a oauth2 client for the github api to consume // githubToken returns a oauth2 client for the github api to consume
@@ -867,16 +850,6 @@ func loadToml() error {
return nil return nil
} }
// ownerTarget checks if we are dealing with a remote owner
func ownerTarget() bool {
if opts.GithubOrg != "" ||
opts.GithubUser != "" ||
opts.OwnerPath != "" {
return true
}
return false
}
// getSSHAuth generates ssh auth // getSSHAuth generates ssh auth
func getSSHAuth() (*ssh.PublicKeys, error) { func getSSHAuth() (*ssh.PublicKeys, error) {
var ( var (
@@ -895,7 +868,7 @@ func getSSHAuth() (*ssh.PublicKeys, error) {
return sshAuth, err return sshAuth, err
} }
func (leak *Leak) log() { func (leak Leak) log() {
b, _ := json.MarshalIndent(leak, "", " ") b, _ := json.MarshalIndent(leak, "", " ")
fmt.Println(string(b)) fmt.Println(string(b))
} }