Stage 6, Part 2 of 9 · p. 48, RBAC, ServiceAccounts & Security

PART 2: ADVANCED CONCEPTS

6. Pod Security Standards

Pod Security Standards (PSS) define three security profiles that namespace admins can enforce.

The Three Levels

LevelRestrictivenessUse Case
PrivilegedUnrestrictedSystem workloads
BaselineMinimally restrictiveMost workloads
RestrictedHeavily restrictiveSecurity-critical

Privileged (No Restrictions)

Everything allowed. Only for cluster-admin workloads (CNI, monitoring, system components).

Baseline (Common Restrictions)

Blocks:

Allows:

Restricted (Maximum Security)

Everything in Baseline, plus:

Baseline vs Restricted Comparison

SettingBaselineRestricted
Privileged❌❌
Host namespaces❌❌
hostPath❌❌
Host ports❌❌
CapabilitiesLimitedDrop ALL
Privilege escalation❌❌
Non-rootOptionalRequired
Read-only rootfsOptionalRecommended
seccompOptionalRequired

7. Pod Security Admission

Pod Security Admission (PSA) is the built-in admission controller that enforces PSS.

Enforcing PSS via Namespace Labels

bash
kubectl label namespace production \
  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

The Three Modes

ModeBehavior
enforceReject violating Pods
auditLog violations
warnShow warning to user

Version Pinning

yaml
pod-security.kubernetes.io/enforce-version: v1.30
pod-security.kubernetes.io/enforce-version: latest

Pinning prevents surprises when the cluster is upgraded.

Migration Path

Recommended migration:

  1. Audit only: audit=restricted, no enforcement
  2. Warn only: warn=restricted
  3. Enforce baseline: enforce=baseline
  4. Enforce restricted: enforce=restricted

Exempting Namespaces

Some namespaces (kube-system, CNI plugins) need privileged access. Use a label:

yaml
pod-security.kubernetes.io/enforce: privileged

Or exclude at the API server:

text
--admission-control-config-file=/etc/kubernetes/admission-config.yaml

What PSS Doesn't Cover

PSS is limited to a specific set of security controls. For deeper policies (e.g., required labels, image registry whitelist), use Kyverno or OPA Gatekeeper.


8. Admission Webhooks

Admission webhooks are HTTP callbacks from the API server to external services. They run during admission.

Mutating vs Validating

TypeCan Modify?Order
Mutating✅ YesFirst
Validating❌ NoSecond

Failure Policy

PolicyBehaviorWhen to Use
FailReject if webhook unreachableSecurity-critical
IgnoreAllow if webhook unreachableOptional features

Webhook Timeout

Default: 10 seconds (configurable up to 30).

The Recovery Pattern

If a webhook is blocking cluster recovery:

bash
# Temporarily change failurePolicy to Ignore
kubectl patch validatingwebhookconfiguration <name> --type='json' \
  -p='[{"op":"replace","path":"/webhooks/0/failurePolicy","value":"Ignore"}]'

⚠️ This disables enforcement. Use only during confirmed outages.

Webhook Anti-Patterns

Anti-PatternRisk
failurePolicy: Fail with no HAWebhook outage → cluster outage
Webhooks for every resourceMassive overhead
Slow webhooks (> 1s)Cluster-wide slowdown
No timeoutRequests hang
Broad resource scopeUnintended side effects

9. OPA Gatekeeper

OPA (Open Policy Agent) Gatekeeper is a policy engine that uses Rego (a declarative policy language).

Architecture

text
┌─────────────────────────────────────────────────────────────┐
│                    OPA GATEKEEPER                           │
│                                                             │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  Gatekeeper Controller                              │   │
│  │  • Watches ConstraintTemplates and Constraints      │   │
│  │  • Manages policies                                 │   │
│  └──────────────────────┬──────────────────────────────┘   │
│                         │                                   │
│                         ▼                                   │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  Gatekeeper Webhook                                 │   │
│  │  • Receives admission requests                      │   │
│  │  • Evaluates against Rego policies                  │   │
│  │  • Returns allow/deny                               │   │
│  └─────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────┘

The Two CRDs

CRDPurpose
ConstraintTemplateDefines a policy type (Rego code)
ConstraintInstance of a policy with parameters

ConstraintTemplate Example

yaml
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])
      }

Constraint Example

yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
  name: require-team-label
