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

proposal: SqlServer connection string detector #867

Merged
merged 5 commits into from
Oct 26, 2022
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
89 changes: 89 additions & 0 deletions pkg/detectors/sqlserver/sqlserver.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package sqlserver

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

"github.com/denisenkom/go-mssqldb/msdsn"
log "github.com/sirupsen/logrus"
"github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb"

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

type Scanner struct{}

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

var (
// SQLServer connection string is a semicolon delimited set of case-insensitive parameters which may go in any order.
pattern = regexp.MustCompile("(?:\n|`|'|\"| )?((?:[A-Za-z0-9_ ]+=[^;$'`\"$]+;?){3,})(?:'|`|\"|\r\n|\n)?")
)

// 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{"sqlserver"}
}

// FromData will find and optionally verify SpotifyKey secrets in a given set of bytes.
func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {
matches := pattern.FindAllStringSubmatch(string(data), -1)
for _, match := range matches {
params, _, err := msdsn.Parse(match[1])
if err != nil {
log.Debugf("sqlserver: unable to parse connection string '%s' because '%s'", match[1], err.Error())
continue
}

if params.Password == "" {
log.Debugf("sqlserver: skip connection string '%s' because it does not contain password", match[1])
continue
}

detected := detectors.Result{
DetectorType: detectorspb.DetectorType_SQLServer,
Raw: []byte(params.Password),
}

if verify {
verified, err := ping(params)
if err != nil {
log.Debugf("sqlserver: unable to verify '%s' because '%s'", params.URL(), err.Error())
} else {
detected.Verified = verified
}
}

results = append(results, detected)
}

return detectors.CleanResults(results), nil
}

var ping = func(config msdsn.Config) (bool, error) {
url := config.URL()
query := url.Query()
query.Set("dial timeout", "3")
query.Set("connection timeout", "3")
url.RawQuery = query.Encode()

conn, err := sql.Open("mssql", url.String())
if err != nil {
return false, err
}

err = conn.Ping()
if err != nil {
return false, err
}

err = conn.Close()
if err != nil {
log.Debugf("sqlserver: unable to close connection '%s' because '%s'", url.String(), err.Error())
}

return true, nil
}
145 changes: 145 additions & 0 deletions pkg/detectors/sqlserver/sqlserver_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
//go:build detectors
// +build detectors

package sqlserver

import (
"context"
"fmt"
"github.com/denisenkom/go-mssqldb/msdsn"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"testing"

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

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

func TestSQLServer_FromChunk(t *testing.T) {
secret := "Server=localhost;Initial Catalog=Demo;User ID=sa;Password=P@ssw0rd!;Persist Security Info=true;MultipleActiveResultSets=true;"
inactiveSecret := "Server=localhost;User ID=sa;Password=123"

type args struct {
ctx context.Context
data []byte
verify bool
}
tests := []struct {
name string
s Scanner
args args
want []detectors.Result
wantErr bool
mockFunc func()
}{
{
name: "found, verified",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf("You can find a sqlserver secret %s within", secret)),
verify: true,
},
want: []detectors.Result{
{
DetectorType: detectorspb.DetectorType_SQLServer,
Verified: true,
},
},
wantErr: false,
mockFunc: func() {
ping = func(config msdsn.Config) (bool, error) {
return true, nil
}
},
},
{
name: "found, unverified",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte(fmt.Sprintf("You can find a sqlserver 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_SQLServer,
Verified: false,
},
},
wantErr: false,
mockFunc: func() {
ping = func(config msdsn.Config) (bool, error) {
return false, nil
}
},
},
{
name: "not found",
s: Scanner{},
args: args{
ctx: context.Background(),
data: []byte("You cannot find the secret within"),
verify: true,
},
want: nil,
wantErr: false,
mockFunc: func() {},
},
}

// preserve the original function
originalPing := ping

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.mockFunc()
s := Scanner{}
got, err := s.FromData(tt.args.ctx, tt.args.verify, tt.args.data)
if (err != nil) != tt.wantErr {
t.Errorf("SQLServer.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
}
ignoreOpts := cmpopts.IgnoreFields(detectors.Result{}, "RawV2")
if diff := cmp.Diff(tt.want, got, ignoreOpts); diff != "" {
t.Errorf("SQLServer.FromData() %s diff: (-got +want)\n%s", tt.name, diff)
}
})
}

ping = originalPing
}

func TestSQLServer_pattern(t *testing.T) {
if !pattern.Match([]byte(`builder.Services.AddDbContext<Database>(optionsBuilder => optionsBuilder.UseSqlServer("Server=localhost;Initial Catalog=master;User ID=sa;Password=P@ssw0rd!;Persist Security Info=true;MultipleActiveResultSets=true;"));`)) {
t.Errorf("SQLServer.pattern: did not catched connection string from Program.cs")
}
if !pattern.Match([]byte(`{"ConnectionStrings": {"Demo": "Server=localhost;Initial Catalog=master;User ID=sa;Password=P@ssw0rd!;Persist Security Info=true;MultipleActiveResultSets=true;"}}`)) {
t.Errorf("SQLServer.pattern: did not catched connection string from appsettings.json")
}
if !pattern.Match([]byte(`CONNECTION_STRING: Server=localhost;Initial Catalog=master;User ID=sa;Password=P@ssw0rd!;Persist Security Info=true;MultipleActiveResultSets=true`)) {
t.Errorf("SQLServer.pattern: did not catched connection string from .env")
}
}

func BenchmarkFromData(benchmark *testing.B) {
ctx := context.Background()
s := Scanner{}
for name, data := range detectors.MustGetBenchmarkData() {
benchmark.Run(name, func(b *testing.B) {
for n := 0; n < b.N; n++ {
_, err := s.FromData(ctx, false, data)
if err != nil {
b.Fatal(err)
}
}
})
}
}
6 changes: 4 additions & 2 deletions pkg/engine/defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -426,8 +426,8 @@ import (
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/noticeable"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/notion"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/nozbeteams"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/npmtoken"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/npmtokenv2"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/npmtoken"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/npmtokenv2"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/numverify"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/nutritionix"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/nylas"
Expand Down Expand Up @@ -593,6 +593,7 @@ import (
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/spoonacular"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/sportradar"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/sportsmonk"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/sqlserver"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/square"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/squareapp"
"github.com/trufflesecurity/trufflehog/v3/pkg/detectors/squarespace"
Expand Down Expand Up @@ -1482,5 +1483,6 @@ func DefaultDetectors() []detectors.Detector {
digitaloceanv2.Scanner{},
npmtoken.Scanner{},
npmtokenv2.Scanner{},
sqlserver.Scanner{},
}
}
8 changes: 6 additions & 2 deletions pkg/pb/detectorspb/detectors.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions proto/detectors.proto
Original file line number Diff line number Diff line change
Expand Up @@ -905,6 +905,7 @@ enum DetectorType {
MongoDB = 895;
NGC = 896;
DigitalOceanV2 = 897;
SQLServer = 898;
}

message Result {
Expand Down