Platform Engineering · Lesson 240

OpenShift Security Context Constraints in Depth

On OpenShift, every pod passes through Security Context Constraints (SCCs) before it runs. An SCC decides whether the pod may run as root, use the host's network or file system, add Linux capabilities, or mount certain volumes, and it fills in what the pod left out: a user ID from the project's range, an SELinux label, a file-system group. Which SCC applies depends on what the pod's service account may use, ordered by priority and then by how restrictive each one is. This lesson follows one pod through SCC admission, compares SCCs with Pod Security Admission, PodSecurityPolicy, Kyverno, and Gatekeeper, and shows the two classic mistakes: granting anyuid to make a root image work, and letting a CI service account use privileged.

Difficulty: Advanced · Know this first: Lesson 133, Lesson 239

What you will learn

By the end of this lesson you can work at four levels:

This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up minutes from apply to a correctly confined pod. It is a worked example, not a measurement. The allowed-SCCs and checks hops are where access grows too wide.

Try it: which SCC admits this pod?

Pick what the pod asks for and which SCCs its service account may use. Admission tries them by priority, then most restrictive first.

noneSCC used
refusedruns as

Refused: unable to validate against any security context constraint

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Working with SCCs grows in four levels: reading them, granting them narrowly, writing your own, and governing them across a cluster.

Basic — Read what happened

At the basic level you can tell which SCC a pod got and why it was refused.

  • oc get scc, oc describe scc restricted-v2.
  • The openshift.io/scc annotation on a pod; the project's sa.scc annotations.
  • "unable to validate against any security context constraint" in the ReplicaSet's events.

Where it breaks: looking at the Deployment's events, when the refusal is on the ReplicaSet.

Try it: Basic

A Deployment has 0 pods and no errors on it. Where do you look?

Now do it: Create a pod with runAsUser: 0 under restricted-v2 and find the error.

Intermediate — Grant narrowly

At the intermediate level grants are small and deliberate.

  • One service account per workload; oc adm policy add-scc-to-user nonroot-v2 -z app-sa, never to default.
  • oc adm policy scc-subject-review -f pod.yaml to see which SCC would admit a pod before you apply it.
  • oc adm policy who-can use scc anyuid to audit grants.

Try it: Intermediate

An image runs as UID 1001 and refuses random UIDs. Which SCC fits best?

Now do it: Move one workload from anyuid to nonroot-v2.

Advanced — Write a custom SCC

At the advanced level you write the SCC a special workload needs, and no more.

  • Start from restricted-v2 and add one thing: a capability, allowHostDirVolumePlugin, or host ports.
  • A Role with verbs: [use] on that SCC, bound to one service account.
  • openshift.io/required-scc on the pod template (OpenShift 4.14 and later) so it cannot pick a different one.

Try it: Advanced

A log shipper needs to read /var/log on the node. What do you give it?

Now do it: Write that SCC and a Role granting use of it.

Master — Govern SCCs across the cluster

At the master level SCC use is policy, reviewed and audited.

  • Grants in Git through GitOps, reviewed like code; no ad hoc oc adm policy in production.
  • A regular report of pods by openshift.io/scc; alerts on new privileged pods outside system projects.
  • Kyverno or Gatekeeper alongside SCCs for what SCCs cannot express (allowed host paths, image sources, labels).

Trade-off: strict SCCs push work onto image builders (any-UID images) and stop a whole class of container escapes.

Try it: Master

How do you find every application pod running with privileged or anyuid?

Now do it: Write the query and run it on a cluster.

Go deeper

A narrow custom SCC for a log shipper: restricted-v2 plus host-directory volumes, granted to one service account.

apiVersion: security.openshift.io/v1
kind: SecurityContextConstraints
metadata:
  name: log-shipper
priority: null
allowPrivilegedContainer: false
allowPrivilegeEscalation: false
allowHostNetwork: false
allowHostPID: false
allowHostIPC: false
allowHostPorts: false
allowHostDirVolumePlugin: true          # the one thing added: hostPath volumes
readOnlyRootFilesystem: true
requiredDropCapabilities: [ALL]
allowedCapabilities: []
runAsUser: {type: MustRunAsRange}
seLinuxContext: {type: MustRunAs}
fsGroup: {type: MustRunAs}
supplementalGroups: {type: RunAsAny}
seccompProfiles: [runtime/default]
volumes: [configMap, downwardAPI, emptyDir, hostPath, projected, secret]
users: []
groups: []
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata: {name: use-log-shipper-scc, namespace: logging}
rules:
- apiGroups: [security.openshift.io]
  resources: [securitycontextconstraints]
  resourceNames: [log-shipper]
  verbs: [use]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata: {name: log-shipper-scc, namespace: logging}
