K8s List security context settings for all running pods/containers
When trying to security harden (or pentest) a Kubernetes cluster, it is quite useful to be able to extract all security context settings without needing third party tools. Here’s an example using vanilla kubectl and go-templates:
kubectl get pods -n $NAMESPACE -o go-template --template='
{{range .items}}
{{"POD NAME: "}}{{.metadata.name}}
{{if .spec.securityContext}}
Pod Security Context:
- {{"runAsGroup: "}}{{.spec.securityContext.runAsGroup}}
- {{"runAsNonRoot: "}}{{.spec.securityContext.runAsNonRoot}}
- {{"runAsUser: "}}{{.spec.securityContext.runAsUser}}
{{if .spec.securityContext.seLinuxOptions}}
- {{"seLinuxOptions: "}}{{.spec.securityContext.seLinuxOptions}}
{{else}}
- seLinuxOptions is not set
{{end}}
{{else}}
!Pod Security Context is not set
{{end}}
{{range .spec.containers}}
{{"CONTAINER NAME: "}}{{.name}}
{{"IMAGE: "}}{{.image}}
{{if .securityContext}}
- {{"allowPrivilegeEscalation: "}}{{.securityContext.allowPrivilegeEscalation}}
{{if .securityContext.capabilities}}
- {{"capabilities: "}}{{.securityContext.capabilities}}
{{else}}
- "capabilities is not set
{{end}}
- {{"privileged: "}}{{.securityContext.privileged}}
{{if .securityContext.procMount}}
- {{"procMount: "}}{{.securityContext.procMount}}
{{else}}
- procMount in not set
{{end}}
- {{"readOnlyRootFilesystem: "}}{{.securityContext.readOnlyRootFilesystem}}
- {{"runAsGroup: "}}{{.securityContext.runAsGroup}}
- {{"runAsNonRoot: "}}{{.securityContext.runAsNonRoot}}
- {{"runAsUser: "}}{{.securityContext.runAsUser}}
{{if .securityContext.seLinuxOptions}}
- {{"seLinuxOptions: "}}{{.securityContext.seLinuxOptions}}
{{else}}
- seLinuxOptions is not set
{{end}}
{{if .securityContext.windowsOptions}}
- {{"windowsOptions: "}}{{.securityContext.windowsOptions}}
{{else}}
- windowsOptions is not set
{{end}}
{{else}}
!SecurityContext is not set!
{{end}}
{{end}}
{{end}}' | grep '\S'
Please note that container SecurityContexts overwrite PodSecurityContexts. For more information consult the official documentation.
Source
- https://medium.com/@pjbgf/kubectl-list-security-context-settings-for-all-pods-containers-within-a-cluster-93349681ef5d