-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
SecurityUtility.java
569 lines (508 loc) · 25.8 KB
/
SecurityUtility.java
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.pulsar.common.util;
import io.netty.handler.ssl.ClientAuth;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
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.Provider;
import java.security.SecureRandom;
import java.security.Security;
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.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import javax.net.ssl.HostnameVerifier;
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 lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.pulsar.common.classification.InterfaceAudience;
import org.apache.pulsar.common.classification.InterfaceStability;
import org.apache.pulsar.common.tls.TlsHostnameVerifier;
import org.eclipse.jetty.util.ssl.SslContextFactory;
/**
* Helper class for the security domain.
*/
@Slf4j
public class SecurityUtility {
public static final Provider BC_PROVIDER = getProvider();
public static final String BC_FIPS_PROVIDER_CLASS = "org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider";
public static final String BC_NON_FIPS_PROVIDER_CLASS = "org.bouncycastle.jce.provider.BouncyCastleProvider";
public static final String CONSCRYPT_PROVIDER_CLASS = "org.conscrypt.OpenSSLProvider";
public static final Provider CONSCRYPT_PROVIDER = loadConscryptProvider();
// Security.getProvider("BC") / Security.getProvider("BCFIPS").
// also used to get Factories. e.g. CertificateFactory.getInstance("X.509", "BCFIPS")
public static final String BC_FIPS = "BCFIPS";
public static final String BC = "BC";
public static boolean isBCFIPS() {
return BC_PROVIDER.getClass().getCanonicalName().equals(BC_FIPS_PROVIDER_CLASS);
}
/**
* Get Bouncy Castle provider, and call Security.addProvider(provider) if success.
* 1. try get from classpath.
* 2. try get from Nar.
*/
public static Provider getProvider() {
boolean isProviderInstalled =
Security.getProvider(BC) != null || Security.getProvider(BC_FIPS) != null;
if (isProviderInstalled) {
Provider provider = Security.getProvider(BC) != null
? Security.getProvider(BC)
: Security.getProvider(BC_FIPS);
if (log.isDebugEnabled()) {
log.debug("Already instantiated Bouncy Castle provider {}", provider.getName());
}
return provider;
}
// Not installed, try load from class path
try {
return getBCProviderFromClassPath();
} catch (Exception e) {
log.warn("Not able to get Bouncy Castle provider for both FIPS and Non-FIPS from class path:", e);
throw new RuntimeException(e);
}
}
private static Provider loadConscryptProvider() {
Class<?> conscryptClazz;
try {
conscryptClazz = Class.forName("org.conscrypt.Conscrypt");
conscryptClazz.getMethod("checkAvailability").invoke(null);
} catch (Throwable e) {
log.warn("Conscrypt isn't available. Using JDK default security provider.", e);
return null;
}
Provider provider;
try {
provider = (Provider) Class.forName(CONSCRYPT_PROVIDER_CLASS).newInstance();
} catch (ReflectiveOperationException e) {
log.warn("Unable to get security provider for class {}", CONSCRYPT_PROVIDER_CLASS, e);
return null;
}
// Configure Conscrypt's default hostname verifier to use Pulsar's TlsHostnameVerifier which
// is more relaxed than the Conscrypt HostnameVerifier checking for RFC 2818 conformity.
//
// Certificates used in Pulsar docs and examples aren't strictly RFC 2818 compliant since they use the
// deprecated way of specifying the hostname in the CN field of the subject DN of the certificate.
// RFC 2818 recommends the use of SAN (subjectAltName) extension for specifying the hostname in the dNSName
// field of the subjectAltName extension.
//
// Conscrypt's default HostnameVerifier has dropped support for the deprecated method of specifying the hostname
// in the CN field. Pulsar's TlsHostnameVerifier continues to support the CN field.
//
// more details of Conscrypt's hostname verification:
// https://github.com/google/conscrypt/blob/master/IMPLEMENTATION_NOTES.md#hostname-verification
// there's a bug in Conscrypt while setting a custom HostnameVerifier,
// https://github.com/google/conscrypt/issues/1015 and therefore this solution alone
// isn't sufficient to configure Conscrypt's hostname verifier. The method processConscryptTrustManager
// contains the workaround.
try {
HostnameVerifier hostnameVerifier = new TlsHostnameVerifier();
Object wrappedHostnameVerifier = conscryptClazz
.getMethod("wrapHostnameVerifier",
new Class[]{HostnameVerifier.class}).invoke(null, hostnameVerifier);
Method setDefaultHostnameVerifierMethod =
conscryptClazz
.getMethod("setDefaultHostnameVerifier",
new Class[]{Class.forName("org.conscrypt.ConscryptHostnameVerifier")});
setDefaultHostnameVerifierMethod.invoke(null, wrappedHostnameVerifier);
} catch (Exception e) {
log.warn("Unable to set default hostname verifier for Conscrypt", e);
}
Security.addProvider(provider);
if (log.isDebugEnabled()) {
log.debug("Added security provider '{}' from class {}", provider.getName(), CONSCRYPT_PROVIDER_CLASS);
}
return provider;
}
/**
* Get Bouncy Castle provider from classpath, and call Security.addProvider.
* Throw Exception if failed.
*/
public static Provider getBCProviderFromClassPath() throws Exception {
Class clazz;
try {
// prefer non FIPS, for backward compatibility concern.
clazz = Class.forName(BC_NON_FIPS_PROVIDER_CLASS);
} catch (ClassNotFoundException cnf) {
log.warn("Not able to get Bouncy Castle provider: {}, try to get FIPS provider {}",
BC_NON_FIPS_PROVIDER_CLASS, BC_FIPS_PROVIDER_CLASS);
// attempt to use the FIPS provider.
clazz = Class.forName(BC_FIPS_PROVIDER_CLASS);
}
Provider provider = (Provider) clazz.newInstance();
Security.addProvider(provider);
if (log.isDebugEnabled()) {
log.debug("Found and Instantiated Bouncy Castle provider in classpath {}", provider.getName());
}
return provider;
}
public static SSLContext createSslContext(boolean allowInsecureConnection, Certificate[] trustCertificates)
throws GeneralSecurityException {
return createSslContext(allowInsecureConnection, trustCertificates, (Certificate[]) null, (PrivateKey) null);
}
public static SslContext createNettySslContextForClient(boolean allowInsecureConnection, String trustCertsFilePath)
throws GeneralSecurityException, SSLException, FileNotFoundException, IOException {
return createNettySslContextForClient(allowInsecureConnection, trustCertsFilePath, (Certificate[]) null,
(PrivateKey) null);
}
public static SSLContext createSslContext(boolean allowInsecureConnection, String trustCertsFilePath,
String certFilePath, String keyFilePath) throws GeneralSecurityException {
X509Certificate[] trustCertificates = loadCertificatesFromPemFile(trustCertsFilePath);
X509Certificate[] certificates = loadCertificatesFromPemFile(certFilePath);
PrivateKey privateKey = loadPrivateKeyFromPemFile(keyFilePath);
return createSslContext(allowInsecureConnection, trustCertificates, certificates, privateKey);
}
/**
* Creates {@link SslContext} with capability to do auto-cert refresh.
* @param allowInsecureConnection
* @param trustCertsFilePath
* @param certFilePath
* @param keyFilePath
* @param sslContextAlgorithm
* @param refreshDurationSec
* @param executor
* @return
* @throws GeneralSecurityException
* @throws SSLException
* @throws FileNotFoundException
* @throws IOException
*/
public static SslContext createAutoRefreshSslContextForClient(boolean allowInsecureConnection,
String trustCertsFilePath, String certFilePath, String keyFilePath, String sslContextAlgorithm,
int refreshDurationSec, ScheduledExecutorService executor)
throws GeneralSecurityException, SSLException, FileNotFoundException, IOException {
KeyManagerProxy keyManager = new KeyManagerProxy(certFilePath, keyFilePath, refreshDurationSec, executor);
SslContextBuilder sslContexBuilder = SslContextBuilder.forClient();
sslContexBuilder.keyManager(keyManager);
if (allowInsecureConnection) {
sslContexBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
} else {
TrustManagerProxy trustManager = new TrustManagerProxy(trustCertsFilePath, refreshDurationSec, executor);
sslContexBuilder.trustManager(trustManager);
}
return sslContexBuilder.build();
}
public static SslContext createNettySslContextForClient(boolean allowInsecureConnection, String trustCertsFilePath,
String certFilePath, String keyFilePath)
throws GeneralSecurityException, SSLException, FileNotFoundException, IOException {
X509Certificate[] certificates = loadCertificatesFromPemFile(certFilePath);
PrivateKey privateKey = loadPrivateKeyFromPemFile(keyFilePath);
return createNettySslContextForClient(allowInsecureConnection, trustCertsFilePath, certificates, privateKey);
}
public static SslContext createNettySslContextForClient(boolean allowInsecureConnection, String trustCertsFilePath,
Certificate[] certificates, PrivateKey privateKey)
throws GeneralSecurityException, SSLException, FileNotFoundException, IOException {
if (StringUtils.isNotBlank(trustCertsFilePath)) {
try (FileInputStream trustCertsStream = new FileInputStream(trustCertsFilePath)) {
return createNettySslContextForClient(allowInsecureConnection, trustCertsStream, certificates,
privateKey);
}
} else {
return createNettySslContextForClient(allowInsecureConnection, (InputStream) null, certificates,
privateKey);
}
}
public static SslContext createNettySslContextForClient(boolean allowInsecureConnection,
InputStream trustCertsStream, Certificate[] certificates, PrivateKey privateKey)
throws GeneralSecurityException, SSLException, FileNotFoundException, IOException {
SslContextBuilder builder = SslContextBuilder.forClient();
setupTrustCerts(builder, allowInsecureConnection, trustCertsStream);
setupKeyManager(builder, privateKey, (X509Certificate[]) certificates);
return builder.build();
}
public static SslContext createNettySslContextForServer(boolean allowInsecureConnection, String trustCertsFilePath,
String certFilePath, String keyFilePath, Set<String> ciphers, Set<String> protocols,
boolean requireTrustedClientCertOnConnect)
throws GeneralSecurityException, SSLException, FileNotFoundException, IOException {
X509Certificate[] certificates = loadCertificatesFromPemFile(certFilePath);
PrivateKey privateKey = loadPrivateKeyFromPemFile(keyFilePath);
SslContextBuilder builder = SslContextBuilder.forServer(privateKey, (X509Certificate[]) certificates);
setupCiphers(builder, ciphers);
setupProtocols(builder, protocols);
if (StringUtils.isNotBlank(trustCertsFilePath)) {
try (FileInputStream trustCertsStream = new FileInputStream(trustCertsFilePath)) {
setupTrustCerts(builder, allowInsecureConnection, trustCertsStream);
}
} else {
setupTrustCerts(builder, allowInsecureConnection, null);
}
setupKeyManager(builder, privateKey, certificates);
setupClientAuthentication(builder, requireTrustedClientCertOnConnect);
return builder.build();
}
public static SSLContext createSslContext(boolean allowInsecureConnection, Certificate[] trustCertficates,
Certificate[] certificates, PrivateKey privateKey) throws GeneralSecurityException {
KeyStoreHolder ksh = new KeyStoreHolder();
TrustManager[] trustManagers = null;
KeyManager[] keyManagers = null;
trustManagers = setupTrustCerts(ksh, allowInsecureConnection, trustCertficates, CONSCRYPT_PROVIDER);
keyManagers = setupKeyManager(ksh, privateKey, certificates);
SSLContext sslCtx = CONSCRYPT_PROVIDER != null ? SSLContext.getInstance("TLS", CONSCRYPT_PROVIDER)
: SSLContext.getInstance("TLS");
sslCtx.init(keyManagers, trustManagers, new SecureRandom());
sslCtx.getDefaultSSLParameters();
return sslCtx;
}
private static KeyManager[] setupKeyManager(KeyStoreHolder ksh, PrivateKey privateKey, Certificate[] certificates)
throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
KeyManager[] keyManagers = null;
if (certificates != null && privateKey != null) {
ksh.setPrivateKey("private", privateKey, certificates);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ksh.getKeyStore(), "".toCharArray());
keyManagers = kmf.getKeyManagers();
}
return keyManagers;
}
private static TrustManager[] setupTrustCerts(KeyStoreHolder ksh, boolean allowInsecureConnection,
Certificate[] trustCertficates, Provider securityProvider)
throws NoSuchAlgorithmException, KeyStoreException {
TrustManager[] trustManagers;
if (allowInsecureConnection) {
trustManagers = InsecureTrustManagerFactory.INSTANCE.getTrustManagers();
} else {
TrustManagerFactory tmf = securityProvider != null
? TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm(), securityProvider)
: TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
if (trustCertficates == null || trustCertficates.length == 0) {
tmf.init((KeyStore) null);
} else {
for (int i = 0; i < trustCertficates.length; i++) {
ksh.setCertificate("trust" + i, trustCertficates[i]);
}
tmf.init(ksh.getKeyStore());
}
trustManagers = tmf.getTrustManagers();
for (TrustManager trustManager : trustManagers) {
processConscryptTrustManager(trustManager);
}
}
return trustManagers;
}
/***
* Conscrypt TrustManager instances will be configured to use the Pulsar {@link TlsHostnameVerifier}
* class.
* This method is used as a workaround for https://github.com/google/conscrypt/issues/1015
* when Conscrypt / OpenSSL is used as the TLS security provider.
*
* @param trustManagers the array of TrustManager instances to process.
* @return same instance passed as parameter
*/
@InterfaceAudience.Private
public static TrustManager[] processConscryptTrustManagers(TrustManager[] trustManagers) {
for (TrustManager trustManager : trustManagers) {
processConscryptTrustManager(trustManager);
}
return trustManagers;
}
// workaround https://github.com/google/conscrypt/issues/1015
private static void processConscryptTrustManager(TrustManager trustManager) {
if (trustManager.getClass().getName().equals("org.conscrypt.TrustManagerImpl")) {
try {
Class<?> conscryptClazz = Class.forName("org.conscrypt.Conscrypt");
Object hostnameVerifier = conscryptClazz.getMethod("getHostnameVerifier",
new Class[]{TrustManager.class}).invoke(null, trustManager);
if (hostnameVerifier == null) {
Object defaultHostnameVerifier = conscryptClazz.getMethod("getDefaultHostnameVerifier",
new Class[]{TrustManager.class}).invoke(null, trustManager);
if (defaultHostnameVerifier != null) {
conscryptClazz.getMethod("setHostnameVerifier", new Class[]{
TrustManager.class,
Class.forName("org.conscrypt.ConscryptHostnameVerifier")
}).invoke(null, trustManager, defaultHostnameVerifier);
}
}
} catch (ReflectiveOperationException e) {
log.warn("Unable to set hostname verifier for Conscrypt TrustManager implementation", e);
}
}
}
public static X509Certificate[] loadCertificatesFromPemFile(String certFilePath) throws KeyManagementException {
X509Certificate[] certificates = null;
if (certFilePath == null || certFilePath.isEmpty()) {
return certificates;
}
try (FileInputStream input = new FileInputStream(certFilePath)) {
certificates = loadCertificatesFromPemStream(input);
} catch (GeneralSecurityException | IOException e) {
throw new KeyManagementException("Certificate loading error", e);
}
return certificates;
}
public static X509Certificate[] loadCertificatesFromPemStream(InputStream inStream) throws KeyManagementException {
if (inStream == null) {
return null;
}
CertificateFactory cf;
try {
if (inStream.markSupported()) {
inStream.reset();
}
cf = CertificateFactory.getInstance("X.509");
Collection<X509Certificate> collection = (Collection<X509Certificate>) cf.generateCertificates(inStream);
return collection.toArray(new X509Certificate[collection.size()]);
} catch (CertificateException | IOException e) {
throw new KeyManagementException("Certificate loading error", e);
}
}
public static PrivateKey loadPrivateKeyFromPemFile(String keyFilePath) throws KeyManagementException {
if (keyFilePath == null || keyFilePath.isEmpty()) {
return null;
}
PrivateKey privateKey;
try (FileInputStream input = new FileInputStream(keyFilePath)) {
privateKey = loadPrivateKeyFromPemStream(input);
} catch (IOException e) {
throw new KeyManagementException("Private key loading error", e);
}
return privateKey;
}
public static PrivateKey loadPrivateKeyFromPemStream(InputStream inStream) throws KeyManagementException {
if (inStream == null) {
return null;
}
PrivateKey privateKey;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, StandardCharsets.UTF_8))) {
if (inStream.markSupported()) {
inStream.reset();
}
StringBuilder sb = new StringBuilder();
String currentLine = null;
// Jump to the first line after -----BEGIN [RSA] PRIVATE KEY-----
while ((currentLine = reader.readLine()) != null && !currentLine.startsWith("-----BEGIN")) {
reader.readLine();
}
// Stop (and skip) at the last line that has, say, -----END [RSA] PRIVATE KEY-----
while ((currentLine = reader.readLine()) != null && !currentLine.startsWith("-----END")) {
sb.append(currentLine);
}
KeyFactory kf = KeyFactory.getInstance("RSA");
KeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(sb.toString()));
privateKey = kf.generatePrivate(keySpec);
} catch (GeneralSecurityException | IOException e) {
throw new KeyManagementException("Private key loading error", e);
}
return privateKey;
}
private static void setupTrustCerts(SslContextBuilder builder, boolean allowInsecureConnection,
InputStream trustCertsStream) throws IOException, FileNotFoundException {
if (allowInsecureConnection) {
builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
} else {
if (trustCertsStream != null) {
builder.trustManager(trustCertsStream);
} else {
builder.trustManager((File) null);
}
}
}
private static void setupKeyManager(SslContextBuilder builder, PrivateKey privateKey,
X509Certificate[] certificates) {
builder.keyManager(privateKey, (X509Certificate[]) certificates);
}
private static void setupCiphers(SslContextBuilder builder, Set<String> ciphers) {
if (ciphers != null && ciphers.size() > 0) {
builder.ciphers(ciphers);
}
}
private static void setupProtocols(SslContextBuilder builder, Set<String> protocols) {
if (protocols != null && protocols.size() > 0) {
builder.protocols(protocols.toArray(new String[protocols.size()]));
}
}
private static void setupClientAuthentication(SslContextBuilder builder,
boolean requireTrustedClientCertOnConnect) {
if (requireTrustedClientCertOnConnect) {
builder.clientAuth(ClientAuth.REQUIRE);
} else {
builder.clientAuth(ClientAuth.OPTIONAL);
}
}
public static SslContextFactory createSslContextFactory(boolean tlsAllowInsecureConnection,
String tlsTrustCertsFilePath, String tlsCertificateFilePath, String tlsKeyFilePath,
boolean tlsRequireTrustedClientCertOnConnect, boolean autoRefresh, long certRefreshInSec)
throws GeneralSecurityException, SSLException, FileNotFoundException, IOException {
SslContextFactory sslCtxFactory = null;
if (autoRefresh) {
sslCtxFactory = new SslContextFactoryWithAutoRefresh(tlsAllowInsecureConnection, tlsTrustCertsFilePath,
tlsCertificateFilePath, tlsKeyFilePath, tlsRequireTrustedClientCertOnConnect, 0);
} else {
sslCtxFactory = new SslContextFactory();
SSLContext sslCtx = createSslContext(tlsAllowInsecureConnection, tlsTrustCertsFilePath,
tlsCertificateFilePath, tlsKeyFilePath);
sslCtxFactory.setSslContext(sslCtx);
}
if (tlsRequireTrustedClientCertOnConnect) {
sslCtxFactory.setNeedClientAuth(true);
} else {
sslCtxFactory.setWantClientAuth(true);
}
sslCtxFactory.setTrustAll(true);
return sslCtxFactory;
}
/**
* {@link SslContextFactory} that auto-refresh SSLContext.
*/
static class SslContextFactoryWithAutoRefresh extends SslContextFactory {
private final DefaultSslContextBuilder sslCtxRefresher;
public SslContextFactoryWithAutoRefresh(boolean tlsAllowInsecureConnection, String tlsTrustCertsFilePath,
String tlsCertificateFilePath, String tlsKeyFilePath, boolean tlsRequireTrustedClientCertOnConnect,
long certRefreshInSec)
throws SSLException, FileNotFoundException, GeneralSecurityException, IOException {
super();
sslCtxRefresher = new DefaultSslContextBuilder(tlsAllowInsecureConnection, tlsTrustCertsFilePath,
tlsCertificateFilePath, tlsKeyFilePath, tlsRequireTrustedClientCertOnConnect, certRefreshInSec);
if (CONSCRYPT_PROVIDER != null) {
setProvider(CONSCRYPT_PROVIDER.getName());
}
}
@Override
public SSLContext getSslContext() {
return sslCtxRefresher.get();
}
}
}