kubeconfig.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. /*
  2. Copyright 2018 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 kubeconfig
  14. import (
  15. "bytes"
  16. "crypto"
  17. "crypto/x509"
  18. "fmt"
  19. "io"
  20. "os"
  21. "path/filepath"
  22. "github.com/pkg/errors"
  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. "k8s.io/client-go/util/keyutil"
  27. "k8s.io/klog"
  28. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  29. kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  30. kubeadmutil "k8s.io/kubernetes/cmd/kubeadm/app/util"
  31. pkiutil "k8s.io/kubernetes/cmd/kubeadm/app/util/pkiutil"
  32. kubeconfigutil "k8s.io/kubernetes/cmd/kubeadm/app/util/kubeconfig"
  33. )
  34. // clientCertAuth struct holds info required to build a client certificate to provide authentication info in a kubeconfig object
  35. type clientCertAuth struct {
  36. CAKey crypto.Signer
  37. Organizations []string
  38. }
  39. // tokenAuth struct holds info required to use a token to provide authentication info in a kubeconfig object
  40. type tokenAuth struct {
  41. Token string
  42. }
  43. // kubeConfigSpec struct holds info required to build a KubeConfig object
  44. type kubeConfigSpec struct {
  45. CACert *x509.Certificate
  46. APIServer string
  47. ClientName string
  48. TokenAuth *tokenAuth
  49. ClientCertAuth *clientCertAuth
  50. }
  51. // CreateJoinControlPlaneKubeConfigFiles will create and write to disk the kubeconfig files required by kubeadm
  52. // join --control-plane workflow, plus the admin kubeconfig file used by the administrator and kubeadm itself; the
  53. // kubelet.conf file must not be created because it will be created and signed by the kubelet TLS bootstrap process.
  54. // If any kubeconfig files already exists, it used only if evaluated equal; otherwise an error is returned.
  55. func CreateJoinControlPlaneKubeConfigFiles(outDir string, cfg *kubeadmapi.InitConfiguration) error {
  56. return createKubeConfigFiles(
  57. outDir,
  58. cfg,
  59. kubeadmconstants.AdminKubeConfigFileName,
  60. kubeadmconstants.ControllerManagerKubeConfigFileName,
  61. kubeadmconstants.SchedulerKubeConfigFileName,
  62. )
  63. }
  64. // CreateKubeConfigFile creates a kubeconfig file.
  65. // If the kubeconfig file already exists, it is used only if evaluated equal; otherwise an error is returned.
  66. func CreateKubeConfigFile(kubeConfigFileName string, outDir string, cfg *kubeadmapi.InitConfiguration) error {
  67. klog.V(1).Infof("creating kubeconfig file for %s", kubeConfigFileName)
  68. return createKubeConfigFiles(outDir, cfg, kubeConfigFileName)
  69. }
  70. // createKubeConfigFiles creates all the requested kubeconfig files.
  71. // If kubeconfig files already exists, they are used only if evaluated equal; otherwise an error is returned.
  72. func createKubeConfigFiles(outDir string, cfg *kubeadmapi.InitConfiguration, kubeConfigFileNames ...string) error {
  73. // gets the KubeConfigSpecs, actualized for the current InitConfiguration
  74. specs, err := getKubeConfigSpecs(cfg)
  75. if err != nil {
  76. return err
  77. }
  78. for _, kubeConfigFileName := range kubeConfigFileNames {
  79. // retrieves the KubeConfigSpec for given kubeConfigFileName
  80. spec, exists := specs[kubeConfigFileName]
  81. if !exists {
  82. return errors.Errorf("couldn't retrieve KubeConfigSpec for %s", kubeConfigFileName)
  83. }
  84. // builds the KubeConfig object
  85. config, err := buildKubeConfigFromSpec(spec, cfg.ClusterName)
  86. if err != nil {
  87. return err
  88. }
  89. // writes the kubeconfig to disk if it not exists
  90. if err = createKubeConfigFileIfNotExists(outDir, kubeConfigFileName, config); err != nil {
  91. return err
  92. }
  93. }
  94. return nil
  95. }
  96. // getKubeConfigSpecs returns all KubeConfigSpecs actualized to the context of the current InitConfiguration
  97. // NB. this methods holds the information about how kubeadm creates kubeconfig files.
  98. func getKubeConfigSpecs(cfg *kubeadmapi.InitConfiguration) (map[string]*kubeConfigSpec, error) {
  99. caCert, caKey, err := pkiutil.TryLoadCertAndKeyFromDisk(cfg.CertificatesDir, kubeadmconstants.CACertAndKeyBaseName)
  100. if err != nil {
  101. return nil, errors.Wrap(err, "couldn't create a kubeconfig; the CA files couldn't be loaded")
  102. }
  103. controlPlaneEndpoint, err := kubeadmutil.GetControlPlaneEndpoint(cfg.ControlPlaneEndpoint, &cfg.LocalAPIEndpoint)
  104. if err != nil {
  105. return nil, err
  106. }
  107. var kubeConfigSpec = map[string]*kubeConfigSpec{
  108. kubeadmconstants.AdminKubeConfigFileName: {
  109. CACert: caCert,
  110. APIServer: controlPlaneEndpoint,
  111. ClientName: "kubernetes-admin",
  112. ClientCertAuth: &clientCertAuth{
  113. CAKey: caKey,
  114. Organizations: []string{kubeadmconstants.SystemPrivilegedGroup},
  115. },
  116. },
  117. kubeadmconstants.KubeletKubeConfigFileName: {
  118. CACert: caCert,
  119. APIServer: controlPlaneEndpoint,
  120. ClientName: fmt.Sprintf("%s%s", kubeadmconstants.NodesUserPrefix, cfg.NodeRegistration.Name),
  121. ClientCertAuth: &clientCertAuth{
  122. CAKey: caKey,
  123. Organizations: []string{kubeadmconstants.NodesGroup},
  124. },
  125. },
  126. kubeadmconstants.ControllerManagerKubeConfigFileName: {
  127. CACert: caCert,
  128. APIServer: controlPlaneEndpoint,
  129. ClientName: kubeadmconstants.ControllerManagerUser,
  130. ClientCertAuth: &clientCertAuth{
  131. CAKey: caKey,
  132. },
  133. },
  134. kubeadmconstants.SchedulerKubeConfigFileName: {
  135. CACert: caCert,
  136. APIServer: controlPlaneEndpoint,
  137. ClientName: kubeadmconstants.SchedulerUser,
  138. ClientCertAuth: &clientCertAuth{
  139. CAKey: caKey,
  140. },
  141. },
  142. }
  143. return kubeConfigSpec, nil
  144. }
  145. // buildKubeConfigFromSpec creates a kubeconfig object for the given kubeConfigSpec
  146. func buildKubeConfigFromSpec(spec *kubeConfigSpec, clustername string) (*clientcmdapi.Config, error) {
  147. // If this kubeconfig should use token
  148. if spec.TokenAuth != nil {
  149. // create a kubeconfig with a token
  150. return kubeconfigutil.CreateWithToken(
  151. spec.APIServer,
  152. clustername,
  153. spec.ClientName,
  154. pkiutil.EncodeCertPEM(spec.CACert),
  155. spec.TokenAuth.Token,
  156. ), nil
  157. }
  158. // otherwise, create a client certs
  159. clientCertConfig := pkiutil.CertConfig{
  160. Config: certutil.Config{
  161. CommonName: spec.ClientName,
  162. Organization: spec.ClientCertAuth.Organizations,
  163. Usages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
  164. },
  165. }
  166. clientCert, clientKey, err := pkiutil.NewCertAndKey(spec.CACert, spec.ClientCertAuth.CAKey, &clientCertConfig)
  167. if err != nil {
  168. return nil, errors.Wrapf(err, "failure while creating %s client certificate", spec.ClientName)
  169. }
  170. encodedClientKey, err := keyutil.MarshalPrivateKeyToPEM(clientKey)
  171. if err != nil {
  172. return nil, errors.Wrapf(err, "failed to marshal private key to PEM")
  173. }
  174. // create a kubeconfig with the client certs
  175. return kubeconfigutil.CreateWithCerts(
  176. spec.APIServer,
  177. clustername,
  178. spec.ClientName,
  179. pkiutil.EncodeCertPEM(spec.CACert),
  180. encodedClientKey,
  181. pkiutil.EncodeCertPEM(clientCert),
  182. ), nil
  183. }
  184. // validateKubeConfig check if the kubeconfig file exist and has the expected CA and server URL
  185. func validateKubeConfig(outDir, filename string, config *clientcmdapi.Config) error {
  186. kubeConfigFilePath := filepath.Join(outDir, filename)
  187. if _, err := os.Stat(kubeConfigFilePath); err != nil {
  188. return err
  189. }
  190. // The kubeconfig already exists, let's check if it has got the same CA and server URL
  191. currentConfig, err := clientcmd.LoadFromFile(kubeConfigFilePath)
  192. if err != nil {
  193. return errors.Wrapf(err, "failed to load kubeconfig file %s that already exists on disk", kubeConfigFilePath)
  194. }
  195. expectedCtx, exists := config.Contexts[config.CurrentContext]
  196. if !exists {
  197. return errors.Errorf("failed to find expected context %s", config.CurrentContext)
  198. }
  199. expectedCluster := expectedCtx.Cluster
  200. currentCtx, exists := currentConfig.Contexts[currentConfig.CurrentContext]
  201. if !exists {
  202. return errors.Errorf("failed to find CurrentContext in Contexts of the kubeconfig file %s", kubeConfigFilePath)
  203. }
  204. currentCluster := currentCtx.Cluster
  205. if currentConfig.Clusters[currentCluster] == nil {
  206. return errors.Errorf("failed to find the given CurrentContext Cluster in Clusters of the kubeconfig file %s", kubeConfigFilePath)
  207. }
  208. // Make sure the compared CAs are whitespace-trimmed. The function clientcmd.LoadFromFile() just decodes
  209. // the base64 CA and places it raw in the v1.Config object. In case the user has extra whitespace
  210. // in the CA they used to create a kubeconfig this comparison to a generated v1.Config will otherwise fail.
  211. caCurrent := bytes.TrimSpace(currentConfig.Clusters[currentCluster].CertificateAuthorityData)
  212. caExpected := bytes.TrimSpace(config.Clusters[expectedCluster].CertificateAuthorityData)
  213. // If the current CA cert on disk doesn't match the expected CA cert, error out because we have a file, but it's stale
  214. if !bytes.Equal(caCurrent, caExpected) {
  215. return errors.Errorf("a kubeconfig file %q exists already but has got the wrong CA cert", kubeConfigFilePath)
  216. }
  217. // If the current API Server location on disk doesn't match the expected API server, error out because we have a file, but it's stale
  218. if currentConfig.Clusters[currentCluster].Server != config.Clusters[expectedCluster].Server {
  219. return errors.Errorf("a kubeconfig file %q exists already but has got the wrong API Server URL", kubeConfigFilePath)
  220. }
  221. return nil
  222. }
  223. // createKubeConfigFileIfNotExists saves the KubeConfig object into a file if there isn't any file at the given path.
  224. // If there already is a kubeconfig file at the given path; kubeadm tries to load it and check if the values in the
  225. // existing and the expected config equals. If they do; kubeadm will just skip writing the file as it's up-to-date,
  226. // but if a file exists but has old content or isn't a kubeconfig file, this function returns an error.
  227. func createKubeConfigFileIfNotExists(outDir, filename string, config *clientcmdapi.Config) error {
  228. kubeConfigFilePath := filepath.Join(outDir, filename)
  229. err := validateKubeConfig(outDir, filename, config)
  230. if err != nil {
  231. // Check if the file exist, and if it doesn't, just write it to disk
  232. if !os.IsNotExist(err) {
  233. return err
  234. }
  235. fmt.Printf("[kubeconfig] Writing %q kubeconfig file\n", filename)
  236. err = kubeconfigutil.WriteToDisk(kubeConfigFilePath, config)
  237. if err != nil {
  238. return errors.Wrapf(err, "failed to save kubeconfig file %q on disk", kubeConfigFilePath)
  239. }
  240. return nil
  241. }
  242. // kubeadm doesn't validate the existing kubeconfig file more than this (kubeadm trusts the client certs to be valid)
  243. // Basically, if we find a kubeconfig file with the same path; the same CA cert and the same server URL;
  244. // kubeadm thinks those files are equal and doesn't bother writing a new file
  245. fmt.Printf("[kubeconfig] Using existing kubeconfig file: %q\n", kubeConfigFilePath)
  246. return nil
  247. }
  248. // WriteKubeConfigWithClientCert writes a kubeconfig file - with a client certificate as authentication info - to the given writer.
  249. func WriteKubeConfigWithClientCert(out io.Writer, cfg *kubeadmapi.InitConfiguration, clientName string, organizations []string) error {
  250. // creates the KubeConfigSpecs, actualized for the current InitConfiguration
  251. caCert, caKey, err := pkiutil.TryLoadCertAndKeyFromDisk(cfg.CertificatesDir, kubeadmconstants.CACertAndKeyBaseName)
  252. if err != nil {
  253. return errors.Wrap(err, "couldn't create a kubeconfig; the CA files couldn't be loaded")
  254. }
  255. controlPlaneEndpoint, err := kubeadmutil.GetControlPlaneEndpoint(cfg.ControlPlaneEndpoint, &cfg.LocalAPIEndpoint)
  256. if err != nil {
  257. return err
  258. }
  259. spec := &kubeConfigSpec{
  260. ClientName: clientName,
  261. APIServer: controlPlaneEndpoint,
  262. CACert: caCert,
  263. ClientCertAuth: &clientCertAuth{
  264. CAKey: caKey,
  265. Organizations: organizations,
  266. },
  267. }
  268. return writeKubeConfigFromSpec(out, spec, cfg.ClusterName)
  269. }
  270. // WriteKubeConfigWithToken writes a kubeconfig file - with a token as client authentication info - to the given writer.
  271. func WriteKubeConfigWithToken(out io.Writer, cfg *kubeadmapi.InitConfiguration, clientName, token string) error {
  272. // creates the KubeConfigSpecs, actualized for the current InitConfiguration
  273. caCert, _, err := pkiutil.TryLoadCertAndKeyFromDisk(cfg.CertificatesDir, kubeadmconstants.CACertAndKeyBaseName)
  274. if err != nil {
  275. return errors.Wrap(err, "couldn't create a kubeconfig; the CA files couldn't be loaded")
  276. }
  277. controlPlaneEndpoint, err := kubeadmutil.GetControlPlaneEndpoint(cfg.ControlPlaneEndpoint, &cfg.LocalAPIEndpoint)
  278. if err != nil {
  279. return err
  280. }
  281. spec := &kubeConfigSpec{
  282. ClientName: clientName,
  283. APIServer: controlPlaneEndpoint,
  284. CACert: caCert,
  285. TokenAuth: &tokenAuth{
  286. Token: token,
  287. },
  288. }
  289. return writeKubeConfigFromSpec(out, spec, cfg.ClusterName)
  290. }
  291. // writeKubeConfigFromSpec creates a kubeconfig object from a kubeConfigSpec and writes it to the given writer.
  292. func writeKubeConfigFromSpec(out io.Writer, spec *kubeConfigSpec, clustername string) error {
  293. // builds the KubeConfig object
  294. config, err := buildKubeConfigFromSpec(spec, clustername)
  295. if err != nil {
  296. return err
  297. }
  298. // writes the kubeconfig to disk if it not exists
  299. configBytes, err := clientcmd.Write(*config)
  300. if err != nil {
  301. return errors.Wrap(err, "failure while serializing admin kubeconfig")
  302. }
  303. fmt.Fprintln(out, string(configBytes))
  304. return nil
  305. }
  306. // ValidateKubeconfigsForExternalCA check if the kubeconfig file exist and has the expected CA and server URL using kubeadmapi.InitConfiguration.
  307. func ValidateKubeconfigsForExternalCA(outDir string, cfg *kubeadmapi.InitConfiguration) error {
  308. kubeConfigFileNames := []string{
  309. kubeadmconstants.AdminKubeConfigFileName,
  310. kubeadmconstants.KubeletKubeConfigFileName,
  311. kubeadmconstants.ControllerManagerKubeConfigFileName,
  312. kubeadmconstants.SchedulerKubeConfigFileName,
  313. }
  314. // Creates a kubeconfig file with the target CA and server URL
  315. // to be used as a input for validating user provided kubeconfig files
  316. caCert, err := pkiutil.TryLoadCertFromDisk(cfg.CertificatesDir, kubeadmconstants.CACertAndKeyBaseName)
  317. if err != nil {
  318. return errors.Wrapf(err, "the CA file couldn't be loaded")
  319. }
  320. controlPlaneEndpoint, err := kubeadmutil.GetControlPlaneEndpoint(cfg.ControlPlaneEndpoint, &cfg.LocalAPIEndpoint)
  321. if err != nil {
  322. return err
  323. }
  324. validationConfig := kubeconfigutil.CreateBasic(controlPlaneEndpoint, "dummy", "dummy", pkiutil.EncodeCertPEM(caCert))
  325. // validate user provided kubeconfig files
  326. for _, kubeConfigFileName := range kubeConfigFileNames {
  327. if err = validateKubeConfig(outDir, kubeConfigFileName, validationConfig); err != nil {
  328. return errors.Wrapf(err, "the %s file does not exists or it is not valid", kubeConfigFileName)
  329. }
  330. }
  331. return nil
  332. }