-
Notifications
You must be signed in to change notification settings - Fork 2.5k
feat: add Rancher/Cattle token detector #4997
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sridhar-3009
wants to merge
4
commits into
trufflesecurity:main
Choose a base branch
from
sridhar-3009:feat/rancher-token-detector
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
ffc2490
feat: add Rancher/Cattle token detector
sridhar-3009 9bf0780
fix: address Cursor Bugbot review on rancher detector
sridhar-3009 df672a6
fix: scope (?i) to variable prefix only; move rancher to alphabetical…
sridhar-3009 19490ee
fix: propagate verifyToken errors via SetVerificationError
sridhar-3009 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| package rancher | ||
|
|
||
| import ( | ||
| "context" | ||
| "net/http" | ||
| "strings" | ||
|
|
||
| regexp "github.com/wasilibs/go-re2" | ||
|
|
||
| "github.com/trufflesecurity/trufflehog/v3/pkg/detectors" | ||
| "github.com/trufflesecurity/trufflehog/v3/pkg/pb/detector_typepb" | ||
| ) | ||
|
|
||
| type Scanner struct { | ||
| detectors.DefaultMultiPartCredentialProvider | ||
| } | ||
|
|
||
| var _ detectors.Detector = (*Scanner)(nil) | ||
|
|
||
| var ( | ||
| // Use the SSRF-safe client that blocks requests to local/private IP ranges. | ||
| client = detectors.DetectorHttpClientWithNoLocalAddresses | ||
|
|
||
| // Match variable name case-insensitively via (?i:...) scope, then require strictly | ||
| // lowercase alphanumeric token to avoid false positives from the broad character set. | ||
| keyPat = regexp.MustCompile(`(?i:(?:CATTLE_TOKEN|RANCHER_TOKEN|CATTLE_BOOTSTRAP_PASSWORD|RANCHER_API_TOKEN)[\w]*\s*[=:]\s*["']?)([a-z0-9]{54,64})["']?`) | ||
|
|
||
| // Server URL used for validation; must appear nearby in the same chunk. | ||
| serverPat = regexp.MustCompile(`(?i:(?:CATTLE_SERVER|RANCHER_URL|RANCHER_SERVER)\s*[=:]\s*["']?)(https?://[^\s"']+)["']?`) | ||
| ) | ||
|
|
||
| func (s Scanner) Keywords() []string { | ||
| return []string{"CATTLE_TOKEN", "RANCHER_TOKEN", "CATTLE_BOOTSTRAP_PASSWORD", "RANCHER_API_TOKEN"} | ||
| } | ||
|
|
||
| func verifyToken(ctx context.Context, serverURL, token string) (bool, error) { | ||
| req, err := http.NewRequestWithContext(ctx, "GET", serverURL+"/v3", nil) | ||
| if err != nil { | ||
| return false, err | ||
| } | ||
| req.Header.Set("Authorization", "Bearer "+token) | ||
|
|
||
| res, err := client.Do(req) | ||
| if err != nil { | ||
| return false, err | ||
| } | ||
| defer func() { _ = res.Body.Close() }() | ||
| return res.StatusCode == http.StatusOK, nil | ||
| } | ||
|
|
||
| func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) { | ||
| dataStr := string(data) | ||
|
|
||
| tokenMatches := keyPat.FindAllStringSubmatch(dataStr, -1) | ||
| serverMatches := serverPat.FindAllStringSubmatch(dataStr, -1) | ||
|
|
||
| for _, tokenMatch := range tokenMatches { | ||
| token := strings.TrimSpace(tokenMatch[1]) | ||
|
|
||
| s1 := detectors.Result{ | ||
| DetectorType: detector_typepb.DetectorType_RancherToken, | ||
| Raw: []byte(token), | ||
| SecretParts: map[string]string{"token": token}, | ||
| } | ||
|
|
||
| if verify && len(serverMatches) > 0 { | ||
| serverURL := strings.TrimRight(strings.TrimSpace(serverMatches[0][1]), "/") | ||
| verified, verifyErr := verifyToken(ctx, serverURL, token) | ||
| if verifyErr != nil { | ||
| s1.SetVerificationError(verifyErr, token) | ||
| } else { | ||
| s1.Verified = verified | ||
| } | ||
| } | ||
|
|
||
| results = append(results, s1) | ||
| } | ||
|
|
||
| return results, nil | ||
| } | ||
|
|
||
| func (s Scanner) Type() detector_typepb.DetectorType { | ||
| return detector_typepb.DetectorType_RancherToken | ||
| } | ||
|
|
||
| func (s Scanner) Description() string { | ||
| return "Rancher is a Kubernetes management platform. Rancher API tokens provide full cluster admin access and must be protected." | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| package rancher | ||
|
|
||
| import ( | ||
| "context" | ||
| "testing" | ||
|
|
||
| "github.com/google/go-cmp/cmp" | ||
|
|
||
| "github.com/trufflesecurity/trufflehog/v3/pkg/detectors" | ||
| "github.com/trufflesecurity/trufflehog/v3/pkg/engine/ahocorasick" | ||
| ) | ||
|
|
||
| var ( | ||
| // Fake token and server for pattern matching tests only. | ||
| validInput = ` | ||
| CATTLE_SERVER=https://rancher.example.com | ||
| CATTLE_TOKEN=jswpl27hs8pd88rmw2mgfgrjtpljp85fd5v7rhdwr2s6z22hvt6vjt | ||
| ` | ||
| validToken = "jswpl27hs8pd88rmw2mgfgrjtpljp85fd5v7rhdwr2s6z22hvt6vjt" | ||
|
|
||
| invalidInput = ` | ||
| # random string without Rancher context | ||
| random_data = "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuv" | ||
| ` | ||
| ) | ||
|
|
||
| func TestRancher_Pattern(t *testing.T) { | ||
| d := Scanner{} | ||
| ahoCorasickCore := ahocorasick.NewAhoCorasickCore([]detectors.Detector{d}) | ||
|
|
||
| tests := []struct { | ||
| name string | ||
| input string | ||
| want []string | ||
| }{ | ||
| { | ||
| name: "valid CATTLE_TOKEN pattern", | ||
| input: validInput, | ||
| want: []string{validToken}, | ||
| }, | ||
| { | ||
| name: "no match without cattle/rancher variable name", | ||
| input: invalidInput, | ||
| want: []string{}, | ||
| }, | ||
| } | ||
|
|
||
| for _, test := range tests { | ||
| t.Run(test.name, func(t *testing.T) { | ||
| matchedDetectors := ahoCorasickCore.FindDetectorMatches([]byte(test.input)) | ||
| if len(test.want) == 0 { | ||
| if len(matchedDetectors) != 0 { | ||
| t.Errorf("expected no matches, got %d", len(matchedDetectors)) | ||
| } | ||
| return | ||
| } | ||
| if len(matchedDetectors) == 0 { | ||
| t.Errorf("keywords '%v' not matched by: %s", d.Keywords(), test.input) | ||
| return | ||
| } | ||
|
|
||
| results, err := d.FromData(context.Background(), false, []byte(test.input)) | ||
| if err != nil { | ||
| t.Errorf("error = %v", err) | ||
| return | ||
| } | ||
|
|
||
| got := make([]string, len(results)) | ||
| for i, r := range results { | ||
| got[i] = string(r.Raw) | ||
| } | ||
|
|
||
| if diff := cmp.Diff(test.want, got); diff != "" { | ||
| t.Errorf("mismatch (-want +got):\n%s", diff) | ||
| } | ||
| }) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -1054,4 +1054,5 @@ enum DetectorType { | |
| GitLabOauth2 = 1050; | ||
| SpectralOps = 1051; | ||
| AWSAppSync = 1052; | ||
| RancherToken = 1053; | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Verification errors silently swallowed, misclassifying results
Medium Severity
verifyTokenreturns onlybool, swallowing all errors (network timeouts, DNS failures, non-200 status codes). BecauseSetVerificationErroris never called, the engine atengine.go:1274misclassifies transient verification failures as definitively "unverified" instead of "unknown." Users filtering with--results=verified,unknownwill silently miss these results. The established pattern (seen inapiflash.go,abstract.go, and most other detectors) is to return(bool, error)and calls1.SetVerificationError(...).Additional Locations (1)
pkg/detectors/rancher/rancher.go#L65-L69Reviewed by Cursor Bugbot for commit df672a6. Configure here.