Thursday, November 7, 2019

Security with HTTPS and SSL socket client creating with Trusted Certificate, KeyStore, bks type

private fun createHttpClient(): HttpClient {
        var httpClient: HttpClient? = null        try {
            val is_unsafe = AppConfig.current.getApiItem("unsafe").toBoolean()
            val requestConfig = RequestConfig.custom().setCircularRedirectsAllowed(true).build()

            var trustAllCerts = arrayOf<TrustManager>()
            val sslContext = SSLContext.getInstance(ConstVariables.SSLContext_TLS)
            if (is_unsafe) {
                trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
                    override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
                    override fun checkClientTrusted(certs: Array<X509Certificate>, authType: String) = Unit
                    override fun checkServerTrusted(certs: Array<X509Certificate>, authType: String) = Unit
                })
                sslContext.init(null, trustAllCerts, SecureRandom())
            } else {
                var keyStore = App.getTrustedKeyStore()
                var trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
                trustManagerFactory.init(keyStore)
//                val keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())//                keyManagerFactory.init(keyStore, null)                sslContext.init(null, trustManagerFactory.trustManagers, SecureRandom())
            }

            var sslsf = SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE)
            var socketFactoryRegistry = RegistryBuilder.create<ConnectionSocketFactory>()
                    .register("https", sslsf).build()//.register("http", PlainConnectionSocketFactory())
            var connectionManager = BasicHttpClientConnectionManager(socketFactoryRegistry)
            httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig)
                    .setConnectionManager(connectionManager).build()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return httpClient as HttpClient
    }
**********************************************************************
private fun makeSocket(roomInfo: JSONObject): Socket? {
        if (mSocket != null)
            return mSocket        else {
            try {
                val is_unsafe = AppConfig.current.getApiItem("unsafe").toBoolean()
                val bot_timeout = AppConfig.current.getApiItem("bot_timeout").toLong()

                var trustAllCerts = arrayOf<TrustManager>()
                val sslContext = SSLContext.getInstance(ConstVariables.SSLContext_TLS)
                var trustManager: X509TrustManager? = null                if (is_unsafe) {
                    trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
                        override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
                        override fun checkClientTrusted(certs: Array<X509Certificate>, authType: String) = Unit
                        override fun checkServerTrusted(certs: Array<X509Certificate>, authType: String) = Unit
                    })
                    sslContext.init(null, trustAllCerts, SecureRandom())

                    trustManager = trustAllCerts.get(0) as X509TrustManager
                } else {
                    var keyStore = App.getTrustedKeyStore()
                    var trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
                    trustManagerFactory.init(keyStore)
//                    val keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())//                    keyManagerFactory.init(keyStore, null)                    sslContext.init(null, trustManagerFactory.trustManagers, SecureRandom())

                    trustManager = trustManagerFactory.trustManagers.get(0) as X509TrustManager
                }

                //val trustManager = trustManagerFactory.trustManagers.get(0) as X509TrustManager                val okHttpClient = OkHttpClient.Builder().hostnameVerifier(NoopHostnameVerifier.INSTANCE)
                        .sslSocketFactory(sslContext.getSocketFactory(), trustManager)
                        .cookieJar(makeCookieJar())
                        .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                        .readTimeout(bot_timeout, TimeUnit.SECONDS).writeTimeout(bot_timeout, TimeUnit.SECONDS)
                        .build()

                val options = IO.Options()
                //options.query = ("authtoken=" + AppSharedPrefrence.getString(this, App..AUTH_TOKEN))                options.forceNew = AppConfig.current.getApiItem("bot_forceNew").toBoolean()
                options.secure = AppConfig.current.getApiItem("bot_secure").toBoolean()
                options.callFactory = okHttpClient
                options.webSocketFactory = okHttpClient
                options.transports = arrayOf(WebSocket.NAME, Polling.NAME)
                val botUrl = UrlHelper.botUrl("room-" + roomInfo.getInt("id"))
                mSocket = IO.socket(botUrl, options)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return mSocket    }
**********************************************************************
fun getTrustedKeyStore(): KeyStore {
    if (trusted != null) return trusted as KeyStore
    val caInput = resource.openRawResource(R.raw.server)
    val cf = CertificateFactory.getInstance("X.509")
    val ca: Certificate
    try {
        ca = cf.generateCertificate(caInput)
        System.out.println("ca=" + (ca as X509Certificate).getSubjectDN())
    } finally {
        caInput.close()
    }

    // Create a KeyStore containing our trusted CAs    val keyStoreType = KeyStore.getDefaultType()
    val keyStore = KeyStore.getInstance(keyStoreType)
    keyStore.load(null, null)
    keyStore.setCertificateEntry("ca", ca)
    if (keyStoreType == ConstVariables.KeyStore_BKS) {
        return keyStore
    } else {
        var host = AppConfig.current.getApiItem("host")
        var hi = host.indexOf(':')
        var hip = host.substring(0, hi)
        var hips = hip.split('.')
        var ks = "ks_" + hips[2] + "_" + hips[3]
        var rid = ResourceHelper.getResourceId(ks, "raw")
        trusted = KeyStore.getInstance(ConstVariables.KeyStore_BKS)
        var ins = if (AppConfig.isApiRunatDevMode()) resource.openRawResource(rid)
        else resource.openRawResource(R.raw.key_store)//key_store.bks        try {
            trusted?.load(ins, null)
        } finally {
            ins.close()
            return trusted as KeyStore
        }
    }
}

No comments: