mirror of
https://github.com/gitleaks/gitleaks.git
synced 2026-11-27 19:54:24 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
60267523e9 | ||
|
|
8153da6e9c | ||
|
|
5f6fb388ec | ||
|
|
ba49396755 | ||
|
|
40240cb5ee | ||
|
|
bba926693e | ||
|
|
9103834503 | ||
|
|
7e3c740592 | ||
|
|
35a59746df | ||
|
|
23b5ce3264 | ||
|
|
03c53d2978 | ||
|
|
695449d73d | ||
|
|
6bad1e7194 | ||
|
|
77dec1461b | ||
|
|
14d77f59d4 | ||
|
|
afb598cf15 | ||
|
|
b4c6fe92e0 | ||
|
|
f50577be1c | ||
|
|
c358ae9310 | ||
|
|
9554258d02 | ||
|
|
95ee2cc30e | ||
|
|
79a35f0c27 | ||
|
|
7a021cda9e | ||
|
|
447f7a04cb | ||
|
|
e5b62cbc7c | ||
|
|
6739a34f74 | ||
|
|
e502bf29de | ||
|
|
51b504bf99 | ||
|
|
107d582e7b | ||
|
|
ea42ed406f | ||
|
|
c869812875 | ||
|
|
4f7ce9c195 | ||
|
|
847687a637 | ||
|
|
94389137e8 | ||
|
|
98e6ba9378 | ||
|
|
e288db29a8 | ||
|
|
98aeee9b1d | ||
|
|
45a2aa8495 | ||
|
|
4b350987a1 | ||
|
|
3b2b754fe5 | ||
|
|
64e7afea98 | ||
|
|
16765c19cf | ||
|
|
87d916fc24 | ||
|
|
21b59fab5d | ||
|
|
9272e1e556 | ||
|
|
0a51dabb17 | ||
|
|
8c1cee4e00 | ||
|
|
4d5315e2ca | ||
|
|
88cc9bb363 | ||
|
|
80e41ee14c | ||
|
|
23489f3f18 | ||
|
|
a998ddc9d4 | ||
|
|
833963c1c1 | ||
|
|
4b11f87f80 |
No files matched your search
+54
-4
@@ -1,9 +1,59 @@
|
||||
CHANGELOG
|
||||
=========
|
||||
|
||||
1.19.1
|
||||
----
|
||||
- mistakenly removed default whitelist files
|
||||
|
||||
1.19.0
|
||||
----
|
||||
- removed `--all-refs`. By default gitleaks now scans all branches, remote and local.
|
||||
- added commit memoizer to prevent duplicate commit audits
|
||||
- removed branch whitelist
|
||||
- removed branch from report as a commit is an object independent of branch
|
||||
- Better regexes for facebook, github, twitter (no more unbounded wildcards)
|
||||
|
||||
1.18.0
|
||||
----
|
||||
- fixing slack token
|
||||
- defaulting to single thread process
|
||||
- `--max-go=` --> `--threads=`
|
||||
- guarding `--threads=` > max threads available (you aint gettin any more performance)
|
||||
|
||||
1.17.0
|
||||
----
|
||||
- Default regex added to search: slack, telegram.
|
||||
- Default whitelisting: bin, doc, jpeg, gif
|
||||
|
||||
1.16.1
|
||||
----
|
||||
- Fixing default ssh auth logic
|
||||
|
||||
1.16.0
|
||||
----
|
||||
- Better commit coverage. Now iterates through each commit in git log and generates a patch with each commit's parent.
|
||||
- Removing the need for --private/-p option. Instead gitleaks will determine if the repo is private or not.
|
||||
|
||||
|
||||
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
|
||||
----
|
||||
- Github PR support
|
||||
- Github has its own go file. All other services, bitbucket, gitlab, etc should follow this convention
|
||||
|
||||
1.12.1
|
||||
----
|
||||
- Show program usage when no arguments are provided
|
||||
- Exit program after the -h or --help options are used
|
||||
|
||||
1.12.0
|
||||
----
|
||||
- removing --csv option
|
||||
@@ -56,14 +106,14 @@ CHANGELOG
|
||||
|
||||
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.
|
||||
- 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 the risk of running out of disk space.
|
||||
|
||||
|
||||
1.5.0
|
||||
-----
|
||||
- Support for CSV reporting
|
||||
- Refactoring github user/owner audits
|
||||
- Refactoring Github user/owner audits
|
||||
|
||||
1.4.0
|
||||
-----
|
||||
@@ -80,7 +130,7 @@ CHANGELOG
|
||||
|
||||
1.2.0
|
||||
-----
|
||||
- Added support for providing an alternate GitHub URL to support scanning GitHub Enteprise repositories
|
||||
- Added support for providing an alternate GitHub URL to support scanning GitHub Enterprise repositories
|
||||
|
||||
1.1.2
|
||||
-----
|
||||
|
||||
+3
-3
@@ -5,14 +5,14 @@ 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.
|
||||
Open a PR. Give the PR a descriptive title. Add some comments describing what is 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`.
|
||||
- You've run `go fmt`.
|
||||
- You've run `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).
|
||||
|
||||
@@ -6,20 +6,58 @@
|
||||
</p>
|
||||
|
||||
## 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">
|
||||
</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
|
||||
go get -u github.com/zricethezav/gitleaks
|
||||
```
|
||||
Or download from release binaries [here](https://github.com/zricethezav/gitleaks/releases)
|
||||
|
||||
|
||||
#### 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:
|
||||
gitleaks [OPTIONS]
|
||||
@@ -29,15 +67,13 @@ Application Options:
|
||||
--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)
|
||||
--github-pr= Github PR url to audit. This does not clone the repo. GITHUB_TOKEN must be set
|
||||
-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
|
||||
--threads= Maximum number of threads gitleaks spawns
|
||||
--disk Clones repo(s) to disk
|
||||
--all-refs run audit on all refs
|
||||
--single-search= single regular expression to search for
|
||||
--config= path to gitleaks config
|
||||
--ssh-key= path to ssh key
|
||||
@@ -53,18 +89,34 @@ Application Options:
|
||||
Help Options:
|
||||
-h, --help Show this help message
|
||||
```
|
||||
|
||||
#### Exit Codes
|
||||
Gitleaks provides consistent 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
|
||||
1: leaks present
|
||||
2: error encountered
|
||||
```
|
||||
|
||||
#### Additional Examples and Explanations
|
||||
Check the wiki [here](https://github.com/zricethezav/gitleaks/wiki)
|
||||
#### Additional information
|
||||
* 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 capability 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`
|
||||
@@ -0,0 +1,236 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/google/go-github/github"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"golang.org/x/oauth2"
|
||||
git "gopkg.in/src-d/go-git.v4"
|
||||
"gopkg.in/src-d/go-git.v4/storage/memory"
|
||||
)
|
||||
|
||||
var githubPages = 100
|
||||
|
||||
// auditPR audits a single github PR
|
||||
func auditGithubPR() ([]Leak, error) {
|
||||
var leaks []Leak
|
||||
ctx := context.Background()
|
||||
githubClient := github.NewClient(githubToken())
|
||||
splits := strings.Split(opts.GithubPR, "/")
|
||||
owner := splits[len(splits)-4]
|
||||
repo := splits[len(splits)-3]
|
||||
prNum, err := strconv.Atoi(splits[len(splits)-1])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
page := 1
|
||||
for {
|
||||
commits, resp, err := githubClient.PullRequests.ListCommits(ctx, owner, repo, prNum, &github.ListOptions{
|
||||
PerPage: githubPages,
|
||||
Page: page,
|
||||
})
|
||||
if err != nil {
|
||||
return leaks, err
|
||||
}
|
||||
|
||||
for _, commit := range commits {
|
||||
totalCommits = totalCommits + 1
|
||||
commit, _, err := githubClient.Repositories.GetCommit(ctx, owner, repo, *commit.SHA)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
files := commit.Files
|
||||
for _, f := range files {
|
||||
diff := gitDiff{
|
||||
sha: commit.GetSHA(),
|
||||
content: *f.Patch,
|
||||
filePath: *f.Filename,
|
||||
repoName: repo,
|
||||
githubCommit: commit,
|
||||
author: commit.GetCommitter().GetLogin(),
|
||||
message: *commit.Commit.Message,
|
||||
}
|
||||
leaks = append(leaks, inspect(diff)...)
|
||||
}
|
||||
}
|
||||
page = resp.NextPage
|
||||
if resp.LastPage == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return leaks, nil
|
||||
}
|
||||
|
||||
// auditGithubRepos kicks off audits if --github-user or --github-org options are set.
|
||||
// First, we gather all the github repositories from the github api (this doesnt actually clone the repo).
|
||||
// After all the repos have been pulled from github's api we proceed to audit the repos by calling auditGithubRepo.
|
||||
// If an error occurs during an audit of a repo, that error is logged but won't break the execution cycle.
|
||||
func auditGithubRepos() ([]Leak, error) {
|
||||
var (
|
||||
err error
|
||||
githubRepos []*github.Repository
|
||||
pagedGithubRepos []*github.Repository
|
||||
resp *github.Response
|
||||
githubOrgOptions *github.RepositoryListByOrgOptions
|
||||
githubOptions *github.RepositoryListOptions
|
||||
done bool
|
||||
leaks []Leak
|
||||
ownerDir string
|
||||
)
|
||||
ctx := context.Background()
|
||||
githubClient := github.NewClient(githubToken())
|
||||
|
||||
if opts.GithubOrg != "" {
|
||||
if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
|
||||
ghURL, _ := url.Parse(opts.GithubURL)
|
||||
githubClient.BaseURL = ghURL
|
||||
}
|
||||
githubOrgOptions = &github.RepositoryListByOrgOptions{
|
||||
ListOptions: github.ListOptions{PerPage: 100},
|
||||
}
|
||||
} else if opts.GithubUser != "" {
|
||||
if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
|
||||
ghURL, _ := url.Parse(opts.GithubURL)
|
||||
githubClient.BaseURL = ghURL
|
||||
}
|
||||
|
||||
githubOptions = &github.RepositoryListOptions{
|
||||
Affiliation: "owner",
|
||||
ListOptions: github.ListOptions{
|
||||
PerPage: 100,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
for {
|
||||
if done {
|
||||
break
|
||||
}
|
||||
if opts.GithubUser != "" {
|
||||
pagedGithubRepos, resp, err = githubClient.Repositories.List(ctx, opts.GithubUser, githubOptions)
|
||||
if err != nil {
|
||||
done = true
|
||||
}
|
||||
githubOptions.Page = resp.NextPage
|
||||
githubRepos = append(githubRepos, pagedGithubRepos...)
|
||||
if resp.NextPage == 0 {
|
||||
done = true
|
||||
}
|
||||
} else if opts.GithubOrg != "" {
|
||||
pagedGithubRepos, resp, err = githubClient.Repositories.ListByOrg(ctx, opts.GithubOrg, githubOrgOptions)
|
||||
if err != nil {
|
||||
done = true
|
||||
}
|
||||
githubOrgOptions.Page = resp.NextPage
|
||||
githubRepos = append(githubRepos, pagedGithubRepos...)
|
||||
if resp.NextPage == 0 {
|
||||
done = true
|
||||
}
|
||||
}
|
||||
if opts.Log == "Debug" || opts.Log == "debug" {
|
||||
for _, githubRepo := range pagedGithubRepos {
|
||||
log.Debugf("staging repos %s", *githubRepo.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
if opts.Disk {
|
||||
ownerDir, _ = ioutil.TempDir(dir, opts.GithubUser)
|
||||
}
|
||||
for _, githubRepo := range githubRepos {
|
||||
repo, err := cloneGithubRepo(githubRepo)
|
||||
if err != nil {
|
||||
log.Warn(err)
|
||||
continue
|
||||
}
|
||||
leaksFromRepo, err := auditGitRepo(repo)
|
||||
if opts.Disk {
|
||||
os.RemoveAll(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name))
|
||||
}
|
||||
if len(leaksFromRepo) == 0 {
|
||||
log.Infof("no leaks found for repo %s", *githubRepo.Name)
|
||||
} else {
|
||||
log.Warnf("leaks found for repo %s", *githubRepo.Name)
|
||||
}
|
||||
if err != nil {
|
||||
log.Warn(err)
|
||||
}
|
||||
leaks = append(leaks, leaksFromRepo...)
|
||||
}
|
||||
return leaks, nil
|
||||
}
|
||||
|
||||
// cloneGithubRepo clones a repo from the url parsed from a github repo. The repo
|
||||
// will be cloned to disk if --disk is set. If the repo is private, you must include the
|
||||
// --private/-p option. After the repo is clone, an audit will begin.
|
||||
func cloneGithubRepo(githubRepo *github.Repository) (*RepoDescriptor, error) {
|
||||
var (
|
||||
repo *git.Repository
|
||||
err error
|
||||
)
|
||||
if opts.ExcludeForks && githubRepo.GetFork() {
|
||||
return nil, fmt.Errorf("skipping %s, excluding forks", *githubRepo.Name)
|
||||
}
|
||||
for _, re := range whiteListRepos {
|
||||
if re.FindString(*githubRepo.Name) != "" {
|
||||
return nil, fmt.Errorf("skipping %s, whitelisted", *githubRepo.Name)
|
||||
}
|
||||
}
|
||||
log.Infof("cloning: %s", *githubRepo.Name)
|
||||
if opts.Disk {
|
||||
ownerDir, err := ioutil.TempDir(dir, opts.GithubUser)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unable to generater owner temp dir: %v", err)
|
||||
}
|
||||
if sshAuth != nil {
|
||||
repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
|
||||
URL: *githubRepo.SSHURL,
|
||||
Auth: sshAuth,
|
||||
})
|
||||
} else {
|
||||
repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
|
||||
URL: *githubRepo.CloneURL,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
if sshAuth != nil {
|
||||
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
|
||||
URL: *githubRepo.SSHURL,
|
||||
Auth: sshAuth,
|
||||
})
|
||||
} else {
|
||||
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
|
||||
URL: *githubRepo.CloneURL,
|
||||
})
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &RepoDescriptor{
|
||||
repository: repo,
|
||||
name: *githubRepo.Name,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// githubToken returns an oauth2 client for the github api to consume. This token is necessary
|
||||
// if you are running audits with --github-user or --github-org
|
||||
func githubToken() *http.Client {
|
||||
githubToken := os.Getenv("GITHUB_TOKEN")
|
||||
if githubToken == "" {
|
||||
return nil
|
||||
}
|
||||
ts := oauth2.StaticTokenSource(
|
||||
&oauth2.Token{AccessToken: githubToken},
|
||||
)
|
||||
return oauth2.NewClient(context.Background(), ts)
|
||||
}
|
||||
@@ -20,6 +20,15 @@ regex = '''(?i)facebook.*['\"][0-9a-f]{32}['\"]'''
|
||||
[[regexes]]
|
||||
description = "Twitter"
|
||||
regex = '''(?i)twitter.*['\"][0-9a-zA-Z]{35,44}['\"]'''
|
||||
[[regexes]]
|
||||
description = "Telegram"
|
||||
regex = '''(?i)telegram.*['\"][0-9]{1,12}+:[0-9a-zA-Z-]{32,44}['\"]'''
|
||||
[[regexes]]
|
||||
description = "PGP"
|
||||
regex = '''-----BEGIN PGP PRIVATE KEY BLOCK-----'''
|
||||
[[regexes]]
|
||||
description = "Slack token"
|
||||
regex = '''xox[baprs]-.*'''
|
||||
|
||||
[whitelist]
|
||||
regexes = [
|
||||
|
||||
+110
-277
@@ -8,6 +8,7 @@ import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/franela/goblin"
|
||||
git "gopkg.in/src-d/go-git.v4"
|
||||
@@ -34,16 +35,6 @@ files = [
|
||||
".go",
|
||||
]
|
||||
`
|
||||
const testWhitelistBranch = `
|
||||
[[regexes]]
|
||||
description = "AWS"
|
||||
regex = '''AKIA[0-9A-Z]{16}'''
|
||||
|
||||
[whitelist]
|
||||
branches = [
|
||||
"origin/master",
|
||||
]
|
||||
`
|
||||
|
||||
const testWhitelistRegex = `
|
||||
[[regexes]]
|
||||
@@ -67,34 +58,25 @@ repos = [
|
||||
]
|
||||
`
|
||||
|
||||
var benchmarkRepo *RepoDescriptor
|
||||
var benchmarkLeaksRepo *RepoDescriptor
|
||||
|
||||
func getBenchmarkLeaksRepo() *RepoDescriptor {
|
||||
if benchmarkLeaksRepo != nil {
|
||||
return benchmarkLeaksRepo
|
||||
}
|
||||
leaksR, _ := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
|
||||
URL: "https://github.com/gitleakstest/gronit.git",
|
||||
})
|
||||
benchmarkLeaksRepo = &RepoDescriptor{
|
||||
repository: leaksR,
|
||||
}
|
||||
return benchmarkLeaksRepo
|
||||
}
|
||||
|
||||
func getBenchmarkRepo() *RepoDescriptor {
|
||||
if benchmarkRepo != nil {
|
||||
return benchmarkRepo
|
||||
}
|
||||
bmRepo, _ := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
|
||||
URL: "https://github.com/apple/swift-package-manager.git",
|
||||
})
|
||||
benchmarkRepo = &RepoDescriptor{
|
||||
repository: bmRepo,
|
||||
}
|
||||
return benchmarkRepo
|
||||
}
|
||||
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",
|
||||
]
|
||||
`
|
||||
|
||||
func TestGetRepo(t *testing.T) {
|
||||
var err error
|
||||
@@ -147,17 +129,15 @@ func TestGetRepo(t *testing.T) {
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
Repo: "https://github.com/gitleakstest/private",
|
||||
IncludePrivate: true,
|
||||
Repo: "https://github.com/gitleakstest/private",
|
||||
},
|
||||
description: "test private repo",
|
||||
expectedErrMsg: "invalid auth method",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
Repo: "https://github.com/gitleakstest/private",
|
||||
IncludePrivate: true,
|
||||
Disk: true,
|
||||
Repo: "https://github.com/gitleakstest/private",
|
||||
Disk: true,
|
||||
},
|
||||
description: "test private repo",
|
||||
expectedErrMsg: "invalid auth method",
|
||||
@@ -198,6 +178,7 @@ func TestRun(t *testing.T) {
|
||||
whiteListRepos []string
|
||||
numLeaks int
|
||||
configPath string
|
||||
commitPerPage int
|
||||
}{
|
||||
{
|
||||
testOpts: Options{
|
||||
@@ -243,13 +224,12 @@ func TestRun(t *testing.T) {
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
GithubOrg: "gitleakstestorg",
|
||||
IncludePrivate: true,
|
||||
SSHKey: "reallyreallyreallyreallywrongpath",
|
||||
Repo: "git@github.com:gitleakstest/gronit.git",
|
||||
SSHKey: "trash",
|
||||
},
|
||||
description: "test private org no ssh",
|
||||
description: "test leak",
|
||||
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{
|
||||
@@ -293,6 +273,23 @@ func TestRun(t *testing.T) {
|
||||
numLeaks: 0,
|
||||
expectedErrMsg: "",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
GithubPR: "https://github.com/gitleakstest/gronit/pull/1",
|
||||
},
|
||||
description: "test github pr",
|
||||
numLeaks: 4,
|
||||
expectedErrMsg: "",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
GithubPR: "https://github.com/gitleakstest/gronit/pull/1",
|
||||
},
|
||||
description: "test github pr",
|
||||
numLeaks: 4,
|
||||
expectedErrMsg: "",
|
||||
commitPerPage: 1,
|
||||
},
|
||||
}
|
||||
g := goblin.Goblin(t)
|
||||
for _, test := range tests {
|
||||
@@ -301,12 +298,16 @@ func TestRun(t *testing.T) {
|
||||
if test.configPath != "" {
|
||||
os.Setenv("GITLEAKS_CONFIG", test.configPath)
|
||||
}
|
||||
if test.commitPerPage != 0 {
|
||||
githubPages = test.commitPerPage
|
||||
}
|
||||
opts = test.testOpts
|
||||
leaks, err := run()
|
||||
if err != nil {
|
||||
g.Assert(err.Error()).Equal(test.expectedErrMsg)
|
||||
}
|
||||
g.Assert(len(leaks)).Equal(test.numLeaks)
|
||||
githubPages = 100
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -328,7 +329,7 @@ func TestWriteReport(t *testing.T) {
|
||||
Message: "get",
|
||||
Author: "some",
|
||||
File: "sleep",
|
||||
Branch: "thxu",
|
||||
Date: time.Now(),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -401,10 +402,12 @@ func TestWriteReport(t *testing.T) {
|
||||
func testTomlLoader() string {
|
||||
tmpDir, _ := ioutil.TempDir("", "whiteListConfigs")
|
||||
ioutil.WriteFile(path.Join(tmpDir, "regex"), []byte(testWhitelistRegex), 0644)
|
||||
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)
|
||||
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
|
||||
}
|
||||
|
||||
@@ -440,17 +443,16 @@ func TestAuditRepo(t *testing.T) {
|
||||
}
|
||||
|
||||
var tests = []struct {
|
||||
testOpts Options
|
||||
description string
|
||||
expectedErrMsg string
|
||||
numLeaks int
|
||||
repo *RepoDescriptor
|
||||
whiteListFiles []*regexp.Regexp
|
||||
whiteListCommits map[string]bool
|
||||
whiteListBranches []string
|
||||
whiteListRepos []string
|
||||
whiteListRegexes []*regexp.Regexp
|
||||
configPath string
|
||||
testOpts Options
|
||||
description string
|
||||
expectedErrMsg string
|
||||
numLeaks int
|
||||
repo *RepoDescriptor
|
||||
whiteListFiles []*regexp.Regexp
|
||||
whiteListCommits map[string]bool
|
||||
whiteListRepos []*regexp.Regexp
|
||||
whiteListRegexes []*regexp.Regexp
|
||||
configPath string
|
||||
}{
|
||||
{
|
||||
repo: leaksRepo,
|
||||
@@ -462,42 +464,7 @@ func TestAuditRepo(t *testing.T) {
|
||||
description: "two leaks present limit goroutines",
|
||||
numLeaks: 2,
|
||||
testOpts: Options{
|
||||
MaxGoRoutines: 4,
|
||||
},
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "audit specific bad branch",
|
||||
numLeaks: 2,
|
||||
testOpts: Options{
|
||||
Branch: "master",
|
||||
},
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "audit specific good branch",
|
||||
numLeaks: 0,
|
||||
testOpts: Options{
|
||||
Branch: "dev",
|
||||
},
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "audit all branch",
|
||||
numLeaks: 6,
|
||||
testOpts: Options{
|
||||
AuditAllRefs: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "audit all branch whitelist 1",
|
||||
numLeaks: 4,
|
||||
testOpts: Options{
|
||||
AuditAllRefs: true,
|
||||
},
|
||||
whiteListBranches: []string{
|
||||
"origin/master",
|
||||
Threads: 4,
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -548,15 +515,6 @@ func TestAuditRepo(t *testing.T) {
|
||||
configPath: path.Join(configsDir, "regex"),
|
||||
numLeaks: 0,
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "toml whitelist branch",
|
||||
configPath: path.Join(configsDir, "branch"),
|
||||
testOpts: Options{
|
||||
AuditAllRefs: true,
|
||||
},
|
||||
numLeaks: 4,
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "toml whitelist file",
|
||||
@@ -573,8 +531,8 @@ func TestAuditRepo(t *testing.T) {
|
||||
repo: leaksRepo,
|
||||
description: "audit whitelist repo",
|
||||
numLeaks: 0,
|
||||
whiteListRepos: []string{
|
||||
"gronit",
|
||||
whiteListRepos: []*regexp.Regexp{
|
||||
regexp.MustCompile("gronit"),
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -589,34 +547,53 @@ func TestAuditRepo(t *testing.T) {
|
||||
testOpts: Options{
|
||||
Entropy: 4.7,
|
||||
},
|
||||
numLeaks: 7,
|
||||
numLeaks: 6,
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "Audit until specific commit",
|
||||
numLeaks: 1,
|
||||
numLeaks: 2,
|
||||
testOpts: Options{
|
||||
Commit: "f6839959b7bbdcd23008f1fb16f797f35bcd3a0c",
|
||||
},
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "commit depth = 1, no leaks",
|
||||
numLeaks: 0,
|
||||
description: "commit depth = 1, one leak",
|
||||
numLeaks: 1,
|
||||
testOpts: Options{
|
||||
Depth: 1,
|
||||
},
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "commit depth = 2, one leak",
|
||||
numLeaks: 1,
|
||||
description: "commit depth = 2, two leaks",
|
||||
numLeaks: 2,
|
||||
testOpts: Options{
|
||||
Depth: 2,
|
||||
},
|
||||
},
|
||||
{
|
||||
repo: leaksRepo,
|
||||
description: "toml entropy range",
|
||||
numLeaks: 284,
|
||||
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)
|
||||
g := goblin.Goblin(t)
|
||||
for _, test := range tests {
|
||||
@@ -634,11 +611,6 @@ func TestAuditRepo(t *testing.T) {
|
||||
} else {
|
||||
whiteListCommits = nil
|
||||
}
|
||||
if test.whiteListBranches != nil {
|
||||
whiteListBranches = test.whiteListBranches
|
||||
} else {
|
||||
whiteListBranches = nil
|
||||
}
|
||||
if test.whiteListRegexes != nil {
|
||||
whiteListRegexes = test.whiteListRegexes
|
||||
} else {
|
||||
@@ -649,19 +621,24 @@ func TestAuditRepo(t *testing.T) {
|
||||
} else {
|
||||
whiteListRepos = nil
|
||||
}
|
||||
|
||||
skip := false
|
||||
// config paths
|
||||
if 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)
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -682,45 +659,24 @@ func TestOptionGuard(t *testing.T) {
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
IncludePrivate: true,
|
||||
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",
|
||||
GithubUser: "fakeUser",
|
||||
GithubOrg: "fakeOrg",
|
||||
},
|
||||
description: "double owner",
|
||||
expectedErrMsg: "github user and organization set",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
IncludePrivate: true,
|
||||
GithubOrg: "fakeOrg",
|
||||
OwnerPath: "/dev/null",
|
||||
GithubOrg: "fakeOrg",
|
||||
OwnerPath: "/dev/null",
|
||||
},
|
||||
description: "local and remote target",
|
||||
expectedErrMsg: "github organization set and local owner path",
|
||||
},
|
||||
{
|
||||
testOpts: Options{
|
||||
IncludePrivate: true,
|
||||
GithubUser: "fakeUser",
|
||||
OwnerPath: "/dev/null",
|
||||
GithubUser: "fakeUser",
|
||||
OwnerPath: "/dev/null",
|
||||
},
|
||||
description: "local and remote target",
|
||||
expectedErrMsg: "github user set and local owner path",
|
||||
@@ -850,126 +806,3 @@ func TestLoadToml(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAuditRepo1Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 1
|
||||
benchmarkRepo = getBenchmarkRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAuditRepo2Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 2
|
||||
benchmarkRepo = getBenchmarkRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAuditRepo4Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 4
|
||||
benchmarkRepo = getBenchmarkRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAuditRepo8Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 8
|
||||
benchmarkRepo = getBenchmarkRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAuditRepo10Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 10
|
||||
benchmarkRepo = getBenchmarkRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAuditRepo100Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 100
|
||||
benchmarkRepo = getBenchmarkRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAuditRepo1000Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 1000
|
||||
benchmarkRepo = getBenchmarkRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
func BenchmarkAuditLeakRepo1Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 1
|
||||
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAuditLeakRepo2Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 2
|
||||
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAuditLeakRepo4Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 4
|
||||
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAuditLeakRepo8Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 8
|
||||
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAuditLeakRepo10Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 10
|
||||
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
func BenchmarkAuditLeakRepo100Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 100
|
||||
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
func BenchmarkAuditLeakRepo1000Proc(b *testing.B) {
|
||||
loadToml()
|
||||
opts.MaxGoRoutines = 1000
|
||||
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
|
||||
for n := 0; n < b.N; n++ {
|
||||
auditGitRepo(benchmarkRepo)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"encoding/csv"
|
||||
"encoding/json"
|
||||
@@ -10,7 +9,6 @@ import (
|
||||
"io/ioutil"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/user"
|
||||
@@ -18,13 +16,13 @@ import (
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gopkg.in/src-d/go-git.v4/plumbing"
|
||||
|
||||
"golang.org/x/oauth2"
|
||||
"gopkg.in/src-d/go-git.v4/plumbing/object"
|
||||
"gopkg.in/src-d/go-git.v4/plumbing/transport/ssh"
|
||||
"gopkg.in/src-d/go-git.v4/storage/memory"
|
||||
@@ -39,15 +37,15 @@ import (
|
||||
|
||||
// Leak represents a leaked secret or regex match.
|
||||
type Leak struct {
|
||||
Line string `json:"line"`
|
||||
Commit string `json:"commit"`
|
||||
Offender string `json:"offender"`
|
||||
Type string `json:"reason"`
|
||||
Message string `json:"commitMsg"`
|
||||
Author string `json:"author"`
|
||||
File string `json:"file"`
|
||||
Branch string `json:"branch"`
|
||||
Repo string `json:"repo"`
|
||||
Line string `json:"line"`
|
||||
Commit string `json:"commit"`
|
||||
Offender string `json:"offender"`
|
||||
Type string `json:"reason"`
|
||||
Message string `json:"commitMsg"`
|
||||
Author string `json:"author"`
|
||||
File string `json:"file"`
|
||||
Repo string `json:"repo"`
|
||||
Date time.Time `json:"date"`
|
||||
}
|
||||
|
||||
// RepoDescriptor contains a src-d git repository and other data about the repo
|
||||
@@ -62,11 +60,11 @@ type RepoDescriptor struct {
|
||||
// Options for gitleaks
|
||||
type Options struct {
|
||||
// remote target options
|
||||
Repo string `short:"r" long:"repo" description:"Repo url to audit"`
|
||||
GithubUser string `long:"github-user" description:"Github user 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/"`
|
||||
IncludePrivate bool `short:"p" long:"private" description:"Include private repos in audit"`
|
||||
Repo string `short:"r" long:"repo" description:"Repo url to audit"`
|
||||
GithubUser string `long:"github-user" description:"Github user 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/"`
|
||||
GithubPR string `long:"github-pr" description:"Github PR url to audit. This does not clone the repo. GITHUB_TOKEN must be set"`
|
||||
|
||||
/*
|
||||
TODO:
|
||||
@@ -74,7 +72,6 @@ type Options struct {
|
||||
GitLabOrg string `long:"gitlab-org" description:"Organization url to audit"`
|
||||
*/
|
||||
|
||||
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"`
|
||||
|
||||
@@ -83,14 +80,13 @@ type Options struct {
|
||||
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"`
|
||||
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)"`
|
||||
Threads int `long:"threads" description:"Maximum number of threads gitleaks spawns"`
|
||||
Disk bool `long:"disk" description:"Clones repo(s) to disk"`
|
||||
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
|
||||
@@ -109,24 +105,35 @@ type Config struct {
|
||||
Regex string
|
||||
}
|
||||
Whitelist struct {
|
||||
Files []string
|
||||
Regexes []string
|
||||
Commits []string
|
||||
Branches []string
|
||||
Repos []string
|
||||
Files []string
|
||||
Regexes []string
|
||||
Commits []string
|
||||
Repos []string
|
||||
}
|
||||
Misc struct {
|
||||
Entropy []string
|
||||
}
|
||||
}
|
||||
|
||||
type gitDiff struct {
|
||||
content string
|
||||
commit *object.Commit
|
||||
filePath string
|
||||
branchName string
|
||||
repoName string
|
||||
content string
|
||||
commit *object.Commit
|
||||
filePath string
|
||||
repoName string
|
||||
githubCommit *github.RepositoryCommit
|
||||
sha string
|
||||
message string
|
||||
author string
|
||||
date time.Time
|
||||
}
|
||||
|
||||
type entropyRange struct {
|
||||
v1 float64
|
||||
v2 float64
|
||||
}
|
||||
|
||||
const defaultGithubURL = "https://api.github.com/"
|
||||
const version = "1.12.1"
|
||||
const version = "1.19.1"
|
||||
const errExit = 2
|
||||
const leakExit = 1
|
||||
const defaultConfig = `
|
||||
@@ -135,51 +142,51 @@ const defaultConfig = `
|
||||
# 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]]
|
||||
description = "AWS"
|
||||
regex = '''AKIA[0-9A-Z]{16}'''
|
||||
[[regexes]]
|
||||
description = "RKCS8"
|
||||
description = "PKCS8"
|
||||
regex = '''-----BEGIN PRIVATE KEY-----'''
|
||||
[[regexes]]
|
||||
description = "RSA"
|
||||
regex = '''-----BEGIN RSA PRIVATE KEY-----'''
|
||||
[[regexes]]
|
||||
description = "Github"
|
||||
regex = '''(?i)github.*['\"][0-9a-zA-Z]{35,40}['\"]'''
|
||||
[[regexes]]
|
||||
description = "SSH"
|
||||
regex = '''-----BEGIN OPENSSH PRIVATE KEY-----'''
|
||||
[[regexes]]
|
||||
description = "PGP"
|
||||
regex = '''-----BEGIN PGP PRIVATE KEY BLOCK-----'''
|
||||
[[regexes]]
|
||||
description = "Facebook"
|
||||
regex = '''(?i)facebook.*['\"][0-9a-f]{32}['\"]'''
|
||||
regex = '''(?i)facebook(.{0,4})?['\"][0-9a-f]{32}['\"]'''
|
||||
[[regexes]]
|
||||
description = "Twitter"
|
||||
regex = '''(?i)twitter.*['\"][0-9a-zA-Z]{35,44}['\"]'''
|
||||
regex = '''(?i)twitter(.{0,4})?['\"][0-9a-zA-Z]{35,44}['\"]'''
|
||||
[[regexes]]
|
||||
description = "Github"
|
||||
regex = '''(?i)github(.{0,4})?['\"][0-9a-zA-Z]{35,40}['\"]'''
|
||||
[[regexes]]
|
||||
description = "Slack"
|
||||
regex = '''xox[baprs]-([0-9a-zA-Z]{10,48})?'''
|
||||
|
||||
[whitelist]
|
||||
#regexes = [
|
||||
# "AKAIMYFAKEAWKKEY",
|
||||
#]
|
||||
|
||||
#files = [
|
||||
# "(.*?)(jpg|gif|doc|pdf|bin)$"
|
||||
#]
|
||||
|
||||
files = [
|
||||
"(.*?)(jpg|gif|doc|pdf|bin)$"
|
||||
]
|
||||
#commits = [
|
||||
# "BADHA5H1",
|
||||
# "BADHA5H2",
|
||||
#]
|
||||
|
||||
#branches = [
|
||||
# "dev/STUPDIFKNFEATURE"
|
||||
#]
|
||||
|
||||
#repos = [
|
||||
# "someYugeRepoWeKnowIsCLEAR"
|
||||
# "mygoodrepo"
|
||||
#]
|
||||
[misc]
|
||||
#entropy = [
|
||||
# "3.3-4.30"
|
||||
# "6.0-8.0
|
||||
#]
|
||||
`
|
||||
|
||||
@@ -190,18 +197,21 @@ var (
|
||||
whiteListRegexes []*regexp.Regexp
|
||||
whiteListFiles []*regexp.Regexp
|
||||
whiteListCommits map[string]bool
|
||||
whiteListBranches []string
|
||||
whiteListRepos []string
|
||||
whiteListRepos []*regexp.Regexp
|
||||
entropyRanges []entropyRange
|
||||
fileDiffRegex *regexp.Regexp
|
||||
sshAuth *ssh.PublicKeys
|
||||
dir string
|
||||
maxGo int
|
||||
threads int
|
||||
totalCommits int64
|
||||
commitMap = make(map[string]bool)
|
||||
cMutex = &sync.Mutex{}
|
||||
)
|
||||
|
||||
func init() {
|
||||
log.SetOutput(os.Stdout)
|
||||
maxGo = runtime.GOMAXPROCS(0) / 2
|
||||
// threads = runtime.GOMAXPROCS(0) / 2
|
||||
threads = 1
|
||||
regexes = make(map[string]*regexp.Regexp)
|
||||
whiteListCommits = make(map[string]bool)
|
||||
}
|
||||
@@ -232,17 +242,21 @@ func main() {
|
||||
now := time.Now()
|
||||
leaks, err := run()
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "whitelisted") {
|
||||
log.Info(err.Error())
|
||||
os.Exit(0)
|
||||
}
|
||||
log.Error(err)
|
||||
os.Exit(errExit)
|
||||
}
|
||||
if opts.Report != "" {
|
||||
writeReport(leaks)
|
||||
}
|
||||
|
||||
log.Infof("%d commits inspected in %s", totalCommits, durafmt.Parse(time.Now().Sub(now)).String())
|
||||
if len(leaks) != 0 {
|
||||
log.Warnf("%d leaks detected", len(leaks))
|
||||
log.Warnf("%d leaks detected. %d commits inspected in %s", len(leaks), totalCommits, durafmt.Parse(time.Now().Sub(now)).String())
|
||||
os.Exit(leakExit)
|
||||
} else {
|
||||
log.Infof("%d leaks detected. %d commits inspected in %s", len(leaks), totalCommits, durafmt.Parse(time.Now().Sub(now)).String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -258,13 +272,11 @@ func run() ([]Leak, error) {
|
||||
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
|
||||
}
|
||||
sshAuth, err = getSSHAuth()
|
||||
if err != nil {
|
||||
return leaks, err
|
||||
}
|
||||
|
||||
if opts.Disk {
|
||||
// temporary directory where all the gitleaks plain clones will reside
|
||||
dir, err = ioutil.TempDir("", "gitleaks")
|
||||
@@ -297,12 +309,13 @@ func run() ([]Leak, error) {
|
||||
leaks = append(leaksFromRepo, leaks...)
|
||||
}
|
||||
} else if opts.GithubOrg != "" || opts.GithubUser != "" {
|
||||
// Audit a github owner -- a user or organization. If you want to include
|
||||
// private repos you must pass a --private/-p option and have your ssh keys set
|
||||
// Audit a github owner -- a user or organization.
|
||||
leaks, err = auditGithubRepos()
|
||||
if err != nil {
|
||||
return leaks, err
|
||||
}
|
||||
} else if opts.GithubPR != "" {
|
||||
return auditGithubPR()
|
||||
}
|
||||
return leaks, nil
|
||||
}
|
||||
@@ -319,9 +332,9 @@ func writeReport(leaks []Leak) error {
|
||||
}
|
||||
defer f.Close()
|
||||
w := csv.NewWriter(f)
|
||||
w.Write([]string{"repo", "line", "commit", "offender", "reason", "commitMsg", "author", "file", "branch"})
|
||||
w.Write([]string{"repo", "line", "commit", "offender", "reason", "commitMsg", "author", "file", "date"})
|
||||
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.Write([]string{leak.Repo, leak.Line, leak.Commit, leak.Offender, leak.Type, leak.Message, leak.Author, leak.File, leak.Date.Format(time.RFC3339)})
|
||||
}
|
||||
w.Flush()
|
||||
} else {
|
||||
@@ -331,18 +344,22 @@ func writeReport(leaks []Leak) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// cloneRepo clones a repo to memory(default) or to disk if the --disk option is set. If you want to
|
||||
// clone a private repo you must set the --private/-p option, use a ssh target, and have your ssh keys
|
||||
// configured. If you want to audit a local repo, getRepo will load up a repo located at --repo-path
|
||||
// cloneRepo clones a repo to memory(default) or to disk if the --disk option is set.
|
||||
func cloneRepo() (*RepoDescriptor, error) {
|
||||
var (
|
||||
err error
|
||||
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 {
|
||||
log.Infof("cloning %s", 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{
|
||||
URL: opts.Repo,
|
||||
Progress: os.Stdout,
|
||||
@@ -355,11 +372,11 @@ func cloneRepo() (*RepoDescriptor, error) {
|
||||
})
|
||||
}
|
||||
} else if opts.RepoPath != "" {
|
||||
log.Infof("opening %s", opts.Repo)
|
||||
log.Infof("opening %s", opts.RepoPath)
|
||||
repo, err = git.PlainOpen(opts.RepoPath)
|
||||
} else {
|
||||
log.Infof("cloning %s", opts.Repo)
|
||||
if opts.IncludePrivate {
|
||||
if strings.HasPrefix(opts.Repo, "git") {
|
||||
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
|
||||
URL: opts.Repo,
|
||||
Progress: os.Stdout,
|
||||
@@ -381,161 +398,105 @@ func cloneRepo() (*RepoDescriptor, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
// auditGitRepo beings an audit on a git repository by checking the default HEAD branch, all branches, or
|
||||
// a single branch depending on what gitleaks is configured to do. Note when I say branch I really
|
||||
// mean reference as these branches are read only.
|
||||
// auditGitRepo beings an audit on a git repository
|
||||
func auditGitRepo(repo *RepoDescriptor) ([]Leak, error) {
|
||||
var (
|
||||
err error
|
||||
leaks []Leak
|
||||
)
|
||||
for _, repoName := range whiteListRepos {
|
||||
if repoName == repo.name {
|
||||
return nil, fmt.Errorf("skipping %s, whitelisted", repoName)
|
||||
for _, re := range whiteListRepos {
|
||||
if re.FindString(repo.name) != "" {
|
||||
return leaks, fmt.Errorf("skipping %s, whitelisted", repo.name)
|
||||
}
|
||||
}
|
||||
ref, err := repo.repository.Head()
|
||||
|
||||
// clear commit cache
|
||||
commitMap = make(map[string]bool)
|
||||
|
||||
refs, err := repo.repository.Storer.IterReferences()
|
||||
if err != nil {
|
||||
return leaks, err
|
||||
}
|
||||
|
||||
if opts.AuditAllRefs {
|
||||
skipBranch := false
|
||||
refs, err := repo.repository.Storer.IterReferences()
|
||||
if err != nil {
|
||||
return leaks, err
|
||||
}
|
||||
err = refs.ForEach(func(ref *plumbing.Reference) error {
|
||||
for _, b := range whiteListBranches {
|
||||
if strings.HasSuffix(string(ref.Name()), b) {
|
||||
skipBranch = true
|
||||
}
|
||||
}
|
||||
if skipBranch {
|
||||
skipBranch = false
|
||||
return nil
|
||||
}
|
||||
branchLeaks := auditGitReference(repo, ref)
|
||||
for _, leak := range branchLeaks {
|
||||
leaks = append(leaks, leak)
|
||||
}
|
||||
err = refs.ForEach(func(ref *plumbing.Reference) error {
|
||||
if ref.Name().IsTag() {
|
||||
return nil
|
||||
})
|
||||
} else {
|
||||
if opts.Branch != "" {
|
||||
foundBranch := false
|
||||
refs, _ := repo.repository.Storer.IterReferences()
|
||||
branch := strings.Split(opts.Branch, "/")[len(strings.Split(opts.Branch, "/"))-1]
|
||||
err = refs.ForEach(func(refBranch *plumbing.Reference) error {
|
||||
if strings.Split(refBranch.Name().String(), "/")[len(strings.Split(refBranch.Name().String(), "/"))-1] == branch {
|
||||
foundBranch = true
|
||||
ref = refBranch
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if foundBranch == false {
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
leaks = auditGitReference(repo, ref)
|
||||
}
|
||||
branchLeaks := auditGitReference(repo, ref)
|
||||
for _, leak := range branchLeaks {
|
||||
leaks = append(leaks, leak)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return leaks, err
|
||||
}
|
||||
|
||||
// auditGitReference beings the audit for a git reference. This function will
|
||||
// traverse the git reference and audit each line of each diff. Set maximum concurrency with
|
||||
// the --max-go option (default is set to the number of cores on your cpu).
|
||||
// traverse the git reference and audit each line of each diff.
|
||||
func auditGitReference(repo *RepoDescriptor, ref *plumbing.Reference) []Leak {
|
||||
var (
|
||||
err error
|
||||
prevCommit *object.Commit
|
||||
semaphore chan bool
|
||||
repoName string
|
||||
leaks []Leak
|
||||
commitCount int
|
||||
commitWg sync.WaitGroup
|
||||
mutex = &sync.Mutex{}
|
||||
commitCount int
|
||||
semaphore chan bool
|
||||
)
|
||||
repoName = repo.name
|
||||
if opts.MaxGoRoutines != 0 {
|
||||
maxGo = opts.MaxGoRoutines
|
||||
if opts.Threads != 0 {
|
||||
threads = opts.Threads
|
||||
}
|
||||
if opts.RepoPath != "" {
|
||||
threads = 1
|
||||
}
|
||||
semaphore = make(chan bool, threads)
|
||||
|
||||
semaphore = make(chan bool, maxGo)
|
||||
cIter, err := repo.repository.Log(&git.LogOptions{From: ref.Hash()})
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
err = cIter.ForEach(func(c *object.Commit) error {
|
||||
if c.Hash.String() == opts.Commit || (opts.Depth != 0 && commitCount == opts.Depth) {
|
||||
if commitMap[c.Hash.String()] {
|
||||
return nil
|
||||
}
|
||||
cMutex.Lock()
|
||||
commitMap[c.Hash.String()] = true
|
||||
cMutex.Unlock()
|
||||
if c == nil || 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
|
||||
}
|
||||
if prevCommit != nil {
|
||||
if whiteListCommits[prevCommit.Hash.String()] {
|
||||
prevCommit = c
|
||||
log.Infof("skipping commit: %s\n", c.Hash.String())
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
commitWg.Add(1)
|
||||
semaphore <- true
|
||||
go func(c *object.Commit, prevCommit *object.Commit) {
|
||||
var (
|
||||
filePath string
|
||||
skipFile bool
|
||||
)
|
||||
defer func() {
|
||||
commitWg.Done()
|
||||
<-semaphore
|
||||
if r := recover(); r != nil {
|
||||
log.Warnf("recoverying from panic on commit %s, likely large diff causing panic", c.Hash.String())
|
||||
}
|
||||
}()
|
||||
diff := gitDiff{
|
||||
commit: prevCommit,
|
||||
branchName: string(ref.Name()),
|
||||
repoName: repoName,
|
||||
}
|
||||
|
||||
if prevCommit == nil {
|
||||
t, _ := c.Tree()
|
||||
files := t.Files()
|
||||
err := files.ForEach(func(file *object.File) error {
|
||||
content, err := file.Contents()
|
||||
if err != nil {
|
||||
return err
|
||||
err = c.Parents().ForEach(func(parent *object.Commit) error {
|
||||
commitWg.Add(1)
|
||||
semaphore <- true
|
||||
go func(c *object.Commit, parent *object.Commit) {
|
||||
var (
|
||||
filePath string
|
||||
skipFile bool
|
||||
)
|
||||
defer func() {
|
||||
commitWg.Done()
|
||||
<-semaphore
|
||||
if r := recover(); r != nil {
|
||||
log.Warnf("recoverying from panic on commit %s, likely large diff causing panic", c.Hash.String())
|
||||
}
|
||||
diff.filePath = file.Name
|
||||
diff.content = content
|
||||
diff.commit = c
|
||||
chunkLeaks := inspect(diff)
|
||||
for _, leak := range chunkLeaks {
|
||||
mutex.Lock()
|
||||
leaks = append(leaks, leak)
|
||||
mutex.Unlock()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
log.Warnf("problem generating diff for commit: %s\n", c.Hash.String())
|
||||
return
|
||||
}
|
||||
} else {
|
||||
patch, err := c.Patch(prevCommit)
|
||||
}()
|
||||
patch, err := c.Patch(parent)
|
||||
if err != nil {
|
||||
log.Warnf("problem generating patch for commit: %s\n", c.Hash.String())
|
||||
return
|
||||
}
|
||||
for _, f := range patch.FilePatches() {
|
||||
if f.IsBinary() {
|
||||
continue
|
||||
}
|
||||
skipFile = false
|
||||
from, to := f.Files()
|
||||
filePath = "???"
|
||||
@@ -544,7 +505,6 @@ func auditGitReference(repo *RepoDescriptor, ref *plumbing.Reference) []Leak {
|
||||
} else if to != nil {
|
||||
filePath = to.Path()
|
||||
}
|
||||
diff.filePath = filePath
|
||||
for _, re := range whiteListFiles {
|
||||
if re.FindString(filePath) != "" {
|
||||
skipFile = true
|
||||
@@ -557,7 +517,15 @@ func auditGitReference(repo *RepoDescriptor, ref *plumbing.Reference) []Leak {
|
||||
chunks := f.Chunks()
|
||||
for _, chunk := range chunks {
|
||||
if chunk.Type() == 1 || chunk.Type() == 2 {
|
||||
diff.content = chunk.Content()
|
||||
diff := gitDiff{
|
||||
repoName: repoName,
|
||||
filePath: filePath,
|
||||
content: chunk.Content(),
|
||||
sha: c.Hash.String(),
|
||||
author: c.Author.String(),
|
||||
message: c.Message,
|
||||
date: c.Author.When,
|
||||
}
|
||||
chunkLeaks := inspect(diff)
|
||||
for _, leak := range chunkLeaks {
|
||||
mutex.Lock()
|
||||
@@ -567,9 +535,9 @@ func auditGitReference(repo *RepoDescriptor, ref *plumbing.Reference) []Leak {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}(c, prevCommit)
|
||||
prevCommit = c
|
||||
}(c, parent)
|
||||
return nil
|
||||
})
|
||||
return nil
|
||||
})
|
||||
commitWg.Wait()
|
||||
@@ -610,11 +578,24 @@ func inspect(diff gitDiff) []Leak {
|
||||
leaks = addLeak(leaks, line, match, leakType, diff)
|
||||
}
|
||||
|
||||
if opts.Entropy > 0 {
|
||||
if opts.Entropy > 0 || len(entropyRanges) != 0 {
|
||||
entropyLeak := false
|
||||
words := strings.Fields(line)
|
||||
for _, word := range words {
|
||||
if getShannonEntropy(word) >= opts.Entropy {
|
||||
leaks = addLeak(leaks, line, word, "High Entropy", diff)
|
||||
entropy := getShannonEntropy(word)
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -622,6 +603,32 @@ func inspect(diff gitDiff) []Leak {
|
||||
return leaks
|
||||
}
|
||||
|
||||
// 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.sha,
|
||||
Offender: offender,
|
||||
Type: leakType,
|
||||
Author: diff.author,
|
||||
File: diff.filePath,
|
||||
Repo: diff.repoName,
|
||||
Message: diff.message,
|
||||
Date: diff.date,
|
||||
}
|
||||
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 == "" {
|
||||
@@ -642,213 +649,6 @@ func getShannonEntropy(data string) (entropy float64) {
|
||||
return entropy
|
||||
}
|
||||
|
||||
// addLeak is helper for func inspect() to append leaks if found during a diff check.
|
||||
func addLeak(leaks []Leak, line string, offender string, leakType string, diff gitDiff) []Leak {
|
||||
leak := Leak{
|
||||
Line: line,
|
||||
Commit: diff.commit.Hash.String(),
|
||||
Offender: offender,
|
||||
Type: leakType,
|
||||
Message: diff.commit.Message,
|
||||
Author: diff.commit.Author.String(),
|
||||
File: diff.filePath,
|
||||
Branch: diff.branchName,
|
||||
Repo: diff.repoName,
|
||||
}
|
||||
|
||||
if opts.Redact {
|
||||
leak.Offender = "REDACTED"
|
||||
leak.Line = "REDACTED"
|
||||
}
|
||||
|
||||
if opts.Verbose {
|
||||
leak.log()
|
||||
}
|
||||
|
||||
leaks = append(leaks, leak)
|
||||
return leaks
|
||||
}
|
||||
|
||||
// auditGithubRepos kicks off audits if --github-user or --github-org options are set.
|
||||
// First, we gather all the github repositories from the github api (this doesnt actually clone the repo).
|
||||
// After all the repos have been pulled from github's api we proceed to audit the repos by calling auditGithubRepo.
|
||||
// If an error occurs during an audit of a repo, that error is logged but won't break the execution cycle.
|
||||
func auditGithubRepos() ([]Leak, error) {
|
||||
var (
|
||||
err error
|
||||
githubRepos []*github.Repository
|
||||
pagedGithubRepos []*github.Repository
|
||||
resp *github.Response
|
||||
githubClient *github.Client
|
||||
githubOrgOptions *github.RepositoryListByOrgOptions
|
||||
githubOptions *github.RepositoryListOptions
|
||||
done bool
|
||||
leaks []Leak
|
||||
ownerDir string
|
||||
)
|
||||
ctx := context.Background()
|
||||
|
||||
if opts.GithubOrg != "" {
|
||||
githubClient = github.NewClient(githubToken())
|
||||
if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
|
||||
ghURL, _ := url.Parse(opts.GithubURL)
|
||||
githubClient.BaseURL = ghURL
|
||||
}
|
||||
githubOrgOptions = &github.RepositoryListByOrgOptions{
|
||||
ListOptions: github.ListOptions{PerPage: 100},
|
||||
}
|
||||
} else if opts.GithubUser != "" {
|
||||
githubClient = github.NewClient(githubToken())
|
||||
if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
|
||||
ghURL, _ := url.Parse(opts.GithubURL)
|
||||
githubClient.BaseURL = ghURL
|
||||
}
|
||||
|
||||
githubOptions = &github.RepositoryListOptions{
|
||||
Affiliation: "owner",
|
||||
ListOptions: github.ListOptions{
|
||||
PerPage: 100,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
for {
|
||||
if done {
|
||||
break
|
||||
}
|
||||
if opts.GithubUser != "" {
|
||||
if opts.IncludePrivate {
|
||||
pagedGithubRepos, resp, err = githubClient.Repositories.List(ctx, "", githubOptions)
|
||||
} else {
|
||||
pagedGithubRepos, resp, err = githubClient.Repositories.List(ctx, opts.GithubUser, githubOptions)
|
||||
}
|
||||
if err != nil {
|
||||
done = true
|
||||
}
|
||||
githubOptions.Page = resp.NextPage
|
||||
githubRepos = append(githubRepos, pagedGithubRepos...)
|
||||
if resp.NextPage == 0 {
|
||||
done = true
|
||||
}
|
||||
} else if opts.GithubOrg != "" {
|
||||
pagedGithubRepos, resp, err = githubClient.Repositories.ListByOrg(ctx, opts.GithubOrg, githubOrgOptions)
|
||||
if err != nil {
|
||||
done = true
|
||||
}
|
||||
githubOrgOptions.Page = resp.NextPage
|
||||
githubRepos = append(githubRepos, pagedGithubRepos...)
|
||||
if resp.NextPage == 0 {
|
||||
done = true
|
||||
}
|
||||
}
|
||||
if opts.Log == "Debug" || opts.Log == "debug" {
|
||||
for _, githubRepo := range pagedGithubRepos {
|
||||
log.Debugf("staging repos %s", *githubRepo.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if opts.Disk {
|
||||
ownerDir, err = ioutil.TempDir(dir, opts.GithubUser)
|
||||
os.RemoveAll(ownerDir)
|
||||
}
|
||||
for _, githubRepo := range githubRepos {
|
||||
repo, err := cloneGithubRepo(githubRepo)
|
||||
if err != nil {
|
||||
log.Warn(err)
|
||||
continue
|
||||
}
|
||||
leaksFromRepo, err := auditGitRepo(repo)
|
||||
if opts.Disk {
|
||||
os.RemoveAll(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name))
|
||||
}
|
||||
if len(leaksFromRepo) == 0 {
|
||||
log.Infof("no leaks found for repo %s", *githubRepo.Name)
|
||||
} else {
|
||||
log.Warnf("leaks found for repo %s", *githubRepo.Name)
|
||||
}
|
||||
if err != nil {
|
||||
log.Warn(err)
|
||||
}
|
||||
leaks = append(leaks, leaksFromRepo...)
|
||||
}
|
||||
return leaks, nil
|
||||
}
|
||||
|
||||
// cloneGithubRepo clones a repo from the url parsed from a github repo. The repo
|
||||
// will be cloned to disk if --disk is set. If the repo is private, you must include the
|
||||
// --private/-p option. After the repo is clone, an audit will begin.
|
||||
func cloneGithubRepo(githubRepo *github.Repository) (*RepoDescriptor, error) {
|
||||
var (
|
||||
repo *git.Repository
|
||||
err error
|
||||
)
|
||||
if opts.ExcludeForks && githubRepo.GetFork() {
|
||||
return nil, fmt.Errorf("skipping %s, excluding forks", *githubRepo.Name)
|
||||
}
|
||||
for _, repoName := range whiteListRepos {
|
||||
if repoName == *githubRepo.Name {
|
||||
return nil, fmt.Errorf("skipping %s, whitelisted", repoName)
|
||||
}
|
||||
}
|
||||
log.Infof("cloning: %s", *githubRepo.Name)
|
||||
if opts.Disk {
|
||||
ownerDir, err := ioutil.TempDir(dir, opts.GithubUser)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unable to generater owner temp dir: %v", err)
|
||||
}
|
||||
if opts.IncludePrivate {
|
||||
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{
|
||||
URL: *githubRepo.SSHURL,
|
||||
Auth: sshAuth,
|
||||
})
|
||||
} else {
|
||||
repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
|
||||
URL: *githubRepo.CloneURL,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
if opts.IncludePrivate {
|
||||
if sshAuth == nil {
|
||||
return nil, fmt.Errorf("no ssh auth available")
|
||||
}
|
||||
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
|
||||
URL: *githubRepo.SSHURL,
|
||||
Auth: sshAuth,
|
||||
})
|
||||
} else {
|
||||
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
|
||||
URL: *githubRepo.CloneURL,
|
||||
})
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &RepoDescriptor{
|
||||
repository: repo,
|
||||
name: *githubRepo.Name,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// githubToken returns an oauth2 client for the github api to consume. This token is necessary
|
||||
// if you are running audits with --github-user or --github-org
|
||||
func githubToken() *http.Client {
|
||||
githubToken := os.Getenv("GITHUB_TOKEN")
|
||||
if githubToken == "" {
|
||||
return nil
|
||||
}
|
||||
ts := oauth2.StaticTokenSource(
|
||||
&oauth2.Token{AccessToken: githubToken},
|
||||
)
|
||||
return oauth2.NewClient(context.Background(), ts)
|
||||
}
|
||||
|
||||
// discoverRepos walks all the children of `path`. If a child directory
|
||||
// contain a .git file then that repo will be added to the list of repos returned
|
||||
func discoverRepos(ownerPath string) ([]*RepoDescriptor, error) {
|
||||
@@ -903,8 +703,10 @@ func optsGuard() error {
|
||||
return fmt.Errorf("github organization set and local owner path")
|
||||
} else if opts.GithubUser != "" && opts.OwnerPath != "" {
|
||||
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")
|
||||
}
|
||||
|
||||
if opts.Threads > runtime.GOMAXPROCS(0) {
|
||||
return fmt.Errorf("%d available threads", runtime.GOMAXPROCS(0))
|
||||
}
|
||||
|
||||
// do the URL Parse and error checking here, so we can skip it later
|
||||
@@ -982,6 +784,13 @@ func loadToml() error {
|
||||
}
|
||||
}
|
||||
|
||||
if len(config.Misc.Entropy) != 0 {
|
||||
err := entropyLimits(config.Misc.Entropy)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if singleSearchRegex != nil {
|
||||
regexes["singleSearch"] = singleSearchRegex
|
||||
} else {
|
||||
@@ -989,8 +798,6 @@ func loadToml() error {
|
||||
regexes[regex.Description] = regexp.MustCompile(regex.Regex)
|
||||
}
|
||||
}
|
||||
whiteListBranches = config.Whitelist.Branches
|
||||
whiteListRepos = config.Whitelist.Repos
|
||||
whiteListCommits = make(map[string]bool)
|
||||
for _, commit := range config.Whitelist.Commits {
|
||||
whiteListCommits[commit] = true
|
||||
@@ -1001,10 +808,40 @@ func loadToml() error {
|
||||
for _, regex := range config.Whitelist.Regexes {
|
||||
whiteListRegexes = append(whiteListRegexes, regexp.MustCompile(regex))
|
||||
}
|
||||
for _, regex := range config.Whitelist.Repos {
|
||||
whiteListRepos = append(whiteListRepos, regexp.MustCompile(regex))
|
||||
}
|
||||
|
||||
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.
|
||||
// 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
|
||||
@@ -1015,14 +852,22 @@ func getSSHAuth() (*ssh.PublicKeys, error) {
|
||||
if opts.SSHKey != "" {
|
||||
sshKeyPath = opts.SSHKey
|
||||
} else {
|
||||
c, _ := user.Current()
|
||||
// try grabbing default
|
||||
c, err := user.Current()
|
||||
if err != nil {
|
||||
return nil, nil
|
||||
}
|
||||
sshKeyPath = fmt.Sprintf("%s/.ssh/id_rsa", c.HomeDir)
|
||||
}
|
||||
sshAuth, err := ssh.NewPublicKeysFromFile("git", sshKeyPath, "")
|
||||
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() {
|
||||
|
||||
Reference in new issue
Block a user