158. Authorization

Why Authorization? 

권한을 지정하여 할 수있는 작업을 제한 해야한다. 

 

Authorization Mechanisms

인증 메카니즘으로 노드, abac, rbac, webhook 이 있다. 

 

Node

kubeapi서버에는 사용자도 접근하고 kubelet 도 접근한다. 

 

kubelet 이 정보를 요청할 때 kubeapi 에 인증을 했기 때문에 kube api 가 응답하는 것이다.

해당 승인을 하는 곳이 node Authorizer 이다. 

 

ABAC - 특성 기반 승인

사용자를 추가시켜서 권한을 부여한다. 

당연히 일일히 수동으로 추가하면 귀찮으니까 ...

 

 

RBAC - 역할 기반 인증

역할 기반으로 하면 좀 더 쉽게 권한 제어가 가능하다. 

 

Webhook 

외부에서 권한 제어를 하고 싶다면 ?

 

Open Policy Agent 가 권한을 체크해준다. 

 

Authorization Mode

AlwaysAllow, AlwaysDeny 이 두가지가 있다. 

kubeapiserver를 보면 authorization 을 확인할 수 있다.

default 는 always allow 이다. 

멀티플 모드도 가능하다.

하나가 거부되면 다음 모드에서 확인하고 승인되면 넘겨준다. 

 


159. Role Based Access Control 

역할을 생성해보자! 

 rule을 여러개 추가할 수도 있다. 

RoleBinding Object

생성한 역할을 쓰기 위해 rolebinding 객체를 생성해야한다. 

View RBAC

해당 명령어로 role 확인

 

 

Check Access - can-i 

can i  명령어로 체크할 수 있다. 

--as user 옵션으로 해당 유저의 권한을 체크할 수 있다. 

ns 도 기입 가능

Resource Names

리소스 이름으로 권한 제한을 할 수 있다. 

( 여기서 resourceNames 가 네임 스페이스 인가 확인해봐야겠다.) 

 


160. Practice Test - RBAC

1. Inspect the environment and identify the authorization modes configured on the cluster.

Check the kube-apiserver settings.

kube-apiserver.yaml 위치 

cat /etc/kubernetes/manifests/kube-apiserver.yaml 

Node, RBAC 이다. 

 

2. How many roles exist in the default namespace?

3. How many roles exist in all namespaces together?

12개

 

4.  What are the resources the kube-proxy role in the kube-system namespace is given access to?

configmaps

 

5. What actions can the kube-proxy role perform on configmaps?

 

get

 

 

6. Which of the following statements are true?

1. kube-proxy role can get details of all configmap objects in the default namespace
2. kube-proxy role can delete the configmap it created
3. kube-proxy role can get details of configmap object by the name kube-proxy only <- 
4. kube-proxy role can get details of all configmap objects in the cluster
5. kube-proxy role can only view and update configmap object by the name kube-proxy

 

7. Which account is the kube-proxy role assigned to?

 Group 부분 

 

8. A user dev-user is created. User's details have been added to the kubeconfig file. Inspect the permissions granted to the user. Check if the user can list pods in the default namespace.

 

9.

Create the necessary roles and role bindings required for the dev-user to create, list and delete pods in the default namespace.

 

10.  A set of new roles and role-bindings are created in the blue namespace for the dev-user. However, the dev-user is unable to get details of the dark-blue-app pod in the blue namespace.

 

Investigate and fix the issue.

We have created the required roles and rolebindings, but something seems to be wrong.

resourceNames 에 dark-blue-app 을 추가해준다. 

 

11. Add a new rule in the existing role developer to grant the dev-user permissions to create deployments in the blue namespace.

Remember to add api group "apps".

추가가해준다. 

 


162.  Cluster Roles and Role bindings

클러스터 롤과 클러스터롤바인딩에 대해 배워보자.

기존에 role은 default 네임스페이스를 가정한다.

 

Namespace

네임스페이스로 걸러지는 리소스가 있고 그 외는 클러스터단의 리소스라고 보면된다. 

확인하고 싶으면 namespaced 옵션을 이용하면 된다. 

지난 시간에 만든 role 과 rolebinding은 네임스페이스에 영향을 받는 구간이다. 

만야 클러스터 단에서 클러스터롤과 바인딩 하고 싶다면?

마찬가지로 클러스터 롤과 바인딩이 있다.

Clusterroles

예시

clusterrolebinding

비슷하다! 

 

클러스터롤 로 파드에 접속하게 허락하면 클러스터내의 모든 파드에 접근할 수 있다. 

 


163. Practice Test - Cluster Roles and Role Bindings

