> ## 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:

Enable and configure Network Policy for the cluster to control pod-to-pod traffic and enforce network segmentation.

### Risk Level

High

### Address

Security

### Compliance Standards

* CIS OKE

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Manual Steps" defaultOpen="true">
        1. **Identify whether the cluster supports NetworkPolicy**
           * On any machine with access to your cloud provider/IaC:
             * For OKE (OCI CLI):
               ```bash theme={null}
               oci ce cluster get --cluster-id <OCID> --query "data.options.\"kubernetes-network-config\""
               ```
               Confirm the CNI/plugin in use supports Kubernetes `NetworkPolicy` (e.g., Calico, Cilium, appropriate OCI CNI mode).

        2. **List existing NetworkPolicy resources and check coverage**
           * On any machine with `kubectl` access:
             ```bash theme={null}
             kubectl get networkpolicy --all-namespaces -o wide
             ```
           * Review whether:
             * Namespaces containing sensitive workloads (e.g., prod, payments, customer-data) have at least one `NetworkPolicy`.
             * There is a strategy (e.g., default deny + explicit allows) rather than a few ad‑hoc policies.

        3. **Check for default-deny behavior per namespace**
           * On any machine with `kubectl` access:
             ```bash theme={null}
             for ns in $(kubectl get ns -o jsonpath='{.items[*].metadata.name}'); do
               echo "=== $ns ==="
               kubectl get networkpolicy -n "$ns" \
                 -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.podSelector}{"\t"}{.spec.policyTypes}{"\n"}{end}' || echo "no policies"
               echo
             done
             ```
           * For important namespaces, confirm there is at least one policy that:
             * Uses an empty `podSelector: {}` with `policyTypes` including `Ingress` and/or `Egress` to enforce default deny,
             * Or otherwise clearly restricts traffic according to your segmentation requirements.

        4. **Review cloud/IaC configuration for CNI and policy enablement**
           * In cloud console or IaC (Terraform, OCI Resource Manager templates, etc.), inspect cluster configuration:
             * Confirm the selected network plugin/CNI is the one intended and supports `NetworkPolicy`.
             * Confirm any “Network Policy” / “Network Security” options exposed by the provider are enabled where required (document the setting and where it is defined in your IaC).
           * If IaC is used, locate the cluster resource and inspect:
             * CNI type and any flags that enable/disable network policies.

        5. **Decide and define the target segmentation model**
           * Outside of the cluster, document:
             * Which namespaces are “default deny” by design.
             * Which system/infra namespaces (e.g., `kube-system`, logging, monitoring) need carefully scoped exceptions.
             * Any required cross-namespace and external dependencies (databases, APIs, ingress controllers).
           * Based on this, determine where NetworkPolicy must be tightened (namespaces with no policies or policies that are too permissive).

        6. **Implement and validate policy changes**
           * Using your cloud provider console/CLI/IaC:
             * If NetworkPolicy is not enabled at the cluster/CNI level, update the cluster configuration to an option that supports it (this may require cluster recreation or node pool changes per provider documentation).
           * Using manifests applied through your normal deployment process (IaC/CI/CD), add or update `NetworkPolicy` objects to enforce the decided model (e.g., default deny + explicit allow).
           * Validate behavior on any machine with `kubectl` access:
             ```bash theme={null}
             kubectl get networkpolicy --all-namespaces -o wide
             ```
             Optionally, run connectivity tests between pods in different namespaces to confirm policies are enforced as intended.
      </Accordion>

      <Accordion title="Using kubectl">
        kubectl cannot be used to enable or configure the cluster‑level Network Policy provider; this must be done in the cloud provider’s managed control plane configuration (console, CLI, or IaC). Refer to the Manual Steps section for guidance on what to review and how to remediate this finding at the provider/IaC level.
      </Accordion>

      <Accordion title="Automation">
        ```bash theme={null}
        #!/usr/bin/env bash
        #
        # Report Kubernetes NetworkPolicy usage and CNI support across all namespaces.
        # Run from any machine with kubectl access and cluster-admin RBAC.
        #
        # Usage:
        #   ./report-network-policy.sh > network-policy-report.txt

        set -euo pipefail

        echo "=== Cluster Network Policy Assessment ==="
        echo "Timestamp: $(date -Iseconds)"
        echo

        #############################################
        # 1. Identify CNI plugin (best-effort only) #
        #############################################

        echo "== CNI / Network plugin detection (best-effort) =="

        # Try well-known CNI indicators in kube-system
        kubectl get pods -n kube-system -o wide 2>/dev/null | \
          awk 'NR==1 || /calico|cilium|weave|flannel|antrea|ovn|kube-router|azure-cni|aws-node|amazon-k8s-cni|gke-net|azure-npm|azure-networkpolicymanager/'

        echo
        echo "# Notes:"
        echo "# - Presence of a CNI that SUPPORTS NetworkPolicy (e.g. calico, cilium, antrea, weave-net,"
        echo "#   ovn-kubernetes, kube-router, Azure NPM, GKE Network Policy, AWS VPC CNI with policy addon)"
        echo "#   is required for policies to be enforced."
        echo "# - If you only see basic CNI pods (e.g. aws-node without policy addon, azure-cni without NPM),"
        echo "#   NetworkPolicy objects may exist but will not be enforced."
        echo

        ###################################################
        # 2. Summary of NetworkPolicy objects by namespace #
        ###################################################

        echo "== NetworkPolicy presence by namespace =="

        # Header
        printf "%-30s %-10s %-10s %-10s\n" "NAMESPACE" "NP_COUNT" "HAS_PODS" "HAS_SVCS"
        echo "----------------------------------------------------------------------"

        # Build summary using a single API query per resource type
        # Namespaces
        namespaces=$(kubectl get ns -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}')

        # Pods map: namespace -> 1/0
        declare -A ns_has_pods
        while read -r ns; do
          [[ -z "$ns" ]] && continue
          count=$(kubectl get pods -n "$ns" --no-headers 2>/dev/null | wc -l | tr -d ' ')
          if [[ "$count" -gt 0 ]]; then
            ns_has_pods["$ns"]=1
          else
            ns_has_pods["$ns"]=0
          fi
        done < <(printf "%s\n" "$namespaces")

        # Services map: namespace -> 1/0
        declare -A ns_has_svcs
        while read -r ns; do
          [[ -z "$ns" ]] && continue
          count=$(kubectl get svc -n "$ns" --no-headers 2>/dev/null | wc -l | tr -d ' ')
          if [[ "$count" -gt 0 ]]; then
            ns_has_svcs["$ns"]=1
          else
            ns_has_svcs["$ns"]=0
          fi
        done < <(printf "%s\n" "$namespaces")

        # NetworkPolicies count
        declare -A ns_np_count
        while read -r line; do
          [[ -z "$line" ]] && continue
          ns=$(cut -d' ' -f1 <<<"$line")
          cnt=$(cut -d' ' -f2 <<<"$line")
          ns_np_count["$ns"]="$cnt"
        done < <(kubectl get networkpolicy --all-namespaces --no-headers 2>/dev/null | awk '{count[$1]++} END{for (n in count) print n, count[n]}')

        # Print summary
        for ns in $namespaces; do
          np_count="${ns_np_count[$ns]:-0}"
          has_pods="${ns_has_pods[$ns]:-0}"
          has_svcs="${ns_has_svcs[$ns]:-0}"
          printf "%-30s %-10s %-10s %-10s\n" "$ns" "$np_count" "$has_pods" "$has_svcs"
        done

        cat <<'EOF'

        # How to interpret:
        # - Focus on namespaces where:
        #     HAS_PODS=1 (there is workload) AND NP_COUNT=0
        #   These namespaces have no NetworkPolicy and therefore allow all pod-to-pod
        #   traffic by default (subject to CNI behavior). This is usually a problem.
        #
        # - Namespaces with HAS_PODS=0 and NP_COUNT=0 are typically not a concern.
        #
        # - System namespaces (kube-system, kube-public, kube-node-lease, etc.) may have
        #   different risk tolerance; review them explicitly.

        EOF

        ########################################################
        # 3. Detailed view of NetworkPolicies (for review)     #
        ########################################################

        echo "== Detailed NetworkPolicy listing =="

        kubectl get networkpolicy --all-namespaces -o wide 2>/dev/null || \
          echo "No NetworkPolicy objects found in the cluster."

        cat <<'EOF'

        # How to interpret:
        # - Confirm that critical namespaces (containing business apps or sensitive data)
        #   have at least one NetworkPolicy.
        # - Review each policy for:
        #     * Selectors: which pods are actually covered (podSelector/namespaceSelector).
        #     * PolicyTypes: Ingress, Egress, or both.
        #     * Default deny/allow posture (e.g., a policy with empty ingress/egress can
        #       serve as a default deny for selected pods).
        #
        # WARNING INDICATORS (potential problems):
        # - Cluster has NO NetworkPolicy objects at all.
        # - Business-critical namespaces with HAS_PODS=1 and NP_COUNT=0.
        # - CNI plugin does NOT support NetworkPolicy, but policies are defined
        #   (they will not be enforced).
        #
        # This script does NOT change any configuration; it only reports the current
        # state so you can make informed, manual decisions and then enforce via your
        # cloud provider's network policy options and/or CNI configuration.
        EOF
        ```
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
