Slide 1

Slide 1 text

Kubernetes Security Oracle Cloud Hangout Cafe Season 5 #3 Yutaka Ichikawa Solutions Architect Oracle Corporation Japan MAR 09, 2022

Slide 2

Slide 2 text

Profile Copyright © 2022, Oracle and/or its affiliates 2 Name • Yutaka Ichikawa/市川 豊 Belong • Solutions Architect Role • Principal Cloud Solution Engineer SNS • Twitter/GitHub/Qiita:cyberblack28 Blog • https://cyberblack28.hatenablog.com/ Materials • https://speakerdeck.com/cyberblack28/ Community • CloudNative Days Tokyo #cndt #o11y2022 Certified • Certified Kubernetes Administrator • Certified Kubernetes Application Developer • Certified Kubernetes Security Specialist • Kubernetes and Cloud Native Associate Publications New 3/11 オンライン・参加費無料 https://event.cloudnativedays.jp/o11y2022/

Slide 3

Slide 3 text

Agenda CKS • CKSとは? • CKSの範囲 • CKS対策 Kubernetes Security • Cluster Setup • NetworkPolicy • CIS Benchmark • Cluster Hardening • RBAC • System Hardening • AppArmor • Minimize Microservice Vulnerabilities • SecurityContext • Open Policy Agent • PodSecurityPolicy • Container Runtime Sandboxes • Supply Chain Security • Trivy • Monitoring, Logging and Runtime Security • Falco • 参考資料 3 Copyright © 2022, Oracle and/or its affiliates

Slide 4

Slide 4 text

CKS CKSとは? CKSの範囲 CKS対策 4 Copyright © 2022, Oracle and/or its affiliates

Slide 5

Slide 5 text

CKSとは? 5 Copyright © 2022, Oracle and/or its affiliates

Slide 6

Slide 6 text

CKS 6 CKSとは? Certified Kubernetes Security Specialist コンテナベースのアプリケーションとKubernetesプラットフォームのビルド、デプロイ、ランタイム時のセキュリティ を確保する幅広いベストプラクティスの実行能力を証明する認定試験 Copyright © 2022, Oracle and/or its affiliates

Slide 7

Slide 7 text

CKS 7 CKSとは? 試験概要 内容 試験時間 2時間 問題数 15-20問(自分が受験した時は15問) 合格基準 67%以上 受験条件 CKAに合格していること 受験形式 オンライン受験・ハンズオン形式 有効期間 2年間 受験料 $375 Copyright © 2022, Oracle and/or its affiliates

Slide 8

Slide 8 text

CKSの試験範囲 8 Copyright © 2022, Oracle and/or its affiliates

Slide 9

Slide 9 text

CKS 9 CKSの試験範囲 カテゴリ/出題割合 内容 Cluster Setup/10% • Network Policyによるアクセス制限 • CISベンチマークに基いたセキュアなKubernetes設定 • SSLによるセキュアなIngress利用など Cluster Hardening/10% • Kubernetes APIのアクセス制限/RBAC設定 • Kubernetesクラスタアップデートなど System Hardening/10% • カーネルのセキュリティ機能利用(AppArmor・seccomp) • ホストOSにおける攻撃対象の縮小など Minimize Microservice Vulnerabilities/20% • コンテナへの適切な権限付与(Pod Security Policy・Open Policy Agent・ Security Context) • サンドボックス化されたコンテナランタイム(gVisor・Kata Containers) • mTLSによるPod間通信の暗号化など Supply Chain Security/20% • ベースイメージのフットプリント最小化(Multi-Stage Builds) • イメージ脆弱性スキャン(Trivy)など Monitoring, Logging and Runtime Security/20% • Syscallやファイルアクセスに基づく振る舞い検知(Falco) • コンテナランタイムの不変性保証 • Audit ログの設定・確認方法など https://training.linuxfoundation.org/certification/certified-kubernetes-security-specialist/ Copyright © 2022, Oracle and/or its affiliates

Slide 10

Slide 10 text

CKS 10 CKSの試験範囲 Documentation URL Kubernetes Documentation • https://kubernetes.io/docs/ • https://github.com/kubernetes/ • https://kubernetes.io/blog/ Trivy Documentation • https://aquasecurity.github.io/trivy/ Sysdig Documentation • https://docs.sysdig.com/ Falco Documentation • https://falco.org/docs/ App Armor Documentation • https://gitlab.com/apparmor/apparmor/-/wikis/Documentation 以下ドキュメントについては、試験中参照可 https://docs.linuxfoundation.org/tc-docs/certification/important-instructions-cks Copyright © 2022, Oracle and/or its affiliates

Slide 11

Slide 11 text

CKS対策 11 Copyright © 2022, Oracle and/or its affiliates

Slide 12

Slide 12 text

CKS 12 CKS対策 Kubernetes CKS 2021 Complete Course - Theory - Practice https://www.udemy.com/course/certified-kubernetes-security-specialist/ Docker/Kubernetes 開発・運用のためのセキュリティ実践ガイド https://book.mynavi.jp/ec/products/detail/id=114099 以下の教材とKubernetes公式ドキュメントを利用 Copyright © 2022, Oracle and/or its affiliates

Slide 13

Slide 13 text

CKS 13 CKS対策 Kubernetesコントロールプレーンコンポーネントの理解も必要、kubeadmでクラスタを構築して対策 Copyright © 2022, Oracle and/or its affiliates

Slide 14

Slide 14 text

CKS 14 CKS対策 Copyright © 2022, Oracle and/or its affiliates Virtual Machine Virtual Machine k8s-control-plane k8s-node Item Spec Shape VM.Standard.A1.Flex CPU Ampere MEM (control plane) 12GB MEM (node/manage) 6GB OS Ubuntu 20.04 ContainerRuntime Containerd CNI Calico kubectl ssh Virtual Machine manage OCI Always-Free 環境で構築できます。 User Demo Environment https://github.com/oracle-japan/ochacafe-s5-3

Slide 15

Slide 15 text

Kubernetes Security Cluster Setup Cluster Hardening System Hardening Minimize Microservice Vulnerabilities Supply Chain Security Monitoring Logging and Runtime Security 16 Copyright © 2022, Oracle and/or its affiliates

Slide 16

Slide 16 text

Cluster Setup NetworkPolicy CIS Benchmark 17 Copyright © 2022, Oracle and/or its affiliates

Slide 17

Slide 17 text

NetworkPolicy 18 NetworkPolicyは、Kubernetesクラスタ内における、Pod同士が通信するトラフィックルールを規定できる仕組み Namespace: A Namespace: B Namespace: A Namespace: B Pod間の通信制御 Namespaceを跨いだ Pod間の通信制御 Copyright © 2022, Oracle and/or its affiliates

Slide 18

Slide 18 text

NetworkPolicy 19 Weave Net NetworkPolicyを利用するには、NetworkPolicyに対応したネットワークプラグイン(CNIプラグイン)が必要。 Copyright © 2022, Oracle and/or its affiliates

Slide 19

Slide 19 text

NetworkPolicy 20 全ての送受信トラフィックを許可 全ての送受信トラフィックを拒否 Copyright © 2022, Oracle and/or its affiliates apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: all-deny-networkpolicy spec: podSelector: {} policyTypes: - Ingress - Egress apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: all-allow-networkpolicy spec: podSelector: {} egress: - {} ingress: - {} policyTypes: - Ingress - Egress

Slide 20

Slide 20 text

NetworkPolicy 21 apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: example-networkpolicy spec: podSelector: # 設定対象Podのラベルセレクタを定義 policyTypes: - Ingress # Ingressルールを指定する場合明示 - Egress # Egressルールを指定する場合明示 ingress: - from: # Ingressルールを定義 ports: # 許可する受信ポート番号とプロトコルを定義 egress: - to: # Egressルールを定義 ports: # 許可する宛先ポート番号とプロトコルを定義 IngressとEgressの各ルールの指定方法は同じ形式 Policy Ingress Rule Egress Rule podSelector 特定のPodからの通信を許可 特定のPodへの通信を許可 namespaceSelector 特定のNamespace上のPodか らの通信を許可 特定のNamespace上の Podへの通信を許可 ipBlock 特定のCIDR(IP)からの通信を 許可 特定のCIDR(IP)への通信を 許可 • podSelector:特定のPodからの通信を制御するポリシー • namespaceSelector:特定のNamespace上のPodか らの通信を制御するポリシー • ipBlock:特定のCIDRからの通信を制御するポリシー Copyright © 2022, Oracle and/or its affiliates

Slide 21

Slide 21 text

NetworkPolicy 22 https://kubernetes.io/docs/concepts/services-networking/network-policies/ サンプルマニフェスト 実際の試験では、サンプルマニフェストを利用して、 問題内容のマニフェストを作成して適用 Copyright © 2022, Oracle and/or its affiliates

Slide 22

Slide 22 text

NetworkPolicy 23 ホワイトリストとブラックリスト • ホワイトリスト • ブラックリスト 予め全てのトラフィックを遮断、特定のトラフィックのみ許可する形式 予め全てのトラフィックを許可、特定のトラフィックのみ遮断する形式 Copyright © 2022, Oracle and/or its affiliates

Slide 23

