rbac.go 7.7 KB

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