cloudkms.go 11 KB

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