|
| 1 | +# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"). You |
| 4 | +# may not use this file except in compliance with the License. A copy of |
| 5 | +# the License is located at |
| 6 | +# |
| 7 | +# http://aws.amazon.com/apache2.0/ |
| 8 | +# |
| 9 | +# or in the "license" file accompanying this file. This file is |
| 10 | +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF |
| 11 | +# ANY KIND, either express or implied. See the License for the specific |
| 12 | +# language governing permissions and limitations under the License. |
| 13 | +"""Meta cryptographic provider store.""" |
| 14 | +from enum import Enum |
| 15 | + |
| 16 | +import attr |
| 17 | +from boto3.dynamodb.conditions import Attr, Key |
| 18 | +from boto3.dynamodb.types import Binary |
| 19 | +import botocore |
| 20 | + |
| 21 | +try: # Python 3.5.0 and 3.5.1 have incompatible typing modules |
| 22 | + from typing import Dict, Optional, Text, Tuple # noqa pylint: disable=unused-import |
| 23 | +except ImportError: # pragma: no cover |
| 24 | + # We only actually need these imports when running the mypy checks |
| 25 | + pass |
| 26 | + |
| 27 | +from dynamodb_encryption_sdk.delegated_keys.jce import JceNameLocalDelegatedKey |
| 28 | +from dynamodb_encryption_sdk.encrypted.table import EncryptedTable |
| 29 | +from dynamodb_encryption_sdk.exceptions import InvalidVersionError, NoKnownVersionError, VersionAlreadyExistsError |
| 30 | +from dynamodb_encryption_sdk.identifiers import EncryptionKeyType, KeyEncodingType |
| 31 | +from dynamodb_encryption_sdk.material_providers import CryptographicMaterialsProvider |
| 32 | +from dynamodb_encryption_sdk.material_providers.wrapped import WrappedCryptographicMaterialsProvider |
| 33 | +from . import ProviderStore |
| 34 | + |
| 35 | +__all__ = ('MetaStore',) |
| 36 | + |
| 37 | + |
| 38 | +class MetaStoreAttributeNames(Enum): |
| 39 | + """Names of attributes in the MetaStore table.""" |
| 40 | + |
| 41 | + PARTITION = 'N' |
| 42 | + SORT = 'V' |
| 43 | + INTEGRITY_ALGORITHM = 'intAlg' |
| 44 | + INTEGRITY_KEY = 'int' |
| 45 | + ENCRYPTION_ALGORITHM = 'encAlg' |
| 46 | + ENCRYPTION_KEY = 'enc' |
| 47 | + MATERIAL_TYPE_VERSION = 't' |
| 48 | + |
| 49 | + |
| 50 | +class MetaStoreValues(Enum): |
| 51 | + """Static values for use by MetaStore.""" |
| 52 | + |
| 53 | + INTEGRITY_ALGORITHM = 'HmacSHA256' |
| 54 | + ENCRYPTION_ALGORITHM = 'AES' |
| 55 | + MATERIAL_TYPE_VERSION = '0' |
| 56 | + KEY_BITS = 256 |
| 57 | + |
| 58 | + |
| 59 | +#: Field in material description to use for the MetaStore material name and version. |
| 60 | +_MATERIAL_DESCRIPTION_META_FIELD = 'amzn-ddb-meta-id' |
| 61 | + |
| 62 | + |
| 63 | +@attr.s(init=False) |
| 64 | +class MetaStore(ProviderStore): |
| 65 | + """Create and retrieve wrapped cryptographic materials providers, storing their cryptographic |
| 66 | + materials using the provided encrypted table. |
| 67 | +
|
| 68 | + :param table: Pre-configured boto3 DynamoDB Table object |
| 69 | + :type table: boto3.resources.base.ServiceResource |
| 70 | + :param materials_provider: Cryptographic materials provider to use |
| 71 | + :type materials_provider: dynamodb_encryption_sdk.material_providers.CryptographicMaterialsProvider |
| 72 | + """ |
| 73 | + |
| 74 | + _table = attr.ib(validator=attr.validators.instance_of(botocore.client.BaseClient)) |
| 75 | + _materials_provider = attr.ib(validator=attr.validators.instance_of(CryptographicMaterialsProvider)) |
| 76 | + |
| 77 | + def __init__(self, table, materials_provider): |
| 78 | + # type: (botocore.client.BaseClient, CryptographicMaterialsProvider) -> None |
| 79 | + """Workaround pending resolution of attrs/mypy interaction. |
| 80 | + https://github.com/python/mypy/issues/2088 |
| 81 | + https://github.com/python-attrs/attrs/issues/215 |
| 82 | + """ |
| 83 | + self._table = table |
| 84 | + self._materials_provider = materials_provider |
| 85 | + attr.validate(self) |
| 86 | + self.__attrs_post_init__() |
| 87 | + |
| 88 | + def __attrs_post_init__(self): |
| 89 | + # type: () -> None |
| 90 | + """Prepare the encrypted table resource from the provided table and materials provider.""" |
| 91 | + self._encrypted_table = EncryptedTable( # attrs confuses pylint: disable=attribute-defined-outside-init |
| 92 | + table=self._table, |
| 93 | + materials_provider=self._materials_provider |
| 94 | + ) |
| 95 | + |
| 96 | + def create_table(self, read_units, write_units): |
| 97 | + # type: (int, int) -> None |
| 98 | + """Create the table for this MetaStore. |
| 99 | +
|
| 100 | + :param int read_units: Read capacity units to provision |
| 101 | + :param int write_units: Write capacity units to provision |
| 102 | + """ |
| 103 | + try: |
| 104 | + self._table.meta.client.create_table( |
| 105 | + TableName=self._table.name, |
| 106 | + AttributeDefinitions=[ |
| 107 | + { |
| 108 | + 'AttributeName': MetaStoreAttributeNames.PARTITION.value, |
| 109 | + 'AttributeType': 'S' |
| 110 | + }, |
| 111 | + { |
| 112 | + 'AttributeName': MetaStoreAttributeNames.SORT.value, |
| 113 | + 'AttributeName': 'N' |
| 114 | + } |
| 115 | + ], |
| 116 | + KeySchema=[ |
| 117 | + { |
| 118 | + 'AttributeName': MetaStoreAttributeNames.PARTITION.value, |
| 119 | + 'KeyType': 'HASH' |
| 120 | + }, |
| 121 | + { |
| 122 | + 'AttributeName': MetaStoreAttributeNames.SORT.value, |
| 123 | + 'KeyType': 'RANGE' |
| 124 | + } |
| 125 | + ], |
| 126 | + ProvisionedThroughput={ |
| 127 | + 'ReadCapacityUnits': read_units, |
| 128 | + 'WriteCapacityUnits': write_units |
| 129 | + } |
| 130 | + ) |
| 131 | + except botocore.exceptions.ClientError: |
| 132 | + raise Exception('TODO: Could not create table') |
| 133 | + |
| 134 | + def _load_materials(self, material_name, version): |
| 135 | + # type: (Text, int) -> Tuple[JceNameLocalDelegatedKey, JceNameLocalDelegatedKey] |
| 136 | + """Load materials from table. |
| 137 | +
|
| 138 | + :returns: Materials loaded into delegated keys |
| 139 | + :rtype: tuple of JceNameLocalDelegatedKey |
| 140 | + """ |
| 141 | + key = { |
| 142 | + MetaStoreAttributeNames.PARTITION.value: material_name, |
| 143 | + MetaStoreAttributeNames.SORT.value: version |
| 144 | + } |
| 145 | + response = self._encrypted_table.get_item(Key=key) |
| 146 | + try: |
| 147 | + item = response['Item'] |
| 148 | + except KeyError: |
| 149 | + raise InvalidVersionError('Version not found: "{}#{}"'.format(material_name, version)) |
| 150 | + |
| 151 | + try: |
| 152 | + encryption_key_kwargs = dict( |
| 153 | + key=item[MetaStoreAttributeNames.ENCRYPTION_KEY.value], |
| 154 | + algorithm=item[MetaStoreAttributeNames.ENCRYPTION_ALGORITHM.value], |
| 155 | + key_type=EncryptionKeyType.SYMMETRIC, |
| 156 | + key_encoding=KeyEncodingType.RAW |
| 157 | + ) |
| 158 | + signing_key_kwargs = dict( |
| 159 | + key=item[MetaStoreAttributeNames.INTEGRITY_KEY.value], |
| 160 | + algorithm=item[MetaStoreAttributeNames.INTEGRITY_ALGORITHM.value], |
| 161 | + key_type=EncryptionKeyType.SYMMETRIC, |
| 162 | + key_encoding=KeyEncodingType.RAW |
| 163 | + ) |
| 164 | + except KeyError: |
| 165 | + raise Exception('TODO: Invalid record') |
| 166 | + |
| 167 | + if item[MetaStoreAttributeNames.MATERIAL_TYPE_VERSION] != MetaStoreValues.MATERIAL_TYPE_VERSION: |
| 168 | + raise InvalidVersionError('Unsupported material type: "{}"'.format( |
| 169 | + item[MetaStoreAttributeNames.MATERIAL_TYPE_VERSION] |
| 170 | + )) |
| 171 | + |
| 172 | + encryption_key = JceNameLocalDelegatedKey(**encryption_key_kwargs) |
| 173 | + signing_key = JceNameLocalDelegatedKey(**signing_key_kwargs) |
| 174 | + return encryption_key, signing_key |
| 175 | + |
| 176 | + def _save_materials(self, material_name, version, encryption_key, signing_key): |
| 177 | + # type: (Text, int, JceNameLocalDelegatedKey, JceNameLocalDelegatedKey) -> None |
| 178 | + """Save materials to the table, raising an error if the version already exists. |
| 179 | +
|
| 180 | + :param str material_name: Material to locate |
| 181 | + :param int version: Version of material to locate |
| 182 | + :raises VersionAlreadyExistsError: if the specified version already exists |
| 183 | + """ |
| 184 | + item = { |
| 185 | + MetaStoreAttributeNames.PARTITION.value: material_name, |
| 186 | + MetaStoreAttributeNames.SORT.value: version, |
| 187 | + MetaStoreAttributeNames.MATERIAL_TYPE_VERSION.value: MetaStoreValues.MATERIAL_TYPE_VERSION.value, |
| 188 | + MetaStoreAttributeNames.ENCRYPTION_ALGORITHM.value: encryption_key.algorithm, |
| 189 | + MetaStoreAttributeNames.ENCRYPTION_KEY.value: Binary(encryption_key.key), |
| 190 | + MetaStoreAttributeNames.INTEGRITY_ALGORITHM.value: signing_key.algorithm, |
| 191 | + MetaStoreAttributeNames.INTEGRITY_KEY.value: Binary(signing_key.key) |
| 192 | + } |
| 193 | + try: |
| 194 | + self._encrypted_table.put_item( |
| 195 | + Item=item, |
| 196 | + ConditionExpression=( |
| 197 | + Attr(MetaStoreAttributeNames.PARTITION.value).not_exists() & |
| 198 | + Attr(MetaStoreAttributeNames.SORT.value).not_exists() |
| 199 | + ) |
| 200 | + ) |
| 201 | + except botocore.exceptions.ClientError as error: |
| 202 | + if error.response['Error']['Code'] == 'ConditionalCheckFailedException': |
| 203 | + raise VersionAlreadyExistsError('Version already exists: "{}#{}"'.format(material_name, version)) |
| 204 | + |
| 205 | + def _save_or_load_materials( |
| 206 | + self, |
| 207 | + material_name, # type: Text |
| 208 | + version, # type: int |
| 209 | + encryption_key, # type: JceNameLocalDelegatedKey |
| 210 | + signing_key # type: JceNameLocalDelegatedKey |
| 211 | + ): |
| 212 | + # type: (...) -> Tuple[JceNameLocalDelegatedKey, JceNameLocalDelegatedKey] |
| 213 | + """Attempt to save the materials to the table. |
| 214 | +
|
| 215 | + If the specified version already exists, the existing materials will be loaded from |
| 216 | + the table and returned. Otherwise, the provided materials will be returned. |
| 217 | +
|
| 218 | + :param str material_name: Material to locate |
| 219 | + :param int version: Version of material to locate |
| 220 | + :param encryption_key: Loaded encryption key |
| 221 | + :type encryption_key: dynamodb_encryption_sdk.delegated_keys.jce.JceNameLocalDelegatedKey |
| 222 | + :param signing_key: Loaded signing key |
| 223 | + :type signing_key: dynamodb_encryption_sdk.delegated_keys.jce.JceNameLocalDelegatedKey |
| 224 | + """ |
| 225 | + try: |
| 226 | + self._save_materials(material_name, version, encryption_key, signing_key) |
| 227 | + return encryption_key, signing_key |
| 228 | + except VersionAlreadyExistsError: |
| 229 | + return self._load_materials(material_name, version) |
| 230 | + |
| 231 | + @staticmethod |
| 232 | + def _material_description(material_name, version): |
| 233 | + # type: (Text, int) -> Dict[Text, Text] |
| 234 | + """Build a material description from a material name and version. |
| 235 | +
|
| 236 | + :param str material_name: Material to locate |
| 237 | + :param int version: Version of material to locate |
| 238 | + """ |
| 239 | + return {_MATERIAL_DESCRIPTION_META_FIELD: '{name}#{version}'.format(name=material_name, version=version)} |
| 240 | + |
| 241 | + def _load_provider_from_table(self, material_name, version): |
| 242 | + # type: (Text, int) -> CryptographicMaterialsProvider |
| 243 | + """Load a provider from the table. |
| 244 | +
|
| 245 | + :param str material_name: Material to locate |
| 246 | + :param int version: Version of material to locate |
| 247 | + """ |
| 248 | + encryption_key, signing_key = self._load_materials(material_name, version) |
| 249 | + return WrappedCryptographicMaterialsProvider( |
| 250 | + signing_key=signing_key, |
| 251 | + wrapping_key=encryption_key, |
| 252 | + unwrapping_key=encryption_key, |
| 253 | + material_description=self._material_description(material_name, version) |
| 254 | + ) |
| 255 | + |
| 256 | + def get_or_create_provider(self, material_name, version): |
| 257 | + # type: (Text, int) -> CryptographicMaterialsProvider |
| 258 | + """Obtain a cryptographic materials provider identified by a name and version. |
| 259 | +
|
| 260 | + If the requested version does not exist, a new one will be created. |
| 261 | +
|
| 262 | + :param str material_name: Material to locate |
| 263 | + :param int version: Version of material to locate |
| 264 | + :returns: cryptographic materials provider |
| 265 | + :rtype: dynamodb_encryption_sdk.material_providers.CryptographicMaterialsProvider |
| 266 | + :raises InvalidVersionError: if the requested version is not available and cannot be created |
| 267 | + """ |
| 268 | + encryption_key = JceNameLocalDelegatedKey.generate( |
| 269 | + MetaStoreValues.ENCRYPTION_ALGORITHM.value, |
| 270 | + MetaStoreValues.KEY_BITS.value |
| 271 | + ) |
| 272 | + signing_key = JceNameLocalDelegatedKey.generate( |
| 273 | + MetaStoreValues.INTEGRITY_ALGORITHM.value, |
| 274 | + MetaStoreValues.KEY_BITS.value |
| 275 | + ) |
| 276 | + encryption_key, signing_key = self._save_or_load_materials(material_name, version, encryption_key, signing_key) |
| 277 | + return WrappedCryptographicMaterialsProvider( |
| 278 | + signing_key=signing_key, |
| 279 | + wrapping_key=encryption_key, |
| 280 | + unwrapping_key=encryption_key, |
| 281 | + material_description=self._material_description(material_name, version) |
| 282 | + ) |
| 283 | + |
| 284 | + def provider(self, material_name, version=None): |
| 285 | + # type: (Text, Optional[int]) -> CryptographicMaterialsProvider |
| 286 | + """Obtain a cryptographic materials provider identified by a name and version. |
| 287 | +
|
| 288 | + If the version is provided, an error will be raised if that version is not found. |
| 289 | +
|
| 290 | + If the version is not provided, the maximum version will be used. |
| 291 | +
|
| 292 | + :param str material_name: Material to locate |
| 293 | + :param int version: Version of material to locate (optional) |
| 294 | + :returns: cryptographic materials provider |
| 295 | + :rtype: dynamodb_encryption_sdk.material_providers.CryptographicMaterialsProvider |
| 296 | + :raises InvalidVersionError: if the requested version is not found |
| 297 | + """ |
| 298 | + if version is not None: |
| 299 | + return self._load_materials(material_name, version) |
| 300 | + |
| 301 | + return super(MetaStore, self).provider(material_name, version) |
| 302 | + |
| 303 | + def version_from_material_description(self, material_description): |
| 304 | + # (Dict[Text, Text]) -> int |
| 305 | + """Determine the version from the provided material description. |
| 306 | +
|
| 307 | + :param dict material_description: Material description to use with this request |
| 308 | + :returns: version to use |
| 309 | + :rtype: int |
| 310 | + """ |
| 311 | + try: |
| 312 | + info = material_description[_MATERIAL_DESCRIPTION_META_FIELD] |
| 313 | + except KeyError: |
| 314 | + raise Exception('TODO: No info found') |
| 315 | + |
| 316 | + try: |
| 317 | + return int(info.split('#', 1)[1]) |
| 318 | + except (IndexError, ValueError): |
| 319 | + raise Exception('TODO: Malformed info') |
| 320 | + |
| 321 | + def max_version(self, material_name): |
| 322 | + # (Text) -> int |
| 323 | + """Find the maximum known version of the specified material. |
| 324 | +
|
| 325 | + :param str material_name: Material to locate |
| 326 | + :returns: Maximum known version |
| 327 | + :rtype: int |
| 328 | + :raises NoKnownVersion: if no version can be found |
| 329 | + """ |
| 330 | + response = self._encrypted_table.query( |
| 331 | + KeyConditionExpression=Key(MetaStoreAttributeNames.PARTITION.value).eq(material_name), |
| 332 | + ScanIndexForward=False, |
| 333 | + Limit=1 |
| 334 | + ) |
| 335 | + |
| 336 | + if not response['Items']: |
| 337 | + raise NoKnownVersionError('No known version for name: "{}"'.format(material_name)) |
| 338 | + |
| 339 | + return response['Items'][0][MetaStoreAttributeNames.SORT.value] |
| 340 | + |
| 341 | + def replicate(self, material_name, version, target): |
| 342 | + """""" |
| 343 | + raise NotImplementedError('TODO: implement this') |
0 commit comments