kubeconfig.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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 := certutil.Config{
  160. CommonName: spec.ClientName,
  161. Organization: spec.ClientCertAuth.Organizations,
  162. Usages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
  163. }
  164. clientCert, clientKey, err := pkiutil.NewCertAndKey(spec.CACert, spec.ClientCertAuth.CAKey, &clientCertConfig)
  165. if err != nil {
  166. return nil, errors.Wrapf(err, "failure while creating %s client certificate", spec.ClientName)
  167. }
  168. encodedClientKey, err := keyutil.MarshalPrivateKeyToPEM(clientKey)
  169. if err != nil {
  170. return nil, errors.Wrapf(err, "failed to marshal private key to PEM")
  171. }
  172. // create a kubeconfig with the client certs
  173. return kubeconfigutil.CreateWithCerts(
  174. spec.APIServer,
  175. clustername,
  176. spec.ClientName,
  177. pkiutil.EncodeCertPEM(spec.CACert),
  178. encodedClientKey,
  179. pkiutil.EncodeCertPEM(clientCert),
  180. ), nil
  181. }
  182. // validateKubeConfig check if the kubeconfig file exist and has the expected CA and server URL
  183. func validateKubeConfig(outDir, filename string, config *clientcmdapi.Config) error {
  184. kubeConfigFilePath := filepath.Join(outDir, filename)
  185. if _, err := os.Stat(kubeConfigFilePath); err != nil {
  186. return err
  187. }
  188. // The kubeconfig already exists, let's check if it has got the same CA and server URL
  189. currentConfig, err := clientcmd.LoadFromFile(kubeConfigFilePath)
  190. if err != nil {
  191. return errors.Wrapf(err, "failed to load kubeconfig file %s that already exists on disk", kubeConfigFilePath)
  192. }
  193. expectedCtx := config.CurrentContext
  194. expectedCluster := config.Contexts[expectedCtx].Cluster
  195. currentCtx := currentConfig.CurrentContext
  196. currentCluster := currentConfig.Contexts[currentCtx].Cluster
  197. // 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
  198. if !bytes.Equal(currentConfig.Clusters[currentCluster].CertificateAuthorityData, config.Clusters[expectedCluster].CertificateAuthorityData) {
  199. return errors.Errorf("a kubeconfig file %q exists already but has got the wrong CA cert", kubeConfigFilePath)
  200. }
  201. // 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
  202. if currentConfig.Clusters[currentCluster].Server != config.Clusters[expectedCluster].Server {
  203. return errors.Errorf("a kubeconfig file %q exists already but has got the wrong API Server URL", kubeConfigFilePath)
  204. }
  205. return nil
  206. }
  207. // createKubeConfigFileIfNotExists saves the KubeConfig object into a file if there isn't any file at the given path.
  208. // If there already is a kubeconfig file at the given path; kubeadm tries to load it and check if the values in the
  209. // existing and the expected config equals. If they do; kubeadm will just skip writing the file as it's up-to-date,
  210. // but if a file exists but has old content or isn't a kubeconfig file, this function returns an error.
  211. func createKubeConfigFileIfNotExists(outDir, filename string, config *clientcmdapi.Config) error {
  212. kubeConfigFilePath := filepath.Join(outDir, filename)
  213. err := validateKubeConfig(outDir, filename, config)
  214. if err != nil {
  215. // Check if the file exist, and if it doesn't, just write it to disk
  216. if !os.IsNotExist(err) {
  217. return err
  218. }
  219. fmt.Printf("[kubeconfig] Writing %q kubeconfig file\n", filename)
  220. err = kubeconfigutil.WriteToDisk(kubeConfigFilePath, config)
  221. if err != nil {
  222. return errors.Wrapf(err, "failed to save kubeconfig file %q on disk", kubeConfigFilePath)
  223. }
  224. return nil
  225. }
  226. // kubeadm doesn't validate the existing kubeconfig file more than this (kubeadm trusts the client certs to be valid)
  227. // Basically, if we find a kubeconfig file with the same path; the same CA cert and the same server URL;
  228. // kubeadm thinks those files are equal and doesn't bother writing a new file
  229. fmt.Printf("[kubeconfig] Using existing kubeconfig file: %q\n", kubeConfigFilePath)
  230. return nil
  231. }
  232. // WriteKubeConfigWithClientCert writes a kubeconfig file - with a client certificate as authentication info - to the given writer.
  233. func WriteKubeConfigWithClientCert(out io.Writer, cfg *kubeadmapi.InitConfiguration, clientName string, organizations []string) error {
  234. // creates the KubeConfigSpecs, actualized for the current InitConfiguration
  235. caCert, caKey, err := pkiutil.TryLoadCertAndKeyFromDisk(cfg.CertificatesDir, kubeadmconstants.CACertAndKeyBaseName)
  236. if err != nil {
  237. return errors.Wrap(err, "couldn't create a kubeconfig; the CA files couldn't be loaded")
  238. }
  239. controlPlaneEndpoint, err := kubeadmutil.GetControlPlaneEndpoint(cfg.ControlPlaneEndpoint, &cfg.LocalAPIEndpoint)
  240. if err != nil {
  241. return err
  242. }
  243. spec := &kubeConfigSpec{
  244. ClientName: clientName,
  245. APIServer: controlPlaneEndpoint,
  246. CACert: caCert,
  247. ClientCertAuth: &clientCertAuth{
  248. CAKey: caKey,
  249. Organizations: organizations,
  250. },
  251. }
  252. return writeKubeConfigFromSpec(out, spec, cfg.ClusterName)
  253. }
  254. // WriteKubeConfigWithToken writes a kubeconfig file - with a token as client authentication info - to the given writer.
  255. func WriteKubeConfigWithToken(out io.Writer, cfg *kubeadmapi.InitConfiguration, clientName, token string) error {
  256. // creates the KubeConfigSpecs, actualized for the current InitConfiguration
  257. caCert, _, err := pkiutil.TryLoadCertAndKeyFromDisk(cfg.CertificatesDir, kubeadmconstants.CACertAndKeyBaseName)
  258. if err != nil {
  259. return errors.Wrap(err, "couldn't create a kubeconfig; the CA files couldn't be loaded")
  260. }
  261. controlPlaneEndpoint, err := kubeadmutil.GetControlPlaneEndpoint(cfg.ControlPlaneEndpoint, &cfg.LocalAPIEndpoint)
  262. if err != nil {
  263. return err
  264. }
  265. spec := &kubeConfigSpec{
  266. ClientName: clientName,
  267. APIServer: controlPlaneEndpoint,
  268. CACert: caCert,
  269. TokenAuth: &tokenAuth{
  270. Token: token,
  271. },
  272. }
  273. return writeKubeConfigFromSpec(out, spec, cfg.ClusterName)
  274. }
  275. // writeKubeConfigFromSpec creates a kubeconfig object from a kubeConfigSpec and writes it to the given writer.
  276. func writeKubeConfigFromSpec(out io.Writer, spec *kubeConfigSpec, clustername string) error {
  277. // builds the KubeConfig object
  278. config, err := buildKubeConfigFromSpec(spec, clustername)
  279. if err != nil {
  280. return err
  281. }
  282. // writes the kubeconfig to disk if it not exists
  283. configBytes, err := clientcmd.Write(*config)
  284. if err != nil {
  285. return errors.Wrap(err, "failure while serializing admin kubeconfig")
  286. }
  287. fmt.Fprintln(out, string(configBytes))
  288. return nil
  289. }
  290. // ValidateKubeconfigsForExternalCA check if the kubeconfig file exist and has the expected CA and server URL using kubeadmapi.InitConfiguration.
  291. func ValidateKubeconfigsForExternalCA(outDir string, cfg *kubeadmapi.InitConfiguration) error {
  292. kubeConfigFileNames := []string{
  293. kubeadmconstants.AdminKubeConfigFileName,
  294. kubeadmconstants.KubeletKubeConfigFileName,
  295. kubeadmconstants.ControllerManagerKubeConfigFileName,
  296. kubeadmconstants.SchedulerKubeConfigFileName,
  297. }
  298. // Creates a kubeconfig file with the target CA and server URL
  299. // to be used as a input for validating user provided kubeconfig files
  300. caCert, err := pkiutil.TryLoadCertFromDisk(cfg.CertificatesDir, kubeadmconstants.CACertAndKeyBaseName)
  301. if err != nil {
  302. return errors.Wrapf(err, "the CA file couldn't be loaded")
  303. }
  304. controlPlaneEndpoint, err := kubeadmutil.GetControlPlaneEndpoint(cfg.ControlPlaneEndpoint, &cfg.LocalAPIEndpoint)
  305. if err != nil {
  306. return err
  307. }
  308. validationConfig := kubeconfigutil.CreateBasic(controlPlaneEndpoint, "dummy", "dummy", pkiutil.EncodeCertPEM(caCert))
  309. // validate user provided kubeconfig files
  310. for _, kubeConfigFileName := range kubeConfigFileNames {
  311. if err = validateKubeConfig(outDir, kubeConfigFileName, validationConfig); err != nil {
  312. return errors.Wrapf(err, "the %s file does not exists or it is not valid", kubeConfigFileName)
  313. }
  314. }
  315. return nil
  316. }