-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcosign.go
500 lines (418 loc) · 13.3 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
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
package main
import (
"bytes"
"context"
"crypto"
"crypto/x509"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"github.com/google/go-containerregistry/pkg/name"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/google/go-containerregistry/pkg/v1/remote"
// "k8s.io/client-go/tools/reference"
"github.com/google/go-containerregistry/pkg/crane"
"github.com/opencontainers/go-digest"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/sigstore/cosign/v2/cmd/cosign/cli/fulcio"
"github.com/sigstore/cosign/v2/pkg/cosign"
"github.com/sigstore/cosign/v2/pkg/oci"
"github.com/sigstore/sigstore/pkg/cryptoutils"
"github.com/sigstore/sigstore/pkg/signature"
"github.com/sigstore/sigstore/pkg/signature/payload"
)
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)
}
func loadCert(pem []byte) (*x509.Certificate, error) {
var out []byte
out, err := base64.StdEncoding.DecodeString(string(pem))
if err != nil {
// not a base64
out = pem
}
certs, err := cryptoutils.UnmarshalCertificatesFromPEM(out)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal certificate from PEM format: %w", err)
}
if len(certs) == 0 {
return nil, fmt.Errorf("no certs found in pem file")
}
return certs[0], nil
}
func v1ToOciSpecDescriptor(v1desc v1.Descriptor) ocispec.Descriptor {
ociDesc := ocispec.Descriptor{
MediaType: string(v1desc.MediaType),
Digest: digest.Digest(v1desc.Digest.String()),
Size: v1desc.Size,
URLs: v1desc.URLs,
Annotations: v1desc.Annotations,
Data: v1desc.Data,
ArtifactType: v1desc.ArtifactType,
}
if v1desc.Platform != nil {
ociDesc.Platform = &ocispec.Platform{
Architecture: v1desc.Platform.Architecture,
OS: v1desc.Platform.OS,
OSVersion: v1desc.Platform.OSVersion,
}
}
return ociDesc
}
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
}
func fetch_image_manifests(image string) error {
ref, err := name.ParseReference(image)
if err != nil {
fmt.Println(err)
}
desc, err := remote.Get(ref)
if err != nil {
panic(err)
}
byteStream, err := json.Marshal(desc.Descriptor)
if err != nil {
fmt.Println("error during the marshaling of descriptor")
panic(err)
}
jsonString := string(byteStream)
fmt.Println(jsonString)
img, err := remote.Image(ref)
if err != nil {
panic(err)
}
manifest, err := img.Manifest()
if err != nil {
panic(err)
}
byteStream3, err := json.Marshal(manifest)
if err != nil {
panic(err)
}
jsonString3 := string(byteStream3)
fmt.Println("manifest :", jsonString3)
return nil
}
func keyed_signatureVerification(image string) error {
ref, err := name.ParseReference(image)
if err != nil {
fmt.Println(err)
}
ctx := context.Background()
fmt.Println("-------------------------------------Keyed Signature verification --------------------------------------")
fmt.Println("")
filePath := "cosign.pub"
data, err := ioutil.ReadFile(filePath)
if err != nil {
fmt.Println("Error reading file:", err)
panic(err)
}
// Convert the data to a byte slice ([]byte)
byteData := []byte(data)
verifier, err := decodePEM(byteData, crypto.SHA256)
if err != nil {
fmt.Println("Error occured during the fetching of verifier;")
panic(err)
}
trustedTransparencyLogPubKeys, err := cosign.GetRekorPubs(ctx)
if err != nil {
fmt.Println("Error occured during the getting rekor pubs keys...")
}
fmt.Println("Rekor keys are : ", trustedTransparencyLogPubKeys.Keys)
// rekor_client := cosign.Get(ctx)
cosignVeriOptions := cosign.CheckOpts{
SigVerifier: verifier,
// RekorClient: rekor_client,
RekorPubKeys: trustedTransparencyLogPubKeys,
}
/*
fmt.Println("Public Key", verifier.PublicKey)
fmt.Println("Verify signature : ", verifier.VerifySignature)
fmt.Println("Sig.Verifier", verifier)
*/
verified_signatures, isVerified, err := cosign.VerifyImageSignatures(ctx, ref, &cosignVeriOptions)
fmt.Println("-----------------------------Signature verification in Progress -------------------------------")
if err != nil {
fmt.Println("No signature matched : ", err)
}
if !isVerified {
fmt.Println("---------------------------------Verification failed ----------------------------------------")
}
fmt.Println("")
fmt.Println("---------------------------- Signature verification completed ----------------------------------")
fmt.Println("")
fmt.Println("--------------------------------List of the verified signatures ----------------------------------")
for _, sig := range verified_signatures {
fmt.Println(sig.Base64Signature())
}
return nil
}
func keyless_sigantureVerification(image string) error {
ref, err := name.ParseReference(image)
if err != nil {
fmt.Println(err)
}
ctx := context.Background()
fmt.Println("-------------------------------------Keyless Signature verification --------------------------------------")
fmt.Println("")
identity := cosign.Identity{
Issuer: "https://accounts.google.com",
Subject: "[email protected]",
}
identities := []cosign.Identity{
identity,
}
trustedTransparencyLogPubKeys, err := cosign.GetRekorPubs(ctx)
if err != nil {
fmt.Println("Error occured during the getting rekor pubs keys...")
panic(err)
}
fmt.Println("Rekor keys are : ", trustedTransparencyLogPubKeys.Keys)
roots, err := fulcio.GetRoots()
if err != nil {
fmt.Println("Did not get roots")
panic(err)
}
ctLogPubKeys, err := cosign.GetCTLogPubs(ctx)
if err != nil {
fmt.Println("Error with CTLogPubKeys")
panic(err)
}
cosignOptions := cosign.CheckOpts{
Identities: identities,
RekorPubKeys: trustedTransparencyLogPubKeys,
CTLogPubKeys: ctLogPubKeys,
RootCerts: roots,
}
verified_signatures, isVerified, err := cosign.VerifyImageSignatures(ctx, ref, &cosignOptions)
fmt.Println("-----------------------------Signature verification in Progress -------------------------------")
if err != nil {
fmt.Println("No signature matched : ", err)
panic(err)
}
if !isVerified {
fmt.Println("---------------------------------Verification failed ----------------------------------------")
panic(err)
}
fmt.Println("")
fmt.Println("---------------------------- Signature verification completed ----------------------------------")
fmt.Println("")
fmt.Println("--------------------------------List of the verified signatures ----------------------------------")
for _, sig := range verified_signatures {
fmt.Println(sig.Base64Signature())
}
return nil
}
func verifyAttestaions(image string) error {
ref, err := name.ParseReference(image)
if err != nil {
fmt.Println(err)
}
ctx := context.Background()
fmt.Println("---------------------------- Image attestations verification ----------------------------------")
filePath := "cosign.pub"
data, err := ioutil.ReadFile(filePath)
if err != nil {
fmt.Println("Error reading file:", err)
panic(err)
}
// Convert the data to a byte slice ([]byte)
byteData := []byte(data)
verifier, err := decodePEM(byteData, crypto.SHA256)
if err != nil {
fmt.Println("Error occured during the fetching of verifier;")
panic(err)
}
trustedTransparencyLogPubKeys, err := cosign.GetRekorPubs(ctx)
if err != nil {
fmt.Println("Error occured during the getting rekor pubs keys...")
panic(err)
}
fmt.Println("Rekor keys are : ", trustedTransparencyLogPubKeys.Keys)
// rekor_client := cosign.Get(ctx)
cosignOptions := cosign.CheckOpts{
SigVerifier: verifier,
// RekorClient: rekor_client,
RekorPubKeys: trustedTransparencyLogPubKeys,
}
sigs, bundelVerified, err := cosign.VerifyImageAttestations(ctx, ref, &cosignOptions)
fmt.Println("-----------------------------Attestations verification in Progress -------------------------------")
fmt.Println("")
if err != nil {
fmt.Println("Error in fething verified siganture", err)
panic(err)
}
if !bundelVerified {
fmt.Println("Bundle is not verified!!", err)
panic(err)
}
/*
Not useful now
payloads, err := extractPayload(sigs)
if err != nil {
fmt.Println(err)
}
for _, p := range payloads {
fmt.Println(p.Critical.Type)
}
*/
fmt.Println("")
fmt.Println("------------------- Verified artifacts are ------------------------------")
fmt.Println("")
for _, sig := range sigs {
io, err := sig.Uncompressed()
if err != nil {
panic(err)
}
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(io)
if err != nil {
panic(err)
}
fmt.Println("---------------------------------------------------------------------------------")
fmt.Println("")
fmt.Println(buf.String())
}
return nil
}
func fetch_attestations(image string, artifactType string) error {
fmt.Println("---------------------------Fetching the referrers-----------------------------------")
fmt.Println()
ref, err := name.ParseReference(image)
if err != nil {
panic(err)
}
desc, err := crane.Head(image)
if err != nil {
fmt.Println("error in Crane.Head call")
panic(err)
}
refDescs, err := remote.Referrers(ref.Context().Digest(desc.Digest.String()))
if err != nil {
fmt.Println("error in refferels api : ", ref.Context().Digest(desc.Digest.String()))
panic(err)
}
// fmt.Println("Data :", str2)
for _, descriptor := range refDescs.Manifests {
fmt.Println("Digest:", descriptor.Digest.String())
fmt.Println("Artifact Type:", descriptor.ArtifactType)
if descriptor.ArtifactType == artifactType {
ref := ref.Context().RegistryStr() + "/" + ref.Context().RepositoryStr() + "@" + descriptor.Digest.String()
reference, err := name.ParseReference(ref)
if err != nil {
panic(err)
}
// desct := v1ToOciSpecDescriptor(descriptor)
manifestBytes, err := crane.Manifest(ref)
if err != nil {
panic(err)
}
var manifest ocispec.Manifest
if err := json.Unmarshal(manifestBytes, &manifest); err != nil {
panic(err)
}
predicateRef := reference.Context().RegistryStr() + "/" + reference.Context().RepositoryStr() + "@" + manifest.Layers[0].Digest.String()
layer, err := crane.PullLayer(predicateRef)
if err != nil {
panic(err)
}
io, err := layer.Uncompressed()
if err != nil {
panic(err)
}
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(io)
if err != nil {
panic(err)
}
fmt.Println(buf.String())
}
}
return nil
}
func images_manifest_and_signature_fetch(image string) {
// regstry := os.Getenv("REGISTRY")
// repo := os.Getenv("REPOSITORY")
// identity := os.Getenv("DIGEST")
// image := regstry + "/" + repo + "@" + identity
// image := os.Getenv("IMAGE_URI")
// fmt.Println(image)
// image := "ghcr.io/hackeramitkumar/client:unverified"
ref, err := name.ParseReference(image)
if err != nil {
panic(err)
}
ctx := context.Background()
fmt.Println("-------------------------------- Image refrence information : ------------------------------")
fmt.Println("Registry : ", ref.Context().RegistryStr())
fmt.Println("Repository : ", ref.Context().RepositoryStr())
fmt.Println("Identifier : ", ref.Identifier())
fmt.Println("")
fmt.Println("------------------------------------------Artifacts--------------------------------------------")
fetch_image_manifests(image)
fmt.Println()
fmt.Print("----------------- Fetching the signedPayload for : ", image)
fmt.Println("-------------------")
fmt.Println("")
fmt.Println("")
signedPayloads, err := cosign.FetchSignaturesForReference(ctx, ref)
if err != nil {
fmt.Println("Error During signedPayloads Fetcheing ")
panic(err)
}
fmt.Println("------------------------------------ Fetched all the signedPayloads ----------------------------")
fmt.Println()
for _, Payload := range signedPayloads {
fmt.Println("------------------------------------- Signed Payload Content --------------------------------")
fmt.Println("")
fmt.Println("--------------------------------------Signed Payload Bundle ----------------------------------")
byteStream, err := json.Marshal(Payload.Bundle)
if err != nil {
fmt.Println("Error marshaling JSON:", err)
return
}
jsonString := string(byteStream)
fmt.Println(jsonString)
fmt.Println("")
fmt.Println("--------------------------------------Signature for Payload -----------------------------------")
fmt.Println(Payload.Base64Signature)
fmt.Println("")
fmt.Println("-----------------------------------Certificate for the Payload---------------------------------")
byteStream2, err := json.Marshal(Payload.Cert)
if err != nil {
fmt.Println("Error marshaling JSON:", err)
return
}
jsonString2 := string(byteStream2)
fmt.Println(jsonString2)
}
fmt.Println("")
}
func main() {
image := "localhost:5001/demo-reffer:app3"
artifactType := "application/spdx+json"
images_manifest_and_signature_fetch(image)
keyed_signatureVerification(image)
keyless_sigantureVerification(image)
fetch_attestations(image, artifactType) // referrers API
verifyAttestaions(image)
}