Compare commits

..
21 Commits
Author SHA1 Message Date
zach rice 98b025da72 bumping versions 2018-12-10 09:48:48 -06:00
Zachary Rice af7717412f Merge pull request #159 from camaya/reduce-entropy-noise
Reduce noise when running entropy checks
2018-12-10 09:40:05 -06:00
Cristhian Amaya 68c2a18f6f Update entropy noise reduction
Instead of reducing noise by default, there's a new flag called
`--noise-reduction` to enable that.
2018-12-10 16:24:53 +01:00
Cristhian Amaya ea49078ffd Reduce noise when running entropy checks
When there's a word on a line with high entropy, we check if the line
matches any of the regex configured on the `lineregexes` element of the
`entropy` section. If so, it's marked as a leaked.

This has reduced the number of leaks found with entropy enabled up to
80%
2018-12-04 10:23:42 +01:00
Zachary Rice b902d7310a Merge pull request #158 from camaya/redact-only-secret-on-line
Change redacted behaviour on the line information
2018-11-30 08:55:22 -06:00
Zachary Rice 3591560b34 Merge pull request #157 from camaya/add-commit-date-prs
Add commit date to Github PRs checks
2018-11-30 08:54:56 -06:00
Cristhian Amaya 949029ca89 Change redacted behaviour on the line information
The line information sometimes contains useful context information so
instead of redacting the whole line, this change redacts only the
secret
2018-11-30 14:13:18 +01:00
Cristhian Amaya cde0894711 Add commit date to Github PRs checks 2018-11-30 13:37:18 +01:00
Zachary Rice 342e9f80db Merge pull request #152 from camaya/fix-github-pr-nilcheck
Fix Github PR checks error
2018-11-29 09:10:36 -06:00
Zachary Rice 96b0f4aab7 Merge pull request #153 from madblobfish/patch-1
Fix releases link in readme
2018-11-26 12:03:40 -06:00
madblobfish 3af6a546ac fix releases link in readme 2018-11-26 11:20:17 +01:00
Cristhian Amaya 6e086c4297 Fix Github PR checks error
When a commit contained a file without patch information like an added
empty file, there was a nil pointer dereference.
2018-11-23 11:56:49 +01:00
zricethezav db08fc0564 actually bump version in code >.< 2018-11-18 08:43:05 -06:00
zricethezav dbb6d4cc5f including camayas changes in version bump 2018-11-18 08:42:32 -06:00
Zachary Rice d0f44da4c2 Merge pull request #151 from AdamKobi/add_support_for_tokens
Add support for tokens
2018-11-18 08:39:17 -06:00
Zachary Rice cb6b01cc5d Merge pull request #149 from camaya/fix-files-whitelist-github-prs
Fix files whitelisting when checking Github PRs
2018-11-18 08:36:47 -06:00
Adam Kobi 392d79b9e2 added changes to changelog 2018-11-15 19:04:51 +02:00
Adam Kobi f8e609d4bf added case for when using oauth token for both listing and cloning repos 2018-11-15 17:58:54 +02:00
Zachary Rice 573bf46fd1 grammar not my best subject 2018-11-13 20:01:44 -06:00
Zachary Rice d65592bbcc Update to readme 2018-11-13 19:57:52 -06:00
Cristhian Amaya 169a137e7f Fix files whitelisting when checking Github PRs
Files whitelisting code was not executed when running the tool against a
Github PR so the config was ignored.

To avoid duplication, the whitelist files check has been moved to the `inspect`
function which is always executed.
2018-11-13 11:54:25 +01:00
5 changed files with 189 additions and 67 deletions

No files matched your search

