bootstrap.go 14 KB

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