diff --git a/detect/detect.go b/detect/detect.go index 61a4bd0e..abb36203 100644 --- a/detect/detect.go +++ b/detect/detect.go @@ -18,15 +18,20 @@ import ( "github.com/fatih/semgroup" "github.com/gitleaks/go-gitdiff/gitdiff" "github.com/spf13/cobra" + "github.com/spf13/viper" ) // Detector is the main detector struct type Detector struct { - // cfg is the configuration for the detector - cfg config.Config + // Config is the configuration for the detector + Config config.Config - redact bool + // Redact is a flag to redact findings. This is exported + // so users using gitleaks as a library can set this flag + // without calling `detector.Start(cmd *cobra.Command)` + Redact bool + // verbose is a flag to print findings verbose bool // commitMap is used to keep track of commits that have been scanned. @@ -37,6 +42,9 @@ type Detector struct { // findings slice when adding findings. findingMutex *sync.Mutex + // findings is a slice of report.Findings. This is the result + // of the detector's scan which can then be used to generate a + // report. findings []report.Finding } @@ -51,26 +59,32 @@ type Fragment struct { // CommitSHA is the SHA of the commit CommitSHA string - // RuleID is the ID of the rule that is to be used. If no RuleID is set then the entire - // rule set will be used - RuleID string - + // newlineIndices is a list of indices of newlines in the raw content. + // This is used to calculate the line location of a finding newlineIndices [][]int } +// NewDetector creates a new detector with the given config func NewDetector(cfg config.Config) *Detector { return &Detector{ commitMap: make(map[string]bool), findingMutex: &sync.Mutex{}, findings: make([]report.Finding, 0), - cfg: cfg, + Config: cfg, } } -func NewDetectorDefaultConfig() *Detector { - // TODO load default config - // return NewDetector() - return nil +// NewDetectorDefaultConfig creates a new detector with the default config +func NewDetectorDefaultConfig() (*Detector, error) { + viper.SetConfigType("toml") + viper.ReadConfig(strings.NewReader(config.DefaultConfig)) + var vc config.ViperConfig + viper.Unmarshal(&vc) + cfg, err := vc.Translate() + if err != nil { + return nil, err + } + return NewDetector(cfg), nil } // Start is called from cmd @@ -82,7 +96,7 @@ func (d *Detector) Start(cmd *cobra.Command) ([]report.Finding, error) { start := time.Now() - d.cfg.Path, err = cmd.Flags().GetString("config") + d.Config.Path, err = cmd.Flags().GetString("config") if err != nil { return findings, err } @@ -94,8 +108,8 @@ func (d *Detector) Start(cmd *cobra.Command) ([]report.Finding, error) { // 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.cfg.Path == "" { - d.cfg.Path = filepath.Join(source, ".gitleaks.toml") + if d.Config.Path == "" { + d.Config.Path = filepath.Join(source, ".gitleaks.toml") } // set verbose flag @@ -104,7 +118,7 @@ func (d *Detector) Start(cmd *cobra.Command) ([]report.Finding, error) { } // set redact flag - if d.redact, err = cmd.Flags().GetBool("redact"); err != nil { + if d.Redact, err = cmd.Flags().GetBool("redact"); err != nil { return findings, err } @@ -116,12 +130,10 @@ func (d *Detector) Start(cmd *cobra.Command) ([]report.Finding, error) { if noGit { // TODO treat the repo as a directory } else { - // TODO scan git history logOpts, err := cmd.Flags().GetString("log-opts") if err != nil { return findings, err } - // TODO abstract git log to "producer" or "pipe" history, err := git.GitLog(source, logOpts) if err != nil { return findings, err @@ -154,20 +166,21 @@ func (d *Detector) Detect(fragment Fragment) []report.Finding { var findings []report.Finding // check if filepath is allowed - if d.cfg.Allowlist.PathAllowed(fragment.FilePath) || - fragment.FilePath == d.cfg.Path { + 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.cfg.Rules { + for _, rule := range d.Config.Rules { findings = append(findings, d.detectRule(fragment, rule)...) } - return filter(findings, d.redact) + return filter(findings, d.Redact) } +// 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 { var findings []report.Finding @@ -224,7 +237,7 @@ func (d *Detector) detectRule(fragment Fragment, rule *config.Rule) []report.Fin // check if the secret is in the allowlist if rule.Allowlist.RegexAllowed(finding.Secret) || - d.cfg.Allowlist.RegexAllowed(finding.Secret) { + d.Config.Allowlist.RegexAllowed(finding.Secret) { continue } @@ -251,29 +264,32 @@ func (d *Detector) detectRule(fragment Fragment, rule *config.Rule) []report.Fin return findings } +// startGitScan 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 +// and determine if the patch contains any findings. func (d *Detector) startGitScan(gitdiffFiles <-chan *gitdiff.File) { s := semgroup.NewGroup(context.Background(), 4) - for f := range gitdiffFiles { - f := f + for gitdiffFile := range gitdiffFiles { + gitdiffFile := gitdiffFile // skip binary files - if f.IsBinary || f.IsDelete { + if gitdiffFile.IsBinary || gitdiffFile.IsDelete { continue } // Check if commit is allowed commitSHA := "" - if f.PatchHeader != nil { - commitSHA = f.PatchHeader.SHA - if d.cfg.Allowlist.CommitAllowed(f.PatchHeader.SHA) { + if gitdiffFile.PatchHeader != nil { + commitSHA = gitdiffFile.PatchHeader.SHA + if d.Config.Allowlist.CommitAllowed(gitdiffFile.PatchHeader.SHA) { continue } } d.addCommit(commitSHA) s.Go(func() error { - for _, textFragment := range f.TextFragments { + for _, textFragment := range gitdiffFile.TextFragments { if textFragment == nil { return nil } @@ -281,11 +297,11 @@ func (d *Detector) startGitScan(gitdiffFiles <-chan *gitdiff.File) { fragment := Fragment{ Raw: textFragment.Raw(gitdiff.OpAdd), CommitSHA: commitSHA, - FilePath: f.NewName, + FilePath: gitdiffFile.NewName, } for _, finding := range d.Detect(fragment) { - d.addFinding(augmentGitFinding(finding, textFragment, f)) + d.addFinding(augmentGitFinding(finding, textFragment, gitdiffFile)) } } return nil diff --git a/detect/detect_test.go b/detect/detect_test.go index 496de7c0..dc649455 100644 --- a/detect/detect_test.go +++ b/detect/detect_test.go @@ -12,20 +12,21 @@ import ( "github.com/zricethezav/gitleaks/v8/report" ) -func TestDetectFindings(t *testing.T) { +const configPath = "../testdata/config/" + +func TestDetect(t *testing.T) { tests := []struct { cfgName string - opts Options - filePath string - bytes []byte - commit string + fragment Fragment expectedFindings []report.Finding wantError error }{ { - cfgName: "escaped_character_group", - bytes: []byte(`pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB`), - filePath: "tmp.go", + cfgName: "escaped_character_group", + fragment: Fragment{ + Raw: `pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB`, + FilePath: "tmp.go", + }, expectedFindings: []report.Finding{ { Description: "PyPI upload token", @@ -38,13 +39,16 @@ func TestDetectFindings(t *testing.T) { EndLine: 1, StartColumn: 1, EndColumn: 86, + Entropy: 1.9606875, }, }, }, { - cfgName: "simple", - bytes: []byte(`awsToken := \"AKIALALEMEL33243OLIA\"`), - filePath: "tmp.go", + cfgName: "simple", + fragment: Fragment{ + Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`, + FilePath: "tmp.go", + }, expectedFindings: []report.Finding{ { Description: "AWS Access Key", @@ -57,32 +61,41 @@ func TestDetectFindings(t *testing.T) { EndLine: 1, StartColumn: 15, EndColumn: 34, + Entropy: 3.0841837, }, }, }, { - cfgName: "allow_aws_re", - bytes: []byte(`awsToken := \"AKIALALEMEL33243OLIA\"`), - filePath: "tmp.go", + cfgName: "allow_aws_re", + fragment: Fragment{ + Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`, + FilePath: "tmp.go", + }, expectedFindings: []report.Finding{}, }, { - cfgName: "allow_path", - bytes: []byte(`awsToken := \"AKIALALEMEL33243OLIA\"`), - filePath: "tmp.go", + cfgName: "allow_path", + fragment: Fragment{ + Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`, + FilePath: "tmp.go", + }, expectedFindings: []report.Finding{}, }, { - cfgName: "allow_commit", - bytes: []byte(`awsToken := \"AKIALALEMEL33243OLIA\"`), - filePath: "tmp.go", + cfgName: "allow_commit", + fragment: Fragment{ + Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`, + FilePath: "tmp.go", + CommitSHA: "allowthiscommit", + }, expectedFindings: []report.Finding{}, - commit: "allowthiscommit", }, { - cfgName: "entropy_group", - bytes: []byte(`const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`), - filePath: "tmp.go", + cfgName: "entropy_group", + fragment: Fragment{ + Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`, + FilePath: "tmp.go", + }, expectedFindings: []report.Finding{ { Description: "Discord API key", @@ -100,15 +113,19 @@ func TestDetectFindings(t *testing.T) { }, }, { - cfgName: "generic_with_py_path", - bytes: []byte(`const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`), - filePath: "tmp.go", + cfgName: "generic_with_py_path", + fragment: Fragment{ + Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`, + FilePath: "tmp.go", + }, expectedFindings: []report.Finding{}, }, { - cfgName: "generic_with_py_path", - bytes: []byte(`const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`), - filePath: "tmp.py", + cfgName: "generic_with_py_path", + fragment: Fragment{ + Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`, + FilePath: "tmp.py", + }, expectedFindings: []report.Finding{ { Description: "Generic API Key", @@ -126,9 +143,11 @@ func TestDetectFindings(t *testing.T) { }, }, { - cfgName: "path_only", - bytes: []byte(`const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`), - filePath: "tmp.py", + cfgName: "path_only", + fragment: Fragment{ + Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`, + FilePath: "tmp.py", + }, expectedFindings: []report.Finding{ { Description: "Python Files", @@ -140,22 +159,28 @@ func TestDetectFindings(t *testing.T) { }, }, { - cfgName: "bad_entropy_group", - bytes: []byte(`const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`), - filePath: "tmp.go", + cfgName: "bad_entropy_group", + fragment: Fragment{ + Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`, + FilePath: "tmp.go", + }, expectedFindings: []report.Finding{}, wantError: fmt.Errorf("Discord API key invalid regex secret group 5, max regex secret group 3"), }, { - cfgName: "simple", - bytes: []byte(`awsToken := \"AKIALALEMEL33243OLIA\"`), - filePath: filepath.Join(configPath, "simple.toml"), + cfgName: "simple", + fragment: Fragment{ + Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`, + FilePath: filepath.Join(configPath, "simple.toml"), + }, expectedFindings: []report.Finding{}, }, { - cfgName: "allow_global_aws_re", - bytes: []byte(`awsToken := \"AKIALALEMEL33243OLIA\"`), - filePath: "tmp.go", + cfgName: "allow_global_aws_re", + fragment: Fragment{ + Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`, + FilePath: "tmp.go", + }, expectedFindings: []report.Finding{}, }, } @@ -180,8 +205,9 @@ func TestDetectFindings(t *testing.T) { } assert.Equal(t, tt.wantError, err) } + d := NewDetector(cfg) - findings := DetectFindings(cfg, tt.bytes, tt.filePath, tt.commit) + findings := d.Detect(tt.fragment) assert.ElementsMatch(t, tt.expectedFindings, findings) } } diff --git a/detect/location_test.go b/detect/location_test.go index 0d23276f..d8c1a58c 100644 --- a/detect/location_test.go +++ b/detect/location_test.go @@ -49,7 +49,7 @@ func TestGetLocation(t *testing.T) { } for _, test := range tests { - loc := getLocation(test.linePairs, test.start, test.end) + loc := location(Fragment{newlineIndices: test.linePairs}, []int{test.start, test.end}) if loc != test.wantLocation { t.Errorf("\nstartLine %d\nstartColumn: %d\nendLine: %d\nendColumn: %d\nstartLineIndex: %d\nendlineIndex %d", loc.startLine, loc.startColumn, loc.endLine, loc.endColumn, loc.startLineIndex, loc.endLineIndex) diff --git a/go.mod b/go.mod index 7b5e3bdb..6bd52061 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/zricethezav/gitleaks/v8 go 1.17 require ( + github.com/davecgh/go-spew v1.1.1 // indirect github.com/fatih/semgroup v1.2.0 // indirect github.com/fsnotify/fsnotify v1.4.9 // indirect github.com/gitleaks/go-gitdiff v0.7.4 // indirect @@ -11,6 +12,7 @@ require ( github.com/magiconair/properties v1.8.5 // indirect github.com/mitchellh/mapstructure v1.4.1 // indirect github.com/pelletier/go-toml v1.9.3 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect github.com/rs/zerolog v1.26.1 // indirect github.com/spf13/afero v1.6.0 // indirect github.com/spf13/cast v1.3.1 // indirect @@ -18,10 +20,12 @@ require ( github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/spf13/viper v1.8.1 // indirect + github.com/stretchr/testify v1.7.0 // indirect github.com/subosito/gotenv v1.2.0 // indirect golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect golang.org/x/sys v0.0.0-20211110154304-99a53858aa08 // indirect golang.org/x/text v0.3.6 // indirect gopkg.in/ini.v1 v1.62.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect + gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect ) diff --git a/go.sum b/go.sum index a0bf6528..4f763c47 100644 --- a/go.sum +++ b/go.sum @@ -57,6 +57,7 @@ github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3Ee github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= @@ -199,6 +200,7 @@ github.com/pelletier/go-toml v1.9.3/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCko github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -231,6 +233,7 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= @@ -586,6 +589,7 @@ gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=