Stage 6, Part 6 of 9, RBAC, ServiceAccounts & Security

Text

PART 6: HANDS-ON LABS

Lab 1: RBAC Basics

Goal: Create Roles, RoleBindings, ServiceAccounts.

bash
# Create a namespace
kubectl create namespace rbac-lab

# Create a ServiceAccount
kubectl create serviceaccount reader -n rbac-lab

# Create a Role
kubectl apply -n rbac-lab -f - <<'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: pod-reader
rules:
- apiGroups: [""]
  resources: ["pods", "pods/log"]
  verbs: ["get", "list", "watch"]
EOF

# Create a RoleBinding
kubectl apply -n rbac-lab -f - <<'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: reader-pod-reader
subjects:
- kind: ServiceAccount
  name: reader
  namespace: rbac-lab
roleRef:
  kind: Role
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io
EOF

# Verify
kubectl auth can-i list pods \
  --as=system:serviceaccount:rbac-lab:reader \
  -n rbac-lab

kubectl auth can-i create pods \
  --as=system:serviceaccount:rbac-lab:reader \
  -n rbac-lab
# Expected: no

# Cleanup
kubectl delete namespace rbac-lab

Lab 2: Least Privilege ServiceAccount

Goal: Create a Pod with a least-privilege SA.

bash
kubectl create namespace sa-lab

# Create a ServiceAccount that can read ConfigMaps
kubectl create serviceaccount config-reader -n sa-lab

