개요

- Kubernetes 클러스터제어 플레인작업자 노드로 구성된다.

- Control Plane Components는 클러스터의 상태를 관리하고, Node Components는 Pod와 컨테이너의 실행을 유지 관리한다.

- 애드온은 Kubernetes의 기능을 확장하며, 다양한 클러스터 관리와 모니터링 기능을 제공한다.

- Kubernetes는 다양한 환경에 맞게 아키텍처를 유연하게 조정할 수 있다.

 

1. 🗂️ Kubernetes의 핵심 구성 요소

  • Kubernetes 클러스터제어 플레인과 하나 이상의 작업자 노드(worker nodes)로 구성된다.
  • 제어 플레인(control plane)은 클러스터의 전반적인 상태를 관리하고 조정하는 역할을 한다.
  • 워커 노드Pod를 실행하고, 컨테이너의 실제 작업을 수행한다.
  • Pod는 Kubernetes에서 실행되는 기본적인 배포 단위이며, 하나 이상의 컨테이너를 포함할 수 있다.
  • 클러스터의 각 구성 요소는 서로 상호작용하며, 이를 통해 클라우드 환경에서의 컨테이너 오케스트레이션을 가능하게 한다.

-> 컨트롤 플레인은 노드들을 관리하고 실제로 파드가 작동 되는 곳은 노드(워커 노드) 이다.

2. 🗝️ Kubernetes의 Control Plane과 Node 구성 요소

  • Control Plane Components는 클러스터 전체 상태를 관리한다. 그래서 Kubernetes HTTP API를 제공하는 핵심 서버가 포함된다.
  • 모든 API 서버 데이터를 위한 일관적이고, 고가용성의 키-값 저장소(ETCD <- 매우 중요!!!)를 가진다.
  • 아직 노드에 할당되지 않은 Pod를 찾아 적합한 노드에 할당한다. 그래서 Kubernetes API 동작을 구현한다.
  • Node Components는 모든 노드에서 실행되며, 실행 중인 Pod와 Kubernetes 런타임 환경을 유지관리한다.
  • Pod가 실행 중인지 확인하고, 그들의 컨테이너도 포함된다.
  • 네트워크 규칙을 노드에서 유지하여 Kubernetes 동작을 구현한다.
  • 컨테이너 실행을 책임지는 소프트웨어가 필요하다. 그래서 추가 소프트웨어가 각 노드에 필요할 수 있다. 예를 들어, 로컬 구성 요소를 감독하기 위해 Linux 노드에서도 실행될 수 있다.

-> 위 내용과 반복되는 내용

3. 🌟 Kubernetes의 기능을 확장하는 애드온

  • 애드온(Addons)은 Kubernetes의 기능을 확장한다.
  • 클러스터 전반의 DNS 이름풀이를 제공한다.
  • 웹 인터페이스를 통한 클러스터 관리가 가능하다.
  • 컨테이너 메트릭스 수집 및 저장을 지원한다.
  • 컨테이너 로그를 중앙 로그 저장소에 저장한다.
  • 🔧 유연한 아키텍처
    • Kubernetes는 구성 요소를 배포하고 관리하는 방식에서 유연성을 제공한다.
    • 소규모 개발 환경부터 대규모 프로덕션 배포까지 다양한 요구에 맞게 아키텍처를 조정할 수 있다.
    • 각 구성 요소에 대한 자세한 정보와 다양한 구성 방법은 추가 학습이 필요하다.

-> 쿠버네티스는 addon들을 통해서 기능을 확장할 수 있고, 확장에 용이하다. 

 

 

ref

Kubernetes Components | Kubernetes

 


167. Image Security

Image

예시 여기 이미지 nginx 는 어디서 왔을까?
.
docker 레지스트리 library 에서 가져온다.

Private Repository

private 레포지토리에서 가져올 수 있다.

먼저 private-registry.io 에 로그인 해야한다. 

image 에 전체 경로를 써야한다.

쿠버네티스가 어떻게 private 레포지토리에 인증할 수 있을까? 

워커노드의 도커 런타임에 어떻게 인증을 전달할 수 있을까 ?

