Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ISSUE#3315]Nacos client support https #3654

Merged
merged 5 commits into from
Aug 24, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@
package com.alibaba.nacos.client.config.impl;

import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.client.identify.Base64;
import com.alibaba.nacos.client.identify.CredentialService;
import com.alibaba.nacos.common.codec.Base64;
import com.alibaba.nacos.common.utils.StringUtils;

import javax.crypto.Mac;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
package com.alibaba.nacos.client.config.utils;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.utils.IpUtil;
import com.alibaba.nacos.common.utils.IpUtils;
import com.alibaba.nacos.common.utils.StringUtils;

import java.util.List;
Expand Down Expand Up @@ -190,7 +190,7 @@ public static void checkBetaIps(String betaIps) throws NacosException {
}
String[] ipsArr = betaIps.split(",");
for (String ip : ipsArr) {
if (!IpUtil.isIpv4(ip)) {
if (!IpUtils.isIpv4(ip)) {
throw new NacosException(NacosException.CLIENT_INVALID_PARAM, "betaIps invalid");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

package com.alibaba.nacos.client.naming.utils;

import com.alibaba.nacos.client.identify.Base64;
import com.alibaba.nacos.common.codec.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* limitations under the License.
*/

package com.alibaba.nacos.client.identify;
package com.alibaba.nacos.common.codec;

import java.nio.charset.Charset;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,22 @@
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
import com.alibaba.nacos.common.http.client.request.DefaultAsyncHttpClientRequest;
import com.alibaba.nacos.common.http.client.request.JdkHttpClientRequest;
import com.alibaba.nacos.common.tls.SelfHostnameVerifier;
import com.alibaba.nacos.common.tls.TlsFileWatcher;
import com.alibaba.nacos.common.tls.TlsHelper;
import com.alibaba.nacos.common.tls.TlsSystemConfig;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.slf4j.Logger;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

/**
* AbstractHttpClientFactory Let the creator only specify the http client config.
*
Expand All @@ -34,7 +46,28 @@ public abstract class AbstractHttpClientFactory implements HttpClientFactory {
@Override
public final NacosRestTemplate createNacosRestTemplate() {
HttpClientConfig httpClientConfig = buildHttpClientConfig();
return new NacosRestTemplate(assignLogger(), new JdkHttpClientRequest(httpClientConfig));
final JdkHttpClientRequest clientRequest = new JdkHttpClientRequest(httpClientConfig);

if (TlsSystemConfig.tlsEnable) {
// enable ssl
clientRequest.setSSLContext(loadSSLContext());
final HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
final SelfHostnameVerifier selfHostnameVerifier = new SelfHostnameVerifier(hv);
clientRequest.replaceSSLHostnameVerifier(selfHostnameVerifier);

try {
TlsFileWatcher.getInstance().addFileChangeListener(new TlsFileWatcher.FileChangeListener() {
@Override
public void onChanged(String filePath) {
clientRequest.setSSLContext(loadSSLContext());
}
}, TlsSystemConfig.tlsClientTrustCertPath, TlsSystemConfig.tlsClientKeyPath);
} catch (IOException e) {
assignLogger().error("add tls file listener fail", e);
}
}

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里的逻辑是不是可以独立为一个函数,看起来相对简洁点。

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

是指tlsFileWatcher这一段吗?addSSLContextChangeListener(FileChangeListener Listener)?
独立成一个函数,这样至少对使用AbstractHttpClientFactory.java 类的开发者来说屏蔽一些tlsClientTrustCertPath这样的细节。是好点,我改下。

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

从51行开始到68行,感觉这里可以独立为一个函数。

return new NacosRestTemplate(assignLogger(), clientRequest);
}

@Override
Expand All @@ -51,6 +84,23 @@ private RequestConfig getRequestConfig() {
.setMaxRedirects(httpClientConfig.getMaxRedirects()).build();
}

@SuppressWarnings("checkstyle:abbreviationaswordinname")
protected synchronized SSLContext loadSSLContext() {
if (!TlsSystemConfig.tlsEnable) {
return null;
}
try {
return TlsHelper.buildSslContext(true);
} catch (NoSuchAlgorithmException e) {
assignLogger().error("Failed to create SSLContext", e);
} catch (KeyManagementException e) {
assignLogger().error("Failed to create SSLContext", e);
} catch (SSLException e) {
assignLogger().error("Failed to create SSLContext", e);
}
return null;
}

/**
* build http client config.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@
import com.alibaba.nacos.common.model.RequestHttpEntity;
import com.alibaba.nacos.common.utils.JacksonUtils;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
Expand All @@ -45,6 +48,30 @@ public JdkHttpClientRequest(HttpClientConfig httpClientConfig) {
this.httpClientConfig = httpClientConfig;
}

/**
* Use specified {@link SSLContext}.
*
* @param sslContext ssl context
*/
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public void setSSLContext(SSLContext sslContext) {
if (sslContext != null) {
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
}
}

/**
* Replace the default HostnameVerifier.
*
* @param hostnameVerifier custom hostnameVerifier
*/
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public void replaceSSLHostnameVerifier(HostnameVerifier hostnameVerifier) {
if (hostnameVerifier != null) {
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
}
}

@Override
public HttpClientResponse execute(URI uri, String httpMethod, RequestHttpEntity requestHttpEntity)
throws Exception {
Expand Down
70 changes: 70 additions & 0 deletions common/src/main/java/com/alibaba/nacos/common/tls/PemReader.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.alibaba.nacos.common.tls;

import com.alibaba.nacos.common.codec.Base64;
import com.alibaba.nacos.common.utils.IoUtils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* Reads a PEM file and converts it into a list of DERs. Support PKCS #8 format
*
* @author wangwei
* @date 2020/8/20 9:32 AM
*/
final class PemReader {

/**
* Header + Base64 text + Footer.
*/
private static final Pattern KEY_PATTERN = Pattern.compile(
"-+BEGIN\\s+.*PRIVATE\\s+KEY[^-]*-+(?:\\s|\\r|\\n)+" + "([a-z0-9+/=\\r\\n]+)"
+ "-+END\\s+.*PRIVATE\\s+KEY[^-]*-+", Pattern.CASE_INSENSITIVE);

private static final String ENCODE_US_ASCII = "US-ASCII";

static byte[] readPrivateKey(String keyPath) throws KeyException {
try {
InputStream in = new FileInputStream(keyPath);
try {
String content;
try {
content = IoUtils.toString(in, ENCODE_US_ASCII);
} catch (IOException e) {
throw new KeyException("failed to read key input stream", e);
}

Matcher m = KEY_PATTERN.matcher(content);
if (!m.find()) {
throw new KeyException("could not find a PKCS #8 private key in input stream");
}
return Base64.decodeBase64(m.group(1).getBytes());
} finally {
IoUtils.closeQuietly(in);
}
} catch (FileNotFoundException e) {
throw new KeyException("could not fine key file: " + keyPath);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.alibaba.nacos.common.tls;

import com.alibaba.nacos.common.utils.IpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import java.util.concurrent.ConcurrentHashMap;

/**
* A HostnameVerifier verify ipv4 and localhost.
*
* @author wangwei
*/

public final class SelfHostnameVerifier implements HostnameVerifier {

private static final Logger LOGGER = LoggerFactory.getLogger(SelfHostnameVerifier.class);

private final HostnameVerifier hv;

private static ConcurrentHashMap<String, Boolean> hosts = new ConcurrentHashMap<String, Boolean>();

private static final String[] LOCALHOST_HOSTNAME = new String[] {"localhost", "127.0.0.1"};

public SelfHostnameVerifier(HostnameVerifier hv) {
this.hv = hv;
}

@Override
public boolean verify(String hostname, SSLSession session) {
if (LOCALHOST_HOSTNAME[0].equalsIgnoreCase(hostname) || LOCALHOST_HOSTNAME[1].equals(hostname)) {
return true;
}
if (isIpv4(hostname)) {
return true;
}
return hv.verify(hostname, session);
}

private static boolean isIpv4(String host) {
if (host == null || host.isEmpty()) {
LOGGER.warn("host is empty, isIPv4 = false");
return false;
}
Boolean cacheHostVerify = hosts.get(host);
if (cacheHostVerify != null) {
return cacheHostVerify;
}
boolean isIp = IpUtils.isIpv4(host);
hosts.putIfAbsent(host, isIp);
return isIp;
}
}
Loading