roleRef: {apiGroup: rbac.authorization.k8s.io, kind: Role, name: use-log-shipper-scc}
subjects:
- {kind: ServiceAccount, name: log-shipper, namespace: logging}

SCCs allow hostPath volumes as a whole; they cannot limit which host paths. Add a Kyverno or Gatekeeper rule for that, and mount the path read-only in the pod.

How SCCs compare with the other ways to control what pods may do:

OpenShift SCCPod Security AdmissionPodSecurityPolicyKyvernoOPA Gatekeeper
WhereBuilt into OpenShiftBuilt into Kubernetes 1.25 and laterRemoved in Kubernetes 1.25Add-on (CNCF)Add-on (CNCF, based on OPA)
Applies toUsers and service accounts, through RBAC useA whole namespace, through labelsUsers and service accounts, through RBAC useAny resource matched by a policyAny resource matched by a constraint
Changes the pod?Yes: UID, SELinux level, fsGroup, seccompNo: enforce, warn, or audit onlyYes: defaultsYes, with mutate rules; can also generate resourcesValidation first; mutation through Assign resources
How rules are writtenFields in an SCC objectThree fixed levels: privileged, baseline, restrictedFields in a policy objectYAML policies (patterns or CEL)Rego in constraint templates
Finest controlMany fields; no allowed host-path listFixed checklistsMany fields, including allowed host pathsAnything a policy can expressAnything Rego can express
Use it forThe default on OpenShiftThe default on other KubernetesMigrating away from itRules and defaults beyond PSA or SCCOrganisation-wide policy and audit

Managed Kubernetes (EKS, AKS, GKE) has Pod Security Admission built in; AKS (Azure Policy) and GKE (Policy Controller) add policy services built on Gatekeeper, and Kyverno or Gatekeeper can be installed on any of them. On OpenShift, Kyverno and Gatekeeper run alongside SCCs, not instead of them.

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. A privileged grant outlived its reason.

Timeline

  • Month 0A CI pipeline needs Docker-in-Docker builds. To make it work, its service account is bound to system:openshift:scc:privileged.
  • Month 3Builds move to a rootless builder that needs no special SCC. The grant stays.
  • Month 8A pull request from a fork changes a build step to start a privileged pod with the node's root file system mounted. It reads the kubelet's credentials and other pods' mounted secrets.
  • Month 8, +8 hThe node is drained and rebuilt, the secrets that were on it are rotated, and the grant is removed.

What changed after

SCC grants live in Git with an owner and an expiry date, a weekly report lists pods by openshift.io/scc, an alert fires on any privileged pod outside openshift-* projects, and builds from forks run in a separate, unprivileged project.

Try it yourself, from scratch

Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.

Before you start: An OpenShift cluster to practise on: OpenShift Local (crc) runs one on a laptop; log in as the kubeadmin user for the policy commands.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. List the SCCs with their priority and the settings that matter most.

    oc get scc
  2. Read the SCC most pods get.

    oc describe scc restricted-v2
  3. Make a project and read the UID range and SELinux level it was given.

    oc new-project scc-lab
    oc get namespace scc-lab -o yaml | grep "openshift.io/sa.scc"
  4. Run a pod, then read which SCC admitted it and the UID it runs as.

    oc run web --image=registry.access.redhat.com/ubi9/ubi-minimal -- sleep 3600
    oc wait --for=condition=Ready pod/web --timeout=120s
    oc get pod web -o jsonpath='{.metadata.annotations.openshift\.io/scc}{"\n"}'
    oc exec web -- id
  5. Ask which SCC would admit a pod that wants root, before creating it.

    cat > root-pod.yaml <<'EOF'
    apiVersion: v1
    kind: Pod
    metadata: {name: root-test}
    spec:
      securityContext: {runAsUser: 0}
      containers:
      - {name: c, image: registry.access.redhat.com/ubi9/ubi-minimal, command: [sleep, "3600"]}
    EOF
    oc adm policy scc-subject-review -f root-pod.yaml
  6. Give one service account nonroot-v2, the RBAC way, and check who can use it.

    oc create serviceaccount legacy-app
    oc adm policy add-scc-to-user nonroot-v2 -z legacy-app
    oc adm policy who-can use scc nonroot-v2 | grep -A3 "ServiceAccounts"
  7. See the Pod Security labels OpenShift synced onto the project.

    oc get namespace scc-lab --show-labels

