handler_impersonation.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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 apiserver
  14. import (
  15. "fmt"
  16. "net/http"
  17. "strings"
  18. "github.com/golang/glog"
  19. "k8s.io/kubernetes/pkg/api"
  20. authenticationapi "k8s.io/kubernetes/pkg/apis/authentication"
  21. "k8s.io/kubernetes/pkg/auth/authorizer"
  22. "k8s.io/kubernetes/pkg/auth/user"
  23. "k8s.io/kubernetes/pkg/httplog"
  24. "k8s.io/kubernetes/pkg/serviceaccount"
  25. )
  26. // WithImpersonation is a filter that will inspect and check requests that attempt to change the user.Info for their requests
  27. func WithImpersonation(handler http.Handler, requestContextMapper api.RequestContextMapper, a authorizer.Authorizer) http.Handler {
  28. return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  29. impersonationRequests, err := buildImpersonationRequests(req.Header)
  30. if err != nil {
  31. glog.V(4).Infof("%v", err)
  32. forbidden(w, req)
  33. return
  34. }
  35. if len(impersonationRequests) == 0 {
  36. handler.ServeHTTP(w, req)
  37. return
  38. }
  39. ctx, exists := requestContextMapper.Get(req)
  40. if !exists {
  41. forbidden(w, req)
  42. return
  43. }
  44. requestor, exists := api.UserFrom(ctx)
  45. if !exists {
  46. forbidden(w, req)
  47. return
  48. }
  49. // if groups are not specified, then we need to look them up differently depending on the type of user
  50. // if they are specified, then they are the authority
  51. groupsSpecified := len(req.Header[authenticationapi.ImpersonateGroupHeader]) > 0
  52. // make sure we're allowed to impersonate each thing we're requesting. While we're iterating through, start building username
  53. // and group information
  54. username := ""
  55. groups := []string{}
  56. userExtra := map[string][]string{}
  57. for _, impersonationRequest := range impersonationRequests {
  58. actingAsAttributes := &authorizer.AttributesRecord{
  59. User: requestor,
  60. Verb: "impersonate",
  61. APIGroup: impersonationRequest.GetObjectKind().GroupVersionKind().Group,
  62. Namespace: impersonationRequest.Namespace,
  63. Name: impersonationRequest.Name,
  64. ResourceRequest: true,
  65. }
  66. switch impersonationRequest.GetObjectKind().GroupVersionKind().GroupKind() {
  67. case api.Kind("ServiceAccount"):
  68. actingAsAttributes.Resource = "serviceaccounts"
  69. username = serviceaccount.MakeUsername(impersonationRequest.Namespace, impersonationRequest.Name)
  70. if !groupsSpecified {
  71. // if groups aren't specified for a service account, we know the groups because its a fixed mapping. Add them
  72. groups = serviceaccount.MakeGroupNames(impersonationRequest.Namespace, impersonationRequest.Name)
  73. }
  74. case api.Kind("User"):
  75. actingAsAttributes.Resource = "users"
  76. username = impersonationRequest.Name
  77. case api.Kind("Group"):
  78. actingAsAttributes.Resource = "groups"
  79. groups = append(groups, impersonationRequest.Name)
  80. case authenticationapi.Kind("UserExtra"):
  81. extraKey := impersonationRequest.FieldPath
  82. extraValue := impersonationRequest.Name
  83. actingAsAttributes.Resource = "userextras"
  84. actingAsAttributes.Subresource = extraKey
  85. userExtra[extraKey] = append(userExtra[extraKey], extraValue)
  86. default:
  87. glog.V(4).Infof("unknown impersonation request type: %v\n", impersonationRequest)
  88. forbidden(w, req)
  89. return
  90. }
  91. allowed, reason, err := a.Authorize(actingAsAttributes)
  92. if err != nil || !allowed {
  93. glog.V(4).Infof("Forbidden: %#v, Reason: %s, Error: %v", req.RequestURI, reason, err)
  94. forbidden(w, req)
  95. return
  96. }
  97. }
  98. newUser := &user.DefaultInfo{
  99. Name: username,
  100. Groups: groups,
  101. Extra: userExtra,
  102. }
  103. requestContextMapper.Update(req, api.WithUser(ctx, newUser))
  104. oldUser, _ := api.UserFrom(ctx)
  105. httplog.LogOf(req, w).Addf("%v is acting as %v", oldUser, newUser)
  106. handler.ServeHTTP(w, req)
  107. })
  108. }
  109. // buildImpersonationRequests returns a list of objectreferences that represent the different things we're requesting to impersonate.
  110. // Also includes a map[string][]string representing user.Info.Extra
  111. // Each request must be authorized against the current user before switching contexts.
  112. func buildImpersonationRequests(headers http.Header) ([]api.ObjectReference, error) {
  113. impersonationRequests := []api.ObjectReference{}
  114. requestedUser := headers.Get(authenticationapi.ImpersonateUserHeader)
  115. hasUser := len(requestedUser) > 0
  116. if hasUser {
  117. if namespace, name, err := serviceaccount.SplitUsername(requestedUser); err == nil {
  118. impersonationRequests = append(impersonationRequests, api.ObjectReference{Kind: "ServiceAccount", Namespace: namespace, Name: name})
  119. } else {
  120. impersonationRequests = append(impersonationRequests, api.ObjectReference{Kind: "User", Name: requestedUser})
  121. }
  122. }
  123. hasGroups := false
  124. for _, group := range headers[authenticationapi.ImpersonateGroupHeader] {
  125. hasGroups = true
  126. impersonationRequests = append(impersonationRequests, api.ObjectReference{Kind: "Group", Name: group})
  127. }
  128. hasUserExtra := false
  129. for headerName, values := range headers {
  130. if !strings.HasPrefix(headerName, authenticationapi.ImpersonateUserExtraHeaderPrefix) {
  131. continue
  132. }
  133. hasUserExtra = true
  134. extraKey := strings.ToLower(headerName[len(authenticationapi.ImpersonateUserExtraHeaderPrefix):])
  135. // make a separate request for each extra value they're trying to set
  136. for _, value := range values {
  137. impersonationRequests = append(impersonationRequests,
  138. api.ObjectReference{
  139. Kind: "UserExtra",
  140. // we only parse out a group above, but the parsing will fail if there isn't SOME version
  141. // using the internal version will help us fail if anyone starts using it
  142. APIVersion: authenticationapi.SchemeGroupVersion.String(),
  143. Name: value,
  144. // ObjectReference doesn't have a subresource field. FieldPath is close and available, so we'll use that
  145. // TODO fight the good fight for ObjectReference to refer to resources and subresources
  146. FieldPath: extraKey,
  147. })
  148. }
  149. }
  150. if (hasGroups || hasUserExtra) && !hasUser {
  151. return nil, fmt.Errorf("requested %v without impersonating a user", impersonationRequests)
  152. }
  153. return impersonationRequests, nil
  154. }