-> secret 을 이용한다.

파드 정의에 secret이 들어간다.


168. Practice Test - Image Security 

1. What secret type must we choose for docker registry?

docker-registry 를 사용한다. 

 

 

2. We have an application running on our cluster. Let us explore it first. What image is the application using?

nginx 알파인

 

3.  We decided to use a modified version of the application from an internal private registry. Update the image of the deployment to use a new image from myprivateregistry.com:5000

The registry is located at myprivateregistry.com:5000. Don't worry about the credentials for now. We will configure them in the upcoming steps.

image 앞에 경로를 추가

4. Are the new PODs created with the new images successfully running?

작동 안된다 credential 문제인듯 

 

5.

Create a secret object with the credentials required to access the registry.

Name: private-reg-cred
Username: dock_user
Password: dock_password
Server: myprivateregistry.com:5000
Email: dock_user@myprivateregistry.com

 

 

 

6. Configure the deployment to use credentials from the new secret to pull images from the private registry

 

deployment 에 secret 을 쓸 수 있게 하자 .

 

Pull an Image from a Private Registry | Kubernetes

 

Pull an Image from a Private Registry

This page shows how to create a Pod that uses a Secret to pull an image from a private container image registry or repository. There are many private registries in use. This task uses Docker Hub as an example registry. 🛇 This item links to a third party

kubernetes.io

 

image 밑에 imagePullsecrets 로 넣자 .

 

7. Check the status of PODs. Wait for them to be running. You have now successfully configured a Deployment to pull images from the private registry.

잘돌아간다. 

 


170. Pre-requisite - Security in Docker

컨테니어와 호스트는 같은 커널을 공유한다. 

컨테이너의 네임스페이스는 밖으로 못나가지만 호스트 단의 네임스페이스는 컨테이너도 다 볼 수 있다. 

 

컨테이너 안에서 ps 명령어로 확인하면 하나의 프로세스만 뜨지만. 

 

호스트 단에 ps 명령어로 확인하면 다 나온다.

여기서는 root 의 pid 가 다르게 나올뿐 (컨테이너에서는 pid 1 이었다.)

마찬가지로 호스트 단의 root  유저와 컨테이너의 root 유저는 다르다 .

root 유저의 권한 어마무시해

권한을 주고 싶다면 --cap-add 명령을 하면 된다 .

또는 cap-drop 으로 권한을 제거할 수 있다. 

privileged 로 모두 가능하게 할 수 있다. 

 


171. Security contexts

도커에 유저를 추가하거나 커널 기능을 주거나.

쿠버네티스도 마찬가지

 

파드레벨
컨테이너 레벨

runAsUser 또는 capabity  등 이용가능


172. Practice Test - Security Contexts

1. What is the user used to execute the sleep process within the ubuntu-sleeper pod?

In the current(default) namespace.

파드에 접속한 후 whoami

 

 

2.

Edit the pod ubuntu-sleeper to run the sleep process with user ID 1010.

Note: Only make the necessary changes. Do not modify the name or image of the pod.

 

 

3. A Pod definition file named multi-pod.yaml is given. With what user are the processes in the web container started?

The pod is created with multiple containers and security contexts defined at the Pod and Container level.

오류 인가 안뜬다??

 

1002

 

4. With what user are the processes in the sidecar container started?

The pod is created with multiple containers and security contexts defined at the Pod and Container level.

명시 안되었으니 파드 단위 1001 

 

5.

Update pod ubuntu-sleeper to run as Root user and with the SYS_TIME capability.

Note: Only make the necessary changes. Do not modify the name of the pod.

apiVersion: v1
kind: Pod
metadata:
  name: ubuntu-sleeper
  namespace: default
spec:
  containers:
  - command:
    - sleep
    - "4800"
    image: ubuntu
    name: ubuntu-sleeper
    securityContext:
      capabilities:
        add: ["SYS_TIME"]

securityContext 를 추가한다. 

 

 

6.

Now update the pod to also make use of the NET_ADMIN capability.

Note: Only make the necessary changes. Do not modify the name of the pod.

