[Cloud native | Learning Kubernetes from scratch] Twenty-eighth, the end of the article - rbac authorization in-depth explanation

This article has been included in the column " Learn k8s from scratch "
Previous article: Configuration Management Center Secret and rbac Authorization Click jump

insert image description here


Next part of previous article

1、ServiceAccount

Service account is designed to facilitate the process in the Pod to call the Kubernetes API or other external services. It is different from User account. User account is designed for people, while service account is designed for the process in Pod to call Kubernetes API; User account is across namespaces, while service account is only limited to the namespace where it is located; each namespace will automatically create a default service account; after opening the ServiceAccount Admission Controller

1) Each Pod will automatically set spec.serviceAccount to default after it is created (unless another ServiceAccout is specified)

2) Verify that the service account referenced by the Pod already exists, otherwise refuse to create it;

When creating a pod, if no serviceaccount is specified, the system will automatically assign a default service account under the same namespace as the pod. This is the account for communication between the pod and the apiserver, as follows:

[root@k8smaster secret]# kubectl get pods
NAME                               READY   STATUS              RESTARTS   AGE
mysql-pod-volume                   1/1     Running             0          50m
nginx-f89759699-5qdtn              1/1     Running             1          19d
pod-secret                         1/1     Running             0          17m
pod-secret-volume                  1/1     Running             0          11m
[root@k8smaster secret]# kubectl get pods mysql-pod-volume -o yaml | grep "serviceAccountName"
  serviceAccountName: default
[root@k8smaster secret]# kubectl describe pods mysql-pod-volume
Volumes:
  mysql-config:
    Type:      ConfigMap (a volume populated by a ConfigMap)
    Name:      mysql
    Optional:  false
  default-token-788ff:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-788ff
    Optional:    false

 
从上面可以看到每个 Pod 无论定义与否都会有个存储卷,这个存储卷为 default-token-***。pod 和 apiserver 的认证信息通过 secret 进行定义,由于认证信息属于敏感信息,所以需要保存在 secret 资源当中,并以存储卷的方式挂载到 Pod 当中。从而让 Pod 内运行的应用通过对应的 secret 中的信息来连接 apiserver,并完成认证。每个 namespace 中都有一个默认的叫做 default 的 serviceaccount 资源。查看名称空间内的 secret,也可以看到对应的 default-token。让当前名称空间中所有的 pod 在连接 apiserver 时可以使用的预制认证信息,从而保证 pod 之间的通信。
 
[root@k8smaster secret]# kubectl get sa
NAME              SECRETS   AGE
default           1         19d

[root@k8smaster secret]# kubectl get secret
NAME                          TYPE                                  DATA   AGE
default-token-788ff           kubernetes.io/service-account-token   3      19d

默认的 service account 仅仅只能获取当前 Pod 自身的相关属性,无法观察到其他名称空间 Pod 的相关属性信息。如果想要扩展 Pod,假设有一个 Pod 需要用于管理其他 Pod 或者是其他资源对象,是无法通过自身的名称空间的 serviceaccount 进行获取其他 Pod 的相关属性信息的,此时就需要进行手动创建一个 serviceaccount,并在创建 Pod 时进行定义。那么 serviceaccount 该如何进行定义呢?实际上,service accout 也属于一个 k8s 资源,serviceAccount 也属于标准的 k8s 资源,可以创建一个 serviceAccount,创建之后由我们创建的 pod 使用 serviceAccountName 去加载自己定义的 serviceAccount 就可以了,如下:

[root@k8smaster secret]# kubectl create sa paopao
serviceaccount/paopao created
[root@k8smaster secret]# kubectl get sa
NAME              SECRETS   AGE
default           1         19d
nfs-provisioner   1         47h
paopao            1         3s
[root@k8smaster secret]# kubectl describe sa paopao
Name:                paopao
Namespace:           default
Labels:              <none>
Annotations:         <none>
Image pull secrets:  <none>
Mountable secrets:   paopao-token-g72jh
Tokens:              paopao-token-g72jh			#自动生成token
Events:              <none>
[root@k8smaster secret]# kubectl get secret
NAME                          TYPE                                  DATA   AGE
default-token-788ff           kubernetes.io/service-account-token   3      19d
mysecret                      Opaque                                2      27m
mysql-password                Opaque                                1      40m
nfs-provisioner-token-tv5dl   kubernetes.io/service-account-token   3      2d
paopao-token-g72jh            kubernetes.io/service-account-token   3      31s		#自动生成secret
[root@k8smaster secret]# kubectl describe secret paopao-token-g72jh 
Name:         paopao-token-g72jh
Namespace:    default
Labels:       <none>
Annotations:  kubernetes.io/service-account.name: paopao
              kubernetes.io/service-account.uid: 74643ebf-6198-4b3a-9aee-ea0da0e6b1a8

Type:  kubernetes.io/service-account-token

Data
====
ca.crt:     1025 bytes
namespace:  7 bytes
token:      eyJhbGciOiJSUzI1NiIsImtpZCI6ImpCVzZXa0U2WDczX0NMeU1yUDM5YkluTWVPdlNFbUp0UnF3aVNnVzhXTkUifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJkZWZhdWx0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6InBhb3Bhby10b2tlbi1nNzJqaCIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJwYW9wYW8iLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC51aWQiOiI3NDY0M2ViZi02MTk4LTRiM2EtOWFlZS1lYTBkYTBlNmIxYTgiLCJzdWIiOiJzeXN0ZW06c2VydmljZWFjY291bnQ6ZGVmYXVsdDpwYW9wYW8ifQ.IzS3gXVOMXlKWSyVk-4Xh04351XkoG5axWba1fOwhrFLMNRT2RdMm3LRvvki_WIuL8prvGNerMt4cG3YzRIgLMTZ1Rk3BtLzo3HY9D4qr4FxZxXdFsqd87kHG5_ExpqzAHn__anL5758XMvsuQCwf-k6wRktbGOIDb6jXZuCVViRyomWWPJaLIBXa5BBlXHKft9mXuM6--293w21-RPTW29tMaIVf18bWXU3OpaPFiULtpUB3faqqmS3H7dKrbwn1uhSwmp4mxU1ossXCcPAdxL-Shh9L3yZ6fTuZTDxgmKb9yF6twVwcmuLr5HFZ3a5Tr_TVI91Z6IBXYlnu0bYuw	#可以看到有这个

上面可以看到生成了 paopao-token-g72jh 的 token 详细信息,这个 token 就是 sa 连接 apiserver 的认证信息,这个 token 也是登陆 k8s dashboard 的 token,这些是一个认证信息,能够登陆k8s,能认证到 k8s,但是不能做别的事情,不代表权限,想要做其他事情,需要授权
#比如在pod部署一个prometheus,如果要获取k8s监控指标要和apiserver交互,不然无法获取,这个时候需要生成sa,做一个rbac授权,比如可以对k8s所有资源下的所有名称空间都访问,才能获取到k8s资源

2. kubeconfig file

In the K8S cluster, each user's access to resources requires communication authentication through the apiserver. In this mechanism, the access to resources can be through tokens, or through configuration files. Using the authentication information, you can view the configuration through kubectl config, as follows:

[root@k8smaster secret]# kubectl config view
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: DATA+OMITTED
    server: https://192.168.11.139:6443	#apiserver 的地址
  name: kubernetes						#集群的名字
contexts:
- context:
    cluster: kubernetes
    user: kubernetes-admin
  name: kubernetes-admin@kubernetes		#上下文的名字
current-context: kubernetes-admin@kubernetes	#当前上下文的名字
kind: Config
preferences: {
    
    }
users:
- name: kubernetes-admin
  user:
    client-certificate-data: REDACTED
    client-key-data: REDACTED