1. For the first few questions of this lab, you would have to inspect the existing ClusterRoles and ClusterRoleBindings that have been created in this cluster.

 

 

2. How many ClusterRoles do you see defined in the cluster?

너무 많을때는??

--no-headers | wc -l 옵션으로 갯수를 찾을 수 있다. 

 

 

3. How many ClusterRoleBindings exist on the cluster?

 

4. What namespace is the cluster-admin clusterrole part of?

1. Cluster Roles are cluster wide and not part of any namespace <- 
2. kube-system
3. kube-public
4. default

 

5. What user/groups are the cluster-admin role bound to?

The ClusterRoleBinding for the role is with the same name.

6. What level of permission does the cluster-admin role grant?

Inspect the cluster-admin role's privileges.

 

1. Perform any action on any resource in the cluster<- 
2. Pod level tasks only
3. Security related tasks only
4. Node level tasks only

 

7. A new user michelle joined the team. She will be focusing on the nodes in the cluster. Create the required ClusterRoles and ClusterRoleBindings so she gets access to the nodes.

node가 아니라 nodes 가 되어야한다.

 

 

8. michelle's responsibilities are growing and now she will be responsible for storage as well. Create the required ClusterRoles and ClusterRoleBindings to allow her access to Storage.

 

Get the API groups and resource names from command kubectl api-resources. Use the given spec:

clusterrole 생성

clusterrolebinding 생성


 165. Service Accounts

서비스 어카운트의 개념을 알아보자! 

account 종류

user 사람

service none 사람

 

프로메테우스나 젠킨스 같은거 

 

dash board 애플리케이션을 만든다면 kube-api에 수시로 요청을 날려야한다. 

당연히 인증이 필요하다.

이럴 때 서비스 계정을 써야한다. 

 

ServiceAccount 관련 명령

서비스 계정을 생성하면 토큰이 생성된다.

토큰의 내용은 암호화되고 해당 토큰으로 kubeapi 에 인증한다.

시크릿 객체이다. 

서비스 객체를 생성하면 토큰을 생성하고 해당 토큰을 시크릿 객체에 넣는다. 

그 후 시크릿 객체와 서비스 객체랑 연결된다. 

따로 시크릿 객체만 확인하는 것도 가능하다.

curl 에 토큰 데이터를 넣어서 api에 접속할 수도 있다. 

대시보드 앱에서 토큰 내용을 사용해서 인증하는 것도 있다.

토큰 마운팅

토큰을 마운팅 하면 앱에서 쉽게 kubeapi 에 접속 가능하다.

 

default sa 는 기본으로 생성됨. 

자세히 보면 volumes 에 default 토큰이 마운트 된다. 

마운트 된 디렉터리를 확인하면 3가지 파일이 있다.

토큰 실행시 암호가 뜬다.

sa 지정해서 사용하기

파드 종료했다가 다시 켜야한다.

default token 안쓰게 하려면

1.22/1.24 업데이트 사항

토큰을 복호화 했을때 자세히 보면 만기 기간이 없다.

 

TokenRequestAPI v1.22

토큰 관리를 위한 api 가 추가되었다.

여러가지 조건을 사용할 수 있다.

pod를 생성하면 주기를 갖는 토큰이 마운트 된다. 

v1.24

예전엔 sa 만들면 토큰도 같이 생성됬지만 이젠 따로 생성해야한다.

이제 토큰에 만기 기간이 뜬다. 

secret 도 생성해야한다. 

 


166. Practice Test Service Accounts

1. 

How many Service Accounts exist in the default namespace?

2개

 

2.

What is the secret token used by the default service account?

none

 

3.

We just deployed the Dashboard application. Inspect the deployment. What is the image used by the deployment?

 

4. 

Wait for the deployment to be ready. Access the custom-dashboard by clicking on the link to dashboard portal.

연결되었다. 

 

5. What is the state of the dashboard? Have the pod details loaded successfully?

failed

 

 

6. What type of account does the Dashboard application use to query the Kubernetes API?

service account 에 연결된다. 

 

7. Which account does the Dashboard application use to query the Kubernetes API?

default 이다..

 

8. Inspect the Dashboard Application POD and identify the Service Account mounted on it.

yaml 열어서 확인

 

9.

At what location is the ServiceAccount credentials available within the pod?

\

 

10. The application needs a ServiceAccount with the Right permissions to be created to authenticate to Kubernetes. The default ServiceAccount has limited access. Create a new ServiceAccount named dashboard-sa.

 

11. We just added additional permissions for the newly created dashboard-sa account using RBAC.

If you are interested checkout the files used to configure RBAC at /var/rbac. We will discuss RBAC in a separate section.

Ok

 

