certs.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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 certs
  14. import (
  15. "crypto"
  16. "crypto/x509"
  17. "fmt"
  18. "os"
  19. "path/filepath"
  20. "github.com/pkg/errors"
  21. "k8s.io/client-go/util/keyutil"
  22. "k8s.io/klog"
  23. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  24. pkiutil "k8s.io/kubernetes/cmd/kubeadm/app/util/pkiutil"
  25. kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  26. )
  27. // CreatePKIAssets will create and write to disk all PKI assets necessary to establish the control plane.
  28. // If the PKI assets already exists in the target folder, they are used only if evaluated equal; otherwise an error is returned.
  29. func CreatePKIAssets(cfg *kubeadmapi.InitConfiguration) error {
  30. klog.V(1).Infoln("creating PKI assets")
  31. // This structure cannot handle multilevel CA hierarchies.
  32. // This isn't a problem right now, but may become one in the future.
  33. var certList Certificates
  34. if cfg.Etcd.Local == nil {
  35. certList = GetCertsWithoutEtcd()
  36. } else {
  37. certList = GetDefaultCertList()
  38. }
  39. certTree, err := certList.AsMap().CertTree()
  40. if err != nil {
  41. return err
  42. }
  43. if err := certTree.CreateTree(cfg); err != nil {
  44. return errors.Wrap(err, "error creating PKI assets")
  45. }
  46. fmt.Printf("[certs] Valid certificates and keys now exist in %q\n", cfg.CertificatesDir)
  47. // Service accounts are not x509 certs, so handled separately
  48. return CreateServiceAccountKeyAndPublicKeyFiles(cfg.CertificatesDir, cfg.ClusterConfiguration.PublicKeyAlgorithm())
  49. }
  50. // CreateServiceAccountKeyAndPublicKeyFiles creates new public/private key files for signing service account users.
  51. // If the sa public/private key files already exist in the target folder, they are used only if evaluated equals; otherwise an error is returned.
  52. func CreateServiceAccountKeyAndPublicKeyFiles(certsDir string, keyType x509.PublicKeyAlgorithm) error {
  53. klog.V(1).Infoln("creating new public/private key files for signing service account users")
  54. _, err := keyutil.PrivateKeyFromFile(filepath.Join(certsDir, kubeadmconstants.ServiceAccountPrivateKeyName))
  55. if err == nil {
  56. // kubeadm doesn't validate the existing certificate key more than this;
  57. // Basically, if we find a key file with the same path kubeadm thinks those files
  58. // are equal and doesn't bother writing a new file
  59. fmt.Printf("[certs] Using the existing %q key\n", kubeadmconstants.ServiceAccountKeyBaseName)
  60. return nil
  61. } else if !os.IsNotExist(err) {
  62. return errors.Wrapf(err, "file %s existed but it could not be loaded properly", kubeadmconstants.ServiceAccountPrivateKeyName)
  63. }
  64. // The key does NOT exist, let's generate it now
  65. key, err := pkiutil.NewPrivateKey(keyType)
  66. if err != nil {
  67. return err
  68. }
  69. // Write .key and .pub files to disk
  70. fmt.Printf("[certs] Generating %q key and public key\n", kubeadmconstants.ServiceAccountKeyBaseName)
  71. if err := pkiutil.WriteKey(certsDir, kubeadmconstants.ServiceAccountKeyBaseName, key); err != nil {
  72. return err
  73. }
  74. return pkiutil.WritePublicKey(certsDir, kubeadmconstants.ServiceAccountKeyBaseName, key.Public())
  75. }
  76. // CreateCACertAndKeyFiles generates and writes out a given certificate authority.
  77. // The certSpec should be one of the variables from this package.
  78. func CreateCACertAndKeyFiles(certSpec *KubeadmCert, cfg *kubeadmapi.InitConfiguration) error {
  79. if certSpec.CAName != "" {
  80. return errors.Errorf("this function should only be used for CAs, but cert %s has CA %s", certSpec.Name, certSpec.CAName)
  81. }
  82. klog.V(1).Infof("creating a new certificate authority for %s", certSpec.Name)
  83. certConfig, err := certSpec.GetConfig(cfg)
  84. if err != nil {
  85. return err
  86. }
  87. caCert, caKey, err := pkiutil.NewCertificateAuthority(certConfig)
  88. if err != nil {
  89. return err
  90. }
  91. return writeCertificateAuthorityFilesIfNotExist(
  92. cfg.CertificatesDir,
  93. certSpec.BaseName,
  94. caCert,
  95. caKey,
  96. )
  97. }
  98. // NewCSR will generate a new CSR and accompanying key
  99. func NewCSR(certSpec *KubeadmCert, cfg *kubeadmapi.InitConfiguration) (*x509.CertificateRequest, crypto.Signer, error) {
  100. certConfig, err := certSpec.GetConfig(cfg)
  101. if err != nil {
  102. return nil, nil, errors.Wrap(err, "failed to retrieve cert configuration")
  103. }
  104. return pkiutil.NewCSRAndKey(certConfig)
  105. }
  106. // CreateCSR creates a certificate signing request
  107. func CreateCSR(certSpec *KubeadmCert, cfg *kubeadmapi.InitConfiguration, path string) error {
  108. csr, key, err := NewCSR(certSpec, cfg)
  109. if err != nil {
  110. return err
  111. }
  112. return writeCSRFilesIfNotExist(path, certSpec.BaseName, csr, key)
  113. }
  114. // CreateCertAndKeyFilesWithCA loads the given certificate authority from disk, then generates and writes out the given certificate and key.
  115. // The certSpec and caCertSpec should both be one of the variables from this package.
  116. func CreateCertAndKeyFilesWithCA(certSpec *KubeadmCert, caCertSpec *KubeadmCert, cfg *kubeadmapi.InitConfiguration) error {
  117. if certSpec.CAName != caCertSpec.Name {
  118. return errors.Errorf("expected CAname for %s to be %q, but was %s", certSpec.Name, certSpec.CAName, caCertSpec.Name)
  119. }
  120. caCert, caKey, err := LoadCertificateAuthority(cfg.CertificatesDir, caCertSpec.BaseName)
  121. if err != nil {
  122. return errors.Wrapf(err, "couldn't load CA certificate %s", caCertSpec.Name)
  123. }
  124. return certSpec.CreateFromCA(cfg, caCert, caKey)
  125. }
  126. // LoadCertificateAuthority tries to load a CA in the given directory with the given name.
  127. func LoadCertificateAuthority(pkiDir string, baseName string) (*x509.Certificate, crypto.Signer, error) {
  128. // Checks if certificate authority exists in the PKI directory
  129. if !pkiutil.CertOrKeyExist(pkiDir, baseName) {
  130. return nil, nil, errors.Errorf("couldn't load %s certificate authority from %s", baseName, pkiDir)
  131. }
  132. // Try to load certificate authority .crt and .key from the PKI directory
  133. caCert, caKey, err := pkiutil.TryLoadCertAndKeyFromDisk(pkiDir, baseName)
  134. if err != nil {
  135. return nil, nil, errors.Wrapf(err, "failure loading %s certificate authority", baseName)
  136. }
  137. // Make sure the loaded CA cert actually is a CA
  138. if !caCert.IsCA {
  139. return nil, nil, errors.Errorf("%s certificate is not a certificate authority", baseName)
  140. }
  141. return caCert, caKey, nil
  142. }
  143. // writeCertificateAuthorityFilesIfNotExist write a new certificate Authority to the given path.
  144. // If there already is a certificate file at the given path; kubeadm tries to load it and check if the values in the
  145. // existing and the expected certificate equals. If they do; kubeadm will just skip writing the file as it's up-to-date,
  146. // otherwise this function returns an error.
  147. func writeCertificateAuthorityFilesIfNotExist(pkiDir string, baseName string, caCert *x509.Certificate, caKey crypto.Signer) error {
  148. // If cert or key exists, we should try to load them
  149. if pkiutil.CertOrKeyExist(pkiDir, baseName) {
  150. // Try to load .crt and .key from the PKI directory
  151. caCert, _, err := pkiutil.TryLoadCertAndKeyFromDisk(pkiDir, baseName)
  152. if err != nil {
  153. return errors.Wrapf(err, "failure loading %s certificate", baseName)
  154. }
  155. // Check if the existing cert is a CA
  156. if !caCert.IsCA {
  157. return errors.Errorf("certificate %s is not a CA", baseName)
  158. }
  159. // kubeadm doesn't validate the existing certificate Authority more than this;
  160. // Basically, if we find a certificate file with the same path; and it is a CA
  161. // kubeadm thinks those files are equal and doesn't bother writing a new file
  162. fmt.Printf("[certs] Using the existing %q certificate and key\n", baseName)
  163. } else {
  164. // Write .crt and .key files to disk
  165. fmt.Printf("[certs] Generating %q certificate and key\n", baseName)
  166. if err := pkiutil.WriteCertAndKey(pkiDir, baseName, caCert, caKey); err != nil {
  167. return errors.Wrapf(err, "failure while saving %s certificate and key", baseName)
  168. }
  169. }
  170. return nil
  171. }
  172. // writeCertificateFilesIfNotExist write a new certificate to the given path.
  173. // If there already is a certificate file at the given path; kubeadm tries to load it and check if the values in the
  174. // existing and the expected certificate equals. If they do; kubeadm will just skip writing the file as it's up-to-date,
  175. // otherwise this function returns an error.
  176. func writeCertificateFilesIfNotExist(pkiDir string, baseName string, signingCert *x509.Certificate, cert *x509.Certificate, key crypto.Signer, cfg *pkiutil.CertConfig) error {
  177. // Checks if the signed certificate exists in the PKI directory
  178. if pkiutil.CertOrKeyExist(pkiDir, baseName) {
  179. // Try to load signed certificate .crt and .key from the PKI directory
  180. signedCert, _, err := pkiutil.TryLoadCertAndKeyFromDisk(pkiDir, baseName)
  181. if err != nil {
  182. return errors.Wrapf(err, "failure loading %s certificate", baseName)
  183. }
  184. // Check if the existing cert is signed by the given CA
  185. if err := signedCert.CheckSignatureFrom(signingCert); err != nil {
  186. return errors.Errorf("certificate %s is not signed by corresponding CA", baseName)
  187. }
  188. // Check if the certificate has the correct attributes
  189. if err := validateCertificateWithConfig(signedCert, baseName, cfg); err != nil {
  190. return err
  191. }
  192. fmt.Printf("[certs] Using the existing %q certificate and key\n", baseName)
  193. } else {
  194. // Write .crt and .key files to disk
  195. fmt.Printf("[certs] Generating %q certificate and key\n", baseName)
  196. if err := pkiutil.WriteCertAndKey(pkiDir, baseName, cert, key); err != nil {
  197. return errors.Wrapf(err, "failure while saving %s certificate and key", baseName)
  198. }
  199. if pkiutil.HasServerAuth(cert) {
  200. fmt.Printf("[certs] %s serving cert is signed for DNS names %v and IPs %v\n", baseName, cert.DNSNames, cert.IPAddresses)
  201. }
  202. }
  203. return nil
  204. }
  205. // writeCSRFilesIfNotExist writes a new CSR to the given path.
  206. // If there already is a CSR file at the given path; kubeadm tries to load it and check if it's a valid certificate.
  207. // otherwise this function returns an error.
  208. func writeCSRFilesIfNotExist(csrDir string, baseName string, csr *x509.CertificateRequest, key crypto.Signer) error {
  209. if pkiutil.CSROrKeyExist(csrDir, baseName) {
  210. _, _, err := pkiutil.TryLoadCSRAndKeyFromDisk(csrDir, baseName)
  211. if err != nil {
  212. return errors.Wrapf(err, "%s CSR existed but it could not be loaded properly", baseName)
  213. }
  214. fmt.Printf("[certs] Using the existing %q CSR\n", baseName)
  215. } else {
  216. // Write .key and .csr files to disk
  217. fmt.Printf("[certs] Generating %q key and CSR\n", baseName)
  218. if err := pkiutil.WriteKey(csrDir, baseName, key); err != nil {
  219. return errors.Wrapf(err, "failure while saving %s key", baseName)
  220. }
  221. if err := pkiutil.WriteCSR(csrDir, baseName, csr); err != nil {
  222. return errors.Wrapf(err, "failure while saving %s CSR", baseName)
  223. }
  224. }
  225. return nil
  226. }
  227. type certKeyLocation struct {
  228. pkiDir string
  229. caBaseName string
  230. baseName string
  231. uxName string
  232. }
  233. // SharedCertificateExists verifies if the shared certificates - the certificates that must be
  234. // equal across control-plane nodes: ca.key, ca.crt, sa.key, sa.pub + etcd/ca.key, etcd/ca.crt if local/stacked etcd
  235. func SharedCertificateExists(cfg *kubeadmapi.ClusterConfiguration) (bool, error) {
  236. if err := validateCACertAndKey(certKeyLocation{cfg.CertificatesDir, kubeadmconstants.CACertAndKeyBaseName, "", "CA"}); err != nil {
  237. return false, err
  238. }
  239. if err := validatePrivatePublicKey(certKeyLocation{cfg.CertificatesDir, "", kubeadmconstants.ServiceAccountKeyBaseName, "service account"}); err != nil {
  240. return false, err
  241. }
  242. if err := validateCACertAndKey(certKeyLocation{cfg.CertificatesDir, kubeadmconstants.FrontProxyCACertAndKeyBaseName, "", "front-proxy CA"}); err != nil {
  243. return false, err
  244. }
  245. // in case of local/stacked etcd
  246. if cfg.Etcd.External == nil {
  247. if err := validateCACertAndKey(certKeyLocation{cfg.CertificatesDir, kubeadmconstants.EtcdCACertAndKeyBaseName, "", "etcd CA"}); err != nil {
  248. return false, err
  249. }
  250. }
  251. return true, nil
  252. }
  253. // UsingExternalCA determines whether the user is relying on an external CA. We currently implicitly determine this is the case
  254. // when the CA Cert is present but the CA Key is not.
  255. // This allows us to, e.g., skip generating certs or not start the csr signing controller.
  256. // In case we are using an external front-proxy CA, the function validates the certificates signed by front-proxy CA that should be provided by the user.
  257. func UsingExternalCA(cfg *kubeadmapi.ClusterConfiguration) (bool, error) {
  258. if err := validateCACert(certKeyLocation{cfg.CertificatesDir, kubeadmconstants.CACertAndKeyBaseName, "", "CA"}); err != nil {
  259. return false, err
  260. }
  261. caKeyPath := filepath.Join(cfg.CertificatesDir, kubeadmconstants.CAKeyName)
  262. if _, err := os.Stat(caKeyPath); !os.IsNotExist(err) {
  263. return false, nil
  264. }
  265. if err := validateSignedCert(certKeyLocation{cfg.CertificatesDir, kubeadmconstants.CACertAndKeyBaseName, kubeadmconstants.APIServerCertAndKeyBaseName, "API server"}); err != nil {
  266. return true, err
  267. }
  268. if err := validateSignedCert(certKeyLocation{cfg.CertificatesDir, kubeadmconstants.CACertAndKeyBaseName, kubeadmconstants.APIServerKubeletClientCertAndKeyBaseName, "API server kubelet client"}); err != nil {
  269. return true, err
  270. }
  271. return true, nil
  272. }
  273. // UsingExternalFrontProxyCA determines whether the user is relying on an external front-proxy CA. We currently implicitly determine this is the case
  274. // when the front proxy CA Cert is present but the front proxy CA Key is not.
  275. // In case we are using an external front-proxy CA, the function validates the certificates signed by front-proxy CA that should be provided by the user.
  276. func UsingExternalFrontProxyCA(cfg *kubeadmapi.ClusterConfiguration) (bool, error) {
  277. if err := validateCACert(certKeyLocation{cfg.CertificatesDir, kubeadmconstants.FrontProxyCACertAndKeyBaseName, "", "front-proxy CA"}); err != nil {
  278. return false, err
  279. }
  280. frontProxyCAKeyPath := filepath.Join(cfg.CertificatesDir, kubeadmconstants.FrontProxyCAKeyName)
  281. if _, err := os.Stat(frontProxyCAKeyPath); !os.IsNotExist(err) {
  282. return false, nil
  283. }
  284. if err := validateSignedCert(certKeyLocation{cfg.CertificatesDir, kubeadmconstants.FrontProxyCACertAndKeyBaseName, kubeadmconstants.FrontProxyClientCertAndKeyBaseName, "front-proxy client"}); err != nil {
  285. return true, err
  286. }
  287. return true, nil
  288. }
  289. // validateCACert tries to load a x509 certificate from pkiDir and validates that it is a CA
  290. func validateCACert(l certKeyLocation) error {
  291. // Check CA Cert
  292. caCert, err := pkiutil.TryLoadCertFromDisk(l.pkiDir, l.caBaseName)
  293. if err != nil {
  294. return errors.Wrapf(err, "failure loading certificate for %s", l.uxName)
  295. }
  296. // Check if cert is a CA
  297. if !caCert.IsCA {
  298. return errors.Errorf("certificate %s is not a CA", l.uxName)
  299. }
  300. return nil
  301. }
  302. // validateCACertAndKey tries to load a x509 certificate and private key from pkiDir,
  303. // and validates that the cert is a CA
  304. func validateCACertAndKey(l certKeyLocation) error {
  305. if err := validateCACert(l); err != nil {
  306. return err
  307. }
  308. _, err := pkiutil.TryLoadKeyFromDisk(l.pkiDir, l.caBaseName)
  309. if err != nil {
  310. return errors.Wrapf(err, "failure loading key for %s", l.uxName)
  311. }
  312. return nil
  313. }
  314. // validateSignedCert tries to load a x509 certificate and private key from pkiDir and validates
  315. // that the cert is signed by a given CA
  316. func validateSignedCert(l certKeyLocation) error {
  317. // Try to load CA
  318. caCert, err := pkiutil.TryLoadCertFromDisk(l.pkiDir, l.caBaseName)
  319. if err != nil {
  320. return errors.Wrapf(err, "failure loading certificate authority for %s", l.uxName)
  321. }
  322. return validateSignedCertWithCA(l, caCert)
  323. }
  324. // validateSignedCertWithCA tries to load a certificate and validate it with the given caCert
  325. func validateSignedCertWithCA(l certKeyLocation, caCert *x509.Certificate) error {
  326. // Try to load key and signed certificate
  327. signedCert, _, err := pkiutil.TryLoadCertAndKeyFromDisk(l.pkiDir, l.baseName)
  328. if err != nil {
  329. return errors.Wrapf(err, "failure loading certificate for %s", l.uxName)
  330. }
  331. // Check if the cert is signed by the CA
  332. if err := signedCert.CheckSignatureFrom(caCert); err != nil {
  333. return errors.Wrapf(err, "certificate %s is not signed by corresponding CA", l.uxName)
  334. }
  335. return nil
  336. }
  337. // validatePrivatePublicKey tries to load a private key from pkiDir
  338. func validatePrivatePublicKey(l certKeyLocation) error {
  339. // Try to load key
  340. _, _, err := pkiutil.TryLoadPrivatePublicKeyFromDisk(l.pkiDir, l.baseName)
  341. if err != nil {
  342. return errors.Wrapf(err, "failure loading key for %s", l.uxName)
  343. }
  344. return nil
  345. }
  346. // validateCertificateWithConfig makes sure that a given certificate is valid at
  347. // least for the SANs defined in the configuration.
  348. func validateCertificateWithConfig(cert *x509.Certificate, baseName string, cfg *pkiutil.CertConfig) error {
  349. for _, dnsName := range cfg.AltNames.DNSNames {
  350. if err := cert.VerifyHostname(dnsName); err != nil {
  351. return errors.Wrapf(err, "certificate %s is invalid", baseName)
  352. }
  353. }
  354. for _, ipAddress := range cfg.AltNames.IPs {
  355. if err := cert.VerifyHostname(ipAddress.String()); err != nil {
  356. return errors.Wrapf(err, "certificate %s is invalid", baseName)
  357. }
  358. }
  359. return nil
  360. }