cloudkms.go 10 KB

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