Webview avoid security alert from google play upon implementation of onReceivedSslError

58,822

Solution 1

To properly handle SSL certificate validation, change your code to invoke SslErrorHandler.proceed() whenever the certificate presented by the server meets your expectations, and invoke SslErrorHandler.cancel() otherwise.

As email said, onReceivedSslError should handle user is going to a page with invalid cert, such like a notify dialog. You should not proceed it directly.

For example, I add an alert dialog to make user have confirmed and seems Google no longer shows warning.


@Override
public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(R.string.notification_error_ssl_cert_invalid);
    builder.setPositiveButton("continue", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            handler.proceed();
        }
    });
    builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            handler.cancel();
        }
    });
    final AlertDialog dialog = builder.create();
    dialog.show();
}

More explain about the email.

Specifically, the implementation ignores all SSL certificate validation errors, making your app vulnerable to man-in-the-middle attacks.

The email says the default implement ignored an important SSL security problem. So we need to handle it in our own app which used WebView. Notify user with a alert dialog is a simple way.

Solution 2

The proposed solutions so far just bypass the security check, so they are not safe.

What I suggest is to embed the certificate(s) in the App, and when a SslError occurs, check that the server certificate matches one of the embedded certificates.

So here are the steps:

  1. Retrieve the certificate from the website.

    • Open the site on Safari
    • Click on the padlock icon near the website name
    • Click on Show Certificate
    • Drag and drop the certificate in a folder

