Search in sources :

Example 1 with MagicTrustManager

use of com.nextcloud.talk.utils.ssl.MagicTrustManager in project talk-android by nextcloud.

the class MainActivity method showCertificateDialog.

public void showCertificateDialog(X509Certificate cert, MagicTrustManager magicTrustManager, @Nullable SslErrorHandler sslErrorHandler) {
    DateFormat formatter = DateFormat.getDateInstance(DateFormat.LONG);
    String validFrom = formatter.format(cert.getNotBefore());
    String validUntil = formatter.format(cert.getNotAfter());
    String issuedBy = cert.getIssuerDN().toString();
    String issuedFor;
    try {
        if (cert.getSubjectAlternativeNames() != null) {
            StringBuilder stringBuilder = new StringBuilder();
            for (Object o : cert.getSubjectAlternativeNames()) {
                List list = (List) o;
                int type = (Integer) list.get(0);
                if (type == 2) {
                    String name = (String) list.get(1);
                    stringBuilder.append("[").append(type).append("]").append(name).append(" ");
                }
            }
            issuedFor = stringBuilder.toString();
        } else {
            issuedFor = cert.getSubjectDN().getName();
        }
        @SuppressLint("StringFormatMatches") String dialogText = String.format(getResources().getString(R.string.nc_certificate_dialog_text), issuedBy, issuedFor, validFrom, validUntil);
        new LovelyStandardDialog(this).setTopColorRes(R.color.nc_darkRed).setNegativeButtonColorRes(R.color.nc_darkRed).setPositiveButtonColorRes(R.color.colorPrimaryDark).setIcon(R.drawable.ic_security_white_24dp).setTitle(R.string.nc_certificate_dialog_title).setMessage(dialogText).setPositiveButton(R.string.nc_yes, v -> {
            magicTrustManager.addCertInTrustStore(cert);
            if (sslErrorHandler != null) {
                sslErrorHandler.proceed();
            }
        }).setNegativeButton(R.string.nc_no, view1 -> {
            if (sslErrorHandler != null) {
                sslErrorHandler.cancel();
            }
        }).show();
    } catch (CertificateParsingException e) {
        Log.d(TAG, "Failed to parse the certificate");
    }
}
Also used : X509Certificate(java.security.cert.X509Certificate) AutoInjector(autodagger.AutoInjector) Bundle(android.os.Bundle) UserUtils(com.nextcloud.talk.utils.database.user.UserUtils) ButterKnife(butterknife.ButterKnife) CertificateParsingException(java.security.cert.CertificateParsingException) Conductor(com.bluelinelabs.conductor.Conductor) SqlCipherDatabaseSource(io.requery.android.sqlcipher.SqlCipherDatabaseSource) CertificateEvent(com.nextcloud.talk.events.CertificateEvent) MagicTrustManager(com.nextcloud.talk.utils.ssl.MagicTrustManager) BindView(butterknife.BindView) Inject(javax.inject.Inject) SuppressLint(android.annotation.SuppressLint) SslErrorHandler(android.webkit.SslErrorHandler) ActionBarProvider(com.nextcloud.talk.controllers.base.providers.ActionBarProvider) EventBus(org.greenrobot.eventbus.EventBus) LovelyStandardDialog(com.yarolegovich.lovelydialog.LovelyStandardDialog) ServerSelectionController(com.nextcloud.talk.controllers.ServerSelectionController) Persistable(io.requery.Persistable) Log(android.util.Log) DateFormat(java.text.DateFormat) MagicBottomNavigationController(com.nextcloud.talk.controllers.MagicBottomNavigationController) R(com.nextcloud.talk.R) ThreadMode(org.greenrobot.eventbus.ThreadMode) ReactiveEntityStore(io.requery.reactivex.ReactiveEntityStore) AppCompatActivity(android.support.v7.app.AppCompatActivity) ViewGroup(android.view.ViewGroup) HorizontalChangeHandler(com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler) List(java.util.List) Subscribe(org.greenrobot.eventbus.Subscribe) Toolbar(android.support.v7.widget.Toolbar) Router(com.bluelinelabs.conductor.Router) Nullable(android.support.annotation.Nullable) NextcloudTalkApplication(com.nextcloud.talk.application.NextcloudTalkApplication) RouterTransaction(com.bluelinelabs.conductor.RouterTransaction) CertificateParsingException(java.security.cert.CertificateParsingException) DateFormat(java.text.DateFormat) SuppressLint(android.annotation.SuppressLint) List(java.util.List) SuppressLint(android.annotation.SuppressLint) LovelyStandardDialog(com.yarolegovich.lovelydialog.LovelyStandardDialog)

