ValidateNamespace

// ValidateNamespace evaluates a namespace create or update request to ensure the pod security labels are valid,
// and checks existing pods in the namespace for violations of the new policy when updating the enforce level on a namespace.
// The returned response may be shared between evaluations and must not be mutated.
func (a *Admission) ValidateNamespace(ctx context.Context, attrs api.Attributes) *admissionv1.AdmissionResponse {
	// short-circuit on subresources
	if attrs.GetSubresource() != "" {
		return sharedAllowedResponse
	}
	obj, err := attrs.GetObject()
	if err != nil {
		klog.ErrorS(err, "failed to decode object")
		return errorResponse(err, &apierrors.NewBadRequest("failed to decode object").ErrStatus)
	}
	namespace, ok := obj.(*corev1.Namespace)
	if !ok {
		klog.InfoS("failed to assert namespace type", "type", reflect.TypeOf(obj))
		return errorResponse(nil, &apierrors.NewBadRequest("failed to decode namespace").ErrStatus)
	}

	newPolicy, newErrs := a.PolicyToEvaluate(namespace.Labels)

	switch attrs.GetOperation() {
	case admissionv1.Create:
		// require valid labels on create
		if len(newErrs) > 0 {
			return invalidResponse(attrs, newErrs)
		}
		if a.exemptNamespace(attrs.GetNamespace()) {
			if warning := a.exemptNamespaceWarning(namespace.Name, newPolicy, namespace.Labels); warning != "" {
				response := allowedResponse()
				response.Warnings = append(response.Warnings, warning)
				return response
			}
		}
		return sharedAllowedResponse

	case admissionv1.Update:
		// if update, check if policy labels changed
		oldObj, err := attrs.GetOldObject()
		if err != nil {
			klog.ErrorS(err, "failed to decode old object")
			return errorResponse(err, &apierrors.NewBadRequest("failed to decode  old object").ErrStatus)
		}
		oldNamespace, ok := oldObj.(*corev1.Namespace)
		if !ok {
			klog.InfoS("failed to assert old namespace type", "type", reflect.TypeOf(oldObj))
			return errorResponse(nil, &apierrors.NewBadRequest("failed to decode  old namespace").ErrStatus)
		}
		oldPolicy, oldErrs := a.PolicyToEvaluate(oldNamespace.Labels)

		// require valid labels on update if they have changed
		if len(newErrs) > 0 && (len(oldErrs) == 0 || !reflect.DeepEqual(newErrs, oldErrs)) {
			return invalidResponse(attrs, newErrs)
		}

		// Skip dry-running pods:
		// * if the enforce policy is unchanged
		// * if the new enforce policy is privileged
		// * if the new enforce is the same version and level was relaxed
		// * for exempt namespaces
		if newPolicy.Enforce == oldPolicy.Enforce {
			return sharedAllowedResponse
		}
		if newPolicy.Enforce.Level == api.LevelPrivileged {
			return sharedAllowedResponse
		}
		if newPolicy.Enforce.Version == oldPolicy.Enforce.Version &&
			api.CompareLevels(newPolicy.Enforce.Level, oldPolicy.Enforce.Level) < 1 {
			return sharedAllowedResponse
		}
		if a.exemptNamespace(attrs.GetNamespace()) {
			if warning := a.exemptNamespaceWarning(namespace.Name, newPolicy, namespace.Labels); warning != "" {
				response := allowedResponse()
				response.Warnings = append(response.Warnings, warning)
				return response
			}
			return sharedAllowedResponse
		}
		response := allowedResponse()
		response.Warnings = a.EvaluatePodsInNamespace(ctx, namespace.Name, newPolicy.Enforce)
		return response

	default:
		return sharedAllowedResponse
	}
}


ValidatePod

// ValidatePod evaluates a pod create or update request against the effective policy for the namespace.
// The returned response may be shared between evaluations and must not be mutated.
func (a *Admission) ValidatePod(ctx context.Context, attrs api.Attributes) *admissionv1.AdmissionResponse {
	// short-circuit on ignored subresources
	if ignoredPodSubresources[attrs.GetSubresource()] {
		return sharedAllowedResponse
	}
	// short-circuit on exempt namespaces and users
	if a.exemptNamespace(attrs.GetNamespace()) {
		a.Metrics.RecordExemption(attrs)
		return sharedAllowedByNamespaceExemptionResponse
	}

	if a.exemptUser(attrs.GetUserName()) {
		a.Metrics.RecordExemption(attrs)
		return sharedAllowedByUserExemptionResponse
	}

	// short-circuit on privileged enforce+audit+warn namespaces
	namespace, err := a.NamespaceGetter.GetNamespace(ctx, attrs.GetNamespace())
	if err != nil {
		klog.ErrorS(err, "failed to fetch pod namespace", "namespace", attrs.GetNamespace())
		a.Metrics.RecordError(true, attrs)
		return errorResponse(err, &apierrors.NewInternalError(fmt.Errorf("failed to lookup namespace %q", attrs.GetNamespace())).ErrStatus)
	}
	nsPolicy, nsPolicyErrs := a.PolicyToEvaluate(namespace.Labels)
	if len(nsPolicyErrs) == 0 && nsPolicy.FullyPrivileged() {
		a.Metrics.RecordEvaluation(metrics.DecisionAllow, nsPolicy.Enforce, metrics.ModeEnforce, attrs)
		return sharedAllowedPrivilegedResponse
	}

	obj, err := attrs.GetObject()
	if err != nil {
		klog.ErrorS(err, "failed to decode object")
		a.Metrics.RecordError(true, attrs)
		return errorResponse(err, &apierrors.NewBadRequest("failed to decode object").ErrStatus)
	}
	pod, ok := obj.(*corev1.Pod)
	if !ok {
		klog.InfoS("failed to assert pod type", "type", reflect.TypeOf(obj))
		a.Metrics.RecordError(true, attrs)
		return errorResponse(nil, &apierrors.NewBadRequest("failed to decode pod").ErrStatus)
	}
	if attrs.GetOperation() == admissionv1.Update {
		oldObj, err := attrs.GetOldObject()
		if err != nil {
			klog.ErrorS(err, "failed to decode old object")
			a.Metrics.RecordError(true, attrs)
			return errorResponse(err, &apierrors.NewBadRequest("failed to decode old object").ErrStatus)
		}
		oldPod, ok := oldObj.(*corev1.Pod)
		if !ok {
			klog.InfoS("Failed to assert old pod type", "type", reflect.TypeOf(oldObj))
			a.Metrics.RecordError(true, attrs)
			return errorResponse(nil, &apierrors.NewBadRequest("failed to decode old pod").ErrStatus)
		}
		if !isSignificantPodUpdate(pod, oldPod) {
			// Nothing we care about changed, so always allow the update.
			return sharedAllowedResponse
		}
	}
	return a.EvaluatePod(ctx, nsPolicy, nsPolicyErrs.ToAggregate(), &pod.ObjectMeta, &pod.Spec, attrs, true)
}


ValidatePodController

// ValidatePodController evaluates a pod controller create or update request against the effective policy for the namespace.
// The returned response may be shared between evaluations and must not be mutated.
func (a *Admission) ValidatePodController(ctx context.Context, attrs api.Attributes) *admissionv1.AdmissionResponse {
	// short-circuit on subresources
	if attrs.GetSubresource() != "" {
		return sharedAllowedResponse
	}
	// short-circuit on exempt namespaces and users
	if a.exemptNamespace(attrs.GetNamespace()) {
		a.Metrics.RecordExemption(attrs)
		return sharedAllowedByNamespaceExemptionResponse
	}

	if a.exemptUser(attrs.GetUserName()) {
		a.Metrics.RecordExemption(attrs)
		return sharedAllowedByUserExemptionResponse
	}

	// short-circuit on privileged audit+warn namespaces
	namespace, err := a.NamespaceGetter.GetNamespace(ctx, attrs.GetNamespace())
	if err != nil {
		klog.ErrorS(err, "failed to fetch pod namespace", "namespace", attrs.GetNamespace())
		a.Metrics.RecordError(true, attrs)
		response := allowedResponse()
		response.AuditAnnotations = map[string]string{
			"error": fmt.Sprintf("failed to lookup namespace %q: %v", attrs.GetNamespace(), err),
		}
		return response
	}
	nsPolicy, nsPolicyErrs := a.PolicyToEvaluate(namespace.Labels)
	if len(nsPolicyErrs) == 0 && nsPolicy.Warn.Level == api.LevelPrivileged && nsPolicy.Audit.Level == api.LevelPrivileged {
		return sharedAllowedResponse
	}

	obj, err := attrs.GetObject()
	if err != nil {
		klog.ErrorS(err, "failed to decode object")
		a.Metrics.RecordError(true, attrs)
		response := allowedResponse()
		response.AuditAnnotations = map[string]string{
			"error": fmt.Sprintf("failed to decode object: %v", err),
		}
		return response
	}
	podMetadata, podSpec, err := a.PodSpecExtractor.ExtractPodSpec(obj)
	if err != nil {
		klog.ErrorS(err, "failed to extract pod spec")
		a.Metrics.RecordError(true, attrs)
		response := allowedResponse()
		response.AuditAnnotations = map[string]string{
			"error": fmt.Sprintf("failed to extract pod template: %v", err),
		}
		return response
	}
	if podMetadata == nil && podSpec == nil {
		// if a controller with an optional pod spec does not contain a pod spec, skip validation
		return sharedAllowedResponse
	}
	return a.EvaluatePod(ctx, nsPolicy, nsPolicyErrs.ToAggregate(), podMetadata, podSpec, attrs, false)
}


EvaluatePod

// EvaluatePod evaluates the given policy against the given pod(-like) object.
// The enforce policy is only checked if enforce=true.
// The returned response may be shared between evaluations and must not be mutated.
func (a *Admission) EvaluatePod(ctx context.Context, nsPolicy api.Policy, nsPolicyErr error, podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec, attrs api.Attributes, enforce bool) *admissionv1.AdmissionResponse {
	// short-circuit on exempt runtimeclass
	if a.exemptRuntimeClass(podSpec.RuntimeClassName) {
		a.Metrics.RecordExemption(attrs)
		return sharedAllowedByRuntimeClassExemptionResponse
	}

	auditAnnotations := map[string]string{}
	if nsPolicyErr != nil {
		klog.V(2).InfoS("failed to parse PodSecurity namespace labels", "err", nsPolicyErr)
		auditAnnotations["error"] = fmt.Sprintf("Failed to parse policy: %v", nsPolicyErr)
		a.Metrics.RecordError(false, attrs)
	}

	klogV := klog.V(5)
	if klogV.Enabled() {
		klogV.InfoS("PodSecurity evaluation", "policy", fmt.Sprintf("%v", nsPolicy), "op", attrs.GetOperation(), "resource", attrs.GetResource(), "namespace", attrs.GetNamespace(), "name", attrs.GetName())
	}
	cachedResults := make(map[api.LevelVersion]policy.AggregateCheckResult)
	response := allowedResponse()
	if enforce {
		auditAnnotations[api.EnforcedPolicyAnnotationKey] = nsPolicy.Enforce.String()

		result := policy.AggregateCheckResults(a.Evaluator.EvaluatePod(nsPolicy.Enforce, podMetadata, podSpec))
		if !result.Allowed {
			response = forbiddenResponse(attrs, fmt.Errorf(
				"violates PodSecurity %q: %s",
				nsPolicy.Enforce.String(),
				result.ForbiddenDetail(),
			))
			a.Metrics.RecordEvaluation(metrics.DecisionDeny, nsPolicy.Enforce, metrics.ModeEnforce, attrs)
		} else {
			a.Metrics.RecordEvaluation(metrics.DecisionAllow, nsPolicy.Enforce, metrics.ModeEnforce, attrs)
		}
		cachedResults[nsPolicy.Enforce] = result
	}

	// reuse previous evaluation if audit level+version is the same as enforce level+version

	auditResult, ok := cachedResults[nsPolicy.Audit]
	if !ok {
		auditResult = policy.AggregateCheckResults(a.Evaluator.EvaluatePod(nsPolicy.Audit, podMetadata, podSpec))
		cachedResults[nsPolicy.Audit] = auditResult
	}
	if !auditResult.Allowed {
		auditAnnotations[api.AuditViolationsAnnotationKey] = fmt.Sprintf(
			"would violate PodSecurity %q: %s",
			nsPolicy.Audit.String(),
			auditResult.ForbiddenDetail(),
		)
		a.Metrics.RecordEvaluation(metrics.DecisionDeny, nsPolicy.Audit, metrics.ModeAudit, attrs)
	}

	// avoid adding warnings to a request we're already going to reject with an error
	if response.Allowed {
		// reuse previous evaluation if warn level+version is the same as audit or enforce level+version
		warnResult, ok := cachedResults[nsPolicy.Warn]
		if !ok {
			warnResult = policy.AggregateCheckResults(a.Evaluator.EvaluatePod(nsPolicy.Warn, podMetadata, podSpec))
		}
		if !warnResult.Allowed {
			// TODO: Craft a better user-facing warning message
			response.Warnings = append(response.Warnings, fmt.Sprintf(
				"would violate PodSecurity %q: %s",
				nsPolicy.Warn.String(),
				warnResult.ForbiddenDetail(),
			))
			a.Metrics.RecordEvaluation(metrics.DecisionDeny, nsPolicy.Warn, metrics.ModeWarn, attrs)
		}
	}

	response.AuditAnnotations = auditAnnotations
	return response
}


EvaluatePodsInNamespace

