Add backup API

This commit is contained in:
Dominik Schürmann 2016-02-16 00:36:27 +01:00
parent 067d5fd0b0
commit a2dcb579ff
12 changed files with 222 additions and 32 deletions

View file

@ -859,6 +859,10 @@
android:name=".remote.ui.RemoteImportKeysActivity"
android:configChanges="orientation|screenSize|keyboardHidden|keyboard"
android:label="@string/title_import_keys" />
<activity
android:name=".remote.ui.RemoteBackupActivity"
android:configChanges="keyboardHidden|keyboard"
android:label="@string/title_backup" />
<!-- DEPRECATED service,
using this service may lead to truncated data being returned to the caller -->

View file

@ -20,6 +20,7 @@ package org.sufficientlysecure.keychain.operations;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
@ -97,6 +98,12 @@ public class BackupOperation extends BaseOperation<BackupKeyringParcel> {
@NonNull
public ExportResult execute(@NonNull BackupKeyringParcel backupInput, @Nullable CryptoInputParcel cryptoInput) {
return execute(backupInput, cryptoInput, null);
}
@NonNull
public ExportResult execute(@NonNull BackupKeyringParcel backupInput, @Nullable CryptoInputParcel cryptoInput,
OutputStream outputStream) {
OperationLog log = new OperationLog();
if (backupInput.mMasterKeyIds != null) {
@ -107,18 +114,23 @@ public class BackupOperation extends BaseOperation<BackupKeyringParcel> {
try {
boolean nonEncryptedOutput = backupInput.mSymmetricPassphrase == null;
boolean nonEncryptedOutput = cryptoInput == null;
Uri backupOutputUri = nonEncryptedOutput
? backupInput.mOutputUri
: TemporaryFileProvider.createFile(mContext);
Uri plainUri = null;
OutputStream plainOut;
if (nonEncryptedOutput && backupInput.mOutputUri == null) {
plainOut = outputStream;
} else if (nonEncryptedOutput) {
plainOut = mContext.getContentResolver().openOutputStream(backupInput.mOutputUri);
} else {
plainUri = TemporaryFileProvider.createFile(mContext);
plainOut = mContext.getContentResolver().openOutputStream(plainUri);
}
int exportedDataSize;
{ // export key data, and possibly return if we don't encrypt
DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(
mContext.getContentResolver().openOutputStream(backupOutputUri)));
DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(plainOut));
boolean backupSuccess = exportKeysToStream(
log, backupInput.mMasterKeyIds, backupInput.mExportSecret, outStream);
@ -140,11 +152,11 @@ public class BackupOperation extends BaseOperation<BackupKeyringParcel> {
PgpSignEncryptOperation pseOp = new PgpSignEncryptOperation(mContext, mProviderHelper, mProgressable, mCancelled);
PgpSignEncryptInputParcel inputParcel = new PgpSignEncryptInputParcel();
inputParcel.setSymmetricPassphrase(backupInput.mSymmetricPassphrase);
inputParcel.setSymmetricPassphrase(cryptoInput.getPassphrase());
inputParcel.setEnableAsciiArmorOutput(true);
inputParcel.setAddBackupHeader(true);
InputStream inStream = mContext.getContentResolver().openInputStream(backupOutputUri);
InputStream inStream = mContext.getContentResolver().openInputStream(plainUri);
String filename;
if (backupInput.mMasterKeyIds != null && backupInput.mMasterKeyIds.length == 1) {
@ -156,7 +168,12 @@ public class BackupOperation extends BaseOperation<BackupKeyringParcel> {
InputData inputData = new InputData(inStream, exportedDataSize, filename);
OutputStream outStream = mContext.getContentResolver().openOutputStream(backupInput.mOutputUri);
OutputStream outStream;
if (backupInput.mOutputUri == null) {
outStream = outputStream;
} else {
outStream = mContext.getContentResolver().openOutputStream(backupInput.mOutputUri);
}
outStream = new BufferedOutputStream(outStream);
PgpSignEncryptResult encryptResult = pseOp.execute(inputParcel, new CryptoInputParcel(), inputData, outStream);

View file

@ -23,6 +23,7 @@ import android.content.Intent;
import android.os.Build;
import org.sufficientlysecure.keychain.provider.KeychainContract;
import org.sufficientlysecure.keychain.remote.ui.RemoteBackupActivity;
import org.sufficientlysecure.keychain.remote.ui.RemoteCreateAccountActivity;
import org.sufficientlysecure.keychain.remote.ui.RemoteErrorActivity;
import org.sufficientlysecure.keychain.remote.ui.RemoteImportKeysActivity;
@ -124,6 +125,14 @@ public class ApiPendingIntentFactory {
return createInternal(data, intent);
}
PendingIntent createBackupPendingIntent(Intent data, long[] masterKeyIds, boolean backupSecret) {
Intent intent = new Intent(mContext, RemoteBackupActivity.class);
intent.putExtra(RemoteBackupActivity.EXTRA_MASTER_KEY_IDS, masterKeyIds);
intent.putExtra(RemoteBackupActivity.EXTRA_SECRET, backupSecret);
return createInternal(data, intent);
}
@Deprecated
PendingIntent createAccountCreationPendingIntent(Intent data, String packageName, String accountName) {
Intent intent = new Intent(mContext, RemoteCreateAccountActivity.class);

View file

@ -37,7 +37,10 @@ import org.sufficientlysecure.keychain.util.Log;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* This service caches CryptoInputParcels, which contain sensitive data like passphrases.
* This way, they are not exposed to the client app using the API.
*/
public class CryptoInputParcelCacheService extends Service {
public static final String ACTION_ADD = Constants.INTENT_PREFIX + "ADD";

View file

@ -37,7 +37,9 @@ import org.openintents.openpgp.OpenPgpMetadata;
import org.openintents.openpgp.OpenPgpSignatureResult;
import org.openintents.openpgp.util.OpenPgpApi;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.operations.BackupOperation;
import org.sufficientlysecure.keychain.operations.results.DecryptVerifyResult;
import org.sufficientlysecure.keychain.operations.results.ExportResult;
import org.sufficientlysecure.keychain.operations.results.OperationResult.LogEntryParcel;
import org.sufficientlysecure.keychain.operations.results.PgpSignEncryptResult;
import org.sufficientlysecure.keychain.pgp.CanonicalizedPublicKeyRing;
@ -52,6 +54,7 @@ import org.sufficientlysecure.keychain.provider.KeychainContract.ApiAccounts;
import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings;
import org.sufficientlysecure.keychain.provider.KeychainDatabase.Tables;
import org.sufficientlysecure.keychain.provider.ProviderHelper;
import org.sufficientlysecure.keychain.service.BackupKeyringParcel;
import org.sufficientlysecure.keychain.service.input.CryptoInputParcel;
import org.sufficientlysecure.keychain.service.input.RequiredInputParcel;
import org.sufficientlysecure.keychain.util.InputData;
@ -670,6 +673,49 @@ public class OpenPgpService extends Service {
}
}
private Intent backupImpl(Intent data, OutputStream outputStream) {
try {
long[] masterKeyIds = data.getLongArrayExtra(OpenPgpApi.EXTRA_KEY_IDS);
boolean backupSecret = data.getBooleanExtra(OpenPgpApi.EXTRA_BACKUP_SECRET, false);
ApiPendingIntentFactory piFactory = new ApiPendingIntentFactory(getBaseContext());
CryptoInputParcel inputParcel = CryptoInputParcelCacheService.getCryptoInputParcel(this, data);
if (inputParcel == null) {
Intent result = new Intent();
result.putExtra(OpenPgpApi.RESULT_INTENT, piFactory.createBackupPendingIntent(data, masterKeyIds, backupSecret));
result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED);
return result;
}
// after user interaction with RemoteBackupActivity,
// the backup code is cached in CryptoInputParcelCacheService, now we can proceed
BackupKeyringParcel input = new BackupKeyringParcel(masterKeyIds, backupSecret, null);
BackupOperation op = new BackupOperation(this, mProviderHelper, null);
ExportResult pgpResult = op.execute(input, inputParcel, outputStream);
if (pgpResult.success()) {
Intent result = new Intent();
result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS);
return result;
} else {
// should not happen normally...
String errorMsg = getString(pgpResult.getLog().getLast().mType.getMsgId());
Intent result = new Intent();
result.putExtra(OpenPgpApi.RESULT_ERROR, new OpenPgpError(OpenPgpError.GENERIC_ERROR, errorMsg));
result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR);
return result;
}
} catch (Exception e) {
Log.d(Constants.TAG, "backupImpl", e);
Intent result = new Intent();
result.putExtra(OpenPgpApi.RESULT_ERROR,
new OpenPgpError(OpenPgpError.GENERIC_ERROR, e.getMessage()));
result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR);
return result;
}
}
private Intent getSignKeyMasterId(Intent data) {
// NOTE: Accounts are deprecated on API version >= 7
if (data.getIntExtra(OpenPgpApi.EXTRA_API_VERSION, -1) < 7) {
@ -831,6 +877,9 @@ public class OpenPgpService extends Service {
case OpenPgpApi.ACTION_GET_KEY: {
return getKeyImpl(data, outputStream);
}
case OpenPgpApi.ACTION_BACKUP: {
return backupImpl(data, outputStream);
}
default: {
return null;
}

View file

@ -0,0 +1,73 @@
/*
* Copyright (C) 2016 Dominik Schürmann <dominik@dominikschuermann.de>
*
* 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 org.sufficientlysecure.keychain.remote.ui;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.remote.CryptoInputParcelCacheService;
import org.sufficientlysecure.keychain.service.input.CryptoInputParcel;
import org.sufficientlysecure.keychain.ui.BackupActivity;
import org.sufficientlysecure.keychain.ui.BackupCodeFragment;
public class RemoteBackupActivity extends BackupActivity {
public static final String EXTRA_DATA = "data";
private Intent mPendingIntentData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// noinspection ConstantConditions, we know this activity has an action bar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (savedInstanceState == null) {
Intent intent = getIntent();
boolean exportSecret = intent.getBooleanExtra(EXTRA_SECRET, false);
long[] masterKeyIds = intent.getLongArrayExtra(EXTRA_MASTER_KEY_IDS);
mPendingIntentData = getIntent().getParcelableExtra(EXTRA_DATA);
// NOTE: return backup!
Fragment frag = BackupCodeFragment.newInstance(masterKeyIds, exportSecret, false);
FragmentManager fragMan = getSupportFragmentManager();
fragMan.beginTransaction()
.setCustomAnimations(0, 0)
.replace(R.id.content_frame, frag)
.commit();
}
}
@Override
public void handleBackupOperation(CryptoInputParcel inputParcel) {
// instead of handling the operation here directly,
// cache inputParcel containing the backup code and return to client
// Next time, the actual operation is directly executed.
CryptoInputParcelCacheService.addCryptoInputParcel(this, mPendingIntentData, inputParcel);
setResult(RESULT_OK, mPendingIntentData);
finish();
}
}

View file

@ -39,7 +39,7 @@ public class RemoteImportKeysActivity extends ImportKeysActivity {
}
@Override
public void handleResult(ImportKeyResult result) {
protected void handleResult(ImportKeyResult result) {
setResult(RESULT_OK, mPendingIntentData);
finish();
}

View file

@ -28,15 +28,12 @@ import org.sufficientlysecure.keychain.util.Passphrase;
public class BackupKeyringParcel implements Parcelable {
public Uri mCanonicalizedPublicKeyringUri;
public Passphrase mSymmetricPassphrase;
public boolean mExportSecret;
public long mMasterKeyIds[];
public Uri mOutputUri;
public BackupKeyringParcel(Passphrase symmetricPassphrase,
long[] masterKeyIds, boolean exportSecret, Uri outputUri) {
mSymmetricPassphrase = symmetricPassphrase;
public BackupKeyringParcel(long[] masterKeyIds, boolean exportSecret, Uri outputUri) {
mMasterKeyIds = masterKeyIds;
mExportSecret = exportSecret;
mOutputUri = outputUri;
@ -47,7 +44,6 @@ public class BackupKeyringParcel implements Parcelable {
mExportSecret = in.readByte() != 0x00;
mOutputUri = (Uri) in.readValue(Uri.class.getClassLoader());
mMasterKeyIds = in.createLongArray();
mSymmetricPassphrase = in.readParcelable(getClass().getClassLoader());
}
@Override
@ -61,7 +57,6 @@ public class BackupKeyringParcel implements Parcelable {
dest.writeByte((byte) (mExportSecret ? 0x01 : 0x00));
dest.writeValue(mOutputUri);
dest.writeLongArray(mMasterKeyIds);
dest.writeParcelable(mSymmetricPassphrase, 0);
}
public static final Parcelable.Creator<BackupKeyringParcel> CREATOR = new Parcelable.Creator<BackupKeyringParcel>() {

View file

@ -24,6 +24,7 @@ import android.support.v4.app.FragmentManager;
import android.view.MenuItem;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.service.input.CryptoInputParcel;
import org.sufficientlysecure.keychain.ui.base.BaseActivity;
@ -49,7 +50,7 @@ public class BackupActivity extends BaseActivity {
boolean exportSecret = intent.getBooleanExtra(EXTRA_SECRET, false);
long[] masterKeyIds = intent.getLongArrayExtra(EXTRA_MASTER_KEY_IDS);
Fragment frag = BackupCodeFragment.newInstance(masterKeyIds, exportSecret);
Fragment frag = BackupCodeFragment.newInstance(masterKeyIds, exportSecret, true);
FragmentManager fragMan = getSupportFragmentManager();
fragMan.beginTransaction()
@ -74,4 +75,11 @@ public class BackupActivity extends BaseActivity {
return super.onOptionsItemSelected(item);
}
/**
* Overridden in RemoteBackupActivity
*/
public void handleBackupOperation(CryptoInputParcel inputParcel) {
// only used for RemoteBackupActivity
}
}

View file

@ -32,8 +32,10 @@ import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
@ -62,6 +64,7 @@ import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.operations.results.ExportResult;
import org.sufficientlysecure.keychain.provider.TemporaryFileProvider;
import org.sufficientlysecure.keychain.service.BackupKeyringParcel;
import org.sufficientlysecure.keychain.service.input.CryptoInputParcel;
import org.sufficientlysecure.keychain.ui.base.CryptoOperationFragment;
import org.sufficientlysecure.keychain.ui.util.Notify;
import org.sufficientlysecure.keychain.ui.util.Notify.ActionListener;
@ -76,6 +79,7 @@ public class BackupCodeFragment extends CryptoOperationFragment<BackupKeyringPar
public static final String ARG_BACKUP_CODE = "backup_code";
public static final String BACK_STACK_INPUT = "state_display";
public static final String ARG_EXPORT_SECRET = "export_secret";
public static final String ARG_EXECUTE_BACKUP_OPERATION = "execute_backup_operation";
public static final String ARG_MASTER_KEY_IDS = "master_key_ids";
public static final String ARG_CURRENT_STATE = "current_state";
@ -94,6 +98,7 @@ public class BackupCodeFragment extends CryptoOperationFragment<BackupKeyringPar
private boolean mExportSecret;
private long[] mMasterKeyIds;
String mBackupCode;
private boolean mExecuteBackupOperation;
private MaskedEditText mCodeEditText;
@ -104,13 +109,15 @@ public class BackupCodeFragment extends CryptoOperationFragment<BackupKeyringPar
private boolean mShareNotSave;
private boolean mDebugModeAcceptAnyCode;
public static BackupCodeFragment newInstance(long[] masterKeyIds, boolean exportSecret) {
public static BackupCodeFragment newInstance(long[] masterKeyIds, boolean exportSecret,
boolean executeBackupOperation) {
BackupCodeFragment frag = new BackupCodeFragment();
Bundle args = new Bundle();
args.putString(ARG_BACKUP_CODE, generateRandomBackupCode());
args.putLongArray(ARG_MASTER_KEY_IDS, masterKeyIds);
args.putBoolean(ARG_EXPORT_SECRET, exportSecret);
args.putBoolean(ARG_EXECUTE_BACKUP_OPERATION, executeBackupOperation);
frag.setArguments(args);
return frag;
@ -198,8 +205,12 @@ public class BackupCodeFragment extends CryptoOperationFragment<BackupKeyringPar
case STATE_OK: {
mTitleAnimator.setDisplayedChild(2, animate);
mStatusAnimator.setDisplayedChild(3, animate);
mCodeFieldsAnimator.setDisplayedChild(1, false);
if (mExecuteBackupOperation) {
mStatusAnimator.setDisplayedChild(3, animate);
} else {
mStatusAnimator.setDisplayedChild(1, animate);
}
hideKeyboard();
@ -215,6 +226,18 @@ public class BackupCodeFragment extends CryptoOperationFragment<BackupKeyringPar
popBackStackNoAction();
// special case for remote API, see RemoteBackupActivity
if (!mExecuteBackupOperation) {
// wait for animation to finish...
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
startBackup();
}
}, 2000);
}
break;
}
@ -232,6 +255,7 @@ public class BackupCodeFragment extends CryptoOperationFragment<BackupKeyringPar
mBackupCode = args.getString(ARG_BACKUP_CODE);
mMasterKeyIds = args.getLongArray(ARG_MASTER_KEY_IDS);
mExportSecret = args.getBoolean(ARG_EXPORT_SECRET);
mExecuteBackupOperation = args.getBoolean(ARG_EXECUTE_BACKUP_OPERATION, true);
// NOTE: order of these method calls matter, see setupAutomaticLinebreak()
mCodeEditText = (MaskedEditText) view.findViewById(R.id.backup_code_input);
@ -436,10 +460,22 @@ public class BackupCodeFragment extends CryptoOperationFragment<BackupKeyringPar
+ (mExportSecret ? Constants.FILE_EXTENSION_ENCRYPTED_BACKUP_SECRET
: Constants.FILE_EXTENSION_ENCRYPTED_BACKUP_PUBLIC);
Passphrase passphrase = new Passphrase(mBackupCode);
if (Constants.DEBUG && mDebugModeAcceptAnyCode) {
passphrase = new Passphrase("AAAA-AAAA-AAAA-AAAA-AAAA-AAAA");
}
// if we don't want to execute the actual operation outside of this activity, drop out here
if (!mExecuteBackupOperation) {
((BackupActivity) getActivity()).handleBackupOperation(new CryptoInputParcel(passphrase));
return;
}
if (mCachedBackupUri == null) {
mCachedBackupUri = TemporaryFileProvider.createFile(activity, filename,
Constants.MIME_TYPE_ENCRYPTED_ALTERNATE);
cryptoOperation();
cryptoOperation(new CryptoInputParcel(passphrase));
return;
}
@ -513,11 +549,7 @@ public class BackupCodeFragment extends CryptoOperationFragment<BackupKeyringPar
@Nullable
@Override
public BackupKeyringParcel createOperationInput() {
Passphrase passphrase = new Passphrase(mBackupCode);
if (Constants.DEBUG && mDebugModeAcceptAnyCode) {
passphrase = new Passphrase("AAAA-AAAA-AAAA-AAAA-AAAA-AAAA");
}
return new BackupKeyringParcel(passphrase, mMasterKeyIds, mExportSecret, mCachedBackupUri);
return new BackupKeyringParcel(mMasterKeyIds, mExportSecret, mCachedBackupUri);
}
@Override

View file

@ -254,7 +254,7 @@ public class ExportTest {
BackupOperation op = new BackupOperation(spyApplication,
new ProviderHelper(RuntimeEnvironment.application), null);
BackupKeyringParcel parcel = new BackupKeyringParcel(null,
BackupKeyringParcel parcel = new BackupKeyringParcel(
new long[] { mStaticRing1.getMasterKeyId() }, false, fakeOutputUri);
ExportResult result = op.execute(parcel, null);
@ -313,10 +313,10 @@ public class ExportTest {
BackupOperation op = new BackupOperation(spyApplication,
new ProviderHelper(RuntimeEnvironment.application), null);
BackupKeyringParcel parcel = new BackupKeyringParcel(passphrase,
BackupKeyringParcel parcel = new BackupKeyringParcel(
new long[] { mStaticRing1.getMasterKeyId() }, false, fakeOutputUri);
ExportResult result = op.execute(parcel, null);
CryptoInputParcel inputParcel = new CryptoInputParcel(passphrase);
ExportResult result = op.execute(parcel, inputParcel);
verify(mockResolver).openOutputStream(fakePipedUri);
verify(mockResolver).openInputStream(fakePipedUri);

@ -1 +1 @@
Subproject commit 075616c461f5ce2bd76a4078c31a51a6ee6b8605
Subproject commit 29a7c77e4757239ae861792dd51d75987940f4e4