use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslContextBuilder in project aerospike-client-java by aerospike.
the class NettyEventLoops method initTlsContext.
/**
* Initialize TLS context. For internal use only.
*/
public void initTlsContext(TlsPolicy policy) {
if (this.tlsPolicy != null) {
// Already initialized.
return;
}
this.tlsPolicy = policy;
if (policy.context != null) {
// I assume the real protocol used is defined by SSLContext.getProtocol().
if (policy.ciphers == null) {
sslContext = new JdkSslContext(policy.context, true, ClientAuth.NONE);
} else {
// Ciphers are filtered in filterCipherSuites().
// Use null for ApplicationProtocolConfig argument.
sslContext = new JdkSslContext(policy.context, true, null, this, null, ClientAuth.NONE);
}
return;
}
try {
SslContextBuilder builder = SslContextBuilder.forClient();
if (policy.protocols != null) {
builder.protocols(policy.protocols);
}
if (policy.ciphers != null) {
builder.ciphers(Arrays.asList(policy.ciphers));
}
sslContext = builder.build();
} catch (Exception e) {
throw new AerospikeException("Failed to init netty TLS: " + Util.getErrorMessage(e));
}
}
use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslContextBuilder in project xipki by xipki.
the class HttpServers method buildSslContext.
private SslContext buildSslContext(HttpserverType conf) throws Exception {
TlsType tt = conf.getTls();
if (tt == null) {
return null;
}
KeystoreType kst = tt.getKeystore();
SslContextBuilder builder;
// key and certificate
if (kst == null) {
throw new IllegalArgumentException("no keystore is configured");
} else {
char[] kstPwd = passwordResolver.resolvePassword(kst.getPassword());
KeyStore ks = loadKeyStore(kst.getType(), kst.getStore(), kstPwd);
String alias = kst.getKeyAlias();
if (alias != null) {
if (!ks.isKeyEntry(alias)) {
throw new Exception("'" + alias + "' is not a valid key alias");
}
} else {
Enumeration<String> aliases = ks.aliases();
while (aliases.hasMoreElements()) {
String al = aliases.nextElement();
if (ks.isKeyEntry(al)) {
alias = al;
break;
}
}
if (alias == null) {
throw new Exception("found no key entries in the keystore");
}
}
char[] keypwd = (kst.getKeyPassword() == null) ? kstPwd : passwordResolver.resolvePassword(kst.getKeyPassword());
PrivateKey key = (PrivateKey) ks.getKey(alias, keypwd);
Certificate[] certs = ks.getCertificateChain(alias);
X509Certificate[] keyCertChain = new X509Certificate[certs.length];
for (int i = 0; i < certs.length; i++) {
keyCertChain[i] = (X509Certificate) certs[i];
}
builder = SslContextBuilder.forServer(key, keyCertChain);
}
boolean opensslAvailable = OpenSsl.isAvailable();
// providers
SslProvider sslProvider;
if (tt.getProvider() == null) {
if (!opensslAvailable) {
logOpenSslWarning();
}
sslProvider = SslContext.defaultServerProvider();
} else {
String providerStr = tt.getProvider();
String providerStr0 = providerStr.toLowerCase().replaceAll("[^a-z0-9]+", "");
if ("jdk".equals(providerStr0)) {
sslProvider = SslProvider.JDK;
} else if ("openssl".equals(providerStr0) || "opensslrefcnt".equals(providerStr0)) {
if (!opensslAvailable) {
logOpenSslWarning();
throw new Exception("OpenSSL not available");
}
sslProvider = "openssl".equals(providerStr0) ? SslProvider.OPENSSL : SslProvider.OPENSSL_REFCNT;
} else {
throw new Exception("unknwon SSL provider " + providerStr);
}
}
LOG.info("use SSL provider {}", sslProvider);
builder.sslProvider(sslProvider);
List<String> availableProtocols;
List<String> availableCiphersuits;
switch(sslProvider) {
case JDK:
SSLParameters sslParams = SSLContext.getDefault().getSupportedSSLParameters();
availableProtocols = Arrays.asList(sslParams.getProtocols());
availableCiphersuits = Arrays.asList(sslParams.getCipherSuites());
break;
case OPENSSL:
case OPENSSL_REFCNT:
// any way to get the supported protocols of OpenSSL?
availableProtocols = Arrays.asList("TLSv1.1", "TLSv1.2");
availableCiphersuits = new ArrayList<>(OpenSsl.availableJavaCipherSuites());
break;
default:
throw new RuntimeException("should not reach here, unknown SssProvider " + sslProvider);
}
// protocols
List<String> protocols;
if (tt.getProtocols() != null) {
protocols = tt.getProtocols().getProtocol();
} else {
protocols = Arrays.asList("TLSv1.1", "TLSv1.2");
}
final String[] strArray = new String[0];
Set<String> usedProtocols = new HashSet<>();
for (String protocol : protocols) {
boolean added = false;
for (String supported : availableProtocols) {
if (protocol.equalsIgnoreCase(supported)) {
usedProtocols.add(supported);
added = true;
break;
}
}
if (!added) {
LOG.warn("SSL Protocol {} unsupported, ignore it", protocol);
}
}
if (usedProtocols.isEmpty()) {
throw new Exception("None of the configured SSL protocols is supported");
}
LOG.info("use SSL protocols {}", usedProtocols);
builder.protocols(usedProtocols.toArray(strArray));
// canonicalize the cipher suites
boolean cipherWithTls = availableCiphersuits.get(0).startsWith("TLS_");
// cipher suites
Set<String> usedCipherSuites = new HashSet<>();
if (tt.getCiphersuites() != null) {
for (String cipherSuite : tt.getCiphersuites().getCiphersuite()) {
if (cipherSuite.length() < 5) {
LOG.warn("cipher suite {} unsupported, ignore it", cipherSuite);
continue;
}
String adaptedCipher;
if (cipherWithTls == cipherSuite.startsWith("TLS_")) {
adaptedCipher = cipherSuite;
} else {
if (cipherWithTls) {
adaptedCipher = "TLS_" + cipherSuite.substring(4);
} else {
adaptedCipher = "SSL_" + cipherSuite.substring(4);
}
}
boolean added = false;
for (String supported : availableCiphersuits) {
if (adaptedCipher.equalsIgnoreCase(supported)) {
usedCipherSuites.add(supported);
added = true;
break;
}
}
if (!added) {
LOG.warn("SSL cipher suite {} unsupported, ignore it", cipherSuite);
}
}
} else {
String[] excludeMiddlePatterns = { "_3DES", "_DES", "EMPTY", "EXPORT", "anno", "NULL" };
String[] excludeEndPatterns = { "MD5", "SHA" };
for (String cipherSuite : availableCiphersuits) {
boolean add = true;
for (String p : excludeMiddlePatterns) {
if (cipherSuite.contains(p)) {
add = false;
break;
}
}
if (add) {
for (String p : excludeEndPatterns) {
if (cipherSuite.endsWith(p)) {
add = false;
break;
}
}
}
if (add) {
usedCipherSuites.add(cipherSuite);
}
}
}
LOG.info("use SSL cipher suites {}", usedCipherSuites);
builder.ciphers(usedCipherSuites);
// client authentication
ClientAuth clientAuth;
String str = tt.getClientauth();
if ("none".equalsIgnoreCase(str)) {
clientAuth = ClientAuth.NONE;
} else if ("optional".equalsIgnoreCase(str)) {
clientAuth = ClientAuth.OPTIONAL;
} else if ("require".equalsIgnoreCase(str)) {
clientAuth = ClientAuth.REQUIRE;
} else {
throw new Exception("invalid client authentication '" + str + "'");
}
builder.clientAuth(clientAuth);
if (clientAuth != ClientAuth.NONE) {
TruststoreType tst = tt.getTruststore();
if (tst == null) {
throw new Exception("Client authentication is activated, but no truststore is configured");
}
char[] pwd = passwordResolver.resolvePassword(tst.getPassword());
KeyStore ks = loadKeyStore(tst.getType(), tst.getStore(), pwd);
List<X509Certificate> trustcerts = new LinkedList<>();
Enumeration<String> aliases = ks.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
Certificate cert = ks.getCertificate(alias);
trustcerts.add((X509Certificate) cert);
}
if (trustcerts.isEmpty()) {
throw new Exception("No certificates found int the truststore. Please verify it via" + " JDK's keytool.");
}
builder.trustManager(trustcerts.toArray(new X509Certificate[0]));
}
return builder.build();
}
use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslContextBuilder in project bookkeeper by apache.
the class TLSContextFactory method createServerContext.
private void createServerContext(AbstractConfiguration conf) throws SecurityException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, InvalidKeySpecException, IllegalArgumentException {
final SslContextBuilder sslContextBuilder;
final ServerConfiguration serverConf;
final SslProvider provider;
final boolean clientAuthentication;
// get key-file and trust-file locations and passwords
if (!(conf instanceof ServerConfiguration)) {
throw new SecurityException("Server configruation not provided");
}
serverConf = (ServerConfiguration) conf;
provider = getTLSProvider(serverConf.getTLSProvider());
clientAuthentication = serverConf.getTLSClientAuthentication();
switch(KeyStoreType.valueOf(serverConf.getTLSKeyStoreType())) {
case PEM:
final String keyPassword;
if (Strings.isNullOrEmpty(serverConf.getTLSKeyStore())) {
throw new SecurityException("Key path is required");
}
if (Strings.isNullOrEmpty(serverConf.getTLSCertificatePath())) {
throw new SecurityException("Certificate path is required");
}
if (!Strings.isNullOrEmpty(serverConf.getTLSKeyStorePasswordPath())) {
keyPassword = getPasswordFromFile(serverConf.getTLSKeyStorePasswordPath());
} else {
keyPassword = null;
}
sslContextBuilder = SslContextBuilder.forServer(new File(serverConf.getTLSCertificatePath()), new File(serverConf.getTLSKeyStore()), keyPassword).ciphers(null).sessionCacheSize(0).sessionTimeout(0).sslProvider(provider).startTls(true);
break;
case JKS:
// falling thru, same as PKCS12
case PKCS12:
KeyManagerFactory kmf = initKeyManagerFactory(serverConf.getTLSKeyStoreType(), serverConf.getTLSKeyStore(), serverConf.getTLSKeyStorePasswordPath());
sslContextBuilder = SslContextBuilder.forServer(kmf).ciphers(null).sessionCacheSize(0).sessionTimeout(0).sslProvider(provider).startTls(true);
break;
default:
throw new SecurityException("Invalid Keyfile type" + serverConf.getTLSKeyStoreType());
}
if (clientAuthentication) {
sslContextBuilder.clientAuth(ClientAuth.REQUIRE);
switch(KeyStoreType.valueOf(serverConf.getTLSTrustStoreType())) {
case PEM:
if (Strings.isNullOrEmpty(serverConf.getTLSTrustStore())) {
throw new SecurityException("CA Certificate chain is required");
}
sslContextBuilder.trustManager(new File(serverConf.getTLSTrustStore()));
break;
case JKS:
// falling thru, same as PKCS12
case PKCS12:
TrustManagerFactory tmf = initTrustManagerFactory(serverConf.getTLSTrustStoreType(), serverConf.getTLSTrustStore(), serverConf.getTLSTrustStorePasswordPath());
sslContextBuilder.trustManager(tmf);
break;
default:
throw new SecurityException("Invalid Truststore type" + serverConf.getTLSTrustStoreType());
}
}
sslContext = sslContextBuilder.build();
}
use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslContextBuilder in project ratpack by ratpack.
the class NettySslContextDeserializer method deserialize.
@SuppressWarnings("Duplicates")
@Override
public SslContext deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
ObjectNode node = jp.readValueAsTree();
try {
String keyStoreFile = node.path("keystoreFile").asText();
String keyStorePassword = node.path("keystorePassword").asText();
String trustStoreFile = node.path("truststoreFile").asText();
String trustStorePassword = node.path("truststorePassword").asText();
if (keyStoreFile.isEmpty()) {
throw new IllegalStateException("keystoreFile must be set if any ssl properties are set");
} else if (keyStorePassword.isEmpty()) {
throw new IllegalStateException("keystorePassword must be set if any ssl properties are set");
} else if (!trustStoreFile.isEmpty() && trustStorePassword.isEmpty()) {
throw new IllegalStateException("truststorePassword must be specified when truststoreFile is specified");
}
KeyManagerFactory keyManagerFactory;
try (InputStream is = Files.newInputStream(Paths.get(keyStoreFile))) {
keyManagerFactory = SslContexts.keyManagerFactory(is, keyStorePassword.toCharArray());
}
SslContextBuilder builder = SslContextBuilder.forServer(keyManagerFactory);
if (!trustStoreFile.isEmpty()) {
try (InputStream is = Files.newInputStream(Paths.get(trustStoreFile))) {
builder.trustManager(SslContexts.trustManagerFactory(is, trustStorePassword.toCharArray()));
}
}
return builder.build();
} catch (GeneralSecurityException ex) {
throw Exceptions.uncheck(ex);
}
}
use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslContextBuilder in project incubator-skywalking by apache.
the class TLSChannelBuilder method build.
@Override
public NettyChannelBuilder build(NettyChannelBuilder managedChannelBuilder) throws AgentPackageNotFoundException, SSLException {
File caFile = new File(AgentPackagePath.getPath(), CA_FILE_NAME);
if (caFile.exists() && caFile.isFile()) {
SslContextBuilder builder = GrpcSslContexts.forClient();
builder.trustManager(caFile);
managedChannelBuilder = managedChannelBuilder.negotiationType(NegotiationType.TLS).sslContext(builder.build());
}
return managedChannelBuilder;
}
Aggregations