在上面的配置文件当中,定义了集群、上下文以及用户。其中 Config 也是 K8S 的标准资源之一,在该配置文件当中定义了一个集群列表,指定的集群可以有多个;用户列表也可以有多个,指明集群。而在上下文列表当中,是进行定义可以使用哪个用户对哪个集群进行访问,以及当前使用的上下文是什么。

Authorize

If the user passes the authentication, he has no permissions, and some follow-up authorization operations are required, such as adding and deleting resources, etc. After kubernetes 1.6, there is an RBAC (Role-based Access Control Mechanism) authorization check mechanism. The authorization of Kubernetes is formed based on plug-ins. The commonly used authorization plug-ins are as follows:

1) Node (node ​​authentication)

2) ABAC (Attribute Based Access Control)

3) RBAC (Role Based Access Control)

4) Webhook (access control based on http callback mechanism)

What is RBAC (Role Based Access Control)?

Let a user (Users) play a role (Role), the role has permissions, so that users have such permissions, then in the authorization mechanism, only need to grant permissions to a role, then the user will get the permissions of the corresponding role, This enables access control for roles. As shown in the figure:

insert image description here

In the authorization mechanism of k8s, RBAC is used for authorization. Its working logic is to define the operation authority of the object into a role, and then bind the user to the role, so that the user can obtain the permission of the corresponding role. If you bind the role through rolebinding, you can only have permission to the resources in the namespace where rolebingding is located. In the above figure, the user user1 is bound to role1, and only has permission to the resources of the role1 namespace, but not to other namespace resources. belonging to the namespace level;

In addition, k8s also has a cluster-level authorization mechanism for this purpose, which is to define a cluster role (ClusterRole), which has operational permissions to all resources in the cluster, so that User2 can pass the ClusterRoleBinding to the ClusterRole, so that User2 has the cluster's rights. Operation permission.

The relationship between Role, RoleBinding, ClusterRole and ClusterRoleBinding is as follows:

insert image description here

As you can see from the above figure, roles can be bound by rolebinding, clusterrole can be bound by rolebinding, and clusterrole can be bound by clusterrolebinding.

Above we said two role bindings:

(1) The user binds the role through rolebinding

(2) The user binds the clusterrole through clusterrolebinding

There is another: rolebinding binding clusterrole

The advantages of rolebinding binding clusterrole:
If there are 6 namespaces, and users of each namespace need to have administrator rights to their own namespaces, then 6 roles and rolebindings need to be defined, and then bound in sequence, if the namespace is more Many, we need to define more roles, which is very troublesome, so we introduce clusterrole, define a clusterrole, grant all permissions to the clusterrole, and then the user binds to the clusterrole through rolebinding, and will have the administrator rights of his own namespace span

Note: RoleBinding only has corresponding permissions for the current namespace.

admission control

Generally speaking, admission control is only used to define other subsequent security check operations after our authorization check is completed. It further supplements the authorization mechanism and is implemented by a combination of multiple plug-ins. Generally speaking, it is used to create, delete, modify or act as a proxy. supplement from time to time.

Kubernetes' Admission Control is actually a list of Admission Controller plugins. Requests sent to APIServer need to be checked by each admission controller plugin in this list. If a certain controller plugin fails admission , the access fails.

The controller plugin is as follows:

AlwaysAdmit: allow all requests through

AlwaysPullImages: Always download the image before starting the container, which is equivalent to checking whether it is authorized to use the container image every time the container is started

AlwaysDeny: Forbid all requests to pass, for testing

DenyEscalatingExec: Deny end-user access to exec and attach commands to pods with escalated privileges. This plugin is recommended if you centralize containers that contain elevated privileges and want to limit the ability of end users to execute commands in those containers

ImagePolicyWebhook ServiceAccount: This plugin implements automation of serviceAccounts, etc. If you use ServiceAccount objects, it is strongly recommended to use this plugin

