SetupEncryptionDialogFragment.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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.Account;
  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.support.annotation.NonNull;
  31. import android.support.v4.app.DialogFragment;
  32. import android.support.v4.graphics.drawable.DrawableCompat;
  33. import android.support.v7.app.AlertDialog;
  34. import android.view.LayoutInflater;
  35. import android.view.View;
  36. import android.widget.Button;
  37. import android.widget.TextView;
  38. import com.owncloud.android.R;
  39. import com.owncloud.android.datamodel.ArbitraryDataProvider;
  40. import com.owncloud.android.lib.common.UserInfo;
  41. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  42. import com.owncloud.android.lib.common.utils.Log_OC;
  43. import com.owncloud.android.lib.resources.users.DeletePublicKeyOperation;
  44. import com.owncloud.android.lib.resources.users.GetPrivateKeyOperation;
  45. import com.owncloud.android.lib.resources.users.GetPublicKeyOperation;
  46. import com.owncloud.android.lib.resources.users.GetRemoteUserInfoOperation;
  47. import com.owncloud.android.lib.resources.users.SendCSROperation;
  48. import com.owncloud.android.lib.resources.users.StorePrivateKeyOperation;
  49. import com.owncloud.android.utils.CsrHelper;
  50. import com.owncloud.android.utils.EncryptionUtils;
  51. import com.owncloud.android.utils.ThemeUtils;
  52. import java.io.IOException;
  53. import java.security.KeyPair;
  54. import java.security.PrivateKey;
  55. import java.util.ArrayList;
  56. import java.util.Locale;
  57. /*
  58. * Dialog to setup encryption
  59. */
  60. public class SetupEncryptionDialogFragment extends DialogFragment {
  61. public static final String SUCCESS = "SUCCESS";
  62. public static final int SETUP_ENCRYPTION_RESULT_CODE = 101;
  63. public static final int SETUP_ENCRYPTION_REQUEST_CODE = 100;
  64. public static final String SETUP_ENCRYPTION_DIALOG_TAG = "SETUP_ENCRYPTION_DIALOG_TAG";
  65. public static final String ARG_POSITION = "ARG_POSITION";
  66. private static String ARG_ACCOUNT = "ARG_ACCOUNT";
  67. private static String TAG = SetupEncryptionDialogFragment.class.getSimpleName();
  68. private static final String KEY_CREATED = "KEY_CREATED";
  69. private static final String KEY_EXISTING_USED = "KEY_EXISTING_USED";
  70. private static final String KEY_FAILED = "KEY_FAILED";
  71. private static final String KEY_GENERATE = "KEY_GENERATE";
  72. private Account account;
  73. private TextView textView;
  74. private TextView passphraseTextView;
  75. private ArbitraryDataProvider arbitraryDataProvider;
  76. private Button positiveButton;
  77. private Button negativeButton;
  78. private DownloadKeysAsyncTask task;
  79. private TextView passwordField;
  80. private String keyResult;
  81. private ArrayList<String> keyWords;
  82. /**
  83. * Public factory method to create new SetupEncryptionDialogFragment instance
  84. *
  85. * @return Dialog ready to show.
  86. */
  87. public static SetupEncryptionDialogFragment newInstance(Account account, int position) {
  88. SetupEncryptionDialogFragment fragment = new SetupEncryptionDialogFragment();
  89. Bundle args = new Bundle();
  90. args.putParcelable(ARG_ACCOUNT, account);
  91. args.putInt(ARG_POSITION, position);
  92. fragment.setArguments(args);
  93. return fragment;
  94. }
  95. @Override
  96. public void onStart() {
  97. super.onStart();
  98. int color = ThemeUtils.primaryAccentColor(getContext());
  99. AlertDialog alertDialog = (AlertDialog) getDialog();
  100. positiveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
  101. positiveButton.setTextColor(color);
  102. negativeButton = alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
  103. negativeButton.setTextColor(color);
  104. task = new DownloadKeysAsyncTask();
  105. task.execute();
  106. }
  107. @NonNull
  108. @Override
  109. public Dialog onCreateDialog(Bundle savedInstanceState) {
  110. int accentColor = ThemeUtils.primaryAccentColor(getContext());
  111. account = getArguments().getParcelable(ARG_ACCOUNT);
  112. arbitraryDataProvider = new ArbitraryDataProvider(getContext().getContentResolver());
  113. // Inflate the layout for the dialog
  114. LayoutInflater inflater = getActivity().getLayoutInflater();
  115. // Setup layout
  116. View v = inflater.inflate(R.layout.setup_encryption_dialog, null);
  117. textView = v.findViewById(R.id.encryption_status);
  118. passphraseTextView = v.findViewById(R.id.encryption_passphrase);
  119. passwordField = v.findViewById(R.id.encryption_passwordInput);
  120. passwordField.getBackground().setColorFilter(accentColor, PorterDuff.Mode.SRC_ATOP);
  121. Drawable wrappedDrawable = DrawableCompat.wrap(passwordField.getBackground());
  122. DrawableCompat.setTint(wrappedDrawable, accentColor);
  123. passwordField.setBackgroundDrawable(wrappedDrawable);
  124. return createDialog(accentColor, v);
  125. }
  126. @NonNull
  127. private Dialog createDialog(int accentColor, View v) {
  128. AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
  129. builder.setView(v).setPositiveButton(R.string.common_ok, null)
  130. .setNegativeButton(R.string.common_cancel, null)
  131. .setTitle(ThemeUtils.getColoredTitle(getString(R.string.end_to_end_encryption_title), accentColor));
  132. Dialog dialog = builder.create();
  133. dialog.setCanceledOnTouchOutside(false);
  134. dialog.setOnShowListener(new DialogInterface.OnShowListener() {
  135. @Override
  136. public void onShow(final DialogInterface dialog) {
  137. Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
  138. button.setOnClickListener(new View.OnClickListener() {
  139. @Override
  140. public void onClick(View view) {
  141. switch (keyResult) {
  142. case KEY_CREATED:
  143. Log_OC.d(TAG, "New keys generated and stored.");
  144. dialog.dismiss();
  145. Intent intentCreated = new Intent();
  146. intentCreated.putExtra(SUCCESS, true);
  147. intentCreated.putExtra(ARG_POSITION, getArguments().getInt(ARG_POSITION));
  148. getTargetFragment().onActivityResult(getTargetRequestCode(),
  149. SETUP_ENCRYPTION_RESULT_CODE, intentCreated);
  150. break;
  151. case KEY_EXISTING_USED:
  152. Log_OC.d(TAG, "Decrypt private key");
  153. textView.setText(R.string.end_to_end_encryption_decrypting);
  154. try {
  155. String privateKey = task.get();
  156. String decryptedPrivateKey = EncryptionUtils.decryptPrivateKey(privateKey,
  157. passwordField.getText().toString().replaceAll("\\s", "")
  158. .toLowerCase(Locale.ROOT));
  159. arbitraryDataProvider.storeOrUpdateKeyValue(account.name,
  160. EncryptionUtils.PRIVATE_KEY, decryptedPrivateKey);
  161. dialog.dismiss();
  162. Log_OC.d(TAG, "Private key successfully decrypted and stored");
  163. Intent intentExisting = new Intent();
  164. intentExisting.putExtra(SUCCESS, true);
  165. intentExisting.putExtra(ARG_POSITION, getArguments().getInt(ARG_POSITION));
  166. getTargetFragment().onActivityResult(getTargetRequestCode(),
  167. SETUP_ENCRYPTION_RESULT_CODE, intentExisting);
  168. } catch (Exception e) {
  169. textView.setText(R.string.end_to_end_encryption_wrong_password);
  170. Log_OC.d(TAG, "Error while decrypting private key: " + e.getMessage());
  171. }
  172. break;
  173. case KEY_GENERATE:
  174. passphraseTextView.setVisibility(View.GONE);
  175. positiveButton.setVisibility(View.GONE);
  176. negativeButton.setVisibility(View.GONE);
  177. getDialog().setTitle(ThemeUtils.getColoredTitle(getString(
  178. R.string.end_to_end_encryption_storing_keys),
  179. ThemeUtils.primaryColor(getContext())));
  180. GenerateNewKeysAsyncTask newKeysTask = new GenerateNewKeysAsyncTask();
  181. newKeysTask.execute();
  182. break;
  183. default:
  184. dialog.dismiss();
  185. break;
  186. }
  187. }
  188. });
  189. }
  190. });
  191. return dialog;
  192. }
  193. private class DownloadKeysAsyncTask extends AsyncTask<Void, Void, String> {
  194. @Override
  195. protected void onPreExecute() {
  196. super.onPreExecute();
  197. textView.setText(R.string.end_to_end_encryption_retrieving_keys);
  198. positiveButton.setVisibility(View.INVISIBLE);
  199. negativeButton.setVisibility(View.INVISIBLE);
  200. }
  201. @Override
  202. protected String doInBackground(Void... voids) {
  203. // fetch private/public key
  204. // if available
  205. // - store public key
  206. // - decrypt private key, store unencrypted private key in database
  207. // get user id
  208. String userID;
  209. GetRemoteUserInfoOperation remoteUserNameOperation = new GetRemoteUserInfoOperation();
  210. RemoteOperationResult remoteUserNameOperationResult = remoteUserNameOperation.execute(account,
  211. getContext(), true);
  212. if (remoteUserNameOperationResult.isSuccess() && remoteUserNameOperationResult.getData() != null) {
  213. UserInfo userInfo = (UserInfo) remoteUserNameOperationResult.getData().get(0);
  214. userID = userInfo.getId();
  215. } else {
  216. userID = account.name;
  217. }
  218. GetPublicKeyOperation publicKeyOperation = new GetPublicKeyOperation(userID);
  219. RemoteOperationResult publicKeyResult = publicKeyOperation.execute(account, getContext(), true);
  220. if (publicKeyResult.isSuccess()) {
  221. Log_OC.d(TAG, "public key successful downloaded for " + account.name);
  222. String publicKeyFromServer = (String) publicKeyResult.getData().get(0);
  223. arbitraryDataProvider.storeOrUpdateKeyValue(account.name, EncryptionUtils.PUBLIC_KEY,
  224. publicKeyFromServer);
  225. } else {
  226. return null;
  227. }
  228. GetPrivateKeyOperation privateKeyOperation = new GetPrivateKeyOperation();
  229. RemoteOperationResult privateKeyResult = privateKeyOperation.execute(account, getContext(), true);
  230. if (privateKeyResult.isSuccess()) {
  231. Log_OC.d(TAG, "private key successful downloaded for " + account.name);
  232. keyResult = KEY_EXISTING_USED;
  233. return (String) privateKeyResult.getData().get(0);
  234. } else {
  235. return null;
  236. }
  237. }
  238. @Override
  239. protected void onPostExecute(String privateKey) {
  240. super.onPostExecute(privateKey);
  241. if (privateKey == null) {
  242. // first show info
  243. try {
  244. keyWords = EncryptionUtils.getRandomWords(12, getContext());
  245. getDialog().setTitle(ThemeUtils.getColoredTitle(
  246. getString(R.string.end_to_end_encryption_passphrase_title),
  247. ThemeUtils.primaryColor(getContext())));
  248. textView.setText(R.string.end_to_end_encryption_keywords_description);
  249. StringBuilder stringBuilder = new StringBuilder();
  250. for (String string : keyWords) {
  251. stringBuilder.append(string).append(" ");
  252. }
  253. String keys = stringBuilder.toString();
  254. passphraseTextView.setText(keys);
  255. passphraseTextView.setVisibility(View.VISIBLE);
  256. positiveButton.setText(R.string.end_to_end_encryption_confirm_button);
  257. positiveButton.setVisibility(View.VISIBLE);
  258. negativeButton.setVisibility(View.VISIBLE);
  259. keyResult = KEY_GENERATE;
  260. } catch (IOException e) {
  261. textView.setText(R.string.common_error);
  262. }
  263. } else if (!privateKey.isEmpty()) {
  264. textView.setText(R.string.end_to_end_encryption_enter_password);
  265. passwordField.setVisibility(View.VISIBLE);
  266. positiveButton.setVisibility(View.VISIBLE);
  267. } else {
  268. Log_OC.e(TAG, "Got empty private key string");
  269. }
  270. }
  271. }
  272. private class GenerateNewKeysAsyncTask extends AsyncTask<Void, Void, String> {
  273. @Override
  274. protected void onPreExecute() {
  275. super.onPreExecute();
  276. textView.setText(R.string.end_to_end_encryption_generating_keys);
  277. }
  278. @Override
  279. protected String doInBackground(Void... voids) {
  280. // - create CSR, push to server, store returned public key in database
  281. // - encrypt private key, push key to server, store unencrypted private key in database
  282. try {
  283. String publicKey;
  284. // Create public/private key pair
  285. KeyPair keyPair = EncryptionUtils.generateKeyPair();
  286. PrivateKey privateKey = keyPair.getPrivate();
  287. // get user id
  288. String userID;
  289. GetRemoteUserInfoOperation remoteUserNameOperation = new GetRemoteUserInfoOperation();
  290. RemoteOperationResult remoteUserNameOperationResult = remoteUserNameOperation
  291. .execute(account, getContext(), true);
  292. if (remoteUserNameOperationResult.isSuccess() &&
  293. remoteUserNameOperationResult.getData() != null) {
  294. UserInfo userInfo = (UserInfo) remoteUserNameOperationResult.getData().get(0);
  295. userID = userInfo.getId();
  296. } else {
  297. userID = account.name;
  298. }
  299. // create CSR
  300. String urlEncoded = CsrHelper.generateCsrPemEncodedString(keyPair, userID);
  301. SendCSROperation operation = new SendCSROperation(urlEncoded);
  302. RemoteOperationResult result = operation.execute(account, getContext(), true);
  303. if (result.isSuccess()) {
  304. Log_OC.d(TAG, "public key success");
  305. publicKey = (String) result.getData().get(0);
  306. } else {
  307. keyResult = KEY_FAILED;
  308. return "";
  309. }
  310. StringBuilder stringBuilder = new StringBuilder();
  311. for (String string : keyWords) {
  312. stringBuilder.append(string);
  313. }
  314. String keyPhrase = stringBuilder.toString();
  315. String privateKeyString = EncryptionUtils.encodeBytesToBase64String(privateKey.getEncoded());
  316. String privatePemKeyString = EncryptionUtils.privateKeyToPEM(privateKey);
  317. String encryptedPrivateKey = EncryptionUtils.encryptPrivateKey(privatePemKeyString, keyPhrase);
  318. // upload encryptedPrivateKey
  319. StorePrivateKeyOperation storePrivateKeyOperation = new StorePrivateKeyOperation(encryptedPrivateKey);
  320. RemoteOperationResult storePrivateKeyResult = storePrivateKeyOperation.execute(account, getContext(),
  321. true);
  322. if (storePrivateKeyResult.isSuccess()) {
  323. Log_OC.d(TAG, "private key success");
  324. arbitraryDataProvider.storeOrUpdateKeyValue(account.name, EncryptionUtils.PRIVATE_KEY,
  325. privateKeyString);
  326. arbitraryDataProvider.storeOrUpdateKeyValue(account.name, EncryptionUtils.PUBLIC_KEY, publicKey);
  327. keyResult = KEY_CREATED;
  328. return (String) storePrivateKeyResult.getData().get(0);
  329. } else {
  330. DeletePublicKeyOperation deletePublicKeyOperation = new DeletePublicKeyOperation();
  331. deletePublicKeyOperation.execute(account, getContext(), true);
  332. }
  333. } catch (Exception e) {
  334. Log_OC.e(TAG, e.getMessage());
  335. }
  336. keyResult = KEY_FAILED;
  337. return "";
  338. }
  339. @Override
  340. protected void onPostExecute(String s) {
  341. super.onPostExecute(s);
  342. if (s.isEmpty()) {
  343. keyResult = KEY_FAILED;
  344. getDialog().setTitle(ThemeUtils.getColoredTitle(
  345. getString(R.string.common_error), ThemeUtils.primaryColor(getContext())));
  346. textView.setText(R.string.end_to_end_encryption_unsuccessful);
  347. positiveButton.setText(R.string.end_to_end_encryption_dialog_close);
  348. positiveButton.setVisibility(View.VISIBLE);
  349. } else {
  350. getDialog().dismiss();
  351. Intent intentExisting = new Intent();
  352. intentExisting.putExtra(SUCCESS, true);
  353. intentExisting.putExtra(ARG_POSITION, getArguments().getInt(ARG_POSITION));
  354. getTargetFragment().onActivityResult(getTargetRequestCode(),
  355. SETUP_ENCRYPTION_RESULT_CODE, intentExisting);
  356. }
  357. }
  358. }
  359. }