Oralce Hangout Cafe Season5 #3
Kubernetes SecurityOracle Cloud Hangout Cafe Season 5 #3Yutaka IchikawaSolutions ArchitectOracle Corporation JapanMAR 09, 2022
View Slide
ProfileCopyright © 2022, Oracle and/or its affiliates2Name• Yutaka Ichikawa/市川 豊Belong• Solutions ArchitectRole• Principal Cloud Solution EngineerSNS• Twitter/GitHub/Qiita:cyberblack28Blog• https://cyberblack28.hatenablog.com/Materials• https://speakerdeck.com/cyberblack28/Community• CloudNative Days Tokyo #cndt #o11y2022Certified• Certified Kubernetes Administrator• Certified Kubernetes Application Developer• Certified Kubernetes Security Specialist• Kubernetes and Cloud Native AssociatePublicationsNew3/11 オンライン・参加費無料https://event.cloudnativedays.jp/o11y2022/
AgendaCKS• CKSとは?• CKSの範囲• CKS対策Kubernetes Security• Cluster Setup• NetworkPolicy• CIS Benchmark• Cluster Hardening• RBAC• System Hardening• AppArmor• Minimize MicroserviceVulnerabilities• SecurityContext• Open Policy Agent• PodSecurityPolicy• Container Runtime Sandboxes• Supply Chain Security• Trivy• Monitoring, Logging andRuntime Security• Falco• 参考資料3 Copyright © 2022, Oracle and/or its affiliates
CKSCKSとは?CKSの範囲CKS対策4 Copyright © 2022, Oracle and/or its affiliates
CKSとは?5 Copyright © 2022, Oracle and/or its affiliates
CKS6CKSとは?Certified Kubernetes Security SpecialistコンテナベースのアプリケーションとKubernetesプラットフォームのビルド、デプロイ、ランタイム時のセキュリティを確保する幅広いベストプラクティスの実行能力を証明する認定試験Copyright © 2022, Oracle and/or its affiliates
CKS7CKSとは?試験概要 内容試験時間 2時間問題数 15-20問(自分が受験した時は15問)合格基準 67%以上受験条件 CKAに合格していること受験形式 オンライン受験・ハンズオン形式有効期間 2年間受験料 $375Copyright © 2022, Oracle and/or its affiliates
CKSの試験範囲8 Copyright © 2022, Oracle and/or its affiliates
CKS9CKSの試験範囲カテゴリ/出題割合 内容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
CKS10CKSの試験範囲Documentation URLKubernetes 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-cksCopyright © 2022, Oracle and/or its affiliates
CKS対策11 Copyright © 2022, Oracle and/or its affiliates
CKS12CKS対策Kubernetes CKS 2021 Complete Course- Theory - Practicehttps://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
CKS13CKS対策Kubernetesコントロールプレーンコンポーネントの理解も必要、kubeadmでクラスタを構築して対策Copyright © 2022, Oracle and/or its affiliates
CKS14CKS対策Copyright © 2022, Oracle and/or its affiliatesVirtualMachineVirtualMachinek8s-control-plane k8s-nodeItem SpecShape VM.Standard.A1.FlexCPU AmpereMEM (control plane) 12GBMEM (node/manage) 6GBOS Ubuntu 20.04ContainerRuntime ContainerdCNI CalicokubectlsshVirtualMachinemanageOCI Always-Free 環境で構築できます。UserDemo Environmenthttps://github.com/oracle-japan/ochacafe-s5-3
Kubernetes SecurityCluster SetupCluster HardeningSystem HardeningMinimize Microservice VulnerabilitiesSupply Chain SecurityMonitoring Logging and Runtime Security16 Copyright © 2022, Oracle and/or its affiliates
Cluster SetupNetworkPolicyCIS Benchmark17 Copyright © 2022, Oracle and/or its affiliates
NetworkPolicy18NetworkPolicyは、Kubernetesクラスタ内における、Pod同士が通信するトラフィックルールを規定できる仕組みNamespace: A Namespace: BNamespace: A Namespace: BPod間の通信制御Namespaceを跨いだPod間の通信制御Copyright © 2022, Oracle and/or its affiliates
NetworkPolicy19Weave NetNetworkPolicyを利用するには、NetworkPolicyに対応したネットワークプラグイン(CNIプラグイン)が必要。Copyright © 2022, Oracle and/or its affiliates
NetworkPolicy20全ての送受信トラフィックを許可 全ての送受信トラフィックを拒否Copyright © 2022, Oracle and/or its affiliatesapiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata:name: all-deny-networkpolicyspec:podSelector: {}policyTypes:- Ingress- EgressapiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata:name: all-allow-networkpolicyspec:podSelector: {}egress:- {}ingress:- {}policyTypes:- Ingress- Egress
NetworkPolicy21apiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata:name: example-networkpolicyspec:podSelector:# 設定対象Podのラベルセレクタを定義policyTypes:- Ingress # Ingressルールを指定する場合明示- Egress # Egressルールを指定する場合明示ingress:- from:# Ingressルールを定義ports:# 許可する受信ポート番号とプロトコルを定義egress:- to:# Egressルールを定義ports:# 許可する宛先ポート番号とプロトコルを定義IngressとEgressの各ルールの指定方法は同じ形式Policy Ingress Rule Egress RulepodSelector 特定の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
NetworkPolicy22https://kubernetes.io/docs/concepts/services-networking/network-policies/サンプルマニフェスト実際の試験では、サンプルマニフェストを利用して、問題内容のマニフェストを作成して適用Copyright © 2022, Oracle and/or its affiliates
NetworkPolicy23ホワイトリストとブラックリスト• ホワイトリスト• ブラックリスト予め全てのトラフィックを遮断、特定のトラフィックのみ許可する形式予め全てのトラフィックを許可、特定のトラフィックのみ遮断する形式Copyright © 2022, Oracle and/or its affiliates
NetworkPolicy24Namespace: defaultNamespace: testapp: pod1app: pod2app: pod3app: pod41.全ての送信トラフィックを許可、受信トラフィックは拒否上記マニフェストを各Namespaceに適用egress-only-allow-networkpolicy.yaml192.168.173.129192.168.173.130192.168.173.132192.168.173.131Copyright © 2022, Oracle and/or its affiliatesapiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata:name: egress-only-allow-networkpolicyspec:podSelector: {}egress:- {}policyTypes:- Ingressmanage
NetworkPolicy25Namespace: defaultNamespace: testapp: pod1app: pod2app: pod3app: pod4sp-pod-allow-networkpolicy.yaml2.「app: pod1」から「app: pod2」のみ受信許可Copyright © 2022, Oracle and/or its affiliatesapiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata:name: sp-pod-allow-networkpolicynamespace: defaultspec:podSelector:matchLabels:app: pod2policyTypes:- Ingressingress:- from:- podSelector:matchLabels:app: pod1ports:- protocol: TCPport: 80192.168.173.129192.168.173.130192.168.173.132192.168.173.131manage
NetworkPolicy26Namespace: defaultNamespace: testapp: pod1app: pod2app: pod3app: pod43.Namespace defaultのPodから「app: pod3」のみ受信許可sp-namespace-allow-networkpolicy.yamlCopyright © 2022, Oracle and/or its affiliatesapiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata:name: sp-namespace-allow-networkpolicynamespace: testspec:podSelector:matchLabels:app: pod3policyTypes:- Ingressingress:- from:- namespaceSelector:matchLabels:kubernetes.io/metadata.name: defaultports:- protocol: TCPport: 80192.168.173.129192.168.173.130192.168.173.132192.168.173.131manage
apiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata:name: sp-ip-allow-networkpolicynamespace: testspec:podSelector:matchLabels:app: pod3policyTypes:- Ingressingress:- from:- ipBlock:cidr: 192.168.173.130/32ports:- protocol: TCPport: 80NetworkPolicyCopyright © 2022, Oracle and/or its affiliates27Namespace: defaultNamespace: testapp: pod1app: pod2app: pod3app: pod4sp-ip-allow-networkpolicy.yaml4. 特定のIP Podから「app: pod3」のみ受信許可192.168.173.129192.168.173.130192.168.173.132192.168.173.131manage
CIS Benchmark28CIS (Center for Internet Security)、セキュリティにおけるベストプラクティスの推奨事項のベンチマークを公開Copyright © 2022, Oracle and/or its affiliatesCIS Kubernetes BenchmarkKubernetes におけるセキュリティを強化するためのガイドラインが定められている1. Control Plane Components2. etcd3. Control Plane Configurration4. Worker Nodes5. Policieshttps://www.cisecurity.org/benchmark/kubernetes
CIS Benchmark29 Copyright © 2022, Oracle and/or its affiliatesCIS Kubernetes BenchmarkOSSだけでなく、OKEをはじめとするマネージドサービス向けのベンチマークも公開されている
CIS Benchmark30 Copyright © 2022, Oracle and/or its affiliateskube-benchとは?• CIS Kubernetes Benchmarkの推奨事項に準拠しているかをチェックできるアプリケーション• Aqua Security社がOSSとして公開している• 導入方法としては、対象のKubernetesクラスタ上でPod/Jobでの実行が簡単https://github.com/aquasecurity/kube-bench
CIS Benchmark31 Copyright © 2022, Oracle and/or its affiliateskube-benchの使用例2.kube-benchの実行1.「job-master.yaml」の作成3.結果の確認公式のGitHubで公開されているYAMLを一部編集作成したYAMLファイルを適用推奨事項に準拠しているか確認
CIS Benchmark32 Copyright © 2022, Oracle and/or its affiliateskube-benchの使用例1.「job-master.yaml」の作成# cat ochacafe-s5-3/kube-bench/job-master.yamlmanageapiVersion: batch/v1kind: Jobmetadata:name: kube-bench-masterspec:(省略)containers:- name: kube-benchimage: aquasec/kube-bench:latestcommand: [“kube-bench”, “run”, “--targets”, “master”] ⇒ command: [“kube-bench”] #変更args: [“--version=1.23”] #追加(省略)https://github.com/aquasecurity/kube-bench/blob/main/job-master.yaml
CIS Benchmark33 Copyright © 2022, Oracle and/or its affiliateskube-benchの使用例2. kube-bench の実行# kubectl apply -f job-master.yamlmanagejob.batch/kube-bench-master created# kubectl get podsNAME READY STATUS RESTARTS AGEkube-bench-master-kvjt7 0/1 Completed 0 64mSTATUS が Completed になるまで待つ
CIS Benchmark34 Copyright © 2022, Oracle and/or its affiliateskube-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.yamlon the master node and set the --enable-admission-plugins parameter to avalue 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」を追加する。
Cluster HardeningRBAC35 Copyright © 2022, Oracle and/or its affiliates
RBAC36 Copyright © 2022, Oracle and/or its affiliatesKubernetesにおける認証/認可ユーザがKubernetesを操作する場合、KubernetesのAPIサーバに対してリクエストを送信、以下の3フェーズを経由してリソース登録。Authentication Authorization Admission Controlリクエストを送信したユーザの認証情報が、有効なものか確認送信したユーザのリクエストが許可されているかを確認リクエストに対して、より柔軟なチェックや強制的な変更を担う
RBAC37 Copyright © 2022, Oracle and/or its affiliatesKubernetesにおけるアカウントの種類ServiceAccountUserAccountKubernetesに関連するアカウントは、ServiceAccountとUserAccountの2種類。• Kubernetesが管理するアカウント• Namespaceに紐づく• Podで実行されるプロセスに割り当てられる• Kubernetesが管理しない外部アカウント• Namespaceには紐づかない• クラウドプロバイダーのアカウントやLDAP管理のアカウント
RBAC38 Copyright © 2022, Oracle and/or its affiliatesKubernetesにおける認可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など)に付与するかを指定
RBAC39 Copyright © 2022, Oracle and/or its affiliatesRole-based Access Control(RBAC)RoleRoleRoleRoleBindingRoleBindingUserUserUserUserに対してRoleを紐づける許可項目ServiceAccountなどPodの一覧表示やDeploymentの作成など
RBAC40 Copyright © 2022, Oracle and/or its affiliates2種類のリソーススコープ• Namespace-scopeNamespace-scopeとCluster-scopeのリソースを対象とした許可設定が可能。RoleとRoleBinding• Cluster-scopeClusterRoleとClusterRoleBinding主なリソース:Pod、Deployment、Service、ServiceAccount、PersistentVolumeClaimなど主なリソース:PersistentVolume、Namespace、Nodeなど
RBAC41 Copyright © 2022, Oracle and/or its affiliatesClusterRoleとClusterRoleBindingCluster-scopeのリソースを対象とする場合、ClusterRoleとClusterRoleBindingを利用するClusterNamespace ANamesapce BRoleBinding RoleBindingRoleUser User UserClusterRoleBindingClusterRole
RBAC42 Copyright © 2022, Oracle and/or its affiliates• 全てのNamespaceのリソースを対象ClusterRoleとClusterRoleBindingは、全てのNamespaceに対して権限が付与されるため、Namespaceを横断して権限管理ができる。ClusterRoleとClusterRoleBindingの用途(例)クラスタ管理者やSREに向けた権限などで利用可能• 全てのNamespaceで共通利用するRoleClusterRoleはクラスタを横断してポリシーを定義できるので、各クラスタのNamespaceからRoleBindingでClusterRoleを参照可能。(例)クラスタ管理者が共通のポリシーを各クラスタのNamespaceに向けて提供可能
RBAC43 Copyright © 2022, Oracle and/or its affiliatesマニフェストを作成して適用する例RoleClusterRole「$ Kubectl get pods」による一覧取得(list)はOK、それ以外はNG「$ Kubectl get namespaces」による一覧取得(list)はOK、それ以外はNGRoleBindingClusterRoleBindingpod-role を pod-sa に紐づけるnamespace は defaultnamespace-clusterrole をnamespace-sa に紐づけるnamespace は defaultpod-sanamespace-sapod-rolenamespace-clusterrolepod-rolebindingnamespace-clusterrolebindingServiceAccountServiceAccount
apiVersion:rbac.authorization.k8s.io/v1kind: Rolemetadata:name: pod-rolerules:- apiGroups:- ""resources:- podsverbs:- listRBAC44 Copyright © 2022, Oracle and/or its affiliatesRoleと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
apiVersion:rbac.authorization.k8s.io/v1kind: ClusterRolemetadata:name: namespace-clusterrolerules:- apiGroups:- ""resources:- namespacesverbs:- listRBAC45 Copyright © 2022, Oracle and/or its affiliatesRoleと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
apiVersion:rbac.authorization.k8s.io/v1kind: RoleBindingmetadata:name: pod-rolebindingnamespace: defaultroleRef:apiGroup: rbac.authorization.k8s.iokind: Rolename: pod-rolesubjects:- kind: ServiceAccountname: pod-sanamespace: defaultRBAC46 Copyright © 2022, Oracle and/or its affiliatesRoleBindingと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
apiVersion:rbac.authorization.k8s.io/v1kind: ClusterRoleBindingmetadata:name: namespace-clusterrolebindingroleRef:apiGroup: rbac.authorization.k8s.iokind: ClusterRolename: namespace-clusterrolesubjects:- kind: ServiceAccountname: namespace-sanamespace: defaultRBAC47 Copyright © 2022, Oracle and/or its affiliatesRoleBindingとClusterRoleBindingのマニフェスト「roleRef」で紐づけるClusterRoleを指定。「subjects」でClusterRoleに紐づけるUserやServiceAccountを指定。# kubectl create clusterrolebinding namespace-clusterrolebinding --clusterrole namespace-clusterrole --serviceaccountdefault:namespace-sa -o yaml --dry-run=client > namespace-clusterrolebinding.yaml「roleRef」に紐づけるClusterRoleを指定。1ClusterRoleBindingに対して1ClusterRole、「subjects」には複数のUserやServiceAccountを指定可能。manage
RBAC48 Copyright © 2022, Oracle and/or its affiliates各アカウントで動作を確認# kubectl --as=system:serviceaccount:default:pod-sa get podsmanageNo resources found in default namespace.# kubectl --as=system:serviceaccount:default:pod-sa run nginx --image=nginxError from server (Forbidden): pods is forbidden: User "system:serviceaccount:default:pod-sa" cannot create resource "pods" in APIgroup "" in the namespace "default"pod-saサービスアカウントでPodの一覧を取得pod-saサービスアカウントでPodを作成しようと試みる
RBAC49 Copyright © 2022, Oracle and/or its affiliates各アカウントで動作を確認# kubectl --as=system:serviceaccount:default:namespace-sa create namespace mynamespacemanageError from server (Forbidden): namespaces is forbidden: User "system:serviceaccount:default:namespace-sa" cannot createresource "namespaces" in API group "" at the cluster scopenamespace-saサービスアカウントでNamespaceを作成しようと試みる# kubectl --as=system:serviceaccount:default:namespace-sa get namespacesNAME STATUS AGEcalico-apiserver Active 4h15mcalico-system Active 4h16mdefault Active 4h18mkube-node-lease Active 4h18mkube-public Active 4h18mkube-system Active 4h18mtigera-operator Active 4h16mnamespace-saサービスアカウントでNamespaceの一覧を取得
System HardeningAppArmor50 Copyright © 2022, Oracle and/or its affiliates
AppArmor51 Copyright © 2022, Oracle and/or its affiliatesAppArmorとは?• Linuxカーネルのセキュリティモジュール• プロファイルを作成して、読み取り、書き込み、プログラムの実行やファイルシステムのマウントなど、システム機能を制限可能• コンテナに許可することを制限可能(例)bind-mountしたディレクトリ全体ではなく、個別のファイルやディレクトリに対して権限(RW)を設定可能。Container HostContainerbind-mount権限設定可能
AppArmor52 Copyright © 2022, Oracle and/or its affiliatesAppArmorの使用例Kubernetes NodeAppArmorProfileDeny/** wKubeletがAppArmorのProfileを読み込むProfileにある制限に反する実行要求は実行不可$ touch /tmp/testAppArmorのProfileを使用するアノテーションを定義したマニフェストからPod作成manifestAppArmorのProfileを作成と登録④③⑤※Kubernetes Version 1.4以上であること※Node LinuxでAppArmor Kernel moduleが有効であること※ContainerRuntimeがAppArmorをサポートしていること※参考:https://kubernetes.io/ja/docs/tutorials/clusters/apparmor/②AppArmorが有効かを確認①
AppArmor53 Copyright © 2022, Oracle and/or its affiliatesAppArmorの使用例#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/enabledY「Y」と表示されれば有効状態# vim /etc/apparmor.d/k8s-apparmor-example-deny-write
AppArmor54 Copyright © 2022, Oracle and/or its affiliatesAppArmorの使用例apiVersion: v1kind: Podmetadata:name: hello-apparmorannotations:# 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-writespec:containers:- name: helloimage: busyboxcommand: [ "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-profiles3.apparmor_parserコマンドを実行して、AppArmorプロファイルを登録# apparmor_parser -q /etc/apparmor.d/k8s-apparmor-example-deny-writemanage
AppArmor55 Copyright © 2022, Oracle and/or its affiliatesAppArmorの使用例# kubectl exec hello-apparmor -- touch /tmp/testコンテナがこのプロファイルで実際に実行されていることを確認するために、コンテナの「/proc/attr/」をチェック。touch: /tmp/file: Permission deniedcommand terminated with exit code 1# kubectl exec hello-apparmor -- cat /proc/1/attr/currentk8s-apparmor-example-deny-write (enforce)6.ファイルを書き込みによる動作確認※プロファイルをannotationに設定せずに起動した場合は、「/tmp/test」は作成される5.マニフェスト適用# kubectl ochacafe-s5-3/seccomp/hello-apparomor.yamlpod/hello-apparmor createmanage
seccomp56 Copyright © 2022, Oracle and/or its affiliatesseccompとは?• seccomp = Secure Computing Mode• Linuxカーネルのセキュリティモジュール• プロファイルを作成して、コンテナが呼び出せるシステムコール(プロセス)を制限。• 不要なシステムコールを制限することで、カーネルの脆弱性を狙った攻撃を防ぐ。Container Hostseccompprofile{"defaultAction": "SCMP_ACT_ALLOW","syscalls": [{"names": ["chmod","fchmodat","chmodat"],"action": "SCMP_ACT_ERRNO"}]}prohibit-chmod.jsonxxxContainer$ chmod 777 xxx$ docker run --security-opt seccomp=prohibit-chmod.json ubuntu:21.10権限設定不可
seccomp57 Copyright © 2022, Oracle and/or its affiliatesseccopmの使用例Kubernetes Nodeseccomp{"defaultAction": "SCMP_ACT_ALLOW","syscalls": [{"names": [“mkdir",“mkdirat"],"action": "SCMP_ACT_ERRNO"}]}$ mkdir testmkdir: cannot create directory 'test': Operation not permitted/var/lib/kubelet/seccomp/profiles/prohibit-mkdirseccompが有効かを確認①seccompのProfileを作成②Profileを指定したマニフェストを作成と適用③ ④manifestmkdirを実行してNGを確認⑤
seccomp58 Copyright © 2022, Oracle and/or its affiliatesseccompの使用例# 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
seccomp59 Copyright © 2022, Oracle and/or its affiliatesseccompの使用例# cat ochacafe-s5-3/seccomp/prohibit-mkdir.yaml3.Profileを指定したマニフェストを作成apiVersion: v1kind: Podmetadata:name: prohibit-mkdirspec:securityContext:seccompProfile:type: LocalhostlocalhostProfile: profiles/prohibit-mkdircontainers:- name: ubuntuimage: ubuntu:21.10command:- sleep- infinity• locahostoProfile:Node上の「/var/lib/kubelet/seccomp」ディレクトリ内のファイルをProfileとして指定※Kubernetes1.19以前はannotationで指定、1.19以降はsecurityContextで指定• RuntimeDefault:CRIランタイムのデフォルトプロファイル指定• unconfined:seccomp不使用(デフォルト)manage
seccomp60 Copyright © 2022, Oracle and/or its affiliatesseccompの使用例# kubectl apply -f ochacafe-s5-3/seccomp/prohibit-mkdir.yaml4.マニフェストを適用pod/prohibit-mkdir created# kubectl get podsNAME READY STATUS RESTARTS AGEprohibit-mkdir 1/1 Running 0 9s# kubectl exec -it prohibit-mkdir -- mkdir test5.挙動確認mkdir: cannot create directory 'test': Operation not permittedcommand terminated with exit code 1manage
seccomp61 Copyright © 2022, Oracle and/or its affiliatesseccompの使用例ホワイトリストでProfileをカスタマイズして作ることは、セキュリティを高められるが運用の煩雑さにつながるKubernetes v1.22からalphaとして SeccompDefault という機能が追加され、PodのSpecでprofileを指定しなかった場合に RuntimeDefaultでコンテナを動かすことが可能https://qiita.com/uesyn/items/3fc1b25eafa0939aebb8ある程度コンテナアプリケーションで利用しないようなsyscallを制限したProfile(RuntimeDefault)を利用
Minimize Microservice VulnerabilitiesSecurityContextOpen Policy AgentPodSecurityPolicyContainer Runtime Sandboxes62 Copyright © 2022, Oracle and/or its affiliates
SecurityContext63 Copyright © 2022, Oracle and/or its affiliatesSecurityContextとは?SecurityContextは、PodまたはContainerの特権とアクセス制御の設定SecurityContext for Container(SecurityContext)PodContainerSecurityContext設定項目 概要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に対するセキュリティ設定
SecurityContext64 Copyright © 2022, Oracle and/or its affiliatesSecurityContext for Pod(PodSecurityContext)Pod内すべてのコンテナに対するセキュリティ設定PodContainerPodSecurityContextContainer設定項目 概要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
SecurityContext65 Copyright © 2022, Oracle and/or its affiliatesmanifestSecurityContext PodSecurityContextapiVersion: v1kind: Podmetadata:name: container-scspec:containers:- name: nginx-containerimage: nginx:1.21securityContext:runAsNonRoot: trueどちらとも結果としては、runAsNonRootによりNginx Podは作成されない。apiVersion: v1kind: Podmetadata:name: pod-scspec:securityContext:runAsNonRoot: truecontainers:- name: nginx-containerimage: nginx:1.21manage
SecurityContext66 Copyright © 2022, Oracle and/or its affiliatesmanifestPodと同様のSecurityContextが指定した場合は、ContainerのSecurityContextが優先される。apiVersion: v1kind: Podmetadata:name: both-testspec:securityContext:runAsUser: 1000containers:- name: ubuntuimage: ubuntu:21.10securityContext:runAsUser: 1001command:- sleep- infinitymanage
Open Policy Agent67 Copyright © 2022, Oracle and/or its affiliatesポリシーチェックKubernetesのすべてのリソースは、マニフェストに記述して登録。そのマニフェストの内容が正しいか、許可できるものかをチェックしてセキュリティを高める。マニフェスト$ kubectl applyCheck
68 Copyright © 2021, Oracle and/or its affiliatesGatekeeperというツールを用いてKubernetesクラスタ登録時にマニフェストチェックを行う方法が利用され、ポリシーチェックにOpen Policy Agentが利用されている。GatekeeperCheckOpen Policy AgentGatekeeper & Open Policy Agentマニフェスト$ kubectl apply
69 Copyright © 2021, Oracle and/or its affiliates• 軽量で汎用性のあるOSSのポリシーエンジン• Regoという言語でポリシーを記述してルールを定義• Kubernetes専用というわけではなく、YAML、JSONなど構造化データのポリシーエンジン• CNCFのGraduationプロジェクトOpen Policy AgentOpen Policy Agenthttps://github.com/open-policy-agent/opa
70 Copyright © 2021, Oracle and/or its affiliatesAPIにDataを送信する(Query)と、Policyを参照してDataを評価して結果(Decision)を返す仕組み。OPA公式ドキュメント: https://www.openpolicyagent.org/docs/latest/Open Policy AgentOpen Policy Agent
71 Copyright © 2021, Oracle and/or its affiliatesGatekeeperは、Kubernetesの認証認可フローの拡張機能であるAdmission Controlから外部Webhookサーバとしてチェック依頼を受けて、OPAの定義でチェックしてリソース登録の許可/拒否を返す仕組み。マニフェスト① $ kubectl apply②リソース作成・変更リクエストの許可チェック(Admission Request)Gatekeeper③ Regoの定義でポリシーチェック④ 許可/拒否(Admission Response)⑤ 許可であれば登録Open Policy AgentGatekeeper
72 Copyright © 2021, Oracle and/or its affiliatesOpen Policy AgentGatekeeper & Open Policy Agent 使用例1. Gatekeeper インストール2. ConstraintTemplateの作成と適用3. latestタグを使用したマニフェストを適用してNG確認
73 Copyright © 2021, Oracle and/or its affiliatesOpen Policy AgentGatekeeper & Open Policy Agent 使用例1. Gatekeeper インストール# kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/v3.7.1/deploy/gatekeeper.yamlOKE# cat ochacafe-s5-3/opa/constrainttemplate.yaml2. ConstraintTemplateの作成と適用kind: ConstraintTemplatemetadata:name: notlatestimagespec:crd:spec:names:kind: NotLatestImagetargets:- target: admission.k8s.gatekeeper.shrego: |package notlatestimageviolation[{"msg": msg}]{input.review.object.kind == "Pod"imagetag := input.review.object.spec.containers[_].imageendswith(imagetag,"latest")msg := "Can't use image of latest tag !!"}Regoでルールを記述コンテナイメージのタグにlatestがある場合は以下のメッセージを返す。「Can't use image of latest tag !!」
74 Copyright © 2021, Oracle and/or its affiliatesOpen Policy AgentGatekeeper & Open Policy Agent 使用例OKEcat ochacafe-s5-3/opa/constraints.yamlapiVersion: constraints.gatekeeper.sh/v1beta1kind: NotLatestImagemetadata:name: notlatestimagespec:match:kinds:- apiGroups: [""]kinds: ["Pod"]# kubectl apply –f ochacafe-s5-3/opa/constrainttemplate.yaml# kubectl apply -f ochacafe-s5-3/opa/constraints.yamlconstrainttemplate.templates.gatekeeper.sh/notlatestimage creatednotlatestimage.constraints.gatekeeper.sh/notlatestimage created対象とするリソースを定義
75 Copyright © 2021, Oracle and/or its affiliatesOpen Policy AgentGatekeeper & Open Policy Agent 使用例OKE# cat ochacafe-s5-3/opa/banlataest.yaml3. latestタグを使用したマニフェストを適用してERROR確認apiVersion: v1kind: Podmetadata:name: pod-nginx-latestspec:containers:- name: nginx-latesttagimage: nginx:latest# kubectl apply -f ochacafe-s5-3/opa/banlataest.yamlError 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 !!
PodSecurityPolicy76 Copyright © 2022, Oracle and/or its affiliatesPodSecurityPolicyとは?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
PodSecurityPolicy77 Copyright © 2022, Oracle and/or its affiliatesPodSecurity(PodSecurity Admission) モードMode Descriptionenforce ポリシー違反により、Podは拒否audit ポリシー違反により、監査ログ(audit.log)に記録されたイベントに監査アノテーションを追加、それ以外は許可warn ポリシー違反はユーザー向けに警告、それ以外は許可Pod Security Standards ポリシーレベルProfile DescriptionPrivileged 無制限ポリシーBaseline 最小限の制限ポリシーRestricted 最も厳しい制限ポリシーPolicy Details : https://kubernetes.io/docs/concepts/security/pod-security-standards/PodSecurity admission : https://kubernetes.io/docs/concepts/security/pod-security-admission/
PodSecurityPolicy78 Copyright © 2022, Oracle and/or its affiliatesPodSecurity manifesthttps://kubernetes.io/docs/concepts/security/pod-security-admission/PodSecurity(PodSecurityAdmission) モードPod Security StandardsポリシーレベルapiVersion: v1kind: Namespacemetadata:labels:pod-security.kubernetes.io/enforce: privilegedpod-security.kubernetes.io/audit: privilegedpod-security.kubernetes.io/warn: baselinename: sample
PodSecurityPolicy79 Copyright © 2022, Oracle and/or its affiliatesPodSecurityPolicy設定可能なポリシーField Names Control Aspectprivileged Running of privileged containershostPID, hostIPC Usage of host namespaceshostNetwork, hostPorts Usage of host networking and portsvolumes Usage of volume typesallowedHostPaths Usage of the host filesystemallowedFlexVolumes Allow specific FlexVolume driversfsGroup Allocating an FSGroup that owns the pod's volumesreadOnlyRootFilesystem Requiring the use of a read only root file systemrunAsUser, runAsGroup, supplementalGroups The user and group IDs of the containerallowPrivilegeEscalation, defaultAllowPrivilegeEscalation Restricting escalation to root privilegesdefaultAddCapabilities, requiredDropCapabilities, allowedCapabilities Linux capabilitiesseLinux The SELinux context of the containerallowedProcMountTypes The Allowed Proc Mount types for the containerannotations The AppArmor profile used by containersannotations The seccomp profile used by containersforbiddenSysctls,allowedUnsafeSysctls The sysctl profile used by containershttps://kubernetes.io/docs/concepts/policy/pod-security-policy/
PodSecurityPolicy80 Copyright © 2022, Oracle and/or its affiliatesapiVersion: policy/v1beta1kind: PodSecurityPolicymetadata:name: privileged-pspannotations:seccomp.security.alpha.kubernetes.io/allowedProfileNames: '*'spec:privileged: trueallowPrivilegeEscalation: trueallowedCapabilities:- '*'volumes:- '*'hostNetwork: truehostPorts:- min: 0max: 65535hostIPC: truehostPID: truerunAsUser:rule: 'RunAsAny'seLinux:rule: 'RunAsAny'supplementalGroups:rule: 'RunAsAny'fsGroup:rule: 'RunAsAny'apiVersion: policy/v1beta1kind: PodSecurityPolicymetadata:name: restricted-pspannotations:seccomp.security.alpha.kubernetes.io/allowedProfileNames: '*'spec:privileged: falseallowPrivilegeEscalation: falseallowedCapabilities:- '*'volumes:- '*'hostNetwork: falsehostPorts:- min: 0max: 65535hostIPC: truehostPID: truerunAsUser:rule: 'MustRunAsNonRoot'seLinux:rule: 'RunAsAny'supplementalGroups:rule: 'RunAsAny'fsGroup:rule: 'RunAsAny'https://kubernetes.io/docs/concepts/policy/pod-security-policy/#example-policiesPodSecurityPolicyの許可ポリシー PodSecurityPolicyの制限ポリシー
PodSecurityPolicy81 Copyright © 2022, Oracle and/or its affiliatesdefaultPodSecurityPolicy・privileged-psp・restricted-pspClusterRole・cluster-admin
PodSecurityPolicy82 Copyright © 2022, Oracle and/or its affiliatesedit-userPodSecurityPolicyClusterRole・edit(non-psp)PodSecurityPolicy・restricted-pspClusterRole・edit(non-psp)・edit-restricted(psp)MustRunAsNonRootNonRoot Nginx Image
PodSecurityPolicy83 Copyright © 2022, Oracle and/or its affiliatesPodSecurityPolicyの使用例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はデフォルト
PodSecurityPolicy84 Copyright © 2022, Oracle and/or its affiliatesPodSecurityPolicyの使用例2.PodSecurityPolicyの制限ポリシーを適用Nginxのpod作成をしながら、adminとedit-user、それぞれの挙動をみる。動作確認1.PodSecurityPolicyの許可ポリシーを適用Nginxのpod作成をしながら、adminとedit-user、それぞれの挙動をみる。3.PodSecurityPolicyの制限ポリシーをedit-userに紐づける4.edit-userでNginxのpodが作成できるか確認
PodSecurityPolicy85 Copyright © 2022, Oracle and/or its affiliatesPodSecurityPolicyの使用例# 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 ノードからログアウト
PodSecurityPolicy86 Copyright © 2022, Oracle and/or its affiliatesPodSecurityPolicyの使用例2.PodSecurityPolicyへの権限を持たない「edit」のClusterRoleと紐づいた、ServiceAccount「edit-user」を作成# kubectl create serviceaccount edit-userServiceAccount 「edit-user」を作成manageserviceaccount/edit-user created
PodSecurityPolicy87 Copyright © 2022, Oracle and/or its affiliatesPodSecurityPolicyの使用例apiVersion:rbac.authorization.k8s.io/v1kind: ClusterRoleBindingmetadata:creationTimestamp: nullname: edit-userroleRef:apiGroup:rbac.authorization.k8s.iokind: ClusterRolename: editsubjects:- kind: ServiceAccountname: edit-usernamespace: default※clusterrole editはデフォルトであります。# kubectl create clusterrolebinding edit-user --clusterrole edit --serviceaccount default:edit-user -o yaml --dry-run=client > edit-user-crolebinding.yamlServiceAccount 「edit-user」に edit 権限付与# cat edit-user-crolebinding.yamlmanage
PodSecurityPolicy88 Copyright © 2022, Oracle and/or its affiliatesPodSecurityPolicyの使用例kubectl apply -f edit-user-crolebinding.yamlclusterrolebinding.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-useredit-user ClusterRole/edit 11mmanage
PodSecurityPolicy89 Copyright © 2022, Oracle and/or its affiliatesPodSecurityPolicyの使用例# kubectl-admin apply -f ochacafe-s5-3/psp/privileged-psp.yaml1.PodSecurityPolicyの許可ポリシーを適用apiVersion: policy/v1beta1kind: PodSecurityPolicymetadata:name: privileged-pspannotations:seccomp.security.alpha.kubernetes.io/allowedProfileNames: '*'spec:privileged: trueallowPrivilegeEscalation: trueallowedCapabilities:- '*'volumes:- '*'hostNetwork: truehostPorts:- min: 0max: 65535hostIPC: truehostPID: truerunAsUser:rule: 'RunAsAny'seLinux:rule: 'RunAsAny'supplementalGroups:rule: 'RunAsAny'fsGroup:rule: 'RunAsAny'privileged-psp.yamlhttps://kubernetes.io/docs/concepts/policy/pod-security-policy/#example-policiespodsecuritypolicy.policy/privileged-psp createdmanage
PodSecurityPolicy90 Copyright © 2022, Oracle and/or its affiliatesPodSecurityPolicyの使用例# kubectl-admin get psp適用の確認NAME PRIV CAPS SELINUX RUNASUSER FSGROUP SUPGROUP READONLYROOTFS VOLUMESprivileged-psp true * RunAsAny RunAsAny RunAsAny RunAsAny false *adminとeditでNginx Podを作成するとどうなるか?# kubectl-admin run nginx-a --image nginx:1.21 --restart=Neverpod/nginx-a created# kubectl-edit run nginx-b --image nginx:1.21 --restart=NeverError from server (Forbidden): pods "nginx-b" is forbidden: PodSecurityPolicy: unable to admit pod: []PodSecurityPolicyへの権限を持つadminはPod作成できるが、権限を持たないeditでは作成できない。manage
PodSecurityPolicy91 Copyright © 2022, Oracle and/or its affiliatesPodSecurityPolicyの使用例# kubectl-admin apply -f ochacafe-s5-3/psp/restricted-psp.yaml2.PodSecurityPolicyの制限ポリシーを適用apiVersion: policy/v1beta1kind: PodSecurityPolicymetadata:name: restricted-pspannotations:seccomp.security.alpha.kubernetes.io/allowedProfileNames: '*'spec:privileged: falseallowPrivilegeEscalation: falseallowedCapabilities:- '*'volumes:- '*'hostNetwork: falsehostPorts:- min: 0max: 65535hostIPC: truehostPID: truerunAsUser:rule: 'MustRunAsNonRoot'seLinux:rule: 'RunAsAny'supplementalGroups:rule: 'RunAsAny'fsGroup:rule: 'RunAsAny'restricted-psp.yamlhttps://kubernetes.io/docs/concepts/policy/pod-security-policy/#example-policiespodsecuritypolicy.policy/restricted-psp createdmanage
PodSecurityPolicy92 Copyright © 2022, Oracle and/or its affiliatesPodSecurityPolicyの使用例# kubectl-admin get psp適用の確認NAME PRIV CAPS SELINUX RUNASUSER FSGROUP SUPGROUP READONLYROOTFS VOLUMESprivileged-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=Neverpod/nginx-c created# kubectl-admin auth can-i use podsecuritypolicy/privileged-pspyes# kubectl-admin auth can-i use podsecuritypolicy/restricted-pspyesadminは、privileged, restricted 両方の権限を保有しているため、Podを作成できる。manage
PodSecurityPolicy93 Copyright © 2022, Oracle and/or its affiliatesPodSecurityPolicyの使用例# kubectl-edit auth can-i use podsecuritypolicy/privileged-pspno# kubectl-edit auth can-i use podsecuritypolicy/restricted-pspnoeditは、privileged-psp, restricted-psp PodSecurityPolicyの権限を持っていない# kubectl-admin create clusterrole edit-restricted --verb=use --resource=podsecuritypolicy --resource-name=restricted-pspClusterRoleを作成して、ClusterRoleBindingでeditを紐づけるclusterrole.rbac.authorization.k8s.io/edit-restricted created# kubectl-admin create clusterrolebinding edit-restricted --clusterrole=edit-restricted --serviceaccount=default:edit-userclusterrolebinding.rbac.authorization.k8s.io/edit-restricted createdmanage
PodSecurityPolicy94 Copyright © 2022, Oracle and/or its affiliatesPodSecurityPolicyの使用例# kubectl-edit auth can-i use podsecuritypolicy/restricted-pspyeseditはrestricted-psp PodSecurityPolicyの権限を持つ# kubectl-edit run nginx-d --image=nginx:1.21 --restart=Neverpod/nginx-d creatededitでNginx Podを作成# kubectl-edit get podsNAME READY STATUS RESTARTS AGEnginx-a 1/1 Running 0 140mnginx-c 1/1 Running 0 120mnginx-d 0/1 CreateContainerConfigError 0 14sNginx Pod作成できるがコンテナが起動できないmanage
PodSecurityPolicy95 Copyright © 2022, Oracle and/or its affiliatesPodSecurityPolicyの使用例# kubectl-edit describe pod nginx-drestricted-psp ポリシーには、「runAsUser」に「MustRunAsNonRoot」が定義されているのでPodが作成できない(省略)Events:Type Reason Age From Message---- ------ ---- ---- -------Normal Scheduled 5m13s default-scheduler Successfully assigned default/nginx-d to k8s-nodeWarning 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
PodSecurityPolicy96 Copyright © 2022, Oracle and/or its affiliatesPodSecurityPolicyの使用例# kubectl-edit run nginx-e --image=nginxinc/nginx-unprivileged --restart=Neverroot以外のユーザで起動できるNginx Imageに変更すると起動できるpod/nginx-e created# kubectl-edit get podsNAME READY STATUS RESTARTS AGEnginx-a 1/1 Running 0 176mnginx-c 1/1 Running 0 155mnginx-d 0/1 CreateContainerConfigError 0 35mnginx-e 1/1 Running 0 17snginx-unprivileged Image https://hub.docker.com/r/nginxinc/nginx-unprivilegedmanage
Container Runtime Sandboxes97 Copyright © 2022, Oracle and/or its affiliatesContainer Runtime おさらいCRI Container Runtime= 高レベルランタイムOCI Container Runtime = 低レベルランタイムコンテナイメージ、ルートファイルシステム、ネットワークなどを担う実体はバイナリで、隔離環境(コンテナ)作成を担う
Container Runtime Sandboxes98 Copyright © 2022, Oracle and/or its affiliatesContainer Runtime おさらいCRI CRI Container Runtime OCI Container RuntimePodContainerContainer Registry
Container Runtime Sandboxes99 Copyright © 2022, Oracle and/or its affiliatesSentry というGoで作られたプログラムがカーネルとしてアプリケーションからの syscall を処理ホストカーネルに到達する syscall が大幅に縮小し、攻撃対象を狭めることでセキュリティを高めるhttps://cloud.google.com/blog/ja/products/containers-kubernetes/how-gvisor-protects-google-cloud-services-from-cve-2020-14386
Container Runtime Sandboxes100 Copyright © 2022, Oracle and/or its affiliates仮想化の技術を利用して作成した軽量なハイパーバイザーの上で動作し、コンテナ個別にカーネルを動作させることで、コンテナ間の分離を図り、セキュリティを高めるhttps://katacontainers.io/learn/
Container Runtime Sandboxes101 Copyright © 2022, Oracle and/or its affiliatesRuntime ClassRuntime ClassKubernetesには、gVisor や Kata Containers のような OCI Container Runtime を Pod 起動時に選択できる仕組みがあり、それを利用してコンテナランタイムレベルでセキュリティ対策を行う
Container Runtime Sandboxes102 Copyright © 2022, Oracle and/or its affiliatesRuntime ClassRuntime Class を利用する上での必要事項• Kubernetes Admission Controller において RuntimeClass を有効• マニフェストで RuntimeClass を定義、そして適用• CRI Container Runtime で OCI Container Runtime の設定
Container Runtime Sandboxes103 Copyright © 2022, Oracle and/or its affiliatesRuntime 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 RuntimeContainer RegistryPod
Container Runtime Sandboxes104 Copyright © 2022, Oracle and/or its affiliatesRuntime 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.yamlControle Plane ノードからログアウト
Container Runtime Sandboxes105 Copyright © 2022, Oracle and/or its affiliatesRuntime Class の使用例2.gVisor の RuntimeClass マニフェストの作成および適用manageapiVersion: node.k8s.io/v1beta1kind: RuntimeClassmetadata:name: gvisorhandler: runsc# cat ochacafe-s5-3/runtimeclass/runtimeclass.yamlRuntimeClass名を定義指定する CRI Container Runtime を定義runsc = gVisor# kubectl apply -f ochacafe-s5-3/runtimeclass/runtimeclass.yamlruntimeclass.node.k8s.io/gvisor created
Container Runtime Sandboxes106 Copyright © 2022, Oracle and/or its affiliatesRuntime Class の使用例apiVersion: v1kind: Podmetadata:labels:run: gvisor-nginxname: gvisor-nginxspec:runtimeClassName: gvisorcontainers:- image: nginx:1.21name: gvisor-nginxrestartPolicy: Never# cat ochacafe-s5-3/runtimeclass/gvisor-nginx.yamlpod.spec.runtimeClassName に RuntimeClass名を定義# kubectl apply -f ochacafe-s5-3/runtimeclass/gvisor-nginx.yamlpod/gvisor-nginx created3.Nginx Pod を gVisor 指定して起動 manage
Container Runtime Sandboxes107 Copyright © 2022, Oracle and/or its affiliatesRuntime Class の使用例# kubectl exec -it gvisor-nginx -- /bin/bash「gvisor-nginx」 Pod に接続して、gVisor 起動を確認[email protected]:/# 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
Supply Chain SecurityTrivy108 Copyright © 2022, Oracle and/or its affiliates
Trivy109 Copyright © 2022, Oracle and/or its affiliatesコンテナイメージとセキュリティ脆弱性を持つコンテナイメージをもとに起動したコンテナは脆弱性を含むため、イメージを保護する必要があるパブリックなコンテナイメージレジストリにあるコンテナイメージが安全とは限らないOSSコミュニティの公式イメージだから安心できるとも限らない
Trivy110 Copyright © 2022, Oracle and/or its affiliatesTrivyとは?コンテナイメージの脆弱性を静的に診断するツールで、OSパッケージ情報、アプリケーションの依存関係などから脆弱性を検出、Aqua Security社がOSSとして公開している主な特徴• ワンバイナリでインストール、操作が簡単• 脆弱性データベースから診断• スキャンと結果出力が速い• コンテナイメージだけでなくローイカルファイルシステムやリモートgitリポジトリなどサポートhttps://github.com/aquasecurity/trivy
Trivy111 Copyright © 2022, Oracle and/or its affiliatesTrivyの使用例Kubernetesクラスタ上で稼働しているPodからイメージを調べて、Trivyで脆弱性スキャンを実行する2.稼働しているPod内のコンテナイメージを確認1.Trivyのダウンロード3.Trivyでスキャンをかけて、HIGHとCRITICALが表示されるイメージを見つける
Trivy112 Copyright © 2022, Oracle and/or its affiliatesTrivyの使用例1.Trivyのダウンロード# trivy -v# curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin v0.24.0Version: 0.24.0manageサンプルPodのデプロイ# kubectl apply -f ochacafe-s5-3/trivy/pod/oraclelinux createddeployment.apps/sample-go-app createdservice/sample-go-app-service createdpod/ubuntu created
Trivy113 Copyright © 2022, Oracle and/or its affiliatesTrivyの使用例2.稼働しているPod内のコンテナイメージを確認# kubectl get podsNAME READY STATUS RESTARTS AGEOraclelinux 1/1 Running 0 11msample-go-app-548b756854-x7x8g 1/1 Running 0 33mUbuntu 1/1 Running 0 24m# kubectl get pods -o yaml | grep image:image: oraclelinux:8.5image: docker.io/library/oraclelinux:8.5- image: icn.ocir.io/orasejapan/ochacafe5-3:armimage: icn.ocir.io/orasejapan/ochacafe5-3:armimage: ubuntu:21.10image: docker.io/library/ubuntu:21.10manage
Trivy114 Copyright © 2022, Oracle and/or its affiliatesTrivyの使用例3.Trivyでスキャンをかけて、HIGHとCRITICALが表示されるイメージを見つける# trivy image --severity HIGH,CRITICAL docker.io/library/oraclelinux:8.5manage# trivy image --severity HIGH,CRITICAL docker.io/library/ubuntu:21.10# trivy image --severity HIGH,CRITICAL icn.ocir.io/orasejapan/ochacafe5-3:arm
Monitoring, Logging and Runtime SecurityFalco115 Copyright © 2022, Oracle and/or its affiliates
Falco116 Copyright © 2022, Oracle and/or its affiliatesコンテナランタイムセキュリティPrevention/Enforcement事前に 「誰が何をするか」 を制御する仕組みDetection/AuditKubernetesクラスタ上で、「何が起こっているのか」を検知して対処する仕組み• Network Policy• RBAC• PodSecurityPolicy• OPA(Admission Control)Prevention/Enforcement における事前の対策では防げない場合の対策起きた事象を検知、追跡して、原因を特定する仕組みが必要
Falco117 Copyright © 2022, Oracle and/or its affiliatesFalcoとは?• カーネルからのシステムコールを解析して、定義したルールに違反した意図しない振る舞いを検知• 設定された出力対象(Syslog、標準出力など)にアラートする• 何を実行したかなどを追跡して、原因究明を支援• Sysdig社によりOSSとして公開されている(CNCF Incubating Project)https://github.com/falcosecurity/falco予期せぬアプリケーションの挙動を検知し、ランタイムレベルで脅威をアラートするランタイムセキュリティツール
Falco118 Copyright © 2022, Oracle and/or its affiliatesFalco Architecturehttps://www.cncf.io/wp-content/uploads/2020/08/Kubernetes-Runtime-Security-with-Falco-and-Sysdig.pdfUser SpaceKernel Space解析アラート
Falco119 Copyright © 2022, Oracle and/or its affiliatesFalco Default Ruleshttps://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
Falco120 Copyright © 2022, Oracle and/or its affiliatesFalco 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/
Falco121 Copyright © 2022, Oracle and/or its affiliatesFalco の使用例Node の仮想マシンに Falco をインストール、httpd の Pod(コンテナ)内で操作して Syslog の結果を確認する。2. テスト用のPodを起動後、Pod(コンテナ)内およびNodeで「/etc/」ディレクトリ内にファイル作成を試みる1.Node の仮想マシンで Falco をインストール3. 「/var/log/syslog」の Falco からの出力を確認する※ Falco は Arm をサーポートしていない(2022年3月時点)ので、デモは AMD 環境で行います。
Falco122 Copyright © 2022, Oracle and/or its affiliatesFalco の使用例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
Falco123 Copyright © 2022, Oracle and/or its affiliatesFalco の使用例2. テスト用のPodを起動後、Pod(コンテナ)内でルール違反をして、ログを確認# kubectl apply -f ochacafe-s5-3/falco/httpd.yamlpod/apache created# kubectl exec -it apache -- touch /etc/test.conf「/etc/」ディレクトリ配下に、ファイルを作成するmanage
Falco124 Copyright © 2022, Oracle and/or its affiliatesFalco の使用例# cat /var/log/syslog | grep falcoNodeの「/etc/」ディレクトリ配下に作った場合のSyslogMar 3 11:11:57 k8s-node-k-945573 falco: 11:11:57.885578617: Error File below /etc opened for writing (user=rootuser_loginuid=1001 command=touch /etc/test2.conf parent=bash pcmdline=bash file=/etc/test2.conf program=touchgparent=sudo ggparent=bash gggparent=node container_id=host image=)# touch /etc/test2.conf# cat /var/log/syslog | grep falcoNode側で「/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=rootuser_loginuid=-1 command=touch /etc/test.conf parent= pcmdline= file=/etc/test.conf program=touchgparent= ggparent= gggparent= container_id=a723e15034a5 image=docker.io/library/httpd)
Falco125 Copyright © 2022, Oracle and/or its affiliatesFalco の使用例ルール定義を確認# vim /etc/falco/falco_rules.yaml(省略)- rule: Write below etcdesc: an attempt to write to any file below /etccondition: write_etc_commonoutput: "File below /etc opened for writing (user=%user.name user_loginuid=%user.loginuid command=%proc.cmdlineparent=%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: ERRORtags: [filesystem, mitre_persistence](省略)
参考資料126 Copyright © 2022, Oracle and/or its affiliates
参考資料127 Copyright © 2022, Oracle and/or its affiliatesKubernetes CKS 2022 Complete Course - Theory – Practicehttps://www.udemy.com/course/certified-kubernetes-security-specialist/Kubernetes Documentationhttps://kubernetes.io/docs/home/KubernetesのSeccompDefaultを試したhttps://qiita.com/uesyn/items/3fc1b25eafa0939aebb8PodSecurityPolicyの廃止に備えて、一足先にPodSecurity Admissionを試してみよう!https://qiita.com/uesyn/items/cf47e12fba5e5c5ea25fKubernetesのRuntime Classについて知ろうhttps://event.cloudnativedays.jp/cndo2021/talks/841Kubernetes: RBACの設定におけるAPIリソースhttps://qiita.com/tkusumi/items/300c566a74b6b64e7e89デモ環境https://github.com/oracle-japan/ochacafe-s5-3CI/CD最新事情(OPA)https://www.youtube.com/watch?v=K62nFSvHo60https://speakerdeck.com/oracle4engineer/oracle-cloud-hangout-cafe-cicdzui-xin-shi-qing
Thank you128 Copyright © 2022, Oracle and/or its affiliates | Confidential: Internal/Restricted/Highly Restricted [Date]