Buckets:

download
raw
23.4 kB
#!/usr/bin/env python3
"""
Zen-AI-Pentest Kubernetes Operator
Ein Kubernetes Operator für automatisierte Security Scans.
Verwendet kopf (Kubernetes Operator Pythonic Framework) für die Reconciliation.
Features:
- Watch ZenPentest CRDs
- Reconcile: Startet Scans basierend auf CRD
- Cron: Scheduled Scans
- Report: Speichert Ergebnisse in ConfigMaps/Secrets
- Notifications: Slack/Email bei Fertigstellung
"""
import base64
import json
import logging
import os
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional
import kopf
import kubernetes_asyncio as k8s
from croniter import croniter
# =============================================================================
# Configuration & Logging
# =============================================================================
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logger = logging.getLogger("zen-ai-operator")
# Environment variables
OPERATOR_NAMESPACE = os.environ.get("OPERATOR_NAMESPACE", "zen-security")
OPERATOR_NAME = os.environ.get("OPERATOR_NAME", "zen-ai-pentest-operator")
WATCH_NAMESPACE = os.environ.get("WATCH_NAMESPACE", "") # Empty = all namespaces
SCAN_TIMEOUT = int(os.environ.get("SCAN_TIMEOUT", "3600"))
MAX_PARALLEL_SCANS = int(os.environ.get("MAX_PARALLEL_SCANS", "5"))
# Scan policy to tool mapping
POLICY_TOOLS = {
"safe": ["nmap", "httpx", "whatweb", "sslscan", "ai_analysis"],
"normal": ["nmap", "nuclei", "httpx", "whatweb", "wafw00f", "sslscan", "ai_analysis"],
"aggressive": [
"nmap",
"nuclei",
"sqlmap",
"ffuf",
"subfinder",
"httpx",
"whatweb",
"wafw00f",
"nikto",
"sslscan",
"ai_analysis",
],
}
# =============================================================================
# Kubernetes Client Helpers
# =============================================================================
async def get_k8s_client() -> k8s.client.ApiClient:
"""Initialize and return Kubernetes API client."""
try:
await k8s.config.load_incluster_config()
except k8s.config.config_exception.ConfigException:
await k8s.config.load_kube_config()
return k8s.client.ApiClient()
async def create_scan_job(api: k8s.client.BatchV1Api, namespace: str, name: str, spec: Dict[str, Any]) -> k8s.client.V1Job:
"""Create a Kubernetes Job for the security scan."""
target = spec["target"]
scan_type = spec["scanType"]
policy = spec.get("policy", "safe")
modules = spec.get("modules", POLICY_TOOLS.get(policy, POLICY_TOOLS["safe"]))
timeout = spec.get("timeout", SCAN_TIMEOUT)
# Generate unique job name
timestamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
job_name = f"zen-scan-{name}-{timestamp}"
# Build scan command
scan_command = build_scan_command(target, scan_type, modules, spec)
# Resource limits
resources = spec.get("resources", {})
limits = resources.get("limits", {"cpu": "2000m", "memory": "4Gi"})
requests = resources.get("requests", {"cpu": "500m", "memory": "1Gi"})
# Container resources
container_resources = k8s.client.V1ResourceRequirements(limits=limits, requests=requests)
# Security context
security_context = k8s.client.V1SecurityContext(
run_as_non_root=True,
run_as_user=1000,
allow_privilege_escalation=False,
read_only_root_filesystem=True,
capabilities=k8s.client.V1Capabilities(drop=["ALL"]),
)
# Pod security context
pod_security_context = k8s.client.V1PodSecurityContext(run_as_non_root=True, run_as_user=1000, fs_group=1000)
# Environment variables
env_vars = [
k8s.client.V1EnvVar(name="SCAN_TARGET", value=target),
k8s.client.V1EnvVar(name="SCAN_TYPE", value=scan_type),
k8s.client.V1EnvVar(name="SCAN_POLICY", value=policy),
k8s.client.V1EnvVar(name="SCAN_MODULES", value=",".join(modules)),
k8s.client.V1EnvVar(name="SCAN_TIMEOUT", value=str(timeout)),
]
# Add auth environment if specified
if "auth" in spec and spec["auth"].get("type") != "none":
auth = spec["auth"]
secret_ref = auth.get("secretRef", {})
secret_name = secret_ref.get("name")
secret_namespace = secret_ref.get("namespace", namespace)
if secret_name:
env_vars.extend(
[
k8s.client.V1EnvVar(name="AUTH_TYPE", value=auth.get("type", "none")),
k8s.client.V1EnvVar(name="AUTH_SECRET_NAME", value=secret_name),
k8s.client.V1EnvVar(name="AUTH_SECRET_NAMESPACE", value=secret_namespace),
]
)
# Container definition
container = k8s.client.V1Container(
name="zen-scan",
image="zenai/zen-pentest-scanner:1.0.0",
image_pull_policy="IfNotPresent",
command=["/bin/sh", "-c"],
args=[scan_command],
env=env_vars,
resources=container_resources,
security_context=security_context,
volume_mounts=[
k8s.client.V1VolumeMount(name="tmp", mount_path="/tmp"), # nosec B108
k8s.client.V1VolumeMount(name="reports", mount_path="/reports"),
],
)
# Volumes
volumes = [
k8s.client.V1Volume(name="tmp", empty_dir=k8s.client.V1EmptyDirVolumeSource()),
]
# Add report volume based on storage type
report_storage = spec.get("report", {}).get("storage", "configmap")
if report_storage == "persistentVolumeClaim":
pvc_spec = spec.get("report", {}).get("persistentVolumeClaim", {})
pvc_name = pvc_spec.get("name", "zen-reports-pvc")
volumes.append(
k8s.client.V1Volume(
name="reports", persistent_volume_claim=k8s.client.V1PersistentVolumeClaimVolumeSource(claim_name=pvc_name)
)
)
else:
volumes.append(k8s.client.V1Volume(name="reports", empty_dir=k8s.client.V1EmptyDirVolumeSource()))
# Job template
template = k8s.client.V1PodTemplateSpec(
metadata=k8s.client.V1ObjectMeta(
labels={
"app.kubernetes.io/name": "zen-ai-pentest",
"app.kubernetes.io/component": "scan-job",
"app.kubernetes.io/scan-name": name,
"zen-ai.io/scan-id": job_name,
}
),
spec=k8s.client.V1PodSpec(
service_account_name="zen-ai-pentest-operator",
security_context=pod_security_context,
restart_policy="Never",
containers=[container],
volumes=volumes,
active_deadline_seconds=timeout + 300, # Add buffer for cleanup
),
)
# Job spec
job_spec = k8s.client.V1JobSpec(template=template, backoff_limit=1, ttl_seconds_after_finished=86400) # Keep for 24 hours
# Job object
job = k8s.client.V1Job(
api_version="batch/v1",
kind="Job",
metadata=k8s.client.V1ObjectMeta(
name=job_name,
namespace=namespace,
labels={
"app.kubernetes.io/name": "zen-ai-pentest",
"app.kubernetes.io/component": "scan-job",
"app.kubernetes.io/managed-by": "zen-ai-operator",
"zen-ai.io/scan-name": name,
},
owner_references=[], # Will be set by kopf
),
spec=job_spec,
)
try:
created_job = await api.create_namespaced_job(namespace=namespace, body=job)
logger.info(f"Created scan job: {job_name} in namespace: {namespace}")
return created_job
except k8s.client.exceptions.ApiException as e:
logger.error(f"Failed to create job: {e}")
raise
def build_scan_command(target: str, scan_type: str, modules: List[str], spec: Dict) -> str:
"""Build the scan command based on configuration."""
# Base command using the Zen-AI-Pentest CLI
cmd_parts = [
"python -m zen_ai_pentest",
f'--target "{target}"',
f"--type {scan_type}",
f"--modules {','.join(modules)}",
"--output /reports/scan-results.json",
"--format json",
]
# Add policy flag
policy = spec.get("policy", "safe")
cmd_parts.append(f"--policy {policy}")
# Add timeout
timeout = spec.get("timeout", SCAN_TIMEOUT)
cmd_parts.append(f"--timeout {timeout}")
# Add AI analysis flag
if "ai_analysis" in modules:
cmd_parts.append("--ai-analysis")
# Build final command with error handling and result capture
command = " ".join(cmd_parts)
return f"""
set -e
echo "Starting Zen-AI-Pentest scan..."
echo "Target: {target}"
echo "Type: {scan_type}"
echo "Modules: {",".join(modules)}"
echo "Policy: {policy}"
# Run the scan
{command} || true
# Copy results to shared location for operator pickup
if [ -f /reports/scan-results.json ]; then
echo "Scan completed successfully"
cat /reports/scan-results.json
else
echo "{{\"error\": \"Scan failed or produced no output\"}}" > /reports/scan-results.json
fi
exit 0
"""
async def store_scan_results(
api: k8s.client.CoreV1Api, namespace: str, name: str, results: Dict[str, Any], storage_type: str = "configmap"
) -> str:
"""Store scan results in ConfigMap or Secret."""
timestamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
result_name = f"zen-scan-results-{name}-{timestamp}"
# Prepare result data
result_data = {"scanName": name, "timestamp": datetime.now(timezone.utc).isoformat(), "results": results}
if storage_type == "secret":
# Store as base64 in Secret
secret_data = {"results.json": base64.b64encode(json.dumps(result_data).encode()).decode()}
secret = k8s.client.V1Secret(
api_version="v1",
kind="Secret",
metadata=k8s.client.V1ObjectMeta(
name=result_name,
namespace=namespace,
labels={
"app.kubernetes.io/name": "zen-ai-pentest",
"app.kubernetes.io/component": "scan-results",
"zen-ai.io/scan-name": name,
},
),
type="Opaque",
data=secret_data,
)
await api.create_namespaced_secret(namespace=namespace, body=secret)
logger.info(f"Stored scan results in Secret: {result_name}")
else:
# Store in ConfigMap (data must be string)
# Truncate if too large (ConfigMap limit ~1MB)
result_json = json.dumps(result_data)
if len(result_json) > 1048576:
result_data["results"] = {"error": "Results too large for ConfigMap"}
result_data["truncated"] = True
result_json = json.dumps(result_data)
configmap = k8s.client.V1ConfigMap(
api_version="v1",
kind="ConfigMap",
metadata=k8s.client.V1ObjectMeta(
name=result_name,
namespace=namespace,
labels={
"app.kubernetes.io/name": "zen-ai-pentest",
"app.kubernetes.io/component": "scan-results",
"zen-ai.io/scan-name": name,
},
),
data={"results.json": result_json},
)
await api.create_namespaced_config_map(namespace=namespace, body=configmap)
logger.info(f"Stored scan results in ConfigMap: {result_name}")
return result_name
async def send_notification(spec: Dict[str, Any], status: str, message: str, results: Optional[Dict] = None):
"""Send notifications via Slack, Email, or Webhook."""
notifications = spec.get("notifications", {})
# Slack notification
if "slack" in notifications:
await send_slack_notification(notifications["slack"], status, message, results)
# Email notification
if "email" in notifications:
await send_email_notification(notifications["email"], status, message, results)
# Generic webhook
if "webhook" in notifications:
await send_webhook_notification(notifications["webhook"], status, message, results)
async def send_slack_notification(config: Dict[str, Any], status: str, message: str, results: Optional[Dict] = None):
"""Send Slack notification."""
try:
import aiohttp
config.get("webhookSecret", "slack-webhook")
channel = config.get("channel", "#security-alerts")
# Get webhook URL from environment or secret
webhook_url = os.environ.get("SLACK_WEBHOOK_URL", "")
# Determine color based on status
color = "good" if status == "Succeeded" else "danger" if status == "Failed" else "warning"
# Build attachment
attachment = {
"color": color,
"title": f"Zen-AI-Pentest Scan {status}",
"text": message,
"fields": [],
"ts": int(datetime.now(timezone.utc).timestamp()),
}
# Add vulnerability counts if available
if results and "vulnerabilities" in results:
vulns = results["vulnerabilities"]
attachment["fields"].extend(
[
{"title": "Critical", "value": str(vulns.get("critical", 0)), "short": True},
{"title": "High", "value": str(vulns.get("high", 0)), "short": True},
{"title": "Medium", "value": str(vulns.get("medium", 0)), "short": True},
{"title": "Low", "value": str(vulns.get("low", 0)), "short": True},
]
)
payload = {"channel": channel, "attachments": [attachment]}
async with aiohttp.ClientSession() as session:
async with session.post(webhook_url, json=payload) as resp:
if resp.status == 200:
logger.info(f"Slack notification sent to {channel}")
else:
logger.warning(f"Failed to send Slack notification: {resp.status}")
except Exception as e:
logger.error(f"Error sending Slack notification: {e}")
async def send_email_notification(config: Dict[str, Any], status: str, message: str, results: Optional[Dict] = None):
"""Send email notification (placeholder - requires SMTP setup)."""
logger.info(f"Email notification would be sent to: {config.get('recipients', [])}")
async def send_webhook_notification(config: Dict[str, Any], status: str, message: str, results: Optional[Dict] = None):
"""Send generic webhook notification."""
try:
import aiohttp
url = config.get("url", "")
headers = config.get("headers", {})
payload = {
"status": status,
"message": message,
"timestamp": datetime.now(timezone.utc).isoformat(),
"results": results,
}
async with aiohttp.ClientSession() as session:
async with session.post(url, json=payload, headers=headers) as resp:
logger.info(f"Webhook notification sent: {resp.status}")
except Exception as e:
logger.error(f"Error sending webhook notification: {e}")
# =============================================================================
# Kopf Event Handlers
# =============================================================================
@kopf.on.startup()
async def startup_fn(logger, **kwargs):
"""Initialize operator on startup."""
logger.info("Starting Zen-AI-Pentest Operator...")
await get_k8s_client()
logger.info("Operator initialized successfully")
@kopf.on.cleanup()
async def cleanup_fn(logger, **kwargs):
"""Cleanup on operator shutdown."""
logger.info("Shutting down Zen-AI-Pentest Operator...")
@kopf.on.create("security.zen-ai.io", "v1", "zenpentests")
async def create_zenpentest(
spec: Dict[str, Any], name: str, namespace: str, body: Dict[str, Any], logger: logging.Logger, **kwargs
):
"""Handle creation of ZenPentest CRD."""
logger.info(f"Creating ZenPentest: {name} in namespace: {namespace}")
# Check if suspended
if spec.get("suspend", False):
logger.info(f"Scan {name} is suspended, skipping")
return {"phase": "Suspended", "message": "Scan is suspended"}
# Check if scheduled
schedule = spec.get("schedule", "")
if schedule:
# Validate cron expression
if not croniter.is_valid(schedule):
raise kopf.PermanentError(f"Invalid cron expression: {schedule}")
# Calculate next run time
next_run = croniter(schedule, datetime.now(timezone.utc)).get_next(datetime)
logger.info(f"Scheduled scan {name} for: {next_run.isoformat()}")
return {
"phase": "Scheduled",
"message": f"Scan scheduled with cron: {schedule}",
"nextScheduleTime": next_run.isoformat(),
}
# Immediate scan - create Job
api = k8s.client.BatchV1Api()
try:
job = await create_scan_job(api, namespace, name, spec)
return {
"phase": "Running",
"message": f"Scan job created: {job.metadata.name}",
"scanId": job.metadata.name,
"startTime": datetime.now(timezone.utc).isoformat(),
}
except Exception as e:
logger.error(f"Failed to create scan job: {e}")
raise kopf.TemporaryError(f"Failed to create job: {e}", delay=30)
@kopf.on.update("security.zen-ai.io", "v1", "zenpentests")
async def update_zenpentest(
spec: Dict[str, Any],
old: Dict[str, Any],
new: Dict[str, Any],
name: str,
namespace: str,
status: Dict[str, Any],
logger: logging.Logger,
**kwargs,
):
"""Handle updates to ZenPentest CRD."""
logger.info(f"Updating ZenPentest: {name}")
old_spec = old.get("spec", {})
new_spec = new.get("spec", {})
# Check for schedule changes
old_schedule = old_spec.get("schedule", "")
new_schedule = new_spec.get("schedule", "")
if old_schedule != new_schedule:
if new_schedule:
if not croniter.is_valid(new_schedule):
raise kopf.PermanentError(f"Invalid cron expression: {new_schedule}")
next_run = croniter(new_schedule, datetime.now(timezone.utc)).get_next(datetime)
logger.info(f"Updated schedule for {name}, next run: {next_run}")
return {
"phase": "Scheduled",
"message": f"Schedule updated to: {new_schedule}",
"nextScheduleTime": next_run.isoformat(),
}
else:
# Schedule removed - scan will run immediately on next reconcile
logger.info(f"Schedule removed for {name}")
# Check for suspend changes
old_suspend = old_spec.get("suspend", False)
new_suspend = new_spec.get("suspend", False)
if old_suspend != new_suspend:
if new_suspend:
logger.info(f"Scan {name} suspended")
return {"phase": "Suspended", "message": "Scan suspended by user"}
else:
logger.info(f"Scan {name} resumed")
# Trigger immediate run
api = k8s.client.BatchV1Api()
job = await create_scan_job(api, namespace, name, new_spec)
return {
"phase": "Running",
"message": f"Scan resumed, job created: {job.metadata.name}",
"scanId": job.metadata.name,
"startTime": datetime.now(timezone.utc).isoformat(),
}
return status
@kopf.on.delete("security.zen-ai.io", "v1", "zenpentests")
async def delete_zenpentest(spec: Dict[str, Any], name: str, namespace: str, logger: logging.Logger, **kwargs):
"""Handle deletion of ZenPentest CRD."""
logger.info(f"Deleting ZenPentest: {name}")
# Cleanup is handled by Kubernetes garbage collection (ownerReferences)
return {"deleted": True}
@kopf.on.field("security.zen-ai.io", "v1", "zenpentests", field="status.phase")
async def on_phase_change(
old: str,
new: str,
name: str,
namespace: str,
spec: Dict[str, Any],
status: Dict[str, Any],
logger: logging.Logger,
**kwargs,
):
"""Handle status phase changes."""
logger.info(f"Phase changed for {name}: {old} -> {new}")
if new in ["Succeeded", "Failed"]:
# Send notifications
message = status.get("message", f"Scan {new.lower()}")
results = status.get("results", {})
await send_notification(spec, new, message, results)
@kopf.timer("security.zen-ai.io", "v1", "zenpentests", interval=60)
async def reconcile_scheduled_scans(
spec: Dict[str, Any], name: str, namespace: str, status: Dict[str, Any], logger: logging.Logger, **kwargs
):
"""Timer handler for scheduled scans."""
schedule = spec.get("schedule", "")
current_phase = status.get("phase", "Pending")
if not schedule or spec.get("suspend", False):
return
# Only process if we're in Scheduled or Succeeded phase
if current_phase not in ["Scheduled", "Succeeded", "Failed"]:
return
# Check if it's time to run
now = datetime.now(timezone.utc)
next_run_str = status.get("nextScheduleTime", "")
if next_run_str:
next_run = datetime.fromisoformat(next_run_str.replace("Z", "+00:00").replace("+00:00", ""))
if now < next_run:
return # Not time yet
# Time to run the scan
logger.info(f"Triggering scheduled scan: {name}")
api = k8s.client.BatchV1Api()
job = await create_scan_job(api, namespace, name, spec)
# Calculate next run
next_run = croniter(schedule, now).get_next(datetime)
return {
"phase": "Running",
"message": f"Scheduled scan triggered: {job.metadata.name}",
"scanId": job.metadata.name,
"startTime": now.isoformat(),
"lastScheduleTime": now.isoformat(),
"nextScheduleTime": next_run.isoformat(),
}
@kopf.on.event("batch", "v1", "jobs", labels={"app.kubernetes.io/component": "scan-job"})
async def watch_scan_jobs(event: Dict[str, Any], logger: logging.Logger, **kwargs):
"""Watch scan jobs and update ZenPentest status."""
job = event.get("object", {})
job_name = job.get("metadata", {}).get("name", "")
labels = job.get("metadata", {}).get("labels", {})
scan_name = labels.get("zen-ai.io/scan-name", "")
job.get("metadata", {}).get("namespace", "")
if not scan_name:
return
# Check job status
job_status = job.get("status", {})
if job_status.get("succeeded", 0) > 0:
logger.info(f"Scan job {job_name} succeeded")
# Results would be processed here in a real implementation
elif job_status.get("failed", 0) > 0:
logger.warning(f"Scan job {job_name} failed")
# =============================================================================
# Main Entry Point
# =============================================================================
def main():
"""Main entry point for the operator."""
logger.info("=" * 60)
logger.info("Zen-AI-Pentest Kubernetes Operator")
logger.info("Version: 1.0.0")
logger.info("=" * 60)
# Run kopf
kopf.run(
clusterwide=True,
namespace=WATCH_NAMESPACE if WATCH_NAMESPACE else None,
)
if __name__ == "__main__":
main()

Xet Storage Details

Size:
23.4 kB
·
Xet hash:
b877d40b2c9d045483753c7ba56944cbfc813de1a64d570a77688a222882f3e8

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.