23.kubernetes(k8s)笔记 认证、授权与准入控制(三) RBAC 访问控制

RBAC 访问控制 Users Accounts


前言:
前面已经对ServiceAccount、Users Account认证进行了介绍与创建,但最后的测试发现是Users Account并没有访问权限,本节介绍RBAC授权 对ServiceAccount、Users Account认证进行授权

RBAC是什么?

RBAC 是基于角色的访问控制(Role-Based Access Control )在 RBAC 中,权限与角色相关联,用户通过成为适当角色的成员而得到这些角色的权限。这就极大地简化了权限的管理。这样管理都是层级相互依赖的,权限赋予给角色,而把角色又赋予用户,这样的权限设计很清楚,管理起来很方便。

角色
  Role:角色,名称空间级别;授权特定命名空间的访问权限
  ClusterRole:集群角色,全局级别;授权所有命名空间的访问权限

角色绑定
  RoleBinding:将角色绑定到主体(即subject),意味着,用户仅得到了特定名称空间下的Role的权限,作用范围也限于该名称空间;
  ClusterRoleBinding:将集群角色绑定到主体,让用户扮演指定的集群角色;意味着,用户得到了是集群级别的权限,作用范围也是集群级别;
  
主体(subject)
  User:用户
  Group:用户组
  ServiceAccount:服务账号

绑定对应关系
主体(Subject) --> RoleBinding --> Role #主体获得名称空间下的Role的权限
主体(Subject) --> ClusterRoleBinding --> clusterRoles #主体获得集群级别clusterRoles的权限
主体(Subject) --> Rolebindig -->ClusterRole #权限降级 主体获得名称空间下的clusterRoles的权限

  • rules中的参数说明:
    1、apiGroups:支持的API组列表,例如:"apiVersion: batch/v1"等
    2、resources:支持的资源对象列表,例如pods、deplayments、jobs等
    3、resourceNames: 指定resource的名称
    3、verbs:对资源对象的操作方法列表。
  • RBAC使用rbac.authorization.k8s.io API Group 来实现授权决策,允许管理员通过 Kubernetes API 动态配置策略,要启用RBAC,需要在 apiserver 中添加参数--authorization-mode=RBAC,如果使用的kubeadm安装的集群,都默认开启了RBAC,可以通过查看 Master 节点上 apiserver 的静态Pod定义文件:
[root@k8s-master usercerts]# cat /etc/kubernetes/manifests/kube-apiserver.yaml 
apiVersion: v1
kind: Pod
metadata:
 ...
spec:
  containers:
  - command:
    - kube-apiserver
    - --advertise-address=192.168.4.170
    - --allow-privileged=true
    - --authorization-mode=Node,RBAC   #默认支持BRAC 基于角色的访问控制
    - --client-ca-file=/etc/kubernetes/pki/ca.crt
    - --enable-admission-plugins=NodeRestriction
    - --enable-bootstrap-token-auth=true
    - --etcd-cafile=/etc/kubernetes/pki/etcd/ca.crt
    - --etcd-certfile=/etc/kubernetes/pki/apiserver-etcd-client.crt
...
  • 查看 kube-system名称空间下的role角色详情
[root@k8s-master ~]# kubectl get role -n kube-system
NAME                                             CREATED AT
extension-apiserver-authentication-reader        2021-06-28T17:43:31Z
kube-proxy                                       2021-06-28T17:43:33Z
kubeadm:kubelet-config-1.19                      2021-06-28T17:43:31Z
kubeadm:nodes-kubeadm-config                     2021-06-28T17:43:31Z
system::leader-locking-kube-controller-manager   2021-06-28T17:43:31Z
system::leader-locking-kube-scheduler            2021-06-28T17:43:31Z
system:controller:bootstrap-signer               2021-06-28T17:43:31Z
system:controller:cloud-provider                 2021-06-28T17:43:31Z
system:controller:token-cleaner                  2021-06-28T17:43:31Z

[root@k8s-master ~]# kubectl get role kube-proxy -n kube-system -o yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  creationTimestamp: "2021-06-28T17:43:33Z"
  managedFields:
  - apiVersion: rbac.authorization.k8s.io/v1
    fieldsType: FieldsV1
    fieldsV1:
      f:rules: {}
    manager: kubeadm
    operation: Update
    time: "2021-06-28T17:43:33Z"
  name: kube-proxy
  namespace: kube-system
  resourceVersion: "195"
  selfLink: /apis/rbac.authorization.k8s.io/v1/namespaces/kube-system/roles/kube-proxy
  uid: a5404b1f-90f0-447f-b104-86fcbdd388e0
