Debian Codegraph @

pkg/signature/kms/azure/client.go

raw
1 //
2 // Copyright 2022 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 implement the interface with microsoft azure kms service
17 package azure
18
19 import (
20 "context"
21 "crypto"
22 "crypto/ecdsa"
23 "crypto/elliptic"
24 "crypto/rsa"
25 "encoding/json"
26 "errors"
27 "fmt"
28 "net/http"
29 "os"
30 "regexp"
31 "strings"
32 "time"
33
34 "github.com/Azure/azure-sdk-for-go/sdk/azcore"
35 "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
36
37 "github.com/go-jose/go-jose/v4"
38 "github.com/jellydator/ttlcache/v3"
39
40 "github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
41 "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
42 "github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys"
43 "github.com/sigstore/sigstore/pkg/signature"
44 sigkms "github.com/sigstore/sigstore/pkg/signature/kms"
45 )
46
47 func init() {
48 sigkms.AddProvider(ReferenceScheme, func(ctx context.Context, keyResourceID string, _ crypto.Hash, _ ...signature.RPCOption) (sigkms.SignerVerifier, error) {
49 return LoadSignerVerifier(ctx, keyResourceID)
50 })
51 }
52
53 type kvClient interface {
54 CreateKey(ctx context.Context, name string, parameters azkeys.CreateKeyParameters, options *azkeys.CreateKeyOptions) (azkeys.CreateKeyResponse, error)
55 GetKey(ctx context.Context, name, version string, options *azkeys.GetKeyOptions) (azkeys.GetKeyResponse, error)
56 Sign(ctx context.Context, name, version string, parameters azkeys.SignParameters, options *azkeys.SignOptions) (azkeys.SignResponse, error)
57 Verify(ctx context.Context, name, version string, parameters azkeys.VerifyParameters, options *azkeys.VerifyOptions) (azkeys.VerifyResponse, error)
58 }
59
60 type azureVaultClient struct {
61 client kvClient
62 keyCache *ttlcache.Cache[string, crypto.PublicKey]
63 vaultURL string
64 keyName string
65 keyVersion string
66 }
67
68 var (
69 errAzureReference = errors.New("kms specification should be in the format azurekms://[VAULT_NAME][VAULT_URL]/[KEY_NAME]/[VERSION (optional)]")
70
71 referenceRegex = regexp.MustCompile(`^azurekms://([^/]+)/([^/]+)(/[a-z0-9]*)?$`)
72 )
73
74 const (
75 // ReferenceScheme schemes for various KMS services are copied from https://github.com/google/go-cloud/tree/master/secrets
76 ReferenceScheme = "azurekms://"
77 cacheKey = "azure_vault_signer"
78 azureClientID = "AZURE_CLIENT_ID"
79 )
80
81 // ValidReference returns a non-nil error if the reference string is invalid
82 func ValidReference(ref string) error {
83 if !referenceRegex.MatchString(ref) {
84 return errAzureReference
85 }
86 return nil
87 }
88
89 // The key version can be optionally provided
90 // If provided, all key operations will specify this version.
91 // If not provided, the key operations will use the latest key version by default.
92 func parseReference(resourceID string) (vaultURL, keyName, keyVersion string, err error) {
93 if isIDValid := referenceRegex.MatchString(resourceID); !isIDValid {
94 err = fmt.Errorf("invalid azurekms format %q", resourceID)
95 return
96 }
97
98 fullRef := strings.Split(resourceID, "azurekms://")[1]
99 splitRef := strings.Split(fullRef, "/")
100 vaultURL = fmt.Sprintf("https://%s/", splitRef[0])
101 keyName = splitRef[1]
102
103 if len(splitRef) == 3 {
104 keyVersion = splitRef[2]
105 }
106
107 return
108 }
109
110 func newAzureKMS(keyResourceID string) (*azureVaultClient, error) {
111 if err := ValidReference(keyResourceID); err != nil {
112 return nil, err
113 }
114 vaultURL, keyName, keyVersion, err := parseReference(keyResourceID)
115 if err != nil {
116 return nil, err
117 }
118
119 opts := getAzClientOpts()
120 cred, err := azidentity.NewDefaultAzureCredential(&azidentity.DefaultAzureCredentialOptions{ClientOptions: opts})
121 if err != nil {
122 return nil, err
123 }
124
125 client, err := azkeys.NewClient(vaultURL, cred, nil)
126 if err != nil {
127 return nil, fmt.Errorf("new azure kms client: %w", err)
128 }
129
130 azClient := &azureVaultClient{
131 client: client,
132 vaultURL: vaultURL,
133 keyName: keyName,
134 keyVersion: keyVersion,
135 keyCache: ttlcache.New[string, crypto.PublicKey](
136 ttlcache.WithDisableTouchOnHit[string, crypto.PublicKey](),
137 ),
138 }
139
140 return azClient, nil
141 }
142
143 func getAzClientOpts() azcore.ClientOptions {
144 envName := os.Getenv("AZURE_ENVIRONMENT")
145 switch envName {
146 case "AZUREUSGOVERNMENT", "AZUREUSGOVERNMENTCLOUD":
147 return azcore.ClientOptions{Cloud: cloud.AzureGovernment}
148 case "AZURECHINACLOUD":
149 return azcore.ClientOptions{Cloud: cloud.AzureChina}
150 case "AZURECLOUD", "AZUREPUBLICCLOUD":
151 return azcore.ClientOptions{Cloud: cloud.AzurePublic}
152 default:
153 return azcore.ClientOptions{Cloud: cloud.AzurePublic}
154 }
155 }
156
157 func (a *azureVaultClient) fetchPublicKey(ctx context.Context) (crypto.PublicKey, error) {
158 keyBundle, err := a.getKey(ctx)
159 if err != nil {
160 return nil, fmt.Errorf("public key: %w", err)
161 }
162
163 key := keyBundle.Key
164 keyType := key.Kty
165
166 // Azure Key Vault allows keys to be stored in either default Key Vault storage
167 // or in managed HSMs. If the key is stored in a HSM, the key type is suffixed
168 // with "-HSM". Since this suffix is specific to Azure Key Vault, it needs
169 // be stripped from the key type before attempting to represent the key
170 // with a go-jose/JSONWebKey struct.
171 switch *keyType {
172 case azkeys.KeyTypeECHSM:
173 *key.Kty = azkeys.KeyTypeEC
174 case azkeys.KeyTypeRSAHSM:
175 *key.Kty = azkeys.KeyTypeRSA
176 }
177
178 jwkJSON, err := json.Marshal(*key)
179 if err != nil {
180 return nil, fmt.Errorf("encoding the jsonWebKey: %w", err)
181 }
182
183 jwk := jose.JSONWebKey{}
184 err = jwk.UnmarshalJSON(jwkJSON)
185 if err != nil {
186 return nil, fmt.Errorf("decoding the jsonWebKey: %w", err)
187 }
188
189 return jwk.Key, nil
190 }
191
192 func (a *azureVaultClient) getKey(ctx context.Context) (azkeys.KeyBundle, error) {
193 resp, err := a.client.GetKey(ctx, a.keyName, a.keyVersion, nil)
194 if err != nil {
195 return azkeys.KeyBundle{}, fmt.Errorf("public key: %w", err)
196 }
197
198 return resp.KeyBundle, err
199 }
200
201 func (a *azureVaultClient) public(ctx context.Context) (crypto.PublicKey, error) {
202 var lerr error
203 loader := ttlcache.LoaderFunc[string, crypto.PublicKey](
204 func(c *ttlcache.Cache[string, crypto.PublicKey], _ string) *ttlcache.Item[string, crypto.PublicKey] {
205 ttl := 300 * time.Second
206 var pubKey crypto.PublicKey
207 pubKey, lerr = a.fetchPublicKey(ctx)
208 if lerr == nil {
209 return c.Set(cacheKey, pubKey, ttl)
210 }
211 return nil
212 },
213 )
214 item := a.keyCache.Get(cacheKey, ttlcache.WithLoader[string, crypto.PublicKey](loader))
215 if lerr != nil {
216 return nil, lerr
217 }
218 return item.Value(), nil
219 }
220
221 func (a *azureVaultClient) createKey(ctx context.Context) (crypto.PublicKey, error) {
222 // check if the key already exists by attempting to fetch it
223 _, err := a.getKey(ctx)
224 // if the error is nil, this means the key already exists
225 // and we can return the public key
226 if err == nil {
227 return a.public(ctx)
228 }
229
230 // If the returned error is not nil, set the error to the
231 // custom azcore.ResponseError error implementation
232 // this custom error allows us to check the status code
233 // returned by the GetKey operation. If the operation
234 // returned a 404, we know that the key does not exist
235 // and we can create it.
236 var respErr *azcore.ResponseError
237 if ok := errors.As(err, &respErr); !ok {
238 return nil, fmt.Errorf("unexpected error returned by get key operation: %w", err)
239 }
240
241 // if a non-404 status code is returned, return the error
242 // since this is an unexpected error response
243 if respErr.StatusCode != http.StatusNotFound {
244 return nil, fmt.Errorf("unexpected status code returned by get key operation: %w", err)
245 }
246
247 // if a 404 was returned, then we can create the key
248 _, err = a.client.CreateKey(
249 ctx,
250 a.keyName,
251 azkeys.CreateKeyParameters{
252 KeyAttributes: &azkeys.KeyAttributes{
253 Enabled: to.Ptr(true),
254 },
255 KeySize: to.Ptr(int32(2048)),
256 KeyOps: []*azkeys.KeyOperation{
257 to.Ptr(azkeys.KeyOperationSign),
258 to.Ptr(azkeys.KeyOperationVerify),
259 },
260 Kty: to.Ptr(azkeys.KeyTypeEC),
261 Tags: map[string]*string{
262 "use": to.Ptr("sigstore"),
263 },
264 }, nil)
265 if err != nil {
266 return nil, err
267 }
268
269 return a.public(ctx)
270 }
271
272 // 3rd return value specifies whether the resulting signature is an EC signature,
273 // thus requiring conversion between the signature formats.
274 func (a *azureVaultClient) getKeyVaultHashFunc(ctx context.Context) (crypto.Hash, azkeys.SignatureAlgorithm, bool, error) {
275 publicKey, err := a.public(ctx)
276 if err != nil {
277 return 0, "", false, fmt.Errorf("failed to get public key: %w", err)
278 }
279 switch keyImpl := publicKey.(type) {
280 case *ecdsa.PublicKey:
281 switch keyImpl.Curve {
282 case elliptic.P256():
283 return crypto.SHA256, azkeys.SignatureAlgorithmES256, true, nil
284 case elliptic.P384():
285 return crypto.SHA384, azkeys.SignatureAlgorithmES384, true, nil
286 case elliptic.P521():
287 return crypto.SHA512, azkeys.SignatureAlgorithmES512, true, nil
288 default:
289 return 0, "", false, fmt.Errorf("unsupported key size: %s", keyImpl.Params().Name)
290 }
291 case *rsa.PublicKey:
292 switch keyImpl.Size() {
293 case 256:
294 return crypto.SHA256, azkeys.SignatureAlgorithmRS256, false, nil
295 case 384:
296 return crypto.SHA384, azkeys.SignatureAlgorithmRS384, false, nil
297 case 512:
298 return crypto.SHA512, azkeys.SignatureAlgorithmRS512, false, nil
299 default:
300 return 0, "", false, fmt.Errorf("unsupported key size: %d", keyImpl.Size())
301 }
302 default:
303 return 0, "", false, fmt.Errorf("unsupported public key type: %T", publicKey)
304 }
305 }
306
307 func (a *azureVaultClient) sign(ctx context.Context, hash []byte) ([]byte, error) {
308 _, keyVaultAlgo, _, err := a.getKeyVaultHashFunc(ctx)
309 if err != nil {
310 return nil, fmt.Errorf("failed to get KeyVaultSignatureAlgorithm: %w", err)
311 }
312
313 params := azkeys.SignParameters{
314 Algorithm: &keyVaultAlgo,
315 Value: hash,
316 }
317
318 result, err := a.client.Sign(ctx, a.keyName, a.keyVersion, params, nil)
319 if err != nil {
320 return nil, fmt.Errorf("signing the payload: %w", err)
321 }
322
323 return result.Result, nil
324 }
325
326 func (a *azureVaultClient) verify(ctx context.Context, signature, hash []byte) error {
327 _, keyVaultAlgo, _, err := a.getKeyVaultHashFunc(ctx)
328 if err != nil {
329 return fmt.Errorf("failed to get KeyVaultSignatureAlgorithm: %w", err)
330 }
331
332 params := azkeys.VerifyParameters{
333 Algorithm: &keyVaultAlgo,
334 Digest: hash,
335 Signature: signature,
336 }
337
338 result, err := a.client.Verify(ctx, a.keyName, a.keyVersion, params, nil)
339 if err != nil {
340 return fmt.Errorf("verify: %w", err)
341 }
342
343 if !*result.Value {
344 return errors.New("failed vault verification")
345 }
346
347 return nil
348 }