Compare commits

..
16 Commits
Author SHA1 Message Date
Zachary Rice 160015b872 Merge pull request #111 from zricethezav/fix-wl-commit
rm commit count log
2018-10-10 09:50:28 -05:00
zach rice abdf2c47f0 cl update 2018-10-10 09:43:01 -05:00
zach rice 8536f16ceb rm commit count log 2018-10-10 09:41:49 -05:00
Zachary Rice 6862c13bf7 Merge pull request #109 from zricethezav/depth
Depth
2018-10-09 21:13:29 -05:00
zach rice 9939c638ec better log 2018-10-09 21:07:49 -05:00
zach rice ed3a512b4b commit depth option 2018-10-09 21:01:56 -05:00
Zachary Rice 7c988c927d Merge pull request #107 from camaya/feature/add-entropy-checks
Add option to check string entropy
2018-10-09 18:46:21 -05:00
zach rice bde9af44ea merging, adding comments, updating flag description 2018-10-09 18:42:09 -05:00
Zachary Rice eee4d05642 Merge pull request #108 from camaya/fix-commit-option
Fix commit option
2018-10-09 16:18:54 -05:00
Cristhian Amaya 9144594d77 Fix commit option
The --commit option was being ignored becase the Close() function doesn't stop
the iterator.
According to the documentation:
https://godoc.org/gopkg.in/src-d/go-git.v4/plumbing/object#FileIter.ForEach
an ErrStop error should be send to stop it.
2018-10-09 16:49:16 +02:00
Cristhian Amaya 1cb15242fd Add option to check string entropy
Strings with high entropy have a good probability of being a secret.
2018-10-08 16:08:04 +02:00
Zachary Rice 08498600d1 Merge pull request #106 from zricethezav/exclude-fork
exclude fork
2018-10-07 18:42:42 -05:00
zach rice 88c0c7779b exclude fork 2018-10-07 18:39:17 -05:00
Zachary Rice 67454d109e Merge pull request #105 from zricethezav/wlrepo
Wlrepo
2018-10-07 18:26:18 -05:00
zach rice ce603c73b4 sample config opt 2018-10-07 18:19:43 -05:00
zach rice 55218fc8f8 whitelist repos 2018-10-07 18:09:10 -05:00
4 changed files with 249 additions and 79 deletions

No files matched your search

