container security

Implementing Runtime Security with Tetragon

Implement eBPF-based runtime security observability and enforcement in Kubernetes clusters using Cilium Tetragon for kernel-level threat detection and policy enforcement.

ciliumcncfcontainer-securityebpfkernel-securitykubernetesobservabilityruntime-security
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

Overview

Tetragon is a CNCF project under Cilium that provides flexible Kubernetes-aware security observability and runtime enforcement using eBPF. By operating at the Linux kernel level, Tetragon can monitor and enforce policies on process execution, file access, network connections, and system calls with less than 1% performance overhead -- far more efficient than traditional user-space security agents.

When to Use

  • When deploying or configuring implementing runtime security with tetragon capabilities in your environment
  • When establishing security controls aligned to compliance requirements
  • When building or improving security architecture for this domain
  • When conducting security assessments that require this implementation

Prerequisites

  • Kubernetes cluster v1.24+ with Helm 3.x installed
  • Linux kernel 5.4+ (5.10+ recommended for full eBPF feature support)
  • kubectl access with cluster-admin privileges
  • Familiarity with eBPF concepts and Kubernetes security primitives

Core Concepts

eBPF-Based Security

Tetragon attaches eBPF programs directly to kernel functions, enabling:

  • Process lifecycle tracking: Monitor every process creation, execution, and termination across all pods
  • File integrity monitoring: Detect unauthorized reads/writes to sensitive files
  • Network observability: Track all TCP/UDP connections with full pod context
  • System call filtering: Enforce policies on dangerous syscalls like ptrace, mount, or unshare

TracingPolicy Custom Resources

Tetragon uses TracingPolicy CRDs to define what kernel events to observe and what actions to take:

apiVersion: cilium.io/v1alpha1
kind: TracingPolicy
metadata:
  name: detect-privilege-escalation
spec:
  kprobes:
    - call: "security_bprm_check"
      syscall: false
      args:
        - index: 0
          type: "linux_binprm"
      selectors:
        - matchBinaries:
            - operator: "In"
              values:
                - "/bin/su"
                - "/usr/bin/sudo"
                - "/usr/bin/passwd"
          matchNamespaces:
            - namespace: Pid
              operator: NotIn
              values:
                - "host_ns"
          matchActions:
            - action: Post

Enforcement Actions

Tetragon can take three types of actions directly in the kernel:

  1. Sigkill: Immediately terminate the offending process
  2. Signal: Send a configurable signal to the process
  3. Override: Override the return value of a kernel function to deny an operation

Installation and Configuration

Step 1: Install Tetragon with Helm

helm repo add cilium https://helm.cilium.io
helm repo update
 
helm install tetragon cilium/tetragon \
  --namespace kube-system \
  --set tetragon.enableProcessCred=true \
  --set tetragon.enableProcessNs=true \
  --set tetragon.grpc.address="localhost:54321"

Step 2: Install the Tetragon CLI

GOOS=$(go env GOOS)
GOARCH=$(go env GOARCH)
curl -L --remote-name-all \
  https://github.com/cilium/tetragon/releases/latest/download/tetra-${GOOS}-${GOARCH}.tar.gz
tar -xzvf tetra-${GOOS}-${GOARCH}.tar.gz
sudo install tetra /usr/local/bin/

Step 3: Verify Installation

kubectl get pods -n kube-system -l app.kubernetes.io/name=tetragon
tetra status

Practical Implementation

Detecting Container Escape Attempts

Create a TracingPolicy to detect processes attempting to escape container namespaces:

apiVersion: cilium.io/v1alpha1
kind: TracingPolicy
metadata:
  name: detect-container-escape
spec:
  kprobes:
    - call: "__x64_sys_setns"
      syscall: true
      args:
        - index: 0
          type: "int"
        - index: 1
          type: "int"
      selectors:
        - matchNamespaces:
            - namespace: Pid
              operator: NotIn
              values:
                - "host_ns"
          matchActions:
            - action: Sigkill

Monitoring Sensitive File Access

Detect reads of sensitive credentials:

apiVersion: cilium.io/v1alpha1
kind: TracingPolicy
metadata:
  name: monitor-sensitive-files
