2022-09-05 03:06:08 -04:00
|
|
|
/*
|
|
|
|
Copyright (c) Edgeless Systems GmbH
|
|
|
|
|
|
|
|
SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
*/
|
|
|
|
|
2022-08-01 03:37:05 -04:00
|
|
|
package sigstore
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"crypto"
|
|
|
|
"encoding/base64"
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/sigstore/sigstore/pkg/cryptoutils"
|
|
|
|
sigsig "github.com/sigstore/sigstore/pkg/signature"
|
|
|
|
)
|
|
|
|
|
2023-06-09 06:48:12 -04:00
|
|
|
// Verifier checks if the signature of content can be verified.
|
|
|
|
type Verifier interface {
|
2023-08-01 10:48:13 -04:00
|
|
|
VerifySignature(content, signature []byte) error
|
2023-06-09 06:48:12 -04:00
|
|
|
}
|
|
|
|
|
2023-08-01 10:48:13 -04:00
|
|
|
// CosignVerifier wraps a public key that can be used for verifying signatures.
|
|
|
|
type CosignVerifier struct {
|
|
|
|
publicKey crypto.PublicKey
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewCosignVerifier unmarshalls and validates the given pem encoded public key and returns a new CosignVerifier.
|
|
|
|
func NewCosignVerifier(pem []byte) (Verifier, error) {
|
|
|
|
pubkey, err := cryptoutils.UnmarshalPEMToPublicKey(pem)
|
|
|
|
if err != nil {
|
|
|
|
return CosignVerifier{}, fmt.Errorf("unable to parse public key: %w", err)
|
|
|
|
}
|
|
|
|
if err := cryptoutils.ValidatePubKey(pubkey); err != nil {
|
|
|
|
return CosignVerifier{}, fmt.Errorf("unable to validate public key: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return CosignVerifier{pubkey}, nil
|
|
|
|
}
|
2023-05-26 11:49:46 -04:00
|
|
|
|
2022-08-01 03:37:05 -04:00
|
|
|
// VerifySignature checks if the signature of content can be verified
|
|
|
|
// using publicKey.
|
|
|
|
// signature is expected to be base64 encoded.
|
|
|
|
// publicKey is expected to be PEM encoded.
|
2023-08-01 10:48:13 -04:00
|
|
|
func (c CosignVerifier) VerifySignature(content, signature []byte) error {
|
|
|
|
// LoadVerifier would also error if no public key is set.
|
|
|
|
// However, this error message should be easier to debug.
|
|
|
|
if c.publicKey == nil {
|
|
|
|
return fmt.Errorf("no public key set")
|
2022-08-01 03:37:05 -04:00
|
|
|
}
|
|
|
|
|
2023-08-01 10:48:13 -04:00
|
|
|
sigRaw := base64.NewDecoder(base64.StdEncoding, bytes.NewReader(signature))
|
|
|
|
|
|
|
|
verifier, err := sigsig.LoadVerifier(c.publicKey, crypto.SHA256)
|
2022-08-01 03:37:05 -04:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("unable to load verifier: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := verifier.VerifySignature(sigRaw, bytes.NewReader(content)); err != nil {
|
|
|
|
return fmt.Errorf("unable to verify signature: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|