Compare commits

..
40 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
zach rice 88cc9bb363 committing to master nbd.... stupid version 2018-10-20 17:28:42 -05:00
Zachary Rice 80e41ee14c Merge pull request #118 from zricethezav/feature/github-pr
Feature/GitHub pr
2018-10-20 18:27:27 -04:00
zach rice 23489f3f18 updating changelog, readme, some other things 2018-10-20 17:16:35 -05:00
zach rice a998ddc9d4 adding github.go, pagination working 2018-10-20 16:31:52 -05:00
zach rice 833963c1c1 refactoring 2018-10-19 19:53:10 -05:00
zach rice 4b11f87f80 poc seems to work fine w token auth 2018-10-19 15:58:25 -04:00
Zachary Rice 923dcf0311 Merge pull request #117 from camaya/update-help-option
Update help option
2018-10-17 08:42:20 -04:00
Cristhian Amaya 8896cf66cd Update help option
* Show program usage when no arguments are provided
* Exit program after the -h or --help options are used
2018-10-15 17:10:44 +02:00
zach rice df133ccaf8 version boss strikes AGAIN 2018-10-12 19:01:42 -05:00
Zachary Rice 23cd693d71 Merge pull request #114 from zricethezav/report
report filetype enforcement, time to audit
2018-10-12 18:53:38 -05:00
zach rice 524d81fde9 durafmt 2018-10-12 18:43:03 -05:00
zach rice d387f528c4 update lint 2018-10-12 18:22:33 -05:00
zach rice dcda26578b report filetype enforcement, time to audit 2018-10-12 17:01:24 -05:00
Zachary Rice 28639d3a49 Merge pull request #112 from zricethezav/wl-commit
look at prev commit too
2018-10-10 12:19:21 -05:00
zach rice 19e23c9cbe look at prev commit too 2018-10-10 12:16:31 -05:00
Zachary Rice 160015b872 Merge pull request #111 from zricethezav/fix-wl-commit
rm commit count log
2018-10-10 09:50:28 -05:00
zach rice abdf2c47f0 cl update 2018-10-10 09:43:01 -05:00
zach rice 8536f16ceb rm commit count log 2018-10-10 09:41:49 -05:00
Zachary Rice 6862c13bf7 Merge pull request #109 from zricethezav/depth
Depth
2018-10-09 21:13:29 -05:00
zach rice 9939c638ec better log 2018-10-09 21:07:49 -05:00
zach rice ed3a512b4b commit depth option 2018-10-09 21:01:56 -05:00
Zachary Rice 7c988c927d Merge pull request #107 from camaya/feature/add-entropy-checks
Add option to check string entropy
2018-10-09 18:46:21 -05:00
zach rice bde9af44ea merging, adding comments, updating flag description 2018-10-09 18:42:09 -05:00
Zachary Rice eee4d05642 Merge pull request #108 from camaya/fix-commit-option
Fix commit option
2018-10-09 16:18:54 -05:00
Cristhian Amaya 9144594d77 Fix commit option
The --commit option was being ignored becase the Close() function doesn't stop
the iterator.
According to the documentation:
https://godoc.org/gopkg.in/src-d/go-git.v4/plumbing/object#FileIter.ForEach
an ErrStop error should be send to stop it.
2018-10-09 16:49:16 +02:00
Cristhian Amaya 1cb15242fd Add option to check string entropy
Strings with high entropy have a good probability of being a secret.
2018-10-08 16:08:04 +02:00
14 changed files with 1168 additions and 417 deletions

No files matched your search