12. Enter the access token in the UI of the dashboard application. Click Load Dashboard button to load Dashboard

 

 

Create an authorization token for the newly created service account, copy the generated token and paste it into the token field of the UI.

To do this, run kubectl create token dashboard-sa for the dashboard-sa service account, copy the token and paste it in the UI.

 

복붙하기

13.

You shouldn't have to copy and paste the token each time. The Dashboard application is programmed to read token from the secret mount location. However currently, the default service account is mounted. Update the deployment to use the newly created ServiceAccount

Edit the deployment to change ServiceAccount from default to dashboard-sa.

 

sa 다시 붙이기

디플로이먼트에서 변경

 

14. Refresh the Dashboard application UI and you should now see the PODs listed automatically.

이제 토큰 기입 없이 사용가능하다. 

 


150. Certificates API 

사용자와 클러스터가 있는 상황이다. 

나는 인증서와 키를 가지고 있다. 

사용자를 추가해야한다면? 

 

b 사용자의 인증서를 관리자한테 주고 관리자가 클러스터에 넘겨 서명을 받는다. 

그리고 사용한다. 

 

쿠버네티스  CA 서버

인증서, 키파일은 서버에 안전하게 저장된다.

마스터 노드에 ca 서버가 있다면 마스터 노드 또한 ca 서버이다 ? 

 

매번 인증서를 넘기고 서명 받는 작업을 하는 것은 귀찮다. 

 

Certificates API 가 하는일

 

인증서를 건낸후 바로 서명 받고 돌려받는 것이 아니라 CSR객체를 만든다 .

객체가 생성되면 모든 유저들이 요청을 검토하고 확인할 수 있다.

1. openssl genrsa - 키생성

2. openssl req - 관리자에게 요청

3. 관리자는 서명 요청 객체 생성

요청은 베이스 64 명령어로 암호화 해야한다.

그 후 인코딩된 텍스트를 요청 필드로 옮기고 요청을 제출한다.

 CSR 이 생성된다. 

csr 확인하기 

인증서 서명하기 

csr yaml 파일을 확인하면 cert 부분은 base 64 로 암호화되어있다. 

 

ca는 controlplane 어느부분에서 담당할까 ?

 

컨트롤러 매니저에서 담당한다. 

controller manager 안에 csr-approving, csr-sigining 이 존재한다.

 

누구든 인증서에 서명하려면 CA 서버의 root 인증서와 개인키 


151. Practice Test - Certificates API 

1.

A new member akshay joined our team. He requires access to our cluster. The Certificate Signing Request is at the /root location.

 

Inspect it

csr과 key 가 있다. 

 

2.

Create a CertificateSigningRequest object with the name akshay with the contents of the akshay.csr file

As of kubernetes 1.19, the API to use for CSR is certificates.k8s.io/v1.

Please note that an additional field called signerName should also be added when creating CSR. For client authentication to the API server we will use the built-in signer kubernetes.io/kube-apiserver-client.

Certificate Signing Requests | Kubernetes

 

Certificate Signing Requests

FEATURE STATE: Kubernetes v1.19 [stable] The Certificates API enables automation of X.509 credential provisioning by providing a programmatic interface for clients of the Kubernetes API to request and obtain X.509 certificates from a Certificate Authority

kubernetes.io

Create CertificateSigningRequest

Create a CertificateSigningRequest and submit it to a Kubernetes Cluster via kubectl. Below is a script to generate the CertificateSigningRequest.

cat <<EOF | kubectl apply -f -
apiVersion: certificates.k8s.io/v1
kind: CertificateSigningRequest
metadata:
  name: myuser
spec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Mkh4TG1WQzg0L1BHT0tWQW9FNkpsYWFHdTlQVmkKdjlOSjVaZlZrcXdCd0hKbzZXdk9xVlA3SVFjZmg3d0drWm89Ci0tLS0tRU5EIENFUlRJRklDQVRFIFJFUVVFU1QtLS0tLQo=
  signerName: kubernetes.io/kube-apiserver-client
  expirationSeconds: 86400  # one day
  usages:
  - client auth
EOF

 

복붙한다.

 

csr 파일의 형식과 다르다. 

 

csr 파일을 -> base 64 로 암호화한뒤 akshay.yaml 파일의 req 부분에 복붙한다. 

-w 0 옵션으로 한줄 출력

실행하기

 

3. What is the Condition of the newly created Certificate Signing Request object?

pending

 

4. Approve the CSR Request

요청 승인하기 

 

5. How many CSR requests are available on the cluster?

2개

 

6.

During a routine check you realized that there is a new CSR request in place. What is the name of this request?

 

agent smith

 

7.

Hmmm.. You are not aware of a request coming in. What groups is this CSR requesting access to?

