{"id":27647204,"url":"https://github.com/techiescamp/cks-certification-guide","last_synced_at":"2025-04-24T01:49:03.469Z","repository":{"id":286269445,"uuid":"877698314","full_name":"techiescamp/cks-certification-guide","owner":"techiescamp","description":"This comprehensive CKS learning path repo equips aspiring Kubernetes administrators with all the knowledge and resources to ace the CKS exam on the first try. It includes valuable study materials, shortcuts, revision commands etc. Pass the CKS and take your Kubernetes security skills to the next level today!","archived":false,"fork":false,"pushed_at":"2025-04-05T10:41:20.000Z","size":34,"stargazers_count":20,"open_issues_count":0,"forks_count":2,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-24T01:48:57.779Z","etag":null,"topics":["certification","cks","cks-exam","cks-exam-preparation","kubernetes"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/techiescamp.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-10-24T05:00:33.000Z","updated_at":"2025-04-21T05:19:37.000Z","dependencies_parsed_at":"2025-04-05T11:30:06.133Z","dependency_job_id":"4a26dcb0-ffb5-4842-8811-a998f86636f8","html_url":"https://github.com/techiescamp/cks-certification-guide","commit_stats":null,"previous_names":["techiescamp/cks-certification-guide"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/techiescamp%2Fcks-certification-guide","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/techiescamp%2Fcks-certification-guide/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/techiescamp%2Fcks-certification-guide/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/techiescamp%2Fcks-certification-guide/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/techiescamp","download_url":"https://codeload.github.com/techiescamp/cks-certification-guide/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250546024,"owners_count":21448255,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["certification","cks","cks-exam","cks-exam-preparation","kubernetes"],"created_at":"2025-04-24T01:49:02.768Z","updated_at":"2025-04-24T01:49:03.449Z","avatar_url":"https://github.com/techiescamp.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Ultimate Certified Kubernetes Security Specialist (CKS) Preparation Guide - V1.31 (2025)\n\n## Hit the Star! :star:\n\nIf you are planning to use this repo for reference, please hit the star. Thanks!\n\n## CKS Exam Overview\n\nThe Certified Kubernetes Security Specialist (CKS) exam has a duration of 2 hours.\nTo pass the exam, candidates need to achieve a score of at least 66%.\nThe exam will be on Kubernetes version 1.31.\nOnce the certificate is earned, the CKS certification remains valid for 2 years. The cost to take the exam is $395 USD.\n\n## CKS Exam Coupon (30% Off Exclusive Discount)\n\n\u003e **CKA Price Update:** The CKS exam price will increase to $435 in January 2025. Take advantage of the current discount and complete the exam within 12 months to maximize your savings.\n\nTo save on CKS exam registration, use the following coupon code.\n\n**Coupon:** Use code **DCUBE30** at [kube.promo/cks](https://kube.promo/cks)\n\n## Table of Contents\n\n1. [Cluster Setup (15%)](#)\n   - [Use Network security policies to restrict cluster level access](#)\n   - [Use CIS benchmark to review the security configuration of Kubernetes components (etcd, kubelet, kubedns, kubeapi)](#)\n   - [Properly set up Ingress with TLS](#)\n   - [Protect node metadata and endpoints](#)\n   - [Verify platform binaries before deploying](#)\n\n2. [Cluster Hardening (15%)](#)\n   - [Use Role Based Access Controls to minimize exposure](#)\n   - [Exercise caution in using service accounts e.g. disable defaults, minimize permissions on newly created ones](#)\n   - [Restrict access to Kubernetes API](#)\n   - [Upgrade Kubernetes to avoid vulnerabilities](#)\n\n3. [System Hardening (10%)](#)\n   - [Minimize host OS footprint (reduce attack surface)](#)\n   - [Using least-privilege identity and access management](#)\n   - [Minimize external access to the network](#)\n   - [Appropriately use kernel hardening tools such as AppArmor, seccomp](#)\n\n4. [Minimize Microservice Vulnerabilities (20%)](#)\n   - [Use appropriate pod security standards](#)\n   - [Manage Kubernetes secrets](#)\n   - [Understand and implement isolation techniques (multi-tenancy, sandboxed containers, etc.)](#)\n   - [Implement Pod-to-Pod encryption using Cilium](#)\n\n5. [Supply Chain Security (20%)](#)\n   - [Minimize base image footprint](#)\n   - [Understand your supply chain (e.g. SBOM, CI/CD, artifact repositories)](#)\n   - [Secure your supply chain (permitted registries, sign and validate artifacts, etc.)](#)\n   - [Perform static analysis of user workloads and container images (e.g. Kubesec, KubeLinter)](#)\n\n6. [Monitoring, Logging and Runtime Security (20%)](#)\n   - [Perform behavioral analytics to detect malicious activities](#)\n   - [Detect threats within physical infrastructure, apps, networks, data, users and workloads](#)\n   - [Investigate and identify phases of attack and bad actors within the environment](#)\n   - [Ensure immutability of containers at runtime](#)\n   - [Use Kubernetes audit logs to monitor access](#)\n\n## CKS Exam Detailed Study Guide \u0026 References\n\nCKS Certification Exam has the following key domains:\n\n## 1. Cluster Setup (15%)\n\nFollowing are the subtopics under Cluster Setup\n\n### Restrict Pod to Pod communication using Network Policy\n\u003e [Network Policy](https://kubernetes.io/docs/concepts/services-networking/network-policies/)  : Understand the restriction of the Pod to Pod communication.\n\n```yaml\n# Create a Deny all Network Policy\napiVersion: networking.k8s.io/v1\nkind: NetworkPolicy\nmetadata:\n  name: deny-all\n  namespace: default\nspec:\n  podSelector: {}\n  policyTypes:\n  - Ingress\n  - Egress\n```\n### Protecting Metadata Server access to the cloud provider Kubernetes cluster using Network Policy\n\u003e [Network Policy](https://kubernetes.io/docs/concepts/services-networking/network-policies/)  : Understand the IP Block parameter in the Network Policy.\n```yaml\n# Create a Network Policy with the IP Block\napiVersion: networking.k8s.io/v1\nkind: NetworkPolicy\nmetadata:\n  name: metadata-network-policy\n  namespace: default\nspec:\n  podSelector: {}\n  policyTypes:\n  - Egress\n  egress:\n  - to:\n    - ipBlock:\n        cidr: 0.0.0.0/0\n        except:\n        - 169.254.169.254/32\n```\n### CIS Benchmark to analyze the cluster components\n\u003e [CIS Benchmark]() : Analyze the cluster components using CIS Benchmark tool Kube Bench.\n```bash\n# CIS Benchmark Best Practices\n./kube-bench --config-dir /root/cfg --config /root/cfg/config.yaml\n```\n```bash\n# Analyze the benchmark of specific check\n./kube-bench --config-dir /root/cfg --config /root/cfg/config.yaml --check 1.4.1\n```\n\n### Secure the Ingress with TLS\n\u003e [Ingress](https://kubernetes.io/docs/concepts/services-networking/ingress/) : Creating an Ingress object with the TLS termination.\n```bash\n# Create a TLS Certificate \u0026 Key\nopenssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout tls.key -out tls.crt\n```\n```bash\n# Create a TLS secret with Certificate \u0026 Key\nkubectl -n tls create secret tls tls-secret --cert=tls.crt --key=tls.key\n```\n```yaml\n# Create Ingress object with TLS\napiVersion: networking.k8s.io/v1\nkind: Ingress\nmetadata:\n  name: tls-ingress\n  namespace: tls\n  annotations:\n    nginx.ingress.kubernetes.io/rewrite-target: /\nspec:\n  ingressClassName: nginx\n\ttls:\n  - hosts:\n      - dev.techiescamp.com\n    secretName: tls-secret\n  rules:\n  - host: dev.techiescamp.com\n    http:\n      paths:\n      - path: /frontend\n        pathType: Prefix\n        backend:\n          service:\n            name: frontend\n            port:\n              number: 80\n      - path: /backend\n        pathType: Prefix\n        backend:\n          service:\n            name: backend\n            port:\n              number: 80\n```\n### Verify Kubernetes Platform Binaries before deploying\n\n```bash\n# Check the current version of the Kubernetes component\nkubectl --version\n\n# Check the current binary hash value\nsha512sum $(which kubectl)\n\n# Download the cluster component\nwget https://dl.k8s.io/v1.31.0/kubernetes-server-linux-amd64.tar.gz\n\n# Extract the package\ntar -xvf kubernetes-server-linux-amd64.tar.gz\n\n# Verify the Platform Binaries using Hash\nsha512sum kubernetes/server/bin/kubelet\n```\n\n## 2. Cluster Hardening (15%)\n\n### RBAC, Certificate \u0026 Certificate Signing Request\n\u003e [Certificates and Certificate Signing Request](https://kubernetes.io/docs/reference/access-authn-authz/certificate-signing-requests/) : Create and issue a certificate for user\n```bash\n# Create private key\nopenssl genrsa -out myuser.key 2048\nopenssl req -new -key myuser.key -out myuser.csr -subj \"/CN=myuser\"\n\n# Create Certificate Signing Request (CSR)\napiVersion: certificates.k8s.io/v1\nkind: CertificateSigningRequest\nmetadata:\n  name: myuser\nspec:\n  request: \n  signerName: kubernetes.io/kube-apiserver-client\n  expirationSeconds: 86400  # one day\n  usages:\n  - client auth\n\n# Copy base64 encoded CSR file content\ncat myuser.csr | base64 | tr -d \"\\n\"\n\n# Paste the content to `spec.request`\napiVersion: certificates.k8s.io/v1\nkind: CertificateSigningRequest\nmetadata:\n  name: myuser\nspec:\n  request: \u003cbase64 encoded csr content\u003e\n  signerName: kubernetes.io/kube-apiserver-client\n  expirationSeconds: 86400  # one day\n  usages:\n  - client auth\n\n# Apply the CSR manifest\nkubectl apply -f csr.yaml\n\n# Get the list of CSR\nkubectl get csr\n\n# Approve the CSR\nkubectl certificate approve myuser\n\n# Export the certificate\nkubectl get csr myuser -o jsonpath='{.status.certificate}'| base64 -d \u003e myuser.crt\n\n# Create Role\nkubectl create role developer --verb=create --verb=get --verb=list --verb=update --verb=delete --resource=pods\n\n# Create Role Binding\nkubectl create rolebinding developer-binding-myuser --role=developer --user=myuser\n\n# Test the role to the user\nkubectl auth can-i delete pods --as myuser\nkubectl auth can-i delete deployments --as myuser\n\n# Add new credentials\nkubectl config set-credentials myuser --client-key=myuser.key --client-certificate=myuser.crt --embed-certs=true\n\n# Add context\nkubectl config set-context myuser --cluster=kubernetes --user=myuser\n\n# List contexts\nkubectl config get-context\n\n# Change context\nkubectl config use-context myuser\n```\n\n### Role Based Access Control\n\u003e [Bind RBAC with Service Account](https://kubernetes.io/docs/reference/access-authn-authz/rbac/) : Understand the Role Based Access Control Authorization to Service Accounts\n```bash\n# Create SA\nkubectl create sa app-sa\n\n# Create Cluster Role\nkubectl create clusterrole app-cr --verb list --resource pods\n\n# Create Role Binding\nkubectl create rolebinding app-rb --clusterrole app-cr --serviceaccount default:app-sa\n\n# List Role Binding\nkubectl get rolebinding\n\n# Describe Role Binding\nkubectl describe rolebinding app-rb\n\n# Check the access\nkubectl auth can-i list pods --as system:serviceaccount:default:app-sa\n\n# Create a Pod with the Service Account\napiVersion: v1\nkind: Pod\nmetadata:\n  labels:\n    run: app-sa\n  name: app-sa\nspec:\n  serviceAccountName: app-sa\n  containers:\n  - image: nginx\n    name: app-sa\n    ports:\n    - containerPort: 80\n```\n### Service Account Token Automount\n\u003e [Service Account](#https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/) : Disable the automounting of the Service Account Token. \n```bash\n# Disable Service Account Token Automounting\napiVersion: v1\nkind: Pod\nmetadata:\n  labels:\n    run: app-sa\n  name: app-sa\nspec:\n  serviceAccountName: app-sa\n  automountServiceAccountToken: false\n  containers:\n  - image: nginx\n    name: app-sa\n    ports:\n    - containerPort: 80\n```\n### Disable the Service Account Token Automount at the Service Account level\n```bash\n# Create a new Service Account or edit an existing Service Account\napiVersion: v1\nautomountServiceAccountToken: false\nkind: ServiceAccount\nmetadata:\n  name: default\n  namespace: two\n\n# To check the automouting after the Pod deployment\nk exec test-pod -- cat /var/run/secrets/kubernetes.io/serviceaccount/token\n```\n### Upgrade Kubernetes clusters.\n\u003e [Perform Cluster Version upgrade Using Kubeadm](https://techiescamp.com/courses/certified-kubernetes-administrator-course/lectures/55120133) : Managing the lifecycle involves upgrading clusters, managing control plane nodes, and ensuring consistency across versions.\n\n## 3. System Hardening (10%)\n### Disable Service\n```bash\n# Stop a running service\nsystemctl stop vsftpd\n\n# Check the status of the service\nsystemctl status vsftpd\n```\n### Remove Unused Packages\n```bash\n# Remove the packages\nsudo apt remove vsftpd\n```\n### Disable Open Ports \n```bash\n# Identify open ports and related processes\nss -tlpn\n\n# Filter a process using the open port number\nss -tlpn | grep :80\n\n# List the Open files for the Port and the Process IDs\nlsof -i :80\n\n# Check the path of the packege\nls -l /proc/12345/exe\n\n# Kill the process using the PID\nkill 12345\n\n# Remove the packege\nrm /usr/bin/app01\n```\n\n### Kernel Hardening using AppArmor\n\u003e[Restrict container access to resources](https://kubernetes.io/docs/tutorials/security/apparmor/) : Minimize the container access to reduce the access to the host resources.\n```bash\n# To list the default and custom loaded profiles\naa-status\n\n# Profile modes - 'enforce' and `complain'\n# Example profile file which is restrict the write function to nodes\n\n\n#include \u003ctunables/global\u003e\n\nprofile k8s-apparmor-example-deny-write flags=(attach_disconnected) {\n  #include \u003cabstractions/base\u003e\n\n  file,\n\n  # Deny all file writes.\n  deny /** w,\n}\n\n# To load the profile ('enforce' mode is default)\n\napparmor_parser /etc/apparmor.d/k8s-apparmor-example-deny-write\n\n# Associate the profile to a Pod\napiVersion: v1\nkind: Pod\nmetadata:\n  name: hello-apparmor\nspec:\n  securityContext:\n    appArmorProfile:\n      type: Localhost\n      localhostProfile: k8s-apparmor-example-deny-write\n  containers:\n  - name: hello\n    image: busybox:1.28\n    command: [ \"sh\", \"-c\", \"echo 'Hello AppArmor!' \u0026\u0026 sleep 1h\" ]\n\n```\n\u003e Note: The profiles should be present in the worker nodes or where the workloads should be in.\n\n## 4. Minimize Microservice Vulnerabilities (20%)\n### Run Container as Non-Root User \n\u003e [Security context to enable non-root containers](https://kubernetes.io/docs/concepts/security/pod-security-standards/) : Understand how to run a container with a non-root user.\n```bash\n# Adding security context to run the container as non root user\napiVersion: v1\nkind: Pod\nmetadata:\n  labels:\n    run: test-pod\n  name: test-pod\nspec:\n  containers:\n  - image: bitnami/nginx\n    name: test-pod\n  securityContext:\n    runAsNonRoot: true\n```\n\n### Run a Container with Specific User ID and Group ID \n\u003e [Run a container with specifice user](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/) : Learn to deploy a container with least privilege and high security.\n```bash\n# Run container with specific user id and group id\napiVersion: v1\nkind: Pod\nmetadata:\n  labels:\n    run: test-pod\n  name: test-pod\nspec:\n  containers:\n  - image: busybox\n    name: test-pod\n    command: [\"sh\", \"-c\", \"sleep 1d\"]\n  securityContext:\n    runAsUser: 1000\n    runAsGroup: 1000\n```\n### Create a Pod with lease privileges\n\u003e [Disable privilege escalation to a Pod](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/) : Prevent containers from unauthorized access.\n```bash\n# Create a container with least privileges\napiVersion: v1\nkind: Pod\nmetadata:\n  name: security-context-demo\nspec:\n  containers:\n  - name: sec-ctx-demo\n    image: busybox:1.28\n    command: [ \"sh\", \"-c\", \"sleep 1h\" ]\n    securityContext:\n      allowPrivilegeEscalation: false\n      privileged: false\n```\n### Pod Security Admission\n\u003e [Enable Pod Secuurity Admission](https://kubernetes.io/docs/concepts/security/pod-security-admission/) : Enforce the Pod Security Standards using Pod Security Admission.\n```bash\n# Add label to the namespace for the PSA\nk label namespace dev pod-security.kubernetes.io/enforce=restricted\n\n# Enable Pod Security Admission Plugin in the Kube Apiserver\nvim /etc/kubernetes/manifests/kube-apiserver\n\n- --enable-admission-plugins=podSecurity\n```\n### ECTD encryption\n\u003e [Encrypt the data at rest](https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/) : Secure the confidential data by encrypting.\n```bash\n# Create a randon base64 encoded key\necho -n \"encryptedsecret\" | base64\n\n# Create an Encryption configuration file with the encoded key\napiVersion: apiserver.config.k8s.io/v1\nkind: EncryptionConfiguration\nresources:\n  - resources:\n      - secrets\n    providers:\n      - aesgcm:\n          keys:\n            - name: key1\n              secret: ZW5jcnlwdGVkc2VjcmV0\n      - identity: {}\n\n# Add Encryption Provider Config parameter and volumes on the Kube Api server\n\n--encryption-provider-config=/etc/kubernetes/etcd/ec.yaml\n\nspec\n  volumes:\n  - name: ec\n    hostPath: \n      path: /etc/kubernetes/etcd\n      type: DirectoryOrCreate\n\n  containers:\n    volumemounts:\n    - name: ec\n      mountPath: /etc/kubernetes/etcd\n      readonly: true\n\n# Wait to the Kube API server to restart\nwatch crictl ps\n\n# Replace the secret\nkubectl get secret test-secret -o json | kubectl replace -f -\n\n# Check the encrypted secret \nETCDCTL_API=3 etcdctl \\\n   --cacert=/etc/kubernetes/pki/etcd/ca.crt   \\\n   --cert=/etc/kubernetes/pki/etcd/server.crt \\\n   --key=/etc/kubernetes/pki/etcd/server.key  \\\n   get /registry/secrets/default/test-secret | hexdump -C\n```\n### Container Runtime sandboxed\n\u003e [Runtime Class](https://kubernetes.io/docs/concepts/containers/runtime-class/) : Improve isolation and security using sandbox container runtimes for important workloads\n```bash\n# Create a Runtime Class - gVisor\napiVersion: node.k8s.io/v1\nkind: RuntimeClass\nmetadata:\n  name: gvisor\nhandler: runsc\n\n# Create a Pod with Runtime Class\napiVersion: v1\nkind: Pod\nmetadata:\n  labels:\n    run: rtc-pod\n  name: rtc-pod\nspec:\n  runtimeClassName: gvisor\n  containers:\n  - image: nginx\n    name: rtc-pod\n    ports:\n    - containerPort: 80\n\n# To check the container runtime\nk exec rtc-pod -- dmesg\n```\n\n### Cilium Network Policy \n\u003e [Endpoint Based Network Policy](https://docs.cilium.io/en/latest/security/policy/language/#endpoints-based) : Configure Cilium Network Policy to enable Pod to Pod encryption.\n```bash\n# Crete Cilium Network Policy to all outgoing traffic to a particular namespace and particular label\napiVersion: \"cilium.io/v2\"\nkind: CiliumNetworkPolicy\nmetadata:\n  name: frontend\n  namespace: frontend\nspec:\n  endpointSelector:\n    matchLabels: {}\n  egress:\n  - toEndpoints:\n    - matchLabels:\n        io.kubernetes.pod.namespace: backend\n        run: b-pod-1\n```\n## 5. Supply Chain Security (20%)\n\n### Image Digest to run a Pod\n\u003e [Run a Pod with Image Digest](https://kubernetes.io/docs/concepts/containers/images/) : Ensure the immutability and consistency of pulling the same image version using image digest.\n```bash\n# Run a Pod using the image digest\nk run digest-pod --image nginx@sha256:5ddf6decf65ea64c0492cd38098a9db11cb0da682478d3e0cfa8cdfdeb112f30\n\n# To get the image digest of a Pod\nk describe pod dig-pod | grep -iE \"Image ID\"\n```\n\n### Image Policy Webhook Admission Controller Plugin\n\u003e [Admission Control](https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/) : Enforce the custom image validation policies through external webhook to improve security and complaince.\n```bash\n# Create Admission Controller configuration file\napiVersion: apiserver.config.k8s.io/v1\nkind: AdmissionConfiguration\nplugins:\n  - name: ImagePolicyWebhook\n    configuration:\n      imagePolicy:\n        kubeConfigFile: \u003cpath-to-kubeconfig-file\u003e\n        allowTTL: 50\n        denyTTL: 50\n        retryBackoff: 500\n        defaultAllow: false\n\n# Find the kubeconf path\nfind / -name kubeconf\n\n# Update the Admission controller configuration and kubeconf path\napiVersion: apiserver.config.k8s.io/v1\nkind: AdmissionConfiguration\nplugins:\n  - name: ImagePolicyWebhook\n    configuration:\n      imagePolicy:\n        kubeConfigFile: /etc/kubernetes/policywebhook/kubeconf\n        allowTTL: 50\n        denyTTL: 50\n        retryBackoff: 500\n        defaultAllow: false\n\n# Image Policy configuration file\napiVersion: v1\nkind: Config\npreferences: {}\nclusters:\n- name: image-check-webhook\n  cluster:\n    certificate-authority: /etc/kubernetes/policywebhook/external-cert.pem \n    server: https://localhost:1234    \ncontexts:\n- context:\n    cluster: image-checker-webhook\n    user: api-server\n  name: image-checker-webhook\ncurrent-context: image-checker-webhook\n\nusers:\n- name: api-server\n  user:\n    client-certificate: /etc/kubernetes/policywebhook/apiserver-client-cert.pem \n    client-key:  /etc/kubernetes/policywebhook/apiserver-client-key.pem          \n\n# Enable and configure Image Policy Admission Plugin\n\nvim /etc/kubernetes/manifests/kube-apiserver\n\n--enable-admission-plugins=ImagePolicyWebhook\n--admission-control-config-file=/etc/kubernetes/policywebhook/admission-config.yaml\n```\n\u003e Note: Admission Configuration could be in JSON format as well\n\n### Scan Kubernetes manifests using Kubesec\n```bash\n# Scan manifest using binary\nkubesec scan pod.yaml\n\n# Scan using Kubesec docker image\ndocker run -i kubesec/kubesec:512c5e0 scan /dev/stdin \u003e pod.yaml\n```\n### Generate Software Bills of Materials (SBOMs) using bom\n\u003e [bom](https://github.com/kubernetes-sigs/bom) :\nScan the container image using bom to generate SBOM.\n```bash\n# Scan container image using Trivy\nbom generate --image nginx:1.19.1-alpine-perl\n\n# Scan the image and create Software Bills of Material\nbom generate --image nginx:1.19.1-alpine-perl --output report.spdx \n```\n## 6. Monitoring, Logging and Runtime Security (20%)\n### Behavior analysis using Falco\n\u003e [Monitor and alert suspicious behavior in kubernets](https://falco.org/docs/reference/rules/supported-fields/) : Monitor runtime security threats and create alerts to inform the suspicios behavior.\n```bash\n# Check the Falco status\nsystemctl status falco\n\n# To list the Falco parameters\nfalco --list\n\n# Override existing rules before modifying \ncp /etc/falco/falco_rules.yaml /etc/falco/falco_rules.local.yaml\n\n# Edit the rule and restart the service\nsystemctl restart falco\n\n# Create a Pod and execuite the shell for testing\nk run test-pod --image nginx\n\nk exec test-pod -- sh\n\n# Check the falo logs\njournalctl -fu falco\n\ncat /var/log/syslog | grep falco\n```\n\n### Make Secret as environment variable inside the Pod\n\u003e [Secret as Env](https://kubernetes.io/docs/tasks/inject-data-application/distribute-credentials-secure/) : Access the secret as environment variable inside the container.\n```bash\n# Create a secret\nk create secret generic secret-1 --from-literal password=admin@123\n\n# Create Secret as environment variable\napiVersion: v1\nkind: Pod\nmetadata:\n  name: env-single-secret\nspec:\n  containers:\n  - name: envars-test-container\n    image: nginx\n    env:\n    - name: SECRET_PASSWORD\n      valueFrom:\n        secretKeyRef:\n          name: secret-1\n          key: password\n\n# To check the secret inside the Pod\nk exec -it env-single-secret -- env\n```\n\n### Mount Secret as Volume \n\u003e [Mount secret as volume](https://kubernetes.io/docs/concepts/configuration/secret/) : Mount the Secret as volume to improve the security and dynamic updates.\n```bash\n# Mount secret as volume in the Pod\napiVersion: v1\nkind: Pod\nmetadata:\n  name: volume-secret-pod\nspec:\n  volumes:\n    - name: secret-volume\n      secret:\n        secretName: secret-2\n  containers:\n    - name: nginx\n      image: nginx\n      volumeMounts:\n        - name: secret-volume\n          readOnly: true\n          mountPath: \"/etc/secret-volume\"\n\n# To check the mounted secret\nk exec -it volume-secret-pod -- ls /etc/secret/volume\n```\n\n### Make the container immutable using the read only root file system \n\u003e [Security Context](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/) : Prevent the container root file system from the modification. \n```bash\n# Create a Pod with ReadOnlyRooFileSystem security context\napiVersion: v1\nkind: Pod\nmetadata:\n  labels:\n    run: immutable-pod\n  name: immutable-pod\nspec:\n  containers:\n  - image: nginx\n    name: immutable-pod\n    securityContext:\n      readOnlyRootFilesystem: true\n```\n\u003e Note: If the container needs to write something then if we are using the Read only root file system, the Pod won't work properly so to resolve this we need to create and mount an empty dir.\n```bash\n# Immutable deployment\n“apiVersion: v1\nkind: Pod\nmetadata:\n  name: nginx\nspec:\n  containers:\n  - name: nginx\n    image: nginx:1.21.6\n    securityContext:\n      readOnlyRootFilesystem: true\n    volumeMounts:\n    - name: nginx-run\n      mountPath: /var/run\n  volumes:\n  - name: nginx-run\n    emptyDir: {}\n```\n\n### Audit Policy\n\u003e [Audit Policy](https://kubernetes.io/docs/tasks/debug/debug-cluster/audit/) : Learn how to Monitor and log the cluster activities\n```bash\n# Create and modify the Audit Policy configuration file\napiVersion: audit.k8s.io/v1 \nkind: Policy\nomitStages:\n  - \"RequestReceived\"\nrules:\n  - level: RequestResponse\n    resources:\n    - group: \"\"\n      resources: [\"pods\"]\n  - level: Metadata\n    resources:\n    - group: \"\"\n      resources: [\"pods/log\", \"pods/status\"]\n\n# Create a directory to store the log files.\nmkdir /var/log/kubernetes/audit\n\n# Add flags on the Kube API server manifest \n- --audit-policy-file=/etc/kubernetes/audit-policy.yaml\n- --audit-log-path=/var/log/kubernetes/audit/audit.log\n- --audit-log-maxage=\n- --audit-log-maxbackup=\n- --audit-log-maxsize=\n\n# Mount volumes of the Policy file and log path\nvolumeMounts:\n  - mountPath: /etc/kubernetes/audit-policy.yaml\n    name: audit\n    readOnly: true\n  - mountPath: /var/log/kubernetes/audit/\n    name: audit-log\n    readOnly: false\n\nvolumes:\n- name: audit\n  hostPath:\n    path: /etc/kubernetes/audit-policy.yaml\n    type: File\n- name: audit-log\n  hostPath:\n    path: /var/log/kubernetes/audit/\n    type: DirectoryOrCreate\n```\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftechiescamp%2Fcks-certification-guide","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftechiescamp%2Fcks-certification-guide","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftechiescamp%2Fcks-certification-guide/lists"}