Skip to content

Commit

Permalink
End to End TLS SSL step #3 (Azure#16773)
Browse files Browse the repository at this point in the history
* Renamed keyVault to keyVaultClient

* Rename from getKey_props to getKeyProperties

* Changed from access_token to accessToken

Co-authored-by: Rujun Chen <[email protected]>
  • Loading branch information
mnriem and rujche authored Oct 26, 2020
1 parent 853a45f commit ce4db65
Show file tree
Hide file tree
Showing 8 changed files with 63 additions and 61 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ public String getAccessToken(String resource, String tenantId,
if (body != null) {
JsonConverter converter = JsonConverterFactory.createJsonConverter();
OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class);
result = token.getAccess_token();
result = token.getAccessToken();
}
LOGGER.log(FINER, "Access token: {0}", result);
return result;
Expand Down Expand Up @@ -146,7 +146,7 @@ private String getAccessTokenOnAppService(String resource) {
if (body != null) {
JsonConverter converter = JsonConverterFactory.createJsonConverter();
OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class);
result = token.getAccess_token();
result = token.getAccessToken();
}
LOGGER.exiting("AuthClient", "getAccessTokenOnAppService", result);
return result;
Expand Down Expand Up @@ -174,7 +174,7 @@ private String getAccessTokenOnOthers(String resource) {
if (body != null) {
JsonConverter converter = JsonConverterFactory.createJsonConverter();
OAuthToken token = (OAuthToken) converter.fromJson(body, OAuthToken.class);
result = token.getAccess_token();
result = token.getAccessToken();
}
LOGGER.exiting("AuthClient", "getAccessTokenOnOthers", result);
return result;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,9 @@ class KeyVaultClient extends DelegateRestClient {
private static final String API_VERSION_POSTFIX = "?api-version=7.1";

/**
* Stores the Azure Key Vault URI.
* Stores the Azure Key Vault URL.
*/
private final String keyVaultUri;
private final String keyVaultUrl;

/**
* Stores the tenant ID.
Expand Down Expand Up @@ -79,7 +79,7 @@ class KeyVaultClient extends DelegateRestClient {
if (!keyVaultUri.endsWith("/")) {
keyVaultUri = keyVaultUri + "/";
}
this.keyVaultUri = keyVaultUri;
this.keyVaultUrl = keyVaultUri;
}

/**
Expand Down Expand Up @@ -125,11 +125,11 @@ private String getAccessToken() {
*
* @return the list of aliases.
*/
public List<String> getAliases() {
List<String> getAliases() {
ArrayList<String> result = new ArrayList<>();
HashMap<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer " + getAccessToken());
String url = String.format("%scertificates%s", keyVaultUri, API_VERSION_POSTFIX);
String url = String.format("%scertificates%s", keyVaultUrl, API_VERSION_POSTFIX);
String response = get(url, headers);
CertificateListResult certificateListResult = null;
if (response != null) {
Expand All @@ -156,7 +156,7 @@ private CertificateBundle getCertificateBundle(String alias) {
CertificateBundle result = null;
HashMap<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer " + getAccessToken());
String url = String.format("%scertificates/%s%s", keyVaultUri, alias, API_VERSION_POSTFIX);
String url = String.format("%scertificates/%s%s", keyVaultUrl, alias, API_VERSION_POSTFIX);
String response = get(url, headers);
if (response != null) {
JsonConverter converter = JsonConverterFactory.createJsonConverter();
Expand All @@ -171,7 +171,7 @@ private CertificateBundle getCertificateBundle(String alias) {
* @param alias the alias.
* @return the certificate, or null if not found.
*/
public Certificate getCertificate(String alias) {
Certificate getCertificate(String alias) {
LOGGER.entering("KeyVaultClient", "getCertificate", alias);
LOGGER.log(INFO, "Getting certificate for alias: {0}", alias);
X509Certificate certificate = null;
Expand All @@ -182,7 +182,7 @@ public Certificate getCertificate(String alias) {
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) cf.generateCertificate(
new ByteArrayInputStream(Base64.getDecoder().decode(certificateBundle.getCer()))
new ByteArrayInputStream(Base64.getDecoder().decode(certificateString))
);
} catch (CertificateException ce) {
LOGGER.log(WARNING, "Certificate error", ce);
Expand All @@ -200,14 +200,14 @@ public Certificate getCertificate(String alias) {
* @param password the password.
* @return the key.
*/
public Key getKey(String alias, char[] password) {
Key getKey(String alias, char[] password) {
LOGGER.entering("KeyVaultClient", "getKey", new Object[] { alias, password });
LOGGER.log(INFO, "Getting key for alias: {0}", alias);
Key key = null;
CertificateBundle certificateBundle = getCertificateBundle(alias);
boolean isExportable = Optional.ofNullable(certificateBundle)
.map(CertificateBundle::getPolicy)
.map(CertificatePolicy::getKey_props)
.map(CertificatePolicy::getKeyProperties)
.map(KeyProperties::isExportable)
.orElse(false);
if (isExportable) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,8 @@ public X509Certificate[] getCertificateChain(String alias) {
chain.add((X509Certificate) certificate);
}
}
} else {
LOGGER.log(WARNING, "No certificate chain found for alias: {0}", alias);
}
} catch (KeyStoreException kse) {
LOGGER.log(WARNING, "Unable to get certificate chain for alias: " + alias, kse);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.security.keyvault.jca;

import java.io.BufferedReader;
Expand Down Expand Up @@ -64,7 +63,7 @@ public class KeyVaultKeyStore extends KeyStoreSpi {
/**
* Stores the key vault client.
*/
private KeyVaultClient keyVault;
private KeyVaultClient keyVaultClient;

/**
* Constructor.
Expand All @@ -83,13 +82,13 @@ public KeyVaultKeyStore() {
String tenantId = System.getProperty("azure.keyvault.tenantId");
String clientId = System.getProperty("azure.keyvault.clientId");
String clientSecret = System.getProperty("azure.keyvault.clientSecret");
keyVault = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret);
keyVaultClient = new KeyVaultClient(keyVaultUri, tenantId, clientId, clientSecret);
}

@Override
public Enumeration<String> engineAliases() {
if (aliases == null) {
aliases = keyVault.getAliases();
aliases = keyVaultClient.getAliases();
}
return Collections.enumeration(aliases);
}
Expand All @@ -114,7 +113,7 @@ public Certificate engineGetCertificate(String alias) {
if (certificates.containsKey(alias)) {
certificate = certificates.get(alias);
} else {
certificate = keyVault.getCertificate(alias);
certificate = keyVaultClient.getCertificate(alias);
if (certificate != null) {
certificates.put(alias, certificate);
if (!aliases.contains(alias)) {
Expand All @@ -130,7 +129,7 @@ public String engineGetCertificateAlias(Certificate cert) {
String alias = null;
if (cert != null) {
if (aliases == null) {
aliases = keyVault.getAliases();
aliases = keyVaultClient.getAliases();
}
for (String candidateAlias : aliases) {
Certificate certificate = engineGetCertificate(candidateAlias);
Expand Down Expand Up @@ -170,7 +169,7 @@ public Key engineGetKey(String alias, char[] password) {
if (certificateKeys.containsKey(alias)) {
key = certificateKeys.get(alias);
} else {
key = keyVault.getKey(alias, password);
key = keyVaultClient.getKey(alias, password);
if (key != null) {
certificateKeys.put(alias, key);
if (!aliases.contains(alias)) {
Expand All @@ -184,7 +183,7 @@ public Key engineGetKey(String alias, char[] password) {
@Override
public boolean engineIsCertificateEntry(String alias) {
if (aliases == null) {
aliases = keyVault.getAliases();
aliases = keyVaultClient.getAliases();
}
return aliases.contains(alias);
}
Expand All @@ -198,11 +197,11 @@ public boolean engineIsKeyEntry(String alias) {
public void engineLoad(KeyStore.LoadStoreParameter param) {
if (param instanceof KeyVaultLoadStoreParameter) {
KeyVaultLoadStoreParameter parameter = (KeyVaultLoadStoreParameter) param;
keyVault = new KeyVaultClient(
parameter.getUri(),
parameter.getTenantId(),
parameter.getClientId(),
parameter.getClientSecret());
keyVaultClient = new KeyVaultClient(
parameter.getUri(),
parameter.getTenantId(),
parameter.getClientId(),
parameter.getClientSecret());
}
sideLoad();
}
Expand All @@ -215,7 +214,7 @@ public void engineLoad(InputStream stream, char[] password) {
@Override
public void engineSetCertificateEntry(String alias, Certificate certificate) {
if (aliases == null) {
aliases = keyVault.getAliases();
aliases = keyVaultClient.getAliases();
}
if (!aliases.contains(alias)) {
aliases.add(alias);
Expand Down Expand Up @@ -258,12 +257,14 @@ public void engineStore(KeyStore.LoadStoreParameter param) {
*/
private String[] getFilenames(String path) throws IOException {
List<String> filenames = new ArrayList<>();
InputStream in = getClass().getResourceAsStream(path);
if (in != null) {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String resource;
while ((resource = br.readLine()) != null) {
filenames.add(resource);
try (InputStream in = getClass().getResourceAsStream(path)) {
if (in != null) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(in))) {
String resource;
while ((resource = br.readLine()) != null) {
filenames.add(resource);
}
}
}
}
return filenames.toArray(new String[0]);
Expand All @@ -277,16 +278,19 @@ private String[] getFilenames(String path) throws IOException {
* @throws IOException when an I/O error occurs.
*/
private byte[] readAllBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
while (true) {
int r = inputStream.read(buffer);
if (r == -1) {
break;
byte[] bytes;
try (ByteArrayOutputStream byteOutput = new ByteArrayOutputStream()) {
byte[] buffer = new byte[1024];
while (true) {
int r = inputStream.read(buffer);
if (r == -1) {
break;
}
byteOutput.write(buffer, 0, r);
}
byteOutput.write(buffer, 0, r);
bytes = byteOutput.toByteArray();
}
return byteOutput.toByteArray();
return bytes;
}

/**
Expand All @@ -307,12 +311,12 @@ private void sideLoad() {
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate) cf.generateCertificate(
new ByteArrayInputStream(bytes));
new ByteArrayInputStream(bytes));
engineSetCertificateEntry(alias, certificate);
LOGGER.log(INFO, "Side loaded certificate: {0} from: {1}",
new Object[] { alias, filename });
new Object[]{alias, filename});
} catch (CertificateException e) {
LOGGER.log(WARNING, "Unable to side-load certificate", e);
LOGGER.log(WARNING, "Unable to side-load certificate from: " + filename, e);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
/**
* The Azure Key Vault variant of the X509TrustManager.
*/
public class KeyVaultTrustManager extends X509ExtendedTrustManager implements X509TrustManager {
public class KeyVaultTrustManager extends X509ExtendedTrustManager {

/**
* Stores the default trust manager.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

package com.azure.security.keyvault.jca.rest;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;

/**
Expand All @@ -13,14 +14,15 @@ public class CertificatePolicy implements Serializable {
/**
* Stores the key properties.
*/
@JsonProperty("key_props")
private KeyProperties keyProperties;

/**
* Get the key properties.
*
* @return the key properties.
*/
public KeyProperties getKey_props() {
public KeyProperties getKeyProperties() {
return keyProperties;
}

Expand All @@ -29,7 +31,7 @@ public KeyProperties getKey_props() {
*
* @param keyProperties the key properties.
*/
public void setKey_props(KeyProperties keyProperties) {
public void setKeyProperties(KeyProperties keyProperties) {
this.keyProperties = keyProperties;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT License.
package com.azure.security.keyvault.jca.rest;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;

/**
Expand All @@ -12,23 +13,24 @@ public class OAuthToken implements Serializable {
/**
* Stores the access token.
*/
private String access_token;
@JsonProperty("access_token")
private String accessToken;

/**
* Get the access token.
*
* @return the access token.
*/
public String getAccess_token() {
return access_token;
public String getAccessToken() {
return accessToken;
}

/**
* Set the access token.
*
* @param accessToken the access token.
*/
public void setAccess_token(String accessToken) {
this.access_token = accessToken;
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

import java.security.Security;
import java.util.Properties;
import java.util.logging.Logger;
import javax.net.ssl.HttpsURLConnection;

import org.springframework.boot.SpringApplication;
Expand All @@ -22,11 +21,6 @@
@Order(LOWEST_PRECEDENCE)
public class KeyVaultCertificatesEnvironmentPostProcessor implements EnvironmentPostProcessor {

/**
* Stores the logger.
*/
private static final Logger LOGGER = Logger.getLogger(KeyVaultCertificatesEnvironmentPostProcessor.class.getName());

@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
SpringApplication application) {
Expand Down Expand Up @@ -100,9 +94,7 @@ public void postProcessEnvironment(ConfigurableEnvironment environment,

enabled = environment.getProperty("azure.keyvault.jca.disableHostnameVerification");
if (Boolean.parseBoolean(enabled)) {
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> {
return true;
});
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
}
}
}
Expand Down

0 comments on commit ce4db65

Please sign in to comment.