spec:
  match:
    kinds:
    - apiGroups: [""]
      kinds: ["Pod"]
    namespaces: ["production"]
  parameters:
    labels: ["team", "environment"]

Common OPA Gatekeeper Use Cases

PolicyPurpose
Required labelsEnforce metadata
Allowed registriesImage policy
No privilegedPod security
Resource limitsGovernance
Namespace restrictionsMulti-tenancy

OPA Rego vs YAML

AspectOPA/RegoKyverno/YAML
LanguageRego (custom DSL)YAML
PowerVery highHigh
Learning curveSteepGentle
EcosystemCNCFKyverno
Best forComplex policiesKubernetes-native

10. Kyverno

Kyverno is a Kubernetes-native policy engine. Policies are written in YAML (no custom DSL).

The Two CRDs

CRDPurpose
ClusterPolicyCluster-wide policy
PolicyNamespace-scoped policy

Kyverno Rule Types

TypePurpose
validateAccept/deny resources
mutateModify resources
generateCreate resources
verifyImagesVerify image signatures

Validation Policy Example

yaml
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: require-non-root
spec:
  validationFailureAction: Enforce
  background: true
  rules:
  - name: check-runAsNonRoot
    match:
      any:
      - resources:
          kinds:
          - Pod
    validate:
      message: "Containers must set runAsNonRoot: true"
      pattern:
        spec:
          containers:
          - securityContext:
              runAsNonRoot: true

Mutation Policy Example

yaml
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: add-default-labels
spec:
  rules:
  - name: add-team-label
    match:
      any:
      - resources:
          kinds:
          - Pod
    mutate:
      patchStrategicMerge:
        metadata:
          labels:
            team: unknown

Generate Policy Example

yaml
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: generate-default-networkpolicy
spec:
  rules:
  - name: create-default-deny
    match:
      any:
      - resources:
          kinds:
          - Namespace
    generate:
      synchronize: true
      kind: NetworkPolicy
      name: default-deny
      namespace: "{{request.object.metadata.name}}"
      data:
        spec:
          podSelector: {}
          policyTypes:
          - Ingress
          - Egress

Kyverno Validation Failure Actions

ActionBehavior
EnforceBlock violation
AuditLog only (report)

Kyverno Best Practices

PracticeWhy
Start with AuditDon't break workloads
Test in stagingPolicies can have bugs
Version-control policiesGitOps
Use background: trueRetroactive enforcement
Set validationFailureActionEnforce vs audit
Exclude system namespacesCNI, kube-system

11. Image Policy

Image policy governs which container images are allowed in the cluster.

The Three Layers

LayerToolPurpose
RegistryHarbor, ECRStore scanned images
AdmissionKyverno verifyImagesVerify signatures at deploy
RuntimeFalco, TetragonDetect anomalous behavior

Image Signature Verification with cosign

Sign an image:

bash
cosign sign --key cosign.key myregistry/myapp:v1.0.0

Verify in Kyverno:

yaml
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: verify-image-signature
spec:
  validationFailureAction: Enforce
  rules:
  - name: verify-cosign-signature
    match:
      any:
      - resources:
          kinds:
          - Pod
    verifyImages:
    - imageReferences:
      - "myregistry.example.com/*"
      attestors:
      - entries:
        - keys:
            publicKeys: |-
              -----BEGIN PUBLIC KEY-----
              MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...
              -----END PUBLIC KEY-----

The Full Image Policy Pipeline

text
Developer → Build Image → Trivy Scan → Fail on CRITICAL → Push
                                                              │
                                                              ▼
                                                    Cosign Sign
                                                              │
                                                              ▼
                                              Registry (Harbor/ECR)
                                                              │
                                                              ▼
                                              Admission (Kyverno)
                                              Verify Signature
                                                              │
                                                              ▼
                                              Deploy to Cluster
                                                              │
                                                              ▼
                                              Runtime (Falco/Tetragon)

Image Policy Best Practices

PracticeWhy
Sign all imagesProve provenance
Scan before signBlock vulnerabilities
Verify at admissionReject unsigned
Use SBOMSupply chain visibility
Pin by digestImmutability
Block :latestNon-deterministic

12. Secrets Management

Secrets in Kubernetes are base64-encoded, not encrypted by default. Production requires external secret management.

The Problem with Native Secrets

IssueImpact
Base64 (not encryption)Anyone with read access can decode
etcd storageDepends on etcd encryption
No rotationManual, error-prone
In GitLeaked into version history
In env varsVisible in docker inspect

