From 256ace38d737abcb4800a33384b5ec8ed5bd65ba Mon Sep 17 00:00:00 2001 From: zach rice Date: Thu, 11 Apr 2019 18:06:18 -0500 Subject: [PATCH 1/8] workin on new filters --- src/config.go | 85 ++++++++++++++++++++++++-------------------- src/constants.go | 49 ++++---------------------- src/core.go | 22 ++++++------ src/entropy.go | 27 -------------- src/github.go | 10 +++--- src/gitlab.go | 4 +-- src/options.go | 27 +++++--------- src/repo.go | 14 ++++---- src/utils.go | 92 +++++++++++++++++++++++++++--------------------- 9 files changed, 139 insertions(+), 191 deletions(-) diff --git a/src/config.go b/src/config.go index c825ac35..388b43b6 100644 --- a/src/config.go +++ b/src/config.go @@ -9,6 +9,7 @@ import ( "strings" "github.com/BurntSushi/toml" + log "github.com/sirupsen/logrus" "gopkg.in/src-d/go-git.v4/plumbing/transport/ssh" ) @@ -17,20 +18,23 @@ type entropyRange struct { v2 float64 } -type Regex struct { +// Rule instructs how gitleaks should audit each line of code +type Rule struct { description string regex *regexp.Regexp + severity string + tags []string + entropies []*entropyRange } // TomlConfig is used for loading gitleaks configs from a toml file type TomlConfig struct { - Regexes []struct { + Rules []struct { Description string Regex string - } - Entropy struct { - LineRegexes []string - Ranges []string + Entropies []string + Tags []string + Severity string } Whitelist struct { Files []string @@ -42,17 +46,13 @@ type TomlConfig struct { // Config contains gitleaks config type Config struct { - Regexes []Regex + Rules []*Rule WhiteList struct { regexes []*regexp.Regexp files []*regexp.Regexp commits map[string]bool repos []*regexp.Regexp } - Entropy struct { - entropyRanges []*entropyRange - regexes []*regexp.Regexp - } sshAuth *ssh.PublicKeys } @@ -104,31 +104,39 @@ func newConfig() (*Config, error) { // updateConfig will update a the global config values func (config *Config) update(tomlConfig TomlConfig) error { - if len(tomlConfig.Entropy.Ranges) != 0 { - err := config.updateEntropyRanges(tomlConfig.Entropy.Ranges) + for _, rule := range tomlConfig.Rules { + re := regexp.MustCompile(rule.Regex) + ranges, err := getEntropyRanges(rule.Entropies) if err != nil { - return err + log.Errorf("could not create entropy range for %s, skipping rule", rule.Description) + continue } - } - - for _, regex := range tomlConfig.Entropy.LineRegexes { - config.Entropy.regexes = append(config.Entropy.regexes, regexp.MustCompile(regex)) - } - - if singleSearchRegex != nil { - config.Regexes = append(config.Regexes, Regex{ - description: "single search", - regex: singleSearchRegex, - }) - } else { - for _, regex := range tomlConfig.Regexes { - config.Regexes = append(config.Regexes, Regex{ - description: regex.Description, - regex: regexp.MustCompile(regex.Regex), - }) + r := &Rule{ + description: rule.Description, + regex: re, + severity: rule.Severity, + tags: rule.Tags, + entropies: ranges, } + config.Rules = append(config.Rules, r) } + // set stand alone rules from opts + if opts.Entropy != 0.0 { + ranges, err := getEntropyRanges([]string{fmt.Sprintf("0.0-%s", opts.Entropy)}) + if err != nil { + log.Fatalf("could not create entropy range for %s", opts.Entropy) + } + r := &Rule{ + description: "Entropy ", + severity: "5", + tags: []string{"entropy"}, + entropies: ranges, + } + config.Rules = append(config.Rules, r) + } + + // set whitelists config.WhiteList.commits = make(map[string]bool) for _, commit := range tomlConfig.Whitelist.Commits { config.WhiteList.commits[commit] = true @@ -147,30 +155,31 @@ func (config *Config) update(tomlConfig TomlConfig) error { } // entropyRanges hydrates entropyRanges which allows for fine tuning entropy checking -func (config *Config) updateEntropyRanges(entropyLimitStr []string) error { +func getEntropyRanges(entropyLimitStr []string) ([]*entropyRange, error) { + var ranges []*entropyRange for _, span := range entropyLimitStr { split := strings.Split(span, "-") v1, err := strconv.ParseFloat(split[0], 64) if err != nil { - return err + return nil, err } v2, err := strconv.ParseFloat(split[1], 64) if err != nil { - return err + return nil, err } if v1 > v2 { - return fmt.Errorf("entropy range must be ascending") + return nil, fmt.Errorf("entropy range must be ascending") } r := &entropyRange{ v1: v1, v2: v2, } if r.v1 > 8.0 || r.v1 < 0.0 || r.v2 > 8.0 || r.v2 < 0.0 { - return fmt.Errorf("invalid entropy ranges, must be within 0.0-8.0") + return nil, fmt.Errorf("invalid entropy ranges, must be within 0.0-8.0") } - config.Entropy.entropyRanges = append(config.Entropy.entropyRanges, r) + ranges = append(ranges, r) } - return nil + return ranges, nil } // externalConfig will attempt to load a pinned ".gitleaks.toml" configuration file diff --git a/src/constants.go b/src/constants.go index 74184c6e..1f374ec7 100644 --- a/src/constants.go +++ b/src/constants.go @@ -1,6 +1,6 @@ package gitleaks -const version = "1.25.1" +const version = "2.0.0" const defaultGithubURL = "https://api.github.com/" const defaultThreadNum = 1 @@ -14,49 +14,14 @@ const defaultConfig = ` # configurations from that path. Gitleaks does not whitelist anything by default. title = "gitleaks config" -# add regexes to the regex table -[[regexes]] +# add rules to the rule table +[[rules]] description = "AWS" regex = '''AKIA[0-9A-Z]{16}''' -[[regexes]] -description = "PKCS8" -regex = '''-----BEGIN PRIVATE KEY-----''' -[[regexes]] -description = "RSA" -regex = '''-----BEGIN RSA PRIVATE KEY-----''' -[[regexes]] -description = "SSH" -regex = '''-----BEGIN OPENSSH PRIVATE KEY-----''' -[[regexes]] -description = "PGP" -regex = '''-----BEGIN PGP PRIVATE KEY BLOCK-----''' -[[regexes]] -description = "Facebook" -regex = '''(?i)facebook(.{0,4})?['\"][0-9a-f]{32}['\"]''' -[[regexes]] -description = "Twitter" -regex = '''(?i)twitter(.{0,4})?['\"][0-9a-zA-Z]{35,44}['\"]''' -[[regexes]] -description = "Github" -regex = '''(?i)github(.{0,4})?['\"][0-9a-zA-Z]{35,40}['\"]''' -[[regexes]] -description = "Slack" -regex = '''xox[baprs]-([0-9a-zA-Z]{10,48})?''' - -[entropy] -lineregexes = [ - "api", - "key", - "signature", - "secret", - "password", - "pass", - "pwd", - "token", - "curl", - "wget", - "https?", -] +tags = ["key", "AWS"] +entropies = [ "3.3-4.30" ] +filetypes = [ "*.go" ] +severity = "5" [whitelist] files = [ diff --git a/src/core.go b/src/core.go index 5bb02cbb..5fbfe076 100644 --- a/src/core.go +++ b/src/core.go @@ -3,7 +3,6 @@ package gitleaks import ( "io/ioutil" "os" - "regexp" "strings" "sync" "time" @@ -13,15 +12,14 @@ import ( ) var ( - opts *Options - config *Config - singleSearchRegex *regexp.Regexp - dir string - threads int - totalCommits int64 - commitMap = make(map[string]bool) - auditDone bool - mutex = &sync.Mutex{} + opts *Options + config *Config + dir string + threads int + totalCommits int64 + commitMap = make(map[string]bool) + auditDone bool + mutex = &sync.Mutex{} ) func init() { @@ -31,7 +29,7 @@ func init() { // Report is type Report struct { - Leaks []Leak + Leaks []*Leak Duration string Commits int64 } @@ -39,7 +37,7 @@ type Report struct { // Run is the entry point for gitleaks func Run(optsL *Options) (*Report, error) { var ( - leaks []Leak + leaks []*Leak err error ) diff --git a/src/entropy.go b/src/entropy.go index a2c20b20..2a7f439f 100644 --- a/src/entropy.go +++ b/src/entropy.go @@ -23,30 +23,3 @@ func getShannonEntropy(data string) (entropy float64) { return entropy } - -func entropyIsHighEnough(entropy float64) bool { - if entropy >= opts.Entropy && len(config.Entropy.entropyRanges) == 0 { - return true - } - - for _, eR := range config.Entropy.entropyRanges { - if entropy > eR.v1 && entropy < eR.v2 { - return true - } - } - - return false -} - -func highEntropyLineIsALeak(line string) bool { - if !opts.NoiseReduction { - return true - } - for _, re := range config.Entropy.regexes { - if re.FindString(line) != "" { - return true - } - } - - return false -} diff --git a/src/github.go b/src/github.go index 424ee47f..0450b7c0 100644 --- a/src/github.go +++ b/src/github.go @@ -21,8 +21,8 @@ import ( var githubPages = 100 // auditPR audits a single github PR -func auditGithubPR() ([]Leak, error) { - var leaks []Leak +func auditGithubPR() ([]*Leak, error) { + var leaks []*Leak ctx := context.Background() githubClient := github.NewClient(githubToken()) splits := strings.Split(opts.GithubPR, "/") @@ -66,7 +66,7 @@ func auditGithubPR() ([]Leak, error) { continue } - commit := commitInfo{ + commit := &commitInfo{ sha: c.GetSHA(), content: *f.Patch, filePath: *f.Filename, @@ -91,7 +91,7 @@ func auditGithubPR() ([]Leak, error) { // First, we gather all the github repositories from the github api (this doesnt actually clone the repo). // After all the repos have been pulled from github's api we proceed to audit the repos by calling auditGithubRepo. // If an error occurs during an audit of a repo, that error is logged but won't break the execution cycle. -func auditGithubRepos() ([]Leak, error) { +func auditGithubRepos() ([]*Leak, error) { var ( err error githubRepos []*github.Repository @@ -100,7 +100,7 @@ func auditGithubRepos() ([]Leak, error) { githubOrgOptions *github.RepositoryListByOrgOptions githubOptions *github.RepositoryListOptions done bool - leaks []Leak + leaks []*Leak ownerDir string ) ctx := context.Background() diff --git a/src/gitlab.go b/src/gitlab.go index 79a2cefe..1e2f5457 100644 --- a/src/gitlab.go +++ b/src/gitlab.go @@ -17,11 +17,11 @@ const gitlabPages = 100 // auditGitlabRepos kicks off audits if --gitlab-user or --gitlab-org options are set. // Getting all repositories from the GitLab API and run audit. If an error occurs during an audit of a repo, // that error is logged. -func auditGitlabRepos() ([]Leak, error) { +func auditGitlabRepos() ([]*Leak, error) { var ( ps []*gitlab.Project resp *gitlab.Response - leaks []Leak + leaks []*Leak tempDir string err error ) diff --git a/src/options.go b/src/options.go index 27054c9b..dc6e17ac 100644 --- a/src/options.go +++ b/src/options.go @@ -6,7 +6,6 @@ import ( "net/url" "os" "path/filepath" - "regexp" "runtime" "strings" "time" @@ -36,16 +35,14 @@ type Options struct { OwnerPath string `long:"owner-path" description:"Path to owner directory (repos discovered)"` // Process options - Threads int `long:"threads" description:"Maximum number of threads gitleaks spawns"` - Disk bool `long:"disk" description:"Clones repo(s) to disk"` - SingleSearch string `long:"single-search" description:"single regular expression to search for"` - ConfigPath string `long:"config" description:"path to gitleaks config"` - SSHKey string `long:"ssh-key" description:"path to ssh key"` - ExcludeForks bool `long:"exclude-forks" description:"exclude forks for organization/user audits"` - Entropy float64 `long:"entropy" short:"e" description:"Include entropy checks during audit. Entropy scale: 0.0(no entropy) - 8.0(max entropy)"` - NoiseReduction bool `long:"noise-reduction" description:"Reduce the number of finds when entropy checks are enabled"` - RepoConfig bool `long:"repo-config" description:"Load config from target repo. Config file must be \".gitleaks.toml\""` - Branch string `long:"branch" description:"Branch to audit"` + Threads int `long:"threads" description:"Maximum number of threads gitleaks spawns"` + Disk bool `long:"disk" description:"Clones repo(s) to disk"` + ConfigPath string `long:"config" description:"path to gitleaks config"` + SSHKey string `long:"ssh-key" description:"path to ssh key"` + ExcludeForks bool `long:"exclude-forks" description:"exclude forks for organization/user audits"` + Entropy float64 `long:"entropy" short:"e" description:"Include entropy checks during audit. Entropy scale: 0.0(no entropy) - 8.0(max entropy)"` + RepoConfig bool `long:"repo-config" description:"Load config from target repo. Config file must be \".gitleaks.toml\""` + Branch string `long:"branch" description:"Branch to audit"` // TODO: IncludeMessages string `long:"messages" description:"include commit messages in audit"` // Output options @@ -95,7 +92,6 @@ func ParseOpts() *Options { // optsGuard prevents invalid options func (opts *Options) guard() error { - var err error if opts.GithubOrg != "" && opts.GithubUser != "" { return fmt.Errorf("github user and organization set") } else if opts.GithubOrg != "" && opts.OwnerPath != "" { @@ -129,13 +125,6 @@ func (opts *Options) guard() error { } } - if opts.SingleSearch != "" { - singleSearchRegex, err = regexp.Compile(opts.SingleSearch) - if err != nil { - return fmt.Errorf("unable to compile regex: %s, %v", opts.SingleSearch, err) - } - } - if opts.Entropy > 8 { return fmt.Errorf("The maximum level of entropy is 8") } diff --git a/src/repo.go b/src/repo.go index e9db2eb5..8202659f 100644 --- a/src/repo.go +++ b/src/repo.go @@ -30,6 +30,8 @@ type Leak struct { File string `json:"file"` Repo string `json:"repo"` Date time.Time `json:"date"` + Tags string `json:"tags"` + Severity string `json:"severity"` } // RepoInfo contains a src-d git repository and other data about the repo @@ -104,10 +106,10 @@ func (repoInfo *RepoInfo) clone() error { } // audit performs an audit -func (repoInfo *RepoInfo) audit() ([]Leak, error) { +func (repoInfo *RepoInfo) audit() ([]*Leak, error) { var ( err error - leaks []Leak + leaks []*Leak commitCount int64 commitWg sync.WaitGroup semaphore chan bool @@ -248,7 +250,7 @@ func (repoInfo *RepoInfo) audit() ([]Leak, error) { chunks := f.Chunks() for _, chunk := range chunks { if chunk.Type() == diffType.Add || chunk.Type() == diffType.Delete { - diff := commitInfo{ + diff := &commitInfo{ repoName: repoInfo.name, filePath: filePath, content: chunk.Content(), @@ -279,8 +281,8 @@ func (repoInfo *RepoInfo) audit() ([]Leak, error) { return leaks, nil } -func (repoInfo *RepoInfo) auditSingleCommit(c *object.Commit) []Leak { - var leaks []Leak +func (repoInfo *RepoInfo) auditSingleCommit(c *object.Commit) []*Leak { + var leaks []*Leak fIter, err := c.Files() if err != nil { return nil @@ -300,7 +302,7 @@ func (repoInfo *RepoInfo) auditSingleCommit(c *object.Commit) []Leak { if err != nil { return nil } - diff := commitInfo{ + diff := &commitInfo{ repoName: repoInfo.name, filePath: f.Name, content: content, diff --git a/src/utils.go b/src/utils.go index baabe10d..68a6bcde 100644 --- a/src/utils.go +++ b/src/utils.go @@ -28,7 +28,7 @@ type commitInfo struct { // writeReport writes a report to a file specified in the --report= option. // Default format for report is JSON. You can use the --csv option to write the report as a csv -func writeReport(leaks []Leak) error { +func writeReport(leaks []*Leak) error { if len(leaks) == 0 { return nil } @@ -82,46 +82,59 @@ func writeReport(leaks []Leak) error { return nil } +// check rule will inspect a single line and return a leak if it encounters one +func (rule *Rule) check(line string, commit *commitInfo) (*Leak, error) { + var ( + match string + entropy float64 + entropyWord string + ) + + if rule.entropies != nil { + words := strings.Fields(line) + for _, word := range words { + _entropy := getShannonEntropy(word) + for _, e := range rule.entropies { + if _entropy > e.v1 && _entropy < e.v2 { + entropy = _entropy + entropyWord = word + } + } + } + } + + if rule.regex != nil { + match = rule.regex.FindString(line) + } + + if match != "" && entropy != 0.0 { + return newLeak(line, entropyWord, rule, commit), nil + } else if match != "" && rule.entropies == nil { + return newLeak(line, match, rule, commit), nil + } else if entropy != 0.0 && rule.regex == nil { + return newLeak(line, entropyWord, rule, commit), nil + } + return nil, nil +} + // inspect will parse each line of the git diff's content against a set of regexes or // a set of regexes set by the config (see gitleaks.toml for example). This function // will skip lines that include a whitelisted regex. A list of leaks is returned. // If verbose mode (-v/--verbose) is set, then checkDiff will log leaks as they are discovered. -func inspect(commit commitInfo) []Leak { - var ( - leaks []Leak - skipLine bool - ) +func inspect(commit *commitInfo) []*Leak { + var leaks []*Leak lines := strings.Split(commit.content, "\n") for _, line := range lines { - skipLine = false - for _, re := range config.Regexes { - match := re.regex.FindString(line) - if match == "" { - continue - } - if skipLine = isLineWhitelisted(line); skipLine { + for _, rule := range config.Rules { + if isLineWhitelisted(line) { break } - leaks = addLeak(leaks, line, match, re.description, commit) - } - - if !skipLine && (opts.Entropy > 0 || len(config.Entropy.entropyRanges) != 0) { - words := strings.Fields(line) - for _, word := range words { - entropy := getShannonEntropy(word) - // Only check entropyRegexes and whiteListRegexes once per line, and only if an entropy leak type - // was found above, since regex checks are expensive. - if !entropyIsHighEnough(entropy) { - continue - } - // If either the line is whitelisted or the line fails the noiseReduction check (when enabled), - // then we can skip checking the rest of the line for high entropy words. - if skipLine = !highEntropyLineIsALeak(line) || isLineWhitelisted(line); skipLine { - break - } - leaks = addLeak(leaks, line, word, fmt.Sprintf("Entropy: %.2f", entropy), commit) + leak, err := rule.check(line, commit) + if err != nil { + continue } + leaks = append(leaks, leak) } } return leaks @@ -138,31 +151,30 @@ func isLineWhitelisted(line string) bool { return false } -// addLeak is helper for func inspect() to append leaks if found during a diff check. -func addLeak(leaks []Leak, line string, offender string, leakType string, commit commitInfo) []Leak { - leak := Leak{ +func newLeak(line string, msg string, rule *Rule, commit *commitInfo) *Leak { + leak := &Leak{ Line: line, Commit: commit.sha, - Offender: offender, - Type: leakType, + Offender: msg, + Type: rule.description, Author: commit.author, Email: commit.email, File: commit.filePath, Repo: commit.repoName, Message: commit.message, Date: commit.date, + Tags: strings.Join(rule.tags, ", "), + Severity: rule.severity, } if opts.Redact { leak.Offender = "REDACTED" - leak.Line = strings.Replace(line, offender, "REDACTED", -1) + leak.Line = strings.Replace(line, msg, "REDACTED", -1) } if opts.Verbose { leak.log() } - - leaks = append(leaks, leak) - return leaks + return leak } // discoverRepos walks all the children of `path`. If a child directory From 7bd55e33b504f76fc2aec27f4f479a5fb2606480 Mon Sep 17 00:00:00 2001 From: zach rice Date: Sat, 13 Apr 2019 12:30:00 -0500 Subject: [PATCH 2/8] working tests out --- src/.gitleaks_test.go.swp | Bin 0 -> 32768 bytes src/config.go | 32 +++++++------ src/constants.go | 52 ++++++++++++++++++-- src/core.go | 11 +++-- src/github.go | 8 ++-- src/gitlab.go | 4 +- src/gitleaks_test.go | 97 +++++++------------------------------- src/options.go | 8 ++-- src/repo.go | 11 +++-- src/utils.go | 62 ++++++++++++++---------- 10 files changed, 144 insertions(+), 141 deletions(-) create mode 100644 src/.gitleaks_test.go.swp diff --git a/src/.gitleaks_test.go.swp b/src/.gitleaks_test.go.swp new file mode 100644 index 0000000000000000000000000000000000000000..51c4caddf75ca1037bba996ff5ab02c6a607dec9 GIT binary patch literal 32768 zcmeI536vaVoxqzU9D@Ra;Cdjh=v{D9bx)I??xwmr z2N+aDa7ATNIl>}OiMV*caw)`Jb;T#zxQL(Rn=epzyEjsk1FCF8J(kI^ap6A=lS>q2xA{W`2geAu( z`HZeww_s@b@Pf`oy*-`1wJ*Lz71*B6w-@b1dphHcmEy5Pe!N{BcgC!X%&l@bYnfY$ z-ZkpWd5%?dV(EPCvYTg`8fa>ujs{9jYC-Q&k?yX}4!P>DqbD1$KW=@UA2d%jHPF;R zQv*#6G&RuFKvM%v4Ky{-)WH8Y4LF6vBJZP8v)qc^>;65Y;_spE_v_ui_f?!f%>90a z`*)37fLG4p?(rMlzdx-wKgT_OmHW5o3grEMwtIZY{X5G&;GK65H~%y>(9}Rv15FJy zHPF;RQv*#6G&RuFKvM%v4Ky{-)Ib#tn8`@wD2^X0_B8Q-&;Ebmm`LP#_$BOzeefWB z8}`8Mup9m!Zh)Pz2~LC8!O?IOyl^ySz&^MO?u1)l7i@tHq+taNzydfLj)FtrC4_q( zeg)6MGw?mQA8v=M;Nx&9Y=d#w0vQ;Cm2d{c;21a>X2I`XOPTO2JPl95_uzim4cEYj z;bPbU+u&?i4Q+4|91F+5QSkh0B9SNHTW~jg9zF**!)M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AWS" +description = "AWS Key" regex = '''AKIA[0-9A-Z]{16}''' tags = ["key", "AWS"] -entropies = [ "3.3-4.30" ] -filetypes = [ "*.go" ] -severity = "5" + +[[rules]] +description = "PKCS8" +regex = '''-----BEGIN PRIVATE KEY-----''' +tags = ["key", "PKCS8"] + +[[rules]] +description = "RSA" +regex = '''-----BEGIN RSA PRIVATE KEY-----''' +tags = ["key", "RSA"] + +[[rules]] +description = "SSH" +regex = '''-----BEGIN OPENSSH PRIVATE KEY-----''' +tags = ["key", "SSH"] + +[[rules]] +description = "PGP" +regex = '''-----BEGIN PGP PRIVATE KEY BLOCK-----''' +tags = ["key", "PGP"] + +[[rules]] +description = "Facebook" +regex = '''(?i)facebook(.{0,4})?['\"][0-9a-f]{32}['\"]''' +tags = ["key", "Facebook"] + +[[rules]] +description = "Twitter" +regex = '''(?i)twitter(.{0,4})?['\"][0-9a-zA-Z]{35,44}['\"]''' +tags = ["key", "Twitter"] + +[[rules]] +description = "Github" +regex = '''(?i)github(.{0,4})?['\"][0-9a-zA-Z]{35,40}['\"]''' +tags = ["key", "Github"] + +[[rules]] +description = "Slack" +regex = '''xox[baprs]-([0-9a-zA-Z]{10,48})?''' +tags = ["key", "Slack"] [whitelist] files = [ diff --git a/src/core.go b/src/core.go index 5fbfe076..7adf321c 100644 --- a/src/core.go +++ b/src/core.go @@ -27,9 +27,10 @@ func init() { threads = defaultThreadNum } -// Report is +// Report can be exported as a json or csv. Used for logging informationn +// about the audit, (duration and # of commits) type Report struct { - Leaks []*Leak + Leaks []Leak Duration string Commits int64 } @@ -37,7 +38,7 @@ type Report struct { // Run is the entry point for gitleaks func Run(optsL *Options) (*Report, error) { var ( - leaks []*Leak + leaks []Leak err error ) @@ -47,6 +48,10 @@ func Run(optsL *Options) (*Report, error) { if err != nil { return nil, err } + if opts.ValidateConfig { + log.Info("valid gitleaks config") + return nil, nil + } if opts.Disk { // temporary directory where all the gitleaks plain clones will reside diff --git a/src/github.go b/src/github.go index 0450b7c0..e8cba876 100644 --- a/src/github.go +++ b/src/github.go @@ -21,8 +21,8 @@ import ( var githubPages = 100 // auditPR audits a single github PR -func auditGithubPR() ([]*Leak, error) { - var leaks []*Leak +func auditGithubPR() ([]Leak, error) { + var leaks []Leak ctx := context.Background() githubClient := github.NewClient(githubToken()) splits := strings.Split(opts.GithubPR, "/") @@ -91,7 +91,7 @@ func auditGithubPR() ([]*Leak, error) { // First, we gather all the github repositories from the github api (this doesnt actually clone the repo). // After all the repos have been pulled from github's api we proceed to audit the repos by calling auditGithubRepo. // If an error occurs during an audit of a repo, that error is logged but won't break the execution cycle. -func auditGithubRepos() ([]*Leak, error) { +func auditGithubRepos() ([]Leak, error) { var ( err error githubRepos []*github.Repository @@ -100,7 +100,7 @@ func auditGithubRepos() ([]*Leak, error) { githubOrgOptions *github.RepositoryListByOrgOptions githubOptions *github.RepositoryListOptions done bool - leaks []*Leak + leaks []Leak ownerDir string ) ctx := context.Background() diff --git a/src/gitlab.go b/src/gitlab.go index 1e2f5457..79a2cefe 100644 --- a/src/gitlab.go +++ b/src/gitlab.go @@ -17,11 +17,11 @@ const gitlabPages = 100 // auditGitlabRepos kicks off audits if --gitlab-user or --gitlab-org options are set. // Getting all repositories from the GitLab API and run audit. If an error occurs during an audit of a repo, // that error is logged. -func auditGitlabRepos() ([]*Leak, error) { +func auditGitlabRepos() ([]Leak, error) { var ( ps []*gitlab.Project resp *gitlab.Response - leaks []*Leak + leaks []Leak tempDir string err error ) diff --git a/src/gitleaks_test.go b/src/gitleaks_test.go index 2b651f46..96da8eb3 100644 --- a/src/gitleaks_test.go +++ b/src/gitleaks_test.go @@ -17,7 +17,7 @@ import ( ) const testWhitelistCommit = ` -[[regexes]] +[[rules]] description = "AWS" regex = '''AKIA[0-9A-Z]{16}''' @@ -27,7 +27,7 @@ commits = [ ] ` const testWhitelistFile = ` -[[regexes]] +[[rules]] description = "AWS" regex = '''AKIA[0-9A-Z]{16}''' @@ -38,7 +38,7 @@ files = [ ` const testWhitelistRegex = ` -[[regexes]] +[[rules]] description = "AWS" regex = '''AKIA[0-9A-Z]{16}''' @@ -49,7 +49,7 @@ regexes= [ ` const testWhitelistRepo = ` -[[regexes]] +[[rules]] description = "AWS" regex = '''AKIA[0-9A-Z]{16}''' @@ -60,34 +60,24 @@ repos = [ ` const testEntropyRange = ` -[entropy] -ranges = [ +[[rules]] +description = "Entropy ranges" +entropies = [ "7.5-8.0", "3.2-3.4", ] -lineregexes = [ - "(?i)api", - "(?i)key", - "signature", - "secret", - "password", - "pass", - "pwd", - "token", - "curl", - "wget", - "https?", -] ` const testBadEntropyRange = ` -[entropy] -ranges = [ +[[rules]] +description = "Bad entropy ranges" +entropies = [ "8.0-3.0", ] ` const testBadEntropyRange2 = ` -[entropy] -ranges = [ +[[rules]] +description = "Bad entropy ranges" +entropies = [ "8.0-8.9", ] ` @@ -373,7 +363,7 @@ func TestWriteReport(t *testing.T) { Line: "eat", Commit: "your", Offender: "veggies", - Type: "and", + Rule: "and", Message: "get", Author: "some", File: "sleep", @@ -630,23 +620,6 @@ func TestAuditRepo(t *testing.T) { testOpts: &Options{}, configPath: path.Join(configsDir, "repo"), }, - { - repo: leaksRepo, - description: "leaks present with entropy", - testOpts: &Options{ - Entropy: 4.7, - }, - numLeaks: 6, - }, - { - repo: leaksRepo, - description: "leaks present with entropy", - testOpts: &Options{ - Entropy: 4.7, - NoiseReduction: true, - }, - numLeaks: 2, - }, { repo: leaksRepo, description: "Audit until specific commit", @@ -666,7 +639,7 @@ func TestAuditRepo(t *testing.T) { { repo: leaksRepo, description: "toml entropy range from opts", - numLeaks: 454, + numLeaks: 426, testOpts: &Options{ ConfigPath: path.Join(configsDir, "entropy"), }, @@ -674,19 +647,10 @@ func TestAuditRepo(t *testing.T) { { repo: leaksRepo, description: "toml entropy range", - numLeaks: 454, + numLeaks: 426, testOpts: &Options{}, configPath: path.Join(configsDir, "entropy"), }, - { - repo: leaksRepo, - testOpts: &Options{ - NoiseReduction: true, - }, - description: "toml entropy noise reduction range", - numLeaks: 64, - configPath: path.Join(configsDir, "entropy"), - }, { repo: leaksRepo, description: "toml bad entropy range", @@ -775,30 +739,6 @@ func TestOptionGuard(t *testing.T) { description: "local and remote target", expectedErrMsg: "github user set and local owner path", }, - { - testOpts: &Options{ - GithubUser: "fakeUser", - SingleSearch: "*/./....", - }, - description: "single search invalid regex gaurd", - expectedErrMsgFuzzy: "unable to compile regex: */./...., ", - }, - { - testOpts: &Options{ - GithubUser: "fakeUser", - SingleSearch: "mystring", - }, - description: "single search regex gaurd", - expectedErrMsg: "", - }, - { - testOpts: &Options{ - GithubOrg: "fakeOrg", - Entropy: 9, - }, - description: "Invalid entropy level guard", - expectedErrMsg: "The maximum level of entropy is 8", - }, } g := goblin.Goblin(t) for _, test := range tests { @@ -880,11 +820,6 @@ func TestLoadToml(t *testing.T) { g.Describe("TestLoadToml", func() { g.It(test.description, func() { opts = test.testOpts - if test.singleSearch { - singleSearchRegex = regexp.MustCompile("test") - } else { - singleSearchRegex = nil - } if test.configPath != "" { os.Setenv("GITLEAKS_CONFIG", test.configPath) } else { diff --git a/src/options.go b/src/options.go index dc6e17ac..8fd8956a 100644 --- a/src/options.go +++ b/src/options.go @@ -40,7 +40,6 @@ type Options struct { ConfigPath string `long:"config" description:"path to gitleaks config"` SSHKey string `long:"ssh-key" description:"path to ssh key"` ExcludeForks bool `long:"exclude-forks" description:"exclude forks for organization/user audits"` - Entropy float64 `long:"entropy" short:"e" description:"Include entropy checks during audit. Entropy scale: 0.0(no entropy) - 8.0(max entropy)"` RepoConfig bool `long:"repo-config" description:"Load config from target repo. Config file must be \".gitleaks.toml\""` Branch string `long:"branch" description:"Branch to audit"` // TODO: IncludeMessages string `long:"messages" description:"include commit messages in audit"` @@ -52,6 +51,7 @@ type Options struct { Redact bool `long:"redact" description:"redact secrets from log messages and report"` Version bool `long:"version" description:"version number"` SampleConfig bool `long:"sample-config" description:"prints a sample config file"` + ValidateConfig bool `long:"validate-config" description:"validate gitleaks config"` } // ParseOpts parses the options @@ -125,9 +125,9 @@ func (opts *Options) guard() error { } } - if opts.Entropy > 8 { - return fmt.Errorf("The maximum level of entropy is 8") - } + // if opts.Entropy > 8 { + // return fmt.Errorf("The maximum level of entropy is 8") + // } if opts.Report != "" { if !strings.HasSuffix(opts.Report, ".json") && !strings.HasSuffix(opts.Report, ".csv") { return fmt.Errorf("Report should be a .json or .csv file") diff --git a/src/repo.go b/src/repo.go index 8202659f..d69976f7 100644 --- a/src/repo.go +++ b/src/repo.go @@ -23,7 +23,8 @@ type Leak struct { Line string `json:"line"` Commit string `json:"commit"` Offender string `json:"offender"` - Type string `json:"reason"` + Rule string `json:"rule"` + Info string `json:"info"` Message string `json:"commitMsg"` Author string `json:"author"` Email string `json:"email"` @@ -106,10 +107,10 @@ func (repoInfo *RepoInfo) clone() error { } // audit performs an audit -func (repoInfo *RepoInfo) audit() ([]*Leak, error) { +func (repoInfo *RepoInfo) audit() ([]Leak, error) { var ( err error - leaks []*Leak + leaks []Leak commitCount int64 commitWg sync.WaitGroup semaphore chan bool @@ -281,8 +282,8 @@ func (repoInfo *RepoInfo) audit() ([]*Leak, error) { return leaks, nil } -func (repoInfo *RepoInfo) auditSingleCommit(c *object.Commit) []*Leak { - var leaks []*Leak +func (repoInfo *RepoInfo) auditSingleCommit(c *object.Commit) []Leak { + var leaks []Leak fIter, err := c.Files() if err != nil { return nil diff --git a/src/utils.go b/src/utils.go index 68a6bcde..03f220ca 100644 --- a/src/utils.go +++ b/src/utils.go @@ -28,7 +28,7 @@ type commitInfo struct { // writeReport writes a report to a file specified in the --report= option. // Default format for report is JSON. You can use the --csv option to write the report as a csv -func writeReport(leaks []*Leak) error { +func writeReport(leaks []Leak) error { if len(leaks) == 0 { return nil } @@ -43,7 +43,7 @@ func writeReport(leaks []*Leak) error { w := csv.NewWriter(f) w.Write([]string{"repo", "line", "commit", "offender", "reason", "commitMsg", "author", "email", "file", "date"}) for _, leak := range leaks { - w.Write([]string{leak.Repo, leak.Line, leak.Commit, leak.Offender, leak.Type, leak.Message, leak.Author, leak.Email, leak.File, leak.Date.Format(time.RFC3339)}) + w.Write([]string{leak.Repo, leak.Line, leak.Commit, leak.Offender, leak.Rule, leak.Message, leak.Author, leak.Email, leak.File, leak.Date.Format(time.RFC3339)}) } w.Flush() } else { @@ -91,28 +91,41 @@ func (rule *Rule) check(line string, commit *commitInfo) (*Leak, error) { ) if rule.entropies != nil { - words := strings.Fields(line) - for _, word := range words { - _entropy := getShannonEntropy(word) - for _, e := range rule.entropies { - if _entropy > e.v1 && _entropy < e.v2 { - entropy = _entropy - entropyWord = word - } - } - } + if rule.entropyROI == "line" { + _entropy := getShannonEntropy(line) + for _, e := range rule.entropies { + if _entropy > e.v1 && _entropy < e.v2 { + entropy = _entropy + entropyWord = line + goto postEntropy + } + } + } else { + words := strings.Fields(line) + for _, word := range words { + _entropy := getShannonEntropy(word) + for _, e := range rule.entropies { + if _entropy > e.v1 && _entropy < e.v2 { + entropy = _entropy + entropyWord = word + goto postEntropy + } + } + } + } } +postEntropy: if rule.regex != nil { match = rule.regex.FindString(line) } if match != "" && entropy != 0.0 { - return newLeak(line, entropyWord, rule, commit), nil + return newLeak(line, fmt.Sprintf("%s regex match and entropy met at %.2f", rule.regex.String(), entropy), entropyWord, rule, commit), nil } else if match != "" && rule.entropies == nil { - return newLeak(line, match, rule, commit), nil - } else if entropy != 0.0 && rule.regex == nil { - return newLeak(line, entropyWord, rule, commit), nil + return newLeak(line, fmt.Sprintf("%s regex match", rule.regex.String()), match, rule, commit), nil + } else if entropy != 0.0 && rule.regex.String() == "" { + return newLeak(line, fmt.Sprintf("entropy met at %.2f", entropy), entropyWord, rule, commit), nil } return nil, nil } @@ -121,8 +134,8 @@ func (rule *Rule) check(line string, commit *commitInfo) (*Leak, error) { // a set of regexes set by the config (see gitleaks.toml for example). This function // will skip lines that include a whitelisted regex. A list of leaks is returned. // If verbose mode (-v/--verbose) is set, then checkDiff will log leaks as they are discovered. -func inspect(commit *commitInfo) []*Leak { - var leaks []*Leak +func inspect(commit *commitInfo) []Leak { + var leaks []Leak lines := strings.Split(commit.content, "\n") for _, line := range lines { @@ -131,10 +144,10 @@ func inspect(commit *commitInfo) []*Leak { break } leak, err := rule.check(line, commit) - if err != nil { + if err != nil || leak == nil { continue } - leaks = append(leaks, leak) + leaks = append(leaks, *leak) } } return leaks @@ -151,12 +164,13 @@ func isLineWhitelisted(line string) bool { return false } -func newLeak(line string, msg string, rule *Rule, commit *commitInfo) *Leak { +func newLeak(line string, info string, offender string, rule *Rule, commit *commitInfo) *Leak { leak := &Leak{ Line: line, Commit: commit.sha, - Offender: msg, - Type: rule.description, + Offender: offender, + Rule: rule.description, + Info: info, Author: commit.author, Email: commit.email, File: commit.filePath, @@ -168,7 +182,7 @@ func newLeak(line string, msg string, rule *Rule, commit *commitInfo) *Leak { } if opts.Redact { leak.Offender = "REDACTED" - leak.Line = strings.Replace(line, msg, "REDACTED", -1) + leak.Line = strings.Replace(line, offender, "REDACTED", -1) } if opts.Verbose { From c4da54750333e8937f6764937f96e2cc31d48347 Mon Sep 17 00:00:00 2001 From: zach rice Date: Sat, 13 Apr 2019 13:12:58 -0500 Subject: [PATCH 3/8] fmt --- README.md | 3 -- gitleaks.toml | 85 ++++++++++++++++++++++++++------------ src/.gitleaks_test.go.swp | Bin 32768 -> 0 bytes src/config.go | 22 ++-------- src/constants.go | 23 ++++------- src/core.go | 8 ++-- src/options.go | 28 ++++++------- src/repo.go | 4 +- src/utils.go | 50 +++++++++++----------- 9 files changed, 114 insertions(+), 109 deletions(-) delete mode 100644 src/.gitleaks_test.go.swp diff --git a/README.md b/README.md index 056bdb69..1c0f8b13 100644 --- a/README.md +++ b/README.md @@ -77,12 +77,9 @@ Application Options: --owner-path= Path to owner directory (repos discovered) --threads= Maximum number of threads gitleaks spawns --disk Clones repo(s) to disk - --single-search= single regular expression to search for --config= path to gitleaks config --ssh-key= path to ssh key --exclude-forks exclude forks for organization/user audits - -e, --entropy= Include entropy checks during audit. Entropy scale: 0.0(no entropy) - 8.0(max entropy) - --noise-reduction Reduce the number of finds when entropy checks are enabled --repo-config Load config from target repo. Config file must be ".gitleaks.toml" --branch= Branch to audit -l, --log= log level diff --git a/gitleaks.toml b/gitleaks.toml index 496fe77b..ad72b69e 100644 --- a/gitleaks.toml +++ b/gitleaks.toml @@ -1,39 +1,72 @@ -title = "gitleaks config" -[[regexes]] -description = "AWS" +title = "sample gitleaks config" + +# This is a sample config file for gitleaks. You can configure gitleaks what to search for and what to whitelist. +# The output you are seeing here is the default gitleaks config. If GITLEAKS_CONFIG environment variable +# is set, gitleaks will load configurations from that path. If option --config-path is set, gitleaks will load +# configurations from that path. Gitleaks does not whitelist anything by default. + +[[rules]] +description = "AWS Key" regex = '''AKIA[0-9A-Z]{16}''' -[[regexes]] -description = "RKCS8" +tags = ["key", "AWS"] + +[[rules]] +description = "PKCS8" regex = '''-----BEGIN PRIVATE KEY-----''' -[[regexes]] +tags = ["key", "PKCS8"] + +[[rules]] description = "RSA" regex = '''-----BEGIN RSA PRIVATE KEY-----''' -[[regexes]] -description = "Github" -regex = '''(?i)github.*['\"][0-9a-zA-Z]{35,40}['\"]''' -[[regexes]] +tags = ["key", "RSA"] + +[[rules]] description = "SSH" regex = '''-----BEGIN OPENSSH PRIVATE KEY-----''' -[[regexes]] -description = "Facebook" -regex = '''(?i)facebook.*['\"][0-9a-f]{32}['\"]''' -[[regexes]] -description = "Twitter" -regex = '''(?i)twitter.*['\"][0-9a-zA-Z]{35,44}['\"]''' -[[regexes]] +tags = ["key", "SSH"] + +[[rules]] description = "PGP" regex = '''-----BEGIN PGP PRIVATE KEY BLOCK-----''' -[[regexes]] -description = "Slack token" -regex = '''xox[baprs]-.*''' -[[regexes]] -description = "Strip API Key" -regex = '''(?i)(sk|pk)_(test|live)_[0-9a-zA-Z]{10,32}''' +tags = ["key", "PGP"] + +[[rules]] +description = "Facebook" +regex = '''(?i)facebook(.{0,4})?['\"][0-9a-f]{32}['\"]''' +tags = ["key", "Facebook"] + +[[rules]] +description = "Twitter" +regex = '''(?i)twitter(.{0,4})?['\"][0-9a-zA-Z]{35,44}['\"]''' +tags = ["key", "Twitter"] + +[[rules]] +description = "Github" +regex = '''(?i)github(.{0,4})?['\"][0-9a-zA-Z]{35,40}['\"]''' +tags = ["key", "Github"] + +[[rules]] +description = "Slack" +regex = '''xox[baprs]-([0-9a-zA-Z]{10,48})?''' +tags = ["key", "Slack"] [whitelist] -regexes = [ - # "AKIA.*EXAMPLE", -] files = [ "(.*?)(jpg|gif|doc|pdf|bin)$" ] +#commits = [ +# "whitelisted-commit1", +# "whitelisted-commit2", +#] +#repos = [ +# "whitelisted-repo" +#] + +# Additional Examples +# [[rules]] +# description = "Generic Key" +# regex = '''(?i)key(.{0,6})?(:|=|=>|:=)''' +# entropies = ["4.1-4.3"] +# entropyROI = "line" +# tags = ["key"] + diff --git a/src/.gitleaks_test.go.swp b/src/.gitleaks_test.go.swp deleted file mode 100644 index 51c4caddf75ca1037bba996ff5ab02c6a607dec9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 32768 zcmeI536vaVoxqzU9D@Ra;Cdjh=v{D9bx)I??xwmr z2N+aDa7ATNIl>}OiMV*caw)`Jb;T#zxQL(Rn=epzyEjsk1FCF8J(kI^ap6A=lS>q2xA{W`2geAu( z`HZeww_s@b@Pf`oy*-`1wJ*Lz71*B6w-@b1dphHcmEy5Pe!N{BcgC!X%&l@bYnfY$ z-ZkpWd5%?dV(EPCvYTg`8fa>ujs{9jYC-Q&k?yX}4!P>DqbD1$KW=@UA2d%jHPF;R zQv*#6G&RuFKvM%v4Ky{-)WH8Y4LF6vBJZP8v)qc^>;65Y;_spE_v_ui_f?!f%>90a z`*)37fLG4p?(rMlzdx-wKgT_OmHW5o3grEMwtIZY{X5G&;GK65H~%y>(9}Rv15FJy zHPF;RQv*#6G&RuFKvM%v4Ky{-)Ib#tn8`@wD2^X0_B8Q-&;Ebmm`LP#_$BOzeefWB z8}`8Mup9m!Zh)Pz2~LC8!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q80+b8El+gk`fvUt2e3TV|5X8QlZRO7S&PWv-dfme~v&W8Oz|OHD=TJVV@+K4p)sB?w z?M2ZTHw&BeT{gQ9sQI@NhmyPwph__^n|:=)''' -# entropies = ["4.1-4.3"] -# entropyROI = "line" -# tags = ["key"] - [[rules]] description = "AWS Key" regex = '''AKIA[0-9A-Z]{16}''' @@ -72,15 +68,10 @@ files = [ "(.*?)(jpg|gif|doc|pdf|bin)$" ] #commits = [ -# "BADHA5H1", -# "BADHA5H2", +# "whitelisted-commit1", +# "whitelisted-commit2", #] #repos = [ -# "mygoodrepo" -#] -[misc] -#entropy = [ -# "3.3-4.30" -# "6.0-8.0 +# "whitelisted-repo" #] ` diff --git a/src/core.go b/src/core.go index 7adf321c..a2ffead3 100644 --- a/src/core.go +++ b/src/core.go @@ -48,10 +48,10 @@ func Run(optsL *Options) (*Report, error) { if err != nil { return nil, err } - if opts.ValidateConfig { - log.Info("valid gitleaks config") - return nil, nil - } + if opts.ValidateConfig { + log.Info("valid gitleaks config") + return nil, nil + } if opts.Disk { // temporary directory where all the gitleaks plain clones will reside diff --git a/src/options.go b/src/options.go index 8fd8956a..fd0d34c5 100644 --- a/src/options.go +++ b/src/options.go @@ -35,23 +35,23 @@ type Options struct { OwnerPath string `long:"owner-path" description:"Path to owner directory (repos discovered)"` // Process options - Threads int `long:"threads" description:"Maximum number of threads gitleaks spawns"` - Disk bool `long:"disk" description:"Clones repo(s) to disk"` - ConfigPath string `long:"config" description:"path to gitleaks config"` - SSHKey string `long:"ssh-key" description:"path to ssh key"` - ExcludeForks bool `long:"exclude-forks" description:"exclude forks for organization/user audits"` - RepoConfig bool `long:"repo-config" description:"Load config from target repo. Config file must be \".gitleaks.toml\""` - Branch string `long:"branch" description:"Branch to audit"` + Threads int `long:"threads" description:"Maximum number of threads gitleaks spawns"` + Disk bool `long:"disk" description:"Clones repo(s) to disk"` + ConfigPath string `long:"config" description:"path to gitleaks config"` + SSHKey string `long:"ssh-key" description:"path to ssh key"` + ExcludeForks bool `long:"exclude-forks" description:"exclude forks for organization/user audits"` + RepoConfig bool `long:"repo-config" description:"Load config from target repo. Config file must be \".gitleaks.toml\""` + Branch string `long:"branch" description:"Branch to audit"` // TODO: IncludeMessages string `long:"messages" description:"include commit messages in audit"` // Output options - Log string `short:"l" long:"log" description:"log level"` - Verbose bool `short:"v" long:"verbose" description:"Show verbose output from gitleaks audit"` - Report string `long:"report" description:"path to write report file. Needs to be csv or json"` - Redact bool `long:"redact" description:"redact secrets from log messages and report"` - Version bool `long:"version" description:"version number"` - SampleConfig bool `long:"sample-config" description:"prints a sample config file"` - ValidateConfig bool `long:"validate-config" description:"validate gitleaks config"` + Log string `short:"l" long:"log" description:"log level"` + Verbose bool `short:"v" long:"verbose" description:"Show verbose output from gitleaks audit"` + Report string `long:"report" description:"path to write report file. Needs to be csv or json"` + Redact bool `long:"redact" description:"redact secrets from log messages and report"` + Version bool `long:"version" description:"version number"` + SampleConfig bool `long:"sample-config" description:"prints a sample config file"` + ValidateConfig bool `long:"validate-config" description:"validate gitleaks config"` } // ParseOpts parses the options diff --git a/src/repo.go b/src/repo.go index d69976f7..09822eee 100644 --- a/src/repo.go +++ b/src/repo.go @@ -23,8 +23,8 @@ type Leak struct { Line string `json:"line"` Commit string `json:"commit"` Offender string `json:"offender"` - Rule string `json:"rule"` - Info string `json:"info"` + Rule string `json:"rule"` + Info string `json:"info"` Message string `json:"commitMsg"` Author string `json:"author"` Email string `json:"email"` diff --git a/src/utils.go b/src/utils.go index 03f220ca..adc12902 100644 --- a/src/utils.go +++ b/src/utils.go @@ -41,9 +41,9 @@ func writeReport(leaks []Leak) error { } defer f.Close() w := csv.NewWriter(f) - w.Write([]string{"repo", "line", "commit", "offender", "reason", "commitMsg", "author", "email", "file", "date"}) + w.Write([]string{"repo", "line", "commit", "offender", "rule", "info", "tags", "commitMsg", "author", "email", "file", "date"}) for _, leak := range leaks { - w.Write([]string{leak.Repo, leak.Line, leak.Commit, leak.Offender, leak.Rule, leak.Message, leak.Author, leak.Email, leak.File, leak.Date.Format(time.RFC3339)}) + w.Write([]string{leak.Repo, leak.Line, leak.Commit, leak.Offender, leak.Rule, leak.Info, leak.Tags, leak.Message, leak.Author, leak.Email, leak.File, leak.Date.Format(time.RFC3339)}) } w.Flush() } else { @@ -91,28 +91,28 @@ func (rule *Rule) check(line string, commit *commitInfo) (*Leak, error) { ) if rule.entropies != nil { - if rule.entropyROI == "line" { - _entropy := getShannonEntropy(line) - for _, e := range rule.entropies { - if _entropy > e.v1 && _entropy < e.v2 { - entropy = _entropy - entropyWord = line - goto postEntropy - } - } - } else { - words := strings.Fields(line) - for _, word := range words { - _entropy := getShannonEntropy(word) - for _, e := range rule.entropies { - if _entropy > e.v1 && _entropy < e.v2 { - entropy = _entropy - entropyWord = word - goto postEntropy - } - } - } - } + if rule.entropyROI == "line" { + _entropy := getShannonEntropy(line) + for _, e := range rule.entropies { + if _entropy > e.v1 && _entropy < e.v2 { + entropy = _entropy + entropyWord = line + goto postEntropy + } + } + } else { + words := strings.Fields(line) + for _, word := range words { + _entropy := getShannonEntropy(word) + for _, e := range rule.entropies { + if _entropy > e.v1 && _entropy < e.v2 { + entropy = _entropy + entropyWord = word + goto postEntropy + } + } + } + } } postEntropy: @@ -170,7 +170,7 @@ func newLeak(line string, info string, offender string, rule *Rule, commit *comm Commit: commit.sha, Offender: offender, Rule: rule.description, - Info: info, + Info: info, Author: commit.author, Email: commit.email, File: commit.filePath, From df8a2d35a81cf4bb8882dae404dcc3f1e0d0f923 Mon Sep 17 00:00:00 2001 From: zach rice Date: Sat, 13 Apr 2019 13:50:14 -0500 Subject: [PATCH 4/8] cleaning up --- Makefile | 5 ----- src/constants.go | 1 + src/options.go | 3 --- src/repo.go | 3 +++ 4 files changed, 4 insertions(+), 8 deletions(-) diff --git a/Makefile b/Makefile index f638fed7..b80fc6e2 100644 --- a/Makefile +++ b/Makefile @@ -20,8 +20,3 @@ build-all: env GOOS="linux" GOARCH="mips" go build -o "build/gitleaks-linux-mips" env GOOS="linux" GOARCH="mips" go build -o "build/gitleaks-linux-mips" env GOOS="darwin" GOARCH="amd64" go build -o "build/gitleaks-darwin-amd64" -benchmark: - go test -run=Benchmark -bench=. -benchtime=5s -benchmark-fast: - go test -bench=BenchmarkAuditLeakRepo -run=BenchmarkAuditLeakRepo$ - diff --git a/src/constants.go b/src/constants.go index 1b1689ff..efae08b5 100644 --- a/src/constants.go +++ b/src/constants.go @@ -67,6 +67,7 @@ tags = ["key", "Slack"] files = [ "(.*?)(jpg|gif|doc|pdf|bin)$" ] + #commits = [ # "whitelisted-commit1", # "whitelisted-commit2", diff --git a/src/options.go b/src/options.go index fd0d34c5..7f98f7f2 100644 --- a/src/options.go +++ b/src/options.go @@ -125,9 +125,6 @@ func (opts *Options) guard() error { } } - // if opts.Entropy > 8 { - // return fmt.Errorf("The maximum level of entropy is 8") - // } if opts.Report != "" { if !strings.HasSuffix(opts.Report, ".json") && !strings.HasSuffix(opts.Report, ".csv") { return fmt.Errorf("Report should be a .json or .csv file") diff --git a/src/repo.go b/src/repo.go index 09822eee..8de90870 100644 --- a/src/repo.go +++ b/src/repo.go @@ -85,6 +85,9 @@ func (repoInfo *RepoInfo) clone() error { } else if repoInfo.path != "" { log.Infof("opening %s", opts.RepoPath) repo, err = git.PlainOpen(repoInfo.path) + if err != nil { + log.Errorf("unable to open %s", opts.RepoPath) + } } else { // cloning to memory log.Infof("cloning %s", opts.Repo) From 87d6c588a614df26b8af251dc17534cb7a8d884d Mon Sep 17 00:00:00 2001 From: zach rice Date: Sat, 13 Apr 2019 14:09:16 -0500 Subject: [PATCH 5/8] removing validating config, already handled --- gitleaks.toml | 1 - src/core.go | 4 ---- src/options.go | 13 ++++++------- 3 files changed, 6 insertions(+), 12 deletions(-) diff --git a/gitleaks.toml b/gitleaks.toml index ad72b69e..eb812b59 100644 --- a/gitleaks.toml +++ b/gitleaks.toml @@ -4,7 +4,6 @@ title = "sample gitleaks config" # The output you are seeing here is the default gitleaks config. If GITLEAKS_CONFIG environment variable # is set, gitleaks will load configurations from that path. If option --config-path is set, gitleaks will load # configurations from that path. Gitleaks does not whitelist anything by default. - [[rules]] description = "AWS Key" regex = '''AKIA[0-9A-Z]{16}''' diff --git a/src/core.go b/src/core.go index a2ffead3..353a72ac 100644 --- a/src/core.go +++ b/src/core.go @@ -48,10 +48,6 @@ func Run(optsL *Options) (*Report, error) { if err != nil { return nil, err } - if opts.ValidateConfig { - log.Info("valid gitleaks config") - return nil, nil - } if opts.Disk { // temporary directory where all the gitleaks plain clones will reside diff --git a/src/options.go b/src/options.go index 7f98f7f2..75157958 100644 --- a/src/options.go +++ b/src/options.go @@ -45,13 +45,12 @@ type Options struct { // TODO: IncludeMessages string `long:"messages" description:"include commit messages in audit"` // Output options - Log string `short:"l" long:"log" description:"log level"` - Verbose bool `short:"v" long:"verbose" description:"Show verbose output from gitleaks audit"` - Report string `long:"report" description:"path to write report file. Needs to be csv or json"` - Redact bool `long:"redact" description:"redact secrets from log messages and report"` - Version bool `long:"version" description:"version number"` - SampleConfig bool `long:"sample-config" description:"prints a sample config file"` - ValidateConfig bool `long:"validate-config" description:"validate gitleaks config"` + Log string `short:"l" long:"log" description:"log level"` + Verbose bool `short:"v" long:"verbose" description:"Show verbose output from gitleaks audit"` + Report string `long:"report" description:"path to write report file. Needs to be csv or json"` + Redact bool `long:"redact" description:"redact secrets from log messages and report"` + Version bool `long:"version" description:"version number"` + SampleConfig bool `long:"sample-config" description:"prints a sample config file"` } // ParseOpts parses the options From cb74386ef04ccbae8dca63f273e74d2f071488ff Mon Sep 17 00:00:00 2001 From: zach rice Date: Sat, 13 Apr 2019 16:48:57 -0500 Subject: [PATCH 6/8] working on filetype filtering --- src/config.go | 17 ++++++++++++++++- src/constants.go | 16 ++++++++++++++++ src/repo.go | 21 +++++++++++++++++++++ src/utils.go | 16 ++++++++++++++-- 4 files changed, 67 insertions(+), 3 deletions(-) diff --git a/src/config.go b/src/config.go index 03adb9a9..99fdb585 100644 --- a/src/config.go +++ b/src/config.go @@ -26,6 +26,7 @@ type Rule struct { tags []string entropies []*entropyRange entropyROI string + fileTypes []*regexp.Regexp } // TomlConfig is used for loading gitleaks configs from a toml file @@ -37,6 +38,7 @@ type TomlConfig struct { Tags []string Severity string EntropyROI string + FileTypes []string } Whitelist struct { Files []string @@ -55,7 +57,8 @@ type Config struct { commits map[string]bool repos []*regexp.Regexp } - sshAuth *ssh.PublicKeys + FileRules []*Rule + sshAuth *ssh.PublicKeys } // loadToml loads of the toml config containing regexes and whitelists. @@ -109,10 +112,16 @@ func (config *Config) update(tomlConfig TomlConfig) error { for _, rule := range tomlConfig.Rules { re := regexp.MustCompile(rule.Regex) ranges, err := getEntropyRanges(rule.Entropies) + var fileTypes = []*regexp.Regexp{} + for _, regex := range rule.FileTypes { + fileTypes = append(fileTypes, regexp.MustCompile(regex)) + } + if err != nil { log.Errorf("could not create entropy range for %s, skipping rule", rule.Description) continue } + r := &Rule{ description: rule.Description, regex: re, @@ -120,8 +129,14 @@ func (config *Config) update(tomlConfig TomlConfig) error { tags: rule.Tags, entropies: ranges, entropyROI: rule.EntropyROI, + fileTypes: fileTypes, + } + + if len(rule.Entropies) == 0 && rule.Regex == "" && len(fileTypes) != 0 { + config.FileRules = append(config.FileRules, r) } config.Rules = append(config.Rules, r) + } // set whitelists diff --git a/src/constants.go b/src/constants.go index efae08b5..52dedefc 100644 --- a/src/constants.go +++ b/src/constants.go @@ -22,6 +22,7 @@ title = "gitleaks config" description = "AWS Key" regex = '''AKIA[0-9A-Z]{16}''' tags = ["key", "AWS"] +severity = "high" [[rules]] description = "PKCS8" @@ -63,6 +64,21 @@ description = "Slack" regex = '''xox[baprs]-([0-9a-zA-Z]{10,48})?''' tags = ["key", "Slack"] +[[rules]] +description = "Generic Key" +regex = '''(?i)key(.{0,6})?(:|=|=>|:=)''' +entropies = ["4.1-4.3"] +filetypes = [".gee"] +entropyROI = "line" +tags = ["key"] +severity = "medium" + +[[rules]] +description = "Any go file" +filetypes = [".go"] +tags = ["go files"] +severity = "low" + [whitelist] files = [ "(.*?)(jpg|gif|doc|pdf|bin)$" diff --git a/src/repo.go b/src/repo.go index 8de90870..52389836 100644 --- a/src/repo.go +++ b/src/repo.go @@ -241,6 +241,27 @@ func (repoInfo *RepoInfo) audit() ([]Leak, error) { } else if to != nil { filePath = to.Path() } + + for _, fr := range config.FileRules { + for _, r := range fr.fileTypes { + if r.FindString(filePath) != "" { + commitInfo := &commitInfo{ + repoName: repoInfo.name, + filePath: filePath, + sha: c.Hash.String(), + author: c.Author.Name, + email: c.Author.Email, + message: strings.Replace(c.Message, "\n", " ", -1), + date: c.Author.When, + } + leak := *newLeak("N/A", fmt.Sprintf("filetype %s found", r.String()), r.String(), fr, commitInfo) + mutex.Lock() + leaks = append(leaks, leak) + mutex.Unlock() + } + } + } + for _, re := range config.WhiteList.files { if re.FindString(filePath) != "" { log.Debugf("skipping whitelisted file (matched regex '%s'): %s", re.String(), filePath) diff --git a/src/utils.go b/src/utils.go index adc12902..6a1fa40c 100644 --- a/src/utils.go +++ b/src/utils.go @@ -41,9 +41,9 @@ func writeReport(leaks []Leak) error { } defer f.Close() w := csv.NewWriter(f) - w.Write([]string{"repo", "line", "commit", "offender", "rule", "info", "tags", "commitMsg", "author", "email", "file", "date"}) + w.Write([]string{"repo", "line", "commit", "offender", "rule", "info", "tags", "severity", "commitMsg", "author", "email", "file", "date"}) for _, leak := range leaks { - w.Write([]string{leak.Repo, leak.Line, leak.Commit, leak.Offender, leak.Rule, leak.Info, leak.Tags, leak.Message, leak.Author, leak.Email, leak.File, leak.Date.Format(time.RFC3339)}) + w.Write([]string{leak.Repo, leak.Line, leak.Commit, leak.Offender, leak.Rule, leak.Info, leak.Tags, leak.Severity, leak.Message, leak.Author, leak.Email, leak.File, leak.Date.Format(time.RFC3339)}) } w.Flush() } else { @@ -86,10 +86,22 @@ func writeReport(leaks []Leak) error { func (rule *Rule) check(line string, commit *commitInfo) (*Leak, error) { var ( match string + fileMatch string entropy float64 entropyWord string ) + for _, f := range rule.fileTypes { + fileMatch = f.FindString(commit.filePath) + if fileMatch != "" { + break + } + } + + if fileMatch == "" && len(rule.fileTypes) != 0 { + return nil, nil + } + if rule.entropies != nil { if rule.entropyROI == "line" { _entropy := getShannonEntropy(line) From 2e7325ce03f767732d8b6341c130ff194aa5551a Mon Sep 17 00:00:00 2001 From: zach rice Date: Tue, 16 Apr 2019 12:04:00 -0500 Subject: [PATCH 7/8] adding some more tests during lunch --- CHANGELOG.md | 6 ++ gitleaks.toml | 18 +++++- src/constants.go | 17 +----- src/constants_test.go | 124 ++++++++++++++++++++++++++++++++++++++++++ src/gitleaks_test.go | 117 +++++++++++---------------------------- 5 files changed, 179 insertions(+), 103 deletions(-) create mode 100644 src/constants_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 5fbf13ce..df425602 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ CHANGELOG ========= +2.0.0 +---- +- rules introduced in the gitleaks configurationn +- removing `--entropy` option +- removing `--single-search` option + 1.25.1 ---- - Fixing #188 diff --git a/gitleaks.toml b/gitleaks.toml index eb812b59..dc8ac508 100644 --- a/gitleaks.toml +++ b/gitleaks.toml @@ -62,10 +62,26 @@ files = [ #] # Additional Examples + # [[rules]] # description = "Generic Key" # regex = '''(?i)key(.{0,6})?(:|=|=>|:=)''' # entropies = ["4.1-4.3"] # entropyROI = "line" # tags = ["key"] - +# severity = "8" +# +# [[rules]] +# description = "Generic Key" +# regex = '''(?i)key(.{0,6})?(:|=|=>|:=)''' +# entropies = ["4.1-4.3"] +# filetypes = [".gee"] +# entropyROI = "line" +# tags = ["key"] +# severity = "medium" +# +# [[rules]] +# description = "Any go file" +# filetypes = [".go"] +# tags = ["go files"] +# severity = "low" diff --git a/src/constants.go b/src/constants.go index 52dedefc..5483b4be 100644 --- a/src/constants.go +++ b/src/constants.go @@ -14,7 +14,7 @@ const LeakExit = 1 const defaultConfig = ` # This is a sample config file for gitleaks. You can configure gitleaks what to search for and what to whitelist. # The output you are seeing here is the default gitleaks config. If GITLEAKS_CONFIG environment variable -# is set, gitleaks will load configurations from that path. If option --config-path is set, gitleaks will load +# is set, gitleaks will load configurations from that path. If option --config is set, gitleaks will load # configurations from that path. Gitleaks does not whitelist anything by default. title = "gitleaks config" @@ -64,21 +64,6 @@ description = "Slack" regex = '''xox[baprs]-([0-9a-zA-Z]{10,48})?''' tags = ["key", "Slack"] -[[rules]] -description = "Generic Key" -regex = '''(?i)key(.{0,6})?(:|=|=>|:=)''' -entropies = ["4.1-4.3"] -filetypes = [".gee"] -entropyROI = "line" -tags = ["key"] -severity = "medium" - -[[rules]] -description = "Any go file" -filetypes = [".go"] -tags = ["go files"] -severity = "low" - [whitelist] files = [ "(.*?)(jpg|gif|doc|pdf|bin)$" diff --git a/src/constants_test.go b/src/constants_test.go new file mode 100644 index 00000000..c637f0e5 --- /dev/null +++ b/src/constants_test.go @@ -0,0 +1,124 @@ +package gitleaks + +import ( + "io/ioutil" + "path" +) + +const testWhitelistCommit = ` +[[rules]] +description = "AWS" +regex = '''AKIA[0-9A-Z]{16}''' + +[whitelist] +commits = [ + "eaeffdc65b4c73ccb67e75d96bd8743be2c85973", +] +` +const testWhitelistFile = ` +[[rules]] +description = "AWS" +regex = '''AKIA[0-9A-Z]{16}''' + +[whitelist] +files = [ + ".go", +] +` + +const testWhitelistRegex = ` +[[rules]] +description = "AWS" +regex = '''AKIA[0-9A-Z]{16}''' + +[whitelist] +regexes= [ + "AKIA", +] +` + +const testWhitelistRepo = ` +[[rules]] +description = "AWS" +regex = '''AKIA[0-9A-Z]{16}''' + +[whitelist] +repos = [ + "gronit", +] +` + +const testEntropyRange = ` +[[rules]] +description = "Entropy ranges" +entropies = [ + "7.5-8.0", + "3.2-3.4", +] +` +const testBadEntropyRange = ` +[[rules]] +description = "Bad entropy ranges" +entropies = [ + "8.0-3.0", +] +` +const testBadEntropyRange2 = ` +[[rules]] +description = "Bad entropy ranges" +entropies = [ + "8.0-8.9", +] +` + +const testEntropyLineRegexRange = ` +[[rules]] +description = "test entropy regex ranges" +regex = '''(?i)key(.{0,6})?(:|=|=>|:=)''' +entropies = [ + "4.1-4.3", +] +entropyROI="line" +` + +const testEntropyRegexRange = ` +[[rules]] +description = "test entropy regex ranges" +regex = '''(?i)key(.{0,6})?(:|=|=>|:=)''' +entropies = [ + "4.1-4.3", +] +` + +const testMDFileType = ` +[[rules]] +description = "test only markdown" +filetypes = [".md"] +` + +const testEntropyRegexRangeGoFilter = ` +[[rules]] +description = "test entropy regex ranges" +regex = '''(?i)key(.{0,6})?(:|=|=>|:=)''' +entropies = [ + "4.1-4.3", +] +filetypes = [".go"] +entropyROI="line" +` + +func testTomlLoader() string { + tmpDir, _ := ioutil.TempDir("", "whiteListConfigs") + ioutil.WriteFile(path.Join(tmpDir, "regex"), []byte(testWhitelistRegex), 0644) + ioutil.WriteFile(path.Join(tmpDir, "entropyLineRegex"), []byte(testEntropyLineRegexRange), 0644) + ioutil.WriteFile(path.Join(tmpDir, "entropyRegex"), []byte(testEntropyRegexRange), 0644) + ioutil.WriteFile(path.Join(tmpDir, "commit"), []byte(testWhitelistCommit), 0644) + ioutil.WriteFile(path.Join(tmpDir, "file"), []byte(testWhitelistFile), 0644) + ioutil.WriteFile(path.Join(tmpDir, "repo"), []byte(testWhitelistRepo), 0644) + ioutil.WriteFile(path.Join(tmpDir, "entropy"), []byte(testEntropyRange), 0644) + ioutil.WriteFile(path.Join(tmpDir, "badEntropy"), []byte(testBadEntropyRange), 0644) + ioutil.WriteFile(path.Join(tmpDir, "badEntropy2"), []byte(testBadEntropyRange2), 0644) + ioutil.WriteFile(path.Join(tmpDir, "mdFiles"), []byte(testMDFileType), 0644) + ioutil.WriteFile(path.Join(tmpDir, "entropyLineRegexGo"), []byte(testEntropyRegexRangeGoFilter), 0644) + return tmpDir +} diff --git a/src/gitleaks_test.go b/src/gitleaks_test.go index 96da8eb3..0ad49d02 100644 --- a/src/gitleaks_test.go +++ b/src/gitleaks_test.go @@ -16,72 +16,6 @@ import ( "gopkg.in/src-d/go-git.v4/storage/memory" ) -const testWhitelistCommit = ` -[[rules]] -description = "AWS" -regex = '''AKIA[0-9A-Z]{16}''' - -[whitelist] -commits = [ - "eaeffdc65b4c73ccb67e75d96bd8743be2c85973", -] -` -const testWhitelistFile = ` -[[rules]] -description = "AWS" -regex = '''AKIA[0-9A-Z]{16}''' - -[whitelist] -files = [ - ".go", -] -` - -const testWhitelistRegex = ` -[[rules]] -description = "AWS" -regex = '''AKIA[0-9A-Z]{16}''' - -[whitelist] -regexes= [ - "AKIA", -] -` - -const testWhitelistRepo = ` -[[rules]] -description = "AWS" -regex = '''AKIA[0-9A-Z]{16}''' - -[whitelist] -repos = [ - "gronit", -] -` - -const testEntropyRange = ` -[[rules]] -description = "Entropy ranges" -entropies = [ - "7.5-8.0", - "3.2-3.4", -] -` -const testBadEntropyRange = ` -[[rules]] -description = "Bad entropy ranges" -entropies = [ - "8.0-3.0", -] -` -const testBadEntropyRange2 = ` -[[rules]] -description = "Bad entropy ranges" -entropies = [ - "8.0-8.9", -] -` - func TestGetRepo(t *testing.T) { var err error dir, err = ioutil.TempDir("", "gitleaksTestRepo") @@ -437,18 +371,6 @@ func TestWriteReport(t *testing.T) { } -func testTomlLoader() string { - tmpDir, _ := ioutil.TempDir("", "whiteListConfigs") - ioutil.WriteFile(path.Join(tmpDir, "regex"), []byte(testWhitelistRegex), 0644) - ioutil.WriteFile(path.Join(tmpDir, "commit"), []byte(testWhitelistCommit), 0644) - ioutil.WriteFile(path.Join(tmpDir, "file"), []byte(testWhitelistFile), 0644) - ioutil.WriteFile(path.Join(tmpDir, "repo"), []byte(testWhitelistRepo), 0644) - ioutil.WriteFile(path.Join(tmpDir, "entropy"), []byte(testEntropyRange), 0644) - ioutil.WriteFile(path.Join(tmpDir, "badEntropy"), []byte(testBadEntropyRange), 0644) - ioutil.WriteFile(path.Join(tmpDir, "badEntropy2"), []byte(testBadEntropyRange2), 0644) - return tmpDir -} - func TestAuditRepo(t *testing.T) { var leaks []Leak configsDir := testTomlLoader() @@ -651,6 +573,20 @@ func TestAuditRepo(t *testing.T) { testOpts: &Options{}, configPath: path.Join(configsDir, "entropy"), }, + { + repo: leaksRepo, + description: "toml entropy regex line range", + numLeaks: 2, + testOpts: &Options{}, + configPath: path.Join(configsDir, "entropyLineRegex"), + }, + { + repo: leaksRepo, + description: "toml entropy regex range", + numLeaks: 0, + testOpts: &Options{}, + configPath: path.Join(configsDir, "entropyRegex"), + }, { repo: leaksRepo, description: "toml bad entropy range", @@ -667,6 +603,20 @@ func TestAuditRepo(t *testing.T) { configPath: path.Join(configsDir, "badEntropy2"), expectedErrMsg: "invalid entropy ranges, must be within 0.0-8.0", }, + { + repo: leaksRepo, + description: "toml md files", + numLeaks: 5, + testOpts: &Options{}, + configPath: path.Join(configsDir, "mdFiles"), + }, + { + repo: leaksRepo, + description: "toml entropys line regex go", + numLeaks: 2, + testOpts: &Options{}, + configPath: path.Join(configsDir, "entropyLineRegexGo"), + }, } g := goblin.Goblin(t) for _, test := range tests { @@ -674,7 +624,6 @@ func TestAuditRepo(t *testing.T) { g.It(test.description, func() { auditDone = false opts = test.testOpts - totalCommits = 0 config, err = newConfig() // config paths @@ -687,14 +636,10 @@ func TestAuditRepo(t *testing.T) { } } leaks, err = test.repo.audit() - if test.testOpts.Depth != 0 { - g.Assert(totalCommits).Equal(test.testOpts.Depth) - } else { - if opts.Redact { - g.Assert(leaks[0].Offender).Equal("REDACTED") - } - g.Assert(len(leaks)).Equal(test.numLeaks) + if opts.Redact { + g.Assert(leaks[0].Offender).Equal("REDACTED") } + g.Assert(len(leaks)).Equal(test.numLeaks) next: os.Setenv("GITLEAKS_CONFIG", "") }) From 7dfa3f2b481aba1ef2225d83c9d870976ebd02bc Mon Sep 17 00:00:00 2001 From: zach rice Date: Tue, 16 Apr 2019 18:13:24 -0500 Subject: [PATCH 8/8] last updates? --- .gitignore | 2 +- gitleaks.toml | 17 +++++++++++------ src/constants_test.go | 9 ++++----- src/gitleaks_test.go | 19 ++++++------------- src/options.go | 6 +++--- src/utils.go | 20 ++++++++++---------- 6 files changed, 35 insertions(+), 38 deletions(-) diff --git a/.gitignore b/.gitignore index 2f51e5a2..03d149d9 100644 --- a/.gitignore +++ b/.gitignore @@ -9,4 +9,4 @@ *.test *.out -tmp +examples diff --git a/gitleaks.toml b/gitleaks.toml index dc8ac508..7f7966ab 100644 --- a/gitleaks.toml +++ b/gitleaks.toml @@ -66,11 +66,16 @@ files = [ # [[rules]] # description = "Generic Key" # regex = '''(?i)key(.{0,6})?(:|=|=>|:=)''' -# entropies = ["4.1-4.3"] +# entropies = [ +# "4.1-4.3", +# "5.5-6.3", +# ] # entropyROI = "line" +# filetypes = [".go", ".py", ".c"] # tags = ["key"] # severity = "8" # +# # [[rules]] # description = "Generic Key" # regex = '''(?i)key(.{0,6})?(:|=|=>|:=)''' @@ -79,9 +84,9 @@ files = [ # entropyROI = "line" # tags = ["key"] # severity = "medium" -# + # [[rules]] -# description = "Any go file" -# filetypes = [".go"] -# tags = ["go files"] -# severity = "low" +# description = "Any pem file" +# filetypes = [".key"] +# tags = ["pem"] +# severity = "high" diff --git a/src/constants_test.go b/src/constants_test.go index c637f0e5..73261049 100644 --- a/src/constants_test.go +++ b/src/constants_test.go @@ -71,14 +71,14 @@ entropies = [ ] ` -const testEntropyLineRegexRange = ` +const testEntropyWordRegexRange = ` [[rules]] description = "test entropy regex ranges" regex = '''(?i)key(.{0,6})?(:|=|=>|:=)''' entropies = [ "4.1-4.3", ] -entropyROI="line" +entropyROI="word" ` const testEntropyRegexRange = ` @@ -104,13 +104,12 @@ entropies = [ "4.1-4.3", ] filetypes = [".go"] -entropyROI="line" ` func testTomlLoader() string { tmpDir, _ := ioutil.TempDir("", "whiteListConfigs") ioutil.WriteFile(path.Join(tmpDir, "regex"), []byte(testWhitelistRegex), 0644) - ioutil.WriteFile(path.Join(tmpDir, "entropyLineRegex"), []byte(testEntropyLineRegexRange), 0644) + ioutil.WriteFile(path.Join(tmpDir, "entropyWordRegex"), []byte(testEntropyWordRegexRange), 0644) ioutil.WriteFile(path.Join(tmpDir, "entropyRegex"), []byte(testEntropyRegexRange), 0644) ioutil.WriteFile(path.Join(tmpDir, "commit"), []byte(testWhitelistCommit), 0644) ioutil.WriteFile(path.Join(tmpDir, "file"), []byte(testWhitelistFile), 0644) @@ -119,6 +118,6 @@ func testTomlLoader() string { ioutil.WriteFile(path.Join(tmpDir, "badEntropy"), []byte(testBadEntropyRange), 0644) ioutil.WriteFile(path.Join(tmpDir, "badEntropy2"), []byte(testBadEntropyRange2), 0644) ioutil.WriteFile(path.Join(tmpDir, "mdFiles"), []byte(testMDFileType), 0644) - ioutil.WriteFile(path.Join(tmpDir, "entropyLineRegexGo"), []byte(testEntropyRegexRangeGoFilter), 0644) + ioutil.WriteFile(path.Join(tmpDir, "entropyRegexGo"), []byte(testEntropyRegexRangeGoFilter), 0644) return tmpDir } diff --git a/src/gitleaks_test.go b/src/gitleaks_test.go index 0ad49d02..8fb587f0 100644 --- a/src/gitleaks_test.go +++ b/src/gitleaks_test.go @@ -561,29 +561,22 @@ func TestAuditRepo(t *testing.T) { { repo: leaksRepo, description: "toml entropy range from opts", - numLeaks: 426, + numLeaks: 266, testOpts: &Options{ ConfigPath: path.Join(configsDir, "entropy"), }, }, { repo: leaksRepo, - description: "toml entropy range", - numLeaks: 426, + description: "toml entropy regex word range", + numLeaks: 0, testOpts: &Options{}, - configPath: path.Join(configsDir, "entropy"), - }, - { - repo: leaksRepo, - description: "toml entropy regex line range", - numLeaks: 2, - testOpts: &Options{}, - configPath: path.Join(configsDir, "entropyLineRegex"), + configPath: path.Join(configsDir, "entropyWordRegex"), }, { repo: leaksRepo, description: "toml entropy regex range", - numLeaks: 0, + numLeaks: 2, testOpts: &Options{}, configPath: path.Join(configsDir, "entropyRegex"), }, @@ -615,7 +608,7 @@ func TestAuditRepo(t *testing.T) { description: "toml entropys line regex go", numLeaks: 2, testOpts: &Options{}, - configPath: path.Join(configsDir, "entropyLineRegexGo"), + configPath: path.Join(configsDir, "entropyRegexGo"), }, } g := goblin.Goblin(t) diff --git a/src/options.go b/src/options.go index 75157958..0e3505a9 100644 --- a/src/options.go +++ b/src/options.go @@ -60,13 +60,13 @@ func ParseOpts() *Options { _, err := parser.Parse() if err != nil { - if flagsErr, ok := err.(*flags.Error); ok && flagsErr.Type == flags.ErrHelp { - os.Exit(0) + if flagsErr, ok := err.(*flags.Error); ok && flagsErr.Type != flags.ErrHelp { + parser.WriteHelp(os.Stdout) } + os.Exit(0) } if len(os.Args) == 1 { - // TODO: this will be a feature, check locally parser.WriteHelp(os.Stdout) os.Exit(0) } diff --git a/src/utils.go b/src/utils.go index 6a1fa40c..5445abff 100644 --- a/src/utils.go +++ b/src/utils.go @@ -103,16 +103,7 @@ func (rule *Rule) check(line string, commit *commitInfo) (*Leak, error) { } if rule.entropies != nil { - if rule.entropyROI == "line" { - _entropy := getShannonEntropy(line) - for _, e := range rule.entropies { - if _entropy > e.v1 && _entropy < e.v2 { - entropy = _entropy - entropyWord = line - goto postEntropy - } - } - } else { + if rule.entropyROI == "word" { words := strings.Fields(line) for _, word := range words { _entropy := getShannonEntropy(word) @@ -124,6 +115,15 @@ func (rule *Rule) check(line string, commit *commitInfo) (*Leak, error) { } } } + } else { + _entropy := getShannonEntropy(line) + for _, e := range rule.entropies { + if _entropy > e.v1 && _entropy < e.v2 { + entropy = _entropy + entropyWord = line + goto postEntropy + } + } } }