-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
auth_methods.go
895 lines (829 loc) · 32.1 KB
/
auth_methods.go
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
// Copyright 2019 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package pgwire
import (
"bytes"
"context"
"crypto/tls"
"fmt"
"math"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/security/password"
"github.com/cockroachdb/cockroach/pkg/security/sessionrevival"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/hba"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/identmap"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgwirebase"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sqltelemetry"
"github.com/cockroachdb/cockroach/pkg/util/errorutil/unimplemented"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/log/eventpb"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/redact"
"github.com/go-ldap/ldap/v3"
"github.com/xdg-go/scram"
)
// This file contains the methods that are accepted to perform
// authentication of users during the pgwire connection handshake.
//
// Which method are accepted for which user is selected using
// the HBA config loaded into the cluster setting
// server.host_based_authentication.configuration.
//
// Other methods can be added using RegisterAuthMethod(). This is done
// e.g. in the CCL modules to add support for GSS authentication using
// Kerberos.
func loadDefaultMethods() {
// The "password" method requires a clear text password.
//
// Care should be taken by administrators to only accept this auth
// method over secure connections, e.g. those encrypted using SSL.
RegisterAuthMethod("password", authPassword, hba.ConnAny, NoOptionsAllowed)
// The "cert" method requires a valid client certificate for the
// user attempting to connect.
//
// This method is only usable over SSL connections.
RegisterAuthMethod("cert", authCert, hba.ConnHostSSL, nil)
// The "cert-password" method requires either a valid client
// certificate for the connecting user, or, if no cert is provided,
// a cleartext password.
RegisterAuthMethod("cert-password", authCertPassword, hba.ConnAny, nil)
// The "scram-sha-256" authentication method uses the 5-way SCRAM
// handshake to negotiate password authn with the client. It hides
// the password from the network connection and is non-replayable.
RegisterAuthMethod("scram-sha-256", authScram, hba.ConnAny, NoOptionsAllowed)
// The "cert-scram-sha-256" method is alike to "cert-password":
// it allows either a client certificate, or a valid 5-way SCRAM handshake.
RegisterAuthMethod("cert-scram-sha-256", authCertScram, hba.ConnAny, NoOptionsAllowed)
// The "reject" method rejects any connection attempt that matches
// the current rule.
RegisterAuthMethod("reject", authReject, hba.ConnAny, NoOptionsAllowed)
// The "trust" method accepts any connection attempt that matches
// the current rule.
RegisterAuthMethod("trust", authTrust, hba.ConnAny, NoOptionsAllowed)
// The "ldap" method requires a clear text password which will be used to bind
// with a LDAP server. The remaining connection parameters are provided in hba
// conf options
//
// Care should be taken by administrators to only accept this auth
// method over secure connections, e.g. those encrypted using SSL.
RegisterAuthMethod("ldap", authLDAP, hba.ConnAny, nil)
}
// AuthMethod is a top-level factory for composing the various
// functionality needed to authenticate an incoming connection.
type AuthMethod = func(
ctx context.Context,
c AuthConn,
tlsState tls.ConnectionState,
execCfg *sql.ExecutorConfig,
entry *hba.Entry,
identMap *identmap.Conf,
) (*AuthBehaviors, error)
var _ AuthMethod = authPassword
var _ AuthMethod = authScram
var _ AuthMethod = authCert
var _ AuthMethod = authCertPassword
var _ AuthMethod = authCertScram
var _ AuthMethod = authTrust
var _ AuthMethod = authReject
var _ AuthMethod = authSessionRevivalToken([]byte{})
var _ AuthMethod = authJwtToken
var _ AuthMethod = authLDAP
// authPassword is the AuthMethod constructor for HBA method
// "password": authenticate using a cleartext password received from
// the client.
func authPassword(
_ context.Context,
c AuthConn,
_ tls.ConnectionState,
execCfg *sql.ExecutorConfig,
_ *hba.Entry,
_ *identmap.Conf,
) (*AuthBehaviors, error) {
b := &AuthBehaviors{}
b.SetRoleMapper(UseProvidedIdentity)
b.SetAuthenticator(func(
ctx context.Context,
systemIdentity username.SQLUsername,
clientConnection bool,
pwRetrieveFn PasswordRetrievalFn,
_ *ldap.DN,
) error {
return passwordAuthenticator(ctx, systemIdentity, clientConnection, pwRetrieveFn, c, execCfg)
})
return b, nil
}
var errExpiredPassword = errors.New("password is expired")
// passwordAuthenticator is the authenticator function for the
// behavior constructed by authPassword().
func passwordAuthenticator(
ctx context.Context,
systemIdentity username.SQLUsername,
clientConnection bool,
pwRetrieveFn PasswordRetrievalFn,
c AuthConn,
execCfg *sql.ExecutorConfig,
) error {
// First step: send a cleartext authentication request to the client.
if err := c.SendAuthRequest(authCleartextPassword, nil /* data */); err != nil {
return err
}
// While waiting for the client response, concurrently
// load the credentials from storage (or cache).
// Note: if this fails, we can't return the error right away,
// because we need to consume the client response first. This
// will be handled below.
expired, hashedPassword, pwRetrievalErr := pwRetrieveFn(ctx)
// Wait for the password response from the client.
pwdData, err := c.GetPwdData()
if err != nil {
c.LogAuthFailed(ctx, eventpb.AuthFailReason_PRE_HOOK_ERROR, err)
if pwRetrievalErr != nil {
return errors.CombineErrors(err, pwRetrievalErr)
}
return err
}
// Now process the password retrieval error, if any.
if pwRetrievalErr != nil {
c.LogAuthFailed(ctx, eventpb.AuthFailReason_USER_RETRIEVAL_ERROR, pwRetrievalErr)
return pwRetrievalErr
}
// Extract the password response from the client.
passwordStr, err := passwordString(pwdData)
if err != nil {
c.LogAuthFailed(ctx, eventpb.AuthFailReason_PRE_HOOK_ERROR, err)
return err
}
// Expiration check.
//
// NB: This check is advisory and could be omitted; the retrieval
// function ensures that the returned hashedPassword is
// security.MissingPasswordHash when the credentials have expired,
// so the credential check below would fail anyway.
if expired {
c.LogAuthFailed(ctx, eventpb.AuthFailReason_CREDENTIALS_EXPIRED, nil)
return errExpiredPassword
} else if hashedPassword.Method() == password.HashMissingPassword {
c.LogAuthInfof(ctx, "user has no password defined")
// NB: the failure reason will be automatically handled by the fallback
// in auth.go (and report CREDENTIALS_INVALID).
}
metrics := c.GetTenantSpecificMetrics()
// Now check the cleartext password against the retrieved credentials.
if err := security.UserAuthPasswordHook(
false, passwordStr, hashedPassword, metrics.ConnsWaitingToHash,
)(ctx, systemIdentity, clientConnection); err != nil {
if errors.HasType(err, &security.PasswordUserAuthError{}) {
c.LogAuthFailed(ctx, eventpb.AuthFailReason_CREDENTIALS_INVALID, err)
}
return err
}
// Password authentication succeeded using cleartext. If the stored hash
// was encoded using crdb-bcrypt, we might want to upgrade it to SCRAM
// instead. Conversely, if the stored hash was encoded using SCRAM, we might
// want to downgrade it to crdb-bcrypt.
//
// This auto-conversion is a CockroachDB-specific feature, which pushes
// clusters upgraded from a previous version into using SCRAM-SHA-256, and
// makes it easy to rollback from SCRAM-SHA-256 if there are issues.
sql.MaybeConvertStoredPasswordHash(ctx,
execCfg,
systemIdentity,
passwordStr, hashedPassword)
return nil
}
func passwordString(pwdData []byte) (string, error) {
// Make a string out of the byte array.
if bytes.IndexByte(pwdData, 0) != len(pwdData)-1 {
return "", fmt.Errorf("expected 0-terminated byte array")
}
return string(pwdData[:len(pwdData)-1]), nil
}
// authScram is the AuthMethod constructor for HBA method
// "scram-sha-256": authenticate using a 5-way SCRAM handshake with
// the client.
// It is also the fallback constructor for HBA method
// "cert-scram-sha-256", when the SQL client does not provide a TLS
// client certificate.
func authScram(
ctx context.Context,
c AuthConn,
_ tls.ConnectionState,
execCfg *sql.ExecutorConfig,
_ *hba.Entry,
_ *identmap.Conf,
) (*AuthBehaviors, error) {
b := &AuthBehaviors{}
b.SetRoleMapper(UseProvidedIdentity)
b.SetAuthenticator(func(
ctx context.Context,
systemIdentity username.SQLUsername,
clientConnection bool,
pwRetrieveFn PasswordRetrievalFn,
_ *ldap.DN,
) error {
return scramAuthenticator(ctx, systemIdentity, clientConnection, pwRetrieveFn, c, execCfg)
})
return b, nil
}
// scramAuthenticator is the authenticator function for the
// behavior constructed by authScram().
func scramAuthenticator(
ctx context.Context,
systemIdentity username.SQLUsername,
clientConnection bool,
pwRetrieveFn PasswordRetrievalFn,
c AuthConn,
execCfg *sql.ExecutorConfig,
) error {
// First step: send a SCRAM authentication request to the client.
// We do this with an auth request with the request type SASL,
// and a payload containing the list of supported SCRAM methods.
//
// NB: SCRAM-SHA-256-PLUS is not supported, see
// https://github.com/cockroachdb/cockroach/issues/74300
// There is one nul byte to terminate the first string,
// then another nul byte to terminate the list.
const supportedMethods = "SCRAM-SHA-256\x00\x00"
if err := c.SendAuthRequest(authReqSASL, []byte(supportedMethods)); err != nil {
return err
}
// While waiting for the client response, concurrently
// load the credentials from storage (or cache).
// Note: if this fails, we can't return the error right away,
// because we need to consume the client response first. This
// will be handled below.
expired, hashedPassword, pwRetrievalErr := pwRetrieveFn(ctx)
scramServer, _ := scram.SHA256.NewServer(func(user string) (creds scram.StoredCredentials, err error) {
// NB: the username passed in the SCRAM exchange (the user
// parameter in this callback) is ignored by PostgreSQL servers;
// see auth-scram.c, read_client_first_message().
//
// Therefore, we can't assume that SQL client drivers populate anything
// useful there. So we ignore it too.
// We still need to check whether the credentials loaded above
// are valid. We place this check in this callback because it
// only needs to happen after the SCRAM handshake actually needs
// to know the credentials.
if expired {
c.LogAuthFailed(ctx, eventpb.AuthFailReason_CREDENTIALS_EXPIRED, nil)
return creds, errExpiredPassword
} else if hashedPassword.Method() != password.HashSCRAMSHA256 {
credentialsNotSCRAMErr := errors.New("user password hash not in SCRAM format")
c.LogAuthFailed(ctx, eventpb.AuthFailReason_PRE_HOOK_ERROR, credentialsNotSCRAMErr)
return creds, credentialsNotSCRAMErr
}
// The method check above ensures this cast is always valid.
ok, creds := password.GetSCRAMStoredCredentials(hashedPassword)
if !ok {
return creds, errors.AssertionFailedf("programming error: hash method is SCRAM but no stored credentials")
}
return creds, nil
})
handshake := scramServer.NewConversation()
initial := true
for {
if handshake.Done() {
break
}
// Receive a response from the client.
resp, err := c.GetPwdData()
if err != nil {
c.LogAuthFailed(ctx, eventpb.AuthFailReason_PRE_HOOK_ERROR, err)
if pwRetrievalErr != nil {
return errors.CombineErrors(err, pwRetrievalErr)
}
return err
}
// Now process the password retrieval error, if any.
if pwRetrievalErr != nil {
c.LogAuthFailed(ctx, eventpb.AuthFailReason_USER_RETRIEVAL_ERROR, pwRetrievalErr)
return pwRetrievalErr
}
var input []byte
if initial {
// Quoth postgres, backend/auth.go:
//
// The first SASLInitialResponse message is different from the others.
// It indicates which SASL mechanism the client selected, and contains
// an optional Initial Client Response payload. The subsequent
// SASLResponse messages contain just the SASL payload.
//
rb := pgwirebase.ReadBuffer{Msg: resp}
reqMethod, err := rb.GetString()
if err != nil {
c.LogAuthFailed(ctx, eventpb.AuthFailReason_PRE_HOOK_ERROR, err)
return err
}
if reqMethod != "SCRAM-SHA-256" {
c.LogAuthInfof(ctx, redact.Sprintf("client requests unknown scram method %q", redact.SafeString(reqMethod)))
err := unimplemented.NewWithIssue(74300, "channel binding not supported")
// We need to manually report the unimplemented error because it is not
// passed through to the client as-is (authn errors are hidden behind
// a generic "authn failed" error).
sqltelemetry.RecordError(ctx, err, &execCfg.Settings.SV)
return err
}
inputLen, err := rb.GetUint32()
if err != nil {
c.LogAuthFailed(ctx, eventpb.AuthFailReason_PRE_HOOK_ERROR, err)
return err
}
// PostgreSQL ignores input from clients that pass -1 as length,
// but does not treat it as invalid.
if inputLen < math.MaxUint32 {
input, err = rb.GetBytes(int(inputLen))
if err != nil {
c.LogAuthFailed(ctx, eventpb.AuthFailReason_PRE_HOOK_ERROR, err)
return err
}
}
initial = false
} else {
input = resp
}
// Feed the client message to the state machine.
got, err := handshake.Step(string(input))
if err != nil {
c.LogAuthFailed(ctx, eventpb.AuthFailReason_PRE_HOOK_ERROR, errors.Wrap(err, "scram handshake error"))
break
}
// Decide which response to send to the client.
reqType := authReqSASLContinue
if handshake.Done() {
// This is the last message.
reqType = authReqSASLFin
}
// Send the response to the client.
if err := c.SendAuthRequest(reqType, []byte(got)); err != nil {
return err
}
}
// Did authentication succeed?
if !handshake.Valid() {
return security.NewErrPasswordUserAuthFailed(systemIdentity)
}
return nil // auth success!
}
// authCert is the AuthMethod constructor for HBA method "cert":
// authenticate using TLS client certificates.
// It is also the fallback constructor for HBA methods "cert-password"
// and "cert-scram-sha-256" when the SQL client provides a TLS client
// certificate.
func authCert(
_ context.Context,
_ AuthConn,
tlsState tls.ConnectionState,
execCfg *sql.ExecutorConfig,
hbaEntry *hba.Entry,
identMap *identmap.Conf,
) (*AuthBehaviors, error) {
b := &AuthBehaviors{}
b.SetRoleMapper(HbaMapper(hbaEntry, identMap))
b.SetAuthenticator(func(
ctx context.Context,
systemIdentity username.SQLUsername,
clientConnection bool,
pwRetrieveFn PasswordRetrievalFn,
roleSubject *ldap.DN,
) error {
if len(tlsState.PeerCertificates) == 0 {
return errors.New("no TLS peer certificates, but required for auth")
}
// Normalize the username contained in the certificate.
tlsState.PeerCertificates[0].Subject.CommonName = tree.Name(
tlsState.PeerCertificates[0].Subject.CommonName,
).Normalize()
cm, err := execCfg.RPCContext.SecurityContext.GetCertificateManager()
if err != nil {
log.Ops.Warningf(ctx, "failed to get cert manager info: %v", err)
}
hook, err := security.UserAuthCertHook(
false, /*insecure*/
&tlsState,
execCfg.RPCContext.TenantID,
cm,
roleSubject,
security.ClientCertSubjectRequired.Get(&execCfg.Settings.SV),
)
if err != nil {
return err
}
return hook(ctx, systemIdentity, clientConnection)
})
if len(tlsState.PeerCertificates) > 0 && hbaEntry.GetOption("map") != "" {
// The common name in the certificate is set as the system identity in case we have an HBAEntry for db user.
commonName, err := username.MakeSQLUsernameFromUserInput(tlsState.PeerCertificates[0].Subject.CommonName, username.PurposeValidation)
if err != nil {
return nil, err
}
b.SetReplacementIdentity(commonName)
}
return b, nil
}
// authCertPassword is the AuthMethod constructor for HBA method
// "cert-password": authenticate EITHER using a TLS client cert OR a
// password exchange.
//
// TLS client cert authn is used iff the client presents a TLS client cert.
// Otherwise, the password authentication protocol is chosen
// depending on the format of the stored credentials: SCRAM is preferred
// if possible, otherwise fallback to cleartext.
// See the documentation for authAutoSelectPasswordProtocol() below.
func authCertPassword(
ctx context.Context,
c AuthConn,
tlsState tls.ConnectionState,
execCfg *sql.ExecutorConfig,
entry *hba.Entry,
identMap *identmap.Conf,
) (*AuthBehaviors, error) {
var fn AuthMethod
if len(tlsState.PeerCertificates) == 0 {
c.LogAuthInfof(ctx, "client did not present TLS certificate")
if AutoSelectPasswordAuth.Get(&execCfg.Settings.SV) {
// We don't call c.LogAuthInfo here; this is done in
// authAutoSelectPasswordProtocol() below.
fn = authAutoSelectPasswordProtocol
} else {
c.LogAuthInfof(ctx, "proceeding with password authentication")
fn = authPassword
}
} else {
c.LogAuthInfof(ctx, "client presented certificate, proceeding with certificate validation")
fn = authCert
}
return fn(ctx, c, tlsState, execCfg, entry, identMap)
}
// AutoSelectPasswordAuth determines whether CockroachDB automatically promotes the password
// protocol when a SCRAM hash is detected in the stored credentials.
//
// It is exported for use in tests.
var AutoSelectPasswordAuth = settings.RegisterBoolSetting(
settings.ApplicationLevel,
"server.user_login.cert_password_method.auto_scram_promotion.enabled",
"whether to automatically promote cert-password authentication to use SCRAM",
true,
settings.WithPublic)
// authAutoSelectPasswordProtocol is the AuthMethod constructor used
// for HBA method "cert-password" when the SQL client does not provide
// a TLS client certificate.
//
// It uses the effective format of the stored hash password to decide
// the hash protocol: if the stored hash uses the SCRAM encoding,
// SCRAM-SHA-256 is used (which is a safer handshake); otherwise,
// cleartext password authentication is used.
func authAutoSelectPasswordProtocol(
_ context.Context,
c AuthConn,
_ tls.ConnectionState,
execCfg *sql.ExecutorConfig,
_ *hba.Entry,
_ *identmap.Conf,
) (*AuthBehaviors, error) {
b := &AuthBehaviors{}
b.SetRoleMapper(UseProvidedIdentity)
b.SetAuthenticator(func(
ctx context.Context,
systemIdentity username.SQLUsername,
clientConnection bool,
pwRetrieveFn PasswordRetrievalFn,
_ *ldap.DN,
) error {
// Request information about the password hash.
expired, hashedPassword, pwRetrieveErr := pwRetrieveFn(ctx)
// Note: we could be checking 'expired' and 'err' here, and exit
// early. However, we already have code paths to do just that in
// each authenticator, so we might as well use them. To do this,
// we capture the same information into the closure that the
// authenticator will call anyway.
newpwfn := func(ctx context.Context) (bool, password.PasswordHash, error) {
return expired, hashedPassword, pwRetrieveErr
}
// Was the password using the bcrypt hash encoding?
if pwRetrieveErr == nil && hashedPassword.Method() == password.HashBCrypt {
// Yes: we have no choice but to request a cleartext password.
c.LogAuthInfof(ctx, "found stored crdb-bcrypt credentials; requesting cleartext password")
return passwordAuthenticator(ctx, systemIdentity, clientConnection, newpwfn, c, execCfg)
}
if pwRetrieveErr == nil && hashedPassword.Method() == password.HashSCRAMSHA256 {
autoDowngradePasswordHashesBool := security.AutoDowngradePasswordHashes.Get(&execCfg.Settings.SV)
autoRehashOnCostChangeBool := security.AutoRehashOnSCRAMCostChange.Get(&execCfg.Settings.SV)
configuredHashMethod := security.GetConfiguredPasswordHashMethod(&execCfg.Settings.SV)
configuredSCRAMCost := security.SCRAMCost.Get(&execCfg.Settings.SV)
if autoDowngradePasswordHashesBool && configuredHashMethod == password.HashBCrypt {
// If the cluster is configured to automatically downgrade from SCRAM to
// bcrypt, then we also request the cleartext password.
c.LogAuthInfof(ctx, "found stored SCRAM-SHA-256 credentials but cluster is configured to downgrade to bcrypt; requesting cleartext password")
return passwordAuthenticator(ctx, systemIdentity, clientConnection, newpwfn, c, execCfg)
}
if autoRehashOnCostChangeBool && configuredHashMethod == password.HashSCRAMSHA256 {
ok, creds := password.GetSCRAMStoredCredentials(hashedPassword)
if !ok {
return errors.AssertionFailedf("programming error: password retrieved but invalid scram hash")
}
if int64(creds.Iters) != configuredSCRAMCost {
// If the cluster is configured to automatically re-hash the SCRAM
// password when the default cost is changed, then we also request the
// cleartext password.
c.LogAuthInfof(ctx, "found stored SCRAM-SHA-256 credentials but cluster is configured to re-hash after SCRAM cost change; requesting cleartext password")
return passwordAuthenticator(ctx, systemIdentity, clientConnection, newpwfn, c, execCfg)
}
}
}
// Error, no credentials or stored SCRAM hash: use the
// SCRAM-SHA-256 logic.
//
// Note: we use SCRAM as a fallback as an additional security
// measure: if the password retrieval fails due to a transient
// error, we don't want the fallback to force the client to
// transmit a password in clear.
c.LogAuthInfof(ctx, "no crdb-bcrypt credentials found; proceeding with SCRAM-SHA-256")
return scramAuthenticator(ctx, systemIdentity, clientConnection, newpwfn, c, execCfg)
})
return b, nil
}
// authCertPassword is the AuthMethod constructor for HBA method
// "cert-scram-sha-256": authenticate EITHER using a TLS client cert
// OR a valid SCRAM exchange.
// TLS client cert authn is used iff the client presents a TLS client cert.
func authCertScram(
ctx context.Context,
c AuthConn,
tlsState tls.ConnectionState,
execCfg *sql.ExecutorConfig,
entry *hba.Entry,
identMap *identmap.Conf,
) (*AuthBehaviors, error) {
var fn AuthMethod
if len(tlsState.PeerCertificates) == 0 {
c.LogAuthInfof(ctx, "no client certificate, proceeding with SCRAM authentication")
fn = authScram
} else {
c.LogAuthInfof(ctx, "client presented certificate, proceeding with certificate validation")
fn = authCert
}
return fn(ctx, c, tlsState, execCfg, entry, identMap)
}
// authTrust is the AuthMethod constructor for HBA method "trust":
// always allow the client, do not perform authentication.
func authTrust(
_ context.Context,
_ AuthConn,
_ tls.ConnectionState,
_ *sql.ExecutorConfig,
_ *hba.Entry,
_ *identmap.Conf,
) (*AuthBehaviors, error) {
b := &AuthBehaviors{}
b.SetRoleMapper(UseProvidedIdentity)
b.SetAuthenticator(func(_ context.Context, _ username.SQLUsername, _ bool, _ PasswordRetrievalFn, _ *ldap.DN) error {
return nil
})
return b, nil
}
// authReject is the AuthMethod constructor for HBA method "reject":
// never allow the client.
func authReject(
_ context.Context,
c AuthConn,
_ tls.ConnectionState,
_ *sql.ExecutorConfig,
_ *hba.Entry,
_ *identmap.Conf,
) (*AuthBehaviors, error) {
b := &AuthBehaviors{}
b.SetRoleMapper(UseProvidedIdentity)
b.SetAuthenticator(func(ctx context.Context, _ username.SQLUsername, _ bool, _ PasswordRetrievalFn, _ *ldap.DN) error {
err := errors.New("authentication rejected by configuration")
c.LogAuthFailed(ctx, eventpb.AuthFailReason_LOGIN_DISABLED, err)
return err
})
return b, nil
}
// authSessionRevivalToken is the AuthMethod constructor for the CRDB-specific
// session revival token.
// The session revival token is passed in the crdb:session_revival_token_base64
// field during initial connection. This value is then extracted, base64 decoded
// and verified.
// This field is only expected to be used in instances where we have a SQL proxy.
// The SQL proxy prevents the end customer from sending this field. In the future,
// We may decide to pass the token in the password field with a boolean field to
// indicate the contents of the password field is a sessionRevivalToken as an
// additional method. This could reduce the risk of the sessionRevivalToken being
// logged accidentally. This risk is already fairly low because it should only be
// passed by the SQL proxy.
func authSessionRevivalToken(token []byte) AuthMethod {
return func(
_ context.Context,
c AuthConn,
_ tls.ConnectionState,
execCfg *sql.ExecutorConfig,
_ *hba.Entry,
_ *identmap.Conf,
) (*AuthBehaviors, error) {
b := &AuthBehaviors{}
b.SetRoleMapper(UseProvidedIdentity)
b.SetAuthenticator(func(ctx context.Context, user username.SQLUsername, _ bool, _ PasswordRetrievalFn, _ *ldap.DN) error {
c.LogAuthInfof(ctx, "session revival token detected; attempting to use it")
if !sql.AllowSessionRevival.Get(&execCfg.Settings.SV) || execCfg.Codec.ForSystemTenant() {
return errors.New("session revival tokens are not supported on this cluster")
}
cm, err := execCfg.RPCContext.SecurityContext.GetCertificateManager()
if err != nil {
return err
}
if err := sessionrevival.ValidateSessionRevivalToken(cm, user, token); err != nil {
return errors.Wrap(err, "invalid session revival token")
}
return nil
})
return b, nil
}
}
// JWTVerifier is an interface for the `jwtauthccl` library to add JWT login support.
// This interface has a method that validates whether a given JWT token is a proper
// credential for a given user to login.
type JWTVerifier interface {
ValidateJWTLogin(_ context.Context, _ *cluster.Settings,
_ username.SQLUsername,
_ []byte,
_ *identmap.Conf,
) (detailedErrorMsg string, authError error)
}
var jwtVerifier JWTVerifier
type noJWTConfigured struct{}
func (c *noJWTConfigured) ValidateJWTLogin(
_ context.Context, _ *cluster.Settings, _ username.SQLUsername, _ []byte, _ *identmap.Conf,
) (detailedErrorMsg string, authError error) {
return "", errors.New("JWT token authentication requires CCL features")
}
// ConfigureJWTAuth is a hook for the `jwtauthccl` library to add JWT login support. It's called to
// setup the JWTVerifier just as it is needed.
var ConfigureJWTAuth = func(
serverCtx context.Context,
ambientCtx log.AmbientContext,
st *cluster.Settings,
clusterUUID uuid.UUID,
) JWTVerifier {
return &noJWTConfigured{}
}
// authJwtToken is the AuthMethod constructor for the CRDB-specific
// jwt auth token.
// The method is triggered when the client passes a specific option indicating
// that it is passing a token in the password field. The token is then extracted
// from the password field and verified.
// The decision was made to pass the token in the password field instead of in
// the options parameter as some drivers may insecurely handle options parameters.
// In contrast, all drivers SHOULD know not to log the password, for example.
func authJwtToken(
sctx context.Context,
c AuthConn,
_ tls.ConnectionState,
execCfg *sql.ExecutorConfig,
_ *hba.Entry,
identMap *identmap.Conf,
) (*AuthBehaviors, error) {
// Initialize the jwt verifier if it hasn't been already.
if jwtVerifier == nil {
jwtVerifier = ConfigureJWTAuth(sctx, execCfg.AmbientCtx, execCfg.Settings, execCfg.NodeInfo.LogicalClusterID())
}
b := &AuthBehaviors{}
b.SetRoleMapper(UseProvidedIdentity)
b.SetAuthenticator(func(ctx context.Context, user username.SQLUsername, clientConnection bool, pwRetrieveFn PasswordRetrievalFn, _ *ldap.DN) error {
c.LogAuthInfof(ctx, "JWT token detected; attempting to use it")
if !clientConnection {
err := errors.New("JWT token authentication is only available for client connections")
c.LogAuthFailed(ctx, eventpb.AuthFailReason_PRE_HOOK_ERROR, err)
return err
}
// Request password from client.
if err := c.SendAuthRequest(authCleartextPassword, nil /* data */); err != nil {
c.LogAuthFailed(ctx, eventpb.AuthFailReason_PRE_HOOK_ERROR, err)
return err
}
// Wait for the password response from the client.
pwdData, err := c.GetPwdData()
if err != nil {
c.LogAuthFailed(ctx, eventpb.AuthFailReason_PRE_HOOK_ERROR, err)
return err
}
// Extract the token response from the password field.
token, err := passwordString(pwdData)
if err != nil {
c.LogAuthFailed(ctx, eventpb.AuthFailReason_PRE_HOOK_ERROR, err)
return err
}
// If there is no token send the Password Auth Failed error to make the client prompt for a password.
if len(token) == 0 {
return security.NewErrPasswordUserAuthFailed(user)
}
if detailedErrors, authError := jwtVerifier.ValidateJWTLogin(ctx, execCfg.Settings, user, []byte(token), identMap); authError != nil {
c.LogAuthFailed(ctx, eventpb.AuthFailReason_CREDENTIALS_INVALID,
errors.Join(authError, errors.Newf("%s", detailedErrors)))
return authError
}
return nil
})
return b, nil
}
// LDAPVerifier is an interface for the `ldapauthccl` library to add ldap login
// support. This interface has a method that validates whether the password
// supplied could be used to bind to ldap server with a distinguished name
// obtained from performing a search operation using options provided in the hba
// conf and supplied sql username.
type LDAPVerifier interface {
ValidateLDAPLogin(_ context.Context, _ *cluster.Settings,
_ username.SQLUsername,
_ string,
_ *hba.Entry,
_ *identmap.Conf,
) (detailedErrorMsg string, authError error)
}
var ldapVerifier LDAPVerifier
type noLDAPConfigured struct{}
func (c *noLDAPConfigured) ValidateLDAPLogin(
_ context.Context,
_ *cluster.Settings,
_ username.SQLUsername,
_ string,
_ *hba.Entry,
_ *identmap.Conf,
) (detailedErrorMsg string, authError error) {
return "", errors.New("LDAP based authentication requires CCL features")
}
// ConfigureLDAPAuth is a hook for the `ldapauthccl` library to add LDAP login
// support. It's called to setup the LDAPVerifier just as it is needed.
var ConfigureLDAPAuth = func(
serverCtx context.Context,
ambientCtx log.AmbientContext,
st *cluster.Settings,
clusterUUID uuid.UUID,
) LDAPVerifier {
return &noLDAPConfigured{}
}
// authLDAP is the AuthMethod constructor for the CRDB-specific
// ldap auth mechanism.
func authLDAP(
sCtx context.Context,
c AuthConn,
_ tls.ConnectionState,
execCfg *sql.ExecutorConfig,
entry *hba.Entry,
identMap *identmap.Conf,
) (*AuthBehaviors, error) {
// Initialize the jwt verifier if it hasn't been already.
if ldapVerifier == nil {
ldapVerifier = ConfigureLDAPAuth(sCtx, execCfg.AmbientCtx, execCfg.Settings, execCfg.NodeInfo.LogicalClusterID())
}
b := &AuthBehaviors{}
b.SetRoleMapper(UseProvidedIdentity)
b.SetAuthenticator(func(ctx context.Context, user username.SQLUsername, clientConnection bool, _ PasswordRetrievalFn, _ *ldap.DN) error {
c.LogAuthInfof(ctx, "LDAP password provided; attempting to bind to domain")
if !clientConnection {
err := errors.New("LDAP authentication is only available for client connections")
c.LogAuthFailed(ctx, eventpb.AuthFailReason_PRE_HOOK_ERROR, err)
return err
}
// Request password from client.
if err := c.SendAuthRequest(authCleartextPassword, nil /* data */); err != nil {
c.LogAuthFailed(ctx, eventpb.AuthFailReason_PRE_HOOK_ERROR, err)
return err
}
// Wait for the password response from the client.
pwdData, err := c.GetPwdData()
if err != nil {
c.LogAuthFailed(ctx, eventpb.AuthFailReason_PRE_HOOK_ERROR, err)
return err
}
// Extract the token response from the password field.
ldapPwd, err := passwordString(pwdData)
if err != nil {
c.LogAuthFailed(ctx, eventpb.AuthFailReason_PRE_HOOK_ERROR, err)
return err
}
// If there is no ldap pwd send the Password Auth Failed error to make the client prompt for a password.
if len(ldapPwd) == 0 {
return security.NewErrPasswordUserAuthFailed(user)
}
if detailedErrors, authError := ldapVerifier.ValidateLDAPLogin(ctx, execCfg.Settings, user, ldapPwd, entry, identMap); authError != nil {
c.LogAuthFailed(ctx, eventpb.AuthFailReason_CREDENTIALS_INVALID,
errors.Join(authError, errors.Newf("%s", detailedErrors)))
return authError
}
return nil
})
return b, nil
}