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

# OCI OKE Should Minimize Containers Sharing the Host Network Namespace

### More Info:

hostNetwork=true gives a pod direct access to node interfaces, bypassing NetworkPolicy and potentially exposing kubelet, kube-proxy, and other host services. Restrict this to system add-ons that genuinely require it.

### Risk Level

High

### Address

Compliance, Security

### Compliance Standards

* CIS OKE

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate “OCI OKE should minimize containers sharing the host network namespace” using the OCI Console, you need to:

        1. **Identify workloads using `hostNetwork`**

        1) Sign in to the **OCI Console**.
        2) In the left menu, go to **Developer Services → Containers & Artifacts → Kubernetes Clusters (OKE)**.
        3) Click your **cluster**.
        4) In the cluster detail page, click **Workloads**.
        5) For each **Deployment / StatefulSet / DaemonSet / Pod**:
           * Open the workload.
           * Click **YAML** (or **Edit YAML** / **View YAML**, depending on the console version).
           * Look for:
             ```yaml theme={null}
             spec:
               hostNetwork: true
             ```
           * Also check container `ports` for `hostPort` values (often appear with hostNetwork).

        Any workload with `hostNetwork: true` is sharing the host network namespace.

        ***

        2. **Edit workloads to stop using the host network**

        For each offending workload you found:

        1. In **Workloads**, click the workload (e.g., a Deployment).
        2. Click **Edit YAML**.
        3. In the pod spec, change or remove:
           ```yaml theme={null}
           spec:
             hostNetwork: true
           ```
           to either:
           ```yaml theme={null}
           spec:
             hostNetwork: false
           ```
           or remove the `hostNetwork` line entirely (default is `false`).
        4. If possible, also remove any `hostPort` mappings under containers:
           ```yaml theme={null}
           containers:
           - name: <container-name>
             ports:
             - containerPort: 8080
               hostPort: 8080      # remove this if not strictly required
           ```
        5. Click **Save** / **Update** to apply the changes.
        6. The Deployment/StatefulSet/DaemonSet will roll out new pods without `hostNetwork`.

        Repeat for all workloads using `hostNetwork: true`.

        ***

        3. **(Optional but recommended) Enforce a policy to prevent future use**

        OKE does not yet provide a native “checkbox” to forbid `hostNetwork`, but you can enforce via Kubernetes policy tools (e.g., Gatekeeper/OPA) deployed to your cluster. From the OCI Console you:

        1. Go to your **OKE cluster** → **Access Cluster** → use the **Cloud Shell** or local `kubectl`.
        2. Deploy an admission policy that denies pods with `spec.hostNetwork: true`.

        Example Gatekeeper `ConstraintTemplate` and `Constraint` would enforce this at cluster level. (This is done via `kubectl apply` rather than GUI, but initiated from the Console via Cloud Shell.)

        ***

        4. **Verify remediation**

        1) In the **Workloads** view, re-open the YAML for each previously offending workload.
        2) Confirm:
           * `hostNetwork` is not present, or explicitly set to `false`.
           * `hostPort` is removed where not necessary.
        3) Optionally, use:
           * **Cloud Guard** (if enabled) → check your target/recipe to ensure the detector for host network sharing is now green/not triggering for the cluster.

        This removes container sharing of the host network namespace for your OKE workloads via changes made through the OCI Console.
      </Accordion>

      <Accordion title="Using CLI">
        In OKE this setting is controlled in the **Pod spec** (`hostNetwork: true`), so the remediation is to update workloads so they no longer request the host network. OCI CLI is only for cluster/infra management, so you use it to get kubeconfig, then use `kubectl` against the cluster.

        ### 1. Get kubeconfig for the OKE cluster using OCI CLI

        ```bash theme={null}
        # Replace these with your values
        COMPARTMENT_OCID="<compartment_ocid>"
        CLUSTER_OCID="<cluster_ocid>"
        KUBECONFIG_PATH="$HOME/.kube/config-oke"

        oci ce cluster create-kubeconfig \
          --cluster-id "$CLUSTER_OCID" \
          --file "$KUBECONFIG_PATH" \
          --region "<region-identifier>" \
          --token-version 2.0.0 \
          --kube-endpoint PUBLIC_ENDPOINT

        export KUBECONFIG="$KUBECONFIG_PATH"
        ```

        ### 2. Find Pods using `hostNetwork: true`

        ```bash theme={null}
        kubectl get pods -A -o jsonpath='{range .items[?(@.spec.hostNetwork==true)]}{.metadata.namespace}{"\t"}{.metadata.name}{"\n"}{end}'
        ```

        If you want to find the owning controllers (Deployments/DaemonSets/StatefulSets):

        ```bash theme={null}
        kubectl get pods -A -o json | jq -r '
          .items[]
          | select(.spec.hostNetwork == true)
          | "\(.metadata.namespace)\t\(.metadata.name)\t\(.metadata.ownerReferences[0].kind)\t\(.metadata.ownerReferences[0].name)"'
        ```

        ### 3. Update the owning resources to stop using host networking

        For each Deployment/DaemonSet/StatefulSet that uses `hostNetwork: true`, remove or set it to `false`.

        Example – patch a Deployment:

        ```bash theme={null}
        NAMESPACE="<ns>"
        DEPLOYMENT_NAME="<deploy-name>"

        kubectl -n "$NAMESPACE" patch deployment "$DEPLOYMENT_NAME" \
          --type='json' \
          -p='[
            {"op":"remove","path":"/spec/template/spec/hostNetwork"}
          ]'
        ```

        If the field must exist and be explicit:

        ```bash theme={null}
        kubectl -n "$NAMESPACE" patch deployment "$DEPLOYMENT_NAME" \
          --type='merge' \
          -p='{"spec":{"template":{"spec":{"hostNetwork":false}}}}'
        ```

        Repeat similarly for DaemonSets/StatefulSets, changing the resource kind:

        ```bash theme={null}
        kubectl -n "$NAMESPACE" patch daemonset "$DAEMONSET_NAME" ...
        kubectl -n "$NAMESPACE" patch statefulset "$STS_NAME" ...
        ```

        Note: If containers were binding to host ports (`hostPort`), you must reconfigure them to use ClusterIP/NodePort/LoadBalancer Services instead.

        ### 4. (Optional) Enforce policy so new Pods can’t use hostNetwork

        You can use Admission Control / Pod Security Standards (if enabled in your OKE version) or a policy engine like Gatekeeper. A simple starting point is to apply a `PodSecurity` admission config or a Gatekeeper constraint that denies Pods with `spec.hostNetwork: true`. That’s done with `kubectl apply -f <policy.yaml>` after preparing the policy YAML; OCI CLI itself does not control that per‑Pod setting.
      </Accordion>

      <Accordion title="Using Python">
        In OKE this is a standard Kubernetes setting: containers use the host network when the Pod spec has `hostNetwork: true`. To “minimize” it, you must:

        1. Find workloads using `hostNetwork: true`.
        2. Update their specs to `hostNetwork: false` (or remove the field).
        3. Optionally enforce a policy so it can’t be reintroduced.

        Below is how to do this programmatically in Python using the Kubernetes Python client against your OKE cluster.

        ***

        ### 1. Prerequisites

        ```bash theme={null}
        pip install kubernetes
        ```

        Make sure your kubeconfig for the OKE cluster is set (e.g. created via OCI CLI) and that `kubectl get pods` works.

        ***

        ### 2. Python: Detect Pods Using `hostNetwork: true`

        This script lists all pods in all namespaces that have `hostNetwork` enabled:

        ```python theme={null}
        from kubernetes import client, config

        def main():
            # Load kubeconfig (for OKE cluster)
            config.load_kube_config()  # or config.load_incluster_config() if running inside cluster

            v1 = client.CoreV1Api()

            pods = v1.list_pod_for_all_namespaces(watch=False)
            print("Pods using hostNetwork:")
            for pod in pods.items:
                if pod.spec.host_network:
                    print(f"{pod.metadata.namespace}/{pod.metadata.name}")

        if __name__ == "__main__":
            main()
        ```

        ***

        ### 3. Python: Identify Higher-Level Controllers Using `hostNetwork`

        Usually you don’t patch pods directly; you patch Deployments/DaemonSets/StatefulSets/Jobs that create them.

        Example to scan Deployments and DaemonSets:

        ```python theme={null}
        from kubernetes import client, config

        def main():
            config.load_kube_config()
            apps_v1 = client.AppsV1Api()

            print("Deployments using hostNetwork:")
            deps = apps_v1.list_deployment_for_all_namespaces()
            for d in deps.items:
                if d.spec.template.spec.host_network:
                    print(f"Deployment: {d.metadata.namespace}/{d.metadata.name}")

            print("\nDaemonSets using hostNetwork:")
            dss = apps_v1.list_daemon_set_for_all_namespaces()
            for ds in dss.items:
                if ds.spec.template.spec.host_network:
                    print(f"DaemonSet: {ds.metadata.namespace}/{ds.metadata.name}")

        if __name__ == "__main__":
            main()
        ```

        ***

        ### 4. Python: Patch Workloads to Disable `hostNetwork`

        This will set `hostNetwork: false` for Deployments and DaemonSets that currently use it.

        ```python theme={null}
        from kubernetes import client, config

        def disable_host_network_deployments():
            config.load_kube_config()
            apps_v1 = client.AppsV1Api()

            deps = apps_v1.list_deployment_for_all_namespaces()
            for d in deps.items:
                if d.spec.template.spec.host_network:
                    ns = d.metadata.namespace
                    name = d.metadata.name
                    print(f"Patching Deployment {ns}/{name}: hostNetwork -> false")

                    patch_body = {
                        "spec": {
                            "template": {
                                "spec": {
                                    "hostNetwork": False
                                }
                            }
                        }
                    }

                    apps_v1.patch_namespaced_deployment(
                        name=name,
                        namespace=ns,
                        body=patch_body
                    )

        def disable_host_network_daemonsets():
            config.load_kube_config()
            apps_v1 = client.AppsV1Api()

            dss = apps_v1.list_daemon_set_for_all_namespaces()
            for ds in dss.items:
                if ds.spec.template.spec.host_network:
                    ns = ds.metadata.namespace
                    name = ds.metadata.name
                    print(f"Patching DaemonSet {ns}/{name}: hostNetwork -> false")

                    patch_body = {
                        "spec": {
                            "template": {
                                "spec": {
                                    "hostNetwork": False
                                }
                            }
                        }
                    }

                    apps_v1.patch_namespaced_daemon_set(
                        name=name,
                        namespace=ns,
                        body=patch_body
                    )

        if __name__ == "__main__":
            disable_host_network_deployments()
            disable_host_network_daemonsets()
        ```

        Notes:

        * This will trigger rolling updates; pods will be recreated without host networking.
        * Only run this on workloads where host networking is not required (e.g., not node-level agents).

        ***

        ### 5. Optional: Enforce No `hostNetwork` via Admission Control (Python + OPA Gatekeeper)

        In OKE you can deploy OPA Gatekeeper or Kyverno. With Gatekeeper, you would:

        1. Install Gatekeeper in the OKE cluster.
        2. Apply a ConstraintTemplate that denies `hostNetwork: true`.
        3. Apply a Constraint that targets your namespaces.

        The actual Gatekeeper policy is YAML, but you can apply it via Python:

        ```python theme={null}
        from kubernetes import client, config

        GATEKEEPER_TEMPLATE = """
        apiVersion: templates.gatekeeper.sh/v1beta1
        kind: ConstraintTemplate
        metadata:
          name: k8snohostnetwork
        spec:
          crd:
            spec:
              names:
                kind: K8sNoHostNetwork
          targets:
          - target: admission.k8s.gatekeeper.sh
            rego: |
              package k8snohostnetwork

              violation[{"msg": msg}] {
                input.review.kind.kind == "Pod"
                input.review.object.spec.hostNetwork == true
                msg := "hostNetwork must not be true"
              }
        """

        GATEKEEPER_CONSTRAINT = """
        apiVersion: constraints.gatekeeper.sh/v1beta1
        kind: K8sNoHostNetwork
        metadata:
          name: disallow-hostnetwork
        spec:
          match:
            kinds:
            - apiGroups: [""]
              kinds: ["Pod"]
            namespaces:
            - default
            - your-app-namespace
        """

        def apply_yaml(yaml_str):
            from kubernetes.utils import create_from_yaml
            config.load_kube_config()
            k8s_client = client.ApiClient()
            create_from_yaml(k8s_client, yaml_objects=[yaml_str])

        if __name__ == "__main__":
            apply_yaml(GATEKEEPER_TEMPLATE)
            apply_yaml(GATEKEEPER_CONSTRAINT)
        ```

        (Adjust namespaces and ensure Gatekeeper is already installed.)

        ***

        ### Summary

        * Use the Kubernetes Python client against your OKE cluster.
        * Enumerate and patch any workloads whose Pod templates have `hostNetwork: true`.
        * Optionally deploy an admission policy (Gatekeeper or Kyverno) to prevent future `hostNetwork` usage.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        # This finding cannot be remediated on the OKE *cluster* Terraform resource itself.
        # The `oci_containerengine_cluster` (or equivalent) resource has no argument that
        # controls whether Pods use `hostNetwork`; that setting lives only in the Pod spec.

        # To fix this with Terraform you must change the Kubernetes workload manifests
        # (or Helm values) that Terraform applies, ensuring `hostNetwork` is not set or is false.

        # Example for a Pod/Deployment managed via the Kubernetes provider:

        resource "kubernetes_deployment_v1" "APP_DEPLOYMENT" {
          metadata {
            name      = "APP_NAME"          # substitute: your app name
            namespace = "APP_NAMESPACE"     # substitute: your namespace
          }

          spec {
            replicas = 1

            selector {
              match_labels = {
                app = "APP_NAME"            # substitute: label matching the pod template
              }
            }

            template {
              metadata {
                labels = {
                  app = "APP_NAME"
                }
              }

              spec {
                # Ensure hostNetwork is NOT true (omit it, or set explicitly to false)
                host_network = false

                container {
                  name  = "APP_CONTAINER_NAME"   # substitute: your container name
                  image = "APP_IMAGE"            # substitute: your container image
                }
              }
            }
          }
        }
        ```

        The OCI OKE “cluster” resource cannot enforce `hostNetwork` usage; you must remediate by updating Kubernetes manifests (Deployments, DaemonSets, Pods, Helm charts) so `spec.hostNetwork` is not set to `true`, and then re-apply via Terraform. This change does not recreate the cluster, only the affected workloads. After changes, `terraform plan` should show updates to the specific Kubernetes workload resources where `host_network` is being changed.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