+38
View File
@@ -1,6 +1,44 @@
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
----
- 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
- --report option now requires .json or .csv in filename
- adding total time to audit in logs
1.11.1
----
- fix commit whitelist logic
1.11.0
-----
- Commit depth option
- Commit stats output
1.10.0
-----
- Add entropy option
1.9.0 1.9.0
----- -----
- exclude fork option - exclude fork option
Generated
+7 -1
View File
@@ -44,6 +44,12 @@
revision = "44c6ddd0a2342c386950e880b658017258da92fc" revision = "44c6ddd0a2342c386950e880b658017258da92fc"
version = "v1.0.0" version = "v1.0.0"
[[projects]]
name = "github.com/hako/durafmt"
packages = ["."]
revision = "7b7ae1e72eade09dbc9c2cfba3e6c4bae7b8bcac"
version = "1.0.0"
[[projects]] [[projects]]
branch = "master" branch = "master"
name = "github.com/jbenet/go-context" name = "github.com/jbenet/go-context"
@@ -249,6 +255,6 @@
[solve-meta] [solve-meta]
analyzer-name = "dep" analyzer-name = "dep"
analyzer-version = 1 analyzer-version = 1
inputs-digest = "8185a08afcb3ad854f58b49061fb70c57e7b64244abb43a08714d55cac7a97f9" inputs-digest = "ad1b6855b3c8b3e1303f29123160cde693d39d6724682ce1cd246cd1a2343c7c"
solver-name = "gps-cdcl" solver-name = "gps-cdcl"
solver-version = 1 solver-version = 1
+1 -1
View File
@@ -1,7 +1,7 @@
.PHONY: test build-all deploy .PHONY: test build-all deploy
test: test:
go get github.com/golang/lint/golint go get golang.org/x/lint/golint
go fmt go fmt
golint golint
go test --race --cover -run=Test$ go test --race --cover -run=Test$
+71 -15
View File
@@ -6,32 +6,71 @@
</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]
Application Options: Application Options:
-r, --repo= Repo url to audit -r, --repo= Repo url to audit
--github-user= User url to audit --github-user= Github user to audit
--github-org= Organization url 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/)
-p, --private Include private repos in audit --github-pr= Github PR url to audit. This does not clone the repo. GITHUB_TOKEN must be set
-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
--repo-path= Path to repo --repo-path= Path to repo
--owner-path= Path to owner directory (repos discovered) --owner-path= Path to owner directory (repos discovered)
--max-go= Maximum number of concurrent go-routines gitleaks spawns --max-go= Maximum number of concurrent go-routines gitleaks spawns
@@ -40,10 +79,11 @@ Application Options:
--single-search= single regular expression to search for --single-search= single regular expression to search for
--config= path to gitleaks config --config= path to gitleaks config
--ssh-key= path to ssh key --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 -l, --log= log level
-v, --verbose Show verbose output from gitleaks audit -v, --verbose Show verbose output from gitleaks audit
--report= path to write report file --report= path to write report file
--csv report output to csv
--redact redact secrets from log messages and report --redact redact secrets from log messages and report
--version version number --version version number
--sample-config prints a sample config file --sample-config prints a sample config file
@@ -51,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`
+240
View File
@@ -0,0 +1,240 @@
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 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 _, 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)
}
+173 -99
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",
@@ -198,6 +216,7 @@ func TestRun(t *testing.T) {
whiteListRepos []string whiteListRepos []string
numLeaks int numLeaks int
configPath string configPath string
commitPerPage int
}{ }{
{ {
testOpts: Options{ testOpts: Options{
@@ -243,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{
@@ -293,6 +311,23 @@ func TestRun(t *testing.T) {
numLeaks: 0, numLeaks: 0,
expectedErrMsg: "", 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) g := goblin.Goblin(t)
for _, test := range tests { for _, test := range tests {
@@ -301,12 +336,16 @@ func TestRun(t *testing.T) {
if test.configPath != "" { if test.configPath != "" {
os.Setenv("GITLEAKS_CONFIG", test.configPath) os.Setenv("GITLEAKS_CONFIG", test.configPath)
} }
if test.commitPerPage != 0 {
githubPages = test.commitPerPage
}
opts = test.testOpts opts = test.testOpts
leaks, err := run() leaks, err := run()
if err != nil { if err != nil {
g.Assert(err.Error()).Equal(test.expectedErrMsg) g.Assert(err.Error()).Equal(test.expectedErrMsg)
} }
g.Assert(len(leaks)).Equal(test.numLeaks) g.Assert(len(leaks)).Equal(test.numLeaks)
githubPages = 100
}) })
}) })
} }
@@ -315,6 +354,8 @@ func TestRun(t *testing.T) {
func TestWriteReport(t *testing.T) { func TestWriteReport(t *testing.T) {
tmpDir, _ := ioutil.TempDir("", "reportDir") tmpDir, _ := ioutil.TempDir("", "reportDir")
reportJSON := path.Join(tmpDir, "report.json") reportJSON := path.Join(tmpDir, "report.json")
reportJASON := path.Join(tmpDir, "report.jason")
reportVOID := path.Join("thereIsNoWay", "thisReportWillGetWritten.json")
reportCSV := path.Join(tmpDir, "report.csv") reportCSV := path.Join(tmpDir, "report.csv")
defer os.RemoveAll(tmpDir) defer os.RemoveAll(tmpDir)
leaks := []Leak{ leaks := []Leak{
@@ -331,17 +372,18 @@ func TestWriteReport(t *testing.T) {
} }
var tests = []struct { var tests = []struct {
leaks []Leak leaks []Leak
reportFile string reportFile string
fileName string fileName string
description string description string
testOpts Options testOpts Options
expectedErrMsg string
}{ }{
{ {
leaks: leaks, leaks: leaks,
reportFile: reportJSON, reportFile: reportJSON,
fileName: "report.json", fileName: "report.json",
description: "can we write a file", description: "can we write a json file",
testOpts: Options{ testOpts: Options{
Report: reportJSON, Report: reportJSON,
}, },
@@ -350,10 +392,29 @@ func TestWriteReport(t *testing.T) {
leaks: leaks, leaks: leaks,
reportFile: reportCSV, reportFile: reportCSV,
fileName: "report.csv", fileName: "report.csv",
description: "can we write a file", description: "can we write a csv file",
testOpts: Options{ testOpts: Options{
Report: reportCSV, Report: reportCSV,
CSV: true, },
},
{
leaks: leaks,
reportFile: reportJASON,
fileName: "report.jason",
description: "bad file",
expectedErrMsg: "Report should be a .json or .csv file",
testOpts: Options{
Report: reportJASON,
},
},
{
leaks: leaks,
reportFile: reportVOID,
fileName: "report.jason",
description: "bad dir",
expectedErrMsg: "thereIsNoWay does not exist",
testOpts: Options{
Report: reportVOID,
}, },
}, },
} }
@@ -362,9 +423,14 @@ func TestWriteReport(t *testing.T) {
g.Describe("TestWriteReport", func() { g.Describe("TestWriteReport", func() {
g.It(test.description, func() { g.It(test.description, func() {
opts = test.testOpts opts = test.testOpts
writeReport(test.leaks) err := optsGuard()
f, _ := os.Stat(test.reportFile) if err != nil {
g.Assert(f.Name()).Equal(test.fileName) g.Assert(err.Error()).Equal(test.expectedErrMsg)
} else {
writeReport(test.leaks)
f, _ := os.Stat(test.reportFile)
g.Assert(f.Name()).Equal(test.fileName)
}
}) })
}) })
} }
@@ -378,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
} }
@@ -421,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
}{ }{
@@ -500,14 +569,12 @@ func TestAuditRepo(t *testing.T) {
numLeaks: 0, numLeaks: 0,
}, },
{ {
// note this double counts the first commit since we are whitelisting
// a "bad" first commit
repo: leaksRepo, repo: leaksRepo,
description: "two leaks present whitelist bad commit", description: "two leaks present whitelist bad commit",
whiteListCommits: map[string]bool{ whiteListCommits: map[string]bool{
"eaeffdc65b4c73ccb67e75d96bd8743be2c85973": true, "eaeffdc65b4c73ccb67e75d96bd8743be2c85973": true,
}, },
numLeaks: 2, numLeaks: 1,
}, },
{ {
repo: leaksRepo, repo: leaksRepo,
@@ -539,19 +606,17 @@ func TestAuditRepo(t *testing.T) {
numLeaks: 0, numLeaks: 0,
}, },
{ {
// note this double counts the first commit since we are whitelisting
// a "bad" first commit
repo: leaksRepo, repo: leaksRepo,
description: "toml whitelist commit", description: "toml whitelist commit",
configPath: path.Join(configsDir, "commit"), configPath: path.Join(configsDir, "commit"),
numLeaks: 2, numLeaks: 1,
}, },
{ {
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"),
}, },
}, },
{ {
@@ -560,8 +625,59 @@ func TestAuditRepo(t *testing.T) {
numLeaks: 0, numLeaks: 0,
configPath: path.Join(configsDir, "repo"), configPath: path.Join(configsDir, "repo"),
}, },
{
repo: leaksRepo,
description: "leaks present with entropy",
testOpts: Options{
Entropy: 4.7,
},
numLeaks: 6,
},
{
repo: leaksRepo,
description: "Audit until specific commit",
numLeaks: 2,
testOpts: Options{
Commit: "f6839959b7bbdcd23008f1fb16f797f35bcd3a0c",
},
},
{
repo: leaksRepo,
description: "commit depth = 1, one leak",
numLeaks: 1,
testOpts: Options{
Depth: 1,
},
},
{
repo: leaksRepo,
description: "commit depth = 2, two leaks",
numLeaks: 2,
testOpts: Options{
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 {
@@ -594,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)
}) })
}) })
} }
@@ -627,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",
@@ -686,6 +786,14 @@ func TestOptionGuard(t *testing.T) {
description: "single search regex gaurd", description: "single search regex gaurd",
expectedErrMsg: "", expectedErrMsg: "",
}, },
{
testOpts: Options{
GithubOrg: "fakeOrg",
Entropy: 9,
},
description: "Invalid entropy level guard",
expectedErrMsg: "The maximum level of entropy is 8",
},
} }
g := goblin.Goblin(t) g := goblin.Goblin(t)
for _, test := range tests { for _, test := range tests {
@@ -850,22 +958,6 @@ func BenchmarkAuditRepo1000Proc(b *testing.B) {
auditGitRepo(benchmarkRepo) auditGitRepo(benchmarkRepo)
} }
} }
func BenchmarkAuditRepo10000Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 10000
benchmarkRepo = getBenchmarkRepo()
for n := 0; n < b.N; n++ {
auditGitRepo(benchmarkRepo)
}
}
func BenchmarkAuditRepo100000Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 100000
benchmarkRepo = getBenchmarkRepo()
for n := 0; n < b.N; n++ {
auditGitRepo(benchmarkRepo)
}
}
func BenchmarkAuditLeakRepo1Proc(b *testing.B) { func BenchmarkAuditLeakRepo1Proc(b *testing.B) {
loadToml() loadToml()
opts.MaxGoRoutines = 1 opts.MaxGoRoutines = 1
@@ -926,21 +1018,3 @@ func BenchmarkAuditLeakRepo1000Proc(b *testing.B) {
auditGitRepo(benchmarkRepo) auditGitRepo(benchmarkRepo)
} }
} }
func BenchmarkAuditLeakRepo10000Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 10000
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
for n := 0; n < b.N; n++ {
auditGitRepo(benchmarkRepo)
}
}
func BenchmarkAuditLeakRepo100000Proc(b *testing.B) {
loadToml()
opts.MaxGoRoutines = 100000
benchmarkLeaksRepo = getBenchmarkLeaksRepo()
for n := 0; n < b.N; n++ {
auditGitRepo(benchmarkRepo)
}
}
+248 -301
View File
@@ -1,14 +1,14 @@
package main package main
import ( import (
"context"
"crypto/md5" "crypto/md5"
"encoding/csv" "encoding/csv"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"math"
"net" "net"
"net/http"
"net/url" "net/url"
"os" "os"
"os/user" "os/user"
@@ -16,27 +16,26 @@ import (
"path/filepath" "path/filepath"
"regexp" "regexp"
"runtime" "runtime"
"strconv"
"strings" "strings"
"sync" "sync"
"time" "time"
"gopkg.in/src-d/go-git.v4/plumbing" "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/object"
"gopkg.in/src-d/go-git.v4/plumbing/transport/ssh" "gopkg.in/src-d/go-git.v4/plumbing/transport/ssh"
"gopkg.in/src-d/go-git.v4/storage/memory" "gopkg.in/src-d/go-git.v4/storage/memory"
"github.com/BurntSushi/toml" "github.com/BurntSushi/toml"
"github.com/google/go-github/github" "github.com/google/go-github/github"
"github.com/hako/durafmt"
flags "github.com/jessevdk/go-flags" flags "github.com/jessevdk/go-flags"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
git "gopkg.in/src-d/go-git.v4" git "gopkg.in/src-d/go-git.v4"
) )
// Leak represents a leaked secret or regex match. // Leak represents a leaked secret or regex match.
// Output to stdout as json if the --verbose option is set or
// as a csv if the --csv and --report options are set.
type Leak struct { type Leak struct {
Line string `json:"line"` Line string `json:"line"`
Commit string `json:"commit"` Commit string `json:"commit"`
@@ -61,11 +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/"`
IncludePrivate bool `short:"p" long:"private" description:"Include private repos in audit"` GithubPR string `long:"github-pr" description:"Github PR url to audit. This does not clone the repo. GITHUB_TOKEN must be set"`
/* /*
TODO: TODO:
@@ -75,26 +74,27 @@ type Options struct {
Branch string `short:"b" long:"branch" description:"branch name to audit (defaults to HEAD)"` 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"` Commit string `short:"c" long:"commit" description:"sha of commit to stop at"`
Depth int `long:"depth" description:"maximum commit depth"`
// local target option // local target option
RepoPath string `long:"repo-path" description:"Path to repo"` RepoPath string `long:"repo-path" description:"Path to repo"`
OwnerPath string `long:"owner-path" description:"Path to owner directory (repos discovered)"` OwnerPath string `long:"owner-path" description:"Path to owner directory (repos discovered)"`
// Process options // Process options
MaxGoRoutines int `long:"max-go" description:"Maximum number of concurrent go-routines gitleaks spawns"` MaxGoRoutines int `long:"max-go" description:"Maximum number of concurrent go-routines gitleaks spawns"`
Disk bool `long:"disk" description:"Clones repo(s) to disk"` Disk bool `long:"disk" description:"Clones repo(s) to disk"`
AuditAllRefs bool `long:"all-refs" description:"run audit on all refs"` AuditAllRefs bool `long:"all-refs" description:"run audit on all refs"`
SingleSearch string `long:"single-search" description:"single regular expression to search for"` SingleSearch string `long:"single-search" description:"single regular expression to search for"`
ConfigPath string `long:"config" description:"path to gitleaks config"` ConfigPath string `long:"config" description:"path to gitleaks config"`
SSHKey string `long:"ssh-key" description:"path to ssh key"` SSHKey string `long:"ssh-key" description:"path to ssh key"`
ExcludeForks bool `long:"exclude-forks" description:"exclude forks for organization/user audits"` 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"` // TODO: IncludeMessages string `long:"messages" description:"include commit messages in audit"`
// Output options // Output options
Log string `short:"l" long:"log" description:"log level"` Log string `short:"l" long:"log" description:"log level"`
Verbose bool `short:"v" long:"verbose" description:"Show verbose output from gitleaks audit"` Verbose bool `short:"v" long:"verbose" description:"Show verbose output from gitleaks audit"`
Report string `long:"report" description:"path to write report file"` Report string `long:"report" description:"path to write report file. Needs to be csv or json"`
CSV bool `long:"csv" description:"report output to csv"`
Redact bool `long:"redact" description:"redact secrets from log messages and report"` Redact bool `long:"redact" description:"redact secrets from log messages and report"`
Version bool `long:"version" description:"version number"` Version bool `long:"version" description:"version number"`
SampleConfig bool `long:"sample-config" description:"prints a sample config file"` SampleConfig bool `long:"sample-config" description:"prints a sample config file"`
@@ -113,18 +113,30 @@ type Config struct {
Branches []string Branches []string
Repos []string Repos []string
} }
Misc struct {
Entropy []string
}
} }
type gitDiff struct { type gitDiff struct {
content string content string
commit *object.Commit commit *object.Commit
filePath string filePath string
branchName string branchName string
repoName string repoName string
githubCommit *github.RepositoryCommit
sha string
message 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.9.0" const version = "1.16.0"
const errExit = 2 const errExit = 2
const leakExit = 1 const leakExit = 1
const defaultConfig = ` const defaultConfig = `
@@ -173,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
#] #]
` `
@@ -189,11 +207,13 @@ 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
maxGo int maxGo int
totalCommits int64
) )
func init() { func init() {
@@ -204,7 +224,20 @@ func init() {
} }
func main() { func main() {
_, err := flags.Parse(&opts) parser := flags.NewParser(&opts, flags.Default)
_, err := parser.Parse()
if err != nil {
if flagsErr, ok := err.(*flags.Error); ok && flagsErr.Type == flags.ErrHelp {
os.Exit(0)
}
}
if len(os.Args) == 1 {
parser.WriteHelp(os.Stdout)
os.Exit(0)
}
if opts.Version { if opts.Version {
fmt.Println(version) fmt.Println(version)
os.Exit(0) os.Exit(0)
@@ -213,18 +246,24 @@ func main() {
fmt.Println(defaultConfig) fmt.Println(defaultConfig)
os.Exit(0) os.Exit(0)
} }
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)
} }
if opts.Report != "" { if opts.Report != "" {
writeReport(leaks) writeReport(leaks)
} }
if len(leaks) != 0 { if len(leaks) != 0 {
log.Warnf("leaks detected") log.Warnf("%d leaks detected. %d commits inspected in %s", len(leaks), totalCommits, durafmt.Parse(time.Now().Sub(now)).String())
os.Exit(leakExit) os.Exit(leakExit)
} else {
log.Infof("%d leaks detected. %d commits inspected in %s", len(leaks), totalCommits, durafmt.Parse(time.Now().Sub(now)).String())
} }
} }
@@ -240,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")
@@ -279,12 +316,13 @@ 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
} }
} else if opts.GithubPR != "" {
return auditGithubPR()
} }
return leaks, nil return leaks, nil
} }
@@ -294,7 +332,7 @@ func run() ([]Leak, error) {
func writeReport(leaks []Leak) error { func writeReport(leaks []Leak) error {
var err error var err error
log.Infof("writing report to %s", opts.Report) log.Infof("writing report to %s", opts.Report)
if opts.CSV { if strings.HasSuffix(opts.Report, ".csv") {
f, err := os.Create(opts.Report) f, err := os.Create(opts.Report)
if err != nil { if err != nil {
return err return err
@@ -313,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,
@@ -337,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,
@@ -371,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()
@@ -425,81 +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 repoName string
semaphore chan bool leaks []Leak
repoName string commitCount int
leaks []Leak commitWg sync.WaitGroup
commitWg sync.WaitGroup mutex = &sync.Mutex{}
mutex = &sync.Mutex{} 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 { if c == nil || c.Hash.String() == opts.Commit || (opts.Depth != 0 && commitCount == opts.Depth) {
cIter.Close() cIter.Close()
return errors.New("ErrStop")
} }
commitCount = commitCount + 1
totalCommits = totalCommits + 1
if whiteListCommits[c.Hash.String()] { if whiteListCommits[c.Hash.String()] {
log.Infof("skipping commit: %s\n", c.Hash.String()) log.Infof("skipping commit: %s\n", c.Hash.String())
return nil 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 { err = c.Parents().ForEach(func(parent *object.Commit) error {
t, _ := c.Tree() commitWg.Add(1)
files := t.Files() semaphore <- true
err := files.ForEach(func(file *object.File) error { go func(c *object.Commit, parent *object.Commit) {
content, err := file.Contents() var (
if err != nil { filePath string
return err 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 patch, err := c.Patch(parent)
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)
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
@@ -513,7 +532,6 @@ func auditGitReference(repo *RepoDescriptor, ref *plumbing.Reference) []Leak {
} else if to != nil { } else if to != nil {
filePath = to.Path() filePath = to.Path()
} }
diff.filePath = filePath
for _, re := range whiteListFiles { for _, re := range whiteListFiles {
if re.FindString(filePath) != "" { if re.FindString(filePath) != "" {
skipFile = true skipFile = true
@@ -526,7 +544,15 @@ func auditGitReference(repo *RepoDescriptor, ref *plumbing.Reference) []Leak {
chunks := f.Chunks() chunks := f.Chunks()
for _, chunk := range chunks { for _, chunk := range chunks {
if chunk.Type() == 1 || chunk.Type() == 2 { if chunk.Type() == 1 || chunk.Type() == 2 {
diff.content = chunk.Content() diff := gitDiff{
branchName: string(ref.Name()),
repoName: repoName,
filePath: filePath,
content: chunk.Content(),
sha: c.Hash.String(),
author: c.Author.String(),
message: c.Message,
}
chunkLeaks := inspect(diff) chunkLeaks := inspect(diff)
for _, leak := range chunkLeaks { for _, leak := range chunkLeaks {
mutex.Lock() mutex.Lock()
@@ -536,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()
@@ -576,208 +602,78 @@ func inspect(diff gitDiff) []Leak {
break break
} }
leak := Leak{ leaks = addLeak(leaks, line, match, leakType, diff)
Line: line, }
Commit: diff.commit.Hash.String(),
Offender: match, if opts.Entropy > 0 || len(entropyRanges) != 0 {
Type: leakType, entropyLeak := false
Message: diff.commit.Message, words := strings.Fields(line)
Author: diff.commit.Author.String(), for _, word := range words {
File: diff.filePath, entropy := getShannonEntropy(word)
Branch: diff.branchName, if entropy >= opts.Entropy && len(entropyRanges) == 0 {
Repo: diff.repoName, 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
}
} }
if opts.Redact {
leak.Offender = "REDACTED"
leak.Line = "REDACTED"
}
if opts.Verbose {
leak.log()
}
leaks = append(leaks, leak)
} }
} }
return leaks return leaks
} }
// auditGithubRepos kicks off audits if --github-user or --github-org options are set. // addLeak is helper for func inspect() to append leaks if found during a diff check.
// First, we gather all the github repositories from the github api (this doesnt actually clone the repo). func addLeak(leaks []Leak, line string, offender string, leakType string, diff gitDiff) []Leak {
// After all the repos have been pulled from github's api we proceed to audit the repos by calling auditGithubRepo. leak := Leak{
// If an error occurs during an audit of a repo, that error is logged but won't break the execution cycle. Line: line,
func auditGithubRepos() ([]Leak, error) { Commit: diff.sha,
var ( Offender: offender,
err error Type: leakType,
githubRepos []*github.Repository Author: diff.author,
pagedGithubRepos []*github.Repository File: diff.filePath,
resp *github.Response Branch: diff.branchName,
githubClient *github.Client Repo: diff.repoName,
githubOrgOptions *github.RepositoryListByOrgOptions Message: diff.message,
githubOptions *github.RepositoryListOptions }
done bool if opts.Redact {
leaks []Leak leak.Offender = "REDACTED"
ownerDir string leak.Line = "REDACTED"
)
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 opts.Verbose {
if done { leak.log()
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 leaks = append(leaks, leak)
} return leaks
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 // getShannonEntropy https://en.wiktionary.org/wiki/Shannon_entropy
// will be cloned to disk if --disk is set. If the repo is private, you must include the func getShannonEntropy(data string) (entropy float64) {
// --private/-p option. After the repo is clone, an audit will begin. if data == "" {
func cloneGithubRepo(githubRepo *github.Repository) (*RepoDescriptor, error) { return 0
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 charCounts := make(map[rune]int)
// if you are running audits with --github-user or --github-org for _, char := range data {
func githubToken() *http.Client { charCounts[char]++
githubToken := os.Getenv("GITHUB_TOKEN")
if githubToken == "" {
return nil
} }
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: githubToken}, invLength := 1.0 / float64(len(data))
) for _, count := range charCounts {
return oauth2.NewClient(context.Background(), ts) freq := float64(count) * invLength
entropy -= freq * math.Log2(freq)
}
return entropy
} }
// discoverRepos walks all the children of `path`. If a child directory // discoverRepos walks all the children of `path`. If a child directory
@@ -834,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
@@ -866,6 +760,19 @@ func optsGuard() error {
} }
} }
if opts.Entropy > 8 {
return fmt.Errorf("The maximum level of entropy is 8")
}
if opts.Report != "" {
if !strings.HasSuffix(opts.Report, ".json") && !strings.HasSuffix(opts.Report, ".csv") {
return fmt.Errorf("Report should be a .json or .csv file")
}
dirPath := filepath.Dir(opts.Report)
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
return fmt.Errorf("%s does not exist", dirPath)
}
}
return nil return nil
} }
@@ -900,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 {
@@ -908,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
@@ -919,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
@@ -938,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() {
+24
View File
@@ -0,0 +1,24 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
*.prof
+21
View File
@@ -0,0 +1,21 @@
language: go
go:
- 1.5
- 1.6
- 1.7
- 1.8
- 1.9
- tip
before_install:
- go get golang.org/x/tools/cmd/cover
script:
- GOARCH=386 go test # test 32bit architectures.
- go test -coverprofile=coverage.txt -covermode=atomic
after_success:
- bash <(curl -s https://codecov.io/bash)
sudo: false
+46
View File
@@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at wesley@hakobaito.co.uk. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
+9
View File
@@ -0,0 +1,9 @@
# Contributing
Contributions are welcome! Fork this repo and add your changes and submit a PR.
If you would like to fix a bug, add a feature or provide feedback you can do so in the issues section.
You can run tests by runnning `go test`. Running `go test; go vet; golint` is recommended.
durafmt is also tested against `gometalinter`.
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016 Wesley Hill
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+122
View File
@@ -0,0 +1,122 @@
# durafmt
[![Build Status](https://travis-ci.org/hako/durafmt.svg?branch=master)](https://travis-ci.org/hako/durafmt) [![Go Report Card](https://goreportcard.com/badge/github.com/hako/durafmt)](https://goreportcard.com/report/github.com/hako/durafmt) [![codecov](https://codecov.io/gh/hako/durafmt/branch/master/graph/badge.svg)](https://codecov.io/gh/hako/durafmt) [![GoDoc](https://godoc.org/github.com/hako/durafmt?status.svg)](https://godoc.org/github.com/hako/durafmt)
[![Open Source Helpers](https://www.codetriage.com/hako/durafmt/badges/users.svg)](https://www.codetriage.com/hako/durafmt)
durafmt is a tiny Go library that formats `time.Duration` strings into a human readable format.
```
go get github.com/hako/durafmt
```
# Why
If you've worked with `time.Duration` in Go, you most likely have come across this:
```
53m28.587093086s // :)
```
The above seems very easy to read, unless your duration looks like this:
```
354h22m3.24s // :S
```
# Usage
### durafmt.ParseString()
```go
package main
import (
"fmt"
"github.com/hako/durafmt"
)
func main() {
duration, err := durafmt.ParseString("354h22m3.24s")
if err != nil {
fmt.Println(err)
}
fmt.Println(duration) // 2 weeks 18 hours 22 minutes 3 seconds
// duration.String() // String representation. "2 weeks 18 hours 22 minutes 3 seconds"
}
```
### durafmt.ParseStringShort()
Version of `durafmt.ParseString()` that only returns the first part of the duration string.
```go
package main
import (
"fmt"
"github.com/hako/durafmt"
)
func main() {
duration, err := durafmt.ParseStringShort("354h22m3.24s")
if err != nil {
fmt.Println(err)
}
fmt.Println(duration) // 2 weeks
// duration.String() // String short representation. "2 weeks"
}
```
### durafmt.Parse()
```go
package main
import (
"fmt"
"time"
"github.com/hako/durafmt"
)
func main() {
timeduration := (354 * time.Hour) + (22 * time.Minute) + (3 * time.Second)
duration := durafmt.Parse(timeduration).String()
fmt.Println(duration) // 2 weeks 18 hours 22 minutes 3 seconds
}
```
### durafmt.ParseShort()
Version of `durafmt.Parse()` that only returns the first part of the duration string.
```go
package main
import (
"fmt"
"time"
"github.com/hako/durafmt"
)
func main() {
timeduration := (354 * time.Hour) + (22 * time.Minute) + (3 * time.Second)
duration := durafmt.ParseShort(timeduration).String()
fmt.Println(duration) // 2 weeks
}
```
# Contributing
Contributions are welcome! Fork this repo and add your changes and submit a PR.
If you would like to fix a bug, add a feature or provide feedback you can do so in the issues section.
You can run tests by runnning `go test`. Running `go test; go vet; golint` is recommended.
durafmt is also tested against `gometalinter`.
# License
MIT
+147
View File
@@ -0,0 +1,147 @@
// Package durafmt formats time.Duration into a human readable format.
package durafmt
import (
"errors"
"strconv"
"strings"
"time"
)
var (
units = []string{"years", "weeks", "days", "hours", "minutes", "seconds", "milliseconds"}
)
// Durafmt holds the parsed duration and the original input duration.
type Durafmt struct {
duration time.Duration
input string // Used as reference.
short bool
}
// Parse creates a new *Durafmt struct, returns error if input is invalid.
func Parse(dinput time.Duration) *Durafmt {
input := dinput.String()
return &Durafmt{dinput, input, false}
}
// ParseShort creates a new *Durafmt struct, short form, returns error if input is invalid.
func ParseShort(dinput time.Duration) *Durafmt {
input := dinput.String()
return &Durafmt{dinput, input, true}
}
// ParseString creates a new *Durafmt struct from a string.
// returns an error if input is invalid.
func ParseString(input string) (*Durafmt, error) {
if input == "0" || input == "-0" {
return nil, errors.New("durafmt: missing unit in duration " + input)
}
duration, err := time.ParseDuration(input)
if err != nil {
return nil, err
}
return &Durafmt{duration, input, false}, nil
}
// ParseStringShort creates a new *Durafmt struct from a string, short form
// returns an error if input is invalid.
func ParseStringShort(input string) (*Durafmt, error) {
if input == "0" || input == "-0" {
return nil, errors.New("durafmt: missing unit in duration " + input)
}
duration, err := time.ParseDuration(input)
if err != nil {
return nil, err
}
return &Durafmt{duration, input, true}, nil
}
// String parses d *Durafmt into a human readable duration.
func (d *Durafmt) String() string {
var duration string
// Check for minus durations.
if string(d.input[0]) == "-" {
duration += "-"
d.duration = -d.duration
}
// Convert duration.
seconds := int64(d.duration.Seconds()) % 60
minutes := int64(d.duration.Minutes()) % 60
hours := int64(d.duration.Hours()) % 24
days := int64(d.duration/(24*time.Hour)) % 365 % 7
// Edge case between 364 and 365 days.
// We need to calculate weeks from what is left from years
leftYearDays := int64(d.duration/(24*time.Hour)) % 365
weeks := leftYearDays / 7
if leftYearDays >= 364 && leftYearDays < 365 {
weeks = 52
}
years := int64(d.duration/(24*time.Hour)) / 365
milliseconds := int64(d.duration/time.Millisecond) -
(seconds * 1000) - (minutes * 60000) - (hours * 3600000) -
(days * 86400000) - (weeks * 604800000) - (years * 31536000000)
// Create a map of the converted duration time.
durationMap := map[string]int64{
"milliseconds": milliseconds,
"seconds": seconds,
"minutes": minutes,
"hours": hours,
"days": days,
"weeks": weeks,
"years": years,
}
// Construct duration string.
for _, u := range units {
v := durationMap[u]
strval := strconv.FormatInt(v, 10)
switch {
// add to the duration string if v > 1.
case v > 1:
duration += strval + " " + u + " "
// remove the plural 's', if v is 1.
case v == 1:
duration += strval + " " + strings.TrimRight(u, "s") + " "
// omit any value with 0s or 0.
case d.duration.String() == "0" || d.duration.String() == "0s":
// note: milliseconds and minutes have the same suffix (m)
// so we have to check if the units match with the suffix.
// check for a suffix that is NOT the milliseconds suffix.
if strings.HasSuffix(d.input, string(u[0])) && !strings.Contains(d.input, "ms") {
// if it happens that the units are milliseconds, skip.
if u == "milliseconds" {
continue
}
duration += strval + " " + u
}
// process milliseconds here.
if u == "milliseconds" {
if strings.Contains(d.input, "ms") {
duration += strval + " " + u
break
}
}
break
// omit any value with 0.
case v == 0:
continue
}
}
// trim any remaining spaces.
duration = strings.TrimSpace(duration)
// if more than 2 spaces present return the first 2 strings
// if short version is requested
if d.short {
duration = strings.Join(strings.Split(duration, " ")[:2], " ")
}
return duration
}