+22
View File
@@ -1,6 +1,28 @@
CHANGELOG
=========
1.11.1
----
- fix commit whitelist logic
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
+6 -2
View File
@@ -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,12 +41,15 @@ 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
+96 -36
View File
@@ -56,6 +56,17 @@ regexes= [
]
`
const testWhitelistRepo = `
[[regexes]]
description = "AWS"
regex = '''AKIA[0-9A-Z]{16}'''
[whitelist]
repos = [
"gronit",
]
`
var benchmarkRepo *RepoDescriptor
var benchmarkLeaksRepo *RepoDescriptor
@@ -166,9 +177,8 @@ func TestGetRepo(t *testing.T) {
}
}
func TestRun(t *testing.T) {
err := loadToml()
var err error
configsDir := testTomlLoader()
defer os.RemoveAll(configsDir)
dir, err = ioutil.TempDir("", "gitleaksTestOwner")
defer os.RemoveAll(dir)
@@ -185,7 +195,9 @@ func TestRun(t *testing.T) {
testOpts Options
description string
expectedErrMsg string
whiteListRepos []string
numLeaks int
configPath string
}{
{
testOpts: Options{
@@ -263,11 +275,32 @@ func TestRun(t *testing.T) {
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("TestRun", func() {
g.It(test.description, func() {
if test.configPath != "" {
os.Setenv("GITLEAKS_CONFIG", test.configPath)
}
opts = test.testOpts
leaks, err := run()
if err != nil {
@@ -344,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
}
@@ -387,6 +421,7 @@ func TestAuditRepo(t *testing.T) {
whiteListFiles []*regexp.Regexp
whiteListCommits map[string]bool
whiteListBranches []string
whiteListRepos []string
whiteListRegexes []*regexp.Regexp
configPath string
}{
@@ -511,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)
@@ -540,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 != "" {
@@ -632,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 {
@@ -796,22 +890,6 @@ func BenchmarkAuditRepo1000Proc(b *testing.B) {
auditGitRepo(benchmarkRepo)
}
}
func BenchmarkAuditRepo10000Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 10000
benchmarkRepo = getBenchmarkRepo()
for n := 0; n < b.N; n++ {
auditGitRepo(benchmarkRepo)
}
}
func BenchmarkAuditRepo100000Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 100000
benchmarkRepo = getBenchmarkRepo()
for n := 0; n < b.N; n++ {
auditGitRepo(benchmarkRepo)
}
}
func BenchmarkAuditLeakRepo1Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 1
@@ -872,21 +950,3 @@ func BenchmarkAuditLeakRepo1000Proc(b *testing.B) {
auditGitRepo(benchmarkRepo)
}
}
func BenchmarkAuditLeakRepo10000Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 10000
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
for n := 0; n < b.N; n++ {
auditGitRepo(benchmarkRepo)
}
}
func BenchmarkAuditLeakRepo100000Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 100000
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
for n := 0; n < b.N; n++ {
auditGitRepo(benchmarkRepo)
}
}
+125 -41
View File
@@ -5,8 +5,10 @@ import (
"crypto/md5"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math"
"net"
"net/http"
"net/url"
@@ -75,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
@@ -109,6 +115,7 @@ type Config struct {
Regexes []string
Commits []string
Branches []string
Repos []string
}
}
@@ -121,10 +128,16 @@ type gitDiff struct {
}
const defaultGithubURL = "https://api.github.com/"
const version = "1.7.3"
const version = "1.11.1"
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]]
@@ -150,7 +163,6 @@ description = "Twitter"
regex = '''(?i)twitter.*['\"][0-9a-zA-Z]{35,44}['\"]'''
[whitelist]
#regexes = [
# "AKAIMYFAKEAWKKEY",
#]
@@ -167,6 +179,10 @@ regex = '''(?i)twitter.*['\"][0-9a-zA-Z]{35,44}['\"]'''
#branches = [
# "dev/STUPDIFKNFEATURE"
#]
#repos = [
# "someYugeRepoWeKnowIsCLEAR"
#]
`
var (
@@ -177,10 +193,12 @@ 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() {
@@ -196,6 +214,10 @@ func main() {
fmt.Println(version)
os.Exit(0)
}
if opts.SampleConfig {
fmt.Println(defaultConfig)
os.Exit(0)
}
leaks, err := run()
if err != nil {
log.Error(err)
@@ -205,8 +227,9 @@ func main() {
writeReport(leaks)
}
log.Infof("%d commits inspected", totalCommits)
if len(leaks) != 0 {
log.Warnf("leaks detected")
log.Warnf("%d leaks detected", len(leaks))
os.Exit(leakExit)
}
}
@@ -354,6 +377,11 @@ func auditGitRepo(repo *RepoDescriptor) ([]Leak, error) {
err error
leaks []Leak
)
for _, repoName := range whiteListRepos {
if repoName == repo.name {
return nil, fmt.Errorf("skipping %s, whitelisted", repoName)
}
}
ref, err := repo.repository.Head()
if err != nil {
return leaks, err
@@ -407,13 +435,14 @@ func auditGitRepo(repo *RepoDescriptor) ([]Leak, error) {
// 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{}
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 {
@@ -426,10 +455,14 @@ func auditGitReference(repo *RepoDescriptor, ref *plumbing.Reference) []Leak {
return nil
}
err = cIter.ForEach(func(c *object.Commit) error {
if c.Hash.String() == opts.Commit {
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()] {
prevCommit = c
log.Infof("skipping commit: %s\n", c.Hash.String())
return nil
}
@@ -554,30 +587,68 @@ func inspect(diff gitDiff) []Leak {
break
}
leak := Leak{
Line: line,
Commit: diff.commit.Hash.String(),
Offender: match,
Type: leakType,
Message: diff.commit.Message,
Author: diff.commit.Author.String(),
File: diff.filePath,
Branch: diff.branchName,
Repo: diff.repoName,
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
}
// 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.
@@ -694,6 +765,14 @@ func cloneGithubRepo(githubRepo *github.Repository) (*RepoDescriptor, 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)
@@ -836,6 +915,10 @@ func optsGuard() error {
}
}
if opts.Entropy > 8 {
return fmt.Errorf("The maximum level of entropy is 8")
}
return nil
}
@@ -878,6 +961,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