Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
Fixed and improved Clickhelp detector (#4384)
Kashif Khan76c63fecb747
diff --git a/pkg/detectors/clickhelp/clickhelp.go b/pkg/detectors/clickhelp/clickhelp.goindex 1fa4ec24c..08b930c16 100644--- a/pkg/detectors/clickhelp/clickhelp.go+++ b/pkg/detectors/clickhelp/clickhelp.go@@ -2,10 +2,9 @@ package clickhelpimport ("context"- b64 "encoding/base64""fmt"+ "io""net/http"- "strings"regexp "github.com/wasilibs/go-re2"@@ -25,55 +24,57 @@ var (client = common.SaneHttpClient()// Make sure that your group is surrounded in boundary characters such as below to reduce false positives.- serverPat = regexp.MustCompile(`\b([0-9A-Za-z]{3,20}.try.clickhelp.co)\b`)- emailPat = regexp.MustCompile(`\b([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-z]+)\b`)- keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"clickhelp"}) + `\b([0-9A-Za-z]{24})\b`)+ portalPat = regexp.MustCompile(`\b([0-9A-Za-z-]{3,20}\.(?:try\.)?clickhelp\.co)\b`)+ emailPat = regexp.MustCompile(common.EmailPattern)+ keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"clickhelp", "key", "token", "api", "secret"}) + `\b([0-9A-Za-z]{24})\b`))+func (s Scanner) Type() detectorspb.DetectorType {+ return detectorspb.DetectorType_ClickHelp+}++func (s Scanner) Description() string {+ return "ClickHelp is a documentation tool that allows users to create and manage online documentation. ClickHelp API keys can be used to access and modify documentation data."+}+// Keywords are used for efficiently pre-filtering chunks.// Use identifiers in the secret preferably, or the provider name.func (s Scanner) Keywords() []string {- return []string{"clickhelp"}+ return []string{"clickhelp.co"}}// FromData will find and optionally verify Clickhelp secrets in a given set of bytes.func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {dataStr := string(data)- serverMatches := serverPat.FindAllStringSubmatch(dataStr, -1)- emailMatches := emailPat.FindAllStringSubmatch(dataStr, -1)- keyMatches := keyPat.FindAllStringSubmatch(dataStr, -1)+ var uniquePortalLinks, uniqueEmails, uniqueAPIKeys = make(map[string]struct{}), make(map[string]struct{}), make(map[string]struct{})- for _, match := range serverMatches {- resServer := strings.TrimSpace(match[1])+ for _, match := range portalPat.FindAllStringSubmatch(dataStr, -1) {+ uniquePortalLinks[match[1]] = struct{}{}+ }++ for _, match := range emailPat.FindAllStringSubmatch(dataStr, -1) {+ uniqueEmails[match[1]] = struct{}{}+ }- for _, emailMatch := range emailMatches {- resEmail := strings.TrimSpace(emailMatch[1])- for _, keyMatch := range keyMatches {- resKey := strings.TrimSpace(keyMatch[1])+ for _, match := range keyPat.FindAllStringSubmatch(dataStr, -1) {+ uniqueAPIKeys[match[1]] = struct{}{}+ }+ for portalLink := range uniquePortalLinks {+ for email := range uniqueEmails {+ for apiKey := range uniqueAPIKeys {s1 := detectors.Result{DetectorType: detectorspb.DetectorType_ClickHelp,- Raw: []byte(resServer),- RawV2: []byte(resServer + resEmail),+ Raw: []byte(portalLink),+ RawV2: []byte(portalLink + email),}if verify {- data := fmt.Sprintf("%s:%s", resEmail, resKey)- sEnc := b64.StdEncoding.EncodeToString([]byte(data))- req, err := http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("https://%s/api/v1/projects", resServer), nil)- if err != nil {- continue- }- req.Header.Add("Content-Type", "application/json")- req.Header.Add("Authorization", fmt.Sprintf("Basic %s", sEnc))- res, err := client.Do(req)- if err == nil {- defer res.Body.Close()- if res.StatusCode >= 200 && res.StatusCode < 300 {- s1.Verified = true- }- }+ isVerified, verificationErr := verifyClickHelp(ctx, client, portalLink, email, apiKey)+ s1.Verified = isVerified+ s1.SetVerificationError(verificationErr)+ s1.SetPrimarySecretValue(apiKey) // line number will point to api key}results = append(results, s1)@@ -84,10 +85,31 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (resultreturn results, nil}-func (s Scanner) Type() detectorspb.DetectorType {- return detectorspb.DetectorType_ClickHelp-}+func verifyClickHelp(ctx context.Context, client *http.Client, portalLink, email, apiKey string) (bool, error) {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("https://%s/api/v1/projects", portalLink), http.NoBody)+ if err != nil {+ return false, err+ }-func (s Scanner) Description() string {- return "ClickHelp is a documentation tool that allows users to create and manage online documentation. ClickHelp API keys can be used to access and modify documentation data."+ req.Header.Add("Content-Type", "application/json")+ req.SetBasicAuth(email, apiKey)++ resp, err := client.Do(req)+ if err != nil {+ return false, err+ }++ defer func() {+ _, _ = io.Copy(io.Discard, resp.Body)+ _ = resp.Body.Close()+ }()++ switch resp.StatusCode {+ case http.StatusOK:+ return true, nil+ case http.StatusUnauthorized:+ return false, nil+ default:+ return false, fmt.Errorf("unexpected status code: %d", resp.StatusCode)+ }}diff --git a/pkg/detectors/clickhelp/clickhelp_integration_test.go b/pkg/detectors/clickhelp/clickhelp_integration_test.goindex 16965f63d..45355743b 100644--- a/pkg/detectors/clickhelp/clickhelp_integration_test.go+++ b/pkg/detectors/clickhelp/clickhelp_integration_test.go@@ -9,7 +9,8 @@ import ("testing""time"- "github.com/kylelemons/godebug/pretty"+ "github.com/google/go-cmp/cmp"+ "github.com/google/go-cmp/cmp/cmpopts""github.com/trufflesecurity/trufflehog/v3/pkg/detectors""github.com/trufflesecurity/trufflehog/v3/pkg/common"@@ -97,9 +98,11 @@ func TestClickhelp_FromChunk(t *testing.T) {t.Fatalf("no raw secret present: \n %+v", got[i])}got[i].Raw = nil+ got[i].RawV2 = nil}- if diff := pretty.Compare(got, tt.want); diff != "" {- t.Errorf("Clickhelp.FromData() %s diff: (-got +want)\n%s", tt.name, diff)+ ignoreOpts := cmpopts.IgnoreFields(detectors.Result{}, "Raw", "RawV2", "verificationError", "primarySecret")+ if diff := cmp.Diff(got, tt.want, ignoreOpts); diff != "" {+ t.Errorf("AdafruitIO.FromData() %s diff: (-got +want)\n%s", tt.name, diff)}})}diff --git a/pkg/detectors/clickhelp/clickhelp_test.go b/pkg/detectors/clickhelp/clickhelp_test.goindex f8ce474a0..ff56a418f 100644--- a/pkg/detectors/clickhelp/clickhelp_test.go+++ b/pkg/detectors/clickhelp/clickhelp_test.go@@ -10,33 +10,6 @@ import ("github.com/trufflesecurity/trufflehog/v3/pkg/engine/ahocorasick")-var (- validPattern = `- # Configuration File: config.yaml- database:- host: $DB_HOST- port: $DB_PORT- username: $DB_USERNAME- password: $DB_PASS # IMPORTANT: Do not share this password publicly-- api:- user_email: "[email protected]"- clickhelp_key: "XzUkp562BtmjfRGoOGBiLLNu"- clickhelp_domain: testingdev.try.clickhelp.co- auth_type: Basic- base_url: "https://testing-dev.try.clickhelp.co/v1/user"- auth_token: ""-- # Notes:- # - Remember to rotate the secret every 90 days.- # - The above credentials should only be used in a secure environment.- `- secrets = []string{- "[email protected]",- "[email protected]",- }-)-func TestClickHelp_Pattern(t *testing.T) {d := Scanner{}ahoCorasickCore := ahocorasick.NewAhoCorasickCore([]detectors.Detector{d})@@ -47,9 +20,46 @@ func TestClickHelp_Pattern(t *testing.T) {want []string}{{- name: "valid pattern",- input: validPattern,- want: secrets,+ name: "valid pattern",+ input: `+ # Configuration File: config.yaml+ database:+ host: $DB_HOST+ port: $DB_PORT+ username: $DB_USERNAME+ password: $DB_PASS # IMPORTANT: Do not share this password publicly++ api:+ user_email: "[email protected]"+ key: "XzUkp562BtmjfRGoOGBiLLNu"+ portal: testingdev.try.clickhelp.co+ auth_type: Basic+ base_url: "https://testing-dev.try.clickhelp.co/v1/user"+ auth_token: ""++ # Notes:+ # - Remember to rotate the secret every 90 days.+ # - The above credentials should only be used in a secure environment.+ `,+ want: []string{+ "[email protected]",+ "[email protected]",+ },+ },+ {+ name: "valid pattern - xml",+ input: `+ <com.cloudbees.plugins.credentials.impl.StringCredentialsImpl>+ <scope>GLOBAL</scope>+ <id>{[email protected]}</id>+ <secret>{AQAAABAAA XzUkp562BtmjfRGoOGBiLLNu}</secret>+ <portal>company-prod.clickhelp.co</portal>+ <description>configuration for production</description>+ <creationDate>2023-05-18T14:32:10Z</creationDate>+ <owner>jenkins-admin</owner>+ </com.cloudbees.plugins.credentials.impl.StringCredentialsImpl>+ `,+ want: []string{"[email protected]"},},}