rules:   #角色规则详细信息
- apiGroups:
  - ""
  resourceNames:
  - kube-proxy
  resources:
  - configmaps
  verbs:   #能执行的操作
  - get
  • role角色绑定
  • RoleBinding 角色绑定
[root@k8s-master ~]# kubectl explain rolebinding
KIND:     RoleBinding
VERSION:  rbac.authorization.k8s.io/v1
...
   roleRef  <Object> -required-
     RoleRef can reference a Role in the current namespace or a ClusterRole in
     the global namespace. If the RoleRef cannot be resolved, the Authorizer
     must return an error.

   subjects <[]Object>
     Subjects holds references to the objects the role applies to.

示例1: 创建role角色绑定 作用域为名称空间
[root@k8s-master authfiles]# cat pods-reader-rbac.yaml 
kind : Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  namespace: default
  name: pods-reader
rules:
- apiGroups: [""]  #空表示默认群组
  resources: ["pods","services","pods/log"]  #对象资源
  verbs: ["get","list","watch"]  #权限

[root@k8s-master authfiles]# cat tom-pods-reader.yaml 
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: tom-pods-reader
  namespace: default
subjects:
- kind: User
  name: tom   #绑定的用户名
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: pods-reader  #绑定之前的角色
  apiGroup: rbac.authorization.k8s.io
  
[root@k8s-master authfiles]# kubectl apply -f pods-reader-rbac.yaml 
[root@k8s-master authfiles]# kubectl apply -f tom-pods-reader.yaml 

[root@k8s-master authfiles]# kubectl get role
NAME          CREATED AT
pods-reader   2021-08-24T07:33:54Z
[root@k8s-master authfiles]# kubectl get rolebinding
NAME              ROLE               AGE
tom-pods-reader   Role/pods-reader   15m
  • 使用tom用户验证权限 pod、svc
[root@k8s-master authfiles]# kubectl config get-contexts   --kubeconfig=/tmp/mykubeconfig  #查看当前用户
CURRENT   NAME             CLUSTER      AUTHINFO   NAMESPACE
*         tom@kubernetes   kubernetes   tom 

[root@k8s-master authfiles]# kubectl get pod --kubeconfig=/tmp/mykubeconfig
NAME                                 READY   STATUS    RESTARTS   AGE
centos-deployment-66d8cd5f8b-bnnw6   1/1     Running   0          7m8s
[root@k8s-master authfiles]# kubectl get svc --kubeconfig=/tmp/mykubeconfig
NAME          TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)    AGE
demoapp       ClusterIP   10.97.26.1     <none>        80/TCP     10d
demoapp-svc   ClusterIP   10.99.170.77   <none>        80/TCP     10d
demodb        ClusterIP   None           <none>        9907/TCP   5d22h
kubernetes    ClusterIP   10.96.0.1      <none>        443/TCP    10d
  • 验证deployment、nodes权限 没有授权访问失败
[root@k8s-master authfiles]# kubectl get deployment  --kubeconfig=/tmp/mykubeconfig
Error from server (Forbidden): deployments.apps is forbidden: User "tom" cannot list resource "deployments" in API group "apps" in the namespace "default"

[root@k8s-master authfiles]# kubectl get nodes  --kubeconfig=/tmp/mykubeconfig
Error from server (Forbidden): nodes is forbidden: User "tom" cannot list resource "nodes" in API group "" at the cluster scope
内建管理员admin
  • 名称空间管理员admin

  • clusterrole admin 名称空间级别资源 拥有所有名称空间下的资源 所有操作权限

  • 集群管理员 cluster-admin

  • clusterrole cluster-admin 集群级别资源 拥有集群所有空的资源 所有操作权限

  • 之前绑定的rolebinding只对默认名称空间有一定的权限

[root@k8s-master authfiles]# kubectl get pod -n longhorn-system  --kubeconfig=/tmp/mykubeconfig
Error from server (Forbidden): pods is forbidden: User "tom" cannot list resource "pods" in API group "" in the namespace "longhorn-system"
  • clusterrole admin 对所有名称空间下的资源权限
[root@k8s-master authfiles]# kubectl get clusterrole admin
NAME    CREATED AT
admin   2021-06-28T17:43:30Z
[root@k8s-master authfiles]# kubectl get clusterrole admin -o yaml
  • 删除绑定,重新绑定到clusterrole admin
[root@k8s-master authfiles]# kubectl get rolebinding
NAME              ROLE               AGE
tom-pods-reader   Role/pods-reader   35m

[root@k8s-master authfiles]# kubectl delete Role/pods-reader
role.rbac.authorization.k8s.io "pods-reader" deleted

