abac.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. /*
  2. Copyright 2014 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 abac authorizes Kubernetes API actions using an Attribute-based access control scheme.
  14. package abac
  15. import (
  16. "bufio"
  17. "context"
  18. "fmt"
  19. "os"
  20. "strings"
  21. "k8s.io/klog"
  22. "k8s.io/apimachinery/pkg/runtime"
  23. "k8s.io/apiserver/pkg/authentication/user"
  24. "k8s.io/apiserver/pkg/authorization/authorizer"
  25. "k8s.io/kubernetes/pkg/apis/abac"
  26. // Import latest API for init/side-effects
  27. _ "k8s.io/kubernetes/pkg/apis/abac/latest"
  28. "k8s.io/kubernetes/pkg/apis/abac/v0"
  29. )
  30. type policyLoadError struct {
  31. path string
  32. line int
  33. data []byte
  34. err error
  35. }
  36. func (p policyLoadError) Error() string {
  37. if p.line >= 0 {
  38. return fmt.Sprintf("error reading policy file %s, line %d: %s: %v", p.path, p.line, string(p.data), p.err)
  39. }
  40. return fmt.Sprintf("error reading policy file %s: %v", p.path, p.err)
  41. }
  42. // PolicyList is simply a slice of Policy structs.
  43. type PolicyList []*abac.Policy
  44. // NewFromFile attempts to create a policy list from the given file.
  45. //
  46. // TODO: Have policies be created via an API call and stored in REST storage.
  47. func NewFromFile(path string) (PolicyList, error) {
  48. // File format is one map per line. This allows easy concatenation of files,
  49. // comments in files, and identification of errors by line number.
  50. file, err := os.Open(path)
  51. if err != nil {
  52. return nil, err
  53. }
  54. defer file.Close()
  55. scanner := bufio.NewScanner(file)
  56. pl := make(PolicyList, 0)
  57. decoder := abac.Codecs.UniversalDecoder()
  58. i := 0
  59. unversionedLines := 0
  60. for scanner.Scan() {
  61. i++
  62. p := &abac.Policy{}
  63. b := scanner.Bytes()
  64. // skip comment lines and blank lines
  65. trimmed := strings.TrimSpace(string(b))
  66. if len(trimmed) == 0 || strings.HasPrefix(trimmed, "#") {
  67. continue
  68. }
  69. decodedObj, _, err := decoder.Decode(b, nil, nil)
  70. if err != nil {
  71. if !(runtime.IsMissingVersion(err) || runtime.IsMissingKind(err) || runtime.IsNotRegisteredError(err)) {
  72. return nil, policyLoadError{path, i, b, err}
  73. }
  74. unversionedLines++
  75. // Migrate unversioned policy object
  76. oldPolicy := &v0.Policy{}
  77. if err := runtime.DecodeInto(decoder, b, oldPolicy); err != nil {
  78. return nil, policyLoadError{path, i, b, err}
  79. }
  80. if err := abac.Scheme.Convert(oldPolicy, p, nil); err != nil {
  81. return nil, policyLoadError{path, i, b, err}
  82. }
  83. pl = append(pl, p)
  84. continue
  85. }
  86. decodedPolicy, ok := decodedObj.(*abac.Policy)
  87. if !ok {
  88. return nil, policyLoadError{path, i, b, fmt.Errorf("unrecognized object: %#v", decodedObj)}
  89. }
  90. pl = append(pl, decodedPolicy)
  91. }
  92. if unversionedLines > 0 {
  93. klog.Warningf("Policy file %s contained unversioned rules. See docs/admin/authorization.md#abac-mode for ABAC file format details.", path)
  94. }
  95. if err := scanner.Err(); err != nil {
  96. return nil, policyLoadError{path, -1, nil, err}
  97. }
  98. return pl, nil
  99. }
  100. func matches(p abac.Policy, a authorizer.Attributes) bool {
  101. if subjectMatches(p, a.GetUser()) {
  102. if verbMatches(p, a) {
  103. // Resource and non-resource requests are mutually exclusive, at most one will match a policy
  104. if resourceMatches(p, a) {
  105. return true
  106. }
  107. if nonResourceMatches(p, a) {
  108. return true
  109. }
  110. }
  111. }
  112. return false
  113. }
  114. // subjectMatches returns true if specified user and group properties in the policy match the attributes
  115. func subjectMatches(p abac.Policy, user user.Info) bool {
  116. matched := false
  117. if user == nil {
  118. return false
  119. }
  120. username := user.GetName()
  121. groups := user.GetGroups()
  122. // If the policy specified a user, ensure it matches
  123. if len(p.Spec.User) > 0 {
  124. if p.Spec.User == "*" {
  125. matched = true
  126. } else {
  127. matched = p.Spec.User == username
  128. if !matched {
  129. return false
  130. }
  131. }
  132. }
  133. // If the policy specified a group, ensure it matches
  134. if len(p.Spec.Group) > 0 {
  135. if p.Spec.Group == "*" {
  136. matched = true
  137. } else {
  138. matched = false
  139. for _, group := range groups {
  140. if p.Spec.Group == group {
  141. matched = true
  142. }
  143. }
  144. if !matched {
  145. return false
  146. }
  147. }
  148. }
  149. return matched
  150. }
  151. func verbMatches(p abac.Policy, a authorizer.Attributes) bool {
  152. // TODO: match on verb
  153. // All policies allow read only requests
  154. if a.IsReadOnly() {
  155. return true
  156. }
  157. // Allow if policy is not readonly
  158. if !p.Spec.Readonly {
  159. return true
  160. }
  161. return false
  162. }
  163. func nonResourceMatches(p abac.Policy, a authorizer.Attributes) bool {
  164. // A non-resource policy cannot match a resource request
  165. if !a.IsResourceRequest() {
  166. // Allow wildcard match
  167. if p.Spec.NonResourcePath == "*" {
  168. return true
  169. }
  170. // Allow exact match
  171. if p.Spec.NonResourcePath == a.GetPath() {
  172. return true
  173. }
  174. // Allow a trailing * subpath match
  175. if strings.HasSuffix(p.Spec.NonResourcePath, "*") && strings.HasPrefix(a.GetPath(), strings.TrimRight(p.Spec.NonResourcePath, "*")) {
  176. return true
  177. }
  178. }
  179. return false
  180. }
  181. func resourceMatches(p abac.Policy, a authorizer.Attributes) bool {
  182. // A resource policy cannot match a non-resource request
  183. if a.IsResourceRequest() {
  184. if p.Spec.Namespace == "*" || p.Spec.Namespace == a.GetNamespace() {
  185. if p.Spec.Resource == "*" || p.Spec.Resource == a.GetResource() {
  186. if p.Spec.APIGroup == "*" || p.Spec.APIGroup == a.GetAPIGroup() {
  187. return true
  188. }
  189. }
  190. }
  191. }
  192. return false
  193. }
  194. // Authorize implements authorizer.Authorize
  195. func (pl PolicyList) Authorize(ctx context.Context, a authorizer.Attributes) (authorizer.Decision, string, error) {
  196. for _, p := range pl {
  197. if matches(*p, a) {
  198. return authorizer.DecisionAllow, "", nil
  199. }
  200. }
  201. return authorizer.DecisionNoOpinion, "No policy matched.", nil
  202. // TODO: Benchmark how much time policy matching takes with a medium size
  203. // policy file, compared to other steps such as encoding/decoding.
  204. // Then, add Caching only if needed.
  205. }
  206. // RulesFor returns rules for the given user and namespace.
  207. func (pl PolicyList) RulesFor(user user.Info, namespace string) ([]authorizer.ResourceRuleInfo, []authorizer.NonResourceRuleInfo, bool, error) {
  208. var (
  209. resourceRules []authorizer.ResourceRuleInfo
  210. nonResourceRules []authorizer.NonResourceRuleInfo
  211. )
  212. for _, p := range pl {
  213. if subjectMatches(*p, user) {
  214. if p.Spec.Namespace == "*" || p.Spec.Namespace == namespace {
  215. if len(p.Spec.Resource) > 0 {
  216. r := authorizer.DefaultResourceRuleInfo{
  217. Verbs: getVerbs(p.Spec.Readonly),
  218. APIGroups: []string{p.Spec.APIGroup},
  219. Resources: []string{p.Spec.Resource},
  220. }
  221. var resourceRule authorizer.ResourceRuleInfo = &r
  222. resourceRules = append(resourceRules, resourceRule)
  223. }
  224. if len(p.Spec.NonResourcePath) > 0 {
  225. r := authorizer.DefaultNonResourceRuleInfo{
  226. Verbs: getVerbs(p.Spec.Readonly),
  227. NonResourceURLs: []string{p.Spec.NonResourcePath},
  228. }
  229. var nonResourceRule authorizer.NonResourceRuleInfo = &r
  230. nonResourceRules = append(nonResourceRules, nonResourceRule)
  231. }
  232. }
  233. }
  234. }
  235. return resourceRules, nonResourceRules, false, nil
  236. }
  237. func getVerbs(isReadOnly bool) []string {
  238. if isReadOnly {
  239. return []string{"get", "list", "watch"}
  240. }
  241. return []string{"*"}
  242. }