PushUtils.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. String keyPath = MainApp.getAppContext().getFilesDir().getAbsolutePath() + File.separator + MainApp.getDataFolder() + File.separator
  91. + KEYPAIR_FOLDER;
  92. String privateKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PRIV_EXTENSION;
  93. String publicKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PUB_EXTENSION;
  94. File keyPathFile = new File(keyPath);
  95. if (!new File(privateKeyPath).exists() && !new File(publicKeyPath).exists()) {
  96. try {
  97. if (!keyPathFile.exists()) {
  98. keyPathFile.mkdir();
  99. }
  100. KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
  101. keyGen.initialize(2048);
  102. KeyPair pair = keyGen.generateKeyPair();
  103. int statusPrivate = saveKeyToFile(pair.getPrivate(), privateKeyPath);
  104. int statusPublic = saveKeyToFile(pair.getPublic(), publicKeyPath);
  105. if (statusPrivate == 0 && statusPublic == 0) {
  106. // all went well
  107. return 0;
  108. } else {
  109. return -2;
  110. }
  111. } catch (NoSuchAlgorithmException e) {
  112. Log_OC.d(TAG, "RSA algorithm not supported");
  113. }
  114. } else {
  115. // we already have the key
  116. return -1;
  117. }
  118. // we failed to generate the key
  119. return -2;
  120. }
  121. private static void deleteRegistrationForAccount(Account account) {
  122. Context context = MainApp.getAppContext();
  123. OwnCloudAccount ocAccount = null;
  124. arbitraryDataProvider = new ArbitraryDataProvider(MainApp.getAppContext().getContentResolver());
  125. try {
  126. ocAccount = new OwnCloudAccount(account, context);
  127. OwnCloudClient mClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  128. getClientFor(ocAccount, context);
  129. RemoteOperation unregisterAccountDeviceForNotificationsOperation = new
  130. UnregisterAccountDeviceForNotificationsOperation();
  131. RemoteOperationResult remoteOperationResult = unregisterAccountDeviceForNotificationsOperation.
  132. execute(mClient);
  133. if (remoteOperationResult.getHttpCode() == HttpStatus.SC_ACCEPTED) {
  134. String arbitraryValue;
  135. if (!TextUtils.isEmpty(arbitraryValue = arbitraryDataProvider.getValue(account, KEY_PUSH))) {
  136. Gson gson = new Gson();
  137. PushConfigurationState pushArbitraryData = gson.fromJson(arbitraryValue,
  138. PushConfigurationState.class);
  139. RemoteOperation unregisterAccountDeviceForProxyOperation =
  140. new UnregisterAccountDeviceForProxyOperation(context.getResources().
  141. getString(R.string.push_server_url),
  142. pushArbitraryData.getDeviceIdentifier(),
  143. pushArbitraryData.getDeviceIdentifierSignature(),
  144. pushArbitraryData.getUserPublicKey());
  145. remoteOperationResult = unregisterAccountDeviceForProxyOperation.execute(mClient);
  146. if (remoteOperationResult.isSuccess()) {
  147. arbitraryDataProvider.deleteKeyForAccount(account.name, KEY_PUSH);
  148. }
  149. }
  150. }
  151. } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) {
  152. Log_OC.d(TAG, "Failed to find an account");
  153. } catch (AuthenticatorException e) {
  154. Log_OC.d(TAG, "Failed via AuthenticatorException");
  155. } catch (IOException e) {
  156. Log_OC.d(TAG, "Failed via IOException");
  157. } catch (OperationCanceledException e) {
  158. Log_OC.d(TAG, "Failed via OperationCanceledException");
  159. }
  160. }
  161. public static void pushRegistrationToServer() {
  162. String token = PreferenceManager.getPushToken(MainApp.getAppContext());
  163. arbitraryDataProvider = new ArbitraryDataProvider(MainApp.getAppContext().getContentResolver());
  164. if (!TextUtils.isEmpty(MainApp.getAppContext().getResources().getString(R.string.push_server_url)) &&
  165. !TextUtils.isEmpty(token)) {
  166. PushUtils.generateRsa2048KeyPair();
  167. String pushTokenHash = PushUtils.generateSHA512Hash(token).toLowerCase(Locale.ROOT);
  168. PublicKey devicePublicKey = (PublicKey) PushUtils.readKeyFromFile(true);
  169. if (devicePublicKey != null) {
  170. byte[] publicKeyBytes = Base64.encode(devicePublicKey.getEncoded(), Base64.NO_WRAP);
  171. String publicKey = new String(publicKeyBytes);
  172. publicKey = publicKey.replaceAll("(.{64})", "$1\n");
  173. publicKey = "-----BEGIN PUBLIC KEY-----\n" + publicKey + "\n-----END PUBLIC KEY-----\n";
  174. Context context = MainApp.getAppContext();
  175. String providerValue;
  176. PushConfigurationState accountPushData = null;
  177. Gson gson = new Gson();
  178. for (Account account : AccountUtils.getAccounts(context)) {
  179. providerValue = arbitraryDataProvider.getValue(account, KEY_PUSH);
  180. if (!TextUtils.isEmpty(providerValue)) {
  181. accountPushData = gson.fromJson(providerValue,
  182. PushConfigurationState.class);
  183. } else {
  184. accountPushData = null;
  185. }
  186. if (accountPushData != null && !accountPushData.getPushToken().equals(token) &&
  187. !accountPushData.isShouldBeDeleted() ||
  188. TextUtils.isEmpty(providerValue)) {
  189. try {
  190. OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
  191. OwnCloudClient mClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  192. getClientFor(ocAccount, context);
  193. RemoteOperation registerAccountDeviceForNotificationsOperation =
  194. new RegisterAccountDeviceForNotificationsOperation(pushTokenHash,
  195. publicKey,
  196. context.getResources().getString(R.string.push_server_url));
  197. RemoteOperationResult remoteOperationResult = registerAccountDeviceForNotificationsOperation.
  198. execute(mClient);
  199. if (remoteOperationResult.isSuccess()) {
  200. PushResponse pushResponse = remoteOperationResult.getPushResponseData();
  201. RemoteOperation registerAccountDeviceForProxyOperation = new
  202. RegisterAccountDeviceForProxyOperation(
  203. context.getResources().getString(R.string.push_server_url),
  204. token, pushResponse.getDeviceIdentifier(), pushResponse.getSignature(),
  205. pushResponse.getPublicKey());
  206. remoteOperationResult = registerAccountDeviceForProxyOperation.execute(mClient);
  207. if (remoteOperationResult.isSuccess()) {
  208. PushConfigurationState pushArbitraryData = new PushConfigurationState(token,
  209. pushResponse.getDeviceIdentifier(), pushResponse.getSignature(),
  210. pushResponse.getPublicKey(), false);
  211. arbitraryDataProvider.storeOrUpdateKeyValue(account.name, KEY_PUSH,
  212. gson.toJson(pushArbitraryData));
  213. }
  214. }
  215. } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) {
  216. Log_OC.d(TAG, "Failed to find an account");
  217. } catch (AuthenticatorException e) {
  218. Log_OC.d(TAG, "Failed via AuthenticatorException");
  219. } catch (IOException e) {
  220. Log_OC.d(TAG, "Failed via IOException");
  221. } catch (OperationCanceledException e) {
  222. Log_OC.d(TAG, "Failed via OperationCanceledException");
  223. }
  224. } else if (accountPushData != null && accountPushData.isShouldBeDeleted()) {
  225. deleteRegistrationForAccount(account);
  226. }
  227. }
  228. }
  229. }
  230. }
  231. public static Key readKeyFromFile(boolean readPublicKey) {
  232. String keyPath = MainApp.getAppContext().getFilesDir().getAbsolutePath() + File.separator + MainApp.getDataFolder() + File.separator
  233. + KEYPAIR_FOLDER;
  234. String privateKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PRIV_EXTENSION;
  235. String publicKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PUB_EXTENSION;
  236. String path;
  237. if (readPublicKey) {
  238. path = publicKeyPath;
  239. } else {
  240. path = privateKeyPath;
  241. }
  242. FileInputStream fileInputStream = null;
  243. try {
  244. fileInputStream = new FileInputStream(path);
  245. byte[] bytes = new byte[fileInputStream.available()];
  246. fileInputStream.read(bytes);
  247. fileInputStream.close();
  248. KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  249. if (readPublicKey) {
  250. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
  251. return keyFactory.generatePublic(keySpec);
  252. } else {
  253. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
  254. return keyFactory.generatePrivate(keySpec);
  255. }
  256. } catch (FileNotFoundException e) {
  257. Log_OC.d(TAG, "Failed to find path while reading the Key");
  258. } catch (IOException e) {
  259. Log_OC.d(TAG, "IOException while reading the key");
  260. } catch (InvalidKeySpecException e) {
  261. Log_OC.d(TAG, "InvalidKeySpecException while reading the key");
  262. } catch (NoSuchAlgorithmException e) {
  263. Log_OC.d(TAG, "RSA algorithm not supported");
  264. }
  265. return null;
  266. }
  267. private static int saveKeyToFile(Key key, String path) {
  268. byte[] encoded = key.getEncoded();
  269. FileOutputStream keyFileOutputStream = null;
  270. try {
  271. if (!new File(path).exists()) {
  272. new File(path).createNewFile();
  273. }
  274. keyFileOutputStream = new FileOutputStream(path);
  275. keyFileOutputStream.write(encoded);
  276. keyFileOutputStream.close();
  277. return 0;
  278. } catch (FileNotFoundException e) {
  279. Log_OC.d(TAG, "Failed to save key to file");
  280. } catch (IOException e) {
  281. Log_OC.d(TAG, "Failed to save key to file via IOException");
  282. }
  283. return -1;
  284. }
  285. }