Skip to content

Commit

Permalink
Merge branch 'main' into update/gcpapplicationdefaultcreds-detector
Browse files Browse the repository at this point in the history
  • Loading branch information
kashifkhan0771 authored Oct 25, 2024
2 parents c2ff0f2 + b48f748 commit 9470c9e
Show file tree
Hide file tree
Showing 13 changed files with 179 additions and 471 deletions.
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ require (
golang.org/x/oauth2 v0.23.0
golang.org/x/sync v0.8.0
golang.org/x/text v0.19.0
google.golang.org/api v0.202.0
google.golang.org/api v0.203.0
google.golang.org/protobuf v1.35.1
gopkg.in/h2non/gock.v1 v1.1.2
gopkg.in/yaml.v2 v2.4.0
Expand All @@ -121,7 +121,7 @@ require (
require (
cel.dev/expr v0.16.1 // indirect
cloud.google.com/go v0.116.0 // indirect
cloud.google.com/go/auth v0.9.8 // indirect
cloud.google.com/go/auth v0.9.9 // indirect
cloud.google.com/go/auth/oauth2adapt v0.2.4 // indirect
cloud.google.com/go/compute/metadata v0.5.2 // indirect
cloud.google.com/go/iam v1.2.1 // indirect
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ cloud.google.com/go/auth v0.9.5 h1:4CTn43Eynw40aFVr3GpPqsQponx2jv0BQpjvajsbbzw=
cloud.google.com/go/auth v0.9.5/go.mod h1:Xo0n7n66eHyOWWCnitop6870Ilwo3PiZyodVkkH1xWM=
cloud.google.com/go/auth v0.9.8 h1:+CSJ0Gw9iVeSENVCKJoLHhdUykDgXSc4Qn+gu2BRtR8=
cloud.google.com/go/auth v0.9.8/go.mod h1:xxA5AqpDrvS+Gkmo9RqrGGRh6WSNKKOXhY3zNOr38tI=
cloud.google.com/go/auth v0.9.9 h1:BmtbpNQozo8ZwW2t7QJjnrQtdganSdmqeIBxHxNkEZQ=
cloud.google.com/go/auth v0.9.9/go.mod h1:xxA5AqpDrvS+Gkmo9RqrGGRh6WSNKKOXhY3zNOr38tI=
cloud.google.com/go/auth/oauth2adapt v0.2.4 h1:0GWE/FUsXhf6C+jAkWgYm7X9tK8cuEIfy19DBn6B6bY=
cloud.google.com/go/auth/oauth2adapt v0.2.4/go.mod h1:jC/jOpwFP6JBxhB3P5Rr0a9HLMC/Pe3eaL4NmdvqPtc=
cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o=
Expand Down Expand Up @@ -1135,6 +1137,8 @@ google.golang.org/api v0.201.0 h1:+7AD9JNM3tREtawRMu8sOjSbb8VYcYXJG/2eEOmfDu0=
google.golang.org/api v0.201.0/go.mod h1:HVY0FCHVs89xIW9fzf/pBvOEm+OolHa86G/txFezyq4=
google.golang.org/api v0.202.0 h1:y1iuVHMqokQbimW79ZqPZWo4CiyFu6HcCYHwSNyzlfo=
google.golang.org/api v0.202.0/go.mod h1:3Jjeq7M/SFblTNCp7ES2xhq+WvGL0KeXI0joHQBfwTQ=
google.golang.org/api v0.203.0 h1:SrEeuwU3S11Wlscsn+LA1kb/Y5xT8uggJSkIhD08NAU=
google.golang.org/api v0.203.0/go.mod h1:BuOVyCSYEPwJb3npWvDnNmFI92f3GeRnHNkETneT3SI=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
Expand Down
4 changes: 2 additions & 2 deletions pkg/detectors/aeroworkflow/aeroworkflow.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ 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{"aeroworkflow"}) + `([a-zA-Z0-9^!?#:*;]{20})\b`)
keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"aeroworkflow"}) + `\b([a-zA-Z0-9^!?#:*;]{20})`)
idPat = regexp.MustCompile(detectors.PrefixRegex([]string{"aeroworkflow"}) + `\b([0-9]{1,})\b`)
)

