use of javax.net.ssl.SSLSocketFactory in project nifi-minifi by apache.
the class HttpConnector method get.
public HttpURLConnection get(String endpointPath, Map<String, List<String>> headers) throws ConfigurationProviderException {
String endpointUrl = baseUrl + endpointPath;
if (logger.isDebugEnabled()) {
logger.debug("Connecting to endpoint: " + endpointUrl);
}
URL url;
try {
url = new URL(endpointUrl);
} catch (MalformedURLException e) {
throw new ConfigurationProviderException("Malformed url " + endpointUrl, e);
}
HttpURLConnection httpURLConnection;
try {
if (proxy == null) {
httpURLConnection = (HttpURLConnection) url.openConnection();
} else {
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
}
if (sslContextFactory != null) {
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) httpURLConnection;
SSLContext sslContext = sslContextFactory.getSslContext();
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
httpsURLConnection.setSSLSocketFactory(socketFactory);
}
} catch (IOException e) {
throw new ConfigurationProviderException("Unable to connect to " + url, e);
}
if (proxyAuthorization != null) {
httpURLConnection.setRequestProperty("Proxy-Authorization", proxyAuthorization);
}
headers.forEach((s, strings) -> httpURLConnection.setRequestProperty(s, strings.stream().collect(Collectors.joining(","))));
return httpURLConnection;
}
use of javax.net.ssl.SSLSocketFactory in project BestPracticeApp by pop1234o.
the class Https method getSSLSocketFactory.
public static SSLSocketFactory getSSLSocketFactory() {
// 创建一个不验证证书的 “信任证书管理器”
TrustManager[] manager = new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
} };
try {
SSLContext tls = SSLContext.getInstance("TLS");
tls.init(null, manager, new SecureRandom());
SSLSocketFactory socketFactory = tls.getSocketFactory();
return socketFactory;
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
use of javax.net.ssl.SSLSocketFactory in project apm-agent-java by elastic.
the class ReporterFactory method disableCertificateValidation.
// based on https://gist.github.com/mefarazath/c9b588044d6bffd26aac3c520660bf40
private void disableCertificateValidation(OkHttpClient.Builder builder) {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
} };
try {
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]).hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
} catch (KeyManagementException | NoSuchAlgorithmException e) {
logger.warn(e.getMessage(), e);
}
}
use of javax.net.ssl.SSLSocketFactory in project photon-model by vmware.
the class CertificateUtil method resolveCertificate.
public static X509TrustManagerResolver resolveCertificate(URI uri, Proxy proxy, String proxyUsername, String proxyPassword, long timeoutMillis) {
logger.entering(logger.getName(), "resolveCertificate");
X509TrustManagerResolver trustManagerResolver = new X509TrustManagerResolver();
SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { trustManagerResolver }, null);
} catch (KeyManagementException | NoSuchAlgorithmException e) {
logger.throwing(logger.getName(), "connect", e);
throw new LocalizableValidationException(e, "Failed to initialize SSL context.", "security.certificate.context.init.error");
}
String hostAddress = uri.getHost();
int port = uri.getPort() == -1 ? DEFAULT_SECURE_CONNECTION_PORT : uri.getPort();
String uriScheme = uri.getScheme();
String host = String.format("%s://%s:%d", uriScheme, hostAddress, port);
try {
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
if (proxy != null && proxy.type() == Type.HTTP && proxyUsername != null && UriUtils.HTTPS_SCHEME.equalsIgnoreCase(uriScheme)) {
URL url = uri.toURL();
handleCertForHttpsThroughHttpProxyWithAuth(url, proxy, proxyUsername, proxyPassword, timeoutMillis, sslSocketFactory);
} else {
SSLSocket sslSocket;
if (proxy != null) {
if (proxyUsername != null) {
throw new LocalizableValidationException("Proxy authentication supported " + "for HTTPS URI through HTTP Proxy only." + " URI: " + uri.toASCIIString() + ", Proxy: " + proxy.toString(), "security.certificate.proxy.authentication.not.supported.error", uri.toASCIIString(), proxy.toString());
}
Socket tunnel = new Socket(proxy);
tunnel.connect(new InetSocketAddress(hostAddress, port), (int) timeoutMillis);
sslSocket = (SSLSocket) sslSocketFactory.createSocket(tunnel, hostAddress, port, true);
} else {
sslSocket = (SSLSocket) sslSocketFactory.createSocket();
if (SSL_CONNECT_USE_SNI) {
SNIHostName serverName = new SNIHostName(hostAddress);
List<SNIServerName> serverNames = new ArrayList<>(1);
serverNames.add(serverName);
SSLParameters params = sslSocket.getSSLParameters();
params.setServerNames(serverNames);
sslSocket.setSSLParameters(params);
}
sslSocket.connect(new InetSocketAddress(hostAddress, port), (int) timeoutMillis);
}
SSLSession session = sslSocket.getSession();
session.invalidate();
}
} catch (IOException e) {
try {
if (trustManagerResolver.isCertsTrusted() || trustManagerResolver.getCertificateChain().length == 0) {
Utils.logWarning("Exception while resolving certificate for host: [%s]. Error: %s ", host, e.getMessage());
} else {
logger.throwing(logger.getName(), "connect", e);
throw new IllegalArgumentException(e.getMessage(), e);
}
} catch (IllegalStateException ise) {
throw new LocalizableValidationException(e, String.format("Cannot connect to host: [%s]. Error: %s", host, e.getMessage()), "security.certificate.connection.error", host, e.getMessage());
}
}
if (trustManagerResolver.getCertificateChain().length == 0) {
LocalizableValidationException e = new LocalizableValidationException("Check ssl certificate failed for server: " + host, "security.certificate.check.error", host);
logger.throwing(logger.getName(), "connect", e);
throw e;
}
logger.exiting(logger.getName(), "resolveCertificate");
return trustManagerResolver;
}
use of javax.net.ssl.SSLSocketFactory in project box-android-sdk by box.
the class BoxRequest method onSend.
/**
* Synchronously make the request to Box and handle the response appropriately.
* @return the expected BoxObject if the request is successful.
* @throws BoxException thrown if there was a problem with handling the request.
*/
protected T onSend() throws BoxException {
BoxRequest.BoxRequestHandler requestHandler = getRequestHandler();
BoxHttpResponse response = null;
HttpURLConnection connection = null;
try {
// Create the HTTP request and send it
BoxHttpRequest request = createHttpRequest();
connection = request.getUrlConnection();
if (mRequiresSocket && connection instanceof HttpsURLConnection) {
final SSLSocketFactory factory = ((HttpsURLConnection) connection).getSSLSocketFactory();
SSLSocketFactoryWrapper wrappedFactory = new SSLSocketFactoryWrapper(factory);
mSocketFactoryRef = new WeakReference<SSLSocketFactoryWrapper>(wrappedFactory);
((HttpsURLConnection) connection).setSSLSocketFactory(wrappedFactory);
}
if (mTimeout > 0) {
connection.setConnectTimeout(mTimeout);
connection.setReadTimeout(mTimeout);
}
response = sendRequest(request, connection);
logDebug(response);
// Process the response through the provided handler
if (requestHandler.isResponseSuccess(response)) {
T result = (T) requestHandler.onResponse(mClazz, response);
return result;
}
throw new BoxException("An error occurred while sending the request", response);
} catch (IOException e) {
return handleSendException(requestHandler, response, e);
} catch (InstantiationException e) {
return handleSendException(requestHandler, response, e);
} catch (IllegalAccessException e) {
return handleSendException(requestHandler, response, e);
} catch (BoxException e) {
return handleSendException(requestHandler, response, e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
Aggregations