From 77d73ee4b7fe0e2e6f1fa2d44f4d02a7e77a492c Mon Sep 17 00:00:00 2001 From: Murtuza Chhil Date: Thu, 12 Nov 2026 18:29:48 +0530 Subject: [PATCH] feat(paymentcryptography): the key exchange, with TR-31, RSA-OAEP and ECDH (#7862) --- .../payment-cryptography-key-exchange.bats | 131 ++ .../floci/test/PaymentCryptographyTest.java | 68 + docs/services/index.md | 2 +- docs/services/payment-cryptography-data.md | 4 +- docs/services/payment-cryptography.md | 79 +- .../core/common/RequestConstraintCheck.java | 5 + ...tCryptographyAuthCryptogramOperations.java | 14 +- ...tCryptographyCardValidationOperations.java | 2 +- .../PaymentCryptographyJsonHandler.java | 212 ++- .../PaymentCryptographyKeyExchange.java | 1176 +++++++++++++++++ .../PaymentCryptographyRequestShapes.java | 10 + .../PaymentCryptographyService.java | 312 ++++- .../PaymentCryptographyTr31.java | 593 +++++++++ .../crypto/Certificates.java | 134 ++ .../paymentcryptography/crypto/Ciphers.java | 28 + .../paymentcryptography/crypto/ConcatKdf.java | 112 ++ .../paymentcryptography/crypto/Ecdh.java | 62 + .../paymentcryptography/crypto/EmvCrypto.java | 14 +- .../paymentcryptography/crypto/RsaOaep.java | 114 ++ ...ment-cryptography-data-request-shapes.json | 146 +- .../payment-cryptography-request-shapes.json | 708 +++++++++- ...ptographyAuthCryptogramOperationsTest.java | 16 + .../PaymentCryptographyIntegrationTest.java | 340 ++++- .../PaymentCryptographyKeyExchangeTest.java | 964 ++++++++++++++ .../PaymentCryptographyServiceTest.java | 239 ++++ .../PaymentCryptographyTr31Test.java | 295 +++++ .../crypto/CertificatesTest.java | 100 ++ ...tepFunctionsAwsSdkTaskIntegrationTest.java | 14 +- .../regen_payment_cryptography_data_shapes.py | 10 +- .../aws/regen_payment_cryptography_shapes.py | 8 +- tools/aws/request_shapes.py | 3 +- tools/aws/test_request_shapes.py | 77 +- 32 files changed, 5863 insertions(+), 129 deletions(-) create mode 100644 compatibility-tests/sdk-test-awscli/test/payment-cryptography-key-exchange.bats create mode 100644 src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchange.java create mode 100644 src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyTr31.java create mode 100644 src/main/java/io/floci/aws/services/paymentcryptography/crypto/Certificates.java create mode 100644 src/main/java/io/floci/aws/services/paymentcryptography/crypto/ConcatKdf.java create mode 100644 src/main/java/io/floci/aws/services/paymentcryptography/crypto/Ecdh.java create mode 100644 src/main/java/io/floci/aws/services/paymentcryptography/crypto/RsaOaep.java create mode 100644 src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchangeTest.java create mode 100644 src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyTr31Test.java create mode 100644 src/test/java/io/floci/aws/services/paymentcryptography/crypto/CertificatesTest.java diff --git a/compatibility-tests/sdk-test-awscli/test/payment-cryptography-key-exchange.bats b/compatibility-tests/sdk-test-awscli/test/payment-cryptography-key-exchange.bats new file mode 100644 index 0000000000..796d374097 --- /dev/null +++ b/compatibility-tests/sdk-test-awscli/test/payment-cryptography-key-exchange.bats @@ -0,0 +1,131 @@ +#!/usr/bin/env bats +# Payment Cryptography key exchange tests +# +# The key exchange is the control plane's own operations, so a client reaches them at the +# control plane's route. These tests drive them with the AWS CLI, which is such a client, +# and its shorthand for a union member is a client's own way of writing the form. + +setup() { + load 'test_helper/common-setup' + WRAPPING_ARN="" + KEY_ARN="" +} + +teardown() { + for key in "$WRAPPING_ARN" "$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 +} + +# The key a key block is wrapped under. +create_wrapping_key() { + aws_cmd payment-cryptography create-key \ + --key-attributes 'KeyAlgorithm=AES_256,KeyClass=SYMMETRIC_KEY,KeyUsage=TR31_K1_KEY_BLOCK_PROTECTION_KEY,KeyModesOfUse={Wrap=true,Unwrap=true}' \ + --exportable \ + --query 'Key.KeyArn' --output text +} + +# The key that leaves the service. +create_key() { + aws_cmd payment-cryptography create-key \ + --key-attributes 'KeyAlgorithm=AES_256,KeyClass=SYMMETRIC_KEY,KeyUsage=TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY,KeyModesOfUse={Encrypt=true,Decrypt=true}' \ + --exportable \ + --query 'Key.KeyArn' --output text +} + +@test "Payment Cryptography key exchange: the import parameters carry a token and a certificate" { + run aws_cmd payment-cryptography get-parameters-for-import \ + --key-material-type KEY_CRYPTOGRAM \ + --wrapping-key-algorithm RSA_2048 + assert_success + TOKEN=$(json_get "$output" '.ImportToken') + [ -n "$TOKEN" ] + # The token is named for the operation that issued it. + [[ "$TOKEN" == import-token-* ]] + [ "$(json_get "$output" '.WrappingKeyAlgorithm')" = "RSA_2048" ] + [ -n "$(json_get "$output" '.WrappingKeyCertificate')" ] + # The chain of a self-signed certificate is the certificate itself. + [ "$(json_get "$output" '.WrappingKeyCertificateChain')" = "$(json_get "$output" '.WrappingKeyCertificate')" ] + [ -n "$(json_get "$output" '.ParametersValidUntilTimestamp')" ] +} + +@test "Payment Cryptography key exchange: the export parameters carry a token and a certificate" { + run aws_cmd payment-cryptography get-parameters-for-export \ + --key-material-type TR34_KEY_BLOCK \ + --signing-key-algorithm RSA_2048 + assert_success + TOKEN=$(json_get "$output" '.ExportToken') + [ -n "$TOKEN" ] + [[ "$TOKEN" == export-token-* ]] + [ "$(json_get "$output" '.SigningKeyAlgorithm')" = "RSA_2048" ] + [ -n "$(json_get "$output" '.SigningKeyCertificate')" ] + [ -n "$(json_get "$output" '.ParametersValidUntilTimestamp')" ] +} + +@test "Payment Cryptography key exchange: a key leaves in a key block and comes back" { + WRAPPING_ARN=$(create_wrapping_key) + KEY_ARN=$(create_key) + [ -n "$WRAPPING_ARN" ] + [ -n "$KEY_ARN" ] + + run aws_cmd payment-cryptography export-key \ + --export-key-identifier "$KEY_ARN" \ + --key-material "Tr31KeyBlock={WrappingKeyIdentifier=$WRAPPING_ARN}" + assert_success + [ "$(json_get "$output" '.WrappedKey.WrappedKeyMaterialFormat')" = "TR31_KEY_BLOCK" ] + [ "$(json_get "$output" '.WrappedKey.WrappingKeyArn')" = "$WRAPPING_ARN" ] + BLOCK=$(json_get "$output" '.WrappedKey.KeyMaterial') + [ -n "$BLOCK" ] + [ -n "$(json_get "$output" '.WrappedKey.KeyCheckValue')" ] + + run aws_cmd payment-cryptography import-key \ + --key-material "Tr31KeyBlock={WrappingKeyIdentifier=$WRAPPING_ARN,WrappedKeyBlock=$BLOCK}" + assert_success + IMPORTED=$(json_get "$output" '.Key.KeyArn') + [ -n "$IMPORTED" ] + [ "$(json_get "$output" '.Key.KeyAttributes.KeyUsage')" = "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY" ] +} + +@test "Payment Cryptography key exchange: a key that may not leave is refused" { + WRAPPING_ARN=$(create_wrapping_key) + [ -n "$WRAPPING_ARN" ] + # The key is made with the export off, which the CLI writes as the negated flag. + run aws_cmd payment-cryptography create-key \ + --key-attributes 'KeyAlgorithm=AES_256,KeyClass=SYMMETRIC_KEY,KeyUsage=TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY,KeyModesOfUse={Encrypt=true,Decrypt=true}' \ + --no-exportable \ + --query 'Key.KeyArn' --output text + assert_success + KEY_ARN="$output" + [ -n "$KEY_ARN" ] + + run aws_cmd payment-cryptography export-key \ + --export-key-identifier "$KEY_ARN" \ + --key-material "Tr31KeyBlock={WrappingKeyIdentifier=$WRAPPING_ARN}" + assert_failure + [[ "$output" == *"ValidationException"* ]] +} + +@test "Payment Cryptography key exchange: a form the service does not serve is refused" { + KEY_ARN=$(create_key) + [ -n "$KEY_ARN" ] + # The request has to carry what the model asks for, or the client refuses it before + # the service ever sees it. + run aws_cmd payment-cryptography get-parameters-for-import \ + --key-material-type KEY_CRYPTOGRAM \ + --wrapping-key-algorithm RSA_2048 + assert_success + CERTIFICATE=$(json_get "$output" '.WrappingKeyCertificate') + [ -n "$CERTIFICATE" ] + + # The TR-34 form is not one this service makes, so the request names the forms it does. + run aws_cmd payment-cryptography export-key \ + --export-key-identifier "$KEY_ARN" \ + --key-material "Tr34KeyBlock={CertificateAuthorityPublicKeyIdentifier=$KEY_ARN,WrappingKeyCertificate=$CERTIFICATE,KeyBlockFormat=X9_TR34_2012}" + assert_failure + [[ "$output" == *"ValidationException"* ]] + # The refusal names the forms the service does serve. + [[ "$output" == *"Tr31KeyBlock, KeyCryptogram, DiffieHellmanTr31KeyBlock"* ]] +} diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyTest.java index d4cceeef82..24efd18b8c 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyTest.java @@ -8,15 +8,21 @@ import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.paymentcryptography.PaymentCryptographyClient; import software.amazon.awssdk.services.paymentcryptography.model.Alias; +import software.amazon.awssdk.services.paymentcryptography.model.ExportKeyResponse; +import software.amazon.awssdk.services.paymentcryptography.model.GetParametersForExportResponse; +import software.amazon.awssdk.services.paymentcryptography.model.GetParametersForImportResponse; +import software.amazon.awssdk.services.paymentcryptography.model.ImportKeyResponse; import software.amazon.awssdk.services.paymentcryptography.model.Key; import software.amazon.awssdk.services.paymentcryptography.model.KeyAlgorithm; import software.amazon.awssdk.services.paymentcryptography.model.KeyAttributes; import software.amazon.awssdk.services.paymentcryptography.model.KeyCheckValueAlgorithm; import software.amazon.awssdk.services.paymentcryptography.model.KeyClass; +import software.amazon.awssdk.services.paymentcryptography.model.KeyMaterialType; import software.amazon.awssdk.services.paymentcryptography.model.KeyState; import software.amazon.awssdk.services.paymentcryptography.model.KeyUsage; import software.amazon.awssdk.services.paymentcryptography.model.ListKeysResponse; import software.amazon.awssdk.services.paymentcryptography.model.Tag; +import software.amazon.awssdk.services.paymentcryptography.model.WrappedKeyMaterialFormat; import java.util.ArrayList; import java.util.List; @@ -81,6 +87,20 @@ class PaymentCryptographyTest { return createKey(KeyAlgorithm.TDES_2_KEY); } + /** The key a key block is wrapped under. */ + private static Key createWrappingKey() { + Key key = client.createKey(r -> r + .keyAttributes(a -> a + .keyAlgorithm(KeyAlgorithm.AES_256) + .keyClass(KeyClass.SYMMETRIC_KEY) + .keyUsage(KeyUsage.TR31_K1_KEY_BLOCK_PROTECTION_KEY) + .keyModesOfUse(m -> m.wrap(true).unwrap(true))) + .exportable(true)) + .key(); + keyArns.add(key.keyArn()); + return key; + } + /** A key of the given algorithm, for the data the cipher protects. */ private static Key createKey(KeyAlgorithm algorithm) { Key key = client.createKey(r -> r @@ -146,6 +166,54 @@ class PaymentCryptographyTest { assertThat(read.keyCheckValueAlgorithm()).isEqualTo(KeyCheckValueAlgorithm.ANSI_X9_24); } + @Test + void theImportAndExportParametersAreServed() { + GetParametersForImportResponse importParameters = client.getParametersForImport(r -> r + .keyMaterialType(KeyMaterialType.KEY_CRYPTOGRAM) + .wrappingKeyAlgorithm(KeyAlgorithm.RSA_2048)); + + assertThat(importParameters.importToken()).startsWith("import-token-"); + assertThat(importParameters.wrappingKeyAlgorithm()).isEqualTo(KeyAlgorithm.RSA_2048); + assertThat(importParameters.wrappingKeyCertificate()).isNotBlank(); + assertThat(importParameters.wrappingKeyCertificateChain()).isNotBlank(); + assertThat(importParameters.parametersValidUntilTimestamp()).isNotNull(); + + GetParametersForExportResponse exportParameters = client.getParametersForExport(r -> r + .keyMaterialType(KeyMaterialType.TR34_KEY_BLOCK) + .signingKeyAlgorithm(KeyAlgorithm.RSA_2048)); + + assertThat(exportParameters.exportToken()).startsWith("export-token-"); + assertThat(exportParameters.signingKeyAlgorithm()).isEqualTo(KeyAlgorithm.RSA_2048); + assertThat(exportParameters.signingKeyCertificate()).isNotBlank(); + assertThat(exportParameters.signingKeyCertificateChain()).isNotBlank(); + assertThat(exportParameters.parametersValidUntilTimestamp()).isNotNull(); + } + + @Test + void aKeyLeavesTheServiceAndComesBackThroughTheKeyExchange() { + Key wrapping = createWrappingKey(); + Key key = createAesKey(); + + ExportKeyResponse exported = client.exportKey(r -> r + .exportKeyIdentifier(key.keyArn()) + .keyMaterial(m -> m.tr31KeyBlock(b -> b.wrappingKeyIdentifier(wrapping.keyArn())))); + + assertThat(exported.wrappedKey().wrappedKeyMaterialFormat()) + .isEqualTo(WrappedKeyMaterialFormat.TR31_KEY_BLOCK); + assertThat(exported.wrappedKey().wrappingKeyArn()).isEqualTo(wrapping.keyArn()); + assertThat(exported.wrappedKey().keyMaterial()).isNotBlank(); + assertThat(exported.wrappedKey().keyCheckValue()).isNotBlank(); + + ImportKeyResponse imported = client.importKey(r -> r + .keyMaterial(m -> m.tr31KeyBlock(b -> b + .wrappingKeyIdentifier(wrapping.keyArn()) + .wrappedKeyBlock(exported.wrappedKey().keyMaterial())))); + + assertThat(imported.key().keyArn()).isNotBlank(); + assertThat(imported.key().keyAttributes().keyUsage()) + .isEqualTo(KeyUsage.TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY); + } + @Test void aKeyIsCreatedDisabledAndWithTags() { Key key = client.createKey(r -> r diff --git a/docs/services/index.md b/docs/services/index.md index 71c16f44d5..266c692c19 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -34,7 +34,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [CloudHSM v2](cloudhsmv2.md) | `POST /` + `X-Amz-Target: BaldrApiService.*` | JSON 1.1 | 18 | | [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](payment-cryptography.md) | `POST /` + `X-Amz-Target: PaymentCryptographyControlPlane.*` | JSON 1.0 | 17 | | [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 | diff --git a/docs/services/payment-cryptography-data.md b/docs/services/payment-cryptography-data.md index 796e35be22..6b850a5b0d 100644 --- a/docs/services/payment-cryptography-data.md +++ b/docs/services/payment-cryptography-data.md @@ -130,8 +130,8 @@ client that talks to the control plane does not reach it by accident. - **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. + one the `Emv2000` attributes ask for, is refused as well: it is over the master key and + the ATC, and this service does not implement that construction. - **The card requests are checked against the model.** The account number is twelve to nineteen digits, the expiry is four of them, the service code is three, and the PAN sequence number is two: the EMV ones, as the model states them. A formatted account diff --git a/docs/services/payment-cryptography.md b/docs/services/payment-cryptography.md index a42bb828b7..85c03966cc 100644 --- a/docs/services/payment-cryptography.md +++ b/docs/services/payment-cryptography.md @@ -17,6 +17,11 @@ | `ListAliases` | List the aliases of a region | | `UpdateAlias` | Point an alias name at another key | | `DeleteAlias` | Remove an alias name | +| `ExportKey` | Export a key under a wrapping key, a certificate or an agreed secret | +| `ImportKey` | Import a key under a wrapping key, a certificate or an agreed secret | +| `GetPublicKeyCertificate` | The certificate of an asymmetric key | +| `GetParametersForImport` | The token and the wrapping key certificate an import quotes back | +| `GetParametersForExport` | The token and the signing key certificate an export quotes back | | `TagResource` | Add tags to a key | | `UntagResource` | Remove tags from a key | | `ListTagsForResource` | List the tags of a key | @@ -54,18 +59,86 @@ a key alone, as the reference states them. A request naming a key another way is refused, and the permission check reads the same member the request does. - **Listing by state:** `ListKeys` takes a `KeyState` and answers with the keys in - that state alone, and with every key when it names none. + that state alone, and with every key when it names none. Each key in the list is the + whole key rather than the summary the model names, which a client reads as the summary. +- **The members a request may name that the service does not read:** `CreateKey` and + `ImportKey` take `ReplicationRegions`, and `ImportKey` takes `RequesterComment`, and the + service reads none of them. No replica is made and no approval is recorded, because the + replication and the multi-party approval are not emulated. - **An alias may name no key:** `UpdateAlias` names the key of an alias, and an update that names none removes the key the alias names and leaves the alias. `CreateAlias` refuses an alias without a key, as the reference does, though its model requires only the name. - **Paging:** `ListKeys`, `ListAliases` and `ListTagsForResource` take `MaxResults` and `NextToken`, and answer with one page and the token that asks for the next. +- **The key exchange:** `ExportKey` and `ImportKey` take the form of the key material the + request names, one form per request. A key leaves under a TR-31 block the service wraps + with a key it holds, under an RSA-OAEP cryptogram the receiver's certificate protects, or + under a key the two parties agreed with ECDH; it comes back under the same protections, and + a public key comes back under the certificate that carries it. A key that is not exportable + does not leave, a key pair has no material a key block could carry, and a counterparty's + certificate that the named authority did not sign is refused. An export may name an initial + DUKPT key by its serial number, and the derived key leaves instead of the base derivation + key. The base derivation key may not be exportable itself and still derive that initial key, + which the export guide says the standards allow. +- **The keys a key exchange names:** a TR-31 block's wrapping key must be a key + encryption key that may wrap, and of the family the block's own type names, so a TDES + wrapping key carries a type B block and an AES one a type D block. A key agreement needs + a key agreement key that may derive. The certificate a cryptogram or an agreement names + must be one the named authority signed. A key that is disabled does no work, so it may + not wrap, unwrap, agree or vouch for a certificate. +- **The strength a wrapping key must have:** a wrapping key must be at least as strong as + the key it carries, by the matrix the guide publishes. A TR-31 block's wrapping key is + therefore no weaker than the key it carries, an RSA cryptogram's is capped by its + modulus, so RSA-2048 carries Triple DES but not AES-128, RSA-3072 and RSA-4096 carry + AES-128, and no RSA size carries AES-192 or AES-256, and a key the two parties agreed + is capped by the curve's strength, so P-256 carries no AES-192. +- **The check value of an export:** a key block carries the check value of the key it + carries, and a cryptogram carries none, because it carries no key block at all. +- **The TR-34 and the AS2805 forms are not made.** A request that asks for one of them is + refused with the error that says so, rather than answered with something of another kind, + and the refusal names the forms the service serves. +- **The block headers a request names:** an export may name the modes of use, the + exportability, the version and the optional blocks of the TR-31 block it produces, and + the block carries them. An optional block is written with its length in hexadecimal, and + the length covers the whole block, the identifier and the length included. The optional + blocks take up a whole number of cipher blocks, so a block whose optional blocks are not + aligned carries a padding block that fills the rest. +- **The block headers may only narrow the key.** A request that names modes of use or an + exportability may not give the key a permission it does not have: a key that may only + encrypt is refused an export that says it may decrypt, and a key that is already set to a + stricter exportability is refused a looser one. A key encryption key wraps and unwraps + where another key encrypts and decrypts, so for one the two spellings of a direction are + the same permission. +- **The order of the exportabilities:** the exportability says what the receiver may do with + the key once it has it. `SENSITIVE` is the loosest, for it lets the receiver export under + a key block, a TR-34 block or a cryptogram, `EXPORTABLE` lets it export under a key block + or a TR-34 block only, and `NON_EXPORTABLE` does not let it export at all. +- **The exportability of a key that comes in:** the exportability of the block says whether + the key may leave the service again. An exportable or a sensitive key may, and only a + non-exportable one may not. +- **The modes of use of a key that comes in:** the mode of use character of the block says + what the key may be used for, and both spellings of a direction stand for it. A block + that says `B` gives the key all four of `Encrypt`, `Decrypt`, `Wrap` and `Unwrap`, + whichever use the key has. +- **The origin of a key that comes in:** a key that was imported says it came from outside + the service, which is `EXTERNAL`, and a key the service made says `AWS_PAYMENT_CRYPTOGRAPHY`. +- **Only the type B and type D key blocks are read.** The standard also has the type A and + the type C block, the key variant ones, and the reference reads them on import; this + service refuses them and names the two it reads. +- **The certificate of a key:** `GetPublicKeyCertificate` answers with the certificate and + its chain, and a certificate the service mints is valid for ninety days. +- **The import and export parameters:** `GetParametersForImport` answers with the token an + import quotes back, the wrapping key's certificate and the chain, and the moment the + parameters expire; `GetParametersForExport` answers with the same for an export, over a + signing key. Each token is named for the operation that issued it, and a token is good + until the parameters expire. - **The data plane is a service of its own:** the operations that use a key are on [the data plane's page](payment-cryptography-data.md), which is reached at its own routes. -- **Not yet emulated:** the import and export formats, and the multi-region replication - operations. +- **Not yet emulated:** the multi-region replication operations, the resource policy + operations, the key usage operations, the key restore operation, the multi-party + approval operations and the certificate signing request. ## Configuration diff --git a/src/main/java/io/floci/aws/core/common/RequestConstraintCheck.java b/src/main/java/io/floci/aws/core/common/RequestConstraintCheck.java index cc8fe7ec62..30a40350ef 100644 --- a/src/main/java/io/floci/aws/core/common/RequestConstraintCheck.java +++ b/src/main/java/io/floci/aws/core/common/RequestConstraintCheck.java @@ -118,6 +118,11 @@ public final class RequestConstraintCheck { checkValue(model.path("operations").path(operation).asText(), request, operation); } + /** Whether the model holds the input shape of {@code operation}. */ + public boolean holds(String operation) { + return model.path("operations").has(operation); + } + /** Checks one modeled value without treating it as a whole request. */ public void checkShape(String shapeName, JsonNode value) { checkValue(shapeName, value, shapeName); diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperations.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperations.java index 36b3961b4a..78296844b2 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperations.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperations.java @@ -35,8 +35,8 @@ import static io.floci.aws.services.paymentcryptography.PaymentCryptographyAttri * *

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. + * worse than an error. The EMV 2000 one is the EMV 4.1 tree derivation, which is over the + * master key and the ATC, and this service does not implement it. */ @ApplicationScoped public class PaymentCryptographyAuthCryptogramOperations { @@ -260,11 +260,9 @@ public class PaymentCryptographyAuthCryptogramOperations { 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); + // The shape check settles the derivation attributes, so they are there, and the + // attributes must name exactly one variant. + String variant = soleVariant(request.get("SessionKeyDerivationAttributes")); if (variant == null) { throw validation("SessionKeyDerivationAttributes must specify exactly one variant"); } @@ -285,7 +283,7 @@ public class PaymentCryptographyAuthCryptogramOperations { throw validation("SessionKeyDerivationAttributes." + variant + " is not a recognized variant"); } - JsonNode attrs = skd.get(variant); + JsonNode attrs = request.get("SessionKeyDerivationAttributes").get(variant); String pan = text(attrs, "PrimaryAccountNumber"); String psn = text(attrs, "PanSequenceNumber"); String atc = text(attrs, "ApplicationTransactionCounter"); diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardValidationOperations.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardValidationOperations.java index 786c9dea15..d5ca9050fa 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardValidationOperations.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardValidationOperations.java @@ -234,7 +234,7 @@ public class PaymentCryptographyCardValidationOperations { } /** - * Checks that the key has the mode of use the operation needs. + * The error a card request is refused with. */ private static AwsException validation(String message) { return new AwsException("ValidationException", message, 400); diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyJsonHandler.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyJsonHandler.java index f34a86559c..8872e274dd 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyJsonHandler.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyJsonHandler.java @@ -14,7 +14,7 @@ import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import java.util.Set; +import java.util.function.Supplier; /** * The Payment Cryptography control plane. @@ -35,49 +35,55 @@ public class PaymentCryptographyJsonHandler { this.service = service; } - /** The actions whose requests are checked against the vendored model constraints first. */ - private static final Set MODEL_CHECKED = Set.of( - "CreateKey", "GetKey", "ListKeys", "DeleteKey", - "CreateAlias", "GetAlias", "ListAliases", "UpdateAlias", "DeleteAlias", - "TagResource", "UntagResource", "ListTagsForResource"); + /** The forms the model's export union holds. */ + private static final List EXPORT_UNION = List.of("Tr31KeyBlock", "Tr34KeyBlock", + "KeyCryptogram", "DiffieHellmanTr31KeyBlock", "As2805KeyCryptogram"); + + /** The forms the model's import union holds. */ + private static final List IMPORT_UNION = List.of("RootCertificatePublicKey", + "TrustedCertificatePublicKey", "Tr31KeyBlock", "Tr34KeyBlock", "KeyCryptogram", + "DiffieHellmanTr31KeyBlock", "As2805KeyCryptogram"); public Response handle(String action, JsonNode request, String region) { - if (MODEL_CHECKED.contains(action)) { - PaymentCryptographyRequestShapes.check(action, request); - } - return switch (action) { - case "CreateKey" -> Response.ok(createKey(request, region)).build(); - case "GetKey" -> Response.ok(getKey(request, region)).build(); - case "ListKeys" -> Response.ok(listKeys(request, region)).build(); - case "DeleteKey" -> Response.ok(deleteKey(request, region)).build(); - case "CreateAlias" -> Response.ok(createAlias(request, region)).build(); - case "GetAlias" -> Response.ok(getAlias(request, region)).build(); - case "ListAliases" -> Response.ok(listAliases(request, region)).build(); - case "UpdateAlias" -> Response.ok(updateAlias(request, region)).build(); - case "DeleteAlias" -> Response.ok(deleteAlias(request, region)).build(); - case "TagResource" -> Response.ok(tagResource(request, region)).build(); - case "UntagResource" -> Response.ok(untagResource(request, region)).build(); - case "ListTagsForResource" -> Response.ok(listTagsForResource(request, region)).build(); + // The switch names the operation and nothing else, so an operation this class serves + // later cannot go without its model check: the check reads the name from the action. + Supplier answer = switch (action) { + case "CreateKey" -> () -> createKey(request, region); + case "GetKey" -> () -> getKey(request, region); + case "ListKeys" -> () -> listKeys(request, region); + case "DeleteKey" -> () -> deleteKey(request, region); + case "CreateAlias" -> () -> createAlias(request, region); + case "GetAlias" -> () -> getAlias(request, region); + case "ListAliases" -> () -> listAliases(request, region); + case "UpdateAlias" -> () -> updateAlias(request, region); + case "DeleteAlias" -> () -> deleteAlias(request, region); + case "ExportKey" -> () -> exportKey(request, region); + case "ImportKey" -> () -> importKey(request, region); + case "GetPublicKeyCertificate" -> () -> getPublicKeyCertificate(request, region); + case "GetParametersForImport" -> () -> getParametersForImport(request, region); + case "GetParametersForExport" -> () -> getParametersForExport(request, region); + case "TagResource" -> () -> tagResource(request, region); + case "UntagResource" -> () -> untagResource(request, region); + case "ListTagsForResource" -> () -> listTagsForResource(request, region); default -> throw new AwsException("UnknownOperationException", "Operation " + action + " is not supported by floci", 400); }; + // The vendored model holds every operation it names, so the request is checked against + // the model's own rules without this class listing the operations it serves. The check + // runs after the switch, so an operation the model names and this service does not + // serve is refused as the unknown operation it is, whatever its body says, and it + // runs before the operation does, so a request that breaks the model's rules is + // refused before the operation does any work. + PaymentCryptographyRequestShapes.check(action, request); + return Response.ok(answer.get()).build(); } // ---- keys --------------------------------------------------------------- private Map createKey(JsonNode request, String region) { + // The shape check settles the attributes and the members they must carry, so they are + // there and they carry a usage and the modes of use, as the reference requires. JsonNode attributes = request.get("KeyAttributes"); - if (attributes == null || !attributes.isObject()) { - throw new AwsException("ValidationException", "KeyAttributes is required", 400); - } - // The service requires the usage and the modes of use of a key, as the - // reference does: a key without them says nothing about what it is for. - if (!attributes.hasNonNull("KeyUsage")) { - throw new AwsException("ValidationException", "KeyAttributes.KeyUsage is required", 400); - } - if (!attributes.hasNonNull("KeyModesOfUse")) { - throw new AwsException("ValidationException", "KeyAttributes.KeyModesOfUse is required", 400); - } Map declared = new LinkedHashMap<>(); attributes.fields().forEachRemaining(entry -> { // KeyModesOfUse is a nested structure, not a name: it is read below @@ -376,4 +382,144 @@ public class PaymentCryptographyJsonHandler { } return out; } + + /** + * The key as it leaves the service, in the form the request names. + * + *

The {@code KeyMaterial} union names one form, and the form says how the key is + * protected: a TR-31 block under a key the service holds, an RSA-OAEP cryptogram under + * the receiver's certificate, a TR-34 block the service signs, a block under a key the + * two parties agreed, or an AS2805 cryptogram. + */ + private Map exportKey(JsonNode request, String region) { + // The required members are settled by the shape check before the handler runs, so + // the identifier is read and not checked again. + String keyIdentifier = request.path("ExportKeyIdentifier").asText(); + JsonNode material = request.path("KeyMaterial"); + String form = soleForm(material, EXPORT_UNION, PaymentCryptographyKeyExchange.EXPORT_FORMS, + "exports"); + JsonNode attributes = request.path("ExportAttributes"); + return service.exportKey(region, keyIdentifier, form, members(material.path(form)), + initialKeySerialNumber(attributes), + attributes.path("KeyCheckValueAlgorithm").asText()); + } + + /** The certificate of an asymmetric key. */ + private Map getPublicKeyCertificate(JsonNode request, String region) { + PaymentCryptographyKey key = requiredKey(request, region, "KeyIdentifier"); + return service.publicKeyCertificate(key); + } + + /** + * The parameters a counterparty needs to import a key into this service: the token the + * import quotes back and the certificate the wrapping key is under. + */ + private Map getParametersForImport(JsonNode request, String region) { + return service.parametersForImport(request.path("KeyMaterialType").asText(), + request.path("WrappingKeyAlgorithm").asText(), + request.path("ReuseLastGeneratedToken").asBoolean(false)); + } + + /** + * The parameters a counterparty needs to import a key this service exported: the token + * the export quotes back and the certificate the signing key is under. + */ + private Map getParametersForExport(JsonNode request, String region) { + return service.parametersForExport(request.path("KeyMaterialType").asText(), + request.path("SigningKeyAlgorithm").asText(), + request.path("ReuseLastGeneratedToken").asBoolean(false)); + } + + /** + * The key that comes into the service, in the form the request names. + */ + private Map importKey(JsonNode request, String region) { + JsonNode material = request.path("KeyMaterial"); + String form = soleForm(material, IMPORT_UNION, PaymentCryptographyKeyExchange.IMPORT_FORMS, + "imports"); + PaymentCryptographyKey key = service.importKey(region, form, members(material.path(form)), + request.path("KeyCheckValueAlgorithm").asText(), + request.path("Enabled").asBoolean(true), tagsOf(request)); + return Map.of("Key", keyObject(key)); + } + + /** + * The serial number of the initial key the request asks to be derived. + * + *

The export attributes name the kind of key that leaves: an initial key for the + * DUKPT derivation is derived from the base derivation key and the serial number the + * request gives, and it is that derived key which leaves. + * + * @param attributes the export attributes of the request + * @return the serial number, or an empty string when the request names no initial key + */ + private static String initialKeySerialNumber(JsonNode attributes) { + JsonNode initial = attributes.path("ExportDukptInitialKey"); + if (initial.isMissingNode() || initial.isNull()) { + return ""; + } + // The serial number is required by the model, so the shape check has settled it. + return initial.path("KeySerialNumber").asText(); + } + + /** + * The one form of the key material union the request names. + * + *

The union holds a member per form, and a request names exactly one of them. Several + * at once is not the same as none: the request says which one it meant, and it cannot be + * more than one. + */ + private static String soleForm(JsonNode material, List union, List served, + String what) { + List named = new ArrayList<>(); + for (String form : union) { + if (material.has(form) && !material.path(form).isNull()) { + named.add(form); + } + } + if (named.size() != 1) { + throw new AwsException("ValidationException", + "KeyMaterial must specify exactly one variant (" + String.join(", ", union) + ")", + 400); + } + String form = named.get(0); + if (!served.contains(form)) { + throw new AwsException("ValidationException", + "KeyMaterial." + form + " is not a form the service " + what + " (" + + String.join(", ", served) + ")", 400); + } + return form; + } + + /** The members of a form, as the service reads them. */ + private static Map members(JsonNode node) { + Map out = new LinkedHashMap<>(); + if (node == null || !node.isObject()) { + return out; + } + node.properties().forEach(entry -> out.put(entry.getKey(), value(entry.getValue()))); + return out; + } + + /** One member of a form, as the service reads it. */ + private static Object value(JsonNode node) { + if (node == null || node.isNull()) { + return null; + } + if (node.isObject()) { + return members(node); + } + if (node.isArray()) { + List values = new ArrayList<>(); + node.forEach(child -> values.add(value(child))); + return values; + } + if (node.isBoolean()) { + return node.asBoolean(); + } + if (node.isNumber()) { + return node.asText(); + } + return node.asText(); + } } diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchange.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchange.java new file mode 100644 index 0000000000..13aa65061d --- /dev/null +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchange.java @@ -0,0 +1,1176 @@ +package io.floci.aws.services.paymentcryptography; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.acm.CertificateGenerator; +import io.floci.aws.services.paymentcryptography.crypto.Certificates; +import io.floci.aws.services.paymentcryptography.crypto.ConcatKdf; +import io.floci.aws.services.paymentcryptography.crypto.Ecdh; +import io.floci.aws.services.paymentcryptography.crypto.RsaOaep; +import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey; +import org.bouncycastle.asn1.x500.X500Name; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.cert.X509Certificate; +import java.security.interfaces.ECKey; +import java.security.interfaces.ECPrivateKey; +import java.security.interfaces.ECPublicKey; +import java.security.interfaces.RSAKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; +import java.time.Clock; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * The key exchange: the forms a key may leave the service in, the forms it may come back + * in, and the certificates the two parties exchange to do it. + * + *

The service's own {@code KeyMaterial} union names one form per request, and each form + * protects the key differently: + * + *

    + *
  • {@code Tr31KeyBlock}: a TR-31 key block under a key the service holds. + *
  • {@code KeyCryptogram}: the key material under the receiver's RSA certificate. + *
  • {@code Tr34KeyBlock}: a TR-31 key block, signed by the service and wrapped for the + * receiver under their certificate. + *
  • {@code DiffieHellmanTr31KeyBlock}: a TR-31 key block under a key the two parties + * agreed with ECDH. + *
  • {@code As2805KeyCryptogram}: the key material under a key encryption key, bound to + * its purpose by the AS2805 variant. + *
+ * + *

The import takes the same forms and two more: a root or trusted public key may arrive + * as a certificate rather than as a block. + * + *

The certificates the exchange mints are the service's own. The real service issues them + * from a certificate authority; this one mints a self-signed certificate over a key pair it + * makes for the occasion, which is enough for two parties that trust each other's copy of it. + */ +final class PaymentCryptographyKeyExchange { + + /** The forms the export produces, in the order the service lists them. */ + static final List EXPORT_FORMS = List.of( + "Tr31KeyBlock", + "KeyCryptogram", + "DiffieHellmanTr31KeyBlock"); + + /** The forms the import takes, in the order the service lists them. */ + static final List IMPORT_FORMS = List.of( + "Tr31KeyBlock", + "KeyCryptogram", + "RootCertificatePublicKey", + "TrustedCertificatePublicKey", + "DiffieHellmanTr31KeyBlock"); + + /** The key material types that take import parameters. */ + private static final List IMPORT_PARAMETER_TYPES = List.of("KEY_CRYPTOGRAM"); + + /** The key material types that take export parameters. */ + private static final List EXPORT_PARAMETER_TYPES = List.of("TR34_KEY_BLOCK"); + + /** The prefix an import token's name carries, as the model states it. */ + private static final String IMPORT_TOKEN_PREFIX = "import-token-"; + + /** The prefix an export token's name carries, as the model states it. */ + private static final String EXPORT_TOKEN_PREFIX = "export-token-"; + + /** + * How long a certificate the service mints is valid, in seconds. + * + *

The reference keeps a certificate for ninety days, so that is how long one the + * service mints is good for. + */ + private static final long CERTIFICATE_VALIDITY_SECONDS = 90L * 24 * 3600; + + /** + * How long an export token is good for, in milliseconds. + * + *

The model says an import token expires after thirty days, and an export token is + * given the same life. + */ + static final long EXPORT_TOKEN_TTL_MS = 30L * 24 * 3600 * 1000; + + /** How long an import token is good for, in milliseconds. */ + static final long IMPORT_TOKEN_TTL_MS = 30L * 24 * 3600 * 1000; + + /** The RSA moduli the service makes a wrapping key of. */ + private static final Map RSA_BITS = + Map.of("RSA_2048", 2048, "RSA_3072", 3072, "RSA_4096", 4096); + + /** The hexadecimal the key material and the cryptograms are written in. */ + private static final HexFormat HEX = HexFormat.of(); + + /** The hexadecimal a cryptogram is written in: the capitals the reference writes it in. */ + private static final HexFormat HEX_UPPER = HexFormat.of().withUpperCase(); + + /** The export tokens the service has issued, by token. */ + private final Map exportTokens = new ConcurrentHashMap<>(); + + /** The import tokens the service has issued, by token. */ + private final Map importTokens = new ConcurrentHashMap<>(); + + /** The last export parameters issued, by material type and algorithm. */ + private final Map lastExportParameters = new ConcurrentHashMap<>(); + + /** The last import parameters issued, by material type and algorithm. */ + private final Map lastImportParameters = new ConcurrentHashMap<>(); + + /** The service whose keys the exchange looks up. */ + private final PaymentCryptographyService service; + + /** The randomness the key pairs and the tokens are made from. */ + private final SecureRandom random = new SecureRandom(); + + /** The generator the certificates are minted with. */ + private final CertificateGenerator certificates; + + /** The clock the times come from. */ + private final Clock clock; + + PaymentCryptographyKeyExchange(PaymentCryptographyService service, CertificateGenerator certificates, + Clock clock) { + this.service = service; + this.certificates = certificates; + this.clock = clock; + } + + /** + * A certificate over a key pair, signed by an issuer. + * + *

The issuer signs the certificate, so a party that trusts the issuer's public key + * trusts the certificate: that is how the key exchange's certificate authority vouches + * for the other party's certificate. + */ + private Certificates.Minted mint(PublicKey subjectPublicKey, String subjectCommonName, + PrivateKey issuerPrivateKey, String issuerCommonName, + Instant notBefore, Instant notAfter) { + try { + X500Name subject = new X500Name("CN=" + subjectCommonName); + X500Name issuer = new X500Name("CN=" + issuerCommonName); + X509Certificate certificate = certificates.signCertificate(subject, subjectPublicKey, + issuer, issuerPrivateKey, List.of(), false, null, notBefore, notAfter); + byte[] der = certificate.getEncoded(); + return new Certificates.Minted(der, Certificates.toPem(der)); + } catch (IOException e) { + throw new IllegalStateException("cannot mint a certificate", e); + } catch (Exception e) { + throw new IllegalStateException("cannot mint a certificate", e); + } + } + + /** A certificate over a key pair, signed by the key pair itself. */ + private Certificates.Minted mintSelfSigned(KeyPair keyPair, String commonName, + Instant notBefore, Instant notAfter) { + return mint(keyPair.getPublic(), commonName, keyPair.getPrivate(), commonName, + notBefore, notAfter); + } + + /** A parameter the service issued: the key pair behind it and the token that names it. */ + private static final class Issued { + private final String token; + private final PrivateKey privateKey; + private final byte[] certificateDer; + private final String algorithm; + /** The kind of key material the token was issued for. */ + private final String materialType; + private final long validUntilMs; + + Issued(String token, PrivateKey privateKey, byte[] certificateDer, String algorithm, + String materialType, long validUntilMs) { + this.token = token; + this.privateKey = privateKey; + this.certificateDer = certificateDer; + this.algorithm = algorithm; + this.materialType = materialType; + this.validUntilMs = validUntilMs; + } + } + + /** What an import brings in: the attributes of the key and its material. */ + record Imported(String algorithm, String usage, Map modes, boolean exportable, + byte[] material, String publicKeyBase64, String privateKeyBase64, + String certificatePem, String keyClass) { + } + + /** What an export produces: the material, its format, and the key it protects. */ + record Exported(String material, String format, String wrappingKeyArn) { + } + + // ---- the export ---------------------------------------------------------- + + /** + * The key that leaves the service, in the form the request names. + * + * @param region the region the key is in + * @param key the key that leaves + * @param form the form the request names, one of {@link #EXPORT_FORMS} + * @param material the members of the form + * @return the material, its format, and the key that protects it + */ + Exported export(String region, PaymentCryptographyKey key, String form, + Map material) { + byte[] clear = clearMaterial(key); + return switch (form) { + case "Tr31KeyBlock" -> exportTr31(region, key, clear, material); + case "KeyCryptogram" -> exportCryptogram(region, key, clear, material); + case "DiffieHellmanTr31KeyBlock" -> exportEcdh(region, key, clear, material); + default -> throw validation("KeyMaterial." + form + " is not a form the service exports (" + + String.join(", ", EXPORT_FORMS) + ")"); + }; + } + + /** A TR-31 key block, under a key the caller names. */ + private Exported exportTr31(String region, PaymentCryptographyKey key, byte[] clear, + Map material) { + String wrappingKeyIdentifier = text(material, "WrappingKeyIdentifier"); + PaymentCryptographyKey protection = usableKey(wrappingKeyIdentifier, region); + if (!PaymentCryptographyService.isKeyEncryptionKey(protection.getKeyUsage())) { + throw validation("the key " + protection.getArn() + " is not a key encryption key, so " + + "it cannot wrap a key block"); + } + if (!PaymentCryptographyService.mayWrap(protection)) { + throw validation("the key " + protection.getArn() + " does not have the mode of use " + + "Wrap, which it needs to wrap a key"); + } + String tooWeak = PaymentCryptographyKeyStrength.refusal( + protection.getKeyAlgorithm(), key.getKeyAlgorithm()); + if (tooWeak != null) { + throw validation(tooWeak); + } + Map headers = object(material, "KeyBlockHeaders"); + String block = PaymentCryptographyTr31.wrap(clear, + PaymentCryptographyKeyRules.material(protection), + PaymentCryptographyService.isAes(protection), + PaymentCryptographyService.algorithmByte(key), + PaymentCryptographyService.usageCode(key), + modeCode(key, headers), + exportabilityCode(key, headers), + versionCode(headers), + optionalBlocks(headers)); + return new Exported(block, "TR31_KEY_BLOCK", protection.getArn()); + } + + /** The key material, encrypted under the receiver's certificate. */ + private Exported exportCryptogram(String region, PaymentCryptographyKey key, byte[] clear, + Map material) { + // The shape check settles the members the model requires and the values it names, + // so the certificate and the authority are there and the spec is one of the two. + String certText = text(material, "WrappingKeyCertificate"); + String caIdentifier = text(material, "CertificateAuthorityPublicKeyIdentifier"); + PaymentCryptographyKey caKey = usableKey(caIdentifier, region); + PublicKey wrappingKey = verifiedCertificate(certText, caKey, "the wrapping key certificate") + .getPublicKey(); + + // The wrapping key has to be at least as strong as the key it protects, and the size + // of the RSA modulus is what decides that. + int modulusBits = modulusBitsOf(wrappingKey); + String tooWeak = PaymentCryptographyKeyStrength.refusal( + PaymentCryptographyKeyStrength.rsaBitsOf(modulusBits), + PaymentCryptographyKeyStrength.bitsOf(key.getKeyAlgorithm()), + "RSA_" + modulusBits, key.getKeyAlgorithm()); + if (tooWeak != null) { + throw validation(tooWeak); + } + String spec = text(material, "WrappingSpec"); + String digest = RsaOaep.digestFor(spec.isEmpty() ? "RSA_OAEP_SHA_256" : spec); + byte[] encrypted = RsaOaep.encrypt(wrappingKey, clear, digest); + return new Exported(HEX_UPPER.formatHex(encrypted), "KEY_CRYPTOGRAM", null); + } + + + /** A TR-31 key block under a key the two parties agreed with ECDH. */ + private Exported exportEcdh(String region, PaymentCryptographyKey key, byte[] clear, + Map material) { + Agreed agreed = agreed(region, material); + + // The derived key is the wrapping key, so it has to be at least as strong as the key it + // protects. The key agreement is only as strong as the curve it was made on, so the + // weaker of the two decides. + int curveBits = Math.min( + PaymentCryptographyKeyStrength.eccBitsOf(agreed.serviceKey().getKeyAlgorithm()), + PaymentCryptographyKeyStrength.eccBitsOf((ECKey) agreed.counterpartyKey())); + int derivedBits = Math.min( + PaymentCryptographyKeyStrength.bitsOf(agreed.deriveAlgorithm().name()), curveBits); + String tooWeak = PaymentCryptographyKeyStrength.refusal(derivedBits, + PaymentCryptographyKeyStrength.bitsOf(key.getKeyAlgorithm()), + agreed.deriveAlgorithm().name(), key.getKeyAlgorithm()); + if (tooWeak != null) { + throw validation(tooWeak); + } + + Map headers = object(material, "KeyBlockHeaders"); + String block = PaymentCryptographyTr31.wrap(clear, agreed.derived(), + agreed.deriveAlgorithm().aes, + PaymentCryptographyService.algorithmByte(key), + PaymentCryptographyService.usageCode(key), + modeCode(key, headers), + exportabilityCode(key, headers), + versionCode(headers), + optionalBlocks(headers)); + return new Exported(block, "TR31_KEY_BLOCK", null); + } + + + // ---- the import ---------------------------------------------------------- + + /** + * The key that comes into the service, in the form the request names. + * + * @param region the region the key comes into + * @param form the form the request names, one of {@link #IMPORT_FORMS} + * @param material the members of the form + * @return what the key is + */ + Imported importKey(String region, String form, Map material) { + return switch (form) { + case "Tr31KeyBlock" -> importTr31(region, material); + case "KeyCryptogram" -> importCryptogram(material); + case "RootCertificatePublicKey" -> importPublicKey(region, material, ""); + case "TrustedCertificatePublicKey" -> importPublicKey(region, material, + text(material, "CertificateAuthorityPublicKeyIdentifier")); + case "DiffieHellmanTr31KeyBlock" -> importEcdh(region, material); + default -> throw validation("KeyMaterial." + form + " is not a form the service imports (" + + String.join(", ", IMPORT_FORMS) + ")"); + }; + } + + /** A key out of a TR-31 key block. */ + private Imported importTr31(String region, Map material) { + String wrappingKeyIdentifier = text(material, "WrappingKeyIdentifier"); + String block = text(material, "WrappedKeyBlock"); + PaymentCryptographyKey protection = usableKey(wrappingKeyIdentifier, region); + if (!PaymentCryptographyService.isKeyEncryptionKey(protection.getKeyUsage())) { + throw validation("the key " + protection.getArn() + " is not a key encryption key, so " + + "it cannot unwrap a key block"); + } + if (!PaymentCryptographyService.mayUnwrap(protection)) { + throw validation("the key " + protection.getArn() + " does not have the mode of use " + + "Unwrap, which it needs to unwrap a key"); + } + // The block type picks the derivation, and the derivation needs a key encryption key of + // the matching family. + boolean blockIsAes = PaymentCryptographyTr31.typeOf(block); + if (PaymentCryptographyService.isAes(protection) != blockIsAes) { + throw validation("a type " + PaymentCryptographyTr31.typeName(block) + " key block needs " + + (blockIsAes ? "an AES" : "a TDES") + " wrapping key, but " + + protection.getKeyId() + " is " + protection.getKeyAlgorithm()); + } + byte[] material2; + try { + material2 = PaymentCryptographyTr31.unwrap(block, + PaymentCryptographyKeyRules.material(protection)); + } catch (RuntimeException e) { + throw validation("the key block did not open under " + protection.getKeyId() + ": " + + e.getMessage()); + } + String usage = PaymentCryptographyTr31.usageOf(block); + String mode = PaymentCryptographyTr31.modeOf(block); + boolean exportable = exportableOnImport(PaymentCryptographyTr31.exportabilityOf(block)); + String algorithm = PaymentCryptographyService.algorithmOf(block, material2.length); + // The wrapping key has to be at least as strong as the key it protects, the + // same rule the export enforces. + String tooWeak = PaymentCryptographyKeyStrength.refusal( + protection.getKeyAlgorithm(), algorithm); + if (tooWeak != null) { + throw validation(tooWeak); + } + return new Imported(algorithm, PaymentCryptographyService.usageName(usage), + PaymentCryptographyService.modesFor(mode), + exportable, material2, null, null, null, "SYMMETRIC_KEY"); + } + + /** + * Whether a key that comes in under a block may leave the service again. + * + *

The exportability of the block says it: an exportable key may leave, and a + * sensitive one may leave under a key that is trusted, so it may leave too. Only the + * non-exportable one stays. + * + * @param exportability the exportability character of the block + * @return whether the key may leave the service again + */ + private static boolean exportableOnImport(String exportability) { + return !"N".equals(exportability); + } + + /** A key out of an RSA-OAEP cryptogram. */ + private Imported importCryptogram(Map material) { + // The shape check settles the members the model requires and the values it names, + // so the attributes are there, the cryptogram is hexadecimal and the spec is one of + // the two. + Map attributes = object(material, "KeyAttributes"); + String algorithm = String.valueOf(attributes.get("KeyAlgorithm")); + PaymentCryptographyKeyAlgorithm keyAlgorithm = + PaymentCryptographyKeyAlgorithm.from(algorithm); + if (keyAlgorithm == null || !keyAlgorithm.symmetric()) { + throw validation("KeyAlgorithm '" + algorithm + "' is not a symmetric algorithm this " + + "service imports (TDES_2KEY, TDES_3KEY, AES_128, AES_192, AES_256)"); + } + String cryptogram = text(material, "WrappedKeyCryptogram"); + String spec = text(material, "WrappingSpec"); + String digest = RsaOaep.digestFor(spec.isEmpty() ? "RSA_OAEP_SHA_256" : spec); + String usage = String.valueOf(attributes.get("KeyUsage")); + // The token is taken last, so a request that is refused for any other reason does not + // spend it. + String token = text(material, "ImportToken"); + Issued issued = take(importTokens, token, "KEY_CRYPTOGRAM"); + if (issued == null) { + throw notFound(token.isEmpty() ? "(missing)" : token); + } + byte[] clear; + try { + clear = RsaOaep.decrypt(issued.privateKey, HEX.parseHex(cryptogram), digest); + } catch (RuntimeException e) { + throw validation("the cryptogram did not open under the import token: " + e.getMessage()); + } + if (clear.length != keyAlgorithm.bytes) { + throw validation("the cryptogram carries " + clear.length + " bytes of key, but " + + algorithm + " needs " + keyAlgorithm.bytes); + } + Map modes = modesOf(attributes); + // The exportability is a member of the form, beside the attributes and not inside + // them, and the model requires it. + boolean exportable = !Boolean.FALSE.equals(material.get("Exportable")); + return new Imported(algorithm, usage, modes, exportable, clear, null, null, null, + "SYMMETRIC_KEY"); + } + + + + /** + * The key the two parties agreed, and what the agreement was made with. + * + *

The service's own key has to be a key agreement key that may derive, the + * counterparty's certificate has to be one the named authority signed, and the two have to + * be on the same curve. + * + * @param region the region the keys are in + * @param material the form the request names + * @return the agreed key and what it was agreed with + */ + private Agreed agreed(String region, Map material) { + String privateKeyIdentifier = text(material, "PrivateKeyIdentifier"); + PaymentCryptographyKey serviceKey = usableKey(privateKeyIdentifier, region); + // The key that agrees has to be a key agreement key, and it has to be allowed to + // derive: a key of another purpose may not be named for an agreement. + PaymentCryptographyKeyRules.requireUsage(serviceKey, + List.of("TR31_K3_ASYMMETRIC_KEY_FOR_KEY_AGREEMENT"), "complete a key agreement"); + PaymentCryptographyKeyRules.requireMode(serviceKey, "DeriveKey", "complete a key agreement"); + PrivateKey privateKey = privateKeyOf(serviceKey); + if (privateKey == null) { + throw validation("the key " + serviceKey.getArn() + " has no private half, so it cannot " + + "complete a key agreement"); + } + if (!(privateKey instanceof ECPrivateKey)) { + throw validation("the key " + serviceKey.getArn() + " has a " + privateKey.getAlgorithm() + + " private key, not an elliptic curve one, so it cannot complete a key " + + "agreement"); + } + String caIdentifier = text(material, "CertificateAuthorityPublicKeyIdentifier"); + PaymentCryptographyKey caKey = usableKey(caIdentifier, region); + String certText = text(material, "PublicKeyCertificate"); + X509Certificate counterparty = verifiedCertificate(certText, caKey, + "the public key certificate"); + PublicKey counterpartyKey = counterparty.getPublicKey(); + if (!(counterpartyKey instanceof ECPublicKey)) { + throw validation("the public key certificate carries a " + counterpartyKey.getAlgorithm() + + " key, not an EC one"); + } + PaymentCryptographyKeyAlgorithm deriveAlgorithm = deriveAlgorithm(material); + byte[] secret; + try { + secret = Ecdh.agree((ECPrivateKey) privateKey, (ECPublicKey) counterpartyKey); + } catch (GeneralSecurityException e) { + throw validation("the key agreement failed: " + e.getMessage()); + } + return new Agreed(derive(deriveAlgorithm, secret, material), serviceKey, deriveAlgorithm, + counterpartyKey); + } + + /** The algorithm the agreed key is derived in. */ + private static PaymentCryptographyKeyAlgorithm deriveAlgorithm(Map material) { + String name = text(material, "DeriveKeyAlgorithm"); + PaymentCryptographyKeyAlgorithm algorithm = PaymentCryptographyKeyAlgorithm.from(name); + if (algorithm == null || !algorithm.symmetric()) { + throw validation("KeyMaterial.DiffieHellmanTr31KeyBlock.DeriveKeyAlgorithm is '" + + name + "', which is not a symmetric algorithm this service supports " + + "(TDES_2KEY, TDES_3KEY, AES_128, AES_192, AES_256)"); + } + return algorithm; + } + + /** The agreed key, derived from the secret the two parties made. */ + private static byte[] derive(PaymentCryptographyKeyAlgorithm algorithm, byte[] secret, + Map material) { + String kdf = text(material, "KeyDerivationFunction"); + if (!"NIST_SP800".equals(kdf) && !"ANSI_X963".equals(kdf)) { + throw validation("KeyMaterial.DiffieHellmanTr31KeyBlock.KeyDerivationFunction '" + kdf + + "' not supported (NIST_SP800, ANSI_X963)"); + } + String hash = text(material, "KeyDerivationHashAlgorithm"); + if (!"SHA_256".equals(hash) && !"SHA_384".equals(hash) && !"SHA_512".equals(hash)) { + throw validation("KeyMaterial.DiffieHellmanTr31KeyBlock." + + "KeyDerivationHashAlgorithm '" + hash + "' not supported (SHA_256, SHA_384, " + + "SHA_512)"); + } + Map derivationData = object(material, "DerivationData"); + String sharedInformation = derivationData == null + ? "" : text(derivationData, "SharedInformation"); + if (sharedInformation.isEmpty() || !isHex(sharedInformation)) { + throw validation("KeyMaterial.DiffieHellmanTr31KeyBlock.DerivationData." + + "SharedInformation must be a hexadecimal string"); + } + return "ANSI_X963".equals(kdf) + ? ConcatKdf.deriveX963(hash, secret, HEX.parseHex(sharedInformation), algorithm.bytes) + : ConcatKdf.derive(hash, secret, HEX.parseHex(sharedInformation), algorithm.bytes); + } + + /** The key the two parties agreed, and the keys they agreed it with. */ + private record Agreed(byte[] derived, PaymentCryptographyKey serviceKey, + PaymentCryptographyKeyAlgorithm deriveAlgorithm, PublicKey counterpartyKey) { + } + + /** A key out of a block the two parties agreed with ECDH. */ + private Imported importEcdh(String region, Map material) { + String block = text(material, "WrappedKeyBlock"); + Agreed agreed = agreed(region, material); + + byte[] clear; + try { + clear = PaymentCryptographyTr31.unwrap(block, agreed.derived()); + } catch (RuntimeException e) { + throw validation("the key block did not open under the key the two parties agreed: " + + e.getMessage()); + } + String usage = PaymentCryptographyTr31.usageOf(block); + String mode = PaymentCryptographyTr31.modeOf(block); + boolean exportable = exportableOnImport(PaymentCryptographyTr31.exportabilityOf(block)); + String algorithm = PaymentCryptographyService.algorithmOf(block, clear.length); + // The derived key protects the imported one, so it has to be as strong as it. + int derivedBits = Math.min( + PaymentCryptographyKeyStrength.bitsOf(agreed.deriveAlgorithm().name()), + Math.min( + PaymentCryptographyKeyStrength.eccBitsOf( + agreed.serviceKey().getKeyAlgorithm()), + PaymentCryptographyKeyStrength.eccBitsOf((ECKey) agreed.counterpartyKey()))); + String tooWeak = PaymentCryptographyKeyStrength.refusal(derivedBits, + PaymentCryptographyKeyStrength.bitsOf(algorithm), + agreed.deriveAlgorithm().name(), algorithm); + if (tooWeak != null) { + throw validation(tooWeak); + } + return new Imported(algorithm, PaymentCryptographyService.usageName(usage), + PaymentCryptographyService.modesFor(mode), + exportable, clear, null, null, null, "SYMMETRIC_KEY"); + } + + + // ---- the certificates ---------------------------------------------------- + + + /** + * The certificate of an asymmetric key. + * + *

A key that arrived with a certificate keeps it. A key the service made has none, so + * it gets a self-signed one over its own public half. + * + *

The certificate the service mints is valid for ninety days, which is how long the + * reference keeps one, and it is valid from an hour ago so that a clock a little behind + * the service's still accepts it. + */ + Map publicKeyCertificate(PaymentCryptographyKey key) { + String pem = key.getKeyCertificatePem(); + if (pem == null || pem.isEmpty()) { + PublicKey publicKey = publicKeyOf(key); + if (publicKey == null) { + throw validation("the key " + key.getKeyId() + " has no public key"); + } + PrivateKey privateKey = privateKeyOf(key); + if (privateKey == null) { + // The certificate is signed with the key's own private half, and a key that + // has only a public half has none to sign it with. + throw validation("the key " + key.getKeyId() + " has no private key, so it has no " + + "certificate to sign"); + } + pem = mintSelfSigned(new KeyPair(publicKey, privateKey), "floci", + clock.instant().minusSeconds(3600), + clock.instant().plusSeconds(CERTIFICATE_VALIDITY_SECONDS)).pem(); + } + Map out = new LinkedHashMap<>(); + // The reference names the member KeyCertificate. + out.put("KeyCertificate", Certificates.pemBase64(pem)); + // The certificate is its own chain: the service signs with a certificate of its own, + // so there is no authority above it to name. + out.put("KeyCertificateChain", Certificates.pemBase64(pem)); + return out; + } + + // ---- helpers ------------------------------------------------------------- + + /** The public half of an asymmetric key, or null when it has none. */ + static PublicKey publicKeyOf(PaymentCryptographyKey key) { + if (key == null || key.getKeyPublicKeyBase64() == null + || key.getKeyPublicKeyBase64().isEmpty()) { + return null; + } + try { + byte[] der = Base64.getDecoder().decode(key.getKeyPublicKeyBase64()); + return KeyFactory.getInstance(keyFactoryAlgorithm(key)).generatePublic( + new X509EncodedKeySpec(der)); + } catch (GeneralSecurityException | IllegalArgumentException e) { + throw validation("the public key of " + key.getKeyId() + " does not parse: " + + e.getMessage()); + } + } + + /** The private half of an asymmetric key, or null when it has none. */ + static PrivateKey privateKeyOf(PaymentCryptographyKey key) { + if (key == null || key.getKeyPrivateKeyBase64() == null + || key.getKeyPrivateKeyBase64().isEmpty()) { + return null; + } + try { + byte[] der = Base64.getDecoder().decode(key.getKeyPrivateKeyBase64()); + return KeyFactory.getInstance(keyFactoryAlgorithm(key)).generatePrivate( + new PKCS8EncodedKeySpec(der)); + } catch (GeneralSecurityException | IllegalArgumentException e) { + throw validation("the private key of " + key.getKeyId() + " does not parse: " + + e.getMessage()); + } + } + + /** The name the key factory knows the key's algorithm by. */ + private static String keyFactoryAlgorithm(PaymentCryptographyKey key) { + PaymentCryptographyKeyAlgorithm algorithm = + PaymentCryptographyKeyAlgorithm.from(key.getKeyAlgorithm()); + if (algorithm != null && algorithm.rsa) { + return "RSA"; + } + return "EC"; + } + + /** + * The certificate a counterparty brought, checked against the authority that signed it. + * + *

The authority has to be allowed to verify, its public key has to be there, the + * signature has to be the authority's, and the certificate has to be inside its validity + * window: a certificate that has expired protects nothing. + * + * @param certText the certificate, in any of the shapes a certificate travels in + * @param caKey the key of the authority that is to have signed it + * @param what the certificate is for, in words the caller can act on + * @return the certificate + */ + private static X509Certificate verifiedCertificate(String certText, PaymentCryptographyKey caKey, + String what) { + requireVerify(caKey, "verifying a certificate"); + PublicKey caPublicKey = publicKeyOf(caKey); + if (caPublicKey == null) { + throw validation("the certificate authority " + caKey.getArn() + " has no public key to " + + "verify the certificate against"); + } + X509Certificate certificate; + try { + certificate = Certificates.parseCertificate(certText); + } catch (RuntimeException e) { + throw validation(what + " is not a certificate: " + e.getMessage()); + } + try { + certificate.verify(caPublicKey); + } catch (GeneralSecurityException e) { + throw validation(what + " is not signed by the certificate authority " + + caKey.getArn() + ": " + e.getMessage()); + } + try { + certificate.checkValidity(); + } catch (GeneralSecurityException e) { + throw validation(what + " is outside its validity window: " + e.getMessage()); + } + return certificate; + } + + /** The size of an RSA modulus, in bits. */ + private static int modulusBitsOf(PublicKey key) { + if (!(key instanceof RSAKey rsa)) { + throw validation("the wrapping key certificate carries a " + key.getAlgorithm() + + " key, not an RSA one"); + } + return rsa.getModulus().bitLength(); + } + + /** The algorithm a certificate's public key is of. */ + private static String algorithmOf(PublicKey key) { + if (key instanceof RSAKey rsa) { + int bits = rsa.getModulus().bitLength(); + return switch (bits) { + case 2048 -> "RSA_2048"; + case 3072 -> "RSA_3072"; + case 4096 -> "RSA_4096"; + default -> "RSA_" + bits; + }; + } + int fieldBits = ((ECKey) key).getParams().getCurve().getField().getFieldSize(); + return switch (fieldBits) { + case 256 -> "ECC_NIST_P256"; + case 384 -> "ECC_NIST_P384"; + case 521 -> "ECC_NIST_P521"; + default -> "ECC_NIST_" + fieldBits; + }; + } + + /** The certificate a caller brought, in PEM. */ + private static String certificatePem(String certText) { + try { + X509Certificate certificate = Certificates.parseCertificate(certText); + return Certificates.toPem(certificate.getEncoded()); + } catch (GeneralSecurityException | RuntimeException e) { + throw validation("the public key certificate is not a certificate: " + e.getMessage()); + } + } + + /** The clear material of a key, which an export needs. */ + private static byte[] clearMaterial(PaymentCryptographyKey key) { + return PaymentCryptographyKeyRules.material(key); + } + + /** The modes of use the attributes name, as the service reads them. */ + private static Map modesOf(Map attributes) { + Map modes = new LinkedHashMap<>(); + Object declared = attributes.get("KeyModesOfUse"); + if (declared instanceof Map map) { + for (Map.Entry entry : map.entrySet()) { + modes.put(String.valueOf(entry.getKey()), + Boolean.TRUE.equals(entry.getValue())); + } + } + return modes; + } + + /** A member of the material, as text. */ + private static String text(Map material, String name) { + Object value = material == null ? null : material.get(name); + return value == null ? "" : String.valueOf(value); + } + + /** A member of the material, as a map. */ + @SuppressWarnings("unchecked") + private static Map object(Map material, String name) { + Object value = material == null ? null : material.get(name); + return value instanceof Map map ? (Map) map : Map.of(); + } + + /** Whether a string is hexadecimal. */ + private static boolean isHex(String text) { + if (text == null || text.isEmpty() || text.length() % 2 != 0) { + return false; + } + for (int i = 0; i < text.length(); i++) { + char c = text.charAt(i); + boolean hex = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); + if (!hex) { + return false; + } + } + return true; + } + + /** + * The parameter a token names, when it is one this service issued for that kind of + * material and it has not expired. + * + *

A token stays usable until it expires: a caller that asks for parameters once may + * import several keys under them. + * + * @param tokens the tokens the service has issued + * @param token the token the request quotes + * @param materialType the kind of material the token must have been issued for + * @return the parameter, or null when the token is not one + */ + private Issued take(Map tokens, String token, String materialType) { + if (token == null || token.isEmpty()) { + return null; + } + Issued issued = tokens.get(token); + if (issued == null || !issued.materialType.equals(materialType)) { + return null; + } + if (issued.validUntilMs < clock.millis()) { + tokens.remove(token); + return null; + } + return issued; + } + + /** + * The number of tokens the service holds. + * + *

For the test that watches the expired ones swept. + * + * @return how many tokens are held + */ + int issuedTokenCount() { + return exportTokens.size() + importTokens.size(); + } + + /** + * Drop the tokens that have expired. + * + *

A token that was issued and never quoted again would otherwise stay for the life of + * the process, and it holds a private key. The last parameters issued are swept with the + * tokens, because they hold the same key. + * + * @param tokens the tokens the service has issued + * @param last the last parameters issued, which hold a token of their own + * @param now the moment the tokens that have expired are dropped at + */ + private static void sweep(Map tokens, Map last, long now) { + tokens.values().removeIf(issued -> issued.validUntilMs < now); + last.values().removeIf(issued -> issued.validUntilMs < now); + } + + /** + * A token name the counterparty quotes back. + * + *

The name says which operation issued it, because the model gives the two kinds + * their own patterns: an import token is named {@code import-token-} and an export token + * {@code export-token-}, each followed by letters and digits. + */ + private String token(String prefix) { + byte[] bytes = new byte[12]; + random.nextBytes(bytes); + return prefix + HEX.formatHex(bytes); + } + + /** + * The authority has to be allowed to verify. + * + *

The authority vouches for a certificate, so a key that may not verify may not be + * named as one. + * + * @param key the authority key + * @param what what the authority was asked to do, in words + */ + private static void requireVerify(PaymentCryptographyKey key, String what) { + Map modes = key.getKeyModesOfUse(); + if (modes != null && !Boolean.TRUE.equals(modes.get("Verify"))) { + throw validation("the key " + key.getArn() + " does not have the mode of use Verify, " + + "so it cannot be used for " + what); + } + } + + /** + * The key an identifier names, and it has to be one the service does work with. + * + *

A disabled key does no work, so it may not be exported, wrapped or agreed with. + * + * @param identifier the key's identifier + * @param region the region the key is in + * @return the key + */ + private PaymentCryptographyKey usableKey(String identifier, String region) { + PaymentCryptographyKey key = service.findKey(region, identifier); + if (key == null) { + throw notFound(identifier); + } + PaymentCryptographyKeyRules.requireEnabled(key); + return key; + } + + /** + * The exportability the block carries. + * + *

The request may name one, and the key's own answers when it does not. The one it + * names may only narrow the key's own: a key that is already set to a stricter + * exportability may not be exported as a looser one. + */ + private static String exportabilityCode(PaymentCryptographyKey key, Map headers) { + String own = ownExportability(key); + String named = text(headers, "KeyExportability"); + String code; + if ("EXPORTABLE".equals(named)) { + code = "E"; + } else if ("NON_EXPORTABLE".equals(named)) { + code = "N"; + } else if ("SENSITIVE".equals(named)) { + code = "S"; + } else { + return own; + } + if (permissiveness(code) > permissiveness(own)) { + throw validation("the exportability " + named + " is looser than the exportability " + + own + " the key " + key.getArn() + " has, and a key may only be exported " + + "with a stricter exportability than it has"); + } + return code; + } + + /** + * The exportability the key itself has. + * + *

An initial DUKPT key is sensitive, which is what the reference exports it as, and + * every other key is exportable or it is not. + */ + private static String ownExportability(PaymentCryptographyKey key) { + if (PaymentCryptographyService.isInitialDerivationKey(key)) { + return "S"; + } + return key.isExportable() ? "E" : "N"; + } + + /** + * How loose an exportability is. + * + *

The exportability says what the receiver may do with the key once it has it, and + * the model states the three in that order: {@code S} lets the receiver export under a + * key block, a TR-34 block or a cryptogram, {@code E} under a key block or a TR-34 block + * only, and {@code N} not at all. + * + *

So {@code S} is the loosest of the three and {@code N} the strictest, and a key + * may only be exported with an exportability that is not looser than its own. + */ + private static int permissiveness(String exportability) { + return switch (exportability) { + case "S" -> 2; + case "E" -> 1; + default -> 0; + }; + } + + /** + * The mode of use the block carries, as the request asks for it or the key has it. + * + *

The request may name modes, and they may only narrow the key's own: a key may not be + * exported with a permission it does not have. + */ + private static String modeCode(PaymentCryptographyKey key, Map headers) { + Map declared = object(headers, "KeyModesOfUse"); + if (declared == null || declared.isEmpty()) { + return PaymentCryptographyService.modeCode(key); + } + Map modes = new LinkedHashMap<>(); + declared.forEach((name, value) -> modes.put(name, Boolean.TRUE.equals(value))); + for (Map.Entry entry : modes.entrySet()) { + if (Boolean.TRUE.equals(entry.getValue()) && !allows(key, entry.getKey())) { + throw validation("the mode of use " + entry.getKey() + " is not one the key " + + key.getArn() + " has, and a key may only be exported with the modes of " + + "use it has"); + } + } + // The modes the request names are read the way the key's own are: a key encryption + // key wraps and unwraps rather than encrypting and decrypting. + return PaymentCryptographyService.modeCode(modes, + PaymentCryptographyService.isKeyEncryptionKey(key.getKeyUsage())); + } + + /** + * Whether the key has a mode of use, or something that stands for it. + * + *

A key encryption key wraps and unwraps where another key encrypts and decrypts, so + * for one the two spellings of a direction are the same permission. + */ + private static boolean allows(PaymentCryptographyKey key, String mode) { + Map modes = key.getKeyModesOfUse(); + if (modes == null) { + return true; + } + if (Boolean.TRUE.equals(modes.get("NoRestrictions"))) { + return true; + } + if (Boolean.TRUE.equals(modes.get(mode))) { + return true; + } + boolean kek = PaymentCryptographyService.isKeyEncryptionKey(key.getKeyUsage()); + if (kek && "Wrap".equals(mode)) { + return Boolean.TRUE.equals(modes.get("Encrypt")); + } + if (kek && "Unwrap".equals(mode)) { + return Boolean.TRUE.equals(modes.get("Decrypt")); + } + if (kek && "Encrypt".equals(mode)) { + return Boolean.TRUE.equals(modes.get("Wrap")); + } + return kek && "Decrypt".equals(mode) && Boolean.TRUE.equals(modes.get("Unwrap")); + } + + /** The version of the key the block carries. */ + private static String versionCode(Map headers) { + String version = text(headers, "KeyVersion"); + return version.isEmpty() ? "00" : version; + } + + /** The optional blocks the block carries, each its identifier and its value. */ + private static List optionalBlocks(Map headers) { + Map named = object(headers, "OptionalBlocks"); + List blocks = new ArrayList<>(); + if (named == null) { + return blocks; + } + for (Map.Entry entry : named.entrySet()) { + blocks.add(new String[] {entry.getKey(), String.valueOf(entry.getValue())}); + } + return blocks; + } + + /** The error a bad request is refused with. */ + private static AwsException validation(String message) { + return new AwsException("ValidationException", message, 400); + } + + /** The error a missing key is refused with. */ + private static AwsException notFound(String identifier) { + return new AwsException("ResourceNotFoundException", "Key not found: " + identifier, 400); + } + + /** + * The parameters a counterparty needs to import a key into this service. + * + * @param materialType the kind of material the counterparty will send + * @param algorithm the wrapping algorithm, one of the RSA ones + */ + Map parametersForImport(String materialType, String algorithm, boolean reuse) { + if (!IMPORT_PARAMETER_TYPES.contains(materialType)) { + throw validation("KeyMaterialType '" + materialType + "' does not take import " + + "parameters here (KEY_CRYPTOGRAM)"); + } + String wrappingAlgorithm = algorithm.isEmpty() ? "RSA_2048" : algorithm; + Integer bits = RSA_BITS.get(wrappingAlgorithm); + if (bits == null) { + throw validation("WrappingKeyAlgorithm '" + wrappingAlgorithm + "' not supported " + + "(RSA_2048, RSA_3072, RSA_4096)"); + } + String last = materialType + "/" + wrappingAlgorithm; + Issued previous = lastImportParameters.get(last); + if (reuse && previous != null && previous.validUntilMs > clock.millis()) { + return importParameters(previous); + } + long now = clock.millis(); + KeyPair pair = PaymentCryptographyKeyPairs.rsa(bits, random); + // The certificate lives as long as the token, so the parameters never hand out a + // certificate that has expired. + Certificates.Minted certificate = mintSelfSigned(pair, "floci key-import KRD", + Instant.ofEpochMilli(now).minus(1, ChronoUnit.HOURS), + Instant.ofEpochMilli(now).plus(IMPORT_TOKEN_TTL_MS, ChronoUnit.MILLIS)); + Issued issued = new Issued(token(IMPORT_TOKEN_PREFIX), pair.getPrivate(), certificate.der(), + wrappingAlgorithm, materialType, now + IMPORT_TOKEN_TTL_MS); + sweep(importTokens, lastImportParameters, now); + importTokens.put(issued.token, issued); + lastImportParameters.put(last, issued); + return importParameters(issued); + } + + /** The import parameters of an issued token, as the answer carries them. */ + private static Map importParameters(Issued issued) { + String certificate64 = Certificates.pemBase64(Certificates.toPem(issued.certificateDer)); + Map out = new LinkedHashMap<>(); + out.put("ImportToken", issued.token); + out.put("WrappingKeyCertificate", certificate64); + // Self-signed, so the chain is the certificate itself. + out.put("WrappingKeyCertificateChain", certificate64); + out.put("WrappingKeyAlgorithm", issued.algorithm); + out.put("ParametersValidUntilTimestamp", issued.validUntilMs / 1000); + return out; + } + + /** + * The parameters a counterparty needs to import a key this service exported. + * + *

The service signs the block it exports, so the parameters carry the signing key's + * certificate and the token that names the export. The export token is issued and kept + * for as long as the parameters are valid; the model has no member that carries it into + * an export, so nothing consumes it yet. + * + * @param materialType the kind of material the export carries + * @param algorithm the signing key's algorithm + * @return the parameters the counterparty quotes back + */ + Map parametersForExport(String materialType, String algorithm, boolean reuse) { + if (!EXPORT_PARAMETER_TYPES.contains(materialType)) { + throw validation("KeyMaterialType '" + materialType + "' does not take export " + + "parameters here (" + String.join(", ", EXPORT_PARAMETER_TYPES) + ")"); + } + PaymentCryptographyKeyAlgorithm signing = PaymentCryptographyKeyAlgorithm.from(algorithm); + if (signing == null || signing.symmetric()) { + throw validation("SigningKeyAlgorithm '" + algorithm + "' not supported " + + "(RSA_2048, RSA_3072, RSA_4096, ECC_NIST_P256, ECC_NIST_P384, ECC_NIST_P521)"); + } + String last = materialType + "/" + algorithm; + Issued previous = lastExportParameters.get(last); + if (reuse && previous != null && previous.validUntilMs > clock.millis()) { + return exportParameters(previous); + } + long now = clock.millis(); + KeyPair pair = signing.rsa + ? PaymentCryptographyKeyPairs.rsa(signing.bytes * 8, random) + : PaymentCryptographyKeyPairs.ec(signing, random); + // The certificate lives as long as the token, so the parameters never hand out a + // certificate that has expired. + Certificates.Minted certificate = mintSelfSigned(pair, "floci key-export KRD", + Instant.ofEpochMilli(now).minus(1, ChronoUnit.HOURS), + Instant.ofEpochMilli(now).plus(EXPORT_TOKEN_TTL_MS, ChronoUnit.MILLIS)); + Issued issued = new Issued(token(EXPORT_TOKEN_PREFIX), pair.getPrivate(), certificate.der(), + algorithm, materialType, now + EXPORT_TOKEN_TTL_MS); + sweep(exportTokens, lastExportParameters, now); + exportTokens.put(issued.token, issued); + lastExportParameters.put(last, issued); + return exportParameters(issued); + } + + /** The export parameters of an issued token, as the answer carries them. */ + private static Map exportParameters(Issued issued) { + String certificate64 = Certificates.pemBase64(Certificates.toPem(issued.certificateDer)); + Map out = new LinkedHashMap<>(); + out.put("ExportToken", issued.token); + out.put("SigningKeyCertificate", certificate64); + // Self-signed, so the chain is the certificate itself. + out.put("SigningKeyCertificateChain", certificate64); + out.put("SigningKeyAlgorithm", issued.algorithm); + out.put("ParametersValidUntilTimestamp", issued.validUntilMs / 1000); + return out; + } + + /** A public key out of a certificate. */ + private Imported importPublicKey(String region, Map material, + String caIdentifier) { + String certText = text(material, "PublicKeyCertificate"); + X509Certificate certificate; + try { + certificate = Certificates.parseCertificate(certText); + } catch (RuntimeException e) { + throw validation("the public key certificate is not a certificate: " + e.getMessage()); + } + // A trusted certificate is one the named authority signed, so it is checked against + // that authority. A root certificate stands on its own: it is the authority. + if (!caIdentifier.isEmpty()) { + // The authority does work here, so it has to be a key the service does work with. + PaymentCryptographyKey caKey = usableKey(caIdentifier, region); + certificate = verifiedCertificate(certText, caKey, "the public key certificate"); + } else { + try { + certificate.checkValidity(); + } catch (GeneralSecurityException e) { + throw validation("the public key certificate is outside its validity window: " + + e.getMessage()); + } + } + PublicKey publicKey = certificate.getPublicKey(); + Map attributes = object(material, "KeyAttributes"); + String algorithm = algorithmOf(publicKey); + Map modes = modesOf(attributes); + return new Imported(algorithm, String.valueOf(attributes.get("KeyUsage")), modes, true, + null, Base64.getEncoder().encodeToString(publicKey.getEncoded()), null, + certificatePem(certText), "PUBLIC_KEY"); + } +} diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyRequestShapes.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyRequestShapes.java index 53c87d5757..023d39ee31 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyRequestShapes.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyRequestShapes.java @@ -12,6 +12,13 @@ import io.floci.aws.core.common.RequestConstraintCheck; * of a key, the ARN of an alias or the name of an alias, while {@code KeyArn} and {@code ResourceArn} * take the ARN of a key alone. A violation is a {@code ValidationException}, with the member's path * from the request's top level. + * + *

The vendored file holds every operation the model names, so an operation the service serves + * is checked without anyone listing it. An operation the model does not name is not checked, and + * the service refuses it as the operation it does not serve. + * + *

Only the operations the service serves are checked: an operation the model names and the + * service does not serve is refused as the unknown operation it is, whatever its body says. */ final class PaymentCryptographyRequestShapes { @@ -23,6 +30,9 @@ final class PaymentCryptographyRequestShapes { } static void check(String operation, JsonNode request) { + if (!CHECK.holds(operation)) { + return; + } CHECK.check(operation, request); } } diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyService.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyService.java index d7439cd5bd..18fc04d33f 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyService.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyService.java @@ -11,6 +11,8 @@ import io.floci.aws.core.common.StoredResourceArns; import io.floci.aws.core.storage.InMemoryStorage; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.acm.CertificateGenerator; +import io.floci.aws.services.paymentcryptography.crypto.DukptCrypto; import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyAlias; import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey; import jakarta.enterprise.context.ApplicationScoped; @@ -18,6 +20,7 @@ import jakarta.inject.Inject; import java.security.KeyPair; import java.security.SecureRandom; +import java.time.Clock; import java.time.Instant; import java.util.ArrayList; import java.util.Base64; @@ -64,23 +67,34 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn /** The class of a key that is only a public half. */ private static final String PUBLIC_KEY_CLASS = "PUBLIC_KEY"; + /** The origin of a key the service made itself. */ + private static final String ORIGIN_SERVICE = "AWS_PAYMENT_CRYPTOGRAPHY"; + + /** The origin of a key whose material came in from outside the service. */ + private static final String ORIGIN_EXTERNAL = "EXTERNAL"; + private final StorageBackend keyStore; private final StorageBackend aliasStore; + /** The key exchange: the forms a key may leave in, and the certificates that carry them. */ + private final PaymentCryptographyKeyExchange exchange; private final RegionResolver regionResolver; private final SecureRandom secureRandom; private final PaymentCryptographyRequestContext requestContext; @Inject public PaymentCryptographyService(StorageFactory storageFactory, RegionResolver regionResolver, - PaymentCryptographyRequestContext requestContext) { + PaymentCryptographyRequestContext requestContext, + CertificateGenerator certificates) { this(storageFactory.create(STORAGE_KEY, "payment-cryptography-keys.json", new TypeReference<>() {}), storageFactory.create(STORAGE_KEY, "payment-cryptography-aliases.json", new TypeReference<>() {}), regionResolver, new SecureRandom(), - requestContext); + requestContext, + certificates, + Clock.systemUTC()); } PaymentCryptographyService(StorageBackend keyStore, @@ -108,9 +122,21 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn RegionResolver regionResolver, SecureRandom secureRandom, PaymentCryptographyRequestContext requestContext) { + this(keyStore, aliasStore, regionResolver, secureRandom, requestContext, + new CertificateGenerator(), Clock.systemUTC()); + } + + PaymentCryptographyService(StorageBackend keyStore, + StorageBackend aliasStore, + RegionResolver regionResolver, + SecureRandom secureRandom, + PaymentCryptographyRequestContext requestContext, + CertificateGenerator certificates, + Clock clock) { this.keyStore = keyStore; this.aliasStore = aliasStore; this.regionResolver = regionResolver; + this.exchange = new PaymentCryptographyKeyExchange(this, certificates, clock); this.secureRandom = secureRandom; this.requestContext = requestContext; } @@ -135,7 +161,7 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn boolean enabled, Map tags, String materialHex) { return makeKey(region, attributes, modesOfUse, exportable, enabled, tags, materialHex, - null, null, null); + null, null, null, ORIGIN_SERVICE); } /** @@ -148,12 +174,14 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn * @param publicKeyBase64 the public half of an asymmetric key, or null * @param privateKeyBase64 the private half of an asymmetric key, or null * @param certificatePem the certificate an imported public key arrived with, or null + * @param origin where the key material came from */ private PaymentCryptographyKey makeKey(String region, Map attributes, Map modesOfUse, boolean exportable, boolean enabled, Map tags, String materialHex, String publicKeyBase64, - String privateKeyBase64, String certificatePem) { + String privateKeyBase64, String certificatePem, + String origin) { String algorithmName = string(attributes, "KeyAlgorithm", "AES_256"); String keyClass = string(attributes, "KeyClass", "SYMMETRIC_KEY"); // The material has to be the algorithm's, so a key that says otherwise would be a key @@ -212,6 +240,7 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn key.setKeyPublicKeyBase64(publicKeyBase64); key.setKeyPrivateKeyBase64(privateKeyBase64); key.setKeyCertificatePem(certificatePem); + key.setKeyOrigin(origin); if (algorithm.symmetric()) { key.setKeyMaterialHex(materialHex != null ? materialHex @@ -527,6 +556,182 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn // ---- the key exchange ---------------------------------------------------- + /** + * The key as it leaves the service, in the form the request names. + * + *

A key that is not exportable does not leave. The form decides how it is protected: a + * TR-31 block under a key the service holds, an RSA-OAEP cryptogram under the receiver's + * certificate, a TR-34 block the service signs, a block under a key the two parties + * agreed, or an AS2805 cryptogram. + * + * @param region the region the key is in + * @param keyIdentifier the key that leaves + * @param form the form the request names + * @param material the members of the form + * @return the material, the format it is in, and the key that protects it + */ + public Map exportKey(String region, String keyIdentifier, String form, + Map material, String keySerialNumber, + String checkValueAlgorithm) { + PaymentCryptographyKey key = findKey(region, keyIdentifier); + if (key == null) { + throw new AwsException("ResourceNotFoundException", "Key not found: " + keyIdentifier, 400); + } + PaymentCryptographyKeyRules.requireEnabled(key); + // An initial key leaves instead of the key itself: the service derives it and does + // not keep it. + PaymentCryptographyKey leaving = keySerialNumber.isEmpty() ? key : initialKey(key, keySerialNumber); + if (!checkValueAlgorithm.isEmpty() + && !checkValueAlgorithm.equals(leaving.getKeyCheckValueAlgorithm())) { + throw new AwsException("ValidationException", + "the check value algorithm " + checkValueAlgorithm + " is not the one the key " + + leaving.getArn() + " has, which is " + + leaving.getKeyCheckValueAlgorithm(), 400); + } + if (!leaving.isExportable() && keySerialNumber.isEmpty()) { + throw new AwsException("ValidationException", + "the key " + key.getArn() + " is not exportable", 400); + } + PaymentCryptographyKeyExchange.Exported exported = exchange.export(region, leaving, form, material); + Map wrapped = new LinkedHashMap<>(); + wrapped.put("KeyMaterial", exported.material()); + wrapped.put("WrappedKeyMaterialFormat", exported.format()); + // The check value belongs to a key block: a cryptogram carries no block, so it has no + // check value either, which is what the reference answers. + if (!"KEY_CRYPTOGRAM".equals(exported.format())) { + wrapped.put("KeyCheckValue", leaving.getKeyCheckValue()); + wrapped.put("KeyCheckValueAlgorithm", leaving.getKeyCheckValueAlgorithm()); + } + if (exported.wrappingKeyArn() != null) { + wrapped.put("WrappingKeyArn", exported.wrappingKeyArn()); + } + return Map.of("WrappedKey", wrapped); + } + + /** + * The key that comes into the service, in the form the request names. + * + * @param region the region the key comes into + * @param form the form the request names + * @param material the members of the form + * @return the key + */ + public PaymentCryptographyKey importKey(String region, String form, Map material, + String checkValueAlgorithm, boolean enabled, + Map tags) { + PaymentCryptographyKeyExchange.Imported imported = exchange.importKey(region, form, material); + Map attributes = new LinkedHashMap<>(); + attributes.put("KeyAlgorithm", imported.algorithm()); + attributes.put("KeyClass", imported.keyClass()); + attributes.put("KeyUsage", imported.usage()); + if (!checkValueAlgorithm.isEmpty()) { + PaymentCryptographyKeyAlgorithm algorithm = + PaymentCryptographyKeyAlgorithm.from(imported.algorithm()); + String own = algorithm == null ? "" : algorithm.checkValueAlgorithm(); + if (!checkValueAlgorithm.equals(own)) { + throw new AwsException("ValidationException", + "the check value algorithm " + checkValueAlgorithm + " is not the one a " + + imported.algorithm() + " key has, which is " + own, 400); + } + } + return makeKey(region, attributes, imported.modes(), imported.exportable(), enabled, tags, + imported.material() == null ? null + : PaymentCryptographyCrypto.toHex(imported.material()), + imported.publicKeyBase64(), imported.privateKeyBase64(), imported.certificatePem(), + ORIGIN_EXTERNAL); + } + + /** + * The initial key of the DUKPT derivation, derived from a base derivation key. + * + *

The derived key is a PIN encryption key of sixteen bytes, and it does not leave the + * service again: what leaves is the derived key, not the base one. + * + * @param base the base derivation key + * @param keySerialNumber the serial number of the key the derivation starts from + * @return the derived key, as the key that leaves + */ + private static PaymentCryptographyKey initialKey(PaymentCryptographyKey base, + String keySerialNumber) { + if (!"TR31_B0_BASE_DERIVATION_KEY".equals(base.getKeyUsage())) { + throw new AwsException("ValidationException", + "an initial key under export is derived from a base derivation key, but " + + base.getArn() + " is " + base.getKeyUsage(), 400); + } + byte[] initial; + try { + initial = DukptCrypto.deriveIpek(PaymentCryptographyKeyRules.materialHex(base), + keySerialNumber); + } catch (RuntimeException e) { + throw new AwsException("ValidationException", + "the initial key could not be derived: " + e.getMessage(), 400); + } + PaymentCryptographyKey derived = new PaymentCryptographyKey(); + derived.setKeyId(base.getKeyId()); + derived.setArn(base.getArn()); + derived.setRegion(base.getRegion()); + derived.setKeyAlgorithm("TDES_2KEY"); + derived.setKeyClass("SYMMETRIC_KEY"); + // The standard gives the key derived from a base derivation key the usage of an + // initial derivation key, and the mode of a derivable one. + derived.setKeyUsage("TR31_B1_INITIAL_DERIVATION_KEY"); + derived.setKeyModesOfUse(new LinkedHashMap<>(Map.of("DeriveKey", Boolean.TRUE))); + derived.setKeyMaterialHex(PaymentCryptographyCrypto.toHex(initial)); + derived.setKeyCheckValue(PaymentCryptographyCrypto.checkValue(derived.getKeyMaterialHex(), + PaymentCryptographyKeyAlgorithm.TDES_2KEY)); + derived.setKeyCheckValueAlgorithm("ANSI_X9_24"); + // The derived key is for the counterparty's use and does not leave again. + derived.setExportable(false); + return derived; + } + + /** + * The number of exchange tokens the service holds. + * + *

For the test that watches the expired ones swept. + * + * @return how many tokens are held + */ + int issuedTokenCount() { + return exchange.issuedTokenCount(); + } + + + + /** + * The algorithm a key block carries. + * + *

The block names the algorithm of the key it carries, and the length of the material + * says which of that family's keys it is. The algorithm is not guessed from the length + * alone, because a TDES key and an AES key of the same length are different keys. + * + *

The header's algorithm byte fixes how long the key may be, so a key of a length the + * algorithm does not allow is refused rather than read as a key of another length. + */ + static String algorithmOf(String block, int materialLength) { + String family = PaymentCryptographyTr31.algorithmInHeader(block); + int length = materialLength; + return switch (family) { + case "A" -> switch (length) { + case 16 -> "AES_128"; + case 24 -> "AES_192"; + case 32 -> "AES_256"; + default -> throw new AwsException("ValidationException", + "the key block carries a " + (length * 8) + "-bit key; AES needs 128/192/256", 400); + }; + case "T" -> switch (length) { + case 16 -> "TDES_2KEY"; + case 24 -> "TDES_3KEY"; + default -> throw new AwsException("ValidationException", + "the key block carries a " + (length * 8) + "-bit key; TDES needs 128/192", 400); + }; + default -> throw new AwsException("ValidationException", + "the key block's algorithm is '" + family + "', which is not one this service has a key " + + "algorithm for (T for TDES, A for AES)", 400); + }; + } + + /** * The usages a key block may carry, and the modes of use each of them has. * @@ -557,6 +762,36 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn Map.entry("V2", "TR31_V2_VISA_PIN_VERIFICATION_KEY"), Map.entry("S0", "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE")); + /** + * The usage name of the key an initial derivation key has. + * + *

The standard gives an initial derivation key the usage code B1, and the key the + * service derives carries that code in the block it is exported in. The name is the + * service's own marker for such a key: the API has no usage name for it, because a key + * with that usage never lives in the service. + */ + static final String INITIAL_DERIVATION_KEY_USAGE = "TR31_B1_INITIAL_DERIVATION_KEY"; + + /** The TR-31 usage code of an initial derivation key. */ + static final String INITIAL_DERIVATION_KEY_CODE = "B1"; + + /** + * Whether a key is the one derived from a base derivation key. + * + *

It is an initial derivation key, and the standard gives it the usage code B1. + */ + static boolean isInitialDerivationKey(PaymentCryptographyKey key) { + return INITIAL_DERIVATION_KEY_USAGE.equals(key.getKeyUsage()); + } + + /** The TR-31 usage code of a key, which the initial derivation key has of its own. */ + static String usageCode(PaymentCryptographyKey key) { + if (isInitialDerivationKey(key)) { + return INITIAL_DERIVATION_KEY_CODE; + } + return usageCode(key.getKeyUsage()); + } + /** The TR-31 usage code of a usage name, such as {@code D0}. */ static String usageCode(String usageName) { for (Map.Entry entry : USAGE_NAMES.entrySet()) { @@ -620,23 +855,20 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn /** * The modes of use a mode of use code of a key block stands for. * - *

A key encryption key wraps and unwraps rather than encrypts and decrypts, so the - * same character means the other modes for one. + *

The character says what the key may be used for, and both spellings of a direction + * stand for it: a key that may encrypt may also wrap, and a key that may decrypt may also + * unwrap. A block that says {@code B} therefore grants all four of them, whichever use the + * key has, which is what the reference does. * * @param mode the mode of use character of the block - * @param isKek true when the block carries a key encryption key + * @return the modes of use the character stands for */ - static Map modesFor(String mode, boolean isKek) { + static Map modesFor(String mode) { return switch (mode) { - case "B" -> isKek - ? Map.of("Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE) - : Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE); - case "E" -> isKek - ? Map.of("Wrap", Boolean.TRUE) - : Map.of("Encrypt", Boolean.TRUE); - case "D" -> isKek - ? Map.of("Unwrap", Boolean.TRUE) - : Map.of("Decrypt", Boolean.TRUE); + case "B" -> Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE, + "Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE); + case "E" -> Map.of("Encrypt", Boolean.TRUE, "Wrap", Boolean.TRUE); + case "D" -> Map.of("Decrypt", Boolean.TRUE, "Unwrap", Boolean.TRUE); case "G" -> Map.of("Generate", Boolean.TRUE); case "V" -> Map.of("Verify", Boolean.TRUE); case "C" -> Map.of("Generate", Boolean.TRUE, "Verify", Boolean.TRUE); @@ -648,19 +880,18 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn } /** - * The mode of use character a key block carries. + * The mode of use character a set of modes gives. * - *

The character is read off the key's own modes, because that is what it says: a key - * that encrypts and decrypts is a {@code B}, one that only encrypts is an {@code E}. A key - * encryption key wraps and unwraps rather than encrypts and decrypts, so its modes are read - * that way. + *

The character is read off the modes, because that is what it says: a key that + * encrypts and decrypts is a {@code B}, one that only encrypts is an {@code E}. A key + * encryption key wraps and unwraps rather than encrypts and decrypts, so its modes are + * read that way. * - * @param key the key the block carries + * @param modes the modes of the key + * @param isKek whether the key is a key encryption key, whose modes are wrap and unwrap * @return the character */ - static String modeCode(PaymentCryptographyKey key) { - Map modes = key.getKeyModesOfUse(); - boolean isKek = isKeyEncryptionKey(key.getKeyUsage()); + static String modeCode(Map modes, boolean isKek) { boolean encrypt = isKek ? enabled(modes, "Wrap") || enabled(modes, "Encrypt") : enabled(modes, "Encrypt"); @@ -694,6 +925,18 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn return "N"; } + /** + * The mode of use character a key block carries. + * + *

The character is read off the key's own modes, because that is what it says. + * + * @param key the key the block carries + * @return the character + */ + static String modeCode(PaymentCryptographyKey key) { + return modeCode(key.getKeyModesOfUse(), isKeyEncryptionKey(key.getKeyUsage())); + } + /** Whether a mode of use is on. A key with no modes at all has every one of them. */ private static boolean enabled(Map modes, String mode) { return modes == null || Boolean.TRUE.equals(modes.get(mode)); @@ -848,4 +1091,21 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn Optional storedKey(String region, String keyId) { return keyStore.get(storageKey(region, keyId)); } + + /** The certificate of a public key. */ + public Map publicKeyCertificate(PaymentCryptographyKey key) { + return exchange.publicKeyCertificate(key); + } + + /** The parameters a counterparty needs to import a key into this service. */ + public Map parametersForImport(String materialType, String algorithm, + boolean reuse) { + return exchange.parametersForImport(materialType, algorithm, reuse); + } + + /** The parameters a counterparty needs to import a key this service exported. */ + public Map parametersForExport(String materialType, String algorithm, + boolean reuse) { + return exchange.parametersForExport(materialType, algorithm, reuse); + } } diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyTr31.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyTr31.java new file mode 100644 index 0000000000..a8849612f3 --- /dev/null +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyTr31.java @@ -0,0 +1,593 @@ +package io.floci.aws.services.paymentcryptography; + +import io.floci.aws.services.paymentcryptography.crypto.Ciphers; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; + +/** + * The TR-31 key block, the form a key takes when it leaves the service. + * + *

A type D block carries a key under a key block protection key: the key is length + * encoded, encrypted under the derived key, and the block carries a MAC over the header and + * the length encoded key. The keys the service makes are AES, so the block is a type D one and + * the protection key is an AES key too. + * + *

The length field of the header counts the whole block in characters, and the key is + * length encoded with its length in bits in front of it, so a reader knows how long the key is + * without the confidential data saying. + */ +final class PaymentCryptographyTr31 { + + /** The initialization vector block of the type D key derivation. */ + private static final String AES_IV_CONST = "80000000000000000000000000000000"; + + /** The reduction constant of Triple DES. */ + private static final String TDEA_RB = "000000000000001B"; + + /** The length of the header, in characters. */ + private static final int HEADER_LENGTH = 16; + + /** The length of the MAC of a type D block, in characters. */ + private static final int MAC_LENGTH = 32; + + private PaymentCryptographyTr31() { + } + + /** + * Wraps a key into a TR-31 block under a key block protection key. + * + * @param clearKey the key the block carries + * @param protectionKey the key that protects the block + * @param protectionAes whether the protection key is an AES key, which decides the block + * type: a type D block under an AES key and a type B one under a TDES + * key. The length alone does not say it, because a 16-byte key is + * both an AES-128 key and a two-key TDES one. + * @param algorithm the algorithm byte of the key the block carries: {@code A} for an + * AES key and {@code T} for a TDES one + * @param usage the usage code of the key, such as {@code D0} + * @param mode the mode of use code of the key, such as {@code B} + * @param exportability {@code E} when the key may leave the service again + * @return the block, in upper-case hexadecimal + */ + static String wrap(byte[] clearKey, byte[] protectionKey, boolean protectionAes, + String algorithm, String usage, String mode, String exportability) { + return wrap(clearKey, protectionKey, protectionAes, algorithm, usage, mode, exportability, + "00", List.of()); + } + + /** + * A key block, with the optional blocks the header carries. + * + *

The optional blocks sit between the header and the cipher text, in the clear, and + * they are authenticated with it. + * + * @param version the version of the key the block carries, over two characters + * @param optionalBlocks the optional blocks, each its identifier and its value + */ + static String wrap(byte[] clearKey, byte[] protectionKey, boolean protectionAes, + String algorithm, String usage, String mode, String exportability, + String version, List optionalBlocks) { + String type = protectionAes ? "D" : "B"; + byte[] lengthEncoded = lengthEncode(clearKey, protectionAes ? 16 : 8); + // The optional blocks are padded so that the header keeps the block alignment the + // standard asks for, and the padding block is one of them. + List padded = withPadding(optionalBlocks, protectionAes ? 16 : 8); + String optional = optionalBlocks(padded); + int blockLength = HEADER_LENGTH + optional.length() + lengthEncoded.length * 2 + + macLength(protectionAes); + String header = header16(type, usage, mode, exportability, blockLength, algorithm, version, + padded.size()); + + byte[][] derived = deriveKeys(protectionKey, protectionAes); + byte[] encryptionKey = derived[0]; + byte[] macKey = derived[1]; + byte[] mac = computeMac(header + optional, lengthEncoded, macKey, protectionAes); + + // The block is encrypted under the derived key, and the MAC is the vector of that + // encryption: the block is authenticated before it is read. + byte[] cipherText = protectionAes + ? PaymentCryptographyCrypto.aesCbcEncrypt(encryptionKey, mac, lengthEncoded) + : Ciphers.tdesCbcEncrypt(lengthEncoded, Ciphers.widenTdesKey(encryptionKey), mac); + return header + optional + hexUpper(cipherText) + hexUpper(mac); + } + + /** + * The optional blocks of a header, with the padding block that keeps them aligned. + * + *

The standard requires the optional blocks to take up a whole number of cipher + * blocks, so a header that carries them and is not aligned gets a padding block whose + * length is the smallest that aligns it. A header whose optional blocks are already + * aligned gets no padding block at all, because one would break the alignment. + * + * @param blocks the optional blocks the caller asked for + * @param blockSize the cipher block size in characters + * @return the blocks, with the padding block appended when one is needed + */ + private static List withPadding(List blocks, int blockSize) { + int total = 0; + for (String[] block : blocks) { + total += block[0].length() + 2 + block[1].length(); + } + if (total % blockSize == 0) { + return blocks; + } + // The padding block spends four characters on its identifier and its length, and + // the rest of the space is what it carries. + int padding = blockSize - ((total + 4) % blockSize); + if (padding == blockSize) { + padding = 0; + } + List padded = new ArrayList<>(blocks); + padded.add(new String[] {"PB", "0".repeat(padding)}); + return padded; + } + + /** + * Opens a TR-31 block under a key block protection key, and gives the key it carries. + * + * @param block the block, in hexadecimal + * @param protectionKey the key that protects the block + * @return the key the block carries + * @throws IllegalArgumentException when the block does not authenticate, or its header says + * something this service does not serve + */ + static byte[] unwrap(String block, byte[] protectionKey) { + if (block == null || block.length() < HEADER_LENGTH + MAC_LENGTH) { + throw new IllegalArgumentException("the key block is too short to be a key block"); + } + String header = block.substring(0, HEADER_LENGTH); + String type = header.substring(0, 1); + if (!"D".equals(type) && !"B".equals(type)) { + throw new IllegalArgumentException("the key block is of type " + type + + ", and this service reads type B and type D blocks"); + } + int declared = parseInt(header.substring(1, 5), "the length of the key block"); + if (declared != block.length()) { + throw new IllegalArgumentException("the key block says it is " + declared + + " characters long, and it is " + block.length()); + } + boolean aes = "D".equals(type); + int macLength = macLength(aes); + byte[] mac = fromHex(block.substring(block.length() - macLength)); + // The optional blocks sit between the header and the cipher text in the clear, and + // they are authenticated with it. + int optionalLength = optionalLength(header, block); + String optional = block.substring(HEADER_LENGTH, HEADER_LENGTH + optionalLength); + byte[] cipherText = fromHex( + block.substring(HEADER_LENGTH + optionalLength, block.length() - macLength)); + + byte[][] derived = deriveKeys(protectionKey, aes); + byte[] encryptionKey = derived[0]; + byte[] macKey = derived[1]; + byte[] lengthEncoded = aes + ? PaymentCryptographyCrypto.aesCbcDecrypt(encryptionKey, mac, cipherText) + : Ciphers.tdesCbcDecrypt(cipherText, Ciphers.widenTdesKey(encryptionKey), mac); + + byte[] recomputed = computeMac(header + optional, lengthEncoded, macKey, aes); + // The MACs are compared as bytes and in constant time: a comparison that stopped at + // the first difference would say how much of the MAC matched. + if (!MessageDigest.isEqual(recomputed, mac)) { + throw new IllegalArgumentException("the key block did not authenticate under the key"); + } + + int bits = parseInt(hexUpper(Arrays.copyOfRange(lengthEncoded, 0, 2)), "the length of the key", 16); + if (bits % 8 != 0) { + throw new IllegalArgumentException("the key block says its key is " + bits + + " bits long, which is not a whole number of bytes"); + } + if (lengthEncoded.length < 2 + bits / 8) { + throw new IllegalArgumentException("the key block says its key is longer than the block"); + } + return Arrays.copyOfRange(lengthEncoded, 2, 2 + bits / 8); + } + + /** + * The optional blocks a key block carries, as the characters of the key block. + * + *

An optional block is its identifier over two characters, its length over two, and + * then its value. The length covers the whole block in characters, the identifier and the + * length included, and it is written in hexadecimal. + * + * @param blocks the optional blocks, each its identifier and its value + * @return the optional blocks, as the characters of the key block + */ + private static String optionalBlocks(List blocks) { + StringBuilder out = new StringBuilder(); + for (String[] block : blocks) { + String id = block[0]; + String value = block[1]; + // The length covers the whole block, the identifier and the length included. + out.append(id).append(two(4 + value.length(), 16)).append(value); + } + return out.toString(); + } + + /** + * How many characters the block's optional blocks take. + * + *

An optional block is its identifier over two characters, its length over two, and + * then its value. The length covers the whole block in characters, the identifier and the + * length included, and it is written in hexadecimal. The header says how many of them + * there are. + * + * @param header the block's header + * @param block the whole block + * @return the length of the optional blocks, in characters + */ + static int optionalLength(String header, String block) { + int count = parseInt(header.substring(12, 14), "the number of optional blocks"); + int length = 0; + for (int i = 0; i < count; i++) { + length += optionalBlockLength(block, HEADER_LENGTH + length); + } + return length; + } + + /** + * How many characters the optional block at a place takes. + * + *

The length field says how long the whole block is, the identifier and the length + * included. A block longer than a length field can hold says so with a zero length, and + * then the number of characters the length itself takes follows, and the length after + * that. + * + * @param block the whole block + * @param at where the optional block starts + * @return the length of the optional block, in characters + */ + private static int optionalBlockLength(String block, int at) { + if (block.length() < at + 4) { + throw new IllegalArgumentException("the key block says it has optional blocks, and it " + + "is too short to hold them"); + } + int length = parseInt(block.substring(at + 2, at + 4), + "the length of an optional block", 16); + if (length != 0) { + return length; + } + // The length did not fit in its field, so the field says so and the length follows + // the number of characters it takes. + if (block.length() < at + 8) { + throw new IllegalArgumentException("the key block says it has optional blocks, and it " + + "is too short to hold them"); + } + int digits = parseInt(block.substring(at + 4, at + 6), + "the length of the length of an optional block", 16); + if (digits == 0 || block.length() < at + 6 + digits) { + throw new IllegalArgumentException("the key block says it has optional blocks, and it " + + "is too short to hold them"); + } + return parseInt(block.substring(at + 6, at + 6 + digits), + "the length of an optional block", 16); + } + + /** The usage code of a block's header, such as {@code D0}. */ + static String usageOf(String block) { + return block.substring(5, 7); + } + + /** + * Whether a block is a type D one, which is derived with AES. + * + *

The type is in the block's own header, so it is read from there and not from the + * wrapping key: a type D block is protected with AES and a type B one with TDES. + */ + static boolean typeOf(String block) { + return "D".equals(block.substring(0, 1)); + } + + /** The type of a block, {@code D} or {@code B}, for a message that names it. */ + static String typeName(String block) { + return block.substring(0, 1); + } + + /** The mode of use code of a block's header, such as {@code B}. */ + static String modeOf(String block) { + return block.substring(8, 9); + } + + /** The exportability of a block's header: {@code E}, {@code N} or {@code S}. */ + static String exportabilityOf(String block) { + return block.substring(11, 12); + } + + /** + * The 16-character header of a block, whose layout the standard fixes. + * + * @param blockLength the length of the whole block, in characters + */ + private static String header16(String type, String usage, String mode, String exportability, + int blockLength, String algorithm, String version, + int optionalBlocks) { + String header = type + + pad4(blockLength) + + usage + + algorithm // the algorithm of the key the block carries + + mode + + version // the version of the key + + exportability + + two(optionalBlocks, 10) // the number of optional blocks + + "00"; // the reserved characters + if (header.length() != HEADER_LENGTH) { + throw new IllegalArgumentException("the key block header must be 16 characters"); + } + return header; + } + + /** The algorithm the header of a block names for the key it carries. */ + static String algorithmInHeader(String block) { + return block.substring(7, 8); + } + + /** The length of the MAC of a block of that type, in characters. */ + private static int macLength(boolean aes) { + return aes ? 32 : 16; + } + + /** + * The two masks of the last block of the MAC: the CMAC subkeys of the MAC key. + * + *

A last block that needed no padding is masked with the first subkey and one that was + * padded with the second, which is what the reference implementation does. + */ + private static byte[][] masksOf(byte[] macKey, boolean aes) { + if (aes) { + byte[][] subkeys = PaymentCryptographyCrypto.cmacSubkeys(macKey); + return new byte[][] {subkeys[0], subkeys[1]}; + } + byte[] subkeys = cmacSubkeys(macKey, 8, TDEA_RB); + return new byte[][] {Arrays.copyOfRange(subkeys, 0, 8), Arrays.copyOfRange(subkeys, 8, 16)}; + } + + /** + * The key as a length encoded block: its length in bits in front of it, zero padded to the + * block size. + */ + static byte[] lengthEncode(byte[] clearKey, int blockSize) { + byte[] body = new byte[2 + clearKey.length]; + body[0] = (byte) ((clearKey.length * 8) >> 8); + body[1] = (byte) (clearKey.length * 8); + System.arraycopy(clearKey, 0, body, 2, clearKey.length); + int padding = (blockSize - (body.length % blockSize)) % blockSize; + byte[] out = new byte[body.length + padding]; + System.arraycopy(body, 0, out, 0, body.length); + return out; + } + + /** The block size of AES, in bytes. */ + private static final int BLOCK_SIZE = 16; + + /** + * The MAC of a block: the CBC-MAC of the header and the length encoded key under the MAC + * key, with the last block masked by a subkey of it. + * + *

A last block that needed no padding is masked with the first subkey and one that was + * padded with the second, which is what the reference implementation does. + */ + static byte[] computeMac(String header, byte[] lengthEncoded, byte[] macKey, boolean aes) { + int blockSize = aes ? BLOCK_SIZE : 8; + byte[][] masks = masksOf(macKey, aes); + byte[] data = new byte[header.length() + lengthEncoded.length]; + System.arraycopy(header.getBytes(StandardCharsets.US_ASCII), 0, data, 0, header.length()); + System.arraycopy(lengthEncoded, 0, data, header.length(), lengthEncoded.length); + + byte[] last; + if (data.length % blockSize != 0) { + int padding = blockSize - (data.length % blockSize); + data = Arrays.copyOf(data, data.length + padding); + data[data.length - padding] = (byte) 0x80; + last = xor(Arrays.copyOfRange(data, data.length - blockSize, data.length), masks[1]); + } else { + last = xor(Arrays.copyOfRange(data, data.length - blockSize, data.length), masks[0]); + } + byte[] macInput = Arrays.copyOf(data, data.length); + System.arraycopy(last, 0, macInput, macInput.length - blockSize, blockSize); + byte[] out = aes + ? PaymentCryptographyCrypto.aesCbcEncrypt(macKey, new byte[BLOCK_SIZE], macInput) + : Ciphers.tdesCbcEncrypt(macInput, Ciphers.widenTdesKey(macKey), new byte[8]); + return Arrays.copyOfRange(out, out.length - blockSize, out.length); + } + + /** + * The two keys a block is made under: the one that encrypts the key and the one that + * authenticates it. + * + *

The derivation follows the family of the protection key, because the block type does + * too: a type D block is derived with AES and a type B one with Triple DES. + */ + static byte[][] deriveKeys(byte[] protectionKey, boolean aes) { + return aes ? deriveAesKeys(protectionKey) : deriveTypeBKeys(protectionKey); + } + + /** + * The derived keys of a type D block. + * + *

The derivation is the counter mode key derivation of NIST SP800-108, seeded with the + * second CMAC subkey of the protection key and encrypted by the protection key itself. The + * derived key is as long as the protection key: a 192-bit protection key derives a 192-bit + * key, whose second part is truncated to eight bytes, so the cipher that uses the result is + * AES-192 rather than a widened AES-256. + */ + private static byte[][] deriveAesKeys(byte[] protectionKey) { + int bits = protectionKey.length * 8; + if (bits != 128 && bits != 192 && bits != 256) { + throw new IllegalArgumentException("a type D block needs a 128, 192 or 256 bit key block " + + "protection key, and this one is " + bits + " bits"); + } + int derivedBytes = bits / 8; + int firstPart = 16; + int secondPart = derivedBytes - firstPart; + byte[] seed = PaymentCryptographyCrypto.cmacSubkeys(protectionKey)[1]; + + byte[] encryptionKey = new byte[derivedBytes]; + byte[] macKey = new byte[derivedBytes]; + System.arraycopy(part(seed, bits, false, 1, protectionKey), 0, encryptionKey, 0, firstPart); + System.arraycopy(part(seed, bits, true, 1, protectionKey), 0, macKey, 0, firstPart); + if (secondPart > 0) { + System.arraycopy(part(seed, bits, false, 2, protectionKey), 0, encryptionKey, firstPart, + secondPart); + System.arraycopy(part(seed, bits, true, 2, protectionKey), 0, macKey, firstPart, secondPart); + } + return new byte[][] {encryptionKey, macKey}; + } + + /** + * The derived keys of a type B block. + * + *

The derivation is the counter mode key derivation of NIST SP800-108, seeded with the + * first CMAC subkey of the protection key, and the reduction constant of Triple DES is the + * whole buffer rather than the top bit alone. + */ + private static byte[][] deriveTypeBKeys(byte[] protectionKey) { + int bits = protectionKey.length * 8; + if (bits != 128 && bits != 192) { + throw new IllegalArgumentException("a type B block needs a 128 or 192 bit key block " + + "protection key, and this one is " + bits + " bits"); + } + byte[] wide = Ciphers.widenTdesKey(protectionKey); + int parts = bits == 192 ? 3 : 2; + byte[] seed = Arrays.copyOfRange(cmacSubkeys(wide, 8, TDEA_RB), 0, 8); + byte[] encryptionKey = new byte[parts * 8]; + byte[] macKey = new byte[parts * 8]; + for (int counter = 1; counter <= parts; counter++) { + byte[] input = xor(seed, fromHex(typeBConstant(bits, false, counter))); + byte[] part = Ciphers.tdes3Encrypt(input, wide); + System.arraycopy(part, 0, encryptionKey, (counter - 1) * 8, 8); + input = xor(seed, fromHex(typeBConstant(bits, true, counter))); + part = Ciphers.tdes3Encrypt(input, wide); + System.arraycopy(part, 0, macKey, (counter - 1) * 8, 8); + } + return new byte[][] {encryptionKey, macKey}; + } + + /** The constant of the type B key derivation. */ + private static String typeBConstant(int bits, boolean mac, int counter) { + String algorithm = bits == 192 ? "0001" : "0000"; + String use = mac ? "0001" : "0000"; + String keyLength = bits == 192 ? "00C0" : "0080"; + return (counter < 10 ? "0" + counter : Integer.toString(counter)) + + use + "00" + algorithm + keyLength; + } + + /** + * The CMAC subkeys of a TDES key. + * + *

The reduction constant of Triple DES is the whole buffer, which is what the reference + * implementation does, and it is not the top bit alone. + */ + private static byte[] cmacSubkeys(byte[] key, int blockSize, String rbHex) { + byte[] s = Ciphers.tdes3Encrypt(new byte[blockSize], key); + byte[] rb = fromHex(rbHex); + byte[] k1 = shiftXor(s, rb); + byte[] k2 = shiftXor(k1, rb); + byte[] out = new byte[k1.length + k2.length]; + System.arraycopy(k1, 0, out, 0, k1.length); + System.arraycopy(k2, 0, out, k1.length, k2.length); + return out; + } + + /** A left shift by one bit, then the reduction constant when the top bit was set. */ + private static byte[] shiftXor(byte[] value, byte[] rb) { + byte[] out = new byte[value.length]; + int carry = 0; + for (int i = value.length - 1; i >= 0; i--) { + int nextCarry = (value[i] & 0x80) != 0 ? 1 : 0; + out[i] = (byte) (((value[i] << 1) | carry) & 0xff); + carry = nextCarry; + } + if ((value[0] & 0x80) != 0) { + for (int i = 0; i < out.length; i++) { + out[i] ^= rb[i % rb.length]; + } + } + return out; + } + + /** One part of the derivation: the protection key encrypts the seeded constant. */ + private static byte[] part(byte[] seed, int bits, boolean mac, int counter, byte[] protectionKey) { + byte[] constant = fromHex(derivationConstant(bits, mac, counter)); + byte[] input = xor(seed, constant); + return PaymentCryptographyCrypto.aesEcbEncrypt(input, protectionKey); + } + + /** The constant of the key derivation, which says what is derived and how long it is. */ + private static String derivationConstant(int bits, boolean mac, int counter) { + String algorithm = bits == 128 ? "0002" : bits == 192 ? "0003" : "0004"; + String use = mac ? "0001" : "0000"; + String keyLength = bits == 128 ? "0080" : bits == 192 ? "00C0" : "0100"; + return (counter < 10 ? "0" + counter : Integer.toString(counter)) + + use + "00" + algorithm + keyLength + AES_IV_CONST; + } + + /** Two byte arrays, one after the other. */ + + private static byte[] xor(byte[] left, byte[] right) { + byte[] out = new byte[left.length]; + for (int i = 0; i < left.length; i++) { + out[i] = (byte) (left[i] ^ right[i % right.length]); + } + return out; + } + + /** The length of the block, in four decimal characters. */ + private static String pad4(int value) { + String text = Integer.toString(value); + if (text.length() > 4) { + throw new IllegalArgumentException("the key block is too long: " + value); + } + return "0000".substring(0, 4 - text.length()) + text; + } + + /** + * A number of two characters, in the radix the field it goes into is written in. + * + *

The header's count of the optional blocks is written in ten, and the length of an + * optional block in sixteen, as the standard has it. + * + * @param value the number + * @param radix the radix the field is written in + * @return the number, in two characters + */ + private static String two(int value, int radix) { + String text = Integer.toString(value, radix).toUpperCase(Locale.ROOT); + if (text.length() > 2) { + throw new IllegalArgumentException("the number does not fit in two characters: " + value); + } + return "00".substring(0, 2 - text.length()) + text; + } + + private static int parseInt(String text, String what) { + return parseInt(text, what, 10); + } + + /** + * A number of the text. + * + *

The length of the block is written in decimal and the length of the key in the + * length encoded block is written in hexadecimal, so the base is a parameter. + */ + private static int parseInt(String text, String what, int radix) { + try { + return Integer.parseInt(text, radix); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(what + " is not a number: " + text); + } + } + + private static String hexUpper(byte[] bytes) { + return PaymentCryptographyCrypto.toHex(bytes).toUpperCase(Locale.ROOT); + } + + private static byte[] fromHex(String hex) { + try { + return PaymentCryptographyCrypto.fromHex(hex); + } catch (RuntimeException e) { + throw new IllegalArgumentException("the key block is not hexadecimal"); + } + } +} diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Certificates.java b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Certificates.java new file mode 100644 index 0000000000..b3039ff9ac --- /dev/null +++ b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Certificates.java @@ -0,0 +1,134 @@ +package io.floci.aws.services.paymentcryptography.crypto; + +import io.floci.aws.core.common.CertificateMaterialException; +import io.floci.aws.core.common.Pem; +import org.bouncycastle.asn1.pkcs.IssuerAndSerialNumber; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.openssl.jcajce.JcaPEMWriter; +import org.bouncycastle.util.io.pem.PemObject; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.StringWriter; +import java.nio.charset.StandardCharsets; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Base64; + +/** + * The certificates the key exchange hands out and reads. + * + *

The service gives a counterparty a certificate over a key pair it made for the occasion, + * and reads the certificate a counterparty brings. A certificate travels in three shapes: PEM, + * base64 of PEM (which is how the service returns one), and base64 of DER. + * + *

Reading a certificate is the emulator's own business, through {@link Pem}; minting one + * belongs to ACM's generator, which the service asks for a certificate with. + */ +public final class Certificates { + + private Certificates() { + } + + /** A minted certificate, in the two forms the service uses it in. */ + public record Minted(byte[] der, String pem) { + } + + /** + * Parse a certificate the service hands over, or one a counterparty brings. + * + *

PEM, base64 of PEM and base64 of DER are all accepted: the service returns a + * certificate as base64 of its PEM, and a client certificate arrives the same way. + * + * @param pemOrBase64 the certificate, in any of those shapes + * @return the parsed certificate + * @throws IllegalArgumentException if the text is not a certificate in any of them + */ + public static X509Certificate parseCertificate(String pemOrBase64) { + String text = pemOrBase64 == null ? "" : pemOrBase64.trim(); + if (text.contains("-----BEGIN")) { + return readPem(text); + } + byte[] decoded; + try { + decoded = Base64.getMimeDecoder().decode(text); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException("the certificate is neither PEM nor base64"); + } + String decodedText = new String(decoded, StandardCharsets.UTF_8); + // base64 of a PEM, which is how the service returns one, or base64 of the DER itself. + if (decodedText.contains("-----BEGIN")) { + return readPem(decodedText); + } + return readDer(decoded); + } + + /** The certificate a DER document holds. */ + private static X509Certificate readDer(byte[] der) { + try { + return (X509Certificate) CertificateFactory.getInstance("X.509") + .generateCertificate(new ByteArrayInputStream(der)); + } catch (CertificateException e) { + throw new IllegalArgumentException("the certificate does not parse: " + e.getMessage()); + } + } + + /** The certificate a PEM document holds, read by the emulator's own PEM reader. */ + private static X509Certificate readPem(String pem) { + try { + return Pem.parseCertificate(pem); + } catch (CertificateMaterialException e) { + throw new IllegalArgumentException("the certificate does not parse: " + e.getMessage()); + } + } + + /** + * The identifier a TR-34 block uses to name its recipient. + * + *

A RecipientInfo carries the receiver's certificate identifier: an + * IssuerAndSerialNumber, which is the issuer's name and the certificate's serial number. + * Both are taken from the certificate itself, so the identifier is the one the receiver's + * own certificate carries. + * + * @param certDer the certificate in DER + * @return the issuer and serial number, as the DER of an IssuerAndSerialNumber + */ + public static byte[] certificateId(byte[] certDer) { + X509Certificate certificate = readDer(certDer); + try { + return new IssuerAndSerialNumber( + new X500Name(certificate.getIssuerX500Principal().getName()), + certificate.getSerialNumber()).getEncoded(); + } catch (IOException e) { + throw new IllegalStateException("cannot encode the certificate identifier", e); + } + } + + /** + * Wrap DER as a PEM document. + * + * @param der the certificate in DER + * @return the certificate in PEM + */ + public static String toPem(byte[] der) { + StringWriter writer = new StringWriter(); + try (JcaPEMWriter pemWriter = new JcaPEMWriter(writer)) { + pemWriter.writeObject(new PemObject("CERTIFICATE", der)); + } catch (IOException e) { + throw new IllegalStateException("cannot write the certificate as PEM", e); + } + return writer.toString(); + } + + /** + * A PEM certificate as base64, which is how the service returns one. + * + * @param pem the certificate in PEM + * @return the base64 of the PEM + */ + public static String pemBase64(String pem) { + return Base64.getEncoder().encodeToString(pem.getBytes(StandardCharsets.US_ASCII)); + } + +} 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 374ee9c352..6db226f350 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 @@ -84,6 +84,34 @@ public final class Ciphers { return block(AESEngine.newInstance(), false, block16, key); } + /** + * Widen a two-key (sixteen-byte) Triple DES key to the three-key form, K1||K2 to + * K1||K2||K1. + * + *

The cipher takes the three keys K1||K2||K1, which is what the two-key form means, + * and TR-31 derives a type B block's keys from the widened form, so the derivation and + * the cipher have to be on the same key. A three-key key is returned as it is. + * + * @param key the sixteen- or twenty-four-byte key + * @return the twenty-four-byte key + */ + public static byte[] widenTdesKey(byte[] key) { + if (key == null) { + throw new IllegalArgumentException("key is required"); + } + if (key.length == 24) { + return key; + } + if (key.length != 16) { + throw new IllegalArgumentException( + "TDES key must be 16 or 24 bytes, got " + key.length); + } + byte[] out = new byte[24]; + System.arraycopy(key, 0, out, 0, 16); + System.arraycopy(key, 0, out, 16, 8); + return out; + } + /** * The Triple DES encryption of a block under a two-key key, in ECB mode. * diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/ConcatKdf.java b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/ConcatKdf.java new file mode 100644 index 0000000000..e23a39dfd0 --- /dev/null +++ b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/ConcatKdf.java @@ -0,0 +1,112 @@ +package io.floci.aws.services.paymentcryptography.crypto; + +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.digests.SHA256Digest; +import org.bouncycastle.crypto.digests.SHA384Digest; +import org.bouncycastle.crypto.digests.SHA512Digest; + +import java.util.Arrays; + +/** + * The NIST SP 800-56A concatenation KDF, as the service applies it. + * + *

It is the single-step KDF of SP 800-56A with the counter, the shared + * secret and the shared information concatenated in that order: + * + *

+ *   K = H(counter || Z || OtherInfo) for counter = 1, 2, ... truncated to length
+ * 
+ * + *

The other information is what binds the derived key to the two parties and + * to the context, so the same shared secret derived under different shared + * information gives a different key. + */ +public final class ConcatKdf { + + private ConcatKdf() { + } + + /** + * Derive key material from a shared secret. + * + * @param hash the digest algorithm: {@code SHA-256}, {@code SHA-384} or + * {@code SHA-512} + * @param secret the shared secret + * @param otherInfo the shared information + * @param length how many bytes to derive + * @return the derived key + */ + public static byte[] derive(String hash, byte[] secret, byte[] otherInfo, int length) { + return derive(hash, secret, otherInfo, length, true); + } + + /** + * The ANSI X9.63 key derivation. + * + *

The same construction as the SP 800-108 concatenation KDF, but with + * the shared secret and the counter the other way round: + * + *

+     *   K = H(Z || counter || OtherInfo)
+     * 
+ * + *

So the two derivations over the same secret give different keys, and + * a caller has to say which one it means. + */ + public static byte[] deriveX963(String hash, byte[] secret, byte[] otherInfo, int length) { + return derive(hash, secret, otherInfo, length, false); + } + + private static byte[] derive(String hash, byte[] secret, byte[] otherInfo, int length, + boolean counterFirst) { + if (length <= 0) { + throw new IllegalArgumentException("the derived length must be positive"); + } + Digest digest = digestFor(hash); + int hashBytes = digest.getDigestSize(); + int reps = (length + hashBytes - 1) / hashBytes; + byte[] out = new byte[reps * hashBytes]; + byte[] block = new byte[hashBytes]; + for (int i = 1; i <= reps; i++) { + digest.reset(); + if (counterFirst) { + digest.update(counter(i), 0, 4); + digest.update(secret, 0, secret.length); + } else { + digest.update(secret, 0, secret.length); + digest.update(counter(i), 0, 4); + } + digest.update(otherInfo, 0, otherInfo.length); + digest.doFinal(block, 0); + System.arraycopy(block, 0, out, (i - 1) * hashBytes, hashBytes); + } + return Arrays.copyOf(out, length); + } + + /** The four-byte big-endian counter, starting at one. */ + private static byte[] counter(int n) { + return new byte[] { + (byte) (n >>> 24), (byte) (n >>> 16), (byte) (n >>> 8), (byte) n, + }; + } + + /** + * The digest for a wire hash name. + * + *

The service names the digests with an underscore, and the library + * knows them as the SHA-2 family. + */ + private static Digest digestFor(String hash) { + if ("SHA_256".equals(hash)) { + return new SHA256Digest(); + } + if ("SHA_384".equals(hash)) { + return new SHA384Digest(); + } + if ("SHA_512".equals(hash)) { + return new SHA512Digest(); + } + throw new IllegalArgumentException("unsupported digest '" + hash + + "' (SHA_256, SHA_384, SHA_512)"); + } +} diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Ecdh.java b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Ecdh.java new file mode 100644 index 0000000000..92443d2119 --- /dev/null +++ b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Ecdh.java @@ -0,0 +1,62 @@ +package io.floci.aws.services.paymentcryptography.crypto; + +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.crypto.agreement.ECDHBasicAgreement; +import org.bouncycastle.crypto.params.ECPrivateKeyParameters; +import org.bouncycastle.crypto.params.ECPublicKeyParameters; +import org.bouncycastle.crypto.util.PrivateKeyFactory; +import org.bouncycastle.crypto.util.PublicKeyFactory; + +import java.io.IOException; +import java.math.BigInteger; +import java.security.GeneralSecurityException; +import java.security.interfaces.ECPrivateKey; +import java.security.interfaces.ECPublicKey; + +/** + * The elliptic curve key agreement the key exchange derives its shared secret with. + * + *

The keys are the ones the service holds, which are the JDK's key objects. They are + * turned into the library's own parameters through their encodings, which carry the curve + * by name, so the two parties' keys are read on the same curve rather than on two curves + * that happen to look alike. + */ +public final class Ecdh { + + private Ecdh() { + } + + /** + * The secret the two parties agree. + * + * @param privateKey the service's own private key + * @param counterpartyKey the other party's public key + * @return the shared secret, the x coordinate of the agreed point + * @throws GeneralSecurityException when the two keys are not on the same curve + */ + public static byte[] agree(ECPrivateKey privateKey, ECPublicKey counterpartyKey) + throws GeneralSecurityException { + try { + ECPrivateKeyParameters own = (ECPrivateKeyParameters) PrivateKeyFactory + .createKey(PrivateKeyInfo.getInstance(privateKey.getEncoded())); + ECPublicKeyParameters other = (ECPublicKeyParameters) PublicKeyFactory + .createKey(SubjectPublicKeyInfo.getInstance(counterpartyKey.getEncoded())); + ECDHBasicAgreement agreement = new ECDHBasicAgreement(); + agreement.init(own); + // The agreed point's x coordinate, in as many bytes as the field is wide. + BigInteger x = agreement.calculateAgreement(other); + int size = agreement.getFieldSize(); + byte[] raw = x.toByteArray(); + byte[] secret = new byte[size]; + int from = Math.max(0, raw.length - size); + System.arraycopy(raw, from, secret, size - (raw.length - from), raw.length - from); + return secret; + } catch (IOException | ClassCastException | IllegalArgumentException + | IllegalStateException e) { + // The library raises IllegalStateException when the two keys are on different + // curves, which is a refusal and not a crash. + throw new GeneralSecurityException("the key agreement failed: " + e.getMessage(), e); + } + } +} 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 index a34baf1bef..a528af1d83 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/EmvCrypto.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/EmvCrypto.java @@ -19,8 +19,8 @@ import java.util.HexFormat; * 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. + *

Each cipher says which one it uses: the retail MAC is single DES, and the + * key derivations are two-key TDES, which the cipher takes as K1||K2||K1. * *

The full PAN flows into master key derivation, because the derivation is * defined over the whole of it. @@ -94,11 +94,12 @@ public final class EmvCrypto { } /** - * ISO/IEC 9797-1 MAC algorithm 3 (the retail MAC) with a 16-byte key. + * The retail MAC over data padded with the given ISO 9797-1 method. * - *

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: + *

This is ISO/IEC 9797-1 MAC algorithm 3 with a 16-byte key, and it 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
@@ -108,7 +109,6 @@ public final class EmvCrypto {
      * 

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); diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/RsaOaep.java b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/RsaOaep.java new file mode 100644 index 0000000000..46e10f99ef --- /dev/null +++ b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/RsaOaep.java @@ -0,0 +1,114 @@ +package io.floci.aws.services.paymentcryptography.crypto; + +import org.bouncycastle.crypto.AsymmetricBlockCipher; +import org.bouncycastle.crypto.Digest; +import org.bouncycastle.crypto.InvalidCipherTextException; +import org.bouncycastle.crypto.digests.SHA256Digest; +import org.bouncycastle.crypto.digests.SHA512Digest; +import org.bouncycastle.crypto.encodings.OAEPEncoding; +import org.bouncycastle.crypto.engines.RSABlindedEngine; +import org.bouncycastle.crypto.engines.RSAEngine; +import org.bouncycastle.crypto.params.RSAKeyParameters; +import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters; + +import java.security.Key; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.interfaces.RSAPrivateCrtKey; +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; + +/** + * RSA-OAEP, with the parameters built explicitly. + * + *

MGF1 follows the OAEP digest. The parameters are still + * built by hand rather than by asking for {@code OAEPWithSHA-256AndMGF1Padding}, + * for two reasons. There is no {@code OAEPWithSHA-512AndMGF1Padding} constant, + * so the SHA-512 wrapping specification has to be constructed - and a spec + * built by copying a SHA-1 example leaves MGF1 on SHA-1 and fails with an + * opaque OAEP decoding error on a hex string that looks perfectly valid. And + * every OAEP operation in this project routes through here, so the two digests + * cannot drift apart again. + */ +public final class RsaOaep { + + private RsaOaep() { + } + + /** The OAEP digest for a wrapping specification, or null when unsupported. */ + public static String digestFor(String wrappingSpec) { + if ("RSA_OAEP_SHA_256".equals(wrappingSpec) || wrappingSpec == null) { + return "SHA-256"; + } + if ("RSA_OAEP_SHA_512".equals(wrappingSpec)) { + return "SHA-512"; + } + return null; + } + + /** Decrypt an OAEP-wrapped block. */ + public static byte[] decrypt(PrivateKey key, byte[] ciphertext, String digest) { + return run(false, key, null, ciphertext, digest); + } + + /** Encrypt to an OAEP-wrapped block. Used by tests and by the demo. */ + public static byte[] encrypt(PublicKey key, byte[] plaintext, String digest) { + return run(true, null, key, plaintext, digest); + } + + /** + * The OAEP encoding, with the requested digest for the OAEP digest and for MGF1. + * + *

The label is empty, which is what the reference implementation's + * {@code PSource.PSpecified.DEFAULT} means. + */ + private static OAEPEncoding encoding(String digest, boolean encrypt) { + // The private operation is the blinded one: it decrypts what a caller brought, so its + // timing must not say how far the exponentiation has come. The public operation + // exponentiates with a public exponent, and blinding that protects nothing. + AsymmetricBlockCipher engine = encrypt ? new RSAEngine() : new RSABlindedEngine(); + Digest hash = "SHA-512".equals(digest) ? new SHA512Digest() : new SHA256Digest(); + return new OAEPEncoding(engine, hash, hash, null); + } + + private static byte[] run(boolean encrypt, PrivateKey priv, PublicKey pub, + byte[] input, String digest) { + try { + OAEPEncoding oaep = encoding(digest, encrypt); + if (encrypt) { + RSAPublicKey rsa = (RSAPublicKey) pub; + oaep.init(true, new RSAKeyParameters(false, rsa.getModulus(), rsa.getPublicExponent())); + } else { + oaep.init(false, privateParameters((RSAPrivateKey) priv)); + } + return oaep.processBlock(input, 0, input.length); + } catch (InvalidCipherTextException e) { + throw new IllegalArgumentException("RSA-OAEP failed: " + e.getMessage(), e); + } catch (RuntimeException e) { + throw new IllegalArgumentException("RSA-OAEP failed: " + e.getMessage(), e); + } + } + + /** + * The private key's parameters, with the CRT values when the key carries them. + * + *

The blinded engine blinds the exponentiation it is given, and it does so with the + * CRT values, so a key that has them is passed as they are. + * + * @param key the private key + * @return the parameters the engine works with + */ + private static RSAKeyParameters privateParameters(RSAPrivateKey key) { + if (key instanceof RSAPrivateCrtKey crt) { + return new RSAPrivateCrtKeyParameters(crt.getModulus(), crt.getPublicExponent(), + crt.getPrivateExponent(), crt.getPrimeP(), crt.getPrimeQ(), + crt.getPrimeExponentP(), crt.getPrimeExponentQ(), crt.getCrtCoefficient()); + } + return new RSAKeyParameters(true, key.getModulus(), key.getPrivateExponent()); + } + + /** Decrypt with a key given as the generic {@link Key} type. */ + public static byte[] decrypt(Key key, byte[] ciphertext, String digest) { + return decrypt((PrivateKey) key, ciphertext, digest); + } +} 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 458680d7f9..42c35064ea 100644 --- a/src/main/resources/aws/payment-cryptography-data-request-shapes.json +++ b/src/main/resources/aws/payment-cryptography-data-request-shapes.json @@ -4,19 +4,21 @@ "botocore": "botocore 1.43.118 (installed package)" }, "operations": { - "EncryptData": "EncryptDataInput", "DecryptData": "DecryptDataInput", - "ReEncryptData": "ReEncryptDataInput", - "GenerateMac": "GenerateMacInput", - "VerifyMac": "VerifyMacInput", - "GeneratePinData": "GeneratePinDataInput", - "VerifyPinData": "VerifyPinDataInput", - "TranslatePinData": "TranslatePinDataInput", - "GenerateMacEmvPinChange": "GenerateMacEmvPinChangeInput", - "GenerateCardValidationData": "GenerateCardValidationDataInput", - "VerifyCardValidationData": "VerifyCardValidationDataInput", + "EncryptData": "EncryptDataInput", + "GenerateAs2805KekValidation": "GenerateAs2805KekValidationInput", "GenerateAuthRequestCryptogram": "GenerateAuthRequestCryptogramInput", - "VerifyAuthRequestCryptogram": "VerifyAuthRequestCryptogramInput" + "GenerateCardValidationData": "GenerateCardValidationDataInput", + "GenerateMac": "GenerateMacInput", + "GenerateMacEmvPinChange": "GenerateMacEmvPinChangeInput", + "GeneratePinData": "GeneratePinDataInput", + "ReEncryptData": "ReEncryptDataInput", + "TranslateKeyMaterial": "TranslateKeyMaterialInput", + "TranslatePinData": "TranslatePinDataInput", + "VerifyAuthRequestCryptogram": "VerifyAuthRequestCryptogramInput", + "VerifyCardValidationData": "VerifyCardValidationDataInput", + "VerifyMac": "VerifyMacInput", + "VerifyPinData": "VerifyPinDataInput" }, "shapes": { "AmexAttributes": { @@ -63,6 +65,13 @@ "max": 16, "pattern": "[0-9a-fA-F]+" }, + "As2805KekValidationType": { + "type": "structure", + "members": { + "KekValidationRequest": "KekValidationRequest", + "KekValidationResponse": "KekValidationResponse" + } + }, "As2805PekDerivationAttributes": { "type": "structure", "required": [ @@ -74,6 +83,12 @@ "TransactionAmount": "TransactionAmountType" } }, + "As2805RandomKeyMaterial": { + "type": "string", + "min": 16, + "max": 48, + "pattern": "(?:[0-9a-fA-F]{16}|[0-9a-fA-F]{32}|[0-9a-fA-F]{48})" + }, "AsymmetricEncryptionAttributes": { "type": "structure", "members": { @@ -235,6 +250,12 @@ "Mastercard": "MasterCardAttributes" } }, + "DiffieHellmanDerivationData": { + "type": "structure", + "members": { + "SharedInformation": "SharedInformation" + } + }, "DiscoverDynamicCardVerificationCode": { "type": "structure", "required": [ @@ -466,6 +487,19 @@ "OFB" ] }, + "GenerateAs2805KekValidationInput": { + "type": "structure", + "required": [ + "KeyIdentifier", + "KekValidationType", + "RandomKeySendVariantMask" + ], + "members": { + "KeyIdentifier": "KeyArnOrKeyAliasType", + "KekValidationType": "As2805KekValidationType", + "RandomKeySendVariantMask": "RandomKeySendVariantMask" + } + }, "GenerateAuthRequestCryptogramInput": { "type": "structure", "required": [ @@ -661,6 +695,35 @@ "PinValidationData": "PinValidationDataType" } }, + "IncomingDiffieHellmanTr31KeyBlock": { + "type": "structure", + "required": [ + "PrivateKeyIdentifier", + "CertificateAuthorityPublicKeyIdentifier", + "PublicKeyCertificate", + "DeriveKeyAlgorithm", + "KeyDerivationFunction", + "KeyDerivationHashAlgorithm", + "DerivationData", + "WrappedKeyBlock" + ], + "members": { + "PrivateKeyIdentifier": "KeyArnOrKeyAliasType", + "CertificateAuthorityPublicKeyIdentifier": "KeyArnOrKeyAliasType", + "PublicKeyCertificate": "CertificateType", + "DeriveKeyAlgorithm": "SymmetricKeyAlgorithm", + "KeyDerivationFunction": "KeyDerivationFunction", + "KeyDerivationHashAlgorithm": "KeyDerivationHashAlgorithm", + "DerivationData": "DiffieHellmanDerivationData", + "WrappedKeyBlock": "Tr31WrappedKeyBlock" + } + }, + "IncomingKeyMaterial": { + "type": "structure", + "members": { + "DiffieHellmanTr31KeyBlock": "IncomingDiffieHellmanTr31KeyBlock" + } + }, "InitializationVectorType": { "type": "string", "min": 16, @@ -687,6 +750,25 @@ "min": 4, "max": 32 }, + "KekValidationRequest": { + "type": "structure", + "required": [ + "DeriveKeyAlgorithm" + ], + "members": { + "DeriveKeyAlgorithm": "SymmetricKeyAlgorithm", + "RandomKeyMaxLength": "RandomKeyMaxLength" + } + }, + "KekValidationResponse": { + "type": "structure", + "required": [ + "RandomKeySend" + ], + "members": { + "RandomKeySend": "As2805RandomKeyMaterial" + } + }, "KeyArnOrKeyAliasType": { "type": "string", "min": 7, @@ -810,6 +892,21 @@ "max": 2, "pattern": "[0-9]+" }, + "OutgoingKeyMaterial": { + "type": "structure", + "members": { + "Tr31KeyBlock": "OutgoingTr31KeyBlock" + } + }, + "OutgoingTr31KeyBlock": { + "type": "structure", + "required": [ + "WrappingKeyIdentifier" + ], + "members": { + "WrappingKeyIdentifier": "KeyArnOrKeyAliasType" + } + }, "PaddingType": { "type": "string", "enum": [ @@ -904,6 +1001,21 @@ "max": 16, "pattern": "[0-9a-fA-F]+" }, + "RandomKeyMaxLength": { + "type": "string", + "enum": [ + "BYTES_8", + "BYTES_16", + "BYTES_24" + ] + }, + "RandomKeySendVariantMask": { + "type": "string", + "enum": [ + "VARIANT_MASK_82C0", + "VARIANT_MASK_82" + ] + }, "ReEncryptDataInput": { "type": "structure", "required": [ @@ -1109,6 +1221,18 @@ "max": 1024, "pattern": "[0-9a-fA-F]+" }, + "TranslateKeyMaterialInput": { + "type": "structure", + "required": [ + "IncomingKeyMaterial", + "OutgoingKeyMaterial" + ], + "members": { + "IncomingKeyMaterial": "IncomingKeyMaterial", + "OutgoingKeyMaterial": "OutgoingKeyMaterial", + "KeyCheckValueAlgorithm": "KeyCheckValueAlgorithm" + } + }, "TranslatePinDataInput": { "type": "structure", "required": [ diff --git a/src/main/resources/aws/payment-cryptography-request-shapes.json b/src/main/resources/aws/payment-cryptography-request-shapes.json index 973325d26c..287447b9b8 100644 --- a/src/main/resources/aws/payment-cryptography-request-shapes.json +++ b/src/main/resources/aws/payment-cryptography-request-shapes.json @@ -4,29 +4,144 @@ "botocore": "botocore 1.43.118 (installed package)" }, "operations": { - "CreateKey": "CreateKeyInput", - "GetKey": "GetKeyInput", - "ListKeys": "ListKeysInput", - "DeleteKey": "DeleteKeyInput", + "AddKeyReplicationRegions": "AddKeyReplicationRegionsInput", + "AssociateMpaTeam": "AssociateMpaTeamInput", "CreateAlias": "CreateAliasInput", - "GetAlias": "GetAliasInput", - "ListAliases": "ListAliasesInput", - "UpdateAlias": "UpdateAliasInput", + "CreateKey": "CreateKeyInput", "DeleteAlias": "DeleteAliasInput", + "DeleteKey": "DeleteKeyInput", + "DeleteResourcePolicy": "DeleteResourcePolicyInput", + "DisableDefaultKeyReplicationRegions": "DisableDefaultKeyReplicationRegionsInput", + "DisassociateMpaTeam": "DisassociateMpaTeamInput", + "EnableDefaultKeyReplicationRegions": "EnableDefaultKeyReplicationRegionsInput", + "ExportKey": "ExportKeyInput", + "GetAlias": "GetAliasInput", + "GetCertificateSigningRequest": "GetCertificateSigningRequestInput", + "GetDefaultKeyReplicationRegions": "GetDefaultKeyReplicationRegionsInput", + "GetKey": "GetKeyInput", + "GetMpaTeamAssociation": "GetMpaTeamAssociationInput", + "GetParametersForExport": "GetParametersForExportInput", + "GetParametersForImport": "GetParametersForImportInput", + "GetPublicKeyCertificate": "GetPublicKeyCertificateInput", + "GetResourcePolicy": "GetResourcePolicyInput", + "ImportKey": "ImportKeyInput", + "ListAliases": "ListAliasesInput", + "ListKeys": "ListKeysInput", + "ListTagsForResource": "ListTagsForResourceInput", + "PutResourcePolicy": "PutResourcePolicyInput", + "RemoveKeyReplicationRegions": "RemoveKeyReplicationRegionsInput", + "RestoreKey": "RestoreKeyInput", + "StartKeyUsage": "StartKeyUsageInput", + "StopKeyUsage": "StopKeyUsageInput", "TagResource": "TagResourceInput", "UntagResource": "UntagResourceInput", - "ListTagsForResource": "ListTagsForResourceInput" + "UpdateAlias": "UpdateAliasInput" }, "shapes": { + "AddKeyReplicationRegionsInput": { + "type": "structure", + "required": [ + "KeyIdentifier", + "ReplicationRegions" + ], + "members": { + "KeyIdentifier": "KeyArnOrKeyAliasType", + "ReplicationRegions": "Regions" + } + }, "AliasName": { "type": "string", "min": 7, "max": 256, "pattern": "alias/[a-zA-Z0-9/_-]+" }, + "As2805KeyVariant": { + "type": "string", + "enum": [ + "TERMINAL_MAJOR_KEY_VARIANT_00", + "PIN_ENCRYPTION_KEY_VARIANT_28", + "MESSAGE_AUTHENTICATION_KEY_VARIANT_24", + "DATA_ENCRYPTION_KEY_VARIANT_22" + ] + }, + "AssociateMpaTeamInput": { + "type": "structure", + "required": [ + "Action", + "MpaTeamArn" + ], + "members": { + "Action": "MpaOperation", + "MpaTeamArn": "MpaTeamArn", + "RequesterComment": "MpaRequesterComment" + } + }, "Boolean": { "type": "boolean" }, + "CertificateSubjectType": { + "type": "structure", + "required": [ + "CommonName" + ], + "members": { + "CommonName": "CertificateSubjectTypeCommonNameString", + "OrganizationUnit": "CertificateSubjectTypeOrganizationUnitString", + "Organization": "CertificateSubjectTypeOrganizationString", + "City": "CertificateSubjectTypeCityString", + "Country": "CertificateSubjectTypeCountryString", + "StateOrProvince": "CertificateSubjectTypeStateOrProvinceString", + "EmailAddress": "CertificateSubjectTypeEmailAddressString" + } + }, + "CertificateSubjectTypeCityString": { + "type": "string", + "min": 1, + "max": 128, + "pattern": "[^\\[;\\]<>]+" + }, + "CertificateSubjectTypeCommonNameString": { + "type": "string", + "min": 1, + "max": 64, + "pattern": "[^\\[;\\]<>]+" + }, + "CertificateSubjectTypeCountryString": { + "type": "string", + "min": 2, + "max": 2, + "pattern": "[A-Za-z]+" + }, + "CertificateSubjectTypeEmailAddressString": { + "type": "string", + "min": 1, + "max": 128, + "pattern": "[a-zA-Z0-9.!#$%&\u2019*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*" + }, + "CertificateSubjectTypeOrganizationString": { + "type": "string", + "min": 1, + "max": 64, + "pattern": "[^\\[;\\]<>]+" + }, + "CertificateSubjectTypeOrganizationUnitString": { + "type": "string", + "min": 1, + "max": 64, + "pattern": "[^\\[;\\]<>]+" + }, + "CertificateSubjectTypeStateOrProvinceString": { + "type": "string", + "min": 1, + "max": 128, + "pattern": "[^\\[;\\]<>]+" + }, + "CertificateType": { + "type": "string", + "min": 1, + "max": 32768, + "pattern": "[^\\[;\\]<>]+" + }, "CreateAliasInput": { "type": "structure", "required": [ @@ -77,6 +192,15 @@ "min": 3, "max": 180 }, + "DeleteResourcePolicyInput": { + "type": "structure", + "required": [ + "ResourceArn" + ], + "members": { + "ResourceArn": "ResourceArn" + } + }, "DeriveKeyUsage": { "type": "string", "enum": [ @@ -101,6 +225,161 @@ "TR31_V2_VISA_PIN_VERIFICATION_KEY" ] }, + "DiffieHellmanDerivationData": { + "type": "structure", + "members": { + "SharedInformation": "SharedInformation" + } + }, + "DisableDefaultKeyReplicationRegionsInput": { + "type": "structure", + "required": [ + "ReplicationRegions" + ], + "members": { + "ReplicationRegions": "Regions" + } + }, + "DisassociateMpaTeamInput": { + "type": "structure", + "required": [ + "Action" + ], + "members": { + "Action": "MpaOperation", + "RequesterComment": "MpaRequesterComment" + } + }, + "EnableDefaultKeyReplicationRegionsInput": { + "type": "structure", + "required": [ + "ReplicationRegions" + ], + "members": { + "ReplicationRegions": "Regions" + } + }, + "EvenHexLengthBetween16And32": { + "type": "string", + "min": 16, + "max": 32, + "pattern": "(?:[0-9a-fA-F][0-9a-fA-F])+" + }, + "ExportAs2805KeyCryptogram": { + "type": "structure", + "required": [ + "WrappingKeyIdentifier", + "As2805KeyVariant" + ], + "members": { + "WrappingKeyIdentifier": "KeyArnOrKeyAliasType", + "As2805KeyVariant": "As2805KeyVariant" + } + }, + "ExportAttributes": { + "type": "structure", + "members": { + "ExportDukptInitialKey": "ExportDukptInitialKey", + "KeyCheckValueAlgorithm": "KeyCheckValueAlgorithm" + } + }, + "ExportDiffieHellmanTr31KeyBlock": { + "type": "structure", + "required": [ + "PrivateKeyIdentifier", + "CertificateAuthorityPublicKeyIdentifier", + "PublicKeyCertificate", + "DeriveKeyAlgorithm", + "KeyDerivationFunction", + "KeyDerivationHashAlgorithm", + "DerivationData" + ], + "members": { + "PrivateKeyIdentifier": "KeyArnOrKeyAliasType", + "CertificateAuthorityPublicKeyIdentifier": "KeyArnOrKeyAliasType", + "PublicKeyCertificate": "CertificateType", + "DeriveKeyAlgorithm": "SymmetricKeyAlgorithm", + "KeyDerivationFunction": "KeyDerivationFunction", + "KeyDerivationHashAlgorithm": "KeyDerivationHashAlgorithm", + "DerivationData": "DiffieHellmanDerivationData", + "KeyBlockHeaders": "KeyBlockHeaders" + } + }, + "ExportDukptInitialKey": { + "type": "structure", + "required": [ + "KeySerialNumber" + ], + "members": { + "KeySerialNumber": "HexLength20Or24" + } + }, + "ExportKeyCryptogram": { + "type": "structure", + "required": [ + "CertificateAuthorityPublicKeyIdentifier", + "WrappingKeyCertificate" + ], + "members": { + "CertificateAuthorityPublicKeyIdentifier": "KeyArnOrKeyAliasType", + "WrappingKeyCertificate": "CertificateType", + "WrappingSpec": "WrappingKeySpec" + } + }, + "ExportKeyInput": { + "type": "structure", + "required": [ + "KeyMaterial", + "ExportKeyIdentifier" + ], + "members": { + "KeyMaterial": "ExportKeyMaterial", + "ExportKeyIdentifier": "KeyArnOrKeyAliasType", + "ExportAttributes": "ExportAttributes" + } + }, + "ExportKeyMaterial": { + "type": "structure", + "members": { + "Tr31KeyBlock": "ExportTr31KeyBlock", + "Tr34KeyBlock": "ExportTr34KeyBlock", + "KeyCryptogram": "ExportKeyCryptogram", + "DiffieHellmanTr31KeyBlock": "ExportDiffieHellmanTr31KeyBlock", + "As2805KeyCryptogram": "ExportAs2805KeyCryptogram" + } + }, + "ExportTokenId": { + "type": "string", + "pattern": "(export-token-[0-9a-zA-Z]{16,64})?" + }, + "ExportTr31KeyBlock": { + "type": "structure", + "required": [ + "WrappingKeyIdentifier" + ], + "members": { + "WrappingKeyIdentifier": "KeyArnOrKeyAliasType", + "KeyBlockHeaders": "KeyBlockHeaders" + } + }, + "ExportTr34KeyBlock": { + "type": "structure", + "required": [ + "CertificateAuthorityPublicKeyIdentifier", + "WrappingKeyCertificate", + "KeyBlockFormat" + ], + "members": { + "CertificateAuthorityPublicKeyIdentifier": "KeyArnOrKeyAliasType", + "WrappingKeyCertificate": "CertificateType", + "ExportToken": "ExportTokenId", + "SigningKeyIdentifier": "KeyArnOrKeyAliasType", + "SigningKeyCertificate": "CertificateType", + "KeyBlockFormat": "Tr34KeyBlockFormat", + "RandomNonce": "EvenHexLengthBetween16And32", + "KeyBlockHeaders": "KeyBlockHeaders" + } + }, "GetAliasInput": { "type": "structure", "required": [ @@ -110,6 +389,23 @@ "AliasName": "AliasName" } }, + "GetCertificateSigningRequestInput": { + "type": "structure", + "required": [ + "KeyIdentifier", + "SigningAlgorithm", + "CertificateSubject" + ], + "members": { + "KeyIdentifier": "KeyArnOrKeyAliasType", + "SigningAlgorithm": "SigningAlgorithmType", + "CertificateSubject": "CertificateSubjectType" + } + }, + "GetDefaultKeyReplicationRegionsInput": { + "type": "structure", + "members": {} + }, "GetKeyInput": { "type": "structure", "required": [ @@ -119,6 +415,181 @@ "KeyIdentifier": "KeyArnOrKeyAliasType" } }, + "GetMpaTeamAssociationInput": { + "type": "structure", + "required": [ + "Action" + ], + "members": { + "Action": "MpaOperation" + } + }, + "GetParametersForExportInput": { + "type": "structure", + "required": [ + "KeyMaterialType", + "SigningKeyAlgorithm" + ], + "members": { + "KeyMaterialType": "KeyMaterialType", + "SigningKeyAlgorithm": "KeyAlgorithm", + "ReuseLastGeneratedToken": "Boolean" + } + }, + "GetParametersForImportInput": { + "type": "structure", + "required": [ + "KeyMaterialType", + "WrappingKeyAlgorithm" + ], + "members": { + "KeyMaterialType": "KeyMaterialType", + "WrappingKeyAlgorithm": "KeyAlgorithm", + "ReuseLastGeneratedToken": "Boolean" + } + }, + "GetPublicKeyCertificateInput": { + "type": "structure", + "required": [ + "KeyIdentifier" + ], + "members": { + "KeyIdentifier": "KeyArnOrKeyAliasType" + } + }, + "GetResourcePolicyInput": { + "type": "structure", + "required": [ + "ResourceArn" + ], + "members": { + "ResourceArn": "ResourceArn" + } + }, + "HexLength20Or24": { + "type": "string", + "min": 20, + "max": 24, + "pattern": "[0-9A-F]{20}$|^[0-9A-F]{24}" + }, + "ImportAs2805KeyCryptogram": { + "type": "structure", + "required": [ + "As2805KeyVariant", + "KeyModesOfUse", + "KeyAlgorithm", + "Exportable", + "WrappingKeyIdentifier", + "WrappedKeyCryptogram" + ], + "members": { + "As2805KeyVariant": "As2805KeyVariant", + "KeyModesOfUse": "KeyModesOfUse", + "KeyAlgorithm": "KeyAlgorithm", + "Exportable": "Boolean", + "WrappingKeyIdentifier": "KeyArnOrKeyAliasType", + "WrappedKeyCryptogram": "WrappedKeyCryptogram" + } + }, + "ImportDiffieHellmanTr31KeyBlock": { + "type": "structure", + "required": [ + "PrivateKeyIdentifier", + "CertificateAuthorityPublicKeyIdentifier", + "PublicKeyCertificate", + "DeriveKeyAlgorithm", + "KeyDerivationFunction", + "KeyDerivationHashAlgorithm", + "DerivationData", + "WrappedKeyBlock" + ], + "members": { + "PrivateKeyIdentifier": "KeyArnOrKeyAliasType", + "CertificateAuthorityPublicKeyIdentifier": "KeyArnOrKeyAliasType", + "PublicKeyCertificate": "CertificateType", + "DeriveKeyAlgorithm": "SymmetricKeyAlgorithm", + "KeyDerivationFunction": "KeyDerivationFunction", + "KeyDerivationHashAlgorithm": "KeyDerivationHashAlgorithm", + "DerivationData": "DiffieHellmanDerivationData", + "WrappedKeyBlock": "Tr31WrappedKeyBlock" + } + }, + "ImportKeyCryptogram": { + "type": "structure", + "required": [ + "KeyAttributes", + "Exportable", + "WrappedKeyCryptogram", + "ImportToken" + ], + "members": { + "KeyAttributes": "KeyAttributes", + "Exportable": "Boolean", + "WrappedKeyCryptogram": "WrappedKeyCryptogram", + "ImportToken": "ImportTokenId", + "WrappingSpec": "WrappingKeySpec" + } + }, + "ImportKeyInput": { + "type": "structure", + "required": [ + "KeyMaterial" + ], + "members": { + "KeyMaterial": "ImportKeyMaterial", + "KeyCheckValueAlgorithm": "KeyCheckValueAlgorithm", + "Enabled": "Boolean", + "Tags": "Tags", + "ReplicationRegions": "Regions", + "RequesterComment": "MpaRequesterComment" + } + }, + "ImportKeyMaterial": { + "type": "structure", + "members": { + "RootCertificatePublicKey": "RootCertificatePublicKey", + "TrustedCertificatePublicKey": "TrustedCertificatePublicKey", + "Tr31KeyBlock": "ImportTr31KeyBlock", + "Tr34KeyBlock": "ImportTr34KeyBlock", + "KeyCryptogram": "ImportKeyCryptogram", + "DiffieHellmanTr31KeyBlock": "ImportDiffieHellmanTr31KeyBlock", + "As2805KeyCryptogram": "ImportAs2805KeyCryptogram" + } + }, + "ImportTokenId": { + "type": "string", + "pattern": "(import-token-[0-9a-zA-Z]{16,64})?" + }, + "ImportTr31KeyBlock": { + "type": "structure", + "required": [ + "WrappingKeyIdentifier", + "WrappedKeyBlock" + ], + "members": { + "WrappingKeyIdentifier": "KeyArnOrKeyAliasType", + "WrappedKeyBlock": "Tr31WrappedKeyBlock" + } + }, + "ImportTr34KeyBlock": { + "type": "structure", + "required": [ + "CertificateAuthorityPublicKeyIdentifier", + "SigningKeyCertificate", + "WrappedKeyBlock", + "KeyBlockFormat" + ], + "members": { + "CertificateAuthorityPublicKeyIdentifier": "KeyArnOrKeyAliasType", + "SigningKeyCertificate": "CertificateType", + "ImportToken": "ImportTokenId", + "WrappingKeyIdentifier": "KeyArnOrKeyAliasType", + "WrappingKeyCertificate": "CertificateType", + "WrappedKeyBlock": "Tr34WrappedKeyBlock", + "KeyBlockFormat": "Tr34KeyBlockFormat", + "RandomNonce": "EvenHexLengthBetween16And32" + } + }, "KeyAlgorithm": { "type": "string", "enum": [ @@ -166,6 +637,15 @@ "KeyModesOfUse": "KeyModesOfUse" } }, + "KeyBlockHeaders": { + "type": "structure", + "members": { + "KeyModesOfUse": "KeyModesOfUse", + "KeyExportability": "KeyExportability", + "KeyVersion": "KeyVersion", + "OptionalBlocks": "OptionalBlocks" + } + }, "KeyCheckValueAlgorithm": { "type": "string", "enum": [ @@ -184,6 +664,39 @@ "PUBLIC_KEY" ] }, + "KeyDerivationFunction": { + "type": "string", + "enum": [ + "NIST_SP800", + "ANSI_X963" + ] + }, + "KeyDerivationHashAlgorithm": { + "type": "string", + "enum": [ + "SHA_256", + "SHA_384", + "SHA_512" + ] + }, + "KeyExportability": { + "type": "string", + "enum": [ + "EXPORTABLE", + "NON_EXPORTABLE", + "SENSITIVE" + ] + }, + "KeyMaterialType": { + "type": "string", + "enum": [ + "TR34_KEY_BLOCK", + "TR31_KEY_BLOCK", + "ROOT_PUBLIC_KEY_CERTIFICATE", + "TRUSTED_PUBLIC_KEY_CERTIFICATE", + "KEY_CRYPTOGRAM" + ] + }, "KeyModesOfUse": { "type": "structure", "members": { @@ -236,6 +749,12 @@ "TR31_K2_TR34_ASYMMETRIC_KEY" ] }, + "KeyVersion": { + "type": "string", + "min": 2, + "max": 2, + "pattern": "[0-9A-Z]{2}+" + }, "ListAliasesInput": { "type": "structure", "members": { @@ -268,14 +787,59 @@ "min": 1, "max": 100 }, + "MpaOperation": { + "type": "string", + "enum": [ + "IMPORT_ROOT_PUBLIC_KEY_CERTIFICATE" + ] + }, + "MpaRequesterComment": { + "type": "string", + "min": 0, + "max": 200 + }, + "MpaTeamArn": { + "type": "string", + "min": 20, + "max": 2048, + "pattern": "arn:aws(-[^:]+)?:mpa:[a-z0-9-]{1,20}:[0-9]{12}:approval-team/[a-zA-Z0-9._-]+" + }, "NextToken": { "type": "string", "min": 1, "max": 8192 }, + "OptionalBlockId": { + "type": "string", + "min": 2, + "max": 2, + "pattern": "[0-9A-Z]{2}+" + }, + "OptionalBlockValue": { + "type": "string", + "min": 1, + "max": 108, + "pattern": "[0-9a-zA-Z]+" + }, + "OptionalBlocks": { + "type": "map", + "key": "OptionalBlockId", + "value": "OptionalBlockValue" + }, "PrimitiveBoolean": { "type": "boolean" }, + "PutResourcePolicyInput": { + "type": "structure", + "required": [ + "ResourceArn", + "Policy" + ], + "members": { + "ResourceArn": "ResourceArn", + "Policy": "ResourcePolicy" + } + }, "Region": { "type": "string", "pattern": "[a-z]{2,4}(-[a-z]{1,16})+-[0-9]+" @@ -284,12 +848,96 @@ "type": "list", "member": "Region" }, + "RemoveKeyReplicationRegionsInput": { + "type": "structure", + "required": [ + "KeyIdentifier", + "ReplicationRegions" + ], + "members": { + "KeyIdentifier": "KeyArnOrKeyAliasType", + "ReplicationRegions": "Regions" + } + }, "ResourceArn": { "type": "string", "min": 70, "max": 150, "pattern": "arn:aws[a-z0-9-]*:payment-cryptography:[a-z]{2,4}(-[a-z]{1,16})+-[0-9]+:[0-9]{12}:key/[0-9a-zA-Z]{16,64}" }, + "ResourcePolicy": { + "type": "string", + "min": 1, + "max": 20480, + "pattern": "[\\u0009\\u000A\\u000D\\u0020-\\u00FF]+" + }, + "RestoreKeyInput": { + "type": "structure", + "required": [ + "KeyIdentifier" + ], + "members": { + "KeyIdentifier": "KeyArnOrKeyAliasType" + } + }, + "RootCertificatePublicKey": { + "type": "structure", + "required": [ + "KeyAttributes", + "PublicKeyCertificate" + ], + "members": { + "KeyAttributes": "KeyAttributes", + "PublicKeyCertificate": "CertificateType" + } + }, + "SharedInformation": { + "type": "string", + "min": 2, + "max": 2048, + "pattern": "(?:[0-9a-fA-F][0-9a-fA-F])+" + }, + "SigningAlgorithmType": { + "type": "string", + "enum": [ + "SHA224", + "SHA256", + "SHA384", + "SHA512" + ] + }, + "StartKeyUsageInput": { + "type": "structure", + "required": [ + "KeyIdentifier" + ], + "members": { + "KeyIdentifier": "KeyArnOrKeyAliasType" + } + }, + "StopKeyUsageInput": { + "type": "structure", + "required": [ + "KeyIdentifier" + ], + "members": { + "KeyIdentifier": "KeyArnOrKeyAliasType" + } + }, + "SymmetricKeyAlgorithm": { + "type": "string", + "enum": [ + "TDES_2KEY", + "TDES_3KEY", + "AES_128", + "AES_192", + "AES_256", + "HMAC_SHA256", + "HMAC_SHA384", + "HMAC_SHA512", + "HMAC_SHA224" + ] + }, "Tag": { "type": "structure", "required": [ @@ -334,6 +982,37 @@ "max": 200, "member": "Tag" }, + "Tr31WrappedKeyBlock": { + "type": "string", + "min": 56, + "max": 9984, + "pattern": "[0-9a-zA-Z]+" + }, + "Tr34KeyBlockFormat": { + "type": "string", + "enum": [ + "X9_TR34_2012" + ] + }, + "Tr34WrappedKeyBlock": { + "type": "string", + "min": 2, + "max": 4096, + "pattern": "[0-9A-F]+" + }, + "TrustedCertificatePublicKey": { + "type": "structure", + "required": [ + "KeyAttributes", + "PublicKeyCertificate", + "CertificateAuthorityPublicKeyIdentifier" + ], + "members": { + "KeyAttributes": "KeyAttributes", + "PublicKeyCertificate": "CertificateType", + "CertificateAuthorityPublicKeyIdentifier": "KeyArnOrKeyAliasType" + } + }, "UntagResourceInput": { "type": "structure", "required": [ @@ -354,6 +1033,19 @@ "AliasName": "AliasName", "KeyArn": "KeyArn" } + }, + "WrappedKeyCryptogram": { + "type": "string", + "min": 16, + "max": 4096, + "pattern": "[0-9A-F]+" + }, + "WrappingKeySpec": { + "type": "string", + "enum": [ + "RSA_OAEP_SHA_256", + "RSA_OAEP_SHA_512" + ] } } } diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperationsTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperationsTest.java index 1bd1ac8077..bdd098ee01 100644 --- a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperationsTest.java +++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperationsTest.java @@ -146,6 +146,22 @@ class PaymentCryptographyAuthCryptogramOperationsTest { "4111111111111111111", PSN)), HEX.formatHex(optionB)); } + @Test + void aRequestWithoutItsDerivationAttributesIsRefusedByTheModel() { + // The shape check settles the members the model requires, so it is the refusal that + // answers, and the message a caller sees is its own. + AwsException refused = assertThrows(AwsException.class, + () -> cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of( + "KeyIdentifier", "arn:aws:payment-cryptography:us-east-1:000000000000:key/" + + "0123456789abcdef", + "TransactionData", TRANSACTION_DATA, + "MajorKeyDerivationMode", "EMV_OPTION_A")), "us-east-1")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("failed to satisfy constraint"), refused.getMessage()); + assertTrue(refused.getMessage().contains("SessionKeyDerivationAttributes"), refused.getMessage()); + } + @Test void theEmv41DerivationIsRefusedRatherThanApproximated() { PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey"); diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyIntegrationTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyIntegrationTest.java index 3d72c4a75c..8136534a18 100644 --- a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyIntegrationTest.java @@ -65,6 +65,12 @@ class PaymentCryptographyIntegrationTest { "KeyModesOfUse":{"Encrypt":true,"Decrypt":true}}, "Exportable":true}"""; + private static final String CREATE_KEY_PAIR = """ + {"KeyAttributes":{"KeyAlgorithm":"RSA_2048","KeyClass":"ASYMMETRIC_KEY_PAIR", + "KeyUsage":"TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE", + "KeyModesOfUse":{"Sign":true,"Verify":true}}, + "Exportable":true}"""; + @Test void aKeyIsCreatedAndReadBack() { String arn = call("CreateKey", CREATE_KEY) @@ -101,6 +107,276 @@ class PaymentCryptographyIntegrationTest { .body("Key.DeriveKeyUsage", equalTo("TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY")); } + @Test + void anInitialKeyLeavesUnderTheBaseKeyItIsDerivedFrom() { + // The export names the key that leaves and the attributes that say which key of it + // leaves: the initial key is derived from the base key and is not the base key. + // The base derivation key is a double-length Triple DES key, which is what the + // derivation is defined over. + String base = call("CreateKey", "{\"KeyAttributes\":{\"KeyAlgorithm\":\"TDES_2KEY\"," + + "\"KeyClass\":\"SYMMETRIC_KEY\",\"KeyUsage\":\"TR31_B0_BASE_DERIVATION_KEY\"," + + "\"KeyModesOfUse\":{\"DeriveKey\":true}}," + + "\"Exportable\":true}") + .then().statusCode(200) + .extract().path("Key.KeyArn"); + String protection = call("CreateKey", "{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\"," + + "\"KeyClass\":\"SYMMETRIC_KEY\"," + + "\"KeyUsage\":\"TR31_K1_KEY_BLOCK_PROTECTION_KEY\"," + + "\"KeyModesOfUse\":{\"Wrap\":true,\"Unwrap\":true}}," + + "\"Exportable\":true}") + .then().statusCode(200) + .extract().path("Key.KeyArn"); + + call("ExportKey", """ + {"ExportKeyIdentifier":"%s", + "ExportAttributes":{"ExportDukptInitialKey": + {"KeySerialNumber":"12345678900000000001"}}, + "KeyMaterial":{"Tr31KeyBlock":{"WrappingKeyIdentifier":"%s"}}} + """.formatted(base, protection)) + .then().statusCode(200) + .body("WrappedKey.WrappedKeyMaterialFormat", equalTo("TR31_KEY_BLOCK")) + .body("WrappedKey.WrappingKeyArn", equalTo(protection)); + } + + @Test + void theImportParametersAreServedOverTheWire() { + call("GetParametersForImport", """ + {"KeyMaterialType":"KEY_CRYPTOGRAM","WrappingKeyAlgorithm":"RSA_2048"} + """) + .then().statusCode(200) + .body("ImportToken", matchesPattern("import-token-[0-9a-zA-Z]{16,64}")) + .body("WrappingKeyAlgorithm", equalTo("RSA_2048")) + .body("WrappingKeyCertificate", notNullValue()) + .body("WrappingKeyCertificateChain", notNullValue()) + .body("ParametersValidUntilTimestamp", greaterThanOrEqualTo(0)); + } + + @Test + void theParametersCanBeReusedOverTheWire() { + // A caller that asks for the last parameters gets them, token and certificate alike. + String first = call("GetParametersForImport", """ + {"KeyMaterialType":"KEY_CRYPTOGRAM","WrappingKeyAlgorithm":"RSA_2048"} + """) + .then().statusCode(200) + .extract().path("ImportToken"); + + call("GetParametersForImport", """ + {"KeyMaterialType":"KEY_CRYPTOGRAM","WrappingKeyAlgorithm":"RSA_2048", + "ReuseLastGeneratedToken":true} + """) + .then().statusCode(200) + .body("ImportToken", equalTo(first)); + } + + @Test + void theExportParametersAreServedOverTheWire() { + call("GetParametersForExport", """ + {"KeyMaterialType":"TR34_KEY_BLOCK","SigningKeyAlgorithm":"RSA_2048"} + """) + .then().statusCode(200) + .body("ExportToken", matchesPattern("export-token-[0-9a-zA-Z]{16,64}")) + .body("SigningKeyAlgorithm", equalTo("RSA_2048")) + .body("SigningKeyCertificate", notNullValue()) + .body("SigningKeyCertificateChain", notNullValue()) + .body("ParametersValidUntilTimestamp", greaterThanOrEqualTo(0)); + } + + @Test + void anImportedKeyCarriesTheEnabledFlagAndTheTags() { + // The import names the key's state and its tags, and the key comes back that way. + String wrapping = call("CreateKey", """ + {"KeyAttributes":{"KeyAlgorithm":"AES_256","KeyClass":"SYMMETRIC_KEY", + "KeyUsage":"TR31_K1_KEY_BLOCK_PROTECTION_KEY", + "KeyModesOfUse":{"Wrap":true,"Unwrap":true}}, + "Exportable":true} + """) + .then().statusCode(200) + .extract().path("Key.KeyArn"); + String arn = call("CreateKey", CREATE_KEY) + .then().statusCode(200) + .extract().path("Key.KeyArn"); + String block = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + arn + + "\",\"KeyMaterial\":{\"Tr31KeyBlock\":{\"WrappingKeyIdentifier\":\"" + + wrapping + "\"}}}") + .then().statusCode(200) + .extract().path("WrappedKey.KeyMaterial"); + + String importedArn = call("ImportKey", "{\"KeyMaterial\":{\"Tr31KeyBlock\":{" + + "\"WrappingKeyIdentifier\":\"" + wrapping + "\",\"WrappedKeyBlock\":\"" + block + + "\"}},\"Enabled\":false,\"Tags\":[{\"Key\":\"Origin\",\"Value\":\"PRIMARY\"}]}") + .then().statusCode(200) + .body("Key.Enabled", equalTo(false)) + .extract().path("Key.KeyArn"); + + // The key's answer carries no tags, so they are read the way they are read elsewhere. + call("ListTagsForResource", "{\"ResourceArn\":\"" + importedArn + "\"}") + .then().statusCode(200) + .body("Tags[0].Key", equalTo("Origin")) + .body("Tags[0].Value", equalTo("PRIMARY")); + } + + @Test + void aRequestNamingTwoFormsIsRefused() { + // The union holds one form per request, and naming two is not naming one. + String arn = call("CreateKey", CREATE_KEY) + .then().statusCode(200) + .extract().path("Key.KeyArn"); + + call("ExportKey", "{\"ExportKeyIdentifier\":\"" + arn + "\",\"KeyMaterial\":{" + + "\"Tr31KeyBlock\":{\"WrappingKeyIdentifier\":\"" + arn + "\"}," + + "\"KeyCryptogram\":{\"CertificateAuthorityPublicKeyIdentifier\":\"" + arn + + "\",\"WrappingKeyCertificate\":\"x\"}}}") + .then().statusCode(400) + .body("__type", equalTo("ValidationException")); + } + + @Test + void aRequestNamingAFormTheServiceDoesNotServeIsRefused() { + // The TR-34 form is one the model has and this service does not make. + String arn = call("CreateKey", CREATE_KEY) + .then().statusCode(200) + .extract().path("Key.KeyArn"); + + call("ExportKey", "{\"ExportKeyIdentifier\":\"" + arn + "\",\"KeyMaterial\":{" + + "\"Tr34KeyBlock\":{\"CertificateAuthorityPublicKeyIdentifier\":\"" + arn + + "\",\"WrappingKeyCertificate\":\"x\",\"KeyBlockFormat\":\"X9_TR34_2012\"}}}") + .then().statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", containsString("not a form the service exports")); + } + + /** + * The shape check settles the members the model requires, so a request missing one is + * refused by it, before the operation does any work. The refusal a caller sees is + * therefore the shape check's, and the service does not repeat the check. + */ + @Test + void theModelCheckRefusesAnExportWithoutAWrappingKeyCertificate() { + String arn = call("CreateKey", CREATE_KEY) + .then().statusCode(200) + .extract().path("Key.KeyArn"); + + Response answer = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + arn + "\",\"KeyMaterial\":{" + + "\"KeyCryptogram\":{\"CertificateAuthorityPublicKeyIdentifier\":\"" + arn + "\"}}}"); + + assertTheModelRefused(answer, "WrappingKeyCertificate"); + } + + @Test + void theModelCheckRefusesAnImportWithoutItsKeyAttributes() { + Response answer = call("ImportKey", "{\"KeyMaterial\":{\"KeyCryptogram\":{" + + "\"Exportable\":true," + + "\"WrappedKeyCryptogram\":\"" + "0".repeat(32) + "\"," + + "\"ImportToken\":\"import-token-" + "0".repeat(24) + "\"}}}"); + + assertTheModelRefused(answer, "KeyAttributes"); + } + + @Test + void theModelCheckRefusesAnImportWhoseKeyAttributesHaveNoUsage() { + Response answer = call("ImportKey", "{\"KeyMaterial\":{\"KeyCryptogram\":{" + + "\"Exportable\":true," + + "\"WrappedKeyCryptogram\":\"" + "0".repeat(32) + "\"," + + "\"ImportToken\":\"import-token-" + "0".repeat(24) + "\"," + + "\"KeyAttributes\":{\"KeyClass\":\"SYMMETRIC_KEY\"," + + "\"KeyAlgorithm\":\"AES_128\"," + + "\"KeyModesOfUse\":{\"Encrypt\":true,\"Decrypt\":true}}}}}"); + + assertTheModelRefused(answer, "KeyUsage"); + } + + @Test + void theModelCheckRefusesAnImportOfAPublicKeyWithoutItsKeyAttributes() { + Response answer = call("ImportKey", "{\"KeyMaterial\":{\"RootCertificatePublicKey\":{" + + "\"PublicKeyCertificate\":\"a certificate\"}}}"); + + assertTheModelRefused(answer, "KeyAttributes"); + } + + @Test + void theModelCheckRefusesAnExportWithoutItsCertificateAuthorityPublicKeyIdentifier() { + Response answer = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + keyArn() + "\"," + + "\"KeyMaterial\":{\"KeyCryptogram\":{\"WrappingKeyCertificate\":\"a certificate\"}}}"); + + assertTheModelRefused(answer, "CertificateAuthorityPublicKeyIdentifier"); + } + + @Test + void theModelCheckRefusesAnImportWhoseCryptogramIsNotHexadecimal() { + Response answer = call("ImportKey", "{\"KeyMaterial\":{\"KeyCryptogram\":{" + + "\"Exportable\":true," + + "\"WrappedKeyCryptogram\":\"not hexadecimal at all\"," + + "\"ImportToken\":\"import-token-" + "0".repeat(24) + "\"," + + "\"KeyAttributes\":" + keyAttributes() + "}}}"); + + assertTheModelRefused(answer, "WrappedKeyCryptogram"); + } + + @Test + void theModelCheckRefusesACryptogramWithAWrappingSpecItDoesNotName() { + Response answer = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + keyArn() + "\"," + + "\"KeyMaterial\":{\"KeyCryptogram\":{" + + "\"CertificateAuthorityPublicKeyIdentifier\":\"" + keyArn() + "\"," + + "\"WrappingKeyCertificate\":\"a certificate\"," + + "\"WrappingSpec\":\"RSA_OAEP_SHA_1\"}}}"); + + assertTheModelRefused(answer, "WrappingSpec"); + } + + @Test + void theModelCheckRefusesAnAgreementWithADerivationFunctionItDoesNotName() { + Response answer = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + keyArn() + "\"," + + "\"KeyMaterial\":{\"DiffieHellmanTr31KeyBlock\":{" + + "\"PrivateKeyIdentifier\":\"" + keyArn() + "\"," + + "\"CertificateAuthorityPublicKeyIdentifier\":\"" + keyArn() + "\"," + + "\"PublicKeyCertificate\":\"a certificate\"," + + "\"DeriveKeyAlgorithm\":\"AES_128\"," + + "\"KeyDerivationFunction\":\"NIST_SP800_X\"," + + "\"KeyDerivationHashAlgorithm\":\"SHA_256\"," + + "\"DerivationData\":{\"SharedInformation\":\"00112233\"}}}}"); + + assertTheModelRefused(answer, "KeyDerivationFunction"); + } + + @Test + void theModelCheckRefusesAnAgreementWithADerivationHashItDoesNotName() { + Response answer = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + keyArn() + "\"," + + "\"KeyMaterial\":{\"DiffieHellmanTr31KeyBlock\":{" + + "\"PrivateKeyIdentifier\":\"" + keyArn() + "\"," + + "\"CertificateAuthorityPublicKeyIdentifier\":\"" + keyArn() + "\"," + + "\"PublicKeyCertificate\":\"a certificate\"," + + "\"DeriveKeyAlgorithm\":\"AES_128\"," + + "\"KeyDerivationFunction\":\"NIST_SP800\"," + + "\"KeyDerivationHashAlgorithm\":\"SHA_224\"," + + "\"DerivationData\":{\"SharedInformation\":\"00112233\"}}}}"); + + assertTheModelRefused(answer, "KeyDerivationHashAlgorithm"); + } + + /** The ARN of a key the request may name. */ + private static String keyArn() { + return call("CreateKey", CREATE_KEY).then().statusCode(200) + .extract().path("Key.KeyArn"); + } + + /** The key attributes of a symmetric key, with every member the model requires. */ + private static String keyAttributes() { + return "{\"KeyUsage\":\"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY\"," + + "\"KeyClass\":\"SYMMETRIC_KEY\",\"KeyAlgorithm\":\"AES_128\"," + + "\"KeyModesOfUse\":{\"Encrypt\":true,\"Decrypt\":true}}"; + } + + /** + * The refusal a caller sees when a request is missing a member the model requires: the + * shape check's, because the shape check runs before the operation does. + */ + private static void assertTheModelRefused(Response answer, String member) { + answer.then().statusCode(400) + .body("__type", equalTo("ValidationException")) + .body("message", containsString("failed to satisfy constraint")) + .body("message", containsString(member)); + } + @Test void aKeyThatAsksForACheckValueOfAnotherKindIsRefused() { // The kind follows the algorithm, so a request that names another is refused @@ -206,20 +482,68 @@ class PaymentCryptographyIntegrationTest { .body("__type", containsString("UnknownOperationException")); } + @Test + void anOperationTheServiceDoesNotServeIsRefusedWhateverItsBodySays() { + // The model names the operation and the service does not serve it, so it is refused + // as the unknown operation it is. The body it carries does not change that: a body + // that breaks the model's rules is not the answer to an operation that is not + // served at all. + call("RestoreKey", "{}") + .then().statusCode(400) + .body("__type", containsString("UnknownOperationException")); + call("RestoreKey", "{\"KeyIdentifier\":\"arn:aws:payment-cryptography:us-east-1:" + + "000000000000:key/abcdefghijklmnop\"}") + .then().statusCode(400) + .body("__type", containsString("UnknownOperationException")); + } + + @Test + void theCertificateOfAKeyIsServedOverTheWire() { + // The certificate of an asymmetric key, with the chain that goes with it. + String arn = call("CreateKey", CREATE_KEY_PAIR) + .then().statusCode(200) + .extract().path("Key.KeyArn"); + + call("GetPublicKeyCertificate", "{\"KeyIdentifier\":\"" + arn + "\"}") + .then().statusCode(200) + .body("KeyCertificate", notNullValue()) + .body("KeyCertificateChain", notNullValue()); + } + + @Test + void theCertificateOfAKeyIsNotServedForABareKeyId() { + // The identifier of a key is its ARN, an alias ARN or an alias name, and the model's + // pattern is what settles it, the same as for the other operations that take one. A + // bare id names no key, so it is refused the way GetKey refuses it. + String arn = call("CreateKey", CREATE_KEY_PAIR).then().statusCode(200) + .extract().path("Key.KeyArn"); + String id = arn.substring(arn.lastIndexOf('/') + 1); + + call("GetPublicKeyCertificate", "{\"KeyIdentifier\":\"" + id + "\"}") + .then().statusCode(400) + .body("__type", containsString("ValidationException")); + } + /** * A key is created with the usage and the modes of use the reference * requires, and a request without either of them is refused. */ @Test void aKeyWithoutItsUsageOrItsModesIsRefused() { - call("CreateKey", "{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\",\"KeyClass\":\"SYMMETRIC_KEY\"," - + "\"KeyModesOfUse\":{\"Encrypt\":true}},\"Exportable\":true}") - .then().statusCode(400) - .body("__type", containsString("ValidationException")); - call("CreateKey", "{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\",\"KeyClass\":\"SYMMETRIC_KEY\"," - + "\"KeyUsage\":\"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY\"},\"Exportable\":true}") - .then().statusCode(400) - .body("__type", containsString("ValidationException")); + // The shape check settles the members the attributes must carry, so it is the refusal + // that answers, and the message a caller sees is its own. + assertTheModelRefused(call("CreateKey", "{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\"," + + "\"KeyClass\":\"SYMMETRIC_KEY\",\"KeyModesOfUse\":{\"Encrypt\":true}}," + + "\"Exportable\":true}"), "KeyUsage"); + assertTheModelRefused(call("CreateKey", "{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\"," + + "\"KeyClass\":\"SYMMETRIC_KEY\"," + + "\"KeyUsage\":\"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY\"},\"Exportable\":true}"), + "KeyModesOfUse"); + } + + @Test + void aKeyWithoutItsAttributesIsRefused() { + assertTheModelRefused(call("CreateKey", "{\"Exportable\":true}"), "KeyAttributes"); } /** diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchangeTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchangeTest.java new file mode 100644 index 0000000000..30550e09f7 --- /dev/null +++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchangeTest.java @@ -0,0 +1,964 @@ +package io.floci.aws.services.paymentcryptography; + +import com.fasterxml.jackson.databind.ObjectMapper; +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.acm.CertificateGenerator; +import io.floci.aws.services.paymentcryptography.crypto.Certificates; +import io.floci.aws.services.paymentcryptography.crypto.CertificatesTest; +import io.floci.aws.services.paymentcryptography.crypto.RsaOaep; +import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey; +import io.floci.aws.testing.ManualClock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.security.KeyPair; +import java.security.SecureRandom; +import java.security.cert.X509Certificate; +import java.time.Duration; +import java.time.Instant; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +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 certificate-based half of the key exchange. + * + *

A key that leaves the service under a certificate is wrapped for the receiver, and the + * certificates the two sides exchange are the ones the service mints for the occasion. A key + * that comes back is checked against the authority that signed the certificate, and against + * the signature the sender made over it. + */ +class PaymentCryptographyKeyExchangeTest { + + private PaymentCryptographyService service; + + /** The key a key block is wrapped under. */ + private PaymentCryptographyKey protection; + + @BeforeEach + void setUp() { + service = new PaymentCryptographyService( + new InMemoryStorage<>(), + new InMemoryStorage<>(), + new RegionResolver("us-east-1", "000000000000")); + protection = service.createKey("us-east-1", + Map.of("KeyAlgorithm", "AES_256", + "KeyClass", "SYMMETRIC_KEY", + "KeyUsage", "TR31_K1_KEY_BLOCK_PROTECTION_KEY", + "KeyModesOfUse", Map.of("Wrap", true, "Unwrap", true)), + Map.of("Wrap", true, "Unwrap", true), true, true, Map.of()); + } + + + @Test + void theImportParametersCarryACertificateAndAToken() { + Map parameters = service.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048", false); + + assertNotNull(parameters.get("ImportToken")); + assertNotNull(parameters.get("WrappingKeyCertificate")); + assertNotNull(parameters.get("WrappingKeyCertificateChain")); + assertEquals("RSA_2048", parameters.get("WrappingKeyAlgorithm")); + assertNotNull(parameters.get("ParametersValidUntilTimestamp")); + assertNotNull(Certificates + .parseCertificate((String) parameters.get("WrappingKeyCertificate"))); + } + + @Test + void theExportParametersCarryACertificateAndAToken() { + Map parameters = service.parametersForExport("TR34_KEY_BLOCK", "RSA_2048", false); + + assertNotNull(parameters.get("ExportToken")); + assertNotNull(parameters.get("SigningKeyCertificate")); + assertNotNull(parameters.get("SigningKeyCertificateChain")); + assertEquals("RSA_2048", parameters.get("SigningKeyAlgorithm")); + assertNotNull(parameters.get("ParametersValidUntilTimestamp")); + assertNotNull(Certificates + .parseCertificate((String) parameters.get("SigningKeyCertificate"))); + } + + @Test + void eachTokenIsNamedForTheOperationThatIssuedIt() { + String importToken = (String) service.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048", false) + .get("ImportToken"); + String exportToken = (String) service.parametersForExport("TR34_KEY_BLOCK", "RSA_2048", false) + .get("ExportToken"); + + assertTrue(importToken.startsWith("import-token-"), importToken); + assertTrue(exportToken.startsWith("export-token-"), exportToken); + } + + @Test + void aMaterialTypeThatTakesNoParametersIsRefused() { + AwsException refused = assertThrows(AwsException.class, + () -> service.parametersForImport("TR31_KEY_BLOCK", "RSA_2048", false)); + AwsException refusedExport = assertThrows(AwsException.class, + () -> service.parametersForExport("KEY_CRYPTOGRAM", "RSA_2048", false)); + + assertEquals("ValidationException", refused.getErrorCode()); + assertEquals("ValidationException", refusedExport.getErrorCode()); + } + + @Test + void anAlgorithmThatIsNotAKeyAlgorithmIsRefused() { + AwsException refused = assertThrows(AwsException.class, + () -> service.parametersForImport("TR34_KEY_BLOCK", "AES_256", false)); + AwsException refusedExport = assertThrows(AwsException.class, + () -> service.parametersForExport("TR34_KEY_BLOCK", "AES_256", false)); + + assertEquals("ValidationException", refused.getErrorCode()); + assertEquals("ValidationException", refusedExport.getErrorCode()); + } + + + + + @Test + void theBlockCarriesTheHeadersTheRequestNames() { + // The optional blocks are in the clear and are authenticated with the cipher text, and + // the exportability and the version sit in the header. + Map material = new LinkedHashMap<>(); + material.put("WrappingKeyIdentifier", protection.getKeyId()); + material.put("KeyBlockHeaders", Map.of( + "KeyExportability", "NON_EXPORTABLE", + "KeyVersion", "01", + "OptionalBlocks", Map.of("AB", "0011"))); + + Map answer = service.exportKey("us-east-1", + createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY").getKeyId(), + "Tr31KeyBlock", material, "", ""); + Map wrapped = (Map) answer.get("WrappedKey"); + String block = (String) wrapped.get("KeyMaterial"); + + // The header carries the version and the exportability the request asked for. + assertEquals("01", block.substring(9, 11), "the version of the key"); + assertEquals("N", block.substring(11, 12), "the exportability of the key"); + // The optional block sits between the header and the cipher text, and its length is + // in hexadecimal and covers the whole block, the identifier and the length included. + assertEquals("AB", block.substring(16, 18), "the optional block's identifier"); + assertEquals("08", block.substring(18, 20), "the optional block's length"); + // The optional blocks take up a whole number of cipher blocks, so the block carries a + // padding block that fills the rest. + assertEquals("02", block.substring(12, 14), "the number of optional blocks"); + assertEquals("PB080000", block.substring(24, 32), "the padding block"); + + // And the block still opens, so the optional blocks are authenticated with it. + PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr31KeyBlock", + Map.of("WrappingKeyIdentifier", protection.getKeyId(), + "WrappedKeyBlock", block), "", true, Map.of()); + assertEquals("TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", imported.getKeyUsage()); + } + + /** + * A key that leaves under a cryptogram comes back. + * + *

The import decrypts what the caller brought under the private key the parameters + * issued, and that operation is blinded, so a wrong set of CRT values would decrypt to + * nothing and the key would not come back. + */ + @Test + void aKeyThatLeavesUnderACryptogramComesBack() { Map importParameters = service.parametersForImport("KEY_CRYPTOGRAM", + "RSA_2048", false); + + PaymentCryptographyKey key = createKey("TDES_2KEY", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"); + PaymentCryptographyKey authority = createAuthority( + (String) importParameters.get("WrappingKeyCertificate")); + + Map material = new LinkedHashMap<>(); + material.put("WrappingKeyCertificate", importParameters.get("WrappingKeyCertificate")); + material.put("CertificateAuthorityPublicKeyIdentifier", authority.getKeyId()); + material.put("WrappingSpec", "RSA_OAEP_SHA_256"); + + Map answer = service.exportKey("us-east-1", key.getKeyId(), "KeyCryptogram", + material, "", ""); + Map wrapped = (Map) answer.get("WrappedKey"); + assertEquals("KEY_CRYPTOGRAM", wrapped.get("WrappedKeyMaterialFormat")); + + Map incoming = new LinkedHashMap<>(); + incoming.put("ImportToken", importParameters.get("ImportToken")); + incoming.put("WrappedKeyCryptogram", wrapped.get("KeyMaterial")); + incoming.put("WrappingKeyIdentifier", authority.getKeyId()); + incoming.put("WrappingSpec", "RSA_OAEP_SHA_256"); + incoming.put("KeyAttributes", Map.of( + "KeyAlgorithm", "TDES_2KEY", + "KeyClass", "SYMMETRIC_KEY", + "KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", + "KeyModesOfUse", Map.of("Encrypt", true, "Decrypt", true))); + + PaymentCryptographyKey imported = service.importKey("us-east-1", "KeyCryptogram", incoming, "", true, Map.of()); + + assertEquals(key.getKeyMaterialHex(), imported.getKeyMaterialHex()); + } + + + + @Test + void aKeyLeavesUnderAKeyTheTwoPartiesAgreed() { + // The two parties agree a key with ECDH, and the key leaves in a block under it. + SecureRandom random = new SecureRandom(); + KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random); + KeyPair counterparty = PaymentCryptographyKeyPairs.ec( + PaymentCryptographyKeyAlgorithm.ECC_NIST_P256, random); + Certificates.Minted authorityCertificate = CertificatesTest.mint(authority.getPublic(), + "floci key-exchange CA", authority.getPrivate(), "floci key-exchange CA"); + // The counterparty's certificate is signed by the authority, which is what lets the + // service trust it. + Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(), + "floci counterparty", authority.getPrivate(), "floci key-exchange CA"); + Exchange exchange = agreedExchange(authorityCertificate, counterpartyCertificate); + + Map wrapped = (Map) service.exportKey("us-east-1", exchange.key().getKeyId(), + "DiffieHellmanTr31KeyBlock", exchange.material(), "", "").get("WrappedKey"); + + assertEquals("TR31_KEY_BLOCK", wrapped.get("WrappedKeyMaterialFormat")); + + // The two parties agree the key again, so the block opens under it. + Map incoming = new LinkedHashMap<>(exchange.material()); + incoming.put("WrappedKeyBlock", wrapped.get("KeyMaterial")); + PaymentCryptographyKey imported = service.importKey("us-east-1", + "DiffieHellmanTr31KeyBlock", incoming, "", true, Map.of()); + + assertEquals(exchange.key().getKeyMaterialHex(), imported.getKeyMaterialHex()); + assertEquals(exchange.key().getKeyUsage(), imported.getKeyUsage()); + } + + @Test + void aKeyLeavesUnderAKeyTheTwoPartiesAgreedCarriesTheHeadersTheRequestNames() { + // The block headers the request names travel with the block under the agreed key, + // the same as they do under a key the service holds. + SecureRandom random = new SecureRandom(); + KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random); + KeyPair counterparty = PaymentCryptographyKeyPairs.ec( + PaymentCryptographyKeyAlgorithm.ECC_NIST_P256, random); + Certificates.Minted authorityCertificate = CertificatesTest.mint(authority.getPublic(), + "floci key-exchange CA", authority.getPrivate(), "floci key-exchange CA"); + Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(), + "floci counterparty", authority.getPrivate(), "floci key-exchange CA"); + Exchange exchange = agreedExchange(authorityCertificate, counterpartyCertificate); + Map material = new LinkedHashMap<>(exchange.material()); + material.put("KeyBlockHeaders", Map.of( + "KeyExportability", "NON_EXPORTABLE", + "KeyVersion", "01", + "OptionalBlocks", Map.of("AB", "0011"))); + + Map wrapped = (Map) service.exportKey("us-east-1", exchange.key().getKeyId(), + "DiffieHellmanTr31KeyBlock", material, "", "").get("WrappedKey"); + String block = (String) wrapped.get("KeyMaterial"); + + // The header carries the version and the exportability the request asked for, and + // the optional block sits between the header and the cipher text. + assertEquals("01", block.substring(9, 11), "the version of the key"); + assertEquals("N", block.substring(11, 12), "the exportability of the key"); + assertEquals("AB", block.substring(16, 18), "the optional block's identifier"); + assertEquals("08", block.substring(18, 20), "the optional block's length"); + } + + @Test + void aCounterpartyCertificateTheAuthorityDidNotSignIsRefused() { + SecureRandom random = new SecureRandom(); + KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random); + KeyPair other = PaymentCryptographyKeyPairs.rsa(2048, random); + KeyPair counterparty = PaymentCryptographyKeyPairs.ec( + PaymentCryptographyKeyAlgorithm.ECC_NIST_P256, random); + Certificates.Minted authorityCertificate = CertificatesTest.mint(authority.getPublic(), + "floci key-exchange CA", authority.getPrivate(), "floci key-exchange CA"); + // Signed by somebody else, so the authority cannot vouch for it. + Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(), + "floci counterparty", other.getPrivate(), "floci somebody else"); + Exchange exchange = agreedExchange(authorityCertificate, counterpartyCertificate); + + AwsException refused = assertThrows(AwsException.class, + () -> service.exportKey("us-east-1", exchange.key().getKeyId(), + "DiffieHellmanTr31KeyBlock", exchange.material(), "", "")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("not signed by the certificate authority"), + refused.getMessage()); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void anInitialKeyLeavesInsteadOfTheBaseKey(boolean baseMayLeave) { + // The initial key of the DUKPT derivation is derived from the base + // derivation key, and it is the derived key that leaves. The base key may not + // leave itself and still derive that initial key, which the export guide says + // the standards allow. + Map attributes = new LinkedHashMap<>(); + attributes.put("KeyAlgorithm", "TDES_2KEY"); + attributes.put("KeyClass", "SYMMETRIC_KEY"); + attributes.put("KeyUsage", "TR31_B0_BASE_DERIVATION_KEY"); + PaymentCryptographyKey base = service.createKey("us-east-1", attributes, + Map.of("DeriveKey", Boolean.TRUE), baseMayLeave, true, Map.of()); + + Map answer = service.exportKey("us-east-1", base.getKeyId(), "Tr31KeyBlock", + Map.of("WrappingKeyIdentifier", protection.getKeyId()), "12345678900000000001", ""); + + Map wrapped = (Map) answer.get("WrappedKey"); + String block = (String) wrapped.get("KeyMaterial"); + // The header names the derived key: an initial derivation key of Triple DES, which + // the receiver may derive with and may export, but not as a plain working key. + assertEquals("B1", block.substring(5, 7), "the usage of the derived key"); + assertEquals("T", block.substring(7, 8), "the algorithm of the derived key"); + assertEquals("X", block.substring(8, 9), "the derived key is a derivable one"); + assertEquals("S", block.substring(11, 12), "the derived key is a sensitive one"); + // And the check value is the derived key's, not the base key's. + assertNotEquals(base.getKeyCheckValue(), wrapped.get("KeyCheckValue")); + } + + @Test + void anInitialKeyCannotBeDerivedFromAnotherKey() { + Map attributes = new LinkedHashMap<>(); + attributes.put("KeyAlgorithm", "TDES_2KEY"); + attributes.put("KeyClass", "SYMMETRIC_KEY"); + attributes.put("KeyUsage", "TR31_P0_PIN_ENCRYPTION_KEY"); + PaymentCryptographyKey key = service.createKey("us-east-1", attributes, + Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE), true, true, Map.of()); + + AwsException refused = assertThrows(AwsException.class, + () -> service.exportKey("us-east-1", key.getKeyId(), "Tr31KeyBlock", + Map.of("WrappingKeyIdentifier", protection.getKeyId()), + "12345678900000000001", "")); + + assertEquals("ValidationException", refused.getErrorCode()); + } + + + @Test + void anImportTokenWorksForEveryImportUntilItExpires() { + // A caller that asks for the parameters once may import several keys under them. + Map parameters = service.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048", false); + String token = (String) parameters.get("ImportToken"); + // The cryptogram is built under the wrapping key the parameters carry, so it opens. + X509Certificate certificate = + Certificates.parseCertificate((String) parameters.get("WrappingKeyCertificate")); + String cryptogram = HexFormat.of().withUpperCase().formatHex(RsaOaep.encrypt( + certificate.getPublicKey(), + HexFormat.of().parseHex("00112233445566778899AABBCCDDEEFF"), "SHA-256")); + + for (int i = 0; i < 2; i++) { + PaymentCryptographyKey imported = service.importKey("us-east-1", "KeyCryptogram", + Map.of("ImportToken", token, + "WrappedKeyCryptogram", cryptogram, + "KeyAttributes", Map.of("KeyAlgorithm", "AES_128", + "KeyClass", "SYMMETRIC_KEY", + "KeyUsage", "TR31_K1_KEY_BLOCK_PROTECTION_KEY", + "KeyModesOfUse", Map.of("Wrap", true, "Unwrap", true))), "", true, Map.of()); + assertNotNull(imported, "the second import was refused"); + } + } + + + + @Test + void theExpiredTokensAreSwept() { + // A token that was issued and never quoted again would otherwise stay for the life + // of the process, and it holds a private key. The clock moves past the token's life, + // so the token is expired and the next issue sweeps it. + ManualClock clock = new ManualClock(Instant.parse("2026-01-01T00:00:00Z")); + PaymentCryptographyService timed = new PaymentCryptographyService( + new InMemoryStorage<>(), + new InMemoryStorage<>(), + new RegionResolver("us-east-1", "000000000000"), + new SecureRandom(), + new PaymentCryptographyRequestContext(), + new CertificateGenerator(), + clock); + timed.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048", false); + clock.advance(Duration.ofDays(31)); + timed.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048", false); + + assertEquals(1, timed.issuedTokenCount(), + "the token that expired was not swept"); + } + + @Test + void thePrivateKeyIsNotWrittenToTheStore() throws Exception { + // The store is a file in the working directory, and a private key in clear in it is + // a secret on disk. + PaymentCryptographyKey pair = createKeyPair("RSA_2048"); + + String written = new ObjectMapper().writeValueAsString(pair); + + assertFalse(written.contains(pair.getKeyPrivateKeyBase64()), + "the private key was written to the store"); + assertFalse(written.contains("keyPrivateKeyBase64"), + "the private key was written to the store"); + } + + @Test + void aFormTheServiceDoesNotKnowIsRefused() { + PaymentCryptographyKey key = createKey("AES_256", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"); + + AwsException refused = assertThrows(AwsException.class, + () -> service.exportKey("us-east-1", key.getKeyId(), "Nonsense", Map.of(), "", "")); + assertEquals("ValidationException", refused.getErrorCode()); + } + + /** A symmetric key of the given algorithm and usage. */ + private PaymentCryptographyKey createKey(String algorithm, String usage) { + Map attributes = new LinkedHashMap<>(); + attributes.put("KeyAlgorithm", algorithm); + attributes.put("KeyClass", "SYMMETRIC_KEY"); + attributes.put("KeyUsage", usage); + return service.createKey("us-east-1", attributes, + Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE), true, true, Map.of()); + } + + /** A key pair of the given algorithm. */ + private PaymentCryptographyKey createKeyPair(String algorithm) { + return createKeyPair(algorithm, "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE"); + } + + /** A key pair of the given algorithm, for the given usage. */ + private PaymentCryptographyKey createKeyPair(String algorithm, String usage) { + Map attributes = new LinkedHashMap<>(); + attributes.put("KeyAlgorithm", algorithm); + attributes.put("KeyClass", "ASYMMETRIC_KEY_PAIR"); + attributes.put("KeyUsage", usage); + // The modes are the ones the purpose allows: a key agreement key derives, a signing + // key signs and verifies. + Map modes = "TR31_K3_ASYMMETRIC_KEY_FOR_KEY_AGREEMENT".equals(usage) + ? Map.of("DeriveKey", true) + : Map.of("Sign", true, "Verify", true); + return service.createKey("us-east-1", attributes, modes, true, true, Map.of()); + } + + /** + * The authority of the exchange: the public half of the certificate the receiver brings. + * + *

A certificate that the service minted for the import is signed by the key it names, + * so the key that holds its public half is the authority that can vouch for it. + */ + private PaymentCryptographyKey createAuthority(String certificate) { + return createAuthority(certificate, true); + } + + /** An authority that vouches for a certificate, enabled or not. */ + private PaymentCryptographyKey createAuthority(String certificate, boolean enabled) { + return service.importKey("us-east-1", "TrustedCertificatePublicKey", Map.of( + "PublicKeyCertificate", certificate, + "KeyAttributes", authorityAttributes()), "", enabled, Map.of()); + } + + /** The attributes an authority carries: a public key that may verify. */ + private static Map authorityAttributes() { + return Map.of( + "KeyAlgorithm", "RSA_2048", + "KeyClass", "PUBLIC_KEY", + "KeyUsage", "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE", + "KeyModesOfUse", Map.of("Verify", Boolean.TRUE)); + } + + /** + * A key exchange under a key the two parties agreed with ECDH. + * + *

The service trusts the certificate the counterparty brings because the authority + * signed it, so the helper imports the authority, makes the agreement key and builds the + * material of the export. + * + * @param authorityCertificate the certificate of the authority that vouches for the + * counterparty + * @param counterpartyCertificate the certificate the counterparty brings + * @return the material of the export, and the key that leaves under it + */ + private Exchange agreedExchange(Certificates.Minted authorityCertificate, + Certificates.Minted counterpartyCertificate) { + PaymentCryptographyKey authority = createAuthority(authorityCertificate.pem()); + PaymentCryptographyKey agreement = createKeyPair("ECC_NIST_P256", + "TR31_K3_ASYMMETRIC_KEY_FOR_KEY_AGREEMENT"); + Map material = new LinkedHashMap<>(); + material.put("PrivateKeyIdentifier", agreement.getKeyId()); + material.put("CertificateAuthorityPublicKeyIdentifier", authority.getKeyId()); + material.put("PublicKeyCertificate", counterpartyCertificate.pem()); + material.put("DeriveKeyAlgorithm", "AES_128"); + material.put("KeyDerivationFunction", "ANSI_X963"); + material.put("KeyDerivationHashAlgorithm", "SHA_256"); + material.put("DerivationData", Map.of( + "SharedInformation", "00112233445566778899AABBCCDDEEFF")); + return new Exchange(material, + createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY")); + } + + /** The material of a key exchange, and the key that leaves under it. */ + private record Exchange(Map material, PaymentCryptographyKey key) { + } + + + @Test + void anAuthorityThatMayNotVerifyIsRefused() { + // The authority vouches for the other party's certificate, so it has to be allowed to + // verify. + SecureRandom random = new SecureRandom(); + KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random); + // The cryptogram is wrapped under the receiver's certificate, and a certificate over + // a 3072-bit modulus is as strong as the key it wraps. + KeyPair counterparty = PaymentCryptographyKeyPairs.rsa(3072, random); + Instant now = Instant.now(); + Certificates.Minted caCertificate = CertificatesTest.mint(authority.getPublic(), "floci CA", authority.getPrivate(), "floci CA"); + Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(), "floci counterparty", authority.getPrivate(), "floci CA"); + Map attributes = new LinkedHashMap<>(); + attributes.put("KeyAlgorithm", "RSA_2048"); + attributes.put("KeyClass", "PUBLIC_KEY"); + attributes.put("KeyUsage", "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE"); + attributes.put("KeyModesOfUse", Map.of("Encrypt", Boolean.TRUE)); + PaymentCryptographyKey ca = service.importKey("us-east-1", "TrustedCertificatePublicKey", + Map.of("PublicKeyCertificate", caCertificate.pem(), "KeyAttributes", attributes), + "", true, Map.of()); + + AwsException refused = assertThrows(AwsException.class, + () -> service.exportKey("us-east-1", createKey("AES_128", + "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY").getKeyId(), "KeyCryptogram", + Map.of("WrappingKeyCertificate", counterpartyCertificate.pem(), + "CertificateAuthorityPublicKeyIdentifier", ca.getKeyId()), "", "")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("Verify"), refused.getMessage()); + } + + @Test + void anExpiredCertificateIsRefused() { + SecureRandom random = new SecureRandom(); + KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random); + // The cryptogram is wrapped under the receiver's certificate, and a certificate over + // a 3072-bit modulus is as strong as the key it wraps. + KeyPair counterparty = PaymentCryptographyKeyPairs.rsa(3072, random); + Instant now = Instant.now(); + Certificates.Minted caCertificate = CertificatesTest.mint(authority.getPublic(), "floci CA", authority.getPrivate(), "floci CA"); + // The counterparty's certificate has expired, so it protects nothing. + Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(), + "floci counterparty", authority.getPrivate(), "floci CA", + now.minusSeconds(7200), now.minusSeconds(3600)); + PaymentCryptographyKey ca = createAuthority(caCertificate.pem()); + + AwsException refused = assertThrows(AwsException.class, + () -> service.exportKey("us-east-1", createKey("AES_128", + "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY").getKeyId(), "KeyCryptogram", + Map.of("WrappingKeyCertificate", counterpartyCertificate.pem(), + "CertificateAuthorityPublicKeyIdentifier", ca.getKeyId()), "", "")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("validity window"), refused.getMessage()); + } + + @Test + void aCertificateThatDoesNotParseIsRefused() { + // The text is not a certificate, so it is refused rather than stored as one. + AwsException refused = assertThrows(AwsException.class, + () -> createAuthority("not a certificate at all")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("not a certificate"), refused.getMessage()); + } + + @Test + void aDisabledKeyDoesNotLeave() { + // A disabled key does no work, so it may not be exported. + PaymentCryptographyKey key = service.createKey("us-east-1", + Map.of("KeyAlgorithm", "AES_128", "KeyClass", "SYMMETRIC_KEY", + "KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", + "KeyModesOfUse", Map.of("Encrypt", true, "Decrypt", true)), + Map.of("Encrypt", true, "Decrypt", true), true, false, Map.of()); + + AwsException refused = assertThrows(AwsException.class, + () -> service.exportKey("us-east-1", key.getKeyId(), "Tr31KeyBlock", + Map.of("WrappingKeyIdentifier", protection.getKeyId()), "", "")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("disabled"), refused.getMessage()); + } + + @Test + void anImportedKeyGetsEveryModeTheBlockStandsFor() { + // The mode of use character of the block says what the key may be used for, and + // both spellings of a direction stand for it. A block that says B gives the key all + // four of Encrypt, Decrypt, Wrap and Unwrap, whichever use the key has. + PaymentCryptographyKey key = createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"); + String block = blockOf(key); + assertEquals("B", block.substring(8, 9), "the mode of use of the block"); + + PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr31KeyBlock", + Map.of("WrappingKeyIdentifier", protection.getKeyId(), "WrappedKeyBlock", block), + "", true, Map.of()); + + Map modes = imported.getKeyModesOfUse(); + assertEquals(Boolean.TRUE, modes.get("Encrypt"), "the imported key may encrypt"); + assertEquals(Boolean.TRUE, modes.get("Decrypt"), "the imported key may decrypt"); + assertEquals(Boolean.TRUE, modes.get("Wrap"), "the imported key may wrap"); + assertEquals(Boolean.TRUE, modes.get("Unwrap"), "the imported key may unwrap"); + } + + @Test + void anExportMayNotGiveAKeyAPermissionItDoesNotHave() { + // A key that may only encrypt is refused an export that says it may decrypt: the + // modes of use a request names may only narrow the ones the key has. + PaymentCryptographyKey key = service.createKey("us-east-1", + Map.of("KeyAlgorithm", "AES_128", "KeyClass", "SYMMETRIC_KEY", + "KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", + "KeyModesOfUse", Map.of("Encrypt", true)), + Map.of("Encrypt", true), true, true, Map.of()); + + AwsException refused = assertThrows(AwsException.class, + () -> service.exportKey("us-east-1", key.getKeyId(), "Tr31KeyBlock", + Map.of("WrappingKeyIdentifier", protection.getKeyId(), + "KeyBlockHeaders", Map.of("KeyModesOfUse", + Map.of("Encrypt", true, "Decrypt", true))), + "", "")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("Decrypt"), refused.getMessage()); + } + + @Test + void anExportMayNotLoosenTheExportability() { + // The exportability says what the receiver may do with the key once it has it, and + // the model states SENSITIVE as the loosest of the three: it lets the receiver + // export under a key block, a TR-34 block or a cryptogram, where EXPORTABLE lets it + // export under a key block or a TR-34 block only. So an exportable key may not + // leave as SENSITIVE, because that is looser than what the key has. + PaymentCryptographyKey key = createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"); + + AwsException refused = assertThrows(AwsException.class, + () -> service.exportKey("us-east-1", key.getKeyId(), "Tr31KeyBlock", + Map.of("WrappingKeyIdentifier", protection.getKeyId(), + "KeyBlockHeaders", Map.of("KeyExportability", "SENSITIVE")), + "", "")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("looser"), refused.getMessage()); + } + + @Test + void anExportMayTightenTheExportability() { + // The other way round: the initial key of the DUKPT derivation is sensitive, and + // EXPORTABLE is stricter than that, so it may leave as one. + Map attributes = new LinkedHashMap<>(); + attributes.put("KeyAlgorithm", "TDES_2KEY"); + attributes.put("KeyClass", "SYMMETRIC_KEY"); + attributes.put("KeyUsage", "TR31_B0_BASE_DERIVATION_KEY"); + PaymentCryptographyKey base = service.createKey("us-east-1", attributes, + Map.of("DeriveKey", Boolean.TRUE), true, true, Map.of()); + + Map answer = service.exportKey("us-east-1", base.getKeyId(), "Tr31KeyBlock", + Map.of("WrappingKeyIdentifier", protection.getKeyId(), + "KeyBlockHeaders", Map.of("KeyExportability", "EXPORTABLE")), + "12345678900000000001", ""); + String block = (String) ((Map) answer.get("WrappedKey")).get("KeyMaterial"); + + assertEquals("E", block.substring(11, 12), "the exportability of the derived key"); + } + + @Test + void aDisabledAuthorityDoesNotVouchForACertificate() { + // The authority does work when it vouches for a certificate, and a disabled key does + // no work, so a disabled authority is refused. + SecureRandom random = new SecureRandom(); + KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random); + KeyPair counterparty = PaymentCryptographyKeyPairs.rsa(2048, random); + Certificates.Minted caCertificate = CertificatesTest.mint(authority.getPublic(), "floci CA", + authority.getPrivate(), "floci CA"); + Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(), + "floci counterparty", authority.getPrivate(), "floci CA"); + PaymentCryptographyKey ca = createAuthority(caCertificate.pem(), false); + + AwsException refused = assertThrows(AwsException.class, + () -> service.importKey("us-east-1", "TrustedCertificatePublicKey", + Map.of("PublicKeyCertificate", counterpartyCertificate.pem(), + "CertificateAuthorityPublicKeyIdentifier", ca.getKeyId(), + "KeyAttributes", authorityAttributes()), + "", true, Map.of())); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("disabled"), refused.getMessage()); + } + + @Test + void anImportedKeySaysItCameFromOutsideTheService() { + // A key that came in says its origin is EXTERNAL, and a key the service made says + // it is AWS_PAYMENT_CRYPTOGRAPHY. + PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr31KeyBlock", + Map.of("WrappingKeyIdentifier", protection.getKeyId(), + "WrappedKeyBlock", blockOf(createKey("AES_128", + "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"))), + "", true, Map.of()); + + assertEquals("EXTERNAL", imported.getKeyOrigin(), "the origin of an imported key"); + assertEquals("AWS_PAYMENT_CRYPTOGRAPHY", protection.getKeyOrigin(), + "the origin of a key the service made"); + } + + @Test + void aCryptogramCarriesNoCheckValue() { + // A key block carries the check value of the key it carries, and a cryptogram + // carries no key block at all, so it carries no check value either. + SecureRandom random = new SecureRandom(); + KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random); + KeyPair counterparty = PaymentCryptographyKeyPairs.rsa(3072, random); + Certificates.Minted caCertificate = CertificatesTest.mint(authority.getPublic(), "floci CA", + authority.getPrivate(), "floci CA"); + Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(), + "floci counterparty", authority.getPrivate(), "floci CA"); + PaymentCryptographyKey ca = createAuthority(caCertificate.pem()); + + Map answer = service.exportKey("us-east-1", + createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY").getKeyId(), + "KeyCryptogram", + Map.of("WrappingKeyCertificate", counterpartyCertificate.pem(), + "CertificateAuthorityPublicKeyIdentifier", ca.getKeyId()), "", ""); + + Map wrapped = (Map) answer.get("WrappedKey"); + assertEquals("KEY_CRYPTOGRAM", wrapped.get("WrappedKeyMaterialFormat")); + assertFalse(wrapped.containsKey("KeyCheckValue"), "the cryptogram carries a check value"); + assertFalse(wrapped.containsKey("KeyCheckValueAlgorithm"), + "the cryptogram carries a check value algorithm"); + } + + /** The key block a key leaves under the protection key of the test. */ + private String blockOf(PaymentCryptographyKey key) { + Map answer = service.exportKey("us-east-1", key.getKeyId(), "Tr31KeyBlock", + Map.of("WrappingKeyIdentifier", protection.getKeyId()), "", ""); + return (String) ((Map) answer.get("WrappedKey")).get("KeyMaterial"); + } + + @Test + void aDataEncryptionKeyMayNotWrapAnExport() { + // The wrapping key of a key block is a key encryption key, and a data encryption key + // is not one. + PaymentCryptographyKey data = service.createKey("us-east-1", + Map.of("KeyAlgorithm", "AES_256", "KeyClass", "SYMMETRIC_KEY", + "KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", + "KeyModesOfUse", Map.of("Encrypt", true, "Decrypt", true)), + Map.of("Encrypt", true, "Decrypt", true), true, true, Map.of()); + PaymentCryptographyKey key = createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"); + + AwsException refused = assertThrows(AwsException.class, + () -> service.exportKey("us-east-1", key.getKeyId(), "Tr31KeyBlock", + Map.of("WrappingKeyIdentifier", data.getKeyId()), "", "")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("not a key encryption key"), refused.getMessage()); + } + + @Test + void anImportedKeyThatMayNotLeaveStaysThatWay() { + // The exportability is a member of the form, beside the attributes and not inside + // them. + Map importParameters = service.parametersForImport("KEY_CRYPTOGRAM", + "RSA_2048", false); + PaymentCryptographyKey key = createKey("TDES_2KEY", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"); + PaymentCryptographyKey authority = createAuthority( + (String) importParameters.get("WrappingKeyCertificate")); + Map material = new LinkedHashMap<>(); + material.put("WrappingKeyCertificate", importParameters.get("WrappingKeyCertificate")); + material.put("CertificateAuthorityPublicKeyIdentifier", authority.getKeyId()); + material.put("WrappingSpec", "RSA_OAEP_SHA_256"); + Map answer = service.exportKey("us-east-1", key.getKeyId(), "KeyCryptogram", + material, "", ""); + Map wrapped = (Map) answer.get("WrappedKey"); + + Map incoming = new LinkedHashMap<>(); + incoming.put("ImportToken", importParameters.get("ImportToken")); + incoming.put("WrappedKeyCryptogram", wrapped.get("KeyMaterial")); + incoming.put("WrappingKeyIdentifier", authority.getKeyId()); + incoming.put("WrappingSpec", "RSA_OAEP_SHA_256"); + incoming.put("Exportable", Boolean.FALSE); + incoming.put("KeyAttributes", Map.of( + "KeyAlgorithm", "TDES_2KEY", + "KeyClass", "SYMMETRIC_KEY", + "KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", + "KeyModesOfUse", Map.of("Encrypt", true, "Decrypt", true))); + + PaymentCryptographyKey imported = service.importKey("us-east-1", "KeyCryptogram", incoming, + "", true, Map.of()); + + assertFalse(imported.isExportable(), "the key was imported as one that may leave"); + } + + @Test + void aKeyOfAnotherPurposeMayNotAgree() { + // The key that agrees has to be a key agreement key. + PaymentCryptographyKey signing = createKeyPair("ECC_NIST_P256"); + PaymentCryptographyKey key = createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"); + + AwsException refused = assertThrows(AwsException.class, + () -> service.exportKey("us-east-1", key.getKeyId(), "DiffieHellmanTr31KeyBlock", + Map.of("PrivateKeyIdentifier", signing.getKeyId(), + "CertificateAuthorityPublicKeyIdentifier", signing.getKeyId(), + "PublicKeyCertificate", "not a certificate", + "DeriveKeyAlgorithm", "AES_128", + "KeyDerivationFunction", "ANSI_X963", + "KeyDerivationHashAlgorithm", "SHA_256", + "DerivationData", Map.of( + "SharedInformation", "00112233445566778899AABBCCDDEEFF")), + "", "")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("key agreement"), refused.getMessage()); + } + + @Test + void aKeyThatIsNotACurveKeyIsRefused() { + // An RSA key cannot take part in an agreement, and it is refused rather than read as + // a curve key. + PaymentCryptographyKey rsa = createKeyPair("RSA_2048"); + PaymentCryptographyKey key = createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"); + + AwsException refused = assertThrows(AwsException.class, + () -> service.exportKey("us-east-1", key.getKeyId(), "DiffieHellmanTr31KeyBlock", + Map.of("PrivateKeyIdentifier", rsa.getKeyId(), + "CertificateAuthorityPublicKeyIdentifier", rsa.getKeyId(), + "PublicKeyCertificate", "not a certificate", + "DeriveKeyAlgorithm", "AES_128", + "KeyDerivationFunction", "ANSI_X963", + "KeyDerivationHashAlgorithm", "SHA_256", + "DerivationData", Map.of( + "SharedInformation", "00112233445566778899AABBCCDDEEFF")), + "", "")); + + assertEquals("ValidationException", refused.getErrorCode()); + } + + @Test + void anExportWithAnotherCheckValueAlgorithmIsRefused() { + PaymentCryptographyKey key = createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"); + + AwsException refused = assertThrows(AwsException.class, + () -> service.exportKey("us-east-1", key.getKeyId(), "Tr31KeyBlock", + Map.of("WrappingKeyIdentifier", protection.getKeyId()), "", "ANSI_X9_24")); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("check value algorithm"), refused.getMessage()); + } + + @Test + void anImportWithAnotherCheckValueAlgorithmIsRefused() { + PaymentCryptographyKey key = createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"); + Map answer = service.exportKey("us-east-1", key.getKeyId(), "Tr31KeyBlock", + Map.of("WrappingKeyIdentifier", protection.getKeyId()), "", ""); + Map wrapped = (Map) answer.get("WrappedKey"); + String block = (String) wrapped.get("KeyMaterial"); + + AwsException refused = assertThrows(AwsException.class, + () -> service.importKey("us-east-1", "Tr31KeyBlock", + Map.of("WrappingKeyIdentifier", protection.getKeyId(), + "WrappedKeyBlock", block), + "ANSI_X9_24", true, Map.of())); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("check value algorithm"), refused.getMessage()); + } + + @Test + void theParametersCanBeReused() { + // A caller that asks for the last parameters gets them, token and certificate alike. + Map first = service.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048", false); + Map again = service.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048", true); + Map fresh = service.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048", false); + + assertEquals(first.get("ImportToken"), again.get("ImportToken")); + assertEquals(first.get("WrappingKeyCertificate"), again.get("WrappingKeyCertificate")); + assertNotEquals(first.get("ImportToken"), fresh.get("ImportToken")); + } + + @Test + void theExportParametersOutliveTheirCertificate() { + // The parameters are good until the certificate they carry is not. + Map parameters = service.parametersForExport("TR34_KEY_BLOCK", "RSA_2048", + false); + String certificate = (String) parameters.get("SigningKeyCertificate"); + long validUntil = ((Number) parameters.get("ParametersValidUntilTimestamp")).longValue(); + X509Certificate parsed = Certificates.parseCertificate(certificate); + + assertTrue(parsed.getNotAfter().toInstant().getEpochSecond() >= validUntil, + "the certificate expires before the parameters do"); + } + + @Test + void aSensitiveKeyMayLeaveTheServiceAgain() { + // The exportability of a block says whether the key that comes in may leave again. + // A sensitive one may: it is only under a trusted key that it may not be worked with. + // + // The block is made here rather than exported, because the service writes the + // exportability of the block it makes itself: a key it exports is exportable, and + // the only key it exports as sensitive is the initial DUKPT key, whose usage the + // model has no name for. A counterparty's block may carry the sensitive one all the + // same. + String block = PaymentCryptographyTr31.wrap( + PaymentCryptographyKeyRules.material( + createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY")), + PaymentCryptographyKeyRules.material(protection), + true, "A", "D0", "B", "S"); + + PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr31KeyBlock", + Map.of("WrappingKeyIdentifier", protection.getKeyId(), "WrappedKeyBlock", block), + "", true, Map.of()); + + assertTrue(imported.isExportable(), "the sensitive key may not leave the service again"); + } + + @Test + void aKeyThatIsNotExportableDoesNotComeBackExportable() { + // The exportability of a block says whether the key that comes in may leave again. + Map material = new LinkedHashMap<>(); + material.put("WrappingKeyIdentifier", protection.getKeyId()); + material.put("KeyBlockHeaders", Map.of("KeyExportability", "NON_EXPORTABLE")); + + PaymentCryptographyKey key = createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"); + Map wrapped = (Map) service.exportKey("us-east-1", key.getKeyId(), + "Tr31KeyBlock", material, "", "").get("WrappedKey"); + String block = (String) wrapped.get("KeyMaterial"); + + PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr31KeyBlock", + Map.of("WrappingKeyIdentifier", protection.getKeyId(), "WrappedKeyBlock", block), + "", true, Map.of()); + + assertFalse(imported.isExportable(), "the key that may not leave came back exportable"); + } + + @Test + void theModesOfUseTheRequestNamesAreReadTheWayTheKeyHasThem() { + // A key encryption key wraps and unwraps rather than encrypting and decrypting, so + // the modes the request names for one are read that way too. + Map material = new LinkedHashMap<>(); + material.put("WrappingKeyIdentifier", protection.getKeyId()); + material.put("KeyBlockHeaders", Map.of( + "KeyModesOfUse", Map.of("Wrap", true, "Unwrap", true))); + + PaymentCryptographyKey key = createKey("AES_128", "TR31_K0_KEY_ENCRYPTION_KEY"); + Map wrapped = (Map) service.exportKey("us-east-1", key.getKeyId(), + "Tr31KeyBlock", material, "", "").get("WrappedKey"); + String block = (String) wrapped.get("KeyMaterial"); + + assertEquals("B", block.substring(8, 9), "the mode of use of the key"); + } + + @Test + void theCertificateOfAKeyCarriesItsChain() { + // The certificate the service mints is signed by the service, so the chain is the + // certificate itself. + PaymentCryptographyKey key = createKeyPair("RSA_2048"); + + Map answer = service.publicKeyCertificate(key); + + assertNotNull(answer.get("KeyCertificate"), "the certificate is missing"); + assertNotNull(answer.get("KeyCertificateChain"), "the chain of the certificate is missing"); + X509Certificate parsed = Certificates.parseCertificate( + (String) answer.get("KeyCertificate")); + long validity = parsed.getNotAfter().toInstant().getEpochSecond() + - parsed.getNotBefore().toInstant().getEpochSecond(); + // The certificate is good for ninety days, and it starts an hour early so that a + // clock a little behind the service's still accepts it. + assertEquals(90L * 24 * 3600 + 3600, validity, + "the certificate is not valid for ninety days"); + } + +} diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyServiceTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyServiceTest.java index 0b957ea63a..3c68430ffc 100644 --- a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyServiceTest.java +++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyServiceTest.java @@ -61,6 +61,23 @@ class PaymentCryptographyServiceTest { return service.createKey(region, attributes, modes, true, true, Map.of()); } + /** + * The key a key block is wrapped under. + * + *

A key block is wrapped under a key encryption key, and not under a data encryption + * key: the usages keep the two apart. + */ + private PaymentCryptographyKey createWrappingKey(String region) { + Map attributes = new LinkedHashMap<>(); + attributes.put("KeyAlgorithm", "AES_256"); + attributes.put("KeyClass", "SYMMETRIC_KEY"); + attributes.put("KeyUsage", "TR31_K1_KEY_BLOCK_PROTECTION_KEY"); + Map modes = new LinkedHashMap<>(); + modes.put("Wrap", Boolean.TRUE); + modes.put("Unwrap", Boolean.TRUE); + return service.createKey(region, attributes, modes, true, true, Map.of()); + } + @Test void aCreatedKeyIsInItsRegionAndCarriesMaterial() { PaymentCryptographyKey key = createKey("us-east-1"); @@ -540,4 +557,226 @@ class PaymentCryptographyServiceTest { service.find("alias", List.of("alias/team/card-key"), "us-east-1")); assertEquals(Optional.empty(), service.find("approval-team", List.of("whatever"), "us-east-1")); } + + @Test + void aKeyLeavesTheServiceAndComesBack() { + PaymentCryptographyKey protection = createWrappingKey("us-east-1"); + PaymentCryptographyKey key = createKey("us-east-1"); + + Map answer = exportTr31Answer("us-east-1", key.getKeyId(), + protection.getKeyId()); + Map wrapped = (Map) answer.get("WrappedKey"); + String export = (String) wrapped.get("KeyMaterial"); + + assertEquals(protection.getArn(), wrapped.get("WrappingKeyArn")); + assertEquals(key.getKeyCheckValue(), wrapped.get("KeyCheckValue")); + assertTrue(export.length() > 32, "the block is only its header"); + + PaymentCryptographyKey imported = importTr31("us-east-1", protection.getKeyId(), export); + + assertEquals(key.getKeyMaterialHex(), imported.getKeyMaterialHex()); + assertEquals(key.getKeyCheckValue(), imported.getKeyCheckValue()); + assertEquals(key.getKeyUsage(), imported.getKeyUsage()); + assertTrue(imported.isExportable(), "the block said the key is exportable"); + } + + @Test + void aKeyLeavesUnderATdesProtectionKeyAsATypeBBlock() { + // The block type follows the protection key's family: a TDES key gives a type B block, + // an AES one a type D block. That is the rule the emulator follows. + PaymentCryptographyKey protection = service.createKey("us-east-1", + attributes("TDES_2KEY", "TR31_K1_KEY_BLOCK_PROTECTION_KEY"), + Map.of("Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE), true, true, Map.of()); + PaymentCryptographyKey key = service.createKey("us-east-1", + attributes("TDES_2KEY", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"), + Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE), true, true, Map.of()); + + String export = exportTr31("us-east-1", key.getKeyId(), protection.getKeyId()); + + assertTrue(export.startsWith("B"), "a TDES protection key gives a type B block"); + assertEquals("T", export.substring(7, 8), "the block carries a TDES key"); + + PaymentCryptographyKey imported = importTr31("us-east-1", protection.getKeyId(), export); + + assertEquals(key.getKeyMaterialHex(), imported.getKeyMaterialHex()); + assertEquals(key.getKeyCheckValue(), imported.getKeyCheckValue()); + } + + @Test + void aKeyLeavesUnderAnAesProtectionKeyAsATypeDBlock() { + PaymentCryptographyKey protection = service.createKey("us-east-1", + attributes("AES_256", "TR31_K1_KEY_BLOCK_PROTECTION_KEY"), + Map.of("Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE), true, true, Map.of()); + PaymentCryptographyKey key = service.createKey("us-east-1", + attributes("AES_256", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"), + Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE), true, true, Map.of()); + + String export = exportTr31("us-east-1", key.getKeyId(), protection.getKeyId()); + + assertTrue(export.startsWith("D"), "an AES protection key gives a type D block"); + assertEquals("A", export.substring(7, 8), "the block carries an AES key"); + } + + @Test + void aKeyUnderAWeakerProtectionKeyIsRefused() { + // The wrapping key has to be at least as strong as the key it protects, or the + // protection buys nothing. The strengths are the ones the standards count, so a + // two-key TDES key is 80 bits and an AES-128 one is 128. + PaymentCryptographyKey protection = service.createKey("us-east-1", + attributes("AES_128", "TR31_K1_KEY_BLOCK_PROTECTION_KEY"), + Map.of("Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE), true, true, Map.of()); + PaymentCryptographyKey key = service.createKey("us-east-1", + attributes("AES_256", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"), + Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE), true, true, Map.of()); + + AwsException refused = assertThrows(AwsException.class, + () -> exportTr31("us-east-1", key.getKeyId(), protection.getKeyId())); + + assertEquals("ValidationException", refused.getErrorCode()); + assertTrue(refused.getMessage().contains("at least as strong"), refused.getMessage()); + } + + @Test + void aKeyUnderAStrongerProtectionKeyIsAllowed() { + PaymentCryptographyKey protection = service.createKey("us-east-1", + attributes("AES_256", "TR31_K1_KEY_BLOCK_PROTECTION_KEY"), + Map.of("Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE), true, true, Map.of()); + PaymentCryptographyKey key = service.createKey("us-east-1", + attributes("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"), + Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE), true, true, Map.of()); + + String export = exportTr31("us-east-1", key.getKeyId(), protection.getKeyId()); + + assertTrue(export.startsWith("D"), "an AES protection key gives a type D block"); + } + + @Test + void aKeyOfEveryUsageTheServiceMakesLeavesAsItsOwnUsage() { + // A key block carries the usage of the key it carries, so every usage the service + // makes has to have a code. A usage without one could not leave the service at all, + // and the counterparty could not tell what it had. + // + // The asymmetric usage is not in the list: a key pair has no material a key block + // could carry, so it leaves in a TR-34 block, which this service does not write. + List usages = List.of( + new String[] {"TR31_B0_BASE_DERIVATION_KEY", "AES_256"}, + new String[] {"TR31_C0_CARD_VERIFICATION_KEY", "AES_256"}, + new String[] {"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", "AES_256"}, + new String[] {"TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "AES_256"}, + new String[] {"TR31_E1_EMV_MKEY_CONFIDENTIALITY", "AES_256"}, + new String[] {"TR31_E2_EMV_MKEY_INTEGRITY", "AES_256"}, + new String[] {"TR31_E4_EMV_MKEY_DYNAMIC_NUMBERS", "AES_256"}, + new String[] {"TR31_E5_EMV_MKEY_CARD_PERSONALIZATION", "AES_256"}, + new String[] {"TR31_E6_EMV_MKEY_OTHER", "AES_256"}, + new String[] {"TR31_K0_KEY_ENCRYPTION_KEY", "AES_256"}, + new String[] {"TR31_K1_KEY_BLOCK_PROTECTION_KEY", "AES_256"}, + // The ISO 9797 MACs are defined over Triple DES. + new String[] {"TR31_M0_ISO_16609_MAC_KEY", "TDES_2KEY"}, + new String[] {"TR31_M1_ISO_9797_1_MAC_KEY", "TDES_2KEY"}, + new String[] {"TR31_M3_ISO_9797_3_MAC_KEY", "TDES_2KEY"}, + new String[] {"TR31_M6_ISO_9797_5_CMAC_KEY", "AES_256"}, + new String[] {"TR31_M7_HMAC_KEY", "AES_256"}, + new String[] {"TR31_P0_PIN_ENCRYPTION_KEY", "AES_256"}, + new String[] {"TR31_P1_PIN_GENERATION_KEY", "AES_256"}, + new String[] {"TR31_V1_IBM3624_PIN_VERIFICATION_KEY", "AES_256"}, + new String[] {"TR31_V2_VISA_PIN_VERIFICATION_KEY", "AES_256"}); + + PaymentCryptographyKey protection = service.createKey("us-east-1", + attributes("AES_256", "TR31_K1_KEY_BLOCK_PROTECTION_KEY"), + Map.of("Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE), true, true, Map.of()); + + for (String[] usage : usages) { + PaymentCryptographyKey key = service.createKey("us-east-1", + attributes(usage[1], usage[0]), + Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE), true, true, Map.of()); + + String export = exportTr31("us-east-1", key.getKeyId(), protection.getKeyId()); + + PaymentCryptographyKey imported = importTr31("us-east-1", protection.getKeyId(), export); + + assertEquals(usage[0], imported.getKeyUsage(), usage[0] + " did not survive the round trip"); + } + } + + @Test + void anAsymmetricKeyDoesNotLeaveInAKeyBlock() { + // The asymmetric usage is a key pair, and a key pair has no material a key block + // could carry. It leaves in a TR-34 block, which this service does not write. + PaymentCryptographyKey protection = service.createKey("us-east-1", + attributes("AES_256", "TR31_K1_KEY_BLOCK_PROTECTION_KEY"), + Map.of("Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE), true, true, Map.of()); + Map attributes = new LinkedHashMap<>(); + attributes.put("KeyAlgorithm", "RSA_2048"); + attributes.put("KeyClass", "ASYMMETRIC_KEY_PAIR"); + attributes.put("KeyUsage", "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE"); + PaymentCryptographyKey key = service.createKey("us-east-1", attributes, + Map.of("Sign", Boolean.TRUE, "Verify", Boolean.TRUE), true, true, Map.of()); + + AwsException refused = assertThrows(AwsException.class, + () -> exportTr31("us-east-1", key.getKeyId(), protection.getKeyId())); + + assertEquals("ValidationException", refused.getErrorCode()); + } + + @Test + void aKeyThatIsNotExportableDoesNotLeaveTheService() { + PaymentCryptographyKey protection = createKey("us-east-1"); + Map attributes = new LinkedHashMap<>(); + attributes.put("KeyAlgorithm", "AES_256"); + attributes.put("KeyClass", "SYMMETRIC_KEY"); + attributes.put("KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"); + PaymentCryptographyKey key = service.createKey("us-east-1", attributes, Map.of(), false, true, Map.of()); + + AwsException refused = assertThrows(AwsException.class, + () -> exportTr31("us-east-1", key.getKeyId(), protection.getKeyId())); + + assertEquals("ValidationException", refused.getErrorCode()); + } + + @Test + void aBlockThatIsNotTheKeysDoesNotOpen() { + PaymentCryptographyKey protection = createWrappingKey("us-east-1"); + PaymentCryptographyKey other = createWrappingKey("us-east-1"); + PaymentCryptographyKey key = createKey("us-east-1"); + String export = exportTr31("us-east-1", key.getKeyId(), protection.getKeyId()); + + AwsException refused = assertThrows(AwsException.class, + () -> importTr31("us-east-1", other.getKeyId(), export)); + + assertEquals("ValidationException", refused.getErrorCode()); + } + + /** + * The TR-31 key block a key leaves the service in. + */ + private String exportTr31(String region, String keyId, String wrappingKeyId) { + return (String) ((Map) exportTr31Answer(region, keyId, wrappingKeyId) + .get("WrappedKey")).get("KeyMaterial"); + } + + /** + * The whole answer of an export, which carries the block and what wrapped it. + */ + private Map exportTr31Answer(String region, String keyId, String wrappingKeyId) { + return service.exportKey(region, keyId, "Tr31KeyBlock", + Map.of("WrappingKeyIdentifier", wrappingKeyId), "", ""); + } + + /** + * The key that comes into the service out of a TR-31 key block. + */ + private PaymentCryptographyKey importTr31(String region, String wrappingKeyId, String block) { + return service.importKey(region, "Tr31KeyBlock", Map.of( + "WrappingKeyIdentifier", wrappingKeyId, + "WrappedKeyBlock", block), "", true, Map.of()); + } + + /** The attributes of a key with that algorithm and usage. */ + private static Map attributes(String algorithm, String usage) { + Map attributes = new LinkedHashMap<>(); + attributes.put("KeyAlgorithm", algorithm); + attributes.put("KeyClass", "SYMMETRIC_KEY"); + attributes.put("KeyUsage", usage); + return attributes; + } } diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyTr31Test.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyTr31Test.java new file mode 100644 index 0000000000..cb852b7503 --- /dev/null +++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyTr31Test.java @@ -0,0 +1,295 @@ +package io.floci.aws.services.paymentcryptography; + +import org.junit.jupiter.api.Test; + +import java.util.HexFormat; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The TR-31 key block, against the vectors the standard's examples give. + * + *

The values here are the ones a key block must have, checked against an + * independent implementation of the same formats. The block type follows the family of the + * key that protects it: a type B block under a TDES key and a type D one under an AES key, and + * the algorithm byte says which family the key the block carries belongs to. + * + *

Every vector here was computed by the emulator itself, so a block made here and a block + * made there are the same bytes and a block made under one kind of protection key does not open + * under another. + */ +class PaymentCryptographyTr31Test { + + /** The hexadecimal the blocks are written in. */ + private static final HexFormat HEX = HexFormat.of().withUpperCase(); + + /** A two-key TDES key block protection key, sixteen bytes. */ + private static final String TDES_2KEY_KEK = "0123456789ABCDEFFEDCBA9876543210"; + + /** A three-key TDES key block protection key, twenty-four bytes. */ + private static final String TDES_3KEY_KEK = "0123456789ABCDEFFEDCBA9876543210FEDCBA9876543210"; + + /** An AES-128 key block protection key, sixteen bytes. */ + private static final String AES_128_KEK = "0123456789ABCDEFFEDCBA9876543210"; + + /** An AES-192 key block protection key, twenty-four bytes. */ + private static final String AES_192_KEK = "0123456789ABCDEFFEDCBA9876543210FEDCBA9876543210"; + + /** An AES-256 key block protection key, thirty-two bytes. */ + private static final String AES_256_KEK = + "0123456789ABCDEFFEDCBA9876543210FEDCBA98765432100011223344556677"; + + /** The key a block carries. */ + private static final String CLEAR_KEY = "00112233445566778899AABBCCDDEEFF"; + + @Test + void aTypeBBlockUnderATwoKeyTdesKeyIsTheOneTheEmulatorMakes() { + String block = PaymentCryptographyTr31.wrap( + PaymentCryptographyCrypto.fromHex(CLEAR_KEY), + PaymentCryptographyCrypto.fromHex(TDES_2KEY_KEK), + false, "T", "D0", "B", "E"); + + assertEquals("B0080D0TB00E000026E528E7FBDBA2578329DDD6F427055C2D51AF1AF42ED5829C79F8ADD31152C8", + block); + assertEquals("D0", PaymentCryptographyTr31.usageOf(block)); + assertEquals("B", PaymentCryptographyTr31.modeOf(block)); + assertEquals("E", PaymentCryptographyTr31.exportabilityOf(block)); + } + + @Test + void aTypeBBlockUnderAThreeKeyTdesKeyIsTheOneTheEmulatorMakes() { + String block = PaymentCryptographyTr31.wrap( + PaymentCryptographyCrypto.fromHex(CLEAR_KEY), + PaymentCryptographyCrypto.fromHex(TDES_3KEY_KEK), + false, "T", "D0", "B", "E"); + + assertEquals("B0080D0TB00E000001FF74012D3ABDE92191B91AA598383A0FD7CB744A9E4AFE9D34A369AD6552C3", + block); + } + + @Test + void aTypeDBlockUnderAnAes128KeyIsTheOneTheEmulatorMakes() { + String block = PaymentCryptographyTr31.wrap( + PaymentCryptographyCrypto.fromHex(CLEAR_KEY), + PaymentCryptographyCrypto.fromHex(AES_128_KEK), + true, "A", "D0", "B", "E"); + + assertEquals("D0112D0AB00E00002BF9E2CB83E27A26C8790C18CAC198C415E9E78520142D81320789CFD5B9C09DEF03F7569177D33FD1BE0A1DAB4D33AB", + block); + } + + @Test + void aTypeDBlockUnderAnAes192KeyIsTheOneTheEmulatorMakes() { + String block = PaymentCryptographyTr31.wrap( + PaymentCryptographyCrypto.fromHex(CLEAR_KEY), + PaymentCryptographyCrypto.fromHex(AES_192_KEK), + true, "A", "D0", "B", "E"); + + assertEquals("D0112D0AB00E00003FF1AB040D384A3F1827C5EE54DC7CFA43635B0186A3A63A57E77958737CEA57B972DFE983F559525768746563BC6FF7", + block); + assertEquals("D0", PaymentCryptographyTr31.usageOf(block)); + assertEquals("B", PaymentCryptographyTr31.modeOf(block)); + assertEquals("E", PaymentCryptographyTr31.exportabilityOf(block)); + } + + @Test + void aTypeDBlockUnderAnAes256KeyIsTheOneTheEmulatorMakes() { + String block = PaymentCryptographyTr31.wrap( + PaymentCryptographyCrypto.fromHex(CLEAR_KEY), + PaymentCryptographyCrypto.fromHex(AES_256_KEK), + true, "A", "D0", "B", "E"); + + assertEquals("D0112D0AB00E00003E9F4789A8798032CEC87CBA5960E1D7F4512292784F56164C0A62AA2F184D2151167F8F8013169102F89530D9B0C647", + block); + } + + @Test + void aBlockOpensUnderTheKeyThatMadeIt() { + String block = PaymentCryptographyTr31.wrap( + PaymentCryptographyCrypto.fromHex(CLEAR_KEY), + PaymentCryptographyCrypto.fromHex(TDES_2KEY_KEK), + false, "T", "D0", "B", "E"); + + assertArrayEquals(PaymentCryptographyCrypto.fromHex(CLEAR_KEY), + PaymentCryptographyTr31.unwrap(block, PaymentCryptographyCrypto.fromHex(TDES_2KEY_KEK))); + } + + @Test + void aTypeDBlockOpensUnderTheAesKeyThatMadeIt() { + String block = PaymentCryptographyTr31.wrap( + PaymentCryptographyCrypto.fromHex(CLEAR_KEY), + PaymentCryptographyCrypto.fromHex(AES_192_KEK), + true, "A", "D0", "B", "E"); + + assertArrayEquals(PaymentCryptographyCrypto.fromHex(CLEAR_KEY), + PaymentCryptographyTr31.unwrap(block, PaymentCryptographyCrypto.fromHex(AES_192_KEK))); + } + + @Test + void aBlockDoesNotOpenUnderAnotherKey() { + String block = PaymentCryptographyTr31.wrap( + PaymentCryptographyCrypto.fromHex(CLEAR_KEY), + PaymentCryptographyCrypto.fromHex(TDES_2KEY_KEK), + false, "T", "D0", "B", "E"); + + try { + PaymentCryptographyTr31.unwrap(block, + PaymentCryptographyCrypto.fromHex("FEDCBA98765432100123456789ABCDEF")); + throw new AssertionError("the block opened under the wrong key"); + } catch (IllegalArgumentException expected) { + assertEquals("the key block did not authenticate under the key", expected.getMessage()); + } + } + + @Test + void aTypeDBlockDoesNotOpenUnderAnotherKeyOfTheSameLength() { + String block = PaymentCryptographyTr31.wrap( + PaymentCryptographyCrypto.fromHex(CLEAR_KEY), + PaymentCryptographyCrypto.fromHex(AES_192_KEK), + true, "A", "D0", "B", "E"); + + try { + PaymentCryptographyTr31.unwrap(block, + PaymentCryptographyCrypto.fromHex("FEDCBA98765432100123456789ABCDEFFEDCBA9876543210")); + throw new AssertionError("the block opened under another key"); + } catch (IllegalArgumentException expected) { + assertEquals("the key block did not authenticate under the key", expected.getMessage()); + } + } + + @Test + void aBlockWithOptionalBlocksIsImported() { + // An optional block sits between the header and the cipher text in the clear, and it + // is authenticated with it, so the cipher text starts after it. + // The identifier, the length over two characters and the value. The length covers + // the whole block, the identifier and the length included, and it is in hexadecimal. + String block = blockWithOptionalBlock("00" + "0C" + "61626364"); + + byte[] key = PaymentCryptographyTr31.unwrap(block, + PaymentCryptographyCrypto.fromHex(AES_128_KEK)); + + assertArrayEquals(PaymentCryptographyCrypto.fromHex(CLEAR_KEY), key); + } + + @Test + void anOptionalBlockWithALengthInHexadecimalIsRead() { + // The length of an optional block is in hexadecimal, so a length of "0E" is fourteen + // characters and not a number at all. + String block = blockWithOptionalBlock("TT" + "0E" + "0123456789"); + + byte[] key = PaymentCryptographyTr31.unwrap(block, + PaymentCryptographyCrypto.fromHex(AES_128_KEK)); + + assertArrayEquals(PaymentCryptographyCrypto.fromHex(CLEAR_KEY), key); + } + + @Test + void theOptionalBlockTheReferenceGivesIsWrittenAsItGivesIt() { + // The reference gives the base derivation key identifier of a DUKPT key as "BI" with + // the value "00ABCDEFABCD", and its length is written as "10": the whole block is + // sixteen characters, the identifier and the length included. + String block = PaymentCryptographyTr31.wrap( + PaymentCryptographyCrypto.fromHex(CLEAR_KEY), + PaymentCryptographyCrypto.fromHex(AES_128_KEK), true, + "A", "D0", "B", "E", "00", + List.of(new String[] {"BI", "00ABCDEFABCD"})); + + assertEquals("BI1000ABCDEFABCD", block.substring(16, 32), + "the optional block was not written as the standard says"); + } + + @Test + void aBlockIsPaddedSoThatItsOptionalBlocksStayAligned() { + // The optional blocks take up a whole number of cipher blocks, so a block whose + // optional blocks are not aligned gets a padding block that makes them so. The + // optional block here is twenty-four characters and a cipher block is sixteen, so + // the padding block carries four characters of filler. + String block = PaymentCryptographyTr31.wrap( + PaymentCryptographyCrypto.fromHex(CLEAR_KEY), + PaymentCryptographyCrypto.fromHex(AES_128_KEK), true, + "A", "D0", "B", "E", "00", + List.of(new String[] {"KS", "00604B120F9292800000"})); + + // The optional block and the padding block between the header and the cipher text. + String optional = block.substring(16, 16 + 32); + assertEquals("KS1800604B120F9292800000", optional.substring(0, 24), + "the optional block was not written as the standard says"); + assertEquals("PB080000", optional.substring(24), "the padding block was not added"); + assertEquals(2, Integer.parseInt(block.substring(12, 14)), + "the padding block was not counted"); + } + + @Test + void aBlockWhoseOptionalBlocksAreAlignedGetsNoPaddingBlock() { + // Optional blocks that already fill whole cipher blocks are left alone, because a + // padding block would break the alignment. Twelve characters of data make the + // optional block sixteen characters long, which is one cipher block. + String block = PaymentCryptographyTr31.wrap( + PaymentCryptographyCrypto.fromHex(CLEAR_KEY), + PaymentCryptographyCrypto.fromHex(AES_128_KEK), true, + "A", "D0", "B", "E", "00", + List.of(new String[] {"KS", "00604B120F92"})); + + assertEquals(1, Integer.parseInt(block.substring(12, 14)), + "a padding block was added to aligned optional blocks"); + } + + @Test + void aBlockWhoseKeyIsNotAWholeNumberOfBytesIsRefused() { + // The length the block declares is in bits, and a key is a whole number of bytes. + String block = blockWithLength("0081"); + + IllegalArgumentException refused = assertThrows(IllegalArgumentException.class, + () -> PaymentCryptographyTr31.unwrap(block, + PaymentCryptographyCrypto.fromHex(AES_128_KEK))); + + assertTrue(refused.getMessage().contains("whole number of bytes"), refused.getMessage()); + } + + /** + * A type D block with an optional block in the clear. + * + *

The optional block is its identifier over two characters, its length over four and + * then its value. The header says how many of them there are. + */ + private String blockWithOptionalBlock(String optional) { + byte[] lengthEncoded = PaymentCryptographyTr31.lengthEncode( + PaymentCryptographyCrypto.fromHex(CLEAR_KEY), 16); + byte[][] derived = PaymentCryptographyTr31.deriveKeys( + PaymentCryptographyCrypto.fromHex(AES_128_KEK), true); + int blockLength = 16 + optional.length() + lengthEncoded.length * 2 + 32; + String header = "D" + String.format("%04d", blockLength) + "D0" + "A" + "B" + "00" + "E" + + "01" + "00"; + byte[] mac = PaymentCryptographyTr31.computeMac(header + optional, lengthEncoded, + derived[1], true); + byte[] cipherText = PaymentCryptographyCrypto.aesCbcEncrypt(derived[0], mac, lengthEncoded); + return header + optional + HEX.formatHex(cipherText) + HEX.formatHex(mac); + } + + /** + * A type D block whose length field says the given bits. + * + *

The length is over the key the block carries, and the rest of the block is built the + * way the emulator builds one. + */ + private String blockWithLength(String length) { + byte[] clearKey = PaymentCryptographyCrypto.fromHex(CLEAR_KEY); + byte[] lengthEncoded = new byte[32]; + lengthEncoded[0] = (byte) ((Integer.parseInt(length, 16) >> 8) & 0xff); + lengthEncoded[1] = (byte) (Integer.parseInt(length, 16) & 0xff); + System.arraycopy(clearKey, 0, lengthEncoded, 2, clearKey.length); + byte[][] derived = PaymentCryptographyTr31.deriveKeys( + PaymentCryptographyCrypto.fromHex(AES_128_KEK), true); + int blockLength = 16 + lengthEncoded.length * 2 + 32; + String header = "D" + String.format("%04d", blockLength) + "D0" + "A" + "B" + "00" + "E" + + "00" + "00"; + byte[] mac = PaymentCryptographyTr31.computeMac(header, lengthEncoded, derived[1], true); + byte[] cipherText = PaymentCryptographyCrypto.aesCbcEncrypt(derived[0], mac, lengthEncoded); + return header + HEX.formatHex(cipherText) + HEX.formatHex(mac); + } + +} diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/crypto/CertificatesTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/crypto/CertificatesTest.java new file mode 100644 index 0000000000..44b3524e25 --- /dev/null +++ b/src/test/java/io/floci/aws/services/paymentcryptography/crypto/CertificatesTest.java @@ -0,0 +1,100 @@ +package io.floci.aws.services.paymentcryptography.crypto; + +import io.floci.aws.services.acm.CertificateGenerator; +import org.bouncycastle.asn1.pkcs.IssuerAndSerialNumber; +import org.bouncycastle.asn1.x500.X500Name; +import org.junit.jupiter.api.Test; + +import java.math.BigInteger; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * The certificates the key exchange hands out and reads. + * + *

The identifier a TR-34 block names its recipient with is the certificate's own issuer + * and serial number, so the two are read back from the certificate the service minted and + * compared with what the identifier carries. + */ +public class CertificatesTest { + + private static final String CN = "floci key-exchange"; + + @Test + void theIdentifierOfACertificateIsItsIssuerAndItsSerial() throws Exception { + KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); + Instant now = Instant.now(); + Certificates.Minted certificate = mint(keyPair.getPublic(), CN, keyPair.getPrivate(), CN); + + byte[] identifier = Certificates.certificateId(certificate.der()); + + assertNotNull(identifier); + IssuerAndSerialNumber parsed = IssuerAndSerialNumber.getInstance(identifier); + X509Certificate certificateParsed = Certificates.parseCertificate(certificate.pem()); + assertEquals(certificateParsed.getSerialNumber(), + parsed.getCertificateSerialNumber().getValue()); + assertEquals(certificateParsed.getIssuerX500Principal().getName(), + parsed.getName().toString()); + } + + @Test + void theIdentifierOfACertificateThatDoesNotParseIsRefused() { + try { + Certificates.certificateId(new byte[] {0x30, 0x03, 0x02, 0x01, 0x05}); + } catch (RuntimeException refused) { + assertEquals(true, refused.getMessage().contains("does not parse")); + return; + } + throw new AssertionError("a certificate that does not parse was accepted"); + } + + @Test + void theSerialOfTheIdentifierIsTheCertificatesOwn() throws Exception { + KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); + Instant now = Instant.now(); + Certificates.Minted certificate = mint(keyPair.getPublic(), CN, keyPair.getPrivate(), CN); + + BigInteger serial = IssuerAndSerialNumber + .getInstance(Certificates.certificateId(certificate.der())) + .getCertificateSerialNumber().getValue(); + + assertEquals(Certificates.parseCertificate(certificate.pem()).getSerialNumber(), serial); + } + + /** + * A certificate over a key pair, signed by an issuer. + * + *

The service mints its certificates through ACM's generator, and a test that needs a + * certificate of its own mints it the same way. + */ + public static Certificates.Minted mint(PublicKey subjectKey, String subjectName, + PrivateKey issuerKey, String issuerName) { + return mint(subjectKey, subjectName, issuerKey, issuerName, + Instant.now().minusSeconds(3600), Instant.now().plusSeconds(86400)); + } + + /** A certificate over a key pair, signed by an issuer, with the given validity window. */ + public static Certificates.Minted mint(PublicKey subjectKey, String subjectName, + PrivateKey issuerKey, String issuerName, + Instant notBefore, Instant notAfter) { + CertificateGenerator generator = new CertificateGenerator(); + try { + X509Certificate certificate = generator.signCertificate( + new X500Name("CN=" + subjectName), subjectKey, + new X500Name("CN=" + issuerName), issuerKey, + List.of(), false, null, notBefore, notAfter); + byte[] der = certificate.getEncoded(); + return new Certificates.Minted(der, Certificates.toPem(der)); + } catch (Exception e) { + throw new IllegalStateException("cannot mint a certificate", e); + } + } +} diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsAwsSdkTaskIntegrationTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsAwsSdkTaskIntegrationTest.java index d758c15a67..669f4bc03f 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsAwsSdkTaskIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsAwsSdkTaskIntegrationTest.java @@ -148,7 +148,7 @@ class StepFunctionsAwsSdkTaskIntegrationTest { @Test @Order(4) - void startExecutionReusingAnExecutionNameFailsWithTheSdkExceptionName() { + void startExecutionReusingAnExecutionNameFailsWithTheSdkExceptionName() throws Exception { String smArn = createStateMachine("aws-sdk-start-execution-named", """ { "QueryLanguage": "JSONata", @@ -164,8 +164,16 @@ class StepFunctionsAwsSdkTaskIntegrationTest { } """.replace("CHILD_ARN", quickChildArn)); - assertEquals("SUCCEEDED", waitForTerminalState(startExecution(smArn, "{}")) - .jsonPath().getString("status")); + Response first = waitForTerminalState(startExecution(smArn, "{}")); + assertEquals("SUCCEEDED", first.jsonPath().getString("status")); + + // The name is taken while the child's execution runs, and a start with that name and + // the same input then returns that execution again, so the second start would + // succeed. The name is a conflict once the child's execution is closed, so the test + // waits for that. + String childArn = mapper.readTree(first.jsonPath().getString("output")) + .path("ExecutionArn").asText(); + waitForTerminalState(childArn); Response describe = waitForTerminalState(startExecution(smArn, "{}")); assertEquals("FAILED", describe.jsonPath().getString("status")); diff --git a/tools/aws/regen_payment_cryptography_data_shapes.py b/tools/aws/regen_payment_cryptography_data_shapes.py index f7d8a45633..5522d9645f 100644 --- a/tools/aws/regen_payment_cryptography_data_shapes.py +++ b/tools/aws/regen_payment_cryptography_data_shapes.py @@ -23,18 +23,12 @@ import request_shapes OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/payment-cryptography-data-request-shapes.json" MODEL = Path("payment-cryptography-data/2022-02-03") -OPERATIONS = ( - "EncryptData", "DecryptData", "ReEncryptData", - "GenerateMac", "VerifyMac", - "GeneratePinData", "VerifyPinData", "TranslatePinData", "GenerateMacEmvPinChange", - "GenerateCardValidationData", "VerifyCardValidationData", - "GenerateAuthRequestCryptogram", "VerifyAuthRequestCryptogram", -) def main(argv: list[str] | None = None) -> int: return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT, - description=__doc__, operations=OPERATIONS, + description=__doc__, + constraints=True, prepare=request_shapes.widen_partition_and_region) diff --git a/tools/aws/regen_payment_cryptography_shapes.py b/tools/aws/regen_payment_cryptography_shapes.py index 28baa2f77d..8e5f2917c0 100644 --- a/tools/aws/regen_payment_cryptography_shapes.py +++ b/tools/aws/regen_payment_cryptography_shapes.py @@ -20,16 +20,12 @@ import request_shapes OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/payment-cryptography-request-shapes.json" MODEL = Path("payment-cryptography/2021-09-14") -OPERATIONS = ( - "CreateKey", "GetKey", "ListKeys", "DeleteKey", - "CreateAlias", "GetAlias", "ListAliases", "UpdateAlias", "DeleteAlias", - "TagResource", "UntagResource", "ListTagsForResource", -) def main(argv: list[str] | None = None) -> int: return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT, - description=__doc__, operations=OPERATIONS, + description=__doc__, + constraints=True, prepare=request_shapes.widen_partition_and_region) diff --git a/tools/aws/request_shapes.py b/tools/aws/request_shapes.py index 5896d55be6..0052ca326e 100644 --- a/tools/aws/request_shapes.py +++ b/tools/aws/request_shapes.py @@ -152,7 +152,8 @@ def generator_name(script: str) -> str: return path.relative_to(REPO_ROOT).as_posix() if path.is_relative_to(REPO_ROOT) else path.name -def main(argv: list[str] | None, *, script: str, model: Path, output: Path, description: str, +def main(argv: list[str] | None, *, script: str, model: Path, output: Path, + description: str | None = None, outputs: bool = False, required: bool = False, operations: tuple[str, ...] | None = None, constraints: bool = False, prepare: Callable[[dict], dict] | None = None) -> int: diff --git a/tools/aws/test_request_shapes.py b/tools/aws/test_request_shapes.py index 39989553ed..4f1f7d937c 100644 --- a/tools/aws/test_request_shapes.py +++ b/tools/aws/test_request_shapes.py @@ -26,6 +26,7 @@ import regen_ecr_shapes import regen_ecs_shapes import regen_emr_serverless_shapes import regen_iam_shapes +import regen_payment_cryptography_data_shapes import regen_payment_cryptography_shapes import regen_logs_delivery_shapes import regen_resource_groups_shapes @@ -400,6 +401,30 @@ def test_each_constraints_script_runs_the_shared_main_with_its_operations(script })] +@pytest.mark.parametrize("script, model, output", [ + (regen_payment_cryptography_shapes, "payment-cryptography/2021-09-14", + "payment-cryptography-request-shapes.json"), + (regen_payment_cryptography_data_shapes, "payment-cryptography-data/2022-02-03", + "payment-cryptography-data-request-shapes.json"), +]) +def test_each_payment_cryptography_script_runs_the_shared_main_with_every_operation(script, model, output, + monkeypatch): + # The generator names no operation, so it asks the driver for the model's whole set: an + # operation the service serves later is covered without anyone adding it to a list. + calls = [] + monkeypatch.setattr(r, "main", lambda argv, **kwargs: calls.append((argv, kwargs)) or 0) + + assert script.main(["--check"]) == 0 + assert calls == [(["--check"], { + "script": script.__file__, + "model": Path(model), + "output": r.REPO_ROOT / "src/main/resources/aws" / output, + "description": script.__doc__ or "", + "constraints": True, + "prepare": r.widen_partition_and_region, + })] + + def vendored(script) -> tuple[str, ...]: """The operations a generator's file carries, which is `OPERATIONS` unless it names more.""" return getattr(script, "VENDORED", None) or script.OPERATIONS @@ -407,7 +432,6 @@ def vendored(script) -> tuple[str, ...]: @pytest.mark.parametrize("script", [ regen_apigateway_documentation_shapes, regen_ecr_shapes, regen_iam_shapes, regen_logs_delivery_shapes, - regen_payment_cryptography_shapes, regen_resource_groups_shapes, regen_sts_shapes, regen_securityhub_shapes, regen_rekognition_shapes, @@ -416,8 +440,52 @@ def vendored(script) -> tuple[str, ...]: def test_each_vendored_constraints_file_carries_its_operations_and_resolves_its_shapes(script): doc = json.loads(script.OUTPUT.read_text(encoding="utf-8")) + # A generator that names no operation carries every one the model names, so the + # operations are only compared for one that names them. if hasattr(script, "OPERATIONS") or hasattr(script, "VENDORED"): assert sorted(doc["operations"]) == sorted(vendored(script)) + assert_shapes_resolve(doc) + + +@pytest.mark.parametrize("script", [ + regen_payment_cryptography_shapes, regen_payment_cryptography_data_shapes, +]) +def test_each_payment_cryptography_file_carries_every_operation_the_model_names(script): + # The generator names no operation, so the file carries every operation the model names: + # an operation the service serves later is checked without anyone adding it to a list. + pytest.importorskip("botocore") + try: + data, _ = r.resolve_botocore_data(None) + except SystemExit: + pytest.skip("the botocore data cannot be read here") + model = r.load_model(data, script.MODEL) + + doc = json.loads(script.OUTPUT.read_text(encoding="utf-8")) + + # An operation the model names without an input has no request to constrain. + named = {name for name, operation in model["operations"].items() if "input" in operation} + assert sorted(doc["operations"]) == sorted(named) + assert_shapes_resolve(doc) + + +def test_main_leaves_out_an_operation_without_an_input(tmp_path, monkeypatch): + # An operation the model names without an input has no request to constrain, and the + # generator that asks for every operation leaves it out. + model = {"operations": {"Put": {"input": {"shape": "PutRequest"}}, "Nothing": {}}, + "shapes": {"PutRequest": {"type": "structure", "members": {}}}} + output = tmp_path / "shapes.json" + monkeypatch.setattr(r, "resolve_botocore_data", lambda explicit: (tmp_path, "botocore test")) + monkeypatch.setattr(r, "load_model", lambda data, path: model) + + assert r.main(["--output", str(output)], script=__file__, model=Path("x"), output=output, + description="test", constraints=True) == 0 + + doc = json.loads(output.read_text()) + assert doc["operations"] == {"Put": "PutRequest"} + + +def assert_shapes_resolve(doc: dict) -> None: + """Every operation's shape is in the file, and every shape's members resolve to shapes in it.""" for operation, shape in doc["operations"].items(): assert shape in doc["shapes"], operation for name, shape in doc["shapes"].items(): @@ -499,8 +567,11 @@ def test_ecr_shapes_name_the_ecr_model_and_its_registry_setting_actions(): def test_payment_cryptography_shapes_name_its_model_and_its_control_plane_actions(): assert regen_payment_cryptography_shapes.MODEL == Path("payment-cryptography/2021-09-14") assert regen_payment_cryptography_shapes.OUTPUT.name == "payment-cryptography-request-shapes.json" - assert "TagResource" in regen_payment_cryptography_shapes.OPERATIONS - assert "UpdateAlias" in regen_payment_cryptography_shapes.OPERATIONS + # The generator names no operation, so the file carries the model's whole set. + assert not hasattr(regen_payment_cryptography_shapes, "OPERATIONS") + operations = json.loads(regen_payment_cryptography_shapes.OUTPUT.read_text(encoding="utf-8"))["operations"] + assert "TagResource" in operations + assert "UpdateAlias" in operations def test_payment_cryptography_shapes_widen_the_partition_the_model_writes():