Public Key pinning with X509TrustManagerExtensions checkServerTrusted - android

Public key pinning in for a HTTPS TLS connection.
There is an issue with Android API, below 17, that enables MITM (Man in the Middle) attack incase of public key pinning. This has been explained in the link below.
https://www.cigital.com/blog/ineffective-certificate-pinning-implementations/
So in Android minimum sdk below 17, ie, below Android version 4.2, we need to initialise the X509TrustManager with Android Keystore which has only the server root certificates (instead of the default keystore; which would have all certificates installed in the device). This helps in cleaning the leaf certificates received from the server before performing public key pinning.
From Android API 17 onwards, Android has introduced X509TrustManagerExtensions which performs this root cleaning at OS level.
https://developer.android.com/reference/android/net/http/X509TrustManagerExtensions.html
My question:
I would be glad if anyone could please provide an example on how to implement the following method provided by the X509TrustManagerExtensions for root cleaning.
List<X509Certificate> checkServerTrusted (X509Certificate[] chain,
String authType,
String host)
I am confused with the following.
host; should it be the domain URL? with https or without? or should it be the full url (domain + relative path)
How to create instant of a X509TrustManagerExtensions?
The constructor for X509TrustManagerExtensions takes X509TrustManager as input. Do we create this X509TrustManager with the android default keystore?
Code snippet (Not working):
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(KeyStore.getInstance(KeyStore.getDefaultType()));
for (TrustManager trustManager : tmf.getTrustManagers()) {
X509TrustManagerExtensions tme = new X509TrustManagerExtensions((X509TrustManager) trustManager);
tme.checkServerTrusted(chain, authType, <<String https://www.example.com>>);
}
Exception:
Trust anchor for certification path not found
Possible security risk:
Using KeyStore.getDefaultType()
Any help would be greatly appreciated.

Firstly you need to get hold of the trust manager by using the TrustManagerFactory. When initialising this you pass in null for it to use the default Keystore and it will return the default trust managers. With this you can then create the X509TrustManagerExtensions using the first X509TrustManager.
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
// Find first X509TrustManager in the TrustManagerFactory
X509TrustManager x509TrustManager = null;
for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
if (trustManager instanceof X509TrustManager) {
x509TrustManager = (X509TrustManager) trustManager;
break;
}
}
X509TrustManagerExtensions x509TrustManagerExtensions =
new X509TrustManagerExtensions(trustManager());
Then to execute this the host I've successfully used just the domain part:
List<X509Certificate> trustedCerts = x509TrustManagerExtensions
.checkServerTrusted(untrustedCerts, "RSA", "appmattus.com");
For those using HttpUrlConnection the the untrusted certs is determined with:
Certificate[] serverCerts = ((HttpsUrlConnection)conn).getServerCertificates();
X509Certificate[] untrustedCerts = Arrays.copyOf(serverCerts,
serverCerts.length,
X509Certificate[].class);
If you are using OkHttp then you can just use the built in CertificatePinner that has since been updated to fix the issues mentioned in that article.

Related

Check if client certificate is already installed in Android Programatically

I have an android app where I am installing the client certificate using the following code.
val inputStream: InputStream = resources.openRawResource(R.raw.client)
val intent = KeyChain.createInstallIntent()
val p12: ByteArray = inputStream.readBytes()
intent.putExtra(KeyChain.EXTRA_PKCS12, p12)
intent.putExtra(KeyChain.EXTRA_NAME, "Sample cert")
startActivityForResult(intent,3)
Now once user installs the certificate, I dont want to repeat this again so I want to check if the certificate is already installed.
I used the following code to check it, but doest get the certificate with both "AndroidCAStore" and "PKCS12".
"AndroidCAStore" - returns all trusted CA certs but my certificate is in user credentials.
"PKCS12" - IS empty
//val ks = KeyStore.getInstance("AndroidCAStore")
val ks: KeyStore = KeyStore.getInstance("PKCS12")
if (ks != null) {
ks.load(null, null)
val aliases = ks.aliases()
while (aliases.hasMoreElements()) {
val alias = aliases.nextElement() as String
val cert = ks.getCertificate(alias) as X509Certificate
Log.d("Cert ---->",cert.issuerDN.name)
if (cert.issuerDN.name.contains(issuerDn)) {
return true
}
}
}
Can some one help me fix this.
When you call
val intent = KeyChain.createInstallIntent()
you are storing the Certificate in the Android Keychain and I don't think there's a way of accessing the Certificates stored there programatecally, see this unanswered post.
Since you want to check if the certificate was installed in the KeyChain, you can call KeyChain.getPrivateKey() or KeyChain.getCertificateChain() and if they return null, then it means that the Certificate has not been installed yet.
Note: You have the limitation that you have to call KeyChain.choosePrivateKeyAlias first to establish trust between the app and the KeyChain, otherwise you'll get a KeyChain exception.
If you don't need to use the KeyChain, then you can simply create your own KeyStore and add your certificates to it. Then you will be able to call aliases() to get all of the aliases of the certificates in the KeyStore.

