-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
kube.go
1264 lines (1104 loc) · 40.1 KB
/
kube.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 main
import (
"context"
"fmt"
"io"
"net/url"
"os"
"sort"
"strconv"
"strings"
"time"
"github.com/ghodss/yaml"
"github.com/gravitational/kingpin"
"github.com/gravitational/trace"
dockerterm "github.com/moby/term"
"golang.org/x/exp/slices"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/cli-runtime/pkg/resource"
coreclient "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/pkg/apis/clientauthentication"
clientauthv1beta1 "k8s.io/client-go/pkg/apis/clientauthentication/v1beta1"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/tools/remotecommand"
cmdutil "k8s.io/kubectl/pkg/cmd/util"
"k8s.io/kubectl/pkg/cmd/util/podcmd"
"k8s.io/kubectl/pkg/polymorphichelpers"
"k8s.io/kubectl/pkg/scheme"
"k8s.io/kubectl/pkg/util/term"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/api/client/proto"
"github.com/gravitational/teleport/api/profile"
"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/api/utils/keypaths"
"github.com/gravitational/teleport/lib/asciitable"
"github.com/gravitational/teleport/lib/client"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/kube/kubeconfig"
kubeutils "github.com/gravitational/teleport/lib/kube/utils"
"github.com/gravitational/teleport/lib/tlsca"
"github.com/gravitational/teleport/lib/utils"
)
type kubeCommands struct {
credentials *kubeCredentialsCommand
ls *kubeLSCommand
login *kubeLoginCommand
sessions *kubeSessionsCommand
exec *kubeExecCommand
join *kubeJoinCommand
}
func newKubeCommand(app *kingpin.Application) kubeCommands {
kube := app.Command("kube", "Manage available Kubernetes clusters")
cmds := kubeCommands{
credentials: newKubeCredentialsCommand(kube),
ls: newKubeLSCommand(kube),
login: newKubeLoginCommand(kube),
sessions: newKubeSessionsCommand(kube),
exec: newKubeExecCommand(kube),
join: newKubeJoinCommand(kube),
}
return cmds
}
type kubeJoinCommand struct {
*kingpin.CmdClause
session string
mode string
siteName string
}
func newKubeJoinCommand(parent *kingpin.CmdClause) *kubeJoinCommand {
c := &kubeJoinCommand{
CmdClause: parent.Command("join", "Join an active Kubernetes session."),
}
c.Flag("mode", "Mode of joining the session, valid modes are observer and moderator").Short('m').Default("moderator").StringVar(&c.mode)
c.Flag("cluster", clusterHelp).Short('c').StringVar(&c.siteName)
c.Arg("session", "The ID of the target session.").Required().StringVar(&c.session)
return c
}
func (c *kubeJoinCommand) getSessionMeta(ctx context.Context, tc *client.TeleportClient) (types.SessionTracker, error) {
proxy, err := tc.ConnectToProxy(ctx)
if err != nil {
return nil, trace.Wrap(err)
}
site := proxy.CurrentCluster()
return site.GetSessionTracker(ctx, c.session)
}
func (c *kubeJoinCommand) run(cf *CLIConf) error {
if err := validateParticipantMode(types.SessionParticipantMode(c.mode)); err != nil {
return trace.Wrap(err)
}
cf.SiteName = c.siteName
tc, err := makeClient(cf, true)
if err != nil {
return trace.Wrap(err)
}
meta, err := c.getSessionMeta(cf.Context, tc)
if trace.IsNotFound(err) {
return trace.NotFound("Failed to find session %q. The ID may be incorrect.", c.session)
} else if err != nil {
return trace.Wrap(err)
}
cluster := meta.GetClusterName()
kubeCluster := meta.GetKubeCluster()
var k *client.Key
// Try loading existing keys.
k, err = tc.LocalAgent().GetKey(cluster, client.WithKubeCerts{})
if err != nil && !trace.IsNotFound(err) {
return trace.Wrap(err)
}
// Loaded existing credentials and have a cert for this cluster? Return it
// right away.
if err == nil {
crt, err := k.KubeTLSCertificate(kubeCluster)
if err != nil && !trace.IsNotFound(err) {
return trace.Wrap(err)
}
if crt != nil && time.Until(crt.NotAfter) > time.Minute {
log.Debugf("Re-using existing TLS cert for kubernetes cluster %q", kubeCluster)
} else {
err = client.RetryWithRelogin(cf.Context, tc, func() error {
var err error
k, err = tc.IssueUserCertsWithMFA(cf.Context, client.ReissueParams{
RouteToCluster: cluster,
KubernetesCluster: kubeCluster,
}, nil /*applyOpts*/)
return trace.Wrap(err)
})
if err != nil {
return trace.Wrap(err)
}
// Cache the new cert on disk for reuse.
if err := tc.LocalAgent().AddKubeKey(k); err != nil {
return trace.Wrap(err)
}
}
// Otherwise, cert for this k8s cluster is missing or expired. Request
// a new one.
}
if _, err := tc.Ping(cf.Context); err != nil {
return trace.Wrap(err)
}
if tc.KubeProxyAddr == "" {
// Kubernetes support disabled, don't touch kubeconfig.
return trace.AccessDenied("this cluster does not support Kubernetes")
}
kubeStatus, err := fetchKubeStatus(cf.Context, tc)
if err != nil {
return trace.Wrap(err)
}
ciphers := utils.DefaultCipherSuites()
tlsConfig, err := k.KubeClientTLSConfig(ciphers, kubeCluster)
if err != nil {
return trace.Wrap(err)
}
tlsConfig.InsecureSkipVerify = cf.InsecureSkipVerify
session, err := client.NewKubeSession(cf.Context, tc, meta, tc.KubeProxyAddr, kubeStatus.tlsServerName, types.SessionParticipantMode(c.mode), tlsConfig)
if err != nil {
return trace.Wrap(err)
}
session.Wait()
return trace.Wrap(session.Detach())
}
// RemoteExecutor defines the interface accepted by the Exec command - provided for test stubbing
type RemoteExecutor interface {
Execute(ctx context.Context, method string, url *url.URL, config *restclient.Config, stdin io.Reader, stdout, stderr io.Writer, tty bool, terminalSizeQueue remotecommand.TerminalSizeQueue) error
}
// DefaultRemoteExecutor is the standard implementation of remote command execution
type DefaultRemoteExecutor struct{}
func (*DefaultRemoteExecutor) Execute(ctx context.Context, method string, url *url.URL, config *restclient.Config, stdin io.Reader, stdout, stderr io.Writer, tty bool, terminalSizeQueue remotecommand.TerminalSizeQueue) error {
exec, err := remotecommand.NewSPDYExecutor(config, method, url)
if err != nil {
return err
}
return exec.StreamWithContext(ctx, remotecommand.StreamOptions{
Stdin: stdin,
Stdout: stdout,
Stderr: stderr,
Tty: tty,
TerminalSizeQueue: terminalSizeQueue,
})
}
type StreamOptions struct {
Namespace string
PodName string
ContainerName string
Stdin bool
TTY bool
// minimize unnecessary output
Quiet bool
genericclioptions.IOStreams
overrideStreams func() (io.ReadCloser, io.Writer, io.Writer)
isTerminalIn func(t term.TTY) bool
}
func (o *StreamOptions) SetupTTY() term.TTY {
t := term.TTY{
Out: o.Out,
}
if !o.Stdin {
// need to nil out o.In to make sure we don't create a stream for stdin
o.In = nil
o.TTY = false
return t
}
t.In = o.In
if !o.TTY {
return t
}
if o.isTerminalIn == nil {
o.isTerminalIn = func(tty term.TTY) bool {
return tty.IsTerminalIn()
}
}
if !o.isTerminalIn(t) {
o.TTY = false
if !o.Quiet && o.ErrOut != nil {
fmt.Fprintln(o.ErrOut, "Unable to use a TTY - input is not a terminal or the right kind of file")
}
return t
}
// if we get to here, the user wants to attach stdin, wants a TTY, and o.In is a terminal, so we
// can safely set t.Raw to true
t.Raw = true
if o.overrideStreams == nil {
// use dockerterm.StdStreams() to get the right I/O handles on Windows
o.overrideStreams = dockerterm.StdStreams
}
stdin, stdout, _ := o.overrideStreams()
o.In = stdin
t.In = stdin
if o.Out != nil {
o.Out = stdout
t.Out = stdout
}
return t
}
type ExecOptions struct {
StreamOptions
resource.FilenameOptions
ResourceName string
Command []string
EnforceNamespace bool
Builder func() *resource.Builder
ExecutablePodFn polymorphichelpers.AttachablePodForObjectFunc
restClientGetter genericclioptions.RESTClientGetter
Pod *corev1.Pod
Executor RemoteExecutor
PodClient coreclient.PodsGetter
GetPodTimeout time.Duration
Config *restclient.Config
displayParticipantRequirements bool
}
// Run executes a validated remote execution against a pod.
func (p *ExecOptions) Run(ctx context.Context) error {
var err error
if len(p.PodName) != 0 {
p.Pod, err = p.PodClient.Pods(p.Namespace).Get(ctx, p.PodName, metav1.GetOptions{})
if err != nil {
return err
}
} else {
builder := p.Builder().
WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
FilenameParam(p.EnforceNamespace, &p.FilenameOptions).
NamespaceParam(p.Namespace).DefaultNamespace()
if len(p.ResourceName) > 0 {
builder = builder.ResourceNames("pods", p.ResourceName)
}
obj, err := builder.Do().Object()
if err != nil {
return err
}
p.Pod, err = p.ExecutablePodFn(p.restClientGetter, obj, p.GetPodTimeout)
if err != nil {
return err
}
}
pod := p.Pod
if pod.Status.Phase == corev1.PodSucceeded || pod.Status.Phase == corev1.PodFailed {
return fmt.Errorf("cannot exec into a container in a completed pod; current phase is %s", pod.Status.Phase)
}
containerName := p.ContainerName
if len(containerName) == 0 {
container, err := podcmd.FindOrDefaultContainerByName(pod, containerName, p.Quiet, p.ErrOut)
if err != nil {
return err
}
containerName = container.Name
}
// ensure we can recover the terminal while attached
t := p.SetupTTY()
var sizeQueue remotecommand.TerminalSizeQueue
if t.Raw {
// this call spawns a goroutine to monitor/update the terminal size
sizeQueue = t.MonitorSize(t.GetSize())
// unset p.Err if it was previously set because both stdout and stderr go over p.Out when tty is
// true
p.ErrOut = nil
}
fn := func() error {
restClient, err := restclient.RESTClientFor(p.Config)
if err != nil {
return err
}
req := restClient.Post().
Resource("pods").
Name(pod.Name).
Namespace(pod.Namespace).
SubResource("exec").
Param("displayParticipantRequirements", strconv.FormatBool(p.displayParticipantRequirements))
req.VersionedParams(&corev1.PodExecOptions{
Container: containerName,
Command: p.Command,
Stdin: p.Stdin,
Stdout: p.Out != nil,
Stderr: p.ErrOut != nil,
TTY: t.Raw,
}, scheme.ParameterCodec)
return p.Executor.Execute(ctx, "POST", req.URL(), p.Config, p.In, p.Out, p.ErrOut, t.Raw, sizeQueue)
}
return trace.Wrap(t.Safe(fn))
}
type kubeExecCommand struct {
*kingpin.CmdClause
target string
container string
filename string
quiet bool
stdin bool
tty bool
reason string
invited string
command []string
displayParticipantRequirements bool
}
func newKubeExecCommand(parent *kingpin.CmdClause) *kubeExecCommand {
c := &kubeExecCommand{
CmdClause: parent.Command("exec", "Execute a command in a Kubernetes pod"),
}
c.Flag("container", "Container name. If omitted, use the kubectl.kubernetes.io/default-container annotation for selecting the container to be attached or the first container in the pod will be chosen").Short('c').StringVar(&c.container)
c.Flag("filename", "to use to exec into the resource").Short('f').StringVar(&c.filename)
c.Flag("quiet", "Only print output from the remote session").Short('q').BoolVar(&c.quiet)
c.Flag("stdin", "Pass stdin to the container").Short('s').BoolVar(&c.stdin)
c.Flag("tty", "Stdin is a TTY").Short('t').BoolVar(&c.tty)
c.Flag("reason", "The purpose of the session.").StringVar(&c.reason)
c.Flag("invite", "A comma separated list of people to mark as invited for the session.").StringVar(&c.invited)
c.Flag("participant-req", "Displays a verbose list of required participants in a moderated session.").BoolVar(&c.displayParticipantRequirements)
c.Arg("target", "Pod or deployment name").Required().StringVar(&c.target)
c.Arg("command", "Command to execute in the container").Required().StringsVar(&c.command)
return c
}
func (c *kubeExecCommand) run(cf *CLIConf) error {
var p ExecOptions
var err error
p.IOStreams = genericclioptions.IOStreams{
In: os.Stdin,
Out: os.Stdout,
ErrOut: os.Stderr,
}
kubeConfigFlags := genericclioptions.NewConfigFlags(true).WithDeprecatedPasswordFlag()
matchVersionKubeConfigFlags := cmdutil.NewMatchVersionFlags(kubeConfigFlags)
f := cmdutil.NewFactory(matchVersionKubeConfigFlags)
p.ResourceName = c.target
p.ContainerName = c.container
p.Quiet = c.quiet
p.Stdin = c.stdin
p.TTY = c.tty
p.Command = c.command
p.ExecutablePodFn = polymorphichelpers.AttachablePodForObjectFn
p.GetPodTimeout = time.Second * 5
p.Builder = f.NewBuilder
p.restClientGetter = f
p.Executor = &DefaultRemoteExecutor{}
p.displayParticipantRequirements = c.displayParticipantRequirements
p.Namespace, p.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()
if err != nil {
return trace.Wrap(err)
}
p.Config, err = f.ToRESTConfig()
if err != nil {
return trace.Wrap(err)
}
clientset, err := f.KubernetesClientSet()
if err != nil {
return trace.Wrap(err)
}
p.PodClient = clientset.CoreV1()
return trace.Wrap(p.Run(cf.Context))
}
type kubeSessionsCommand struct {
*kingpin.CmdClause
format string
siteName string
}
func newKubeSessionsCommand(parent *kingpin.CmdClause) *kubeSessionsCommand {
c := &kubeSessionsCommand{
CmdClause: parent.Command("sessions", "Get a list of active Kubernetes sessions."),
}
c.Flag("format", defaults.FormatFlagDescription(defaults.DefaultFormats...)).Short('f').Default(teleport.Text).EnumVar(&c.format, defaults.DefaultFormats...)
c.Flag("cluster", clusterHelp).Short('c').StringVar(&c.siteName)
return c
}
func (c *kubeSessionsCommand) run(cf *CLIConf) error {
if c.siteName != "" {
cf.SiteName = c.siteName
}
tc, err := makeClient(cf, true)
if err != nil {
return trace.Wrap(err)
}
proxy, err := tc.ConnectToProxy(cf.Context)
if err != nil {
return trace.Wrap(err)
}
site := proxy.CurrentCluster()
sessions, err := site.GetActiveSessionTrackers(cf.Context)
if err != nil {
return trace.Wrap(err)
}
filteredSessions := make([]types.SessionTracker, 0)
for _, session := range sessions {
if session.GetSessionKind() == types.KubernetesSessionKind {
filteredSessions = append(filteredSessions, session)
}
}
sort.Slice(filteredSessions, func(i, j int) bool {
return filteredSessions[i].GetCreated().Before(filteredSessions[j].GetCreated())
})
format := strings.ToLower(c.format)
switch format {
case teleport.Text, "":
printSessions(cf.Stdout(), filteredSessions)
case teleport.JSON, teleport.YAML:
out, err := serializeKubeSessions(sessions, format)
if err != nil {
return trace.Wrap(err)
}
fmt.Fprintln(cf.Stdout(), out)
default:
return trace.BadParameter("unsupported format %q", c.format)
}
return nil
}
func serializeKubeSessions(sessions []types.SessionTracker, format string) (string, error) {
var out []byte
var err error
if format == teleport.JSON {
out, err = utils.FastMarshalIndent(sessions, "", " ")
} else {
out, err = yaml.Marshal(sessions)
}
return string(out), trace.Wrap(err)
}
func printSessions(output io.Writer, sessions []types.SessionTracker) {
table := asciitable.MakeTable([]string{"ID", "State", "Created", "Hostname", "Address", "Login", "Reason"})
for _, s := range sessions {
table.AddRow([]string{s.GetSessionID(), s.GetState().String(), s.GetCreated().Format(time.RFC3339), s.GetHostname(), s.GetAddress(), s.GetLogin(), s.GetReason()})
}
tableOutput := table.AsBuffer().String()
fmt.Fprintln(output, tableOutput)
}
type kubeCredentialsCommand struct {
*kingpin.CmdClause
kubeCluster string
teleportCluster string
}
func newKubeCredentialsCommand(parent *kingpin.CmdClause) *kubeCredentialsCommand {
c := &kubeCredentialsCommand{
// This command is always hidden. It's called from the kubeconfig that
// tsh generates and never by users directly.
CmdClause: parent.Command("credentials", "Get credentials for kubectl access").Hidden(),
}
c.Flag("teleport-cluster", "Name of the teleport cluster to get credentials for.").Required().StringVar(&c.teleportCluster)
c.Flag("kube-cluster", "Name of the Kubernetes cluster to get credentials for.").Required().StringVar(&c.kubeCluster)
return c
}
func (c *kubeCredentialsCommand) run(cf *CLIConf) error {
// client.LoadKeysToKubeFromStore function is used to speed up the credentials
// loading process since Teleport Store transverses the entire store to find the keys.
// This operation takes a long time when the store has a lot of keys and when
// we call the function multiple times in parallel.
// Although client.LoadKeysToKubeFromStore function speeds up the process since
// it removes all transversals, it still has to read 3 different files from the disk:
// - $TSH_HOME/$profile.yaml
// - $TSH_HOME/keys/$PROXY/$USER-kube/$TELEPORT_CLUSTER/$KUBE_CLUSTER-x509.pem
// - $TSH_HOME/keys/$PROXY/$USER
if kubeCert, privKey, err := client.LoadKeysToKubeFromStore(
cf.HomePath,
cf.Proxy,
c.teleportCluster,
c.kubeCluster,
); err == nil {
crt, _ := tlsca.ParseCertificatePEM(kubeCert)
if crt != nil && time.Until(crt.NotAfter) > time.Minute {
log.Debugf("Re-using existing TLS cert for Kubernetes cluster %q", c.kubeCluster)
return c.writeByteResponse(cf.Stdout(), kubeCert, privKey, crt.NotAfter)
}
}
tc, err := makeClient(cf, true)
if err != nil {
return trace.Wrap(err)
}
_, span := tc.Tracer.Start(cf.Context, "tsh.kubeCredentials/GetKey")
// Try loading existing keys.
k, err := tc.LocalAgent().GetKey(c.teleportCluster, client.WithKubeCerts{})
span.End()
if err != nil && !trace.IsNotFound(err) {
return trace.Wrap(err)
}
// Loaded existing credentials and have a cert for this cluster? Return it
// right away.
if err == nil {
_, span := tc.Tracer.Start(cf.Context, "tsh.kubeCredentials/KubeTLSCertificate")
crt, err := k.KubeTLSCertificate(c.kubeCluster)
span.End()
if err != nil && !trace.IsNotFound(err) {
return trace.Wrap(err)
}
if crt != nil && time.Until(crt.NotAfter) > time.Minute {
log.Debugf("Re-using existing TLS cert for Kubernetes cluster %q", c.kubeCluster)
return c.writeKeyResponse(cf.Stdout(), k, c.kubeCluster)
}
// Otherwise, cert for this k8s cluster is missing or expired. Request
// a new one.
}
log.Debugf("Requesting TLS cert for Kubernetes cluster %q", c.kubeCluster)
ctx, span := tc.Tracer.Start(cf.Context, "tsh.kubeCredentials/RetryWithRelogin")
err = client.RetryWithRelogin(ctx, tc, func() error {
var err error
k, err = tc.IssueUserCertsWithMFA(ctx, client.ReissueParams{
RouteToCluster: c.teleportCluster,
KubernetesCluster: c.kubeCluster,
}, nil /*applyOpts*/)
return err
})
span.End()
if err != nil {
return trace.Wrap(err)
}
// Make sure the cert is allowed to access the cluster.
// At this point we already know that the user has access to the cluster
// via the RBAC rules, but we also need to make sure that the user has
// access to the cluster with at least one kubernetes_user or kubernetes_group
// defined.
if err := checkIfCertsAreAllowedToAccessCluster(k, c.kubeCluster); err != nil {
return trace.Wrap(err)
}
// Cache the new cert on disk for reuse.
if err := tc.LocalAgent().AddKubeKey(k); err != nil {
return trace.Wrap(err)
}
return c.writeKeyResponse(cf.Stdout(), k, c.kubeCluster)
}
// checkIfCertsAreAllowedToAccessCluster evaluates if the new cert created by the user
// to access kubeCluster has at least one kubernetes_user or kubernetes_group
// defined. If not, it returns an error.
// This is a safety check in order to print a better message to the user even
// before hitting Teleport Kubernetes Proxy.
func checkIfCertsAreAllowedToAccessCluster(k *client.Key, kubeCluster string) error {
for k8sCluster, cert := range k.KubeTLSCerts {
if k8sCluster != kubeCluster {
continue
}
log.Debugf("Got TLS cert for Kubernetes cluster %q", k8sCluster)
exist, err := checkIfCertHasKubeGroupsAndUsers(cert)
if err != nil {
return trace.Wrap(err)
} else if exist {
return nil
}
}
errMsg := "Your user's Teleport role does not allow Kubernetes access." +
" Please ask cluster administrator to ensure your role has appropriate kubernetes_groups and kubernetes_users set."
return trace.AccessDenied(errMsg)
}
// checkIfCertHasKubeGroupsAndUsers checks if the certificate has Kubernetes groups or users
// in the Subject Name. If it does, it returns true, otherwise false.
// Having no Kubernetes groups or users in the certificate means that the user
// is not allowed to access the Kubernetes cluster since Kubernetes Access enforces
// the presence of at least one of Kubernetes groups or users in the certificate.
// If the certificate does not have any Kubernetes groups or users, the
func checkIfCertHasKubeGroupsAndUsers(certB []byte) (bool, error) {
cert, err := tlsca.ParseCertificatePEM(certB)
if err != nil {
return false, trace.Wrap(err)
}
for _, name := range cert.Subject.Names {
if name.Type.Equal(tlsca.KubeGroupsASN1ExtensionOID) || name.Type.Equal(tlsca.KubeUsersASN1ExtensionOID) {
return true, nil
}
}
return false, nil
}
func (c *kubeCredentialsCommand) writeKeyResponse(output io.Writer, key *client.Key, kubeClusterName string) error {
crt, err := key.KubeTLSCertificate(kubeClusterName)
if err != nil {
return trace.Wrap(err)
}
expiry := crt.NotAfter
// Indicate slightly earlier expiration to avoid the cert expiring
// mid-request, if possible.
if time.Until(expiry) > time.Minute {
expiry = expiry.Add(-1 * time.Minute)
}
// TODO (Joerger): Create a custom k8s Auth Provider or Exec Provider to use non-rsa
// private keys for kube credentials (if possible)
rsaKeyPEM, err := key.PrivateKey.RSAPrivateKeyPEM()
if err != nil {
return trace.Wrap(err)
}
return trace.Wrap(c.writeResponse(output, key.KubeTLSCerts[kubeClusterName], rsaKeyPEM, expiry))
}
// writeByteResponse writes the exec credential response to the output stream.
func (c *kubeCredentialsCommand) writeByteResponse(output io.Writer, kubeTLSCert, rsaKeyPEM []byte, expiry time.Time) error {
// Indicate slightly earlier expiration to avoid the cert expiring
// mid-request, if possible.
if time.Until(expiry) > time.Minute {
expiry = expiry.Add(-1 * time.Minute)
}
return trace.Wrap(c.writeResponse(output, kubeTLSCert, rsaKeyPEM, expiry))
}
// writeResponse writes the exec credential response to the output stream.
func (c *kubeCredentialsCommand) writeResponse(output io.Writer, kubeTLSCert, rsaKeyPEM []byte, expiry time.Time) error {
resp := &clientauthentication.ExecCredential{
Status: &clientauthentication.ExecCredentialStatus{
ExpirationTimestamp: &metav1.Time{Time: expiry},
ClientCertificateData: string(kubeTLSCert),
ClientKeyData: string(rsaKeyPEM),
},
}
data, err := runtime.Encode(kubeCodecs.LegacyCodec(kubeGroupVersion), resp)
if err != nil {
return trace.Wrap(err)
}
fmt.Fprintln(output, string(data))
return nil
}
type kubeLSCommand struct {
*kingpin.CmdClause
labels string
predicateExpr string
searchKeywords string
format string
listAll bool
siteName string
verbose bool
quiet bool
}
func newKubeLSCommand(parent *kingpin.CmdClause) *kubeLSCommand {
c := &kubeLSCommand{
CmdClause: parent.Command("ls", "Get a list of Kubernetes clusters"),
}
c.Flag("cluster", clusterHelp).Short('c').StringVar(&c.siteName)
c.Flag("search", searchHelp).StringVar(&c.searchKeywords)
c.Flag("query", queryHelp).StringVar(&c.predicateExpr)
c.Flag("format", defaults.FormatFlagDescription(defaults.DefaultFormats...)).Short('f').Default(teleport.Text).EnumVar(&c.format, defaults.DefaultFormats...)
c.Flag("all", "List Kubernetes clusters from all clusters and proxies.").Short('R').BoolVar(&c.listAll)
c.Arg("labels", labelHelp).StringVar(&c.labels)
c.Flag("verbose", "Show an untruncated list of labels.").Short('v').BoolVar(&c.verbose)
c.Flag("quiet", "Quiet mode.").Short('q').BoolVar(&c.quiet)
return c
}
type kubeListing struct {
Proxy string `json:"proxy"`
Cluster string `json:"cluster"`
KubeCluster types.KubeCluster `json:"kube_cluster"`
}
type kubeListings []kubeListing
func (l kubeListings) Len() int {
return len(l)
}
func (l kubeListings) 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].KubeCluster.GetName() < l[j].KubeCluster.GetName()
}
func (l kubeListings) Swap(i, j int) {
l[i], l[j] = l[j], l[i]
}
func formatKubeLabels(cluster types.KubeCluster) string {
labels := make([]string, 0, len(cluster.GetStaticLabels())+len(cluster.GetDynamicLabels()))
for key, value := range cluster.GetStaticLabels() {
labels = append(labels, fmt.Sprintf("%s=%s", key, value))
}
for key, value := range cluster.GetDynamicLabels() {
labels = append(labels, fmt.Sprintf("%s=%s", key, value.GetResult()))
}
sort.Strings(labels)
return strings.Join(labels, " ")
}
func (c *kubeLSCommand) run(cf *CLIConf) error {
cf.SearchKeywords = c.searchKeywords
cf.UserHost = c.labels
cf.PredicateExpression = c.predicateExpr
cf.SiteName = c.siteName
if c.listAll {
return trace.Wrap(c.runAllClusters(cf))
}
tc, err := makeClient(cf, true)
if err != nil {
return trace.Wrap(err)
}
currentTeleportCluster, kubeClusters, err := fetchKubeClusters(cf.Context, tc)
if err != nil {
return trace.Wrap(err)
}
selectedCluster := selectedKubeCluster(currentTeleportCluster)
format := strings.ToLower(c.format)
switch format {
case teleport.Text, "":
var (
t asciitable.Table
columns = []string{"Kube Cluster Name", "Labels", "Selected"}
rows [][]string
)
for _, cluster := range kubeClusters {
var selectedMark string
if cluster.GetName() == selectedCluster {
selectedMark = "*"
}
rows = append(rows, []string{cluster.GetName(), formatKubeLabels(cluster), selectedMark})
}
if c.quiet {
t = asciitable.MakeHeadlessTable(2)
for _, row := range rows {
t.AddRow(row[:2])
}
} else if c.verbose {
t = asciitable.MakeTable(columns, rows...)
} else {
t = asciitable.MakeTableWithTruncatedColumn(columns, rows, "Labels")
}
fmt.Fprintln(cf.Stdout(), t.AsBuffer().String())
case teleport.JSON, teleport.YAML:
out, err := serializeKubeClusters(kubeClusters, selectedCluster, format)
if err != nil {
return trace.Wrap(err)
}
fmt.Fprintln(cf.Stdout(), out)
default:
return trace.BadParameter("unsupported format %q", cf.Format)
}
return nil
}
func serializeKubeClusters(kubeClusters []types.KubeCluster, selectedCluster, format string) (string, error) {
type cluster struct {
KubeClusterName string `json:"kube_cluster_name"`
Labels map[string]string `json:"labels"`
Selected bool `json:"selected"`
}
clusterInfo := make([]cluster, 0, len(kubeClusters))
for _, cl := range kubeClusters {
labels := cl.GetStaticLabels()
for key, value := range cl.GetDynamicLabels() {
labels[key] = value.GetResult()
}
clusterInfo = append(clusterInfo, cluster{
KubeClusterName: cl.GetName(),
Labels: labels,
Selected: cl.GetName() == selectedCluster,
})
}
var out []byte
var err error
if format == teleport.JSON {
out, err = utils.FastMarshalIndent(clusterInfo, "", " ")
} else {
out, err = yaml.Marshal(clusterInfo)
}
return string(out), trace.Wrap(err)
}
func (c *kubeLSCommand) runAllClusters(cf *CLIConf) error {
var listings kubeListings
err := forEachProfile(cf, func(tc *client.TeleportClient, profile *client.ProfileStatus) error {
req := proto.ListResourcesRequest{
SearchKeywords: tc.SearchKeywords,
PredicateExpression: tc.PredicateExpression,
Labels: tc.Labels,
}
kubeClusters, err := tc.ListKubernetesClustersWithFiltersAllClusters(cf.Context, req)
if err != nil {
return trace.Wrap(err)
}
for clusterName, kubeClusters := range kubeClusters {
for _, kc := range kubeClusters {
listings = append(listings, kubeListing{
Proxy: profile.ProxyURL.Host,
Cluster: clusterName,
KubeCluster: kc,
})
}
}
return nil
})
if err != nil {
return trace.Wrap(err)
}
sort.Sort(listings)
format := strings.ToLower(c.format)
switch format {
case teleport.Text, "":
var t asciitable.Table
if cf.Quiet {
t = asciitable.MakeHeadlessTable(3)
} else {
t = asciitable.MakeTable([]string{"Proxy", "Cluster", "Kube Cluster Name", "Labels"})
}
for _, listing := range listings {
t.AddRow([]string{listing.Proxy, listing.Cluster, listing.KubeCluster.GetName(), formatKubeLabels(listing.KubeCluster)})
}
fmt.Fprintln(cf.Stdout(), t.AsBuffer().String())
case teleport.JSON, teleport.YAML:
out, err := serializeKubeListings(listings, format)
if err != nil {
return trace.Wrap(err)
}
fmt.Fprintln(cf.Stdout(), out)
default:
return trace.BadParameter("Unrecognized format %q", c.format)
}
return nil
}
func serializeKubeListings(kubeListings []kubeListing, format string) (string, error) {
var out []byte
var err error
if format == teleport.JSON {
out, err = utils.FastMarshalIndent(kubeListings, "", " ")
} else {
out, err = yaml.Marshal(kubeListings)
}
return string(out), trace.Wrap(err)
}
func selectedKubeCluster(currentTeleportCluster string) string {
kc, err := kubeconfig.Load("")
if err != nil {
log.WithError(err).Warning("Failed parsing existing kubeconfig")
return ""
}
return kubeconfig.KubeClusterFromContext(kc.CurrentContext, currentTeleportCluster)
}
type kubeLoginCommand struct {
*kingpin.CmdClause
kubeCluster string
siteName string
impersonateUser string
impersonateGroups []string
namespace string
all bool
overrideContextName string
}
func newKubeLoginCommand(parent *kingpin.CmdClause) *kubeLoginCommand {
c := &kubeLoginCommand{
CmdClause: parent.Command("login", "Login to a Kubernetes cluster"),
}
c.Flag("cluster", clusterHelp).Short('c').StringVar(&c.siteName)
c.Arg("kube-cluster", "Name of the Kubernetes cluster to login to. Check 'tsh kube ls' for a list of available clusters.").StringVar(&c.kubeCluster)