Initial commit - 611 cybersecurity skills across all subdomains

This commit is contained in:
mukul975
2026-02-25 10:47:44 +01:00
commit 22a7ab1462
1765 changed files with 280648 additions and 0 deletions
@@ -0,0 +1,214 @@
---
name: None
description: Kubernetes NetworkPolicies provide pod-level network segmentation by defining ingress and egress rules that control traffic flow between pods, namespaces, and external endpoints. Combined with CNI plu
domain: cybersecurity
subdomain: container-security
tags: [containers, kubernetes, security, network-policies, microsegmentation]
version: "1.0"
author: mahipal
license: MIT
---
# Implementing Network Policies for Kubernetes
## Overview
Kubernetes NetworkPolicies provide pod-level network segmentation by defining ingress and egress rules that control traffic flow between pods, namespaces, and external endpoints. Combined with CNI plugins like Calico or Cilium, network policies enforce zero-trust microsegmentation to prevent lateral movement within the cluster.
## Prerequisites
- Kubernetes cluster with NetworkPolicy-supporting CNI (Calico, Cilium, Antrea)
- kubectl configured with admin access
- Understanding of pod labels and selectors
## Implementation Steps
### Step 1: Default Deny All Traffic
```yaml
# default-deny-all.yaml - Apply to every namespace
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-all
namespace: production
spec:
podSelector: {} # Applies to all pods
policyTypes:
- Ingress
- Egress
```
### Step 2: Allow DNS Egress (Required for Service Discovery)
```yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-dns
namespace: production
spec:
podSelector: {}
policyTypes:
- Egress
egress:
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: kube-system
ports:
- protocol: UDP
port: 53
- protocol: TCP
port: 53
```
### Step 3: Application-Specific Policies
```yaml
# Allow frontend to reach backend only
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: backend-allow-frontend
namespace: production
spec:
podSelector:
matchLabels:
app: backend
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
ports:
- protocol: TCP
port: 8080
---
# Allow backend to reach database only
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: database-allow-backend
namespace: production
spec:
podSelector:
matchLabels:
app: database
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
app: backend
ports:
- protocol: TCP
port: 5432
```
### Step 4: Cross-Namespace Policies
```yaml
# Allow monitoring namespace to scrape metrics
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-monitoring-scrape
namespace: production
spec:
podSelector: {}
policyTypes:
- Ingress
ingress:
- from:
- namespaceSelector:
matchLabels:
purpose: monitoring
ports:
- protocol: TCP
port: 9090 # Prometheus metrics port
```
### Step 5: Egress Restrictions
```yaml
# Restrict egress to specific external services
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: restrict-egress
namespace: production
spec:
podSelector:
matchLabels:
app: backend
policyTypes:
- Egress
egress:
- to:
- podSelector:
matchLabels:
app: database
ports:
- protocol: TCP
port: 5432
- to: # Allow external API
- ipBlock:
cidr: 203.0.113.0/24
ports:
- protocol: TCP
port: 443
- to: # DNS
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: kube-system
ports:
- protocol: UDP
port: 53
```
### Step 6: Block Cloud Metadata Access
```yaml
# Prevent SSRF to cloud metadata service
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: block-metadata
namespace: production
spec:
podSelector: {}
policyTypes:
- Egress
egress:
- to:
- ipBlock:
cidr: 0.0.0.0/0
except:
- 169.254.169.254/32 # AWS/GCP metadata
- 100.100.100.200/32 # Azure metadata
```
## Validation Commands
```bash
# Verify policies are applied
kubectl get networkpolicies -n production
# Test connectivity (should be blocked)
kubectl run test-pod --image=busybox --restart=Never -n production -- wget -qO- --timeout=2 http://database-service:5432
# Expected: timeout (blocked by policy)
# Test allowed traffic
kubectl run frontend-test --image=busybox --labels=app=frontend --restart=Never -n production -- wget -qO- --timeout=2 http://backend-service:8080
# Expected: connection succeeds
```
## References
- [Kubernetes Network Policies](https://kubernetes.io/docs/concepts/services-networking/network-policies/)
- [Calico Network Policies](https://docs.tigera.io/calico/latest/network-policy/)
- [Cilium Network Policies](https://docs.cilium.io/en/stable/security/policy/)
- [Network Policy Editor](https://editor.networkpolicy.io/)
@@ -0,0 +1,16 @@
# Network Policy Audit Template
## Namespace Policy Matrix
| Namespace | Default-Deny Ingress | Default-Deny Egress | DNS Allowed | Metadata Blocked |
|-----------|---------------------|---------------------|-------------|-----------------|
| | | | | |
## Service Communication Map
| Source | Destination | Port | Protocol | Policy Name |
|--------|-------------|------|----------|-------------|
| | | | | |
## Remediation
| Namespace | Missing Policy | Action | Status |
|-----------|---------------|--------|--------|
| | | | |
@@ -0,0 +1,18 @@
# Standards Reference - Kubernetes Network Policies
## CIS Kubernetes Benchmark v1.8 - Section 5.3
- 5.3.1: Ensure CNI supports Network Policies
- 5.3.2: Ensure default deny NetworkPolicy for all namespaces
## NSA/CISA Kubernetes Hardening Guide
- Implement network segmentation between namespaces
- Apply default-deny network policies
- Restrict pod-to-pod communication to required paths only
- Block access to cloud metadata endpoints
## MITRE ATT&CK Mitigations
| Technique | Mitigation via Network Policy |
|-----------|------------------------------|
| T1046 - Network Service Scanning | Limit reachable services |
| T1021 - Remote Services | Block lateral movement |
| T1552 - Credentials from IMDS | Block 169.254.169.254 |
@@ -0,0 +1,20 @@
# Workflows - Kubernetes Network Policies
## Workflow 1: Network Policy Deployment
```
[Identify communication paths] --> [Create default-deny] --> [Add allow rules per service]
| | |
v v v
Map pod-to-pod traffic Apply to all namespaces Test with connectivity checks
Document required flows Verify DNS still works Monitor for broken connections
```
## Workflow 2: Progressive Enforcement
```
Step 1: Deploy in audit mode (Calico: log-only)
Step 2: Monitor traffic patterns for 1 week
Step 3: Create policies matching observed traffic
Step 4: Apply default-deny in non-production
Step 5: Validate application functionality
Step 6: Roll out to production namespaces
```
@@ -0,0 +1,119 @@
#!/usr/bin/env python3
"""
Kubernetes Network Policy Auditor
Checks for missing network policies, default-deny enforcement,
and identifies namespaces without proper segmentation.
"""
import subprocess
import json
import sys
from dataclasses import dataclass, field
@dataclass
class NetPolFinding:
namespace: str
severity: str
issue: str
remediation: str
def run_kubectl_json(args: list):
cmd = ["kubectl"] + args + ["-o", "json"]
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
if result.returncode != 0:
return None
return json.loads(result.stdout)
except (subprocess.TimeoutExpired, json.JSONDecodeError, FileNotFoundError):
return None
def audit_network_policies():
findings = []
system_ns = {"kube-system", "kube-public", "kube-node-lease"}
namespaces = run_kubectl_json(["get", "namespaces"])
if not namespaces:
print("[!] Cannot list namespaces")
return findings
for ns in namespaces.get("items", []):
ns_name = ns["metadata"]["name"]
if ns_name in system_ns:
continue
netpols = run_kubectl_json(["get", "networkpolicies", "-n", ns_name])
policies = netpols.get("items", []) if netpols else []
if not policies:
findings.append(NetPolFinding(
namespace=ns_name, severity="HIGH",
issue="No NetworkPolicies defined",
remediation=f"Create default-deny ingress/egress policy in namespace '{ns_name}'"
))
continue
# Check for default-deny
has_default_deny_ingress = False
has_default_deny_egress = False
for pol in policies:
spec = pol.get("spec", {})
pod_selector = spec.get("podSelector", {})
policy_types = spec.get("policyTypes", [])
if not pod_selector.get("matchLabels") and not pod_selector.get("matchExpressions"):
if "Ingress" in policy_types and not spec.get("ingress"):
has_default_deny_ingress = True
if "Egress" in policy_types and not spec.get("egress"):
has_default_deny_egress = True
if not has_default_deny_ingress:
findings.append(NetPolFinding(
namespace=ns_name, severity="HIGH",
issue="Missing default-deny ingress policy",
remediation="Create NetworkPolicy with empty podSelector and Ingress policyType with no ingress rules"
))
if not has_default_deny_egress:
findings.append(NetPolFinding(
namespace=ns_name, severity="MEDIUM",
issue="Missing default-deny egress policy",
remediation="Create NetworkPolicy with empty podSelector and Egress policyType with no egress rules"
))
return findings
def main():
print("[*] Kubernetes Network Policy Auditor\n")
findings = audit_network_policies()
print(f"\n{'='*60}")
print(f"NETWORK POLICY AUDIT REPORT")
print(f"{'='*60}")
print(f"Total Findings: {len(findings)}")
for sev in ["CRITICAL", "HIGH", "MEDIUM", "LOW"]:
sev_findings = [f for f in findings if f.severity == sev]
if sev_findings:
print(f"\n{sev}:")
for f in sev_findings:
print(f" [{f.namespace}] {f.issue}")
print(f" Fix: {f.remediation}")
with open("netpol_audit_report.json", "w") as fh:
json.dump({"findings": [{"namespace": f.namespace, "severity": f.severity,
"issue": f.issue, "remediation": f.remediation}
for f in findings]}, fh, indent=2)
print("\n[*] Report saved to netpol_audit_report.json")
if any(f.severity in ("CRITICAL", "HIGH") for f in findings):
sys.exit(1)
if __name__ == "__main__":
main()