PART 2: ADVANCED CONCEPTS
6. Pod Security Standards
Pod Security Standards (PSS) define three security profiles that namespace admins can enforce.
The Three Levels
| Level | Restrictiveness | Use Case |
| Privileged | Unrestricted | System workloads |
| Baseline | Minimally restrictive | Most workloads |
| Restricted | Heavily restrictive | Security-critical |
Privileged (No Restrictions)
Everything allowed. Only for cluster-admin workloads (CNI, monitoring, system components).
Baseline (Common Restrictions)
Blocks:
- Privileged containers
- Host namespaces (hostNetwork, hostPID, hostIPC)
- hostPath volumes
- Host ports
- Unsafe capabilities (SYS_ADMIN, NET_ADMIN, etc.)
- Unsafe sysctls
- Privilege escalation
Allows:
- Running as root
- Any container user
- Read-write root filesystem
Restricted (Maximum Security)
Everything in Baseline, plus:
runAsNonRoot: truerequiredallowPrivilegeEscalation: falserequiredcapabilities.drop: [ALL]requiredseccompProfile.type: RuntimeDefaultorLocalhostrequiredreadOnlyRootFilesystemrecommended
Baseline vs Restricted Comparison
| Setting | Baseline | Restricted |
| Privileged | ❌ | ❌ |
| Host namespaces | ❌ | ❌ |
| hostPath | ❌ | ❌ |
| Host ports | ❌ | ❌ |
| Capabilities | Limited | Drop ALL |
| Privilege escalation | ❌ | ❌ |
| Non-root | Optional | Required |
| Read-only rootfs | Optional | Recommended |
| seccomp | Optional | Required |
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
| Mode | Behavior |
| enforce | Reject violating Pods |
| audit | Log violations |
| warn | Show 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:
- Audit only:
audit=restricted, no enforcement - Warn only:
warn=restricted - Enforce baseline:
enforce=baseline - 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
| Type | Can Modify? | Order |
| Mutating | ✅ Yes | First |
| Validating | ❌ No | Second |
Failure Policy
| Policy | Behavior | When to Use |
| Fail | Reject if webhook unreachable | Security-critical |
| Ignore | Allow if webhook unreachable | Optional 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-Pattern | Risk |
| failurePolicy: Fail with no HA | Webhook outage → cluster outage |
| Webhooks for every resource | Massive overhead |
| Slow webhooks (> 1s) | Cluster-wide slowdown |
| No timeout | Requests hang |
| Broad resource scope | Unintended 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
| CRD | Purpose |
| ConstraintTemplate | Defines a policy type (Rego code) |
| Constraint | Instance 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
| Policy | Purpose |
| Required labels | Enforce metadata |
| Allowed registries | Image policy |
| No privileged | Pod security |
| Resource limits | Governance |
| Namespace restrictions | Multi-tenancy |
OPA Rego vs YAML
| Aspect | OPA/Rego | Kyverno/YAML |
| Language | Rego (custom DSL) | YAML |
| Power | Very high | High |
| Learning curve | Steep | Gentle |
| Ecosystem | CNCF | Kyverno |
| Best for | Complex policies | Kubernetes-native |
10. Kyverno
Kyverno is a Kubernetes-native policy engine. Policies are written in YAML (no custom DSL).
The Two CRDs
| CRD | Purpose |
| ClusterPolicy | Cluster-wide policy |
| Policy | Namespace-scoped policy |
Kyverno Rule Types
| Type | Purpose |
| validate | Accept/deny resources |
| mutate | Modify resources |
| generate | Create resources |
| verifyImages | Verify 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
| Action | Behavior |
| Enforce | Block violation |
| Audit | Log only (report) |
Kyverno Best Practices
| Practice | Why |
| Start with Audit | Don't break workloads |
| Test in staging | Policies can have bugs |
| Version-control policies | GitOps |
Use background: true | Retroactive enforcement |
Set validationFailureAction | Enforce vs audit |
| Exclude system namespaces | CNI, kube-system |
11. Image Policy
Image policy governs which container images are allowed in the cluster.
The Three Layers
| Layer | Tool | Purpose |
| Registry | Harbor, ECR | Store scanned images |
| Admission | Kyverno verifyImages | Verify signatures at deploy |
| Runtime | Falco, Tetragon | Detect 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
| Practice | Why |
| Sign all images | Prove provenance |
| Scan before sign | Block vulnerabilities |
| Verify at admission | Reject unsigned |
| Use SBOM | Supply chain visibility |
| Pin by digest | Immutability |
Block :latest | Non-deterministic |
12. Secrets Management
Secrets in Kubernetes are base64-encoded, not encrypted by default. Production requires external secret management.
The Problem with Native Secrets
| Issue | Impact |
| Base64 (not encryption) | Anyone with read access can decode |
| etcd storage | Depends on etcd encryption |
| No rotation | Manual, error-prone |
| In Git | Leaked into version history |
| In env vars | Visible 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:
- AWS Secrets Manager
- AWS Systems Manager Parameter Store
- GCP Secret Manager
- Azure Key Vault
- HashiCorp Vault
- 1Password
- Doppler
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:
| Method | Description |
| Vault Agent Injector | Sidecar injects secrets |
| Vault Secrets Operator | Syncs Vault to K8s Secrets |
| CSI Secrets Store | Mounts secrets as volumes |
| Vault API | Direct API access |
Secrets Management Comparison
| Approach | Complexity | Security | Use Case |
| Native Secrets | Low | ⚠️ Base64 | Dev/test |
| Encryption at rest | Medium | ✅ | Basic hardening |
| Sealed Secrets | Low | ✅ | GitOps |
| SOPS | Low | ✅ | GitOps + KMS |
| External Secrets | Medium | ✅✅ | Multi-cloud |
| Vault | High | ✅✅✅ | 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
| Field | Purpose |
| runAsUser | UID to run container |
| runAsGroup | GID to run container |
| runAsNonRoot | Require non-root |
| fsGroup | Volume ownership group |
| supplementalGroups | Extra groups |
| allowPrivilegeEscalation | Prevent suid, setuid |
| readOnlyRootFilesystem | Immutable rootfs |
| privileged | Full privileges (never) |
| capabilities | Linux capabilities |
| seccompProfile | Syscall filtering |
| procMount | Proc 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
| Level | What's Logged |
| None | Nothing |
| Metadata | Who, what, when — no body |
| Request | Metadata + request body |
| RequestResponse | Metadata + 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
| Resource | Level | Why |
| Secrets | RequestResponse | Track access |
| RBAC | Request | Detect privilege changes |
| Authentication failures | Metadata | Detect attacks |
| Exec/port-forward | Metadata | Track access |
| Pod creation | Metadata | Workload 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
| Practice | Why |
| Log Secrets access | Detect data exfiltration |
| Log RBAC changes | Detect privilege escalation |
| Ship to SIEM | Centralized analysis |
| Retain 90+ days | Compliance |
| Alert on anomalies | Detect attacks |
| Protect audit logs | Append-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
| Cloud | Name | Mechanism |
| AWS | IRSA | OIDC + IAM Role |
| GCP | Workload Identity | GKE SA + GCP SA |
| Azure | Azure AD Workload Identity | OIDC + Azure AD |
Best Practices
| Practice | Why |
| One SA per workload | Least privilege |
| One IAM role per SA | Audit clarity |
| Scoped IAM policies | Least privilege |
| No static credentials | Rotation-free |
| Audit IAM role usage | CloudTrail |
1:1 copy of the class Google Doc, code in code blocks.