Search in sources :

Example 11 with SslError

use of android.net.http.SslError in project chromeview by pwnall.

the class AwContentsClientBridge method allowCertificateError.

// If returns false, the request is immediately canceled, and any call to proceedSslError
// has no effect. If returns true, the request should be canceled or proceeded using
// proceedSslError().
// Unlike the webview classic, we do not keep keep a database of certificates that
// are allowed by the user, because this functionality is already handled via
// ssl_policy in native layers.
@CalledByNative
private boolean allowCertificateError(int certError, byte[] derBytes, final String url, final int id) {
    final SslCertificate cert = SslUtil.getCertificateFromDerBytes(derBytes);
    if (cert == null) {
        // if the certificate or the client is null, cancel the request
        return false;
    }
    final SslError sslError = SslUtil.sslErrorFromNetErrorCode(certError, cert, url);
    ValueCallback<Boolean> callback = new ValueCallback<Boolean>() {

        @Override
        public void onReceiveValue(Boolean value) {
            proceedSslError(value.booleanValue(), id);
        }
    };
    mClient.onReceivedSslError(callback, sslError);
    return true;
}
Also used : ValueCallback(android.webkit.ValueCallback) SslCertificate(android.net.http.SslCertificate) SslError(android.net.http.SslError) CalledByNative(org.chromium.base.CalledByNative)

Example 12 with SslError

use of android.net.http.SslError in project android by nextcloud.

the class AuthenticatorActivity method initWebViewLogin.

private void initWebViewLogin(String baseURL) {
    mLoginWebView.setVisibility(View.GONE);
    final ProgressBar progressBar = findViewById(R.id.login_webview_progress_bar);
    mLoginWebView.getSettings().setAllowFileAccess(false);
    mLoginWebView.getSettings().setJavaScriptEnabled(true);
    mLoginWebView.getSettings().setDomStorageEnabled(true);
    mLoginWebView.getSettings().setUserAgentString(getWebLoginUserAgent());
    mLoginWebView.getSettings().setSaveFormData(false);
    mLoginWebView.getSettings().setSavePassword(false);
    Map<String, String> headers = new HashMap<>();
    headers.put(RemoteOperation.OCS_API_HEADER, RemoteOperation.OCS_API_HEADER_VALUE);
    String url;
    if (baseURL != null && !baseURL.isEmpty()) {
        url = baseURL + WEB_LOGIN;
    } else {
        url = getResources().getString(R.string.webview_login_url);
    }
    mLoginWebView.loadUrl(url, headers);
    mLoginWebView.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith(getString(R.string.login_data_own_scheme) + PROTOCOL_SUFFIX + "login/")) {
                parseAndLoginFromWebView(url);
                return true;
            }
            return false;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            progressBar.setVisibility(View.GONE);
            mLoginWebView.setVisibility(View.VISIBLE);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            X509Certificate cert = SsoWebViewClient.getX509CertificateFromError(error);
            try {
                if (cert != null && NetworkUtils.isCertInKnownServersStore(cert, getApplicationContext())) {
                    handler.proceed();
                } else {
                    showUntrustedCertDialog(cert, error, handler);
                }
            } catch (Exception e) {
                Log_OC.e(TAG, "Cert could not be verified");
            }
        }

        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            progressBar.setVisibility(View.GONE);
            mLoginWebView.setVisibility(View.VISIBLE);
            InputStream resources = getResources().openRawResource(R.raw.custom_error);
            String customError = DisplayUtils.getData(resources);
            if (!customError.isEmpty()) {
                mLoginWebView.loadData(customError, "text/html; charset=UTF-8", null);
            }
        }
    });
    // show snackbar after 60s to switch back to old login method
    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            Snackbar.make(mLoginWebView, R.string.fallback_weblogin_text, Snackbar.LENGTH_INDEFINITE).setAction(R.string.fallback_weblogin_back, new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    mLoginWebView.setVisibility(View.INVISIBLE);
                    webViewLoginMethod = false;
                    setContentView(R.layout.account_setup);
                    // initialize general UI elements
                    initOverallUi();
                    mPasswordInputLayout.setVisibility(View.VISIBLE);
                    mUsernameInputLayout.setVisibility(View.VISIBLE);
                    mUsernameInput.requestFocus();
                    mOAuth2Check.setVisibility(View.INVISIBLE);
                    mAuthStatusView.setVisibility(View.INVISIBLE);
                    mServerStatusView.setVisibility(View.INVISIBLE);
                    mTestServerButton.setVisibility(View.INVISIBLE);
                    forceOldLoginMethod = true;
                    mOkButton.setVisibility(View.VISIBLE);
                    initServerPreFragment(null);
                    mHostUrlInput.setText(baseURL);
                    checkOcServer();
                }
            }).show();
        }
    }, 60000);
}
Also used : SslErrorHandler(android.webkit.SslErrorHandler) HashMap(java.util.HashMap) InputStream(java.io.InputStream) SslError(android.net.http.SslError) SslErrorHandler(android.webkit.SslErrorHandler) Handler(android.os.Handler) HttpAuthHandler(android.webkit.HttpAuthHandler) View(android.view.View) WebView(android.webkit.WebView) TextView(android.widget.TextView) X509Certificate(java.security.cert.X509Certificate) AndroidRuntimeException(android.util.AndroidRuntimeException) CertificateCombinedException(com.owncloud.android.lib.common.network.CertificateCombinedException) AccountNotFoundException(com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException) WebView(android.webkit.WebView) ProgressBar(android.widget.ProgressBar) WebViewClient(android.webkit.WebViewClient)

