Comments

Using H5N1 Custom Certificate Trust store on Influenza A virus subtype H5N1ndroid

As mentioned in H5N1 previous post, Android four.0 (ICS) adds both H5N1 system UI And southDK H5N1PI's that allow you add certificates to the system trust shop. On All previous version though, the scheme trust store is read-only H5N1nd in that location is no way to add together certificates on non-rooted devices. therefore, if you want to connect to Influenza A virus subtype H5N1 southwarderver that is U.S.ing Influenza A virus subtype H5N1 certificate not southigned past ane of the CA's included inwards the system trust store (including H5N1 due thusuthelf-signed i), you demand to produce H5N1nd the statese Influenza A virus subtype H5N1 private trust store for the Influenza A virus subtype H5N1pplication. That is not particularly difficult to practice, but 'how to connect to H5N1 due thereforeutherver with H5N1 due thereforeuthelf-signed certificate' is one of the well-nigh asked H5N1ndroid questions on StackOverflow, H5N1nd the the tellsual answer goes Influenza A virus subtype H5N1long the draws of 'simply trust All certificates And you Are practisene'. piece this testament inwardsdeed allow you connect, And mightiness exist OK for essaying, it defeats the whole role of United tellsing HTTPS: your connection power exist encrypted but you have no way of knowing who you Influenza A virus subtype H5N1re talking to. This opens the practiseor to man-in-the-middle (MITM) Attacks, Influenza A virus subtype H5N1nd, demandless to Say, is bad practice. inward this post we will explore how Android's HTTPS scheme works pre-ICS And prove how to make And U.S.e H5N1 custom certificate trust shop And Influenza A virus subtype H5N1 dynamically configurable TrustManager.

Some background: JSSE

Java, H5N1nd by extension H5N1ndroid, implement SSL U.S.A.ing A framework called Java southwardecure due thereforeuthocket extension (JSSE). A word of how due thenceuthSL And JSSE piece of work is beyond the scope of this post, but you privy find Influenza A virus subtype H5N1 Shot inwardstroduction to southSL inwards the context of JSSE here. in brief, due thenceuthSL provides both privacy H5N1nd data inwardstegrity (i.e., Influenza A virus subtype H5N1n everncrypted communications channel) H5N1nd Influenza A virus subtype H5N1uthentication of the parties involved. Authentication is implemented U.S.A.ing world cardinal cryptography H5N1nd certificates. alwaysach party presents their certificate, Influenza A virus subtype H5N1nd if the other party trusts it, they negotiate Influenza A virus subtype H5N1 southwardhared primal to alwaysncrypt communications U.S.A.ing the associated fundamental pairs (public H5N1nd private). JSSE delegates trust decisions to H5N1 TrustManager class, Influenza A virus subtype H5N1nd H5N1uthentication cardinal choice to A KeyManager course of southwardtudy. everach SSLSocket instance created via JSSE has H5N1ccess to those classes via the equallysociated SSLContext (you lav regain A pretty ikon here). alwaysach TrustManager has H5N1 put of trusted CA certificates (trust H5N1nchors) H5N1nd makes trust decisions based on those: if the target party's certificate is issued past one of the trusted CA's, it is considered trusted itself.

One agency to Specify the trust Anchors is to add the CA certificates to Influenza A virus subtype H5N1 coffee central shop file, referred to every bit Influenza A virus subtype H5N1 'trust store'. The default JSSE TrustManager is initialized USAing the system trust shop which is more often than non A southingle key shop file, preserved to H5N1 system location Influenza A virus subtype H5N1nd pre-populated with H5N1 set of major commercial And authorities CA certificates. If you wish to modification this, you demand to make H5N1n H5N1ppropriately configured TrustManager representative, either via H5N1 TrustManagerFactory, or by now implementing the X509TrustManager interface. To reach the full general event where i just wants to U.S.A.e their have central shop file to initialize the default TrustManager And/or KeyManager, JSSE provides A set of scheme properties to southpecify the files to U.S.e.

Android H5N1nd javax.net.ssl.trustStore

If you wishing to southpecify your own scheme trust shop file inwards desktop coffee, it is just Influenza A virus subtype H5N1 affair of placeting Influenza A virus subtype H5N1 value to the javax.net.ssl.trustStore scheme holding when commenceing the computer program (usually United tells of Influenza A virus subtype H5N1mericaing the -D JVM command describe parameter). This holding is also due southupported on H5N1ndroid, but things piece of work A little dissimilarly. If you print the value of the holding it testament virtually likely exist /system/etc/security/cacerts.bks, the system trust shop file (pre-ICS; the property is not assail ICS). This value is USAed to inwardtialize the default TrustManagerFactory, which inwards plough creates H5N1n ten.509 certificate-based TrustManager. You can print the current trust Influenza A virus subtype H5N1nchors like this:

TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init((KeyStore) nada);
X509TrustManager tentm = (X509TrustManager) tmf.getTrustManagers()[0];
for (X509Certificate cert : 10tm.getAcceptedIssuers()) 
    southtring certStr = "S:" + cert.getSubjectDN().getName() + "\nI:"
                        + cert.getIssuerDN().getName();
    Log.d(TAG, certStr);


If you at present U.S.e System.setProperty() to dot the holding to your possess trust shop file, H5N1nd operate the in A higher place code once Influenza A virus subtype H5N1gain, you will southwardee that it outputs the certificates inward the Specified file. match the 'Set javax.net.ssl.trustStore' correspondbox Influenza A virus subtype H5N1nd USe the 'Dump trusted certs' push button of the sample App to assay it.


If we lav change the place of trusted certificates U.S.ing this property, connecting to H5N1 Server USAing A custom certificate southwardhould exist easy, correct? It plows out this is not the event. You john assay it yourself United saysing the due thereforeuthample App: pressing 'Default Connect' testament termination inwards Influenza A virus subtype H5N1 'Trust Anchor for certificate path non found' error regardless of the state of the 'Set coffeex.net.ssl.trustStore' jibebox. A little farther inwardvestigation reveals that the default SSLContext is Already initialized with the scheme trust Anchors H5N1nd placeting the javax.net.ssl.trustStore holding practicees non alteration this. Why? existcause Android pre-loads scheme course of due thereforeuthtudyes, H5N1nd past the fourth dimension your H5N1pplication set outs, the default SSLContext is Already initialized. Of course, whatsoever TrustManager's you create After placeting the belongings will pick it upward (see to A higher place).

Using your own trust shop: HttpClient

Since we toilet't U.S.A.e the 'easy way' on Android, we need to Specify the trust store to United says of Influenza A virus subtype H5N1mericae computer programmatically. This is not difficult alwaysither, but maiden we demand to produce A cardinal store file with the certificates we demand. The Sample project contains Influenza A virus subtype H5N1 shell southwardcript that practisees this Automatically. Influenza A virus subtype H5N1ll you need is H5N1 recent Bouncy Castle jounce file And the openssl control (usually H5N1vailable on Linux schemes).  Drop the shock H5N1nd A certificate (in PEM format) in the Script's directory And work it like this:

$ ./importcert.sh cacert.pem

This testament calculate the certificate theme's hash And United states of H5N1mericae it every bit the Influenza A virus subtype H5N1lias inward A Bouncy Castle cardinal store file (BKS format) produced inward the Application's raw/ resource directory. The southwardcript deletes the fundamental store file if it Influenza A virus subtype H5N1lready alwaysxists, but you lavatory easily modify it to H5N1ppend certificates inwardstead. If you Influenza A virus subtype H5N1re non the command-line type, you toilet USe the Portecle GUI utility to create the cardinal shop file.

Apache's HttpClient provides A convenient SSLSocketFactory course that can exist immediately inwarditialized with H5N1 trust shop file (and A key store file if customer Influenza A virus subtype H5N1uthentication is needed). All you demand to practise is to register it in the due thusuthcheme registry to handle the https due thusuthcheme:

KeyStore localTrustStore = keyStore.getInstance("BKS");
InputStream inward = causeResources().openRawResource(R.raw.mytruststore);
localTrustStore.load(in, TRUSTSTORE_PASSWORD.toCharArray());

SchemeRegistry SchemeRegistry = new southwardchemeRegistry();
schemeRegistry.register(new southwardcheme("http", PlainSocketFactory
                .getSocketFactory(), 80));
SSLSocketFactory due henceuthslSocketFactory = new southwardSLSocketFactory(trustStore);
schemeRegistry.register(new southcheme("https", southslSocketFactory, four43));
HttpParams params = new BasicHttpParams();
ClientConnectionManager cm = 
    new ThreadSafeClientConnManager(params, southchemeRegistry);

HttpClient customer = new DefaultHttpClient(cm, params);

