From faca0e14d91e974afec4d491e504a8eaebefbb31 Mon Sep 17 00:00:00 2001 From: zricethezav Date: Tue, 27 Feb 2018 21:56:46 -0600 Subject: [PATCH 01/16] refactoring after actually learning some go patterns --- checks.go | 10 +- checks_test.go | 4 +- leaks.go | 209 ++++++---------------------------------- main.go | 201 ++++++++------------------------------- owner.go | 251 +++++++++++++++++++++++++++++++++++++++++++++++++ repo.go | 224 +++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 549 insertions(+), 350 deletions(-) create mode 100644 owner.go create mode 100644 repo.go diff --git a/checks.go b/checks.go index 86cfdcca..78993189 100644 --- a/checks.go +++ b/checks.go @@ -9,11 +9,11 @@ import ( // TODO LOCAL REPO!!!! // checks Regex and if enabled, entropy and stopwords -func doChecks(diff string, commit Commit, opts *Options, repo RepoDesc) []LeakElem { +func doChecks(diff string, commit Commit, opts *Options, repo *Repo) []Leak { var ( match string - leaks []LeakElem - leak LeakElem + leaks []Leak + leak Leak ) lines := strings.Split(diff, "\n") @@ -34,7 +34,7 @@ func doChecks(diff string, commit Commit, opts *Options, repo RepoDesc) []LeakEl continue } - leak = LeakElem{ + leak = Leak{ Line: line, Commit: commit.Hash, Offender: match, @@ -109,7 +109,7 @@ func checkShannonEntropy(target string, opts *Options) bool { func containsStopWords(target string) bool { // Convert to lowercase to reduce the number of loops needed. target = strings.ToLower(target) - + for _, stopWord := range stopWords { if strings.Contains(target, stopWord) { return true diff --git a/checks_test.go b/checks_test.go index 0d1e5905..89a377de 100644 --- a/checks_test.go +++ b/checks_test.go @@ -5,14 +5,14 @@ import ( ) func TestCheckRegex(t *testing.T) { - var results []LeakElem + var results []Leak opts := &Options{ Concurrency: 10, B64EntropyCutoff: 70, HexEntropyCutoff: 40, Entropy: false, } - repo := RepoDesc{ + repo := Repo{ url: "someurl", } commit := Commit{} diff --git a/leaks.go b/leaks.go index 3281f700..ec732b3a 100644 --- a/leaks.go +++ b/leaks.go @@ -1,66 +1,25 @@ package main -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "log" - "os" - "os/exec" - "os/signal" - "path/filepath" - "strings" - "sync" - "syscall" -) +// TODO https://medium.com/@sebdah/go-best-practices-error-handling-2d15e1f0c5ee +// implement better error handling -// LeakElem contains the line and commit of a leak -type LeakElem struct { - Line string `json:"line"` - Commit string `json:"commit"` - Offender string `json:"string"` - Reason string `json:"reason"` - Msg string `json:"commitMsg"` - Time string `json:"time"` - Author string `json:"author"` - File string `json:"file"` - RepoURL string `json:"repoURL"` -} +// Commit is so and so -type Commit struct { - Hash string - Author string - Time string - Msg string -} - -func rmTmp(owner *Owner) { - if _, err := os.Stat(owner.path); err == nil { - err := os.RemoveAll(owner.path) - log.Printf("\nCleaning up tmp repos in %s\n", owner.path) - if err != nil { - log.Printf("failed to properly remove tmp gitleaks dir: %v", err) - } - } - os.Exit(1) -} - -// start -func start(repos []RepoDesc, owner *Owner, opts *Options) { - var report []LeakElem - if opts.Tmp { - defer rmTmp(owner) - } +/* +// start kicks off the audit +func start(repos []Repo, owner *Owner, opts *Options) error { + var ( + report []Leak + err error + ) + defer rmTmpDirs(owner, opts) // interrupt handling c := make(chan os.Signal, 2) signal.Notify(c, os.Interrupt, syscall.SIGTERM) go func() { <-c - if opts.Tmp { - rmTmp(owner) - } + rmTmpDirs(owner, opts) os.Exit(1) }() @@ -73,24 +32,23 @@ func start(repos []RepoDesc, owner *Owner, opts *Options) { } // use pre-cloned repo fmt.Printf("Checking \x1b[37;1m%s\x1b[0m...\n", repo.url) - err := exec.Command("git", "fetch").Run() - if err != nil { - log.Printf("failed to fetch repo %v", err) - return - } - report = getLeaks(repo, owner, opts) + err = exec.Command("git", "fetch").Run() } else { // no repo present, clone it if err := os.Chdir(fmt.Sprintf(owner.path)); err != nil { log.Fatal(err) } fmt.Printf("Cloning \x1b[37;1m%s\x1b[0m...\n", repo.url) - err := exec.Command("git", "clone", repo.url).Run() - if err != nil { - fmt.Printf("failed to clone repo %v", err) - return - } - report = getLeaks(repo, owner, opts) + err = exec.Command("git", "clone", repo.url).Run() + } + if err != nil { + log.Printf("failed to fetch repo %v", err) + return nil + } + + report, err = audit(&repo, opts) + if err != nil { + return nil } if len(report) == 0 { @@ -98,123 +56,14 @@ func start(repos []RepoDesc, owner *Owner, opts *Options) { } if opts.EnableJSON && len(report) != 0 { - outputGitLeaksReport(report, repo, opts) + writeReport(report, repo) } } + return nil } +*/ -// outputGitLeaksReport -func outputGitLeaksReport(report []LeakElem, repo RepoDesc, opts *Options) { - reportJSON, _ := json.MarshalIndent(report, "", "\t") - if _, err := os.Stat(repo.owner.reportPath); os.IsNotExist(err) { - os.Mkdir(repo.owner.reportPath, os.ModePerm) - } +// Used by start, writeReport will generate a report and write it out to +// $GITLEAKS_HOME/report//. No report will be generated if +// no leaks have been found - reportFileName := fmt.Sprintf("%s_leaks.json", repo.name) - reportFile := filepath.Join(repo.owner.reportPath, reportFileName) - err := ioutil.WriteFile(reportFile, reportJSON, 0644) - if err != nil { - log.Fatalf("Can't write to file: %s", err) - } - fmt.Printf("Report written to %s\n", reportFile) -} - -// getLeaks will attempt to find gitleaks -func getLeaks(repo RepoDesc, owner *Owner, opts *Options) []LeakElem { - var ( - out []byte - err error - commitWG sync.WaitGroup - gitLeakReceiverWG sync.WaitGroup - gitLeaks = make(chan LeakElem) - report []LeakElem - ) - semaphoreChan := make(chan struct{}, opts.Concurrency) - - go func(commitWG *sync.WaitGroup, gitLeakReceiverWG *sync.WaitGroup) { - for gitLeak := range gitLeaks { - b, err := json.MarshalIndent(gitLeak, "", " ") - if err != nil { - fmt.Println("failed to output leak:", err) - } - fmt.Println(string(b)) - report = append(report, gitLeak) - gitLeakReceiverWG.Done() - } - }(&commitWG, &gitLeakReceiverWG) - - if err := os.Chdir(fmt.Sprintf(repo.path)); err != nil { - log.Fatal(err) - } - - gitFormat := "--format=%H%n%an%n%s%n%ci" - out, err = exec.Command("git", "rev-list", "--all", - "--remotes", "--topo-order", gitFormat).Output() - if err != nil { - log.Fatalf("error retrieving commits%v\n", err) - } - - revListLines := bytes.Split(out, []byte("\n")) - commits := parseFormattedRevList(revListLines) - - for _, commit := range commits { - if commit.Hash == "" { - continue - } - - commitWG.Add(1) - go func(currCommit Commit, repoName string, commitWG *sync.WaitGroup, - gitLeakReceiverWG *sync.WaitGroup, opts *Options) { - defer commitWG.Done() - if err := os.Chdir(fmt.Sprintf(repo.path)); err != nil { - log.Fatal(err) - } - - commitCmp := fmt.Sprintf("%s^!", currCommit.Hash) - semaphoreChan <- struct{}{} - out, err := exec.Command("git", "diff", commitCmp).Output() - <-semaphoreChan - - if err != nil { - if strings.Contains(err.Error(), "too many files open") { - log.Printf("error retrieving diff for commit %s. Try turning concurrency down. %v\n", currCommit, err) - } - if opts.Tmp { - rmTmp(owner) - } - } - - leaks := doChecks(string(out), currCommit, opts, repo) - if len(leaks) == 0 { - return - } - for _, leak := range leaks { - gitLeakReceiverWG.Add(1) - gitLeaks <- leak - } - - }(commit, repo.name, &commitWG, &gitLeakReceiverWG, opts) - - if commit.Hash == opts.SinceCommit { - break - } - } - - commitWG.Wait() - gitLeakReceiverWG.Wait() - return report -} - -func parseFormattedRevList(revList [][]byte) []Commit { - var commits []Commit - for i := 0; i < len(revList)-1; i = i + 5 { - commit := Commit{ - Hash: string(revList[i+1]), - Author: string(revList[i+2]), - Msg: string(revList[i+3]), - Time: string(revList[i+4]), - } - commits = append(commits, commit) - } - return commits -} diff --git a/main.go b/main.go index fc5d82df..9af8bb28 100644 --- a/main.go +++ b/main.go @@ -1,20 +1,22 @@ package main import ( - "context" - "github.com/google/go-github/github" + _ "fmt" "github.com/mitchellh/go-homedir" - "golang.org/x/oauth2" - "io/ioutil" "log" - "net/http" + _"io/ioutil" "os" - "path" "path/filepath" "regexp" - "strings" + "go.uber.org/zap" + _"time" + "go.uber.org/zap/zapcore" ) +const EXIT_CLEAN = 0 +const EXIT_FAILURE = 1 +const EXIT_LEAKS = 2 + var ( regexes map[string]*regexp.Regexp stopWords []string @@ -25,29 +27,13 @@ var ( gitLeaksPath string gitLeaksClonePath string gitLeaksReportPath string + logger *zap.Logger ) -type RepoDesc struct { - name string - url string - path string - owner *Owner -} - -type Owner struct { - name string - url string - accountType string - path string - reportPath string -} - func init() { base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" hexChars = "1234567890abcdefABCDEF" - stopWords = []string{"setting", "info", "env", "environment"} - regexes = map[string]*regexp.Regexp{ "PKCS8": regexp.MustCompile("-----BEGIN PRIVATE KEY-----"), "RSA": regexp.MustCompile("-----BEGIN RSA PRIVATE KEY-----"), @@ -60,14 +46,19 @@ func init() { "Heroku": regexp.MustCompile("(?i)heroku.*[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}"), // "Custom": regexp.MustCompile(".*") } - assignRegex = regexp.MustCompile(`(=|:|:=|<-)`) fileDiffRegex = regexp.MustCompile("diff --git a.+b/") - homeDir, err := homedir.Dir() - if err != nil { - log.Fatal("Cant find home dir") + assignRegex = regexp.MustCompile(`(=|:|:=|<-)`) + + // gitleaks dir defaults to $HOME/.gitleaks if no env var GITLEAKS_HOME is present. + gitLeaksPath = os.Getenv("GITLEAKS_HOME") + if gitLeaksPath == "" { + homeDir, err := homedir.Dir() + if err != nil { + log.Fatal("Cant find home dir") + } + gitLeaksPath = filepath.Join(homeDir, ".gitleaks") } - gitLeaksPath = filepath.Join(homeDir, ".gitleaks") if _, err := os.Stat(gitLeaksPath); os.IsNotExist(err) { os.Mkdir(gitLeaksPath, os.ModePerm) } @@ -81,141 +72,25 @@ func init() { } } -// getOwner -func getOwner(opts *Options) *Owner { - var owner Owner - if opts.RepoURL != "" { - splitSlashes := strings.Split(opts.RepoURL, "/") - owner = Owner{ - name: splitSlashes[len(splitSlashes)-2], - url: opts.RepoURL, - accountType: "users", - } - - } else if opts.UserURL != "" { - _, ownerName := path.Split(opts.UserURL) - owner = Owner{ - name: ownerName, - url: opts.UserURL, - accountType: "user", - } - } else if opts.OrgURL != "" { - _, ownerName := path.Split(opts.OrgURL) - owner = Owner{ - name: ownerName, - url: opts.OrgURL, - accountType: "org", - } - } - - if opts.Tmp { - dir, err := ioutil.TempDir("", owner.name) - if err != nil { - log.Fatal("Cant make temp dir") - } - owner.path = dir - } else { - owner.path = filepath.Join(gitLeaksClonePath, owner.name) - if _, err := os.Stat(owner.path); os.IsNotExist(err) { - os.Mkdir(owner.path, os.ModePerm) - } - } - owner.reportPath = filepath.Join(gitLeaksPath, "report", owner.name) - return &owner -} - -// getRepos -func getRepos(opts *Options, owner *Owner) []RepoDesc { - var ( - allRepos []*github.Repository - repos []*github.Repository - repoDescs []RepoDesc - resp *github.Response - ctx = context.Background() - err error - ) - if opts.RepoURL != "" { - _, repoName := path.Split(opts.RepoURL) - if strings.HasSuffix(repoName, ".git") { - repoName = repoName[:len(repoName)-4] - } - ownerPath := filepath.Join(owner.path, repoName) - repo := RepoDesc{ - name: repoName, - url: opts.RepoURL, - owner: owner, - path: ownerPath} - repoDescs = append(repoDescs, repo) - return repoDescs - } - - tokenClient := getAccessToken(opts) - gitClient := github.NewClient(tokenClient) - - // TODO include fork check - orgOpt := &github.RepositoryListByOrgOptions{ - ListOptions: github.ListOptions{PerPage: 10}, - } - userOpt := &github.RepositoryListOptions{ - ListOptions: github.ListOptions{PerPage: 10}, - } - - for { - if opts.UserURL != "" { - repos, resp, err = gitClient.Repositories.List( - ctx, owner.name, userOpt) - } else if opts.OrgURL != "" { - repos, resp, err = gitClient.Repositories.ListByOrg( - ctx, owner.name, orgOpt) - } - allRepos = append(allRepos, repos...) - if resp.NextPage == 0 || err != nil { - break - } - - for _, repo := range repos { - repoPath := filepath.Join(owner.path, *repo.Name) - repoDescs = append(repoDescs, - RepoDesc{ - name: *repo.Name, - url: *repo.CloneURL, - owner: owner, - path: repoPath}) - } - - orgOpt.Page = resp.NextPage - userOpt.Page = resp.NextPage - } - - return repoDescs -} - -// getAccessToken checks -// 1. option -// 2. env var -// TODO. $HOME/.gitleaks/.creds -func getAccessToken(opts *Options) *http.Client { - var token string - if opts.Token != "" { - token = opts.Token - } else { - token = os.Getenv("GITHUB_TOKEN") - } - if token == "" { - return nil - } - - tokenService := oauth2.StaticTokenSource( - &oauth2.Token{AccessToken: token}, - ) - tokenClient := oauth2.NewClient(context.Background(), tokenService) - return tokenClient -} - func main() { + // TODO abstract logging + atom := zap.NewAtomicLevel() + encoderCfg := zap.NewProductionEncoderConfig() + encoderCfg.TimeKey = "" + logger = zap.New(zapcore.NewCore( + zapcore.NewJSONEncoder(encoderCfg), + zapcore.Lock(os.Stdout), + atom, + )) + logger.Info("HEY") + atom.SetLevel(zap.InfoLevel) + logger.Info("HEY") + + args := os.Args[1:] opts := parseOptions(args) - owner := getOwner(opts) - repos := getRepos(opts, owner) - start(repos, owner, opts) + owner := newOwner(opts) + owner.auditRepos(opts) + // repos := getRepos(opts, owner) + // start(repos, owner, opts) } diff --git a/owner.go b/owner.go new file mode 100644 index 00000000..1af6cc28 --- /dev/null +++ b/owner.go @@ -0,0 +1,251 @@ +package main + +import ( + "path" + "io/ioutil" + "path/filepath" + "os" + "github.com/google/go-github/github" + "strings" + "context" + "golang.org/x/oauth2" + "net/http" + "log" + "os/signal" + _"fmt" +) + +type Owner struct { + name string + url string + accountType string + path string + reportPath string + repos []Repo +} + +// newOwner instantiates an owner and creates any necessary resources for said owner. +// newOwner returns a Owner struct pointer +func newOwner(opts *Options) *Owner { + name, err := ownerName(opts) + owner := &Owner{ + name: name, + url: opts.UserURL, + accountType: ownerType(opts), + } + + if err != nil { + owner.failf() + } + + // listen for ctrl-c + // NOTE: need some help on how to actually shut down gracefully. + // On interrupt a repo may still be trying to clone... This has no + // actual effect other than extraneous logging. + sigC := make(chan os.Signal, 1) + signal.Notify(sigC, os.Interrupt, os.Interrupt) + go func() { + <-sigC + owner.rmTmp() + }() + + owner.setupDir(opts) + owner.fetchRepos(opts) + return owner +} + +// fetchRepos is used by newOwner and is responsible for fetching one or more +// of the owner's repos. If opts.RepoURL is not the empty string then fetchRepos will +// only grab the repo specified in opts.RepoURL. Otherwise, fetchRepos will reach out to +// github's api and grab all repos associated with owner. +func (owner *Owner) fetchRepos(opts *Options) { + ctx := context.Background() + if owner.accountType == "" { + // single repo, ambiguous account type + _, repoName := path.Split(opts.RepoURL) + repo := newRepo(owner, repoName, opts.RepoURL) + owner.repos = append(owner.repos, *repo) + } else { + // org or user account type, would fail if not valid before + tokenClient := githubTokenClient(opts) + gitClient := github.NewClient(tokenClient) + + if owner.accountType == "org" { + // org account type + orgOpt := &github.RepositoryListByOrgOptions{ + ListOptions: github.ListOptions{PerPage: 10}, + } + owner.fetchOrgRepos(orgOpt, gitClient, ctx) + } else { + // user account type + userOpt := &github.RepositoryListOptions{ + ListOptions: github.ListOptions{PerPage: 10}, + } + owner.fetchUserRepos(userOpt, gitClient, ctx) + } + } +} + +// fetchOrgRepos used by fetchRepos is responsible for parsing github's org repo response. If no +// github token is available then fetchOrgRepos might run into a rate limit in which case owner will +// log an error and gitleaks will exit. The rate limit for no token is 50 req/hour... not much. +func (owner *Owner) fetchOrgRepos(orgOpts *github.RepositoryListByOrgOptions, gitClient *github.Client, + ctx context.Context) { + var ( + githubRepos []*github.Repository + resp *github.Response + err error + ) + + for { + githubRepos, resp, err = gitClient.Repositories.ListByOrg( + ctx, owner.name, orgOpts) + owner.addRepos(githubRepos) + if _, ok := err.(*github.RateLimitError); ok { + log.Println("hit rate limit") + break + } else if err != nil { + log.Println("other error") + break + } else if resp.NextPage == 0 { + break + } + orgOpts.Page = resp.NextPage + } +} + +// fetchUserRepos used by fetchRepos is responsible for parsing github's user repo response. If no +// github token is available then fetchUserRepos might run into a rate limit in which case owner will +// log an error and gitleaks will exit. The rate limit for no token is 50 req/hour... not much. +// sorry for the redundancy +func (owner *Owner) fetchUserRepos(userOpts *github.RepositoryListOptions, gitClient *github.Client, + ctx context.Context) { + var ( + githubRepos []*github.Repository + resp *github.Response + err error + ) + for { + githubRepos, resp, err = gitClient.Repositories.List( + ctx, owner.name, userOpts) + owner.addRepos(githubRepos) + if _, ok := err.(*github.RateLimitError); ok { + log.Println("hit rate limit") + break + } else if err != nil { + log.Println("other error") + break + } else if resp.NextPage == 0 { + break + } + userOpts.Page = resp.NextPage + } +} + +// addRepos used by fetchUserRepos and fetchOrgRepos appends new repos from +// github's org/user response. +func (owner *Owner) addRepos (githubRepos []*github.Repository) { + for _, repo := range githubRepos { + owner.repos = append(owner.repos, *newRepo(owner, *repo.Name, *repo.CloneURL)) + } +} + +// auditRepos +func (owner *Owner) auditRepos(opts *Options) { + for _, repo := range owner.repos { + err := repo.audit(owner, opts) + if err != nil { + owner.failf() + } + } +} + +// failf +func (owner *Owner) failf() { + // TODO +} + +// exitNow +func (owner *Owner) exitNow() { + +} + +// setupDir sets up the owner's directory for clones and reports. +// If the temporary option is set then a temporary directory will be +// used for the owner repo clones. +func (owner *Owner) setupDir(opts *Options) { + if opts.Tmp { + dir, err := ioutil.TempDir("", owner.name) + if err != nil { + owner.failf() + } + owner.path = dir + } else { + owner.path = filepath.Join(gitLeaksClonePath, owner.name) + if _, err := os.Stat(owner.path); os.IsNotExist(err) { + os.Mkdir(owner.path, os.ModePerm) + } + } + owner.reportPath = filepath.Join(gitLeaksPath, "report", owner.name) +} + +// rmTmp removes the temporary repo +func (owner *Owner) rmTmp() { + os.RemoveAll(owner.path) + os.Exit(EXIT_FAILURE) +} + +// ownerType returns the owner type extracted from opts. +// If no owner type is provided, gitleaks assumes the owner is ambiguous +// and the user is running gitleaks on a single repo +func ownerType(opts *Options) string { + if opts.OrgURL != "" { + return "org" + + } else if opts.UserURL != "" { + return "user" + } + return "" +} + +// ownerName returns the owner name extracted from the urls provided in opts. +// If no RepoURL, OrgURL, or UserURL is provided, then owner will log an error +// and gitleaks will exit. +func ownerName(opts *Options) (string, error) { + if opts.RepoURL != "" { + splitSlashes := strings.Split(opts.RepoURL, "/") + return splitSlashes[len(splitSlashes)-2], nil + } else if opts.UserURL != "" { + _, ownerName := path.Split(opts.UserURL) + return ownerName, nil + } else if opts.OrgURL != "" { + _, ownerName := path.Split(opts.OrgURL) + return ownerName, nil + } + + // TODO error + return "", nil +} + +// githubTokenClient creates an oauth client from your github access token. +// Gitleaks will attempt to retrieve your github access token from a cli argument +// or an env var - "GITHUB_TOKEN". +// Might be good to eventually parse the token from a config or creds file in +// $GITLEAKS_HOME +func githubTokenClient(opts *Options) *http.Client { + var token string + if opts.Token != "" { + token = opts.Token + } else { + token = os.Getenv("GITHUB_TOKEN") + } + if token == "" { + return nil + } + + tokenService := oauth2.StaticTokenSource( + &oauth2.Token{AccessToken: token}, + ) + tokenClient := oauth2.NewClient(context.Background(), tokenService) + return tokenClient +} diff --git a/repo.go b/repo.go new file mode 100644 index 00000000..8259e2a4 --- /dev/null +++ b/repo.go @@ -0,0 +1,224 @@ +package main + +import ( + "path/filepath" + "os" + "fmt" + "os/exec" + "sync" + "bytes" + "encoding/json" + "log" + "strings" + "io/ioutil" +) + +type Repo struct { + name string + url string + path string + status string // TODO + leaks []Leak + owner *Owner +} + +type Leak struct { + Line string `json:"line"` + Commit string `json:"commit"` + Offender string `json:"string"` + Reason string `json:"reason"` + Msg string `json:"commitMsg"` + Time string `json:"time"` + Author string `json:"author"` + File string `json:"file"` + RepoURL string `json:"repoURL"` +} + +type Commit struct { + Hash string + Author string + Time string + Msg string +} + +func newRepo(owner *Owner, name string, url string) *Repo { + repo := &Repo{ + name: name, + url: url, + path: owner.path + "/" + name, + } + return repo +} + +// Audit operates on a single repo and searches the full or partial history of the repo. +// A semaphore is declared for every repo to bind concurrency. If unbounded, the system will throw a +// `too many open files` error. Eventually, gitleaks should use src-d/go-git to avoid shelling out +// commands so that users could opt for doing all clones/diffs in memory. +// Audit also declares two WaitGroups, one for distributing regex/entropy checks, and one for receiving +// the leaks if there are any. This could be done a little more elegantly in the future. +func (repo *Repo) audit(owner *Owner, opts *Options) error { + var ( + out []byte + err error + commitWG sync.WaitGroup + gitLeakReceiverWG sync.WaitGroup + gitLeaksChan = make(chan Leak) + leaks []Leak + semaphoreChan = make(chan struct{}, opts.Concurrency) + ) + + dotGitPath := filepath.Join(repo.path, ".git") + + // Navigate to proper location to being audit. Clone repo + // if not present, otherwise fetch for new changes. + if _, err := os.Stat(dotGitPath); os.IsNotExist(err) { + // no repo present, clone it + fmt.Printf("Cloning \x1b[37;1m%s\x1b[0m into %s...\n", repo.url, repo.path) + err = exec.Command("git", "clone", repo.url, repo.path).Run() + if err != nil{ + fmt.Println("can run clonse") + } + } else { + fmt.Printf("Checking \x1b[37;1m%s\x1b[0m from %s...\n", repo.url, repo.path) + err = exec.Command("git", "fetch").Run() + if err != nil{ + fmt.Println("can run fetch") + } + } + + if err := os.Chdir(fmt.Sprintf(repo.path)); err != nil { + fmt.Println("cant chdir") + } + + gitFormat := "--format=%H%n%an%n%s%n%ci" + out, err = exec.Command("git", "rev-list", "--all", + "--remotes", "--topo-order", gitFormat).Output() + + if err != nil { + fmt.Println("problem with rev list") + } + + revListLines := bytes.Split(out, []byte("\n")) + commits := parseRevList(revListLines) + + for _, commit := range commits { + if commit.Hash == "" { + continue + } + + commitWG.Add(1) + go auditDiff(commit, repo, &commitWG, &gitLeakReceiverWG, opts, + semaphoreChan, gitLeaksChan) + + if commit.Hash == opts.SinceCommit { + break + } + } + go reportAggregator(&gitLeakReceiverWG, gitLeaksChan, &leaks) + commitWG.Wait() + gitLeakReceiverWG.Wait() + + // repo audit has finished + repo.leaks = leaks + + if opts.EnableJSON && len(leaks) != 0 { + repo.writeReport(owner) + } + + return nil +} + +func (repo *Repo) log() { + +} + +// Used by audit, writeReport will generate a report and write it out to +// $GITLEAKS_HOME/report//. No report will be generated if +// no leaks have been found +func (repo *Repo) writeReport(owner *Owner) { + reportJSON, _ := json.MarshalIndent(repo.leaks, "", "\t") + if _, err := os.Stat(owner.reportPath); os.IsNotExist(err) { + os.Mkdir(repo.owner.reportPath, os.ModePerm) + } + + reportFileName := fmt.Sprintf("%s_leaks.json", repo.name) + reportFile := filepath.Join(owner.reportPath, reportFileName) + err := ioutil.WriteFile(reportFile, reportJSON, 0644) + if err != nil { + fmt.Println("cant write report") + } + fmt.Printf("Report written to %s\n", reportFile) +} + +// parseRevList is responsible for parsing the output of +// $ `git rev-list --all -remotes --topo-order --format=%H%n%an%n%s%n%ci` +// sample output from the above command looks like: +// ... +// SHA +// Author Name +// Commit Msg +// Commit Date +// ... +// Used by audit +func parseRevList(revList [][]byte) []Commit { + var commits []Commit + for i := 0; i < len(revList)-1; i = i + 5 { + commit := Commit{ + Hash: string(revList[i+1]), + Author: string(revList[i+2]), + Msg: string(revList[i+3]), + Time: string(revList[i+4]), + } + commits = append(commits, commit) + } + return commits +} + +// reportAggregator is a go func responsible for ... +func reportAggregator(gitLeakReceiverWG *sync.WaitGroup, gitLeaks chan Leak, leaks *[]Leak) { + for gitLeak := range gitLeaks { + b, err := json.MarshalIndent(gitLeak, "", " ") + if err != nil { + fmt.Println("failed to output leak:", err) + } + fmt.Println(string(b)) + *leaks = append(*leaks, gitLeak) + gitLeakReceiverWG.Done() + } +} + +// Used by audit, auditDiff is a go func responsible for diffing and auditing a commit. +// Three channels are input here: 1. a semaphore to bind gitleaks, 2. a leak stream, 3. error handling (TODO) +// This func performs a diff and runs regexes checks on each line of the diff. +func auditDiff(currCommit Commit, repo *Repo, commitWG *sync.WaitGroup, + gitLeakReceiverWG *sync.WaitGroup, opts *Options, semaphoreChan chan struct{}, + gitLeaks chan Leak) { + // signal to WG this diff is done being audited + defer commitWG.Done() + + if err := os.Chdir(fmt.Sprintf(repo.path)); err != nil { + log.Fatal(err) + } + + commitCmp := fmt.Sprintf("%s^!", currCommit.Hash) + semaphoreChan <- struct{}{} + out, err := exec.Command("git", "diff", commitCmp).Output() + <-semaphoreChan + + if err != nil { + // TODO + if strings.Contains(err.Error(), "too many files open") { + log.Printf("error retrieving diff for commit %s. Try turning concurrency down. %v\n", currCommit, err) + } + } + + leaks := doChecks(string(out), currCommit, opts, repo) + if len(leaks) == 0 { + return + } + for _, leak := range leaks { + gitLeakReceiverWG.Add(1) + gitLeaks <- leak + } +} + From 7919e15a653aecbf475054353f7143beeb28890b Mon Sep 17 00:00:00 2001 From: zricethezav Date: Wed, 28 Feb 2018 19:36:21 -0600 Subject: [PATCH 02/16] my, things have changed... --- checks.go | 4 +- leaks.go | 69 ------------- main.go | 90 ++++++----------- options.go | 278 +++++++++++++++++++++++++++++++++++++++++++---------- owner.go | 165 ++++++++++++++++--------------- repo.go | 116 +++++++++++++--------- 6 files changed, 415 insertions(+), 307 deletions(-) delete mode 100644 leaks.go diff --git a/checks.go b/checks.go index 78993189..0c287bb2 100644 --- a/checks.go +++ b/checks.go @@ -6,10 +6,8 @@ import ( "strings" ) -// TODO LOCAL REPO!!!! - // checks Regex and if enabled, entropy and stopwords -func doChecks(diff string, commit Commit, opts *Options, repo *Repo) []Leak { +func doChecks(diff string, commit Commit, repo *Repo) []Leak { var ( match string leaks []Leak diff --git a/leaks.go b/leaks.go deleted file mode 100644 index ec732b3a..00000000 --- a/leaks.go +++ /dev/null @@ -1,69 +0,0 @@ -package main - -// TODO https://medium.com/@sebdah/go-best-practices-error-handling-2d15e1f0c5ee -// implement better error handling - -// Commit is so and so - -/* -// start kicks off the audit -func start(repos []Repo, owner *Owner, opts *Options) error { - var ( - report []Leak - err error - ) - defer rmTmpDirs(owner, opts) - - // interrupt handling - c := make(chan os.Signal, 2) - signal.Notify(c, os.Interrupt, syscall.SIGTERM) - go func() { - <-c - rmTmpDirs(owner, opts) - os.Exit(1) - }() - - // run checks on repos - for _, repo := range repos { - dotGitPath := filepath.Join(repo.path, ".git") - if _, err := os.Stat(dotGitPath); err == nil { - if err := os.Chdir(fmt.Sprintf(repo.path)); err != nil { - log.Fatal(err) - } - // use pre-cloned repo - fmt.Printf("Checking \x1b[37;1m%s\x1b[0m...\n", repo.url) - err = exec.Command("git", "fetch").Run() - } else { - // no repo present, clone it - if err := os.Chdir(fmt.Sprintf(owner.path)); err != nil { - log.Fatal(err) - } - fmt.Printf("Cloning \x1b[37;1m%s\x1b[0m...\n", repo.url) - err = exec.Command("git", "clone", repo.url).Run() - } - if err != nil { - log.Printf("failed to fetch repo %v", err) - return nil - } - - report, err = audit(&repo, opts) - if err != nil { - return nil - } - - if len(report) == 0 { - fmt.Printf("No Leaks detected for \x1b[35;2m%s\x1b[0m...\n", repo.url) - } - - if opts.EnableJSON && len(report) != 0 { - writeReport(report, repo) - } - } - return nil -} -*/ - -// Used by start, writeReport will generate a report and write it out to -// $GITLEAKS_HOME/report//. No report will be generated if -// no leaks have been found - diff --git a/main.go b/main.go index 9af8bb28..ad8aa84f 100644 --- a/main.go +++ b/main.go @@ -2,38 +2,38 @@ package main import ( _ "fmt" - "github.com/mitchellh/go-homedir" - "log" - _"io/ioutil" - "os" - "path/filepath" - "regexp" "go.uber.org/zap" - _"time" - "go.uber.org/zap/zapcore" + _ "io/ioutil" + "os" + "regexp" + _ "time" + "fmt" ) const EXIT_CLEAN = 0 const EXIT_FAILURE = 1 const EXIT_LEAKS = 2 +// package globals var ( - regexes map[string]*regexp.Regexp - stopWords []string - base64Chars string - hexChars string - assignRegex *regexp.Regexp - fileDiffRegex *regexp.Regexp - gitLeaksPath string - gitLeaksClonePath string - gitLeaksReportPath string - logger *zap.Logger + regexes map[string]*regexp.Regexp + stopWords []string + base64Chars string + hexChars string + assignRegex *regexp.Regexp + fileDiffRegex *regexp.Regexp + logger *zap.Logger + opts *Options ) func init() { base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" hexChars = "1234567890abcdefABCDEF" stopWords = []string{"setting", "info", "env", "environment"} + fileDiffRegex = regexp.MustCompile("diff --git a.+b/") + assignRegex = regexp.MustCompile(`(=|:|:=|<-)`) + + // TODO Externalize regex... this is tricky making it yml compliant regexes = map[string]*regexp.Regexp{ "PKCS8": regexp.MustCompile("-----BEGIN PRIVATE KEY-----"), "RSA": regexp.MustCompile("-----BEGIN RSA PRIVATE KEY-----"), @@ -44,53 +44,19 @@ func init() { "AWS": regexp.MustCompile("AKIA[0-9A-Z]{16}"), "Reddit": regexp.MustCompile("(?i)reddit.*['|\"][0-9a-zA-Z]{14}['|\"]"), "Heroku": regexp.MustCompile("(?i)heroku.*[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}"), - // "Custom": regexp.MustCompile(".*") - } - fileDiffRegex = regexp.MustCompile("diff --git a.+b/") - assignRegex = regexp.MustCompile(`(=|:|:=|<-)`) - - // gitleaks dir defaults to $HOME/.gitleaks if no env var GITLEAKS_HOME is present. - gitLeaksPath = os.Getenv("GITLEAKS_HOME") - if gitLeaksPath == "" { - homeDir, err := homedir.Dir() - if err != nil { - log.Fatal("Cant find home dir") - } - gitLeaksPath = filepath.Join(homeDir, ".gitleaks") - } - - if _, err := os.Stat(gitLeaksPath); os.IsNotExist(err) { - os.Mkdir(gitLeaksPath, os.ModePerm) - } - gitLeaksClonePath = filepath.Join(gitLeaksPath, "clones") - if _, err := os.Stat(gitLeaksClonePath); os.IsNotExist(err) { - os.Mkdir(gitLeaksClonePath, os.ModePerm) - } - gitLeaksReportPath = filepath.Join(gitLeaksPath, "report") - if _, err := os.Stat(gitLeaksReportPath); os.IsNotExist(err) { - os.Mkdir(gitLeaksReportPath, os.ModePerm) } } func main() { - // TODO abstract logging - atom := zap.NewAtomicLevel() - encoderCfg := zap.NewProductionEncoderConfig() - encoderCfg.TimeKey = "" - logger = zap.New(zapcore.NewCore( - zapcore.NewJSONEncoder(encoderCfg), - zapcore.Lock(os.Stdout), - atom, - )) - logger.Info("HEY") - atom.SetLevel(zap.InfoLevel) - logger.Info("HEY") - - args := os.Args[1:] - opts := parseOptions(args) - owner := newOwner(opts) - owner.auditRepos(opts) - // repos := getRepos(opts, owner) - // start(repos, owner, opts) + opts = newOpts(args) + owner := newOwner() + os.Exit(owner.auditRepos()) } + +func failF(format string, args ...interface{}) { + fmt.Fprintf(os.Stderr, format, args...) + os.Exit(EXIT_FAILURE) +} + + diff --git a/options.go b/options.go index 7a4b7fa2..353d4630 100644 --- a/options.go +++ b/options.go @@ -4,52 +4,90 @@ import ( "fmt" "os" "strconv" + "strings" + "regexp" + "github.com/mitchellh/go-homedir" + "path/filepath" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" ) -const usage = `usage: gitleaks [options] +const DEBUG = 0 +const INFO = 1 +const ERROR = 2 + +const usage = `usage: gitleaks [options] / Options: - -c --concurrency Upper bound on concurrent diffs - -u --user Git user url - -r --repo Git repo url - -o --org Git organization url - -s --since Commit to stop at - -b --b64Entropy Base64 entropy cutoff (default is 70) - -x --hexEntropy Hex entropy cutoff (default is 40) +Modes + -u --user Git user mode + -r --repo Git repo mode + -o --org Git organization mode + -l --local Local mode, gitleaks will look for local repo in + +Logging + -ll --log= 0: Debug, 1: Info, 3: Error + -v --verbose Verbose mode, will output leaks as gitleaks finds them + +Locations + --report_path= Report output, default $GITLEAKS_HOME/report + --clone_path= Gitleaks will clone repos here, default $GITLEAKS_HOME/clones + +Other + -t --temp Clone to temporary directory + -c Upper bound on concurrent diffs + --since= Commit to stop at + --b64Entropy= Base64 entropy cutoff (default is 70) + --hexEntropy= Hex entropy cutoff (default is 40) -e --entropy Enable entropy - -j --json Output gitleaks report -h --help Display this message - --token Github API token - --strict Enables stopwords + --token= Github API token + --stopwords Enables stopwords + ` -// Options for gitleaks + +// Options for gitleaks. need to support remote repo/owner +// and local repo/owner mode type Options struct { + URL string + RepoPath string + + ClonePath string + ReportPath string + Concurrency int B64EntropyCutoff int HexEntropyCutoff int - UserURL string - OrgURL string - RepoURL string + + // MODES + UserMode bool + OrgMode bool + RepoMode bool + LocalMode bool + + // OPTS Strict bool Entropy bool SinceCommit string Persist bool IncludeForks bool Tmp bool - EnableJSON bool + ReportOut bool Token string + + // LOGS/REPORT Verbose bool + LogLevel int } // help prints the usage string and exits func help() { os.Stderr.WriteString(usage) - os.Exit(1) } // optionsNextInt is a parseOptions helper that returns the value (int) of an option if valid -func optionsNextInt(args []string, i *int) int { +func (opts *Options) nextInt(args []string, i *int) int { if len(args) > *i+1 { *i++ } else { @@ -57,30 +95,90 @@ func optionsNextInt(args []string, i *int) int { } argInt, err := strconv.Atoi(args[*i]) if err != nil { - fmt.Printf("Invalid %s option: %s\n", args[*i-1], args[*i]) - help() + opts.failF("Invalid %s option: %s\n", args[*i-1], args[*i]) } return argInt } // optionsNextString is a parseOptions helper that returns the value (string) of an option if valid -func optionsNextString(args []string, i *int) string { +func (opts *Options) nextString(args []string, i *int) string { if len(args) > *i+1 { *i++ } else { - fmt.Printf("Invalid %s option: %s\n", args[*i-1], args[*i]) - help() + opts.failF("Invalid %s option: %s\n", args[*i-1], args[*i]) } return args[*i] } -// parseOptions -func parseOptions(args []string) *Options { - opts := &Options{ +// optInt grabs the string ... +func (opts *Options) optString(arg string, prefixes ...string) (bool, string) { + for _, prefix := range prefixes { + if strings.HasPrefix(arg, prefix) { + return true, arg[len(prefix):] + } + } + return false, "" +} + +// optInt grabs the int ... +func (opts *Options) optInt(arg string, prefixes ...string) (bool, int) { + for _, prefix := range prefixes { + if strings.HasPrefix(arg, prefix) { + i, err := strconv.Atoi(arg[len(prefix):]) + if err != nil { + opts.failF("Invalid %s int option\n", prefix) + } + return true, i + } + } + return false, 0 +} + +// newOpts generates opts and parses arguments +func newOpts(args []string) (*Options) { + opts, err := defaultOptions() + if err != nil{ + opts.failF("%v", err) + } + err = opts.parseOptions(args) + if err != nil{ + opts.failF("%v", err) + } + opts.setupLogger() + return opts +} + +// deafultOptions provides the default options +func defaultOptions() (*Options, error) { + // default GITLEAKS_HOME is $HOME/.gitleaks + // gitleaks will use this location for clones if + // no clone-path is provided + gitleaksHome := os.Getenv("GITLEAKS_HOME") + if gitleaksHome == "" { + homeDir, err := homedir.Dir() + if err != nil { + return nil, fmt.Errorf("could not find system home dir") + } + gitleaksHome = filepath.Join(homeDir, ".gitleaks") + } + + // make sure gitleaks home exists + if _, err := os.Stat(gitleaksHome); os.IsNotExist(err) { + os.Mkdir(gitleaksHome, os.ModePerm) + } + + return &Options{ Concurrency: 10, B64EntropyCutoff: 70, HexEntropyCutoff: 40, - } + LogLevel: INFO, + ClonePath: filepath.Join(gitleaksHome, "clone"), + ReportPath: filepath.Join(gitleaksHome, "report"), + }, nil +} + +// parseOptions +func (opts *Options) parseOptions(args []string) error { if len(args) == 0 { help() @@ -89,48 +187,130 @@ func parseOptions(args []string) *Options { for i := 0; i < len(args); i++ { arg := args[i] switch arg { - case "-s", "--since": - opts.SinceCommit = optionsNextString(args, &i) + case "-s": + opts.SinceCommit = opts.nextString(args, &i) case "--strict": opts.Strict = true case "-b", "--b64Entropy": - opts.B64EntropyCutoff = optionsNextInt(args, &i) + opts.B64EntropyCutoff = opts.nextInt(args, &i) case "-x", "--hexEntropy": - opts.HexEntropyCutoff = optionsNextInt(args, &i) + opts.HexEntropyCutoff = opts.nextInt(args, &i) case "-e", "--entropy": opts.Entropy = true - case "-c", "--concurrency": - opts.Concurrency = optionsNextInt(args, &i) + case "-c": + opts.Concurrency = opts.nextInt(args, &i) + case "-o", "--org": - opts.OrgURL = optionsNextString(args, &i) + opts.OrgMode = true case "-u", "--user": - opts.UserURL = optionsNextString(args, &i) + opts.UserMode = true case "-r", "--repo": - opts.RepoURL = optionsNextString(args, &i) - case "-t", "--temporary": + opts.RepoMode = true + case "-l", "--local": + opts.LocalMode = true + + case "--report-out": + opts.ReportOut = true + + case "-t", "--temp": opts.Tmp = true - case "--token": - opts.Token = optionsNextString(args, &i) - case "-j", "--json": - opts.EnableJSON = true + case "-ll": + opts.LogLevel = opts.nextInt(args, &i) case "-h", "--help": help() - return nil + os.Exit(EXIT_CLEAN) default: - if i == len(args)-1 && opts.OrgURL == "" && opts.RepoURL == "" && - opts.UserURL == "" { - opts.RepoURL = arg + // TARGETS + if i == len(args)-1 { + fmt.Println(arg[i]) + if opts.LocalMode { + opts.RepoPath = args[i] + } else { + opts.URL = args[i] + } + } else if match, value := opts.optString(arg, "--token="); match { + opts.Token = value + } else if match, value := opts.optString(arg, "--since="); match { + opts.SinceCommit = value + } else if match, value := opts.optString(arg, "--report-path="); match { + opts.ReportPath = value + } else if match, value := opts.optString(arg, "--clone-path="); match { + opts.ClonePath = value + } else if match, value := opts.optInt(arg, "--log="); match { + opts.LogLevel = value + } else if match, value := opts.optInt(arg, "--b64Entropy="); match { + opts.B64EntropyCutoff = value + } else if match, value := opts.optInt(arg, "--hexEntropy="); match { + opts.HexEntropyCutoff = value } else { fmt.Printf("Unknown option %s\n\n", arg) help() + return fmt.Errorf("Unknown option %s\n\n", arg) } } } + err := opts.guards() + if err != nil{ + fmt.Printf("%v", err) + } + return err +} - // "guards" - if opts.Tmp && opts.EnableJSON { - fmt.Println("Report generation with temporary clones not supported") +// failF prints a failure message out to stderr, displays help +// and exits with a exit code 2 +func (opts *Options) failF(format string, args ...interface{}) { + fmt.Fprintf(os.Stderr, format, args...) + help() + os.Exit(EXIT_FAILURE) +} + +// guards will prevent gitleaks from continuing if any invalid options +// are found. +func (opts *Options) guards() error { + if (opts.RepoMode || opts.OrgMode || opts.UserMode) && !isGithubTarget(opts.URL) { + return fmt.Errorf("Not valid github target %s\n", opts.URL) + } else if (opts.RepoMode || opts.OrgMode || opts.UserMode) && opts.LocalMode { + return fmt.Errorf("Cannot run Gitleaks on repo/user/org mode and local mode\n") + } else if (opts.RepoMode || opts.UserMode) && opts.OrgMode { + return fmt.Errorf("Cannot run Gitleaks on more than one mode\n") + } else if (opts.OrgMode || opts.UserMode) && opts.RepoMode { + return fmt.Errorf("Cannot run Gitleaks on more than one mode\n") + } else if (opts.OrgMode || opts.RepoMode) && opts.UserMode{ + return fmt.Errorf("Cannot run Gitleaks on more than one mode\n") + } else if opts.LocalMode && opts.Tmp { + return fmt.Errorf("Cannot run Gitleaks with temp settings and local mode\n") + } else if opts.SinceCommit != "" && (opts.OrgMode || opts.UserMode) { + return fmt.Errorf("Cannot run Gitleaks with since commit flag and a owner mode\n") } - return opts + return nil +} + +// setupLogger initiates the logger and sets the logging level +// based on what is set in arguments. Default logging level is +// INFO +func (opts *Options) setupLogger() { + atom := zap.NewAtomicLevel() + encoderCfg := zap.NewProductionEncoderConfig() + encoderCfg.TimeKey = "" + logger = zap.New(zapcore.NewCore( + zapcore.NewJSONEncoder(encoderCfg), + zapcore.Lock(os.Stdout), + atom, + )) + + switch opts.LogLevel { + case DEBUG: + atom.SetLevel(zap.DebugLevel) + case INFO: + atom.SetLevel(zap.InfoLevel) + case ERROR: + atom.SetLevel(zap.ErrorLevel) + } +} + +// isGithubTarget checks if url is a valid github target +func isGithubTarget(url string) bool { + re := regexp.MustCompile("github\\.com\\/") + return re.MatchString(url) } diff --git a/owner.go b/owner.go index 1af6cc28..b7e80eab 100644 --- a/owner.go +++ b/owner.go @@ -1,18 +1,17 @@ package main import ( - "path" - "io/ioutil" - "path/filepath" - "os" - "github.com/google/go-github/github" - "strings" "context" + _ "fmt" + "github.com/google/go-github/github" "golang.org/x/oauth2" + "io/ioutil" "net/http" - "log" + "os" "os/signal" - _"fmt" + "path" + "strings" + "fmt" ) type Owner struct { @@ -21,21 +20,17 @@ type Owner struct { accountType string path string reportPath string - repos []Repo + repos []Repo } // newOwner instantiates an owner and creates any necessary resources for said owner. // newOwner returns a Owner struct pointer -func newOwner(opts *Options) *Owner { - name, err := ownerName(opts) +func newOwner() (*Owner) { + name := ownerName() owner := &Owner{ name: name, - url: opts.UserURL, - accountType: ownerType(opts), - } - - if err != nil { - owner.failf() + url: opts.URL, + accountType: ownerType(), } // listen for ctrl-c @@ -49,8 +44,23 @@ func newOwner(opts *Options) *Owner { owner.rmTmp() }() - owner.setupDir(opts) - owner.fetchRepos(opts) + + // if running on local repo, just go right to it. + if opts.LocalMode { + repo := newLocalRepo(opts.RepoPath) + owner.repos = append(owner.repos, *repo) + return owner + } + + err := owner.setupDir() + if err != nil { + owner.failF("%v", err) + } + + err = owner.fetchRepos() + if err != nil { + owner.failF("%v", err) + } return owner } @@ -58,16 +68,17 @@ func newOwner(opts *Options) *Owner { // of the owner's repos. If opts.RepoURL is not the empty string then fetchRepos will // only grab the repo specified in opts.RepoURL. Otherwise, fetchRepos will reach out to // github's api and grab all repos associated with owner. -func (owner *Owner) fetchRepos(opts *Options) { +func (owner *Owner) fetchRepos() error { + var err error ctx := context.Background() if owner.accountType == "" { // single repo, ambiguous account type - _, repoName := path.Split(opts.RepoURL) - repo := newRepo(owner, repoName, opts.RepoURL) + _, repoName := path.Split(opts.URL) + repo := newRepo(repoName, opts.URL) owner.repos = append(owner.repos, *repo) } else { // org or user account type, would fail if not valid before - tokenClient := githubTokenClient(opts) + tokenClient := githubTokenClient() gitClient := github.NewClient(tokenClient) if owner.accountType == "org" { @@ -75,26 +86,27 @@ func (owner *Owner) fetchRepos(opts *Options) { orgOpt := &github.RepositoryListByOrgOptions{ ListOptions: github.ListOptions{PerPage: 10}, } - owner.fetchOrgRepos(orgOpt, gitClient, ctx) + err = owner.fetchOrgRepos(orgOpt, gitClient, ctx) } else { // user account type userOpt := &github.RepositoryListOptions{ ListOptions: github.ListOptions{PerPage: 10}, } - owner.fetchUserRepos(userOpt, gitClient, ctx) + err = owner.fetchUserRepos(userOpt, gitClient, ctx) } } + return err } // fetchOrgRepos used by fetchRepos is responsible for parsing github's org repo response. If no // github token is available then fetchOrgRepos might run into a rate limit in which case owner will // log an error and gitleaks will exit. The rate limit for no token is 50 req/hour... not much. func (owner *Owner) fetchOrgRepos(orgOpts *github.RepositoryListByOrgOptions, gitClient *github.Client, - ctx context.Context) { + ctx context.Context) error { var ( - githubRepos []*github.Repository - resp *github.Response - err error + githubRepos []*github.Repository + resp *github.Response + err error ) for { @@ -102,16 +114,15 @@ func (owner *Owner) fetchOrgRepos(orgOpts *github.RepositoryListByOrgOptions, gi ctx, owner.name, orgOpts) owner.addRepos(githubRepos) if _, ok := err.(*github.RateLimitError); ok { - log.Println("hit rate limit") - break + logger.Info("hit rate limit") } else if err != nil { - log.Println("other error") - break + return fmt.Errorf("failed fetching org repos, bad request") } else if resp.NextPage == 0 { break } orgOpts.Page = resp.NextPage } + return nil } // fetchUserRepos used by fetchRepos is responsible for parsing github's user repo response. If no @@ -119,74 +130,79 @@ func (owner *Owner) fetchOrgRepos(orgOpts *github.RepositoryListByOrgOptions, gi // log an error and gitleaks will exit. The rate limit for no token is 50 req/hour... not much. // sorry for the redundancy func (owner *Owner) fetchUserRepos(userOpts *github.RepositoryListOptions, gitClient *github.Client, - ctx context.Context) { + ctx context.Context) error { var ( - githubRepos []*github.Repository - resp *github.Response - err error + githubRepos []*github.Repository + resp *github.Response + err error ) for { githubRepos, resp, err = gitClient.Repositories.List( ctx, owner.name, userOpts) owner.addRepos(githubRepos) if _, ok := err.(*github.RateLimitError); ok { - log.Println("hit rate limit") + logger.Info("hit rate limit") break } else if err != nil { - log.Println("other error") - break + return fmt.Errorf("failed fetching user repos, bad request") } else if resp.NextPage == 0 { break } userOpts.Page = resp.NextPage } + return nil } // addRepos used by fetchUserRepos and fetchOrgRepos appends new repos from // github's org/user response. -func (owner *Owner) addRepos (githubRepos []*github.Repository) { +func (owner *Owner) addRepos(githubRepos []*github.Repository) { for _, repo := range githubRepos { - owner.repos = append(owner.repos, *newRepo(owner, *repo.Name, *repo.CloneURL)) + owner.repos = append(owner.repos, *newRepo(*repo.Name, *repo.CloneURL)) } } // auditRepos -func (owner *Owner) auditRepos(opts *Options) { +func (owner *Owner) auditRepos() (int) { + exitCode := EXIT_CLEAN for _, repo := range owner.repos { - err := repo.audit(owner, opts) + leaksPst, err := repo.audit(owner) if err != nil { - owner.failf() + failF("%v\n", err) + } + if leaksPst{ + exitCode = EXIT_LEAKS } } + return exitCode } -// failf -func (owner *Owner) failf() { - // TODO -} - -// exitNow -func (owner *Owner) exitNow() { - +// failF prints a failure message out to stderr +// and exits with a exit code 2 +func (owner *Owner) failF(format string, args ...interface{}) { + fmt.Fprintf(os.Stderr, format, args...) + os.Exit(EXIT_FAILURE) } // setupDir sets up the owner's directory for clones and reports. // If the temporary option is set then a temporary directory will be // used for the owner repo clones. -func (owner *Owner) setupDir(opts *Options) { +func (owner *Owner) setupDir() error { if opts.Tmp { dir, err := ioutil.TempDir("", owner.name) if err != nil { - owner.failf() + return err + owner.failF("Unabled to create temp directories for cloning") } owner.path = dir } else { - owner.path = filepath.Join(gitLeaksClonePath, owner.name) - if _, err := os.Stat(owner.path); os.IsNotExist(err) { + if _, err := os.Stat(opts.ClonePath); os.IsNotExist(err) { os.Mkdir(owner.path, os.ModePerm) } } - owner.reportPath = filepath.Join(gitLeaksPath, "report", owner.name) + return nil + + // TODO could be handled via option + // owner.reportPath = filepath.Join(gitLeaksPath, "report", owner.name) } // rmTmp removes the temporary repo @@ -198,11 +214,10 @@ func (owner *Owner) rmTmp() { // ownerType returns the owner type extracted from opts. // If no owner type is provided, gitleaks assumes the owner is ambiguous // and the user is running gitleaks on a single repo -func ownerType(opts *Options) string { - if opts.OrgURL != "" { +func ownerType() string { + if opts.OrgMode { return "org" - - } else if opts.UserURL != "" { + } else if opts.UserMode { return "user" } return "" @@ -211,28 +226,24 @@ func ownerType(opts *Options) string { // ownerName returns the owner name extracted from the urls provided in opts. // If no RepoURL, OrgURL, or UserURL is provided, then owner will log an error // and gitleaks will exit. -func ownerName(opts *Options) (string, error) { - if opts.RepoURL != "" { - splitSlashes := strings.Split(opts.RepoURL, "/") - return splitSlashes[len(splitSlashes)-2], nil - } else if opts.UserURL != "" { - _, ownerName := path.Split(opts.UserURL) - return ownerName, nil - } else if opts.OrgURL != "" { - _, ownerName := path.Split(opts.OrgURL) - return ownerName, nil +func ownerName() (string) { + if opts.RepoMode { + splitSlashes := strings.Split(opts.URL, "/") + return splitSlashes[len(splitSlashes)-2] + } else if opts.UserMode|| opts.OrgMode { + _, ownerName := path.Split(opts.URL) + return ownerName } - - // TODO error - return "", nil + // local repo + return "" } // githubTokenClient creates an oauth client from your github access token. // Gitleaks will attempt to retrieve your github access token from a cli argument // or an env var - "GITHUB_TOKEN". -// Might be good to eventually parse the token from a config or creds file in +// Might be good to eventually parse the token from a Config or creds file in // $GITLEAKS_HOME -func githubTokenClient(opts *Options) *http.Client { +func githubTokenClient() *http.Client { var token string if opts.Token != "" { token = opts.Token diff --git a/repo.go b/repo.go index 8259e2a4..0e70f2e8 100644 --- a/repo.go +++ b/repo.go @@ -1,25 +1,24 @@ package main import ( - "path/filepath" - "os" - "fmt" - "os/exec" - "sync" "bytes" "encoding/json" - "log" - "strings" + "fmt" + "go.uber.org/zap" "io/ioutil" + "os" + "os/exec" + "path/filepath" + "sync" + "path" ) type Repo struct { - name string - url string - path string + name string + url string + path string status string // TODO leaks []Leak - owner *Owner } type Leak struct { @@ -41,13 +40,33 @@ type Commit struct { Msg string } -func newRepo(owner *Owner, name string, url string) *Repo { +// running gitleaks on local repo +func newLocalRepo(repoPath string) *Repo { + _, name := path.Split(repoPath) repo := &Repo{ name: name, - url: url, - path: owner.path + "/" + name, + path: repoPath, } return repo + +} + +func newRepo(name string, url string) *Repo { + repo := &Repo{ + name: name, + url: url, + // TODO handle existing one + path: opts.ClonePath + "/" + name, + } + return repo +} + +func (repo *Repo) rLog(msg string) { + // logger should have these infos: msg, repo, owner, time + logger.Debug("Beginning audit", + zap.String("repo", repo.name), + zap.String("repo_path", repo.path), + ) } // Audit operates on a single repo and searches the full or partial history of the repo. @@ -56,7 +75,7 @@ func newRepo(owner *Owner, name string, url string) *Repo { // commands so that users could opt for doing all clones/diffs in memory. // Audit also declares two WaitGroups, one for distributing regex/entropy checks, and one for receiving // the leaks if there are any. This could be done a little more elegantly in the future. -func (repo *Repo) audit(owner *Owner, opts *Options) error { +func (repo *Repo) audit(owner *Owner) (bool, error) { var ( out []byte err error @@ -65,6 +84,7 @@ func (repo *Repo) audit(owner *Owner, opts *Options) error { gitLeaksChan = make(chan Leak) leaks []Leak semaphoreChan = make(chan struct{}, opts.Concurrency) + leaksPst bool ) dotGitPath := filepath.Join(repo.path, ".git") @@ -72,22 +92,26 @@ func (repo *Repo) audit(owner *Owner, opts *Options) error { // Navigate to proper location to being audit. Clone repo // if not present, otherwise fetch for new changes. if _, err := os.Stat(dotGitPath); os.IsNotExist(err) { + if opts.LocalMode { + return false, fmt.Errorf("%s does not exist", repo.path) + } // no repo present, clone it fmt.Printf("Cloning \x1b[37;1m%s\x1b[0m into %s...\n", repo.url, repo.path) err = exec.Command("git", "clone", repo.url, repo.path).Run() - if err != nil{ - fmt.Println("can run clonse") + if err != nil { + return false, fmt.Errorf("cannot clone %s into %s", repo.url, repo.path) } } else { fmt.Printf("Checking \x1b[37;1m%s\x1b[0m from %s...\n", repo.url, repo.path) err = exec.Command("git", "fetch").Run() - if err != nil{ - fmt.Println("can run fetch") + if err != nil { + return false, fmt.Errorf("cannot fetch %s from %s", repo.url, repo.path) } } - if err := os.Chdir(fmt.Sprintf(repo.path)); err != nil { - fmt.Println("cant chdir") + err = os.Chdir(fmt.Sprintf(repo.path)) + if err != nil { + return false, fmt.Errorf("cannot navigate to %s", repo.path) } gitFormat := "--format=%H%n%an%n%s%n%ci" @@ -95,7 +119,7 @@ func (repo *Repo) audit(owner *Owner, opts *Options) error { "--remotes", "--topo-order", gitFormat).Output() if err != nil { - fmt.Println("problem with rev list") + return false, fmt.Errorf("could not retreive rev-list from %s", repo.name) } revListLines := bytes.Split(out, []byte("\n")) @@ -107,7 +131,7 @@ func (repo *Repo) audit(owner *Owner, opts *Options) error { } commitWG.Add(1) - go auditDiff(commit, repo, &commitWG, &gitLeakReceiverWG, opts, + go auditDiff(commit, repo, &commitWG, &gitLeakReceiverWG, semaphoreChan, gitLeaksChan) if commit.Hash == opts.SinceCommit { @@ -117,37 +141,37 @@ func (repo *Repo) audit(owner *Owner, opts *Options) error { go reportAggregator(&gitLeakReceiverWG, gitLeaksChan, &leaks) commitWG.Wait() gitLeakReceiverWG.Wait() - - // repo audit has finished - repo.leaks = leaks - - if opts.EnableJSON && len(leaks) != 0 { - repo.writeReport(owner) + if len(leaks) != 0{ + leaksPst = true } - return nil -} - -func (repo *Repo) log() { - + if opts.ReportPath != "" && len(leaks) != 0 { + err = repo.writeReport() + if err != nil { + return leaksPst, fmt.Errorf("could not write report to %s", opts.ReportPath) + } + } + return leaksPst, nil } // Used by audit, writeReport will generate a report and write it out to // $GITLEAKS_HOME/report//. No report will be generated if // no leaks have been found -func (repo *Repo) writeReport(owner *Owner) { +func (repo *Repo) writeReport() error { reportJSON, _ := json.MarshalIndent(repo.leaks, "", "\t") - if _, err := os.Stat(owner.reportPath); os.IsNotExist(err) { - os.Mkdir(repo.owner.reportPath, os.ModePerm) + + if _, err := os.Stat(opts.ReportPath); os.IsNotExist(err) { + os.Mkdir(opts.ReportPath, os.ModePerm) } reportFileName := fmt.Sprintf("%s_leaks.json", repo.name) - reportFile := filepath.Join(owner.reportPath, reportFileName) + reportFile := filepath.Join(opts.ReportPath, reportFileName) err := ioutil.WriteFile(reportFile, reportJSON, 0644) if err != nil { - fmt.Println("cant write report") + return err } fmt.Printf("Report written to %s\n", reportFile) + return nil } // parseRevList is responsible for parsing the output of @@ -179,6 +203,7 @@ func reportAggregator(gitLeakReceiverWG *sync.WaitGroup, gitLeaks chan Leak, lea for gitLeak := range gitLeaks { b, err := json.MarshalIndent(gitLeak, "", " ") if err != nil { + // make waitgroup errArray fmt.Println("failed to output leak:", err) } fmt.Println(string(b)) @@ -191,13 +216,14 @@ func reportAggregator(gitLeakReceiverWG *sync.WaitGroup, gitLeaks chan Leak, lea // Three channels are input here: 1. a semaphore to bind gitleaks, 2. a leak stream, 3. error handling (TODO) // This func performs a diff and runs regexes checks on each line of the diff. func auditDiff(currCommit Commit, repo *Repo, commitWG *sync.WaitGroup, - gitLeakReceiverWG *sync.WaitGroup, opts *Options, semaphoreChan chan struct{}, + gitLeakReceiverWG *sync.WaitGroup, semaphoreChan chan struct{}, gitLeaks chan Leak) { // signal to WG this diff is done being audited defer commitWG.Done() if err := os.Chdir(fmt.Sprintf(repo.path)); err != nil { - log.Fatal(err) + // TODO handle this better + os.Exit(EXIT_FAILURE) } commitCmp := fmt.Sprintf("%s^!", currCommit.Hash) @@ -206,13 +232,10 @@ func auditDiff(currCommit Commit, repo *Repo, commitWG *sync.WaitGroup, <-semaphoreChan if err != nil { - // TODO - if strings.Contains(err.Error(), "too many files open") { - log.Printf("error retrieving diff for commit %s. Try turning concurrency down. %v\n", currCommit, err) - } + os.Exit(EXIT_FAILURE) } - leaks := doChecks(string(out), currCommit, opts, repo) + leaks := doChecks(string(out), currCommit, repo) if len(leaks) == 0 { return } @@ -221,4 +244,3 @@ func auditDiff(currCommit Commit, repo *Repo, commitWG *sync.WaitGroup, gitLeaks <- leak } } - From 0d75136c1c266710de798c99f95cd4225b4e4e25 Mon Sep 17 00:00:00 2001 From: zricethezav Date: Wed, 28 Feb 2018 22:02:03 -0600 Subject: [PATCH 03/16] structured logs --- main.go | 6 ++--- options.go | 72 +++++++++++++++++++++++++++++------------------------- owner.go | 21 ++++++---------- repo.go | 55 ++++++++++++++++++++++++++++------------- 4 files changed, 87 insertions(+), 67 deletions(-) diff --git a/main.go b/main.go index ad8aa84f..02480510 100644 --- a/main.go +++ b/main.go @@ -1,13 +1,13 @@ package main import ( + "fmt" _ "fmt" "go.uber.org/zap" _ "io/ioutil" "os" "regexp" _ "time" - "fmt" ) const EXIT_CLEAN = 0 @@ -23,7 +23,7 @@ var ( assignRegex *regexp.Regexp fileDiffRegex *regexp.Regexp logger *zap.Logger - opts *Options + opts *Options ) func init() { @@ -58,5 +58,3 @@ func failF(format string, args ...interface{}) { fmt.Fprintf(os.Stderr, format, args...) os.Exit(EXIT_FAILURE) } - - diff --git a/options.go b/options.go index 353d4630..b9d03be2 100644 --- a/options.go +++ b/options.go @@ -2,14 +2,14 @@ package main import ( "fmt" - "os" - "strconv" - "strings" - "regexp" "github.com/mitchellh/go-homedir" - "path/filepath" "go.uber.org/zap" "go.uber.org/zap/zapcore" + "os" + "path/filepath" + "regexp" + "strconv" + "strings" ) const DEBUG = 0 @@ -43,42 +43,42 @@ Other -h --help Display this message --token= Github API token --stopwords Enables stopwords + --pretty Enables pretty printing for humans, otherwise you'll get logs' ` - // Options for gitleaks. need to support remote repo/owner // and local repo/owner mode type Options struct { - URL string - RepoPath string + URL string + RepoPath string - ClonePath string - ReportPath string + ClonePath string + ReportPath string Concurrency int B64EntropyCutoff int HexEntropyCutoff int // MODES - UserMode bool - OrgMode bool - RepoMode bool - LocalMode bool + UserMode bool + OrgMode bool + RepoMode bool + LocalMode bool // OPTS - Strict bool - Entropy bool - SinceCommit string - Persist bool - IncludeForks bool - Tmp bool - ReportOut bool - Token string + Strict bool + Entropy bool + SinceCommit string + Persist bool + IncludeForks bool + Tmp bool + ReportOut bool + Token string // LOGS/REPORT - Verbose bool - LogLevel int + LogLevel int + PrettyPrint bool } // help prints the usage string and exits @@ -135,13 +135,13 @@ func (opts *Options) optInt(arg string, prefixes ...string) (bool, int) { } // newOpts generates opts and parses arguments -func newOpts(args []string) (*Options) { +func newOpts(args []string) *Options { opts, err := defaultOptions() - if err != nil{ + if err != nil { opts.failF("%v", err) } err = opts.parseOptions(args) - if err != nil{ + if err != nil { opts.failF("%v", err) } opts.setupLogger() @@ -171,9 +171,9 @@ func defaultOptions() (*Options, error) { Concurrency: 10, B64EntropyCutoff: 70, HexEntropyCutoff: 40, - LogLevel: INFO, - ClonePath: filepath.Join(gitleaksHome, "clone"), - ReportPath: filepath.Join(gitleaksHome, "report"), + LogLevel: INFO, + ClonePath: filepath.Join(gitleaksHome, "clone"), + ReportPath: filepath.Join(gitleaksHome, "report"), }, nil } @@ -211,6 +211,8 @@ func (opts *Options) parseOptions(args []string) error { case "--report-out": opts.ReportOut = true + case "--pretty": + opts.PrettyPrint = true case "-t", "--temp": opts.Tmp = true @@ -222,7 +224,6 @@ func (opts *Options) parseOptions(args []string) error { default: // TARGETS if i == len(args)-1 { - fmt.Println(arg[i]) if opts.LocalMode { opts.RepoPath = args[i] } else { @@ -250,7 +251,7 @@ func (opts *Options) parseOptions(args []string) error { } } err := opts.guards() - if err != nil{ + if err != nil { fmt.Printf("%v", err) } return err @@ -275,7 +276,7 @@ func (opts *Options) guards() error { return fmt.Errorf("Cannot run Gitleaks on more than one mode\n") } else if (opts.OrgMode || opts.UserMode) && opts.RepoMode { return fmt.Errorf("Cannot run Gitleaks on more than one mode\n") - } else if (opts.OrgMode || opts.RepoMode) && opts.UserMode{ + } else if (opts.OrgMode || opts.RepoMode) && opts.UserMode { return fmt.Errorf("Cannot run Gitleaks on more than one mode\n") } else if opts.LocalMode && opts.Tmp { return fmt.Errorf("Cannot run Gitleaks with temp settings and local mode\n") @@ -307,6 +308,11 @@ func (opts *Options) setupLogger() { case ERROR: atom.SetLevel(zap.ErrorLevel) } + + // set to ErrorLevel if pretty printing + if opts.PrettyPrint{ + atom.SetLevel(zap.ErrorLevel) + } } // isGithubTarget checks if url is a valid github target diff --git a/owner.go b/owner.go index b7e80eab..b62b69ab 100644 --- a/owner.go +++ b/owner.go @@ -2,6 +2,7 @@ package main import ( "context" + "fmt" _ "fmt" "github.com/google/go-github/github" "golang.org/x/oauth2" @@ -11,7 +12,6 @@ import ( "os/signal" "path" "strings" - "fmt" ) type Owner struct { @@ -25,8 +25,8 @@ type Owner struct { // newOwner instantiates an owner and creates any necessary resources for said owner. // newOwner returns a Owner struct pointer -func newOwner() (*Owner) { - name := ownerName() +func newOwner() *Owner { + name := ownerName() owner := &Owner{ name: name, url: opts.URL, @@ -44,7 +44,6 @@ func newOwner() (*Owner) { owner.rmTmp() }() - // if running on local repo, just go right to it. if opts.LocalMode { repo := newLocalRepo(opts.RepoPath) @@ -162,14 +161,14 @@ func (owner *Owner) addRepos(githubRepos []*github.Repository) { } // auditRepos -func (owner *Owner) auditRepos() (int) { +func (owner *Owner) auditRepos() int { exitCode := EXIT_CLEAN for _, repo := range owner.repos { leaksPst, err := repo.audit(owner) if err != nil { failF("%v\n", err) } - if leaksPst{ + if leaksPst { exitCode = EXIT_LEAKS } } @@ -190,8 +189,7 @@ func (owner *Owner) setupDir() error { if opts.Tmp { dir, err := ioutil.TempDir("", owner.name) if err != nil { - return err - owner.failF("Unabled to create temp directories for cloning") + fmt.Errorf("unable to create temp directories for cloning") } owner.path = dir } else { @@ -200,9 +198,6 @@ func (owner *Owner) setupDir() error { } } return nil - - // TODO could be handled via option - // owner.reportPath = filepath.Join(gitLeaksPath, "report", owner.name) } // rmTmp removes the temporary repo @@ -226,11 +221,11 @@ func ownerType() string { // ownerName returns the owner name extracted from the urls provided in opts. // If no RepoURL, OrgURL, or UserURL is provided, then owner will log an error // and gitleaks will exit. -func ownerName() (string) { +func ownerName() string { if opts.RepoMode { splitSlashes := strings.Split(opts.URL, "/") return splitSlashes[len(splitSlashes)-2] - } else if opts.UserMode|| opts.OrgMode { + } else if opts.UserMode || opts.OrgMode { _, ownerName := path.Split(opts.URL) return ownerName } diff --git a/repo.go b/repo.go index 0e70f2e8..6235adc6 100644 --- a/repo.go +++ b/repo.go @@ -8,9 +8,9 @@ import ( "io/ioutil" "os" "os/exec" + "path" "path/filepath" "sync" - "path" ) type Repo struct { @@ -53,22 +53,28 @@ func newLocalRepo(repoPath string) *Repo { func newRepo(name string, url string) *Repo { repo := &Repo{ - name: name, - url: url, + name: name, + url: url, // TODO handle existing one - path: opts.ClonePath + "/" + name, + path: opts.ClonePath + "/" + name, } return repo } -func (repo *Repo) rLog(msg string) { +func (repo *Repo) Info(msg string) { // logger should have these infos: msg, repo, owner, time - logger.Debug("Beginning audit", + logger.Info(msg, zap.String("repo", repo.name), zap.String("repo_path", repo.path), ) } +func (repo *Repo) PrettyPrintF(format string, args ...interface{}) { + if opts.PrettyPrint { + fmt.Fprintf(os.Stderr, format, args...) + } +} + // Audit operates on a single repo and searches the full or partial history of the repo. // A semaphore is declared for every repo to bind concurrency. If unbounded, the system will throw a // `too many open files` error. Eventually, gitleaks should use src-d/go-git to avoid shelling out @@ -84,7 +90,7 @@ func (repo *Repo) audit(owner *Owner) (bool, error) { gitLeaksChan = make(chan Leak) leaks []Leak semaphoreChan = make(chan struct{}, opts.Concurrency) - leaksPst bool + leaksPst bool ) dotGitPath := filepath.Join(repo.path, ".git") @@ -96,13 +102,15 @@ func (repo *Repo) audit(owner *Owner) (bool, error) { return false, fmt.Errorf("%s does not exist", repo.path) } // no repo present, clone it - fmt.Printf("Cloning \x1b[37;1m%s\x1b[0m into %s...\n", repo.url, repo.path) + repo.Info("cloning") + repo.PrettyPrintF("Cloning \x1b[37;1m%s\x1b[0m...\n", repo.url) err = exec.Command("git", "clone", repo.url, repo.path).Run() if err != nil { return false, fmt.Errorf("cannot clone %s into %s", repo.url, repo.path) } } else { - fmt.Printf("Checking \x1b[37;1m%s\x1b[0m from %s...\n", repo.url, repo.path) + repo.Info("fetching") + repo.PrettyPrintF("Fetching \x1b[37;1m%s\x1b[0m...\n", repo.url) err = exec.Command("git", "fetch").Run() if err != nil { return false, fmt.Errorf("cannot fetch %s from %s", repo.url, repo.path) @@ -141,7 +149,7 @@ func (repo *Repo) audit(owner *Owner) (bool, error) { go reportAggregator(&gitLeakReceiverWG, gitLeaksChan, &leaks) commitWG.Wait() gitLeakReceiverWG.Wait() - if len(leaks) != 0{ + if len(leaks) != 0 { leaksPst = true } @@ -170,7 +178,7 @@ func (repo *Repo) writeReport() error { if err != nil { return err } - fmt.Printf("Report written to %s\n", reportFile) + repo.Info(fmt.Sprintf("Report written to %s\n", reportFile)) return nil } @@ -201,13 +209,26 @@ func parseRevList(revList [][]byte) []Commit { // reportAggregator is a go func responsible for ... func reportAggregator(gitLeakReceiverWG *sync.WaitGroup, gitLeaks chan Leak, leaks *[]Leak) { for gitLeak := range gitLeaks { - b, err := json.MarshalIndent(gitLeak, "", " ") - if err != nil { - // make waitgroup errArray - fmt.Println("failed to output leak:", err) - } - fmt.Println(string(b)) + logger.Info("leak", + zap.String("line", gitLeak.Line), + zap.String("commit", gitLeak.Commit), + zap.String("offender", gitLeak.Offender), + zap.String("Reason", gitLeak.Reason), + zap.String("author", gitLeak.Author), + zap.String("file", gitLeak.File), + zap.String("repoURL", gitLeak.RepoURL), + zap.String("timeOfCommit", gitLeak.Time), + ) *leaks = append(*leaks, gitLeak) + if opts.PrettyPrint { + b, err := json.MarshalIndent(gitLeak, "", " ") + if err != nil { + // handle this? + fmt.Println("failed to output leak:", err) + } + fmt.Println(string(b)) + } + gitLeakReceiverWG.Done() } } From 25736d115fcd0c66fda47257ecb185bf951c0124 Mon Sep 17 00:00:00 2001 From: zricethezav Date: Wed, 28 Feb 2018 23:25:04 -0600 Subject: [PATCH 04/16] some barebones tests --- checks_test.go | 4 ++-- options.go | 2 +- repo.go | 1 - 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/checks_test.go b/checks_test.go index 89a377de..56cb8cdf 100644 --- a/checks_test.go +++ b/checks_test.go @@ -6,7 +6,7 @@ import ( func TestCheckRegex(t *testing.T) { var results []Leak - opts := &Options{ + opts = &Options{ Concurrency: 10, B64EntropyCutoff: 70, HexEntropyCutoff: 40, @@ -22,7 +22,7 @@ func TestCheckRegex(t *testing.T) { } for k, v := range checks { - results = doChecks(k, commit, opts, repo) + results = doChecks(k, commit, &repo) if v != len(results) { t.Errorf("regexCheck failed on string %s", k) } diff --git a/options.go b/options.go index b9d03be2..9063c79d 100644 --- a/options.go +++ b/options.go @@ -317,6 +317,6 @@ func (opts *Options) setupLogger() { // isGithubTarget checks if url is a valid github target func isGithubTarget(url string) bool { - re := regexp.MustCompile("github\\.com\\/") + re := regexp.MustCompile("github.com") return re.MatchString(url) } diff --git a/repo.go b/repo.go index 6235adc6..f378d2dc 100644 --- a/repo.go +++ b/repo.go @@ -228,7 +228,6 @@ func reportAggregator(gitLeakReceiverWG *sync.WaitGroup, gitLeaks chan Leak, lea } fmt.Println(string(b)) } - gitLeakReceiverWG.Done() } } From 9dd624affac83c0b84278556a7c135cf17b17dc6 Mon Sep 17 00:00:00 2001 From: zricethezav Date: Thu, 1 Mar 2018 00:01:13 -0600 Subject: [PATCH 05/16] options and repo testing --- options_test.go | 89 +++++++++++++++++++++++++++++++++++++++++++++++++ repo_test.go | 29 ++++++++++++++++ 2 files changed, 118 insertions(+) create mode 100644 options_test.go create mode 100644 repo_test.go diff --git a/options_test.go b/options_test.go new file mode 100644 index 00000000..103c180c --- /dev/null +++ b/options_test.go @@ -0,0 +1,89 @@ +package main + +import ( + "testing" +) + +func TestNextInt(t *testing.T) { + args := []string{"-c", "10"} + i := 0 + opts, err := defaultOptions() + if err != nil { + t.Error() + } + n := opts.nextInt(args, &i) + if n != 10 { + t.Error() + } +} + +func TestNextString(t *testing.T) { + args := []string{"--fake", "flag"} + i := 0 + opts, err := defaultOptions() + if err != nil { + t.Error() + } + n := opts.nextString(args, &i) + if n != "flag" { + t.Error() + } +} + +func TestOptString(t *testing.T) { + opts, err := defaultOptions() + if err != nil { + t.Error() + } + match, n := opts.optString("--fake=flag", "--fake=") + if !match || n != "flag" { + t.Error() + } +} + +func TestOptInt(t *testing.T) { + opts, err := defaultOptions() + if err != nil { + t.Error() + } + match, n := opts.optInt("--fake=10", "--fake=") + if !match || n != 10 { + t.Error() + } +} + +func TestParseOptions(t *testing.T) { + opts, err := defaultOptions() + opts.URL = "github.com/sample" + if err != nil { + t.Error() + } + opts.RepoMode = false + opts.UserMode = true + opts.LocalMode = true + err = opts.guards() + if err == nil { + t.Error() + } + + opts.RepoMode = true + opts.UserMode = false + opts.LocalMode = false + err = opts.guards() + if err != nil { + t.Error() + } +} + +func TestGithubTarget(t *testing.T) { + if !isGithubTarget("github.com"){ + t.Error() + } + if !isGithubTarget("https://github.com/"){ + t.Error() + } + if !isGithubTarget("git@github.com:zricethezav/gitleaks.git"){ + t.Error() + } + +} diff --git a/repo_test.go b/repo_test.go new file mode 100644 index 00000000..909eb261 --- /dev/null +++ b/repo_test.go @@ -0,0 +1,29 @@ +package main + +import "testing" + +func TestNewRepo(t *testing.T) { + // TODO +} + +func TestNewLocalRepo(t *testing.T) { + // TODO +} + +func TestWriteReport(t *testing.T) { + // TODO + opts, err := defaultOptions() + r := newRepo("fakerepo", "github.com") + sampleLeak := Leak{ + Line: "yoo", + Commit: "mycommit", + Offender: "oh boy", + Reason: "hello", + Msg: "msg", + Time: "time", + Author: "lol", + RepoURL: "yooo", + } + r.leaks = []Leak{sampleLeak, sampleLeak} + r.writeReport() +} From 39c9cb617cfe35947bdc09a4f01ef7c66848a4ec Mon Sep 17 00:00:00 2001 From: zricethezav Date: Thu, 1 Mar 2018 19:08:58 -0600 Subject: [PATCH 06/16] cleaning up path logic for clones and reports, local repos are supported now --- main.go | 2 -- options.go | 58 ++++++++-------------------------------------------- owner.go | 50 +++++++++++++++++++++++++++++++++++++------- repo.go | 46 ++++++++++------------------------------- repo_test.go | 2 ++ 5 files changed, 65 insertions(+), 93 deletions(-) diff --git a/main.go b/main.go index 02480510..7ca5e0c0 100644 --- a/main.go +++ b/main.go @@ -3,7 +3,6 @@ package main import ( "fmt" _ "fmt" - "go.uber.org/zap" _ "io/ioutil" "os" "regexp" @@ -22,7 +21,6 @@ var ( hexChars string assignRegex *regexp.Regexp fileDiffRegex *regexp.Regexp - logger *zap.Logger opts *Options ) diff --git a/options.go b/options.go index 9063c79d..8975872e 100644 --- a/options.go +++ b/options.go @@ -2,20 +2,13 @@ package main import ( "fmt" - "github.com/mitchellh/go-homedir" - "go.uber.org/zap" - "go.uber.org/zap/zapcore" "os" - "path/filepath" "regexp" "strconv" "strings" + "path/filepath" ) -const DEBUG = 0 -const INFO = 1 -const ERROR = 2 - const usage = `usage: gitleaks [options] / Options: @@ -53,7 +46,6 @@ type Options struct { URL string RepoPath string - ClonePath string ReportPath string Concurrency int @@ -144,12 +136,12 @@ func newOpts(args []string) *Options { if err != nil { opts.failF("%v", err) } - opts.setupLogger() return opts } // deafultOptions provides the default options func defaultOptions() (*Options, error) { + /* // default GITLEAKS_HOME is $HOME/.gitleaks // gitleaks will use this location for clones if // no clone-path is provided @@ -166,14 +158,12 @@ func defaultOptions() (*Options, error) { if _, err := os.Stat(gitleaksHome); os.IsNotExist(err) { os.Mkdir(gitleaksHome, os.ModePerm) } + */ return &Options{ Concurrency: 10, B64EntropyCutoff: 70, HexEntropyCutoff: 40, - LogLevel: INFO, - ClonePath: filepath.Join(gitleaksHome, "clone"), - ReportPath: filepath.Join(gitleaksHome, "report"), }, nil } @@ -225,7 +215,7 @@ func (opts *Options) parseOptions(args []string) error { // TARGETS if i == len(args)-1 { if opts.LocalMode { - opts.RepoPath = args[i] + opts.RepoPath = filepath.Clean(args[i]) } else { opts.URL = args[i] } @@ -235,8 +225,6 @@ func (opts *Options) parseOptions(args []string) error { opts.SinceCommit = value } else if match, value := opts.optString(arg, "--report-path="); match { opts.ReportPath = value - } else if match, value := opts.optString(arg, "--clone-path="); match { - opts.ClonePath = value } else if match, value := opts.optInt(arg, "--log="); match { opts.LogLevel = value } else if match, value := opts.optInt(arg, "--b64Entropy="); match { @@ -251,8 +239,8 @@ func (opts *Options) parseOptions(args []string) error { } } err := opts.guards() - if err != nil { - fmt.Printf("%v", err) + if !opts.RepoMode && !opts.UserMode && !opts.OrgMode && !opts.LocalMode { + opts.RepoMode = true } return err } @@ -268,10 +256,10 @@ func (opts *Options) failF(format string, args ...interface{}) { // guards will prevent gitleaks from continuing if any invalid options // are found. func (opts *Options) guards() error { - if (opts.RepoMode || opts.OrgMode || opts.UserMode) && !isGithubTarget(opts.URL) { - return fmt.Errorf("Not valid github target %s\n", opts.URL) - } else if (opts.RepoMode || opts.OrgMode || opts.UserMode) && opts.LocalMode { + if (opts.RepoMode || opts.OrgMode || opts.UserMode) && opts.LocalMode { return fmt.Errorf("Cannot run Gitleaks on repo/user/org mode and local mode\n") + } else if (opts.RepoMode || opts.OrgMode || opts.UserMode) && !isGithubTarget(opts.URL) { + return fmt.Errorf("Not valid github target %s\n", opts.URL) } else if (opts.RepoMode || opts.UserMode) && opts.OrgMode { return fmt.Errorf("Cannot run Gitleaks on more than one mode\n") } else if (opts.OrgMode || opts.UserMode) && opts.RepoMode { @@ -287,34 +275,6 @@ func (opts *Options) guards() error { return nil } -// setupLogger initiates the logger and sets the logging level -// based on what is set in arguments. Default logging level is -// INFO -func (opts *Options) setupLogger() { - atom := zap.NewAtomicLevel() - encoderCfg := zap.NewProductionEncoderConfig() - encoderCfg.TimeKey = "" - logger = zap.New(zapcore.NewCore( - zapcore.NewJSONEncoder(encoderCfg), - zapcore.Lock(os.Stdout), - atom, - )) - - switch opts.LogLevel { - case DEBUG: - atom.SetLevel(zap.DebugLevel) - case INFO: - atom.SetLevel(zap.InfoLevel) - case ERROR: - atom.SetLevel(zap.ErrorLevel) - } - - // set to ErrorLevel if pretty printing - if opts.PrettyPrint{ - atom.SetLevel(zap.ErrorLevel) - } -} - // isGithubTarget checks if url is a valid github target func isGithubTarget(url string) bool { re := regexp.MustCompile("github.com") diff --git a/owner.go b/owner.go index b62b69ab..dff4dbe5 100644 --- a/owner.go +++ b/owner.go @@ -12,6 +12,9 @@ import ( "os/signal" "path" "strings" + "github.com/mitchellh/go-homedir" + "path/filepath" + "log" ) type Owner struct { @@ -23,14 +26,42 @@ type Owner struct { repos []Repo } +func ownerPath(ownerName string) (string, error){ + if opts.Tmp { + fmt.Println("creating tmp") + dir, err := ioutil.TempDir("", ownerName) + return dir, err + } + + gitleaksHome := os.Getenv("GITLEAKS_HOME") + if gitleaksHome == "" { + homeDir, err := homedir.Dir() + if err != nil { + return "", fmt.Errorf("could not find system home dir") + } + gitleaksHome = filepath.Join(homeDir, ".gitleaks") + } + + // make sure gitleaks home exists + if _, err := os.Stat(gitleaksHome); os.IsNotExist(err) { + os.Mkdir(gitleaksHome, os.ModePerm) + } + return gitleaksHome + "/" + ownerName, nil +} + // newOwner instantiates an owner and creates any necessary resources for said owner. // newOwner returns a Owner struct pointer func newOwner() *Owner { name := ownerName() + ownerPath, err := ownerPath(name) + if err != nil{ + failF("%v", err) + } owner := &Owner{ name: name, url: opts.URL, accountType: ownerType(), + path: ownerPath, } // listen for ctrl-c @@ -51,11 +82,11 @@ func newOwner() *Owner { return owner } + /* err := owner.setupDir() if err != nil { owner.failF("%v", err) - } - + }*/ err = owner.fetchRepos() if err != nil { owner.failF("%v", err) @@ -73,7 +104,7 @@ func (owner *Owner) fetchRepos() error { if owner.accountType == "" { // single repo, ambiguous account type _, repoName := path.Split(opts.URL) - repo := newRepo(repoName, opts.URL) + repo := newRepo(repoName, opts.URL, owner.path + "/" + repoName) owner.repos = append(owner.repos, *repo) } else { // org or user account type, would fail if not valid before @@ -113,7 +144,7 @@ func (owner *Owner) fetchOrgRepos(orgOpts *github.RepositoryListByOrgOptions, gi ctx, owner.name, orgOpts) owner.addRepos(githubRepos) if _, ok := err.(*github.RateLimitError); ok { - logger.Info("hit rate limit") + fmt.Println("Hit rate limit") } else if err != nil { return fmt.Errorf("failed fetching org repos, bad request") } else if resp.NextPage == 0 { @@ -140,7 +171,7 @@ func (owner *Owner) fetchUserRepos(userOpts *github.RepositoryListOptions, gitCl ctx, owner.name, userOpts) owner.addRepos(githubRepos) if _, ok := err.(*github.RateLimitError); ok { - logger.Info("hit rate limit") + fmt.Println("Hit rate limit") break } else if err != nil { return fmt.Errorf("failed fetching user repos, bad request") @@ -156,7 +187,7 @@ func (owner *Owner) fetchUserRepos(userOpts *github.RepositoryListOptions, gitCl // github's org/user response. func (owner *Owner) addRepos(githubRepos []*github.Repository) { for _, repo := range githubRepos { - owner.repos = append(owner.repos, *newRepo(*repo.Name, *repo.CloneURL)) + owner.repos = append(owner.repos, *newRepo(*repo.Name, *repo.CloneURL, owner.path + "/" + *repo.Name)) } } @@ -169,7 +200,10 @@ func (owner *Owner) auditRepos() int { failF("%v\n", err) } if leaksPst { + log.Printf("\x1b[31;2mLEAKS DETECTED for %s\x1b[0m!\n", repo.name) exitCode = EXIT_LEAKS + } else { + log.Printf("No Leaks detected for \x1b[32;2m%s\x1b[0m\n", repo.name) } } return exitCode @@ -187,13 +221,14 @@ func (owner *Owner) failF(format string, args ...interface{}) { // used for the owner repo clones. func (owner *Owner) setupDir() error { if opts.Tmp { + fmt.Println("creating tmp") dir, err := ioutil.TempDir("", owner.name) if err != nil { fmt.Errorf("unable to create temp directories for cloning") } owner.path = dir } else { - if _, err := os.Stat(opts.ClonePath); os.IsNotExist(err) { + if _, err := os.Stat(owner.path); os.IsNotExist(err) { os.Mkdir(owner.path, os.ModePerm) } } @@ -202,6 +237,7 @@ func (owner *Owner) setupDir() error { // rmTmp removes the temporary repo func (owner *Owner) rmTmp() { + log.Printf("removing tmp gitleaks repo for %s\n", owner.name) os.RemoveAll(owner.path) os.Exit(EXIT_FAILURE) } diff --git a/repo.go b/repo.go index f378d2dc..ec45a2c9 100644 --- a/repo.go +++ b/repo.go @@ -4,13 +4,13 @@ import ( "bytes" "encoding/json" "fmt" - "go.uber.org/zap" "io/ioutil" "os" "os/exec" "path" "path/filepath" "sync" + "log" ) type Repo struct { @@ -19,6 +19,7 @@ type Repo struct { path string status string // TODO leaks []Leak + reportPath string } type Leak struct { @@ -46,35 +47,23 @@ func newLocalRepo(repoPath string) *Repo { repo := &Repo{ name: name, path: repoPath, + reportPath: opts.ReportPath, } return repo } -func newRepo(name string, url string) *Repo { +func newRepo(name string, url string, path string) *Repo { repo := &Repo{ name: name, url: url, // TODO handle existing one - path: opts.ClonePath + "/" + name, + path: path, + reportPath: opts.ReportPath, } return repo } -func (repo *Repo) Info(msg string) { - // logger should have these infos: msg, repo, owner, time - logger.Info(msg, - zap.String("repo", repo.name), - zap.String("repo_path", repo.path), - ) -} - -func (repo *Repo) PrettyPrintF(format string, args ...interface{}) { - if opts.PrettyPrint { - fmt.Fprintf(os.Stderr, format, args...) - } -} - // Audit operates on a single repo and searches the full or partial history of the repo. // A semaphore is declared for every repo to bind concurrency. If unbounded, the system will throw a // `too many open files` error. Eventually, gitleaks should use src-d/go-git to avoid shelling out @@ -102,15 +91,13 @@ func (repo *Repo) audit(owner *Owner) (bool, error) { return false, fmt.Errorf("%s does not exist", repo.path) } // no repo present, clone it - repo.Info("cloning") - repo.PrettyPrintF("Cloning \x1b[37;1m%s\x1b[0m...\n", repo.url) + log.Printf("Cloning \x1b[37;1m%s\x1b[0m into %s...\n", repo.url, repo.path) err = exec.Command("git", "clone", repo.url, repo.path).Run() if err != nil { return false, fmt.Errorf("cannot clone %s into %s", repo.url, repo.path) } } else { - repo.Info("fetching") - repo.PrettyPrintF("Fetching \x1b[37;1m%s\x1b[0m...\n", repo.url) + log.Printf("Fetching \x1b[37;1m%s\x1b[0m from %s ...\n", repo.name, repo.path) err = exec.Command("git", "fetch").Run() if err != nil { return false, fmt.Errorf("cannot fetch %s from %s", repo.url, repo.path) @@ -171,14 +158,13 @@ func (repo *Repo) writeReport() error { if _, err := os.Stat(opts.ReportPath); os.IsNotExist(err) { os.Mkdir(opts.ReportPath, os.ModePerm) } - reportFileName := fmt.Sprintf("%s_leaks.json", repo.name) - reportFile := filepath.Join(opts.ReportPath, reportFileName) + reportFile := filepath.Join(repo.reportPath, reportFileName) err := ioutil.WriteFile(reportFile, reportJSON, 0644) if err != nil { return err } - repo.Info(fmt.Sprintf("Report written to %s\n", reportFile)) + log.Printf("report for %s written to %s", repo.name, reportFileName) return nil } @@ -209,22 +195,12 @@ func parseRevList(revList [][]byte) []Commit { // reportAggregator is a go func responsible for ... func reportAggregator(gitLeakReceiverWG *sync.WaitGroup, gitLeaks chan Leak, leaks *[]Leak) { for gitLeak := range gitLeaks { - logger.Info("leak", - zap.String("line", gitLeak.Line), - zap.String("commit", gitLeak.Commit), - zap.String("offender", gitLeak.Offender), - zap.String("Reason", gitLeak.Reason), - zap.String("author", gitLeak.Author), - zap.String("file", gitLeak.File), - zap.String("repoURL", gitLeak.RepoURL), - zap.String("timeOfCommit", gitLeak.Time), - ) *leaks = append(*leaks, gitLeak) if opts.PrettyPrint { b, err := json.MarshalIndent(gitLeak, "", " ") if err != nil { // handle this? - fmt.Println("failed to output leak:", err) + fmt.Printf("failed to output leak: %v", err) } fmt.Println(string(b)) } diff --git a/repo_test.go b/repo_test.go index 909eb261..b1d87fc1 100644 --- a/repo_test.go +++ b/repo_test.go @@ -12,6 +12,7 @@ func TestNewLocalRepo(t *testing.T) { func TestWriteReport(t *testing.T) { // TODO + /* opts, err := defaultOptions() r := newRepo("fakerepo", "github.com") sampleLeak := Leak{ @@ -26,4 +27,5 @@ func TestWriteReport(t *testing.T) { } r.leaks = []Leak{sampleLeak, sampleLeak} r.writeReport() + */ } From d85c8d8abdf35e786da39c6bcfe5763cb6a9b4f6 Mon Sep 17 00:00:00 2001 From: zricethezav Date: Thu, 1 Mar 2018 19:14:20 -0600 Subject: [PATCH 07/16] support for running gitleaks w no args --- main.go | 1 + options.go | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/main.go b/main.go index 7ca5e0c0..e171f7cd 100644 --- a/main.go +++ b/main.go @@ -22,6 +22,7 @@ var ( assignRegex *regexp.Regexp fileDiffRegex *regexp.Regexp opts *Options + pwd string ) func init() { diff --git a/options.go b/options.go index 8975872e..f943f00f 100644 --- a/options.go +++ b/options.go @@ -171,7 +171,8 @@ func defaultOptions() (*Options, error) { func (opts *Options) parseOptions(args []string) error { if len(args) == 0 { - help() + opts.LocalMode = true + opts.RepoPath, _ = os.Getwd() } for i := 0; i < len(args); i++ { From 36c31bf1812d08a24ba4a5bfaafd085cf9cdd4dc Mon Sep 17 00:00:00 2001 From: zricethezav Date: Thu, 1 Mar 2018 22:35:13 -0600 Subject: [PATCH 08/16] working on tests --- main.go | 2 +- options.go | 65 +++++++++++++++++++++++++++---------------------- options_test.go | 6 ++--- owner.go | 62 +++++++++++++--------------------------------- repo.go | 23 +++++++++-------- repo_test.go | 38 ++++++++++++++++++++++------- 6 files changed, 97 insertions(+), 99 deletions(-) diff --git a/main.go b/main.go index e171f7cd..8f84e3e2 100644 --- a/main.go +++ b/main.go @@ -22,7 +22,7 @@ var ( assignRegex *regexp.Regexp fileDiffRegex *regexp.Regexp opts *Options - pwd string + pwd string ) func init() { diff --git a/options.go b/options.go index f943f00f..c851f408 100644 --- a/options.go +++ b/options.go @@ -3,10 +3,10 @@ package main import ( "fmt" "os" + "path/filepath" "regexp" "strconv" "strings" - "path/filepath" ) const usage = `usage: gitleaks [options] / @@ -47,6 +47,7 @@ type Options struct { RepoPath string ReportPath string + ClonePath string Concurrency int B64EntropyCutoff int @@ -141,25 +142,6 @@ func newOpts(args []string) *Options { // deafultOptions provides the default options func defaultOptions() (*Options, error) { - /* - // default GITLEAKS_HOME is $HOME/.gitleaks - // gitleaks will use this location for clones if - // no clone-path is provided - gitleaksHome := os.Getenv("GITLEAKS_HOME") - if gitleaksHome == "" { - homeDir, err := homedir.Dir() - if err != nil { - return nil, fmt.Errorf("could not find system home dir") - } - gitleaksHome = filepath.Join(homeDir, ".gitleaks") - } - - // make sure gitleaks home exists - if _, err := os.Stat(gitleaksHome); os.IsNotExist(err) { - os.Mkdir(gitleaksHome, os.ModePerm) - } - */ - return &Options{ Concurrency: 10, B64EntropyCutoff: 70, @@ -213,25 +195,33 @@ func (opts *Options) parseOptions(args []string) error { help() os.Exit(EXIT_CLEAN) default: - // TARGETS - if i == len(args)-1 { - if opts.LocalMode { - opts.RepoPath = filepath.Clean(args[i]) - } else { - opts.URL = args[i] - } - } else if match, value := opts.optString(arg, "--token="); match { + if match, value := opts.optString(arg, "--token="); match { opts.Token = value } else if match, value := opts.optString(arg, "--since="); match { opts.SinceCommit = value } else if match, value := opts.optString(arg, "--report-path="); match { opts.ReportPath = value + } else if match, value := opts.optString(arg, "--clone-path="); match { + opts.ClonePath = value } else if match, value := opts.optInt(arg, "--log="); match { opts.LogLevel = value } else if match, value := opts.optInt(arg, "--b64Entropy="); match { opts.B64EntropyCutoff = value } else if match, value := opts.optInt(arg, "--hexEntropy="); match { opts.HexEntropyCutoff = value + } else if i == len(args)-1 { + fmt.Println(args[i]) + if opts.LocalMode { + opts.RepoPath = filepath.Clean(args[i]) + } else { + if isGithubTarget(args[i]) { + opts.URL = args[i] + } else { + fmt.Printf("Unknown option %s\n\n", arg) + help() + os.Exit(EXIT_CLEAN) + } + } } else { fmt.Printf("Unknown option %s\n\n", arg) help() @@ -239,9 +229,26 @@ func (opts *Options) parseOptions(args []string) error { } } } + err := opts.guards() if !opts.RepoMode && !opts.UserMode && !opts.OrgMode && !opts.LocalMode { - opts.RepoMode = true + if opts.URL != "" { + opts.RepoMode = true + return nil + } + pwd, _ = os.Getwd() + // check if pwd contains a .git, if it does, run local mode + dotGitPath := filepath.Join(pwd, ".git") + + if _, err := os.Stat(dotGitPath); os.IsNotExist(err) { + fmt.Printf("gitleaks has no target") + os.Exit(EXIT_CLEAN) + } else { + opts.LocalMode = true + opts.RepoPath = pwd + opts.RepoMode = false + } + } return err } diff --git a/options_test.go b/options_test.go index 103c180c..e1d66964 100644 --- a/options_test.go +++ b/options_test.go @@ -76,13 +76,13 @@ func TestParseOptions(t *testing.T) { } func TestGithubTarget(t *testing.T) { - if !isGithubTarget("github.com"){ + if !isGithubTarget("github.com") { t.Error() } - if !isGithubTarget("https://github.com/"){ + if !isGithubTarget("https://github.com/") { t.Error() } - if !isGithubTarget("git@github.com:zricethezav/gitleaks.git"){ + if !isGithubTarget("git@github.com:zricethezav/gitleaks.git") { t.Error() } diff --git a/owner.go b/owner.go index dff4dbe5..62698120 100644 --- a/owner.go +++ b/owner.go @@ -7,14 +7,12 @@ import ( "github.com/google/go-github/github" "golang.org/x/oauth2" "io/ioutil" + "log" "net/http" "os" "os/signal" "path" "strings" - "github.com/mitchellh/go-homedir" - "path/filepath" - "log" ) type Owner struct { @@ -26,27 +24,20 @@ type Owner struct { repos []Repo } -func ownerPath(ownerName string) (string, error){ +func ownerPath(ownerName string) (string, error) { if opts.Tmp { fmt.Println("creating tmp") dir, err := ioutil.TempDir("", ownerName) return dir, err - } - - gitleaksHome := os.Getenv("GITLEAKS_HOME") - if gitleaksHome == "" { - homeDir, err := homedir.Dir() - if err != nil { - return "", fmt.Errorf("could not find system home dir") + } else if opts.ClonePath != "" { + if _, err := os.Stat(opts.ClonePath); os.IsNotExist(err) { + os.Mkdir(opts.ClonePath, os.ModePerm) } - gitleaksHome = filepath.Join(homeDir, ".gitleaks") + return opts.ClonePath, nil + } else { + return os.Getwd() } - // make sure gitleaks home exists - if _, err := os.Stat(gitleaksHome); os.IsNotExist(err) { - os.Mkdir(gitleaksHome, os.ModePerm) - } - return gitleaksHome + "/" + ownerName, nil } // newOwner instantiates an owner and creates any necessary resources for said owner. @@ -54,14 +45,14 @@ func ownerPath(ownerName string) (string, error){ func newOwner() *Owner { name := ownerName() ownerPath, err := ownerPath(name) - if err != nil{ + if err != nil { failF("%v", err) } owner := &Owner{ name: name, url: opts.URL, accountType: ownerType(), - path: ownerPath, + path: ownerPath, } // listen for ctrl-c @@ -83,10 +74,10 @@ func newOwner() *Owner { } /* - err := owner.setupDir() - if err != nil { - owner.failF("%v", err) - }*/ + err := owner.setupDir() + if err != nil { + owner.failF("%v", err) + }*/ err = owner.fetchRepos() if err != nil { owner.failF("%v", err) @@ -104,7 +95,7 @@ func (owner *Owner) fetchRepos() error { if owner.accountType == "" { // single repo, ambiguous account type _, repoName := path.Split(opts.URL) - repo := newRepo(repoName, opts.URL, owner.path + "/" + repoName) + repo := newRepo(repoName, opts.URL, owner.path+"/"+repoName) owner.repos = append(owner.repos, *repo) } else { // org or user account type, would fail if not valid before @@ -187,7 +178,7 @@ func (owner *Owner) fetchUserRepos(userOpts *github.RepositoryListOptions, gitCl // github's org/user response. func (owner *Owner) addRepos(githubRepos []*github.Repository) { for _, repo := range githubRepos { - owner.repos = append(owner.repos, *newRepo(*repo.Name, *repo.CloneURL, owner.path + "/" + *repo.Name)) + owner.repos = append(owner.repos, *newRepo(*repo.Name, *repo.CloneURL, owner.path+"/"+*repo.Name)) } } @@ -195,7 +186,7 @@ func (owner *Owner) addRepos(githubRepos []*github.Repository) { func (owner *Owner) auditRepos() int { exitCode := EXIT_CLEAN for _, repo := range owner.repos { - leaksPst, err := repo.audit(owner) + leaksPst, err := repo.audit() if err != nil { failF("%v\n", err) } @@ -216,25 +207,6 @@ func (owner *Owner) failF(format string, args ...interface{}) { os.Exit(EXIT_FAILURE) } -// setupDir sets up the owner's directory for clones and reports. -// If the temporary option is set then a temporary directory will be -// used for the owner repo clones. -func (owner *Owner) setupDir() error { - if opts.Tmp { - fmt.Println("creating tmp") - dir, err := ioutil.TempDir("", owner.name) - if err != nil { - fmt.Errorf("unable to create temp directories for cloning") - } - owner.path = dir - } else { - if _, err := os.Stat(owner.path); os.IsNotExist(err) { - os.Mkdir(owner.path, os.ModePerm) - } - } - return nil -} - // rmTmp removes the temporary repo func (owner *Owner) rmTmp() { log.Printf("removing tmp gitleaks repo for %s\n", owner.name) diff --git a/repo.go b/repo.go index ec45a2c9..bdffe81e 100644 --- a/repo.go +++ b/repo.go @@ -5,20 +5,20 @@ import ( "encoding/json" "fmt" "io/ioutil" + "log" "os" "os/exec" "path" "path/filepath" "sync" - "log" ) type Repo struct { - name string - url string - path string - status string // TODO - leaks []Leak + name string + url string + path string + status string // TODO + leaks []Leak reportPath string } @@ -45,8 +45,8 @@ type Commit struct { func newLocalRepo(repoPath string) *Repo { _, name := path.Split(repoPath) repo := &Repo{ - name: name, - path: repoPath, + name: name, + path: repoPath, reportPath: opts.ReportPath, } return repo @@ -58,7 +58,7 @@ func newRepo(name string, url string, path string) *Repo { name: name, url: url, // TODO handle existing one - path: path, + path: path, reportPath: opts.ReportPath, } return repo @@ -70,7 +70,7 @@ func newRepo(name string, url string, path string) *Repo { // commands so that users could opt for doing all clones/diffs in memory. // Audit also declares two WaitGroups, one for distributing regex/entropy checks, and one for receiving // the leaks if there are any. This could be done a little more elegantly in the future. -func (repo *Repo) audit(owner *Owner) (bool, error) { +func (repo *Repo) audit() (bool, error) { var ( out []byte err error @@ -140,7 +140,7 @@ func (repo *Repo) audit(owner *Owner) (bool, error) { leaksPst = true } - if opts.ReportPath != "" && len(leaks) != 0 { + if (opts.ReportPath != "" || opts.ReportOut) && len(leaks) != 0 { err = repo.writeReport() if err != nil { return leaksPst, fmt.Errorf("could not write report to %s", opts.ReportPath) @@ -154,7 +154,6 @@ func (repo *Repo) audit(owner *Owner) (bool, error) { // no leaks have been found func (repo *Repo) writeReport() error { reportJSON, _ := json.MarshalIndent(repo.leaks, "", "\t") - if _, err := os.Stat(opts.ReportPath); os.IsNotExist(err) { os.Mkdir(opts.ReportPath, os.ModePerm) } diff --git a/repo_test.go b/repo_test.go index b1d87fc1..510be9ba 100644 --- a/repo_test.go +++ b/repo_test.go @@ -1,6 +1,10 @@ package main -import "testing" +import ( + "testing" + "os" + "fmt" +) func TestNewRepo(t *testing.T) { // TODO @@ -11,11 +15,30 @@ func TestNewLocalRepo(t *testing.T) { } func TestWriteReport(t *testing.T) { - // TODO - /* - opts, err := defaultOptions() - r := newRepo("fakerepo", "github.com") - sampleLeak := Leak{ + opts, _ = defaultOptions() + r := newRepo("fakerepo", "github.com", "") + r.leaks = []Leak{*sampleLeak(), *sampleLeak()} + r.writeReport() + if _, err := os.Stat("fakerepo_leaks.json"); os.IsNotExist(err) { + t.Error() + } else { + os.Remove("fakerepo_leaks.json") + } +} + +func TestAudit(t *testing.T) { + opts, _ = defaultOptions() + opts.RepoMode = true + opts.Tmp = true + opts.URL = "https://github.com/zricethezav/gronit" + owner := newOwner() + r := newRepo("gronit", "https://github.com/zricethezav/gronit", owner.path) + r.audit() + +} + +func sampleLeak() *Leak { + return &Leak{ Line: "yoo", Commit: "mycommit", Offender: "oh boy", @@ -25,7 +48,4 @@ func TestWriteReport(t *testing.T) { Author: "lol", RepoURL: "yooo", } - r.leaks = []Leak{sampleLeak, sampleLeak} - r.writeReport() - */ } From 0ed0489c2da894c113ed0a82b54c6fc9b44bfe54 Mon Sep 17 00:00:00 2001 From: zricethezav Date: Fri, 2 Mar 2018 16:55:02 -0600 Subject: [PATCH 09/16] linting, more testing, cleaning --- checks.go | 1 - main.go | 13 +++++++--- options.go | 8 +++--- owner.go | 69 ++++++++++++++++++++++++++++------------------------ repo.go | 47 +++++++++++++++++++++++------------ repo_test.go | 47 +++++++++++++++++++++++------------ 6 files changed, 113 insertions(+), 72 deletions(-) diff --git a/checks.go b/checks.go index 0c287bb2..faf54b2c 100644 --- a/checks.go +++ b/checks.go @@ -1,7 +1,6 @@ package main import ( - _ "fmt" "math" "strings" ) diff --git a/main.go b/main.go index 8f84e3e2..cd9a2563 100644 --- a/main.go +++ b/main.go @@ -9,9 +9,14 @@ import ( _ "time" ) -const EXIT_CLEAN = 0 -const EXIT_FAILURE = 1 -const EXIT_LEAKS = 2 +// ExitClean : no leaks have been found +const ExitClean = 0 + +// ExitFailure : gitleaks has encountered an error or SIGINT +const ExitFailure = 1 + +// ExitLeaks : leaks are present in scanned repos +const ExitLeaks = 2 // package globals var ( @@ -55,5 +60,5 @@ func main() { func failF(format string, args ...interface{}) { fmt.Fprintf(os.Stderr, format, args...) - os.Exit(EXIT_FAILURE) + os.Exit(ExitFailure) } diff --git a/options.go b/options.go index c851f408..94ee28ea 100644 --- a/options.go +++ b/options.go @@ -193,7 +193,7 @@ func (opts *Options) parseOptions(args []string) error { opts.LogLevel = opts.nextInt(args, &i) case "-h", "--help": help() - os.Exit(EXIT_CLEAN) + os.Exit(ExitClean) default: if match, value := opts.optString(arg, "--token="); match { opts.Token = value @@ -219,7 +219,7 @@ func (opts *Options) parseOptions(args []string) error { } else { fmt.Printf("Unknown option %s\n\n", arg) help() - os.Exit(EXIT_CLEAN) + os.Exit(ExitClean) } } } else { @@ -242,7 +242,7 @@ func (opts *Options) parseOptions(args []string) error { if _, err := os.Stat(dotGitPath); os.IsNotExist(err) { fmt.Printf("gitleaks has no target") - os.Exit(EXIT_CLEAN) + os.Exit(ExitClean) } else { opts.LocalMode = true opts.RepoPath = pwd @@ -258,7 +258,7 @@ func (opts *Options) parseOptions(args []string) error { func (opts *Options) failF(format string, args ...interface{}) { fmt.Fprintf(os.Stderr, format, args...) help() - os.Exit(EXIT_FAILURE) + os.Exit(ExitFailure) } // guards will prevent gitleaks from continuing if any invalid options diff --git a/owner.go b/owner.go index 62698120..c7e13fa2 100644 --- a/owner.go +++ b/owner.go @@ -3,7 +3,6 @@ package main import ( "context" "fmt" - _ "fmt" "github.com/google/go-github/github" "golang.org/x/oauth2" "io/ioutil" @@ -15,6 +14,7 @@ import ( "strings" ) +// Owner blah blah type Owner struct { name string url string @@ -24,9 +24,14 @@ type Owner struct { repos []Repo } +// ownerPath is used by newOwner and is responsible for returning a path parsed from +// opts.ClonePath, PWD, or a temporary directory. If a user provides --clone-path=$Home/Desktop/audits +// then the owner path with be $HOME/Desktop/audits. If the user does not provide a --clone-path= argument +// then ownerPath will return the current working directory. If the user sets the temporary option, then +// ownerPath will be $TMPDIR/ownerName. For example running gitleaks on github.com/mozilla, ownerPath would +// return $TMPDIR/mozilla func ownerPath(ownerName string) (string, error) { if opts.Tmp { - fmt.Println("creating tmp") dir, err := ioutil.TempDir("", ownerName) return dir, err } else if opts.ClonePath != "" { @@ -37,11 +42,14 @@ func ownerPath(ownerName string) (string, error) { } else { return os.Getwd() } - } -// newOwner instantiates an owner and creates any necessary resources for said owner. -// newOwner returns a Owner struct pointer +// newOwner is the entry point for gitleaks after all the options have been parsed and +// is responsible for returning an Owner pointer. If running in localmode then the Owner +// that gets created will create a single repo specified in opts.RepoPath. Otherwise +// newOwner will go out to github and fetch all the repos associated with the owner if +// gitleaks is running in owner mode. If gitleaks is running in a non-local repo mode, then +// newOwner will skip hitting the github api and go directly to cloning. func newOwner() *Owner { name := ownerName() ownerPath, err := ownerPath(name) @@ -73,11 +81,6 @@ func newOwner() *Owner { return owner } - /* - err := owner.setupDir() - if err != nil { - owner.failF("%v", err) - }*/ err = owner.fetchRepos() if err != nil { owner.failF("%v", err) @@ -107,13 +110,13 @@ func (owner *Owner) fetchRepos() error { orgOpt := &github.RepositoryListByOrgOptions{ ListOptions: github.ListOptions{PerPage: 10}, } - err = owner.fetchOrgRepos(orgOpt, gitClient, ctx) + err = owner.fetchOrgRepos(ctx, orgOpt, gitClient) } else { // user account type userOpt := &github.RepositoryListOptions{ ListOptions: github.ListOptions{PerPage: 10}, } - err = owner.fetchUserRepos(userOpt, gitClient, ctx) + err = owner.fetchUserRepos(ctx, userOpt, gitClient) } } return err @@ -122,8 +125,8 @@ func (owner *Owner) fetchRepos() error { // fetchOrgRepos used by fetchRepos is responsible for parsing github's org repo response. If no // github token is available then fetchOrgRepos might run into a rate limit in which case owner will // log an error and gitleaks will exit. The rate limit for no token is 50 req/hour... not much. -func (owner *Owner) fetchOrgRepos(orgOpts *github.RepositoryListByOrgOptions, gitClient *github.Client, - ctx context.Context) error { +func (owner *Owner) fetchOrgRepos(ctx context.Context, orgOpts *github.RepositoryListByOrgOptions, + gitClient *github.Client) error { var ( githubRepos []*github.Repository resp *github.Response @@ -135,9 +138,10 @@ func (owner *Owner) fetchOrgRepos(orgOpts *github.RepositoryListByOrgOptions, gi ctx, owner.name, orgOpts) owner.addRepos(githubRepos) if _, ok := err.(*github.RateLimitError); ok { - fmt.Println("Hit rate limit") + log.Printf("hit rate limit retreiving %s, continuing with partial audit\n", + owner.name) } else if err != nil { - return fmt.Errorf("failed fetching org repos, bad request") + return fmt.Errorf("failed obtaining %s repos from githuib api, bad request", owner.name) } else if resp.NextPage == 0 { break } @@ -150,8 +154,8 @@ func (owner *Owner) fetchOrgRepos(orgOpts *github.RepositoryListByOrgOptions, gi // github token is available then fetchUserRepos might run into a rate limit in which case owner will // log an error and gitleaks will exit. The rate limit for no token is 50 req/hour... not much. // sorry for the redundancy -func (owner *Owner) fetchUserRepos(userOpts *github.RepositoryListOptions, gitClient *github.Client, - ctx context.Context) error { +func (owner *Owner) fetchUserRepos(ctx context.Context, userOpts *github.RepositoryListOptions, + gitClient *github.Client) error { var ( githubRepos []*github.Repository resp *github.Response @@ -162,10 +166,11 @@ func (owner *Owner) fetchUserRepos(userOpts *github.RepositoryListOptions, gitCl ctx, owner.name, userOpts) owner.addRepos(githubRepos) if _, ok := err.(*github.RateLimitError); ok { - fmt.Println("Hit rate limit") + log.Printf("hit rate limit retreiving %s, continuing with partial audit\n", + owner.name) break } else if err != nil { - return fmt.Errorf("failed fetching user repos, bad request") + return fmt.Errorf("failed obtaining %s repos from github api, bad request", owner.name) } else if resp.NextPage == 0 { break } @@ -182,19 +187,20 @@ func (owner *Owner) addRepos(githubRepos []*github.Repository) { } } -// auditRepos +// auditRepos is responsible for auditing all the owner's +// repos. auditRepos is used by main and will return the following exit codes +// 0: The audit succeeded with no findings +// 1: The audit failed, or wasn't attempted due to an execution failure. +// 2: The audit succeeded, and secrets / patterns were found. func (owner *Owner) auditRepos() int { - exitCode := EXIT_CLEAN + exitCode := ExitClean for _, repo := range owner.repos { leaksPst, err := repo.audit() if err != nil { - failF("%v\n", err) + failF("%v", err) } if leaksPst { - log.Printf("\x1b[31;2mLEAKS DETECTED for %s\x1b[0m!\n", repo.name) - exitCode = EXIT_LEAKS - } else { - log.Printf("No Leaks detected for \x1b[32;2m%s\x1b[0m\n", repo.name) + exitCode = ExitLeaks } } return exitCode @@ -204,14 +210,15 @@ func (owner *Owner) auditRepos() int { // and exits with a exit code 2 func (owner *Owner) failF(format string, args ...interface{}) { fmt.Fprintf(os.Stderr, format, args...) - os.Exit(EXIT_FAILURE) + os.Exit(ExitFailure) } -// rmTmp removes the temporary repo +// rmTmp removes the owner's temporary repo. rmTmp will only get called if temporary +// mode is set. rmTmp is called on a SIGINT and after the audits have finished func (owner *Owner) rmTmp() { log.Printf("removing tmp gitleaks repo for %s\n", owner.name) os.RemoveAll(owner.path) - os.Exit(EXIT_FAILURE) + os.Exit(ExitFailure) } // ownerType returns the owner type extracted from opts. @@ -244,8 +251,6 @@ func ownerName() string { // githubTokenClient creates an oauth client from your github access token. // Gitleaks will attempt to retrieve your github access token from a cli argument // or an env var - "GITHUB_TOKEN". -// Might be good to eventually parse the token from a Config or creds file in -// $GITLEAKS_HOME func githubTokenClient() *http.Client { var token string if opts.Token != "" { diff --git a/repo.go b/repo.go index bdffe81e..15a61b73 100644 --- a/repo.go +++ b/repo.go @@ -13,6 +13,7 @@ import ( "sync" ) +// Repo is type Repo struct { name string url string @@ -22,6 +23,7 @@ type Repo struct { reportPath string } +// Leak is type Leak struct { Line string `json:"line"` Commit string `json:"commit"` @@ -34,6 +36,7 @@ type Leak struct { RepoURL string `json:"repoURL"` } +// Commit is type Commit struct { Hash string Author string @@ -41,7 +44,7 @@ type Commit struct { Msg string } -// running gitleaks on local repo +// newLocalRepo will such and such func newLocalRepo(repoPath string) *Repo { _, name := path.Split(repoPath) repo := &Repo{ @@ -53,17 +56,23 @@ func newLocalRepo(repoPath string) *Repo { } +// newRepo func newRepo(name string, url string, path string) *Repo { repo := &Repo{ - name: name, - url: url, - // TODO handle existing one + name: name, + url: url, path: path, reportPath: opts.ReportPath, } return repo } +// rmTmp +func (repo *Repo) rmTmp() { + log.Printf("removing tmp gitleaks repo %s\n", repo.path) + os.Remove(repo.path) +} + // Audit operates on a single repo and searches the full or partial history of the repo. // A semaphore is declared for every repo to bind concurrency. If unbounded, the system will throw a // `too many open files` error. Eventually, gitleaks should use src-d/go-git to avoid shelling out @@ -82,6 +91,10 @@ func (repo *Repo) audit() (bool, error) { leaksPst bool ) + if opts.Tmp { + defer repo.rmTmp() + } + dotGitPath := filepath.Join(repo.path, ".git") // Navigate to proper location to being audit. Clone repo @@ -91,13 +104,13 @@ func (repo *Repo) audit() (bool, error) { return false, fmt.Errorf("%s does not exist", repo.path) } // no repo present, clone it - log.Printf("Cloning \x1b[37;1m%s\x1b[0m into %s...\n", repo.url, repo.path) + log.Printf("cloning \x1b[37;1m%s\x1b[0m into %s...\n", repo.url, repo.path) err = exec.Command("git", "clone", repo.url, repo.path).Run() if err != nil { return false, fmt.Errorf("cannot clone %s into %s", repo.url, repo.path) } } else { - log.Printf("Fetching \x1b[37;1m%s\x1b[0m from %s ...\n", repo.name, repo.path) + log.Printf("fetching \x1b[37;1m%s\x1b[0m from %s ...\n", repo.name, repo.path) err = exec.Command("git", "fetch").Run() if err != nil { return false, fmt.Errorf("cannot fetch %s from %s", repo.url, repo.path) @@ -138,10 +151,13 @@ func (repo *Repo) audit() (bool, error) { gitLeakReceiverWG.Wait() if len(leaks) != 0 { leaksPst = true + log.Printf("\x1b[31;2mLEAKS DETECTED for %s\x1b[0m!\n", repo.name) + } else { + log.Printf("No Leaks detected for \x1b[32;2m%s\x1b[0m\n", repo.name) } if (opts.ReportPath != "" || opts.ReportOut) && len(leaks) != 0 { - err = repo.writeReport() + err = repo.writeReport(leaks) if err != nil { return leaksPst, fmt.Errorf("could not write report to %s", opts.ReportPath) } @@ -150,12 +166,13 @@ func (repo *Repo) audit() (bool, error) { } // Used by audit, writeReport will generate a report and write it out to -// $GITLEAKS_HOME/report//. No report will be generated if -// no leaks have been found -func (repo *Repo) writeReport() error { - reportJSON, _ := json.MarshalIndent(repo.leaks, "", "\t") +// --report-path= if specified, otherwise a report will be generated to +// $PWD/_leaks.json. No report will be generated if +// no leaks have been found or --report-out is not set. +func (repo *Repo) writeReport(leaks []Leak) error { + reportJSON, _ := json.MarshalIndent(leaks, "", "\t") if _, err := os.Stat(opts.ReportPath); os.IsNotExist(err) { - os.Mkdir(opts.ReportPath, os.ModePerm) + os.MkdirAll(opts.ReportPath, os.ModePerm) } reportFileName := fmt.Sprintf("%s_leaks.json", repo.name) reportFile := filepath.Join(repo.reportPath, reportFileName) @@ -163,7 +180,7 @@ func (repo *Repo) writeReport() error { if err != nil { return err } - log.Printf("report for %s written to %s", repo.name, reportFileName) + log.Printf("report for %s written to %s", repo.name, reportFile) return nil } @@ -218,7 +235,7 @@ func auditDiff(currCommit Commit, repo *Repo, commitWG *sync.WaitGroup, if err := os.Chdir(fmt.Sprintf(repo.path)); err != nil { // TODO handle this better - os.Exit(EXIT_FAILURE) + os.Exit(ExitFailure) } commitCmp := fmt.Sprintf("%s^!", currCommit.Hash) @@ -227,7 +244,7 @@ func auditDiff(currCommit Commit, repo *Repo, commitWG *sync.WaitGroup, <-semaphoreChan if err != nil { - os.Exit(EXIT_FAILURE) + os.Exit(ExitFailure) } leaks := doChecks(string(out), currCommit, repo) diff --git a/repo_test.go b/repo_test.go index 510be9ba..450aad69 100644 --- a/repo_test.go +++ b/repo_test.go @@ -1,17 +1,20 @@ package main import ( - "testing" + _ "fmt" "os" - "fmt" + "testing" ) -func TestNewRepo(t *testing.T) { - // TODO -} - func TestNewLocalRepo(t *testing.T) { - // TODO + r := newLocalRepo("") + if r.path != "" { + t.Error() + } + r = newLocalRepo("some/path") + if r.name != "path" || r.path != "some/path" { + t.Error() + } } func TestWriteReport(t *testing.T) { @@ -32,20 +35,32 @@ func TestAudit(t *testing.T) { opts.Tmp = true opts.URL = "https://github.com/zricethezav/gronit" owner := newOwner() - r := newRepo("gronit", "https://github.com/zricethezav/gronit", owner.path) - r.audit() + r := newRepo("gronit", opts.URL, owner.path) + leaksPst, _ := r.audit() + if !leaksPst { + // TODO setup actual test repo + t.Error() + } + // new owner + opts.URL = "https://github.com/kelseyhightower/nocode" + owner = newOwner() + r = newRepo("nocode", opts.URL, owner.path) + leaksPst, _ = r.audit() + if leaksPst { + t.Error() + } } func sampleLeak() *Leak { return &Leak{ - Line: "yoo", - Commit: "mycommit", + Line: "yoo", + Commit: "mycommit", Offender: "oh boy", - Reason: "hello", - Msg: "msg", - Time: "time", - Author: "lol", - RepoURL: "yooo", + Reason: "hello", + Msg: "msg", + Time: "time", + Author: "lol", + RepoURL: "yooo", } } From c019a9d80df500a82e5b477bba578f5cd4485beb Mon Sep 17 00:00:00 2001 From: zricethezav Date: Fri, 2 Mar 2018 17:19:11 -0600 Subject: [PATCH 10/16] guard rm temp dirs --- owner.go | 9 +++++++-- repo_test.go | 2 +- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/owner.go b/owner.go index c7e13fa2..2ecd8a8e 100644 --- a/owner.go +++ b/owner.go @@ -71,7 +71,10 @@ func newOwner() *Owner { signal.Notify(sigC, os.Interrupt, os.Interrupt) go func() { <-sigC - owner.rmTmp() + if opts.Tmp { + owner.rmTmp() + } + os.Exit(ExitFailure) }() // if running on local repo, just go right to it. @@ -203,6 +206,9 @@ func (owner *Owner) auditRepos() int { exitCode = ExitLeaks } } + if opts.Tmp { + owner.rmTmp() + } return exitCode } @@ -218,7 +224,6 @@ func (owner *Owner) failF(format string, args ...interface{}) { func (owner *Owner) rmTmp() { log.Printf("removing tmp gitleaks repo for %s\n", owner.name) os.RemoveAll(owner.path) - os.Exit(ExitFailure) } // ownerType returns the owner type extracted from opts. diff --git a/repo_test.go b/repo_test.go index 450aad69..9f0cf5eb 100644 --- a/repo_test.go +++ b/repo_test.go @@ -21,7 +21,7 @@ func TestWriteReport(t *testing.T) { opts, _ = defaultOptions() r := newRepo("fakerepo", "github.com", "") r.leaks = []Leak{*sampleLeak(), *sampleLeak()} - r.writeReport() + r.writeReport(r.leaks) if _, err := os.Stat("fakerepo_leaks.json"); os.IsNotExist(err) { t.Error() } else { From 2fadf219d93df25c938431173b42c4867f65b87c Mon Sep 17 00:00:00 2001 From: zricethezav Date: Sat, 3 Mar 2018 21:44:04 -0600 Subject: [PATCH 11/16] more coverage --- main.go | 3 --- options.go | 31 ++++++++++++++----------------- options_test.go | 1 - owner_test.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ repo_test.go | 1 - 5 files changed, 59 insertions(+), 22 deletions(-) create mode 100644 owner_test.go diff --git a/main.go b/main.go index cd9a2563..3729355d 100644 --- a/main.go +++ b/main.go @@ -2,11 +2,8 @@ package main import ( "fmt" - _ "fmt" - _ "io/ioutil" "os" "regexp" - _ "time" ) // ExitClean : no leaks have been found diff --git a/options.go b/options.go index 94ee28ea..4b150bee 100644 --- a/options.go +++ b/options.go @@ -28,7 +28,7 @@ Locations Other -t --temp Clone to temporary directory - -c Upper bound on concurrent diffs + --concurrency= Upper bound on concurrent diffs --since= Commit to stop at --b64Entropy= Base64 entropy cutoff (default is 70) --hexEntropy= Hex entropy cutoff (default is 40) @@ -160,19 +160,12 @@ func (opts *Options) parseOptions(args []string) error { for i := 0; i < len(args); i++ { arg := args[i] switch arg { - case "-s": - opts.SinceCommit = opts.nextString(args, &i) case "--strict": opts.Strict = true - case "-b", "--b64Entropy": - opts.B64EntropyCutoff = opts.nextInt(args, &i) - case "-x", "--hexEntropy": - opts.HexEntropyCutoff = opts.nextInt(args, &i) case "-e", "--entropy": opts.Entropy = true case "-c": opts.Concurrency = opts.nextInt(args, &i) - case "-o", "--org": opts.OrgMode = true case "-u", "--user": @@ -181,12 +174,10 @@ func (opts *Options) parseOptions(args []string) error { opts.RepoMode = true case "-l", "--local": opts.LocalMode = true - case "--report-out": opts.ReportOut = true case "--pretty": opts.PrettyPrint = true - case "-t", "--temp": opts.Tmp = true case "-ll": @@ -217,38 +208,44 @@ func (opts *Options) parseOptions(args []string) error { if isGithubTarget(args[i]) { opts.URL = args[i] } else { - fmt.Printf("Unknown option %s\n\n", arg) help() - os.Exit(ExitClean) + return fmt.Errorf("Unknown option %s\n", arg) } } } else { - fmt.Printf("Unknown option %s\n\n", arg) help() - return fmt.Errorf("Unknown option %s\n\n", arg) + return fmt.Errorf("Unknown option %s\n", arg) } } } - err := opts.guards() + // TODO cleanup this logic if !opts.RepoMode && !opts.UserMode && !opts.OrgMode && !opts.LocalMode { if opts.URL != "" { opts.RepoMode = true + err := opts.guards() + if err != nil{ + return err + } return nil } + pwd, _ = os.Getwd() // check if pwd contains a .git, if it does, run local mode dotGitPath := filepath.Join(pwd, ".git") if _, err := os.Stat(dotGitPath); os.IsNotExist(err) { - fmt.Printf("gitleaks has no target") - os.Exit(ExitClean) + return fmt.Errorf("gitleaks has no target: %v", err) } else { opts.LocalMode = true opts.RepoPath = pwd opts.RepoMode = false } + } + err := opts.guards() + if err != nil{ + return err } return err } diff --git a/options_test.go b/options_test.go index e1d66964..f6d9b535 100644 --- a/options_test.go +++ b/options_test.go @@ -85,5 +85,4 @@ func TestGithubTarget(t *testing.T) { if !isGithubTarget("git@github.com:zricethezav/gitleaks.git") { t.Error() } - } diff --git a/owner_test.go b/owner_test.go new file mode 100644 index 00000000..ee9f8cff --- /dev/null +++ b/owner_test.go @@ -0,0 +1,45 @@ +package main + +import ( + "testing" + "os" + "fmt" +) + +func TestOwnerPath(t *testing.T) { + opts, _ = defaultOptions() + p, err := ownerPath("testName") + if err != nil { + t.Error() + } + pwd, _ := os.Getwd() + if pwd != p { + t.Error() + } + opts.ClonePath = "test" + p, err = ownerPath("nameToIgnore") + fmt.Println(p) + if p != "test" { + t.Error() + } +} + +func TestNewOwner(t *testing.T) { + opts, _ = defaultOptions() + owner := newOwner() + + // default options will assume gitleaks is + // running on local mode + pwd, _ := os.Getwd() + if pwd != owner.path { + t.Error() + } + + // fuck on this some more + opts.URL = "github.com/testowner/test" + owner = newOwner() + fmt.Println(owner.path) + if owner.path != pwd + "/testowner" { + t.Error() + } +} diff --git a/repo_test.go b/repo_test.go index 9f0cf5eb..2fcbc9dd 100644 --- a/repo_test.go +++ b/repo_test.go @@ -1,7 +1,6 @@ package main import ( - _ "fmt" "os" "testing" ) From b6b3e768dc77f591fade12fb18a1d81151a4ff7b Mon Sep 17 00:00:00 2001 From: zricethezav Date: Sun, 4 Mar 2018 18:36:27 -0600 Subject: [PATCH 12/16] working on readme --- README.md | 97 ++++++++++++++------------------------------------- options.go | 22 +++++------- owner.go | 2 +- owner_test.go | 10 ------ repo.go | 4 +-- 5 files changed, 39 insertions(+), 96 deletions(-) diff --git a/README.md b/README.md index 60c98d0d..7ec74d23 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ ![Alt Text](https://github.com/zricethezav/gifs/blob/master/gitleaks1.png) [![Build Status](https://travis-ci.org/zricethezav/gitleaks.svg?branch=master)](https://travis-ci.org/zricethezav/gitleaks) -## Check git repos for secrets and keys +## Audit git repos for secrets and keys #### Installing @@ -12,85 +12,42 @@ go get -u github.com/zricethezav/gitleaks ![Alt Text](https://github.com/zricethezav/gifs/blob/master/gitleaks.gif) ```bash -./gitleaks {git url} +./gitleaks [options] ``` -Gitleaks will clone the target `` to `$HOME/.gitleaks/clones/` and run a regex check against all diffs of all commits on all remotes in topological order. If any leaks are found gitleaks will output the leak in json, Ex: -``` -{ - "line": "-const AWS_KEY = \"AKIALALEMEL33243OLIAE\"", - "commit": "eaeffdc65b4c73ccb67e75d96bd8743be2c85973", - "string": "AKIALALEMEL33243OLIA", - "reason": "AWS", - "commitMsg": "remove fake key", - "time": "2018-02-04 19:43:28 -0600", - "author": "Zachary Rice", - "file": "main.go", - "repoURL": "https://github.com/zricethezav/gronit" -} -``` -Gitleaks will not re-clone repos unless the temporary flag is set (see Options section), instead gitleaks will `fetch` all new changes before the scan. This works for users and organization repos as well. Regex's for the scan are defined in `main.go`. Feel free to open a PR and contribute if you have additional regex you want included. Work largely based on [https://people.eecs.berkeley.edu/~rohanpadhye/files/key_leaks-msr15.pdf](https://people.eecs.berkeley.edu/~rohanpadhye/files/key_leaks-msr15.pdf) and regexes from https://github.com/dxa4481/truffleHog and https://github.com/anshumanbh/git-all-secrets. - -#### Example with Report -```bash -gitleaks --json https://github.com/zricethezav/gronit -``` -This will run gitleaks on one of my projects, gronit and create the following structure in `$HOME/.gitleaks`: -``` -. -├── clones -│   └── zricethezav -│   └── gronit -│   ├── README.md -│   ├── main.go -│   ├── options.go -│   ├── server.go -│   └── utils.go -└── report - └── zricethezav - └── gronit_leaks.json -``` -The clones directory contains the repo owner (me) and any repos gitleaks has scanned. Next time we run gitleaks on gronit again we will `fetch` gronit rather than `clone`. Reports are written out to `$HOME/.gitleaks/report//_leaks.json` +Gitleaks audits local and remote repos by running regex checks against all commits. #### Options ``` -usage: gitleaks [options] +usage: gitleaks [options] / Options: - -c --concurrency Upper bound on concurrent diffs - -u --user Git user url - -r --repo Git repo url - -o --org Git organization url - -s --since Commit to stop at - -b --b64Entropy Base64 entropy cutoff (default is 70) - -x --hexEntropy Hex entropy cutoff (default is 40) - -e --entropy Enable entropy - -j --json Output gitleaks report - --token Github API token - --strict Enables stopwords - -h --help Display this message +Modes + -u --user Git user mode + -r --repo Git repo mode + -o --org Git organization mode + -l --local Local mode, gitleaks will look for local repo in +Logging + --log= 0: Debug, 1: Info, 3: Error + -v --verbose Verbose mode, will output leaks as gitleaks finds them + +Locations + --report_path= Report output, default $GITLEAKS_HOME/report + --clone_path= Gitleaks will clone repos here, default $GITLEAKS_HOME/clones + +Other + -t --temp Clone to temporary directory + --concurrency= Upper bound on concurrent diffs + --since= Commit to stop at + --b64Entropy= Base64 entropy cutoff (default is 70) + --hexEntropy= Hex entropy cutoff (default is 40) + -e --entropy Enable entropy + -h --help Display this message + --token= Github API token + --stopwords Enables stopwords ``` -##### Options Explained - -| Option | Explanation | -| ------------- | ------------- | -| -c --concurrency | Set the limit on the number of concurrent diffs. If unbounded, your system would throw a `too many open files` error. Tweak `ulimit` for quicker scans at your own risk. Ex: `gitleaks -c 100 ` | -| -u --user | Target git user. Reports and clones are dumped to `$HOME/.gitleaks/clones//` and `$HOME/.gitleaks/reports//`. Ex: `gitleaks -u `. -| -o --org | Target git organization. Reports and clones are dumped to `$HOME/.gitleaks/clones//` and `$HOME/.gitleaks/reports//`. Ex: `gitleaks -o ` -| -r --repo | Default behavior is to have gitleaks target a specific repo, so this option is unecessary, but... Target git repo. Reports and clones are dumped to `$HOME/.gitleaks/clones//` and `$HOME/.gitleaks/reports//` -| -s --since | Since argument accepts a commit hash and will scan the repo history up to and including this hash. Ex: `gitleaks -s ` -| -b --b64Entropy | Entropy cutoff for base 64 characters. Ex: `gitleaks -e -b 70 ` | -| -x --hexEntropy | Entropy cutoff for hex characters. Ex: `gitleaks -e -x 70 ` | -| -e --entroy | Enable entropy checks. Ex: `gitleaks -e ` | -| -j --json | Enable report generation. Ex: `gitleaks --json ` | -| -t --temporary | Cloned repos will be cloned into a temp directory and removed after gitleaks exits. Ex: `gitleaks -t ` | -| --token | NOTE: you should use env var `GITHUB_TOKEN` instead of this flag. Github API token needed for scanning private repos and pagination on repo fetching from github's api. | -| -- strict | Enable stopwords. Ex: `gitleaks --strict ` | - -NOTE: your mileage may vary so if you aren't getting the results you expected try updating the regexes to fit your needs or try tweaking the entropy cutoffs and stopwords. Entropy cutoff for base64 alphabets seemed to give good results around 70 and hex alphabets seemed to give good results around 40. Entropy is calculated using [Shannon entropy](http://www.bearcave.com/misl/misl_tech/wavelets/compression/shannon.html). - ### If you find a valid leak in a repo Please read the [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. diff --git a/options.go b/options.go index 4b150bee..ab426dad 100644 --- a/options.go +++ b/options.go @@ -9,7 +9,8 @@ import ( "strings" ) -const usage = `usage: gitleaks [options] / +const usage = ` +usage: gitleaks [options] / Options: Modes @@ -63,15 +64,12 @@ type Options struct { Strict bool Entropy bool SinceCommit string - Persist bool - IncludeForks bool Tmp bool - ReportOut bool Token string // LOGS/REPORT - LogLevel int - PrettyPrint bool + LogLevel int + Verbose bool } // help prints the usage string and exits @@ -160,7 +158,7 @@ func (opts *Options) parseOptions(args []string) error { for i := 0; i < len(args); i++ { arg := args[i] switch arg { - case "--strict": + case "--stopwords": opts.Strict = true case "-e", "--entropy": opts.Entropy = true @@ -174,14 +172,10 @@ func (opts *Options) parseOptions(args []string) error { opts.RepoMode = true case "-l", "--local": opts.LocalMode = true - case "--report-out": - opts.ReportOut = true - case "--pretty": - opts.PrettyPrint = true + case "-v", "--verbose": + opts.Verbose = true case "-t", "--temp": opts.Tmp = true - case "-ll": - opts.LogLevel = opts.nextInt(args, &i) case "-h", "--help": help() os.Exit(ExitClean) @@ -275,6 +269,8 @@ func (opts *Options) guards() error { return fmt.Errorf("Cannot run Gitleaks with temp settings and local mode\n") } else if opts.SinceCommit != "" && (opts.OrgMode || opts.UserMode) { return fmt.Errorf("Cannot run Gitleaks with since commit flag and a owner mode\n") + } else if opts.ClonePath != "" && opts.Tmp { + return fmt.Errorf("Cannot run Gitleaks with --clone-path set and temporary repo\n") } return nil diff --git a/owner.go b/owner.go index 2ecd8a8e..5350ee9d 100644 --- a/owner.go +++ b/owner.go @@ -222,7 +222,7 @@ func (owner *Owner) failF(format string, args ...interface{}) { // rmTmp removes the owner's temporary repo. rmTmp will only get called if temporary // mode is set. rmTmp is called on a SIGINT and after the audits have finished func (owner *Owner) rmTmp() { - log.Printf("removing tmp gitleaks repo for %s\n", owner.name) + log.Printf("removing tmp gitleaks repo for %s\n", owner.path) os.RemoveAll(owner.path) } diff --git a/owner_test.go b/owner_test.go index ee9f8cff..fd41a2ba 100644 --- a/owner_test.go +++ b/owner_test.go @@ -3,7 +3,6 @@ package main import ( "testing" "os" - "fmt" ) func TestOwnerPath(t *testing.T) { @@ -18,7 +17,6 @@ func TestOwnerPath(t *testing.T) { } opts.ClonePath = "test" p, err = ownerPath("nameToIgnore") - fmt.Println(p) if p != "test" { t.Error() } @@ -34,12 +32,4 @@ func TestNewOwner(t *testing.T) { if pwd != owner.path { t.Error() } - - // fuck on this some more - opts.URL = "github.com/testowner/test" - owner = newOwner() - fmt.Println(owner.path) - if owner.path != pwd + "/testowner" { - t.Error() - } } diff --git a/repo.go b/repo.go index 15a61b73..94ee0dd4 100644 --- a/repo.go +++ b/repo.go @@ -156,7 +156,7 @@ func (repo *Repo) audit() (bool, error) { log.Printf("No Leaks detected for \x1b[32;2m%s\x1b[0m\n", repo.name) } - if (opts.ReportPath != "" || opts.ReportOut) && len(leaks) != 0 { + if opts.ReportPath != "" && len(leaks) != 0 { err = repo.writeReport(leaks) if err != nil { return leaksPst, fmt.Errorf("could not write report to %s", opts.ReportPath) @@ -212,7 +212,7 @@ func parseRevList(revList [][]byte) []Commit { func reportAggregator(gitLeakReceiverWG *sync.WaitGroup, gitLeaks chan Leak, leaks *[]Leak) { for gitLeak := range gitLeaks { *leaks = append(*leaks, gitLeak) - if opts.PrettyPrint { + if opts.Verbose { b, err := json.MarshalIndent(gitLeak, "", " ") if err != nil { // handle this? From 078b951a4392ec1c63776b292c667aea861bbd7d Mon Sep 17 00:00:00 2001 From: zricethezav Date: Sun, 4 Mar 2018 18:51:09 -0600 Subject: [PATCH 13/16] removing some options --- README.md | 10 +--------- options.go | 2 -- 2 files changed, 1 insertion(+), 11 deletions(-) diff --git a/README.md b/README.md index 7ec74d23..fcedb1c3 100644 --- a/README.md +++ b/README.md @@ -22,22 +22,14 @@ Gitleaks audits local and remote repos by running regex checks against all commi usage: gitleaks [options] / Options: -Modes -u --user Git user mode -r --repo Git repo mode -o --org Git organization mode -l --local Local mode, gitleaks will look for local repo in - -Logging - --log= 0: Debug, 1: Info, 3: Error + -t --temp Clone to temporary directory -v --verbose Verbose mode, will output leaks as gitleaks finds them - -Locations --report_path= Report output, default $GITLEAKS_HOME/report --clone_path= Gitleaks will clone repos here, default $GITLEAKS_HOME/clones - -Other - -t --temp Clone to temporary directory --concurrency= Upper bound on concurrent diffs --since= Commit to stop at --b64Entropy= Base64 entropy cutoff (default is 70) diff --git a/options.go b/options.go index ab426dad..4fee5dfb 100644 --- a/options.go +++ b/options.go @@ -188,8 +188,6 @@ func (opts *Options) parseOptions(args []string) error { opts.ReportPath = value } else if match, value := opts.optString(arg, "--clone-path="); match { opts.ClonePath = value - } else if match, value := opts.optInt(arg, "--log="); match { - opts.LogLevel = value } else if match, value := opts.optInt(arg, "--b64Entropy="); match { opts.B64EntropyCutoff = value } else if match, value := opts.optInt(arg, "--hexEntropy="); match { From ce44961e6e575dc5eb75715ccc801ec15e04b2b5 Mon Sep 17 00:00:00 2001 From: zricethezav Date: Sun, 4 Mar 2018 20:16:04 -0600 Subject: [PATCH 14/16] README again --- README.md | 40 ++++++++++++++++++++++++++++++++++++++-- options.go | 26 ++++---------------------- 2 files changed, 42 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index fcedb1c3..1b844e64 100644 --- a/README.md +++ b/README.md @@ -28,8 +28,8 @@ Options: -l --local Local mode, gitleaks will look for local repo in -t --temp Clone to temporary directory -v --verbose Verbose mode, will output leaks as gitleaks finds them - --report_path= Report output, default $GITLEAKS_HOME/report - --clone_path= Gitleaks will clone repos here, default $GITLEAKS_HOME/clones + --report-path= Save report to path, gitleaks default behavior is to save report to pwd + --clone-path= Gitleaks will clone repos here, default pwd --concurrency= Upper bound on concurrent diffs --since= Commit to stop at --b64Entropy= Base64 entropy cutoff (default is 70) @@ -40,6 +40,42 @@ Options: --stopwords Enables stopwords ``` +#### Exit Codes +Use these codes to hook gitleaks into whatever pipeline you're running +| code | explanation | +| ------------- | ------------- | +| 0 | Gitleaks succeeded with no leaks | +| 1 | Gitleaks failed or wasn't attempted due to execution failure | +| 2 | Gitleaks succeeded and leaks were present during the audit | + +#### Examples +```bash +gitleaks +``` +Run audit on current working directory if `.git` is present | + +```bash +gitleaks https://github.com/some/repo +``` +Run audit on `github.com/some/repo.git` and clone repo to + +```bash +gitleaks --clone-path=$HOME/Desktop/audits https://github.com/some/repo +``` +Run audit on `github.com/some/repo.git` and clone repo to $HOME/Desktop/audits + +```bash +gitleaks --temp https://github.com/some/repo +``` +Run audit on `github.com/some/repo.git` and clone repo to $TMPDIR (this will remove repos after audit is complete) + +```bash +gitleaks --temp -u https://github.com/some-user +``` +Run audit on all of `some-user`'s repos. Again, `--temp` flag will clone all repos into $TMPDIR after be removed after audit + + + ### If you find a valid leak in a repo Please read the [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. diff --git a/options.go b/options.go index 4fee5dfb..d1b2e94c 100644 --- a/options.go +++ b/options.go @@ -13,21 +13,13 @@ const usage = ` usage: gitleaks [options] / Options: -Modes -u --user Git user mode -r --repo Git repo mode -o --org Git organization mode -l --local Local mode, gitleaks will look for local repo in - -Logging - -ll --log= 0: Debug, 1: Info, 3: Error -v --verbose Verbose mode, will output leaks as gitleaks finds them - -Locations - --report_path= Report output, default $GITLEAKS_HOME/report - --clone_path= Gitleaks will clone repos here, default $GITLEAKS_HOME/clones - -Other + --report-path= Report output, default $GITLEAKS_HOME/report + --clone-path= Gitleaks will clone repos here, default $GITLEAKS_HOME/clones -t --temp Clone to temporary directory --concurrency= Upper bound on concurrent diffs --since= Commit to stop at @@ -37,7 +29,6 @@ Other -h --help Display this message --token= Github API token --stopwords Enables stopwords - --pretty Enables pretty printing for humans, otherwise you'll get logs' ` @@ -46,29 +37,20 @@ Other type Options struct { URL string RepoPath string - ReportPath string ClonePath string - Concurrency int B64EntropyCutoff int HexEntropyCutoff int - - // MODES UserMode bool OrgMode bool RepoMode bool LocalMode bool - - // OPTS Strict bool Entropy bool SinceCommit string Tmp bool Token string - - // LOGS/REPORT - LogLevel int Verbose bool } @@ -162,8 +144,6 @@ func (opts *Options) parseOptions(args []string) error { opts.Strict = true case "-e", "--entropy": opts.Entropy = true - case "-c": - opts.Concurrency = opts.nextInt(args, &i) case "-o", "--org": opts.OrgMode = true case "-u", "--user": @@ -192,6 +172,8 @@ func (opts *Options) parseOptions(args []string) error { opts.B64EntropyCutoff = value } else if match, value := opts.optInt(arg, "--hexEntropy="); match { opts.HexEntropyCutoff = value + } else if match, value := opts.optInt(arg, "--concurrency="); match { + opts.Concurrency = value } else if i == len(args)-1 { fmt.Println(args[i]) if opts.LocalMode { From e2060e9cd31412805a09fb8ba3cfb28af87ad591 Mon Sep 17 00:00:00 2001 From: zricethezav Date: Sun, 4 Mar 2018 20:23:04 -0600 Subject: [PATCH 15/16] fixing table --- README.md | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 1b844e64..7fa48fb6 100644 --- a/README.md +++ b/README.md @@ -42,17 +42,22 @@ Options: #### Exit Codes Use these codes to hook gitleaks into whatever pipeline you're running -| code | explanation | -| ------------- | ------------- | -| 0 | Gitleaks succeeded with no leaks | -| 1 | Gitleaks failed or wasn't attempted due to execution failure | -| 2 | Gitleaks succeeded and leaks were present during the audit | +code | explanation + -------------|------------- +0 | Gitleaks succeeded with no leaks +1 | Gitleaks failed or wasn't attempted due to execution failure +2 | Gitleaks succeeded and leaks were present during the audit #### Examples ```bash gitleaks ``` -Run audit on current working directory if `.git` is present | +Run audit on current working directory if `.git` is present + +```bash +gitleaks --local $HOME/audits/some/repo +``` +Run audit on repo located in `HOME/audits/some/repo` if `.git` is present ```bash gitleaks https://github.com/some/repo From 2fd1d44e0a7e01fddb5c795ae4703433bc424bae Mon Sep 17 00:00:00 2001 From: zricethezav Date: Sun, 4 Mar 2018 20:26:41 -0600 Subject: [PATCH 16/16] actually fixing table --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 7fa48fb6..32b0c928 100644 --- a/README.md +++ b/README.md @@ -41,13 +41,14 @@ Options: ``` #### Exit Codes -Use these codes to hook gitleaks into whatever pipeline you're running code | explanation -------------|------------- 0 | Gitleaks succeeded with no leaks 1 | Gitleaks failed or wasn't attempted due to execution failure 2 | Gitleaks succeeded and leaks were present during the audit +Use these codes to hook gitleaks into whatever pipeline you're running + #### Examples ```bash gitleaks