{{- $name := "restrict-sysctls" }}
{{- if eq (include "kyverno-policies.podSecurityBaseline" (merge (dict "name" $name) .)) "true" }}
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: {{ $name }}
  annotations:
    {{- with .Values.autogenControllers }}
    pod-policies.kyverno.io/autogen-controllers: {{ . }}
    {{- end }}
    policies.kyverno.io/title: Restrict sysctls
    policies.kyverno.io/category: Pod Security Standards (Baseline)
    {{- if .Values.podSecuritySeverity }}
    policies.kyverno.io/severity: {{ .Values.podSecuritySeverity }}
    {{- end }}
    policies.kyverno.io/subject: Pod
    kyverno.io/kyverno-version: 1.6.0
    kyverno.io/kubernetes-version: "1.22-1.23"
    policies.kyverno.io/description: >-
      Sysctls can disable security mechanisms or affect all containers on a
      host, and should be disallowed except for an allowed "safe" subset. A
      sysctl is considered safe if it is namespaced in the container or the
      Pod, and it is isolated from other Pods or processes on the same Node.
      This policy ensures that only those "safe" subsets can be specified in
      a Pod.
  labels: {{ include "kyverno-policies.labels" . | nindent 4 }}
spec:
  {{- with index .Values "validationFailureActionByPolicy" $name }}
  validationFailureAction: {{ toYaml . }}
  {{- else }}
  validationFailureAction: {{ .Values.validationFailureAction }}
  {{- end }}
  {{- with concat (index .Values "validationFailureActionOverrides" "all") (default list (index .Values "validationFailureActionOverrides" $name)) }}
  validationFailureActionOverrides: {{ toYaml . | nindent 4 }}
  {{- end }}
  background: {{ .Values.background }}
  failurePolicy: {{ .Values.failurePolicy }}
  rules:
    - name: check-sysctls
      match:
        any:
        - resources:
            kinds:
              - Pod
      {{- with index .Values "policyExclude" $name }}
      exclude:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- with index .Values "policyPreconditions" $name }}
      preconditions:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      validate:
        message: >-
          Setting additional sysctls above the allowed type is disallowed.
          The field spec.securityContext.sysctls must be unset or not use any other names
          than kernel.shm_rmid_forced, net.ipv4.ip_local_port_range,
          net.ipv4.ip_unprivileged_port_start, net.ipv4.tcp_syncookies and
          net.ipv4.ping_group_range.
        pattern:
          spec:
            =(securityContext):
              =(sysctls):
                - =(name): "kernel.shm_rmid_forced | net.ipv4.ip_local_port_range | net.ipv4.ip_unprivileged_port_start | net.ipv4.tcp_syncookies | net.ipv4.ping_group_range"
{{- end }}
