Back to Security & Vulnerability Analysis

k8s-security-policies

Kubernetesk8ssecurityNetworkPolicyRBACPod Security Standardscloud nativedevops
36.8k📄 MIT🕒 2026-06-16Source ↗

Install this skill

npx skills add wshobson/agents

Works across Claude Code, Cursor, Codex, Copilot & Antigravity

This skill provides a structured framework for applying hardening techniques across Kubernetes clusters. It addresses administrative access control via RBAC, network isolation through traffic filtering, and container runtime security using Pod Security Standards and SecurityContext settings. Instead of relying on manual configurations, this module organizes infrastructure security into defined segments: privileged, baseline, and restricted namespaces, along with specific network policy definitions for egress and ingress. It also includes integration patterns for OPA Gatekeeper to enforce custom compliance rules through Rego policies. By aligning cluster configurations with these hardened templates, operators reduce the attack surface of multi-tenant environments and maintain consistent security postures across production and development workloads. The skill acts as a reference library for auditing cluster-wide permissions and validating container execution environments.

When to Use This Skill

  • Hardening multi-tenant cluster environments against lateral movement
  • Ensuring internal compliance by enforcing mandatory resource labels
  • Restricting container capabilities to prevent root-level execution
  • Auditing cluster access permissions using scoped Role and ClusterRole definitions

How to Invoke This Skill

Example prompts that trigger this skill in Claude Code, Cursor, or Antigravity:

  • Apply a default deny network policy to my production namespace
  • Create a restricted pod security profile for new deployments
  • Setup RBAC rules to allow read access to pods only
  • Configure mTLS peer authentication using Istio patterns
  • Enforce required labels on all new deployments using Gatekeeper

Pro Tips

  • 💡Always start with a 'Restricted' Pod Security Standard and only escalate privileges when absolutely necessary, documenting all exceptions clearly.
  • 💡Regularly audit your NetworkPolicies and RBAC configurations to ensure they align with the principle of least privilege and prevent unintended access.
  • 💡Integrate these security policies into your CI/CD pipeline using policy-as-code tools to ensure consistent enforcement and prevent configuration drift across environments.

What this skill does

  • Define Pod Security Standards for automated namespace enforcement
  • Configure fine-grained NetworkPolicies to implement zero-trust ingress and egress
  • Apply least-privilege RBAC roles and bindings for users and service accounts
  • Inject OPA Gatekeeper constraints for custom object validation
  • Set restrictive Pod SecurityContexts to prevent privilege escalation

When not to use it

  • Managing application-level security that is better handled by an identity provider
  • Replacing dedicated security audit tools for compliance reporting

Example workflow

  1. Define a baseline Pod Security Standard for the target namespace
  2. Create a 'deny-all' NetworkPolicy to isolate the application traffic
  3. Define a Role with specific verbs to limit resource access
  4. Apply a RoleBinding to map the user to the new role
  5. Deploy a test pod with a hardened SecurityContext to verify constraints

Prerequisites

  • Kubernetes cluster with administrative access
  • kubectl configured for the target environment
  • OPA Gatekeeper installed for constraint enforcement

Pitfalls & limitations

  • !Default-deny network policies can block essential DNS resolution if not explicitly permitted
  • !Strict Pod Security Standards may cause legacy containers to fail if they require root access
  • !RBAC changes are immediate and can inadvertently lock out legitimate service accounts

FAQ

What happens if I apply a restricted pod security profile to an existing container?
Existing pods will continue running, but new pods or updates that violate the profile's restrictions will be rejected by the admission controller.
How does this differ from simple namespace isolation?
While namespaces provide logical separation, these policies enforce technical boundaries such as network traffic, API access, and system call privileges.
Can I use these policies on managed Kubernetes services like EKS or GKE?
Yes, these are standard Kubernetes manifests compatible with all major managed distributions that support admission webhooks and network plugins.

How it compares

This skill provides production-ready, standardized YAML patterns that reduce the risk of syntax errors inherent in crafting custom security manifests from scratch.

Source & trust

37k stars📄 MIT🕒 Updated 2026-06-16
📄 Full skill instructions — original source: wshobson/agents
# Kubernetes Security Policies

Comprehensive guide for implementing NetworkPolicy, PodSecurityPolicy, RBAC, and Pod Security Standards in Kubernetes.

## Purpose

Implement defense-in-depth security for Kubernetes clusters using network policies, pod security standards, and RBAC.

## When to Use This Skill

- Implement network segmentation
- Configure pod security standards
- Set up RBAC for least-privilege access
- Create security policies for compliance
- Implement admission control
- Secure multi-tenant clusters

## Pod Security Standards

### 1. Privileged (Unrestricted)

apiVersion: v1
kind: Namespace
metadata:
name: privileged-ns
labels:
pod-security.kubernetes.io/enforce: privileged
pod-security.kubernetes.io/audit: privileged
pod-security.kubernetes.io/warn: privileged


### 2. Baseline (Minimally restrictive)

apiVersion: v1
kind: Namespace
metadata:
name: baseline-ns
labels:
pod-security.kubernetes.io/enforce: baseline
pod-security.kubernetes.io/audit: baseline
pod-security.kubernetes.io/warn: baseline


### 3. Restricted (Most restrictive)

apiVersion: v1
kind: Namespace
metadata:
name: restricted-ns
labels:
pod-security.kubernetes.io/enforce: restricted
pod-security.kubernetes.io/audit: restricted
pod-security.kubernetes.io/warn: restricted


## Network Policies

### Default Deny All

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


### Allow Frontend to Backend

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


### Allow DNS

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-dns
namespace: production
spec:
podSelector: {}
policyTypes:
- Egress
egress:
- to:
- namespaceSelector:
matchLabels:
name: kube-system
ports:
- protocol: UDP
port: 53