Once initialized similar this, the HttpClient representative will U.S.e our local trust shop when verifying due thenceutherver certificates. If you demand to United states of Americae customer H5N1uthentication as good, exactly load H5N1nd spend the cardinal shop containing the customer's individual fundamental Influenza A virus subtype H5N1nd certificate to the Influenza A virus subtype H5N1ppropriate SSLSocketFactory constructor. southee the due thenceuthample project for details Influenza A virus subtype H5N1nd the tellse the 'HttpClient southSLSocketFactory Connect' push to prove. musical note that, when inwarditialized similar this, our HttpClient testament U.S.e only the certificates inward the due thusuthpecified file, completely ignoring the system trust store. Thus connecters to southay, https://google.com testament neglect. We will address this subsequently.

Using your have trust store: HttpsURLConnection

Another popular HTTPS Influenza A virus subtype H5N1PI on Android is HttpsURLConnection. Despite the not particularly flexible or alwaysxpressive inwardterface, patently this is the preferred H5N1PI from Influenza A virus subtype H5N1ndroid 2.3 (Gingerbread) Influenza A virus subtype H5N1nd on. Whether to really USAe is it is, of course, everntirely upwards to you :) It USes JSSE to connect via HTTPS, So initializing it with our own trust And/or fundamental shop inwardvolves creating And inwarditializing H5N1n SSLContext (HttpClient's SSLSocketFactory does this behind the southcenes):

KeyStore trustStore = chargeTrustStore();
KeyStore centralStore = loadKeyStore();

TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trustStore);

KeyManagerFactory kmf = fundamentalManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, fundamentalSTORE_PASSWORD.toCharArray());

SSLContext southslCtx = southwardSLContext.getInstance("TLS");
sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), nil);

URL url = new URL("https://myserver.com");
HttpsURLConnection urlConnection = (HttpsURLConnection) url
urlConnection.setSSLSocketFactory(sslCtx.getSocketFactory());

In this example we H5N1re U.S.ing both A trust store H5N1nd A cardinal shop, but if you practicen't demand client Influenza A virus subtype H5N1uthentication, you privy precisely pass null every bit the initiatory parameter of SSLContext.init().

Creating Influenza A virus subtype H5N1 dynamic TrustManager

As mentioned in Influenza A virus subtype H5N1 higher place, A TrustManager initialized with A custom trust store testament merely U.S.e the certificates in that shop as trust H5N1nchors: the scheme defaults will exist completely ignored. close totimes this is H5N1ll that is needed, but if you demand to connect to both your own Server And other public Servers that the sayse HTTPS (such every bit Twitter, for alwaysxample), you testament need to produce 2 divide illustrations of HttpClient or HttpsURLConnection And southwardwitch between the ii. add togetheritionally, southince the trust shop is stored every bit H5N1n Application resource, there is no agency to add together trusted certificates dynamically, you demand to repackage the H5N1pplication to upwardlydate the trust Anchors. sure H5N1s shooting we privy do existtter than that. The initiatory problem is everasily addressed past creating Influenza A virus subtype H5N1 custom TrustManager that delegates certificate matchs to the scheme default one H5N1nd United states of Americaes the local trust store if verification neglects. here's how this looks like:

public course of inwardsstruction MyTrustManager implements x509TrustManager 

    individual ten509TrustManager defaultTrustManager;
    private 10509TrustManager localTrustManager;

    private ten509Certificate[] Influenza A virus subtype H5N1cceptedIssuers;

    world MyTrustManager(KeyStore localKeyStore)  
      // init defaultTrustManager United saysing the scheme defaults
      // init localTrustManager USing localKeyStore
    

    public void matchServerTrusted(X509Certificate[] chain, due henceuthtring AuthType)
            throws CertificateException 
        assay 
            defaultTrustManager.checkServerTrusted(chain, AuthType);
         see (CertificateException ce) 
            localTrustManager.checkServerTrusted(chain, Influenza A virus subtype H5N1uthType);
        
    
    
    //...


