PushUtils.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. /*
  2. * Nextcloud Android client application
  3. *
  4. * @author Mario Danic
  5. * Copyright (C) 2017 Mario Danic
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Affero General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU Affero General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Affero General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. package com.owncloud.android.utils;
  21. import android.accounts.Account;
  22. import android.accounts.AuthenticatorException;
  23. import android.accounts.OperationCanceledException;
  24. import android.content.Context;
  25. import android.text.TextUtils;
  26. import android.util.Base64;
  27. import com.google.gson.Gson;
  28. import com.owncloud.android.MainApp;
  29. import com.owncloud.android.R;
  30. import com.owncloud.android.authentication.AccountUtils;
  31. import com.owncloud.android.datamodel.ArbitraryDataProvider;
  32. import com.owncloud.android.datamodel.PushConfigurationState;
  33. import com.owncloud.android.db.PreferenceManager;
  34. import com.owncloud.android.lib.common.OwnCloudAccount;
  35. import com.owncloud.android.lib.common.OwnCloudClient;
  36. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  37. import com.owncloud.android.lib.common.operations.RemoteOperation;
  38. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  39. import com.owncloud.android.lib.common.utils.Log_OC;
  40. import com.owncloud.android.lib.resources.notifications.RegisterAccountDeviceForNotificationsOperation;
  41. import com.owncloud.android.lib.resources.notifications.RegisterAccountDeviceForProxyOperation;
  42. import com.owncloud.android.lib.resources.notifications.UnregisterAccountDeviceForNotificationsOperation;
  43. import com.owncloud.android.lib.resources.notifications.UnregisterAccountDeviceForProxyOperation;
  44. import com.owncloud.android.lib.resources.notifications.models.PushResponse;
  45. import org.apache.commons.httpclient.HttpStatus;
  46. import java.io.File;
  47. import java.io.FileInputStream;
  48. import java.io.FileNotFoundException;
  49. import java.io.FileOutputStream;
  50. import java.io.IOException;
  51. import java.security.Key;
  52. import java.security.KeyFactory;
  53. import java.security.KeyPair;
  54. import java.security.KeyPairGenerator;
  55. import java.security.MessageDigest;
  56. import java.security.NoSuchAlgorithmException;
  57. import java.security.PublicKey;
  58. import java.security.spec.InvalidKeySpecException;
  59. import java.security.spec.PKCS8EncodedKeySpec;
  60. import java.security.spec.X509EncodedKeySpec;
  61. import java.util.Locale;
  62. public class PushUtils {
  63. private static final String TAG = "PushUtils";
  64. private static final String KEYPAIR_FOLDER = "nc-keypair";
  65. private static final String KEYPAIR_FILE_NAME = "push_key";
  66. private static final String KEYPAIR_PRIV_EXTENSION = ".priv";
  67. private static final String KEYPAIR_PUB_EXTENSION = ".pub";
  68. public static final String KEY_PUSH = "push";
  69. private static ArbitraryDataProvider arbitraryDataProvider;
  70. public static String generateSHA512Hash(String pushToken) {
  71. MessageDigest messageDigest = null;
  72. try {
  73. messageDigest = MessageDigest.getInstance("SHA-512");
  74. messageDigest.update(pushToken.getBytes());
  75. return bytesToHex(messageDigest.digest());
  76. } catch (NoSuchAlgorithmException e) {
  77. Log_OC.d(TAG, "SHA-512 algorithm not supported");
  78. }
  79. return "";
  80. }
  81. public static String bytesToHex(byte[] bytes) {
  82. StringBuilder result = new StringBuilder();
  83. for (byte individualByte : bytes) {
  84. result.append(Integer.toString((individualByte & 0xff) + 0x100, 16)
  85. .substring(1));
  86. }
  87. return result.toString();
  88. }
  89. private static int generateRsa2048KeyPair() {
  90. migratePushKeys();
  91. String keyPath = MainApp.getAppContext().getFilesDir().getAbsolutePath() + File.separator +
  92. MainApp.getDataFolder() + File.separator + KEYPAIR_FOLDER;
  93. String privateKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PRIV_EXTENSION;
  94. String publicKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PUB_EXTENSION;
  95. File keyPathFile = new File(keyPath);
  96. if (!new File(privateKeyPath).exists() && !new File(publicKeyPath).exists()) {
  97. try {
  98. if (!keyPathFile.exists()) {
  99. keyPathFile.mkdir();
  100. }
  101. KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
  102. keyGen.initialize(2048);
  103. KeyPair pair = keyGen.generateKeyPair();
  104. int statusPrivate = saveKeyToFile(pair.getPrivate(), privateKeyPath);
  105. int statusPublic = saveKeyToFile(pair.getPublic(), publicKeyPath);
  106. if (statusPrivate == 0 && statusPublic == 0) {
  107. // all went well
  108. return 0;
  109. } else {
  110. return -2;
  111. }
  112. } catch (NoSuchAlgorithmException e) {
  113. Log_OC.d(TAG, "RSA algorithm not supported");
  114. }
  115. } else {
  116. // we already have the key
  117. return -1;
  118. }
  119. // we failed to generate the key
  120. return -2;
  121. }
  122. private static void deleteRegistrationForAccount(Account account) {
  123. Context context = MainApp.getAppContext();
  124. OwnCloudAccount ocAccount = null;
  125. arbitraryDataProvider = new ArbitraryDataProvider(MainApp.getAppContext().getContentResolver());
  126. try {
  127. ocAccount = new OwnCloudAccount(account, context);
  128. OwnCloudClient mClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  129. getClientFor(ocAccount, context);
  130. RemoteOperation unregisterAccountDeviceForNotificationsOperation = new
  131. UnregisterAccountDeviceForNotificationsOperation();
  132. RemoteOperationResult remoteOperationResult = unregisterAccountDeviceForNotificationsOperation.
  133. execute(mClient);
  134. if (remoteOperationResult.getHttpCode() == HttpStatus.SC_ACCEPTED) {
  135. String arbitraryValue;
  136. if (!TextUtils.isEmpty(arbitraryValue = arbitraryDataProvider.getValue(account, KEY_PUSH))) {
  137. Gson gson = new Gson();
  138. PushConfigurationState pushArbitraryData = gson.fromJson(arbitraryValue,
  139. PushConfigurationState.class);
  140. RemoteOperation unregisterAccountDeviceForProxyOperation =
  141. new UnregisterAccountDeviceForProxyOperation(context.getResources().
  142. getString(R.string.push_server_url),
  143. pushArbitraryData.getDeviceIdentifier(),
  144. pushArbitraryData.getDeviceIdentifierSignature(),
  145. pushArbitraryData.getUserPublicKey());
  146. remoteOperationResult = unregisterAccountDeviceForProxyOperation.execute(mClient);
  147. if (remoteOperationResult.isSuccess()) {
  148. arbitraryDataProvider.deleteKeyForAccount(account.name, KEY_PUSH);
  149. }
  150. }
  151. }
  152. } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) {
  153. Log_OC.d(TAG, "Failed to find an account");
  154. } catch (AuthenticatorException e) {
  155. Log_OC.d(TAG, "Failed via AuthenticatorException");
  156. } catch (IOException e) {
  157. Log_OC.d(TAG, "Failed via IOException");
  158. } catch (OperationCanceledException e) {
  159. Log_OC.d(TAG, "Failed via OperationCanceledException");
  160. }
  161. }
  162. public static void pushRegistrationToServer() {
  163. String token = PreferenceManager.getPushToken(MainApp.getAppContext());
  164. arbitraryDataProvider = new ArbitraryDataProvider(MainApp.getAppContext().getContentResolver());
  165. if (!TextUtils.isEmpty(MainApp.getAppContext().getResources().getString(R.string.push_server_url)) &&
  166. !TextUtils.isEmpty(token)) {
  167. PushUtils.generateRsa2048KeyPair();
  168. String pushTokenHash = PushUtils.generateSHA512Hash(token).toLowerCase(Locale.ROOT);
  169. PublicKey devicePublicKey = (PublicKey) PushUtils.readKeyFromFile(true);
  170. if (devicePublicKey != null) {
  171. byte[] publicKeyBytes = Base64.encode(devicePublicKey.getEncoded(), Base64.NO_WRAP);
  172. String publicKey = new String(publicKeyBytes);
  173. publicKey = publicKey.replaceAll("(.{64})", "$1\n");
  174. publicKey = "-----BEGIN PUBLIC KEY-----\n" + publicKey + "\n-----END PUBLIC KEY-----\n";
  175. Context context = MainApp.getAppContext();
  176. String providerValue;
  177. PushConfigurationState accountPushData = null;
  178. Gson gson = new Gson();
  179. for (Account account : AccountUtils.getAccounts(context)) {
  180. providerValue = arbitraryDataProvider.getValue(account, KEY_PUSH);
  181. if (!TextUtils.isEmpty(providerValue)) {
  182. accountPushData = gson.fromJson(providerValue,
  183. PushConfigurationState.class);
  184. } else {
  185. accountPushData = null;
  186. }
  187. if (accountPushData != null && !accountPushData.getPushToken().equals(token) &&
  188. !accountPushData.isShouldBeDeleted() ||
  189. TextUtils.isEmpty(providerValue)) {
  190. try {
  191. OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
  192. OwnCloudClient mClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  193. getClientFor(ocAccount, context);
  194. RemoteOperation registerAccountDeviceForNotificationsOperation =
  195. new RegisterAccountDeviceForNotificationsOperation(pushTokenHash,
  196. publicKey,
  197. context.getResources().getString(R.string.push_server_url));
  198. RemoteOperationResult remoteOperationResult =
  199. registerAccountDeviceForNotificationsOperation.execute(mClient);
  200. if (remoteOperationResult.isSuccess()) {
  201. PushResponse pushResponse = remoteOperationResult.getPushResponseData();
  202. RemoteOperation registerAccountDeviceForProxyOperation = new
  203. RegisterAccountDeviceForProxyOperation(
  204. context.getResources().getString(R.string.push_server_url),
  205. token, pushResponse.getDeviceIdentifier(), pushResponse.getSignature(),
  206. pushResponse.getPublicKey());
  207. remoteOperationResult = registerAccountDeviceForProxyOperation.execute(mClient);
  208. if (remoteOperationResult.isSuccess()) {
  209. PushConfigurationState pushArbitraryData = new PushConfigurationState(token,
  210. pushResponse.getDeviceIdentifier(), pushResponse.getSignature(),
  211. pushResponse.getPublicKey(), false);
  212. arbitraryDataProvider.storeOrUpdateKeyValue(account.name, KEY_PUSH,
  213. gson.toJson(pushArbitraryData));
  214. }
  215. }
  216. } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) {
  217. Log_OC.d(TAG, "Failed to find an account");
  218. } catch (AuthenticatorException e) {
  219. Log_OC.d(TAG, "Failed via AuthenticatorException");
  220. } catch (IOException e) {
  221. Log_OC.d(TAG, "Failed via IOException");
  222. } catch (OperationCanceledException e) {
  223. Log_OC.d(TAG, "Failed via OperationCanceledException");
  224. }
  225. } else if (accountPushData != null && accountPushData.isShouldBeDeleted()) {
  226. deleteRegistrationForAccount(account);
  227. }
  228. }
  229. }
  230. }
  231. }
  232. public static Key readKeyFromFile(boolean readPublicKey) {
  233. String keyPath = MainApp.getAppContext().getFilesDir().getAbsolutePath() + File.separator +
  234. MainApp.getDataFolder() + File.separator + KEYPAIR_FOLDER;
  235. String privateKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PRIV_EXTENSION;
  236. String publicKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PUB_EXTENSION;
  237. String path;
  238. if (readPublicKey) {
  239. path = publicKeyPath;
  240. } else {
  241. path = privateKeyPath;
  242. }
  243. FileInputStream fileInputStream = null;
  244. try {
  245. fileInputStream = new FileInputStream(path);
  246. byte[] bytes = new byte[fileInputStream.available()];
  247. fileInputStream.read(bytes);
  248. fileInputStream.close();
  249. KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  250. if (readPublicKey) {
  251. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
  252. return keyFactory.generatePublic(keySpec);
  253. } else {
  254. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
  255. return keyFactory.generatePrivate(keySpec);
  256. }
  257. } catch (FileNotFoundException e) {
  258. Log_OC.d(TAG, "Failed to find path while reading the Key");
  259. } catch (IOException e) {
  260. Log_OC.d(TAG, "IOException while reading the key");
  261. } catch (InvalidKeySpecException e) {
  262. Log_OC.d(TAG, "InvalidKeySpecException while reading the key");
  263. } catch (NoSuchAlgorithmException e) {
  264. Log_OC.d(TAG, "RSA algorithm not supported");
  265. }
  266. return null;
  267. }
  268. private static int saveKeyToFile(Key key, String path) {
  269. byte[] encoded = key.getEncoded();
  270. FileOutputStream keyFileOutputStream = null;
  271. try {
  272. if (!new File(path).exists()) {
  273. new File(path).createNewFile();
  274. }
  275. keyFileOutputStream = new FileOutputStream(path);
  276. keyFileOutputStream.write(encoded);
  277. keyFileOutputStream.close();
  278. return 0;
  279. } catch (FileNotFoundException e) {
  280. Log_OC.d(TAG, "Failed to save key to file");
  281. } catch (IOException e) {
  282. Log_OC.d(TAG, "Failed to save key to file via IOException");
  283. }
  284. return -1;
  285. }
  286. private static void migratePushKeys() {
  287. }
  288. }