From ab312d68e65a1e05ec9ca1f40e70e1671567cc60 Mon Sep 17 00:00:00 2001 From: Murtuza Chhil Date: Mon, 9 Nov 2026 20:48:07 +0530 Subject: [PATCH] feat(paymentcryptography): the card values and the authorization cryptograms (#7400) * feat(paymentcryptography): the single DES decryption The retail MAC closes its tag with a decryption under the right half of the key, so the cipher package needs the Single DES decryption as well as the encryption. It is the same cipher the encryption is, the other way round, and it is BouncyCastle's like every other cipher here. * feat(paymentcryptography): the card values and the authorization cryptograms The card validation value is the three digit value of the X9 algorithm: the account number, the expiry and the service code, enciphered under the card verification key, and decimalized. The dynamic variants compute the value from the transaction rather than from the card's own fields, and they take a key of their own usage that may derive. The authorization cryptogram is the ARQC of the transaction: the ISO 9797-1 algorithm 3 retail MAC over the transaction data, cut to eight bytes, under a session key the request's derivation produces. The EMV common session key, the EMV 2000 one, the Mastercard one and the Visa one are served. The American Express derivation is refused rather than approximated: the AEIPS session key derivation is proprietary and there is nothing to verify it against, and a plausible wrong cryptogram is worse than an error. The operations are written on the data plane as it is now: the hexadecimal is java.util.HexFormat, the digests are the shared Digests, and the ciphers are the BouncyCastle ones the package already uses. The routes of the card operations are in the vendored rest-routes.json already, so they are authorized by the generated rules and need no hand-written ones. * test(paymentcryptography): the card operations over the SDK and the CLI The unit tests call the operations directly, so they do not reach the routes the requests travel, the JSON the body carries, or the rules that decide which action a request is. The suite does, through a client that signs the request the way a client of the data plane signs it. The Java suite drives the card verification value and the authorization cryptogram with the AWS SDK for Java v2, and the CLI suite drives them with the AWS CLI. Both refuse the American Express derivation, the key of another usage, and the value or the cryptogram that does not verify. * fix(paymentcryptography): the card requests are checked against the model The card operations' constraints were not vendored, so their requests were checked by hand and only partly: the account number was read as the digits it carried, the expiry and the service code were not checked at all for the first card verification value, and the key an operation acted on was not checked to be a key. The constraints are in the model, so they are vendored now, the four operations are checked against them before they look at the request, and the checks that repeat them are gone. The model states that the PAN sequence number is two digits and that the application transaction counter is two bytes. The derivation reads the last eight bytes of the packed PAN || PSN and the first two bytes of the counter, so the longer values the hand-rolled checks allowed were read as something other than the counter they stood for. The vectors are the ones the EMV derivation gives for the model's inputs. * docs(paymentcryptography): the card requests are checked against the model The account number is 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 number and a longer sequence number are refused rather than read as the digits they carry. * docs(paymentcryptography): the data plane's operation count The Service Matrix counts the operations a service documents, and the data plane documents four more now: the card verification value and the authorization cryptogram. * fix(paymentcryptography): the card operations raise the errors the model names Three findings from the review, all in the card operations. A key that may not be used for the operation was refused with InvalidKeyUsageException, which the data plane's model does not name, so a client cannot catch it as its own type. The data plane names three errors, and a refusal that is not one of them is a ValidationException. The ARPC method 2 read an ArpcInputFormat member that no model, and no SDK, carries, so the branch it guarded could never be taken. The member is gone and the response value is always made the way the reference makes it. And a hexadecimal member of an odd length is a request the model allows and the cipher cannot read, so it was answered with an internal failure the caller cannot catch. It is refused with the error the model names, and the refusal names the member. * test(paymentcryptography): the card operations' members are covered Seven members the card operations read were read by no test, so nothing proved they work: the response attributes and the response code, the card status update and the proprietary data, the track data, the unpredictable number and the validation data length. Each is sent now, and the shape the service receives with them is exercised. The response value is made by both ARPC methods, and a request that asks for none is answered without one. * test(paymentcryptography): the padding type is refused The padding type belongs to RSA, and the symmetric cipher does not pad, so a request that names one is refused rather than answered with a cipher that ignored it. Nothing sent one, so the refusal was never exercised. * fix(paymentcryptography): 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. A request that carries one is refused, as the PIN operations already refused it, rather than answered as if the key were a fixed one. The rule now lives in one place, so the two paths cannot disagree on it. * fix(paymentcryptography): the master key is derived over the rightmost sixteen digits The block the ICC master key is derived over is the rightmost sixteen digits of the account number and the PAN sequence number, padded on the left with zeros when they are shorter. That is the rule EMV 4.4 Book 2 Annex A1.4.1 gives for Option A, and the Visa Integrated Circuit Card Specification states it the same way. An account number of twelve digits is therefore read and derived from, where the derivation used to refuse it, and the refusal in the request layer goes with it. A derivation the request cannot be read for is refused with the error the model names, rather than answered with a failure the caller cannot catch. * test(paymentcryptography): the derivations are the ones the specifications give The vectors are the ones the specifications publish: the ICC master key from the EMV Option A derivation, the MasterCard proprietary session key and the application cryptogram it produces over the same data from the M/Chip worked example, and the common session key from the same document. The common session key is compared with the parity bits masked, because the document does not force the parity of the derived key and the derivation does not affect the computation. * fix(paymentcryptography): the dynamic value is the one Visa describes The Visa Contactless Payment Specification gives the dynamic card verification value in full: the leftmost four digits of the account number are replaced by the transaction counter, and the result, the expiry and the service code are enciphered under the card's unique derived key, which the issuer derives from the master key with the account number and the PAN sequence number. The three leftmost decimal digits of the result are the value. The derivation used a session key and covered the account number as it stands, so it was the emulator's own construction and not the value Visa describes. The key it needs is the one the unique derived key derivation already makes, and the request carries the PAN sequence number that derivation takes. The counter is a binary coded decimal counter, so a counter that is not one is refused rather than read. * docs(paymentcryptography): the dynamic code is the emulator's one * fix(paymentcryptography): the card value carries the length asked for The model states the length of a card validation value as three to five, and the service refused every length but three. The value now carries the number of digits the request asks for, and the verification compares as many. The dynamic value's counter is a binary coded decimal counter, so the digits that replace the leftmost ones of the account number are zero padded on the left to the four the field holds. * fix(paymentcryptography): the card values and cryptograms as specified The review of the branch found that the card values and the authorization cryptograms did not follow the rules they are made by. The Option B master key derivation turned the hexadecimal digits of the hash into digits as it scanned them. The specification takes the decimal digits of the hash first and only then the nibbles that are not decimal digits, each reduced modulo ten, so the derivation now follows it. The transaction data reaches the service already padded, because the caller pads it the way the card padded it before the card enciphered it. The service was padding it a second time, which enciphered a block the card never enciphered. The data is enciphered as it was sent now, and a length that is not a whole number of eight-byte blocks is refused, because the ISO 9797-1 MAC runs over whole blocks. The key table names the application cryptogram usage, the TDES_2KEY algorithm and the DeriveKey mode of use for the ARQC key, so a key of another usage, another algorithm or without the mode of use is refused. The rules are asked in one place now, so the card operations and the cryptogram operations cannot drift apart on what they accept. The response value of the second issuer authentication method is made of the card status update and the proprietary data, as the specification has it. The response code belongs to the first method. The EMV 4.1 tree derivation and the dynamic card verification code are refused rather than approximated: the first is proprietary, and the second was the emulator's own construction. A verification that fails carries the reason the model names, and a key that is not there is answered with a 404. * refactor(paymentcryptography): the model settles the card value's length The card operations refused a validation data length that was not three to five digits, and a validation data that was not, while the model states both. The model is checked before the operation runs, so the two checks never reached the point where they could answer, and the model answers the same request with the same error. The checks are gone, and the model's own constraints have a test each, so the refusal is proved. The class comment of EmvCrypto said the ARQC is made over the CDOL, and it is made over the transaction data as the caller sent it, so the comment says that now. * refactor(paymentcryptography): the card side reads the shared helpers The review found the card side holding copies of what the service already holds, and the comments around them out of date. The card operations read the request members through PaymentCryptographyAttributes now, the same as the cryptogram operations, instead of carrying their own text and soleVariant. They read the key's material through PaymentCryptographyKeyRules.materialHex as well. A key read back after a restart holds no material, and the shared rule says so, where the raw accessor gave a null that the derivation failed on. The refused dynamic card verification code left its branch in the computation and the track data and unpredictable number fields behind, and the two-argument retailMac had no callers. They are gone. The comments are in step with the code now: the class comment of the cryptogram operations no longer calls the EMV 2000 derivation the common one, the comment on the second issuer authentication method no longer carries the response code in its input, and the class comment of EmvCrypto no longer names OpenSSL or the original engine. --- compatibility-tests/sdk-test-awscli/README.md | 1 + .../test/payment-cryptography-card.bats | 150 ++++++ .../test/PaymentCryptographyCardTest.java | 276 ++++++++++ docs/services/index.md | 2 +- docs/services/payment-cryptography-data.md | 73 +++ .../core/common/ResolvedServiceCatalog.java | 4 +- .../PaymentCryptographyAttributes.java | 59 +++ ...tCryptographyAuthCryptogramOperations.java | 328 ++++++++++++ .../PaymentCryptographyCardController.java | 58 +++ ...tCryptographyCardValidationOperations.java | 246 +++++++++ .../PaymentCryptographyCryptoHandler.java | 4 + .../PaymentCryptographyKeyRules.java | 40 ++ .../PaymentCryptographyPinOperations.java | 4 +- .../paymentcryptography/crypto/Ciphers.java | 11 + .../paymentcryptography/crypto/CvvCrypto.java | 119 +++++ .../paymentcryptography/crypto/EmvCrypto.java | 348 +++++++++++++ ...ment-cryptography-data-request-shapes.json | 367 ++++++++++++- ...mentCryptographyDataPlaneIamRouteTest.java | 12 + ...ptographyAuthCryptogramOperationsTest.java | 485 ++++++++++++++++++ ...ptographyCardValidationOperationsTest.java | 283 ++++++++++ .../PaymentCryptographyCryptoHandlerTest.java | 59 +++ ...mentCryptographyDataRequestShapesTest.java | 21 + .../PaymentCryptographyTestFixtures.java | 84 +++ .../crypto/CvvCryptoTest.java | 124 +++++ .../crypto/EmvCryptoTest.java | 106 ++++ .../regen_payment_cryptography_data_shapes.py | 2 + tools/docs/services.yaml | 1 + 27 files changed, 3261 insertions(+), 6 deletions(-) create mode 100644 compatibility-tests/sdk-test-awscli/test/payment-cryptography-card.bats create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyCardTest.java create mode 100644 src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperations.java create mode 100644 src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardController.java create mode 100644 src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardValidationOperations.java create mode 100644 src/main/java/io/floci/aws/services/paymentcryptography/crypto/CvvCrypto.java create mode 100644 src/main/java/io/floci/aws/services/paymentcryptography/crypto/EmvCrypto.java create mode 100644 src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperationsTest.java create mode 100644 src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardValidationOperationsTest.java create mode 100644 src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyTestFixtures.java create mode 100644 src/test/java/io/floci/aws/services/paymentcryptography/crypto/CvvCryptoTest.java create mode 100644 src/test/java/io/floci/aws/services/paymentcryptography/crypto/EmvCryptoTest.java diff --git a/compatibility-tests/sdk-test-awscli/README.md b/compatibility-tests/sdk-test-awscli/README.md index d2a9f83cdb..4435fad035 100644 --- a/compatibility-tests/sdk-test-awscli/README.md +++ b/compatibility-tests/sdk-test-awscli/README.md @@ -22,6 +22,7 @@ Tests are plain bash scripts that call `aws` CLI commands with `--endpoint-url` | `s3-notifications` | S3 → SQS event notifications | | `payment-cryptography-data` | The Payment Cryptography data plane: encrypt, decrypt, MAC | | `payment-cryptography-pin` | The Payment Cryptography PIN operations: generate, verify, translate | +| `payment-cryptography-card` | The Payment Cryptography card operations: the card verification value and the authorization cryptogram | ## Requirements diff --git a/compatibility-tests/sdk-test-awscli/test/payment-cryptography-card.bats b/compatibility-tests/sdk-test-awscli/test/payment-cryptography-card.bats new file mode 100644 index 0000000000..a4569bc673 --- /dev/null +++ b/compatibility-tests/sdk-test-awscli/test/payment-cryptography-card.bats @@ -0,0 +1,150 @@ +#!/usr/bin/env bats +# Payment Cryptography card validation value and authorization cryptogram tests +# +# The card operations are the data plane's own routes, so a client of it reaches them +# under the internal prefix the router rewrites them onto. These tests drive them with +# the AWS CLI, which is such a client. + +setup() { + load 'test_helper/common-setup' + CVK_ARN="" + ACG_ARN="" + DATA_KEY_ARN="" +} + +teardown() { + for key in "$CVK_ARN" "$ACG_ARN" "$DATA_KEY_ARN"; do + if [ -n "$key" ]; then + aws_cmd payment-cryptography delete-key --key-identifier "$key" \ + --delete-key-in-days 7 >/dev/null 2>&1 || true + fi + done +} + +# A key of the card verification usage, for the value of the card account. +create_cvk() { + aws_cmd payment-cryptography create-key \ + --key-attributes 'KeyAlgorithm=TDES_2KEY,KeyClass=SYMMETRIC_KEY,KeyUsage=TR31_C0_CARD_VERIFICATION_KEY,KeyModesOfUse={Generate=true,Verify=true}' \ + --exportable \ + --query 'Key.KeyArn' --output text +} + +# A key of the application cryptogram usage, for the cryptogram of the transaction. +create_acg() { + aws_cmd payment-cryptography create-key \ + --key-attributes 'KeyAlgorithm=TDES_2KEY,KeyClass=SYMMETRIC_KEY,KeyUsage=TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS,KeyModesOfUse={Generate=true,DeriveKey=true}' \ + --exportable \ + --query 'Key.KeyArn' --output text +} + +@test "Payment Cryptography card: a card verification value is generated and verifies" { + CVK_ARN=$(create_cvk) + [ -n "$CVK_ARN" ] + + run aws_cmd payment-cryptography-data generate-card-validation-data \ + --key-identifier "$CVK_ARN" \ + --primary-account-number "5081470082639564" \ + --generation-attributes 'CardVerificationValue1={CardExpiryDate=3003,ServiceCode=201}' + assert_success + VALUE=$(json_get "$output" '.ValidationData') + [ -n "$VALUE" ] + # The value is three digits. + [ "${#VALUE}" -eq 3 ] + # The answer names the key the value was computed under. + [ "$(json_get "$output" '.KeyArn')" = "$CVK_ARN" ] + + run aws_cmd payment-cryptography-data verify-card-validation-data \ + --key-identifier "$CVK_ARN" \ + --primary-account-number "5081470082639564" \ + --validation-data "$VALUE" \ + --verification-attributes 'CardVerificationValue1={CardExpiryDate=3003,ServiceCode=201}' + assert_success +} + +@test "Payment Cryptography card: a card verification value that does not verify is refused" { + CVK_ARN=$(create_cvk) + [ -n "$CVK_ARN" ] + + # The value is not the one over the card account, so the verification fails. + run aws_cmd payment-cryptography-data verify-card-validation-data \ + --key-identifier "$CVK_ARN" \ + --primary-account-number "5081470082639564" \ + --validation-data "999" \ + --verification-attributes 'CardVerificationValue1={CardExpiryDate=3003,ServiceCode=201}' + assert_failure + # A value that does not verify is a verification that failed, not a malformed request. + [[ "$output" == *"VerificationFailedException"* ]] +} + +@test "Payment Cryptography card: a key of the wrong usage is refused" { + # The card verification value is computed under the card verification key, and the + # usage is what says which key that is. + run aws_cmd payment-cryptography create-key \ + --key-attributes 'KeyAlgorithm=TDES_2KEY,KeyClass=SYMMETRIC_KEY,KeyUsage=TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY,KeyModesOfUse={Encrypt=true,Decrypt=true}' \ + --exportable \ + --query 'Key.KeyArn' --output text + assert_success + DATA_KEY_ARN="$output" + [ -n "$DATA_KEY_ARN" ] + + run aws_cmd payment-cryptography-data generate-card-validation-data \ + --key-identifier "$DATA_KEY_ARN" \ + --primary-account-number "5081470082639564" \ + --generation-attributes 'CardVerificationValue1={CardExpiryDate=3003,ServiceCode=201}' + assert_failure + [[ "$output" == *"ValidationException"* ]] +} + +@test "Payment Cryptography card: the authorization cryptogram is generated and verifies" { + ACG_ARN=$(create_acg) + [ -n "$ACG_ARN" ] + + run aws_cmd payment-cryptography-data generate-auth-request-cryptogram \ + --key-identifier "$ACG_ARN" \ + --transaction-data "00000000170000000000000008400080008000084016051700000000093800000B1F2201030000000000000000000000000000000000000000000000000000008000000000000000" \ + --major-key-derivation-mode EMV_OPTION_A \ + --session-key-derivation-attributes 'EmvCommon={PrimaryAccountNumber=5081470082639564,PanSequenceNumber=01,ApplicationTransactionCounter=0001}' + assert_success + CRYPTOGRAM=$(json_get "$output" '.AuthRequestCryptogram') + [ -n "$CRYPTOGRAM" ] + # The cryptogram is the eight bytes of the retail MAC, as hexadecimal. + [ "${#CRYPTOGRAM}" -eq 16 ] + + run aws_cmd payment-cryptography-data verify-auth-request-cryptogram \ + --key-identifier "$ACG_ARN" \ + --transaction-data "00000000170000000000000008400080008000084016051700000000093800000B1F2201030000000000000000000000000000000000000000000000000000008000000000000000" \ + --auth-request-cryptogram "$CRYPTOGRAM" \ + --major-key-derivation-mode EMV_OPTION_A \ + --session-key-derivation-attributes 'EmvCommon={PrimaryAccountNumber=5081470082639564,PanSequenceNumber=01,ApplicationTransactionCounter=0001}' + assert_success +} + +@test "Payment Cryptography card: an authorization cryptogram that does not verify is refused" { + ACG_ARN=$(create_acg) + [ -n "$ACG_ARN" ] + + # The cryptogram is not the one over the transaction, so the verification fails. + run aws_cmd payment-cryptography-data verify-auth-request-cryptogram \ + --key-identifier "$ACG_ARN" \ + --transaction-data "00000000170000000000000008400080008000084016051700000000093800000B1F2201030000000000000000000000000000000000000000000000000000008000000000000000" \ + --auth-request-cryptogram "0000000000000000" \ + --major-key-derivation-mode EMV_OPTION_A \ + --session-key-derivation-attributes 'EmvCommon={PrimaryAccountNumber=5081470082639564,PanSequenceNumber=01,ApplicationTransactionCounter=0001}' + assert_failure + [[ "$output" == *"VerificationFailedException"* ]] +} + +@test "Payment Cryptography card: the American Express cryptogram is refused" { + ACG_ARN=$(create_acg) + [ -n "$ACG_ARN" ] + + # The AEIPS session key derivation is proprietary, so the service answers with the + # error that says so rather than with a cryptogram of its own making. + run aws_cmd payment-cryptography-data generate-auth-request-cryptogram \ + --key-identifier "$ACG_ARN" \ + --transaction-data "00000000170000000000000008400080008000084016051700000000093800000B1F2201030000000000000000000000000000000000000000000000000000008000000000000000" \ + --major-key-derivation-mode EMV_OPTION_A \ + --session-key-derivation-attributes 'Amex={PrimaryAccountNumber=5081470082639564,PanSequenceNumber=01}' + assert_failure + [[ "$output" == *"ValidationException"* ]] +} diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyCardTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyCardTest.java new file mode 100644 index 0000000000..cb68174516 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyCardTest.java @@ -0,0 +1,276 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.paymentcryptography.PaymentCryptographyClient; +import software.amazon.awssdk.services.paymentcryptography.model.KeyAlgorithm; +import software.amazon.awssdk.services.paymentcryptography.model.KeyClass; +import software.amazon.awssdk.services.paymentcryptography.model.KeyModesOfUse; +import software.amazon.awssdk.services.paymentcryptography.model.KeyUsage; +import software.amazon.awssdk.services.paymentcryptographydata.PaymentCryptographyDataClient; +import software.amazon.awssdk.services.paymentcryptographydata.model.CardGenerationAttributes; +import software.amazon.awssdk.services.paymentcryptographydata.model.CardVerificationAttributes; +import software.amazon.awssdk.services.paymentcryptographydata.model.CardVerificationValue1; +import software.amazon.awssdk.services.paymentcryptographydata.model.DynamicCardVerificationValue; +import software.amazon.awssdk.services.paymentcryptographydata.model.GenerateAuthRequestCryptogramResponse; +import software.amazon.awssdk.services.paymentcryptographydata.model.GenerateCardValidationDataResponse; +import software.amazon.awssdk.services.paymentcryptographydata.model.MajorKeyDerivationMode; +import software.amazon.awssdk.services.paymentcryptographydata.model.SessionKeyAmex; +import software.amazon.awssdk.services.paymentcryptographydata.model.SessionKeyDerivation; +import software.amazon.awssdk.services.paymentcryptographydata.model.SessionKeyEmvCommon; +import software.amazon.awssdk.services.paymentcryptographydata.model.ValidationException; +import software.amazon.awssdk.services.paymentcryptographydata.model.VerificationFailedException; +import software.amazon.awssdk.services.paymentcryptographydata.model.VerificationFailedReason; + +import java.util.function.Consumer; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@DisplayName("Payment Cryptography card validation values and authorization cryptograms") +class PaymentCryptographyCardTest { + + /** The account number the card values belong to. */ + private static final String PAN = "5081470082639564"; + + /** The expiry of the card, in the YYMM form the request takes. */ + private static final String EXPIRY = "3003"; + + /** The service code of the first card verification value. */ + private static final String SERVICE_CODE = "201"; + + /** The sequence number of the card, which the master key derivation takes. */ + private static final String PSN = "01"; + + /** The transaction counter the session key derivation takes. */ + private static final String ATC = "0001"; + + /** + * The transaction data the cryptogram is computed over. + * + *

The user guide tells the caller to pad the transaction data before sending + * it, and the data here is padded the way its example is: a whole number of + * eight-byte blocks, with the {@code 80} and the zeros that method 2 appends. + */ + private static final String TRANSACTION_DATA = + "00000000170000000000000008400080008000084016051700000000093800000B1F2201" + + "030000000000000000000000000000000000000000000000000000008000000000000000"; + + private static PaymentCryptographyDataClient client; + private static String cardVerificationKeyArn; + private static String dynamicValueKeyArn; + private static String applicationCryptogramKeyArn; + + @BeforeAll + static void setup() { + client = TestFixtures.paymentCryptographyDataClient(); + // The card verification value is computed under the card verification key, the dynamic + // one under a key of its own usage that may derive, and the cryptogram under the + // application cryptogram key. + cardVerificationKeyArn = createKeyArn(KeyAlgorithm.TDES_2_KEY, + KeyUsage.TR31_C0_CARD_VERIFICATION_KEY, m -> m.generate(true).verify(true)); + dynamicValueKeyArn = createKeyArn(KeyAlgorithm.TDES_2_KEY, + KeyUsage.TR31_E6_EMV_MKEY_OTHER, m -> m.generate(true).verify(true).deriveKey(true)); + applicationCryptogramKeyArn = createKeyArn(KeyAlgorithm.TDES_2_KEY, + KeyUsage.TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS, m -> m.generate(true).deriveKey(true)); + } + + /** + * The ARN of a key of the given algorithm, usage and modes of use. + * + *

Every key this test needs is made the same way, so the request is written once + * and each key only differs in the attributes it carries. + * + * @param algorithm the key's algorithm + * @param usage the key's usage + * @param modes the modes of use the key allows + * @return the ARN of the key that was made + */ + private static String createKeyArn(KeyAlgorithm algorithm, KeyUsage usage, + Consumer modes) { + try (PaymentCryptographyClient keyClient = TestFixtures.paymentCryptographyClient()) { + return keyClient.createKey(r -> r + .keyAttributes(a -> a + .keyAlgorithm(algorithm) + .keyClass(KeyClass.SYMMETRIC_KEY) + .keyUsage(usage) + .keyModesOfUse(modes)) + .exportable(true)) + .key().keyArn(); + } + } + + @AfterAll + static void cleanup() { + if (client != null) { + client.close(); + } + } + + @Test + void theCardVerificationValueIsGeneratedAndVerifies() { + GenerateCardValidationDataResponse generated = client.generateCardValidationData(r -> r + .keyIdentifier(cardVerificationKeyArn) + .primaryAccountNumber(PAN) + .generationAttributes(CardGenerationAttributes.builder() + .cardVerificationValue1(CardVerificationValue1.builder() + .cardExpiryDate(EXPIRY) + .serviceCode(SERVICE_CODE) + .build()) + .build())); + + String value = generated.validationData(); + assertThat(value).isNotBlank(); + assertThat(value).hasSize(3); + assertThat(generated.keyArn()).isEqualTo(cardVerificationKeyArn); + + // The value verifies against the one that was generated. + client.verifyCardValidationData(r -> r + .keyIdentifier(cardVerificationKeyArn) + .primaryAccountNumber(PAN) + .validationData(value) + .verificationAttributes(CardVerificationAttributes.builder() + .cardVerificationValue1(CardVerificationValue1.builder() + .cardExpiryDate(EXPIRY) + .serviceCode(SERVICE_CODE) + .build()) + .build())); + } + + @Test + void aCardVerificationValueThatDoesNotVerifyIsRefused() { + assertThatThrownBy(() -> client.verifyCardValidationData(r -> r + .keyIdentifier(cardVerificationKeyArn) + .primaryAccountNumber(PAN) + .validationData("999") + .verificationAttributes(CardVerificationAttributes.builder() + .cardVerificationValue1(CardVerificationValue1.builder() + .cardExpiryDate(EXPIRY) + .serviceCode(SERVICE_CODE) + .build()) + .build()))) + .isInstanceOf(VerificationFailedException.class) + // The exception carries the reason the model names for a card value that + // does not verify, so the caller can tell the two failures apart. + .extracting(e -> ((VerificationFailedException) e).reason()) + .isEqualTo(VerificationFailedReason.INVALID_VALIDATION_DATA); + } + + @Test + void theDynamicCardVerificationValueIsGeneratedAndVerifies() { + GenerateCardValidationDataResponse generated = client.generateCardValidationData(r -> r + .keyIdentifier(dynamicValueKeyArn) + .primaryAccountNumber(PAN) + .generationAttributes(CardGenerationAttributes.builder() + .dynamicCardVerificationValue(DynamicCardVerificationValue.builder() + .cardExpiryDate(EXPIRY) + .serviceCode(SERVICE_CODE) + .panSequenceNumber(PSN) + .applicationTransactionCounter(ATC) + .build()) + .build())); + + String value = generated.validationData(); + assertThat(value).isNotBlank(); + assertThat(value).hasSize(3); + + client.verifyCardValidationData(r -> r + .keyIdentifier(dynamicValueKeyArn) + .primaryAccountNumber(PAN) + .validationData(value) + .verificationAttributes(CardVerificationAttributes.builder() + .dynamicCardVerificationValue(DynamicCardVerificationValue.builder() + .cardExpiryDate(EXPIRY) + .serviceCode(SERVICE_CODE) + .panSequenceNumber(PSN) + .applicationTransactionCounter(ATC) + .build()) + .build())); + } + + @Test + void aKeyOfTheWrongUsageIsRefused() { + String dataKeyArn = createKeyArn(KeyAlgorithm.TDES_2_KEY, + KeyUsage.TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY, m -> m.encrypt(true).decrypt(true)); + + assertThatThrownBy(() -> client.generateCardValidationData(r -> r + .keyIdentifier(dataKeyArn) + .primaryAccountNumber(PAN) + .generationAttributes(CardGenerationAttributes.builder() + .cardVerificationValue1(CardVerificationValue1.builder() + .cardExpiryDate(EXPIRY) + .serviceCode(SERVICE_CODE) + .build()) + .build()))) + .isInstanceOf(ValidationException.class); + } + + @Test + void theAuthorizationCryptogramIsGeneratedAndVerifies() { + GenerateAuthRequestCryptogramResponse generated = client.generateAuthRequestCryptogram(r -> r + .keyIdentifier(applicationCryptogramKeyArn) + .transactionData(TRANSACTION_DATA) + .majorKeyDerivationMode(MajorKeyDerivationMode.EMV_OPTION_A) + .sessionKeyDerivationAttributes(SessionKeyDerivation.builder() + .emvCommon(SessionKeyEmvCommon.builder() + .primaryAccountNumber(PAN) + .panSequenceNumber(PSN) + .applicationTransactionCounter(ATC) + .build()) + .build())); + + String cryptogram = generated.authRequestCryptogram(); + assertThat(cryptogram).isNotBlank(); + assertThat(cryptogram).hasSize(16); + assertThat(generated.keyArn()).isEqualTo(applicationCryptogramKeyArn); + + client.verifyAuthRequestCryptogram(r -> r + .keyIdentifier(applicationCryptogramKeyArn) + .transactionData(TRANSACTION_DATA) + .authRequestCryptogram(cryptogram) + .majorKeyDerivationMode(MajorKeyDerivationMode.EMV_OPTION_A) + .sessionKeyDerivationAttributes(SessionKeyDerivation.builder() + .emvCommon(SessionKeyEmvCommon.builder() + .primaryAccountNumber(PAN) + .panSequenceNumber(PSN) + .applicationTransactionCounter(ATC) + .build()) + .build())); + } + + @Test + void anAuthorizationCryptogramThatDoesNotVerifyIsRefused() { + assertThatThrownBy(() -> client.verifyAuthRequestCryptogram(r -> r + .keyIdentifier(applicationCryptogramKeyArn) + .transactionData(TRANSACTION_DATA) + .authRequestCryptogram("0000000000000000") + .majorKeyDerivationMode(MajorKeyDerivationMode.EMV_OPTION_A) + .sessionKeyDerivationAttributes(SessionKeyDerivation.builder() + .emvCommon(SessionKeyEmvCommon.builder() + .primaryAccountNumber(PAN) + .panSequenceNumber(PSN) + .applicationTransactionCounter(ATC) + .build()) + .build()))) + .isInstanceOf(VerificationFailedException.class); + } + + @Test + void theAmexCryptogramIsRefusedRatherThanApproximated() { + // The AEIPS session key derivation is proprietary, so the service answers with the + // error that says so rather than with a cryptogram of its own making. + assertThatThrownBy(() -> client.generateAuthRequestCryptogram(r -> r + .keyIdentifier(applicationCryptogramKeyArn) + .transactionData(TRANSACTION_DATA) + .majorKeyDerivationMode(MajorKeyDerivationMode.EMV_OPTION_A) + .sessionKeyDerivationAttributes(SessionKeyDerivation.builder() + .amex(SessionKeyAmex.builder() + .primaryAccountNumber(PAN) + .panSequenceNumber(PSN) + .build()) + .build()))) + .isInstanceOf(ValidationException.class); + } +} diff --git a/docs/services/index.md b/docs/services/index.md index 6f2d977d12..7aef930198 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 | 29 | | [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 | 12 | -| [Payment Cryptography data plane](payment-cryptography-data.md) | `POST /keys/{KeyIdentifier}/encrypt` and the rest | REST JSON | 8 | +| [Payment Cryptography data plane](payment-cryptography-data.md) | `POST /keys/{KeyIdentifier}/encrypt` and the rest | REST JSON | 12 | | [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 fc7046bfc6..796e35be22 100644 --- a/docs/services/payment-cryptography-data.md +++ b/docs/services/payment-cryptography-data.md @@ -20,6 +20,10 @@ client that talks to the control plane does not reach it by accident. | `GeneratePinData` | Generate a PIN block and the verification value that goes with it, on `POST /pindata/generate` | | `VerifyPinData` | Verify a PIN block against the verification value the issuer holds, on `POST /pindata/verify` | | `TranslatePinData` | Re-encipher a PIN block from one key to another, on `POST /pindata/translate` | +| `GenerateCardValidationData` | Generate the card verification value of a card account, on `POST /cardvalidationdata/generate` | +| `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` | ## Emulation Behavior @@ -75,6 +79,75 @@ 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 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 + refused rather than answered as if the key were a fixed one. +- **The card verification value is the three digit value of the X9 algorithm.** It is computed + from the account number, the expiry and the service code, enciphered under the card + verification key, and the value is the decimalized left-most digits of the enciphered block. + The static values take a key of the `TR31_C0_CARD_VERIFICATION_KEY` usage. The value + carries the number of digits the request asks for, which the model states as three to + five. +- **The dynamic value is the one Visa describes for the magstripe data path.** The leftmost + four digits of the account number are replaced by the transaction counter, and the result, + the expiry and the service code are enciphered under the card's unique derived key, which + the issuer derives from the master key with the account number and the PAN sequence + number. The value is bound to the transaction, and the counter diversifies it through the + data it is inserted into rather than through the key. It takes a key of the + `TR31_E6_EMV_MKEY_OTHER` usage. The dynamic card verification code, which is the + Mastercard counterpart over the track data, is refused rather than approximated: it is a + proprietary construction and there is nothing published to check a derivation against. +- **The authorization cryptogram is the ARQC of the transaction.** It is the ISO 9797-1 + algorithm 3 retail MAC over the transaction data, cut to eight bytes, under a session key + the request's derivation produces. Three derivations are served: the EMV common session key, + the Mastercard one, which also diversifies with the terminal's unpredictable number, and + the Visa one, which derives no session key at all and enciphers the transaction data under + the ICC master key. +- **The transaction data is enciphered exactly as it is given.** It reaches the service + already padded, as the user guide tells the caller to pad it, because the card padded + it the same way before it enciphered it. The service therefore pads nothing: padding + it again would encipher a block the card never enciphered. +- **The transaction data has to be a whole number of eight-byte blocks.** The ISO 9797-1 + MAC runs over eight-byte blocks, and the guide tells the caller to pad the data to a + multiple of the block size before sending it, so a length that is not a whole number + of blocks is a request the cipher cannot read and is refused. +- **The authorization cryptogram is made under a key of the application cryptogram + usage.** The key table names `TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS` with a `TDES_2KEY` + algorithm and the `DeriveKey` mode of use for it, so a key of another usage, another + algorithm, or without the mode of use is refused. +- **A key that is disabled does no work, and a key that is not there is a 404.** The + service reads a disabled key and tells the caller about it, but it does not compute a card + value or a cryptogram under it, and a request that names a key the service does not hold + is answered with the not-found error and the status the data plane answers it with. +- **The card operations and the cryptogram operations read the key through one helper.** + The usage, the algorithm, the mode of use, whether the key is enabled and whether it + still holds its material are asked in one place, so the two cannot drift apart on + what they accept. +- **The response value of the second method is made of the card status update.** The first + method takes the response code, and the second takes the card status update and the + proprietary data, as EMV Book 2 section 8.2.2 has it. +- **The American Express cryptogram is refused rather than approximated.** The AEIPS session + key derivation is proprietary and there is nothing to verify it against, and a plausible + 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 for the same reason: it needs the card's + public key certificate. +- **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 + number and a longer sequence number are refused rather than read as the digits they + carry, because the derivation reads the account number and the sequence number as they + are given. +- **The master key is derived over the rightmost sixteen digits.** The account number and + the PAN sequence number are padded on the left with zeros when they are shorter, which + is the rule EMV 4.4 Book 2 gives and the Visa Integrated Circuit Card Specification + states the same way. So an account number of twelve digits is read and derived from, + rather than refused. +- **A hexadecimal member of an odd length is refused.** The model states the length of a + hexadecimal member and does not always state an even one, so an odd number of + 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 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/src/main/java/io/floci/aws/core/common/ResolvedServiceCatalog.java b/src/main/java/io/floci/aws/core/common/ResolvedServiceCatalog.java index a54b1f00d5..409529bdbc 100644 --- a/src/main/java/io/floci/aws/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/floci/aws/core/common/ResolvedServiceCatalog.java @@ -67,6 +67,7 @@ import io.floci.aws.services.mwaa.MwaaController; import io.floci.aws.services.oam.OamController; import io.floci.aws.services.opensearch.ElasticsearchController; import io.floci.aws.services.opensearch.OpenSearchController; +import io.floci.aws.services.paymentcryptography.PaymentCryptographyCardController; import io.floci.aws.services.paymentcryptography.PaymentCryptographyCryptoController; import io.floci.aws.services.paymentcryptography.PaymentCryptographyPinController; import io.floci.aws.services.pipes.PipesController; @@ -325,7 +326,8 @@ public class ResolvedServiceCatalog { // scope its own plane is named by is an alias of that one. Set.of(), Set.of("payment-cryptography", "payment-cryptography-data"), Set.of(), Set.of(PaymentCryptographyCryptoController.class, - PaymentCryptographyPinController.class)), + PaymentCryptographyPinController.class, + PaymentCryptographyCardController.class)), descriptor("secretsmanager", "secretsmanager", config.services().secretsmanager().enabled(), true, "secretsmanager", storageMode(config.storage().services().secretsmanager().mode(), config.storage().mode()), config.storage().services().secretsmanager().flushIntervalMs(), null, ServiceProtocol.JSON, diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAttributes.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAttributes.java index 7bf5906fc9..7f7cec0e58 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAttributes.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAttributes.java @@ -1,6 +1,7 @@ package io.floci.aws.services.paymentcryptography; import com.fasterxml.jackson.databind.JsonNode; +import io.floci.aws.core.common.AwsException; import java.util.Iterator; import java.util.Map; @@ -33,6 +34,64 @@ final class PaymentCryptographyAttributes { return declared == null || declared.isNull() ? "" : declared.asText(""); } + /** + * A hexadecimal member, checked to be one the cipher can read. + * + *

The model states the length of a hexadecimal member and does not always state an + * even one, so a member of an odd length is a request the model allows and the cipher + * cannot read. It is refused with the error the model names, rather than answered with + * a failure the caller cannot catch. + * + * @param member the member's path, for the refusal + * @param value the member's text + * @return the member's text, unchanged + */ + static String hex(String member, String value) { + if (value.length() % 2 != 0) { + throw new AwsException("ValidationException", + member + " must be an even number of hexadecimal characters", 400); + } + return value; + } + + /** + * A hexadecimal member that the cipher reads as whole blocks. + * + *

The ISO 9797-1 MAC runs over eight-byte blocks, so the data it reads has to + * be a whole number of them. The user guide tells the caller to pad the + * transaction data before sending it, and a length that is not a whole number of + * blocks is a request the cipher cannot read, so it is refused rather than read + * as the blocks that fit. + * + * @param member the member's path, for the refusal + * @param value the member's text + * @return the member's text, unchanged + */ + static String blocks(String member, String value) { + if (value.length() % 16 != 0) { + throw new AwsException("ValidationException", + member + " must be a whole number of eight-byte blocks", 400); + } + return value; + } + + /** + * Refuses the wrapped-key form of a key. + * + *

A wrapped key is a TR-31 key block that the service unwraps with a key-encryption + * key, and the unwrapping is part of the key exchange. Until it is made, a request that + * carries one is refused rather than answered as if the key were a fixed one. + * + * @param request the request to read + * @param member the member the wrapped key would come in + */ + static void refuseWrappedKey(JsonNode request, String member) { + if (request.get(member) != null) { + throw new AwsException("ValidationException", + member + " is not supported by this service", 400); + } + } + /** * The one variant an attributes member holds. * diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperations.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperations.java new file mode 100644 index 0000000000..36b3961b4a --- /dev/null +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperations.java @@ -0,0 +1,328 @@ +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.crypto.EmvCrypto; +import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static io.floci.aws.services.paymentcryptography.PaymentCryptographyAttributes.soleVariant; +import static io.floci.aws.services.paymentcryptography.PaymentCryptographyAttributes.text; + +/** + * The authorization request cryptograms. + * + *

The ARQC is the cryptogram of an authorization request, computed under a session key that + * the transaction's key derivation produces. The session key is derived from the ICC AC master + * key, which is itself derived from the account number and the sequence number, so the whole + * chain is one derivation and the cryptogram is the ISO 9797-1 algorithm 3 retail MAC over the + * transaction data, cut to eight bytes. + * + *

Three derivations are served. The EMV common session key is the one the EMV common + * specification gives. The Mastercard derivation is the proprietary one, which also + * diversifies with the unpredictable number. The Visa derivation derives no session key at + * all: the transaction data is enciphered under the ICC master key, which is the Visa Smart + * Debit and Credit method. + * + *

Two derivations are refused rather than approximated. The American Express one is + * proprietary and there is nothing to verify it against, and a plausible wrong cryptogram is + * worse than an error. The EMV 2000 one is the EMV 4.1 tree derivation, which needs the + * card's public key certificate. + */ +@ApplicationScoped +public class PaymentCryptographyAuthCryptogramOperations { + + /** The hexadecimal the data plane's blobs are written in. */ + private static final HexFormat HEX = HexFormat.of().withUpperCase(); + + /** The session key derivations. */ + private enum Scheme { + /** The EMV common session key, derived from the application transaction counter. */ + EMV_COMMON, + /** The Mastercard proprietary derivation, which also diversifies with the number. */ + MASTERCARD, + /** No session key: the transaction data is enciphered under the ICC master key. */ + VSDC + } + + /** The variants that use the EMV common session key. */ + private static final Set COMMON_SK = + new LinkedHashSet<>(Arrays.asList("EmvCommon")); + + /** The variants that derive nothing and encipher under the ICC master key. */ + private static final Set DIRECT_SK = new LinkedHashSet<>(Arrays.asList("Visa")); + + private final PaymentCryptographyService service; + + @Inject + public PaymentCryptographyAuthCryptogramOperations(PaymentCryptographyService service) { + this.service = service; + } + + /** The resolved session-key derivation for a request. */ + private static final class SessionKey { + final String pan; + final String psn; + final String atc; + final Scheme scheme; + final String unpredictableNumber; + final boolean optionB; + + SessionKey(String pan, String psn, String atc, Scheme scheme, + String unpredictableNumber, boolean optionB) { + this.pan = pan; + this.psn = psn; + this.atc = atc; + this.scheme = scheme; + this.unpredictableNumber = unpredictableNumber; + this.optionB = optionB; + } + } + + // ---- GenerateAuthRequestCryptogram --------------------------------------- + + /** + * The cryptogram of an authorization request. + */ + Map generate(JsonNode request, String region) { + PaymentCryptographyDataRequestShapes.check("GenerateAuthRequestCryptogram", request); + String keyIdentifier = text(request, "KeyIdentifier"); + String transactionData = PaymentCryptographyAttributes.blocks("TransactionData", + PaymentCryptographyAttributes.hex("TransactionData", + text(request, "TransactionData"))); + SessionKey sk = resolveDerivation(request); + + PaymentCryptographyKey key = requiredKey(keyIdentifier, region); + PaymentCryptographyKeyRules.requireUsage(key, + List.of("TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS"), "computing a cryptogram"); + PaymentCryptographyKeyRules.requireAlgorithm(key, "TDES_2KEY", "computing a cryptogram"); + PaymentCryptographyKeyRules.requireDerive(key, "deriving a session key"); + byte[] material = HEX.parseHex(PaymentCryptographyKeyRules.materialHex(key)); + + EmvCrypto.Arqc computed = computeArqc(sk, material, transactionData); + + Map out = new LinkedHashMap<>(); + out.put("KeyArn", key.getArn()); + out.put("KeyCheckValue", key.getKeyCheckValue()); + out.put("AuthRequestCryptogram", HEX.formatHex(computed.arqc)); + return out; + } + + // ---- VerifyAuthRequestCryptogram ----------------------------------------- + + /** + * The cryptogram of an authorization request, verified, and the response value that goes + * with it. + */ + Map verify(JsonNode request, String region) { + PaymentCryptographyDataRequestShapes.check("VerifyAuthRequestCryptogram", request); + String keyIdentifier = text(request, "KeyIdentifier"); + String arqc = text(request, "AuthRequestCryptogram"); + String transactionData = PaymentCryptographyAttributes.blocks("TransactionData", + PaymentCryptographyAttributes.hex("TransactionData", + text(request, "TransactionData"))); + SessionKey sk = resolveDerivation(request); + + // The response attributes are optional, and the answer carries the response value only + // when the caller asked for one. + String arpcMethod = null; + String arc = "0000"; + String csu = null; + String pad = ""; + JsonNode responseAttributes = request.get("AuthResponseAttributes"); + if (responseAttributes != null) { + String variant = soleVariant(responseAttributes); + if (variant == null) { + throw validation("AuthResponseAttributes must specify exactly one variant"); + } + if ("ArpcMethod1".equals(variant)) { + arpcMethod = "1"; + JsonNode method = responseAttributes.get(variant); + arc = text(method, "AuthResponseCode"); + } else if ("ArpcMethod2".equals(variant)) { + arpcMethod = "2"; + JsonNode method = responseAttributes.get(variant); + csu = text(method, "CardStatusUpdate"); + pad = PaymentCryptographyAttributes.hex( + "AuthResponseAttributes.ArpcMethod2.ProprietaryAuthenticationData", + text(method, "ProprietaryAuthenticationData")); + if (sk.scheme == Scheme.MASTERCARD) { + throw validation("ARPC method 2 is not used in practice with the Mastercard " + + "session key derivation (method 1 only)"); + } + if (sk.scheme == Scheme.VSDC) { + throw validation("ARPC method 2 is not used in practice with the Visa session " + + "key derivation (method 1 only)"); + } + } else { + throw validation("AuthResponseAttributes." + variant + + " not supported by this service (ArpcMethod1, ArpcMethod2)"); + } + } + + PaymentCryptographyKey key = requiredKey(keyIdentifier, region); + PaymentCryptographyKeyRules.requireUsage(key, + List.of("TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS"), "computing a cryptogram"); + PaymentCryptographyKeyRules.requireAlgorithm(key, "TDES_2KEY", "computing a cryptogram"); + PaymentCryptographyKeyRules.requireDerive(key, "deriving a session key"); + byte[] material = HEX.parseHex(PaymentCryptographyKeyRules.materialHex(key)); + + EmvCrypto.Arqc computed = computeArqc(sk, material, transactionData); + String expected = HEX.formatHex(computed.arqc); + if (!expected.equalsIgnoreCase(arqc)) { + throw verificationFailed("the authorization request cryptogram did not verify", + "INVALID_AUTH_REQUEST_CRYPTOGRAM"); + } + + Map out = new LinkedHashMap<>(); + out.put("KeyArn", key.getArn()); + out.put("KeyCheckValue", key.getKeyCheckValue()); + // The response key is not the session key. M/Chip 4 v1.1 section 7-4 defines + // SKARPC := MKAC for the proprietary method, and only the EMV common session key method + // sets SKARPC := SKAC. Using the session key here would encipher under a key no M/Chip + // terminal would use. + byte[] arpcKey = sk.scheme == Scheme.EMV_COMMON + ? computed.sessionKey + : masterKeyOf(sk, HEX.parseHex(key.getKeyMaterialHex())); + if ("1".equals(arpcMethod)) { + out.put("AuthResponseValue", HEX.formatHex(EmvCrypto.computeArpcMethod1( + arpcKey, HEX.parseHex(arqc), arc))); + } else if ("2".equals(arpcMethod)) { + // The second method is made from the card status update and the proprietary + // data; the response code belongs to the first method. + out.put("AuthResponseValue", HEX.formatHex(EmvCrypto.computeArpcMethod2( + arpcKey, HEX.parseHex(arqc), csu, pad))); + } + return out; + } + + // ---- the parts ----------------------------------------------------------- + + /** + * The ARQC for a resolved scheme, and the session key it was computed under. + * + *

The session key is derived per scheme, so this is the one place the choice is made; the + * cryptogram itself is always the ISO 9797-1 algorithm 3 retail MAC, cut to eight bytes. + */ + private static EmvCrypto.Arqc computeArqc(SessionKey sk, byte[] imk, String transactionData) { + byte[] mk = masterKeyOf(sk, imk); + byte[] atc = HEX.parseHex(sk.atc); + byte[] sessionKey; + switch (sk.scheme) { + case MASTERCARD: + sessionKey = EmvCrypto.deriveSessionKeyMastercard( + mk, atc, HEX.parseHex(sk.unpredictableNumber)); + break; + case EMV_COMMON: + sessionKey = EmvCrypto.deriveSessionKey(mk, atc); + break; + case VSDC: + default: + // No session key: the transaction data is enciphered under the ICC master key, + // which is the Visa Smart Debit method. + sessionKey = mk; + break; + } + byte[] mac = EmvCrypto.retailMac(sessionKey, HEX.parseHex(transactionData), + EmvCrypto.Padding.NONE); + return new EmvCrypto.Arqc(Arrays.copyOf(mac, 8), sessionKey); + } + + /** + * The ICC AC master key for the resolved derivation, which is also the M/Chip ARPC key. + * + *

A derivation the request cannot be read for is refused with the error the model + * names, rather than answered with a failure the caller cannot catch. + */ + private static byte[] masterKeyOf(SessionKey sk, byte[] imk) { + try { + return sk.optionB + ? EmvCrypto.deriveIccMasterKeyOptionB(imk, sk.pan, sk.psn) + : EmvCrypto.deriveIccMasterKey(imk, sk.pan, sk.psn); + } catch (IllegalArgumentException e) { + throw validation(e.getMessage()); + } + } + + /** + * Resolves the master-key derivation mode and the session-key derivation attributes, which + * both cryptogram operations share. + */ + private static SessionKey resolveDerivation(JsonNode request) { + boolean optionB = "EMV_OPTION_B".equals(text(request, "MajorKeyDerivationMode")); + + JsonNode skd = request.get("SessionKeyDerivationAttributes"); + if (skd == null) { + throw validation("SessionKeyDerivationAttributes is required"); + } + String variant = soleVariant(skd); + if (variant == null) { + throw validation("SessionKeyDerivationAttributes must specify exactly one variant"); + } + // Amex is refused rather than approximated: the AEIPS session key derivation is + // proprietary and there is nothing to verify a derivation against, and a plausible wrong + // cryptogram is the one outcome worse than an error. + if ("Amex".equals(variant)) { + throw validation("SessionKeyDerivationAttributes.Amex requires the AEIPS session key " + + "derivation, which this service does not implement. It is not approximated."); + } + if ("Emv2000".equals(variant)) { + throw validation("SessionKeyDerivationAttributes.Emv2000 requires the EMV 4.1 tree " + + "derivation, which this service does not implement. It is not approximated."); + } + boolean common = COMMON_SK.contains(variant); + boolean mastercard = "Mastercard".equals(variant); + if (!common && !mastercard && !DIRECT_SK.contains(variant)) { + throw validation("SessionKeyDerivationAttributes." + variant + + " is not a recognized variant"); + } + JsonNode attrs = skd.get(variant); + String pan = text(attrs, "PrimaryAccountNumber"); + String psn = text(attrs, "PanSequenceNumber"); + String atc = text(attrs, "ApplicationTransactionCounter"); + if (mastercard && optionB) { + // The reference implementation's own constraint: master key derivation option B is + // not used in practice with this scheme. + throw validation("MasterKeyDerivationMode EMV_OPTION_B is not used in practice with " + + "the Mastercard session key derivation (EMV_OPTION_A only)"); + } + String unpredictableNumber = null; + if (mastercard) { + // Taken from the request, never inferred: the transaction data is an opaque + // concatenated block whose layout the caller chooses, so a fixed offset would be + // right for one CDOL and silently wrong for every other. + unpredictableNumber = text(attrs, "UnpredictableNumber"); + } + Scheme scheme = mastercard ? Scheme.MASTERCARD + : (common ? Scheme.EMV_COMMON : Scheme.VSDC); + return new SessionKey(pan, psn, atc, scheme, unpredictableNumber, optionB); + } + + // ---- 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); + } + + private static AwsException verificationFailed(String message, String reason) { + return new AwsException("VerificationFailedException", message, 400, Map.of("Reason", reason)); + } +} diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardController.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardController.java new file mode 100644 index 0000000000..eba6730798 --- /dev/null +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardController.java @@ -0,0 +1,58 @@ +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 card validation values and the authorization cryptograms. + * + *

The routes are the ones the AWS SDK builds: the card validation value of a card account, + * and the cryptogram an authorization request carries. + */ +@Path(PaymentCryptographyDataPlaneRouteFilter.INTERNAL_PREFIX) +public class PaymentCryptographyCardController extends PaymentCryptographyDataPlaneController { + + private final PaymentCryptographyCardValidationOperations cardValidation; + + private final PaymentCryptographyAuthCryptogramOperations authCryptogram; + + @Inject + public PaymentCryptographyCardController(PaymentCryptographyCardValidationOperations cardValidation, + PaymentCryptographyAuthCryptogramOperations authCryptogram, + ObjectMapper objectMapper, + RegionResolver regionResolver) { + super(objectMapper, regionResolver); + this.cardValidation = cardValidation; + this.authCryptogram = authCryptogram; + } + + @POST + @Path("/cardvalidationdata/generate") + public Response generateCardValidationData(String body, @Context HttpHeaders headers) { + return respond(cardValidation.generate(parse(body), region(headers))); + } + + @POST + @Path("/cardvalidationdata/verify") + public Response verifyCardValidationData(String body, @Context HttpHeaders headers) { + return respond(cardValidation.verify(parse(body), region(headers))); + } + + @POST + @Path("/cryptogram/generate") + public Response generateAuthRequestCryptogram(String body, @Context HttpHeaders headers) { + return respond(authCryptogram.generate(parse(body), region(headers))); + } + + @POST + @Path("/cryptogram/verify") + public Response verifyAuthRequestCryptogram(String body, @Context HttpHeaders headers) { + return respond(authCryptogram.verify(parse(body), region(headers))); + } +} diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardValidationOperations.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardValidationOperations.java new file mode 100644 index 0000000000..786c9dea15 --- /dev/null +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardValidationOperations.java @@ -0,0 +1,246 @@ +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.crypto.CvvCrypto; +import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +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 card validation operations. + * + *

The card verification value is the value the issuer holds and the acquirer asks for: the + * three digits of the CVV, computed under the card verification key from the account number, + * the expiry and the service code. + * + *

The dynamic variants compute the value from the transaction instead: the dynamic card + * verification value from the account number and the transaction counters, and the dynamic card + * verification code from the track data. They need a key of their own usage, and one that may + * derive. + */ +@ApplicationScoped +public class PaymentCryptographyCardValidationOperations { + + /** The length of the value when the request does not name one. */ + private static final int DEFAULT_VALIDATION_DATA_LENGTH = 3; + + /** The service code of the second card verification value, which the service fixes. */ + private static final String CVV2_SERVICE_CODE = "000"; + + private final PaymentCryptographyService service; + + @Inject + public PaymentCryptographyCardValidationOperations(PaymentCryptographyService service) { + this.service = service; + } + + /** + * The card validation attributes of a request. + */ + private static final class CardAttrs { + /** The static variants: the expiry and the service code. */ + String expiry; + String serviceCode; + /** The dynamic variants. */ + String panSequenceNumber; + String applicationTransactionCounter; + /** Which variant this is, for the key rules and the cipher. */ + String variant; + } + + // ---- GenerateCardValidationData ------------------------------------------ + + /** + * The card validation value of a card account. + */ + Map generate(JsonNode request, String region) { + PaymentCryptographyDataRequestShapes.check("GenerateCardValidationData", request); + String keyIdentifier = text(request, "KeyIdentifier"); + String pan = text(request, "PrimaryAccountNumber"); + Integer validationDataLength = request.hasNonNull("ValidationDataLength") + ? request.path("ValidationDataLength").asInt() + : null; + int length = validationDataLength == null ? DEFAULT_VALIDATION_DATA_LENGTH + : validationDataLength; + CardAttrs attrs = resolveCardAttrs(request.get("GenerationAttributes")); + + PaymentCryptographyKey key = requiredKey(keyIdentifier, region); + requireKeyForVariant(key, attrs.variant, "Generate"); + + Map out = new LinkedHashMap<>(); + out.put("ValidationData", computeValue(pan, attrs, key, length)); + out.put("KeyArn", key.getArn()); + out.put("KeyCheckValue", key.getKeyCheckValue()); + return out; + } + + // ---- VerifyCardValidationData -------------------------------------------- + + /** + * The card validation value of a card account, verified. + */ + Map verify(JsonNode request, String region) { + PaymentCryptographyDataRequestShapes.check("VerifyCardValidationData", request); + String keyIdentifier = text(request, "KeyIdentifier"); + String pan = text(request, "PrimaryAccountNumber"); + String validationData = text(request, "ValidationData"); + int length = validationData.length(); + CardAttrs attrs = resolveCardAttrs(request.get("VerificationAttributes")); + + PaymentCryptographyKey key = requiredKey(keyIdentifier, region); + requireKeyForVariant(key, attrs.variant, "Verify"); + + String computed = computeValue(pan, attrs, key, length); + if (!computed.equals(validationData)) { + throw verificationFailed("the validation data did not verify", + "INVALID_VALIDATION_DATA"); + } + Map out = new LinkedHashMap<>(); + out.put("KeyArn", key.getArn()); + out.put("KeyCheckValue", key.getKeyCheckValue()); + return out; + } + + // ---- the parts ----------------------------------------------------------- + + /** + * The value for the variant, under the given key. + * + *

A request the derivation cannot read is refused with the error the model names, + * rather than answered with a failure the caller cannot catch. + */ + private static String computeValue(String pan, CardAttrs attrs, PaymentCryptographyKey key, + int length) { + try { + return compute(pan, attrs, key, length); + } catch (RuntimeException e) { + throw validation("Unable to compute the card validation value: " + e.getMessage()); + } + } + + /** The value for the variant, under the given key. */ + private static String compute(String pan, CardAttrs attrs, PaymentCryptographyKey key, + int length) { + if ("DynamicCardVerificationValue".equals(attrs.variant)) { + return CvvCrypto.computeDynamicValue(pan, attrs.expiry, attrs.serviceCode, + attrs.applicationTransactionCounter, + PaymentCryptographyKeyRules.materialHex(key), + attrs.panSequenceNumber, length); + } + return CvvCrypto.computeCvv(pan, attrs.expiry, attrs.serviceCode, + PaymentCryptographyKeyRules.materialHex(key), length); + } + + /** + * The key the variant needs, checked against the service's rules. + * + *

Getting this wrong is the usual reason a call against the real service is rejected, so + * it is checked here rather than left to the cipher. + */ + private static void requireKeyForVariant(PaymentCryptographyKey key, String variant, String mode) { + if ("DynamicCardVerificationValue".equals(variant)) { + PaymentCryptographyKeyRules.requireUsage(key, + List.of("TR31_E6_EMV_MKEY_OTHER"), "deriving a dynamic card verification value"); + PaymentCryptographyKeyRules.requireAlgorithm(key, "TDES_2KEY", + "deriving a dynamic card verification value"); + PaymentCryptographyKeyRules.requireDerive(key, "deriving a dynamic card verification value"); + return; + } + // The static values use the card verification key. + PaymentCryptographyKeyRules.requireUsage(key, + List.of("TR31_C0_CARD_VERIFICATION_KEY"), "computing a card verification value"); + PaymentCryptographyKeyRules.requireAlgorithm(key, "TDES_2KEY", + "computing a card verification value"); + PaymentCryptographyKeyRules.requireMode(key, mode, "Generate".equals(mode) + ? "generating a card verification value" + : "verifying a card verification value"); + } + + /** + * The card validation attributes of a request. + * + *

The attributes are a union, and exactly one variant of it may be given. + */ + private static CardAttrs resolveCardAttrs(JsonNode attributes) { + String variant = soleVariant(attributes); + if (variant == null) { + throw validation("attributes must specify exactly one variant"); + } + switch (variant) { + case "CardVerificationValue1": { + JsonNode value = attributes.get(variant); + String expiry = text(value, "CardExpiryDate"); + String serviceCode = text(value, "ServiceCode"); + CardAttrs out = new CardAttrs(); + out.variant = variant; + out.expiry = expiry; + out.serviceCode = serviceCode; + return out; + } + case "CardVerificationValue2": { + JsonNode value = attributes.get(variant); + String expiry = text(value, "CardExpiryDate"); + CardAttrs out = new CardAttrs(); + out.variant = variant; + out.expiry = expiry; + out.serviceCode = CVV2_SERVICE_CODE; + return out; + } + case "DynamicCardVerificationValue": { + JsonNode value = attributes.get(variant); + String expiry = text(value, "CardExpiryDate"); + String serviceCode = text(value, "ServiceCode"); + String psn = text(value, "PanSequenceNumber"); + String atc = PaymentCryptographyAttributes.hex( + variant + ".ApplicationTransactionCounter", + text(value, "ApplicationTransactionCounter")); + CardAttrs out = new CardAttrs(); + out.variant = variant; + out.expiry = expiry; + out.serviceCode = serviceCode; + out.panSequenceNumber = psn; + out.applicationTransactionCounter = atc; + return out; + } + case "DynamicCardVerificationCode": { + // Refused rather than approximated: the dynamic code is a Mastercard + // proprietary construction, and there is nothing published to check a + // derivation against. + throw validation("the dynamic card verification code is not implemented: it is a " + + "Mastercard proprietary construction and it is not approximated"); + } + default: + throw validation(variant + " not supported by this service " + + "(only CardVerificationValue1/CardVerificationValue2" + + "/DynamicCardVerificationValue/DynamicCardVerificationCode)"); + } + } + + 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; + } + + /** + * Checks that the key has the mode of use the operation needs. + */ + private static AwsException validation(String message) { + return new AwsException("ValidationException", message, 400); + } + + private static AwsException verificationFailed(String message, String reason) { + return new AwsException("VerificationFailedException", message, 400, Map.of("Reason", reason)); + } +} 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 eb62ea9721..4e0505eed9 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoHandler.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoHandler.java @@ -86,6 +86,7 @@ public class PaymentCryptographyCryptoHandler { public Map encryptData(JsonNode request, String region) { // The request is checked against the constraints the model states for it. PaymentCryptographyDataRequestShapes.check("EncryptData", request); + PaymentCryptographyAttributes.refuseWrappedKey(request, "WrappedKey"); PaymentCryptographyKey key = requiredKey(request, region, "KeyIdentifier"); requireMode(key, "Encrypt", "encrypt"); Encryption encryption = encryptionAttributes(request.get("EncryptionAttributes")); @@ -104,6 +105,7 @@ public class PaymentCryptographyCryptoHandler { public Map decryptData(JsonNode request, String region) { // The request is checked against the constraints the model states for it. PaymentCryptographyDataRequestShapes.check("DecryptData", request); + PaymentCryptographyAttributes.refuseWrappedKey(request, "WrappedKey"); PaymentCryptographyKey key = requiredKey(request, region, "KeyIdentifier"); requireMode(key, "Decrypt", "decrypt"); Encryption encryption = encryptionAttributes(request.get("DecryptionAttributes")); @@ -122,6 +124,8 @@ public class PaymentCryptographyCryptoHandler { public Map reEncryptData(JsonNode request, String region) { // The request is checked against the constraints the model states for it. PaymentCryptographyDataRequestShapes.check("ReEncryptData", request); + PaymentCryptographyAttributes.refuseWrappedKey(request, "IncomingWrappedKey"); + PaymentCryptographyAttributes.refuseWrappedKey(request, "OutgoingWrappedKey"); PaymentCryptographyKey incoming = requiredKey(request, region, "IncomingKeyIdentifier"); requireMode(incoming, "Decrypt", "decrypt"); PaymentCryptographyKey outgoing = requiredKey(request, region, "OutgoingKeyIdentifier"); 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 a1943a6bd8..64c7791d1e 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyRules.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyRules.java @@ -107,6 +107,46 @@ final class PaymentCryptographyKeyRules { } } + /** + * The algorithm a key has to have for an operation. + * + *

The algorithm is what the cipher runs, so the operation names the one it is + * defined over: a Triple DES key and an AES key are different ciphers, and so are + * the two Triple DES forms. + * + * @param key the key the operation runs under + * @param algorithm the algorithm the operation needs + * @param what the operation, for the message + */ + static void requireAlgorithm(PaymentCryptographyKey key, String algorithm, String what) { + if (!algorithm.equals(key.getKeyAlgorithm())) { + throw new AwsException("ValidationException", + "the key " + key.getArn() + " is a " + key.getKeyAlgorithm() + " key, and " + + what + " needs a " + algorithm + " one", 400); + } + } + + /** + * The mode of use a key has to have to derive from it. + * + *

A derivation reads the key, so the key has to allow it. A key with no modes + * of use allows nothing, and is refused here rather than read. + * + * @param key the key the operation runs under + * @param what the operation, for the message + */ + static void requireDerive(PaymentCryptographyKey key, String what) { + Map modes = key.getKeyModesOfUse(); + boolean derives = modes != null + && (Boolean.TRUE.equals(modes.get("DeriveKey")) + || Boolean.TRUE.equals(modes.get("NoRestrictions"))); + if (!derives) { + throw new AwsException("ValidationException", + "the key " + key.getArn() + " does not have the mode of use DeriveKey, " + + "which it needs to " + what, 400); + } + } + /** * The material of a key. * 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 a2dfa26796..049450d8fc 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyPinOperations.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyPinOperations.java @@ -504,9 +504,7 @@ public class PaymentCryptographyPinOperations { * carries one is refused rather than answered as if the key were a fixed one. */ private static void refuseWrappedKey(JsonNode request, String member) { - if (request.get(member) != null) { - throw validation(member + " is not supported by this service"); - } + PaymentCryptographyAttributes.refuseWrappedKey(request, member); } private static PinBlockFormat format(String wireName) { diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Ciphers.java b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Ciphers.java index 9c7ae7c76c..374ee9c352 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Ciphers.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Ciphers.java @@ -137,6 +137,17 @@ public final class Ciphers { return block(new DESEngine(), true, block8, key8); } + /** + * The Single DES decryption of a block under a key, in ECB mode. + * + * @param block8 the eight-byte block to decrypt + * @param key8 the eight-byte key + * @return the decrypted block + */ + public static byte[] tdesSingleDesDecrypt(byte[] block8, byte[] key8) { + return block(new DESEngine(), false, block8, key8); + } + /** * The Triple DES encryption of data under a two-key key, in CBC mode. * diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/CvvCrypto.java b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/CvvCrypto.java new file mode 100644 index 0000000000..6ff311eba0 --- /dev/null +++ b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/CvvCrypto.java @@ -0,0 +1,119 @@ +package io.floci.aws.services.paymentcryptography.crypto; + +import java.util.HexFormat; + +/** + * Visa CVV / Mastercard CVC - the standard X9 card-verification algorithm. + * + *

One routine serves CVV1, CVV2 (service code 000) and iCVV (service code + * 999); only the inputs differ. + * + *

+ *   data = (PAN || expiry || serviceCode), right-padded with '0' to 32 hex
+ *   B1, B2 = the two 8-byte blocks
+ *   r   = 3DES_EDE(CVK, DES_e(B1, CVK-A) XOR B2)      with CVK = CVK-A || CVK-B
+ *   value = decimalize(r, 3)
+ * 
+ */ +public final class CvvCrypto { + + /** The hexadecimal the data plane's blobs are written in. */ + private static final HexFormat HEX = HexFormat.of().withUpperCase(); + + private CvvCrypto() { + } + + /** Compute the 3-digit card verification value. {@code cvkHex} is CVK-A || CVK-B. */ + public static String computeCvv(String pan, String expiryYYMM, String serviceCode, + String cvkHex, int length) { + byte[] cvk = HEX.parseHex(cvkHex); + if (cvk.length != 16) { + throw new IllegalArgumentException("CVK must be 16 bytes (32 hex)"); + } + return decimalize(PinCrypto.digits(pan) + PinCrypto.digits(expiryYYMM) + + PinCrypto.digits(serviceCode), cvk, length); + } + + /** + * The dynamic card verification value (dCVV). + * + *

Visa's construction: the leftmost four digits of the account number are replaced by + * the transaction counter, and the result, the expiry and the service code are + * enciphered under the card's unique derived key. The three leftmost decimal digits of + * the result are the value. + * + *

+     *   altered PAN = the leftmost four digits of the PAN replaced by the counter
+     *   r   = 3DES_EDE(UDK, DES_e(B1, UDK-A) XOR B2)  over altered PAN || expiry || service code
+     *   value = decimalize(r, 3)
+     * 
+ * + *

The key is the unique derived key the card is personalised with, which the issuer + * derives from the master key with the account number and the PAN sequence number. The + * counter diversifies the value by the data it is inserted into, not by the key. + */ + public static String computeDynamicValue(String pan, String expiryYYMM, String serviceCode, + String atcHex, String emkHex, String psn, + int length) { + byte[] udk = EmvCrypto.deriveIccMasterKey(HEX.parseHex(emkHex), pan, psn); + return decimalize(alteredPan(pan, atcHex) + PinCrypto.digits(expiryYYMM) + + PinCrypto.digits(serviceCode), udk, length); + } + + /** + * The account number with its leftmost four digits replaced by the transaction counter. + * + *

The counter is a binary coded decimal counter, so its digits are the four decimal + * digits of its bytes, and only the rightmost four of them are inserted. + */ + private static String alteredPan(String pan, String atcHex) { + String digits = PinCrypto.digits(pan); + String counter = atcHex; + if (counter.length() > 4) { + counter = counter.substring(counter.length() - 4); + } + StringBuilder altered = new StringBuilder(counter.length() + digits.length()); + for (int i = 0; i < counter.length(); i++) { + char c = counter.charAt(i); + if (c < '0' || c > '9') { + throw new IllegalArgumentException( + "the transaction counter must be a binary coded decimal counter"); + } + altered.append(c); + } + while (altered.length() < 4) { + altered.insert(0, '0'); + } + return altered.append(digits.substring(4)).toString(); + } + + /** + * The card verification cipher: two blocks, the left one enciphered with + * the key's left half, exclusive-or the right one, then enciphered again + * with the whole key. + * + * @param input hexadecimal input, at most 32 characters, zero-padded + */ + private static String decimalize(String input, byte[] key, int length) { + if (input.length() > 32) { + throw new IllegalArgumentException("the input exceeds two blocks"); + } + StringBuilder padded = new StringBuilder(); + padded.append(input); + while (padded.length() < 32) { + padded.append('0'); + } + String p = padded.substring(0, 32); + byte[] b1 = HEX.parseHex(p.substring(0, 16)); + byte[] b2 = HEX.parseHex(p.substring(16, 32)); + + byte[] r = Ciphers.tdes2Encrypt(Ciphers.xor(Ciphers.tdesSingleDesEncrypt(b1, slice(key, 0, 8)), b2), key); + return Decimalize.of(HEX.formatHex(r), length); + } + + private static byte[] slice(byte[] b, int from, int to) { + byte[] out = new byte[to - from]; + System.arraycopy(b, from, out, 0, to - from); + return out; + } +} diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/EmvCrypto.java b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/EmvCrypto.java new file mode 100644 index 0000000000..a34baf1bef --- /dev/null +++ b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/EmvCrypto.java @@ -0,0 +1,348 @@ +package io.floci.aws.services.paymentcryptography.crypto; + +import io.floci.aws.core.common.Digests; + +import java.util.HexFormat; + +/** + * The canonical EMV ARQC/ARPC spine, and the primitives it rests on. + * + *

+ *   1. ICC master key derivation (EMV Book 2, Option A)   IMK + PAN + PSN -> MK
+ *   2. Common session key derivation (EMV Book 2 A1.3.1)  MK  + ATC       -> SK
+ *   3. ARQC = ISO 9797-1 MAC algorithm 3 over the transaction data, truncated to 8 bytes
+ *   4. ARPC method 1 = 3DES_EDE(SK, ARQC XOR (ARC || 00*6))
+ * 
+ * + *

The transaction data reaches the service already padded, because the caller pads it + * the way the card padded it before the card enciphered it. The service enciphers it as + * it was sent, and the padding the service applies is the one it applies to the input it + * builds itself, which is the issuer authentication cryptogram. + * + *

All DES is done through three-key TDES rather than a single-DES provider: + * single DES is expressed as TDES with K||K||K. + * + *

The full PAN flows into master key derivation, because the derivation is + * defined over the whole of it. + */ +public final class EmvCrypto { + + /** The hexadecimal the data plane's blobs are written in. */ + private static final HexFormat HEX = HexFormat.of().withUpperCase(); + + private EmvCrypto() { + } + + // ---- primitives --------------------------------------------------------- + + /** Force every DES key byte to odd parity. */ + public static byte[] adjustDesParity(byte[] key) { + byte[] out = new byte[key.length]; + for (int i = 0; i < key.length; i++) { + int b = key[i] & 0xff; + int p = 0; + // The parity bit is bit 0; XOR bits 1..7, then force the byte odd. + for (int bit = 1; bit < 8; bit++) { + p ^= (b >> bit) & 1; + } + out[i] = (byte) ((b & 0xfe) | ((p ^ 0x01) & 0x01)); + } + return out; + } + + /** + * The ISO 9797-1 padding method used for an application cryptogram. + * + *

The transaction data reaches the service already padded: the user guide tells + * the caller to pad it before sending it, because the card padded it the same way + * before it enciphered it. The service therefore enciphers the data as it was + * given, and padding it again would encipher a block the card never enciphered. + */ + public enum Padding { + /** + * No padding: the data is enciphered exactly as it was given. + */ + NONE, + /** + * Method 2: append {@code 0x80}, then zeros to the next boundary, + * always adding a block even when the data is already aligned. The input of + * an issuer authentication cryptogram is built here rather than by the + * caller, so it is this one that is padded. + */ + METHOD2 + } + + /** Pad according to the given method. */ + public static byte[] pad(byte[] data, Padding padding) { + return switch (padding) { + case NONE -> data; + case METHOD2 -> pad80(data); + }; + } + + /** + * ISO/IEC 9797-1 padding method 2: append {@code 0x80}, then zeros to the + * next 8-byte boundary. Always pads a block, so a block-aligned input gains + * a whole extra block. + */ + public static byte[] pad80(byte[] data) { + int total = data.length - (data.length % 8) + 8; + byte[] out = new byte[total]; + System.arraycopy(data, 0, out, 0, data.length); + out[data.length] = (byte) 0x80; + return out; + } + + /** + * ISO/IEC 9797-1 MAC algorithm 3 (the retail MAC) with a 16-byte key. + * + *

This is single-DES chaining, not three-key TDES. The key splits into + * K1 (left 8) and K2 (right 8); each block is enciphered under K1, and a + * single D_KR then E_KL final transform closes the tag: + * + *

+     *   H_i  = E_KL(D_i XOR H_{i-1})   for i = 1..n
+     *   MAC  = E_KL(D_KR(H_n))
+     * 
+ * + *

Running a 3DES transform per block instead - the obvious reading - + * produces a different MAC. + */ + /** The retail MAC over data padded with the given ISO 9797-1 method. */ + public static byte[] retailMac(byte[] key16, byte[] data, Padding padding) { + byte[] kl = slice(key16, 0, 8); + byte[] kr = slice(key16, 8, 16); + byte[] padded = pad(data, padding); + int nBlocks = padded.length / 8; + byte[] h = new byte[8]; + for (int i = 0; i < nBlocks; i++) { + h = Ciphers.tdesSingleDesEncrypt(Ciphers.xor(h, slice(padded, i * 8, i * 8 + 8)), kl); + } + return Ciphers.tdesSingleDesEncrypt(Ciphers.tdesSingleDesDecrypt(h, kr), kl); + } + + // ---- EMV key derivation ------------------------------------------------- + + /** + * EMV Book 2 Option A ICC master key derivation. + * + *

+     *   Y  = the RIGHT-MOST 16 digits of PAN || PSN, left-padded with zeros when shorter
+     *   ZR = Y XOR FF..FF
+     *   MK = 3DES(IMK, Y) || 3DES(IMK, ZR), odd parity adjusted
+     * 
+ * + *

Y is the last sixteen digits, not the first. For a 16-digit PAN the two differ, + * and using the first changes the master key and every tag that follows. The rule is the + * one EMV 4.4 Book 2 Annex A1.4.1 gives, and the Visa Integrated Circuit Card + * Specification states it the same way: the rightmost sixteen digits of the PAN and the + * sequence number, padded on the left with zeros when they are shorter. + */ + public static byte[] deriveIccMasterKey(byte[] imk16, String pan, String psn) { + byte[] y = masterKeyInput(pan, psn); + byte[] zr = new byte[8]; + for (int i = 0; i < 8; i++) { + zr[i] = (byte) (y[i] ^ 0xff); + } + return adjustDesParity(concat( + Ciphers.tdes2Encrypt(y, imk16), + Ciphers.tdes2Encrypt(zr, imk16))); + } + + /** + * EMV Book 2 Option B master key derivation, for PANs longer than 16 digits. + * + *

+     *   H  = SHA-1(PAN || PSN as packed BCD)
+     *   Y  = the leftmost 16 digits of {H's decimal digits || H's other nibbles mod 10}
+     *   MK = 3DES(IMK, Y) || 3DES(IMK, Y XOR FF..FF)
+     * 
+ * + *

The decimal digits of the hash come first, in the order they appear, and the + * nibbles that are not decimal digits follow them, each reduced modulo ten. A hash + * of a packed account number and sequence number holds sixteen decimal digits + * almost every time, so the second part is rarely reached. + * + *

A PAN of sixteen digits or fewer is derived the Option A way: the hash is + * only there for the longer numbers. + */ + public static byte[] deriveIccMasterKeyOptionB(byte[] imk16, String pan, String psn) { + if (PinCrypto.digits(pan).length() <= 16) { + return deriveIccMasterKey(imk16, pan, psn); + } + byte[] b = packedBcd(pan, psn); + String hash = HEX.formatHex(Digests.sha1(b)); + StringBuilder decimal = new StringBuilder(hash.length()); + StringBuilder other = new StringBuilder(hash.length()); + for (int i = 0; i < hash.length(); i++) { + char c = hash.charAt(i); + if (c >= '0' && c <= '9') { + decimal.append(c); + } else { + other.append((char) ('0' + (c - 'A'))); + } + } + StringBuilder y = new StringBuilder(decimal).append(other); + if (y.length() < 16) { + throw new IllegalArgumentException("Option B: the SHA-1 hash yields fewer than 16 digits"); + } + byte[] zl = HEX.parseHex(y.substring(0, 16)); + byte[] zr = new byte[8]; + for (int i = 0; i < 8; i++) { + zr[i] = (byte) (zl[i] ^ 0xff); + } + return adjustDesParity(concat( + Ciphers.tdes2Encrypt(zl, imk16), + Ciphers.tdes2Encrypt(zr, imk16))); + } + + /** + * The EMV common session key (EMV 4.2 Book 2 Annex A1.3.1). + * + *

+     *   F1 = ATC(2) || F0 || 00*5     SK_L = 3DES(MK, F1)
+     *   F2 = ATC(2) || 0F || 00*5     SK_R = 3DES(MK, F2)
+     * 
+ * + *

Each half carries odd DES parity. + */ + public static byte[] deriveSessionKey(byte[] mk16, byte[] atc) { + byte[] r = new byte[8]; + System.arraycopy(atc, 0, r, 0, Math.min(2, atc.length)); + return sessionKeyFromDiversifier(mk16, r); + } + + /** + * The MasterCard proprietary session key derivation (M/Chip). + * + *

Identical to the EMV common session key except for the 8-byte + * diversification input, which here is the low two bytes of the application + * transaction counter followed by the low four bytes of the terminal's + * unpredictable number, rather than the counter followed by zeros. + * + *

Both halves still carry odd DES parity, as the MasterCard method + * requires. + * + * @param unpredictableNumber the terminal-generated unpredictable number; its + * low four bytes are used + */ + public static byte[] deriveSessionKeyMastercard(byte[] mk16, byte[] atc, + byte[] unpredictableNumber) { + byte[] r = new byte[8]; + // The LOW bytes, so an over-long counter or + // unpredictable number gives the same result on both sides. + int atcFrom = Math.max(0, atc.length - 2); + System.arraycopy(atc, atcFrom, r, 0, Math.min(2, atc.length)); + int unFrom = Math.max(0, unpredictableNumber.length - 4); + System.arraycopy(unpredictableNumber, unFrom, r, 4, Math.min(4, unpredictableNumber.length)); + return sessionKeyFromDiversifier(mk16, r); + } + + /** The shared tail of both derivations: the 0xF0/0x0F halves, enciphered, parity adjusted. */ + private static byte[] sessionKeyFromDiversifier(byte[] mk16, byte[] r) { + byte[] f1 = r.clone(); + f1[2] = (byte) 0xf0; + byte[] f2 = r.clone(); + f2[2] = (byte) 0x0f; + return adjustDesParity(concat( + Ciphers.tdes2Encrypt(f1, mk16), + Ciphers.tdes2Encrypt(f2, mk16))); + } + + // ---- cryptograms -------------------------------------------------------- + + /** An ARQC together with the session key it was computed under. */ + public static final class Arqc { + public final byte[] arqc; + public final byte[] sessionKey; + + public Arqc(byte[] arqc, byte[] sessionKey) { + this.arqc = arqc; + this.sessionKey = sessionKey; + } + } + + /** + * ARPC method 1: {@code 3DES_EDE(SK, ARQC XOR (ARC || 00*6))}. + * + * @param arcHex the authorization response code, right-padded to 8 bytes + */ + public static byte[] computeArpcMethod1(byte[] sk, byte[] arqc, String arcHex) { + byte[] arc = HEX.parseHex(arcHex); + byte[] x = new byte[8]; + System.arraycopy(arc, 0, x, 0, Math.min(8, arc.length)); + return Ciphers.tdes2Encrypt(Ciphers.xor(arqc, x), sk); + } + + /** + * ARPC method 2, the CSU-based one: the leftmost 4 bytes of the retail MAC + * over {@code ARQC || CSU || proprietary} under the session key. + * + *

The response code belongs in the input of the first method. The second + * method has none: the card status update and the proprietary data are what + * it is made from, and EMV Book 2 section 8.2.2 says so. + * + *

The request carries no way to ask for the other form: the model gives + * the card status update and the proprietary data, and nothing else. + */ + public static byte[] computeArpcMethod2(byte[] sk, byte[] arqc, + String csuHex, String padHex) { + byte[] data = concat( + arqc, + csuHex == null ? new byte[0] : HEX.parseHex(csuHex), + padHex == null ? new byte[0] : HEX.parseHex(padHex)); + return slice(retailMac(sk, data, Padding.METHOD2), 0, 4); + } + + // ---- helpers ------------------------------------------------------------ + + /** PAN concatenated with PSN as packed BCD, left-zero-padded to an even nibble count. */ + static byte[] packedBcd(String pan, String psn) { + String digits = PinCrypto.digits(pan) + PinCrypto.digits(psn == null ? "00" : psn); + if (digits.isEmpty()) { + throw new IllegalArgumentException("PAN and PSN must contain digits"); + } + if (digits.length() % 2 != 0) { + digits = "0" + digits; + } + return HEX.parseHex(digits); + } + + /** + * The block the ICC master key is derived over: the rightmost sixteen digits of the PAN + * and the PAN sequence number, padded on the left with zeros when they are shorter. + */ + private static byte[] masterKeyInput(String pan, String psn) { + String digits = PinCrypto.digits(pan) + PinCrypto.digits(psn == null ? "00" : psn); + if (digits.isEmpty()) { + throw new IllegalArgumentException("PAN and PSN must contain digits"); + } + if (digits.length() > 16) { + digits = digits.substring(digits.length() - 16); + } + while (digits.length() < 16) { + digits = "0" + digits; + } + return HEX.parseHex(digits); + } + + private static byte[] slice(byte[] b, int from, int to) { + byte[] out = new byte[to - from]; + System.arraycopy(b, from, out, 0, to - from); + return out; + } + + private static byte[] concat(byte[]... parts) { + int n = 0; + for (byte[] p : parts) { + n += p.length; + } + byte[] out = new byte[n]; + int at = 0; + for (byte[] p : parts) { + System.arraycopy(p, 0, out, at, p.length); + at += p.length; + } + return out; + } +} diff --git a/src/main/resources/aws/payment-cryptography-data-request-shapes.json b/src/main/resources/aws/payment-cryptography-data-request-shapes.json index da514ff260..458680d7f9 100644 --- a/src/main/resources/aws/payment-cryptography-data-request-shapes.json +++ b/src/main/resources/aws/payment-cryptography-data-request-shapes.json @@ -12,7 +12,11 @@ "GeneratePinData": "GeneratePinDataInput", "VerifyPinData": "VerifyPinDataInput", "TranslatePinData": "TranslatePinDataInput", - "GenerateMacEmvPinChange": "GenerateMacEmvPinChangeInput" + "GenerateMacEmvPinChange": "GenerateMacEmvPinChangeInput", + "GenerateCardValidationData": "GenerateCardValidationDataInput", + "VerifyCardValidationData": "VerifyCardValidationDataInput", + "GenerateAuthRequestCryptogram": "GenerateAuthRequestCryptogramInput", + "VerifyAuthRequestCryptogram": "VerifyAuthRequestCryptogramInput" }, "shapes": { "AmexAttributes": { @@ -33,6 +37,26 @@ "CurrentPinAttributes": "CurrentPinAttributes" } }, + "AmexCardSecurityCodeVersion1": { + "type": "structure", + "required": [ + "CardExpiryDate" + ], + "members": { + "CardExpiryDate": "CardExpiryDateType" + } + }, + "AmexCardSecurityCodeVersion2": { + "type": "structure", + "required": [ + "CardExpiryDate", + "ServiceCode" + ], + "members": { + "CardExpiryDate": "CardExpiryDateType", + "ServiceCode": "ServiceCodeType" + } + }, "ApplicationCryptogramType": { "type": "string", "min": 16, @@ -56,6 +80,76 @@ "PaddingType": "PaddingType" } }, + "AuthRequestCryptogramType": { + "type": "string", + "min": 16, + "max": 16, + "pattern": "[0-9a-fA-F]+" + }, + "CardExpiryDateType": { + "type": "string", + "min": 4, + "max": 4, + "pattern": "[0-9]+" + }, + "CardGenerationAttributes": { + "type": "structure", + "members": { + "AmexCardSecurityCodeVersion1": "AmexCardSecurityCodeVersion1", + "AmexCardSecurityCodeVersion2": "AmexCardSecurityCodeVersion2", + "CardVerificationValue1": "CardVerificationValue1", + "CardVerificationValue2": "CardVerificationValue2", + "CardHolderVerificationValue": "CardHolderVerificationValue", + "DynamicCardVerificationCode": "DynamicCardVerificationCode", + "DynamicCardVerificationValue": "DynamicCardVerificationValue" + } + }, + "CardHolderVerificationValue": { + "type": "structure", + "required": [ + "UnpredictableNumber", + "PanSequenceNumber", + "ApplicationTransactionCounter" + ], + "members": { + "UnpredictableNumber": "HexLengthBetween2And8", + "PanSequenceNumber": "NumberLengthEquals2", + "ApplicationTransactionCounter": "HexLengthBetween2And4" + } + }, + "CardVerificationAttributes": { + "type": "structure", + "members": { + "AmexCardSecurityCodeVersion1": "AmexCardSecurityCodeVersion1", + "AmexCardSecurityCodeVersion2": "AmexCardSecurityCodeVersion2", + "CardVerificationValue1": "CardVerificationValue1", + "CardVerificationValue2": "CardVerificationValue2", + "CardHolderVerificationValue": "CardHolderVerificationValue", + "DynamicCardVerificationCode": "DynamicCardVerificationCode", + "DynamicCardVerificationValue": "DynamicCardVerificationValue", + "DiscoverDynamicCardVerificationCode": "DiscoverDynamicCardVerificationCode" + } + }, + "CardVerificationValue1": { + "type": "structure", + "required": [ + "CardExpiryDate", + "ServiceCode" + ], + "members": { + "CardExpiryDate": "CardExpiryDateType", + "ServiceCode": "ServiceCodeType" + } + }, + "CardVerificationValue2": { + "type": "structure", + "required": [ + "CardExpiryDate" + ], + "members": { + "CardExpiryDate": "CardExpiryDateType" + } + }, "CertificateType": { "type": "string", "min": 1, @@ -74,6 +168,32 @@ "max": 1024, "pattern": "(?:[0-9a-fA-F][0-9a-fA-F])+" }, + "CryptogramAuthResponse": { + "type": "structure", + "members": { + "ArpcMethod1": "CryptogramVerificationArpcMethod1", + "ArpcMethod2": "CryptogramVerificationArpcMethod2" + } + }, + "CryptogramVerificationArpcMethod1": { + "type": "structure", + "required": [ + "AuthResponseCode" + ], + "members": { + "AuthResponseCode": "HexLengthEquals4" + } + }, + "CryptogramVerificationArpcMethod2": { + "type": "structure", + "required": [ + "CardStatusUpdate" + ], + "members": { + "CardStatusUpdate": "HexLengthEquals8", + "ProprietaryAuthenticationData": "ProprietaryAuthenticationDataType" + } + }, "CurrentPinAttributes": { "type": "structure", "required": [ @@ -115,6 +235,19 @@ "Mastercard": "MasterCardAttributes" } }, + "DiscoverDynamicCardVerificationCode": { + "type": "structure", + "required": [ + "CardExpiryDate", + "UnpredictableNumber", + "ApplicationTransactionCounter" + ], + "members": { + "CardExpiryDate": "CardExpiryDateType", + "UnpredictableNumber": "HexLengthBetween2And8", + "ApplicationTransactionCounter": "HexLengthBetween2And4" + } + }, "DukptAttributes": { "type": "structure", "required": [ @@ -175,6 +308,36 @@ "RESPONSE" ] }, + "DynamicCardVerificationCode": { + "type": "structure", + "required": [ + "UnpredictableNumber", + "PanSequenceNumber", + "ApplicationTransactionCounter", + "TrackData" + ], + "members": { + "UnpredictableNumber": "HexLengthBetween2And8", + "PanSequenceNumber": "NumberLengthEquals2", + "ApplicationTransactionCounter": "HexLengthBetween2And4", + "TrackData": "TrackDataType" + } + }, + "DynamicCardVerificationValue": { + "type": "structure", + "required": [ + "PanSequenceNumber", + "CardExpiryDate", + "ServiceCode", + "ApplicationTransactionCounter" + ], + "members": { + "PanSequenceNumber": "NumberLengthEquals2", + "CardExpiryDate": "CardExpiryDateType", + "ServiceCode": "ServiceCodeType", + "ApplicationTransactionCounter": "HexLengthBetween2And4" + } + }, "EcdhDerivationAttributes": { "type": "structure", "required": [ @@ -303,6 +466,35 @@ "OFB" ] }, + "GenerateAuthRequestCryptogramInput": { + "type": "structure", + "required": [ + "KeyIdentifier", + "TransactionData", + "MajorKeyDerivationMode", + "SessionKeyDerivationAttributes" + ], + "members": { + "KeyIdentifier": "KeyArnOrKeyAliasType", + "TransactionData": "TransactionDataType", + "MajorKeyDerivationMode": "MajorKeyDerivationMode", + "SessionKeyDerivationAttributes": "SessionKeyDerivation" + } + }, + "GenerateCardValidationDataInput": { + "type": "structure", + "required": [ + "KeyIdentifier", + "PrimaryAccountNumber", + "GenerationAttributes" + ], + "members": { + "KeyIdentifier": "KeyArnOrKeyAliasType", + "PrimaryAccountNumber": "PrimaryAccountNumberType", + "GenerationAttributes": "CardGenerationAttributes", + "ValidationDataLength": "IntegerRangeBetween3And5Type" + } + }, "GenerateMacEmvPinChangeInput": { "type": "structure", "required": [ @@ -368,6 +560,18 @@ "max": 24, "pattern": "(?:[0-9a-fA-F]{16}|[0-9a-fA-F]{20}|[0-9a-fA-F]{24})" }, + "HexLengthBetween2And4": { + "type": "string", + "min": 2, + "max": 4, + "pattern": "[0-9a-fA-F]+" + }, + "HexLengthBetween2And8": { + "type": "string", + "min": 2, + "max": 8, + "pattern": "[0-9a-fA-F]+" + }, "HexLengthEquals1": { "type": "string", "min": 1, @@ -380,6 +584,12 @@ "max": 4, "pattern": "[0-9a-fA-F]+" }, + "HexLengthEquals8": { + "type": "string", + "min": 8, + "max": 8, + "pattern": "[0-9a-fA-F]+" + }, "Ibm3624NaturalPin": { "type": "structure", "required": [ @@ -462,6 +672,11 @@ "min": 0, "max": 6 }, + "IntegerRangeBetween3And5Type": { + "type": "integer", + "min": 3, + "max": 5 + }, "IntegerRangeBetween4And12": { "type": "integer", "min": 4, @@ -683,6 +898,12 @@ "max": 19, "pattern": "[0-9]+" }, + "ProprietaryAuthenticationDataType": { + "type": "string", + "min": 1, + "max": 16, + "pattern": "[0-9a-fA-F]+" + }, "ReEncryptDataInput": { "type": "structure", "required": [ @@ -710,12 +931,40 @@ "Dukpt": "DukptEncryptionAttributes" } }, + "ServiceCodeType": { + "type": "string", + "min": 3, + "max": 3, + "pattern": "[0-9]+" + }, "SessionDerivationDataType": { "type": "string", "min": 16, "max": 16, "pattern": "[0-9a-fA-F]+" }, + "SessionKeyAmex": { + "type": "structure", + "required": [ + "PrimaryAccountNumber", + "PanSequenceNumber" + ], + "members": { + "PrimaryAccountNumber": "PrimaryAccountNumberType", + "PanSequenceNumber": "NumberLengthEquals2" + } + }, + "SessionKeyDerivation": { + "type": "structure", + "members": { + "EmvCommon": "SessionKeyEmvCommon", + "Mastercard": "SessionKeyMastercard", + "Emv2000": "SessionKeyEmv2000", + "Amex": "SessionKeyAmex", + "Visa": "SessionKeyVisa", + "UnionPay": "SessionKeyUnionPay" + } + }, "SessionKeyDerivationMode": { "type": "string", "enum": [ @@ -734,6 +983,71 @@ "ApplicationTransactionCounter": "HexLengthEquals4" } }, + "SessionKeyEmv2000": { + "type": "structure", + "required": [ + "PrimaryAccountNumber", + "PanSequenceNumber", + "ApplicationTransactionCounter" + ], + "members": { + "PrimaryAccountNumber": "PrimaryAccountNumberType", + "PanSequenceNumber": "NumberLengthEquals2", + "ApplicationTransactionCounter": "HexLengthEquals4" + } + }, + "SessionKeyEmvCommon": { + "type": "structure", + "required": [ + "PrimaryAccountNumber", + "PanSequenceNumber", + "ApplicationTransactionCounter" + ], + "members": { + "PrimaryAccountNumber": "PrimaryAccountNumberType", + "PanSequenceNumber": "NumberLengthEquals2", + "ApplicationTransactionCounter": "HexLengthEquals4" + } + }, + "SessionKeyMastercard": { + "type": "structure", + "required": [ + "PrimaryAccountNumber", + "PanSequenceNumber", + "ApplicationTransactionCounter", + "UnpredictableNumber" + ], + "members": { + "PrimaryAccountNumber": "PrimaryAccountNumberType", + "PanSequenceNumber": "NumberLengthEquals2", + "ApplicationTransactionCounter": "HexLengthEquals4", + "UnpredictableNumber": "HexLengthEquals8" + } + }, + "SessionKeyUnionPay": { + "type": "structure", + "required": [ + "PrimaryAccountNumber", + "PanSequenceNumber", + "ApplicationTransactionCounter" + ], + "members": { + "PrimaryAccountNumber": "PrimaryAccountNumberType", + "PanSequenceNumber": "NumberLengthEquals2", + "ApplicationTransactionCounter": "HexLengthEquals4" + } + }, + "SessionKeyVisa": { + "type": "structure", + "required": [ + "PrimaryAccountNumber", + "PanSequenceNumber" + ], + "members": { + "PrimaryAccountNumber": "PrimaryAccountNumberType", + "PanSequenceNumber": "NumberLengthEquals2" + } + }, "SharedInformation": { "type": "string", "min": 2, @@ -777,12 +1091,24 @@ "max": 9984, "pattern": "[0-9a-zA-Z]+" }, + "TrackDataType": { + "type": "string", + "min": 2, + "max": 160, + "pattern": "[0-9a-fA-F]+" + }, "TransactionAmountType": { "type": "string", "min": 12, "max": 12, "pattern": "[0-9]+" }, + "TransactionDataType": { + "type": "string", + "min": 2, + "max": 1024, + "pattern": "[0-9a-fA-F]+" + }, "TranslatePinDataInput": { "type": "structure", "required": [ @@ -837,12 +1163,51 @@ "type": "structure", "members": {} }, + "ValidationDataType": { + "type": "string", + "min": 3, + "max": 5, + "pattern": "[0-9]+" + }, "VerificationValueType": { "type": "string", "min": 4, "max": 12, "pattern": "[0-9]+" }, + "VerifyAuthRequestCryptogramInput": { + "type": "structure", + "required": [ + "KeyIdentifier", + "TransactionData", + "AuthRequestCryptogram", + "MajorKeyDerivationMode", + "SessionKeyDerivationAttributes" + ], + "members": { + "KeyIdentifier": "KeyArnOrKeyAliasType", + "TransactionData": "TransactionDataType", + "AuthRequestCryptogram": "AuthRequestCryptogramType", + "MajorKeyDerivationMode": "MajorKeyDerivationMode", + "SessionKeyDerivationAttributes": "SessionKeyDerivation", + "AuthResponseAttributes": "CryptogramAuthResponse" + } + }, + "VerifyCardValidationDataInput": { + "type": "structure", + "required": [ + "KeyIdentifier", + "PrimaryAccountNumber", + "VerificationAttributes", + "ValidationData" + ], + "members": { + "KeyIdentifier": "KeyArnOrKeyAliasType", + "PrimaryAccountNumber": "PrimaryAccountNumberType", + "VerificationAttributes": "CardVerificationAttributes", + "ValidationData": "ValidationDataType" + } + }, "VerifyMacInput": { "type": "structure", "required": [ diff --git a/src/test/java/io/floci/aws/services/iam/PaymentCryptographyDataPlaneIamRouteTest.java b/src/test/java/io/floci/aws/services/iam/PaymentCryptographyDataPlaneIamRouteTest.java index f4c8507814..2eba5b20fd 100644 --- a/src/test/java/io/floci/aws/services/iam/PaymentCryptographyDataPlaneIamRouteTest.java +++ b/src/test/java/io/floci/aws/services/iam/PaymentCryptographyDataPlaneIamRouteTest.java @@ -96,6 +96,18 @@ class PaymentCryptographyDataPlaneIamRouteTest { resolve("/_paymentcryptography/keys/" + KEY_ARN + "/encrypt")); } + @Test + void theCardOperationsResolveToTheirActions() { + assertEquals("payment-cryptography:GenerateCardValidationData", + resolve("/_paymentcryptography/cardvalidationdata/generate")); + assertEquals("payment-cryptography:VerifyCardValidationData", + resolve("/_paymentcryptography/cardvalidationdata/verify")); + assertEquals("payment-cryptography:GenerateAuthRequestCryptogram", + resolve("/_paymentcryptography/cryptogram/generate")); + assertEquals("payment-cryptography:VerifyAuthRequestCryptogram", + resolve("/_paymentcryptography/cryptogram/verify")); + } + /** The action the registry resolves for a POST to the path, for the service's scope. */ private String resolve(String path) { return resolve("payment-cryptography", path); diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperationsTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperationsTest.java new file mode 100644 index 0000000000..1bd1ac8077 --- /dev/null +++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperationsTest.java @@ -0,0 +1,485 @@ +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.crypto.EmvCrypto; +import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.HexFormat; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The authorization request cryptograms. + * + *

The derivations in the first test are the emulator's, and the emulator checks them + * against an independent implementation: the ICC master key, the session key that + * comes from it, and the ARQC of a + * transaction. + */ +class PaymentCryptographyAuthCryptogramOperationsTest { + + /** The hexadecimal the data plane's blobs are written in. */ + private static final HexFormat HEX = HexFormat.of().withUpperCase(); + + private static final String IMK = "0123456789ABCDEFFEDCBA9876543210"; + private static final String PAN = "4111111111111111"; + /** The PAN sequence number, which the model states is two digits. */ + private static final String PSN = "01"; + /** The application transaction counter, which the model states is two bytes. */ + private static final String ATC = "0001"; + /** + * The transaction data the cryptogram is computed over. + * + *

The user guide tells the caller to pad the transaction data before sending + * it, because the card padded it the same way before it enciphered it. The + * data here is padded that way: a whole number of eight-byte blocks, with the + * {@code 80} and the zeros that method 2 appends. + */ + /** + * Another transaction's data, of the same shape as the one above. + * + *

The amount differs, so the cryptogram over it differs, and the data is still + * a whole number of eight-byte blocks. + */ + private static final String ANOTHER_TRANSACTION_DATA = + "00000000180000000000000008400080008000084016051700000000093800000B1F2201" + + "030000000000000000000000000000000000000000000000000000008000000000000000"; + + private static final String TRANSACTION_DATA = + "00000000170000000000000008400080008000084016051700000000093800000B1F2201" + + "030000000000000000000000000000000000000000000000000000008000000000000000"; + + private PaymentCryptographyService service; + private PaymentCryptographyAuthCryptogramOperations cryptogram; + private final ObjectMapper mapper = new ObjectMapper(); + + @BeforeEach + void setUp() { + service = new PaymentCryptographyService( + new InMemoryStorage<>(), + new InMemoryStorage<>(), + new RegionResolver("us-east-1", "000000000000")); + cryptogram = new PaymentCryptographyAuthCryptogramOperations(service); + } + + /** The session key derivation attributes of the EMV common variant. */ + /** The attributes of the EMV 4.1 tree derivation, which this service refuses. */ + private static JsonNode emv2000() { + ObjectMapper mapper = new ObjectMapper(); + ObjectNode value = mapper.createObjectNode(); + value.put("PrimaryAccountNumber", PAN); + value.put("PanSequenceNumber", PSN); + value.put("ApplicationTransactionCounter", ATC); + ObjectNode outer = mapper.createObjectNode(); + outer.set("Emv2000", value); + return outer; + } + + private static JsonNode emvCommon() { + return emvCommon(PAN); + } + + /** The session key derivation attributes of the EMV common variant, for an account number. */ + private static JsonNode emvCommon(String pan) { + ObjectMapper mapper = new ObjectMapper(); + ObjectNode value = mapper.createObjectNode(); + value.put("PrimaryAccountNumber", pan); + value.put("PanSequenceNumber", PSN); + value.put("ApplicationTransactionCounter", ATC); + ObjectNode outer = mapper.createObjectNode(); + outer.set("EmvCommon", value); + return outer; + } + + @Test + void anAccountNumberShorterThanTheFieldIsRead() { + PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey"); + + // The model lets the account number be twelve digits, and the derivation reads the + // rightmost sixteen digits of it and the sequence number, so it is read rather than + // refused. + Map generated = cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", key.getArn(), + "TransactionData", TRANSACTION_DATA, + "MajorKeyDerivationMode", "EMV_OPTION_A", + "SessionKeyDerivationAttributes", emvCommon("411111111111"))), "us-east-1"); + + assertEquals(16, ((String) generated.get("AuthRequestCryptogram")).length()); + } + + @Test + void theDerivationsAreTheOnesTheStandardGives() { + // The values are the ones the EMV derivation gives for these inputs: the master key + // from the packed PAN || PSN, and the session key from the counter and that key. The + // derivation itself is pinned to the vectors the specifications publish in + // EmvCryptoTest. + byte[] masterKey = EmvCrypto.deriveIccMasterKey(HEX.parseHex(IMK), PAN, PSN); + assertEquals("A768CE9E1551FDE3A45B4C7C3DE9DC52", HEX.formatHex(masterKey)); + // A PAN of sixteen digits or fewer is derived the Option A way, so the two agree. + assertEquals(HEX.formatHex(masterKey), + HEX.formatHex(EmvCrypto.deriveIccMasterKeyOptionB(HEX.parseHex(IMK), PAN, PSN))); + assertEquals("892FA4A7F8C8ABC7464FBF5DD63ECBD5", + HEX.formatHex(EmvCrypto.deriveSessionKey(masterKey, HEX.parseHex(ATC)))); + } + + @Test + void theLongerAccountNumberIsDerivedTheOptionBWay() { + // The hash is only there for the longer numbers, and the letters of the hash + // stand for the digits zero to five. + byte[] optionB = EmvCrypto.deriveIccMasterKeyOptionB(HEX.parseHex(IMK), + "4111111111111111111", PSN); + assertEquals(16, optionB.length); + assertNotEquals(HEX.formatHex(EmvCrypto.deriveIccMasterKey(HEX.parseHex(IMK), + "4111111111111111111", PSN)), HEX.formatHex(optionB)); + } + + @Test + void theEmv41DerivationIsRefusedRatherThanApproximated() { + PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey"); + + // Emv2000 is the EMV 4.1 tree derivation, not the common one, and the tree needs + // the card's public key certificate. + AwsException refused = assertThrows(AwsException.class, + () -> cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", key.getArn(), + "TransactionData", TRANSACTION_DATA, + "MajorKeyDerivationMode", "EMV_OPTION_A", + "SessionKeyDerivationAttributes", emv2000())), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("Emv2000"), refused.getMessage()); + } + + @Test + void aVerificationThatFailsSaysWhy() { + PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey"); + + AwsException refused = assertThrows(AwsException.class, + () -> cryptogram.verify(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", key.getArn(), + "AuthRequestCryptogram", "0000000000000000", + "TransactionData", TRANSACTION_DATA, + "MajorKeyDerivationMode", "EMV_OPTION_A", + "SessionKeyDerivationAttributes", emvCommon())), "us-east-1")); + + assertEquals("VerificationFailedException", refused.getErrorCode()); + assertEquals("INVALID_AUTH_REQUEST_CRYPTOGRAM", refused.getExtendedData().get("Reason")); + } + + @Test + void aKeyThatIsNotThereIsNotFound() { + AwsException refused = assertThrows(AwsException.class, + () -> cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", "arn:aws:payment-cryptography:us-east-1:111122223333:key/0123456789abcdef", + "TransactionData", TRANSACTION_DATA, + "MajorKeyDerivationMode", "EMV_OPTION_A", + "SessionKeyDerivationAttributes", emvCommon())), "us-east-1")); + + assertEquals("ResourceNotFoundException", refused.getErrorCode()); + assertEquals(404, refused.getHttpStatus()); + } + + @Test + void aGeneratedCryptogramVerifies() { + PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey"); + + Map generated = cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", key.getArn(), + "TransactionData", TRANSACTION_DATA, + "MajorKeyDerivationMode", "EMV_OPTION_A", + "SessionKeyDerivationAttributes", emvCommon())), "us-east-1"); + + String arqc = (String) generated.get("AuthRequestCryptogram"); + assertEquals(16, arqc.length()); + assertEquals(key.getArn(), generated.get("KeyArn")); + + Map verified = cryptogram.verify(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", key.getArn(), + "AuthRequestCryptogram", arqc, + "TransactionData", TRANSACTION_DATA, + "MajorKeyDerivationMode", "EMV_OPTION_A", + "SessionKeyDerivationAttributes", emvCommon())), "us-east-1"); + + assertEquals(key.getArn(), verified.get("KeyArn")); + } + + @Test + void aCryptogramOfAnotherTransactionIsRefused() { + PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey"); + + Map generated = cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", key.getArn(), + "TransactionData", TRANSACTION_DATA, + "MajorKeyDerivationMode", "EMV_OPTION_A", + "SessionKeyDerivationAttributes", emvCommon())), "us-east-1"); + + AwsException refused = assertThrows(AwsException.class, () -> cryptogram.verify(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", key.getArn(), + "AuthRequestCryptogram", generated.get("AuthRequestCryptogram"), + "TransactionData", ANOTHER_TRANSACTION_DATA, + "MajorKeyDerivationMode", "EMV_OPTION_A", + "SessionKeyDerivationAttributes", emvCommon())), "us-east-1")); + + assertEquals("VerificationFailedException", refused.getErrorCode()); + } + + @Test + void theAmexDerivationIsRefusedRatherThanApproximated() { + PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey"); + ObjectMapper mapper = new ObjectMapper(); + ObjectNode amex = mapper.createObjectNode(); + amex.put("PrimaryAccountNumber", PAN); + amex.put("PanSequenceNumber", PSN); + ObjectNode attributes = mapper.createObjectNode(); + attributes.set("Amex", amex); + + AwsException refused = assertThrows(AwsException.class, () -> cryptogram.generate( + PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", key.getArn(), + "TransactionData", TRANSACTION_DATA, + "MajorKeyDerivationMode", "EMV_OPTION_A", + "SessionKeyDerivationAttributes", attributes)), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("not approximated"), refused.getMessage()); + } + + @Test + void aKeyThatMayNotDeriveIsRefused() { + PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "Sign"); + + AwsException refused = assertThrows(AwsException.class, () -> cryptogram.generate( + PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", key.getArn(), + "TransactionData", TRANSACTION_DATA, + "MajorKeyDerivationMode", "EMV_OPTION_A", + "SessionKeyDerivationAttributes", emvCommon())), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + } + + @Test + void theSequenceNumberTheModelStatesIsTheOneTheDerivationTakes() { + PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey"); + ObjectMapper mapper = new ObjectMapper(); + ObjectNode common = mapper.createObjectNode(); + common.put("PrimaryAccountNumber", PAN); + // The model states that the PAN sequence number is two digits, and the derivation + // reads the last eight bytes of the packed PAN || PSN, so a longer one moves the + // window the master key is taken from. + common.put("PanSequenceNumber", "0001"); + common.put("ApplicationTransactionCounter", ATC); + ObjectNode attributes = mapper.createObjectNode(); + attributes.set("EmvCommon", common); + + AwsException refused = assertThrows(AwsException.class, () -> cryptogram.generate( + PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", key.getArn(), + "TransactionData", TRANSACTION_DATA, + "MajorKeyDerivationMode", "EMV_OPTION_A", + "SessionKeyDerivationAttributes", attributes)), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("PanSequenceNumber"), refused.getMessage()); + } + + @Test + void transactionDataThatIsNotHexadecimalIsRefused() { + PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey"); + + AwsException refused = assertThrows(AwsException.class, () -> cryptogram.generate( + PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", key.getArn(), + "TransactionData", "not hexadecimal", + "MajorKeyDerivationMode", "EMV_OPTION_A", + "SessionKeyDerivationAttributes", emvCommon())), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("TransactionData"), refused.getMessage()); + } + + @Test + void theResponseValueIsTheOneTheFirstMethodMakes() { + PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey"); + String arqc = (String) cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", key.getArn(), + "TransactionData", TRANSACTION_DATA, + "MajorKeyDerivationMode", "EMV_OPTION_A", + "SessionKeyDerivationAttributes", emvCommon())), "us-east-1") + .get("AuthRequestCryptogram"); + + // The response attributes are what the response value is made from, and the first + // method takes the response code. + Map verified = cryptogram.verify(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", key.getArn(), + "TransactionData", TRANSACTION_DATA, + "AuthRequestCryptogram", arqc, + "MajorKeyDerivationMode", "EMV_OPTION_A", + "SessionKeyDerivationAttributes", emvCommon(), + "AuthResponseAttributes", responseCode("1234"))), "us-east-1"); + + String value = (String) verified.get("AuthResponseValue"); + assertNotNull(value); + assertEquals(16, value.length()); + } + + @Test + void theResponseValueIsTheOneTheSecondMethodMakes() { + PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey"); + String arqc = (String) cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", key.getArn(), + "TransactionData", TRANSACTION_DATA, + "MajorKeyDerivationMode", "EMV_OPTION_A", + "SessionKeyDerivationAttributes", emvCommon())), "us-east-1") + .get("AuthRequestCryptogram"); + + // The second method takes the card status update and the proprietary data. + Map verified = cryptogram.verify(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", key.getArn(), + "TransactionData", TRANSACTION_DATA, + "AuthRequestCryptogram", arqc, + "MajorKeyDerivationMode", "EMV_OPTION_A", + "SessionKeyDerivationAttributes", emvCommon(), + "AuthResponseAttributes", cardStatusUpdate("12345678", "ABCD"))), "us-east-1"); + + String value = (String) verified.get("AuthResponseValue"); + assertNotNull(value); + assertEquals(8, value.length()); + } + + @Test + void aTransactionDataThatIsNotWholeBlocksIsRefused() { + PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey"); + + // The ISO 9797-1 MAC runs over eight-byte blocks, and the user guide tells the + // caller to pad the transaction data before sending it, so a length that is not + // a whole number of blocks is a request the cipher cannot read. + AwsException refused = assertThrows(AwsException.class, + () -> cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", key.getArn(), + "TransactionData", "0000000001000000000000000000800000", + "MajorKeyDerivationMode", "EMV_OPTION_A", + "SessionKeyDerivationAttributes", emvCommon())), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("TransactionData"), refused.getMessage()); + assertTrue(refused.getMessage().contains("blocks"), refused.getMessage()); + } + + @Test + void aKeyOfAnotherAlgorithmIsRefused() { + // The key table names TDES_2KEY for the ARQC key, and the derivation reads + // sixteen bytes of material, so a three-key Triple DES key is refused. + PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_3KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey"); + + AwsException refused = assertThrows(AwsException.class, + () -> cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", key.getArn(), + "TransactionData", TRANSACTION_DATA, + "MajorKeyDerivationMode", "EMV_OPTION_A", + "SessionKeyDerivationAttributes", emvCommon())), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("TDES_2KEY"), refused.getMessage()); + } + + @Test + void aDisabledKeyIsRefused() { + PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createDisabledKey(service, + "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey"); + + AwsException refused = assertThrows(AwsException.class, + () -> cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", key.getArn(), + "TransactionData", TRANSACTION_DATA, + "MajorKeyDerivationMode", "EMV_OPTION_A", + "SessionKeyDerivationAttributes", emvCommon())), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + } + + @Test + void aKeyOfTheWrongUsageIsRefused() { + PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", + "TR31_C0_CARD_VERIFICATION_KEY", "DeriveKey"); + + AwsException refused = assertThrows(AwsException.class, + () -> cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", key.getArn(), + "TransactionData", TRANSACTION_DATA, + "MajorKeyDerivationMode", "EMV_OPTION_A", + "SessionKeyDerivationAttributes", emvCommon())), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + } + + @Test + void aKeyThatIsNotTripleDesIsRefused() { + PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "AES_128", + "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey"); + + AwsException refused = assertThrows(AwsException.class, + () -> cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", key.getArn(), + "TransactionData", TRANSACTION_DATA, + "MajorKeyDerivationMode", "EMV_OPTION_A", + "SessionKeyDerivationAttributes", emvCommon())), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + } + + @Test + void aResponseValueThatIsNotAskedForIsNotAnswered() { + PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey"); + String arqc = (String) cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", key.getArn(), + "TransactionData", TRANSACTION_DATA, + "MajorKeyDerivationMode", "EMV_OPTION_A", + "SessionKeyDerivationAttributes", emvCommon())), "us-east-1") + .get("AuthRequestCryptogram"); + + Map verified = cryptogram.verify(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", key.getArn(), + "TransactionData", TRANSACTION_DATA, + "AuthRequestCryptogram", arqc, + "MajorKeyDerivationMode", "EMV_OPTION_A", + "SessionKeyDerivationAttributes", emvCommon())), "us-east-1"); + + assertEquals(key.getArn(), verified.get("KeyArn")); + assertNull(verified.get("AuthResponseValue")); + } + + /** The response attributes of the first ARPC method, which takes the response code. */ + private static JsonNode responseCode(String code) { + ObjectMapper mapper = new ObjectMapper(); + ObjectNode method = mapper.createObjectNode(); + method.put("AuthResponseCode", code); + ObjectNode outer = mapper.createObjectNode(); + outer.set("ArpcMethod1", method); + return outer; + } + + /** The response attributes of the second ARPC method. */ + private static JsonNode cardStatusUpdate(String status, String proprietary) { + ObjectMapper mapper = new ObjectMapper(); + ObjectNode method = mapper.createObjectNode(); + method.put("CardStatusUpdate", status); + method.put("ProprietaryAuthenticationData", proprietary); + ObjectNode outer = mapper.createObjectNode(); + outer.set("ArpcMethod2", method); + return outer; + } +} diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardValidationOperationsTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardValidationOperationsTest.java new file mode 100644 index 0000000000..af55b3f063 --- /dev/null +++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardValidationOperationsTest.java @@ -0,0 +1,283 @@ +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.crypto.CvvCrypto; +import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The card validation operations. + * + *

The values in the first test are the emulator's, and the emulator checks them against + * an independent implementation: the card verification value of an account number, + * an expiry and a service code. + */ +class PaymentCryptographyCardValidationOperationsTest { + + private static final String PAN = "5081470082639564"; + private static final String EXPIRY = "3003"; + private static final String CVK = "0123456789ABCDEFFEDCBA9876543210"; + + private PaymentCryptographyService service; + private PaymentCryptographyCardValidationOperations cardValidation; + private final ObjectMapper mapper = new ObjectMapper(); + + @BeforeEach + void setUp() { + service = new PaymentCryptographyService( + new InMemoryStorage<>(), + new InMemoryStorage<>(), + new RegionResolver("us-east-1", "000000000000")); + cardValidation = new PaymentCryptographyCardValidationOperations(service); + } + + /** The attributes of a card verification value: the expiry and the service code. */ + private static JsonNode cardVerificationValue1(String expiry, String serviceCode) { + ObjectMapper mapper = new ObjectMapper(); + ObjectNode value = mapper.createObjectNode(); + value.put("CardExpiryDate", expiry); + value.put("ServiceCode", serviceCode); + ObjectNode outer = mapper.createObjectNode(); + outer.set("CardVerificationValue1", value); + return outer; + } + + @Test + void theCardVerificationValueIsTheOneTheStandardGives() { + assertEquals("131", CvvCrypto.computeCvv(PAN, EXPIRY, "201", CVK, 3)); + assertEquals("886", CvvCrypto.computeCvv(PAN, EXPIRY, "000", CVK, 3)); + assertEquals("660", CvvCrypto.computeCvv(PAN, EXPIRY, "999", CVK, 3)); + } + + @Test + void aGeneratedValueVerifies() { + PaymentCryptographyKey cvk = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_C0_CARD_VERIFICATION_KEY", + "Generate", "Verify"); + + Map generated = cardValidation.generate(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", cvk.getArn(), + "PrimaryAccountNumber", PAN, + "GenerationAttributes", cardVerificationValue1(EXPIRY, "201"))), "us-east-1"); + + String value = (String) generated.get("ValidationData"); + assertEquals(3, value.length()); + assertEquals(cvk.getArn(), generated.get("KeyArn")); + + Map verified = cardValidation.verify(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", cvk.getArn(), + "PrimaryAccountNumber", PAN, + "ValidationData", value, + "VerificationAttributes", cardVerificationValue1(EXPIRY, "201"))), "us-east-1"); + + assertEquals(cvk.getArn(), verified.get("KeyArn")); + } + + @Test + void aWrongValueIsRefused() { + PaymentCryptographyKey cvk = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_C0_CARD_VERIFICATION_KEY", + "Generate", "Verify"); + + AwsException refused = assertThrows(AwsException.class, () -> cardValidation.verify( + PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", cvk.getArn(), + "PrimaryAccountNumber", PAN, + "ValidationData", "999", + "VerificationAttributes", cardVerificationValue1(EXPIRY, "201"))), + "us-east-1")); + + assertEquals("VerificationFailedException", refused.getErrorCode()); + } + + @Test + void aKeyOfTheWrongUsageIsRefused() { + PaymentCryptographyKey wrong = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", + "Generate", "Verify"); + + AwsException refused = assertThrows(AwsException.class, + () -> cardValidation.generate(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", wrong.getArn(), + "PrimaryAccountNumber", PAN, + "GenerationAttributes", cardVerificationValue1(EXPIRY, "201"))), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("TR31_C0_CARD_VERIFICATION_KEY"), + refused.getMessage()); + } + + @Test + void aKeyThatMayNotGenerateIsRefused() { + PaymentCryptographyKey cvk = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_C0_CARD_VERIFICATION_KEY", + "Verify"); + + AwsException refused = assertThrows(AwsException.class, + () -> cardValidation.generate(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", cvk.getArn(), + "PrimaryAccountNumber", PAN, + "GenerationAttributes", cardVerificationValue1(EXPIRY, "201"))), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + } + + @Test + void anExpiryThatIsNotFourDigitsIsRefused() { + PaymentCryptographyKey cvk = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_C0_CARD_VERIFICATION_KEY", + "Generate", "Verify"); + + // The model states that the expiry is four digits, and the card verification value + // is computed over the expiry the request carries. + AwsException refused = assertThrows(AwsException.class, + () -> cardValidation.generate(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", cvk.getArn(), + "PrimaryAccountNumber", PAN, + "GenerationAttributes", cardVerificationValue1("30", "201"))), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("CardExpiryDate"), refused.getMessage()); + } + + @Test + void anAccountNumberThatIsNotDigitsIsRefused() { + PaymentCryptographyKey cvk = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_C0_CARD_VERIFICATION_KEY", + "Generate", "Verify"); + + // The model states that the account number is digits, so a formatted one is refused + // rather than read as the digits it carries. + AwsException refused = assertThrows(AwsException.class, + () -> cardValidation.generate(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", cvk.getArn(), + "PrimaryAccountNumber", "5081-4700-8263-9564", + "GenerationAttributes", cardVerificationValue1(EXPIRY, "201"))), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("PrimaryAccountNumber"), refused.getMessage()); + } + + @Test + void theDynamicCardVerificationCodeIsRefusedRatherThanApproximated() { + PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E4_EMV_MKEY_DYNAMIC_NUMBERS", + "Generate", "Verify", "DeriveKey"); + + // The dynamic code is a Mastercard proprietary construction, and there is nothing + // published to check a derivation against. + AwsException refused = assertThrows(AwsException.class, + () -> cardValidation.generate(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", key.getArn(), + "PrimaryAccountNumber", PAN, + "GenerationAttributes", dynamicCardVerificationCode())), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("not implemented"), refused.getMessage()); + } + + @Test + void theValidationDataLengthIsTheOneTheModelStates() { + PaymentCryptographyKey cvk = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_C0_CARD_VERIFICATION_KEY", + "Generate", "Verify"); + + // The model lets the length be three to five, and the value carries that many + // digits of the decimalised block. + cardValidation.generate(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", cvk.getArn(), + "PrimaryAccountNumber", PAN, + "ValidationDataLength", 3, + "GenerationAttributes", cardVerificationValue1(EXPIRY, "201"))), "us-east-1"); + + Map longer = cardValidation.generate(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", cvk.getArn(), + "PrimaryAccountNumber", PAN, + "ValidationDataLength", 5, + "GenerationAttributes", cardVerificationValue1(EXPIRY, "201"))), "us-east-1"); + + assertEquals(5, ((String) longer.get("ValidationData")).length()); + } + + @Test + void aLengthTheModelDoesNotStateIsRefused() { + PaymentCryptographyKey cvk = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_C0_CARD_VERIFICATION_KEY", + "Generate", "Verify"); + + // The model states the length as three to five, so the request is refused against the + // model's own constraint rather than by a check of our own. + AwsException refused = assertThrows(AwsException.class, + () -> cardValidation.generate(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", cvk.getArn(), + "PrimaryAccountNumber", PAN, + "ValidationDataLength", 2, + "GenerationAttributes", cardVerificationValue1(EXPIRY, "201"))), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("ValidationDataLength"), refused.getMessage()); + } + + @Test + void aValueTheModelDoesNotStateIsRefused() { + PaymentCryptographyKey cvk = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_C0_CARD_VERIFICATION_KEY", + "Generate", "Verify"); + + // The model states the value as three to five digits, so a shorter one is refused + // against the model's own constraint. + AwsException refused = assertThrows(AwsException.class, + () -> cardValidation.verify(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", cvk.getArn(), + "PrimaryAccountNumber", PAN, + "ValidationData", "99", + "VerificationAttributes", cardVerificationValue1(EXPIRY, "201"))), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("ValidationData"), refused.getMessage()); + } + + @Test + void aDisabledKeyIsRefused() { + PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createDisabledKey(service, + "TDES_2KEY", "TR31_C0_CARD_VERIFICATION_KEY", "Generate", "Verify"); + + AwsException refused = assertThrows(AwsException.class, + () -> cardValidation.generate(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", key.getArn(), + "PrimaryAccountNumber", PAN, + "GenerationAttributes", cardVerificationValue1(EXPIRY, "201"))), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + } + + /** The attributes of the dynamic card verification code, which is computed over the track. */ + private static JsonNode dynamicCardVerificationCode() { + return dynamicCardVerificationCode("01", "5081470082639564300303D25061010000000000"); + } + + /** The attributes of the dynamic card verification code, over the given track data. */ + private static JsonNode dynamicCardVerificationCode(String trackData) { + return dynamicCardVerificationCode("01", trackData); + } + + /** + * The attributes of the dynamic card verification code of a card with the given + * sequence number, over the given track data. + */ + private static JsonNode dynamicCardVerificationCode(String psn, String trackData) { + ObjectMapper mapper = new ObjectMapper(); + ObjectNode value = mapper.createObjectNode(); + value.put("UnpredictableNumber", "12345678"); + value.put("PanSequenceNumber", psn); + value.put("ApplicationTransactionCounter", "0001"); + value.put("TrackData", trackData); + ObjectNode outer = mapper.createObjectNode(); + outer.set("DynamicCardVerificationCode", value); + return outer; + } +} 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 577a38cd4b..e468c62768 100644 --- a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoHandlerTest.java +++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoHandlerTest.java @@ -323,6 +323,65 @@ class PaymentCryptographyCryptoHandlerTest { assertTrue(refused.getMessage().contains("16 bytes"), refused.getMessage()); } + @Test + void aPaddingTypeIsRefused() { + // The padding type belongs to RSA, and the symmetric cipher does not pad, so a + // request that names one is refused rather than answered with a cipher that + // ignored it. + PaymentCryptographyKey key = createKey("Encrypt", "Decrypt"); + + ObjectNode symmetric = mapper.createObjectNode(); + symmetric.put("Mode", "CBC"); + symmetric.put("PaddingType", "OAEP_SHA1"); + 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("PaddingType"), refused.getMessage()); + } + + @Test + void aWrappedKeyIsRefused() { + // The wrapped-key form is the key exchange, and the unwrapping is part of it, so a + // request that carries one is refused rather than answered as if the key were a + // fixed one. + PaymentCryptographyKey key = createKey("Encrypt", "Decrypt"); + + AwsException refused = assertThrows(AwsException.class, () -> handler.encryptData(request(Map.of( + "KeyIdentifier", key.getArn(), "PlainText", hex("hello, world!!!!".getBytes()), + "EncryptionAttributes", cbc(), + "WrappedKey", wrappedKey())), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("WrappedKey"), refused.getMessage()); + } + + @Test + void aWrappedKeyIsRefusedOnDecryptionToo() { + PaymentCryptographyKey key = createKey("Encrypt", "Decrypt"); + + AwsException refused = assertThrows(AwsException.class, () -> handler.decryptData(request(Map.of( + "KeyIdentifier", key.getArn(), "CipherText", "00".repeat(16), + "DecryptionAttributes", cbc(), + "WrappedKey", wrappedKey())), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("WrappedKey"), refused.getMessage()); + } + + /** The wrapped key the model carries, which the service refuses. */ + private JsonNode wrappedKey() { + ObjectNode material = mapper.createObjectNode(); + material.put("Tr31KeyBlock", "A".repeat(56)); + ObjectNode wrapped = mapper.createObjectNode(); + wrapped.set("WrappedKeyMaterial", material); + return wrapped; + } + @Test void aCipherTextIsAsLongAsThePlainTextItHolds() { // The cipher pads no data, so a ciphertext is as long as its plaintext. diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyDataRequestShapesTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyDataRequestShapesTest.java index fb10fd1b33..f5f29a5edc 100644 --- a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyDataRequestShapesTest.java +++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyDataRequestShapesTest.java @@ -11,6 +11,7 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * The members that name a key, checked against the vendored constraints in every published region. @@ -59,4 +60,24 @@ class PaymentCryptographyDataRequestShapesTest { assertEquals("ValidationException", refused.getErrorCode()); } + + @Test + void theCardOperationsAreCheckedAgainstTheModelToo() { + // The card operations' constraints are vendored, so a request that names a key by + // its identifier on its own is refused the way the other operations' is. + ObjectNode attributes = MAPPER.createObjectNode(); + ObjectNode value = attributes.putObject("CardVerificationValue1"); + value.put("CardExpiryDate", "3003"); + value.put("ServiceCode", "201"); + ObjectNode card = MAPPER.createObjectNode(); + card.put("KeyIdentifier", KEY_ID); + card.put("PrimaryAccountNumber", "4111111111111111"); + card.set("GenerationAttributes", attributes); + + AwsException refused = assertThrows(AwsException.class, + () -> PaymentCryptographyDataRequestShapes.check("GenerateCardValidationData", card)); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("KeyIdentifier"), refused.getMessage()); + } } diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyTestFixtures.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyTestFixtures.java new file mode 100644 index 0000000000..bd62b640c8 --- /dev/null +++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyTestFixtures.java @@ -0,0 +1,84 @@ +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.services.paymentcryptography.model.PaymentCryptographyKey; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * The builders the payment cryptography tests share. + * + *

A key and a request are built the same way whichever operation is under test, so + * they are built here once. A change to how they are built is then a change in one + * place. + */ +final class PaymentCryptographyTestFixtures { + + private PaymentCryptographyTestFixtures() { + } + + /** + * A key of the algorithm and the usage, with the modes of use the test names. + * + * @param service the service the key is made in + * @param algorithm the key's algorithm + * @param usage the key's usage + * @param modes the modes of use the key allows + * @return the key that was made + */ + static PaymentCryptographyKey createKey(PaymentCryptographyService service, String algorithm, + String usage, String... modes) { + return key(service, algorithm, usage, true, modes); + } + + /** + * A key that was made disabled, and may therefore not be used. + * + * @param service the service the key is made in + * @param algorithm the key's algorithm + * @param usage the key's usage + * @param modes the modes of use the key allows + * @return the key that was made + */ + static PaymentCryptographyKey createDisabledKey(PaymentCryptographyService service, String algorithm, + String usage, String... modes) { + return key(service, algorithm, usage, false, modes); + } + + private static PaymentCryptographyKey key(PaymentCryptographyService service, String algorithm, + String usage, boolean enabled, String... modes) { + Map attributes = new LinkedHashMap<>(); + attributes.put("KeyAlgorithm", algorithm); + attributes.put("KeyClass", "SYMMETRIC_KEY"); + attributes.put("KeyUsage", usage); + Map declared = new LinkedHashMap<>(); + for (String mode : modes) { + declared.put(mode, Boolean.TRUE); + } + return service.createKey("us-east-1", attributes, declared, true, enabled, Map.of()); + } + + /** + * A request body of the members the test names. + * + * @param members the members of the request + * @return the body + */ + static JsonNode request(Map members) { + ObjectMapper mapper = new ObjectMapper(); + ObjectNode node = mapper.createObjectNode(); + members.forEach((name, value) -> { + if (value instanceof JsonNode json) { + node.set(name, json); + } else if (value instanceof Number number) { + node.put(name, number.intValue()); + } else { + node.put(name, String.valueOf(value)); + } + }); + return node; + } +} diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/crypto/CvvCryptoTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/crypto/CvvCryptoTest.java new file mode 100644 index 0000000000..244566f297 --- /dev/null +++ b/src/test/java/io/floci/aws/services/paymentcryptography/crypto/CvvCryptoTest.java @@ -0,0 +1,124 @@ +package io.floci.aws.services.paymentcryptography.crypto; + +import org.junit.jupiter.api.Test; + +import javax.crypto.Cipher; +import javax.crypto.spec.SecretKeySpec; +import java.util.HexFormat; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * The card verification values, against the constructions the specifications give. + * + *

The dynamic value is the one the Visa Contactless Payment Specification describes: the + * leftmost four digits of the account number are replaced by the transaction counter, and + * the result, the expiry and the service code are enciphered under the card's unique + * derived key. The expected value is computed here from the specification's own steps, + * with the cipher written out, so that a change to the service is a change against the + * specification rather than against itself. + */ +class CvvCryptoTest { + + /** The issuer master key the unique derived key is derived from. */ + private static final String IMK = "0123456789ABCDEFFEDCBA9876543210"; + + /** The account number of the card. */ + private static final String PAN = "5081470082639564"; + + /** The expiry of the card, in the YYMM form the request carries. */ + private static final String EXPIRY = "3003"; + + /** The service code of the value. */ + private static final String SERVICE_CODE = "201"; + + /** The transaction counter, in the binary coded decimal the track data carries. */ + private static final String ATC = "0001"; + + /** The PAN sequence number, which the unique derived key is derived with. */ + private static final String PSN = "01"; + + @Test + void theDynamicValueIsTheOneTheSpecificationGives() { + assertEquals(dcvv(), CvvCrypto.computeDynamicValue( + PAN, EXPIRY, SERVICE_CODE, ATC, IMK, PSN, 3)); + } + + @Test + void theDynamicValueIsNotTheStaticValue() { + // The counter is inserted into the account number, so the value is bound to the + // transaction and is not the value of the card's fields. + assertEquals(false, CvvCrypto.computeDynamicValue( + PAN, EXPIRY, SERVICE_CODE, ATC, IMK, PSN, 3) + .equals(CvvCrypto.computeCvv(PAN, EXPIRY, SERVICE_CODE, IMK, 3))); + } + + /** + * The dynamic value, written from the specification's steps. + * + *

    + *
  1. The leftmost four digits of the account number are replaced by the counter.
  2. + *
  3. The result, the expiry and the service code are enciphered under the unique + * derived key: the left block is enciphered with the first half of the key, the + * result is exclusive-ored with the right block, and the block is enciphered, + * deciphered and enciphered with the two halves of the key.
  4. + *
  5. The three leftmost decimal digits of the result are the value.
  6. + *
+ */ + private static String dcvv() { + String data = ATC + PAN.substring(4) + EXPIRY + SERVICE_CODE; + while (data.length() < 32) { + data = data + "0"; + } + byte[] left = hex(data.substring(0, 16)); + byte[] right = hex(data.substring(16, 32)); + byte[] udk = EmvCrypto.deriveIccMasterKey(hex(IMK), PAN, PSN); + + byte[] block = singleDes(left, udk, 0, false); + block = xor(block, right); + block = singleDes(block, udk, 0, false); + block = singleDes(block, udk, 8, true); + block = singleDes(block, udk, 0, false); + + StringBuilder digits = new StringBuilder(); + StringBuilder letters = new StringBuilder(); + for (byte b : block) { + for (int nibble : new int[]{(b >> 4) & 0xf, b & 0xf}) { + if (nibble < 10) { + digits.append((char) ('0' + nibble)); + } else { + letters.append((char) ('0' + nibble - 10)); + } + } + } + return digits.append(letters).substring(0, 3); + } + + /** One block of Single DES, with the first or the second half of the double length key. */ + private static byte[] singleDes(byte[] block, byte[] key16, int half, boolean decrypt) { + byte[] key = new byte[8]; + System.arraycopy(key16, half, key, 0, 8); + try { + Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding"); + cipher.init(decrypt ? Cipher.DECRYPT_MODE : Cipher.ENCRYPT_MODE, + new SecretKeySpec(key, "DES")); + return cipher.doFinal(block); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + /** The exclusive-or of two byte arrays of the same length. */ + private static byte[] xor(byte[] a, byte[] b) { + byte[] out = new byte[a.length]; + for (int i = 0; i < a.length; i++) { + out[i] = (byte) (a[i] ^ b[i]); + } + return out; + } + + /** The bytes of a hexadecimal string. */ + private static byte[] hex(String value) { + return HexFormat.of().parseHex(value); + } +} diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/crypto/EmvCryptoTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/crypto/EmvCryptoTest.java new file mode 100644 index 0000000000..276388beab --- /dev/null +++ b/src/test/java/io/floci/aws/services/paymentcryptography/crypto/EmvCryptoTest.java @@ -0,0 +1,106 @@ +package io.floci.aws.services.paymentcryptography.crypto; + +import org.junit.jupiter.api.Test; + +import java.util.HexFormat; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * The EMV derivations, against the vectors the specifications publish. + * + *

The ICC master key is the one EMV 4.4 Book 2 Annex A1.4.1 Option A gives, and the + * Visa Integrated Circuit Card Specification states the same rule. The session keys and the + * cryptogram are the worked examples of the M/Chip Card Application Cryptographic + * Algorithms: the MasterCard proprietary derivation and the common one, with the application + * cryptogram each produces over the same data. + */ +class EmvCryptoTest { + + /** The issuer master key of the published ICC master key vector. */ + private static final String IMK = "0123456789ABCDEFFEDCBA9876543210"; + + /** The account number of the published ICC master key vector. */ + private static final String PAN = "4111111111111111"; + + /** The sequence number of the published ICC master key vector. */ + private static final String PSN = "00"; + + /** The ICC master key the published vector gives. */ + private static final String UDK = "31089464674C73EC851A6E0737029D19"; + + /** The AC master key of the M/Chip worked examples. */ + private static final String MKAC = "08DF34253220A720EFF2C1343852E63D"; + + /** The application transaction counter of the M/Chip worked examples. */ + private static final String ATC = "3456"; + + /** The terminal unpredictable number of the M/Chip worked examples. */ + private static final String UN = "11111111"; + + /** The data the M/Chip worked examples compute the application cryptogram over. */ + private static final String CDOL = """ + 00 00 00 01 00 00 00 00 00 00 10 00 08 40 00 00 + 00 10 80 08 40 98 07 04 00 11 11 11 11 58 00 34 + 56 03 A4 00 20"""; + + /** The application cryptogram the M/Chip worked example gives. */ + private static final String ARQC = "DBC1E0B820FFE7DB"; + + /** The common session key the M/Chip worked example gives. */ + private static final String COMMON_SESSION_KEY = "182025BA4FAB32F5A63A1BA5E6845D4E"; + + @Test + void theIccMasterKeyIsTheOneTheStandardGives() { + assertEquals(UDK, hex(EmvCrypto.deriveIccMasterKey(hex(IMK), PAN, PSN))); + } + + @Test + void aShortAccountNumberIsPaddedOnTheLeft() { + // The block is the rightmost sixteen digits of the account number and the sequence + // number, padded on the left with zeros when they are shorter. So an account number + // that is two digits short of the field derives the key that the same number with + // those two zeros derives. + String shortNumber = "411111111111"; + String paddedNumber = "00" + shortNumber; + + assertArrayEquals(EmvCrypto.deriveIccMasterKey(hex(IMK), paddedNumber, "01"), + EmvCrypto.deriveIccMasterKey(hex(IMK), shortNumber, "01")); + } + + @Test + void theMasterCardSessionKeyAndCryptogramAreTheOnesTheDocumentGives() { + byte[] sessionKey = EmvCrypto.deriveSessionKeyMastercard(hex(MKAC), hex(ATC), hex(UN)); + + assertEquals(ARQC, hex(EmvCrypto.retailMac(sessionKey, hex(CDOL), EmvCrypto.Padding.METHOD2))); + } + + @Test + void theCommonSessionKeyIsTheOneTheDocumentGives() { + byte[] sessionKey = EmvCrypto.deriveSessionKey(hex(MKAC), hex(ATC)); + + // The document does not force the parity of the derived key, and the derivation does + // not affect the computation, so the parity bits are masked on both sides. + assertEquals(withoutParity(COMMON_SESSION_KEY), withoutParity(hex(sessionKey))); + } + + /** The bytes of a hexadecimal string, the spaces and the line breaks in it ignored. */ + private static byte[] hex(String value) { + return HexFormat.of().parseHex(value.replaceAll("\\s", "")); + } + + /** The hexadecimal of the bytes, in the case the documents print them. */ + private static String hex(byte[] value) { + return HexFormat.of().withUpperCase().formatHex(value); + } + + /** The key with the DES parity bits masked, which the derivation does not affect. */ + private static String withoutParity(String key) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < key.length(); i += 2) { + sb.append(String.format("%02X", Integer.parseInt(key.substring(i, i + 2), 16) & 0xFE)); + } + return sb.toString(); + } +} diff --git a/tools/aws/regen_payment_cryptography_data_shapes.py b/tools/aws/regen_payment_cryptography_data_shapes.py index 3ac1978324..f7d8a45633 100644 --- a/tools/aws/regen_payment_cryptography_data_shapes.py +++ b/tools/aws/regen_payment_cryptography_data_shapes.py @@ -27,6 +27,8 @@ OPERATIONS = ( "EncryptData", "DecryptData", "ReEncryptData", "GenerateMac", "VerifyMac", "GeneratePinData", "VerifyPinData", "TranslatePinData", "GenerateMacEmvPinChange", + "GenerateCardValidationData", "VerifyCardValidationData", + "GenerateAuthRequestCryptogram", "VerifyAuthRequestCryptogram", ) diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml index 44f0fcdb70..f1c789b652 100644 --- a/tools/docs/services.yaml +++ b/tools/docs/services.yaml @@ -42,6 +42,7 @@ services: sources: - { path: services/paymentcryptography/PaymentCryptographyCryptoController.java, mode: rest } - { path: services/paymentcryptography/PaymentCryptographyPinController.java, mode: rest } + - { path: services/paymentcryptography/PaymentCryptographyCardController.java, mode: rest } exclude_actions: - GenerateMacEmvPinChange - service: applicationautoscaling