-
Notifications
You must be signed in to change notification settings - Fork 498
/
verify.go
298 lines (271 loc) · 8.48 KB
/
verify.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
//
// 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 verify
import (
"context"
"crypto"
"crypto/ecdsa"
"crypto/x509"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"os"
"github.com/google/go-containerregistry/pkg/name"
"github.com/pkg/errors"
"github.com/sigstore/cosign/cmd/cosign/cli/fulcio"
"github.com/sigstore/cosign/cmd/cosign/cli/options"
"github.com/sigstore/cosign/cmd/cosign/cli/rekor"
"github.com/sigstore/cosign/cmd/cosign/cli/sign"
"github.com/sigstore/cosign/pkg/blob"
"github.com/sigstore/cosign/pkg/cosign"
"github.com/sigstore/cosign/pkg/cosign/pivkey"
"github.com/sigstore/cosign/pkg/cosign/pkcs11key"
"github.com/sigstore/cosign/pkg/oci"
sigs "github.com/sigstore/cosign/pkg/signature"
"github.com/sigstore/sigstore/pkg/cryptoutils"
"github.com/sigstore/sigstore/pkg/signature"
"github.com/sigstore/sigstore/pkg/signature/payload"
)
// VerifyCommand verifies a signature on a supplied container image
// nolint
type VerifyCommand struct {
options.RegistryOptions
CheckClaims bool
KeyRef string
CertRef string
CertEmail string
CertOidcIssuer string
Sk bool
Slot string
Output string
RekorURL string
Attachment string
Annotations sigs.AnnotationsMap
SignatureRef string
HashAlgorithm crypto.Hash
LocalImage bool
}
// Exec runs the verification command
func (c *VerifyCommand) Exec(ctx context.Context, images []string) (err error) {
if len(images) == 0 {
return flag.ErrHelp
}
switch c.Attachment {
case "sbom", "":
break
default:
return flag.ErrHelp
}
// always default to sha256 if the algorithm hasn't been explicitly set
if c.HashAlgorithm == 0 {
c.HashAlgorithm = crypto.SHA256
}
if !options.OneOf(c.KeyRef, c.CertRef, c.Sk) && !options.EnableExperimental() {
return &options.KeyParseError{}
}
ociremoteOpts, err := c.ClientOpts(ctx)
if err != nil {
return errors.Wrap(err, "constructing client options")
}
co := &cosign.CheckOpts{
Annotations: c.Annotations.Annotations,
RegistryClientOpts: ociremoteOpts,
CertEmail: c.CertEmail,
CertOidcIssuer: c.CertOidcIssuer,
SignatureRef: c.SignatureRef,
}
if c.CheckClaims {
co.ClaimVerifier = cosign.SimpleClaimVerifier
}
if options.EnableExperimental() {
if c.RekorURL != "" {
rekorClient, err := rekor.NewClient(c.RekorURL)
if err != nil {
return errors.Wrap(err, "creating Rekor client")
}
co.RekorClient = rekorClient
}
co.RootCerts = fulcio.GetRoots()
}
keyRef := c.KeyRef
certRef := c.CertRef
// Keys are optional!
var pubKey signature.Verifier
switch {
case keyRef != "":
pubKey, err = sigs.PublicKeyFromKeyRefWithHashAlgo(ctx, keyRef, c.HashAlgorithm)
if err != nil {
return errors.Wrap(err, "loading public key")
}
pkcs11Key, ok := pubKey.(*pkcs11key.Key)
if ok {
defer pkcs11Key.Close()
}
case c.Sk:
sk, err := pivkey.GetKeyWithSlot(c.Slot)
if err != nil {
return errors.Wrap(err, "opening piv token")
}
defer sk.Close()
pubKey, err = sk.Verifier()
if err != nil {
return errors.Wrap(err, "initializing piv token verifier")
}
case certRef != "":
cert, err := loadCertFromFileOrURL(c.CertRef)
if err != nil {
return err
}
pubKey, err = signature.LoadECDSAVerifier(cert.PublicKey.(*ecdsa.PublicKey), crypto.SHA256)
if err != nil {
return err
}
}
co.SigVerifier = pubKey
// NB: There are only 2 kinds of verification right now:
// 1. You gave us the public key explicitly to verify against so co.SigVerifier is non-nil or,
// 2. We're going to find an x509 certificate on the signature and verify against Fulcio root trust
// TODO(nsmith5): Refactor this verification logic to pass back _how_ verification
// was performed so we don't need to use this fragile logic here.
fulcioVerified := (co.SigVerifier == nil)
for _, img := range images {
if c.LocalImage {
verified, bundleVerified, err := cosign.VerifyLocalImageSignatures(ctx, img, co)
if err != nil {
return err
}
PrintVerificationHeader(img, co, bundleVerified, fulcioVerified)
PrintVerification(img, verified, c.Output)
} else {
ref, err := name.ParseReference(img)
if err != nil {
return errors.Wrap(err, "parsing reference")
}
ref, err = sign.GetAttachedImageRef(ref, c.Attachment, ociremoteOpts...)
if err != nil {
return errors.Wrapf(err, "resolving attachment type %s for image %s", c.Attachment, img)
}
verified, bundleVerified, err := cosign.VerifyImageSignatures(ctx, ref, co)
if err != nil {
return err
}
PrintVerificationHeader(ref.Name(), co, bundleVerified, fulcioVerified)
PrintVerification(ref.Name(), verified, c.Output)
}
}
return nil
}
func PrintVerificationHeader(imgRef string, co *cosign.CheckOpts, bundleVerified, fulcioVerified bool) {
fmt.Fprintf(os.Stderr, "\nVerification for %s --\n", imgRef)
fmt.Fprintln(os.Stderr, "The following checks were performed on each of these signatures:")
if co.ClaimVerifier != nil {
if co.Annotations != nil {
fmt.Fprintln(os.Stderr, " - The specified annotations were verified.")
}
fmt.Fprintln(os.Stderr, " - The cosign claims were validated")
}
if bundleVerified {
fmt.Fprintln(os.Stderr, " - Existence of the claims in the transparency log was verified offline")
} else if co.RekorClient != nil {
fmt.Fprintln(os.Stderr, " - The claims were present in the transparency log")
fmt.Fprintln(os.Stderr, " - The signatures were integrated into the transparency log when the certificate was valid")
}
if co.SigVerifier != nil {
fmt.Fprintln(os.Stderr, " - The signatures were verified against the specified public key")
}
if fulcioVerified {
fmt.Fprintln(os.Stderr, " - Any certificates were verified against the Fulcio roots.")
}
}
// PrintVerification logs details about the verification to stdout
func PrintVerification(imgRef string, verified []oci.Signature, output string) {
switch output {
case "text":
for _, sig := range verified {
if cert, err := sig.Cert(); err == nil && cert != nil {
fmt.Println("Certificate subject: ", sigs.CertSubject(cert))
if issuerURL := sigs.CertIssuerExtension(cert); issuerURL != "" {
fmt.Println("Certificate issuer URL: ", issuerURL)
}
}
p, err := sig.Payload()
if err != nil {
fmt.Fprintf(os.Stderr, "Error fetching payload: %v", err)
return
}
fmt.Println(string(p))
}
default:
var outputKeys []payload.SimpleContainerImage
for _, sig := range verified {
p, err := sig.Payload()
if err != nil {
fmt.Fprintf(os.Stderr, "Error fetching payload: %v", err)
return
}
ss := payload.SimpleContainerImage{}
if err := json.Unmarshal(p, &ss); err != nil {
fmt.Println("error decoding the payload:", err.Error())
return
}
if cert, err := sig.Cert(); err == nil && cert != nil {
if ss.Optional == nil {
ss.Optional = make(map[string]interface{})
}
ss.Optional["Subject"] = sigs.CertSubject(cert)
if issuerURL := sigs.CertIssuerExtension(cert); issuerURL != "" {
ss.Optional["Issuer"] = issuerURL
}
}
if bundle, err := sig.Bundle(); err == nil && bundle != nil {
if ss.Optional == nil {
ss.Optional = make(map[string]interface{})
}
ss.Optional["Bundle"] = bundle
}
outputKeys = append(outputKeys, ss)
}
b, err := json.Marshal(outputKeys)
if err != nil {
fmt.Println("error when generating the output:", err.Error())
return
}
fmt.Printf("\n%s\n", string(b))
}
}
func loadCertFromFileOrURL(path string) (*x509.Certificate, error) {
pems, err := blob.LoadFileOrURL(path)
if err != nil {
return nil, err
}
return loadCertFromPEM(pems)
}
func loadCertFromPEM(pems []byte) (*x509.Certificate, error) {
var out []byte
out, err := base64.StdEncoding.DecodeString(string(pems))
if err != nil {
// not a base64
out = pems
}
certs, err := cryptoutils.UnmarshalCertificatesFromPEM(out)
if err != nil {
return nil, err
}
if len(certs) == 0 {
return nil, errors.New("no certs found in pem file")
}
return certs[0], nil
}