All Policies

Disallow hostPorts Range (Alternate) in CEL expressions

Access to host ports allows potential snooping of network traffic and should not be allowed, or at minimum restricted to a known list. This policy ensures the `hostPort` field is set to one in the designated list. Note that Kubernetes Pod Security Admission does not support this rule.

Policy Definition

/pod-security-cel/baseline/disallow-host-ports-range/disallow-host-ports-range.yaml

 1apiVersion: kyverno.io/v1
 2kind: ClusterPolicy
 3metadata:
 4  name: disallow-host-ports-range
 5  annotations:
 6    policies.kyverno.io/title: Disallow hostPorts Range (Alternate) in CEL expressions
 7    policies.kyverno.io/category: Pod Security Standards (Baseline) in CEL
 8    policies.kyverno.io/severity: medium
 9    policies.kyverno.io/subject: Pod
10    policies.kyverno.io/minversion: 1.11.0
11    kyverno.io/kubernetes-version: "1.26-1.27"
12    policies.kyverno.io/description: >-
13      Access to host ports allows potential snooping of network traffic and should not be
14      allowed, or at minimum restricted to a known list. This policy ensures the `hostPort`
15      field is set to one in the designated list. Note that Kubernetes Pod Security Admission
16      does not support this rule.
17spec:
18  validationFailureAction: Audit
19  background: true
20  rules:
21    - name: host-port-range
22      match:
23        any:
24        - resources:
25            kinds:
26              - Pod
27            operations:
28            - CREATE
29            - UPDATE
30      validate:
31        cel:
32          variables:
33            - name: allContainers
34              expression: >-
35               object.spec.containers + 
36               object.spec.?initContainers.orValue([]) + 
37               object.spec.?ephemeralContainers.orValue([])
38          expressions:
39            - expression: >- 
40                variables.allContainers.all(container, 
41                container.?ports.orValue([]).all(port,
42                size(port) == 0 ||
43                !has(port.hostPort) || (port.hostPort >= 5000 && port.hostPort <= 6000) ))             
44              message: >-
45                The only permitted hostPorts are in the range 5000-6000.