cani.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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 auth
  14. import (
  15. "errors"
  16. "fmt"
  17. "io"
  18. "io/ioutil"
  19. "os"
  20. "sort"
  21. "strings"
  22. "github.com/spf13/cobra"
  23. authorizationv1 "k8s.io/api/authorization/v1"
  24. rbacv1 "k8s.io/api/rbac/v1"
  25. "k8s.io/apimachinery/pkg/api/meta"
  26. "k8s.io/apimachinery/pkg/runtime/schema"
  27. utilerrors "k8s.io/apimachinery/pkg/util/errors"
  28. "k8s.io/cli-runtime/pkg/genericclioptions"
  29. discovery "k8s.io/client-go/discovery"
  30. authorizationv1client "k8s.io/client-go/kubernetes/typed/authorization/v1"
  31. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  32. describeutil "k8s.io/kubernetes/pkg/kubectl/describe/versioned"
  33. "k8s.io/kubernetes/pkg/kubectl/util/printers"
  34. rbacutil "k8s.io/kubernetes/pkg/kubectl/util/rbac"
  35. "k8s.io/kubernetes/pkg/kubectl/util/templates"
  36. )
  37. // CanIOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of
  38. // referencing the cmd.Flags()
  39. type CanIOptions struct {
  40. AllNamespaces bool
  41. Quiet bool
  42. NoHeaders bool
  43. Namespace string
  44. AuthClient authorizationv1client.AuthorizationV1Interface
  45. DiscoveryClient discovery.DiscoveryInterface
  46. Verb string
  47. Resource schema.GroupVersionResource
  48. NonResourceURL string
  49. Subresource string
  50. ResourceName string
  51. List bool
  52. genericclioptions.IOStreams
  53. }
  54. var (
  55. canILong = templates.LongDesc(`
  56. Check whether an action is allowed.
  57. VERB is a logical Kubernetes API verb like 'get', 'list', 'watch', 'delete', etc.
  58. TYPE is a Kubernetes resource. Shortcuts and groups will be resolved.
  59. NONRESOURCEURL is a partial URL starts with "/".
  60. NAME is the name of a particular Kubernetes resource.`)
  61. canIExample = templates.Examples(`
  62. # Check to see if I can create pods in any namespace
  63. kubectl auth can-i create pods --all-namespaces
  64. # Check to see if I can list deployments in my current namespace
  65. kubectl auth can-i list deployments.extensions
  66. # Check to see if I can do everything in my current namespace ("*" means all)
  67. kubectl auth can-i '*' '*'
  68. # Check to see if I can get the job named "bar" in namespace "foo"
  69. kubectl auth can-i list jobs.batch/bar -n foo
  70. # Check to see if I can read pod logs
  71. kubectl auth can-i get pods --subresource=log
  72. # Check to see if I can access the URL /logs/
  73. kubectl auth can-i get /logs/
  74. # List all allowed actions in namespace "foo"
  75. kubectl auth can-i --list --namespace=foo`)
  76. )
  77. // NewCmdCanI returns an initialized Command for 'auth can-i' sub command
  78. func NewCmdCanI(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
  79. o := &CanIOptions{
  80. IOStreams: streams,
  81. }
  82. cmd := &cobra.Command{
  83. Use: "can-i VERB [TYPE | TYPE/NAME | NONRESOURCEURL]",
  84. DisableFlagsInUseLine: true,
  85. Short: "Check whether an action is allowed",
  86. Long: canILong,
  87. Example: canIExample,
  88. Run: func(cmd *cobra.Command, args []string) {
  89. cmdutil.CheckErr(o.Complete(f, args))
  90. cmdutil.CheckErr(o.Validate())
  91. var err error
  92. if o.List {
  93. err = o.RunAccessList()
  94. } else {
  95. var allowed bool
  96. allowed, err = o.RunAccessCheck()
  97. if err == nil {
  98. if !allowed {
  99. os.Exit(1)
  100. }
  101. }
  102. }
  103. cmdutil.CheckErr(err)
  104. },
  105. }
  106. cmd.Flags().BoolVarP(&o.AllNamespaces, "all-namespaces", "A", o.AllNamespaces, "If true, check the specified action in all namespaces.")
  107. cmd.Flags().BoolVarP(&o.Quiet, "quiet", "q", o.Quiet, "If true, suppress output and just return the exit code.")
  108. cmd.Flags().StringVar(&o.Subresource, "subresource", o.Subresource, "SubResource such as pod/log or deployment/scale")
  109. cmd.Flags().BoolVar(&o.List, "list", o.List, "If true, prints all allowed actions.")
  110. cmd.Flags().BoolVar(&o.NoHeaders, "no-headers", o.NoHeaders, "If true, prints allowed actions without headers")
  111. return cmd
  112. }
  113. // Complete completes all the required options
  114. func (o *CanIOptions) Complete(f cmdutil.Factory, args []string) error {
  115. if o.List {
  116. if len(args) != 0 {
  117. return errors.New("list option must be specified with no arguments")
  118. }
  119. } else {
  120. if o.Quiet {
  121. o.Out = ioutil.Discard
  122. }
  123. switch len(args) {
  124. case 2:
  125. o.Verb = args[0]
  126. if strings.HasPrefix(args[1], "/") {
  127. o.NonResourceURL = args[1]
  128. break
  129. }
  130. resourceTokens := strings.SplitN(args[1], "/", 2)
  131. restMapper, err := f.ToRESTMapper()
  132. if err != nil {
  133. return err
  134. }
  135. o.Resource = o.resourceFor(restMapper, resourceTokens[0])
  136. if len(resourceTokens) > 1 {
  137. o.ResourceName = resourceTokens[1]
  138. }
  139. default:
  140. return errors.New("you must specify two or three arguments: verb, resource, and optional resourceName")
  141. }
  142. }
  143. var err error
  144. client, err := f.KubernetesClientSet()
  145. if err != nil {
  146. return err
  147. }
  148. o.AuthClient = client.AuthorizationV1()
  149. o.DiscoveryClient = client.Discovery()
  150. o.Namespace = ""
  151. if !o.AllNamespaces {
  152. o.Namespace, _, err = f.ToRawKubeConfigLoader().Namespace()
  153. if err != nil {
  154. return err
  155. }
  156. }
  157. return nil
  158. }
  159. // Validate makes sure provided values for CanIOptions are valid
  160. func (o *CanIOptions) Validate() error {
  161. if o.List {
  162. if o.Quiet || o.AllNamespaces || o.Subresource != "" {
  163. return errors.New("list option can't be specified with neither quiet, all-namespaces nor subresource options")
  164. }
  165. return nil
  166. }
  167. if o.NonResourceURL != "" {
  168. if o.Subresource != "" {
  169. return fmt.Errorf("--subresource can not be used with NonResourceURL")
  170. }
  171. if o.Resource != (schema.GroupVersionResource{}) || o.ResourceName != "" {
  172. return fmt.Errorf("NonResourceURL and ResourceName can not specified together")
  173. }
  174. } else if !o.Resource.Empty() && !o.AllNamespaces && o.DiscoveryClient != nil {
  175. if namespaced, err := isNamespaced(o.Resource, o.DiscoveryClient); err == nil && !namespaced {
  176. if len(o.Resource.Group) == 0 {
  177. fmt.Fprintf(o.ErrOut, "Warning: resource '%s' is not namespace scoped\n", o.Resource.Resource)
  178. } else {
  179. fmt.Fprintf(o.ErrOut, "Warning: resource '%s' is not namespace scoped in group '%s'\n", o.Resource.Resource, o.Resource.Group)
  180. }
  181. }
  182. }
  183. if o.NoHeaders {
  184. return fmt.Errorf("--no-headers cannot be set without --list specified")
  185. }
  186. return nil
  187. }
  188. // RunAccessList lists all the access current user has
  189. func (o *CanIOptions) RunAccessList() error {
  190. sar := &authorizationv1.SelfSubjectRulesReview{
  191. Spec: authorizationv1.SelfSubjectRulesReviewSpec{
  192. Namespace: o.Namespace,
  193. },
  194. }
  195. response, err := o.AuthClient.SelfSubjectRulesReviews().Create(sar)
  196. if err != nil {
  197. return err
  198. }
  199. return o.printStatus(response.Status)
  200. }
  201. // RunAccessCheck checks if user has access to a certain resource or non resource URL
  202. func (o *CanIOptions) RunAccessCheck() (bool, error) {
  203. var sar *authorizationv1.SelfSubjectAccessReview
  204. if o.NonResourceURL == "" {
  205. sar = &authorizationv1.SelfSubjectAccessReview{
  206. Spec: authorizationv1.SelfSubjectAccessReviewSpec{
  207. ResourceAttributes: &authorizationv1.ResourceAttributes{
  208. Namespace: o.Namespace,
  209. Verb: o.Verb,
  210. Group: o.Resource.Group,
  211. Resource: o.Resource.Resource,
  212. Subresource: o.Subresource,
  213. Name: o.ResourceName,
  214. },
  215. },
  216. }
  217. } else {
  218. sar = &authorizationv1.SelfSubjectAccessReview{
  219. Spec: authorizationv1.SelfSubjectAccessReviewSpec{
  220. NonResourceAttributes: &authorizationv1.NonResourceAttributes{
  221. Verb: o.Verb,
  222. Path: o.NonResourceURL,
  223. },
  224. },
  225. }
  226. }
  227. response, err := o.AuthClient.SelfSubjectAccessReviews().Create(sar)
  228. if err != nil {
  229. return false, err
  230. }
  231. if response.Status.Allowed {
  232. fmt.Fprintln(o.Out, "yes")
  233. } else {
  234. fmt.Fprint(o.Out, "no")
  235. if len(response.Status.Reason) > 0 {
  236. fmt.Fprintf(o.Out, " - %v", response.Status.Reason)
  237. }
  238. if len(response.Status.EvaluationError) > 0 {
  239. fmt.Fprintf(o.Out, " - %v", response.Status.EvaluationError)
  240. }
  241. fmt.Fprintln(o.Out)
  242. }
  243. return response.Status.Allowed, nil
  244. }
  245. func (o *CanIOptions) resourceFor(mapper meta.RESTMapper, resourceArg string) schema.GroupVersionResource {
  246. if resourceArg == "*" {
  247. return schema.GroupVersionResource{Resource: resourceArg}
  248. }
  249. fullySpecifiedGVR, groupResource := schema.ParseResourceArg(strings.ToLower(resourceArg))
  250. gvr := schema.GroupVersionResource{}
  251. if fullySpecifiedGVR != nil {
  252. gvr, _ = mapper.ResourceFor(*fullySpecifiedGVR)
  253. }
  254. if gvr.Empty() {
  255. var err error
  256. gvr, err = mapper.ResourceFor(groupResource.WithVersion(""))
  257. if err != nil {
  258. if len(groupResource.Group) == 0 {
  259. fmt.Fprintf(o.ErrOut, "Warning: the server doesn't have a resource type '%s'\n", groupResource.Resource)
  260. } else {
  261. fmt.Fprintf(o.ErrOut, "Warning: the server doesn't have a resource type '%s' in group '%s'\n", groupResource.Resource, groupResource.Group)
  262. }
  263. return schema.GroupVersionResource{Resource: resourceArg}
  264. }
  265. }
  266. return gvr
  267. }
  268. func (o *CanIOptions) printStatus(status authorizationv1.SubjectRulesReviewStatus) error {
  269. if status.Incomplete {
  270. fmt.Fprintf(o.ErrOut, "warning: the list may be incomplete: %v\n", status.EvaluationError)
  271. }
  272. breakdownRules := []rbacv1.PolicyRule{}
  273. for _, rule := range convertToPolicyRule(status) {
  274. breakdownRules = append(breakdownRules, rbacutil.BreakdownRule(rule)...)
  275. }
  276. compactRules, err := rbacutil.CompactRules(breakdownRules)
  277. if err != nil {
  278. return err
  279. }
  280. sort.Stable(rbacutil.SortableRuleSlice(compactRules))
  281. w := printers.GetNewTabWriter(o.Out)
  282. defer w.Flush()
  283. allErrs := []error{}
  284. if !o.NoHeaders {
  285. if err := printAccessHeaders(w); err != nil {
  286. allErrs = append(allErrs, err)
  287. }
  288. }
  289. if err := printAccess(w, compactRules); err != nil {
  290. allErrs = append(allErrs, err)
  291. }
  292. return utilerrors.NewAggregate(allErrs)
  293. }
  294. func convertToPolicyRule(status authorizationv1.SubjectRulesReviewStatus) []rbacv1.PolicyRule {
  295. ret := []rbacv1.PolicyRule{}
  296. for _, resource := range status.ResourceRules {
  297. ret = append(ret, rbacv1.PolicyRule{
  298. Verbs: resource.Verbs,
  299. APIGroups: resource.APIGroups,
  300. Resources: resource.Resources,
  301. ResourceNames: resource.ResourceNames,
  302. })
  303. }
  304. for _, nonResource := range status.NonResourceRules {
  305. ret = append(ret, rbacv1.PolicyRule{
  306. Verbs: nonResource.Verbs,
  307. NonResourceURLs: nonResource.NonResourceURLs,
  308. })
  309. }
  310. return ret
  311. }
  312. func printAccessHeaders(out io.Writer) error {
  313. columnNames := []string{"Resources", "Non-Resource URLs", "Resource Names", "Verbs"}
  314. _, err := fmt.Fprintf(out, "%s\n", strings.Join(columnNames, "\t"))
  315. return err
  316. }
  317. func printAccess(out io.Writer, rules []rbacv1.PolicyRule) error {
  318. for _, r := range rules {
  319. if _, err := fmt.Fprintf(out, "%s\t%v\t%v\t%v\n", describeutil.CombineResourceGroup(r.Resources, r.APIGroups), r.NonResourceURLs, r.ResourceNames, r.Verbs); err != nil {
  320. return err
  321. }
  322. }
  323. return nil
  324. }
  325. func isNamespaced(gvr schema.GroupVersionResource, discoveryClient discovery.DiscoveryInterface) (bool, error) {
  326. if gvr.Resource == "*" {
  327. return true, nil
  328. }
  329. apiResourceList, err := discoveryClient.ServerResourcesForGroupVersion(schema.GroupVersion{
  330. Group: gvr.Group, Version: gvr.Version,
  331. }.String())
  332. if err != nil {
  333. return true, err
  334. }
  335. for _, resource := range apiResourceList.APIResources {
  336. if resource.Name == gvr.Resource {
  337. return resource.Namespaced, nil
  338. }
  339. }
  340. return false, fmt.Errorf("the server doesn't have a resource type '%s' in group '%s'", gvr.Resource, gvr.Group)
  341. }