Example 13 with SslError

use of android.net.http.SslError in project openremote by openremote.

the class MainActivity method initializeWebView.

protected void initializeWebView() {
    LOG.fine("Initializing web view");
    final WebAppInterface webAppInterface = new WebAppInterface(this);
    webView.addJavascriptInterface(webAppInterface, "MobileInterface");
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
    webSettings.setDomStorageEnabled(true);
    webSettings.setDatabaseEnabled(true);
    webView.setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            return true;
        }
    });
    webView.setLongClickable(false);
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            // TODO should we ignore images?
            if (request.getUrl().getLastPathSegment() != null && (request.getUrl().getLastPathSegment().endsWith("png") || request.getUrl().getLastPathSegment().endsWith("jpg") || request.getUrl().getLastPathSegment().endsWith("ico")))
                return;
            // invalid token. The web app will then start a new login.
            if (request.getUrl().getLastPathSegment() != null && request.getUrl().getLastPathSegment().equals("token") && request.getMethod().equals("POST") && errorResponse.getStatusCode() == 400) {
                webAppInterface.tokenService.clearToken();
                return;
            }
            LOG.warning("Error requesting '" + request.getUrl() + "', response code: " + errorResponse.getStatusCode());
            errorViewHolder.show(R.string.httpError, R.string.httpErrorExplain, true, true);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            if (Boolean.parseBoolean(getString(R.string.SSL_IGNORE))) {
                LOG.fine("Ignoring SSL certificate error: " + error.getPrimaryError());
                // Ignore SSL certificate errors
                handler.proceed();
            } else {
                LOG.severe("SSL error: " + error.getPrimaryError());
                LOG.severe("SSL certificate: " + error.getCertificate());
                errorViewHolder.show(R.string.httpError, R.string.httpErrorExplain, true, true);
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            // TODO should we ignore images?
            if (request.getUrl().getLastPathSegment() != null && (request.getUrl().getLastPathSegment().endsWith("png") || request.getUrl().getLastPathSegment().endsWith("jpg") || request.getUrl().getLastPathSegment().endsWith("ico")))
                return;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // Remote debugging sessions from Chrome trigger "ERR_CACHE_MISS" that don't hurt, but we should not redirect the view
                if (isRemoteDebuggingEnabled() && error.getErrorCode() == ERROR_UNKNOWN) {
                    return;
                }
                // Remote debugging session from Chrome wants to load about:blank and then fails with "ERROR_UNSUPPORTED_SCHEME", ignore
                if (request.getUrl().toString().equals("about:blank") && error.getErrorCode() == ERROR_UNSUPPORTED_SCHEME) {
                    return;
                }
                LOG.warning("Error requesting '" + request.getUrl() + "': " + error.getErrorCode());
            }
            errorViewHolder.show(R.string.fatalError, R.string.fatalErrorExplain, false, true);
        }
    });
    webView.setWebChromeClient(new WebChromeClient() {

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            String msg = "WebApp console (" + consoleMessage.sourceId() + ":" + consoleMessage.lineNumber() + "): " + consoleMessage.message();
            switch(consoleMessage.messageLevel()) {
                case DEBUG:
                case TIP:
                    LOG.fine(msg);
                    break;
                case LOG:
                    LOG.info(msg);
                    break;
                default:
                    LOG.severe(msg);
            }
            return true;
        }
    });
    webView.setDownloadListener(new DownloadListener() {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
            String writePermission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
            if (ContextCompat.checkSelfPermission(context, writePermission) != PackageManager.PERMISSION_GRANTED) {
                // Location permission has not been granted yet, request it.
                ActivityCompat.requestPermissions((MainActivity) context, new String[] { writePermission }, WRITE_PERMISSION_REQUEST);
            } else {
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                request.setMimeType(mimetype);
                // ------------------------COOKIE!!------------------------
                String cookies = CookieManager.getInstance().getCookie(url);
                request.addRequestHeader("cookie", cookies);
                // ------------------------COOKIE!!------------------------
                request.addRequestHeader("User-Agent", userAgent);
                request.setDescription("Downloading file...");
                request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimetype));
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimetype));
                DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                if (dm != null) {
                    Toast.makeText(getApplicationContext(), R.string.downloading_file, Toast.LENGTH_LONG).show();
                    dm.enqueue(request);
                } else {
                    Toast.makeText(getApplicationContext(), R.string.error_downloading, Toast.LENGTH_LONG).show();
                }
            }
        }
    });
}
Also used : SslErrorHandler(android.webkit.SslErrorHandler) WebResourceRequest(android.webkit.WebResourceRequest) SslError(android.net.http.SslError) WebResourceRequest(android.webkit.WebResourceRequest) View(android.view.View) WebView(android.webkit.WebView) TextView(android.widget.TextView) DownloadManager(android.app.DownloadManager) ConsoleMessage(android.webkit.ConsoleMessage) WebResourceResponse(android.webkit.WebResourceResponse) DownloadListener(android.webkit.DownloadListener) WebSettings(android.webkit.WebSettings) WebChromeClient(android.webkit.WebChromeClient) WebResourceError(android.webkit.WebResourceError) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient)

