|
| 1 | +package uk.gov.di.ipv.cri.common.library.service; |
| 2 | + |
| 3 | +import com.nimbusds.jose.EncryptionMethod; |
| 4 | +import com.nimbusds.jose.JOSEException; |
| 5 | +import com.nimbusds.jose.JWEAlgorithm; |
| 6 | +import com.nimbusds.jose.JWEDecrypter; |
| 7 | +import com.nimbusds.jose.JWEHeader; |
| 8 | +import com.nimbusds.jose.crypto.impl.AlgorithmSupportMessage; |
| 9 | +import com.nimbusds.jose.crypto.impl.ContentCryptoProvider; |
| 10 | +import com.nimbusds.jose.jca.JWEJCAContext; |
| 11 | +import com.nimbusds.jose.util.Base64URL; |
| 12 | +import org.apache.logging.log4j.LogManager; |
| 13 | +import org.apache.logging.log4j.Logger; |
| 14 | +import software.amazon.awssdk.core.SdkBytes; |
| 15 | +import software.amazon.awssdk.services.kms.KmsClient; |
| 16 | +import software.amazon.awssdk.services.kms.model.DecryptRequest; |
| 17 | +import software.amazon.awssdk.services.kms.model.DecryptResponse; |
| 18 | +import software.amazon.awssdk.services.kms.model.EncryptionAlgorithmSpec; |
| 19 | +import uk.gov.di.ipv.cri.common.library.util.EventProbe; |
| 20 | + |
| 21 | +import javax.crypto.SecretKey; |
| 22 | +import javax.crypto.spec.SecretKeySpec; |
| 23 | + |
| 24 | +import java.util.Objects; |
| 25 | +import java.util.Set; |
| 26 | + |
| 27 | +import static software.amazon.awssdk.services.kms.model.EncryptionAlgorithmSpec.RSAES_OAEP_SHA_256; |
| 28 | + |
| 29 | +public class KMSRSADecrypter implements JWEDecrypter { |
| 30 | + private static final Set<JWEAlgorithm> SUPPORTED_ALGORITHMS = Set.of(JWEAlgorithm.RSA_OAEP_256); |
| 31 | + private static final Set<EncryptionMethod> SUPPORTED_ENCRYPTION_METHODS = |
| 32 | + Set.of(EncryptionMethod.A256GCM); |
| 33 | + private static final Logger LOGGER = LogManager.getLogger(); |
| 34 | + private static final String SESSION_DECRYPTION_KEY_PRIMARY_ALIAS = |
| 35 | + "session_decryption_key_active_alias"; |
| 36 | + private static final String SESSION_DECRYPTION_KEY_SECONDARY_ALIAS = |
| 37 | + "session_decryption_key_inactive_alias"; |
| 38 | + private static final String SESSION_DECRYPTION_KEY_PREVIOUS_ALIAS = |
| 39 | + "session_decryption_key_previous_alias"; |
| 40 | + private static final String ALL_ALIASES_UNAVAILABLE = "all_aliases_unavailable_for_decryption"; |
| 41 | + private boolean keyRotationEnabled = false; |
| 42 | + private final JWEJCAContext jcaContext; |
| 43 | + private final KmsClient kmsClient; |
| 44 | + private final EventProbe eventProbe; |
| 45 | + private final String keyId; |
| 46 | + |
| 47 | + public KMSRSADecrypter(String keyId, KmsClient kmsClient, EventProbe eventProbe) { |
| 48 | + this( |
| 49 | + kmsClient, |
| 50 | + eventProbe, |
| 51 | + keyId, |
| 52 | + Boolean.parseBoolean(System.getenv("ENV_VAR_FEATURE_FLAG_KEY_ROTATION"))); |
| 53 | + } |
| 54 | + |
| 55 | + public KMSRSADecrypter( |
| 56 | + KmsClient kmsClient, EventProbe eventProbe, String keyId, Boolean keyRotationEnabled) { |
| 57 | + this.jcaContext = new JWEJCAContext(); |
| 58 | + this.kmsClient = kmsClient; |
| 59 | + this.eventProbe = eventProbe; |
| 60 | + this.keyId = keyId; |
| 61 | + this.keyRotationEnabled = keyRotationEnabled; |
| 62 | + } |
| 63 | + |
| 64 | + @Override |
| 65 | + public byte[] decrypt( |
| 66 | + JWEHeader header, |
| 67 | + Base64URL encryptedKey, |
| 68 | + Base64URL iv, |
| 69 | + Base64URL cipherText, |
| 70 | + Base64URL authTag, |
| 71 | + byte[] aad) |
| 72 | + throws JOSEException { |
| 73 | + // Validate required JWE parts |
| 74 | + if (Objects.isNull(encryptedKey)) { |
| 75 | + throw new JOSEException("Missing JWE encrypted key"); |
| 76 | + } |
| 77 | + |
| 78 | + if (Objects.isNull(iv)) { |
| 79 | + throw new JOSEException("Missing JWE initialization vector (IV)"); |
| 80 | + } |
| 81 | + |
| 82 | + if (Objects.isNull(authTag)) { |
| 83 | + throw new JOSEException("Missing JWE authentication tag"); |
| 84 | + } |
| 85 | + |
| 86 | + JWEAlgorithm alg = header.getAlgorithm(); |
| 87 | + |
| 88 | + if (!SUPPORTED_ALGORITHMS.contains(alg)) { |
| 89 | + throw new JOSEException( |
| 90 | + AlgorithmSupportMessage.unsupportedJWEAlgorithm(alg, supportedJWEAlgorithms())); |
| 91 | + } |
| 92 | + DecryptResponse decryptResponse; |
| 93 | + if (isKeyRotationEnabled()) { |
| 94 | + LOGGER.info("Key rotation enabled. Attempting to decrypt with key aliases."); |
| 95 | + // During a key rotation we might receive JWTs encrypted with either the old or new key. |
| 96 | + decryptResponse = decryptWithKeyAliases(encryptedKey); |
| 97 | + |
| 98 | + if (decryptResponse == null) { |
| 99 | + String message = "Failed to decrypt with all available key aliases."; |
| 100 | + LOGGER.error(message); |
| 101 | + throw new JOSEException(message); |
| 102 | + } |
| 103 | + } else { |
| 104 | + DecryptRequest decryptRequest = |
| 105 | + DecryptRequest.builder() |
| 106 | + .encryptionAlgorithm(EncryptionAlgorithmSpec.RSAES_OAEP_SHA_256) |
| 107 | + .ciphertextBlob(SdkBytes.fromByteArray(encryptedKey.decode())) |
| 108 | + .keyId(this.keyId) |
| 109 | + .build(); |
| 110 | + decryptResponse = this.kmsClient.decrypt(decryptRequest); |
| 111 | + } |
| 112 | + |
| 113 | + SecretKey cek = new SecretKeySpec(decryptResponse.plaintext().asByteArray(), "AES"); |
| 114 | + return ContentCryptoProvider.decrypt( |
| 115 | + header, null, encryptedKey, iv, cipherText, authTag, cek, getJCAContext()); |
| 116 | + } |
| 117 | + |
| 118 | + private DecryptResponse decryptWithKeyAliases(Base64URL encryptedKey) { |
| 119 | + String[] keyAliases = { |
| 120 | + SESSION_DECRYPTION_KEY_PRIMARY_ALIAS, |
| 121 | + SESSION_DECRYPTION_KEY_SECONDARY_ALIAS, |
| 122 | + SESSION_DECRYPTION_KEY_PREVIOUS_ALIAS |
| 123 | + }; |
| 124 | + |
| 125 | + DecryptResponse decryptResponse = null; |
| 126 | + for (String alias : keyAliases) { |
| 127 | + try { |
| 128 | + decryptResponse = kmsClient.decrypt(buildDecryptRequest(alias, encryptedKey)); |
| 129 | + LOGGER.info("Decryption successful with key alias: {}", alias); |
| 130 | + return decryptResponse; |
| 131 | + } catch (Exception e) { |
| 132 | + LOGGER.warn( |
| 133 | + "Failed to decrypt with key alias: {}. Error: {}", alias, e.getMessage()); |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + eventProbe.counterMetric(ALL_ALIASES_UNAVAILABLE); |
| 138 | + |
| 139 | + return decryptResponse; |
| 140 | + } |
| 141 | + |
| 142 | + public boolean isKeyRotationEnabled() { |
| 143 | + return keyRotationEnabled; |
| 144 | + } |
| 145 | + |
| 146 | + private DecryptRequest buildDecryptRequest(String keyAlias, Base64URL encryptedKey) { |
| 147 | + return DecryptRequest.builder() |
| 148 | + .ciphertextBlob(SdkBytes.fromByteArray(encryptedKey.decode())) |
| 149 | + .encryptionAlgorithm(RSAES_OAEP_SHA_256) |
| 150 | + .keyId("alias/" + keyAlias) |
| 151 | + .build(); |
| 152 | + } |
| 153 | + |
| 154 | + @Override |
| 155 | + public Set<JWEAlgorithm> supportedJWEAlgorithms() { |
| 156 | + return SUPPORTED_ALGORITHMS; |
| 157 | + } |
| 158 | + |
| 159 | + @Override |
| 160 | + public Set<EncryptionMethod> supportedEncryptionMethods() { |
| 161 | + return SUPPORTED_ENCRYPTION_METHODS; |
| 162 | + } |
| 163 | + |
| 164 | + @Override |
| 165 | + public JWEJCAContext getJCAContext() { |
| 166 | + return jcaContext; |
| 167 | + } |
| 168 | +} |
0 commit comments