OwnCloudClientUtils.java 14 KB

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