Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
fix(jdbc): ignore invalid sqlserver URLs (#3429)
Richard Gomez3063f6353657
diff --git a/pkg/detectors/jdbc/jdbc.go b/pkg/detectors/jdbc/jdbc.goindex 5048cbbe9..8edb48a33 100644--- a/pkg/detectors/jdbc/jdbc.go+++ b/pkg/detectors/jdbc/jdbc.go@@ -9,6 +9,7 @@ import ("strings""time"+ logContext "github.com/trufflesecurity/trufflehog/v3/pkg/context""github.com/trufflesecurity/trufflehog/v3/pkg/detectors""github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb")@@ -60,6 +61,7 @@ func (s Scanner) Keywords() []string {// FromData will find and optionally verify Jdbc secrets in a given set of bytes.func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (results []detectors.Result, err error) {+ logCtx := logContext.AddLogger(ctx)dataStr := string(data)matches := keyPat.FindAllStringSubmatch(dataStr, -1)@@ -81,11 +83,11 @@ matchLoop:}if verify {- result.Verified = false- j, err := newJDBC(jdbcConn)+ j, err := newJDBC(logCtx, jdbcConn)if err != nil {continue}+ctx, cancel := context.WithTimeout(ctx, 5*time.Second)defer cancel()pingRes := j.ping(ctx)@@ -204,7 +206,7 @@ func tryRedactRegex(conn string) (string, bool) {return newConn, true}-var supportedSubprotocols = map[string]func(string) (jdbc, error){+var supportedSubprotocols = map[string]func(logContext.Context, string) (jdbc, error){"mysql": parseMySQL,"postgresql": parsePostgres,"sqlserver": parseSqlServer,@@ -219,22 +221,24 @@ type jdbc interface {ping(context.Context) pingResult}-func newJDBC(conn string) (jdbc, error) {+func newJDBC(ctx logContext.Context, conn string) (jdbc, error) {// expected format: "jdbc:{subprotocol}:{subname}"if !strings.HasPrefix(strings.ToLower(conn), "jdbc:") {return nil, errors.New("expected jdbc prefix")}conn = conn[len("jdbc:"):]+subprotocol, subname, found := strings.Cut(conn, ":")if !found {return nil, errors.New("expected a colon separated subprotocol and subname")}+// get the subprotocol parserparser, ok := supportedSubprotocols[strings.ToLower(subprotocol)]if !ok {return nil, errors.New("unsupported subprotocol")}- return parser(subname)+ return parser(ctx, subname)}func ping(ctx context.Context, driverName string, isDeterminate func(error) bool, candidateConns ...string) pingResult {diff --git a/pkg/detectors/jdbc/mysql.go b/pkg/detectors/jdbc/mysql.goindex 291bc375e..605720160 100644--- a/pkg/detectors/jdbc/mysql.go+++ b/pkg/detectors/jdbc/mysql.go@@ -7,6 +7,8 @@ import ("net/url""strings"+ logContext "github.com/trufflesecurity/trufflehog/v3/pkg/context"+"github.com/go-sql-driver/mysql")@@ -49,7 +51,7 @@ func isMySQLErrorDeterminate(err error) bool {return false}-func parseMySQL(subname string) (jdbc, error) {+func parseMySQL(_ logContext.Context, subname string) (jdbc, error) {// expected form: [subprotocol:]//[user:password@]HOST[/DB][?key=val[&key=val]]if !strings.HasPrefix(subname, "//") {return nil, errors.New("expected host to start with //")diff --git a/pkg/detectors/jdbc/postgres.go b/pkg/detectors/jdbc/postgres.goindex c9b678bd7..9e262e85e 100644--- a/pkg/detectors/jdbc/postgres.go+++ b/pkg/detectors/jdbc/postgres.go@@ -7,6 +7,8 @@ import ("net/url""strings"+ logContext "github.com/trufflesecurity/trufflehog/v3/pkg/context"+"github.com/lib/pq")@@ -57,7 +59,7 @@ func joinKeyValues(m map[string]string, sep string) string {return strings.Join(data, sep)}-func parsePostgres(subname string) (jdbc, error) {+func parsePostgres(_ logContext.Context, subname string) (jdbc, error) {// expected form: [subprotocol:]//[user:password@]HOST[/DB][?key=val[&key=val]]if !strings.HasPrefix(subname, "//") {diff --git a/pkg/detectors/jdbc/sqlserver.go b/pkg/detectors/jdbc/sqlserver.goindex 23629c128..4178b99f1 100644--- a/pkg/detectors/jdbc/sqlserver.go+++ b/pkg/detectors/jdbc/sqlserver.go@@ -4,8 +4,11 @@ import ("context""errors""fmt"+ "net/url""strings"+ logContext "github.com/trufflesecurity/trufflehog/v3/pkg/context"+mssql "github.com/microsoft/go-mssqldb")@@ -20,19 +23,19 @@ func (s *sqlServerJDBC) ping(ctx context.Context) pingResult {func isSqlServerErrorDeterminate(err error) bool {// Error numbers from https://learn.microsoft.com/en-us/sql/relational-databases/errors-events/database-engine-events-and-errors?view=sql-server-ver16- if mssqlError, isMssqlError := err.(mssql.Error); isMssqlError {- switch mssqlError.Number {+ var sqlErr mssql.Error+ if errors.As(err, &sqlErr) {+ switch sqlErr.Number {case 18456:// Login failed// This is a determinate failure iff we tried to use a real user- return mssqlError.Message != "login error: Login failed for user ''."+ return sqlErr.Message != "login error: Login failed for user ''."}}-return false}-func parseSqlServer(subname string) (jdbc, error) {+func parseSqlServer(ctx logContext.Context, subname string) (jdbc, error) {if !strings.HasPrefix(subname, "//") {return nil, errors.New("expected connection to start with //")}@@ -65,7 +68,15 @@ func parseSqlServer(subname string) (jdbc, error) {port = value}}- return &sqlServerJDBC{- connStr: fmt.Sprintf("sqlserver://sa:%s@%s:%s?database=master&connection+timeout=5", password, host, port),- }, nil++ urlStr := fmt.Sprintf("sqlserver://sa:%s@%s:%s?database=master&connection+timeout=5", password, host, port)+ jdbcUrl, err := url.Parse(urlStr)+ if err != nil {+ ctx.Logger().WithName("jdbc").+ V(3).+ Info("Skipping invalid SQL Server URL", "url", urlStr, "err", err)+ return nil, err+ }++ return &sqlServerJDBC{connStr: jdbcUrl.String()}, nil}diff --git a/pkg/detectors/sqlserver/sqlserver_integration_test.go b/pkg/detectors/sqlserver/sqlserver_integration_test.goindex 43ebc952d..1c75f155e 100644--- a/pkg/detectors/sqlserver/sqlserver_integration_test.go+++ b/pkg/detectors/sqlserver/sqlserver_integration_test.go@@ -190,7 +190,186 @@ func TestSQLServerIntegration_FromChunk(t *testing.T) {}}+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,+ Redacted: "sqlserver://sa:********@localhost?database=Demo&dial+timeout=15&disableretry=false",+ 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,+ Redacted: "sqlserver://sa:********@localhost?dial+timeout=15&disableretry=false",+ Verified: false,+ },+ },+ wantErr: false,+ mockFunc: func() {+ ping = func(config msdsn.Config) (bool, error) {+ return false, nil+ }+ },+ },+ {+ name: "not found, in XML, missing password param (pwd is not valid)",+ s: Scanner{},+ args: args{+ ctx: context.Background(),+ data: []byte(`<add name="Sample2" value="SERVER=server_name;DATABASE=database_name;user=user_name;pwd=plaintextpassword;encrypt=true;Timeout=120;MultipleActiveResultSets=True;" />`),+ verify: true,+ },+ want: nil,+ wantErr: false,+ mockFunc: func() {+ ping = func(config msdsn.Config) (bool, error) {+ return true, nil+ }+ },+ },+ {+ name: "found, verified, in XML",+ s: Scanner{},+ args: args{+ ctx: context.Background(),+ data: []byte(`<add name="test db" value="SERVER=server_name;DATABASE=testdb;user=username;password=badpassword;encrypt=true;Timeout=120;MultipleActiveResultSets=True;" />`),+ verify: true,+ },+ want: []detectors.Result{+ {+ DetectorType: detectorspb.DetectorType_SQLServer,+ Redacted: "sqlserver://username:********@server_name?database=testdb&dial+timeout=15&disableretry=false&encrypt=true",+ Verified: true,+ },+ },+ wantErr: false,+ mockFunc: func() {+ ping = func(config msdsn.Config) (bool, error) {+ if config.Host != "server_name" {+ return false, errors.New("invalid host")+ }++ if config.User != "username" {+ return false, errors.New("invalid database")+ }++ if config.Password != "badpassword" {+ return false, errors.New("invalid password")+ }++ if config.Database != "testdb" {+ return false, errors.New("invalid database")+ }++ return true, 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 := []cmp.Option{+ cmpopts.IgnoreFields(detectors.Result{}, "RawV2"),+ cmpopts.IgnoreUnexported(detectors.Result{}),+ }+ if diff := cmp.Diff(tt.want, got, ignoreOpts...); diff != "" {+ t.Errorf("SQLServer.FromData() %s diff: (-got +want)\n%s", tt.name, diff)+ for _, g := range got {+ t.Error(g.Redacted)+ }+ }+ })+ }++ ping = originalPing+}+func urlEncode(s string) string {parsed, _ := url.Parse(s)return parsed.String()}++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)+ }+ }+ })+ }+}diff --git a/pkg/detectors/sqlserver/sqlserver_test.go b/pkg/detectors/sqlserver/sqlserver_test.goindex 7ecfbd3b9..33b5fffe2 100644--- a/pkg/detectors/sqlserver/sqlserver_test.go+++ b/pkg/detectors/sqlserver/sqlserver_test.go@@ -1,185 +1,9 @@-//go:build detectors-// +build detectors-package sqlserverimport (- "context"- "errors"- "fmt""testing"-- "github.com/google/go-cmp/cmp"- "github.com/google/go-cmp/cmp/cmpopts"- "github.com/microsoft/go-mssqldb/msdsn"-- "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,- Redacted: "sqlserver://sa:********@localhost?database=Demo&dial+timeout=15&disableretry=false",- 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,- Redacted: "sqlserver://sa:********@localhost?dial+timeout=15&disableretry=false",- Verified: false,- },- },- wantErr: false,- mockFunc: func() {- ping = func(config msdsn.Config) (bool, error) {- return false, nil- }- },- },- {- name: "not found, in XML, missing password param (pwd is not valid)",- s: Scanner{},- args: args{- ctx: context.Background(),- data: []byte(`<add name="Sample2" value="SERVER=server_name;DATABASE=database_name;user=user_name;pwd=plaintextpassword;encrypt=true;Timeout=120;MultipleActiveResultSets=True;" />`),- verify: true,- },- want: nil,- wantErr: false,- mockFunc: func() {- ping = func(config msdsn.Config) (bool, error) {- return true, nil- }- },- },- {- name: "found, verified, in XML",- s: Scanner{},- args: args{- ctx: context.Background(),- data: []byte(`<add name="test db" value="SERVER=server_name;DATABASE=testdb;user=username;password=badpassword;encrypt=true;Timeout=120;MultipleActiveResultSets=True;" />`),- verify: true,- },- want: []detectors.Result{- {- DetectorType: detectorspb.DetectorType_SQLServer,- Redacted: "sqlserver://username:********@server_name?database=testdb&dial+timeout=15&disableretry=false&encrypt=true",- Verified: true,- },- },- wantErr: false,- mockFunc: func() {- ping = func(config msdsn.Config) (bool, error) {- if config.Host != "server_name" {- return false, errors.New("invalid host")- }-- if config.User != "username" {- return false, errors.New("invalid database")- }-- if config.Password != "badpassword" {- return false, errors.New("invalid password")- }-- if config.Database != "testdb" {- return false, errors.New("invalid database")- }-- return true, 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 := []cmp.Option{- cmpopts.IgnoreFields(detectors.Result{}, "RawV2"),- cmpopts.IgnoreUnexported(detectors.Result{}),- }- if diff := cmp.Diff(tt.want, got, ignoreOpts...); diff != "" {- t.Errorf("SQLServer.FromData() %s diff: (-got +want)\n%s", tt.name, diff)- for _, g := range got {- t.Error(g.Redacted)- }- }- })- }-- 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 find connection string from Program.cs")@@ -194,19 +18,3 @@ func TestSQLServer_pattern(t *testing.T) {t.Errorf("SQLServer.pattern: did not find connection string in xml format")}}--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)- }- }- })- }-}