Expand security checks to 43 cloud checks + 34 Kubernetes checks
Browse files- security.py: grew from 5 to 43 rule-based checks covering storage,
database, network, IAM, compute, container, serverless, cache, queue,
CDN, gateway, and cross-cutting (hardcoded creds, transit encryption)
- kubernetes_security.py: new analyzer with 34 K8s-specific checks:
pod security (hostNetwork/PID/IPC, privileged, allowPrivilegeEscalation,
readOnlyRootFilesystem, runAsRoot, seccomp, sysctls, capabilities),
image hygiene (:latest, untagged, Docker Hub), volumes (hostPath, PV
reclaim policy), RBAC (cluster-admin, wildcard verbs/resources, secrets
access, system:serviceaccounts binding), network (NetworkPolicy, NodePort,
LoadBalancer, Ingress TLS), and config (ConfigMap secrets, default namespace)
- kubernetes.py: new YAML parser for K8s manifests (Deployment, StatefulSet,
DaemonSet, Job, CronJob, Pod, Service, Ingress, RBAC, NetworkPolicy,
ConfigMap, Secret, PV/PVC, ServiceAccount); handles multi-doc YAML
- registry.py / engine.py: register KubernetesParser and KubernetesSecurityAnalyzer
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Files changed (6)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693"""Kubernetes-specific security analyzer — checks K8s manifest best practices."""
from __future__ import annotations
from .base import BaseAnalyzerfrom ..models.architecture import ArchitectureModel, ComponentTypefrom ..models.findings import Finding, FindingType, Severity
_WORKLOAD_SERVICES = {"deployment", "statefulset", "daemonset", "replicaset", "job", "cronjob", "pod"}
_DANGEROUS_CAPS = { "ALL", "SYS_ADMIN", "NET_ADMIN", "SYS_PTRACE", "SYS_MODULE", "DAC_READ_SEARCH", "DAC_OVERRIDE", "SETUID", "SETGID", "NET_RAW", "SYS_RAWIO", "AUDIT_WRITE", "SYS_CHROOT", "KILL", "MKNOD", "NET_BIND_SERVICE",}
_SENSITIVE_KEY_FRAGMENTS = { "password", "secret", "token", "api_key", "apikey", "private_key", "credentials", "passwd", "auth",}
class KubernetesSecurityAnalyzer(BaseAnalyzer): def analyze(self, model: ArchitectureModel) -> list[Finding]: if model.source != "kubernetes": return [] findings: list[Finding] = [] for check in [ # Pod / workload self._check_host_namespaces, self._check_privileged_container, self._check_allow_privilege_escalation, self._check_readonly_root_filesystem, self._check_run_as_root, self._check_no_security_context, self._check_dangerous_capabilities, self._check_no_cap_drop_all, self._check_no_resource_limits, self._check_no_resource_requests, self._check_no_liveness_probe, self._check_no_readiness_probe, self._check_no_seccomp_profile, self._check_unsafe_sysctls, # Image hygiene self._check_image_latest_tag, self._check_image_no_tag, self._check_image_from_public_registry, # Volumes self._check_host_path_volume, self._check_pv_host_path, self._check_pv_delete_reclaim_policy, # Service account self._check_default_service_account, self._check_automount_sa_token, # RBAC self._check_cluster_admin_binding, self._check_wildcard_rbac_verbs, self._check_wildcard_rbac_resources, self._check_rbac_access_to_secrets, self._check_rbac_binds_all_service_accounts, # Network self._check_no_network_policy, self._check_service_type_loadbalancer, self._check_service_type_nodeport, self._check_ingress_no_tls, self._check_ingress_no_class, # Secrets / config self._check_configmap_sensitive_keys, self._check_default_namespace, ]: findings.extend(check(model)) return findings
# ----------------------------------------------------------------- helpers
def _workloads(self, model: ArchitectureModel) -> list: return [ c for c in model.components_by_type(ComponentType.CONTAINER) if c.provider == "kubernetes" and c.service in _WORKLOAD_SERVICES ]
# --------------------------------------------------------- Host namespaces
def _check_host_namespaces(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in self._workloads(model): for key, label in [ ("k8s_host_network", "hostNetwork"), ("k8s_host_pid", "hostPID"), ("k8s_host_ipc", "hostIPC"), ]: if c.properties.get(key, False): findings.append(Finding( type=FindingType.SECURITY, severity=Severity.CRITICAL, title=f"Workload '{c.name}' sets {label}: true", description=f"{label} shares the host's namespace with the container, enabling surveillance of host processes and trivial container escape.", component_id=c.id, component_name=c.name, recommendation=f"Remove {label}: true. Only CNI/node-level daemonsets ever legitimately need this.", references=["https://kubernetes.io/docs/concepts/security/pod-security-standards/"], )) return findings
# --------------------------------------------------------- Privileged mode
def _check_privileged_container(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in self._workloads(model): if c.properties.get("k8s_privileged", False): findings.append(Finding( type=FindingType.SECURITY, severity=Severity.CRITICAL, title=f"Workload '{c.name}' runs a privileged container", description="privileged: true grants root-equivalent host access — a container escape becomes a full node compromise.", component_id=c.id, component_name=c.name, recommendation="Remove privileged: true. Use securityContext.capabilities.add for the specific capabilities actually needed.", references=["https://kubernetes.io/docs/concepts/security/pod-security-standards/#privileged"], )) return findings
# ----------------------------------------------- Privilege escalation
def _check_allow_privilege_escalation(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in self._workloads(model): if c.properties.get("k8s_allow_privilege_escalation", True): findings.append(Finding( type=FindingType.SECURITY, severity=Severity.HIGH, title=f"Workload '{c.name}' allows privilege escalation", description="allowPrivilegeEscalation defaults to true, permitting setuid binaries to gain more privileges than their parent process.", component_id=c.id, component_name=c.name, recommendation="Set securityContext.allowPrivilegeEscalation: false on every container.", references=["https://kubernetes.io/docs/tasks/configure-pod-container/security-context/"], )) return findings
# --------------------------------------------------- Read-only rootfs
def _check_readonly_root_filesystem(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in self._workloads(model): if not c.properties.get("k8s_readonly_root_filesystem", False): findings.append(Finding( type=FindingType.SECURITY, severity=Severity.MEDIUM, title=f"Workload '{c.name}' does not use a read-only root filesystem", description="A writable root filesystem lets an attacker persist malware or modify binaries after compromising a container.", component_id=c.id, component_name=c.name, recommendation="Set securityContext.readOnlyRootFilesystem: true. Mount writable emptyDir volumes for paths that genuinely need writes.", references=["https://kubernetes.io/docs/tasks/configure-pod-container/security-context/"], )) return findings
# ------------------------------------------------------------- Run as root
def _check_run_as_root(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in self._workloads(model): run_as_non_root = c.properties.get("k8s_run_as_non_root", False) run_as_user = c.properties.get("k8s_run_as_user") if not run_as_non_root and (run_as_user is None or str(run_as_user) == "0"): findings.append(Finding( type=FindingType.SECURITY, severity=Severity.HIGH, title=f"Workload '{c.name}' may run as root (UID 0)", description="Most images default to root. Running as root maximises the impact of any vulnerability or escape.", component_id=c.id, component_name=c.name, recommendation="Set securityContext.runAsNonRoot: true and runAsUser to a non-zero UID (e.g. 1000).", references=["https://kubernetes.io/docs/tasks/configure-pod-container/security-context/"], )) return findings
# ----------------------------------------------------- No security context
def _check_no_security_context(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in self._workloads(model): if not c.properties.get("k8s_has_security_context", True): findings.append(Finding( type=FindingType.SECURITY, severity=Severity.MEDIUM, title=f"Workload '{c.name}' has no securityContext on at least one container", description="Containers without a securityContext inherit permissive defaults: root UID, privilege escalation allowed, writable rootfs.", component_id=c.id, component_name=c.name, recommendation="Add a securityContext to every container with runAsNonRoot, readOnlyRootFilesystem, and allowPrivilegeEscalation: false at minimum.", references=["https://kubernetes.io/docs/tasks/configure-pod-container/security-context/"], )) return findings
# ------------------------------------------------------ Capabilities
def _check_dangerous_capabilities(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in self._workloads(model): caps = set(c.properties.get("k8s_capabilities_add") or []) dangerous = {cap.upper() for cap in caps} & _DANGEROUS_CAPS if dangerous: findings.append(Finding( type=FindingType.SECURITY, severity=Severity.HIGH, title=f"Workload '{c.name}' adds dangerous capabilities: {', '.join(sorted(dangerous))}", description="Capabilities like SYS_ADMIN and NET_ADMIN give near-root kernel access, enabling container escape and host manipulation.", component_id=c.id, component_name=c.name, recommendation="Drop ALL capabilities first (capabilities.drop: [ALL]) then add back only those the process strictly requires.", references=["https://kubernetes.io/docs/tasks/configure-pod-container/security-context/#set-capabilities-for-a-container"], )) return findings
def _check_no_cap_drop_all(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in self._workloads(model): if not c.properties.get("k8s_drops_all_caps", False): findings.append(Finding( type=FindingType.SECURITY, severity=Severity.MEDIUM, title=f"Workload '{c.name}' does not drop all Linux capabilities", description="Without capabilities.drop: [ALL], the container retains its default capability set, which includes several that can be abused.", component_id=c.id, component_name=c.name, recommendation="Add capabilities.drop: [ALL] to every container's securityContext, then explicitly add back required capabilities.", references=["https://kubernetes.io/docs/tasks/configure-pod-container/security-context/#set-capabilities-for-a-container"], )) return findings
# -------------------------------------------------- Resource limits/requests
def _check_no_resource_limits(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in self._workloads(model): if not c.properties.get("k8s_has_resource_limits", True): findings.append(Finding( type=FindingType.SECURITY, severity=Severity.MEDIUM, title=f"Workload '{c.name}' has no resource limits (CPU/memory)", description="Without limits, a compromised or buggy container can exhaust node resources and cause a denial-of-service for other pods.", component_id=c.id, component_name=c.name, recommendation="Set resources.limits.cpu and resources.limits.memory on every container.", references=["https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/"], )) return findings
def _check_no_resource_requests(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in self._workloads(model): if not c.properties.get("k8s_has_resource_requests", True): findings.append(Finding( type=FindingType.SECURITY, severity=Severity.LOW, title=f"Workload '{c.name}' has no resource requests", description="Without requests, the scheduler cannot make informed placement decisions, leading to resource contention and noisy-neighbour effects.", component_id=c.id, component_name=c.name, recommendation="Set resources.requests.cpu and resources.requests.memory so the scheduler can plan appropriately.", references=["https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/"], )) return findings
# -------------------------------------------- Liveness / readiness probes
def _check_no_liveness_probe(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in self._workloads(model): if not c.properties.get("k8s_has_liveness_probe", True): findings.append(Finding( type=FindingType.SECURITY, severity=Severity.LOW, title=f"Workload '{c.name}' has no livenessProbe", description="Without a liveness probe, a deadlocked container is never restarted — degrading availability without alerting operators.", component_id=c.id, component_name=c.name, recommendation="Define a livenessProbe (HTTP GET, TCP, or exec) matching the application's health check semantics.", references=["https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/"], )) return findings
def _check_no_readiness_probe(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in self._workloads(model): if not c.properties.get("k8s_has_readiness_probe", True): findings.append(Finding( type=FindingType.SECURITY, severity=Severity.LOW, title=f"Workload '{c.name}' has no readinessProbe", description="Without a readiness probe, traffic is routed to containers before they are ready to serve, causing errors during startup or rolling updates.", component_id=c.id, component_name=c.name, recommendation="Define a readinessProbe so Kubernetes gates traffic until the container signals readiness.", references=["https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/"], )) return findings
# ---------------------------------------------------------- Seccomp / sysctls
def _check_no_seccomp_profile(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in self._workloads(model): if not c.properties.get("k8s_seccomp_profile", ""): findings.append(Finding( type=FindingType.SECURITY, severity=Severity.MEDIUM, title=f"Workload '{c.name}' has no seccomp profile", description="Without seccomp, the container can make any Linux syscall — a broad kernel attack surface exploitable via CVEs.", component_id=c.id, component_name=c.name, recommendation="Set securityContext.seccompProfile.type: RuntimeDefault (or Localhost with a custom profile for stricter enforcement).", references=["https://kubernetes.io/docs/tutorials/security/seccomp/"], )) return findings
def _check_unsafe_sysctls(self, model: ArchitectureModel) -> list[Finding]: findings = [] unsafe_prefixes = {"net.", "kernel.", "vm.", "fs."} for c in self._workloads(model): sysctls = c.properties.get("k8s_sysctls") or [] unsafe = [s.get("name", "") for s in sysctls if any(s.get("name", "").startswith(p) for p in unsafe_prefixes)] if unsafe: findings.append(Finding( type=FindingType.SECURITY, severity=Severity.HIGH, title=f"Workload '{c.name}' modifies unsafe kernel parameters via sysctls: {', '.join(unsafe)}", description="Unsafe sysctls modify kernel networking or memory settings that can destabilise the node or bypass network isolation.", component_id=c.id, component_name=c.name, recommendation="Remove unsafe sysctls. If absolutely required, confine them with PodSecurityAdmission allowedUnsafeSysctls.", references=["https://kubernetes.io/docs/tasks/administer-cluster/sysctl-cluster/"], )) return findings
# ---------------------------------------------------- Image hygiene
def _check_image_latest_tag(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in self._workloads(model): images = c.properties.get("k8s_images") or [] bad = [img for img in images if img.endswith(":latest")] if bad: findings.append(Finding( type=FindingType.SECURITY, severity=Severity.MEDIUM, title=f"Workload '{c.name}' uses ':latest' image tag: {', '.join(bad)}", description=":latest is a mutable pointer — an upstream push can silently change what runs in production without a re-deploy.", component_id=c.id, component_name=c.name, recommendation="Pin images to an immutable digest (image@sha256:...) or a specific semver tag (image:1.2.3).", references=["https://kubernetes.io/docs/concepts/containers/images/#image-pull-policy"], )) return findings
def _check_image_no_tag(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in self._workloads(model): images = c.properties.get("k8s_images") or [] untagged = [img for img in images if img and ":" not in img and "@" not in img] if untagged: findings.append(Finding( type=FindingType.SECURITY, severity=Severity.MEDIUM, title=f"Workload '{c.name}' references untagged images: {', '.join(untagged)}", description="Images without a tag or digest default to :latest and are indeterminate — you cannot reason about what version is running.", component_id=c.id, component_name=c.name, recommendation="Always specify an explicit tag or digest.", references=["https://kubernetes.io/docs/concepts/containers/images/"], )) return findings
def _check_image_from_public_registry(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in self._workloads(model): images = c.properties.get("k8s_images") or [] public = [ img for img in images if img and "." not in img.split("/")[0] and "/" in img or (img and "/" not in img.split(":")[0]) ] if public: findings.append(Finding( type=FindingType.SECURITY, severity=Severity.LOW, title=f"Workload '{c.name}' pulls images from Docker Hub (public registry)", description="Public registries have rate limits, no SLA, and allow anyone to push to public repos — compromised images are a supply-chain risk.", component_id=c.id, component_name=c.name, recommendation="Mirror approved images to a private registry (ECR, Artifact Registry, Harbor) with vulnerability scanning enabled.", references=["https://kubernetes.io/docs/concepts/containers/images/"], )) return findings
# ----------------------------------------------------- Volumes
def _check_host_path_volume(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in self._workloads(model): if c.properties.get("k8s_host_path_volumes", False): findings.append(Finding( type=FindingType.SECURITY, severity=Severity.HIGH, title=f"Workload '{c.name}' mounts a hostPath volume", description="hostPath mounts expose arbitrary host filesystem paths — a container escape can read or modify the entire host.", component_id=c.id, component_name=c.name, recommendation="Replace hostPath mounts with PersistentVolumeClaims backed by a CSI driver. Restrict remaining cases with PodSecurityAdmission.", references=["https://kubernetes.io/docs/concepts/storage/volumes/#hostpath"], )) return findings
def _check_pv_host_path(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in model.components_by_type(ComponentType.STORAGE): if c.provider == "kubernetes" and c.properties.get("k8s_pv_host_path", False): findings.append(Finding( type=FindingType.SECURITY, severity=Severity.HIGH, title=f"PersistentVolume '{c.name}' uses hostPath storage", description="hostPath PVs bind to a specific node's filesystem, enabling container escape and creating opaque data persistence outside normal backup paths.", component_id=c.id, component_name=c.name, recommendation="Replace with a network-attached CSI driver (EBS, EFS, NFS, Longhorn) that is node-independent and backup-friendly.", references=["https://kubernetes.io/docs/concepts/storage/volumes/#hostpath"], )) return findings
def _check_pv_delete_reclaim_policy(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in model.components_by_type(ComponentType.STORAGE): if c.provider == "kubernetes" and c.properties.get("k8s_pv_reclaim_policy", "Delete") == "Delete": findings.append(Finding( type=FindingType.SECURITY, severity=Severity.MEDIUM, title=f"PersistentVolume '{c.name}' uses reclaimPolicy: Delete", description="Delete reclaim policy permanently destroys the underlying volume when the PVC is released — data is unrecoverable.", component_id=c.id, component_name=c.name, recommendation="Set persistentVolumeReclaimPolicy: Retain for stateful workloads. Implement a separate backup and manual cleanup process.", references=["https://kubernetes.io/docs/concepts/storage/persistent-volumes/#reclaiming"], )) return findings
# ------------------------------------------------ Service account
def _check_default_service_account(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in self._workloads(model): if c.properties.get("k8s_service_account", "default") == "default": findings.append(Finding( type=FindingType.SECURITY, severity=Severity.MEDIUM, title=f"Workload '{c.name}' uses the default service account", description="The default service account is shared across all workloads in a namespace, making least-privilege RBAC and token scope impossible.", component_id=c.id, component_name=c.name, recommendation="Create a dedicated ServiceAccount per workload and bind only the RBAC permissions that workload requires.", references=["https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/"], )) return findings
def _check_automount_sa_token(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in self._workloads(model): if c.properties.get("k8s_automount_sa_token", True): findings.append(Finding( type=FindingType.SECURITY, severity=Severity.MEDIUM, title=f"Workload '{c.name}' auto-mounts the service account token", description="Auto-mounted tokens are available to any process in the container. A compromised workload can use the token to call the Kubernetes API.", component_id=c.id, component_name=c.name, recommendation="Set automountServiceAccountToken: false on pod specs (and ServiceAccount objects) for workloads that don't need API access.", references=["https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/#opt-out-of-api-credential-automounting"], )) return findings
# ---------------------------------------------------------------- RBAC
def _check_cluster_admin_binding(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in model.components_by_type(ComponentType.IAM): if c.provider == "kubernetes" and c.properties.get("k8s_is_cluster_admin", False): findings.append(Finding( type=FindingType.SECURITY, severity=Severity.CRITICAL, title=f"RBAC '{c.name}' binds to the cluster-admin role", description="cluster-admin grants unrestricted access to every API and resource in the cluster — a stolen token is a total compromise.", component_id=c.id, component_name=c.name, recommendation="Replace cluster-admin bindings with least-privilege Roles scoped to specific namespaces and resource types.", references=["https://kubernetes.io/docs/reference/access-authn-authz/rbac/#user-facing-roles"], )) return findings
def _check_wildcard_rbac_verbs(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in model.components_by_type(ComponentType.IAM): if c.provider == "kubernetes" and c.properties.get("k8s_wildcard_verbs", False): findings.append(Finding( type=FindingType.SECURITY, severity=Severity.HIGH, title=f"RBAC '{c.name}' grants wildcard verbs (*)", description="verbs: ['*'] allows get, list, create, delete, escalate, and more on all matched resources.", component_id=c.id, component_name=c.name, recommendation="Replace ['*'] with the exact verb list needed (e.g. [get, list, watch]).", references=["https://kubernetes.io/docs/reference/access-authn-authz/rbac/"], )) return findings
def _check_wildcard_rbac_resources(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in model.components_by_type(ComponentType.IAM): if c.provider == "kubernetes" and c.properties.get("k8s_wildcard_resources", False): findings.append(Finding( type=FindingType.SECURITY, severity=Severity.HIGH, title=f"RBAC '{c.name}' grants access to all resources (*)", description="resources: ['*'] covers every API resource type including secrets, configmaps, and pods/exec — all sensitive.", component_id=c.id, component_name=c.name, recommendation="List only the specific resource types needed. Treat secrets access as a separate, explicitly justified grant.", references=["https://kubernetes.io/docs/reference/access-authn-authz/rbac/"], )) return findings
def _check_rbac_access_to_secrets(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in model.components_by_type(ComponentType.IAM): if ( c.provider == "kubernetes" and c.service in ("role", "clusterrole") and c.properties.get("k8s_accesses_secrets", False) and not c.properties.get("k8s_wildcard_resources", False) ): findings.append(Finding( type=FindingType.SECURITY, severity=Severity.MEDIUM, title=f"RBAC '{c.name}' explicitly grants access to Secrets", description="Permissions on secrets allow reading API tokens, TLS private keys, and application credentials stored in the cluster.", component_id=c.id, component_name=c.name, recommendation="Minimise who can read Secrets. Prefer injecting secrets via an external secrets operator (Vault, ASM) with per-workload scoping.", references=["https://kubernetes.io/docs/concepts/configuration/secret/#information-security-for-secrets"], )) return findings
def _check_rbac_binds_all_service_accounts(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in model.components_by_type(ComponentType.IAM): if c.provider == "kubernetes" and c.properties.get("k8s_binds_all_sa", False): findings.append(Finding( type=FindingType.SECURITY, severity=Severity.HIGH, title=f"RBAC '{c.name}' grants permissions to ALL service accounts in the cluster", description="Binding to system:serviceaccounts gives every pod in every namespace these permissions — any workload compromise becomes privileged.", component_id=c.id, component_name=c.name, recommendation="Bind roles to specific ServiceAccount subjects, not the system:serviceaccounts group.", references=["https://kubernetes.io/docs/reference/access-authn-authz/rbac/#referring-to-subjects"], )) return findings
# -------------------------------------------------------------- Network
def _check_no_network_policy(self, model: ArchitectureModel) -> list[Finding]: has_netpol = any(c.properties.get("k8s_kind") == "NetworkPolicy" for c in model.components) if self._workloads(model) and not has_netpol: return [Finding( type=FindingType.SECURITY, severity=Severity.HIGH, title="No NetworkPolicy found — all pod-to-pod traffic is unrestricted", description="Without NetworkPolicies, any compromised pod can freely reach every other pod, database, and internal API in the cluster.", recommendation="Define a default-deny NetworkPolicy per namespace, then whitelist only the pod-to-pod connections that are required.", references=["https://kubernetes.io/docs/concepts/services-networking/network-policies/"], )] return []
def _check_service_type_loadbalancer(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in model.components_by_type(ComponentType.NETWORK): if c.provider == "kubernetes" and c.properties.get("k8s_service_type") == "LoadBalancer": findings.append(Finding( type=FindingType.SECURITY, severity=Severity.MEDIUM, title=f"Service '{c.name}' is type LoadBalancer (public cloud LB per service)", description="LoadBalancer services provision a separate public LB for each service, potentially exposing internal services directly to the internet.", component_id=c.id, component_name=c.name, recommendation="Use a shared Ingress controller with TLS termination and WAF instead of per-service LoadBalancers.", references=["https://kubernetes.io/docs/concepts/services-networking/service/#loadbalancer"], )) return findings
def _check_service_type_nodeport(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in model.components_by_type(ComponentType.NETWORK): if c.provider == "kubernetes" and c.properties.get("k8s_service_type") == "NodePort": findings.append(Finding( type=FindingType.SECURITY, severity=Severity.MEDIUM, title=f"Service '{c.name}' is type NodePort", description="NodePort opens a high-numbered port on every cluster node, bypassing ingress controls and exposing the service on every node IP.", component_id=c.id, component_name=c.name, recommendation="Replace NodePort with ClusterIP + Ingress for external traffic, or LoadBalancer with strict security groups.", references=["https://kubernetes.io/docs/concepts/services-networking/service/#type-nodeport"], )) return findings
def _check_ingress_no_tls(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in model.components_by_type(ComponentType.GATEWAY): if c.provider == "kubernetes" and not c.properties.get("k8s_has_tls", True): findings.append(Finding( type=FindingType.SECURITY, severity=Severity.HIGH, title=f"Ingress '{c.name}' has no TLS configured", description="An Ingress without TLS serves traffic over plain HTTP, exposing credentials, session tokens, and data to network interception.", component_id=c.id, component_name=c.name, recommendation="Add a tls: block with a valid certificate. Use cert-manager with Let's Encrypt for automated certificate lifecycle.", references=["https://kubernetes.io/docs/concepts/services-networking/ingress/#tls"], )) return findings
def _check_ingress_no_class(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in model.components_by_type(ComponentType.GATEWAY): if c.provider == "kubernetes" and not c.properties.get("k8s_ingress_class", ""): findings.append(Finding( type=FindingType.SECURITY, severity=Severity.LOW, title=f"Ingress '{c.name}' has no ingress class specified", description="Without an explicit ingressClassName, any controller in the cluster may claim the Ingress, leading to unintended routing.", component_id=c.id, component_name=c.name, recommendation="Set spec.ingressClassName (or the kubernetes.io/ingress.class annotation) to the intended controller.", references=["https://kubernetes.io/docs/concepts/services-networking/ingress/#ingress-class"], )) return findings
# ------------------------------------------------- Secrets / ConfigMap
def _check_configmap_sensitive_keys(self, model: ArchitectureModel) -> list[Finding]: findings = [] for c in model.components: if c.provider != "kubernetes" or c.properties.get("k8s_kind") != "ConfigMap": continue keys = [k.lower() for k in c.properties.get("k8s_configmap_keys") or []] matched = [k for k in keys if any(s in k for s in _SENSITIVE_KEY_FRAGMENTS)] if matched: findings.append(Finding( type=FindingType.SECURITY, severity=Severity.HIGH, title=f"ConfigMap '{c.name}' may store sensitive data (keys: {', '.join(matched)})", description="ConfigMaps are stored in plaintext in etcd and are readable by anyone with namespace read access.", component_id=c.id, component_name=c.name, recommendation="Move sensitive values to Kubernetes Secrets (with KMS encryption at rest), or use an external secrets operator.", references=["https://kubernetes.io/docs/concepts/configuration/secret/"], )) return findings
# ----------------------------------------------------------- Namespace
def _check_default_namespace(self, model: ArchitectureModel) -> list[Finding]: findings = [] seen: set[str] = set() for c in model.components: if c.provider != "kubernetes": continue ns = c.properties.get("k8s_namespace", "") if ns == "default" and ns not in seen: seen.add(c.name) findings.append(Finding( type=FindingType.SECURITY, severity=Severity.LOW, title=f"Resource '{c.name}' is deployed in the 'default' namespace", description="Deploying workloads in 'default' mixes concerns and makes namespace-scoped RBAC and NetworkPolicies harder to apply and audit.", component_id=c.id, component_name=c.name, recommendation="Create dedicated namespaces per team or application and enforce RBAC and NetworkPolicy per namespace.", references=["https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/"], )) return findings10 unmodified lines1112131415161718192068 unmodified lines8990919293945 unmodified lines10010110210 unmodified linesdef analyze(self, model: ArchitectureModel) -> list[Finding]:findings: list[Finding] = []for check in [self._check_public_storage,self._check_unencrypted_databases,self._check_overpermissive_iam,self._check_open_security_groups,self._check_no_monitoring,]:findings.extend(check(model))68 unmodified lines))return findingsdef _check_no_monitoring(self, model: ArchitectureModel) -> list[Finding]:has_monitoring = bool(model.components_by_type(ComponentType.MONITORING))if not has_monitoring and model.components:5 unmodified linesrecommendation="Add CloudWatch, Datadog, or equivalent. Enable VPC Flow Logs and CloudTrail.",)]return []10 unmodified lines11121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697068 unmodified lines1391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413425 unmodified lines34834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388410 unmodified linesdef analyze(self, model: ArchitectureModel) -> list[Finding]:findings: list[Finding] = []for check in [# Storageself._check_public_storage,self._check_unencrypted_storage,self._check_no_access_logging,self._check_s3_versioning_disabled,self._check_public_access_block_missing,# Databaseself._check_unencrypted_databases,self._check_database_publicly_accessible,self._check_no_deletion_protection,self._check_no_backup,self._check_database_no_multi_az,self._check_database_no_audit_log,self._check_database_auto_minor_version_disabled,# Networkself._check_open_security_groups,self._check_ssh_rdp_open_to_world,self._check_unrestricted_egress,self._check_ipv6_unrestricted_ingress,# IAMself._check_overpermissive_iam,self._check_iam_wildcard_resource,self._check_iam_no_mfa_required,self._check_iam_direct_user_attach,# Computeself._check_compute_imdsv2,self._check_compute_public_ip,self._check_compute_no_ebs_encryption,# Containerself._check_container_privileged,self._check_container_root_user,self._check_container_no_resource_limits,self._check_container_no_image_scanning,# Serverlessself._check_serverless_overpermissive_role,self._check_serverless_no_dead_letter,self._check_serverless_no_vpc,# Cacheself._check_cache_no_auth,self._check_cache_not_encrypted,# Queueself._check_queue_no_encryption,self._check_queue_no_dlq,# CDNself._check_cdn_no_https_only,self._check_cdn_outdated_tls,# Gatewayself._check_gateway_no_auth,self._check_gateway_no_throttling,self._check_gateway_no_logging,self._check_no_waf,# Cross-cuttingself._check_hardcoded_credentials,self._check_encryption_in_transit,self._check_no_monitoring,]:findings.extend(check(model))68 unmodified lines))return findingsdef _check_unencrypted_storage(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.STORAGE):sse = str(c.properties.get("server_side_encryption", c.properties.get("encryption", ""))).lower()if sse in ("false", "no", "none", "disabled", ""):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.HIGH,title=f"Storage '{c.name}' is not encrypted at rest",description="Unencrypted storage exposes data if the underlying media is accessed or stolen.",component_id=c.id,component_name=c.name,recommendation="Enable server-side encryption (SSE-S3 minimum, SSE-KMS for sensitive data).",references=["https://docs.aws.amazon.com/AmazonS3/latest/userguide/serv-side-encryption.html"],))return findingsdef _check_no_access_logging(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.STORAGE):logging_val = str(c.properties.get("logging", c.properties.get("access_log", ""))).lower()if logging_val in ("false", "no", "none", "disabled", ""):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.MEDIUM,title=f"Storage '{c.name}' has no access logging enabled",description="Without access logs, unauthorized data access or exfiltration cannot be detected or investigated.",component_id=c.id,component_name=c.name,recommendation="Enable S3 server access logging or equivalent. Ship logs to a SIEM.",references=["https://docs.aws.amazon.com/AmazonS3/latest/userguide/ServerLogs.html"],))return findingsdef _check_database_publicly_accessible(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.DATABASE):publicly_accessible = str(c.properties.get("publicly_accessible", "false")).lower()if publicly_accessible in ("true", "yes", "1"):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.CRITICAL,title=f"Database '{c.name}' is publicly accessible from the internet",description="A publicly accessible database is directly reachable without going through the application tier, bypassing network controls.",component_id=c.id,component_name=c.name,recommendation="Set publicly_accessible = false. Place databases in private subnets and access via the application tier.",references=["https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Overview.DBInstance.Modifying.html"],))return findingsdef _check_no_deletion_protection(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.DATABASE):deletion_protection = str(c.properties.get("deletion_protection", "false")).lower()if deletion_protection in ("false", "no", "0", ""):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.MEDIUM,title=f"Database '{c.name}' has no deletion protection",description="Without deletion protection, a misconfigured deployment or human error can permanently destroy the database.",component_id=c.id,component_name=c.name,recommendation="Set deletion_protection = true on all production databases.",references=["https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_DeleteInstance.html"],))return findingsdef _check_no_backup(self, model: ArchitectureModel) -> list[Finding]:findings = []backup_types = {ComponentType.DATABASE, ComponentType.STORAGE}for c in model.components:if c.type not in backup_types:continueretention = str(c.properties.get("backup_retention_period", "0"))backup_enabled = str(c.properties.get("backup_enabled", "")).lower()if retention in ("0", "") and backup_enabled not in ("true", "yes", "1"):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.HIGH,title=f"'{c.name}' has no backup configured",description="Without backups, data is irrecoverable after corruption, accidental deletion, or ransomware.",component_id=c.id,component_name=c.name,recommendation="Set backup_retention_period >= 7 days. Validate restores periodically.",references=["https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithAutomatedBackups.html"],))return findingsdef _check_ssh_rdp_open_to_world(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.NETWORK):ingress = c.properties.get("ingress", [])if not isinstance(ingress, list):ingress = [ingress]for rule in ingress:rule_str = str(rule)if "0.0.0.0/0" not in rule_str and "::/0" not in rule_str:continueports_exposed = Falseif isinstance(rule, dict):try:fp = int(rule.get("from_port", rule.get("FromPort", -1)))tp = int(rule.get("to_port", rule.get("ToPort", fp)))ports_exposed = (fp <= 22 <= tp) or (fp <= 3389 <= tp)except (ValueError, TypeError):ports_exposed = "22" in rule_str or "3389" in rule_strelse:ports_exposed = "22" in rule_str or "3389" in rule_strif ports_exposed:findings.append(Finding(type=FindingType.SECURITY,severity=Severity.HIGH,title=f"Network '{c.name}' exposes SSH/RDP to the internet",description="Open SSH (22) or RDP (3389) to 0.0.0.0/0 allows brute-force and credential-stuffing attacks from any IP.",component_id=c.id,component_name=c.name,recommendation="Restrict SSH/RDP ingress to known IP ranges, or use a bastion host / VPN.",references=["https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-rules.html"],))breakreturn findingsdef _check_gateway_no_auth(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.GATEWAY):auth = str(c.properties.get("authorization", c.properties.get("authentication", ""))).lower()if auth in ("none", ""):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.HIGH,title=f"API Gateway '{c.name}' has no authentication configured",description="An unauthenticated API endpoint is reachable by any caller on the internet with no identity verification.",component_id=c.id,component_name=c.name,recommendation="Add an authorizer (IAM SigV4, JWT/Cognito, or Lambda) to all API Gateway stages.",references=["https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-to-api.html"],))return findingsdef _check_no_waf(self, model: ArchitectureModel) -> list[Finding]:gateways = model.components_by_type(ComponentType.GATEWAY)cdns = model.components_by_type(ComponentType.CDN)if not gateways and not cdns:return []has_waf = any("waf" in c.service.lower() or "waf" in c.name.lower()for c in model.components)if not has_waf:return [Finding(type=FindingType.SECURITY,severity=Severity.MEDIUM,title="No WAF detected for public-facing endpoints",description="Without a Web Application Firewall, internet-facing APIs and CDNs are unprotected against SQLi, XSS, and volumetric attacks.",recommendation="Attach AWS WAF (or equivalent) to API Gateway stages and CloudFront distributions.",references=["https://docs.aws.amazon.com/waf/latest/developerguide/what-is-aws-waf.html"],)]return []def _check_serverless_overpermissive_role(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.SERVERLESS):role = str(c.properties.get("role", "")).lower()if "admin" in role or "administrator" in role or role.endswith(":*"):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.HIGH,title=f"Serverless function '{c.name}' uses an overpermissive IAM role",description="An admin or wildcard role attached to a function violates least-privilege and widens the blast radius of a compromise.",component_id=c.id,component_name=c.name,recommendation="Create a dedicated execution role scoped to only the permissions the function requires.",references=["https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html"],))return findingsdef _check_compute_imdsv2(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.COMPUTE):metadata_opts = c.properties.get("metadata_options", {})http_tokens = str(metadata_opts.get("http_tokens", "") if isinstance(metadata_opts, dict)else c.properties.get("http_tokens", "optional")).lower()if http_tokens not in ("required", "v2"):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.MEDIUM,title=f"Compute '{c.name}' may allow IMDSv1 (instance metadata service v1)",description="IMDSv1 is vulnerable to SSRF attacks that can expose instance credentials and role tokens.",component_id=c.id,component_name=c.name,recommendation="Set metadata_options.http_tokens = 'required' to enforce IMDSv2 on all EC2 instances.",references=["https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html"],))return findingsdef _check_no_monitoring(self, model: ArchitectureModel) -> list[Finding]:has_monitoring = bool(model.components_by_type(ComponentType.MONITORING))if not has_monitoring and model.components:5 unmodified linesrecommendation="Add CloudWatch, Datadog, or equivalent. Enable VPC Flow Logs and CloudTrail.",)]return []# ------------------------------------------------------------------ Storagedef _check_s3_versioning_disabled(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.STORAGE):versioning = str(c.properties.get("versioning", c.properties.get("versioning_enabled", ""))).lower()if versioning not in ("enabled", "true", "yes", "1"):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.MEDIUM,title=f"Storage '{c.name}' has versioning disabled",description="Without versioning, accidental deletions and ransomware overwrites are unrecoverable.",component_id=c.id,component_name=c.name,recommendation="Enable S3 versioning and pair it with lifecycle rules to expire old versions cost-effectively.",references=["https://docs.aws.amazon.com/AmazonS3/latest/userguide/Versioning.html"],))return findingsdef _check_public_access_block_missing(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.STORAGE):block = str(c.properties.get("block_public_acls", c.properties.get("public_access_block", "false"))).lower()if block not in ("true", "yes", "1", "enabled"):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.HIGH,title=f"Storage '{c.name}' is missing the public access block",description="Without block_public_acls/block_public_policy, future ACL or policy changes can silently expose the bucket.",component_id=c.id,component_name=c.name,recommendation="Enable all four S3 Block Public Access settings at the bucket and account level.",references=["https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-control-block-public-access.html"],))return findings# ----------------------------------------------------------------- Databasedef _check_database_no_multi_az(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.DATABASE):multi_az = str(c.properties.get("multi_az", c.properties.get("availability", "false"))).lower()if multi_az not in ("true", "yes", "1", "enabled"):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.MEDIUM,title=f"Database '{c.name}' is not Multi-AZ",description="A single-AZ database is a single point of failure; an AZ outage causes downtime and potential data loss.",component_id=c.id,component_name=c.name,recommendation="Enable Multi-AZ for automatic failover in production environments.",references=["https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.MultiAZ.html"],))return findingsdef _check_database_no_audit_log(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.DATABASE):audit = str(c.properties.get("audit_log", c.properties.get("enable_audit_log", ""))).lower()if audit not in ("true", "yes", "1", "enabled"):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.MEDIUM,title=f"Database '{c.name}' has no audit logging enabled",description="Without audit logs, unauthorized queries, privilege escalations, and data exfiltration go undetected.",component_id=c.id,component_name=c.name,recommendation="Enable database audit logging and ship logs to CloudWatch Logs or a SIEM.",references=["https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_LogAccess.html"],))return findingsdef _check_database_auto_minor_version_disabled(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.DATABASE):auto_upgrade = str(c.properties.get("auto_minor_version_upgrade", "true")).lower()if auto_upgrade in ("false", "no", "0"):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.LOW,title=f"Database '{c.name}' will not auto-apply minor version patches",description="Disabling automatic minor version upgrades leaves known CVEs unpatched until manually applied.",component_id=c.id,component_name=c.name,recommendation="Enable auto_minor_version_upgrade = true, or establish a documented patching schedule.",references=["https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Upgrading.html"],))return findings# ------------------------------------------------------------------ Networkdef _check_unrestricted_egress(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.NETWORK):egress = c.properties.get("egress", [])if not isinstance(egress, list):egress = [egress]for rule in egress:rule_str = str(rule)if "0.0.0.0/0" in rule_str or "::/0" in rule_str:findings.append(Finding(type=FindingType.SECURITY,severity=Severity.MEDIUM,title=f"Network '{c.name}' has unrestricted outbound (egress) traffic",description="Unrestricted egress enables data exfiltration and C2 communication if a workload is compromised.",component_id=c.id,component_name=c.name,recommendation="Restrict egress to specific ports and destinations required by the application.",references=["https://docs.aws.amazon.com/vpc/latest/userguide/vpc-security-groups.html"],))breakreturn findingsdef _check_ipv6_unrestricted_ingress(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.NETWORK):ingress = c.properties.get("ingress", [])if not isinstance(ingress, list):ingress = [ingress]for rule in ingress:if "::/0" in str(rule):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.MEDIUM,title=f"Network '{c.name}' allows unrestricted IPv6 inbound traffic",description="::/0 grants access from any IPv6 address. IPv6 rules are often overlooked while IPv4 is tightly controlled.",component_id=c.id,component_name=c.name,recommendation="Apply the same least-privilege CIDR restrictions to IPv6 rules as to IPv4.",references=["https://docs.aws.amazon.com/vpc/latest/userguide/vpc-security-groups.html"],))breakreturn findings# --------------------------------------------------------------------- IAMdef _check_iam_wildcard_resource(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.IAM):policy = str(c.properties.get("policy", ""))if '"Resource": "*"' in policy or "'Resource': '*'" in policy or "Resource: '*'" in policy:findings.append(Finding(type=FindingType.SECURITY,severity=Severity.HIGH,title=f"IAM '{c.name}' grants permissions on all resources (*)",description="Wildcard Resource (*) allows the policy to act on any AWS resource, not just the intended targets.",component_id=c.id,component_name=c.name,recommendation="Scope Resource to specific ARNs. Use conditions to add additional guardrails.",references=["https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html"],))return findingsdef _check_iam_no_mfa_required(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.IAM):mfa = str(c.properties.get("mfa_required", c.properties.get("mfa", ""))).lower()if mfa not in ("true", "yes", "1", "required", "enabled"):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.HIGH,title=f"IAM '{c.name}' does not require MFA",description="Without MFA enforcement, a stolen password alone is sufficient to access sensitive operations.",component_id=c.id,component_name=c.name,recommendation="Add a Condition with aws:MultiFactorAuthPresent: true to policies that control sensitive actions.",references=["https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa.html"],))return findingsdef _check_iam_direct_user_attach(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.IAM):attached_to = str(c.properties.get("attached_to", c.properties.get("principal_type", ""))).lower()if "user" in attached_to:findings.append(Finding(type=FindingType.SECURITY,severity=Severity.LOW,title=f"IAM policy '{c.name}' is attached directly to a user",description="Attaching policies directly to users instead of roles/groups makes access reviews and revocation harder.",component_id=c.id,component_name=c.name,recommendation="Attach policies to IAM groups or roles, then assign users to groups.",references=["https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#use-groups-for-permissions"],))return findings# ----------------------------------------------------------------- Computedef _check_compute_public_ip(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.COMPUTE):public_ip = str(c.properties.get("associate_public_ip_address", c.properties.get("public_ip", "false"))).lower()if public_ip in ("true", "yes", "1"):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.MEDIUM,title=f"Compute '{c.name}' has a public IP address directly assigned",description="A directly attached public IP exposes the instance to the internet without the protection of a load balancer or NAT.",component_id=c.id,component_name=c.name,recommendation="Place instances in private subnets. Use a load balancer for inbound and a NAT gateway for outbound traffic.",references=["https://docs.aws.amazon.com/vpc/latest/userguide/vpc-ip-addressing.html"],))return findingsdef _check_compute_no_ebs_encryption(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.COMPUTE):ebs_opts = c.properties.get("ebs_block_device", c.properties.get("root_block_device", {}))if isinstance(ebs_opts, dict):encrypted = str(ebs_opts.get("encrypted", "false")).lower()else:encrypted = str(c.properties.get("ebs_encrypted", "false")).lower()if encrypted not in ("true", "yes", "1"):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.HIGH,title=f"Compute '{c.name}' has unencrypted EBS volumes",description="Unencrypted EBS volumes expose data if a snapshot is shared, exported, or the volume is detached and moved.",component_id=c.id,component_name=c.name,recommendation="Enable EBS encryption by default in the account, or set encrypted = true on each block device.",references=["https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html"],))return findings# --------------------------------------------------------------- Containerdef _check_container_privileged(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.CONTAINER):privileged = str(c.properties.get("privileged", "false")).lower()if privileged in ("true", "yes", "1"):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.CRITICAL,title=f"Container '{c.name}' runs in privileged mode",description="Privileged containers have full access to the host kernel — a container escape becomes a full host compromise.",component_id=c.id,component_name=c.name,recommendation="Remove privileged: true. Use specific Linux capabilities (cap_add) instead of full privilege.",references=["https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities"],))return findingsdef _check_container_root_user(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.CONTAINER):user = str(c.properties.get("user", c.properties.get("run_as_user", "0"))).strip()if user in ("0", "root", ""):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.HIGH,title=f"Container '{c.name}' runs as root",description="Running as root inside a container increases the impact of a container breakout or process exploit.",component_id=c.id,component_name=c.name,recommendation="Set a non-root USER in the Dockerfile, or use run_as_user / run_as_non_root in the pod spec.",references=["https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#user"],))return findingsdef _check_container_no_resource_limits(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.CONTAINER):cpu = c.properties.get("cpu_limit", c.properties.get("cpu", ""))memory = c.properties.get("memory_limit", c.properties.get("memory", ""))if not cpu or not memory:findings.append(Finding(type=FindingType.SECURITY,severity=Severity.MEDIUM,title=f"Container '{c.name}' has no CPU/memory limits",description="Without resource limits, a compromised or buggy container can exhaust host resources and cause a denial-of-service.",component_id=c.id,component_name=c.name,recommendation="Set explicit cpu_limit and memory_limit on all containers.",references=["https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/"],))return findingsdef _check_container_no_image_scanning(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.CONTAINER):scan = str(c.properties.get("image_scanning_enabled", c.properties.get("scan_on_push", "false"))).lower()if scan not in ("true", "yes", "1", "enabled"):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.MEDIUM,title=f"Container '{c.name}' has no image vulnerability scanning",description="Images without scanning may ship known CVEs into production undetected.",component_id=c.id,component_name=c.name,recommendation="Enable scan_on_push in ECR (or equivalent registry). Fail CI pipelines on critical CVEs.",references=["https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-scanning.html"],))return findings# --------------------------------------------------------------- Serverlessdef _check_serverless_no_dead_letter(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.SERVERLESS):dlq = str(c.properties.get("dead_letter_config", c.properties.get("dlq", ""))).lower()if dlq in ("", "none", "false", "{}"):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.MEDIUM,title=f"Serverless function '{c.name}' has no dead-letter queue",description="Failed async invocations are silently dropped without a DLQ, hiding processing errors and potential data loss.",component_id=c.id,component_name=c.name,recommendation="Configure a dead_letter_config pointing to an SQS queue or SNS topic, and alert on DLQ depth.",references=["https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#invocation-dlq"],))return findingsdef _check_serverless_no_vpc(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.SERVERLESS):vpc = str(c.properties.get("vpc_config", c.properties.get("vpc_id", ""))).strip()if vpc in ("", "none", "{}", "null"):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.LOW,title=f"Serverless function '{c.name}' runs outside a VPC",description="Functions outside a VPC access downstream services over the public internet, bypassing private network controls.",component_id=c.id,component_name=c.name,recommendation="Attach the function to a VPC with private subnets if it needs to reach databases or internal services.",references=["https://docs.aws.amazon.com/lambda/latest/dg/configuration-vpc.html"],))return findings# ------------------------------------------------------------------- Cachedef _check_cache_no_auth(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.CACHE):auth = str(c.properties.get("auth_token", c.properties.get("authentication", ""))).strip()if auth in ("", "none", "false"):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.HIGH,title=f"Cache '{c.name}' has no authentication configured",description="An unauthenticated cache (Redis/Memcached) can be read and written by any process that can reach it on the network.",component_id=c.id,component_name=c.name,recommendation="Enable AUTH tokens for Redis, or use VPC security groups and IAM auth as a minimum control.",references=["https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/auth.html"],))return findingsdef _check_cache_not_encrypted(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.CACHE):at_rest = str(c.properties.get("at_rest_encryption_enabled", "false")).lower()in_transit = str(c.properties.get("transit_encryption_enabled", "false")).lower()if at_rest not in ("true", "yes", "1") or in_transit not in ("true", "yes", "1"):which = []if at_rest not in ("true", "yes", "1"):which.append("at rest")if in_transit not in ("true", "yes", "1"):which.append("in transit")findings.append(Finding(type=FindingType.SECURITY,severity=Severity.HIGH,title=f"Cache '{c.name}' is not encrypted ({' and '.join(which)})",description=f"Unencrypted cache data ({', '.join(which)}) is readable by anyone with network access to the node.",component_id=c.id,component_name=c.name,recommendation="Enable at_rest_encryption_enabled and transit_encryption_enabled on all ElastiCache clusters.",references=["https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/encryption.html"],))return findings# ------------------------------------------------------------------- Queuedef _check_queue_no_encryption(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.QUEUE):kms = str(c.properties.get("kms_master_key_id", c.properties.get("encryption", ""))).strip()if kms in ("", "none", "false"):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.MEDIUM,title=f"Queue '{c.name}' messages are not encrypted at rest",description="Unencrypted SQS/SNS messages can be read by anyone with access to the underlying storage.",component_id=c.id,component_name=c.name,recommendation="Set kms_master_key_id to a KMS key (or use alias/aws/sqs for the AWS-managed key).",references=["https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html"],))return findingsdef _check_queue_no_dlq(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.QUEUE):dlq = str(c.properties.get("redrive_policy", c.properties.get("dlq", ""))).strip()if dlq in ("", "none", "false", "{}"):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.MEDIUM,title=f"Queue '{c.name}' has no dead-letter queue (redrive policy)",description="Messages that fail processing repeatedly are deleted without a DLQ, causing silent data loss.",component_id=c.id,component_name=c.name,recommendation="Configure a redrive_policy with a DLQ and set maxReceiveCount to a low value (e.g. 3–5).",references=["https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html"],))return findings# --------------------------------------------------------------------- CDNdef _check_cdn_no_https_only(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.CDN):protocol = str(c.properties.get("viewer_protocol_policy", c.properties.get("https_only", ""))).lower()if protocol not in ("redirect-to-https", "https-only", "true", "yes", "1"):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.HIGH,title=f"CDN '{c.name}' allows plain HTTP traffic",description="Allowing HTTP exposes users to MITM attacks and cookie/credential theft over unencrypted connections.",component_id=c.id,component_name=c.name,recommendation="Set viewer_protocol_policy = 'redirect-to-https' or 'https-only' on all CloudFront behaviors.",references=["https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-https.html"],))return findingsdef _check_cdn_outdated_tls(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.CDN):tls_policy = str(c.properties.get("minimum_protocol_version", c.properties.get("ssl_policy", ""))).lower()outdated = {"tlsv1", "tlsv1_2016", "tlsv1.1_2016", "tlsv1_2018", "tls 1.0", "tls 1.1"}if tls_policy and tls_policy in outdated:findings.append(Finding(type=FindingType.SECURITY,severity=Severity.MEDIUM,title=f"CDN '{c.name}' allows outdated TLS versions",description=f"TLS policy '{tls_policy}' permits TLS 1.0/1.1, which have known vulnerabilities (BEAST, POODLE).",component_id=c.id,component_name=c.name,recommendation="Set minimum_protocol_version to TLSv1.2_2021 or newer on all CloudFront distributions.",references=["https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/secure-connections-supported-viewer-protocols-ciphers.html"],))return findings# ----------------------------------------------------------------- Gatewaydef _check_gateway_no_throttling(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.GATEWAY):throttle = str(c.properties.get("throttling_rate_limit", c.properties.get("rate_limit", ""))).strip()if throttle in ("", "0", "none", "-1"):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.MEDIUM,title=f"API Gateway '{c.name}' has no throttling / rate limits",description="Without throttling, the API is vulnerable to abuse, credential stuffing, and volumetric DoS attacks.",component_id=c.id,component_name=c.name,recommendation="Set throttling_rate_limit and throttling_burst_limit on the stage, and use a usage plan for API key clients.",references=["https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-request-throttling.html"],))return findingsdef _check_gateway_no_logging(self, model: ArchitectureModel) -> list[Finding]:findings = []for c in model.components_by_type(ComponentType.GATEWAY):logging_val = str(c.properties.get("access_log_settings", c.properties.get("logging", ""))).lower()if logging_val in ("", "none", "false", "disabled", "{}"):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.MEDIUM,title=f"API Gateway '{c.name}' has no access logging configured",description="Without access logs, malicious API calls, error spikes, and data exfiltration attempts go undetected.",component_id=c.id,component_name=c.name,recommendation="Enable access_log_settings with a CloudWatch log group ARN, and enable execution logging at the stage level.",references=["https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-logging.html"],))return findings# ----------------------------------------------------------- Cross-cuttingdef _check_hardcoded_credentials(self, model: ArchitectureModel) -> list[Finding]:findings = []sensitive_keys = {"password", "secret", "token", "api_key", "apikey","access_key", "secret_key", "private_key", "credentials","db_password", "database_password",}for c in model.components:for key, value in c.properties.items():if key.lower() in sensitive_keys and isinstance(value, str) and value and value.lower() not in ("true", "false", "", "null", "none", "var.", "${", "arn:", "ssm:", "secretsmanager:") and not value.startswith(("${", "var.", "data.", "arn:", "ssm:", "/aws/")):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.CRITICAL,title=f"Possible hardcoded credential in '{c.name}' (key: {key})",description=f"The property '{key}' appears to contain a literal secret rather than a reference to a secrets manager.",component_id=c.id,component_name=c.name,recommendation="Replace hardcoded values with references to AWS Secrets Manager, SSM Parameter Store, or Vault.",references=["https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html"],))breakreturn findingsdef _check_encryption_in_transit(self, model: ArchitectureModel) -> list[Finding]:findings = []check_types = {ComponentType.DATABASE, ComponentType.CACHE, ComponentType.QUEUE}for c in model.components:if c.type not in check_types:continuetls = str(c.properties.get("transit_encryption_enabled",c.properties.get("ssl_enabled",c.properties.get("require_ssl", "false")))).lower()if tls not in ("true", "yes", "1", "enabled", "required"):findings.append(Finding(type=FindingType.SECURITY,severity=Severity.HIGH,title=f"'{c.name}' does not enforce encryption in transit",description="Data flowing to/from this service without TLS can be intercepted in a VPC by a compromised workload.",component_id=c.id,component_name=c.name,recommendation="Enable transit_encryption_enabled / require_ssl on all data-tier services.",references=["https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL.html"],))return findings
6 unmodified lines7891011121 unmodified line141516171819206 unmodified linesfrom .parsers.registry import detect_parserfrom .analyzers.security import SecurityAnalyzerfrom .analyzers.cost import CostAnalyzerdef run_analysis(source: str, format_hint: str | None = None) -> AnalysisReport:1 unmodified linemodel = parser.parse(source)findings: list[Finding] = []for analyzer in [SecurityAnalyzer(), CostAnalyzer()]:findings.extend(analyzer.analyze(model))return AnalysisReport(architecture_name=model.name, findings=findings)6 unmodified lines789101112131 unmodified line151617181920216 unmodified linesfrom .parsers.registry import detect_parserfrom .analyzers.security import SecurityAnalyzerfrom .analyzers.cost import CostAnalyzerfrom .analyzers.kubernetes_security import KubernetesSecurityAnalyzerdef run_analysis(source: str, format_hint: str | None = None) -> AnalysisReport:1 unmodified linemodel = parser.parse(source)findings: list[Finding] = []for analyzer in [SecurityAnalyzer(), KubernetesSecurityAnalyzer(), CostAnalyzer()]:findings.extend(analyzer.analyze(model))return AnalysisReport(architecture_name=model.name, findings=findings)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261"""Kubernetes YAML parser — reads K8s manifests and builds an ArchitectureModel."""
from __future__ import annotationsfrom pathlib import Pathfrom typing import Any
from .base import BaseParserfrom ..models.architecture import ArchitectureModel, Component, ComponentType, Connection
try: import yaml _YAML_AVAILABLE = Trueexcept ImportError: _YAML_AVAILABLE = False
_KIND_TO_COMPONENT_TYPE: dict[str, ComponentType] = { "Pod": ComponentType.CONTAINER, "Deployment": ComponentType.CONTAINER, "StatefulSet": ComponentType.CONTAINER, "DaemonSet": ComponentType.CONTAINER, "ReplicaSet": ComponentType.CONTAINER, "Job": ComponentType.CONTAINER, "CronJob": ComponentType.CONTAINER, "Service": ComponentType.NETWORK, "Ingress": ComponentType.GATEWAY, "NetworkPolicy": ComponentType.NETWORK, "ServiceAccount": ComponentType.IAM, "Role": ComponentType.IAM, "ClusterRole": ComponentType.IAM, "RoleBinding": ComponentType.IAM, "ClusterRoleBinding": ComponentType.IAM, "PersistentVolume": ComponentType.STORAGE, "PersistentVolumeClaim": ComponentType.STORAGE, "ConfigMap": ComponentType.OTHER, "Secret": ComponentType.OTHER, "Namespace": ComponentType.OTHER, "HorizontalPodAutoscaler": ComponentType.COMPUTE,}
_WORKLOAD_KINDS = {"Pod", "Deployment", "StatefulSet", "DaemonSet", "ReplicaSet", "Job", "CronJob"}
class KubernetesParser(BaseParser): def can_parse(self, source: str | Path) -> bool: if not _YAML_AVAILABLE: return False p = Path(source) if p.is_dir(): return any(p.rglob("*.yaml")) or any(p.rglob("*.yml")) if p.suffix in {".yaml", ".yml"} and p.exists(): try: content = p.read_text(encoding="utf-8") return "apiVersion:" in content and "kind:" in content except Exception: return False return False
def parse(self, source: str | Path) -> ArchitectureModel: if not _YAML_AVAILABLE: raise ImportError("Install PyYAML: pip install pyyaml") p = Path(source) model = ArchitectureModel(name=p.name, source="kubernetes")
yaml_files = list(p.rglob("*.yaml")) + list(p.rglob("*.yml")) if p.is_dir() else [p] for yf in yaml_files: try: content = yf.read_text(encoding="utf-8") for doc in yaml.safe_load_all(content): if doc and isinstance(doc, dict): component = self._parse_resource(doc) if component: model.components.append(component) except Exception: continue return model
def _parse_resource(self, doc: dict) -> Component | None: kind = doc.get("kind", "") if not kind: return None component_type = _KIND_TO_COMPONENT_TYPE.get(kind, ComponentType.OTHER) metadata = doc.get("metadata", {}) or {} name = metadata.get("name", "unknown") namespace = metadata.get("namespace", "default")
props: dict[str, Any] = {"k8s_kind": kind, "k8s_namespace": namespace}
if kind in _WORKLOAD_KINDS: self._extract_workload_props(doc, kind, props) elif kind == "Service": self._extract_service_props(doc, props) elif kind == "Ingress": self._extract_ingress_props(doc, props) elif kind in ("Role", "ClusterRole"): self._extract_role_props(doc, props) elif kind in ("RoleBinding", "ClusterRoleBinding"): self._extract_binding_props(doc, props) elif kind == "NetworkPolicy": self._extract_netpol_props(doc, props) elif kind == "ServiceAccount": self._extract_sa_props(doc, props) elif kind == "ConfigMap": self._extract_configmap_props(doc, props) elif kind == "Secret": self._extract_secret_props(doc, props) elif kind == "PersistentVolume": self._extract_pv_props(doc, props)
return Component( id=f"k8s.{kind.lower()}.{namespace}.{name}", name=name, type=component_type, provider="kubernetes", service=kind.lower(), properties=props, tags=dict(metadata.get("labels") or {}), )
def _extract_workload_props(self, doc: dict, kind: str, props: dict) -> None: if kind == "CronJob": spec = (doc.get("spec") or {}).get("jobTemplate", {}).get("spec", {}).get("template", {}).get("spec", {}) elif kind == "Pod": spec = doc.get("spec") or {} else: spec = (doc.get("spec") or {}).get("template", {}).get("spec", {})
spec = spec or {} props["k8s_host_network"] = spec.get("hostNetwork", False) props["k8s_host_pid"] = spec.get("hostPID", False) props["k8s_host_ipc"] = spec.get("hostIPC", False) props["k8s_automount_sa_token"] = spec.get("automountServiceAccountToken", True) props["k8s_service_account"] = spec.get("serviceAccountName", "default")
volumes = spec.get("volumes") or [] props["k8s_host_path_volumes"] = any("hostPath" in (v or {}) for v in volumes)
pod_sc = spec.get("securityContext") or {} props["k8s_run_as_non_root"] = pod_sc.get("runAsNonRoot", False) props["k8s_run_as_user"] = pod_sc.get("runAsUser", None) props["k8s_seccomp_profile"] = (pod_sc.get("seccompProfile") or {}).get("type", "") props["k8s_sysctls"] = pod_sc.get("sysctls", [])
containers = list(spec.get("containers") or []) + list(spec.get("initContainers") or [])
has_limits = True has_requests = True has_liveness = True has_readiness = True images: list[str] = [] worst_privileged = False worst_allow_priv_esc = False worst_readonly_rootfs = True all_caps_add: list[str] = [] any_missing_sc = False any_drops_all = False
for container in containers: container = container or {} images.append(container.get("image", ""))
resources = container.get("resources") or {} if not resources.get("limits"): has_limits = False if not resources.get("requests"): has_requests = False
if not container.get("livenessProbe"): has_liveness = False if not container.get("readinessProbe"): has_readiness = False
sc = container.get("securityContext") if sc is None: any_missing_sc = True sc = {}
if sc.get("privileged", False): worst_privileged = True if sc.get("allowPrivilegeEscalation", True): worst_allow_priv_esc = True if not sc.get("readOnlyRootFilesystem", False): worst_readonly_rootfs = False
caps = sc.get("capabilities") or {} added = caps.get("add") or [] dropped = caps.get("drop") or [] all_caps_add.extend(added) if "ALL" in [d.upper() for d in dropped]: any_drops_all = True
props["k8s_has_resource_limits"] = has_limits props["k8s_has_resource_requests"] = has_requests props["k8s_has_liveness_probe"] = has_liveness props["k8s_has_readiness_probe"] = has_readiness props["k8s_images"] = images props["k8s_privileged"] = worst_privileged props["k8s_allow_privilege_escalation"] = worst_allow_priv_esc props["k8s_readonly_root_filesystem"] = worst_readonly_rootfs props["k8s_capabilities_add"] = all_caps_add props["k8s_drops_all_caps"] = any_drops_all props["k8s_has_security_context"] = not any_missing_sc props["k8s_container_count"] = len(containers)
def _extract_service_props(self, doc: dict, props: dict) -> None: spec = doc.get("spec") or {} props["k8s_service_type"] = spec.get("type", "ClusterIP") props["k8s_node_port"] = spec.get("nodePort")
def _extract_ingress_props(self, doc: dict, props: dict) -> None: spec = doc.get("spec") or {} annotations = (doc.get("metadata") or {}).get("annotations") or {} props["k8s_has_tls"] = bool(spec.get("tls")) props["k8s_ingress_class"] = ( annotations.get("kubernetes.io/ingress.class", "") or spec.get("ingressClassName", "") ) props["k8s_has_default_backend"] = bool(spec.get("defaultBackend"))
def _extract_role_props(self, doc: dict, props: dict) -> None: rules = doc.get("rules") or [] props["k8s_wildcard_verbs"] = any("*" in (r.get("verbs") or []) for r in rules) props["k8s_wildcard_resources"] = any("*" in (r.get("resources") or []) for r in rules) props["k8s_wildcard_api_groups"] = any("*" in (r.get("apiGroups") or []) for r in rules) props["k8s_accesses_secrets"] = any("secrets" in (r.get("resources") or []) for r in rules)
def _extract_binding_props(self, doc: dict, props: dict) -> None: role_ref = doc.get("roleRef") or {} props["k8s_role_ref"] = role_ref.get("name", "") props["k8s_is_cluster_admin"] = role_ref.get("name") == "cluster-admin" subjects = doc.get("subjects") or [] props["k8s_binds_default_sa"] = any( (s or {}).get("name") == "default" and (s or {}).get("kind") == "ServiceAccount" for s in subjects ) props["k8s_binds_all_sa"] = any((s or {}).get("kind") == "Group" and (s or {}).get("name") == "system:serviceaccounts" for s in subjects)
def _extract_netpol_props(self, doc: dict, props: dict) -> None: spec = doc.get("spec") or {} props["k8s_policy_types"] = spec.get("policyTypes", []) props["k8s_netpol_allows_all_ingress"] = not bool(spec.get("ingress")) props["k8s_netpol_allows_all_egress"] = not bool(spec.get("egress")) props["k8s_netpol_empty_pod_selector"] = not bool(spec.get("podSelector"))
def _extract_sa_props(self, doc: dict, props: dict) -> None: props["k8s_automount_sa_token"] = doc.get("automountServiceAccountToken", True)
def _extract_configmap_props(self, doc: dict, props: dict) -> None: data = doc.get("data") or {} props["k8s_configmap_keys"] = list(data.keys()) props["k8s_configmap_data"] = data
def _extract_secret_props(self, doc: dict, props: dict) -> None: props["k8s_secret_type"] = doc.get("type", "Opaque") props["k8s_secret_keys"] = list((doc.get("data") or {}).keys())
def _extract_pv_props(self, doc: dict, props: dict) -> None: spec = doc.get("spec") or {} props["k8s_pv_access_modes"] = spec.get("accessModes", []) props["k8s_pv_host_path"] = "hostPath" in spec props["k8s_pv_reclaim_policy"] = spec.get("persistentVolumeReclaimPolicy", "Delete")9 unmodified lines10111213141516171819206 unmodified lines2728293031329 unmodified linesfrom .cloudformation import CloudFormationParserfrom .aws_config import AWSConfigParserfrom .gcp_asset import GCPAssetParser# Order matters: more specific parsers first, text (LLM) last as fallback_PARSERS: list[BaseParser] = [TerraformParser(),DrawioParser(),CloudFormationParser(),AWSConfigParser(),6 unmodified linesif format_hint:mapping = {"terraform": TerraformParser(),"drawio": DrawioParser(),"cloudformation": CloudFormationParser(),"aws_config": AWSConfigParser(),9 unmodified lines101112131415161718192021226 unmodified lines29303132333435369 unmodified linesfrom .cloudformation import CloudFormationParserfrom .aws_config import AWSConfigParserfrom .gcp_asset import GCPAssetParserfrom .kubernetes import KubernetesParser# Order matters: more specific parsers first, text (LLM) last as fallback_PARSERS: list[BaseParser] = [TerraformParser(),KubernetesParser(),DrawioParser(),CloudFormationParser(),AWSConfigParser(),6 unmodified linesif format_hint:mapping = {"terraform": TerraformParser(),"kubernetes": KubernetesParser(),"k8s": KubernetesParser(),"drawio": DrawioParser(),"cloudformation": CloudFormationParser(),"aws_config": AWSConfigParser(),
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071apiVersion: apps/v1kind: Deploymentmetadata: name: api-server namespace: defaultspec: template: spec: hostNetwork: true serviceAccountName: default automountServiceAccountToken: true containers: - name: api image: myapp:latest securityContext: privileged: true allowPrivilegeEscalation: true capabilities: add: ["NET_ADMIN", "SYS_ADMIN"]---apiVersion: v1kind: Servicemetadata: name: api-svc namespace: defaultspec: type: NodePort---apiVersion: networking.k8s.io/v1kind: Ingressmetadata: name: api-ingress namespace: defaultspec: rules: - host: api.example.com---apiVersion: rbac.authorization.k8s.io/v1kind: ClusterRoleBindingmetadata: name: admin-binding namespace: defaultroleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-adminsubjects: - kind: ServiceAccount name: default---apiVersion: v1kind: ConfigMapmetadata: name: app-config namespace: defaultdata: database_password: "s3cr3t123" api_key: "abcdef123456" app_port: "8080"---apiVersion: v1kind: PersistentVolumemetadata: name: data-pv namespace: defaultspec: hostPath: path: /data accessModes: - ReadWriteOnce persistentVolumeReclaimPolicy: Delete