SecurityContextDeny: Deactivates all SecurityContext options defined in the Pod definition.

SecurityContext contains options that define OS-level security options such as fsGroup, selinux, etc. in the container

ResourceQuota: Used for quota management on the namespace, it will observe incoming requests to ensure that the quota on the namespace is not exceeded. It is recommended to put this plugin last in the admission controller list. The ResourceQuota admission controller can not only limit the number of resources created in a namespace, but also limit the total amount of resources requested by Pods in a namespace. The ResourceQuota admission controller and the ResourceQuota resource object work together to implement resource quota management.

LimitRanger: For quota management on Pods and Containers, it observes incoming requests to ensure that quotas on Pods and Containers are not exceeded. The admission controller LimitRange and the resource object LimitRange implement resource limit management together

NamespaceLifecycle: When a request is to create a resource object under a namespace that does not exist, the request will be rejected. When deleting a namespace, all resource objects under the namespace will be deleted

DefaultStorageClass
DefaultTolerationSeconds
PodSecurityPolicy
当 Kubernetes 版本>=1.6.0,官方建议使用这些插件:
–admission-control=NamespaceLifecycle,LimitRanger,ServiceAccount,PersistentVolumeLabel,DefaultStorageClass,ResourceQuota,DefaultTolerationSeconds
当 Kubernetes 版本>=1.4.0,官方建议使用这些插件:
–admission-control=NamespaceLifecycle,LimitRanger,ServiceAccount,DefaultStorageClass,ResourceQuota
以上是标准的准入插件,如果是自己定制的话,k8s1.7版 出了两个 alpha features, Initializers 和 External Admission Webhooks

RBAC Authentication and Authorization Policy

Introduction to RBAC

In Kubernetes, all resource objects are manipulated through API, and they are stored in etcd. The operation of etcd needs to be realized by accessing kube-apiserver. The above Service Account is actually the authentication process of APIServer, and the authorization mechanism is realized through RBAC: role-based access control.

RBAC has four resource objects, namely Role, ClusterRole, RoleBinding, and ClusterRoleBinding

Role: role

一组权限的集合,在一个命名空间中,可以用其来定义一个角色,只能对命名空间内的资源进行授权。如果是集群级别的资源,则需要使用 ClusterRole。
例如:定义一个角色用来读取 Pod 的权限
apiVersion: rbac.authorization.k8s.io/v1		#认证相关的api
kind: Role
metadata:
  namespace: rbac 								#只能对rbac这个名称空间才有权限
  name: pod-read								
rules:											#策略
  - apiGroups: [""]								#k8s所有的apiversion都支持 kubectl api-versions查看
    resources: ["pods"] 						#资源名字
    resourceNames: []							#如果需要具体的pod就写具体的 不写就是所有的
    verbs: ["get","watch","list"]				#具体的步骤吗,获取,查看,以列表列出来
rules 中的参数说明:
1、apiGroups:支持的 API 组列表,例如:"apiVersion: batch/v1"2、resources:支持的资源对象列表,例如 pods、deplayments、jobs 等
3、resourceNames: 指定 resource 的名称
4、verbs:对资源对象的操作方法列表。

ClusterRole: Cluster role

具有和角色一致的命名空间资源的管理能力,还可用于以下特殊元素的授权
1、集群范围的资源,例如 Node
2、非资源型的路径,例如:/healthz
3、包含全部命名空间的资源,例如 Pods
例如:定义一个集群角色可让用户访问任意 secrets
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: secrets-clusterrole
rules:
  - apiGroups: [""]
    resources: ["secrets"]			#对所有名称空间下的secrets都有查看的权限
    verbs: ["get","watch","list"]

RoleBinding: role binding, ClusterRolebinding: cluster role binding

角色绑定和集群角色绑定用于把一个角色绑定在一个目标上,可以是 User,Group,Service Account,使用 RoleBinding 为某个命名空间授权,使用 ClusterRoleBinding 为集群范围内授权。
例如:将在 rbac 命名空间中把 pod-read 角色授予用户 es
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: pod-read-bind
  namespace: rbac