Expand Down Expand Up @@ -85,7 +85,7 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
}

func verifyAeroworkflow(ctx context.Context, client *http.Client, resMatch, resIdMatch string) (bool, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, aeroworkflowURL+"/api/"+resIdMatch+"/v1/AeroAppointments", nil)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, aeroworkflowURL+"/api/"+resIdMatch+"/me", nil)
if err != nil {
return false, err
}
Expand Down
80 changes: 52 additions & 28 deletions pkg/detectors/alegra/alegra.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package alegra

import (
"context"
"fmt"
"io"
"net/http"
"strings"

Expand All @@ -13,18 +15,17 @@ import (
)

type Scanner struct {
detectors.DefaultMultiPartCredentialProvider
client *http.Client
}

// Ensure the Scanner satisfies the interface at compile time.
var _ detectors.Detector = (*Scanner)(nil)

var (
client = common.SaneHttpClient()

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{"alegra"}) + `\b([a-z0-9-]{20})\b`)
idPat = regexp.MustCompile(detectors.PrefixRegex([]string{"alegra"}) + `\b([a-zA-Z0-9\.\-\@]{25,30})\b`)
idPat = regexp.MustCompile(detectors.PrefixRegex([]string{"alegra"}) + common.EmailPattern)
)

// Keywords are used for efficiently pre-filtering chunks.
Expand All @@ -37,41 +38,38 @@ func (s Scanner) Keywords() []string {
func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {
dataStr := string(data)

matches := keyPat.FindAllStringSubmatch(dataStr, -1)
keyMatches := keyPat.FindAllStringSubmatch(dataStr, -1)
idMatches := idPat.FindAllStringSubmatch(dataStr, -1)

for _, match := range matches {
if len(match) != 2 {
continue
}
tokenPatMatch := strings.TrimSpace(match[1])
uniqueTokens := make(map[string]struct{})
uniqueIDs := make(map[string]struct{})

for _, idMatch := range idMatches {
if len(idMatch) != 2 {
continue
}
for _, match := range keyMatches {
uniqueTokens[match[1]] = struct{}{}
}

userPatMatch := strings.TrimSpace(idMatch[1])
for _, match := range idMatches {
id := match[0][strings.LastIndex(match[0], " ")+1:]
uniqueIDs[id] = struct{}{}
}

for token := range uniqueTokens {
for id := range uniqueIDs {
s1 := detectors.Result{
DetectorType: detectorspb.DetectorType_Alegra,
Raw: []byte(tokenPatMatch),
RawV2: []byte(tokenPatMatch + userPatMatch),
Raw: []byte(token),
RawV2: []byte(token + ":" + id),
}

if verify {
req, err := http.NewRequestWithContext(ctx, "GET", "https://api.alegra.com/api/v1/users", nil)
if err != nil {
continue
}
req.SetBasicAuth(userPatMatch, tokenPatMatch)
res, err := client.Do(req)
if err == nil {
defer res.Body.Close()
if res.StatusCode >= 200 && res.StatusCode < 300 {
s1.Verified = true
}
client := s.client
if client == nil {
client = defaultClient
}

isVerified, verificationErr := verifyCredentials(ctx, client, id, token)
s1.Verified = isVerified
s1.SetVerificationError(verificationErr, token)
}

results = append(results, s1)
Expand All @@ -81,6 +79,32 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
return results, nil
}

func verifyCredentials(ctx context.Context, client *http.Client, username, token string) (bool, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.alegra.com/api/v1/users/self", nil)
if err != nil {
return false, nil
}
req.SetBasicAuth(username, token)

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

switch res.StatusCode {
case http.StatusOK:
return true, nil
case http.StatusUnauthorized:
return false, nil
default:
return false, fmt.Errorf("unexpected HTTP response status %d", res.StatusCode)
}
}

func (s Scanner) Type() detectorspb.DetectorType {
return detectorspb.DetectorType_Alegra
}
Expand Down
1 change: 1 addition & 0 deletions pkg/detectors/alegra/alegra_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ func TestAlegra_FromChunk(t *testing.T) {
t.Fatalf("no raw secret present: \n %+v", got[i])
}
got[i].Raw = nil
got[i].RawV2 = nil
}
if diff := pretty.Compare(got, tt.want); diff != "" {
t.Errorf("Alegra.FromData() %s diff: (-got +want)\n%s", tt.name, diff)
Expand Down
22 changes: 9 additions & 13 deletions pkg/detectors/alegra/alegra_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
var (
validPattern = "wdvn-usa87a-fxp9ioas/[email protected]"
validSpecialCharPattern = "wdvn-usa87a-fxp9ioas / [email protected]"
invalidPattern = "wdvn-usa87a-fxp9ioas/testUser$1005@example.com"
invalidPattern = "wdvn-usa87a-fxp9ioasQQsstestUsQQ@example"
)

func TestAlegra_Pattern(t *testing.T) {
Expand All @@ -28,30 +28,30 @@ func TestAlegra_Pattern(t *testing.T) {
}{
{
name: "valid pattern",
input: fmt.Sprintf("alegra: '%s'", validPattern),
want: []string{"wdvn-usa87a-fxp9ioastestUser[email protected]"},
input: fmt.Sprintf("alegra: %s", validPattern),
want: []string{"wdvn-usa87a-fxp9ioas:wdvn-usa87a-fxp9ioas/testUser[email protected]"},
},
{
name: "valid pattern - with special characters",
input: fmt.Sprintf("alegra: '%s'", validSpecialCharPattern),
want: []string{"wdvn-usa87a-fxp9ioastest[email protected]"},
input: fmt.Sprintf("alegra: %s", validSpecialCharPattern),
want: []string{"wdvn-usa87a-fxp9ioas:test[email protected]"},
},
{
name: "valid pattern - key out of prefix range",
input: fmt.Sprintf("alegra keyword is not close to the real key and id = '%s'", validPattern),
input: fmt.Sprintf("alegra keyword is not close to the real key and id = %s", validPattern),
want: nil,
},
{
name: "invalid pattern",
input: fmt.Sprintf("alegra: '%s'", invalidPattern),
input: fmt.Sprintf("alegra: %s", invalidPattern),
want: nil,
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
matchedDetectors := ahoCorasickCore.FindDetectorMatches([]byte(test.input))
if len(matchedDetectors) == 0 {
if len(matchedDetectors) == 0 && test.want != nil {
t.Errorf("keywords '%v' not matched by: %s", d.Keywords(), test.input)
return
}
Expand All @@ -63,11 +63,7 @@ func TestAlegra_Pattern(t *testing.T) {
}

if len(results) != len(test.want) {
if len(results) == 0 {
t.Errorf("did not receive result")
} else {
t.Errorf("expected %d results, only received %d", len(test.want), len(results))
}
t.Errorf("expected %d results, got %d", len(test.want), len(results))
return
}

Expand Down
91 changes: 76 additions & 15 deletions pkg/detectors/algoliaadminkey/algoliaadminkey.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package algoliaadminkey

import (
"context"
"fmt"
"encoding/json"
regexp "github.com/wasilibs/go-re2"
"net/http"
"strings"
Expand All @@ -22,14 +24,14 @@ 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{"algolia"}) + `\b([a-zA-Z0-9]{32})\b`)
idPat = regexp.MustCompile(detectors.PrefixRegex([]string{"algolia"}) + `\b([A-Z0-9]{10})\b`)
keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"algolia", "docsearch", "apiKey"}) + `\b([a-zA-Z0-9]{32})\b`)
idPat = regexp.MustCompile(detectors.PrefixRegex([]string{"algolia", "docsearch", "appId"}) + `\b([A-Z0-9]{10})\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{"algolia"}
return []string{"algolia", "docsearch"}
}

// FromData will find and optionally verify AlgoliaAdminKey secrets in a given set of bytes.
Expand Down Expand Up @@ -57,19 +59,16 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
}

if verify {
req, err := http.NewRequestWithContext(ctx, "GET", "https://"+resIdMatch+"-dsn.algolia.net/1/keys", nil)
if err != nil {
continue
}
req.Header.Add("X-Algolia-Application-Id", resIdMatch)
req.Header.Add("X-Algolia-API-Key", resMatch)
res, err := client.Do(req)
if err == nil {
defer res.Body.Close()
if res.StatusCode >= 200 && res.StatusCode < 300 {
s1.Verified = true
}
// Verify if the key is a valid Algolia Admin Key.
isVerified, verificationErr := verifyAlgoliaKey(ctx, resIdMatch, resMatch)

// Verify if the key has sensitive permissions, even if it's not an Admin Key.
if !isVerified {
isVerified, verificationErr = verifyAlgoliaKeyACL(ctx, resIdMatch, resMatch)
}

s1.SetVerificationError(verificationErr, resMatch)
s1.Verified = isVerified
}

results = append(results, s1)
Expand All @@ -78,6 +77,68 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
return results, nil
}

func verifyAlgoliaKey(ctx context.Context, appId, apiKey string) (bool, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://"+appId+"-dsn.algolia.net/1/keys", nil)
if err != nil {
return false, err
}

req.Header.Add("X-Algolia-Application-Id", appId)
req.Header.Add("X-Algolia-API-Key", apiKey)

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

if res.StatusCode == 403 {
return false, nil
} else if res.StatusCode < 200 || res.StatusCode > 299 {
return false, fmt.Errorf("unexpected HTTP response status %d", res.StatusCode)
}

return true, nil
}

func verifyAlgoliaKeyACL(ctx context.Context, appId, apiKey string) (bool, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://"+appId+".algolia.net/1/keys/"+apiKey, nil)
if err != nil {
return false, err
}

req.Header.Add("X-Algolia-Application-Id", appId)
req.Header.Add("X-Algolia-API-Key", apiKey)

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

if res.StatusCode == 403 {
return false, nil
} else if res.StatusCode < 200 || res.StatusCode > 299 {
return false, fmt.Errorf("unexpected HTTP response status %d", res.StatusCode)
}

var jsonResponse struct {
ACL []string `json:"acl"`
}

if err := json.NewDecoder(res.Body).Decode(&jsonResponse); err != nil {
return false, err
}

for _, acl := range jsonResponse.ACL {
if acl != "search" && acl != "listIndexes" && acl != "settings" {
return true, nil // Other permissions are sensitive.
}
}

return false, nil
}

func (s Scanner) Type() detectorspb.DetectorType {
return detectorspb.DetectorType_AlgoliaAdminKey
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ func TestAlgoliaAdminKey_FromChunk(t *testing.T) {
{
DetectorType: detectorspb.DetectorType_AlgoliaAdminKey,
Verified: true,
RawV2: []byte(fmt.Sprintf("%s%s", secret, id)),
},
},
wantErr: false,
Expand All @@ -67,6 +68,7 @@ func TestAlgoliaAdminKey_FromChunk(t *testing.T) {
{
DetectorType: detectorspb.DetectorType_AlgoliaAdminKey,
Verified: false,
RawV2: []byte(fmt.Sprintf("%s%s", inactiveSecret, id)),
},
},
wantErr: false,
Expand Down
Loading

0 comments on commit 9470c9e

Please sign in to comment.