PushUtils.java 22 KB

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