Encryption at Rest

Enable etcd encryption at rest:

yaml
apiVersion: apiserver.config.k8s.io/v1
kind: EncryptionConfiguration
resources:
- resources:
  - secrets
  - configmaps
  providers:
  - aescbc:
      keys:
      - name: key1
        secret: <base64-key>
  - identity: {}

Pass to kube-apiserver: --encryption-provider-config=/etc/kubernetes/encryption-config.yaml.

External Secrets Operator

External Secrets Operator (ESO) syncs secrets from external stores to Kubernetes.

Supported stores:

Example ExternalSecret:

yaml
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
  name: db-secret
spec:
  refreshInterval: 1h
  secretStoreRef:
    name: aws-secrets-manager
    kind: SecretStore
  target:
    name: db-secret
  data:
  - secretKey: password
    remoteRef:
      key: prod/db/password

Sealed Secrets

Sealed Secrets encrypts secrets so they can be safely committed to Git.

bash
# Encrypt
kubeseal --format=yaml < secret.yaml > sealed-secret.yaml

# The sealed secret is safe to commit
git add sealed-secret.yaml

# Sealed Secrets controller decrypts in-cluster
kubectl apply -f sealed-secret.yaml

SOPS (Secrets OPerationS)

SOPS encrypts YAML/JSON files using cloud KMS. Works with GitOps.

bash
# Encrypt
sops --encrypt --age <age-key> secret.yaml > secret.enc.yaml

# Decrypt
sops --decrypt secret.enc.yaml

Vault Integration

HashiCorp Vault is the enterprise standard. Integration methods:

MethodDescription
Vault Agent InjectorSidecar injects secrets
Vault Secrets OperatorSyncs Vault to K8s Secrets
CSI Secrets StoreMounts secrets as volumes
Vault APIDirect API access

Secrets Management Comparison

ApproachComplexitySecurityUse Case
Native SecretsLow⚠️ Base64Dev/test
Encryption at restMedium✅Basic hardening
Sealed SecretsLow✅GitOps
SOPSLow✅GitOps + KMS
External SecretsMedium✅✅Multi-cloud
VaultHigh✅✅✅Enterprise

13. SecurityContext Deep Dive

SecurityContext is where you configure container security at the Pod and container level.

Pod-Level SecurityContext

yaml
spec:
  securityContext:
    runAsUser: 1000
    runAsGroup: 1000
    fsGroup: 1000
    runAsNonRoot: true
    fsGroupChangePolicy: "OnRootMismatch"
    seccompProfile:
      type: RuntimeDefault
    supplementalGroups: [2000]
    sysctls:
    - name: net.ipv4.ip_unprivileged_port_start
      value: "0"

Container-Level SecurityContext

yaml
spec:
  containers:
  - name: app
    securityContext:
      runAsUser: 1000
      runAsGroup: 1000
      runAsNonRoot: true
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      privileged: false
      capabilities:
        drop: ["ALL"]
        add: ["NET_BIND_SERVICE"]
      seccompProfile:
        type: RuntimeDefault
      procMount: Default

Key Security Context Fields

FieldPurpose
runAsUserUID to run container
runAsGroupGID to run container
runAsNonRootRequire non-root
fsGroupVolume ownership group
supplementalGroupsExtra groups
allowPrivilegeEscalationPrevent suid, setuid
readOnlyRootFilesystemImmutable rootfs
privilegedFull privileges (never)
capabilitiesLinux capabilities
seccompProfileSyscall filtering
procMountProc filesystem

The Complete Hardened SecurityContext

yaml
apiVersion: v1
kind: Pod
metadata:
  name: hardened
spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 1000
    runAsGroup: 1000
    fsGroup: 1000
    seccompProfile:
      type: RuntimeDefault
  automountServiceAccountToken: false
  containers:
  - name: app
    image: myapp:1.0
    securityContext:
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      privileged: false
      capabilities:
        drop: ["ALL"]
    resources:
      limits:
        cpu: 500m
        memory: 256Mi
    volumeMounts:
    - name: tmp
      mountPath: /tmp
  volumes:
  - name: tmp
    emptyDir: {}

This is the gold standard for workload hardening.


14. Audit Logging

Audit logging records every request to the API server with who/what/when/where.

Audit Policy

