aboutsummaryrefslogtreecommitdiffstats
path: root/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/operations/BackupOperation.java
blob: 1e6de9c9fcb0291eb72df63af59b63594ba11abf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
/*
 * Copyright (C) 2012-2014 Dominik Schürmann <dominik@dominikschuermann.de>
 * Copyright (C) 2010-2014 Thialfihar <thi@thialfihar.org>
 *
 * 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.operations;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import org.bouncycastle.bcpg.ArmoredOutputStream;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.operations.results.ExportResult;
import org.sufficientlysecure.keychain.operations.results.OperationResult.LogType;
import org.sufficientlysecure.keychain.operations.results.OperationResult.OperationLog;
import org.sufficientlysecure.keychain.operations.results.PgpSignEncryptResult;
import org.sufficientlysecure.keychain.pgp.CanonicalizedKeyRing;
import org.sufficientlysecure.keychain.pgp.PgpSignEncryptData;
import org.sufficientlysecure.keychain.pgp.PgpSignEncryptInputParcel;
import org.sufficientlysecure.keychain.pgp.PgpSignEncryptOperation;
import org.sufficientlysecure.keychain.pgp.Progressable;
import org.sufficientlysecure.keychain.pgp.UncachedKeyRing;
import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException;
import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings;
import org.sufficientlysecure.keychain.provider.KeychainDatabase.Tables;
import org.sufficientlysecure.keychain.provider.ProviderHelper;
import org.sufficientlysecure.keychain.provider.TemporaryFileProvider;
import org.sufficientlysecure.keychain.service.BackupKeyringParcel;
import org.sufficientlysecure.keychain.service.input.CryptoInputParcel;
import org.sufficientlysecure.keychain.ui.util.KeyFormattingUtils;
import org.sufficientlysecure.keychain.util.InputData;
import org.sufficientlysecure.keychain.util.Log;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * An operation class which implements high level backup
 * operations.
 * This class receives a source and/or destination of keys as input and performs
 * all steps for this backup.
 *
 * @see org.sufficientlysecure.keychain.ui.adapter.ImportKeysAdapter#getSelectedEntries()
 * For the backup operation, the input consists of a set of key ids and
 * either the name of a file or an output uri to write to.
 */
public class BackupOperation extends BaseOperation<BackupKeyringParcel> {

    private static final String[] PROJECTION = new String[]{
            KeyRings.MASTER_KEY_ID,
            KeyRings.PUBKEY_DATA,
            KeyRings.PRIVKEY_DATA,
            KeyRings.HAS_ANY_SECRET
    };
    private static final int INDEX_MASTER_KEY_ID = 0;
    private static final int INDEX_PUBKEY_DATA = 1;
    private static final int INDEX_SECKEY_DATA = 2;
    private static final int INDEX_HAS_ANY_SECRET = 3;

    public BackupOperation(Context context, ProviderHelper providerHelper, Progressable
            progressable) {
        super(context, providerHelper, progressable);
    }

    public BackupOperation(Context context, ProviderHelper providerHelper,
                           Progressable progressable, AtomicBoolean cancelled) {
        super(context, providerHelper, progressable, cancelled);
    }