[root@k8s-master authfiles]# kubectl delete rolebinding/tom-pods-reader
rolebinding.rbac.authorization.k8s.io "tom-pods-reader" deleted

[root@k8s-master authfiles]# kubectl get pod  --kubeconfig=/tmp/mykubeconfig
Error from server (Forbidden): pods is forbidden: User "tom" cannot list resource "pods" in API group "" in the namespace "default"
示例2: 绑定admin 并验证权限,作用域为名称空间
[root@k8s-master authfiles]# kubectl create --help  
...
Available Commands:
  clusterrole         Create a ClusterRole.
  clusterrolebinding  Create a ClusterRoleBinding for a particular ClusterRole
  configmap           Create a configmap from a local file, directory or literal value
  cronjob             Create a cronjob with the specified name.
  deployment          Create a deployment with the specified name.
  job                 Create a job with the specified name.
  namespace           Create a namespace with the specified name
  poddisruptionbudget Create a pod disruption budget with the specified name.
  priorityclass       Create a priorityclass with the specified name.
  quota               Create a quota with the specified name.
  role                Create a role with single rule.
  rolebinding         Create a RoleBinding for a particular Role or ClusterRole
  secret              Create a secret using specified subcommand
  service             Create a service using specified subcommand.
  serviceaccount      Create a service account with the specified name
  • 可以分别对--user、--group、--serviceaccount进行授权
[root@k8s-master authfiles]# kubectl create clusterrolebinding  --help
Create a ClusterRoleBinding for a particular ClusterRole.
....
Usage:  
  kubectl create clusterrolebinding NAME --clusterrole=NAME [--user=username] [--group=groupname]
[--serviceaccount=namespace:serviceaccountname] [--dry-run=server|client|none] [options]
  • 绑定并进行权限验证
[root@k8s-master authfiles]# kubectl create clusterrolebinding tom-admin --user=tom  --clusterrole=admin
clusterrolebinding.rbac.authorization.k8s.io/tom-admin created

[root@k8s-master authfiles]# kubectl get pod -n longhorn-system  --kubeconfig=/tmp/mykubeconfig
NAME                                        READY   STATUS    RESTARTS   AGE
csi-attacher-54c7586574-bh88g               1/1     Running   5          7d
csi-attacher-54c7586574-fvv4p               1/1     Running   7          19d
csi-attacher-54c7586574-zkzrg               1/1     Running   10         19d
csi-provisioner-5ff5bd6b88-9tqnh            1/1     Running   5          7d
csi-provisioner-5ff5bd6b88-bs687            1/1     Running   8          19d
csi-provisioner-5ff5bd6b88-qkzt4            1/1     Running   12         19d
csi-resizer-7699cdfc4-4w49w                 1/1     Running   8          19d
......

[root@k8s-master authfiles]# kubectl get pod -n kube-system  --kubeconfig=/tmp/mykubeconfig
NAME                                 READY   STATUS    RESTARTS   AGE
coredns-f9fd979d6-l9zck              1/1     Running   16         56d
coredns-f9fd979d6-s8fp5              1/1     Running   15         56d
etcd-k8s-master                      1/1     Running   12         56d
kube-apiserver-k8s-master            1/1     Running   16         56d
kube-controller-manager-k8s-master   1/1     Running   39         56d
kube-flannel-ds-6sppx                1/1     Running   1          6d22h
kube-flannel-ds-j5g9s                1/1     Running   3          6d22h
kube-flannel-ds-nfz77                1/1     Running   1          6d22h
kube-flannel-ds-sqhq2                1/1     Running   1          6d22h

[root@k8s-master authfiles]# kubectl get deployment   --kubeconfig=/tmp/mykubeconfig
NAME                READY   UP-TO-DATE   AVAILABLE   AGE
centos-deployment   1/1     1            1           6d22h

  • node是集群级别资源 无权限
[root@k8s-master authfiles]# kubectl get node  --kubeconfig=/tmp/mykubeconfig
Error from server (Forbidden): nodes is forbidden: User "tom" cannot list resource "nodes" in API group "" at the cluster scope

[root@k8s-master authfiles]# kubectl get pv  --kubeconfig=/tmp/mykubeconfig
Error from server (Forbidden): persistentvolumes is forbidden: User "tom" cannot list resource "persistentvolumes" in API group "" at the cluster scope
示例3: 绑定cluster-admin 并验证权限 作用域为集群级别资源
[root@k8s-master authfiles]# kubectl delete clusterrolebinding tom-admin
clusterrolebinding.rbac.authorization.k8s.io "tom-admin" deleted

