Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
added entropy filter and improved verification for gitlab v2/v3 (#5358)
Jordan Tunstillc73dc6483ab3
diff --git a/pkg/detectors/gitlab/v1/gitlab.go b/pkg/detectors/gitlab/v1/gitlab.goindex 2aab2d094..e77633eb0 100644--- a/pkg/detectors/gitlab/v1/gitlab.go+++ b/pkg/detectors/gitlab/v1/gitlab.go@@ -37,8 +37,16 @@ var (keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"gitlab"}) + `\b([a-zA-Z0-9][a-zA-Z0-9\-=_]{19,21})\b`)BlockedUserMessage = "403 Forbidden - Your account has been blocked"++ // GitLab's forbidden! helper formats every reasoned 403 as "403 Forbidden - <reason>".+ forbiddenWithReasonPrefix = "403 Forbidden - ")+type gitlabErrorResponse struct {+ Message string `json:"message"`+ Error string `json:"error"`+}+func (s Scanner) getClient() *http.Client {if s.client != nil {return s.client@@ -140,22 +148,34 @@ func VerifyGitlab(ctx context.Context, client *http.Client, baseEndpoint, resMat}// 200 means good key and has `read_user` scope- // 403 means good key but not the right scope+ // 403 from GitLab means good key, but either the scope or the account state denies access// 401 is bad keyswitch res.StatusCode {case http.StatusOK:return json.Valid(bodyBytes), nil, nilcase http.StatusForbidden:- // check if the user account is blocked or not- stringBody := string(bodyBytes)- if strings.Contains(stringBody, BlockedUserMessage) {- return true, map[string]string{- "blocked": "True",- }, nil+ var errResp gitlabErrorResponse+ if err := json.Unmarshal(bodyBytes, &errResp); err != nil {+ return false, nil, fmt.Errorf("unexpected 403 response, unable to verify token")+ }++ switch {+ // GitLab only rejects an account (blocked, deactivated, password expired, unconfirmed+ // email, etc.) after the token has resolved to a user.+ case strings.HasPrefix(errResp.Message, forbiddenWithReasonPrefix):+ extraData := map[string]string{+ "access_denied_reason": strings.TrimPrefix(errResp.Message, forbiddenWithReasonPrefix),+ }+ if strings.HasPrefix(errResp.Message, BlockedUserMessage) {+ extraData["blocked"] = "True"+ }+ return true, extraData, nil+ case errResp.Error == "insufficient_scope", errResp.Error == "insufficient_granular_scope":+ // Good key but not the right scope+ return true, nil, nil}- // Good key but not the right scope- return true, nil, nil+ return false, nil, fmt.Errorf("unexpected 403 response, unable to verify token")case http.StatusUnauthorized:// Nothing to do; zero values are the ones we wantreturn false, nil, nildiff --git a/pkg/detectors/gitlab/v1/gitlab_integration_test.go b/pkg/detectors/gitlab/v1/gitlab_integration_test.goindex 5a4d82307..60a1a3e8d 100644--- a/pkg/detectors/gitlab/v1/gitlab_integration_test.go+++ b/pkg/detectors/gitlab/v1/gitlab_integration_test.go@@ -143,7 +143,7 @@ func TestGitlab_FromChunk(t *testing.T) {},{name: "found, good key but wrong scope",- s: Scanner{client: common.ConstantResponseHttpClient(403, "")},+ s: Scanner{client: common.ConstantResponseHttpClient(403, `{"error":"insufficient_scope","error_description":"The request requires higher privileges than provided by the access token.","scope":"read_user api read_api"}`)},args: args{ctx: context.Background(),data: []byte(fmt.Sprintf("You can find a gitlab super secret %s within", secret)),@@ -161,6 +161,27 @@ func TestGitlab_FromChunk(t *testing.T) {},wantErr: false,},+ {+ name: "found but ambiguous 403 (not insufficient_scope)",+ s: Scanner{client: common.ConstantResponseHttpClient(403, "")},+ args: args{+ ctx: context.Background(),+ data: []byte(fmt.Sprintf("You can find a gitlab super secret %s within", secret)),+ verify: true,+ },+ want: []detectors.Result{+ {+ DetectorType: detector_typepb.DetectorType_Gitlab,+ Verified: false,+ ExtraData: map[string]string{+ "rotation_guide": "https://howtorotate.com/docs/tutorials/gitlab/",+ "version": "1",+ },+ },+ },+ wantErr: false,+ wantVerificationErr: true,+ },{name: "not found",s: Scanner{},diff --git a/pkg/detectors/gitlab/v1/gitlab_v1_test.go b/pkg/detectors/gitlab/v1/gitlab_v1_test.goindex b5d479bf7..410d599b2 100644--- a/pkg/detectors/gitlab/v1/gitlab_v1_test.go+++ b/pkg/detectors/gitlab/v1/gitlab_v1_test.go@@ -6,6 +6,7 @@ import ("github.com/google/go-cmp/cmp"+ "github.com/trufflesecurity/trufflehog/v3/pkg/common""github.com/trufflesecurity/trufflehog/v3/pkg/detectors""github.com/trufflesecurity/trufflehog/v3/pkg/engine/ahocorasick")@@ -89,3 +90,81 @@ func TestGitLab_Pattern(t *testing.T) {})}}++func TestVerifyGitlab_Forbidden(t *testing.T) {+ tests := []struct {+ name string+ body string+ wantVerified bool+ wantExtraData map[string]string+ wantErr bool+ }{+ {+ name: "blocked account",+ body: `{"message":"403 Forbidden - Your account has been blocked."}`,+ wantVerified: true,+ wantExtraData: map[string]string{+ "access_denied_reason": "Your account has been blocked.",+ "blocked": "True",+ },+ },+ {+ name: "password expired",+ body: `{"message":"403 Forbidden - Your password expired. Please access GitLab from a web browser to update your password."}`,+ wantVerified: true,+ wantExtraData: map[string]string{+ "access_denied_reason": "Your password expired. Please access GitLab from a web browser to update your password.",+ },+ },+ {+ name: "unconfirmed email",+ body: `{"message":"403 Forbidden - Your primary email address is not confirmed. Please check your inbox for the confirmation instructions."}`,+ wantVerified: true,+ wantExtraData: map[string]string{+ "access_denied_reason": "Your primary email address is not confirmed. Please check your inbox for the confirmation instructions.",+ },+ },+ {+ name: "insufficient scope",+ body: `{"error":"insufficient_scope","error_description":"The request requires higher privileges than provided by the access token.","scope":"read_user api read_api"}`,+ wantVerified: true,+ },+ {+ name: "insufficient granular scope",+ body: `{"error":"insufficient_granular_scope","error_description":"The request requires higher privileges than provided by the access token."}`,+ wantVerified: true,+ },+ {+ name: "empty body",+ body: "",+ wantErr: true,+ },+ {+ name: "non-JSON body from a proxy or WAF",+ body: "<html><body>403 Forbidden</body></html>",+ wantErr: true,+ },+ {+ name: "JSON without a GitLab reason",+ body: `{"message":"403 Forbidden"}`,+ wantErr: true,+ },+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ client := common.ConstantResponseHttpClient(403, test.body)+ verified, extraData, err := VerifyGitlab(context.Background(), client, "https://gitlab.com", "token")++ if (err != nil) != test.wantErr {+ t.Fatalf("error = %v, wantErr %v", err, test.wantErr)+ }+ if verified != test.wantVerified {+ t.Errorf("verified = %v, want %v", verified, test.wantVerified)+ }+ if diff := cmp.Diff(test.wantExtraData, extraData); diff != "" {+ t.Errorf("extraData diff: (-want +got)\n%s", diff)+ }+ })+ }+}diff --git a/pkg/detectors/gitlab/v2/gitlab_integration_test.go b/pkg/detectors/gitlab/v2/gitlab_integration_test.goindex beb684395..8689e4ede 100644--- a/pkg/detectors/gitlab/v2/gitlab_integration_test.go+++ b/pkg/detectors/gitlab/v2/gitlab_integration_test.go@@ -328,7 +328,7 @@ func TestGitlabV2_FromChunk(t *testing.T) {},{name: "found, good key but wrong scope",- s: Scanner{client: common.ConstantResponseHttpClient(403, "")},+ s: Scanner{client: common.ConstantResponseHttpClient(403, `{"error":"insufficient_scope","error_description":"The request requires higher privileges than provided by the access token.","scope":"read_user api read_api"}`)},args: args{ctx: context.Background(),data: []byte(fmt.Sprintf("You can find a gitlab super secret %s within", secret)),@@ -346,6 +346,27 @@ func TestGitlabV2_FromChunk(t *testing.T) {},wantErr: false,},+ {+ name: "found but ambiguous 403 (not insufficient_scope)",+ s: Scanner{client: common.ConstantResponseHttpClient(403, "")},+ args: args{+ ctx: context.Background(),+ data: []byte(fmt.Sprintf("You can find a gitlab super secret %s within", secret)),+ verify: true,+ },+ want: []detectors.Result{+ {+ DetectorType: detector_typepb.DetectorType_Gitlab,+ Verified: false,+ ExtraData: map[string]string{+ "rotation_guide": "https://howtorotate.com/docs/tutorials/gitlab/",+ "version": "2",+ },+ },+ },+ wantErr: false,+ wantVerificationErr: true,+ },{name: "not found",s: Scanner{},diff --git a/pkg/detectors/gitlab/v2/gitlab_v2.go b/pkg/detectors/gitlab/v2/gitlab_v2.goindex 30789f382..cef9fd22f 100644--- a/pkg/detectors/gitlab/v2/gitlab_v2.go+++ b/pkg/detectors/gitlab/v2/gitlab_v2.go@@ -61,6 +61,10 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (resultfor _, match := range matches {resMatch := strings.TrimSpace(match[1])+ if detectors.StringShannonEntropy(resMatch) < 3.6 {+ continue+ }+for _, endpoint := range s.Endpoints() {s1 := detectors.Result{DetectorType: detector_typepb.DetectorType_Gitlab,diff --git a/pkg/detectors/gitlab/v2/gitlab_v2_test.go b/pkg/detectors/gitlab/v2/gitlab_v2_test.goindex 05f8e815f..701525f28 100644--- a/pkg/detectors/gitlab/v2/gitlab_v2_test.go+++ b/pkg/detectors/gitlab/v2/gitlab_v2_test.go@@ -39,6 +39,11 @@ func TestGitLab_Pattern(t *testing.T) {}]`,want: []string{"glpat-W6fYSu70dPEo5w_SwbHWgQhttps://gitlab.com"},},+ {+ name: "low-entropy placeholder",+ input: `gitlab_secret = "glpat-xxxxxxxxxxxxxxxxxxxx"`,+ want: nil,+ },}for _, test := range tests {diff --git a/pkg/detectors/gitlab/v3/gitlab_v3.go b/pkg/detectors/gitlab/v3/gitlab_v3.goindex 0a4a26633..f37098dde 100644--- a/pkg/detectors/gitlab/v3/gitlab_v3.go+++ b/pkg/detectors/gitlab/v3/gitlab_v3.go@@ -62,6 +62,10 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (resultfor _, match := range matches {resMatch := strings.TrimSpace(match[1])+ if detectors.StringShannonEntropy(resMatch) < 3.6 {+ continue+ }+for _, endpoint := range s.Endpoints() {s1 := detectors.Result{DetectorType: detector_typepb.DetectorType_Gitlab,diff --git a/pkg/detectors/gitlab/v3/gitlab_v3_integration_test.go b/pkg/detectors/gitlab/v3/gitlab_v3_integration_test.goindex 3db44ae0a..eecdd2dd7 100644--- a/pkg/detectors/gitlab/v3/gitlab_v3_integration_test.go+++ b/pkg/detectors/gitlab/v3/gitlab_v3_integration_test.go@@ -124,7 +124,7 @@ func TestGitlabV3_FromChunk(t *testing.T) {},{name: "found, good key but wrong scope",- s: Scanner{client: common.ConstantResponseHttpClient(403, "")},+ s: Scanner{client: common.ConstantResponseHttpClient(403, `{"error":"insufficient_scope","error_description":"The request requires higher privileges than provided by the access token.","scope":"read_user api read_api"}`)},args: args{ctx: context.Background(),data: []byte(fmt.Sprintf("You can find a gitlab super secret %s within", secret)),@@ -142,6 +142,27 @@ func TestGitlabV3_FromChunk(t *testing.T) {},wantErr: false,},+ {+ name: "found but ambiguous 403 (not insufficient_scope)",+ s: Scanner{client: common.ConstantResponseHttpClient(403, "")},+ args: args{+ ctx: context.Background(),+ data: []byte(fmt.Sprintf("You can find a gitlab super secret %s within", secret)),+ verify: true,+ },+ want: []detectors.Result{+ {+ DetectorType: detector_typepb.DetectorType_Gitlab,+ Verified: false,+ ExtraData: map[string]string{+ "rotation_guide": "https://howtorotate.com/docs/tutorials/gitlab/",+ "version": "3",+ },+ },+ },+ wantErr: false,+ wantVerificationErr: true,+ },{name: "not found",s: Scanner{},diff --git a/pkg/detectors/gitlab/v3/gitlab_v3_test.go b/pkg/detectors/gitlab/v3/gitlab_v3_test.goindex 4a901baf7..80f84dd20 100644--- a/pkg/detectors/gitlab/v3/gitlab_v3_test.go+++ b/pkg/detectors/gitlab/v3/gitlab_v3_test.go@@ -39,6 +39,11 @@ func TestGitLab_Pattern(t *testing.T) {}]`,want: []string{"glpat-3fZ1p5y4XWcCvMGVlfakeW86MQp1Oml3Ymg0Cw.01.1203afakehttps://gitlab.com"},},+ {+ name: "low-entropy placeholder",+ input: `gitlab_secret = "glpat-xxxxxxxxxxxxxxxxxxxxxxxxxxx.xx.xxxxxxxxx"`,+ want: nil,+ },}for _, test := range tests {