controller.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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 certificates
  14. import (
  15. "fmt"
  16. "reflect"
  17. "strings"
  18. "time"
  19. "k8s.io/kubernetes/pkg/api"
  20. "k8s.io/kubernetes/pkg/apis/certificates"
  21. "k8s.io/kubernetes/pkg/client/cache"
  22. clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
  23. unversionedcore "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned"
  24. "k8s.io/kubernetes/pkg/client/record"
  25. "k8s.io/kubernetes/pkg/controller"
  26. "k8s.io/kubernetes/pkg/controller/framework"
  27. "k8s.io/kubernetes/pkg/runtime"
  28. utilcertificates "k8s.io/kubernetes/pkg/util/certificates"
  29. utilruntime "k8s.io/kubernetes/pkg/util/runtime"
  30. "k8s.io/kubernetes/pkg/util/wait"
  31. "k8s.io/kubernetes/pkg/util/workqueue"
  32. "k8s.io/kubernetes/pkg/watch"
  33. "github.com/cloudflare/cfssl/config"
  34. "github.com/cloudflare/cfssl/signer"
  35. "github.com/cloudflare/cfssl/signer/local"
  36. "github.com/golang/glog"
  37. )
  38. type CertificateController struct {
  39. kubeClient clientset.Interface
  40. // CSR framework and store
  41. csrController *framework.Controller
  42. csrStore cache.StoreToCertificateRequestLister
  43. // To allow injection of updateCertificateRequestStatus for testing.
  44. updateHandler func(csr *certificates.CertificateSigningRequest) error
  45. syncHandler func(csrKey string) error
  46. approveAllKubeletCSRsForGroup string
  47. signer *local.Signer
  48. queue *workqueue.Type
  49. }
  50. func NewCertificateController(kubeClient clientset.Interface, syncPeriod time.Duration, caCertFile, caKeyFile string, approveAllKubeletCSRsForGroup string) (*CertificateController, error) {
  51. // Send events to the apiserver
  52. eventBroadcaster := record.NewBroadcaster()
  53. eventBroadcaster.StartLogging(glog.Infof)
  54. eventBroadcaster.StartRecordingToSink(&unversionedcore.EventSinkImpl{Interface: kubeClient.Core().Events("")})
  55. // Configure cfssl signer
  56. // TODO: support non-default policy and remote/pkcs11 signing
  57. policy := &config.Signing{
  58. Default: config.DefaultConfig(),
  59. }
  60. ca, err := local.NewSignerFromFile(caCertFile, caKeyFile, policy)
  61. if err != nil {
  62. return nil, err
  63. }
  64. cc := &CertificateController{
  65. kubeClient: kubeClient,
  66. queue: workqueue.NewNamed("certificate"),
  67. signer: ca,
  68. approveAllKubeletCSRsForGroup: approveAllKubeletCSRsForGroup,
  69. }
  70. // Manage the addition/update of certificate requests
  71. cc.csrStore.Store, cc.csrController = framework.NewInformer(
  72. &cache.ListWatch{
  73. ListFunc: func(options api.ListOptions) (runtime.Object, error) {
  74. return cc.kubeClient.Certificates().CertificateSigningRequests().List(options)
  75. },
  76. WatchFunc: func(options api.ListOptions) (watch.Interface, error) {
  77. return cc.kubeClient.Certificates().CertificateSigningRequests().Watch(options)
  78. },
  79. },
  80. &certificates.CertificateSigningRequest{},
  81. syncPeriod,
  82. framework.ResourceEventHandlerFuncs{
  83. AddFunc: func(obj interface{}) {
  84. csr := obj.(*certificates.CertificateSigningRequest)
  85. glog.V(4).Infof("Adding certificate request %s", csr.Name)
  86. cc.enqueueCertificateRequest(obj)
  87. },
  88. UpdateFunc: func(old, new interface{}) {
  89. oldCSR := old.(*certificates.CertificateSigningRequest)
  90. glog.V(4).Infof("Updating certificate request %s", oldCSR.Name)
  91. cc.enqueueCertificateRequest(new)
  92. },
  93. DeleteFunc: func(obj interface{}) {
  94. csr := obj.(*certificates.CertificateSigningRequest)
  95. glog.V(4).Infof("Deleting certificate request %s", csr.Name)
  96. cc.enqueueCertificateRequest(obj)
  97. },
  98. },
  99. )
  100. cc.syncHandler = cc.maybeSignCertificate
  101. return cc, nil
  102. }
  103. // Run the main goroutine responsible for watching and syncing jobs.
  104. func (cc *CertificateController) Run(workers int, stopCh <-chan struct{}) {
  105. defer utilruntime.HandleCrash()
  106. go cc.csrController.Run(stopCh)
  107. glog.Infof("Starting certificate controller manager")
  108. for i := 0; i < workers; i++ {
  109. go wait.Until(cc.worker, time.Second, stopCh)
  110. }
  111. <-stopCh
  112. glog.Infof("Shutting down certificate controller")
  113. cc.queue.ShutDown()
  114. }
  115. // worker runs a thread that dequeues CSRs, handles them, and marks them done.
  116. func (cc *CertificateController) worker() {
  117. for {
  118. func() {
  119. key, quit := cc.queue.Get()
  120. if quit {
  121. return
  122. }
  123. defer cc.queue.Done(key)
  124. err := cc.syncHandler(key.(string))
  125. if err != nil {
  126. glog.Errorf("Error syncing CSR: %v", err)
  127. }
  128. }()
  129. }
  130. }
  131. func (cc *CertificateController) enqueueCertificateRequest(obj interface{}) {
  132. key, err := controller.KeyFunc(obj)
  133. if err != nil {
  134. glog.Errorf("Couldn't get key for object %+v: %v", obj, err)
  135. return
  136. }
  137. cc.queue.Add(key)
  138. }
  139. func (cc *CertificateController) updateCertificateRequestStatus(csr *certificates.CertificateSigningRequest) error {
  140. _, updateErr := cc.kubeClient.Certificates().CertificateSigningRequests().UpdateStatus(csr)
  141. if updateErr == nil {
  142. // success!
  143. return nil
  144. }
  145. // retry on failure
  146. cc.enqueueCertificateRequest(csr)
  147. return updateErr
  148. }
  149. // maybeSignCertificate will inspect the certificate request and, if it has
  150. // been approved and meets policy expectations, generate an X509 cert using the
  151. // cluster CA assets. If successful it will update the CSR approve subresource
  152. // with the signed certificate.
  153. func (cc *CertificateController) maybeSignCertificate(key string) error {
  154. startTime := time.Now()
  155. defer func() {
  156. glog.V(4).Infof("Finished syncing certificate request %q (%v)", key, time.Now().Sub(startTime))
  157. }()
  158. obj, exists, err := cc.csrStore.Store.GetByKey(key)
  159. if err != nil {
  160. cc.queue.Add(key)
  161. return err
  162. }
  163. if !exists {
  164. glog.V(3).Infof("csr has been deleted: %v", key)
  165. return nil
  166. }
  167. csr := obj.(*certificates.CertificateSigningRequest)
  168. csr, err = cc.maybeAutoApproveCSR(csr)
  169. if err != nil {
  170. return fmt.Errorf("error auto approving csr: %v", err)
  171. }
  172. // At this point, the controller needs to:
  173. // 1. Check the approval conditions
  174. // 2. Generate a signed certificate
  175. // 3. Update the Status subresource
  176. if csr.Status.Certificate == nil && IsCertificateRequestApproved(csr) {
  177. pemBytes := csr.Spec.Request
  178. req := signer.SignRequest{Request: string(pemBytes)}
  179. certBytes, err := cc.signer.Sign(req)
  180. if err != nil {
  181. return err
  182. }
  183. csr.Status.Certificate = certBytes
  184. }
  185. return cc.updateCertificateRequestStatus(csr)
  186. }
  187. func (cc *CertificateController) maybeAutoApproveCSR(csr *certificates.CertificateSigningRequest) (*certificates.CertificateSigningRequest, error) {
  188. // short-circuit if we're not auto-approving
  189. if cc.approveAllKubeletCSRsForGroup == "" {
  190. return csr, nil
  191. }
  192. // short-circuit if we're already approved or denied
  193. if approved, denied := getCertApprovalCondition(&csr.Status); approved || denied {
  194. return csr, nil
  195. }
  196. isKubeletBootstrapGroup := false
  197. for _, g := range csr.Spec.Groups {
  198. if g == cc.approveAllKubeletCSRsForGroup {
  199. isKubeletBootstrapGroup = true
  200. break
  201. }
  202. }
  203. if !isKubeletBootstrapGroup {
  204. return csr, nil
  205. }
  206. x509cr, err := utilcertificates.ParseCertificateRequestObject(csr)
  207. if err != nil {
  208. glog.Errorf("unable to parse csr %q: %v", csr.ObjectMeta.Name, err)
  209. return csr, nil
  210. }
  211. if !reflect.DeepEqual([]string{"system:nodes"}, x509cr.Subject.Organization) {
  212. return csr, nil
  213. }
  214. if !strings.HasPrefix(x509cr.Subject.CommonName, "system:node:") {
  215. return csr, nil
  216. }
  217. if len(x509cr.DNSNames)+len(x509cr.EmailAddresses)+len(x509cr.IPAddresses) != 0 {
  218. return csr, nil
  219. }
  220. csr.Status.Conditions = append(csr.Status.Conditions, certificates.CertificateSigningRequestCondition{
  221. Type: certificates.CertificateApproved,
  222. Reason: "AutoApproved",
  223. Message: "Auto approving of all kubelet CSRs is enabled on the controller manager",
  224. })
  225. return cc.kubeClient.Certificates().CertificateSigningRequests().UpdateApproval(csr)
  226. }