subjects:									#主体
- kind: User							
  name: es									#要对es这个用户
  apiGroup: rbac.authorization.k8s.io
roleRef:									#通过 pod-read-bind 绑定到roleref上
- kind: Role
  name: pod-read							#角色名字
  apiGroup: rbac.authorizatioin.k8s.io
#用户es在rbac这个命名空间下具有role设置的权限,比如资源查看

RoleBinding 也可以引用 ClusterRole,对属于同一命名空间内的 ClusterRole 定义的资源主体进行授权, 例如:es 能获取到集群中所有的资源信息
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: es-allresource
  namespace: rbac
subjects:
- kind: User
  name: es								#通过RoleBinding绑定到cluster-admin这个ClusterRole上 管理员的角色
  apiGroup: rbac.authorization.k8s.io
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin

集群角色绑定的角色只能是集群角色,用于进行集群级别或对所有命名空间都生效的授权
例如:允许 manager 组的用户读取所有 namaspace 的 secrets
apiVersion: rabc.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: read-secret-global
subjects:
- kind: Group
  name: manager							#通过ClusterRoleBinding绑定到secret-read这个ClusterRole
  apiGroup: rabc.authorization.k8s.io
ruleRef:
- kind: ClusterRole
  name: secret-read						#读的权限
  apiGroup: rabc.authorization.k8s.io

How resources are referenced

多数资源可以用其名称的字符串表示,也就是 Endpoint 中的 URL 相对路径
例如 pod 中的日志是GET /api/v1/namaspaces/{
    
    namespace}/pods/{
    
    podname}/log

如果需要在一个 RBAC 对象中体现上下级资源,就需要使用“/”分割资源和下级资源。
例如:若想授权让某个主体同时能够读取 Pod 和 Pod log,则可以配置 resources 为一个数组
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: logs-reader
  namespace: default
rules:
- apiGroups: [""]
  resources: ["pods","pods/log"]				#对pods和podslog下的资源可以读取
  verbs: ["get","list"]

资源还可以通过名称(ResourceName)进行引用,在指定 ResourceName 后,使用 get、delete、update、patch 请求,就会被限制在这个资源实例范围内
例如,下面的声明让一个主体只能对名为 my-configmap 的 Configmap 进行 get 和 update 操作:
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namaspace: default
  name: configmap-update
rules:
- apiGroups: [""]
  resources: ["configmap"]
  resourceNames: ["my-configmap"]				#只能对这个名字my-configmap进行get和更新操作
  verbs: ["get","update"]

Examples of common roles

(1) Allows reading the Pod resources of the core API group

rules:
- apiGroups: [""]					#读取所有apiversion的pods的资源可以查看信息等
  resources: ["pods"]
  verbs: ["get","list","watch"]

(2) Allows reading and writing the deployment resource rules in the extensions and apps API groups:

- apiGroups: ["extensions","apps"]									#组名,apiversion下也能看到组
  resources: ["deployments"]										#对上面两个组下的deplo资源有下面的权限
  verbs: ["get","list","watch","create","update","patch","delete"]  #查看 更新 删除等

(3) Allow to read Pod and read and write job information

rules:
- apiGroups: [""]														#所有核心api
  resources: ["pods"]													#读取pods资源
  verbs: ["get","list","watch"]、
- apiVersion: ["batch","extensions"]									#能对这两个组的jobs资源删除更新等
  resources: ["jobs"]	
  verbs: ["get","list","watch","create","update","patch","delete"]

(4) Allows reading a ConfigMap named my-config (must be bound to a RoleBinding to limit to a ConfigMap under a Namespace):

rules:
- apiGroups: [""]					#所有api
  resources: ["configmap"]			#获取configmap资源
  resourceNames: ["my-configmap"]	#为资源取得名字,configmap可能很多,只能查看my-configmap这个configmap
  verbs: ["get"]

