Compare commits

..
14 Commits
Author SHA1 Message Date
Zachary Rice 4f7ce9c195 Merge pull request #126 from zricethezav/fix/concurrency
Fix/concurrency
2018-10-24 16:56:01 -05:00
zach rice 847687a637 fixing test. travis doesnt have rsa id 2018-10-24 16:48:34 -05:00
zach rice 94389137e8 removing private opts 2018-10-24 16:00:15 -05:00
zach rice 98e6ba9378 better ssh handling 2018-10-24 15:49:53 -05:00
zach rice e288db29a8 fixing tests 2018-10-24 12:40:05 -05:00
zach rice 98aeee9b1d fixing everything 2018-10-24 12:28:54 -05:00
zach rice 64e7afea98 updating version 2018-10-24 09:58:39 -05:00
zach rice 16765c19cf adding go routines does not help performance much.... posting benchmarks soon 2018-10-24 09:38:36 -05:00
Zachary Rice 87d916fc24 Merge pull request #123 from zricethezav/update/whitelist-repo
whitelist repo update
2018-10-23 16:38:17 -05:00
zach rice 21b59fab5d whitelist repo update 2018-10-23 16:34:36 -05:00
Zachary Rice 9272e1e556 Merge pull request #122 from zricethezav/feature/entropy-range
entropy ranges
2018-10-22 18:55:51 -05:00
zach rice 0a51dabb17 entropy ranges 2018-10-22 18:51:01 -05:00
Zachary Rice 8c1cee4e00 Merge pull request #116 from keirans/documentation_updates
Documentation enhancements
2018-10-21 10:23:48 -05:00
Keiran Sweet 4d5315e2ca Documentation updates 2018-10-21 17:12:00 +11:00
5 changed files with 292 additions and 183 deletions

No files matched your search

