> ## Documentation Index
> Fetch the complete documentation index at: https://cloudanix.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Ensure Network Policy Is Enabled And Set As Appropriate

### More Info:

Deploy a network policy engine such as Calico to segment and isolate pod traffic, enforcing least-privilege network communication within the cluster.

### Risk Level

High

### Address

Security

### Compliance Standards

* CIS EKS

### Triage and Remediation

<Tabs>
  <Tab title="Remediation">
    ### Remediation

    <AccordionGroup>
      <Accordion title="Manual Steps" defaultOpen="true">
        1. **Identify how networking is provisioned for the cluster**
           * On any machine with access to your cloud account, determine the CNI / network plugin and any network policy support flags:
             * EKS (AWS CLI):
               ```bash theme={null}
               aws eks describe-cluster --name my-eks-cluster --region us-east-1 --query 'cluster.resourcesVpcConfig'
               ```
               Check your provisioning/IaC (CloudFormation/Terraform) for any addons like `aws-k8s-cni`, Calico, Cilium, etc.
             * AKS (Azure CLI):
               ```bash theme={null}
               az aks show -g my-aks-rg -n my-aks-cluster --query '{networkPlugin:networkProfile.networkPlugin, networkPolicy:networkProfile.networkPolicy}'
               ```
             * GKE (gcloud):
               ```bash theme={null}
               gcloud container clusters describe my-gke-cluster --region us-central1 --format='value(networkPolicy.enabled,networkPolicy.provider)'
               ```

        2. **Verify whether a network policy–capable CNI is enabled**
           * From step 1, determine if the chosen CNI supports Kubernetes `NetworkPolicy` (e.g., Calico, Cilium, Antrea, Azure network policy, GKE network policy).
           * If your cloud provider shows `networkPolicy` disabled or a CNI that does not enforce NetworkPolicy, record this as a gap to be remediated.

        3. **Review existing NetworkPolicy usage in the cluster**
           * On any machine with kubectl access:
             ```bash theme={null}
             kubectl get networkpolicy --all-namespaces
             ```
           * If no `NetworkPolicy` objects exist, or they are only present in a few namespaces, note that most workloads are not isolated and rely on default “allow all” behavior.

        4. **Decide on and enable an appropriate network policy engine at the provider level**
           * Adjust cloud provider configuration or IaC (do not use kubectl) to enable a NetworkPolicy-capable engine, following provider guidance:
             * EKS: configure a CNI like Calico/Cilium via your chosen add-on mechanism (e.g., Helm/operator via IaC, or managed add-on if available).
             * AKS: recreate or update the cluster with `networkPlugin` and `networkPolicy` set to values that support NetworkPolicy (e.g., `azure`/`calico`), via `az aks create` / `az aks update` or IaC.
             * GKE: create/update clusters with `--enable-network-policy` (or equivalent in IaC).
           * Be aware this may require cluster recreation in some providers; plan for migration and maintenance windows.

        5. **Define and apply a baseline isolation model for all namespaces**
           * Design a policy model (e.g., default deny within each namespace, explicitly allowing required app, DNS, and ingress/egress flows).
           * Implement these policies via your existing IaC or GitOps tooling (YAML manifests committed to source control) so they are applied consistently; ensure each application namespace has at least a baseline NetworkPolicy.

        6. **Re-verify that network policy enforcement is active and effective**
           * From any machine with kubectl access:
             ```bash theme={null}
             kubectl get networkpolicy --all-namespaces
             ```
           * From your cloud provider / IaC: re-run the commands from step 1 to confirm that a network-policy-capable engine is enabled.
           * Optionally, run connectivity tests between test pods across namespaces to confirm that traffic is blocked/allowed according to your policies.
      </Accordion>

      <Accordion title="Using kubectl">
        kubectl cannot be used to enable or configure the cluster’s network policy engine because this setting is controlled at the cloud provider / managed control plane level (console, provider CLI, or IaC). Refer to the Manual Steps section for guidance on selecting and configuring a network policy engine such as Calico through your provider’s configuration surface.
      </Accordion>

      <Accordion title="Automation">
        ```bash theme={null}
        #!/usr/bin/env bash
        # Purpose:
        #   Report Kubernetes NetworkPolicy usage and CNI/network policy engines
        #   so you can review whether network segmentation is in place.
        #
        # Run on:
        #   Any machine with kubectl context to the target cluster.

        set -euo pipefail

        echo "=== Cluster-wide NetworkPolicy Inventory ==="
        echo

        # 1) List all namespaces and whether they have any NetworkPolicy objects
        echo "Per-namespace NetworkPolicy counts:"
        echo "namespace,networkpolicies"
        kubectl get ns -o jsonpath='{range .items[*]}{.metadata.name}{";"}{.metadata.name}{"\n"}{end}' \
          | while IFS=';' read -r ns _; do
              count="$(kubectl get networkpolicy -n "${ns}" --no-headers 2>/dev/null | wc -l || true)"
              # If there are no NetworkPolicy resources, wc -l prints 0 but also prints a header if present.
              # Strip spaces.
              count="$(echo "${count}" | tr -d ' ')"
              echo "${ns},${count}"
            done \
          | sort

        echo
        echo "=== Explanation ==="
        echo "Namespaces with '0' NetworkPolicy objects allow all pod-to-pod traffic by default."
        echo "These namespaces should be reviewed: consider adding default-deny policies and explicit allow rules."

        # 2) Show detail for namespaces with zero NetworkPolicies
        echo
        echo "Namespaces with NO NetworkPolicies (potentially wide-open):"
        no_np_namespaces=$(kubectl get ns -o json | jq -r '
          .items[].metadata.name as $ns
          | ($ns + " " + (
              (try (.[0].metadata.name) catch "") // ""
            ))
          ' 2>/dev/null || true)

        # Simpler: re-use output from above
        kubectl get ns -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}' \
          | while read -r ns; do
              count="$(kubectl get networkpolicy -n "${ns}" --no-headers 2>/dev/null | wc -l || true)"
              count="$(echo "${count}" | tr -d ' ')"
              if [ "${count}" = "0" ]; then
                echo " - ${ns}"
              fi
            done

        echo
        echo "For each listed namespace, verify whether unrestricted traffic is acceptable."
        echo "If not, design and apply NetworkPolicies implementing least-privilege communication."

        # 3) Check for Cilium (example network policy–capable CNI)
        echo
        echo "=== CNI / Network Policy Engine Indicators ==="
        echo "Checking for common network policy–capable CNIs (Calico, Cilium, etc.)"
        echo

        echo "- Pods in kube-system that may indicate CNI:"
        kubectl get pods -n kube-system -o wide | grep -Ei 'calico|cilium|weave|antrea|ovn|azure-cni|aws-node|amazon-vpc-cni' || \
          echo "  (No obvious CNI pods matched common names; inspect your cloud provider docs/console.)"

        echo
        echo "- Node CNI annotations (if present):"
        kubectl get nodes -o jsonpath='{range .items[*]}{.metadata.name}{"  cni: "}{.metadata.annotations.k8s\.ovn\.org/node-preferred-cidr}{"\n"}{end}' 2>/dev/null || \
          echo "  (No specific CNI-related node annotations found via this pattern.)"

        echo
        echo "=== How to interpret this report ==="
        echo "1) If no network policy–capable CNI (e.g., Calico, Cilium, Antrea) is visible here, verify via:"
        echo "   - Your cloud provider console/CLI/IaC which CNI is configured for this cluster."
        echo "   - Ensure the chosen CNI supports Kubernetes NetworkPolicy and is actually enabled."
        echo
        echo "2) If many namespaces show '0' NetworkPolicies, network segmentation is likely weak or absent."
        echo "   That is a potential problem relative to the benchmark."
        echo
        echo "3) This script does NOT change configuration."
        echo "   Use it periodically to track whether namespaces are covered by NetworkPolicies and"
        echo "   to confirm the presence of a network policy–capable CNI (e.g., Calico)."
        ```

        **Problem indicators in the output**

        * Namespaces listed with `0` NetworkPolicies: those namespaces likely allow all traffic and must be manually reviewed; add default-deny and explicit allow policies where appropriate.
        * No pods in `kube-system` matching common network-policy engines and no clear CNI indicators: verify in the cloud provider console/CLI that a NetworkPolicy-capable CNI (such as Calico) is deployed and enabled.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
