bootstrap.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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 app
  14. import (
  15. "crypto/x509/pkix"
  16. "fmt"
  17. "io/ioutil"
  18. _ "net/http/pprof"
  19. "os"
  20. "path/filepath"
  21. "github.com/golang/glog"
  22. "k8s.io/kubernetes/pkg/api"
  23. "k8s.io/kubernetes/pkg/api/unversioned"
  24. "k8s.io/kubernetes/pkg/apis/certificates"
  25. unversionedcertificates "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned"
  26. "k8s.io/kubernetes/pkg/client/restclient"
  27. "k8s.io/kubernetes/pkg/client/unversioned/clientcmd"
  28. clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api"
  29. "k8s.io/kubernetes/pkg/fields"
  30. utilcertificates "k8s.io/kubernetes/pkg/util/certificates"
  31. "k8s.io/kubernetes/pkg/util/crypto"
  32. "k8s.io/kubernetes/pkg/watch"
  33. )
  34. const (
  35. defaultKubeletClientCertificateFile = "kubelet-client.crt"
  36. defaultKubeletClientKeyFile = "kubelet-client.key"
  37. )
  38. // bootstrapClientCert requests a client cert for kubelet if the kubeconfigPath file does not exist.
  39. // The kubeconfig at bootstrapPath is used to request a client certificate from the API server.
  40. // On success, a kubeconfig file referencing the generated key and obtained certificate is written to kubeconfigPath.
  41. // The certificate and key file are stored in certDir.
  42. func bootstrapClientCert(kubeconfigPath string, bootstrapPath string, certDir string, nodeName string) error {
  43. // Short-circuit if the kubeconfig file already exists.
  44. // TODO: inspect the kubeconfig, ensure a rest client can be built from it, verify client cert expiration, etc.
  45. _, err := os.Stat(kubeconfigPath)
  46. if err == nil {
  47. glog.V(2).Infof("Kubeconfig %s exists, skipping bootstrap", kubeconfigPath)
  48. return nil
  49. }
  50. if !os.IsNotExist(err) {
  51. glog.Errorf("Error reading kubeconfig %s, skipping bootstrap: %v", kubeconfigPath, err)
  52. return err
  53. }
  54. glog.V(2).Info("Using bootstrap kubeconfig to generate TLS client cert, key and kubeconfig file")
  55. bootstrapClientConfig, err := loadRESTClientConfig(bootstrapPath)
  56. if err != nil {
  57. return fmt.Errorf("unable to load bootstrap kubeconfig: %v", err)
  58. }
  59. bootstrapClient, err := unversionedcertificates.NewForConfig(bootstrapClientConfig)
  60. if err != nil {
  61. return fmt.Errorf("unable to create certificates signing request client: %v", err)
  62. }
  63. success := false
  64. // Get the private key.
  65. keyPath, err := filepath.Abs(filepath.Join(certDir, defaultKubeletClientKeyFile))
  66. if err != nil {
  67. return fmt.Errorf("unable to build bootstrap key path: %v", err)
  68. }
  69. keyData, generatedKeyFile, err := loadOrGenerateKeyFile(keyPath)
  70. if err != nil {
  71. return err
  72. }
  73. if generatedKeyFile {
  74. defer func() {
  75. if !success {
  76. if err := os.Remove(keyPath); err != nil {
  77. glog.Warningf("Cannot clean up the key file %q: %v", keyPath, err)
  78. }
  79. }
  80. }()
  81. }
  82. // Get the cert.
  83. certPath, err := filepath.Abs(filepath.Join(certDir, defaultKubeletClientCertificateFile))
  84. if err != nil {
  85. return fmt.Errorf("unable to build bootstrap client cert path: %v", err)
  86. }
  87. certData, err := RequestClientCertificate(bootstrapClient.CertificateSigningRequests(), keyData, nodeName)
  88. if err != nil {
  89. return err
  90. }
  91. if err := crypto.WriteCertToPath(certPath, certData); err != nil {
  92. return err
  93. }
  94. defer func() {
  95. if !success {
  96. if err := os.Remove(certPath); err != nil {
  97. glog.Warningf("Cannot clean up the cert file %q: %v", certPath, err)
  98. }
  99. }
  100. }()
  101. // Get the CA data from the bootstrap client config.
  102. caFile, caData := bootstrapClientConfig.CAFile, []byte{}
  103. if len(caFile) == 0 {
  104. caData = bootstrapClientConfig.CAData
  105. }
  106. // Build resulting kubeconfig.
  107. kubeconfigData := clientcmdapi.Config{
  108. // Define a cluster stanza based on the bootstrap kubeconfig.
  109. Clusters: map[string]*clientcmdapi.Cluster{"default-cluster": {
  110. Server: bootstrapClientConfig.Host,
  111. InsecureSkipTLSVerify: bootstrapClientConfig.Insecure,
  112. CertificateAuthority: caFile,
  113. CertificateAuthorityData: caData,
  114. }},
  115. // Define auth based on the obtained client cert.
  116. AuthInfos: map[string]*clientcmdapi.AuthInfo{"default-auth": {
  117. ClientCertificate: certPath,
  118. ClientKey: keyPath,
  119. }},
  120. // Define a context that connects the auth info and cluster, and set it as the default
  121. Contexts: map[string]*clientcmdapi.Context{"default-context": {
  122. Cluster: "default-cluster",
  123. AuthInfo: "default-auth",
  124. Namespace: "default",
  125. }},
  126. CurrentContext: "default-context",
  127. }
  128. // Marshal to disk
  129. if err := clientcmd.WriteToFile(kubeconfigData, kubeconfigPath); err != nil {
  130. return err
  131. }
  132. success = true
  133. return nil
  134. }
  135. func loadRESTClientConfig(kubeconfig string) (*restclient.Config, error) {
  136. // Load structured kubeconfig data from the given path.
  137. loader := &clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfig}
  138. loadedConfig, err := loader.Load()
  139. if err != nil {
  140. return nil, err
  141. }
  142. // Flatten the loaded data to a particular restclient.Config based on the current context.
  143. return clientcmd.NewNonInteractiveClientConfig(
  144. *loadedConfig,
  145. loadedConfig.CurrentContext,
  146. &clientcmd.ConfigOverrides{},
  147. loader,
  148. ).ClientConfig()
  149. }
  150. func loadOrGenerateKeyFile(keyPath string) (data []byte, wasGenerated bool, err error) {
  151. loadedData, err := ioutil.ReadFile(keyPath)
  152. if err == nil {
  153. return loadedData, false, err
  154. }
  155. if !os.IsNotExist(err) {
  156. return nil, false, fmt.Errorf("error loading key from %s: %v", keyPath, err)
  157. }
  158. generatedData, err := utilcertificates.GeneratePrivateKey()
  159. if err != nil {
  160. return nil, false, fmt.Errorf("error generating key: %v", err)
  161. }
  162. if err := crypto.WriteKeyToPath(keyPath, generatedData); err != nil {
  163. return nil, false, fmt.Errorf("error writing key to %s: %v", keyPath, err)
  164. }
  165. return generatedData, true, nil
  166. }
  167. // RequestClientCertificate will create a certificate signing request and send it to API server,
  168. // then it will watch the object's status, once approved by API server, it will return the API
  169. // server's issued certificate (pem-encoded). If there is any errors, or the watch timeouts,
  170. // it will return an error.
  171. func RequestClientCertificate(client unversionedcertificates.CertificateSigningRequestInterface, privateKeyData []byte, nodeName string) (certData []byte, err error) {
  172. subject := &pkix.Name{
  173. Organization: []string{"system:nodes"},
  174. CommonName: fmt.Sprintf("system:node:%s", nodeName),
  175. }
  176. privateKey, err := utilcertificates.ParsePrivateKey(privateKeyData)
  177. if err != nil {
  178. return nil, fmt.Errorf("invalid private key for certificate request: %v", err)
  179. }
  180. csr, err := utilcertificates.NewCertificateRequest(privateKey, subject, nil, nil)
  181. if err != nil {
  182. return nil, fmt.Errorf("unable to generate certificate request: %v", err)
  183. }
  184. req, err := client.Create(&certificates.CertificateSigningRequest{
  185. // Username, UID, Groups will be injected by API server.
  186. TypeMeta: unversioned.TypeMeta{Kind: "CertificateSigningRequest"},
  187. ObjectMeta: api.ObjectMeta{GenerateName: "csr-"},
  188. // TODO: For now, this is a request for a certificate with allowed usage of "TLS Web Client Authentication".
  189. // Need to figure out whether/how to surface the allowed usage in the spec.
  190. Spec: certificates.CertificateSigningRequestSpec{Request: csr},
  191. })
  192. if err != nil {
  193. return nil, fmt.Errorf("cannot create certificate signing request: %v", err)
  194. }
  195. // Make a default timeout = 3600s.
  196. var defaultTimeoutSeconds int64 = 3600
  197. resultCh, err := client.Watch(api.ListOptions{
  198. Watch: true,
  199. TimeoutSeconds: &defaultTimeoutSeconds,
  200. FieldSelector: fields.OneTermEqualSelector("metadata.name", req.Name),
  201. })
  202. if err != nil {
  203. return nil, fmt.Errorf("cannot watch on the certificate signing request: %v", err)
  204. }
  205. var status certificates.CertificateSigningRequestStatus
  206. ch := resultCh.ResultChan()
  207. for {
  208. event, ok := <-ch
  209. if !ok {
  210. break
  211. }
  212. if event.Type == watch.Modified || event.Type == watch.Added {
  213. if event.Object.(*certificates.CertificateSigningRequest).UID != req.UID {
  214. continue
  215. }
  216. status = event.Object.(*certificates.CertificateSigningRequest).Status
  217. for _, c := range status.Conditions {
  218. if c.Type == certificates.CertificateDenied {
  219. return nil, fmt.Errorf("certificate signing request is not approved, reason: %v, message: %v", c.Reason, c.Message)
  220. }
  221. if c.Type == certificates.CertificateApproved && status.Certificate != nil {
  222. return status.Certificate, nil
  223. }
  224. }
  225. }
  226. }
  227. return nil, fmt.Errorf("watch channel closed")
  228. }