Skip to content

Update AzureDevops scanner #4244

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
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,14 @@ var _ detectors.Detector = (*Scanner)(nil)

var (
defaultClient = 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{"azure"}) + `\b([0-9a-z]{52})\b`)
keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"azure", "token", "pat", "vsce"}) + `[:\s]?\s*["']?([0-9a-z]{52})["']?\b`)
orgPat = regexp.MustCompile(detectors.PrefixRegex([]string{"azure"}) + `\b([0-9a-zA-Z][0-9a-zA-Z-]{5,48}[0-9a-zA-Z])\b`)
)

// 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{"azure"}
return []string{"azure", "token", "pat", "vsce"}
}

// FromData will find and optionally verify AzureDevopsPersonalAccessToken secrets in a given set of bytes.
Expand All @@ -43,6 +42,27 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result

for _, match := range matches {
resMatch := strings.TrimSpace(match[1])

Copy link
Contributor

Choose a reason for hiding this comment

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

I’ve raised some concerns about this new approach with the internal team.

Copy link
Author

Choose a reason for hiding this comment

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

I wondered if this shouldn't be another detector at all, might be better choice

// First case it matches a pattern without org
s1 := detectors.Result{
DetectorType: detectorspb.DetectorType_AzureDevopsPersonalAccessToken,
Raw: []byte(resMatch),
RawV2: []byte(resMatch),
}
if verify {
client := s.client
if client == nil {
client = defaultClient
}
isVerified, verificationErr := verifyPAT(ctx, client, resMatch)
s1.Verified = isVerified
if verificationErr != nil {
s1.SetVerificationError(verificationErr, resMatch)
}
}
results = append(results, s1)

// Second case: It matches an org
for _, orgMatch := range orgMatches {
resOrgMatch := strings.TrimSpace(orgMatch[1])

Expand All @@ -57,25 +77,10 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
if client == nil {
client = defaultClient
}
req, err := http.NewRequestWithContext(ctx, "GET", "https://dev.azure.com/"+resOrgMatch+"/_apis/projects", nil)
if err != nil {
continue
}
req.SetBasicAuth("", resMatch)
res, err := client.Do(req)
if err == nil {
defer res.Body.Close()
hasVerifiedRes, _ := common.ResponseContainsSubstring(res.Body, "lastUpdateTime")
if res.StatusCode >= 200 && res.StatusCode < 300 && hasVerifiedRes {
s1.Verified = true
} else if res.StatusCode == 401 {
// The secret is determinately not verified (nothing to do)
} else {
err = fmt.Errorf("unexpected HTTP response status %d", res.StatusCode)
s1.SetVerificationError(err, resMatch)
}
} else {
s1.SetVerificationError(err, resMatch)
isVerified, verificationErr := verifyOrgPAT(ctx, client, resMatch, resOrgMatch)
s1.Verified = isVerified
if verificationErr != nil {
s1.SetVerificationError(verificationErr, resMatch)
}
}

Expand All @@ -93,3 +98,56 @@ func (s Scanner) Type() detectorspb.DetectorType {
func (s Scanner) Description() string {
return "Azure DevOps is a suite of development tools provided by Microsoft. Personal Access Tokens (PATs) are used to authenticate and authorize access to Azure DevOps services and resources."
}

// verifyPAT verifies if the Azure DevOps Personal Access Token is valid
func verifyPAT(ctx context.Context, client *http.Client, token string) (bool, error) {
req, err := http.NewRequestWithContext(ctx, "OPTIONS", "https://marketplace.visualstudio.com/_apis/securityroles", nil)
if err != nil {
return false, err
}

req.SetBasicAuth("OAuth", token)
req.Header.Add("Accept", "application/json")
req.Header.Add("User-Agent", "node-SecurityRoles-api")
req.Header.Add("X-Tfs-Fedauthredirect", "Suppress")
req.Header.Add("Connection", "close")

res, err := client.Do(req)
if err != nil {
return false, err
}
defer res.Body.Close()

if res.StatusCode >= 200 && res.StatusCode < 300 {
return true, nil
} else if res.StatusCode == 401 {
// The secret is determinately not verified
return false, nil
} else {
return false, fmt.Errorf("unexpected HTTP response status %d", res.StatusCode)
}
}

// verifyOrgPAT verifies if the Azure DevOps Personal Access Token is valid for a specific organization
func verifyOrgPAT(ctx context.Context, client *http.Client, token, org string) (bool, error) {
req, err := http.NewRequestWithContext(ctx, "GET", "https://dev.azure.com/"+org+"/_apis/projects", nil)
if err != nil {
return false, err
}
req.SetBasicAuth("", token)
res, err := client.Do(req)
if err != nil {
return false, err
}
defer res.Body.Close()

hasVerifiedRes, _ := common.ResponseContainsSubstring(res.Body, "lastUpdateTime")
if res.StatusCode >= 200 && res.StatusCode < 300 && hasVerifiedRes {
return true, nil
} else if res.StatusCode == 401 {
// The secret is determinately not verified
return false, nil
} else {
return false, fmt.Errorf("unexpected HTTP response status %d", res.StatusCode)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ var (
azure_key: uie5tff7m5h5lqnqjhaltetqli90a08p6dhv9rn59uo30jgzw8un
azure_org_id: WOkQXnjSxCyioEJRa8R6J39cN4Xfyy8CWl1BZksHYsevxVBFzG
`
validPatternNoOrg = `
azure:
azure_key: uie5tff7m5h5lqnqjhaltetqli90a08p6dhv9rn59uo30jgzw8un
`
invalidPattern = `
azure:
azure_key: uie5tff7m5H5lqnqjhaltetqli90a08p6dhv9rn59uo30jgzw8un
Expand All @@ -33,9 +37,17 @@ func TestAzureDevopsPersonalAccessToken_Pattern(t *testing.T) {
want []string
}{
{
name: "valid pattern",
name: "valid pattern with org",
input: validPattern,
want: []string{"uie5tff7m5h5lqnqjhaltetqli90a08p6dhv9rn59uo30jgzw8unWOkQXnjSxCyioEJRa8R6J39cN4Xfyy8CWl1BZksHYsevxVBFzG"},
want: []string{
"uie5tff7m5h5lqnqjhaltetqli90a08p6dhv9rn59uo30jgzw8un", // token only
"uie5tff7m5h5lqnqjhaltetqli90a08p6dhv9rn59uo30jgzw8unWOkQXnjSxCyioEJRa8R6J39cN4Xfyy8CWl1BZksHYsevxVBFzG", // token + org
},
},
{
name: "valid pattern without org",
input: validPatternNoOrg,
want: []string{"uie5tff7m5h5lqnqjhaltetqli90a08p6dhv9rn59uo30jgzw8un"}, // token only
},
{
name: "invalid pattern",
Expand Down