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.
Related
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.
I am building an Android App which communicates with my REST API that is protected by Spring Security.
Since the Android App is "public" and no keys etc is secure I want to create diffrent obstacles and make things complicated to protect my API as much as possible.
One way in which I would like to add more security is to make sure that the one calling my API has a certificate. I don't want to create thousands of certificates in my APIs trust-store so I just want to make sure that the caller have one single certificate that I hid away in a keystore in my Android app.
In the examples I have found it seems like a "normal" X509Certificate authentication in Spring Security requires a unique certificate for every user and then this certificate replaces Basic auth or JWT auth. I would like to have individual client JWT tokens but make sure that every call brings my ONE Android App certificate to make (more) sure that someone is calling my API from my Android app.
Is this possible or is it just not what it is for?
When you create a RestTemplate you can configure it with a keystore and trust-store so in that end it should be easy. But as for protecting my REST API it seems more difficult since I want both certificate + JWT token or Basic auth.
I am not using XML configuration for my securityconfig. I instead extend WebSecurityConfigurerAdapter. It would be great if this was configurable in the configure(HttpSecurity http) method, but I'm thinking that maybe I could achieve this in a OncePerRequestFilter somehow? Perhaps configure a filter before my JwtAuthFilter?
Edit:
In all the examples I have found for configuration of spring security they always seems to use the certificate as an authentication. I just want to configure so that when someone call example.com/api/** it checks so that the certificate is approved by my custom trust store (so that I "know" it is probably a call from my app) but if someone call example.com/website it should use the default java trust store.
If someone call example.com/api/** I would like my server to
check certificate and kill the connection if the certificate is not approved in my custom truststore.
If certificate is ok, establish https (or move on if I can't kill the connection before it have already established https-connection) to user auth with Basic-/JWT-authentication.
I think I figured it out. Here is how I configured it and it seems to work.
The "/**" endpoint is the website which should work with any browser without any specific certificate, but it requires Admin authority (you need to login as admin).
The "/api/**" and "/connect/**" endpoints require the correct certificate, the correct API-key and valid Basic- or JWT-token authentification.
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/**").hasRole("ADMIN")
.and()
.formLogin()
.loginPage("/loginForm")
.loginProcessingUrl("/authenticateTheUser")
.permitAll()
.and()
.logout()
.permitAll().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS);
http.requestMatchers()
.antMatchers("/connect/**","/api/**")
.and()
.addFilterBefore(new APIKeyFilter(null), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new JwtAuthorizationFilter(), BasicAuthenticationFilter.class)
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.httpBasic()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.authorizeRequests()
.antMatchers("/connect/**").hasAnyRole("MASTER,APPCALLER,NEGOTIATOR,MEMBER")
.antMatchers("/api/**").hasAnyRole("MASTER,MEMBER,ANONYMOUS");
}
The ApiKeyFilter class is the one that check the api-key and also make sure that the certificate used in the call is approved in my server trust-store. The api-key check is all that I had to configure, the extended X509AuthenticationFilter will automatically check the request certificate. My ApiKeyFilter looks like this:
public class APIKeyFilter extends X509AuthenticationFilter {
private String principalRequestHeader = "x-api-key";
private String apiKey = "XXXX";
public APIKeyFilter(String principalRequestHeader) {
if (principalRequestHeader != null) {
this.principalRequestHeader = principalRequestHeader;
}
setAuthenticationManager(new AuthenticationManager() {
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if(authentication.getPrincipal() == null) {
throw new BadCredentialsException("Access Denied.");
}
String rApiKey = (String) authentication.getPrincipal();
if (authentication.getPrincipal() != null && apiKey.equals(rApiKey)) {
return authentication;
} else {
throw new BadCredentialsException("Access Denied.");
}
}
});
}
#Override
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
return request.getHeader(principalRequestHeader);
}
#Override
protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
X509Certificate[] certificates = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
if (certificates != null && certificates.length > 0) {
return certificates[0].getSubjectDN();
}
return super.getPreAuthenticatedCredentials(request);
}
}
Cred goes to these resources that helped me put things together:
Spring Boot - require api key AND x509, but not for all endpoints
spring security http antMatcher with multiple paths
I am developing an Android project.
I have a PEM certificate string:
-----BEGIN CERTIFICATE-----
MIIEczCCA1ugAwIBAgIBADANBgkqhkiG9w0BAQQFAD..AkGA1UEBhMCR0Ix
EzARBgNVBAgTClNvbWUtU3RhdGUxFDASBgNVBAoTC0..0EgTHRkMTcwNQYD
VQQLEy5DbGFzcyAxIFB1YmxpYyBQcmltYXJ5IENlcn..XRpb24gQXV0aG9y
...MANY LINES...
It8una2gY4l2O//on88r5IWJlm1L0oA8e4fR2yrBHX..adsGeFKkyNrwGi/
7vQMfXdGsRrXNGRGnX+vWDZ3/zWI0joDtCkNnqEpVn..HoX
-----END CERTIFICATE-----
(assigned above certificate string to a variable named CERT_STR)
I decode above PEM string to byte array:
byte[] pemBytes = Base64.decode(
CERT_STR.replaceAll("-----(BEGIN|END) CERTIFICATE-----", "")
.replaceAll("\n", "")
.getBytes("UTF-8"),
Base64.DEFAULT
);
I try to programmatically install the PEM certificate to my Android phone by following code:
Intent intent = KeyChain.createInstallIntent();
// because my PEM only contains a certificate, no private key, so I use EXTRA_CERTIFICATE
intent.putExtra(KeyChain.EXTRA_CERTIFICATE, pemBytes);// above PEM bytes
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
When run my code (in Android 7 device), the Android system certificate installer app pops up the window, when I press "OK" button of that window, I got following log:
java.io.IOException: stream does not represent a PKCS12 key store
at com.android.org.bouncycastle.jcajce.provider.keystore.pkcs12.PKCS12KeyStoreSpi.engineLoad(PKCS12KeyStoreSpi.java:793)
at java.security.KeyStore.load(KeyStore.java:1247)
at com.android.certinstaller.CredentialHelper.loadPkcs12Internal(CredentialHelper.java:396)
at com.android.certinstaller.CredentialHelper.extractPkcs12Internal(CredentialHelper.java:364)
at com.android.certinstaller.CredentialHelper.extractPkcs12(CredentialHelper.java:354)
at com.android.certinstaller.CertInstaller$1.doInBackground(CertInstaller.java:328)
at com.android.certinstaller.CertInstaller$1.doInBackground(CertInstaller.java:327)
My questions:
I have used EXTRA_CERTIFICATE & set it to intent, I am NOT using EXTRA_PKCS12, but from the log, Android system thinks I am installing PKCS#12 keystore. Why?
What is the correct way to programmatically install PEM certificate in Android?
Your code should work, as said #Sergey Nikitin. This starred example at Github is using similar code
I have reviewed the Android 7.1 source code of CredentialHelper and CertInstaller to trace your exception log. The unique reachable path to execute the pkcs12 loader at
com.android.certinstaller.CredentialHelper.extractPkcs12(CredentialHelper.java:354)
is the method onScreenlockOk
private void onScreenlockOk() {
if (mCredentials.hasPkcs12KeyStore()) {
if (mCredentials.hasPassword()) {
showDialog(PKCS12_PASSWORD_DIALOG);
} else {
new Pkcs12ExtractAction("").run(this);
}
which is protected by CredentialHelper.hasPkcs12KeyStore()
boolean hasPkcs12KeyStore() {
return mBundle.containsKey(KeyChain.EXTRA_PKCS12);
}
I have not found default assigned values or alternative paths, so I deduce that KeyChain.EXTRA_PKCS12 is being used in some way. It is a weird behaviour, may be you have a clean&rebuild issue?
I suggest to debug the code including Android CertInstaller class to ensure the values of the Extras and ensure that the executed code is the expected
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.
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.