kubectl apply -n sa-lab -f - <<'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: config-reader
rules:
- apiGroups: [""]
  resources: ["configmaps"]
  verbs: ["get", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: config-reader
subjects:
- kind: ServiceAccount
  name: config-reader
  namespace: sa-lab
roleRef:
  kind: Role
  name: config-reader
  apiGroup: rbac.authorization.k8s.io
EOF

# Create a config map
kubectl create configmap app-config --from-literal=key=value -n sa-lab

# Create a Pod using the SA
kubectl apply -n sa-lab -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
  name: config-reader-pod
spec:
  serviceAccountName: config-reader
  containers:
  - name: app
    image: bitnami/kubectl:latest
    command:
    - sh
    - -c
    - |
      # Read configmaps (allowed)
      kubectl get configmaps
      # Try to read secrets (should fail)
      kubectl get secrets || echo "FORBIDDEN as expected"
    env:
    - name: KUBERNETES_SERVICE_HOST
      value: "kubernetes.default.svc"
EOF

sleep 10
kubectl logs -n sa-lab config-reader-pod

# Cleanup
kubectl delete namespace sa-lab

Lab 3: Pod Security Standards

Goal: Enforce PSS and observe violations.

bash
# Create a namespace with restricted enforcement
kubectl create namespace pss-lab

kubectl label namespace pss-lab \
  pod-security.kubernetes.io/enforce=restricted \
  pod-security.kubernetes.io/enforce-version=latest \
  pod-security.kubernetes.io/audit=restricted \
  pod-security.kubernetes.io/warn=restricted

# Try a privileged Pod (should fail)
kubectl apply -n pss-lab -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
  name: bad
spec:
  containers:
  - name: app
    image: nginx
    securityContext:
      privileged: true
EOF
# Expected: Error from server (Forbidden)

# Try a compliant Pod
kubectl apply -n pss-lab -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
  name: good
spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 1000
    seccompProfile:
      type: RuntimeDefault
  containers:
  - name: app
    image: nginxinc/nginx-unprivileged:1.25-alpine
    securityContext:
      allowPrivilegeEscalation: false
      capabilities:
        drop: ["ALL"]
      readOnlyRootFilesystem: false
    resources:
      limits:
        cpu: 100m
        memory: 128Mi
EOF

kubectl get pod -n pss-lab good

# Cleanup
kubectl delete namespace pss-lab

Lab 4: Kyverno Policy

Goal: Enforce non-root with Kyverno.

bash
# Install Kyverno
helm repo add kyverno https://kyverno.github.io/kyverno/
helm install kyverno kyverno/kyverno -n kyverno --create-namespace

# Wait for Kyverno
kubectl wait --for=condition=Ready pods --all -n kyverno --timeout=180s

# Create a policy
kubectl apply -f - <<'EOF'
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: require-non-root
spec:
  validationFailureAction: Enforce
  background: false
  rules:
  - name: check-runAsNonRoot
    match:
      any:
      - resources:
          kinds:
          - Pod
    validate:
      message: "Pods must set runAsNonRoot: true"
      pattern:
        spec:
          containers:
          - securityContext:
              runAsNonRoot: true
EOF

# Try a non-compliant Pod
kubectl run bad --image=nginx
# Expected: denied by policy

# Try a compliant Pod
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata:
  name: good
spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 1000
  containers:
  - name: app
    image: nginxinc/nginx-unprivileged:1.25-alpine
    securityContext:
      runAsNonRoot: true
EOF

kubectl get pod good

# Cleanup
kubectl delete pod good --ignore-not-found
kubectl delete clusterpolicy require-non-root

Lab 5: OPA Gatekeeper Constraint

Goal: Enforce required labels.

bash
# Install OPA Gatekeeper
kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/deploy/gatekeeper.yaml

# Wait
kubectl wait --for=condition=Ready pods -l control-plane=controller-manager -n gatekeeper-system --timeout=180s

# Create a ConstraintTemplate
kubectl apply -f - <<'EOF'
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: k8srequiredlabels
spec:
  crd:
    spec:
      names:
        kind: K8sRequiredLabels
      validation:
        openAPIV3Schema:
          properties:
            labels:
              type: array
              items:
                type: string
  targets:
  - target: admission.k8s.gatekeeper.sh
    rego: |
      package k8srequiredlabels

      violation[{"msg": msg}] {
        provided := {label | input.review.object.metadata.labels[label]}
        required := {label | label := input.parameters.labels[_]}
        missing := required - provided
        count(missing) > 0
        msg := sprintf("Missing labels: %v", [missing])
      }
EOF

# Wait for the CRD
sleep 10

# Create a Constraint
kubectl apply -f - <<'EOF'
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
  name: require-team-label
spec:
  match:
    kinds:
    - apiGroups: [""]
      kinds: ["Pod"]
  parameters:
    labels: ["team"]
EOF

# Try a Pod without label
kubectl run bad --image=nginx
# Expected: denied

# Try a Pod with label
kubectl run good --image=nginx --labels=team=platform

# Cleanup
kubectl delete pod good --ignore-not-found
kubectl delete constraint require-team-label
kubectl delete constrainttemplate k8srequiredlabels

Lab 6: Image Signature Verification

Goal: Sign an image and verify at admission.

Prerequisites: cosign, a registry (Docker Hub, ECR, or local).

bash
# Generate a key pair
cosign generate-key-pair

# Build and push an image
cat > Dockerfile <<'EOF'
FROM alpine:3.19
CMD ["echo", "hello"]
EOF

docker build -t myregistry/myapp:v1 .
docker push myregistry/myapp:v1

# Sign the image
cosign sign --key cosign.key myregistry/myapp:v1

# Verify
cosign verify --key cosign.pub myregistry/myapp:v1

# In Kyverno, create a verifyImages policy
# (uses cosign.pub content)

Kyverno policy for image verification is in the main doc.


Lab 7: RBAC Debugging

Goal: Diagnose RBAC issues.

bash
kubectl create namespace rbac-debug

# Create a ServiceAccount
kubectl create serviceaccount limited -n rbac-debug

# Check permissions
kubectl auth can-i --list --as=system:serviceaccount:rbac-debug:limited -n rbac-debug
# Should show very limited (probably nothing)

# Create a Pod running as the SA
kubectl run limited --image=bitnami/kubectl:latest -n rbac-debug \
  --overrides='{"spec":{"serviceAccountName":"limited","containers":[{"name":"limited","image":"bitnami/kubectl:latest","command":["sh","-c","sleep 3600"]}]}}'

sleep 5

# Exec in and try commands
kubectl exec -n rbac-debug limited -- kubectl get pods
# Expected: Error from server (Forbidden)

# Check logs, events
kubectl describe pod limited -n rbac-debug

# Add permissions
kubectl create role pod-reader --verb=get,list,watch --resource=pods -n rbac-debug
kubectl create rolebinding limited --role=pod-reader \
  --serviceaccount=rbac-debug:limited -n rbac-debug

# Retry (may need to restart pod for token refresh; projected tokens rotate)
sleep 60
kubectl exec -n rbac-debug limited -- kubectl get pods
# Expected: succeeds

# Cleanup
kubectl delete namespace rbac-debug

Lab 8: Audit Logging

Goal: Configure and read audit logs.

Note: Requires kube-apiserver access (control plane node).

bash
# Create an audit policy (on the control plane node)
sudo tee /etc/kubernetes/audit-policy.yaml <<'EOF'
apiVersion: audit.k8s.io/v1
kind: Policy
rules:
- level: RequestResponse
  resources:
  - group: ""
    resources: ["secrets"]
- level: Request
  resources:
  - group: "rbac.authorization.k8s.io"
    resources: ["roles", "clusterroles", "rolebindings", "clusterrolebindings"]
- level: Metadata
  omitStages:
  - RequestReceived
EOF

# Add flags to kube-apiserver (edit the static pod)
# --audit-policy-file=/etc/kubernetes/audit-policy.yaml
# --audit-log-path=/var/log/kubernetes/audit.log
# --audit-log-maxage=30
# --audit-log-maxbackup=10
# --audit-log-maxsize=100

# Restart apiserver
# (Automatic in static pod mode)

# Read audit logs
sudo tail -f /var/log/kubernetes/audit.log | jq

# Trigger an event
kubectl get secrets -n default

# Check the audit log for the secret access
sudo grep "secrets" /var/log/kubernetes/audit.log | tail -5 | jq

Lab 9: End-to-End Secure Workload

Goal: Deploy a fully hardened workload.

bash
kubectl create namespace secure-app

# Label namespace for restricted PSS
kubectl label namespace secure-app \
  pod-security.kubernetes.io/enforce=restricted \
  pod-security.kubernetes.io/audit=restricted \
  pod-security.kubernetes.io/warn=restricted

# ServiceAccount
kubectl create serviceaccount app-sa -n secure-app

# Role + RoleBinding (read configmaps)
kubectl apply -n secure-app -f - <<'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: config-reader
rules:
- apiGroups: [""]
  resources: ["configmaps"]
  verbs: ["get", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: app-config-reader
subjects:
- kind: ServiceAccount
  name: app-sa
  namespace: secure-app
roleRef:
  kind: Role
  name: config-reader
  apiGroup: rbac.authorization.k8s.io
EOF

# ConfigMap
kubectl create configmap app-config --from-literal=key=value -n secure-app

# Hardened Deployment
kubectl apply -n secure-app -f - <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: secure-app
spec:
  replicas: 2
  selector:
    matchLabels:
      app: secure-app
  template:
    metadata:
      labels:
        app: secure-app
    spec:
      serviceAccountName: app-sa
      automountServiceAccountToken: false
      securityContext:
        runAsNonRoot: true
        runAsUser: 1000
        runAsGroup: 1000
        fsGroup: 1000
        seccompProfile:
          type: RuntimeDefault
      containers:
      - name: app
        image: nginxinc/nginx-unprivileged:1.25-alpine
        ports:
        - containerPort: 8080
        securityContext:
          allowPrivilegeEscalation: false
          readOnlyRootFilesystem: true
          capabilities:
            drop: ["ALL"]
        resources:
          requests:
            cpu: 100m
            memory: 128Mi
          limits:
            cpu: 500m
            memory: 256Mi
        volumeMounts:
        - name: cache
          mountPath: /var/cache/nginx
        - name: run
          mountPath: /var/run
      volumes:
      - name: cache
        emptyDir: {}
      - name: run
        emptyDir: {}
---
apiVersion: v1
kind: Service
metadata:
  name: secure-app
spec:
  selector:
    app: secure-app
  ports:
  - port: 80
    targetPort: 8080
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: secure-app
spec:
  minAvailable: 1
  selector:
    matchLabels:
      app: secure-app
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  - Egress
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-app
spec:
  podSelector:
    matchLabels:
      app: secure-app
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: ingress-nginx
  egress:
  - to:
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: kube-system
    ports:
    - protocol: UDP
      port: 53
EOF

# Verify
kubectl get all -n secure-app
kubectl get pdb,netpol -n secure-app

# Test
kubectl port-forward -n secure-app svc/secure-app 8080:80 &
sleep 2
curl http://localhost:8080
kill %1

# Cleanup
kubectl delete namespace secure-app

1:1 copy of the class Google Doc, code in code blocks.