aboutsummaryrefslogtreecommitdiffstats
path: root/OpenKeychain/src/test/java/org/sufficientlysecure/keychain/pgp/UncachedKeyringCanonicalizeTest.java
blob: df92547fee278609301437f1a167bf35e3831ea5 (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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
/*
 * Copyright (C) 2014 Dominik Schürmann <dominik@dominikschuermann.de>
 * Copyright (C) 2014 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 org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.Assert;
import org.junit.Test;
import org.junit.Before;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowLog;
import org.bouncycastle.bcpg.BCPGInputStream;
import org.bouncycastle.bcpg.HashAlgorithmTags;
import org.bouncycastle.bcpg.Packet;
import org.bouncycastle.bcpg.PacketTags;
import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags;
import org.bouncycastle.bcpg.UserIDPacket;
import org.bouncycastle.bcpg.sig.KeyFlags;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPSignatureGenerator;
import org.bouncycastle.openpgp.PGPSignatureSubpacketGenerator;
import org.bouncycastle.openpgp.PGPUtil;
import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptor;
import org.bouncycastle.openpgp.operator.PBESecretKeyEncryptor;
import org.bouncycastle.openpgp.operator.PGPContentSignerBuilder;
import org.bouncycastle.openpgp.operator.PGPDigestCalculator;
import org.bouncycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator;
import org.bouncycastle.openpgp.operator.jcajce.JcaPGPContentSignerBuilder;
import org.bouncycastle.openpgp.operator.jcajce.JcaPGPDigestCalculatorProviderBuilder;
import org.bouncycastle.openpgp.operator.jcajce.JcePBESecretKeyDecryptorBuilder;
import org.bouncycastle.openpgp.operator.jcajce.JcePBESecretKeyEncryptorBuilder;
import org.bouncycastle.util.Strings;
import org.sufficientlysecure.keychain.BuildConfig;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.WorkaroundBuildConfig;
import org.sufficientlysecure.keychain.operations.results.OperationResult;
import org.sufficientlysecure.keychain.operations.results.PgpEditKeyResult;
import org.sufficientlysecure.keychain.service.SaveKeyringParcel;
import org.sufficientlysecure.keychain.service.SaveKeyringParcel.Algorithm;
import org.sufficientlysecure.keychain.operations.results.OperationResult.LogType;
import org.sufficientlysecure.keychain.operations.results.OperationResult.OperationLog;
import org.sufficientlysecure.keychain.service.SaveKeyringParcel.ChangeUnlockParcel;
import org.sufficientlysecure.keychain.service.input.CryptoInputParcel;
import org.sufficientlysecure.keychain.support.KeyringTestingHelper;
import org.sufficientlysecure.keychain.support.KeyringTestingHelper.RawPacket;
import org.sufficientlysecure.keychain.util.Passphrase;

import java.io.ByteArrayInputStream;
import java.security.Security;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;


/** Tests for the UncachedKeyring.canonicalize method.
 *
 * This is a complex and crypto-relevant method, which takes care of sanitizing keyrings.
 * Test cases are made for all its assertions.
 */

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = WorkaroundBuildConfig.class, sdk = 21, manifest = "src/main/AndroidManifest.xml")
public class UncachedKeyringCanonicalizeTest {

    static UncachedKeyRing staticRing;
    static int totalPackets;
    UncachedKeyRing ring;
    ArrayList<RawPacket> onlyA = new ArrayList<>();
    ArrayList<RawPacket> onlyB = new ArrayList<>();
    OperationResult.OperationLog log = new OperationResult.OperationLog();
    PGPSignatureSubpacketGenerator subHashedPacketsGen;
    PGPSecretKey secretKey;

