Debian Codegraph @

v3/integration/awskms/aws_kms_client.go

raw symbols SCIP
1 // Copyright 2017 Google Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package awskms
16
17 import (
18 "context"
19 "encoding/csv"
20 "errors"
21 "fmt"
22 "os"
23 "regexp"
24 "strconv"
25 "strings"
26
27 "github.com/aws/aws-sdk-go-v2/config"
28 "github.com/aws/aws-sdk-go-v2/credentials"
29 "github.com/aws/aws-sdk-go-v2/service/kms"
30 "github.com/aws/aws-sdk-go-v2/aws"
31 "github.com/tink-crypto/tink-go/v2/core/registry"
32 "github.com/tink-crypto/tink-go/v2/tink"
33 )
34
35 const (
36 awsPrefix = "aws-kms://"
37 )
38
39 var (
40 errCred = errors.New("invalid credential path")
41 errBadFile = errors.New("cannot open credential path")
42 errCredCSV = errors.New("malformed credential CSV file")
43 )
44
45 // KMSAPI is a subset of the methods in the interface of *kms.Client that we use in this package.
46 type KMSAPI interface {
47 Encrypt(ctx context.Context, params *kms.EncryptInput, optFns ...func(*kms.Options)) (*kms.EncryptOutput, error)
48 Decrypt(ctx context.Context, params *kms.DecryptInput, optFns ...func(*kms.Options)) (*kms.DecryptOutput, error)
49 }
50
51 // awsClient is a wrapper around an AWS SDK provided KMS client that can
52 // instantiate Tink primitives.
53 type awsClient struct {
54 keyURIPrefix string
55 kms KMSAPI
56 encryptionContextName EncryptionContextName
57 }
58
59 // ClientOption is an interface for defining options that are passed to
60 // [NewClientWithOptions].
61 type ClientOption interface {
62 set(ctx context.Context, a *awsClient) error
63 }
64
65 type option func(ctx context.Context, a *awsClient) error
66
67 func (o option) set(ctx context.Context, a *awsClient) error { return o(ctx, a) }
68
69 // WithCredentialPath instantiates the underlying AWS KMS client using the
70 // credentials located at credentialPath.
71 //
72 // credentialPath can specify a file in CSV format as provided in the IAM
73 // console or an INI-style credentials file.
74 //
75 // See https://docs.aws.amazon.com/cli/latest/userguide/cli-authentication-user.html#cli-authentication-user-configure-csv
76 // and https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-format.
77 func WithCredentialPath(credentialPath string) ClientOption {
78 return option(func(ctx context.Context, a *awsClient) error {
79 if a.kms != nil {
80 return errors.New("WithCredentialPath option cannot be used, KMS client already set")
81 }
82
83 cfg, err := getConfigFromCredentialPath(ctx, a.keyURIPrefix, credentialPath)
84 if err != nil {
85 return err
86 }
87 a.kms = kms.NewFromConfig(cfg)
88 return nil
89 })
90 }
91
92 // WithKMS sets the underlying AWS KMS client to kms, a preexisting AWS KMS
93 // client instance.
94 //
95 // It's the callers responsibility to ensure that the configured region of kms
96 // aligns with the region in key URIs passed to this client. Otherwise, API
97 // requests will fail.
98 func WithKMS(kms KMSAPI) ClientOption {
99 return option(func(ctx context.Context, a *awsClient) error {
100 if a.kms != nil {
101 return errors.New("WithKMS option cannot be used, KMS client already set")
102 }
103 a.kms = kms
104 return nil
105 })
106 }
107
108 // EncryptionContextName specifies the name used in the EncryptionContext field
109 // of EncryptInput and DecryptInput requests. See [WithEncryptionContextName]
110 // for further details.
111 type EncryptionContextName uint
112
113 const (
114 // AssociatedData will set the EncryptionContext name to "associatedData".
115 AssociatedData EncryptionContextName = 1 + iota
116 // LegacyAdditionalData will set the EncryptionContext name to "additionalData".
117 LegacyAdditionalData
118 )
119
120 var encryptionContextNames = map[EncryptionContextName]string{
121 AssociatedData: "associatedData",
122 LegacyAdditionalData: "additionalData",
123 }
124
125 func (n EncryptionContextName) valid() bool {
126 _, ok := encryptionContextNames[n]
127 return ok
128 }
129
130 func (n EncryptionContextName) String() string {
131 if !n.valid() {
132 return "unrecognized value " + strconv.Itoa(int(n))
133 }
134 return encryptionContextNames[n]
135 }
136
137 // WithEncryptionContextName sets the name which maps to the base64 encoded
138 // associated data within the EncryptionContext field of EncrypInput and
139 // DecryptInput requests.
140 //
141 // The default is [AssociatedData], which is compatible with the Tink AWS KMS
142 // extensions in other languages. In older versions of this packge, before this
143 // option was present, "additionalData" was hardcoded.
144 //
145 // This option is provided to facilitate compatibility with older ciphertexts.
146 func WithEncryptionContextName(name EncryptionContextName) ClientOption {
147 return option(func(ctx context.Context, a *awsClient) error {
148 if !name.valid() {
149 return fmt.Errorf("invalid EncryptionContextName: %v", name)
150 }
151 if a.encryptionContextName != 0 {
152 return errors.New("encryptionContextName already set")
153 }
154 a.encryptionContextName = name
155 return nil
156 })
157 }
158
159 func newAWSClient(ctx context.Context, uriPrefix string, opts ...ClientOption) (*awsClient, error) {
160 if !strings.HasPrefix(strings.ToLower(uriPrefix), awsPrefix) {
161 return nil, fmt.Errorf("uriPrefix must start with %q, but got %q", awsPrefix, uriPrefix)
162 }
163
164 a := &awsClient{
165 keyURIPrefix: uriPrefix,
166 }
167
168 // Process options, if any.
169 for _, opt := range opts {
170 if err := opt.set(ctx, a); err != nil {
171 return nil, fmt.Errorf("failed setting option: %v", err)
172 }
173 }
174
175 // Populate values not defined via options.
176 if a.kms == nil {
177 k, err := getKMS(ctx, uriPrefix)
178 if err != nil {
179 return nil, err
180 }
181 a.kms = k
182 }
183 if a.encryptionContextName == 0 {
184 a.encryptionContextName = AssociatedData
185 }
186
187 return a, nil
188 }
189
190 // NewClientWithOptions returns a [registry.KMSClient] which wraps an AWS KMS
191 // client and will handle keys whose URIs start with uriPrefix.
192 //
193 // By default, the client will use default credentials.
194 //
195 // AEAD primitives produced by this client will use [AssociatedData] when
196 // serializing associated data.
197 func NewClientWithOptions(ctx context.Context, uriPrefix string, opts ...ClientOption) (registry.KMSClient, error) {
198 return newAWSClient(ctx, uriPrefix, opts...)
199 }
200
201 // NewClient returns a KMSClient backed by AWS KMS using default credentials to
202 // handle keys whose URIs start with uriPrefix.
203 //
204 // uriPrefix must have the following format:
205 //
206 // aws-kms://arn:<partition>:kms:<region>:[<path>]
207 //
208 // See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference-arns.html
209 //
210 // AEAD primitives produced by this client will use [LegacyAdditionalData] when
211 // serializing associated data.
212 //
213 // Deprecated: Instead, use [NewClientWithOptions].
214 //
215 // awskms.NewClientWithOptions(ctx, uriPrefix)
216 func NewClient(ctx context.Context, uriPrefix string) (registry.KMSClient, error) {
217 return NewClientWithOptions(ctx, uriPrefix, WithEncryptionContextName(LegacyAdditionalData))
218 }
219
220 // NewClientWithCredentials returns a KMSClient backed by AWS KMS using the given
221 // credentials to handle keys whose URIs start with uriPrefix.
222 //
223 // uriPrefix must have the following format:
224 //
225 // aws-kms://arn:<partition>:kms:<region>:[<path>]
226 //
227 // See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference-arns.html
228 //
229 // credentialPath can specify a file in CSV format as provided in the IAM
230 // console or an INI-style credentials file.
231 //
232 // See https://docs.aws.amazon.com/cli/latest/userguide/cli-authentication-user.html#cli-authentication-user-configure-csv
233 // and https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-format.
234 //
235 // AEAD primitives produced by this client will use [LegacyAdditionalData] when
236 // serializing associated data.
237 //
238 // Deprecated: Instead use [NewClientWithOptions] and [WithCredentialPath].
239 //
240 // awskms.NewClientWithOptions(ctx, uriPrefix, awskms.WithCredentialPath(credentialPath))
241 func NewClientWithCredentials(ctx context.Context, uriPrefix string, credentialPath string) (registry.KMSClient, error) {
242 return NewClientWithOptions(ctx, uriPrefix, WithCredentialPath(credentialPath), WithEncryptionContextName(LegacyAdditionalData))
243 }
244
245 // NewClientWithKMS returns a KMSClient backed by AWS KMS using the provided
246 // instance of the AWS SDK KMS client.
247 //
248 // The caller is responsible for ensuring that the region specified in the KMS
249 // client is consitent with the region specified within uriPrefix.
250 //
251 // uriPrefix must have the following format:
252 //
253 // aws-kms://arn:<partition>:kms:<region>:[<path>]
254 //
255 // See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference-arns.html
256 //
257 // AEAD primitives produced by this client will use [LegacyAdditionalData] when
258 // serializing associated data.
259 //
260 // Deprecated: Instead use [NewClientWithOptions] and [WithKMS].
261 //
262 // awskms.NewClientWithOptions(ctx, uriPrefix, awskms.WithKMS(kms))
263 func NewClientWithKMS(ctx context.Context, uriPrefix string, kms KMSAPI) (registry.KMSClient, error) {
264 return NewClientWithOptions(ctx, uriPrefix, WithKMS(kms), WithEncryptionContextName(LegacyAdditionalData))
265 }
266
267 // Supported returns true if keyURI starts with the URI prefix provided when
268 // creating the client.
269 func (c *awsClient) Supported(keyURI string) bool {
270 return strings.HasPrefix(keyURI, c.keyURIPrefix)
271 }
272
273 // GetAEAD returns an implementation of the AEAD interface which performs
274 // cryptographic operations remotely via AWS KMS using keyURI.
275 //
276 // keyURI must be supported by this client and must have the following format:
277 //
278 // aws-kms://arn:<partition>:kms:<region>:<path>
279 //
280 // See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference-arns.html
281 func (c *awsClient) GetAEAD(keyURI string) (tink.AEAD, error) {
282 if !c.Supported(keyURI) {
283 return nil, fmt.Errorf("keyURI must start with prefix %s, but got %s", c.keyURIPrefix, keyURI)
284 }
285
286 keyID := strings.TrimPrefix(keyURI, awsPrefix)
287 return newAWSAEAD(keyID, c.kms, c.encryptionContextName), nil
288 }
289
290 func getKMS(ctx context.Context, uriPrefix string) (*kms.Client, error) {
291 r, err := getRegion(uriPrefix)
292 if err != nil {
293 return nil, err
294 }
295
296 cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(r))
297 if err != nil {
298 return nil, err
299 }
300
301 return kms.NewFromConfig(cfg), nil
302 }
303
304 func getConfigFromCredentialPath(ctx context.Context, uriPrefix string, credentialPath string) (aws.Config, error) {
305 r, err := getRegion(uriPrefix)
306 if err != nil {
307 return aws.Config{}, err
308 }
309
310 if len(credentialPath) == 0 {
311 return aws.Config{}, errCred
312 }
313
314 // Attempt to load as static credentials from CSV
315 creds, err := extractCredsCSV(credentialPath)
316 switch err {
317 case nil:
318 return config.LoadDefaultConfig(ctx,
319 config.WithRegion(r),
320 config.WithCredentialsProvider(credentials.StaticCredentialsProvider{
321 Value: aws.Credentials{
322 AccessKeyID: creds.AccessKeyID,
323 SecretAccessKey: creds.SecretAccessKey,
324 },
325 }),
326 )
327 case errBadFile, errCredCSV:
328 return aws.Config{}, err
329 default:
330 // Fallback to load as shared credentials from INI file
331 return config.LoadDefaultConfig(ctx,
332 config.WithRegion(r),
333 config.WithSharedConfigProfile("default"),
334 config.WithSharedConfigFiles([]string{credentialPath}),
335 )
336 }
337 }
338
339 // extractCredsCSV extracts credentials from a CSV file.
340 //
341 // A CSV formatted credentials file can be obtained when an AWS IAM user is
342 // created through the IAM console.
343 //
344 // Properties of a properly formatted CSV file:
345 //
346 // 1. The first line consists of the headers:
347 // "User name,Password,Access key ID,Secret access key,Console login link"
348 // 2. The second line contains 5 comma separated values.
349 func extractCredsCSV(file string) (*aws.Credentials, error) {
350 f, err := os.Open(file)
351 if err != nil {
352 return nil, errBadFile
353 }
354 defer f.Close()
355
356 lines, err := csv.NewReader(f).ReadAll()
357 if err != nil {
358 return nil, err
359 }
360
361 // It is possible that the file is an AWS .ini credential file, and it can be
362 // parsed as 1-column CSV file as well. A real AWS credentials.csv is never 1 column.
363 if len(lines) > 0 && len(lines[0]) == 1 {
364 return nil, errors.New("not a valid CSV credential file")
365 }
366
367 if len(lines) < 2 {
368 return nil, errCredCSV
369 }
370
371 if len(lines[1]) < 4 {
372 return nil, errCredCSV
373 }
374
375 return &aws.Credentials{
376 AccessKeyID: lines[1][2],
377 SecretAccessKey: lines[1][3],
378 },
379 nil
380 }
381
382 // getRegion extracts the region from keyURI.
383 func getRegion(keyURI string) (string, error) {
384 re1, err := regexp.Compile(`aws-kms://arn:(aws[a-zA-Z0-9-_]*):kms:([a-z0-9-]+):`)
385 if err != nil {
386 return "", err
387 }
388 r := re1.FindStringSubmatch(keyURI)
389 if len(r) != 3 {
390 return "", errors.New("extracting region from URI failed")
391 }
392 return r[2], nil
393 }