see https://www.markbrilman.nl/2012/03/howto-save-a-certificate-via-safari-on-mac/

  1. Copy the certificate (.cer file) into the res/raw folder of your app

  2. In your code, load the certificate(s) by calling loadSSLCertificates()

    private static final int[] CERTIFICATES = {
            R.raw.my_certificate,   // you can put several certificates
    };
    private ArrayList<SslCertificate> certificates = new ArrayList<>();
    
    private void loadSSLCertificates() {
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            for (int rawId : CERTIFICATES) {
                InputStream inputStream = getResources().openRawResource(rawId);
                InputStream certificateInput = new BufferedInputStream(inputStream);
                try {
                    Certificate certificate = certificateFactory.generateCertificate(certificateInput);
                    if (certificate instanceof X509Certificate) {
                        X509Certificate x509Certificate = (X509Certificate) certificate;
                        SslCertificate sslCertificate = new SslCertificate(x509Certificate);
                        certificates.add(sslCertificate);
                    } else {
                        Log.w(TAG, "Wrong Certificate format: " + rawId);
                    }
                } catch (CertificateException exception) {
                    Log.w(TAG, "Cannot read certificate: " + rawId);
                } finally {
                    try {
                        certificateInput.close();
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (CertificateException e) {
            e.printStackTrace();
        }
    }
    
  3. When a SslError occurs, check that the server certificate matches one embedded certificate. Note that it is not possible to directly compare certificates, so I use SslCertificate.saveState to put the certificate data into a Bundle, and then I compare all the bundle entries.

    webView.setWebViewClient(new WebViewClient() {
    
        @Override
        public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
    
            // Checks Embedded certificates
            SslCertificate serverCertificate = error.getCertificate();
            Bundle serverBundle = SslCertificate.saveState(serverCertificate);
            for (SslCertificate appCertificate : certificates) {
                if (TextUtils.equals(serverCertificate.toString(), appCertificate.toString())) { // First fast check
                    Bundle appBundle = SslCertificate.saveState(appCertificate);
                    Set<String> keySet = appBundle.keySet();
                    boolean matches = true;
                    for (String key : keySet) {
                        Object serverObj = serverBundle.get(key);
                        Object appObj = appBundle.get(key);
                        if (serverObj instanceof byte[] && appObj instanceof byte[]) {     // key "x509-certificate"
                            if (!Arrays.equals((byte[]) serverObj, (byte[]) appObj)) {
                                matches = false;
                                break;
                            }
                        } else if ((serverObj != null) && !serverObj.equals(appObj)) {
                            matches = false;
                            break;
                        }
                    }
                    if (matches) {
                        handler.proceed();
                        return;
                    }
                }
            }
    
            handler.cancel();
            String message = "SSL Error " + error.getPrimaryError();
            Log.w(TAG, message);
        }
    
    
    });
    

Solution 3

I needed to check our truststore before show any message to the user so I did this:

public class MyWebViewClient extends WebViewClient {
private static final String TAG = MyWebViewClient.class.getCanonicalName();

Resources resources;
Context context;

public MyWebViewClient(Resources resources, Context context){
    this.resources = resources;
    this.context = context;
}

@Override
public void onReceivedSslError(WebView v, final SslErrorHandler handler, SslError er){
    // first check certificate with our truststore
    // if not trusted, show dialog to user
    // if trusted, proceed
    try {
        TrustManagerFactory tmf = TrustManagerUtil.getTrustManagerFactory(resources);

        for(TrustManager t: tmf.getTrustManagers()){
            if (t instanceof X509TrustManager) {

                X509TrustManager trustManager = (X509TrustManager) t;

                Bundle bundle = SslCertificate.saveState(er.getCertificate());
                X509Certificate x509Certificate;
                byte[] bytes = bundle.getByteArray("x509-certificate");
                if (bytes == null) {
                    x509Certificate = null;
                } else {
                    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
                    Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
                    x509Certificate = (X509Certificate) cert;
                }
                X509Certificate[] x509Certificates = new X509Certificate[1];
                x509Certificates[0] = x509Certificate;

                trustManager.checkServerTrusted(x509Certificates, "ECDH_RSA");
            }
        }
        Log.d(TAG, "Certificate from " + er.getUrl() + " is trusted.");
        handler.proceed();
    }catch(Exception e){
        Log.d(TAG, "Failed to access " + er.getUrl() + ". Error: " + er.getPrimaryError());
        final AlertDialog.Builder builder = new AlertDialog.Builder(context);
        String message = "SSL Certificate error.";
        switch (er.getPrimaryError()) {
            case SslError.SSL_UNTRUSTED:
                message = "O certificado não é confiável.";
                break;
            case SslError.SSL_EXPIRED:
                message = "O certificado expirou.";
                break;
            case SslError.SSL_IDMISMATCH:
                message = "Hostname inválido para o certificado.";
                break;
            case SslError.SSL_NOTYETVALID:
                message = "O certificado é inválido.";
                break;
        }
        message += " Deseja continuar mesmo assim?";

        builder.setTitle("Erro");
        builder.setMessage(message);
        builder.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                handler.proceed();
            }
        });
        builder.setNegativeButton("Não", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                handler.cancel();
            }
        });
        final AlertDialog dialog = builder.create();
        dialog.show();
    }
}
}

Solution 4

Fix which works for me is just disable onReceivedSslError function defined in AuthorizationWebViewClient. In this case handler.cancel will be called in case of SSL error. However it works good with One Drive SSL certificates. Tested on Android 2.3.7, Android 5.1.

Solution 5

According to Google Security Alert: Unsafe implementation of the interface X509TrustManager, Google Play won't support X509TrustManager from 11th July 2016:

Hello Google Play Developer,

Your app(s) listed at the end of this email use an unsafe implementation of the interface X509TrustManager. Specifically, the implementation ignores all SSL certificate validation errors when establishing an HTTPS connection to a remote host, thereby making your app vulnerable to man-in-the-middle attacks. An attacker could read transmitted data (such as login credentials) and even change the data transmitted on the HTTPS connection. If you have more than 20 affected apps in your account, please check the Developer Console for a full list.

To properly handle SSL certificate validation, change your code in the checkServerTrusted method of your custom X509TrustManager interface to raise either CertificateException or IllegalArgumentException whenever the certificate presented by the server does not meet your expectations. For technical questions, you can post to Stack Overflow and use the tags “android-security” and “TrustManager.”