Example 14 with SslError

use of android.net.http.SslError in project SmartMesh_Android by SmartMeshFoundation.

the class AdvancedWebView method init.

@SuppressLint({ "SetJavaScriptEnabled" })
protected void init(final Context context) {
    if (context instanceof Activity) {
        mActivity = new WeakReference<Activity>((Activity) context);
    }
    mLanguageIso3 = getLanguageIso3();
    setFocusable(true);
    setFocusableInTouchMode(true);
    setSaveEnabled(true);
    final String filesDir = context.getFilesDir().getPath();
    final String databaseDir = filesDir.substring(0, filesDir.lastIndexOf("/")) + DATABASES_SUB_FOLDER;
    final WebSettings webSettings = getSettings();
    webSettings.setAllowFileAccess(false);
    setAllowAccessFromFileUrls(webSettings, true);
    webSettings.setBuiltInZoomControls(false);
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    if (Build.VERSION.SDK_INT < 18) {
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
    }
    webSettings.setDatabaseEnabled(true);
    if (Build.VERSION.SDK_INT < 19) {
        webSettings.setDatabasePath(databaseDir);
    }
    setMixedContentAllowed(webSettings, true);
    setThirdPartyCookiesEnabled(true);
    super.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (!hasError()) {
                if (mListener != null) {
                    mListener.onPageStarted(url, favicon);
                }
            }
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onPageStarted(view, url, favicon);
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (!hasError()) {
                if (mListener != null) {
                    mListener.onPageFinished(url);
                }
            }
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onPageFinished(view, url);
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            setLastError();
            if (mListener != null) {
                mListener.onPageError(errorCode, description, failingUrl);
            }
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onReceivedError(view, errorCode, description, failingUrl);
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
            if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("www.")) {
                return super.shouldOverrideUrlLoading(view, url);
            } else {
                return true;
            }
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onLoadResource(view, url);
            } else {
                super.onLoadResource(view, url);
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            if (Build.VERSION.SDK_INT >= 11) {
                if (mCustomWebViewClient != null) {
                    return mCustomWebViewClient.shouldInterceptRequest(view, url);
                } else {
                    return super.shouldInterceptRequest(view, url);
                }
            } else {
                return null;
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            if (Build.VERSION.SDK_INT >= 21) {
                if (mCustomWebViewClient != null) {
                    return mCustomWebViewClient.shouldInterceptRequest(view, request);
                } else {
                    return super.shouldInterceptRequest(view, request);
                }
            } else {
                return null;
            }
        }

        @Override
        public void onFormResubmission(WebView view, Message dontResend, Message resend) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onFormResubmission(view, dontResend, resend);
            } else {
                super.onFormResubmission(view, dontResend, resend);
            }
        }

        @Override
        public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.doUpdateVisitedHistory(view, url, isReload);
            } else {
                super.doUpdateVisitedHistory(view, url, isReload);
            }
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onReceivedSslError(view, handler, error);
            } else {
                super.onReceivedSslError(view, handler, error);
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) {
            if (Build.VERSION.SDK_INT >= 21) {
                if (mCustomWebViewClient != null) {
                    mCustomWebViewClient.onReceivedClientCertRequest(view, request);
                } else {
                    super.onReceivedClientCertRequest(view, request);
                }
            }
        }

        @Override
        public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onReceivedHttpAuthRequest(view, handler, host, realm);
            } else {
                super.onReceivedHttpAuthRequest(view, handler, host, realm);
            }
        }

        @Override
        public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
            if (mCustomWebViewClient != null) {
                return mCustomWebViewClient.shouldOverrideKeyEvent(view, event);
            } else {
                return super.shouldOverrideKeyEvent(view, event);
            }
        }

        @Override
        public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onUnhandledKeyEvent(view, event);
            } else {
                super.onUnhandledKeyEvent(view, event);
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public void onUnhandledInputEvent(WebView view, InputEvent event) {
            if (Build.VERSION.SDK_INT >= 21) {
                if (mCustomWebViewClient != null) {
                    mCustomWebViewClient.onUnhandledInputEvent(view, event);
                } else {
                    super.onUnhandledInputEvent(view, event);
                }
            }
        }

        @Override
        public void onScaleChanged(WebView view, float oldScale, float newScale) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onScaleChanged(view, oldScale, newScale);
            } else {
                super.onScaleChanged(view, oldScale, newScale);
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public void onReceivedLoginRequest(WebView view, String realm, String account, String args) {
            if (Build.VERSION.SDK_INT >= 12) {
                if (mCustomWebViewClient != null) {
                    mCustomWebViewClient.onReceivedLoginRequest(view, realm, account, args);
                } else {
                    super.onReceivedLoginRequest(view, realm, account, args);
                }
            }
        }
    });
    super.setWebChromeClient(new WebChromeClient() {

        // file upload callback (Android 2.2 (API level 8) -- Android 2.3 (API level 10)) (hidden method)
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooser(uploadMsg, null);
        }

        // file upload callback (Android 3.0 (API level 11) -- Android 4.0 (API level 15)) (hidden method)
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            openFileChooser(uploadMsg, acceptType, null);
        }

        // file upload callback (Android 4.1 (API level 16) -- Android 4.3 (API level 18)) (hidden method)
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileInput(uploadMsg, null);
        }

        // file upload callback (Android 5.0 (API level 21) -- current) (public method)
        @SuppressWarnings("all")
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            openFileInput(null, filePathCallback);
            return true;
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onProgressChanged(view, newProgress);
            } else {
                super.onProgressChanged(view, newProgress);
            }
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onReceivedTitle(view, title);
            } else {
                super.onReceivedTitle(view, title);
            }
        }

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onReceivedIcon(view, icon);
            } else {
                super.onReceivedIcon(view, icon);
            }
        }

        @Override
        public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onReceivedTouchIconUrl(view, url, precomposed);
            } else {
                super.onReceivedTouchIconUrl(view, url, precomposed);
            }
        }

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onShowCustomView(view, callback);
            } else {
                super.onShowCustomView(view, callback);
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) {
            if (Build.VERSION.SDK_INT >= 14) {
                if (mCustomWebChromeClient != null) {
                    mCustomWebChromeClient.onShowCustomView(view, requestedOrientation, callback);
                } else {
                    super.onShowCustomView(view, requestedOrientation, callback);
                }
            }
        }

        @Override
        public void onHideCustomView() {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onHideCustomView();
            } else {
                super.onHideCustomView();
            }
        }

        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
            } else {
                return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
            }
        }

        @Override
        public void onRequestFocus(WebView view) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onRequestFocus(view);
            } else {
                super.onRequestFocus(view);
            }
        }

        @Override
        public void onCloseWindow(WebView window) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onCloseWindow(window);
            } else {
                super.onCloseWindow(window);
            }
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onJsAlert(view, url, message, result);
            } else {
                return super.onJsAlert(view, url, message, result);
            }
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onJsConfirm(view, url, message, result);
            } else {
                return super.onJsConfirm(view, url, message, result);
            }
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onJsPrompt(view, url, message, defaultValue, result);
            } else {
                return super.onJsPrompt(view, url, message, defaultValue, result);
            }
        }

        @Override
        public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onJsBeforeUnload(view, url, message, result);
            } else {
                return super.onJsBeforeUnload(view, url, message, result);
            }
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
            if (mGeolocationEnabled) {
                callback.invoke(origin, true, false);
            } else {
                if (mCustomWebChromeClient != null) {
                    mCustomWebChromeClient.onGeolocationPermissionsShowPrompt(origin, callback);
                } else {
                    super.onGeolocationPermissionsShowPrompt(origin, callback);
                }
            }
        }

        @Override
        public void onGeolocationPermissionsHidePrompt() {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onGeolocationPermissionsHidePrompt();
            } else {
                super.onGeolocationPermissionsHidePrompt();
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public void onPermissionRequest(PermissionRequest request) {
            if (Build.VERSION.SDK_INT >= 21) {
                if (mCustomWebChromeClient != null) {
                    mCustomWebChromeClient.onPermissionRequest(request);
                } else {
                    super.onPermissionRequest(request);
                }
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public void onPermissionRequestCanceled(PermissionRequest request) {
            if (Build.VERSION.SDK_INT >= 21) {
                if (mCustomWebChromeClient != null) {
                    mCustomWebChromeClient.onPermissionRequestCanceled(request);
                } else {
                    super.onPermissionRequestCanceled(request);
                }
            }
        }

        @Override
        public boolean onJsTimeout() {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onJsTimeout();
            } else {
                return super.onJsTimeout();
            }
        }

        @Override
        public void onConsoleMessage(String message, int lineNumber, String sourceID) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onConsoleMessage(message, lineNumber, sourceID);
            } else {
                super.onConsoleMessage(message, lineNumber, sourceID);
            }
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onConsoleMessage(consoleMessage);
            } else {
                return super.onConsoleMessage(consoleMessage);
            }
        }

        @Override
        public Bitmap getDefaultVideoPoster() {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.getDefaultVideoPoster();
            } else {
                return super.getDefaultVideoPoster();
            }
        }

        @Override
        public View getVideoLoadingProgressView() {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.getVideoLoadingProgressView();
            } else {
                return super.getVideoLoadingProgressView();
            }
        }

        @Override
        public void getVisitedHistory(ValueCallback<String[]> callback) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.getVisitedHistory(callback);
            } else {
                super.getVisitedHistory(callback);
            }
        }

        @Override
        public void onExceededDatabaseQuota(String url, String databaseIdentifier, long quota, long estimatedDatabaseSize, long totalQuota, QuotaUpdater quotaUpdater) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize, totalQuota, quotaUpdater);
            } else {
                super.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize, totalQuota, quotaUpdater);
            }
        }

        @Override
        public void onReachedMaxAppCacheSize(long requiredStorage, long quota, QuotaUpdater quotaUpdater) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater);
            } else {
                super.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater);
            }
        }
    });
    setDownloadListener(new DownloadListener() {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
            if (mListener != null) {
                mListener.onDownloadRequested(url, userAgent, contentDisposition, mimetype, contentLength);
            }
        }
    });
}
Also used : SslErrorHandler(android.webkit.SslErrorHandler) PermissionRequest(android.webkit.PermissionRequest) ConsoleMessage(android.webkit.ConsoleMessage) Message(android.os.Message) SslError(android.net.http.SslError) ClientCertRequest(android.webkit.ClientCertRequest) FragmentActivity(android.support.v4.app.FragmentActivity) Activity(android.app.Activity) Uri(android.net.Uri) ConsoleMessage(android.webkit.ConsoleMessage) KeyEvent(android.view.KeyEvent) JsResult(android.webkit.JsResult) Bitmap(android.graphics.Bitmap) HttpAuthHandler(android.webkit.HttpAuthHandler) WebChromeClient(android.webkit.WebChromeClient) InputEvent(android.view.InputEvent) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient) WebResourceRequest(android.webkit.WebResourceRequest) View(android.view.View) WebView(android.webkit.WebView) SuppressLint(android.annotation.SuppressLint) ValueCallback(android.webkit.ValueCallback) Callback(android.webkit.GeolocationPermissions.Callback) WebResourceResponse(android.webkit.WebResourceResponse) DownloadListener(android.webkit.DownloadListener) WebSettings(android.webkit.WebSettings) QuotaUpdater(android.webkit.WebStorage.QuotaUpdater) SuppressLint(android.annotation.SuppressLint) JsPromptResult(android.webkit.JsPromptResult) SuppressLint(android.annotation.SuppressLint)

Example 15 with SslError

use of android.net.http.SslError 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

SslError (android.net.http.SslError)17 SslErrorHandler (android.webkit.SslErrorHandler)12 WebView (android.webkit.WebView)12 WebViewClient (android.webkit.WebViewClient)11 Bitmap (android.graphics.Bitmap)8 View (android.view.View)7 WebSettings (android.webkit.WebSettings)7 Intent (android.content.Intent)6 WebChromeClient (android.webkit.WebChromeClient)6 WebResourceRequest (android.webkit.WebResourceRequest)6 SslCertificate (android.net.http.SslCertificate)5 WebResourceError (android.webkit.WebResourceError)5 WebResourceResponse (android.webkit.WebResourceResponse)5 Uri (android.net.Uri)4 HttpAuthHandler (android.webkit.HttpAuthHandler)4 SuppressLint (android.annotation.SuppressLint)3 X509Certificate (java.security.cert.X509Certificate)3 Activity (android.app.Activity)2 Build (android.os.Build)2 Handler (android.os.Handler)2