OCI OKE Should Prevent Container Privilege Escalation
More Info:
allowPrivilegeEscalation=true lets a process gain more privileges than its parent (for example via setuid binaries). Set it to false in pod security policies to enforce no-new-privs and reduce container breakout paths.
Risk Level
High
Address
Compliance, Security
Compliance Standards
- Cloudanix Best Practice
Triage and Remediation
- Remediation
Remediation
Using Console
To prevent container privilege escalation in OCI OKE using the OCI Console, the most practical native method is to use Pod Security Admission (PSA) with a restricted policy on your namespaces.
Below are the step‑by‑step console actions.
1. Confirm your OKE cluster supports Pod Security Admission
- In the OCI Console, open the navigation menu.
- Go to Developer Services → Kubernetes Clusters (OKE).
- Click your cluster name.
- On the Cluster details page, check the Kubernetes version:
- PSA is supported on recent versions (e.g., 1.25+).
- If you are on an older version, plan to upgrade the cluster (Actions → Upgrade cluster).
2. Enable / Verify Pod Security Admission on the Cluster
Depending on your console view:
- From the Cluster details page, look for a section or tab such as Security, Pod Security, or Add-ons (naming can vary by release).
- Ensure that Pod Security Admission (or “Pod Security Standards”) is enabled.
- If there is a toggle or configuration option to enable pod security, turn it ON and save.
If your UI version exposes it at namespace level only, continue directly to the next step.
3. Apply a “restricted” Pod Security profile to namespaces (console)
You want the restricted profile in enforce mode on the namespaces where you run workloads. This profile disallows privilege escalation (and other unsafe settings).
- In the OCI Console, still under your OKE cluster, go to the Workloads or Kubernetes Resources section.
- Click Namespaces.
- For each target namespace:
- Click the namespace name to open its details.
- Look for a section to manage labels or pod security configuration.
- Add/ensure the following labels are set (field names may be “Key” and “Value”):
- Key:
pod-security.kubernetes.io/enforce
Value:restricted - (Optional, but recommended for consistency/preview):
Key:pod-security.kubernetes.io/audit
Value:restricted
Key:pod-security.kubernetes.io/warn
Value:restricted
- Key:
- Save or Update the namespace.
Some console builds may show pod security as dropdowns instead of raw labels; in that case, select:
- Enforce level:
restricted - (Optional) Audit level:
restricted - Warn level:
restricted
4. Effect on privilege escalation
Once restricted is enforced on the namespace:
- Pods that attempt to set:
securityContext.allowPrivilegeEscalation: true, orsecurityContext.privileged: true,- or other restricted capabilities
- will be rejected by the API server at admission time.
This directly prevents privilege‑escalating container configurations in that namespace.
5. (Optional) Validate via the Console
You can confirm that the policy works by attempting to deploy a workload via the console that includes a privileged/privilege‑escalating container:
- Under your cluster, go to Workloads → Deployments (or Pods).
- Try to create a deployment (via “Create deployment”) with a container security context that requests privilege escalation.
- The pod creation should fail with an error referencing pod security / restricted policy.
If your specific OCI Console version does not expose PSA/labels via UI for namespaces, you will need a one‑time kubectl command to add the pod‑security labels; the enforcement behavior in the cluster is the same once labels are present.
Using CLI
To prevent container privilege escalation on OKE, you must enforce Kubernetes security controls on the cluster. OCI CLI is used to connect to the cluster; the actual enforcement is done via Kubernetes (kubectl) once connected.
Below are minimal, concrete steps.
1. Get kubeconfig for your OKE cluster via OCI CLI
# Variables (replace with your values)
COMPARTMENT_OCID="<your_compartment_ocid>"
CLUSTER_OCID="<your_oke_cluster_ocid>"
KUBECONFIG_PATH="$HOME/.kube/config"
# Generate kubeconfig for the cluster
oci ce cluster create-kubeconfig \
--cluster-id "$CLUSTER_OCID" \
--file "$KUBECONFIG_PATH" \
--region "<your_region>" \
--token-version 2.0.0 \
--kube-endpoint PUBLIC_ENDPOINT
Verify access:
kubectl get nodes
2. Enforce Pod Security Admission (PSA) – “restricted” Profile
This prevents privileged containers and privilege escalation at the namespace level.
2.1 Label current namespaces to restricted
For each workload namespace:
NAMESPACE="<your_namespace>"
kubectl label namespace "$NAMESPACE" \
pod-security.kubernetes.io/enforce=restricted \
pod-security.kubernetes.io/enforce-version=latest \
--overwrite
Check:
kubectl get ns --show-labels | grep pod-security.kubernetes.io/enforce
Any new pod in those namespaces will be denied if it requests privilege escalation or privileged mode.
3. Ensure new workloads cannot request privilege escalation
Update your deployment specs so containers explicitly set:
securityContext:
allowPrivilegeEscalation: false
privileged: false
runAsNonRoot: true
capabilities:
drop:
- ALL
Apply via kubectl:
kubectl apply -f your-deployment.yaml
4. Optionally, block privilege escalation cluster‑wide via a Validating Admission (Gatekeeper)
If you want a strict policy everywhere, deploy Gatekeeper and a constraint:
4.1 Install Gatekeeper
kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/deploy/gatekeeper.yaml
Wait for pods:
kubectl -n gatekeeper-system get pods
4.2 Create a ConstraintTemplate
cat << 'EOF' | kubectl apply -f -
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8sallowprivilegeescalation
spec:
crd:
spec:
names:
kind: K8sAllowPrivilegeEscalation
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8sallowprivilegeescalation
violation[{"msg": msg}] {
input.review.kind.kind == "Pod"
c := input.review.object.spec.containers[_]
not has_allow_false(c)
msg := sprintf("container %v must set securityContext.allowPrivilegeEscalation=false", [c.name])
}
has_allow_false(c) {
c.securityContext.allowPrivilegeEscalation == false
}
EOF
4.3 Create the Constraint (enforce everywhere or per-namespace)
Cluster-wide:
cat << 'EOF' | kubectl apply -f -
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sAllowPrivilegeEscalation
metadata:
name: no-priv-escalation
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
EOF
Now any pod without allowPrivilegeEscalation: false will be rejected.
5. Validate
Try to create a non-compliant pod:
cat << 'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
name: test-priv-escalation
spec:
containers:
- name: test
image: busybox
command: ["sh", "-c", "sleep 3600"]
securityContext:
allowPrivilegeEscalation: true
EOF
You should see an admission error (from PSA or Gatekeeper) blocking the pod.
Summary:
- Use OCI CLI to generate kubeconfig and connect to the OKE cluster.
- Use Kubernetes Pod Security Admission with
restrictedlabels on namespaces. - Update workloads to set
securityContext.allowPrivilegeEscalation: false. - Optionally enforce globally via Gatekeeper + constraint.
Using Python
To prevent container privilege escalation in OCI OKE using Python, you typically do two things:
- Enforce the policy at admission time (recommended, cluster-wide).
- Fix existing workloads (patch Deployments, StatefulSets, etc. to set
allowPrivilegeEscalation: false).
Below are step‑by‑step instructions for both, focused on Python where applicable.
1. Enforce “no privilege escalation” via Kubernetes policy
Option A – Use Kubernetes Pod Security Admission (if available in your OKE version)
Define a PodSecurity enforce level of restricted (which includes allowPrivilegeEscalation=false) at namespace level.
- Label the namespace:
kubectl label ns my-namespace pod-security.kubernetes.io/enforce=restricted --overwrite
This does not require Python; it’s a cluster configuration step. All new Pods in that namespace must comply (i.e., allowPrivilegeEscalation must be false, among other things).
Option B – Use OPA Gatekeeper / Kyverno (if you already use them)
If you’re using Gatekeeper or Kyverno on OKE, create a policy that:
- Denies Pods/Deployments where:
securityContext.allowPrivilegeEscalationis not set or istrue.
Example Gatekeeper ConstraintTemplate (YAML) or Kyverno policy can be applied via kubectl apply. You can also apply them with a Python script using the Kubernetes Python client’s create_namespaced_custom_object, but most teams manage these as YAML in Git.
2. Remediate existing workloads with Python (Kubernetes Python client)
Below is a Python approach that:
- Connects to your OKE cluster
- Lists Deployments (you can extend to StatefulSets, DaemonSets, Jobs)
- Patches pod specs so every container and initContainer has:
securityContext.allowPrivilegeEscalation = False
2.1. Install Python dependencies
pip install kubernetes
Ensure your kubeconfig points to the OKE cluster:
export KUBECONFIG=/path/to/oke-kubeconfig
2.2. Python script to set allowPrivilegeEscalation: false
from kubernetes import client, config
# Load kubeconfig (for local) or in-cluster config (if running inside OKE)
try:
config.load_kube_config()
except:
config.load_incluster_config()
apps_v1 = client.AppsV1Api()
TARGET_NAMESPACE = "my-namespace" # or None / "" to do all namespaces carefully
def ensure_no_priv_escalation(container):
if container.security_context is None:
container.security_context = client.V1SecurityContext()
# Only set if not explicitly false already
if container.security_context.allow_privilege_escalation is None or \
container.security_context.allow_privilege_escalation is True:
container.security_context.allow_privilege_escalation = False
def patch_deployment(deploy, namespace):
# Work on a deep copy of the pod spec from the Deployment template
pod_spec = deploy.spec.template.spec
if pod_spec.containers:
for c in pod_spec.containers:
ensure_no_priv_escalation(c)
if pod_spec.init_containers:
for c in pod_spec.init_containers:
ensure_no_priv_escalation(c)
# Prepare a minimal patch body
patch_body = {
"spec": {
"template": {
"spec": {
"containers": [],
}
}
}
}
# containers
patch_body["spec"]["template"]["spec"]["containers"] = []
for c in pod_spec.containers:
container_patch = {
"name": c.name,
"securityContext": {
"allowPrivilegeEscalation": c.security_context.allow_privilege_escalation
}
}
patch_body["spec"]["template"]["spec"]["containers"].append(container_patch)
# initContainers (only if present)
if pod_spec.init_containers:
patch_body["spec"]["template"]["spec"]["initContainers"] = []
for c in pod_spec.init_containers:
container_patch = {
"name": c.name,
"securityContext": {
"allowPrivilegeEscalation": c.security_context.allow_privilege_escalation
}
}
patch_body["spec"]["template"]["spec"]["initContainers"].append(container_patch)
# Apply patch
print(f"Patching Deployment {namespace}/{deploy.metadata.name}")
apps_v1.patch_namespaced_deployment(
name=deploy.metadata.name,
namespace=namespace,
body=patch_body
)
def main():
if TARGET_NAMESPACE and TARGET_NAMESPACE != "ALL":
namespaces = [TARGET_NAMESPACE]
else:
# All namespaces
core_v1 = client.CoreV1Api()
namespaces = [ns.metadata.name for ns in core_v1.list_namespace().items]
for ns in namespaces:
deployments = apps_v1.list_namespaced_deployment(ns).items
for d in deployments:
patch_deployment(d, ns)
if __name__ == "__main__":
main()
Run:
python remediate_priv_escalation.py
This will trigger a rollout for each modified Deployment, recreating Pods with allowPrivilegeEscalation: false.
3. (Optional) Extend to StatefulSets / DaemonSets / Jobs
Use the same pattern with:
apps_v1.list_namespaced_stateful_set+patch_namespaced_stateful_setapps_v1.list_namespaced_daemon_set+patch_namespaced_daemon_setbatch_v1.list_namespaced_job+patch_namespaced_job
Reuse ensure_no_priv_escalation and adjust the API calls.
4. Validate
- Describe a Pod:
kubectl get pod <pod-name> -n my-namespace -o yaml | grep -A3 securityContext
You should see:
securityContext:
allowPrivilegeEscalation: false
- Try to deploy a workload that sets
allowPrivilegeEscalation: trueand ensure it is blocked (if you enabled Pod Security Admission / policy).
Using Terraform
# There is no Terraform argument on the oci_containerengine_cluster (OKE cluster)
# resource that controls allowPrivilegeEscalation; this is enforced at the
# Kubernetes workload / policy layer (e.g., Pod Security Standards / admission),
# not on the cluster object itself.
# Use Kubernetes manifests (via kubernetes provider, helm, or kubectl) to:
# - Apply Pod Security Standards (or equivalent) to namespaces, and
# - Set securityContext.allowPrivilegeEscalation = false on Pods/Containers,
# or enforce it via an admission controller.
# In the OCI Console, this is managed by configuring pod security policies /
# pod security admission for the OKE cluster, not by changing the OKE cluster
# resource itself.
# No Terraform change on the oci_containerengine_cluster resource is possible
# for this specific setting, so `terraform plan` will show no diffs related to
# privilege escalation control on the cluster.