diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyDataPlaneTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyDataPlaneTest.java index 833c8ed319..cf834b8ba4 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyDataPlaneTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyDataPlaneTest.java @@ -5,6 +5,9 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import software.amazon.awssdk.awscore.exception.AwsServiceException; +import software.amazon.awssdk.services.paymentcryptography.PaymentCryptographyClient; +import software.amazon.awssdk.services.paymentcryptography.model.ExportDiffieHellmanTr31KeyBlock; +import software.amazon.awssdk.services.paymentcryptography.model.Key; import software.amazon.awssdk.services.paymentcryptography.model.KeyAlgorithm; import software.amazon.awssdk.services.paymentcryptography.model.KeyClass; import software.amazon.awssdk.services.paymentcryptography.model.KeyUsage; @@ -12,12 +15,24 @@ import software.amazon.awssdk.services.paymentcryptographydata.PaymentCryptograp import software.amazon.awssdk.services.paymentcryptographydata.model.EncryptionDecryptionAttributes; import software.amazon.awssdk.services.paymentcryptographydata.model.EncryptionMode; import software.amazon.awssdk.services.paymentcryptographydata.model.GenerateMacRequest; +import software.amazon.awssdk.services.paymentcryptographydata.model.IncomingDiffieHellmanTr31KeyBlock; +import software.amazon.awssdk.services.paymentcryptographydata.model.KeyDerivationFunction; +import software.amazon.awssdk.services.paymentcryptographydata.model.KeyDerivationHashAlgorithm; import software.amazon.awssdk.services.paymentcryptographydata.model.MacAlgorithm; import software.amazon.awssdk.services.paymentcryptographydata.model.MacAttributes; import software.amazon.awssdk.services.paymentcryptographydata.model.ReEncryptionAttributes; import software.amazon.awssdk.services.paymentcryptographydata.model.SymmetricEncryptionAttributes; +import software.amazon.awssdk.services.paymentcryptographydata.model.SymmetricKeyAlgorithm; +import software.amazon.awssdk.services.paymentcryptographydata.model.TranslateKeyMaterialResponse; +import software.amazon.awssdk.services.paymentcryptographydata.model.WrappedKeyMaterialFormat; import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.spec.ECGenParameterSpec; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -39,6 +54,9 @@ class PaymentCryptographyDataPlaneTest { private static String keyArn; private static String macKeyArn; + /** The keys the tests made, deleted when the class is done with them. */ + private static final List keyArns = new ArrayList<>(); + @BeforeAll static void setup() { client = TestFixtures.paymentCryptographyDataClient(); @@ -66,6 +84,19 @@ class PaymentCryptographyDataPlaneTest { if (client != null) { client.close(); } + if (keyArns.isEmpty()) { + return; + } + try (PaymentCryptographyClient control = TestFixtures.paymentCryptographyClient()) { + for (String arn : keyArns) { + try { + control.deleteKey(k -> k.keyIdentifier(arn)); + } catch (Exception ignored) { + // The key may already be gone, and real AWS wants a key disabled before + // it is deleted. + } + } + } } @Test @@ -206,6 +237,166 @@ class PaymentCryptographyDataPlaneTest { } /** Bytes as the data plane carries them: hexadecimal. */ + + @Test + @DisplayName("A key is translated from a key the two parties agreed to another key") + void aKeyIsTranslatedFromAKeyTheTwoPartiesAgreedToAnotherKey() throws Exception { + try (PaymentCryptographyClient control = TestFixtures.paymentCryptographyClient()) { + // The authority that vouches for the other party's certificate, and the other + // party. + KeyPair authority = KeyPairGenerator.getInstance("RSA") + .generateKeyPair(); + // The curve is the one the service's key pair is on: the two parties have to be + // on the same curve for the agreement to work. + KeyPairGenerator ecGenerator = KeyPairGenerator.getInstance("EC"); + ecGenerator.initialize(new ECGenParameterSpec("secp256r1")); + KeyPair counterparty = ecGenerator.generateKeyPair(); + String authorityPem = PaymentCryptographyTest.pem(authority, "floci key-exchange CA", + authority, "floci key-exchange CA"); + String counterpartyPem = PaymentCryptographyTest.pem(counterparty, "floci counterparty", + authority, "floci key-exchange CA"); + + String authorityArn = control.importKey(r -> r + .keyMaterial(publicKey -> publicKey.rootCertificatePublicKey(t -> t + .publicKeyCertificate(base64(authorityPem)) + .keyAttributes(a -> a + .keyAlgorithm(KeyAlgorithm.RSA_2048) + .keyClass(KeyClass.PUBLIC_KEY) + .keyUsage(KeyUsage.TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE) + .keyModesOfUse(modes -> modes.verify(true)))))) + .key().keyArn(); + // The key that agrees with the other party. + String agreementArn = control.createKey(r -> r + .keyAttributes(a -> a + .keyAlgorithm(KeyAlgorithm.ECC_NIST_P256) + .keyClass(KeyClass.ASYMMETRIC_KEY_PAIR) + .keyUsage(KeyUsage.TR31_K3_ASYMMETRIC_KEY_FOR_KEY_AGREEMENT) + .keyModesOfUse(m -> m.deriveKey(true))) + .exportable(true)).key().keyArn(); + // The key that is translated, and the key it is translated under. + String keyArn = control.createKey(r -> r + .keyAttributes(a -> a + .keyAlgorithm(KeyAlgorithm.AES_128) + .keyClass(KeyClass.SYMMETRIC_KEY) + .keyUsage(KeyUsage.TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY) + .keyModesOfUse(m -> m.encrypt(true).decrypt(true))) + .exportable(true)).key().keyArn(); + String kekArn = control.createKey(r -> r + .keyAttributes(a -> a + .keyAlgorithm(KeyAlgorithm.AES_128) + .keyClass(KeyClass.SYMMETRIC_KEY) + .keyUsage(KeyUsage.TR31_K0_KEY_ENCRYPTION_KEY) + .keyModesOfUse(m -> m.wrap(true).unwrap(true))) + .exportable(true)).key().keyArn(); + // Every key the test made is deleted when the class is done with it. + keyArns.add(authorityArn); + keyArns.add(agreementArn); + keyArns.add(keyArn); + keyArns.add(kekArn); + + String exported = control.exportKey(r -> r + .exportKeyIdentifier(keyArn) + .keyMaterial(m -> m.diffieHellmanTr31KeyBlock(controlAgreement( + authorityArn, agreementArn, counterpartyPem)))) + .wrappedKey().keyMaterial(); + + TranslateKeyMaterialResponse translated = client.translateKeyMaterial(r -> r + .incomingKeyMaterial(i -> i.diffieHellmanTr31KeyBlock(dataAgreement( + authorityArn, agreementArn, counterpartyPem, exported))) + .outgoingKeyMaterial(o -> o.tr31KeyBlock(t -> t.wrappingKeyIdentifier(kekArn)))); + + // The block that goes out opens under the key the request named, and it holds the + // key that came in. + Key imported = control.importKey(r -> r + .keyMaterial(m -> m.tr31KeyBlock(t -> t + .wrappingKeyIdentifier(kekArn) + .wrappedKeyBlock(translated.wrappedKey().wrappedKeyMaterial())))) + .key(); + // The key that came in is a key of the service now, so it is deleted with the + // others when the class is done. + keyArns.add(imported.keyArn()); + + assertThat(imported.keyCheckValue()).isNotBlank(); + assertThat(translated.wrappedKey().wrappedKeyMaterialFormat()) + .isEqualTo(WrappedKeyMaterialFormat.TR31_KEY_BLOCK); + } + } + + /** + * The agreement the two parties made, in the builder of the control plane. + * + *

The export that makes the block that comes in is the control plane's, and it names + * the agreement the same way the translation does, so the members of the agreement are + * written once for each plane. + * + * @param authorityArn the key of the authority that vouches for the counterparty + * @param agreementArn the key the two parties agree with + * @param counterpartyPem the certificate the counterparty brings + * @return the agreement, as the control plane names it + */ + private static ExportDiffieHellmanTr31KeyBlock controlAgreement(String authorityArn, + String agreementArn, + String counterpartyPem) { + return ExportDiffieHellmanTr31KeyBlock.builder() + .privateKeyIdentifier(agreementArn) + .certificateAuthorityPublicKeyIdentifier(authorityArn) + .publicKeyCertificate(base64(counterpartyPem)) + .deriveKeyAlgorithm(CONTROL_DERIVE_ALGORITHM) + .keyDerivationFunction(CONTROL_KDF) + .keyDerivationHashAlgorithm(CONTROL_HASH) + .derivationData(d -> d.sharedInformation(SHARED_INFORMATION)) + .build(); + } + + /** + * The agreement the two parties made, in the builder of the data plane. + * + * @param authorityArn the key of the authority that vouches for the counterparty + * @param agreementArn the key the two parties agree with + * @param counterpartyPem the certificate the counterparty brings + * @param block the block that comes in + * @return the agreement, as the data plane names it + */ + private static IncomingDiffieHellmanTr31KeyBlock dataAgreement(String authorityArn, + String agreementArn, + String counterpartyPem, + String block) { + return IncomingDiffieHellmanTr31KeyBlock.builder() + .privateKeyIdentifier(agreementArn) + .certificateAuthorityPublicKeyIdentifier(authorityArn) + .publicKeyCertificate(base64(counterpartyPem)) + .deriveKeyAlgorithm(SymmetricKeyAlgorithm.AES_128) + .keyDerivationFunction(KeyDerivationFunction.ANSI_X963) + .keyDerivationHashAlgorithm(KeyDerivationHashAlgorithm.SHA_256) + .derivationData(d -> d.sharedInformation(SHARED_INFORMATION)) + .wrappedKeyBlock(block) + .build(); + } + + /** + * The algorithm the agreed key is derived in, as the control plane names it. + * + *

The two planes have their own enums for it, and the export that makes the block + * that comes in is the control plane's. + */ + private static final software.amazon.awssdk.services.paymentcryptography.model.SymmetricKeyAlgorithm + CONTROL_DERIVE_ALGORITHM = + software.amazon.awssdk.services.paymentcryptography.model.SymmetricKeyAlgorithm.AES_128; + private static final software.amazon.awssdk.services.paymentcryptography.model.KeyDerivationFunction + CONTROL_KDF = + software.amazon.awssdk.services.paymentcryptography.model.KeyDerivationFunction.ANSI_X963; + private static final software.amazon.awssdk.services.paymentcryptography.model.KeyDerivationHashAlgorithm + CONTROL_HASH = + software.amazon.awssdk.services.paymentcryptography.model.KeyDerivationHashAlgorithm.SHA_256; + + /** The shared information the two parties agree with. */ + private static final String SHARED_INFORMATION = "00112233445566778899AABBCCDDEEFF"; + + /** The PEM of a certificate over a key pair, signed by an issuer. */ + private static String base64(String text) { + return Base64.getEncoder().encodeToString(text.getBytes(StandardCharsets.US_ASCII)); + } + private static String hex(String text) { StringBuilder sb = new StringBuilder(); for (byte b : text.getBytes(StandardCharsets.UTF_8)) { diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyPinTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyPinTest.java index e840b10002..c9eeea595e 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyPinTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyPinTest.java @@ -150,6 +150,41 @@ class PaymentCryptographyPinTest { .isInstanceOf(VerificationFailedException.class); } + @Test + @DisplayName("a PIN block in a format the reference does not verify is refused") + void aBlockInAFormatTheReferenceDoesNotVerifyIsRefused() { + // The reference's page for the operation says it supports ISO_Format_0 and + // ISO_Format_3, so a verification that names the format 4 is refused. + String aesKeyArn = createKeyArn(KeyAlgorithm.AES_128, + KeyUsage.TR31_P0_PIN_ENCRYPTION_KEY, m -> m.encrypt(true).decrypt(true)); + + String block4 = client.generatePinData(r -> r + .encryptionKeyIdentifier(aesKeyArn) + .generationKeyIdentifier(visaVerificationKeyArn) + .pinBlockFormat(PinBlockFormatForPinData.ISO_FORMAT_4) + .primaryAccountNumber(PAN) + .generationAttributes(PinGenerationAttributes.builder() + .visaPin(VisaPin.builder() + .pinVerificationKeyIndex(VERIFICATION_KEY_INDEX) + .build()) + .build())) + .encryptedPinBlock(); + + assertThatThrownBy(() -> client.verifyPinData(r -> r + .encryptionKeyIdentifier(aesKeyArn) + .verificationKeyIdentifier(visaVerificationKeyArn) + .pinBlockFormat(PinBlockFormatForPinData.ISO_FORMAT_4) + .primaryAccountNumber(PAN) + .encryptedPinBlock(block4) + .verificationAttributes(PinVerificationAttributes.builder() + .visaPin(VisaPinVerification.builder() + .pinVerificationKeyIndex(VERIFICATION_KEY_INDEX) + .verificationValue("1234") + .build()) + .build()))) + .isInstanceOf(ValidationException.class); + } + @Test void aPinBlockTranslatesFromTheAesFormatToTheTdesOne() { String aesKeyArn = createKeyArn(KeyAlgorithm.AES_128, diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyTest.java index f6536cd8ea..7364150411 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyTest.java @@ -1128,6 +1128,22 @@ class PaymentCryptographyTest { return generator.generateKeyPair(); } + + /** + * The PEM of a certificate over a key pair, signed by an issuer. + * + *

The service reads a certificate as the base64 of its PEM, so the PEM is what the + * tests hand it. + */ + static String pem(KeyPair subject, String subjectName, KeyPair issuer, String issuerName) + throws Exception { + X509Certificate certificate = certificate(subject, subjectName, issuer, issuerName); + return "-----BEGIN CERTIFICATE-----\n" + + Base64.getMimeEncoder(64, "\n".getBytes(StandardCharsets.US_ASCII)) + .encodeToString(certificate.getEncoded()) + + "\n-----END CERTIFICATE-----\n"; + } + /** A certificate over a key pair, signed by an issuer. */ private static X509Certificate certificate(KeyPair subject, String subjectName, KeyPair issuer, String issuerName) throws Exception { diff --git a/docs/services/index.md b/docs/services/index.md index 50f455603b..503686d3ae 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -35,7 +35,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Kinesis](kinesis.md) | `POST /` + `X-Amz-Target: Kinesis_20131202.*` | JSON 1.1 | 32 | | [Managed Service for Apache Flink](kinesisanalytics.md) | `POST /` + `X-Amz-Target: KinesisAnalytics_20180523.*` | JSON 1.1 | 15 | | [Payment Cryptography](payment-cryptography.md) | `POST /` + `X-Amz-Target: PaymentCryptographyControlPlane.*` | JSON 1.0 | 32 | -| [Payment Cryptography data plane](payment-cryptography-data.md) | `POST /keys/{KeyIdentifier}/encrypt` and the rest | REST JSON | 12 | +| [Payment Cryptography data plane](payment-cryptography-data.md) | `POST /keys/{KeyIdentifier}/encrypt` and the rest | REST JSON | 13 | | [Secrets Manager](secrets-manager.md) | `POST /` + `X-Amz-Target: secretsmanager.*` | JSON 1.1 | 23 | | [Step Functions](step-functions.md) | `POST /` + `X-Amz-Target: AmazonStatesService.*` | JSON 1.1 | 32 | | [SWF](swf.md) | `POST /` + `X-Amz-Target: SimpleWorkflowService.*` | JSON 1.0 | 39 | diff --git a/docs/services/payment-cryptography-data.md b/docs/services/payment-cryptography-data.md index 6b850a5b0d..6ac07e2c69 100644 --- a/docs/services/payment-cryptography-data.md +++ b/docs/services/payment-cryptography-data.md @@ -15,6 +15,7 @@ client that talks to the control plane does not reach it by accident. | `EncryptData` | Encrypt plaintext under a key, on `POST /keys/{KeyIdentifier}/encrypt` | | `DecryptData` | Decrypt a ciphertext under a key, on `POST /keys/{KeyIdentifier}/decrypt` | | `ReEncryptData` | Decrypt under one key and encrypt under another, on `POST /keys/{IncomingKeyIdentifier}/reencrypt` | +| `TranslateKeyMaterial` | Move a key from a key the two parties agreed to another key, on `POST /keymaterial/translate` | | `GenerateMac` | A MAC of a message under a key, on `POST /mac/generate` | | `VerifyMac` | Verify a MAC over a message, on `POST /mac/verify` | | `GeneratePinData` | Generate a PIN block and the verification value that goes with it, on `POST /pindata/generate` | @@ -35,11 +36,27 @@ client that talks to the control plane does not reach it by accident. the plaintext it holds: the initialization vector travels in the request's attributes, and a request that names none gets a zero vector. The blobs of the data plane are hexadecimal, which is what the reference says they are. +- **Only the CBC mode is made.** The reference's model names eight block cipher modes for the + symmetric encryption, and the reference's page for the attributes names them as the valid + values. This service makes the CBC one, so a request that names the ECB, the CFB, the CFB1, the + CFB8, the CFB64, the CFB128 or the OFB mode is refused with `ValidationException` rather than + answered with a cipher of another kind. The padding of the symmetric attributes belongs to the + RSA cipher, so a request that names one is refused as well. - **The MAC is the one the request asks for.** The ISO 9797-1 algorithms 1 and 3 are the ones defined over Triple DES, and the CMAC is the AES-CMAC of RFC 4493, which is a whole block wide, so it is cut to a length the caller asks for. The service fails the request when the MAC is not the one over the message, because the answer of a verification has no verdict in it. +- **The MAC algorithms this service makes are the three the model names beside the DUKPT ones.** + The ISO 9797-1 algorithms 1 and 3, the CMAC, and the DUKPT derivations of the two ISO 9797 + algorithms are made. The HMAC family, the EMV MAC, the DUKPT CMAC and the AS 2805 4.1 MAC + are not, so a request that names one of them is refused with `ValidationException`. The + reference makes them, and the reference's page for the operation says a HMAC can be asked + for, so this is a deviation and not a rule of the model. +- **The length of a MAC is the one the algorithm gives.** The model states the range of four to + thirty-two bytes, and the length a request asks for is refused when the algorithm gives a + shorter one. The reference names the lengths that hold for each algorithm, and this service + takes any length the algorithm can give. - **The modes of use of a key decide what it may be used for.** A key without the `Encrypt` mode is refused for an encryption, and a key with `NoRestrictions` is refused for nothing. - **The usage of a key decides what it may be used for.** The modes say whether a key may be @@ -58,6 +75,11 @@ client that talks to the control plane does not reach it by accident. over is a four-digit one and a longer PIN has no verification value. A PIN that does not verify fails the request with `VerificationFailedException`, because the answer of a verification has no verdict in it. +- **A verification reads the two Triple DES formats.** The reference's page for `VerifyPinData` + says "AWS Payment Cryptography supports `ISO_Format_0` and `ISO_Format_3`", while the + generation reads the format 4 as well, so a verification that names the format 4 or the + format 1 is refused with `ValidationException`. The format 1 is a format ISO 9564-1 defines + that this service does not make anywhere, so a request that asks for one is refused. - **A PIN block that is not one the service can read is a different failure.** A block that does not decipher into a PIN field, because the key is another one, the account number is another one, or the block is corrupted, is refused with `ValidationException` and the @@ -73,12 +95,39 @@ client that talks to the control plane does not reach it by accident. Triple DES one, so a request that asks for another of the five the model allows is refused, and the PIN key it derives both encrypts and decrypts, so a key variant other than the bidirectional one is refused. +- **The key material of a key may be translated:** `TranslateKeyMaterial` takes a key block + that came under a key two parties agreed with ECDH, and answers with the same key wrapped + under the key the request names. The key material never leaves the service: the block is + opened under the agreed key and wrapped again under the other one, and the block that goes + out carries the attributes of the key it holds, its version and its optional blocks with + them. The reference has it for the keys that + are rotated for every transaction, such as a PEK wrapped under a key that was agreed + with ECDH, so the key is moved to another wrapping key without being imported. +- **A translation is refused when the key that protects it is too weak.** The agreed key + opens the block that comes in and the wrapping key closes the one that goes out, so both + have to be at least as strong as the key they protect, the rule the export and the import + enforce. A key that may not leave the service is refused as well: a block that carries the + exportability `N` holds a key that may not be exported, and the block that goes out is + handed to the caller. The usage the block carries has to be one the algorithm serves, the + rule the import and the creation enforce, so a block that names a signature key and an AES + key at once is refused. The check value algorithm the request names has to be the one the + key has, the CMAC for an AES key and the ANSI X9.24 one for a Triple DES key, and a request + that names another one is refused rather than answered with a value of another kind. - **The PIN operations are not the IBM 3624 ones, and the AS2805 translation is not made.** A request that asks for one of them is refused with the error that says so, rather than answered with something of another kind. The EMV PIN change MAC is refused as well: it needs the session key the EMV secure messaging rules define, which this service does not make. It is not one of the actions the service lists as supported. The wrapped-key form of a PIN encryption key is refused too, because the unwrapping is part of the key exchange. +- **The AS2805 key validation is not served.** The reference publishes the operation + `GenerateAs2805KekValidation`, which answers with the two random numbers the AS2805 + ceremony makes of one, and this service has no route for it: a request for it does not + reach a payment cryptography operation at all. +- **The UnionPay session key derivation is not made.** The reference's model names six ways + of deriving the session key of an authorization request, and this service makes three of + them: the EMV common session key, the Mastercard one and the Visa one, which derives none. + The EMV 2000 one and the American Express one are refused, and so is the UnionPay one, each + with the error that says so. - **The wrapped key is refused on every operation that carries one.** The encrypt, decrypt and re-encrypt requests hold a wrapped key for the key exchange, and the unwrapping is part of that exchange rather than part of the cipher, so a request that carries one is @@ -148,6 +197,10 @@ client that talks to the control plane does not reach it by accident. hexadecimal characters is a request the model allows and the cipher cannot read. The track data, the transaction data and the proprietary authentication data are the members it applies to, and the refusal names the member. +- **The quotas of the reference are not enforced.** The reference holds five hundred + symmetric data plane requests a second and twenty asymmetric ones, and it throttles the + request that passes the limit. The emulator holds no such limit, and answers every request + it is given. The two-segment paths are moved to an internal prefix for the requests signed for this service, so a path-style request for a bucket of that name still reaches S3. diff --git a/docs/services/payment-cryptography.md b/docs/services/payment-cryptography.md index 17e795230f..7ab3267e47 100644 --- a/docs/services/payment-cryptography.md +++ b/docs/services/payment-cryptography.md @@ -80,8 +80,16 @@ `KeyModesOfUse` of the key are required, as the reference requires them. The answer carries every mode of use the reference gives a key, the ones the key was not made with as false, so a caller reading them finds a boolean for each of them. The check - value is a CMAC, which is the only algorithm this service computes, so a request - naming another one is refused. + value is a CMAC under an AES key and the ANSI X9.24 value under a Triple DES one, and a + request that names another one is refused. +- **The key attributes this service makes.** The algorithms are the Triple DES, the AES, + the RSA and the ECC ones, so the HMAC algorithms the reference's model names, which fix + the hash of the key at its creation, are refused. The SHA-1 check value the reference's + model also names is refused as well. The classes are the symmetric key, the asymmetric + key pair and the public key, so the private key class the reference's model also names is + refused. The usage says what the key is for and the algorithm has to serve it, so a key + of a MAC usage may not be made of an AES key, and the asymmetric usages take the key + pairs the reference's table gives them. - **Which key a request may name:** `KeyIdentifier` takes the ARN of a key, the ARN of an alias or the name of an alias, while `KeyArn` and `ResourceArn` take the ARN of a key alone, as the reference states them. A request naming a key another way is @@ -261,6 +269,9 @@ - **The replication is in sync at once:** the service does not model the progress of a replication, so the status of a replica that is there is `SYNCHRONIZED` right away, where the reference answers `IN_PROGRESS` until the replication has finished. +- **The quotas of the reference are not enforced.** The reference holds two thousand keys + and two thousand aliases in a Region and throttles the control plane to five requests a + second. The emulator holds no such limit, and answers every request it is given. - **Resource policies:** `PutResourcePolicy` attaches or replaces the policy stored on the key, `GetResourcePolicy` returns it and `DeleteResourcePolicy` removes it. A key without a policy is answered with `ResourceNotFoundException` by both reads. The policy is a JSON diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoController.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoController.java index 0b5218e92f..59f1a55444 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoController.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoController.java @@ -55,6 +55,12 @@ public class PaymentCryptographyCryptoController extends PaymentCryptographyData return respond(handler.reEncryptData(request, region(headers))); } + @POST + @Path("/keymaterial/translate") + public Response translateKeyMaterial(String body, @Context HttpHeaders headers) { + return respond(handler.translateKeyMaterial(parse(body), region(headers))); + } + @POST @Path("/mac/generate") public Response generateMac(String body, @Context HttpHeaders headers) { diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoHandler.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoHandler.java index 4e0505eed9..f6e69a3b86 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoHandler.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoHandler.java @@ -9,6 +9,7 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import java.security.MessageDigest; +import java.util.ArrayList; import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.List; @@ -207,10 +208,40 @@ public class PaymentCryptographyCryptoHandler { /** The cryptogram of an authorization request, generated. */ - /** The material of a key translated into another form. */ + /** + * The material of a key translated into another form. + * + *

The key material never leaves the service: the block comes in under the key the two + * parties agreed with ECDH, it is opened there, and it is wrapped again under the key the + * request names. + */ public Map translateKeyMaterial(JsonNode request, String region) { - refused("TranslateKeyMaterial"); - return Map.of(); + // The request is checked against the constraints the model states for it. + PaymentCryptographyDataRequestShapes.check("TranslateKeyMaterial", request); + return service.translateKeyMaterial(region, members(request)); + } + + /** The members of a request, as the map the exchange reads. */ + private static Map members(JsonNode node) { + Map out = new LinkedHashMap<>(); + if (node == null || !node.isObject()) { + return out; + } + node.properties().forEach(entry -> out.put(entry.getKey(), member(entry.getValue()))); + return out; + } + + /** The value of a member, as the exchange reads it. */ + private static Object member(JsonNode node) { + if (node.isObject()) { + return members(node); + } + if (node.isArray()) { + List values = new ArrayList<>(); + node.forEach(value -> values.add(member(value))); + return values; + } + return node.asText(); } /** diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchange.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchange.java index 2f77c8ae3e..e63afbfcac 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchange.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchange.java @@ -248,15 +248,7 @@ final class PaymentCryptographyKeyExchange { private Exported exportTr31(String region, PaymentCryptographyKey key, byte[] clear, Map material) { String wrappingKeyIdentifier = text(material, "WrappingKeyIdentifier"); - PaymentCryptographyKey protection = usableKey(wrappingKeyIdentifier, region); - if (!PaymentCryptographyService.isKeyEncryptionKey(protection.getKeyUsage())) { - throw validation("the key " + protection.getArn() + " is not a key encryption key, so " - + "it cannot wrap a key block"); - } - if (!PaymentCryptographyService.mayWrap(protection)) { - throw validation("the key " + protection.getArn() + " does not have the mode of use " - + "Wrap, which it needs to wrap a key"); - } + PaymentCryptographyKey protection = wrappingKey(wrappingKeyIdentifier, region); String tooWeak = PaymentCryptographyKeyStrength.refusal( protection.getKeyAlgorithm(), key.getKeyAlgorithm()); if (tooWeak != null) { @@ -558,6 +550,144 @@ final class PaymentCryptographyKeyExchange { } /** A key out of a block the two parties agreed with ECDH. */ + + /** + * The material of a key that came under a key the two parties agreed with, and goes out + * under another key. + * + *

The key material never leaves the service: the block comes in under the key the two + * parties agreed with ECDH, it is opened there, and it is wrapped again under the key the + * request names. The block that goes out carries the attributes of the key it holds, so + * the key that is translated is the same key on the way out. + * + * @param region the region the request is in + * @param material the request's members + * @return the wrapped key, its check value and the format it is in + */ + Map translateKeyMaterial(String region, Map material) { + Map incoming = object(material, "IncomingKeyMaterial"); + Map incomingBlock = object(incoming, "DiffieHellmanTr31KeyBlock"); + Map outgoing = object(material, "OutgoingKeyMaterial"); + Map outgoingBlock = object(outgoing, "Tr31KeyBlock"); + + String wrappingKeyIdentifier = text(outgoingBlock, "WrappingKeyIdentifier"); + PaymentCryptographyKey protection = wrappingKey(wrappingKeyIdentifier, region); + + Agreed agreed = agreed(region, incomingBlock); + String block = text(incomingBlock, "WrappedKeyBlock"); + byte[] clear; + try { + clear = PaymentCryptographyTr31.unwrap(block, agreed.derived()); + } catch (RuntimeException e) { + throw validation("the key block did not open under the key the two parties agreed: " + + e.getMessage()); + } + // The block that came in carries the attributes of the key it holds, and the block + // that goes out carries the same ones. The usage and the mode of use are read + // through the helpers the import reads them through, and they refuse a value this + // service does not serve, so a block that names one is refused here rather than + // answered with a block the import would refuse. + String usage = PaymentCryptographyTr31.usageOf(block); + String mode = PaymentCryptographyTr31.modeOf(block); + String exportability = PaymentCryptographyTr31.exportabilityOf(block); + String usageName = PaymentCryptographyService.usageName(usage); + PaymentCryptographyService.modesFor(mode); + if (!"E".equals(exportability) && !"N".equals(exportability) && !"S".equals(exportability)) { + throw validation("the key block carries the exportability '" + exportability + + "', which is not one of E, N or S"); + } + if ("N".equals(exportability)) { + // The key in the block may not leave the service again, and the block that goes + // out is handed to the caller, so a key that may not leave is refused. + throw validation("the key block carries the exportability N, so the key in it may " + + "not leave the service and may not be translated out of it"); + } + + PaymentCryptographyKeyAlgorithm algorithm = PaymentCryptographyKeyAlgorithm.from( + PaymentCryptographyService.algorithmOf(block, clear.length)); + // The usage binds the key to its purpose, so a key whose algorithm does not serve + // that purpose is not one the service makes. The rule is the one the import and the + // creation enforce, and a block that breaks it is refused here rather than answered + // with a block the import would refuse. + String badAlgorithm = PaymentCryptographyKeyAlgorithm.refusal(usageName, algorithm); + if (badAlgorithm != null) { + throw validation(badAlgorithm); + } + // The agreed key opens the block that comes in, and the wrapping key closes the one + // that goes out, so both have to be at least as strong as the key they protect. The + // rule is the one the import and the export enforce. + requireAgreedStrength(agreed, algorithm.name()); + String tooWeak = PaymentCryptographyKeyStrength.refusal(protection.getKeyAlgorithm(), + algorithm.name()); + if (tooWeak != null) { + throw validation(tooWeak); + } + requireCheckValueAlgorithm(material, algorithm); + + String wrapped = PaymentCryptographyTr31.wrap(clear, + PaymentCryptographyKeyRules.material(protection), + PaymentCryptographyService.isAes(protection), + PaymentCryptographyTr31.algorithmInHeader(block), + usage, + mode, + exportability, + PaymentCryptographyTr31.versionOf(block), + PaymentCryptographyTr31.optionalBlocksOf(block)); + + Map out = new LinkedHashMap<>(); + out.put("WrappedKeyMaterial", wrapped); + out.put("KeyCheckValue", PaymentCryptographyCrypto.checkValue(clear, algorithm)); + out.put("WrappedKeyMaterialFormat", "TR31_KEY_BLOCK"); + return Map.of("WrappedKey", out); + } + + /** + * The check value algorithm a request names, and it has to be the one the key has. + * + *

An AES key's check value is a CMAC and a Triple DES key's is the ANSI X9.24 one, + * so a request that names another one asks for a value the service does not compute, + * and it is refused rather than answered with the value of another algorithm. + * + * @param material the request's members + * @param algorithm the algorithm of the key that is translated + */ + private static void requireCheckValueAlgorithm(Map material, + PaymentCryptographyKeyAlgorithm algorithm) { + String wanted = text(material, "KeyCheckValueAlgorithm"); + if (wanted.isEmpty()) { + return; + } + String own = algorithm.checkValueAlgorithm(); + if (!own.equals(wanted)) { + throw validation("the check value algorithm " + wanted + " is not the one a " + + algorithm.name() + " key has, which is " + own); + } + } + + /** + * The strength of the key the two parties agreed, held against the key it protects. + * + *

The agreement is only as strong as the curve it was made on, so the weaker of the + * derivation and the two curves decides, the way the export decides. + * + * @param agreed the agreed key + * @param algorithm the algorithm of the key the agreement protects + */ + private static void requireAgreedStrength(Agreed agreed, String algorithm) { + int derivedBits = Math.min( + PaymentCryptographyKeyStrength.bitsOf(agreed.deriveAlgorithm().name()), + Math.min( + PaymentCryptographyKeyStrength.eccBitsOf( + agreed.serviceKey().getKeyAlgorithm()), + PaymentCryptographyKeyStrength.eccBitsOf((ECKey) agreed.counterpartyKey()))); + String tooWeak = PaymentCryptographyKeyStrength.refusal(derivedBits, + PaymentCryptographyKeyStrength.bitsOf(algorithm), + agreed.deriveAlgorithm().name(), algorithm); + if (tooWeak != null) { + throw validation(tooWeak); + } + } + private Imported importEcdh(String region, Map material) { String block = text(material, "WrappedKeyBlock"); Agreed agreed = agreed(region, material); @@ -574,18 +704,7 @@ final class PaymentCryptographyKeyExchange { boolean exportable = exportableOnImport(PaymentCryptographyTr31.exportabilityOf(block)); String algorithm = PaymentCryptographyService.algorithmOf(block, clear.length); // The derived key protects the imported one, so it has to be as strong as it. - int derivedBits = Math.min( - PaymentCryptographyKeyStrength.bitsOf(agreed.deriveAlgorithm().name()), - Math.min( - PaymentCryptographyKeyStrength.eccBitsOf( - agreed.serviceKey().getKeyAlgorithm()), - PaymentCryptographyKeyStrength.eccBitsOf((ECKey) agreed.counterpartyKey()))); - String tooWeak = PaymentCryptographyKeyStrength.refusal(derivedBits, - PaymentCryptographyKeyStrength.bitsOf(algorithm), - agreed.deriveAlgorithm().name(), algorithm); - if (tooWeak != null) { - throw validation(tooWeak); - } + requireAgreedStrength(agreed, algorithm); return new Imported(algorithm, PaymentCryptographyService.usageName(usage), PaymentCryptographyService.modesFor(mode), exportable, clear, null, null, null, "SYMMETRIC_KEY"); @@ -924,6 +1043,29 @@ final class PaymentCryptographyKeyExchange { } } + /** + * The key a block is wrapped under, and it has to be one that may wrap. + * + *

The export and the translation both wrap a block under a key the request names, so + * they insist on the same of it: a key encryption key that is allowed to wrap. + * + * @param identifier the key's identifier + * @param region the region the key is in + * @return the key the block is wrapped under + */ + private PaymentCryptographyKey wrappingKey(String identifier, String region) { + PaymentCryptographyKey protection = usableKey(identifier, region); + if (!PaymentCryptographyService.isKeyEncryptionKey(protection.getKeyUsage())) { + throw validation("the key " + protection.getArn() + " is not a key encryption key, so " + + "it cannot wrap a key block"); + } + if (!PaymentCryptographyService.mayWrap(protection)) { + throw validation("the key " + protection.getArn() + " does not have the mode of use " + + "Wrap, which it needs to wrap a key"); + } + return protection; + } + /** * The key an identifier names, and it has to be one the service does work with. * diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyPinOperations.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyPinOperations.java index 049450d8fc..e91245bd65 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyPinOperations.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyPinOperations.java @@ -105,7 +105,7 @@ public class PaymentCryptographyPinOperations { String encryptionKeyIdentifier = text(request, "EncryptionKeyIdentifier"); String verificationKeyIdentifier = text(request, "VerificationKeyIdentifier"); refuseWrappedKey(request, "EncryptionWrappedKey"); - PinBlockFormat format = format(text(request, "PinBlockFormat")); + PinBlockFormat format = verificationFormat(text(request, "PinBlockFormat")); String pan = requirePan(text(request, "PrimaryAccountNumber"), "PrimaryAccountNumber is required for Visa PVV verification"); requireVisaPinLength(request); @@ -516,6 +516,27 @@ public class PaymentCryptographyPinOperations { return format; } + /** + * The PIN block format a verification reads. + * + *

The reference names the formats it supports for this operation: "AWS Payment + * Cryptography supports {@code ISO_Format_0} and {@code ISO_Format_3}". The format 4 + * block is an AES block, and the reference's verification reads the Triple DES blocks, so + * a request that names the format 4 is refused rather than answered as if the reference + * read it. + * + * @param wireName the name the request carries + * @return the format the block is in + */ + private static PinBlockFormat verificationFormat(String wireName) { + PinBlockFormat format = PinBlockFormat.from(wireName); + if (format != PinBlockFormat.ISO_FORMAT_0 && format != PinBlockFormat.ISO_FORMAT_3) { + throw validation("PinBlockFormat '" + wireName + "' is not a format the reference " + + "verifies (ISO_FORMAT_0, ISO_FORMAT_3)"); + } + return format; + } + /** * The verification key index the attributes name. * diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyService.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyService.java index a335fa38a4..35163f6ee9 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyService.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyService.java @@ -1570,6 +1570,18 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn return exchange.publicKeyCertificate(key); } + /** + * The material of a key that came under a key the two parties agreed with, and goes out + * under another key. + * + * @param region the region the request is in + * @param material the request's members + * @return the wrapped key, its check value and the format it is in + */ + public Map translateKeyMaterial(String region, Map material) { + return exchange.translateKeyMaterial(region, material); + } + /** The parameters a counterparty needs to import a key into this service. */ public Map parametersForImport(String materialType, String algorithm, boolean reuse) { diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyTr31.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyTr31.java index 6332c4776c..b23b334441 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyTr31.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyTr31.java @@ -271,6 +271,74 @@ final class PaymentCryptographyTr31 { return block.substring(5, 7); } + /** + * The version of the key a block carries, over two characters. + * + *

The version is in the header, so it is read from there and not carried separately. + */ + static String versionOf(String block) { + return block.substring(9, 11); + } + + /** + * The optional blocks a block carries, each its identifier and its value. + * + *

The padding block is not one of them: it is the block that keeps the optional + * blocks aligned, and the block that goes out is padded for its own protection, so the + * padding of the block that came in is dropped. + * + * @param block the block + * @return the optional blocks, without the padding block + */ + static List optionalBlocksOf(String block) { + int count = parseInt(block.substring(12, 14), "the number of optional blocks"); + List blocks = new ArrayList<>(); + int at = HEADER_LENGTH; + for (int i = 0; i < count; i++) { + if (block.length() < at + 4) { + throw new IllegalArgumentException("the key block says it has optional blocks, and " + + "it is too short to hold them"); + } + String id = block.substring(at, at + 2); + int length = parseInt(block.substring(at + 2, at + 4), + "the length of an optional block", 16); + int valueStart; + int valueLength; + int total; + if (length != 0) { + valueStart = at + 4; + valueLength = length - 4; + total = length; + } else { + // The length did not fit in its field, so the field says so and the length + // follows the number of characters it takes. + if (block.length() < at + 6) { + throw new IllegalArgumentException("the key block says it has optional blocks, " + + "and it is too short to hold them"); + } + int digits = parseInt(block.substring(at + 4, at + 6), + "the length of the length of an optional block", 16); + if (digits == 0 || block.length() < at + 6 + digits) { + throw new IllegalArgumentException("the key block says it has optional blocks, " + + "and it is too short to hold them"); + } + valueLength = parseInt(block.substring(at + 6, at + 6 + digits), + "the length of an optional block", 16); + valueStart = at + 6 + digits; + total = 6 + digits + valueLength; + } + if (valueLength < 0 || block.length() < at + total) { + throw new IllegalArgumentException("the key block says it has optional blocks, and " + + "it is too short to hold them"); + } + if (!"PB".equals(id)) { + blocks.add(new String[] {id, block.substring(valueStart, valueStart + valueLength)}); + } + at += total; + } + return blocks; + } + /** * Whether a block is a type D one, which is derived with AES. * diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoHandlerTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoHandlerTest.java index e468c62768..42700a3081 100644 --- a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoHandlerTest.java +++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoHandlerTest.java @@ -238,6 +238,58 @@ class PaymentCryptographyCryptoHandlerTest { assertEquals(key.getArn(), verified.get("KeyArn")); } + @Test + void aMacAlgorithmThisServiceDoesNotMakeIsRefused() { + // The reference's page for the operation says a HMAC, a CMAC, a DUKPT or an EMV MAC + // can be asked for, and its model names the HMAC family, the EMV MAC and the DUKPT + // CMAC beside the ones this service makes. This service makes the ISO 9797 + // algorithms 1 and 3 and the CMAC, and a request that asks for another is refused + // with the error that names the ones it makes. + PaymentCryptographyKey key = createTdesKey("Generate", "Verify"); + String message = hex("a message".getBytes()); + for (String algorithm : new String[] {"HMAC", "HMAC_SHA256", "AS2805_4_1"}) { + ObjectNode attributes = mapper.createObjectNode(); + attributes.put("Algorithm", algorithm); + AwsException refused = assertThrows(AwsException.class, + () -> handler.generateMac(request(Map.of( + "KeyIdentifier", key.getArn(), "MessageData", message, + "GenerationAttributes", attributes)), "us-east-1")); + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("CMAC"), refused.getMessage()); + } + for (String variant : new String[] {"EmvMac", "DukptCmac"}) { + ObjectNode attributes = mapper.createObjectNode(); + attributes.put(variant, mapper.createObjectNode()); + AwsException refused = assertThrows(AwsException.class, + () -> handler.generateMac(request(Map.of( + "KeyIdentifier", key.getArn(), "MessageData", message, + "GenerationAttributes", attributes)), "us-east-1")); + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains(variant), refused.getMessage()); + } + } + + @Test + void anEncryptionModeThisServiceDoesNotMakeIsRefused() { + // The reference's model names eight block cipher modes for the symmetric + // encryption, and this service makes the CBC one, so a request that names another is + // refused rather than answered with a cipher of another kind. + PaymentCryptographyKey key = createKey("Encrypt", "Decrypt"); + for (String mode : new String[] {"ECB", "CFB", "CFB8", "OFB"}) { + ObjectNode symmetric = mapper.createObjectNode(); + symmetric.put("Mode", mode); + ObjectNode attributes = mapper.createObjectNode(); + attributes.set("Symmetric", symmetric); + AwsException refused = assertThrows(AwsException.class, + () -> handler.encryptData(request(Map.of( + "KeyIdentifier", key.getArn(), + "PlainText", hex("hello, world!!!!".getBytes()), + "EncryptionAttributes", attributes)), "us-east-1")); + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("CBC"), refused.getMessage()); + } + } + @Test void aMacUnderAThreeKeyTdesKeyIsComputedAndVerified() { // The ISO 9797 MACs are defined over Triple DES, and the cipher takes the three keys diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyDocumentedExceptionsTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyDocumentedExceptionsTest.java new file mode 100644 index 0000000000..97ffd681b6 --- /dev/null +++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyDocumentedExceptionsTest.java @@ -0,0 +1,186 @@ +package io.floci.aws.services.paymentcryptography; + +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; + +/** + * The errors the reference documents, and the status it answers them with. + * + *

The reference's API pages state, for every action, the errors it raises and the status + * each one carries. The control plane answers them all with 400, the not-found error + * included, which is worth a test of its own: an emulator that answers a missing key with a + * 404 is a client-visible difference that no other test would catch. + * + *

The table is the reference's own: an action that names a resource that is not there + * answers with the not-found error. + */ +@QuarkusTest +class PaymentCryptographyDocumentedExceptionsTest { + + /** The control plane of Payment Cryptography is an awsJson 1.0 service. */ + private static final String CONTENT_TYPE = "application/x-amz-json-1.0"; + + private static final String TARGET = "PaymentCryptographyControlPlane."; + + /** A key identifier of a key the service does not hold. */ + private static final String MISSING_KEY = "arn:aws:payment-cryptography:us-east-1:" + + "000000000000:key/0123456789abcdef0123456789abcdef"; + + /** The alias of an alias the service does not hold. */ + private static final String MISSING_ALIAS = "alias/team/missing"; + + /** The key the requests that need one name, made once for the whole class. */ + private static String keyArn; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + /** + * A key of the service, made once for the whole class. + * + *

The requests that name a key make one, so the ones that name a key that is not + * there are answered with the not-found error rather than with the error of a request + * that names nothing. + * + * @return the ARN of the key + */ + private static synchronized String keyArn() { + if (keyArn == null) { + keyArn = given() + .header("X-Amz-Target", TARGET + "CreateKey") + .contentType(CONTENT_TYPE) + .body("{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\"," + + "\"KeyClass\":\"SYMMETRIC_KEY\"," + + "\"KeyUsage\":\"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY\"," + + "\"KeyModesOfUse\":{\"Encrypt\":true,\"Decrypt\":true}}," + + "\"Exportable\":true}") + .when().post("/") + .then().statusCode(200) + .extract().path("Key.KeyArn"); + } + return keyArn; + } + + private static Response call(String action, String body) { + return given() + .header("X-Amz-Target", TARGET + action) + .contentType(CONTENT_TYPE) + .body(body) + .when().post("/"); + } + + /** + * The actions that name a key or an alias, with the body that names one that is not + * there. + * + * @return the action and the body of each of them + */ + private static Stream actionsThatNameAMissingResource() { + return Stream.of( + Arguments.of("GetKey", "{\"KeyIdentifier\":\"" + MISSING_KEY + "\"}"), + Arguments.of("DeleteKey", "{\"KeyIdentifier\":\"" + MISSING_KEY + "\"}"), + Arguments.of("RestoreKey", "{\"KeyIdentifier\":\"" + MISSING_KEY + "\"}"), + Arguments.of("StartKeyUsage", "{\"KeyIdentifier\":\"" + MISSING_KEY + "\"}"), + Arguments.of("StopKeyUsage", "{\"KeyIdentifier\":\"" + MISSING_KEY + "\"}"), + Arguments.of("GetPublicKeyCertificate", "{\"KeyIdentifier\":\"" + MISSING_KEY + "\"}"), + Arguments.of("AddKeyReplicationRegions", "{\"KeyIdentifier\":\"" + MISSING_KEY + + "\",\"ReplicationRegions\":[\"us-west-2\"]}"), + Arguments.of("RemoveKeyReplicationRegions", "{\"KeyIdentifier\":\"" + MISSING_KEY + + "\",\"ReplicationRegions\":[\"us-west-2\"]}"), + Arguments.of("TagResource", "{\"ResourceArn\":\"" + MISSING_KEY + + "\",\"Tags\":[{\"Key\":\"Origin\",\"Value\":\"PRIMARY\"}]}"), + Arguments.of("UntagResource", "{\"ResourceArn\":\"" + MISSING_KEY + + "\",\"TagKeys\":[\"Origin\"]}"), + Arguments.of("ListTagsForResource", "{\"ResourceArn\":\"" + MISSING_KEY + "\"}"), + Arguments.of("GetResourcePolicy", "{\"ResourceArn\":\"" + MISSING_KEY + "\"}"), + Arguments.of("DeleteResourcePolicy", "{\"ResourceArn\":\"" + MISSING_KEY + "\"}"), + Arguments.of("PutResourcePolicy", "{\"ResourceArn\":\"" + MISSING_KEY + + "\",\"Policy\":\"{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[]}\"}"), + Arguments.of("GetAlias", "{\"AliasName\":\"" + MISSING_ALIAS + "\"}"), + Arguments.of("DeleteAlias", "{\"AliasName\":\"" + MISSING_ALIAS + "\"}"), + Arguments.of("UpdateAlias", "{\"AliasName\":\"" + MISSING_ALIAS + "\"}"), + Arguments.of("GetMpaTeamAssociation", + "{\"Action\":\"IMPORT_ROOT_PUBLIC_KEY_CERTIFICATE\"}")); + } + + @ParameterizedTest + @MethodSource("actionsThatNameAMissingResource") + void anActionThatNamesAKeyThatIsNotThereAnswersNotFound(String action, String body) { + // The reference answers a resource it cannot find with the not-found error, and the + // control plane answers every one of its errors with 400. + call(action, body) + .then().statusCode(400) + .body("__type", containsString("ResourceNotFoundException")); + } + + @Test + void anActionThatNamesAnAliasThatIsNotThereAnswersNotFound() { + // The alias of the update is named, and the key it would point at is not there + // either, so the alias is what the request cannot find. + call("UpdateAlias", "{\"AliasName\":\"" + MISSING_ALIAS + "\",\"KeyArn\":\"" + + keyArn() + "\"}") + .then().statusCode(400) + .body("__type", containsString("ResourceNotFoundException")); + } + + @Test + void anActionThatNamesNoResourceAtAllIsRefused() { + // The reference's model makes the member of each of these requests required, so a + // request that leaves it out is refused before the action does any work. + call("GetKey", "{}") + .then().statusCode(400) + .body("__type", containsString("ValidationException")); + call("GetAlias", "{}") + .then().statusCode(400) + .body("__type", containsString("ValidationException")); + call("ListTagsForResource", "{}") + .then().statusCode(400) + .body("__type", containsString("ValidationException")); + } + + @Test + void anActionThatIsNotServedIsRefused() { + call("NotAnAction", "{}") + .then().statusCode(400) + .body("__type", containsString("UnknownOperationException")); + } + + @Test + void anActionThatChangesNothingAnswersWithAnEmptyBody() { + // The reference's pages for these three actions show a response with no members at + // all, so the answer carries nothing. + call("TagResource", "{\"ResourceArn\":\"" + keyArn() + + "\",\"Tags\":[{\"Key\":\"Origin\",\"Value\":\"PRIMARY\"}]}") + .then().statusCode(200) + .body(equalTo("{}")); + call("UntagResource", "{\"ResourceArn\":\"" + keyArn() + "\",\"TagKeys\":[\"Origin\"]}") + .then().statusCode(200) + .body(equalTo("{}")); + // The policy is put first: a key that carries none has no policy to delete, and the + // reference answers that with the not-found error rather than with an empty answer. + // The document is carried in one line: a line break inside a JSON string is not a + // JSON string, and the request would never reach the service. + String policy = PaymentCryptographyTestFixtures.CROSS_ACCOUNT_POLICY + .replaceAll("\\s*\\n\\s*", " "); + call("PutResourcePolicy", "{\"ResourceArn\":\"" + keyArn() + + "\",\"Policy\":\"" + policy.replace("\"", "\\\"") + "\"}") + .then().statusCode(200); + call("DeleteResourcePolicy", "{\"ResourceArn\":\"" + keyArn() + "\"}") + .then().statusCode(200) + .body(equalTo("{}")); + } +} diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchangeTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchangeTest.java index 9580f93d73..9607785e4b 100644 --- a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchangeTest.java +++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchangeTest.java @@ -7,19 +7,28 @@ import io.floci.aws.core.storage.InMemoryStorage; import io.floci.aws.services.acm.CertificateGenerator; import io.floci.aws.services.paymentcryptography.crypto.Certificates; import io.floci.aws.services.paymentcryptography.crypto.CertificatesTest; +import io.floci.aws.services.paymentcryptography.crypto.Ecdh; import io.floci.aws.services.paymentcryptography.crypto.PaymentCryptographyTr34RoundTripTest; import io.floci.aws.services.paymentcryptography.crypto.RsaOaep; import io.floci.aws.services.paymentcryptography.crypto.Tr34; import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey; import io.floci.aws.testing.ManualClock; +import org.bouncycastle.crypto.engines.AESEngine; +import org.bouncycastle.crypto.macs.CMac; +import org.bouncycastle.crypto.params.KeyParameter; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import java.nio.charset.StandardCharsets; import java.security.KeyPair; +import java.security.MessageDigest; +import java.security.PrivateKey; import java.security.SecureRandom; import java.security.cert.X509Certificate; +import java.security.interfaces.ECPrivateKey; +import java.security.interfaces.ECPublicKey; import java.time.Duration; import java.time.Instant; import java.util.HexFormat; @@ -58,6 +67,13 @@ class PaymentCryptographyKeyExchangeTest { /** The variant the terminal major key is bound to. */ private static final String MAJOR_VARIANT = "TERMINAL_MAJOR_KEY_VARIANT_00"; + /** + * The shared information the sample passes: 32 bytes, the same bytes as the KDF's + * other info. + */ + private static final String SAMPLE_SHARED_INFORMATION = + "00112233445566778899AABBCCDDEEFF00112233445566778899AABBCCDDEEFF"; + @BeforeEach void setUp() { service = new PaymentCryptographyService( @@ -217,17 +233,7 @@ class PaymentCryptographyKeyExchangeTest { @Test void aKeyLeavesUnderAKeyTheTwoPartiesAgreed() { // The two parties agree a key with ECDH, and the key leaves in a block under it. - SecureRandom random = new SecureRandom(); - KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random); - KeyPair counterparty = PaymentCryptographyKeyPairs.ec( - PaymentCryptographyKeyAlgorithm.ECC_NIST_P256, random); - Certificates.Minted authorityCertificate = CertificatesTest.mint(authority.getPublic(), - "floci key-exchange CA", authority.getPrivate(), "floci key-exchange CA"); - // The counterparty's certificate is signed by the authority, which is what lets the - // service trust it. - Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(), - "floci counterparty", authority.getPrivate(), "floci key-exchange CA"); - Exchange exchange = agreedExchange(authorityCertificate, counterpartyCertificate); + Exchange exchange = agreedExchange(); Map wrapped = (Map) service.exportKey("us-east-1", exchange.key().getKeyId(), "DiffieHellmanTr31KeyBlock", exchange.material(), "", "").get("WrappedKey"); @@ -244,19 +250,326 @@ class PaymentCryptographyKeyExchangeTest { assertEquals(exchange.key().getKeyUsage(), imported.getKeyUsage()); } + + @Test + void aKeyIsTranslatedFromAKeyTheTwoPartiesAgreedToAnotherKey() { + // The key comes under a key the two parties agreed with ECDH, and it goes out under + // the key the request names. + Exchange exchange = agreedExchange(); + + // The key that leaves under the agreed key. + Map wrapped = (Map) service.exportKey("us-east-1", exchange.key().getKeyId(), + "DiffieHellmanTr31KeyBlock", exchange.material(), "", "").get("WrappedKey"); + + // The key it is translated under. + PaymentCryptographyKey outgoing = createKey("AES_128", "TR31_K0_KEY_ENCRYPTION_KEY"); + + Map translated = (Map) service.translateKeyMaterial("us-east-1", + translateRequest(exchange.material(), (String) wrapped.get("KeyMaterial"), outgoing)) + .get("WrappedKey"); + + assertEquals("TR31_KEY_BLOCK", translated.get("WrappedKeyMaterialFormat")); + // The block that goes out opens under the key the request named, and it holds the key + // that came in. + PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr31KeyBlock", + Map.of("WrappingKeyIdentifier", outgoing.getKeyId(), + "WrappedKeyBlock", translated.get("WrappedKeyMaterial")), + "", true, Map.of()); + assertEquals(exchange.key().getKeyMaterialHex(), imported.getKeyMaterialHex()); + assertEquals(exchange.key().getKeyUsage(), imported.getKeyUsage()); + } + + @Test + void aTranslatedBlockCarriesTheVersionAndTheOptionalBlocksOfTheBlockThatCameIn() { + // The block that came in is authenticated with its header and its optional blocks, + // so the block that goes out carries the same ones. + Exchange exchange = agreedExchange(); + Map material = new LinkedHashMap<>(exchange.material()); + material.put("KeyBlockHeaders", Map.of( + "KeyVersion", "01", + "KeyExportability", "EXPORTABLE", + "OptionalBlocks", Map.of("AB", "0011"))); + Map wrapped = (Map) service.exportKey("us-east-1", exchange.key().getKeyId(), + "DiffieHellmanTr31KeyBlock", material, "", "").get("WrappedKey"); + + PaymentCryptographyKey outgoing = createKey("AES_128", "TR31_K0_KEY_ENCRYPTION_KEY"); + Map translated = (Map) service.translateKeyMaterial("us-east-1", + translateRequest(exchange.material(), (String) wrapped.get("KeyMaterial"), outgoing)) + .get("WrappedKey"); + + String block = (String) translated.get("WrappedKeyMaterial"); + assertEquals("01", block.substring(9, 11), "the version of the key"); + assertEquals("AB", block.substring(16, 18), "the optional block's identifier"); + assertEquals("08", block.substring(18, 20), "the optional block's length"); + } + + @Test + void aKeyThatMayNotLeaveIsNotTranslatedOut() { + // The block that comes in says the key in it may not leave the service, and the + // block that goes out is handed to the caller, so the key may not be translated + // out of it. + Exchange exchange = agreedExchange(); + Map material = new LinkedHashMap<>(exchange.material()); + material.put("KeyBlockHeaders", Map.of("KeyExportability", "NON_EXPORTABLE")); + Map wrapped = (Map) service.exportKey("us-east-1", exchange.key().getKeyId(), + "DiffieHellmanTr31KeyBlock", material, "", "").get("WrappedKey"); + PaymentCryptographyKey outgoing = createKey("AES_128", "TR31_K0_KEY_ENCRYPTION_KEY"); + + AwsException refused = assertThrows(AwsException.class, + () -> service.translateKeyMaterial("us-east-1", translateRequest( + exchange.material(), (String) wrapped.get("KeyMaterial"), outgoing))); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("may not leave the service"), refused.getMessage()); + } + + @Test + void aKeyIsNotTranslatedUnderAKeyWeakerThanIt() { + // The wrapping key has to be at least as strong as the key it protects, the rule + // the export and the import enforce. + Exchange exchange = agreedExchange("ECC_NIST_P521"); + Map material = new LinkedHashMap<>(exchange.material()); + material.put("DeriveKeyAlgorithm", "AES_256"); + PaymentCryptographyKey key = createKey("AES_256", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"); + Map wrapped = (Map) service.exportKey("us-east-1", key.getKeyId(), + "DiffieHellmanTr31KeyBlock", material, "", "").get("WrappedKey"); + PaymentCryptographyKey outgoing = createKey("AES_128", "TR31_K0_KEY_ENCRYPTION_KEY"); + + AwsException refused = assertThrows(AwsException.class, + () -> service.translateKeyMaterial("us-east-1", translateRequest( + material, (String) wrapped.get("KeyMaterial"), outgoing))); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("at least as strong"), refused.getMessage()); + } + + @Test + void aKeyIsNotTranslatedUnderAnAgreementWeakerThanIt() throws Exception { + // The agreed key opens the block that comes in, so it has to be as strong as the + // key in it, the rule the import enforces. + Exchange exchange = agreedExchange(); + Map material = sampleAgreement(exchange); + byte[] derived = sampleDerivedKey(exchange); + // The block carries an AES-256 key, and the agreement is on a curve that is + // weaker than it. + String incoming = PaymentCryptographyTr31.wrap( + HexFormat.of().parseHex( + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"), + derived, true, "A", "D0", "B", "E"); + PaymentCryptographyKey outgoing = createKey("AES_256", "TR31_K0_KEY_ENCRYPTION_KEY"); + + AwsException refused = assertThrows(AwsException.class, + () -> service.translateKeyMaterial("us-east-1", + translateRequest(material, incoming, outgoing))); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("at least as strong"), refused.getMessage()); + } + + @Test + void aKeyWithAUsageItsAlgorithmDoesNotServeIsNotTranslated() throws Exception { + // The usage binds the key to its purpose: a signature key is an asymmetric one, so an + // AES key may not carry that usage. The block that came in says it does, and the + // translation refuses it rather than answering with a block the import would refuse. + Exchange exchange = agreedExchange("ECC_NIST_P521"); + Map material = sampleAgreement(exchange); + byte[] derived = sampleDerivedKey(exchange); + String incoming = PaymentCryptographyTr31.wrap( + HexFormat.of().parseHex( + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"), + derived, true, "A", "S0", "B", "E"); + PaymentCryptographyKey outgoing = createKey("AES_256", "TR31_K0_KEY_ENCRYPTION_KEY"); + + AwsException refused = assertThrows(AwsException.class, + () -> service.translateKeyMaterial("us-east-1", + translateRequest(material, incoming, outgoing))); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("may not be made of"), refused.getMessage()); + } + + @Test + void aKeyIsTranslatedWithTheCheckValueAlgorithmTheRequestNames() { + // The request may name the check value algorithm, and the one it names for an AES + // key is the CMAC. + Exchange exchange = agreedExchange(); + Map wrapped = (Map) service.exportKey("us-east-1", exchange.key().getKeyId(), + "DiffieHellmanTr31KeyBlock", exchange.material(), "", "").get("WrappedKey"); + PaymentCryptographyKey outgoing = createKey("AES_128", "TR31_K0_KEY_ENCRYPTION_KEY"); + Map request = translateRequest(exchange.material(), + (String) wrapped.get("KeyMaterial"), outgoing); + request.put("KeyCheckValueAlgorithm", "CMAC"); + + Map translated = (Map) service.translateKeyMaterial("us-east-1", request) + .get("WrappedKey"); + + assertEquals(cmacKeyCheckValue(exchange.key().getKeyMaterialHex()), + translated.get("KeyCheckValue")); + } + + @Test + void aCheckValueAlgorithmTheKeyDoesNotHaveIsRefused() { + // The check value of an AES key is a CMAC, so a request that asks for the ANSI + // X9.24 one asks for a value this service does not compute. + Exchange exchange = agreedExchange(); + Map wrapped = (Map) service.exportKey("us-east-1", exchange.key().getKeyId(), + "DiffieHellmanTr31KeyBlock", exchange.material(), "", "").get("WrappedKey"); + PaymentCryptographyKey outgoing = createKey("AES_128", "TR31_K0_KEY_ENCRYPTION_KEY"); + Map request = translateRequest(exchange.material(), + (String) wrapped.get("KeyMaterial"), outgoing); + request.put("KeyCheckValueAlgorithm", "ANSI_X9_24"); + + AwsException refused = assertThrows(AwsException.class, + () -> service.translateKeyMaterial("us-east-1", request)); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("check value algorithm"), + refused.getMessage()); + } + + @Test + void aKeyIsTranslatedUnderTheKeyTheSampleDerives() throws Exception { + // The sample derives the one-time wrapping key with the Concat KDF of NIST SP + // 800-56A over the shared secret, with SHA-512 and a 32-byte shared information, + // and the emulator has to derive the same key from the request's parameters. The + // agreement is on a curve as strong as the key it opens, because the agreed key + // has to be at least as strong as the key in the block. + Exchange exchange = agreedExchange("ECC_NIST_P521"); + Map material = sampleAgreement(exchange); + byte[] derived = sampleDerivedKey(exchange); + + // The block that comes in is under the derived key, as the sample wraps it. The + // key in it may leave the service, because the translation hands it to the + // caller. + String incoming = PaymentCryptographyTr31.wrap( + HexFormat.of().parseHex( + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"), + derived, true, "A", "D0", "B", "E"); + + // The wrapping key has to be at least as strong as the key it carries. + PaymentCryptographyKey outgoing = createKey("AES_256", "TR31_K0_KEY_ENCRYPTION_KEY"); + + Map translated = (Map) service.translateKeyMaterial("us-east-1", + translateRequest(material, incoming, outgoing)).get("WrappedKey"); + + // The block that goes out holds the key that came in, and the check value is the + // one the sample computes locally. + PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr31KeyBlock", + Map.of("WrappingKeyIdentifier", outgoing.getKeyId(), + "WrappedKeyBlock", translated.get("WrappedKeyMaterial")), + "", true, Map.of()); + assertEquals("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + imported.getKeyMaterialHex()); + assertEquals(cmacKeyCheckValue(imported.getKeyMaterialHex()), translated.get("KeyCheckValue")); + } + + /** + * The request that translates a block that came in under the agreed key. + * + * @param material the material of the agreement + * @param block the block that comes in + * @param wrappingKey the key the block goes out under + * @return the request + */ + private static Map translateRequest(Map material, String block, + PaymentCryptographyKey wrappingKey) { + Map incoming = new LinkedHashMap<>(material); + incoming.put("WrappedKeyBlock", block); + Map request = new LinkedHashMap<>(); + request.put("IncomingKeyMaterial", Map.of("DiffieHellmanTr31KeyBlock", incoming)); + request.put("OutgoingKeyMaterial", Map.of( + "Tr31KeyBlock", Map.of("WrappingKeyIdentifier", wrappingKey.getKeyId()))); + return request; + } + + /** + * The material of the sample's agreement: a key derived with the Concat KDF of NIST + * SP 800-56A. + * + * @param exchange the exchange the two parties made + * @return the material of the agreement + */ + private static Map sampleAgreement(Exchange exchange) { + Map material = new LinkedHashMap<>(exchange.material()); + material.put("DeriveKeyAlgorithm", "AES_256"); + material.put("KeyDerivationFunction", "NIST_SP800"); + material.put("KeyDerivationHashAlgorithm", "SHA_512"); + material.put("DerivationData", Map.of("SharedInformation", SAMPLE_SHARED_INFORMATION)); + return material; + } + + /** + * The key the sample derives from the secret the two parties made. + * + * @param exchange the exchange the two parties made + * @return the derived key + */ + private byte[] sampleDerivedKey(Exchange exchange) throws Exception { + return concatKdf("SHA-512", sharedSecret(exchange), + HexFormat.of().parseHex(SAMPLE_SHARED_INFORMATION), 32); + } + + /** + * The Concat KDF of NIST SP 800-56A, as the standard writes it. + * + *

The key is the digest of the counter, the secret and the shared information, the + * counter over the blocks that are needed, so the derivation here does not use the + * service's own. + */ + private static byte[] concatKdf(String hash, byte[] secret, byte[] otherInfo, int length) + throws Exception { + MessageDigest digest = MessageDigest.getInstance(hash); + byte[] out = new byte[length]; + int at = 0; + for (int counter = 1; at < length; counter++) { + digest.reset(); + // The standard's order: the counter, then the secret, then the shared + // information. + digest.update(new byte[] { + (byte) (counter >>> 24), (byte) (counter >>> 16), (byte) (counter >>> 8), + (byte) counter}); + digest.update(secret); + digest.update(otherInfo); + byte[] block = digest.digest(); + int take = Math.min(block.length, length - at); + System.arraycopy(block, 0, out, at, take); + at += take; + } + return out; + } + + /** + * The check value of a key: the leftmost three bytes of the CMAC of sixteen zero bytes. + * + *

The sample computes it the same way, so the emulator's answer is held to the + * sample's. + */ + private static String cmacKeyCheckValue(String keyHex) { + CMac mac = new CMac(new AESEngine()); + mac.init(new KeyParameter(HexFormat.of().parseHex(keyHex))); + // The CMAC of sixteen zero bytes. + mac.update(new byte[16], 0, 16); + byte[] value = new byte[16]; + mac.doFinal(value, 0); + return HexFormat.of().withUpperCase().formatHex(value).substring(0, 6); + } + + + /** The secret the two parties made, from the service's key and the counterparty's. */ + private byte[] sharedSecret(Exchange exchange) throws Exception { + PaymentCryptographyKey agreement = service.findKey("us-east-1", + (String) exchange.material().get("PrivateKeyIdentifier")); + PrivateKey privateKey = PaymentCryptographyKeyExchange.privateKeyOf(agreement); + X509Certificate certificate = Certificates.parseCertificate( + (String) exchange.material().get("PublicKeyCertificate")); + return Ecdh.agree((ECPrivateKey) privateKey, (ECPublicKey) certificate.getPublicKey()); + } + @Test void aKeyLeavesUnderAKeyTheTwoPartiesAgreedCarriesTheHeadersTheRequestNames() { // The block headers the request names travel with the block under the agreed key, // the same as they do under a key the service holds. - SecureRandom random = new SecureRandom(); - KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random); - KeyPair counterparty = PaymentCryptographyKeyPairs.ec( - PaymentCryptographyKeyAlgorithm.ECC_NIST_P256, random); - Certificates.Minted authorityCertificate = CertificatesTest.mint(authority.getPublic(), - "floci key-exchange CA", authority.getPrivate(), "floci key-exchange CA"); - Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(), - "floci counterparty", authority.getPrivate(), "floci key-exchange CA"); - Exchange exchange = agreedExchange(authorityCertificate, counterpartyCertificate); + Exchange exchange = agreedExchange(); Map material = new LinkedHashMap<>(exchange.material()); material.put("KeyBlockHeaders", Map.of( "KeyExportability", "NON_EXPORTABLE", @@ -287,7 +600,8 @@ class PaymentCryptographyKeyExchangeTest { // Signed by somebody else, so the authority cannot vouch for it. Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(), "floci counterparty", other.getPrivate(), "floci somebody else"); - Exchange exchange = agreedExchange(authorityCertificate, counterpartyCertificate); + Exchange exchange = agreedExchange(authorityCertificate, counterpartyCertificate, + "ECC_NIST_P256"); AwsException refused = assertThrows(AwsException.class, () -> service.exportKey("us-east-1", exchange.key().getKeyId(), @@ -1141,6 +1455,39 @@ class PaymentCryptographyKeyExchangeTest { "KeyModesOfUse", Map.of("Verify", Boolean.TRUE)); } + /** + * A key exchange under a key the two parties agreed with ECDH, on the curve the + * cardholder-device flow uses. + * + * @return the material of the export, and the key that leaves under it + */ + private Exchange agreedExchange() { + return agreedExchange("ECC_NIST_P256"); + } + + /** + * A key exchange under a key the two parties agreed with ECDH, on the given curve. + * + *

The authority vouches for the counterparty's certificate, so the helper mints the + * two certificates and builds the agreement. + * + * @param curve the curve the agreement is made on + * @return the material of the export, and the key that leaves under it + */ + private Exchange agreedExchange(String curve) { + SecureRandom random = new SecureRandom(); + KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random); + KeyPair counterparty = PaymentCryptographyKeyPairs.ec( + PaymentCryptographyKeyAlgorithm.from(curve), random); + Certificates.Minted authorityCertificate = CertificatesTest.mint(authority.getPublic(), + "floci key-exchange CA", authority.getPrivate(), "floci key-exchange CA"); + // The counterparty's certificate is signed by the authority, which is what lets the + // service trust it. + Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(), + "floci counterparty", authority.getPrivate(), "floci key-exchange CA"); + return agreedExchange(authorityCertificate, counterpartyCertificate, curve); + } + /** * A key exchange under a key the two parties agreed with ECDH. * @@ -1151,12 +1498,13 @@ class PaymentCryptographyKeyExchangeTest { * @param authorityCertificate the certificate of the authority that vouches for the * counterparty * @param counterpartyCertificate the certificate the counterparty brings + * @param curve the curve the agreement is made on * @return the material of the export, and the key that leaves under it */ private Exchange agreedExchange(Certificates.Minted authorityCertificate, - Certificates.Minted counterpartyCertificate) { + Certificates.Minted counterpartyCertificate, String curve) { PaymentCryptographyKey authority = createAuthority(authorityCertificate.pem()); - PaymentCryptographyKey agreement = createKeyPair("ECC_NIST_P256", + PaymentCryptographyKey agreement = createKeyPair(curve, "TR31_K3_ASYMMETRIC_KEY_FOR_KEY_AGREEMENT"); Map material = new LinkedHashMap<>(); material.put("PrivateKeyIdentifier", agreement.getKeyId()); diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyPinOperationsTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyPinOperationsTest.java index 9ab5d404ac..dd7a8addcc 100644 --- a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyPinOperationsTest.java +++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyPinOperationsTest.java @@ -202,6 +202,29 @@ class PaymentCryptographyPinOperationsTest { assertEquals(pvk.getArn(), verified.get("VerificationKeyArn")); } + @Test + void aBlockInAFormatTheReferenceDoesNotVerifyIsRefused() { + // The reference names the formats it verifies: "AWS Payment Cryptography supports + // ISO_Format_0 and ISO_Format_3". The format 4 block is an AES block, and the + // verification reads the Triple DES blocks, so a request that names another format + // is refused rather than answered as if the reference read it. + PaymentCryptographyKey pek = pinEncryptionKey(); + PaymentCryptographyKey pvk = visaVerificationKey(); + for (String format : new String[] {"ISO_FORMAT_4", "ISO_FORMAT_1"}) { + AwsException refused = assertThrows(AwsException.class, + () -> pin.verifyPinData(request(Map.of( + "EncryptionKeyIdentifier", pek.getArn(), + "VerificationKeyIdentifier", pvk.getArn(), + "PinBlockFormat", format, + "PrimaryAccountNumber", PAN, + "EncryptedPinBlock", "00000000000000000000000000000000", + "VerificationAttributes", visaPin(1, "1234"))), + "us-east-1")); + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("ISO_FORMAT_0"), refused.getMessage()); + } + } + @Test void aBlockWithTheWrongVerificationValueIsRefused() { PaymentCryptographyKey pek = pinEncryptionKey();