github.com/khulnasoft-lab/defsec@v1.0.5-0.20230827010352-5e9f46893d95/rules/kubernetes/policies/pss/baseline/5_access_to_host_ports.rego (about)

     1  # METADATA
     2  # title: "Access to host ports"
     3  # description: "HostPorts should be disallowed, or at minimum restricted to a known list."
     4  # scope: package
     5  # schemas:
     6  # - input: schema["kubernetes"]
     7  # related_resources:
     8  # - https://kubernetes.io/docs/concepts/security/pod-security-standards/#baseline
     9  # custom:
    10  #   id: KSV024
    11  #   avd_id: AVD-KSV-0024
    12  #   severity: HIGH
    13  #   short_code: no-host-port-access
    14  #   recommended_action: "Do not set spec.containers[*].ports[*].hostPort and spec.initContainers[*].ports[*].hostPort."
    15  #   input:
    16  #     selector:
    17  #     - type: kubernetes
    18  package builtin.kubernetes.KSV024
    19  
    20  import data.lib.kubernetes
    21  
    22  default failHostPorts = false
    23  
    24  # Add allowed host ports to this set
    25  allowed_host_ports = set()
    26  
    27  # getContainersWithDisallowedHostPorts returns a list of containers which have
    28  # host ports not included in the allowed host port list
    29  getContainersWithDisallowedHostPorts[container] {
    30  	allContainers := kubernetes.containers[_]
    31  	set_host_ports := {port | port := allContainers.ports[_].hostPort}
    32  	host_ports_not_allowed := set_host_ports - allowed_host_ports
    33  	count(host_ports_not_allowed) > 0
    34  	container := allContainers.name
    35  }
    36  
    37  # host_ports_msg is a string of allowed host ports to be print as part of deny message
    38  host_ports_msg = "" {
    39  	count(allowed_host_ports) == 0
    40  } else = msg {
    41  	msg := sprintf(" or set it to the following allowed values: %s", [concat(", ", allowed_host_ports)])
    42  }
    43  
    44  # Get all containers which don't include 'ALL' in security.capabilities.drop
    45  getContainersWitNohDisallowedHostPorts[container] {
    46  	container := kubernetes.containers[_]
    47  	not getContainersWithDisallowedHostPorts[container]
    48  }
    49  
    50  deny[res] {
    51  	output := getContainersWitNohDisallowedHostPorts[_]
    52  	msg := sprintf("Container '%s' of %s '%s' should not set host ports, 'ports[*].hostPort'%s", [getContainersWithDisallowedHostPorts[_], kubernetes.kind, kubernetes.name, host_ports_msg])
    53  	res := result.new(msg, output)
    54  }