SSL connection reusing and caching with Android OkHttpClient - android

I am using Retrofit and OkHttp to perform all network operations like GET, POST for both HTTP and HTTPS url. Everything is working fine but except that i have a requirement to reuse the sessions in order to reduce the Handshake timing process for each and every service calls. As of now the server takes more than 800ms to initiate the handshake between client and server for all the service calls.
What I need:
I have to reuse the SSLSessions in order to make handshake happen only for the first time or during specific intervals.
Code I am using for SSL using Okhttp and Retrofit:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseURL)
.addConverterFactory(GsonConverterFactory.create())
.client(getOkHttpClient(context, new OkHttpClient(), context.getResources().openRawResource(R.raw.mysslcertificate)))
.build();
retrofit.create(apiClass);
public static OkHttpClient getOkHttpClient(Context context,OkHttpClient client, InputStream inputStream) {
try {
if (inputStream != null) {
SSLContext sslContext = sslContextForTrustedCertificates(inputStream);
if (sslContext != null) {
client = client.newBuilder()
.sslSocketFactory(sslContext.getSocketFactory()).build();
else {
CLog.i(Constants.LOG_TAG_HTTPLIBRARY,"GZip not done because it is not a Analytics data");
client = client.newBuilder()
.sslSocketFactory(sslContext.getSocketFactory()).build();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return client;
}
private static SSLContext sslContextForTrustedCertificates(InputStream in) {
try {
CertificateFactory e = CertificateFactory.getInstance("X.509");
Collection certificates = e.generateCertificates(in);
if (certificates.isEmpty()) {
throw new IllegalArgumentException("expected non-empty set of trusted certificates");
} else {
char[] password = "password".toCharArray();
KeyStore keyStore = newEmptyKeyStore(password);
int index = 0;
Iterator keyManagerFactory = certificates.iterator();
while (keyManagerFactory.hasNext()) {
Certificate trustManagerFactory = (Certificate) keyManagerFactory.next();
String sslContext = Integer.toString(index++);
keyStore.setCertificateEntry(sslContext, trustManagerFactory);
}
KeyManagerFactory var10 = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
var10.init(keyStore, password);
TrustManagerFactory var11 = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
var11.init(keyStore);
SSLContext var12 = SSLContext.getInstance("TLS");
var12.init(var10.getKeyManagers(), var11.getTrustManagers(), new SecureRandom());
return var12;
}
} catch (Exception var9) {
var9.printStackTrace();
}
return null;
}
What I have tried:
Since i couldn't find anything related to OkHttpClient but i tried referring few of the solutions like from the link as follows:
https://gist.github.com/codebutler/5565971
https://developer.android.com/reference/javax/net/ssl/SSLContext.html
But to be very frank nothing was helpful to me and I couldn't even find any relavant solutions for my requirement. In turn finally, I am completely stuck with this solution for the couple of weeks. Kindly help me to achieve my tasks through any of your tips and suggestions. Any piece of code or approach will be very useful to me. Thanks in advance.

Related

xamarin.android adding client certificate

I'm trying to send a request to a web api in Xamarin.Android. The api requires a client certificate. I followed the advice in this question: xamarin.ios httpclient clientcertificate not working with https, but I get a "method not implemented" exception. Can anyone help?
Here's my code:
string result = await CallApi(new System.Uri("myurl"));
protected async Task<string> CallApi(Uri url)
{
try
{
AndroidClientHandler clientHandler = new AndroidClientHandler();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Ssl3;
using (var mmstream = new MemoryStream())
{
Application.Context.Assets.Open("mycert.pfx").CopyTo(mmstream);
byte[] b = mmstream.ToArray();
X509Certificate2 cert = new X509Certificate2(b, "password", X509KeyStorageFlags.DefaultKeySet);
clientHandler.ClientCertificates.Add(cert);
}
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback((sender, certificate, chain, policyErrors) => { return true; });
HttpClient client = new HttpClient(clientHandler);
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
return responseBody;
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
return string.Empty;
}
}
In the post you mentioned probably the managed handler is used. Since this handler currently doesn't support TLS 1.2 you shouldn't use it, but instead really use the AndroidClientHandler (see also Xamarin and TLS 1.2).
Unfortunately ClientCertificates is indeed not implemented in AndroidClientHandler.
If you want to use client certificate with android you can extend the AndroidClientHandler:
using Java.Security;
using Java.Security.Cert;
using Javax.Net.Ssl;
using Xamarin.Android.Net;
using Xamarin.Forms;
public class AndroidHttpsClientHandler : AndroidClientHandler
{
private SSLContext sslContext;
public AndroidHttpsClientHandler(byte[] customCA, byte[] keystoreRaw) : base()
{
IKeyManager[] keyManagers = null;
ITrustManager[] trustManagers = null;
// client certificate
if (keystoreRaw != null)
{
using (MemoryStream memoryStream = new MemoryStream(keystoreRaw))
{
KeyStore keyStore = KeyStore.GetInstance("pkcs12");
keyStore.Load(memoryStream, clientCertPassword.ToCharArray());
KeyManagerFactory kmf = KeyManagerFactory.GetInstance("x509");
kmf.Init(keyStore, clientCertPassword.ToCharArray());
keyManagers = kmf.GetKeyManagers();
}
}
// custom truststore if you have your own ca
if (customCA != null)
{
CertificateFactory certFactory = CertificateFactory.GetInstance("X.509");
using (MemoryStream memoryStream = new MemoryStream(customCA))
{
KeyStore keyStore = KeyStore.GetInstance("pkcs12");
keyStore.Load(null, null);
keyStore.SetCertificateEntry("MyCA", certFactory.GenerateCertificate(memoryStream));
TrustManagerFactory tmf = TrustManagerFactory.GetInstance("x509");
tmf.Init(keyStore);
trustManagers = tmf.GetTrustManagers();
}
}
sslContext = SSLContext.GetInstance("TLS");
sslContext.Init(keyManagers, trustManagers, null);
}
protected override SSLSocketFactory ConfigureCustomSSLSocketFactory(HttpsURLConnection connection)
{
SSLSocketFactory socketFactory = sslContext.SocketFactory;
if (connection != null)
{
connection.SSLSocketFactory = socketFactory;
}
return socketFactory;
}
}
If you refer to AndroidClientHandler Source Code, you can find following statement:
AndroidClientHandler also supports requests to servers with "invalid" (e.g. self-signed) SSL certificates. Since this process is a bit convoluted using
the Java APIs, AndroidClientHandler defines two ways to handle the situation. First, easier, is to store the necessary certificates (either CA or server certificates)
in the collection or, after deriving a custom class from AndroidClientHandler, by overriding one or more methods provided for this purpose(, and ). The former method should be sufficient for most use cases...
So, for usage of AndroidClientHandler you should use clientHandler.TrustedCerts together with Java.Security.Cert.X509Certificate:
Java.Security.Cert.X509Certificate cert = null;
try
{
CertificateFactory factory = CertificateFactory.GetInstance("X.509");
using (var stream = Application.Context.Assets.Open("MyCert.pfx"))
{
cert = (Java.Security.Cert.X509Certificate)factory.GenerateCertificate(stream);
}
} catch (Exception e)
{
System.Console.WriteLine(e.Message);
}
if (clientHandler.TrustedCerts != null)
{
clientHandler.TrustedCerts.Add(cert);
}
else
{
clientHandler.TrustedCerts = new List<Certificate>();
clientHandler.TrustedCerts.Add(cert);
}
Notes: don't use Application.Context.Assets.Open("ca.pfx").CopyTo(mmstream); otherwise you will get inputstream is empty exception.

Getting OkHttp to accept self-signed certificate

I successfully got the server to use a certificate in the form of a JKS file. HTTPS is working as expected when used with web browsers and other web clients.
For Android, my team uses the following to persuade OkHttp to accept the certificate.
static KeyStore readKeyStore() throws KeyStoreException, CertificateException, NoSuchAlgorithmException
{
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
// get user password and file input stream
char[] password = "password".toCharArray();
java.io.InputStream fis = null;
try {
fis = ServiceProducer.class.getClassLoader().getResourceAsStream("res/raw/keystore.jks");
ks.load(fis, password);
} catch (IOException e)
{
} finally
{
if (fis != null)
{
try
{
fis.close();
} catch (IOException e)
{
}
}
}
return ks;
}
The code that uses the key:
OkHttpClient.Builder builder = new OkHttpClient.Builder();
KeyStore keyStore = readKeyStore();
SSLContext sslContext = SSLContext.getInstance("SSL");
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, "password".toCharArray());
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
builder.sslSocketFactory(sslContext.getSocketFactory());
OkHttpClient client = builder.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://192.168.5.91:9443")
.addConverterFactory(JacksonConverterFactory.create())
.client(client)
.build();
However, accessing the service throws the following exception:
java.security.cert.CertPathValidationException: Trust anchor for certification path not found.
Have we done the certificate installation correctly? Or are we facing a different kind of problem?

SSL Certificate Pinning w/ Picasso

I am using Picasso to cache Images. Our backend recently switched to HTTPS using self signed certificate pinning as authentication. I used the khandroid library to create an HTTP client that pins the certificates to each request; basically following this example.
http://ogrelab.ikratko.com/using-android-volley-with-self-signed-certificate/
I now need to apply this same concept to Picasso but am unsure how to modify Picasso's singleton to use pinned SSL certificates.
Turns out I was Just looking in the wrong place. I was attempting to modify the OkHttpDownloader, but I needed to modify the OkHttpClient. Here is some sample code.
public static Picasso getInstance(Context context) {
if (sPicasso == null) {
InputStream keyStore = context.getResources().openRawResource(R.raw.my_keystore);
Picasso.Builder builder = new Picasso.Builder(context);
OkHttpClient okHttpClient = new OkHttpClient();
SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{new SsX509TrustManager(keyStore, password)}, null);
okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());
OkHttpDownloader okHttpDownloader = new OkHttpDownloader(okHttpClient);
builder.downloader(okHttpDownloader);
sPicasso = builder.build();
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Failure initializing default SSL context", e);
} catch (KeyManagementException e) {
throw new IllegalStateException("Failure initializing default SSL context", e);
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
}
return sPicasso;
}

SSL Pinning with Volley network library on Android

I want to use SSL Pinning in volley network library. Is there any way to implement SSL pinning with volley? Does volley provide this support for security improvements?
I just implemented it like described here: http://blog.ostorlab.co/2016/05/ssl-pinning-in-android-networking.html
Here is the needed code for a volley-implementation:
CertificateFactory cf = CertificateFactory.getInstance("X.509");
// Generate the certificate using the certificate file under res/raw/cert.cer
InputStream caInput = new BufferedInputStream(getResources().openRawResource(R.raw.cert));
Certificate ca = cf.generateCertificate(caInput);
caInput.close();
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore trusted = KeyStore.getInstance(keyStoreType);
trusted.load(null, null);
trusted.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(trusted);
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
SSLSocketFactory sf = context.getSocketFactory();
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext(), new HurlStack(null, sf));
Seems to work!
I just looked into the same thing for a project I am working on. The position I am in may be different to you however.
I am using Volley with an OKHttp Network stack (https://gist.github.com/JakeWharton/5616899):
Add these to your Gradle Build:1
compile "com.squareup.okhttp:okhttp:2.7.5"
compile "com.squareup.okhttp:okhttp-urlconnection:2.7.5"
Add a OKHttpStack class;
public class OKHttpStack extends HurlStack {
private final OkUrlFactory okUrlFactory;
public OKHttpStack() {
this(new OkUrlFactory(
new OkHttpClient.Builder()
.certificatePinner(
new CertificatePinner.Builder()
.add("example.com", "sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=") //This is the cert
.build())
.build();
));
}
public OKHttpStack(OkUrlFactory okUrlFactory) {
if (okUrlFactory == null) {
throw new NullPointerException("Client must not be null.");
}
this.okUrlFactory = okUrlFactory;
}
#Override
protected HttpURLConnection createConnection(URL url) throws IOException {
return okUrlFactory.open(url);
}
}
When you then create your RequestQueue do something like:
Network network = new BasicNetwork(new OKHttpStack());
File cacheDir = new File(context.getCacheDir(), "volley");
int threads = 4;
mRequestQueue = new RequestQueue(new DiskBasedCache(cacheDir), network, threads);
Please note I have yet to test this, we are thinking about pinning at the moment.
Good luck!
Gav
References:
https://gist.github.com/JakeWharton/5616899
https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/CertificatePinning.java
You can use public key pinning instead of certificate pinning:
Public Key Pinning with Volley Library
I am implementing the same exact thing. I found a blog post that will hopefully be of help to you
http://ogrelab.ikratko.com/using-android-volley-with-self-signed-certificate/
You can use network_security_config.xml, more info : https://developer.android.com/training/articles/security-config

How to use Onionkit with Volley

The app I am working on uses Onionkit to do TSL/SSL certificate verification. I added Volley support in the app, but realized that Volley only supports the Apache HttpClient, while Onionkit uses the boye.androidlib HttpClient. So these 2 do not work together.
Right now I am using the fork of Volley at here https://github.com/kulik/volley.git, it works with the boye library so my app is working.
However I would rather just use Volley. Is there a way to make it work? I looked at HurlStack class, it has the SSLSocketFactory field. I suppose this one will work for the Cert verification. But I have not figured out a way to get it work. Sorry for the kind of vague question but I am not a security expert. When using the Onikit, I passed in the cert pins to the TrustManager. However I have not found a way to link the SSLFactory with the TrustManager. Any help will be appreciated.
Thanks
Ray
You can use HurlStack to use different HttpClient implementations. For example, see how to use OkHttp with Volley:
public class OkHttpStack extends HurlStack {
private final OkHttpClient client;
public OkHttpStack() {
this(new OkHttpClient());
}
public OkHttpStack(OkHttpClient client) {
if (client == null) {
throw new NullPointerException("Client must not be null.");
}
this.client = client;
}
#Override protected HttpURLConnection createConnection(URL url) throws IOException {
return client.open(url);
}
}
and use it with
Volley.newRequestQueue(context, new OkHttpStack())
It should be easy to derive how to use your http client from that. If you want to use your own SSL logic you can overwrite this method from HurlStack
private static SSLSocketFactory createPinnedSSLCertFactory(Context ctx) {
//create your implementation
}
I dont really know what exactly you want to do here but here is an example that loads an empty keystore and pins it to only 1 cert (any others would not be accepted -> ssl pinning)
private static SSLSocketFactory createPinnedSSLCertFactory(Context ctx) {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate myCert = //read certificate in;
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null); //inputstream null creates new keystore
keyStore.setCertificateEntry("mycert", myCert );
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
return context.getSocketFactory();
}
Note: I had problems with creating my own SSLFactory with Gingerbread (2.3) and lower meaning it didn't work.

Categories

Resources