Kubernetes RBAC

The new role-based access control mechanism (Role-Based Access, RBAC) in Kubernetes version 1.6 allows cluster administrators to conduct more precise resource access control for the roles of specific users or service accounts. In RBAC, permissions are associated with roles, and users gain permissions from those roles by becoming members of the appropriate roles. This greatly simplifies the management of permissions. In an organization, roles are created to complete various tasks, and users are assigned corresponding roles based on their responsibilities and qualifications. Users can be easily assigned from one role to another.

You need to understand some basic concepts and ideas of RBAC. RBAC is an authorization method that allows users to access Kubernetes API resources.

a51223d13121de324b96f95079739b13

Two objects are defined in RBAC to describe connection permissions between users and resources.

Role

A role is a collection of a series of permissions. For example, a role can include permissions to read Pods and list Pods. ClusterRole is similar to Role, but can be used everywhere in the cluster (Role is at the namespace level).

Character Binding

RoleBinding maps roles to users, allowing those users to inherit the role’s permissions in the namespace. ClusterRoleBinding lets users inherit ClusterRole permissions across the cluster.

57bdf8ca7815303ad055ddfdb208836f

Service account principle

There are two kinds of users in k8s, one is User, and the other is service account. User is used by people, and service account is used by processes to give them relevant permissions.

If dasboard is a process, we can create a service account for it and let it access k8s.

Example 1: dashborad yaml

# ------------------- Dashboard Secret ------------------- #

apiVersion: v1
Kind: Secret
metadata:
  labels:
    k8s-app: kubernetes-dashboard
  name: kubernetes-dashboard-certs
  namespace: kube-system
type: Opaque

---
# ------------------- Dashboard Service Account ------------------- #

apiVersion: v1
kind: ServiceAccount
metadata:
  labels:
    k8s-app: kubernetes-dashboard
  name: kubernetes-dashboard
  namespace: kube-system

---
# ------------------- Dashboard Role & amp; Role Binding ------------------- #

kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: kubernetes-dashboard-minimal
  namespace: kube-system
rules:
  # Allow Dashboard to create 'kubernetes-dashboard-key-holder' secret.
- apiGroups: [""]
  resources: ["secrets"]
  verbs: ["create"]
  # Allow Dashboard to create 'kubernetes-dashboard-settings' config map.
- apiGroups: [""]
  resources: ["configmaps"]
  verbs: ["create"]
  # Allow Dashboard to get, update and delete Dashboard exclusive secrets.
- apiGroups: [""]
  resources: ["secrets"]
  resourceNames: ["kubernetes-dashboard-key-holder", "kubernetes-dashboard-certs"]
  verbs: ["get", "update", "delete"]
  # Allow Dashboard to get and update 'kubernetes-dashboard-settings' config map.
- apiGroups: [""]
  resources: ["configmaps"]
  resourceNames: ["kubernetes-dashboard-settings"]
  verbs: ["get", "update"]
  # Allow Dashboard to get metrics from heapster.
- apiGroups: [""]
  resources: ["services"]
  resourceNames: ["heapster"]
  verbs: ["proxy"]
- apiGroups: [""]
  resources: ["services/proxy"]
  resourceNames: ["heapster", "http:heapster:", "https:heapster:"]
  verbs: ["get"]

---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: kubernetes-dashboard-minimal
  namespace: kube-system
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: kubernetes-dashboard-minimal
subjects:
- kind: ServiceAccount
  name: kubernetes-dashboard
  namespace: kube-system

---
# ------------------- Dashboard Deployment ------------------- #

Kind: Deployment
apiVersion: apps/v1
metadata:
  labels:
    k8s-app: kubernetes-dashboard
  name: kubernetes-dashboard
  namespace: kube-system
spec:
  replicas: 1
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      k8s-app: kubernetes-dashboard
  template:
    metadata:
      labels:
        k8s-app: kubernetes-dashboard
    spec:
      nodeSelector:
        node-role.kubernetes.io/master: ""
      containers:
      - name: kubernetes-dashboard
        image: registry.cn-hangzhou.aliyuncs.com/k8sth/kubernetes-dashboard-amd64:v1.8.3
        ports:
        - containerPort: 8443
          protocol: TCP
        args:
          - --auto-generate-certificates
          # Uncomment the following line to manually specify Kubernetes API server Host
          # If not specified, Dashboard will attempt to auto discover the API server and connect
          # to it. Uncomment only if the default does not work.
          # - --apiserver-host=http://my-address:port
        volumeMounts:
        - name: kubernetes-dashboard-certs
          mountPath: /certs
          # Create on-disk volume to store exec logs
        - mountPath: /tmp
          name: tmp-volume
        livenessProbe:
          httpGet:
            scheme: HTTPS
            path: /
            port: 8443
          initialDelaySeconds: 30
          timeoutSeconds: 30
      volumes:
      - name: kubernetes-dashboard-certs
        secret:
          secretName: kubernetes-dashboard-certs
      - name: tmp-volume
        emptyDir: {}
      serviceAccountName: kubernetes-dashboard
      # Comment the following tolerations if Dashboard must not be deployed on master
      tolerations:
      - key: node-role.kubernetes.io/master
        effect:NoSchedule

