This shows you the differences between two versions of the page.
| Next revision | Previous revision | ||
|
управление_правами_в_kubernetes [2025/11/01 06:08] val created |
управление_правами_в_kubernetes [2025/11/01 13:31] (current) val [Управление правами в Kubernetes] |
||
|---|---|---|---|
| Line 1: | Line 1: | ||
| ====== Управление правами в Kubernetes ====== | ====== Управление правами в Kubernetes ====== | ||
| + | * [[https://kubernetes.io/docs/reference/access-authn-authz/authentication/|Kubernetes Documentation -> Reference -> API Access Control -> Authenticating]] | ||
| + | |||
| + | * [[https://habr.com/ru/articles/779190/|Как работает аутентификация в Kubernetes: ServiceAccount и RBAC]] | ||
| + | * [[https://medium.com/@muppedaanvesh/a-hand-on-guide-to-kubernetes-rbac-with-a-user-creation-%EF%B8%8F-1ad9aa3cafb1|A Hands-On Guide to Kubernetes RBAC With a User Creation]] | ||
| + | * [[https://kubernetes.io/docs/reference/kubectl/generated/kubectl_config/kubectl_config_set-credentials/|Kubernetes Documentation kubectl config set-credentials]] | ||
| + | |||
| + | * [[https://www.container-security.site/security_research/node_proxy.html|Node/Proxy in Kubernetes RBAC]] | ||
| + | * [[https://stackoverflow.com/questions/60445336/how-to-grant-access-to-specify-namespace-in-kubernetes-dashboard|How to grant access to specify namespace in kubernetes dashboard?]] | ||
| + | * [[https://docs.sc.otc.t-systems.com/cloud-container-engine/umn/permissions_management/namespace_permissions_kubernetes_rbac-based.html|Namespace Permissions (Kubernetes RBAC-based)]] | ||
| + | * [[https://medium.com/@ManagedKube/kubernetes-rbac-port-forward-4c7eb3951e28|Kubernetes RBAC Port Forward]] | ||
| + | |||
| + | |||
| + | ===== Реклама ===== | ||
| + | |||
| + | * Kubernetes — это решение, превращающее Linux сервера в кластер, и, как Linux является многопользовательской, многозадачной операционной системой, так и Kubernetes позволяет множеству пользователей и приложений работать в одном кластере безопасно разделяя его ресурсы | ||
| + | * На нашем вебинаре Вы узнаете как настраивать права доступа в Kubernetes на примерах практических, полезных задач | ||
| + | |||
| + | |||
| + | ===== Техническое задание ===== | ||
| + | |||
| + | * Создать учетную запись пользователя с необходимыми правами и файл конфигурации для подключения младшего системного администратора к Web ресурсам Kubernetes | ||
| + | * Создать учтённую запись для сервиса с необходимыми правами для запуска приложений в Kubernetes | ||
| + | |||
| + | ===== Запись вебинара ===== | ||
| + | |||
| + | * Тэги: Kubernetes, ServiceAccout, RBAC | ||
| + | |||
| + | ===== Шаг 1. Что у нас есть, для начала ===== | ||
| + | |||
| + | * [[Система Kubernetes]] | ||
| + | |||
| + | * Cloud native distributed block storage for Kubernetes [[Сервис Keycloak#longhorn]] | ||
| + | * [[Сервис Keycloak#rancher local-path-provisioner]] и кластер [[Сервис PostgreSQL#CloudNativePG]] для Keycloak в [[Сервис Keycloak#Kubernetes]] | ||
| + | * [[Система Kubernetes#Kubernetes Dashboard]] без ServiceAccout | ||
| + | |||
| + | * Linux [[Инсталяция системы в конфигурации Desktop]] и [[Управление учетными записями в Linux#Создание тестового набора учетных записей]] | ||
| + | |||
| + | ===== Шаг 2. Создание учетной записи ===== | ||
| + | |||
| + | ==== Вариант 2.1 Использование сертификатов ==== | ||
| + | |||
| + | * [[Пакет OpenSSL#Создание пользовательского сертификата, подписанного CA]] | ||
| + | |||
| + | <code> | ||
| + | user1@client1:~$ cat user1.req | base64 -w0 | ||
| + | </code> | ||
| + | * [[https://stackoverflow.com/questions/75735249/what-do-the-values-in-certificatesigningrequest-spec-usages-mean|What do the values in CertificateSigningRequest.spec.usages mean?]] | ||
| + | <code> | ||
| + | kube1:~/users# kubectl explain csr.spec.usages | ||
| + | |||
| + | kube1:~/users# cat user1.req.yaml | ||
| + | </code><code> | ||
| + | apiVersion: certificates.k8s.io/v1 | ||
| + | kind: CertificateSigningRequest | ||
| + | metadata: | ||
| + | name: user1 | ||
| + | spec: | ||
| + | request: LS0t...S0tCg== | ||
| + | signerName: kubernetes.io/kube-apiserver-client | ||
| + | expirationSeconds: 8640000 # 100 * one day | ||
| + | usages: | ||
| + | # - digital signature | ||
| + | # - key encipherment | ||
| + | - client auth | ||
| + | </code><code> | ||
| + | kube1:~/users# kubectl apply -f user1.req.yaml | ||
| + | |||
| + | kube1:~/users# kubectl describe csr/user1 | ||
| + | |||
| + | kube1:~/users# kubectl certificate approve user1 | ||
| + | |||
| + | kube1:~/users# kubectl get csr | ||
| + | |||
| + | kube1:~/users# kubectl get csr/user1 -o yaml | ||
| + | |||
| + | kube1:~/users# kubectl get csr/user1 -o jsonpath="{.status.certificate}" | base64 -d | tee user1.crt | ||
| + | |||
| + | |||
| + | user1@client1:~$ scp root@kube1:users/user1.crt . | ||
| + | </code> | ||
| + | |||
| + | ==== Вариант 2.2 Использование ServiceAccount ==== | ||
| + | |||
| + | * Для примера можно использовать ServiceAccout из темы [[Система Kubernetes#Kubernetes Dashboard]] в Namespace default | ||
| + | * Показать временные и long-lived Bearer Token для ServiceAccount | ||
| + | |||
| + | ==== Шаг 2.3 Создание файла конфигурации kubectl ==== | ||
| + | |||
| + | * [[Система Kubernetes#Инструмент командной строки kubectl]] | ||
| + | * [[https://kubernetes.io/docs/reference/kubectl/generated/kubectl_config/kubectl_config_set-credentials/]] | ||
| + | <code> | ||
| + | user1@client1:~$ kubectl config set-cluster cluster.local --insecure-skip-tls-verify=true --server=https://192.168.13.221:6443 | ||
| + | |||
| + | user1@client1:~$ cat .kube/config | ||
| + | |||
| + | user1@client1:~$ kubectl config set-credentials user1 --client-certificate=user1.crt --client-key=user1.key --embed-certs=true | ||
| + | ИЛИ | ||
| + | user1@client1:~$ kubectl config set-credentials user1 --token=................................... | ||
| + | |||
| + | user1@client1:~$ kubectl config get-users | ||
| + | |||
| + | user1@client1:~$ kubectl config set-context default-context --cluster=cluster.local --user=user1 | ||
| + | |||
| + | user1@client1:~$ kubectl config use-context default-context | ||
| + | |||
| + | user1@client1:~$ kubectl auth whoami | ||
| + | |||
| + | user1@client1:~$ kubectl get pods | ||
| + | Error from server (Forbidden) или ... | ||
| + | </code> | ||
| + | |||
| + | ===== Шаг 3. Использование Role и RoleBinding ===== | ||
| + | |||
| + | ==== Предоставление доступа к services/proxy в Namespace ==== | ||
| + | |||
| + | * Cloud native distributed block storage for Kubernetes [[Сервис Keycloak#longhorn]] | ||
| + | |||
| + | <code> | ||
| + | kube1:~/users# cat lh-svc-proxy-role.yaml | ||
| + | </code><code> | ||
| + | apiVersion: rbac.authorization.k8s.io/v1 | ||
| + | kind: Role | ||
| + | metadata: | ||
| + | namespace: longhorn-system | ||
| + | name: lh-svc-proxy-role | ||
| + | rules: | ||
| + | - apiGroups: [""] | ||
| + | resources: ["services/proxy"] | ||
| + | verbs: ["get"] | ||
| + | </code><code> | ||
| + | kube1:~/users# cat user1-lh-svc-proxy-rolebinding.yaml | ||
| + | </code><code> | ||
| + | apiVersion: rbac.authorization.k8s.io/v1 | ||
| + | kind: RoleBinding | ||
| + | metadata: | ||
| + | name: user1-lh-svc-proxy-rolebinding | ||
| + | namespace: longhorn-system | ||
| + | subjects: | ||
| + | - kind: User | ||
| + | name: user1 | ||
| + | apiGroup: rbac.authorization.k8s.io | ||
| + | roleRef: | ||
| + | kind: Role | ||
| + | name: lh-svc-proxy-role | ||
| + | apiGroup: rbac.authorization.k8s.io | ||
| + | </code><code> | ||
| + | kube1:~/users# kubectl apply -f lh-svc-proxy-role.yaml,user1-lh-svc-proxy-rolebinding.yaml | ||
| + | |||
| + | student@client1:~$ kubectl proxy | ||
| + | |||
| + | student@client1:~$ curl http://localhost:8001/api/v1/namespaces/longhorn-system/services/longhorn-frontend:80/proxy/ | ||
| + | |||
| + | student@client1:~$ curl http://localhost:8001/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/ | ||
| + | </code> | ||
| + | ==== Предоставление полного доступа к Namespace ==== | ||
| + | |||
| + | <code> | ||
| + | </code> | ||
| + | |||
| + | * [[Система Kubernetes#Базовые объекты k8s]] | ||
| + | ==== Поиск предоставленных ролей для учетной записи ==== | ||
| + | <code> | ||
| + | kube1:~/users# kubectl get rolebindings --all-namespaces -o=json | jq '.items[] | select(.subjects[]?.name == "user1")' | ||
| + | </code> | ||
| + | ===== Шаг 4. Использование ClusterRole и ClusterRoleBinding на ===== | ||
| + | |||
| + | ==== Предоставление доступа к services/port-forward в Cluster ==== | ||
| + | |||
| + | <code> | ||
| + | kube1:~/users# cat svc-pfw-role.yaml | ||
| + | </code><code> | ||
| + | apiVersion: rbac.authorization.k8s.io/v1 | ||
| + | kind: ClusterRole | ||
| + | #kind: Role | ||
| + | metadata: | ||
| + | name: svc-pfw-role | ||
| + | # namespace: my-pgcluster-ns | ||
| + | rules: | ||
| + | - apiGroups: [""] | ||
| + | resources: ["services"] | ||
| + | verbs: ["get"] | ||
| + | - apiGroups: [""] | ||
| + | resources: ["pods"] | ||
| + | verbs: ["get", "list"] | ||
| + | - apiGroups: [""] | ||
| + | resources: ["pods/portforward"] | ||
| + | verbs: ["create"] | ||
| + | </code><code> | ||
| + | kube1:~/users# cat user1-svc-pfw-rolebinding.yaml | ||
| + | </code><code> | ||
| + | apiVersion: rbac.authorization.k8s.io/v1 | ||
| + | kind: ClusterRoleBinding | ||
| + | #kind: RoleBinding | ||
| + | metadata: | ||
| + | name: user1-svc-pfw-rolebinding | ||
| + | # namespace: my-pgcluster-ns | ||
| + | subjects: | ||
| + | - kind: User | ||
| + | name: user1 | ||
| + | apiGroup: rbac.authorization.k8s.io | ||
| + | roleRef: | ||
| + | kind: ClusterRole | ||
| + | # kind: Role | ||
| + | name: svc-pfw-role | ||
| + | apiGroup: rbac.authorization.k8s.io | ||
| + | kube1:~/users# kubectl apply -f svc-pfw-role.yaml,user1-svc-pfw-rolebinding.yaml | ||
| + | |||
| + | student@client1:~$ kubectl port-forward -n my-pgcluster-ns services/my-pgcluster-rw 5432:5432 | ||
| + | |||
| + | student@client1:~$ psql postgres://keycloak:strongpassword@127.0.0.1:5432/postgres | ||
| + | </code> | ||
| + | |||
| + | ==== Предоставление полного доступа к Cluster ==== | ||
| + | |||
| + | <code> | ||
| + | kube1:~/users# kubectl get clusterroles |less | ||
| + | |||
| + | kube1:~/users# kubectl get clusterrolebindings cluster-admin -o yaml | ||
| + | |||
| + | kube1:~/users# kubectl get clusterrole view -o yaml | ||
| + | |||
| + | kube1:~/users# cat user1-view-clusterrolebinding.yaml | ||
| + | </code><code> | ||
| + | apiVersion: rbac.authorization.k8s.io/v1 | ||
| + | kind: ClusterRoleBinding | ||
| + | metadata: | ||
| + | name: user1-view-clusterrolebinding | ||
| + | subjects: | ||
| + | - kind: User | ||
| + | name: user1 | ||
| + | apiGroup: rbac.authorization.k8s.io | ||
| + | roleRef: | ||
| + | kind: ClusterRole | ||
| + | name: view | ||
| + | apiGroup: rbac.authorization.k8s.io | ||
| + | </code><code> | ||
| + | kube1:~/users# kubectl apply -f user1-view-clusterrolebinding.yaml | ||
| + | |||
| + | student@client1:~$ kubectl get pods -A | ||
| + | |||
| + | student@client1:~$ kubectl port-forward -n my-pgcluster-ns services/my-pgcluster-rw 5432:5432 | ||
| + | error: error upgrading connection: pods "my-pgcluster-3" is forbidden: User "user1" cannot create resource "pods/portforward" in API group "" in the namespace "my-pgcluster-ns" | ||
| + | </code> | ||
| + | |||
| + | ==== Поиск предоставленных кластерных ролей для учетной записи ==== | ||
| + | <code> | ||
| + | kube1:~/users# kubectl get clusterrolebindings -o=json | jq '.items[] | select(.subjects[]?.name == "user1")' | ||
| + | </code> | ||
| + | |||
| + | ===== Шаг 5. Использование JSON Web Token (JWT) для доступа в Kubernetes ===== | ||
| + | |||
| + | * Возвращаемся на [[#Вариант 2.2 Использование ServiceAccount]] | ||
| + | |||
| + | ===== Вопросы? ===== | ||
| + | |||
| + | ===== Домашнее задание ===== | ||
| + | |||
| + | - Куда и через сколько исчезает "kubectl get csr" после "approve" ? | ||