Translated ['.github/pull_request_template.md', 'src/pentesting-cloud/az

This commit is contained in:
Translator
2024-12-31 18:57:14 +00:00
parent 7770a50092
commit 77a009d308
244 changed files with 8632 additions and 11470 deletions

View File

@@ -1,94 +1,93 @@
# Kubernetes Basics
# Kubernetes Grundlagen
## Kubernetes Basics
## Kubernetes Grundlagen
{{#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)**)**
**Der ursprüngliche Autor dieser Seite ist** [**Jorge**](https://www.linkedin.com/in/jorge-belmonte-a924b616b/) **(lesen Sie seinen ursprünglichen Beitrag** [**hier**](https://sickrov.github.io)**)**
## Architecture & Basics
## Architektur & Grundlagen
### What does Kubernetes do?
### Was macht Kubernetes?
- Allows running container/s in a container engine.
- Schedule allows containers mission efficient.
- Keep containers alive.
- Allows container communications.
- Allows deployment techniques.
- Handle volumes of information.
- Ermöglicht das Ausführen von Containern in einer Container-Engine.
- Der Scheduler ermöglicht eine effiziente Planung von Containermissionen.
- Hält Container am Leben.
- Ermöglicht die Kommunikation zwischen Containern.
- Ermöglicht Bereitstellungstechniken.
- Verarbeitet Informationsvolumen.
### Architecture
### Architektur
![](https://sickrov.github.io/media/Screenshot-68.jpg)
- **Node**: operating system with pod or pods.
- **Pod**: Wrapper around a container or multiple containers with. A pod should only contain one application (so usually, a pod run just 1 container). The pod is the way kubernetes abstracts the container technology running.
- **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. The component that establishes communication between node and kubectl, and only can run pods (through API server). The kubelet doesnt manage containers that were not created by Kubernetes.
- **Kube-proxy**: is the 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 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 Kubernetess 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 the specific controller for flow controls and applications, i.e: if you have clusters in AWS or OpenStack.
- **Node**: Betriebssystem mit Pod oder Pods.
- **Pod**: Wrapper um einen Container oder mehrere Container. Ein Pod sollte nur eine Anwendung enthalten (normalerweise läuft ein Pod nur 1 Container). Der Pod ist die Art und Weise, wie Kubernetes die Containertechnologie abstrahiert.
- **Service**: Jeder Pod hat 1 interne **IP-Adresse** aus dem internen Bereich des Nodes. Er kann jedoch auch über einen Service exponiert werden. Der **Service hat ebenfalls eine IP-Adresse** und sein Ziel ist es, die Kommunikation zwischen Pods aufrechtzuerhalten, sodass, wenn einer ausfällt, der **neue Ersatz** (mit einer anderen internen IP) **über die gleiche IP des Services zugänglich ist**. Er kann als intern oder extern konfiguriert werden. Der Service fungiert auch als **Lastenausgleich, wenn 2 Pods mit demselben Service verbunden sind**.\
Wenn ein **Service** **erstellt** wird, können Sie die Endpunkte jedes Services mit `kubectl get endpoints` finden.
- **Kubelet**: Primärer Node-Agent. Die Komponente, die die Kommunikation zwischen Node und kubectl herstellt und nur Pods ausführen kann (über den API-Server). Der Kubelet verwaltet keine Container, die nicht von Kubernetes erstellt wurden.
- **Kube-proxy**: Ist der Service, der für die Kommunikation (Services) zwischen dem Apiserver und dem Node verantwortlich ist. Die Basis ist ein IPtables für Nodes. Erfahrene Benutzer könnten andere Kube-Proxys von anderen Anbietern installieren.
- **Sidecar-Container**: Sidecar-Container sind die Container, die zusammen mit dem Hauptcontainer im Pod ausgeführt werden sollten. Dieses Sidecar-Muster erweitert und verbessert die Funktionalität der aktuellen Container, ohne sie zu ändern. Heutzutage wissen wir, dass wir Containertechnologie verwenden, um alle Abhängigkeiten für die Anwendung zu verpacken, damit sie überall ausgeführt werden kann. Ein Container macht nur eine Sache und macht diese Sache sehr gut.
- **Master-Prozess:**
- **Api Server:** Ist der Weg, den die Benutzer und die Pods verwenden, um mit dem Master-Prozess zu kommunizieren. Nur authentifizierte Anfragen sollten erlaubt sein.
- **Scheduler**: Die Planung bezieht sich darauf, sicherzustellen, dass Pods den Nodes zugeordnet werden, damit Kubelet sie ausführen kann. Er hat genug Intelligenz, um zu entscheiden, welcher Node mehr verfügbare Ressourcen hat, um den neuen Pod zuzuweisen. Beachten Sie, dass der Scheduler keine neuen Pods startet, sondern nur mit dem Kubelet-Prozess kommuniziert, der im Node läuft und den neuen Pod starten wird.
- **Kube Controller Manager**: Er überprüft Ressourcen wie Replica-Sets oder Deployments, um zu überprüfen, ob beispielsweise die richtige Anzahl von Pods oder Nodes läuft. Falls ein Pod fehlt, kommuniziert er mit dem Scheduler, um einen neuen zu starten. Er steuert Replikation, Tokens und Kontodienste für die API.
- **etcd**: Datenspeicher, persistent, konsistent und verteilt. Ist die Datenbank von Kubernetes und der Schlüssel-Wert-Speicher, in dem der vollständige Zustand der Cluster gespeichert wird (jede Änderung wird hier protokolliert). Komponenten wie der Scheduler oder der Controller Manager sind auf diese Daten angewiesen, um zu wissen, welche Änderungen aufgetreten sind (verfügbare Ressourcen der Nodes, Anzahl der laufenden Pods...).
- **Cloud Controller Manager**: Ist der spezifische Controller für Flusskontrollen und Anwendungen, d.h.: wenn Sie Cluster in AWS oder OpenStack haben.
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.
Beachten Sie, dass es mehrere Nodes (die mehrere Pods ausführen) geben kann, und es kann auch mehrere Master-Prozesse geben, deren Zugriff auf den Api-Server lastenausgeglichen und deren etcd synchronisiert ist.
**Volumes:**
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.
Wenn ein Pod Daten erstellt, die nicht verloren gehen sollten, wenn der Pod verschwindet, sollten sie in einem physischen Volume gespeichert werden. **Kubernetes ermöglicht es, ein Volume an einen Pod anzuhängen, um die Daten zu persistieren**. Das Volume kann auf der lokalen Maschine oder in einem **Remote-Speicher** sein. Wenn Sie Pods auf verschiedenen physischen Nodes ausführen, sollten Sie einen Remote-Speicher verwenden, damit alle Pods darauf zugreifen können.
**Other configurations:**
**Weitere Konfigurationen:**
- **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!
- **Secret**: This is the place to **store secret data** like passwords, API keys... encoded in B64. The pod will be able to access this data to use the required credentials.
- **Deployments**: This is where the components to be run by kubernetes are indicated. A user usually won't work directly with pods, pods are abstracted in **ReplicaSets** (number of same pods replicated), which are run via deployments. Note that deployments are for **stateless** applications. The minimum configuration for a deployment is the name and the image to run.
- **StatefulSet**: This component is meant specifically for applications like **databases** which needs to **access the same storage**.
- **Ingress**: This is the configuration that is use to **expose the application publicly with an URL**. Note that this can also be done using external services, but this is the correct way to expose the application.
- If you implement an Ingress you will need to create **Ingress Controllers**. The Ingress Controller is a **pod** that will be the endpoint that will receive the requests and check and will load balance them to the services. the ingress controller will **send the request based on the ingress rules configured**. Note that the ingress rules can point to different paths or even subdomains to different internal kubernetes services.
- A better security practice would be to use a cloud load balancer or a proxy server as entrypoint to don't have any part of the Kubernetes cluster exposed.
- When request that doesn't match any ingress rule is received, the ingress controller will direct it to the "**Default backend**". You can `describe` the ingress controller to get the address of this parameter.
- `minikube addons enable ingress`
- **ConfigMap**: Sie können **URLs** konfigurieren, um auf Services zuzugreifen. Der Pod wird Daten von hier abrufen, um zu wissen, wie er mit den anderen Services (Pods) kommunizieren kann. Beachten Sie, dass dies nicht der empfohlene Ort ist, um Anmeldeinformationen zu speichern!
- **Secret**: Dies ist der Ort, um **geheime Daten** wie Passwörter, API-Schlüssel... in B64 kodiert zu speichern. Der Pod kann auf diese Daten zugreifen, um die erforderlichen Anmeldeinformationen zu verwenden.
- **Deployments**: Hier werden die Komponenten angegeben, die von Kubernetes ausgeführt werden sollen. Ein Benutzer arbeitet normalerweise nicht direkt mit Pods, Pods sind in **ReplicaSets** abstrahiert (Anzahl der gleichen Pods, die repliziert werden), die über Deployments ausgeführt werden. Beachten Sie, dass Deployments für **zustandslose** Anwendungen gedacht sind. Die minimale Konfiguration für ein Deployment ist der Name und das auszuführende Image.
- **StatefulSet**: Diese Komponente ist speziell für Anwendungen wie **Datenbanken** gedacht, die **auf denselben Speicher zugreifen** müssen.
- **Ingress**: Dies ist die Konfiguration, die verwendet wird, um **die Anwendung öffentlich mit einer URL exponieren**. Beachten Sie, dass dies auch mit externen Services erfolgen kann, aber dies ist der richtige Weg, um die Anwendung zu exponieren.
- Wenn Sie ein Ingress implementieren, müssen Sie **Ingress-Controller** erstellen. Der Ingress-Controller ist ein **Pod**, der der Endpunkt sein wird, der die Anfragen empfängt, überprüft und sie an die Services lastenausgleicht. Der Ingress-Controller wird **die Anfrage basierend auf den konfigurierten Ingress-Regeln senden**. Beachten Sie, dass die Ingress-Regeln auf verschiedene Pfade oder sogar Subdomains zu verschiedenen internen Kubernetes-Services verweisen können.
- Eine bessere Sicherheitspraktik wäre es, einen Cloud-Lastenausgleich oder einen Proxy-Server als Einstiegspunkt zu verwenden, um keinen Teil des Kubernetes-Clusters exponiert zu haben.
- Wenn eine Anfrage empfangen wird, die keiner Ingress-Regel entspricht, wird der Ingress-Controller sie an den "**Default backend**" weiterleiten. Sie können den Ingress-Controller `describe` verwenden, um die Adresse dieses Parameters zu erhalten.
- `minikube addons enable ingress`
### PKI infrastructure - Certificate Authority CA:
### PKI-Infrastruktur - Zertifizierungsstelle CA:
![](https://sickrov.github.io/media/Screenshot-66.jpg)
- CA is the trusted root for all certificates inside the cluster.
- Allows components to validate to each other.
- All cluster certificates are signed by the CA.
- ETCd has its own certificate.
- types:
- apiserver cert.
- kubelet cert.
- scheduler cert.
- CA ist die vertrauenswürdige Wurzel für alle Zertifikate innerhalb des Clusters.
- Ermöglicht es Komponenten, sich gegenseitig zu validieren.
- Alle Clusterzertifikate werden von der CA signiert.
- etcd hat sein eigenes Zertifikat.
- Typen:
- apiserver-Zertifikat.
- kubelet-Zertifikat.
- scheduler-Zertifikat.
## Basic Actions
## Grundlegende Aktionen
### Minikube
**Minikube** can be used to perform some **quick tests** on kubernetes without needing to deploy a whole kubernetes environment. It will run the **master and node processes in one machine**. Minikube will use virtualbox to run the node. See [**here how to install it**](https://minikube.sigs.k8s.io/docs/start/).
**Minikube** kann verwendet werden, um einige **schnelle Tests** auf Kubernetes durchzuführen, ohne eine gesamte Kubernetes-Umgebung bereitstellen zu müssen. Es wird die **Master- und Node-Prozesse auf einer Maschine** ausführen. Minikube verwendet VirtualBox, um den Node auszuführen. Siehe [**hier, wie man es installiert**](https://minikube.sigs.k8s.io/docs/start/).
```
$ minikube start
😄 minikube v1.19.0 on Ubuntu 20.04
✨ Automatically selected the virtualbox driver. Other choices: none, ssh
💿 Downloading VM boot image ...
> minikube-v1.19.0.iso.sha256: 65 B / 65 B [-------------] 100.00% ? p/s 0s
> minikube-v1.19.0.iso: 244.49 MiB / 244.49 MiB 100.00% 1.78 MiB p/s 2m17.
> minikube-v1.19.0.iso.sha256: 65 B / 65 B [-------------] 100.00% ? p/s 0s
> minikube-v1.19.0.iso: 244.49 MiB / 244.49 MiB 100.00% 1.78 MiB p/s 2m17.
👍 Starting control plane node minikube in cluster minikube
💾 Downloading Kubernetes v1.20.2 preload ...
> preloaded-images-k8s-v10-v1...: 491.71 MiB / 491.71 MiB 100.00% 2.59 MiB
> preloaded-images-k8s-v10-v1...: 491.71 MiB / 491.71 MiB 100.00% 2.59 MiB
🔥 Creating virtualbox VM (CPUs=2, Memory=3900MB, Disk=20000MB) ...
🐳 Preparing Kubernetes v1.20.2 on Docker 20.10.4 ...
▪ Generating certificates and keys ...
▪ Booting up control plane ...
▪ Configuring RBAC rules ...
▪ Generating certificates and keys ...
▪ Booting up control plane ...
▪ Configuring RBAC rules ...
🔎 Verifying Kubernetes components...
▪ Using image gcr.io/k8s-minikube/storage-provisioner:v5
▪ Using image gcr.io/k8s-minikube/storage-provisioner:v5
🌟 Enabled addons: storage-provisioner, default-storageclass
🏄 Done! kubectl is now configured to use "minikube" cluster and "default" namespace by defaul
@@ -106,11 +105,9 @@ $ minikube delete
🔥 Deleting "minikube" in virtualbox ...
💀 Removed all traces of the "minikube" cluster
```
### Kubectl Grundlagen
### Kubectl Basics
**`Kubectl`** is the command line tool for kubernetes clusters. It communicates with the Api server of the master process to perform actions in kubernetes or to ask for data.
**`Kubectl`** ist das Befehlszeilenwerkzeug für Kubernetes-Cluster. Es kommuniziert mit dem API-Server des Master-Prozesses, um Aktionen in Kubernetes auszuführen oder um Daten anzufordern.
```bash
kubectl version #Get client and server version
kubectl get pod
@@ -141,188 +138,172 @@ kubectl delete deployment mongo-depl
#Deploy from config file
kubectl apply -f deployment.yml
```
### Minikube Dashboard
The dashboard allows you to see easier what is minikube running, you can find the URL to access it in:
Das Dashboard ermöglicht es Ihnen, einfacher zu sehen, was Minikube ausführt. Sie finden die URL, um darauf zuzugreifen, in:
```
minikube dashboard --url
🔌 Enabling dashboard ...
▪ Using image kubernetesui/dashboard:v2.3.1
▪ Using image kubernetesui/metrics-scraper:v1.0.7
▪ Using image kubernetesui/dashboard:v2.3.1
▪ Using image kubernetesui/metrics-scraper:v1.0.7
🤔 Verifying dashboard health ...
🚀 Launching proxy ...
🤔 Verifying proxy health ...
http://127.0.0.1:50034/api/v1/namespaces/kubernetes-dashboard/services/http:kubernetes-dashboard:/proxy/
```
### YAML-Konfigurationsdateien Beispiele
### YAML configuration files examples
Jede Konfigurationsdatei hat 3 Teile: **Metadaten**, **Spezifikation** (was gestartet werden muss), **Status** (gewünschter Zustand).\
Innerhalb der Spezifikation der Bereitstellungs-Konfigurationsdatei finden Sie die Vorlage, die mit einer neuen Konfigurationsstruktur definiert ist, die das auszuführende Image definiert:
Each configuration file has 3 parts: **metadata**, **specification** (what need to be launch), **status** (desired state).\
Inside the specification of the deployment configuration file you can find the template defined with a new configuration structure defining the image to run:
**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):
**Beispiel für Bereitstellung + Dienst, die in derselben Konfigurationsdatei deklariert sind (von** [**hier**](https://gitlab.com/nanuchi/youtube-tutorial-series/-/blob/master/demo-kubernetes-components/mongo.yaml)**)**
Da ein Dienst normalerweise mit einer Bereitstellung verbunden ist, ist es möglich, beide in derselben Konfigurationsdatei zu deklarieren (der in dieser Konfiguration deklarierte Dienst ist nur intern zugänglich):
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: mongodb-deployment
labels:
app: mongodb
name: mongodb-deployment
labels:
app: mongodb
spec:
replicas: 1
selector:
matchLabels:
app: mongodb
template:
metadata:
labels:
app: mongodb
spec:
containers:
- name: mongodb
image: mongo
ports:
- containerPort: 27017
env:
- name: MONGO_INITDB_ROOT_USERNAME
valueFrom:
secretKeyRef:
name: mongodb-secret
key: mongo-root-username
- name: MONGO_INITDB_ROOT_PASSWORD
valueFrom:
secretKeyRef:
name: mongodb-secret
key: mongo-root-password
replicas: 1
selector:
matchLabels:
app: mongodb
template:
metadata:
labels:
app: mongodb
spec:
containers:
- name: mongodb
image: mongo
ports:
- containerPort: 27017
env:
- name: MONGO_INITDB_ROOT_USERNAME
valueFrom:
secretKeyRef:
name: mongodb-secret
key: mongo-root-username
- name: MONGO_INITDB_ROOT_PASSWORD
valueFrom:
secretKeyRef:
name: mongodb-secret
key: mongo-root-password
---
apiVersion: v1
kind: Service
metadata:
name: mongodb-service
name: mongodb-service
spec:
selector:
app: mongodb
ports:
- protocol: TCP
port: 27017
targetPort: 27017
selector:
app: mongodb
ports:
- protocol: TCP
port: 27017
targetPort: 27017
```
**Beispiel für die Konfiguration eines externen Dienstes**
**Example of external service config**
This service will be accessible externally (check the `nodePort` and `type: LoadBlancer` attributes):
Dieser Dienst wird extern zugänglich sein (überprüfen Sie die Attribute `nodePort` und `type: LoadBlancer`):
```yaml
---
apiVersion: v1
kind: Service
metadata:
name: mongo-express-service
name: mongo-express-service
spec:
selector:
app: mongo-express
type: LoadBalancer
ports:
- protocol: TCP
port: 8081
targetPort: 8081
nodePort: 30000
selector:
app: mongo-express
type: LoadBalancer
ports:
- protocol: TCP
port: 8081
targetPort: 8081
nodePort: 30000
```
> [!NOTE]
> This is useful for testing but for production you should have only internal services and an Ingress to expose the application.
> Dies ist nützlich für Tests, aber für die Produktion sollten Sie nur interne Dienste und ein Ingress haben, um die Anwendung bereitzustellen.
**Example of Ingress config file**
This will expose the application in `http://dashboard.com`.
**Beispiel einer Ingress-Konfigurationsdatei**
Dies wird die Anwendung unter `http://dashboard.com` bereitstellen.
```yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: dashboard-ingress
namespace: kubernetes-dashboard
name: dashboard-ingress
namespace: kubernetes-dashboard
spec:
rules:
- host: dashboard.com
http:
paths:
- backend:
serviceName: kubernetes-dashboard
servicePort: 80
rules:
- host: dashboard.com
http:
paths:
- backend:
serviceName: kubernetes-dashboard
servicePort: 80
```
**Beispiel einer Secrets-Konfigurationsdatei**
**Example of secrets config file**
Note how the password are encoded in B64 (which isn't secure!)
Beachten Sie, wie die Passwörter in B64 kodiert sind (was nicht sicher ist!)
```yaml
apiVersion: v1
kind: Secret
metadata:
name: mongodb-secret
name: mongodb-secret
type: Opaque
data:
mongo-root-username: dXNlcm5hbWU=
mongo-root-password: cGFzc3dvcmQ=
mongo-root-username: dXNlcm5hbWU=
mongo-root-password: cGFzc3dvcmQ=
```
**Beispiel für ConfigMap**
**Example of ConfigMap**
A **ConfigMap** is the configuration that is given to the pods so they know how to locate and access other services. In this case, each pod will know that the name `mongodb-service` is the address of a pod that they can communicate with (this pod will be executing a mongodb):
Ein **ConfigMap** ist die Konfiguration, die den Pods gegeben wird, damit sie wissen, wie sie andere Dienste finden und darauf zugreifen können. In diesem Fall wird jeder Pod wissen, dass der Name `mongodb-service` die Adresse eines Pods ist, mit dem sie kommunizieren können (dieser Pod wird ein mongodb ausführen):
```yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: mongodb-configmap
name: mongodb-configmap
data:
database_url: mongodb-service
database_url: mongodb-service
```
Then, inside a **deployment config** this address can be specified in the following way so it's loaded inside the env of the pod:
Dann kann diese Adresse innerhalb einer **deployment config** auf folgende Weise angegeben werden, sodass sie in die Umgebungsvariablen des Pods geladen wird:
```yaml
[...]
spec:
[...]
template:
[...]
spec:
containers:
- name: mongo-express
image: mongo-express
ports:
- containerPort: 8081
env:
- name: ME_CONFIG_MONGODB_SERVER
valueFrom:
configMapKeyRef:
name: mongodb-configmap
key: database_url
[...]
template:
[...]
spec:
containers:
- name: mongo-express
image: mongo-express
ports:
- containerPort: 8081
env:
- name: ME_CONFIG_MONGODB_SERVER
valueFrom:
configMapKeyRef:
name: mongodb-configmap
key: database_url
[...]
```
**Beispiel für die Volumen-Konfiguration**
**Example of volume config**
You can find different example of storage configuration yaml files in [https://gitlab.com/nanuchi/youtube-tutorial-series/-/tree/master/kubernetes-volumes](https://gitlab.com/nanuchi/youtube-tutorial-series/-/tree/master/kubernetes-volumes).\
**Note that volumes aren't inside namespaces**
Sie finden verschiedene Beispiele für Speicher-Konfigurations-YAML-Dateien in [https://gitlab.com/nanuchi/youtube-tutorial-series/-/tree/master/kubernetes-volumes](https://gitlab.com/nanuchi/youtube-tutorial-series/-/tree/master/kubernetes-volumes).\
**Beachten Sie, dass Volumes nicht innerhalb von Namespaces sind**
### Namespaces
Kubernetes supports **multiple virtual clusters** backed by the same physical cluster. These virtual clusters are called **namespaces**. These are intended for use in environments with many users spread across multiple teams, or projects. For clusters with a few to tens of users, you should not need to create or think about namespaces at all. You only should start using namespaces to have a better control and organization of each part of the application deployed in kubernetes.
Kubernetes unterstützt **mehrere virtuelle Cluster**, die von demselben physischen Cluster unterstützt werden. Diese virtuellen Cluster werden **Namespaces** genannt. Sie sind für den Einsatz in Umgebungen mit vielen Benutzern, die über mehrere Teams oder Projekte verteilt sind, gedacht. Für Cluster mit wenigen bis mehreren Dutzend Benutzern sollten Sie keine Namespaces erstellen oder darüber nachdenken müssen. Sie sollten nur beginnen, Namespaces zu verwenden, um eine bessere Kontrolle und Organisation jedes Teils der in Kubernetes bereitgestellten Anwendung zu haben.
Namespaces provide a scope for names. Names of 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**.
There are 4 namespaces by default if you are using minikube:
Namespaces bieten einen Geltungsbereich für Namen. Die Namen von Ressourcen müssen innerhalb eines Namespaces eindeutig sein, jedoch nicht über Namespaces hinweg. Namespaces können nicht ineinander geschachtelt werden, und **jede** Kubernetes **Ressource** kann nur **in** **einem** **Namespace** sein.
Es gibt standardmäßig 4 Namespaces, wenn Sie Minikube verwenden:
```
kubectl get namespace
NAME STATUS AGE
@@ -331,116 +312,108 @@ kube-node-lease Active 1d
kube-public Active 1d
kube-system Active 1d
```
- **kube-system**: It's not meant or the users use and you shouldn't touch it. It's for master and kubectl processes.
- **kube-public**: Publicly accessible date. Contains a configmap which contains cluster information
- **kube-node-lease**: Determines the availability of a node
- **default**: The namespace the user will use to create resources
- **kube-system**: Es ist nicht für die Benutzer gedacht und Sie sollten es nicht anfassen. Es ist für Master- und kubectl-Prozesse.
- **kube-public**: Öffentlich zugängliche Daten. Enthält ein ConfigMap, das Clusterinformationen enthält.
- **kube-node-lease**: Bestimmt die Verfügbarkeit eines Knotens.
- **default**: Der Namespace, den der Benutzer verwenden wird, um Ressourcen zu erstellen.
```bash
#Create namespace
kubectl create namespace my-namespace
```
> [!NOTE]
> Note that most Kubernetes resources (e.g. pods, services, replication controllers, and others) are in some namespaces. However, other resources like namespace resources and low-level resources, such as nodes and persistenVolumes are not in a namespace. To see which Kubernetes resources are and arent in a namespace:
> Beachten Sie, dass die meisten Kubernetes-Ressourcen (z. B. Pods, Dienste, Replikationscontroller und andere) in einigen Namespaces sind. Andere Ressourcen wie Namespace-Ressourcen und Low-Level-Ressourcen, wie Knoten und persistentVolumes, befinden sich jedoch nicht in einem Namespace. Um zu sehen, welche Kubernetes-Ressourcen sich in einem Namespace befinden und welche nicht:
>
> ```bash
> kubectl api-resources --namespaced=true #In a namespace
> kubectl api-resources --namespaced=false #Not in a namespace
> kubectl api-resources --namespaced=true #In einem Namespace
> kubectl api-resources --namespaced=false #Nicht in einem Namespace
> ```
You can save the namespace for all subsequent kubectl commands in that context.
Sie können den Namespace für alle nachfolgenden kubectl-Befehle in diesem Kontext speichern.
```bash
kubectl config set-context --current --namespace=<insert-namespace-name-here>
```
### Helm
Helm is the **package manager** for Kubernetes. It allows to package YAML files and distribute them in public and private repositories. These packages are called **Helm Charts**.
Helm ist der **Paketmanager** für Kubernetes. Er ermöglicht das Verpacken von YAML-Dateien und deren Verteilung in öffentlichen und privaten Repositories. Diese Pakete werden **Helm Charts** genannt.
```
helm search <keyword>
```
Helm ist auch eine Template-Engine, die es ermöglicht, Konfigurationsdateien mit Variablen zu generieren:
Helm is also a template engine that allows to generate config files with variables:
## Kubernetes Secrets
## Kubernetes secrets
Ein **Secret** ist ein Objekt, das **sensible Daten** wie ein Passwort, ein Token oder einen Schlüssel **enthält**. Solche Informationen könnten andernfalls in einer Pod-Spezifikation oder in einem Image gespeichert werden. Benutzer können Secrets erstellen und das System erstellt ebenfalls Secrets. Der Name eines Secret-Objekts muss ein gültiger **DNS-Subdomänenname** sein. Lesen Sie hier [die offizielle Dokumentation](https://kubernetes.io/docs/concepts/configuration/secret/).
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 here [the official documentation](https://kubernetes.io/docs/concepts/configuration/secret/).
Secrets können Dinge wie Folgendes sein:
Secrets might be things like:
- API-, SSH-Schlüssel.
- OAuth-Token.
- Anmeldeinformationen, Passwörter (im Klartext oder b64 + Verschlüsselung).
- Informationen oder Kommentare.
- Datenbankverbindungs-Code, Strings… .
- API, SSH Keys.
- OAuth tokens.
- Credentials, Passwords (plain text or b64 + encryption).
- Information or comments.
- Database connection code, strings… .
Es gibt verschiedene Arten von Secrets in Kubernetes
There are different types of secrets in Kubernetes
| Builtin Type | Usage |
| ----------------------------------- | ----------------------------------------- |
| **Opaque** | **arbitrary user-defined data (Default)** |
| kubernetes.io/service-account-token | service account token |
| kubernetes.io/dockercfg | serialized \~/.dockercfg file |
| kubernetes.io/dockerconfigjson | serialized \~/.docker/config.json file |
| kubernetes.io/basic-auth | credentials for basic authentication |
| kubernetes.io/ssh-auth | credentials for SSH authentication |
| kubernetes.io/tls | data for a TLS client or server |
| bootstrap.kubernetes.io/token | bootstrap token data |
| Eingebauter Typ | Verwendung |
| ------------------------------------ | ----------------------------------------- |
| **Opaque** | **willkürliche benutzerdefinierte Daten (Standard)** |
| kubernetes.io/service-account-token | Token des Dienstkontos |
| kubernetes.io/dockercfg | serialisierte \~/.dockercfg-Datei |
| kubernetes.io/dockerconfigjson | serialisierte \~/.docker/config.json-Datei |
| kubernetes.io/basic-auth | Anmeldeinformationen für die grundlegende Authentifizierung |
| kubernetes.io/ssh-auth | Anmeldeinformationen für die SSH-Authentifizierung |
| kubernetes.io/tls | Daten für einen TLS-Client oder -Server |
| bootstrap.kubernetes.io/token | Bootstrap-Token-Daten |
> [!NOTE]
> **The Opaque type is the default one, the typical key-value pair defined by users.**
> **Der Opaque-Typ ist der Standardtyp, das typische Schlüssel-Wert-Paar, das von Benutzern definiert wird.**
**How secrets works:**
**Wie Secrets funktionieren:**
![](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 folgende Konfigurationsdatei definiert ein **Secret** namens `mysecret` mit 2 Schlüssel-Wert-Paaren `username: YWRtaW4=` und `password: MWYyZDFlMmU2N2Rm`. Es definiert auch ein **Pod** namens `secretpod`, das die in `mysecret` definierten `username` und `password` in den **Umgebungsvariablen** `SECRET_USERNAME` \_\_ und \_\_ `SECRET_PASSWOR` verfügbar macht. Es wird auch das `username`-Secret innerhalb von `mysecret` im Pfad `/etc/foo/my-group/my-username` mit `0640` Berechtigungen **einbinden**.
```yaml:secretpod.yaml
apiVersion: v1
kind: Secret
metadata:
name: mysecret
name: mysecret
type: Opaque
data:
username: YWRtaW4=
password: MWYyZDFlMmU2N2Rm
username: YWRtaW4=
password: MWYyZDFlMmU2N2Rm
---
apiVersion: v1
kind: Pod
metadata:
name: secretpod
name: secretpod
spec:
containers:
- name: secretpod
image: nginx
env:
- name: SECRET_USERNAME
valueFrom:
secretKeyRef:
name: mysecret
key: username
- name: SECRET_PASSWORD
valueFrom:
secretKeyRef:
name: mysecret
key: password
volumeMounts:
- name: foo
mountPath: "/etc/foo"
restartPolicy: Never
volumes:
- name: foo
secret:
secretName: mysecret
items:
- key: username
path: my-group/my-username
mode: 0640
containers:
- name: secretpod
image: nginx
env:
- name: SECRET_USERNAME
valueFrom:
secretKeyRef:
name: mysecret
key: username
- name: SECRET_PASSWORD
valueFrom:
secretKeyRef:
name: mysecret
key: password
volumeMounts:
- name: foo
mountPath: "/etc/foo"
restartPolicy: Never
volumes:
- name: foo
secret:
secretName: mysecret
items:
- key: username
path: my-group/my-username
mode: 0640
```
```bash
@@ -449,114 +422,97 @@ kubectl get pods #Wait until the pod secretpod is running
kubectl exec -it secretpod -- bash
env | grep SECRET && cat /etc/foo/my-group/my-username && echo
```
### Secrets in etcd <a href="#discover-secrets-in-etcd" id="discover-secrets-in-etcd"></a>
**etcd** is a consistent and highly-available **key-value store** used as Kubernetes backing store for all cluster data. Lets access to the secrets stored in etcd:
**etcd** ist ein konsistenter und hochverfügbarer **Key-Value-Speicher**, der als Kubernetes-Backend-Speicher für alle Cluster-Daten verwendet wird. Lassen Sie uns auf die in etcd gespeicherten Secrets zugreifen:
```bash
cat /etc/kubernetes/manifests/kube-apiserver.yaml | grep etcd
```
You will see certs, keys and urls were are located in the FS. Once you get it, you would be able to connect to etcd.
Sie werden sehen, dass Zertifikate, Schlüssel und URLs im Dateisystem (FS) gespeichert sind. Sobald Sie diese haben, können Sie sich mit etcd verbinden.
```bash
#ETCDCTL_API=3 etcdctl --cert <path to client.crt> --key <path to client.ket> --cacert <path to CA.cert> endpoint=[<ip:port>] 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
```
Once you achieve establish communication you would be able to get the secrets:
Sobald Sie die Kommunikation hergestellt haben, können Sie die Geheimnisse abrufen:
```bash
#ETCDCTL_API=3 etcdctl --cert <path to client.crt> --key <path to client.ket> --cacert <path to CA.cert> endpoint=[<ip:port>] get <path/to/secret>
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] get /registry/secrets/default/secret_02
```
**Verschlüsselung zum ETCD hinzufügen**
**Adding encryption to the ETCD**
By default all the secrets are **stored in plain** text inside etcd unless you apply an encryption layer. The following example is based on [https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/](https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/)
Standardmäßig werden alle Geheimnisse **im Klartext** in etcd gespeichert, es sei denn, Sie wenden eine Verschlüsselungsschicht an. Das folgende Beispiel basiert auf [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
resources:
- resources:
- secrets
providers:
- aescbc:
keys:
- name: key1
secret: cjjPMcWpTPKhAdieVtd+KhG4NN+N6e3NmBPMXJvbfrY= #Any random key
- identity: {}
- resources:
- secrets
providers:
- aescbc:
keys:
- name: key1
secret: cjjPMcWpTPKhAdieVtd+KhG4NN+N6e3NmBPMXJvbfrY= #Any random key
- identity: {}
```
After that, you need to set the `--encryption-provider-config` flag on the `kube-apiserver` to point to the location of the created config file. You can modify `/etc/kubernetes/manifest/kube-apiserver.yaml` and add the following lines:
Nach dem müssen Sie das `--encryption-provider-config`-Flag auf dem `kube-apiserver` setzen, um auf den Speicherort der erstellten Konfigurationsdatei zu verweisen. Sie können `/etc/kubernetes/manifest/kube-apiserver.yaml` bearbeiten und die folgenden Zeilen hinzufügen:
```yaml
containers:
- command:
- kube-apiserver
- --encriyption-provider-config=/etc/kubernetes/etcd/<configFile.yaml>
- command:
- kube-apiserver
- --encriyption-provider-config=/etc/kubernetes/etcd/<configFile.yaml>
```
Scroll down in the volumeMounts:
Scrollen Sie nach unten in den volumeMounts:
```yaml
- mountPath: /etc/kubernetes/etcd
name: etcd
readOnly: true
name: etcd
readOnly: true
```
Scroll down in the volumeMounts to hostPath:
Scrollen Sie nach unten in den volumeMounts zu hostPath:
```yaml
- hostPath:
path: /etc/kubernetes/etcd
type: DirectoryOrCreate
name: etcd
path: /etc/kubernetes/etcd
type: DirectoryOrCreate
name: etcd
```
**Überprüfen, ob Daten verschlüsselt sind**
Daten werden verschlüsselt, wenn sie in etcd geschrieben werden. Nach dem Neustart Ihres `kube-apiserver` sollte jedes neu erstellte oder aktualisierte Geheimnis verschlüsselt gespeichert werden. Um dies zu überprüfen, können Sie das `etcdctl`-Befehlszeilenprogramm verwenden, um den Inhalt Ihres Geheimnisses abzurufen.
1. Erstellen Sie ein neues Geheimnis mit dem Namen `secret1` im `default`-Namespace:
```
kubectl create secret generic secret1 -n default --from-literal=mykey=mydata
```
**Verifying that data is encrypted**
2. Lesen Sie dieses Geheimnis mit dem etcdctl-Befehlszeilenprogramm aus etcd:
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.
`ETCDCTL_API=3 etcdctl get /registry/secrets/default/secret1 [...] | hexdump -C`
1. Create a new secret called `secret1` in the `default` namespace:
wobei `[...]` die zusätzlichen Argumente für die Verbindung zum etcd-Server sein müssen.
```
kubectl create secret generic secret1 -n default --from-literal=mykey=mydata
```
3. Überprüfen Sie, ob das gespeicherte Geheimnis mit `k8s:enc:aescbc:v1:` vorangestellt ist, was darauf hinweist, dass der `aescbc`-Provider die resultierenden Daten verschlüsselt hat.
4. Überprüfen Sie, ob das Geheimnis korrekt entschlüsselt wird, wenn es über die API abgerufen wird:
2. Using the etcdctl commandline, read that secret out of etcd:
```
kubectl describe secret secret1 -n default
```
`ETCDCTL_API=3 etcdctl get /registry/secrets/default/secret1 [...] | hexdump -C`
where `[...]` must be the additional arguments for connecting to the etcd server.
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
```
should match `mykey: bXlkYXRh`, mydata is encoded, check [decoding a secret](https://kubernetes.io/docs/concepts/configuration/secret#decoding-a-secret) to completely decode the secret.
**Since secrets are encrypted on write, performing an update on a secret will encrypt that content:**
sollte `mykey: bXlkYXRh` entsprechen, mydata ist kodiert, überprüfen Sie [das Dekodieren eines Geheimnisses](https://kubernetes.io/docs/concepts/configuration/secret#decoding-a-secret), um das Geheimnis vollständig zu dekodieren.
**Da Geheimnisse beim Schreiben verschlüsselt werden, wird das Aktualisieren eines Geheimnisses diesen Inhalt verschlüsseln:**
```
kubectl get secrets --all-namespaces -o json | kubectl replace -f -
```
**Abschließende Tipps:**
**Final tips:**
- Try not to keep secrets in the FS, get them from other places.
- Check out [https://www.vaultproject.io/](https://www.vaultproject.io) for add more protection to your secrets.
- Versuche, keine Geheimnisse im FS zu speichern, hole sie aus anderen Quellen.
- Schau dir [https://www.vaultproject.io/](https://www.vaultproject.io) an, um zusätzlichen Schutz für deine Geheimnisse zu erhalten.
- [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
## Referenzen
{{#ref}}
https://sickrov.github.io/
@@ -567,7 +523,3 @@ https://www.youtube.com/watch?v=X48VuDVv0do
{{#endref}}
{{#include ../../banners/hacktricks-training.md}}