manager.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. // adds the certificateRenewHandler.
  132. // Certificates embedded kubeConfig files in are indexed by fileName, that is a well know constant defined
  133. // in the kubeadm constants package and that can be reused across all the kubeadm codebase
  134. rm.certificates[kubeConfig.fileName] = &CertificateRenewHandler{
  135. Name: kubeConfig.fileName, // we are using fileName as name, because there is nothing similar outside
  136. LongName: kubeConfig.longName,
  137. FileName: kubeConfig.fileName,
  138. CABaseName: kubeadmconstants.CACertAndKeyBaseName, // all certificates in kubeConfig files are signed by the Kubernetes CA
  139. readwriter: kubeConfigReadWriter,
  140. }
  141. }
  142. return rm, nil
  143. }
  144. // Certificates returns the list of certificates controlled by this Manager
  145. func (rm *Manager) Certificates() []*CertificateRenewHandler {
  146. certificates := []*CertificateRenewHandler{}
  147. for _, h := range rm.certificates {
  148. certificates = append(certificates, h)
  149. }
  150. sort.Slice(certificates, func(i, j int) bool { return certificates[i].Name < certificates[j].Name })
  151. return certificates
  152. }
  153. // CAs returns the list of CAs related to the certificates that are controlled by this manager
  154. func (rm *Manager) CAs() []*CAExpirationHandler {
  155. cas := []*CAExpirationHandler{}
  156. for _, h := range rm.cas {
  157. cas = append(cas, h)
  158. }
  159. sort.Slice(cas, func(i, j int) bool { return cas[i].Name < cas[j].Name })
  160. return cas
  161. }
  162. // RenewUsingLocalCA executes certificate renewal using local certificate authorities for generating new certs.
  163. // For PKI certificates, use the name defined in the certsphase package, while for certificates
  164. // embedded in the kubeConfig files, use the kubeConfig file name defined in the kubeadm constants package.
  165. // If you use the CertificateRenewHandler returned by Certificates func, handler.Name already contains the right value.
  166. func (rm *Manager) RenewUsingLocalCA(name string) (bool, error) {
  167. handler, ok := rm.certificates[name]
  168. if !ok {
  169. return false, errors.Errorf("%s is not a valid certificate for this cluster", name)
  170. }
  171. // checks if the certificate is externally managed (CA certificate provided without the certificate key)
  172. externallyManaged, err := rm.IsExternallyManaged(handler.CABaseName)
  173. if err != nil {
  174. return false, err
  175. }
  176. // in case of external CA it is not possible to renew certificates, then return early
  177. if externallyManaged {
  178. return false, nil
  179. }
  180. // reads the current certificate
  181. cert, err := handler.readwriter.Read()
  182. if err != nil {
  183. return false, err
  184. }
  185. // extract the certificate config
  186. cfg := certToConfig(cert)
  187. // reads the CA
  188. caCert, caKey, err := certsphase.LoadCertificateAuthority(rm.cfg.CertificatesDir, handler.CABaseName)
  189. if err != nil {
  190. return false, err
  191. }
  192. // create a new certificate with the same config
  193. newCert, newKey, err := NewFileRenewer(caCert, caKey).Renew(cfg)
  194. if err != nil {
  195. return false, errors.Wrapf(err, "failed to renew certificate %s", name)
  196. }
  197. // writes the new certificate to disk
  198. err = handler.readwriter.Write(newCert, newKey)
  199. if err != nil {
  200. return false, err
  201. }
  202. return true, nil
  203. }
  204. // RenewUsingCSRAPI executes certificate renewal uses the K8s certificate API.
  205. // For PKI certificates, use the name defined in the certsphase package, while for certificates
  206. // embedded in the kubeConfig files, use the kubeConfig file name defined in the kubeadm constants package.
  207. // If you use the CertificateRenewHandler returned by Certificates func, handler.Name already contains the right value.
  208. func (rm *Manager) RenewUsingCSRAPI(name string, client clientset.Interface) error {
  209. handler, ok := rm.certificates[name]
  210. if !ok {
  211. return errors.Errorf("%s is not a valid certificate for this cluster", name)
  212. }
  213. // reads the current certificate
  214. cert, err := handler.readwriter.Read()
  215. if err != nil {
  216. return err
  217. }
  218. // extract the certificate config
  219. cfg := certToConfig(cert)
  220. // create a new certificate with the same config
  221. newCert, newKey, err := NewAPIRenewer(client).Renew(cfg)
  222. if err != nil {
  223. return errors.Wrapf(err, "failed to renew certificate %s", name)
  224. }
  225. // writes the new certificate to disk
  226. err = handler.readwriter.Write(newCert, newKey)
  227. if err != nil {
  228. return err
  229. }
  230. return nil
  231. }
  232. // CreateRenewCSR generates CSR request for certificate renewal.
  233. // For PKI certificates, use the name defined in the certsphase package, while for certificates
  234. // embedded in the kubeConfig files, use the kubeConfig file name defined in the kubeadm constants package.
  235. // If you use the CertificateRenewHandler returned by Certificates func, handler.Name already contains the right value.
  236. func (rm *Manager) CreateRenewCSR(name, outdir string) error {
  237. handler, ok := rm.certificates[name]
  238. if !ok {
  239. return errors.Errorf("%s is not a known certificate", name)
  240. }
  241. // reads the current certificate
  242. cert, err := handler.readwriter.Read()
  243. if err != nil {
  244. return err
  245. }
  246. // extracts the certificate config
  247. cfg := certToConfig(cert)
  248. // generates the CSR request and save it
  249. csr, key, err := pkiutil.NewCSRAndKey(cfg)
  250. if err != nil {
  251. return errors.Wrapf(err, "failure while generating %s CSR and key", name)
  252. }
  253. if err := pkiutil.WriteKey(outdir, name, key); err != nil {
  254. return errors.Wrapf(err, "failure while saving %s key", name)
  255. }
  256. if err := pkiutil.WriteCSR(outdir, name, csr); err != nil {
  257. return errors.Wrapf(err, "failure while saving %s CSR", name)
  258. }
  259. return nil
  260. }
  261. // CertificateExists returns true if a certificate exists.
  262. func (rm *Manager) CertificateExists(name string) (bool, error) {
  263. handler, ok := rm.certificates[name]
  264. if !ok {
  265. return false, errors.Errorf("%s is not a known certificate", name)
  266. }
  267. return handler.readwriter.Exists(), nil
  268. }
  269. // GetCertificateExpirationInfo returns certificate expiration info.
  270. // For PKI certificates, use the name defined in the certsphase package, while for certificates
  271. // embedded in the kubeConfig files, use the kubeConfig file name defined in the kubeadm constants package.
  272. // If you use the CertificateRenewHandler returned by Certificates func, handler.Name already contains the right value.
  273. func (rm *Manager) GetCertificateExpirationInfo(name string) (*ExpirationInfo, error) {
  274. handler, ok := rm.certificates[name]
  275. if !ok {
  276. return nil, errors.Errorf("%s is not a known certificate", name)
  277. }
  278. // checks if the certificate is externally managed (CA certificate provided without the certificate key)
  279. externallyManaged, err := rm.IsExternallyManaged(handler.CABaseName)
  280. if err != nil {
  281. return nil, err
  282. }
  283. // reads the current certificate
  284. cert, err := handler.readwriter.Read()
  285. if err != nil {
  286. return nil, err
  287. }
  288. // returns the certificate expiration info
  289. return newExpirationInfo(name, cert, externallyManaged), nil
  290. }
  291. // CAExists returns true if a certificate authority exists.
  292. func (rm *Manager) CAExists(name string) (bool, error) {
  293. handler, ok := rm.cas[name]
  294. if !ok {
  295. return false, errors.Errorf("%s is not a known certificate", name)
  296. }
  297. return handler.readwriter.Exists(), nil
  298. }
  299. // GetCAExpirationInfo returns CA expiration info.
  300. func (rm *Manager) GetCAExpirationInfo(name string) (*ExpirationInfo, error) {
  301. handler, ok := rm.cas[name]
  302. if !ok {
  303. return nil, errors.Errorf("%s is not a known CA", name)
  304. }
  305. // checks if the CA is externally managed (CA certificate provided without the certificate key)
  306. externallyManaged, err := rm.IsExternallyManaged(handler.FileName)
  307. if err != nil {
  308. return nil, err
  309. }
  310. // reads the current CA
  311. ca, err := handler.readwriter.Read()
  312. if err != nil {
  313. return nil, err
  314. }
  315. // returns the CA expiration info
  316. return newExpirationInfo(name, ca, externallyManaged), nil
  317. }
  318. // IsExternallyManaged checks if we are in the external CA case (CA certificate provided without the certificate key)
  319. func (rm *Manager) IsExternallyManaged(caBaseName string) (bool, error) {
  320. switch caBaseName {
  321. case kubeadmconstants.CACertAndKeyBaseName:
  322. externallyManaged, err := certsphase.UsingExternalCA(rm.cfg)
  323. if err != nil {
  324. return false, errors.Wrapf(err, "Error checking external CA condition for %s certificate authority", caBaseName)
  325. }
  326. return externallyManaged, nil
  327. case kubeadmconstants.FrontProxyCACertAndKeyBaseName:
  328. externallyManaged, err := certsphase.UsingExternalFrontProxyCA(rm.cfg)
  329. if err != nil {
  330. return false, errors.Wrapf(err, "Error checking external CA condition for %s certificate authority", caBaseName)
  331. }
  332. return externallyManaged, nil
  333. case kubeadmconstants.EtcdCACertAndKeyBaseName:
  334. return false, nil
  335. default:
  336. return false, errors.Errorf("unknown certificate authority %s", caBaseName)
  337. }
  338. }
  339. func certToConfig(cert *x509.Certificate) *certutil.Config {
  340. return &certutil.Config{
  341. CommonName: cert.Subject.CommonName,
  342. Organization: cert.Subject.Organization,
  343. AltNames: certutil.AltNames{
  344. IPs: cert.IPAddresses,
  345. DNSNames: cert.DNSNames,
  346. },
  347. Usages: cert.ExtKeyUsage,
  348. }
  349. }