Slide 23 text

NetworkPolicy 24 Namespace: default Namespace: test app: pod1 app: pod2 app: pod3 app: pod4 1.全ての送信トラフィックを許可、受信トラフィックは拒否 上記マニフェストを各Namespaceに適用 egress-only-allow-networkpolicy.yaml 192.168.173.129 192.168.173.130 192.168.173.132 192.168.173.131 Copyright © 2022, Oracle and/or its affiliates apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: egress-only-allow-networkpolicy spec: podSelector: {} egress: - {} policyTypes: - Ingress manage

Slide 24

Slide 24 text

NetworkPolicy 25 Namespace: default Namespace: test app: pod1 app: pod2 app: pod3 app: pod4 sp-pod-allow-networkpolicy.yaml 2.「app: pod1」から「app: pod2」のみ受信許可 Copyright © 2022, Oracle and/or its affiliates apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: sp-pod-allow-networkpolicy namespace: default spec: podSelector: matchLabels: app: pod2 policyTypes: - Ingress ingress: - from: - podSelector: matchLabels: app: pod1 ports: - protocol: TCP port: 80 192.168.173.129 192.168.173.130 192.168.173.132 192.168.173.131 manage

Slide 25

Slide 25 text

NetworkPolicy 26 Namespace: default Namespace: test app: pod1 app: pod2 app: pod3 app: pod4 3.Namespace defaultのPodから「app: pod3」のみ受信許可 sp-namespace-allow-networkpolicy.yaml Copyright © 2022, Oracle and/or its affiliates apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: sp-namespace-allow-networkpolicy namespace: test spec: podSelector: matchLabels: app: pod3 policyTypes: - Ingress ingress: - from: - namespaceSelector: matchLabels: kubernetes.io/metadata.name: default ports: - protocol: TCP port: 80 192.168.173.129 192.168.173.130 192.168.173.132 192.168.173.131 manage

Slide 26

Slide 26 text

apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: sp-ip-allow-networkpolicy namespace: test spec: podSelector: matchLabels: app: pod3 policyTypes: - Ingress ingress: - from: - ipBlock: cidr: 192.168.173.130/32 ports: - protocol: TCP port: 80 NetworkPolicy Copyright © 2022, Oracle and/or its affiliates 27 Namespace: default Namespace: test app: pod1 app: pod2 app: pod3 app: pod4 sp-ip-allow-networkpolicy.yaml 4. 特定のIP Podから「app: pod3」のみ受信許可 192.168.173.129 192.168.173.130 192.168.173.132 192.168.173.131 manage

Slide 27

Slide 27 text

CIS Benchmark 28 CIS (Center for Internet Security)、セキュリティにおけるベストプラクティスの推奨事項のベンチマークを公開 Copyright © 2022, Oracle and/or its affiliates CIS Kubernetes Benchmark Kubernetes におけるセキュリティを強化するためのガイドラインが定められている 1. Control Plane Components 2. etcd 3. Control Plane Configurration 4. Worker Nodes 5. Policies https://www.cisecurity.org/benchmark/kubernetes

Slide 28

Slide 28 text

CIS Benchmark 29 Copyright © 2022, Oracle and/or its affiliates CIS Kubernetes Benchmark OSSだけでなく、OKEをはじめとするマネージドサービス向けのベンチマークも公開されている

Slide 29

Slide 29 text

CIS Benchmark 30 Copyright © 2022, Oracle and/or its affiliates kube-benchとは? • CIS Kubernetes Benchmarkの推奨事項に準拠しているかをチェックできるアプリケーション • Aqua Security社がOSSとして公開している • 導入方法としては、対象のKubernetesクラスタ上でPod/Jobでの実行が簡単 https://github.com/aquasecurity/kube-bench

Slide 30

Slide 30 text

CIS Benchmark 31 Copyright © 2022, Oracle and/or its affiliates kube-benchの使用例 2.kube-benchの実行 1.「job-master.yaml」の作成 3.結果の確認 公式のGitHubで公開されているYAMLを一部編集 作成したYAMLファイルを適用 推奨事項に準拠しているか確認

Slide 31

Slide 31 text

CIS Benchmark 32 Copyright © 2022, Oracle and/or its affiliates kube-benchの使用例 1.「job-master.yaml」の作成 # cat ochacafe-s5-3/kube-bench/job-master.yaml manage apiVersion: batch/v1 kind: Job metadata: name: kube-bench-master spec: (省略) containers: - name: kube-bench image: aquasec/kube-bench:latest command: [“kube-bench”, “run”, “--targets”, “master”] ⇒ command: [“kube-bench”] #変更 args: [“--version=1.23”] #追加 (省略) https://github.com/aquasecurity/kube-bench/blob/main/job-master.yaml

Slide 32

Slide 32 text

CIS Benchmark 33 Copyright © 2022, Oracle and/or its affiliates kube-benchの使用例 2. kube-bench の実行 # kubectl apply -f job-master.yaml manage job.batch/kube-bench-master created # kubectl get pods NAME READY STATUS RESTARTS AGE kube-bench-master-kvjt7 0/1 Completed 0 64m STATUS が Completed になるまで待つ

Slide 33

Slide 33 text

CIS Benchmark 34 Copyright © 2022, Oracle and/or its affiliates kube-benchの使用例 3.結果の確認 manage # kubectl logs kube-bench-master-kvjt7 (省略) [FAIL] 1.2.15 Ensure that the admission control plugin PodSecurityPolicy is set (Automated) (省略) == Remediations master == (省略) 1.2.15 Follow the documentation and create Pod Security Policy objects as per your environment. Then, edit the API server pod specification file /etc/kubernetes/manifests/kube-apiserver.yaml on the master node and set the --enable-admission-plugins parameter to a value that includes PodSecurityPolicy: --enable-admission-plugins=...,PodSecurityPolicy,... Then restart the API Server. (省略) [FAIL]については、設定方法まで出力されるの で、その内容に従って実際に設定を行う この場合では、Control-Planeノードにある 「/etc/kubernetes/manifests/kube- apiserver.yaml」の「--enable-admission- plugins」の箇所に「PodSecurityPolicy」を追 加する。

Slide 34

Slide 34 text

Cluster Hardening RBAC 35 Copyright © 2022, Oracle and/or its affiliates

Slide 35

Slide 35 text

RBAC 36 Copyright © 2022, Oracle and/or its affiliates Kubernetesにおける認証/認可 ユーザがKubernetesを操作する場合、KubernetesのAPIサーバに対してリクエストを送信、以下の3フェーズを経由し てリソース登録。 Authentication Authorization Admission Control リクエストを送信したユー ザの認証情報が、有効 なものか確認 送信したユーザのリクエス トが許可されているかを 確認 リクエストに対して、より 柔軟なチェックや強制的 な変更を担う

Slide 36

Slide 36 text

RBAC 37 Copyright © 2022, Oracle and/or its affiliates Kubernetesにおけるアカウントの種類 ServiceAccount UserAccount Kubernetesに関連するアカウントは、ServiceAccountとUserAccountの2種類。 • Kubernetesが管理するアカウント • Namespaceに紐づく • Podで実行されるプロセスに割り当てられる • Kubernetesが管理しない外部アカウント • Namespaceには紐づかない • クラウドプロバイダーのアカウントやLDAP管理のアカウント

Slide 37

Slide 37 text

RBAC 38 Copyright © 2022, Oracle and/or its affiliates Kubernetesにおける認可 Role-based Access Control(RBAC) Kubernetesの認可方法には、Attribute-based Access Control(ABAC)とRole-based Access Control (RBAC)の2種類あり、主にRBACが利用されている。 RBACでは、RoleとRoleBindingの2種類のリソースを利用して権限管理を行う。 • Role 各リソースに対する権限を定義 (例)Podに対するDelete、DeploymentのUpdateなど • RoleBinding 定義されたRoleの権限をどのアカウント(ServiceAccountなど)に付与するかを指定

Slide 38

Slide 38 text

RBAC 39 Copyright © 2022, Oracle and/or its affiliates Role-based Access Control(RBAC) Role Role Role RoleBinding RoleBinding User User User Userに対して Roleを紐づける 許可項目 Service Accountなど Podの一覧表示や Deploymentの作 成など

Slide 39

Slide 39 text

RBAC 40 Copyright © 2022, Oracle and/or its affiliates 2種類のリソーススコープ • Namespace-scope Namespace-scopeとCluster-scopeのリソースを対象とした許可設定が可能。 RoleとRoleBinding • Cluster-scope ClusterRoleとClusterRoleBinding 主なリソース:Pod、Deployment、Service、ServiceAccount、PersistentVolumeClaimなど 主なリソース:PersistentVolume、Namespace、Nodeなど

Slide 40

Slide 40 text

RBAC 41 Copyright © 2022, Oracle and/or its affiliates ClusterRoleとClusterRoleBinding Cluster-scopeのリソースを対象とする場合、ClusterRoleとClusterRoleBindingを利用する Cluster Namespace A Namesapce B RoleBinding RoleBinding Role User User User ClusterRoleBinding ClusterRole

Slide 41

Slide 41 text