Please address this issue as soon as possible and increment the version number of the upgraded APK. Beginning May 17, 2016, Google Play will block publishing of any new apps or updates containing the unsafe implementation of the interface X509TrustManager.

To confirm you’ve made the correct changes, submit the updated version of your app to the Developer Console and check back after five hours. If the app hasn’t been correctly upgraded, we will display a warning.

While these specific issues may not affect every app with the TrustManager implementation, it’s best not to ignore SSL certificate validation errors. Apps with vulnerabilities that expose users to risk of compromise may be considered dangerous products in violation of the Content Policy and section 4.4 of the Developer Distribution Agreement.

...

Share:
58,822
captaindroid
Author by

captaindroid

all work and no play makes Jack a dull boy ♫

Updated on July 05, 2022

Comments

  • captaindroid
    captaindroid almost 2 years

    I have a link which will open in webview. The problem is it cannot be open until I override onReceivedSslError like this:

     @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
    

    I am getting security alert from google play saying:

    Security alert Your application has an unsafe implementation of the WebViewClient.onReceivedSslError handler. Specifically, the implementation ignores all SSL certificate validation errors, making your app vulnerable to man-in-the-middle attacks. An attacker could change the affected WebView's content, read transmitted data (such as login credentials), and execute code inside the app using JavaScript.

    To properly handle SSL certificate validation, change your code to invoke SslErrorHandler.proceed() whenever the certificate presented by the server meets your expectations, and invoke SslErrorHandler.cancel() otherwise. An email alert containing the affected app(s) and class(es) has been sent to your developer account address.

    Please address this vulnerability as soon as possible and increment the version number of the upgraded APK. For more information about the SSL error handler, please see our documentation in the Developer Help Center. For other technical questions, you can post to https://www.stackoverflow.com/questions and use the tags “android-security” and “SslErrorHandler.” If you are using a 3rd party library that’s responsible for this, please notify the 3rd party and work with them to address the issue.

    To confirm that you've upgraded correctly, upload the updated version to the Developer Console and check back after five hours. If the app hasn't been correctly upgraded, we will display a warning.

    Please note, while these specific issues may not affect every app that uses WebView SSL, it's best to stay up to date on all security patches. Apps with vulnerabilities that expose users to risk of compromise may be considered dangerous products in violation of the Content Policy and section 4.4 of the Developer Distribution Agreement.

    Please ensure all apps published are compliant with the Developer Distribution Agreement and Content Policy. If you have questions or concerns, please contact our support team through the Google Play Developer Help Center.

    If I remove onReceivedSslError (handler.proceed()), then page won't open.

    Is there anyway I can open page in webview and avoid security alert.

  • captaindroid
    captaindroid over 8 years
    I will update the code and will push to play store. Will let you know, Thanks.
  • David Gourde
    David Gourde almost 8 years
    It is important to to add the important part of linked articles.
  • jww
    jww almost 8 years
    X509TrustManager will still be supported. The issue is with developer's override of its methods, and doing things like VERIFY_NONE so there are no exceptions. Also see The most dangerous code in the world: validating SSL certificates in non-browser software.
  • oldergod
    oldergod almost 8 years
    The email does not actually say we should specify the user about anything, am I wrong?
  • Aman Gupta -  ΔMΔN
    Aman Gupta - ΔMΔN over 7 years
    Can you please give more explanation that why is warning shows.
  • Huy Tower
    Huy Tower over 7 years
    @sakiM : Is possible to not use onReceivedSslError() or not Override code inside? Is it better?
  • sakiM
    sakiM over 7 years
    @TranDucHuy the google warning indicate the inside WebView should notify handle the invalid certification problem. Maybe reject all these cases also can do it?
  • Huy Tower
    Huy Tower over 7 years
    Is it necessary to check case onReceiveSslError? Why we not ignored that case? I delete onReceiveSslError method without error also.
  • Bao HQ
    Bao HQ over 7 years
    IN my case, I implement this like @sakiM said. But google still rejected. Someone give me other solutions?
  • DevAndroid
    DevAndroid over 7 years
    Can't we simply call handler.cancel(); inside onReceivedSslError? Will google still reject it?
  • DevAndroid
    DevAndroid over 7 years
    Can't we simply call handler.cancel(); inside onReceivedSslError? Will google still reject it?
  • DevAndroid
    DevAndroid over 7 years
    Can't we simply call handler.cancel(); inside onReceivedSslError? Will google still reject it?
  • captaindroid
    captaindroid about 7 years
    @BaulHoa, by showing the above dialog works for me, please check your code carefully, there may be code yet to handle the onReceiveSslError(). Did you get the same email (as I got) from google again ?
  • Sandip Lawate
    Sandip Lawate about 7 years
    @DevAndroid : Did it worked by simply calling handler.cancel(); inside onReceivedSslError ?
  • nik
    nik about 7 years
    final AlertDialog.Builder builder = new AlertDialog.Builder(this); it is not accepting "this" as parameter as i have copied this code to SystemWebViewClient.java(cordova app).So what I need to pass here?
  • Vishesh Chandra
    Vishesh Chandra about 7 years
    @sakiM I added the same code and Google rejected again with same reason. Any idea?
  • varotariya vajsi
    varotariya vajsi about 7 years
    I got response from google support team that "vulnerable version of SslErrorHandler: com.backendless.SocialAsyncCallback$1;" so i update version of backendless library and issue solved...you can check more from stackoverflow.com/questions/35720753/…
  • Pabel
    Pabel almost 7 years
    @DevAndroid Google cancels that option because you do not inform the user. With this method filtering the error shows more information that because the connection has been rejected
  • livemaker
    livemaker over 6 years
    Is there any way to solve this without a alert dialog, Is it possible to add certificate for web view from server.
  • captaindroid
    captaindroid over 6 years
    @livemaker I don't think , google will reject the app from playstore without confirmation alert dialog. I tried by submitting the app multiple times without alert dialog and google keep sending me the security alert.
  • Parag Chauhan
    Parag Chauhan over 5 years
    I am facing same an issue any one got solution?
  • ShriKant A
    ShriKant A over 3 years
    what is TrustManagerUtil .how to implement it
  • AmandaHLA
    AmandaHLA over 3 years
  • S.Ambika
    S.Ambika about 3 years
    But if we disable onReceivedSslError method & remove handler.proceed then Webview is not able to load URL. What should be done in this case? I have asked this question here stackoverflow.com/q/65949051/8063842 BUT DIDN'T GET ANY SOLUTION
  • Shashank singh
    Shashank singh about 3 years
    Hey, So finally which suggestion you take in above one. Please mention this, I am also facing this issue.
  • Udara Seneviratne
    Udara Seneviratne about 3 years
    @Shashanksingh we did a full rollout to the latest version.
  • Shashank singh
    Shashank singh about 3 years
    That I got it, just want did you remove onReceivedSslError method or you implement it with call handler.cancel(); always?
  • Shashank singh
    Shashank singh about 3 years
    From the above 4 methods which is mentioned in your answer by which you proceed. I need that help.
  • Udara Seneviratne
    Udara Seneviratne about 3 years
    @Shashanksingh You can follow the 4th approach and no need to override onReceivedSslError() if it not really required. Let it to happen according to android default behaviour.
  • Shashank singh
    Shashank singh about 3 years
    Thanks @Udara Seneviratne
  • idumban
    idumban almost 3 years
    is possible to solve the issue without alert message?
  • Prosenjith Roy
    Prosenjith Roy over 2 years
    I implement this like @sakiM said. But google still rejected. Someone please help me?