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
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.
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.
Pick what the pod asks for and which SCCs its service account may use. Admission tries them by priority, then most restrictive first.
Refused: unable to validate against any security context constraint
Three questions. No score is saved anywhere — this is just you against the material.
Working with SCCs grows in four levels: reading them, granting them narrowly, writing your own, and governing them across a cluster.
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.openshift.io/scc annotation on a pod; the project's sa.scc annotations.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.
At the intermediate level grants are small and deliberate.
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.
At the advanced level you write the SCC a special workload needs, and no more.
restricted-v2 and add one thing: a capability, allowHostDirVolumePlugin, or host ports.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.
At the master level SCC use is policy, reviewed and audited.
oc adm policy in production.openshift.io/scc; alerts on new privileged pods outside system projects.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.
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 SCC | Pod Security Admission | PodSecurityPolicy | Kyverno | OPA Gatekeeper | |
|---|---|---|---|---|---|
| Where | Built into OpenShift | Built into Kubernetes 1.25 and later | Removed in Kubernetes 1.25 | Add-on (CNCF) | Add-on (CNCF, based on OPA) |
| Applies to | Users and service accounts, through RBAC use | A whole namespace, through labels | Users and service accounts, through RBAC use | Any resource matched by a policy | Any resource matched by a constraint |
| Changes the pod? | Yes: UID, SELinux level, fsGroup, seccomp | No: enforce, warn, or audit only | Yes: defaults | Yes, with mutate rules; can also generate resources | Validation first; mutation through Assign resources |
| How rules are written | Fields in an SCC object | Three fixed levels: privileged, baseline, restricted | Fields in a policy object | YAML policies (patterns or CEL) | Rego in constraint templates |
| Finest control | Many fields; no allowed host-path list | Fixed checklists | Many fields, including allowed host paths | Anything a policy can express | Anything Rego can express |
| Use it for | The default on OpenShift | The default on other Kubernetes | Migrating away from it | Rules and defaults beyond PSA or SCC | Organisation-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.
This is a composite of a failure pattern that keeps repeating; the details are illustrative. A privileged grant outlived its reason.
system:openshift:scc:privileged.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.
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.
Type each one, read what it prints, and compare it with the note above it.
List the SCCs with their priority and the settings that matter most.
oc get scc
Read the SCC most pods get.
oc describe scc restricted-v2
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"
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 -- idAsk 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.yamlGive 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"
See the Pod Security labels OpenShift synced onto the project.
oc get namespace scc-lab --show-labels
scc_admission.pyThis 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)
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
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
grep, cat, Pipes, Redirection, Here documents.Your OpenShift cluster hosts 40 teams. Design how pods get their SCCs: defaults, exceptions, how teams request them, and how you audit them.
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?
Say 40 projects, about 1,500 pods, five workloads that genuinely need host access, and a security review every quarter.
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.
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.
Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.
| Scenario | Where | Effect | What goes wrong |
|---|---|---|---|
| An image that needs root | Hop 6: The checks | Breaks | restricted-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 root | Hop 9: Pod Security | Degrades | With anyuid in use, the synced level drops to baseline or privileged for the project. |
| CI can use privileged | Hop 3: Allowed SCCs | Breaks | pipeline was bound to system:openshift:scc:privileged eight months ago for a Docker-in-Docker build that no longer exists. |
| CI can use privileged | Hop 4: Order | Degrades | privileged sorts last among priority-0 SCCs, but it is the only one that accepts this pod. |
| CI can use privileged | Hop 6: The checks | Degrades | privileged accepts everything: root, every capability, host mounts. |
| CI can use privileged | Hop 9: Pod Security | Degrades | The CI project is labelled privileged. |
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.