(5) Read the Node resource of the core group (Node is a cluster-level resource, so it must exist in ClusterRole and use ClusterRoleBinding for binding)

rules:		
- apiGroups: [""]	
  resources: ["nodes"]				
  verbs: ["get","list","watch"]

(6) Allow GET and POST operations to the non-resource endpoint "/healthz" and all its sub-paths (ClusterRole and ClusterRoleBinding must be used):

rules:
- nonResourceURLs: ["/healthz","/healthz/*"]	#定义两个具体路径
  verbs: ["get","post"]

Common role binding examples

(1)用户名 alice
subjects:
- kind: User
  name: alice
  apiGroup: rbac.authorization.k8s.io
 
(2)组名 alice
subjects:
- kind: Group
  name: alice
  apiGroup: rbac.authorization.k8s.io
  
(3)kube-system 命名空间中默认 Service Account
subjects:
- kind: ServiceAccount
  name: default
  namespace: kube-system

(4)qa 命名空间中的所有 Service Account:
subjects:
- kind: Group
  name: system:serviceaccounts:qa			#qa名称空间下所有的sa资源
  apiGroup: rbac.authorization.k8s.io

(5)所有 Service Account
subjects:
- kind: Group
  name: system:serviceaccounts				#所有的sa
  apiGroup: rbac.authorization.k8s.io
 
(6)所有认证用户
subjects:
- kind: Group
  name: system:authenticated				#同
  apiGroup: rbac.authorization.k8s.io
 
(7)所有未认证用户
subjects:
- kind: Group
  name: system:unauthenticated				#同
  apiGroup: rbac.authorization.k8s.io		
 
(8)全部用户
subjects:
- kind: Group
  name: system:authenticated				#包括认证与未认证用户
  apiGroup: rbac.authorization.k8s.io
- kind: Group
  name: system:unauthenticated
  apiGroup: rbac.authorization.k8s.io

Authorization management for Service Account

Service Account is also an account, which provides the necessary identity proof for the process running in the Pod. The referenced Service Account needs to be specified in the Pod definition, so that the Pod can be empowered. For example, all Pod resources in the rbac namespace can be obtained in a pod, and the Service Account of pod-reader-sc is bound to a Role named pod-read

apiVersion: v1
kind: Pod
metadata:
  name: nginx
  namespace: rbac
spec:
  serviceAccountName: pod-reader-sc		#指定的sc 绑定到rbac命名空间下 可以读取pods
  containers:
  - name: nginx
    image: nginx
    imagePullPolicy: IfNotPresent
    ports:
    - containerPort: 80
默认的 RBAC 策略为控制平台组件、节点和控制器授予有限范围的权限,但是除 kube-system 外的 Service Account 是没有任何权限的。

1 为一个应用专属的 Service Account 赋权
此应用需要在 Pod 的 spec 中指定一个 serviceAccountName。
用于API,Application,Manifest,kubectl create serviceaccount 等创建 Service Account 的命令。

例如为 my-namespace 中的 my-sa Service Account 授予只读权限
kubectl create rolebinding my-sa-view --clusterrole=view --serviceaccount=my-namespace:my-sa --namespace=my-namespace
kubectl 创建 rolebinding rbd 的名字 --service是my-namespace这个命名空间下通过rolebinding绑定到clusterrole上,view是安装k8s的时候默认的角色 只读权限。

2 为一个命名空间中名为 default 的 Service Account 授权
如果一个应用没有指定 serviceAccountName,则会使用名为 default 的 Service Account。
注意,赋予 Service Account “default”的权限会让所有没有指定 serviceAccountName 的 Pod都具有这些权限

例如,在 my-namespace 命名空间中为 Service Account“default”授予只读权限
kubectl create rolebinding default-view --clusterrole=view --serviceaccount=my-namespace:default --namespace=my-namespace

