bootstrap.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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 bootstrap
  14. import (
  15. "context"
  16. "crypto/sha512"
  17. "crypto/x509/pkix"
  18. "encoding/base64"
  19. "errors"
  20. "fmt"
  21. "os"
  22. "path/filepath"
  23. "time"
  24. "k8s.io/klog"
  25. certificates "k8s.io/api/certificates/v1beta1"
  26. "k8s.io/apimachinery/pkg/types"
  27. utilruntime "k8s.io/apimachinery/pkg/util/runtime"
  28. "k8s.io/apimachinery/pkg/util/wait"
  29. "k8s.io/client-go/kubernetes/scheme"
  30. certificatesv1beta1 "k8s.io/client-go/kubernetes/typed/certificates/v1beta1"
  31. restclient "k8s.io/client-go/rest"
  32. "k8s.io/client-go/tools/clientcmd"
  33. clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
  34. "k8s.io/client-go/transport"
  35. certutil "k8s.io/client-go/util/cert"
  36. "k8s.io/client-go/util/certificate"
  37. "k8s.io/client-go/util/certificate/csr"
  38. "k8s.io/client-go/util/keyutil"
  39. )
  40. const tmpPrivateKeyFile = "kubelet-client.key.tmp"
  41. // LoadClientConfig tries to load the appropriate client config for retrieving certs and for use by users.
  42. // If bootstrapPath is empty, only kubeconfigPath is checked. If bootstrap path is set and the contents
  43. // of kubeconfigPath are valid, both certConfig and userConfig will point to that file. Otherwise the
  44. // kubeconfigPath on disk is populated based on bootstrapPath but pointing to the location of the client cert
  45. // in certDir. This preserves the historical behavior of bootstrapping where on subsequent restarts the
  46. // most recent client cert is used to request new client certs instead of the initial token.
  47. func LoadClientConfig(kubeconfigPath, bootstrapPath, certDir string) (certConfig, userConfig *restclient.Config, err error) {
  48. if len(bootstrapPath) == 0 {
  49. clientConfig, err := loadRESTClientConfig(kubeconfigPath)
  50. if err != nil {
  51. return nil, nil, fmt.Errorf("unable to load kubeconfig: %v", err)
  52. }
  53. klog.V(2).Infof("No bootstrapping requested, will use kubeconfig")
  54. return clientConfig, restclient.CopyConfig(clientConfig), nil
  55. }
  56. store, err := certificate.NewFileStore("kubelet-client", certDir, certDir, "", "")
  57. if err != nil {
  58. return nil, nil, fmt.Errorf("unable to build bootstrap cert store")
  59. }
  60. ok, err := isClientConfigStillValid(kubeconfigPath)
  61. if err != nil {
  62. return nil, nil, err
  63. }
  64. // use the current client config
  65. if ok {
  66. clientConfig, err := loadRESTClientConfig(kubeconfigPath)
  67. if err != nil {
  68. return nil, nil, fmt.Errorf("unable to load kubeconfig: %v", err)
  69. }
  70. klog.V(2).Infof("Current kubeconfig file contents are still valid, no bootstrap necessary")
  71. return clientConfig, restclient.CopyConfig(clientConfig), nil
  72. }
  73. bootstrapClientConfig, err := loadRESTClientConfig(bootstrapPath)
  74. if err != nil {
  75. return nil, nil, fmt.Errorf("unable to load bootstrap kubeconfig: %v", err)
  76. }
  77. clientConfig := restclient.AnonymousClientConfig(bootstrapClientConfig)
  78. pemPath := store.CurrentPath()
  79. clientConfig.KeyFile = pemPath
  80. clientConfig.CertFile = pemPath
  81. if err := writeKubeconfigFromBootstrapping(clientConfig, kubeconfigPath, pemPath); err != nil {
  82. return nil, nil, err
  83. }
  84. klog.V(2).Infof("Use the bootstrap credentials to request a cert, and set kubeconfig to point to the certificate dir")
  85. return bootstrapClientConfig, clientConfig, nil
  86. }
  87. // LoadClientCert requests a client cert for kubelet if the kubeconfigPath file does not exist.
  88. // The kubeconfig at bootstrapPath is used to request a client certificate from the API server.
  89. // On success, a kubeconfig file referencing the generated key and obtained certificate is written to kubeconfigPath.
  90. // The certificate and key file are stored in certDir.
  91. func LoadClientCert(kubeconfigPath, bootstrapPath, certDir string, nodeName types.NodeName) error {
  92. // Short-circuit if the kubeconfig file exists and is valid.
  93. ok, err := isClientConfigStillValid(kubeconfigPath)
  94. if err != nil {
  95. return err
  96. }
  97. if ok {
  98. klog.V(2).Infof("Kubeconfig %s exists and is valid, skipping bootstrap", kubeconfigPath)
  99. return nil
  100. }
  101. klog.V(2).Info("Using bootstrap kubeconfig to generate TLS client cert, key and kubeconfig file")
  102. bootstrapClientConfig, err := loadRESTClientConfig(bootstrapPath)
  103. if err != nil {
  104. return fmt.Errorf("unable to load bootstrap kubeconfig: %v", err)
  105. }
  106. bootstrapClient, err := certificatesv1beta1.NewForConfig(bootstrapClientConfig)
  107. if err != nil {
  108. return fmt.Errorf("unable to create certificates signing request client: %v", err)
  109. }
  110. store, err := certificate.NewFileStore("kubelet-client", certDir, certDir, "", "")
  111. if err != nil {
  112. return fmt.Errorf("unable to build bootstrap cert store")
  113. }
  114. var keyData []byte
  115. if cert, err := store.Current(); err == nil {
  116. if cert.PrivateKey != nil {
  117. keyData, err = keyutil.MarshalPrivateKeyToPEM(cert.PrivateKey)
  118. if err != nil {
  119. keyData = nil
  120. }
  121. }
  122. }
  123. // Cache the private key in a separate file until CSR succeeds. This has to
  124. // be a separate file because store.CurrentPath() points to a symlink
  125. // managed by the store.
  126. privKeyPath := filepath.Join(certDir, tmpPrivateKeyFile)
  127. if !verifyKeyData(keyData) {
  128. klog.V(2).Infof("No valid private key and/or certificate found, reusing existing private key or creating a new one")
  129. // Note: always call LoadOrGenerateKeyFile so that private key is
  130. // reused on next startup if CSR request fails.
  131. keyData, _, err = keyutil.LoadOrGenerateKeyFile(privKeyPath)
  132. if err != nil {
  133. return err
  134. }
  135. }
  136. if err := waitForServer(*bootstrapClientConfig, 1*time.Minute); err != nil {
  137. klog.Warningf("Error waiting for apiserver to come up: %v", err)
  138. }
  139. certData, err := requestNodeCertificate(bootstrapClient.CertificateSigningRequests(), keyData, nodeName)
  140. if err != nil {
  141. return err
  142. }
  143. if _, err := store.Update(certData, keyData); err != nil {
  144. return err
  145. }
  146. if err := os.Remove(privKeyPath); err != nil && !os.IsNotExist(err) {
  147. klog.V(2).Infof("failed cleaning up private key file %q: %v", privKeyPath, err)
  148. }
  149. return writeKubeconfigFromBootstrapping(bootstrapClientConfig, kubeconfigPath, store.CurrentPath())
  150. }
  151. func writeKubeconfigFromBootstrapping(bootstrapClientConfig *restclient.Config, kubeconfigPath, pemPath string) error {
  152. // Get the CA data from the bootstrap client config.
  153. caFile, caData := bootstrapClientConfig.CAFile, []byte{}
  154. if len(caFile) == 0 {
  155. caData = bootstrapClientConfig.CAData
  156. }
  157. // Build resulting kubeconfig.
  158. kubeconfigData := clientcmdapi.Config{
  159. // Define a cluster stanza based on the bootstrap kubeconfig.
  160. Clusters: map[string]*clientcmdapi.Cluster{"default-cluster": {
  161. Server: bootstrapClientConfig.Host,
  162. InsecureSkipTLSVerify: bootstrapClientConfig.Insecure,
  163. CertificateAuthority: caFile,
  164. CertificateAuthorityData: caData,
  165. }},
  166. // Define auth based on the obtained client cert.
  167. AuthInfos: map[string]*clientcmdapi.AuthInfo{"default-auth": {
  168. ClientCertificate: pemPath,
  169. ClientKey: pemPath,
  170. }},
  171. // Define a context that connects the auth info and cluster, and set it as the default
  172. Contexts: map[string]*clientcmdapi.Context{"default-context": {
  173. Cluster: "default-cluster",
  174. AuthInfo: "default-auth",
  175. Namespace: "default",
  176. }},
  177. CurrentContext: "default-context",
  178. }
  179. // Marshal to disk
  180. return clientcmd.WriteToFile(kubeconfigData, kubeconfigPath)
  181. }
  182. func loadRESTClientConfig(kubeconfig string) (*restclient.Config, error) {
  183. // Load structured kubeconfig data from the given path.
  184. loader := &clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfig}
  185. loadedConfig, err := loader.Load()
  186. if err != nil {
  187. return nil, err
  188. }
  189. // Flatten the loaded data to a particular restclient.Config based on the current context.
  190. return clientcmd.NewNonInteractiveClientConfig(
  191. *loadedConfig,
  192. loadedConfig.CurrentContext,
  193. &clientcmd.ConfigOverrides{},
  194. loader,
  195. ).ClientConfig()
  196. }
  197. // isClientConfigStillValid checks the provided kubeconfig to see if it has a valid
  198. // client certificate. It returns true if the kubeconfig is valid, or an error if bootstrapping
  199. // should stop immediately.
  200. func isClientConfigStillValid(kubeconfigPath string) (bool, error) {
  201. _, err := os.Stat(kubeconfigPath)
  202. if os.IsNotExist(err) {
  203. return false, nil
  204. }
  205. if err != nil {
  206. return false, fmt.Errorf("error reading existing bootstrap kubeconfig %s: %v", kubeconfigPath, err)
  207. }
  208. bootstrapClientConfig, err := loadRESTClientConfig(kubeconfigPath)
  209. if err != nil {
  210. utilruntime.HandleError(fmt.Errorf("Unable to read existing bootstrap client config: %v", err))
  211. return false, nil
  212. }
  213. transportConfig, err := bootstrapClientConfig.TransportConfig()
  214. if err != nil {
  215. utilruntime.HandleError(fmt.Errorf("Unable to load transport configuration from existing bootstrap client config: %v", err))
  216. return false, nil
  217. }
  218. // has side effect of populating transport config data fields
  219. if _, err := transport.TLSConfigFor(transportConfig); err != nil {
  220. utilruntime.HandleError(fmt.Errorf("Unable to load TLS configuration from existing bootstrap client config: %v", err))
  221. return false, nil
  222. }
  223. certs, err := certutil.ParseCertsPEM(transportConfig.TLS.CertData)
  224. if err != nil {
  225. utilruntime.HandleError(fmt.Errorf("Unable to load TLS certificates from existing bootstrap client config: %v", err))
  226. return false, nil
  227. }
  228. if len(certs) == 0 {
  229. utilruntime.HandleError(fmt.Errorf("Unable to read TLS certificates from existing bootstrap client config: %v", err))
  230. return false, nil
  231. }
  232. now := time.Now()
  233. for _, cert := range certs {
  234. if now.After(cert.NotAfter) {
  235. utilruntime.HandleError(fmt.Errorf("Part of the existing bootstrap client certificate is expired: %s", cert.NotAfter))
  236. return false, nil
  237. }
  238. }
  239. return true, nil
  240. }
  241. // verifyKeyData returns true if the provided data appears to be a valid private key.
  242. func verifyKeyData(data []byte) bool {
  243. if len(data) == 0 {
  244. return false
  245. }
  246. _, err := keyutil.ParsePrivateKeyPEM(data)
  247. return err == nil
  248. }
  249. func waitForServer(cfg restclient.Config, deadline time.Duration) error {
  250. cfg.NegotiatedSerializer = scheme.Codecs.WithoutConversion()
  251. cfg.Timeout = 1 * time.Second
  252. cli, err := restclient.UnversionedRESTClientFor(&cfg)
  253. if err != nil {
  254. return fmt.Errorf("couldn't create client: %v", err)
  255. }
  256. ctx, cancel := context.WithTimeout(context.TODO(), deadline)
  257. defer cancel()
  258. var connected bool
  259. wait.JitterUntil(func() {
  260. if _, err := cli.Get().AbsPath("/healthz").Do().Raw(); err != nil {
  261. klog.Infof("Failed to connect to apiserver: %v", err)
  262. return
  263. }
  264. cancel()
  265. connected = true
  266. }, 2*time.Second, 0.2, true, ctx.Done())
  267. if !connected {
  268. return errors.New("timed out waiting to connect to apiserver")
  269. }
  270. return nil
  271. }
  272. // requestNodeCertificate will create a certificate signing request for a node
  273. // (Organization and CommonName for the CSR will be set as expected for node
  274. // certificates) and send it to API server, then it will watch the object's
  275. // status, once approved by API server, it will return the API server's issued
  276. // certificate (pem-encoded). If there is any errors, or the watch timeouts, it
  277. // will return an error. This is intended for use on nodes (kubelet and
  278. // kubeadm).
  279. func requestNodeCertificate(client certificatesv1beta1.CertificateSigningRequestInterface, privateKeyData []byte, nodeName types.NodeName) (certData []byte, err error) {
  280. subject := &pkix.Name{
  281. Organization: []string{"system:nodes"},
  282. CommonName: "system:node:" + string(nodeName),
  283. }
  284. privateKey, err := keyutil.ParsePrivateKeyPEM(privateKeyData)
  285. if err != nil {
  286. return nil, fmt.Errorf("invalid private key for certificate request: %v", err)
  287. }
  288. csrData, err := certutil.MakeCSR(privateKey, subject, nil, nil)
  289. if err != nil {
  290. return nil, fmt.Errorf("unable to generate certificate request: %v", err)
  291. }
  292. usages := []certificates.KeyUsage{
  293. certificates.UsageDigitalSignature,
  294. certificates.UsageKeyEncipherment,
  295. certificates.UsageClientAuth,
  296. }
  297. name := digestedName(privateKeyData, subject, usages)
  298. req, err := csr.RequestCertificate(client, csrData, name, usages, privateKey)
  299. if err != nil {
  300. return nil, err
  301. }
  302. ctx, cancel := context.WithTimeout(context.Background(), 3600*time.Second)
  303. defer cancel()
  304. return csr.WaitForCertificate(ctx, client, req)
  305. }
  306. // This digest should include all the relevant pieces of the CSR we care about.
  307. // We can't direcly hash the serialized CSR because of random padding that we
  308. // regenerate every loop and we include usages which are not contained in the
  309. // CSR. This needs to be kept up to date as we add new fields to the node
  310. // certificates and with ensureCompatible.
  311. func digestedName(privateKeyData []byte, subject *pkix.Name, usages []certificates.KeyUsage) string {
  312. hash := sha512.New512_256()
  313. // Here we make sure two different inputs can't write the same stream
  314. // to the hash. This delimiter is not in the base64.URLEncoding
  315. // alphabet so there is no way to have spill over collisions. Without
  316. // it 'CN:foo,ORG:bar' hashes to the same value as 'CN:foob,ORG:ar'
  317. const delimiter = '|'
  318. encode := base64.RawURLEncoding.EncodeToString
  319. write := func(data []byte) {
  320. hash.Write([]byte(encode(data)))
  321. hash.Write([]byte{delimiter})
  322. }
  323. write(privateKeyData)
  324. write([]byte(subject.CommonName))
  325. for _, v := range subject.Organization {
  326. write([]byte(v))
  327. }
  328. for _, v := range usages {
  329. write([]byte(v))
  330. }
  331. return "node-csr-" + encode(hash.Sum(nil))
  332. }