---
# ------------------- Dashboard Service ------------------- #

Kind: Service
apiVersion: v1
metadata:
  labels:
    k8s-app: kubernetes-dashboard
  name: kubernetes-dashboard
  namespace: kube-system
spec:
  type: NodePort
  ports:
    - port: 443
      targetPort: 8443
      nodePort: 30000
  selector:
    k8s-app: kubernetes-dashboard

---
apiVersion: v1
kind: ServiceAccount
metadata:
  name:admin-user
  namespace: kube-system

---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name:admin-user
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
- kind: ServiceAccount
  name:admin-user
  namespace: kube-system


# Get TOken
# kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep admin-user | awk '{print $1}')

View Code

Example 2: Create a devuser user and grant read-only permissions to pods in a specific namespace

The first step is to install cfssl

wget https://pkg.cfssl.org/R1.2/cfssl_linux-amd64
chmod +x cfssl_linux-amd64
mv cfssl_linux-amd64 /bin/cfssl

wget https://pkg.cfssl.org/R1.2/cfssljson_linux-amd64
chmod +x cfssljson_linux-amd64
mv cfssljson_linux-amd64 /bin/cfssljson

wget https://pkg.cfssl.org/R1.2/cfssl-certinfo_linux-amd64
chmod +x cfssl-certinfo_linux-amd64
mv cfssl-certinfo_linux-amd64 /bin/cfssl-certinfo

View Code

The second step is to issue the client certificate

Create ca-config.json file

cat > ca-config.json <<EOF
{
  "signing": {
    "default": {
      "expiry": "87600h"
    },
    "profiles": {
      "kubernetes": {
        "usages": [
            "signing",
            "key encipherment",
            "server auth",
            "client auth"
        ],
        "expiry": "87600h"
      }
    }
  }
}
EOF

View Code

Create devuser-csr.json file

cat > devuser-csr.json <<EOF
{
  "CN": "devuser",
  "hosts": [],
  "key": {
    "algo": "rsa",
    "size": 2048
  },
  "names": [
    {
      "C": "CN",
      "ST": "BeiJing",
      "L": "BeiJing",
      "O": "k8s",
      "OU": "System"
    }
  ]
}
EOF

View Code

The third step is to generate the devuser certificate

$ cfssl gencert -ca=ca.crt -ca-key=ca.key -config=ca-config.json -profile=kubernetes devuser-csr.json | cfssljson -bare devuser

View Code

Three files will be generated: devuser.csr devuser-key.pem devuser.pem

The fourth step is to generate the config file

ubeadm has generated admin.conf. We can use this file directly to save ourselves the trouble of configuring cluster parameters ourselves.

$ cp /etc/kubernetes/admin.conf devuser.kubeconfig

Set client authentication parameters:

kubectl config set-credentials devuser \
--client-certificate=/etc/kubernetes/pki/devuser.pem \
--client-key=/etc/kubernetes/pki/devuser-key.pem \
--embed-certs=true \
--kubeconfig=devuser.kubeconfig

Set context parameters:

kubectl config set-context kubernetes \
--cluster=kubernetes \
--user=devuser \
--namespace=kube-system \
--kubeconfig=devuser.kubeconfig

Set the MoD context:

kubectl config use-context kubernetes --kubeconfig=devuser.kubeconfig

Perform the above steps to see the changes in devuser.kubeconfig. The three most important things in it

  • cluster: cluster information, including cluster address and public key
  • user: user information, client certificate and private key. The real information is read from the certificate. What people can see is only for others.
  • context: maintain a triplet, namespace cluster and user

Step 5: Create a role

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: kube-system
  name: pod-reader
rules:
  - apiGroups: [""] # represents the core API Group
    resources: ["pods"] # Resource objects that can be accessed
    verbs: ["get", "watch", "list"] # Operations that can be performed

---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: read-pods
  namespace: kube-system
subjects:
  - kind: User
    name: devuser
    namespace: kube-system
    apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io

Step six, use the new config file

$ rm .kube/config & amp; & amp; cp devuser.kubeconfig .kube/config

Step 7, test the effect

[root@node01 ~]# kubectl get pod
NAME READY STATUS RESTARTS AGE
coredns-777d78ff6f-rrpx8 1/1 Running 3 8d
coredns-777d78ff6f-tql47 1/1 Running 3 8d
etcd-node01 1/1 Running 3 8d
kube-apiserver-node01 1/1 Running 3 8d
kube-controller-manager-node01 1/1 Running 3 8d
kube-flannel-ds-rxrp5 1/1 Running 3 8d
kube-proxy-r6bd2 1/1 Running 3 8d
kube-scheduler-node01 1/1 Running 2 8d
kubernetes-dashboard-d4866d978-kpz4m 1/1 Running 0 10h
[root@node01 ~]# kubectl get service
No resources found.
Error from server (Forbidden): services is forbidden: User "devuser" cannot list services in the namespace "kube-system"

Reference document: https://www.jianshu.com/p/61e8297f9838

The knowledge points of the article match the official knowledge archives, and you can further learn relevant knowledge. Java skill treeIn-depth study of the functional methods of the containerCollection 132706 people are learning the system