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

Detector-Competition-Fix: Fix LiveAgent Detector & Verifier #2001

Merged
merged 8 commits into from
Nov 3, 2023
Merged
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
72 changes: 50 additions & 22 deletions pkg/detectors/liveagent/liveagent.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package liveagent

import (
"context"
"encoding/json"
"net/http"
"regexp"
"strings"
Expand All @@ -20,53 +21,80 @@ 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{"liveagent"}) + `\b([a-zA-Z0-9]{32})\b`)
domainPat = regexp.MustCompile(`\b(https?://[A-Za-z0-9-]+\.ladesk\.com)\b`)
keyPat = regexp.MustCompile(detectors.PrefixRegex([]string{"liveagent", "apikey"}) + `\b([a-zA-Z0-9]{32})\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{"liveagent"}
return []string{"liveagent", "ladesk"}
}

type response struct {
Message string `json:"message"`
}

// FromData will find and optionally verify LiveAgent secrets in a given set of bytes.
func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {
dataStr := string(data)

domainMatches := domainPat.FindAllStringSubmatch(dataStr, -1)
matches := keyPat.FindAllStringSubmatch(dataStr, -1)

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

s1 := detectors.Result{
DetectorType: detectorspb.DetectorType_LiveAgent,
Raw: []byte(resMatch),
}
resMatch := strings.TrimSpace(match[1])

if verify {
req, err := http.NewRequestWithContext(ctx, "GET", "https://secretscanner.ladesk.com/api/v3/agents", nil)
if err != nil {
for _, domainMatch := range domainMatches {
if len(domainMatch) != 2 {
continue
}
req.Header.Add("apikey", resMatch)
res, err := client.Do(req)
if err == nil {
defer res.Body.Close()
if res.StatusCode >= 200 && res.StatusCode < 300 {
s1.Verified = true
} else {
// This function will check false positives for common test words, but also it will make sure the key appears 'random' enough to be a real key.
if detectors.IsKnownFalsePositive(resMatch, detectors.DefaultFalsePositives, true) {
continue
domainRes := strings.TrimSpace(domainMatch[0])
s1 := detectors.Result{
DetectorType: detectorspb.DetectorType_LiveAgent,
Raw: []byte(resMatch),
ExtraData: map[string]string{
"domain": domainRes,
},
}

if verify {
req, err := http.NewRequestWithContext(ctx, "GET", domainRes+"/api/v3/agents", nil)
if err != nil {
continue
}
req.Header.Add("apikey", resMatch)
res, err := client.Do(req)
if err == nil {
defer res.Body.Close()
if res.StatusCode >= 200 && res.StatusCode < 300 {
s1.Verified = true
} else if res.StatusCode == 403 {
var r response
if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
s1.VerificationError = err
continue
}

// If the message is "You do not have sufficient privileges", then the key is valid, but does not have access to the `/agents` endpoint.
if r.Message == "You do not have sufficient privileges" {
s1.Verified = true
}
} else {
// This function will check false positives for common test words, but also it will make sure the key appears 'random' enough to be a real key.
if detectors.IsKnownFalsePositive(resMatch, detectors.DefaultFalsePositives, true) {
continue
}
}
}
}
}

results = append(results, s1)
results = append(results, s1)
}
}

return results, nil
Expand Down
17 changes: 15 additions & 2 deletions pkg/detectors/liveagent/liveagent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package liveagent
import (
"context"
"fmt"
"net/url"
"testing"
"time"

Expand All @@ -23,8 +24,14 @@ func TestLiveAgent_FromChunk(t *testing.T) {
if err != nil {
t.Fatalf("could not get test secrets from GCP: %s", err)
}
deskUrl := testSecrets.MustGetField("LIVEAGENT_URL")
secret := testSecrets.MustGetField("LIVEAGENT_TOKEN")
inactiveSecret := testSecrets.MustGetField("LIVEAGENT_INACTIVE")
u, err := url.Parse(deskUrl)
if err != nil {
t.Fatalf("could not parse LIVEAGENT_URL: %s", err)
}
wantUrl := u.Scheme + "://" + u.Hostname()

type args struct {
ctx context.Context
Expand All @@ -43,13 +50,16 @@ func TestLiveAgent_FromChunk(t *testing.T) {
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf("You can find a liveagent secret %s within", secret)),
data: []byte(fmt.Sprintf("You can find a liveagent secret %s within for %s", secret, deskUrl)),
verify: true,
},
want: []detectors.Result{
{
DetectorType: detectorspb.DetectorType_LiveAgent,
Verified: true,
ExtraData: map[string]string{
"domain": wantUrl,
},
},
},
wantErr: false,
Expand All @@ -59,13 +69,16 @@ func TestLiveAgent_FromChunk(t *testing.T) {
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf("You can find a liveagent secret %s within but not valid", inactiveSecret)), // the secret would satisfy the regex but not pass validation
data: []byte(fmt.Sprintf("You can find a liveagent secret %s within but not valid for %s", inactiveSecret, deskUrl)), // the secret would satisfy the regex but not pass validation
verify: true,
},
want: []detectors.Result{
{
DetectorType: detectorspb.DetectorType_LiveAgent,
Verified: false,
ExtraData: map[string]string{
"domain": wantUrl,
},
},
},
wantErr: false,
Expand Down