spec:
  kprobes:
    - call: "security_file_open"
      syscall: false
      args:
        - index: 0
          type: "file"
      selectors:
        - matchArgs:
            - index: 0
              operator: "Prefix"
              values:
                - "/etc/shadow"
                - "/etc/kubernetes/pki"
                - "/var/run/secrets/kubernetes.io"
          matchActions:
            - action: Post

Blocking Crypto-Miner Execution

Prevent known crypto-mining binaries from executing:

apiVersion: cilium.io/v1alpha1
kind: TracingPolicy
metadata:
  name: block-cryptominers
spec:
  kprobes:
    - call: "security_bprm_check"
      syscall: false
      args:
        - index: 0
          type: "linux_binprm"
      selectors:
        - matchBinaries:
            - operator: "In"
              values:
                - "/usr/bin/xmrig"
                - "/tmp/xmrig"
                - "/usr/bin/minerd"
          matchActions:
            - action: Sigkill

Observing Events with Tetra CLI

Stream runtime events in real-time:

# Watch all process execution events
kubectl exec -n kube-system ds/tetragon -c tetragon -- \
  tetra getevents -o compact --process-only
 
# Filter events for a specific namespace
kubectl exec -n kube-system ds/tetragon -c tetragon -- \
  tetra getevents -o compact --namespace production
 
# Export events in JSON for SIEM integration
kubectl exec -n kube-system ds/tetragon -c tetragon -- \
  tetra getevents -o json | tee /var/log/tetragon-events.json

Integration with SIEM and Alerting

Export to Elasticsearch

# tetragon-helm-values.yaml
export:
  stdout:
    enabledCommand: true
    enabledArgs: true
  filenames:
    - /var/log/tetragon/tetragon.log
  elasticsearch:
    enabled: true
    url: "https://elasticsearch.monitoring:9200"
    index: "tetragon-events"

Prometheus Metrics

Tetragon exposes metrics at :2112/metrics:

apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: tetragon-metrics
  namespace: kube-system
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: tetragon
  endpoints:
    - port: metrics
      interval: 15s

Key Metrics and Alerts

Metric Description Alert Threshold
tetragon_events_total Total security events observed Spike > 3x baseline
tetragon_policy_events_total Events matching TracingPolicies Any Sigkill action
tetragon_process_exec_total Process executions tracked Anomalous new binaries
tetragon_missed_events_total Dropped events due to buffer overflow > 0 sustained

References

Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 3

api-reference.md0.9 KB

API Reference: Cilium Tetragon Runtime Security

TracingPolicy CRD

apiVersion: cilium.io/v1alpha1
kind: TracingPolicy
metadata:
  name: monitor-sensitive-files
spec:
  kprobes:
    - call: fd_install
      args:
        - index: 1
          type: file
      selectors:
        - matchArgs:
            - index: 1
              operator: Prefix
              values: ["/etc/shadow", "/etc/passwd"]

Tetra CLI Commands

Command Description
tetra status Tetragon health
tetra getevents Stream events
tetra tracingpolicy list List policies

Event Types

Type Description
process_exec Process execution
process_exit Process termination
process_kprobe Kernel probe trigger

Key Libraries

Library Use
kubernetes K8s API client
subprocess kubectl/tetra CLI
grpc Tetragon gRPC API
standards.md2.0 KB

Standards and References - Runtime Security with Tetragon

Industry Standards

NIST SP 800-190: Application Container Security Guide

  • Section 4.2: Runtime monitoring and anomaly detection for containers
  • Section 4.4: Container-level network monitoring requirements
  • Recommends kernel-level security monitoring for container environments

CIS Kubernetes Benchmark v1.9

  • Control 5.7.1: Create administrative boundaries between resources using namespaces
  • Control 5.7.3: Apply Security Context to pods and containers
  • Control 5.7.4: The default namespace should not be used

MITRE ATT&CK for Containers

  • T1611: Escape to Host -- Tetragon detects namespace manipulation attempts
  • T1059.004: Command and Scripting Interpreter: Unix Shell -- process execution monitoring
  • T1053.007: Container Orchestration Job -- detects unauthorized job creation
  • T1496: Resource Hijacking -- crypto-miner detection and blocking

