PushUtils.java 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. /*
  2. * Nextcloud Talk application
  3. *
  4. * @author Mario Danic
  5. * Copyright (C) 2017 Mario Danic <mario@lovelyhq.com>
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU 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 General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. package com.nextcloud.talk.utils;
  21. import android.content.Context;
  22. import android.text.TextUtils;
  23. import android.util.Base64;
  24. import android.util.Log;
  25. import com.bluelinelabs.logansquare.LoganSquare;
  26. import com.nextcloud.talk.R;
  27. import com.nextcloud.talk.api.NcApi;
  28. import com.nextcloud.talk.application.NextcloudTalkApplication;
  29. import com.nextcloud.talk.events.EventStatus;
  30. import com.nextcloud.talk.models.SignatureVerification;
  31. import com.nextcloud.talk.models.database.UserEntity;
  32. import com.nextcloud.talk.models.json.push.PushConfigurationState;
  33. import com.nextcloud.talk.models.json.push.PushRegistrationOverall;
  34. import com.nextcloud.talk.utils.database.user.UserUtils;
  35. import com.nextcloud.talk.utils.preferences.AppPreferences;
  36. import com.nextcloud.talk.utils.singletons.ApplicationWideApiHolder;
  37. import org.greenrobot.eventbus.EventBus;
  38. import java.io.File;
  39. import java.io.FileInputStream;
  40. import java.io.FileNotFoundException;
  41. import java.io.FileOutputStream;
  42. import java.io.IOException;
  43. import java.security.InvalidKeyException;
  44. import java.security.Key;
  45. import java.security.KeyFactory;
  46. import java.security.KeyPair;
  47. import java.security.KeyPairGenerator;
  48. import java.security.MessageDigest;
  49. import java.security.NoSuchAlgorithmException;
  50. import java.security.PublicKey;
  51. import java.security.Signature;
  52. import java.security.SignatureException;
  53. import java.security.spec.InvalidKeySpecException;
  54. import java.security.spec.PKCS8EncodedKeySpec;
  55. import java.security.spec.X509EncodedKeySpec;
  56. import java.util.HashMap;
  57. import java.util.List;
  58. import java.util.Map;
  59. import javax.inject.Inject;
  60. import autodagger.AutoInjector;
  61. import io.reactivex.Observer;
  62. import io.reactivex.disposables.Disposable;
  63. import io.reactivex.schedulers.Schedulers;
  64. @AutoInjector(NextcloudTalkApplication.class)
  65. public class PushUtils {
  66. private static final String TAG = "PushUtils";
  67. @Inject
  68. UserUtils userUtils;
  69. @Inject
  70. AppPreferences appPreferences;
  71. @Inject
  72. EventBus eventBus;
  73. NcApi ncApi;
  74. private File keysFile;
  75. private File publicKeyFile;
  76. private File privateKeyFile;
  77. private String proxyServer;
  78. public PushUtils() {
  79. NextcloudTalkApplication.getSharedApplication().getComponentApplication().inject(this);
  80. keysFile = NextcloudTalkApplication.getSharedApplication().getDir("PushKeyStore", Context.MODE_PRIVATE);
  81. publicKeyFile = new File(NextcloudTalkApplication.getSharedApplication().getDir("PushKeystore",
  82. Context.MODE_PRIVATE), "push_key.pub");
  83. privateKeyFile = new File(NextcloudTalkApplication.getSharedApplication().getDir("PushKeystore",
  84. Context.MODE_PRIVATE), "push_key.priv");
  85. proxyServer = NextcloudTalkApplication.getSharedApplication().getResources().
  86. getString(R.string.nc_push_server_url);
  87. }
  88. public SignatureVerification verifySignature(byte[] signatureBytes, byte[] subjectBytes) {
  89. Signature signature = null;
  90. PushConfigurationState pushConfigurationState;
  91. PublicKey publicKey;
  92. SignatureVerification signatureVerification = new SignatureVerification();
  93. signatureVerification.setSignatureValid(false);
  94. List<UserEntity> userEntities = userUtils.getUsers();
  95. try {
  96. signature = Signature.getInstance("SHA512withRSA");
  97. if (userEntities != null && userEntities.size() > 0) {
  98. for (UserEntity userEntity : userEntities) {
  99. if (!TextUtils.isEmpty(userEntity.getPushConfigurationState())) {
  100. pushConfigurationState = LoganSquare.parse(userEntity.getPushConfigurationState(),
  101. PushConfigurationState.class);
  102. publicKey = (PublicKey) readKeyFromString(true,
  103. pushConfigurationState.getUserPublicKey());
  104. signature.initVerify(publicKey);
  105. signature.update(subjectBytes);
  106. if (signature.verify(signatureBytes)) {
  107. signatureVerification.setSignatureValid(true);
  108. signatureVerification.setUserEntity(userEntity);
  109. return signatureVerification;
  110. }
  111. }
  112. }
  113. }
  114. } catch (NoSuchAlgorithmException e) {
  115. Log.d(TAG, "No such algorithm");
  116. } catch (IOException e) {
  117. Log.d(TAG, "Error while trying to parse push configuration state");
  118. } catch (InvalidKeyException e) {
  119. Log.d(TAG, "Invalid key while trying to verify");
  120. } catch (SignatureException e) {
  121. Log.d(TAG, "Signature exception while trying to verify");
  122. }
  123. return signatureVerification;
  124. }
  125. private int saveKeyToFile(Key key, String path) {
  126. byte[] encoded = key.getEncoded();
  127. FileOutputStream keyFileOutputStream = null;
  128. try {
  129. if (!new File(path).exists()) {
  130. new File(path).createNewFile();
  131. }
  132. keyFileOutputStream = new FileOutputStream(path);
  133. keyFileOutputStream.write(encoded);
  134. keyFileOutputStream.close();
  135. return 0;
  136. } catch (FileNotFoundException e) {
  137. Log.d(TAG, "Failed to save key to file");
  138. } catch (IOException e) {
  139. Log.d(TAG, "Failed to save key to file via IOException");
  140. }
  141. return -1;
  142. }
  143. public String generateSHA512Hash(String pushToken) {
  144. MessageDigest messageDigest = null;
  145. try {
  146. messageDigest = MessageDigest.getInstance("SHA-512");
  147. messageDigest.update(pushToken.getBytes());
  148. return bytesToHex(messageDigest.digest());
  149. } catch (NoSuchAlgorithmException e) {
  150. Log.d(TAG, "SHA-512 algorithm not supported");
  151. }
  152. return "";
  153. }
  154. public String bytesToHex(byte[] bytes) {
  155. StringBuilder result = new StringBuilder();
  156. for (byte individualByte : bytes) {
  157. result.append(Integer.toString((individualByte & 0xff) + 0x100, 16)
  158. .substring(1));
  159. }
  160. return result.toString();
  161. }
  162. public int generateRsa2048KeyPair() {
  163. if (!publicKeyFile.exists() && !privateKeyFile.exists()) {
  164. if (!keysFile.exists()) {
  165. keysFile.mkdirs();
  166. }
  167. KeyPairGenerator keyGen = null;
  168. try {
  169. keyGen = KeyPairGenerator.getInstance("RSA");
  170. keyGen.initialize(2048);
  171. KeyPair pair = keyGen.generateKeyPair();
  172. int statusPrivate = saveKeyToFile(pair.getPrivate(), privateKeyFile.getAbsolutePath());
  173. int statusPublic = saveKeyToFile(pair.getPublic(), publicKeyFile.getAbsolutePath());
  174. if (statusPrivate == 0 && statusPublic == 0) {
  175. // all went well
  176. return 0;
  177. } else {
  178. return -2;
  179. }
  180. } catch (NoSuchAlgorithmException e) {
  181. Log.d(TAG, "RSA algorithm not supported");
  182. }
  183. } else {
  184. // We already have the key
  185. return -1;
  186. }
  187. // we failed to generate the key
  188. return -2;
  189. }
  190. public void pushRegistrationToServer() {
  191. String token = appPreferences.getPushToken();
  192. if (!TextUtils.isEmpty(token)) {
  193. String credentials;
  194. String pushTokenHash = generateSHA512Hash(token).toLowerCase();
  195. PublicKey devicePublicKey = (PublicKey) readKeyFromFile(true);
  196. if (devicePublicKey != null) {
  197. byte[] publicKeyBytes = Base64.encode(devicePublicKey.getEncoded(), Base64.NO_WRAP);
  198. String publicKey = new String(publicKeyBytes);
  199. publicKey = publicKey.replaceAll("(.{64})", "$1\n");
  200. publicKey = "-----BEGIN PUBLIC KEY-----\n" + publicKey + "\n-----END PUBLIC KEY-----\n";
  201. if (userUtils.anyUserExists()) {
  202. String providerValue;
  203. PushConfigurationState accountPushData = null;
  204. for (Object userEntityObject : userUtils.getUsers()) {
  205. UserEntity userEntity = (UserEntity) userEntityObject;
  206. providerValue = userEntity.getPushConfigurationState();
  207. if (!TextUtils.isEmpty(providerValue)) {
  208. try {
  209. accountPushData = LoganSquare.parse(providerValue, PushConfigurationState.class);
  210. } catch (IOException e) {
  211. Log.d(TAG, "Failed to parse account push data");
  212. accountPushData = null;
  213. }
  214. } else {
  215. accountPushData = null;
  216. }
  217. if (accountPushData != null && !accountPushData.getPushToken().equals(token) &&
  218. !userEntity.getScheduledForDeletion() ||
  219. TextUtils.isEmpty(providerValue) && !userEntity.getScheduledForDeletion()) {
  220. Map<String, String> queryMap = new HashMap<>();
  221. queryMap.put("format", "json");
  222. queryMap.put("pushTokenHash", pushTokenHash);
  223. queryMap.put("devicePublicKey", publicKey);
  224. queryMap.put("proxyServer", proxyServer);
  225. ncApi = ApplicationWideApiHolder.getInstance().getNcApiInstanceForAccountId(userEntity.getId(), null);
  226. credentials = ApiUtils.getCredentials(userEntity.getUserId(), userEntity.getToken());
  227. String finalCredentials = credentials;
  228. ncApi.registerDeviceForNotificationsWithNextcloud(
  229. credentials,
  230. ApiUtils.getUrlNextcloudPush(userEntity.getBaseUrl()), queryMap)
  231. .blockingSubscribe(new Observer<PushRegistrationOverall>() {
  232. @Override
  233. public void onSubscribe(Disposable d) {
  234. }
  235. @Override
  236. public void onNext(PushRegistrationOverall pushRegistrationOverall) {
  237. Map<String, String> proxyMap = new HashMap<>();
  238. proxyMap.put("pushToken", token);
  239. proxyMap.put("deviceIdentifier", pushRegistrationOverall.getOcs().getData().
  240. getDeviceIdentifier());
  241. proxyMap.put("deviceIdentifierSignature", pushRegistrationOverall.getOcs()
  242. .getData().getSignature());
  243. proxyMap.put("userPublicKey", pushRegistrationOverall.getOcs()
  244. .getData().getPublicKey());
  245. ncApi.registerDeviceForNotificationsWithProxy(finalCredentials,
  246. ApiUtils.getUrlPushProxy(), proxyMap)
  247. .subscribeOn(Schedulers.newThread())
  248. .subscribe(new Observer<Void>() {
  249. @Override
  250. public void onSubscribe(Disposable d) {
  251. }
  252. @Override
  253. public void onNext(Void aVoid) {
  254. PushConfigurationState pushConfigurationState =
  255. new PushConfigurationState();
  256. pushConfigurationState.setPushToken(token);
  257. pushConfigurationState.setDeviceIdentifier(
  258. pushRegistrationOverall.getOcs()
  259. .getData().getDeviceIdentifier());
  260. pushConfigurationState.setDeviceIdentifierSignature(
  261. pushRegistrationOverall
  262. .getOcs().getData().getSignature());
  263. pushConfigurationState.setUserPublicKey(
  264. pushRegistrationOverall.getOcs()
  265. .getData().getPublicKey());
  266. pushConfigurationState.setUsesRegularPass(false);
  267. try {
  268. userUtils.createOrUpdateUser(null,
  269. null, null,
  270. userEntity.getDisplayName(),
  271. LoganSquare.serialize(pushConfigurationState), null,
  272. null, userEntity.getId(), null, null)
  273. .subscribe(new Observer<UserEntity>() {
  274. @Override
  275. public void onSubscribe(Disposable d) {
  276. }
  277. @Override
  278. public void onNext(UserEntity userEntity) {
  279. eventBus.post(new EventStatus(userEntity.getId(), EventStatus.EventType.PUSH_REGISTRATION, true));
  280. }
  281. @Override
  282. public void onError(Throwable e) {
  283. eventBus.post(new EventStatus
  284. (userEntity.getId(),
  285. EventStatus.EventType
  286. .PUSH_REGISTRATION, false));
  287. }
  288. @Override
  289. public void onComplete() {
  290. }
  291. });
  292. } catch (IOException e) {
  293. Log.e(TAG, "IOException while updating user");
  294. }
  295. }
  296. @Override
  297. public void onError(Throwable e) {
  298. eventBus.post(new EventStatus(userEntity.getId(),
  299. EventStatus.EventType.PUSH_REGISTRATION, false));
  300. }
  301. @Override
  302. public void onComplete() {
  303. }
  304. });
  305. }
  306. @Override
  307. public void onError(Throwable e) {
  308. eventBus.post(new EventStatus(userEntity.getId(),
  309. EventStatus.EventType.PUSH_REGISTRATION, false));
  310. }
  311. @Override
  312. public void onComplete() {
  313. }
  314. });
  315. }
  316. }
  317. }
  318. }
  319. }
  320. }
  321. private Key readKeyFromString(boolean readPublicKey, String keyString) {
  322. if (readPublicKey) {
  323. keyString = keyString.replaceAll("\\n", "").replace("-----BEGIN PUBLIC KEY-----",
  324. "").replace("-----END PUBLIC KEY-----", "");
  325. } else {
  326. keyString = keyString.replaceAll("\\n", "").replace("-----BEGIN PRIVATE KEY-----",
  327. "").replace("-----END PRIVATE KEY-----", "");
  328. }
  329. KeyFactory keyFactory = null;
  330. try {
  331. keyFactory = KeyFactory.getInstance("RSA");
  332. if (readPublicKey) {
  333. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decode(keyString, Base64.DEFAULT));
  334. return keyFactory.generatePublic(keySpec);
  335. } else {
  336. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decode(keyString, Base64.DEFAULT));
  337. return keyFactory.generatePrivate(keySpec);
  338. }
  339. } catch (NoSuchAlgorithmException e) {
  340. Log.d("TAG", "No such algorithm while reading key from string");
  341. } catch (InvalidKeySpecException e) {
  342. Log.d("TAG", "Invalid key spec while reading key from string");
  343. }
  344. return null;
  345. }
  346. public Key readKeyFromFile(boolean readPublicKey) {
  347. String path;
  348. if (readPublicKey) {
  349. path = publicKeyFile.getAbsolutePath();
  350. } else {
  351. path = privateKeyFile.getAbsolutePath();
  352. }
  353. FileInputStream fileInputStream = null;
  354. try {
  355. fileInputStream = new FileInputStream(path);
  356. byte[] bytes = new byte[fileInputStream.available()];
  357. fileInputStream.read(bytes);
  358. fileInputStream.close();
  359. KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  360. if (readPublicKey) {
  361. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
  362. return keyFactory.generatePublic(keySpec);
  363. } else {
  364. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
  365. return keyFactory.generatePrivate(keySpec);
  366. }
  367. } catch (FileNotFoundException e) {
  368. Log.d(TAG, "Failed to find path while reading the Key");
  369. } catch (IOException e) {
  370. Log.d(TAG, "IOException while reading the key");
  371. } catch (InvalidKeySpecException e) {
  372. Log.d(TAG, "InvalidKeySpecException while reading the key");
  373. } catch (NoSuchAlgorithmException e) {
  374. Log.d(TAG, "RSA algorithm not supported");
  375. }
  376. return null;
  377. }
  378. }