SetupEncryptionDialogFragment.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. /*
  2. * Nextcloud Android client application
  3. *
  4. * @author Tobias Kaminsky
  5. * Copyright (C) 2017 Tobias Kaminsky
  6. * Copyright (C) 2017 Nextcloud GmbH.
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU Affero General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU Affero General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. */
  21. package com.owncloud.android.ui.dialog;
  22. import android.accounts.AccountManager;
  23. import android.app.Dialog;
  24. import android.content.DialogInterface;
  25. import android.content.Intent;
  26. import android.graphics.PorterDuff;
  27. import android.graphics.drawable.Drawable;
  28. import android.os.AsyncTask;
  29. import android.os.Bundle;
  30. import android.view.LayoutInflater;
  31. import android.view.View;
  32. import android.widget.Button;
  33. import android.widget.TextView;
  34. import com.nextcloud.client.account.User;
  35. import com.owncloud.android.R;
  36. import com.owncloud.android.datamodel.ArbitraryDataProvider;
  37. import com.owncloud.android.lib.common.accounts.AccountUtils;
  38. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  39. import com.owncloud.android.lib.common.utils.Log_OC;
  40. import com.owncloud.android.lib.resources.users.DeletePublicKeyOperation;
  41. import com.owncloud.android.lib.resources.users.GetPrivateKeyOperation;
  42. import com.owncloud.android.lib.resources.users.GetPublicKeyOperation;
  43. import com.owncloud.android.lib.resources.users.SendCSROperation;
  44. import com.owncloud.android.lib.resources.users.StorePrivateKeyOperation;
  45. import com.owncloud.android.utils.CsrHelper;
  46. import com.owncloud.android.utils.EncryptionUtils;
  47. import com.owncloud.android.utils.theme.ThemeButtonUtils;
  48. import com.owncloud.android.utils.theme.ThemeColorUtils;
  49. import java.io.IOException;
  50. import java.security.KeyPair;
  51. import java.security.PrivateKey;
  52. import java.util.Arrays;
  53. import java.util.List;
  54. import java.util.Locale;
  55. import androidx.annotation.NonNull;
  56. import androidx.annotation.VisibleForTesting;
  57. import androidx.appcompat.app.AlertDialog;
  58. import androidx.core.graphics.drawable.DrawableCompat;
  59. import androidx.fragment.app.DialogFragment;
  60. import static com.owncloud.android.utils.EncryptionUtils.decodeStringToBase64Bytes;
  61. import static com.owncloud.android.utils.EncryptionUtils.decryptStringAsymmetric;
  62. import static com.owncloud.android.utils.EncryptionUtils.encodeBytesToBase64String;
  63. import static com.owncloud.android.utils.EncryptionUtils.generateKey;
  64. /*
  65. * Dialog to setup encryption
  66. */
  67. public class SetupEncryptionDialogFragment extends DialogFragment {
  68. public static final String SUCCESS = "SUCCESS";
  69. public static final int SETUP_ENCRYPTION_RESULT_CODE = 101;
  70. public static final int SETUP_ENCRYPTION_REQUEST_CODE = 100;
  71. public static final String SETUP_ENCRYPTION_DIALOG_TAG = "SETUP_ENCRYPTION_DIALOG_TAG";
  72. public static final String ARG_POSITION = "ARG_POSITION";
  73. private static final String ARG_USER = "ARG_USER";
  74. private static final String TAG = SetupEncryptionDialogFragment.class.getSimpleName();
  75. private static final String KEY_CREATED = "KEY_CREATED";
  76. private static final String KEY_EXISTING_USED = "KEY_EXISTING_USED";
  77. private static final String KEY_FAILED = "KEY_FAILED";
  78. private static final String KEY_GENERATE = "KEY_GENERATE";
  79. private User user;
  80. private TextView textView;
  81. private TextView passphraseTextView;
  82. private ArbitraryDataProvider arbitraryDataProvider;
  83. private Button positiveButton;
  84. private Button neutralButton;
  85. private DownloadKeysAsyncTask task;
  86. private TextView passwordField;
  87. private String keyResult;
  88. private List<String> keyWords;
  89. /**
  90. * Public factory method to create new SetupEncryptionDialogFragment instance
  91. *
  92. * @return Dialog ready to show.
  93. */
  94. public static SetupEncryptionDialogFragment newInstance(User user, int position) {
  95. SetupEncryptionDialogFragment fragment = new SetupEncryptionDialogFragment();
  96. Bundle args = new Bundle();
  97. args.putParcelable(ARG_USER, user);
  98. args.putInt(ARG_POSITION, position);
  99. fragment.setArguments(args);
  100. return fragment;
  101. }
  102. @Override
  103. public void onStart() {
  104. super.onStart();
  105. AlertDialog alertDialog = (AlertDialog) getDialog();
  106. positiveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
  107. neutralButton = alertDialog.getButton(AlertDialog.BUTTON_NEUTRAL);
  108. ThemeButtonUtils.themeBorderlessButton(positiveButton,
  109. neutralButton);
  110. task = new DownloadKeysAsyncTask();
  111. task.execute();
  112. }
  113. @NonNull
  114. @Override
  115. public Dialog onCreateDialog(Bundle savedInstanceState) {
  116. int primaryColor = ThemeColorUtils.primaryColor(getContext());
  117. user = getArguments().getParcelable(ARG_USER);
  118. arbitraryDataProvider = new ArbitraryDataProvider(getContext().getContentResolver());
  119. // Inflate the layout for the dialog
  120. LayoutInflater inflater = getActivity().getLayoutInflater();
  121. // Setup layout
  122. View v = inflater.inflate(R.layout.setup_encryption_dialog, null);
  123. textView = v.findViewById(R.id.encryption_status);
  124. passphraseTextView = v.findViewById(R.id.encryption_passphrase);
  125. passwordField = v.findViewById(R.id.encryption_passwordInput);
  126. passwordField.getBackground().setColorFilter(primaryColor, PorterDuff.Mode.SRC_ATOP);
  127. Drawable wrappedDrawable = DrawableCompat.wrap(passwordField.getBackground());
  128. DrawableCompat.setTint(wrappedDrawable, primaryColor);
  129. passwordField.setBackgroundDrawable(wrappedDrawable);
  130. return createDialog(v);
  131. }
  132. @NonNull
  133. private Dialog createDialog(View v) {
  134. AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
  135. builder.setView(v).setPositiveButton(R.string.common_ok, null)
  136. .setNeutralButton(R.string.common_cancel, null)
  137. .setTitle(R.string.end_to_end_encryption_title);
  138. Dialog dialog = builder.create();
  139. dialog.setCanceledOnTouchOutside(false);
  140. dialog.setOnShowListener(new DialogInterface.OnShowListener() {
  141. @Override
  142. public void onShow(final DialogInterface dialog) {
  143. Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
  144. button.setOnClickListener(new View.OnClickListener() {
  145. @Override
  146. public void onClick(View view) {
  147. switch (keyResult) {
  148. case KEY_CREATED:
  149. Log_OC.d(TAG, "New keys generated and stored.");
  150. dialog.dismiss();
  151. Intent intentCreated = new Intent();
  152. intentCreated.putExtra(SUCCESS, true);
  153. intentCreated.putExtra(ARG_POSITION, getArguments().getInt(ARG_POSITION));
  154. getTargetFragment().onActivityResult(getTargetRequestCode(),
  155. SETUP_ENCRYPTION_RESULT_CODE, intentCreated);
  156. break;
  157. case KEY_EXISTING_USED:
  158. Log_OC.d(TAG, "Decrypt private key");
  159. textView.setText(R.string.end_to_end_encryption_decrypting);
  160. try {
  161. String privateKey = task.get();
  162. String mnemonicUnchanged = passwordField.getText().toString();
  163. String mnemonic = passwordField.getText().toString().replaceAll("\\s", "")
  164. .toLowerCase(Locale.ROOT);
  165. String decryptedPrivateKey = EncryptionUtils.decryptPrivateKey(privateKey,
  166. mnemonic);
  167. arbitraryDataProvider.storeOrUpdateKeyValue(user.getAccountName(),
  168. EncryptionUtils.PRIVATE_KEY, decryptedPrivateKey);
  169. dialog.dismiss();
  170. Log_OC.d(TAG, "Private key successfully decrypted and stored");
  171. arbitraryDataProvider.storeOrUpdateKeyValue(user.getAccountName(),
  172. EncryptionUtils.MNEMONIC,
  173. mnemonicUnchanged);
  174. // check if private key and public key match
  175. String publicKey = arbitraryDataProvider.getValue(user.getAccountName(),
  176. EncryptionUtils.PUBLIC_KEY);
  177. byte[] key1 = generateKey();
  178. String base64encodedKey = encodeBytesToBase64String(key1);
  179. String encryptedString = EncryptionUtils.encryptStringAsymmetric(base64encodedKey,
  180. publicKey);
  181. String decryptedString = decryptStringAsymmetric(encryptedString,
  182. decryptedPrivateKey);
  183. byte[] key2 = decodeStringToBase64Bytes(decryptedString);
  184. if (!Arrays.equals(key1, key2)) {
  185. throw new Exception("Keys do not match");
  186. }
  187. Intent intentExisting = new Intent();
  188. intentExisting.putExtra(SUCCESS, true);
  189. intentExisting.putExtra(ARG_POSITION, getArguments().getInt(ARG_POSITION));
  190. getTargetFragment().onActivityResult(getTargetRequestCode(),
  191. SETUP_ENCRYPTION_RESULT_CODE, intentExisting);
  192. } catch (Exception e) {
  193. textView.setText(R.string.end_to_end_encryption_wrong_password);
  194. Log_OC.d(TAG, "Error while decrypting private key: " + e.getMessage());
  195. }
  196. break;
  197. case KEY_GENERATE:
  198. passphraseTextView.setVisibility(View.GONE);
  199. positiveButton.setVisibility(View.GONE);
  200. neutralButton.setVisibility(View.GONE);
  201. getDialog().setTitle(R.string.end_to_end_encryption_storing_keys);
  202. GenerateNewKeysAsyncTask newKeysTask = new GenerateNewKeysAsyncTask();
  203. newKeysTask.execute();
  204. break;
  205. default:
  206. dialog.dismiss();
  207. break;
  208. }
  209. }
  210. });
  211. }
  212. });
  213. return dialog;
  214. }
  215. public class DownloadKeysAsyncTask extends AsyncTask<Void, Void, String> {
  216. @Override
  217. protected void onPreExecute() {
  218. super.onPreExecute();
  219. textView.setText(R.string.end_to_end_encryption_retrieving_keys);
  220. positiveButton.setVisibility(View.INVISIBLE);
  221. neutralButton.setVisibility(View.INVISIBLE);
  222. }
  223. @Override
  224. protected String doInBackground(Void... voids) {
  225. // fetch private/public key
  226. // if available
  227. // - store public key
  228. // - decrypt private key, store unencrypted private key in database
  229. GetPublicKeyOperation publicKeyOperation = new GetPublicKeyOperation();
  230. RemoteOperationResult publicKeyResult = publicKeyOperation.execute(user.toPlatformAccount(), getContext());
  231. if (publicKeyResult.isSuccess()) {
  232. Log_OC.d(TAG, "public key successful downloaded for " + user.getAccountName());
  233. String publicKeyFromServer = (String) publicKeyResult.getData().get(0);
  234. arbitraryDataProvider.storeOrUpdateKeyValue(user.getAccountName(),
  235. EncryptionUtils.PUBLIC_KEY,
  236. publicKeyFromServer);
  237. } else {
  238. return null;
  239. }
  240. RemoteOperationResult<com.owncloud.android.lib.ocs.responses.PrivateKey> privateKeyResult =
  241. new GetPrivateKeyOperation().execute(user.toPlatformAccount(), getContext());
  242. if (privateKeyResult.isSuccess()) {
  243. Log_OC.d(TAG, "private key successful downloaded for " + user.getAccountName());
  244. keyResult = KEY_EXISTING_USED;
  245. return privateKeyResult.getResultData().getKey();
  246. } else {
  247. return null;
  248. }
  249. }
  250. @Override
  251. protected void onPostExecute(String privateKey) {
  252. super.onPostExecute(privateKey);
  253. if (privateKey == null) {
  254. // first show info
  255. try {
  256. keyWords = EncryptionUtils.getRandomWords(12, requireContext());
  257. showMnemonicInfo();
  258. } catch (IOException e) {
  259. textView.setText(R.string.common_error);
  260. }
  261. } else if (!privateKey.isEmpty()) {
  262. textView.setText(R.string.end_to_end_encryption_enter_password);
  263. passwordField.setVisibility(View.VISIBLE);
  264. positiveButton.setVisibility(View.VISIBLE);
  265. } else {
  266. Log_OC.e(TAG, "Got empty private key string");
  267. }
  268. }
  269. }
  270. public class GenerateNewKeysAsyncTask extends AsyncTask<Void, Void, String> {
  271. @Override
  272. protected void onPreExecute() {
  273. super.onPreExecute();
  274. textView.setText(R.string.end_to_end_encryption_generating_keys);
  275. }
  276. @Override
  277. protected String doInBackground(Void... voids) {
  278. // - create CSR, push to server, store returned public key in database
  279. // - encrypt private key, push key to server, store unencrypted private key in database
  280. try {
  281. String publicKey;
  282. // Create public/private key pair
  283. KeyPair keyPair = EncryptionUtils.generateKeyPair();
  284. // create CSR
  285. AccountManager accountManager = AccountManager.get(getContext());
  286. String userId = accountManager.getUserData(user.toPlatformAccount(), AccountUtils.Constants.KEY_USER_ID);
  287. String urlEncoded = CsrHelper.generateCsrPemEncodedString(keyPair, userId);
  288. SendCSROperation operation = new SendCSROperation(urlEncoded);
  289. RemoteOperationResult result = operation.execute(user.toPlatformAccount(), getContext());
  290. if (result.isSuccess()) {
  291. Log_OC.d(TAG, "public key success");
  292. publicKey = (String) result.getData().get(0);
  293. } else {
  294. keyResult = KEY_FAILED;
  295. return "";
  296. }
  297. PrivateKey privateKey = keyPair.getPrivate();
  298. String privateKeyString = EncryptionUtils.encodeBytesToBase64String(privateKey.getEncoded());
  299. String privatePemKeyString = EncryptionUtils.privateKeyToPEM(privateKey);
  300. String encryptedPrivateKey = EncryptionUtils.encryptPrivateKey(privatePemKeyString,
  301. generateMnemonicString(false));
  302. // upload encryptedPrivateKey
  303. StorePrivateKeyOperation storePrivateKeyOperation = new StorePrivateKeyOperation(encryptedPrivateKey);
  304. RemoteOperationResult storePrivateKeyResult = storePrivateKeyOperation.execute(user.toPlatformAccount(),
  305. getContext());
  306. if (storePrivateKeyResult.isSuccess()) {
  307. Log_OC.d(TAG, "private key success");
  308. arbitraryDataProvider.storeOrUpdateKeyValue(user.getAccountName(), EncryptionUtils.PRIVATE_KEY,
  309. privateKeyString);
  310. arbitraryDataProvider.storeOrUpdateKeyValue(user.getAccountName(), EncryptionUtils.PUBLIC_KEY, publicKey);
  311. arbitraryDataProvider.storeOrUpdateKeyValue(user.getAccountName(), EncryptionUtils.MNEMONIC,
  312. generateMnemonicString(true));
  313. keyResult = KEY_CREATED;
  314. return (String) storePrivateKeyResult.getData().get(0);
  315. } else {
  316. DeletePublicKeyOperation deletePublicKeyOperation = new DeletePublicKeyOperation();
  317. deletePublicKeyOperation.execute(user.toPlatformAccount(), getContext());
  318. }
  319. } catch (Exception e) {
  320. Log_OC.e(TAG, e.getMessage());
  321. }
  322. keyResult = KEY_FAILED;
  323. return "";
  324. }
  325. @Override
  326. protected void onPostExecute(String s) {
  327. super.onPostExecute(s);
  328. if (s.isEmpty()) {
  329. errorSavingKeys();
  330. } else {
  331. requireDialog().dismiss();
  332. Intent intentExisting = new Intent();
  333. intentExisting.putExtra(SUCCESS, true);
  334. intentExisting.putExtra(ARG_POSITION, requireArguments().getInt(ARG_POSITION));
  335. getTargetFragment().onActivityResult(getTargetRequestCode(),
  336. SETUP_ENCRYPTION_RESULT_CODE, intentExisting);
  337. }
  338. }
  339. }
  340. private String generateMnemonicString(boolean withWhitespace) {
  341. StringBuilder stringBuilder = new StringBuilder();
  342. for (String string : keyWords) {
  343. stringBuilder.append(string);
  344. if (withWhitespace) {
  345. stringBuilder.append(' ');
  346. }
  347. }
  348. return stringBuilder.toString();
  349. }
  350. @VisibleForTesting
  351. public void showMnemonicInfo() {
  352. requireDialog().setTitle(R.string.end_to_end_encryption_passphrase_title);
  353. textView.setText(R.string.end_to_end_encryption_keywords_description);
  354. passphraseTextView.setText(generateMnemonicString(true));
  355. passphraseTextView.setVisibility(View.VISIBLE);
  356. positiveButton.setText(R.string.end_to_end_encryption_confirm_button);
  357. positiveButton.setVisibility(View.VISIBLE);
  358. neutralButton.setVisibility(View.VISIBLE);
  359. ThemeButtonUtils.themeBorderlessButton(positiveButton, neutralButton);
  360. keyResult = KEY_GENERATE;
  361. }
  362. @VisibleForTesting
  363. public void errorSavingKeys() {
  364. keyResult = KEY_FAILED;
  365. requireDialog().setTitle(R.string.common_error);
  366. textView.setText(R.string.end_to_end_encryption_unsuccessful);
  367. positiveButton.setText(R.string.end_to_end_encryption_dialog_close);
  368. positiveButton.setVisibility(View.VISIBLE);
  369. positiveButton.setTextColor(ThemeColorUtils.primaryAccentColor(getContext()));
  370. }
  371. @VisibleForTesting
  372. public void setMnemonic(List<String> keyWords) {
  373. this.keyWords = keyWords;
  374. }
  375. }