CNCF Landscape Positioning

Tetragon is positioned in the CNCF Runtime Security category alongside:

  • Falco (audit-log and syscall-based detection)
  • KubeArmor (LSM-based enforcement)
  • Tracee (eBPF-based tracing)

Key Differentiators

  • Kernel-level filtering reduces event volume before reaching user space
  • Native enforcement (Sigkill/Override) without requiring separate enforcement engine
  • Deep integration with Cilium for combined network + runtime security
  • TracingPolicy CRD for Kubernetes-native policy management

Compliance Mapping

Requirement Framework Tetragon Capability
Runtime threat detection PCI DSS 11.5 TracingPolicy with file integrity monitoring
Unauthorized process detection SOC 2 CC6.8 Process execution monitoring with namespace context
Container isolation enforcement NIST 800-190 4.2 Namespace escape detection and blocking
Audit trail generation ISO 27001 A.12.4 JSON event export to SIEM systems
Incident response automation NIST CSF DE.AE Real-time Sigkill enforcement on policy violations
workflows.md2.7 KB

Workflows - Runtime Security with Tetragon

Deployment Workflow

Phase 1: Observation Mode

  1. Install Tetragon with default TracingPolicies (no enforcement)
  2. Collect baseline process execution data for 7-14 days
  3. Analyze event patterns to identify normal vs anomalous behavior
  4. Document expected processes per namespace and workload type

Phase 2: Detection Policies

  1. Create TracingPolicies for known attack patterns (container escape, privilege escalation)
  2. Configure event export to SIEM (Elasticsearch, Splunk, or Datadog)
  3. Build alerting rules based on TracingPolicy matches
  4. Validate detection accuracy with red team exercises

Phase 3: Enforcement

  1. Enable Sigkill actions for high-confidence threats (known malware binaries)
  2. Enable Override actions for dangerous syscalls in non-privileged containers
  3. Implement graduated response -- alert first, block after confirmation
  4. Monitor enforcement actions for false positives

TracingPolicy Development Workflow

1. Identify Threat -> Map to MITRE ATT&CK technique
2. Determine Kernel Hook -> kprobe, tracepoint, or LSM hook
3. Define Selectors -> Binary, namespace, capability filters
4. Set Action -> Post (observe), Sigkill (block), Override (deny)
5. Test in Staging -> Deploy to non-production namespace first
6. Validate with Attack Simulation -> Confirm detection
7. Deploy to Production -> Apply via GitOps
8. Monitor False Positives -> Tune selectors as needed

Incident Response Integration

When Tetragon Detects a Threat

  1. Event is generated with full context (pod, namespace, binary, args, capabilities)
  2. Event exported to SIEM via JSON log export or Prometheus metric
  3. SOAR platform receives alert and triggers playbook
  4. Automated actions: isolate pod network (via Cilium NetworkPolicy), capture forensic data
  5. Security team receives enriched alert with Kubernetes context

Forensic Data Collection

# Export recent events for a specific pod
tetra getevents --namespace <ns> --pod <pod-name> \
  --since 1h -o json > /forensics/tetragon-events.json
 
# Get process tree for suspicious activity
tetra getevents --process-pid <pid> --ancestors 5 -o compact

Operational Runbook

Daily Checks

  • Review tetragon_missed_events_total metric for event buffer overflows
  • Check Tetragon DaemonSet health across all nodes
  • Review new TracingPolicy match counts

Weekly Checks

  • Analyze top 10 most frequent event types
  • Review enforcement action logs for false positives
  • Update TracingPolicies based on new threat intelligence

Monthly Checks

  • Performance impact assessment (CPU/memory overhead per node)
  • TracingPolicy effectiveness review with red team
  • Update Tetragon to latest stable release

Scripts 2

