Kubernetes RBAC Combat kubernetes User role access control, dashboard Access, KUBECTL configuration generation

Source: Internet
Author: User
Tags k8s
This is a creation in Article, where the information may have evolved or changed.

Kubernetes RBAC Combat

Environment preparation

First with Kubeadm installed Kubernetes cluster, package address in this handy and convenient, thoughtful service, fair trade

For purposes of this article, users named Devuser can only have access to pods under a specific namespace

Command line KUBECTL Access

Installing CFSSL

This tool generates certificates very conveniently, and the PEM certificate is consistent with the CRT certificate, which can be used directly

wget https://pkg.cfssl.org/R1.2/cfssl_linux-amd64chmod +x cfssl_linux-amd64mv cfssl_linux-amd64 /bin/cfsslwget https://pkg.cfssl.org/R1.2/cfssljson_linux-amd64chmod +x cfssljson_linux-amd64mv cfssljson_linux-amd64 /bin/cfssljsonwget https://pkg.cfssl.org/R1.2/cfssl-certinfo_linux-amd64chmod +x cfssl-certinfo_linux-amd64mv cfssl-certinfo_linux-amd64 /bin/cfssl-certinfo

Issuing client certificates

Issuing a user certificate based on the CA certificate and the key
The root certificate is already in the/etc/kubernetes/pki directory.

[root@master1 ~]# ls /etc/kubernetes/pki/apiserver.crt                 ca-config.json  devuser-csr.json    front-proxy-ca.key      sa.pubapiserver.key                 ca.crt          devuser-key.pem     front-proxy-client.crtapiserver-kubelet-client.crt  ca.key          devuser.pem         front-proxy-client.keyapiserver-kubelet-client.key  devuser.csr     front-proxy-ca.crt  sa.key

Note the following several files:ca.crt ca.key ca-config.json devuser-csr.json

Create a 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

To create a Devuser-csr.json file:
K8s's username is obtained from the CN. The group is obtained from O. This user or group is used for subsequent role bindings

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

Generate the user's certificate:

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

The following file is generated:

devuser.csr  devuser-key.pem  devuser.pem

Verifying certificates

# cfssl-certinfo -cert kubernetes.pem

Generate config file

Kubeadm has generated admin.conf, we can directly use this file, save yourself to configure the cluster parameters

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

Set Client Authentication parameters:

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

To set the context parameters:

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

Set the MO-recognition context:

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

Take a step above to see the devuser.kubeconfig changes. The main three things inside.

    • Cluster: Cluster information, including cluster address and public key
    • User information, client certificate and private key, the real information is read from the certificate, people can see just to show people.
    • Context: Maintenance of a ternary group, namespace cluster and user

Create a role

Create a role called Pod-reader

[root@master1 ~]# cat pod-reader.yamlkind: RoleapiVersion: rbac.authorization.k8s.io/v1metadata:  namespace: kube-system  name: pod-readerrules:- apiGroups: [""] # "" indicates the core API group  resources: ["pods"]  verbs: ["get", "watch", "list"]
kubectl create -f pod-reader.yaml

Bind user

Create a role binding to bind the Pod-reader role to the Devuser

[root@master1 ~]# cat devuser-role-bind.yamlkind: RoleBindingapiVersion: rbac.authorization.k8s.io/v1metadata:  name: read-pods  namespace: kube-systemsubjects:- kind: User  name: devuser   # 目标用户  apiGroup: rbac.authorization.k8s.ioroleRef:  kind: Role  name: pod-reader  # 角色信息  apiGroup: rbac.authorization.k8s.io
kubectl create -f devuser-role-bind.yaml

Using the new config file

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

Effect, there is no other namespace permissions, and can not access node information:

[Root@master1 ~]# Kubectl get nodeerror from server (Forbidden): Nodes are Forbidden:user "Devuser" cannot list nodes at t He cluster Scope[root@master1 ~]# kubectl get pod-n kube-systemname ready Statu                          S restarts agecalico-kube-controllers-55449f8d88-74x8f 1/1 Running 0 8DCALICO-NODE-CLPQR          2/2 Running 0 8dkube-apiserver-master1 1/1 Running 2                  8dkube-controller-manager-master1 1/1 Running 1 8dkube-dns-545bc4bfd4-p6trj 3/3 Running 0 8dkube-proxy-tln54 1/1 Running 0 8dkube-schedule R-master1 1/1 Running 1 8d[root@master1 ~]# kubectl get pod-n defaulterror from serv ER (Forbidden): Pods is Forbidden:user "devuser" cannot list pods in the namespace "default": role.rbac.authorization.k8s . io "Pod-reader" not found 

Dashboard Access

Service Account Principle

K8s inside there are two kinds of users, one is user, one is the service account,user for people, service account for the process, so that the process has the relevant permissions.

