2021-07-10 01:01:46 +00:00
|
|
|
package engine
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
2021-09-28 19:19:26 +00:00
|
|
|
"time"
|
|
|
|
|
2021-10-29 16:13:20 +00:00
|
|
|
v1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
2021-10-02 21:24:06 +00:00
|
|
|
"github.com/kyverno/kyverno/pkg/engine/variables"
|
2022-01-17 04:06:44 +00:00
|
|
|
"github.com/kyverno/kyverno/pkg/registryclient"
|
2021-10-02 21:24:06 +00:00
|
|
|
"github.com/pkg/errors"
|
2021-09-28 19:19:26 +00:00
|
|
|
|
2021-07-10 01:01:46 +00:00
|
|
|
"github.com/go-logr/logr"
|
|
|
|
"github.com/kyverno/kyverno/pkg/cosign"
|
|
|
|
"github.com/kyverno/kyverno/pkg/engine/context"
|
|
|
|
"github.com/kyverno/kyverno/pkg/engine/response"
|
|
|
|
"github.com/kyverno/kyverno/pkg/engine/utils"
|
2021-09-28 19:19:26 +00:00
|
|
|
"github.com/minio/pkg/wildcard"
|
2021-07-10 01:01:46 +00:00
|
|
|
"sigs.k8s.io/controller-runtime/pkg/log"
|
|
|
|
)
|
|
|
|
|
|
|
|
func VerifyAndPatchImages(policyContext *PolicyContext) (resp *response.EngineResponse) {
|
|
|
|
resp = &response.EngineResponse{}
|
|
|
|
images := policyContext.JSONContext.ImageInfo()
|
|
|
|
if images == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
policy := policyContext.Policy
|
|
|
|
patchedResource := policyContext.NewResource
|
|
|
|
logger := log.Log.WithName("EngineVerifyImages").WithValues("policy", policy.Name,
|
|
|
|
"kind", patchedResource.GetKind(), "namespace", patchedResource.GetNamespace(), "name", patchedResource.GetName())
|
|
|
|
|
|
|
|
startTime := time.Now()
|
|
|
|
defer func() {
|
2021-09-26 09:12:31 +00:00
|
|
|
buildResponse(policyContext, resp, startTime)
|
2021-07-10 01:01:46 +00:00
|
|
|
logger.V(4).Info("finished policy processing", "processingTime", resp.PolicyResponse.ProcessingTime.String(), "rulesApplied", resp.PolicyResponse.RulesAppliedCount)
|
|
|
|
}()
|
|
|
|
|
|
|
|
policyContext.JSONContext.Checkpoint()
|
|
|
|
defer policyContext.JSONContext.Restore()
|
|
|
|
|
2021-12-07 00:08:16 +00:00
|
|
|
// update image registry secrets
|
2022-01-17 04:06:44 +00:00
|
|
|
if len(registryclient.Secrets) > 0 {
|
|
|
|
logger.V(4).Info("updating registry credentials", "secrets", registryclient.Secrets)
|
|
|
|
if err := registryclient.UpdateKeychain(); err != nil {
|
2021-12-07 00:08:16 +00:00
|
|
|
logger.Error(err, "failed to update image pull secrets")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-10 01:01:46 +00:00
|
|
|
for i := range policyContext.Policy.Spec.Rules {
|
2021-10-04 06:23:45 +00:00
|
|
|
rule := &policyContext.Policy.Spec.Rules[i]
|
2021-07-10 01:01:46 +00:00
|
|
|
if len(rule.VerifyImages) == 0 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if !matches(logger, rule, policyContext) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
policyContext.JSONContext.Restore()
|
2021-10-02 08:19:47 +00:00
|
|
|
|
2021-10-26 17:41:27 +00:00
|
|
|
if err := LoadContext(logger, rule.Context, policyContext.ResourceCache, policyContext, rule.Name); err != nil {
|
|
|
|
appendError(resp, rule, fmt.Sprintf("failed to load context: %s", err.Error()), response.RuleStatusError)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
ruleCopy, err := substituteVariables(rule, policyContext.JSONContext, logger)
|
|
|
|
if err != nil {
|
|
|
|
appendError(resp, rule, fmt.Sprintf("failed to substitute variables: %s", err.Error()), response.RuleStatusError)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2021-10-02 21:24:06 +00:00
|
|
|
iv := &imageVerifier{
|
|
|
|
logger: logger,
|
2021-10-02 08:19:47 +00:00
|
|
|
policyContext: policyContext,
|
2021-10-26 17:41:27 +00:00
|
|
|
rule: ruleCopy,
|
2021-10-02 21:24:06 +00:00
|
|
|
resp: resp,
|
2021-10-02 08:19:47 +00:00
|
|
|
}
|
|
|
|
|
2021-10-26 17:41:27 +00:00
|
|
|
for _, imageVerify := range ruleCopy.VerifyImages {
|
2021-10-02 08:19:47 +00:00
|
|
|
iv.verify(imageVerify, images.Containers)
|
|
|
|
iv.verify(imageVerify, images.InitContainers)
|
2022-01-07 08:55:52 +00:00
|
|
|
iv.verify(imageVerify, images.EphemeralContainers)
|
2021-07-10 01:01:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-10-26 17:41:27 +00:00
|
|
|
func appendError(resp *response.EngineResponse, rule *v1.Rule, msg string, status response.RuleStatus) {
|
|
|
|
rr := ruleResponse(rule, utils.ImageVerify, msg, status)
|
|
|
|
resp.PolicyResponse.Rules = append(resp.PolicyResponse.Rules, *rr)
|
|
|
|
incrementErrorCount(resp)
|
|
|
|
}
|
|
|
|
|
|
|
|
func substituteVariables(rule *v1.Rule, ctx context.EvalInterface, logger logr.Logger) (*v1.Rule, error) {
|
2021-10-26 20:22:00 +00:00
|
|
|
|
|
|
|
// remove attestations as variables are not substituted in them
|
|
|
|
ruleCopy := rule.DeepCopy()
|
|
|
|
for _, iv := range ruleCopy.VerifyImages {
|
|
|
|
iv.Attestations = nil
|
|
|
|
}
|
|
|
|
|
|
|
|
var err error
|
|
|
|
*ruleCopy, err = variables.SubstituteAllInRule(logger, ctx, *ruleCopy)
|
2021-10-26 17:41:27 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2021-10-26 20:22:00 +00:00
|
|
|
// replace attestations
|
2021-10-26 20:25:41 +00:00
|
|
|
for i := range rule.VerifyImages {
|
2021-10-26 20:22:00 +00:00
|
|
|
ruleCopy.VerifyImages[i].Attestations = rule.VerifyImages[i].Attestations
|
|
|
|
}
|
|
|
|
|
|
|
|
return ruleCopy, nil
|
2021-10-26 17:41:27 +00:00
|
|
|
}
|
|
|
|
|
2021-10-02 08:19:47 +00:00
|
|
|
type imageVerifier struct {
|
2021-10-02 21:24:06 +00:00
|
|
|
logger logr.Logger
|
2021-10-02 08:19:47 +00:00
|
|
|
policyContext *PolicyContext
|
2021-10-02 21:24:06 +00:00
|
|
|
rule *v1.Rule
|
|
|
|
resp *response.EngineResponse
|
2021-10-02 08:19:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (iv *imageVerifier) verify(imageVerify *v1.ImageVerification, images map[string]*context.ImageInfo) {
|
2021-07-10 01:01:46 +00:00
|
|
|
imagePattern := imageVerify.Image
|
|
|
|
key := imageVerify.Key
|
2021-10-01 18:10:36 +00:00
|
|
|
repository := getSignatureRepository(imageVerify)
|
2021-07-10 01:01:46 +00:00
|
|
|
|
|
|
|
for _, imageInfo := range images {
|
|
|
|
image := imageInfo.String()
|
2021-07-20 16:36:12 +00:00
|
|
|
jmespath := utils.JsonPointerToJMESPath(imageInfo.JSONPointer)
|
2021-10-02 08:19:47 +00:00
|
|
|
changed, err := iv.policyContext.JSONContext.HasChanged(jmespath)
|
2021-07-20 16:36:12 +00:00
|
|
|
if err == nil && !changed {
|
2021-10-02 08:19:47 +00:00
|
|
|
iv.logger.V(4).Info("no change in image, skipping check", "image", image)
|
2021-07-20 16:36:12 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2021-07-10 01:01:46 +00:00
|
|
|
if !wildcard.Match(imagePattern, image) {
|
2021-10-02 08:19:47 +00:00
|
|
|
iv.logger.V(4).Info("image does not match pattern", "image", image, "pattern", imagePattern)
|
2021-07-10 01:01:46 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2021-10-02 08:19:47 +00:00
|
|
|
var ruleResp *response.RuleResponse
|
|
|
|
if len(imageVerify.Attestations) == 0 {
|
|
|
|
var digest string
|
2021-11-05 06:26:22 +00:00
|
|
|
ruleResp, digest = iv.verifySignature(imageVerify, imageInfo)
|
2021-10-02 21:24:06 +00:00
|
|
|
if ruleResp.Status == response.RuleStatusPass {
|
2021-10-02 08:19:47 +00:00
|
|
|
iv.patchDigest(imageInfo, digest, ruleResp)
|
|
|
|
}
|
|
|
|
} else {
|
2021-10-02 21:24:06 +00:00
|
|
|
ruleResp = iv.attestImage(repository, key, imageInfo, imageVerify.Attestations)
|
2021-10-02 08:19:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
iv.resp.PolicyResponse.Rules = append(iv.resp.PolicyResponse.Rules, *ruleResp)
|
|
|
|
incrementAppliedCount(iv.resp)
|
2021-10-01 18:10:36 +00:00
|
|
|
}
|
|
|
|
}
|
2021-07-10 01:01:46 +00:00
|
|
|
|
2021-10-01 18:10:36 +00:00
|
|
|
func getSignatureRepository(imageVerify *v1.ImageVerification) string {
|
|
|
|
repository := cosign.ImageSignatureRepository
|
|
|
|
if imageVerify.Repository != "" {
|
|
|
|
repository = imageVerify.Repository
|
|
|
|
}
|
|
|
|
|
|
|
|
return repository
|
|
|
|
}
|
|
|
|
|
2021-11-05 06:26:22 +00:00
|
|
|
func (iv *imageVerifier) verifySignature(imageVerify *v1.ImageVerification, imageInfo *context.ImageInfo) (*response.RuleResponse, string) {
|
2021-10-01 18:10:36 +00:00
|
|
|
image := imageInfo.String()
|
2021-10-02 08:19:47 +00:00
|
|
|
iv.logger.Info("verifying image", "image", image)
|
2021-10-01 18:10:36 +00:00
|
|
|
|
|
|
|
ruleResp := &response.RuleResponse{
|
2021-10-02 08:19:47 +00:00
|
|
|
Name: iv.rule.Name,
|
2021-10-01 18:10:36 +00:00
|
|
|
Type: utils.Validation.String(),
|
|
|
|
}
|
2021-07-10 01:01:46 +00:00
|
|
|
|
2021-11-05 06:26:22 +00:00
|
|
|
opts := cosign.Options{
|
|
|
|
ImageRef: image,
|
|
|
|
Repository: imageVerify.Repository,
|
|
|
|
Log: iv.logger,
|
|
|
|
}
|
|
|
|
|
|
|
|
if imageVerify.Key != "" {
|
|
|
|
opts.Key = imageVerify.Key
|
|
|
|
} else {
|
|
|
|
opts.Roots = []byte(imageVerify.Roots)
|
2021-12-16 06:19:44 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if imageVerify.Issuer != "" {
|
|
|
|
opts.Issuer = imageVerify.Issuer
|
|
|
|
}
|
|
|
|
|
|
|
|
if imageVerify.Subject != "" {
|
2021-11-05 06:26:22 +00:00
|
|
|
opts.Subject = imageVerify.Subject
|
|
|
|
}
|
|
|
|
|
2021-12-16 06:19:44 +00:00
|
|
|
if imageVerify.Annotations != nil {
|
|
|
|
opts.Annotations = imageVerify.Annotations
|
|
|
|
}
|
|
|
|
|
2021-10-01 18:10:36 +00:00
|
|
|
start := time.Now()
|
2021-11-05 06:26:22 +00:00
|
|
|
digest, err := cosign.VerifySignature(opts)
|
2021-10-01 18:10:36 +00:00
|
|
|
if err != nil {
|
2021-10-02 08:19:47 +00:00
|
|
|
iv.logger.Info("failed to verify image signature", "image", image, "error", err, "duration", time.Since(start).Seconds())
|
2021-10-02 21:24:06 +00:00
|
|
|
ruleResp.Status = response.RuleStatusFail
|
2021-10-02 08:19:47 +00:00
|
|
|
ruleResp.Message = fmt.Sprintf("image signature verification failed for %s: %v", image, err)
|
|
|
|
return ruleResp, ""
|
2021-10-01 18:10:36 +00:00
|
|
|
}
|
|
|
|
|
2021-10-02 21:24:06 +00:00
|
|
|
ruleResp.Status = response.RuleStatusPass
|
2021-10-02 08:19:47 +00:00
|
|
|
ruleResp.Message = fmt.Sprintf("image %s verified", image)
|
|
|
|
iv.logger.V(3).Info("verified image", "image", image, "digest", digest, "duration", time.Since(start).Seconds())
|
|
|
|
return ruleResp, digest
|
2021-10-01 18:10:36 +00:00
|
|
|
}
|
|
|
|
|
2021-10-02 08:19:47 +00:00
|
|
|
func (iv *imageVerifier) patchDigest(imageInfo *context.ImageInfo, digest string, ruleResp *response.RuleResponse) {
|
2021-10-01 18:10:36 +00:00
|
|
|
if imageInfo.Digest == "" {
|
|
|
|
patch, err := makeAddDigestPatch(imageInfo, digest)
|
|
|
|
if err != nil {
|
2021-10-02 08:19:47 +00:00
|
|
|
iv.logger.Error(err, "failed to patch image with digest", "image", imageInfo.String(), "jsonPath", imageInfo.JSONPointer)
|
2021-10-01 18:10:36 +00:00
|
|
|
} else {
|
2021-10-02 08:19:47 +00:00
|
|
|
iv.logger.V(4).Info("patching verified image with digest", "patch", string(patch))
|
2021-10-01 18:10:36 +00:00
|
|
|
ruleResp.Patches = [][]byte{patch}
|
|
|
|
}
|
2021-07-10 01:01:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func makeAddDigestPatch(imageInfo *context.ImageInfo, digest string) ([]byte, error) {
|
|
|
|
var patch = make(map[string]interface{})
|
|
|
|
patch["op"] = "replace"
|
2021-07-20 16:36:12 +00:00
|
|
|
patch["path"] = imageInfo.JSONPointer
|
2021-07-10 01:01:46 +00:00
|
|
|
patch["value"] = imageInfo.String() + "@" + digest
|
|
|
|
return json.Marshal(patch)
|
|
|
|
}
|
2021-10-02 08:19:47 +00:00
|
|
|
|
2021-10-06 05:42:42 +00:00
|
|
|
func (iv *imageVerifier) attestImage(repository, key string, imageInfo *context.ImageInfo, attestationChecks []*v1.Attestation) *response.RuleResponse {
|
2021-10-02 08:19:47 +00:00
|
|
|
image := imageInfo.String()
|
2021-10-02 21:24:06 +00:00
|
|
|
start := time.Now()
|
2021-11-22 18:49:21 +00:00
|
|
|
|
2021-11-05 06:26:22 +00:00
|
|
|
statements, err := cosign.FetchAttestations(image, key, repository, iv.logger)
|
2021-10-02 21:24:06 +00:00
|
|
|
if err != nil {
|
|
|
|
iv.logger.Info("failed to fetch attestations", "image", image, "error", err, "duration", time.Since(start).Seconds())
|
2021-10-07 05:48:56 +00:00
|
|
|
return ruleError(iv.rule, utils.ImageVerify, fmt.Sprintf("failed to fetch attestations for %s", image), err)
|
2021-10-02 08:19:47 +00:00
|
|
|
}
|
|
|
|
|
2021-11-22 18:49:21 +00:00
|
|
|
iv.logger.V(4).Info("received attestations", "statements", statements)
|
|
|
|
statementsByPredicate := buildStatementMap(statements)
|
2021-10-06 05:42:42 +00:00
|
|
|
|
|
|
|
for _, ac := range attestationChecks {
|
2021-11-22 18:49:21 +00:00
|
|
|
statements := statementsByPredicate[ac.PredicateType]
|
|
|
|
if statements == nil {
|
|
|
|
msg := fmt.Sprintf("predicate type %s not found", ac.PredicateType)
|
|
|
|
return ruleResponse(iv.rule, utils.ImageVerify, msg, response.RuleStatusFail)
|
|
|
|
}
|
|
|
|
|
2021-10-06 05:42:42 +00:00
|
|
|
for _, s := range statements {
|
2021-11-22 18:49:21 +00:00
|
|
|
val, err := iv.checkAttestations(ac, s, imageInfo)
|
|
|
|
if err != nil {
|
|
|
|
return ruleError(iv.rule, utils.ImageVerify, "failed to check attestation", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if !val {
|
|
|
|
msg := fmt.Sprintf("attestation checks failed for %s and predicate %s", imageInfo.String(), ac.PredicateType)
|
|
|
|
return ruleResponse(iv.rule, utils.ImageVerify, msg, response.RuleStatusFail)
|
2021-10-06 05:42:42 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-06 16:55:23 +00:00
|
|
|
msg := fmt.Sprintf("attestation checks passed for %s", imageInfo.String())
|
|
|
|
iv.logger.V(2).Info(msg)
|
2021-10-07 05:48:56 +00:00
|
|
|
return ruleResponse(iv.rule, utils.ImageVerify, msg, response.RuleStatusPass)
|
2021-10-06 05:42:42 +00:00
|
|
|
}
|
|
|
|
|
2021-11-22 18:49:21 +00:00
|
|
|
func buildStatementMap(statements []map[string]interface{}) map[string][]map[string]interface{} {
|
|
|
|
results := map[string][]map[string]interface{}{}
|
|
|
|
for _, s := range statements {
|
|
|
|
predicateType := s["predicateType"].(string)
|
|
|
|
if results[predicateType] != nil {
|
|
|
|
results[predicateType] = append(results[predicateType], s)
|
|
|
|
} else {
|
|
|
|
results[predicateType] = []map[string]interface{}{s}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return results
|
|
|
|
}
|
|
|
|
|
2021-10-06 18:18:36 +00:00
|
|
|
func (iv *imageVerifier) checkAttestations(a *v1.Attestation, s map[string]interface{}, img *context.ImageInfo) (bool, error) {
|
2021-10-06 05:42:42 +00:00
|
|
|
if len(a.Conditions) == 0 {
|
|
|
|
return true, nil
|
|
|
|
}
|
2021-10-02 21:24:06 +00:00
|
|
|
|
|
|
|
iv.policyContext.JSONContext.Checkpoint()
|
|
|
|
defer iv.policyContext.JSONContext.Restore()
|
2021-10-06 05:42:42 +00:00
|
|
|
|
|
|
|
predicate, ok := s["predicate"].(map[string]interface{})
|
|
|
|
if !ok {
|
|
|
|
return false, fmt.Errorf("failed to extract predicate from statement: %v", s)
|
2021-10-02 21:24:06 +00:00
|
|
|
}
|
|
|
|
|
2021-10-06 05:42:42 +00:00
|
|
|
if err := iv.policyContext.JSONContext.AddJSONObject(predicate); err != nil {
|
|
|
|
return false, errors.Wrapf(err, fmt.Sprintf("failed to add Statement to the context %v", s))
|
2021-10-02 08:19:47 +00:00
|
|
|
}
|
|
|
|
|
2021-10-06 05:42:42 +00:00
|
|
|
imgMap := map[string]interface{}{
|
2021-10-06 18:18:36 +00:00
|
|
|
"image": map[string]interface{}{
|
|
|
|
"image": img.String(),
|
2021-10-06 05:42:42 +00:00
|
|
|
"registry": img.Registry,
|
2021-10-06 18:18:36 +00:00
|
|
|
"path": img.Path,
|
|
|
|
"name": img.Name,
|
|
|
|
"tag": img.Tag,
|
|
|
|
"digest": img.Digest,
|
2021-10-06 05:42:42 +00:00
|
|
|
},
|
2021-10-02 21:24:06 +00:00
|
|
|
}
|
2021-10-02 08:19:47 +00:00
|
|
|
|
2021-10-06 05:42:42 +00:00
|
|
|
if err := iv.policyContext.JSONContext.AddJSONObject(imgMap); err != nil {
|
|
|
|
return false, errors.Wrapf(err, fmt.Sprintf("failed to add image to the context %v", s))
|
|
|
|
}
|
2021-10-02 08:19:47 +00:00
|
|
|
|
2021-10-06 05:42:42 +00:00
|
|
|
conditions, err := variables.SubstituteAllInConditions(iv.logger, iv.policyContext.JSONContext, a.Conditions)
|
2021-10-02 21:24:06 +00:00
|
|
|
if err != nil {
|
2021-10-06 05:42:42 +00:00
|
|
|
return false, errors.Wrapf(err, "failed to substitute variables in attestation conditions")
|
2021-10-02 21:24:06 +00:00
|
|
|
}
|
|
|
|
|
2021-10-06 05:42:42 +00:00
|
|
|
pass := variables.EvaluateAnyAllConditions(iv.logger, iv.policyContext.JSONContext, conditions)
|
2021-10-02 21:24:06 +00:00
|
|
|
return pass, nil
|
2021-10-02 08:19:47 +00:00
|
|
|
}
|