private static void cleanUpKMSKeys(Regions testRegion, String testResourcePrefix, Date createdBeforeThreshold, AWSCredentialsProvider awsCredentials) { LOG.info("Cleaning KMS..."); AWSKMS kmsClient = AWSKMSClientBuilder.standard() .withCredentials(awsCredentials) .withRegion(testRegion) .build(); List<AliasListEntry> keys = kmsClient.listAliases().getAliases(); for (AliasListEntry entry: keys) { if (!entry.getAliasName().startsWith("alias/" + testResourcePrefix)) { continue; } DescribeKeyRequest request = new DescribeKeyRequest().withKeyId(entry.getTargetKeyId()); KeyMetadata metadata = kmsClient.describeKey(request).getKeyMetadata(); if (KMSKeyState.fromString(metadata.getKeyState()) != KMSKeyState.PENDING_DELETION && metadata.getCreationDate().before(createdBeforeThreshold)) { LOG.info("Scheduling KMS key for deletion:" + entry.getAliasName()); scheduleKeyDeletion(kmsClient, entry); } } }
LinkGeneratorLambdaHandler(String region, String jwtEncryptKeyArn, String pageStorageBucket, String authVerifyEndpointURL, AWSCredentialsProvider awsCredential, String introPageTemplateName) throws IOException, TemplateException { AWSKMS kmsClient = AWSKMSClientBuilder.standard() .withCredentials(awsCredential) .withRegion(region) .build(); AmazonS3 s3client = AmazonS3ClientBuilder .standard() .withCredentials(awsCredential) .withRegion(region) .build(); kmsEncrypt = new KMSEncrypt(kmsClient, jwtEncryptKeyArn); this.pageStorageBucket = pageStorageBucket; this.authVerifyEndpointURL = authVerifyEndpointURL; this.pageUploader = new PageUploader(s3client, pageStorageBucket); this.introPageTemplate = new IntroPageTemplate(introPageTemplateName); }
@Before public void setUp() throws Exception { context = mock(Context.class); when(context.getLogger()).thenReturn(System.out::println); handler = new AuthLambdaHandler(TEST_AWS_REGION, TEST_JWT_KEY_ARN, TEST_VIDEO_STORAGE_BUCKET, TEST_USER_ACCESS_KEY_ID, TEST_USER_SECRET_ACCESS_KEY); AWSKMS kmsClient = AWSKMSClientBuilder.standard() .withRegion(TEST_AWS_REGION) .withCredentials(new AWSStaticCredentialsProvider( new BasicAWSCredentials(TEST_USER_ACCESS_KEY_ID, TEST_USER_SECRET_ACCESS_KEY)) ) .build(); kmsEncrypt = new KMSEncrypt(kmsClient, TEST_JWT_KEY_ARN); }
@Before public void setUp() { dynamoDBClient = Mockito.mock(AmazonDynamoDB.class); GenerateDataKeyResult generateDatakeyResult = new GenerateDataKeyResult(); generateDatakeyResult.setCiphertextBlob(Mockito.mock(ByteBuffer.class)); generateDatakeyResult.setPlaintext(Mockito.mock(ByteBuffer.class)); DecryptResult decryptResult = new DecryptResult(); decryptResult.setKeyId("alias/foo"); decryptResult.setPlaintext(Mockito.mock(ByteBuffer.class)); awskmsClient = Mockito.mock(AWSKMS.class); Mockito.when(awskmsClient.generateDataKey(Mockito.any(GenerateDataKeyRequest.class))).thenReturn(generateDatakeyResult); Mockito.when(awskmsClient.decrypt(Mockito.any(DecryptRequest.class))).thenReturn(decryptResult); }
private RegionalClientSupplier clientFactory() { if (regionalClientSupplier_ != null) { return regionalClientSupplier_; } // Clone again; this MKP builder might be reused to build a second MKP with different creds. AWSKMSClientBuilder builder = templateBuilder_ != null ? cloneClientBuilder(templateBuilder_) : AWSKMSClientBuilder.standard(); ConcurrentHashMap<String, AWSKMS> clientCache = new ConcurrentHashMap<>(); return region -> clientCache.computeIfAbsent(region, region2 -> { // Clone yet again as we're going to change the region field. return cloneClientBuilder(builder).withRegion(region2).build(); }); }
@Override public KmsMasterKey getMasterKey(final String provider, final String keyId) throws UnsupportedProviderException, NoSuchMasterKeyException { if (!canProvide(provider)) { throw new UnsupportedProviderException(); } String regionName = parseRegionfromKeyArn(keyId); AWSKMS kms = regionalClientSupplier_.getClient(regionName); if (kms == null) { throw new AwsCryptoException("Can't use keys from region " + regionName); } final KmsMasterKey result = KmsMasterKey.getInstance(kms, keyId, this); result.setGrantTokens(grantTokens_); return result; }
public static String decrypt(String str, Region region) throws UnsupportedEncodingException { if (isJUnitTest()) { return str; } AWSKMS kms = AWSKMSClientBuilder.standard().withRegion(region.getName()).build(); /* * The KMS ciphertext is base64 encoded and must be decoded before the request is made */ String cipherString = str; byte[] cipherBytes = Base64.decode(cipherString); /* * Create decode request and decode */ ByteBuffer cipherBuffer = ByteBuffer.wrap(cipherBytes); DecryptRequest req = new DecryptRequest().withCiphertextBlob(cipherBuffer); DecryptResult resp = kms.decrypt(req); /* * Convert the response plaintext bytes to a string */ return new String(resp.getPlaintext().array(), Charset.forName("UTF-8")); }
@Override public KeyProvider build() { if ( null == key || 0 == key.length ) { return new KeyProviderImpl(null); } else if ( 16 == key.length ) { return new KeyProviderImpl(new SecretKeySpec(key, "AES")); } AWSKMS kms = _amazonWebServiceClients.withEndpoint( new AWSKMSClient( _credProviderFactory.create(credProvider), _clientConfigurations.withProxy(new ClientConfiguration(), proxy)), endpoint); key = kms.decrypt(new DecryptRequest() .withCiphertextBlob(ByteBuffer.wrap(key))) .getPlaintext().array(); if ( 16 != key.length ) { LOG.warn("Expected decrypted key to be exactly 16 bytes, got "+key.length+" bytes. Please "+ "verify the key was not base64 encoded before encrypting with KMS"); return new KeyProviderImpl(null); } return new KeyProviderImpl(new SecretKeySpec(key, "AES")); }
/** * Decodes the encrypted token and attempts to decrypt it using AWS KMS. If * successful, the token is returned. * * @param kmsClient KMS client * @param encryptedToken Token to decode and decrypt * @return Decrypted token */ protected VaultAuthResponse decryptToken(AWSKMS kmsClient, String encryptedToken) { byte[] decodedToken; try { decodedToken = Base64.decode(encryptedToken); } catch (IllegalArgumentException iae) { throw new VaultClientException("Encrypted token not Base64 encoded", iae); } final DecryptRequest request = new DecryptRequest().withCiphertextBlob(ByteBuffer.wrap(decodedToken)); final DecryptResult result = kmsClient.decrypt(request); final String decryptedAuthData = new String(result.getPlaintext().array(), Charset.forName("UTF-8")); return gson.fromJson(decryptedAuthData, VaultAuthResponse.class); }
@Test public void testAwsPrivateKeyStore() throws Exception { String bucketName = "my_bucket"; String keyName = "my_key"; String expected = "my_value"; AmazonS3 s3 = Mockito.mock(AmazonS3.class); AWSKMS kms = Mockito.mock(AWSKMS.class); S3Object s3Object = Mockito.mock(S3Object.class); Mockito.when(s3.getObject(bucketName, keyName)).thenReturn(s3Object); InputStream is = new ByteArrayInputStream( expected.getBytes() ); S3ObjectInputStream s3ObjectInputStream = new S3ObjectInputStream(is, null); Mockito.when(s3Object.getObjectContent()).thenReturn(s3ObjectInputStream); String result = expected; ByteBuffer buffer = ByteBuffer.wrap(result.getBytes()); DecryptResult decryptResult = Mockito.mock(DecryptResult.class); Mockito.when(kms.decrypt(Mockito.any(DecryptRequest.class))).thenReturn(decryptResult); Mockito.when(decryptResult.getPlaintext()).thenReturn(buffer); AwsPrivateKeyStore awsPrivateKeyStore = new AwsPrivateKeyStore(s3, kms); String actual = awsPrivateKeyStore.getApplicationSecret(bucketName, keyName); Assert.assertEquals(actual, expected); }
@Before public void setUp() throws Exception { mockKms = mock(AWSKMS.class); textEncryptor = new KmsTextEncryptor(mockKms, KMS_KEY_ID); expectedEncryptRequest = new EncryptRequest(); expectedEncryptRequest.setKeyId(KMS_KEY_ID); expectedEncryptRequest.setPlaintext(wrap(PLAINTEXT.getBytes())); encryptResult = new EncryptResult(); encryptResult.setCiphertextBlob(wrap(CIPHER_TEXT.getBytes())); when(mockKms.encrypt(any(EncryptRequest.class))).thenReturn(encryptResult); expectedDecryptRequest = new DecryptRequest(); expectedDecryptRequest.setCiphertextBlob(wrap(CIPHER_TEXT.getBytes())); decryptResult = new DecryptResult(); decryptResult.setPlaintext(wrap(PLAINTEXT.getBytes())); when(mockKms.decrypt(any(DecryptRequest.class))).thenReturn(decryptResult); }
public DirectKmsMaterialProvider(AWSKMS kms, String encryptionKeyId, Map<String, String> materialDescription) { this.kms = kms; this.encryptionKeyId = encryptionKeyId; this.description = materialDescription != null ? Collections.unmodifiableMap(new HashMap<>(materialDescription)) : Collections.<String, String> emptyMap(); dataKeyDesc = description .containsKey(WrappedRawMaterials.CONTENT_KEY_ALGORITHM) ? description .get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM) : DEFAULT_ENC_ALG; String[] parts = dataKeyDesc.split("/", 2); this.dataKeyAlg = parts[0]; this.dataKeyLength = parts.length == 2 ? Integer.parseInt(parts[1]) : 256; sigKeyDesc = description .containsKey(SIGNING_KEY_ALGORITHM) ? description .get(SIGNING_KEY_ALGORITHM) : DEFAULT_SIG_ALG; parts = sigKeyDesc.split("/", 2); this.sigKeyAlg = parts[0]; this.sigKeyLength = parts.length == 2 ? Integer.parseInt(parts[1]) : 256; }
/** * Creates the KMS client {@link Bean}. * * Uses the default client, but if a region is unspecified, uses {@code us-east-1}. * * @return The KMS client. */ @Bean public AWSKMS awsKms() { AWSKMS client = null; try { client = AWSKMSClientBuilder.defaultClient(); } catch (SdkClientException exception) { API_LOG.info("Default KMS client failed to build, trying again with region us-east-1", exception); client = planB(); } return client; }
@Test public void testDefaultClient() { mockStatic(AWSKMSClientBuilder.class); when(AWSKMSClientBuilder.defaultClient()).thenReturn(Mockito.mock(AWSKMS.class)); Assert.assertNotNull(underTest.awsKms()); verify(underTest, times(0)).planB(); }
public KMSManager(AWSKMS client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier) { this.kms = client; this.awsCredentials = awsCredentials; this.clientConfiguration = clientConfiguration; this.group = groupIdentifier; RegionLocalResourceName resourceName = new RegionLocalResourceName(groupIdentifier); this.aliasKeyName = ALIAS_PREFIX + resourceName.toString(); }
public static KMSManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier) { AWSKMS client = AWSKMSClientBuilder.standard() .withCredentials(awsCredentials) .withClientConfiguration(transformAndVerifyOrThrow(clientConfiguration)) .withRegion(groupIdentifier.region.getName()) .build(); return new KMSManager(client, awsCredentials, clientConfiguration, groupIdentifier); }
AmazonS3EncryptionClientParamsWrapper(AwsSyncClientParams getClientParams, S3ClientOptions getS3ClientOptions, EncryptionMaterialsProvider encryptionMaterials, CryptoConfiguration cryptoConfiguration, AWSKMS kms) { this.encryptionMaterials = encryptionMaterials; this.cryptoConfiguration = cryptoConfiguration; this.kms = kms; this.getClientParams = getClientParams; this.getS3ClientOptions = getS3ClientOptions; }
/** * Decrypts the secured CEK via KMS; involves network calls. * * @return the CEK (in plaintext). */ private static SecretKey cekByKMS(byte[] cekSecured, String keyWrapAlgo, EncryptionMaterials materials, ContentCryptoScheme contentCryptoScheme, AWSKMS kms) { DecryptRequest kmsreq = new DecryptRequest() .withEncryptionContext(materials.getMaterialsDescription()) .withCiphertextBlob(ByteBuffer.wrap(cekSecured)); DecryptResult result = kms.decrypt(kmsreq); return new SecretKeySpec(copyAllBytesFrom(result.getPlaintext()), contentCryptoScheme.getKeyGeneratorAlgorithm()); }
/** * @return a non-null content crypto material. */ static ContentCryptoMaterial fromObjectMetadata( ObjectMetadata metadata, EncryptionMaterialsAccessor kekMaterialAccessor, Provider securityProvider, boolean keyWrapExpected, AWSKMS kms) { return fromObjectMetadata0(metadata, kekMaterialAccessor, securityProvider, null, NONE, keyWrapExpected, kms); }
/** * Factory method to return the content crypto material from the S3 object * meta data, using the specified key encrypting key material accessor and * an optional security provider. * * @return a non-null content crypto material. */ static ContentCryptoMaterial fromObjectMetadata( ObjectMetadata metadata, EncryptionMaterialsAccessor kekMaterialAccessor, Provider securityProvider, long[] range, ExtraMaterialsDescription extra, boolean keyWrapExpected, AWSKMS kms) { return fromObjectMetadata0(metadata, kekMaterialAccessor, securityProvider, range, extra, keyWrapExpected, kms); }
/** * @return a non-null content crypto material. */ static ContentCryptoMaterial fromInstructionFile( Map<String, String> instFile, EncryptionMaterialsAccessor kekMaterialAccessor, Provider securityProvider, boolean keyWrapExpected, AWSKMS kms) { return fromInstructionFile0(instFile, kekMaterialAccessor, securityProvider, null, NONE, keyWrapExpected, kms); }
/** * Factory method to return the content crypto material from the S3 * instruction file, using the specified key encrypting key material * accessor and an optional security provider. * * @return a non-null content crypto material. */ static ContentCryptoMaterial fromInstructionFile( Map<String, String> instFile, EncryptionMaterialsAccessor kekMaterialAccessor, Provider securityProvider, long[] range, ExtraMaterialsDescription extra, boolean keyWrapExpected, AWSKMS kms) { return fromInstructionFile0(instFile, kekMaterialAccessor, securityProvider, range, extra, keyWrapExpected, kms); }
/** * Recreates a new content crypto material from the current material given a * new KEK material-descriptions. The purpose is to re-encrypt the CEK under * a different KEK. * * Note network calls are involved if the CEK has been or is to be protected * by KMS. * * @param newKEKMatDesc * material descriptions for the new KEK; never null * @param accessor * used to retrieve the KEK given the corresponding material * description * @param targetScheme * the target crypto scheme to be used for key wrapping, etc. * @param p * optional security provider; null means to use the default. * @throws SecurityException * if the old and new material description are the same; or if * the old and new KEK are the same */ ContentCryptoMaterial recreate(Map<String, String> newKEKMatDesc, EncryptionMaterialsAccessor accessor, S3CryptoScheme targetScheme, Provider p, AWSKMS kms, AmazonWebServiceRequest req) { if (!usesKMSKey() && newKEKMatDesc.equals(kekMaterialsDescription)) { throw new SecurityException( "Material description of the new KEK must differ from the current one"); } final EncryptionMaterials origKEK; if (usesKMSKey()) { origKEK = new KMSEncryptionMaterials(kekMaterialsDescription.get( KMSEncryptionMaterials.CUSTOMER_MASTER_KEY_ID)); } else { origKEK = accessor.getEncryptionMaterials(kekMaterialsDescription); } EncryptionMaterials newKEK = accessor.getEncryptionMaterials(newKEKMatDesc); if (newKEK == null) { throw new SdkClientException( "No material available with the description " + newKEKMatDesc + " from the encryption material provider"); } SecretKey cek = cek(encryptedCEK, keyWrappingAlgorithm, origKEK, p, getContentCryptoScheme(), kms); ContentCryptoMaterial output = create(cek, cipherLite.getIV(), newKEK, getContentCryptoScheme(), // must use same content crypto scheme targetScheme, p, kms, req); if (Arrays.equals(output.encryptedCEK, encryptedCEK)) { throw new SecurityException( "The new KEK must differ from the original"); } return output; }
/** * Recreates a new content crypto material from the current material given a * new KEK encryption materials. The purpose is to re-encrypt the CEK under * the new KEK. * * Note network calls are involved if the CEK has been or is to be protected * by KMS. * * @param newKEK * encryption materials for the new KEK; must not be null * @param accessor * used to retrieve the original KEK given the corresponding * material description * @param targetScheme * the target crypto scheme to use for recreating the content * crypto material * @param p * optional security provider; null means to use the default. * @throws SecurityException * if the old and new material description are the same; or if * the old and new KEK are the same */ ContentCryptoMaterial recreate(EncryptionMaterials newKEK, EncryptionMaterialsAccessor accessor, S3CryptoScheme targetScheme, Provider p, AWSKMS kms, AmazonWebServiceRequest req) { if (!usesKMSKey() && newKEK.getMaterialsDescription().equals(kekMaterialsDescription)) { throw new SecurityException( "Material description of the new KEK must differ from the current one"); } final EncryptionMaterials origKEK; if (usesKMSKey()) { origKEK = new KMSEncryptionMaterials(kekMaterialsDescription.get( KMSEncryptionMaterials.CUSTOMER_MASTER_KEY_ID)); } else { origKEK = accessor.getEncryptionMaterials(kekMaterialsDescription); } SecretKey cek = cek(encryptedCEK, keyWrappingAlgorithm, origKEK, p, getContentCryptoScheme(), kms); ContentCryptoMaterial output = create(cek, cipherLite.getIV(), newKEK, getContentCryptoScheme(), // must use same content crypto scheme targetScheme, // target scheme used to recreate the content crypto material p, kms, req); if (Arrays.equals(output.encryptedCEK, encryptedCEK)) { throw new SecurityException( "The new KEK must differ from the original"); } return output; }
/** * @param cryptoConfig a read-only copy of the crypto configuration. */ S3CryptoModuleAEStrict(AWSKMS kms, S3Direct s3, AWSCredentialsProvider credentialsProvider, EncryptionMaterialsProvider encryptionMaterialsProvider, CryptoConfiguration cryptoConfig) { super(kms, s3, credentialsProvider, encryptionMaterialsProvider, cryptoConfig); if (cryptoConfig.getCryptoMode() != StrictAuthenticatedEncryption) throw new IllegalArgumentException(); }
/** * @param cryptoConfig a read-only copy of the crypto configuration. */ protected S3CryptoModuleBase(AWSKMS kms, S3Direct s3, AWSCredentialsProvider credentialsProvider, EncryptionMaterialsProvider kekMaterialsProvider, CryptoConfiguration cryptoConfig) { if (!cryptoConfig.isReadOnly()) throw new IllegalArgumentException("The cryto configuration parameter is required to be read-only"); this.kekMaterialsProvider = kekMaterialsProvider; this.s3 = s3; this.cryptoConfig = cryptoConfig; this.cryptoScheme = S3CryptoScheme.from(cryptoConfig.getCryptoMode()); this.contentCryptoScheme = cryptoScheme.getContentCryptoScheme(); this.kms = kms; }
/** * @param cryptoConfig a read-only copy of the crypto configuration */ S3CryptoModuleEO(AWSKMS kms, S3Direct s3, AWSCredentialsProvider credentialsProvider, EncryptionMaterialsProvider encryptionMaterialsProvider, CryptoConfiguration cryptoConfig) { super(kms, s3, credentialsProvider, encryptionMaterialsProvider, cryptoConfig); if (cryptoConfig.getCryptoMode() != EncryptionOnly) throw new IllegalArgumentException(); }
/** * Used for testing purposes only. */ S3CryptoModuleEO(AWSKMS kms, S3Direct s3, EncryptionMaterialsProvider encryptionMaterialsProvider, CryptoConfiguration cryptoConfig) { this(kms, s3, new DefaultAWSCredentialsProviderChain(), encryptionMaterialsProvider, cryptoConfig); }
/** * @param cryptoConfig a read-only copy of the crypto configuration. */ S3CryptoModuleAE(AWSKMS kms, S3Direct s3, AWSCredentialsProvider credentialsProvider, EncryptionMaterialsProvider encryptionMaterialsProvider, CryptoConfiguration cryptoConfig) { super(kms, s3, credentialsProvider, encryptionMaterialsProvider, cryptoConfig); CryptoMode mode = cryptoConfig.getCryptoMode(); if (mode != StrictAuthenticatedEncryption && mode != AuthenticatedEncryption) { throw new IllegalArgumentException(); } }
/** * Used for testing purposes only. */ S3CryptoModuleAE(AWSKMS kms, S3Direct s3, EncryptionMaterialsProvider encryptionMaterialsProvider, CryptoConfiguration cryptoConfig) { this(kms, s3, new DefaultAWSCredentialsProviderChain(), encryptionMaterialsProvider, cryptoConfig); }
public JWTKMSAuthorizer(String region, String jwtDecryptKeyARN, AWSCredentialsProvider credential) { AWSKMS kmsClient = AWSKMSClientBuilder.standard() .withRegion(region) .withCredentials(credential) .build(); KMSDecrypt kmsDecrypt = new KMSDecrypt(kmsClient, Collections.singleton(jwtDecryptKeyARN)); jwtDecoder = new JWTDecoder(kmsDecrypt); }
private AWSKMS getClient() throws IOException { AWSKMSClientBuilder clientBuilder = AWSKMSClientBuilder.standard(); ClientConfiguration clientConfig = PredefinedClientConfigurations.defaultConfig(); String proxyHost = ConfigManager.getEnvironmentVariable(ConfigKeys.ProxyHost); if (proxyHost != null) { clientConfig.setProxyHost(proxyHost); clientConfig.setProxyPort(Integer.parseInt(ConfigManager.getEnvironmentVariable(ConfigKeys.ProxyPort))); } clientBuilder.setClientConfiguration(clientConfig); return clientBuilder.build(); }
private String generateJWT() throws KeyOperationException { log.info("Generating JWT for user \"{}\" with journey \"{}\", valid for {} days", username, journey, expiresInDays); AWSKMS kmsClient = AWSKMSClientBuilder.standard() .withRegion(region) .build(); KMSEncrypt kmsEncrypt = new KMSEncrypt(kmsClient, keyARN); Date expiryDate = expirationDate(expiresInDays); return JWTEncoder.builder(kmsEncrypt) .setExpiration(expiryDate) .claim("usr", username) .claim("jrn", journey) .compact(); }
private String provisionKmsCmkForBackupRegion(String region) { Policy kmsPolicy = new Policy(); final List<Statement> statements = new LinkedList<>(); // allow the configured admin iam principals all permissions configStore.getBackupAdminIamPrincipals().forEach( principal -> { log.debug("Adding principal: {} to the CMK Policy for region {}", principal, region); statements.add(new Statement(Statement.Effect.Allow) .withId("Principal " + principal + " Has All Actions") .withPrincipals(new Principal(AWS_PROVIDER, principal, false)) .withActions(KMSActions.AllKMSActions) .withResources(new Resource("*"))); }); kmsPolicy.setStatements(statements); String policyString = kmsPolicy.toJson(); log.debug("Creating key for region {} with policy {}", region, policyString); AWSKMS kms = AWSKMSClient.builder().withCredentials(getAWSCredentialsProviderChain()).withRegion(region).build(); CreateKeyResult createKeyResult = kms.createKey( new CreateKeyRequest() .withPolicy(policyString) .withBypassPolicyLockoutSafetyCheck(true) .withDescription(String.format("Cerberus Backup Encryption key for env: %S region: %s", environmentMetadata.getName(), region)) .withTags( new Tag().withTagKey("env").withTagValue(environmentMetadata.getName()), new Tag().withTagKey("region").withTagValue(region), new Tag().withTagKey("cerberus-backup-key").withTagValue("true") ) ); String keyId = createKeyResult.getKeyMetadata().getKeyId(); log.info("Created new backup KMS CMK with id: {} for region: {}", keyId, region); return keyId; }
/** * Binds all the Amazon services used. */ @Override protected void configure() { final Region region = Region.getRegion(Regions.fromName(regionName)); bind(AmazonEC2.class).toInstance(createAmazonClientInstance(AmazonEC2Client.class, region)); bind(AmazonCloudFormation.class).toInstance(createAmazonClientInstance(AmazonCloudFormationClient.class, region)); bind(AmazonIdentityManagement.class).toInstance(createAmazonClientInstance(AmazonIdentityManagementClient.class, region)); bind(AWSKMS.class).toInstance(createAmazonClientInstance(AWSKMSClient.class, region)); bind(AmazonS3.class).toInstance(createAmazonClientInstance(AmazonS3Client.class, region)); bind(AmazonAutoScaling.class).toInstance(createAmazonClientInstance(AmazonAutoScalingClient.class, region)); bind(AWSSecurityTokenService.class).toInstance(createAmazonClientInstance(AWSSecurityTokenServiceClient.class, region)); bind(AWSLambda.class).toInstance(createAmazonClientInstance(AWSLambdaClient.class, region)); bind(AmazonSNS.class).toInstance(createAmazonClientInstance(AmazonSNSClient.class, region)); }
@Bean AWSKMS kms() { final AWSKMS mock = mock(AWSKMS.class); when(mock.decrypt(any(DecryptRequest.class))).thenAnswer((Answer<DecryptResult>) invocation -> new DecryptResult().withPlaintext(ByteBuffer.wrap(KmsEncryptionIntegrationConfigurationTest.PLAINTEXT.getBytes()))); return mock; }
@Test public void generateDataKeyIsCalledWith256NumberOfBits() { final AtomicBoolean gdkCalled = new AtomicBoolean(false); AWSKMS kmsSpy = new FakeKMS() { @Override public GenerateDataKeyResult generateDataKey(GenerateDataKeyRequest r) { gdkCalled.set(true); assertEquals((Integer) 32, r.getNumberOfBytes()); assertNull(r.getKeySpec()); return super.generateDataKey(r); } }; assertFalse(gdkCalled.get()); new DirectKmsMaterialProvider(kmsSpy, keyId).getEncryptionMaterials(ctx); assertTrue(gdkCalled.get()); }
private static void scheduleKeyDeletion(AWSKMS client, AliasListEntry entry) { ScheduleKeyDeletionRequest deletionRequest = new ScheduleKeyDeletionRequest(); deletionRequest.withKeyId(entry.getTargetKeyId()).withPendingWindowInDays(7); client.scheduleKeyDeletion(deletionRequest); }
@Override AWSKMS getKmsClient() { return kms; }
/** * @return a non-null content crypto material. */ private static ContentCryptoMaterial fromObjectMetadata0( ObjectMetadata metadata, EncryptionMaterialsAccessor kekMaterialAccessor, Provider securityProvider, long[] range, ExtraMaterialsDescription extra, boolean keyWrapExpected, AWSKMS kms) { // CEK and IV Map<String, String> userMeta = metadata.getUserMetadata(); String b64key = userMeta.get(Headers.CRYPTO_KEY_V2); if (b64key == null) { b64key = userMeta.get(Headers.CRYPTO_KEY); if (b64key == null) throw new SdkClientException( "Content encrypting key not found."); } byte[] cekWrapped = Base64.decode(b64key); byte[] iv = Base64.decode(userMeta.get(Headers.CRYPTO_IV)); if (cekWrapped == null || iv == null) { throw new SdkClientException( "Content encrypting key or IV not found."); } // Material description String matdescStr = userMeta.get(Headers.MATERIALS_DESCRIPTION); final String keyWrapAlgo = userMeta.get(Headers.CRYPTO_KEYWRAP_ALGORITHM); final boolean isKMS = isKMSKeyWrapped(keyWrapAlgo); final Map<String, String> core = matdescFromJson(matdescStr); final Map<String, String> merged = isKMS || extra == null ? core : extra.mergeInto(core); final EncryptionMaterials materials; if (isKMS) { materials = new KMSEncryptionMaterials( core.get(KMSEncryptionMaterials.CUSTOMER_MASTER_KEY_ID)); materials.addDescriptions(core); } else { materials = kekMaterialAccessor == null ? null : kekMaterialAccessor.getEncryptionMaterials(merged) ; if (materials == null) { throw new SdkClientException( "Unable to retrieve the client encryption materials"); } } // CEK algorithm String cekAlgo = userMeta.get(Headers.CRYPTO_CEK_ALGORITHM); boolean isRangeGet = range != null; // The content crypto scheme may vary depending on whether // it is a range get operation ContentCryptoScheme contentCryptoScheme = ContentCryptoScheme.fromCEKAlgo(cekAlgo, isRangeGet); if (isRangeGet) { // Adjust the IV as needed iv = contentCryptoScheme.adjustIV(iv, range[0]); } else { // Validate the tag length supported int tagLenExpected = contentCryptoScheme.getTagLengthInBits(); if (tagLenExpected > 0) { String s = userMeta.get(Headers.CRYPTO_TAG_LENGTH); int tagLenActual = Integer.parseInt(s); if (tagLenExpected != tagLenActual) { throw new SdkClientException("Unsupported tag length: " + tagLenActual + ", expected: " + tagLenExpected); } } } // Unwrap or decrypt the CEK if (keyWrapExpected && keyWrapAlgo == null) throw newKeyWrapException(); SecretKey cek = cek(cekWrapped, keyWrapAlgo, materials, securityProvider, contentCryptoScheme, kms); return new ContentCryptoMaterial(merged, cekWrapped, keyWrapAlgo, contentCryptoScheme.createCipherLite(cek, iv, Cipher.DECRYPT_MODE, securityProvider)); }