File: awskms.go

package info (click to toggle)
golang-github-smallstep-certificates 0.20.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 23,144 kB
  • sloc: sh: 278; makefile: 170
file content (267 lines) | stat: -rw-r--r-- 7,771 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package awskms

import (
	"context"
	"crypto"
	"net/url"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/request"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/kms"
	"github.com/pkg/errors"
	"github.com/smallstep/certificates/kms/apiv1"
	"github.com/smallstep/certificates/kms/uri"
	"go.step.sm/crypto/pemutil"
)

// Scheme is the scheme used in uris.
const Scheme = "awskms"

// KMS implements a KMS using AWS Key Management Service.
type KMS struct {
	session *session.Session
	service KeyManagementClient
}

// KeyManagementClient defines the methods on KeyManagementClient that this
// package will use. This interface will be used for unit testing.
type KeyManagementClient interface {
	GetPublicKeyWithContext(ctx aws.Context, input *kms.GetPublicKeyInput, opts ...request.Option) (*kms.GetPublicKeyOutput, error)
	CreateKeyWithContext(ctx aws.Context, input *kms.CreateKeyInput, opts ...request.Option) (*kms.CreateKeyOutput, error)
	CreateAliasWithContext(ctx aws.Context, input *kms.CreateAliasInput, opts ...request.Option) (*kms.CreateAliasOutput, error)
	SignWithContext(ctx aws.Context, input *kms.SignInput, opts ...request.Option) (*kms.SignOutput, error)
}

// customerMasterKeySpecMapping is a mapping between the step signature algorithm,
// and bits for RSA keys, with awskms CustomerMasterKeySpec.
var customerMasterKeySpecMapping = map[apiv1.SignatureAlgorithm]interface{}{
	apiv1.UnspecifiedSignAlgorithm: kms.CustomerMasterKeySpecEccNistP256,
	apiv1.SHA256WithRSA: map[int]string{
		0:    kms.CustomerMasterKeySpecRsa3072,
		2048: kms.CustomerMasterKeySpecRsa2048,
		3072: kms.CustomerMasterKeySpecRsa3072,
		4096: kms.CustomerMasterKeySpecRsa4096,
	},
	apiv1.SHA512WithRSA: map[int]string{
		0:    kms.CustomerMasterKeySpecRsa4096,
		4096: kms.CustomerMasterKeySpecRsa4096,
	},
	apiv1.SHA256WithRSAPSS: map[int]string{
		0:    kms.CustomerMasterKeySpecRsa3072,
		2048: kms.CustomerMasterKeySpecRsa2048,
		3072: kms.CustomerMasterKeySpecRsa3072,
		4096: kms.CustomerMasterKeySpecRsa4096,
	},
	apiv1.SHA512WithRSAPSS: map[int]string{
		0:    kms.CustomerMasterKeySpecRsa4096,
		4096: kms.CustomerMasterKeySpecRsa4096,
	},
	apiv1.ECDSAWithSHA256: kms.CustomerMasterKeySpecEccNistP256,
	apiv1.ECDSAWithSHA384: kms.CustomerMasterKeySpecEccNistP384,
	apiv1.ECDSAWithSHA512: kms.CustomerMasterKeySpecEccNistP521,
}

// New creates a new AWSKMS. By default, sessions will be created using the
// credentials in `~/.aws/credentials`, but this can be overridden using the
// CredentialsFile option, the Region and Profile can also be configured as
// options.
//
// AWS sessions can also be configured with environment variables, see docs at
// https://docs.aws.amazon.com/sdk-for-go/api/aws/session/ for all the options.
func New(ctx context.Context, opts apiv1.Options) (*KMS, error) {
	var o session.Options

	if opts.URI != "" {
		u, err := uri.ParseWithScheme(Scheme, opts.URI)
		if err != nil {
			return nil, err
		}
		o.Profile = u.Get("profile")
		if v := u.Get("region"); v != "" {
			o.Config.Region = new(string)
			*o.Config.Region = v
		}
		if f := u.Get("credentials-file"); f != "" {
			o.SharedConfigFiles = []string{f}
		}
	}

	// Deprecated way to set configuration parameters.
	if opts.Region != "" {
		o.Config.Region = &opts.Region
	}
	if opts.Profile != "" {
		o.Profile = opts.Profile
	}
	if opts.CredentialsFile != "" {
		o.SharedConfigFiles = []string{opts.CredentialsFile}
	}

	sess, err := session.NewSessionWithOptions(o)
	if err != nil {
		return nil, errors.Wrap(err, "error creating AWS session")
	}

	return &KMS{
		session: sess,
		service: kms.New(sess),
	}, nil
}

func init() {
	apiv1.Register(apiv1.AmazonKMS, func(ctx context.Context, opts apiv1.Options) (apiv1.KeyManager, error) {
		return New(ctx, opts)
	})
}