Example 2 with MagicTrustManager

use of com.nextcloud.talk.utils.ssl.MagicTrustManager in project talk-android by nextcloud.

the class WebViewLoginController method onViewBound.

@Override
protected void onViewBound(@NonNull View view) {
    super.onViewBound(view);
    NextcloudTalkApplication.getSharedApplication().getComponentApplication().inject(this);
    if (getActivity() != null) {
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
    if (getActionBar() != null) {
        getActionBar().hide();
    }
    assembledPrefix = getResources().getString(R.string.nc_talk_login_scheme) + PROTOCOL_SUFFIX + "login/";
    webView.getSettings().setAllowFileAccess(false);
    webView.getSettings().setAllowFileAccessFromFileURLs(false);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setUserAgentString(getWebLoginUserAgent());
    webView.getSettings().setSaveFormData(false);
    webView.getSettings().setSavePassword(false);
    webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    webView.clearCache(true);
    webView.clearFormData();
    webView.clearHistory();
    CookieSyncManager.createInstance(getActivity());
    android.webkit.CookieManager.getInstance().removeAllCookies(null);
    Map<String, String> headers = new HashMap<>();
    headers.put("OCS-APIRequest", "true");
    webView.setWebViewClient(new WebViewClient() {

        private boolean basePageLoaded;

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith(assembledPrefix)) {
                parseAndLoginFromWebView(url);
                return true;
            }
            return false;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            loginStep++;
            if (!basePageLoaded) {
                if (progressBar != null) {
                    progressBar.setVisibility(View.GONE);
                }
                if (webView != null) {
                    webView.setVisibility(View.VISIBLE);
                }
                basePageLoaded = true;
            }
            if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)) {
                if (loginStep == 1) {
                    webView.loadUrl("javascript: {document.getElementsByClassName('login')[0].click(); };");
                } else if (!automatedLoginAttempted) {
                    automatedLoginAttempted = true;
                    webView.loadUrl("javascript: {" + "document.getElementById('user').value = '" + username + "';" + "document.getElementById('password').value = '" + password + "';" + "document.getElementById('submit').click(); };");
                }
            }
            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) {
            String host = null;
            try {
                URL url = new URL(webView.getUrl());
                host = url.getHost();
            } catch (MalformedURLException e) {
                Log.d(TAG, "Failed to create url");
            }
            KeyChain.choosePrivateKeyAlias(getActivity(), alias -> {
                try {
                    if (alias != null) {
                        PrivateKey privateKey = KeyChain.getPrivateKey(getActivity(), alias);
                        X509Certificate[] certificates = KeyChain.getCertificateChain(getActivity(), alias);
                        request.proceed(privateKey, certificates);
                    } else {
                        request.cancel();
                    }
                } catch (KeyChainException e) {
                    Log.e(TAG, "Failed to get keys via keychain exception");
                    request.cancel();
                } catch (InterruptedException e) {
                    Log.e(TAG, "Failed to get keys due to interruption");
                    request.cancel();
                }
            }, new String[] { "RSA" }, null, host, -1, null);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            try {
                SslCertificate sslCertificate = error.getCertificate();
                Field f = sslCertificate.getClass().getDeclaredField("mX509Certificate");
                f.setAccessible(true);
                X509Certificate cert = (X509Certificate) f.get(sslCertificate);
                if (cert == null) {
                    handler.cancel();
                } else {
                    try {
                        magicTrustManager.checkServerTrusted(new X509Certificate[] { cert }, "generic");
                        handler.proceed();
                    } catch (CertificateException exception) {
                        eventBus.post(new CertificateEvent(cert, magicTrustManager, handler));
                    }
                }
            } catch (Exception exception) {
                handler.cancel();
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    });
    webView.loadUrl(baseUrl + "/index.php/login/flow", headers);
}
Also used : X509Certificate(java.security.cert.X509Certificate) AutoInjector(autodagger.AutoInjector) Bundle(android.os.Bundle) KeyChain(android.security.KeyChain) UserUtils(com.nextcloud.talk.utils.database.user.UserUtils) URLDecoder(java.net.URLDecoder) ProgressBar(android.widget.ProgressBar) URL(java.net.URL) BindView(butterknife.BindView) SslErrorHandler(android.webkit.SslErrorHandler) Locale(java.util.Locale) Map(java.util.Map) ActivityInfo(android.content.pm.ActivityInfo) WebViewClient(android.webkit.WebViewClient) View(android.view.View) CookieSyncManager(android.webkit.CookieSyncManager) WebView(android.webkit.WebView) Persistable(io.requery.Persistable) Log(android.util.Log) ReactiveEntityStore(io.requery.reactivex.ReactiveEntityStore) ViewGroup(android.view.ViewGroup) BundleKeys(com.nextcloud.talk.utils.bundle.BundleKeys) Disposable(io.reactivex.disposables.Disposable) ClientCertRequest(android.webkit.ClientCertRequest) LoginData(com.nextcloud.talk.models.LoginData) PrivateKey(java.security.PrivateKey) UserEntity(com.nextcloud.talk.models.database.UserEntity) HashMap(java.util.HashMap) NonNull(android.support.annotation.NonNull) CertificateEvent(com.nextcloud.talk.events.CertificateEvent) MagicTrustManager(com.nextcloud.talk.utils.ssl.MagicTrustManager) Inject(javax.inject.Inject) WebSettings(android.webkit.WebSettings) BaseController(com.nextcloud.talk.controllers.base.BaseController) EventBus(org.greenrobot.eventbus.EventBus) Build(android.os.Build) SslError(android.net.http.SslError) R(com.nextcloud.talk.R) MalformedURLException(java.net.MalformedURLException) LayoutInflater(android.view.LayoutInflater) TextUtils(android.text.TextUtils) CertificateException(java.security.cert.CertificateException) Field(java.lang.reflect.Field) HorizontalChangeHandler(com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler) KeyChainException(android.security.KeyChainException) SslCertificate(android.net.http.SslCertificate) ApplicationWideMessageHolder(com.nextcloud.talk.utils.ApplicationWideMessageHolder) NextcloudTalkApplication(com.nextcloud.talk.application.NextcloudTalkApplication) RouterTransaction(com.bluelinelabs.conductor.RouterTransaction) SslErrorHandler(android.webkit.SslErrorHandler) MalformedURLException(java.net.MalformedURLException) PrivateKey(java.security.PrivateKey) HashMap(java.util.HashMap) ClientCertRequest(android.webkit.ClientCertRequest) SslError(android.net.http.SslError) CertificateException(java.security.cert.CertificateException) URL(java.net.URL) X509Certificate(java.security.cert.X509Certificate) MalformedURLException(java.net.MalformedURLException) CertificateException(java.security.cert.CertificateException) KeyChainException(android.security.KeyChainException) Field(java.lang.reflect.Field) KeyChainException(android.security.KeyChainException) SslCertificate(android.net.http.SslCertificate) CertificateEvent(com.nextcloud.talk.events.CertificateEvent) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient)

Aggregations

Bundle (android.os.Bundle)2 Log (android.util.Log)2 ViewGroup (android.view.ViewGroup)2 SslErrorHandler (android.webkit.SslErrorHandler)2 AutoInjector (autodagger.AutoInjector)2 BindView (butterknife.BindView)2 RouterTransaction (com.bluelinelabs.conductor.RouterTransaction)2 HorizontalChangeHandler (com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler)2 R (com.nextcloud.talk.R)2 NextcloudTalkApplication (com.nextcloud.talk.application.NextcloudTalkApplication)2 CertificateEvent (com.nextcloud.talk.events.CertificateEvent)2 UserUtils (com.nextcloud.talk.utils.database.user.UserUtils)2 MagicTrustManager (com.nextcloud.talk.utils.ssl.MagicTrustManager)2 Persistable (io.requery.Persistable)2 ReactiveEntityStore (io.requery.reactivex.ReactiveEntityStore)2 SuppressLint (android.annotation.SuppressLint)1 ActivityInfo (android.content.pm.ActivityInfo)1 SslCertificate (android.net.http.SslCertificate)1 SslError (android.net.http.SslError)1 Build (android.os.Build)1