/
kubernetes.go
750 lines (667 loc) · 26.8 KB
/
kubernetes.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
/*
Copyright 2022 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 azure
import (
"context"
"fmt"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
armazcore "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v2"
"github.com/golang-jwt/jwt/v4"
"github.com/gravitational/trace"
"github.com/sirupsen/logrus"
v1 "k8s.io/api/rbac/v1"
kubeerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/kubernetes"
authztypes "k8s.io/client-go/kubernetes/typed/authorization/v1"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
// AKSAuthMethod defines the authentication method for AKS cluster.
type AKSAuthMethod uint8
const (
// AzureRBAC indicates that the Azure AD is enabled and authorization is handled by Azure RBAC.
AzureRBAC AKSAuthMethod = iota
// AzureAD indicates that the Azure AD is enabled but authorization is handled by Kubernetes RBAC.
AzureAD
// LocalAccounts indicates that the cluster access happens through Local accounts created
// during provisioning phase.
LocalAccounts
)
// AKSCluster represents an AKS cluster.
type AKSCluster struct {
// Name is the name of the cluster.
Name string
// GroupName is the resource group name.
GroupName string
// TenantID is the cluster TenantID.
TenantID string
// Location is the cluster region.
Location string
// SubscriptionID is the cluster subscription id.
SubscriptionID string
// Tags are the cluster tags.
Tags map[string]string
// Properties are the cluster authentication and authorization properties.
Properties AKSClusterProperties
}
// AKSClusterProperties holds the AZ cluster authentication properties.
type AKSClusterProperties struct {
// AccessConfig indicates the authentication & authorization config to use with the cluster.
AccessConfig AKSAuthMethod
// LocalAccounts indicates if the cluster has local accounts.
LocalAccounts bool
}
// ARMAKS is an interface for armcontainerservice.ManagedClustersClient.
type ARMAKS interface {
BeginRunCommand(ctx context.Context, resourceGroupName string, resourceName string, requestPayload armcontainerservice.RunCommandRequest, options *armcontainerservice.ManagedClustersClientBeginRunCommandOptions) (*runtime.Poller[armcontainerservice.ManagedClustersClientRunCommandResponse], error)
Get(ctx context.Context, resourceGroupName string, resourceName string, options *armcontainerservice.ManagedClustersClientGetOptions) (armcontainerservice.ManagedClustersClientGetResponse, error)
GetCommandResult(ctx context.Context, resourceGroupName string, resourceName string, commandID string, options *armcontainerservice.ManagedClustersClientGetCommandResultOptions) (armcontainerservice.ManagedClustersClientGetCommandResultResponse, error)
ListClusterAdminCredentials(ctx context.Context, resourceGroupName string, resourceName string, options *armcontainerservice.ManagedClustersClientListClusterAdminCredentialsOptions) (armcontainerservice.ManagedClustersClientListClusterAdminCredentialsResponse, error)
ListClusterUserCredentials(ctx context.Context, resourceGroupName string, resourceName string, options *armcontainerservice.ManagedClustersClientListClusterUserCredentialsOptions) (armcontainerservice.ManagedClustersClientListClusterUserCredentialsResponse, error)
NewListByResourceGroupPager(resourceGroupName string, options *armcontainerservice.ManagedClustersClientListByResourceGroupOptions) *runtime.Pager[armcontainerservice.ManagedClustersClientListByResourceGroupResponse]
NewListPager(options *armcontainerservice.ManagedClustersClientListOptions) *runtime.Pager[armcontainerservice.ManagedClustersClientListResponse]
}
var _ ARMAKS = (*armcontainerservice.ManagedClustersClient)(nil)
// ImpersonationPermissionsChecker describes a function that can be used to check
// for the required impersonation permissions on a Kubernetes cluster. Return nil
// to indicate success.
type ImpersonationPermissionsChecker func(ctx context.Context, clusterName string,
sarClient authztypes.SelfSubjectAccessReviewInterface) error
// azureIdentityFunction is a function signature used to setup azure credentials.
// This is used to generate special credentials with cluster TentantID to retrieve
// access tokens.
type azureIdentityFunction func(options *azidentity.DefaultAzureCredentialOptions) (GetToken, error)
// GetToken is an interface for generating tokens from credentials.
type GetToken interface {
// GetToken returns an azure token.
GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error)
}
// ClusterCredentialsConfig are the required parameters for generating cluster credentials.
type ClusterCredentialsConfig struct {
// ResourceGroup is the AKS cluster resource group.
ResourceGroup string
// ResourceName is the AKS cluster name.
ResourceName string
// TenantID is the AKS cluster tenant id.
TenantID string
// ImpersonationPermissionsChecker is checker function that validates if access
// was granted.
ImpersonationPermissionsChecker ImpersonationPermissionsChecker
}
// CheckAndSetDefaults checks for required parameters.
func (c ClusterCredentialsConfig) CheckAndSetDefaults() error {
if len(c.ResourceGroup) == 0 {
return trace.BadParameter("invalid ResourceGroup field")
}
if len(c.ResourceName) == 0 {
return trace.BadParameter("invalid ResourceName field")
}
if c.ImpersonationPermissionsChecker == nil {
return trace.BadParameter("invalid ImpersonationPermissionsChecker field")
}
return nil
}
// AKSClient is the Azure client to interact with AKS.
type AKSClient interface {
// ListAll returns all AKSClusters the user has access to.
ListAll(ctx context.Context) ([]*AKSCluster, error)
// ListAll returns all AKSClusters the user has access to within the resource group.
ListWithinGroup(ctx context.Context, group string) ([]*AKSCluster, error)
// ClusterCredentials returns the credentials for accessing the desired AKS cluster.
// If agent access has not yet been configured, this function will attempt to configure it
// using administrator credentials `ListClusterAdminCredentials`` or by running a command `BeginRunCommand`.
// If the access setup is not successful, then an error is returned.
ClusterCredentials(ctx context.Context, cfg ClusterCredentialsConfig) (*rest.Config, time.Time, error)
}
// aksClient wraps the ARMAKS API and satisfies AKSClient.
type aksClient struct {
api ARMAKS
azIdentity azureIdentityFunction
}
// NewAKSClustersClient returns a client for Azure AKS clusters.
func NewAKSClustersClient(api ARMAKS, azIdentity azureIdentityFunction) AKSClient {
if azIdentity == nil {
azIdentity = func(options *azidentity.DefaultAzureCredentialOptions) (GetToken, error) {
cc, err := azidentity.NewDefaultAzureCredential(options)
return cc, err
}
}
return &aksClient{api: api, azIdentity: azIdentity}
}
// get returns AKSCluster information for a single AKS cluster.
func (c *aksClient) get(ctx context.Context, group, name string) (*AKSCluster, error) {
res, err := c.api.Get(ctx, group, name, nil)
if err != nil {
return nil, trace.Wrap(ConvertResponseError(err))
}
cluster, err := AKSClusterFromManagedCluster(&res.ManagedCluster)
return cluster, trace.Wrap(err)
}
func (c *aksClient) ListAll(ctx context.Context) ([]*AKSCluster, error) {
var servers []*AKSCluster
options := &armcontainerservice.ManagedClustersClientListOptions{}
pager := c.api.NewListPager(options)
for pager.More() {
page, err := pager.NextPage(ctx)
if err != nil {
return nil, trace.Wrap(ConvertResponseError(err))
}
for _, s := range page.Value {
cluster, err := AKSClusterFromManagedCluster(s)
if err != nil {
logrus.WithError(err).Debugf("Failed to convert discovered AKS cluster %q to Teleport internal representation.", StringVal(s.Name))
continue
}
servers = append(servers, cluster)
}
}
return servers, nil
}
func (c *aksClient) ListWithinGroup(ctx context.Context, group string) ([]*AKSCluster, error) {
var servers []*AKSCluster
options := &armcontainerservice.ManagedClustersClientListByResourceGroupOptions{}
pager := c.api.NewListByResourceGroupPager(group, options)
for pager.More() {
page, err := pager.NextPage(ctx)
if err != nil {
return nil, trace.Wrap(ConvertResponseError(err))
}
for _, s := range page.Value {
cluster, err := AKSClusterFromManagedCluster(s)
if err != nil {
logrus.WithError(err).Debugf("Failed to convert discovered AKS cluster %q to Teleport internal representation.", StringVal(s.Name))
continue
}
servers = append(servers, cluster)
}
}
return servers, nil
}
type ClientConfig struct {
ResourceGroup string
Name string
TenantID string
}
func (c *aksClient) ClusterCredentials(ctx context.Context, cfg ClusterCredentialsConfig) (*rest.Config, time.Time, error) {
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, time.Time{}, trace.Wrap(err)
}
// get cluster auth information
clusterDetails, err := c.get(ctx, cfg.ResourceGroup, cfg.ResourceName)
if err != nil {
return nil, time.Time{}, trace.Wrap(ConvertResponseError(err))
}
switch clusterDetails.Properties.AccessConfig {
case AzureRBAC:
// In this mode, Authentication happens via AD users and Authorization is granted by AzureRBAC.
cfg, expiresOn, err := c.getAzureRBACCredentials(ctx, cfg)
return cfg, expiresOn, trace.Wrap(err)
case AzureAD:
// In this mode, Authentication happens via AD users and Authorization is granted by Kubernetes RBAC.
cfg, expiresOn, err := c.getAzureADCredentials(ctx, cfg)
return cfg, expiresOn, trace.Wrap(err)
case LocalAccounts:
// In this mode, Authentication is granted by provisioned static accounts accessible via
// ListClusterUserCredentials
cfg, err := c.getUserCredentials(ctx, cfg)
if err != nil {
return nil, time.Time{}, trace.Wrap(err)
}
// make sure the credentials are not exec based.
cfg, err = checkIfAuthMethodIsUnSupported(cfg)
// the access credentials are static and are only changed if there is a change in the cluster CA, however to prevent this we will refresh the credentials
return cfg, time.Now().Add(1 * time.Hour), trace.Wrap(err)
default:
return nil, time.Time{}, trace.BadParameter("unsuported AKS authentication mode %v", clusterDetails.Properties.AccessConfig)
}
}
// getAzureRBACCredentials generates a config to access the cluster.
// When AzureRBAC is enabled, the authentication happens with a BearerToken and the agent's Active Directory
// group has the access rules to access the cluster. If checkPermissions fails we cannot do anything
// and the user has to manually edit the agent's group permissions.
func (c *aksClient) getAzureRBACCredentials(ctx context.Context, cluster ClusterCredentialsConfig) (*rest.Config, time.Time, error) {
cfg, err := c.getUserCredentials(ctx, cluster)
if err != nil {
return nil, time.Time{}, trace.Wrap(err)
}
expiresOn, err := c.getAzureToken(ctx, cluster.TenantID, cfg)
if err != nil {
return nil, time.Time{}, trace.Wrap(err)
}
if err := c.checkAccessPermissions(ctx, cfg, cluster); err != nil {
return nil, time.Time{}, trace.WrapWithMessage(err, `Azure RBAC rules have not been configured for the agent.
Please check that you have configured them correctly.`)
}
return cfg, expiresOn, nil
}
// getUserCredentials gets the user credentials by calling `ListClusterUserCredentials` method
// and parsing the kubeconfig returned.
func (c *aksClient) getUserCredentials(ctx context.Context, cfg ClusterCredentialsConfig) (*rest.Config, error) {
options := &armcontainerservice.ManagedClustersClientListClusterUserCredentialsOptions{
// format is only applied if AD is enabled but we can force the request with it.
Format: to.Ptr(armcontainerservice.FormatExec),
}
res, err := c.api.ListClusterUserCredentials(ctx, cfg.ResourceGroup, cfg.ResourceName, options)
if err != nil {
return nil, trace.Wrap(ConvertResponseError(err))
}
result, err := c.getRestConfigFromKubeconfigs(res.Kubeconfigs)
return result, trace.Wrap(err)
}
// getAzureADCredentials gets the client configuration and checks if Kubernetes RBAC is configured.
func (c *aksClient) getAzureADCredentials(ctx context.Context, cluster ClusterCredentialsConfig) (*rest.Config, time.Time, error) {
// getUserCredentials is used to extract the cluster CA and API endpoint.
cfg, err := c.getUserCredentials(ctx, cluster)
if err != nil {
return nil, time.Time{}, trace.Wrap(err)
}
expiresOn, err := c.getAzureToken(ctx, cluster.TenantID, cfg)
if err != nil {
return nil, time.Time{}, trace.Wrap(err)
}
// checks if agent already has access to the cluster
if err := c.checkAccessPermissions(ctx, cfg, cluster); err == nil {
// access to the cluster was already granted!
return cfg, expiresOn, nil
}
// parse the azure JWT token to extract the first groupID the principal belongs to.
groupID, err := extractGroupFromAzure(cfg.BearerToken)
if err != nil {
return nil, time.Time{}, trace.Wrap(err)
}
var (
adminCredentialsErr error
runCMDErr error
)
// calls the ListClusterAdminCrdentials endpoint to return the admin static credentials.
adminCfg, err := c.getAdminCredentials(ctx, cluster.ResourceGroup, cluster.ResourceName)
switch {
case err == nil:
// given the admin credentials, the agent will try to create the ClusterRole and
// ClusterRoleBinding objects in the AKS cluster.
if adminCredentialsErr = c.grantAccessWithAdminCredentials(ctx, adminCfg, groupID); adminCredentialsErr == nil {
// checks if agent already has access to the cluster
if err := c.checkAccessPermissions(ctx, cfg, cluster); err == nil {
// access to the cluster was already granted!
return cfg, expiresOn, nil
}
}
adminCredentialsErr = trace.WrapWithMessage(adminCredentialsErr, `Tried to grant access to %s/%s using aks.ListClusterAdminCredentials`, cluster.ResourceGroup, cluster.ResourceName)
// if the creation failed, then the agent will try to run a command to create them.
fallthrough
case err != nil:
if runCMDErr = c.grantAccessWithCommand(ctx, cluster.ResourceGroup, cluster.ResourceName, cluster.TenantID, groupID); runCMDErr != nil {
return nil, time.Time{}, trace.Wrap(err)
}
if err := c.checkAccessPermissions(ctx, cfg, cluster); err == nil {
// access to the cluster was already granted!
return cfg, expiresOn, nil
}
runCMDErr = trace.WrapWithMessage(runCMDErr, `Tried to grant access to %s/%s using aks.BeginRunCommand`, cluster.ResourceGroup, cluster.ResourceName)
return nil, time.Time{}, trace.WrapWithMessage(trace.NewAggregate(adminCredentialsErr, runCMDErr), `Cannot grant access to %s/%s AKS cluster`, cluster.ResourceGroup, cluster.ResourceName)
}
return nil, time.Time{}, trace.NotImplemented("code shouldn't reach")
}
// getAdminCredentials returns the cluster admin credentials by calling ListClusterAdminCredentials method.
// This function also validates if the credentials are not exec based.
func (c *aksClient) getAdminCredentials(ctx context.Context, group, name string) (*rest.Config, error) {
options := &armcontainerservice.ManagedClustersClientListClusterAdminCredentialsOptions{}
res, err := c.api.ListClusterAdminCredentials(ctx, group, name, options)
if err != nil {
return nil, trace.Wrap(ConvertResponseError(err))
}
result, err := c.getRestConfigFromKubeconfigs(res.Kubeconfigs)
if err != nil {
return nil, trace.Wrap(err)
}
result, err = checkIfAuthMethodIsUnSupported(result)
return result, trace.Wrap(err)
}
// getRestConfigFromKubeconfigs parses the first kubeConfig returned by ListClusterAdminCredentials and
// ListClusterUserCredentials methods.
func (c *aksClient) getRestConfigFromKubeconfigs(kubes []*armcontainerservice.CredentialResult) (*rest.Config, error) {
if len(kubes) == 0 {
return nil, trace.NotFound("no valid kubeconfig returned")
}
config, err := clientcmd.Load(kubes[0].Value)
if err != nil {
return nil, trace.Wrap(err)
}
kubeRestConfig, err := clientcmd.NewDefaultClientConfig(*config, nil).ClientConfig()
return kubeRestConfig, trace.Wrap(err)
}
// checkAccessPermissions checks if the agent has the required permissions to operate.
func (c *aksClient) checkAccessPermissions(ctx context.Context, clientCfg *rest.Config, cfg ClusterCredentialsConfig) error {
client, err := kubernetes.NewForConfig(clientCfg)
if err != nil {
return trace.Wrap(err, "failed to generate Kubernetes client for cluster")
}
sarClient := client.AuthorizationV1().SelfSubjectAccessReviews()
return trace.Wrap(cfg.ImpersonationPermissionsChecker(ctx, cfg.ResourceName, sarClient))
}
// getAzureToken generates an authentication token and changes the rest.Config.
func (c *aksClient) getAzureToken(ctx context.Context, tentantID string, clientCfg *rest.Config) (time.Time, error) {
token, time, err := c.genAzureToken(ctx, tentantID)
if err != nil {
return time, trace.Wrap(err)
}
// reset the old exec provider credentials
clientCfg.ExecProvider = nil
clientCfg.BearerToken = token
return time, nil
}
// genAzureToken generates an authentication token for clusters with AD enabled.
func (c *aksClient) genAzureToken(ctx context.Context, tentantID string) (string, time.Time, error) {
const (
// azureManagedClusterScope is a fixed uuid used to inform Azure
// that we want a Token fully populated with identity principals.
// ref: https://github.com/Azure/kubelogin#exec-plugin-format
azureManagedClusterScope = "6dae42f8-4368-4678-94ff-3960e28e3630"
)
cred, err := c.azIdentity(&azidentity.DefaultAzureCredentialOptions{
TenantID: tentantID,
})
if err != nil {
return "", time.Time{}, trace.Wrap(ConvertResponseError(err))
}
cliAccessToken, err := cred.GetToken(ctx, policy.TokenRequestOptions{
// azureManagedClusterScope is a fixed scope that identifies azure AKS managed clusters.
Scopes: []string{azureManagedClusterScope},
},
)
if err != nil {
return "", time.Time{}, trace.Wrap(ConvertResponseError(err))
}
return cliAccessToken.Token, cliAccessToken.ExpiresOn, nil
}
// grantAccessWithAdminCredentials tries to create the ClusterRole and ClusterRoleBinding into the AKS cluster
// using admin credentials.
func (c *aksClient) grantAccessWithAdminCredentials(ctx context.Context, adminCfg *rest.Config, groupID string) error {
client, err := kubernetes.NewForConfig(adminCfg)
if err != nil {
return trace.Wrap(err, "failed to generate Kubernetes client for cluster")
}
if err := c.upsertClusterRoleWithAdminCredentials(ctx, client); err != nil {
return trace.Wrap(err)
}
err = c.upsertClusterRoleBindingWithAdminCredentials(ctx, client, groupID)
return trace.Wrap(err)
}
// upsertClusterRoleWithAdminCredentials tries to upsert the ClusterRole using admin credentials.
func (c *aksClient) upsertClusterRoleWithAdminCredentials(ctx context.Context, client *kubernetes.Clientset) error {
clusterRole := &v1.ClusterRole{}
if err := yaml.Unmarshal([]byte(clusterRoleTemplate), clusterRole); err != nil {
return trace.Wrap(err)
}
_, err := client.RbacV1().ClusterRoles().Create(ctx, clusterRole, metav1.CreateOptions{
FieldManager: resourceOwner,
})
if err == nil {
return nil
}
if kubeerrors.IsAlreadyExists(err) {
_, err := client.RbacV1().ClusterRoles().Update(ctx, clusterRole, metav1.UpdateOptions{
FieldManager: resourceOwner,
})
return trace.Wrap(err)
}
return trace.Wrap(err)
}
// upsertClusterRoleBindingWithAdminCredentials tries to upsert the ClusterRoleBinding using admin credentials
// and maps it into the principal group.
func (c *aksClient) upsertClusterRoleBindingWithAdminCredentials(ctx context.Context, client *kubernetes.Clientset, groupID string) error {
clusterRoleBinding := &v1.ClusterRoleBinding{}
if err := yaml.Unmarshal([]byte(clusterRoleBindingTemplate), clusterRoleBinding); err != nil {
return trace.Wrap(err)
}
if len(clusterRoleBinding.Subjects) == 0 {
return trace.BadParameter("Subjects field were not correctly unmarshaled")
}
clusterRoleBinding.Subjects[0].Name = groupID
_, err := client.RbacV1().ClusterRoleBindings().Create(ctx, clusterRoleBinding, metav1.CreateOptions{
FieldManager: resourceOwner,
})
if err == nil {
return nil
}
if kubeerrors.IsAlreadyExists(err) {
_, err := client.RbacV1().ClusterRoleBindings().Update(ctx, clusterRoleBinding, metav1.UpdateOptions{
FieldManager: resourceOwner,
})
return trace.Wrap(err)
}
return trace.Wrap(err)
}
// grantAccessWithCommand tries to create the ClusterRole and ClusterRoleBinding into the AKS cluster
// using remote kubectl command.
func (c *aksClient) grantAccessWithCommand(ctx context.Context, resourceGroupName, resourceName, tentantID, groupID string) error {
token, _, err := c.genAzureToken(ctx, tentantID)
if err != nil {
return trace.Wrap(err)
}
cmd, err := c.api.BeginRunCommand(ctx, resourceGroupName, resourceName, armcontainerservice.RunCommandRequest{
ClusterToken: to.Ptr(token),
Command: to.Ptr(kubectlApplyString(groupID)),
}, &armcontainerservice.ManagedClustersClientBeginRunCommandOptions{})
if err != nil {
return trace.Wrap(ConvertResponseError(err))
}
_, err = cmd.PollUntilDone(ctx, &runtime.PollUntilDoneOptions{Frequency: time.Second})
return trace.Wrap(ConvertResponseError(err))
}
// extractGroupFromAzure extracts the first group id in the Azure Bearer Token.
func extractGroupFromAzure(token string) (string, error) {
p := jwt.NewParser()
claims := &azureGroupClaims{}
// We do not want to validate the token since
// we generated it from Azure SDK.
_, _, err := p.ParseUnverified(token, claims)
if err != nil {
return "", trace.Wrap(err)
}
// ParseUnverified already validates that len(claims.Groups)>0
return claims.Groups[0], nil
}
// checkIfAuthMethodIsUnSupported checks if the credentials are not exec based.
func checkIfAuthMethodIsUnSupported(cfg *rest.Config) (*rest.Config, error) {
if cfg.ExecProvider != nil {
return nil, trace.BadParameter("exec auth format not supported")
}
return cfg, nil
}
// AKSClusterFromManagedCluster converts an Azure armcontainerservice.ManagedCluster into AKSCluster.
func AKSClusterFromManagedCluster(cluster *armcontainerservice.ManagedCluster) (*AKSCluster, error) {
result := &AKSCluster{
Name: StringVal(cluster.Name),
Location: StringVal(cluster.Location),
Tags: ConvertTags(cluster.Tags),
}
if cluster.Identity != nil {
result.TenantID = StringVal(cluster.Identity.TenantID)
}
if subID, groupName, err := extractSubscriptionAndGroupName(cluster.ID); err == nil {
result.GroupName, result.SubscriptionID = groupName, subID
}
if cluster.Properties == nil {
return nil, trace.BadParameter("invalid AKS Cluster Properties")
}
if !isAKSClusterRunning(cluster.Properties) {
return nil, trace.BadParameter("AKS cluster not running")
}
if cluster.Properties.AADProfile != nil && ptrToVal(cluster.Properties.AADProfile.EnableAzureRBAC) {
result.Properties = AKSClusterProperties{
AccessConfig: AzureRBAC,
}
} else if cluster.Properties.AADProfile != nil {
result.Properties = AKSClusterProperties{
AccessConfig: AzureAD,
LocalAccounts: !ptrToVal(cluster.Properties.DisableLocalAccounts),
}
} else {
result.Properties = AKSClusterProperties{
AccessConfig: LocalAccounts,
LocalAccounts: true,
}
}
return result, nil
}
func ptrToVal[T any](ptr *T) T {
var result T
if ptr != nil {
result = *ptr
}
return result
}
// extractSubscriptionAndGroupName extracts the group name and subscription id from resource id.
// ids are in the form of:
// /subscriptions/{subscription_id}/resourcegroups/{resource_group}/providers/Microsoft.ContainerService/managedClusters/{name}
func extractSubscriptionAndGroupName(id *string) (string, string, error) {
if id == nil {
return "", "", trace.BadParameter("invalid resource_id provided")
}
resource, err := armazcore.ParseResourceID(*id)
if err != nil {
return "", "", trace.Wrap(err)
}
return resource.SubscriptionID, resource.ResourceGroupName, nil
}
// azureGroupClaims the configuration settings of the Azure Active Directory allowed principals.
type azureGroupClaims struct {
// Groups - The list of the allowed groups.
Groups []string `json:"groups,omitempty"`
}
func (c *azureGroupClaims) Valid() error {
if len(c.Groups) == 0 {
return trace.BadParameter("invalid claims received")
}
return nil
}
func isAKSClusterRunning(properties *armcontainerservice.ManagedClusterProperties) bool {
if properties.PowerState != nil && properties.PowerState.Code != nil &&
*properties.PowerState.Code == armcontainerservice.CodeRunning {
return true
}
return false
}
const (
clusterRoleTemplate = `
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: teleport
rules:
- apiGroups:
- ""
resources:
- users
- groups
- serviceaccounts
verbs:
- impersonate
- apiGroups:
- ""
resources:
- pods
verbs:
- get
- apiGroups:
- "authorization.k8s.io"
resources:
- selfsubjectaccessreviews
- selfsubjectrulesreviews
verbs:
- create
`
clusterRoleBindingTemplate = `
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: teleport
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: teleport
subjects:
- kind: Group
name: group_name
apiGroup: rbac.authorization.k8s.io`
)
// kubectlApplyString generates a kubectl apply command to create the ClusterRole
// and ClusterRoleBinding.
// cat <<EOF | kubectl apply -f -
// apiVersion: rbac.authorization.k8s.io/v1
// kind: ClusterRole
// metadata:
//
// name: teleport
//
// rules:
// - apiGroups:
// - ""
// resources:
// - users
// - groups
// - serviceaccounts
// verbs:
// - impersonate
//
// - apiGroups:
// - ""
// resources:
// - pods
// verbs:
// - get
//
// - apiGroups:
// - "authorization.k8s.io"
// resources:
// - selfsubjectaccessreviews
// - selfsubjectrulesreviews
// verbs:
// - create
//
// ---
// apiVersion: rbac.authorization.k8s.io/v1
// kind: ClusterRoleBinding
// metadata:
//
// name: teleport
//
// roleRef:
//
// apiGroup: rbac.authorization.k8s.io
// kind: ClusterRole
// name: teleport
//
// subjects:
// - kind: Group
// name: group
// apiGroup: rbac.authorization.k8s.io
//
// EOF
func kubectlApplyString(group string) string {
return fmt.Sprintf(`cat <<EOF | kubectl apply -f -
%s
---
%s
EOF`, clusterRoleTemplate, strings.ReplaceAll(clusterRoleBindingTemplate, "group_name", group))
}