Network Policy Security Scanning
Network Policy Security Scanning
Analyze network policies for security gaps:
# Example network policy scanner implementation
apiVersion: v1
kind: ConfigMap
metadata:
name: netpol-scanner
namespace: security-tools
data:
scan-network-policies.py: |
import subprocess
import json
import yaml
def get_network_policies():
result = subprocess.run(
['kubectl', 'get', 'networkpolicies', '-A', '-o', 'json'],
capture_output=True,
text=True
)
return json.loads(result.stdout)['items']
def get_pods_without_network_policies():
# Get all pods
pods_result = subprocess.run(
['kubectl', 'get', 'pods', '-A', '-o', 'json'],
capture_output=True,
text=True
)
all_pods = json.loads(pods_result.stdout)['items']
# Get network policies
netpols = get_network_policies()
# Find unprotected pods
unprotected = []
for pod in all_pods:
namespace = pod['metadata']['namespace']
pod_labels = pod['metadata'].get('labels', {})
protected = False
for netpol in netpols:
if netpol['metadata']['namespace'] == namespace:
selector = netpol['spec'].get('podSelector', {})
if matches_selector(pod_labels, selector):
protected = True
break
if not protected:
unprotected.append(f"{namespace}/{pod['metadata']['name']}")
return unprotected
def matches_selector(labels, selector):
match_labels = selector.get('matchLabels', {})
for key, value in match_labels.items():
if labels.get(key) != value:
return False
return True
# Run analysis
unprotected_pods = get_pods_without_network_policies()
print(f"Found {len(unprotected_pods)} pods without network policies:")
for pod in unprotected_pods:
print(f" - {pod}")