manager.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. /*
  2. Copyright 2019 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 renewal
  14. import (
  15. "crypto/x509"
  16. "sort"
  17. "github.com/pkg/errors"
  18. clientset "k8s.io/client-go/kubernetes"
  19. certutil "k8s.io/client-go/util/cert"
  20. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  21. kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  22. certsphase "k8s.io/kubernetes/cmd/kubeadm/app/phases/certs"
  23. "k8s.io/kubernetes/cmd/kubeadm/app/util/pkiutil"
  24. )
  25. // Manager can be used to coordinate certificate renewal and related processes,
  26. // like CSR generation or checking certificate expiration
  27. type Manager struct {
  28. // cfg holds the kubeadm ClusterConfiguration
  29. cfg *kubeadmapi.ClusterConfiguration
  30. // kubernetesDir holds the directory where kubeConfig files are stored
  31. kubernetesDir string
  32. // certificates contains the certificateRenewHandler controlled by this manager
  33. certificates map[string]*CertificateRenewHandler
  34. // cas contains the CAExpirationHandler related to the certificates that are controlled by this manager
  35. cas map[string]*CAExpirationHandler
  36. }
  37. // CertificateRenewHandler defines required info for renewing a certificate
  38. type CertificateRenewHandler struct {
  39. // Name of the certificate to be used for UX.
  40. // This value can be used to trigger operations on this certificate
  41. Name string
  42. // LongName of the certificate to be used for UX
  43. LongName string
  44. // FileName defines the name (or the BaseName) of the certificate file
  45. FileName string
  46. // CAName defines the name for the CA on which this certificate depends
  47. CAName string
  48. // CABaseName defines the base name for the CA that should be used for certificate renewal
  49. CABaseName string
  50. // readwriter defines a CertificateReadWriter to be used for certificate renewal
  51. readwriter certificateReadWriter
  52. }
  53. // CAExpirationHandler defines required info for CA expiration check
  54. type CAExpirationHandler struct {
  55. // Name of the CA to be used for UX.
  56. // This value can be used to trigger operations on this CA
  57. Name string
  58. // LongName of the CA to be used for UX
  59. LongName string
  60. // FileName defines the name (or the BaseName) of the CA file
  61. FileName string
  62. // readwriter defines a CertificateReadWriter to be used for CA expiration check
  63. readwriter certificateReadWriter
  64. }
  65. // NewManager return a new certificate renewal manager ready for handling certificates in the cluster
  66. func NewManager(cfg *kubeadmapi.ClusterConfiguration, kubernetesDir string) (*Manager, error) {
  67. rm := &Manager{
  68. cfg: cfg,
  69. kubernetesDir: kubernetesDir,
  70. certificates: map[string]*CertificateRenewHandler{},
  71. cas: map[string]*CAExpirationHandler{},
  72. }
  73. // gets the list of certificates that are expected according to the current cluster configuration
  74. certListFunc := certsphase.GetDefaultCertList
  75. if cfg.Etcd.External != nil {
  76. certListFunc = certsphase.GetCertsWithoutEtcd
  77. }
  78. certTree, err := certListFunc().AsMap().CertTree()
  79. if err != nil {
  80. return nil, err
  81. }
  82. // create a CertificateRenewHandler for each signed certificate in the certificate tree;
  83. // NB. we are not offering support for renewing CAs; this would cause serious consequences
  84. for ca, certs := range certTree {
  85. for _, cert := range certs {
  86. // create a ReadWriter for certificates stored in the K8s local PKI
  87. pkiReadWriter := newPKICertificateReadWriter(rm.cfg.CertificatesDir, cert.BaseName)
  88. // adds the certificateRenewHandler.
  89. // PKI certificates are indexed by name, that is a well know constant defined
  90. // in the certsphase package and that can be reused across all the kubeadm codebase
  91. rm.certificates[cert.Name] = &CertificateRenewHandler{
  92. Name: cert.Name,
  93. LongName: cert.LongName,
  94. FileName: cert.BaseName,
  95. CAName: ca.Name,
  96. CABaseName: ca.BaseName, //Nb. this is a path for etcd certs (they are stored in a subfolder)
  97. readwriter: pkiReadWriter,
  98. }
  99. }
  100. pkiReadWriter := newPKICertificateReadWriter(rm.cfg.CertificatesDir, ca.BaseName)
  101. rm.cas[ca.Name] = &CAExpirationHandler{
  102. Name: ca.Name,
  103. LongName: ca.LongName,
  104. FileName: ca.BaseName,
  105. readwriter: pkiReadWriter,
  106. }
  107. }
  108. // gets the list of certificates that should be considered for renewal
  109. kubeConfigs := []struct {
  110. longName string
  111. fileName string
  112. }{
  113. {
  114. longName: "certificate embedded in the kubeconfig file for the admin to use and for kubeadm itself",
  115. fileName: kubeadmconstants.AdminKubeConfigFileName,
  116. },
  117. {
  118. longName: "certificate embedded in the kubeconfig file for the controller manager to use",
  119. fileName: kubeadmconstants.ControllerManagerKubeConfigFileName,
  120. },
  121. {
  122. longName: "certificate embedded in the kubeconfig file for the scheduler manager to use",
  123. fileName: kubeadmconstants.SchedulerKubeConfigFileName,
  124. },
  125. //NB. we are excluding KubeletKubeConfig from renewal because management of this certificate is delegated to kubelet
  126. }
  127. // create a CertificateRenewHandler for each kubeConfig file
  128. for _, kubeConfig := range kubeConfigs {
  129. // create a ReadWriter for certificates embedded in kubeConfig files
  130. kubeConfigReadWriter := newKubeconfigReadWriter(kubernetesDir, kubeConfig.fileName,
  131. rm.cfg.CertificatesDir, kubeadmconstants.CACertAndKeyBaseName)
  132. // adds the certificateRenewHandler.
  133. // Certificates embedded kubeConfig files in are indexed by fileName, that is a well know constant defined
  134. // in the kubeadm constants package and that can be reused across all the kubeadm codebase
  135. rm.certificates[kubeConfig.fileName] = &CertificateRenewHandler{
  136. Name: kubeConfig.fileName, // we are using fileName as name, because there is nothing similar outside
  137. LongName: kubeConfig.longName,
  138. FileName: kubeConfig.fileName,
  139. CABaseName: kubeadmconstants.CACertAndKeyBaseName, // all certificates in kubeConfig files are signed by the Kubernetes CA
  140. readwriter: kubeConfigReadWriter,
  141. }
  142. }
  143. return rm, nil
  144. }
  145. // Certificates returns the list of certificates controlled by this Manager
  146. func (rm *Manager) Certificates() []*CertificateRenewHandler {
  147. certificates := []*CertificateRenewHandler{}
  148. for _, h := range rm.certificates {
  149. certificates = append(certificates, h)
  150. }
  151. sort.Slice(certificates, func(i, j int) bool { return certificates[i].Name < certificates[j].Name })
  152. return certificates
  153. }
  154. // CAs returns the list of CAs related to the certificates that are controlled by this manager
  155. func (rm *Manager) CAs() []*CAExpirationHandler {
  156. cas := []*CAExpirationHandler{}
  157. for _, h := range rm.cas {
  158. cas = append(cas, h)
  159. }
  160. sort.Slice(cas, func(i, j int) bool { return cas[i].Name < cas[j].Name })
  161. return cas
  162. }
  163. // RenewUsingLocalCA executes certificate renewal using local certificate authorities for generating new certs.
  164. // For PKI certificates, use the name defined in the certsphase package, while for certificates
  165. // embedded in the kubeConfig files, use the kubeConfig file name defined in the kubeadm constants package.
  166. // If you use the CertificateRenewHandler returned by Certificates func, handler.Name already contains the right value.
  167. func (rm *Manager) RenewUsingLocalCA(name string) (bool, error) {
  168. handler, ok := rm.certificates[name]
  169. if !ok {
  170. return false, errors.Errorf("%s is not a valid certificate for this cluster", name)
  171. }
  172. // checks if the certificate is externally managed (CA certificate provided without the certificate key)
  173. externallyManaged, err := rm.IsExternallyManaged(handler.CABaseName)
  174. if err != nil {
  175. return false, err
  176. }
  177. // in case of external CA it is not possible to renew certificates, then return early
  178. if externallyManaged {
  179. return false, nil
  180. }
  181. // reads the current certificate
  182. cert, err := handler.readwriter.Read()
  183. if err != nil {
  184. return false, err
  185. }
  186. // extract the certificate config
  187. cfg := &pkiutil.CertConfig{
  188. Config: certToConfig(cert),
  189. PublicKeyAlgorithm: rm.cfg.PublicKeyAlgorithm(),
  190. }
  191. // reads the CA
  192. caCert, caKey, err := certsphase.LoadCertificateAuthority(rm.cfg.CertificatesDir, handler.CABaseName)
  193. if err != nil {
  194. return false, err
  195. }
  196. // create a new certificate with the same config
  197. newCert, newKey, err := NewFileRenewer(caCert, caKey).Renew(cfg)
  198. if err != nil {
  199. return false, errors.Wrapf(err, "failed to renew certificate %s", name)
  200. }
  201. // writes the new certificate to disk
  202. err = handler.readwriter.Write(newCert, newKey)
  203. if err != nil {
  204. return false, err
  205. }
  206. return true, nil
  207. }
  208. // RenewUsingCSRAPI executes certificate renewal uses the K8s certificate API.
  209. // For PKI certificates, use the name defined in the certsphase package, while for certificates
  210. // embedded in the kubeConfig files, use the kubeConfig file name defined in the kubeadm constants package.
  211. // If you use the CertificateRenewHandler returned by Certificates func, handler.Name already contains the right value.
  212. func (rm *Manager) RenewUsingCSRAPI(name string, client clientset.Interface) error {
  213. handler, ok := rm.certificates[name]
  214. if !ok {
  215. return errors.Errorf("%s is not a valid certificate for this cluster", name)
  216. }
  217. // reads the current certificate
  218. cert, err := handler.readwriter.Read()
  219. if err != nil {
  220. return err
  221. }
  222. // extract the certificate config
  223. cfg := &pkiutil.CertConfig{
  224. Config: certToConfig(cert),
  225. PublicKeyAlgorithm: rm.cfg.PublicKeyAlgorithm(),
  226. }
  227. // create a new certificate with the same config
  228. newCert, newKey, err := NewAPIRenewer(client).Renew(cfg)
  229. if err != nil {
  230. return errors.Wrapf(err, "failed to renew certificate %s", name)
  231. }
  232. // writes the new certificate to disk
  233. err = handler.readwriter.Write(newCert, newKey)
  234. if err != nil {
  235. return err
  236. }
  237. return nil
  238. }
  239. // CreateRenewCSR generates CSR request for certificate renewal.
  240. // For PKI certificates, use the name defined in the certsphase package, while for certificates
  241. // embedded in the kubeConfig files, use the kubeConfig file name defined in the kubeadm constants package.
  242. // If you use the CertificateRenewHandler returned by Certificates func, handler.Name already contains the right value.
  243. func (rm *Manager) CreateRenewCSR(name, outdir string) error {
  244. handler, ok := rm.certificates[name]
  245. if !ok {
  246. return errors.Errorf("%s is not a known certificate", name)
  247. }
  248. // reads the current certificate
  249. cert, err := handler.readwriter.Read()
  250. if err != nil {
  251. return err
  252. }
  253. // extracts the certificate config
  254. cfg := &pkiutil.CertConfig{
  255. Config: certToConfig(cert),
  256. PublicKeyAlgorithm: rm.cfg.PublicKeyAlgorithm(),
  257. }
  258. // generates the CSR request and save it
  259. csr, key, err := pkiutil.NewCSRAndKey(cfg)
  260. if err != nil {
  261. return errors.Wrapf(err, "failure while generating %s CSR and key", name)
  262. }
  263. if err := pkiutil.WriteKey(outdir, name, key); err != nil {
  264. return errors.Wrapf(err, "failure while saving %s key", name)
  265. }
  266. if err := pkiutil.WriteCSR(outdir, name, csr); err != nil {
  267. return errors.Wrapf(err, "failure while saving %s CSR", name)
  268. }
  269. return nil
  270. }
  271. // CertificateExists returns true if a certificate exists.
  272. func (rm *Manager) CertificateExists(name string) (bool, error) {
  273. handler, ok := rm.certificates[name]
  274. if !ok {
  275. return false, errors.Errorf("%s is not a known certificate", name)
  276. }
  277. return handler.readwriter.Exists(), nil
  278. }
  279. // GetCertificateExpirationInfo returns certificate expiration info.
  280. // For PKI certificates, use the name defined in the certsphase package, while for certificates
  281. // embedded in the kubeConfig files, use the kubeConfig file name defined in the kubeadm constants package.
  282. // If you use the CertificateRenewHandler returned by Certificates func, handler.Name already contains the right value.
  283. func (rm *Manager) GetCertificateExpirationInfo(name string) (*ExpirationInfo, error) {
  284. handler, ok := rm.certificates[name]
  285. if !ok {
  286. return nil, errors.Errorf("%s is not a known certificate", name)
  287. }
  288. // checks if the certificate is externally managed (CA certificate provided without the certificate key)
  289. externallyManaged, err := rm.IsExternallyManaged(handler.CABaseName)
  290. if err != nil {
  291. return nil, err
  292. }
  293. // reads the current certificate
  294. cert, err := handler.readwriter.Read()
  295. if err != nil {
  296. return nil, err
  297. }
  298. // returns the certificate expiration info
  299. return newExpirationInfo(name, cert, externallyManaged), nil
  300. }
  301. // CAExists returns true if a certificate authority exists.
  302. func (rm *Manager) CAExists(name string) (bool, error) {
  303. handler, ok := rm.cas[name]
  304. if !ok {
  305. return false, errors.Errorf("%s is not a known certificate", name)
  306. }
  307. return handler.readwriter.Exists(), nil
  308. }
  309. // GetCAExpirationInfo returns CA expiration info.
  310. func (rm *Manager) GetCAExpirationInfo(name string) (*ExpirationInfo, error) {
  311. handler, ok := rm.cas[name]
  312. if !ok {
  313. return nil, errors.Errorf("%s is not a known CA", name)
  314. }
  315. // checks if the CA is externally managed (CA certificate provided without the certificate key)
  316. externallyManaged, err := rm.IsExternallyManaged(handler.FileName)
  317. if err != nil {
  318. return nil, err
  319. }
  320. // reads the current CA
  321. ca, err := handler.readwriter.Read()
  322. if err != nil {
  323. return nil, err
  324. }
  325. // returns the CA expiration info
  326. return newExpirationInfo(name, ca, externallyManaged), nil
  327. }
  328. // IsExternallyManaged checks if we are in the external CA case (CA certificate provided without the certificate key)
  329. func (rm *Manager) IsExternallyManaged(caBaseName string) (bool, error) {
  330. switch caBaseName {
  331. case kubeadmconstants.CACertAndKeyBaseName:
  332. externallyManaged, err := certsphase.UsingExternalCA(rm.cfg)
  333. if err != nil {
  334. return false, errors.Wrapf(err, "Error checking external CA condition for %s certificate authority", caBaseName)
  335. }
  336. return externallyManaged, nil
  337. case kubeadmconstants.FrontProxyCACertAndKeyBaseName:
  338. externallyManaged, err := certsphase.UsingExternalFrontProxyCA(rm.cfg)
  339. if err != nil {
  340. return false, errors.Wrapf(err, "Error checking external CA condition for %s certificate authority", caBaseName)
  341. }
  342. return externallyManaged, nil
  343. case kubeadmconstants.EtcdCACertAndKeyBaseName:
  344. return false, nil
  345. default:
  346. return false, errors.Errorf("unknown certificate authority %s", caBaseName)
  347. }
  348. }
  349. func certToConfig(cert *x509.Certificate) certutil.Config {
  350. return certutil.Config{
  351. CommonName: cert.Subject.CommonName,
  352. Organization: cert.Subject.Organization,
  353. AltNames: certutil.AltNames{
  354. IPs: cert.IPAddresses,
  355. DNSNames: cert.DNSNames,
  356. },
  357. Usages: cert.ExtKeyUsage,
  358. }
  359. }