另外,许多系统级 Add-Ons(附加组件)都需要在 kube-system 命名空间中运行,要让这些 Add-Ons 能够使用超级用户权限,则可以把 cluster-admin 权限赋予 kube-system 命名空间中名为 default 的 Service Account,这一操作意味着 kube-system 命名空间包含了通向 API 超级用户的捷径。
kubectl create clusterrolebinding add-ons-add-admin --clusterrole=cluster-admin --serviceaccount=kube-system:default

(3)为命名空间中所有 Service Account 都授予一个角色
如果希望在一个命名空间中,任何 Service Account 应用都具有一个角色,则可以为这一命名空间的 Service Account 群组进行授权
kubectl create rolebinding serviceaccounts-view --clusterrole=view --group=system:serviceaccounts:my-namespace --namespace=my-namespace

(4)为集群范围内所有 Service Account 都授予一个低权限角色
如果不想为每个命名空间管理授权,则可以把一个集群级别的角色赋给所有 Service Account。 
kubectl create clusterrolebinding serviceaccounts-view --clusterrole=view --group=system:serviceaccounts
让所有sa都具有查看的权限,创建pod时用任何一个sa就只有查看的权限

(5)为所有 Service Account 授予超级用户权限
kubectl create clusterrolebinding serviceaccounts-view --clusterrole=cluster-admin --group=system:serviceaccounts

Use the kubectl command line tool to create resource objects

(1)在命名空间 rbac 中为用户 es 授权 admin ClusterRole:
kubectl create rolebinding bob-admin-binding --clusterrole=admin --user=es --namespace=rbac
#对于mes这个用户,他对rbac这个命名空间具有admin权限,通过rolebinding绑定到admin这个ClusterRole上
 
(2)在命名空间 rbac 中为名为 myapp 的 Service Account 授予 view ClusterRole:
kubctl create rolebinding myapp-role-binding --clusterrole=view --serviceaccount=rbac:myapp --namespace=rbac
#对于myapp这个sa用户,他对rbac这个命名空间就只有查看的权限,通过rolebinding绑定到admin这个ClusterRole上
 
(3)在全集群范围内为用户 root 授予 cluster-admin ClusterRole:
kubectl create clusterrolebinding cluster-binding --clusterrole=cluster-admin --user=root
#对于root这个用户,对所有的名称空间都具有管理员权限,通过clusterrolebinding绑定到admin这个ClusterRole上

(4)在全集群范围内为名为 myapp 的 Service Account 授予 view ClusterRole:
kubectl create clusterrolebinding service-account-binding --clusterrole=view --serviceaccount=myapp
#对于myapp这个sa用户,对所有的名称空间都具有查看的权限,通过clusterrolebinding绑定到view这个ClusterRole上

yaml 文件进行 rbac 授权:https://kubernetes.io/zh/docs/reference/access-authn-authz/rbac

Restrict different users to operate k8s cluster

ssl 认证 生成一个证书 
1 生成一个私钥 
[root@k8smaster secret]# cd /etc/kubernetes/pki/ 
[root@k8smaster pki]# (umask 077; openssl genrsa -out paopao.key 2048) 
Generating RSA private key, 2048 bit long modulus
.......................................................+++
.....................................................+++
e is 65537 (0x10001)

2 生成一个证书请求,并且生成证书
[root@k8smaster pki]# openssl req -new -key paopao.key -out paopao.csr -subj "/CN=paopao" 
[root@k8smaster pki]# openssl x509 -req -in paopao.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out paopao.crt -days 3650 					用ca这个机构颁发证书,paopao.crt这个证书是被ca.crt这个apiservion信任的
Signature ok
subject=/CN=paopao
Getting CA Private Key