agent.py4.1 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Agent for auditing Cilium Tetragon runtime security configuration."""

import argparse
import json
import subprocess
from datetime import datetime, timezone

try:
    from kubernetes import client, config as k8s_config
except ImportError:
    client = None


def check_tetragon_deployment(namespace="kube-system"):
    """Check if Tetragon is deployed in the cluster."""
    findings = []
    if not client:
        return [{"error": "kubernetes library required"}]
    try:
        k8s_config.load_kube_config()
        v1 = client.AppsV1Api()
        daemonsets = v1.list_namespaced_daemon_set(namespace)
        tetragon_found = False
        for ds in daemonsets.items:
            if "tetragon" in ds.metadata.name.lower():
                tetragon_found = True
                desired = ds.status.desired_number_scheduled or 0
                ready = ds.status.number_ready or 0
                if ready < desired:
                    findings.append({"check": "Tetragon Readiness",
                                     "desired": desired, "ready": ready,
                                     "severity": "HIGH"})
        if not tetragon_found:
            findings.append({"check": "Tetragon Deployment", "status": "NOT_FOUND",
                             "severity": "CRITICAL"})
    except Exception as e:
        findings.append({"error": str(e)})
    return findings


def check_tracing_policies():
    """Check TracingPolicy custom resources."""
    findings = []
    try:
        result = subprocess.check_output(
            ["kubectl", "get", "tracingpolicies", "-o", "json"],
            text=True, timeout=10,
        )
        data = json.loads(result)
        items = data.get("items", [])
        if not items:
            findings.append({"check": "TracingPolicies", "count": 0,
                             "severity": "MEDIUM",
                             "recommendation": "Deploy TracingPolicy for runtime enforcement"})
        for item in items:
            name = item.get("metadata", {}).get("name", "unknown")
            spec = item.get("spec", {})
            if not spec.get("kprobes") and not spec.get("tracepoints"):
                findings.append({"check": f"Policy: {name}", "severity": "LOW",
                                 "recommendation": "Add kprobes or tracepoints"})
    except (subprocess.SubprocessError, json.JSONDecodeError):
        findings.append({"check": "TracingPolicies", "status": "query_failed",
                         "severity": "MEDIUM"})
    return findings


def check_tetragon_cli():
    """Check tetra CLI availability and events."""
    findings = []
    try:
        result = subprocess.check_output(
            ["tetra", "status"], text=True, timeout=5,
        )
        if "running" not in result.lower():
            findings.append({"check": "Tetragon Status", "severity": "HIGH"})
    except (subprocess.SubprocessError, FileNotFoundError):
        findings.append({"check": "Tetra CLI", "status": "not_available",
                         "severity": "LOW"})
    return findings


def main():
    parser = argparse.ArgumentParser(description="Tetragon runtime security audit agent")
    parser.add_argument("--namespace", default="kube-system")
    parser.add_argument("--output", "-o", help="Output JSON report")
    parser.add_argument("--verbose", "-v", action="store_true")
    args = parser.parse_args()

    print("[*] Tetragon Runtime Security Audit Agent")
    report = {"timestamp": datetime.now(timezone.utc).isoformat(), "findings": []}
    report["findings"].extend(check_tetragon_deployment(args.namespace))
    report["findings"].extend(check_tracing_policies())
    report["findings"].extend(check_tetragon_cli())
    crit = sum(1 for f in report["findings"] if f.get("severity") == "CRITICAL")
    report["risk_level"] = "CRITICAL" if crit > 0 else "HIGH" if report["findings"] else "LOW"
    print(f"[*] {len(report['findings'])} findings, risk: {report['risk_level']}")
    if args.output:
        with open(args.output, "w") as f:
            json.dump(report, f, indent=2)
    else:
        print(json.dumps(report, indent=2))

if __name__ == "__main__":
    main()
process.py13.4 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
Tetragon Runtime Security Event Analyzer

Parses Tetragon JSON event logs and generates security reports
including process execution anomalies, policy violations, and
container escape attempt detection.
"""

import json
import sys
import subprocess
import argparse
from datetime import datetime, timedelta
from collections import Counter, defaultdict
from pathlib import Path


def run_kubectl_command(command: list[str]) -> str:
    """Execute a kubectl command and return output."""
    try:
        result = subprocess.run(
            command, capture_output=True, text=True, timeout=30
        )
        if result.returncode != 0:
            print(f"[ERROR] kubectl command failed: {result.stderr.strip()}")
            return ""
        return result.stdout.strip()
    except subprocess.TimeoutExpired:
        print("[ERROR] kubectl command timed out")
        return ""
    except FileNotFoundError:
        print("[ERROR] kubectl not found in PATH")
        return ""


