Skip to content
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

fix: fixed verifcation pattern logic for bulksms #3478

Merged
merged 5 commits into from
Oct 25, 2024

Conversation

sahil9001
Copy link
Contributor

@sahil9001 sahil9001 commented Oct 19, 2024

Description:

Fixes #3477

Screenshot 2024-10-19 at 1 51 50 PM

Checklist:

  • Tests passing (make test-community)?
  • Lint passing (make lint this requires golangci-lint)?

@@ -24,7 +25,7 @@ var (
client = common.SaneHttpClient()

// Make sure that your group is surrounded in boundary characters such as below to reduce false positives
keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"bulksms"}) + `\b([a-fA-Z0-9*]{29})\b`)
keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"bulksms"}) + `\b([a-zA-Z0-9!@#$%^&*()]{29})\b`)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I generated over 10 tokens, and it appears the new regex is correct. So far, I’ve only received tokens containing the special characters !_*#, though I believe other special characters are possible.

Potential Improvements for the Detector:

  • Instead of manually encoding the key and ID for basic authentication, we can leverage the SetBasicAuth function to simplify the process.
  • Currently, we consider the result verified if the API returns a status code between 200 and 300. We could improve this by being more specific. Let's add the comment to reference the API docs as well.
  • Based on my observations, both the ID and key are unique for each token generation. If a key is verified successfully with any ID, we can skip the remaining verification attempts for that key and proceed to the next one.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the review @kashifkhan0771 , I have addressed the changes

@@ -59,25 +59,30 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
}

