token.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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. "context"
  17. "fmt"
  18. "time"
  19. "github.com/pkg/errors"
  20. v1 "k8s.io/api/core/v1"
  21. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  22. "k8s.io/apimachinery/pkg/util/wait"
  23. clientset "k8s.io/client-go/kubernetes"
  24. "k8s.io/client-go/tools/clientcmd"
  25. clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
  26. certutil "k8s.io/client-go/util/cert"
  27. bootstrapapi "k8s.io/cluster-bootstrap/token/api"
  28. bootstrap "k8s.io/cluster-bootstrap/token/jws"
  29. "k8s.io/klog"
  30. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  31. kubeadmapiv1beta2 "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1beta2"
  32. "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  33. kubeconfigutil "k8s.io/kubernetes/cmd/kubeadm/app/util/kubeconfig"
  34. "k8s.io/kubernetes/cmd/kubeadm/app/util/pubkeypin"
  35. )
  36. // BootstrapUser defines bootstrap user name
  37. const BootstrapUser = "token-bootstrap-client"
  38. // RetrieveValidatedConfigInfo connects to the API Server and tries to fetch the cluster-info ConfigMap
  39. // It then makes sure it can trust the API Server by looking at the JWS-signed tokens and (if CACertHashes is not empty)
  40. // validating the cluster CA against a set of pinned public keys
  41. func RetrieveValidatedConfigInfo(cfg *kubeadmapi.Discovery) (*clientcmdapi.Config, error) {
  42. return retrieveValidatedConfigInfo(nil, cfg, constants.DiscoveryRetryInterval)
  43. }
  44. // retrieveValidatedConfigInfo is a private implementation of RetrieveValidatedConfigInfo.
  45. // It accepts an optional clientset that can be used for testing purposes.
  46. func retrieveValidatedConfigInfo(client clientset.Interface, cfg *kubeadmapi.Discovery, interval time.Duration) (*clientcmdapi.Config, error) {
  47. token, err := kubeadmapi.NewBootstrapTokenString(cfg.BootstrapToken.Token)
  48. if err != nil {
  49. return nil, err
  50. }
  51. // Load the CACertHashes into a pubkeypin.Set
  52. pubKeyPins := pubkeypin.NewSet()
  53. if err = pubKeyPins.Allow(cfg.BootstrapToken.CACertHashes...); err != nil {
  54. return nil, err
  55. }
  56. duration := cfg.Timeout.Duration
  57. // Make sure the interval is not bigger than the duration
  58. if interval > duration {
  59. interval = duration
  60. }
  61. endpoint := cfg.BootstrapToken.APIServerEndpoint
  62. insecureBootstrapConfig := buildInsecureBootstrapKubeConfig(endpoint, kubeadmapiv1beta2.DefaultClusterName)
  63. clusterName := insecureBootstrapConfig.Contexts[insecureBootstrapConfig.CurrentContext].Cluster
  64. klog.V(1).Infof("[discovery] Created cluster-info discovery client, requesting info from %q", endpoint)
  65. insecureClusterInfo, err := getClusterInfo(client, insecureBootstrapConfig, token, interval, duration)
  66. if err != nil {
  67. return nil, err
  68. }
  69. // Validate the token in the cluster info
  70. insecureKubeconfigBytes, err := validateClusterInfoToken(insecureClusterInfo, token)
  71. if err != nil {
  72. return nil, err
  73. }
  74. // Load the insecure config
  75. insecureConfig, err := clientcmd.Load(insecureKubeconfigBytes)
  76. if err != nil {
  77. return nil, errors.Wrapf(err, "couldn't parse the kubeconfig file in the %s ConfigMap", bootstrapapi.ConfigMapClusterInfo)
  78. }
  79. // The ConfigMap should contain a single cluster
  80. if len(insecureConfig.Clusters) != 1 {
  81. 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))
  82. }
  83. // If no TLS root CA pinning was specified, we're done
  84. if pubKeyPins.Empty() {
  85. klog.V(1).Infof("[discovery] Cluster info signature and contents are valid and no TLS pinning was specified, will use API Server %q", endpoint)
  86. return insecureConfig, nil
  87. }
  88. // Load and validate the cluster CA from the insecure kubeconfig
  89. clusterCABytes, err := validateClusterCA(insecureConfig, pubKeyPins)
  90. if err != nil {
  91. return nil, err
  92. }
  93. // Now that we know the cluster CA, connect back a second time validating with that CA
  94. secureBootstrapConfig := buildSecureBootstrapKubeConfig(endpoint, clusterCABytes, clusterName)
  95. klog.V(1).Infof("[discovery] Requesting info from %q again to validate TLS against the pinned public key", endpoint)
  96. secureClusterInfo, err := getClusterInfo(client, secureBootstrapConfig, token, interval, duration)
  97. if err != nil {
  98. return nil, err
  99. }
  100. // Pull the kubeconfig from the securely-obtained ConfigMap and validate that it's the same as what we found the first time
  101. secureKubeconfigBytes := []byte(secureClusterInfo.Data[bootstrapapi.KubeConfigKey])
  102. if !bytes.Equal(secureKubeconfigBytes, insecureKubeconfigBytes) {
  103. return nil, errors.Errorf("the second kubeconfig from the %s ConfigMap (using validated TLS) was different from the first", bootstrapapi.ConfigMapClusterInfo)
  104. }
  105. secureKubeconfig, err := clientcmd.Load(secureKubeconfigBytes)
  106. if err != nil {
  107. return nil, errors.Wrapf(err, "couldn't parse the kubeconfig file in the %s ConfigMap", bootstrapapi.ConfigMapClusterInfo)
  108. }
  109. klog.V(1).Infof("[discovery] Cluster info signature and contents are valid and TLS certificate validates against pinned roots, will use API Server %q", endpoint)
  110. return secureKubeconfig, nil
  111. }
  112. // buildInsecureBootstrapKubeConfig makes a kubeconfig object that connects insecurely to the API Server for bootstrapping purposes
  113. func buildInsecureBootstrapKubeConfig(endpoint, clustername string) *clientcmdapi.Config {
  114. controlPlaneEndpoint := fmt.Sprintf("https://%s", endpoint)
  115. bootstrapConfig := kubeconfigutil.CreateBasic(controlPlaneEndpoint, clustername, BootstrapUser, []byte{})
  116. bootstrapConfig.Clusters[clustername].InsecureSkipTLSVerify = true
  117. return bootstrapConfig
  118. }
  119. // buildSecureBootstrapKubeConfig makes a kubeconfig object that connects securely to the API Server for bootstrapping purposes (validating with the specified CA)
  120. func buildSecureBootstrapKubeConfig(endpoint string, caCert []byte, clustername string) *clientcmdapi.Config {
  121. controlPlaneEndpoint := fmt.Sprintf("https://%s", endpoint)
  122. bootstrapConfig := kubeconfigutil.CreateBasic(controlPlaneEndpoint, clustername, BootstrapUser, caCert)
  123. return bootstrapConfig
  124. }
  125. // validateClusterInfoToken validates that the JWS token present in the cluster info ConfigMap is valid
  126. func validateClusterInfoToken(insecureClusterInfo *v1.ConfigMap, token *kubeadmapi.BootstrapTokenString) ([]byte, error) {
  127. insecureKubeconfigString, ok := insecureClusterInfo.Data[bootstrapapi.KubeConfigKey]
  128. if !ok || len(insecureKubeconfigString) == 0 {
  129. 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",
  130. bootstrapapi.KubeConfigKey, bootstrapapi.ConfigMapClusterInfo)
  131. }
  132. detachedJWSToken, ok := insecureClusterInfo.Data[bootstrapapi.JWSSignatureKeyPrefix+token.ID]
  133. if !ok || len(detachedJWSToken) == 0 {
  134. 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)
  135. }
  136. if !bootstrap.DetachedTokenIsValid(detachedJWSToken, insecureKubeconfigString, token.ID, token.Secret) {
  137. return nil, errors.New("failed to verify JWS signature of received cluster info object, can't trust this API Server")
  138. }
  139. return []byte(insecureKubeconfigString), nil
  140. }
  141. // validateClusterCA validates the cluster CA found in the insecure kubeconfig
  142. func validateClusterCA(insecureConfig *clientcmdapi.Config, pubKeyPins *pubkeypin.Set) ([]byte, error) {
  143. var clusterCABytes []byte
  144. for _, cluster := range insecureConfig.Clusters {
  145. clusterCABytes = cluster.CertificateAuthorityData
  146. }
  147. clusterCAs, err := certutil.ParseCertsPEM(clusterCABytes)
  148. if err != nil {
  149. return nil, errors.Wrapf(err, "failed to parse cluster CA from the %s ConfigMap", bootstrapapi.ConfigMapClusterInfo)
  150. }
  151. // Validate the cluster CA public key against the pinned set
  152. err = pubKeyPins.CheckAny(clusterCAs)
  153. if err != nil {
  154. return nil, errors.Wrapf(err, "cluster CA found in %s ConfigMap is invalid", bootstrapapi.ConfigMapClusterInfo)
  155. }
  156. return clusterCABytes, nil
  157. }
  158. // getClusterInfo creates a client from the given kubeconfig if the given client is nil,
  159. // and requests the cluster info ConfigMap using PollImmediate.
  160. // If a client is provided it will be used instead.
  161. func getClusterInfo(client clientset.Interface, kubeconfig *clientcmdapi.Config, token *kubeadmapi.BootstrapTokenString, interval, duration time.Duration) (*v1.ConfigMap, error) {
  162. var cm *v1.ConfigMap
  163. var err error
  164. // Create client from kubeconfig
  165. if client == nil {
  166. client, err = kubeconfigutil.ToClientSet(kubeconfig)
  167. if err != nil {
  168. return nil, err
  169. }
  170. }
  171. ctx, cancel := context.WithTimeout(context.TODO(), duration)
  172. defer cancel()
  173. wait.JitterUntil(func() {
  174. cm, err = client.CoreV1().ConfigMaps(metav1.NamespacePublic).Get(context.TODO(), bootstrapapi.ConfigMapClusterInfo, metav1.GetOptions{})
  175. if err != nil {
  176. klog.V(1).Infof("[discovery] Failed to request cluster-info, will try again: %v", err)
  177. return
  178. }
  179. // Even if the ConfigMap is available the JWS signature is patched-in a bit later.
  180. // Make sure we retry util then.
  181. if _, ok := cm.Data[bootstrapapi.JWSSignatureKeyPrefix+token.ID]; !ok {
  182. klog.V(1).Infof("[discovery] The cluster-info ConfigMap does not yet contain a JWS signature for token ID %q, will try again", token.ID)
  183. err = errors.Errorf("could not find a JWS signature in the cluster-info ConfigMap for token ID %q", token.ID)
  184. return
  185. }
  186. // Cancel the context on success
  187. cancel()
  188. }, interval, 0.3, true, ctx.Done())
  189. if err != nil {
  190. return nil, err
  191. }
  192. return cm, nil
  193. }