| 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 |
"encoding/csv" |
| 19 |
"errors" |
| 20 |
"fmt" |
| 21 |
"os" |
| 22 |
"regexp" |
| 23 |
"strconv" |
| 24 |
"strings" |
| 25 |
|
| 26 |
"github.com/aws/aws-sdk-go/aws" |
| 27 |
"github.com/aws/aws-sdk-go/aws/credentials" |
| 28 |
"github.com/aws/aws-sdk-go/aws/session" |
| 29 |
"github.com/aws/aws-sdk-go/service/kms" |
| 30 |
"github.com/aws/aws-sdk-go/service/kms/kmsiface" |
| 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 |
// awsClient is a wrapper around an AWS SDK provided KMS client that can |
| 46 |
// instantiate Tink primitives. |
| 47 |
type awsClient struct { |
| 48 |
keyURIPrefix string |
| 49 |
kms kmsiface.KMSAPI |
| 50 |
encryptionContextName EncryptionContextName |
| 51 |
} |
| 52 |
|
| 53 |
// ClientOption is an interface for defining options that are passed to |
| 54 |
// [NewClientWithOptions]. |
| 55 |
type ClientOption interface{ set(*awsClient) error } |
| 56 |
|
| 57 |
type option func(*awsClient) error |
| 58 |
|
| 59 |
func (o option) set(a *awsClient) error { return o(a) } |
| 60 |
|
| 61 |
// WithCredentialPath instantiates the underlying AWS KMS client using the |
| 62 |
// credentials located at credentialPath. |
| 63 |
// |
| 64 |
// credentialPath can specify a file in CSV format as provided in the IAM |
| 65 |
// console or an INI-style credentials file. |
| 66 |
// |
| 67 |
// See https://docs.aws.amazon.com/cli/latest/userguide/cli-authentication-user.html#cli-authentication-user-configure-csv |
| 68 |
// and https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-format. |
| 69 |
func WithCredentialPath(credentialPath string) ClientOption { |
| 70 |
return option(func(a *awsClient) error { |
| 71 |
if a.kms != nil { |
| 72 |
return errors.New("WithCredentialPath option cannot be used, KMS client already set") |
| 73 |
} |
| 74 |
|
| 75 |
k, err := getKMSFromCredentialPath(a.keyURIPrefix, credentialPath) |
| 76 |
if err != nil { |
| 77 |
return err |
| 78 |
} |
| 79 |
|
| 80 |
a.kms = k |
| 81 |
return nil |
| 82 |
}) |
| 83 |
} |
| 84 |
|
| 85 |
// WithKMS sets the underlying AWS KMS client to kms, a preexisting AWS KMS |
| 86 |
// client instance. |
| 87 |
// |
| 88 |
// It's the callers responsibility to ensure that the configured region of kms |
| 89 |
// aligns with the region in key URIs passed to this client. Otherwise, API |
| 90 |
// requests will fail. |
| 91 |
func WithKMS(kms kmsiface.KMSAPI) ClientOption { |
| 92 |
return option(func(a *awsClient) error { |
| 93 |
if a.kms != nil { |
| 94 |
return errors.New("WithKMS option cannot be used, KMS client already set") |
| 95 |
} |
| 96 |
a.kms = kms |
| 97 |
return nil |
| 98 |
}) |
| 99 |
} |
| 100 |
|
| 101 |
// EncryptionContextName specifies the name used in the EncryptionContext field |
| 102 |
// of EncryptInput and DecryptInput requests. See [WithEncryptionContextName] |
| 103 |
// for further details. |
| 104 |
type EncryptionContextName uint |
| 105 |
|
| 106 |
const ( |
| 107 |
// AssociatedData will set the EncryptionContext name to "associatedData". |
| 108 |
AssociatedData EncryptionContextName = 1 + iota |
| 109 |
// LegacyAdditionalData will set the EncryptionContext name to "additionalData". |
| 110 |
LegacyAdditionalData |
| 111 |
) |
| 112 |
|
| 113 |
var encryptionContextNames = map[EncryptionContextName]string{ |
| 114 |
AssociatedData: "associatedData", |
| 115 |
LegacyAdditionalData: "additionalData", |
| 116 |
} |
| 117 |
|
| 118 |
func (n EncryptionContextName) valid() bool { |
| 119 |
_, ok := encryptionContextNames[n] |
| 120 |
return ok |
| 121 |
} |
| 122 |
|
| 123 |
func (n EncryptionContextName) String() string { |
| 124 |
if !n.valid() { |
| 125 |
return "unrecognized value " + strconv.Itoa(int(n)) |
| 126 |
} |
| 127 |
return encryptionContextNames[n] |
| 128 |
} |
| 129 |
|
| 130 |
// WithEncryptionContextName sets the name which maps to the base64 encoded |
| 131 |
// associated data within the EncryptionContext field of EncrypInput and |
| 132 |
// DecryptInput requests. |
| 133 |
// |
| 134 |
// The default is [AssociatedData], which is compatible with the Tink AWS KMS |
| 135 |
// extensions in other languages. In older versions of this packge, before this |
| 136 |
// option was present, "additionalData" was hardcoded. |
| 137 |
// |
| 138 |
// This option is provided to facilitate compatibility with older ciphertexts. |
| 139 |
func WithEncryptionContextName(name EncryptionContextName) ClientOption { |
| 140 |
return option(func(a *awsClient) error { |
| 141 |
if !name.valid() { |
| 142 |
return fmt.Errorf("invalid EncryptionContextName: %v", name) |
| 143 |
} |
| 144 |
if a.encryptionContextName != 0 { |
| 145 |
return errors.New("encryptionContextName already set") |
| 146 |
} |
| 147 |
a.encryptionContextName = name |
| 148 |
return nil |
| 149 |
}) |
| 150 |
} |
| 151 |
|
| 152 |
// NewClientWithOptions returns a [registry.KMSClient] which wraps an AWS KMS |
| 153 |
// client and will handle keys whose URIs start with uriPrefix. |
| 154 |
// |
| 155 |
// By default, the client will use default credentials. |
| 156 |
// |
| 157 |
// AEAD primitives produced by this client will use [AssociatedData] when |
| 158 |
// serializing associated data. |
| 159 |
func NewClientWithOptions(uriPrefix string, opts ...ClientOption) (registry.KMSClient, 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(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(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 |
// NewClient returns a KMSClient backed by AWS KMS using default credentials to |
| 191 |
// handle keys whose URIs start with uriPrefix. |
| 192 |
// |
| 193 |
// uriPrefix must have the following format: |
| 194 |
// |
| 195 |
// aws-kms://arn:<partition>:kms:<region>:[<path>] |
| 196 |
// |
| 197 |
// See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference-arns.html |
| 198 |
// |
| 199 |
// AEAD primitives produced by this client will use [LegacyAdditionalData] when |
| 200 |
// serializing associated data. |
| 201 |
// |
| 202 |
// Deprecated: Instead, use [NewClientWithOptions]. |
| 203 |
// |
| 204 |
// awskms.NewClientWithOptions(uriPrefix) |
| 205 |
func NewClient(uriPrefix string) (registry.KMSClient, error) { |
| 206 |
return NewClientWithOptions(uriPrefix, WithEncryptionContextName(LegacyAdditionalData)) |
| 207 |
} |
| 208 |
|
| 209 |
// NewClientWithCredentials returns a KMSClient backed by AWS KMS using the given |
| 210 |
// credentials to handle keys whose URIs start with uriPrefix. |
| 211 |
// |
| 212 |
// uriPrefix must have the following format: |
| 213 |
// |
| 214 |
// aws-kms://arn:<partition>:kms:<region>:[<path>] |
| 215 |
// |
| 216 |
// See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference-arns.html |
| 217 |
// |
| 218 |
// credentialPath can specify a file in CSV format as provided in the IAM |
| 219 |
// console or an INI-style credentials file. |
| 220 |
// |
| 221 |
// See https://docs.aws.amazon.com/cli/latest/userguide/cli-authentication-user.html#cli-authentication-user-configure-csv |
| 222 |
// and https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-format. |
| 223 |
// |
| 224 |
// AEAD primitives produced by this client will use [LegacyAdditionalData] when |
| 225 |
// serializing associated data. |
| 226 |
// |
| 227 |
// Deprecated: Instead use [NewClientWithOptions] and [WithCredentialPath]. |
| 228 |
// |
| 229 |
// awskms.NewClientWithOptions(uriPrefix, awskms.WithCredentialPath(credentialPath)) |
| 230 |
func NewClientWithCredentials(uriPrefix string, credentialPath string) (registry.KMSClient, error) { |
| 231 |
return NewClientWithOptions(uriPrefix, WithCredentialPath(credentialPath), WithEncryptionContextName(LegacyAdditionalData)) |
| 232 |
} |
| 233 |
|
| 234 |
// NewClientWithKMS returns a KMSClient backed by AWS KMS using the provided |
| 235 |
// instance of the AWS SDK KMS client. |
| 236 |
// |
| 237 |
// The caller is responsible for ensuring that the region specified in the KMS |
| 238 |
// client is consitent with the region specified within uriPrefix. |
| 239 |
// |
| 240 |
// uriPrefix must have the following format: |
| 241 |
// |
| 242 |
// aws-kms://arn:<partition>:kms:<region>:[<path>] |
| 243 |
// |
| 244 |
// See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference-arns.html |
| 245 |
// |
| 246 |
// AEAD primitives produced by this client will use [LegacyAdditionalData] when |
| 247 |
// serializing associated data. |
| 248 |
// |
| 249 |
// Deprecated: Instead use [NewClientWithOptions] and [WithKMS]. |
| 250 |
// |
| 251 |
// awskms.NewClientWithOptions(uriPrefix, awskms.WithKMS(kms)) |
| 252 |
func NewClientWithKMS(uriPrefix string, kms kmsiface.KMSAPI) (registry.KMSClient, error) { |
| 253 |
return NewClientWithOptions(uriPrefix, WithKMS(kms), WithEncryptionContextName(LegacyAdditionalData)) |
| 254 |
} |
| 255 |
|
| 256 |
// Supported returns true if keyURI starts with the URI prefix provided when |
| 257 |
// creating the client. |
| 258 |
func (c *awsClient) Supported(keyURI string) bool { |
| 259 |
return strings.HasPrefix(keyURI, c.keyURIPrefix) |
| 260 |
} |
| 261 |
|
| 262 |
// GetAEAD returns an implementation of the AEAD interface which performs |
| 263 |
// cryptographic operations remotely via AWS KMS using keyURI. |
| 264 |
// |
| 265 |
// keyURI must be supported by this client and must have the following format: |
| 266 |
// |
| 267 |
// aws-kms://arn:<partition>:kms:<region>:<path> |
| 268 |
// |
| 269 |
// See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference-arns.html |
| 270 |
func (c *awsClient) GetAEAD(keyURI string) (tink.AEAD, error) { |
| 271 |
if !c.Supported(keyURI) { |
| 272 |
return nil, fmt.Errorf("keyURI must start with prefix %s, but got %s", c.keyURIPrefix, keyURI) |
| 273 |
} |
| 274 |
|
| 275 |
keyID := strings.TrimPrefix(keyURI, awsPrefix) |
| 276 |
return newAWSAEAD(keyID, c.kms, c.encryptionContextName), nil |
| 277 |
} |
| 278 |
|
| 279 |
func getKMS(uriPrefix string) (*kms.KMS, error) { |
| 280 |
r, err := getRegion(uriPrefix) |
| 281 |
if err != nil { |
| 282 |
return nil, err |
| 283 |
} |
| 284 |
|
| 285 |
session, err := session.NewSession(&aws.Config{ |
| 286 |
Region: aws.String(r), |
| 287 |
}) |
| 288 |
if err != nil { |
| 289 |
return nil, err |
| 290 |
} |
| 291 |
|
| 292 |
return kms.New(session), nil |
| 293 |
} |
| 294 |
|
| 295 |
func getKMSFromCredentialPath(uriPrefix string, credentialPath string) (*kms.KMS, error) { |
| 296 |
r, err := getRegion(uriPrefix) |
| 297 |
if err != nil { |
| 298 |
return nil, err |
| 299 |
} |
| 300 |
|
| 301 |
var creds *credentials.Credentials |
| 302 |
if len(credentialPath) == 0 { |
| 303 |
return nil, errCred |
| 304 |
} |
| 305 |
c, err := extractCredsCSV(credentialPath) |
| 306 |
switch err { |
| 307 |
case nil: |
| 308 |
creds = credentials.NewStaticCredentialsFromCreds(*c) |
| 309 |
case errBadFile, errCredCSV: |
| 310 |
return nil, err |
| 311 |
default: |
| 312 |
// Fallback to load the credential path as .ini shared credentials. |
| 313 |
creds = credentials.NewSharedCredentials(credentialPath, "default") |
| 314 |
} |
| 315 |
|
| 316 |
session, err := session.NewSession(&aws.Config{ |
| 317 |
Credentials: creds, |
| 318 |
Region: aws.String(r), |
| 319 |
}) |
| 320 |
if err != nil { |
| 321 |
return nil, err |
| 322 |
} |
| 323 |
|
| 324 |
return kms.New(session), nil |
| 325 |
} |
| 326 |
|
| 327 |
// extractCredsCSV extracts credentials from a CSV file. |
| 328 |
// |
| 329 |
// A CSV formatted credentials file can be obtained when an AWS IAM user is |
| 330 |
// created through the IAM console. |
| 331 |
// |
| 332 |
// Properties of a properly formatted CSV file: |
| 333 |
// |
| 334 |
// 1. The first line consists of the headers: |
| 335 |
// "User name,Password,Access key ID,Secret access key,Console login link" |
| 336 |
// 2. The second line contains 5 comma separated values. |
| 337 |
func extractCredsCSV(file string) (*credentials.Value, error) { |
| 338 |
f, err := os.Open(file) |
| 339 |
if err != nil { |
| 340 |
return nil, errBadFile |
| 341 |
} |
| 342 |
defer f.Close() |
| 343 |
|
| 344 |
lines, err := csv.NewReader(f).ReadAll() |
| 345 |
if err != nil { |
| 346 |
return nil, err |
| 347 |
} |
| 348 |
|
| 349 |
// It is possible that the file is an AWS .ini credential file, and it can be |
| 350 |
// parsed as 1-column CSV file as well. A real AWS credentials.csv is never 1 column. |
| 351 |
if len(lines) > 0 && len(lines[0]) == 1 { |
| 352 |
return nil, errors.New("not a valid CSV credential file") |
| 353 |
} |
| 354 |
|
| 355 |
if len(lines) < 2 { |
| 356 |
return nil, errCredCSV |
| 357 |
} |
| 358 |
|
| 359 |
if len(lines[1]) < 4 { |
| 360 |
return nil, errCredCSV |
| 361 |
} |
| 362 |
|
| 363 |
return &credentials.Value{ |
| 364 |
AccessKeyID: lines[1][2], |
| 365 |
SecretAccessKey: lines[1][3], |
| 366 |
}, nil |
| 367 |
} |
| 368 |
|
| 369 |
// getRegion extracts the region from keyURI. |
| 370 |
func getRegion(keyURI string) (string, error) { |
| 371 |
re1, err := regexp.Compile(`aws-kms://arn:(aws[a-zA-Z0-9-_]*):kms:([a-z0-9-]+):`) |
| 372 |
if err != nil { |
| 373 |
return "", err |
| 374 |
} |
| 375 |
r := re1.FindStringSubmatch(keyURI) |
| 376 |
if len(r) != 3 { |
| 377 |
return "", errors.New("extracting region from URI failed") |
| 378 |
} |
| 379 |
return r[2], nil |
| 380 |
} |