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] - Dropbox detector #3406

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
84 changes: 51 additions & 33 deletions pkg/detectors/dropbox/dropbox.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,73 +3,91 @@ package dropbox
import (
"context"
"fmt"
regexp "github.com/wasilibs/go-re2"
"io"
"net/http"

regexp "github.com/wasilibs/go-re2"

"github.com/trufflesecurity/trufflehog/v3/pkg/common"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"
)

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

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

var (
keyPat = regexp.MustCompile(`\b(sl\.[A-Za-z0-9\-\_]{130,140})\b`)
Copy link
Contributor

Choose a reason for hiding this comment

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

It looks like this pattern matches older tokens. I've found several examples where the tail was 150. Perhaps both the new and old are necessary?

The new is sl.u., the old (?) is sl.B.

\b(sl\.B[A-Za-z0-9\-\_]{129,200})\b

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yea, that seems to track. I'll update a little later today. Thank you both ❤️

Copy link
Contributor

Choose a reason for hiding this comment

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

There's no period after the B.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

There are two types of tokens: an API explorer token, which is longer, and a regular access token, which is shorter. Should I create separate regex patterns for each or use separate detectors? I’m thinking separate detectors.

Copy link
Contributor

Choose a reason for hiding this comment

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

Are the endpoints and verification logic the same? You could create separate detectors but reuse the same logic.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I updated the PR to include both credentials in the test but left everything else unchanged. The endpoint seems to work for both, with the only difference being the token. 😅 Yea, okay i'll do that. 👍

defaultClient = common.SaneHttpClient()
keyPat = regexp.MustCompile(`sl\.u\.[0-9a-zA-Z_-]+`)
Copy link
Contributor

Choose a reason for hiding this comment

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

Are all the tokens as long as in the test? It's probably worth putting a minimum range here.

E.g., there's no point in trying for sl.u.a

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yea, that makes sense. The 5 that I generated were all 1309 characters long.

Copy link
Contributor

Choose a reason for hiding this comment

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

The 5 that I generated were all 1309 characters long.

Idk if they're all consistently 1,000+ characters. Even {250,} would likely be sufficient.

)

// 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{"sl."}
}
func (s Scanner) Keywords() []string { return []string{"sl.u."} }

// FromData will find and optionally verify Dropbox 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)

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

for _, match := range matches {
uniqueMatches := make(map[string]struct{})
for _, match := range keyPat.FindAllStringSubmatch(dataStr, -1) {
uniqueMatches[match[0]] = struct{}{}
}

result := detectors.Result{
for match := range uniqueMatches {
s1 := detectors.Result{
DetectorType: detectorspb.DetectorType_Dropbox,
Raw: []byte(match[1]),
Raw: []byte(match),
}

if verify {

baseURL := "https://api.dropboxapi.com/2/users/get_current_account"

client := common.SaneHttpClient()

req, err := http.NewRequestWithContext(ctx, "POST", baseURL, nil)
if err != nil {
continue
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", match[1]))
res, err := client.Do(req)
if err == nil {
res.Body.Close() // The request body is unused.

// 200 means good key for get current user
// 400 is bad (malformed)
// 403 bad scope
if res.StatusCode == http.StatusOK {
result.Verified = true
}
client := s.client
if client == nil {
client = defaultClient
}

isVerified, verificationErr := verifyMatch(ctx, client, match)
s1.Verified = isVerified
s1.SetVerificationError(verificationErr, match)
}

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

return
}

func verifyMatch(ctx context.Context, client *http.Client, token string) (bool, error) {
const baseURL = "https://api.dropboxapi.com/2/check/user"
req, err := http.NewRequestWithContext(ctx, http.MethodPost, baseURL, nil)
if err != nil {
return false, nil
}
req.Header.Add("Authorization", "Bearer "+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:
// 401 access token not found
// The secret is determinately not verified (nothing to do)
return false, nil
default:
return false, fmt.Errorf("unexpected HTTP response status %d", res.StatusCode)
}
}

func (s Scanner) Type() detectorspb.DetectorType {
return detectorspb.DetectorType_Dropbox
}
Expand Down
149 changes: 149 additions & 0 deletions pkg/detectors/dropbox/dropbox_integration_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
//go:build detectors
// +build detectors

package dropbox

import (
"fmt"
"testing"
"time"

"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"

"github.com/trufflesecurity/trufflehog/v3/pkg/common"
"github.com/trufflesecurity/trufflehog/v3/pkg/context"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"
)

func TestDropbox_FromChunk(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
testSecrets, err := common.GetSecret(ctx, "trufflehog-testing", "detectors5")
if err != nil {
t.Fatalf("could not get test secrets from GCP: %s", err)
}

secret := testSecrets.MustGetField("DROPBOX")
secretInactive := testSecrets.MustGetField("DROPBOX_INACTIVE")

type args struct {
ctx context.Context
data []byte
verify bool
}
tests := []struct {
name string
s Scanner
args args
want []detectors.Result
wantErr bool
wantVerificationErr bool
}{
{
name: "found, verified",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf("You can find a dropbox secret %s within", secret)),
verify: true,
},
want: []detectors.Result{
{
DetectorType: detectorspb.DetectorType_Dropbox,
Verified: true,
Raw: []byte(secret),
},
},
wantErr: false,
},
{
name: "found, unverified",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf("You can find a dropbox secret %s within", secretInactive)),
verify: true,
},
want: []detectors.Result{
{
DetectorType: detectorspb.DetectorType_Dropbox,
Verified: false,
Raw: []byte(secretInactive),
},
},
wantErr: false,
},
{
name: "not found",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte("You cannot find the secret within"),
verify: true,
},
want: nil,
wantErr: false,
},
{
name: "found, would be verified if not for timeout",
s: Scanner{client: common.SaneHttpClientTimeOut(1 * time.Microsecond)},
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf("You can find a dropbox token %s within", secret)),
verify: true,
},
want: []detectors.Result{
{
DetectorType: detectorspb.DetectorType_Dropbox,
Verified: false,
Raw: []byte(secret),
},
},
wantErr: false,
wantVerificationErr: true,
},
{
name: "found, verified but unexpected api surface",
s: Scanner{client: common.ConstantResponseHttpClient(500, "")},
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf("You can find a dropbox secret %s within", secret)),
verify: true,
},
want: []detectors.Result{
{
DetectorType: detectorspb.DetectorType_Dropbox,
Verified: false,
Raw: []byte(secret),
},
},
wantErr: false,
wantVerificationErr: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := tt.s.FromData(tt.args.ctx, tt.args.verify, tt.args.data)
if (err != nil) != tt.wantErr {
t.Errorf("Dropbox.FromData() error = %v, wantErr %v", err, tt.wantErr)
return
}

for i := range got {
if len(got[i].Raw) == 0 {
t.Fatalf("no raw secret present: \n %+v", got[i])
}
if (got[i].VerificationError() != nil) != tt.wantVerificationErr {
t.Fatalf("wantVerificationError = %v, verification error = %v", tt.wantVerificationErr, got[i].VerificationError())
}
}
ignoreOpts := cmpopts.IgnoreFields(detectors.Result{}, "verificationError", "ExtraData")
if diff := cmp.Diff(got, tt.want, ignoreOpts); diff != "" {
t.Errorf("Box.FromData() %s diff: (-got +want)\n%s", tt.name, diff)
}
})
}
}
Loading
Loading