PushUtils.java 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. /*
  2. * Nextcloud Android client application
  3. *
  4. * @author Mario Danic
  5. * Copyright (C) 2017-2018 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 android.util.Log;
  28. import com.google.gson.Gson;
  29. import com.owncloud.android.MainApp;
  30. import com.owncloud.android.R;
  31. import com.owncloud.android.authentication.AccountUtils;
  32. import com.owncloud.android.datamodel.ArbitraryDataProvider;
  33. import com.owncloud.android.datamodel.PushConfigurationState;
  34. import com.owncloud.android.datamodel.SignatureVerification;
  35. import com.owncloud.android.db.PreferenceManager;
  36. import com.owncloud.android.lib.common.OwnCloudAccount;
  37. import com.owncloud.android.lib.common.OwnCloudClient;
  38. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  39. import com.owncloud.android.lib.common.operations.RemoteOperation;
  40. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  41. import com.owncloud.android.lib.common.utils.Log_OC;
  42. import com.owncloud.android.lib.resources.notifications.RegisterAccountDeviceForNotificationsOperation;
  43. import com.owncloud.android.lib.resources.notifications.RegisterAccountDeviceForProxyOperation;
  44. import com.owncloud.android.lib.resources.notifications.UnregisterAccountDeviceForNotificationsOperation;
  45. import com.owncloud.android.lib.resources.notifications.UnregisterAccountDeviceForProxyOperation;
  46. import com.owncloud.android.lib.resources.notifications.models.PushResponse;
  47. import org.apache.commons.httpclient.HttpStatus;
  48. import org.apache.commons.io.FileUtils;
  49. import java.io.File;
  50. import java.io.FileInputStream;
  51. import java.io.FileNotFoundException;
  52. import java.io.FileOutputStream;
  53. import java.io.IOException;
  54. import java.security.InvalidKeyException;
  55. import java.security.Key;
  56. import java.security.KeyFactory;
  57. import java.security.KeyPair;
  58. import java.security.KeyPairGenerator;
  59. import java.security.MessageDigest;
  60. import java.security.NoSuchAlgorithmException;
  61. import java.security.PublicKey;
  62. import java.security.Signature;
  63. import java.security.SignatureException;
  64. import java.security.spec.InvalidKeySpecException;
  65. import java.security.spec.PKCS8EncodedKeySpec;
  66. import java.security.spec.X509EncodedKeySpec;
  67. import java.util.Locale;
  68. public class PushUtils {
  69. public static final String KEY_PUSH = "push";
  70. private static final String TAG = "PushUtils";
  71. private static final String KEYPAIR_FOLDER = "nc-keypair";
  72. private static final String KEYPAIR_FILE_NAME = "push_key";
  73. private static final String KEYPAIR_PRIV_EXTENSION = ".priv";
  74. private static final String KEYPAIR_PUB_EXTENSION = ".pub";
  75. private static ArbitraryDataProvider arbitraryDataProvider;
  76. public static String generateSHA512Hash(String pushToken) {
  77. MessageDigest messageDigest = null;
  78. try {
  79. messageDigest = MessageDigest.getInstance("SHA-512");
  80. messageDigest.update(pushToken.getBytes());
  81. return bytesToHex(messageDigest.digest());
  82. } catch (NoSuchAlgorithmException e) {
  83. Log_OC.d(TAG, "SHA-512 algorithm not supported");
  84. }
  85. return "";
  86. }
  87. public static String bytesToHex(byte[] bytes) {
  88. StringBuilder result = new StringBuilder();
  89. for (byte individualByte : bytes) {
  90. result.append(Integer.toString((individualByte & 0xff) + 0x100, 16)
  91. .substring(1));
  92. }
  93. return result.toString();
  94. }
  95. private static int generateRsa2048KeyPair() {
  96. migratePushKeys();
  97. String keyPath = MainApp.getAppContext().getFilesDir().getAbsolutePath() + File.separator +
  98. MainApp.getDataFolder() + File.separator + KEYPAIR_FOLDER;
  99. String privateKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PRIV_EXTENSION;
  100. String publicKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PUB_EXTENSION;
  101. File keyPathFile = new File(keyPath);
  102. if (!new File(privateKeyPath).exists() && !new File(publicKeyPath).exists()) {
  103. try {
  104. if (!keyPathFile.exists()) {
  105. keyPathFile.mkdir();
  106. }
  107. KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
  108. keyGen.initialize(2048);
  109. KeyPair pair = keyGen.generateKeyPair();
  110. int statusPrivate = saveKeyToFile(pair.getPrivate(), privateKeyPath);
  111. int statusPublic = saveKeyToFile(pair.getPublic(), publicKeyPath);
  112. if (statusPrivate == 0 && statusPublic == 0) {
  113. // all went well
  114. return 0;
  115. } else {
  116. return -2;
  117. }
  118. } catch (NoSuchAlgorithmException e) {
  119. Log_OC.d(TAG, "RSA algorithm not supported");
  120. }
  121. } else {
  122. // we already have the key
  123. return -1;
  124. }
  125. // we failed to generate the key
  126. return -2;
  127. }
  128. private static void deleteRegistrationForAccount(Account account) {
  129. Context context = MainApp.getAppContext();
  130. OwnCloudAccount ocAccount = null;
  131. arbitraryDataProvider = new ArbitraryDataProvider(MainApp.getAppContext().getContentResolver());
  132. try {
  133. ocAccount = new OwnCloudAccount(account, context);
  134. OwnCloudClient mClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  135. getClientFor(ocAccount, context);
  136. RemoteOperation unregisterAccountDeviceForNotificationsOperation = new
  137. UnregisterAccountDeviceForNotificationsOperation();
  138. RemoteOperationResult remoteOperationResult = unregisterAccountDeviceForNotificationsOperation.
  139. execute(mClient);
  140. if (remoteOperationResult.getHttpCode() == HttpStatus.SC_ACCEPTED) {
  141. String arbitraryValue;
  142. if (!TextUtils.isEmpty(arbitraryValue = arbitraryDataProvider.getValue(account, KEY_PUSH))) {
  143. Gson gson = new Gson();
  144. PushConfigurationState pushArbitraryData = gson.fromJson(arbitraryValue,
  145. PushConfigurationState.class);
  146. RemoteOperation unregisterAccountDeviceForProxyOperation =
  147. new UnregisterAccountDeviceForProxyOperation(context.getResources().
  148. getString(R.string.push_server_url),
  149. pushArbitraryData.getDeviceIdentifier(),
  150. pushArbitraryData.getDeviceIdentifierSignature(),
  151. pushArbitraryData.getUserPublicKey());
  152. remoteOperationResult = unregisterAccountDeviceForProxyOperation.execute(mClient);
  153. if (remoteOperationResult.isSuccess()) {
  154. arbitraryDataProvider.deleteKeyForAccount(account.name, KEY_PUSH);
  155. }
  156. }
  157. }
  158. } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) {
  159. Log_OC.d(TAG, "Failed to find an account");
  160. } catch (AuthenticatorException e) {
  161. Log_OC.d(TAG, "Failed via AuthenticatorException");
  162. } catch (IOException e) {
  163. Log_OC.d(TAG, "Failed via IOException");
  164. } catch (OperationCanceledException e) {
  165. Log_OC.d(TAG, "Failed via OperationCanceledException");
  166. }
  167. }
  168. public static void pushRegistrationToServer() {
  169. String token = PreferenceManager.getPushToken(MainApp.getAppContext());
  170. arbitraryDataProvider = new ArbitraryDataProvider(MainApp.getAppContext().getContentResolver());
  171. if (!TextUtils.isEmpty(MainApp.getAppContext().getResources().getString(R.string.push_server_url)) &&
  172. !TextUtils.isEmpty(token)) {
  173. PushUtils.generateRsa2048KeyPair();
  174. String pushTokenHash = PushUtils.generateSHA512Hash(token).toLowerCase(Locale.ROOT);
  175. PublicKey devicePublicKey = (PublicKey) PushUtils.readKeyFromFile(true);
  176. if (devicePublicKey != null) {
  177. byte[] publicKeyBytes = Base64.encode(devicePublicKey.getEncoded(), Base64.NO_WRAP);
  178. String publicKey = new String(publicKeyBytes);
  179. publicKey = publicKey.replaceAll("(.{64})", "$1\n");
  180. publicKey = "-----BEGIN PUBLIC KEY-----\n" + publicKey + "\n-----END PUBLIC KEY-----\n";
  181. Context context = MainApp.getAppContext();
  182. String providerValue;
  183. PushConfigurationState accountPushData = null;
  184. Gson gson = new Gson();
  185. for (Account account : AccountUtils.getAccounts(context)) {
  186. providerValue = arbitraryDataProvider.getValue(account, KEY_PUSH);
  187. if (!TextUtils.isEmpty(providerValue)) {
  188. accountPushData = gson.fromJson(providerValue,
  189. PushConfigurationState.class);
  190. } else {
  191. accountPushData = null;
  192. }
  193. if (accountPushData != null && !accountPushData.getPushToken().equals(token) &&
  194. !accountPushData.isShouldBeDeleted() ||
  195. TextUtils.isEmpty(providerValue)) {
  196. try {
  197. OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
  198. OwnCloudClient mClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  199. getClientFor(ocAccount, context);
  200. RemoteOperation registerAccountDeviceForNotificationsOperation =
  201. new RegisterAccountDeviceForNotificationsOperation(pushTokenHash,
  202. publicKey,
  203. context.getResources().getString(R.string.push_server_url));
  204. RemoteOperationResult remoteOperationResult =
  205. registerAccountDeviceForNotificationsOperation.execute(mClient);
  206. if (remoteOperationResult.isSuccess()) {
  207. PushResponse pushResponse = remoteOperationResult.getPushResponseData();
  208. RemoteOperation registerAccountDeviceForProxyOperation = new
  209. RegisterAccountDeviceForProxyOperation(
  210. context.getResources().getString(R.string.push_server_url),
  211. token, pushResponse.getDeviceIdentifier(), pushResponse.getSignature(),
  212. pushResponse.getPublicKey());
  213. remoteOperationResult = registerAccountDeviceForProxyOperation.execute(mClient);
  214. if (remoteOperationResult.isSuccess()) {
  215. PushConfigurationState pushArbitraryData = new PushConfigurationState(token,
  216. pushResponse.getDeviceIdentifier(), pushResponse.getSignature(),
  217. pushResponse.getPublicKey(), false);
  218. arbitraryDataProvider.storeOrUpdateKeyValue(account.name, KEY_PUSH,
  219. gson.toJson(pushArbitraryData));
  220. }
  221. } else if (remoteOperationResult.getCode() ==
  222. RemoteOperationResult.ResultCode.ACCOUNT_USES_STANDARD_PASSWORD) {
  223. arbitraryDataProvider.storeOrUpdateKeyValue(account.name,
  224. AccountUtils.ACCOUNT_USES_STANDARD_PASSWORD, "true");
  225. }
  226. } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) {
  227. Log_OC.d(TAG, "Failed to find an account");
  228. } catch (AuthenticatorException e) {
  229. Log_OC.d(TAG, "Failed via AuthenticatorException");
  230. } catch (IOException e) {
  231. Log_OC.d(TAG, "Failed via IOException");
  232. } catch (OperationCanceledException e) {
  233. Log_OC.d(TAG, "Failed via OperationCanceledException");
  234. }
  235. } else if (accountPushData != null && accountPushData.isShouldBeDeleted()) {
  236. deleteRegistrationForAccount(account);
  237. }
  238. }
  239. }
  240. }
  241. }
  242. public static Key readKeyFromFile(boolean readPublicKey) {
  243. String keyPath = MainApp.getAppContext().getFilesDir().getAbsolutePath() + File.separator +
  244. MainApp.getDataFolder() + File.separator + KEYPAIR_FOLDER;
  245. String privateKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PRIV_EXTENSION;
  246. String publicKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PUB_EXTENSION;
  247. String path;
  248. if (readPublicKey) {
  249. path = publicKeyPath;
  250. } else {
  251. path = privateKeyPath;
  252. }
  253. FileInputStream fileInputStream = null;
  254. try {
  255. fileInputStream = new FileInputStream(path);
  256. byte[] bytes = new byte[fileInputStream.available()];
  257. fileInputStream.read(bytes);
  258. fileInputStream.close();
  259. KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  260. if (readPublicKey) {
  261. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
  262. return keyFactory.generatePublic(keySpec);
  263. } else {
  264. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
  265. return keyFactory.generatePrivate(keySpec);
  266. }
  267. } catch (FileNotFoundException e) {
  268. Log_OC.d(TAG, "Failed to find path while reading the Key");
  269. } catch (IOException e) {
  270. Log_OC.d(TAG, "IOException while reading the key");
  271. } catch (InvalidKeySpecException e) {
  272. Log_OC.d(TAG, "InvalidKeySpecException while reading the key");
  273. } catch (NoSuchAlgorithmException e) {
  274. Log_OC.d(TAG, "RSA algorithm not supported");
  275. }
  276. return null;
  277. }
  278. private static int saveKeyToFile(Key key, String path) {
  279. byte[] encoded = key.getEncoded();
  280. FileOutputStream keyFileOutputStream = null;
  281. try {
  282. if (!new File(path).exists()) {
  283. File newFile = new File(path);
  284. newFile.getParentFile().mkdirs();
  285. newFile.createNewFile();
  286. }
  287. keyFileOutputStream = new FileOutputStream(path);
  288. keyFileOutputStream.write(encoded);
  289. keyFileOutputStream.close();
  290. return 0;
  291. } catch (FileNotFoundException e) {
  292. Log_OC.d(TAG, "Failed to save key to file");
  293. } catch (IOException e) {
  294. Log_OC.d(TAG, "Failed to save key to file via IOException");
  295. }
  296. return -1;
  297. }
  298. public static void reinitKeys() {
  299. Context context = MainApp.getAppContext();
  300. Account[] accounts = AccountUtils.getAccounts(context);
  301. for (Account account : accounts) {
  302. deleteRegistrationForAccount(account);
  303. }
  304. String keyPath = context.getDir("nc-keypair", Context.MODE_PRIVATE).getAbsolutePath();
  305. File privateKeyFile = new File(keyPath, "push_key.priv");
  306. File publicKeyFile = new File(keyPath, "push_key.pub");
  307. FileUtils.deleteQuietly(privateKeyFile);
  308. FileUtils.deleteQuietly(publicKeyFile);
  309. pushRegistrationToServer();
  310. PreferenceManager.setKeysReInit(context);
  311. }
  312. private static void migratePushKeys() {
  313. Context context = MainApp.getAppContext();
  314. if (!PreferenceManager.getKeysMigration(context)) {
  315. String oldKeyPath = MainApp.getStoragePath() + File.separator + MainApp.getDataFolder()
  316. + File.separator + "nc-keypair";
  317. File oldPrivateKeyFile = new File(oldKeyPath, "push_key.priv");
  318. File oldPublicKeyFile = new File(oldKeyPath, "push_key.pub");
  319. String keyPath = context.getDir("nc-keypair", Context.MODE_PRIVATE).getAbsolutePath();
  320. File privateKeyFile = new File(keyPath, "push_key.priv");
  321. File publicKeyFile = new File(keyPath, "push_key.pub");
  322. if ((privateKeyFile.exists() && publicKeyFile.exists()) ||
  323. (!oldPrivateKeyFile.exists() && !oldPublicKeyFile.exists())) {
  324. PreferenceManager.setKeysMigration(context, true);
  325. } else {
  326. if (oldPrivateKeyFile.exists()) {
  327. try {
  328. FileStorageUtils.moveFile(oldPrivateKeyFile, privateKeyFile);
  329. } catch (IOException e) {
  330. Log.e(TAG, "Failed to move old private key to new location");
  331. }
  332. }
  333. if (oldPublicKeyFile.exists()) {
  334. try {
  335. FileStorageUtils.moveFile(oldPublicKeyFile, publicKeyFile);
  336. } catch (IOException e) {
  337. Log.e(TAG, "Failed to move old public key to new location");
  338. }
  339. }
  340. if (privateKeyFile.exists() && publicKeyFile.exists()) {
  341. PreferenceManager.setKeysMigration(context, true);
  342. }
  343. }
  344. }
  345. }
  346. public SignatureVerification verifySignature(Context context, byte[] signatureBytes, byte[] subjectBytes) {
  347. Signature signature = null;
  348. PublicKey publicKey;
  349. SignatureVerification signatureVerification = new SignatureVerification();
  350. signatureVerification.setSignatureValid(false);
  351. Account[] userEntities = AccountUtils.getAccounts(context);
  352. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(context.getContentResolver());
  353. String arbitraryValue;
  354. Gson gson = new Gson();
  355. PushConfigurationState pushArbitraryData;
  356. try {
  357. signature = Signature.getInstance("SHA512withRSA");
  358. if (userEntities.length > 0) {
  359. for (Account userEntity : userEntities) {
  360. if (!TextUtils.isEmpty(arbitraryValue = arbitraryDataProvider.getValue(userEntity, KEY_PUSH))) {
  361. pushArbitraryData = gson.fromJson(arbitraryValue, PushConfigurationState.class);
  362. publicKey = (PublicKey) readKeyFromString(true, pushArbitraryData.getUserPublicKey());
  363. signature.initVerify(publicKey);
  364. signature.update(subjectBytes);
  365. if (signature.verify(signatureBytes)) {
  366. signatureVerification.setSignatureValid(true);
  367. signatureVerification.setAccount(userEntity);
  368. return signatureVerification;
  369. }
  370. }
  371. }
  372. }
  373. } catch (NoSuchAlgorithmException e) {
  374. Log.d(TAG, "No such algorithm");
  375. } catch (InvalidKeyException e) {
  376. Log.d(TAG, "Invalid key while trying to verify");
  377. } catch (SignatureException e) {
  378. Log.d(TAG, "Signature exception while trying to verify");
  379. }
  380. return signatureVerification;
  381. }
  382. private Key readKeyFromString(boolean readPublicKey, String keyString) {
  383. if (readPublicKey) {
  384. keyString = keyString.replaceAll("\\n", "").replace("-----BEGIN PUBLIC KEY-----",
  385. "").replace("-----END PUBLIC KEY-----", "");
  386. } else {
  387. keyString = keyString.replaceAll("\\n", "").replace("-----BEGIN PRIVATE KEY-----",
  388. "").replace("-----END PRIVATE KEY-----", "");
  389. }
  390. KeyFactory keyFactory = null;
  391. try {
  392. keyFactory = KeyFactory.getInstance("RSA");
  393. if (readPublicKey) {
  394. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decode(keyString, Base64.DEFAULT));
  395. return keyFactory.generatePublic(keySpec);
  396. } else {
  397. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decode(keyString, Base64.DEFAULT));
  398. return keyFactory.generatePrivate(keySpec);
  399. }
  400. } catch (NoSuchAlgorithmException e) {
  401. Log.d("TAG", "No such algorithm while reading key from string");
  402. } catch (InvalidKeySpecException e) {
  403. Log.d("TAG", "Invalid key spec while reading key from string");
  404. }
  405. return null;
  406. }
  407. }