|
@@ -0,0 +1,317 @@
|
|
|
+/*
|
|
|
+ * Nextcloud Talk application
|
|
|
+ *
|
|
|
+ * @author Mario Danic
|
|
|
+ * Copyright (C) 2017 Mario Danic <mario@lovelyhq.com>
|
|
|
+ *
|
|
|
+ * This program is free software: you can redistribute it and/or modify
|
|
|
+ * it under the terms of the GNU General Public License as published by
|
|
|
+ * the Free Software Foundation, either version 3 of the License, or
|
|
|
+ * at your option) any later version.
|
|
|
+ *
|
|
|
+ * This program is distributed in the hope that it will be useful,
|
|
|
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
+ * GNU General Public License for more details.
|
|
|
+ *
|
|
|
+ * You should have received a copy of the GNU General Public License
|
|
|
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
+ */
|
|
|
+
|
|
|
+package com.nextcloud.talk.utils;
|
|
|
+
|
|
|
+import android.content.Context;
|
|
|
+import android.text.TextUtils;
|
|
|
+import android.util.Base64;
|
|
|
+import android.util.Log;
|
|
|
+
|
|
|
+import com.bluelinelabs.logansquare.LoganSquare;
|
|
|
+import com.nextcloud.talk.R;
|
|
|
+import com.nextcloud.talk.api.NcApi;
|
|
|
+import com.nextcloud.talk.api.helpers.api.ApiHelper;
|
|
|
+import com.nextcloud.talk.api.models.PushConfigurationState;
|
|
|
+import com.nextcloud.talk.application.NextcloudTalkApplication;
|
|
|
+import com.nextcloud.talk.persistence.entities.UserEntity;
|
|
|
+import com.nextcloud.talk.utils.database.user.UserUtils;
|
|
|
+import com.nextcloud.talk.utils.preferences.AppPreferences;
|
|
|
+
|
|
|
+import java.io.File;
|
|
|
+import java.io.FileInputStream;
|
|
|
+import java.io.FileNotFoundException;
|
|
|
+import java.io.FileOutputStream;
|
|
|
+import java.io.IOException;
|
|
|
+import java.security.Key;
|
|
|
+import java.security.KeyFactory;
|
|
|
+import java.security.KeyPair;
|
|
|
+import java.security.KeyPairGenerator;
|
|
|
+import java.security.MessageDigest;
|
|
|
+import java.security.NoSuchAlgorithmException;
|
|
|
+import java.security.PublicKey;
|
|
|
+import java.security.spec.InvalidKeySpecException;
|
|
|
+import java.security.spec.PKCS8EncodedKeySpec;
|
|
|
+import java.security.spec.X509EncodedKeySpec;
|
|
|
+import java.util.HashMap;
|
|
|
+import java.util.Map;
|
|
|
+
|
|
|
+import javax.inject.Inject;
|
|
|
+
|
|
|
+import autodagger.AutoInjector;
|
|
|
+import io.reactivex.functions.Consumer;
|
|
|
+import io.reactivex.schedulers.Schedulers;
|
|
|
+
|
|
|
+@AutoInjector(NextcloudTalkApplication.class)
|
|
|
+public class PushUtils {
|
|
|
+ private static final String TAG = "PushUtils";
|
|
|
+
|
|
|
+ @Inject
|
|
|
+ UserUtils userUtils;
|
|
|
+
|
|
|
+ @Inject
|
|
|
+ AppPreferences appPreferences;
|
|
|
+
|
|
|
+ @Inject
|
|
|
+ NcApi ncApi;
|
|
|
+
|
|
|
+ private File keysFile;
|
|
|
+ private File publicKeyFile;
|
|
|
+ private File privateKeyFile;
|
|
|
+
|
|
|
+ private String proxyServer;
|
|
|
+
|
|
|
+ public PushUtils() {
|
|
|
+ NextcloudTalkApplication.getSharedApplication().getComponentApplication().inject(this);
|
|
|
+
|
|
|
+ keysFile = NextcloudTalkApplication.getSharedApplication().getDir("PushKeyStore", Context.MODE_PRIVATE);
|
|
|
+ publicKeyFile = new File(NextcloudTalkApplication.getSharedApplication().getDir("PushKeystore",
|
|
|
+ Context.MODE_PRIVATE), "push_key.pub");
|
|
|
+ privateKeyFile = new File(NextcloudTalkApplication.getSharedApplication().getDir("PushKeystore",
|
|
|
+ Context.MODE_PRIVATE), "push_key.priv");
|
|
|
+ proxyServer = NextcloudTalkApplication.getSharedApplication().getResources().
|
|
|
+ getString(R.string.nc_push_server_url);
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ private static int saveKeyToFile(Key key, String path) {
|
|
|
+ byte[] encoded = key.getEncoded();
|
|
|
+ FileOutputStream keyFileOutputStream = null;
|
|
|
+ try {
|
|
|
+ if (!new File(path).exists()) {
|
|
|
+ new File(path).createNewFile();
|
|
|
+ }
|
|
|
+ keyFileOutputStream = new FileOutputStream(path);
|
|
|
+ keyFileOutputStream.write(encoded);
|
|
|
+ keyFileOutputStream.close();
|
|
|
+ return 0;
|
|
|
+ } catch (FileNotFoundException e) {
|
|
|
+ Log.d(TAG, "Failed to save key to file");
|
|
|
+ } catch (IOException e) {
|
|
|
+ Log.d(TAG, "Failed to save key to file via IOException");
|
|
|
+ }
|
|
|
+
|
|
|
+ return -1;
|
|
|
+ }
|
|
|
+
|
|
|
+ public String generateSHA512Hash(String pushToken) {
|
|
|
+ MessageDigest messageDigest = null;
|
|
|
+ try {
|
|
|
+ messageDigest = MessageDigest.getInstance("SHA-512");
|
|
|
+ messageDigest.update(pushToken.getBytes());
|
|
|
+ return bytesToHex(messageDigest.digest());
|
|
|
+ } catch (NoSuchAlgorithmException e) {
|
|
|
+ Log.d(TAG, "SHA-512 algorithm not supported");
|
|
|
+ }
|
|
|
+ return "";
|
|
|
+ }
|
|
|
+
|
|
|
+ public String bytesToHex(byte[] bytes) {
|
|
|
+ StringBuilder result = new StringBuilder();
|
|
|
+ for (byte individualByte : bytes) {
|
|
|
+ result.append(Integer.toString((individualByte & 0xff) + 0x100, 16)
|
|
|
+ .substring(1));
|
|
|
+ }
|
|
|
+ return result.toString();
|
|
|
+ }
|
|
|
+
|
|
|
+ private void deleteRegistrationForAccount(UserEntity userEntity) {
|
|
|
+ }
|
|
|
+
|
|
|
+ public int generateRsa2048KeyPair() {
|
|
|
+ if (!publicKeyFile.exists() && !privateKeyFile.exists()) {
|
|
|
+ if (!keysFile.exists()) {
|
|
|
+ keysFile.mkdirs();
|
|
|
+ }
|
|
|
+
|
|
|
+ KeyPairGenerator keyGen = null;
|
|
|
+ try {
|
|
|
+ keyGen = KeyPairGenerator.getInstance("RSA");
|
|
|
+ keyGen.initialize(2048);
|
|
|
+
|
|
|
+ KeyPair pair = keyGen.generateKeyPair();
|
|
|
+ int statusPrivate = saveKeyToFile(pair.getPrivate(), privateKeyFile.getAbsolutePath());
|
|
|
+ int statusPublic = saveKeyToFile(pair.getPublic(), publicKeyFile.getAbsolutePath());
|
|
|
+
|
|
|
+ if (statusPrivate == 0 && statusPublic == 0) {
|
|
|
+ // all went well
|
|
|
+ return 0;
|
|
|
+ } else {
|
|
|
+ return -2;
|
|
|
+ }
|
|
|
+
|
|
|
+ } catch (NoSuchAlgorithmException e) {
|
|
|
+ Log.d(TAG, "RSA algorithm not supported");
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ // We already have the key
|
|
|
+ return -1;
|
|
|
+ }
|
|
|
+
|
|
|
+ // we failed to generate the key
|
|
|
+ return -2;
|
|
|
+ }
|
|
|
+
|
|
|
+ public void pushRegistrationToServer() {
|
|
|
+ String token = appPreferences.getPushToken();
|
|
|
+
|
|
|
+ if (!TextUtils.isEmpty(token)) {
|
|
|
+ String pushTokenHash = generateSHA512Hash(token).toLowerCase();
|
|
|
+ PublicKey devicePublicKey = (PublicKey) readKeyFromFile(true);
|
|
|
+ if (devicePublicKey != null) {
|
|
|
+ byte[] publicKeyBytes = Base64.encode(devicePublicKey.getEncoded(), Base64.NO_WRAP);
|
|
|
+ String publicKey = new String(publicKeyBytes);
|
|
|
+ publicKey = publicKey.replaceAll("(.{64})", "$1\n");
|
|
|
+
|
|
|
+ publicKey = "-----BEGIN PUBLIC KEY-----\n" + publicKey + "\n-----END PUBLIC KEY-----\n";
|
|
|
+
|
|
|
+ if (userUtils.anyUserExists()) {
|
|
|
+ String providerValue;
|
|
|
+ PushConfigurationState accountPushData = null;
|
|
|
+ for (UserEntity userEntity : userUtils.getUsers()) {
|
|
|
+ providerValue = userEntity.getPushConfigurationState();
|
|
|
+ if (!TextUtils.isEmpty(providerValue)) {
|
|
|
+ try {
|
|
|
+ accountPushData = LoganSquare.parse(providerValue, PushConfigurationState.class);
|
|
|
+ } catch (IOException e) {
|
|
|
+ Log.d(TAG, "Failed to parse account push data");
|
|
|
+ accountPushData = null;
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ accountPushData = null;
|
|
|
+ }
|
|
|
+
|
|
|
+ if (accountPushData != null && !accountPushData.getPushToken().equals(token) &&
|
|
|
+ !accountPushData.isShouldBeDeleted() ||
|
|
|
+ TextUtils.isEmpty(providerValue)) {
|
|
|
+
|
|
|
+
|
|
|
+ Map<String, String> queryMap = new HashMap<>();
|
|
|
+ queryMap.put("format", "json");
|
|
|
+ queryMap.put("pushTokenHash", pushTokenHash);
|
|
|
+ queryMap.put("devicePublicKey", publicKey);
|
|
|
+ queryMap.put("proxyServer", proxyServer);
|
|
|
+
|
|
|
+ ncApi.registerDeviceForNotificationsWithNextcloud(
|
|
|
+ ApiHelper.getCredentials(userEntity.getUsername(), userEntity.getToken()),
|
|
|
+ ApiHelper.getUrlNextcloudPush(userEntity.getBaseUrl()), queryMap)
|
|
|
+ .subscribeOn(Schedulers.newThread())
|
|
|
+ .subscribe(pushRegistrationOverall -> {
|
|
|
+ Map<String, String> proxyMap = new HashMap<>();
|
|
|
+ proxyMap.put("pushToken", token);
|
|
|
+ proxyMap.put("deviceIdentifier", pushRegistrationOverall.getOcs().getData().
|
|
|
+ getDeviceIdentifier());
|
|
|
+ proxyMap.put("deviceIdentifierSignature", pushRegistrationOverall.getOcs()
|
|
|
+ .getData().getSignature());
|
|
|
+ proxyMap.put("userPublicKey", pushRegistrationOverall.getOcs()
|
|
|
+ .getData().getPublicKey());
|
|
|
+
|
|
|
+
|
|
|
+ ncApi.registerDeviceForNotificationsWithProxy(ApiHelper.getCredentials
|
|
|
+ (userEntity.getUsername(), userEntity.getToken()),
|
|
|
+ ApiHelper.getUrlPushProxy(userEntity.getBaseUrl()), proxyMap)
|
|
|
+ .subscribeOn(Schedulers.newThread())
|
|
|
+ .subscribe(new Consumer<Void>() {
|
|
|
+ @Override
|
|
|
+ public void accept(Void aVoid) throws Exception {
|
|
|
+
|
|
|
+ PushConfigurationState pushConfigurationState =
|
|
|
+ new PushConfigurationState();
|
|
|
+ pushConfigurationState.setPushToken(token);
|
|
|
+ pushConfigurationState.setDeviceIdentifier(
|
|
|
+ pushRegistrationOverall.getOcs()
|
|
|
+ .getData().getDeviceIdentifier());
|
|
|
+ pushConfigurationState.setDeviceIdentifierSignature(
|
|
|
+ pushRegistrationOverall
|
|
|
+ .getOcs().getData().getSignature());
|
|
|
+ pushConfigurationState.setUserPublicKey(
|
|
|
+ pushRegistrationOverall.getOcs()
|
|
|
+ .getData().getPublicKey());
|
|
|
+ pushConfigurationState.setShouldBeDeleted(false);
|
|
|
+ pushConfigurationState.setUsesRegularPass(false);
|
|
|
+
|
|
|
+ userUtils.createOrUpdateUser(userEntity.getUsername(),
|
|
|
+ userEntity.getToken(), userEntity.getBaseUrl(),
|
|
|
+ userEntity.getDisplayName(),
|
|
|
+ LoganSquare.serialize(pushConfigurationState));
|
|
|
+
|
|
|
+ }
|
|
|
+ }, new Consumer<Throwable>() {
|
|
|
+ @Override
|
|
|
+ public void accept(Throwable throwable) throws Exception {
|
|
|
+ // something went wrong
|
|
|
+ }
|
|
|
+ });
|
|
|
+
|
|
|
+
|
|
|
+ }, new Consumer<Throwable>() {
|
|
|
+ @Override
|
|
|
+ public void accept(Throwable throwable) throws Exception {
|
|
|
+ // TODO: If 400, we're using regular token
|
|
|
+ }
|
|
|
+ });
|
|
|
+
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private Key readKeyFromFile(boolean readPublicKey) {
|
|
|
+ String path;
|
|
|
+
|
|
|
+ if (readPublicKey) {
|
|
|
+ path = publicKeyFile.getAbsolutePath();
|
|
|
+ } else {
|
|
|
+ path = privateKeyFile.getAbsolutePath();
|
|
|
+ }
|
|
|
+
|
|
|
+ FileInputStream fileInputStream = null;
|
|
|
+ try {
|
|
|
+ fileInputStream = new FileInputStream(path);
|
|
|
+ byte[] bytes = new byte[fileInputStream.available()];
|
|
|
+ fileInputStream.read(bytes);
|
|
|
+ fileInputStream.close();
|
|
|
+
|
|
|
+ KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
|
|
+
|
|
|
+ if (readPublicKey) {
|
|
|
+ X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
|
|
|
+ return keyFactory.generatePublic(keySpec);
|
|
|
+ } else {
|
|
|
+ PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
|
|
|
+ return keyFactory.generatePrivate(keySpec);
|
|
|
+ }
|
|
|
+
|
|
|
+ } catch (FileNotFoundException e) {
|
|
|
+ Log.d(TAG, "Failed to find path while reading the Key");
|
|
|
+ } catch (IOException e) {
|
|
|
+ Log.d(TAG, "IOException while reading the key");
|
|
|
+ } catch (InvalidKeySpecException e) {
|
|
|
+ Log.d(TAG, "InvalidKeySpecException while reading the key");
|
|
|
+ } catch (NoSuchAlgorithmException e) {
|
|
|
+ Log.d(TAG, "RSA algorithm not supported");
|
|
|
+ }
|
|
|
+
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+}
|