abac.go 7.3 KB

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