-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathjdbc.go
More file actions
284 lines (251 loc) · 7.63 KB
/
jdbc.go
File metadata and controls
284 lines (251 loc) · 7.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package jdbc
import (
"context"
"database/sql"
"errors"
"fmt"
"regexp"
"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"
)
type Scanner struct {
detectors.DefaultMultiPartCredentialProvider
ignorePatterns []regexp.Regexp
}
func New(opts ...func(*Scanner)) *Scanner {
scanner := &Scanner{
ignorePatterns: []regexp.Regexp{},
}
for _, opt := range opts {
opt(scanner)
}
return scanner
}
func WithIgnorePattern(ignoreStrings []string) func(*Scanner) {
return func(s *Scanner) {
var ignorePatterns []regexp.Regexp
for _, ignoreString := range ignoreStrings {
ignorePattern, err := regexp.Compile(ignoreString)
if err != nil {
panic(fmt.Sprintf("%s is not a valid regex, error received: %v", ignoreString, err))
}
ignorePatterns = append(ignorePatterns, *ignorePattern)
}
s.ignorePatterns = ignorePatterns
}
}
// Ensure the Scanner satisfies the interface at compile time.
var _ detectors.Detector = (*Scanner)(nil)
var _ detectors.CustomFalsePositiveChecker = (*Scanner)(nil)
var (
// Matches typical JDBC connection strings.
// The terminal character class additionally excludes () and & to avoid
// capturing surrounding delimiters (e.g. "(jdbc:…)" or "…&user=x&").
keyPat = regexp.MustCompile(`(?i)jdbc:[\w]{3,10}:[^\s"'<>,{}[\]]{10,511}[^\s"'<>,{}[\]()&]`)
)
// 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{"jdbc"}
}
// 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)
matchLoop:
for _, match := range matches {
if len(s.ignorePatterns) != 0 {
for _, ignore := range s.ignorePatterns {
if ignore.MatchString(match[0]) {
continue matchLoop
}
}
}
jdbcConn := match[0]
result := detectors.Result{
DetectorType: detectorspb.DetectorType_JDBC,
Raw: []byte(jdbcConn),
Redacted: tryRedactAnonymousJDBC(jdbcConn),
}
// Try to parse connection info for ExtraData regardless of verification.
if j, parseErr := NewJDBC(logCtx, jdbcConn); parseErr == nil {
if info := j.GetConnectionInfo(); info != nil {
extraData := make(map[string]string)
if info.Host != "" {
extraData["host"] = info.Host
}
if info.User != "" {
extraData["username"] = info.User
}
if info.Database != "" {
extraData["database"] = info.Database
}
if len(extraData) > 0 {
result.ExtraData = extraData
}
}
if verify {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
pingRes := j.ping(ctx)
result.Verified = pingRes.err == nil
// If there's a ping error that is marked as "determinate" we throw it away. We do this because this was the
// behavior before tri-state verification was introduced and preserving it allows us to gradually migrate
// detectors to use tri-state verification.
if pingRes.err != nil && !pingRes.determinate {
result.SetVerificationError(pingRes.err, jdbcConn)
}
result.AnalysisInfo = map[string]string{
"connection_string": jdbcConn,
}
// TODO: specialized redaction
}
} else if verify {
continue
}
results = append(results, result)
}
return
}
func (s Scanner) IsFalsePositive(_ detectors.Result) (bool, string) {
return false, ""
}
func tryRedactAnonymousJDBC(conn string) string {
if s, ok := tryRedactURLParams(conn); ok {
return s
}
if s, ok := tryRedactODBC(conn); ok {
return s
}
if s, ok := tryRedactBasicAuth(conn); ok {
return s
}
if s, ok := tryRedactRegex(conn); ok {
return s
}
return conn
}
// Basic authentication "username:password@host" style
func tryRedactBasicAuth(conn string) (string, bool) {
userPass, postfix, found := strings.Cut(conn, "@")
if !found {
return "", false
}
index := strings.LastIndex(userPass, ":")
if index == -1 {
return "", false
}
prefix, pass := userPass[:index], userPass[index+1:]
return prefix + ":" + strings.Repeat("*", len(pass)) + "@" + postfix, true
}
// URL param "?password=password" style
func tryRedactURLParams(conn string) (string, bool) {
prefix, paramString, found := strings.Cut(conn, "?")
if !found {
return "", false
}
var newParams []string
found = false
for _, param := range strings.Split(paramString, "&") {
key, val, _ := strings.Cut(param, "=")
if strings.Contains(strings.ToLower(key), "pass") {
newParams = append(newParams, key+"="+strings.Repeat("*", len(val)))
found = true
continue
}
newParams = append(newParams, param)
}
if !found {
return "", false
}
return prefix + "?" + strings.Join(newParams, "&"), true
}
// ODBC params ";password=password" style
func tryRedactODBC(conn string) (string, bool) {
var found bool
var newParams []string
for _, param := range strings.Split(conn, ";") {
key, val, isKvp := strings.Cut(param, "=")
if isKvp && strings.Contains(strings.ToLower(key), "pass") {
newParams = append(newParams, key+"="+strings.Repeat("*", len(val)))
found = true
continue
}
newParams = append(newParams, param)
}
if !found {
return "", false
}
return strings.Join(newParams, ";"), true
}
// Naively search the string for "pass="
func tryRedactRegex(conn string) (string, bool) {
pattern := regexp.MustCompile(`(?i)pass.*?=(.+?)\b`)
var found bool
newConn := pattern.ReplaceAllStringFunc(conn, func(s string) string {
index := strings.Index(s, "=")
if index == -1 {
// unreachable due to regex containing '='
return s
}
found = true
return s[:index+1] + strings.Repeat("*", len(s[index+1:]))
})
if !found {
return "", false
}
return newConn, true
}
var supportedSubprotocols = map[string]func(logContext.Context, string) (JDBC, error){
"mysql": parseMySQL,
"postgresql": parsePostgres,
"sqlserver": parseSqlServer,
}
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")
}
parser, ok := supportedSubprotocols[strings.ToLower(subprotocol)]
if !ok {
return nil, fmt.Errorf("unsupported subprotocol: %s", subprotocol)
}
return parser(ctx, subname)
}
func ping(ctx context.Context, driverName string, isDeterminate func(error) bool, candidateConns ...string) pingResult {
var indeterminateErrors []error
for _, c := range candidateConns {
err := pingErr(ctx, driverName, c)
if err == nil || isDeterminate(err) {
return pingResult{err, true}
}
indeterminateErrors = append(indeterminateErrors, err)
}
return pingResult{errors.Join(indeterminateErrors...), false}
}
func pingErr(ctx context.Context, driverName, conn string) error {
db, err := sql.Open(driverName, conn)
if err != nil {
return err
}
defer db.Close()
if err := db.PingContext(ctx); err != nil {
return err
}
return nil
}
func (s Scanner) Type() detectorspb.DetectorType {
return detectorspb.DetectorType_JDBC
}
func (s Scanner) Description() string {
return "JDBC (Java Database Connectivity) is an API for connecting and executing queries with databases. JDBC connection strings can be used to access and manipulate databases."
}