token.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package token
  14. import (
  15. "bytes"
  16. "fmt"
  17. "sync"
  18. "time"
  19. "github.com/pkg/errors"
  20. "k8s.io/api/core/v1"
  21. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  22. "k8s.io/apimachinery/pkg/util/wait"
  23. "k8s.io/client-go/tools/clientcmd"
  24. clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
  25. certutil "k8s.io/client-go/util/cert"
  26. bootstrapapi "k8s.io/cluster-bootstrap/token/api"
  27. "k8s.io/klog"
  28. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  29. kubeadmapiv1beta2 "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1beta2"
  30. "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  31. kubeconfigutil "k8s.io/kubernetes/cmd/kubeadm/app/util/kubeconfig"
  32. "k8s.io/kubernetes/cmd/kubeadm/app/util/pubkeypin"
  33. "k8s.io/kubernetes/pkg/controller/bootstrap"
  34. )
  35. // BootstrapUser defines bootstrap user name
  36. const BootstrapUser = "token-bootstrap-client"
  37. // RetrieveValidatedConfigInfo connects to the API Server and tries to fetch the cluster-info ConfigMap
  38. // It then makes sure it can trust the API Server by looking at the JWS-signed tokens and (if cfg.DiscoveryTokenCACertHashes is not empty)
  39. // validating the cluster CA against a set of pinned public keys
  40. func RetrieveValidatedConfigInfo(cfg *kubeadmapi.JoinConfiguration) (*clientcmdapi.Config, error) {
  41. token, err := kubeadmapi.NewBootstrapTokenString(cfg.Discovery.BootstrapToken.Token)
  42. if err != nil {
  43. return nil, err
  44. }
  45. // Load the cfg.DiscoveryTokenCACertHashes into a pubkeypin.Set
  46. pubKeyPins := pubkeypin.NewSet()
  47. err = pubKeyPins.Allow(cfg.Discovery.BootstrapToken.CACertHashes...)
  48. if err != nil {
  49. return nil, err
  50. }
  51. // The function below runs for every endpoint, and all endpoints races with each other.
  52. // The endpoint that wins the race and completes the task first gets its kubeconfig returned below
  53. baseKubeConfig, err := fetchKubeConfigWithTimeout(cfg.Discovery.BootstrapToken.APIServerEndpoint, cfg.Discovery.Timeout.Duration, func(endpoint string) (*clientcmdapi.Config, error) {
  54. insecureBootstrapConfig := buildInsecureBootstrapKubeConfig(endpoint, kubeadmapiv1beta2.DefaultClusterName)
  55. clusterName := insecureBootstrapConfig.Contexts[insecureBootstrapConfig.CurrentContext].Cluster
  56. insecureClient, err := kubeconfigutil.ToClientSet(insecureBootstrapConfig)
  57. if err != nil {
  58. return nil, err
  59. }
  60. klog.V(1).Infof("[discovery] Created cluster-info discovery client, requesting info from %q\n", insecureBootstrapConfig.Clusters[clusterName].Server)
  61. // Make an initial insecure connection to get the cluster-info ConfigMap
  62. var insecureClusterInfo *v1.ConfigMap
  63. wait.PollImmediateInfinite(constants.DiscoveryRetryInterval, func() (bool, error) {
  64. var err error
  65. insecureClusterInfo, err = insecureClient.CoreV1().ConfigMaps(metav1.NamespacePublic).Get(bootstrapapi.ConfigMapClusterInfo, metav1.GetOptions{})
  66. if err != nil {
  67. klog.V(1).Infof("[discovery] Failed to request cluster info, will try again: [%s]\n", err)
  68. return false, nil
  69. }
  70. return true, nil
  71. })
  72. // Validate the MAC on the kubeconfig from the ConfigMap and load it
  73. insecureKubeconfigString, ok := insecureClusterInfo.Data[bootstrapapi.KubeConfigKey]
  74. if !ok || len(insecureKubeconfigString) == 0 {
  75. return nil, errors.Errorf("there is no %s key in the %s ConfigMap. This API Server isn't set up for token bootstrapping, can't connect",
  76. bootstrapapi.KubeConfigKey, bootstrapapi.ConfigMapClusterInfo)
  77. }
  78. detachedJWSToken, ok := insecureClusterInfo.Data[bootstrapapi.JWSSignatureKeyPrefix+token.ID]
  79. if !ok || len(detachedJWSToken) == 0 {
  80. return nil, errors.Errorf("token id %q is invalid for this cluster or it has expired. Use \"kubeadm token create\" on the control-plane node to create a new valid token", token.ID)
  81. }
  82. if !bootstrap.DetachedTokenIsValid(detachedJWSToken, insecureKubeconfigString, token.ID, token.Secret) {
  83. return nil, errors.New("failed to verify JWS signature of received cluster info object, can't trust this API Server")
  84. }
  85. insecureKubeconfigBytes := []byte(insecureKubeconfigString)
  86. insecureConfig, err := clientcmd.Load(insecureKubeconfigBytes)
  87. if err != nil {
  88. return nil, errors.Wrapf(err, "couldn't parse the kubeconfig file in the %s configmap", bootstrapapi.ConfigMapClusterInfo)
  89. }
  90. // If no TLS root CA pinning was specified, we're done
  91. if pubKeyPins.Empty() {
  92. klog.V(1).Infof("[discovery] Cluster info signature and contents are valid and no TLS pinning was specified, will use API Server %q\n", endpoint)
  93. return insecureConfig, nil
  94. }
  95. // Load the cluster CA from the Config
  96. if len(insecureConfig.Clusters) != 1 {
  97. return nil, errors.Errorf("expected the kubeconfig file in the %s configmap to have a single cluster, but it had %d", bootstrapapi.ConfigMapClusterInfo, len(insecureConfig.Clusters))
  98. }
  99. var clusterCABytes []byte
  100. for _, cluster := range insecureConfig.Clusters {
  101. clusterCABytes = cluster.CertificateAuthorityData
  102. }
  103. clusterCAs, err := certutil.ParseCertsPEM(clusterCABytes)
  104. if err != nil {
  105. return nil, errors.Wrapf(err, "failed to parse cluster CA from the %s configmap", bootstrapapi.ConfigMapClusterInfo)
  106. }
  107. // Validate the cluster CA public key against the pinned set
  108. err = pubKeyPins.CheckAny(clusterCAs)
  109. if err != nil {
  110. return nil, errors.Wrapf(err, "cluster CA found in %s configmap is invalid", bootstrapapi.ConfigMapClusterInfo)
  111. }
  112. // Now that we know the proported cluster CA, connect back a second time validating with that CA
  113. secureBootstrapConfig := buildSecureBootstrapKubeConfig(endpoint, clusterCABytes, clusterName)
  114. secureClient, err := kubeconfigutil.ToClientSet(secureBootstrapConfig)
  115. if err != nil {
  116. return nil, err
  117. }
  118. klog.V(1).Infof("[discovery] Requesting info from %q again to validate TLS against the pinned public key\n", insecureBootstrapConfig.Clusters[clusterName].Server)
  119. var secureClusterInfo *v1.ConfigMap
  120. wait.PollImmediateInfinite(constants.DiscoveryRetryInterval, func() (bool, error) {
  121. var err error
  122. secureClusterInfo, err = secureClient.CoreV1().ConfigMaps(metav1.NamespacePublic).Get(bootstrapapi.ConfigMapClusterInfo, metav1.GetOptions{})
  123. if err != nil {
  124. klog.V(1).Infof("[discovery] Failed to request cluster info, will try again: [%s]\n", err)
  125. return false, nil
  126. }
  127. return true, nil
  128. })
  129. // Pull the kubeconfig from the securely-obtained ConfigMap and validate that it's the same as what we found the first time
  130. secureKubeconfigBytes := []byte(secureClusterInfo.Data[bootstrapapi.KubeConfigKey])
  131. if !bytes.Equal(secureKubeconfigBytes, insecureKubeconfigBytes) {
  132. return nil, errors.Errorf("the second kubeconfig from the %s configmap (using validated TLS) was different from the first", bootstrapapi.ConfigMapClusterInfo)
  133. }
  134. secureKubeconfig, err := clientcmd.Load(secureKubeconfigBytes)
  135. if err != nil {
  136. return nil, errors.Wrapf(err, "couldn't parse the kubeconfig file in the %s configmap", bootstrapapi.ConfigMapClusterInfo)
  137. }
  138. klog.V(1).Infof("[discovery] Cluster info signature and contents are valid and TLS certificate validates against pinned roots, will use API Server %q\n", endpoint)
  139. return secureKubeconfig, nil
  140. })
  141. if err != nil {
  142. return nil, err
  143. }
  144. return baseKubeConfig, nil
  145. }
  146. // buildInsecureBootstrapKubeConfig makes a kubeconfig object that connects insecurely to the API Server for bootstrapping purposes
  147. func buildInsecureBootstrapKubeConfig(endpoint, clustername string) *clientcmdapi.Config {
  148. controlPlaneEndpoint := fmt.Sprintf("https://%s", endpoint)
  149. bootstrapConfig := kubeconfigutil.CreateBasic(controlPlaneEndpoint, clustername, BootstrapUser, []byte{})
  150. bootstrapConfig.Clusters[clustername].InsecureSkipTLSVerify = true
  151. return bootstrapConfig
  152. }
  153. // buildSecureBootstrapKubeConfig makes a kubeconfig object that connects securely to the API Server for bootstrapping purposes (validating with the specified CA)
  154. func buildSecureBootstrapKubeConfig(endpoint string, caCert []byte, clustername string) *clientcmdapi.Config {
  155. controlPlaneEndpoint := fmt.Sprintf("https://%s", endpoint)
  156. bootstrapConfig := kubeconfigutil.CreateBasic(controlPlaneEndpoint, clustername, BootstrapUser, caCert)
  157. return bootstrapConfig
  158. }
  159. // fetchKubeConfigWithTimeout tries to run fetchKubeConfigFunc on every DiscoveryRetryInterval, but until discoveryTimeout is reached
  160. func fetchKubeConfigWithTimeout(apiEndpoint string, discoveryTimeout time.Duration, fetchKubeConfigFunc func(string) (*clientcmdapi.Config, error)) (*clientcmdapi.Config, error) {
  161. stopChan := make(chan struct{})
  162. var resultingKubeConfig *clientcmdapi.Config
  163. var once sync.Once
  164. var wg sync.WaitGroup
  165. wg.Add(1)
  166. go func() {
  167. defer wg.Done()
  168. wait.Until(func() {
  169. klog.V(1).Infof("[discovery] Trying to connect to API Server %q\n", apiEndpoint)
  170. cfg, err := fetchKubeConfigFunc(apiEndpoint)
  171. if err != nil {
  172. klog.V(1).Infof("[discovery] Failed to connect to API Server %q: %v\n", apiEndpoint, err)
  173. return
  174. }
  175. klog.V(1).Infof("[discovery] Successfully established connection with API Server %q\n", apiEndpoint)
  176. once.Do(func() {
  177. resultingKubeConfig = cfg
  178. close(stopChan)
  179. })
  180. }, constants.DiscoveryRetryInterval, stopChan)
  181. }()
  182. select {
  183. case <-time.After(discoveryTimeout):
  184. once.Do(func() {
  185. close(stopChan)
  186. })
  187. err := errors.Errorf("abort connecting to API servers after timeout of %v", discoveryTimeout)
  188. klog.V(1).Infof("[discovery] %v\n", err)
  189. wg.Wait()
  190. return nil, err
  191. case <-stopChan:
  192. wg.Wait()
  193. return resultingKubeConfig, nil
  194. }
  195. }