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 93a5e682de..50588f353c 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 @@ -14,12 +14,15 @@ import software.amazon.awssdk.services.paymentcryptography.model.KeyUsage; import software.amazon.awssdk.services.paymentcryptographydata.PaymentCryptographyDataClient; import software.amazon.awssdk.services.paymentcryptographydata.model.EncryptionDecryptionAttributes; import software.amazon.awssdk.services.paymentcryptographydata.model.EncryptionMode; +import software.amazon.awssdk.services.paymentcryptographydata.model.GenerateAs2805KekValidationResponse; 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.RandomKeyMaxLength; +import software.amazon.awssdk.services.paymentcryptographydata.model.RandomKeySendVariantMask; import software.amazon.awssdk.services.paymentcryptographydata.model.ReEncryptionAttributes; import software.amazon.awssdk.services.paymentcryptographydata.model.SymmetricEncryptionAttributes; import software.amazon.awssdk.services.paymentcryptographydata.model.SymmetricKeyAlgorithm; @@ -297,6 +300,49 @@ class PaymentCryptographyDataPlaneTest { assertThat(refusal.statusCode()).isEqualTo(404); } + @Test + @DisplayName("A key encryption key answers a KEK validation of itself") + void aKeyEncryptionKeyAnswersAKeyEncryptionKeyValidationOfItself() { + String kekArn; + try (PaymentCryptographyClient control = TestFixtures.paymentCryptographyClient()) { + kekArn = control.createKey(r -> r + .keyAttributes(a -> a + .keyAlgorithm(KeyAlgorithm.TDES_2_KEY) + .keyClass(KeyClass.SYMMETRIC_KEY) + .keyUsage(KeyUsage.TR31_K0_KEY_ENCRYPTION_KEY) + .keyModesOfUse(m -> m.encrypt(true).decrypt(true))) + .exportable(true)) + .key().keyArn(); + } + // Every key the test made is deleted when the class is done with it. + keyArns.add(kekArn); + + // The node that starts the exchange makes a random number and answers with the two + // numbers the ceremony is made of. + GenerateAs2805KekValidationResponse asked = client.generateAs2805KekValidation(r -> r + .keyIdentifier(kekArn) + .randomKeySendVariantMask(RandomKeySendVariantMask.VARIANT_MASK_82) + .kekValidationType(t -> t.kekValidationRequest(q -> q + .deriveKeyAlgorithm(SymmetricKeyAlgorithm.TDES_2_KEY) + .randomKeyMaxLength(RandomKeyMaxLength.BYTES_16)))); + + assertThat(asked.keyArn()).isEqualTo(kekArn); + assertThat(asked.keyCheckValue()).hasSize(6); + assertThat(asked.randomKeySend()).hasSize(32); + assertThat(asked.randomKeyReceive()).hasSize(32); + + // The node that answers deciphers the number it was given and answers with the + // inverted value, which is the one the first node expects. + GenerateAs2805KekValidationResponse answered = client.generateAs2805KekValidation(r -> r + .keyIdentifier(kekArn) + .randomKeySendVariantMask(RandomKeySendVariantMask.VARIANT_MASK_82) + .kekValidationType(t -> t.kekValidationResponse(q -> q + .randomKeySend(asked.randomKeySend())))); + + assertThat(answered.randomKeySend()).isEqualTo(asked.randomKeySend()); + assertThat(answered.randomKeyReceive()).isEqualTo(asked.randomKeyReceive()); + } + /** Bytes as the data plane carries them: hexadecimal. */ @Test diff --git a/docs/services/index.md b/docs/services/index.md index a0b9fcbef1..3d1d8fa8f5 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 | 13 | +| [Payment Cryptography data plane](payment-cryptography-data.md) | `POST /keys/{KeyIdentifier}/encrypt` and the rest | REST JSON | 14 | | [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 4addbfdd67..da9e68226b 100644 --- a/docs/services/payment-cryptography-data.md +++ b/docs/services/payment-cryptography-data.md @@ -25,6 +25,7 @@ client that talks to the control plane does not reach it by accident. | `VerifyCardValidationData` | Verify a card verification value against the one the issuer holds, on `POST /cardvalidationdata/verify` | | `GenerateAuthRequestCryptogram` | Generate the cryptogram an authorization request carries, on `POST /cryptogram/generate` | | `VerifyAuthRequestCryptogram` | Verify the cryptogram an authorization request carries, on `POST /cryptogram/verify` | +| `GenerateAs2805KekValidation` | Make or answer the AS2805 KEK validation of a key encryption key, on `POST /as2805kekvalidation/generate` | ## Emulation Behavior @@ -145,10 +146,6 @@ client that talks to the control plane does not reach it by accident. 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. @@ -216,6 +213,33 @@ client that talks to the control plane does not reach it by accident. wrong cryptogram is the one outcome worse than an error. The EMV 4.1 tree derivation, the one the `Emv2000` attributes ask for, is refused as well: it is over the master key and the ATC, and this service does not implement that construction. +- **The KEK validation is the AS2805 ceremony two nodes use to prove they hold the same + key.** The node that starts the exchange makes a random number of eight, sixteen or + twenty-four bytes, gives every byte the odd parity the standard's Single DES asks for, + and enciphers it under a variant of the key it holds: the key exclusive-ored with the + mask the request names, repeated over the key's length. The node that answers deciphers + that number, inverts every bit of it, and enciphers the inverted value under the other + variant of its own key. The first node compares the answer with the one it computed, so + two nodes whose keys differ do not agree. The random number is enciphered a block at a + time, in Triple DES, the cipher AS2805's cryptography is made of, and it is sixteen bytes + long when the request does not name a length. +- **The key of a KEK validation is a Triple DES key encryption key.** It is the one AS2805 + calls the terminal major key, the usage `TR31_K0_KEY_ENCRYPTION_KEY`. The reference does + not name the usage the key must have for this operation, so the one the service's own + AS2805 import gives that key is the one it asks for. AS2805's cryptography is all TDES, + so a key of another family is refused. The request form enciphers, so the key must allow + `Encrypt`; the response form deciphers and enciphers the inverted number, so it must + allow `Decrypt` and `Encrypt`. +- **The two variant masks are the standard's two forms of the ceremony.** The `82` form is + the one an independent implementation of the ceremony confirms, byte for byte. The `82C0` + form is the same ceremony under the longer of the two masks the reference names, and the + mask of its inverted number is that form's `84C0`: two nodes validating under it agree + with each other, but not with the reference. +- **The requests the ceremony does not fit are refused.** The derived key is the variant of + the key the request names, so the algorithm the request names has to be the algorithm of + that key, and a request that names another one is refused. The random number is + enciphered in whole Triple DES blocks, and the three lengths the model names are whole + numbers of them. - **The card requests are checked against the model.** The account number is twelve to nineteen digits, the expiry is four of them, the service code is three, and the PAN sequence number is two: the EMV ones, as the model states them. A formatted account diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperations.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperations.java index 78296844b2..0fbe33f690 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperations.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperations.java @@ -101,7 +101,7 @@ public class PaymentCryptographyAuthCryptogramOperations { text(request, "TransactionData"))); SessionKey sk = resolveDerivation(request); - PaymentCryptographyKey key = requiredKey(keyIdentifier, region); + PaymentCryptographyKey key = PaymentCryptographyKeyRules.requiredKey(service, keyIdentifier, region); PaymentCryptographyKeyRules.requireUsage(key, List.of("TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS"), "computing a cryptogram"); PaymentCryptographyKeyRules.requireAlgorithm(key, "TDES_2KEY", "computing a cryptogram"); @@ -169,7 +169,7 @@ public class PaymentCryptographyAuthCryptogramOperations { } } - PaymentCryptographyKey key = requiredKey(keyIdentifier, region); + PaymentCryptographyKey key = PaymentCryptographyKeyRules.requiredKey(service, keyIdentifier, region); PaymentCryptographyKeyRules.requireUsage(key, List.of("TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS"), "computing a cryptogram"); PaymentCryptographyKeyRules.requireAlgorithm(key, "TDES_2KEY", "computing a cryptogram"); @@ -307,15 +307,6 @@ public class PaymentCryptographyAuthCryptogramOperations { // ---- the helpers --------------------------------------------------------- - private PaymentCryptographyKey requiredKey(String identifier, String region) { - PaymentCryptographyKey key = service.findKey(region, identifier); - if (key == null) { - throw new AwsException("ResourceNotFoundException", "Key not found: " + identifier, 404); - } - PaymentCryptographyKeyRules.requireEnabled(key); - return key; - } - private static AwsException validation(String message) { return new AwsException("ValidationException", message, 400); } diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardValidationOperations.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardValidationOperations.java index d5ca9050fa..3c5a97c47d 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardValidationOperations.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardValidationOperations.java @@ -72,7 +72,7 @@ public class PaymentCryptographyCardValidationOperations { : validationDataLength; CardAttrs attrs = resolveCardAttrs(request.get("GenerationAttributes")); - PaymentCryptographyKey key = requiredKey(keyIdentifier, region); + PaymentCryptographyKey key = PaymentCryptographyKeyRules.requiredKey(service, keyIdentifier, region); requireKeyForVariant(key, attrs.variant, "Generate"); Map out = new LinkedHashMap<>(); @@ -95,7 +95,7 @@ public class PaymentCryptographyCardValidationOperations { int length = validationData.length(); CardAttrs attrs = resolveCardAttrs(request.get("VerificationAttributes")); - PaymentCryptographyKey key = requiredKey(keyIdentifier, region); + PaymentCryptographyKey key = PaymentCryptographyKeyRules.requiredKey(service, keyIdentifier, region); requireKeyForVariant(key, attrs.variant, "Verify"); String computed = computeValue(pan, attrs, key, length); @@ -224,15 +224,6 @@ public class PaymentCryptographyCardValidationOperations { } } - private PaymentCryptographyKey requiredKey(String identifier, String region) { - PaymentCryptographyKey key = service.findKey(region, identifier); - if (key == null) { - throw new AwsException("ResourceNotFoundException", "Key not found: " + identifier, 404); - } - PaymentCryptographyKeyRules.requireEnabled(key); - return key; - } - /** * The error a card request is refused with. */ diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKekValidation.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKekValidation.java new file mode 100644 index 0000000000..1983508d5a --- /dev/null +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKekValidation.java @@ -0,0 +1,175 @@ +package io.floci.aws.services.paymentcryptography; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.paymentcryptography.crypto.BlockMode; +import io.floci.aws.services.paymentcryptography.crypto.Ciphers; +import io.floci.aws.services.paymentcryptography.crypto.EmvCrypto; + +/** + * The AS2805 KEK validation: the ceremony two nodes use to prove they hold the same key. + * + *

The node that starts the exchange enciphers a random number under a variant of the key + * it holds and sends it. The node it talks to deciphers that number, inverts every bit of + * it, and enciphers the inverted value under another variant of its own key. The first node + * compares the answer with the one it computed, and the two agree only when both hold the + * same key. + * + *

A variant is the key exclusive-ored with a constant, tiled over the key's length: the + * constant says what the variant is for, so a key made for one purpose does not open under + * the variant of another. The reference names the constant of the random number's variant + * 82 and that of the inverted number's 84, and the longer form of the first 82C0. + * + *

The random number is eight, sixteen or twenty-four bytes, and every byte of it carries + * the odd parity the standard's Single DES asks for. It is enciphered a block at a time + * under the variant, in Triple DES, the cipher AS2805's cryptography is made of. + */ +final class PaymentCryptographyKekValidation { + + /** The block of the cipher the ceremony runs in: the Triple DES block of eight bytes. */ + private static final int BLOCK = 8; + + /** + * The variant masks a request may name, and the mask of the inverted number's variant. + */ + enum Variant { + + /** The random number is enciphered under the 82 variant, the inverted one under 84. */ + VARIANT_MASK_82("82", "84"), + + /** The random number is enciphered under the 82C0 variant, the inverted one under 84C0. */ + VARIANT_MASK_82C0("82C0", "84C0"); + + private final String sendMask; + private final String receiveMask; + + Variant(String sendMask, String receiveMask) { + this.sendMask = sendMask; + this.receiveMask = receiveMask; + } + + /** The mask of the random number's variant. */ + String sendMask() { + return sendMask; + } + + /** The mask of the inverted number's variant. */ + String receiveMask() { + return receiveMask; + } + + /** + * The variant a request names. + * + *

The request's mask is one of the model's two, and the shape check settles it + * before the operation reads it, so a name that is not one of them is a fault of the + * service rather than of the caller. + * + * @param name the name of the mask + * @return the variant + */ + static Variant from(String name) { + for (Variant variant : values()) { + if (variant.name().equals(name)) { + return variant; + } + } + throw new IllegalStateException("the variant mask " + name + " is not one of them"); + } + } + + private PaymentCryptographyKekValidation() { + } + + /** + * The variant of a key: the key exclusive-ored with the mask, tiled over its length. + * + *

The mask is a constant the standard gives for the purpose, and it is repeated over + * the whole key, so a key of any length gets a variant of the same length. + * + * @param key the key the variant is of + * @param mask the mask, as hexadecimal + * @return the variant key + */ + static byte[] variantKey(byte[] key, String mask) { + byte[] constant = PaymentCryptographyCrypto.fromHex(mask); + byte[] out = new byte[key.length]; + for (int i = 0; i < key.length; i++) { + out[i] = (byte) (key[i] ^ constant[i % constant.length]); + } + return out; + } + + /** + * The odd parity every byte of the random number carries. + * + *

The standard's Single DES reads a key whose bytes each hold an odd number of bits, + * so the random number is put to that parity before it is enciphered. The rule is the + * service's own DES parity rule, so there is one of it: a byte whose lowest bit is + * already set and whose count is even is corrected, not left as it is. + * + * @param data the random number + * @return the random number, with the parity put to it + */ + static byte[] oddParity(byte[] data) { + return EmvCrypto.adjustDesParity(data); + } + + /** + * The inversion of every byte: the number the node answers with. + * + * @param data the number to invert + * @return the inverted number + */ + static byte[] invert(byte[] data) { + byte[] out = new byte[data.length]; + for (int i = 0; i < data.length; i++) { + out[i] = (byte) ~data[i]; + } + return out; + } + + /** + * The enciphering of the number under a variant, a block at a time. + * + *

The cipher is Triple DES, the one AS2805's cryptography is made of, and it is the + * cipher's own ECB mode: every block stands alone, so the number is enciphered without + * a vector and without a chain. + * + * @param data the number to encipher + * @param variantKey the variant key + * @return the enciphered number + */ + static byte[] encrypt(byte[] data, byte[] variantKey) { + requireWholeBlocks(data); + return Ciphers.tdesEncrypt(data, variantKey, null, BlockMode.ECB); + } + + /** + * The deciphering of the number under a variant, a block at a time. + * + * @param data the enciphered number + * @param variantKey the variant key + * @return the number + */ + static byte[] decrypt(byte[] data, byte[] variantKey) { + requireWholeBlocks(data); + return Ciphers.tdesDecrypt(data, variantKey, null, BlockMode.ECB); + } + + /** + * The number fills whole Triple DES blocks. + * + *

The block is the Triple DES block of eight bytes, and the lengths the model names + * for the random number are whole numbers of them, so this is a guard on the cipher + * rather than a refusal the model settles. + * + * @param data the number + */ + private static void requireWholeBlocks(byte[] data) { + if (data.length % BLOCK != 0) { + throw new AwsException("ValidationException", + "the number is " + data.length + " bytes; it is a whole number of " + + BLOCK + "-byte blocks", 400); + } + } +} diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKekValidationController.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKekValidationController.java new file mode 100644 index 0000000000..941d82357c --- /dev/null +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKekValidationController.java @@ -0,0 +1,36 @@ +package io.floci.aws.services.paymentcryptography; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.RegionResolver; +import jakarta.inject.Inject; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.Response; + +/** + * The data plane's AS2805 KEK validation. + * + *

The route is the one the AWS SDK builds, and the key the validation is made with is in + * the body, because the reference's operation takes no URI parameter. + */ +@Path(PaymentCryptographyDataPlaneRouteFilter.INTERNAL_PREFIX) +public class PaymentCryptographyKekValidationController extends PaymentCryptographyDataPlaneController { + + private final PaymentCryptographyKekValidationOperations operations; + + @Inject + public PaymentCryptographyKekValidationController(PaymentCryptographyKekValidationOperations operations, + ObjectMapper objectMapper, + RegionResolver regionResolver) { + super(objectMapper, regionResolver); + this.operations = operations; + } + + @POST + @Path("/as2805kekvalidation/generate") + public Response generateAs2805KekValidation(String body, @Context HttpHeaders headers) { + return respond(operations.generate(parse(body), region(headers))); + } +} diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKekValidationOperations.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKekValidationOperations.java new file mode 100644 index 0000000000..5574249235 --- /dev/null +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKekValidationOperations.java @@ -0,0 +1,203 @@ +package io.floci.aws.services.paymentcryptography; + +import com.fasterxml.jackson.databind.JsonNode; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.security.SecureRandom; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static io.floci.aws.services.paymentcryptography.PaymentCryptographyAttributes.soleVariant; +import static io.floci.aws.services.paymentcryptography.PaymentCryptographyAttributes.text; + +/** + * The AS2805 KEK validation: the ceremony two nodes use to prove they hold the same key. + * + *

The operation has two forms. The request form is the node that starts the exchange: it + * makes a random number, enciphers it under a variant of the key it holds, and answers with + * that enciphered number and the answer it expects the other node to send back. The response + * form is the node that answers: it deciphers the number it was given, inverts it and + * enciphers the inverted value, which is the answer the first node compares. + * + *

The key is a Triple DES key encryption key, the one AS2805 calls the terminal major + * key. The reference does not name the usage the key must have for this operation, so the + * one the service's own AS2805 import gives that key is the one it asks for, and AS2805's + * cryptography is all TDES, so a key of another family is refused. + */ +@ApplicationScoped +public class PaymentCryptographyKekValidationOperations { + + /** The usages a key may have to be the key of a KEK validation. */ + private static final List KEK_USAGES = List.of("TR31_K0_KEY_ENCRYPTION_KEY"); + + /** The length of the random number when the request does not name one. */ + private static final int DEFAULT_RANDOM_LENGTH = 16; + + /** The lengths the request may name, in bytes. */ + private static final Map RANDOM_LENGTHS = Map.of( + "BYTES_8", 8, + "BYTES_16", 16, + "BYTES_24", 24); + + /** The hexadecimal the data plane carries its blobs in. */ + private static final HexFormat HEX = HexFormat.of().withUpperCase(); + + private final SecureRandom random; + + private final PaymentCryptographyService service; + + @Inject + public PaymentCryptographyKekValidationOperations(PaymentCryptographyService service) { + this(service, new SecureRandom()); + } + + PaymentCryptographyKekValidationOperations(PaymentCryptographyService service, SecureRandom random) { + this.service = service; + this.random = random; + } + + /** + * The KEK validation of a key encryption key. + */ + Map generate(JsonNode request, String region) { + // The request is checked against the constraints the model states for it. + PaymentCryptographyDataRequestShapes.check("GenerateAs2805KekValidation", request); + PaymentCryptographyKekValidation.Variant variant = + variant(text(request, "RandomKeySendVariantMask")); + JsonNode type = request.get("KekValidationType"); + String form = soleVariant(type); + if (form == null) { + throw validation("KekValidationType must specify exactly one variant"); + } + if (!"KekValidationRequest".equals(form) && !"KekValidationResponse".equals(form)) { + throw validation("KekValidationType." + form + " not supported by this service " + + "(KekValidationRequest, KekValidationResponse)"); + } + + PaymentCryptographyKey key = requiredKey(text(request, "KeyIdentifier"), region); + PaymentCryptographyKeyAlgorithm algorithm = algorithmOf(key); + byte[] material = PaymentCryptographyKeyRules.material(key); + byte[] variantRn = PaymentCryptographyKekValidation.variantKey( + material, variant.sendMask()); + byte[] variantNotRn = PaymentCryptographyKekValidation.variantKey( + material, variant.receiveMask()); + + Map out = new LinkedHashMap<>(); + out.put("KeyArn", key.getArn()); + out.put("KeyCheckValue", PaymentCryptographyCrypto.checkValue(material, algorithm)); + + byte[] send; + byte[] receive; + if ("KekValidationRequest".equals(form)) { + // The node that starts the exchange enciphers under the key. + PaymentCryptographyKeyRules.requireMode(key, "Encrypt", + "enciphering a random number for a KEK validation"); + JsonNode attributes = type.get("KekValidationRequest"); + requireAlgorithm(key, algorithm, text(attributes, "DeriveKeyAlgorithm")); + byte[] rn = PaymentCryptographyKekValidation.oddParity( + randomBytes(randomLength(text(attributes, "RandomKeyMaxLength")))); + send = PaymentCryptographyKekValidation.encrypt(rn, variantRn); + receive = PaymentCryptographyKekValidation.encrypt( + PaymentCryptographyKekValidation.invert(rn), variantNotRn); + } else { + // The node that answers deciphers the number and enciphers the inverted one. + PaymentCryptographyKeyRules.requireMode(key, "Decrypt", + "deciphering a random number for a KEK validation"); + PaymentCryptographyKeyRules.requireMode(key, "Encrypt", + "enciphering the inverted number for a KEK validation"); + send = HEX.parseHex(text(type.get("KekValidationResponse"), "RandomKeySend")); + byte[] rn = PaymentCryptographyKekValidation.decrypt(send, variantRn); + receive = PaymentCryptographyKekValidation.encrypt( + PaymentCryptographyKekValidation.invert(rn), variantNotRn); + } + out.put("RandomKeySend", HEX.formatHex(send)); + out.put("RandomKeyReceive", HEX.formatHex(receive)); + return out; + } + + // ---- the parts ----------------------------------------------------------- + + /** + * The variant mask the request names. + * + *

The mask is one of the model's two, and the shape check settles it before the + * operation reads it, so a name that is not one of them is a fault of the service rather + * than of the caller. + */ + private static PaymentCryptographyKekValidation.Variant variant(String name) { + return PaymentCryptographyKekValidation.Variant.from(name); + } + + /** + * The length of the random number the request names. + * + *

The length is one of the model's three, and the shape check settles it before the + * operation reads it. A request that names none gets the length the reference's own + * example answers with. + */ + private static int randomLength(String name) { + if (name.isEmpty()) { + return DEFAULT_RANDOM_LENGTH; + } + Integer length = RANDOM_LENGTHS.get(name); + if (length == null) { + throw new IllegalStateException("the random key length " + name + " is not one of them"); + } + return length; + } + + /** + * The algorithm of the key, which is the algorithm the variant is used with. + * + *

AS2805's cryptography is all TDES: the ceremony runs over Single DES blocks and + * the key variants are DES key variants, so a key of another family is refused. + */ + private static PaymentCryptographyKeyAlgorithm algorithmOf(PaymentCryptographyKey key) { + return PaymentCryptographyKeyRules.requireTdes(key.getKeyAlgorithm(), + "key " + key.getArn()); + } + + /** + * The algorithm the request says the derived key is of, which is the key's own. + * + *

The derived key is the variant of the key the request names, so it is of the same + * algorithm and the same length. A request that names another one is a request for a + * key the service does not hold. + */ + private static void requireAlgorithm(PaymentCryptographyKey key, + PaymentCryptographyKeyAlgorithm algorithm, + String declared) { + if (declared.isEmpty()) { + return; + } + if (!declared.equals(algorithm.name())) { + throw validation("DeriveKeyAlgorithm '" + declared + "' is not the algorithm of the " + + "key " + key.getArn() + ", which is " + algorithm.name()); + } + } + + /** + * The random number, of the length the request names. + */ + private byte[] randomBytes(int length) { + byte[] out = new byte[length]; + random.nextBytes(out); + return out; + } + + private PaymentCryptographyKey requiredKey(String identifier, String region) { + PaymentCryptographyKey key = + PaymentCryptographyKeyRules.requiredKey(service, identifier, region); + PaymentCryptographyKeyRules.requireUsage(key, KEK_USAGES, "validating a key encryption key"); + return key; + } + + private static AwsException validation(String message) { + return new AwsException("ValidationException", message, 400); + } +} 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 e63afbfcac..481e552621 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchange.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchange.java @@ -941,24 +941,6 @@ final class PaymentCryptographyKeyExchange { return value instanceof Map map ? (Map) map : Map.of(); } - /** - * Refuses a key that is not TDES, and returns its algorithm: AS2805 - * cryptography is all TDES. - * - * @param algorithmName the key's algorithm - * @param role what the key is, for the refusal - * @return the algorithm - */ - private static PaymentCryptographyKeyAlgorithm requireTdes(String algorithmName, String role) { - PaymentCryptographyKeyAlgorithm algorithm = - PaymentCryptographyKeyAlgorithm.from(algorithmName); - if (algorithm == null || !algorithm.isTdes()) { - throw validation("an AS2805 key is a TDES key, but the " + role + " is " - + algorithmName); - } - return algorithm; - } - /** * The parameter a token names, when it is one this service issued for that kind of * material and it has not expired. @@ -1447,11 +1429,11 @@ final class PaymentCryptographyKeyExchange { + "which it needs to wrap a key cryptogram"); } requireKeyEncryptionKey(kek); - requireTdes(kek.getKeyAlgorithm(), "AS2805 wrapping key " + kek.getArn()); + PaymentCryptographyKeyRules.requireTdes(kek.getKeyAlgorithm(), "AS2805 wrapping key " + kek.getArn()); // AS2805's cryptography is all TDES, so only TDES keys leave and come back in // an AS2805 cryptogram. PaymentCryptographyKeyAlgorithm algorithm = - requireTdes(key.getKeyAlgorithm(), "key " + key.getArn()); + PaymentCryptographyKeyRules.requireTdes(key.getKeyAlgorithm(), "key " + key.getArn()); String tooWeak = PaymentCryptographyKeyStrength.refusal(kek.getKeyAlgorithm(), key.getKeyAlgorithm()); if (tooWeak != null) { @@ -1581,7 +1563,7 @@ final class PaymentCryptographyKeyExchange { String wrappingKeyIdentifier = text(material, "WrappingKeyIdentifier"); PaymentCryptographyKey kek = usableKey(wrappingKeyIdentifier, region); requireKeyEncryptionKey(kek); - requireTdes(kek.getKeyAlgorithm(), "AS2805 wrapping key " + kek.getArn()); + PaymentCryptographyKeyRules.requireTdes(kek.getKeyAlgorithm(), "AS2805 wrapping key " + kek.getArn()); // The wrapping key opens an incoming cryptogram, so it has to be allowed to unwrap. // The model names no error code of its own for this, so it is a validation error, // as the rest of the refusals about a key's modes of use are. @@ -1593,7 +1575,8 @@ final class PaymentCryptographyKeyExchange { String algorithmName = text(material, "KeyAlgorithm"); // AS2805's cryptography is all TDES, so only TDES keys leave and come back in // an AS2805 cryptogram. - PaymentCryptographyKeyAlgorithm algorithm = requireTdes(algorithmName, "carried key"); + PaymentCryptographyKeyAlgorithm algorithm = + PaymentCryptographyKeyRules.requireTdes(algorithmName, "carried key"); // The wrapping key has to be at least as strong as the key it protects, the same // rule the export enforces, so a cryptogram that the export would refuse to write // does not open here either. diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyRules.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyRules.java index 64c7791d1e..f77332ef32 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyRules.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyRules.java @@ -126,6 +126,50 @@ final class PaymentCryptographyKeyRules { } } + /** + * The key a request names, and the rules it has to satisfy before it does any work. + * + *

The key is the one the request names in the region the request is for, and it has + * to be there and enabled: a key the service does not hold is the not-found error, and + * a key that is disabled does no work. + * + * @param service the service the key is held by + * @param identifier the key the request names + * @param region the region the request is for + * @return the key + */ + static PaymentCryptographyKey requiredKey(PaymentCryptographyService service, String identifier, + String region) { + PaymentCryptographyKey key = service.findKey(region, identifier); + if (key == null) { + throw new AwsException("ResourceNotFoundException", "Key not found: " + identifier, 404); + } + requireEnabled(key); + return key; + } + + /** + * The Triple DES algorithm an AS2805 key has to have. + * + *

AS2805's cryptography is all TDES: the ceremony runs over Single DES blocks, the + * key variants are DES key variants, and the random numbers the standard names are + * whole DES blocks. A key of another family is refused rather than read as bytes it is + * not. + * + * @param algorithmName the algorithm of the key + * @param role what the key is, for the message + * @return the algorithm + */ + static PaymentCryptographyKeyAlgorithm requireTdes(String algorithmName, String role) { + PaymentCryptographyKeyAlgorithm algorithm = + PaymentCryptographyKeyAlgorithm.from(algorithmName); + if (algorithm == null || !algorithm.isTdes()) { + throw new AwsException("ValidationException", + "an AS2805 key is a TDES key, but the " + role + " is " + algorithmName, 400); + } + return algorithm; + } + /** * The mode of use a key has to have to derive from it. * 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 e91245bd65..54767dee90 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyPinOperations.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyPinOperations.java @@ -17,10 +17,10 @@ import java.util.Map; import static io.floci.aws.services.paymentcryptography.PaymentCryptographyAttributes.soleVariant; import static io.floci.aws.services.paymentcryptography.PaymentCryptographyAttributes.text; import static io.floci.aws.services.paymentcryptography.PaymentCryptographyKeyRules.materialHex; -import static io.floci.aws.services.paymentcryptography.PaymentCryptographyKeyRules.requireEnabled; import static io.floci.aws.services.paymentcryptography.PaymentCryptographyKeyRules.requireFamily; import static io.floci.aws.services.paymentcryptography.PaymentCryptographyKeyRules.requireMode; import static io.floci.aws.services.paymentcryptography.PaymentCryptographyKeyRules.requireUsage; +import static io.floci.aws.services.paymentcryptography.PaymentCryptographyKeyRules.requiredKey; /** * The PIN operations, over the Visa PVV path. @@ -131,7 +131,7 @@ public class PaymentCryptographyPinOperations { requireNoDukptForAes(format, request.get("DukptAttributes")); requireKeyMatchesFormat(pek, format, "EncryptionKeyIdentifier"); - PaymentCryptographyKey pvk = requiredKey(verificationKeyIdentifier, region); + PaymentCryptographyKey pvk = requiredKey(service, verificationKeyIdentifier, region); requireMode(pvk, "Verify", "verifying a PIN"); requireUsage(pvk, VISA_VERIFICATION_USAGES, "verifying a PIN"); // The Visa PVV is defined over Triple DES, so the key is one. @@ -202,7 +202,7 @@ public class PaymentCryptographyPinOperations { PinLeg pek = resolvePinLeg(encryptionKeyIdentifier, null, region, "Encrypt", "encrypting a PIN block"); - PaymentCryptographyKey pvk = requiredKey(generationKeyIdentifier, region); + PaymentCryptographyKey pvk = requiredKey(service, generationKeyIdentifier, region); requireMode(pvk, "Generate", "generating a PIN verification value"); requireUsage(pvk, VISA_VERIFICATION_USAGES, "generating a PIN verification value"); // The Visa PVV is defined over Triple DES, so the key is one. @@ -376,11 +376,7 @@ public class PaymentCryptographyPinOperations { */ private PinLeg resolvePinLeg(String identifier, JsonNode dukptAttributes, String region, String mode, String what) { - PaymentCryptographyKey key = service.findKey(region, identifier); - if (key == null) { - throw notFound(identifier); - } - requireEnabled(key); + PaymentCryptographyKey key = requiredKey(service, identifier, region); if (dukptAttributes == null) { requireMode(key, mode, what); requireUsage(key, PIN_ENCRYPTION_USAGES, what); @@ -452,15 +448,6 @@ public class PaymentCryptographyPinOperations { // ---- the helpers --------------------------------------------------------- - private PaymentCryptographyKey requiredKey(String identifier, String region) { - PaymentCryptographyKey key = service.findKey(region, identifier); - if (key == null) { - throw notFound(identifier); - } - requireEnabled(key); - return key; - } - private static PaymentCryptographyKeyAlgorithm algorithmOf(PaymentCryptographyKey key) { PaymentCryptographyKeyAlgorithm algorithm = PaymentCryptographyKeyAlgorithm.from(key.getKeyAlgorithm()); @@ -615,10 +602,6 @@ public class PaymentCryptographyPinOperations { return new AwsException("ValidationException", message, 400); } - private static AwsException notFound(String identifier) { - return new AwsException("ResourceNotFoundException", "Key not found: " + identifier, 404); - } - /** * The PIN did not verify. * diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKekValidationTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKekValidationTest.java new file mode 100644 index 0000000000..5daab57eed --- /dev/null +++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKekValidationTest.java @@ -0,0 +1,299 @@ +package io.floci.aws.services.paymentcryptography; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.InMemoryStorage; +import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey; +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.util.Map; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The AS2805 KEK validation. + * + *

The values in the first tests are an independent implementation's: a reference that + * implements the standard's ceremony answers the same numbers for the same key, and the + * emulator is held to them. They are the keys and the numbers of that reference, so a change + * to the construction is a change to the bytes the standard's two nodes agree on. + */ +class PaymentCryptographyKekValidationTest { + + /** The key the reference used, and the variant of it the random number is enciphered under. */ + private static final String KEK = "000102030405060708090A0B0C0D0E0F"; + private static final String VARIANT_RN = "82838081868784858A8B88898E8F8C8D"; + private static final String VARIANT_NOT_RN = "84858687808182838C8D8E8F88898A8B"; + + /** The random number of one block, and the two numbers the ceremony makes of it. */ + private static final String RN = "468AD0B5CE10FBB6"; + private static final String SEND = "53E0A068482E18E7"; + private static final String RECEIVE = "3A343F9B1845D305"; + + /** The random number of two blocks, and the two numbers the ceremony makes of it. */ + private static final String LONG_RN = "468AD0B5CE10FBB60123456789ABCDEF"; + private static final String LONG_SEND = "53E0A068482E18E75FF1C1A1C1A1EF65"; + private static final String LONG_RECEIVE = "3A343F9B1845D3050CC638EBBA236EC2"; + + private PaymentCryptographyService service; + private PaymentCryptographyKekValidationOperations validation; + + @BeforeEach + void setUp() { + service = new PaymentCryptographyService( + new InMemoryStorage<>(), + new InMemoryStorage<>(), + new RegionResolver("us-east-1", "000000000000")); + validation = new PaymentCryptographyKekValidationOperations(service); + } + + // ---- the construction ---------------------------------------------------- + + @Test + void theVariantKeyIsTheKeyExclusiveOrWithTheMask() { + byte[] key = PaymentCryptographyCrypto.fromHex(KEK); + + assertArrayEquals(PaymentCryptographyCrypto.fromHex(VARIANT_RN), + PaymentCryptographyKekValidation.variantKey(key, "82")); + assertArrayEquals(PaymentCryptographyCrypto.fromHex(VARIANT_NOT_RN), + PaymentCryptographyKekValidation.variantKey(key, "84")); + } + + @Test + void theRandomNumberIsEncipheredUnderTheVariant() { + byte[] variant = PaymentCryptographyKekValidation.variantKey( + PaymentCryptographyCrypto.fromHex(KEK), "82"); + + assertArrayEquals(PaymentCryptographyCrypto.fromHex(SEND), + PaymentCryptographyKekValidation.encrypt( + PaymentCryptographyCrypto.fromHex(RN), variant)); + } + + @Test + void theInvertedNumberIsEncipheredUnderTheOtherVariant() { + byte[] variant = PaymentCryptographyKekValidation.variantKey( + PaymentCryptographyCrypto.fromHex(KEK), "84"); + + assertArrayEquals(PaymentCryptographyCrypto.fromHex(RECEIVE), + PaymentCryptographyKekValidation.encrypt( + PaymentCryptographyKekValidation.invert( + PaymentCryptographyCrypto.fromHex(RN)), + variant)); + } + + @Test + void aLongerNumberIsEncipheredABlockAtATime() { + byte[] variant = PaymentCryptographyKekValidation.variantKey( + PaymentCryptographyCrypto.fromHex(KEK), "82"); + byte[] other = PaymentCryptographyKekValidation.variantKey( + PaymentCryptographyCrypto.fromHex(KEK), "84"); + + assertArrayEquals(PaymentCryptographyCrypto.fromHex(LONG_SEND), + PaymentCryptographyKekValidation.encrypt( + PaymentCryptographyCrypto.fromHex(LONG_RN), variant)); + assertArrayEquals(PaymentCryptographyCrypto.fromHex(LONG_RECEIVE), + PaymentCryptographyKekValidation.encrypt( + PaymentCryptographyKekValidation.invert( + PaymentCryptographyCrypto.fromHex(LONG_RN)), + other)); + } + + @Test + void theRandomNumberCarriesTheOddParity() { + assertArrayEquals(new byte[] {0x01}, + PaymentCryptographyKekValidation.oddParity(new byte[] {0x00})); + assertArrayEquals(new byte[] {0x7F}, + PaymentCryptographyKekValidation.oddParity(new byte[] {0x7E})); + assertArrayEquals(new byte[] {0x7F}, + PaymentCryptographyKekValidation.oddParity(new byte[] {0x7F})); + // A byte whose lowest bit is already set and whose count is even is the one the + // rule has to correct: setting the bit alone would leave the byte even. + assertArrayEquals(new byte[] {0x02}, + PaymentCryptographyKekValidation.oddParity(new byte[] {0x03})); + } + + // ---- the operation ------------------------------------------------------- + + @ParameterizedTest + @ValueSource(strings = {"VARIANT_MASK_82", "VARIANT_MASK_82C0"}) + void theAnswerOfTheRequestFormIsTheAnswerOfTheResponseForm(String mask) { + PaymentCryptographyKey kek = kek(); + + Map asked = validation.generate(request(kek.getArn(), null, + "BYTES_16", mask, "TDES_2KEY"), "us-east-1"); + String send = (String) asked.get("RandomKeySend"); + String receive = (String) asked.get("RandomKeyReceive"); + + assertEquals(kek.getArn(), asked.get("KeyArn")); + assertTrue(send.matches("[0-9A-F]{32}"), send); + assertTrue(receive.matches("[0-9A-F]{32}"), receive); + + Map answered = validation.generate(request(kek.getArn(), send, null, mask, + "TDES_2KEY"), "us-east-1"); + + assertEquals(send, answered.get("RandomKeySend")); + assertEquals(receive, answered.get("RandomKeyReceive")); + } + + @Test + void theTwoNodesThatHoldDifferentKeysDoNotAgree() { + PaymentCryptographyKey one = kek(); + PaymentCryptographyKey other = kek(); + + Map asked = validation.generate(request(one.getArn(), null, "BYTES_16"), + "us-east-1"); + Map answered = validation.generate(request(other.getArn(), + (String) asked.get("RandomKeySend"), null), "us-east-1"); + + assertNotEquals(asked.get("RandomKeyReceive"), answered.get("RandomKeyReceive")); + } + + @Test + void aKeyOfTheWrongUsageIsRefused() { + PaymentCryptographyKey wrong = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", + "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", "Encrypt", "Decrypt"); + AwsException refused = assertThrows(AwsException.class, () -> validation.generate( + request(wrong.getArn(), null, "BYTES_16"), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + } + + @Test + void aKeyThatMayNotEncryptIsRefused() { + PaymentCryptographyKey wrong = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", + "TR31_K0_KEY_ENCRYPTION_KEY", "Decrypt"); + + AwsException refused = assertThrows(AwsException.class, () -> validation.generate( + request(wrong.getArn(), null, "BYTES_16"), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + } + + @Test + void aKeyThatMayNotEncryptIsRefusedInTheResponseForm() { + // The node that answers enciphers the inverted number, so a key that may only + // decipher is refused there as well. + PaymentCryptographyKey wrong = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", + "TR31_K0_KEY_ENCRYPTION_KEY", "Decrypt"); + + AwsException refused = assertThrows(AwsException.class, () -> validation.generate( + request(wrong.getArn(), RN, null, "VARIANT_MASK_82", "TDES_2KEY"), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + } + + @Test + void aKeyThatIsNotTdesIsRefused() { + // AS2805's cryptography is all TDES, so a key of another family is refused before + // any random material is made. + PaymentCryptographyKey wrong = PaymentCryptographyTestFixtures.createKey(service, "AES_128", + "TR31_K0_KEY_ENCRYPTION_KEY", "Encrypt", "Decrypt"); + + AwsException refused = assertThrows(AwsException.class, () -> validation.generate( + request(wrong.getArn(), null, "BYTES_16", "VARIANT_MASK_82", "AES_128"), + "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + } + + @Test + void aKeyThatIsNotThereIsRefused() { + AwsException refused = assertThrows(AwsException.class, () -> validation.generate( + request("arn:aws:payment-cryptography:us-east-1:000000000000:key/" + + "abcdefghij012345", null, "BYTES_16"), "us-east-1")); + + assertEquals("ResourceNotFoundException", refused.getErrorCode()); + } + + @Test + void aRequestThatNamesNoVariantIsRefused() { + PaymentCryptographyKey kek = kek(); + + AwsException refused = assertThrows(AwsException.class, () -> validation.generate( + requestWithoutAVariant(kek.getArn()), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + } + + @Test + void aMaskTheModelDoesNotNameIsRefused() { + PaymentCryptographyKey kek = kek(); + + AwsException refused = assertThrows(AwsException.class, () -> validation.generate( + request(kek.getArn(), null, "BYTES_16", "VARIANT_MASK_42", "TDES_2KEY"), + "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + } + + @Test + void aDerivedAlgorithmThatIsNotTheKeysIsRefused() { + PaymentCryptographyKey kek = kek(); + + AwsException refused = assertThrows(AwsException.class, () -> validation.generate( + request(kek.getArn(), null, "BYTES_16", "VARIANT_MASK_82", "AES_256"), + "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + } + + /** A key of the usage and the modes a KEK validation needs. */ + private PaymentCryptographyKey kek() { + return PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", + "TR31_K0_KEY_ENCRYPTION_KEY", "Encrypt", "Decrypt"); + } + + /** + * A request of the operation: the request form, or the response form when a random + * number is given. + */ + private static JsonNode request(String keyIdentifier, String incoming, String length) { + return request(keyIdentifier, incoming, length, "VARIANT_MASK_82", "TDES_2KEY"); + } + + /** + * A request of the operation under the mask and the algorithm the request names. + */ + private static JsonNode request(String keyIdentifier, String incoming, String length, + String mask, String algorithm) { + ObjectMapper mapper = new ObjectMapper(); + ObjectNode body = mapper.createObjectNode(); + body.put("KeyIdentifier", keyIdentifier); + body.put("RandomKeySendVariantMask", mask); + ObjectNode type = mapper.createObjectNode(); + if (incoming == null) { + ObjectNode attributes = mapper.createObjectNode(); + attributes.put("DeriveKeyAlgorithm", algorithm); + attributes.put("RandomKeyMaxLength", length); + type.set("KekValidationRequest", attributes); + } else { + ObjectNode attributes = mapper.createObjectNode(); + attributes.put("RandomKeySend", incoming); + type.set("KekValidationResponse", attributes); + } + body.set("KekValidationType", type); + return body; + } + + /** + * A request whose validation type names no variant at all. + */ + private static JsonNode requestWithoutAVariant(String keyIdentifier) { + ObjectMapper mapper = new ObjectMapper(); + ObjectNode body = mapper.createObjectNode(); + body.put("KeyIdentifier", keyIdentifier); + body.put("RandomKeySendVariantMask", "VARIANT_MASK_82"); + body.set("KekValidationType", mapper.createObjectNode()); + return body; + } +} diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml index 9b10172257..c6a70fa652 100644 --- a/tools/docs/services.yaml +++ b/tools/docs/services.yaml @@ -43,6 +43,7 @@ services: - { path: services/paymentcryptography/PaymentCryptographyCryptoController.java, mode: rest } - { path: services/paymentcryptography/PaymentCryptographyPinController.java, mode: rest } - { path: services/paymentcryptography/PaymentCryptographyCardController.java, mode: rest } + - { path: services/paymentcryptography/PaymentCryptographyKekValidationController.java, mode: rest } exclude_actions: - GenerateMacEmvPinChange - service: applicationautoscaling