Check the details about the request. Preferebly in YAML.

열어서 확인해보자

masters 그룹에서 요청

 

8. That doesn't look very right. Reject that request.

 

k certificate deny agent-smith 로 요청 거부할 수 있다. 

 

9. Let's get rid of it. Delete the new CSR object


153. KubeConfig

사용자가 my-kube-playground   클러스터로 인증서 요청을 날린다면 

 

아래는 kubectl 을 이용한 요청 

키, 인증서, ca

매번하면 귀찮기 때문에 kubeconfig 를 만들어서 쉽게 사용

kubeconfig file 의 경로는 $HOME/.kube/config 이다. 

기본으로 설정되어있기 때문에 이때까지 생략하고 잘 쓴거

 KubeConfigFile의 구성

Clusters, Contexts, Users 

이 세가지 context는 어떤 유저가 어떤 클러스터에 접근할 수 있는지 명시한다. 

config 파일이 위와 같다면

mykubeplayground, certificate-authority 는 클러스터로 간다. 

키, 인증서는 users 로 간다. 

두개를 조합해서 컨텍스트를 만든다. 

 

yaml 파일에서 확인 

clusters, user, context 이렇게 되어있다. 

 

파일은 그대로 두고 kubectl 로 실행 

 

kubectl 은 어떤 컨텍스트를 골라야할까 ? 

currentcontext를 사용해 기본 컨텍스트 정의 

 

kubectl config

클러스터 확인 가능

 

현재 컨텍스트 변경하기 

use context 로 컨텍스트를 변경한다. 

 

네임스페이스 관련

네임스페이스는 클러스터 단위에서 생성된다.

컨텍스트 부분에 네임스페이스도 명시한다. 

Certificates in kubeConfig

인증서 파일의 경우 전체 경로를 쓰는 것이 좋다.

ca 파일의 경우 그냥 crt 내용을 암호화해서 복붙할 수도 있다. 


154. Practice Test - KubeConfig

1.  Where is the default kubeconfig file located in the current environment? 

Find the current home directory by looking at the HOME environment variable.

실행해보고 확인가능 

/root/.kube/config

 

2. How many clusters are defined in the default kubeconfig file?

 

1개

 

3. How many Users are defined in the default kubeconfig file?

1개

 

4. How many contexts are defined in the default kubeconfig file?

1개

 

5. What is the user configured in the current context?

6. What is the name of the cluster configured in the default kubeconfig file?

kubernetes

 

7. A new kubeconfig file named my-kube-config is created. It is placed in the /root directory. How many clusters are defined in that kubeconfig file?

 

4개

 

8. How many contexts are configured in the my-kube-config file?

4개

 

9. What user is configured in the research context?

 

dev-user

 

10. What is the name of the client-certificate file configured for the aws-user?

 

aws-user.crt

 

11. What is the current context set to in the my-kube-config file?

 

12.

I would like to use the dev-user to access test-cluster-1. Set the current context to the right one so I can do that.

Once the right context is identified, use the kubectl config use-context command.

 

my-kubeconfig 가 기본 config 파일이 아니기 때문에 --kubeconfig 옵션이 필요하다. 

 

13. We don't want to have to specify the kubeconfig file option on each command. Make the my-kube-config file the default kubeconfig.

 

파일을 기본 디렉터리로 옮긴다. 

 

14.

With the current-context set to research, we are trying to access the cluster. However something seems to be wrong. Identify and fix the issue.

Try running the kubectl get pods command and look for the error. All users certificates are stored at /etc/kubernetes/pki/users.

 

 

developer.crt. 가 아니라 dev-user.crt 로 되어있다. 

/root/.kube/config 파일을 수정하자. 

 


157. API Groups

api 버전을 확인하고 싶다면? 

master 노드 포트에 접속해서 확인가능하다. 

이렇게도 접속가능하다. 

 

api 포드에 대해 집중해보자 

쿠버네티스api 는 여러종류로 나눠진다. 

core, named api 그룹에 대해 알아보자

core api 에는 우리가 아는 중요한거 다 들어있다. 

naemd api 에는 다양한 기능들이 있다. 

 

마스터 노드 포트로 바로 접속하면 사용 가능한 api 그룹 리스트가 나온다. 

모든 리소스 출력하기

 

인증서 없이 클러스터 api 에 접속할 수 없다. 

키,인증서, ca 를 넘겨야한다. 

Kubectl Proxy 로 접속하기

프록시로 접속한후 8001 포트를 통해 api 리스트를 가져올 수 있다. ( 인증서 필요 없음) 

Kube proxy ≠ kubectl proxy

엄연히 다른거다. 

 

+ Recent posts