Skip to content

Commit

Permalink
Merge branch 'main' into tests/pattern-test-cases-c
Browse files Browse the repository at this point in the history
  • Loading branch information
kashifkhan0771 authored Nov 7, 2024
2 parents 91f0666 + d421a94 commit bb9a7d8
Show file tree
Hide file tree
Showing 7 changed files with 570 additions and 364 deletions.
93 changes: 50 additions & 43 deletions pkg/detectors/mongodb/mongodb.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ import (
"strings"
"time"

regexp "github.com/wasilibs/go-re2"
logContext "github.com/trufflesecurity/trufflehog/v3/pkg/context"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"

regexp "github.com/wasilibs/go-re2"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/x/mongo/driver/auth"

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

type Scanner struct {
Expand All @@ -42,39 +42,68 @@ func (s Scanner) Keywords() []string {

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

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

for _, match := range matches {
uniqueMatches := make(map[string]string)
for _, match := range connStrPat.FindAllStringSubmatch(dataStr, -1) {
// Filter out common placeholder passwords.
password := match[3]
if password == "" || placeholderPasswordPat.MatchString(password) {
continue
}

// If the query string contains `&` the options will not be parsed.
resMatch := strings.Replace(strings.TrimSpace(match[1]), "&", "&", -1)
s1 := detectors.Result{
DetectorType: detectorspb.DetectorType_MongoDB,
Raw: []byte(resMatch),
connStr := strings.Replace(strings.TrimSpace(match[1]), "&", "&", -1)
connUrl, err := url.Parse(connStr)
if err != nil {
logger.V(3).Info("Skipping invalid URL", "err", err)
continue
}
s1.ExtraData = map[string]string{
"rotation_guide": "https://howtorotate.com/docs/tutorials/mongo/",

params := connUrl.Query()
for k, v := range connUrl.Query() {
if len(v) > 0 {
switch k {
case "tls":
if v[0] == "false" {
params.Set("tls", "false")
} else {
params.Set("tls", "true")
}
}
}
}

connUrl.RawQuery = params.Encode()
connStr = connUrl.String()

uniqueMatches[connStr] = password
}

for connStr, password := range uniqueMatches {
r := detectors.Result{
DetectorType: detectorspb.DetectorType_MongoDB,
Raw: []byte(connStr),
ExtraData: map[string]string{
"rotation_guide": "https://howtorotate.com/docs/tutorials/mongo/",
},
}

if verify {
timeout := s.timeout
if timeout == 0 {
timeout = defaultTimeout
}
isVerified, verificationErr := verifyUri(ctx, resMatch, timeout)
s1.Verified = isVerified
if !isErrDeterminate(verificationErr) {
s1.SetVerificationError(verificationErr, resMatch)

isVerified, vErr := verifyUri(ctx, connStr, timeout)
r.Verified = isVerified
if isErrDeterminate(vErr) {
continue
}
r.SetVerificationError(vErr, password)
}
results = append(results, s1)
results = append(results, r)
}

return results, nil
Expand All @@ -93,34 +122,12 @@ func isErrDeterminate(err error) bool {
return errors.As(err, &authErr)
}

func verifyUri(ctx context.Context, uri string, timeout time.Duration) (bool, error) {
parsed, err := url.Parse(uri)
if err != nil {
return false, err
}

params := url.Values{}
for k, v := range parsed.Query() {
if len(v) > 0 {
switch k {
case "tls":
if v[0] == "false" {
params.Set("tls", "false")
} else {
params.Set("tls", "true")
}
}
}
}
parsed.RawQuery = params.Encode()
parsed.Path = "/"
uri = parsed.String()

func verifyUri(ctx context.Context, connStr string, timeout time.Duration) (bool, error) {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()

clientOptions := options.Client().SetTimeout(timeout).ApplyURI(uri)
if err = clientOptions.Validate(); err != nil {
clientOptions := options.Client().SetTimeout(timeout).ApplyURI(connStr)
if err := clientOptions.Validate(); err != nil {
return false, err
}

Expand Down
153 changes: 153 additions & 0 deletions pkg/detectors/mongodb/mongodb_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,3 +180,156 @@ func TestIntegrationMongoDB_FromChunk(t *testing.T) {
})
}
}

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

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 mongodb secret %s within", secret)),
verify: true,
},
want: []detectors.Result{
{
DetectorType: detectorspb.DetectorType_MongoDB,
Verified: true,
ExtraData: map[string]string{
"rotation_guide": "https://howtorotate.com/docs/tutorials/mongo/",
},
},
},
wantErr: false,
},
{
name: "found, unverified",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf("You can find a mongodb secret %s within but not valid", inactiveSecret)), // the secret would satisfy the regex but not pass validation
verify: true,
},
want: []detectors.Result{
{
DetectorType: detectorspb.DetectorType_MongoDB,
Verified: false,
ExtraData: map[string]string{
"rotation_guide": "https://howtorotate.com/docs/tutorials/mongo/",
},
},
},
wantErr: false,
},
{
name: "found, would be verified but for connection timeout",
s: Scanner{timeout: 1 * time.Microsecond},
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf("You can find a mongodb secret %s within", secret)),
verify: true,
},
want: []detectors.Result{
{
DetectorType: detectorspb.DetectorType_MongoDB,
Verified: false,
ExtraData: map[string]string{
"rotation_guide": "https://howtorotate.com/docs/tutorials/mongo/",
},
},
},
wantErr: false,
wantVerificationErr: true,
},
{
name: "found, bad host",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf("You can find a mongodb secret %s within", strings.ReplaceAll(secret, ".mongodb.net", ".mongodb.net.bad"))),
verify: true,
},
want: []detectors.Result{
{
DetectorType: detectorspb.DetectorType_MongoDB,
Verified: false,
ExtraData: map[string]string{
"rotation_guide": "https://howtorotate.com/docs/tutorials/mongo/",
},
},
},
wantErr: false,
wantVerificationErr: true,
},
{
name: "not found",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte("You cannot find the secret within"),
verify: true,
},
want: nil,
wantErr: false,
},
}
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("MongoDB.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])
}
got[i].Raw = nil
if (got[i].VerificationError() != nil) != tt.wantVerificationErr {
t.Fatalf("wantVerificationErr = %v, verification error = %v", tt.wantVerificationErr, got[i].VerificationError())
}
}
ignoreOpts := cmpopts.IgnoreFields(detectors.Result{}, "RawV2", "verificationError")
if diff := cmp.Diff(tt.want, got, ignoreOpts); diff != "" {
t.Errorf("MongoDB.FromData() %s diff: (-got +want)\n%s", tt.name, diff)
}
})
}
}

func BenchmarkFromData(benchmark *testing.B) {
ctx := context.Background()
s := Scanner{}
for name, data := range detectors.MustGetBenchmarkData() {
benchmark.Run(name, func(b *testing.B) {
b.ResetTimer()
for n := 0; n < b.N; n++ {
_, err := s.FromData(ctx, false, data)
if err != nil {
b.Fatal(err)
}
}
})
}
}
Loading

0 comments on commit bb9a7d8

Please sign in to comment.