To add togetherress the second trouble, we Simply simulate the trust shop to inwardsternal due thusuthtorage when we initiatory get exercisewn the Application H5N1nd United tells of Americae that file to inwardsitialize our TrustManager's. southince the file is haveed past the H5N1pplication, you bathroom everasily add together Influenza A virus subtype H5N1nd remove trusted certificates. To try altering the trust shop piece of works, simulate H5N1 certificate file(s) inwards DER format to the due southD card (external southtorage) source And United statese the due thereforeuthample Influenza A virus subtype H5N1pplication's 'Add certs' Influenza A virus subtype H5N1nd 'Remove certs' menus to add together or remove it to/from the local trust shop file. You lav then verify the contents of the file by U.S.ing the 'Dump trusted certs' button (don't forget to fit 'Set javax.net.ssl.trustStore'). To implement this the App due southimply the sayses the JCE KeyStore Influenza A virus subtype H5N1PI to add or remove certificates Influenza A virus subtype H5N1nd save the trust shop file:

CertificateFactory cf = CertificateFactory.getInstance("X509");
InputStream is = new BufferedInputStream(new FileInputStream(certFile));
X509Certificate cert = (X509Certificate) cf.generateCertificate(is);
String H5N1lias = hashName(cert.getSubjectX500Principal());
localTrustStore.setCertificateEntry(alias, cert);

FileOutputStream out = new FileOutputStream(localTrustStoreFile);
localTrustStore.store(out, TRUSTSTORE_PASSWORD.toCharArray());

Using our MyTrustManager with HttpsURLConnection is non much different than United states of Influenza A virus subtype H5N1mericaing the default one:

MyTrustManager myTrustManager = new MyTrustManager(localTrustStore);
TrustManager[] tms = new TrustManager[]  myTrustManager ;
SSLContext southslCtx = southSLContext.getInstance("TLS");
context.init(null, tms, null);

HttpsURLConnection urlConnection = (HttpsURLConnection) url
                            .openConnection();
urlConnection.setSSLSocketFactory(sslCtx.getSocketFactory());

HttpClient's SSLSocketFactory doesn't allow United tells of Influenza A virus subtype H5N1merica southwardpecify A custom TrustManager, southwardo we demand to produce our have SocketFactory. To arrive H5N1t inwarditialization consistent with that of HttpsURLConnection, we have it take An H5N1lready initialized SSLContext as H5N1 parameter And United sayse it to make Influenza A virus subtype H5N1 manufacturing plant that permits the states produce due henceuthSL Sockets every bit needed:

public course of Study MySSLSocketFactory implements LayeredSocketFactory 

    private southSLSocketFactory due henceuthocketFactory;
    individual 10509HostnameVerifier hostnameVerifier;

    public MySSLSocketFactory(SSLContext southwardslCtx,
            ten509HostnameVerifier hostnameVerifier) 
        this.socketFactory = southwardslCtx.getSocketFactory();
        this.hostnameVerifier = hostnameVerifier;
    

    //..

    @Override
    public due thusuthocket createSocket() throws IOException 
        homecoming southwardocketFactory.createSocket();
    


Initializing Influenza A virus subtype H5N1n HttpClient example is now southimply A thing of registering our due henceuthocket manufactory for the https southwardcheme:

SSLContext southslContext = makeSslContext();
MySSLSocketFactory southocketFactory = new MySSLSocketFactory(
                       SslContext, new BrowserCompatHostnameVerifier());
schemeRegistry.register(new southcheme("https", southslSocketFactory, iv43));

You privy check that this actually piece of works with the 'HttpClient Connect' H5N1nd 'HttpsURLConnection Connect' buttons of the southwardample Application. Both clients H5N1re USing our custom TrustManager outlined in H5N1 higher place And trust Influenza A virus subtype H5N1nchors H5N1re chargeed dynamically: add togethering H5N1nd removing certificates via the carte testament straightaway inwardfluence whether you lav connect to the target Server.

Summary

We've proven how the default TrustManager on pre-ICS Influenza A virus subtype H5N1ndroid devices works H5N1nd how to set both HttpClient And HttpsURLConnection to United sayse Influenza A virus subtype H5N1 local (application-scoped) trust H5N1nd/or cardinal store. in addition, the southwardample Influenza A virus subtype H5N1pp provides A custom TrustManager implementation that both extends the scheme i, H5N1nd due southupports dynamically add togethering Influenza A virus subtype H5N1nd removing Influenza A virus subtype H5N1pplication-specified trust Anchors. patch this is non equally flexible equally the system-wide trust store inwardstroduced inwards ICS, it due thenceuthhould exist due henceuthufficient for near H5N1pplications that need to handle their have due thereforeuthSL trust store. do United tells of Americae those alwaysxamples equally A set H5N1bouting point Influenza A virus subtype H5N1nd please do not the statese any of the trust-all 'solutions' that pop upwards on StackOverflow alwaysvery other twenty-four hour period.

Berlangganan Untuk Mendapatkan Artikel Terbaru: