PushUtils.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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.api.helpers.api.ApiHelper;
  29. import com.nextcloud.talk.api.models.json.push.PushConfigurationState;
  30. import com.nextcloud.talk.application.NextcloudTalkApplication;
  31. import com.nextcloud.talk.models.SignatureVerification;
  32. import com.nextcloud.talk.persistence.entities.UserEntity;
  33. import com.nextcloud.talk.utils.database.user.UserUtils;
  34. import com.nextcloud.talk.utils.preferences.AppPreferences;
  35. import java.io.File;
  36. import java.io.FileInputStream;
  37. import java.io.FileNotFoundException;
  38. import java.io.FileOutputStream;
  39. import java.io.IOException;
  40. import java.net.CookieManager;
  41. import java.security.InvalidKeyException;
  42. import java.security.Key;
  43. import java.security.KeyFactory;
  44. import java.security.KeyPair;
  45. import java.security.KeyPairGenerator;
  46. import java.security.MessageDigest;
  47. import java.security.NoSuchAlgorithmException;
  48. import java.security.PublicKey;
  49. import java.security.Signature;
  50. import java.security.SignatureException;
  51. import java.security.spec.InvalidKeySpecException;
  52. import java.security.spec.PKCS8EncodedKeySpec;
  53. import java.security.spec.X509EncodedKeySpec;
  54. import java.util.HashMap;
  55. import java.util.List;
  56. import java.util.Map;
  57. import javax.inject.Inject;
  58. import autodagger.AutoInjector;
  59. import io.reactivex.functions.Consumer;
  60. import io.reactivex.schedulers.Schedulers;
  61. import okhttp3.JavaNetCookieJar;
  62. import okhttp3.OkHttpClient;
  63. import retrofit2.Retrofit;
  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. OkHttpClient okHttpClient;
  73. @Inject
  74. Retrofit retrofit;
  75. NcApi ncApi;
  76. private File keysFile;
  77. private File publicKeyFile;
  78. private File privateKeyFile;
  79. private String proxyServer;
  80. public PushUtils() {
  81. NextcloudTalkApplication.getSharedApplication().getComponentApplication().inject(this);
  82. keysFile = NextcloudTalkApplication.getSharedApplication().getDir("PushKeyStore", Context.MODE_PRIVATE);
  83. publicKeyFile = new File(NextcloudTalkApplication.getSharedApplication().getDir("PushKeystore",
  84. Context.MODE_PRIVATE), "push_key.pub");
  85. privateKeyFile = new File(NextcloudTalkApplication.getSharedApplication().getDir("PushKeystore",
  86. Context.MODE_PRIVATE), "push_key.priv");
  87. proxyServer = NextcloudTalkApplication.getSharedApplication().getResources().
  88. getString(R.string.nc_push_server_url);
  89. }
  90. public SignatureVerification verifySignature(byte[] signatureBytes, byte[] subjectBytes) {
  91. Signature signature = null;
  92. PushConfigurationState pushConfigurationState;
  93. PublicKey publicKey;
  94. SignatureVerification signatureVerification = new SignatureVerification();
  95. signatureVerification.setSignatureValid(false);
  96. List<UserEntity> userEntities = userUtils.getUsers();
  97. try {
  98. signature = Signature.getInstance("SHA512withRSA");
  99. if (userEntities != null && userEntities.size() > 0) {
  100. for (UserEntity userEntity : userEntities) {
  101. if (!TextUtils.isEmpty(userEntity.getPushConfigurationState())) {
  102. pushConfigurationState = LoganSquare.parse(userEntity.getPushConfigurationState(),
  103. PushConfigurationState.class);
  104. publicKey = (PublicKey) readKeyFromString(true,
  105. pushConfigurationState.getUserPublicKey());
  106. signature.initVerify(publicKey);
  107. signature.update(subjectBytes);
  108. if (signature.verify(signatureBytes)) {
  109. signatureVerification.setSignatureValid(true);
  110. signatureVerification.setUserEntity(userEntity);
  111. return signatureVerification;
  112. }
  113. }
  114. }
  115. }
  116. } catch (NoSuchAlgorithmException e) {
  117. Log.d(TAG, "No such algorithm");
  118. } catch (IOException e) {
  119. Log.d(TAG, "Error while trying to parse push configuration state");
  120. } catch (InvalidKeyException e) {
  121. Log.d(TAG, "Invalid key while trying to verify");
  122. } catch (SignatureException e) {
  123. Log.d(TAG, "Signature exception while trying to verify");
  124. }
  125. return signatureVerification;
  126. }
  127. private int saveKeyToFile(Key key, String path) {
  128. byte[] encoded = key.getEncoded();
  129. FileOutputStream keyFileOutputStream = null;
  130. try {
  131. if (!new File(path).exists()) {
  132. new File(path).createNewFile();
  133. }
  134. keyFileOutputStream = new FileOutputStream(path);
  135. keyFileOutputStream.write(encoded);
  136. keyFileOutputStream.close();
  137. return 0;
  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. public 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. public 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 pushTokenHash = generateSHA512Hash(token).toLowerCase();
  196. PublicKey devicePublicKey = (PublicKey) readKeyFromFile(true);
  197. if (devicePublicKey != null) {
  198. byte[] publicKeyBytes = Base64.encode(devicePublicKey.getEncoded(), Base64.NO_WRAP);
  199. String publicKey = new String(publicKeyBytes);
  200. publicKey = publicKey.replaceAll("(.{64})", "$1\n");
  201. publicKey = "-----BEGIN PUBLIC KEY-----\n" + publicKey + "\n-----END PUBLIC KEY-----\n";
  202. if (userUtils.anyUserExists()) {
  203. String providerValue;
  204. PushConfigurationState accountPushData = null;
  205. for (Object userEntityObject : userUtils.getUsers()) {
  206. UserEntity userEntity = (UserEntity) userEntityObject;
  207. providerValue = userEntity.getPushConfigurationState();
  208. if (!TextUtils.isEmpty(providerValue)) {
  209. try {
  210. accountPushData = LoganSquare.parse(providerValue, PushConfigurationState.class);
  211. } catch (IOException e) {
  212. Log.d(TAG, "Failed to parse account push data");
  213. accountPushData = null;
  214. }
  215. } else {
  216. accountPushData = null;
  217. }
  218. if (accountPushData != null && !accountPushData.getPushToken().equals(token) &&
  219. !userEntity.getScheduledForDeletion() ||
  220. TextUtils.isEmpty(providerValue) && !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. ncApi = retrofit.newBuilder().client(okHttpClient.newBuilder().cookieJar(new
  227. JavaNetCookieJar(new CookieManager())).build()).build().create(NcApi.class);
  228. ncApi.registerDeviceForNotificationsWithNextcloud(
  229. ApiHelper.getCredentials(userEntity.getUsername(), userEntity.getToken()),
  230. ApiHelper.getUrlNextcloudPush(userEntity.getBaseUrl()), queryMap)
  231. .subscribeOn(Schedulers.newThread())
  232. .subscribe(pushRegistrationOverall -> {
  233. Map<String, String> proxyMap = new HashMap<>();
  234. proxyMap.put("pushToken", token);
  235. proxyMap.put("deviceIdentifier", pushRegistrationOverall.getOcs().getData().
  236. getDeviceIdentifier());
  237. proxyMap.put("deviceIdentifierSignature", pushRegistrationOverall.getOcs()
  238. .getData().getSignature());
  239. proxyMap.put("userPublicKey", pushRegistrationOverall.getOcs()
  240. .getData().getPublicKey());
  241. ncApi.registerDeviceForNotificationsWithProxy(ApiHelper.getCredentials
  242. (userEntity.getUsername(), userEntity.getToken()),
  243. ApiHelper.getUrlPushProxy(), proxyMap)
  244. .subscribeOn(Schedulers.newThread())
  245. .subscribe(new Consumer<Void>() {
  246. @Override
  247. public void accept(Void aVoid) throws Exception {
  248. PushConfigurationState pushConfigurationState =
  249. new PushConfigurationState();
  250. pushConfigurationState.setPushToken(token);
  251. pushConfigurationState.setDeviceIdentifier(
  252. pushRegistrationOverall.getOcs()
  253. .getData().getDeviceIdentifier());
  254. pushConfigurationState.setDeviceIdentifierSignature(
  255. pushRegistrationOverall
  256. .getOcs().getData().getSignature());
  257. pushConfigurationState.setUserPublicKey(
  258. pushRegistrationOverall.getOcs()
  259. .getData().getPublicKey());
  260. pushConfigurationState.setUsesRegularPass(false);
  261. userUtils.createOrUpdateUser(userEntity.getUsername(),
  262. userEntity.getToken(), userEntity.getBaseUrl(),
  263. userEntity.getDisplayName(),
  264. LoganSquare.serialize(pushConfigurationState), null)
  265. .subscribe(new Consumer<UserEntity>() {
  266. @Override
  267. public void accept(UserEntity userEntity) throws Exception {
  268. // all went well
  269. }
  270. }, new Consumer<Throwable>() {
  271. @Override
  272. public void accept(Throwable throwable) throws Exception {
  273. }
  274. });
  275. }
  276. }, new Consumer<Throwable>() {
  277. @Override
  278. public void accept(Throwable throwable) throws Exception {
  279. // something went wrong
  280. }
  281. });
  282. }, new Consumer<Throwable>() {
  283. @Override
  284. public void accept(Throwable throwable) throws Exception {
  285. // TODO: If 400, we're using regular token
  286. }
  287. });
  288. }
  289. }
  290. }
  291. }
  292. }
  293. }
  294. private Key readKeyFromString(boolean readPublicKey, String keyString) {
  295. keyString = keyString.replace("-----BEGIN PUBLIC KEY-----", "");
  296. keyString = keyString.replace("-----END PUBLIC KEY-----", "");
  297. if (readPublicKey) {
  298. keyString = keyString.replaceAll("\\n", "").replace("-----BEGIN PUBLIC KEY-----",
  299. "").replace("-----END PUBLIC KEY-----", "");
  300. ;
  301. } else {
  302. keyString = keyString.replaceAll("\\n", "").replace("-----BEGIN PRIVATE KEY-----",
  303. "").replace("-----END PRIVATE KEY-----", "");
  304. }
  305. KeyFactory keyFactory = null;
  306. try {
  307. keyFactory = KeyFactory.getInstance("RSA");
  308. if (readPublicKey) {
  309. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decode(keyString, Base64.DEFAULT));
  310. return keyFactory.generatePublic(keySpec);
  311. } else {
  312. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decode(keyString, Base64.DEFAULT));
  313. return keyFactory.generatePrivate(keySpec);
  314. }
  315. } catch (NoSuchAlgorithmException e) {
  316. Log.d("TAG", "No such algorithm while reading key from string");
  317. } catch (InvalidKeySpecException e) {
  318. Log.d("TAG", "Invalid key spec while reading key from string");
  319. }
  320. return null;
  321. }
  322. public Key readKeyFromFile(boolean readPublicKey) {
  323. String path;
  324. if (readPublicKey) {
  325. path = publicKeyFile.getAbsolutePath();
  326. } else {
  327. path = privateKeyFile.getAbsolutePath();
  328. }
  329. FileInputStream fileInputStream = null;
  330. try {
  331. fileInputStream = new FileInputStream(path);
  332. byte[] bytes = new byte[fileInputStream.available()];
  333. fileInputStream.read(bytes);
  334. fileInputStream.close();
  335. KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  336. if (readPublicKey) {
  337. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
  338. return keyFactory.generatePublic(keySpec);
  339. } else {
  340. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
  341. return keyFactory.generatePrivate(keySpec);
  342. }
  343. } catch (FileNotFoundException e) {
  344. Log.d(TAG, "Failed to find path while reading the Key");
  345. } catch (IOException e) {
  346. Log.d(TAG, "IOException while reading the key");
  347. } catch (InvalidKeySpecException e) {
  348. Log.d(TAG, "InvalidKeySpecException while reading the key");
  349. } catch (NoSuchAlgorithmException e) {
  350. Log.d(TAG, "RSA algorithm not supported");
  351. }
  352. return null;
  353. }
  354. }