sarapprove.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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 approver implements an automated approver for kubelet certificates.
  14. package approver
  15. import (
  16. "context"
  17. "crypto/x509"
  18. "fmt"
  19. "reflect"
  20. "strings"
  21. authorization "k8s.io/api/authorization/v1"
  22. capi "k8s.io/api/certificates/v1beta1"
  23. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  24. certificatesinformers "k8s.io/client-go/informers/certificates/v1beta1"
  25. clientset "k8s.io/client-go/kubernetes"
  26. capihelper "k8s.io/kubernetes/pkg/apis/certificates/v1beta1"
  27. "k8s.io/kubernetes/pkg/controller/certificates"
  28. )
  29. type csrRecognizer struct {
  30. recognize func(csr *capi.CertificateSigningRequest, x509cr *x509.CertificateRequest) bool
  31. permission authorization.ResourceAttributes
  32. successMessage string
  33. }
  34. type sarApprover struct {
  35. client clientset.Interface
  36. recognizers []csrRecognizer
  37. }
  38. // NewCSRApprovingController creates a new CSRApprovingController.
  39. func NewCSRApprovingController(client clientset.Interface, csrInformer certificatesinformers.CertificateSigningRequestInformer) *certificates.CertificateController {
  40. approver := &sarApprover{
  41. client: client,
  42. recognizers: recognizers(),
  43. }
  44. return certificates.NewCertificateController(
  45. "csrapproving",
  46. client,
  47. csrInformer,
  48. approver.handle,
  49. )
  50. }
  51. func recognizers() []csrRecognizer {
  52. recognizers := []csrRecognizer{
  53. {
  54. recognize: isSelfNodeClientCert,
  55. permission: authorization.ResourceAttributes{Group: "certificates.k8s.io", Resource: "certificatesigningrequests", Verb: "create", Subresource: "selfnodeclient"},
  56. successMessage: "Auto approving self kubelet client certificate after SubjectAccessReview.",
  57. },
  58. {
  59. recognize: isNodeClientCert,
  60. permission: authorization.ResourceAttributes{Group: "certificates.k8s.io", Resource: "certificatesigningrequests", Verb: "create", Subresource: "nodeclient"},
  61. successMessage: "Auto approving kubelet client certificate after SubjectAccessReview.",
  62. },
  63. }
  64. return recognizers
  65. }
  66. func (a *sarApprover) handle(csr *capi.CertificateSigningRequest) error {
  67. if len(csr.Status.Certificate) != 0 {
  68. return nil
  69. }
  70. if approved, denied := certificates.GetCertApprovalCondition(&csr.Status); approved || denied {
  71. return nil
  72. }
  73. x509cr, err := capihelper.ParseCSR(csr)
  74. if err != nil {
  75. return fmt.Errorf("unable to parse csr %q: %v", csr.Name, err)
  76. }
  77. tried := []string{}
  78. for _, r := range a.recognizers {
  79. if !r.recognize(csr, x509cr) {
  80. continue
  81. }
  82. tried = append(tried, r.permission.Subresource)
  83. approved, err := a.authorize(csr, r.permission)
  84. if err != nil {
  85. return err
  86. }
  87. if approved {
  88. appendApprovalCondition(csr, r.successMessage)
  89. _, err = a.client.CertificatesV1beta1().CertificateSigningRequests().UpdateApproval(csr)
  90. if err != nil {
  91. return fmt.Errorf("error updating approval for csr: %v", err)
  92. }
  93. return nil
  94. }
  95. }
  96. if len(tried) != 0 {
  97. return certificates.IgnorableError("recognized csr %q as %v but subject access review was not approved", csr.Name, tried)
  98. }
  99. return nil
  100. }
  101. func (a *sarApprover) authorize(csr *capi.CertificateSigningRequest, rattrs authorization.ResourceAttributes) (bool, error) {
  102. extra := make(map[string]authorization.ExtraValue)
  103. for k, v := range csr.Spec.Extra {
  104. extra[k] = authorization.ExtraValue(v)
  105. }
  106. sar := &authorization.SubjectAccessReview{
  107. Spec: authorization.SubjectAccessReviewSpec{
  108. User: csr.Spec.Username,
  109. UID: csr.Spec.UID,
  110. Groups: csr.Spec.Groups,
  111. Extra: extra,
  112. ResourceAttributes: &rattrs,
  113. },
  114. }
  115. sar, err := a.client.AuthorizationV1().SubjectAccessReviews().Create(context.TODO(), sar, metav1.CreateOptions{})
  116. if err != nil {
  117. return false, err
  118. }
  119. return sar.Status.Allowed, nil
  120. }
  121. func appendApprovalCondition(csr *capi.CertificateSigningRequest, message string) {
  122. csr.Status.Conditions = append(csr.Status.Conditions, capi.CertificateSigningRequestCondition{
  123. Type: capi.CertificateApproved,
  124. Reason: "AutoApproved",
  125. Message: message,
  126. })
  127. }
  128. func hasExactUsages(csr *capi.CertificateSigningRequest, usages []capi.KeyUsage) bool {
  129. if len(usages) != len(csr.Spec.Usages) {
  130. return false
  131. }
  132. usageMap := map[capi.KeyUsage]struct{}{}
  133. for _, u := range usages {
  134. usageMap[u] = struct{}{}
  135. }
  136. for _, u := range csr.Spec.Usages {
  137. if _, ok := usageMap[u]; !ok {
  138. return false
  139. }
  140. }
  141. return true
  142. }
  143. var kubeletClientUsages = []capi.KeyUsage{
  144. capi.UsageKeyEncipherment,
  145. capi.UsageDigitalSignature,
  146. capi.UsageClientAuth,
  147. }
  148. func isNodeClientCert(csr *capi.CertificateSigningRequest, x509cr *x509.CertificateRequest) bool {
  149. if !reflect.DeepEqual([]string{"system:nodes"}, x509cr.Subject.Organization) {
  150. return false
  151. }
  152. if len(x509cr.DNSNames) > 0 || len(x509cr.EmailAddresses) > 0 || len(x509cr.IPAddresses) > 0 || len(x509cr.URIs) > 0 {
  153. return false
  154. }
  155. if !hasExactUsages(csr, kubeletClientUsages) {
  156. return false
  157. }
  158. if !strings.HasPrefix(x509cr.Subject.CommonName, "system:node:") {
  159. return false
  160. }
  161. return true
  162. }
  163. func isSelfNodeClientCert(csr *capi.CertificateSigningRequest, x509cr *x509.CertificateRequest) bool {
  164. if !isNodeClientCert(csr, x509cr) {
  165. return false
  166. }
  167. if csr.Spec.Username != x509cr.Subject.CommonName {
  168. return false
  169. }
  170. return true
  171. }