I'm using OkHttp3 to establish a connection between android app and server. I have a self-signed certificate, which is needed to talk to the server. Problem was that android doesn't trust self-signed certs so I got code from this website to disable SSL verification. Now the problem is that I'm not sending a certificate with my request. If I add this certificate to trusted certificates I get "Trust anchor for certification path not found." error.
Current code:
#Override
protected Void doInBackground(Void... voids) {
try {
OkHttpClient client = ApiAuth.getUnsafeOkHttpClient();
Request request = new Request.Builder()
.url(url)
.get().build();
Response response = client.newCall(request).execute();
Log.d("Server connection", "connection established!");
Log.d("Server response -------------\n", String.valueOf(response));
} catch (IOException | NullPointerException e) {
e.printStackTrace();
Log.d("catch", "cought exception ");
}
return null; //(CertificateException | IOException | KeyStoreException | NoSuchAlgorithmException | KeyManagementException | NullPointerException e)
}
}
private static OkHttpClient getUnsafeOkHttpClient() {
try {
final TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
#Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
#Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
#Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.sslSocketFactory(sslSocketFactory, (X509TrustManager)trustAllCerts[0]);
builder.hostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
OkHttpClient okHttpClient = builder.build();
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
Is there a better solution (that actually works)?
I got a response with postman. I disabled SSL verification and gave .pfx file in settings (or .crt and .key). How can I do the same in andorid studio?
Related
I'm trying to replace the following deprecated (e.g. Apache DefaultHttpClient, SSLSocketFactory are deprecated) code:
public class HttpUtil {
public static DefaultHttpClient getDefaultHttpClient(IClientConfiguration configuration,
ExternalAPILogger logger) {
DefaultHttpClient client = new DefaultHttpClient();
if(configuration.isIgnoreSSLCertificate()) {
try {
SSLContext context = SSLContext.getInstance("TLS");
X509TrustManager trustManager = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
context.init(null, new TrustManager[]{trustManager}, null);
SSLSocketFactory sslSocketFactory = new SSLSocketFactory(context);
sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager connectionManager = client.getConnectionManager();
SchemeRegistry schemeRegistry = connectionManager.getSchemeRegistry();
schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
client = new DefaultHttpClient(connectionManager, client.getParams());
} catch (NoSuchAlgorithmException e) {
logger.log(HttpUtil.class.getName(), "TLS not available", e, ExternalAPILogger.DEBUG);
} catch(KeyManagementException e) {
logger.log(HttpUtil.class, "ssl context init failed", e, ExternalAPILogger.DEBUG);
}
}
if(configuration.isUseProxy()) {
HttpHost proxy = new HttpHost(configuration.getProxyHost(),
configuration.getProxyPort());
ConnRouteParams.setDefaultProxy(client.getParams(), proxy);
}
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60 * 1000);
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60 * 1000);
return client;
}
}
by this new code:
public static HttpClient getHttpClient(IClientConfiguration configuration,
ExternalAPILogger logger) {
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
// clientBuilder.useSystemProperties();
if (configuration.isIgnoreSSLCertificate()) {
try {
SSLContext context = SSLContext.getInstance("TLS");
X509TrustManager trustManager = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
context.init(null, new TrustManager[] { trustManager }, null);
// clientBuilder.setSSLContext(context);
// clientBuilder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
SSLConnectionSocketFactory sslSocketFactory =
new SSLConnectionSocketFactory(context, NoopHostnameVerifier.INSTANCE);
clientBuilder.setSSLSocketFactory(sslSocketFactory);
Registry<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslSocketFactory).build();
HttpClientConnectionManager httpClientConnectionManager =
new BasicHttpClientConnectionManager(schemeRegistry);
clientBuilder.setConnectionManager(httpClientConnectionManager);
} catch (NoSuchAlgorithmException e) {
logger.log(HttpUtil.class.getName(), "TLS not available", e, ExternalAPILogger.DEBUG);
} catch (KeyManagementException e) {
logger.log(HttpUtil.class, "ssl context init failed", e, ExternalAPILogger.DEBUG);
}
}
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
if (configuration.isUseProxy()) {
HttpHost proxy = new HttpHost(
configuration.getProxyHost(),
configuration.getProxyPort());
// clientBuilder
// .setRoutePlanner(new DefaultProxyRoutePlanner(proxy))
// .setProxy(proxy)
// .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
requestConfigBuilder.setProxy(proxy);
}
requestConfigBuilder
.setConnectTimeout(60 * 1000)
.setSocketTimeout(60 * 1000);
clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
// SocketConfig.Builder socketConfig = SocketConfig.custom();
// socketConfig.setSoTimeout(60 * 1000);
// clientBuilder.setDefaultSocketConfig(socketConfig.build());
return clientBuilder.build();
}
but I have problems to get the code running using a http proxy. I get the following error message.:
Caused by: org.apache.http.conn.UnsupportedSchemeException: http protocol is not supported
I got - closed connection -1 , draft org.java_websocket.drafts.Draft_17#75599672 refuses handshake , false - then changed the code as below:
Socket creation coode
webClient = new APICWebClient(new URI(getWebSocketUrl(currentApic.IPAddress, port)), new Draft_17());
webClient.connect();
Constructor:
public APICWebClient(URI serverURI, Draft draft) {
super(serverURI, draft);
SSLContext sslContext = null;
try {
sslContext = SSLContext.getDefault();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setWebSocketFactory(new DefaultSSLWebSocketClientFactory(sslContext));
logger.info("Socket object created");
}
Draft_17. I get : closed connection -1 , , true. Any help here. This happens during socket creation.
Need to create sslcontext like below. it skips the certificate. I was successfully able make a connection without certificate
SSLContext sslContext = SSLContext.getInstance("SSL");
// set up a TrustManager that trusts everything
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
System.out.println("getAcceptedIssuers =============");
return null;
}
public void checkClientTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkClientTrusted =============");
}
public void checkServerTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkServerTrusted =============");
}
} }, new SecureRandom());
I'm getting javax.net.ssl.SSLHandshakeException: Connection closed by peer when i try to make https request from android app using HttpsURLConnection
Above the code for to make request and return a Bitmap.
protected Bitmap doInBackground(String... params) {
try {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
HttpsURLConnection connection = (HttpsURLConnection)
new URL("www.example.com.br").openConnection();
connection.setHostnameVerifier(getHostnameVerifier("www.example.com.br");
connection.setRequestMethod("GET");
connection.setConnectTimeout(3000);
connection.setUseCaches(false);
connection.setAllowUserInteraction(false);
connection.connect();
setCookieActivity(connection.getHeaderField("Set-Cookie"));
return BitmapFactory.decodeStream(connection.getInputStream());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private HostnameVerifier getHostnameVerifier(final String url) {
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
HostnameVerifier hv =
HttpsURLConnection.getDefaultHostnameVerifier();
return hv.verify(url, session);
}
};
return hostnameVerifier;
}
I already tried many thing, but i get the same exception
This link works for many, but not for me.
telling java to accept self-signed ssl certificate
There are several examples out there [1][2] of how to configure HTTPS in Java/Groovy to ignore SSL certificate errors. In short they all create a custom TrustManager, add it to an SSLContext and then install the resulting SocketFactory as the default connection factory for HTTPS connections. And of course they comes with all the requisite warnings about MITM attacks and how dangerous this is.
Indeed in my situation where I am writing a groovy script to be run inside of a Jenkins job, setting the default socket factory is nuts. It would have affects well beyond that of my script. So my question is, how do you accomplish this for a specific connection or specific HTTP client and not for all connections/clients? In other words, how to I localize such a change to just my transient piece of code?
public class BasicHttpClientFactory implements HttpClientFactory {
private String proxyHost;
private Integer proxyPort;
private boolean isSocksProxy = false;
HttpClient httpClient;
final Integer maxConnections = new Integer(10);
private static final Log logger = LogFactory.getLog(BasicHttpClientFactory.class);
#Override
public HttpClient createNewClient() {
SSLConnectionSocketFactory sslsf = null;
try {
SSLContextBuilder builder = SSLContexts.custom();
builder.loadTrustMaterial(null, new TrustStrategy() {
#Override
public boolean isTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
return true;
}
});
SSLContext sslContext = builder.build();
sslsf = new SSLConnectionSocketFactory(
sslContext, new X509HostnameVerifier() {
#Override
public void verify(String host, SSLSocket ssl)
throws IOException {
}
#Override
public void verify(String host, X509Certificate cert)
throws SSLException {
}
#Override
public void verify(String host, String[] cns,
String[] subjectAlts) throws SSLException {
}
#Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
} catch (KeyManagementException e) {
logger.error(e.getMessage(), e);
} catch (NoSuchAlgorithmException e) {
logger.error(e.getMessage(), e);
} catch (KeyStoreException e) {
logger.error(e.getMessage(), e);
}
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", new PlainConnectionSocketFactory())
.register("https", sslsf)
.build();
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager(registry);
poolingConnManager.setMaxTotal(maxConnections);
poolingConnManager.setDefaultMaxPerRoute(maxConnections);
ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() {
#Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
return 60 * 1000;
}
};
if (proxyHost != null) {
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setProxy(proxy).setConnectionManager(poolingConnManager).setKeepAliveStrategy(keepAliveStrategy).build();
}else {
httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(poolingConnManager).setKeepAliveStrategy(keepAliveStrategy).build();
}
return httpClient;
}
public void setProxyHost(String proxyHost) {
this.proxyHost = proxyHost;
}
public void setProxyPort(Integer proxyPort) {
this.proxyPort = proxyPort;
}
public void setSocksProxy(boolean isSocksProxy) {
this.isSocksProxy = isSocksProxy;
}
}
And interface :
import org.apache.http.client.HttpClient;
public interface HttpClientFactory {
public HttpClient createNewClient();
}
After that You could use :
HttpClient httpClient = new BasicHttpClientFactory().createNewClient();
If You need any ideas how to merge it into Your project, just post some info - maybe i'll come up with some ideas ;)
I am trying to interact with a webservice which is a HTTPS call that works totally fine on different variants of 4.0(I havent checked it below 4.0 so I cant say about them) and its perfectly working. The issue I am facing is on Android 5.0 and the device I was able to grab was Nexus 5 and below is the exception i get when doing connectivity
javax.net.ssl.SSLPeerUnverifiedException: No peer certificate
at org.apache.harmony.xnet.provider.jsse.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:146)
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:93)
After tonnes of searching and analyzing our production server SSL certificate i figured out that the server accept TLSv1 and the only cipher suite it supports is TLS_RSA_WITH_3DES_EDE_CBC_SHA. Though i understand that its not safe and it should be upgraded but right now i have to find out some way to get my Android app connected with the server.
I tried through the way suggested on this page
https://code.google.com/p/android-developer-preview/issues/attachmentText?id=1200&aid=12000009000&name=CompatSSLSocketFactory.java&token=ABZ6GAcWKpRZhuG6Skof32VtvF0Lzv3Z-A%3A1435550700632
And replaced my required algorithm i.e TLS_RSA_WITH_3DES_EDE_CBC_SHA but now the problem is that i am seeing this exception
Caused by: java.lang.IllegalArgumentException: cipherSuite
TLS_RSA_WITH_3DES_EDE_CBC_SHA is not supported.
at com.android.org.conscrypt.NativeCrypto.checkEnabledCipherSuites(NativeCrypto.java:1091)
at com.android.org.conscrypt.SSLParametersImpl.setEnabledCipherSuites(SSLParametersImpl.java:244)
at com.android.org.conscrypt.OpenSSLSocketImpl.setEnabledCipherSuites(OpenSSLSocketImpl.java:822)
So according to this exception the cipher suite i required is not supported by Android 5.0. But i got puzzled after seeing it in Android 5.0's supported list on this page
http://developer.android.com/reference/javax/net/ssl/SSLEngine.html
Anybody any idea whats this mystery?
I got the answer finally after working out on the issue for three days. Posting out the correct solution for people who gets stuck in a similar issue in future
First implement CustomTrustManager
public class CustomX509TrustManager implements X509TrustManager {
#Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
#Override
public void checkServerTrusted(X509Certificate[] certs,
String authType) throws CertificateException {
// Here you can verify the servers certificate. (e.g. against one which is stored on mobile device)
// InputStream inStream = null;
// try {
// inStream = MeaApplication.loadCertAsInputStream();
// CertificateFactory cf = CertificateFactory.getInstance("X.509");
// X509Certificate ca = (X509Certificate)
// cf.generateCertificate(inStream);
// inStream.close();
//
// for (X509Certificate cert : certs) {
// // Verifing by public key
// cert.verify(ca.getPublicKey());
// }
// } catch (Exception e) {
// throw new IllegalArgumentException("Untrusted Certificate!");
// } finally {
// try {
// inStream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
Than implement your own Socket Factory
public class CustomSSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
public CustomSSLSocketFactory(KeyStore truststore)
throws NoSuchAlgorithmException, KeyManagementException,
KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new CustomX509TrustManager();
sslContext.init(null, new TrustManager[] { tm }, null);
}
public CustomSSLSocketFactory(SSLContext context)
throws KeyManagementException, NoSuchAlgorithmException,
KeyStoreException, UnrecoverableKeyException {
super(null);
sslContext = context;
}
#Override
public Socket createSocket(Socket socket, String host, int port,
boolean autoClose) throws IOException, UnknownHostException {
Socket newSocket = sslContext.getSocketFactory().createSocket(socket, host, port,
autoClose);
((SSLSocket) newSocket).setEnabledCipherSuites(((SSLSocket) newSocket).getSupportedCipherSuites());
AdjustSocket(newSocket);
return newSocket;
}
#Override
public Socket createSocket() throws IOException {
Socket socket = sslContext.getSocketFactory().createSocket();
((SSLSocket) socket).setEnabledCipherSuites(((SSLSocket) socket).getSupportedCipherSuites());
adjustSocket(socket);
return socket;
}
private void adjustSocket(Socket socket)
{
String[] cipherSuites = ((SSLSocket) socket).getSSLParameters().getCipherSuites();
ArrayList<String> cipherSuiteList = new ArrayList<String>(Arrays.asList(cipherSuites));
cipherSuiteList.add("TLS_RSA_WITH_3DES_EDE_CBC_SHA");
cipherSuites = cipherSuiteList.toArray(new String[cipherSuiteList.size()]);
((SSLSocket) socket).getSSLParameters().setCipherSuites(cipherSuites);
String[] protocols = ((SSLSocket) socket).getSSLParameters().getProtocols();
ArrayList<String> protocolList = new ArrayList<String>(Arrays.asList(protocols));
for (int ii = protocolList.size() - 1; ii >= 0; --ii )
{
if ((protocolList.get(ii).contains("SSLv3")) || (protocolList.get(ii).contains("TLSv1.1")) || (protocolList.get(ii).contains("TLSv1.2")))
protocolList.remove(ii);
}
protocols = protocolList.toArray(new String[protocolList.size()]);
((SSLSocket)socket).setEnabledProtocols(protocols);
}
}
Now add a function in the class to create a HttpClient
public HttpClient createHttpClient(){
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
CustomSSLSocketFactory sf = new CustomSSLSocketFactory(trustStore);
sf.setHostnameVerifier(CustomSSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 15000);
HttpConnectionParams.setSoTimeout(params, 5000);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
And now write below lines to call the server/webservice
HttpClient httpClient = createHttpClient();
HttpPost httpost = new HttpPost(url);
HttpResponse response = null;
try {
response = httpClient.execute(httpost);
StatusLine statusLine = response.getStatusLine();
} catch (IOException e) {
e.printStackTrace();
}