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

implemented planet scale creds (passwords and API keys) #1841

Merged
merged 3 commits into from
Oct 2, 2023
Merged
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
87 changes: 87 additions & 0 deletions pkg/detectors/planetscale/planetscale.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package planetscale

import (
"context"
"fmt"
"net/http"
"regexp"

"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 {
client *http.Client
}

var (
defaultClient = common.SaneHttpClient()
usernamePat = regexp.MustCompile(`\b[a-z0-9]{12}\b`)
dustin-decker marked this conversation as resolved.
Show resolved Hide resolved
passwordPat = regexp.MustCompile(`\bpscale_tkn_[A-Za-z0-9_]{43}\b`)
)

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

// Keywords are used for efficiently pre-filtering chunks.
func (s Scanner) Keywords() []string {
return []string{"pscale_tkn_"}
}

func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {
dataStr := string(data)

usernameMatches := usernamePat.FindAllString(dataStr, -1)
passwordMatches := passwordPat.FindAllString(dataStr, -1)

for _, username := range usernameMatches {

for _, password := range passwordMatches {
credentials := fmt.Sprintf("%s:%s", username, password)

s1 := detectors.Result{
DetectorType: detectorspb.DetectorType_PlanetScale,
Raw: []byte(credentials),
}

if verify {
client := s.client
if client == nil {
client = defaultClient
}

// Construct HTTP request
req, err := http.NewRequestWithContext(ctx, "GET", "https://api.planetscale.com/v1/organizations", nil)
if err != nil {
continue
}
req.Header.Set("Authorization", credentials)
req.Header.Set("accept", "application/json")

// Send HTTP request
res, err := client.Do(req)
if err == nil {
defer res.Body.Close()
if res.StatusCode >= 200 && res.StatusCode < 300 {
s1.Verified = true
} else {
// The secret is determinately not verified
s1.Verified = false
}
} else {
s1.VerificationError = err
}
}

results = append(results, s1)
}
}

return results, nil
}

func (s Scanner) Type() detectorspb.DetectorType {
return detectorspb.DetectorType_PlanetScale
}

161 changes: 161 additions & 0 deletions pkg/detectors/planetscale/planetscale_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
//go:build detectors
// +build detectors

package planetscale

import (
"context"
"fmt"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"testing"
"time"

"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"

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

func TestPlanetscale_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("PLANETSCALE")
inactiveSecret := testSecrets.MustGetField("PLANETSCALE_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 planetscale secret %s within", secret)),
verify: true,
},
want: []detectors.Result{
{
DetectorType: detectorspb.DetectorType_Planetscale,
Verified: true,
},
},
wantErr: false,
wantVerificationErr: false,
},
{
name: "found, unverified",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf("You can find a planetscale 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_Planetscale,
Verified: false,
},
},
wantErr: false,
wantVerificationErr: 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,
wantVerificationErr: 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 planetscale secret %s within", secret)),
verify: true,
},
want: []detectors.Result{
{
DetectorType: detectorspb.DetectorType_Planetscale,
Verified: false,
},
},
wantErr: false,
wantVerificationErr: true,
},
{
name: "found, verified but unexpected api surface",
s: Scanner{client: common.ConstantResponseHttpClient(404, "")},
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf("You can find a planetscale secret %s within", secret)),
verify: true,
},
want: []detectors.Result{
{
DetectorType: detectorspb.DetectorType_Planetscale,
Verified: false,
},
},
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("Planetscale.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{}, "Raw", "VerificationError")
if diff := cmp.Diff(got, tt.want, ignoreOpts); diff != "" {
t.Errorf("Planetscale.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)
}
}
})
}
}
82 changes: 82 additions & 0 deletions pkg/detectors/planetscaledb/planetscaledb.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package planetscaledb

import (
"context"
"database/sql"
"regexp"
"strings"

"github.com/go-sql-driver/mysql"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"
)

type Scanner struct {
db *sql.DB

Check failure on line 15 in pkg/detectors/planetscaledb/planetscaledb.go

View workflow job for this annotation

GitHub Actions / lint

field `db` is unused (unused)
}

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

var (
usernamePat = regexp.MustCompile(`\b[a-z0-9]{20}\b`)
passwordPat = regexp.MustCompile(`\bpscale_pw_[A-Za-z0-9_]{43}\b`)
hostPat = regexp.MustCompile(`\b(aws|gcp)\.connect\.psdb\.cloud\b`)
)

// Keywords are used for efficiently pre-filtering chunks.
func (s Scanner) Keywords() []string {
return []string{"pscale_pw_"}
}

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

usernameMatches := usernamePat.FindAllStringSubmatch(dataStr, -1)
passwordMatches := passwordPat.FindAllStringSubmatch(dataStr, -1)
hostMatches := hostPat.FindAllString(dataStr, -1)

for _, username := range usernameMatches {
for _, password := range passwordMatches {
for _, host := range hostMatches {
s1 := detectors.Result{
DetectorType: detectorspb.DetectorType_PlanetScaleDb,
Raw: []byte(strings.Join([]string{host, username[0], password[0]}, "\t")),
}

if verify {
cfg := mysql.Config{
User: username[0],
Passwd: password[0],
Net: "tcp",
Addr: host,
TLSConfig: "true", // assuming SSL is required
AllowNativePasswords: true,
}
db, err := sql.Open("mysql", cfg.FormatDSN())
if err != nil {
s1.VerificationError = err
} else {
err = db.Ping()
if err == nil {
s1.Verified = true
} else {
s1.VerificationError = err
}
db.Close()
}
}

results = append(results, s1)
}
}
}

return results, nil
}

func (s Scanner) Type() detectorspb.DetectorType {
return detectorspb.DetectorType_PlanetScaleDb
}

Loading
Loading