RBAC 42 Copyright © 2022, Oracle and/or its affiliates • 全てのNamespaceのリソースを対象 ClusterRoleとClusterRoleBindingは、全てのNamespaceに対して権限が付与されるため、Namespaceを横断し て権限管理ができる。 ClusterRoleとClusterRoleBindingの用途 (例)クラスタ管理者やSREに向けた権限などで利用可能 • 全てのNamespaceで共通利用するRole ClusterRoleはクラスタを横断してポリシーを定義できるので、各クラスタのNamespaceからRoleBindingで ClusterRoleを参照可能。 (例)クラスタ管理者が共通のポリシーを各クラスタのNamespaceに向けて提供可能

Slide 42

Slide 42 text

RBAC 43 Copyright © 2022, Oracle and/or its affiliates マニフェストを作成して適用する例 Role ClusterRole 「$ Kubectl get pods」による一 覧取得(list)はOK、それ以外 はNG 「$ Kubectl get namespaces」 による一覧取得(list)はOK、そ れ以外はNG RoleBinding ClusterRoleBinding pod-role を pod-sa に紐づける namespace は default namespace-clusterrole を namespace-sa に紐づける namespace は default pod-sa namespace-sa pod-role namespace- clusterrole pod-rolebinding namespace- clusterrolebinding ServiceAccount ServiceAccount

Slide 43

Slide 43 text

apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: name: pod-role rules: - apiGroups: - "" resources: - pods verbs: - list RBAC 44 Copyright © 2022, Oracle and/or its affiliates RoleとClusterRoleのマニフェスト 「apiGroups」、「resources」、「verbs」の3つを指定し、 「apiGroups」、「resources」で指定するリソースに対して、 「verbs」の権限で管理する。RoleとClusterRoleの指定方法は基本的に同じ。 # kubectl create role pod-role --resource pods --verb list -o yaml --dry-run=client > pod-role.yaml 空文字指定の場合、Core apiGroupsが指定される。 Namespace-scopeのリソースを対象、ClusterRoleの場合は Cluster-scopeのリソースも設定可能 種別 内容 * 全ての処理 create 作成 delete 削除 get 取得 list 一覧取得 patch 一部変更 update 更新 watch 変更の監視 manage

Slide 44

Slide 44 text

apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: namespace-clusterrole rules: - apiGroups: - "" resources: - namespaces verbs: - list RBAC 45 Copyright © 2022, Oracle and/or its affiliates RoleとClusterRoleのマニフェスト # kubectl create clusterrole namespace-clusterrole --resource namespaces --verb list -o yaml --dry-run=client > namespace-clusterrole.yaml 空文字指定の場合、Core apiGroupsが指定される。 Namespace-scopeのリソースを対象、ClusterRoleの場合は Cluster-scopeのリソースも設定可能 種別 内容 * 全ての処理 create 作成 delete 削除 get 取得 list 一覧取得 patch 一部変更 update 更新 watch 変更の監視 RoleとClusterRoleの指定方法は基本的に同じ。 manage

Slide 45

Slide 45 text

apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: pod-rolebinding namespace: default roleRef: apiGroup: rbac.authorization.k8s.io kind: Role name: pod-role subjects: - kind: ServiceAccount name: pod-sa namespace: default RBAC 46 Copyright © 2022, Oracle and/or its affiliates RoleBindingとClusterRoleBindingのマニフェスト 「roleRef」で紐づけるRole指定、 「subjects」でRoleに紐づける UserやServiceAccountを指定。 # kubectl create rolebinding pod-rolebinding --role pod-role --serviceaccount default:pod-sa -o yaml --dry-run=client > pod- rolebinding.yaml 「roleRef」に紐づけるRoleを指定。 1RoleBindingに対 して1Role、 「subjects」には複 数のUserや ServiceAccountを 指定可能。 manage

Slide 46

Slide 46 text

apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: namespace-clusterrolebinding roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: namespace-clusterrole subjects: - kind: ServiceAccount name: namespace-sa namespace: default RBAC 47 Copyright © 2022, Oracle and/or its affiliates RoleBindingとClusterRoleBindingのマニフェスト 「roleRef」で紐づける ClusterRoleを指定。 「subjects」でClusterRoleに紐 づけるUserやServiceAccount を指定。 # kubectl create clusterrolebinding namespace-clusterrolebinding --clusterrole namespace-clusterrole --serviceaccount default:namespace-sa -o yaml --dry-run=client > namespace-clusterrolebinding.yaml 「roleRef」に紐づける ClusterRoleを指定。 1ClusterRoleBindi ngに対して 1ClusterRole、 「subjects」には複 数のUserや ServiceAccountを 指定可能。 manage

Slide 47

Slide 47 text

RBAC 48 Copyright © 2022, Oracle and/or its affiliates 各アカウントで動作を確認 # kubectl --as=system:serviceaccount:default:pod-sa get pods manage No resources found in default namespace. # kubectl --as=system:serviceaccount:default:pod-sa run nginx --image=nginx Error from server (Forbidden): pods is forbidden: User "system:serviceaccount:default:pod-sa" cannot create resource "pods" in API group "" in the namespace "default" pod-saサービスアカウントでPodの一覧を取得 pod-saサービスアカウントでPodを作成しようと試みる

Slide 48

Slide 48 text

RBAC 49 Copyright © 2022, Oracle and/or its affiliates 各アカウントで動作を確認 # kubectl --as=system:serviceaccount:default:namespace-sa create namespace mynamespace manage Error from server (Forbidden): namespaces is forbidden: User "system:serviceaccount:default:namespace-sa" cannot create resource "namespaces" in API group "" at the cluster scope namespace-saサービスアカウントでNamespaceを作成しようと試みる # kubectl --as=system:serviceaccount:default:namespace-sa get namespaces NAME STATUS AGE calico-apiserver Active 4h15m calico-system Active 4h16m default Active 4h18m kube-node-lease Active 4h18m kube-public Active 4h18m kube-system Active 4h18m tigera-operator Active 4h16m namespace-saサービスアカウントでNamespaceの一覧を取得

Slide 49

Slide 49 text

System Hardening AppArmor 50 Copyright © 2022, Oracle and/or its affiliates

Slide 50

Slide 50 text

AppArmor 51 Copyright © 2022, Oracle and/or its affiliates AppArmorとは? • Linuxカーネルのセキュリティモジュール • プロファイルを作成して、読み取り、書き込み、プログラムの実行やファイルシステムのマウントなど、システム機能を制 限可能 • コンテナに許可することを制限可能 (例)bind-mountしたディレクトリ全体ではなく、個別のファイルやディレクトリに対して権限(RW)を設定可能。 Container Host Container bind-mount 権限設定可能

Slide 51

Slide 51 text

