2019-05-14 01:17:28 +00:00
|
|
|
package engine
|
|
|
|
|
2019-05-14 15:10:25 +00:00
|
|
|
import (
|
2022-12-09 13:45:11 +00:00
|
|
|
"context"
|
2021-09-26 09:12:31 +00:00
|
|
|
"encoding/json"
|
2019-06-20 15:21:55 +00:00
|
|
|
"fmt"
|
|
|
|
"reflect"
|
2020-12-07 19:26:04 +00:00
|
|
|
"strings"
|
2019-08-19 23:40:10 +00:00
|
|
|
"time"
|
2019-05-16 16:31:02 +00:00
|
|
|
|
2022-05-17 05:56:48 +00:00
|
|
|
"github.com/go-logr/logr"
|
|
|
|
gojmespath "github.com/jmespath/go-jmespath"
|
2022-05-17 11:12:43 +00:00
|
|
|
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
2022-12-16 09:13:14 +00:00
|
|
|
kyvernov2alpha1 "github.com/kyverno/kyverno/api/kyverno/v2alpha1"
|
2022-03-28 14:01:27 +00:00
|
|
|
"github.com/kyverno/kyverno/pkg/autogen"
|
2023-01-02 17:14:40 +00:00
|
|
|
"github.com/kyverno/kyverno/pkg/config"
|
2023-01-30 11:41:09 +00:00
|
|
|
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
|
2023-01-30 18:26:35 +00:00
|
|
|
"github.com/kyverno/kyverno/pkg/engine/utils"
|
2020-10-07 18:12:31 +00:00
|
|
|
"github.com/kyverno/kyverno/pkg/engine/validate"
|
|
|
|
"github.com/kyverno/kyverno/pkg/engine/variables"
|
2022-10-02 19:45:03 +00:00
|
|
|
"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"
|
2022-12-07 15:08:37 +00:00
|
|
|
"github.com/kyverno/kyverno/pkg/registryclient"
|
2022-12-12 20:32:11 +00:00
|
|
|
"github.com/kyverno/kyverno/pkg/tracing"
|
2022-12-12 15:20:20 +00:00
|
|
|
"github.com/kyverno/kyverno/pkg/utils/api"
|
2022-12-22 06:39:54 +00:00
|
|
|
datautils "github.com/kyverno/kyverno/pkg/utils/data"
|
2022-12-16 09:13:14 +00:00
|
|
|
matched "github.com/kyverno/kyverno/pkg/utils/match"
|
2022-05-17 05:56:48 +00:00
|
|
|
"github.com/pkg/errors"
|
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"
|
2022-05-17 05:56:48 +00:00
|
|
|
"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"
|
2019-08-13 18:32:12 +00:00
|
|
|
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
2022-12-16 09:13:14 +00:00
|
|
|
"k8s.io/client-go/tools/cache"
|
2019-05-14 15:10:25 +00:00
|
|
|
)
|
|
|
|
|
2022-05-17 06:19:03 +00:00
|
|
|
// Validate applies validation rules from policy on the resource
|
2023-01-30 11:41:09 +00:00
|
|
|
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-05-19 07:14:23 +00:00
|
|
|
|
2020-12-23 23:10:07 +00:00
|
|
|
logger := buildLogger(policyContext)
|
2022-04-19 15:35:12 +00:00
|
|
|
logger.V(4).Info("start validate policy processing", "startTime", startTime)
|
2020-05-05 15:28:02 +00:00
|
|
|
defer func() {
|
2021-09-26 09:12:31 +00:00
|
|
|
buildResponse(policyContext, resp, startTime)
|
2021-01-07 19:24:38 +00:00
|
|
|
logger.V(4).Info("finished policy processing", "processingTime", resp.PolicyResponse.ProcessingTime.String(), "validationRulesApplied", resp.PolicyResponse.RulesAppliedCount)
|
2020-05-05 15:28:02 +00:00
|
|
|
}()
|
|
|
|
|
2023-01-02 17:14:40 +00:00
|
|
|
resp = validateResource(ctx, logger, rclient, policyContext, cfg)
|
2023-01-18 10:21:34 +00:00
|
|
|
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 {
|
2022-12-02 08:14:23 +00:00
|
|
|
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 {
|
2022-12-02 08:14:23 +00:00
|
|
|
logger = logger.WithValues("kind", ctx.newResource.GetKind(), "namespace", ctx.newResource.GetNamespace(), "name", ctx.newResource.GetName())
|
2020-06-24 17:26:04 +00:00
|
|
|
}
|
|
|
|
|
2020-12-23 23:10:07 +00:00
|
|
|
return logger
|
|
|
|
}
|
|
|
|
|
2023-01-30 11:41:09 +00:00
|
|
|
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
|
2022-12-02 08:14:23 +00:00
|
|
|
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
|
|
|
|
2022-12-02 08:14:23 +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()
|
2022-12-02 08:14:23 +00:00
|
|
|
resp.PolicyResponse.ValidationFailureAction = ctx.policy.GetSpec().ValidationFailureAction
|
2022-01-21 12:36:44 +00:00
|
|
|
|
2022-12-02 08:14:23 +00:00
|
|
|
for _, v := range ctx.policy.GetSpec().ValidationFailureActionOverrides {
|
2023-01-30 11:41:09 +00:00
|
|
|
newOverrides := engineapi.ValidationFailureActionOverride{Action: v.Action, Namespaces: v.Namespaces, NamespaceSelector: v.NamespaceSelector}
|
2023-01-18 10:21:34 +00:00
|
|
|
resp.PolicyResponse.ValidationFailureActionOverrides = append(resp.PolicyResponse.ValidationFailureActionOverrides, newOverrides)
|
2022-01-21 12:36:44 +00:00
|
|
|
}
|
|
|
|
|
2020-01-10 01:44:11 +00:00
|
|
|
resp.PolicyResponse.ProcessingTime = time.Since(startTime)
|
2023-01-30 14:49:44 +00:00
|
|
|
resp.PolicyResponse.Timestamp = startTime.Unix()
|
2020-01-10 01:44:11 +00:00
|
|
|
}
|
|
|
|
|
2023-01-30 11:41:09 +00:00
|
|
|
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
|
|
|
|
2022-12-09 13:45:11 +00:00
|
|
|
enginectx.jsonContext.Checkpoint()
|
|
|
|
defer enginectx.jsonContext.Restore()
|
2021-02-02 07:22:19 +00:00
|
|
|
|
2022-12-09 13:45:11 +00:00
|
|
|
rules := autogen.ComputeRules(enginectx.policy)
|
2022-07-29 07:02:26 +00:00
|
|
|
matchCount := 0
|
2022-12-09 13:45:11 +00:00
|
|
|
applyRules := enginectx.policy.GetSpec().GetApplyRules()
|
2022-07-29 07:02:26 +00:00
|
|
|
|
2022-12-09 13:45:11 +00:00
|
|
|
if enginectx.policy.IsNamespaced() {
|
|
|
|
polNs := enginectx.policy.GetNamespace()
|
|
|
|
if enginectx.newResource.Object != nil && (enginectx.newResource.GetNamespace() != polNs || enginectx.newResource.GetNamespace() == "") {
|
2022-09-26 04:47:37 +00:00
|
|
|
return resp
|
|
|
|
}
|
2022-12-09 13:45:11 +00:00
|
|
|
if enginectx.oldResource.Object != nil && (enginectx.oldResource.GetNamespace() != polNs || enginectx.oldResource.GetNamespace() == "") {
|
2022-09-26 04:47:37 +00:00
|
|
|
return resp
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-09 15:28:31 +00:00
|
|
|
for i := range rules {
|
|
|
|
rule := &rules[i]
|
2022-07-29 07:02:26 +00:00
|
|
|
log.V(3).Info("processing validation rule", "matchCount", matchCount, "applyRules", applyRules)
|
2022-12-09 13:45:11 +00:00
|
|
|
enginectx.jsonContext.Reset()
|
2021-09-26 09:12:31 +00:00
|
|
|
startTime := time.Now()
|
2022-12-12 20:32:11 +00:00
|
|
|
ruleResp := tracing.ChildSpan1(
|
|
|
|
ctx,
|
|
|
|
"pkg/engine",
|
|
|
|
fmt.Sprintf("RULE %s", rule.Name),
|
2023-01-30 11:41:09 +00:00
|
|
|
func(ctx context.Context, span trace.Span) *engineapi.RuleResponse {
|
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)
|
2023-01-05 06:23:44 +00:00
|
|
|
kindsInPolicy := append(rule.MatchResources.GetKinds(), rule.ExcludeResources.GetKinds()...)
|
|
|
|
subresourceGVKToAPIResource := GetSubresourceGVKToAPIResourceMap(kindsInPolicy, enginectx)
|
|
|
|
|
|
|
|
if !matches(log, rule, enginectx, subresourceGVKToAPIResource) {
|
2022-12-12 20:32:11 +00:00
|
|
|
return nil
|
|
|
|
}
|
2022-12-21 04:35:26 +00:00
|
|
|
// check if there is a corresponding policy exception
|
2023-01-05 06:23:44 +00:00
|
|
|
ruleResp := hasPolicyExceptions(enginectx, rule, subresourceGVKToAPIResource, log)
|
2022-12-21 04:35:26 +00:00
|
|
|
if ruleResp != nil {
|
|
|
|
return ruleResp
|
2022-12-16 09:13:14 +00:00
|
|
|
}
|
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 {
|
2023-01-02 17:14:40 +00:00
|
|
|
return processImageValidationRule(ctx, log, rclient, enginectx, rule, cfg)
|
2022-12-12 20:32:11 +00:00
|
|
|
} else if hasYAMLSignatureVerify {
|
|
|
|
return processYAMLValidationRule(log, enginectx, rule)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
},
|
|
|
|
)
|
2021-09-26 09:12:31 +00:00
|
|
|
if ruleResp != nil {
|
|
|
|
addRuleResponse(log, resp, ruleResp, startTime)
|
2022-07-29 07:02:26 +00:00
|
|
|
if applyRules == kyvernov1.ApplyOne && resp.PolicyResponse.RulesAppliedCount > 0 {
|
|
|
|
break
|
|
|
|
}
|
2019-09-03 22:48:13 +00:00
|
|
|
}
|
2021-09-26 09:12:31 +00:00
|
|
|
}
|
2020-01-07 23:13:57 +00:00
|
|
|
|
2021-09-26 09:12:31 +00:00
|
|
|
return resp
|
|
|
|
}
|
2021-01-07 19:24:38 +00:00
|
|
|
|
2023-01-30 11:41:09 +00:00
|
|
|
func processValidationRule(ctx context.Context, log logr.Logger, rclient registryclient.Client, policyContext *PolicyContext, rule *kyvernov1.Rule) *engineapi.RuleResponse {
|
2022-12-12 15:20:20 +00:00
|
|
|
v := newValidator(log, rclient, policyContext, rule)
|
2022-12-09 13:45:11 +00:00
|
|
|
return v.validate(ctx)
|
2021-09-26 09:12:31 +00:00
|
|
|
}
|
|
|
|
|
2023-01-30 11:41:09 +00:00
|
|
|
func addRuleResponse(log logr.Logger, resp *engineapi.EngineResponse, ruleResp *engineapi.RuleResponse, startTime time.Time) {
|
2023-01-30 14:49:44 +00:00
|
|
|
ruleResp.ExecutionStats.ProcessingTime = time.Since(startTime)
|
|
|
|
ruleResp.ExecutionStats.Timestamp = startTime.Unix()
|
|
|
|
log.V(4).Info("finished processing rule", "processingTime", ruleResp.ExecutionStats.ProcessingTime.String())
|
2021-09-26 09:12:31 +00:00
|
|
|
|
2023-01-30 11:41:09 +00:00
|
|
|
if ruleResp.Status == engineapi.RuleStatusPass || ruleResp.Status == engineapi.RuleStatusFail {
|
2021-09-26 09:12:31 +00:00
|
|
|
incrementAppliedCount(resp)
|
2023-01-30 11:41:09 +00:00
|
|
|
} else if ruleResp.Status == engineapi.RuleStatusError {
|
2021-09-26 09:12:31 +00:00
|
|
|
incrementErrorCount(resp)
|
|
|
|
}
|
|
|
|
|
|
|
|
resp.PolicyResponse.Rules = append(resp.PolicyResponse.Rules, *ruleResp)
|
|
|
|
}
|
|
|
|
|
|
|
|
type validator struct {
|
2021-09-28 06:40:05 +00:00
|
|
|
log logr.Logger
|
2022-12-12 15:20:20 +00:00
|
|
|
policyContext *PolicyContext
|
2022-05-17 11:12:43 +00:00
|
|
|
rule *kyvernov1.Rule
|
|
|
|
contextEntries []kyvernov1.ContextEntry
|
2021-09-26 09:12:31 +00:00
|
|
|
anyAllConditions apiextensions.JSON
|
2021-09-28 06:40:05 +00:00
|
|
|
pattern apiextensions.JSON
|
|
|
|
anyPattern apiextensions.JSON
|
2022-05-17 11:12:43 +00:00
|
|
|
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
|
2022-12-12 19:24:13 +00:00
|
|
|
forEach []kyvernov1.ForEachValidation
|
2022-12-07 15:08:37 +00:00
|
|
|
rclient registryclient.Client
|
2022-12-12 15:20:20 +00:00
|
|
|
nesting int
|
2021-09-26 09:12:31 +00:00
|
|
|
}
|
|
|
|
|
2022-12-07 15:08:37 +00:00
|
|
|
func newValidator(log logr.Logger, rclient registryclient.Client, ctx *PolicyContext, rule *kyvernov1.Rule) *validator {
|
2021-09-26 09:12:31 +00:00
|
|
|
ruleCopy := rule.DeepCopy()
|
|
|
|
return &validator{
|
2021-09-28 06:40:05 +00:00
|
|
|
log: log,
|
|
|
|
rule: ruleCopy,
|
2022-12-12 15:20:20 +00:00
|
|
|
policyContext: ctx,
|
|
|
|
rclient: rclient,
|
2021-09-28 06:40:05 +00:00
|
|
|
contextEntries: ruleCopy.Context,
|
2022-03-06 19:07:51 +00:00
|
|
|
anyAllConditions: ruleCopy.GetAnyAllConditions(),
|
|
|
|
pattern: ruleCopy.Validation.GetPattern(),
|
|
|
|
anyPattern: ruleCopy.Validation.GetAnyPattern(),
|
2021-09-28 06:40:05 +00:00
|
|
|
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,
|
2022-12-12 19:24:13 +00:00
|
|
|
forEach: ruleCopy.Validation.ForEachValidation,
|
2021-09-26 09:12:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-12 19:24:13 +00:00
|
|
|
func newForEachValidator(foreach kyvernov1.ForEachValidation, rclient registryclient.Client, nesting int, rule *kyvernov1.Rule, ctx *PolicyContext, log logr.Logger) (*validator, error) {
|
2021-09-26 09:12:31 +00:00
|
|
|
ruleCopy := rule.DeepCopy()
|
2022-12-22 06:39:54 +00:00
|
|
|
anyAllConditions, err := datautils.ToMap(foreach.AnyAllConditions)
|
2021-10-19 10:04:53 +00:00
|
|
|
if err != nil {
|
2022-12-12 15:20:20 +00:00
|
|
|
return nil, errors.Wrap(err, "failed to convert ruleCopy.Validation.ForEachValidation.AnyAllConditions")
|
|
|
|
}
|
|
|
|
|
2022-12-12 19:24:13 +00:00
|
|
|
nestedForEach, err := api.DeserializeJSONArray[kyvernov1.ForEachValidation](foreach.ForEachValidation)
|
2022-12-12 15:20:20 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "failed to convert ruleCopy.Validation.ForEachValidation.AnyAllConditions")
|
2021-10-19 10:04:53 +00:00
|
|
|
}
|
2022-01-05 01:36:33 +00:00
|
|
|
|
2021-10-19 10:04:53 +00:00
|
|
|
return &validator{
|
|
|
|
log: log,
|
2022-12-12 15:20:20 +00:00
|
|
|
policyContext: ctx,
|
2021-10-19 10:04:53 +00:00
|
|
|
rule: ruleCopy,
|
2022-12-12 15:20:20 +00:00
|
|
|
rclient: rclient,
|
2022-01-05 01:36:33 +00:00
|
|
|
contextEntries: foreach.Context,
|
2021-10-19 10:04:53 +00:00
|
|
|
anyAllConditions: anyAllConditions,
|
2022-03-06 19:07:51 +00:00
|
|
|
pattern: foreach.GetPattern(),
|
|
|
|
anyPattern: foreach.GetAnyPattern(),
|
2022-01-05 01:36:33 +00:00
|
|
|
deny: foreach.Deny,
|
2022-12-12 19:24:13 +00:00
|
|
|
forEach: nestedForEach,
|
2022-12-12 15:20:20 +00:00
|
|
|
nesting: nesting,
|
|
|
|
}, nil
|
2021-09-26 09:12:31 +00:00
|
|
|
}
|
|
|
|
|
2023-01-30 11:41:09 +00:00
|
|
|
func (v *validator) validate(ctx context.Context) *engineapi.RuleResponse {
|
2022-12-09 13:45:11 +00:00
|
|
|
if err := v.loadContext(ctx); err != nil {
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleError(v.rule, engineapi.Validation, "failed to load context", err)
|
2021-09-26 09:12:31 +00:00
|
|
|
}
|
|
|
|
|
2022-12-12 15:20:20 +00:00
|
|
|
preconditionsPassed, err := checkPreconditions(v.log, v.policyContext, v.anyAllConditions)
|
2021-09-26 09:12:31 +00:00
|
|
|
if err != nil {
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleError(v.rule, engineapi.Validation, "failed to evaluate preconditions", err)
|
2022-01-05 01:36:33 +00:00
|
|
|
}
|
2022-04-27 15:09:52 +00:00
|
|
|
|
2022-07-14 04:05:27 +00:00
|
|
|
if !preconditionsPassed {
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleResponse(*v.rule, engineapi.Validation, "preconditions not met", engineapi.RuleStatusSkip)
|
2021-09-26 09:12:31 +00:00
|
|
|
}
|
|
|
|
|
2022-02-17 17:18:49 +00:00
|
|
|
if v.deny != nil {
|
|
|
|
return v.validateDeny()
|
|
|
|
}
|
|
|
|
|
2021-09-27 21:28:55 +00:00
|
|
|
if v.pattern != nil || v.anyPattern != nil {
|
2021-09-26 09:12:31 +00:00
|
|
|
if err = v.substitutePatterns(); err != nil {
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleError(v.rule, engineapi.Validation, "variable substitution failed", err)
|
2021-07-28 16:54:50 +00:00
|
|
|
}
|
|
|
|
|
2021-09-26 09:12:31 +00:00
|
|
|
ruleResponse := v.validateResourceWithRule()
|
|
|
|
return ruleResponse
|
|
|
|
}
|
2022-09-10 16:58:10 +00:00
|
|
|
|
|
|
|
if v.podSecurity != nil {
|
2022-12-12 15:20:20 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
2021-09-26 09:12:31 +00:00
|
|
|
|
2022-12-12 19:24:13 +00:00
|
|
|
if v.forEach != nil {
|
2022-12-12 15:20:20 +00:00
|
|
|
ruleResponse := v.validateForEach(ctx)
|
|
|
|
return ruleResponse
|
|
|
|
}
|
|
|
|
|
2022-09-10 16:58:10 +00:00
|
|
|
v.log.V(2).Info("invalid validation rule: podSecurity, patterns, or deny expected")
|
2021-09-26 09:12:31 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-01-30 11:41:09 +00:00
|
|
|
func (v *validator) validateForEach(ctx context.Context) *engineapi.RuleResponse {
|
2021-10-14 07:20:52 +00:00
|
|
|
applyCount := 0
|
2022-12-12 19:24:13 +00:00
|
|
|
for _, foreach := range v.forEach {
|
2022-12-12 15:20:20 +00:00
|
|
|
elements, err := evaluateList(foreach.List, (v.policyContext.JSONContext()))
|
2021-10-14 07:20:52 +00:00
|
|
|
if err != nil {
|
2022-08-18 13:24:59 +00:00
|
|
|
v.log.V(2).Info("failed to evaluate list", "list", foreach.List, "error", err.Error())
|
2021-10-19 10:04:53 +00:00
|
|
|
continue
|
2021-03-02 04:31:06 +00:00
|
|
|
}
|
2022-12-12 15:20:20 +00:00
|
|
|
|
|
|
|
resp, count := v.validateElements(ctx, v.rclient, foreach, elements, foreach.ElementScope)
|
2023-01-30 11:41:09 +00:00
|
|
|
if resp.Status != engineapi.RuleStatusPass {
|
2022-01-05 01:36:33 +00:00
|
|
|
return resp
|
2021-10-14 07:20:52 +00:00
|
|
|
}
|
2022-01-05 01:36:33 +00:00
|
|
|
|
|
|
|
applyCount += count
|
2021-09-28 06:40:05 +00:00
|
|
|
}
|
2021-04-13 18:44:43 +00:00
|
|
|
|
2021-09-28 06:40:05 +00:00
|
|
|
if applyCount == 0 {
|
2022-12-12 19:24:13 +00:00
|
|
|
if v.forEach == nil {
|
2022-12-12 15:20:20 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleResponse(*v.rule, engineapi.Validation, "rule skipped", engineapi.RuleStatusSkip)
|
2021-09-26 09:12:31 +00:00
|
|
|
}
|
2021-07-28 16:54:50 +00:00
|
|
|
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleResponse(*v.rule, engineapi.Validation, "rule passed", engineapi.RuleStatusPass)
|
2021-09-26 09:12:31 +00:00
|
|
|
}
|
2021-07-28 16:54:50 +00:00
|
|
|
|
2023-01-30 11:41:09 +00:00
|
|
|
func (v *validator) validateElements(ctx context.Context, rclient registryclient.Client, foreach kyvernov1.ForEachValidation, elements []interface{}, elementScope *bool) (*engineapi.RuleResponse, int) {
|
2022-12-12 15:20:20 +00:00
|
|
|
v.policyContext.jsonContext.Checkpoint()
|
|
|
|
defer v.policyContext.jsonContext.Restore()
|
2022-01-05 01:36:33 +00:00
|
|
|
applyCount := 0
|
|
|
|
|
2023-01-30 15:30:47 +00:00
|
|
|
for index, element := range elements {
|
|
|
|
if element == nil {
|
2022-11-04 09:35:25 +00:00
|
|
|
continue
|
|
|
|
}
|
2022-12-12 15:20:20 +00:00
|
|
|
|
|
|
|
v.policyContext.JSONContext().Reset()
|
|
|
|
policyContext := v.policyContext.Copy()
|
2023-01-30 15:30:47 +00:00
|
|
|
if err := addElementToContext(policyContext, element, index, v.nesting, elementScope); err != nil {
|
2022-01-05 01:36:33 +00:00
|
|
|
v.log.Error(err, "failed to add element to context")
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleError(v.rule, engineapi.Validation, "failed to process foreach", err), applyCount
|
2022-01-05 01:36:33 +00:00
|
|
|
}
|
|
|
|
|
2022-12-12 19:24:13 +00:00
|
|
|
foreachValidator, err := newForEachValidator(foreach, rclient, v.nesting+1, v.rule, policyContext, v.log)
|
2022-12-12 15:20:20 +00:00
|
|
|
if err != nil {
|
|
|
|
v.log.Error(err, "failed to create foreach validator")
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleError(v.rule, engineapi.Validation, "failed to create foreach validator", err), applyCount
|
2022-12-12 15:20:20 +00:00
|
|
|
}
|
|
|
|
|
2022-12-09 13:45:11 +00:00
|
|
|
r := foreachValidator.validate(ctx)
|
2022-01-05 01:36:33 +00:00
|
|
|
if r == nil {
|
2022-08-18 13:24:59 +00:00
|
|
|
v.log.V(2).Info("skip rule due to empty result")
|
2022-01-05 01:36:33 +00:00
|
|
|
continue
|
2023-01-30 11:41:09 +00:00
|
|
|
} else if r.Status == engineapi.RuleStatusSkip {
|
2022-08-18 13:24:59 +00:00
|
|
|
v.log.V(2).Info("skip rule", "reason", r.Message)
|
2022-01-05 01:36:33 +00:00
|
|
|
continue
|
2023-01-30 11:41:09 +00:00
|
|
|
} else if r.Status != engineapi.RuleStatusPass {
|
|
|
|
if r.Status == engineapi.RuleStatusError {
|
2023-01-30 15:30:47 +00:00
|
|
|
if index < len(elements)-1 {
|
2022-08-18 04:34:36 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
msg := fmt.Sprintf("validation failure: %v", r.Message)
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleResponse(*v.rule, engineapi.Validation, msg, r.Status), applyCount
|
2022-08-18 04:34:36 +00:00
|
|
|
}
|
2022-01-23 13:54:22 +00:00
|
|
|
msg := fmt.Sprintf("validation failure: %v", r.Message)
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleResponse(*v.rule, engineapi.Validation, msg, r.Status), applyCount
|
2022-01-05 01:36:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
applyCount++
|
|
|
|
}
|
|
|
|
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleResponse(*v.rule, engineapi.Validation, "", engineapi.RuleStatusPass), applyCount
|
2022-01-05 01:36:33 +00:00
|
|
|
}
|
|
|
|
|
2023-01-30 15:30:47 +00:00
|
|
|
func addElementToContext(ctx *PolicyContext, element interface{}, index, nesting int, elementScope *bool) error {
|
|
|
|
data, err := variables.DocumentToUntyped(element)
|
2021-09-27 21:28:55 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-01-30 15:30:47 +00:00
|
|
|
if err := ctx.JSONContext().AddElement(data, index, nesting); err != nil {
|
|
|
|
return errors.Wrapf(err, "failed to add element (%v) to JSON context", element)
|
2021-09-27 21:28:55 +00:00
|
|
|
}
|
2022-05-02 16:39:37 +00:00
|
|
|
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 {
|
2022-01-05 01:36:33 +00:00
|
|
|
u := unstructured.Unstructured{}
|
2022-05-02 16:39:37 +00:00
|
|
|
u.SetUnstructuredContent(dataMap)
|
2022-12-02 08:14:23 +00:00
|
|
|
ctx.element = u
|
2022-01-05 01:36:33 +00:00
|
|
|
}
|
2021-09-27 21:28:55 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-12-09 13:45:11 +00:00
|
|
|
func (v *validator) loadContext(ctx context.Context) error {
|
2022-12-12 15:20:20 +00:00
|
|
|
if err := LoadContext(ctx, v.log, v.rclient, v.contextEntries, v.policyContext, v.rule.Name); err != nil {
|
2021-09-26 09:12:31 +00:00
|
|
|
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
|
|
|
}
|
2021-09-26 09:12:31 +00:00
|
|
|
|
|
|
|
return err
|
2020-05-05 13:49:47 +00:00
|
|
|
}
|
2020-12-23 23:10:07 +00:00
|
|
|
|
2021-09-26 09:12:31 +00:00
|
|
|
return nil
|
2020-05-05 13:49:47 +00:00
|
|
|
}
|
|
|
|
|
2023-01-30 11:41:09 +00:00
|
|
|
func (v *validator) validateDeny() *engineapi.RuleResponse {
|
2022-03-06 19:07:51 +00:00
|
|
|
anyAllCond := v.deny.GetAnyAllConditions()
|
2022-12-12 15:20:20 +00:00
|
|
|
anyAllCond, err := variables.SubstituteAll(v.log, v.policyContext.jsonContext, anyAllCond)
|
2021-09-26 09:12:31 +00:00
|
|
|
if err != nil {
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleError(v.rule, engineapi.Validation, "failed to substitute variables in deny conditions", err)
|
2021-09-26 09:12:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if err = v.substituteDeny(); err != nil {
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleError(v.rule, engineapi.Validation, "failed to substitute variables in rule", err)
|
2021-09-26 09:12:31 +00:00
|
|
|
}
|
|
|
|
|
2023-01-30 18:26:35 +00:00
|
|
|
denyConditions, err := utils.TransformConditions(anyAllCond)
|
2021-09-26 09:12:31 +00:00
|
|
|
if err != nil {
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleError(v.rule, engineapi.Validation, "invalid deny conditions", err)
|
2021-09-26 09:12:31 +00:00
|
|
|
}
|
|
|
|
|
2022-12-12 15:20:20 +00:00
|
|
|
deny := variables.EvaluateConditions(v.log, v.policyContext.jsonContext, denyConditions)
|
2021-09-26 09:12:31 +00:00
|
|
|
if deny {
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleResponse(*v.rule, engineapi.Validation, v.getDenyMessage(deny), engineapi.RuleStatusFail)
|
2021-09-26 09:12:31 +00:00
|
|
|
}
|
|
|
|
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleResponse(*v.rule, engineapi.Validation, v.getDenyMessage(deny), engineapi.RuleStatusPass)
|
2021-09-26 09:12:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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)
|
|
|
|
}
|
2022-12-12 15:20:20 +00:00
|
|
|
raw, err := variables.SubstituteAll(v.log, v.policyContext.jsonContext, msg)
|
2021-09-26 09:12:31 +00:00
|
|
|
if err != nil {
|
|
|
|
return msg
|
|
|
|
}
|
2022-12-13 20:30:36 +00:00
|
|
|
switch typed := raw.(type) {
|
|
|
|
case string:
|
|
|
|
return typed
|
|
|
|
default:
|
|
|
|
return "the produced message didn't resolve to a string, check your policy definition."
|
|
|
|
}
|
2021-09-26 09:12:31 +00:00
|
|
|
}
|
|
|
|
|
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) {
|
2022-12-12 15:20:20 +00:00
|
|
|
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
|
|
|
|
2022-11-14 20:05:05 +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
|
|
|
|
|
2022-12-12 15:20:20 +00:00
|
|
|
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
|
|
|
|
|
2022-12-12 15:20:20 +00:00
|
|
|
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
|
|
|
|
|
2022-12-12 15:20:20 +00:00
|
|
|
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
|
2023-01-30 11:41:09 +00:00
|
|
|
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 {
|
2023-01-30 11:41:09 +00:00
|
|
|
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,
|
|
|
|
}
|
2022-09-28 10:03:53 +00:00
|
|
|
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 {
|
2023-01-30 11:41:09 +00:00
|
|
|
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
|
|
|
}
|
2023-01-30 11:41:09 +00:00
|
|
|
podSecurityChecks := &engineapi.PodSecurityChecks{
|
2022-12-20 05:57:23 +00:00
|
|
|
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)
|
2023-01-30 11:41:09 +00:00
|
|
|
rspn := ruleResponse(*v.rule, engineapi.Validation, msg, engineapi.RuleStatusPass)
|
2022-12-20 05:57:23 +00:00
|
|
|
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 {
|
2022-09-28 10:03:53 +00:00
|
|
|
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))
|
2023-01-30 11:41:09 +00:00
|
|
|
rspn := ruleResponse(*v.rule, engineapi.Validation, msg, engineapi.RuleStatusFail)
|
2022-12-20 05:57:23 +00:00
|
|
|
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
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-30 11:41:09 +00:00
|
|
|
func (v *validator) validateResourceWithRule() *engineapi.RuleResponse {
|
2022-12-12 15:20:20 +00:00
|
|
|
if !isEmptyUnstructured(&v.policyContext.element) {
|
|
|
|
return v.validatePatterns(v.policyContext.element)
|
2021-10-02 23:53:02 +00:00
|
|
|
}
|
|
|
|
|
2022-12-12 15:20:20 +00:00
|
|
|
if isDeleteRequest(v.policyContext) {
|
2021-09-26 09:12:31 +00:00
|
|
|
v.log.V(3).Info("skipping validation on deleted resource")
|
2021-01-02 09:10:14 +00:00
|
|
|
return nil
|
2020-06-24 17:26:04 +00:00
|
|
|
}
|
|
|
|
|
2022-12-12 15:20:20 +00:00
|
|
|
resp := v.validatePatterns(v.policyContext.newResource)
|
2022-02-17 17:18:49 +00:00
|
|
|
return resp
|
|
|
|
}
|
|
|
|
|
|
|
|
func isDeleteRequest(ctx *PolicyContext) bool {
|
|
|
|
// if the OldResource is not empty, and the NewResource is empty, the request is a DELETE
|
2022-12-02 08:14:23 +00:00
|
|
|
return isEmptyUnstructured(&ctx.newResource)
|
2022-02-17 17:18:49 +00:00
|
|
|
}
|
2020-08-08 00:09:24 +00:00
|
|
|
|
2021-10-02 23:53:02 +00:00
|
|
|
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
|
2023-01-05 06:23:44 +00:00
|
|
|
func matches(logger logr.Logger, rule *kyvernov1.Rule, ctx *PolicyContext, subresourceGVKToAPIResource map[string]*metav1.APIResource) bool {
|
2022-12-09 16:45:23 +00:00
|
|
|
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
|
|
|
|
}
|
2020-12-09 06:52:37 +00:00
|
|
|
|
2022-12-09 16:45:23 +00:00
|
|
|
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
|
|
|
}
|
|
|
|
}
|
2019-10-16 03:56:41 +00:00
|
|
|
|
2022-05-05 21:06:18 +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-11-13 21:13:07 +00:00
|
|
|
}
|
|
|
|
|
2019-08-21 19:38:15 +00:00
|
|
|
// validatePatterns validate pattern and anyPattern
|
2023-01-30 11:41:09 +00:00
|
|
|
func (v *validator) validatePatterns(resource unstructured.Unstructured) *engineapi.RuleResponse {
|
2021-09-26 09:12:31 +00:00
|
|
|
if v.pattern != nil {
|
2021-10-01 06:34:04 +00:00
|
|
|
if err := validate.MatchPattern(v.log, resource.Object, v.pattern); err != nil {
|
2021-10-29 15:06:03 +00:00
|
|
|
pe, ok := err.(*validate.PatternError)
|
|
|
|
if ok {
|
2021-10-01 06:34:04 +00:00
|
|
|
v.log.V(3).Info("validation error", "path", pe.Path, "error", err.Error())
|
2021-10-03 10:15:22 +00:00
|
|
|
|
|
|
|
if pe.Skip {
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleResponse(*v.rule, engineapi.Validation, pe.Error(), engineapi.RuleStatusSkip)
|
2021-10-03 10:15:22 +00:00
|
|
|
}
|
2020-05-26 17:36:56 +00:00
|
|
|
|
2021-10-01 06:34:04 +00:00
|
|
|
if pe.Path == "" {
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleResponse(*v.rule, engineapi.Validation, v.buildErrorMessage(err, ""), engineapi.RuleStatusError)
|
2021-10-01 06:34:04 +00:00
|
|
|
}
|
2020-01-10 01:44:11 +00:00
|
|
|
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleResponse(*v.rule, engineapi.Validation, v.buildErrorMessage(err, pe.Path), engineapi.RuleStatusFail)
|
2021-10-01 06:34:04 +00:00
|
|
|
}
|
2021-10-29 15:06:03 +00:00
|
|
|
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleResponse(*v.rule, engineapi.Validation, v.buildErrorMessage(err, pe.Path), engineapi.RuleStatusError)
|
2020-02-14 19:59:28 +00:00
|
|
|
}
|
2020-12-04 20:05:24 +00:00
|
|
|
|
2021-09-26 09:12:31 +00:00
|
|
|
v.log.V(4).Info("successfully processed rule")
|
|
|
|
msg := fmt.Sprintf("validation rule '%s' passed.", v.rule.Name)
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleResponse(*v.rule, engineapi.Validation, msg, engineapi.RuleStatusPass)
|
2019-05-14 15:10:25 +00:00
|
|
|
}
|
|
|
|
|
2021-09-26 09:12:31 +00:00
|
|
|
if v.anyPattern != nil {
|
2020-02-14 19:59:28 +00:00
|
|
|
var failedAnyPatternsErrors []error
|
2022-11-28 13:01:51 +00:00
|
|
|
var skippedAnyPatternErrors []error
|
2020-02-14 19:59:28 +00:00
|
|
|
var err error
|
2020-11-14 00:25:51 +00:00
|
|
|
|
2021-09-26 09:12:31 +00:00
|
|
|
anyPatterns, err := deserializeAnyPattern(v.anyPattern)
|
2020-11-14 00:25:51 +00:00
|
|
|
if err != nil {
|
2021-09-26 09:12:31 +00:00
|
|
|
msg := fmt.Sprintf("failed to deserialize anyPattern, expected type array: %v", err)
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleResponse(*v.rule, engineapi.Validation, msg, engineapi.RuleStatusError)
|
2020-11-14 00:25:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
for idx, pattern := range anyPatterns {
|
2021-10-01 06:34:04 +00:00
|
|
|
err := validate.MatchPattern(v.log, resource.Object, pattern)
|
2020-02-14 19:59:28 +00:00
|
|
|
if err == nil {
|
2021-09-26 09:12:31 +00:00
|
|
|
msg := fmt.Sprintf("validation rule '%s' anyPattern[%d] passed.", v.rule.Name, idx)
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleResponse(*v.rule, engineapi.Validation, msg, engineapi.RuleStatusPass)
|
2019-09-05 19:44:38 +00:00
|
|
|
}
|
2020-12-07 19:26:04 +00:00
|
|
|
|
2021-10-01 06:34:04 +00:00
|
|
|
if pe, ok := err.(*validate.PatternError); ok {
|
2022-11-28 13:01:51 +00:00
|
|
|
var patternErr error
|
2021-10-01 06:34:04 +00:00
|
|
|
v.log.V(3).Info("validation rule failed", "anyPattern[%d]", idx, "path", pe.Path)
|
2022-11-28 13:01:51 +00:00
|
|
|
|
|
|
|
if pe.Skip {
|
|
|
|
patternErr = fmt.Errorf("rule %s[%d] skipped: %s", v.rule.Name, idx, err.Error())
|
|
|
|
skippedAnyPatternErrors = append(skippedAnyPatternErrors, patternErr)
|
2021-10-01 06:34:04 +00:00
|
|
|
} else {
|
2022-11-28 13:01:51 +00:00
|
|
|
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)
|
|
|
|
}
|
2021-10-01 06:34:04 +00:00
|
|
|
failedAnyPatternsErrors = append(failedAnyPatternsErrors, patternErr)
|
|
|
|
}
|
2021-09-26 09:12:31 +00:00
|
|
|
}
|
2019-09-05 19:44:38 +00:00
|
|
|
}
|
2019-11-05 01:54:06 +00:00
|
|
|
|
2020-02-14 19:59:28 +00:00
|
|
|
// Any Pattern validation errors
|
2022-11-28 13:01:51 +00:00
|
|
|
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))
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleResponse(*v.rule, engineapi.Validation, strings.Join(errorStr, " "), engineapi.RuleStatusSkip)
|
2022-11-28 13:01:51 +00:00
|
|
|
} 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())
|
|
|
|
}
|
2020-12-07 19:26:04 +00:00
|
|
|
|
2021-09-26 09:12:31 +00:00
|
|
|
v.log.V(4).Info(fmt.Sprintf("Validation rule '%s' failed. %s", v.rule.Name, errorStr))
|
|
|
|
msg := buildAnyPatternErrorMessage(v.rule, errorStr)
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleResponse(*v.rule, engineapi.Validation, msg, engineapi.RuleStatusFail)
|
2020-01-10 01:44:11 +00:00
|
|
|
}
|
2019-08-21 19:38:15 +00:00
|
|
|
}
|
2021-01-02 09:10:14 +00:00
|
|
|
|
2023-01-30 11:41:09 +00:00
|
|
|
return ruleResponse(*v.rule, engineapi.Validation, v.rule.Validation.Message, engineapi.RuleStatusPass)
|
2019-05-15 16:25:49 +00:00
|
|
|
}
|
2020-12-07 19:26:04 +00:00
|
|
|
|
2021-09-28 06:40:05 +00:00
|
|
|
func deserializeAnyPattern(anyPattern apiextensions.JSON) ([]interface{}, error) {
|
2021-09-26 09:12:31 +00:00
|
|
|
if anyPattern == nil {
|
|
|
|
return nil, nil
|
2020-12-07 19:26:04 +00:00
|
|
|
}
|
|
|
|
|
2021-09-26 09:12:31 +00:00
|
|
|
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())
|
|
|
|
}
|
|
|
|
|
2022-12-12 15:20:20 +00:00
|
|
|
msgRaw, sErr := variables.SubstituteAll(v.log, v.policyContext.jsonContext, v.rule.Validation.Message)
|
2021-10-02 23:53:02 +00:00
|
|
|
if sErr != nil {
|
2022-10-13 10:16:47 +00:00
|
|
|
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())
|
2020-12-07 19:26:04 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-17 11:12:43 +00:00
|
|
|
func buildAnyPatternErrorMessage(rule *kyvernov1.Rule, errors []string) string {
|
2020-12-07 19:26:04 +00:00
|
|
|
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)
|
|
|
|
}
|
2021-07-28 16:54:50 +00:00
|
|
|
|
2021-09-28 06:40:05 +00:00
|
|
|
func (v *validator) substitutePatterns() error {
|
2021-09-26 09:12:31 +00:00
|
|
|
if v.pattern != nil {
|
2022-12-12 15:20:20 +00:00
|
|
|
i, err := variables.SubstituteAll(v.log, v.policyContext.jsonContext, v.pattern)
|
2021-09-26 09:12:31 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
2021-07-28 16:54:50 +00:00
|
|
|
}
|
|
|
|
|
2021-09-26 09:12:31 +00:00
|
|
|
v.pattern = i.(apiextensions.JSON)
|
|
|
|
return nil
|
|
|
|
}
|
2021-07-28 16:54:50 +00:00
|
|
|
|
2021-09-26 09:12:31 +00:00
|
|
|
if v.anyPattern != nil {
|
2022-12-12 15:20:20 +00:00
|
|
|
i, err := variables.SubstituteAll(v.log, v.policyContext.jsonContext, v.anyPattern)
|
2021-09-26 09:12:31 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
2021-07-28 16:54:50 +00:00
|
|
|
}
|
|
|
|
|
2021-09-26 09:12:31 +00:00
|
|
|
v.anyPattern = i.(apiextensions.JSON)
|
|
|
|
return nil
|
2021-07-28 16:54:50 +00:00
|
|
|
}
|
|
|
|
|
2021-09-26 09:12:31 +00:00
|
|
|
return nil
|
2021-07-28 16:54:50 +00:00
|
|
|
}
|
2021-09-26 09:12:31 +00:00
|
|
|
|
2021-09-28 06:40:05 +00:00
|
|
|
func (v *validator) substituteDeny() error {
|
2021-09-26 09:12:31 +00:00
|
|
|
if v.deny == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-12-12 15:20:20 +00:00
|
|
|
i, err := variables.SubstituteAll(v.log, v.policyContext.jsonContext, v.deny)
|
2021-09-26 09:12:31 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-05-17 11:12:43 +00:00
|
|
|
v.deny = i.(*kyvernov1.Deny)
|
2021-09-26 09:12:31 +00:00
|
|
|
return nil
|
|
|
|
}
|
2022-12-16 09:13:14 +00:00
|
|
|
|
|
|
|
// matchesException checks if an exception applies to the resource being admitted
|
2023-01-08 00:48:44 +00:00
|
|
|
func matchesException(
|
|
|
|
policyContext *PolicyContext,
|
|
|
|
rule *kyvernov1.Rule,
|
|
|
|
subresourceGVKToAPIResource map[string]*metav1.APIResource,
|
|
|
|
) (*kyvernov2alpha1.PolicyException, error) {
|
2022-12-16 09:13:14 +00:00
|
|
|
candidates, err := policyContext.FindExceptions(rule.Name)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
for _, candidate := range candidates {
|
2023-01-08 00:48:44 +00:00
|
|
|
err := matched.CheckMatchesResources(
|
|
|
|
policyContext.newResource,
|
|
|
|
candidate.Spec.Match,
|
|
|
|
policyContext.namespaceLabels,
|
|
|
|
subresourceGVKToAPIResource,
|
|
|
|
policyContext.subresource,
|
|
|
|
policyContext.admissionInfo,
|
|
|
|
policyContext.excludeGroupRole,
|
|
|
|
)
|
2022-12-16 09:13:14 +00:00
|
|
|
// if there's no error it means a match
|
|
|
|
if err == nil {
|
|
|
|
return candidate, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil, nil
|
|
|
|
}
|
2022-12-21 04:35:26 +00:00
|
|
|
|
|
|
|
// hasPolicyExceptions returns nil when there are no matching exceptions.
|
|
|
|
// A rule response is returned when an exception is matched, or there is an error.
|
2023-01-30 11:41:09 +00:00
|
|
|
func hasPolicyExceptions(ctx *PolicyContext, rule *kyvernov1.Rule, subresourceGVKToAPIResource map[string]*metav1.APIResource, log logr.Logger) *engineapi.RuleResponse {
|
2022-12-21 04:35:26 +00:00
|
|
|
// if matches, check if there is a corresponding policy exception
|
2023-01-05 06:23:44 +00:00
|
|
|
exception, err := matchesException(ctx, rule, subresourceGVKToAPIResource)
|
2022-12-21 04:35:26 +00:00
|
|
|
// 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())
|
2023-01-30 11:41:09 +00:00
|
|
|
return &engineapi.RuleResponse{
|
2022-12-21 04:35:26 +00:00
|
|
|
Name: rule.Name,
|
|
|
|
Message: "failed to find matched exception " + key,
|
2023-01-30 11:41:09 +00:00
|
|
|
Status: engineapi.RuleStatusError,
|
2022-12-21 04:35:26 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
log.V(3).Info("policy rule skipped due to policy exception", "exception", key)
|
2023-01-30 11:41:09 +00:00
|
|
|
return &engineapi.RuleResponse{
|
2022-12-21 04:35:26 +00:00
|
|
|
Name: rule.Name,
|
|
|
|
Message: "rule skipped due to policy exception " + key,
|
2023-01-30 11:41:09 +00:00
|
|
|
Status: engineapi.RuleStatusSkip,
|
2022-12-21 04:35:26 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|