Session cookie caught and saved to use in requests after successful SAML-based federa...
[pub/Android/ownCloud.git] / src / com / owncloud / android / network / OwnCloudClientUtils.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 package com.owncloud.android.network;
18
19 import java.io.File;
20 import java.io.FileInputStream;
21 import java.io.FileOutputStream;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.security.GeneralSecurityException;
25 import java.security.KeyStore;
26 import java.security.KeyStoreException;
27 import java.security.NoSuchAlgorithmException;
28 import java.security.cert.Certificate;
29 import java.security.cert.CertificateException;
30
31 import javax.net.ssl.SSLContext;
32 import javax.net.ssl.TrustManager;
33
34 import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
35 import org.apache.commons.httpclient.protocol.Protocol;
36 import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier;
37 import org.apache.http.conn.ssl.X509HostnameVerifier;
38
39 import com.owncloud.android.authentication.AccountAuthenticator;
40 import com.owncloud.android.authentication.AccountUtils;
41 import com.owncloud.android.authentication.AccountUtils.AccountNotFoundException;
42 import com.owncloud.android.Log_OC;
43
44 import eu.alefzero.webdav.WebdavClient;
45
46 import android.accounts.Account;
47 import android.accounts.AccountManager;
48 import android.accounts.AccountManagerFuture;
49 import android.accounts.AuthenticatorException;
50 import android.accounts.OperationCanceledException;
51 import android.app.Activity;
52 import android.content.Context;
53 import android.net.Uri;
54 import android.os.Bundle;
55
56 public class OwnCloudClientUtils {
57
58 final private static String TAG = OwnCloudClientUtils.class.getSimpleName();
59
60 /** Default timeout for waiting data from the server */
61 public static final int DEFAULT_DATA_TIMEOUT = 60000;
62
63 /** Default timeout for establishing a connection */
64 public static final int DEFAULT_CONNECTION_TIMEOUT = 60000;
65
66 /** Connection manager for all the WebdavClients */
67 private static MultiThreadedHttpConnectionManager mConnManager = null;
68
69 private static Protocol mDefaultHttpsProtocol = null;
70
71 private static AdvancedSslSocketFactory mAdvancedSslSocketFactory = null;
72
73 private static X509HostnameVerifier mHostnameVerifier = null;
74
75
76 /**
77 * Creates a WebdavClient setup for an ownCloud account
78 *
79 * Do not call this method from the main thread.
80 *
81 * @param account The ownCloud account
82 * @param appContext Android application context
83 * @return A WebdavClient object ready to be used
84 * @throws AuthenticatorException If the authenticator failed to get the authorization token for the account.
85 * @throws OperationCanceledException If the authenticator operation was cancelled while getting the authorization token for the account.
86 * @throws IOException If there was some I/O error while getting the authorization token for the account.
87 * @throws AccountNotFoundException If 'account' is unknown for the AccountManager
88 */
89 public static WebdavClient createOwnCloudClient (Account account, Context appContext) throws OperationCanceledException, AuthenticatorException, IOException, AccountNotFoundException {
90 //Log_OC.d(TAG, "Creating WebdavClient associated to " + account.name);
91
92 Uri uri = Uri.parse(AccountUtils.constructFullURLForAccount(appContext, account));
93 WebdavClient client = createOwnCloudClient(uri, appContext, true);
94 AccountManager am = AccountManager.get(appContext);
95 if (am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null) { // TODO avoid a call to getUserData here
96 String accessToken = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, false);
97 client.setBearerCredentials(accessToken); // TODO not assume that the access token is a bearer token
98
99 } else if (am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO) != null) { // TODO avoid a call to getUserData here
100 String accessToken = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE, false);
101 client.setSsoSessionCookie(accessToken);
102
103 } else {
104 String username = account.name.substring(0, account.name.lastIndexOf('@'));
105 //String password = am.getPassword(account);
106 String password = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD, false);
107 client.setBasicCredentials(username, password);
108 }
109
110 return client;
111 }
112
113
114 public static WebdavClient createOwnCloudClient (Account account, Context appContext, Activity currentActivity) throws OperationCanceledException, AuthenticatorException, IOException, AccountNotFoundException {
115 Uri uri = Uri.parse(AccountUtils.constructFullURLForAccount(appContext, account));
116 WebdavClient client = createOwnCloudClient(uri, appContext, true);
117 AccountManager am = AccountManager.get(appContext);
118 if (am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null) { // TODO avoid a call to getUserData here
119 AccountManagerFuture<Bundle> future = am.getAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, null, currentActivity, null, null);
120 Bundle result = future.getResult();
121 String accessToken = result.getString(AccountManager.KEY_AUTHTOKEN);
122 if (accessToken == null) throw new AuthenticatorException("WTF!");
123 client.setBearerCredentials(accessToken); // TODO not assume that the access token is a bearer token
124
125 } else if (am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO) != null) { // TODO avoid a call to getUserData here
126 AccountManagerFuture<Bundle> future = am.getAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE, null, currentActivity, null, null);
127 Bundle result = future.getResult();
128 String accessToken = result.getString(AccountManager.KEY_AUTHTOKEN);
129 if (accessToken == null) throw new AuthenticatorException("WTF!");
130 client.setSsoSessionCookie(accessToken);
131
132 } else {
133 String username = account.name.substring(0, account.name.lastIndexOf('@'));
134 //String password = am.getPassword(account);
135 //String password = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD, false);
136 AccountManagerFuture<Bundle> future = am.getAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD, null, currentActivity, null, null);
137 Bundle result = future.getResult();
138 String password = result.getString(AccountManager.KEY_AUTHTOKEN);
139 client.setBasicCredentials(username, password);
140 }
141
142 return client;
143 }
144
145 /**
146 * Creates a WebdavClient to access a URL and sets the desired parameters for ownCloud client connections.
147 *
148 * @param uri URL to the ownCloud server
149 * @param context Android context where the WebdavClient is being created.
150 * @return A WebdavClient object ready to be used
151 */
152 public static WebdavClient createOwnCloudClient(Uri uri, Context context, boolean followRedirects) {
153 try {
154 registerAdvancedSslContext(true, context);
155 } catch (GeneralSecurityException e) {
156 Log_OC.e(TAG, "Advanced SSL Context could not be loaded. Default SSL management in the system will be used for HTTPS connections", e);
157
158 } catch (IOException e) {
159 Log_OC.e(TAG, "The local server truststore could not be read. Default SSL management in the system will be used for HTTPS connections", e);
160 }
161
162 WebdavClient client = new WebdavClient(getMultiThreadedConnManager());
163
164 client.setDefaultTimeouts(DEFAULT_DATA_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);
165 client.setBaseUri(uri);
166 client.setFollowRedirects(followRedirects);
167
168 return client;
169 }
170
171
172 /**
173 * Registers or unregisters the proper components for advanced SSL handling.
174 * @throws IOException
175 */
176 private static void registerAdvancedSslContext(boolean register, Context context) throws GeneralSecurityException, IOException {
177 Protocol pr = null;
178 try {
179 pr = Protocol.getProtocol("https");
180 if (pr != null && mDefaultHttpsProtocol == null) {
181 mDefaultHttpsProtocol = pr;
182 }
183 } catch (IllegalStateException e) {
184 // nothing to do here; really
185 }
186 boolean isRegistered = (pr != null && pr.getSocketFactory() instanceof AdvancedSslSocketFactory);
187 if (register && !isRegistered) {
188 Protocol.registerProtocol("https", new Protocol("https", getAdvancedSslSocketFactory(context), 443));
189
190 } else if (!register && isRegistered) {
191 if (mDefaultHttpsProtocol != null) {
192 Protocol.registerProtocol("https", mDefaultHttpsProtocol);
193 }
194 }
195 }
196
197 public static AdvancedSslSocketFactory getAdvancedSslSocketFactory(Context context) throws GeneralSecurityException, IOException {
198 if (mAdvancedSslSocketFactory == null) {
199 KeyStore trustStore = getKnownServersStore(context);
200 AdvancedX509TrustManager trustMgr = new AdvancedX509TrustManager(trustStore);
201 TrustManager[] tms = new TrustManager[] { trustMgr };
202
203 SSLContext sslContext = SSLContext.getInstance("TLS");
204 sslContext.init(null, tms, null);
205
206 mHostnameVerifier = new BrowserCompatHostnameVerifier();
207 mAdvancedSslSocketFactory = new AdvancedSslSocketFactory(sslContext, trustMgr, mHostnameVerifier);
208 }
209 return mAdvancedSslSocketFactory;
210 }
211
212
213 private static String LOCAL_TRUSTSTORE_FILENAME = "knownServers.bks";
214
215 private static String LOCAL_TRUSTSTORE_PASSWORD = "password";
216
217 private static KeyStore mKnownServersStore = null;
218
219 /**
220 * Returns the local store of reliable server certificates, explicitly accepted by the user.
221 *
222 * Returns a KeyStore instance with empty content if the local store was never created.
223 *
224 * Loads the store from the storage environment if needed.
225 *
226 * @param context Android context where the operation is being performed.
227 * @return KeyStore instance with explicitly-accepted server certificates.
228 * @throws KeyStoreException When the KeyStore instance could not be created.
229 * @throws IOException When an existing local trust store could not be loaded.
230 * @throws NoSuchAlgorithmException When the existing local trust store was saved with an unsupported algorithm.
231 * @throws CertificateException When an exception occurred while loading the certificates from the local trust store.
232 */
233 private static KeyStore getKnownServersStore(Context context) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
234 if (mKnownServersStore == null) {
235 //mKnownServersStore = KeyStore.getInstance("BKS");
236 mKnownServersStore = KeyStore.getInstance(KeyStore.getDefaultType());
237 File localTrustStoreFile = new File(context.getFilesDir(), LOCAL_TRUSTSTORE_FILENAME);
238 Log_OC.d(TAG, "Searching known-servers store at " + localTrustStoreFile.getAbsolutePath());
239 if (localTrustStoreFile.exists()) {
240 InputStream in = new FileInputStream(localTrustStoreFile);
241 try {
242 mKnownServersStore.load(in, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
243 } finally {
244 in.close();
245 }
246 } else {
247 mKnownServersStore.load(null, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); // necessary to initialize an empty KeyStore instance
248 }
249 }
250 return mKnownServersStore;
251 }
252
253
254 public static void addCertToKnownServersStore(Certificate cert, Context context) throws KeyStoreException, NoSuchAlgorithmException,
255 CertificateException, IOException {
256 KeyStore knownServers = getKnownServersStore(context);
257 knownServers.setCertificateEntry(Integer.toString(cert.hashCode()), cert);
258 FileOutputStream fos = null;
259 try {
260 fos = context.openFileOutput(LOCAL_TRUSTSTORE_FILENAME, Context.MODE_PRIVATE);
261 knownServers.store(fos, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
262 } finally {
263 fos.close();
264 }
265 }
266
267
268 static private MultiThreadedHttpConnectionManager getMultiThreadedConnManager() {
269 if (mConnManager == null) {
270 mConnManager = new MultiThreadedHttpConnectionManager();
271 mConnManager.getParams().setDefaultMaxConnectionsPerHost(5);
272 mConnManager.getParams().setMaxTotalConnections(5);
273 }
274 return mConnManager;
275 }
276
277
278 }