This repository was archived by the owner on Sep 23, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathvalidator.go
More file actions
1714 lines (1572 loc) · 64.1 KB
/
Copy pathvalidator.go
File metadata and controls
1714 lines (1572 loc) · 64.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright 2021 The Sigstore Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package webhook
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/sha256"
"crypto/x509"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"strings"
"sync"
"github.com/google/go-containerregistry/pkg/authn"
"github.com/google/go-containerregistry/pkg/authn/k8schain"
"github.com/google/go-containerregistry/pkg/name"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/google/go-containerregistry/pkg/v1/remote"
"github.com/google/go-containerregistry/pkg/v1/types"
"github.com/sigstore/cosign/v2/pkg/cosign"
ociremote "github.com/sigstore/cosign/v2/pkg/oci/remote"
"github.com/sigstore/cosign/v2/pkg/policy"
"github.com/sigstore/policy-controller/pkg/apis/config"
policyduckv1beta1 "github.com/sigstore/policy-controller/pkg/apis/duck/v1beta1"
policycontrollerconfig "github.com/sigstore/policy-controller/pkg/config"
pctuf "github.com/sigstore/policy-controller/pkg/tuf"
webhookcip "github.com/sigstore/policy-controller/pkg/webhook/clusterimagepolicy"
"github.com/sigstore/policy-controller/pkg/webhook/registryauth"
rekor "github.com/sigstore/rekor/pkg/client"
"github.com/sigstore/rekor/pkg/generated/client"
"github.com/sigstore/sigstore/pkg/cryptoutils"
"github.com/sigstore/sigstore/pkg/fulcioroots"
"github.com/sigstore/sigstore/pkg/signature"
"github.com/sigstore/sigstore/pkg/tuf"
admissionv1 "k8s.io/api/admission/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"knative.dev/pkg/apis"
duckv1 "knative.dev/pkg/apis/duck/v1"
kubeclient "knative.dev/pkg/client/injection/kube/client"
"knative.dev/pkg/logging"
sgroot "github.com/sigstore/sigstore-go/pkg/root"
"github.com/sigstore/sigstore-go/pkg/verify"
)
type Signature interface {
Digest() (v1.Hash, error)
Payload() ([]byte, error)
Signature() ([]byte, error)
Cert() (*x509.Certificate, error)
}
// Assert that Signature implements policy.PayloadProvider (used by
// policy.AttestationToPayloadJSON)
var _ policy.PayloadProvider = (Signature)(nil)
type Validator struct{}
func NewValidator(_ context.Context) *Validator {
return &Validator{}
}
// isDeletedOrStatusUpdate returns true if the resource in question is being
// deleted, is already deleted or Status is being updated. In any of those
// cases, we do not validate the resource
func isDeletedOrStatusUpdate(ctx context.Context, deletionTimestamp *metav1.Time) bool {
return apis.IsInDelete(ctx) || deletionTimestamp != nil || apis.IsInStatusUpdate(ctx)
}
// This is attached to contexts passed to webhook methods so that if the
// user wants to get the Spec for the PolicyResult we can attach it.
type includeSpecKey struct{}
// IncludeSpec adds the spec to context so it's later available for
// inclusion in PolicyResult. This is safe to call multiple times, first
// one "wins". This is on purpose so that since we call down the various
// levels and we want the highest resource level to be available, otherwise
// everything boils down to PodSpec and it's lossy then.
func IncludeSpec(ctx context.Context, spec interface{}) context.Context {
if GetIncludeSpec(ctx) == nil {
return context.WithValue(ctx, includeSpecKey{}, spec)
}
return ctx
}
// GetIncludeSpec returns the highest level spec for a resource possible.
// For example, for Deployment it would return Deployment.Spec
func GetIncludeSpec(ctx context.Context) interface{} {
return ctx.Value(includeSpecKey{})
}
// This is attached to contexts passed to webhook methods so that if the
// user wants to get the ObjectMeta for the PolicyResult we can attach it.
type includeObjectMetaKey struct{}
// This is attached to contexts passed to webhook methods so that if the
// user wants to get the TypeMeta for the PolicyResult we can attach it.
type includeTypeMetaKey struct{}
// IncludeObjectMeta adds the ObjectMeta to context so it's later available for
// inclusion in PolicyResult. This is safe to call multiple times, first
// one "wins". This is on purpose so that since we call down the various
// levels and we want the highest resource level to be available, otherwise
// everything boils down to PodSpec and it's lossy then.
func IncludeObjectMeta(ctx context.Context, meta interface{}) context.Context {
if GetIncludeObjectMeta(ctx) == nil {
return context.WithValue(ctx, includeObjectMetaKey{}, meta)
}
return ctx
}
// GetIncludeObjectMeta returns the highest level ObjectMeta for a resource
// possible. For example, for Deployment it would return Deployment.Spec
func GetIncludeObjectMeta(ctx context.Context) interface{} {
return ctx.Value(includeObjectMetaKey{})
}
// IncludeTypeMeta adds the TypeMeta to context so it's later available for
// inclusion in PolicyResult. This is safe to call multiple times, first
// one "wins". This is on purpose so that since we call down the various
// levels and we want the highest resource level to be available, otherwise
// everything boils down to PodSpec and it's lossy then.
func IncludeTypeMeta(ctx context.Context, meta interface{}) context.Context {
if GetIncludeTypeMeta(ctx) == nil {
return context.WithValue(ctx, includeTypeMetaKey{}, meta)
}
return ctx
}
// GetIncludeTypeMeta returns the highest level TypeMeta for a resource
// possible. For example, for Deployment it would return:
// apiVersion: apps/v1
// kind: Deployment
func GetIncludeTypeMeta(ctx context.Context) interface{} {
return ctx.Value(includeTypeMetaKey{})
}
// ValidatePodScalable implements policyduckv1beta1.PodScalableValidator
// It is very similar to ValidatePodSpecable, but allows for spec.replicas
// to be decremented. This allows for scaling down pods with non-compliant
// images that would otherwise be forbidden.
func (v *Validator) ValidatePodScalable(ctx context.Context, ps *policyduckv1beta1.PodScalable) *apis.FieldError {
// If we are deleting (or already deleted) or updating status, don't block.
if isDeletedOrStatusUpdate(ctx, ps.DeletionTimestamp) {
return nil
}
// If we are being scaled down don't block it.
if ps.IsScalingDown(ctx) {
logging.FromContext(ctx).Debugf("Skipping validations due to scale down request %s/%s", &ps.ObjectMeta.Name, &ps.ObjectMeta.Namespace)
return nil
}
// Attach the spec for down the line to be attached if it's required by
// policy to be included in the PolicyResult.
ctx = IncludeSpec(ctx, ps.Spec)
ctx = IncludeObjectMeta(ctx, ps.ObjectMeta)
ctx = IncludeTypeMeta(ctx, ps.TypeMeta)
imagePullSecrets := make([]string, 0, len(ps.Spec.Template.Spec.ImagePullSecrets))
for _, s := range ps.Spec.Template.Spec.ImagePullSecrets {
imagePullSecrets = append(imagePullSecrets, s.Name)
}
ns := getNamespace(ctx, ps.Namespace)
opt := k8schain.Options{
Namespace: ns,
ServiceAccountName: ps.Spec.Template.Spec.ServiceAccountName,
ImagePullSecrets: imagePullSecrets,
}
return v.validatePodSpec(ctx, ns, ps.Kind, ps.APIVersion, ps.ObjectMeta.Labels, &ps.Spec.Template.Spec, opt).ViaField("spec.template.spec")
}
// ValidatePodSpecable implements duckv1.PodSpecValidator
func (v *Validator) ValidatePodSpecable(ctx context.Context, wp *duckv1.WithPod) *apis.FieldError {
// If we are deleting (or already deleted) or updating status, don't block.
if isDeletedOrStatusUpdate(ctx, wp.DeletionTimestamp) {
return nil
}
// Attach the spec/metadata for down the line to be attached if it's
// required by policy to be included in the PolicyResult.
ctx = IncludeSpec(ctx, wp.Spec)
ctx = IncludeObjectMeta(ctx, wp.ObjectMeta)
ctx = IncludeTypeMeta(ctx, wp.TypeMeta)
imagePullSecrets := make([]string, 0, len(wp.Spec.Template.Spec.ImagePullSecrets))
for _, s := range wp.Spec.Template.Spec.ImagePullSecrets {
imagePullSecrets = append(imagePullSecrets, s.Name)
}
ns := getNamespace(ctx, wp.Namespace)
opt := k8schain.Options{
Namespace: ns,
ServiceAccountName: wp.Spec.Template.Spec.ServiceAccountName,
ImagePullSecrets: imagePullSecrets,
}
return v.validatePodSpec(ctx, ns, wp.Kind, wp.APIVersion, wp.ObjectMeta.Labels, &wp.Spec.Template.Spec, opt).ViaField("spec.template.spec")
}
// ValidatePod implements duckv1.PodValidator
func (v *Validator) ValidatePod(ctx context.Context, p *duckv1.Pod) *apis.FieldError {
// If we are deleting (or already deleted) or updating status, don't block.
if isDeletedOrStatusUpdate(ctx, p.DeletionTimestamp) {
return nil
}
// Attach the spec/metadata for down the line to be attached if it's
// required by policy to be included in the PolicyResult.
ctx = IncludeSpec(ctx, p.Spec)
ctx = IncludeObjectMeta(ctx, p.ObjectMeta)
imagePullSecrets := make([]string, 0, len(p.Spec.ImagePullSecrets))
for _, s := range p.Spec.ImagePullSecrets {
imagePullSecrets = append(imagePullSecrets, s.Name)
}
ns := getNamespace(ctx, p.Namespace)
opt := k8schain.Options{
Namespace: ns,
ServiceAccountName: p.Spec.ServiceAccountName,
ImagePullSecrets: imagePullSecrets,
}
return v.validatePodSpec(ctx, ns, p.Kind, p.APIVersion, p.ObjectMeta.Labels, &p.Spec, opt).ViaField("spec")
}
// ValidateCronJob implements duckv1.CronJobValidator
func (v *Validator) ValidateCronJob(ctx context.Context, c *duckv1.CronJob) *apis.FieldError {
// If we are deleting (or already deleted) or updating status, don't block.
if isDeletedOrStatusUpdate(ctx, c.DeletionTimestamp) {
return nil
}
// Attach the spec/metadata for down the line to be attached if it's
// required by policy to be included in the PolicyResult.
ctx = IncludeSpec(ctx, c.Spec)
ctx = IncludeObjectMeta(ctx, c.ObjectMeta)
ctx = IncludeTypeMeta(ctx, c.TypeMeta)
imagePullSecrets := make([]string, 0, len(c.Spec.JobTemplate.Spec.Template.Spec.ImagePullSecrets))
for _, s := range c.Spec.JobTemplate.Spec.Template.Spec.ImagePullSecrets {
imagePullSecrets = append(imagePullSecrets, s.Name)
}
ns := getNamespace(ctx, c.Namespace)
opt := k8schain.Options{
Namespace: ns,
ServiceAccountName: c.Spec.JobTemplate.Spec.Template.Spec.ServiceAccountName,
ImagePullSecrets: imagePullSecrets,
}
return v.validatePodSpec(ctx, ns, c.Kind, c.APIVersion, c.ObjectMeta.Labels, &c.Spec.JobTemplate.Spec.Template.Spec, opt).ViaField("spec.jobTemplate.spec.template.spec")
}
func (v *Validator) validatePodSpec(ctx context.Context, namespace, kind, apiVersion string, labels map[string]string, ps *corev1.PodSpec, opt k8schain.Options) (errs *apis.FieldError) {
kc, err := registryauth.NewK8sKeychain(ctx, kubeclient.Get(ctx), opt)
if err != nil {
logging.FromContext(ctx).Warnf("Unable to build k8schain: %v", err)
return apis.ErrGeneric(err.Error(), apis.CurrentField)
}
type containerCheckResult struct {
index int
containerCheckResult *apis.FieldError
}
checkContainers := func(cs []corev1.Container, field string) {
results := make(chan containerCheckResult, len(cs))
wg := new(sync.WaitGroup)
for i, c := range cs {
i := i
c := c
wg.Add(1)
go func() {
defer wg.Done()
// Require digests, otherwise the validation is meaningless
// since the tag can move.
fe := refOrFieldError(c.Image, field, i)
if fe != nil {
results <- containerCheckResult{index: i, containerCheckResult: fe}
return
}
containerErrors := v.validateContainerImage(ctx, c.Image, namespace, field, i, kind, apiVersion, labels, kc, ociremote.WithRemoteOptions(
remote.WithContext(ctx),
remote.WithAuthFromKeychain(kc),
))
results <- containerCheckResult{index: i, containerCheckResult: containerErrors}
}()
}
for i := 0; i < len(cs); i++ {
select {
case <-ctx.Done():
errs = errs.Also(apis.ErrGeneric("context was canceled before validation completed"))
case result, ok := <-results:
if !ok {
errs = errs.Also(apis.ErrGeneric("results channel failed to produce a result"))
} else {
errs = errs.Also(result.containerCheckResult)
}
}
}
wg.Wait()
}
checkEphemeralContainers := func(cs []corev1.EphemeralContainer, field string) {
results := make(chan containerCheckResult, len(cs))
wg := new(sync.WaitGroup)
for i, c := range cs {
i := i
c := c
wg.Add(1)
go func() {
defer wg.Done()
// Require digests, otherwise the validation is meaningless
// since the tag can move.
fe := refOrFieldError(c.Image, field, i)
if fe != nil {
results <- containerCheckResult{index: i, containerCheckResult: fe}
return
}
containerErrors := v.validateContainerImage(ctx, c.Image, namespace, field, i, kind, apiVersion, labels, kc, ociremote.WithRemoteOptions(
remote.WithContext(ctx),
remote.WithAuthFromKeychain(kc),
))
results <- containerCheckResult{index: i, containerCheckResult: containerErrors}
}()
}
for i := 0; i < len(cs); i++ {
select {
case <-ctx.Done():
errs = errs.Also(apis.ErrGeneric("context was canceled before validation completed"))
case result, ok := <-results:
if !ok {
errs = errs.Also(apis.ErrGeneric("results channel failed to produce a result"))
} else {
errs = errs.Also(result.containerCheckResult)
}
}
}
wg.Wait()
}
checkContainers(ps.InitContainers, "initContainers")
checkContainers(ps.Containers, "containers")
checkEphemeralContainers(ps.EphemeralContainers, "ephemeralContainers")
return errs
}
// setNoMatchingPoliciesError returns nil if the no matching policies behaviour
// has been set to allow or has not been set. Otherwise returns either a warning
// or error based on the NoMatchPolicy.
func setNoMatchingPoliciesError(ctx context.Context, image, field string, index int) *apis.FieldError {
// Check what the configuration is and act accordingly.
pcConfig := policycontrollerconfig.FromContextOrDefaults(ctx)
noMatchingPolicyError := apis.ErrGeneric("no matching policies", "image").ViaFieldIndex(field, index)
noMatchingPolicyError.Details = image
if pcConfig == nil {
// This should not happen, but handle it as fail close
return noMatchingPolicyError
}
switch pcConfig.NoMatchPolicy {
case policycontrollerconfig.AllowAll:
// Allow it through, nothing to do.
return nil
case policycontrollerconfig.DenyAll:
return noMatchingPolicyError
case policycontrollerconfig.WarnAll:
return noMatchingPolicyError.At(apis.WarningLevel)
default:
// Fail closed.
return noMatchingPolicyError
}
}
// validatePolicies will go through all the matching Policies and their
// Authorities for a given image. Returns the map of policy=>Validated
// signatures. From the map you can see the number of matched policies along
// with the signatures that were verified.
// If there's a policy that did not match, it will be returned in the errors map
// along with all the errors that caused it to fail.
// Note that if an image does not match any policies, it's perfectly
// reasonable that the return value is 0, nil since there were no errors, but
// the image was not validated against any matching policy and hence authority.
func validatePolicies(ctx context.Context, namespace string, ref name.Reference, policies map[string]webhookcip.ClusterImagePolicy, kc authn.Keychain, remoteOpts ...ociremote.Option) (map[string]*PolicyResult, map[string][]error) {
type retChannelType struct {
name string
policyResult *PolicyResult
errors []error
}
results := make(chan retChannelType, len(policies))
wg := new(sync.WaitGroup)
// For each matching policy it must validate at least one Authority within
// it.
// From the Design document, the part about multiple Policies matching:
// "If multiple policies match a particular image, then ALL of those
// policies must be satisfied for the image to be admitted."
// If none of the Authorities for a given policy pass the checks, gather
// the errors here. If one passes, do not return the errors.
for cipName, cip := range policies {
// Due to running in gofunc
cipName := cipName
cip := cip
logging.FromContext(ctx).Debugf("Checking Policy: %s", cipName)
wg.Add(1)
go func() {
defer wg.Done()
result := retChannelType{name: cipName}
result.policyResult, result.errors = ValidatePolicy(ctx, namespace, ref, cip, kc, remoteOpts...)
// Cache the result.
FromContext(ctx).Set(ctx, ref.Name(), cipName, string(cip.UID), cip.ResourceVersion, &CacheResult{
PolicyResult: result.policyResult,
Errors: result.errors,
})
results <- result
}()
}
// Gather all validated policies here.
policyResults := make(map[string]*PolicyResult)
// For a policy that does not pass at least one authority, gather errors
// here so that we can give meaningful errors to the user.
ret := map[string][]error{}
for i := 0; i < len(policies); i++ {
select {
case <-ctx.Done():
ret["internalerror"] = append(ret["internalerror"], fmt.Errorf("context was canceled before validation completed"))
case result, ok := <-results:
if !ok {
ret["internalerror"] = append(ret["internalerror"], fmt.Errorf("results channel failed to produce a result"))
continue
}
switch {
// Return AuthorityMatches before errors, since even if there
// are errors, if there are 0 or more authorities that match,
// it will pass the Policy. Of course, a CIP level policy can
// override this behaviour, but that has been checked above and
// if it failed, it will nil out the policyResult.
case result.policyResult != nil:
policyResults[result.name] = result.policyResult
case len(result.errors) > 0:
ret[result.name] = append(ret[result.name], result.errors...)
default:
ret[result.name] = append(ret[result.name], fmt.Errorf("failed to process policy: %s", result.name))
}
}
}
wg.Wait()
return policyResults, ret
}
func asFieldError(warn bool, err error) *apis.FieldError {
r := &apis.FieldError{Message: err.Error()}
if warn {
return r.At(apis.WarningLevel)
}
return r.At(apis.ErrorLevel)
}
// ValidatePolicy will go through all the Authorities for a given image/policy
// and return validated authorities if at least one of the Authorities
// validated the signatures OR attestations if atttestations were specified.
// Returns PolicyResult if one or more authorities matched, otherwise nil.
// In any case returns all errors encountered if none of the authorities
// passed.
// kc is the Keychain to use for fetching ConfigFile that's independent of the
// signatures / attestations.
func ValidatePolicy(ctx context.Context, namespace string, ref name.Reference, cip webhookcip.ClusterImagePolicy, kc authn.Keychain, remoteOpts ...ociremote.Option) (*PolicyResult, []error) {
// Check the cache and return if hit, otherwise, check the policy
cacheResult := FromContext(ctx).Get(ctx, ref.String(), string(cip.UID), cip.ResourceVersion)
if cacheResult != nil {
return cacheResult.PolicyResult, cacheResult.Errors
}
// Each gofunc creates and puts one of these into a results channel.
// Once each gofunc finishes, we go through the channel and pull out
// the results.
type retChannelType struct {
name string
static bool
attestations map[string][]PolicyAttestation
signatures []PolicySignature
err error
}
wg := new(sync.WaitGroup)
results := make(chan retChannelType, len(cip.Authorities))
for _, authority := range cip.Authorities {
authority := authority // due to gofunc
logging.FromContext(ctx).Debugf("Checking Authority: %s", authority.Name)
wg.Add(1)
go func() {
defer wg.Done()
result := retChannelType{name: authority.Name}
// Assignment for appendAssign lint error
authorityRemoteOpts := remoteOpts
authorityRemoteOpts = append(authorityRemoteOpts, authority.RemoteOpts...)
signaturePullSecretsOpts, err := authority.SourceSignaturePullSecretsOpts(ctx, namespace)
if err != nil {
result.err = err
results <- result
return
}
authorityRemoteOpts = append(authorityRemoteOpts, signaturePullSecretsOpts...)
switch {
case authority.Static != nil:
if authority.Static.Action == "fail" {
result.err = cosign.NewVerificationError("disallowed by static policy: " + authority.Static.Message)
results <- result
return
}
result.static = true
case len(authority.Attestations) > 0:
if authority.SignatureFormat == "bundle" {
result.attestations, result.err = ValidatePolicyAttestationsForAuthorityWithBundle(ctx, ref, authority, kc)
} else {
// We're doing the verify-attestations path, so validate (.att)
result.attestations, result.err = ValidatePolicyAttestationsForAuthority(ctx, ref, authority, authorityRemoteOpts...)
}
default:
result.signatures, result.err = ValidatePolicySignaturesForAuthority(ctx, ref, authority, authorityRemoteOpts...)
}
results <- result
}()
}
// If none of the Authorities for a given policy pass the checks, gather
// the errors here. Even if there are errors, return the matched
// authoritypolicies.
authorityErrors := make([]error, 0, len(cip.Authorities))
// We collect all the successfully satisfied Authorities into this and
// return it.
policyResult := &PolicyResult{
AuthorityMatches: make(map[string]AuthorityMatch, len(cip.Authorities)),
}
for range cip.Authorities {
select {
case <-ctx.Done():
authorityErrors = append(authorityErrors, fmt.Errorf("%w before validation completed", ctx.Err()))
case result, ok := <-results:
if !ok {
authorityErrors = append(authorityErrors, errors.New("results channel closed before all results were sent"))
continue
}
switch {
case result.err != nil:
// We only wrap actual policy failures as FieldErrors with the
// possibly Warn level. Other things imho should be still
// be considered errors.
authorityErrors = append(authorityErrors, asFieldError(cip.Mode == "warn", result.err))
case len(result.signatures) > 0:
policyResult.AuthorityMatches[result.name] = AuthorityMatch{Signatures: result.signatures}
case len(result.attestations) > 0:
policyResult.AuthorityMatches[result.name] = AuthorityMatch{Attestations: result.attestations}
case result.static:
// This happens when we encounter a policy with:
// static:
// action: "pass"
policyResult.AuthorityMatches[result.name] = AuthorityMatch{
Static: true,
}
default:
authorityErrors = append(authorityErrors, fmt.Errorf("failed to process authority: %s", result.name))
}
}
}
wg.Wait()
// Even if there are errors, return the policies, since as per the
// spec, we just need one authority to pass checks. If more than
// one are required, that is enforced at the CIP policy level.
// If however there are no authorityMatches, return nil so we don't have
// to keep checking the length on the returned calls.
if len(policyResult.AuthorityMatches) == 0 {
return nil, authorityErrors
}
// Ok, there's at least one valid authority that matched. If there's a CIP
// level policy, validate it here before returning.
if cip.Policy != nil {
if cip.Policy.FetchConfigFile != nil && *cip.Policy.FetchConfigFile {
logging.FromContext(ctx).Debug("Fetching ConfigFiles")
// It's unfortunate that we have to keep having the kc here. It
// would be nice if we could just unwrap/generate the ggcr remote
// options from the oci remote options, but for now this is how
// we're rolling.
rOpts := []remote.Option{
remote.WithContext(ctx),
remote.WithAuthFromKeychain(kc),
}
configFiles, errs := getConfigs(ctx, ref, rOpts...)
if len(errs) > 0 {
for _, e := range errs {
authorityErrors = append(authorityErrors, asFieldError(cip.Mode == "warn", e))
}
return nil, authorityErrors
}
policyResult.Config = configFiles
}
if cip.Policy.IncludeSpec != nil && *cip.Policy.IncludeSpec {
policyResult.Spec = GetIncludeSpec(ctx)
}
if cip.Policy.IncludeObjectMeta != nil && *cip.Policy.IncludeObjectMeta {
policyResult.ObjectMeta = GetIncludeObjectMeta(ctx)
}
if cip.Policy.IncludeTypeMeta != nil && *cip.Policy.IncludeTypeMeta {
policyResult.TypeMeta = GetIncludeTypeMeta(ctx)
}
logging.FromContext(ctx).Info("Validating CIP level policy")
policyJSON, err := json.Marshal(policyResult)
if err != nil {
return nil, append(authorityErrors, err)
}
logging.FromContext(ctx).Infof("CIP level policy: %s", string(policyJSON))
warn, err := policy.EvaluatePolicyAgainstJSON(ctx, "ClusterImagePolicy", cip.Policy.Type, cip.Policy.Data, policyJSON)
if err != nil {
logging.FromContext(ctx).Warnf("Failed to validate CIP level policy; err: %w; against %s", err, string(policyJSON))
return nil, append(authorityErrors, asFieldError(cip.Mode == "warn", err))
}
if warn != nil {
logging.FromContext(ctx).Warnf("Failed to validate CIP level policy; warn: %w; against %s", warn, string(policyJSON))
return nil, append(authorityErrors, asFieldError(cip.Mode == "warn", warn))
}
}
return policyResult, authorityErrors
}
func ociSignatureToPolicySignature(ctx context.Context, sigs []Signature) []PolicySignature {
ret := make([]PolicySignature, 0, len(sigs))
for _, ociSig := range sigs {
logging.FromContext(ctx).Debugf("Converting signature %+v", ociSig)
sigID, err := signatureID(ociSig)
if err != nil {
logging.FromContext(ctx).Debugf("Error fetching signature %+v", err)
continue
}
if cert, err := ociSig.Cert(); err == nil && cert != nil {
ce := cosign.CertExtensions{
Cert: cert,
}
sub := ""
if sans := cryptoutils.GetSubjectAlternateNames(cert); len(sans) > 0 {
sub = sans[0]
}
ret = append(ret, PolicySignature{
ID: sigID,
Subject: sub,
Issuer: ce.GetIssuer(),
GithubExtensions: GithubExtensions{
WorkflowTrigger: ce.GetCertExtensionGithubWorkflowTrigger(),
WorkflowSHA: ce.GetExtensionGithubWorkflowSha(),
WorkflowName: ce.GetCertExtensionGithubWorkflowName(),
WorkflowRepo: ce.GetCertExtensionGithubWorkflowRepository(),
WorkflowRef: ce.GetCertExtensionGithubWorkflowRef(),
},
})
} else {
ret = append(ret, PolicySignature{
ID: sigID,
// TODO(mattmoor): Is there anything we should encode for key-based?
})
}
}
return ret
}
// signatureID creates a unique hash for the Signature, using both the signature itself + the cert.
func signatureID(sig Signature) (string, error) {
h := sha256.New()
s, err := sig.Signature()
if err != nil {
return "", err
}
if _, err := h.Write(s); err != nil {
return "", err
}
cert, err := sig.Cert()
if err != nil {
return "", err
}
if cert != nil {
c, err := cryptoutils.MarshalCertificateToPEM(cert)
if err != nil {
return "", err
}
if _, err := h.Write(c); err != nil {
return "", err
}
}
return hex.EncodeToString(h.Sum(nil)), nil
}
// attestation is used to accumulate the signature along with extracted and
// validated metadata during validation to construct a list of
// PolicyAttestations upon completion without needing to refetch any of the
// parts.
type attestation struct {
Signature
PredicateType string
Payload []byte
Digest string
}
func attestationToPolicyAttestations(ctx context.Context, atts []attestation) []PolicyAttestation {
ret := make([]PolicyAttestation, 0, len(atts))
for _, att := range atts {
logging.FromContext(ctx).Debugf("Converting attestation %+v", att)
sigID, err := signatureID(att.Signature)
if err != nil {
logging.FromContext(ctx).Debugf("Error fetching attestation signature %+v", err)
continue
}
if cert, err := att.Cert(); err == nil && cert != nil {
ce := cosign.CertExtensions{
Cert: cert,
}
sub := ""
if sans := cryptoutils.GetSubjectAlternateNames(cert); len(sans) > 0 {
sub = sans[0]
}
ret = append(ret, PolicyAttestation{
PolicySignature: PolicySignature{
ID: sigID,
Subject: sub,
Issuer: ce.GetIssuer(),
GithubExtensions: GithubExtensions{
WorkflowTrigger: ce.GetCertExtensionGithubWorkflowTrigger(),
WorkflowSHA: ce.GetExtensionGithubWorkflowSha(),
WorkflowName: ce.GetCertExtensionGithubWorkflowName(),
WorkflowRepo: ce.GetCertExtensionGithubWorkflowRepository(),
WorkflowRef: ce.GetCertExtensionGithubWorkflowRef(),
},
},
Digest: att.Digest,
PredicateType: att.PredicateType,
Payload: att.Payload,
})
} else {
ret = append(ret, PolicyAttestation{
PolicySignature: PolicySignature{
ID: sigID,
// TODO(mattmoor): Is there anything we should encode for key-based?
},
PredicateType: att.PredicateType,
Payload: att.Payload,
Digest: att.Digest,
})
}
}
return ret
}
// ValidatePolicySignaturesForAuthority takes the Authority and tries to
// verify a signature against it.
func ValidatePolicySignaturesForAuthority(ctx context.Context, ref name.Reference, authority webhookcip.Authority, remoteOpts ...ociremote.Option) ([]PolicySignature, error) {
name := authority.Name
checkOpts, err := checkOptsFromAuthority(ctx, authority, remoteOpts...)
if err != nil {
logging.FromContext(ctx).Errorf("failed constructing checkOpts for %s: +v", name, err)
return nil, fmt.Errorf("constructing checkOpts for %s: %w", name, err)
}
switch {
case authority.Key != nil:
if len(authority.Key.PublicKeys) == 0 {
return nil, fmt.Errorf("there are no public keys for authority %s", name)
}
// TODO(vaikas): What should happen if there are multiple keys
// Is it even allowed? 'valid' returns success if any key
// matches.
// https://github.com/sigstore/policy-controller/issues/1652
sps, err := valid(ctx, ref, authority.Key.PublicKeys, authority.Key.HashAlgorithmCode, checkOpts)
if err != nil {
return nil, fmt.Errorf("signature key validation failed for authority %s for %s: %w", name, ref.Name(), err)
}
logging.FromContext(ctx).Debugf("validated signature for %s for authority %s got %d signatures", ref.Name(), authority.Name, len(sps))
return ociSignatureToPolicySignature(ctx, sps), nil
case authority.Keyless != nil:
if authority.Keyless.URL != nil {
sps, err := validSignatures(ctx, ref, checkOpts)
if err != nil {
logging.FromContext(ctx).Errorf("failed validSignatures for authority %s with fulcio for %s: %v", name, ref.Name(), err)
return nil, fmt.Errorf("signature keyless validation failed for authority %s for %s: %w", name, ref.Name(), err)
}
logging.FromContext(ctx).Debugf("validated signature for %s, got %d signatures", ref.Name(), len(sps))
return ociSignatureToPolicySignature(ctx, sps), nil
}
return nil, fmt.Errorf("no Keyless URL specified")
case authority.RFC3161Timestamp != nil:
sps, err := validSignatures(ctx, ref, checkOpts)
if err != nil {
logging.FromContext(ctx).Errorf("failed validSignatures for authority %s with fulcio for %s: %v", name, ref.Name(), err)
return nil, fmt.Errorf("signature TSA validation failed for authority %s for %s: %w", name, ref.Name(), err)
}
logging.FromContext(ctx).Debugf("validated TSA signature for %s, got %d signatures", ref.Name(), len(sps))
return ociSignatureToPolicySignature(ctx, sps), nil
}
// This should never happen because authority has to have been validated to
// be either having a Key, Keyless, or Static (handled elsewhere)
return nil, errors.New("authority has neither key, keyless, or static specified")
}
// ValidatePolicyAttestationsForAuthority takes the Authority and tries to
// verify attestations against it.
func ValidatePolicyAttestationsForAuthority(ctx context.Context, ref name.Reference, authority webhookcip.Authority, remoteOpts ...ociremote.Option) (map[string][]PolicyAttestation, error) {
name := authority.Name
checkOpts, err := checkOptsFromAuthority(ctx, authority, remoteOpts...)
if err != nil {
logging.FromContext(ctx).Errorf("failed creating checkopts client: %v", err)
return nil, fmt.Errorf("creating CheckOpts: %w", err)
}
verifiedAttestations := []Signature{}
switch {
case authority.Key != nil && len(authority.Key.PublicKeys) > 0:
for _, k := range authority.Key.PublicKeys {
verifier, err := signature.LoadVerifier(k, authority.Key.HashAlgorithmCode)
if err != nil {
logging.FromContext(ctx).Errorf("error creating verifier: %v", err)
return nil, fmt.Errorf("creating verifier: %w", err)
}
checkOpts.SigVerifier = verifier
va, err := validAttestations(ctx, ref, checkOpts)
if err != nil {
logging.FromContext(ctx).Errorf("error validating attestations: %v", err)
return nil, fmt.Errorf("attestation key validation failed for authority %s for %s: %w", name, ref.Name(), err)
}
verifiedAttestations = append(verifiedAttestations, va...)
}
case authority.Keyless != nil:
if authority.Keyless != nil && authority.Keyless.URL != nil {
va, err := validAttestations(ctx, ref, checkOpts)
if err != nil {
logging.FromContext(ctx).Errorf("failed validAttestationsWithFulcio for authority %s with fulcio for %s: %v", name, ref.Name(), err)
return nil, fmt.Errorf("attestation keyless validation failed for authority %s for %s: %w", name, ref.Name(), err)
}
verifiedAttestations = append(verifiedAttestations, va...)
}
case authority.RFC3161Timestamp != nil:
va, err := validAttestations(ctx, ref, checkOpts)
if err != nil {
logging.FromContext(ctx).Errorf("failed validAttestations for authority %s with fulcio for %s: %v", name, ref.Name(), err)
return nil, fmt.Errorf("signature TSA validAttestations failed for authority %s for %s: %w", name, ref.Name(), err)
}
logging.FromContext(ctx).Debugf("validated TSA signature for %s, got %d signatures", ref.Name(), len(va))
verifiedAttestations = append(verifiedAttestations, va...)
}
// If we didn't get any verified attestations either from the Key or Keyless
// path, then error out
if len(verifiedAttestations) == 0 {
logging.FromContext(ctx).Errorf("no valid attestations found for authority %s for %s", name, ref.Name())
return nil, fmt.Errorf("%s for authority %s for %s", cosign.ErrNoMatchingAttestationsMessage, name, ref.Name())
}
logging.FromContext(ctx).Debugf("Found %d valid attestations, validating policies for them", len(verifiedAttestations))
return checkPredicates(ctx, authority, verifiedAttestations)
}
func checkPredicates(ctx context.Context, authority webhookcip.Authority, verifiedAttestations []Signature) (map[string][]PolicyAttestation, error) {
// Now spin through the Attestations that the user specified and validate
// them.
// TODO(vaikas): Pretty inefficient here, figure out a better way if
// possible.
ret := make(map[string][]PolicyAttestation, len(authority.Attestations))
// Keep track of all the predicate types that we checked so that we can
// provide the user with a helpful error message in cases where the
// precicateType specified is not found (typoed, using different than
// expected, etc.).
// We keep these in the map since there can be duplicates, so just use
// map as uniquifier.
checkedPredicateTypes := map[string]struct{}{}
for _, wantedAttestation := range authority.Attestations {
// Since there can be multiple verified attestations that matched, for
// example multiple 'custom' attestations. We keep the first error that
// we encounter here but do not exit on it, in case another attestation
// satisfies the policy.
var reterror error
// There's a particular type, so we need to go through all the verified
// attestations and make sure that our particular one is satisfied.
checkedAttestations := make([]attestation, 0, len(verifiedAttestations))
for _, va := range verifiedAttestations {
attDigest, err := va.Digest()
if err != nil {
logging.FromContext(ctx).Errorf("failed to get the attestation digest for %s: %v", wantedAttestation.Name, err)
continue
}
attBytes, gotPredicateType, err := policy.AttestationToPayloadJSON(ctx, wantedAttestation.PredicateType, va)
if gotPredicateType != "" {
checkedPredicateTypes[gotPredicateType] = struct{}{}
}
if err != nil {
if reterror == nil {
// Only stash the first error
reterror = err
}
logging.FromContext(ctx).Warnf("failed to convert attestation payload to json: %v", err)
continue
}
if attBytes == nil {
// This happens when we ask for a predicate type that this
// attestation is not for. It's not an error, so we skip it.
continue
}
if wantedAttestation.Type != "" {
if warn, err := policy.EvaluatePolicyAgainstJSON(ctx, wantedAttestation.Name, wantedAttestation.Type, wantedAttestation.Data, attBytes); err != nil || warn != nil {
if reterror == nil {
// Only stash the first error
reterror = err
if err == nil {
reterror = warn
}
}
logging.FromContext(ctx).Warnf("failed policy validation for %s: %v", wantedAttestation.Name, err)
continue
}
}
logging.FromContext(ctx).Debugf("found verified attestation with digest: %s", attDigest.String())
// Ok, so this passed aok, jot it down to our result set as
// verified attestation with the predicate type match
checkedAttestations = append(checkedAttestations, attestation{
Signature: va,
PredicateType: wantedAttestation.PredicateType,
Payload: attBytes,
Digest: attDigest.String(),
})
}
if len(checkedAttestations) == 0 {
if reterror != nil {
// If there was a matching policy, but it failed to be validated
// then return that more specific error instead of the more
// generic 'no matching attestations'.
return nil, reterror
}
cpt := make([]string, 0, len(checkedPredicateTypes))
for pt := range checkedPredicateTypes {
cpt = append(cpt, pt)
}
return nil, fmt.Errorf("%s with type %s, checked the following predicateTypes: %q", cosign.ErrNoMatchingAttestationsMessage, wantedAttestation.PredicateType, strings.Join(cpt, ","))
}
ret[wantedAttestation.Name] = attestationToPolicyAttestations(ctx, checkedAttestations)
}
return ret, nil
}
func ValidatePolicyAttestationsForAuthorityWithBundle(ctx context.Context, ref name.Reference, authority webhookcip.Authority, kc authn.Keychain) (map[string][]PolicyAttestation, error) {
// TODO: Apply authority.Source options (Tag prefix, alternative registry, and signature pull secrets)
remoteOpts := []remote.Option{
remote.WithContext(ctx),
remote.WithAuthFromKeychain(kc),
}
trustedMaterial, err := trustedMaterialFromAuthority(ctx, authority)
if err != nil {
return nil, fmt.Errorf("failed to get trusted material: %w", err)
}