k8s-security-policies
Comprehensive guide for implementing NetworkPolicy, PodSecurityPolicy, RBAC, and Pod Security Standards in Kubernetes.
About this skill
This skill acts as an expert guide for AI agents, providing comprehensive instructions and best practices for securing Kubernetes clusters. It covers the implementation of NetworkPolicy to control network traffic flow, Role-Based Access Control (RBAC) for managing permissions, Pod Security Standards (PSS) for enforcing security at the pod level, and PodSecurityPolicy (PSP), acknowledging its role in past and potentially legacy systems. The AI agent leverages this skill to clarify user goals, apply relevant security best practices, offer actionable steps, and provide verification methods for robust Kubernetes security configurations. It can also refer to detailed examples within an internal playbook when required.
Best use case
Users can leverage this skill to design and implement secure configurations for Kubernetes clusters, audit existing cluster security postures, understand the nuances of Kubernetes security primitives, and generate best-practice recommendations for pod and cluster security.
Comprehensive guide for implementing NetworkPolicy, PodSecurityPolicy, RBAC, and Pod Security Standards in Kubernetes.
Users can expect to receive actionable advice, step-by-step instructions, and best-practice recommendations for securing their Kubernetes clusters. The guidance will cover how to effectively set up NetworkPolicies, RBAC, and align with Pod Security Standards, potentially including references to detailed implementation examples and verification steps.
Practical example
Example input
How do I implement a NetworkPolicy to isolate my backend pods in the 'production' namespace, allowing ingress only from the 'frontend' namespace and egress only to the 'db-services' namespace?
Example output
AI Agent: "Alright, let's break down this NetworkPolicy requirement for your `production` namespace backend pods.
**Goals Clarified:**
1. **Ingress Isolation**: Backend pods in `production` should deny all ingress by default.
2. **Specific Ingress Allow**: Only allow ingress from pods in the `frontend` namespace.
3. **Specific Egress Allow**: Only allow egress to pods in the `db-services` namespace.
4. **Target Pods**: Apply this policy to your backend pods in `production`.
**Best Practices:**
* Always start with `policyTypes` that includes both `Ingress` and `Egress` if you're defining both, effectively denying traffic not explicitly allowed.
* Use `podSelector` and `namespaceSelector` for fine-grained control.
**Actionable Steps & Verification:**
1. **Define the Policy:** Create a `NetworkPolicy` object in the `production` namespace.
2. **Select Target Pods:** Use `podSelector` to match your backend pods (e.g., `app: backend`).
3. **Set Policy Types:** Include `Ingress` and `Egress` in `policyTypes`.
4. **Configure Ingress Rules:**
* Add an `ingress` rule with a `from` clause that uses `namespaceSelector: matchLabels: name: frontend`.
5. **Configure Egress Rules:**
* Add an `egress` rule with a `to` clause that uses `namespaceSelector: matchLabels: name: db-services`.
**Example (Conceptual YAML):**
```yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: backend-isolation-policy
namespace: production
spec:
podSelector:
matchLabels:
app: backend
policyTypes:
- Ingress
- Egress
ingress:
- from:
- namespaceSelector:
matchLabels:
name: frontend
egress:
- to:
- namespaceSelector:
matchLabels:
name: db-services
```
**Verification:**
After applying, you'd test connectivity. Try to access the backend from other namespaces (should fail), from `frontend` (should succeed), and verify the backend can only reach `db-services`.
Does this align with your requirements? Would you like to explore any of these steps in more detail, perhaps by opening the `implementation-playbook.md` for full YAML examples?"When to use this skill
- Use this skill when you need detailed guidance on understanding, designing, or implementing security measures in a Kubernetes environment. Specifically, when configuring NetworkPolicies, setting up RBAC, adhering to Pod Security Standards, or evaluating the security configuration of your Kubernetes deployments.
When not to use this skill
- Do not use this skill for tasks unrelated to Kubernetes security policies. Avoid using it if the required solution involves tools or domains outside of Kubernetes security's scope, such as cloud provider-specific security, application-level security, or general infrastructure provisioning that is not directly tied to K8s security features.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/k8s-security-policies/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How k8s-security-policies Compares
| Feature / Agent | k8s-security-policies | Standard Approach |
|---|---|---|
| Platform Support | Claude | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | easy | N/A |
Frequently Asked Questions
What does this skill do?
Comprehensive guide for implementing NetworkPolicy, PodSecurityPolicy, RBAC, and Pod Security Standards in Kubernetes.
Which AI agents support this skill?
This skill is designed for Claude.
How difficult is it to install?
The installation complexity is rated as easy. You can find the installation instructions above.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
ChatGPT vs Claude for Agent Skills
Compare ChatGPT and Claude for AI agent skills across coding, writing, research, and reusable workflow execution.
SKILL.md Source
# Kubernetes Security Policies
Comprehensive guide for implementing NetworkPolicy, PodSecurityPolicy, RBAC, and Pod Security Standards in Kubernetes.
## Do not use this skill when
- The task is unrelated to kubernetes security policies
- You need a different domain or tool outside this scope
## Instructions
- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.
## Purpose
Implement defense-in-depth security for Kubernetes clusters using network policies, pod security standards, and RBAC.
## Use this skill when
- 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)
```yaml
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)
```yaml
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)
```yaml
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
```yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-all
namespace: production
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
```
### Allow Frontend to Backend
```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
```
### Allow DNS
```yaml
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)
```yaml
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)
```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: secret-reader
rules:
- apiGroups: [""]
resources: ["secrets"]
verbs: ["get", "watch", "list"]
```
### RoleBinding
```yaml
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
```yaml
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
```yaml
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
```yaml
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)
```yaml
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
name: default
namespace: production
spec:
mtls:
mode: STRICT
```
### AuthorizationPolicy
```yaml
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:**
```bash
# Check if CNI supports NetworkPolicy
kubectl get nodes -o wide
kubectl describe networkpolicy <name>
```
**RBAC permission denied:**
```bash
# 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 deploymentRelated Skills
mobile-security-coder
Expert in secure mobile coding practices specializing in input validation, WebView security, and mobile-specific security patterns.
laravel-security-audit
Security auditor for Laravel applications. Analyzes code for vulnerabilities, misconfigurations, and insecure practices using OWASP standards and Laravel security best practices.
gha-security-review
Find exploitable vulnerabilities in GitHub Actions workflows. Every finding MUST include a concrete exploitation scenario — if you can't build the attack, don't report it.
frontend-security-coder
Expert in secure frontend coding practices specializing in XSS prevention, output sanitization, and client-side security patterns.
frontend-mobile-security-xss-scan
You are a frontend security specialist focusing on Cross-Site Scripting (XSS) vulnerability detection and prevention. Analyze React, Vue, Angular, and vanilla JavaScript code to identify injection poi
azure-security-keyvault-keys-java
Azure Key Vault Keys Java SDK for cryptographic key management. Use when creating, managing, or using RSA/EC keys, performing encrypt/decrypt/sign/verify operations, or working with HSM-backed keys.
azure-security-keyvault-keys-dotnet
Azure Key Vault Keys SDK for .NET. Client library for managing cryptographic keys in Azure Key Vault and Managed HSM. Use for key creation, rotation, encryption, decryption, signing, and verification.
backend-security-coder
Expert in secure backend coding practices specializing in input validation, authentication, and API security. Use PROACTIVELY for backend security implementations or security code reviews.
nft-standards
Master ERC-721 and ERC-1155 NFT standards, metadata best practices, and advanced NFT features.
nextjs-app-router-patterns
Comprehensive patterns for Next.js 14+ App Router architecture, Server Components, and modern full-stack React development.
new-rails-project
Create a new Rails project
networkx
NetworkX is a Python package for creating, manipulating, and analyzing complex networks and graphs.