func (a *Admission) EvaluatePodsInNamespace(ctx context.Context, namespace string, enforce api.LevelVersion) []string {
	// start with the default timeout
	timeout := a.namespacePodCheckTimeout
	if deadline, ok := ctx.Deadline(); ok {
		timeRemaining := time.Until(deadline) / 2 // don't take more than half the remaining time
		if timeout > timeRemaining {
			timeout = timeRemaining
		}
	}
	deadline := time.Now().Add(timeout)
	ctx, cancel := context.WithDeadline(ctx, deadline)
	defer cancel()

	pods, err := a.PodLister.ListPods(ctx, namespace)
	if err != nil {
		klog.ErrorS(err, "failed to list pods", "namespace", namespace)
		return []string{"failed to list pods while checking new PodSecurity enforce level"}
	}

	var (
		warnings []string

		podWarnings        []string
		podWarningsToCount = make(map[string]podCount)
		prioritizedPods    = a.prioritizePods(pods)
	)

	totalPods := len(prioritizedPods)
	if len(prioritizedPods) > a.namespaceMaxPodsToCheck {
		prioritizedPods = prioritizedPods[0:a.namespaceMaxPodsToCheck]
	}

	checkedPods := len(prioritizedPods)
	for i, pod := range prioritizedPods {
		r := policy.AggregateCheckResults(a.Evaluator.EvaluatePod(enforce, &pod.ObjectMeta, &pod.Spec))
		if !r.Allowed {
			warning := r.ForbiddenReason()
			c, seen := podWarningsToCount[warning]
			if !seen {
				c.podName = pod.Name
				podWarnings = append(podWarnings, warning)
			} else if pod.Name < c.podName {
				c.podName = pod.Name
			}
			c.podCount++
			podWarningsToCount[warning] = c
		}
		if err := ctx.Err(); err != nil { // deadline exceeded or context was cancelled
			checkedPods = i + 1
			break
		}
	}

	if checkedPods < totalPods {
		warnings = append(warnings, fmt.Sprintf("new PodSecurity enforce level only checked against the first %d of %d existing pods", checkedPods, totalPods))
	}

	if len(podWarnings) > 0 {
		warnings = append(warnings, fmt.Sprintf("existing pods in namespace %q violate the new PodSecurity enforce level %q", namespace, enforce.String()))
	}

	// prepend pod names to warnings
	decoratePodWarnings(podWarningsToCount, podWarnings)
	// put warnings in a deterministic order
	sort.Strings(podWarnings)

	return append(warnings, podWarnings...)
}


decoratePodWarnings

// prefixes warnings with the pod names related to that warning
func decoratePodWarnings(podWarningsToCount map[string]podCount, warnings []string) {
	for i, warning := range warnings {
		c := podWarningsToCount[warning]
		switch c.podCount {
		case 0:
			// unexpected, just leave the warning alone
		case 1:
			warnings[i] = fmt.Sprintf("%s: %s", c.podName, warning)
		case 2:
			warnings[i] = fmt.Sprintf("%s (and 1 other pod): %s", c.podName, warning)
		default:
			warnings[i] = fmt.Sprintf("%s (and %d other pods): %s", c.podName, c.podCount-1, warning)
		}
	}
}


PolicyToEvaluate

func (a *Admission) PolicyToEvaluate(labels map[string]string) (api.Policy, field.ErrorList) {
	return api.PolicyToEvaluate(labels, a.defaultPolicy)
}


isSignificantPodUpdate

// isSignificantPodUpdate determines whether a pod update should trigger a policy evaluation.
// Relevant mutable pod fields as of 1.21 are image annotations:
// * https://github.com/kubernetes/kubernetes/blob/release-1.21/pkg/apis/core/validation/validation.go#L3947-L3949
func isSignificantPodUpdate(pod, oldPod *corev1.Pod) bool {
	// TODO: invert this logic to only allow specific update types.
	if len(pod.Spec.Containers) != len(oldPod.Spec.Containers) {
		return true
	}
	if len(pod.Spec.InitContainers) != len(oldPod.Spec.InitContainers) {
		return true
	}
	for i := 0; i < len(pod.Spec.Containers); i++ {
		if isSignificantContainerUpdate(&pod.Spec.Containers[i], &oldPod.Spec.Containers[i]) {
			return true
		}
	}
	for i := 0; i < len(pod.Spec.InitContainers); i++ {
		if isSignificantContainerUpdate(&pod.Spec.InitContainers[i], &oldPod.Spec.InitContainers[i]) {
			return true
		}
	}
	for _, c := range pod.Spec.EphemeralContainers {
		var oldC *corev1.Container
		for i, oc := range oldPod.Spec.EphemeralContainers {
			if oc.Name == c.Name {
				oldC = (*corev1.Container)(&oldPod.Spec.EphemeralContainers[i].EphemeralContainerCommon)
				break
			}
		}
		if oldC == nil {
			return true // EphemeralContainer added
		}
		if isSignificantContainerUpdate((*corev1.Container)(&c.EphemeralContainerCommon), oldC) {
			return true
		}
	}
	return false
}


isSignificantContainerUpdate

// isSignificantContainerUpdate determines whether a container update should trigger a policy evaluation.
func isSignificantContainerUpdate(container, oldContainer *corev1.Container) bool {
	return container.Image != oldContainer.Image
}


exemptNamespace

func (a *Admission) exemptNamespace(namespace string) bool {
	if len(namespace) == 0 {
		return false
	}
	// TODO: consider optimizing to O(1) lookup
	return containsString(namespace, a.Configuration.Exemptions.Namespaces)
}


exemptUser

func (a *Admission) exemptUser(username string) bool {
	if len(username) == 0 {
		return false
	}
	// TODO: consider optimizing to O(1) lookup
	return containsString(username, a.Configuration.Exemptions.Usernames)
}


exemptRuntimeClass

func (a *Admission) exemptRuntimeClass(runtimeClass *string) bool {
	if runtimeClass == nil || len(*runtimeClass) == 0 {
		return false
	}
	// TODO: consider optimizing to O(1) lookup
	return containsString(*runtimeClass, a.Configuration.Exemptions.RuntimeClasses)
}


prioritizePods

// Filter and prioritize pods based on runtimeclass and uniqueness of the controller respectively for evaluation.
// The input slice is modified in place and should not be reused.
func (a *Admission) prioritizePods(pods []*corev1.Pod) []*corev1.Pod {
	// accumulate the list of prioritized pods in-place to avoid double-allocating
	prioritizedPods := pods[:0]
	// accumulate any additional replicated pods after the first one encountered for a given controller uid
	var duplicateReplicatedPods []*corev1.Pod
	evaluatedControllers := make(map[types.UID]bool)
	for _, pod := range pods {
		// short-circuit on exempt runtimeclass
		if a.exemptRuntimeClass(pod.Spec.RuntimeClassName) {
			continue
		}
		// short-circuit if pod from the same controller is evaluated
		podOwnerControllerRef := metav1.GetControllerOfNoCopy(pod)
		if podOwnerControllerRef == nil {
			prioritizedPods = append(prioritizedPods, pod)
			continue
		}
		if evaluatedControllers[podOwnerControllerRef.UID] {
			duplicateReplicatedPods = append(duplicateReplicatedPods, pod)
			continue
		}
		prioritizedPods = append(prioritizedPods, pod)
		evaluatedControllers[podOwnerControllerRef.UID] = true
	}
	return append(prioritizedPods, duplicateReplicatedPods...)
}


containsString

func containsString(needle string, haystack []string) bool {
	for _, s := range haystack {
		if s == needle {
			return true
		}
	}
	return false
}


exemptNamespaceWarning

// exemptNamespaceWarning returns a non-empty warning message if the exempt namespace has a
// non-privileged policy and sets pod security labels.
func (a *Admission) exemptNamespaceWarning(exemptNamespace string, policy api.Policy, nsLabels map[string]string) string {
	if policy.FullyPrivileged() || policy.Equivalent(&a.defaultPolicy) {
		return ""
	}

	// Build a compact representation of the policy, only printing non-privileged modes that have
	// been explicitly set.
	sb := strings.Builder{}
	_, hasEnforceLevel := nsLabels[api.EnforceLevelLabel]
	_, hasEnforceVersion := nsLabels[api.EnforceVersionLabel]
	if policy.Enforce.Level != api.LevelPrivileged && (hasEnforceLevel || hasEnforceVersion) {
		sb.WriteString("enforce=")
		sb.WriteString(policy.Enforce.String())
	}
	_, hasAuditLevel := nsLabels[api.AuditLevelLabel]
	_, hasAuditVersion := nsLabels[api.AuditVersionLabel]
	if policy.Audit.Level != api.LevelPrivileged && (hasAuditLevel || hasAuditVersion) {
		if sb.Len() > 0 {
			sb.WriteString(", ")
		}
		sb.WriteString("audit=")
		sb.WriteString(policy.Audit.String())
	}
	_, hasWarnLevel := nsLabels[api.WarnLevelLabel]
	_, hasWarnVersion := nsLabels[api.WarnVersionLabel]
	if policy.Warn.Level != api.LevelPrivileged && (hasWarnLevel || hasWarnVersion) {
		if sb.Len() > 0 {
			sb.WriteString(", ")
		}
		sb.WriteString("warn=")
		sb.WriteString(policy.Warn.String())
	}

	return fmt.Sprintf("namespace %q is exempt from Pod Security, and the policy (%s) will be ignored",
		exemptNamespace, sb.String())
}


ToPolicy

// TODO: deduplicate against PolicyToEvaluate
func ToPolicy(defaults PodSecurityDefaults) (policyapi.Policy, error) {
	var (
		err  error
		errs []error
		p    policyapi.Policy
	)

	if len(defaults.Enforce) == 0 {
		errs = appendErr(errs, requiredErr, "enforce")
	} else {
		p.Enforce.Level, err = policyapi.ParseLevel(defaults.Enforce)
		errs = appendErr(errs, err, "enforce")
	}

	if len(defaults.EnforceVersion) == 0 {
		errs = appendErr(errs, requiredErr, "enforce-version")
	} else {
		p.Enforce.Version, err = policyapi.ParseVersion(defaults.EnforceVersion)
		errs = appendErr(errs, err, "enforce-version")
	}

	if len(defaults.Audit) == 0 {
		errs = appendErr(errs, requiredErr, "audit")
	} else {
		p.Audit.Level, err = policyapi.ParseLevel(defaults.Audit)
		errs = appendErr(errs, err, "audit")
	}

	if len(defaults.AuditVersion) == 0 {
		errs = appendErr(errs, requiredErr, "audit-version")
	} else {
		p.Audit.Version, err = policyapi.ParseVersion(defaults.AuditVersion)
		errs = appendErr(errs, err, "audit-version")
	}

	if len(defaults.Warn) == 0 {
		errs = appendErr(errs, requiredErr, "warn")
	} else {
		p.Warn.Level, err = policyapi.ParseLevel(defaults.Warn)
		errs = appendErr(errs, err, "warn")
	}

	if len(defaults.WarnVersion) == 0 {
		errs = appendErr(errs, requiredErr, "warn-version")
	} else {
		p.Warn.Version, err = policyapi.ParseVersion(defaults.WarnVersion)
		errs = appendErr(errs, err, "warn-version")
	}

	return p, errors.NewAggregate(errs)
}


appendErr

// appendErr is a helper function to collect field-specific errors.
func appendErr(errs []error, err error, field string) []error {
	if err != nil {
		return append(errs, fmt.Errorf("%s: %s", field, err.Error()))
	}
	return errs
}


LoadFromFile

func LoadFromFile(file string) (*api.PodSecurityConfiguration, error) {
	if len(file) == 0 {
		// no file specified, use default config
		return LoadFromData(nil)
	}

	// read from file
	data, err := os.ReadFile(file)
	if err != nil {
		return nil, err
	}
	return LoadFromData(data)
}


LoadFromReader

func LoadFromReader(reader io.Reader) (*api.PodSecurityConfiguration, error) {
	if reader == nil {
		// no reader specified, use default config
		return LoadFromData(nil)
	}

	data, err := io.ReadAll(reader)
	if err != nil {
		return nil, err
	}
	return LoadFromData(data)
}


LoadFromData

func LoadFromData(data []byte) (*api.PodSecurityConfiguration, error) {
	if len(data) == 0 {
		// no config provided, return default
		externalConfig := &apiv1.PodSecurityConfiguration{}
		scheme.Scheme.Default(externalConfig)
		internalConfig := &api.PodSecurityConfiguration{}
		if err := scheme.Scheme.Convert(externalConfig, internalConfig, nil); err != nil {
			return nil, err
		}
		return internalConfig, nil
	}

	decodedObj, err := runtime.Decode(scheme.Codecs.UniversalDecoder(), data)
	if err != nil {
		return nil, err
	}
	configuration, ok := decodedObj.(*api.PodSecurityConfiguration)
	if !ok {
		return nil, fmt.Errorf("expected PodSecurityConfiguration, got %T", decodedObj)
	}
	return configuration, nil
}


init

func init() {
	// We only register manually written functions here. The registration of the
	// generated functions takes place in the generated files. The separation
	// makes the code compile even when the generated files are missing.
	localSchemeBuilder.Register(addKnownTypes)
}


addKnownTypes

func addKnownTypes(scheme *runtime.Scheme) error {
	scheme.AddKnownTypes(SchemeGroupVersion,
		&PodSecurityConfiguration{},
	)
	return nil
}


AddToScheme