yaml
apiVersion: audit.k8s.io/v1
kind: Policy
rules:
# Log all secrets access (RequestResponse = full body)
- level: RequestResponse
  resources:
  - group: ""
    resources: ["secrets"]
  verbs: ["get", "list", "watch", "create", "update", "delete"]

# Log RBAC changes
- level: Request
  resources:
  - group: "rbac.authorization.k8s.io"
    resources: ["roles", "clusterroles", "rolebindings", "clusterrolebindings"]

# Log all authentication failures
- level: Metadata
  omitStages:
  - RequestReceived
  users: ["system:anonymous"]

Audit Levels

LevelWhat's Logged
NoneNothing
MetadataWho, what, when — no body
RequestMetadata + request body
RequestResponseMetadata + request + response

API Server Flags

text
--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

What to Audit

ResourceLevelWhy
SecretsRequestResponseTrack access
RBACRequestDetect privilege changes
Authentication failuresMetadataDetect attacks
Exec/port-forwardMetadataTrack access
Pod creationMetadataWorkload tracking

Audit Log Example

json
{
  "kind": "Event",
  "apiVersion": "audit.k8s.io/v1",
  "level": "RequestResponse",
  "timestamp": "2024-01-15T14:03:00Z",
  "user": {
    "username": "alice",
    "groups": ["developers"]
  },
  "sourceIPs": ["10.0.0.1"],
  "verb": "get",
  "resource": {
    "group": "",
    "resource": "secrets",
    "namespace": "production",
    "name": "db-password"
  },
  "responseStatus": {
    "code": 200
  }
}

Audit Log Best Practices

PracticeWhy
Log Secrets accessDetect data exfiltration
Log RBAC changesDetect privilege escalation
Ship to SIEMCentralized analysis
Retain 90+ daysCompliance
Alert on anomaliesDetect attacks
Protect audit logsAppend-only storage

15. Network Policies

Network Policies are the firewall for Pods. Covered in depth in Stage 7 (Networking), but essential for security.

Default Deny

yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny
  namespace: production
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  - Egress

Allow Specific Traffic

yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-frontend-to-backend
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: backend
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: frontend
    ports:
    - protocol: TCP
      port: 8080

Egress (Often Forgotten)

yaml
spec:
  policyTypes:
  - Egress
  egress:
  - to:
    - namespaceSelector:
        matchLabels:
          name: kube-system
    ports:
    - protocol: UDP
      port: 53

The default is allow-all egress. Attackers use egress for C2, exfiltration. Always define egress policies.


16. IRSA and Workload Identity

IRSA (IAM Roles for Service Accounts) allows Pods to assume AWS IAM roles without static credentials.

How IRSA Works

text
1. Cluster has OIDC provider configured
2. AWS IAM trusts the OIDC provider
3. A ServiceAccount is mapped to an IAM role
4. Pod uses its ServiceAccount token
5. AWS SDK exchanges the token for temporary IAM credentials
6. Pod makes AWS API calls with IAM role

Setting Up IRSA (AWS)

Step 1: Create OIDC provider for the cluster

bash
eksctl utils associate-iam-oidc-provider --cluster my-cluster --approve

Step 2: Create IAM role with trust policy

json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Federated": "arn:aws:iam::123456789:oidc-provider/oidc.eks.us-east-1.amazonaws.com/id/ABC123"
      },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "oidc.eks.us-east-1.amazonaws.com/id/ABC123:sub": "system:serviceaccount:production:my-app-sa",
          "oidc.eks.us-east-1.amazonaws.com/id/ABC123:aud": "sts.amazonaws.com"
        }
      }
    }
  ]
}

Step 3: Annotate ServiceAccount

yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: my-app-sa
  namespace: production
  annotations:
    eks.amazonaws.com/role-arn: arn:aws:iam::123456789:role/my-app-role

Step 4: Use in Pod

yaml
spec:
  serviceAccountName: my-app-sa
  containers:
  - name: app
    image: my-app:1.0
    # AWS SDK automatically uses IRSA credentials

Comparison

CloudNameMechanism
AWSIRSAOIDC + IAM Role
GCPWorkload IdentityGKE SA + GCP SA
AzureAzure AD Workload IdentityOIDC + Azure AD

Best Practices

PracticeWhy
One SA per workloadLeast privilege
One IAM role per SAAudit clarity
Scoped IAM policiesLeast privilege
No static credentialsRotation-free
Audit IAM role usageCloudTrail

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