if verify {
data := fmt.Sprintf("%s:%s", resIdMatch, resMatch)
sEnc := b64.StdEncoding.EncodeToString([]byte(data))
// data := fmt.Sprintf("%s:%s", resIdMatch, resMatch)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please remove these commented lines. Also I guess you missed the third point from my last review.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, I am unclear about the last point, are you talking about the tests? Can you please elaborate more?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The secret (Basic Auth token) is a combination of two components here, an ID and a Key. Both the ID and Key are unique for each secret as I observed after generating multiple tokens. Currently, we loop through each ID and attempt to verify it against all the available keys. [O(nxm)]

If we find 3 IDs and 3 Keys, we start by verifying the first ID with all the keys. If, on the first attempt, we successfully verify that the first ID and the first Key form a valid Basic Auth token, there is no need to check the remaining keys for that ID since it has already been verified. We can then move on to the next ID.

To further optimize this process, it would be more better to avoid comparing the remaining IDs with any keys that have already been verified with previous IDs. This would reduce the number of unnecessary comparisons and improve efficiency.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I have created a map of string -> boolean to mark the keys if a combination matches.

Comment on lines 41 to 70
keyMatches := keyPat.FindAllStringSubmatch(dataStr, -1)

verifiedKeys := make(map[string]bool)
verifiedIDs := make(map[string]bool)

for _, match := range matches {
if len(match) != 2 {
for _, idMatch := range idMatches {
if len(idMatch) != 2 {
continue
}
resMatch := strings.TrimSpace(match[1])
for _, idmatch := range idMatches {
if len(match) != 2 {
resIDMatch := strings.TrimSpace(idMatch[1])

if verifiedIDs[resIDMatch] {
continue
}

for _, keyMatch := range keyMatches {
if len(keyMatch) != 2 {
continue
}
resKeyMatch := strings.TrimSpace(keyMatch[1])

if verifiedKeys[resKeyMatch] {
continue
}
resIdMatch := strings.TrimSpace(idmatch[1])

s1 := detectors.Result{
DetectorType: detectorspb.DetectorType_Bulksms,
Raw: []byte(resMatch),
RawV2: []byte(resMatch + resIdMatch),
Raw: []byte(resKeyMatch),
RawV2: []byte(resKeyMatch + resIDMatch),
}
Copy link
Contributor

@kashifkhan0771 kashifkhan0771 Oct 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Few suggestions:

  • Can remove trim space funcs as there is no space in regex
  • Instead of creating map[string]bool, we can define map[string]struct{} and filter unique values before processing the matches. This will also keep it same as other detectors.

Suggested Code: (This is a suggestion code, you can run it locally and verify and make changes if required)

	var uniqueIds = make(map[string]struct{})
	var uniqueKeys = make(map[string]struct{})

	for _, match := range idPat.FindAllStringSubmatch(dataStr, -1) {
		uniqueIds[match[1]] = struct{}{}
	}

	for _, match := range keyPat.FindAllStringSubmatch(dataStr, -1) {
		uniqueKeys[match[1]] = struct{}{}
	}

	for id := range uniqueIds {
		for key := range uniqueKeys {
			s1 := detectors.Result{
				DetectorType: detectorspb.DetectorType_Bulksms,
				Raw:          []byte(key),
				RawV2:        []byte(key + id),
			}

			if verify {
				req, err := http.NewRequestWithContext(ctx, "GET", "https://api.bulksms.com/v1/messages", nil)
				if err != nil {
					continue
				}
				req.SetBasicAuth(id, key)
				res, err := client.Do(req)
				if err == nil {
					defer func() {
						_, _ = io.Copy(io.Discard, res.Body)
						_ = res.Body.Close()
					}()

					if res.StatusCode == http.StatusOK {
						s1.Verified = true
						results = append(results, s1)
						// move to next id, by skipping remaining key's
						break
					}
				} else {
					s1.SetVerificationError(err, key)
				}
			}

			results = append(results, s1)
		}
	}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @kashifkhan0771 , this method is better, I agree. I have made the changes and tested it too, please check.

Signed-off-by: Sahil Silare <sahilsilare@gmail.com>
Copy link
Contributor

@kashifkhan0771 kashifkhan0771 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@kashifkhan0771 kashifkhan0771 merged commit b48f748 into trufflesecurity:main Oct 25, 2024
13 checks passed
abmussani added a commit to abmussani/trufflehog that referenced this pull request Oct 30, 2024
* main: (76 commits)
  update aws descriptions (trufflesecurity#3529)
  enforce timeout on circleci test (trufflesecurity#3528)
  rm snifftest (trufflesecurity#3527)
  Redact more source credentials (trufflesecurity#3526)
  Create global log redaction capability (trufflesecurity#3522)
  Adding basic "what is trufflehog" to the readme (trufflesecurity#3514)
  Handle custom detector response and include in extra data (trufflesecurity#3411)
  fix: fixed validation logic for `calendarific` (trufflesecurity#3480)
  fix(deps): update github.com/tailscale/depaware digest to 3d7f3b3 (trufflesecurity#3518)
  Move DecoderType into ResultWithMetadata trufflesecurity#3502
  Addeded 403 account block status code handling for gitlab (trufflesecurity#3471)
  updated gcpapplicationdefaultcredentials detector results with RawV2 (trufflesecurity#3499)
  fix(deps): update module github.com/brianvoe/gofakeit/v7 to v7.1.1 (trufflesecurity#3512)
  fix(deps): update module github.com/schollz/progressbar/v3 to v3.17.0 (trufflesecurity#3510)
  fix(deps): update module cloud.google.com/go/secretmanager to v1.14.2 (trufflesecurity#3498)
  Adds a logging section in the contributing guidelines (trufflesecurity#3509)
  fix: fixed verifcation pattern logic for `bulksms` (trufflesecurity#3478)
  Extend `algoliaadminkey` with additional checks (trufflesecurity#3459)
  fix(deps): update module google.golang.org/api to v0.203.0 (trufflesecurity#3497)
  fix: added correct api endpoint for verification & logic for Aeroworkflow (trufflesecurity#3435)
  ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

Successfully merging this pull request may close these issues.

Issue with verification logic & tests for bulksms
2 participants