// AddToScheme builds the podsecurity scheme using all known versions of the podsecurity api.
func AddToScheme(scheme *runtime.Scheme) {
	utilruntime.Must(podsecurityapi.AddToScheme(scheme))
	utilruntime.Must(podsecurityv1alpha1.AddToScheme(scheme))
	utilruntime.Must(podsecurityv1beta1.AddToScheme(scheme))
	utilruntime.Must(podsecurityv1.AddToScheme(scheme))
	utilruntime.Must(scheme.SetVersionPriority(podsecurityv1.SchemeGroupVersion, podsecurityv1beta1.SchemeGroupVersion, podsecurityv1alpha1.SchemeGroupVersion))
}


addDefaultingFuncs

func addDefaultingFuncs(scheme *runtime.Scheme) error {
	return RegisterDefaults(scheme)
}


func SetDefaults_PodSecurityDefaults(obj *PodSecurityDefaults) {
	if len(obj.Enforce) == 0 {
		obj.Enforce = string(api.LevelPrivileged)
	}
	if len(obj.Warn) == 0 {
		obj.Warn = string(api.LevelPrivileged)
	}
	if len(obj.Audit) == 0 {
		obj.Audit = string(api.LevelPrivileged)
	}

	if len(obj.EnforceVersion) == 0 {
		obj.EnforceVersion = string(api.VersionLatest)
	}
	if len(obj.WarnVersion) == 0 {
		obj.WarnVersion = string(api.VersionLatest)
	}
	if len(obj.AuditVersion) == 0 {
		obj.AuditVersion = string(api.VersionLatest)
	}
}


init

func init() {
	// We only register manually written functions here. The registration of the
	// generated functions takes place in the generated files. The separation
	// makes the code compile even when the generated files are missing.
	localSchemeBuilder.Register(addKnownTypes, addDefaultingFuncs)
}


ValidatePodSecurityConfiguration

// ValidatePodSecurityConfiguration validates a given PodSecurityConfiguration.
func ValidatePodSecurityConfiguration(configuration *admissionapi.PodSecurityConfiguration) field.ErrorList {
	allErrs := field.ErrorList{}

	// validate defaults
	allErrs = append(allErrs, validateLevel(field.NewPath("defaults", "enforce"), configuration.Defaults.Enforce)...)
	allErrs = append(allErrs, validateVersion(field.NewPath("defaults", "enforce-version"), configuration.Defaults.EnforceVersion)...)
	allErrs = append(allErrs, validateLevel(field.NewPath("defaults", "warn"), configuration.Defaults.Warn)...)
	allErrs = append(allErrs, validateVersion(field.NewPath("defaults", "warn-version"), configuration.Defaults.WarnVersion)...)
	allErrs = append(allErrs, validateLevel(field.NewPath("defaults", "audit"), configuration.Defaults.Audit)...)
	allErrs = append(allErrs, validateVersion(field.NewPath("defaults", "audit-version"), configuration.Defaults.AuditVersion)...)

	// validate exemptions
	allErrs = append(allErrs, validateNamespaces(configuration)...)
	allErrs = append(allErrs, validateRuntimeClasses(configuration)...)
	allErrs = append(allErrs, validateUsernames(configuration)...)

	return allErrs
}


validateLevel

// validateLevel validates a level
func validateLevel(p *field.Path, value string) field.ErrorList {
	errs := field.ErrorList{}
	_, err := api.ParseLevel(value)
	if err != nil {
		errs = append(errs, field.Invalid(p, value, err.Error()))
	}
	return errs
}


validateVersion

// validateVersion validates a version
func validateVersion(p *field.Path, value string) field.ErrorList {
	errs := field.ErrorList{}
	_, err := api.ParseVersion(value)
	if err != nil {
		errs = append(errs, field.Invalid(p, value, err.Error()))
	}
	return errs
}


validateNamespaces

func validateNamespaces(configuration *admissionapi.PodSecurityConfiguration) field.ErrorList {
	errs := field.ErrorList{}
	validSet := sets.NewString()
	for i, ns := range configuration.Exemptions.Namespaces {
		err := machinery.ValidateNamespaceName(ns, false)
		if len(err) > 0 {
			path := field.NewPath("exemptions", "namespaces").Index(i)
			errs = append(errs, field.Invalid(path, ns, strings.Join(err, ", ")))
			continue
		}
		if validSet.Has(ns) {
			path := field.NewPath("exemptions", "namespaces").Index(i)
			errs = append(errs, field.Duplicate(path, ns))
			continue
		}
		validSet.Insert(ns)
	}
	return errs
}


validateRuntimeClasses

func validateRuntimeClasses(configuration *admissionapi.PodSecurityConfiguration) field.ErrorList {
	errs := field.ErrorList{}
	validSet := sets.NewString()
	for i, rc := range configuration.Exemptions.RuntimeClasses {
		err := machinery.NameIsDNSSubdomain(rc, false)
		if len(err) > 0 {
			path := field.NewPath("exemptions", "runtimeClasses").Index(i)
			errs = append(errs, field.Invalid(path, rc, strings.Join(err, ", ")))
			continue
		}
		if validSet.Has(rc) {
			path := field.NewPath("exemptions", "runtimeClasses").Index(i)
			errs = append(errs, field.Duplicate(path, rc))
			continue
		}
		validSet.Insert(rc)
	}
	return errs
}


validateUsernames

func validateUsernames(configuration *admissionapi.PodSecurityConfiguration) field.ErrorList {
	errs := field.ErrorList{}
	validSet := sets.NewString()
	for i, uname := range configuration.Exemptions.Usernames {
		if uname == "" {
			path := field.NewPath("exemptions", "usernames").Index(i)
			errs = append(errs, field.Invalid(path, uname, "username must not be empty"))
			continue
		}
		if validSet.Has(uname) {
			path := field.NewPath("exemptions", "usernames").Index(i)
			errs = append(errs, field.Duplicate(path, uname))
			continue
		}
		validSet.Insert(uname)
	}

	return errs
}


NamespaceGetterFromClient

func NamespaceGetterFromClient(client kubernetes.Interface) NamespaceGetter {
	return &namespaceGetter{client: client}
}


NamespaceGetterFromListerAndClient

func NamespaceGetterFromListerAndClient(lister corev1listers.NamespaceLister, client kubernetes.Interface) NamespaceGetter {
	return &namespaceGetter{lister: lister, client: client}
}


GetNamespace

func (n *namespaceGetter) GetNamespace(ctx context.Context, name string) (namespace *corev1.Namespace, err error) {
	if n.lister != nil {
		namespace, err := n.lister.Get(name)
		if err == nil || !apierrors.IsNotFound(err) {
			return namespace, err
		}
	}
	return n.client.CoreV1().Namespaces().Get(ctx, name, metav1.GetOptions{})
}


PodListerFromClient

// PodListerFromClient returns a PodLister that does live lists using the provided client.
func PodListerFromClient(client kubernetes.Interface) PodLister {
	return &clientPodLister{client}
}


ListPods

func (p *clientPodLister) ListPods(ctx context.Context, namespace string) ([]*corev1.Pod, error) {
	list, err := p.client.CoreV1().Pods(namespace).List(ctx, metav1.ListOptions{})
	if err != nil {
		return nil, err
	}
	pods := make([]*corev1.Pod, len(list.Items))
	for i := range list.Items {
		pods[i] = &list.Items[i]
	}
	return pods, nil
}


PodListerFromInformer

// PodListerFromInformer returns a PodLister that does cached lists using the provided lister.
func PodListerFromInformer(lister corev1listers.PodLister) PodLister {
	return &informerPodLister{lister}
}


ListPods

func (p *informerPodLister) ListPods(ctx context.Context, namespace string) ([]*corev1.Pod, error) {
	return p.lister.Pods(namespace).List(labels.Everything())
}


init

func init() {
	sharedAllowedPrivilegedResponse.AuditAnnotations = map[string]string{
		api.EnforcedPolicyAnnotationKey: api.LevelVersion{Level: api.LevelPrivileged, Version: api.LatestVersion()}.String(),
	}
	sharedAllowedByUserExemptionResponse.AuditAnnotations = map[string]string{api.ExemptionReasonAnnotationKey: "user"}
	sharedAllowedByNamespaceExemptionResponse.AuditAnnotations = map[string]string{api.ExemptionReasonAnnotationKey: "namespace"}
	sharedAllowedByRuntimeClassExemptionResponse.AuditAnnotations = map[string]string{api.ExemptionReasonAnnotationKey: "runtimeClass"}
}


allowedResponse

// allowedResponse is the response used when the admission decision is allow.
func allowedResponse() *admissionv1.AdmissionResponse {
	return &admissionv1.AdmissionResponse{Allowed: true}
}


forbiddenResponse

// forbiddenResponse is the response used when the admission decision is deny for policy violations.
func forbiddenResponse(attrs api.Attributes, err error) *admissionv1.AdmissionResponse {
	return &admissionv1.AdmissionResponse{
		Allowed: false,
		Result:  &apierrors.NewForbidden(attrs.GetResource().GroupResource(), attrs.GetName(), err).ErrStatus,
	}
}


invalidResponse

// invalidResponse is the response used for namespace requests when namespace labels are invalid.
func invalidResponse(attrs api.Attributes, fieldErrors field.ErrorList) *admissionv1.AdmissionResponse {
	return &admissionv1.AdmissionResponse{
		Allowed: false,
		Result:  &apierrors.NewInvalid(attrs.GetKind().GroupKind(), attrs.GetName(), fieldErrors).ErrStatus,
	}
}


errorResponse

// errorResponse is the response used to capture generic errors.
func errorResponse(err error, status *metav1.Status) *admissionv1.AdmissionResponse {
	var errDetail string
	if err != nil {
		errDetail = fmt.Sprintf("%s: %v", status.Message, err)
	} else {
		errDetail = status.Message
	}
	return &admissionv1.AdmissionResponse{
		Allowed:          false,
		Result:           status,
		AuditAnnotations: map[string]string{"error": errDetail},
	}
}


GetName

func (a *AttributesRecord) GetName() string {
	return a.Name
}


GetNamespace

func (a *AttributesRecord) GetNamespace() string {
	return a.Namespace
}


GetKind

func (a *AttributesRecord) GetKind() schema.GroupVersionKind {
	return a.Kind
}


GetResource

func (a *AttributesRecord) GetResource() schema.GroupVersionResource {
	return a.Resource
}


GetSubresource

func (a *AttributesRecord) GetSubresource() string {
	return a.Subresource
}


GetOperation

func (a *AttributesRecord) GetOperation() admissionv1.Operation {
	return a.Operation
}


GetUserName

func (a *AttributesRecord) GetUserName() string {
	return a.Username
}


GetObject

func (a *AttributesRecord) GetObject() (runtime.Object, error) {
	return a.Object, nil
}


GetOldObject

func (a *AttributesRecord) GetOldObject() (runtime.Object, error) {
	return a.OldObject, nil
}


RequestAttributes

// RequestAttributes adapts an admission.Request to the Attributes interface.
func RequestAttributes(request *admissionv1.AdmissionRequest, decoder runtime.Decoder) Attributes {
	return &attributes{
		r:       request,
		decoder: decoder,
	}
}


GetName

func (a *attributes) GetName() string {
	return a.r.Name
}


GetNamespace

func (a *attributes) GetNamespace() string {
	return a.r.Namespace
}


GetKind

func (a *attributes) GetKind() schema.GroupVersionKind {
	return schema.GroupVersionKind(a.r.Kind)
}


GetResource

func (a *attributes) GetResource() schema.GroupVersionResource {
	return schema.GroupVersionResource(a.r.Resource)
}


GetSubresource

func (a *attributes) GetSubresource() string {
	return a.r.RequestSubResource
}


GetOperation

func (a *attributes) GetOperation() admissionv1.Operation {
	return a.r.Operation
}


GetUserName

func (a *attributes) GetUserName() string {
	return a.r.UserInfo.Username
}


GetObject

func (a *attributes) GetObject() (runtime.Object, error) {
	return a.decode(a.r.Object)
}


GetOldObject

func (a *attributes) GetOldObject() (runtime.Object, error) {
	return a.decode(a.r.OldObject)
}


decode

func (a *attributes) decode(in runtime.RawExtension) (runtime.Object, error) {
	if in.Raw == nil {
		return nil, nil
	}
	gvk := schema.GroupVersionKind(a.r.Kind)
	out, _, err := a.decoder.Decode(in.Raw, &gvk, nil)
	return out, err
}


String

func (v Version) String() string {
	if v.latest {
		return "latest"
	}
	return fmt.Sprintf("v%d.%d", v.major, v.minor)
}


Older

// Older returns true if this version v is older than the other.
func (v *Version) Older(other Version) bool {
	if v.latest { // Latest is always consider newer, even than future versions.
		return false
	}
	if other.latest {
		return true
	}
	if v.major != other.major {
		return v.major < other.major
	}
	return v.minor < other.minor
}


Major

func (v *Version) Major() int {
	return v.major
}


Minor

func (v *Version) Minor() int {
	return v.minor
}


Latest

func (v *Version) Latest() bool {
	return v.latest
}


MajorMinorVersion

func MajorMinorVersion(major, minor int) Version {
	return Version{major: major, minor: minor}
}


GetAPIVersion

// GetAPIVersion get the version of apiServer and return the version major and minor
func GetAPIVersion() Version {
	var err error
	v := Version{}
	apiVersion := version.Get()
	major, err := strconv.Atoi(apiVersion.Major)
	if err != nil {
		return v
	}
	// split the "normal" + and - for semver stuff to get the leading minor number
	minorString := strings.FieldsFunc(apiVersion.Minor, func(r rune) bool {
		return !unicode.IsDigit(r)
	})[0]
	minor, err := strconv.Atoi(minorString)
	if err != nil {
		return v
	}
	v = MajorMinorVersion(major, minor)
	return v
}


LatestVersion

func LatestVersion() Version {
	return Version{latest: true}
}