apiVersion: v1
kind: Pod
metadata:
  name: ubuntu-sleeper
  namespace: default
spec:
  containers:
  - command:
    - sleep
    - "4800"
    image: ubuntu
    name: ubuntu-sleeper
    securityContext:
      capabilities:
        add: ["SYS_TIME", "NET_ADMIN"]

net_admin 추가

 

파드 실행 중이니까 바로 수정안된다. 

파드 제거하고 수정된 경로에서 kubectl apply -f [파일명]

 


174. Network Policy

Traffic

웹서버, 백엔드 서버, db 서버 이렇게 있다.

Ingress & Egress

Ingress - 들어오는 거

Egress - 나가는 거

Network Security

노드와 파드들은 각자 ip 를 가지고 있다. 

파드들은 서로 통신 가능해야한다.

쿠버네티스는 기본적으로 파드들끼리 allow 정책을 한다. 

쿠버네티스를 예시로 들어보자. 모두 파드로 치환됨.

파드니까 모두 서로 통신 가능하다. 

네트워크 정책을 적용해서 트래픽을 통제하자

레이블을 지정한 후 적용한다.

Network Policy - Rules 

ingress 정책 

특정 포트, 파드로 통신마 허용함

Network Policy - yaml 구성

파드 셀렉터 먼저 오고 정책 타입이 들어간다. 

인그레스 관련해서 모두 영향 받음

당연히 create 명령
네트워크 정책에 영향 받는 것과 아닌 것 확인


175. Developing Network Policy

 

예로 들어보자

web 으로부터 db 접근을 막아야한다. 

db와 api 먼저 확인하자
db 입장에서 api 로부터 들어오는 ingress 만 잘관리하면 된다.

요청 받은 후 응답을 자동으로 해야하기 때문에 egress는 필요없다. 

yaml 파일 예시
네임스페이스가 필요한 경우 name 밑에 기입하자

 

특정 ns가 필요하면 matchLabels 밑에 명시

이 상황에서 podSelector 가 없다면 ?

Staging에서 들어오는 모든 트래픽이 허용된다. 

다시 api pod 로 변경

외부 백업 서버와 연결하고 싶다면 ?

ipBlock 을 추가한다. 

from 아래에선 독립적으로 조건이 적용된다.

Egress 추가하기 


176. Practice Test - Network Policy

1. How many network policies do you see in the environment?

 

We have deployed few web applications, services and network policies. Inspect the environment.

1개

 

2. What is the name of the Network Policy?

payroll-policy

 

3. Which pod is the Network Policy applied on?

payroll

 

 

4. What type of traffic is this Network Policy configured to handle?

 

ingress 만 

 

5.  What is the impact of the rule configured on this Network Policy?

internal 

 

6. What is the impact of the rule configured on this Network Policy?

internal pod can access port 8080 on payroll pod

 

7. Access the UI of these applications using the link given above the terminal.

 

8. Perform a connectivity test using the User Interface in these Applications to access the payroll-service at port 8080.

9. Perform a connectivity test using the User Interface of the Internal Application to access the external-service at port 8080.

 

10.

Create a network policy to allow traffic from the Internal application only to the payroll-service and db-service.

Use the spec given below. You might want to enable ingress traffic to the pod to test your rules in the UI.

Policy Name: internal-policy
Policy Type: Egress
Egress Allow: payroll
Payroll Port: 8080
Egress Allow: mysql
MySQL Port: 3306
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: internal-policy
  namespace: default
spec:
  podSelector:
    matchLabels:
      name: internal
  policyTypes:
  - Egress
  - Ingress
  ingress:
    - {}
  egress:
  - to:
    - podSelector:
        matchLabels:
          name: mysql
    ports:
    - protocol: TCP
      port: 3306

  - to:
    - podSelector:
        matchLabels:
          name: payroll
    ports:
    - protocol: TCP
      port: 8080

  - ports:
    - port: 53
      protocol: UDP
    - port: 53
      protocol: TCP

 


휴 드디어 그 많은 분량의  section7 security 가 끝났다.

cka 너무 멀고 먼 길이여

화이팅

 

 


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.

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

 

+ Recent posts