OC-3212: Show appropiate error messages for SslError in SSL error dialog shown by...
[pub/Android/ownCloud.git] / src / com / owncloud / android / authentication / SsoWebViewClient.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012-2013 ownCloud Inc.
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2,
6 * as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 */
17
18 package com.owncloud.android.authentication;
19
20 import java.io.ByteArrayInputStream;
21 import java.lang.ref.WeakReference;
22 import java.security.cert.Certificate;
23 import java.security.cert.CertificateException;
24 import java.security.cert.CertificateFactory;
25 import java.security.cert.X509Certificate;
26
27 import com.owncloud.android.lib.common.network.NetworkUtils;
28 import com.actionbarsherlock.app.SherlockFragmentActivity;
29 import com.owncloud.android.R;
30 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;
31 import com.owncloud.android.ui.dialog.SslUntrustedCertDialogABSTRACT;
32 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;
33 import com.owncloud.android.utils.Log_OC;
34
35 import android.content.Context;
36 import android.graphics.Bitmap;
37 import android.net.http.SslCertificate;
38 import android.net.http.SslError;
39 import android.os.Bundle;
40 import android.os.Handler;
41 import android.os.Message;
42 import android.support.v4.app.FragmentManager;
43 import android.support.v4.app.FragmentTransaction;
44 import android.view.KeyEvent;
45 import android.view.View;
46 import android.webkit.CookieManager;
47 import android.webkit.HttpAuthHandler;
48 import android.webkit.SslErrorHandler;
49 import android.webkit.WebResourceResponse;
50 import android.webkit.WebView;
51 import android.webkit.WebViewClient;
52
53
54 /**
55 * Custom {@link WebViewClient} client aimed to catch the end of a single-sign-on process
56 * running in the {@link WebView} that is attached to.
57 *
58 * Assumes that the single-sign-on is kept thanks to a cookie set at the end of the
59 * authentication process.
60 *
61 * @author David A. Velasco
62 */
63 public class SsoWebViewClient extends WebViewClient {
64
65 private static final String TAG = SsoWebViewClient.class.getSimpleName();
66
67 public interface SsoWebViewClientListener {
68 public void onSsoFinished(String sessionCookie);
69 }
70
71 private Context mContext;
72 private Handler mListenerHandler;
73 private WeakReference<SsoWebViewClientListener> mListenerRef;
74 private String mTargetUrl;
75 private String mLastReloadedUrlAtError;
76
77 public SsoWebViewClient (Context context, Handler listenerHandler, SsoWebViewClientListener listener) {
78 mContext = context;
79 mListenerHandler = listenerHandler;
80 mListenerRef = new WeakReference<SsoWebViewClient.SsoWebViewClientListener>(listener);
81 mTargetUrl = "fake://url.to.be.set";
82 mLastReloadedUrlAtError = null;
83 }
84
85 public String getTargetUrl() {
86 return mTargetUrl;
87 }
88
89 public void setTargetUrl(String targetUrl) {
90 mTargetUrl = targetUrl;
91 }
92
93 @Override
94 public void onPageStarted (WebView view, String url, Bitmap favicon) {
95 Log_OC.d(TAG, "onPageStarted : " + url);
96 super.onPageStarted(view, url, favicon);
97 }
98
99 @Override
100 public void onFormResubmission (WebView view, Message dontResend, Message resend) {
101 Log_OC.d(TAG, "onFormResubMission ");
102
103 // necessary to grant reload of last page when device orientation is changed after sending a form
104 resend.sendToTarget();
105 }
106
107 @Override
108 public boolean shouldOverrideUrlLoading(WebView view, String url) {
109 return false;
110 }
111
112 @Override
113 public void onReceivedError (WebView view, int errorCode, String description, String failingUrl) {
114 Log_OC.e(TAG, "onReceivedError : " + failingUrl + ", code " + errorCode + ", description: " + description);
115 if (!failingUrl.equals(mLastReloadedUrlAtError)) {
116 view.reload();
117 mLastReloadedUrlAtError = failingUrl;
118 } else {
119 mLastReloadedUrlAtError = null;
120 super.onReceivedError(view, errorCode, description, failingUrl);
121 }
122 }
123
124 @Override
125 public void onPageFinished (WebView view, String url) {
126 Log_OC.d(TAG, "onPageFinished : " + url);
127 mLastReloadedUrlAtError = null;
128 if (url.startsWith(mTargetUrl)) {
129 view.setVisibility(View.GONE);
130 CookieManager cookieManager = CookieManager.getInstance();
131 final String cookies = cookieManager.getCookie(url);
132 Log_OC.d(TAG, "Cookies: " + cookies);
133 if (mListenerHandler != null && mListenerRef != null) {
134 // this is good idea because onPageFinished is not running in the UI thread
135 mListenerHandler.post(new Runnable() {
136 @Override
137 public void run() {
138 SsoWebViewClientListener listener = mListenerRef.get();
139 if (listener != null) {
140 // Send Cookies to the listener
141 listener.onSsoFinished(cookies);
142 }
143 }
144 });
145 }
146 }
147 }
148
149
150 @Override
151 public void doUpdateVisitedHistory (WebView view, String url, boolean isReload) {
152 Log_OC.d(TAG, "doUpdateVisitedHistory : " + url);
153 }
154
155 @Override
156 public void onReceivedSslError (final WebView view, final SslErrorHandler handler, SslError error) {
157 Log_OC.d(TAG, "onReceivedSslError : " + error);
158 // Test 1
159 X509Certificate x509Certificate = getX509CertificateFromError(error);
160 boolean isKnownServer = false;
161
162 if (x509Certificate != null) {
163 Log_OC.d(TAG, "------>>>>> x509Certificate " + x509Certificate.toString());
164
165 try {
166 isKnownServer = NetworkUtils.isCertInKnownServersStore((Certificate) x509Certificate, mContext);
167 } catch (Exception e) {
168 Log_OC.e(TAG, "Exception: " + e.getMessage());
169 }
170 }
171
172 if (isKnownServer) {
173 handler.proceed();
174 } else if (x509Certificate != null) {
175 // Show a dialog with the certificate info
176 ((AuthenticatorActivity)mContext).showUntrustedCertDialog(x509Certificate, error);
177 handler.cancel();
178 } else {
179 // Show a dialog with the certificate information available in SslError (not full)
180 SslUntrustedCertDialogABSTRACT dialog = SslUntrustedCertDialogABSTRACT.newInstanceForEmptySslError(error, handler);
181 FragmentManager fm = ((SherlockFragmentActivity)mContext).getSupportFragmentManager();
182 FragmentTransaction ft = fm.beginTransaction();
183 dialog.show(ft, AuthenticatorActivity.DIALOG_UNTRUSTED_CERT);
184 // let's forward the handler, and see what happens...
185 }
186 }
187
188 /**
189 * Obtain the X509Certificate from SslError
190 * @param error SslError
191 * @return X509Certificate from error
192 */
193 public X509Certificate getX509CertificateFromError (SslError error) {
194 Bundle bundle = SslCertificate.saveState(error.getCertificate());
195 X509Certificate x509Certificate;
196 byte[] bytes = bundle.getByteArray("x509-certificate");
197 if (bytes == null) {
198 x509Certificate = null;
199 } else {
200 try {
201 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
202 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
203 x509Certificate = (X509Certificate) cert;
204 } catch (CertificateException e) {
205 x509Certificate = null;
206 }
207 }
208 return x509Certificate;
209 }
210
211 @Override
212 public void onReceivedHttpAuthRequest (WebView view, HttpAuthHandler handler, String host, String realm) {
213 Log_OC.d(TAG, "onReceivedHttpAuthRequest : " + host);
214 }
215
216 @Override
217 public WebResourceResponse shouldInterceptRequest (WebView view, String url) {
218 Log_OC.d(TAG, "shouldInterceptRequest : " + url);
219 return null;
220 }
221
222 @Override
223 public void onLoadResource (WebView view, String url) {
224 Log_OC.d(TAG, "onLoadResource : " + url);
225 }
226
227 @Override
228 public void onReceivedLoginRequest (WebView view, String realm, String account, String args) {
229 Log_OC.d(TAG, "onReceivedLoginRequest : " + realm + ", " + account + ", " + args);
230 }
231
232 @Override
233 public void onScaleChanged (WebView view, float oldScale, float newScale) {
234 Log_OC.d(TAG, "onScaleChanged : " + oldScale + " -> " + newScale);
235 super.onScaleChanged(view, oldScale, newScale);
236 }
237
238 @Override
239 public void onUnhandledKeyEvent (WebView view, KeyEvent event) {
240 Log_OC.d(TAG, "onUnhandledKeyEvent : " + event);
241 }
242
243 @Override
244 public boolean shouldOverrideKeyEvent (WebView view, KeyEvent event) {
245 Log_OC.d(TAG, "shouldOverrideKeyEvent : " + event);
246 return false;
247 }
248
249 }