Debian Codegraph @

notation.go

raw
1 // Copyright The Notary Project Authors.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // Package notation provides signer and verifier for notation Sign
15 // and Verification.
16 package notation
17
18 import (
19 "context"
20 "crypto/sha256"
21 "crypto/x509"
22 "encoding/hex"
23 "encoding/json"
24 "errors"
25 "fmt"
26 "strings"
27 "time"
28
29 orasRegistry "oras.land/oras-go/v2/registry"
30 "oras.land/oras-go/v2/registry/remote"
31
32 "github.com/notaryproject/notation-core-go/revocation"
33 "github.com/notaryproject/notation-core-go/signature"
34 "github.com/notaryproject/notation-core-go/signature/cose"
35 "github.com/notaryproject/notation-core-go/signature/jws"
36 "github.com/notaryproject/notation-go/internal/envelope"
37 "github.com/notaryproject/notation-go/log"
38 "github.com/notaryproject/notation-go/registry"
39 "github.com/notaryproject/notation-go/verifier/trustpolicy"
40 "github.com/notaryproject/tspclient-go"
41 "github.com/opencontainers/go-digest"
42 ocispec "github.com/opencontainers/image-spec/specs-go/v1"
43 )
44
45 var errDoneVerification = errors.New("done verification")
46
47 var reservedAnnotationPrefixes = [...]string{"io.cncf.notary"}
48
49 // SignerSignOptions contains parameters for Signer.Sign.
50 type SignerSignOptions struct {
51 // SignatureMediaType is the envelope type of the signature.
52 // Currently, both `application/jose+json` and `application/cose` are
53 // supported.
54 SignatureMediaType string
55
56 // ExpiryDuration identifies the expiry duration of the resulted signature.
57 // Zero value represents no expiry duration.
58 ExpiryDuration time.Duration
59
60 // PluginConfig sets or overrides the plugin configuration.
61 PluginConfig map[string]string
62
63 // SigningAgent sets the signing agent name
64 SigningAgent string
65
66 // Timestamper denotes the timestamper for RFC 3161 timestamping
67 Timestamper tspclient.Timestamper
68
69 // TSARootCAs is the cert pool holding caller's TSA trust anchor
70 TSARootCAs *x509.CertPool
71
72 // TSARevocationValidator is used for validating revocation status of
73 // timestamping certificate chain with context during signing.
74 // When present, only used when timestamping is performed.
75 TSARevocationValidator revocation.Validator
76 }
77
78 // Signer is a generic interface for signing an OCI artifact.
79 // The interface allows signing with local or remote keys,
80 // and packing in various signature formats.
81 type Signer interface {
82 // Sign signs the OCI artifact described by its descriptor,
83 // and returns the signature and SignerInfo.
84 Sign(ctx context.Context, desc ocispec.Descriptor, opts SignerSignOptions) ([]byte, *signature.SignerInfo, error)
85 }
86
87 // signerAnnotation facilitates return of manifest annotations by signers
88 type signerAnnotation interface {
89 // PluginAnnotations returns signature manifest annotations returned from
90 // plugin
91 PluginAnnotations() map[string]string
92 }
93
94 // SignOptions contains parameters for notation.Sign.
95 type SignOptions struct {
96 SignerSignOptions
97
98 // ArtifactReference sets the reference of the artifact that needs to be
99 // signed. It can be a tag, a digest or a full reference.
100 ArtifactReference string
101
102 // UserMetadata contains key-value pairs that are added to the signature
103 // payload
104 UserMetadata map[string]string
105 }
106
107 // Sign signs the OCI artifact and push the signature to the Repository.
108 // The descriptor of the sign content is returned upon successful signing.
109 func Sign(ctx context.Context, signer Signer, repo registry.Repository, signOpts SignOptions) (ocispec.Descriptor, error) {
110 // sanity check
111 if err := validateSignArguments(signer, signOpts.SignerSignOptions); err != nil {
112 return ocispec.Descriptor{}, err
113 }
114 if repo == nil {
115 return ocispec.Descriptor{}, errors.New("repo cannot be nil")
116 }
117
118 logger := log.GetLogger(ctx)
119 artifactRef := signOpts.ArtifactReference
120 if ref, err := orasRegistry.ParseReference(artifactRef); err == nil {
121 // artifactRef is a valid full reference
122 artifactRef = ref.Reference
123 }
124 targetDesc, err := repo.Resolve(ctx, artifactRef)
125 if err != nil {
126 return ocispec.Descriptor{}, fmt.Errorf("failed to resolve reference: %w", err)
127 }
128 // artifactRef is a tag or a digest, if it's a digest it has to match
129 // the resolved digest
130 if artifactRef != targetDesc.Digest.String() {
131 if _, err := digest.Parse(artifactRef); err == nil {
132 // artifactRef is a digest, but does not match the resolved digest
133 return ocispec.Descriptor{}, fmt.Errorf("user input digest %s does not match the resolved digest %s", artifactRef, targetDesc.Digest.String())
134 }
135 // artifactRef is a tag
136 logger.Warnf("Always sign the artifact using digest(`@sha256:...`) rather than a tag(`:%s`) because tags are mutable and a tag reference can point to a different artifact than the one signed", artifactRef)
137 logger.Infof("Resolved artifact tag `%s` to digest `%v` before signing", artifactRef, targetDesc.Digest)
138 }
139 descToSign, err := addUserMetadataToDescriptor(ctx, targetDesc, signOpts.UserMetadata)
140 if err != nil {
141 return ocispec.Descriptor{}, err
142 }
143 sig, signerInfo, err := signer.Sign(ctx, descToSign, signOpts.SignerSignOptions)
144 if err != nil {
145 return ocispec.Descriptor{}, err
146 }
147 var pluginAnnotations map[string]string
148 if signerAnts, ok := signer.(signerAnnotation); ok {
149 pluginAnnotations = signerAnts.PluginAnnotations()
150 }
151
152 logger.Debug("Generating annotation")
153 annotations, err := generateAnnotations(signerInfo, pluginAnnotations)
154 if err != nil {
155 return ocispec.Descriptor{}, err
156 }
157 logger.Debugf("Generated annotations: %+v", annotations)
158 logger.Debugf("Pushing signature of artifact descriptor: %+v, signature media type: %v", targetDesc, signOpts.SignatureMediaType)
159 _, _, err = repo.PushSignature(ctx, signOpts.SignatureMediaType, sig, targetDesc, annotations)
160 if err != nil {
161 var referrerError *remote.ReferrersError
162 // do not log an error for failing to delete referral index
163 if !errors.As(err, &referrerError) || !referrerError.IsReferrersIndexDelete() {
164 logger.Error("Failed to push the signature")
165 }
166 return ocispec.Descriptor{}, ErrorPushSignatureFailed{Msg: err.Error()}
167 }
168
169 return targetDesc, nil
170 }
171
172 func validateSignArguments(signer any, signOpts SignerSignOptions) error {
173 if signer == nil {
174 return errors.New("signer cannot be nil")
175 }
176 if signOpts.ExpiryDuration < 0 {
177 return errors.New("expiry duration cannot be a negative value")
178 }
179 if signOpts.ExpiryDuration%time.Second != 0 {
180 return errors.New("expiry duration supports minimum granularity of seconds")
181 }
182 if signOpts.SignatureMediaType == "" {
183 return errors.New("signature media-type cannot be empty")
184 }
185 if err := validateSigMediaType(signOpts.SignatureMediaType); err != nil {
186 return err
187 }
188
189 return nil
190 }
191
192 func addUserMetadataToDescriptor(ctx context.Context, desc ocispec.Descriptor, userMetadata map[string]string) (ocispec.Descriptor, error) {
193 logger := log.GetLogger(ctx)
194
195 if desc.Annotations == nil && len(userMetadata) > 0 {
196 desc.Annotations = map[string]string{}
197 }
198
199 for k, v := range userMetadata {
200 logger.Debugf("Adding metadata %v=%v to annotations", k, v)
201
202 for _, reservedPrefix := range reservedAnnotationPrefixes {
203 if strings.HasPrefix(k, reservedPrefix) {
204 return desc, fmt.Errorf("error adding user metadata: metadata key %v has reserved prefix %v", k, reservedPrefix)
205 }
206 }
207
208 if _, ok := desc.Annotations[k]; ok {
209 return desc, fmt.Errorf("error adding user metadata: metadata key %v is already present in the target artifact", k)
210 }
211
212 desc.Annotations[k] = v
213 }
214
215 return desc, nil
216 }
217
218 // ValidationResult encapsulates the verification result (passed or failed)
219 // for a verification type, including the desired verification action as
220 // specified in the trust policy
221 type ValidationResult struct {
222 // Type of verification that is performed
223 Type trustpolicy.ValidationType
224
225 // Action is the intended action for the given verification type as defined
226 // in the trust policy
227 Action trustpolicy.ValidationAction
228
229 // Error is set if there are any errors during the verification process
230 Error error
231 }
232
233 // VerificationOutcome encapsulates a signature envelope blob, its content,
234 // the verification level and results for each verification type that was
235 // performed.
236 type VerificationOutcome struct {
237 // RawSignature is the signature envelope blob
238 RawSignature []byte
239
240 // EnvelopeContent contains the details of the digital signature and
241 // associated metadata
242 EnvelopeContent *signature.EnvelopeContent
243
244 // VerificationLevel describes what verification level was used for
245 // performing signature verification
246 VerificationLevel *trustpolicy.VerificationLevel
247
248 // VerificationResults contains the verifications performed on the signature
249 // and their results
250 VerificationResults []*ValidationResult
251
252 // Error that caused the verification to fail (if it fails)
253 Error error
254 }
255
256 func (outcome *VerificationOutcome) UserMetadata() (map[string]string, error) {
257 if outcome.EnvelopeContent == nil {
258 return nil, errors.New("unable to find envelope content for verification outcome")
259 }
260
261 var payload envelope.Payload
262 err := json.Unmarshal(outcome.EnvelopeContent.Payload.Content, &payload)
263 if err != nil {
264 return nil, errors.New("failed to unmarshal the payload content in the signature blob to envelope.Payload")
265 }
266
267 if payload.TargetArtifact.Annotations == nil {
268 return map[string]string{}, nil
269 }
270
271 return payload.TargetArtifact.Annotations, nil
272 }
273
274 // VerifierVerifyOptions contains parameters for Verifier.Verify used for verifying OCI artifact.
275 type VerifierVerifyOptions struct {
276 // ArtifactReference is the reference of the artifact that is being
277 // verified against to. It must be a full reference.
278 ArtifactReference string
279
280 // SignatureMediaType is the envelope type of the signature.
281 // Currently only `application/jose+json` and `application/cose` are
282 // supported.
283 SignatureMediaType string
284
285 // PluginConfig is a map of plugin configs.
286 PluginConfig map[string]string
287
288 // UserMetadata contains key-value pairs that must be present in the
289 // signature.
290 UserMetadata map[string]string
291 }
292
293 // Verifier is a interface for verifying an OCI artifact.
294 type Verifier interface {
295 // Verify verifies the `signature` associated with the target OCI artifact
296 //with manifest descriptor `desc`, and returns the outcome upon
297 // successful verification.
298 // If nil signature is present and the verification level is not 'skip',
299 // an error will be returned.
300 Verify(ctx context.Context, desc ocispec.Descriptor, signature []byte, opts VerifierVerifyOptions) (*VerificationOutcome, error)
301 }
302
303 type verifySkipper interface {
304 // SkipVerify validates whether the verification level is skip.
305 SkipVerify(ctx context.Context, opts VerifierVerifyOptions) (bool, *trustpolicy.VerificationLevel, error)
306 }
307
308 // VerifyOptions contains parameters for notation.Verify.
309 type VerifyOptions struct {
310 // ArtifactReference is the reference of the artifact that is being
311 // verified against to.
312 ArtifactReference string
313
314 // PluginConfig is a map of plugin configs.
315 PluginConfig map[string]string
316
317 // MaxSignatureAttempts is the maximum number of signature envelopes that
318 // will be processed for verification. If set to less than or equals
319 // to zero, an error will be returned.
320 MaxSignatureAttempts int
321
322 // UserMetadata contains key-value pairs that must be present in the
323 // signature
324 UserMetadata map[string]string
325 }
326
327 // Verify performs signature verification on each of the notation supported
328 // verification types (like integrity, authenticity, etc.) and return the
329 // successful signature verification outcome.
330 // For more details on signature verification, see
331 // https://github.com/notaryproject/notaryproject/blob/main/specs/trust-store-trust-policy.md#signature-verification
332 func Verify(ctx context.Context, verifier Verifier, repo registry.Repository, verifyOpts VerifyOptions) (ocispec.Descriptor, []*VerificationOutcome, error) {
333 logger := log.GetLogger(ctx)
334
335 // sanity check
336 if verifier == nil {
337 return ocispec.Descriptor{}, nil, errors.New("verifier cannot be nil")
338 }
339 if repo == nil {
340 return ocispec.Descriptor{}, nil, errors.New("repo cannot be nil")
341 }
342 if verifyOpts.MaxSignatureAttempts <= 0 {
343 return ocispec.Descriptor{}, nil, ErrorSignatureRetrievalFailed{Msg: fmt.Sprintf("verifyOptions.MaxSignatureAttempts expects a positive number, got %d", verifyOpts.MaxSignatureAttempts)}
344 }
345
346 // opts to be passed in verifier.Verify()
347 opts := VerifierVerifyOptions{
348 ArtifactReference: verifyOpts.ArtifactReference,
349 PluginConfig: verifyOpts.PluginConfig,
350 UserMetadata: verifyOpts.UserMetadata,
351 }
352
353 if skipChecker, ok := verifier.(verifySkipper); ok {
354 logger.Info("Checking whether signature verification should be skipped or not")
355 skip, verificationLevel, err := skipChecker.SkipVerify(ctx, opts)
356 if err != nil {
357 return ocispec.Descriptor{}, nil, err
358 }
359 if skip {
360 logger.Infoln("Signature verification skipped for", verifyOpts.ArtifactReference)
361 return ocispec.Descriptor{}, []*VerificationOutcome{{VerificationLevel: verificationLevel}}, nil
362 }
363 logger.Info("Check over. The signature verification level is not set to 'skip' in the trust policy.")
364 }
365
366 // get artifact descriptor
367 artifactRef := verifyOpts.ArtifactReference
368 ref, err := orasRegistry.ParseReference(artifactRef)
369 if err != nil {
370 return ocispec.Descriptor{}, nil, ErrorSignatureRetrievalFailed{Msg: err.Error()}
371 }
372 if ref.Reference == "" {
373 return ocispec.Descriptor{}, nil, ErrorSignatureRetrievalFailed{Msg: "reference is missing digest or tag"}
374 }
375 artifactDescriptor, err := repo.Resolve(ctx, ref.Reference)
376 if err != nil {
377 return ocispec.Descriptor{}, nil, ErrorSignatureRetrievalFailed{Msg: err.Error()}
378 }
379 if ref.ValidateReferenceAsDigest() != nil {
380 // artifactRef is not a digest reference
381 logger.Infof("Resolved artifact tag `%s` to digest `%v` before verification", ref.Reference, artifactDescriptor.Digest)
382 logger.Warn("The resolved digest may not point to the same signed artifact, since tags are mutable")
383 } else if ref.Reference != artifactDescriptor.Digest.String() {
384 return ocispec.Descriptor{}, nil, ErrorSignatureRetrievalFailed{Msg: fmt.Sprintf("user input digest %s does not match the resolved digest %s", ref.Reference, artifactDescriptor.Digest.String())}
385 }
386
387 var verificationSucceeded bool
388 var verificationOutcomes []*VerificationOutcome
389 var verificationFailedErrorArray = []error{ErrorVerificationFailed{}}
390 errExceededMaxVerificationLimit := ErrorVerificationFailed{Msg: fmt.Sprintf("signature evaluation stopped. The configured limit of %d signatures to verify per artifact exceeded", verifyOpts.MaxSignatureAttempts)}
391 numOfSignatureProcessed := 0
392
393 // get signature manifests
394 logger.Debug("Fetching signature manifests")
395 err = repo.ListSignatures(ctx, artifactDescriptor, func(signatureManifests []ocispec.Descriptor) error {
396 // process signatures
397 for _, sigManifestDesc := range signatureManifests {
398 if numOfSignatureProcessed >= verifyOpts.MaxSignatureAttempts {
399 break
400 }
401 numOfSignatureProcessed++
402 logger.Infof("Processing signature with manifest mediaType: %v and digest: %v", sigManifestDesc.MediaType, sigManifestDesc.Digest)
403 // get signature envelope
404 sigBlob, sigDesc, err := repo.FetchSignatureBlob(ctx, sigManifestDesc)
405 if err != nil {
406 return ErrorSignatureRetrievalFailed{Msg: fmt.Sprintf("unable to retrieve digital signature with digest %q associated with %q from the Repository, error : %v", sigManifestDesc.Digest, artifactRef, err.Error())}
407 }
408
409 // using signature media type fetched from registry
410 opts.SignatureMediaType = sigDesc.MediaType
411
412 // verify each signature
413 outcome, err := verifier.Verify(ctx, artifactDescriptor, sigBlob, opts)
414 if err != nil {
415 logger.Warnf("Signature %v failed verification with error: %v", sigManifestDesc.Digest, err)
416 if outcome == nil {
417 logger.Error("Got nil outcome. Expecting non-nil outcome on verification failure")
418 return err
419 }
420 outcome.Error = fmt.Errorf("failed to verify signature with digest %v, %w", sigManifestDesc.Digest, outcome.Error)
421 verificationFailedErrorArray = append(verificationFailedErrorArray, outcome.Error)
422 continue
423 }
424 // at this point, the signature is verified successfully
425 verificationSucceeded = true
426 // on success, verificationOutcomes only contains the
427 // succeeded outcome
428 verificationOutcomes = []*VerificationOutcome{outcome}
429 logger.Debugf("Signature verification succeeded for artifact %v with signature digest %v", artifactDescriptor.Digest, sigManifestDesc.Digest)
430
431 // early break on success
432 return errDoneVerification
433 }
434
435 if numOfSignatureProcessed >= verifyOpts.MaxSignatureAttempts {
436 return errExceededMaxVerificationLimit
437 }
438
439 return nil
440 })
441
442 if err != nil && !errors.Is(err, errDoneVerification) {
443 if errors.Is(err, errExceededMaxVerificationLimit) {
444 return ocispec.Descriptor{}, verificationOutcomes, err
445 }
446 return ocispec.Descriptor{}, nil, err
447 }
448
449 // If there's no signature associated with the reference
450 if numOfSignatureProcessed == 0 {
451 return ocispec.Descriptor{}, nil, ErrorSignatureRetrievalFailed{Msg: fmt.Sprintf("no signature is associated with %q, make sure the artifact was signed successfully", artifactRef)}
452 }
453
454 // Verification Failed
455 if !verificationSucceeded {
456 logger.Debugf("Signature verification failed for all the signatures associated with artifact %v", artifactDescriptor.Digest)
457 return ocispec.Descriptor{}, verificationOutcomes, errors.Join(verificationFailedErrorArray...)
458 }
459
460 // Verification Succeeded
461 return artifactDescriptor, verificationOutcomes, nil
462 }
463
464 func generateAnnotations(signerInfo *signature.SignerInfo, annotations map[string]string) (map[string]string, error) {
465 // sanity check
466 if signerInfo == nil {
467 return nil, errors.New("failed to generate annotations: signerInfo cannot be nil")
468 }
469 var thumbprints []string
470 for _, cert := range signerInfo.CertificateChain {
471 checkSum := sha256.Sum256(cert.Raw)
472 thumbprints = append(thumbprints, hex.EncodeToString(checkSum[:]))
473 }
474 val, err := json.Marshal(thumbprints)
475 if err != nil {
476 return nil, err
477 }
478 if annotations == nil {
479 annotations = make(map[string]string)
480 }
481 annotations[envelope.AnnotationX509ChainThumbprint] = string(val)
482 signingTime, err := envelope.SigningTime(signerInfo)
483 if err != nil {
484 return nil, err
485 }
486 annotations[ocispec.AnnotationCreated] = signingTime.Format(time.RFC3339)
487 return annotations, nil
488 }
489
490 func validateSigMediaType(sigMediaType string) error {
491 if !(sigMediaType == jws.MediaTypeEnvelope || sigMediaType == cose.MediaTypeEnvelope) {
492 return fmt.Errorf("invalid signature media-type %q", sigMediaType)
493 }
494 return nil
495 }