aboutsummaryrefslogtreecommitdiffstats
path: root/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpSignatureChecker.java
blob: 7421bee6c2e822ee170cb4987fd34348021cd322 (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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
/*
 * Copyright (C) 2015-2016 Dominik Schürmann <dominik@dominikschuermann.de>
 * Copyright (C) 2015-2016 Vincent Breitmoser <v.breitmoser@mugenguild.com>
 *
 * 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.pgp;


import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.SignatureException;

import org.openintents.openpgp.OpenPgpSignatureResult;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPOnePassSignature;
import org.bouncycastle.openpgp.PGPOnePassSignatureList;
import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPSignatureList;
import org.bouncycastle.openpgp.operator.jcajce.JcaPGPContentVerifierBuilderProvider;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.operations.results.OperationResult.LogType;
import org.sufficientlysecure.keychain.operations.results.OperationResult.OperationLog;
import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings;
import org.sufficientlysecure.keychain.provider.ProviderHelper;
import org.sufficientlysecure.keychain.util.Log;


/** This class is used to track the state of a single signature verification.
 *
 *
 */
class PgpSignatureChecker {

    OpenPgpSignatureResultBuilder signatureResultBuilder = new OpenPgpSignatureResultBuilder();

    private CanonicalizedPublicKey signingKey;

    private int signatureIndex;
    PGPOnePassSignature onePassSignature;
    PGPSignature signature;

    ProviderHelper mProviderHelper;

    PgpSignatureChecker(ProviderHelper providerHelper) {
        mProviderHelper = providerHelper;
    }

    boolean initializeSignature(Object dataChunk, OperationLog log, int indent) throws PGPException {

        if (!(dataChunk instanceof PGPSignatureList)) {
            return false;
        }

        PGPSignatureList sigList = (PGPSignatureList) dataChunk;
        findAvailableSignature(sigList);

        if (signingKey != null) {

            // key found in our database!
            signatureResultBuilder.initValid(signingKey);

            JcaPGPContentVerifierBuilderProvider contentVerifierBuilderProvider =
                    new JcaPGPContentVerifierBuilderProvider()
                            .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME);
            signature.init(contentVerifierBuilderProvider, signingKey.getPublicKey());
            checkKeySecurity(log, indent);


        } else if (!sigList.isEmpty()) {

            signatureResultBuilder.setSignatureAvailable(true);
            signatureResultBuilder.setKnownKey(false);
            signatureResultBuilder.setKeyId(sigList.get(0).getKeyID());

        }

        return true;

    }

    boolean initializeOnePassSignature(Object dataChunk, OperationLog log, int indent) throws PGPException {

        if (!(dataChunk instanceof PGPOnePassSignatureList)) {
            return false;
        }

        log.add(LogType.MSG_DC_CLEAR_SIGNATURE, indent + 1);

        PGPOnePassSignatureList sigList = (PGPOnePassSignatureList) dataChunk;
        findAvailableSignature(sigList);

        if (signingKey != null) {

            // key found in our database!
            signatureResultBuilder.initValid(signingKey);

            JcaPGPContentVerifierBuilderProvider contentVerifierBuilderProvider =
                    new JcaPGPContentVerifierBuilderProvider()
                            .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME);
            onePassSignature.init(contentVerifierBuilderProvider, signingKey.getPublicKey());

            checkKeySecurity(log, indent);

        } else if (!sigList.isEmpty()) {

            signatureResultBuilder.setSignatureAvailable(true);
            signatureResultBuilder.setKnownKey(false);
            signatureResultBuilder.setKeyId(sigList.get(0).getKeyID());

        }

        return true;

    }

    private void checkKeySecurity(OperationLog log, int indent) {
        // TODO: checks on signingRing ?
        if (!PgpSecurityConstants.isSecureKey(signingKey)) {
            log.add(LogType.MSG_DC_INSECURE_KEY, indent + 1);
            signatureResultBuilder.setInsecure(true);
        }
    }

    public boolean isInitialized() {
        return signingKey != null;
    }

    private void findAvailableSignature(PGPOnePassSignatureList sigList) {
        // go through all signatures (should be just one), make sure we have
        //  the key and it matches the one we’re looking for
        for (int i = 0; i < sigList.size(); ++i) {
            try {
                long sigKeyId = sigList.get(i).getKeyID();
                CanonicalizedPublicKeyRing signingRing = mProviderHelper.getCanonicalizedPublicKeyRing(
                        KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(sigKeyId)
                );
                CanonicalizedPublicKey keyCandidate = signingRing.getPublicKey(sigKeyId);
                if ( ! keyCandidate.canSign()) {
                    continue;
                }
                signatureIndex = i;
                signingKey = keyCandidate;
                onePassSignature = sigList.get(i);
                return;
            } catch (ProviderHelper.NotFoundException e) {
                Log.d(Constants.TAG, "key not found, trying next signature...");
            }
        }
    }

    public void findAvailableSignature(PGPSignatureList sigList) {
        // go through all signatures (should be just one), make sure we have
        //  the key and it matches the one we’re looking for
        for (int i = 0; i < sigList.size(); ++i) {
            try {
                long sigKeyId = sigList.get(i).getKeyID();
                CanonicalizedPublicKeyRing signingRing = mProviderHelper.getCanonicalizedPublicKeyRing(
                        KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(sigKeyId)
                );
                CanonicalizedPublicKey keyCandidate = signingRing.getPublicKey(sigKeyId);
                if ( ! keyCandidate.canSign()) {
                    continue;
                }
                signatureIndex = i;
                signingKey = keyCandidate;
                signature = sigList.get(i);
                return;
            } catch (ProviderHelper.NotFoundException e) {
                Log.d(Constants.TAG, "key not found, trying next signature...");
            }
        }
    }

    public void updateSignatureWithCleartext(byte[] clearText) throws IOException, SignatureException {

        InputStream sigIn = new BufferedInputStream(new ByteArrayInputStream(clearText));

        ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream();

        int lookAhead = readInputLine(outputBuffer, sigIn);

        processLine(signature, outputBuffer.toByteArray());

        while (lookAhead != -1) {
            lookAhead = readInputLine(outputBuffer, lookAhead, sigIn);

            signature.update((byte) '\r');
            signature.update((byte) '\n');

            processLine(signature, outputBuffer.toByteArray());
        }

    }

    public void updateSignatureData(byte[] buf, int off, int len) {
        if (signature != null) {
            signature.update(buf, off, len);
        } else if (onePassSignature != null) {
            onePassSignature.update(buf, off, len);
        }
    }

    void verifySignature(OperationLog log, int indent) throws PGPException {

        log.add(LogType.MSG_DC_CLEAR_SIGNATURE_CHECK, indent);

        // Verify signature
        boolean validSignature = signature.verify();
        if (validSignature) {
            log.add(LogType.MSG_DC_CLEAR_SIGNATURE_OK, indent + 1);
        } else {
            log.add(LogType.MSG_DC_CLEAR_SIGNATURE_BAD, indent + 1);
        }

        // check for insecure hash algorithms
        if (!PgpSecurityConstants.isSecureHashAlgorithm(signature.getHashAlgorithm())) {
            log.add(LogType.MSG_DC_INSECURE_HASH_ALGO, indent + 1);
            signatureResultBuilder.setInsecure(true);
        }

        signatureResultBuilder.setValidSignature(validSignature);

    }

    boolean verifySignatureOnePass(Object o, OperationLog log, int indent) throws PGPException {

        if (!(o instanceof PGPSignatureList)) {
            log.add(LogType.MSG_DC_ERROR_NO_SIGNATURE, indent);
            return false;
        }
        PGPSignatureList signatureList = (PGPSignatureList) o;
        if (signatureList.size() <= signatureIndex) {
            log.add(LogType.MSG_DC_ERROR_NO_SIGNATURE, indent);
            return false;
        }

        // PGPOnePassSignature and PGPSignature packets are "bracketed",
        // so we need to take the last-minus-index'th element here
        PGPSignature messageSignature = signatureList.get(signatureList.size() - 1 - signatureIndex);

        // Verify signature
        boolean validSignature = onePassSignature.verify(messageSignature);
        if (validSignature) {
            log.add(LogType.MSG_DC_CLEAR_SIGNATURE_OK, indent + 1);
        } else {
            log.add(LogType.MSG_DC_CLEAR_SIGNATURE_BAD, indent + 1);
        }

        // check for insecure hash algorithms
        if (!PgpSecurityConstants.isSecureHashAlgorithm(onePassSignature.getHashAlgorithm())) {
            log.add(LogType.MSG_DC_INSECURE_HASH_ALGO, indent + 1);
            signatureResultBuilder.setInsecure(true);
        }

        signatureResultBuilder.setValidSignature(validSignature);

        return true;

    }

    public byte[] getSigningFingerprint() {
        return signingKey.getFingerprint();
    }

    public OpenPgpSignatureResult getSignatureResult() {
        return signatureResultBuilder.build();
    }

    /**
     * Mostly taken from ClearSignedFileProcessor in Bouncy Castle
     */

    private static void processLine(PGPSignature sig, byte[] line)
            throws SignatureException {
        int length = getLengthWithoutWhiteSpace(line);
        if (length > 0) {
            sig.update(line, 0, length);
        }
    }

    private static int readInputLine(ByteArrayOutputStream bOut, InputStream fIn)
            throws IOException {
        bOut.reset();

        int lookAhead = -1;
        int ch;

        while ((ch = fIn.read()) >= 0) {
            bOut.write(ch);
            if (ch == '\r' || ch == '\n') {
                lookAhead = readPastEOL(bOut, ch, fIn);
                break;
            }
        }

        return lookAhead;
    }

    private static int readInputLine(ByteArrayOutputStream bOut, int lookAhead, InputStream fIn)
            throws IOException {
        bOut.reset();

        int ch = lookAhead;

        do {
            bOut.write(ch);
            if (ch == '\r' || ch == '\n') {
                lookAhead = readPastEOL(bOut, ch, fIn);
                break;
            }
        } while ((ch = fIn.read()) >= 0);

        if (ch < 0) {
            lookAhead = -1;
        }

        return lookAhead;
    }

    private static int readPastEOL(ByteArrayOutputStream bOut, int lastCh, InputStream fIn)
            throws IOException {
        int lookAhead = fIn.read();

        if (lastCh == '\r' && lookAhead == '\n') {
            bOut.write(lookAhead);
            lookAhead = fIn.read();
        }

        return lookAhead;
    }

    private static int getLengthWithoutWhiteSpace(byte[] line) {
        int end = line.length - 1;

        while (end >= 0 && isWhiteSpace(line[end])) {
            end--;
        }

        return end + 1;
    }

    private static boolean isWhiteSpace(byte b) {
        return b == '\r' || b == '\n' || b == '\t' || b == ' ';
    }

}