    @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) {
            log.add(LogType.MSG_BACKUP, 0, backupInput.mMasterKeyIds.length);
        } else {
            log.add(LogType.MSG_BACKUP_ALL, 0);
        }

        try {

            Uri plainUri = null;
            OutputStream plainOut;
            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(plainOut));

                boolean backupSuccess = exportKeysToStream(
                        log, backupInput.mMasterKeyIds, backupInput.mExportSecret, outStream);

                exportedDataSize = outStream.size();

                if (!backupSuccess) {
                    // if there was an error, it will be in the log so we just have to return
                    return new ExportResult(ExportResult.RESULT_ERROR, log);
                }
            }

            PgpSignEncryptOperation pseOp = new PgpSignEncryptOperation(mContext, mProviderHelper, mProgressable, mCancelled);

            PgpSignEncryptData data = new PgpSignEncryptData();
            data.setSymmetricPassphrase(cryptoInput.getPassphrase());
            data.setEnableAsciiArmorOutput(true);
            data.setAddBackupHeader(true);
            PgpSignEncryptInputParcel inputParcel = new PgpSignEncryptInputParcel(data);

            InputStream inStream = mContext.getContentResolver().openInputStream(plainUri);

            String filename;
            if (backupInput.mMasterKeyIds != null && backupInput.mMasterKeyIds.length == 1) {
                filename = Constants.FILE_BACKUP_PREFIX + KeyFormattingUtils.convertKeyIdToHex(backupInput.mMasterKeyIds[0]);
            } else {
                filename = Constants.FILE_BACKUP_PREFIX + new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
            }
            filename += backupInput.mExportSecret ? Constants.FILE_EXTENSION_BACKUP_SECRET : Constants.FILE_EXTENSION_BACKUP_PUBLIC;

            InputData inputData = new InputData(inStream, exportedDataSize, filename);

            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);
            if (!encryptResult.success()) {
                log.addByMerge(encryptResult, 1);
                // log.add(LogType.MSG_EXPORT_ERROR_ENCRYPT, 1);
                return new ExportResult(ExportResult.RESULT_ERROR, log);
            }

            log.add(encryptResult, 1);
            log.add(LogType.MSG_BACKUP_SUCCESS, 1);
            return new ExportResult(ExportResult.RESULT_OK, log);

        } catch (FileNotFoundException e) {
            log.add(LogType.MSG_BACKUP_ERROR_URI_OPEN, 1);
            return new ExportResult(ExportResult.RESULT_ERROR, log);

        }

    }

    boolean exportKeysToStream(OperationLog log, long[] masterKeyIds, boolean exportSecret, OutputStream outStream) {

        // noinspection unused TODO use these in a log entry
        int okSecret = 0, okPublic = 0;

        int progress = 0;

        Cursor cursor = queryForKeys(masterKeyIds);

        if (cursor == null || !cursor.moveToFirst()) {
            log.add(LogType.MSG_BACKUP_ERROR_DB, 1);
            return false; // new ExportResult(ExportResult.RESULT_ERROR, log);
        }

        try {

            int numKeys = cursor.getCount();

            updateProgress(mContext.getResources().getQuantityString(R.plurals.progress_exporting_key, numKeys),
                    0, numKeys);

            // For each public masterKey id
            while (!cursor.isAfterLast()) {

                long keyId = cursor.getLong(INDEX_MASTER_KEY_ID);
                log.add(LogType.MSG_BACKUP_PUBLIC, 1, KeyFormattingUtils.beautifyKeyId(keyId));

                if (writePublicKeyToStream(log, outStream, cursor)) {
                    okPublic += 1;

                    boolean hasSecret = cursor.getInt(INDEX_HAS_ANY_SECRET) > 0;
                    if (exportSecret && hasSecret) {
                        log.add(LogType.MSG_BACKUP_SECRET, 2, KeyFormattingUtils.beautifyKeyId(keyId));
                        if (writeSecretKeyToStream(log, outStream, cursor)) {
                            okSecret += 1;
                        }
                    }
                }

                updateProgress(progress++, numKeys);
                cursor.moveToNext();
            }

            updateProgress(R.string.progress_done, numKeys, numKeys);

        } catch (IOException e) {
            log.add(LogType.MSG_BACKUP_ERROR_IO, 1);
            return false; // new ExportResult(ExportResult.RESULT_ERROR, log);
        } finally {
            // Make sure the stream is closed
            if (outStream != null) try {
                outStream.close();
            } catch (Exception e) {
                Log.e(Constants.TAG, "error closing stream", e);
            }
            cursor.close();
        }

        return true;

    }

    private boolean writePublicKeyToStream(OperationLog log, OutputStream outStream, Cursor cursor)
            throws IOException {

        ArmoredOutputStream arOutStream = null;

        try {
            arOutStream = new ArmoredOutputStream(outStream);
            byte[] data = cursor.getBlob(INDEX_PUBKEY_DATA);
            CanonicalizedKeyRing ring = UncachedKeyRing.decodeFromData(data).canonicalize(log, 2, true);
            ring.encode(arOutStream);

        } catch (PgpGeneralException e) {
            log.add(LogType.MSG_UPLOAD_ERROR_IO, 2);
        } finally {
            if (arOutStream != null) {
                arOutStream.close();
            }
        }
        return true;
    }

    private boolean writeSecretKeyToStream(OperationLog log, OutputStream outStream, Cursor cursor)
            throws IOException {

        ArmoredOutputStream arOutStream = null;

        try {
            arOutStream = new ArmoredOutputStream(outStream);
            byte[] data = cursor.getBlob(INDEX_SECKEY_DATA);
            CanonicalizedKeyRing ring = UncachedKeyRing.decodeFromData(data).canonicalize(log, 2, true);
            ring.encode(arOutStream);

        } catch (PgpGeneralException e) {
            log.add(LogType.MSG_UPLOAD_ERROR_IO, 2);
        } finally {
            if (arOutStream != null) {
                arOutStream.close();
            }
        }
        return true;
    }

    private Cursor queryForKeys(long[] masterKeyIds) {

        String selection = null, selectionArgs[] = null;

        if (masterKeyIds != null) {
            // convert long[] to String[]
            selectionArgs = new String[masterKeyIds.length];
            for (int i = 0; i < masterKeyIds.length; i++) {
                selectionArgs[i] = Long.toString(masterKeyIds[i]);
            }

            // generates ?,?,? as placeholders for selectionArgs
            String placeholders = TextUtils.join(",",
                    Collections.nCopies(masterKeyIds.length, "?"));

            // put together selection string
            selection = Tables.KEYS + "." + KeyRings.MASTER_KEY_ID
                    + " IN (" + placeholders + ")";
        }

        return mProviderHelper.getContentResolver().query(
                KeyRings.buildUnifiedKeyRingsUri(), PROJECTION, selection, selectionArgs,
                Tables.KEYS + "." + KeyRings.MASTER_KEY_ID
        );

    }

}