    @BeforeClass
    public static void setUpOnce() throws Exception {
        Security.insertProviderAt(new BouncyCastleProvider(), 1);
        ShadowLog.stream = System.out;

        SaveKeyringParcel parcel = new SaveKeyringParcel();
        parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd(
                Algorithm.ECDSA, 0, SaveKeyringParcel.Curve.NIST_P256, KeyFlags.CERTIFY_OTHER, 0L));
        parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd(
                Algorithm.ECDSA, 0, SaveKeyringParcel.Curve.NIST_P256, KeyFlags.SIGN_DATA, 0L));
        parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd(
                Algorithm.ECDH, 0, SaveKeyringParcel.Curve.NIST_P256, KeyFlags.ENCRYPT_COMMS, 0L));

        parcel.mAddUserIds.add("twi");
        parcel.mAddUserIds.add("pink");
        {
            WrappedUserAttribute uat = WrappedUserAttribute.fromSubpacket(100,
                    "sunshine, sunshine, ladybugs awake~".getBytes());
            parcel.mAddUserAttribute.add(uat);
        }

        // passphrase is tested in PgpKeyOperationTest, just use empty here
        parcel.mNewUnlock = new ChangeUnlockParcel(new Passphrase());
        PgpKeyOperation op = new PgpKeyOperation(null);

        PgpEditKeyResult result = op.createSecretKeyRing(parcel);
        Assert.assertTrue("initial test key creation must succeed", result.success());
        staticRing = result.getRing();
        Assert.assertNotNull("initial test key creation must succeed", staticRing);

        staticRing = staticRing.canonicalize(new OperationLog(), 0).getUncachedKeyRing();

        // just for later reference
        totalPackets = 11;

        // we sleep here for a second, to make sure all new certificates have different timestamps
        Thread.sleep(1000);
    }

    @Before public void setUp() throws Exception {
        // show Log.x messages in system.out
        ShadowLog.stream = System.out;
        ring = staticRing;

        subHashedPacketsGen = new PGPSignatureSubpacketGenerator();
        secretKey = new PGPSecretKeyRing(ring.getEncoded(), new JcaKeyFingerprintCalculator())
                .getSecretKey();
    }

    /** Make sure the assumptions made about the generated ring packet structure are valid. */
    @Test public void testGeneratedRingStructure() throws Exception {

        Iterator<RawPacket> it = KeyringTestingHelper.parseKeyring(ring.getEncoded());

        Assert.assertEquals("packet #0 should be secret key",
                PacketTags.SECRET_KEY, it.next().tag);

        Assert.assertEquals("packet #1 should be user id",
                PacketTags.USER_ID, it.next().tag);
        Assert.assertEquals("packet #2 should be signature",
                PacketTags.SIGNATURE, it.next().tag);

        Assert.assertEquals("packet #3 should be user id",
                PacketTags.USER_ID, it.next().tag);
        Assert.assertEquals("packet #4 should be signature",
                PacketTags.SIGNATURE, it.next().tag);

        Assert.assertEquals("packet #5 should be user id",
                PacketTags.USER_ATTRIBUTE, it.next().tag);
        Assert.assertEquals("packet #6 should be signature",
                PacketTags.SIGNATURE, it.next().tag);

        Assert.assertEquals("packet #7 should be secret subkey",
                PacketTags.SECRET_SUBKEY, it.next().tag);
        Assert.assertEquals("packet #8 should be signature",
                PacketTags.SIGNATURE, it.next().tag);

        Assert.assertEquals("packet #9 should be secret subkey",
                PacketTags.SECRET_SUBKEY, it.next().tag);
        Assert.assertEquals("packet #10 should be signature",
                PacketTags.SIGNATURE, it.next().tag);

        Assert.assertFalse("exactly 11 packets total", it.hasNext());

        Assert.assertArrayEquals("created keyring should be constant through canonicalization",
                ring.getEncoded(), ring.canonicalize(log, 0).getEncoded());

    }

    @Test public void testUidSignature() throws Exception {

        UncachedPublicKey masterKey = ring.getPublicKey();
        final WrappedSignature sig = masterKey.getSignaturesForRawId(Strings.toUTF8ByteArray("twi")).next();

        byte[] raw = sig.getEncoded();
        // destroy the signature
        raw[raw.length - 5] += 1;
        final WrappedSignature brokenSig = WrappedSignature.fromBytes(raw);

        { // bad certificates get stripped
            UncachedKeyRing modified = KeyringTestingHelper.injectPacket(ring, brokenSig.getEncoded(), 3);
            CanonicalizedKeyRing canonicalized = modified.canonicalize(log, 0);

            Assert.assertTrue("canonicalized keyring with invalid extra sig must be same as original one",
                    !KeyringTestingHelper.diffKeyrings(
                        ring.getEncoded(), canonicalized.getEncoded(), onlyA, onlyB));
        }

        // remove user id certificate for one user
        final UncachedKeyRing base = KeyringTestingHelper.removePacket(ring, 2);

        { // user id without certificate should be removed
            CanonicalizedKeyRing modified = base.canonicalize(log, 0);
            Assert.assertTrue("canonicalized keyring must differ", KeyringTestingHelper.diffKeyrings(
                    ring.getEncoded(), modified.getEncoded(), onlyA, onlyB));

            Assert.assertEquals("two packets should be stripped after canonicalization", 2, onlyA.size());
            Assert.assertEquals("no new packets after canonicalization", 0, onlyB.size());

            Packet p = new BCPGInputStream(new ByteArrayInputStream(onlyA.get(0).buf)).readPacket();
            Assert.assertTrue("first stripped packet must be user id", p instanceof UserIDPacket);
            Assert.assertEquals("missing user id must be the expected one",
                    "twi", ((UserIDPacket) p).getID());

            Assert.assertArrayEquals("second stripped packet must be signature we removed",
                    sig.getEncoded(), onlyA.get(1).buf);

        }

        { // add error to signature

            UncachedKeyRing modified = KeyringTestingHelper.injectPacket(base, brokenSig.getEncoded(), 3);
            CanonicalizedKeyRing canonicalized = modified.canonicalize(log, 0);

            Assert.assertTrue("canonicalized keyring must differ", KeyringTestingHelper.diffKeyrings(
                    ring.getEncoded(), canonicalized.getEncoded(), onlyA, onlyB));

            Assert.assertEquals("two packets should be missing after canonicalization", 2, onlyA.size());
            Assert.assertEquals("no new packets after canonicalization", 0, onlyB.size());

            Packet p = new BCPGInputStream(new ByteArrayInputStream(onlyA.get(0).buf)).readPacket();
            Assert.assertTrue("first stripped packet must be user id", p instanceof UserIDPacket);
            Assert.assertEquals("missing user id must be the expected one",
                    "twi", ((UserIDPacket) p).getID());

            Assert.assertArrayEquals("second stripped packet must be signature we removed",
                    sig.getEncoded(), onlyA.get(1).buf);
        }

    }

    @Test public void testUidDestroy() throws Exception {

        // signature for "twi"
        ring = KeyringTestingHelper.removePacket(ring, 2);
        // signature for "pink"
        ring = KeyringTestingHelper.removePacket(ring, 3);

        // canonicalization should fail, because there are no valid uids left
        CanonicalizedKeyRing canonicalized = ring.canonicalize(log, 0);
        Assert.assertNull("canonicalization of keyring with no valid uids should fail", canonicalized);

    }

    @Test public void testRevocationRedundant() throws Exception {

        PGPSignature revocation = forgeSignature(
                secretKey, PGPSignature.KEY_REVOCATION, subHashedPacketsGen, secretKey.getPublicKey());

        UncachedKeyRing modified = KeyringTestingHelper.injectPacket(ring, revocation.getEncoded(), 1);

        // try to add the same packet again, it should be rejected in all positions
        injectEverywhere(modified, revocation.getEncoded());

        // an older (but different!) revocation should be rejected as well
        subHashedPacketsGen.setSignatureCreationTime(false, new Date(new Date().getTime() -1000*1000));
        revocation = forgeSignature(
                secretKey, PGPSignature.KEY_REVOCATION, subHashedPacketsGen, secretKey.getPublicKey());

        injectEverywhere(modified, revocation.getEncoded());

    }

    @Test public void testUidRedundant() throws Exception {

        // an older uid certificate should be rejected
        subHashedPacketsGen.setSignatureCreationTime(false, new Date(new Date().getTime() -1000*1000));
        PGPSignature revocation = forgeSignature(
                secretKey, PGPSignature.DEFAULT_CERTIFICATION, subHashedPacketsGen, "twi", secretKey.getPublicKey());

        injectEverywhere(ring, revocation.getEncoded());

    }

    @Test public void testUidRevocationOutdated() throws Exception {
        // an older uid revocation cert should be rejected
        subHashedPacketsGen.setSignatureCreationTime(false, new Date(new Date().getTime() -1000*1000));
        PGPSignature revocation = forgeSignature(
                secretKey, PGPSignature.CERTIFICATION_REVOCATION, subHashedPacketsGen, "twi", secretKey.getPublicKey());

        injectEverywhere(ring, revocation.getEncoded());

    }

    @Test public void testUidRevocationRedundant() throws Exception {

        PGPSignature revocation = forgeSignature(
                secretKey, PGPSignature.CERTIFICATION_REVOCATION, subHashedPacketsGen, "twi", secretKey.getPublicKey());

        // add that revocation to the base, and check if the redundant one will be rejected as well
        UncachedKeyRing modified = KeyringTestingHelper.injectPacket(ring, revocation.getEncoded(), 2);

        injectEverywhere(modified, revocation.getEncoded());

        // an older (but different!) uid revocation should be rejected as well
        subHashedPacketsGen.setSignatureCreationTime(false, new Date(new Date().getTime() -1000*1000));
        revocation = forgeSignature(
                secretKey, PGPSignature.CERTIFICATION_REVOCATION, subHashedPacketsGen, "twi", secretKey.getPublicKey());

        injectEverywhere(modified, revocation.getEncoded());

    }

    @Test public void testDuplicateUid() throws Exception {

        // get subkey packets
        Iterator<RawPacket> it = KeyringTestingHelper.parseKeyring(ring.getEncoded());
        RawPacket uidPacket = KeyringTestingHelper.getNth(it, 3);
        RawPacket uidSig = it.next();

        // inject at a second position
        UncachedKeyRing modified = ring;
        modified = KeyringTestingHelper.injectPacket(modified, uidPacket.buf, 5);
        modified = KeyringTestingHelper.injectPacket(modified, uidSig.buf, 6);

        // canonicalize, and check if we lose the bad signature
        OperationLog log = new OperationLog();
        CanonicalizedKeyRing canonicalized = modified.canonicalize(log, 0);
        Assert.assertNotNull("canonicalization with duplicate user id should succeed", canonicalized);
        Assert.assertTrue("log should contain uid_dup event", log.containsType(LogType.MSG_KC_UID_DUP));
        /* TODO actually test ths, and fix behavior
        Assert.assertTrue("duplicate user id packets should be gone after canonicalization",
                KeyringTestingHelper.diffKeyrings(modified.getEncoded(), canonicalized.getEncoded(),
                        onlyA, onlyB)
        );
        Assert.assertEquals("canonicalized keyring should have lost the two duplicate packets",
                2, onlyA.size());
        Assert.assertTrue("canonicalized keyring should still contain the user id",
                canonicalized.getUnorderedUserIds().contains(new UserIDPacket(uidPacket.buf).getID()));
        */

    }

    @Test public void testSignatureBroken() throws Exception {

        injectEverytype(secretKey, ring, subHashedPacketsGen, true);

    }

    @Test public void testForeignSignature() throws Exception {

        SaveKeyringParcel parcel = new SaveKeyringParcel();
        parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd(
                Algorithm.ECDSA, 0, SaveKeyringParcel.Curve.NIST_P256, KeyFlags.CERTIFY_OTHER, 0L));
        parcel.mAddUserIds.add("trix");
        PgpKeyOperation op = new PgpKeyOperation(null);

        OperationResult.OperationLog log = new OperationResult.OperationLog();
        UncachedKeyRing foreign = op.createSecretKeyRing(parcel).getRing();

        Assert.assertNotNull("initial test key creation must succeed", foreign);
        PGPSecretKey foreignSecretKey =
                new PGPSecretKeyRing(foreign.getEncoded(), new JcaKeyFingerprintCalculator())
                .getSecretKey();

        injectEverytype(foreignSecretKey, ring, subHashedPacketsGen);

    }

    @Test public void testSignatureFuture() throws Exception {

        // generate future timestamp (we allow up to one day future timestamps)
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR, 2);
        subHashedPacketsGen.setSignatureCreationTime(false, cal.getTime());

        injectEverytype(secretKey, ring, subHashedPacketsGen);

    }

    @Test public void testSignatureLocal() throws Exception {

        // make key local only
        subHashedPacketsGen.setExportable(false, false);

        injectEverytype(secretKey, ring, subHashedPacketsGen);

    }

    @Test public void testSubkeyDestroy() throws Exception {

        // signature for second key (first subkey)
        UncachedKeyRing modified = KeyringTestingHelper.removePacket(ring, 8);

        // canonicalization should fail, because there are no valid uids left
        CanonicalizedKeyRing canonicalized = modified.canonicalize(log, 0);
        Assert.assertTrue("keyring with missing subkey binding sig should differ from intact one after canonicalization",
                KeyringTestingHelper.diffKeyrings(ring.getEncoded(), canonicalized.getEncoded(),
                        onlyA, onlyB)
        );

        Assert.assertEquals("canonicalized keyring should have two extra packets", 2, onlyA.size());
        Assert.assertEquals("canonicalized keyring should have no extra packets", 0, onlyB.size());

        Assert.assertEquals("first missing packet should be the subkey",
                PacketTags.SECRET_SUBKEY, onlyA.get(0).tag);
        Assert.assertEquals("second missing packet should be subkey's signature",
                PacketTags.SIGNATURE, onlyA.get(1).tag);
        Assert.assertEquals("second missing packet should be next to subkey",
                onlyA.get(0).position + 1, onlyA.get(1).position);

    }

    @Test public void testSubkeyBindingNoPKB() throws Exception {

        UncachedPublicKey pKey = KeyringTestingHelper.getNth(ring.getPublicKeys(), 1);
        PGPSignature sig;

        subHashedPacketsGen.setKeyFlags(false, KeyFlags.SIGN_DATA);

        {
            // forge a (newer) signature, which has the sign flag but no primary key binding sig
            PGPSignatureSubpacketGenerator unhashedSubs = new PGPSignatureSubpacketGenerator();

            // just add any random signature, because why not
            unhashedSubs.setEmbeddedSignature(false, forgeSignature(
                            secretKey, PGPSignature.POSITIVE_CERTIFICATION, subHashedPacketsGen,
                            secretKey.getPublicKey()
                    )
            );

            sig = forgeSignature(
                    secretKey, PGPSignature.SUBKEY_BINDING, subHashedPacketsGen, unhashedSubs,
                    secretKey.getPublicKey(), pKey.getPublicKey());

            // inject in the right position
            UncachedKeyRing modified = KeyringTestingHelper.injectPacket(ring, sig.getEncoded(), 8);

            // canonicalize, and check if we lose the bad signature
            CanonicalizedKeyRing canonicalized = modified.canonicalize(log, 0);
            Assert.assertFalse("subkey binding signature should be gone after canonicalization",
                    KeyringTestingHelper.diffKeyrings(ring.getEncoded(), canonicalized.getEncoded(),
                            onlyA, onlyB)
            );
        }

        { // now try one with a /bad/ primary key binding signature

            PGPSignatureSubpacketGenerator unhashedSubs = new PGPSignatureSubpacketGenerator();
            // this one is signed by the primary key itself, not the subkey - but it IS primary binding
            unhashedSubs.setEmbeddedSignature(false, forgeSignature(
                            secretKey, PGPSignature.PRIMARYKEY_BINDING, subHashedPacketsGen,
                            secretKey.getPublicKey(), pKey.getPublicKey()
                    )
            );

            sig = forgeSignature(
                    secretKey, PGPSignature.SUBKEY_BINDING, subHashedPacketsGen, unhashedSubs,
                    secretKey.getPublicKey(), pKey.getPublicKey());

            // inject in the right position
            UncachedKeyRing modified = KeyringTestingHelper.injectPacket(ring, sig.getEncoded(), 8);

            // canonicalize, and check if we lose the bad signature
            CanonicalizedKeyRing canonicalized = modified.canonicalize(log, 0);
            Assert.assertFalse("subkey binding signature should be gone after canonicalization",
                    KeyringTestingHelper.diffKeyrings(ring.getEncoded(), canonicalized.getEncoded(),
                            onlyA, onlyB)
            );
        }

    }

    @Test public void testSubkeyBindingRedundant() throws Exception {

        UncachedPublicKey pKey = KeyringTestingHelper.getNth(ring.getPublicKeys(), 2);

        subHashedPacketsGen.setKeyFlags(false, KeyFlags.ENCRYPT_COMMS);
        PGPSignature sig2 = forgeSignature(
                secretKey, PGPSignature.SUBKEY_BINDING, subHashedPacketsGen,
                secretKey.getPublicKey(), pKey.getPublicKey());

        subHashedPacketsGen.setSignatureCreationTime(false, new Date(new Date().getTime() -1000*1000));
        PGPSignature sig1 = forgeSignature(
                secretKey, PGPSignature.SUBKEY_REVOCATION, subHashedPacketsGen,
                secretKey.getPublicKey(), pKey.getPublicKey());

        subHashedPacketsGen = new PGPSignatureSubpacketGenerator();
        subHashedPacketsGen.setSignatureCreationTime(false, new Date(new Date().getTime() -100*1000));
        PGPSignature sig3 = forgeSignature(
                secretKey, PGPSignature.SUBKEY_BINDING, subHashedPacketsGen,
                secretKey.getPublicKey(), pKey.getPublicKey());

        UncachedKeyRing modified = KeyringTestingHelper.injectPacket(ring, sig1.getEncoded(), 10);
        modified = KeyringTestingHelper.injectPacket(modified, sig2.getEncoded(), 11);
        modified = KeyringTestingHelper.injectPacket(modified, sig1.getEncoded(), 12);
        modified = KeyringTestingHelper.injectPacket(modified, sig3.getEncoded(), 13);

        // canonicalize, and check if we lose the bad signature
        CanonicalizedKeyRing canonicalized = modified.canonicalize(log, 0);
        Assert.assertTrue("subkey binding signature should be gone after canonicalization",
                KeyringTestingHelper.diffKeyrings(modified.getEncoded(), canonicalized.getEncoded(),
                        onlyA, onlyB)
        );

        Assert.assertEquals("canonicalized keyring should have lost two packets", 3, onlyA.size());
        Assert.assertEquals("canonicalized keyring should have no extra packets", 0, onlyB.size());

        Assert.assertEquals("first missing packet should be the subkey",
                PacketTags.SIGNATURE, onlyA.get(0).tag);
        Assert.assertEquals("second missing packet should be a signature",
                PacketTags.SIGNATURE, onlyA.get(1).tag);
        Assert.assertEquals("second missing packet should be a signature",
                PacketTags.SIGNATURE, onlyA.get(2).tag);

    }

    @Test
    public void testDuplicateSubkey() throws Exception {

        { // duplicate subkey

            // get subkey packets
            Iterator<RawPacket> it = KeyringTestingHelper.parseKeyring(ring.getEncoded());
            RawPacket subKey = KeyringTestingHelper.getNth(it, 7);
            RawPacket subSig = it.next();

            // inject at a second position
            UncachedKeyRing modified = ring;
            modified = KeyringTestingHelper.injectPacket(modified, subKey.buf, 9);
            modified = KeyringTestingHelper.injectPacket(modified, subSig.buf, 10);

            // canonicalize, and check if we lose the bad signature
            OperationLog log = new OperationLog();
            CanonicalizedKeyRing canonicalized = modified.canonicalize(log, 0);
            Assert.assertNull("canonicalization with duplicate subkey should fail", canonicalized);
            Assert.assertTrue("log should contain dup_key event", log.containsType(LogType.MSG_KC_ERROR_DUP_KEY));
        }

        { // duplicate subkey, which is the same as the master key

            // We actually encountered one of these in the wild:
            // https://www.sparkasse-holstein.de/firmenkunden/electronic_banking/secure-e-mail/pdf/Spk_Holstein_PGP_Domain-Zertifikat.asc

            CanonicalizedSecretKeyRing canonicalized = (CanonicalizedSecretKeyRing) ring.canonicalize(log, 0);

            CanonicalizedSecretKey masterSecretKey = canonicalized.getSecretKey();
            masterSecretKey.unlock(new Passphrase());
            PGPPublicKey masterPublicKey = masterSecretKey.getPublicKey();
            CryptoInputParcel cryptoInput = new CryptoInputParcel(new Date());
            PGPSignature cert = PgpKeyOperation.generateSubkeyBindingSignature(
                    PgpKeyOperation.getSignatureGenerator(masterSecretKey.getSecretKey(), cryptoInput),
                    cryptoInput.getSignatureTime(),
                    masterPublicKey, masterSecretKey.getPrivateKey(),
                    PgpKeyOperation.getSignatureGenerator(masterSecretKey.getSecretKey(), null),
                    masterSecretKey.getPrivateKey(), masterPublicKey, masterSecretKey.getKeyUsage(), 0);
            PGPPublicKey subPubKey = PGPPublicKey.addSubkeyBindingCertification(masterPublicKey, cert);

            PGPSecretKey sKey;
            {
                // Build key encrypter and decrypter based on passphrase
                PGPDigestCalculator encryptorHashCalc = new JcaPGPDigestCalculatorProviderBuilder()
                        .build().get(HashAlgorithmTags.SHA256);
                PBESecretKeyEncryptor keyEncryptor = new JcePBESecretKeyEncryptorBuilder(
                        SymmetricKeyAlgorithmTags.AES_256, encryptorHashCalc, 10)
                        .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME).build("".toCharArray());

                // NOTE: only SHA1 is supported for key checksum calculations.
                PGPDigestCalculator sha1Calc = new JcaPGPDigestCalculatorProviderBuilder()
                        .build().get(HashAlgorithmTags.SHA1);
                sKey = new PGPSecretKey(masterSecretKey.getPrivateKey(), subPubKey, sha1Calc, false, keyEncryptor);
            }

            UncachedKeyRing modified = KeyringTestingHelper.injectPacket(ring, sKey.getEncoded(), 7);

            // canonicalize, and check if we lose the bad signature
            OperationLog log = new OperationLog();
            CanonicalizedKeyRing result = modified.canonicalize(log, 0);
            Assert.assertNull("canonicalization with duplicate subkey (from master) should fail", result);
            Assert.assertTrue("log should contain dup_key event", log.containsType(LogType.MSG_KC_ERROR_DUP_KEY));
        }

    }

    private static final int[] sigtypes_direct = new int[] {
        PGPSignature.KEY_REVOCATION,
        PGPSignature.DIRECT_KEY,
    };
    private static final int[] sigtypes_uid = new int[] {
        PGPSignature.DEFAULT_CERTIFICATION,
        PGPSignature.NO_CERTIFICATION,
        PGPSignature.CASUAL_CERTIFICATION,
        PGPSignature.POSITIVE_CERTIFICATION,
        PGPSignature.CERTIFICATION_REVOCATION,
    };
    private static final int[] sigtypes_subkey = new int[] {
        PGPSignature.SUBKEY_BINDING,
        PGPSignature.PRIMARYKEY_BINDING,
        PGPSignature.SUBKEY_REVOCATION,
    };

    private static void injectEverytype(PGPSecretKey secretKey,
                                        UncachedKeyRing ring,
                                        PGPSignatureSubpacketGenerator subHashedPacketsGen)
            throws Exception {
        injectEverytype(secretKey, ring, subHashedPacketsGen, false);
    }

    private static void injectEverytype(PGPSecretKey secretKey,
                                        UncachedKeyRing ring,
                                        PGPSignatureSubpacketGenerator subHashedPacketsGen,
                                        boolean breakSig)
            throws Exception {

        for (int sigtype : sigtypes_direct) {
            PGPSignature sig = forgeSignature(
                    secretKey, sigtype, subHashedPacketsGen, secretKey.getPublicKey());
            byte[] encoded = sig.getEncoded();
            if (breakSig) {
                encoded[encoded.length-10] += 1;
            }
            injectEverywhere(ring, encoded);
        }

        for (int sigtype : sigtypes_uid) {
            PGPSignature sig = forgeSignature(
                    secretKey, sigtype, subHashedPacketsGen, "twi", secretKey.getPublicKey());

            byte[] encoded = sig.getEncoded();
            if (breakSig) {
                encoded[encoded.length-10] += 1;
            }
            injectEverywhere(ring, encoded);
        }

        for (int sigtype : sigtypes_subkey) {
            PGPSignature sig = forgeSignature(
                    secretKey, sigtype, subHashedPacketsGen,
                    secretKey.getPublicKey(), secretKey.getPublicKey());

            byte[] encoded = sig.getEncoded();
            if (breakSig) {
                encoded[encoded.length-10] += 1;
            }
            injectEverywhere(ring, encoded);
        }

    }

    private static void injectEverywhere(UncachedKeyRing ring, byte[] packet) throws Exception {

        OperationResult.OperationLog log = new OperationResult.OperationLog();

        byte[] encodedRing = ring.getEncoded();

        for(int i = 0; i < totalPackets; i++) {

            byte[] brokenEncoded = KeyringTestingHelper.injectPacket(encodedRing, packet, i);

            try {

                UncachedKeyRing brokenRing = UncachedKeyRing.decodeFromData(brokenEncoded);

                CanonicalizedKeyRing canonicalized = brokenRing.canonicalize(log, 0);
                if (canonicalized == null) {
                    System.out.println("ok, canonicalization failed.");
                    continue;
                }

                Assert.assertArrayEquals("injected bad signature must be gone after canonicalization",
                        ring.getEncoded(), canonicalized.getEncoded());

            } catch (Exception e) {
                System.out.println("ok, rejected with: " + e.getMessage());
            }
        }

    }

    private static PGPSignature forgeSignature(PGPSecretKey key, int type,
                                               PGPSignatureSubpacketGenerator subpackets,
                                               PGPPublicKey publicKey)
            throws Exception {

        PBESecretKeyDecryptor keyDecryptor = new JcePBESecretKeyDecryptorBuilder().setProvider(
                Constants.BOUNCY_CASTLE_PROVIDER_NAME).build("".toCharArray());
        PGPPrivateKey privateKey = key.extractPrivateKey(keyDecryptor);

        PGPContentSignerBuilder signerBuilder = new JcaPGPContentSignerBuilder(
                publicKey.getAlgorithm(), PGPUtil.SHA1)
                .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME);

        PGPSignatureGenerator sGen = new PGPSignatureGenerator(signerBuilder);
        sGen.setHashedSubpackets(subpackets.generate());
        sGen.init(type, privateKey);
        return sGen.generateCertification(publicKey);

    }

    private static PGPSignature forgeSignature(PGPSecretKey key, int type,
                                               PGPSignatureSubpacketGenerator subpackets,
                                               String userId, PGPPublicKey publicKey)
            throws Exception {

        PBESecretKeyDecryptor keyDecryptor = new JcePBESecretKeyDecryptorBuilder().setProvider(
                Constants.BOUNCY_CASTLE_PROVIDER_NAME).build("".toCharArray());
        PGPPrivateKey privateKey = key.extractPrivateKey(keyDecryptor);

        PGPContentSignerBuilder signerBuilder = new JcaPGPContentSignerBuilder(
                publicKey.getAlgorithm(), PGPUtil.SHA1)
                .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME);

        PGPSignatureGenerator sGen = new PGPSignatureGenerator(signerBuilder);
        sGen.setHashedSubpackets(subpackets.generate());
        sGen.init(type, privateKey);
        return sGen.generateCertification(userId, publicKey);

    }

    private static PGPSignature forgeSignature(PGPSecretKey key, int type,
                                               PGPSignatureSubpacketGenerator subpackets,
                                               PGPPublicKey publicKey, PGPPublicKey signedKey)
            throws Exception {

        PBESecretKeyDecryptor keyDecryptor = new JcePBESecretKeyDecryptorBuilder().setProvider(
                Constants.BOUNCY_CASTLE_PROVIDER_NAME).build("".toCharArray());
        PGPPrivateKey privateKey = key.extractPrivateKey(keyDecryptor);

        PGPContentSignerBuilder signerBuilder = new JcaPGPContentSignerBuilder(
                publicKey.getAlgorithm(), PGPUtil.SHA1)
                .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME);

        PGPSignatureGenerator sGen = new PGPSignatureGenerator(signerBuilder);
        sGen.setHashedSubpackets(subpackets.generate());
        sGen.init(type, privateKey);
        return sGen.generateCertification(publicKey, signedKey);

    }

    private static PGPSignature forgeSignature(PGPSecretKey key, int type,
                                               PGPSignatureSubpacketGenerator hashedSubs,
                                               PGPSignatureSubpacketGenerator unhashedSubs,
                                               PGPPublicKey publicKey, PGPPublicKey signedKey)
            throws Exception {

        PBESecretKeyDecryptor keyDecryptor = new JcePBESecretKeyDecryptorBuilder().setProvider(
                Constants.BOUNCY_CASTLE_PROVIDER_NAME).build("".toCharArray());
        PGPPrivateKey privateKey = key.extractPrivateKey(keyDecryptor);

        PGPContentSignerBuilder signerBuilder = new JcaPGPContentSignerBuilder(
                publicKey.getAlgorithm(), PGPUtil.SHA1)
                .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME);

        PGPSignatureGenerator sGen = new PGPSignatureGenerator(signerBuilder);
        sGen.setHashedSubpackets(hashedSubs.generate());
        sGen.setUnhashedSubpackets(unhashedSubs.generate());
        sGen.init(type, privateKey);
        return sGen.generateCertification(publicKey, signedKey);

    }

}