1

I make an web service on an Android device using NanoHTTPD. But it will trust all certificate and accept SSL connection from all client. I want to limit the access from specific client only.

Update: I try to work like this:

        String KEYSTOREPASS = "test";
        char[]ctpass = KEYSTOREPASS.toCharArray();
        KeyStore ks = KeyStore.getInstance("PKCS12");

        //Directly load cert from Resources
        //ks.load(ctx.getResources().openRawResource(R.raw.cayan_cert),kspass);

        //Or dynamically generate a cert and use it
        ipAddressInCN = MainApplication.getIPAddress();

        //Use the current IP Address to generate a cert that signed by hard coded CA, and add to keystore
        String CN = "CN=" + ipAddressInCN;
        ks.load(null, null);
        GenerateCSR.AddCertToKeyStore(ks, ctpass, CN);

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, ctpass);

        SSLContext sc = SSLContext.getInstance("TLS");

        TrustManager[] tm = new TrustManager[]{new X509TrustManager() {

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {

                return new java.security.cert.X509Certificate[0];
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] certs,
                                           String authType) {
                System.out.println("abc");
                return;
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs,
                                           String authType) {

                return;
            }

        }};

        sc.init(kmf.getKeyManagers(), tm, null);
        server.makeSecure(sc.getServerSocketFactory(), null);

I try to set break point to my custom trust manager functions but they are never called.

sing lam
  • 131
  • 1
  • 10
  • 2
    Server side of what? Are you looking for [`SSLServerSocket.setNeedClientAuth()`](https://docs.oracle.com/javase/8/docs/api/javax/net/ssl/SSLServerSocket.html#setNeedClientAuth-boolean-)? – user207421 Aug 15 '17 at 01:07
  • Sorry, I have made my question more specific. – sing lam Aug 15 '17 at 01:36

1 Answers1

1

But it will trust all certificate and accept SSL connection from all client.

Not true. It will only accept SSL connections from clients with trusted certificates, unless you have installed some brain-dead trust-all-certificates garbage, in which case you should remove them.

I want to limit the access from specific client only.

You should do that via authorization, which you have to implement yourself in NanoHTTPD.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Could you show how to do that? I just find a page related: https://stackoverflow.com/questions/31270613/https-server-on-android-device-using-nanohttpd I try to follow it but my nanoHttpd still response anonymous browser request..... – sing lam Aug 15 '17 at 02:46