SetupEncryptionDialogFragment.java 15 KB

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