If Dasboard is a process, we can create a service account to give it access to k8s.

Let's take a look at how to assign Admin permissions to dashboard:

╰─➤  cat dashboard-admin.yamlapiVersion: rbac.authorization.k8s.io/v1beta1kind: ClusterRoleBindingmetadata:  name: kubernetes-dashboard  labels:    k8s-app: kubernetes-dashboardroleRef:  apiGroup: rbac.authorization.k8s.io  kind: ClusterRole  name: cluster-adminsubjects:- kind: ServiceAccount  name: kubernetes-dashboard  namespace: kube-system

Kubernetes-dashboard this serviceaccount binding to cluster-admin this clusterrole, this cluster role is very good, what permissions have

[root@master1 ~]# kubectl describe clusterrole cluster-admin -n kube-systemName:         cluster-adminLabels:       kubernetes.io/bootstrapping=rbac-defaultsAnnotations:  rbac.authorization.kubernetes.io/autoupdate=truePolicyRule:  Resources  Non-Resource URLs  Resource Names  Verbs  ---------  -----------------  --------------  -----             [*]                []              [*]  *.*        []                 []              [*]

This service account was created when Dashboard was created:

apiVersion: v1kind: ServiceAccountmetadata:  labels:    k8s-app: kubernetes-dashboard  name: kubernetes-dashboard  namespace: kube-system

Then specify the service account in the deployment

      volumes:      - name: kubernetes-dashboard-certs        secret:          secretName: kubernetes-dashboard-certs      - name: tmp-volume        emptyDir: {}      serviceAccountName: kubernetes-dashboard

More secure approach

[root@master1 ~]# cat admin-token.yamlkind: ClusterRoleBindingapiVersion: rbac.authorization.k8s.io/v1beta1metadata:  name: admin  annotations:    rbac.authorization.kubernetes.io/autoupdate: "true"roleRef:  kind: ClusterRole  name: cluster-admin  apiGroup: rbac.authorization.k8s.iosubjects:- kind: ServiceAccount  name: admin  namespace: kube-system---apiVersion: v1kind: ServiceAccountmetadata:  name: admin  namespace: kube-system  labels:    kubernetes.io/cluster-service: "true"    addonmanager.kubernetes.io/mode: Reconcile
[root@master1 ~]# kubectl get secret -n kube-system|grep adminadmin-token-7rdhf                        kubernetes.io/service-account-token   3         14m
[Root@master1 ~]# Kubectl describe secret admin-token-7rdhf-n Kube-systemname:admin-token-7rdhfnamespace:kub E-systemlabels: <none>annotations:kubernetes.io/service-account.name=admin Kubernetes.io/servic e-account.uid=affe82d4-d10b-11e7-ad03-00163e01d684type:kubernetes.io/service-account-tokendata====ca.crt:1025      Bytesnamespace:11 Bytestoken: Eyjhbgcioijsuzi1niisinr5cci6ikpxvcj9.eyjpc3mioijrdwjlcm5ldgvzl3nlcnzpy2vhy2nvdw50iiwia3vizxjuzxrlcy5pby9zzxj2awnlywnjb3vu Dc9uyw1lc3bhy2uioijrdwjllxn5c3rlbsisimt1ymvybmv0zxmuaw8vc2vydmljzwfjy291bnqvc2vjcmv0lm5hbwuioijhzg1pbi10b2tlbi03cmroziisi Mt1ymvybmv0zxmuaw8vc2vydmljzwfjy291bnqvc2vydmljzs1hy2nvdw50lm5hbwuioijhzg1pbiisimt1ymvybmv0zxmuaw8vc2vydmljzwfjy291bnqvc2 Vydmljzs1hy2nvdw50lnvpzci6imfmzmu4mmq0lwqxmgitmtflny1hzdazltawmtyzztaxzdy4ncisinn1yii6inn5c3rlbtpzzxj2awnlywnjb3vuddprdwj Llxn5c3rlbtphzg1pbij9.jsfqhfsy7v0zmfqxm8lm_ Uuoouhi86axdseyvvtldsuy-bep2nw4q-ookgjtbbsrowvmiqepcqxjtkr1k4eifna2fonvm4ijMa40pr7-orvy37ynr_ 1lmalg9vrwmqfiqiske9hjkofducap7uiuv16rsv7hrll4itoqmjmyj1xj2qb1ow4p1pdarr4pw02xbz9ybpd1fs-lbwheu1ukcenbhs_ 0s3zlmagcrpwdfl2uyomgukqvpjhx4wbrrqbwo1sn4refvi1nia9l_ Lm7mf6yequlhru3bcztdu9yfy9pevqz4ofhe0novdiqmgrl8z9kpadaxbljwzcd1m1xcq

Sign in with this token on the interface

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.