-
Notifications
You must be signed in to change notification settings - Fork 624
Expand file tree
/
Copy pathClickHouseDefaultSslContextProvider.java
More file actions
225 lines (198 loc) · 9.98 KB
/
ClickHouseDefaultSslContextProvider.java
File metadata and controls
225 lines (198 loc) · 9.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package com.clickhouse.client.config;
import com.clickhouse.client.ClickHouseConfig;
import com.clickhouse.client.ClickHouseSslContextProvider;
import com.clickhouse.data.ClickHouseUtils;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.Optional;
@Deprecated
public class ClickHouseDefaultSslContextProvider implements ClickHouseSslContextProvider {
static final String PEM_HEADER_PREFIX = "---BEGIN ";
static final String PEM_HEADER_SUFFIX = " PRIVATE KEY---";
static final String PEM_FOOTER_PREFIX = "---END ";
/** Standard PEM encapsulation boundary (RFC 7468). Present in any PEM content, never in a file path. */
static final String PEM_BEGIN_MARKER = "-----BEGIN";
/**
* Opens a stream over PEM material that may be supplied either as a file path (also searched in the home
* directory and on the classpath) or directly as PEM content.
*
* @param certOrContent file path or PEM content of a certificate or a private key
* @return stream over the PEM content
* @throws IOException when the value is a path and the file cannot be opened
*/
static InputStream getCertificateInputStream(String certOrContent) throws IOException {
if (certOrContent.contains(PEM_BEGIN_MARKER)) {
return new ByteArrayInputStream(certOrContent.getBytes(StandardCharsets.US_ASCII));
}
return ClickHouseUtils.getFileInputStream(certOrContent);
}
/**
* An insecure {@link javax.net.ssl.TrustManager}, that don't validate the
* certificate.
*/
static class NonValidatingTrustManager implements X509TrustManager {
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
@Override
@SuppressWarnings("squid:S4830")
public void checkClientTrusted(X509Certificate[] certs, String authType) {
// ignore
}
@Override
@SuppressWarnings("squid:S4830")
public void checkServerTrusted(X509Certificate[] certs, String authType) {
// ignore
}
}
static String getAlgorithm(String header, String defaultAlg) {
int startIndex = header.indexOf(PEM_HEADER_PREFIX);
int endIndex = startIndex < 0 ? startIndex
: header.indexOf(PEM_HEADER_SUFFIX, (startIndex += PEM_HEADER_PREFIX.length()));
return startIndex < endIndex ? header.substring(startIndex, endIndex) : defaultAlg;
}
public static PrivateKey getPrivateKey(String keyFile)
throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
String algorithm = (String) ClickHouseDefaults.SSL_KEY_ALGORITHM.getEffectiveDefaultValue();
StringBuilder builder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(getCertificateInputStream(keyFile)))) {
String line = reader.readLine();
if (line != null) {
algorithm = getAlgorithm(line, algorithm);
while ((line = reader.readLine()) != null) {
if (line.indexOf(PEM_FOOTER_PREFIX) >= 0) {
break;
}
builder.append(line);
}
}
}
byte[] encoded = Base64.getDecoder().decode(builder.toString());
KeyFactory kf = KeyFactory.getInstance(algorithm);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
return kf.generatePrivate(keySpec);
}
public KeyStore getKeyStore(String cert, String key) throws NoSuchAlgorithmException, InvalidKeySpecException,
IOException, CertificateException, KeyStoreException {
final KeyStore ks;
try {
ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null, null); // needed to initialize the key store
} catch (KeyStoreException e) {
throw new NoSuchAlgorithmException(
ClickHouseUtils.format("%s KeyStore not available", KeyStore.getDefaultType()));
}
try (InputStream in = getCertificateInputStream(cert)) {
CertificateFactory factory = CertificateFactory
.getInstance((String) ClickHouseDefaults.SSL_CERTIFICATE_TYPE.getEffectiveDefaultValue());
if (key == null || key.isEmpty()) {
int index = 1;
for (Certificate c : factory.generateCertificates(in)) {
ks.setCertificateEntry("cert" + (index++), c);
}
} else {
Certificate[] certChain = factory.generateCertificates(in).toArray(new Certificate[0]);
ks.setKeyEntry("key", getPrivateKey(key), null, certChain);
}
}
return ks;
}
public SSLContext getJavaSslContext(ClickHouseConfig config) throws SSLException {
ClickHouseSslMode sslMode = config.getSslMode();
String clientCert = config.getSslCert();
String clientKey = config.getSslKey();
String sslRootCert = config.getSslRootCert();
String truststorePath = config.getTrustStore();
String truststorePassword = config.getTrustStorePassword();
String keyStoreType = (!config.getKeyStoreType().isEmpty() && config.getKeyStoreType() != null) ? config.getKeyStoreType() : KeyStore.getDefaultType();
return getSslContextImpl(sslMode, clientCert, clientKey, sslRootCert, truststorePath, truststorePassword,
keyStoreType);
}
public SSLContext getSslContextFromCerts(String clientCert, String clientKey, String sslRootCert) throws SSLException {
return getSslContextImpl(ClickHouseSslMode.STRICT,
clientCert, clientKey, sslRootCert, null, null, KeyStore.getDefaultType());
}
public SSLContext getSslContextFromKeyStore(String truststorePath, String truststorePassword, String keyStoreType) throws SSLException {
return getSslContextImpl(ClickHouseSslMode.STRICT, null, null, null, truststorePath, truststorePassword, keyStoreType);
}
private SSLContext getSslContextImpl(ClickHouseSslMode sslMode, String clientCert, String clientKey, String sslRootCert, String truststorePath, String truststorePassword, String keyStoreType) throws SSLException {
SSLContext ctx;
try {
ctx = SSLContext.getInstance((String) ClickHouseDefaults.SSL_PROTOCOL.getEffectiveDefaultValue());
TrustManager[] tms = null;
KeyManager[] kms = null;
SecureRandom sr = null;
if (sslMode == ClickHouseSslMode.NONE) {
tms = new TrustManager[]{new NonValidatingTrustManager()};
kms = new KeyManager[0];
sr = new SecureRandom();
} else if (sslMode == ClickHouseSslMode.STRICT) {
if (truststorePath != null && !truststorePath.isEmpty()) {
try (InputStream in = ClickHouseUtils.getFileInputStream(truststorePath)) {
KeyStore myTrustStore = KeyStore.getInstance(keyStoreType);
myTrustStore.load(in, truststorePassword.toCharArray());
TrustManagerFactory factory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(myTrustStore);
tms = factory.getTrustManagers();
}
} else {
if (clientCert != null && !clientCert.isEmpty()) {
KeyManagerFactory factory = KeyManagerFactory
.getInstance(KeyManagerFactory.getDefaultAlgorithm());
factory.init(getKeyStore(clientCert, clientKey), null);
kms = factory.getKeyManagers();
}
if (sslRootCert != null && !sslRootCert.isEmpty()) {
TrustManagerFactory factory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(getKeyStore(sslRootCert, null));
tms = factory.getTrustManagers();
}
}
sr = new SecureRandom();
} else {
throw new IllegalArgumentException(ClickHouseUtils.format("unspported ssl mode '%s'", sslMode));
}
ctx.init(kms, tms, sr);
} catch (KeyManagementException | InvalidKeySpecException | NoSuchAlgorithmException | KeyStoreException
| CertificateException | IOException | UnrecoverableKeyException e) {
throw new SSLException("Failed to get SSL context", e);
}
return ctx;
}
@SuppressWarnings("unchecked")
@Override
public <T> Optional<T> getSslContext(Class<? extends T> sslContextClass, ClickHouseConfig config)
throws SSLException {
return SSLContext.class == sslContextClass ? Optional.of((T) getJavaSslContext(config)) : Optional.empty();
}
}