// GetPublicKey returns a public key from KMS.
func (k *KMS) GetPublicKey(req *apiv1.GetPublicKeyRequest) (crypto.PublicKey, error) {
	if req.Name == "" {
		return nil, errors.New("getPublicKey 'name' cannot be empty")
	}
	keyID, err := parseKeyID(req.Name)
	if err != nil {
		return nil, err
	}

	ctx, cancel := defaultContext()
	defer cancel()

	resp, err := k.service.GetPublicKeyWithContext(ctx, &kms.GetPublicKeyInput{
		KeyId: &keyID,
	})
	if err != nil {
		return nil, errors.Wrap(err, "awskms GetPublicKeyWithContext failed")
	}

	return pemutil.ParseDER(resp.PublicKey)
}

// CreateKey generates a new key in KMS and returns the public key version
// of it.
func (k *KMS) CreateKey(req *apiv1.CreateKeyRequest) (*apiv1.CreateKeyResponse, error) {
	if req.Name == "" {
		return nil, errors.New("createKeyRequest 'name' cannot be empty")
	}

	keySpec, err := getCustomerMasterKeySpecMapping(req.SignatureAlgorithm, req.Bits)
	if err != nil {
		return nil, err
	}

	tag := new(kms.Tag)
	tag.SetTagKey("name")
	tag.SetTagValue(req.Name)

	input := &kms.CreateKeyInput{
		Description:           &req.Name,
		CustomerMasterKeySpec: &keySpec,
		Tags:                  []*kms.Tag{tag},
	}
	input.SetKeyUsage(kms.KeyUsageTypeSignVerify)

	ctx, cancel := defaultContext()
	defer cancel()

	resp, err := k.service.CreateKeyWithContext(ctx, input)
	if err != nil {
		return nil, errors.Wrap(err, "awskms CreateKeyWithContext failed")
	}
	if err := k.createKeyAlias(*resp.KeyMetadata.KeyId, req.Name); err != nil {
		return nil, err
	}

	// Create uri for key
	name := uri.New("awskms", url.Values{
		"key-id": []string{*resp.KeyMetadata.KeyId},
	}).String()

	publicKey, err := k.GetPublicKey(&apiv1.GetPublicKeyRequest{
		Name: name,
	})
	if err != nil {
		return nil, err
	}

	// Names uses Amazon Resource Name
	// https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html
	return &apiv1.CreateKeyResponse{
		Name:      name,
		PublicKey: publicKey,
		CreateSignerRequest: apiv1.CreateSignerRequest{
			SigningKey: name,
		},
	}, nil
}

func (k *KMS) createKeyAlias(keyID, alias string) error {
	alias = "alias/" + alias + "-" + keyID[:8]

	ctx, cancel := defaultContext()
	defer cancel()

	_, err := k.service.CreateAliasWithContext(ctx, &kms.CreateAliasInput{
		AliasName:   &alias,
		TargetKeyId: &keyID,
	})
	if err != nil {
		return errors.Wrap(err, "awskms CreateAliasWithContext failed")
	}
	return nil
}

// CreateSigner creates a new crypto.Signer with a previously configured key.
func (k *KMS) CreateSigner(req *apiv1.CreateSignerRequest) (crypto.Signer, error) {
	if req.SigningKey == "" {
		return nil, errors.New("createSigner 'signingKey' cannot be empty")
	}
	return NewSigner(k.service, req.SigningKey)
}

// Close closes the connection of the KMS client.
func (k *KMS) Close() error {
	return nil
}

func defaultContext() (context.Context, context.CancelFunc) {
	return context.WithTimeout(context.Background(), 15*time.Second)
}

// parseKeyID extracts the key-id from an uri.
func parseKeyID(name string) (string, error) {
	name = strings.ToLower(name)
	if strings.HasPrefix(name, "awskms:") || strings.HasPrefix(name, "aws:") {
		u, err := uri.Parse(name)
		if err != nil {
			return "", err
		}
		if k := u.Get("key-id"); k != "" {
			return k, nil
		}
		return "", errors.Errorf("failed to get key-id from %s", name)
	}
	return name, nil
}

func getCustomerMasterKeySpecMapping(alg apiv1.SignatureAlgorithm, bits int) (string, error) {
	v, ok := customerMasterKeySpecMapping[alg]
	if !ok {
		return "", errors.Errorf("awskms does not support signature algorithm '%s'", alg)
	}

	switch v := v.(type) {
	case string:
		return v, nil
	case map[int]string:
		s, ok := v[bits]
		if !ok {
			return "", errors.Errorf("awskms does not support signature algorithm '%s' with '%d' bits", alg, bits)
		}
		return s, nil
	default:
		return "", errors.Errorf("unexpected error: this should not happen")
	}
}