use of org.apache.http.conn.ssl.AllowAllHostnameVerifier in project cdap by caskdata.
the class NettyRouterHttpsTest method getHTTPClient.
@Override
protected DefaultHttpClient getHTTPClient() throws Exception {
SSLContext sslContext = SSLContext.getInstance("TLS");
// set up a TrustManager that trusts everything
sslContext.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), new SecureRandom());
SSLSocketFactory sf = new SSLSocketFactory(sslContext, new AllowAllHostnameVerifier());
Scheme httpsScheme = new Scheme("https", 10101, sf);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(httpsScheme);
// apache HttpClient version >4.2 should use BasicClientConnectionManager
ClientConnectionManager cm = new BasicClientConnectionManager(schemeRegistry);
return new DefaultHttpClient(cm);
}
use of org.apache.http.conn.ssl.AllowAllHostnameVerifier in project syncany by syncany.
the class CommandLineClient method sendToRest.
private int sendToRest(Command command, String commandName, String[] commandArgs, File portFile) {
try {
// Read port config (for daemon) from port file
PortTO portConfig = readPortConfig(portFile);
// Create authentication details
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(SERVER_HOSTNAME, portConfig.getPort()), new UsernamePasswordCredentials(portConfig.getUser().getUsername(), portConfig.getUser().getPassword()));
// Allow all hostnames in CN; this is okay as long as hostname is localhost/127.0.0.1!
// See: https://github.com/syncany/syncany/pull/196#issuecomment-52197017
X509HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier();
// Fetch the SSL context (using the user key/trust store)
SSLContext sslContext = UserConfig.createUserSSLContext();
// Create client with authentication details
CloseableHttpClient client = HttpClients.custom().setSslcontext(sslContext).setHostnameVerifier(hostnameVerifier).setDefaultCredentialsProvider(credentialsProvider).build();
// Build and send request, print response
Request request = buildFolderRequestFromCommand(command, commandName, commandArgs, config.getLocalDir().getAbsolutePath());
String serverUri = SERVER_SCHEMA + SERVER_HOSTNAME + ":" + portConfig.getPort() + SERVER_REST_API;
String xmlMessageString = XmlMessageFactory.toXml(request);
StringEntity xmlMessageEntity = new StringEntity(xmlMessageString);
HttpPost httpPost = new HttpPost(serverUri);
httpPost.setEntity(xmlMessageEntity);
logger.log(Level.INFO, "Sending HTTP Request to: " + serverUri);
logger.log(Level.FINE, httpPost.toString());
logger.log(Level.FINE, xmlMessageString);
HttpResponse httpResponse = client.execute(httpPost);
int exitCode = handleRestResponse(command, httpResponse);
return exitCode;
} catch (Exception e) {
logger.log(Level.SEVERE, "Command " + command.toString() + " FAILED. ", e);
return showErrorAndExit(e.getMessage());
}
}
use of org.apache.http.conn.ssl.AllowAllHostnameVerifier in project xabber-android by redsolution.
the class ConnectionBuilder method build.
@NonNull
public static XMPPTCPConnection build(AccountJid account, @NonNull final ConnectionSettings connectionSettings) {
XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
builder.setXmppDomain(connectionSettings.getServerName());
if (connectionSettings.isCustomHostAndPort()) {
setCustomHost(connectionSettings, builder);
builder.setPort(connectionSettings.getPort());
}
builder.setDebuggerEnabled(true);
builder.setSecurityMode(connectionSettings.getTlsMode().getSecurityMode());
builder.setCompressionEnabled(connectionSettings.useCompression());
builder.setSendPresence(false);
builder.setUsernameAndPassword(connectionSettings.getUserName(), connectionSettings.getPassword());
builder.setResource(connectionSettings.getResource());
builder.setProxyInfo(getProxyInfo(connectionSettings));
try {
LogManager.i(LOG_TAG, "SettingsManager.securityCheckCertificate: " + SettingsManager.securityCheckCertificate());
if (SettingsManager.securityCheckCertificate()) {
SSLContext sslContext = SSLContext.getInstance("TLS");
MemorizingTrustManager mtm = CertificateManager.getInstance().getNewMemorizingTrustManager(account);
sslContext.init(null, new X509TrustManager[] { mtm }, new java.security.SecureRandom());
builder.setCustomSSLContext(sslContext);
builder.setHostnameVerifier(mtm.wrapHostnameVerifier(new CustomDomainVerifier()));
} else {
TLSUtils.acceptAllCertificates(builder);
builder.setHostnameVerifier(new AllowAllHostnameVerifier());
}
} catch (NoSuchAlgorithmException | KeyManagementException e) {
LogManager.exception(LOG_TAG, e);
}
// if account have token
if (connectionSettings.getToken() != null && !connectionSettings.getToken().isEmpty() && connectionSettings.getPassword() != null && connectionSettings.getPassword().isEmpty()) {
// then enable only SASLXOauth2Mechanism
builder.addEnabledSaslMechanism(SASLXOauth2Mechanism.NAME);
// and set token as password
builder.setUsernameAndPassword(connectionSettings.getUserName(), connectionSettings.getToken());
}
// X-TOKEN
if (connectionSettings.getXToken() != null && !connectionSettings.getXToken().isExpired()) {
LogManager.d(LOG_TAG, "Authorization with x-token");
SASLAuthentication.registerSASLMechanism(new SASLXTOKENMechanism());
builder.addEnabledSaslMechanism(SASLXTOKENMechanism.NAME);
builder.setUsernameAndPassword(connectionSettings.getUserName(), connectionSettings.getXToken().getToken());
}
LogManager.i(LOG_TAG, "new XMPPTCPConnection " + connectionSettings.getServerName());
return new XMPPTCPConnection(builder.build());
}
use of org.apache.http.conn.ssl.AllowAllHostnameVerifier in project vcell by virtualcell.
the class VCellApiClient method initClient.
private void initClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
SSLContextBuilder builder = new SSLContextBuilder();
if (bIgnoreCertProblems) {
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
}
SSLConnectionSocketFactory sslsf = null;
if (bIgnoreHostMismatch) {
X509HostnameVerifier hostNameVerifier = new AllowAllHostnameVerifier();
sslsf = new SSLConnectionSocketFactory(builder.build(), hostNameVerifier);
} else {
sslsf = new SSLConnectionSocketFactory(builder.build());
}
HttpClientBuilder httpClientBuilder = HttpClients.custom();
try {
HttpHost proxy = null;
if (System.getProperty("http.proxyHost") != null && System.getProperty("http.proxyPort") != null) {
// System.getProperty(NetworkProxyUtils.PROXY_HTTP_HOST);
proxy = new HttpHost(System.getProperty("http.proxyHost"), Integer.parseUnsignedInt(System.getProperty("http.proxyPort")), "http");
} else if (System.getProperty("socksProxyHost") != null && System.getProperty("socksProxyPort") != null) {
// System.getProperty(NetworkProxyUtils.PROXY_SOCKS_HOST);
proxy = new HttpHost(System.getProperty("socksProxyHost"), Integer.parseUnsignedInt(System.getProperty("socksProxyPort")), "socks");
}
if (proxy != null) {
RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
httpClientBuilder.setDefaultRequestConfig(config);
}
} catch (Exception e) {
e.printStackTrace();
// continue, try connections anyway
}
httpclient = httpClientBuilder.setSSLSocketFactory(sslsf).setRedirectStrategy(new DefaultRedirectStrategy()).build();
httpClientContext = HttpClientContext.create();
}
use of org.apache.http.conn.ssl.AllowAllHostnameVerifier in project yorc-a4c-plugin by ystia.
the class RestClient method setProviderConfiguration.
public void setProviderConfiguration(ProviderConfig providerConfiguration) throws PluginConfigurationException {
this.providerConfiguration = providerConfiguration;
log.debug("setProviderConfiguration YorcURL=" + providerConfiguration.getUrlYorc());
RequestConfig clientConfig = RequestConfig.custom().setConnectTimeout(((Long) CONNECTION_TIMEOUT).intValue()).setSocketTimeout(((Long) SOCKET_TIMEOUT).intValue()).setConnectionRequestTimeout(((Long) SOCKET_TIMEOUT).intValue()).build();
CloseableHttpClient httpClient;
if (Boolean.TRUE.equals(providerConfiguration.getInsecureTLS())) {
SSLContext sslContext;
try {
sslContext = SSLContexts.custom().loadTrustMaterial(null, (chain, authType) -> true).build();
} catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
e.printStackTrace();
throw new PluginConfigurationException("Failed to create SSL socket factory", e);
}
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslsf).build();
PoolingHttpClientConnectionManager poolHttpConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
configurePoolingHttpClientConnectionManager(poolHttpConnManager);
httpClient = HttpClientBuilder.create().useSystemProperties().setConnectionManager(poolHttpConnManager).setDefaultRequestConfig(clientConfig).setSslcontext(sslContext).build();
} else if (providerConfiguration.getUrlYorc().startsWith("https")) {
SSLContext sslContext;
// on system default keystore and truststore
if (providerConfiguration.getCaCertificate().isEmpty() || providerConfiguration.getClientCertificate().isEmpty() || providerConfiguration.getClientKey().isEmpty()) {
log.warn("Missing CA|Client certificate|Client key in plugin configuration, will use system defaults");
if (System.getProperty("javax.net.ssl.keyStore") == null || System.getProperty("javax.net.ssl.keyStorePassword") == null) {
log.warn("Using SSL but you didn't provide client keystore and password. This means that if required by Yorc client authentication will fail.\n" + "Please use -Djavax.net.ssl.keyStore <keyStorePath> -Djavax.net.ssl.keyStorePassword <password> while starting java VM");
}
if (System.getProperty("javax.net.ssl.trustStore") == null || System.getProperty("javax.net.ssl.trustStorePassword") == null) {
log.warn("You didn't provide client trustore and password. Using defalut one \n" + "Please use -Djavax.net.ssl.trustStore <trustStorePath> -Djavax.net.ssl.trustStorePassword <password> while starting java VM");
}
sslContext = SSLContexts.createSystemDefault();
} else {
// Create a key store containing CA and client key/certificate provided
// in the plugin configuration
KeyStore keystore;
try {
// Create the CA certificate from its configuration string value
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
ByteArrayInputStream inputStream = new ByteArrayInputStream(providerConfiguration.getCaCertificate().getBytes());
X509Certificate trustedCert = (X509Certificate) certFactory.generateCertificate(inputStream);
inputStream.close();
// Create the client private key from its configuration string value
String keyContent = providerConfiguration.getClientKey().replaceFirst("-----BEGIN PRIVATE KEY-----\n", "").replaceFirst("\n-----END PRIVATE KEY-----", "").trim();
PKCS8EncodedKeySpec clientKeySpec = new PKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(keyContent));
// Getting the key algorithm
ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(clientKeySpec.getEncoded()));
PrivateKeyInfo pki = PrivateKeyInfo.getInstance(bIn.readObject());
bIn.close();
String algorithm = pki.getPrivateKeyAlgorithm().getAlgorithm().getId();
// Workaround for a missing algorithm OID in the list of default providers
if ("1.2.840.113549.1.1.1".equals(algorithm)) {
algorithm = "RSA";
}
KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
PrivateKey clientKey = keyFactory.generatePrivate(clientKeySpec);
// Create the client certificate from its configuration string value
inputStream = new ByteArrayInputStream(providerConfiguration.getClientCertificate().getBytes());
Certificate clientCert = certFactory.generateCertificate(inputStream);
inputStream.close();
// Create an empty keystore
keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(null);
// Add the certificate authority
keystore.setCertificateEntry(trustedCert.getSubjectX500Principal().getName(), trustedCert);
// Add client key/certificate and chain to the Key store
Certificate[] chain = { clientCert, trustedCert };
keystore.setKeyEntry("Yorc Client", clientKey, "yorc".toCharArray(), chain);
} catch (CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException | KeyStoreException e) {
e.printStackTrace();
throw new PluginConfigurationException("Failed to create keystore", e);
}
// Create a SSL context using this Key Store
try {
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keystore);
sslContext = SSLContext.getInstance("TLS");
KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
kmf.init(keystore, "yorc".toCharArray());
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
} catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) {
e.printStackTrace();
throw new PluginConfigurationException("Failed to create SSL context", e);
}
}
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslsf).build();
PoolingHttpClientConnectionManager poolHttpConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
configurePoolingHttpClientConnectionManager(poolHttpConnManager);
httpClient = HttpClientBuilder.create().useSystemProperties().setConnectionManager(poolHttpConnManager).setDefaultRequestConfig(clientConfig).setSslcontext(sslContext).build();
} else {
PoolingHttpClientConnectionManager poolHttpConnManager = new PoolingHttpClientConnectionManager();
configurePoolingHttpClientConnectionManager(poolHttpConnManager);
httpClient = HttpClientBuilder.create().useSystemProperties().setConnectionManager(poolHttpConnManager).setDefaultRequestConfig(clientConfig).build();
}
// Instantiate restTemplate
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
restTemplate = new RestTemplate(requestFactory);
// Display deployments
try {
logDeployments();
} catch (Exception e) {
log.warn("Unable to retrieve deployments due to: {}", e.getMessage());
e.printStackTrace();
throw new PluginConfigurationException("Failed to connect to yorc", e);
}
}
Aggregations