|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +package com.azure.spring.cloud.autoconfigure.implementation.keyvault.jca; |
| 5 | + |
| 6 | +import com.azure.security.keyvault.jca.KeyVaultJcaProvider; |
| 7 | +import com.azure.spring.cloud.autoconfigure.implementation.keyvault.jca.properties.AzureKeyVaultJcaProperties; |
| 8 | +import com.azure.spring.cloud.autoconfigure.implementation.keyvault.jca.properties.AzureKeyVaultSslBundleProperties; |
| 9 | +import com.azure.spring.cloud.core.implementation.properties.PropertyMapper; |
| 10 | +import org.slf4j.Logger; |
| 11 | +import org.slf4j.LoggerFactory; |
| 12 | +import org.springframework.boot.autoconfigure.ssl.SslBundleRegistrar; |
| 13 | +import org.springframework.boot.ssl.SslBundle; |
| 14 | +import org.springframework.boot.ssl.SslBundleKey; |
| 15 | +import org.springframework.boot.ssl.SslBundleRegistry; |
| 16 | +import org.springframework.boot.ssl.SslOptions; |
| 17 | +import org.springframework.boot.ssl.SslStoreBundle; |
| 18 | +import org.springframework.context.ResourceLoaderAware; |
| 19 | +import org.springframework.core.io.ResourceLoader; |
| 20 | +import org.springframework.util.ClassUtils; |
| 21 | +import org.springframework.util.StringUtils; |
| 22 | + |
| 23 | +import java.io.IOException; |
| 24 | +import java.security.KeyStore; |
| 25 | +import java.security.KeyStoreException; |
| 26 | +import java.security.NoSuchAlgorithmException; |
| 27 | +import java.security.NoSuchProviderException; |
| 28 | +import java.security.Security; |
| 29 | +import java.security.cert.CertificateException; |
| 30 | +import java.util.Arrays; |
| 31 | +import java.util.Map; |
| 32 | +import java.util.Objects; |
| 33 | +import java.util.Optional; |
| 34 | +import java.util.concurrent.atomic.AtomicBoolean; |
| 35 | + |
| 36 | +/** |
| 37 | + * Azure Key Vault SslBundleRegistrar that registers SSL bundles based Key Vault JCA properties and Key Vault SSL bundle properties. |
| 38 | + * |
| 39 | + * @since 5.21.0 |
| 40 | + */ |
| 41 | +public class AzureKeyVaultSslBundleRegistrar implements SslBundleRegistrar, ResourceLoaderAware { |
| 42 | + |
| 43 | + private static final Logger LOGGER = LoggerFactory.getLogger(AzureKeyVaultSslBundleRegistrar.class); |
| 44 | + private ResourceLoader resourceLoader; |
| 45 | + private final Map<String, AzureKeyVaultJcaProperties.JcaVaultProperties> jcaVaults; |
| 46 | + private final Map<String, AzureKeyVaultSslBundleProperties.KeyVaultSslBundleProperties> sslBundles; |
| 47 | + private static final String[] JCA_SYSTEM_PROPERTY_KEYS = new String[]{ |
| 48 | + "azure.keyvault.uri", |
| 49 | + "azure.keyvault.tenant-id", |
| 50 | + "azure.keyvault.client-id", |
| 51 | + "azure.keyvault.client-secret", |
| 52 | + "azure.keyvault.managed-identity", |
| 53 | + "azure.keyvault.jca.certificates-refresh-interval", |
| 54 | + "azure.keyvault.jca.refresh-certificates-when-have-un-trust-certificate", |
| 55 | + "azure.cert-path.well-known", |
| 56 | + "azure.cert-path.custom" |
| 57 | + }; |
| 58 | + |
| 59 | + public AzureKeyVaultSslBundleRegistrar(AzureKeyVaultJcaProperties azureKeyVaultJcaProperties, |
| 60 | + AzureKeyVaultSslBundleProperties azureKeyVaultSslBundleProperties) { |
| 61 | + this.jcaVaults = azureKeyVaultJcaProperties.getVaults(); |
| 62 | + this.sslBundles = azureKeyVaultSslBundleProperties.getKeyvault(); |
| 63 | + } |
| 64 | + |
| 65 | + @Override |
| 66 | + public void registerBundles(SslBundleRegistry registry) { |
| 67 | + if (!hasKeyVaultJcaOnClasspath()) { |
| 68 | + LOGGER.debug("Skip configuring Key Vault SSL bundles because {}", "'com.azure:azure-security-keyvault-jca' " |
| 69 | + + "doesn't exist in classpath."); |
| 70 | + return; |
| 71 | + } |
| 72 | + |
| 73 | + if (sslBundles.isEmpty()) { |
| 74 | + LOGGER.debug("Skip configuring Key Vault SSL bundles because {}", "'spring.ssl.bundle.azure-keyvault' " |
| 75 | + + "is empty."); |
| 76 | + return; |
| 77 | + } |
| 78 | + |
| 79 | + final AtomicBoolean providerConfigured = new AtomicBoolean(false); |
| 80 | + sslBundles.forEach((bundleName, bundle) -> { |
| 81 | + boolean hasAnyCertConfiguredForTruststore = hasAnyCertConfigured(jcaVaults, bundle.getTruststore()); |
| 82 | + boolean hasAnyCertConfiguredForKeyStore = hasAnyCertConfigured(jcaVaults, bundle.getKeystore()); |
| 83 | + boolean anyCertConfigured = hasAnyCertConfiguredForTruststore || hasAnyCertConfiguredForKeyStore; |
| 84 | + if (!anyCertConfigured) { |
| 85 | + LOGGER.debug("Skip configuring Key Vault SSL bundle '{}'. Consider configuring 'keyvault-ref', " |
| 86 | + + "'certificate-paths.custom' or 'certificate-paths.well-known' properties of the keystore or " |
| 87 | + + "truststore.", bundleName); |
| 88 | + return; |
| 89 | + } |
| 90 | + |
| 91 | + KeyStore keyVaultKeyStore = initilizeKeyVaultKeyStore("keystore", |
| 92 | + bundleName, |
| 93 | + hasAnyCertConfiguredForKeyStore, |
| 94 | + providerConfigured, |
| 95 | + jcaVaults.get(bundle.getKeystore().getKeyvaultRef()), |
| 96 | + bundle.getKeystore()); |
| 97 | + |
| 98 | + KeyStore keyVaultTruststore = initilizeKeyVaultKeyStore("truststore", |
| 99 | + bundleName, |
| 100 | + hasAnyCertConfiguredForTruststore, |
| 101 | + providerConfigured, |
| 102 | + jcaVaults.get(bundle.getTruststore().getKeyvaultRef()), |
| 103 | + bundle.getTruststore()); |
| 104 | + |
| 105 | + SslStoreBundle sslStoreBundle = SslStoreBundle.of(keyVaultKeyStore, null, keyVaultTruststore); |
| 106 | + |
| 107 | + SslBundleKey sslBundleKey = Optional.ofNullable(bundle.getKey()) |
| 108 | + .map(k -> SslBundleKey.of(k.getPassword(), k.getAlias())) |
| 109 | + .orElse(SslBundleKey.NONE); |
| 110 | + |
| 111 | + SslOptions sslOptions = Optional.ofNullable(bundle.getOptions()) |
| 112 | + .map(o -> SslOptions.of(o.getCiphers(), o.getEnabledProtocols())) |
| 113 | + .orElse(SslOptions.NONE); |
| 114 | + |
| 115 | + SslBundle sslBundle = SslBundle.of(sslStoreBundle, sslBundleKey, |
| 116 | + sslOptions, |
| 117 | + bundle.getProtocol(), |
| 118 | + new KeyVaultSslManagerBundle(sslStoreBundle, sslBundleKey, bundle.isForClientAuth())); |
| 119 | + |
| 120 | + registry.registerBundle(bundleName, sslBundle); |
| 121 | + |
| 122 | + LOGGER.debug("Registered Azure Key Vault SSL bundle '{}'.", bundleName); |
| 123 | + }); |
| 124 | + } |
| 125 | + |
| 126 | + private KeyStore initilizeKeyVaultKeyStore(String storeName, |
| 127 | + String bundleName, |
| 128 | + boolean anyCertConfigured, |
| 129 | + AtomicBoolean providerConfigured, |
| 130 | + AzureKeyVaultJcaProperties.JcaVaultProperties jcaVaultProperties, |
| 131 | + AzureKeyVaultSslBundleProperties.KeyStoreProperties keyStoreProperties) { |
| 132 | + if (!anyCertConfigured) { |
| 133 | + LOGGER.debug("The {} parameter of Key Vault SSL bundle '{}' is null.", storeName, bundleName); |
| 134 | + return null; |
| 135 | + } |
| 136 | + |
| 137 | + configureJcaKeyStoreSystemProperties(jcaVaultProperties, keyStoreProperties, resourceLoader); |
| 138 | + if (providerConfigured.compareAndSet(false, true)) { |
| 139 | + Security.removeProvider(KeyVaultJcaProvider.PROVIDER_NAME); |
| 140 | + Security.insertProviderAt(new KeyVaultJcaProvider(), 1); |
| 141 | + } |
| 142 | + KeyStore azureKeyVaultKeyStore; |
| 143 | + try { |
| 144 | + if (hasEmbeddedTomcat()) { |
| 145 | + // DKS (Domain Key Store) type key store can act as a single logical key store and support key stores of various |
| 146 | + // types (JKS - Java Key Store, pkcs12) within a single domain. When configuring the Tomcat SSL context, if the |
| 147 | + // KeyStore is not of type DKS, the final key store will be reinitialized and loaded, see source code from |
| 148 | + // https://github.com/apache/tomcat/blob/cab38e5b9c4f498336f716afd1bf4161adedd71d/java/org/apache/tomcat/util/net/SSLUtilBase.java#L393~L403, |
| 149 | + // which will result in the KeyManager being used not being wrapped by the JSSEKeyManager provided by Tomcat, see source code from |
| 150 | + // https://github.com/apache/tomcat/blob/cab38e5b9c4f498336f716afd1bf4161adedd71d/java/org/apache/tomcat/util/net/SSLUtilBase.java#L424, |
| 151 | + // so JSSEKeyManager#chooseEngineServerAlias does not delegate KeyVaultKeyManager.chooseEngineServerAlias, resulting in a null return value. |
| 152 | + azureKeyVaultKeyStore = KeyStore.getInstance("DKS", KeyVaultJcaProvider.PROVIDER_NAME); |
| 153 | + } else { |
| 154 | + azureKeyVaultKeyStore = KeyStore.getInstance(KeyVaultJcaProvider.PROVIDER_NAME); |
| 155 | + } |
| 156 | + azureKeyVaultKeyStore.load(null); |
| 157 | + } catch (CertificateException | KeyStoreException | IOException | NoSuchAlgorithmException | NoSuchProviderException e) { |
| 158 | + throw new RuntimeException("Failed to load Key Vault " + storeName + " for SSL bundle '" + bundleName + "'", e); |
| 159 | + } |
| 160 | + return azureKeyVaultKeyStore; |
| 161 | + } |
| 162 | + |
| 163 | + private static boolean hasKeyVaultJcaOnClasspath() { |
| 164 | + return ClassUtils.isPresent("com.azure.security.keyvault.jca.KeyVaultJcaProvider", |
| 165 | + AzureKeyVaultSslBundleRegistrar.class.getClassLoader()); |
| 166 | + } |
| 167 | + |
| 168 | + private static boolean hasAnyCertConfigured(Map<String, AzureKeyVaultJcaProperties.JcaVaultProperties> jcaVaults, |
| 169 | + AzureKeyVaultSslBundleProperties.KeyStoreProperties keyStoreProperties) { |
| 170 | + AzureKeyVaultSslBundleProperties.CertificatePathsProperties certificatePaths = keyStoreProperties.getCertificatePaths(); |
| 171 | + String keyvaultRef = keyStoreProperties.getKeyvaultRef(); |
| 172 | + boolean localCertConfigured = StringUtils.hasText(certificatePaths.getWellKnown()) || StringUtils.hasText(certificatePaths.getCustom()); |
| 173 | + boolean keyVaultRefConfigured = StringUtils.hasText(keyvaultRef) && jcaVaults.get(keyvaultRef) != null; |
| 174 | + return localCertConfigured || keyVaultRefConfigured; |
| 175 | + } |
| 176 | + |
| 177 | + private static boolean hasEmbeddedTomcat() { |
| 178 | + try { |
| 179 | + Class.forName("org.apache.tomcat.InstanceManager"); |
| 180 | + return true; |
| 181 | + } catch (ClassNotFoundException ex) { |
| 182 | + return false; |
| 183 | + } |
| 184 | + } |
| 185 | + |
| 186 | + private static void configureJcaKeyStoreSystemProperties(AzureKeyVaultJcaProperties.JcaVaultProperties jcaVaultProperties, |
| 187 | + AzureKeyVaultSslBundleProperties.KeyStoreProperties keyStoreProperties, |
| 188 | + ResourceLoader resourceLoader) { |
| 189 | + PropertyMapper pm = new PropertyMapper(); |
| 190 | + clearJcaSystemProperties(); |
| 191 | + if (jcaVaultProperties != null) { |
| 192 | + pm.from(jcaVaultProperties.getEndpoint()) |
| 193 | + .when(StringUtils::hasText) |
| 194 | + .to(v -> System.setProperty("azure.keyvault.uri", v)); |
| 195 | + pm.from(jcaVaultProperties.getProfile().getTenantId()) |
| 196 | + .when(StringUtils::hasText) |
| 197 | + .to(v -> System.setProperty("azure.keyvault.tenant-id", v)); |
| 198 | + pm.from(jcaVaultProperties.getCredential().getClientId()) |
| 199 | + .when(StringUtils::hasText) |
| 200 | + .to(v -> System.setProperty("azure.keyvault.client-id", v)); |
| 201 | + pm.from(jcaVaultProperties.getCredential().getClientSecret()) |
| 202 | + .when(StringUtils::hasText) |
| 203 | + .to(v -> System.setProperty("azure.keyvault.client-secret", v)); |
| 204 | + pm.from(jcaVaultProperties.getCredential().isManagedIdentityEnabled()) |
| 205 | + .whenTrue() |
| 206 | + // should put the client id to the managed-identity property |
| 207 | + .to(v -> System.setProperty("azure.keyvault.managed-identity", jcaVaultProperties.getCredential().getClientId())); |
| 208 | + } |
| 209 | + |
| 210 | + pm.from(keyStoreProperties.getCertificatesRefreshInterval()) |
| 211 | + .when(Objects::nonNull) |
| 212 | + .to(v -> System.setProperty("azure.keyvault.jca.certificates-refresh-interval", String.valueOf(v.toMillis()))); |
| 213 | + pm.from(keyStoreProperties.isRefreshCertificatesWhenHaveUntrustedCertificate()) |
| 214 | + .to(v -> System.setProperty("azure.keyvault.jca.refresh-certificates-when-have-un-trust-certificate", Boolean.toString(v))); |
| 215 | + |
| 216 | + pm.from(keyStoreProperties.getCertificatePaths().getWellKnown()) |
| 217 | + .to(v -> resolvePath(resourceLoader, v).ifPresent(path -> System.setProperty("azure.cert-path.well-known", path))); |
| 218 | + pm.from(keyStoreProperties.getCertificatePaths().getCustom()) |
| 219 | + .to(v -> resolvePath(resourceLoader, v).ifPresent(path -> System.setProperty("azure.cert-path.custom", path))); |
| 220 | + } |
| 221 | + |
| 222 | + private static void clearJcaSystemProperties() { |
| 223 | + Arrays.stream(JCA_SYSTEM_PROPERTY_KEYS).forEach(System::clearProperty); |
| 224 | + } |
| 225 | + |
| 226 | + private static Optional<String> resolvePath(ResourceLoader resourceLoader, String path) { |
| 227 | + return Optional.ofNullable(path) |
| 228 | + .filter(p -> p.startsWith("classpath:") || p.startsWith("file:")) |
| 229 | + .map(resourceLoader::getResource) |
| 230 | + .map(res -> { |
| 231 | + try { |
| 232 | + return res.getFile().getAbsolutePath(); |
| 233 | + } catch (IOException e) { |
| 234 | + throw new RuntimeException("Failed to load the certificate path '" + path + "'", e); |
| 235 | + } |
| 236 | + }); |
| 237 | + } |
| 238 | + |
| 239 | + @Override |
| 240 | + public void setResourceLoader(ResourceLoader resourceLoader) { |
| 241 | + this.resourceLoader = resourceLoader; |
| 242 | + } |
| 243 | +} |
0 commit comments