Debian Codegraph @

pkg/signature/kms/azure/signer.go

raw
1 //
2 // Copyright 2021 The Sigstore Authors.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15
16 package azure
17
18 import (
19 "context"
20 "crypto"
21 "errors"
22 "fmt"
23 "io"
24 "math/big"
25
26 "github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys"
27 "golang.org/x/crypto/cryptobyte"
28 "golang.org/x/crypto/cryptobyte/asn1"
29
30 "github.com/sigstore/sigstore/pkg/signature"
31 "github.com/sigstore/sigstore/pkg/signature/options"
32 )
33
34 var azureSupportedHashFuncs = []crypto.Hash{
35 crypto.SHA256,
36 crypto.SHA384,
37 crypto.SHA512,
38 }
39
40 var azureSupportedAlgorithms = []string{
41 string(azkeys.SignatureAlgorithmES256),
42 string(azkeys.SignatureAlgorithmES384),
43 string(azkeys.SignatureAlgorithmES512),
44 string(azkeys.SignatureAlgorithmRS256),
45 string(azkeys.SignatureAlgorithmRS384),
46 string(azkeys.SignatureAlgorithmRS512),
47 }
48
49 // SignerVerifier creates and verifies digital signatures over a message using Azure KMS service
50 type SignerVerifier struct {
51 defaultCtx context.Context
52 client *azureVaultClient
53 }
54
55 // LoadSignerVerifier generates signatures using the specified key in Azure Key Vault and hash algorithm.
56 //
57 // It also can verify signatures locally using the public key. hashFunc must not be crypto.Hash(0).
58 func LoadSignerVerifier(defaultCtx context.Context, referenceStr string) (*SignerVerifier, error) {
59 a := &SignerVerifier{
60 defaultCtx: defaultCtx,
61 }
62
63 var err error
64 a.client, err = newAzureKMS(referenceStr)
65 if err != nil {
66 return nil, err
67 }
68
69 return a, nil
70 }
71
72 // SignMessage signs the provided message using Azure Key Vault. If the message is provided,
73 // this method will compute the digest according to the hash function specified
74 // when the Signer was created.
75 //
76 // SignMessage recognizes the following Options listed in order of preference:
77 //
78 // - WithContext()
79 //
80 // - WithDigest()
81 //
82 // - WithCryptoSignerOpts()
83 //
84 // All other options are ignored if specified.
85 func (a *SignerVerifier) SignMessage(message io.Reader, opts ...signature.SignOption) ([]byte, error) {
86 var digest []byte
87 ctx := a.defaultCtx
88
89 for _, opt := range opts {
90 opt.ApplyContext(&ctx)
91 opt.ApplyDigest(&digest)
92 }
93
94 hashFunc, _, signatureRequiresECWrapping, err := a.client.getKeyVaultHashFunc(ctx)
95 if err != nil {
96 return nil, err
97 }
98
99 digest, _, err = signature.ComputeDigestForSigning(message, hashFunc, azureSupportedHashFuncs, opts...)
100 if err != nil {
101 return nil, err
102 }
103
104 rawSig, err := a.client.sign(ctx, digest)
105 if err != nil {
106 return nil, err
107 }
108
109 if signatureRequiresECWrapping {
110 l := len(rawSig)
111 r, s := &big.Int{}, &big.Int{}
112 r.SetBytes(rawSig[0 : l/2])
113 s.SetBytes(rawSig[l/2:])
114
115 // Convert the concatenated r||s byte string to an ASN.1 sequence
116 // This logic is borrowed from https://cs.opensource.google/go/go/+/refs/tags/go1.17.3:src/crypto/ecdsa/ecdsa.go;l=121
117 var b cryptobyte.Builder
118 b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
119 b.AddASN1BigInt(r)
120 b.AddASN1BigInt(s)
121 })
122
123 newBytes, err := b.Bytes()
124
125 if err != nil {
126 return nil, err
127 }
128
129 rawSig = newBytes
130 }
131
132 return rawSig, nil
133 }
134
135 // VerifySignature verifies the signature for the given message. Unless provided
136 // in an option, the digest of the message will be computed using the hash function specified
137 // when the SignerVerifier was created.
138 //
139 // This function returns nil if the verification succeeded, and an error message otherwise.
140 //
141 // This function recognizes the following Options listed in order of preference:
142 //
143 // - WithDigest()
144 //
145 // All other options are ignored if specified.
146 func (a *SignerVerifier) VerifySignature(sig, message io.Reader, opts ...signature.VerifyOption) error {
147 hashFunc, _, signatureRequiresECWrapping, err := a.client.getKeyVaultHashFunc(a.defaultCtx)
148 if err != nil {
149 return err
150 }
151
152 var digest []byte
153 var signerOpts crypto.SignerOpts = hashFunc
154 for _, opt := range opts {
155 opt.ApplyDigest(&digest)
156 }
157
158 digest, _, err = signature.ComputeDigestForVerifying(message, signerOpts.HashFunc(), azureSupportedHashFuncs, opts...)
159 if err != nil {
160 return err
161 }
162
163 sigBytes, err := io.ReadAll(sig)
164 if err != nil {
165 return fmt.Errorf("reading signature: %w", err)
166 }
167
168 if signatureRequiresECWrapping {
169 // Convert the ASN.1 Sequence to a concatenated r||s byte string
170 // This logic is borrowed from https://cs.opensource.google/go/go/+/refs/tags/go1.17.3:src/crypto/ecdsa/ecdsa.go;l=339
171 var (
172 r, s = &big.Int{}, &big.Int{}
173 inner cryptobyte.String
174 )
175 input := cryptobyte.String(sigBytes)
176 if !input.ReadASN1(&inner, asn1.SEQUENCE) ||
177 !input.Empty() ||
178 !inner.ReadASN1Integer(r) ||
179 !inner.ReadASN1Integer(s) ||
180 !inner.Empty() {
181 return errors.New("parsing signature")
182 }
183
184 rBytes := r.Bytes()
185 sBytes := r.Bytes()
186
187 sigBytes = make([]byte, 0, len(rBytes)+len(sBytes))
188 sigBytes = append(sigBytes, rBytes...)
189 sigBytes = append(sigBytes, sBytes...)
190 }
191
192 return a.client.verify(a.defaultCtx, sigBytes, digest)
193 }
194
195 // PublicKey returns the public key that can be used to verify signatures created by
196 // this signer. All options provided in arguments to this method are ignored.
197 func (a *SignerVerifier) PublicKey(_ ...signature.PublicKeyOption) (crypto.PublicKey, error) {
198 return a.client.public(a.defaultCtx)
199 }
200
201 // CreateKey attempts to create a new key in Vault with the specified algorithm.
202 func (a *SignerVerifier) CreateKey(ctx context.Context, _ string) (crypto.PublicKey, error) {
203 return a.client.createKey(ctx)
204 }
205
206 type cryptoSignerWrapper struct {
207 ctx context.Context
208 hashFunc crypto.Hash
209 sv *SignerVerifier
210 errFunc func(error)
211 }
212
213 func (c cryptoSignerWrapper) Public() crypto.PublicKey {
214 pk, err := c.sv.PublicKey(options.WithContext(c.ctx))
215 if err != nil && c.errFunc != nil {
216 c.errFunc(err)
217 }
218 return pk
219 }
220
221 func (c cryptoSignerWrapper) Sign(_ io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
222 hashFunc := c.hashFunc
223 if opts != nil {
224 hashFunc = opts.HashFunc()
225 }
226 azOptions := []signature.SignOption{
227 options.WithContext(c.ctx),
228 options.WithDigest(digest),
229 options.WithCryptoSignerOpts(hashFunc),
230 }
231
232 return c.sv.SignMessage(nil, azOptions...)
233 }
234
235 // CryptoSigner returns a crypto.Signer object that uses the underlying SignerVerifier, along with a crypto.SignerOpts object
236 // that allows the KMS to be used in APIs that only accept the standard golang objects
237 func (a *SignerVerifier) CryptoSigner(ctx context.Context, errFunc func(error)) (crypto.Signer, crypto.SignerOpts, error) {
238 hashFunc, _, _, err := a.client.getKeyVaultHashFunc(a.defaultCtx)
239 if err != nil {
240 return nil, nil, err
241 }
242
243 csw := &cryptoSignerWrapper{
244 ctx: ctx,
245 sv: a,
246 hashFunc: hashFunc,
247 errFunc: errFunc,
248 }
249
250 return csw, hashFunc, nil
251 }
252
253 // SupportedAlgorithms returns the list of algorithms supported by the Azure KMS service
254 func (*SignerVerifier) SupportedAlgorithms() []string {
255 return azureSupportedAlgorithms
256 }
257
258 // DefaultAlgorithm returns the default algorithm for the Azure KMS service
259 func (*SignerVerifier) DefaultAlgorithm() string {
260 return string(azkeys.SignatureAlgorithmES256)
261 }