certs.go 17 KB

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