node_authorizer.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. /*
  2. Copyright 2017 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 node
  14. import (
  15. "context"
  16. "fmt"
  17. "k8s.io/klog"
  18. rbacv1 "k8s.io/api/rbac/v1"
  19. "k8s.io/apimachinery/pkg/runtime/schema"
  20. "k8s.io/apiserver/pkg/authorization/authorizer"
  21. utilfeature "k8s.io/apiserver/pkg/util/feature"
  22. "k8s.io/component-base/featuregate"
  23. coordapi "k8s.io/kubernetes/pkg/apis/coordination"
  24. api "k8s.io/kubernetes/pkg/apis/core"
  25. storageapi "k8s.io/kubernetes/pkg/apis/storage"
  26. "k8s.io/kubernetes/pkg/auth/nodeidentifier"
  27. "k8s.io/kubernetes/pkg/features"
  28. "k8s.io/kubernetes/plugin/pkg/auth/authorizer/rbac"
  29. "k8s.io/kubernetes/third_party/forked/gonum/graph"
  30. "k8s.io/kubernetes/third_party/forked/gonum/graph/traverse"
  31. )
  32. // NodeAuthorizer authorizes requests from kubelets, with the following logic:
  33. // 1. If a request is not from a node (NodeIdentity() returns isNode=false), reject
  34. // 2. If a specific node cannot be identified (NodeIdentity() returns nodeName=""), reject
  35. // 3. If a request is for a secret, configmap, persistent volume or persistent volume claim, reject unless the verb is get, and the requested object is related to the requesting node:
  36. // node <- configmap
  37. // node <- pod
  38. // node <- pod <- secret
  39. // node <- pod <- configmap
  40. // node <- pod <- pvc
  41. // node <- pod <- pvc <- pv
  42. // node <- pod <- pvc <- pv <- secret
  43. // 4. For other resources, authorize all nodes uniformly using statically defined rules
  44. type NodeAuthorizer struct {
  45. graph *Graph
  46. identifier nodeidentifier.NodeIdentifier
  47. nodeRules []rbacv1.PolicyRule
  48. // allows overriding for testing
  49. features featuregate.FeatureGate
  50. }
  51. // NewAuthorizer returns a new node authorizer
  52. func NewAuthorizer(graph *Graph, identifier nodeidentifier.NodeIdentifier, rules []rbacv1.PolicyRule) authorizer.Authorizer {
  53. return &NodeAuthorizer{
  54. graph: graph,
  55. identifier: identifier,
  56. nodeRules: rules,
  57. features: utilfeature.DefaultFeatureGate,
  58. }
  59. }
  60. var (
  61. configMapResource = api.Resource("configmaps")
  62. secretResource = api.Resource("secrets")
  63. pvcResource = api.Resource("persistentvolumeclaims")
  64. pvResource = api.Resource("persistentvolumes")
  65. vaResource = storageapi.Resource("volumeattachments")
  66. svcAcctResource = api.Resource("serviceaccounts")
  67. leaseResource = coordapi.Resource("leases")
  68. csiNodeResource = storageapi.Resource("csinodes")
  69. )
  70. func (r *NodeAuthorizer) Authorize(ctx context.Context, attrs authorizer.Attributes) (authorizer.Decision, string, error) {
  71. nodeName, isNode := r.identifier.NodeIdentity(attrs.GetUser())
  72. if !isNode {
  73. // reject requests from non-nodes
  74. return authorizer.DecisionNoOpinion, "", nil
  75. }
  76. if len(nodeName) == 0 {
  77. // reject requests from unidentifiable nodes
  78. klog.V(2).Infof("NODE DENY: unknown node for user %q", attrs.GetUser().GetName())
  79. return authorizer.DecisionNoOpinion, fmt.Sprintf("unknown node for user %q", attrs.GetUser().GetName()), nil
  80. }
  81. // subdivide access to specific resources
  82. if attrs.IsResourceRequest() {
  83. requestResource := schema.GroupResource{Group: attrs.GetAPIGroup(), Resource: attrs.GetResource()}
  84. switch requestResource {
  85. case secretResource:
  86. return r.authorizeReadNamespacedObject(nodeName, secretVertexType, attrs)
  87. case configMapResource:
  88. return r.authorizeReadNamespacedObject(nodeName, configMapVertexType, attrs)
  89. case pvcResource:
  90. if r.features.Enabled(features.ExpandPersistentVolumes) {
  91. if attrs.GetSubresource() == "status" {
  92. return r.authorizeStatusUpdate(nodeName, pvcVertexType, attrs)
  93. }
  94. }
  95. return r.authorizeGet(nodeName, pvcVertexType, attrs)
  96. case pvResource:
  97. return r.authorizeGet(nodeName, pvVertexType, attrs)
  98. case vaResource:
  99. return r.authorizeGet(nodeName, vaVertexType, attrs)
  100. case svcAcctResource:
  101. if r.features.Enabled(features.TokenRequest) {
  102. return r.authorizeCreateToken(nodeName, serviceAccountVertexType, attrs)
  103. }
  104. return authorizer.DecisionNoOpinion, fmt.Sprintf("disabled by feature gate %s", features.TokenRequest), nil
  105. case leaseResource:
  106. return r.authorizeLease(nodeName, attrs)
  107. case csiNodeResource:
  108. if r.features.Enabled(features.CSINodeInfo) {
  109. return r.authorizeCSINode(nodeName, attrs)
  110. }
  111. return authorizer.DecisionNoOpinion, fmt.Sprintf("disabled by feature gates %s", features.CSINodeInfo), nil
  112. }
  113. }
  114. // Access to other resources is not subdivided, so just evaluate against the statically defined node rules
  115. if rbac.RulesAllow(attrs, r.nodeRules...) {
  116. return authorizer.DecisionAllow, "", nil
  117. }
  118. return authorizer.DecisionNoOpinion, "", nil
  119. }
  120. // authorizeStatusUpdate authorizes get/update/patch requests to status subresources of the specified type if they are related to the specified node
  121. func (r *NodeAuthorizer) authorizeStatusUpdate(nodeName string, startingType vertexType, attrs authorizer.Attributes) (authorizer.Decision, string, error) {
  122. switch attrs.GetVerb() {
  123. case "update", "patch":
  124. // ok
  125. default:
  126. klog.V(2).Infof("NODE DENY: %s %#v", nodeName, attrs)
  127. return authorizer.DecisionNoOpinion, "can only get/update/patch this type", nil
  128. }
  129. if attrs.GetSubresource() != "status" {
  130. klog.V(2).Infof("NODE DENY: %s %#v", nodeName, attrs)
  131. return authorizer.DecisionNoOpinion, "can only update status subresource", nil
  132. }
  133. return r.authorize(nodeName, startingType, attrs)
  134. }
  135. // authorizeGet authorizes "get" requests to objects of the specified type if they are related to the specified node
  136. func (r *NodeAuthorizer) authorizeGet(nodeName string, startingType vertexType, attrs authorizer.Attributes) (authorizer.Decision, string, error) {
  137. if attrs.GetVerb() != "get" {
  138. klog.V(2).Infof("NODE DENY: %s %#v", nodeName, attrs)
  139. return authorizer.DecisionNoOpinion, "can only get individual resources of this type", nil
  140. }
  141. if len(attrs.GetSubresource()) > 0 {
  142. klog.V(2).Infof("NODE DENY: %s %#v", nodeName, attrs)
  143. return authorizer.DecisionNoOpinion, "cannot get subresource", nil
  144. }
  145. return r.authorize(nodeName, startingType, attrs)
  146. }
  147. // authorizeReadNamespacedObject authorizes "get", "list" and "watch" requests to single objects of a
  148. // specified types if they are related to the specified node.
  149. func (r *NodeAuthorizer) authorizeReadNamespacedObject(nodeName string, startingType vertexType, attrs authorizer.Attributes) (authorizer.Decision, string, error) {
  150. switch attrs.GetVerb() {
  151. case "get", "list", "watch":
  152. //ok
  153. default:
  154. klog.V(2).Infof("NODE DENY: %s %#v", nodeName, attrs)
  155. return authorizer.DecisionNoOpinion, "can only read resources of this type", nil
  156. }
  157. if len(attrs.GetSubresource()) > 0 {
  158. klog.V(2).Infof("NODE DENY: %s %#v", nodeName, attrs)
  159. return authorizer.DecisionNoOpinion, "cannot read subresource", nil
  160. }
  161. if len(attrs.GetNamespace()) == 0 {
  162. klog.V(2).Infof("NODE DENY: %s %#v", nodeName, attrs)
  163. return authorizer.DecisionNoOpinion, "can only read namespaced object of this type", nil
  164. }
  165. return r.authorize(nodeName, startingType, attrs)
  166. }
  167. func (r *NodeAuthorizer) authorize(nodeName string, startingType vertexType, attrs authorizer.Attributes) (authorizer.Decision, string, error) {
  168. if len(attrs.GetName()) == 0 {
  169. klog.V(2).Infof("NODE DENY: %s %#v", nodeName, attrs)
  170. return authorizer.DecisionNoOpinion, "No Object name found", nil
  171. }
  172. ok, err := r.hasPathFrom(nodeName, startingType, attrs.GetNamespace(), attrs.GetName())
  173. if err != nil {
  174. klog.V(2).Infof("NODE DENY: %v", err)
  175. return authorizer.DecisionNoOpinion, fmt.Sprintf("no relationship found between node %q and this object", nodeName), nil
  176. }
  177. if !ok {
  178. klog.V(2).Infof("NODE DENY: %q %#v", nodeName, attrs)
  179. return authorizer.DecisionNoOpinion, fmt.Sprintf("no relationship found between node %q and this object", nodeName), nil
  180. }
  181. return authorizer.DecisionAllow, "", nil
  182. }
  183. // authorizeCreateToken authorizes "create" requests to serviceaccounts 'token'
  184. // subresource of pods running on a node
  185. func (r *NodeAuthorizer) authorizeCreateToken(nodeName string, startingType vertexType, attrs authorizer.Attributes) (authorizer.Decision, string, error) {
  186. if attrs.GetVerb() != "create" || len(attrs.GetName()) == 0 {
  187. klog.V(2).Infof("NODE DENY: %s %#v", nodeName, attrs)
  188. return authorizer.DecisionNoOpinion, "can only create tokens for individual service accounts", nil
  189. }
  190. if attrs.GetSubresource() != "token" {
  191. klog.V(2).Infof("NODE DENY: %s %#v", nodeName, attrs)
  192. return authorizer.DecisionNoOpinion, "can only create token subresource of serviceaccount", nil
  193. }
  194. ok, err := r.hasPathFrom(nodeName, startingType, attrs.GetNamespace(), attrs.GetName())
  195. if err != nil {
  196. klog.V(2).Infof("NODE DENY: %v", err)
  197. return authorizer.DecisionNoOpinion, fmt.Sprintf("no relationship found between node %q and this object", nodeName), nil
  198. }
  199. if !ok {
  200. klog.V(2).Infof("NODE DENY: %q %#v", nodeName, attrs)
  201. return authorizer.DecisionNoOpinion, fmt.Sprintf("no relationship found between node %q and this object", nodeName), nil
  202. }
  203. return authorizer.DecisionAllow, "", nil
  204. }
  205. // authorizeLease authorizes node requests to coordination.k8s.io/leases.
  206. func (r *NodeAuthorizer) authorizeLease(nodeName string, attrs authorizer.Attributes) (authorizer.Decision, string, error) {
  207. // allowed verbs: get, create, update, patch, delete
  208. verb := attrs.GetVerb()
  209. switch verb {
  210. case "get", "create", "update", "patch", "delete":
  211. //ok
  212. default:
  213. klog.V(2).Infof("NODE DENY: %s %#v", nodeName, attrs)
  214. return authorizer.DecisionNoOpinion, "can only get, create, update, patch, or delete a node lease", nil
  215. }
  216. // the request must be against the system namespace reserved for node leases
  217. if attrs.GetNamespace() != api.NamespaceNodeLease {
  218. klog.V(2).Infof("NODE DENY: %s %#v", nodeName, attrs)
  219. return authorizer.DecisionNoOpinion, fmt.Sprintf("can only access leases in the %q system namespace", api.NamespaceNodeLease), nil
  220. }
  221. // the request must come from a node with the same name as the lease
  222. // note we skip this check for create, since the authorizer doesn't know the name on create
  223. // the noderestriction admission plugin is capable of performing this check at create time
  224. if verb != "create" && attrs.GetName() != nodeName {
  225. klog.V(2).Infof("NODE DENY: %s %#v", nodeName, attrs)
  226. return authorizer.DecisionNoOpinion, "can only access node lease with the same name as the requesting node", nil
  227. }
  228. return authorizer.DecisionAllow, "", nil
  229. }
  230. // authorizeCSINode authorizes node requests to CSINode storage.k8s.io/csinodes
  231. func (r *NodeAuthorizer) authorizeCSINode(nodeName string, attrs authorizer.Attributes) (authorizer.Decision, string, error) {
  232. // allowed verbs: get, create, update, patch, delete
  233. verb := attrs.GetVerb()
  234. switch verb {
  235. case "get", "create", "update", "patch", "delete":
  236. //ok
  237. default:
  238. klog.V(2).Infof("NODE DENY: %s %#v", nodeName, attrs)
  239. return authorizer.DecisionNoOpinion, "can only get, create, update, patch, or delete a CSINode", nil
  240. }
  241. if len(attrs.GetSubresource()) > 0 {
  242. klog.V(2).Infof("NODE DENY: %s %#v", nodeName, attrs)
  243. return authorizer.DecisionNoOpinion, "cannot authorize CSINode subresources", nil
  244. }
  245. // the request must come from a node with the same name as the CSINode
  246. // note we skip this check for create, since the authorizer doesn't know the name on create
  247. // the noderestriction admission plugin is capable of performing this check at create time
  248. if verb != "create" && attrs.GetName() != nodeName {
  249. klog.V(2).Infof("NODE DENY: %s %#v", nodeName, attrs)
  250. return authorizer.DecisionNoOpinion, "can only access CSINode with the same name as the requesting node", nil
  251. }
  252. return authorizer.DecisionAllow, "", nil
  253. }
  254. // hasPathFrom returns true if there is a directed path from the specified type/namespace/name to the specified Node
  255. func (r *NodeAuthorizer) hasPathFrom(nodeName string, startingType vertexType, startingNamespace, startingName string) (bool, error) {
  256. r.graph.lock.RLock()
  257. defer r.graph.lock.RUnlock()
  258. nodeVertex, exists := r.graph.getVertex_rlocked(nodeVertexType, "", nodeName)
  259. if !exists {
  260. return false, fmt.Errorf("unknown node %q cannot get %s %s/%s", nodeName, vertexTypes[startingType], startingNamespace, startingName)
  261. }
  262. startingVertex, exists := r.graph.getVertex_rlocked(startingType, startingNamespace, startingName)
  263. if !exists {
  264. return false, fmt.Errorf("node %q cannot get unknown %s %s/%s", nodeName, vertexTypes[startingType], startingNamespace, startingName)
  265. }
  266. // Fast check to see if we know of a destination edge
  267. if r.graph.destinationEdgeIndex[startingVertex.ID()].has(nodeVertex.ID()) {
  268. return true, nil
  269. }
  270. found := false
  271. traversal := &traverse.VisitingDepthFirst{
  272. EdgeFilter: func(edge graph.Edge) bool {
  273. if destinationEdge, ok := edge.(*destinationEdge); ok {
  274. if destinationEdge.DestinationID() != nodeVertex.ID() {
  275. // Don't follow edges leading to other nodes
  276. return false
  277. }
  278. // We found an edge leading to the node we want
  279. found = true
  280. }
  281. // Visit this edge
  282. return true
  283. },
  284. }
  285. traversal.Walk(r.graph.graph, startingVertex, func(n graph.Node) bool {
  286. if n.ID() == nodeVertex.ID() {
  287. // We found the node we want
  288. found = true
  289. }
  290. // Stop visiting if we've found the node we want
  291. return found
  292. })
  293. if !found {
  294. return false, fmt.Errorf("node %q cannot get %s %s/%s, no relationship to this object was found in the node authorizer graph", nodeName, vertexTypes[startingType], startingNamespace, startingName)
  295. }
  296. return true, nil
  297. }