cloudkms.go 12 KB

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