587c33e7eaaf5dddb5a5a15e961573b020bc18ec
[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.R;
28 import com.owncloud.android.lib.common.network.NetworkUtils;
29 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;
30 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;
31 import com.owncloud.android.utils.Log_OC;
32
33 import android.app.AlertDialog;
34 import android.content.Context;
35 import android.content.DialogInterface;
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.FragmentActivity;
43 import android.support.v4.app.FragmentManager;
44 import android.support.v4.app.FragmentTransaction;
45 import android.view.KeyEvent;
46 import android.view.View;
47 import android.webkit.CookieManager;
48 import android.webkit.HttpAuthHandler;
49 import android.webkit.SslErrorHandler;
50 import android.webkit.WebResourceResponse;
51 import android.webkit.WebView;
52 import android.webkit.WebViewClient;
53
54
55 /**
56 * Custom {@link WebViewClient} client aimed to catch the end of a single-sign-on process
57 * running in the {@link WebView} that is attached to.
58 *
59 * Assumes that the single-sign-on is kept thanks to a cookie set at the end of the
60 * authentication process.
61 *
62 * @author David A. Velasco
63 */
64 public class SsoWebViewClient extends WebViewClient implements OnSslUntrustedCertListener {
65
66 private static final String TAG = SsoWebViewClient.class.getSimpleName();
67
68 public final static String DIALOG_UNTRUSTED_CERT = "UNTRUSTED CERT";
69
70 public interface SsoWebViewClientListener {
71 public void onSsoFinished(String sessionCookie);
72 }
73
74 private Context mContext;
75 private Handler mListenerHandler;
76 private WeakReference<SsoWebViewClientListener> mListenerRef;
77 private String mTargetUrl;
78 private String mLastReloadedUrlAtError;
79
80 public SsoWebViewClient (Context context, Handler listenerHandler, SsoWebViewClientListener listener) {
81 mContext = context;
82 mListenerHandler = listenerHandler;
83 mListenerRef = new WeakReference<SsoWebViewClient.SsoWebViewClientListener>(listener);
84 mTargetUrl = "fake://url.to.be.set";
85 mLastReloadedUrlAtError = null;
86 }
87
88 public String getTargetUrl() {
89 return mTargetUrl;
90 }
91
92 public void setTargetUrl(String targetUrl) {
93 mTargetUrl = targetUrl;
94 }
95
96 @Override
97 public void onPageStarted (WebView view, String url, Bitmap favicon) {
98 Log_OC.d(TAG, "onPageStarted : " + url);
99 super.onPageStarted(view, url, favicon);
100 }
101
102 @Override
103 public void onFormResubmission (WebView view, Message dontResend, Message resend) {
104 Log_OC.d(TAG, "onFormResubMission ");
105
106 // necessary to grant reload of last page when device orientation is changed after sending a form
107 resend.sendToTarget();
108 }
109
110 @Override
111 public boolean shouldOverrideUrlLoading(WebView view, String url) {
112 return false;
113 }
114
115 @Override
116 public void onReceivedError (WebView view, int errorCode, String description, String failingUrl) {
117 Log_OC.e(TAG, "onReceivedError : " + failingUrl + ", code " + errorCode + ", description: " + description);
118 if (!failingUrl.equals(mLastReloadedUrlAtError)) {
119 view.reload();
120 mLastReloadedUrlAtError = failingUrl;
121 } else {
122 mLastReloadedUrlAtError = null;
123 super.onReceivedError(view, errorCode, description, failingUrl);
124 }
125 }
126
127 @Override
128 public void onPageFinished (WebView view, String url) {
129 Log_OC.d(TAG, "onPageFinished : " + url);
130 mLastReloadedUrlAtError = null;
131 if (url.startsWith(mTargetUrl)) {
132 view.setVisibility(View.GONE);
133 CookieManager cookieManager = CookieManager.getInstance();
134 final String cookies = cookieManager.getCookie(url);
135 Log_OC.d(TAG, "Cookies: " + cookies);
136 if (mListenerHandler != null && mListenerRef != null) {
137 // this is good idea because onPageFinished is not running in the UI thread
138 mListenerHandler.post(new Runnable() {
139 @Override
140 public void run() {
141 SsoWebViewClientListener listener = mListenerRef.get();
142 if (listener != null) {
143 // Send Cookies to the listener
144 listener.onSsoFinished(cookies);
145 }
146 }
147 });
148 }
149 }
150 }
151
152
153 @Override
154 public void doUpdateVisitedHistory (WebView view, String url, boolean isReload) {
155 Log_OC.d(TAG, "doUpdateVisitedHistory : " + url);
156 }
157
158 @Override
159 public void onReceivedSslError (final WebView view, final SslErrorHandler handler, SslError error) {
160 Log_OC.d(TAG, "onReceivedSslError : " + error);
161 // Test 1
162 X509Certificate x509Certificate = getX509CertificateFromError(error);
163 boolean isKnowServer = false;
164
165 if (x509Certificate != null) {
166 Log_OC.d(TAG, "------>>>>> x509Certificate " + x509Certificate.toString());
167
168 try {
169 isKnowServer = NetworkUtils.isCertInKnownServersStore((Certificate) x509Certificate, mContext);
170 } catch (Exception e) {
171 Log_OC.e(TAG, "Exception: " + e.getMessage());
172 }
173 }
174
175 if (isKnowServer) {
176 handler.proceed();
177 } else {
178 // Show a dialog with the certificate info
179 SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstance(mContext, x509Certificate, this, handler);
180 FragmentManager fm = ((FragmentActivity)mContext).getSupportFragmentManager();
181 FragmentTransaction ft = fm.beginTransaction();
182 dialog.show(ft, DIALOG_UNTRUSTED_CERT);
183 handler.cancel();
184 }
185 }
186
187 /**
188 * Obtain the X509Certificate from SslError
189 * @param error SslError
190 * @return X509Certificate from error
191 */
192 public X509Certificate getX509CertificateFromError (SslError error) {
193 Bundle bundle = SslCertificate.saveState(error.getCertificate());
194 X509Certificate x509Certificate;
195 byte[] bytes = bundle.getByteArray("x509-certificate");
196 if (bytes == null) {
197 x509Certificate = null;
198 } else {
199 try {
200 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
201 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
202 x509Certificate = (X509Certificate) cert;
203 } catch (CertificateException e) {
204 x509Certificate = null;
205 }
206 }
207 return x509Certificate;
208 }
209
210 @Override
211 public void onReceivedHttpAuthRequest (WebView view, HttpAuthHandler handler, String host, String realm) {
212 Log_OC.d(TAG, "onReceivedHttpAuthRequest : " + host);
213 }
214
215 @Override
216 public WebResourceResponse shouldInterceptRequest (WebView view, String url) {
217 Log_OC.d(TAG, "shouldInterceptRequest : " + url);
218 return null;
219 }
220
221 @Override
222 public void onLoadResource (WebView view, String url) {
223 Log_OC.d(TAG, "onLoadResource : " + url);
224 }
225
226 @Override
227 public void onReceivedLoginRequest (WebView view, String realm, String account, String args) {
228 Log_OC.d(TAG, "onReceivedLoginRequest : " + realm + ", " + account + ", " + args);
229 }
230
231 @Override
232 public void onScaleChanged (WebView view, float oldScale, float newScale) {
233 Log_OC.d(TAG, "onScaleChanged : " + oldScale + " -> " + newScale);
234 super.onScaleChanged(view, oldScale, newScale);
235 }
236
237 @Override
238 public void onUnhandledKeyEvent (WebView view, KeyEvent event) {
239 Log_OC.d(TAG, "onUnhandledKeyEvent : " + event);
240 }
241
242 @Override
243 public boolean shouldOverrideKeyEvent (WebView view, KeyEvent event) {
244 Log_OC.d(TAG, "shouldOverrideKeyEvent : " + event);
245 return false;
246 }
247
248 @Override
249 public void onFailedSavingCertificate() {
250 AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
251 builder.setMessage(mContext.getString(R.string.ssl_validator_not_saved));
252 builder.setCancelable(false);
253 builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
254 @Override
255 public void onClick(DialogInterface dialog, int which) {
256 dialog.dismiss();
257 };
258 });
259 builder.create().show();
260
261 }
262
263 }