Debian Codegraph @

pkg/signature/kms/gcp/client.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 gcp implement the interface with google cloud kms service
17 package gcp
18
19 import (
20 "context"
21 "crypto"
22 "crypto/ecdsa"
23 "crypto/rsa"
24 "errors"
25 "fmt"
26 "hash/crc32"
27 "io"
28 "log"
29 "regexp"
30 "time"
31
32 gcpkms "cloud.google.com/go/kms/apiv1"
33 "cloud.google.com/go/kms/apiv1/kmspb"
34 "google.golang.org/api/option"
35 "google.golang.org/protobuf/types/known/wrapperspb"
36
37 "github.com/jellydator/ttlcache/v3"
38 "github.com/sigstore/sigstore/pkg/cryptoutils"
39 "github.com/sigstore/sigstore/pkg/signature"
40 sigkms "github.com/sigstore/sigstore/pkg/signature/kms"
41 "github.com/sigstore/sigstore/pkg/signature/options"
42 )
43
44 func init() {
45 sigkms.AddProvider(ReferenceScheme, func(ctx context.Context, keyResourceID string, _ crypto.Hash, opts ...signature.RPCOption) (sigkms.SignerVerifier, error) {
46 clientOpts := make([]option.ClientOption, 0)
47 for _, opt := range opts {
48 if gcpOpt, ok := opt.(*requestGoogleAPIClientOption); ok {
49 var clientOpt option.ClientOption
50 gcpOpt.ApplyGoogleAPIClientOption(&clientOpt)
51 clientOpts = append(clientOpts, clientOpt)
52 }
53 }
54 return LoadSignerVerifier(ctx, keyResourceID, clientOpts...)
55 })
56 }
57
58 //nolint:revive
59 const (
60 AlgorithmECDSAP256SHA256 = "ecdsa-p256-sha256"
61 AlgorithmECDSAP384SHA384 = "ecdsa-p384-sha384"
62 AlgorithmRSAPKCS1v152048SHA256 = "rsa-pkcs1v15-2048-sha256"
63 AlgorithmRSAPKCS1v153072SHA256 = "rsa-pkcs1v15-3072-sha256"
64 AlgorithmRSAPKCS1v154096SHA256 = "rsa-pkcs1v15-4096-sha256"
65 AlgorithmRSAPKCS1v154096SHA512 = "rsa-pkcs1v15-4096-sha512"
66 AlgorithmRSAPSS2048SHA256 = "rsa-pss-2048-sha256"
67 AlgorithmRSAPSS3072SHA256 = "rsa-pss-3072-sha256"
68 AlgorithmRSAPSS4096SHA256 = "rsa-pss-4096-sha256"
69 AlgorithmRSAPSS4096SHA512 = "rsa-pss-4096-sha512"
70 )
71
72 var algorithmMap = map[string]kmspb.CryptoKeyVersion_CryptoKeyVersionAlgorithm{
73 AlgorithmECDSAP256SHA256: kmspb.CryptoKeyVersion_EC_SIGN_P256_SHA256,
74 AlgorithmECDSAP384SHA384: kmspb.CryptoKeyVersion_EC_SIGN_P384_SHA384,
75 AlgorithmRSAPKCS1v152048SHA256: kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_2048_SHA256,
76 AlgorithmRSAPKCS1v153072SHA256: kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_3072_SHA256,
77 AlgorithmRSAPKCS1v154096SHA256: kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_4096_SHA256,
78 AlgorithmRSAPKCS1v154096SHA512: kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_4096_SHA512,
79 AlgorithmRSAPSS2048SHA256: kmspb.CryptoKeyVersion_RSA_SIGN_PSS_2048_SHA256,
80 AlgorithmRSAPSS3072SHA256: kmspb.CryptoKeyVersion_RSA_SIGN_PSS_3072_SHA256,
81 AlgorithmRSAPSS4096SHA256: kmspb.CryptoKeyVersion_RSA_SIGN_PSS_4096_SHA256,
82 AlgorithmRSAPSS4096SHA512: kmspb.CryptoKeyVersion_RSA_SIGN_PSS_4096_SHA512,
83 }
84
85 type gcpClient struct {
86 defaultCtx context.Context
87 refString string
88 projectID string
89 locationID string
90 keyRing string
91 keyName string
92 version string
93 kvCache *ttlcache.Cache[string, cryptoKeyVersion]
94 kmsClient *gcpkms.KeyManagementClient
95 }
96
97 func newGCPClient(ctx context.Context, refStr string, opts ...option.ClientOption) (*gcpClient, error) {
98 if err := ValidReference(refStr); err != nil {
99 return nil, err
100 }
101
102 if ctx == nil {
103 ctx = context.Background()
104 }
105
106 g := &gcpClient{
107 defaultCtx: ctx,
108 refString: refStr,
109 kvCache: nil,
110 }
111 var err error
112 g.projectID, g.locationID, g.keyRing, g.keyName, g.version, err = parseReference(refStr)
113 if err != nil {
114 return nil, err
115 }
116
117 g.kmsClient, err = gcpkms.NewKeyManagementClient(ctx, opts...)
118 if err != nil {
119 return nil, fmt.Errorf("new gcp kms client: %w", err)
120 }
121
122 g.kvCache = ttlcache.New[string, cryptoKeyVersion](
123 ttlcache.WithDisableTouchOnHit[string, cryptoKeyVersion](),
124 )
125
126 // prime the cache
127 g.kvCache.Get(cacheKey)
128 return g, nil
129 }
130
131 var (
132 errKMSReference = errors.New("kms specification should be in the format gcpkms://projects/[PROJECT_ID]/locations/[LOCATION]/keyRings/[KEY_RING]/cryptoKeys/[KEY]/cryptoKeyVersions/[VERSION]")
133
134 re = regexp.MustCompile(`^gcpkms://projects/([^/]+)/locations/([^/]+)/keyRings/([^/]+)/cryptoKeys/([^/]+)(?:/(?:cryptoKeyVersions|versions)/([^/]+))?$`)
135 )
136
137 // ReferenceScheme schemes for various KMS services are copied from https://github.com/google/go-cloud/tree/master/secrets
138 const ReferenceScheme = "gcpkms://"
139
140 // ValidReference returns a non-nil error if the reference string is invalid
141 func ValidReference(ref string) error {
142 if !re.MatchString(ref) {
143 return errKMSReference
144 }
145 return nil
146 }
147
148 func parseReference(resourceID string) (projectID, locationID, keyRing, keyName, version string, err error) {
149 v := re.FindStringSubmatch(resourceID)
150 if len(v) != 6 {
151 err = fmt.Errorf("invalid gcpkms format %q", resourceID)
152 return
153 }
154 projectID, locationID, keyRing, keyName, version = v[1], v[2], v[3], v[4], v[5]
155 return
156 }
157
158 type cryptoKeyVersion struct {
159 CryptoKeyVersion *kmspb.CryptoKeyVersion
160 Verifier signature.Verifier
161 HashFunc crypto.Hash
162 }
163
164 // use a consistent key for cache lookups
165 const cacheKey = "crypto_key_version"
166
167 // keyVersionName returns the first key version found for a key in KMS
168 func (g *gcpClient) keyVersionName(ctx context.Context) (*cryptoKeyVersion, error) {
169 parent := fmt.Sprintf("projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s", g.projectID, g.locationID, g.keyRing, g.keyName)
170
171 parentReq := &kmspb.GetCryptoKeyRequest{
172 Name: parent,
173 }
174 key, err := g.kmsClient.GetCryptoKey(ctx, parentReq)
175 if err != nil {
176 return nil, err
177 }
178 if key.Purpose != kmspb.CryptoKey_ASYMMETRIC_SIGN {
179 return nil, errors.New("specified key cannot be used to sign")
180 }
181
182 // if g.version was specified, use it explicitly
183 var kv *kmspb.CryptoKeyVersion
184 if g.version != "" {
185 req := &kmspb.GetCryptoKeyVersionRequest{
186 Name: parent + fmt.Sprintf("/cryptoKeyVersions/%s", g.version),
187 }
188 kv, err = g.kmsClient.GetCryptoKeyVersion(ctx, req)
189 if err != nil {
190 return nil, err
191 }
192 } else {
193 req := &kmspb.ListCryptoKeyVersionsRequest{
194 Parent: parent,
195 Filter: "state=ENABLED",
196 OrderBy: "name desc",
197 }
198 iterator := g.kmsClient.ListCryptoKeyVersions(ctx, req)
199
200 // pick the key version that is enabled with the greatest version value
201 kv, err = iterator.Next()
202 if err != nil {
203 return nil, fmt.Errorf("unable to find an enabled key version in GCP KMS: %w", err)
204 }
205 }
206 // kv is keyVersion to use
207 crv := cryptoKeyVersion{
208 CryptoKeyVersion: kv,
209 }
210
211 pubKey, err := g.fetchPublicKey(ctx, kv.Name)
212 if err != nil {
213 return nil, fmt.Errorf("unable to fetch public key while creating signer: %w", err)
214 }
215
216 // crv.Verifier is set here to enable storing the public key & hash algorithm together,
217 // as well as using the in memory Verifier to perform the verify operations.
218 switch kv.Algorithm {
219 case kmspb.CryptoKeyVersion_EC_SIGN_P256_SHA256:
220 pk, ok := pubKey.(*ecdsa.PublicKey)
221 if !ok {
222 return nil, fmt.Errorf("asserting public key type ecdsa.PublicKey")
223 }
224 crv.Verifier, err = signature.LoadECDSAVerifier(pk, crypto.SHA256)
225 crv.HashFunc = crypto.SHA256
226 case kmspb.CryptoKeyVersion_EC_SIGN_P384_SHA384:
227 pk, ok := pubKey.(*ecdsa.PublicKey)
228 if !ok {
229 return nil, fmt.Errorf("asserting public key type ecdsa.PublicKey")
230 }
231 crv.Verifier, err = signature.LoadECDSAVerifier(pk, crypto.SHA384)
232 crv.HashFunc = crypto.SHA384
233 case kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_2048_SHA256,
234 kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_3072_SHA256,
235 kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_4096_SHA256:
236 pk, ok := pubKey.(*rsa.PublicKey)
237 if !ok {
238 return nil, fmt.Errorf("asserting public key type rsa.PublicKey")
239 }
240 crv.Verifier, err = signature.LoadRSAPKCS1v15Verifier(pk, crypto.SHA256)
241 crv.HashFunc = crypto.SHA256
242 case kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_4096_SHA512:
243 pk, ok := pubKey.(*rsa.PublicKey)
244 if !ok {
245 return nil, fmt.Errorf("asserting public key type rsa.PublicKey")
246 }
247 crv.Verifier, err = signature.LoadRSAPKCS1v15Verifier(pk, crypto.SHA512)
248 crv.HashFunc = crypto.SHA512
249 case kmspb.CryptoKeyVersion_RSA_SIGN_PSS_2048_SHA256,
250 kmspb.CryptoKeyVersion_RSA_SIGN_PSS_3072_SHA256,
251 kmspb.CryptoKeyVersion_RSA_SIGN_PSS_4096_SHA256:
252 pk, ok := pubKey.(*rsa.PublicKey)
253 if !ok {
254 return nil, fmt.Errorf("asserting public key type rsa.PublicKey")
255 }
256 crv.Verifier, err = signature.LoadRSAPSSVerifier(pk, crypto.SHA256, nil)
257 crv.HashFunc = crypto.SHA256
258 case kmspb.CryptoKeyVersion_RSA_SIGN_PSS_4096_SHA512:
259 pk, ok := pubKey.(*rsa.PublicKey)
260 if !ok {
261 return nil, fmt.Errorf("asserting public key type rsa.PublicKey")
262 }
263 crv.Verifier, err = signature.LoadRSAPSSVerifier(pk, crypto.SHA512, nil)
264 crv.HashFunc = crypto.SHA512
265 default:
266 return nil, errors.New("unknown algorithm specified by KMS")
267 }
268 if err != nil {
269 return nil, fmt.Errorf("initializing internal verifier: %w", err)
270 }
271 return &crv, nil
272 }
273
274 func (g *gcpClient) fetchPublicKey(ctx context.Context, name string) (crypto.PublicKey, error) {
275 // Build the request.
276 pkreq := &kmspb.GetPublicKeyRequest{Name: name}
277 // Call the API.
278 pk, err := g.kmsClient.GetPublicKey(ctx, pkreq)
279 if err != nil {
280 return nil, fmt.Errorf("public key: %w", err)
281 }
282 return cryptoutils.UnmarshalPEMToPublicKey([]byte(pk.GetPem()))
283 }
284
285 func (g *gcpClient) getHashFunc() (crypto.Hash, error) {
286 ckv, err := g.getCKV()
287 if err != nil {
288 return 0, err
289 }
290 return ckv.HashFunc, nil
291 }
292
293 // getCKV gets the latest CryptoKeyVersion from the client's cache, which may trigger an actual
294 // call to GCP if the existing entry in the cache has expired.
295 func (g *gcpClient) getCKV() (*cryptoKeyVersion, error) {
296 var lerr error
297 loader := ttlcache.LoaderFunc[string, cryptoKeyVersion](
298 func(c *ttlcache.Cache[string, cryptoKeyVersion], key string) *ttlcache.Item[string, cryptoKeyVersion] {
299 var ttl time.Duration
300 var data *cryptoKeyVersion
301
302 // if we're given an explicit version, cache this value forever
303 if g.version != "" {
304 ttl = time.Second * 0
305 } else {
306 ttl = time.Second * 300
307 }
308 data, lerr = g.keyVersionName(context.Background())
309 if lerr == nil {
310 return c.Set(key, *data, ttl)
311 }
312 return nil
313 },
314 )
315
316 // we get once and use consistently to ensure the cache value doesn't change underneath us
317 item := g.kvCache.Get(cacheKey, ttlcache.WithLoader[string, cryptoKeyVersion](loader))
318 if item != nil {
319 v := item.Value()
320 return &v, nil
321 }
322 return nil, lerr
323 }
324
325 func (g *gcpClient) sign(ctx context.Context, digest []byte, alg crypto.Hash, crc uint32) ([]byte, error) {
326 ckv, err := g.getCKV()
327 if err != nil {
328 return nil, err
329 }
330
331 gcpSignReq := kmspb.AsymmetricSignRequest{
332 Name: ckv.CryptoKeyVersion.Name,
333 Digest: &kmspb.Digest{},
334 }
335
336 if crc != 0 {
337 gcpSignReq.DigestCrc32C = wrapperspb.Int64(int64(crc))
338 }
339
340 switch alg {
341 case crypto.SHA256:
342 gcpSignReq.Digest.Digest = &kmspb.Digest_Sha256{
343 Sha256: digest,
344 }
345 case crypto.SHA384:
346 gcpSignReq.Digest.Digest = &kmspb.Digest_Sha384{
347 Sha384: digest,
348 }
349 case crypto.SHA512:
350 gcpSignReq.Digest.Digest = &kmspb.Digest_Sha512{
351 Sha512: digest,
352 }
353 default:
354 return nil, errors.New("unsupported hash function")
355 }
356
357 resp, err := g.kmsClient.AsymmetricSign(ctx, &gcpSignReq)
358 if err != nil {
359 return nil, fmt.Errorf("calling GCP AsymmetricSign: %w", err)
360 }
361
362 // Optional, but recommended: perform integrity verification on result.
363 // For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
364 // https://cloud.google.com/kms/docs/data-integrity-guidelines
365 if crc != 0 && !resp.VerifiedDigestCrc32C {
366 return nil, fmt.Errorf("AsymmetricSign: request corrupted in-transit")
367 }
368 if int64(crc32.Checksum(resp.Signature, crc32.MakeTable(crc32.Castagnoli))) != resp.SignatureCrc32C.Value {
369 return nil, fmt.Errorf("AsymmetricSign: response corrupted in-transit")
370 }
371
372 return resp.Signature, nil
373 }
374
375 func (g *gcpClient) public(ctx context.Context) (crypto.PublicKey, error) {
376 crv, err := g.getCKV()
377 if err != nil {
378 return nil, fmt.Errorf("transient error getting info from KMS: %w", err)
379 }
380 return crv.Verifier.PublicKey(options.WithContext(ctx))
381 }
382
383 func (g *gcpClient) verify(sig, message io.Reader, opts ...signature.VerifyOption) error {
384 crv, err := g.getCKV()
385 if err != nil {
386 return fmt.Errorf("transient error getting info from KMS: %w", err)
387 }
388 if err := crv.Verifier.VerifySignature(sig, message, opts...); err != nil {
389 // key could have been rotated, clear cache and try again if we're not pinned to a version
390 if g.version == "" {
391 g.kvCache.Delete(cacheKey)
392 crv, err = g.getCKV()
393 if err != nil {
394 return fmt.Errorf("transient error getting info from KMS: %w", err)
395 }
396 return crv.Verifier.VerifySignature(sig, message, opts...)
397 }
398 return fmt.Errorf("failed to verify for fixed version: %w", err)
399 }
400 return nil
401 }
402
403 func (g *gcpClient) createKey(ctx context.Context, algorithm string) (crypto.PublicKey, error) {
404 if err := g.createKeyRing(ctx); err != nil {
405 return nil, fmt.Errorf("creating key ring: %w", err)
406 }
407
408 getKeyRequest := &kmspb.GetCryptoKeyRequest{
409 Name: fmt.Sprintf("projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s", g.projectID, g.locationID, g.keyRing, g.keyName),
410 }
411 if _, err := g.kmsClient.GetCryptoKey(ctx, getKeyRequest); err == nil {
412 return g.public(ctx)
413 }
414
415 if _, ok := algorithmMap[algorithm]; !ok {
416 return nil, errors.New("unknown algorithm requested")
417 }
418
419 createKeyRequest := &kmspb.CreateCryptoKeyRequest{
420 Parent: fmt.Sprintf("projects/%s/locations/%s/keyRings/%s", g.projectID, g.locationID, g.keyRing),
421 CryptoKeyId: g.keyName,
422 CryptoKey: &kmspb.CryptoKey{
423 Purpose: kmspb.CryptoKey_ASYMMETRIC_SIGN,
424 VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
425 Algorithm: algorithmMap[algorithm],
426 },
427 },
428 }
429 if _, err := g.kmsClient.CreateCryptoKey(ctx, createKeyRequest); err != nil {
430 return nil, fmt.Errorf("creating crypto key: %w", err)
431 }
432 return g.public(ctx)
433 }
434
435 func (g *gcpClient) createKeyRing(ctx context.Context) error {
436 getKeyRingRequest := &kmspb.GetKeyRingRequest{
437 Name: fmt.Sprintf("projects/%s/locations/%s/keyRings/%s", g.projectID, g.locationID, g.keyRing),
438 }
439 if result, err := g.kmsClient.GetKeyRing(ctx, getKeyRingRequest); err == nil {
440 log.Printf("Key ring %s already exists in GCP KMS, moving on to creating key.\n", result.GetName())
441 // key ring already exists, no need to create
442 return nil
443 }
444 // try to create key ring
445 createKeyRingRequest := &kmspb.CreateKeyRingRequest{
446 Parent: fmt.Sprintf("projects/%s/locations/%s", g.projectID, g.locationID),
447 KeyRingId: g.keyRing,
448 }
449 result, err := g.kmsClient.CreateKeyRing(ctx, createKeyRingRequest)
450 if err != nil {
451 return fmt.Errorf("creating keyring: %w", err)
452 }
453 log.Printf("Created key ring %s in GCP KMS.\n", result.GetName())
454 return nil
455 }