AppArmor 52 Copyright © 2022, Oracle and/or its affiliates AppArmorの使用例 Kubernetes Node AppArmor Profile Deny/** w Kubeletが AppArmorの Profileを読み込む Profileにある制限に反する実行要求は実行不可 $ touch /tmp/test AppArmorのProfileを使用するアノテーションを定義したマ ニフェストからPod作成 manifest AppArmorの Profileを作成と登録 ④ ③ ⑤ ※Kubernetes Version 1.4以上であること ※Node LinuxでAppArmor Kernel moduleが有効であること ※ContainerRuntimeがAppArmorをサポートしていること ※参考:https://kubernetes.io/ja/docs/tutorials/clusters/apparmor/ ② AppArmorが有効かを確認 ①

Slide 52

Slide 52 text

AppArmor 53 Copyright © 2022, Oracle and/or its affiliates AppArmorの使用例 #include profile k8s-apparmor-example-deny-write flags=(attach_disconnected) { #include file, # Deny all file writes. deny /** w, } 2.Nodeに接続して、以下のAppArmor Profileを作成 ファイル書き込みを拒否するAppArmor Profile(/etc/apparmor.d/k8s-apparmor-example-deny-write) 1.Nodeに接続して、apparmorが有効か確認 # cat /sys/module/apparmor/parameters/enabled Y 「Y」と表示されれば有効状態 # vim /etc/apparmor.d/k8s-apparmor-example-deny-write

Slide 53

Slide 53 text

AppArmor 54 Copyright © 2022, Oracle and/or its affiliates AppArmorの使用例 apiVersion: v1 kind: Pod metadata: name: hello-apparmor annotations: # Tell Kubernetes to apply the AppArmor profile "k8s-apparmor-example-deny-write". # Note that this is ignored if the Kubernetes node is not running version 1.4 or greater. container.apparmor.security.beta.kubernetes.io/hello: localhost/k8s-apparmor-example-deny-write spec: containers: - name: hello image: busybox command: [ "sh", "-c", "echo 'Hello AppArmor!' && sleep 1h" ] 4.AppArmor Profileのアノテーションを定義したマニフェストの作成 マニフェスト(hello-apparmor.yaml) ※Nodeが複数の場合、それぞれに適用する。セットアップ方法は以下を参考。 https://kubernetes.io/ja/docs/tutorials/clusters/apparmor/#setting-up-nodes-with-profiles 3.apparmor_parserコマンドを実行して、AppArmorプロファイルを登録 # apparmor_parser -q /etc/apparmor.d/k8s-apparmor-example-deny-write manage

Slide 54

Slide 54 text

AppArmor 55 Copyright © 2022, Oracle and/or its affiliates AppArmorの使用例 # kubectl exec hello-apparmor -- touch /tmp/test コンテナがこのプロファイルで実際に実行されていることを確認するために、コンテナの「/proc/attr/」をチェック。 touch: /tmp/file: Permission denied command terminated with exit code 1 # kubectl exec hello-apparmor -- cat /proc/1/attr/current k8s-apparmor-example-deny-write (enforce) 6.ファイルを書き込みによる動作確認 ※プロファイルをannotationに設定せずに起動した場合は、「/tmp/test」は作成される 5.マニフェスト適用 # kubectl ochacafe-s5-3/seccomp/hello-apparomor.yaml pod/hello-apparmor create manage

Slide 55

Slide 55 text

seccomp 56 Copyright © 2022, Oracle and/or its affiliates seccompとは? • seccomp = Secure Computing Mode • Linuxカーネルのセキュリティモジュール • プロファイルを作成して、コンテナが呼び出せるシステムコール(プロセス)を制限。 • 不要なシステムコールを制限することで、カーネルの脆弱性を狙った攻撃を防ぐ。 Container Host seccomp profile { "defaultAction": "SCMP_ACT_ALLOW", "syscalls": [ { "names": ["chmod","fchmodat","chmodat"], "action": "SCMP_ACT_ERRNO" } ] } prohibit-chmod.json xxx Container $ chmod 777 xxx $ docker run --security-opt seccomp=prohibit-chmod.json ubuntu:21.10 権限設定不可

Slide 56

Slide 56 text

seccomp 57 Copyright © 2022, Oracle and/or its affiliates seccopmの使用例 Kubernetes Node seccomp { "defaultAction": "SCMP_ACT_ALLOW", "syscalls": [ { "names": [“mkdir",“mkdirat"], "action": "SCMP_ACT_ERRNO" } ] } $ mkdir test mkdir: cannot create directory 'test': Operation not permitted /var/lib/kubelet/seccomp/pro files/prohibit-mkdir seccompが有効か を確認 ① seccompのProfile を作成 ② Profileを指定したマニフェストを作成と適用 ③ ④ manifest mkdirを実行してNGを確認 ⑤

Slide 57

Slide 57 text

seccomp 58 Copyright © 2022, Oracle and/or its affiliates seccompの使用例 # grep CONFIG_SECCOMP= /boot/config-$(uname -r) 1.Nodeに接続して、seccompが有効か確認 「CONFIG_SECCOMP=y」と表示されれば有効状態 2.seccompのprofileを作成 # mkdir -p /var/lib/kubelet/seccomp/profiles $ vim /var/lib/kubelet/seccomp/profiles/prohibit-mkdir.json { "defaultAction": "SCMP_ACT_ALLOW", "syscalls": [ { "names": [“mkdir",“mkdirat"], "action": "SCMP_ACT_ERRNO" } ] } CONFIG_SECCOMP=y

Slide 58

Slide 58 text

seccomp 59 Copyright © 2022, Oracle and/or its affiliates seccompの使用例 # cat ochacafe-s5-3/seccomp/prohibit-mkdir.yaml 3.Profileを指定したマニフェストを作成 apiVersion: v1 kind: Pod metadata: name: prohibit-mkdir spec: securityContext: seccompProfile: type: Localhost localhostProfile: profiles/prohibit-mkdir containers: - name: ubuntu image: ubuntu:21.10 command: - sleep - infinity • locahostoProfile:Node上の 「/var/lib/kubelet/seccomp」ディレクトリ内のファイルを Profileとして指定 ※Kubernetes1.19以前はannotationで指定、1.19以降はsecurityContextで指定 • RuntimeDefault:CRIランタイムのデフォルトプロファイル指 定 • unconfined:seccomp不使用(デフォルト) manage

Slide 59

Slide 59 text

seccomp 60 Copyright © 2022, Oracle and/or its affiliates seccompの使用例 # kubectl apply -f ochacafe-s5-3/seccomp/prohibit-mkdir.yaml 4.マニフェストを適用 pod/prohibit-mkdir created # kubectl get pods NAME READY STATUS RESTARTS AGE prohibit-mkdir 1/1 Running 0 9s # kubectl exec -it prohibit-mkdir -- mkdir test 5.挙動確認 mkdir: cannot create directory 'test': Operation not permitted command terminated with exit code 1 manage

Slide 60

Slide 60 text

seccomp 61 Copyright © 2022, Oracle and/or its affiliates seccompの使用例 ホワイトリストでProfileをカスタマイズして作ることは、セキュリティを高められるが運用の煩雑さにつながる Kubernetes v1.22からalphaとして SeccompDefault という機能が追加され、PodのSpecでprofileを指定しなかっ た場合に RuntimeDefaultでコンテナを動かすことが可能 https://qiita.com/uesyn/items/3fc1b25eafa0939aebb8 ある程度コンテナアプリケーションで利用しないようなsyscallを制限したProfile(RuntimeDefault)を利用

Slide 61

Slide 61 text

Minimize Microservice Vulnerabilities SecurityContext Open Policy Agent PodSecurityPolicy Container Runtime Sandboxes 62 Copyright © 2022, Oracle and/or its affiliates

Slide 62

Slide 62 text

SecurityContext 63 Copyright © 2022, Oracle and/or its affiliates SecurityContextとは? SecurityContextは、PodまたはContainerの特権とアクセス制御の設定 SecurityContext for Container(SecurityContext) Pod Container SecurityContext 設定項目 概要 privileged 特権コンテナ実行 capabilities Capabilitiesの追加/削除 allowPrivilegeEscalation コンテナ実行時に親プロセス以上の権限を与えるか制御 readOnlyRootFilesystem RootファイルシステムをReadOnlyとするかの制御 runAsUser 実行するユーザ runAsGroup 実行するグループ runAsNonRoot rootでの実行を拒否 seLinuxOptions コンテナで使用するSELinuxオプション seccompProfile コンテナで使用するseccompオプション windowsOptions コンテナ(windows)で使用するWindows固有の設定 https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#securitycontext-v1-core 個々のContainerに対するセキュリティ設定

Slide 63

Slide 63 text

SecurityContext 64 Copyright © 2022, Oracle and/or its affiliates SecurityContext for Pod(PodSecurityContext) Pod内すべてのコンテナに対するセキュリティ設定 Pod Container PodSecurityContext Container 設定項目 概要 privileged Podの特権実行 readOnlyRootFilesystem RootファイルシステムをReadOnlyとするかの制御 runAsUser 実行するユーザ runAsGroup 実行するグループ runAsNonRoot rootでの実行を拒否 fsGroup ファイルシステムのグループ指定 runtimeClass Podで許可するruntimeClassを指定 supplementalGroups プライマリGIDに追加付与するGIDリストを指定 https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#podsecuritypolicy-v1beta1-policy

Slide 64

Slide 64 text

SecurityContext 65 Copyright © 2022, Oracle and/or its affiliates manifest SecurityContext PodSecurityContext apiVersion: v1 kind: Pod metadata: name: container-sc spec: containers: - name: nginx-container image: nginx:1.21 securityContext: runAsNonRoot: true どちらとも結果としては、runAsNonRootによりNginx Podは作成されない。 apiVersion: v1 kind: Pod metadata: name: pod-sc spec: securityContext: runAsNonRoot: true containers: - name: nginx-container image: nginx:1.21 manage

Slide 65

Slide 65 text

SecurityContext 66 Copyright © 2022, Oracle and/or its affiliates manifest Podと同様のSecurityContextが指定した場合は、ContainerのSecurityContextが優先される。 apiVersion: v1 kind: Pod metadata: name: both-test spec: securityContext: runAsUser: 1000 containers: - name: ubuntu image: ubuntu:21.10 securityContext: runAsUser: 1001 command: - sleep - infinity manage

Slide 66

Slide 66 text

Open Policy Agent 67 Copyright © 2022, Oracle and/or its affiliates ポリシーチェック Kubernetesのすべてのリソースは、マニフェストに記述して登録。そのマニフェストの内容が正しいか、許可できるものかを チェックしてセキュリティを高める。 マニフェスト $ kubectl apply Check

Slide 67

Slide 67 text

68 Copyright © 2021, Oracle and/or its affiliates Gatekeeperというツールを用いてKubernetesクラスタ登録時にマニフェストチェックを行う方法が利用され、ポリシー チェックにOpen Policy Agentが利用されている。 Gatekeeper Check Open Policy Agent Gatekeeper & Open Policy Agent マニフェスト $ kubectl apply

Slide 68

Slide 68 text

69 Copyright © 2021, Oracle and/or its affiliates • 軽量で汎用性のあるOSSのポリシーエンジン • Regoという言語でポリシーを記述してルールを定義 • Kubernetes専用というわけではなく、YAML、JSONなど構造化データのポリシーエンジン • CNCFのGraduationプロジェクト Open Policy Agent Open Policy Agent https://github.com/open-policy-agent/opa

Slide 69

Slide 69 text

70 Copyright © 2021, Oracle and/or its affiliates APIにDataを送信する(Query)と、Policyを参照してDataを評価し て結果(Decision)を返す仕組み。 OPA公式ドキュメント: https://www.openpolicyagent.org/docs/latest/ Open Policy Agent Open Policy Agent

Slide 70

Slide 70 text

71 Copyright © 2021, Oracle and/or its affiliates Gatekeeperは、Kubernetesの認証認可フローの拡張機能であるAdmission Controlから外部Webhookサーバとし てチェック依頼を受けて、OPAの定義でチェックしてリソース登録の許可/拒否を返す仕組み。 マニフェスト ① $ kubectl apply ②リソース作成・変更リクエスト の許可チェック(Admission Request) Gatekeeper ③ Regoの定義でポリシーチェック ④ 許可/拒否(Admission Response) ⑤ 許可であれば登録 Open Policy Agent Gatekeeper

Slide 71

Slide 71 text

72 Copyright © 2021, Oracle and/or its affiliates Open Policy Agent Gatekeeper & Open Policy Agent 使用例 1. Gatekeeper インストール 2. ConstraintTemplateの作成と適用 3. latestタグを使用したマニフェストを適用してNG確認

Slide 72

Slide 72 text

73 Copyright © 2021, Oracle and/or its affiliates Open Policy Agent Gatekeeper & Open Policy Agent 使用例 1. Gatekeeper インストール # kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/v3.7.1/deploy/gatekeeper.yaml OKE # cat ochacafe-s5-3/opa/constrainttemplate.yaml 2. ConstraintTemplateの作成と適用 kind: ConstraintTemplate metadata: name: notlatestimage spec: crd: spec: names: kind: NotLatestImage targets: - target: admission.k8s.gatekeeper.sh rego: | package notlatestimage violation[{"msg": msg}]{ input.review.object.kind == "Pod" imagetag := input.review.object.spec.containers[_].image endswith(imagetag,"latest") msg := "Can't use image of latest tag !!" } Regoでルールを記述 コンテナイメージのタグにlatestがある場合は以下の メッセージを返す。 「Can't use image of latest tag !!」

Slide 73

Slide 73 text

74 Copyright © 2021, Oracle and/or its affiliates Open Policy Agent Gatekeeper & Open Policy Agent 使用例 OKE cat ochacafe-s5-3/opa/constraints.yaml apiVersion: constraints.gatekeeper.sh/v1beta1 kind: NotLatestImage metadata: name: notlatestimage spec: match: kinds: - apiGroups: [""] kinds: ["Pod"] # kubectl apply –f ochacafe-s5-3/opa/constrainttemplate.yaml # kubectl apply -f ochacafe-s5-3/opa/constraints.yaml constrainttemplate.templates.gatekeeper.sh/notlatestimage created notlatestimage.constraints.gatekeeper.sh/notlatestimage created 対象とするリソースを定義

Slide 74

Slide 74 text

75 Copyright © 2021, Oracle and/or its affiliates Open Policy Agent Gatekeeper & Open Policy Agent 使用例 OKE # cat ochacafe-s5-3/opa/banlataest.yaml 3. latestタグを使用したマニフェストを適用してERROR確認 apiVersion: v1 kind: Pod metadata: name: pod-nginx-latest spec: containers: - name: nginx-latesttag image: nginx:latest # kubectl apply -f ochacafe-s5-3/opa/banlataest.yaml Error from server ([notlatestimage] Can't use image of latest tag !!): error when creating "banlatest.yaml": admission webhook "validation.gatekeeper.sh" denied the request: [notlatestimage] Can't use image of latest tag !!

Slide 75

Slide 75 text

PodSecurityPolicy 76 Copyright © 2022, Oracle and/or its affiliates PodSecurityPolicyとは? Kubernetesクラスタに対してセキュリティポリシーによる制限をかけることを可能にするリソース Kubernetes v1.21から非推奨となり、v1.25から廃止になる予定 • 後継としては、PodSecurity として admission controller 実装 • PodSecurity(PodSecurity Admission)は、3つモード(enforce、audit、warn)があり、Namespaceのラベ ルで制御する形式 • その3つのモードの値として、Pod Security Standards で定義されるポリシー(privileged、restricted、 baseline)を適用 「PodSecurityPolicyの廃止に備えて、一足先にPodSecurity Admissionを試してみよう!」 https://qiita.com/uesyn/items/cf47e12fba5e5c5ea25f

Slide 76

Slide 76 text

PodSecurityPolicy 77 Copyright © 2022, Oracle and/or its affiliates PodSecurity(PodSecurity Admission) モード Mode Description enforce ポリシー違反により、Podは拒否 audit ポリシー違反により、監査ログ(audit.log)に記録されたイベントに監査アノテーションを追加、それ以外は許可 warn ポリシー違反はユーザー向けに警告、それ以外は許可 Pod Security Standards ポリシーレベル Profile Description Privileged 無制限ポリシー Baseline 最小限の制限ポリシー Restricted 最も厳しい制限ポリシー Policy Details : https://kubernetes.io/docs/concepts/security/pod-security-standards/ PodSecurity admission : https://kubernetes.io/docs/concepts/security/pod-security-admission/

Slide 77

Slide 77 text

PodSecurityPolicy 78 Copyright © 2022, Oracle and/or its affiliates PodSecurity manifest https://kubernetes.io/docs/concepts/security/pod-security-admission/ PodSecurity(PodSecurity Admission) モード Pod Security Standards ポリシーレベル apiVersion: v1 kind: Namespace metadata: labels: pod-security.kubernetes.io/enforce: privileged pod-security.kubernetes.io/audit: privileged pod-security.kubernetes.io/warn: baseline name: sample

Slide 78

Slide 78 text

PodSecurityPolicy 79 Copyright © 2022, Oracle and/or its affiliates PodSecurityPolicy設定可能なポリシー Field Names Control Aspect privileged Running of privileged containers hostPID, hostIPC Usage of host namespaces hostNetwork, hostPorts Usage of host networking and ports volumes Usage of volume types allowedHostPaths Usage of the host filesystem allowedFlexVolumes Allow specific FlexVolume drivers fsGroup Allocating an FSGroup that owns the pod's volumes readOnlyRootFilesystem Requiring the use of a read only root file system runAsUser, runAsGroup, supplementalGroups The user and group IDs of the container allowPrivilegeEscalation, defaultAllowPrivilegeEscalation Restricting escalation to root privileges defaultAddCapabilities, requiredDropCapabilities, allowedCapabilities Linux capabilities seLinux The SELinux context of the container allowedProcMountTypes The Allowed Proc Mount types for the container annotations The AppArmor profile used by containers annotations The seccomp profile used by containers forbiddenSysctls,allowedUnsafeSysctls The sysctl profile used by containers https://kubernetes.io/docs/concepts/policy/pod-security-policy/

Slide 79

Slide 79 text

PodSecurityPolicy 80 Copyright © 2022, Oracle and/or its affiliates apiVersion: policy/v1beta1 kind: PodSecurityPolicy metadata: name: privileged-psp annotations: seccomp.security.alpha.kubernetes.io/allowedProfileNames: '*' spec: privileged: true allowPrivilegeEscalation: true allowedCapabilities: - '*' volumes: - '*' hostNetwork: true hostPorts: - min: 0 max: 65535 hostIPC: true hostPID: true runAsUser: rule: 'RunAsAny' seLinux: rule: 'RunAsAny' supplementalGroups: rule: 'RunAsAny' fsGroup: rule: 'RunAsAny' apiVersion: policy/v1beta1 kind: PodSecurityPolicy metadata: name: restricted-psp annotations: seccomp.security.alpha.kubernetes.io/allowedProfileNames: '*' spec: privileged: false allowPrivilegeEscalation: false allowedCapabilities: - '*' volumes: - '*' hostNetwork: false hostPorts: - min: 0 max: 65535 hostIPC: true hostPID: true runAsUser: rule: 'MustRunAsNonRoot' seLinux: rule: 'RunAsAny' supplementalGroups: rule: 'RunAsAny' fsGroup: rule: 'RunAsAny' https://kubernetes.io/docs/concepts/policy/pod-security-policy/#example-policies PodSecurityPolicyの許可ポリシー PodSecurityPolicyの制限ポリシー

Slide 80

Slide 80 text

PodSecurityPolicy 81 Copyright © 2022, Oracle and/or its affiliates default PodSecurityPolicy ・privileged-psp ・restricted-psp ClusterRole ・cluster-admin

Slide 81

Slide 81 text

PodSecurityPolicy 82 Copyright © 2022, Oracle and/or its affiliates edit-user PodSecurityPolicy ClusterRole ・edit(non-psp) PodSecurityPolicy ・restricted-psp ClusterRole ・edit(non-psp) ・edit-restricted(psp) MustRunAsNonRoot NonRoot Nginx Image

Slide 82

Slide 82 text

PodSecurityPolicy 83 Copyright © 2022, Oracle and/or its affiliates PodSecurityPolicyの使用例 2.PodSecurityPolicyへの権限を持たない「edit」のClusterRoleと紐づいた、ServiceAccount「edit-user」を作成 ※この設定をしないと、ポリシーは有効にならない ※設定後のデフォルト状態では、Pod作成ができない(ホワイトリスト)ため、定義する必要がある。 ※デフォルトの「cluster-admin」権限を持つdefaultと「edit」権限を持つedit-user の挙動を見る。 事前準備 1.kube-apiserverのAdmission ControlでPodSecurityPolicyを有効化する admin edit-user ※clusterrole editはデフォルト

Slide 83

Slide 83 text

PodSecurityPolicy 84 Copyright © 2022, Oracle and/or its affiliates PodSecurityPolicyの使用例 2.PodSecurityPolicyの制限ポリシーを適用 Nginxのpod作成をしながら、adminとedit-user、それぞれの挙動をみる。 動作確認 1.PodSecurityPolicyの許可ポリシーを適用 Nginxのpod作成をしながら、adminとedit-user、それぞれの挙動をみる。 3.PodSecurityPolicyの制限ポリシーをedit-userに紐づける 4.edit-userでNginxのpodが作成できるか確認

Slide 84

Slide 84 text

PodSecurityPolicy 85 Copyright © 2022, Oracle and/or its affiliates PodSecurityPolicyの使用例 # vim /etc/kubernetes/manifests/kube-apiserver.yaml 事前準備 1.kube-apiserverのAdmission ControlでPodSecurityPolicyを有効化する 「/etc/kubernetes/manifests/kube-apiserver.yaml」ファイルを編集 (省略) spec: containers: - command: (省略) - --enable-admission-plugins=NodeRestriction,PodSecurityPolicy (省略) ※Admission Controller におけるプラグイン対応については、各ベンダーのマネージドサービスで異なるので確認が必要 OKEではこちらを参照(https://docs.oracle.com/en-us/iaas/Content/ContEng/Reference/contengadmissioncontrollers.htm) Controle Plane ノードからログアウト

Slide 85

Slide 85 text

PodSecurityPolicy 86 Copyright © 2022, Oracle and/or its affiliates PodSecurityPolicyの使用例 2.PodSecurityPolicyへの権限を持たない「edit」のClusterRoleと紐づいた、ServiceAccount「edit-user」を作成 # kubectl create serviceaccount edit-user ServiceAccount 「edit-user」を作成 manage serviceaccount/edit-user created

Slide 86

Slide 86 text

PodSecurityPolicy 87 Copyright © 2022, Oracle and/or its affiliates PodSecurityPolicyの使用例 apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: creationTimestamp: null name: edit-user roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: edit subjects: - kind: ServiceAccount name: edit-user namespace: default ※clusterrole editはデフォルトであります。 # kubectl create clusterrolebinding edit-user --clusterrole edit --serviceaccount default:edit-user -o yaml --dry-run=client > edit- user-crolebinding.yaml ServiceAccount 「edit-user」に edit 権限付与 # cat edit-user-crolebinding.yaml manage

Slide 87

Slide 87 text

PodSecurityPolicy 88 Copyright © 2022, Oracle and/or its affiliates PodSecurityPolicyの使用例 kubectl apply -f edit-user-crolebinding.yaml clusterrolebinding.rbac.authorization.k8s.io/edit-user created マニフェスト適用 動作確認 # alias kubectl-admin='kubectl' 分かりやすいようにエイリアスを設定 # alias kubectl-edit='kubectl --as=system:serviceaccount:default:edit-user' 「cluster-admin」権限を持つdefault(serviceaccout) 「edit」権限を持つedit-user (serviceaccout) kubectl get clusterrolebindings | grep edit-user edit-user ClusterRole/edit 11m manage

Slide 88

Slide 88 text

PodSecurityPolicy 89 Copyright © 2022, Oracle and/or its affiliates PodSecurityPolicyの使用例 # kubectl-admin apply -f ochacafe-s5-3/psp/privileged-psp.yaml 1.PodSecurityPolicyの許可ポリシーを適用 apiVersion: policy/v1beta1 kind: PodSecurityPolicy metadata: name: privileged-psp annotations: seccomp.security.alpha.kubernetes.io/allowedProfileNames: '*' spec: privileged: true allowPrivilegeEscalation: true allowedCapabilities: - '*' volumes: - '*' hostNetwork: true hostPorts: - min: 0 max: 65535 hostIPC: true hostPID: true runAsUser: rule: 'RunAsAny' seLinux: rule: 'RunAsAny' supplementalGroups: rule: 'RunAsAny' fsGroup: rule: 'RunAsAny' privileged-psp.yaml https://kubernetes.io/docs/concepts/policy/pod-security-policy/#example-policies podsecuritypolicy.policy/privileged-psp created manage

Slide 89

Slide 89 text

PodSecurityPolicy 90 Copyright © 2022, Oracle and/or its affiliates PodSecurityPolicyの使用例 # kubectl-admin get psp 適用の確認 NAME PRIV CAPS SELINUX RUNASUSER FSGROUP SUPGROUP READONLYROOTFS VOLUMES privileged-psp true * RunAsAny RunAsAny RunAsAny RunAsAny false * adminとeditでNginx Podを作成するとどうなるか? # kubectl-admin run nginx-a --image nginx:1.21 --restart=Never pod/nginx-a created # kubectl-edit run nginx-b --image nginx:1.21 --restart=Never Error from server (Forbidden): pods "nginx-b" is forbidden: PodSecurityPolicy: unable to admit pod: [] PodSecurityPolicyへの権限を持つadminはPod作成できるが、権限を持たないeditでは作成できない。 manage

Slide 90

Slide 90 text

PodSecurityPolicy 91 Copyright © 2022, Oracle and/or its affiliates PodSecurityPolicyの使用例 # kubectl-admin apply -f ochacafe-s5-3/psp/restricted-psp.yaml 2.PodSecurityPolicyの制限ポリシーを適用 apiVersion: policy/v1beta1 kind: PodSecurityPolicy metadata: name: restricted-psp annotations: seccomp.security.alpha.kubernetes.io/allowedProfileNames: '*' spec: privileged: false allowPrivilegeEscalation: false allowedCapabilities: - '*' volumes: - '*' hostNetwork: false hostPorts: - min: 0 max: 65535 hostIPC: true hostPID: true runAsUser: rule: 'MustRunAsNonRoot' seLinux: rule: 'RunAsAny' supplementalGroups: rule: 'RunAsAny' fsGroup: rule: 'RunAsAny' restricted-psp.yaml https://kubernetes.io/docs/concepts/policy/pod-security-policy/#example-policies podsecuritypolicy.policy/restricted-psp created manage

Slide 91

Slide 91 text

PodSecurityPolicy 92 Copyright © 2022, Oracle and/or its affiliates PodSecurityPolicyの使用例 # kubectl-admin get psp 適用の確認 NAME PRIV CAPS SELINUX RUNASUSER FSGROUP SUPGROUP READONLYROOTFS VOLUMES privileged-psp true * RunAsAny RunAsAny RunAsAny RunAsAny false * restricted-psp false * RunAsAny MustRunAsNonRoot RunAsAny RunAsAny false * adminとeditでNginx Podを作成するとどうなるか? # kubectl-admin run nginx-c --image nginx:1.21 --restart=Never pod/nginx-c created # kubectl-admin auth can-i use podsecuritypolicy/privileged-psp yes # kubectl-admin auth can-i use podsecuritypolicy/restricted-psp yes adminは、privileged, restricted 両方の権限を保有しているため、Podを作成できる。 manage

Slide 92

Slide 92 text

PodSecurityPolicy 93 Copyright © 2022, Oracle and/or its affiliates PodSecurityPolicyの使用例 # kubectl-edit auth can-i use podsecuritypolicy/privileged-psp no # kubectl-edit auth can-i use podsecuritypolicy/restricted-psp no editは、privileged-psp, restricted-psp PodSecurityPolicyの権限を持っていない # kubectl-admin create clusterrole edit-restricted --verb=use --resource=podsecuritypolicy --resource-name=restricted-psp ClusterRoleを作成して、ClusterRoleBindingでeditを紐づける clusterrole.rbac.authorization.k8s.io/edit-restricted created # kubectl-admin create clusterrolebinding edit-restricted --clusterrole=edit-restricted --serviceaccount=default:edit-user clusterrolebinding.rbac.authorization.k8s.io/edit-restricted created manage

Slide 93

Slide 93 text

PodSecurityPolicy 94 Copyright © 2022, Oracle and/or its affiliates PodSecurityPolicyの使用例 # kubectl-edit auth can-i use podsecuritypolicy/restricted-psp yes editはrestricted-psp PodSecurityPolicyの権限を持つ # kubectl-edit run nginx-d --image=nginx:1.21 --restart=Never pod/nginx-d created editでNginx Podを作成 # kubectl-edit get pods NAME READY STATUS RESTARTS AGE nginx-a 1/1 Running 0 140m nginx-c 1/1 Running 0 120m nginx-d 0/1 CreateContainerConfigError 0 14s Nginx Pod作成できるがコンテナが起動できない manage

Slide 94

Slide 94 text

PodSecurityPolicy 95 Copyright © 2022, Oracle and/or its affiliates PodSecurityPolicyの使用例 # kubectl-edit describe pod nginx-d restricted-psp ポリシーには、「runAsUser」に「MustRunAsNonRoot」が定義されているのでPodが作成できない (省略) Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Scheduled 5m13s default-scheduler Successfully assigned default/nginx-d to k8s-node Warning Failed 3m9s (x12 over 5m13s) kubelet Error: container has runAsNonRoot and image will run as root (pod: "nginx- d_default(c23e101b-ca14-4823-a4c1-651a0b09d7ce)", container: nginx-d) (省略) runAsUser: rule: 'MustRunAsNonRoot' seLinux: rule: 'RunAsAny' supplementalGroups: rule: 'RunAsAny' fsGroup: rule: 'RunAsAny' manage

Slide 95

Slide 95 text

PodSecurityPolicy 96 Copyright © 2022, Oracle and/or its affiliates PodSecurityPolicyの使用例 # kubectl-edit run nginx-e --image=nginxinc/nginx-unprivileged --restart=Never root以外のユーザで起動できるNginx Imageに変更すると起動できる pod/nginx-e created # kubectl-edit get pods NAME READY STATUS RESTARTS AGE nginx-a 1/1 Running 0 176m nginx-c 1/1 Running 0 155m nginx-d 0/1 CreateContainerConfigError 0 35m nginx-e 1/1 Running 0 17s nginx-unprivileged Image https://hub.docker.com/r/nginxinc/nginx-unprivileged manage

Slide 96

Slide 96 text

Container Runtime Sandboxes 97 Copyright © 2022, Oracle and/or its affiliates Container Runtime おさらい CRI Container Runtime= 高レベルランタイム OCI Container Runtime = 低レベルランタイム コンテナイメージ、ルートファイルシステム、ネットワークなどを担う 実体はバイナリで、隔離環境(コンテナ)作成を担う

Slide 97

Slide 97 text

Container Runtime Sandboxes 98 Copyright © 2022, Oracle and/or its affiliates Container Runtime おさらい CRI CRI Container Runtime OCI Container Runtime Pod Container Container Registry

Slide 98

Slide 98 text

Container Runtime Sandboxes 99 Copyright © 2022, Oracle and/or its affiliates Sentry というGoで作られたプログラムがカーネルとしてアプリケーション からの syscall を処理 ホストカーネルに到達する syscall が大幅に縮小し、攻撃対象を狭 めることでセキュリティを高める https://cloud.google.com/blog/ja/products/containers-kubernetes/how-gvisor-protects-google-cloud-services-from-cve-2020-14386

Slide 99

Slide 99 text

Container Runtime Sandboxes 100 Copyright © 2022, Oracle and/or its affiliates 仮想化の技術を利用して作成した軽量なハイパーバイザーの上で動作し、コンテナ個別にカーネルを動作させることで、 コンテナ間の分離を図り、セキュリティを高める https://katacontainers.io/learn/

Slide 100

Slide 100 text

Container Runtime Sandboxes 101 Copyright © 2022, Oracle and/or its affiliates Runtime Class Runtime Class Kubernetesには、gVisor や Kata Containers のような OCI Container Runtime を Pod 起動時に選択できる仕 組みがあり、それを利用してコンテナランタイムレベルでセキュリティ対策を行う

Slide 101

Slide 101 text

Container Runtime Sandboxes 102 Copyright © 2022, Oracle and/or its affiliates Runtime Class Runtime Class を利用する上での必要事項 • Kubernetes Admission Controller において RuntimeClass を有効 • マニフェストで RuntimeClass を定義、そして適用 • CRI Container Runtime で OCI Container Runtime の設定

Slide 102

Slide 102 text

Container Runtime Sandboxes 103 Copyright © 2022, Oracle and/or its affiliates Runtime Class の使用例 1.kube-apiserver の Admission Control で RuntimeClass を有効化する 2.gVisor の RuntimeClass マニフェストの作成および適用 3.Nginx Pod を gVisor 指定して起動 ※事前に gVisor インストールおよび CRI Container Runtime (containerd) への設定は完了前提 CRI CRI Container Runtime OCI Container Runtime Container Registry Pod

Slide 103

Slide 103 text

Container Runtime Sandboxes 104 Copyright © 2022, Oracle and/or its affiliates Runtime Class の使用例 1.kube-apiserver の Admission Control で RuntimeClass を有効化する 「/etc/kubernetes/manifests/kube-apiserver.yaml」ファイルを編集 (省略) spec: containers: - command: (省略) - --enable-admission-plugins=NodeRestriction,PodSecurityPolicy,RuntimeClass (省略) ※Admission Controller におけるプラグイン対応については、各ベンダーのマネージドサービスで異なるので確認が必要 OKEではこちらを参照(https://docs.oracle.com/en-us/iaas/Content/ContEng/Reference/contengadmissioncontrollers.htm) # vim /etc/kubernetes/manifests/kube-apiserver.yaml Controle Plane ノードからログアウト

Slide 104

Slide 104 text

Container Runtime Sandboxes 105 Copyright © 2022, Oracle and/or its affiliates Runtime Class の使用例 2.gVisor の RuntimeClass マニフェストの作成および適用 manage apiVersion: node.k8s.io/v1beta1 kind: RuntimeClass metadata: name: gvisor handler: runsc # cat ochacafe-s5-3/runtimeclass/runtimeclass.yaml RuntimeClass名を定義 指定する CRI Container Runtime を定義 runsc = gVisor # kubectl apply -f ochacafe-s5-3/runtimeclass/runtimeclass.yaml runtimeclass.node.k8s.io/gvisor created

Slide 105

Slide 105 text

Container Runtime Sandboxes 106 Copyright © 2022, Oracle and/or its affiliates Runtime Class の使用例 apiVersion: v1 kind: Pod metadata: labels: run: gvisor-nginx name: gvisor-nginx spec: runtimeClassName: gvisor containers: - image: nginx:1.21 name: gvisor-nginx restartPolicy: Never # cat ochacafe-s5-3/runtimeclass/gvisor-nginx.yaml pod.spec.runtimeClassName に RuntimeClass名を定義 # kubectl apply -f ochacafe-s5-3/runtimeclass/gvisor-nginx.yaml pod/gvisor-nginx created 3.Nginx Pod を gVisor 指定して起動 manage

Slide 106

Slide 106 text

Container Runtime Sandboxes 107 Copyright © 2022, Oracle and/or its affiliates Runtime Class の使用例 # kubectl exec -it gvisor-nginx -- /bin/bash 「gvisor-nginx」 Pod に接続して、gVisor 起動を確認 root@gvisor-nginx:/# dmesg [ 0.000000] Starting gVisor... [ 0.375132] Reading process obituaries... [ 0.816984] Creating cloned children... [ 1.260229] Verifying that no non-zero bytes made their way into /dev/zero... [ 1.509300] Letting the watchdogs out... [ 1.526183] Synthesizing system calls... [ 1.619388] Checking naughty and nice process list... [ 1.657616] Recruiting cron-ies... [ 2.124831] Feeding the init monster... [ 2.190595] Forking spaghetti code... [ 2.258599] Singleplexing /dev/ptmx... [ 2.716595] Ready! manage

Slide 107

Slide 107 text

Supply Chain Security Trivy 108 Copyright © 2022, Oracle and/or its affiliates

Slide 108

Slide 108 text

Trivy 109 Copyright © 2022, Oracle and/or its affiliates コンテナイメージとセキュリティ 脆弱性を持つコンテナイメージをもとに起動したコンテナは脆弱性を含むため、イメージを保護する必要がある パブリックなコンテナイメージレジストリにあるコンテナイメージが安全とは限らない OSSコミュニティの公式イメージだから安心できるとも限らない

Slide 109

Slide 109 text

Trivy 110 Copyright © 2022, Oracle and/or its affiliates Trivyとは? コンテナイメージの脆弱性を静的に診断するツールで、OSパッケージ情報、アプリケーションの依存関係などから脆弱性 を検出、Aqua Security社がOSSとして公開している 主な特徴 • ワンバイナリでインストール、操作が簡単 • 脆弱性データベースから診断 • スキャンと結果出力が速い • コンテナイメージだけでなくローイカルファイルシステムやリモートgitリポジトリなどサポート https://github.com/aquasecurity/trivy

Slide 110

Slide 110 text

Trivy 111 Copyright © 2022, Oracle and/or its affiliates Trivyの使用例 Kubernetesクラスタ上で稼働しているPodからイメージを調べて、Trivyで脆弱性スキャンを実行する 2.稼働しているPod内のコンテナイメージを確認 1.Trivyのダウンロード 3.Trivyでスキャンをかけて、HIGHとCRITICALが表示されるイメージを見つける

Slide 111

Slide 111 text

Trivy 112 Copyright © 2022, Oracle and/or its affiliates Trivyの使用例 1.Trivyのダウンロード # trivy -v # curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin v0.24.0 Version: 0.24.0 manage サンプルPodのデプロイ # kubectl apply -f ochacafe-s5-3/trivy/ pod/oraclelinux created deployment.apps/sample-go-app created service/sample-go-app-service created pod/ubuntu created

Slide 112

Slide 112 text

Trivy 113 Copyright © 2022, Oracle and/or its affiliates Trivyの使用例 2.稼働しているPod内のコンテナイメージを確認 # kubectl get pods NAME READY STATUS RESTARTS AGE Oraclelinux 1/1 Running 0 11m sample-go-app-548b756854-x7x8g 1/1 Running 0 33m Ubuntu 1/1 Running 0 24m # kubectl get pods -o yaml | grep image: image: oraclelinux:8.5 image: docker.io/library/oraclelinux:8.5 - image: icn.ocir.io/orasejapan/ochacafe5-3:arm image: icn.ocir.io/orasejapan/ochacafe5-3:arm image: ubuntu:21.10 image: docker.io/library/ubuntu:21.10 manage

Slide 113

Slide 113 text

Trivy 114 Copyright © 2022, Oracle and/or its affiliates Trivyの使用例 3.Trivyでスキャンをかけて、HIGHとCRITICALが表示されるイメージを見つける # trivy image --severity HIGH,CRITICAL docker.io/library/oraclelinux:8.5 manage # trivy image --severity HIGH,CRITICAL docker.io/library/ubuntu:21.10 # trivy image --severity HIGH,CRITICAL icn.ocir.io/orasejapan/ochacafe5-3:arm

Slide 114

Slide 114 text

Monitoring, Logging and Runtime Security Falco 115 Copyright © 2022, Oracle and/or its affiliates

Slide 115

Slide 115 text

Falco 116 Copyright © 2022, Oracle and/or its affiliates コンテナランタイムセキュリティ Prevention/Enforcement 事前に 「誰が何をするか」 を制御する仕組み Detection/Audit Kubernetesクラスタ上で、「何が起こっているのか」を検知して対処する仕組み • Network Policy • RBAC • PodSecurityPolicy • OPA(Admission Control) Prevention/Enforcement における事前の対策では防げない場合の対策 起きた事象を検知、追跡して、原因を特定する仕組みが必要

Slide 116

Slide 116 text

Falco 117 Copyright © 2022, Oracle and/or its affiliates Falcoとは? • カーネルからのシステムコールを解析して、定義したルールに違反した意図しない振る舞いを検知 • 設定された出力対象(Syslog、標準出力など)にアラートする • 何を実行したかなどを追跡して、原因究明を支援 • Sysdig社によりOSSとして公開されている(CNCF Incubating Project) https://github.com/falcosecurity/falco 予期せぬアプリケーションの挙動を検知し、ランタイムレベルで脅威をアラートするランタイムセキュリティツール

Slide 117

Slide 117 text

Falco 118 Copyright © 2022, Oracle and/or its affiliates Falco Architecture https://www.cncf.io/wp-content/uploads/2020/08/Kubernetes-Runtime-Security-with-Falco-and-Sysdig.pdf User Space Kernel Space 解析 アラート

Slide 118

Slide 118 text

Falco 119 Copyright © 2022, Oracle and/or its affiliates Falco Default Rules https://falco.org/ja/docs/#falco%E3%81%AF%E4%BD%95%E3%82%92%E8%A6%8B%E3%81 %A6%E3%81%84%E3%82%8B%E3%81%AE%E3%81%8B • 特権コンテナを使用した特権のエスカレーション • setns のようなツールを使ったネームスペースの変更 • /etc, /usr/bin, /usr/sbin などのよく知られたディレクトリへの読み込み/書き込み • シンボリックリンクの作成 • 所有権とモードの変更 • 予期しないネットワーク接続またはソケットの変異 • execve を使ってプロセスをSpawnした • sh, bash, csh, zsh などのシェルバイナリの実行 • SSH バイナリ ssh, scp, sftp などを実行する • Linux の coreutils 実行ファイルを変異させる • ログインバイナリの変異 • shadowutil や passwd の実行ファイルを変異させる • shadowconfig • pwck • chpasswd • getpasswd • change • useradd など YAMLとしては、3,000行以上 https://github.com/falcosecurity/falco/blob/master/rules/falco_rules.yaml

Slide 119

Slide 119 text

Falco 120 Copyright © 2022, Oracle and/or its affiliates Falco Install • Linux Host • Kubernetes インストール方法は以下2通りで、侵害された場合、Kubernetesから分離する Linux Host へのインストールを推奨 FalcoはKubernetesランタイムセキュリティに使用できます。 Falcoを実行する最も安全な方法は、ホストシステムにFalcoを直接イン ストールすることです。これにより、侵害された場合にFalcoがKubernetesから分離されます。 その後、Falcoアラートは、Kubernetes で実行されている読み取り専用エージェントを介して使用できます。 分離が問題にならない場合は、FalcoをKubernetesで直接実行することもできます。 Kind、Minikube、Helmなどのツールを使用し てKubernetesで直接Falcoを実行する場合は、サードパーティ統合をご覧ください。 https://falco.org/ja/docs/getting-started/installation/

Slide 120

Slide 120 text

Falco 121 Copyright © 2022, Oracle and/or its affiliates Falco の使用例 Node の仮想マシンに Falco をインストール、httpd の Pod(コンテナ)内で操作して Syslog の結果を確認する。 2. テスト用のPodを起動後、Pod(コンテナ)内およびNodeで「/etc/」ディレクトリ内にファイル作成を試みる 1.Node の仮想マシンで Falco をインストール 3. 「/var/log/syslog」の Falco からの出力を確認する ※ Falco は Arm をサーポートしていない(2022年3月時点)ので、デモは AMD 環境で行います。

Slide 121

Slide 121 text

Falco 122 Copyright © 2022, Oracle and/or its affiliates Falco の使用例 1.Node の仮想マシンで Falco をインストール # curl -s https://falco.org/repo/falcosecurity-3672BA8F.asc | apt-key add - Falco のインストール # echo "deb https://download.falco.org/packages/deb stable main" | tee -a /etc/apt/sources.list.d/falcosecurity.list # apt-get update -y # apt-get -y install linux-headers-$(uname -r) # apt-get install -y falco

Slide 122

Slide 122 text

Falco 123 Copyright © 2022, Oracle and/or its affiliates Falco の使用例 2. テスト用のPodを起動後、Pod(コンテナ)内でルール違反をして、ログを確認 # kubectl apply -f ochacafe-s5-3/falco/httpd.yaml pod/apache created # kubectl exec -it apache -- touch /etc/test.conf 「/etc/」ディレクトリ配下に、ファイルを作成する manage

Slide 123

Slide 123 text

Falco 124 Copyright © 2022, Oracle and/or its affiliates Falco の使用例 # cat /var/log/syslog | grep falco Nodeの「/etc/」ディレクトリ配下に作った場合のSyslog Mar 3 11:11:57 k8s-node-k-945573 falco: 11:11:57.885578617: Error File below /etc opened for writing (user=root user_loginuid=1001 command=touch /etc/test2.conf parent=bash pcmdline=bash file=/etc/test2.conf program=touch gparent=sudo ggparent=bash gggparent=node container_id=host image=) # touch /etc/test2.conf # cat /var/log/syslog | grep falco Node側で「/var/log/syslog」に出力される Falco のログを確認 Mar 3 11:01:31 k8s-node-k-945573 falco: 11:01:31.183863989: Error File below /etc opened for writing (user=root user_loginuid=-1 command=touch /etc/test.conf parent= pcmdline= file=/etc/test.conf program=touch gparent= ggparent= gggparent= container_id=a723e15034a5 image=docker.io/library/httpd)

Slide 124

Slide 124 text

Falco 125 Copyright © 2022, Oracle and/or its affiliates Falco の使用例 ルール定義を確認 # vim /etc/falco/falco_rules.yaml (省略) - rule: Write below etc desc: an attempt to write to any file below /etc condition: write_etc_common output: "File below /etc opened for writing (user=%user.name user_loginuid=%user.loginuid command=%proc.cmdline parent=%proc.pname pcmdline=%proc.pcmdline file=%fd.name program=%proc.name gparent=%proc.aname[2] ggparent=%proc.aname[3] gggparent=%proc.aname[4] container_id=%container.id image=%container.image.repository)" priority: ERROR tags: [filesystem, mitre_persistence] (省略)

Slide 125

Slide 125 text

参考資料 126 Copyright © 2022, Oracle and/or its affiliates

Slide 126

Slide 126 text

参考資料 127 Copyright © 2022, Oracle and/or its affiliates Kubernetes CKS 2022 Complete Course - Theory – Practice https://www.udemy.com/course/certified-kubernetes-security-specialist/ Kubernetes Documentation https://kubernetes.io/docs/home/ KubernetesのSeccompDefaultを試した https://qiita.com/uesyn/items/3fc1b25eafa0939aebb8 PodSecurityPolicyの廃止に備えて、一足先にPodSecurity Admissionを試してみよう! https://qiita.com/uesyn/items/cf47e12fba5e5c5ea25f KubernetesのRuntime Classについて知ろう https://event.cloudnativedays.jp/cndo2021/talks/841 Kubernetes: RBACの設定におけるAPIリソース https://qiita.com/tkusumi/items/300c566a74b6b64e7e89 デモ環境 https://github.com/oracle-japan/ochacafe-s5-3 CI/CD最新事情(OPA) https://www.youtube.com/watch?v=K62nFSvHo60 https://speakerdeck.com/oracle4engineer/oracle-cloud-hangout-cafe-cicdzui-xin-shi-qing

Slide 127

Slide 127 text

Thank you 128 Copyright © 2022, Oracle and/or its affiliates | Confidential: Internal/Restricted/Highly Restricted [Date]

Slide 128

Slide 128 text

No content