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.

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
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