2. Python: scc_admission.py

This program follows SCC admission for five pods: it takes the SCCs each service account may use, sorts them by priority and then by how restrictive they are, and uses the first one that accepts the pod, filling in the UID from the project's range. Save it as scc_admission.py, then run it.

# scc_admission.py
UID_RANGE = (1000680000, 10000)
SCCS = {  # name: (priority, restrictiveness rank, what it allows)
    "restricted-v2":  (0, 1, {"uid": "range", "host_network": False, "caps": {"NET_BIND_SERVICE"}, "host_path": False}),
    "nonroot-v2":     (0, 2, {"uid": "nonroot", "host_network": False, "caps": {"NET_BIND_SERVICE"}, "host_path": False}),
    "hostnetwork-v2": (0, 3, {"uid": "range", "host_network": True, "caps": {"NET_BIND_SERVICE"}, "host_path": False}),
    "anyuid":         (10, 4, {"uid": "any", "host_network": False, "caps": set(), "host_path": False}),
    "privileged":     (0, 9, {"uid": "any", "host_network": True, "caps": {"ALL"}, "host_path": True}),
}

def accepts(rule, pod):
    uid = pod.get("run_as_user")
    if rule["uid"] == "range" and uid is not None and not (UID_RANGE[0] <= uid < sum(UID_RANGE)):
        return False
    if rule["uid"] == "nonroot" and uid == 0:
        return False
    if pod.get("host_network") and not rule["host_network"]:
        return False
    if pod.get("host_path") and not rule["host_path"]:
        return False
    extra = set(pod.get("caps", [])) - rule["caps"]
    return not extra or "ALL" in rule["caps"]

def admit(pod, may_use):
    order = sorted(may_use, key=lambda n: (-SCCS[n][0], SCCS[n][1], n))
    for name in order:
        if accepts(SCCS[name][2], pod):
            uid = pod.get("run_as_user")
            if uid is None:
                uid = UID_RANGE[0] if SCCS[name][2]["uid"] == "range" else "image USER"
            return f"{name:<15} runs as {uid}   (tried: {', '.join(order)})"
    return f"{'REFUSED':<15} unable to validate against any security context constraint   (tried: {', '.join(order)})"

pods = [
    ("plain web pod", {}, ["restricted-v2"]),
    ("wants root", {"run_as_user": 0}, ["restricted-v2"]),
    ("fixed UID 1001", {"run_as_user": 1001}, ["restricted-v2", "nonroot-v2"]),
    ("plain pod, anyuid granted", {}, ["restricted-v2", "anyuid"]),
    ("log shipper with hostPath", {"host_path": True}, ["restricted-v2", "privileged"]),
]
for label, pod, may_use in pods:
    print(f"{label:<27} -> {admit(pod, may_use)}")

Run it, and you should see this output:

$ python3 scc_admission.py
plain web pod               -> restricted-v2   runs as 1000680000   (tried: restricted-v2)
wants root                  -> REFUSED         unable to validate against any security context constraint   (tried: restricted-v2)
fixed UID 1001              -> nonroot-v2      runs as 1001   (tried: restricted-v2, nonroot-v2)
plain pod, anyuid granted   -> anyuid          runs as image USER   (tried: anyuid, restricted-v2)
log shipper with hostPath   -> privileged      runs as image USER   (tried: restricted-v2, privileged)

3. What to notice

4. Advanced: every step as one Bash script

The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/openshift-security-context-constraints && cd ~/labs/openshift-security-context-constraints) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "OpenShift Security Context Constraints in Depth", as one script (save it as lab.sh).
#
#   ./lab.sh          run every step, in order
#   ./lab.sh 2 4      run only steps 2 and 4
#   ./lab.sh --list   list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.

STEPS=(
  'List the SCCs with their priority and the settings that matter most.'
  'Read the SCC most pods get.'
  'Make a project and read the UID range and SELinux level it was given.'
  'Run a pod, then read which SCC admitted it and the UID it runs as.'
  'Ask which SCC would admit a pod that wants root, before creating it.'
  'Give one service account nonroot-v2, the RBAC way, and check who can use it.'
  'See the Pod Security labels OpenShift synced onto the project.'
)

step_1() {
oc get scc
}

step_2() {
oc describe scc restricted-v2
}

