awskms.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. package awskms
  2. import (
  3. "context"
  4. "crypto"
  5. "net/url"
  6. "strings"
  7. "time"
  8. "github.com/aws/aws-sdk-go/aws"
  9. "github.com/aws/aws-sdk-go/aws/request"
  10. "github.com/aws/aws-sdk-go/aws/session"
  11. "github.com/aws/aws-sdk-go/service/kms"
  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. )
  17. // Scheme is the scheme used in uris.
  18. const Scheme = "awskms"
  19. // KMS implements a KMS using AWS Key Management Service.
  20. type KMS struct {
  21. session *session.Session
  22. service KeyManagementClient
  23. }
  24. // KeyManagementClient defines the methods on KeyManagementClient that this
  25. // package will use. This interface will be used for unit testing.
  26. type KeyManagementClient interface {
  27. GetPublicKeyWithContext(ctx aws.Context, input *kms.GetPublicKeyInput, opts ...request.Option) (*kms.GetPublicKeyOutput, error)
  28. CreateKeyWithContext(ctx aws.Context, input *kms.CreateKeyInput, opts ...request.Option) (*kms.CreateKeyOutput, error)
  29. CreateAliasWithContext(ctx aws.Context, input *kms.CreateAliasInput, opts ...request.Option) (*kms.CreateAliasOutput, error)
  30. SignWithContext(ctx aws.Context, input *kms.SignInput, opts ...request.Option) (*kms.SignOutput, error)
  31. }
  32. // customerMasterKeySpecMapping is a mapping between the step signature algorithm,
  33. // and bits for RSA keys, with awskms CustomerMasterKeySpec.
  34. var customerMasterKeySpecMapping = map[apiv1.SignatureAlgorithm]interface{}{
  35. apiv1.UnspecifiedSignAlgorithm: kms.CustomerMasterKeySpecEccNistP256,
  36. apiv1.SHA256WithRSA: map[int]string{
  37. 0: kms.CustomerMasterKeySpecRsa3072,
  38. 2048: kms.CustomerMasterKeySpecRsa2048,
  39. 3072: kms.CustomerMasterKeySpecRsa3072,
  40. 4096: kms.CustomerMasterKeySpecRsa4096,
  41. },
  42. apiv1.SHA512WithRSA: map[int]string{
  43. 0: kms.CustomerMasterKeySpecRsa4096,
  44. 4096: kms.CustomerMasterKeySpecRsa4096,
  45. },
  46. apiv1.SHA256WithRSAPSS: map[int]string{
  47. 0: kms.CustomerMasterKeySpecRsa3072,
  48. 2048: kms.CustomerMasterKeySpecRsa2048,
  49. 3072: kms.CustomerMasterKeySpecRsa3072,
  50. 4096: kms.CustomerMasterKeySpecRsa4096,
  51. },
  52. apiv1.SHA512WithRSAPSS: map[int]string{
  53. 0: kms.CustomerMasterKeySpecRsa4096,
  54. 4096: kms.CustomerMasterKeySpecRsa4096,
  55. },
  56. apiv1.ECDSAWithSHA256: kms.CustomerMasterKeySpecEccNistP256,
  57. apiv1.ECDSAWithSHA384: kms.CustomerMasterKeySpecEccNistP384,
  58. apiv1.ECDSAWithSHA512: kms.CustomerMasterKeySpecEccNistP521,
  59. }
  60. // New creates a new AWSKMS. By default, sessions will be created using the
  61. // credentials in `~/.aws/credentials`, but this can be overridden using the
  62. // CredentialsFile option, the Region and Profile can also be configured as
  63. // options.
  64. //
  65. // AWS sessions can also be configured with environment variables, see docs at
  66. // https://docs.aws.amazon.com/sdk-for-go/api/aws/session/ for all the options.
  67. func New(ctx context.Context, opts apiv1.Options) (*KMS, error) {
  68. var o session.Options
  69. if opts.URI != "" {
  70. u, err := uri.ParseWithScheme(Scheme, opts.URI)
  71. if err != nil {
  72. return nil, err
  73. }
  74. o.Profile = u.Get("profile")
  75. if v := u.Get("region"); v != "" {
  76. o.Config.Region = new(string)
  77. *o.Config.Region = v
  78. }
  79. if f := u.Get("credentials-file"); f != "" {
  80. o.SharedConfigFiles = []string{f}
  81. }
  82. }
  83. // Deprecated way to set configuration parameters.
  84. if opts.Region != "" {
  85. o.Config.Region = &opts.Region
  86. }
  87. if opts.Profile != "" {
  88. o.Profile = opts.Profile
  89. }
  90. if opts.CredentialsFile != "" {
  91. o.SharedConfigFiles = []string{opts.CredentialsFile}
  92. }
  93. sess, err := session.NewSessionWithOptions(o)
  94. if err != nil {
  95. return nil, errors.Wrap(err, "error creating AWS session")
  96. }
  97. return &KMS{
  98. session: sess,
  99. service: kms.New(sess),
  100. }, nil
  101. }
  102. func init() {
  103. apiv1.Register(apiv1.AmazonKMS, func(ctx context.Context, opts apiv1.Options) (apiv1.KeyManager, error) {
  104. return New(ctx, opts)
  105. })
  106. }
  107. // GetPublicKey returns a public key from KMS.
  108. func (k *KMS) GetPublicKey(req *apiv1.GetPublicKeyRequest) (crypto.PublicKey, error) {
  109. if req.Name == "" {
  110. return nil, errors.New("getPublicKey 'name' cannot be empty")
  111. }
  112. keyID, err := parseKeyID(req.Name)
  113. if err != nil {
  114. return nil, err
  115. }
  116. ctx, cancel := defaultContext()
  117. defer cancel()
  118. resp, err := k.service.GetPublicKeyWithContext(ctx, &kms.GetPublicKeyInput{
  119. KeyId: &keyID,
  120. })
  121. if err != nil {
  122. return nil, errors.Wrap(err, "awskms GetPublicKeyWithContext failed")
  123. }
  124. return pemutil.ParseDER(resp.PublicKey)
  125. }
  126. // CreateKey generates a new key in KMS and returns the public key version
  127. // of it.
  128. func (k *KMS) CreateKey(req *apiv1.CreateKeyRequest) (*apiv1.CreateKeyResponse, error) {
  129. if req.Name == "" {
  130. return nil, errors.New("createKeyRequest 'name' cannot be empty")
  131. }
  132. keySpec, err := getCustomerMasterKeySpecMapping(req.SignatureAlgorithm, req.Bits)
  133. if err != nil {
  134. return nil, err
  135. }
  136. tag := new(kms.Tag)
  137. tag.SetTagKey("name")
  138. tag.SetTagValue(req.Name)
  139. input := &kms.CreateKeyInput{
  140. Description: &req.Name,
  141. CustomerMasterKeySpec: &keySpec,
  142. Tags: []*kms.Tag{tag},
  143. }
  144. input.SetKeyUsage(kms.KeyUsageTypeSignVerify)
  145. ctx, cancel := defaultContext()
  146. defer cancel()
  147. resp, err := k.service.CreateKeyWithContext(ctx, input)
  148. if err != nil {
  149. return nil, errors.Wrap(err, "awskms CreateKeyWithContext failed")
  150. }
  151. if err := k.createKeyAlias(*resp.KeyMetadata.KeyId, req.Name); err != nil {
  152. return nil, err
  153. }
  154. // Create uri for key
  155. name := uri.New("awskms", url.Values{
  156. "key-id": []string{*resp.KeyMetadata.KeyId},
  157. }).String()
  158. publicKey, err := k.GetPublicKey(&apiv1.GetPublicKeyRequest{
  159. Name: name,
  160. })
  161. if err != nil {
  162. return nil, err
  163. }
  164. // Names uses Amazon Resource Name
  165. // https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html
  166. return &apiv1.CreateKeyResponse{
  167. Name: name,
  168. PublicKey: publicKey,
  169. CreateSignerRequest: apiv1.CreateSignerRequest{
  170. SigningKey: name,
  171. },
  172. }, nil
  173. }
  174. func (k *KMS) createKeyAlias(keyID, alias string) error {
  175. alias = "alias/" + alias + "-" + keyID[:8]
  176. ctx, cancel := defaultContext()
  177. defer cancel()
  178. _, err := k.service.CreateAliasWithContext(ctx, &kms.CreateAliasInput{
  179. AliasName: &alias,
  180. TargetKeyId: &keyID,
  181. })
  182. if err != nil {
  183. return errors.Wrap(err, "awskms CreateAliasWithContext failed")
  184. }
  185. return nil
  186. }
  187. // CreateSigner creates a new crypto.Signer with a previously configured key.
  188. func (k *KMS) CreateSigner(req *apiv1.CreateSignerRequest) (crypto.Signer, error) {
  189. if req.SigningKey == "" {
  190. return nil, errors.New("createSigner 'signingKey' cannot be empty")
  191. }
  192. return NewSigner(k.service, req.SigningKey)
  193. }
  194. // Close closes the connection of the KMS client.
  195. func (k *KMS) Close() error {
  196. return nil
  197. }
  198. func defaultContext() (context.Context, context.CancelFunc) {
  199. return context.WithTimeout(context.Background(), 15*time.Second)
  200. }
  201. // parseKeyID extracts the key-id from an uri.
  202. func parseKeyID(name string) (string, error) {
  203. name = strings.ToLower(name)
  204. if strings.HasPrefix(name, "awskms:") || strings.HasPrefix(name, "aws:") {
  205. u, err := uri.Parse(name)
  206. if err != nil {
  207. return "", err
  208. }
  209. if k := u.Get("key-id"); k != "" {
  210. return k, nil
  211. }
  212. return "", errors.Errorf("failed to get key-id from %s", name)
  213. }
  214. return name, nil
  215. }
  216. func getCustomerMasterKeySpecMapping(alg apiv1.SignatureAlgorithm, bits int) (string, error) {
  217. v, ok := customerMasterKeySpecMapping[alg]
  218. if !ok {
  219. return "", errors.Errorf("awskms does not support signature algorithm '%s'", alg)
  220. }
  221. switch v := v.(type) {
  222. case string:
  223. return v, nil
  224. case map[int]string:
  225. s, ok := v[bits]
  226. if !ok {
  227. return "", errors.Errorf("awskms does not support signature algorithm '%s' with '%d' bits", alg, bits)
  228. }
  229. return s, nil
  230. default:
  231. return "", errors.Errorf("unexpected error: this should not happen")
  232. }
  233. }