All Policies

Remove hostPath Volumes

Pods which mount hostPath volumes are provided access to the underlying filesystem of the Node on which they run. In most scenarios, this should be forbidden. In others, it may be useful to silently remove those hostPath volumes rather than blocking the Pod. This policy removes all hostPath volumes and their volumeMount references from all containers within a Pod.

Policy Definition

/other/remove-hostpath-volumes/remove-hostpath-volumes.yaml

 1apiVersion: kyverno.io/v1
 2kind: ClusterPolicy
 3metadata:
 4  name: remove-hostpath-volumes
 5  annotations:
 6    policies.kyverno.io/title: Remove hostPath Volumes
 7    policies.kyverno.io/category: Other
 8    policies.kyverno.io/severity: medium
 9    policies.kyverno.io/subject: Pod,Volume
10    kyverno.io/kyverno-version: 1.10.0
11    policies.kyverno.io/minversion: 1.10.0
12    kyverno.io/kubernetes-version: "1.25"
13    policies.kyverno.io/description: >-
14      Pods which mount hostPath volumes are provided access to the underlying filesystem
15      of the Node on which they run. In most scenarios, this should be forbidden. In others,
16      it may be useful to silently remove those hostPath volumes rather than blocking the Pod.
17      This policy removes all hostPath volumes and their volumeMount references from all containers
18      within a Pod.
19spec:
20  background: false
21  rules:
22    - name: remove-hostpath-all
23      match:
24        any:
25          - resources:
26              kinds:
27                - Pod
28      context:
29      - name: hostpathvolnames
30        variable:
31          jmesPath: request.object.spec.volumes[?hostPath].name
32      preconditions:
33        all:
34        - key: "{{ length(hostpathvolnames) }}"
35          operator: GreaterThan
36          value: 0
37      mutate:
38        foreach:
39          - list: request.object.spec.volumes[]
40            order: Descending
41            preconditions:
42              all:
43              - key: hostPath
44                operator: AnyIn
45                value: "{{ element.keys(@) }}"
46            patchesJson6902: |-
47              - path: /spec/volumes/{{elementIndex}}
48                op: remove
49          - list: request.object.spec.containers[]
50            foreach:
51            - list: " element.volumeMounts || `[]` "
52              order: Descending
53              preconditions:
54                all:
55                - key: "{{element.name}}"
56                  operator: AnyIn
57                  value: "{{ hostpathvolnames }}"
58              patchesJson6902: |-
59                - path: /spec/containers/{{elementIndex0}}/volumeMounts/{{elementIndex1}}
60                  op: remove