def get_tetragon_status() -> dict:
    """Check Tetragon DaemonSet health."""
    output = run_kubectl_command([
        "kubectl", "get", "ds", "tetragon", "-n", "kube-system",
        "-o", "jsonpath={.status.desiredNumberScheduled},{.status.numberReady}"
    ])
    if not output:
        return {"healthy": False, "desired": 0, "ready": 0}
    parts = output.split(",")
    desired = int(parts[0]) if len(parts) > 0 and parts[0] else 0
    ready = int(parts[1]) if len(parts) > 1 and parts[1] else 0
    return {"healthy": desired == ready and desired > 0, "desired": desired, "ready": ready}


def get_tracing_policies() -> list[dict]:
    """List all TracingPolicies deployed in the cluster."""
    output = run_kubectl_command([
        "kubectl", "get", "tracingpolicies", "-o", "json"
    ])
    if not output:
        return []
    try:
        data = json.loads(output)
        policies = []
        for item in data.get("items", []):
            policies.append({
                "name": item["metadata"]["name"],
                "created": item["metadata"].get("creationTimestamp", "unknown"),
                "kprobes": len(item.get("spec", {}).get("kprobes", [])),
                "tracepoints": len(item.get("spec", {}).get("tracepoints", []))
            })
        return policies
    except (json.JSONDecodeError, KeyError):
        return []


def parse_tetragon_events(log_file: str) -> list[dict]:
    """Parse Tetragon JSON event log file."""
    events = []
    path = Path(log_file)
    if not path.exists():
        print(f"[ERROR] Log file not found: {log_file}")
        return events

    with open(path, "r") as f:
        for line_num, line in enumerate(f, 1):
            line = line.strip()
            if not line:
                continue
            try:
                event = json.loads(line)
                events.append(event)
            except json.JSONDecodeError:
                print(f"[WARN] Skipping malformed JSON at line {line_num}")
    return events


def classify_event(event: dict) -> str:
    """Classify a Tetragon event by type."""
    if "process_exec" in event:
        return "process_exec"
    elif "process_exit" in event:
        return "process_exit"
    elif "process_kprobe" in event:
        return "kprobe"
    elif "process_tracepoint" in event:
        return "tracepoint"
    elif "process_lsm" in event:
        return "lsm"
    return "unknown"


def extract_process_info(event: dict) -> dict:
    """Extract process information from a Tetragon event."""
    info = {"binary": "", "args": "", "namespace": "", "pod": "", "uid": 0, "action": ""}
    for event_type in ["process_exec", "process_kprobe", "process_tracepoint"]:
        if event_type in event:
            process = event[event_type].get("process", {})
            info["binary"] = process.get("binary", "")
            info["args"] = process.get("arguments", "")
            info["uid"] = process.get("uid", {}).get("value", 0)
            pod_info = process.get("pod", {})
            info["namespace"] = pod_info.get("namespace", "")
            info["pod"] = pod_info.get("name", "")
            if event_type == "process_kprobe":
                info["action"] = event[event_type].get("action", "")
            break
    return info


def detect_suspicious_binaries(events: list[dict]) -> list[dict]:
    """Detect execution of known suspicious binaries."""
    suspicious_binaries = {
        "/bin/sh", "/bin/bash", "/bin/dash", "/usr/bin/curl",
        "/usr/bin/wget", "/usr/bin/nc", "/usr/bin/ncat",
        "/usr/bin/nmap", "/usr/bin/python", "/usr/bin/python3",
        "/usr/bin/perl", "/usr/bin/ruby", "/usr/bin/gcc",
        "/usr/bin/cc", "/usr/bin/make", "/usr/bin/xmrig",
        "/tmp/xmrig", "/usr/bin/minerd",
        "/usr/bin/sudo", "/bin/su", "/usr/bin/passwd",
        "/usr/bin/nsenter", "/usr/bin/unshare"
    }
    findings = []
    for event in events:
        info = extract_process_info(event)
        if info["binary"] in suspicious_binaries:
            findings.append({
                "severity": "HIGH" if info["binary"] in {"/usr/bin/xmrig", "/usr/bin/nsenter", "/usr/bin/unshare"} else "MEDIUM",
                "binary": info["binary"],
                "args": info["args"],
                "namespace": info["namespace"],
                "pod": info["pod"],
                "description": f"Suspicious binary execution: {info['binary']}"
            })
    return findings


