Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
Implement EndpointCustomizer (#1291)
Miccahb1675194ca0c
diff --git a/main.go b/main.goindex 8ab6ac647..42346a850 100644--- a/main.go+++ b/main.go@@ -221,8 +221,6 @@ func run(state overseer.State) {}}- urls := splitVerifierURLs(*verifiers)-if *archiveMaxSize != 0 {handlers.SetArchiveMaxSize(int(*archiveMaxSize))}@@ -234,18 +232,22 @@ func run(state overseer.State) {}// Build include and exclude detector sets for filtering on engine initialization.+ // Exit if there was an error to inform the user of the misconfiguration.var includeDetectorSet, excludeDetectorSet map[config.DetectorID]struct{}+ var detectorsWithCustomVerifierEndpoints map[config.DetectorID][]string{includeList, err := config.ParseDetectors(*includeDetectors)if err != nil {- // Exit if there was an error to inform the user of the misconfiguration.logFatal(err, "invalid include list detector configuration")}excludeList, err := config.ParseDetectors(*excludeDetectors)if err != nil {- // Exit if there was an error to inform the user of the misconfiguration.logFatal(err, "invalid exclude list detector configuration")}+ detectorsWithCustomVerifierEndpoints, err = config.ParseVerifierEndpoints(*verifiers)+ if err != nil {+ logFatal(err, "invalid verifier detector configuration")+ }includeDetectorSet = detectorTypeToSet(includeList)excludeDetectorSet = detectorTypeToSet(excludeList)}@@ -253,38 +255,25 @@ func run(state overseer.State) {// Verify that all the user-provided detectors support the optional// detector features.{- isVersioner := engine.DefaultDetectorTypesImplementing[detectors.Versioner]()- for id := range includeDetectorSet {- if id.Version == 0 {- // Version not provided.- continue+ if err, id := verifyDetectorsAreVersioner(includeDetectorSet); err != nil {+ logFatal(err, "invalid include list detector configuration", "detector", id)+ }+ if err, id := verifyDetectorsAreVersioner(excludeDetectorSet); err != nil {+ logFatal(err, "invalid exclude list detector configuration", "detector", id)+ }+ if err, id := verifyDetectorsAreVersioner(detectorsWithCustomVerifierEndpoints); err != nil {+ logFatal(err, "invalid verifier detector configuration", "detector", id)+ }+ // Extra check for endpoint customization.+ isEndpointCustomizer := engine.DefaultDetectorTypesImplementing[detectors.EndpointCustomizer]()+ for id := range detectorsWithCustomVerifierEndpoints {+ if _, ok := isEndpointCustomizer[id.ID]; !ok {+ logFatal(+ fmt.Errorf("endpoint provided but detector does not support endpoint customization"),+ "invalid custom verifier endpoint detector configuration",+ "detector", id,+ )}- if _, ok := isVersioner[id.ID]; ok {- // Version provided for a Versioner detector.- continue- }- // Version provided on a non-Versioner detector.- logFatal(- fmt.Errorf("version provided but detector does not have a version"),- "invalid include list detector configuration",- "detector", id,- )- }- for id := range excludeDetectorSet {- if id.Version == 0 {- // Version not provided.- continue- }- if _, ok := isVersioner[id.ID]; ok {- // Version provided for a Versioner detector.- continue- }- // Version provided on a non-Versioner detector.- logFatal(- fmt.Errorf("version provided but detector does not have a version"),- "invalid exclude list detector configuration",- "detector", id,- )}}@@ -296,14 +285,41 @@ func run(state overseer.State) {_, ok := getWithDetectorID(d, excludeDetectorSet)return !ok}+ // Abuse filter to cause a side-effect.+ endpointCustomizer := func(d detectors.Detector) bool {+ urls, ok := getWithDetectorID(d, detectorsWithCustomVerifierEndpoints)+ if !ok {+ return true+ }+ id := config.GetDetectorID(d)+ customizer, ok := d.(detectors.EndpointCustomizer)+ if !ok {+ // NOTE: We should never reach here due to validation above.+ logFatal(+ fmt.Errorf("failed to configure a detector endpoint"),+ "the provided detector does not support endpoint configuration",+ "detector", id,+ )+ }+ // TODO: Add flag to ignore the default endpoint.+ urls = append(urls, customizer.DefaultEndpoint())+ if err := customizer.SetEndpoints(urls...); err != nil {+ logFatal(err, "failed configuring custom endpoint for detector", "detector", id)+ }+ logger.Info("configured detector with verification urls",+ "detector", id, "urls", urls,+ )+ return true+ }e := engine.Start(ctx,engine.WithConcurrency(*concurrency),engine.WithDecoders(decoders.DefaultDecoders()...),- engine.WithDetectors(!*noVerification, engine.CustomDetectors(ctx, urls)...),+ engine.WithDetectors(!*noVerification, engine.DefaultDetectors()...),engine.WithDetectors(!*noVerification, conf.Detectors...),engine.WithFilterDetectors(includeFilter),engine.WithFilterDetectors(excludeFilter),+ engine.WithFilterDetectors(endpointCustomizer),engine.WithFilterUnverified(*filterUnverified),)@@ -513,19 +529,6 @@ func printAverageDetectorTime(e *engine.Engine) {}}-func splitVerifierURLs(verifierURLs map[string]string) map[string][]string {- verifiers := make(map[string][]string, len(verifierURLs))- for k, v := range verifierURLs {- key := strings.ToLower(k)- sliceOfValues := strings.Split(v, ",")- for i, s := range sliceOfValues {- sliceOfValues[i] = strings.TrimSpace(s)- }- verifiers[key] = sliceOfValues- }- return verifiers-}-// logFatalFunc returns a log.Fatal style function. Calling the returned// function will terminate the program without cleanup.func logFatalFunc(logger logr.Logger) func(error, string, ...any) {@@ -563,3 +566,22 @@ func getWithDetectorID[T any](d detectors.Detector, data map[config.DetectorID]Tt, ok := data[key]return t, ok}++// verifyDetectorsAreVersioner checks all keys in a provided map to verify the+// provided type is actually a Versioner.+func verifyDetectorsAreVersioner[T any](data map[config.DetectorID]T) (error, config.DetectorID) {+ isVersioner := engine.DefaultDetectorTypesImplementing[detectors.Versioner]()+ for id := range data {+ if id.Version == 0 {+ // Version not provided.+ continue+ }+ if _, ok := isVersioner[id.ID]; ok {+ // Version provided for a Versioner detector.+ continue+ }+ // Version provided on a non-Versioner detector.+ return fmt.Errorf("version provided but detector does not have a version"), id+ }+ return nil, config.DetectorID{}+}diff --git a/pkg/config/detectors.go b/pkg/config/detectors.goindex 542f28bb8..baf6f9000 100644--- a/pkg/config/detectors.go+++ b/pkg/config/detectors.go@@ -2,6 +2,7 @@ package configimport ("fmt"+ "net/url""sort""strconv""strings"@@ -84,6 +85,37 @@ func ParseDetectors(input string) ([]DetectorID, error) {return output, nil}+// ParseDetector parses a user supplied string into a single DetectorID. Input+// is case-insensitive and either the detector name or ID may be used.+func ParseDetector(input string) (DetectorID, error) {+ return asDetectorID(strings.TrimSpace(input))+}++// ParseVerifierEndpoints parses a map of user supplied verifier URLs. The+// input keys are detector IDs and the values are a comma separated list of+// URLs. The URLs are validated as HTTPS endpoints.+func ParseVerifierEndpoints(verifierURLs map[string]string) (map[DetectorID][]string, error) {+ verifiers := make(map[DetectorID][]string, len(verifierURLs))+ for detectorID, urls := range verifierURLs {+ key, err := ParseDetector(detectorID)+ if err != nil {+ return nil, fmt.Errorf("invalid detector ID for verifier: %w", err)+ }+ verifierURLs := strings.Split(urls, ",")+ for i, rawEndpoint := range verifierURLs {+ rawEndpoint := strings.TrimSpace(rawEndpoint)+ verifierURLs[i] = rawEndpoint+ if endpoint, err := url.Parse(rawEndpoint); err != nil {+ return nil, fmt.Errorf("invalid verifier url %q: %w", rawEndpoint, err)+ } else if endpoint.Scheme != "https" {+ return nil, fmt.Errorf("verifier url must be https: %q", rawEndpoint)+ }+ }+ verifiers[key] = append(verifiers[key], verifierURLs...)+ }+ return verifiers, nil+}+func (id DetectorID) String() string {name := dpb.DetectorType_name[int32(id.ID)]if name == "" {@@ -155,8 +187,8 @@ func asRange(input string) ([]DetectorID, error) {return append(output, dtEnd), nil}-// asDetectorID converts the case-insensitive input into a DetectorID.-// Name or ID may be used.+// asDetectorID converts the case-insensitive input into a DetectorID. Name or+// ID may be used. Input is expected to be already trimmed of whitespace.func asDetectorID(input string) (DetectorID, error) {if input == "" {return DetectorID{}, fmt.Errorf("empty detector")diff --git a/pkg/detectors/detectors.go b/pkg/detectors/detectors.goindex 7d395bdb0..70c0ac9a8 100644--- a/pkg/detectors/detectors.go+++ b/pkg/detectors/detectors.go@@ -31,6 +31,13 @@ type Versioner interface {Version() int}+// EndpointCustomizer is an optional interface that a detector can implement to+// support verifying against user-supplied endpoints.+type EndpointCustomizer interface {+ SetEndpoints(...string) error+ DefaultEndpoint() string+}+type Result struct {// DetectorType is the type of Detector.DetectorType detectorspb.DetectorTypediff --git a/pkg/detectors/endpoint_customizer.go b/pkg/detectors/endpoint_customizer.gonew file mode 100644index 000000000..85510cd9e--- /dev/null+++ b/pkg/detectors/endpoint_customizer.go@@ -0,0 +1,36 @@+package detectors++import (+ "fmt"++ "github.com/trufflesecurity/trufflehog/v3/pkg/common"+)++// EndpointSetter implements a sensible default for the SetEndpoints function+// of the EndpointCustomizer interface. A detector can embed this struct to+// gain the functionality.+type EndpointSetter struct {+ endpoints []string+}++func (e *EndpointSetter) SetEndpoints(endpoints ...string) error {+ if len(endpoints) == 0 {+ return fmt.Errorf("at least one endpoint required")+ }+ deduped := make([]string, 0, len(endpoints))+ for _, endpoint := range endpoints {+ common.AddStringSliceItem(endpoint, &deduped)+ }+ e.endpoints = deduped+ return nil+}++func (e *EndpointSetter) Endpoints(defaultEndpoint string) []string {+ // The only valid time len(e.endpoints) == 0 is when EndpointSetter is+ // initializetd to its default state. That means SetEndpoints was never+ // called and we should use the default.+ if len(e.endpoints) == 0 {+ return []string{defaultEndpoint}+ }+ return e.endpoints+}diff --git a/pkg/detectors/endpoint_customizer_test.go b/pkg/detectors/endpoint_customizer_test.gonew file mode 100644index 000000000..dc8542293--- /dev/null+++ b/pkg/detectors/endpoint_customizer_test.go@@ -0,0 +1,16 @@+package detectors++import (+ "testing"++ "github.com/stretchr/testify/assert"+)++func TestEmbeddedEndpointSetter(t *testing.T) {+ type Scanner struct{ EndpointSetter }+ var s Scanner+ assert.Equal(t, []string{"baz"}, s.Endpoints("baz"))+ assert.NoError(t, s.SetEndpoints("foo", "bar"))+ assert.Error(t, s.SetEndpoints())+ assert.Equal(t, []string{"foo", "bar"}, s.Endpoints("baz"))+}diff --git a/pkg/detectors/github/github.go b/pkg/detectors/github/github.goindex cda1c7098..82036681f 100644--- a/pkg/detectors/github/github.go+++ b/pkg/detectors/github/github.go@@ -13,40 +13,15 @@ import ("github.com/trufflesecurity/trufflehog/v3/pkg/common")-const defaultURL = "https://api.github.com"--type Scanner struct {- verifierURLs []string-}--// New creates a new Scanner with the given options.-func New(opts ...func(*Scanner)) *Scanner {- scanner := &Scanner{- verifierURLs: make([]string, 0),- }- for _, opt := range opts {- opt(scanner)- }-- return scanner-}--// WithVerifierURLs adds the given URLs to the list of URLs to check for-// verification of secrets.-func WithVerifierURLs(urls []string, includeDefault bool) func(*Scanner) {- return func(s *Scanner) {- if includeDefault {- urls = append(urls, defaultURL)- }- s.verifierURLs = append(s.verifierURLs, urls...)- }-}+type Scanner struct{ detectors.EndpointSetter }// Ensure the Scanner satisfies the interfaces at compile time.var _ detectors.Detector = (*Scanner)(nil)var _ detectors.Versioner = (*Scanner)(nil)+var _ detectors.EndpointCustomizer = (*Scanner)(nil)-func (s Scanner) Version() int { return 2 }+func (Scanner) Version() int { return 2 }+func (Scanner) DefaultEndpoint() string { return "https://api.github.com" }var (// Oauth token@@ -82,10 +57,6 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (resultmatches := keyPat.FindAllStringSubmatch(dataStr, -1)- if len(s.verifierURLs) == 0 {- s.verifierURLs = append(s.verifierURLs, defaultURL)- }-for _, match := range matches {// First match is entire regex, second is the first group.if len(match) != 2 {@@ -102,7 +73,7 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (resultif verify {client := common.SaneHttpClient()// https://developer.github.com/v3/users/#get-the-authenticated-user- for _, url := range s.verifierURLs {+ for _, url := range s.Endpoints(s.DefaultEndpoint()) {req, err := http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("%s/user", url), nil)if err != nil {continuediff --git a/pkg/detectors/github_old/github_old.go b/pkg/detectors/github_old/github_old.goindex f948aa548..21a4d0409 100644--- a/pkg/detectors/github_old/github_old.go+++ b/pkg/detectors/github_old/github_old.go@@ -12,40 +12,15 @@ import ("github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb")-const defaultURL = "https://api.github.com"--type Scanner struct {- verifierURLs []string-}--// New creates a new Scanner with the given options.-func New(opts ...func(*Scanner)) *Scanner {- scanner := &Scanner{- verifierURLs: make([]string, 0),- }- for _, opt := range opts {- opt(scanner)- }-- return scanner-}--// WithVerifierURLs adds the given URLs to the list of URLs to check for-// verification of secrets.-func WithVerifierURLs(urls []string, includeDefault bool) func(*Scanner) {- return func(s *Scanner) {- if includeDefault {- urls = append(urls, defaultURL)- }- s.verifierURLs = append(s.verifierURLs, urls...)- }-}+type Scanner struct{ detectors.EndpointSetter }// Ensure the Scanner satisfies the interfaces at compile time.var _ detectors.Detector = (*Scanner)(nil)var _ detectors.Versioner = (*Scanner)(nil)+var _ detectors.EndpointCustomizer = (*Scanner)(nil)-func (s Scanner) Version() int { return 1 }+func (Scanner) Version() int { return 1 }+func (Scanner) DefaultEndpoint() string { return "https://api.github.com" }var (// Oauth token@@ -98,7 +73,7 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (resultif verify {client := common.SaneHttpClient()// https://developer.github.com/v3/users/#get-the-authenticated-user- for _, url := range s.verifierURLs {+ for _, url := range s.Endpoints(s.DefaultEndpoint()) {req, err := http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("%s/user", url), nil)if err != nil {continuediff --git a/pkg/detectors/gitlab/gitlab.go b/pkg/detectors/gitlab/gitlab.goindex 6fe1d11ed..6c8bd5fbf 100644--- a/pkg/detectors/gitlab/gitlab.go+++ b/pkg/detectors/gitlab/gitlab.go@@ -12,40 +12,15 @@ import ("github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb")-const defaultURL = "https://gitlab.com"--type Scanner struct {- verifierURLs []string-}--// New creates a new Scanner with the given options.-func New(opts ...func(*Scanner)) *Scanner {- scanner := &Scanner{- verifierURLs: make([]string, 0),- }- for _, opt := range opts {- opt(scanner)- }-- return scanner-}--// WithVerifierURLs adds the given URLs to the list of URLs to check for-// verification of secrets.-func WithVerifierURLs(urls []string, includeDefault bool) func(*Scanner) {- return func(s *Scanner) {- if includeDefault {- urls = append(urls, defaultURL)- }- s.verifierURLs = append(s.verifierURLs, urls...)- }-}+type Scanner struct{ detectors.EndpointSetter }// Ensure the Scanner satisfies the interfaces at compile time.var _ detectors.Detector = (*Scanner)(nil)var _ detectors.Versioner = (*Scanner)(nil)+var _ detectors.EndpointCustomizer = (*Scanner)(nil)-func (s Scanner) Version() int { return 1 }+func (Scanner) Version() int { return 1 }+func (Scanner) DefaultEndpoint() string { return "https://gitlab.com" }var (keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"gitlab"}) + `\b((?:glpat|)[a-zA-Z0-9\-=_]{20,22})\b`)@@ -63,10 +38,6 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (resultmatches := keyPat.FindAllStringSubmatch(dataStr, -1)- if len(s.verifierURLs) == 0 {- s.verifierURLs = append(s.verifierURLs, defaultURL)- }-for _, match := range matches {if len(match) != 2 {continue@@ -89,7 +60,7 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result// of them contain data, we know we have a valid key, but if they all fail, we don'tclient := common.SaneHttpClient()- for _, baseURL := range s.verifierURLs {+ for _, baseURL := range s.Endpoints(s.DefaultEndpoint()) {// test `read_user` scopereq, err := http.NewRequestWithContext(ctx, "GET", baseURL+"/api/v4/user", nil)if err != nil {diff --git a/pkg/detectors/gitlabv2/gitlab.go b/pkg/detectors/gitlabv2/gitlab.goindex 41f62c419..c522751df 100644--- a/pkg/detectors/gitlabv2/gitlab.go+++ b/pkg/detectors/gitlabv2/gitlab.go@@ -11,40 +11,15 @@ import ("github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb")-const defaultURL = "https://gitlab.com"--type Scanner struct {- verifierURLs []string-}--// New creates a new Scanner with the given options.-func New(opts ...func(*Scanner)) *Scanner {- scanner := &Scanner{- verifierURLs: make([]string, 0),- }- for _, opt := range opts {- opt(scanner)- }-- return scanner-}--// WithVerifierURLs adds the given URLs to the list of URLs to check for-// verification of secrets.-func WithVerifierURLs(urls []string, includeDefault bool) func(*Scanner) {- return func(s *Scanner) {- if includeDefault {- urls = append(urls, defaultURL)- }- s.verifierURLs = append(s.verifierURLs, urls...)- }-}+type Scanner struct{ detectors.EndpointSetter }// Ensure the Scanner satisfies the interfaces at compile time.var _ detectors.Detector = (*Scanner)(nil)var _ detectors.Versioner = (*Scanner)(nil)+var _ detectors.EndpointCustomizer = (*Scanner)(nil)-func (*Scanner) Version() int { return 2 }+func (Scanner) Version() int { return 2 }+func (Scanner) DefaultEndpoint() string { return "https://gitlab.com" }var (keyPat = regexp.MustCompile(`\b(glpat-[a-zA-Z0-9\-=_]{20,22})\b`)@@ -62,10 +37,6 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (resultmatches := keyPat.FindAllStringSubmatch(dataStr, -1)- if len(s.verifierURLs) == 0 {- s.verifierURLs = append(s.verifierURLs, defaultURL)- }-for _, match := range matches {if len(match) != 2 {continue@@ -82,7 +53,7 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result// one of these scopes has access to, so we just check an example endpoint for each scope. If any// of them contain data, we know we have a valid key, but if they all fail, we don'tclient := common.SaneHttpClient()- for _, baseURL := range s.verifierURLs {+ for _, baseURL := range s.Endpoints(s.DefaultEndpoint()) {// test `read_user` scopereq, err := http.NewRequestWithContext(ctx, "GET", baseURL+"/api/v4/user", nil)if err != nil {diff --git a/pkg/engine/defaults.go b/pkg/engine/defaults.goindex c100f9d44..9980da734 100644--- a/pkg/engine/defaults.go+++ b/pkg/engine/defaults.go@@ -1,7 +1,6 @@package engineimport (- "github.com/trufflesecurity/trufflehog/v3/pkg/context""github.com/trufflesecurity/trufflehog/v3/pkg/detectors""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/abbysale""github.com/trufflesecurity/trufflehog/v3/pkg/detectors/abuseipdb"@@ -743,65 +742,6 @@ import ("github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb")-// CustomDetectors returns a list of detectors that are enabled by default, but-// can be overridden by the user.-func CustomDetectors(ctx context.Context, urls map[string][]string) []detectors.Detector {- defaultDetectors := DefaultDetectors()- if len(urls) == 0 {- return defaultDetectors- }-- for i, detector := range defaultDetectors {-- switch detector.Type() {- case detectorspb.DetectorType_Github:- githubUrls, ok := urls["github"]- if !ok {- ctx.Logger().V(2).Info("no GitHub urls to ignore")- continue- }- ctx.Logger().V(2).Info("ignoring GitHub urls: %v", githubUrls)-- versioner, ok := detector.(detectors.Versioner)- if !ok {- ctx.Logger().V(2).Info("Failed to get version for GitHub detector")- }- switch versioner.Version() {- case 1:- defaultDetectors[i] = github_old.New(github_old.WithVerifierURLs(githubUrls, true))- default:- defaultDetectors[i] = github.New(github.WithVerifierURLs(githubUrls, true))- }-- case detectorspb.DetectorType_Gitlab:- gitlabUrls, ok := urls["gitlab"]- if !ok {- ctx.Logger().V(2).Info("no GitLab urls to ignore")- continue- }- ctx.Logger().V(2).Info("ignoring GitLab urls: %v", gitlabUrls)-- versioner, ok := detector.(detectors.Versioner)- if !ok {- ctx.Logger().V(2).Info("Failed to get version for Gitlab detector")- }- switch versioner.Version() {- case 1:- defaultDetectors[i] = gitlab.New(gitlab.WithVerifierURLs(gitlabUrls, true))- default:- defaultDetectors[i] = gitlabv2.New(gitlabv2.WithVerifierURLs(gitlabUrls, true))- }-- case detectorspb.DetectorType_JiraToken:- // TODO(ahrav): Double check that we need to do this.- default:- ctx.Logger().V(5).Info("ignoring custom detector", "type", detector.Type())- continue- }- }- return defaultDetectors-}-func DefaultDetectors() []detectors.Detector {return []detectors.Detector{&heroku.Scanner{},