[root@k8s-master authfiles]# kubectl create clusterrolebinding tom-cluste-admin --user=tom  --clusterrole=cluster-admin
clusterrolebinding.rbac.authorization.k8s.io/tom-cluste-admin created
[root@k8s-master authfiles]# kubectl get pv  --kubeconfig=/tmp/mykubeconfig
NAME                                       CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS      CLAIM                   STORAGECLASS   REASON   AGE
pv-nfs-demo002                             10Gi       RWX            Retain           Available                                                   21d
pv-nfs-demo003                             1Gi        RWO            Retain           Available                                                   21d
pvc-33e9acff-afd9-417e-bbfb-293cb6305fb1   1Gi        RWX            Retain           Bound       default/data-demodb-1   longhorn                5d23h
pvc-c5a0bfaa-6948-4814-886f-8bf079b00dd1   1Gi        RWX            Retain           Bound       default/data-demodb-0   longhorn                5d23h
[root@k8s-master authfiles]# kubectl get node  --kubeconfig=/tmp/mykubeconfig
NAME         STATUS   ROLES    AGE   VERSION
k8s-master   Ready    master   56d   v1.19.9
k8s-node1    Ready    <none>   56d   v1.19.9
k8s-node2    Ready    <none>   56d   v1.19.9
k8s-node3    Ready    <none>   20d   v1.19.9
  • 需要注意的是 cluster-admin 是通过system:masters组方式进行授权,如果我们在创建用户证书时,/CN=XX/O=system:masters;那么这个用户就拥有超级管理员的权限
[root@k8s-master authfiles]# kubectl describe clusterrolebinding cluster-admin
Name:         cluster-admin
Labels:       kubernetes.io/bootstrapping=rbac-defaults
Annotations:  rbac.authorization.kubernetes.io/autoupdate: true
Role:
  Kind:  ClusterRole
  Name:  cluster-admin
Subjects:
  Kind   Name            Namespace
  ----   ----            ---------
  Group  system:masters   #通过组授权所有system:masters都拥有超级管理员权限
示例4: rolebinding 绑定admin 并验证权限 权限降级
  • 前面有提到
    User --> Rolebindig -->ClusterRole:权限降级,
    ClusterRole,用户得到的权限仅是ClusterRole的权限在Rolebinding所属的名称空间上的一个子集;

  • 删除之前绑定

[root@k8s-master authfiles]# kubectl delete  clusterrolebinding tom-cluste-admin
clusterrolebinding.rbac.authorization.k8s.io "tom-cluste-admin" deleted
  • 创建角色绑定集群角色 权限降级 只对指定名称空间有权限
[root@k8s-master authfiles]# kubectl create  rolebinding tom-admin --user=tom  -n longhorn-system --clusterrole=admin
rolebinding.rbac.authorization.k8s.io/tom-admin created
  • 测试权限 作用域尽为longhorn-system名称空间
[root@k8s-master authfiles]# kubectl get pod -n kube-system  --kubeconfig=/tmp/mykubeconfig
Error from server (Forbidden): pods is forbidden: User "tom" cannot list resource "pods" in API group "" in the namespace "kube-system"

[root@k8s-master authfiles]# kubectl get pod --kubeconfig=/tmp/mykubeconfig
Error from server (Forbidden): pods is forbidden: User "tom" cannot list resource "pods" in API group "" in the namespace "default"

[root@k8s-master authfiles]# kubectl get deployment  --kubeconfig=/tmp/mykubeconfig
Error from server (Forbidden): deployments.apps is forbidden: User "tom" cannot list resource "deployments" in API group "apps" in the namespace "default"

[root@k8s-master authfiles]# kubectl get pod -n longhorn-system  --kubeconfig=/tmp/mykubeconfig
NAME                                        READY   STATUS    RESTARTS   AGE
csi-attacher-54c7586574-bh88g               1/1     Running   5          7d
csi-attacher-54c7586574-fvv4p               1/1     Running   7          19d
csi-attacher-54c7586574-zkzrg               1/1     Running   10         19d
csi-provisioner-5ff5bd6b88-9tqnh            1/1     Running   5          7d
csi-provisioner-5ff5bd6b88-bs687            1/1     Running   8          19d
csi-provisioner-5ff5bd6b88-qkzt4            1/1     Running   12         19d
csi-resizer-7699cdfc4-4w49w                 1/1     Running   8          19d
csi-resizer-7699cdfc4-f5jph                 1/1     Running   6          7d
csi-resizer-7699cdfc4-l2j49                 1/1     Running   9          19d
...
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,222评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,455评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,720评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,568评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,696评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,879评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,028评论 3 409
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,773评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,220评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,550评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,697评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,360评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,002评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,782评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,010评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,433评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,587评论 2 350

推荐阅读更多精彩内容