more cleaning up

This commit is contained in:
Zach Rice committed 2022-03-11 15:00:31 -06:00
1 parent c9bc6b4608
commit 7bca6e757b
2 files changed
+119 -143

No files matched your search

+77 -47
View File
@@ -1,12 +1,17 @@
package cmd package cmd
import ( import (
"os"
"path/filepath"
"time"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/zricethezav/gitleaks/v8/config" "github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/detect" "github.com/zricethezav/gitleaks/v8/detect"
"github.com/zricethezav/gitleaks/v8/report"
) )
func init() { func init() {
@@ -24,9 +29,9 @@ var detectCmd = &cobra.Command{
func runDetect(cmd *cobra.Command, args []string) { func runDetect(cmd *cobra.Command, args []string) {
initConfig() initConfig()
var ( var (
vc config.ViperConfig vc config.ViperConfig
// findings []report.Finding findings []report.Finding
err error err error
) )
viper.Unmarshal(&vc) viper.Unmarshal(&vc)
@@ -36,56 +41,81 @@ func runDetect(cmd *cobra.Command, args []string) {
} }
cfg.Path, _ = cmd.Flags().GetString("config") cfg.Path, _ = cmd.Flags().GetString("config")
detector := detect.NewDetector(cfg) detector := detect.NewDetector(cfg)
detector.Start(cmd)
// source, _ := cmd.Flags().GetString("source") start := time.Now()
// logOpts, _ := cmd.Flags().GetString("log-opts")
// verbose, _ := cmd.Flags().GetBool("verbose")
// redact, _ := cmd.Flags().GetBool("redact")
// noGit, _ := cmd.Flags().GetBool("no-git")
// exitCode, _ := cmd.Flags().GetInt("exit-code")
// if cfg.Path == "" {
// cfg.Path = filepath.Join(source, ".gitleaks.toml")
// }
// start := time.Now()
// if noGit { detector.Config.Path, err = cmd.Flags().GetString("config")
// if logOpts != "" { if err != nil {
// log.Fatal().Err(err).Msg("--log-opts cannot be used with --no-git") log.Fatal().Err(err)
// } }
// findings, err = detect.FromFiles(source, cfg, detect.Options{
// Verbose: verbose,
// Redact: redact,
// })
// if err != nil {
// log.Fatal().Err(err).Msg("Failed to scan files")
// }
// } else {
// files, err := git.GitLog(source, logOpts)
// if err != nil {
// log.Fatal().Err(err).Msg("Failed to get git log")
// }
// findings = detect.FromGit(files, cfg, detect.Options{Verbose: verbose, Redact: redact}) source, err := cmd.Flags().GetString("source")
// } if err != nil {
log.Fatal().Err(err)
}
// if len(findings) != 0 { exitCode, err := cmd.Flags().GetInt("exit-code")
// log.Warn().Msgf("leaks found: %d", len(findings)) if err != nil {
// } else { log.Fatal().Err(err)
// log.Info().Msg("no leaks found") }
// }
// log.Info().Msgf("scan completed in %s", time.Since(start)) // if config path is not set, then use the {source}/.gitleaks.toml path.
// note that there may not be a `{source}/.gitleaks.toml` file, this is ok.
if detector.Config.Path == "" {
detector.Config.Path = filepath.Join(source, ".gitleaks.toml")
}
// reportPath, _ := cmd.Flags().GetString("report-path") // set verbose flag
// ext, _ := cmd.Flags().GetString("report-format") if detector.Verbose, err = cmd.Flags().GetBool("verbose"); err != nil {
// if reportPath != "" { log.Fatal().Err(err)
// report.Write(findings, cfg, ext, reportPath) }
// }
// if len(findings) != 0 { // set redact flag
// os.Exit(exitCode) if detector.Redact, err = cmd.Flags().GetBool("redact"); err != nil {
// } log.Fatal().Err(err)
}
noGit, err := cmd.Flags().GetBool("no-git")
if err != nil {
log.Fatal().Err(err)
}
if noGit {
// TODO treat the repo as a directory
findings, err = detector.DetectFiles(source)
if err != nil {
// don't exit on error, just log it
log.Error().Err(err)
}
} else {
logOpts, err := cmd.Flags().GetString("log-opts")
if err != nil {
log.Fatal().Err(err)
}
findings, err = detector.DetectGit(source, logOpts)
if err != nil {
// don't exit on error, just log it
log.Error().Err(err)
}
}
log.Info().Msgf("scan completed in %s", time.Since(start))
if len(findings) != 0 {
log.Warn().Msgf("leaks found: %d", len(findings))
} else {
log.Info().Msg("no leaks found")
}
reportPath, _ := cmd.Flags().GetString("report-path")
ext, _ := cmd.Flags().GetString("report-format")
if reportPath != "" {
report.Write(findings, cfg, ext, reportPath)
}
if len(findings) != 0 {
os.Exit(exitCode)
}
} }
+42 -96
View File
@@ -8,7 +8,6 @@ import (
"regexp" "regexp"
"strings" "strings"
"sync" "sync"
"time"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
"github.com/zricethezav/gitleaks/v8/config" "github.com/zricethezav/gitleaks/v8/config"
@@ -17,7 +16,6 @@ import (
"github.com/fatih/semgroup" "github.com/fatih/semgroup"
"github.com/gitleaks/go-gitdiff/gitdiff" "github.com/gitleaks/go-gitdiff/gitdiff"
"github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
) )
@@ -32,7 +30,7 @@ type Detector struct {
Redact bool Redact bool
// verbose is a flag to print findings // verbose is a flag to print findings
verbose bool Verbose bool
// commitMap is used to keep track of commits that have been scanned. // commitMap is used to keep track of commits that have been scanned.
// This is only used for logging purposes and git scans. // This is only used for logging purposes and git scans.
@@ -48,15 +46,15 @@ type Detector struct {
findings []report.Finding findings []report.Finding
} }
// Fragment contains the data to be scanned. Other names to consider: segment, section, part // Fragment contains the data to be scanned
type Fragment struct { type Fragment struct {
// Raw is the raw content of the fragment // Raw is the raw content of the fragment
Raw string Raw string
// FilePath is the path to the file // FilePath is the path to the file if applicable
FilePath string FilePath string
// CommitSHA is the SHA of the commit // CommitSHA is the SHA of the commit if applicable
CommitSHA string CommitSHA string
// newlineIndices is a list of indices of newlines in the raw content. // newlineIndices is a list of indices of newlines in the raw content.
@@ -87,68 +85,6 @@ func NewDetectorDefaultConfig() (*Detector, error) {
return NewDetector(cfg), nil return NewDetector(cfg), nil
} }
// Start is called from cmd
func (d *Detector) Start(cmd *cobra.Command) ([]report.Finding, error) {
var (
findings []report.Finding
err error
)
start := time.Now()
d.Config.Path, err = cmd.Flags().GetString("config")
if err != nil {
return findings, err
}
source, err := cmd.Flags().GetString("source")
if err != nil {
return findings, err
}
// if config path is not set, then use the {source}/.gitleaks.toml path.
// note that there may not be a `{source}/.gitleaks.toml` file, this is ok.
if d.Config.Path == "" {
d.Config.Path = filepath.Join(source, ".gitleaks.toml")
}
// set verbose flag
if d.verbose, err = cmd.Flags().GetBool("verbose"); err != nil {
return findings, err
}
// set redact flag
if d.Redact, err = cmd.Flags().GetBool("redact"); err != nil {
return findings, err
}
noGit, err := cmd.Flags().GetBool("no-git")
if err != nil {
return findings, err
}
if noGit {
// TODO treat the repo as a directory
} else {
logOpts, err := cmd.Flags().GetString("log-opts")
if err != nil {
return findings, err
}
history, err := git.GitLog(source, logOpts)
if err != nil {
return findings, err
}
d.startGitScan(history)
}
log.Info().Msgf("scan completed in %s", time.Since(start))
// TODO generate report, check exit code, etc
// exitCode, err := cmd.Flags().GetInt("exit-code")
return findings, nil
}
// DetectBytes scans the given bytes and returns a list of findings // DetectBytes scans the given bytes and returns a list of findings
func (d *Detector) DetectBytes(content []byte) []report.Finding { func (d *Detector) DetectBytes(content []byte) []report.Finding {
return d.DetectString(string(content)) return d.DetectString(string(content))
@@ -161,25 +97,6 @@ func (d *Detector) DetectString(content string) []report.Finding {
}) })
} }
// Detect scans the given fragment and returns a list of findings
func (d *Detector) Detect(fragment Fragment) []report.Finding {
var findings []report.Finding
// check if filepath is allowed
if d.Config.Allowlist.PathAllowed(fragment.FilePath) ||
fragment.FilePath == d.Config.Path {
return findings
}
// add newline indices for location calculation in detectRule
fragment.newlineIndices = regexp.MustCompile("\n").FindAllStringIndex(fragment.Raw, -1)
for _, rule := range d.Config.Rules {
findings = append(findings, d.detectRule(fragment, rule)...)
}
return filter(findings, d.Redact)
}
// detectRule scans the given fragment for the given rule and returns a list of findings // detectRule scans the given fragment for the given rule and returns a list of findings
func (d *Detector) detectRule(fragment Fragment, rule *config.Rule) []report.Finding { func (d *Detector) detectRule(fragment Fragment, rule *config.Rule) []report.Finding {
var findings []report.Finding var findings []report.Finding
@@ -254,7 +171,7 @@ func (d *Detector) detectRule(fragment Fragment, rule *config.Rule) []report.Fin
// check entropy // check entropy
finding.Entropy = float32(shannonEntropy(secret)) finding.Entropy = float32(shannonEntropy(secret))
if rule.EntropySet() && finding.Entropy < float32(rule.Entropy) { if rule.EntropySet() && finding.Entropy <= float32(rule.Entropy) {
// entropy is too low, skip this finding // entropy is too low, skip this finding
return findings return findings
} }
@@ -264,13 +181,18 @@ func (d *Detector) detectRule(fragment Fragment, rule *config.Rule) []report.Fin
return findings return findings
} }
// startGitScan accepts a *gitdiff.File channel which contents a git history generated from // GitScan accepts a *gitdiff.File channel which contents a git history generated from
// the output of `git log -p ...`. startGitScan will look at each file (patch) in the history // the output of `git log -p ...`. startGitScan will look at each file (patch) in the history
// and determine if the patch contains any findings. // and determine if the patch contains any findings.
func (d *Detector) startGitScan(gitdiffFiles <-chan *gitdiff.File) { func (d *Detector) DetectGit(source string, logOpts string) ([]report.Finding, error) {
history, err := git.GitLog(source, logOpts)
if err != nil {
return d.findings, err
}
s := semgroup.NewGroup(context.Background(), 4) s := semgroup.NewGroup(context.Background(), 4)
for gitdiffFile := range gitdiffFiles { for gitdiffFile := range history {
gitdiffFile := gitdiffFile gitdiffFile := gitdiffFile
// skip binary files // skip binary files
@@ -309,12 +231,13 @@ func (d *Detector) startGitScan(gitdiffFiles <-chan *gitdiff.File) {
} }
if err := s.Wait(); err != nil { if err := s.Wait(); err != nil {
fmt.Println(err) return d.findings, err
} }
log.Debug().Msgf("%d commits scanned. Note: this number might be smaller than expected due to commits with no additions", len(d.commitMap))
return d.findings, nil
} }
func (d *Detector) startFileScan(source string) []report.Finding { func (d *Detector) DetectFiles(source string) ([]report.Finding, error) {
var findings []report.Finding
s := semgroup.NewGroup(context.Background(), 4) s := semgroup.NewGroup(context.Background(), 4)
paths := make(chan string) paths := make(chan string)
s.Go(func() error { s.Go(func() error {
@@ -352,14 +275,37 @@ func (d *Detector) startFileScan(source string) []report.Finding {
}) })
} }
return findings if err := s.Wait(); err != nil {
return d.findings, err
}
return d.findings, nil
}
// Detect scans the given fragment and returns a list of findings
func (d *Detector) Detect(fragment Fragment) []report.Finding {
var findings []report.Finding
// check if filepath is allowed
if d.Config.Allowlist.PathAllowed(fragment.FilePath) ||
fragment.FilePath == d.Config.Path {
return findings
}
// add newline indices for location calculation in detectRule
fragment.newlineIndices = regexp.MustCompile("\n").FindAllStringIndex(fragment.Raw, -1)
for _, rule := range d.Config.Rules {
findings = append(findings, d.detectRule(fragment, rule)...)
}
return filter(findings, d.Redact)
} }
// addFinding synchronously adds a finding to the findings slice // addFinding synchronously adds a finding to the findings slice
func (d *Detector) addFinding(finding report.Finding) { func (d *Detector) addFinding(finding report.Finding) {
d.findingMutex.Lock() d.findingMutex.Lock()
d.findings = append(d.findings, finding) d.findings = append(d.findings, finding)
if d.verbose { if d.Verbose {
printFinding(finding) printFinding(finding)
} }
d.findingMutex.Unlock() d.findingMutex.Unlock()