← Policy catalog
</> ValidatingAdmissionPolicy · Apache-2.0

Binds a hostPort on the Node

container-hostports

severityModerate resourceContainers productKubernetes bundles2

A hostPort binds the container port onto the node network interfaces, exposing it to anything that can reach the node, bypassing Service and NetworkPolicy controls and squatting on node component ports.

Rejects unless

object.spec.containers.all(c,
  !has(c.ports) ||
  c.ports.all(p,
    !has(p.hostPort) ||
    p.hostPort == 0 ||
    variables.allowedHostPorts.exists(h, h == p.hostPort)
  )
)

hostPort must be undefined, 0, or in the variables.allowedHostPorts list.

Variables

allowedHostPorts

[]

Remediation

Remove the hostPort field or set it to 0 and publish the workload through a Service instead. Field: spec.containers[*].ports[*].hostPort.

Applies to

  • pods · v1 · CREATE, UPDATE

Manifest

apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
  name: container-hostports
  annotations:
    kubeapt.io/uuid: "8f1b04b9-f999-4be0-aa75-a72ea9c33c1e"
    security.kubeapt.io/displayName: "Binds a hostPort on the Node"
    security.kubeapt.io/description: "A hostPort binds the container port onto the node network interfaces, exposing it to anything that can reach the node, bypassing Service and NetworkPolicy controls and squatting on node component ports."
    security.kubeapt.io/resource: "Containers"
    security.kubeapt.io/severity: "Moderate"
    security.kubeapt.io/remediation: "Remove the hostPort field or set it to 0 and publish the workload through a Service instead. Field: spec.containers[*].ports[*].hostPort."
    security.kubeapt.io/product: "Kubernetes"
spec:
  failurePolicy: Fail
  matchConstraints:
    resourceRules:
    - apiGroups:
      - ''
      apiVersions:
      - v1
      operations:
      - CREATE
      - UPDATE
      resources:
      - pods
  variables:
  - name: allowedHostPorts
    expression: |
      []
  validations:
  - expression: |
      object.spec.containers.all(c,
        !has(c.ports) ||
        c.ports.all(p,
          !has(p.hostPort) ||
          p.hostPort == 0 ||
          variables.allowedHostPorts.exists(h, h == p.hostPort)
        )
      )
    message: |
      hostPort must be undefined, 0, or in the variables.allowedHostPorts list.

Save it as container-hostports.yaml — the commands below assume that name.

Validate with kubeapt

Check a workload against this one policy, before anything is installed on a cluster.

$ kubeapt validate -p ./container-hostports.yaml -r ./workload.yaml

Or without the file, from the published policy set — -r takes a directory too:

$ kubeapt policies download && kubeapt validate --policy-name container-hostports -r ./manifests

Or against every namespace in the cluster your kubeconfig points at:

$ kubeapt validate --policy-name container-hostports -A