PushUtils.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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 org.greenrobot.eventbus.EventBus;
  37. import java.io.File;
  38. import java.io.FileInputStream;
  39. import java.io.FileNotFoundException;
  40. import java.io.FileOutputStream;
  41. import java.io.IOException;
  42. import java.security.InvalidKeyException;
  43. import java.security.Key;
  44. import java.security.KeyFactory;
  45. import java.security.KeyPair;
  46. import java.security.KeyPairGenerator;
  47. import java.security.MessageDigest;
  48. import java.security.NoSuchAlgorithmException;
  49. import java.security.PublicKey;
  50. import java.security.Signature;
  51. import java.security.SignatureException;
  52. import java.security.spec.InvalidKeySpecException;
  53. import java.security.spec.PKCS8EncodedKeySpec;
  54. import java.security.spec.X509EncodedKeySpec;
  55. import java.util.HashMap;
  56. import java.util.List;
  57. import java.util.Map;
  58. import javax.inject.Inject;
  59. import autodagger.AutoInjector;
  60. import io.reactivex.Observer;
  61. import io.reactivex.disposables.Disposable;
  62. import io.reactivex.schedulers.Schedulers;
  63. @AutoInjector(NextcloudTalkApplication.class)
  64. public class PushUtils {
  65. private static final String TAG = "PushUtils";
  66. @Inject
  67. UserUtils userUtils;
  68. @Inject
  69. AppPreferences appPreferences;
  70. @Inject
  71. EventBus eventBus;
  72. @Inject
  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. credentials = ApiUtils.getCredentials(userEntity.getUserId(), userEntity.getToken());
  226. String finalCredentials = credentials;
  227. ncApi.registerDeviceForNotificationsWithNextcloud(
  228. credentials,
  229. ApiUtils.getUrlNextcloudPush(userEntity.getBaseUrl()), queryMap)
  230. .subscribe(new Observer<PushRegistrationOverall>() {
  231. @Override
  232. public void onSubscribe(Disposable d) {
  233. }
  234. @Override
  235. public void onNext(PushRegistrationOverall pushRegistrationOverall) {
  236. Map<String, String> proxyMap = new HashMap<>();
  237. proxyMap.put("pushToken", token);
  238. proxyMap.put("deviceIdentifier", pushRegistrationOverall.getOcs().getData().
  239. getDeviceIdentifier());
  240. proxyMap.put("deviceIdentifierSignature", pushRegistrationOverall.getOcs()
  241. .getData().getSignature());
  242. proxyMap.put("userPublicKey", pushRegistrationOverall.getOcs()
  243. .getData().getPublicKey());
  244. ncApi.registerDeviceForNotificationsWithProxy(finalCredentials,
  245. ApiUtils.getUrlPushProxy(), proxyMap)
  246. .subscribeOn(Schedulers.newThread())
  247. .subscribe(new Observer<Void>() {
  248. @Override
  249. public void onSubscribe(Disposable d) {
  250. }
  251. @Override
  252. public void onNext(Void aVoid) {
  253. PushConfigurationState pushConfigurationState =
  254. new PushConfigurationState();
  255. pushConfigurationState.setPushToken(token);
  256. pushConfigurationState.setDeviceIdentifier(
  257. pushRegistrationOverall.getOcs()
  258. .getData().getDeviceIdentifier());
  259. pushConfigurationState.setDeviceIdentifierSignature(
  260. pushRegistrationOverall
  261. .getOcs().getData().getSignature());
  262. pushConfigurationState.setUserPublicKey(
  263. pushRegistrationOverall.getOcs()
  264. .getData().getPublicKey());
  265. pushConfigurationState.setUsesRegularPass(false);
  266. try {
  267. userUtils.createOrUpdateUser(null,
  268. null, null,
  269. userEntity.getDisplayName(),
  270. LoganSquare.serialize(pushConfigurationState), null,
  271. null, userEntity.getId(), null, null)
  272. .subscribe(new Observer<UserEntity>() {
  273. @Override
  274. public void onSubscribe(Disposable d) {
  275. }
  276. @Override
  277. public void onNext(UserEntity userEntity) {
  278. eventBus.post(new EventStatus(userEntity.getId(), EventStatus.EventType.PUSH_REGISTRATION, true));
  279. }
  280. @Override
  281. public void onError(Throwable e) {
  282. eventBus.post(new EventStatus
  283. (userEntity.getId(),
  284. EventStatus.EventType
  285. .PUSH_REGISTRATION, false));
  286. }
  287. @Override
  288. public void onComplete() {
  289. }
  290. });
  291. } catch (IOException e) {
  292. Log.e(TAG, "IOException while updating user");
  293. }
  294. }
  295. @Override
  296. public void onError(Throwable e) {
  297. eventBus.post(new EventStatus(userEntity.getId(),
  298. EventStatus.EventType.PUSH_REGISTRATION, false));
  299. }
  300. @Override
  301. public void onComplete() {
  302. }
  303. });
  304. }
  305. @Override
  306. public void onError(Throwable e) {
  307. eventBus.post(new EventStatus(userEntity.getId(),
  308. EventStatus.EventType.PUSH_REGISTRATION, false));
  309. }
  310. @Override
  311. public void onComplete() {
  312. }
  313. });
  314. }
  315. }
  316. }
  317. }
  318. }
  319. }
  320. private Key readKeyFromString(boolean readPublicKey, String keyString) {
  321. if (readPublicKey) {
  322. keyString = keyString.replaceAll("\\n", "").replace("-----BEGIN PUBLIC KEY-----",
  323. "").replace("-----END PUBLIC KEY-----", "");
  324. } else {
  325. keyString = keyString.replaceAll("\\n", "").replace("-----BEGIN PRIVATE KEY-----",
  326. "").replace("-----END PRIVATE KEY-----", "");
  327. }
  328. KeyFactory keyFactory = null;
  329. try {
  330. keyFactory = KeyFactory.getInstance("RSA");
  331. if (readPublicKey) {
  332. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decode(keyString, Base64.DEFAULT));
  333. return keyFactory.generatePublic(keySpec);
  334. } else {
  335. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decode(keyString, Base64.DEFAULT));
  336. return keyFactory.generatePrivate(keySpec);
  337. }
  338. } catch (NoSuchAlgorithmException e) {
  339. Log.d("TAG", "No such algorithm while reading key from string");
  340. } catch (InvalidKeySpecException e) {
  341. Log.d("TAG", "Invalid key spec while reading key from string");
  342. }
  343. return null;
  344. }
  345. public Key readKeyFromFile(boolean readPublicKey) {
  346. String path;
  347. if (readPublicKey) {
  348. path = publicKeyFile.getAbsolutePath();
  349. } else {
  350. path = privateKeyFile.getAbsolutePath();
  351. }
  352. FileInputStream fileInputStream = null;
  353. try {
  354. fileInputStream = new FileInputStream(path);
  355. byte[] bytes = new byte[fileInputStream.available()];
  356. fileInputStream.read(bytes);
  357. fileInputStream.close();
  358. KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  359. if (readPublicKey) {
  360. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
  361. return keyFactory.generatePublic(keySpec);
  362. } else {
  363. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
  364. return keyFactory.generatePrivate(keySpec);
  365. }
  366. } catch (FileNotFoundException e) {
  367. Log.d(TAG, "Failed to find path while reading the Key");
  368. } catch (IOException e) {
  369. Log.d(TAG, "IOException while reading the key");
  370. } catch (InvalidKeySpecException e) {
  371. Log.d(TAG, "InvalidKeySpecException while reading the key");
  372. } catch (NoSuchAlgorithmException e) {
  373. Log.d(TAG, "RSA algorithm not supported");
  374. }
  375. return null;
  376. }
  377. }