PushUtils.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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.annotations.NonNull;
  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. @Inject
  74. NcApi ncApi;
  75. private File keysFile;
  76. private File publicKeyFile;
  77. private File privateKeyFile;
  78. private String proxyServer;
  79. public PushUtils() {
  80. NextcloudTalkApplication.Companion.getSharedApplication().getComponentApplication().inject(this);
  81. keysFile = NextcloudTalkApplication.Companion.getSharedApplication().getDir("PushKeyStore", Context.MODE_PRIVATE);
  82. publicKeyFile = new File(NextcloudTalkApplication.Companion.getSharedApplication().getDir("PushKeystore",
  83. Context.MODE_PRIVATE), "push_key.pub");
  84. privateKeyFile = new File(NextcloudTalkApplication.Companion.getSharedApplication().getDir("PushKeystore",
  85. Context.MODE_PRIVATE), "push_key.priv");
  86. proxyServer = NextcloudTalkApplication.Companion.getSharedApplication().getResources().
  87. getString(R.string.nc_push_server_url);
  88. }
  89. public SignatureVerification verifySignature(byte[] signatureBytes, byte[] subjectBytes) {
  90. Signature signature = null;
  91. PushConfigurationState pushConfigurationState;
  92. PublicKey publicKey;
  93. SignatureVerification signatureVerification = new SignatureVerification();
  94. signatureVerification.setSignatureValid(false);
  95. List<UserEntity> userEntities = userUtils.getUsers();
  96. try {
  97. signature = Signature.getInstance("SHA512withRSA");
  98. if (userEntities != null && userEntities.size() > 0) {
  99. for (UserEntity userEntity : userEntities) {
  100. if (!TextUtils.isEmpty(userEntity.getPushConfigurationState())) {
  101. pushConfigurationState = LoganSquare.parse(userEntity.getPushConfigurationState(),
  102. PushConfigurationState.class);
  103. publicKey = (PublicKey) readKeyFromString(true,
  104. pushConfigurationState.getUserPublicKey());
  105. signature.initVerify(publicKey);
  106. signature.update(subjectBytes);
  107. if (signature.verify(signatureBytes)) {
  108. signatureVerification.setSignatureValid(true);
  109. signatureVerification.setUserEntity(userEntity);
  110. return signatureVerification;
  111. }
  112. }
  113. }
  114. }
  115. } catch (NoSuchAlgorithmException e) {
  116. Log.d(TAG, "No such algorithm");
  117. } catch (IOException e) {
  118. Log.d(TAG, "Error while trying to parse push configuration state");
  119. } catch (InvalidKeyException e) {
  120. Log.d(TAG, "Invalid key while trying to verify");
  121. } catch (SignatureException e) {
  122. Log.d(TAG, "Signature exception while trying to verify");
  123. }
  124. return signatureVerification;
  125. }
  126. private int saveKeyToFile(Key key, String path) {
  127. byte[] encoded = key.getEncoded();
  128. try {
  129. if (!new File(path).exists()) {
  130. if (!new File(path).createNewFile()) {
  131. return -1;
  132. }
  133. }
  134. try (FileOutputStream keyFileOutputStream = new FileOutputStream(path)) {
  135. keyFileOutputStream.write(encoded);
  136. return 0;
  137. }
  138. } catch (FileNotFoundException e) {
  139. Log.d(TAG, "Failed to save key to file");
  140. } catch (IOException e) {
  141. Log.d(TAG, "Failed to save key to file via IOException");
  142. }
  143. return -1;
  144. }
  145. private String generateSHA512Hash(String pushToken) {
  146. MessageDigest messageDigest = null;
  147. try {
  148. messageDigest = MessageDigest.getInstance("SHA-512");
  149. messageDigest.update(pushToken.getBytes());
  150. return bytesToHex(messageDigest.digest());
  151. } catch (NoSuchAlgorithmException e) {
  152. Log.d(TAG, "SHA-512 algorithm not supported");
  153. }
  154. return "";
  155. }
  156. private String bytesToHex(byte[] bytes) {
  157. StringBuilder result = new StringBuilder();
  158. for (byte individualByte : bytes) {
  159. result.append(Integer.toString((individualByte & 0xff) + 0x100, 16)
  160. .substring(1));
  161. }
  162. return result.toString();
  163. }
  164. public int generateRsa2048KeyPair() {
  165. if (!publicKeyFile.exists() && !privateKeyFile.exists()) {
  166. if (!keysFile.exists()) {
  167. keysFile.mkdirs();
  168. }
  169. KeyPairGenerator keyGen = null;
  170. try {
  171. keyGen = KeyPairGenerator.getInstance("RSA");
  172. keyGen.initialize(2048);
  173. KeyPair pair = keyGen.generateKeyPair();
  174. int statusPrivate = saveKeyToFile(pair.getPrivate(), privateKeyFile.getAbsolutePath());
  175. int statusPublic = saveKeyToFile(pair.getPublic(), publicKeyFile.getAbsolutePath());
  176. if (statusPrivate == 0 && statusPublic == 0) {
  177. // all went well
  178. return 0;
  179. } else {
  180. return -2;
  181. }
  182. } catch (NoSuchAlgorithmException e) {
  183. Log.d(TAG, "RSA algorithm not supported");
  184. }
  185. } else {
  186. // We already have the key
  187. return -1;
  188. }
  189. // we failed to generate the key
  190. return -2;
  191. }
  192. public void pushRegistrationToServer() {
  193. String token = appPreferences.getPushToken();
  194. if (!TextUtils.isEmpty(token)) {
  195. String credentials;
  196. String pushTokenHash = generateSHA512Hash(token).toLowerCase();
  197. PublicKey devicePublicKey = (PublicKey) readKeyFromFile(true);
  198. if (devicePublicKey != null) {
  199. byte[] publicKeyBytes = Base64.encode(devicePublicKey.getEncoded(), Base64.NO_WRAP);
  200. String publicKey = new String(publicKeyBytes);
  201. publicKey = publicKey.replaceAll("(.{64})", "$1\n");
  202. publicKey = "-----BEGIN PUBLIC KEY-----\n" + publicKey + "\n-----END PUBLIC KEY-----\n";
  203. if (userUtils.anyUserExists()) {
  204. String providerValue;
  205. PushConfigurationState accountPushData = null;
  206. for (Object userEntityObject : userUtils.getUsers()) {
  207. UserEntity userEntity = (UserEntity) userEntityObject;
  208. providerValue = userEntity.getPushConfigurationState();
  209. if (!TextUtils.isEmpty(providerValue)) {
  210. try {
  211. accountPushData = LoganSquare.parse(providerValue, PushConfigurationState.class);
  212. } catch (IOException e) {
  213. Log.d(TAG, "Failed to parse account push data");
  214. accountPushData = null;
  215. }
  216. } else {
  217. accountPushData = null;
  218. }
  219. if (((TextUtils.isEmpty(providerValue) || accountPushData == null) && !userEntity.getScheduledForDeletion()) ||
  220. (accountPushData != null && !accountPushData.getPushToken().equals(token) && !userEntity.getScheduledForDeletion())) {
  221. Map<String, String> queryMap = new HashMap<>();
  222. queryMap.put("format", "json");
  223. queryMap.put("pushTokenHash", pushTokenHash);
  224. queryMap.put("devicePublicKey", publicKey);
  225. queryMap.put("proxyServer", proxyServer);
  226. credentials = ApiUtils.getCredentials(userEntity.getUsername(), userEntity.getToken());
  227. ncApi.registerDeviceForNotificationsWithNextcloud(
  228. credentials,
  229. ApiUtils.getUrlNextcloudPush(userEntity.getBaseUrl()), queryMap)
  230. .subscribe(new Observer<PushRegistrationOverall>() {
  231. @Override
  232. public void onSubscribe(@NonNull Disposable d) {
  233. }
  234. @Override
  235. public void onNext(@NonNull 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(
  245. ApiUtils.getUrlPushProxy(), proxyMap)
  246. .subscribeOn(Schedulers.io())
  247. .subscribe(new Observer<Void>() {
  248. @Override
  249. public void onSubscribe(@NonNull Disposable d) {
  250. }
  251. @Override
  252. public void onNext(@NonNull 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, 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(@NonNull 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(@NonNull 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. try (FileInputStream fileInputStream = new FileInputStream(path)) {
  353. byte[] bytes = new byte[fileInputStream.available()];
  354. fileInputStream.read(bytes);
  355. KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  356. if (readPublicKey) {
  357. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
  358. return keyFactory.generatePublic(keySpec);
  359. } else {
  360. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
  361. return keyFactory.generatePrivate(keySpec);
  362. }
  363. } catch (FileNotFoundException e) {
  364. Log.d(TAG, "Failed to find path while reading the Key");
  365. } catch (IOException e) {
  366. Log.d(TAG, "IOException while reading the key");
  367. } catch (InvalidKeySpecException e) {
  368. Log.d(TAG, "InvalidKeySpecException while reading the key");
  369. } catch (NoSuchAlgorithmException e) {
  370. Log.d(TAG, "RSA algorithm not supported");
  371. }
  372. return null;
  373. }
  374. }