istio

Форк
0
143 строки · 5.5 Кб
1
// Copyright Istio Authors
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14

15
package options
16

17
import (
18
	"fmt"
19
	"strings"
20

21
	meshconfig "istio.io/api/mesh/v1alpha1"
22
	"istio.io/istio/pilot/pkg/features"
23
	"istio.io/istio/pkg/config/constants"
24
	"istio.io/istio/pkg/jwt"
25
	"istio.io/istio/pkg/log"
26
	"istio.io/istio/pkg/security"
27
	"istio.io/istio/security/pkg/credentialfetcher"
28
	"istio.io/istio/security/pkg/nodeagent/cafile"
29
	"istio.io/istio/security/pkg/nodeagent/plugin/providers/google/stsclient"
30
	"istio.io/istio/security/pkg/stsservice/tokenmanager"
31
)
32

33
func NewSecurityOptions(proxyConfig *meshconfig.ProxyConfig, stsPort int, tokenManagerPlugin string) (*security.Options, error) {
34
	o := &security.Options{
35
		CAEndpoint:                     caEndpointEnv,
36
		CAProviderName:                 caProviderEnv,
37
		PilotCertProvider:              features.PilotCertProvider,
38
		OutputKeyCertToDir:             outputKeyCertToDir,
39
		ProvCert:                       provCert,
40
		ClusterID:                      clusterIDVar.Get(),
41
		FileMountedCerts:               fileMountedCertsEnv,
42
		WorkloadNamespace:              PodNamespaceVar.Get(),
43
		ServiceAccount:                 serviceAccountVar.Get(),
44
		XdsAuthProvider:                xdsAuthProvider.Get(),
45
		TrustDomain:                    trustDomainEnv,
46
		WorkloadRSAKeySize:             workloadRSAKeySizeEnv,
47
		Pkcs8Keys:                      pkcs8KeysEnv,
48
		ECCSigAlg:                      eccSigAlgEnv,
49
		ECCCurve:                       eccCurvEnv,
50
		SecretTTL:                      secretTTLEnv,
51
		FileDebounceDuration:           fileDebounceDuration,
52
		SecretRotationGracePeriodRatio: secretRotationGracePeriodRatioEnv,
53
		STSPort:                        stsPort,
54
		CertSigner:                     certSigner.Get(),
55
		CARootPath:                     cafile.CACertFilePath,
56
		CertChainFilePath:              security.DefaultCertChainFilePath,
57
		KeyFilePath:                    security.DefaultKeyFilePath,
58
		RootCertFilePath:               security.DefaultRootCertFilePath,
59
	}
60

61
	o, err := SetupSecurityOptions(proxyConfig, o, jwtPolicy.Get(),
62
		credFetcherTypeEnv, credIdentityProvider)
63
	if err != nil {
64
		return o, err
65
	}
66

67
	var tokenManager security.TokenManager
68
	if stsPort > 0 || xdsAuthProvider.Get() != "" {
69
		// tokenManager is gcp token manager when using the default token manager plugin.
70
		tokenManager, err = tokenmanager.CreateTokenManager(tokenManagerPlugin,
71
			tokenmanager.Config{CredFetcher: o.CredFetcher, TrustDomain: o.TrustDomain})
72
	}
73
	o.TokenManager = tokenManager
74

75
	return o, err
76
}
77

78
func SetupSecurityOptions(proxyConfig *meshconfig.ProxyConfig, secOpt *security.Options, jwtPolicy,
79
	credFetcherTypeEnv, credIdentityProvider string,
80
) (*security.Options, error) {
81
	jwtPath := constants.ThirdPartyJwtPath
82
	switch jwtPolicy {
83
	case jwt.PolicyThirdParty:
84
		log.Info("JWT policy is third-party-jwt")
85
		jwtPath = constants.ThirdPartyJwtPath
86
	case jwt.PolicyFirstParty:
87
		log.Warnf("Using deprecated JWT policy 'first-party-jwt'; treating as 'third-party-jwt'")
88
		jwtPath = constants.ThirdPartyJwtPath
89
	default:
90
		log.Info("Using existing certs")
91
	}
92

93
	o := secOpt
94

95
	// If not set explicitly, default to the discovery address.
96
	if o.CAEndpoint == "" {
97
		o.CAEndpoint = proxyConfig.DiscoveryAddress
98
		o.CAEndpointSAN = istiodSAN.Get()
99
	}
100

101
	o.CredIdentityProvider = credIdentityProvider
102
	credFetcher, err := credentialfetcher.NewCredFetcher(credFetcherTypeEnv, o.TrustDomain, jwtPath, o.CredIdentityProvider)
103
	if err != nil {
104
		return nil, fmt.Errorf("failed to create credential fetcher: %v", err)
105
	}
106
	log.Infof("using credential fetcher of %s type in %s trust domain", credFetcherTypeEnv, o.TrustDomain)
107
	o.CredFetcher = credFetcher
108

109
	if o.CAProviderName == security.GkeWorkloadCertificateProvider {
110
		if !security.CheckWorkloadCertificate(security.GkeWorkloadCertChainFilePath,
111
			security.GkeWorkloadKeyFilePath, security.GkeWorkloadRootCertFilePath) {
112
			return nil, fmt.Errorf("GKE workload certificate files (%v, %v, %v) not present",
113
				security.GkeWorkloadCertChainFilePath, security.GkeWorkloadKeyFilePath, security.GkeWorkloadRootCertFilePath)
114
		}
115
		if o.ProvCert != "" {
116
			return nil, fmt.Errorf(
117
				"invalid options: PROV_CERT and FILE_MOUNTED_CERTS of GKE workload cert are mutually exclusive")
118
		}
119
		o.FileMountedCerts = true
120
		o.CertChainFilePath = security.GkeWorkloadCertChainFilePath
121
		o.KeyFilePath = security.GkeWorkloadKeyFilePath
122
		o.RootCertFilePath = security.GkeWorkloadRootCertFilePath
123
		return o, nil
124
	}
125

126
	// Default the CA provider where possible
127
	if strings.Contains(o.CAEndpoint, "googleapis.com") {
128
		o.CAProviderName = security.GoogleCAProvider
129
	}
130
	// TODO extract this logic out to a plugin
131
	if o.CAProviderName == security.GoogleCAProvider || o.CAProviderName == security.GoogleCASProvider {
132
		var err error
133
		o.TokenExchanger, err = stsclient.NewSecureTokenServiceExchanger(o.CredFetcher, o.TrustDomain)
134
		if err != nil {
135
			return nil, err
136
		}
137
	}
138

139
	if o.ProvCert != "" && o.FileMountedCerts {
140
		return nil, fmt.Errorf("invalid options: PROV_CERT and FILE_MOUNTED_CERTS are mutually exclusive")
141
	}
142
	return o, nil
143
}
144

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.