ParseLevel

// ParseLevel returns the level that should be evaluated.
// level must be "privileged", "baseline", or "restricted".
// if level does not match one of those strings, "restricted" and an error is returned.
func ParseLevel(level string) (Level, error) {
	switch Level(level) {
	case LevelPrivileged, LevelBaseline, LevelRestricted:
		return Level(level), nil
	default:
		return LevelRestricted, fmt.Errorf(`must be one of %s`, strings.Join(validLevels, ", "))
	}
}


Valid

// Valid checks whether the level l is a valid level.
func (l *Level) Valid() bool {
	switch *l {
	case LevelPrivileged, LevelBaseline, LevelRestricted:
		return true
	default:
		return false
	}
}


ParseVersion

// ParseVersion returns the policy version that should be evaluated.
// version must be "latest" or "v1.x".
// If version does not match one of those patterns, the latest version and an error is returned.
func ParseVersion(version string) (Version, error) {
	if version == "latest" {
		return Version{latest: true}, nil
	}
	match := versionRegexp.FindStringSubmatch(version)
	if len(match) != 2 {
		return Version{latest: true}, fmt.Errorf(`must be "latest" or "v1.x"`)
	}
	versionNumber, err := strconv.Atoi(match[1])
	if err != nil || versionNumber < 0 {
		return Version{latest: true}, fmt.Errorf(`must be "latest" or "v1.x"`)
	}
	return Version{major: 1, minor: versionNumber}, nil
}


String

func (lv LevelVersion) String() string {
	return fmt.Sprintf("%s:%s", lv.Level, lv.Version)
}


Equivalent

// Equivalent determines whether two LevelVersions are functionally equivalent. LevelVersions are
// considered equivalent if both are privileged, or both levels & versions are equal.
func (lv *LevelVersion) Equivalent(other *LevelVersion) bool {
	return (lv.Level == LevelPrivileged && other.Level == LevelPrivileged) ||
		(lv.Level == other.Level && lv.Version == other.Version)
}


String

func (p *Policy) String() string {
	return fmt.Sprintf("enforce=%#v, audit=%#v, warn=%#v", p.Enforce, p.Audit, p.Warn)
}


Equivalent

// Equivalent determines whether two policies are functionally equivalent. Policies are considered
// equivalent if all 3 modes are considered equivalent.
func (p *Policy) Equivalent(other *Policy) bool {
	return p.Enforce.Equivalent(&other.Enforce) && p.Audit.Equivalent(&other.Audit) && p.Warn.Equivalent(&other.Warn)
}


FullyPrivileged

// FullyPrivileged returns true if all 3 policy modes are privileged.
func (p *Policy) FullyPrivileged() bool {
	return p.Enforce.Level == LevelPrivileged &&
		p.Audit.Level == LevelPrivileged &&
		p.Warn.Level == LevelPrivileged
}


PolicyToEvaluate

// PolicyToEvaluate resolves the PodSecurity namespace labels to the policy for that namespace,
// falling back to the provided defaults when a label is unspecified. A valid policy is always
// returned, even when an error is returned. If labels cannot be parsed correctly, the values of
// "restricted" and "latest" are used for level and version respectively.
func PolicyToEvaluate(labels map[string]string, defaults Policy) (Policy, field.ErrorList) {
	var (
		err  error
		errs field.ErrorList

		p = defaults

		hasEnforceLevel              bool
		hasWarnLevel, hasWarnVersion bool
	)
	if len(labels) == 0 {
		return p, nil
	}
	if level, ok := labels[EnforceLevelLabel]; ok {
		p.Enforce.Level, err = ParseLevel(level)
		hasEnforceLevel = (err == nil) // Don't default warn in case of error
		errs = appendErr(errs, err, EnforceLevelLabel, level)
	}
	if version, ok := labels[EnforceVersionLabel]; ok {
		p.Enforce.Version, err = ParseVersion(version)
		errs = appendErr(errs, err, EnforceVersionLabel, version)
	}
	if level, ok := labels[AuditLevelLabel]; ok {
		p.Audit.Level, err = ParseLevel(level)
		errs = appendErr(errs, err, AuditLevelLabel, level)
		if err != nil {
			p.Audit.Level = LevelPrivileged // Fail open for audit.
		}
	}
	if version, ok := labels[AuditVersionLabel]; ok {
		p.Audit.Version, err = ParseVersion(version)
		errs = appendErr(errs, err, AuditVersionLabel, version)
	}
	if level, ok := labels[WarnLevelLabel]; ok {
		hasWarnLevel = true
		p.Warn.Level, err = ParseLevel(level)
		errs = appendErr(errs, err, WarnLevelLabel, level)
		if err != nil {
			p.Warn.Level = LevelPrivileged // Fail open for warn.
		}
	}
	if version, ok := labels[WarnVersionLabel]; ok {
		hasWarnVersion = true
		p.Warn.Version, err = ParseVersion(version)
		errs = appendErr(errs, err, WarnVersionLabel, version)
	}

	// Default warn to the enforce level when explicitly set to a more restrictive level.
	if !hasWarnLevel && hasEnforceLevel && CompareLevels(p.Enforce.Level, p.Warn.Level) > 0 {
		p.Warn.Level = p.Enforce.Level
		if !hasWarnVersion {
			p.Warn.Version = p.Enforce.Version
		}
	}

	return p, errs
}


CompareLevels

// CompareLevels returns an integer comparing two levels by strictness. The result will be 0 if
// a==b, -1 if a is less strict than b, and +1 if a is more strict than b.
func CompareLevels(a, b Level) int {
	if a == b {
		return 0
	}
	switch a {
	case LevelPrivileged:
		return -1
	case LevelRestricted:
		return 1
	default:
		if b == LevelPrivileged {
			return 1
		} else if b == LevelRestricted {
			return -1
		}
	}
	// This should only happen if both a & b are invalid levels.
	return 0
}


appendErr

// appendErr is a helper function to collect label-specific errors.
func appendErr(errs field.ErrorList, err error, label, value string) field.ErrorList {
	if err != nil {
		return append(errs, field.Invalid(labelsPath.Key(label), value, err.Error()))
	}
	return errs
}


NewOptions

func NewOptions() *Options {
	secureServing := apiserveroptions.NewSecureServingOptions()
	secureServing.ServerCert.PairName = "webhook"
	o := &Options{
		SecureServing:   *secureServing,
		InsecureServing: apiserveroptions.DeprecatedInsecureServingOptions{},
		ClientQPSLimit:  DefaultClientQPSLimit,
		ClientQPSBurst:  DefaultClientQPSBurst,
	}
	o.SecureServing.BindPort = DefaultPort
	o.InsecureServing.BindPort = DefaultInsecurePort
	return o
}


AddFlags

func (o *Options) AddFlags(fs *pflag.FlagSet) {
	fs.StringVar(&o.Kubeconfig, "kubeconfig", o.Kubeconfig, "Path to the kubeconfig file specifying how to connect to the API server. Leave empty to use an in-cluster config.")
	fs.StringVar(&o.Config, "config", o.Config, "The path to the PodSecurity configuration file.")
	fs.Float32Var(&o.ClientQPSLimit, "client-qps-limit", o.ClientQPSLimit, "Client QPS limit for throttling requests to the API server.")
	fs.IntVar(&o.ClientQPSBurst, "client-qps-burst", o.ClientQPSBurst, "Client QPS burst limit for throttling requests to the API server.")

	o.SecureServing.AddFlags(fs)
	o.InsecureServing.AddFlags(fs)
}


Validate

// Validate validates all the required options.
func (o *Options) Validate() []error {
	var errs []error

	errs = append(errs, o.SecureServing.Validate()...)
	errs = append(errs, o.InsecureServing.Validate()...)

	return errs
}


addToScheme

func addToScheme(scheme *runtime.Scheme) {
	utilruntime.Must(corev1.AddToScheme(scheme))
	utilruntime.Must(appsv1.AddToScheme(scheme))
	utilruntime.Must(batchv1.AddToScheme(scheme))
	utilruntime.Must(admissionv1.AddToScheme(scheme))
}


NewServerCommand

// NewSchedulerCommand creates a *cobra.Command object with default parameters and registryOptions
func NewServerCommand() *cobra.Command {
	opts := options.NewOptions()

	cmdName := "podsecurity-webhook"
	if executable, err := os.Executable(); err == nil {
		cmdName = filepath.Base(executable)
	}
	cmd := &cobra.Command{
		Use: cmdName,
		Long: `The PodSecurity webhook is a standalone webhook server implementing the Pod
Security Standards.`,
		RunE: func(cmd *cobra.Command, _ []string) error {
			verflag.PrintAndExitIfRequested()
			return runServer(cmd.Context(), opts)
		},
		Args: cobra.NoArgs,
	}
	opts.AddFlags(cmd.Flags())
	verflag.AddFlags(cmd.Flags())

	return cmd
}


runServer

func runServer(ctx context.Context, opts *options.Options) error {
	config, err := LoadConfig(opts)
	if err != nil {
		return err
	}
	server, err := Setup(config)
	if err != nil {
		return err
	}

	ctx, cancel := context.WithCancel(ctx)
	defer cancel()
	go func() {
		stopCh := apiserver.SetupSignalHandler()
		<-stopCh
		cancel()
	}()

	return server.Start(ctx)
}


Start

func (s *Server) Start(ctx context.Context) error {
	s.informerFactory.Start(ctx.Done())

	mux := http.NewServeMux()
	healthz.InstallHandler(mux, healthz.PingHealthz)
	healthz.InstallReadyzHandler(mux, healthz.NewInformerSyncHealthz(s.informerFactory))
	// The webhook is stateless, so it's safe to expose everything on the insecure port for
	// debugging or proxy purposes. The API server will not connect to an http webhook.
	mux.HandleFunc("/", s.HandleValidate)

	// Serve the metrics.
	mux.Handle("/metrics",
		compbasemetrics.HandlerFor(s.metricsRegistry, compbasemetrics.HandlerOpts{ErrorHandling: compbasemetrics.ContinueOnError}))

	if s.insecureServing != nil {
		if err := s.insecureServing.Serve(mux, 0, ctx.Done()); err != nil {
			return fmt.Errorf("failed to start insecure server: %w", err)
		}
	}

	var shutdownCh <-chan struct{}
	var listenerStoppedCh <-chan struct{}
	if s.secureServing != nil {
		var err error
		shutdownCh, listenerStoppedCh, err = s.secureServing.Serve(mux, 0, ctx.Done())
		if err != nil {
			return fmt.Errorf("failed to start secure server: %w", err)
		}
	}

	<-listenerStoppedCh
	klog.V(1).InfoS("[graceful-termination] HTTP Server has stopped listening")

	// Wait for graceful shutdown.
	<-shutdownCh
	klog.V(1).Info("[graceful-termination] HTTP Server is exiting")

	return nil
}


HandleValidate