def detect_privilege_escalation(events: list[dict]) -> list[dict]:
    """Detect privilege escalation attempts from event data."""
    findings = []
    priv_esc_binaries = {"/usr/bin/sudo", "/bin/su", "/usr/bin/passwd", "/usr/bin/newgrp"}
    for event in events:
        info = extract_process_info(event)
        if info["binary"] in priv_esc_binaries and info["namespace"]:
            findings.append({
                "severity": "CRITICAL",
                "binary": info["binary"],
                "namespace": info["namespace"],
                "pod": info["pod"],
                "description": f"Privilege escalation attempt via {info['binary']} in pod {info['pod']}"
            })
        if info["uid"] == 0 and info["binary"] and info["namespace"]:
            findings.append({
                "severity": "HIGH",
                "binary": info["binary"],
                "namespace": info["namespace"],
                "pod": info["pod"],
                "description": f"Process running as root (UID 0): {info['binary']}"
            })
    return findings


def detect_container_escape_attempts(events: list[dict]) -> list[dict]:
    """Detect potential container escape attempts."""
    escape_indicators = {
        "__x64_sys_setns": "Namespace manipulation (potential container escape)",
        "__x64_sys_unshare": "Namespace unshare (potential privilege escalation)",
        "__x64_sys_mount": "Mount syscall (potential host filesystem access)",
        "__x64_sys_ptrace": "Ptrace syscall (potential process injection)",
    }
    findings = []
    for event in events:
        if "process_kprobe" in event:
            function_name = event["process_kprobe"].get("functionName", "")
            if function_name in escape_indicators:
                info = extract_process_info(event)
                findings.append({
                    "severity": "CRITICAL",
                    "function": function_name,
                    "binary": info["binary"],
                    "namespace": info["namespace"],
                    "pod": info["pod"],
                    "action": info["action"],
                    "description": escape_indicators[function_name]
                })
    return findings


def generate_event_summary(events: list[dict]) -> dict:
    """Generate a statistical summary of Tetragon events."""
    event_types = Counter()
    namespaces = Counter()
    binaries = Counter()
    actions = Counter()

    for event in events:
        event_type = classify_event(event)
        event_types[event_type] += 1
        info = extract_process_info(event)
        if info["namespace"]:
            namespaces[info["namespace"]] += 1
        if info["binary"]:
            binaries[info["binary"]] += 1
        if info["action"]:
            actions[info["action"]] += 1

    return {
        "total_events": len(events),
        "event_types": dict(event_types.most_common(10)),
        "top_namespaces": dict(namespaces.most_common(10)),
        "top_binaries": dict(binaries.most_common(20)),
        "enforcement_actions": dict(actions),
    }


