in core/src/main/java/com/google/cloud/sql/core/DefaultConnectionInfoRepository.java [450:502]
private SslData createSslData(
KeyPair keyPair,
InstanceMetadata instanceMetadata,
Certificate ephemeralCertificate,
CloudSqlInstanceName instanceName,
AuthType authType) {
try {
KeyStore authKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
authKeyStore.load(null, null);
KeyStore.PrivateKeyEntry privateKey =
new PrivateKeyEntry(keyPair.getPrivate(), new Certificate[] {ephemeralCertificate});
authKeyStore.setEntry("ephemeral", privateKey, new PasswordProtection(new char[0]));
KeyManagerFactory kmf =
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(authKeyStore, new char[0]);
// The InstanceCheckingTrustManagerFactory implements the custom certificate validation
// logic. After using the standard TLS CA chain of trust, it will implement a custom
// hostname verification to gracefully handle the hostnames in Cloud SQL server certificates.
TrustManagerFactory tmf = InstanceCheckingTrustManagerFactory.newInstance(instanceMetadata);
SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("TLSv1.3");
} catch (NoSuchAlgorithmException ex) {
if (authType == AuthType.IAM) {
throw new RuntimeException(
String.format(
"[%s] Unable to create a SSLContext for the Cloud SQL instance.",
instanceName.getConnectionName())
+ " TLSv1.3 is not supported for your Java version and is required to connect"
+ " using IAM authentication",
ex);
} else {
logger.debug("TLSv1.3 is not supported for your Java version, fallback to TLSv1.2");
sslContext = SSLContext.getInstance("TLSv1.2");
}
}
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
logger.debug(
String.format("[%s %d] SSL CONTEXT", instanceName, Thread.currentThread().getId()));
return new SslData(sslContext, kmf, tmf);
} catch (GeneralSecurityException | IOException ex) {
throw new RuntimeException(
String.format(
"[%s] Unable to create a SSLContext for the Cloud SQL instance.",
instanceName.getConnectionName()),
ex);
}
}