step_3() {
oc new-project scc-lab
oc get namespace scc-lab -o yaml | grep "openshift.io/sa.scc"
}

step_4() {
oc run web --image=registry.access.redhat.com/ubi9/ubi-minimal -- sleep 3600
oc wait --for=condition=Ready pod/web --timeout=120s
oc get pod web -o jsonpath='{.metadata.annotations.openshift\.io/scc}{"\n"}'
oc exec web -- id
}

step_5() {
cat > root-pod.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata: {name: root-test}
spec:
  securityContext: {runAsUser: 0}
  containers:
  - {name: c, image: registry.access.redhat.com/ubi9/ubi-minimal, command: [sleep, "3600"]}
EOF
oc adm policy scc-subject-review -f root-pod.yaml
}

step_6() {
oc create serviceaccount legacy-app
oc adm policy add-scc-to-user nonroot-v2 -z legacy-app
oc adm policy who-can use scc nonroot-v2 | grep -A3 "ServiceAccounts"
}

step_7() {
oc get namespace scc-lab --show-labels
}

# print a step that has to be run by hand, instead of running it
by_hand() {
  echo "  (run this one yourself: $1)"
  sed 's/^/    /'
}

RESULTS=()
run_step() {
  local n=$1 start=$SECONDS code
  printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
  "step_$n"
  code=$?
  RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}

summary() {
  echo
  echo "== summary"
  local r
  for r in "${RESULTS[@]}"; do echo "  $r"; done
}

case "${1:-}" in
  -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
  --list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac

[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
  if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
    echo "there is no step '$n'; try --list" >&2
    exit 2
  fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done

Then make it executable and run it:

chmod +x lab.sh
./lab.sh --list     # the steps
./lab.sh            # every step, then a summary of exit codes and times
./lab.sh 2 3        # only steps 2 and 3

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Your OpenShift cluster hosts 40 teams. Design how pods get their SCCs: defaults, exceptions, how teams request them, and how you audit them.

Clarifying questions to ask

Which SCC do ordinary workloads get? How does a team get nonroot-v2 or a custom SCC, and for how long? How do you stop anyuid and privileged spreading? What do you report and alert on? Where do Pod Security labels and a policy engine fit?

Rough sizing

Say 40 projects, about 1,500 pods, five workloads that genuinely need host access, and a security review every quarter.

Shape of the answer

restricted-v2 for everything by default; per-workload service accounts; exceptions as pull requests to a GitOps repository adding a Role with use on nonroot-v2 or a named custom SCC, with an owner and expiry label; no grants to default service accounts (a Kyverno or Gatekeeper rule rejects such RoleBindings); a weekly report of pods by openshift.io/scc and an alert on privileged outside openshift-* projects; PSA labels left synced; images built to run as any UID.

Trade-offs to name

A strict default with reviewed exceptions slows teams that bring root-expecting images, and makes every exception visible; per-workload service accounts mean more objects, and grants that are exactly as wide as they need to be.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
An image that needs rootHop 6: The checksBreaksrestricted-v2 gives the container a UID from the range, so the root-expecting image cannot write /var/cache and crash-loops; a later attempt with runAsUser: 0 is refused outright.
An image that needs rootHop 9: Pod SecurityDegradesWith anyuid in use, the synced level drops to baseline or privileged for the project.
CI can use privilegedHop 3: Allowed SCCsBreakspipeline was bound to system:openshift:scc:privileged eight months ago for a Docker-in-Docker build that no longer exists.
CI can use privilegedHop 4: OrderDegradesprivileged sorts last among priority-0 SCCs, but it is the only one that accepts this pod.
CI can use privilegedHop 6: The checksDegradesprivileged accepts everything: root, every capability, host mounts.
CI can use privilegedHop 9: Pod SecurityDegradesThe CI project is labelled privileged.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: The pod spec → Who is asking → Allowed SCCs → Order → Namespace ranges → The checks → Defaults filled in → Annotation → Pod Security. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

References and review

The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.

Last updated . Next review due by November 2027. Found something out of date? Tell me.

Saved on this device, in this browser.
Next in this series · Lesson 241
Kubernetes Secrets & ConfigMaps: The Cluster's Own Config System

Lesson 118 taught you how to create a Secret and a ConfigMap and hand them to a pod. This lesson teaches you the system behind them: the five kinds of Secret, the choice between an env var and a file, the encryption that protects…

Go to Lesson 241 →

Or browse the full course from the Lessons index.