def generate_report(events: list[dict], output_format: str = "text") -> str:
    """Generate a comprehensive security report."""
    summary = generate_event_summary(events)
    suspicious = detect_suspicious_binaries(events)
    priv_esc = detect_privilege_escalation(events)
    escape_attempts = detect_container_escape_attempts(events)
    tetragon_status = get_tetragon_status()
    policies = get_tracing_policies()

    if output_format == "json":
        report = {
            "report_generated": datetime.utcnow().isoformat(),
            "tetragon_status": tetragon_status,
            "tracing_policies": policies,
            "event_summary": summary,
            "findings": {
                "suspicious_binaries": suspicious,
                "privilege_escalation": priv_esc,
                "container_escape_attempts": escape_attempts
            },
            "risk_score": calculate_risk_score(suspicious, priv_esc, escape_attempts)
        }
        return json.dumps(report, indent=2)

    lines = []
    lines.append("=" * 70)
    lines.append("TETRAGON RUNTIME SECURITY REPORT")
    lines.append(f"Generated: {datetime.utcnow().isoformat()}")
    lines.append("=" * 70)

    lines.append("\n## Tetragon Health")
    lines.append(f"  Status: {'HEALTHY' if tetragon_status['healthy'] else 'DEGRADED'}")
    lines.append(f"  Nodes: {tetragon_status['ready']}/{tetragon_status['desired']} ready")

    lines.append(f"\n## TracingPolicies Deployed: {len(policies)}")
    for p in policies:
        lines.append(f"  - {p['name']} (kprobes: {p['kprobes']}, tracepoints: {p['tracepoints']})")

    lines.append(f"\n## Event Summary")
    lines.append(f"  Total Events: {summary['total_events']}")
    lines.append("  Event Types:")
    for etype, count in summary["event_types"].items():
        lines.append(f"    {etype}: {count}")

    lines.append("\n  Top Namespaces:")
    for ns, count in summary["top_namespaces"].items():
        lines.append(f"    {ns}: {count}")

    lines.append("\n  Top Binaries:")
    for binary, count in list(summary["top_binaries"].items())[:10]:
        lines.append(f"    {binary}: {count}")

    risk = calculate_risk_score(suspicious, priv_esc, escape_attempts)
    lines.append(f"\n## Risk Score: {risk['score']}/100 ({risk['level']})")

    if escape_attempts:
        lines.append(f"\n## CRITICAL: Container Escape Attempts ({len(escape_attempts)})")
        for f in escape_attempts:
            lines.append(f"  [{f['severity']}] {f['description']}")
            lines.append(f"    Pod: {f['namespace']}/{f['pod']} | Binary: {f['binary']}")

    if priv_esc:
        lines.append(f"\n## Privilege Escalation Findings ({len(priv_esc)})")
        for f in priv_esc[:20]:
            lines.append(f"  [{f['severity']}] {f['description']}")

    if suspicious:
        lines.append(f"\n## Suspicious Binary Executions ({len(suspicious)})")
        for f in suspicious[:20]:
            lines.append(f"  [{f['severity']}] {f['description']}")
            lines.append(f"    Namespace: {f['namespace']} | Pod: {f['pod']}")

    lines.append("\n" + "=" * 70)
    return "\n".join(lines)


def calculate_risk_score(suspicious: list, priv_esc: list, escapes: list) -> dict:
    """Calculate overall risk score based on findings."""
    score = 0
    score += len(escapes) * 25
    score += len([f for f in priv_esc if f["severity"] == "CRITICAL"]) * 15
    score += len([f for f in priv_esc if f["severity"] == "HIGH"]) * 5
    score += len([f for f in suspicious if f["severity"] == "HIGH"]) * 10
    score += len([f for f in suspicious if f["severity"] == "MEDIUM"]) * 3
    score = min(score, 100)

    if score >= 80:
        level = "CRITICAL"
    elif score >= 50:
        level = "HIGH"
    elif score >= 25:
        level = "MEDIUM"
    else:
        level = "LOW"

    return {"score": score, "level": level}


def main():
    parser = argparse.ArgumentParser(
        description="Tetragon Runtime Security Event Analyzer"
    )
    parser.add_argument(
        "--log-file",
        help="Path to Tetragon JSON event log file"
    )
    parser.add_argument(
        "--format", choices=["text", "json"], default="text",
        help="Output format (default: text)"
    )
    parser.add_argument(
        "--status-only", action="store_true",
        help="Only check Tetragon health and policy status"
    )
    args = parser.parse_args()

    if args.status_only:
        status = get_tetragon_status()
        policies = get_tracing_policies()
        print(f"Tetragon Health: {'HEALTHY' if status['healthy'] else 'DEGRADED'}")
        print(f"Nodes Ready: {status['ready']}/{status['desired']}")
        print(f"TracingPolicies: {len(policies)}")
        for p in policies:
            print(f"  - {p['name']}")
        return

    if not args.log_file:
        print("[ERROR] --log-file is required (or use --status-only)")
        sys.exit(1)

    events = parse_tetragon_events(args.log_file)
    if not events:
        print("[WARN] No events found in log file")
        return

    report = generate_report(events, args.format)
    print(report)


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 2.5 KB
Keep exploring