在 kubeconfig 下新增加一个 lucky 这个用户 
1 把 paopao 这个用户添加到 kubernetes 集群中,可以用来认证 apiserver 的连接 
[root@k8smaster pki]# kubectl config set-credentials paopao --client-certificate=./paopao.crt --client-key=./paopao.key --embed-certs=true 
User "paopao" set.
#添加了一个用户paopao,用的客户端证书是paopao.crt,key是paopao.key。

[root@k8smaster pki]# vim /root/.kube/config	#不修改 进去查看刚才创建的用户
- name: paopao
  user:
 
2 在 kubeconfig 下新增加一个 lucky 这个账号 
[root@k8smaster pki]# kubectl config set-context paopao@kubernetes --cluster=kubernetes --user=paopao
Context "paopao@kubernetes" created.
这个上下文包括了k8s集群,用户是paopao

[root@k8smaster pki]# vim /root/.kube/config	#不修改 进去查看刚才创建的
- context:
    cluster: kubernetes
    user: paopao
  name: paopao@kubernetes
current-context: kubernetes-admin@kubernetes

3 切换账号到 paopao,默认没有任何权限 
[root@k8smaster pki]# kubectl config use-context paopao@kubernetes 
Switched to context "paopao@kubernetes".
[root@k8smaster pki]# kubectl get pods
Error from server (Forbidden): pods is forbidden: User "paopao" cannot list resource "pods" in API group "" in the namespace "default"
#没有权限!
[root@k8smaster pki]# kubectl config use-context kubernetes-admin@kubernetes 这个是集群用户,有所有权限 
把 user 这个用户通过 rolebinding 绑定到 clusterrole 上,授予权限,权限只是在 paopao 这个名称空间有效 

1 把 lucky 这个用户通过 rolebinding 绑定到 clusterrole 上 
[root@k8smaster ~]# kubectl create ns paopao 
namespace/paopao created
[root@k8smaster ~]# kubectl create rolebinding paopao -n paopao --clusterrole=cluster-admin --user=paopao
rolebinding.rbac.authorization.k8s.io/paopao created

2 测试是否有权限 
[root@k8smaster ~]# kubectl config use-context paopao@kubernetes 
Switched to context "paopao@kubernetes".
[root@k8smaster ~]# kubectl get pods					没有权限操作其他名称空间 
Error from server (Forbidden): pods is forbidden: User "paopao" cannot list resource "pods" in API group "" in the namespace "default"
[root@k8smaster ~]# kubectl get pods -n paopao			有权限操作这个名称空间 
No resources found in paopao namespace.

添加一个 paopao 的普通用户 
[root@k8smaster ~]# useradd paopao
[root@k8smaster ~]# cp /root/.kube/config /root/testconfig
[root@k8smaster ~]# vim /root/testconfig
#删除以下内容
- context:
    cluster: kubernetes
    user: kubernetes-admin
  name: kubernetes-admin@kubernetes

- name: kubernetes-admin
  user:
    client-certificate-data: 
#下面的两大行密钥也删除

[root@k8smaster ~]# cp -ar /root/.kube/ /home/paopao/ 
[root@k8smaster ~]# cp -ar /root/testconfig /home/paopao/.kube/config 
cp: overwrite ‘/home/paopao/.kube/config’? y
[root@k8smaster ~]# rm -f /home/paopao/.kube/testconfig 
[root@k8smaster ~]# chown -R paopao.paopao /home/paopao/ 
[root@k8smaster ~]# su - paopao
Last login: Sat Jul 16 00:47:20 PDT 2022 on pts/0
[paopao@k8smaster ~]$ kubectl get pods -n paopao
No resources found in paopao namespace.
#只能查看paopao这个命名空间

write at the end

It is not easy to create, if you think the content is helpful to you, please give me a three-link follow to support me! If there are any mistakes, please point them out in the comments and I will change them in time!

Series currently being updated: TBD

Thank you for watching, the article is mixed with personal understanding, if there is any error, please contact me to point out~

Guess you like

Origin blog.csdn.net/qq_45400861/article/details/127294791