This repository has been archived by the owner on Mar 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 100
/
cosign.go
354 lines (300 loc) · 11.9 KB
/
cosign.go
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
package cosign
import (
"context"
"crypto"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
v1 "github.com/acorn-io/runtime/pkg/apis/internal.acorn.io/v1"
"github.com/acorn-io/runtime/pkg/imagesystem"
"github.com/google/go-containerregistry/pkg/crane"
"github.com/google/go-containerregistry/pkg/name"
ggcrv1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/google/go-containerregistry/pkg/v1/remote/transport"
"github.com/sigstore/cosign/v2/pkg/cosign"
"github.com/sigstore/cosign/v2/pkg/oci"
ociremote "github.com/sigstore/cosign/v2/pkg/oci/remote"
"github.com/sigstore/cosign/v2/pkg/oci/static"
cosignature "github.com/sigstore/cosign/v2/pkg/signature"
"github.com/sigstore/sigstore/pkg/cryptoutils"
"github.com/sigstore/sigstore/pkg/signature"
"github.com/sigstore/sigstore/pkg/signature/payload"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/labels"
"sigs.k8s.io/controller-runtime/pkg/client"
)
type VerifyOpts struct {
ImageRef name.Digest
SignatureRef name.Reference
Namespace string
AnnotationRules v1.SignatureAnnotations
Key string
SignatureAlgorithm string
OciRemoteOpts []ociremote.Option
CraneOpts []crane.Option
NoCache bool
}
// EnsureReferences will enrich the VerifyOpts with the image digest and signature reference.
// It's outsourced here, so we can ensure that it's used as few times as possible to reduce the number of potential
// GET requests to the registry which would count against potential rate limits.
func EnsureReferences(ctx context.Context, c client.Reader, img string, opts *VerifyOpts) error {
if opts == nil {
opts = &VerifyOpts{}
}
if opts.ImageRef.Identifier() == "" {
// --- image name to digest hash
imgRef, err := name.ParseReference(img)
if err != nil {
return fmt.Errorf("failed to parse image %s: %w", img, err)
}
// in the best case, we have a digest ref already, so we don't need to do any external request
if imgDigest, ok := imgRef.(name.Digest); ok {
opts.ImageRef = imgDigest
} else {
imgDigest, err := crane.Digest(imgRef.Name(), opts.CraneOpts...) // this uses HEAD to determine the digest, but falls back to GET if HEAD fails
if err != nil {
return fmt.Errorf("failed to resolve image digest: %w", err)
}
opts.ImageRef = imgRef.Context().Digest(imgDigest)
}
}
if opts.SignatureRef == nil || opts.SignatureRef.Identifier() == "" {
signatureRef, err := ensureSignatureArtifact(ctx, c, opts.Namespace, opts.ImageRef, opts.NoCache, opts.OciRemoteOpts, opts.CraneOpts)
if err != nil {
return fmt.Errorf("failed to ensure signature artifact: %w", err)
}
opts.SignatureRef = signatureRef
}
return nil
}
func ensureSignatureArtifact(ctx context.Context, c client.Reader, namespace string, img name.Digest, noCache bool, ociRemoteOpts []ociremote.Option, craneOpts []crane.Option) (name.Reference, error) {
// -- signature hash
sigTag, err := ociremote.SignatureTag(img, ociRemoteOpts...) // we force imgRef to be a digest above, so this should *not* make a GET request to the registry
if err != nil {
return nil, fmt.Errorf("failed to get signature tag: %w", err)
}
sigDigest, err := SimpleDigest(sigTag, craneOpts...) // similar to crane.Digest, but fails if HEAD returns 404 Not Found
if err != nil {
var terr *transport.Error
if ok := errors.As(err, &terr); ok && terr.StatusCode == http.StatusNotFound {
// signature artifact not found -> that's an actual verification error
cerr := cosign.NewVerificationError(cosign.ErrNoSignaturesFoundMessage)
cerr.(*cosign.VerificationError).SetErrorType(cosign.ErrNoSignaturesFoundType)
return nil, fmt.Errorf("%w: expected signature artifact %s not found", cerr, sigTag.Name())
}
return nil, fmt.Errorf("failed to get signature digest: %w", err)
}
sigRefToUse, err := name.ParseReference(sigTag.Name(), name.WeakValidation)
if err != nil {
return nil, fmt.Errorf("failed to parse signature reference: %w", err)
}
logrus.Debugf("Signature %s has digest: %s", sigRefToUse.Name(), sigDigest)
if !noCache {
internalRepo, _, err := imagesystem.GetInternalRepoForNamespace(ctx, c, namespace)
if err != nil {
return nil, fmt.Errorf("failed to get internal repo for namespace %s: %w", namespace, err)
}
localSignatureArtifact := fmt.Sprintf("%s:%s", internalRepo, sigTag.Identifier())
// --- check if we have the signature artifact locally, if not, copy it over from external registry
mustPull := false
localSigSHA, err := crane.Digest(localSignatureArtifact, craneOpts...) // this uses HEAD to determine the digest, but falls back to GET if HEAD fails
if err != nil {
var terr *transport.Error
if ok := errors.As(err, &terr); ok && terr.StatusCode == http.StatusNotFound {
logrus.Debugf("signature artifact %s not found locally, will try to pull it", localSignatureArtifact)
mustPull = true
} else {
return nil, fmt.Errorf("failed to get local signature digest, cannot check if we have it cached locally: %w", err)
}
} else if localSigSHA != sigDigest {
logrus.Debugf("Local signature digest %s does not match remote signature digest %s, will try to pull it", localSigSHA, sigDigest)
mustPull = true
}
if mustPull {
// --- pull signature artifact
err := crane.Copy(sigTag.Name(), localSignatureArtifact, craneOpts...) // Pull (GET) counts against the rate limits, so this shouldn't be done too often
if err != nil {
return nil, fmt.Errorf("failed to copy signature artifact: %w", err)
}
}
lname, err := name.ParseReference(localSignatureArtifact, name.WeakValidation)
if err != nil {
return nil, fmt.Errorf("failed to parse local signature artifact %s: %w", localSignatureArtifact, err)
}
sigRefToUse = lname
logrus.Debugf("Checking if image %s is signed with %s (cache: %s)", img, sigTag, localSignatureArtifact)
}
return sigRefToUse, nil
}
// VerifySignature checks if the image is signed with the given key and if the annotations match the given rules
// This does a lot of image and image manifest juggling to fetch artifacts, digests, etc. from the registry, so we have to be
// careful to not do too many GET requests that count against registry rate limits (e.g. for Docker Hub).
// Crane uses HEAD (with GET as a fallback) wherever it can, so it's a good choice here e.g. for fetching digests.
func VerifySignature(ctx context.Context, opts VerifyOpts) error {
sigs, err := ociremote.Signatures(opts.SignatureRef, opts.OciRemoteOpts...) // this runs against our internal registry, so it should not count against the rate limits
if err != nil {
return fmt.Errorf("failed to get signatures: %w", err)
}
imgDigestHash, err := ggcrv1.NewHash(opts.ImageRef.DigestStr())
if err != nil {
return err
}
// --- cosign verifier options
cosignOpts := &cosign.CheckOpts{
Annotations: map[string]interface{}{},
ClaimVerifier: cosign.SimpleClaimVerifier,
RegistryClientOpts: opts.OciRemoteOpts,
IgnoreTlog: true,
}
// --- parse key
if opts.Key != "" {
verifier, err := LoadKey(ctx, opts.Key, opts.SignatureAlgorithm)
if err != nil {
return fmt.Errorf("failed to load key: %w", err)
}
cosignOpts.SigVerifier = verifier
}
// --- get and verify signatures
signatures, bundlesVerified, err := verifySignatures(ctx, sigs, imgDigestHash, cosignOpts)
if err != nil {
if _, ok := err.(*cosign.VerificationError); ok {
return err
}
return fmt.Errorf("failed to verify image signatures: %w", err)
}
logrus.Debugf("image %s: %d signatures verified (bundle verified: %v)", opts.ImageRef.Name(), len(signatures), bundlesVerified)
// --- extract payloads for subsequent checks
payloads, err := extractPayload(signatures)
if err != nil {
return fmt.Errorf("failed to extract payload: %w", err)
}
// --- check annotations
if err := checkAnnotations(payloads, opts.AnnotationRules); err != nil {
if _, ok := err.(*cosign.VerificationError); ok {
return err
}
return fmt.Errorf("failed to check annotations: %w", err)
}
logrus.Debugf("image %s: Annotations (%+v) verified", opts.ImageRef.Name(), opts.AnnotationRules)
return nil
}
func decodePEM(raw []byte, signatureAlgorithm crypto.Hash) (signature.Verifier, error) {
// PEM encoded file.
pubKey, err := cryptoutils.UnmarshalPEMToPublicKey(raw)
if err != nil {
return nil, fmt.Errorf("pem to public key: %w", err)
}
return signature.LoadVerifier(pubKey, signatureAlgorithm)
}
var ErrAnnotationsUnmatched = cosign.NewVerificationError("annotations unmatched")
func checkAnnotations(payloads []payload.SimpleContainerImage, annotationRule v1.SignatureAnnotations) error {
sel, err := annotationRule.AsSelector()
if err != nil {
return fmt.Errorf("failed to parse annotation rule: %w", err)
}
if sel.Empty() {
return nil
}
kvLists := map[string][]string{}
for _, p := range payloads {
for k, v := range p.Optional {
if v != nil {
kvLists[k] = append(kvLists[k], fmt.Sprint(v))
}
}
}
labelMaps := generateVariations(kvLists) // alternatively we can re-write the label matching logic to work with a map[string][]string
logrus.Debugf("Checking against %d generated label maps: %+v", len(labelMaps), labelMaps)
for _, labelMap := range labelMaps {
if sel.Matches(labels.Set(labelMap)) {
return nil
}
}
logrus.Debugf("No label map variation matched the selector %+v", sel)
return ErrAnnotationsUnmatched
}
func generateVariations(input map[string][]string) []map[string]string {
// Count the number of variations
count := 1
for _, values := range input {
count *= len(values)
}
// Initialize the output slice
output := make([]map[string]string, count)
// Generate variations
for i := 0; i < count; i++ {
output[i] = make(map[string]string)
j := 1
for key, values := range input {
output[i][key] = values[(i/j)%len(values)]
j *= len(values)
}
}
return output
}
func verifySignatures(ctx context.Context, sigs oci.Signatures, h ggcrv1.Hash, co *cosign.CheckOpts) (checkedSignatures []oci.Signature, bundleVerified bool, err error) {
sl, err := sigs.Get()
if err != nil {
return nil, false, err
}
validationErrs := []string{}
for _, sig := range sl {
sig, err := static.Copy(sig)
if err != nil {
validationErrs = append(validationErrs, err.Error())
continue
}
var verr error
bundleVerified, verr = cosign.VerifyImageSignature(ctx, sig, h, co)
if verr != nil {
validationErrs = append(validationErrs, verr.Error())
continue
}
checkedSignatures = append(checkedSignatures, sig)
}
if len(checkedSignatures) == 0 {
cerr := cosign.NewVerificationError(cosign.ErrNoMatchingSignaturesMessage)
cerr.(*cosign.VerificationError).SetErrorType(cosign.ErrNoMatchingSignaturesType)
return nil, false, fmt.Errorf("%w:\n%s", cerr, strings.Join(validationErrs, "\n "))
}
return checkedSignatures, bundleVerified, nil
}
func extractPayload(verified []oci.Signature) ([]payload.SimpleContainerImage, error) {
var sigPayloads []payload.SimpleContainerImage
for _, sig := range verified {
pld, err := sig.Payload()
if err != nil {
return nil, fmt.Errorf("failed to get payload: %w", err)
}
sci := payload.SimpleContainerImage{}
if err := json.Unmarshal(pld, &sci); err != nil {
return nil, fmt.Errorf("error decoding the payload: %w", err)
}
sigPayloads = append(sigPayloads, sci)
}
return sigPayloads, nil
}
var algorithms = map[string]crypto.Hash{
"": crypto.SHA256,
"sha256": crypto.SHA256,
"sha512": crypto.SHA512,
}
func LoadKey(ctx context.Context, keyRef string, algorithm string) (verifier signature.Verifier, err error) {
if strings.HasPrefix(strings.TrimSpace(keyRef), "-----BEGIN PUBLIC KEY-----") {
// no scheme, inline PEM
verifier, err = decodePEM([]byte(keyRef), algorithms[algorithm])
if err != nil {
return nil, fmt.Errorf("failed to load public key from PEM: %w", err)
}
// TODO: add github
} else {
// schemes: k8s://, pkcs11://, gitlab://
verifier, err = cosignature.PublicKeyFromKeyRef(ctx, keyRef)
if err != nil {
return nil, fmt.Errorf("failed to load public key from %s: %w", keyRef, err)
}
}
return
}