1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2024-12-15 17:51:20 +00:00
kyverno/pkg/engine/validation.go

828 lines
28 KiB
Go
Raw Normal View History

2019-05-14 01:17:28 +00:00
package engine
import (
"context"
"encoding/json"
"fmt"
"reflect"
"strings"
2019-08-19 23:40:10 +00:00
"time"
2019-05-16 16:31:02 +00:00
"github.com/go-logr/logr"
gojmespath "github.com/jmespath/go-jmespath"
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
kyvernov2alpha1 "github.com/kyverno/kyverno/api/kyverno/v2alpha1"
"github.com/kyverno/kyverno/pkg/autogen"
"github.com/kyverno/kyverno/pkg/config"
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
"github.com/kyverno/kyverno/pkg/engine/utils"
"github.com/kyverno/kyverno/pkg/engine/validate"
"github.com/kyverno/kyverno/pkg/engine/variables"
"github.com/kyverno/kyverno/pkg/logging"
Extend Pod Security Admission (#4364) * init commit for pss Signed-off-by: ShutingZhao <shuting@nirmata.com> * add test for Volume Type control * add test for App Armor control except ExemptProfile. Fix PSS profile check in EvaluatePSS() * remove unused code, still a JMESPATH problem with app armor ExemptProfile() * test for Host Process / Host Namespaces controls * test for Privileged containers controls * test for HostPathVolume control * test for HostPorts control * test for HostPorts control * test for SELinux control * test for Proc mount type control * Set to baseline * test for Seccomp control * test for Sysctl control * test for Privilege escalation control * test for Run as non root control * test for Restricted Seccomp control * Add problems to address * add solutions to problems * Add validate rule for PSA * api.Version --> string. latest by default * Exclude all values for a restrictedField * add tests for kyverno engine * code to be used to match kyverno rule's namespace * Refacto pkg/pss * fix multiple problems: not matching containers, add contains methods, select the right container when we have the same exclude.RestrictedField for multiple containers: * EvaluatePod * Use EvaluatePod in kyverno engine * Set pod instead of container in context to use full Jmespath. e.g.: securityContext.capabilities.add --> spec.containers[*].securityContext.capabilities.add * Check if PSSCheckResult matched at least one exclude value * add tests for engine * fix engine validation test * config * update go.mod and go.sum * crds * Check validate value: add PodSecurity * exclude all restrictedFields when we only specify the controlName * ExemptProfile(): check if exclud.RestrictedField matches at least one restrictedField.path * handle containers, initContainers, ephemeralContainers when we only specify the controlName (all restrictedFields are excluded) * refacto pks/pss/evaluate.go and add pkg/engine/validation_test.go * add all controls with containers in restrictedFields as comments * add tests for capabilities and privileged containers and fix some errors * add tests for host ports control * add tests for proc mount control * add tests for privilege escalation control * add tests for capabilities control * remove comments * new algo * refacto algo, working. Add test for hostProcess control * remove unused code * fix getPodWithNotMatchingContainers(), add tests for host namespaces control * refacto ExemptProfile() * get values for a specific container. add test for SELinuxOptions control * fix allowedValues for SELinuxOptions * add tests for seccompProfile_baseline control * refacto checkContainers(), add test for seccomp control * add test for running as non root control * add some tests for runAsUser control, have to update current PSA version * add sysctls control * add allowed values for restrictedVolumes control * add some tests for appArmor, volume types controls * add tests for volume types control * add tests for hostPath volume control * finish merge conflicts and add tests for runAsUser * update charts and crds * exclude.images optional * change volume types control exclude values * add appAmor control * fix: did not match any exclude value for pod-level restrictedFields * create autogen for validate.PodSecurity * clean code, remove logs * fix sonatype lift errors * fix sonatype lift errors: duplication * fix crash in pkg/policy/validate/ tests and unmarshall errors for pkg/engine tests * beginning of autogen implement for validate.exclude * Autogen for validation.PodSecurity * working autogen with simple tests * change validate.PodSecurity failure response format * make codegen * fix lint errors, remove debug prints * fix tags * fix tags * fix crash when deleting pods matching validate.podSecurity rule. Only check validatePodSecurity() when it's not a delete request * Changes requested * Changes requested 2 * Changes requested 3 * Changes requested 4 * Changes requested and make codegen * fix host namespaces control * fix lint * fix codegen error * update docs/crd/v1/index.html Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix path Signed-off-by: ShutingZhao <shuting@nirmata.com> * update crd schema Signed-off-by: ShutingZhao <shuting@nirmata.com> * update charts/kyverno/templates/crds.yaml Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: ShutingZhao <shuting@nirmata.com>
2022-08-31 09:16:31 +00:00
"github.com/kyverno/kyverno/pkg/pss"
"github.com/kyverno/kyverno/pkg/registryclient"
feat: add engine traces (#5463) * feat: make traces better Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * feat: add tracing in engine validation Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * refactor Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * audit Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * values Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * chart deps Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * trace Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes and image verification Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutate Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutate Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * remove chart deps Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * remove tempo Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * bump deps Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * prometheus Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * child span Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more spans Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * audit Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix cosign spans Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix cosign spans Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutation Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutation tracing Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>
2022-12-12 20:32:11 +00:00
"github.com/kyverno/kyverno/pkg/tracing"
"github.com/kyverno/kyverno/pkg/utils/api"
datautils "github.com/kyverno/kyverno/pkg/utils/data"
matched "github.com/kyverno/kyverno/pkg/utils/match"
"github.com/pkg/errors"
feat: add engine traces (#5463) * feat: make traces better Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * feat: add tracing in engine validation Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * refactor Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * audit Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * values Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * chart deps Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * trace Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes and image verification Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutate Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutate Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * remove chart deps Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * remove tempo Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * bump deps Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * prometheus Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * child span Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more spans Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * audit Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix cosign spans Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix cosign spans Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutation Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutation tracing Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>
2022-12-12 20:32:11 +00:00
"go.opentelemetry.io/otel/trace"
Extend Pod Security Admission (#4364) * init commit for pss Signed-off-by: ShutingZhao <shuting@nirmata.com> * add test for Volume Type control * add test for App Armor control except ExemptProfile. Fix PSS profile check in EvaluatePSS() * remove unused code, still a JMESPATH problem with app armor ExemptProfile() * test for Host Process / Host Namespaces controls * test for Privileged containers controls * test for HostPathVolume control * test for HostPorts control * test for HostPorts control * test for SELinux control * test for Proc mount type control * Set to baseline * test for Seccomp control * test for Sysctl control * test for Privilege escalation control * test for Run as non root control * test for Restricted Seccomp control * Add problems to address * add solutions to problems * Add validate rule for PSA * api.Version --> string. latest by default * Exclude all values for a restrictedField * add tests for kyverno engine * code to be used to match kyverno rule's namespace * Refacto pkg/pss * fix multiple problems: not matching containers, add contains methods, select the right container when we have the same exclude.RestrictedField for multiple containers: * EvaluatePod * Use EvaluatePod in kyverno engine * Set pod instead of container in context to use full Jmespath. e.g.: securityContext.capabilities.add --> spec.containers[*].securityContext.capabilities.add * Check if PSSCheckResult matched at least one exclude value * add tests for engine * fix engine validation test * config * update go.mod and go.sum * crds * Check validate value: add PodSecurity * exclude all restrictedFields when we only specify the controlName * ExemptProfile(): check if exclud.RestrictedField matches at least one restrictedField.path * handle containers, initContainers, ephemeralContainers when we only specify the controlName (all restrictedFields are excluded) * refacto pks/pss/evaluate.go and add pkg/engine/validation_test.go * add all controls with containers in restrictedFields as comments * add tests for capabilities and privileged containers and fix some errors * add tests for host ports control * add tests for proc mount control * add tests for privilege escalation control * add tests for capabilities control * remove comments * new algo * refacto algo, working. Add test for hostProcess control * remove unused code * fix getPodWithNotMatchingContainers(), add tests for host namespaces control * refacto ExemptProfile() * get values for a specific container. add test for SELinuxOptions control * fix allowedValues for SELinuxOptions * add tests for seccompProfile_baseline control * refacto checkContainers(), add test for seccomp control * add test for running as non root control * add some tests for runAsUser control, have to update current PSA version * add sysctls control * add allowed values for restrictedVolumes control * add some tests for appArmor, volume types controls * add tests for volume types control * add tests for hostPath volume control * finish merge conflicts and add tests for runAsUser * update charts and crds * exclude.images optional * change volume types control exclude values * add appAmor control * fix: did not match any exclude value for pod-level restrictedFields * create autogen for validate.PodSecurity * clean code, remove logs * fix sonatype lift errors * fix sonatype lift errors: duplication * fix crash in pkg/policy/validate/ tests and unmarshall errors for pkg/engine tests * beginning of autogen implement for validate.exclude * Autogen for validation.PodSecurity * working autogen with simple tests * change validate.PodSecurity failure response format * make codegen * fix lint errors, remove debug prints * fix tags * fix tags * fix crash when deleting pods matching validate.podSecurity rule. Only check validatePodSecurity() when it's not a delete request * Changes requested * Changes requested 2 * Changes requested 3 * Changes requested 4 * Changes requested and make codegen * fix host namespaces control * fix lint * fix codegen error * update docs/crd/v1/index.html Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix path Signed-off-by: ShutingZhao <shuting@nirmata.com> * update crd schema Signed-off-by: ShutingZhao <shuting@nirmata.com> * update charts/kyverno/templates/crds.yaml Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: ShutingZhao <shuting@nirmata.com>
2022-08-31 09:16:31 +00:00
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
Extend Pod Security Admission (#4364) * init commit for pss Signed-off-by: ShutingZhao <shuting@nirmata.com> * add test for Volume Type control * add test for App Armor control except ExemptProfile. Fix PSS profile check in EvaluatePSS() * remove unused code, still a JMESPATH problem with app armor ExemptProfile() * test for Host Process / Host Namespaces controls * test for Privileged containers controls * test for HostPathVolume control * test for HostPorts control * test for HostPorts control * test for SELinux control * test for Proc mount type control * Set to baseline * test for Seccomp control * test for Sysctl control * test for Privilege escalation control * test for Run as non root control * test for Restricted Seccomp control * Add problems to address * add solutions to problems * Add validate rule for PSA * api.Version --> string. latest by default * Exclude all values for a restrictedField * add tests for kyverno engine * code to be used to match kyverno rule's namespace * Refacto pkg/pss * fix multiple problems: not matching containers, add contains methods, select the right container when we have the same exclude.RestrictedField for multiple containers: * EvaluatePod * Use EvaluatePod in kyverno engine * Set pod instead of container in context to use full Jmespath. e.g.: securityContext.capabilities.add --> spec.containers[*].securityContext.capabilities.add * Check if PSSCheckResult matched at least one exclude value * add tests for engine * fix engine validation test * config * update go.mod and go.sum * crds * Check validate value: add PodSecurity * exclude all restrictedFields when we only specify the controlName * ExemptProfile(): check if exclud.RestrictedField matches at least one restrictedField.path * handle containers, initContainers, ephemeralContainers when we only specify the controlName (all restrictedFields are excluded) * refacto pks/pss/evaluate.go and add pkg/engine/validation_test.go * add all controls with containers in restrictedFields as comments * add tests for capabilities and privileged containers and fix some errors * add tests for host ports control * add tests for proc mount control * add tests for privilege escalation control * add tests for capabilities control * remove comments * new algo * refacto algo, working. Add test for hostProcess control * remove unused code * fix getPodWithNotMatchingContainers(), add tests for host namespaces control * refacto ExemptProfile() * get values for a specific container. add test for SELinuxOptions control * fix allowedValues for SELinuxOptions * add tests for seccompProfile_baseline control * refacto checkContainers(), add test for seccomp control * add test for running as non root control * add some tests for runAsUser control, have to update current PSA version * add sysctls control * add allowed values for restrictedVolumes control * add some tests for appArmor, volume types controls * add tests for volume types control * add tests for hostPath volume control * finish merge conflicts and add tests for runAsUser * update charts and crds * exclude.images optional * change volume types control exclude values * add appAmor control * fix: did not match any exclude value for pod-level restrictedFields * create autogen for validate.PodSecurity * clean code, remove logs * fix sonatype lift errors * fix sonatype lift errors: duplication * fix crash in pkg/policy/validate/ tests and unmarshall errors for pkg/engine tests * beginning of autogen implement for validate.exclude * Autogen for validation.PodSecurity * working autogen with simple tests * change validate.PodSecurity failure response format * make codegen * fix lint errors, remove debug prints * fix tags * fix tags * fix crash when deleting pods matching validate.podSecurity rule. Only check validatePodSecurity() when it's not a delete request * Changes requested * Changes requested 2 * Changes requested 3 * Changes requested 4 * Changes requested and make codegen * fix host namespaces control * fix lint * fix codegen error * update docs/crd/v1/index.html Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix path Signed-off-by: ShutingZhao <shuting@nirmata.com> * update crd schema Signed-off-by: ShutingZhao <shuting@nirmata.com> * update charts/kyverno/templates/crds.yaml Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: ShutingZhao <shuting@nirmata.com>
2022-08-31 09:16:31 +00:00
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/client-go/tools/cache"
)
// Validate applies validation rules from policy on the resource
func Validate(ctx context.Context, rclient registryclient.Client, policyContext *PolicyContext, cfg config.Configuration) (resp *engineapi.EngineResponse) {
resp = &engineapi.EngineResponse{}
2019-09-03 22:48:13 +00:00
startTime := time.Now()
2020-12-23 23:10:07 +00:00
logger := buildLogger(policyContext)
logger.V(4).Info("start validate policy processing", "startTime", startTime)
2020-05-05 15:28:02 +00:00
defer func() {
buildResponse(policyContext, resp, startTime)
logger.V(4).Info("finished policy processing", "processingTime", resp.PolicyResponse.ProcessingTime.String(), "validationRulesApplied", resp.PolicyResponse.RulesAppliedCount)
2020-05-05 15:28:02 +00:00
}()
resp = validateResource(ctx, logger, rclient, policyContext, cfg)
resp.NamespaceLabels = policyContext.namespaceLabels
2020-12-24 02:46:12 +00:00
return
2020-12-23 23:10:07 +00:00
}
func buildLogger(ctx *PolicyContext) logr.Logger {
logger := logging.WithName("EngineValidate").WithValues("policy", ctx.policy.GetName())
if reflect.DeepEqual(ctx.newResource, unstructured.Unstructured{}) {
logger = logger.WithValues("kind", ctx.oldResource.GetKind(), "namespace", ctx.oldResource.GetNamespace(), "name", ctx.oldResource.GetName())
2020-12-23 23:10:07 +00:00
} else {
logger = logger.WithValues("kind", ctx.newResource.GetKind(), "namespace", ctx.newResource.GetNamespace(), "name", ctx.newResource.GetName())
}
2020-12-23 23:10:07 +00:00
return logger
}
func buildResponse(ctx *PolicyContext, resp *engineapi.EngineResponse, startTime time.Time) {
if reflect.DeepEqual(resp, engineapi.EngineResponse{}) {
2020-12-23 23:10:07 +00:00
return
2019-09-03 22:48:13 +00:00
}
2020-12-23 23:10:07 +00:00
if reflect.DeepEqual(resp.PatchedResource, unstructured.Unstructured{}) {
// for delete requests patched resource will be oldResource since newResource is empty
resource := ctx.newResource
if reflect.DeepEqual(ctx.newResource, unstructured.Unstructured{}) {
resource = ctx.oldResource
2020-12-23 23:10:07 +00:00
}
2020-12-24 02:51:07 +00:00
resp.PatchedResource = resource
2020-05-05 13:49:47 +00:00
}
2020-05-05 15:28:02 +00:00
resp.Policy = ctx.policy
resp.PolicyResponse.Policy.Name = ctx.policy.GetName()
resp.PolicyResponse.Policy.Namespace = ctx.policy.GetNamespace()
2020-12-24 02:51:07 +00:00
resp.PolicyResponse.Resource.Name = resp.PatchedResource.GetName()
resp.PolicyResponse.Resource.Namespace = resp.PatchedResource.GetNamespace()
resp.PolicyResponse.Resource.Kind = resp.PatchedResource.GetKind()
resp.PolicyResponse.Resource.APIVersion = resp.PatchedResource.GetAPIVersion()
resp.PolicyResponse.ValidationFailureAction = ctx.policy.GetSpec().ValidationFailureAction
for _, v := range ctx.policy.GetSpec().ValidationFailureActionOverrides {
newOverrides := engineapi.ValidationFailureActionOverride{Action: v.Action, Namespaces: v.Namespaces, NamespaceSelector: v.NamespaceSelector}
resp.PolicyResponse.ValidationFailureActionOverrides = append(resp.PolicyResponse.ValidationFailureActionOverrides, newOverrides)
}
resp.PolicyResponse.ProcessingTime = time.Since(startTime)
resp.PolicyResponse.Timestamp = startTime.Unix()
}
func validateResource(ctx context.Context, log logr.Logger, rclient registryclient.Client, enginectx *PolicyContext, cfg config.Configuration) *engineapi.EngineResponse {
resp := &engineapi.EngineResponse{}
2020-12-23 23:10:07 +00:00
enginectx.jsonContext.Checkpoint()
defer enginectx.jsonContext.Restore()
rules := autogen.ComputeRules(enginectx.policy)
matchCount := 0
applyRules := enginectx.policy.GetSpec().GetApplyRules()
if enginectx.policy.IsNamespaced() {
polNs := enginectx.policy.GetNamespace()
if enginectx.newResource.Object != nil && (enginectx.newResource.GetNamespace() != polNs || enginectx.newResource.GetNamespace() == "") {
return resp
}
if enginectx.oldResource.Object != nil && (enginectx.oldResource.GetNamespace() != polNs || enginectx.oldResource.GetNamespace() == "") {
return resp
}
}
for i := range rules {
rule := &rules[i]
log.V(3).Info("processing validation rule", "matchCount", matchCount, "applyRules", applyRules)
enginectx.jsonContext.Reset()
startTime := time.Now()
feat: add engine traces (#5463) * feat: make traces better Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * feat: add tracing in engine validation Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * refactor Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * audit Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * values Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * chart deps Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * trace Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes and image verification Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutate Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutate Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * remove chart deps Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * remove tempo Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * bump deps Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * prometheus Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * child span Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more spans Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * audit Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix cosign spans Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix cosign spans Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutation Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutation tracing Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>
2022-12-12 20:32:11 +00:00
ruleResp := tracing.ChildSpan1(
ctx,
"pkg/engine",
fmt.Sprintf("RULE %s", rule.Name),
func(ctx context.Context, span trace.Span) *engineapi.RuleResponse {
feat: add engine traces (#5463) * feat: make traces better Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * feat: add tracing in engine validation Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * refactor Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * audit Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * values Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * chart deps Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * trace Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes and image verification Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutate Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutate Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * remove chart deps Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * remove tempo Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * bump deps Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * prometheus Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * child span Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more spans Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * audit Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix cosign spans Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix cosign spans Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutation Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutation tracing Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>
2022-12-12 20:32:11 +00:00
hasValidate := rule.HasValidate()
hasValidateImage := rule.HasImagesValidationChecks()
hasYAMLSignatureVerify := rule.HasYAMLSignatureVerify()
if !hasValidate && !hasValidateImage {
return nil
}
log = log.WithValues("rule", rule.Name)
kindsInPolicy := append(rule.MatchResources.GetKinds(), rule.ExcludeResources.GetKinds()...)
subresourceGVKToAPIResource := GetSubresourceGVKToAPIResourceMap(kindsInPolicy, enginectx)
if !matches(log, rule, enginectx, subresourceGVKToAPIResource) {
feat: add engine traces (#5463) * feat: make traces better Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * feat: add tracing in engine validation Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * refactor Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * audit Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * values Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * chart deps Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * trace Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes and image verification Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutate Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutate Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * remove chart deps Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * remove tempo Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * bump deps Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * prometheus Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * child span Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more spans Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * audit Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix cosign spans Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix cosign spans Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutation Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutation tracing Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>
2022-12-12 20:32:11 +00:00
return nil
}
// check if there is a corresponding policy exception
ruleResp := hasPolicyExceptions(enginectx, rule, subresourceGVKToAPIResource, log)
if ruleResp != nil {
return ruleResp
}
feat: add engine traces (#5463) * feat: make traces better Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * feat: add tracing in engine validation Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * refactor Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * audit Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * values Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * chart deps Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * trace Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes and image verification Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutate Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutate Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * remove chart deps Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * remove tempo Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * bump deps Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * prometheus Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * child span Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more spans Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * audit Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix cosign spans Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix cosign spans Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutation Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutation tracing Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>
2022-12-12 20:32:11 +00:00
log.V(3).Info("processing validation rule", "matchCount", matchCount, "applyRules", applyRules)
enginectx.jsonContext.Reset()
if hasValidate && !hasYAMLSignatureVerify {
return processValidationRule(ctx, log, rclient, enginectx, rule)
} else if hasValidateImage {
return processImageValidationRule(ctx, log, rclient, enginectx, rule, cfg)
feat: add engine traces (#5463) * feat: make traces better Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * feat: add tracing in engine validation Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * refactor Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * audit Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * values Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * chart deps Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * trace Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes and image verification Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutate Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutate Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * remove chart deps Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * remove tempo Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * bump deps Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * makefile Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * prometheus Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * child span Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more spans Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * audit Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix cosign spans Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix cosign spans Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutation Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * mutation tracing Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>
2022-12-12 20:32:11 +00:00
} else if hasYAMLSignatureVerify {
return processYAMLValidationRule(log, enginectx, rule)
}
return nil
},
)
if ruleResp != nil {
addRuleResponse(log, resp, ruleResp, startTime)
if applyRules == kyvernov1.ApplyOne && resp.PolicyResponse.RulesAppliedCount > 0 {
break
}
2019-09-03 22:48:13 +00:00
}
}
593 feature (#594) * initial commit * background policy validation * correct message * skip non-background policy process for add/update * add Generate Request CR * generate Request Generator Initial * test generate request CR generation * initial commit gr generator * generate controller initial framework * add crd for generate request * gr cleanup controller initial commit * cleanup controller initial * generate mid-commit * generate rule processing * create PV on generate error * embed resource type * testing phase 1- generate resources with variable substitution * fix tests * comment broken test #586 * add printer column for state * return if existing resource for clone * set resync time to 2 mins & remove resource version check in update handler for gr * generate events for reporting * fix logs * initial commit * fix trailing quote in patch * remove comments * initial condition (equal & notequal) * initial support for conditions * initial support fo conditions in generate * support precondition checks * cleanup * re-evaluate GR on namespace update using dynamic informers * add status for generated resources * display loaded variable SA * support delete cleanup of generate request main resources * fix log * remove namespace from SA username * support multiple variables per statement for scalar values * fix fail variables * add check for userInfo * validation checks for conditions * update policy * refactor logs * code review * add openapispec for clusterpolicy preconditions * Update documentation * CR fixes * documentation * CR fixes * update variable * fix logs * update policy * pre-defined variables (serviceAccountName & serviceAccountNamespace) * update test
2020-01-07 23:13:57 +00:00
return resp
}
func processValidationRule(ctx context.Context, log logr.Logger, rclient registryclient.Client, policyContext *PolicyContext, rule *kyvernov1.Rule) *engineapi.RuleResponse {
v := newValidator(log, rclient, policyContext, rule)
return v.validate(ctx)
}
func addRuleResponse(log logr.Logger, resp *engineapi.EngineResponse, ruleResp *engineapi.RuleResponse, startTime time.Time) {
ruleResp.ExecutionStats.ProcessingTime = time.Since(startTime)
ruleResp.ExecutionStats.Timestamp = startTime.Unix()
log.V(4).Info("finished processing rule", "processingTime", ruleResp.ExecutionStats.ProcessingTime.String())
if ruleResp.Status == engineapi.RuleStatusPass || ruleResp.Status == engineapi.RuleStatusFail {
incrementAppliedCount(resp)
} else if ruleResp.Status == engineapi.RuleStatusError {
incrementErrorCount(resp)
}
resp.PolicyResponse.Rules = append(resp.PolicyResponse.Rules, *ruleResp)
}
type validator struct {
log logr.Logger
policyContext *PolicyContext
rule *kyvernov1.Rule
contextEntries []kyvernov1.ContextEntry
anyAllConditions apiextensions.JSON
pattern apiextensions.JSON
anyPattern apiextensions.JSON
deny *kyvernov1.Deny
Extend Pod Security Admission (#4364) * init commit for pss Signed-off-by: ShutingZhao <shuting@nirmata.com> * add test for Volume Type control * add test for App Armor control except ExemptProfile. Fix PSS profile check in EvaluatePSS() * remove unused code, still a JMESPATH problem with app armor ExemptProfile() * test for Host Process / Host Namespaces controls * test for Privileged containers controls * test for HostPathVolume control * test for HostPorts control * test for HostPorts control * test for SELinux control * test for Proc mount type control * Set to baseline * test for Seccomp control * test for Sysctl control * test for Privilege escalation control * test for Run as non root control * test for Restricted Seccomp control * Add problems to address * add solutions to problems * Add validate rule for PSA * api.Version --> string. latest by default * Exclude all values for a restrictedField * add tests for kyverno engine * code to be used to match kyverno rule's namespace * Refacto pkg/pss * fix multiple problems: not matching containers, add contains methods, select the right container when we have the same exclude.RestrictedField for multiple containers: * EvaluatePod * Use EvaluatePod in kyverno engine * Set pod instead of container in context to use full Jmespath. e.g.: securityContext.capabilities.add --> spec.containers[*].securityContext.capabilities.add * Check if PSSCheckResult matched at least one exclude value * add tests for engine * fix engine validation test * config * update go.mod and go.sum * crds * Check validate value: add PodSecurity * exclude all restrictedFields when we only specify the controlName * ExemptProfile(): check if exclud.RestrictedField matches at least one restrictedField.path * handle containers, initContainers, ephemeralContainers when we only specify the controlName (all restrictedFields are excluded) * refacto pks/pss/evaluate.go and add pkg/engine/validation_test.go * add all controls with containers in restrictedFields as comments * add tests for capabilities and privileged containers and fix some errors * add tests for host ports control * add tests for proc mount control * add tests for privilege escalation control * add tests for capabilities control * remove comments * new algo * refacto algo, working. Add test for hostProcess control * remove unused code * fix getPodWithNotMatchingContainers(), add tests for host namespaces control * refacto ExemptProfile() * get values for a specific container. add test for SELinuxOptions control * fix allowedValues for SELinuxOptions * add tests for seccompProfile_baseline control * refacto checkContainers(), add test for seccomp control * add test for running as non root control * add some tests for runAsUser control, have to update current PSA version * add sysctls control * add allowed values for restrictedVolumes control * add some tests for appArmor, volume types controls * add tests for volume types control * add tests for hostPath volume control * finish merge conflicts and add tests for runAsUser * update charts and crds * exclude.images optional * change volume types control exclude values * add appAmor control * fix: did not match any exclude value for pod-level restrictedFields * create autogen for validate.PodSecurity * clean code, remove logs * fix sonatype lift errors * fix sonatype lift errors: duplication * fix crash in pkg/policy/validate/ tests and unmarshall errors for pkg/engine tests * beginning of autogen implement for validate.exclude * Autogen for validation.PodSecurity * working autogen with simple tests * change validate.PodSecurity failure response format * make codegen * fix lint errors, remove debug prints * fix tags * fix tags * fix crash when deleting pods matching validate.podSecurity rule. Only check validatePodSecurity() when it's not a delete request * Changes requested * Changes requested 2 * Changes requested 3 * Changes requested 4 * Changes requested and make codegen * fix host namespaces control * fix lint * fix codegen error * update docs/crd/v1/index.html Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix path Signed-off-by: ShutingZhao <shuting@nirmata.com> * update crd schema Signed-off-by: ShutingZhao <shuting@nirmata.com> * update charts/kyverno/templates/crds.yaml Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: ShutingZhao <shuting@nirmata.com>
2022-08-31 09:16:31 +00:00
podSecurity *kyvernov1.PodSecurity
forEach []kyvernov1.ForEachValidation
rclient registryclient.Client
nesting int
}
func newValidator(log logr.Logger, rclient registryclient.Client, ctx *PolicyContext, rule *kyvernov1.Rule) *validator {
ruleCopy := rule.DeepCopy()
return &validator{
log: log,
rule: ruleCopy,
policyContext: ctx,
rclient: rclient,
contextEntries: ruleCopy.Context,
anyAllConditions: ruleCopy.GetAnyAllConditions(),
pattern: ruleCopy.Validation.GetPattern(),
anyPattern: ruleCopy.Validation.GetAnyPattern(),
deny: ruleCopy.Validation.Deny,
Extend Pod Security Admission (#4364) * init commit for pss Signed-off-by: ShutingZhao <shuting@nirmata.com> * add test for Volume Type control * add test for App Armor control except ExemptProfile. Fix PSS profile check in EvaluatePSS() * remove unused code, still a JMESPATH problem with app armor ExemptProfile() * test for Host Process / Host Namespaces controls * test for Privileged containers controls * test for HostPathVolume control * test for HostPorts control * test for HostPorts control * test for SELinux control * test for Proc mount type control * Set to baseline * test for Seccomp control * test for Sysctl control * test for Privilege escalation control * test for Run as non root control * test for Restricted Seccomp control * Add problems to address * add solutions to problems * Add validate rule for PSA * api.Version --> string. latest by default * Exclude all values for a restrictedField * add tests for kyverno engine * code to be used to match kyverno rule's namespace * Refacto pkg/pss * fix multiple problems: not matching containers, add contains methods, select the right container when we have the same exclude.RestrictedField for multiple containers: * EvaluatePod * Use EvaluatePod in kyverno engine * Set pod instead of container in context to use full Jmespath. e.g.: securityContext.capabilities.add --> spec.containers[*].securityContext.capabilities.add * Check if PSSCheckResult matched at least one exclude value * add tests for engine * fix engine validation test * config * update go.mod and go.sum * crds * Check validate value: add PodSecurity * exclude all restrictedFields when we only specify the controlName * ExemptProfile(): check if exclud.RestrictedField matches at least one restrictedField.path * handle containers, initContainers, ephemeralContainers when we only specify the controlName (all restrictedFields are excluded) * refacto pks/pss/evaluate.go and add pkg/engine/validation_test.go * add all controls with containers in restrictedFields as comments * add tests for capabilities and privileged containers and fix some errors * add tests for host ports control * add tests for proc mount control * add tests for privilege escalation control * add tests for capabilities control * remove comments * new algo * refacto algo, working. Add test for hostProcess control * remove unused code * fix getPodWithNotMatchingContainers(), add tests for host namespaces control * refacto ExemptProfile() * get values for a specific container. add test for SELinuxOptions control * fix allowedValues for SELinuxOptions * add tests for seccompProfile_baseline control * refacto checkContainers(), add test for seccomp control * add test for running as non root control * add some tests for runAsUser control, have to update current PSA version * add sysctls control * add allowed values for restrictedVolumes control * add some tests for appArmor, volume types controls * add tests for volume types control * add tests for hostPath volume control * finish merge conflicts and add tests for runAsUser * update charts and crds * exclude.images optional * change volume types control exclude values * add appAmor control * fix: did not match any exclude value for pod-level restrictedFields * create autogen for validate.PodSecurity * clean code, remove logs * fix sonatype lift errors * fix sonatype lift errors: duplication * fix crash in pkg/policy/validate/ tests and unmarshall errors for pkg/engine tests * beginning of autogen implement for validate.exclude * Autogen for validation.PodSecurity * working autogen with simple tests * change validate.PodSecurity failure response format * make codegen * fix lint errors, remove debug prints * fix tags * fix tags * fix crash when deleting pods matching validate.podSecurity rule. Only check validatePodSecurity() when it's not a delete request * Changes requested * Changes requested 2 * Changes requested 3 * Changes requested 4 * Changes requested and make codegen * fix host namespaces control * fix lint * fix codegen error * update docs/crd/v1/index.html Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix path Signed-off-by: ShutingZhao <shuting@nirmata.com> * update crd schema Signed-off-by: ShutingZhao <shuting@nirmata.com> * update charts/kyverno/templates/crds.yaml Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: ShutingZhao <shuting@nirmata.com>
2022-08-31 09:16:31 +00:00
podSecurity: ruleCopy.Validation.PodSecurity,
forEach: ruleCopy.Validation.ForEachValidation,
}
}
func newForEachValidator(foreach kyvernov1.ForEachValidation, rclient registryclient.Client, nesting int, rule *kyvernov1.Rule, ctx *PolicyContext, log logr.Logger) (*validator, error) {
ruleCopy := rule.DeepCopy()
anyAllConditions, err := datautils.ToMap(foreach.AnyAllConditions)
2021-10-19 10:04:53 +00:00
if err != nil {
return nil, errors.Wrap(err, "failed to convert ruleCopy.Validation.ForEachValidation.AnyAllConditions")
}
nestedForEach, err := api.DeserializeJSONArray[kyvernov1.ForEachValidation](foreach.ForEachValidation)
if err != nil {
return nil, errors.Wrap(err, "failed to convert ruleCopy.Validation.ForEachValidation.AnyAllConditions")
2021-10-19 10:04:53 +00:00
}
updates for foreach and mutate (#2891) * updates for foreach and mutate Signed-off-by: Jim Bugwadia <jim@nirmata.com> * allow tests to pass on Windows Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter check Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add elementIndex variable Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix jsonResult usage Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add mutate validation and fix error in validate.foreach Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * do not skip validation for all array entries when one is skipped Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add foreach tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix format errors Signed-off-by: Jim Bugwadia <jim@nirmata.com> * remove unused declarations Signed-off-by: Jim Bugwadia <jim@nirmata.com> * revert namespaceWithLabelYaml Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix mutate of element list Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update CRDs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Update api/kyverno/v1/policy_types.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/custom-functions/policy.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/foreach/policies.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * accept review comments and format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add comments to strategicMergePatch buffer Signed-off-by: Jim Bugwadia <jim@nirmata.com> * load context and evaluate preconditions foreach element Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add test for foreach mutate context and precondition * precondition testcase * address review comments Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Steven E. Harris <seh@panix.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com>
2022-01-05 01:36:33 +00:00
2021-10-19 10:04:53 +00:00
return &validator{
log: log,
policyContext: ctx,
2021-10-19 10:04:53 +00:00
rule: ruleCopy,
rclient: rclient,
updates for foreach and mutate (#2891) * updates for foreach and mutate Signed-off-by: Jim Bugwadia <jim@nirmata.com> * allow tests to pass on Windows Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter check Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add elementIndex variable Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix jsonResult usage Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add mutate validation and fix error in validate.foreach Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * do not skip validation for all array entries when one is skipped Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add foreach tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix format errors Signed-off-by: Jim Bugwadia <jim@nirmata.com> * remove unused declarations Signed-off-by: Jim Bugwadia <jim@nirmata.com> * revert namespaceWithLabelYaml Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix mutate of element list Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update CRDs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Update api/kyverno/v1/policy_types.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/custom-functions/policy.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/foreach/policies.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * accept review comments and format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add comments to strategicMergePatch buffer Signed-off-by: Jim Bugwadia <jim@nirmata.com> * load context and evaluate preconditions foreach element Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add test for foreach mutate context and precondition * precondition testcase * address review comments Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Steven E. Harris <seh@panix.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com>
2022-01-05 01:36:33 +00:00
contextEntries: foreach.Context,
2021-10-19 10:04:53 +00:00
anyAllConditions: anyAllConditions,
pattern: foreach.GetPattern(),
anyPattern: foreach.GetAnyPattern(),
updates for foreach and mutate (#2891) * updates for foreach and mutate Signed-off-by: Jim Bugwadia <jim@nirmata.com> * allow tests to pass on Windows Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter check Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add elementIndex variable Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix jsonResult usage Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add mutate validation and fix error in validate.foreach Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * do not skip validation for all array entries when one is skipped Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add foreach tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix format errors Signed-off-by: Jim Bugwadia <jim@nirmata.com> * remove unused declarations Signed-off-by: Jim Bugwadia <jim@nirmata.com> * revert namespaceWithLabelYaml Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix mutate of element list Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update CRDs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Update api/kyverno/v1/policy_types.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/custom-functions/policy.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/foreach/policies.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * accept review comments and format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add comments to strategicMergePatch buffer Signed-off-by: Jim Bugwadia <jim@nirmata.com> * load context and evaluate preconditions foreach element Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add test for foreach mutate context and precondition * precondition testcase * address review comments Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Steven E. Harris <seh@panix.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com>
2022-01-05 01:36:33 +00:00
deny: foreach.Deny,
forEach: nestedForEach,
nesting: nesting,
}, nil
}
func (v *validator) validate(ctx context.Context) *engineapi.RuleResponse {
if err := v.loadContext(ctx); err != nil {
return ruleError(v.rule, engineapi.Validation, "failed to load context", err)
}
preconditionsPassed, err := checkPreconditions(v.log, v.policyContext, v.anyAllConditions)
if err != nil {
return ruleError(v.rule, engineapi.Validation, "failed to evaluate preconditions", err)
updates for foreach and mutate (#2891) * updates for foreach and mutate Signed-off-by: Jim Bugwadia <jim@nirmata.com> * allow tests to pass on Windows Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter check Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add elementIndex variable Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix jsonResult usage Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add mutate validation and fix error in validate.foreach Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * do not skip validation for all array entries when one is skipped Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add foreach tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix format errors Signed-off-by: Jim Bugwadia <jim@nirmata.com> * remove unused declarations Signed-off-by: Jim Bugwadia <jim@nirmata.com> * revert namespaceWithLabelYaml Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix mutate of element list Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update CRDs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Update api/kyverno/v1/policy_types.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/custom-functions/policy.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/foreach/policies.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * accept review comments and format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add comments to strategicMergePatch buffer Signed-off-by: Jim Bugwadia <jim@nirmata.com> * load context and evaluate preconditions foreach element Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add test for foreach mutate context and precondition * precondition testcase * address review comments Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Steven E. Harris <seh@panix.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com>
2022-01-05 01:36:33 +00:00
}
if !preconditionsPassed {
return ruleResponse(*v.rule, engineapi.Validation, "preconditions not met", engineapi.RuleStatusSkip)
}
if v.deny != nil {
return v.validateDeny()
}
if v.pattern != nil || v.anyPattern != nil {
if err = v.substitutePatterns(); err != nil {
return ruleError(v.rule, engineapi.Validation, "variable substitution failed", err)
}
ruleResponse := v.validateResourceWithRule()
return ruleResponse
}
if v.podSecurity != nil {
if !isDeleteRequest(v.policyContext) {
Extend Pod Security Admission (#4364) * init commit for pss Signed-off-by: ShutingZhao <shuting@nirmata.com> * add test for Volume Type control * add test for App Armor control except ExemptProfile. Fix PSS profile check in EvaluatePSS() * remove unused code, still a JMESPATH problem with app armor ExemptProfile() * test for Host Process / Host Namespaces controls * test for Privileged containers controls * test for HostPathVolume control * test for HostPorts control * test for HostPorts control * test for SELinux control * test for Proc mount type control * Set to baseline * test for Seccomp control * test for Sysctl control * test for Privilege escalation control * test for Run as non root control * test for Restricted Seccomp control * Add problems to address * add solutions to problems * Add validate rule for PSA * api.Version --> string. latest by default * Exclude all values for a restrictedField * add tests for kyverno engine * code to be used to match kyverno rule's namespace * Refacto pkg/pss * fix multiple problems: not matching containers, add contains methods, select the right container when we have the same exclude.RestrictedField for multiple containers: * EvaluatePod * Use EvaluatePod in kyverno engine * Set pod instead of container in context to use full Jmespath. e.g.: securityContext.capabilities.add --> spec.containers[*].securityContext.capabilities.add * Check if PSSCheckResult matched at least one exclude value * add tests for engine * fix engine validation test * config * update go.mod and go.sum * crds * Check validate value: add PodSecurity * exclude all restrictedFields when we only specify the controlName * ExemptProfile(): check if exclud.RestrictedField matches at least one restrictedField.path * handle containers, initContainers, ephemeralContainers when we only specify the controlName (all restrictedFields are excluded) * refacto pks/pss/evaluate.go and add pkg/engine/validation_test.go * add all controls with containers in restrictedFields as comments * add tests for capabilities and privileged containers and fix some errors * add tests for host ports control * add tests for proc mount control * add tests for privilege escalation control * add tests for capabilities control * remove comments * new algo * refacto algo, working. Add test for hostProcess control * remove unused code * fix getPodWithNotMatchingContainers(), add tests for host namespaces control * refacto ExemptProfile() * get values for a specific container. add test for SELinuxOptions control * fix allowedValues for SELinuxOptions * add tests for seccompProfile_baseline control * refacto checkContainers(), add test for seccomp control * add test for running as non root control * add some tests for runAsUser control, have to update current PSA version * add sysctls control * add allowed values for restrictedVolumes control * add some tests for appArmor, volume types controls * add tests for volume types control * add tests for hostPath volume control * finish merge conflicts and add tests for runAsUser * update charts and crds * exclude.images optional * change volume types control exclude values * add appAmor control * fix: did not match any exclude value for pod-level restrictedFields * create autogen for validate.PodSecurity * clean code, remove logs * fix sonatype lift errors * fix sonatype lift errors: duplication * fix crash in pkg/policy/validate/ tests and unmarshall errors for pkg/engine tests * beginning of autogen implement for validate.exclude * Autogen for validation.PodSecurity * working autogen with simple tests * change validate.PodSecurity failure response format * make codegen * fix lint errors, remove debug prints * fix tags * fix tags * fix crash when deleting pods matching validate.podSecurity rule. Only check validatePodSecurity() when it's not a delete request * Changes requested * Changes requested 2 * Changes requested 3 * Changes requested 4 * Changes requested and make codegen * fix host namespaces control * fix lint * fix codegen error * update docs/crd/v1/index.html Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix path Signed-off-by: ShutingZhao <shuting@nirmata.com> * update crd schema Signed-off-by: ShutingZhao <shuting@nirmata.com> * update charts/kyverno/templates/crds.yaml Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: ShutingZhao <shuting@nirmata.com>
2022-08-31 09:16:31 +00:00
ruleResponse := v.validatePodSecurity()
return ruleResponse
}
}
if v.forEach != nil {
ruleResponse := v.validateForEach(ctx)
return ruleResponse
}
v.log.V(2).Info("invalid validation rule: podSecurity, patterns, or deny expected")
return nil
}
func (v *validator) validateForEach(ctx context.Context) *engineapi.RuleResponse {
applyCount := 0
for _, foreach := range v.forEach {
elements, err := evaluateList(foreach.List, (v.policyContext.JSONContext()))
if err != nil {
v.log.V(2).Info("failed to evaluate list", "list", foreach.List, "error", err.Error())
2021-10-19 10:04:53 +00:00
continue
}
resp, count := v.validateElements(ctx, v.rclient, foreach, elements, foreach.ElementScope)
if resp.Status != engineapi.RuleStatusPass {
updates for foreach and mutate (#2891) * updates for foreach and mutate Signed-off-by: Jim Bugwadia <jim@nirmata.com> * allow tests to pass on Windows Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter check Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add elementIndex variable Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix jsonResult usage Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add mutate validation and fix error in validate.foreach Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * do not skip validation for all array entries when one is skipped Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add foreach tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix format errors Signed-off-by: Jim Bugwadia <jim@nirmata.com> * remove unused declarations Signed-off-by: Jim Bugwadia <jim@nirmata.com> * revert namespaceWithLabelYaml Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix mutate of element list Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update CRDs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Update api/kyverno/v1/policy_types.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/custom-functions/policy.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/foreach/policies.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * accept review comments and format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add comments to strategicMergePatch buffer Signed-off-by: Jim Bugwadia <jim@nirmata.com> * load context and evaluate preconditions foreach element Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add test for foreach mutate context and precondition * precondition testcase * address review comments Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Steven E. Harris <seh@panix.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com>
2022-01-05 01:36:33 +00:00
return resp
}
updates for foreach and mutate (#2891) * updates for foreach and mutate Signed-off-by: Jim Bugwadia <jim@nirmata.com> * allow tests to pass on Windows Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter check Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add elementIndex variable Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix jsonResult usage Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add mutate validation and fix error in validate.foreach Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * do not skip validation for all array entries when one is skipped Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add foreach tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix format errors Signed-off-by: Jim Bugwadia <jim@nirmata.com> * remove unused declarations Signed-off-by: Jim Bugwadia <jim@nirmata.com> * revert namespaceWithLabelYaml Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix mutate of element list Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update CRDs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Update api/kyverno/v1/policy_types.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/custom-functions/policy.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/foreach/policies.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * accept review comments and format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add comments to strategicMergePatch buffer Signed-off-by: Jim Bugwadia <jim@nirmata.com> * load context and evaluate preconditions foreach element Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add test for foreach mutate context and precondition * precondition testcase * address review comments Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Steven E. Harris <seh@panix.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com>
2022-01-05 01:36:33 +00:00
applyCount += count
}
if applyCount == 0 {
if v.forEach == nil {
return nil
}
return ruleResponse(*v.rule, engineapi.Validation, "rule skipped", engineapi.RuleStatusSkip)
}
return ruleResponse(*v.rule, engineapi.Validation, "rule passed", engineapi.RuleStatusPass)
}
func (v *validator) validateElements(ctx context.Context, rclient registryclient.Client, foreach kyvernov1.ForEachValidation, elements []interface{}, elementScope *bool) (*engineapi.RuleResponse, int) {
v.policyContext.jsonContext.Checkpoint()
defer v.policyContext.jsonContext.Restore()
updates for foreach and mutate (#2891) * updates for foreach and mutate Signed-off-by: Jim Bugwadia <jim@nirmata.com> * allow tests to pass on Windows Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter check Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add elementIndex variable Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix jsonResult usage Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add mutate validation and fix error in validate.foreach Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * do not skip validation for all array entries when one is skipped Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add foreach tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix format errors Signed-off-by: Jim Bugwadia <jim@nirmata.com> * remove unused declarations Signed-off-by: Jim Bugwadia <jim@nirmata.com> * revert namespaceWithLabelYaml Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix mutate of element list Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update CRDs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Update api/kyverno/v1/policy_types.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/custom-functions/policy.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/foreach/policies.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * accept review comments and format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add comments to strategicMergePatch buffer Signed-off-by: Jim Bugwadia <jim@nirmata.com> * load context and evaluate preconditions foreach element Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add test for foreach mutate context and precondition * precondition testcase * address review comments Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Steven E. Harris <seh@panix.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com>
2022-01-05 01:36:33 +00:00
applyCount := 0
for index, element := range elements {
if element == nil {
continue
}
v.policyContext.JSONContext().Reset()
policyContext := v.policyContext.Copy()
if err := addElementToContext(policyContext, element, index, v.nesting, elementScope); err != nil {
updates for foreach and mutate (#2891) * updates for foreach and mutate Signed-off-by: Jim Bugwadia <jim@nirmata.com> * allow tests to pass on Windows Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter check Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add elementIndex variable Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix jsonResult usage Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add mutate validation and fix error in validate.foreach Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * do not skip validation for all array entries when one is skipped Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add foreach tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix format errors Signed-off-by: Jim Bugwadia <jim@nirmata.com> * remove unused declarations Signed-off-by: Jim Bugwadia <jim@nirmata.com> * revert namespaceWithLabelYaml Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix mutate of element list Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update CRDs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Update api/kyverno/v1/policy_types.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/custom-functions/policy.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/foreach/policies.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * accept review comments and format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add comments to strategicMergePatch buffer Signed-off-by: Jim Bugwadia <jim@nirmata.com> * load context and evaluate preconditions foreach element Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add test for foreach mutate context and precondition * precondition testcase * address review comments Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Steven E. Harris <seh@panix.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com>
2022-01-05 01:36:33 +00:00
v.log.Error(err, "failed to add element to context")
return ruleError(v.rule, engineapi.Validation, "failed to process foreach", err), applyCount
updates for foreach and mutate (#2891) * updates for foreach and mutate Signed-off-by: Jim Bugwadia <jim@nirmata.com> * allow tests to pass on Windows Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter check Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add elementIndex variable Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix jsonResult usage Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add mutate validation and fix error in validate.foreach Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * do not skip validation for all array entries when one is skipped Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add foreach tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix format errors Signed-off-by: Jim Bugwadia <jim@nirmata.com> * remove unused declarations Signed-off-by: Jim Bugwadia <jim@nirmata.com> * revert namespaceWithLabelYaml Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix mutate of element list Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update CRDs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Update api/kyverno/v1/policy_types.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/custom-functions/policy.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/foreach/policies.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * accept review comments and format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add comments to strategicMergePatch buffer Signed-off-by: Jim Bugwadia <jim@nirmata.com> * load context and evaluate preconditions foreach element Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add test for foreach mutate context and precondition * precondition testcase * address review comments Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Steven E. Harris <seh@panix.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com>
2022-01-05 01:36:33 +00:00
}
foreachValidator, err := newForEachValidator(foreach, rclient, v.nesting+1, v.rule, policyContext, v.log)
if err != nil {
v.log.Error(err, "failed to create foreach validator")
return ruleError(v.rule, engineapi.Validation, "failed to create foreach validator", err), applyCount
}
r := foreachValidator.validate(ctx)
updates for foreach and mutate (#2891) * updates for foreach and mutate Signed-off-by: Jim Bugwadia <jim@nirmata.com> * allow tests to pass on Windows Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter check Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add elementIndex variable Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix jsonResult usage Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add mutate validation and fix error in validate.foreach Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * do not skip validation for all array entries when one is skipped Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add foreach tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix format errors Signed-off-by: Jim Bugwadia <jim@nirmata.com> * remove unused declarations Signed-off-by: Jim Bugwadia <jim@nirmata.com> * revert namespaceWithLabelYaml Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix mutate of element list Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update CRDs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Update api/kyverno/v1/policy_types.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/custom-functions/policy.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/foreach/policies.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * accept review comments and format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add comments to strategicMergePatch buffer Signed-off-by: Jim Bugwadia <jim@nirmata.com> * load context and evaluate preconditions foreach element Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add test for foreach mutate context and precondition * precondition testcase * address review comments Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Steven E. Harris <seh@panix.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com>
2022-01-05 01:36:33 +00:00
if r == nil {
v.log.V(2).Info("skip rule due to empty result")
updates for foreach and mutate (#2891) * updates for foreach and mutate Signed-off-by: Jim Bugwadia <jim@nirmata.com> * allow tests to pass on Windows Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter check Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add elementIndex variable Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix jsonResult usage Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add mutate validation and fix error in validate.foreach Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * do not skip validation for all array entries when one is skipped Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add foreach tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix format errors Signed-off-by: Jim Bugwadia <jim@nirmata.com> * remove unused declarations Signed-off-by: Jim Bugwadia <jim@nirmata.com> * revert namespaceWithLabelYaml Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix mutate of element list Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update CRDs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Update api/kyverno/v1/policy_types.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/custom-functions/policy.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/foreach/policies.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * accept review comments and format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add comments to strategicMergePatch buffer Signed-off-by: Jim Bugwadia <jim@nirmata.com> * load context and evaluate preconditions foreach element Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add test for foreach mutate context and precondition * precondition testcase * address review comments Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Steven E. Harris <seh@panix.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com>
2022-01-05 01:36:33 +00:00
continue
} else if r.Status == engineapi.RuleStatusSkip {
v.log.V(2).Info("skip rule", "reason", r.Message)
updates for foreach and mutate (#2891) * updates for foreach and mutate Signed-off-by: Jim Bugwadia <jim@nirmata.com> * allow tests to pass on Windows Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter check Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add elementIndex variable Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix jsonResult usage Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add mutate validation and fix error in validate.foreach Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * do not skip validation for all array entries when one is skipped Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add foreach tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix format errors Signed-off-by: Jim Bugwadia <jim@nirmata.com> * remove unused declarations Signed-off-by: Jim Bugwadia <jim@nirmata.com> * revert namespaceWithLabelYaml Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix mutate of element list Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update CRDs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Update api/kyverno/v1/policy_types.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/custom-functions/policy.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/foreach/policies.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * accept review comments and format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add comments to strategicMergePatch buffer Signed-off-by: Jim Bugwadia <jim@nirmata.com> * load context and evaluate preconditions foreach element Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add test for foreach mutate context and precondition * precondition testcase * address review comments Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Steven E. Harris <seh@panix.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com>
2022-01-05 01:36:33 +00:00
continue
} else if r.Status != engineapi.RuleStatusPass {
if r.Status == engineapi.RuleStatusError {
if index < len(elements)-1 {
continue
}
msg := fmt.Sprintf("validation failure: %v", r.Message)
return ruleResponse(*v.rule, engineapi.Validation, msg, r.Status), applyCount
}
msg := fmt.Sprintf("validation failure: %v", r.Message)
return ruleResponse(*v.rule, engineapi.Validation, msg, r.Status), applyCount
updates for foreach and mutate (#2891) * updates for foreach and mutate Signed-off-by: Jim Bugwadia <jim@nirmata.com> * allow tests to pass on Windows Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter check Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add elementIndex variable Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix jsonResult usage Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add mutate validation and fix error in validate.foreach Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * do not skip validation for all array entries when one is skipped Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add foreach tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix format errors Signed-off-by: Jim Bugwadia <jim@nirmata.com> * remove unused declarations Signed-off-by: Jim Bugwadia <jim@nirmata.com> * revert namespaceWithLabelYaml Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix mutate of element list Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update CRDs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Update api/kyverno/v1/policy_types.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/custom-functions/policy.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/foreach/policies.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * accept review comments and format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add comments to strategicMergePatch buffer Signed-off-by: Jim Bugwadia <jim@nirmata.com> * load context and evaluate preconditions foreach element Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add test for foreach mutate context and precondition * precondition testcase * address review comments Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Steven E. Harris <seh@panix.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com>
2022-01-05 01:36:33 +00:00
}
applyCount++
}
return ruleResponse(*v.rule, engineapi.Validation, "", engineapi.RuleStatusPass), applyCount
updates for foreach and mutate (#2891) * updates for foreach and mutate Signed-off-by: Jim Bugwadia <jim@nirmata.com> * allow tests to pass on Windows Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter check Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add elementIndex variable Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix jsonResult usage Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add mutate validation and fix error in validate.foreach Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * do not skip validation for all array entries when one is skipped Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add foreach tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix format errors Signed-off-by: Jim Bugwadia <jim@nirmata.com> * remove unused declarations Signed-off-by: Jim Bugwadia <jim@nirmata.com> * revert namespaceWithLabelYaml Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix mutate of element list Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update CRDs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Update api/kyverno/v1/policy_types.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/custom-functions/policy.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/foreach/policies.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * accept review comments and format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add comments to strategicMergePatch buffer Signed-off-by: Jim Bugwadia <jim@nirmata.com> * load context and evaluate preconditions foreach element Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add test for foreach mutate context and precondition * precondition testcase * address review comments Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Steven E. Harris <seh@panix.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com>
2022-01-05 01:36:33 +00:00
}
func addElementToContext(ctx *PolicyContext, element interface{}, index, nesting int, elementScope *bool) error {
data, err := variables.DocumentToUntyped(element)
if err != nil {
return err
}
if err := ctx.JSONContext().AddElement(data, index, nesting); err != nil {
return errors.Wrapf(err, "failed to add element (%v) to JSON context", element)
}
dataMap, ok := data.(map[string]interface{})
// We set scoped to true by default if the data is a map
// otherwise we do not do element scoped foreach unless the user
// has explicitly set it to true
scoped := ok
// If the user has explicitly provided an element scope
// we check if data is a map or not. In case it is not a map and the user
// has set elementscoped to true, we throw an error.
// Otherwise we set the value to what is specified by the user.
if elementScope != nil {
if *elementScope && !ok {
return fmt.Errorf("cannot use elementScope=true foreach rules for elements that are not maps, expected type=map got type=%T", data)
}
scoped = *elementScope
}
if scoped {
updates for foreach and mutate (#2891) * updates for foreach and mutate Signed-off-by: Jim Bugwadia <jim@nirmata.com> * allow tests to pass on Windows Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter check Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add elementIndex variable Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix jsonResult usage Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add mutate validation and fix error in validate.foreach Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * do not skip validation for all array entries when one is skipped Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add foreach tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix format errors Signed-off-by: Jim Bugwadia <jim@nirmata.com> * remove unused declarations Signed-off-by: Jim Bugwadia <jim@nirmata.com> * revert namespaceWithLabelYaml Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix mutate of element list Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update CRDs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Update api/kyverno/v1/policy_types.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/custom-functions/policy.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/foreach/policies.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * accept review comments and format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add comments to strategicMergePatch buffer Signed-off-by: Jim Bugwadia <jim@nirmata.com> * load context and evaluate preconditions foreach element Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add test for foreach mutate context and precondition * precondition testcase * address review comments Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Steven E. Harris <seh@panix.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com>
2022-01-05 01:36:33 +00:00
u := unstructured.Unstructured{}
u.SetUnstructuredContent(dataMap)
ctx.element = u
updates for foreach and mutate (#2891) * updates for foreach and mutate Signed-off-by: Jim Bugwadia <jim@nirmata.com> * allow tests to pass on Windows Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter check Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add elementIndex variable Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix jsonResult usage Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add mutate validation and fix error in validate.foreach Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * do not skip validation for all array entries when one is skipped Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add foreach tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix fmt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix format errors Signed-off-by: Jim Bugwadia <jim@nirmata.com> * remove unused declarations Signed-off-by: Jim Bugwadia <jim@nirmata.com> * revert namespaceWithLabelYaml Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix mutate of element list Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update CRDs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Update api/kyverno/v1/policy_types.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/forceMutate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/mutation.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update pkg/engine/validate/validate.go Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/custom-functions/policy.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * Update test/cli/test/foreach/policies.yaml Co-authored-by: Steven E. Harris <seh@panix.com> * accept review comments and format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add comments to strategicMergePatch buffer Signed-off-by: Jim Bugwadia <jim@nirmata.com> * load context and evaluate preconditions foreach element Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add test for foreach mutate context and precondition * precondition testcase * address review comments Signed-off-by: Jim Bugwadia <jim@nirmata.com> * update message Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Steven E. Harris <seh@panix.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com>
2022-01-05 01:36:33 +00:00
}
return nil
}
func (v *validator) loadContext(ctx context.Context) error {
if err := LoadContext(ctx, v.log, v.rclient, v.contextEntries, v.policyContext, v.rule.Name); err != nil {
if _, ok := err.(gojmespath.NotFoundError); ok {
v.log.V(3).Info("failed to load context", "reason", err.Error())
} else {
v.log.Error(err, "failed to load context")
2020-12-23 23:10:07 +00:00
}
return err
2020-05-05 13:49:47 +00:00
}
2020-12-23 23:10:07 +00:00
return nil
2020-05-05 13:49:47 +00:00
}
func (v *validator) validateDeny() *engineapi.RuleResponse {
anyAllCond := v.deny.GetAnyAllConditions()
anyAllCond, err := variables.SubstituteAll(v.log, v.policyContext.jsonContext, anyAllCond)
if err != nil {
return ruleError(v.rule, engineapi.Validation, "failed to substitute variables in deny conditions", err)
}
if err = v.substituteDeny(); err != nil {
return ruleError(v.rule, engineapi.Validation, "failed to substitute variables in rule", err)
}
denyConditions, err := utils.TransformConditions(anyAllCond)
if err != nil {
return ruleError(v.rule, engineapi.Validation, "invalid deny conditions", err)
}
deny := variables.EvaluateConditions(v.log, v.policyContext.jsonContext, denyConditions)
if deny {
return ruleResponse(*v.rule, engineapi.Validation, v.getDenyMessage(deny), engineapi.RuleStatusFail)
}
return ruleResponse(*v.rule, engineapi.Validation, v.getDenyMessage(deny), engineapi.RuleStatusPass)
}
func (v *validator) getDenyMessage(deny bool) string {
if !deny {
return fmt.Sprintf("validation rule '%s' passed.", v.rule.Name)
}
msg := v.rule.Validation.Message
if msg == "" {
return fmt.Sprintf("validation error: rule %s failed", v.rule.Name)
}
raw, err := variables.SubstituteAll(v.log, v.policyContext.jsonContext, msg)
if err != nil {
return msg
}
switch typed := raw.(type) {
case string:
return typed
default:
return "the produced message didn't resolve to a string, check your policy definition."
}
}
Extend Pod Security Admission (#4364) * init commit for pss Signed-off-by: ShutingZhao <shuting@nirmata.com> * add test for Volume Type control * add test for App Armor control except ExemptProfile. Fix PSS profile check in EvaluatePSS() * remove unused code, still a JMESPATH problem with app armor ExemptProfile() * test for Host Process / Host Namespaces controls * test for Privileged containers controls * test for HostPathVolume control * test for HostPorts control * test for HostPorts control * test for SELinux control * test for Proc mount type control * Set to baseline * test for Seccomp control * test for Sysctl control * test for Privilege escalation control * test for Run as non root control * test for Restricted Seccomp control * Add problems to address * add solutions to problems * Add validate rule for PSA * api.Version --> string. latest by default * Exclude all values for a restrictedField * add tests for kyverno engine * code to be used to match kyverno rule's namespace * Refacto pkg/pss * fix multiple problems: not matching containers, add contains methods, select the right container when we have the same exclude.RestrictedField for multiple containers: * EvaluatePod * Use EvaluatePod in kyverno engine * Set pod instead of container in context to use full Jmespath. e.g.: securityContext.capabilities.add --> spec.containers[*].securityContext.capabilities.add * Check if PSSCheckResult matched at least one exclude value * add tests for engine * fix engine validation test * config * update go.mod and go.sum * crds * Check validate value: add PodSecurity * exclude all restrictedFields when we only specify the controlName * ExemptProfile(): check if exclud.RestrictedField matches at least one restrictedField.path * handle containers, initContainers, ephemeralContainers when we only specify the controlName (all restrictedFields are excluded) * refacto pks/pss/evaluate.go and add pkg/engine/validation_test.go * add all controls with containers in restrictedFields as comments * add tests for capabilities and privileged containers and fix some errors * add tests for host ports control * add tests for proc mount control * add tests for privilege escalation control * add tests for capabilities control * remove comments * new algo * refacto algo, working. Add test for hostProcess control * remove unused code * fix getPodWithNotMatchingContainers(), add tests for host namespaces control * refacto ExemptProfile() * get values for a specific container. add test for SELinuxOptions control * fix allowedValues for SELinuxOptions * add tests for seccompProfile_baseline control * refacto checkContainers(), add test for seccomp control * add test for running as non root control * add some tests for runAsUser control, have to update current PSA version * add sysctls control * add allowed values for restrictedVolumes control * add some tests for appArmor, volume types controls * add tests for volume types control * add tests for hostPath volume control * finish merge conflicts and add tests for runAsUser * update charts and crds * exclude.images optional * change volume types control exclude values * add appAmor control * fix: did not match any exclude value for pod-level restrictedFields * create autogen for validate.PodSecurity * clean code, remove logs * fix sonatype lift errors * fix sonatype lift errors: duplication * fix crash in pkg/policy/validate/ tests and unmarshall errors for pkg/engine tests * beginning of autogen implement for validate.exclude * Autogen for validation.PodSecurity * working autogen with simple tests * change validate.PodSecurity failure response format * make codegen * fix lint errors, remove debug prints * fix tags * fix tags * fix crash when deleting pods matching validate.podSecurity rule. Only check validatePodSecurity() when it's not a delete request * Changes requested * Changes requested 2 * Changes requested 3 * Changes requested 4 * Changes requested and make codegen * fix host namespaces control * fix lint * fix codegen error * update docs/crd/v1/index.html Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix path Signed-off-by: ShutingZhao <shuting@nirmata.com> * update crd schema Signed-off-by: ShutingZhao <shuting@nirmata.com> * update charts/kyverno/templates/crds.yaml Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: ShutingZhao <shuting@nirmata.com>
2022-08-31 09:16:31 +00:00
func getSpec(v *validator) (podSpec *corev1.PodSpec, metadata *metav1.ObjectMeta, err error) {
kind := v.policyContext.newResource.GetKind()
Extend Pod Security Admission (#4364) * init commit for pss Signed-off-by: ShutingZhao <shuting@nirmata.com> * add test for Volume Type control * add test for App Armor control except ExemptProfile. Fix PSS profile check in EvaluatePSS() * remove unused code, still a JMESPATH problem with app armor ExemptProfile() * test for Host Process / Host Namespaces controls * test for Privileged containers controls * test for HostPathVolume control * test for HostPorts control * test for HostPorts control * test for SELinux control * test for Proc mount type control * Set to baseline * test for Seccomp control * test for Sysctl control * test for Privilege escalation control * test for Run as non root control * test for Restricted Seccomp control * Add problems to address * add solutions to problems * Add validate rule for PSA * api.Version --> string. latest by default * Exclude all values for a restrictedField * add tests for kyverno engine * code to be used to match kyverno rule's namespace * Refacto pkg/pss * fix multiple problems: not matching containers, add contains methods, select the right container when we have the same exclude.RestrictedField for multiple containers: * EvaluatePod * Use EvaluatePod in kyverno engine * Set pod instead of container in context to use full Jmespath. e.g.: securityContext.capabilities.add --> spec.containers[*].securityContext.capabilities.add * Check if PSSCheckResult matched at least one exclude value * add tests for engine * fix engine validation test * config * update go.mod and go.sum * crds * Check validate value: add PodSecurity * exclude all restrictedFields when we only specify the controlName * ExemptProfile(): check if exclud.RestrictedField matches at least one restrictedField.path * handle containers, initContainers, ephemeralContainers when we only specify the controlName (all restrictedFields are excluded) * refacto pks/pss/evaluate.go and add pkg/engine/validation_test.go * add all controls with containers in restrictedFields as comments * add tests for capabilities and privileged containers and fix some errors * add tests for host ports control * add tests for proc mount control * add tests for privilege escalation control * add tests for capabilities control * remove comments * new algo * refacto algo, working. Add test for hostProcess control * remove unused code * fix getPodWithNotMatchingContainers(), add tests for host namespaces control * refacto ExemptProfile() * get values for a specific container. add test for SELinuxOptions control * fix allowedValues for SELinuxOptions * add tests for seccompProfile_baseline control * refacto checkContainers(), add test for seccomp control * add test for running as non root control * add some tests for runAsUser control, have to update current PSA version * add sysctls control * add allowed values for restrictedVolumes control * add some tests for appArmor, volume types controls * add tests for volume types control * add tests for hostPath volume control * finish merge conflicts and add tests for runAsUser * update charts and crds * exclude.images optional * change volume types control exclude values * add appAmor control * fix: did not match any exclude value for pod-level restrictedFields * create autogen for validate.PodSecurity * clean code, remove logs * fix sonatype lift errors * fix sonatype lift errors: duplication * fix crash in pkg/policy/validate/ tests and unmarshall errors for pkg/engine tests * beginning of autogen implement for validate.exclude * Autogen for validation.PodSecurity * working autogen with simple tests * change validate.PodSecurity failure response format * make codegen * fix lint errors, remove debug prints * fix tags * fix tags * fix crash when deleting pods matching validate.podSecurity rule. Only check validatePodSecurity() when it's not a delete request * Changes requested * Changes requested 2 * Changes requested 3 * Changes requested 4 * Changes requested and make codegen * fix host namespaces control * fix lint * fix codegen error * update docs/crd/v1/index.html Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix path Signed-off-by: ShutingZhao <shuting@nirmata.com> * update crd schema Signed-off-by: ShutingZhao <shuting@nirmata.com> * update charts/kyverno/templates/crds.yaml Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: ShutingZhao <shuting@nirmata.com>
2022-08-31 09:16:31 +00:00
if kind == "DaemonSet" || kind == "Deployment" || kind == "Job" || kind == "StatefulSet" || kind == "ReplicaSet" || kind == "ReplicationController" {
Extend Pod Security Admission (#4364) * init commit for pss Signed-off-by: ShutingZhao <shuting@nirmata.com> * add test for Volume Type control * add test for App Armor control except ExemptProfile. Fix PSS profile check in EvaluatePSS() * remove unused code, still a JMESPATH problem with app armor ExemptProfile() * test for Host Process / Host Namespaces controls * test for Privileged containers controls * test for HostPathVolume control * test for HostPorts control * test for HostPorts control * test for SELinux control * test for Proc mount type control * Set to baseline * test for Seccomp control * test for Sysctl control * test for Privilege escalation control * test for Run as non root control * test for Restricted Seccomp control * Add problems to address * add solutions to problems * Add validate rule for PSA * api.Version --> string. latest by default * Exclude all values for a restrictedField * add tests for kyverno engine * code to be used to match kyverno rule's namespace * Refacto pkg/pss * fix multiple problems: not matching containers, add contains methods, select the right container when we have the same exclude.RestrictedField for multiple containers: * EvaluatePod * Use EvaluatePod in kyverno engine * Set pod instead of container in context to use full Jmespath. e.g.: securityContext.capabilities.add --> spec.containers[*].securityContext.capabilities.add * Check if PSSCheckResult matched at least one exclude value * add tests for engine * fix engine validation test * config * update go.mod and go.sum * crds * Check validate value: add PodSecurity * exclude all restrictedFields when we only specify the controlName * ExemptProfile(): check if exclud.RestrictedField matches at least one restrictedField.path * handle containers, initContainers, ephemeralContainers when we only specify the controlName (all restrictedFields are excluded) * refacto pks/pss/evaluate.go and add pkg/engine/validation_test.go * add all controls with containers in restrictedFields as comments * add tests for capabilities and privileged containers and fix some errors * add tests for host ports control * add tests for proc mount control * add tests for privilege escalation control * add tests for capabilities control * remove comments * new algo * refacto algo, working. Add test for hostProcess control * remove unused code * fix getPodWithNotMatchingContainers(), add tests for host namespaces control * refacto ExemptProfile() * get values for a specific container. add test for SELinuxOptions control * fix allowedValues for SELinuxOptions * add tests for seccompProfile_baseline control * refacto checkContainers(), add test for seccomp control * add test for running as non root control * add some tests for runAsUser control, have to update current PSA version * add sysctls control * add allowed values for restrictedVolumes control * add some tests for appArmor, volume types controls * add tests for volume types control * add tests for hostPath volume control * finish merge conflicts and add tests for runAsUser * update charts and crds * exclude.images optional * change volume types control exclude values * add appAmor control * fix: did not match any exclude value for pod-level restrictedFields * create autogen for validate.PodSecurity * clean code, remove logs * fix sonatype lift errors * fix sonatype lift errors: duplication * fix crash in pkg/policy/validate/ tests and unmarshall errors for pkg/engine tests * beginning of autogen implement for validate.exclude * Autogen for validation.PodSecurity * working autogen with simple tests * change validate.PodSecurity failure response format * make codegen * fix lint errors, remove debug prints * fix tags * fix tags * fix crash when deleting pods matching validate.podSecurity rule. Only check validatePodSecurity() when it's not a delete request * Changes requested * Changes requested 2 * Changes requested 3 * Changes requested 4 * Changes requested and make codegen * fix host namespaces control * fix lint * fix codegen error * update docs/crd/v1/index.html Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix path Signed-off-by: ShutingZhao <shuting@nirmata.com> * update crd schema Signed-off-by: ShutingZhao <shuting@nirmata.com> * update charts/kyverno/templates/crds.yaml Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: ShutingZhao <shuting@nirmata.com>
2022-08-31 09:16:31 +00:00
var deployment appsv1.Deployment
resourceBytes, err := v.policyContext.newResource.MarshalJSON()
Extend Pod Security Admission (#4364) * init commit for pss Signed-off-by: ShutingZhao <shuting@nirmata.com> * add test for Volume Type control * add test for App Armor control except ExemptProfile. Fix PSS profile check in EvaluatePSS() * remove unused code, still a JMESPATH problem with app armor ExemptProfile() * test for Host Process / Host Namespaces controls * test for Privileged containers controls * test for HostPathVolume control * test for HostPorts control * test for HostPorts control * test for SELinux control * test for Proc mount type control * Set to baseline * test for Seccomp control * test for Sysctl control * test for Privilege escalation control * test for Run as non root control * test for Restricted Seccomp control * Add problems to address * add solutions to problems * Add validate rule for PSA * api.Version --> string. latest by default * Exclude all values for a restrictedField * add tests for kyverno engine * code to be used to match kyverno rule's namespace * Refacto pkg/pss * fix multiple problems: not matching containers, add contains methods, select the right container when we have the same exclude.RestrictedField for multiple containers: * EvaluatePod * Use EvaluatePod in kyverno engine * Set pod instead of container in context to use full Jmespath. e.g.: securityContext.capabilities.add --> spec.containers[*].securityContext.capabilities.add * Check if PSSCheckResult matched at least one exclude value * add tests for engine * fix engine validation test * config * update go.mod and go.sum * crds * Check validate value: add PodSecurity * exclude all restrictedFields when we only specify the controlName * ExemptProfile(): check if exclud.RestrictedField matches at least one restrictedField.path * handle containers, initContainers, ephemeralContainers when we only specify the controlName (all restrictedFields are excluded) * refacto pks/pss/evaluate.go and add pkg/engine/validation_test.go * add all controls with containers in restrictedFields as comments * add tests for capabilities and privileged containers and fix some errors * add tests for host ports control * add tests for proc mount control * add tests for privilege escalation control * add tests for capabilities control * remove comments * new algo * refacto algo, working. Add test for hostProcess control * remove unused code * fix getPodWithNotMatchingContainers(), add tests for host namespaces control * refacto ExemptProfile() * get values for a specific container. add test for SELinuxOptions control * fix allowedValues for SELinuxOptions * add tests for seccompProfile_baseline control * refacto checkContainers(), add test for seccomp control * add test for running as non root control * add some tests for runAsUser control, have to update current PSA version * add sysctls control * add allowed values for restrictedVolumes control * add some tests for appArmor, volume types controls * add tests for volume types control * add tests for hostPath volume control * finish merge conflicts and add tests for runAsUser * update charts and crds * exclude.images optional * change volume types control exclude values * add appAmor control * fix: did not match any exclude value for pod-level restrictedFields * create autogen for validate.PodSecurity * clean code, remove logs * fix sonatype lift errors * fix sonatype lift errors: duplication * fix crash in pkg/policy/validate/ tests and unmarshall errors for pkg/engine tests * beginning of autogen implement for validate.exclude * Autogen for validation.PodSecurity * working autogen with simple tests * change validate.PodSecurity failure response format * make codegen * fix lint errors, remove debug prints * fix tags * fix tags * fix crash when deleting pods matching validate.podSecurity rule. Only check validatePodSecurity() when it's not a delete request * Changes requested * Changes requested 2 * Changes requested 3 * Changes requested 4 * Changes requested and make codegen * fix host namespaces control * fix lint * fix codegen error * update docs/crd/v1/index.html Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix path Signed-off-by: ShutingZhao <shuting@nirmata.com> * update crd schema Signed-off-by: ShutingZhao <shuting@nirmata.com> * update charts/kyverno/templates/crds.yaml Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: ShutingZhao <shuting@nirmata.com>
2022-08-31 09:16:31 +00:00
if err != nil {
return nil, nil, err
}
err = json.Unmarshal(resourceBytes, &deployment)
if err != nil {
return nil, nil, err
}
podSpec = &deployment.Spec.Template.Spec
metadata = &deployment.Spec.Template.ObjectMeta
return podSpec, metadata, nil
} else if kind == "CronJob" {
var cronJob batchv1.CronJob
resourceBytes, err := v.policyContext.newResource.MarshalJSON()
Extend Pod Security Admission (#4364) * init commit for pss Signed-off-by: ShutingZhao <shuting@nirmata.com> * add test for Volume Type control * add test for App Armor control except ExemptProfile. Fix PSS profile check in EvaluatePSS() * remove unused code, still a JMESPATH problem with app armor ExemptProfile() * test for Host Process / Host Namespaces controls * test for Privileged containers controls * test for HostPathVolume control * test for HostPorts control * test for HostPorts control * test for SELinux control * test for Proc mount type control * Set to baseline * test for Seccomp control * test for Sysctl control * test for Privilege escalation control * test for Run as non root control * test for Restricted Seccomp control * Add problems to address * add solutions to problems * Add validate rule for PSA * api.Version --> string. latest by default * Exclude all values for a restrictedField * add tests for kyverno engine * code to be used to match kyverno rule's namespace * Refacto pkg/pss * fix multiple problems: not matching containers, add contains methods, select the right container when we have the same exclude.RestrictedField for multiple containers: * EvaluatePod * Use EvaluatePod in kyverno engine * Set pod instead of container in context to use full Jmespath. e.g.: securityContext.capabilities.add --> spec.containers[*].securityContext.capabilities.add * Check if PSSCheckResult matched at least one exclude value * add tests for engine * fix engine validation test * config * update go.mod and go.sum * crds * Check validate value: add PodSecurity * exclude all restrictedFields when we only specify the controlName * ExemptProfile(): check if exclud.RestrictedField matches at least one restrictedField.path * handle containers, initContainers, ephemeralContainers when we only specify the controlName (all restrictedFields are excluded) * refacto pks/pss/evaluate.go and add pkg/engine/validation_test.go * add all controls with containers in restrictedFields as comments * add tests for capabilities and privileged containers and fix some errors * add tests for host ports control * add tests for proc mount control * add tests for privilege escalation control * add tests for capabilities control * remove comments * new algo * refacto algo, working. Add test for hostProcess control * remove unused code * fix getPodWithNotMatchingContainers(), add tests for host namespaces control * refacto ExemptProfile() * get values for a specific container. add test for SELinuxOptions control * fix allowedValues for SELinuxOptions * add tests for seccompProfile_baseline control * refacto checkContainers(), add test for seccomp control * add test for running as non root control * add some tests for runAsUser control, have to update current PSA version * add sysctls control * add allowed values for restrictedVolumes control * add some tests for appArmor, volume types controls * add tests for volume types control * add tests for hostPath volume control * finish merge conflicts and add tests for runAsUser * update charts and crds * exclude.images optional * change volume types control exclude values * add appAmor control * fix: did not match any exclude value for pod-level restrictedFields * create autogen for validate.PodSecurity * clean code, remove logs * fix sonatype lift errors * fix sonatype lift errors: duplication * fix crash in pkg/policy/validate/ tests and unmarshall errors for pkg/engine tests * beginning of autogen implement for validate.exclude * Autogen for validation.PodSecurity * working autogen with simple tests * change validate.PodSecurity failure response format * make codegen * fix lint errors, remove debug prints * fix tags * fix tags * fix crash when deleting pods matching validate.podSecurity rule. Only check validatePodSecurity() when it's not a delete request * Changes requested * Changes requested 2 * Changes requested 3 * Changes requested 4 * Changes requested and make codegen * fix host namespaces control * fix lint * fix codegen error * update docs/crd/v1/index.html Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix path Signed-off-by: ShutingZhao <shuting@nirmata.com> * update crd schema Signed-off-by: ShutingZhao <shuting@nirmata.com> * update charts/kyverno/templates/crds.yaml Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: ShutingZhao <shuting@nirmata.com>
2022-08-31 09:16:31 +00:00
if err != nil {
return nil, nil, err
}
err = json.Unmarshal(resourceBytes, &cronJob)
if err != nil {
return nil, nil, err
}
podSpec = &cronJob.Spec.JobTemplate.Spec.Template.Spec
metadata = &cronJob.Spec.JobTemplate.ObjectMeta
} else if kind == "Pod" {
var pod corev1.Pod
resourceBytes, err := v.policyContext.newResource.MarshalJSON()
Extend Pod Security Admission (#4364) * init commit for pss Signed-off-by: ShutingZhao <shuting@nirmata.com> * add test for Volume Type control * add test for App Armor control except ExemptProfile. Fix PSS profile check in EvaluatePSS() * remove unused code, still a JMESPATH problem with app armor ExemptProfile() * test for Host Process / Host Namespaces controls * test for Privileged containers controls * test for HostPathVolume control * test for HostPorts control * test for HostPorts control * test for SELinux control * test for Proc mount type control * Set to baseline * test for Seccomp control * test for Sysctl control * test for Privilege escalation control * test for Run as non root control * test for Restricted Seccomp control * Add problems to address * add solutions to problems * Add validate rule for PSA * api.Version --> string. latest by default * Exclude all values for a restrictedField * add tests for kyverno engine * code to be used to match kyverno rule's namespace * Refacto pkg/pss * fix multiple problems: not matching containers, add contains methods, select the right container when we have the same exclude.RestrictedField for multiple containers: * EvaluatePod * Use EvaluatePod in kyverno engine * Set pod instead of container in context to use full Jmespath. e.g.: securityContext.capabilities.add --> spec.containers[*].securityContext.capabilities.add * Check if PSSCheckResult matched at least one exclude value * add tests for engine * fix engine validation test * config * update go.mod and go.sum * crds * Check validate value: add PodSecurity * exclude all restrictedFields when we only specify the controlName * ExemptProfile(): check if exclud.RestrictedField matches at least one restrictedField.path * handle containers, initContainers, ephemeralContainers when we only specify the controlName (all restrictedFields are excluded) * refacto pks/pss/evaluate.go and add pkg/engine/validation_test.go * add all controls with containers in restrictedFields as comments * add tests for capabilities and privileged containers and fix some errors * add tests for host ports control * add tests for proc mount control * add tests for privilege escalation control * add tests for capabilities control * remove comments * new algo * refacto algo, working. Add test for hostProcess control * remove unused code * fix getPodWithNotMatchingContainers(), add tests for host namespaces control * refacto ExemptProfile() * get values for a specific container. add test for SELinuxOptions control * fix allowedValues for SELinuxOptions * add tests for seccompProfile_baseline control * refacto checkContainers(), add test for seccomp control * add test for running as non root control * add some tests for runAsUser control, have to update current PSA version * add sysctls control * add allowed values for restrictedVolumes control * add some tests for appArmor, volume types controls * add tests for volume types control * add tests for hostPath volume control * finish merge conflicts and add tests for runAsUser * update charts and crds * exclude.images optional * change volume types control exclude values * add appAmor control * fix: did not match any exclude value for pod-level restrictedFields * create autogen for validate.PodSecurity * clean code, remove logs * fix sonatype lift errors * fix sonatype lift errors: duplication * fix crash in pkg/policy/validate/ tests and unmarshall errors for pkg/engine tests * beginning of autogen implement for validate.exclude * Autogen for validation.PodSecurity * working autogen with simple tests * change validate.PodSecurity failure response format * make codegen * fix lint errors, remove debug prints * fix tags * fix tags * fix crash when deleting pods matching validate.podSecurity rule. Only check validatePodSecurity() when it's not a delete request * Changes requested * Changes requested 2 * Changes requested 3 * Changes requested 4 * Changes requested and make codegen * fix host namespaces control * fix lint * fix codegen error * update docs/crd/v1/index.html Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix path Signed-off-by: ShutingZhao <shuting@nirmata.com> * update crd schema Signed-off-by: ShutingZhao <shuting@nirmata.com> * update charts/kyverno/templates/crds.yaml Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: ShutingZhao <shuting@nirmata.com>
2022-08-31 09:16:31 +00:00
if err != nil {
return nil, nil, err
}
err = json.Unmarshal(resourceBytes, &pod)
if err != nil {
return nil, nil, err
}
podSpec = &pod.Spec
metadata = &pod.ObjectMeta
return podSpec, metadata, nil
}
if err != nil {
return nil, nil, err
}
return podSpec, metadata, err
}
// Unstructured
func (v *validator) validatePodSecurity() *engineapi.RuleResponse {
Extend Pod Security Admission (#4364) * init commit for pss Signed-off-by: ShutingZhao <shuting@nirmata.com> * add test for Volume Type control * add test for App Armor control except ExemptProfile. Fix PSS profile check in EvaluatePSS() * remove unused code, still a JMESPATH problem with app armor ExemptProfile() * test for Host Process / Host Namespaces controls * test for Privileged containers controls * test for HostPathVolume control * test for HostPorts control * test for HostPorts control * test for SELinux control * test for Proc mount type control * Set to baseline * test for Seccomp control * test for Sysctl control * test for Privilege escalation control * test for Run as non root control * test for Restricted Seccomp control * Add problems to address * add solutions to problems * Add validate rule for PSA * api.Version --> string. latest by default * Exclude all values for a restrictedField * add tests for kyverno engine * code to be used to match kyverno rule's namespace * Refacto pkg/pss * fix multiple problems: not matching containers, add contains methods, select the right container when we have the same exclude.RestrictedField for multiple containers: * EvaluatePod * Use EvaluatePod in kyverno engine * Set pod instead of container in context to use full Jmespath. e.g.: securityContext.capabilities.add --> spec.containers[*].securityContext.capabilities.add * Check if PSSCheckResult matched at least one exclude value * add tests for engine * fix engine validation test * config * update go.mod and go.sum * crds * Check validate value: add PodSecurity * exclude all restrictedFields when we only specify the controlName * ExemptProfile(): check if exclud.RestrictedField matches at least one restrictedField.path * handle containers, initContainers, ephemeralContainers when we only specify the controlName (all restrictedFields are excluded) * refacto pks/pss/evaluate.go and add pkg/engine/validation_test.go * add all controls with containers in restrictedFields as comments * add tests for capabilities and privileged containers and fix some errors * add tests for host ports control * add tests for proc mount control * add tests for privilege escalation control * add tests for capabilities control * remove comments * new algo * refacto algo, working. Add test for hostProcess control * remove unused code * fix getPodWithNotMatchingContainers(), add tests for host namespaces control * refacto ExemptProfile() * get values for a specific container. add test for SELinuxOptions control * fix allowedValues for SELinuxOptions * add tests for seccompProfile_baseline control * refacto checkContainers(), add test for seccomp control * add test for running as non root control * add some tests for runAsUser control, have to update current PSA version * add sysctls control * add allowed values for restrictedVolumes control * add some tests for appArmor, volume types controls * add tests for volume types control * add tests for hostPath volume control * finish merge conflicts and add tests for runAsUser * update charts and crds * exclude.images optional * change volume types control exclude values * add appAmor control * fix: did not match any exclude value for pod-level restrictedFields * create autogen for validate.PodSecurity * clean code, remove logs * fix sonatype lift errors * fix sonatype lift errors: duplication * fix crash in pkg/policy/validate/ tests and unmarshall errors for pkg/engine tests * beginning of autogen implement for validate.exclude * Autogen for validation.PodSecurity * working autogen with simple tests * change validate.PodSecurity failure response format * make codegen * fix lint errors, remove debug prints * fix tags * fix tags * fix crash when deleting pods matching validate.podSecurity rule. Only check validatePodSecurity() when it's not a delete request * Changes requested * Changes requested 2 * Changes requested 3 * Changes requested 4 * Changes requested and make codegen * fix host namespaces control * fix lint * fix codegen error * update docs/crd/v1/index.html Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix path Signed-off-by: ShutingZhao <shuting@nirmata.com> * update crd schema Signed-off-by: ShutingZhao <shuting@nirmata.com> * update charts/kyverno/templates/crds.yaml Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: ShutingZhao <shuting@nirmata.com>
2022-08-31 09:16:31 +00:00
// Marshal pod metadata and spec
podSpec, metadata, err := getSpec(v)
if err != nil {
return ruleError(v.rule, engineapi.Validation, "Error while getting new resource", err)
Extend Pod Security Admission (#4364) * init commit for pss Signed-off-by: ShutingZhao <shuting@nirmata.com> * add test for Volume Type control * add test for App Armor control except ExemptProfile. Fix PSS profile check in EvaluatePSS() * remove unused code, still a JMESPATH problem with app armor ExemptProfile() * test for Host Process / Host Namespaces controls * test for Privileged containers controls * test for HostPathVolume control * test for HostPorts control * test for HostPorts control * test for SELinux control * test for Proc mount type control * Set to baseline * test for Seccomp control * test for Sysctl control * test for Privilege escalation control * test for Run as non root control * test for Restricted Seccomp control * Add problems to address * add solutions to problems * Add validate rule for PSA * api.Version --> string. latest by default * Exclude all values for a restrictedField * add tests for kyverno engine * code to be used to match kyverno rule's namespace * Refacto pkg/pss * fix multiple problems: not matching containers, add contains methods, select the right container when we have the same exclude.RestrictedField for multiple containers: * EvaluatePod * Use EvaluatePod in kyverno engine * Set pod instead of container in context to use full Jmespath. e.g.: securityContext.capabilities.add --> spec.containers[*].securityContext.capabilities.add * Check if PSSCheckResult matched at least one exclude value * add tests for engine * fix engine validation test * config * update go.mod and go.sum * crds * Check validate value: add PodSecurity * exclude all restrictedFields when we only specify the controlName * ExemptProfile(): check if exclud.RestrictedField matches at least one restrictedField.path * handle containers, initContainers, ephemeralContainers when we only specify the controlName (all restrictedFields are excluded) * refacto pks/pss/evaluate.go and add pkg/engine/validation_test.go * add all controls with containers in restrictedFields as comments * add tests for capabilities and privileged containers and fix some errors * add tests for host ports control * add tests for proc mount control * add tests for privilege escalation control * add tests for capabilities control * remove comments * new algo * refacto algo, working. Add test for hostProcess control * remove unused code * fix getPodWithNotMatchingContainers(), add tests for host namespaces control * refacto ExemptProfile() * get values for a specific container. add test for SELinuxOptions control * fix allowedValues for SELinuxOptions * add tests for seccompProfile_baseline control * refacto checkContainers(), add test for seccomp control * add test for running as non root control * add some tests for runAsUser control, have to update current PSA version * add sysctls control * add allowed values for restrictedVolumes control * add some tests for appArmor, volume types controls * add tests for volume types control * add tests for hostPath volume control * finish merge conflicts and add tests for runAsUser * update charts and crds * exclude.images optional * change volume types control exclude values * add appAmor control * fix: did not match any exclude value for pod-level restrictedFields * create autogen for validate.PodSecurity * clean code, remove logs * fix sonatype lift errors * fix sonatype lift errors: duplication * fix crash in pkg/policy/validate/ tests and unmarshall errors for pkg/engine tests * beginning of autogen implement for validate.exclude * Autogen for validation.PodSecurity * working autogen with simple tests * change validate.PodSecurity failure response format * make codegen * fix lint errors, remove debug prints * fix tags * fix tags * fix crash when deleting pods matching validate.podSecurity rule. Only check validatePodSecurity() when it's not a delete request * Changes requested * Changes requested 2 * Changes requested 3 * Changes requested 4 * Changes requested and make codegen * fix host namespaces control * fix lint * fix codegen error * update docs/crd/v1/index.html Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix path Signed-off-by: ShutingZhao <shuting@nirmata.com> * update crd schema Signed-off-by: ShutingZhao <shuting@nirmata.com> * update charts/kyverno/templates/crds.yaml Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: ShutingZhao <shuting@nirmata.com>
2022-08-31 09:16:31 +00:00
}
pod := &corev1.Pod{
Spec: *podSpec,
ObjectMeta: *metadata,
}
allowed, pssChecks, err := pss.EvaluatePod(v.podSecurity, pod)
Extend Pod Security Admission (#4364) * init commit for pss Signed-off-by: ShutingZhao <shuting@nirmata.com> * add test for Volume Type control * add test for App Armor control except ExemptProfile. Fix PSS profile check in EvaluatePSS() * remove unused code, still a JMESPATH problem with app armor ExemptProfile() * test for Host Process / Host Namespaces controls * test for Privileged containers controls * test for HostPathVolume control * test for HostPorts control * test for HostPorts control * test for SELinux control * test for Proc mount type control * Set to baseline * test for Seccomp control * test for Sysctl control * test for Privilege escalation control * test for Run as non root control * test for Restricted Seccomp control * Add problems to address * add solutions to problems * Add validate rule for PSA * api.Version --> string. latest by default * Exclude all values for a restrictedField * add tests for kyverno engine * code to be used to match kyverno rule's namespace * Refacto pkg/pss * fix multiple problems: not matching containers, add contains methods, select the right container when we have the same exclude.RestrictedField for multiple containers: * EvaluatePod * Use EvaluatePod in kyverno engine * Set pod instead of container in context to use full Jmespath. e.g.: securityContext.capabilities.add --> spec.containers[*].securityContext.capabilities.add * Check if PSSCheckResult matched at least one exclude value * add tests for engine * fix engine validation test * config * update go.mod and go.sum * crds * Check validate value: add PodSecurity * exclude all restrictedFields when we only specify the controlName * ExemptProfile(): check if exclud.RestrictedField matches at least one restrictedField.path * handle containers, initContainers, ephemeralContainers when we only specify the controlName (all restrictedFields are excluded) * refacto pks/pss/evaluate.go and add pkg/engine/validation_test.go * add all controls with containers in restrictedFields as comments * add tests for capabilities and privileged containers and fix some errors * add tests for host ports control * add tests for proc mount control * add tests for privilege escalation control * add tests for capabilities control * remove comments * new algo * refacto algo, working. Add test for hostProcess control * remove unused code * fix getPodWithNotMatchingContainers(), add tests for host namespaces control * refacto ExemptProfile() * get values for a specific container. add test for SELinuxOptions control * fix allowedValues for SELinuxOptions * add tests for seccompProfile_baseline control * refacto checkContainers(), add test for seccomp control * add test for running as non root control * add some tests for runAsUser control, have to update current PSA version * add sysctls control * add allowed values for restrictedVolumes control * add some tests for appArmor, volume types controls * add tests for volume types control * add tests for hostPath volume control * finish merge conflicts and add tests for runAsUser * update charts and crds * exclude.images optional * change volume types control exclude values * add appAmor control * fix: did not match any exclude value for pod-level restrictedFields * create autogen for validate.PodSecurity * clean code, remove logs * fix sonatype lift errors * fix sonatype lift errors: duplication * fix crash in pkg/policy/validate/ tests and unmarshall errors for pkg/engine tests * beginning of autogen implement for validate.exclude * Autogen for validation.PodSecurity * working autogen with simple tests * change validate.PodSecurity failure response format * make codegen * fix lint errors, remove debug prints * fix tags * fix tags * fix crash when deleting pods matching validate.podSecurity rule. Only check validatePodSecurity() when it's not a delete request * Changes requested * Changes requested 2 * Changes requested 3 * Changes requested 4 * Changes requested and make codegen * fix host namespaces control * fix lint * fix codegen error * update docs/crd/v1/index.html Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix path Signed-off-by: ShutingZhao <shuting@nirmata.com> * update crd schema Signed-off-by: ShutingZhao <shuting@nirmata.com> * update charts/kyverno/templates/crds.yaml Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: ShutingZhao <shuting@nirmata.com>
2022-08-31 09:16:31 +00:00
if err != nil {
return ruleError(v.rule, engineapi.Validation, "failed to parse pod security api version", err)
Extend Pod Security Admission (#4364) * init commit for pss Signed-off-by: ShutingZhao <shuting@nirmata.com> * add test for Volume Type control * add test for App Armor control except ExemptProfile. Fix PSS profile check in EvaluatePSS() * remove unused code, still a JMESPATH problem with app armor ExemptProfile() * test for Host Process / Host Namespaces controls * test for Privileged containers controls * test for HostPathVolume control * test for HostPorts control * test for HostPorts control * test for SELinux control * test for Proc mount type control * Set to baseline * test for Seccomp control * test for Sysctl control * test for Privilege escalation control * test for Run as non root control * test for Restricted Seccomp control * Add problems to address * add solutions to problems * Add validate rule for PSA * api.Version --> string. latest by default * Exclude all values for a restrictedField * add tests for kyverno engine * code to be used to match kyverno rule's namespace * Refacto pkg/pss * fix multiple problems: not matching containers, add contains methods, select the right container when we have the same exclude.RestrictedField for multiple containers: * EvaluatePod * Use EvaluatePod in kyverno engine * Set pod instead of container in context to use full Jmespath. e.g.: securityContext.capabilities.add --> spec.containers[*].securityContext.capabilities.add * Check if PSSCheckResult matched at least one exclude value * add tests for engine * fix engine validation test * config * update go.mod and go.sum * crds * Check validate value: add PodSecurity * exclude all restrictedFields when we only specify the controlName * ExemptProfile(): check if exclud.RestrictedField matches at least one restrictedField.path * handle containers, initContainers, ephemeralContainers when we only specify the controlName (all restrictedFields are excluded) * refacto pks/pss/evaluate.go and add pkg/engine/validation_test.go * add all controls with containers in restrictedFields as comments * add tests for capabilities and privileged containers and fix some errors * add tests for host ports control * add tests for proc mount control * add tests for privilege escalation control * add tests for capabilities control * remove comments * new algo * refacto algo, working. Add test for hostProcess control * remove unused code * fix getPodWithNotMatchingContainers(), add tests for host namespaces control * refacto ExemptProfile() * get values for a specific container. add test for SELinuxOptions control * fix allowedValues for SELinuxOptions * add tests for seccompProfile_baseline control * refacto checkContainers(), add test for seccomp control * add test for running as non root control * add some tests for runAsUser control, have to update current PSA version * add sysctls control * add allowed values for restrictedVolumes control * add some tests for appArmor, volume types controls * add tests for volume types control * add tests for hostPath volume control * finish merge conflicts and add tests for runAsUser * update charts and crds * exclude.images optional * change volume types control exclude values * add appAmor control * fix: did not match any exclude value for pod-level restrictedFields * create autogen for validate.PodSecurity * clean code, remove logs * fix sonatype lift errors * fix sonatype lift errors: duplication * fix crash in pkg/policy/validate/ tests and unmarshall errors for pkg/engine tests * beginning of autogen implement for validate.exclude * Autogen for validation.PodSecurity * working autogen with simple tests * change validate.PodSecurity failure response format * make codegen * fix lint errors, remove debug prints * fix tags * fix tags * fix crash when deleting pods matching validate.podSecurity rule. Only check validatePodSecurity() when it's not a delete request * Changes requested * Changes requested 2 * Changes requested 3 * Changes requested 4 * Changes requested and make codegen * fix host namespaces control * fix lint * fix codegen error * update docs/crd/v1/index.html Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix path Signed-off-by: ShutingZhao <shuting@nirmata.com> * update crd schema Signed-off-by: ShutingZhao <shuting@nirmata.com> * update charts/kyverno/templates/crds.yaml Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: ShutingZhao <shuting@nirmata.com>
2022-08-31 09:16:31 +00:00
}
podSecurityChecks := &engineapi.PodSecurityChecks{
Level: v.podSecurity.Level,
Version: v.podSecurity.Version,
Checks: pssChecks,
}
Extend Pod Security Admission (#4364) * init commit for pss Signed-off-by: ShutingZhao <shuting@nirmata.com> * add test for Volume Type control * add test for App Armor control except ExemptProfile. Fix PSS profile check in EvaluatePSS() * remove unused code, still a JMESPATH problem with app armor ExemptProfile() * test for Host Process / Host Namespaces controls * test for Privileged containers controls * test for HostPathVolume control * test for HostPorts control * test for HostPorts control * test for SELinux control * test for Proc mount type control * Set to baseline * test for Seccomp control * test for Sysctl control * test for Privilege escalation control * test for Run as non root control * test for Restricted Seccomp control * Add problems to address * add solutions to problems * Add validate rule for PSA * api.Version --> string. latest by default * Exclude all values for a restrictedField * add tests for kyverno engine * code to be used to match kyverno rule's namespace * Refacto pkg/pss * fix multiple problems: not matching containers, add contains methods, select the right container when we have the same exclude.RestrictedField for multiple containers: * EvaluatePod * Use EvaluatePod in kyverno engine * Set pod instead of container in context to use full Jmespath. e.g.: securityContext.capabilities.add --> spec.containers[*].securityContext.capabilities.add * Check if PSSCheckResult matched at least one exclude value * add tests for engine * fix engine validation test * config * update go.mod and go.sum * crds * Check validate value: add PodSecurity * exclude all restrictedFields when we only specify the controlName * ExemptProfile(): check if exclud.RestrictedField matches at least one restrictedField.path * handle containers, initContainers, ephemeralContainers when we only specify the controlName (all restrictedFields are excluded) * refacto pks/pss/evaluate.go and add pkg/engine/validation_test.go * add all controls with containers in restrictedFields as comments * add tests for capabilities and privileged containers and fix some errors * add tests for host ports control * add tests for proc mount control * add tests for privilege escalation control * add tests for capabilities control * remove comments * new algo * refacto algo, working. Add test for hostProcess control * remove unused code * fix getPodWithNotMatchingContainers(), add tests for host namespaces control * refacto ExemptProfile() * get values for a specific container. add test for SELinuxOptions control * fix allowedValues for SELinuxOptions * add tests for seccompProfile_baseline control * refacto checkContainers(), add test for seccomp control * add test for running as non root control * add some tests for runAsUser control, have to update current PSA version * add sysctls control * add allowed values for restrictedVolumes control * add some tests for appArmor, volume types controls * add tests for volume types control * add tests for hostPath volume control * finish merge conflicts and add tests for runAsUser * update charts and crds * exclude.images optional * change volume types control exclude values * add appAmor control * fix: did not match any exclude value for pod-level restrictedFields * create autogen for validate.PodSecurity * clean code, remove logs * fix sonatype lift errors * fix sonatype lift errors: duplication * fix crash in pkg/policy/validate/ tests and unmarshall errors for pkg/engine tests * beginning of autogen implement for validate.exclude * Autogen for validation.PodSecurity * working autogen with simple tests * change validate.PodSecurity failure response format * make codegen * fix lint errors, remove debug prints * fix tags * fix tags * fix crash when deleting pods matching validate.podSecurity rule. Only check validatePodSecurity() when it's not a delete request * Changes requested * Changes requested 2 * Changes requested 3 * Changes requested 4 * Changes requested and make codegen * fix host namespaces control * fix lint * fix codegen error * update docs/crd/v1/index.html Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix path Signed-off-by: ShutingZhao <shuting@nirmata.com> * update crd schema Signed-off-by: ShutingZhao <shuting@nirmata.com> * update charts/kyverno/templates/crds.yaml Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: ShutingZhao <shuting@nirmata.com>
2022-08-31 09:16:31 +00:00
if allowed {
msg := fmt.Sprintf("Validation rule '%s' passed.", v.rule.Name)
rspn := ruleResponse(*v.rule, engineapi.Validation, msg, engineapi.RuleStatusPass)
rspn.PodSecurityChecks = podSecurityChecks
return rspn
Extend Pod Security Admission (#4364) * init commit for pss Signed-off-by: ShutingZhao <shuting@nirmata.com> * add test for Volume Type control * add test for App Armor control except ExemptProfile. Fix PSS profile check in EvaluatePSS() * remove unused code, still a JMESPATH problem with app armor ExemptProfile() * test for Host Process / Host Namespaces controls * test for Privileged containers controls * test for HostPathVolume control * test for HostPorts control * test for HostPorts control * test for SELinux control * test for Proc mount type control * Set to baseline * test for Seccomp control * test for Sysctl control * test for Privilege escalation control * test for Run as non root control * test for Restricted Seccomp control * Add problems to address * add solutions to problems * Add validate rule for PSA * api.Version --> string. latest by default * Exclude all values for a restrictedField * add tests for kyverno engine * code to be used to match kyverno rule's namespace * Refacto pkg/pss * fix multiple problems: not matching containers, add contains methods, select the right container when we have the same exclude.RestrictedField for multiple containers: * EvaluatePod * Use EvaluatePod in kyverno engine * Set pod instead of container in context to use full Jmespath. e.g.: securityContext.capabilities.add --> spec.containers[*].securityContext.capabilities.add * Check if PSSCheckResult matched at least one exclude value * add tests for engine * fix engine validation test * config * update go.mod and go.sum * crds * Check validate value: add PodSecurity * exclude all restrictedFields when we only specify the controlName * ExemptProfile(): check if exclud.RestrictedField matches at least one restrictedField.path * handle containers, initContainers, ephemeralContainers when we only specify the controlName (all restrictedFields are excluded) * refacto pks/pss/evaluate.go and add pkg/engine/validation_test.go * add all controls with containers in restrictedFields as comments * add tests for capabilities and privileged containers and fix some errors * add tests for host ports control * add tests for proc mount control * add tests for privilege escalation control * add tests for capabilities control * remove comments * new algo * refacto algo, working. Add test for hostProcess control * remove unused code * fix getPodWithNotMatchingContainers(), add tests for host namespaces control * refacto ExemptProfile() * get values for a specific container. add test for SELinuxOptions control * fix allowedValues for SELinuxOptions * add tests for seccompProfile_baseline control * refacto checkContainers(), add test for seccomp control * add test for running as non root control * add some tests for runAsUser control, have to update current PSA version * add sysctls control * add allowed values for restrictedVolumes control * add some tests for appArmor, volume types controls * add tests for volume types control * add tests for hostPath volume control * finish merge conflicts and add tests for runAsUser * update charts and crds * exclude.images optional * change volume types control exclude values * add appAmor control * fix: did not match any exclude value for pod-level restrictedFields * create autogen for validate.PodSecurity * clean code, remove logs * fix sonatype lift errors * fix sonatype lift errors: duplication * fix crash in pkg/policy/validate/ tests and unmarshall errors for pkg/engine tests * beginning of autogen implement for validate.exclude * Autogen for validation.PodSecurity * working autogen with simple tests * change validate.PodSecurity failure response format * make codegen * fix lint errors, remove debug prints * fix tags * fix tags * fix crash when deleting pods matching validate.podSecurity rule. Only check validatePodSecurity() when it's not a delete request * Changes requested * Changes requested 2 * Changes requested 3 * Changes requested 4 * Changes requested and make codegen * fix host namespaces control * fix lint * fix codegen error * update docs/crd/v1/index.html Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix path Signed-off-by: ShutingZhao <shuting@nirmata.com> * update crd schema Signed-off-by: ShutingZhao <shuting@nirmata.com> * update charts/kyverno/templates/crds.yaml Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: ShutingZhao <shuting@nirmata.com>
2022-08-31 09:16:31 +00:00
} else {
msg := fmt.Sprintf(`Validation rule '%s' failed. It violates PodSecurity "%s:%s": %s`, v.rule.Name, v.podSecurity.Level, v.podSecurity.Version, pss.FormatChecksPrint(pssChecks))
rspn := ruleResponse(*v.rule, engineapi.Validation, msg, engineapi.RuleStatusFail)
rspn.PodSecurityChecks = podSecurityChecks
return rspn
Extend Pod Security Admission (#4364) * init commit for pss Signed-off-by: ShutingZhao <shuting@nirmata.com> * add test for Volume Type control * add test for App Armor control except ExemptProfile. Fix PSS profile check in EvaluatePSS() * remove unused code, still a JMESPATH problem with app armor ExemptProfile() * test for Host Process / Host Namespaces controls * test for Privileged containers controls * test for HostPathVolume control * test for HostPorts control * test for HostPorts control * test for SELinux control * test for Proc mount type control * Set to baseline * test for Seccomp control * test for Sysctl control * test for Privilege escalation control * test for Run as non root control * test for Restricted Seccomp control * Add problems to address * add solutions to problems * Add validate rule for PSA * api.Version --> string. latest by default * Exclude all values for a restrictedField * add tests for kyverno engine * code to be used to match kyverno rule's namespace * Refacto pkg/pss * fix multiple problems: not matching containers, add contains methods, select the right container when we have the same exclude.RestrictedField for multiple containers: * EvaluatePod * Use EvaluatePod in kyverno engine * Set pod instead of container in context to use full Jmespath. e.g.: securityContext.capabilities.add --> spec.containers[*].securityContext.capabilities.add * Check if PSSCheckResult matched at least one exclude value * add tests for engine * fix engine validation test * config * update go.mod and go.sum * crds * Check validate value: add PodSecurity * exclude all restrictedFields when we only specify the controlName * ExemptProfile(): check if exclud.RestrictedField matches at least one restrictedField.path * handle containers, initContainers, ephemeralContainers when we only specify the controlName (all restrictedFields are excluded) * refacto pks/pss/evaluate.go and add pkg/engine/validation_test.go * add all controls with containers in restrictedFields as comments * add tests for capabilities and privileged containers and fix some errors * add tests for host ports control * add tests for proc mount control * add tests for privilege escalation control * add tests for capabilities control * remove comments * new algo * refacto algo, working. Add test for hostProcess control * remove unused code * fix getPodWithNotMatchingContainers(), add tests for host namespaces control * refacto ExemptProfile() * get values for a specific container. add test for SELinuxOptions control * fix allowedValues for SELinuxOptions * add tests for seccompProfile_baseline control * refacto checkContainers(), add test for seccomp control * add test for running as non root control * add some tests for runAsUser control, have to update current PSA version * add sysctls control * add allowed values for restrictedVolumes control * add some tests for appArmor, volume types controls * add tests for volume types control * add tests for hostPath volume control * finish merge conflicts and add tests for runAsUser * update charts and crds * exclude.images optional * change volume types control exclude values * add appAmor control * fix: did not match any exclude value for pod-level restrictedFields * create autogen for validate.PodSecurity * clean code, remove logs * fix sonatype lift errors * fix sonatype lift errors: duplication * fix crash in pkg/policy/validate/ tests and unmarshall errors for pkg/engine tests * beginning of autogen implement for validate.exclude * Autogen for validation.PodSecurity * working autogen with simple tests * change validate.PodSecurity failure response format * make codegen * fix lint errors, remove debug prints * fix tags * fix tags * fix crash when deleting pods matching validate.podSecurity rule. Only check validatePodSecurity() when it's not a delete request * Changes requested * Changes requested 2 * Changes requested 3 * Changes requested 4 * Changes requested and make codegen * fix host namespaces control * fix lint * fix codegen error * update docs/crd/v1/index.html Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix path Signed-off-by: ShutingZhao <shuting@nirmata.com> * update crd schema Signed-off-by: ShutingZhao <shuting@nirmata.com> * update charts/kyverno/templates/crds.yaml Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: ShutingZhao <shuting@nirmata.com>
2022-08-31 09:16:31 +00:00
}
}
func (v *validator) validateResourceWithRule() *engineapi.RuleResponse {
if !isEmptyUnstructured(&v.policyContext.element) {
return v.validatePatterns(v.policyContext.element)
}
if isDeleteRequest(v.policyContext) {
v.log.V(3).Info("skipping validation on deleted resource")
return nil
}
resp := v.validatePatterns(v.policyContext.newResource)
return resp
}
func isDeleteRequest(ctx *PolicyContext) bool {
// if the OldResource is not empty, and the NewResource is empty, the request is a DELETE
return isEmptyUnstructured(&ctx.newResource)
}
func isEmptyUnstructured(u *unstructured.Unstructured) bool {
if u == nil {
return true
}
if reflect.DeepEqual(*u, unstructured.Unstructured{}) {
return true
}
return false
2020-12-23 23:10:07 +00:00
}
2020-05-05 13:49:47 +00:00
2020-12-23 23:10:07 +00:00
// matches checks if either the new or old resource satisfies the filter conditions defined in the rule
func matches(logger logr.Logger, rule *kyvernov1.Rule, ctx *PolicyContext, subresourceGVKToAPIResource map[string]*metav1.APIResource) bool {
err := MatchesResourceDescription(subresourceGVKToAPIResource, ctx.newResource, *rule, ctx.admissionInfo, ctx.excludeGroupRole, ctx.namespaceLabels, "", ctx.subresource)
2020-12-23 23:10:07 +00:00
if err == nil {
return true
}
if !reflect.DeepEqual(ctx.OldResource, unstructured.Unstructured{}) {
err := MatchesResourceDescription(subresourceGVKToAPIResource, ctx.oldResource, *rule, ctx.admissionInfo, ctx.excludeGroupRole, ctx.namespaceLabels, "", ctx.subresource)
2020-12-23 23:10:07 +00:00
if err == nil {
return true
2019-09-03 22:48:13 +00:00
}
}
logger.V(5).Info("resource does not match rule", "reason", err.Error())
2020-12-23 23:10:07 +00:00
return false
}
2019-08-21 19:38:15 +00:00
// validatePatterns validate pattern and anyPattern
func (v *validator) validatePatterns(resource unstructured.Unstructured) *engineapi.RuleResponse {
if v.pattern != nil {
if err := validate.MatchPattern(v.log, resource.Object, v.pattern); err != nil {
pe, ok := err.(*validate.PatternError)
if ok {
v.log.V(3).Info("validation error", "path", pe.Path, "error", err.Error())
if pe.Skip {
return ruleResponse(*v.rule, engineapi.Validation, pe.Error(), engineapi.RuleStatusSkip)
}
if pe.Path == "" {
return ruleResponse(*v.rule, engineapi.Validation, v.buildErrorMessage(err, ""), engineapi.RuleStatusError)
}
return ruleResponse(*v.rule, engineapi.Validation, v.buildErrorMessage(err, pe.Path), engineapi.RuleStatusFail)
}
return ruleResponse(*v.rule, engineapi.Validation, v.buildErrorMessage(err, pe.Path), engineapi.RuleStatusError)
2020-02-14 19:59:28 +00:00
}
v.log.V(4).Info("successfully processed rule")
msg := fmt.Sprintf("validation rule '%s' passed.", v.rule.Name)
return ruleResponse(*v.rule, engineapi.Validation, msg, engineapi.RuleStatusPass)
}
if v.anyPattern != nil {
2020-02-14 19:59:28 +00:00
var failedAnyPatternsErrors []error
var skippedAnyPatternErrors []error
2020-02-14 19:59:28 +00:00
var err error
2020-11-14 00:25:51 +00:00
anyPatterns, err := deserializeAnyPattern(v.anyPattern)
2020-11-14 00:25:51 +00:00
if err != nil {
msg := fmt.Sprintf("failed to deserialize anyPattern, expected type array: %v", err)
return ruleResponse(*v.rule, engineapi.Validation, msg, engineapi.RuleStatusError)
2020-11-14 00:25:51 +00:00
}
for idx, pattern := range anyPatterns {
err := validate.MatchPattern(v.log, resource.Object, pattern)
2020-02-14 19:59:28 +00:00
if err == nil {
msg := fmt.Sprintf("validation rule '%s' anyPattern[%d] passed.", v.rule.Name, idx)
return ruleResponse(*v.rule, engineapi.Validation, msg, engineapi.RuleStatusPass)
}
if pe, ok := err.(*validate.PatternError); ok {
var patternErr error
v.log.V(3).Info("validation rule failed", "anyPattern[%d]", idx, "path", pe.Path)
if pe.Skip {
patternErr = fmt.Errorf("rule %s[%d] skipped: %s", v.rule.Name, idx, err.Error())
skippedAnyPatternErrors = append(skippedAnyPatternErrors, patternErr)
} else {
if pe.Path == "" {
patternErr = fmt.Errorf("rule %s[%d] failed: %s", v.rule.Name, idx, err.Error())
} else {
patternErr = fmt.Errorf("rule %s[%d] failed at path %s", v.rule.Name, idx, pe.Path)
}
failedAnyPatternsErrors = append(failedAnyPatternsErrors, patternErr)
}
}
}
2020-02-14 19:59:28 +00:00
// Any Pattern validation errors
if len(skippedAnyPatternErrors) > 0 && len(failedAnyPatternsErrors) == 0 {
var errorStr []string
for _, err := range skippedAnyPatternErrors {
errorStr = append(errorStr, err.Error())
}
v.log.V(4).Info(fmt.Sprintf("Validation rule '%s' skipped. %s", v.rule.Name, errorStr))
return ruleResponse(*v.rule, engineapi.Validation, strings.Join(errorStr, " "), engineapi.RuleStatusSkip)
} else if len(failedAnyPatternsErrors) > 0 {
2020-02-14 19:59:28 +00:00
var errorStr []string
for _, err := range failedAnyPatternsErrors {
errorStr = append(errorStr, err.Error())
}
v.log.V(4).Info(fmt.Sprintf("Validation rule '%s' failed. %s", v.rule.Name, errorStr))
msg := buildAnyPatternErrorMessage(v.rule, errorStr)
return ruleResponse(*v.rule, engineapi.Validation, msg, engineapi.RuleStatusFail)
}
2019-08-21 19:38:15 +00:00
}
return ruleResponse(*v.rule, engineapi.Validation, v.rule.Validation.Message, engineapi.RuleStatusPass)
}
func deserializeAnyPattern(anyPattern apiextensions.JSON) ([]interface{}, error) {
if anyPattern == nil {
return nil, nil
}
ap, err := json.Marshal(anyPattern)
if err != nil {
return nil, err
}
var res []interface{}
if err := json.Unmarshal(ap, &res); err != nil {
return nil, err
}
return res, nil
}
func (v *validator) buildErrorMessage(err error, path string) string {
if v.rule.Validation.Message == "" {
if path != "" {
return fmt.Sprintf("validation error: rule %s failed at path %s", v.rule.Name, path)
}
return fmt.Sprintf("validation error: rule %s execution error: %s", v.rule.Name, err.Error())
}
msgRaw, sErr := variables.SubstituteAll(v.log, v.policyContext.jsonContext, v.rule.Validation.Message)
if sErr != nil {
v.log.V(2).Info("failed to substitute variables in message", "error", sErr)
return fmt.Sprintf("validation error: variables substitution error in rule %s execution error: %s", v.rule.Name, err.Error())
} else {
msg := msgRaw.(string)
if !strings.HasSuffix(msg, ".") {
msg = msg + "."
}
if path != "" {
return fmt.Sprintf("validation error: %s rule %s failed at path %s", msg, v.rule.Name, path)
}
return fmt.Sprintf("validation error: %s rule %s execution error: %s", msg, v.rule.Name, err.Error())
}
}
func buildAnyPatternErrorMessage(rule *kyvernov1.Rule, errors []string) string {
errStr := strings.Join(errors, " ")
if rule.Validation.Message == "" {
return fmt.Sprintf("validation error: %s", errStr)
}
if strings.HasSuffix(rule.Validation.Message, ".") {
return fmt.Sprintf("validation error: %s %s", rule.Validation.Message, errStr)
}
return fmt.Sprintf("validation error: %s. %s", rule.Validation.Message, errStr)
}
func (v *validator) substitutePatterns() error {
if v.pattern != nil {
i, err := variables.SubstituteAll(v.log, v.policyContext.jsonContext, v.pattern)
if err != nil {
return err
}
v.pattern = i.(apiextensions.JSON)
return nil
}
if v.anyPattern != nil {
i, err := variables.SubstituteAll(v.log, v.policyContext.jsonContext, v.anyPattern)
if err != nil {
return err
}
v.anyPattern = i.(apiextensions.JSON)
return nil
}
return nil
}
func (v *validator) substituteDeny() error {
if v.deny == nil {
return nil
}
i, err := variables.SubstituteAll(v.log, v.policyContext.jsonContext, v.deny)
if err != nil {
return err
}
v.deny = i.(*kyvernov1.Deny)
return nil
}
// matchesException checks if an exception applies to the resource being admitted
func matchesException(
policyContext *PolicyContext,
rule *kyvernov1.Rule,
subresourceGVKToAPIResource map[string]*metav1.APIResource,
) (*kyvernov2alpha1.PolicyException, error) {
candidates, err := policyContext.FindExceptions(rule.Name)
if err != nil {
return nil, err
}
for _, candidate := range candidates {
err := matched.CheckMatchesResources(
policyContext.newResource,
candidate.Spec.Match,
policyContext.namespaceLabels,
subresourceGVKToAPIResource,
policyContext.subresource,
policyContext.admissionInfo,
policyContext.excludeGroupRole,
)
// if there's no error it means a match
if err == nil {
return candidate, nil
}
}
return nil, nil
}
// hasPolicyExceptions returns nil when there are no matching exceptions.
// A rule response is returned when an exception is matched, or there is an error.
func hasPolicyExceptions(ctx *PolicyContext, rule *kyvernov1.Rule, subresourceGVKToAPIResource map[string]*metav1.APIResource, log logr.Logger) *engineapi.RuleResponse {
// if matches, check if there is a corresponding policy exception
exception, err := matchesException(ctx, rule, subresourceGVKToAPIResource)
// if we found an exception
if err == nil && exception != nil {
key, err := cache.MetaNamespaceKeyFunc(exception)
if err != nil {
log.Error(err, "failed to compute policy exception key", "namespace", exception.GetNamespace(), "name", exception.GetName())
return &engineapi.RuleResponse{
Name: rule.Name,
Message: "failed to find matched exception " + key,
Status: engineapi.RuleStatusError,
}
}
log.V(3).Info("policy rule skipped due to policy exception", "exception", key)
return &engineapi.RuleResponse{
Name: rule.Name,
Message: "rule skipped due to policy exception " + key,
Status: engineapi.RuleStatusSkip,
}
}
return nil
}