cloudkms.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. package cloudkms
  2. import (
  3. "context"
  4. "crypto"
  5. "strings"
  6. "time"
  7. "google.golang.org/grpc/codes"
  8. "google.golang.org/grpc/status"
  9. cloudkms "cloud.google.com/go/kms/apiv1"
  10. gax "github.com/googleapis/gax-go/v2"
  11. "github.com/pkg/errors"
  12. "github.com/smallstep/certificates/kms/apiv1"
  13. "github.com/smallstep/cli/crypto/pemutil"
  14. "google.golang.org/api/option"
  15. kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1"
  16. )
  17. // protectionLevelMapping maps step protection levels with cloud kms ones.
  18. var protectionLevelMapping = map[apiv1.ProtectionLevel]kmspb.ProtectionLevel{
  19. apiv1.UnspecifiedProtectionLevel: kmspb.ProtectionLevel_PROTECTION_LEVEL_UNSPECIFIED,
  20. apiv1.Software: kmspb.ProtectionLevel_SOFTWARE,
  21. apiv1.HSM: kmspb.ProtectionLevel_HSM,
  22. }
  23. // signatureAlgorithmMapping is a mapping between the step signature algorithm,
  24. // and bits for RSA keys, with cloud kms one.
  25. //
  26. // Cloud KMS does not support SHA384WithRSA, SHA384WithRSAPSS, SHA384WithRSAPSS,
  27. // ECDSAWithSHA512, and PureEd25519.
  28. var signatureAlgorithmMapping = map[apiv1.SignatureAlgorithm]interface{}{
  29. apiv1.UnspecifiedSignAlgorithm: kmspb.CryptoKeyVersion_CRYPTO_KEY_VERSION_ALGORITHM_UNSPECIFIED,
  30. apiv1.SHA256WithRSA: map[int]kmspb.CryptoKeyVersion_CryptoKeyVersionAlgorithm{
  31. 0: kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_3072_SHA256,
  32. 2048: kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_2048_SHA256,
  33. 3072: kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_3072_SHA256,
  34. 4096: kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_4096_SHA256,
  35. },
  36. apiv1.SHA512WithRSA: map[int]kmspb.CryptoKeyVersion_CryptoKeyVersionAlgorithm{
  37. 0: kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_4096_SHA256,
  38. 4096: kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_4096_SHA256,
  39. },
  40. apiv1.SHA256WithRSAPSS: map[int]kmspb.CryptoKeyVersion_CryptoKeyVersionAlgorithm{
  41. 0: kmspb.CryptoKeyVersion_RSA_SIGN_PSS_3072_SHA256,
  42. 2048: kmspb.CryptoKeyVersion_RSA_SIGN_PSS_2048_SHA256,
  43. 3072: kmspb.CryptoKeyVersion_RSA_SIGN_PSS_3072_SHA256,
  44. 4096: kmspb.CryptoKeyVersion_RSA_SIGN_PSS_4096_SHA256,
  45. },
  46. apiv1.SHA512WithRSAPSS: map[int]kmspb.CryptoKeyVersion_CryptoKeyVersionAlgorithm{
  47. 0: kmspb.CryptoKeyVersion_RSA_SIGN_PSS_4096_SHA512,
  48. 4096: kmspb.CryptoKeyVersion_RSA_SIGN_PSS_4096_SHA512,
  49. },
  50. apiv1.ECDSAWithSHA256: kmspb.CryptoKeyVersion_EC_SIGN_P256_SHA256,
  51. apiv1.ECDSAWithSHA384: kmspb.CryptoKeyVersion_EC_SIGN_P384_SHA384,
  52. }
  53. // KeyManagementClient defines the methods on KeyManagementClient that this
  54. // package will use. This interface will be used for unit testing.
  55. type KeyManagementClient interface {
  56. Close() error
  57. GetPublicKey(context.Context, *kmspb.GetPublicKeyRequest, ...gax.CallOption) (*kmspb.PublicKey, error)
  58. AsymmetricSign(context.Context, *kmspb.AsymmetricSignRequest, ...gax.CallOption) (*kmspb.AsymmetricSignResponse, error)
  59. CreateCryptoKey(context.Context, *kmspb.CreateCryptoKeyRequest, ...gax.CallOption) (*kmspb.CryptoKey, error)
  60. GetKeyRing(context.Context, *kmspb.GetKeyRingRequest, ...gax.CallOption) (*kmspb.KeyRing, error)
  61. CreateKeyRing(context.Context, *kmspb.CreateKeyRingRequest, ...gax.CallOption) (*kmspb.KeyRing, error)
  62. CreateCryptoKeyVersion(ctx context.Context, req *kmspb.CreateCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error)
  63. }
  64. // CloudKMS implements a KMS using Google's Cloud apiv1.
  65. type CloudKMS struct {
  66. client KeyManagementClient
  67. }
  68. // New creates a new CloudKMS configured with a new client.
  69. func New(ctx context.Context, opts apiv1.Options) (*CloudKMS, error) {
  70. var cloudOpts []option.ClientOption
  71. if opts.CredentialsFile != "" {
  72. cloudOpts = append(cloudOpts, option.WithCredentialsFile(opts.CredentialsFile))
  73. }
  74. client, err := cloudkms.NewKeyManagementClient(ctx, cloudOpts...)
  75. if err != nil {
  76. return nil, err
  77. }
  78. return &CloudKMS{
  79. client: client,
  80. }, nil
  81. }
  82. // NewCloudKMS creates a CloudKMS with a given client.
  83. func NewCloudKMS(client KeyManagementClient) *CloudKMS {
  84. return &CloudKMS{
  85. client: client,
  86. }
  87. }
  88. // Close closes the connection of the Cloud KMS client.
  89. func (k *CloudKMS) Close() error {
  90. if err := k.client.Close(); err != nil {
  91. return errors.Wrap(err, "cloudKMS Close failed")
  92. }
  93. return nil
  94. }
  95. // CreateSigner returns a new cloudkms signer configured with the given signing
  96. // key name.
  97. func (k *CloudKMS) CreateSigner(req *apiv1.CreateSignerRequest) (crypto.Signer, error) {
  98. if req.SigningKey == "" {
  99. return nil, errors.New("signing key cannot be empty")
  100. }
  101. return NewSigner(k.client, req.SigningKey), nil
  102. }
  103. // CreateKey creates in Google's Cloud KMS a new asymmetric key for signing.
  104. func (k *CloudKMS) CreateKey(req *apiv1.CreateKeyRequest) (*apiv1.CreateKeyResponse, error) {
  105. if req.Name == "" {
  106. return nil, errors.New("createKeyRequest 'name' cannot be empty")
  107. }
  108. protectionLevel, ok := protectionLevelMapping[req.ProtectionLevel]
  109. if !ok {
  110. return nil, errors.Errorf("cloudKMS does not support protection level '%s'", req.ProtectionLevel)
  111. }
  112. var signatureAlgorithm kmspb.CryptoKeyVersion_CryptoKeyVersionAlgorithm
  113. v, ok := signatureAlgorithmMapping[req.SignatureAlgorithm]
  114. if !ok {
  115. return nil, errors.Errorf("cloudKMS does not support signature algorithm '%s'", req.SignatureAlgorithm)
  116. }
  117. switch v := v.(type) {
  118. case kmspb.CryptoKeyVersion_CryptoKeyVersionAlgorithm:
  119. signatureAlgorithm = v
  120. case map[int]kmspb.CryptoKeyVersion_CryptoKeyVersionAlgorithm:
  121. if signatureAlgorithm, ok = v[req.Bits]; !ok {
  122. return nil, errors.Errorf("cloudKMS does not support signature algorithm '%s' with '%d' bits", req.SignatureAlgorithm, req.Bits)
  123. }
  124. default:
  125. return nil, errors.Errorf("unexpected error: this should not happen")
  126. }
  127. var crytoKeyName string
  128. // Split `projects/PROJECT_ID/locations/global/keyRings/RING_ID/cryptoKeys/KEY_ID`
  129. // to `projects/PROJECT_ID/locations/global/keyRings/RING_ID` and `KEY_ID`.
  130. keyRing, keyID := Parent(req.Name)
  131. if err := k.createKeyRingIfNeeded(keyRing); err != nil {
  132. return nil, err
  133. }
  134. ctx, cancel := defaultContext()
  135. defer cancel()
  136. // Create private key in CloudKMS.
  137. response, err := k.client.CreateCryptoKey(ctx, &kmspb.CreateCryptoKeyRequest{
  138. Parent: keyRing,
  139. CryptoKeyId: keyID,
  140. CryptoKey: &kmspb.CryptoKey{
  141. Purpose: kmspb.CryptoKey_ASYMMETRIC_SIGN,
  142. VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
  143. ProtectionLevel: protectionLevel,
  144. Algorithm: signatureAlgorithm,
  145. },
  146. },
  147. })
  148. if err != nil {
  149. if status.Code(err) != codes.AlreadyExists {
  150. return nil, errors.Wrap(err, "cloudKMS CreateCryptoKey failed")
  151. }
  152. // Create a new version if the key already exists.
  153. //
  154. // Note that it will have the same purpose, protection level and
  155. // algorithm than as previous one.
  156. req := &kmspb.CreateCryptoKeyVersionRequest{
  157. Parent: req.Name,
  158. CryptoKeyVersion: &kmspb.CryptoKeyVersion{
  159. State: kmspb.CryptoKeyVersion_ENABLED,
  160. },
  161. }
  162. response, err := k.client.CreateCryptoKeyVersion(ctx, req)
  163. if err != nil {
  164. return nil, errors.Wrap(err, "cloudKMS CreateCryptoKeyVersion failed")
  165. }
  166. crytoKeyName = response.Name
  167. } else {
  168. crytoKeyName = response.Name + "/cryptoKeyVersions/1"
  169. }
  170. // Retrieve public key to add it to the response.
  171. pk, err := k.GetPublicKey(&apiv1.GetPublicKeyRequest{
  172. Name: crytoKeyName,
  173. })
  174. if err != nil {
  175. return nil, errors.Wrap(err, "cloudKMS GetPublicKey failed")
  176. }
  177. return &apiv1.CreateKeyResponse{
  178. Name: crytoKeyName,
  179. PublicKey: pk,
  180. CreateSignerRequest: apiv1.CreateSignerRequest{
  181. SigningKey: crytoKeyName,
  182. },
  183. }, nil
  184. }
  185. func (k *CloudKMS) createKeyRingIfNeeded(name string) error {
  186. ctx, cancel := defaultContext()
  187. defer cancel()
  188. _, err := k.client.GetKeyRing(ctx, &kmspb.GetKeyRingRequest{
  189. Name: name,
  190. })
  191. if err == nil {
  192. return nil
  193. }
  194. parent, child := Parent(name)
  195. _, err = k.client.CreateKeyRing(ctx, &kmspb.CreateKeyRingRequest{
  196. Parent: parent,
  197. KeyRingId: child,
  198. })
  199. if err != nil && status.Code(err) != codes.AlreadyExists {
  200. return errors.Wrap(err, "cloudKMS CreateKeyRing failed")
  201. }
  202. return nil
  203. }
  204. // GetPublicKey gets from Google's Cloud KMS a public key by name. Key names
  205. // follow the pattern:
  206. // projects/([^/]+)/locations/([a-zA-Z0-9_-]{1,63})/keyRings/([a-zA-Z0-9_-]{1,63})/cryptoKeys/([a-zA-Z0-9_-]{1,63})/cryptoKeyVersions/([a-zA-Z0-9_-]{1,63})
  207. func (k *CloudKMS) GetPublicKey(req *apiv1.GetPublicKeyRequest) (crypto.PublicKey, error) {
  208. if req.Name == "" {
  209. return nil, errors.New("createKeyRequest 'name' cannot be empty")
  210. }
  211. ctx, cancel := defaultContext()
  212. defer cancel()
  213. response, err := k.client.GetPublicKey(ctx, &kmspb.GetPublicKeyRequest{
  214. Name: req.Name,
  215. })
  216. if err != nil {
  217. return nil, errors.Wrap(err, "cloudKMS GetPublicKey failed")
  218. }
  219. pk, err := pemutil.ParseKey([]byte(response.Pem))
  220. if err != nil {
  221. return nil, err
  222. }
  223. return pk, nil
  224. }
  225. func defaultContext() (context.Context, context.CancelFunc) {
  226. return context.WithTimeout(context.Background(), 15*time.Second)
  227. }
  228. // Parent splits a string in the format `key/value/key2/value2` in a parent and
  229. // child, for the previous string it will return `key/value` and `value2`.
  230. func Parent(name string) (string, string) {
  231. a, b := parent(name)
  232. a, _ = parent(a)
  233. return a, b
  234. }
  235. func parent(name string) (string, string) {
  236. i := strings.LastIndex(name, "/")
  237. switch i {
  238. case -1:
  239. return "", name
  240. case 0:
  241. return "", name[i+1:]
  242. default:
  243. return name[:i], name[i+1:]
  244. }
  245. }