From b49709571fe526ba2c997aa9ef73db79ba0750d8 Mon Sep 17 00:00:00 2001 From: Translator Date: Sat, 4 Jul 2026 11:50:03 +0000 Subject: [PATCH] Translated ['src/pentesting-cloud/kubernetes-security/kubernetes-basics. --- .../exposing-services-in-kubernetes.md | 72 ++++++---- .../kubernetes-security/kubernetes-basics.md | 128 ++++++++++-------- .../kubernetes-securitycontext-s.md | 90 ++++++------ 3 files changed, 160 insertions(+), 130 deletions(-) diff --git a/src/pentesting-cloud/kubernetes-security/exposing-services-in-kubernetes.md b/src/pentesting-cloud/kubernetes-security/exposing-services-in-kubernetes.md index 0d9199bd7..c9684c549 100644 --- a/src/pentesting-cloud/kubernetes-security/exposing-services-in-kubernetes.md +++ b/src/pentesting-cloud/kubernetes-security/exposing-services-in-kubernetes.md @@ -2,11 +2,11 @@ {{#include ../../banners/hacktricks-training.md}} -Daar is **verskillende maniere om services bloot te stel** in Kubernetes sodat beide **interne** endpoints en **eksterne** endpoints toegang daartoe kan kry. Hierdie Kubernetes-konfigurasie is redelik krities, aangesien die administrateur **attackers toegang kan gee tot services waartoe hulle nie toegang behoort te hê nie**. +Daar is **verskillende maniere om services bloot te stel** in Kubernetes sodat beide **interne** endpoints en **eksterne** endpoints hulle kan toegang. Hierdie Kubernetes-konfigurasie is nogal krities, aangesien die administrateur **attackers toegang kan gee tot services waartoe hulle nie toegang behoort te hê nie**. ### Automatic Enumeration -Voordat jy begin om die maniere te enumerate wat K8s bied om services aan die publiek bloot te stel, weet dat as jy namespaces, services en ingresses kan lys, kan jy alles vind wat aan die publiek blootgestel is met: +Voordat jy begin om die maniere te enumereer wat K8s bied om services aan die publiek bloot te stel, weet dat as jy namespaces, services en ingresses kan lys, jy alles wat publiek blootgestel is kan vind met: ```bash kubectl get namespace -o custom-columns='NAME:.metadata.name' | grep -v NAME | while IFS='' read -r ns; do echo "Namespace: $ns" @@ -20,13 +20,13 @@ done | grep -v "ClusterIP" ``` ### ClusterIP -’n **ClusterIP**-service is die **standaard** Kubernetes **service**. Dit gee jou ’n **service binne** jou cluster wat ander apps binne jou cluster kan toegang verkry. Daar is **geen eksterne toegang**. +'n **ClusterIP** service is die **standaard** Kubernetes **service**. Dit gee jou 'n **service binne** jou cluster wat ander apps binne jou cluster kan gebruik. Daar is **geen eksterne toegang** nie. -Dit kan egter verkry word met die Kubernetes Proxy: +Dit kan egter via die Kubernetes Proxy gebruik word: ```bash kubectl proxy --port=8080 ``` -Nou kan jy deur die Kubernetes API navigeer om toegang tot services te verkry met hierdie skema: +Nou kan jy deur die Kubernetes API navigeer om services te access using this scheme: `http://localhost:8080/api/v1/proxy/namespaces//services/:/` @@ -34,7 +34,7 @@ Byvoorbeeld, jy kan die volgende URL gebruik: `http://localhost:8080/api/v1/proxy/namespaces/default/services/my-internal-service:http/` -om toegang te verkry tot hierdie service: +om toegang tot hierdie service te kry: ```yaml apiVersion: v1 kind: Service @@ -50,7 +50,7 @@ port: 80 targetPort: 80 protocol: TCP ``` -_Hierdie metode vereis dat jy `kubectl` as ’n **geïdentifiseerde gebruiker** laat loop._ +_Hierdie metode vereis dat jy `kubectl` as ’n **geauthentiseerde gebruiker** laat loop._ Lys alle ClusterIPs: ```bash @@ -58,7 +58,7 @@ kubectl get services --all-namespaces -o=custom-columns='NAMESPACE:.metadata.nam ``` ### NodePort -Wanneer **NodePort** gebruik word, word 'n aangewese poort op al die Nodes beskikbaar gemaak (wat die Virtual Machines verteenwoordig). **Traffic** wat na hierdie spesifieke poort gerig word, word dan sistematies **na die service herlei**. Gewoonlik word hierdie metode nie aanbeveel nie weens sy nadele. +Wanneer **NodePort** gebruik word, word ’n aangewese poort beskikbaar gemaak op alle Nodes (wat die Virtual Machines verteenwoordig). **Traffic** wat na hierdie spesifieke poort gerig word, word dan sistematies **na die service gerouteer**. Tipies word hierdie metode nie aanbeveel nie weens sy nadele. Lys alle NodePorts: ```bash @@ -81,30 +81,41 @@ targetPort: 80 nodePort: 30036 protocol: TCP ``` -As jy nie die **nodePort** in die yaml **spesifiseer** nie (dit is die poort wat oopgemaak sal word), sal ’n poort in die **reeks 30000–32767 gebruik word**. +As jy **nie die** **nodePort** in die yaml spesifiseer nie (dit is die poort wat oopgemaak sal word), sal ’n poort in die **reeks 30000–32767 gebruik word**. + +Wanneer NodePort- of LoadBalancer-Services hersien word, inspekteer ook traffic-policy fields omdat hulle verander watter nodes en backends nuttig is vanaf ’n gegewe bron: +```bash +kubectl get services --all-namespaces \ +-o custom-columns='NAMESPACE:.metadata.namespace,NAME:.metadata.name,TYPE:.spec.type,ETP:.spec.externalTrafficPolicy,ITP:.spec.internalTrafficPolicy,AFFINITY:.spec.sessionAffinity,DIST:.spec.trafficDistribution,NODEPORTS:.spec.ports[*].nodePort' +``` +- `externalTrafficPolicy: Local` behou die oorspronklike kliënt bron-IP vir NodePort/LoadBalancer traffic en vermy forwarding na endpoints op ander nodes. ’n node sonder ’n plaaslike ready endpoint mag die traffic drop, selfs al het die Service elders endpoints. +- `externalTrafficPolicy: Cluster` is die default en kan deur enige node forward, maar backend logs mag node IPs sien in plaas van die werklike eksterne kliënt-IP. +- `internalTrafficPolicy: Local` beperk in-cluster Service traffic tot endpoints wat plaaslik op die bron-node is. Dit is locality routing, nie ’n authorization boundary nie. +- `sessionAffinity: ClientIP` kan herhaalde tests vanaf een client laat hit dieselfde backend, wat ander ready endpoints tydens manual checks verberg. +- `trafficDistribution` en EndpointSlice topology hints kan dieselfde-zone of dieselfde-node endpoints op nuwer clusters voorkeur gee; behandel dit as routing preferences eerder as harde security policy. ### LoadBalancer -Maak die Service ekstern bloot **met behulp van ’n cloud provider se load balancer**. Op GKE sal dit ’n [Network Load Balancer](https://cloud.google.com/compute/docs/load-balancing/network/) opstel wat jou ’n enkele IP-adres sal gee wat al die verkeer na jou service sal deurstuur. In AWS sal dit ’n Load Balancer lanseer. +Expose die Service ekstern **met behulp van 'n cloud provider se load balancer**. Op GKE sal dit ’n [Network Load Balancer](https://cloud.google.com/compute/docs/load-balancing/network/) opstel wat jou ’n enkele IP address gee wat al die traffic na jou service sal forward. In AWS sal dit ’n Load Balancer launch. -Jy moet vir ’n LoadBalancer per blootgestelde service betaal, wat duur kan wees. +Jy moet betaal vir ’n LoadBalancer per exposed service, wat duur kan wees. Lys alle LoadBalancers: ```bash kubectl get services --all-namespaces -o=custom-columns='NAMESPACE:.metadata.namespace,NAME:.metadata.name,TYPE:.spec.type,CLUSTER-IP:.spec.clusterIP,EXTERNAL-IP:.status.loadBalancer.ingress[*],PORT(S):.spec.ports[*].port,NODEPORT(S):.spec.ports[*].nodePort,TARGETPORT(S):.spec.ports[*].targetPort,SELECTOR:.spec.selector' | grep LoadBalancer ``` -### Extern IP's +### External IPs > [!TIP] -> External IP's word blootgestel deur services van tipe Load Balancers en hulle word oor die algemeen gebruik wanneer 'n eksterne Cloud Provider Load Balancer gebruik word. +> External IPs word blootgestel deur services van type Load Balancers en hulle word oor die algemeen gebruik wanneer 'n external Cloud Provider Load Balancer gebruik word. > > Om hulle te vind, kyk vir load balancers met waardes in die `EXTERNAL-IP` veld. -Traffic wat die cluster binnegaan met die **external IP** (as **destination IP**), op die Service-poort, sal **gerouteer word na een van die Service-endpoints**. `externalIPs` word nie deur Kubernetes bestuur nie en is die verantwoordelikheid van die cluster administrator. +Traffic that ingresses into the cluster with the **external IP** (as **destination IP**), on the Service port, will be **routed to one of the Service endpoints**. `externalIPs` is not managed by Kubernetes and is the responsibility of the cluster administrator. -`externalIPs` is 'n sensitiewe route-control veld omdat 'n user wat dit kan stel traffic vir 'n IP address kan opeis wat die Service owner nie behoort te beheer nie as die omliggende network daardie IP na die cluster route. Kubernetes het die deprecation en beplande removal van Service `externalIPs` in v1.36 aangekondig, so verkies controller-owned exposure mechanisms soos LoadBalancer integrations of Gateway API waar moontlik, en beperk/admiteer hierdie veld versigtig terwyl dit nog bestaan. +`externalIPs` is a sensitive route-control field because a user who can set it might claim traffic for an IP address the Service owner should not control if the surrounding network routes that IP to the cluster. Kubernetes announced the deprecation and planned removal of Service `externalIPs` in v1.36, so prefer controller-owned exposure mechanisms such as LoadBalancer integrations or Gateway API where possible, and restrict/admit this field carefully while it still exists. -In die Service spec, `externalIPs` kan saam met enige van die `ServiceTypes` gespesifiseer word. In die voorbeeld hieronder, "`my-service`" kan deur clients verkry word op "`80.11.12.10:80`" (`externalIP:port`) +In the Service spec, `externalIPs` can be specified along with any of the `ServiceTypes`. In the example below, "`my-service`" can be accessed by clients on "`80.11.12.10:80`" (`externalIP:port`) ```yaml apiVersion: v1 kind: Service @@ -123,7 +134,7 @@ externalIPs: ``` ### ExternalName -[**Uit die docs:**](https://kubernetes.io/docs/concepts/services-networking/service/#externalname) Services van tipe ExternalName **map 'n Service na 'n DNS-naam**, nie na 'n tipiese selector soos `my-service` of `cassandra` nie. Jy spesifiseer hierdie Services met die `spec.externalName` parameter. +[**Uit die docs:**](https://kubernetes.io/docs/concepts/services-networking/service/#externalname) Services van die tipe ExternalName **map 'n Service na 'n DNS name**, nie na 'n tipiese selector soos `my-service` of `cassandra` nie. Jy spesifiseer hierdie Services met die `spec.externalName` parameter. Hierdie Service-definisie, byvoorbeeld, map die `my-service` Service in die `prod` namespace na `my.database.example.com`: ```yaml @@ -136,34 +147,34 @@ spec: type: ExternalName externalName: my.database.example.com ``` -Wanneer die host `my-service.prod.svc.cluster.local` opsoek word, gee die cluster DNS Service ’n `CNAME` rekord terug met die waarde `my.database.example.com`. Toegang tot `my-service` werk op dieselfde manier as ander Services, maar met die deurslaggewende verskil dat **herleiding op die DNS-vlak plaasvind** eerder as via proxying of forwarding. +Wanneer jy die host `my-service.prod.svc.cluster.local` opsoek, stuur die cluster DNS Service ’n `CNAME`-rekord terug met die waarde `my.database.example.com`. Toegang tot `my-service` werk op dieselfde manier as ander Services, maar met die deurslaggewende verskil dat **omleiding op die DNS-vlak plaasvind** eerder as via proxying of forwarding. -Lys al die ExternalNames: +Lys alle ExternalNames: ```bash kubectl get services --all-namespaces | grep ExternalName ``` ### EndpointSlices -EndpointSlices wys die konkrete backend-adresse en poorte waarna 'n Service tans routeer. Hulle is veral nuttig wanneer 'n Service geen selector het nie, wanneer labels nie die traffic-pad verduidelik nie, of wanneer slegs sommige backends gereed is. +EndpointSlices wys die konkrete backend-adresse en poorte waarna 'n Service tans roeteer. Hulle is veral nuttig wanneer 'n Service geen selector het nie, wanneer labels nie die traffic-pad verduidelik nie, of wanneer slegs sommige backends gereed is. -Lys EndpointSlices geassosieer met Services: +Lys EndpointSlices wat met Services geassosieer is: ```bash kubectl get endpointslices --all-namespaces kubectl get endpointslice -n -l kubernetes.io/service-name= -o yaml kubectl get endpointslice -n -l kubernetes.io/service-name= \ -o custom-columns='NAME:.metadata.name,ADDR:.endpoints[*].addresses,READY:.endpoints[*].conditions.ready,PORTS:.ports[*].port' ``` -Wanneer exposure hersien, vergelyk die Service selector met die EndpointSlice `targetRef`, endpoint-adresse, readiness conditions, en ports. ’n Selectorless Service kan met handmatig bestuurde EndpointSlices gepaar word en verkeer na non-Pod of onverwagte bestemmings roeteer. +When reviewing exposure, compare the Service selector with the EndpointSlice `targetRef`, endpoint addresses, readiness conditions, and ports. A selectorless Service can be paired with manually managed EndpointSlices and route traffic to non-Pod or unexpected destinations. ### Ingress -Anders as al die bogenoemde voorbeelde, is **Ingress NIE ’n tipe service** nie. In plaas daarvan sit dit **voor verskeie services en tree op as ’n “smart router”** of entrypoint in jou cluster. +Anders as al die bogenoemde voorbeelde, **Ingress is NIE ’n tipe service nie**. In plaas daarvan sit dit **voor verskeie services en tree op as ’n “smart router”** of entrypoint in jou cluster. Jy kan baie verskillende dinge met ’n Ingress doen, en daar is **baie tipes Ingress controllers wat verskillende capabilities het**. -Die standaard GKE ingress controller sal vir jou ’n [HTTP(S) Load Balancer](https://cloud.google.com/compute/docs/load-balancing/http/) opstel. Dit sal jou toelaat om beide path based en subdomain based routing na backend services te doen. Jy kan byvoorbeeld alles op foo.yourdomain.com na die foo service stuur, en alles onder die yourdomain.com/bar/ path na die bar service. +Die verstek GKE ingress controller sal vir jou ’n [HTTP(S) Load Balancer](https://cloud.google.com/compute/docs/load-balancing/http/) opstel. Dit sal jou toelaat om beide path-gebaseerde en subdomain-gebaseerde routing na backend services te doen. Byvoorbeeld, jy kan alles op foo.yourdomain.com na die foo service stuur, en alles onder die yourdomain.com/bar/ path na die bar service. -Die YAML vir ’n Ingress object op GKE met ’n [L7 HTTP Load Balancer](https://cloud.google.com/compute/docs/load-balancing/http/) kan so lyk: +Die YAML vir ’n Ingress object op GKE met ’n [L7 HTTP Load Balancer](https://cloud.google.com/compute/docs/load-balancing/http/) kan dalk só lyk: ```yaml apiVersion: networking.k8s.io/v1 kind: Ingress @@ -197,7 +208,7 @@ name: bar port: number: 8080 ``` -Lys alle die ingresses: +Lys al die ingresses: ```bash kubectl get ingresses --all-namespaces -o=custom-columns='NAMESPACE:.metadata.namespace,NAME:.metadata.name,RULES:spec.rules[*],STATUS:status' ``` @@ -207,9 +218,9 @@ kubectl get ingresses --all-namespaces -o=yaml ``` ### Gateway API -Gateway API is die nuwer Kubernetes API vir die blootstel van Services. Dit skei infrastruktuur-besitte Gateway objects van toepassing-besitte Route objects soos HTTPRoute. Dit is nuttig vir delegasie, maar dit beteken ook exposure kan oor namespaces gesplit word. +Gateway API is die nuwer Kubernetes API vir die blootstel van Services. Dit skei infrastruktuur-besitte Gateway objects van application-besitte Route objects soos HTTPRoute. Dit is nuttig vir delegation, maar dit beteken ook dat exposure oor namespaces verdeel kan word. -List Gateway API exposure objects: +Lys Gateway API exposure objects: ```bash kubectl get gatewayclasses kubectl get gateways --all-namespaces @@ -217,13 +228,16 @@ kubectl get httproutes --all-namespaces kubectl get gateway -n -o yaml kubectl get httproute -n -o yaml ``` -Kontroleer Gateway listeners, toegelate route namespaces, Route `parentRefs`, hostnames, filters, backend references, en status conditions soos of die route aanvaar is. ’n Route wat deur ’n shared Gateway aanvaar word, kan ’n backend blootstel selfs wanneer geen legacy Ingress object bestaan nie. +Kontroleer Gateway listeners, toegelate route namespaces, Route `parentRefs`, hostnames, filters, backend references, en status conditions soos of die route aanvaar was. ’n Route wat deur ’n shared Gateway aanvaar word, kan ’n backend blootstel selfs wanneer geen legacy Ingress object bestaan nie. ### References - [https://medium.com/google-cloud/kubernetes-nodeport-vs-loadbalancer-vs-ingress-when-should-i-use-what-922f010849e0](https://medium.com/google-cloud/kubernetes-nodeport-vs-loadbalancer-vs-ingress-when-should-i-use-what-922f010849e0) - [https://kubernetes.io/docs/concepts/services-networking/service/](https://kubernetes.io/docs/concepts/services-networking/service/) - [https://kubernetes.io/blog/2026/05/14/kubernetes-v1-36-deprecation-and-removal-of-service-externalips/](https://kubernetes.io/blog/2026/05/14/kubernetes-v1-36-deprecation-and-removal-of-service-externalips/) +- [https://kubernetes.io/docs/concepts/services-networking/service-traffic-policy/](https://kubernetes.io/docs/concepts/services-networking/service-traffic-policy/) +- [https://kubernetes.io/docs/tutorials/services/source-ip/](https://kubernetes.io/docs/tutorials/services/source-ip/) +- [https://kubernetes.io/docs/concepts/services-networking/topology-aware-routing/](https://kubernetes.io/docs/concepts/services-networking/topology-aware-routing/) - [https://kubernetes.io/docs/concepts/services-networking/endpoint-slices/](https://kubernetes.io/docs/concepts/services-networking/endpoint-slices/) - [https://gateway-api.sigs.k8s.io/](https://gateway-api.sigs.k8s.io/) diff --git a/src/pentesting-cloud/kubernetes-security/kubernetes-basics.md b/src/pentesting-cloud/kubernetes-security/kubernetes-basics.md index 0df63c25c..4e3034b18 100644 --- a/src/pentesting-cloud/kubernetes-security/kubernetes-basics.md +++ b/src/pentesting-cloud/kubernetes-security/kubernetes-basics.md @@ -2,36 +2,36 @@ {{#include ../../banners/hacktricks-training.md}} -**The original author of this page is** [**Jorge**](https://www.linkedin.com/in/jorge-belmonte-a924b616b/) **(read his original post** [**here**](https://sickrov.github.io)**)** +**Die oorspronklike outeur van hierdie bladsy is** [**Jorge**](https://www.linkedin.com/in/jorge-belmonte-a924b616b/) **(lees sy oorspronklike pos** [**hier**](https://sickrov.github.io)**)** ## Architecture & Basics ### What does Kubernetes do? - Laat toe om container/s in 'n container engine te laat loop. -- Schedule laat containers missie-doeltreffend wees. -- Hou containers lewend. -- Laat container communications toe. -- Laat deployment techniques toe. -- Hanteer volumes of information. +- Schedule laat containers missie-doeltreffend toe. +- Hou containers lewendig. +- Laat container-kommunikasie toe. +- Laat deployment-tegnieke toe. +- Hanteer volumes van inligting. ### Architecture ![Kubernetes architecture diagram showing control plane components, API server, kubelet, kube-proxy, pods, and worker nodes](https://sickrov.github.io/media/Screenshot-68.jpg) - **Node**: operating system met pod of pods. -- **Pod**: Wrapper rondom 'n container of multiple containers with. 'n pod should only contain one application (so usually, a pod run just 1 container). Die pod is die manier waarop kubernetes die container technology wat loop abstraheer. -- **Service**: Elke pod het 1 interne **IP address** uit die interne reeks van die node. However, dit kan ook via 'n service blootgestel word. Die **service has also an IP address** en die doel daarvan is om die communication tussen pods te behou sodat as een sterf die **new replacement** (met 'n verskillende interne IP) **accessible** blootgestel sal wees in dieselfde **IP of the service**. Dit kan as internal of external gekonfigureer word. Die service tree ook op as 'n **load balancer when 2 pods are connected** to the same service.\ +- **Pod**: Wrapper rondom 'n container of multiple containers met. A pod should only contain one application (so usually, a pod run just 1 container). Die pod is die manier waarop kubernetes die container-tegnologie wat loop abstrakteer. +- **Service**: Each pod has 1 internal **IP address** from the internal range of the node. However, it can be also exposed via a service. The **service has also an IP address** and its goal is to maintain the communication between pods so if one dies the **new replacement** (with a different internal IP) **will be accessible** exposed in the **same IP of the service**. It can be configured as internal or external. The service also actuates as a **load balancer when 2 pods are connected** to the same service.\ When a **service** is **created** you can find the endpoints of each service running `kubectl get endpoints` -- **Kubelet**: Primary node agent. Die component wat communication tussen node en kubectl vestig, en kan net pods run (through API server). The kubelet doesn’t manage containers that were not created by Kubernetes. +- **Kubelet**: Primêre node-agent. Die komponent wat kommunikasie tussen node en kubectl vestig, en kan slegs pods laat loop (through API server). Die kubelet bestuur nie containers wat nie deur Kubernetes geskep is nie. - **Kube-proxy**: is die service in charge of the communications (services) between the apiserver and the node. The base is an IPtables for nodes. Most experienced users could install other kube-proxies from other vendors. - **Sidecar container**: Sidecar containers are the containers that should run along with the main container in the pod. This sidecar pattern extends and enhances the functionality of current containers without changing them. Nowadays, We know that we use container technology to wrap all the dependencies for the application to run anywhere. A container does only one thing and does that thing very well. - **Master process:** -- **Api Server:** Is die manier waarop die users en die pods gebruik om met the master process te communicate. Only authenticated request should be allowed. -- **Scheduler**: Scheduling verwys daarna om seker te maak dat Pods by Nodes gepas word sodat Kubelet hulle kan run. It has enough intelligence to decide which node has more available resources the assign the new pod to it. Note that the scheduler doesn't start new pods, it just communicate with the Kubelet process running inside the node, which will launch the new pod. +- **Api Server:** Is the way the users and the pods use to communicate with the master process. Only authenticated request should be allowed. +- **Scheduler**: Scheduling refers to making sure that Pods are matched to Nodes so that Kubelet can run them. It has enough intelligence to decide which node has more available resources the assign the new pod to it. Note that the scheduler doesn't start new pods, it just communicate with the Kubelet process running inside the node, which will launch the new pod. - **Kube Controller manager**: It checks resources like replica sets or deployments to check if, for example, the correct number of pods or nodes are running. In case a pod is missing, it will communicate with the scheduler to start a new one. It controls replication, tokens, and account services to the API. - **etcd**: Data storage, persistent, consistent, and distributed. Is Kubernetes’s database and the key-value storage where it keeps the complete state of the clusters (each change is logged here). Components like the Scheduler or the Controller manager depends on this date to know which changes have occurred (available resourced of the nodes, number of pods running...) -- **Cloud controller manager**: Is die spesifieke controller vir flow controls and applications, i.e: if you have clusters in AWS or OpenStack. +- **Cloud controller manager**: Is the specific controller for flow controls and applications, i.e: if you have clusters in AWS or OpenStack. Note that as the might be several nodes (running several pods), there might also be several master processes which their access to the Api server load balanced and their etcd synchronized. @@ -39,6 +39,8 @@ Note that as the might be several nodes (running several pods), there might also When a pod creates data that shouldn't be lost when the pod disappear it should be stored in a physical volume. **Kubernetes allow to attach a volume to a pod to persist the data**. The volume can be in the local machine or in a **remote storage**. If you are running pods in different physical nodes you should use a remote storage so all the pods can access it. +Kubernetes also supports **image volumes** in recent versions. An `image` volume mounts an OCI image or artifact as a **read-only** filesystem source inside the Pod, using fields such as `volumes[].image.reference` and `volumes[].image.pullPolicy`. The kubelet pulls the artifact with the same credential sources used for container images, including node credentials, Pod `imagePullSecrets`, and ServiceAccount `imagePullSecrets`. During a security review, treat image volumes as runtime inputs and supply-chain dependencies: check whether the reference is pinned by digest, which registry credentials can fetch it, where it is mounted, and whether `subPath` limits the visible directory. + **Other configurations:** - **ConfigMap**: You can configure **URLs** to access services. The pod will obtain data from here to know how to communicate with the rest of the services (pods). Note that this is not the recommended place to save credentials! @@ -103,9 +105,9 @@ $ minikube delete 🔥 Deleting "minikube" in virtualbox ... 💀 Removed all traces of the "minikube" cluster ``` -### Kubectl Basics +### Kubectl-basiese -**`Kubectl`** is die command line tool vir kubernetes clusters. Dit kommunikeer met die Api server van die master process om aksies in kubernetes uit te voer of om data te versoek. +**`Kubectl`** is die command line tool vir kubernetes clusters. Dit kommunikeer met die Api server van die master process om aksies in kubernetes uit te voer of om vir data te vra. ```bash kubectl version #Get client and server version kubectl get pod @@ -138,7 +140,7 @@ kubectl apply -f deployment.yml ``` ### Minikube Dashboard -Die dashboard laat jou makliker sien wat minikube laat loop, jy kan die URL vind om dit te benader in: +Die dashboard maak dit makliker om te sien wat minikube laat loop, jy kan die URL kry om dit te toegang by: ``` minikube dashboard --url @@ -153,12 +155,12 @@ http://127.0.0.1:50034/api/v1/namespaces/kubernetes-dashboard/services/http:kube ``` ### YAML configuration files examples -Each configuration file has 3 parts: **metadata**, **specification** (wat nodig is om gelanseer te word), **status** (gewenste toestand).\ -Inside the specification of the deployment configuration file you can find the template defined with a new configuration structure defining the image to run: +Elke konfigurasielêer het 3 dele: **metadata**, **specification** (wat gelaai moet word), **status** (gewenste toestand).\ +Binne die specification van die deployment konfigurasielêer kan jy die template vind wat gedefinieer is met ’n nuwe konfigurasiestruktuur wat die image om te run definieer: **Example of Deployment + Service declared in the same configuration file (from** [**here**](https://gitlab.com/nanuchi/youtube-tutorial-series/-/blob/master/demo-kubernetes-components/mongo.yaml)**)** -As a service usually is related to one deployment it's possible to declare both in the same configuration file (the service declared in this config is only accessible internally): +Aangesien ’n service gewoonlik met een deployment verband hou, is dit moontlik om albei in dieselfde konfigurasielêer te verklaar (die service wat in hierdie config verklaar word is slegs intern toeganklik): ```yaml apiVersion: apps/v1 kind: Deployment @@ -205,9 +207,9 @@ ports: port: 27017 targetPort: 27017 ``` -**Voorbeeld van eksterne service-konfigurasie** +**Voorbeeld van eksterne dienskonfigurasie** -Hierdie service sal ekstern toeganklik wees (kontroleer die `nodePort` en `type: LoadBlancer` attributes): +Hierdie diens sal ekstern toeganklik wees (kontroleer die `nodePort`- en `type: LoadBlancer`-eienskappe): ```yaml --- apiVersion: v1 @@ -227,9 +229,9 @@ nodePort: 30000 > [!NOTE] > Dit is nuttig vir toetsing, maar vir produksie behoort jy slegs interne dienste en ’n Ingress te hê om die toepassing bloot te stel. -**Example of Ingress config file** +**Voorbeeld van Ingress-konfigurasielêer** -Dit sal die toepassing blootstel in `http://dashboard.com`. +Dit sal die toepassing blootstel by `http://dashboard.com`. ```yaml apiVersion: networking.k8s.io/v1 kind: Ingress @@ -247,7 +249,7 @@ servicePort: 80 ``` **Voorbeeld van secrets config file** -Let op hoe die password in B64 geënkodeer is (wat nie veilig is nie!) +Let op hoe die password in B64 geënkodeer is (wat nie secure is nie!) ```yaml apiVersion: v1 kind: Secret @@ -260,7 +262,7 @@ mongo-root-password: cGFzc3dvcmQ= ``` **Voorbeeld van ConfigMap** -’n **ConfigMap** is die konfigurasie wat aan die pods gegee word sodat hulle weet hoe om ander services te vind en toegang daartoe te verkry. In hierdie geval sal elke pod weet dat die naam `mongodb-service` die adres is van ’n pod waarmee hulle kan kommunikeer (hierdie pod sal ’n mongodb uitvoer): +’n **ConfigMap** is die konfigurasie wat aan die pods gegee word sodat hulle weet hoe om ander services te vind en toegang daartoe te kry. In hierdie geval sal elke pod weet dat die naam `mongodb-service` die adres is van ’n pod waarmee hulle kan kommunikeer (hierdie pod sal ’n mongodb uitvoer): ```yaml apiVersion: v1 kind: ConfigMap @@ -269,7 +271,7 @@ name: mongodb-configmap data: database_url: mongodb-service ``` -Dan kan binne ’n **deployment config** hierdie adres op die volgende manier gespesifiseer word sodat dit binne die env van die pod gelaai word: +Dan, binne 'n **deployment config** kan hierdie adres op die volgende manier gespesifiseer word sodat dit in die env van die pod gelaai word: ```yaml [...] spec: @@ -293,13 +295,13 @@ key: database_url **Example of volume config** Jy kan verskillende voorbeelde van storage configuration yaml files vind in [https://gitlab.com/nanuchi/youtube-tutorial-series/-/tree/master/kubernetes-volumes](https://gitlab.com/nanuchi/youtube-tutorial-series/-/tree/master/kubernetes-volumes).\ -**Let daarop dat volumes nie binne namespaces is nie** +**Note that volumes aren't inside namespaces** ### Namespaces -Kubernetes ondersteun **multiple virtual clusters** wat deur dieselfde fisiese cluster gerugsteun word. Hierdie virtual clusters word **namespaces** genoem. Dit is bedoel vir gebruik in environments met baie users wat oor multiple teams of projects versprei is. Vir clusters met 'n paar tot tientalle users, behoort jy glad nie namespaces te hoef te skep of daaroor te dink nie. Jy behoort eers namespaces te begin gebruik om beter control en organization te hê oor elke deel van die application wat in kubernetes deployed is. +Kubernetes ondersteun **multiple virtual clusters** wat deur dieselfde physical cluster ondersteun word. Hierdie virtual clusters word **namespaces** genoem. Dit is bedoel vir gebruik in environments met baie users wat oor multiple teams of projects versprei is. Vir clusters met 'n paar tot 'n paar tiene users, behoort jy glad nie namespaces te hoef te create of daaroor te dink nie. Jy behoort eers namespaces te begin gebruik om beter control en organization te hê van elke deel van die application wat in kubernetes deployed is. -Namespaces provide a scope for names. Names van resources need to be unique within a namespace, but not across namespaces. Namespaces cannot be nested inside one another and **each** Kubernetes **resource** can only be **in** **one** namespace. +Namespaces provide a scope for names. Names van resources needs to be unique within a namespace, but not across namespaces. Namespaces cannot be nested inside one another and **each** Kubernetes **resource** kan slegs **in** **one** **namespace** wees. Daar is 4 namespaces by default as jy minikube gebruik: ``` @@ -310,47 +312,47 @@ kube-node-lease Active 1d kube-public Active 1d kube-system Active 1d ``` -- **kube-system**: Dit is nie bedoel vir die users om te use nie en jy should dit nie touch nie. Dit is vir master en kubectl processes. -- **kube-public**: Publiek toeganklike date. Contains 'n configmap which bevat cluster information -- **kube-node-lease**: Bepaal die availability van 'n node -- **default**: Die namespace wat die user sal use om resources te create +- **kube-system**: Dit is nie bedoel vir gebruikersgebruik nie en jy behoort dit nie te verander nie. Dit is vir master en kubectl prosesse. +- **kube-public**: Publiek toeganklike data. Bevat ’n configmap wat clusterinligting bevat +- **kube-node-lease**: Bepaal die beskikbaarheid van ’n node +- **default**: Die namespace wat die gebruiker sal gebruik om resources te skep ```bash #Create namespace kubectl create namespace my-namespace ``` > [!NOTE] -> Let op dat die meeste Kubernetes hulpbronne (bv. pods, services, replication controllers, en ander) in sommige namespaces is. Ander hulpbronne soos namespace resources en lae-vlak hulpbronne, soos nodes en persistenVolumes, is egter nie in 'n namespace nie. Om te sien watter Kubernetes hulpbronne in 'n namespace is en watter nie: +> Let daarop dat die meeste Kubernetes-bronne (bv. pods, services, replication controllers, en ander) in some namespaces is. However, ander bronne soos namespace-bronne en low-level-bronne, soos nodes en persistenVolumes is nie in ’n namespace nie. Om te sien watter Kubernetes-bronne in ’n namespace is en nie is nie: > > ```bash > kubectl api-resources --namespaced=true #In a namespace > kubectl api-resources --namespaced=false #Not in a namespace > ``` -Jy kan die namespace stoor vir alle daaropvolgende kubectl opdragte in daardie context. +Jy kan die namespace stoor vir alle daaropvolgende kubectl commands in daardie context. ```bash kubectl config set-context --current --namespace= ``` ### Helm -Helm is die **package manager** vir Kubernetes. Dit laat toe om YAML-lêers te verpak en hulle in public en private repositories te versprei. Hierdie pakkette word **Helm Charts** genoem. +Helm is die **package manager** vir Kubernetes. Dit laat toe om YAML-lêers te package en hulle te versprei in public en private repositories. Hierdie packages word **Helm Charts** genoem. ``` helm search ``` -Helm is also a template engine that allows to generate config files with variables: +Helm is ook `n template engine wat toelaat om config files met variables te genereer: ## Kubernetes secrets -A **Secret** is an object that **contains sensitive data** such as a password, a token or a key. Such information might otherwise be put in a Pod specification or in an image. Users can create Secrets and the system also creates Secrets. The name of a Secret object must be a valid **DNS subdomain name**. Read hier [the official documentation](https://kubernetes.io/docs/concepts/configuration/secret/). +’n **Secret** is ’n object wat **sensitiewe data** bevat soos ’n password, ’n token of ’n key. Sulke inligting kan andersins in ’n Pod specification of in ’n image geplaas word. Users kan Secrets skep en die system skep ook Secrets. Die naam van ’n Secret object moet ’n geldige **DNS subdomain name** wees. Lees hier [the official documentation](https://kubernetes.io/docs/concepts/configuration/secret/). -Secrets might be things like: +Secrets kan dinge wees soos: - API, SSH Keys. - OAuth tokens. -- Credentials, Passwords (plain text or b64 + encryption). -- Information or comments. +- Credentials, Passwords (plain text of b64 + encryption). +- Inligting of comments. - Database connection code, strings… . -There are different types of secrets in Kubernetes +Daar is verskillende types van secrets in Kubernetes | Builtin Type | Usage | | ----------------------------------- | ----------------------------------------- | @@ -364,13 +366,13 @@ There are different types of secrets in Kubernetes | bootstrap.kubernetes.io/token | bootstrap token data | > [!NOTE] -> **The Opaque type is the default one, the typical key-value pair defined by users.** +> **Die Opaque type is die default een, die tipiese key-value pair wat deur users gedefinieer word.** -**How secrets works:** +**Hoe secrets werk:** ![Kubernetes secrets diagram showing secret data reaching the API server and being consumed by a pod](https://sickrov.github.io/media/Screenshot-164.jpg) -The following configuration file defines a **secret** called `mysecret` with 2 key-value pairs `username: YWRtaW4=` and `password: MWYyZDFlMmU2N2Rm`. It also defines a **pod** called `secretpod` that will have the `username` and `password` defined in `mysecret` exposed in the **environment variables** `SECRET_USERNAME` \_\_ and \_\_ `SECRET_PASSWOR`. It will also **mount** the `username` secret inside `mysecret` in the path `/etc/foo/my-group/my-username` with `0640` permissions. +Die volgende configuration file definieer ’n **secret** genaamd `mysecret` met 2 key-value pairs `username: YWRtaW4=` en `password: MWYyZDFlMmU2N2Rm`. Dit definieer ook ’n **pod** genaamd `secretpod` wat die `username` en `password` wat in `mysecret` gedefinieer is, sal blootstel in die **environment variables** `SECRET_USERNAME` \_\_ en \_\_ `SECRET_PASSWOR`. Dit sal ook die `username` secret binne `mysecret` **mount** in die path `/etc/foo/my-group/my-username` met `0640` permissions. ```yaml:secretpod.yaml apiVersion: v1 kind: Secret @@ -422,17 +424,17 @@ env | grep SECRET && cat /etc/foo/my-group/my-username && echo ``` ### Secrets in etcd -**etcd** is 'n konsekwente en hoog-beskikbare **key-value store** wat as Kubernetes se backing store vir alle cluster data gebruik word. Kom ons kry toegang tot die secrets wat in etcd gestoor is: +**etcd** is 'n konsekwente en hoog-beskikbare **key-value store** wat as Kubernetes se backing store gebruik word vir alle cluster data. Kom ons verkry toegang tot die secrets wat in etcd gestoor is: ```bash cat /etc/kubernetes/manifests/kube-apiserver.yaml | grep etcd ``` -Jy sal sien sertifikate, sleutels en URL’s waar hulle in die FS geleë is. Sodra jy dit kry, sal jy in staat wees om met etcd te koppel. +Jy sal sertifikate, sleutels en URL’s sien wat in die FS geleë is. Sodra jy dit kry, sal jy in staat wees om aan etcd te koppel. ```bash #ETCDCTL_API=3 etcdctl --cert --key --cacert endpoint=[] health ETCDCTL_API=3 etcdctl --cert /etc/kubernetes/pki/apiserver-etcd-client.crt --key /etc/kubernetes/pki/apiserver-etcd-client.key --cacert /etc/kubernetes/pki/etcd/etcd/ca.cert endpoint=[127.0.0.1:1234] health ``` -Sodra jy kommunikasie tot stand bring, sal jy die secrets kan kry: +Sodra jy kommunikasie tot stand gebring het, sal jy die secrets kan kry: ```bash #ETCDCTL_API=3 etcdctl --cert --key --cacert endpoint=[] get @@ -440,7 +442,7 @@ ETCDCTL_API=3 etcdctl --cert /etc/kubernetes/pki/apiserver-etcd-client.crt --key ``` **Voeg enkripsie by die ETCD** -By default word al die secrets **in plain** teks binne etcd gestoor tensy jy 'n encryption-laag toepas. Die volgende voorbeeld is gebaseer op [https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/](https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/) +By default word al die secrets in **plain** teks binne etcd gestoor tensy jy ’n enkripsielaag toepas. Die volgende voorbeeld is gebaseer op [https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/](https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/) ```yaml:encryption.yaml apiVersion: apiserver.config.k8s.io/v1 kind: EncryptionConfiguration @@ -454,14 +456,14 @@ keys: secret: cjjPMcWpTPKhAdieVtd+KhG4NN+N6e3NmBPMXJvbfrY= #Any random key - identity: {} ``` -Daarna moet jy die `--encryption-provider-config` vlag op die `kube-apiserver` stel om na die ligging van die geskepte config-lêer te wys. Jy kan `/etc/kubernetes/manifest/kube-apiserver.yaml` wysig en die volgende reëls byvoeg: +Daarna moet jy die `--encryption-provider-config` vlag op die `kube-apiserver` stel om na die ligging van die geskepte config-lêer te wys. Jy kan `/etc/kubernetes/manifest/kube-apiserver.yaml` wysig en die volgende lyne byvoeg: ```yaml containers: - command: - kube-apiserver - --encriyption-provider-config=/etc/kubernetes/etcd/ ``` -Skuif af in die volumeMounts: +Rol af in die volumeMounts: ```yaml - mountPath: /etc/kubernetes/etcd name: etcd @@ -476,22 +478,22 @@ name: etcd ``` **Verifying that data is encrypted** -Data is encrypted wanneer dit na etcd geskryf word. Nadat jy jou `kube-apiserver` herbegin het, should enige nuutgeskepte of opgedateerde secret encrypted wees wanneer dit gestoor word. Om dit te check, kan jy die `etcdctl` command line program gebruik om die contents van jou secret te retrieve. +Data is encrypted when written to etcd. After restarting your `kube-apiserver`, any newly created or updated secret should be encrypted when stored. To check, you can use the `etcdctl` command line program to retrieve the contents of your secret. -1. Create ’n nuwe secret genaamd `secret1` in die `default` namespace: +1. Create a new secret called `secret1` in the `default` namespace: ``` kubectl create secret generic secret1 -n default --from-literal=mykey=mydata ``` -2. Using the etcdctl commandline, read daardie secret uit etcd: +2. Using the etcdctl commandline, read that secret out of etcd: `ETCDCTL_API=3 etcdctl get /registry/secrets/default/secret1 [...] | hexdump -C` -where `[...]` moet die additional arguments wees vir connecting to die etcd server. +where `[...]` must be the additional arguments for connecting to the etcd server. -3. Verify die gestoor secret is prefixed met `k8s:enc:aescbc:v1:` which dui aan die `aescbc` provider het die resulting data encrypted. -4. Verify die secret is korrekt decrypted wanneer dit via die API retrieved word: +3. Verify the stored secret is prefixed with `k8s:enc:aescbc:v1:` which indicates the `aescbc` provider has encrypted the resulting data. +4. Verify the secret is correctly decrypted when retrieved via the API: ``` kubectl describe secret secret1 -n default @@ -503,14 +505,14 @@ should match `mykey: bXlkYXRh`, mydata is encoded, check [decoding a secret](htt ``` kubectl get secrets --all-namespaces -o json | kubectl replace -f - ``` -**Final tips:** +**Finale wenke:** -- Probeer om nie secrets in die FS te hou nie, kry hulle uit ander plekke. +- Probeer om nie secrets in die FS te hou nie, kry hulle van ander plekke. - Kyk na [https://www.vaultproject.io/](https://www.vaultproject.io) om meer beskerming by jou secrets te voeg. - [https://kubernetes.io/docs/concepts/configuration/secret/#risks](https://kubernetes.io/docs/concepts/configuration/secret/#risks) - [https://docs.cyberark.com/Product-Doc/OnlineHelp/AAM-DAP/11.2/en/Content/Integrations/Kubernetes_deployApplicationsConjur-k8s-Secrets.htm](https://docs.cyberark.com/Product-Doc/OnlineHelp/AAM-DAP/11.2/en/Content/Integrations/Kubernetes_deployApplicationsConjur-k8s-Secrets.htm) -## References +## Verwysings {{#ref}} https://sickrov.github.io/ @@ -520,4 +522,12 @@ https://sickrov.github.io/ https://www.youtube.com/watch?v=X48VuDVv0do {{#endref}} +{{#ref}} +https://kubernetes.io/docs/concepts/storage/volumes/#image +{{#endref}} + +{{#ref}} +https://kubernetes.io/docs/tasks/configure-pod-container/image-volumes/ +{{#endref}} + {{#include ../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/kubernetes-security/kubernetes-hardening/kubernetes-securitycontext-s.md b/src/pentesting-cloud/kubernetes-security/kubernetes-hardening/kubernetes-securitycontext-s.md index 53bd4255b..648026a43 100644 --- a/src/pentesting-cloud/kubernetes-security/kubernetes-hardening/kubernetes-securitycontext-s.md +++ b/src/pentesting-cloud/kubernetes-security/kubernetes-hardening/kubernetes-securitycontext-s.md @@ -6,79 +6,85 @@ [**From the docs:**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#podsecuritycontext-v1-core) -Wanneer jy die security context van 'n Pod spesifiseer, kan jy verskeie eienskappe gebruik. Vanuit 'n defensive security-oogpunt behoort jy die volgende te oorweeg: +Wanneer jy die security context van 'n Pod spesifiseer, kan jy verskeie attribute gebruik. Vanuit 'n defensive security oogpunt behoort jy te oorweeg: - Om **runASNonRoot** as **True** te hê -- Om **runAsUser** te konfigureer +- Om **runAsUser** te configure - Indien moontlik, oorweeg om **permissions** te **limiting** deur **seLinuxOptions** en **seccompProfile** aan te dui - Gee **MOENIE** **privilege** **group** access via **runAsGroup** en **supplementaryGroups** nie | Parameter | Description | -|

fsGroup
integer

|

'n Spesiale aanvullende groep wat op all containers in a pod van toepassing is. Sommige volume tipes laat die Kubelet toe om die ownership of that volume te verander sodat dit deur die pod besit word:
1. The owning GID will be the FSGroup
2. The setgid bit is set (new files created in the volume will be owned by FSGroup)
3. The permission bits are OR'd with rw-rw---- If unset, the Kubelet will not modify the ownership and permissions of any volume

| +|

fsGroup
integer

|

'n Spesiale supplemental group wat op **alle containers in 'n pod** van toepassing is. Sommige volume types laat die Kubelet toe om die eienaarskap van daardie volume te **change** sodat dit aan die pod behoort:
1. Die owning GID sal die FSGroup wees
2. Die setgid bit word gestel (nuwe files wat in die volume geskep word sal deur FSGroup besit word)
3. Die permission bits word OR'd met rw-rw---- As dit nie gestel is nie, sal die Kubelet nie die eienaarskap en permissions van enige volume modify nie

| -|

fsGroupChangePolicy
string

| This defines behavior of **changing ownership and permission of the volume** before being exposed inside Pod. | -|

runAsGroup
integer

| The **GID to run the entrypoint of the container process**. Uses runtime default if unset. May also be set in SecurityContext. | -|

runAsNonRoot
boolean

| Indicates that the container must run as a non-root user. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does. | -|

runAsUser
integer

| The **UID to run the entrypoint of the container process**. Defaults to user specified in image metadata if unspecified. | -|

seLinuxOptions
SELinuxOptions
More info about seLinux

| The **SELinux context to be applied to all containers**. If unspecified, the container runtime will allocate a random SELinux context for each container. | -|

seccompProfile
SeccompProfile
More info about Seccomp

| The **seccomp options to use by the containers** in this pod. | -|

supplementalGroups
integer array

| A list of **groups applied to the first process run in each container**, in addition to the container's primary GID. | -|

sysctls
Sysctl array
More info about sysctls

| Sysctls hold a list of **namespaced sysctls used for the pod**. Pods with unsupported sysctls (by the container runtime) might fail to launch. | -|

windowsOptions
WindowsSecurityContextOptions

| The Windows specific settings applied to all containers. If unspecified, the options within a container's SecurityContext will be used. | +|

fsGroupChangePolicy
string

| Dit definieer gedrag van **changing ownership and permission of the volume** voordat dit binne die Pod blootgestel word. | +|

runAsGroup
integer

| Die **GID to run the entrypoint of the container process**. Gebruik runtime default indien nie gestel nie. Kan ook in SecurityContext gestel word. | +|

runAsNonRoot
boolean

| Dui aan dat die container as 'n non-root user moet loop. Indien true, sal die Kubelet die image by runtime valideer om seker te maak dat dit nie as UID 0 (root) loop nie, en sal die container nie start as dit wel doen nie. | +|

runAsUser
integer

| Die **UID to run the entrypoint of the container process**. Default na die user gespesifiseer in image metadata indien nie gespesifiseer nie. | +|

seLinuxOptions
SELinuxOptions
More info about seLinux

| Die **SELinux context to be applied to all containers**. Indien nie gespesifiseer nie, sal die container runtime 'n random SELinux context vir elke container toeken. | +|

seccompProfile
SeccompProfile
More info about Seccomp

| Die **seccomp options to use by the containers** in hierdie pod. | +|

supplementalGroups
integer array

| 'n Lys van **groups applied to the first process run in each container**, benewens die container se primary GID. | +|

sysctls
Sysctl array
More info about sysctls

| Sysctls bevat 'n lys van **namespaced sysctls used for the pod**. Pods met unsupported sysctls (deur die container runtime) kan dalk faal om te launch. | +|

windowsOptions
WindowsSecurityContextOptions

| Die Windows-spesifieke settings wat op alle containers toegepas word. Indien nie gespesifiseer nie, sal die options binne 'n container se SecurityContext gebruik word. | ## SecurityContext [**From the docs:**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#securitycontext-v1-core) -This context is set inside the **containers definitions**. From a defensive security point of view you should consider: +Hierdie context word binne die **containers definitions** gestel. Vanuit 'n defensive security oogpunt behoort jy te oorweeg: -- **allowPrivilegeEscalation** to **False** -- Do not add sensitive **capabilities** (and remove the ones you don't need) -- **privileged** to **False** -- If possible, set **readOnlyFilesystem** as **True** -- Set **runAsNonRoot** to **True** and set a **runAsUser** -- If possible, consider **limiting** **permissions** indicating **seLinuxOptions** and **seccompProfile** -- Do **NOT** give **privilege** **group** access via **runAsGroup.** +- **allowPrivilegeEscalation** na **False** +- Moenie sensitiewe **capabilities** byvoeg nie (en verwyder die een wat jy nie nodig het nie) +- **privileged** na **False** +- Indien moontlik, stel **readOnlyFilesystem** as **True** +- Stel **runAsNonRoot** na **True** en stel 'n **runAsUser** +- Indien moontlik, oorweeg om **permissions** te **limiting** deur **seLinuxOptions** en **seccompProfile** aan te dui +- Gee **MOENIE** **privilege** **group** access via **runAsGroup.** -Note that the attributes set in **both SecurityContext and PodSecurityContext**, the value specified in **SecurityContext** takes **precedence**. +Let daarop dat die attribute wat in **beide SecurityContext en PodSecurityContext** gestel word, die waarde gespesifiseer in **SecurityContext** **precedence** kry. -|

allowPrivilegeEscalation
boolean

| **AllowPrivilegeEscalation** controls whether a process can **gain more privileges** than its parent process. This bool directly controls if the no_new_privs flag will be set on the container process. AllowPrivilegeEscalation is true always when the container is run as **Privileged** or has **CAP_SYS_ADMIN** | +|

allowPrivilegeEscalation
boolean

| **AllowPrivilegeEscalation** beheer of 'n process **more privileges** as sy parent process kan kry. Hierdie bool beheer direk of die no_new_privs flag op die container process gestel sal word. AllowPrivilegeEscalation is altyd true wanneer die container as **Privileged** loop of **CAP_SYS_ADMIN** het | | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -|

capabilities
Capabilities
More info about Capabilities

| The **capabilities to add/drop when running containers**. Defaults to the default set of capabilities. | -|

privileged
boolean

| Run container in privileged mode. Processes in privileged containers are essentially **equivalent to root on the host**. Defaults to false. | -|

procMount
string

| procMount denotes the **type of proc mount to use for the containers**. The default is DefaultProcMount which uses the container runtime defaults for readonly paths and masked paths. | -|

readOnlyRootFilesystem
boolean

| Whether this **container has a read-only root filesystem**. Default is false. | -|

runAsGroup
integer

| The **GID to run the entrypoint** of the container process. Uses runtime default if unset. | -|

runAsNonRoot
boolean

| Indicates that the container must **run as a non-root user**. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does. | -|

runAsUser
integer

| The **UID to run the entrypoint** of the container process. Defaults to user specified in image metadata if unspecified. | -|

seLinuxOptions
SELinuxOptions
More info about seLinux

| The **SELinux context to be applied to the container**. If unspecified, the container runtime will allocate a random SELinux context for each container. | -|

seccompProfile
SeccompProfile

| The **seccomp options** to use by this container. | -|

windowsOptions
WindowsSecurityContextOptions

| The **Windows specific settings** applied to all containers. | +|

capabilities
Capabilities
More info about Capabilities

| Die **capabilities to add/drop when running containers**. Default na die default stel van capabilities. | +|

privileged
boolean

| Run container in privileged mode. Processes in privileged containers is in wese **equivalent to root on the host**. Default na false. | +|

procMount
string

| procMount dui die **type of proc mount to use for the containers** aan. Die default is DefaultProcMount wat die container runtime defaults vir readonly paths en masked paths gebruik. | +|

readOnlyRootFilesystem
boolean

| Of hierdie **container has a read-only root filesystem**. Default is false. | +|

runAsGroup
integer

| Die **GID to run the entrypoint** van die container process. Gebruik runtime default indien nie gestel nie. | +|

runAsNonRoot
boolean

| Dui aan dat die container as 'n non-root user moet **run as a non-root user**. Indien true, sal die Kubelet die image by runtime valideer om seker te maak dat dit nie as UID 0 (root) loop nie, en sal die container nie start as dit wel doen nie. | +|

runAsUser
integer

| Die **UID to run the entrypoint** van die container process. Default na die user gespesifiseer in image metadata indien nie gespesifiseer nie. | +|

seLinuxOptions
SELinuxOptions
More info about seLinux

| Die **SELinux context to be applied to the container**. Indien nie gespesifiseer nie, sal die container runtime 'n random SELinux context vir elke container toeken. | +|

seccompProfile
SeccompProfile

| Die **seccomp options** to use by this container. | +|

windowsOptions
WindowsSecurityContextOptions

| Die **Windows specific settings** wat op alle containers toegepas word. | ## Practical workload review checklist -When reviewing a Pod or workload template, inspect both `spec.securityContext` and every container-level `securityContext` under `containers`, `initContainers`, and `ephemeralContainers`. Container-level fields can override the pod-level defaults, so a safe-looking pod default does not guarantee that every container is safe. +Wanneer jy 'n Pod of workload template review, inspekteer beide `spec.securityContext` en elke container-vlak `securityContext` onder `containers`, `initContainers`, en `ephemeralContainers`. Container-vlak fields kan die pod-vlak defaults override, so 'n veilig-lykende pod default waarborg nie dat elke container veilig is nie. -High-risk combinations to prioritize: +Hoë-risiko kombinasies om te prioritiseer: -- `privileged: true`, especially with `hostPID`, `hostIPC`, `hostNetwork`, `hostPath`, host ports, or runtime socket mounts. -- Added capabilities such as `SYS_ADMIN`, `NET_ADMIN`, `SYS_PTRACE`, `SYS_MODULE`, `DAC_READ_SEARCH`, or `DAC_OVERRIDE`. -- `allowPrivilegeEscalation: true` or unset in containers that can execute attacker-controlled code. -- `seccompProfile: Unconfined`, `procMount: Unmasked`, or missing runtime profiles on sensitive workloads. -- Writable root filesystems or broad writable volume mounts in workloads that process untrusted input. -- Missing CPU, memory, or ephemeral-storage requests and limits in multi-tenant namespaces. +- `privileged: true`, veral met `hostPID`, `hostIPC`, `hostNetwork`, `hostPath`, host ports, of runtime socket mounts. +- Bygevoegde capabilities soos `SYS_ADMIN`, `NET_ADMIN`, `SYS_PTRACE`, `SYS_MODULE`, `DAC_READ_SEARCH`, of `DAC_OVERRIDE`. +- `allowPrivilegeEscalation: true` of unset in containers wat attacker-controlled code kan execute. +- `seccompProfile: Unconfined`, `procMount: Unmasked`, of ontbrekende runtime profiles op sensitiewe workloads. +- Writable root filesystems of breë writable volume mounts in workloads wat untrusted input process. +- Ontbrekende CPU, memory, of ephemeral-storage requests en limits in multi-tenant namespaces. +- Ontbrekende of onrealistiese pod-vlak `spec.resources` budgets, en principals met `patch` of `update` op die Pod `resize` subresource, omdat supported clusters die lopende CPU- en memory desired state kan change sonder om die Pod te recreate. -For most application workloads, a good baseline is to run as a non-root UID, set `runAsNonRoot: true`, set `allowPrivilegeEscalation: false`, drop all capabilities and add back only the minimum required ones, use `seccompProfile: RuntimeDefault`, prefer a read-only root filesystem, and avoid host namespaces, hostPath mounts, and privileged mode. +Resource controls is nie deel van `securityContext` nie, maar review dit in dieselfde workload pass omdat hulle die availability boundary definieer. Moderne Kubernetes kan CPU, memory, en hugepage budgets op Pod-vlak onder `spec.resources` definieer, benewens container-vlak `resources`. 'n Pod met sidecars kan deur 'n aggregate Pod envelope bounded wees selfs wanneer een container geen individuele limits het nie, terwyl local ephemeral storage steeds aparte `ephemeral-storage` limits, `emptyDir.sizeLimit`, LimitRanges, en ResourceQuotas nodig het. Vergelyk ook desired resources in die Pod spec met `status.containerStatuses[].resources` na 'n in-place resize request; 'n failed of pending resize kan die requested value in `spec` laat terwyl die kubelet die vorige runtime allocation behou en 'n `PodResizePending` condition rapporteer. -At cluster level, use [Pod Security Admission](https://kubernetes.io/docs/concepts/security/pod-security-admission/) namespace labels to enforce the Kubernetes [Pod Security Standards](https://kubernetes.io/docs/concepts/security/pod-security-standards/) where possible. Use `restricted` for namespaces that can support it, at least `baseline` for ordinary application namespaces, and keep privileged exceptions narrow, documented, and isolated to trusted platform namespaces or node pools. +Vir die meeste application workloads is 'n goeie baseline om as 'n non-root UID te loop, `runAsNonRoot: true` te stel, `allowPrivilegeEscalation: false` te stel, alle capabilities te drop en net die minimum nodige terug te voeg, `seccompProfile: RuntimeDefault` te gebruik, 'n read-only root filesystem te verkies, en host namespaces, hostPath mounts, en privileged mode te vermy. + +Op cluster-vlak, gebruik [Pod Security Admission](https://kubernetes.io/docs/concepts/security/pod-security-admission/) namespace labels om die Kubernetes [Pod Security Standards](https://kubernetes.io/docs/concepts/security/pod-security-standards/) af te dwing waar moontlik. Gebruik `restricted` vir namespaces wat dit kan ondersteun, ten minste `baseline` vir gewone application namespaces, en hou privileged exceptions nou, gedokumenteer, en geïsoleer tot trusted platform namespaces of node pools. ## References - [https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#podsecuritycontext-v1-core](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#podsecuritycontext-v1-core) - [https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#securitycontext-v1-core](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#securitycontext-v1-core) - [https://kubernetes.io/docs/tasks/configure-pod-container/security-context/](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/) +- [https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/) - [https://kubernetes.io/docs/concepts/security/linux-kernel-security-constraints/](https://kubernetes.io/docs/concepts/security/linux-kernel-security-constraints/) - [https://kubernetes.io/docs/concepts/security/pod-security-standards/](https://kubernetes.io/docs/concepts/security/pod-security-standards/) - [https://kubernetes.io/docs/concepts/security/pod-security-admission/](https://kubernetes.io/docs/concepts/security/pod-security-admission/) +- [https://kubernetes.io/docs/tasks/configure-pod-container/assign-pod-level-resources/](https://kubernetes.io/docs/tasks/configure-pod-container/assign-pod-level-resources/) +- [https://kubernetes.io/docs/tasks/configure-pod-container/resize-container-resources/](https://kubernetes.io/docs/tasks/configure-pod-container/resize-container-resources/) {{#include ../../../banners/hacktricks-training.md}}