+9
View File
@@ -1,6 +1,15 @@
CHANGELOG CHANGELOG
========= =========
1.15.0
----
- Whitelist repos use regex now
- Whitelist repo check before clone
1.14.0
----
- Entropy Range support in gitleaks config
1.13.0 1.13.0
---- ----
- Github PR support - Github PR support
+65 -12
View File
@@ -6,20 +6,58 @@
</p> </p>
## Audit git repos for secrets ## Audit git repos for secrets
### Powered by src-d's [go-git](https://github.com/src-d/go-git)
<p align="center"> Gitleaks provides a way for you to find unencrypted secrets and other unwanted data types in git source code repositories.
As part of it's core functionality, it provides;
* Github support including support for bulk organisation and repository owner (user) repository scans, as well as pull request scanning for use in common CI workflows.
* Support for private repository scans, and repositories that require key based authentication
* Output in CSV and JSON formats for consumption in other reporting tools and frameworks
* Externalised configuration for environment specific customisation including regex rules
* Customisable repository name, file type, commit ID, branchname and regex whitelisting to reduce false positives
* High performance through the use of src-d's [go-git](https://github.com/src-d/go-git) framework
It has been sucessfully used in a number of different scenarios, including;
* Adhoc scans of local and remote repositories by filesystem path or clone URL
* Automated scans of github users and organisations (Both public and enterprise platforms)
* As part of a CICD workflow to identify secrets before they make it deeper into your codebase
* As part of a wider secrets auditing automation capability for git data in large environments
### Example execution
<p align="left">
<img src="https://cdn.rawgit.com/zricethezav/5bf8259b7fea0170becffc06b8588edb/raw/f762769fe20ef3669bff34612b1bede6457631e6/termtosvg_je8bp82s.svg"> <img src="https://cdn.rawgit.com/zricethezav/5bf8259b7fea0170becffc06b8588edb/raw/f762769fe20ef3669bff34612b1bede6457631e6/termtosvg_je8bp82s.svg">
</p> </p>
#### Installing #### Installation
Written in Go, gitleaks is available in binary form for many popular platforms and OS types from the [releases page](https://github.com/zricethezav/gitleaks). Alternatively, executed via Docker or it can be installed using Go directly, as per the below;
##### Docker
```bash
# Run gitleaks against a public repository
docker run --rm --name=gitleaks zricethezav/gitleaks -v -r https://github.com/zricethezav/gitleaks.git
# Run gitleaks against a local repository already cloned into /tmp/
docker run --rm --name=gitleaks -v /tmp/:/code/ zricethezav/gitleaks -v --repo-path=/code/gitleaks
# Run gitleaks against a specific Github Pull request
docker run --rm --name=gitleaks -e GITHUB_TOKEN={your token} zricethezav/gitleaks --github-pr=https://github.com/owner/repo/pull/9000
```
##### Go
```bash ```bash
go get -u github.com/zricethezav/gitleaks go get -u github.com/zricethezav/gitleaks
``` ```
Or download from release binaries [here](https://github.com/zricethezav/gitleaks/releases)
#### Usage and Options #### Usage and Options
gitleaks has a wide range of configuration options that can be adjusted at runtime or via a configuration file based on your specific requirements.
``` ```
Usage: Usage:
gitleaks [OPTIONS] gitleaks [OPTIONS]
@@ -30,7 +68,6 @@ Application Options:
--github-org= Github organization 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/) --github-url= GitHub API Base URL, use for GitHub Enterprise. Example: https://github.example.com/api/v3/ (default: https://api.github.com/)
--github-pr= Github PR url to audit. This does not clone the repo. GITHUB_TOKEN must be set --github-pr= Github PR url to audit. This does not clone the repo. GITHUB_TOKEN must be set
-p, --private Include private repos in audit
-b, --branch= branch name to audit (defaults to HEAD) -b, --branch= branch name to audit (defaults to HEAD)
-c, --commit= sha of commit to stop at -c, --commit= sha of commit to stop at
--depth= maximum commit depth --depth= maximum commit depth
@@ -54,18 +91,34 @@ Application Options:
Help Options: Help Options:
-h, --help Show this help message -h, --help Show this help message
``` ```
#### Exit Codes #### Exit Codes
Gitleaks provides consisten exist codes to assist in automation workflows such as CICD platforms and bulk scanning.
These can be effectively used in conjunction with the report output file to detect and return meaningful data back to the user or external system about if leaks have been detected, and where they reside.
The code return codes are:
``` ```
0: no leaks 0: no leaks
1: leaks present 1: leaks present
2: error encountered 2: error encountered
``` ```
#### Additional Examples and Explanations #### Additional information
Check the wiki [here](https://github.com/zricethezav/gitleaks/wiki) * Additional documentation about how gitleaks functions can be found on the [wiki page](https://github.com/zricethezav/gitleaks/wiki)
* The below links detail the various approaches to remediating unwanted data in git repos
* [Removing sensitive data from a repository (github.com)](https://help.github.com/articles/removing-sensitive-data-from-a-repository/)
* [Removing sensitive files from commit history (atlassian.com)](https://community.atlassian.com/t5/Bitbucket-questions/Remove-sensitive-files-from-commit-history/qaq-p/243807)
* [Rewrite git history with the BFG (theguardian.com)](https://www.theguardian.com/info/developer-blog/2013/apr/29/rewrite-git-history-with-the-bfg)
* [Auditing Bitbucket Server Data for Credentials in AWS (sourcedgroup.com)](https://www.sourcedgroup.com/blog/auditing-bitbucket-server-data-credentials-in-aws)
This blog post details how gitleaks was used to audit data in Atlassian Bitbucket server when hosted on AWS, and visualise the results in a compliance dashboard using Splunk.
* How does gitleaks differ to github token scanning ?
* [Github recently announced](https://blog.github.com/2018-10-16-future-of-software/#github-token-scanning-for-public-repositories-public-beta) a new capbility to their cloud platform that detects exposed credentials for a number of common services and platforms and automatically notifies the provider for revocation or similar action. Gitleaks provides a similar detection capability for non-github cloud users, in which repositories can be easily audited and results provided in a number of formats.
### If you find a valid leak in a repo
Please read this [Github article on removing sensitive data from a repository](https://help.github.com/articles/removing-sensitive-data-from-a-repository/) to remove the sensitive information from your history.
### Run me with docker
Simply run `docker run --rm --name=gitleaks zricethezav/gitleaks --help`
+6 -16
View File
@@ -117,11 +117,7 @@ func auditGithubRepos() ([]Leak, error) {
break break
} }
if opts.GithubUser != "" { if opts.GithubUser != "" {
if opts.IncludePrivate { pagedGithubRepos, resp, err = githubClient.Repositories.List(ctx, opts.GithubUser, githubOptions)
pagedGithubRepos, resp, err = githubClient.Repositories.List(ctx, "", githubOptions)
} else {
pagedGithubRepos, resp, err = githubClient.Repositories.List(ctx, opts.GithubUser, githubOptions)
}
if err != nil { if err != nil {
done = true done = true
} }
@@ -188,9 +184,9 @@ func cloneGithubRepo(githubRepo *github.Repository) (*RepoDescriptor, error) {
if opts.ExcludeForks && githubRepo.GetFork() { if opts.ExcludeForks && githubRepo.GetFork() {
return nil, fmt.Errorf("skipping %s, excluding forks", *githubRepo.Name) return nil, fmt.Errorf("skipping %s, excluding forks", *githubRepo.Name)
} }
for _, repoName := range whiteListRepos { for _, re := range whiteListRepos {
if repoName == *githubRepo.Name { if re.FindString(*githubRepo.Name) != "" {
return nil, fmt.Errorf("skipping %s, whitelisted", repoName) return nil, fmt.Errorf("skipping %s, whitelisted", *githubRepo.Name)
} }
} }
log.Infof("cloning: %s", *githubRepo.Name) log.Infof("cloning: %s", *githubRepo.Name)
@@ -199,10 +195,7 @@ func cloneGithubRepo(githubRepo *github.Repository) (*RepoDescriptor, error) {
if err != nil { if err != nil {
return nil, 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 {
if sshAuth == nil {
return nil, fmt.Errorf("no ssh auth available")
}
repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{ repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
URL: *githubRepo.SSHURL, URL: *githubRepo.SSHURL,
Auth: sshAuth, Auth: sshAuth,
@@ -213,10 +206,7 @@ func cloneGithubRepo(githubRepo *github.Repository) (*RepoDescriptor, error) {
}) })
} }
} else { } else {
if opts.IncludePrivate { if sshAuth != nil {
if sshAuth == nil {
return nil, fmt.Errorf("no ssh auth available")
}
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{ repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: *githubRepo.SSHURL, URL: *githubRepo.SSHURL,
Auth: sshAuth, Auth: sshAuth,
+77 -54
View File
@@ -67,6 +67,26 @@ repos = [
] ]
` `
const testEntropyRange = `
[misc]
entropy = [
"7.5-8.0",
"3.3-3.4",
]
`
const testBadEntropyRange = `
[misc]
entropy = [
"8.0-3.0",
]
`
const testBadEntropyRange2 = `
[misc]
entropy = [
"8.0-8.9",
]
`
var benchmarkRepo *RepoDescriptor var benchmarkRepo *RepoDescriptor
var benchmarkLeaksRepo *RepoDescriptor var benchmarkLeaksRepo *RepoDescriptor
@@ -147,17 +167,15 @@ func TestGetRepo(t *testing.T) {
}, },
{ {
testOpts: Options{ testOpts: Options{
Repo: "https://github.com/gitleakstest/private", Repo: "https://github.com/gitleakstest/private",
IncludePrivate: true,
}, },
description: "test private repo", description: "test private repo",
expectedErrMsg: "invalid auth method", expectedErrMsg: "invalid auth method",
}, },
{ {
testOpts: Options{ testOpts: Options{
Repo: "https://github.com/gitleakstest/private", Repo: "https://github.com/gitleakstest/private",
IncludePrivate: true, Disk: true,
Disk: true,
}, },
description: "test private repo", description: "test private repo",
expectedErrMsg: "invalid auth method", expectedErrMsg: "invalid auth method",
@@ -244,13 +262,12 @@ func TestRun(t *testing.T) {
}, },
{ {
testOpts: Options{ testOpts: Options{
GithubOrg: "gitleakstestorg", Repo: "git@github.com:gitleakstest/gronit.git",
IncludePrivate: true, SSHKey: "trash",
SSHKey: "reallyreallyreallyreallywrongpath",
}, },
description: "test private org no ssh", description: "test leak",
numLeaks: 0, numLeaks: 0,
expectedErrMsg: "unable to generate ssh key: open reallyreallyreallyreallywrongpath: no such file or directory", expectedErrMsg: "unable to generate ssh key: open trash: no such file or directory",
}, },
{ {
testOpts: Options{ testOpts: Options{
@@ -427,6 +444,9 @@ func testTomlLoader() string {
ioutil.WriteFile(path.Join(tmpDir, "commit"), []byte(testWhitelistCommit), 0644) ioutil.WriteFile(path.Join(tmpDir, "commit"), []byte(testWhitelistCommit), 0644)
ioutil.WriteFile(path.Join(tmpDir, "file"), []byte(testWhitelistFile), 0644) ioutil.WriteFile(path.Join(tmpDir, "file"), []byte(testWhitelistFile), 0644)
ioutil.WriteFile(path.Join(tmpDir, "repo"), []byte(testWhitelistRepo), 0644) ioutil.WriteFile(path.Join(tmpDir, "repo"), []byte(testWhitelistRepo), 0644)
ioutil.WriteFile(path.Join(tmpDir, "entropy"), []byte(testEntropyRange), 0644)
ioutil.WriteFile(path.Join(tmpDir, "badEntropy"), []byte(testBadEntropyRange), 0644)
ioutil.WriteFile(path.Join(tmpDir, "badEntropy2"), []byte(testBadEntropyRange2), 0644)
return tmpDir return tmpDir
} }
@@ -470,7 +490,7 @@ func TestAuditRepo(t *testing.T) {
whiteListFiles []*regexp.Regexp whiteListFiles []*regexp.Regexp
whiteListCommits map[string]bool whiteListCommits map[string]bool
whiteListBranches []string whiteListBranches []string
whiteListRepos []string whiteListRepos []*regexp.Regexp
whiteListRegexes []*regexp.Regexp whiteListRegexes []*regexp.Regexp
configPath string configPath string
}{ }{
@@ -595,8 +615,8 @@ func TestAuditRepo(t *testing.T) {
repo: leaksRepo, repo: leaksRepo,
description: "audit whitelist repo", description: "audit whitelist repo",
numLeaks: 0, numLeaks: 0,
whiteListRepos: []string{ whiteListRepos: []*regexp.Regexp{
"gronit", regexp.MustCompile("gronit"),
}, },
}, },
{ {
@@ -611,34 +631,53 @@ func TestAuditRepo(t *testing.T) {
testOpts: Options{ testOpts: Options{
Entropy: 4.7, Entropy: 4.7,
}, },
numLeaks: 7, numLeaks: 6,
}, },
{ {
repo: leaksRepo, repo: leaksRepo,
description: "Audit until specific commit", description: "Audit until specific commit",
numLeaks: 1, numLeaks: 2,
testOpts: Options{ testOpts: Options{
Commit: "f6839959b7bbdcd23008f1fb16f797f35bcd3a0c", Commit: "f6839959b7bbdcd23008f1fb16f797f35bcd3a0c",
}, },
}, },
{ {
repo: leaksRepo, repo: leaksRepo,
description: "commit depth = 1, no leaks", description: "commit depth = 1, one leak",
numLeaks: 0, numLeaks: 1,
testOpts: Options{ testOpts: Options{
Depth: 1, Depth: 1,
}, },
}, },
{ {
repo: leaksRepo, repo: leaksRepo,
description: "commit depth = 2, one leak", description: "commit depth = 2, two leaks",
numLeaks: 1, numLeaks: 2,
testOpts: Options{ testOpts: Options{
Depth: 2, Depth: 2,
}, },
}, },
{
repo: leaksRepo,
description: "toml entropy range",
numLeaks: 283,
configPath: path.Join(configsDir, "entropy"),
},
{
repo: leaksRepo,
description: "toml bad entropy range",
numLeaks: 0,
configPath: path.Join(configsDir, "badEntropy"),
expectedErrMsg: "entropy range must be ascending",
},
{
repo: leaksRepo,
description: "toml bad entropy2 range",
numLeaks: 0,
configPath: path.Join(configsDir, "badEntropy2"),
expectedErrMsg: "invalid entropy ranges, must be within 0.0-8.0",
},
} }
whiteListCommits = make(map[string]bool) whiteListCommits = make(map[string]bool)
g := goblin.Goblin(t) g := goblin.Goblin(t)
for _, test := range tests { for _, test := range tests {
@@ -671,19 +710,24 @@ func TestAuditRepo(t *testing.T) {
} else { } else {
whiteListRepos = nil whiteListRepos = nil
} }
skip := false
// config paths // config paths
if test.configPath != "" { if test.configPath != "" {
os.Setenv("GITLEAKS_CONFIG", test.configPath) os.Setenv("GITLEAKS_CONFIG", test.configPath)
loadToml() err := loadToml()
if err != nil {
g.Assert(err.Error()).Equal(test.expectedErrMsg)
skip = true
}
} }
if !skip {
leaks, err = auditGitRepo(test.repo)
leaks, err = auditGitRepo(test.repo) if opts.Redact {
g.Assert(leaks[0].Offender).Equal("REDACTED")
if opts.Redact { }
g.Assert(leaks[0].Offender).Equal("REDACTED") g.Assert(len(leaks)).Equal(test.numLeaks)
} }
g.Assert(len(leaks)).Equal(test.numLeaks)
}) })
}) })
} }
@@ -704,45 +748,24 @@ func TestOptionGuard(t *testing.T) {
}, },
{ {
testOpts: Options{ testOpts: Options{
IncludePrivate: true, GithubUser: "fakeUser",
GithubOrg: "fakeOrg", GithubOrg: "fakeOrg",
},
description: "private org no githubtoken",
expectedErrMsg: "user/organization private repos require env var GITHUB_TOKEN to be set",
githubToken: false,
},
{
testOpts: Options{
IncludePrivate: true,
GithubUser: "fakeUser",
},
description: "private user no githubtoken",
expectedErrMsg: "user/organization private repos require env var GITHUB_TOKEN to be set",
githubToken: false,
},
{
testOpts: Options{
IncludePrivate: true,
GithubUser: "fakeUser",
GithubOrg: "fakeOrg",
}, },
description: "double owner", description: "double owner",
expectedErrMsg: "github user and organization set", expectedErrMsg: "github user and organization set",
}, },
{ {
testOpts: Options{ testOpts: Options{
IncludePrivate: true, GithubOrg: "fakeOrg",
GithubOrg: "fakeOrg", OwnerPath: "/dev/null",
OwnerPath: "/dev/null",
}, },
description: "local and remote target", description: "local and remote target",
expectedErrMsg: "github organization set and local owner path", expectedErrMsg: "github organization set and local owner path",
}, },
{ {
testOpts: Options{ testOpts: Options{
IncludePrivate: true, GithubUser: "fakeUser",
GithubUser: "fakeUser", OwnerPath: "/dev/null",
OwnerPath: "/dev/null",
}, },
description: "local and remote target", description: "local and remote target",
expectedErrMsg: "github user set and local owner path", expectedErrMsg: "github user set and local owner path",
+135 -101
View File
@@ -16,6 +16,7 @@ import (
"path/filepath" "path/filepath"
"regexp" "regexp"
"runtime" "runtime"
"strconv"
"strings" "strings"
"sync" "sync"
"time" "time"
@@ -59,12 +60,11 @@ type RepoDescriptor struct {
// Options for gitleaks // Options for gitleaks
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:"Github user to audit"` GithubUser string `long:"github-user" description:"Github user to audit"`
GithubOrg string `long:"github-org" description:"Github organization 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/"`
GithubPR string `long:"github-pr" description:"Github PR url to audit. This does not clone the repo. GITHUB_TOKEN must be set"` GithubPR string `long:"github-pr" description:"Github PR url to audit. This does not clone the repo. GITHUB_TOKEN must be set"`
IncludePrivate bool `short:"p" long:"private" description:"Include private repos in audit"`
/* /*
TODO: TODO:
@@ -113,6 +113,9 @@ type Config struct {
Branches []string Branches []string
Repos []string Repos []string
} }
Misc struct {
Entropy []string
}
} }
type gitDiff struct { type gitDiff struct {
@@ -127,8 +130,13 @@ type gitDiff struct {
author string author string
} }
type entropyRange struct {
v1 float64
v2 float64
}
const defaultGithubURL = "https://api.github.com/" const defaultGithubURL = "https://api.github.com/"
const version = "1.13.0" const version = "1.16.0"
const errExit = 2 const errExit = 2
const leakExit = 1 const leakExit = 1
const defaultConfig = ` const defaultConfig = `
@@ -177,11 +185,17 @@ regex = '''(?i)twitter.*['\"][0-9a-zA-Z]{35,44}['\"]'''
#] #]
#branches = [ #branches = [
# "dev/STUPDIFKNFEATURE" # "dev/goodrepo"
#] #]
#repos = [ #repos = [
# "someYugeRepoWeKnowIsCLEAR" # "mygoodrepo"
#]
[misc]
#entropy = [
# "3.3-4.30"
# "6.0-8.0
#] #]
` `
@@ -193,7 +207,8 @@ var (
whiteListFiles []*regexp.Regexp whiteListFiles []*regexp.Regexp
whiteListCommits map[string]bool whiteListCommits map[string]bool
whiteListBranches []string whiteListBranches []string
whiteListRepos []string whiteListRepos []*regexp.Regexp
entropyRanges []entropyRange
fileDiffRegex *regexp.Regexp fileDiffRegex *regexp.Regexp
sshAuth *ssh.PublicKeys sshAuth *ssh.PublicKeys
dir string dir string
@@ -234,6 +249,10 @@ func main() {
now := time.Now() now := time.Now()
leaks, err := run() leaks, err := run()
if err != nil { if err != nil {
if strings.Contains(err.Error(), "whitelisted") {
log.Info(err.Error())
os.Exit(0)
}
log.Error(err) log.Error(err)
os.Exit(errExit) os.Exit(errExit)
} }
@@ -260,13 +279,11 @@ func run() ([]Leak, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
if opts.IncludePrivate { sshAuth, err = getSSHAuth()
// if including private repos use ssh as authentication if err != nil {
sshAuth, err = getSSHAuth() return leaks, err
if err != nil {
return nil, err
}
} }
if opts.Disk { if opts.Disk {
// temporary directory where all the gitleaks plain clones will reside // temporary directory where all the gitleaks plain clones will reside
dir, err = ioutil.TempDir("", "gitleaks") dir, err = ioutil.TempDir("", "gitleaks")
@@ -299,8 +316,7 @@ func run() ([]Leak, error) {
leaks = append(leaksFromRepo, leaks...) leaks = append(leaksFromRepo, leaks...)
} }
} else if opts.GithubOrg != "" || opts.GithubUser != "" { } else if opts.GithubOrg != "" || opts.GithubUser != "" {
// Audit a github owner -- a user or organization. If you want to include // Audit a github owner -- a user or organization.
// private repos you must pass a --private/-p option and have your ssh keys set
leaks, err = auditGithubRepos() leaks, err = auditGithubRepos()
if err != nil { if err != nil {
return leaks, err return leaks, err
@@ -335,18 +351,22 @@ func writeReport(leaks []Leak) error {
return err return err
} }
// cloneRepo clones a repo to memory(default) or to disk if the --disk option is set. If you want to // cloneRepo clones a repo to memory(default) or to disk if the --disk option is set.
// 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) { func cloneRepo() (*RepoDescriptor, error) {
var ( var (
err error err error
repo *git.Repository repo *git.Repository
) )
// check if whitelist
for _, re := range whiteListRepos {
if re.FindString(opts.Repo) != "" {
return nil, fmt.Errorf("skipping %s, whitelisted", opts.Repo)
}
}
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 strings.HasPrefix(opts.Repo, "git") {
repo, 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,
@@ -359,11 +379,11 @@ func cloneRepo() (*RepoDescriptor, error) {
}) })
} }
} else if opts.RepoPath != "" { } else if opts.RepoPath != "" {
log.Infof("opening %s", opts.Repo) log.Infof("opening %s", opts.RepoPath)
repo, 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 strings.HasPrefix(opts.Repo, "git") {
repo, 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,
@@ -393,9 +413,9 @@ func auditGitRepo(repo *RepoDescriptor) ([]Leak, error) {
err error err error
leaks []Leak leaks []Leak
) )
for _, repoName := range whiteListRepos { for _, re := range whiteListRepos {
if repoName == repo.name { if re.FindString(repo.name) != "" {
return nil, fmt.Errorf("skipping %s, whitelisted", repoName) return leaks, fmt.Errorf("skipping %s, whitelisted", repo.name)
} }
} }
ref, err := repo.repository.Head() ref, err := repo.repository.Head()
@@ -447,95 +467,58 @@ func auditGitRepo(repo *RepoDescriptor) ([]Leak, error) {
} }
// auditGitReference beings the audit for a git reference. This function will // 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 // traverse the git reference and audit each line of each diff.
// the --max-go option (default is set to the number of cores on your cpu).
func auditGitReference(repo *RepoDescriptor, ref *plumbing.Reference) []Leak { func auditGitReference(repo *RepoDescriptor, ref *plumbing.Reference) []Leak {
var ( var (
err error err error
prevCommit *object.Commit
semaphore chan bool
repoName string repoName string
leaks []Leak leaks []Leak
commitCount int
commitWg sync.WaitGroup commitWg sync.WaitGroup
mutex = &sync.Mutex{} mutex = &sync.Mutex{}
commitCount int semaphore chan bool
) )
repoName = repo.name repoName = repo.name
if opts.MaxGoRoutines != 0 { if opts.MaxGoRoutines != 0 {
maxGo = opts.MaxGoRoutines maxGo = opts.MaxGoRoutines
} }
if opts.RepoPath != "" {
maxGo = 1
}
semaphore = make(chan bool, maxGo) 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 nil return nil
} }
err = cIter.ForEach(func(c *object.Commit) error { err = cIter.ForEach(func(c *object.Commit) error {
if c.Hash.String() == opts.Commit || (opts.Depth != 0 && commitCount == opts.Depth) { if c == nil || c.Hash.String() == opts.Commit || (opts.Depth != 0 && commitCount == opts.Depth) {
cIter.Close() cIter.Close()
return errors.New("ErrStop") return errors.New("ErrStop")
} }
commitCount = commitCount + 1 commitCount = commitCount + 1
totalCommits = totalCommits + 1 totalCommits = totalCommits + 1
if whiteListCommits[c.Hash.String()] { if whiteListCommits[c.Hash.String()] {
prevCommit = c
log.Infof("skipping commit: %s\n", c.Hash.String()) log.Infof("skipping commit: %s\n", c.Hash.String())
return nil return nil
} }
if prevCommit != nil {
if whiteListCommits[prevCommit.Hash.String()] {
prevCommit = c
log.Infof("skipping commit: %s\n", c.Hash.String())
return nil
}
}
commitWg.Add(1) err = c.Parents().ForEach(func(parent *object.Commit) error {
semaphore <- true commitWg.Add(1)
go func(c *object.Commit, prevCommit *object.Commit) { semaphore <- true
var ( go func(c *object.Commit, parent *object.Commit) {
filePath string var (
skipFile bool filePath string
) skipFile bool
defer func() { )
commitWg.Done() defer func() {
<-semaphore commitWg.Done()
if r := recover(); r != nil { <-semaphore
log.Warnf("recoverying from panic on commit %s, likely large diff causing panic", c.Hash.String()) if r := recover(); r != nil {
} log.Warnf("recoverying from panic on commit %s, likely large diff causing panic", c.Hash.String())
}()
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 := gitDiff{ }()
branchName: string(ref.Name()), patch, err := c.Patch(parent)
repoName: repoName,
filePath: file.Name,
content: content,
sha: c.Hash.String(),
author: c.Author.String(),
message: c.Message,
}
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 { 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())
return return
@@ -566,9 +549,9 @@ func auditGitReference(repo *RepoDescriptor, ref *plumbing.Reference) []Leak {
repoName: repoName, repoName: repoName,
filePath: filePath, filePath: filePath,
content: chunk.Content(), content: chunk.Content(),
sha: prevCommit.Hash.String(), sha: c.Hash.String(),
author: prevCommit.Author.String(), author: c.Author.String(),
message: prevCommit.Message, message: c.Message,
} }
chunkLeaks := inspect(diff) chunkLeaks := inspect(diff)
for _, leak := range chunkLeaks { for _, leak := range chunkLeaks {
@@ -579,9 +562,9 @@ func auditGitReference(repo *RepoDescriptor, ref *plumbing.Reference) []Leak {
} }
} }
} }
} }(c, parent)
}(c, prevCommit) return nil
prevCommit = c })
return nil return nil
}) })
commitWg.Wait() commitWg.Wait()
@@ -622,11 +605,24 @@ func inspect(diff gitDiff) []Leak {
leaks = addLeak(leaks, line, match, leakType, diff) leaks = addLeak(leaks, line, match, leakType, diff)
} }
if opts.Entropy > 0 { if opts.Entropy > 0 || len(entropyRanges) != 0 {
entropyLeak := false
words := strings.Fields(line) words := strings.Fields(line)
for _, word := range words { for _, word := range words {
if getShannonEntropy(word) >= opts.Entropy { entropy := getShannonEntropy(word)
leaks = addLeak(leaks, line, word, "High Entropy", diff) if entropy >= opts.Entropy && len(entropyRanges) == 0 {
entropyLeak = true
}
if len(entropyRanges) != 0 {
for _, eR := range entropyRanges {
if entropy > eR.v1 && entropy < eR.v2 {
entropyLeak = true
}
}
}
if entropyLeak {
leaks = addLeak(leaks, line, word, fmt.Sprintf("Entropy: %.2f", entropy), diff)
entropyLeak = false
} }
} }
} }
@@ -734,8 +730,6 @@ func optsGuard() error {
return fmt.Errorf("github organization set and local owner path") return fmt.Errorf("github organization set and local owner path")
} else if opts.GithubUser != "" && opts.OwnerPath != "" { } else if opts.GithubUser != "" && opts.OwnerPath != "" {
return fmt.Errorf("github user set and local owner path") return fmt.Errorf("github user set and local owner path")
} else if opts.IncludePrivate && os.Getenv("GITHUB_TOKEN") == "" && (opts.GithubOrg != "" || opts.GithubUser != "") {
return fmt.Errorf("user/organization private repos require env var GITHUB_TOKEN to be set")
} }
// do the URL Parse and error checking here, so we can skip it later // do the URL Parse and error checking here, so we can skip it later
@@ -813,6 +807,13 @@ func loadToml() error {
} }
} }
if len(config.Misc.Entropy) != 0 {
err := entropyLimits(config.Misc.Entropy)
if err != nil {
return err
}
}
if singleSearchRegex != nil { if singleSearchRegex != nil {
regexes["singleSearch"] = singleSearchRegex regexes["singleSearch"] = singleSearchRegex
} else { } else {
@@ -821,7 +822,6 @@ func loadToml() error {
} }
} }
whiteListBranches = config.Whitelist.Branches whiteListBranches = config.Whitelist.Branches
whiteListRepos = config.Whitelist.Repos
whiteListCommits = make(map[string]bool) whiteListCommits = make(map[string]bool)
for _, commit := range config.Whitelist.Commits { for _, commit := range config.Whitelist.Commits {
whiteListCommits[commit] = true whiteListCommits[commit] = true
@@ -832,10 +832,40 @@ func loadToml() error {
for _, regex := range config.Whitelist.Regexes { for _, regex := range config.Whitelist.Regexes {
whiteListRegexes = append(whiteListRegexes, regexp.MustCompile(regex)) whiteListRegexes = append(whiteListRegexes, regexp.MustCompile(regex))
} }
for _, regex := range config.Whitelist.Repos {
whiteListRepos = append(whiteListRepos, regexp.MustCompile(regex))
}
return nil return nil
} }
// entropyLimits hydrates entropyRanges which allows for fine tuning entropy checking
func entropyLimits(entropyLimitStr []string) error {
for _, span := range entropyLimitStr {
split := strings.Split(span, "-")
v1, err := strconv.ParseFloat(split[0], 64)
if err != nil {
return err
}
v2, err := strconv.ParseFloat(split[1], 64)
if err != nil {
return err
}
if v1 > v2 {
return fmt.Errorf("entropy range must be ascending")
}
r := entropyRange{
v1: v1,
v2: v2,
}
if r.v1 > 8.0 || r.v1 < 0.0 || r.v2 > 8.0 || r.v2 < 0.0 {
return fmt.Errorf("invalid entropy ranges, must be within 0.0-8.0")
}
entropyRanges = append(entropyRanges, r)
}
return nil
}
// getSSHAuth return an ssh auth use by go-git to clone repos behind authentication. // 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, // 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 // gitleaks will use the default $HOME/.ssh/id_rsa key
@@ -851,9 +881,13 @@ func getSSHAuth() (*ssh.PublicKeys, error) {
} }
sshAuth, err := ssh.NewPublicKeysFromFile("git", sshKeyPath, "") sshAuth, err := ssh.NewPublicKeysFromFile("git", sshKeyPath, "")
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to generate ssh key: %v", err) if strings.HasPrefix(opts.Repo, "git") {
// if you are attempting to clone a git repo via ssh and supply a bad ssh key,
// the clone will fail.
return nil, fmt.Errorf("unable to generate ssh key: %v", err)
}
} }
return sshAuth, err return sshAuth, nil
} }
func (leak Leak) log() { func (leak Leak) log() {