rbac.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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 rbac implements the authorizer.Authorizer interface using roles base access control.
  14. package rbac
  15. import (
  16. "bytes"
  17. "context"
  18. "fmt"
  19. "k8s.io/klog"
  20. rbacv1 "k8s.io/api/rbac/v1"
  21. "k8s.io/apimachinery/pkg/labels"
  22. utilerrors "k8s.io/apimachinery/pkg/util/errors"
  23. "k8s.io/apiserver/pkg/authentication/user"
  24. "k8s.io/apiserver/pkg/authorization/authorizer"
  25. rbaclisters "k8s.io/client-go/listers/rbac/v1"
  26. rbacv1helpers "k8s.io/kubernetes/pkg/apis/rbac/v1"
  27. rbacregistryvalidation "k8s.io/kubernetes/pkg/registry/rbac/validation"
  28. )
  29. type RequestToRuleMapper interface {
  30. // RulesFor returns all known PolicyRules and any errors that happened while locating those rules.
  31. // Any rule returned is still valid, since rules are deny by default. If you can pass with the rules
  32. // supplied, you do not have to fail the request. If you cannot, you should indicate the error along
  33. // with your denial.
  34. RulesFor(subject user.Info, namespace string) ([]rbacv1.PolicyRule, error)
  35. // VisitRulesFor invokes visitor() with each rule that applies to a given user in a given namespace,
  36. // and each error encountered resolving those rules. Rule may be nil if err is non-nil.
  37. // If visitor() returns false, visiting is short-circuited.
  38. VisitRulesFor(user user.Info, namespace string, visitor func(source fmt.Stringer, rule *rbacv1.PolicyRule, err error) bool)
  39. }
  40. type RBACAuthorizer struct {
  41. authorizationRuleResolver RequestToRuleMapper
  42. }
  43. // authorizingVisitor short-circuits once allowed, and collects any resolution errors encountered
  44. type authorizingVisitor struct {
  45. requestAttributes authorizer.Attributes
  46. allowed bool
  47. reason string
  48. errors []error
  49. }
  50. func (v *authorizingVisitor) visit(source fmt.Stringer, rule *rbacv1.PolicyRule, err error) bool {
  51. if rule != nil && RuleAllows(v.requestAttributes, rule) {
  52. v.allowed = true
  53. v.reason = fmt.Sprintf("RBAC: allowed by %s", source.String())
  54. return false
  55. }
  56. if err != nil {
  57. v.errors = append(v.errors, err)
  58. }
  59. return true
  60. }
  61. func (r *RBACAuthorizer) Authorize(ctx context.Context, requestAttributes authorizer.Attributes) (authorizer.Decision, string, error) {
  62. ruleCheckingVisitor := &authorizingVisitor{requestAttributes: requestAttributes}
  63. r.authorizationRuleResolver.VisitRulesFor(requestAttributes.GetUser(), requestAttributes.GetNamespace(), ruleCheckingVisitor.visit)
  64. if ruleCheckingVisitor.allowed {
  65. return authorizer.DecisionAllow, ruleCheckingVisitor.reason, nil
  66. }
  67. // Build a detailed log of the denial.
  68. // Make the whole block conditional so we don't do a lot of string-building we won't use.
  69. if klog.V(5) {
  70. var operation string
  71. if requestAttributes.IsResourceRequest() {
  72. b := &bytes.Buffer{}
  73. b.WriteString(`"`)
  74. b.WriteString(requestAttributes.GetVerb())
  75. b.WriteString(`" resource "`)
  76. b.WriteString(requestAttributes.GetResource())
  77. if len(requestAttributes.GetAPIGroup()) > 0 {
  78. b.WriteString(`.`)
  79. b.WriteString(requestAttributes.GetAPIGroup())
  80. }
  81. if len(requestAttributes.GetSubresource()) > 0 {
  82. b.WriteString(`/`)
  83. b.WriteString(requestAttributes.GetSubresource())
  84. }
  85. b.WriteString(`"`)
  86. if len(requestAttributes.GetName()) > 0 {
  87. b.WriteString(` named "`)
  88. b.WriteString(requestAttributes.GetName())
  89. b.WriteString(`"`)
  90. }
  91. operation = b.String()
  92. } else {
  93. operation = fmt.Sprintf("%q nonResourceURL %q", requestAttributes.GetVerb(), requestAttributes.GetPath())
  94. }
  95. var scope string
  96. if ns := requestAttributes.GetNamespace(); len(ns) > 0 {
  97. scope = fmt.Sprintf("in namespace %q", ns)
  98. } else {
  99. scope = "cluster-wide"
  100. }
  101. klog.Infof("RBAC DENY: user %q groups %q cannot %s %s", requestAttributes.GetUser().GetName(), requestAttributes.GetUser().GetGroups(), operation, scope)
  102. }
  103. reason := ""
  104. if len(ruleCheckingVisitor.errors) > 0 {
  105. reason = fmt.Sprintf("RBAC: %v", utilerrors.NewAggregate(ruleCheckingVisitor.errors))
  106. }
  107. return authorizer.DecisionNoOpinion, reason, nil
  108. }
  109. func (r *RBACAuthorizer) RulesFor(user user.Info, namespace string) ([]authorizer.ResourceRuleInfo, []authorizer.NonResourceRuleInfo, bool, error) {
  110. var (
  111. resourceRules []authorizer.ResourceRuleInfo
  112. nonResourceRules []authorizer.NonResourceRuleInfo
  113. )
  114. policyRules, err := r.authorizationRuleResolver.RulesFor(user, namespace)
  115. for _, policyRule := range policyRules {
  116. if len(policyRule.Resources) > 0 {
  117. r := authorizer.DefaultResourceRuleInfo{
  118. Verbs: policyRule.Verbs,
  119. APIGroups: policyRule.APIGroups,
  120. Resources: policyRule.Resources,
  121. ResourceNames: policyRule.ResourceNames,
  122. }
  123. var resourceRule authorizer.ResourceRuleInfo = &r
  124. resourceRules = append(resourceRules, resourceRule)
  125. }
  126. if len(policyRule.NonResourceURLs) > 0 {
  127. r := authorizer.DefaultNonResourceRuleInfo{
  128. Verbs: policyRule.Verbs,
  129. NonResourceURLs: policyRule.NonResourceURLs,
  130. }
  131. var nonResourceRule authorizer.NonResourceRuleInfo = &r
  132. nonResourceRules = append(nonResourceRules, nonResourceRule)
  133. }
  134. }
  135. return resourceRules, nonResourceRules, false, err
  136. }
  137. func New(roles rbacregistryvalidation.RoleGetter, roleBindings rbacregistryvalidation.RoleBindingLister, clusterRoles rbacregistryvalidation.ClusterRoleGetter, clusterRoleBindings rbacregistryvalidation.ClusterRoleBindingLister) *RBACAuthorizer {
  138. authorizer := &RBACAuthorizer{
  139. authorizationRuleResolver: rbacregistryvalidation.NewDefaultRuleResolver(
  140. roles, roleBindings, clusterRoles, clusterRoleBindings,
  141. ),
  142. }
  143. return authorizer
  144. }
  145. func RulesAllow(requestAttributes authorizer.Attributes, rules ...rbacv1.PolicyRule) bool {
  146. for i := range rules {
  147. if RuleAllows(requestAttributes, &rules[i]) {
  148. return true
  149. }
  150. }
  151. return false
  152. }
  153. func RuleAllows(requestAttributes authorizer.Attributes, rule *rbacv1.PolicyRule) bool {
  154. if requestAttributes.IsResourceRequest() {
  155. combinedResource := requestAttributes.GetResource()
  156. if len(requestAttributes.GetSubresource()) > 0 {
  157. combinedResource = requestAttributes.GetResource() + "/" + requestAttributes.GetSubresource()
  158. }
  159. return rbacv1helpers.VerbMatches(rule, requestAttributes.GetVerb()) &&
  160. rbacv1helpers.APIGroupMatches(rule, requestAttributes.GetAPIGroup()) &&
  161. rbacv1helpers.ResourceMatches(rule, combinedResource, requestAttributes.GetSubresource()) &&
  162. rbacv1helpers.ResourceNameMatches(rule, requestAttributes.GetName())
  163. }
  164. return rbacv1helpers.VerbMatches(rule, requestAttributes.GetVerb()) &&
  165. rbacv1helpers.NonResourceURLMatches(rule, requestAttributes.GetPath())
  166. }
  167. type RoleGetter struct {
  168. Lister rbaclisters.RoleLister
  169. }
  170. func (g *RoleGetter) GetRole(namespace, name string) (*rbacv1.Role, error) {
  171. return g.Lister.Roles(namespace).Get(name)
  172. }
  173. type RoleBindingLister struct {
  174. Lister rbaclisters.RoleBindingLister
  175. }
  176. func (l *RoleBindingLister) ListRoleBindings(namespace string) ([]*rbacv1.RoleBinding, error) {
  177. return l.Lister.RoleBindings(namespace).List(labels.Everything())
  178. }
  179. type ClusterRoleGetter struct {
  180. Lister rbaclisters.ClusterRoleLister
  181. }
  182. func (g *ClusterRoleGetter) GetClusterRole(name string) (*rbacv1.ClusterRole, error) {
  183. return g.Lister.Get(name)
  184. }
  185. type ClusterRoleBindingLister struct {
  186. Lister rbaclisters.ClusterRoleBindingLister
  187. }
  188. func (l *ClusterRoleBindingLister) ListClusterRoleBindings() ([]*rbacv1.ClusterRoleBinding, error) {
  189. return l.Lister.List(labels.Everything())
  190. }