-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
db.go
1784 lines (1599 loc) · 57 KB
/
db.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
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2020-2021 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package common
import (
"bytes"
"context"
"crypto/tls"
"fmt"
"io"
"net"
"os"
"sort"
"strings"
"sync"
"text/template"
"github.com/ghodss/yaml"
"github.com/gravitational/trace"
"go.opentelemetry.io/otel/attribute"
oteltrace "go.opentelemetry.io/otel/trace"
"golang.org/x/exp/slices"
"golang.org/x/sync/errgroup"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/api/client/proto"
"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/api/utils/keys"
"github.com/gravitational/teleport/lib/client"
dbprofile "github.com/gravitational/teleport/lib/client/db"
"github.com/gravitational/teleport/lib/client/db/dbcmd"
"github.com/gravitational/teleport/lib/client/db/oracle"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/srv/alpnproxy"
"github.com/gravitational/teleport/lib/srv/db/common/role"
"github.com/gravitational/teleport/lib/tlsca"
"github.com/gravitational/teleport/lib/utils"
)
// onListDatabases implements "tsh db ls" command.
func onListDatabases(cf *CLIConf) error {
if cf.ListAll {
return trace.Wrap(listDatabasesAllClusters(cf))
}
tc, err := makeClient(cf)
if err != nil {
return trace.Wrap(err)
}
profile, err := tc.ProfileStatus()
if err != nil {
return trace.Wrap(err)
}
var proxy *client.ProxyClient
err = client.RetryWithRelogin(cf.Context, tc, func() error {
proxy, err = tc.ConnectToProxy(cf.Context)
return trace.Wrap(err)
})
if err != nil {
return trace.Wrap(err)
}
defer proxy.Close()
databases, err := proxy.FindDatabasesByFiltersForCluster(cf.Context, *tc.ResourceFilter(types.KindDatabaseServer), tc.SiteName)
if err != nil {
return trace.Wrap(err)
}
accessChecker, err := accessCheckerForRemoteCluster(cf.Context, profile, proxy, tc.SiteName)
if err != nil {
log.Debugf("Failed to fetch user roles: %v.", err)
}
activeDatabases, err := profile.DatabasesForCluster(tc.SiteName)
if err != nil {
return trace.Wrap(err)
}
sort.Sort(types.Databases(databases))
return trace.Wrap(showDatabases(cf, databases, activeDatabases, accessChecker))
}
func accessCheckerForRemoteCluster(ctx context.Context, profile *client.ProfileStatus, proxy *client.ProxyClient, clusterName string) (services.AccessChecker, error) {
cluster, err := proxy.ConnectToCluster(ctx, clusterName)
if err != nil {
return nil, trace.Wrap(err)
}
defer cluster.Close()
accessChecker, err := services.NewAccessCheckerForRemoteCluster(ctx, profile.AccessInfo(), clusterName, cluster)
return accessChecker, trace.Wrap(err)
}
type databaseListing struct {
Proxy string `json:"proxy"`
Cluster string `json:"cluster"`
accessChecker services.AccessChecker `json:"-"`
Database types.Database `json:"database"`
}
type databaseListings []databaseListing
func (l databaseListings) Len() int {
return len(l)
}
func (l databaseListings) Less(i, j int) bool {
if l[i].Proxy != l[j].Proxy {
return l[i].Proxy < l[j].Proxy
}
if l[i].Cluster != l[j].Cluster {
return l[i].Cluster < l[j].Cluster
}
return l[i].Database.GetName() < l[j].Database.GetName()
}
func (l databaseListings) Swap(i, j int) {
l[i], l[j] = l[j], l[i]
}
func listDatabasesAllClusters(cf *CLIConf) error {
tracer := cf.TracingProvider.Tracer(teleport.ComponentTSH)
clusters, err := getClusterClients(cf, types.KindDatabaseServer)
if err != nil {
return trace.Wrap(err)
}
defer func() {
// close all clients
for _, cluster := range clusters {
_ = cluster.Close()
}
}()
// Fetch database listings for all clusters in parallel with an upper limit
group, groupCtx := errgroup.WithContext(cf.Context)
group.SetLimit(10)
// mu guards access to dbListings
var (
mu sync.Mutex
dbListings databaseListings
errors []error
)
for _, cluster := range clusters {
cluster := cluster
if cluster.connectionError != nil {
mu.Lock()
errors = append(errors, cluster.connectionError)
mu.Unlock()
continue
}
group.Go(func() error {
ctx, span := tracer.Start(
groupCtx,
"ListDatabases",
oteltrace.WithAttributes(attribute.String("cluster", cluster.name)))
defer span.End()
logger := log.WithField("cluster", cluster.name)
databases, err := cluster.proxy.FindDatabasesByFiltersForCluster(ctx, cluster.req, cluster.name)
if err != nil {
logger.Errorf("Failed to get databases: %v.", err)
mu.Lock()
errors = append(errors, trace.ConnectionProblem(err, "failed to list databases for cluster %s: %v", cluster.name, err))
mu.Unlock()
return nil
}
accessChecker, err := accessCheckerForRemoteCluster(ctx, cluster.profile, cluster.proxy, cluster.name)
if err != nil {
log.Debugf("Failed to fetch user roles: %v.", err)
}
localDBListings := make(databaseListings, 0, len(databases))
for _, database := range databases {
localDBListings = append(localDBListings, databaseListing{
Proxy: cluster.profile.ProxyURL.Host,
Cluster: cluster.name,
accessChecker: accessChecker,
Database: database,
})
}
mu.Lock()
dbListings = append(dbListings, localDBListings...)
mu.Unlock()
return nil
})
}
if err := group.Wait(); err != nil {
return trace.Wrap(err)
}
if len(dbListings) == 0 && len(errors) > 0 {
return trace.NewAggregate(errors...)
}
sort.Sort(dbListings)
profile, err := cf.ProfileStatus()
if err != nil {
return trace.Wrap(err)
}
var active []tlsca.RouteToDatabase
if profile != nil {
active = profile.Databases
}
format := strings.ToLower(cf.Format)
switch format {
case teleport.Text, "":
printDatabasesWithClusters(cf, dbListings, active)
case teleport.JSON, teleport.YAML:
out, err := serializeDatabasesAllClusters(dbListings, format)
if err != nil {
return trace.Wrap(err)
}
fmt.Println(out)
default:
return trace.BadParameter("unsupported format %q", format)
}
return trace.NewAggregate(errors...)
}
// onDatabaseLogin implements "tsh db login" command.
func onDatabaseLogin(cf *CLIConf) error {
tc, err := makeClient(cf)
if err != nil {
return trace.Wrap(err)
}
profile, err := tc.ProfileStatus()
if err != nil {
return trace.Wrap(err)
}
routes, err := profile.DatabasesForCluster(tc.SiteName)
if err != nil {
return trace.Wrap(err)
}
dbInfo, err := getDatabaseInfo(cf, tc, routes)
if err != nil {
return trace.Wrap(err)
}
database, err := dbInfo.GetDatabase(cf.Context, tc)
if err != nil {
return trace.Wrap(err)
}
if err := databaseLogin(cf, tc, dbInfo); err != nil {
return trace.Wrap(err)
}
// Print after-login message.
templateData := map[string]string{
"name": dbInfo.ServiceName,
}
if protocolSupportsInteractiveMode(database.GetProtocol()) {
templateData["connectCommand"] = utils.Color(utils.Yellow, formatDatabaseConnectCommand(cf.SiteName, dbInfo.RouteToDatabase))
}
requires := getDBLocalProxyRequirement(tc, dbInfo.RouteToDatabase)
if requires.localProxy {
templateData["proxyCommand"] = utils.Color(utils.Yellow, formatDatabaseProxyCommand(cf.SiteName, dbInfo.RouteToDatabase))
} else {
templateData["configCommand"] = utils.Color(utils.Yellow, formatDatabaseConfigCommand(cf.SiteName, dbInfo.RouteToDatabase))
}
return trace.Wrap(dbConnectTemplate.Execute(cf.Stdout(), templateData))
}
// protocolSupportsInteractiveMode checks if DB Protocol integration support
// client interactive mode that is needed for the tsh db connect flow.
func protocolSupportsInteractiveMode(dbProtocol string) bool {
switch dbProtocol {
case defaults.ProtocolDynamoDB, defaults.ProtocolClickHouseHTTP:
return false
}
return true
}
func databaseLogin(cf *CLIConf, tc *client.TeleportClient, dbInfo *databaseInfo) error {
log.Debugf("Fetching database access certificate for %s on cluster %v.", dbInfo.RouteToDatabase, tc.SiteName)
profile, err := tc.ProfileStatus()
if err != nil {
return trace.Wrap(err)
}
var key *client.Key
// Identity files themselves act as the database credentials (if any), so
// don't bother fetching new certs.
if profile.IsVirtual {
log.Info("Note: already logged in due to an identity file (`-i ...`); will only update database config files.")
} else {
if err = client.RetryWithRelogin(cf.Context, tc, func() error {
key, err = tc.IssueUserCertsWithMFA(cf.Context, client.ReissueParams{
RouteToCluster: tc.SiteName,
RouteToDatabase: proto.RouteToDatabase{
ServiceName: dbInfo.ServiceName,
Protocol: dbInfo.Protocol,
Username: dbInfo.Username,
Database: dbInfo.Database,
},
AccessRequests: profile.ActiveRequests.AccessRequests,
})
return trace.Wrap(err)
}); err != nil {
return trace.Wrap(err)
}
if err = tc.LocalAgent().AddDatabaseKey(key); err != nil {
return trace.Wrap(err)
}
}
if dbInfo.Protocol == defaults.ProtocolOracle {
if err := generateDBLocalProxyCert(key, profile); err != nil {
return trace.Wrap(err)
}
err = oracle.GenerateClientConfiguration(key, dbInfo.RouteToDatabase, profile)
if err != nil {
return trace.Wrap(err)
}
}
// Refresh the profile.
profile, err = tc.ProfileStatus()
if err != nil {
return trace.Wrap(err)
}
// Update the database-specific connection profile file.
err = dbprofile.Add(cf.Context, tc, dbInfo.RouteToDatabase, *profile)
return trace.Wrap(err)
}
// onDatabaseLogout implements "tsh db logout" command.
func onDatabaseLogout(cf *CLIConf) error {
tc, err := makeClient(cf)
if err != nil {
return trace.Wrap(err)
}
profile, err := tc.ProfileStatus()
if err != nil {
return trace.Wrap(err)
}
activeRoutes, err := profile.DatabasesForCluster(tc.SiteName)
if err != nil {
return trace.Wrap(err)
}
databases, err := getDatabasesForLogout(cf, tc, activeRoutes)
if err != nil {
return trace.Wrap(err)
}
if profile.IsVirtual {
log.Info("Note: an identity file is in use (`-i ...`); will only update database config files.")
}
for _, db := range databases {
if err := databaseLogout(tc, db, profile.IsVirtual); err != nil {
return trace.Wrap(err)
}
}
msg, err := makeLogoutMessage(cf, databases, activeRoutes)
if err != nil {
return trace.Wrap(err)
}
fmt.Fprintln(cf.Stdout(), msg)
return nil
}
// makeLogoutMessage is a helper func that returns a logout message for the
// result of "tsh db logout".
func makeLogoutMessage(cf *CLIConf, logout, activeRoutes []tlsca.RouteToDatabase) (string, error) {
switch len(logout) {
case 1:
return fmt.Sprintf("Logged out of database %v", logout[0].ServiceName), nil
case len(activeRoutes):
return "Logged out of all databases", nil
case 0:
selectors := newDatabaseResourceSelectors(cf)
if selectors.IsEmpty() {
return "", trace.NotFound("Not logged into any databases")
}
return "", trace.NotFound("Not logged into %s", selectors)
default:
names := make([]string, 0, len(logout))
for _, route := range logout {
names = append(names, route.ServiceName)
}
slices.Sort(names)
nameLines := strings.Join(names, "\n")
return fmt.Sprintf("Logged out of databases:\n%v", nameLines), nil
}
}
func databaseLogout(tc *client.TeleportClient, db tlsca.RouteToDatabase, virtual bool) error {
// First remove respective connection profile.
err := dbprofile.Delete(tc, db)
if err != nil {
return trace.Wrap(err)
}
// Then remove the certificate from the keystore, but only for real
// profiles.
if !virtual {
err = tc.LogoutDatabase(db.ServiceName)
if err != nil {
return trace.Wrap(err)
}
}
return nil
}
// onDatabaseEnv implements "tsh db env" command.
func onDatabaseEnv(cf *CLIConf) error {
tc, err := makeClient(cf)
if err != nil {
return trace.Wrap(err)
}
profile, err := tc.ProfileStatus()
if err != nil {
return trace.Wrap(err)
}
routes, err := profile.DatabasesForCluster(tc.SiteName)
if err != nil {
return trace.Wrap(err)
}
database, err := pickActiveDatabase(cf, tc, routes)
if err != nil {
return trace.Wrap(err)
}
if !dbprofile.IsSupported(*database) {
return trace.BadParameter(formatDbCmdUnsupportedDBProtocol(cf, *database))
}
requires := getDBLocalProxyRequirement(tc, *database)
if requires.localProxy {
return trace.BadParameter(formatDbCmdUnsupported(cf, *database, requires.localProxyReasons...))
}
env, err := dbprofile.Env(tc, *database)
if err != nil {
return trace.Wrap(err)
}
format := strings.ToLower(cf.Format)
switch format {
case dbFormatText, "":
for k, v := range env {
fmt.Printf("export %v=%v\n", k, v)
}
case dbFormatJSON, dbFormatYAML:
out, err := serializeDatabaseEnvironment(env, format)
if err != nil {
return trace.Wrap(err)
}
fmt.Println(out)
default:
return trace.BadParameter("unsupported format %q", cf.Format)
}
return nil
}
func serializeDatabaseEnvironment(env map[string]string, format string) (string, error) {
var out []byte
var err error
if format == dbFormatJSON {
out, err = utils.FastMarshalIndent(env, "", " ")
} else {
out, err = yaml.Marshal(env)
}
return string(out), trace.Wrap(err)
}
// onDatabaseConfig implements "tsh db config" command.
func onDatabaseConfig(cf *CLIConf) error {
tc, err := makeClient(cf)
if err != nil {
return trace.Wrap(err)
}
profile, err := tc.ProfileStatus()
if err != nil {
return trace.Wrap(err)
}
routes, err := profile.DatabasesForCluster(tc.SiteName)
if err != nil {
return trace.Wrap(err)
}
database, err := pickActiveDatabase(cf, tc, routes)
if err != nil {
return trace.Wrap(err)
}
requires := getDBLocalProxyRequirement(tc, *database)
// "tsh db config" prints out instructions for native clients to connect to
// the remote proxy directly. Return errors here when direct connection
// does NOT work (e.g. when ALPN local proxy is required).
if requires.localProxy {
msg := formatDbCmdUnsupported(cf, *database, requires.localProxyReasons...)
return trace.BadParameter(msg)
}
host, port := tc.DatabaseProxyHostPort(*database)
rootCluster, err := tc.RootClusterName(cf.Context)
if err != nil {
return trace.Wrap(err)
}
format := strings.ToLower(cf.Format)
switch format {
case dbFormatCommand:
cmd, err := dbcmd.NewCmdBuilder(tc, profile, *database, rootCluster,
dbcmd.WithPrintFormat(),
dbcmd.WithLogger(log),
).GetConnectCommand()
if err != nil {
return trace.Wrap(err)
}
fmt.Println(strings.Join(cmd.Env, " "), cmd.Path, strings.Join(cmd.Args[1:], " "))
case dbFormatJSON, dbFormatYAML:
configInfo := &dbConfigInfo{
database.ServiceName, host, port, database.Username,
database.Database, profile.CACertPathForCluster(rootCluster),
profile.DatabaseCertPathForCluster(tc.SiteName, database.ServiceName),
profile.KeyPath(),
}
out, err := serializeDatabaseConfig(configInfo, format)
if err != nil {
return trace.Wrap(err)
}
fmt.Println(out)
default:
fmt.Printf(`Name: %v
Host: %v
Port: %v
User: %v
Database: %v
CA: %v
Cert: %v
Key: %v
`,
database.ServiceName, host, port, database.Username,
database.Database, profile.CACertPathForCluster(rootCluster),
profile.DatabaseCertPathForCluster(tc.SiteName, database.ServiceName), profile.KeyPath())
}
return nil
}
type dbConfigInfo struct {
Name string `json:"name"`
Host string `json:"host"`
Port int `json:"port"`
User string `json:"user,omitempty"`
Database string `json:"database,omitempty"`
CA string `json:"ca"`
Cert string `json:"cert"`
Key string `json:"key"`
}
func serializeDatabaseConfig(configInfo *dbConfigInfo, format string) (string, error) {
var out []byte
var err error
if format == dbFormatJSON {
out, err = utils.FastMarshalIndent(configInfo, "", " ")
} else {
out, err = yaml.Marshal(configInfo)
}
return string(out), trace.Wrap(err)
}
// maybeStartLocalProxy starts local TLS ALPN proxy if needed depending on the
// connection scenario and returns a list of options to use in the connect
// command.
func maybeStartLocalProxy(ctx context.Context, cf *CLIConf,
tc *client.TeleportClient, profile *client.ProfileStatus,
dbInfo *databaseInfo, rootClusterName string,
requires *dbLocalProxyRequirement,
) ([]dbcmd.ConnectCommandFunc, error) {
if !requires.localProxy {
return nil, nil
}
if requires.tunnel {
log.Debugf("Starting local proxy tunnel because: %v", strings.Join(requires.tunnelReasons, ", "))
} else {
log.Debugf("Starting local proxy because: %v", strings.Join(requires.localProxyReasons, ", "))
}
listener, err := createLocalProxyListener("localhost:0", dbInfo.RouteToDatabase, profile)
if err != nil {
return nil, trace.Wrap(err)
}
opts, err := prepareLocalProxyOptions(&localProxyConfig{
cf: cf,
tc: tc,
profile: profile,
dbInfo: dbInfo,
tunnel: requires.tunnel,
})
if err != nil {
return nil, trace.Wrap(err)
}
lp, err := alpnproxy.NewLocalProxy(makeBasicLocalProxyConfig(cf, tc, listener), opts...)
if err != nil {
return nil, trace.Wrap(err)
}
go func() {
defer listener.Close()
if err := lp.Start(ctx); err != nil {
log.WithError(err).Errorf("Failed to start local proxy")
}
}()
addr, err := utils.ParseAddr(lp.GetAddr())
if err != nil {
return nil, trace.Wrap(err)
}
// When connecting over TLS, psql only validates hostname against presented
// certificate's DNS names. As such, connecting to 127.0.0.1 will fail
// validation, so connect to localhost.
host := "localhost"
cmdOpts := []dbcmd.ConnectCommandFunc{
dbcmd.WithLocalProxy(host, addr.Port(0), profile.CACertPathForCluster(rootClusterName)),
}
if requires.tunnel {
cmdOpts = append(cmdOpts, dbcmd.WithNoTLS())
}
return cmdOpts, nil
}
// localProxyConfig is an argument pack used in prepareLocalProxyOptions().
type localProxyConfig struct {
cf *CLIConf
tc *client.TeleportClient
profile *client.ProfileStatus
dbInfo *databaseInfo
// tunnel controls whether client certs will always be used to dial upstream
// by the local proxy, and whether db certs will be auto-reissued for the
// connection.
// - when `tsh db connect` needs to tunnel it will set this field.
// - when `tsh proxy db` is used with `--tunnel` cli flag it will set this field.
tunnel bool
}
func createLocalProxyListener(addr string, route tlsca.RouteToDatabase, profile *client.ProfileStatus) (net.Listener, error) {
if route.Protocol == defaults.ProtocolOracle {
localCert, err := tls.LoadX509KeyPair(
profile.DatabaseLocalCAPath(),
profile.KeyPath(),
)
if err != nil {
return nil, trace.Wrap(err)
}
l, err := tls.Listen("tcp", addr, &tls.Config{
Certificates: []tls.Certificate{localCert},
ServerName: "localhost",
})
return l, trace.Wrap(err)
}
l, err := net.Listen("tcp", addr)
return l, trace.Wrap(err)
}
// prepareLocalProxyOptions created localProxyOpts needed to create local proxy from localProxyConfig.
func prepareLocalProxyOptions(arg *localProxyConfig) ([]alpnproxy.LocalProxyConfigOpt, error) {
opts := []alpnproxy.LocalProxyConfigOpt{
alpnproxy.WithDatabaseProtocol(arg.dbInfo.Protocol),
alpnproxy.WithClusterCAsIfConnUpgrade(arg.cf.Context, arg.tc.RootClusterCACertPool),
}
if arg.tunnel {
cc := client.NewDBCertChecker(arg.tc, arg.dbInfo.RouteToDatabase, nil)
opts = append(opts, alpnproxy.WithMiddleware(cc))
// When using a tunnel, try to load certs, but if that fails
// just skip them and let the reissuer fetch new certs when the local
// proxy starts instead.
cert, err := loadDBCertificate(arg.tc, arg.dbInfo.ServiceName)
if err == nil {
opts = append(opts, alpnproxy.WithClientCerts(cert))
}
return opts, nil
}
// no tunnel, check for protocol-specific cases
switch arg.dbInfo.Protocol {
case defaults.ProtocolPostgres:
// certs are needed for non-tunnel postgres cancel requests.
cert, err := loadDBCertificate(arg.tc, arg.dbInfo.ServiceName)
if err != nil {
return nil, trace.Wrap(err)
}
opts = append(opts, alpnproxy.WithClientCerts(cert))
opts = append(opts, alpnproxy.WithCheckCertsNeeded())
case defaults.ProtocolMySQL:
// To set correct MySQL server version DB proxy needs additional protocol.
db, err := arg.dbInfo.GetDatabase(arg.cf.Context, arg.tc)
if err != nil {
return nil, trace.Wrap(err)
}
opts = append(opts, alpnproxy.WithMySQLVersionProto(db))
}
return opts, nil
}
// onDatabaseConnect implements "tsh db connect" command.
func onDatabaseConnect(cf *CLIConf) error {
tc, err := makeClient(cf)
if err != nil {
return trace.Wrap(err)
}
profile, err := tc.ProfileStatus()
if err != nil {
return trace.Wrap(err)
}
routes, err := profile.DatabasesForCluster(tc.SiteName)
if err != nil {
return trace.Wrap(err)
}
dbInfo, err := getDatabaseInfo(cf, tc, routes)
if err != nil {
return trace.Wrap(err)
}
switch dbInfo.Protocol {
case defaults.ProtocolDynamoDB, defaults.ProtocolClickHouseHTTP:
return trace.BadParameter(formatDbCmdUnsupportedDBProtocol(cf, dbInfo.RouteToDatabase))
}
requires := getDBConnectLocalProxyRequirement(cf.Context, tc, dbInfo.RouteToDatabase)
if err := maybeDatabaseLogin(cf, tc, profile, dbInfo, requires); err != nil {
return trace.Wrap(err)
}
rootClusterName, err := tc.RootClusterName(cf.Context)
if err != nil {
return trace.Wrap(err)
}
// To avoid termination of background DB teleport proxy when a SIGINT is received don't use the cf.Context.
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
opts, err := maybeStartLocalProxy(ctx, cf, tc, profile, dbInfo, rootClusterName, requires)
if err != nil {
return trace.Wrap(err)
}
opts = append(opts, dbcmd.WithLogger(log))
if opts, err = maybeAddDBUserPassword(cf, tc, dbInfo, opts); err != nil {
return trace.Wrap(err)
}
bb := dbcmd.NewCmdBuilder(tc, profile, dbInfo.RouteToDatabase, rootClusterName, opts...)
cmd, err := bb.GetConnectCommand()
if err != nil {
return trace.Wrap(err)
}
log.Debug(cmd.String())
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
// Use io.MultiWriter to duplicate stderr to the capture writer. The
// captured stderr can be used for diagnosing command failures. The capture
// writer captures up to a fixed number to limit memory usage.
peakStderr := utils.NewCaptureNBytesWriter(dbcmd.PeakStderrSize)
cmd.Stderr = io.MultiWriter(os.Stderr, peakStderr)
err = cmd.Run()
if err != nil {
return dbcmd.ConvertCommandError(cmd, err, string(peakStderr.Bytes()))
}
return nil
}
// getDatabaseInfo fetches information about the database from tsh profile if DB
// is active in profile and no labels or predicate query are given.
// Otherwise, the ListDatabases endpoint is called.
func getDatabaseInfo(cf *CLIConf, tc *client.TeleportClient, routes []tlsca.RouteToDatabase) (*databaseInfo, error) {
if route, err := maybePickActiveDatabase(cf, routes); err == nil && route != nil {
info := &databaseInfo{RouteToDatabase: *route, isActive: true}
return info, info.checkAndSetDefaults(cf, tc)
} else if err != nil {
if trace.IsNotFound(err) {
return nil, trace.BadParameter("please specify a database service by name, --labels, or --query")
}
return nil, trace.Wrap(err)
}
db, err := getDatabaseByNameOrDiscoveredName(cf, tc, routes)
if err != nil {
return nil, trace.Wrap(err)
}
info := &databaseInfo{
database: db,
RouteToDatabase: tlsca.RouteToDatabase{
ServiceName: db.GetName(),
Protocol: db.GetProtocol(),
},
}
// check for an active route now that we have the full db name.
if route, ok := findActiveDatabase(db.GetName(), routes); ok {
info.RouteToDatabase = route
info.isActive = true
}
if err := info.checkAndSetDefaults(cf, tc); err != nil {
return nil, trace.Wrap(err)
}
return info, nil
}
// checkAndSetDefaults checks the db route, applies cli flags, and sets defaults.
func (d *databaseInfo) checkAndSetDefaults(cf *CLIConf, tc *client.TeleportClient) error {
if d.ServiceName == "" {
return trace.BadParameter("missing database service name")
}
if cf.DatabaseUser != "" {
d.Username = cf.DatabaseUser
}
if cf.DatabaseName != "" {
d.Database = cf.DatabaseName
}
db, err := d.GetDatabase(cf.Context, tc)
if err != nil {
if d.isActive && trace.IsNotFound(err) && strings.Contains(err.Error(), d.ServiceName) {
hint := formatStaleDBCert(cf.SiteName, d.ServiceName)
return trace.Wrap(err, hint)
}
return trace.Wrap(err)
}
// ensure the route protocol matches the db.
d.Protocol = db.GetProtocol()
needDBUser := d.Username == "" && role.RequireDatabaseUserMatcher(d.Protocol)
needDBName := d.Database == "" && role.RequireDatabaseNameMatcher(d.Protocol)
if !needDBUser && !needDBName {
return nil
}
// If database has admin user defined, we're most likely using automatic
// user provisioning so default to Teleport username unless database
// username was provided explicitly.
if needDBUser && db.GetAdminUser().Name != "" {
log.Debugf("Defaulting to Teleport username %q as database username.", tc.Username)
d.Username = tc.Username
needDBUser = false
}
if !needDBUser && !needDBName {
return nil
}
var proxy *client.ProxyClient
err = client.RetryWithRelogin(cf.Context, tc, func() error {
proxy, err = tc.ConnectToProxy(cf.Context)
return trace.Wrap(err)
})
if err != nil {
return trace.Wrap(err)
}
defer proxy.Close()
profile, err := tc.ProfileStatus()
if err != nil {
return trace.Wrap(err)
}
checker, err := accessCheckerForRemoteCluster(cf.Context, profile, proxy, tc.SiteName)
if err != nil {
return trace.Wrap(err)
}
if needDBUser {
dbUser, err := getDefaultDBUser(db, checker)
if err != nil {
return trace.Wrap(err)
}
log.Debugf("Defaulting to the allowed database user %q\n", dbUser)
d.Username = dbUser
}
if needDBName {
dbName, err := getDefaultDBName(db, checker)
if err != nil {
return trace.Wrap(err)
}
log.Debugf("Defaulting to the allowed database name %q\n", dbName)
d.Database = dbName
}
return nil
}
// databaseInfo wraps a RouteToDatabase and the corresponding database.
// Its purpose is to prevent repeated fetches of the same database, by lazily
// fetching and caching the database for use as needed.
type databaseInfo struct {
tlsca.RouteToDatabase
// database corresponds to the db route and may be nil, so use GetDatabase
// instead of accessing it directly.
database types.Database
// isActive indicates an active database matched this db info.
isActive bool
mu sync.Mutex
}
// GetDatabase returns the cached database or fetches it using the db route and
// caches the result.
func (d *databaseInfo) GetDatabase(ctx context.Context, tc *client.TeleportClient) (types.Database, error) {
d.mu.Lock()
defer d.mu.Unlock()
if d.database != nil {
return d.database, nil
}
// holding mutex across the api call to avoid multiple redundant api calls.
database, err := getDatabase(ctx, tc, d.ServiceName)
if err != nil {
return nil, trace.Wrap(err)
}
d.database = database
return d.database, nil
}
// chooseOneDatabase is a helper func that returns either the only database in a
// list of databases or returns a database that matches the selector name
// or unambiguous discovered name exactly, otherwise an error.
func chooseOneDatabase(cf *CLIConf, databases types.Databases) (types.Database, error) {
selectors := newDatabaseResourceSelectors(cf)
// Check if the name matches any database exactly and, if so, choose
// that database over any others.
for _, db := range databases {
if db.GetName() == selectors.name {
log.Debugf("Selected database %q by exact name match", db.GetName())
return db, nil
}
}
// look for a single database with a matching discovered name label.
if dbs := findDatabasesByDiscoveredName(databases, selectors.name); len(dbs) > 0 {
names := make([]string, 0, len(dbs))
for _, db := range dbs {
names = append(names, db.GetName())
}
log.Debugf("Choosing amongst databases (%v) by discovered name", names)
databases = dbs
}
if len(databases) == 1 {
log.Debugf("Selected database %q", databases[0].GetName())
return databases[0], nil
}
// error - we need exactly one database.
if len(databases) == 0 {
return nil, trace.NotFound(
"%v not found, use '%v' to see registered databases", selectors,
formatDatabaseListCommand(cf.SiteName))
}
errMsg := formatAmbiguousDB(cf, selectors, databases)
return nil, trace.BadParameter(errMsg)
}
// findDatabasesByDiscoveredName returns all databases that have a discovered
// name label that matches the given name.
func findDatabasesByDiscoveredName(databases types.Databases, name string) types.Databases {
var out types.Databases
for _, db := range databases {
discoveredName, ok := db.GetLabel(types.DiscoveredNameLabel)
if ok && discoveredName == name {
out = append(out, db)
}
}
return out
}
// getDatabase gets a database using its full name.
func getDatabase(ctx context.Context, tc *client.TeleportClient, name string) (types.Database, error) {
matchName := makeNamePredicate(name)