**Reference:** See assets/network-policy-template.yaml

## RBAC Configuration

### Role (Namespace-scoped)

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: pod-reader
namespace: production
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "watch", "list"]


### ClusterRole (Cluster-wide)

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: secret-reader
rules:
- apiGroups: [""]
resources: ["secrets"]
verbs: ["get", "watch", "list"]


### RoleBinding

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: read-pods
namespace: production
subjects:
- kind: User
name: jane
apiGroup: rbac.authorization.k8s.io
- kind: ServiceAccount
name: default
namespace: production
roleRef:
kind: Role
name: pod-reader
apiGroup: rbac.authorization.k8s.io


**Reference:** See references/rbac-patterns.md

## Pod Security Context

### Restricted Pod

apiVersion: v1
kind: Pod
metadata:
name: secure-pod
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
fsGroup: 1000
seccompProfile:
type: RuntimeDefault
containers:
- name: app
image: myapp:1.0
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL


## Policy Enforcement with OPA Gatekeeper

### ConstraintTemplate

apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8srequiredlabels
spec:
crd:
spec:
names:
kind: K8sRequiredLabels
validation:
openAPIV3Schema:
type: object
properties:
labels:
type: array
items:
type: string
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8srequiredlabels
violation[{"msg": msg, "details": {"missing_labels": missing}}] {
provided := {label | input.review.object.metadata.labels[label]}
required := {label | label := input.parameters.labels[_]}
missing := required - provided
count(missing) > 0
msg := sprintf("missing required labels: %v", [missing])
}


### Constraint

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
name: require-app-label
spec:
match:
kinds:
- apiGroups: ["apps"]
kinds: ["Deployment"]
parameters:
labels: ["app", "environment"]


## Service Mesh Security (Istio)

### PeerAuthentication (mTLS)

apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
name: default
namespace: production
spec:
mtls:
mode: STRICT


### AuthorizationPolicy

apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
name: allow-frontend
namespace: production
spec:
selector:
matchLabels:
app: backend
action: ALLOW
rules:
- from:
- source:
principals: ["cluster.local/ns/production/sa/frontend"]


## Best Practices

1. **Implement Pod Security Standards** at namespace level
2. **Use Network Policies** for network segmentation
3. **Apply least-privilege RBAC** for all service accounts
4. **Enable admission control** (OPA Gatekeeper/Kyverno)
5. **Run containers as non-root**
6. **Use read-only root filesystem**
7. **Drop all capabilities** unless needed
8. **Implement resource quotas** and limit ranges
9. **Enable audit logging** for security events
10. **Regular security scanning** of images

## Compliance Frameworks

### CIS Kubernetes Benchmark

- Use RBAC authorization
- Enable audit logging
- Use Pod Security Standards
- Configure network policies
- Implement secrets encryption at rest
- Enable node authentication

### NIST Cybersecurity Framework

- Implement defense in depth
- Use network segmentation
- Configure security monitoring
- Implement access controls
- Enable logging and monitoring

## Troubleshooting

**NetworkPolicy not working:**

# Check if CNI supports NetworkPolicy
kubectl get nodes -o wide
kubectl describe networkpolicy <name>


**RBAC permission denied:**

# Check effective permissions
kubectl auth can-i list pods --as system:serviceaccount:default:my-sa
kubectl auth can-i '*' '*' --as system:serviceaccount:default:my-sa


## Reference Files

- assets/network-policy-template.yaml - Network policy examples
- assets/pod-security-template.yaml - Pod security policies
- references/rbac-patterns.md - RBAC configuration patterns

## Related Skills

- k8s-manifest-generator - For creating secure manifests
- gitops-workflow - For automated policy deployment

How to Use This Skill Unit

Option A: Project-Specific (Recommended)

  1. Click "Download" above
  2. In your project, create the directory: .agent/skills/k8s-security-policies/
  3. Save the file as SKILL.md
  4. The agent will automatically discover the skill based on its description.

Option B: Global Installation (All Agents)

Save the file to these locations to make it available across all projects:

  • Claude Code: ~/.claude/skills/wshobson/agents/k8s-security-policies/SKILL.md
  • Cursor: ~/.cursor/skills/wshobson/agents/k8s-security-policies/SKILL.md
  • Antigravity: ~/.gemini/antigravity/skills/wshobson/agents/k8s-security-policies/SKILL.md

🚀 Install with CLI:
npx skills add wshobson/agents

Read the Master Guide: Mastering Agent Skills

Recommended Rules

View more rules

Recommended Workflows

View more workflows

Recommended MCP Servers

View more MCP servers

Take It Further

Maximize your productivity with these powerful resources

📋

Define Your Standards

Set up coding standards to ensure this workflow produces consistent, high-quality results.

Browse Rules Library
📖

Master Workflows

Learn how to create custom workflows, use Turbo Mode, and build your automation library.

Complete Guide

How to use this Skill in Claude Code & Cursor

For Claude Code (CLI)

To use this skill in Claude Code, copy the rule content into your project's custom instructions or follow our Add-Skill CLI guide. This ensures Claude follows your standards during every code generation.

For Cursor & Windsurf

For Cursor or Windsurf, individual skills are best used in the "Rules for AI" section. This specific unit helps the agent avoid security & vulnerability analysis issues, leading to cleaner, more efficient code.

Why the skill format matters: the standardized Agent Skills format lets your AI agent load detailed instructions only when they are relevant, keeping your prompt clean while improving results.

Source & attribution

This skill is categorized under Security & Vulnerability Analysis and is published by W. Shobson, maintained in wshobson/agents.

← Browse All Agent Skills
Sponsored AI assistant. Recommendations may be paid.