func (s *Server) HandleValidate(w http.ResponseWriter, r *http.Request) {
	defer utilruntime.HandleCrash(func(_ interface{}) {
		// Assume the crash happened before the response was written.
		http.Error(w, "internal server error", http.StatusInternalServerError)
	})

	var (
		body []byte
		err  error
		ctx  = r.Context()
	)

	if timeout, ok, err := parseTimeout(r); err != nil {
		// Ignore an invalid timeout.
		klog.V(2).InfoS("Invalid timeout", "error", err)
	} else if ok {
		var cancel context.CancelFunc
		ctx, cancel = context.WithTimeout(ctx, timeout)
		defer cancel()
	}

	if r.Body == nil || r.Body == http.NoBody {
		err = errors.New("request body is empty")
		klog.ErrorS(err, "bad request")
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	defer r.Body.Close()
	limitedReader := &io.LimitedReader{R: r.Body, N: maxRequestSize}
	if body, err = ioutil.ReadAll(limitedReader); err != nil {
		klog.ErrorS(err, "unable to read the body from the incoming request")
		http.Error(w, "unable to read the body from the incoming request", http.StatusBadRequest)
		return
	}
	if limitedReader.N <= 0 {
		klog.ErrorS(err, "unable to read the body from the incoming request; limit reached")
		http.Error(w, fmt.Sprintf("request entity is too large; limit is %d bytes", maxRequestSize), http.StatusRequestEntityTooLarge)
		return
	}

	// verify the content type is accurate
	if contentType := r.Header.Get("Content-Type"); contentType != "application/json" {
		err = fmt.Errorf("contentType=%s, expected application/json", contentType)
		klog.ErrorS(err, "unable to process a request with an unknown content type", "contentType", contentType)
		http.Error(w, "unable to process a request with a non-json content type", http.StatusBadRequest)
		return
	}

	v1AdmissionReviewKind := admissionv1.SchemeGroupVersion.WithKind("AdmissionReview")
	reviewObject, gvk, err := codecs.UniversalDeserializer().Decode(body, &v1AdmissionReviewKind, nil)
	if err != nil {
		klog.ErrorS(err, "unable to decode the request")
		http.Error(w, "unable to decode the request", http.StatusBadRequest)
		return
	}
	if *gvk != v1AdmissionReviewKind {
		klog.InfoS("Unexpected AdmissionReview kind", "kind", gvk.String())
		http.Error(w, fmt.Sprintf("unexpected AdmissionReview kind: %s", gvk.String()), http.StatusBadRequest)
		return
	}
	review, ok := reviewObject.(*admissionv1.AdmissionReview)
	if !ok {
		klog.InfoS("Failed admissionv1.AdmissionReview type assertion")
		http.Error(w, "unexpected AdmissionReview type", http.StatusBadRequest)
	}
	klog.V(1).InfoS("received request", "UID", review.Request.UID, "kind", review.Request.Kind, "resource", review.Request.Resource)

	attributes := api.RequestAttributes(review.Request, codecs.UniversalDeserializer())
	response := s.delegate.Validate(ctx, attributes)
	response.UID = review.Request.UID // Response UID must match request UID
	review.Response = response
	writeResponse(w, review)
}


LoadConfig

// LoadConfig loads the Config from the Options.
func LoadConfig(opts *options.Options) (*Config, error) {
	if errs := opts.Validate(); len(errs) > 0 {
		return nil, utilerrors.NewAggregate(errs)
	}

	var c Config
	opts.SecureServing.ApplyTo(&c.SecureServing)
	opts.InsecureServing.ApplyTo(&c.InsecureServing)

	// Load Kube Client
	kubeConfig, err := clientcmd.BuildConfigFromFlags("", opts.Kubeconfig)
	if err != nil {
		return nil, err
	}
	kubeConfig.QPS = opts.ClientQPSLimit
	kubeConfig.Burst = opts.ClientQPSBurst
	c.KubeConfig = restclient.AddUserAgent(kubeConfig, "podsecurity-webhook")

	// Load PodSecurity config
	c.PodSecurityConfig, err = podsecurityconfigloader.LoadFromFile(opts.Config)
	if err != nil {
		return nil, err
	}

	return &c, nil
}


Setup

// Setup creates an Admission object to handle the admission logic.
func Setup(c *Config) (*Server, error) {
	s := &Server{
		secureServing:   c.SecureServing,
		insecureServing: c.InsecureServing,
	}

	if s.secureServing == nil && s.insecureServing == nil {
		return nil, errors.New("no serving info configured")
	}

	client, err := clientset.NewForConfig(c.KubeConfig)
	if err != nil {
		return nil, err
	}
	s.informerFactory = kubeinformers.NewSharedInformerFactory(client, 0 /* no resync */)
	namespaceInformer := s.informerFactory.Core().V1().Namespaces()
	namespaceLister := namespaceInformer.Lister()

	evaluator, err := policy.NewEvaluator(policy.DefaultChecks())
	if err != nil {
		return nil, fmt.Errorf("could not create PodSecurityRegistry: %w", err)
	}
	metrics := metrics.NewPrometheusRecorder(api.GetAPIVersion())
	s.metricsRegistry = compbasemetrics.NewKubeRegistry()
	metrics.MustRegister(s.metricsRegistry.MustRegister)

	s.delegate = &admission.Admission{
		Configuration:    c.PodSecurityConfig,
		Evaluator:        evaluator,
		Metrics:          metrics,
		PodSpecExtractor: admission.DefaultPodSpecExtractor{},
		PodLister:        admission.PodListerFromClient(client),
		NamespaceGetter:  admission.NamespaceGetterFromListerAndClient(namespaceLister, client),
	}

	if err := s.delegate.CompleteConfiguration(); err != nil {
		return nil, fmt.Errorf("configuration error: %w", err)
	}
	if err := s.delegate.ValidateConfiguration(); err != nil {
		return nil, fmt.Errorf("invalid configuration: %w", err)
	}

	return s, nil
}


writeResponse

func writeResponse(w http.ResponseWriter, review *admissionv1.AdmissionReview) {
	// Webhooks should always respond with a 200 HTTP status code when an AdmissionResponse can be sent.
	// In an error case, the true status code is captured in the response.result.code
	if err := json.NewEncoder(w).Encode(review); err != nil {
		klog.ErrorS(err, "Failed to encode response")
		// Unable to send an AdmissionResponse, fall back to an HTTP error.
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}


parseTimeout

// parseTimeout parses the given HTTP request URL and extracts the timeout query parameter
// value if specified by the user.
// If a timeout is not specified the function returns false and err is set to nil
// If the value specified is malformed then the function returns false and err is set
func parseTimeout(req *http.Request) (time.Duration, bool, error) {
	value := req.URL.Query().Get("timeout")
	if value == "" {
		return 0, false, nil
	}

	timeout, err := time.ParseDuration(value)
	if err != nil {
		return 0, false, fmt.Errorf("invalid timeout query: %w", err)
	}

	return timeout, true, nil
}


main

func main() {
	command := server.NewServerCommand()
	code := cli.Run(command)
	os.Exit(code)
}


NewPrometheusRecorder

func NewPrometheusRecorder(version api.Version) *PrometheusRecorder {
	errorsCounter := metrics.NewCounterVec(
		&metrics.CounterOpts{
			Name:           "pod_security_errors_total",
			Help:           "Number of errors preventing normal evaluation. Non-fatal errors may result in the latest restricted profile being used for evaluation.",
			StabilityLevel: metrics.ALPHA,
		},
		[]string{"fatal", "request_operation", "resource", "subresource"},
	)

	return &PrometheusRecorder{
		apiVersion:         version,
		evaluationsCounter: newEvaluationsCounter(),
		exemptionsCounter:  newExemptionsCounter(),
		errorsCounter:      errorsCounter,
	}
}


MustRegister

func (r *PrometheusRecorder) MustRegister(registerFunc func(...metrics.Registerable)) {
	registerFunc(r.evaluationsCounter)
	registerFunc(r.exemptionsCounter)
	registerFunc(r.errorsCounter)
}


Reset

func (r *PrometheusRecorder) Reset() {
	r.evaluationsCounter.Reset()
	r.exemptionsCounter.Reset()
	r.errorsCounter.Reset()
}


RecordEvaluation

func (r *PrometheusRecorder) RecordEvaluation(decision Decision, policy api.LevelVersion, evalMode Mode, attrs api.Attributes) {
	var version string
	if policy.Version.Latest() || policy.Level == api.LevelPrivileged { // Privileged is always effectively latest.
		version = "latest"
	} else {
		if !r.apiVersion.Older(policy.Version) {
			version = policy.Version.String()
		} else {
			version = "future"
		}
	}

	r.evaluationsCounter.CachedInc(evaluationsLabels{
		decision:    string(decision),
		level:       string(policy.Level),
		version:     version,
		mode:        string(evalMode),
		operation:   operationLabel(attrs.GetOperation()),
		resource:    resourceLabel(attrs.GetResource()),
		subresource: attrs.GetSubresource(),
	})
}


RecordExemption

func (r *PrometheusRecorder) RecordExemption(attrs api.Attributes) {
	r.exemptionsCounter.CachedInc(exemptionsLabels{
		operation:   operationLabel(attrs.GetOperation()),
		resource:    resourceLabel(attrs.GetResource()),
		subresource: attrs.GetSubresource(),
	})
}


RecordError

func (r *PrometheusRecorder) RecordError(fatal bool, attrs api.Attributes) {
	r.errorsCounter.WithLabelValues(
		strconv.FormatBool(fatal),
		operationLabel(attrs.GetOperation()),
		resourceLabel(attrs.GetResource()),
		attrs.GetSubresource(),
	).Inc()
}


resourceLabel

func resourceLabel(resource schema.GroupVersionResource) string {
	switch resource.GroupResource() {
	case podResource:
		return "pod"
	case namespaceResource:
		return "namespace"
	default:
		// Assume any other resource is a valid input to pod-security, and therefore a controller.
		return "controller"
	}
}


operationLabel

func operationLabel(op admissionv1.Operation) string {
	switch op {
	case admissionv1.Create:
		return "create"
	case admissionv1.Update:
		return "update"
	default:
		// This is a slower operation, but never used in the default implementation.
		return strings.ToLower(string(op))
	}
}


labels

func (l *evaluationsLabels) labels() []string {
	return []string{l.decision, l.level, l.version, l.mode, l.operation, l.resource, l.subresource}
}


func (l *exemptionsLabels) labels() []string {
	return []string{l.operation, l.resource, l.subresource}
}


newEvaluationsCounter

func newEvaluationsCounter() *evaluationsCounter {
	return &evaluationsCounter{
		CounterVec: metrics.NewCounterVec(
			&metrics.CounterOpts{
				Name:           "pod_security_evaluations_total",
				Help:           "Number of policy evaluations that occurred, not counting ignored or exempt requests.",
				StabilityLevel: metrics.ALPHA,
			},
			[]string{"decision", "policy_level", "policy_version", "mode", "request_operation", "resource", "subresource"},
		),
		cache: make(map[evaluationsLabels]metrics.CounterMetric),
	}
}


CachedInc

func (c *evaluationsCounter) CachedInc(l evaluationsLabels) {
	c.cacheLock.RLock()
	defer c.cacheLock.RUnlock()

	if cachedCounter, ok := c.cache[l]; ok {
		cachedCounter.Inc()
	} else {
		c.CounterVec.WithLabelValues(l.labels()...).Inc()
	}
}


Create

func (c *evaluationsCounter) Create(version *semver.Version) bool {
	c.cacheLock.Lock()
	defer c.cacheLock.Unlock()
	if c.CounterVec.Create(version) {
		c.populateCache()
		return true
	} else {
		return false
	}
}


Reset

func (c *evaluationsCounter) Reset() {
	c.cacheLock.Lock()
	defer c.cacheLock.Unlock()
	c.CounterVec.Reset()
	c.populateCache()
}


populateCache

func (c *evaluationsCounter) populateCache() {
	labelsToCache := []evaluationsLabels{
		{decision: "allow", level: "privileged", version: "latest", mode: "enforce", operation: "create", resource: "pod", subresource: ""},
		{decision: "allow", level: "privileged", version: "latest", mode: "enforce", operation: "update", resource: "pod", subresource: ""},
	}
	for _, l := range labelsToCache {
		c.cache[l] = c.CounterVec.WithLabelValues(l.labels()...)
	}
}


newExemptionsCounter

func newExemptionsCounter() *exemptionsCounter {
	return &exemptionsCounter{
		CounterVec: metrics.NewCounterVec(
			&metrics.CounterOpts{
				Name:           "pod_security_exemptions_total",
				Help:           "Number of exempt requests, not counting ignored or out of scope requests.",
				StabilityLevel: metrics.ALPHA,
			},
			[]string{"request_operation", "resource", "subresource"},
		),
		cache: make(map[exemptionsLabels]metrics.CounterMetric),
	}
}


CachedInc

func (c *exemptionsCounter) CachedInc(l exemptionsLabels) {
	c.cacheLock.RLock()
	defer c.cacheLock.RUnlock()

	if cachedCounter, ok := c.cache[l]; ok {
		cachedCounter.Inc()
	} else {
		c.CounterVec.WithLabelValues(l.labels()...).Inc()
	}
}


Create

func (c *exemptionsCounter) Create(version *semver.Version) bool {
	c.cacheLock.Lock()
	defer c.cacheLock.Unlock()
	if c.CounterVec.Create(version) {
		c.populateCache()
		return true
	} else {
		return false
	}
}


Reset

func (c *exemptionsCounter) Reset() {
	c.cacheLock.Lock()
	defer c.cacheLock.Unlock()
	c.CounterVec.Reset()
	c.populateCache()
}


populateCache

func (c *exemptionsCounter) populateCache() {
	labelsToCache := []exemptionsLabels{
		{operation: "create", resource: "pod", subresource: ""},
		{operation: "update", resource: "pod", subresource: ""},
		{operation: "create", resource: "controller", subresource: ""},
		{operation: "update", resource: "controller", subresource: ""},
	}
	for _, l := range labelsToCache {
		c.cache[l] = c.CounterVec.WithLabelValues(l.labels()...)
	}
}


init

func init() {
	addCheck(CheckAllowPrivilegeEscalation)
}


CheckAllowPrivilegeEscalation

// CheckAllowPrivilegeEscalation returns a restricted level check
// that requires allowPrivilegeEscalation=false in 1.8+
func CheckAllowPrivilegeEscalation() Check {
	return Check{
		ID:    "allowPrivilegeEscalation",
		Level: api.LevelRestricted,
		Versions: []VersionedCheck{
			{
				// Field added in 1.8:
				// https://github.com/kubernetes/kubernetes/blob/v1.8.0/staging/src/k8s.io/api/core/v1/types.go#L4797-L4804
				MinimumVersion: api.MajorMinorVersion(1, 8),
				CheckPod:       allowPrivilegeEscalation_1_8,
			},
			{
				// Starting 1.25, windows pods would be exempted from this check using pod.spec.os field when set to windows.
				MinimumVersion: api.MajorMinorVersion(1, 25),
				CheckPod:       allowPrivilegeEscalation_1_25,
			},
		},
	}
}


func allowPrivilegeEscalation_1_8(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {
	var badContainers []string
	visitContainers(podSpec, func(container *corev1.Container) {
		if container.SecurityContext == nil || container.SecurityContext.AllowPrivilegeEscalation == nil || *container.SecurityContext.AllowPrivilegeEscalation {
			badContainers = append(badContainers, container.Name)
		}
	})

	if len(badContainers) > 0 {
		return CheckResult{
			Allowed:         false,
			ForbiddenReason: "allowPrivilegeEscalation != false",
			ForbiddenDetail: fmt.Sprintf(
				"%s %s must set securityContext.allowPrivilegeEscalation=false",
				pluralize("container", "containers", len(badContainers)),
				joinQuote(badContainers),
			),
		}
	}
	return CheckResult{Allowed: true}
}


func allowPrivilegeEscalation_1_25(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {
	// Pod API validation would have failed if podOS == Windows and if privilegeEscalation has been set.
	// We can admit the Windows pod even if privilegeEscalation has not been set.
	if podSpec.OS != nil && podSpec.OS.Name == corev1.Windows {
		return CheckResult{Allowed: true}
	}
	return allowPrivilegeEscalation_1_8(podMetadata, podSpec)
}


init

/*
On supported hosts, the 'runtime/default' AppArmor profile is applied by default.
The baseline policy should prevent overriding or disabling the default AppArmor
profile, or restrict overrides to an allowed set of profiles.

**Restricted Fields:**
metadata.annotations['container.apparmor.security.beta.kubernetes.io/*']

**Allowed Values:** 'runtime/default', 'localhost/*', empty, undefined
*/
func init() {
	addCheck(CheckAppArmorProfile)
}


CheckAppArmorProfile

// CheckAppArmorProfile returns a baseline level check
// that limits the value of AppArmor profiles in 1.0+
func CheckAppArmorProfile() Check {
	return Check{
		ID:    "appArmorProfile",
		Level: api.LevelBaseline,
		Versions: []VersionedCheck{
			{
				MinimumVersion: api.MajorMinorVersion(1, 0),
				CheckPod:       appArmorProfile_1_0,
			},
		},
	}
}


allowedProfile

func allowedProfile(profile string) bool {
	return len(profile) == 0 ||
		profile == corev1.AppArmorBetaProfileRuntimeDefault ||
		strings.HasPrefix(profile, corev1.AppArmorBetaProfileNamePrefix)
}


func appArmorProfile_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {
	var forbiddenValues []string
	for k, v := range podMetadata.Annotations {
		if strings.HasPrefix(k, corev1.AppArmorBetaContainerAnnotationKeyPrefix) && !allowedProfile(v) {
			forbiddenValues = append(forbiddenValues, fmt.Sprintf("%s=%q", k, v))
		}
	}
	if len(forbiddenValues) > 0 {
		sort.Strings(forbiddenValues)
		return CheckResult{
			Allowed:         false,
			ForbiddenReason: pluralize("forbidden AppArmor profile", "forbidden AppArmor profiles", len(forbiddenValues)),
			ForbiddenDetail: strings.Join(forbiddenValues, ", "),
		}
	}

	return CheckResult{Allowed: true}
}


init

func init() {
	addCheck(CheckCapabilitiesBaseline)
}


CheckCapabilitiesBaseline

// CheckCapabilitiesBaseline returns a baseline level check
// that limits the capabilities that can be added in 1.0+
func CheckCapabilitiesBaseline() Check {
	return Check{
		ID:    checkCapabilitiesBaselineID,
		Level: api.LevelBaseline,
		Versions: []VersionedCheck{
			{
				MinimumVersion: api.MajorMinorVersion(1, 0),
				CheckPod:       capabilitiesBaseline_1_0,
			},
		},
	}
}


func capabilitiesBaseline_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {
	var badContainers []string
	nonDefaultCapabilities := sets.NewString()
	visitContainers(podSpec, func(container *corev1.Container) {
		if container.SecurityContext != nil && container.SecurityContext.Capabilities != nil {
			valid := true
			for _, c := range container.SecurityContext.Capabilities.Add {
				if !capabilities_allowed_1_0.Has(string(c)) {
					valid = false
					nonDefaultCapabilities.Insert(string(c))
				}
			}
			if !valid {
				badContainers = append(badContainers, container.Name)
			}
		}
	})

	if len(badContainers) > 0 {
		return CheckResult{
			Allowed:         false,
			ForbiddenReason: "non-default capabilities",
			ForbiddenDetail: fmt.Sprintf(
				"%s %s must not include %s in securityContext.capabilities.add",
				pluralize("container", "containers", len(badContainers)),
				joinQuote(badContainers),
				joinQuote(nonDefaultCapabilities.List()),
			),
		}
	}
	return CheckResult{Allowed: true}
}


init

func init() {
	addCheck(CheckCapabilitiesRestricted)
}


CheckCapabilitiesRestricted

// CheckCapabilitiesRestricted returns a restricted level check
// that ensures ALL capabilities are dropped in 1.22+
func CheckCapabilitiesRestricted() Check {
	return Check{
		ID:    "capabilities_restricted",
		Level: api.LevelRestricted,
		Versions: []VersionedCheck{
			{
				MinimumVersion:   api.MajorMinorVersion(1, 22),
				CheckPod:         capabilitiesRestricted_1_22,
				OverrideCheckIDs: []CheckID{checkCapabilitiesBaselineID},
			},
			// Starting 1.25, windows pods would be exempted from this check using pod.spec.os field when set to windows.
			{
				MinimumVersion:   api.MajorMinorVersion(1, 25),
				CheckPod:         capabilitiesRestricted_1_25,
				OverrideCheckIDs: []CheckID{checkCapabilitiesBaselineID},
			},
		},
	}
}


func capabilitiesRestricted_1_22(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {
	var (
		containersMissingDropAll  []string
		containersAddingForbidden []string
		forbiddenCapabilities     = sets.NewString()
	)

	visitContainers(podSpec, func(container *corev1.Container) {
		if container.SecurityContext == nil || container.SecurityContext.Capabilities == nil {
			containersMissingDropAll = append(containersMissingDropAll, container.Name)
			return
		}

		droppedAll := false
		for _, c := range container.SecurityContext.Capabilities.Drop {
			if c == capabilityAll {
				droppedAll = true
				break
			}
		}
		if !droppedAll {
			containersMissingDropAll = append(containersMissingDropAll, container.Name)
		}

		addedForbidden := false
		for _, c := range container.SecurityContext.Capabilities.Add {
			if c != capabilityNetBindService {
				addedForbidden = true
				forbiddenCapabilities.Insert(string(c))
			}
		}
		if addedForbidden {
			containersAddingForbidden = append(containersAddingForbidden, container.Name)
		}
	})
	var forbiddenDetails []string
	if len(containersMissingDropAll) > 0 {
		forbiddenDetails = append(forbiddenDetails, fmt.Sprintf(
			`%s %s must set securityContext.capabilities.drop=["ALL"]`,
			pluralize("container", "containers", len(containersMissingDropAll)),
			joinQuote(containersMissingDropAll)))
	}
	if len(containersAddingForbidden) > 0 {
		forbiddenDetails = append(forbiddenDetails, fmt.Sprintf(
			`%s %s must not include %s in securityContext.capabilities.add`,
			pluralize("container", "containers", len(containersAddingForbidden)),
			joinQuote(containersAddingForbidden),
			joinQuote(forbiddenCapabilities.List())))
	}
	if len(forbiddenDetails) > 0 {
		return CheckResult{
			Allowed:         false,
			ForbiddenReason: "unrestricted capabilities",
			ForbiddenDetail: strings.Join(forbiddenDetails, "; "),
		}
	}
	return CheckResult{Allowed: true}
}


func capabilitiesRestricted_1_25(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {
	// Pod API validation would have failed if podOS == Windows and if capabilities have been set.
	// We can admit the Windows pod even if capabilities has not been set.
	if podSpec.OS != nil && podSpec.OS.Name == corev1.Windows {
		return CheckResult{Allowed: true}
	}
	return capabilitiesRestricted_1_22(podMetadata, podSpec)
}


init

func init() {
	addCheck(CheckHostNamespaces)
}


CheckHostNamespaces

// CheckHostNamespaces returns a baseline level check
// that prohibits host namespaces in 1.0+
func CheckHostNamespaces() Check {
	return Check{
		ID:    "hostNamespaces",
		Level: api.LevelBaseline,
		Versions: []VersionedCheck{
			{
				MinimumVersion: api.MajorMinorVersion(1, 0),
				CheckPod:       hostNamespaces_1_0,
			},
		},
	}
}


func hostNamespaces_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {
	var hostNamespaces []string

	if podSpec.HostNetwork {
		hostNamespaces = append(hostNamespaces, "hostNetwork=true")
	}

	if podSpec.HostPID {
		hostNamespaces = append(hostNamespaces, "hostPID=true")
	}

	if podSpec.HostIPC {
		hostNamespaces = append(hostNamespaces, "hostIPC=true")
	}

	if len(hostNamespaces) > 0 {
		return CheckResult{
			Allowed:         false,
			ForbiddenReason: "host namespaces",
			ForbiddenDetail: strings.Join(hostNamespaces, ", "),
		}
	}

	return CheckResult{Allowed: true}
}


init

func init() {
	addCheck(CheckHostPathVolumes)
}


CheckHostPathVolumes

// CheckHostPathVolumes returns a baseline level check
// that requires hostPath=undefined/null in 1.0+
func CheckHostPathVolumes() Check {
	return Check{
		ID:    checkHostPathVolumesID,
		Level: api.LevelBaseline,
		Versions: []VersionedCheck{
			{
				MinimumVersion: api.MajorMinorVersion(1, 0),
				CheckPod:       hostPathVolumes_1_0,
			},
		},
	}
}


func hostPathVolumes_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {
	var hostVolumes []string

	for _, volume := range podSpec.Volumes {
		if volume.HostPath != nil {
			hostVolumes = append(hostVolumes, volume.Name)
		}
	}

	if len(hostVolumes) > 0 {
		return CheckResult{
			Allowed:         false,
			ForbiddenReason: "hostPath volumes",
			ForbiddenDetail: fmt.Sprintf("%s %s", pluralize("volume", "volumes", len(hostVolumes)), joinQuote(hostVolumes)),
		}
	}

	return CheckResult{Allowed: true}
}


init

func init() {
	addCheck(CheckHostPorts)
}


CheckHostPorts

// CheckHostPorts returns a baseline level check
// that forbids any host ports in 1.0+
func CheckHostPorts() Check {
	return Check{
		ID:    "hostPorts",
		Level: api.LevelBaseline,
		Versions: []VersionedCheck{
			{
				MinimumVersion: api.MajorMinorVersion(1, 0),
				CheckPod:       hostPorts_1_0,
			},
		},
	}
}


func hostPorts_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {
	var badContainers []string
	forbiddenHostPorts := sets.NewString()
	visitContainers(podSpec, func(container *corev1.Container) {
		valid := true
		for _, c := range container.Ports {
			if c.HostPort != 0 {
				valid = false
				forbiddenHostPorts.Insert(strconv.Itoa(int(c.HostPort)))
			}
		}
		if !valid {
			badContainers = append(badContainers, container.Name)
		}
	})

	if len(badContainers) > 0 {
		return CheckResult{
			Allowed:         false,
			ForbiddenReason: "hostPort",
			ForbiddenDetail: fmt.Sprintf(
				"%s %s %s %s %s",
				pluralize("container", "containers", len(badContainers)),
				joinQuote(badContainers),
				pluralize("uses", "use", len(badContainers)),
				pluralize("hostPort", "hostPorts", len(forbiddenHostPorts)),
				strings.Join(forbiddenHostPorts.List(), ", "),
			),
		}
	}
	return CheckResult{Allowed: true}
}


init

func init() {
	addCheck(CheckPrivileged)
}


CheckPrivileged

// CheckPrivileged returns a baseline level check
// that forbids privileged=true in 1.0+
func CheckPrivileged() Check {
	return Check{
		ID:    "privileged",
		Level: api.LevelBaseline,
		Versions: []VersionedCheck{
			{
				MinimumVersion: api.MajorMinorVersion(1, 0),
				CheckPod:       privileged_1_0,
			},
		},
	}
}


func privileged_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {
	var badContainers []string
	visitContainers(podSpec, func(container *corev1.Container) {
		if container.SecurityContext != nil && container.SecurityContext.Privileged != nil && *container.SecurityContext.Privileged {
			badContainers = append(badContainers, container.Name)
		}
	})
	if len(badContainers) > 0 {
		return CheckResult{
			Allowed:         false,
			ForbiddenReason: "privileged",
			ForbiddenDetail: fmt.Sprintf(
				`%s %s must not set securityContext.privileged=true`,
				pluralize("container", "containers", len(badContainers)),
				joinQuote(badContainers),
			),
		}
	}
	return CheckResult{Allowed: true}
}


init

func init() {
	addCheck(CheckProcMount)
}


CheckProcMount

// CheckProcMount returns a baseline level check that restricts
// setting the value of securityContext.procMount to DefaultProcMount
// in 1.0+
func CheckProcMount() Check {
	return Check{
		ID:    "procMount",
		Level: api.LevelBaseline,
		Versions: []VersionedCheck{
			{
				MinimumVersion: api.MajorMinorVersion(1, 0),
				CheckPod:       procMount_1_0,
			},
		},
	}
}


func procMount_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {
	var badContainers []string
	forbiddenProcMountTypes := sets.NewString()
	visitContainers(podSpec, func(container *corev1.Container) {
		// allow if the security context is nil.
		if container.SecurityContext == nil {
			return
		}
		// allow if proc mount is not set.
		if container.SecurityContext.ProcMount == nil {
			return
		}
		// check if the value of the proc mount type is valid.
		if *container.SecurityContext.ProcMount != corev1.DefaultProcMount {
			badContainers = append(badContainers, container.Name)
			forbiddenProcMountTypes.Insert(string(*container.SecurityContext.ProcMount))
		}
	})
	if len(badContainers) > 0 {
		return CheckResult{
			Allowed:         false,
			ForbiddenReason: "procMount",
			ForbiddenDetail: fmt.Sprintf(
				"%s %s must not set securityContext.procMount to %s",
				pluralize("container", "containers", len(badContainers)),
				joinQuote(badContainers),
				joinQuote(forbiddenProcMountTypes.List()),
			),
		}
	}
	return CheckResult{Allowed: true}
}


init

func init() {
	addCheck(CheckRestrictedVolumes)
}


CheckRestrictedVolumes

// CheckRestrictedVolumes returns a restricted level check
// that limits usage of specific volume types in 1.0+
func CheckRestrictedVolumes() Check {
	return Check{
		ID:    "restrictedVolumes",
		Level: api.LevelRestricted,
		Versions: []VersionedCheck{
			{
				MinimumVersion:   api.MajorMinorVersion(1, 0),
				CheckPod:         restrictedVolumes_1_0,
				OverrideCheckIDs: []CheckID{checkHostPathVolumesID},
			},
		},
	}
}


func restrictedVolumes_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {
	var badVolumes []string
	badVolumeTypes := sets.NewString()

	for _, volume := range podSpec.Volumes {
		switch {
		case volume.ConfigMap != nil,
			volume.CSI != nil,
			volume.DownwardAPI != nil,
			volume.EmptyDir != nil,
			volume.Ephemeral != nil,
			volume.PersistentVolumeClaim != nil,
			volume.Projected != nil,
			volume.Secret != nil:
			continue

		default:
			badVolumes = append(badVolumes, volume.Name)

			switch {
			case volume.HostPath != nil:
				badVolumeTypes.Insert("hostPath")
			case volume.GCEPersistentDisk != nil:
				badVolumeTypes.Insert("gcePersistentDisk")
			case volume.AWSElasticBlockStore != nil:
				badVolumeTypes.Insert("awsElasticBlockStore")
			case volume.GitRepo != nil:
				badVolumeTypes.Insert("gitRepo")
			case volume.NFS != nil:
				badVolumeTypes.Insert("nfs")
			case volume.ISCSI != nil:
				badVolumeTypes.Insert("iscsi")
			case volume.Glusterfs != nil:
				badVolumeTypes.Insert("glusterfs")
			case volume.RBD != nil:
				badVolumeTypes.Insert("rbd")
			case volume.FlexVolume != nil:
				badVolumeTypes.Insert("flexVolume")
			case volume.Cinder != nil:
				badVolumeTypes.Insert("cinder")
			case volume.CephFS != nil:
				badVolumeTypes.Insert("cephfs")
			case volume.Flocker != nil:
				badVolumeTypes.Insert("flocker")
			case volume.FC != nil:
				badVolumeTypes.Insert("fc")
			case volume.AzureFile != nil:
				badVolumeTypes.Insert("azureFile")
			case volume.VsphereVolume != nil:
				badVolumeTypes.Insert("vsphereVolume")
			case volume.Quobyte != nil:
				badVolumeTypes.Insert("quobyte")
			case volume.AzureDisk != nil:
				badVolumeTypes.Insert("azureDisk")
			case volume.PhotonPersistentDisk != nil:
				badVolumeTypes.Insert("photonPersistentDisk")
			case volume.PortworxVolume != nil:
				badVolumeTypes.Insert("portworxVolume")
			case volume.ScaleIO != nil:
				badVolumeTypes.Insert("scaleIO")
			case volume.StorageOS != nil:
				badVolumeTypes.Insert("storageos")
			default:
				badVolumeTypes.Insert("unknown")
			}
		}
	}

	if len(badVolumes) > 0 {
		return CheckResult{
			Allowed:         false,
			ForbiddenReason: "restricted volume types",
			ForbiddenDetail: fmt.Sprintf(
				"%s %s %s %s %s",
				pluralize("volume", "volumes", len(badVolumes)),
				joinQuote(badVolumes),
				pluralize("uses", "use", len(badVolumes)),
				pluralize("restricted volume type", "restricted volume types", len(badVolumeTypes)),
				joinQuote(badVolumeTypes.List()),
			),
		}
	}

	return CheckResult{Allowed: true}
}


init

func init() {
	addCheck(CheckRunAsNonRoot)
}


CheckRunAsNonRoot

// CheckRunAsNonRoot returns a restricted level check
// that requires runAsNonRoot=true in 1.0+
func CheckRunAsNonRoot() Check {
	return Check{
		ID:    "runAsNonRoot",
		Level: api.LevelRestricted,
		Versions: []VersionedCheck{
			{
				MinimumVersion: api.MajorMinorVersion(1, 0),
				CheckPod:       runAsNonRoot_1_0,
			},
		},
	}
}


func runAsNonRoot_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {
	// things that explicitly set runAsNonRoot=false
	var badSetters []string

	podRunAsNonRoot := false
	if podSpec.SecurityContext != nil && podSpec.SecurityContext.RunAsNonRoot != nil {
		if !*podSpec.SecurityContext.RunAsNonRoot {
			badSetters = append(badSetters, "pod")
		} else {
			podRunAsNonRoot = true
		}
	}

	// containers that explicitly set runAsNonRoot=false
	var explicitlyBadContainers []string
	// containers that didn't set runAsNonRoot and aren't caught by a pod-level runAsNonRoot=true
	var implicitlyBadContainers []string

	visitContainers(podSpec, func(container *corev1.Container) {
		if container.SecurityContext != nil && container.SecurityContext.RunAsNonRoot != nil {
			// container explicitly set runAsNonRoot
			if !*container.SecurityContext.RunAsNonRoot {
				// container explicitly set runAsNonRoot to a bad value
				explicitlyBadContainers = append(explicitlyBadContainers, container.Name)
			}
		} else {
			// container did not explicitly set runAsNonRoot
			if !podRunAsNonRoot {
				// no pod-level runAsNonRoot=true, so this container implicitly has a bad value
				implicitlyBadContainers = append(implicitlyBadContainers, container.Name)
			}
		}
	})

	if len(explicitlyBadContainers) > 0 {
		badSetters = append(
			badSetters,
			fmt.Sprintf(
				"%s %s",
				pluralize("container", "containers", len(explicitlyBadContainers)),
				joinQuote(explicitlyBadContainers),
			),
		)
	}
	// pod or containers explicitly set runAsNonRoot=false
	if len(badSetters) > 0 {
		return CheckResult{
			Allowed:         false,
			ForbiddenReason: "runAsNonRoot != true",
			ForbiddenDetail: fmt.Sprintf("%s must not set securityContext.runAsNonRoot=false", strings.Join(badSetters, " and ")),
		}
	}

	// pod didn't set runAsNonRoot and not all containers opted into runAsNonRoot
	if len(implicitlyBadContainers) > 0 {
		return CheckResult{
			Allowed:         false,
			ForbiddenReason: "runAsNonRoot != true",
			ForbiddenDetail: fmt.Sprintf(
				"pod or %s %s must set securityContext.runAsNonRoot=true",
				pluralize("container", "containers", len(implicitlyBadContainers)),
				joinQuote(implicitlyBadContainers),
			),
		}
	}

	return CheckResult{Allowed: true}
}


init

func init() {
	addCheck(CheckRunAsUser)
}


CheckRunAsUser

// CheckRunAsUser returns a restricted level check
// that forbides runAsUser=0 in 1.23+
func CheckRunAsUser() Check {
	return Check{
		ID:    "runAsUser",
		Level: api.LevelRestricted,
		Versions: []VersionedCheck{
			{
				MinimumVersion: api.MajorMinorVersion(1, 23),
				CheckPod:       runAsUser_1_23,
			},
		},
	}
}


func runAsUser_1_23(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {
	// things that explicitly set runAsUser=0
	var badSetters []string

	if podSpec.SecurityContext != nil && podSpec.SecurityContext.RunAsUser != nil && *podSpec.SecurityContext.RunAsUser == 0 {
		badSetters = append(badSetters, "pod")
	}

	// containers that explicitly set runAsUser=0
	var explicitlyBadContainers []string

	visitContainers(podSpec, func(container *corev1.Container) {
		if container.SecurityContext != nil && container.SecurityContext.RunAsUser != nil && *container.SecurityContext.RunAsUser == 0 {
			explicitlyBadContainers = append(explicitlyBadContainers, container.Name)
		}
	})

	if len(explicitlyBadContainers) > 0 {
		badSetters = append(
			badSetters,
			fmt.Sprintf(
				"%s %s",
				pluralize("container", "containers", len(explicitlyBadContainers)),
				joinQuote(explicitlyBadContainers),
			),
		)
	}
	// pod or containers explicitly set runAsUser=0
	if len(badSetters) > 0 {
		return CheckResult{
			Allowed:         false,
			ForbiddenReason: "runAsUser=0",
			ForbiddenDetail: fmt.Sprintf("%s must not set runAsUser=0", strings.Join(badSetters, " and ")),
		}
	}

	return CheckResult{Allowed: true}
}


init

func init() {
	addCheck(CheckSELinuxOptions)
}


CheckSELinuxOptions

// CheckSELinuxOptions returns a baseline level check
// that limits seLinuxOptions type, user, and role values in 1.0+
func CheckSELinuxOptions() Check {
	return Check{
		ID:    "seLinuxOptions",
		Level: api.LevelBaseline,
		Versions: []VersionedCheck{
			{
				MinimumVersion: api.MajorMinorVersion(1, 0),
				CheckPod:       seLinuxOptions_1_0,
			},
		},
	}
}


func seLinuxOptions_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {
	var (
		// sources that set bad seLinuxOptions
		badSetters []string

		// invalid type values set
		badTypes = sets.NewString()
		// was user set?
		setUser = false
		// was role set?
		setRole = false
	)

	validSELinuxOptions := func(opts *corev1.SELinuxOptions) bool {
		valid := true
		if !selinux_allowed_types_1_0.Has(opts.Type) {
			valid = false
			badTypes.Insert(opts.Type)
		}
		if len(opts.User) > 0 {
			valid = false
			setUser = true
		}
		if len(opts.Role) > 0 {
			valid = false
			setRole = true
		}
		return valid
	}

	if podSpec.SecurityContext != nil && podSpec.SecurityContext.SELinuxOptions != nil {
		if !validSELinuxOptions(podSpec.SecurityContext.SELinuxOptions) {
			badSetters = append(badSetters, "pod")
		}
	}

	var badContainers []string
	visitContainers(podSpec, func(container *corev1.Container) {
		if container.SecurityContext != nil && container.SecurityContext.SELinuxOptions != nil {
			if !validSELinuxOptions(container.SecurityContext.SELinuxOptions) {
				badContainers = append(badContainers, container.Name)
			}
		}
	})
	if len(badContainers) > 0 {
		badSetters = append(
			badSetters,
			fmt.Sprintf(
				"%s %s",
				pluralize("container", "containers", len(badContainers)),
				joinQuote(badContainers),
			),
		)
	}

	if len(badSetters) > 0 {
		var badData []string
		if len(badTypes) > 0 {
			badData = append(badData, fmt.Sprintf(
				"%s %s",
				pluralize("type", "types", len(badTypes)),
				joinQuote(badTypes.List()),
			))
		}
		if setUser {
			badData = append(badData, "user may not be set")
		}
		if setRole {
			badData = append(badData, "role may not be set")
		}

		return CheckResult{
			Allowed:         false,
			ForbiddenReason: "seLinuxOptions",
			ForbiddenDetail: fmt.Sprintf(
				`%s set forbidden securityContext.seLinuxOptions: %s`,
				strings.Join(badSetters, " and "),
				strings.Join(badData, "; "),
			),
		}
	}
	return CheckResult{Allowed: true}
}


init

func init() {
	addCheck(CheckSeccompBaseline)
}


CheckSeccompBaseline

func CheckSeccompBaseline() Check {
	return Check{
		ID:    checkSeccompBaselineID,
		Level: api.LevelBaseline,
		Versions: []VersionedCheck{
			{
				MinimumVersion: api.MajorMinorVersion(1, 0),
				CheckPod:       seccompProfileBaseline_1_0,
			},
			{
				MinimumVersion: api.MajorMinorVersion(1, 19),
				CheckPod:       seccompProfileBaseline_1_19,
			},
		},
	}
}


validSeccomp

func validSeccomp(t corev1.SeccompProfileType) bool {
	return t == corev1.SeccompProfileTypeLocalhost ||
		t == corev1.SeccompProfileTypeRuntimeDefault
}


validSeccompAnnotationValue

func validSeccompAnnotationValue(v string) bool {
	return v == corev1.SeccompProfileRuntimeDefault ||
		v == corev1.DeprecatedSeccompProfileDockerDefault ||
		strings.HasPrefix(v, corev1.SeccompLocalhostProfileNamePrefix)
}


// seccompProfileBaseline_1_0 checks baseline policy on seccomp alpha annotation
func seccompProfileBaseline_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {
	forbidden := sets.NewString()

	if val, ok := podMetadata.Annotations[annotationKeyPod]; ok {
		if !validSeccompAnnotationValue(val) {
			forbidden.Insert(fmt.Sprintf("%s=%q", annotationKeyPod, val))
		}
	}

	visitContainers(podSpec, func(c *corev1.Container) {
		annotation := annotationKeyContainerPrefix + c.Name
		if val, ok := podMetadata.Annotations[annotation]; ok {
			if !validSeccompAnnotationValue(val) {
				forbidden.Insert(fmt.Sprintf("%s=%q", annotation, val))
			}
		}
	})

	if len(forbidden) > 0 {
		return CheckResult{
			Allowed:         false,
			ForbiddenReason: "seccompProfile",
			ForbiddenDetail: fmt.Sprintf(
				"forbidden %s %s",
				pluralize("annotation", "annotations", len(forbidden)),
				strings.Join(forbidden.List(), ", "),
			),
		}
	}

	return CheckResult{Allowed: true}
}


// seccompProfileBaseline_1_19 checks baseline policy on securityContext.seccompProfile field
func seccompProfileBaseline_1_19(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {
	// things that explicitly set seccompProfile.type to a bad value
	var badSetters []string
	badValues := sets.NewString()

	if podSpec.SecurityContext != nil && podSpec.SecurityContext.SeccompProfile != nil {
		if !validSeccomp(podSpec.SecurityContext.SeccompProfile.Type) {
			badSetters = append(badSetters, "pod")
			badValues.Insert(string(podSpec.SecurityContext.SeccompProfile.Type))
		}
	}

	// containers that explicitly set seccompProfile.type to a bad value
	var explicitlyBadContainers []string

	visitContainers(podSpec, func(c *corev1.Container) {
		if c.SecurityContext != nil && c.SecurityContext.SeccompProfile != nil {
			// container explicitly set seccompProfile
			if !validSeccomp(c.SecurityContext.SeccompProfile.Type) {
				// container explicitly set seccompProfile to a bad value
				explicitlyBadContainers = append(explicitlyBadContainers, c.Name)
				badValues.Insert(string(c.SecurityContext.SeccompProfile.Type))
			}
		}
	})

	if len(explicitlyBadContainers) > 0 {
		badSetters = append(
			badSetters,
			fmt.Sprintf(
				"%s %s",
				pluralize("container", "containers", len(explicitlyBadContainers)),
				joinQuote(explicitlyBadContainers),
			),
		)
	}
	// pod or containers explicitly set bad seccompProfiles
	if len(badSetters) > 0 {
		return CheckResult{
			Allowed:         false,
			ForbiddenReason: "seccompProfile",
			ForbiddenDetail: fmt.Sprintf(
				"%s must not set securityContext.seccompProfile.type to %s",
				strings.Join(badSetters, " and "),
				joinQuote(badValues.List()),
			),
		}
	}

	return CheckResult{Allowed: true}
}


init

func init() {
	addCheck(CheckSeccompProfileRestricted)
}


CheckSeccompProfileRestricted

func CheckSeccompProfileRestricted() Check {
	return Check{
		ID:    "seccompProfile_restricted",
		Level: api.LevelRestricted,
		Versions: []VersionedCheck{
			{
				MinimumVersion:   api.MajorMinorVersion(1, 19),
				CheckPod:         seccompProfileRestricted_1_19,
				OverrideCheckIDs: []CheckID{checkSeccompBaselineID},
			},
			// Starting 1.25, windows pods would be exempted from this check using pod.spec.os field when set to windows.
			{
				MinimumVersion:   api.MajorMinorVersion(1, 25),
				CheckPod:         seccompProfileRestricted_1_25,
				OverrideCheckIDs: []CheckID{checkSeccompBaselineID},
			},
		},
	}
}


// seccompProfileRestricted_1_19 checks restricted policy on securityContext.seccompProfile field
func seccompProfileRestricted_1_19(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {
	// things that explicitly set seccompProfile.type to a bad value
	var badSetters []string
	badValues := sets.NewString()

	podSeccompSet := false

	if podSpec.SecurityContext != nil && podSpec.SecurityContext.SeccompProfile != nil {
		if !validSeccomp(podSpec.SecurityContext.SeccompProfile.Type) {
			badSetters = append(badSetters, "pod")
			badValues.Insert(string(podSpec.SecurityContext.SeccompProfile.Type))
		} else {
			podSeccompSet = true
		}
	}

	// containers that explicitly set seccompProfile.type to a bad value
	var explicitlyBadContainers []string
	// containers that didn't set seccompProfile and aren't caught by a pod-level seccompProfile
	var implicitlyBadContainers []string

	visitContainers(podSpec, func(c *corev1.Container) {
		if c.SecurityContext != nil && c.SecurityContext.SeccompProfile != nil {
			// container explicitly set seccompProfile
			if !validSeccomp(c.SecurityContext.SeccompProfile.Type) {
				// container explicitly set seccompProfile to a bad value
				explicitlyBadContainers = append(explicitlyBadContainers, c.Name)
				badValues.Insert(string(c.SecurityContext.SeccompProfile.Type))
			}
		} else {
			// container did not explicitly set seccompProfile
			if !podSeccompSet {
				// no valid pod-level seccompProfile, so this container implicitly has a bad value
				implicitlyBadContainers = append(implicitlyBadContainers, c.Name)
			}
		}
	})

	if len(explicitlyBadContainers) > 0 {
		badSetters = append(
			badSetters,
			fmt.Sprintf(
				"%s %s",
				pluralize("container", "containers", len(explicitlyBadContainers)),
				joinQuote(explicitlyBadContainers),
			),
		)
	}
	// pod or containers explicitly set bad seccompProfiles
	if len(badSetters) > 0 {
		return CheckResult{
			Allowed:         false,
			ForbiddenReason: "seccompProfile",
			ForbiddenDetail: fmt.Sprintf(
				"%s must not set securityContext.seccompProfile.type to %s",
				strings.Join(badSetters, " and "),
				joinQuote(badValues.List()),
			),
		}
	}

	// pod didn't set seccompProfile and not all containers opted into seccompProfile
	if len(implicitlyBadContainers) > 0 {
		return CheckResult{
			Allowed:         false,
			ForbiddenReason: "seccompProfile",
			ForbiddenDetail: fmt.Sprintf(
				`pod or %s %s must set securityContext.seccompProfile.type to "RuntimeDefault" or "Localhost"`,
				pluralize("container", "containers", len(implicitlyBadContainers)),
				joinQuote(implicitlyBadContainers),
			),
		}
	}

	return CheckResult{Allowed: true}
}


// seccompProfileRestricted_1_25 checks restricted policy on securityContext.seccompProfile field for kubernetes
// version 1.25 and above
func seccompProfileRestricted_1_25(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {
	// Pod API validation would have failed if podOS == Windows and if secCompProfile has been set.
	// We can admit the Windows pod even if seccompProfile has not been set.
	if podSpec.OS != nil && podSpec.OS.Name == corev1.Windows {
		return CheckResult{Allowed: true}
	}
	return seccompProfileRestricted_1_19(podMetadata, podSpec)
}


CheckSysctls

// CheckSysctls returns a baseline level check
// that limits the value of sysctls in 1.0+
func CheckSysctls() Check {
	return Check{
		ID:    "sysctls",
		Level: api.LevelBaseline,
		Versions: []VersionedCheck{
			{
				MinimumVersion: api.MajorMinorVersion(1, 0),
				CheckPod:       sysctls_1_0,
			},
			{
				MinimumVersion: api.MajorMinorVersion(1, 27),
				CheckPod:       sysctls_1_27,
			},
		},
	}
}


func sysctls_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {
	return sysctls(podMetadata, podSpec, sysctls_allowed_1_0)
}


func sysctls_1_27(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {
	return sysctls(podMetadata, podSpec, sysctls_allowed_1_27)
}


sysctls

func sysctls(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec, sysctls_allowed_set sets.String) CheckResult {
	var forbiddenSysctls []string

	if podSpec.SecurityContext != nil {
		for _, sysctl := range podSpec.SecurityContext.Sysctls {
			if !sysctls_allowed_set.Has(sysctl.Name) {
				forbiddenSysctls = append(forbiddenSysctls, sysctl.Name)
			}
		}
	}

	if len(forbiddenSysctls) > 0 {
		return CheckResult{
			Allowed:         false,
			ForbiddenReason: "forbidden sysctls",
			ForbiddenDetail: strings.Join(forbiddenSysctls, ", "),
		}
	}
	return CheckResult{Allowed: true}
}


init

func init() {
	addCheck(CheckWindowsHostProcess)
}


CheckWindowsHostProcess

// CheckWindowsHostProcess returns a baseline level check
// that forbids hostProcess=true in 1.0+
func CheckWindowsHostProcess() Check {
	return Check{
		ID:    "windowsHostProcess",
		Level: api.LevelBaseline,
		Versions: []VersionedCheck{
			{
				MinimumVersion: api.MajorMinorVersion(1, 0),
				CheckPod:       windowsHostProcess_1_0,
			},
		},
	}
}


func windowsHostProcess_1_0(podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) CheckResult {
	var badContainers []string
	visitContainers(podSpec, func(container *corev1.Container) {
		if container.SecurityContext != nil &&
			container.SecurityContext.WindowsOptions != nil &&
			container.SecurityContext.WindowsOptions.HostProcess != nil &&
			*container.SecurityContext.WindowsOptions.HostProcess {
			badContainers = append(badContainers, container.Name)
		}
	})

	podSpecForbidden := false
	if podSpec.SecurityContext != nil &&
		podSpec.SecurityContext.WindowsOptions != nil &&
		podSpec.SecurityContext.WindowsOptions.HostProcess != nil &&
		*podSpec.SecurityContext.WindowsOptions.HostProcess {
		podSpecForbidden = true
	}

	// pod or containers explicitly set hostProcess=true
	var forbiddenSetters []string
	if podSpecForbidden {
		forbiddenSetters = append(forbiddenSetters, "pod")
	}
	if len(badContainers) > 0 {
		forbiddenSetters = append(
			forbiddenSetters,
			fmt.Sprintf(
				"%s %s",
				pluralize("container", "containers", len(badContainers)),
				joinQuote(badContainers),
			),
		)
	}
	if len(forbiddenSetters) > 0 {
		return CheckResult{
			Allowed:         false,
			ForbiddenReason: "hostProcess",
			ForbiddenDetail: fmt.Sprintf("%s must not set securityContext.windowsOptions.hostProcess=true", strings.Join(forbiddenSetters, " and ")),
		}
	}

	return CheckResult{Allowed: true}
}


ForbiddenReason

// ForbiddenReason returns a comma-separated string of of the forbidden reasons.
// Example: host ports, privileged containers, non-default capabilities
func (a *AggregateCheckResult) ForbiddenReason() string {
	return strings.Join(a.ForbiddenReasons, ", ")
}


ForbiddenDetail

// ForbiddenDetail returns a detailed forbidden message, with non-empty details formatted in
// parentheses with the associated reason.
// Example: host ports (8080, 9090), privileged containers, non-default capabilities (NET_RAW)
func (a *AggregateCheckResult) ForbiddenDetail() string {
	var b strings.Builder
	for i := 0; i < len(a.ForbiddenReasons); i++ {
		b.WriteString(a.ForbiddenReasons[i])
		if a.ForbiddenDetails[i] != "" {
			b.WriteString(" (")
			b.WriteString(a.ForbiddenDetails[i])
			b.WriteString(")")
		}
		if i != len(a.ForbiddenReasons)-1 {
			b.WriteString(", ")
		}
	}
	return b.String()
}


AggregateCheckResults

// AggregateCheckPod runs all the checks and aggregates the forbidden results into a single CheckResult.
// The aggregated reason is a comma-separated
func AggregateCheckResults(results []CheckResult) AggregateCheckResult {
	var (
		reasons []string
		details []string
	)
	for _, result := range results {
		if !result.Allowed {
			if len(result.ForbiddenReason) == 0 {
				reasons = append(reasons, UnknownForbiddenReason)
			} else {
				reasons = append(reasons, result.ForbiddenReason)
			}
			details = append(details, result.ForbiddenDetail)
		}
	}
	return AggregateCheckResult{
		Allowed:          len(reasons) == 0,
		ForbiddenReasons: reasons,
		ForbiddenDetails: details,
	}
}


addCheck

func addCheck(f func() Check) {
	// add to experimental or versioned list
	c := f()
	if len(c.Versions) == 1 && c.Versions[0].MinimumVersion == (api.Version{}) {
		experimentalChecks = append(experimentalChecks, f)
	} else {
		defaultChecks = append(defaultChecks, f)
	}
}


DefaultChecks

// DefaultChecks returns checks that are expected to be enabled by default.
// The results are mutually exclusive with ExperimentalChecks.
// It returns a new copy of checks on each invocation and is expected to be called once at setup time.
func DefaultChecks() []Check {
	retval := make([]Check, 0, len(defaultChecks))
	for _, f := range defaultChecks {
		retval = append(retval, f())
	}
	return retval
}


ExperimentalChecks

// ExperimentalChecks returns checks that have not yet been assigned to policy versions.
// The results are mutually exclusive with DefaultChecks.
// It returns a new copy of checks on each invocation and is expected to be called once at setup time.
func ExperimentalChecks() []Check {
	retval := make([]Check, 0, len(experimentalChecks))
	for _, f := range experimentalChecks {
		retval = append(retval, f())
	}
	return retval
}


joinQuote

func joinQuote(items []string) string {
	if len(items) == 0 {
		return ""
	}
	return `"` + strings.Join(items, `", "`) + `"`
}


pluralize

func pluralize(singular, plural string, count int) string {
	if count == 1 {
		return singular
	}
	return plural
}


NewEvaluator

// NewEvaluator constructs a new Evaluator instance from the list of checks. If the provided checks are invalid,
// an error is returned. A valid list of checks must meet the following requirements:
// 1. Check.ID is unique in the list
// 2. Check.Level must be either Baseline or Restricted
// 3. Checks must have a non-empty set of versions, sorted in a strictly increasing order
// 4. Check.Versions cannot include 'latest'
func NewEvaluator(checks []Check) (Evaluator, error) {
	if err := validateChecks(checks); err != nil {
		return nil, err
	}
	r := &checkRegistry{
		baselineChecks:   map[api.Version][]CheckPodFn{},
		restrictedChecks: map[api.Version][]CheckPodFn{},
	}
	populate(r, checks)
	return r, nil
}


EvaluatePod

func (r *checkRegistry) EvaluatePod(lv api.LevelVersion, podMetadata *metav1.ObjectMeta, podSpec *corev1.PodSpec) []CheckResult {
	if lv.Level == api.LevelPrivileged {
		return nil
	}
	if r.maxVersion.Older(lv.Version) {
		lv.Version = r.maxVersion
	}

	var checks []CheckPodFn
	if lv.Level == api.LevelBaseline {
		checks = r.baselineChecks[lv.Version]
	} else {
		// includes non-overridden baseline checks
		checks = r.restrictedChecks[lv.Version]
	}

	var results []CheckResult
	for _, check := range checks {
		results = append(results, check(podMetadata, podSpec))
	}
	return results
}