nv-websocket-client self-signed certificate

I am trying to connect to a WSS server on my intranet with a self signed certificate. I have used Volley for HTTPS and TooTallNate library for WSS and I have been able to set SSLContext to accept all certificates. I am currently switching to nv-websocket-client so that I can add custom headers but, for the love of god, cant seem to bypass SSL certificate verification. I continue to run into the error message "The certificate of the peer...does not match the expected hostname". The code is exactly what is in the docs? is something different in v2.2? Here is the code I am using,
SSLContext context = NaiveSSLContext.getInstance("TLS");
ws = new WebSocketFactory().setSSLContext(context).setConnectionTimeout(5000)
.createSocket("wss://192.168.1.164/chat/")
.addListener(new WebSocketAdapter() {
#Override
public void onTextMessage(WebSocket websocket, String message) {
// Received a text message.
}
#Override
public void onConnectError(WebSocket websocket, WebSocketException e){
mTextView.setText(e.getMessage());
}
});
ws.connectAsynchronously();`
Can somebody help me. Thank you!
The author for the package has addressed it as an issue with a new feature in v2.3
WebSocketFactory.setVerifyHostname(false)
https://github.com/TakahikoKawasaki/nv-websocket-client/issues/116

OkHttpClient.Builder sslSocketFactory is deprecated [duplicate]

I am working on an Android app that requires Client Certificate Authentication (with PKCS 12 files).
Following the deprecation of all that's apache.http.*, we have started a pretty big work of refactoring on our network layer, and we have decided to go with OkHttp as a replacement, and so far I like that very much.
However, I haven't found any other way to handle client certificate auth without using SSLSocketFactory, with OkHttp or anything else for that matter. So what would be the best course of action in this particular case?
Is there another way with OkHttp to handle this sort of authentication?
if you are using https, you have to use a valid certificate. During your dev stage you have to trust the certificate, how?
sslSocketFactory(SSLSocketFactory sslSocketFactory) is deprecated and it's replaced by sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager), you have to update your gradle file
the piece of code below will help you to get a trusted OkHttpClient that trusts any ssl certificate.
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
}
X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[] { trustManager }, null);
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient client = new OkHttpClient.Builder().sslSocketFactory(sslSocketFactory, trustManager);
Apparently, there are two SSLSocketFactory classes. HttpClient has its own one, and that is deprecated along with the rest of HttpClient. However, everybody else will be using the more conventional javax.net.ssl edition of SSLSocketFactory, which is not deprecated (thank $DEITY).

Avoid "Accept unknown certificate" warning in android while using xmpp

I am trying to search on XMPP. I got the code from here. It works fine and I am able to connect to the server. But its showing the alert window like this
and If I click "Always" or "Once" it is accepting and I am able to show the contacts and chat messages....
Is there any way to stop this alert and can I connect directly to the server?
This message is displayed by MemorizingTrustManager (MTM), an Android library aimed to improve the security/usability trade-off for "private cloud" SSL installations.
MTM issues this warning whenever you connect to a server with a certificate not issued by one of the Android OS trusted Root CAs, like a self-signed certificate or one by CACert.
If the message appears again after you clicked "Always", this is a bug in MTM (probably due to a mismatching SSL server name), and should be reported via github.
Edit: if you are making an app that only communicates with one server, and you know the server's certificate in advance, you should replace MTM with AndroidPinning, which ensures that nobody can make man-in-the-middle attacks on your connection.
Disclaimer: I am the author of MTM and the mainainer of yaxim.
Get the certificate signed by a certificate authority. Forget all coding solutions.
Is there any way to stop this alert and can I connect directly to the server?
Its not clear to me if you wrote this app that connects to kluebook.com. I think you did, but its not explicit.
Assuming you wrote the app and know the server you are connecting to (kluebook.com), you should provide a custom TrustManager to handle this. You can find code for a custom TrustManger that works with the expected server certificate in OWASP's Certificate and Public Key Pinning example. Its OK to pin because you know what the certificate or public key is, and there's no need to trust someone else like a CA.
If you have no a priori knowledge, then you trust on first use and follow with a key continuity strategy looking for abrupt changes in the certificate or public key. In this case, the trust on first use should include the customary X509 checks.
Pinning is part of an overall security diversification strategy. A great book on the subject is Peter Gutmann's Engineering Security.
What you are seeing with the prompt is one leg of the strategy - namely, the Trust-On-First-Use (TOFU) strategy. The prompt has marginal value because user's don't know how to respond to it, so they just click yes to dismiss the box so they can continue what they are doing. Peter Gutmann has a great write-up on user psychology (complete with Security UI studies) in Engineering Security.
From section 6.1 of OWASP's Certificate and Public Key Pinning:
public final class PubKeyManager implements X509TrustManager
{
private static String PUB_KEY = "30820122300d06092a864886f70d0101...";
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException
{
if (chain == null) {
throw new IllegalArgumentException("checkServerTrusted: X509Certificate array is null");
}
if (!(chain.length > 0)) {
throw new IllegalArgumentException("checkServerTrusted: X509Certificate is empty");
}
if (!(null != authType && authType.equalsIgnoreCase("RSA"))) {
throw new CertificateException("checkServerTrusted: AuthType is not RSA");
}
// Perform customary SSL/TLS checks
try {
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init((KeyStore) null);
for (TrustManager trustManager : tmf.getTrustManagers()) {
((X509TrustManager) trustManager).checkServerTrusted(chain, authType);
}
} catch (Exception e) {
throw new CertificateException(e);
}
// Hack ahead: BigInteger and toString(). We know a DER encoded Public Key begins
// with 0x30 (ASN.1 SEQUENCE and CONSTRUCTED), so there is no leading 0x00 to drop.
RSAPublicKey pubkey = (RSAPublicKey) chain[0].getPublicKey();
String encoded = new BigInteger(1 /* positive */, pubkey.getEncoded()).toString(16);
// Pin it!
final boolean expected = PUB_KEY.equalsIgnoreCase(encoded);
if (!expected) {
throw new CertificateException("checkServerTrusted: Expected public key: "
+ PUB_KEY + ", got public key:" + encoded);
}
}
}
}
You can get the expected public key from OpenSSL's s_client, but you have to know the port. I can't get a response from the well known SSL ports like 5223, and 5222 has no security services:
$ openssl s_client -connect kluebook.com:5222
CONNECTED(00000003)
140735088755164:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:s23_clnt.c:766:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 7 bytes and written 322 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
---
Once you get a public key, plug it back into the TrustManager at PUB_KEY.

Android manual X509 certificate chain validation

I have implemented javax.net.ssl.X509TrustManager in my code so I can validate my self-signed cert, which my software accesses. However, I still need to validate some other "standard" website SSL certificates. I am using CertPathValidator.validate() to do that, but I just realized that one cert chain I am being passed (for maps.googleapis.com) doesn't actually contain the complete chain - it contains the whole chain but the Root CA (Equifax), which does exist on the phone, but validate() still fails because (apparently) it's not explicitly in the chain. What am I missing here, so that the validation succeeds? Thanks for any input.
Edit - Relevant code (with exception checking removed):
CertificateFactory cf = CertificateFactory.getInstance("X.509");
// chain is of type X509Certificate[]
CertPath cp = cf.generateCertPath(Arrays.asList(chain));
CertPathValidator cpv = CertPathValidator.getInstance(CertPathValidator.getDefaultType());
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream is = new FileInputStream("/system/etc/security/cacerts.bks");
ks.load(is, null);
PKIXParameters params = new PKIXParameters(ks);
CertPathValidatorResult cpvr = cpv.validate(cp, params);
Implementing your own TrustManager is generally a bad idea. The better way is to add your certificates to a keystore, and add it as a trust store. See this for an example of how to do it.
You probably need to add the default trust store to your validator. Also, Android does not do revocation (CRL) checking by default, so if you enabled it, you need to get the related CRL's manually. Post your code.

Categories

Resources