+10
View File
@@ -1,6 +1,16 @@
CHANGELOG
=========
1.22.0
----
- context inclusion for redactions
- noise reduction for entropy signals
1.21.0
----
- added support for cloning repositories using github api
- auditing PRs now allows for whitelisting files
1.20.0
----
- adding gitlab user and group support
+35 -30
View File
@@ -33,7 +33,7 @@ It has been sucessfully used in a number of different scenarios, including;
</p>
#### 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;
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/releases). Alternatively, executed via Docker or it can be installed using Go directly, as per the below;
##### Docker
@@ -63,30 +63,31 @@ Usage:
gitleaks [OPTIONS]
Application Options:
-r, --repo= Repo url to audit
--github-user= Github user to audit
--github-org= Github organization to audit
--github-url= GitHub API Base URL, use for GitHub Enterprise. Example: https://github.example.com/api/v3/ (default: https://api.github.com/)
--github-pr= Github PR url to audit. This does not clone the repo. GITHUB_TOKEN must be set
--gitlab-user= GitLab user ID to audit
--gitlab-org= GitLab group ID to audit
-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)
--threads= Maximum number of threads gitleaks spawns
--disk Clones repo(s) to disk
--single-search= single regular expression to search for
--config= path to gitleaks config
--ssh-key= path to ssh key
--exclude-forks exclude forks for organization/user audits
-e, --entropy= Include entropy checks during audit. Entropy scale: 0.0(no entropy) - 8.0(max entropy)
-l, --log= log level
-v, --verbose Show verbose output from gitleaks audit
--report= path to write report file
--redact redact secrets from log messages and report
--version version number
--sample-config prints a sample config file
-r, --repo= Repo url to audit
--github-user= Github user to audit
--github-org= Github organization to audit
--github-url= GitHub API Base URL, use for GitHub Enterprise. Example: https://github.example.com/api/v3/ (default: https://api.github.com/)
--github-pr= Github PR url to audit. This does not clone the repo. GITHUB_TOKEN must be set
--gitlab-user= GitLab user ID to audit
--gitlab-org= GitLab group ID to audit
-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)
--threads= Maximum number of threads gitleaks spawns
--disk Clones repo(s) to disk
--single-search= single regular expression to search for
--config= path to gitleaks config
--ssh-key= path to ssh key
--exclude-forks exclude forks for organization/user audits
-e, --entropy= Include entropy checks during audit. Entropy scale: 0.0(no entropy) - 8.0(max entropy)
--noise-reduction Reduce the number of finds when entropy checks are enabled
-l, --log= log level
-v, --verbose Show verbose output from gitleaks audit
--report= path to write report file
--redact redact secrets from log messages and report
--version version number
--sample-config prints a sample config file
Help Options:
-h, --help Show this help message
@@ -105,11 +106,7 @@ The code return codes are:
2: error encountered
```
### GitLab
To audit public repositories for user on GitLab use `--gitlab-user=` and for group `--gitlab-org=`. For private repositories add `GITLAB_TOKEN` environment variable with your personal access token (is used to list all repositories via API) and set `--ssh-key=` to SSH key path (is used to clone repository).
If self hosted GitLab server add `GITLAB_URL` environment variable with your URL.
#### Additional information
### 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/)
@@ -122,6 +119,14 @@ If self hosted GitLab server add `GITLAB_URL` environment variable with your URL
* 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.
### Give Thanks
If using gitleaks has made you job easier consider donating to an organization, C-U at Home, that does vital work for those who most need it in the community of Champaign-Urbana, IL (my home).
From C-U at Home:
```C-U at Home is a grassroots, 501 c (3), faith-based homelessness ministry with facilities located in the Champaign-Urbana area. Due to our not-for-profit status, all gifts made to C-U at Home (both monetary and in-kind) are tax deductible. Our ministry is funded 100% by the community and we have made it a priority not to accept any state or federal funds. We feel that through community dollars, we can stay true to our mission. While our mission statement reads, “C-U at Home engages and mobilizes our community to house and support the most vulnerable homeless on their journey of healing and restoration,” our connection with those we serve goes much deeper.```
<b>Donate</b>: https://www.cuathome.us/give/
+25 -2
View File
@@ -14,6 +14,7 @@ import (
log "github.com/sirupsen/logrus"
"golang.org/x/oauth2"
git "gopkg.in/src-d/go-git.v4"
gitHttp "gopkg.in/src-d/go-git.v4/plumbing/transport/http"
"gopkg.in/src-d/go-git.v4/storage/memory"
)
@@ -50,6 +51,10 @@ func auditGithubPR() ([]Leak, error) {
}
files := commit.Files
for _, f := range files {
if f.Patch == nil || f.Filename == nil {
continue
}
diff := gitDiff{
sha: commit.GetSHA(),
content: *f.Patch,
@@ -58,6 +63,7 @@ func auditGithubPR() ([]Leak, error) {
githubCommit: commit,
author: commit.GetCommitter().GetLogin(),
message: *commit.Commit.Message,
date: *commit.Commit.Committer.Date,
}
leaks = append(leaks, inspect(diff)...)
}
@@ -177,6 +183,7 @@ func cloneGithubRepo(githubRepo *github.Repository) (*RepoDescriptor, error) {
repo *git.Repository
err error
)
githubToken := os.Getenv("GITHUB_TOKEN")
if opts.ExcludeForks && githubRepo.GetFork() {
return nil, fmt.Errorf("skipping %s, excluding forks", *githubRepo.Name)
}
@@ -191,22 +198,38 @@ func cloneGithubRepo(githubRepo *github.Repository) (*RepoDescriptor, error) {
if err != nil {
return nil, fmt.Errorf("unable to generater owner temp dir: %v", err)
}
if sshAuth != nil {
if sshAuth != nil && githubToken == "" {
repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
URL: *githubRepo.SSHURL,
Auth: sshAuth,
})
} else if githubToken != "" {
repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
URL: *githubRepo.CloneURL,
Auth: &gitHttp.BasicAuth{
Username: "fakeUsername", // yes, this can be anything except an empty string
Password: githubToken,
},
})
} else {
repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
URL: *githubRepo.CloneURL,
})
}
} else {
if sshAuth != nil {
if sshAuth != nil && githubToken == "" {
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: *githubRepo.SSHURL,
Auth: sshAuth,
})
} else if githubToken != "" {
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: *githubRepo.CloneURL,
Auth: &gitHttp.BasicAuth{
Username: "fakeUsername", // yes, this can be anything except an empty string
Password: githubToken,
},
})
} else {
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: *githubRepo.CloneURL,
+45
View File
@@ -176,6 +176,7 @@ func TestRun(t *testing.T) {
description string
expectedErrMsg string
whiteListRepos []string
whiteListFiles []*regexp.Regexp
numLeaks int
configPath string
commitPerPage int
@@ -298,6 +299,27 @@ func TestRun(t *testing.T) {
expectedErrMsg: "",
commitPerPage: 1,
},
{
testOpts: Options{
GithubPR: "https://github.com/gitleakstest/gronit/pull/1",
},
description: "test github pr with whitelisted files",
numLeaks: 0,
expectedErrMsg: "",
commitPerPage: 1,
whiteListFiles: []*regexp.Regexp{
regexp.MustCompile("main.go"),
},
},
{
testOpts: Options{
GithubPR: "https://github.com/gitleakstest/gronit/pull/2",
},
description: "test github pr with commits without patch info",
numLeaks: 0,
expectedErrMsg: "",
commitPerPage: 1,
},
}
g := goblin.Goblin(t)
for _, test := range tests {
@@ -309,6 +331,11 @@ func TestRun(t *testing.T) {
if test.commitPerPage != 0 {
githubPages = test.commitPerPage
}
if test.whiteListFiles != nil {
whiteListFiles = test.whiteListFiles
} else {
whiteListFiles = nil
}
opts = test.testOpts
leaks, err := run()
if err != nil {
@@ -565,6 +592,15 @@ func TestAuditRepo(t *testing.T) {
},
numLeaks: 6,
},
{
repo: leaksRepo,
description: "leaks present with entropy",
testOpts: Options{
Entropy: 4.7,
NoiseReduction: true,
},
numLeaks: 2,
},
{
repo: leaksRepo,
description: "Audit until specific commit",
@@ -587,6 +623,15 @@ func TestAuditRepo(t *testing.T) {
numLeaks: 298,
configPath: path.Join(configsDir, "entropy"),
},
{
repo: leaksRepo,
testOpts: Options{
NoiseReduction: true,
},
description: "toml entropy range",
numLeaks: 58,
configPath: path.Join(configsDir, "entropy"),
},
{
repo: leaksRepo,
description: "toml bad entropy range",
+74 -35
View File
@@ -77,13 +77,14 @@ type Options struct {
OwnerPath string `long:"owner-path" description:"Path to owner directory (repos discovered)"`
// Process options
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)"`
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)"`
NoiseReduction bool `long:"noise-reduction" description:"Reduce the number of finds when entropy checks are enabled"`
// TODO: IncludeMessages string `long:"messages" description:"include commit messages in audit"`
// Output options
@@ -101,6 +102,9 @@ type Config struct {
Description string
Regex string
}
Entropy struct {
LineRegexes []string
}
Whitelist struct {
Files []string
Regexes []string
@@ -130,7 +134,7 @@ type entropyRange struct {
}
const defaultGithubURL = "https://api.github.com/"
const version = "1.20.0"
const version = "1.22.0"
const errExit = 2
const leakExit = 1
const defaultConfig = `
@@ -169,9 +173,24 @@ regex = '''(?i)github(.{0,4})?['\"][0-9a-zA-Z]{35,40}['\"]'''
description = "Slack"
regex = '''xox[baprs]-([0-9a-zA-Z]{10,48})?'''
[entropy]
lineregexes = [
"api",
"key",
"signature",
"secret",
"password",
"pass",
"pwd",
"token",
"curl",
"wget",
"https?",
]
[whitelist]
files = [
"(.*?)(jpg|gif|doc|pdf|bin)$"
"(.*?)(jpg|gif|doc|pdf|bin)$"
]
#commits = [
# "BADHA5H1",
@@ -196,6 +215,7 @@ var (
whiteListCommits map[string]bool
whiteListRepos []*regexp.Regexp
entropyRanges []entropyRange
entropyRegexes []*regexp.Regexp
fileDiffRegex *regexp.Regexp
sshAuth *ssh.PublicKeys
dir string
@@ -488,11 +508,6 @@ func auditGitReference(repo *RepoDescriptor, ref *plumbing.Reference) []Leak {
if bin || err != nil {
return nil
}
for _, re := range whiteListFiles {
if re.FindString(f.Name) != "" {
return nil
}
}
content, err := f.Contents()
if err != nil {
return nil
@@ -560,12 +575,6 @@ func auditGitReference(repo *RepoDescriptor, ref *plumbing.Reference) []Leak {
} else if to != nil {
filePath = to.Path()
}
for _, re := range whiteListFiles {
if re.FindString(filePath) != "" {
skipFile = true
break
}
}
if skipFile {
continue
}
@@ -604,12 +613,19 @@ func auditGitReference(repo *RepoDescriptor, ref *plumbing.Reference) []Leak {
// will skip lines that include a whitelisted regex. A list of leaks is returned.
// If verbose mode (-v/--verbose) is set, then checkDiff will log leaks as they are discovered.
func inspect(diff gitDiff) []Leak {
lines := strings.Split(diff.content, "\n")
var (
leaks []Leak
skipLine bool
)
for _, re := range whiteListFiles {
if re.FindString(diff.filePath) != "" {
return leaks
}
}
lines := strings.Split(diff.content, "\n")
for _, line := range lines {
skipLine = false
for leakType, re := range regexes {
@@ -634,23 +650,12 @@ func inspect(diff gitDiff) []Leak {
}
if opts.Entropy > 0 || len(entropyRanges) != 0 {
entropyLeak := false
words := strings.Fields(line)
for _, word := range words {
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 {
if entropyIsHighEnough(entropy) && highEntropyLineIsALeak(line) {
leaks = addLeak(leaks, line, word, fmt.Sprintf("Entropy: %.2f", entropy), diff)
entropyLeak = false
}
}
}
@@ -673,7 +678,7 @@ func addLeak(leaks []Leak, line string, offender string, leakType string, diff g
}
if opts.Redact {
leak.Offender = "REDACTED"
leak.Line = "REDACTED"
leak.Line = strings.Replace(line, offender, "REDACTED", -1)
}
if opts.Verbose {
@@ -704,6 +709,36 @@ func getShannonEntropy(data string) (entropy float64) {
return entropy
}
func entropyIsHighEnough(entropy float64) bool {
if entropy >= opts.Entropy && len(entropyRanges) == 0 {
return true
}
if len(entropyRanges) != 0 {
for _, eR := range entropyRanges {
if entropy > eR.v1 && entropy < eR.v2 {
return true
}
}
}
return false
}
func highEntropyLineIsALeak(line string) bool {
if !opts.NoiseReduction {
return true
}
for _, re := range entropyRegexes {
if re.FindString(line) != "" {
return true
}
}
return false
}
// 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) {
@@ -846,6 +881,10 @@ func loadToml() error {
}
}
for _, regex := range config.Entropy.LineRegexes {
entropyRegexes = append(entropyRegexes, regexp.MustCompile(regex))
}
if singleSearchRegex != nil {
regexes["singleSearch"] = singleSearchRegex
} else {