From 20a2db9e342955ee313c4fe47cb94f9f991990f9 Mon Sep 17 00:00:00 2001 From: Riccardo Schirone <562321+ret2libc@users.noreply.github.com> Date: Mon, 29 Jan 2024 20:55:56 +0100 Subject: [PATCH] Add support for Ed25519ph Signer/Verifier (#1595) * Added ED25519 pre-hashed Signer/Verifier Signed-off-by: Riccardo Schirone * Add LoadSigner/Verifier WithOpts functions for more flexibility Before this commit, the Signer/Verifier to load was determined exclusively by the public/private key type, however there may be multiple Signers/Verifiers available, like in the case of RSA and ED25519. This commit adds LoadVerifierWithOpts, LoadSignerWithOpts, and LoadSignerVerifierWithOpts to give clients more flexibility, allowing the user of the API to choose between the available options by using options. Signed-off-by: Riccardo Schirone * Move signerverifier_options back into signature pkg Signed-off-by: Riccardo Schirone * Moved LoadOption into pkg/signature/options Signed-off-by: Riccardo Schirone --------- Signed-off-by: Riccardo Schirone --- pkg/signature/ed25519ph.go | 201 +++++++++++++++++++++++++++ pkg/signature/ed25519ph_test.go | 88 ++++++++++++ pkg/signature/options.go | 8 ++ pkg/signature/options/loadoptions.go | 76 ++++++++++ pkg/signature/options/noop.go | 10 ++ pkg/signature/signer.go | 36 +++++ pkg/signature/signer_test.go | 80 +++++++++++ pkg/signature/signerverifier.go | 36 +++++ pkg/signature/signerverifier_test.go | 55 ++++++++ pkg/signature/sv_test.go | 36 ++--- pkg/signature/verifier.go | 38 +++++ pkg/signature/verifier_test.go | 16 +++ 12 files changed, 664 insertions(+), 16 deletions(-) create mode 100644 pkg/signature/ed25519ph.go create mode 100644 pkg/signature/ed25519ph_test.go create mode 100644 pkg/signature/options/loadoptions.go create mode 100644 pkg/signature/signer_test.go create mode 100644 pkg/signature/signerverifier_test.go diff --git a/pkg/signature/ed25519ph.go b/pkg/signature/ed25519ph.go new file mode 100644 index 000000000..c79ed6a2e --- /dev/null +++ b/pkg/signature/ed25519ph.go @@ -0,0 +1,201 @@ +// +// Copyright 2024 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 signature + +import ( + "crypto" + "crypto/ed25519" + "crypto/rand" + "errors" + "fmt" + "io" + + "github.com/sigstore/sigstore/pkg/signature/options" +) + +var ed25519phSupportedHashFuncs = []crypto.Hash{ + crypto.SHA512, +} + +// ED25519phSigner is a signature.Signer that uses the Ed25519 public-key signature system with pre-hashing +type ED25519phSigner struct { + priv ed25519.PrivateKey +} + +// LoadED25519phSigner calculates signatures using the specified private key. +func LoadED25519phSigner(priv ed25519.PrivateKey) (*ED25519phSigner, error) { + if priv == nil { + return nil, errors.New("invalid ED25519 private key specified") + } + + return &ED25519phSigner{ + priv: priv, + }, nil +} + +// SignMessage signs the provided message. If the message is provided, +// this method will compute the digest according to the hash function specified +// when the ED25519phSigner was created. +// +// This function recognizes the following Options listed in order of preference: +// +// - WithDigest() +// +// All other options are ignored if specified. +func (e ED25519phSigner) SignMessage(message io.Reader, opts ...SignOption) ([]byte, error) { + digest, _, err := ComputeDigestForSigning(message, crypto.SHA512, ed25519phSupportedHashFuncs, opts...) + if err != nil { + return nil, err + } + + return e.priv.Sign(nil, digest, crypto.SHA512) +} + +// Public returns the public key that can be used to verify signatures created by +// this signer. +func (e ED25519phSigner) Public() crypto.PublicKey { + if e.priv == nil { + return nil + } + + return e.priv.Public() +} + +// PublicKey returns the public key that can be used to verify signatures created by +// this signer. As this value is held in memory, all options provided in arguments +// to this method are ignored. +func (e ED25519phSigner) PublicKey(_ ...PublicKeyOption) (crypto.PublicKey, error) { + return e.Public(), nil +} + +// Sign computes the signature for the specified message; the first and third arguments to this +// function are ignored as they are not used by the ED25519ph algorithm. +func (e ED25519phSigner) Sign(_ io.Reader, digest []byte, _ crypto.SignerOpts) ([]byte, error) { + return e.SignMessage(nil, options.WithDigest(digest)) +} + +// ED25519phVerifier is a signature.Verifier that uses the Ed25519 public-key signature system +type ED25519phVerifier struct { + publicKey ed25519.PublicKey +} + +// LoadED25519phVerifier returns a Verifier that verifies signatures using the +// specified ED25519 public key. +func LoadED25519phVerifier(pub ed25519.PublicKey) (*ED25519phVerifier, error) { + if pub == nil { + return nil, errors.New("invalid ED25519 public key specified") + } + + return &ED25519phVerifier{ + publicKey: pub, + }, nil +} + +// PublicKey returns the public key that is used to verify signatures by +// this verifier. As this value is held in memory, all options provided in arguments +// to this method are ignored. +func (e *ED25519phVerifier) PublicKey(_ ...PublicKeyOption) (crypto.PublicKey, error) { + return e.publicKey, nil +} + +// VerifySignature verifies the signature for the given message. Unless provided +// in an option, the digest of the message will be computed using the hash function specified +// when the ED25519phVerifier was created. +// +// This function returns nil if the verification succeeded, and an error message otherwise. +// +// This function recognizes the following Options listed in order of preference: +// +// - WithDigest() +// +// All other options are ignored if specified. +func (e *ED25519phVerifier) VerifySignature(signature, message io.Reader, opts ...VerifyOption) error { + if signature == nil { + return errors.New("nil signature passed to VerifySignature") + } + + digest, _, err := ComputeDigestForVerifying(message, crypto.SHA512, ed25519phSupportedHashFuncs, opts...) + if err != nil { + return err + } + + sigBytes, err := io.ReadAll(signature) + if err != nil { + return fmt.Errorf("reading signature: %w", err) + } + + if err := ed25519.VerifyWithOptions(e.publicKey, digest, sigBytes, &ed25519.Options{Hash: crypto.SHA512}); err != nil { + return fmt.Errorf("failed to verify signature: %w", err) + } + return nil +} + +// ED25519phSignerVerifier is a signature.SignerVerifier that uses the Ed25519 public-key signature system +type ED25519phSignerVerifier struct { + *ED25519phSigner + *ED25519phVerifier +} + +// LoadED25519phSignerVerifier creates a combined signer and verifier. This is +// a convenience object that simply wraps an instance of ED25519phSigner and ED25519phVerifier. +func LoadED25519phSignerVerifier(priv ed25519.PrivateKey) (*ED25519phSignerVerifier, error) { + signer, err := LoadED25519phSigner(priv) + if err != nil { + return nil, fmt.Errorf("initializing signer: %w", err) + } + pub, ok := priv.Public().(ed25519.PublicKey) + if !ok { + return nil, fmt.Errorf("given key is not ed25519.PublicKey") + } + verifier, err := LoadED25519phVerifier(pub) + if err != nil { + return nil, fmt.Errorf("initializing verifier: %w", err) + } + + return &ED25519phSignerVerifier{ + ED25519phSigner: signer, + ED25519phVerifier: verifier, + }, nil +} + +// NewDefaultED25519phSignerVerifier creates a combined signer and verifier using ED25519. +// This creates a new ED25519 key using crypto/rand as an entropy source. +func NewDefaultED25519phSignerVerifier() (*ED25519phSignerVerifier, ed25519.PrivateKey, error) { + return NewED25519phSignerVerifier(rand.Reader) +} + +// NewED25519phSignerVerifier creates a combined signer and verifier using ED25519. +// This creates a new ED25519 key using the specified entropy source. +func NewED25519phSignerVerifier(rand io.Reader) (*ED25519phSignerVerifier, ed25519.PrivateKey, error) { + _, priv, err := ed25519.GenerateKey(rand) + if err != nil { + return nil, nil, err + } + + sv, err := LoadED25519phSignerVerifier(priv) + if err != nil { + return nil, nil, err + } + + return sv, priv, nil +} + +// PublicKey returns the public key that is used to verify signatures by +// this verifier. As this value is held in memory, all options provided in arguments +// to this method are ignored. +func (e ED25519phSignerVerifier) PublicKey(_ ...PublicKeyOption) (crypto.PublicKey, error) { + return e.publicKey, nil +} diff --git a/pkg/signature/ed25519ph_test.go b/pkg/signature/ed25519ph_test.go new file mode 100644 index 000000000..046d068c1 --- /dev/null +++ b/pkg/signature/ed25519ph_test.go @@ -0,0 +1,88 @@ +// +// Copyright 2024 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 signature + +import ( + "crypto" + "crypto/ed25519" + "encoding/base64" + "testing" + + "github.com/sigstore/sigstore/pkg/cryptoutils" +) + +// Generated with: +// openssl genpkey -algorithm ed25519 -outform PEM -out - +const ed25519phPriv = `-----BEGIN PRIVATE KEY----- +MC4CAQAwBQYDK2VwBCIEIFP9CZb6J1DiOLfdIkPfy1bwBOCjEG6KR/cIdhw90J1H +-----END PRIVATE KEY-----` + +// Extracted from above with: +// openssl ec -in ec_private.pem -pubout +const ed25519phPub = `-----BEGIN PUBLIC KEY----- +MCowBQYDK2VwAyEA9wy4umF4RHQ8UQXo8fzEQNBWE4GsBMkCzQPAfHvkf/s= +-----END PUBLIC KEY-----` + +func TestED25519phSignerVerifier(t *testing.T) { + privateKey, err := cryptoutils.UnmarshalPEMToPrivateKey([]byte(ed25519phPriv), cryptoutils.SkipPassword) + if err != nil { + t.Fatalf("unexpected error unmarshalling public key: %v", err) + } + edPriv, ok := privateKey.(ed25519.PrivateKey) + if !ok { + t.Fatalf("expected ed25519.PrivateKey") + } + + sv, err := LoadED25519phSignerVerifier(edPriv) + if err != nil { + t.Fatalf("unexpected error creating signer/verifier: %v", err) + } + + message := []byte("sign me") + sig, _ := base64.StdEncoding.DecodeString("9D4pA8jutZnbqKy4fFRl+kDsVUCO50qrOD1lxmsiUFk6NX+7OXUK5BCMkE2KYPRDxjkDFBzbDZEQhaFdDV5tDg==") + testingSigner(t, sv, "ed25519ph", crypto.SHA512, message) + testingVerifier(t, sv, "ed25519ph", crypto.SHA512, sig, message) + pub, err := sv.PublicKey() + if err != nil { + t.Fatalf("unexpected error from PublicKey(): %v", err) + } + assertPublicKeyIsx509Marshalable(t, pub) +} + +func TestED25519phVerifier(t *testing.T) { + publicKey, err := cryptoutils.UnmarshalPEMToPublicKey([]byte(ed25519phPub)) + if err != nil { + t.Fatalf("unexpected error unmarshalling public key: %v", err) + } + edPub, ok := publicKey.(ed25519.PublicKey) + if !ok { + t.Fatalf("public key is not ed25519") + } + + v, err := LoadED25519phVerifier(edPub) + if err != nil { + t.Fatalf("unexpected error creating verifier: %v", err) + } + + message := []byte("sign me") + sig, _ := base64.StdEncoding.DecodeString("9D4pA8jutZnbqKy4fFRl+kDsVUCO50qrOD1lxmsiUFk6NX+7OXUK5BCMkE2KYPRDxjkDFBzbDZEQhaFdDV5tDg==") + testingVerifier(t, v, "ed25519ph", crypto.SHA512, sig, message) + pub, err := v.PublicKey() + if err != nil { + t.Fatalf("unexpected error from PublicKey(): %v", err) + } + assertPublicKeyIsx509Marshalable(t, pub) +} diff --git a/pkg/signature/options.go b/pkg/signature/options.go index 0be699f7e..e17e768c2 100644 --- a/pkg/signature/options.go +++ b/pkg/signature/options.go @@ -18,6 +18,7 @@ package signature import ( "context" "crypto" + "crypto/rsa" "io" "github.com/sigstore/sigstore/pkg/signature/options" @@ -55,3 +56,10 @@ type VerifyOption interface { RPCOption MessageOption } + +// LoadOption specifies options to be used when creating a Signer/Verifier +type LoadOption interface { + ApplyHash(*crypto.Hash) + ApplyED25519ph(*bool) + ApplyRSAPSS(**rsa.PSSOptions) +} diff --git a/pkg/signature/options/loadoptions.go b/pkg/signature/options/loadoptions.go new file mode 100644 index 000000000..e5f3f0116 --- /dev/null +++ b/pkg/signature/options/loadoptions.go @@ -0,0 +1,76 @@ +// +// Copyright 2024 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 options + +import ( + "crypto" + "crypto/rsa" +) + +// RequestHash implements the functional option pattern for setting a Hash +// function when loading a signer or verifier +type RequestHash struct { + NoOpOptionImpl + hashFunc crypto.Hash +} + +// ApplyHash sets the hash as requested by the functional option +func (r RequestHash) ApplyHash(hash *crypto.Hash) { + *hash = r.hashFunc +} + +// WithHash specifies that the given hash function should be used when loading a signer or verifier +func WithHash(hash crypto.Hash) RequestHash { + return RequestHash{hashFunc: hash} +} + +// RequestED25519ph implements the functional option pattern for specifying +// ED25519ph (pre-hashed) should be used when loading a signer or verifier and a +// ED25519 key is +type RequestED25519ph struct { + NoOpOptionImpl + useED25519ph bool +} + +// ApplyED25519ph sets the ED25519ph flag as requested by the functional option +func (r RequestED25519ph) ApplyED25519ph(useED25519ph *bool) { + *useED25519ph = r.useED25519ph +} + +// WithED25519ph specifies that the ED25519ph algorithm should be used when a ED25519 key is used +func WithED25519ph() RequestED25519ph { + return RequestED25519ph{useED25519ph: true} +} + +// RequestPSSOptions implements the functional option pattern for specifying RSA +// PSS should be used when loading a signer or verifier and a RSA key is +// detected +type RequestPSSOptions struct { + NoOpOptionImpl + opts *rsa.PSSOptions +} + +// ApplyRSAPSS sets the RSAPSS options as requested by the functional option +func (r RequestPSSOptions) ApplyRSAPSS(opts **rsa.PSSOptions) { + *opts = r.opts +} + +// WithRSAPSS specifies that the RSAPSS algorithm should be used when a RSA key is used +// Note that the RSA PSSOptions contains an hash algorithm, which will override +// the hash function specified with WithHash. +func WithRSAPSS(opts *rsa.PSSOptions) RequestPSSOptions { + return RequestPSSOptions{opts: opts} +} diff --git a/pkg/signature/options/noop.go b/pkg/signature/options/noop.go index c7f1ccb91..0c0e51856 100644 --- a/pkg/signature/options/noop.go +++ b/pkg/signature/options/noop.go @@ -18,6 +18,7 @@ package options import ( "context" "crypto" + "crypto/rsa" "io" ) @@ -47,3 +48,12 @@ func (NoOpOptionImpl) ApplyKeyVersion(_ *string) {} // ApplyKeyVersionUsed is a no-op required to fully implement the requisite interfaces func (NoOpOptionImpl) ApplyKeyVersionUsed(_ **string) {} + +// ApplyHash is a no-op required to fully implement the requisite interfaces +func (NoOpOptionImpl) ApplyHash(_ *crypto.Hash) {} + +// ApplyED25519ph is a no-op required to fully implement the requisite interfaces +func (NoOpOptionImpl) ApplyED25519ph(_ *bool) {} + +// ApplyRSAPSS is a no-op required to fully implement the requisite interfaces +func (NoOpOptionImpl) ApplyRSAPSS(_ **rsa.PSSOptions) {} diff --git a/pkg/signature/signer.go b/pkg/signature/signer.go index 3bd3823cb..e26def9fa 100644 --- a/pkg/signature/signer.go +++ b/pkg/signature/signer.go @@ -30,6 +30,7 @@ import ( _ "crypto/sha512" "github.com/sigstore/sigstore/pkg/cryptoutils" + "github.com/sigstore/sigstore/pkg/signature/options" // these ensure we have the implementations loaded _ "golang.org/x/crypto/sha3" @@ -59,12 +60,33 @@ func (s SignerOpts) HashFunc() crypto.Hash { // If privateKey is an RSA key, a RSAPKCS1v15Signer will be returned. If a // RSAPSSSigner is desired instead, use the LoadRSAPSSSigner() method directly. func LoadSigner(privateKey crypto.PrivateKey, hashFunc crypto.Hash) (Signer, error) { + return LoadSignerWithOpts(privateKey, options.WithHash(hashFunc)) +} + +// LoadSignerWithOpts returns a signature.Signer based on the algorithm of the private key +// provided. +func LoadSignerWithOpts(privateKey crypto.PrivateKey, opts ...LoadOption) (Signer, error) { + var rsaPSSOptions *rsa.PSSOptions + var useED25519ph bool + hashFunc := crypto.SHA256 + for _, o := range opts { + o.ApplyED25519ph(&useED25519ph) + o.ApplyHash(&hashFunc) + o.ApplyRSAPSS(&rsaPSSOptions) + } + switch pk := privateKey.(type) { case *rsa.PrivateKey: + if rsaPSSOptions != nil { + return LoadRSAPSSSigner(pk, hashFunc, rsaPSSOptions) + } return LoadRSAPKCS1v15Signer(pk, hashFunc) case *ecdsa.PrivateKey: return LoadECDSASigner(pk, hashFunc) case ed25519.PrivateKey: + if useED25519ph { + return LoadED25519phSigner(pk) + } return LoadED25519Signer(pk) } return nil, errors.New("unsupported public key type") @@ -87,3 +109,17 @@ func LoadSignerFromPEMFile(path string, hashFunc crypto.Hash, pf cryptoutils.Pas } return LoadSigner(priv, hashFunc) } + +// LoadSignerFromPEMFileWithOpts returns a signature.Signer based on the algorithm of the private key +// in the file. The Signer will use the hash function specified in the options when computing digests. +func LoadSignerFromPEMFileWithOpts(path string, pf cryptoutils.PassFunc, opts ...LoadOption) (Signer, error) { + fileBytes, err := os.ReadFile(filepath.Clean(path)) + if err != nil { + return nil, err + } + priv, err := cryptoutils.UnmarshalPEMToPrivateKey(fileBytes, pf) + if err != nil { + return nil, err + } + return LoadSignerWithOpts(priv, opts...) +} diff --git a/pkg/signature/signer_test.go b/pkg/signature/signer_test.go new file mode 100644 index 000000000..ee4b660dc --- /dev/null +++ b/pkg/signature/signer_test.go @@ -0,0 +1,80 @@ +// Copyright 2024 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 signature + +import ( + "bytes" + "crypto" + "crypto/ed25519" + "encoding/base64" + "testing" + + "github.com/sigstore/sigstore/pkg/cryptoutils" + "github.com/sigstore/sigstore/pkg/signature/options" +) + +func TestLoadEd25519Signer(t *testing.T) { + privateKey, err := cryptoutils.UnmarshalPEMToPrivateKey([]byte(ed25519Priv), cryptoutils.SkipPassword) + if err != nil { + t.Fatalf("unexpected error unmarshalling public key: %v", err) + } + edPriv, ok := privateKey.(ed25519.PrivateKey) + if !ok { + t.Fatalf("expected ed25519.PrivateKey") + } + + signer, err := LoadSigner(edPriv, crypto.SHA256) + if err != nil { + t.Fatalf("unexpected error loading verifier: %v", err) + } + + msg := []byte("sign me") + sig, err := signer.SignMessage(bytes.NewReader(msg)) + if err != nil { + t.Fatalf("unexpected error signing message: %v", err) + } + + expectedSig, _ := base64.StdEncoding.DecodeString("cnafwd8DKq2nQ564eN66ckYV8anVFGFi5vaYiQg2aal7ej/J0/OE0PPdKHLHe9wdzWRMFy5MpurRD/2cGXGLBQ==") + if !bytes.Equal(sig, expectedSig) { + t.Fatalf("signature was not as expected") + } +} + +func TestLoadEd25519phSigner(t *testing.T) { + privateKey, err := cryptoutils.UnmarshalPEMToPrivateKey([]byte(ed25519Priv), cryptoutils.SkipPassword) + if err != nil { + t.Fatalf("unexpected error unmarshalling public key: %v", err) + } + edPriv, ok := privateKey.(ed25519.PrivateKey) + if !ok { + t.Fatalf("expected ed25519.PrivateKey") + } + + signer, err := LoadSignerWithOpts(edPriv, options.WithED25519ph(), options.WithHash(crypto.SHA512)) + if err != nil { + t.Fatalf("unexpected error loading verifier: %v", err) + } + + msg := []byte("sign me") + sig, err := signer.SignMessage(bytes.NewReader(msg)) + if err != nil { + t.Fatalf("unexpected error signing message: %v", err) + } + + expectedSig, _ := base64.StdEncoding.DecodeString("9D4pA8jutZnbqKy4fFRl+kDsVUCO50qrOD1lxmsiUFk6NX+7OXUK5BCMkE2KYPRDxjkDFBzbDZEQhaFdDV5tDg==") + if !bytes.Equal(sig, expectedSig) { + t.Fatalf("signature was not as expected") + } +} diff --git a/pkg/signature/signerverifier.go b/pkg/signature/signerverifier.go index 90667f2a8..70253b121 100644 --- a/pkg/signature/signerverifier.go +++ b/pkg/signature/signerverifier.go @@ -25,6 +25,7 @@ import ( "path/filepath" "github.com/sigstore/sigstore/pkg/cryptoutils" + "github.com/sigstore/sigstore/pkg/signature/options" ) // SignerVerifier creates and verifies digital signatures over a message using a specified key pair @@ -39,12 +40,33 @@ type SignerVerifier interface { // If privateKey is an RSA key, a RSAPKCS1v15SignerVerifier will be returned. If a // RSAPSSSignerVerifier is desired instead, use the LoadRSAPSSSignerVerifier() method directly. func LoadSignerVerifier(privateKey crypto.PrivateKey, hashFunc crypto.Hash) (SignerVerifier, error) { + return LoadSignerVerifierWithOpts(privateKey, options.WithHash(hashFunc)) +} + +// LoadSignerVerifierWithOpts returns a signature.SignerVerifier based on the +// algorithm of the private key provided and the user's choice. +func LoadSignerVerifierWithOpts(privateKey crypto.PrivateKey, opts ...LoadOption) (SignerVerifier, error) { + var rsaPSSOptions *rsa.PSSOptions + var useED25519ph bool + hashFunc := crypto.SHA256 + for _, o := range opts { + o.ApplyED25519ph(&useED25519ph) + o.ApplyHash(&hashFunc) + o.ApplyRSAPSS(&rsaPSSOptions) + } + switch pk := privateKey.(type) { case *rsa.PrivateKey: + if rsaPSSOptions != nil { + return LoadRSAPSSSignerVerifier(pk, hashFunc, rsaPSSOptions) + } return LoadRSAPKCS1v15SignerVerifier(pk, hashFunc) case *ecdsa.PrivateKey: return LoadECDSASignerVerifier(pk, hashFunc) case ed25519.PrivateKey: + if useED25519ph { + return LoadED25519phSignerVerifier(pk) + } return LoadED25519SignerVerifier(pk) } return nil, errors.New("unsupported public key type") @@ -67,3 +89,17 @@ func LoadSignerVerifierFromPEMFile(path string, hashFunc crypto.Hash, pf cryptou } return LoadSignerVerifier(priv, hashFunc) } + +// LoadSignerVerifierFromPEMFileWithOpts returns a signature.SignerVerifier based on the algorithm of the private key +// in the file. The SignerVerifier will use the hash function specified in the options when computing digests. +func LoadSignerVerifierFromPEMFileWithOpts(path string, pf cryptoutils.PassFunc, opts ...LoadOption) (SignerVerifier, error) { + fileBytes, err := os.ReadFile(filepath.Clean(path)) + if err != nil { + return nil, err + } + priv, err := cryptoutils.UnmarshalPEMToPrivateKey(fileBytes, pf) + if err != nil { + return nil, err + } + return LoadSignerVerifierWithOpts(priv, opts...) +} diff --git a/pkg/signature/signerverifier_test.go b/pkg/signature/signerverifier_test.go new file mode 100644 index 000000000..c6acb2fd9 --- /dev/null +++ b/pkg/signature/signerverifier_test.go @@ -0,0 +1,55 @@ +// Copyright 2024 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 signature + +import ( + "bytes" + "crypto" + "crypto/rsa" + "encoding/base64" + "testing" + + "github.com/sigstore/sigstore/pkg/cryptoutils" + "github.com/sigstore/sigstore/pkg/signature/options" +) + +func TestLoadRSAPSSSignerVerifier(t *testing.T) { + opts := &rsa.PSSOptions{ + Hash: crypto.SHA256, + } + + privateKey, err := cryptoutils.UnmarshalPEMToPrivateKey([]byte(rsaKey), cryptoutils.SkipPassword) + if err != nil { + t.Errorf("unexpected error unmarshalling private key: %v", err) + } + sv, err := LoadSignerVerifierWithOpts(privateKey, options.WithHash(crypto.SHA256), options.WithED25519ph(), options.WithRSAPSS(opts)) + if err != nil { + t.Errorf("unexpected error creating signer/verifier: %v", err) + } + + message := []byte("sign me") + sig, err := sv.SignMessage(bytes.NewReader(message)) + if err != nil { + t.Fatalf("unexpected error signing message: %v", err) + } + if err := sv.VerifySignature(bytes.NewReader(sig), bytes.NewReader(message)); err != nil { + t.Fatalf("unexpected error verifying calculated signature: %v", err) + } + + expectedSig, _ := base64.StdEncoding.DecodeString("UyouJxmgAKdm/Qfi9YA7aK71/eqyLcytmDN8CQqSCgcbGSln7S5fgIAmrwUfGp1tcxKjuNjLScn11+fqawiG9y66740VEC6GfS1hgElC2k3i/v8ly2mlt+4JYs3euzYxtWnxwQr4csc7Jy2V2cjoeQm6GTxkR4E6TRJM8/UxXvjKtp3rxRD8OuyfuGFkI0lU48vjKLgbuZKQqQdWuNUOnsPvtrHxvGRY/F1C0Ig3b7SoTyAjWSXQG42faKsFT+W1L/UdRK+m73TYdxMleI4uIGtl0k0Weui1/gK7Uh2FUP5+/F1ZoQRYk/DMz0M4QPmPsYLGwc8oduoF6JvNMGKymg==") + if err := sv.VerifySignature(bytes.NewReader(expectedSig), bytes.NewReader(message)); err != nil { + t.Fatalf("unexpected error verifying expected signature: %v", err) + } +} diff --git a/pkg/signature/sv_test.go b/pkg/signature/sv_test.go index 93799aaf3..719d81c6f 100644 --- a/pkg/signature/sv_test.go +++ b/pkg/signature/sv_test.go @@ -28,14 +28,13 @@ import ( "github.com/sigstore/sigstore/pkg/signature/options" ) -// Per golangci-lint `hashFunc` always receives `crypto.SHA256` func testingSigner(t *testing.T, s Signer, alg string, hashFunc crypto.Hash, message []byte) { // nolint: unparam t.Helper() - isED25519 := alg == "ed25519" + isPreHashed := alg != "ed25519" var digest []byte - if !isED25519 { + if isPreHashed { hasher := hashFunc.New() _, _ = hasher.Write(message) digest = hasher.Sum(nil) @@ -46,7 +45,7 @@ func testingSigner(t *testing.T, s Signer, alg string, hashFunc crypto.Hash, mes } // if nil is passed for rand, default (crypto/rand.Reader) should be used - if _, err := s.SignMessage(bytes.NewReader(message), options.WithRand(nil)); err != nil && !isED25519 { + if _, err := s.SignMessage(bytes.NewReader(message), options.WithRand(nil)); err != nil && isPreHashed { t.Errorf("unexpected error passing nil Rand: %v", err) } @@ -66,15 +65,15 @@ func testingSigner(t *testing.T, s Signer, alg string, hashFunc crypto.Hash, mes t.Errorf("unexpected error passing valid Digest: %v", err) } - if _, err := s.SignMessage(bytes.NewReader(message), options.WithDigest(digest), options.WithCryptoSignerOpts(crypto.Hash(0))); err == nil && !isED25519 { + if _, err := s.SignMessage(bytes.NewReader(message), options.WithDigest(digest), options.WithCryptoSignerOpts(crypto.Hash(0))); err == nil && isPreHashed { t.Error("no error passing invalid opts") } - if _, err := s.SignMessage(bytes.NewReader(message), options.WithDigest(digest), options.WithCryptoSignerOpts(crypto.SHA512)); err == nil && !isED25519 { + if _, err := s.SignMessage(bytes.NewReader(message), options.WithDigest(digest), options.WithCryptoSignerOpts(crypto.SHA384)); err == nil && isPreHashed { t.Error("no error passing mismatched Digest and opts") } - if _, err := s.SignMessage(bytes.NewReader(message), options.WithCryptoSignerOpts(nil)); err != nil { + if _, err := s.SignMessage(bytes.NewReader(message), options.WithCryptoSignerOpts(nil)); err != nil && alg != "ed25519ph" { t.Errorf("unexpected error passing nil options: %v", err) } @@ -87,25 +86,25 @@ func testingSigner(t *testing.T, s Signer, alg string, hashFunc crypto.Hash, mes t.Errorf("no error passing nil for all args to Sign: %v", err) } - if isED25519 { + if !isPreHashed { if _, err := cs.Sign(nil, message, crypto.Hash(0)); err != nil { t.Errorf("unexpected error passing nil Rand, message and crypto.Hash(0) to Sign: %v", err) } } - if _, err := cs.Sign(nil, digest, nil); err != nil && !isED25519 { + if _, err := cs.Sign(nil, digest, nil); err != nil && isPreHashed { t.Errorf("unexpected error passing nil for Rand and Opts to Sign: %v", err) } - if _, err := cs.Sign(nil, digest, &rsa.PSSOptions{Hash: hashFunc}); err != nil && !isED25519 { + if _, err := cs.Sign(nil, digest, &rsa.PSSOptions{Hash: hashFunc}); err != nil && isPreHashed { t.Errorf("unexpected error passing nil for Rand and valid Opts to Sign: %v", err) } - if _, err := cs.Sign(crand.Reader, digest, &rsa.PSSOptions{Hash: hashFunc}); err != nil && !isED25519 { + if _, err := cs.Sign(crand.Reader, digest, &rsa.PSSOptions{Hash: hashFunc}); err != nil && isPreHashed { t.Errorf("unexpected error passing valid Rand and valid Opts to Sign: %v", err) } - if _, err := cs.Sign(crand.Reader, digest, nil); err != nil && !isED25519 { + if _, err := cs.Sign(crand.Reader, digest, nil); err != nil && isPreHashed { t.Errorf("unexpected error passing valid Rand and nil Opts to Sign: %v", err) } @@ -130,14 +129,13 @@ func assertPublicKeyIsx509Marshalable(t *testing.T, pub crypto.PublicKey) { } } -// Per golangci-lint `hashFunc` always receives `crypto.SHA256` func testingVerifier(t *testing.T, v Verifier, alg string, hashFunc crypto.Hash, signature, message []byte) { // nolint: unparam t.Helper() - isED25519 := alg == "ed25519" + isPreHashed := alg != "ed25519" var digest []byte - if !isED25519 { + if isPreHashed { hasher := hashFunc.New() _, _ = hasher.Write(message) digest = hasher.Sum(nil) @@ -167,7 +165,13 @@ func testingVerifier(t *testing.T, v Verifier, alg string, hashFunc crypto.Hash, t.Errorf("unexpected error when using valid bytes.NewReader(message) with digest & opts: %v", err) } - if err := v.VerifySignature(bytes.NewReader(signature), bytes.NewReader(message), options.WithDigest(digest), options.WithCryptoSignerOpts(crypto.SHA512)); err == nil && !isED25519 { + var alternativeHash crypto.Hash + if hashFunc == crypto.SHA512 { + alternativeHash = crypto.SHA256 + } else { + alternativeHash = crypto.SHA512 + } + if err := v.VerifySignature(bytes.NewReader(signature), bytes.NewReader(message), options.WithDigest(digest), options.WithCryptoSignerOpts(alternativeHash)); err == nil && isPreHashed { t.Error("no error when using mismatched hashFunc with digest & opts") } } diff --git a/pkg/signature/verifier.go b/pkg/signature/verifier.go index 9ca604929..cdde9fc54 100644 --- a/pkg/signature/verifier.go +++ b/pkg/signature/verifier.go @@ -26,6 +26,7 @@ import ( "path/filepath" "github.com/sigstore/sigstore/pkg/cryptoutils" + "github.com/sigstore/sigstore/pkg/signature/options" ) // Verifier verifies the digital signature using a specified public key @@ -40,12 +41,33 @@ type Verifier interface { // If publicKey is an RSA key, a RSAPKCS1v15Verifier will be returned. If a // RSAPSSVerifier is desired instead, use the LoadRSAPSSVerifier() method directly. func LoadVerifier(publicKey crypto.PublicKey, hashFunc crypto.Hash) (Verifier, error) { + return LoadVerifierWithOpts(publicKey, options.WithHash(hashFunc)) +} + +// LoadVerifierWithOpts returns a signature.Verifier based on the algorithm of the public key +// provided that will use the hash function specified when computing digests. +func LoadVerifierWithOpts(publicKey crypto.PublicKey, opts ...LoadOption) (Verifier, error) { + var rsaPSSOptions *rsa.PSSOptions + var useED25519ph bool + hashFunc := crypto.SHA256 + for _, o := range opts { + o.ApplyED25519ph(&useED25519ph) + o.ApplyHash(&hashFunc) + o.ApplyRSAPSS(&rsaPSSOptions) + } + switch pk := publicKey.(type) { case *rsa.PublicKey: + if rsaPSSOptions != nil { + return LoadRSAPSSVerifier(pk, hashFunc, rsaPSSOptions) + } return LoadRSAPKCS1v15Verifier(pk, hashFunc) case *ecdsa.PublicKey: return LoadECDSAVerifier(pk, hashFunc) case ed25519.PublicKey: + if useED25519ph { + return LoadED25519phVerifier(pk) + } return LoadED25519Verifier(pk) } return nil, errors.New("unsupported public key type") @@ -98,3 +120,19 @@ func LoadVerifierFromPEMFile(path string, hashFunc crypto.Hash) (Verifier, error return LoadVerifier(pubKey, hashFunc) } + +// LoadVerifierFromPEMFileWithOpts returns a signature.Verifier based on the contents of a +// file located at path. The Verifier wil use the hash function specified in the options when computing digests. +func LoadVerifierFromPEMFileWithOpts(path string, opts ...LoadOption) (Verifier, error) { + fileBytes, err := os.ReadFile(filepath.Clean(path)) + if err != nil { + return nil, err + } + + pubKey, err := cryptoutils.UnmarshalPEMToPublicKey(fileBytes) + if err != nil { + return nil, err + } + + return LoadVerifierWithOpts(pubKey, opts...) +} diff --git a/pkg/signature/verifier_test.go b/pkg/signature/verifier_test.go index 244099690..60f1ccab8 100644 --- a/pkg/signature/verifier_test.go +++ b/pkg/signature/verifier_test.go @@ -15,6 +15,7 @@ package signature import ( + "crypto" "crypto/rand" "crypto/rsa" "testing" @@ -34,3 +35,18 @@ func TestLoadUnsafeVerifier(t *testing.T) { t.Fatalf("public keys were not equal") } } + +func TestLoadVerifier(t *testing.T) { + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatalf("unexpected error generating key: %v", err) + } + verifier, err := LoadVerifier(key.Public(), crypto.SHA256) + if err != nil { + t.Fatalf("unexpected error loading verifier: %v", err) + } + pubKey, _ := verifier.PublicKey() + if !key.PublicKey.Equal(pubKey) { + t.Fatalf("public keys were not equal") + } +}