Compare commits

...
5 Commits
Author SHA1 Message Date
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
6 changed files with 387 additions and 80 deletions

No files matched your search

+16
View File
@@ -1,6 +1,22 @@
CHANGELOG CHANGELOG
========= =========
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 1.5.0
----- -----
- Support for CSV reporting - Support for CSV reporting
+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$
+2 -1
View File
@@ -52,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
+275
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,6 +165,95 @@ func TestGetRepo(t *testing.T) {
}) })
} }
} }
func TestRunAudit(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: "",
},
{
testOpts: Options{
GithubOrg: "gitleakstestorg",
Disk: true,
},
description: "test org on disk",
numLeaks: 2,
expectedErrMsg: "",
},
{
testOpts: Options{
OwnerPath: dir,
},
description: "test owner path",
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",
},
}
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) { func TestStartAudit(t *testing.T) {
err := loadToml() err := loadToml()
@@ -690,3 +808,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)
}
}
+68 -77
View File
@@ -15,6 +15,7 @@ import (
"path" "path"
"path/filepath" "path/filepath"
"regexp" "regexp"
"runtime"
"strings" "strings"
"sync" "sync"
"time" "time"
@@ -118,7 +119,9 @@ type Config struct {
} }
const defaultGithubURL = "https://api.github.com/" const defaultGithubURL = "https://api.github.com/"
const version = "1.5.0" const version = "1.7.0"
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
@@ -175,79 +178,74 @@ 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
)
_, 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)
} }
if err != nil { if err != nil {
os.Exit(1) log.Error(err)
os.Exit(errExit)
} }
setLogs() leaks, err := run()
err = optsGuard()
if err != nil { if err != nil {
log.Fatal(err) log.Error(err)
os.Exit(errExit)
} }
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)
}
}
leaks, err = startAudits()
if err != nil {
log.Fatal(err)
}
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) { func startAudits() ([]Leak, error) {
var leaks []Leak var leaks []Leak
// start audits // start audits
if opts.Repo != "" || opts.RepoPath != "" { if opts.OwnerPath != "" {
repo, err := getRepo()
if err != nil {
return leaks, err
}
return auditRepo(repo)
} else if opts.OwnerPath != "" {
repos, err := discoverRepos(opts.OwnerPath) repos, err := discoverRepos(opts.OwnerPath)
if err != nil { if err != nil {
return leaks, err return leaks, err
@@ -272,7 +270,7 @@ func startAudits() ([]Leak, error) {
log.Warnf("leaks found for repo %s", *githubRepo.Name) log.Warnf("leaks found for repo %s", *githubRepo.Name)
} }
if err != nil { if err != nil {
return leaks, err log.Warn(err)
} }
leaks = append(leaks, leaksFromRepo...) leaks = append(leaks, leaksFromRepo...)
} }
@@ -359,20 +357,16 @@ func getRepo() (Repo, error) {
// double dip // double dip
func auditRef(repo Repo, ref *plumbing.Reference, commitWg *sync.WaitGroup, commitChan chan []Leak) error { func auditRef(repo Repo, ref *plumbing.Reference, commitWg *sync.WaitGroup, commitChan chan []Leak) error {
var ( var (
err error err error
prevCommit *object.Commit prevCommit *object.Commit
limitGoRoutines bool semaphore chan bool
semaphore chan bool repoName string
repoName string
) )
repoName = repo.name repoName = repo.name
// goroutine limiting
if opts.MaxGoRoutines != 0 { if opts.MaxGoRoutines != 0 {
semaphore = make(chan bool, opts.MaxGoRoutines) maxGo = opts.MaxGoRoutines
limitGoRoutines = true
} }
semaphore = make(chan bool, maxGo)
cIter, err := repo.repository.Log(&git.LogOptions{From: ref.Hash()}) cIter, err := repo.repository.Log(&git.LogOptions{From: ref.Hash()})
if err != nil { if err != nil {
return err return err
@@ -385,9 +379,8 @@ func auditRef(repo Repo, ref *plumbing.Reference, commitWg *sync.WaitGroup, comm
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 semaphore <- true
}
commitWg.Add(1) commitWg.Add(1)
go func(c *object.Commit, prevCommit *object.Commit) { go func(c *object.Commit, prevCommit *object.Commit) {
var ( var (
@@ -395,6 +388,14 @@ func auditRef(repo Repo, ref *plumbing.Reference, commitWg *sync.WaitGroup, comm
filePath string filePath string
skipFile bool skipFile bool
) )
defer func() {
<-semaphore
commitChan <- leaks
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()
@@ -408,20 +409,12 @@ func auditRef(repo Repo, ref *plumbing.Reference, commitWg *sync.WaitGroup, comm
}) })
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() {
@@ -451,10 +444,6 @@ func auditRef(repo Repo, ref *plumbing.Reference, commitWg *sync.WaitGroup, comm
} }
} }
} }
if limitGoRoutines {
<-semaphore
}
commitChan <- leaks
}(c, prevCommit) }(c, prevCommit)
prevCommit = c prevCommit = c
return nil return nil
@@ -511,7 +500,6 @@ func auditRepo(repo Repo) ([]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
} }
} }
@@ -607,7 +595,7 @@ func getGithubRepos() ([]*github.Repository, error) {
githubClient.BaseURL = ghURL githubClient.BaseURL = ghURL
} }
githubOrgOptions = &github.RepositoryListByOrgOptions{ githubOrgOptions = &github.RepositoryListByOrgOptions{
ListOptions: github.ListOptions{PerPage: 10}, ListOptions: github.ListOptions{PerPage: 100},
} }
} else if opts.GithubUser != "" { } else if opts.GithubUser != "" {
githubClient = github.NewClient(githubToken()) githubClient = github.NewClient(githubToken())
@@ -619,7 +607,7 @@ func getGithubRepos() ([]*github.Repository, error) {
githubOptions = &github.RepositoryListOptions{ githubOptions = &github.RepositoryListOptions{
Affiliation: "owner", Affiliation: "owner",
ListOptions: github.ListOptions{ ListOptions: github.ListOptions{
PerPage: 10, PerPage: 100,
}, },
} }
} }
@@ -640,7 +628,7 @@ func getGithubRepos() ([]*github.Repository, error) {
return githubRepos, err return githubRepos, err
} }
} else if opts.GithubOrg != "" { } else if opts.GithubOrg != "" {
rs, resp, err := githubClient.Repositories.ListByOrg(ctx, opts.GithubOrg, githubOrgOptions) rs, resp, err = githubClient.Repositories.ListByOrg(ctx, opts.GithubOrg, githubOrgOptions)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -650,8 +638,10 @@ func getGithubRepos() ([]*github.Repository, error) {
return githubRepos, err return githubRepos, err
} }
} }
for _, githubRepo := range githubRepos { if opts.Log == "Debug" || opts.Log == "debug" {
log.Infof("staging repo %s", *githubRepo.Name) for _, githubRepo := range rs {
log.Debugf("staging repos %s", *githubRepo.Name)
}
} }
} }
} }
@@ -666,6 +656,7 @@ func auditGithubRepo(githubRepo *github.Repository) ([]Leak, error) {
log.Infof("cloning: %s", *githubRepo.Name) log.Infof("cloning: %s", *githubRepo.Name)
if opts.Disk { if opts.Disk {
ownerDir, err := ioutil.TempDir(dir, opts.GithubUser) ownerDir, err := ioutil.TempDir(dir, opts.GithubUser)
defer os.RemoveAll(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name))
if err != nil { if err != nil {
return leaks, fmt.Errorf("unable to generater owner temp dir: %v", err) return leaks, fmt.Errorf("unable to generater owner temp dir: %v", err)
} }