From 11e5261f07d85d76d6fe58aabb5981cda9ead22b Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Fri, 1 Aug 2014 16:47:06 +0200 Subject: move classes around a bit --- .../keychain/pgp/PgpDecryptVerifyTest.java | 53 ++ .../keychain/pgp/PgpKeyOperationTest.java | 764 ++++++++++++++++++++ .../pgp/UncachedKeyringCanonicalizeTest.java | 622 +++++++++++++++++ .../keychain/pgp/UncachedKeyringMergeTest.java | 390 +++++++++++ .../keychain/pgp/UncachedKeyringTest.java | 119 ++++ .../provider/ProviderHelperKeyringTest.java | 101 +++ .../keychain/tests/PgpDecryptVerifyTest.java | 53 -- .../keychain/tests/PgpKeyOperationTest.java | 770 --------------------- .../keychain/tests/ProviderHelperKeyringTest.java | 101 --- .../tests/UncachedKeyringCanonicalizeTest.java | 627 ----------------- .../keychain/tests/UncachedKeyringMergeTest.java | 397 ----------- .../keychain/tests/UncachedKeyringTest.java | 125 ---- .../keychain/keyimport/FileImportCache.java | 97 --- .../keychain/util/FileImportCache.java | 179 +++++ 14 files changed, 2228 insertions(+), 2170 deletions(-) create mode 100644 OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/PgpDecryptVerifyTest.java create mode 100644 OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperationTest.java create mode 100644 OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/UncachedKeyringCanonicalizeTest.java create mode 100644 OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/UncachedKeyringMergeTest.java create mode 100644 OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/UncachedKeyringTest.java create mode 100644 OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/provider/ProviderHelperKeyringTest.java delete mode 100644 OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/PgpDecryptVerifyTest.java delete mode 100644 OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/PgpKeyOperationTest.java delete mode 100644 OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/ProviderHelperKeyringTest.java delete mode 100644 OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringCanonicalizeTest.java delete mode 100644 OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringMergeTest.java delete mode 100644 OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringTest.java delete mode 100644 OpenKeychain/src/main/java/org/sufficientlysecure/keychain/keyimport/FileImportCache.java create mode 100644 OpenKeychain/src/main/java/org/sufficientlysecure/keychain/util/FileImportCache.java diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/PgpDecryptVerifyTest.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/PgpDecryptVerifyTest.java new file mode 100644 index 000000000..158650012 --- /dev/null +++ b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/PgpDecryptVerifyTest.java @@ -0,0 +1,53 @@ +/* + * Copyright (C) Art O Cathain + * + * 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 . + */ + +package tests; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.*; +import org.openintents.openpgp.OpenPgpSignatureResult; +import org.sufficientlysecure.keychain.support.PgpVerifyTestingHelper; + +@RunWith(RobolectricTestRunner.class) +@org.robolectric.annotation.Config(emulateSdk = 18) // Robolectric doesn't yet support 19 +public class PgpDecryptVerifyTest { + + @Test + public void testVerifySuccess() throws Exception { + + String testFileName = "/sample.txt"; + int expectedSignatureResult = OpenPgpSignatureResult.SIGNATURE_SUCCESS_UNCERTIFIED; + + int status = new PgpVerifyTestingHelper(Robolectric.application).doTestFile(testFileName); + + Assert.assertEquals(expectedSignatureResult, status); + } + + @Test + public void testVerifyFailure() throws Exception { + + String testFileName = "/sample-altered.txt"; + int expectedSignatureResult = OpenPgpSignatureResult.SIGNATURE_ERROR; + + int status = new PgpVerifyTestingHelper(Robolectric.application).doTestFile(testFileName); + + Assert.assertEquals(expectedSignatureResult, status); + } + +} diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperationTest.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperationTest.java new file mode 100644 index 000000000..516d1ac63 --- /dev/null +++ b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperationTest.java @@ -0,0 +1,764 @@ +package org.sufficientlysecure.keychain.pgp; + +import junit.framework.AssertionFailedError; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.runner.RunWith; +import org.robolectric.*; +import org.robolectric.shadows.ShadowLog; +import org.spongycastle.bcpg.BCPGInputStream; +import org.spongycastle.bcpg.Packet; +import org.spongycastle.bcpg.PacketTags; +import org.spongycastle.bcpg.SecretSubkeyPacket; +import org.spongycastle.bcpg.SignaturePacket; +import org.spongycastle.bcpg.UserIDPacket; +import org.spongycastle.bcpg.sig.KeyFlags; +import org.spongycastle.openpgp.PGPSignature; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.Constants.choice.algorithm; +import org.sufficientlysecure.keychain.service.OperationResultParcel.OperationLog; +import org.sufficientlysecure.keychain.service.SaveKeyringParcel; +import org.sufficientlysecure.keychain.service.SaveKeyringParcel.SubkeyAdd; +import org.sufficientlysecure.keychain.service.SaveKeyringParcel.SubkeyChange; +import org.sufficientlysecure.keychain.support.KeyringBuilder; +import org.sufficientlysecure.keychain.support.KeyringTestingHelper; +import org.sufficientlysecure.keychain.support.KeyringTestingHelper.RawPacket; +import org.sufficientlysecure.keychain.support.TestDataUtil; +import org.sufficientlysecure.keychain.util.ProgressScaler; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.Random; + +@RunWith(RobolectricTestRunner.class) +@org.robolectric.annotation.Config(emulateSdk = 18) // Robolectric doesn't yet support 19 +public class PgpKeyOperationTest { + + static UncachedKeyRing staticRing; + static String passphrase; + + UncachedKeyRing ring; + PgpKeyOperation op; + SaveKeyringParcel parcel; + ArrayList onlyA = new ArrayList(); + ArrayList onlyB = new ArrayList(); + + @BeforeClass public static void setUpOnce() throws Exception { + ShadowLog.stream = System.out; + + { + String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789!@#$%^&*()-_="; + Random r = new Random(); + StringBuilder passbuilder = new StringBuilder(); + // 20% chance for an empty passphrase + for(int i = 0, j = r.nextInt(10) > 2 ? r.nextInt(20) : 0; i < j; i++) { + passbuilder.append(chars.charAt(r.nextInt(chars.length()))); + } + passphrase = passbuilder.toString(); + System.out.println("Passphrase is '" + passphrase + "'"); + } + + SaveKeyringParcel parcel = new SaveKeyringParcel(); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.CERTIFY_OTHER, null)); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.SIGN_DATA, null)); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.ENCRYPT_COMMS, null)); + + parcel.mAddUserIds.add("twi"); + parcel.mAddUserIds.add("pink"); + parcel.mNewPassphrase = passphrase; + PgpKeyOperation op = new PgpKeyOperation(null); + + staticRing = op.createSecretKeyRing(parcel).getRing(); + + Assert.assertNotNull("initial test key creation must succeed", staticRing); + + // 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; + + // setting up some parameters just to reduce code duplication + op = new PgpKeyOperation(new ProgressScaler(null, 0, 100, 100)); + + // set this up, gonna need it more than once + parcel = new SaveKeyringParcel(); + parcel.mMasterKeyId = ring.getMasterKeyId(); + parcel.mFingerprint = ring.getFingerprint(); + + } + + @Test + public void createSecretKeyRingTests() { + + { + parcel.reset(); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, new Random().nextInt(256)+255, KeyFlags.CERTIFY_OTHER, null)); + parcel.mAddUserIds.add("shy"); + parcel.mNewPassphrase = passphrase; + + UncachedKeyRing ring = op.createSecretKeyRing(parcel).getRing(); + + Assert.assertNull("creating ring with < 512 bytes keysize should fail", ring); + } + + { + parcel.reset(); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.elgamal, 1024, KeyFlags.CERTIFY_OTHER, null)); + parcel.mAddUserIds.add("shy"); + parcel.mNewPassphrase = passphrase; + + UncachedKeyRing ring = op.createSecretKeyRing(parcel).getRing(); + + Assert.assertNull("creating ring with ElGamal master key should fail", ring); + } + + { + parcel.reset(); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + 12345, 1024, KeyFlags.CERTIFY_OTHER, null)); + parcel.mAddUserIds.add("shy"); + parcel.mNewPassphrase = passphrase; + + UncachedKeyRing ring = op.createSecretKeyRing(parcel).getRing(); + Assert.assertNull("creating ring with bad algorithm choice should fail", ring); + } + + { + parcel.reset(); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.SIGN_DATA, null)); + parcel.mAddUserIds.add("shy"); + parcel.mNewPassphrase = passphrase; + + UncachedKeyRing ring = op.createSecretKeyRing(parcel).getRing(); + Assert.assertNull("creating ring with non-certifying master key should fail", ring); + } + + { + parcel.reset(); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.CERTIFY_OTHER, null)); + parcel.mNewPassphrase = passphrase; + + UncachedKeyRing ring = op.createSecretKeyRing(parcel).getRing(); + Assert.assertNull("creating ring without user ids should fail", ring); + } + + { + parcel.reset(); + parcel.mAddUserIds.add("shy"); + parcel.mNewPassphrase = passphrase; + + UncachedKeyRing ring = op.createSecretKeyRing(parcel).getRing(); + Assert.assertNull("creating ring without subkeys should fail", ring); + } + + } + + @Test + // this is a special case since the flags are in user id certificates rather than + // subkey binding certificates + public void testMasterFlags() throws Exception { + SaveKeyringParcel parcel = new SaveKeyringParcel(); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.CERTIFY_OTHER | KeyFlags.SIGN_DATA, null)); + parcel.mAddUserIds.add("luna"); + ring = op.createSecretKeyRing(parcel).getRing(); + + Assert.assertEquals("the keyring should contain only the master key", + 1, KeyringTestingHelper.itToList(ring.getPublicKeys()).size()); + Assert.assertEquals("first (master) key must have both flags", + KeyFlags.CERTIFY_OTHER | KeyFlags.SIGN_DATA, ring.getPublicKey().getKeyUsage()); + + } + + @Test + public void testCreatedKey() throws Exception { + + // an empty modification should change nothing. this also ensures the keyring + // is constant through canonicalization. + // applyModificationWithChecks(parcel, ring, onlyA, onlyB); + + Assert.assertNotNull("key creation failed", ring); + + Assert.assertNull("primary user id must be empty", + ring.getPublicKey().getPrimaryUserId()); + + Assert.assertEquals("number of user ids must be two", + 2, ring.getPublicKey().getUnorderedUserIds().size()); + + Assert.assertEquals("number of subkeys must be three", + 3, KeyringTestingHelper.itToList(ring.getPublicKeys()).size()); + + Assert.assertTrue("key ring should have been created in the last 120 seconds", + ring.getPublicKey().getCreationTime().after(new Date(new Date().getTime()-1000*120))); + + Assert.assertNull("key ring should not expire", + ring.getPublicKey().getExpiryTime()); + + Iterator it = ring.getPublicKeys(); + + Assert.assertEquals("first (master) key can certify", + KeyFlags.CERTIFY_OTHER, it.next().getKeyUsage()); + + UncachedPublicKey signingKey = it.next(); + Assert.assertEquals("second key can sign", + KeyFlags.SIGN_DATA, signingKey.getKeyUsage()); + ArrayList sigs = signingKey.getSignatures().next().getEmbeddedSignatures(); + Assert.assertEquals("signing key signature should have one embedded signature", + 1, sigs.size()); + Assert.assertEquals("embedded signature should be of primary key binding type", + PGPSignature.PRIMARYKEY_BINDING, sigs.get(0).getSignatureType()); + Assert.assertEquals("primary key binding signature issuer should be signing subkey", + signingKey.getKeyId(), sigs.get(0).getKeyId()); + + Assert.assertEquals("third key can encrypt", + KeyFlags.ENCRYPT_COMMS, it.next().getKeyUsage()); + + } + + @Test + public void testBadKeyModification() throws Exception { + + { + SaveKeyringParcel parcel = new SaveKeyringParcel(); + // off by one + parcel.mMasterKeyId = ring.getMasterKeyId() -1; + parcel.mFingerprint = ring.getFingerprint(); + + CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); + UncachedKeyRing modified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); + + Assert.assertNull("keyring modification with bad master key id should fail", modified); + } + + { + SaveKeyringParcel parcel = new SaveKeyringParcel(); + // off by one + parcel.mMasterKeyId = null; + parcel.mFingerprint = ring.getFingerprint(); + + CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); + UncachedKeyRing modified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); + + Assert.assertNull("keyring modification with null master key id should fail", modified); + } + + { + SaveKeyringParcel parcel = new SaveKeyringParcel(); + parcel.mMasterKeyId = ring.getMasterKeyId(); + parcel.mFingerprint = ring.getFingerprint(); + // some byte, off by one + parcel.mFingerprint[5] += 1; + + CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); + UncachedKeyRing modified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); + + Assert.assertNull("keyring modification with bad fingerprint should fail", modified); + } + + { + SaveKeyringParcel parcel = new SaveKeyringParcel(); + parcel.mMasterKeyId = ring.getMasterKeyId(); + parcel.mFingerprint = null; + + CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); + UncachedKeyRing modified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); + + Assert.assertNull("keyring modification with null fingerprint should fail", modified); + } + + { + String badphrase = ""; + if (badphrase.equals(passphrase)) { + badphrase = "a"; + } + CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); + UncachedKeyRing modified = op.modifySecretKeyRing(secretRing, parcel, badphrase).getRing(); + + Assert.assertNull("keyring modification with bad passphrase should fail", modified); + } + + } + + @Test + public void testSubkeyAdd() throws Exception { + + long expiry = new Date().getTime() / 1000 + 159; + int flags = KeyFlags.SIGN_DATA; + int bits = 1024 + new Random().nextInt(8); + parcel.mAddSubKeys.add(new SubkeyAdd(algorithm.rsa, bits, flags, expiry)); + + UncachedKeyRing modified = applyModificationWithChecks(parcel, ring, onlyA, onlyB); + + Assert.assertEquals("no extra packets in original", 0, onlyA.size()); + Assert.assertEquals("exactly two extra packets in modified", 2, onlyB.size()); + + Packet p; + + p = new BCPGInputStream(new ByteArrayInputStream(onlyB.get(0).buf)).readPacket(); + Assert.assertTrue("first new packet must be secret subkey", p instanceof SecretSubkeyPacket); + + p = new BCPGInputStream(new ByteArrayInputStream(onlyB.get(1).buf)).readPacket(); + Assert.assertTrue("second new packet must be signature", p instanceof SignaturePacket); + Assert.assertEquals("signature type must be subkey binding certificate", + PGPSignature.SUBKEY_BINDING, ((SignaturePacket) p).getSignatureType()); + Assert.assertEquals("signature must have been created by master key", + ring.getMasterKeyId(), ((SignaturePacket) p).getKeyID()); + + // get new key from ring. it should be the last one (add a check to make sure?) + UncachedPublicKey newKey = null; + { + Iterator it = modified.getPublicKeys(); + while (it.hasNext()) { + newKey = it.next(); + } + } + + Assert.assertNotNull("new key is not null", newKey); + Assert.assertNotNull("added key must have an expiry date", + newKey.getExpiryTime()); + Assert.assertEquals("added key must have expected expiry date", + expiry, newKey.getExpiryTime().getTime()/1000); + Assert.assertEquals("added key must have expected flags", + flags, newKey.getKeyUsage()); + Assert.assertEquals("added key must have expected bitsize", + bits, newKey.getBitStrength()); + + { // bad keysize should fail + parcel.reset(); + parcel.mAddSubKeys.add(new SubkeyAdd( + algorithm.rsa, new Random().nextInt(512), KeyFlags.SIGN_DATA, null)); + + CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); + modified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); + + Assert.assertNull("creating a subkey with keysize < 512 should fail", modified); + } + + { // a past expiry should fail + parcel.reset(); + parcel.mAddSubKeys.add(new SubkeyAdd(algorithm.rsa, 1024, KeyFlags.SIGN_DATA, + new Date().getTime()/1000-10)); + + CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); + modified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); + + Assert.assertNull("creating subkey with past expiry date should fail", modified); + } + + } + + @Test + public void testSubkeyModify() throws Exception { + + long expiry = new Date().getTime()/1000 + 1024; + long keyId = KeyringTestingHelper.getSubkeyId(ring, 1); + + UncachedKeyRing modified = ring; + { + parcel.mChangeSubKeys.add(new SubkeyChange(keyId, null, expiry)); + modified = applyModificationWithChecks(parcel, modified, onlyA, onlyB); + + Assert.assertEquals("one extra packet in original", 1, onlyA.size()); + Assert.assertEquals("one extra packet in modified", 1, onlyB.size()); + + Assert.assertEquals("old packet must be signature", + PacketTags.SIGNATURE, onlyA.get(0).tag); + + Packet p = new BCPGInputStream(new ByteArrayInputStream(onlyB.get(0).buf)).readPacket(); + Assert.assertTrue("first new packet must be signature", p instanceof SignaturePacket); + Assert.assertEquals("signature type must be subkey binding certificate", + PGPSignature.SUBKEY_BINDING, ((SignaturePacket) p).getSignatureType()); + Assert.assertEquals("signature must have been created by master key", + ring.getMasterKeyId(), ((SignaturePacket) p).getKeyID()); + + Assert.assertNotNull("modified key must have an expiry date", + modified.getPublicKey(keyId).getExpiryTime()); + Assert.assertEquals("modified key must have expected expiry date", + expiry, modified.getPublicKey(keyId).getExpiryTime().getTime()/1000); + Assert.assertEquals("modified key must have same flags as before", + ring.getPublicKey(keyId).getKeyUsage(), modified.getPublicKey(keyId).getKeyUsage()); + } + + { + int flags = KeyFlags.SIGN_DATA | KeyFlags.ENCRYPT_COMMS; + parcel.reset(); + parcel.mChangeSubKeys.add(new SubkeyChange(keyId, flags, null)); + modified = applyModificationWithChecks(parcel, modified, onlyA, onlyB); + + Assert.assertEquals("old packet must be signature", + PacketTags.SIGNATURE, onlyA.get(0).tag); + + Packet p = new BCPGInputStream(new ByteArrayInputStream(onlyB.get(0).buf)).readPacket(); + Assert.assertTrue("first new packet must be signature", p instanceof SignaturePacket); + Assert.assertEquals("signature type must be subkey binding certificate", + PGPSignature.SUBKEY_BINDING, ((SignaturePacket) p).getSignatureType()); + Assert.assertEquals("signature must have been created by master key", + ring.getMasterKeyId(), ((SignaturePacket) p).getKeyID()); + + Assert.assertEquals("modified key must have expected flags", + flags, modified.getPublicKey(keyId).getKeyUsage()); + Assert.assertNotNull("key must retain its expiry", + modified.getPublicKey(keyId).getExpiryTime()); + Assert.assertEquals("key expiry must be unchanged", + expiry, modified.getPublicKey(keyId).getExpiryTime().getTime()/1000); + } + + { // a past expiry should fail + parcel.reset(); + parcel.mChangeSubKeys.add(new SubkeyChange(keyId, null, new Date().getTime()/1000-10)); + + CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); + modified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); + + Assert.assertNull("setting subkey expiry to a past date should fail", modified); + } + + { // modifying nonexistent keyring should fail + parcel.reset(); + parcel.mChangeSubKeys.add(new SubkeyChange(123, null, null)); + + CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); + modified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); + + Assert.assertNull("modifying non-existent subkey should fail", modified); + } + + } + + @Test + public void testSubkeyRevoke() throws Exception { + + long keyId = KeyringTestingHelper.getSubkeyId(ring, 1); + int flags = ring.getPublicKey(keyId).getKeyUsage(); + + UncachedKeyRing modified; + + { + + parcel.reset(); + parcel.mRevokeSubKeys.add(123L); + + CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); + UncachedKeyRing otherModified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); + + Assert.assertNull("revoking a nonexistent subkey should fail", otherModified); + + } + + { // revoked second subkey + + parcel.reset(); + parcel.mRevokeSubKeys.add(keyId); + + modified = applyModificationWithChecks(parcel, ring, onlyA, onlyB); + + Assert.assertEquals("no extra packets in original", 0, onlyA.size()); + Assert.assertEquals("exactly one extra packet in modified", 1, onlyB.size()); + + Packet p; + + p = new BCPGInputStream(new ByteArrayInputStream(onlyB.get(0).buf)).readPacket(); + Assert.assertTrue("first new packet must be secret subkey", p instanceof SignaturePacket); + Assert.assertEquals("signature type must be subkey binding certificate", + PGPSignature.SUBKEY_REVOCATION, ((SignaturePacket) p).getSignatureType()); + Assert.assertEquals("signature must have been created by master key", + ring.getMasterKeyId(), ((SignaturePacket) p).getKeyID()); + + Assert.assertTrue("subkey must actually be revoked", + modified.getPublicKey(keyId).isRevoked()); + } + + { // re-add second subkey + + parcel.reset(); + parcel.mChangeSubKeys.add(new SubkeyChange(keyId, null, null)); + + modified = applyModificationWithChecks(parcel, modified, onlyA, onlyB); + + Assert.assertEquals("exactly two outdated packets in original", 2, onlyA.size()); + Assert.assertEquals("exactly one extra packet in modified", 1, onlyB.size()); + + Packet p; + + p = new BCPGInputStream(new ByteArrayInputStream(onlyA.get(0).buf)).readPacket(); + Assert.assertTrue("first outdated packet must be signature", p instanceof SignaturePacket); + Assert.assertEquals("first outdated signature type must be subkey binding certification", + PGPSignature.SUBKEY_BINDING, ((SignaturePacket) p).getSignatureType()); + Assert.assertEquals("first outdated signature must have been created by master key", + ring.getMasterKeyId(), ((SignaturePacket) p).getKeyID()); + + p = new BCPGInputStream(new ByteArrayInputStream(onlyA.get(1).buf)).readPacket(); + Assert.assertTrue("second outdated packet must be signature", p instanceof SignaturePacket); + Assert.assertEquals("second outdated signature type must be subkey revocation", + PGPSignature.SUBKEY_REVOCATION, ((SignaturePacket) p).getSignatureType()); + Assert.assertEquals("second outdated signature must have been created by master key", + ring.getMasterKeyId(), ((SignaturePacket) p).getKeyID()); + + p = new BCPGInputStream(new ByteArrayInputStream(onlyB.get(0).buf)).readPacket(); + Assert.assertTrue("new packet must be signature ", p instanceof SignaturePacket); + Assert.assertEquals("new signature type must be subkey binding certification", + PGPSignature.SUBKEY_BINDING, ((SignaturePacket) p).getSignatureType()); + Assert.assertEquals("signature must have been created by master key", + ring.getMasterKeyId(), ((SignaturePacket) p).getKeyID()); + + Assert.assertFalse("subkey must no longer be revoked", + modified.getPublicKey(keyId).isRevoked()); + Assert.assertEquals("subkey must have the same usage flags as before", + flags, modified.getPublicKey(keyId).getKeyUsage()); + + } + } + + @Test + public void testUserIdRevoke() throws Exception { + + UncachedKeyRing modified; + String uid = ring.getPublicKey().getUnorderedUserIds().get(1); + + { // revoke second user id + + parcel.mRevokeUserIds.add(uid); + + modified = applyModificationWithChecks(parcel, ring, onlyA, onlyB); + + Assert.assertEquals("no extra packets in original", 0, onlyA.size()); + Assert.assertEquals("exactly one extra packet in modified", 1, onlyB.size()); + + Packet p; + + p = new BCPGInputStream(new ByteArrayInputStream(onlyB.get(0).buf)).readPacket(); + Assert.assertTrue("first new packet must be secret subkey", p instanceof SignaturePacket); + Assert.assertEquals("signature type must be subkey binding certificate", + PGPSignature.CERTIFICATION_REVOCATION, ((SignaturePacket) p).getSignatureType()); + Assert.assertEquals("signature must have been created by master key", + ring.getMasterKeyId(), ((SignaturePacket) p).getKeyID()); + + } + + { // re-add second user id + + parcel.reset(); + parcel.mChangePrimaryUserId = uid; + + CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(modified.getEncoded(), false, 0); + UncachedKeyRing otherModified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); + + Assert.assertNull("setting primary user id to a revoked user id should fail", otherModified); + + } + + { // re-add second user id + + parcel.reset(); + parcel.mAddUserIds.add(uid); + + applyModificationWithChecks(parcel, modified, onlyA, onlyB); + + Assert.assertEquals("exactly two outdated packets in original", 2, onlyA.size()); + Assert.assertEquals("exactly one extra packet in modified", 1, onlyB.size()); + + Packet p; + + p = new BCPGInputStream(new ByteArrayInputStream(onlyA.get(0).buf)).readPacket(); + Assert.assertTrue("first outdated packet must be signature", p instanceof SignaturePacket); + Assert.assertEquals("first outdated signature type must be positive certification", + PGPSignature.POSITIVE_CERTIFICATION, ((SignaturePacket) p).getSignatureType()); + Assert.assertEquals("first outdated signature must have been created by master key", + ring.getMasterKeyId(), ((SignaturePacket) p).getKeyID()); + + p = new BCPGInputStream(new ByteArrayInputStream(onlyA.get(1).buf)).readPacket(); + Assert.assertTrue("second outdated packet must be signature", p instanceof SignaturePacket); + Assert.assertEquals("second outdated signature type must be certificate revocation", + PGPSignature.CERTIFICATION_REVOCATION, ((SignaturePacket) p).getSignatureType()); + Assert.assertEquals("second outdated signature must have been created by master key", + ring.getMasterKeyId(), ((SignaturePacket) p).getKeyID()); + + p = new BCPGInputStream(new ByteArrayInputStream(onlyB.get(0).buf)).readPacket(); + Assert.assertTrue("new packet must be signature ", p instanceof SignaturePacket); + Assert.assertEquals("new signature type must be positive certification", + PGPSignature.POSITIVE_CERTIFICATION, ((SignaturePacket) p).getSignatureType()); + Assert.assertEquals("signature must have been created by master key", + ring.getMasterKeyId(), ((SignaturePacket) p).getKeyID()); + } + + } + + @Test + public void testUserIdAdd() throws Exception { + + { + parcel.mAddUserIds.add(""); + CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); + UncachedKeyRing modified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); + Assert.assertNull("adding an empty user id should fail", modified); + } + + parcel.reset(); + parcel.mAddUserIds.add("rainbow"); + + UncachedKeyRing modified = applyModificationWithChecks(parcel, ring, onlyA, onlyB); + + Assert.assertTrue("keyring must contain added user id", + modified.getPublicKey().getUnorderedUserIds().contains("rainbow")); + + Assert.assertEquals("no extra packets in original", 0, onlyA.size()); + Assert.assertEquals("exactly two extra packets in modified", 2, onlyB.size()); + + Assert.assertTrue("keyring must contain added user id", + modified.getPublicKey().getUnorderedUserIds().contains("rainbow")); + + Packet p; + + p = new BCPGInputStream(new ByteArrayInputStream(onlyB.get(0).buf)).readPacket(); + Assert.assertTrue("first new packet must be user id", p instanceof UserIDPacket); + Assert.assertEquals("user id packet must match added user id", + "rainbow", ((UserIDPacket) p).getID()); + + p = new BCPGInputStream(new ByteArrayInputStream(onlyB.get(1).buf)).readPacket(); + Assert.assertTrue("second new packet must be signature", p instanceof SignaturePacket); + Assert.assertEquals("signature type must be positive certification", + PGPSignature.POSITIVE_CERTIFICATION, ((SignaturePacket) p).getSignatureType()); + + } + + @Test + public void testUserIdPrimary() throws Exception { + + UncachedKeyRing modified = ring; + String uid = ring.getPublicKey().getUnorderedUserIds().get(1); + + { // first part, add new user id which is also primary + parcel.mAddUserIds.add("jack"); + parcel.mChangePrimaryUserId = "jack"; + + modified = applyModificationWithChecks(parcel, modified, onlyA, onlyB); + + Assert.assertEquals("primary user id must be the one added", + "jack", modified.getPublicKey().getPrimaryUserId()); + } + + { // second part, change primary to a different one + parcel.reset(); + parcel.mChangePrimaryUserId = uid; + + modified = applyModificationWithChecks(parcel, modified, onlyA, onlyB); + + Assert.assertEquals("old keyring must have two outdated certificates", 2, onlyA.size()); + Assert.assertEquals("new keyring must have two new packets", 2, onlyB.size()); + + Assert.assertEquals("primary user id must be the one changed to", + "pink", modified.getPublicKey().getPrimaryUserId()); + } + + { // third part, change primary to a non-existent one + parcel.reset(); + //noinspection SpellCheckingInspection + parcel.mChangePrimaryUserId = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; + if (parcel.mChangePrimaryUserId.equals(passphrase)) { + parcel.mChangePrimaryUserId += "A"; + } + + CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); + modified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); + + Assert.assertNull("changing primary user id to a non-existent one should fail", modified); + } + + // check for revoked primary user id already done in revoke test + + } + + + private static UncachedKeyRing applyModificationWithChecks(SaveKeyringParcel parcel, + UncachedKeyRing ring, + ArrayList onlyA, + ArrayList onlyB) { + return applyModificationWithChecks(parcel, ring, onlyA, onlyB, true, true); + } + + // applies a parcel modification while running some integrity checks + private static UncachedKeyRing applyModificationWithChecks(SaveKeyringParcel parcel, + UncachedKeyRing ring, + ArrayList onlyA, + ArrayList onlyB, + boolean canonicalize, + boolean constantCanonicalize) { + + try { + + Assert.assertTrue("modified keyring must be secret", ring.isSecret()); + CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); + + PgpKeyOperation op = new PgpKeyOperation(null); + UncachedKeyRing rawModified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); + Assert.assertNotNull("key modification failed", rawModified); + + if (!canonicalize) { + Assert.assertTrue("keyring must differ from original", KeyringTestingHelper.diffKeyrings( + ring.getEncoded(), rawModified.getEncoded(), onlyA, onlyB)); + return rawModified; + } + + CanonicalizedKeyRing modified = rawModified.canonicalize(new OperationLog(), 0); + if (constantCanonicalize) { + Assert.assertTrue("key must be constant through canonicalization", + !KeyringTestingHelper.diffKeyrings( + modified.getEncoded(), rawModified.getEncoded(), onlyA, onlyB) + ); + } + Assert.assertTrue("keyring must differ from original", KeyringTestingHelper.diffKeyrings( + ring.getEncoded(), modified.getEncoded(), onlyA, onlyB)); + + return modified.getUncachedKeyRing(); + + } catch (IOException e) { + throw new AssertionFailedError("error during encoding!"); + } + } + + @Test + public void testVerifySuccess() throws Exception { + + UncachedKeyRing expectedKeyRing = KeyringBuilder.correctRing(); + UncachedKeyRing inputKeyRing = KeyringBuilder.ringWithExtraIncorrectSignature(); + + CanonicalizedKeyRing canonicalized = inputKeyRing.canonicalize(new OperationLog(), 0); + Assert.assertNotNull("canonicalization must succeed", canonicalized); + + ArrayList onlyA = new ArrayList(); + ArrayList onlyB = new ArrayList(); + //noinspection unchecked + Assert.assertTrue("keyrings differ", !KeyringTestingHelper.diffKeyrings( + expectedKeyRing.getEncoded(), expectedKeyRing.getEncoded(), onlyA, onlyB)); + + } + + /** + * Just testing my own test code. Should really be using a library for this. + */ + @Test + public void testConcat() throws Exception { + byte[] actual = TestDataUtil.concatAll(new byte[]{1}, new byte[]{2,-2}, new byte[]{5},new byte[]{3}); + byte[] expected = new byte[]{1,2,-2,5,3}; + Assert.assertEquals(java.util.Arrays.toString(expected), java.util.Arrays.toString(actual)); + } + + +} diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/UncachedKeyringCanonicalizeTest.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/UncachedKeyringCanonicalizeTest.java new file mode 100644 index 000000000..24b9a3fb6 --- /dev/null +++ b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/UncachedKeyringCanonicalizeTest.java @@ -0,0 +1,622 @@ +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.RobolectricTestRunner; +import org.robolectric.shadows.ShadowLog; +import org.spongycastle.bcpg.BCPGInputStream; +import org.spongycastle.bcpg.Packet; +import org.spongycastle.bcpg.PacketTags; +import org.spongycastle.bcpg.UserIDPacket; +import org.spongycastle.bcpg.sig.KeyFlags; +import org.spongycastle.openpgp.PGPPrivateKey; +import org.spongycastle.openpgp.PGPPublicKey; +import org.spongycastle.openpgp.PGPSecretKey; +import org.spongycastle.openpgp.PGPSecretKeyRing; +import org.spongycastle.openpgp.PGPSignature; +import org.spongycastle.openpgp.PGPSignatureGenerator; +import org.spongycastle.openpgp.PGPSignatureSubpacketGenerator; +import org.spongycastle.openpgp.PGPUtil; +import org.spongycastle.openpgp.operator.PBESecretKeyDecryptor; +import org.spongycastle.openpgp.operator.PGPContentSignerBuilder; +import org.spongycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator; +import org.spongycastle.openpgp.operator.jcajce.JcaPGPContentSignerBuilder; +import org.spongycastle.openpgp.operator.jcajce.JcePBESecretKeyDecryptorBuilder; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.service.OperationResultParcel; +import org.sufficientlysecure.keychain.service.OperationResults.EditKeyResult; +import org.sufficientlysecure.keychain.service.SaveKeyringParcel; +import org.sufficientlysecure.keychain.support.KeyringTestingHelper; +import org.sufficientlysecure.keychain.support.KeyringTestingHelper.RawPacket; + +import java.io.ByteArrayInputStream; +import java.util.ArrayList; +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(RobolectricTestRunner.class) +@org.robolectric.annotation.Config(emulateSdk = 18) // Robolectric doesn't yet support 19 +public class UncachedKeyringCanonicalizeTest { + + static UncachedKeyRing staticRing; + static int totalPackets; + UncachedKeyRing ring; + ArrayList onlyA = new ArrayList(); + ArrayList onlyB = new ArrayList(); + OperationResultParcel.OperationLog log = new OperationResultParcel.OperationLog(); + PGPSignatureSubpacketGenerator subHashedPacketsGen; + PGPSecretKey secretKey; + + @BeforeClass + public static void setUpOnce() throws Exception { + ShadowLog.stream = System.out; + + SaveKeyringParcel parcel = new SaveKeyringParcel(); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.CERTIFY_OTHER, null)); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.SIGN_DATA, null)); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.ENCRYPT_COMMS, null)); + + parcel.mAddUserIds.add("twi"); + parcel.mAddUserIds.add("pink"); + // passphrase is tested in PgpKeyOperationTest, just use empty here + parcel.mNewPassphrase = ""; + PgpKeyOperation op = new PgpKeyOperation(null); + + EditKeyResult 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); + + // just for later reference + totalPackets = 9; + + // 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 it = KeyringTestingHelper.parseKeyring(ring.getEncoded()); + + Assert.assertEquals("packet #1 should be secret key", + PacketTags.SECRET_KEY, it.next().tag); + + Assert.assertEquals("packet #2 should be user id", + PacketTags.USER_ID, it.next().tag); + Assert.assertEquals("packet #3 should be signature", + PacketTags.SIGNATURE, it.next().tag); + + Assert.assertEquals("packet #4 should be user id", + PacketTags.USER_ID, it.next().tag); + Assert.assertEquals("packet #5 should be signature", + PacketTags.SIGNATURE, it.next().tag); + + Assert.assertEquals("packet #6 should be secret subkey", + PacketTags.SECRET_SUBKEY, it.next().tag); + Assert.assertEquals("packet #7 should be signature", + PacketTags.SIGNATURE, it.next().tag); + + Assert.assertEquals("packet #8 should be secret subkey", + PacketTags.SECRET_SUBKEY, it.next().tag); + Assert.assertEquals("packet #9 should be signature", + PacketTags.SIGNATURE, it.next().tag); + + Assert.assertFalse("exactly 9 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.getSignaturesForId("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 testSignatureBroken() throws Exception { + + injectEverytype(secretKey, ring, subHashedPacketsGen, true); + + } + + @Test public void testForeignSignature() throws Exception { + + SaveKeyringParcel parcel = new SaveKeyringParcel(); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.CERTIFY_OTHER, null)); + parcel.mAddUserIds.add("trix"); + PgpKeyOperation op = new PgpKeyOperation(null); + + OperationResultParcel.OperationLog log = new OperationResultParcel.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 + subHashedPacketsGen.setSignatureCreationTime(false, new Date(new Date().getTime() + 1000 * 1000)); + + injectEverytype(secretKey, ring, subHashedPacketsGen); + + + } + + @Test public void testSignatureLocal() throws Exception { + + // generate future + subHashedPacketsGen.setSignatureCreationTime(false, new Date()); + 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, 6); + + // 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); + Assert.assertTrue("second subkey must be able to sign", pKey.canSign()); + + 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(), 6); + + // 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(), 6); + + // 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(), 8); + modified = KeyringTestingHelper.injectPacket(modified, sig2.getEncoded(), 9); + modified = KeyringTestingHelper.injectPacket(modified, sig1.getEncoded(), 10); + modified = KeyringTestingHelper.injectPacket(modified, sig3.getEncoded(), 11); + + // 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); + + } + + 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 { + + OperationResultParcel.OperationLog log = new OperationResultParcel.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); + + } + +} diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/UncachedKeyringMergeTest.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/UncachedKeyringMergeTest.java new file mode 100644 index 000000000..6b19e3c55 --- /dev/null +++ b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/UncachedKeyringMergeTest.java @@ -0,0 +1,390 @@ +package org.sufficientlysecure.keychain.pgp; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.shadows.ShadowLog; +import org.spongycastle.bcpg.PacketTags; +import org.spongycastle.bcpg.sig.KeyFlags; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.service.OperationResultParcel; +import org.sufficientlysecure.keychain.service.OperationResults.EditKeyResult; +import org.sufficientlysecure.keychain.service.SaveKeyringParcel; +import org.sufficientlysecure.keychain.support.KeyringTestingHelper; +import org.sufficientlysecure.keychain.support.KeyringTestingHelper.RawPacket; +import org.sufficientlysecure.keychain.util.ProgressScaler; + +import java.util.ArrayList; +import java.util.Iterator; + +/** Tests for the UncachedKeyring.merge method. + * + * This is another complex, crypto-related method. It merges information from one keyring into + * another, keeping information from the base (ie, called object) keyring in case of conflicts. + * The types of keys may be Public or Secret and can be mixed, For mixed types the result type + * will be the same as the base keyring. + * + * Test cases: + * - Merging keyrings with different masterKeyIds should fail + * - Merging a key with itself should be a no-operation + * - Merging a key with an extra revocation certificate, it should have that certificate + * - Merging a key with an extra user id, it should have that extra user id and its certificates + * - Merging a key with an extra user id certificate, it should have that certificate + * - Merging a key with an extra subkey, it should have that subkey + * - Merging a key with an extra subkey certificate, it should have that certificate + * - All of the above operations should work regardless of the key types. This means in particular + * that for new subkeys, an equivalent subkey of the proper type must be generated. + * - In case of two secret keys with the same id but different S2K, the key of the base keyring + * should be preferred (TODO or should it?) + * + * Note that the merge operation does not care about certificate validity, a bad certificate or + * packet will be copied regardless. Filtering out bad packets is done with canonicalization. + * + */ +@RunWith(RobolectricTestRunner.class) +@org.robolectric.annotation.Config(emulateSdk = 18) // Robolectric doesn't yet support 19 +public class UncachedKeyringMergeTest { + + static UncachedKeyRing staticRingA, staticRingB; + UncachedKeyRing ringA, ringB; + ArrayList onlyA = new ArrayList(); + ArrayList onlyB = new ArrayList(); + OperationResultParcel.OperationLog log = new OperationResultParcel.OperationLog(); + PgpKeyOperation op; + SaveKeyringParcel parcel; + + @BeforeClass + public static void setUpOnce() throws Exception { + ShadowLog.stream = System.out; + + { + SaveKeyringParcel parcel = new SaveKeyringParcel(); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.CERTIFY_OTHER, null)); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.SIGN_DATA, null)); + + parcel.mAddUserIds.add("twi"); + parcel.mAddUserIds.add("pink"); + // passphrase is tested in PgpKeyOperationTest, just use empty here + parcel.mNewPassphrase = ""; + PgpKeyOperation op = new PgpKeyOperation(null); + + OperationResultParcel.OperationLog log = new OperationResultParcel.OperationLog(); + + EditKeyResult result = op.createSecretKeyRing(parcel); + staticRingA = result.getRing(); + } + + { + SaveKeyringParcel parcel = new SaveKeyringParcel(); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.CERTIFY_OTHER, null)); + + parcel.mAddUserIds.add("shy"); + // passphrase is tested in PgpKeyOperationTest, just use empty here + parcel.mNewPassphrase = ""; + PgpKeyOperation op = new PgpKeyOperation(null); + + OperationResultParcel.OperationLog log = new OperationResultParcel.OperationLog(); + EditKeyResult result = op.createSecretKeyRing(parcel); + staticRingB = result.getRing(); + } + + Assert.assertNotNull("initial test key creation must succeed", staticRingA); + Assert.assertNotNull("initial test key creation must succeed", staticRingB); + + // 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; + ringA = staticRingA; + ringB = staticRingB; + + // setting up some parameters just to reduce code duplication + op = new PgpKeyOperation(new ProgressScaler(null, 0, 100, 100)); + + // set this up, gonna need it more than once + parcel = new SaveKeyringParcel(); + parcel.mMasterKeyId = ringA.getMasterKeyId(); + parcel.mFingerprint = ringA.getFingerprint(); + } + + public void testSelfNoOp() throws Exception { + + UncachedKeyRing merged = mergeWithChecks(ringA, ringA, null); + Assert.assertArrayEquals("keyring merged with itself must be identical", + ringA.getEncoded(), merged.getEncoded() + ); + + } + + @Test + public void testDifferentMasterKeyIds() throws Exception { + + Assert.assertNotEquals("generated key ids must be different", + ringA.getMasterKeyId(), ringB.getMasterKeyId()); + + Assert.assertNull("merging keys with differing key ids must fail", + ringA.merge(ringB, log, 0)); + Assert.assertNull("merging keys with differing key ids must fail", + ringB.merge(ringA, log, 0)); + + } + + @Test + public void testAddedUserId() throws Exception { + + UncachedKeyRing modifiedA, modifiedB; { + CanonicalizedSecretKeyRing secretRing = + new CanonicalizedSecretKeyRing(ringA.getEncoded(), false, 0); + + parcel.reset(); + parcel.mAddUserIds.add("flim"); + modifiedA = op.modifySecretKeyRing(secretRing, parcel, "").getRing(); + + parcel.reset(); + parcel.mAddUserIds.add("flam"); + modifiedB = op.modifySecretKeyRing(secretRing, parcel, "").getRing(); + } + + { // merge A into base + UncachedKeyRing merged = mergeWithChecks(ringA, modifiedA); + + Assert.assertEquals("merged keyring must have lost no packets", 0, onlyA.size()); + Assert.assertEquals("merged keyring must have gained two packets", 2, onlyB.size()); + Assert.assertTrue("merged keyring must contain new user id", + merged.getPublicKey().getUnorderedUserIds().contains("flim")); + } + + { // merge A into B + UncachedKeyRing merged = mergeWithChecks(modifiedA, modifiedB, ringA); + + Assert.assertEquals("merged keyring must have lost no packets", 0, onlyA.size()); + Assert.assertEquals("merged keyring must have gained four packets", 4, onlyB.size()); + Assert.assertTrue("merged keyring must contain first new user id", + merged.getPublicKey().getUnorderedUserIds().contains("flim")); + Assert.assertTrue("merged keyring must contain second new user id", + merged.getPublicKey().getUnorderedUserIds().contains("flam")); + + } + + } + + @Test + public void testAddedSubkeyId() throws Exception { + + UncachedKeyRing modifiedA, modifiedB; + long subKeyIdA, subKeyIdB; + { + CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ringA.getEncoded(), false, 0); + + parcel.reset(); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.SIGN_DATA, null)); + modifiedA = op.modifySecretKeyRing(secretRing, parcel, "").getRing(); + modifiedB = op.modifySecretKeyRing(secretRing, parcel, "").getRing(); + + subKeyIdA = KeyringTestingHelper.getSubkeyId(modifiedA, 2); + subKeyIdB = KeyringTestingHelper.getSubkeyId(modifiedB, 2); + + } + + { + UncachedKeyRing merged = mergeWithChecks(ringA, modifiedA); + + Assert.assertEquals("merged keyring must have lost no packets", 0, onlyA.size()); + Assert.assertEquals("merged keyring must have gained two packets", 2, onlyB.size()); + + long mergedKeyId = KeyringTestingHelper.getSubkeyId(merged, 2); + Assert.assertEquals("merged keyring must contain the new subkey", subKeyIdA, mergedKeyId); + } + + { + UncachedKeyRing merged = mergeWithChecks(modifiedA, modifiedB, ringA); + + Assert.assertEquals("merged keyring must have lost no packets", 0, onlyA.size()); + Assert.assertEquals("merged keyring must have gained four packets", 4, onlyB.size()); + + Iterator it = merged.getPublicKeys(); + it.next(); it.next(); + Assert.assertEquals("merged keyring must contain the new subkey", + subKeyIdA, it.next().getKeyId()); + Assert.assertEquals("merged keyring must contain both new subkeys", + subKeyIdB, it.next().getKeyId()); + } + + } + + @Test + public void testAddedKeySignature() throws Exception { + + final UncachedKeyRing modified; { + parcel.reset(); + parcel.mRevokeSubKeys.add(KeyringTestingHelper.getSubkeyId(ringA, 1)); + CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing( + ringA.getEncoded(), false, 0); + modified = op.modifySecretKeyRing(secretRing, parcel, "").getRing(); + } + + { + UncachedKeyRing merged = ringA.merge(modified, log, 0); + Assert.assertNotNull("merge must succeed", merged); + Assert.assertFalse( + "merging keyring with extra signatures into its base should yield that same keyring", + KeyringTestingHelper.diffKeyrings(merged.getEncoded(), modified.getEncoded(), onlyA, onlyB) + ); + } + + } + + @Test + public void testAddedUserIdSignature() throws Exception { + + final UncachedKeyRing pubRing = ringA.extractPublicKeyRing(); + + final UncachedKeyRing modified; { + CanonicalizedPublicKeyRing publicRing = new CanonicalizedPublicKeyRing( + pubRing.getEncoded(), 0); + + CanonicalizedSecretKey secretKey = new CanonicalizedSecretKeyRing( + ringB.getEncoded(), false, 0).getSecretKey(); + secretKey.unlock(""); + // sign all user ids + modified = secretKey.certifyUserIds(publicRing, publicRing.getPublicKey().getUnorderedUserIds()); + } + + { + UncachedKeyRing merged = ringA.merge(modified, log, 0); + Assert.assertNotNull("merge must succeed", merged); + Assert.assertArrayEquals("foreign signatures should not be merged into secret key", + ringA.getEncoded(), merged.getEncoded() + ); + } + + { + byte[] sig = KeyringTestingHelper.getNth( + modified.getPublicKey().getSignaturesForId("twi"), 1).getEncoded(); + + // inject the (foreign!) signature into subkey signature position + UncachedKeyRing moreModified = KeyringTestingHelper.injectPacket(modified, sig, 1); + + UncachedKeyRing merged = ringA.merge(moreModified, log, 0); + Assert.assertNotNull("merge must succeed", merged); + Assert.assertArrayEquals("foreign signatures should not be merged into secret key", + ringA.getEncoded(), merged.getEncoded() + ); + + merged = pubRing.merge(moreModified, log, 0); + Assert.assertNotNull("merge must succeed", merged); + Assert.assertTrue( + "merged keyring should contain new signature", + KeyringTestingHelper.diffKeyrings(pubRing.getEncoded(), merged.getEncoded(), onlyA, onlyB) + ); + Assert.assertEquals("merged keyring should be missing no packets", 0, onlyA.size()); + Assert.assertEquals("merged keyring should contain exactly two more packets", 2, onlyB.size()); + Assert.assertEquals("first added packet should be a signature", + PacketTags.SIGNATURE, onlyB.get(0).tag); + Assert.assertEquals("first added packet should be in the position we injected it at", + 1, onlyB.get(0).position); + Assert.assertEquals("second added packet should be a signature", + PacketTags.SIGNATURE, onlyB.get(1).tag); + + } + + { + UncachedKeyRing merged = pubRing.merge(modified, log, 0); + Assert.assertNotNull("merge must succeed", merged); + Assert.assertFalse( + "merging keyring with extra signatures into its base should yield that same keyring", + KeyringTestingHelper.diffKeyrings(merged.getEncoded(), modified.getEncoded(), onlyA, onlyB) + ); + } + } + + private UncachedKeyRing mergeWithChecks(UncachedKeyRing a, UncachedKeyRing b) + throws Exception { + return mergeWithChecks(a, b, a); + } + + private UncachedKeyRing mergeWithChecks(UncachedKeyRing a, UncachedKeyRing b, + UncachedKeyRing base) + throws Exception { + + Assert.assertTrue("merging keyring must be secret type", a.isSecret()); + Assert.assertTrue("merged keyring must be secret type", b.isSecret()); + + final UncachedKeyRing resultA; + UncachedKeyRing resultB; + + { // sec + sec + resultA = a.merge(b, log, 0); + Assert.assertNotNull("merge must succeed as sec(a)+sec(b)", resultA); + + resultB = b.merge(a, log, 0); + Assert.assertNotNull("merge must succeed as sec(b)+sec(a)", resultB); + + // check commutativity, if requested + Assert.assertFalse("result of merge must be commutative", + KeyringTestingHelper.diffKeyrings( + resultA.getEncoded(), resultB.getEncoded(), onlyA, onlyB) + ); + } + + final UncachedKeyRing pubA = a.extractPublicKeyRing(); + final UncachedKeyRing pubB = b.extractPublicKeyRing(); + + { // sec + pub, pub + sec, and pub + pub + + try { + resultB = a.merge(pubB, log, 0); + Assert.assertNotNull("merge must succeed as sec(a)+pub(b)", resultA); + + Assert.assertFalse("result of sec(a)+pub(b) must be same as sec(a)+sec(b)", + KeyringTestingHelper.diffKeyrings( + resultA.getEncoded(), resultB.getEncoded(), onlyA, onlyB) + ); + } catch (RuntimeException e) { + System.out.println("special case, dummy key generation not in yet"); + } + + final UncachedKeyRing pubResult = resultA.extractPublicKeyRing(); + + resultB = pubA.merge(b, log, 0); + Assert.assertNotNull("merge must succeed as pub(a)+sec(b)", resultA); + + Assert.assertFalse("result of pub(a)+sec(b) must be same as pub(sec(a)+sec(b))", + KeyringTestingHelper.diffKeyrings( + pubResult.getEncoded(), resultB.getEncoded(), onlyA, onlyB) + ); + + resultB = pubA.merge(pubB, log, 0); + Assert.assertNotNull("merge must succeed as pub(a)+pub(b)", resultA); + + Assert.assertFalse("result of pub(a)+pub(b) must be same as pub(sec(a)+sec(b))", + KeyringTestingHelper.diffKeyrings( + pubResult.getEncoded(), resultB.getEncoded(), onlyA, onlyB) + ); + + } + + if (base != null) { + // set up onlyA and onlyB to be a diff to the base + Assert.assertTrue("merged keyring must differ from base", + KeyringTestingHelper.diffKeyrings( + base.getEncoded(), resultA.getEncoded(), onlyA, onlyB) + ); + } + + return resultA; + + } + +} diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/UncachedKeyringTest.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/UncachedKeyringTest.java new file mode 100644 index 000000000..e0772a7dc --- /dev/null +++ b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/UncachedKeyringTest.java @@ -0,0 +1,119 @@ +package org.sufficientlysecure.keychain.pgp; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.shadows.ShadowLog; +import org.spongycastle.bcpg.sig.KeyFlags; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; +import org.sufficientlysecure.keychain.service.OperationResults.EditKeyResult; +import org.sufficientlysecure.keychain.service.SaveKeyringParcel; +import org.sufficientlysecure.keychain.support.KeyringTestingHelper.RawPacket; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.Iterator; + +@RunWith(RobolectricTestRunner.class) +@org.robolectric.annotation.Config(emulateSdk = 18) // Robolectric doesn't yet support 19 +public class UncachedKeyringTest { + + static UncachedKeyRing staticRing, staticPubRing; + UncachedKeyRing ring, pubRing; + ArrayList onlyA = new ArrayList(); + ArrayList onlyB = new ArrayList(); + PgpKeyOperation op; + SaveKeyringParcel parcel; + + @BeforeClass + public static void setUpOnce() throws Exception { + ShadowLog.stream = System.out; + + SaveKeyringParcel parcel = new SaveKeyringParcel(); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.CERTIFY_OTHER, null)); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.SIGN_DATA, null)); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.ENCRYPT_COMMS, null)); + + parcel.mAddUserIds.add("twi"); + parcel.mAddUserIds.add("pink"); + // passphrase is tested in PgpKeyOperationTest, just use empty here + parcel.mNewPassphrase = ""; + PgpKeyOperation op = new PgpKeyOperation(null); + + EditKeyResult result = op.createSecretKeyRing(parcel); + staticRing = result.getRing(); + staticPubRing = staticRing.extractPublicKeyRing(); + + Assert.assertNotNull("initial test key creation must succeed", staticRing); + + // 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; + pubRing = staticPubRing; + } + + @Test(expected = UnsupportedOperationException.class) + public void testPublicKeyItRemove() throws Exception { + Iterator it = ring.getPublicKeys(); + it.remove(); + } + + @Test(expected = PgpGeneralException.class) + public void testDecodeFromEmpty() throws Exception { + UncachedKeyRing.decodeFromData(new byte[0]); + } + + @Test + public void testArmorIdentity() throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ring.encodeArmored(out, "OpenKeychain"); + + Assert.assertArrayEquals("armor encoded and decoded ring should be identical to original", + ring.getEncoded(), + UncachedKeyRing.decodeFromData(out.toByteArray()).getEncoded()); + } + + @Test(expected = PgpGeneralException.class) + public void testDecodeEncodeMulti() throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + // encode secret and public ring in here + ring.encodeArmored(out, "OpenKeychain"); + pubRing.encodeArmored(out, "OpenKeychain"); + + Iterator it = + UncachedKeyRing.fromStream(new ByteArrayInputStream(out.toByteArray())); + Assert.assertTrue("there should be two rings in the stream", it.hasNext()); + Assert.assertArrayEquals("first ring should be the first we put in", + ring.getEncoded(), it.next().getEncoded()); + Assert.assertTrue("there should be two rings in the stream", it.hasNext()); + Assert.assertArrayEquals("second ring should be the second we put in", + pubRing.getEncoded(), it.next().getEncoded()); + Assert.assertFalse("there should be two rings in the stream", it.hasNext()); + + // this should fail with PgpGeneralException, since it expects exactly one ring + UncachedKeyRing.decodeFromData(out.toByteArray()); + } + + @Test(expected = RuntimeException.class) + public void testPublicExtractPublic() throws Exception { + // can't do this, either! + pubRing.extractPublicKeyRing(); + } + +} diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/provider/ProviderHelperKeyringTest.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/provider/ProviderHelperKeyringTest.java new file mode 100644 index 000000000..b0f47af29 --- /dev/null +++ b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/provider/ProviderHelperKeyringTest.java @@ -0,0 +1,101 @@ +/* + * Copyright (C) Art O Cathain + * + * 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 . + */ + +package org.sufficientlysecure.keychain.provider; + +import java.util.Collections; +import java.util.Arrays; +import java.util.Collection; +import java.util.ArrayList; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.*; +import org.sufficientlysecure.keychain.support.KeyringTestingHelper; + +@RunWith(RobolectricTestRunner.class) +@org.robolectric.annotation.Config(emulateSdk = 18) // Robolectric doesn't yet support 19 +public class ProviderHelperKeyringTest { + + @Test + public void testSavePublicKeyring() throws Exception { + Assert.assertTrue(new KeyringTestingHelper(Robolectric.application).addKeyring(Collections.singleton( + "/public-key-for-sample.blob" + ))); + } + + // @Test + public void testSavePublicKeyringRsa() throws Exception { + Assert.assertTrue(new KeyringTestingHelper(Robolectric.application).addKeyring(prependResourcePath(Arrays.asList( + "000001-006.public_key", + "000002-013.user_id", + "000003-002.sig", + "000004-012.ring_trust", + "000005-002.sig", + "000006-012.ring_trust", + "000007-002.sig", + "000008-012.ring_trust", + "000009-002.sig", + "000010-012.ring_trust", + "000011-002.sig", + "000012-012.ring_trust", + "000013-014.public_subkey", + "000014-002.sig", + "000015-012.ring_trust" + )))); + } + + // @Test + public void testSavePublicKeyringDsa() throws Exception { + Assert.assertTrue(new KeyringTestingHelper(Robolectric.application).addKeyring(prependResourcePath(Arrays.asList( + "000016-006.public_key", + "000017-002.sig", + "000018-012.ring_trust", + "000019-013.user_id", + "000020-002.sig", + "000021-012.ring_trust", + "000022-002.sig", + "000023-012.ring_trust", + "000024-014.public_subkey", + "000025-002.sig", + "000026-012.ring_trust" + )))); + } + + // @Test + public void testSavePublicKeyringDsa2() throws Exception { + Assert.assertTrue(new KeyringTestingHelper(Robolectric.application).addKeyring(prependResourcePath(Arrays.asList( + "000027-006.public_key", + "000028-002.sig", + "000029-012.ring_trust", + "000030-013.user_id", + "000031-002.sig", + "000032-012.ring_trust", + "000033-002.sig", + "000034-012.ring_trust" + )))); + } + + private static Collection prependResourcePath(Collection files) { + Collection prependedFiles = new ArrayList(); + for (String file: files) { + prependedFiles.add("/OpenPGP-Haskell/tests/data/" + file); + } + return prependedFiles; + } +} diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/PgpDecryptVerifyTest.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/PgpDecryptVerifyTest.java deleted file mode 100644 index 158650012..000000000 --- a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/PgpDecryptVerifyTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) Art O Cathain - * - * 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 . - */ - -package tests; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.*; -import org.openintents.openpgp.OpenPgpSignatureResult; -import org.sufficientlysecure.keychain.support.PgpVerifyTestingHelper; - -@RunWith(RobolectricTestRunner.class) -@org.robolectric.annotation.Config(emulateSdk = 18) // Robolectric doesn't yet support 19 -public class PgpDecryptVerifyTest { - - @Test - public void testVerifySuccess() throws Exception { - - String testFileName = "/sample.txt"; - int expectedSignatureResult = OpenPgpSignatureResult.SIGNATURE_SUCCESS_UNCERTIFIED; - - int status = new PgpVerifyTestingHelper(Robolectric.application).doTestFile(testFileName); - - Assert.assertEquals(expectedSignatureResult, status); - } - - @Test - public void testVerifyFailure() throws Exception { - - String testFileName = "/sample-altered.txt"; - int expectedSignatureResult = OpenPgpSignatureResult.SIGNATURE_ERROR; - - int status = new PgpVerifyTestingHelper(Robolectric.application).doTestFile(testFileName); - - Assert.assertEquals(expectedSignatureResult, status); - } - -} diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/PgpKeyOperationTest.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/PgpKeyOperationTest.java deleted file mode 100644 index 4f6694049..000000000 --- a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/PgpKeyOperationTest.java +++ /dev/null @@ -1,770 +0,0 @@ -package org.sufficientlysecure.keychain.tests; - -import junit.framework.AssertionFailedError; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.runner.RunWith; -import org.robolectric.*; -import org.robolectric.shadows.ShadowLog; -import org.spongycastle.bcpg.BCPGInputStream; -import org.spongycastle.bcpg.Packet; -import org.spongycastle.bcpg.PacketTags; -import org.spongycastle.bcpg.SecretSubkeyPacket; -import org.spongycastle.bcpg.SignaturePacket; -import org.spongycastle.bcpg.UserIDPacket; -import org.spongycastle.bcpg.sig.KeyFlags; -import org.spongycastle.openpgp.PGPSignature; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.Constants.choice.algorithm; -import org.sufficientlysecure.keychain.pgp.CanonicalizedKeyRing; -import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKeyRing; -import org.sufficientlysecure.keychain.pgp.PgpKeyOperation; -import org.sufficientlysecure.keychain.pgp.UncachedKeyRing; -import org.sufficientlysecure.keychain.pgp.UncachedPublicKey; -import org.sufficientlysecure.keychain.pgp.WrappedSignature; -import org.sufficientlysecure.keychain.service.OperationResultParcel.OperationLog; -import org.sufficientlysecure.keychain.service.SaveKeyringParcel; -import org.sufficientlysecure.keychain.service.SaveKeyringParcel.SubkeyAdd; -import org.sufficientlysecure.keychain.service.SaveKeyringParcel.SubkeyChange; -import org.sufficientlysecure.keychain.support.KeyringBuilder; -import org.sufficientlysecure.keychain.support.KeyringTestingHelper; -import org.sufficientlysecure.keychain.support.KeyringTestingHelper.RawPacket; -import org.sufficientlysecure.keychain.support.TestDataUtil; -import org.sufficientlysecure.keychain.util.ProgressScaler; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; -import java.util.Random; - -@RunWith(RobolectricTestRunner.class) -@org.robolectric.annotation.Config(emulateSdk = 18) // Robolectric doesn't yet support 19 -public class PgpKeyOperationTest { - - static UncachedKeyRing staticRing; - static String passphrase; - - UncachedKeyRing ring; - PgpKeyOperation op; - SaveKeyringParcel parcel; - ArrayList onlyA = new ArrayList(); - ArrayList onlyB = new ArrayList(); - - @BeforeClass public static void setUpOnce() throws Exception { - ShadowLog.stream = System.out; - - { - String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789!@#$%^&*()-_="; - Random r = new Random(); - StringBuilder passbuilder = new StringBuilder(); - // 20% chance for an empty passphrase - for(int i = 0, j = r.nextInt(10) > 2 ? r.nextInt(20) : 0; i < j; i++) { - passbuilder.append(chars.charAt(r.nextInt(chars.length()))); - } - passphrase = passbuilder.toString(); - System.out.println("Passphrase is '" + passphrase + "'"); - } - - SaveKeyringParcel parcel = new SaveKeyringParcel(); - parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( - Constants.choice.algorithm.rsa, 1024, KeyFlags.CERTIFY_OTHER, null)); - parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( - Constants.choice.algorithm.rsa, 1024, KeyFlags.SIGN_DATA, null)); - parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( - Constants.choice.algorithm.rsa, 1024, KeyFlags.ENCRYPT_COMMS, null)); - - parcel.mAddUserIds.add("twi"); - parcel.mAddUserIds.add("pink"); - parcel.mNewPassphrase = passphrase; - PgpKeyOperation op = new PgpKeyOperation(null); - - staticRing = op.createSecretKeyRing(parcel).getRing(); - - Assert.assertNotNull("initial test key creation must succeed", staticRing); - - // 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; - - // setting up some parameters just to reduce code duplication - op = new PgpKeyOperation(new ProgressScaler(null, 0, 100, 100)); - - // set this up, gonna need it more than once - parcel = new SaveKeyringParcel(); - parcel.mMasterKeyId = ring.getMasterKeyId(); - parcel.mFingerprint = ring.getFingerprint(); - - } - - @Test - public void createSecretKeyRingTests() { - - { - parcel.reset(); - parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( - Constants.choice.algorithm.rsa, new Random().nextInt(256)+255, KeyFlags.CERTIFY_OTHER, null)); - parcel.mAddUserIds.add("shy"); - parcel.mNewPassphrase = passphrase; - - UncachedKeyRing ring = op.createSecretKeyRing(parcel).getRing(); - - Assert.assertNull("creating ring with < 512 bytes keysize should fail", ring); - } - - { - parcel.reset(); - parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( - Constants.choice.algorithm.elgamal, 1024, KeyFlags.CERTIFY_OTHER, null)); - parcel.mAddUserIds.add("shy"); - parcel.mNewPassphrase = passphrase; - - UncachedKeyRing ring = op.createSecretKeyRing(parcel).getRing(); - - Assert.assertNull("creating ring with ElGamal master key should fail", ring); - } - - { - parcel.reset(); - parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( - 12345, 1024, KeyFlags.CERTIFY_OTHER, null)); - parcel.mAddUserIds.add("shy"); - parcel.mNewPassphrase = passphrase; - - UncachedKeyRing ring = op.createSecretKeyRing(parcel).getRing(); - Assert.assertNull("creating ring with bad algorithm choice should fail", ring); - } - - { - parcel.reset(); - parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( - Constants.choice.algorithm.rsa, 1024, KeyFlags.SIGN_DATA, null)); - parcel.mAddUserIds.add("shy"); - parcel.mNewPassphrase = passphrase; - - UncachedKeyRing ring = op.createSecretKeyRing(parcel).getRing(); - Assert.assertNull("creating ring with non-certifying master key should fail", ring); - } - - { - parcel.reset(); - parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( - Constants.choice.algorithm.rsa, 1024, KeyFlags.CERTIFY_OTHER, null)); - parcel.mNewPassphrase = passphrase; - - UncachedKeyRing ring = op.createSecretKeyRing(parcel).getRing(); - Assert.assertNull("creating ring without user ids should fail", ring); - } - - { - parcel.reset(); - parcel.mAddUserIds.add("shy"); - parcel.mNewPassphrase = passphrase; - - UncachedKeyRing ring = op.createSecretKeyRing(parcel).getRing(); - Assert.assertNull("creating ring without subkeys should fail", ring); - } - - } - - @Test - // this is a special case since the flags are in user id certificates rather than - // subkey binding certificates - public void testMasterFlags() throws Exception { - SaveKeyringParcel parcel = new SaveKeyringParcel(); - parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( - Constants.choice.algorithm.rsa, 1024, KeyFlags.CERTIFY_OTHER | KeyFlags.SIGN_DATA, null)); - parcel.mAddUserIds.add("luna"); - ring = op.createSecretKeyRing(parcel).getRing(); - - Assert.assertEquals("the keyring should contain only the master key", - 1, KeyringTestingHelper.itToList(ring.getPublicKeys()).size()); - Assert.assertEquals("first (master) key must have both flags", - KeyFlags.CERTIFY_OTHER | KeyFlags.SIGN_DATA, ring.getPublicKey().getKeyUsage()); - - } - - @Test - public void testCreatedKey() throws Exception { - - // an empty modification should change nothing. this also ensures the keyring - // is constant through canonicalization. - // applyModificationWithChecks(parcel, ring, onlyA, onlyB); - - Assert.assertNotNull("key creation failed", ring); - - Assert.assertNull("primary user id must be empty", - ring.getPublicKey().getPrimaryUserId()); - - Assert.assertEquals("number of user ids must be two", - 2, ring.getPublicKey().getUnorderedUserIds().size()); - - Assert.assertEquals("number of subkeys must be three", - 3, KeyringTestingHelper.itToList(ring.getPublicKeys()).size()); - - Assert.assertTrue("key ring should have been created in the last 120 seconds", - ring.getPublicKey().getCreationTime().after(new Date(new Date().getTime()-1000*120))); - - Assert.assertNull("key ring should not expire", - ring.getPublicKey().getExpiryTime()); - - Iterator it = ring.getPublicKeys(); - - Assert.assertEquals("first (master) key can certify", - KeyFlags.CERTIFY_OTHER, it.next().getKeyUsage()); - - UncachedPublicKey signingKey = it.next(); - Assert.assertEquals("second key can sign", - KeyFlags.SIGN_DATA, signingKey.getKeyUsage()); - ArrayList sigs = signingKey.getSignatures().next().getEmbeddedSignatures(); - Assert.assertEquals("signing key signature should have one embedded signature", - 1, sigs.size()); - Assert.assertEquals("embedded signature should be of primary key binding type", - PGPSignature.PRIMARYKEY_BINDING, sigs.get(0).getSignatureType()); - Assert.assertEquals("primary key binding signature issuer should be signing subkey", - signingKey.getKeyId(), sigs.get(0).getKeyId()); - - Assert.assertEquals("third key can encrypt", - KeyFlags.ENCRYPT_COMMS, it.next().getKeyUsage()); - - } - - @Test - public void testBadKeyModification() throws Exception { - - { - SaveKeyringParcel parcel = new SaveKeyringParcel(); - // off by one - parcel.mMasterKeyId = ring.getMasterKeyId() -1; - parcel.mFingerprint = ring.getFingerprint(); - - CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); - UncachedKeyRing modified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); - - Assert.assertNull("keyring modification with bad master key id should fail", modified); - } - - { - SaveKeyringParcel parcel = new SaveKeyringParcel(); - // off by one - parcel.mMasterKeyId = null; - parcel.mFingerprint = ring.getFingerprint(); - - CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); - UncachedKeyRing modified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); - - Assert.assertNull("keyring modification with null master key id should fail", modified); - } - - { - SaveKeyringParcel parcel = new SaveKeyringParcel(); - parcel.mMasterKeyId = ring.getMasterKeyId(); - parcel.mFingerprint = ring.getFingerprint(); - // some byte, off by one - parcel.mFingerprint[5] += 1; - - CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); - UncachedKeyRing modified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); - - Assert.assertNull("keyring modification with bad fingerprint should fail", modified); - } - - { - SaveKeyringParcel parcel = new SaveKeyringParcel(); - parcel.mMasterKeyId = ring.getMasterKeyId(); - parcel.mFingerprint = null; - - CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); - UncachedKeyRing modified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); - - Assert.assertNull("keyring modification with null fingerprint should fail", modified); - } - - { - String badphrase = ""; - if (badphrase.equals(passphrase)) { - badphrase = "a"; - } - CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); - UncachedKeyRing modified = op.modifySecretKeyRing(secretRing, parcel, badphrase).getRing(); - - Assert.assertNull("keyring modification with bad passphrase should fail", modified); - } - - } - - @Test - public void testSubkeyAdd() throws Exception { - - long expiry = new Date().getTime() / 1000 + 159; - int flags = KeyFlags.SIGN_DATA; - int bits = 1024 + new Random().nextInt(8); - parcel.mAddSubKeys.add(new SubkeyAdd(algorithm.rsa, bits, flags, expiry)); - - UncachedKeyRing modified = applyModificationWithChecks(parcel, ring, onlyA, onlyB); - - Assert.assertEquals("no extra packets in original", 0, onlyA.size()); - Assert.assertEquals("exactly two extra packets in modified", 2, onlyB.size()); - - Packet p; - - p = new BCPGInputStream(new ByteArrayInputStream(onlyB.get(0).buf)).readPacket(); - Assert.assertTrue("first new packet must be secret subkey", p instanceof SecretSubkeyPacket); - - p = new BCPGInputStream(new ByteArrayInputStream(onlyB.get(1).buf)).readPacket(); - Assert.assertTrue("second new packet must be signature", p instanceof SignaturePacket); - Assert.assertEquals("signature type must be subkey binding certificate", - PGPSignature.SUBKEY_BINDING, ((SignaturePacket) p).getSignatureType()); - Assert.assertEquals("signature must have been created by master key", - ring.getMasterKeyId(), ((SignaturePacket) p).getKeyID()); - - // get new key from ring. it should be the last one (add a check to make sure?) - UncachedPublicKey newKey = null; - { - Iterator it = modified.getPublicKeys(); - while (it.hasNext()) { - newKey = it.next(); - } - } - - Assert.assertNotNull("new key is not null", newKey); - Assert.assertNotNull("added key must have an expiry date", - newKey.getExpiryTime()); - Assert.assertEquals("added key must have expected expiry date", - expiry, newKey.getExpiryTime().getTime()/1000); - Assert.assertEquals("added key must have expected flags", - flags, newKey.getKeyUsage()); - Assert.assertEquals("added key must have expected bitsize", - bits, newKey.getBitStrength()); - - { // bad keysize should fail - parcel.reset(); - parcel.mAddSubKeys.add(new SubkeyAdd( - algorithm.rsa, new Random().nextInt(512), KeyFlags.SIGN_DATA, null)); - - CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); - modified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); - - Assert.assertNull("creating a subkey with keysize < 512 should fail", modified); - } - - { // a past expiry should fail - parcel.reset(); - parcel.mAddSubKeys.add(new SubkeyAdd(algorithm.rsa, 1024, KeyFlags.SIGN_DATA, - new Date().getTime()/1000-10)); - - CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); - modified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); - - Assert.assertNull("creating subkey with past expiry date should fail", modified); - } - - } - - @Test - public void testSubkeyModify() throws Exception { - - long expiry = new Date().getTime()/1000 + 1024; - long keyId = KeyringTestingHelper.getSubkeyId(ring, 1); - - UncachedKeyRing modified = ring; - { - parcel.mChangeSubKeys.add(new SubkeyChange(keyId, null, expiry)); - modified = applyModificationWithChecks(parcel, modified, onlyA, onlyB); - - Assert.assertEquals("one extra packet in original", 1, onlyA.size()); - Assert.assertEquals("one extra packet in modified", 1, onlyB.size()); - - Assert.assertEquals("old packet must be signature", - PacketTags.SIGNATURE, onlyA.get(0).tag); - - Packet p = new BCPGInputStream(new ByteArrayInputStream(onlyB.get(0).buf)).readPacket(); - Assert.assertTrue("first new packet must be signature", p instanceof SignaturePacket); - Assert.assertEquals("signature type must be subkey binding certificate", - PGPSignature.SUBKEY_BINDING, ((SignaturePacket) p).getSignatureType()); - Assert.assertEquals("signature must have been created by master key", - ring.getMasterKeyId(), ((SignaturePacket) p).getKeyID()); - - Assert.assertNotNull("modified key must have an expiry date", - modified.getPublicKey(keyId).getExpiryTime()); - Assert.assertEquals("modified key must have expected expiry date", - expiry, modified.getPublicKey(keyId).getExpiryTime().getTime()/1000); - Assert.assertEquals("modified key must have same flags as before", - ring.getPublicKey(keyId).getKeyUsage(), modified.getPublicKey(keyId).getKeyUsage()); - } - - { - int flags = KeyFlags.SIGN_DATA | KeyFlags.ENCRYPT_COMMS; - parcel.reset(); - parcel.mChangeSubKeys.add(new SubkeyChange(keyId, flags, null)); - modified = applyModificationWithChecks(parcel, modified, onlyA, onlyB); - - Assert.assertEquals("old packet must be signature", - PacketTags.SIGNATURE, onlyA.get(0).tag); - - Packet p = new BCPGInputStream(new ByteArrayInputStream(onlyB.get(0).buf)).readPacket(); - Assert.assertTrue("first new packet must be signature", p instanceof SignaturePacket); - Assert.assertEquals("signature type must be subkey binding certificate", - PGPSignature.SUBKEY_BINDING, ((SignaturePacket) p).getSignatureType()); - Assert.assertEquals("signature must have been created by master key", - ring.getMasterKeyId(), ((SignaturePacket) p).getKeyID()); - - Assert.assertEquals("modified key must have expected flags", - flags, modified.getPublicKey(keyId).getKeyUsage()); - Assert.assertNotNull("key must retain its expiry", - modified.getPublicKey(keyId).getExpiryTime()); - Assert.assertEquals("key expiry must be unchanged", - expiry, modified.getPublicKey(keyId).getExpiryTime().getTime()/1000); - } - - { // a past expiry should fail - parcel.reset(); - parcel.mChangeSubKeys.add(new SubkeyChange(keyId, null, new Date().getTime()/1000-10)); - - CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); - modified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); - - Assert.assertNull("setting subkey expiry to a past date should fail", modified); - } - - { // modifying nonexistent keyring should fail - parcel.reset(); - parcel.mChangeSubKeys.add(new SubkeyChange(123, null, null)); - - CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); - modified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); - - Assert.assertNull("modifying non-existent subkey should fail", modified); - } - - } - - @Test - public void testSubkeyRevoke() throws Exception { - - long keyId = KeyringTestingHelper.getSubkeyId(ring, 1); - int flags = ring.getPublicKey(keyId).getKeyUsage(); - - UncachedKeyRing modified; - - { - - parcel.reset(); - parcel.mRevokeSubKeys.add(123L); - - CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); - UncachedKeyRing otherModified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); - - Assert.assertNull("revoking a nonexistent subkey should fail", otherModified); - - } - - { // revoked second subkey - - parcel.reset(); - parcel.mRevokeSubKeys.add(keyId); - - modified = applyModificationWithChecks(parcel, ring, onlyA, onlyB); - - Assert.assertEquals("no extra packets in original", 0, onlyA.size()); - Assert.assertEquals("exactly one extra packet in modified", 1, onlyB.size()); - - Packet p; - - p = new BCPGInputStream(new ByteArrayInputStream(onlyB.get(0).buf)).readPacket(); - Assert.assertTrue("first new packet must be secret subkey", p instanceof SignaturePacket); - Assert.assertEquals("signature type must be subkey binding certificate", - PGPSignature.SUBKEY_REVOCATION, ((SignaturePacket) p).getSignatureType()); - Assert.assertEquals("signature must have been created by master key", - ring.getMasterKeyId(), ((SignaturePacket) p).getKeyID()); - - Assert.assertTrue("subkey must actually be revoked", - modified.getPublicKey(keyId).isRevoked()); - } - - { // re-add second subkey - - parcel.reset(); - parcel.mChangeSubKeys.add(new SubkeyChange(keyId, null, null)); - - modified = applyModificationWithChecks(parcel, modified, onlyA, onlyB); - - Assert.assertEquals("exactly two outdated packets in original", 2, onlyA.size()); - Assert.assertEquals("exactly one extra packet in modified", 1, onlyB.size()); - - Packet p; - - p = new BCPGInputStream(new ByteArrayInputStream(onlyA.get(0).buf)).readPacket(); - Assert.assertTrue("first outdated packet must be signature", p instanceof SignaturePacket); - Assert.assertEquals("first outdated signature type must be subkey binding certification", - PGPSignature.SUBKEY_BINDING, ((SignaturePacket) p).getSignatureType()); - Assert.assertEquals("first outdated signature must have been created by master key", - ring.getMasterKeyId(), ((SignaturePacket) p).getKeyID()); - - p = new BCPGInputStream(new ByteArrayInputStream(onlyA.get(1).buf)).readPacket(); - Assert.assertTrue("second outdated packet must be signature", p instanceof SignaturePacket); - Assert.assertEquals("second outdated signature type must be subkey revocation", - PGPSignature.SUBKEY_REVOCATION, ((SignaturePacket) p).getSignatureType()); - Assert.assertEquals("second outdated signature must have been created by master key", - ring.getMasterKeyId(), ((SignaturePacket) p).getKeyID()); - - p = new BCPGInputStream(new ByteArrayInputStream(onlyB.get(0).buf)).readPacket(); - Assert.assertTrue("new packet must be signature ", p instanceof SignaturePacket); - Assert.assertEquals("new signature type must be subkey binding certification", - PGPSignature.SUBKEY_BINDING, ((SignaturePacket) p).getSignatureType()); - Assert.assertEquals("signature must have been created by master key", - ring.getMasterKeyId(), ((SignaturePacket) p).getKeyID()); - - Assert.assertFalse("subkey must no longer be revoked", - modified.getPublicKey(keyId).isRevoked()); - Assert.assertEquals("subkey must have the same usage flags as before", - flags, modified.getPublicKey(keyId).getKeyUsage()); - - } - } - - @Test - public void testUserIdRevoke() throws Exception { - - UncachedKeyRing modified; - String uid = ring.getPublicKey().getUnorderedUserIds().get(1); - - { // revoke second user id - - parcel.mRevokeUserIds.add(uid); - - modified = applyModificationWithChecks(parcel, ring, onlyA, onlyB); - - Assert.assertEquals("no extra packets in original", 0, onlyA.size()); - Assert.assertEquals("exactly one extra packet in modified", 1, onlyB.size()); - - Packet p; - - p = new BCPGInputStream(new ByteArrayInputStream(onlyB.get(0).buf)).readPacket(); - Assert.assertTrue("first new packet must be secret subkey", p instanceof SignaturePacket); - Assert.assertEquals("signature type must be subkey binding certificate", - PGPSignature.CERTIFICATION_REVOCATION, ((SignaturePacket) p).getSignatureType()); - Assert.assertEquals("signature must have been created by master key", - ring.getMasterKeyId(), ((SignaturePacket) p).getKeyID()); - - } - - { // re-add second user id - - parcel.reset(); - parcel.mChangePrimaryUserId = uid; - - CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(modified.getEncoded(), false, 0); - UncachedKeyRing otherModified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); - - Assert.assertNull("setting primary user id to a revoked user id should fail", otherModified); - - } - - { // re-add second user id - - parcel.reset(); - parcel.mAddUserIds.add(uid); - - applyModificationWithChecks(parcel, modified, onlyA, onlyB); - - Assert.assertEquals("exactly two outdated packets in original", 2, onlyA.size()); - Assert.assertEquals("exactly one extra packet in modified", 1, onlyB.size()); - - Packet p; - - p = new BCPGInputStream(new ByteArrayInputStream(onlyA.get(0).buf)).readPacket(); - Assert.assertTrue("first outdated packet must be signature", p instanceof SignaturePacket); - Assert.assertEquals("first outdated signature type must be positive certification", - PGPSignature.POSITIVE_CERTIFICATION, ((SignaturePacket) p).getSignatureType()); - Assert.assertEquals("first outdated signature must have been created by master key", - ring.getMasterKeyId(), ((SignaturePacket) p).getKeyID()); - - p = new BCPGInputStream(new ByteArrayInputStream(onlyA.get(1).buf)).readPacket(); - Assert.assertTrue("second outdated packet must be signature", p instanceof SignaturePacket); - Assert.assertEquals("second outdated signature type must be certificate revocation", - PGPSignature.CERTIFICATION_REVOCATION, ((SignaturePacket) p).getSignatureType()); - Assert.assertEquals("second outdated signature must have been created by master key", - ring.getMasterKeyId(), ((SignaturePacket) p).getKeyID()); - - p = new BCPGInputStream(new ByteArrayInputStream(onlyB.get(0).buf)).readPacket(); - Assert.assertTrue("new packet must be signature ", p instanceof SignaturePacket); - Assert.assertEquals("new signature type must be positive certification", - PGPSignature.POSITIVE_CERTIFICATION, ((SignaturePacket) p).getSignatureType()); - Assert.assertEquals("signature must have been created by master key", - ring.getMasterKeyId(), ((SignaturePacket) p).getKeyID()); - } - - } - - @Test - public void testUserIdAdd() throws Exception { - - { - parcel.mAddUserIds.add(""); - CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); - UncachedKeyRing modified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); - Assert.assertNull("adding an empty user id should fail", modified); - } - - parcel.reset(); - parcel.mAddUserIds.add("rainbow"); - - UncachedKeyRing modified = applyModificationWithChecks(parcel, ring, onlyA, onlyB); - - Assert.assertTrue("keyring must contain added user id", - modified.getPublicKey().getUnorderedUserIds().contains("rainbow")); - - Assert.assertEquals("no extra packets in original", 0, onlyA.size()); - Assert.assertEquals("exactly two extra packets in modified", 2, onlyB.size()); - - Assert.assertTrue("keyring must contain added user id", - modified.getPublicKey().getUnorderedUserIds().contains("rainbow")); - - Packet p; - - p = new BCPGInputStream(new ByteArrayInputStream(onlyB.get(0).buf)).readPacket(); - Assert.assertTrue("first new packet must be user id", p instanceof UserIDPacket); - Assert.assertEquals("user id packet must match added user id", - "rainbow", ((UserIDPacket) p).getID()); - - p = new BCPGInputStream(new ByteArrayInputStream(onlyB.get(1).buf)).readPacket(); - Assert.assertTrue("second new packet must be signature", p instanceof SignaturePacket); - Assert.assertEquals("signature type must be positive certification", - PGPSignature.POSITIVE_CERTIFICATION, ((SignaturePacket) p).getSignatureType()); - - } - - @Test - public void testUserIdPrimary() throws Exception { - - UncachedKeyRing modified = ring; - String uid = ring.getPublicKey().getUnorderedUserIds().get(1); - - { // first part, add new user id which is also primary - parcel.mAddUserIds.add("jack"); - parcel.mChangePrimaryUserId = "jack"; - - modified = applyModificationWithChecks(parcel, modified, onlyA, onlyB); - - Assert.assertEquals("primary user id must be the one added", - "jack", modified.getPublicKey().getPrimaryUserId()); - } - - { // second part, change primary to a different one - parcel.reset(); - parcel.mChangePrimaryUserId = uid; - - modified = applyModificationWithChecks(parcel, modified, onlyA, onlyB); - - Assert.assertEquals("old keyring must have two outdated certificates", 2, onlyA.size()); - Assert.assertEquals("new keyring must have two new packets", 2, onlyB.size()); - - Assert.assertEquals("primary user id must be the one changed to", - "pink", modified.getPublicKey().getPrimaryUserId()); - } - - { // third part, change primary to a non-existent one - parcel.reset(); - //noinspection SpellCheckingInspection - parcel.mChangePrimaryUserId = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; - if (parcel.mChangePrimaryUserId.equals(passphrase)) { - parcel.mChangePrimaryUserId += "A"; - } - - CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); - modified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); - - Assert.assertNull("changing primary user id to a non-existent one should fail", modified); - } - - // check for revoked primary user id already done in revoke test - - } - - - private static UncachedKeyRing applyModificationWithChecks(SaveKeyringParcel parcel, - UncachedKeyRing ring, - ArrayList onlyA, - ArrayList onlyB) { - return applyModificationWithChecks(parcel, ring, onlyA, onlyB, true, true); - } - - // applies a parcel modification while running some integrity checks - private static UncachedKeyRing applyModificationWithChecks(SaveKeyringParcel parcel, - UncachedKeyRing ring, - ArrayList onlyA, - ArrayList onlyB, - boolean canonicalize, - boolean constantCanonicalize) { - - try { - - Assert.assertTrue("modified keyring must be secret", ring.isSecret()); - CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ring.getEncoded(), false, 0); - - PgpKeyOperation op = new PgpKeyOperation(null); - UncachedKeyRing rawModified = op.modifySecretKeyRing(secretRing, parcel, passphrase).getRing(); - Assert.assertNotNull("key modification failed", rawModified); - - if (!canonicalize) { - Assert.assertTrue("keyring must differ from original", KeyringTestingHelper.diffKeyrings( - ring.getEncoded(), rawModified.getEncoded(), onlyA, onlyB)); - return rawModified; - } - - CanonicalizedKeyRing modified = rawModified.canonicalize(new OperationLog(), 0); - if (constantCanonicalize) { - Assert.assertTrue("key must be constant through canonicalization", - !KeyringTestingHelper.diffKeyrings( - modified.getEncoded(), rawModified.getEncoded(), onlyA, onlyB) - ); - } - Assert.assertTrue("keyring must differ from original", KeyringTestingHelper.diffKeyrings( - ring.getEncoded(), modified.getEncoded(), onlyA, onlyB)); - - return modified.getUncachedKeyRing(); - - } catch (IOException e) { - throw new AssertionFailedError("error during encoding!"); - } - } - - @Test - public void testVerifySuccess() throws Exception { - - UncachedKeyRing expectedKeyRing = KeyringBuilder.correctRing(); - UncachedKeyRing inputKeyRing = KeyringBuilder.ringWithExtraIncorrectSignature(); - - CanonicalizedKeyRing canonicalized = inputKeyRing.canonicalize(new OperationLog(), 0); - Assert.assertNotNull("canonicalization must succeed", canonicalized); - - ArrayList onlyA = new ArrayList(); - ArrayList onlyB = new ArrayList(); - //noinspection unchecked - Assert.assertTrue("keyrings differ", !KeyringTestingHelper.diffKeyrings( - expectedKeyRing.getEncoded(), expectedKeyRing.getEncoded(), onlyA, onlyB)); - - } - - /** - * Just testing my own test code. Should really be using a library for this. - */ - @Test - public void testConcat() throws Exception { - byte[] actual = TestDataUtil.concatAll(new byte[]{1}, new byte[]{2,-2}, new byte[]{5},new byte[]{3}); - byte[] expected = new byte[]{1,2,-2,5,3}; - Assert.assertEquals(java.util.Arrays.toString(expected), java.util.Arrays.toString(actual)); - } - - -} diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/ProviderHelperKeyringTest.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/ProviderHelperKeyringTest.java deleted file mode 100644 index 665e8ef2b..000000000 --- a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/ProviderHelperKeyringTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (C) Art O Cathain - * - * 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 . - */ - -package tests; - -import java.util.Collections; -import java.util.Arrays; -import java.util.Collection; -import java.util.ArrayList; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.*; -import org.sufficientlysecure.keychain.support.KeyringTestingHelper; - -@RunWith(RobolectricTestRunner.class) -@org.robolectric.annotation.Config(emulateSdk = 18) // Robolectric doesn't yet support 19 -public class ProviderHelperKeyringTest { - - @Test - public void testSavePublicKeyring() throws Exception { - Assert.assertTrue(new KeyringTestingHelper(Robolectric.application).addKeyring(Collections.singleton( - "/public-key-for-sample.blob" - ))); - } - - // @Test - public void testSavePublicKeyringRsa() throws Exception { - Assert.assertTrue(new KeyringTestingHelper(Robolectric.application).addKeyring(prependResourcePath(Arrays.asList( - "000001-006.public_key", - "000002-013.user_id", - "000003-002.sig", - "000004-012.ring_trust", - "000005-002.sig", - "000006-012.ring_trust", - "000007-002.sig", - "000008-012.ring_trust", - "000009-002.sig", - "000010-012.ring_trust", - "000011-002.sig", - "000012-012.ring_trust", - "000013-014.public_subkey", - "000014-002.sig", - "000015-012.ring_trust" - )))); - } - - // @Test - public void testSavePublicKeyringDsa() throws Exception { - Assert.assertTrue(new KeyringTestingHelper(Robolectric.application).addKeyring(prependResourcePath(Arrays.asList( - "000016-006.public_key", - "000017-002.sig", - "000018-012.ring_trust", - "000019-013.user_id", - "000020-002.sig", - "000021-012.ring_trust", - "000022-002.sig", - "000023-012.ring_trust", - "000024-014.public_subkey", - "000025-002.sig", - "000026-012.ring_trust" - )))); - } - - // @Test - public void testSavePublicKeyringDsa2() throws Exception { - Assert.assertTrue(new KeyringTestingHelper(Robolectric.application).addKeyring(prependResourcePath(Arrays.asList( - "000027-006.public_key", - "000028-002.sig", - "000029-012.ring_trust", - "000030-013.user_id", - "000031-002.sig", - "000032-012.ring_trust", - "000033-002.sig", - "000034-012.ring_trust" - )))); - } - - private static Collection prependResourcePath(Collection files) { - Collection prependedFiles = new ArrayList(); - for (String file: files) { - prependedFiles.add("/OpenPGP-Haskell/tests/data/" + file); - } - return prependedFiles; - } -} diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringCanonicalizeTest.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringCanonicalizeTest.java deleted file mode 100644 index 97e0d8a68..000000000 --- a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringCanonicalizeTest.java +++ /dev/null @@ -1,627 +0,0 @@ -package org.sufficientlysecure.keychain.tests; - -import org.junit.BeforeClass; -import org.junit.runner.RunWith; -import org.junit.Assert; -import org.junit.Test; -import org.junit.Before; -import org.robolectric.RobolectricTestRunner; -import org.robolectric.shadows.ShadowLog; -import org.spongycastle.bcpg.BCPGInputStream; -import org.spongycastle.bcpg.Packet; -import org.spongycastle.bcpg.PacketTags; -import org.spongycastle.bcpg.UserIDPacket; -import org.spongycastle.bcpg.sig.KeyFlags; -import org.spongycastle.openpgp.PGPPrivateKey; -import org.spongycastle.openpgp.PGPPublicKey; -import org.spongycastle.openpgp.PGPSecretKey; -import org.spongycastle.openpgp.PGPSecretKeyRing; -import org.spongycastle.openpgp.PGPSignature; -import org.spongycastle.openpgp.PGPSignatureGenerator; -import org.spongycastle.openpgp.PGPSignatureSubpacketGenerator; -import org.spongycastle.openpgp.PGPUtil; -import org.spongycastle.openpgp.operator.PBESecretKeyDecryptor; -import org.spongycastle.openpgp.operator.PGPContentSignerBuilder; -import org.spongycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator; -import org.spongycastle.openpgp.operator.jcajce.JcaPGPContentSignerBuilder; -import org.spongycastle.openpgp.operator.jcajce.JcePBESecretKeyDecryptorBuilder; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.pgp.CanonicalizedKeyRing; -import org.sufficientlysecure.keychain.pgp.PgpKeyOperation; -import org.sufficientlysecure.keychain.pgp.UncachedKeyRing; -import org.sufficientlysecure.keychain.pgp.UncachedPublicKey; -import org.sufficientlysecure.keychain.pgp.WrappedSignature; -import org.sufficientlysecure.keychain.service.OperationResultParcel; -import org.sufficientlysecure.keychain.service.OperationResults.EditKeyResult; -import org.sufficientlysecure.keychain.service.SaveKeyringParcel; -import org.sufficientlysecure.keychain.support.KeyringTestingHelper; -import org.sufficientlysecure.keychain.support.KeyringTestingHelper.RawPacket; - -import java.io.ByteArrayInputStream; -import java.util.ArrayList; -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(RobolectricTestRunner.class) -@org.robolectric.annotation.Config(emulateSdk = 18) // Robolectric doesn't yet support 19 -public class UncachedKeyringCanonicalizeTest { - - static UncachedKeyRing staticRing; - static int totalPackets; - UncachedKeyRing ring; - ArrayList onlyA = new ArrayList(); - ArrayList onlyB = new ArrayList(); - OperationResultParcel.OperationLog log = new OperationResultParcel.OperationLog(); - PGPSignatureSubpacketGenerator subHashedPacketsGen; - PGPSecretKey secretKey; - - @BeforeClass - public static void setUpOnce() throws Exception { - ShadowLog.stream = System.out; - - SaveKeyringParcel parcel = new SaveKeyringParcel(); - parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( - Constants.choice.algorithm.rsa, 1024, KeyFlags.CERTIFY_OTHER, null)); - parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( - Constants.choice.algorithm.rsa, 1024, KeyFlags.SIGN_DATA, null)); - parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( - Constants.choice.algorithm.rsa, 1024, KeyFlags.ENCRYPT_COMMS, null)); - - parcel.mAddUserIds.add("twi"); - parcel.mAddUserIds.add("pink"); - // passphrase is tested in PgpKeyOperationTest, just use empty here - parcel.mNewPassphrase = ""; - PgpKeyOperation op = new PgpKeyOperation(null); - - EditKeyResult 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); - - // just for later reference - totalPackets = 9; - - // 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 it = KeyringTestingHelper.parseKeyring(ring.getEncoded()); - - Assert.assertEquals("packet #1 should be secret key", - PacketTags.SECRET_KEY, it.next().tag); - - Assert.assertEquals("packet #2 should be user id", - PacketTags.USER_ID, it.next().tag); - Assert.assertEquals("packet #3 should be signature", - PacketTags.SIGNATURE, it.next().tag); - - Assert.assertEquals("packet #4 should be user id", - PacketTags.USER_ID, it.next().tag); - Assert.assertEquals("packet #5 should be signature", - PacketTags.SIGNATURE, it.next().tag); - - Assert.assertEquals("packet #6 should be secret subkey", - PacketTags.SECRET_SUBKEY, it.next().tag); - Assert.assertEquals("packet #7 should be signature", - PacketTags.SIGNATURE, it.next().tag); - - Assert.assertEquals("packet #8 should be secret subkey", - PacketTags.SECRET_SUBKEY, it.next().tag); - Assert.assertEquals("packet #9 should be signature", - PacketTags.SIGNATURE, it.next().tag); - - Assert.assertFalse("exactly 9 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.getSignaturesForId("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 testSignatureBroken() throws Exception { - - injectEverytype(secretKey, ring, subHashedPacketsGen, true); - - } - - @Test public void testForeignSignature() throws Exception { - - SaveKeyringParcel parcel = new SaveKeyringParcel(); - parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( - Constants.choice.algorithm.rsa, 1024, KeyFlags.CERTIFY_OTHER, null)); - parcel.mAddUserIds.add("trix"); - PgpKeyOperation op = new PgpKeyOperation(null); - - OperationResultParcel.OperationLog log = new OperationResultParcel.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 - subHashedPacketsGen.setSignatureCreationTime(false, new Date(new Date().getTime() + 1000 * 1000)); - - injectEverytype(secretKey, ring, subHashedPacketsGen); - - - } - - @Test public void testSignatureLocal() throws Exception { - - // generate future - subHashedPacketsGen.setSignatureCreationTime(false, new Date()); - 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, 6); - - // 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); - Assert.assertTrue("second subkey must be able to sign", pKey.canSign()); - - 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(), 6); - - // 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(), 6); - - // 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(), 8); - modified = KeyringTestingHelper.injectPacket(modified, sig2.getEncoded(), 9); - modified = KeyringTestingHelper.injectPacket(modified, sig1.getEncoded(), 10); - modified = KeyringTestingHelper.injectPacket(modified, sig3.getEncoded(), 11); - - // 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); - - } - - 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 { - - OperationResultParcel.OperationLog log = new OperationResultParcel.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); - - } - -} diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringMergeTest.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringMergeTest.java deleted file mode 100644 index 977ddfc52..000000000 --- a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringMergeTest.java +++ /dev/null @@ -1,397 +0,0 @@ -package org.sufficientlysecure.keychain.tests; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; -import org.robolectric.shadows.ShadowLog; -import org.spongycastle.bcpg.PacketTags; -import org.spongycastle.bcpg.sig.KeyFlags; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKeyRing; -import org.sufficientlysecure.keychain.pgp.PgpKeyOperation; -import org.sufficientlysecure.keychain.pgp.UncachedKeyRing; -import org.sufficientlysecure.keychain.pgp.UncachedPublicKey; -import org.sufficientlysecure.keychain.pgp.CanonicalizedPublicKeyRing; -import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKey; -import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKeyRing; -import org.sufficientlysecure.keychain.service.OperationResultParcel; -import org.sufficientlysecure.keychain.service.OperationResults.EditKeyResult; -import org.sufficientlysecure.keychain.service.SaveKeyringParcel; -import org.sufficientlysecure.keychain.support.KeyringTestingHelper; -import org.sufficientlysecure.keychain.support.KeyringTestingHelper.RawPacket; -import org.sufficientlysecure.keychain.util.ProgressScaler; - -import java.util.ArrayList; -import java.util.Iterator; - -/** Tests for the UncachedKeyring.merge method. - * - * This is another complex, crypto-related method. It merges information from one keyring into - * another, keeping information from the base (ie, called object) keyring in case of conflicts. - * The types of keys may be Public or Secret and can be mixed, For mixed types the result type - * will be the same as the base keyring. - * - * Test cases: - * - Merging keyrings with different masterKeyIds should fail - * - Merging a key with itself should be a no-operation - * - Merging a key with an extra revocation certificate, it should have that certificate - * - Merging a key with an extra user id, it should have that extra user id and its certificates - * - Merging a key with an extra user id certificate, it should have that certificate - * - Merging a key with an extra subkey, it should have that subkey - * - Merging a key with an extra subkey certificate, it should have that certificate - * - All of the above operations should work regardless of the key types. This means in particular - * that for new subkeys, an equivalent subkey of the proper type must be generated. - * - In case of two secret keys with the same id but different S2K, the key of the base keyring - * should be preferred (TODO or should it?) - * - * Note that the merge operation does not care about certificate validity, a bad certificate or - * packet will be copied regardless. Filtering out bad packets is done with canonicalization. - * - */ -@RunWith(RobolectricTestRunner.class) -@org.robolectric.annotation.Config(emulateSdk = 18) // Robolectric doesn't yet support 19 -public class UncachedKeyringMergeTest { - - static UncachedKeyRing staticRingA, staticRingB; - UncachedKeyRing ringA, ringB; - ArrayList onlyA = new ArrayList(); - ArrayList onlyB = new ArrayList(); - OperationResultParcel.OperationLog log = new OperationResultParcel.OperationLog(); - PgpKeyOperation op; - SaveKeyringParcel parcel; - - @BeforeClass - public static void setUpOnce() throws Exception { - ShadowLog.stream = System.out; - - { - SaveKeyringParcel parcel = new SaveKeyringParcel(); - parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( - Constants.choice.algorithm.rsa, 1024, KeyFlags.CERTIFY_OTHER, null)); - parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( - Constants.choice.algorithm.rsa, 1024, KeyFlags.SIGN_DATA, null)); - - parcel.mAddUserIds.add("twi"); - parcel.mAddUserIds.add("pink"); - // passphrase is tested in PgpKeyOperationTest, just use empty here - parcel.mNewPassphrase = ""; - PgpKeyOperation op = new PgpKeyOperation(null); - - OperationResultParcel.OperationLog log = new OperationResultParcel.OperationLog(); - - EditKeyResult result = op.createSecretKeyRing(parcel); - staticRingA = result.getRing(); - } - - { - SaveKeyringParcel parcel = new SaveKeyringParcel(); - parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( - Constants.choice.algorithm.rsa, 1024, KeyFlags.CERTIFY_OTHER, null)); - - parcel.mAddUserIds.add("shy"); - // passphrase is tested in PgpKeyOperationTest, just use empty here - parcel.mNewPassphrase = ""; - PgpKeyOperation op = new PgpKeyOperation(null); - - OperationResultParcel.OperationLog log = new OperationResultParcel.OperationLog(); - EditKeyResult result = op.createSecretKeyRing(parcel); - staticRingB = result.getRing(); - } - - Assert.assertNotNull("initial test key creation must succeed", staticRingA); - Assert.assertNotNull("initial test key creation must succeed", staticRingB); - - // 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; - ringA = staticRingA; - ringB = staticRingB; - - // setting up some parameters just to reduce code duplication - op = new PgpKeyOperation(new ProgressScaler(null, 0, 100, 100)); - - // set this up, gonna need it more than once - parcel = new SaveKeyringParcel(); - parcel.mMasterKeyId = ringA.getMasterKeyId(); - parcel.mFingerprint = ringA.getFingerprint(); - } - - public void testSelfNoOp() throws Exception { - - UncachedKeyRing merged = mergeWithChecks(ringA, ringA, null); - Assert.assertArrayEquals("keyring merged with itself must be identical", - ringA.getEncoded(), merged.getEncoded() - ); - - } - - @Test - public void testDifferentMasterKeyIds() throws Exception { - - Assert.assertNotEquals("generated key ids must be different", - ringA.getMasterKeyId(), ringB.getMasterKeyId()); - - Assert.assertNull("merging keys with differing key ids must fail", - ringA.merge(ringB, log, 0)); - Assert.assertNull("merging keys with differing key ids must fail", - ringB.merge(ringA, log, 0)); - - } - - @Test - public void testAddedUserId() throws Exception { - - UncachedKeyRing modifiedA, modifiedB; { - CanonicalizedSecretKeyRing secretRing = - new CanonicalizedSecretKeyRing(ringA.getEncoded(), false, 0); - - parcel.reset(); - parcel.mAddUserIds.add("flim"); - modifiedA = op.modifySecretKeyRing(secretRing, parcel, "").getRing(); - - parcel.reset(); - parcel.mAddUserIds.add("flam"); - modifiedB = op.modifySecretKeyRing(secretRing, parcel, "").getRing(); - } - - { // merge A into base - UncachedKeyRing merged = mergeWithChecks(ringA, modifiedA); - - Assert.assertEquals("merged keyring must have lost no packets", 0, onlyA.size()); - Assert.assertEquals("merged keyring must have gained two packets", 2, onlyB.size()); - Assert.assertTrue("merged keyring must contain new user id", - merged.getPublicKey().getUnorderedUserIds().contains("flim")); - } - - { // merge A into B - UncachedKeyRing merged = mergeWithChecks(modifiedA, modifiedB, ringA); - - Assert.assertEquals("merged keyring must have lost no packets", 0, onlyA.size()); - Assert.assertEquals("merged keyring must have gained four packets", 4, onlyB.size()); - Assert.assertTrue("merged keyring must contain first new user id", - merged.getPublicKey().getUnorderedUserIds().contains("flim")); - Assert.assertTrue("merged keyring must contain second new user id", - merged.getPublicKey().getUnorderedUserIds().contains("flam")); - - } - - } - - @Test - public void testAddedSubkeyId() throws Exception { - - UncachedKeyRing modifiedA, modifiedB; - long subKeyIdA, subKeyIdB; - { - CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing(ringA.getEncoded(), false, 0); - - parcel.reset(); - parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( - Constants.choice.algorithm.rsa, 1024, KeyFlags.SIGN_DATA, null)); - modifiedA = op.modifySecretKeyRing(secretRing, parcel, "").getRing(); - modifiedB = op.modifySecretKeyRing(secretRing, parcel, "").getRing(); - - subKeyIdA = KeyringTestingHelper.getSubkeyId(modifiedA, 2); - subKeyIdB = KeyringTestingHelper.getSubkeyId(modifiedB, 2); - - } - - { - UncachedKeyRing merged = mergeWithChecks(ringA, modifiedA); - - Assert.assertEquals("merged keyring must have lost no packets", 0, onlyA.size()); - Assert.assertEquals("merged keyring must have gained two packets", 2, onlyB.size()); - - long mergedKeyId = KeyringTestingHelper.getSubkeyId(merged, 2); - Assert.assertEquals("merged keyring must contain the new subkey", subKeyIdA, mergedKeyId); - } - - { - UncachedKeyRing merged = mergeWithChecks(modifiedA, modifiedB, ringA); - - Assert.assertEquals("merged keyring must have lost no packets", 0, onlyA.size()); - Assert.assertEquals("merged keyring must have gained four packets", 4, onlyB.size()); - - Iterator it = merged.getPublicKeys(); - it.next(); it.next(); - Assert.assertEquals("merged keyring must contain the new subkey", - subKeyIdA, it.next().getKeyId()); - Assert.assertEquals("merged keyring must contain both new subkeys", - subKeyIdB, it.next().getKeyId()); - } - - } - - @Test - public void testAddedKeySignature() throws Exception { - - final UncachedKeyRing modified; { - parcel.reset(); - parcel.mRevokeSubKeys.add(KeyringTestingHelper.getSubkeyId(ringA, 1)); - CanonicalizedSecretKeyRing secretRing = new CanonicalizedSecretKeyRing( - ringA.getEncoded(), false, 0); - modified = op.modifySecretKeyRing(secretRing, parcel, "").getRing(); - } - - { - UncachedKeyRing merged = ringA.merge(modified, log, 0); - Assert.assertNotNull("merge must succeed", merged); - Assert.assertFalse( - "merging keyring with extra signatures into its base should yield that same keyring", - KeyringTestingHelper.diffKeyrings(merged.getEncoded(), modified.getEncoded(), onlyA, onlyB) - ); - } - - } - - @Test - public void testAddedUserIdSignature() throws Exception { - - final UncachedKeyRing pubRing = ringA.extractPublicKeyRing(); - - final UncachedKeyRing modified; { - CanonicalizedPublicKeyRing publicRing = new CanonicalizedPublicKeyRing( - pubRing.getEncoded(), 0); - - CanonicalizedSecretKey secretKey = new CanonicalizedSecretKeyRing( - ringB.getEncoded(), false, 0).getSecretKey(); - secretKey.unlock(""); - // sign all user ids - modified = secretKey.certifyUserIds(publicRing, publicRing.getPublicKey().getUnorderedUserIds()); - } - - { - UncachedKeyRing merged = ringA.merge(modified, log, 0); - Assert.assertNotNull("merge must succeed", merged); - Assert.assertArrayEquals("foreign signatures should not be merged into secret key", - ringA.getEncoded(), merged.getEncoded() - ); - } - - { - byte[] sig = KeyringTestingHelper.getNth( - modified.getPublicKey().getSignaturesForId("twi"), 1).getEncoded(); - - // inject the (foreign!) signature into subkey signature position - UncachedKeyRing moreModified = KeyringTestingHelper.injectPacket(modified, sig, 1); - - UncachedKeyRing merged = ringA.merge(moreModified, log, 0); - Assert.assertNotNull("merge must succeed", merged); - Assert.assertArrayEquals("foreign signatures should not be merged into secret key", - ringA.getEncoded(), merged.getEncoded() - ); - - merged = pubRing.merge(moreModified, log, 0); - Assert.assertNotNull("merge must succeed", merged); - Assert.assertTrue( - "merged keyring should contain new signature", - KeyringTestingHelper.diffKeyrings(pubRing.getEncoded(), merged.getEncoded(), onlyA, onlyB) - ); - Assert.assertEquals("merged keyring should be missing no packets", 0, onlyA.size()); - Assert.assertEquals("merged keyring should contain exactly two more packets", 2, onlyB.size()); - Assert.assertEquals("first added packet should be a signature", - PacketTags.SIGNATURE, onlyB.get(0).tag); - Assert.assertEquals("first added packet should be in the position we injected it at", - 1, onlyB.get(0).position); - Assert.assertEquals("second added packet should be a signature", - PacketTags.SIGNATURE, onlyB.get(1).tag); - - } - - { - UncachedKeyRing merged = pubRing.merge(modified, log, 0); - Assert.assertNotNull("merge must succeed", merged); - Assert.assertFalse( - "merging keyring with extra signatures into its base should yield that same keyring", - KeyringTestingHelper.diffKeyrings(merged.getEncoded(), modified.getEncoded(), onlyA, onlyB) - ); - } - } - - private UncachedKeyRing mergeWithChecks(UncachedKeyRing a, UncachedKeyRing b) - throws Exception { - return mergeWithChecks(a, b, a); - } - - private UncachedKeyRing mergeWithChecks(UncachedKeyRing a, UncachedKeyRing b, - UncachedKeyRing base) - throws Exception { - - Assert.assertTrue("merging keyring must be secret type", a.isSecret()); - Assert.assertTrue("merged keyring must be secret type", b.isSecret()); - - final UncachedKeyRing resultA; - UncachedKeyRing resultB; - - { // sec + sec - resultA = a.merge(b, log, 0); - Assert.assertNotNull("merge must succeed as sec(a)+sec(b)", resultA); - - resultB = b.merge(a, log, 0); - Assert.assertNotNull("merge must succeed as sec(b)+sec(a)", resultB); - - // check commutativity, if requested - Assert.assertFalse("result of merge must be commutative", - KeyringTestingHelper.diffKeyrings( - resultA.getEncoded(), resultB.getEncoded(), onlyA, onlyB) - ); - } - - final UncachedKeyRing pubA = a.extractPublicKeyRing(); - final UncachedKeyRing pubB = b.extractPublicKeyRing(); - - { // sec + pub, pub + sec, and pub + pub - - try { - resultB = a.merge(pubB, log, 0); - Assert.assertNotNull("merge must succeed as sec(a)+pub(b)", resultA); - - Assert.assertFalse("result of sec(a)+pub(b) must be same as sec(a)+sec(b)", - KeyringTestingHelper.diffKeyrings( - resultA.getEncoded(), resultB.getEncoded(), onlyA, onlyB) - ); - } catch (RuntimeException e) { - System.out.println("special case, dummy key generation not in yet"); - } - - final UncachedKeyRing pubResult = resultA.extractPublicKeyRing(); - - resultB = pubA.merge(b, log, 0); - Assert.assertNotNull("merge must succeed as pub(a)+sec(b)", resultA); - - Assert.assertFalse("result of pub(a)+sec(b) must be same as pub(sec(a)+sec(b))", - KeyringTestingHelper.diffKeyrings( - pubResult.getEncoded(), resultB.getEncoded(), onlyA, onlyB) - ); - - resultB = pubA.merge(pubB, log, 0); - Assert.assertNotNull("merge must succeed as pub(a)+pub(b)", resultA); - - Assert.assertFalse("result of pub(a)+pub(b) must be same as pub(sec(a)+sec(b))", - KeyringTestingHelper.diffKeyrings( - pubResult.getEncoded(), resultB.getEncoded(), onlyA, onlyB) - ); - - } - - if (base != null) { - // set up onlyA and onlyB to be a diff to the base - Assert.assertTrue("merged keyring must differ from base", - KeyringTestingHelper.diffKeyrings( - base.getEncoded(), resultA.getEncoded(), onlyA, onlyB) - ); - } - - return resultA; - - } - -} diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringTest.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringTest.java deleted file mode 100644 index 15aaa4c5d..000000000 --- a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package org.sufficientlysecure.keychain.tests; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; -import org.robolectric.shadows.ShadowLog; -import org.spongycastle.bcpg.sig.KeyFlags; -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.pgp.PgpKeyOperation; -import org.sufficientlysecure.keychain.pgp.UncachedKeyRing; -import org.sufficientlysecure.keychain.pgp.UncachedPublicKey; -import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; -import org.sufficientlysecure.keychain.service.OperationResultParcel; -import org.sufficientlysecure.keychain.service.OperationResults.EditKeyResult; -import org.sufficientlysecure.keychain.service.SaveKeyringParcel; -import org.sufficientlysecure.keychain.support.KeyringTestingHelper.RawPacket; -import org.sufficientlysecure.keychain.util.ProgressScaler; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -@RunWith(RobolectricTestRunner.class) -@org.robolectric.annotation.Config(emulateSdk = 18) // Robolectric doesn't yet support 19 -public class UncachedKeyringTest { - - static UncachedKeyRing staticRing, staticPubRing; - UncachedKeyRing ring, pubRing; - ArrayList onlyA = new ArrayList(); - ArrayList onlyB = new ArrayList(); - PgpKeyOperation op; - SaveKeyringParcel parcel; - - @BeforeClass - public static void setUpOnce() throws Exception { - ShadowLog.stream = System.out; - - SaveKeyringParcel parcel = new SaveKeyringParcel(); - parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( - Constants.choice.algorithm.rsa, 1024, KeyFlags.CERTIFY_OTHER, null)); - parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( - Constants.choice.algorithm.rsa, 1024, KeyFlags.SIGN_DATA, null)); - parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( - Constants.choice.algorithm.rsa, 1024, KeyFlags.ENCRYPT_COMMS, null)); - - parcel.mAddUserIds.add("twi"); - parcel.mAddUserIds.add("pink"); - // passphrase is tested in PgpKeyOperationTest, just use empty here - parcel.mNewPassphrase = ""; - PgpKeyOperation op = new PgpKeyOperation(null); - - EditKeyResult result = op.createSecretKeyRing(parcel); - staticRing = result.getRing(); - staticPubRing = staticRing.extractPublicKeyRing(); - - Assert.assertNotNull("initial test key creation must succeed", staticRing); - - // 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; - pubRing = staticPubRing; - } - - @Test(expected = UnsupportedOperationException.class) - public void testPublicKeyItRemove() throws Exception { - Iterator it = ring.getPublicKeys(); - it.remove(); - } - - @Test(expected = PgpGeneralException.class) - public void testDecodeFromEmpty() throws Exception { - UncachedKeyRing.decodeFromData(new byte[0]); - } - - @Test - public void testArmorIdentity() throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ring.encodeArmored(out, "OpenKeychain"); - - Assert.assertArrayEquals("armor encoded and decoded ring should be identical to original", - ring.getEncoded(), - UncachedKeyRing.decodeFromData(out.toByteArray()).getEncoded()); - } - - @Test(expected = PgpGeneralException.class) - public void testDecodeEncodeMulti() throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - - // encode secret and public ring in here - ring.encodeArmored(out, "OpenKeychain"); - pubRing.encodeArmored(out, "OpenKeychain"); - - Iterator it = - UncachedKeyRing.fromStream(new ByteArrayInputStream(out.toByteArray())); - Assert.assertTrue("there should be two rings in the stream", it.hasNext()); - Assert.assertArrayEquals("first ring should be the first we put in", - ring.getEncoded(), it.next().getEncoded()); - Assert.assertTrue("there should be two rings in the stream", it.hasNext()); - Assert.assertArrayEquals("second ring should be the second we put in", - pubRing.getEncoded(), it.next().getEncoded()); - Assert.assertFalse("there should be two rings in the stream", it.hasNext()); - - // this should fail with PgpGeneralException, since it expects exactly one ring - UncachedKeyRing.decodeFromData(out.toByteArray()); - } - - @Test(expected = RuntimeException.class) - public void testPublicExtractPublic() throws Exception { - // can't do this, either! - pubRing.extractPublicKeyRing(); - } - -} diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/keyimport/FileImportCache.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/keyimport/FileImportCache.java deleted file mode 100644 index 08b8afae7..000000000 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/keyimport/FileImportCache.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2014 Dominik Schürmann - * - * 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 . - */ - -package org.sufficientlysecure.keychain.keyimport; - -import android.content.Context; -import android.os.Bundle; -import android.os.Parcel; - -import org.sufficientlysecure.keychain.KeychainApplication; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * When sending large data (over 1MB) through Androids Binder IPC you get - * JavaBinder E !!! FAILED BINDER TRANSACTION !!! - *

- * To overcome this problem, we cache large Parcelables into a file in our private cache directory - * instead of sending them through IPC. - */ -public class FileImportCache { - - private Context mContext; - - private static final String FILENAME = "key_import.pcl"; - private static final String BUNDLE_DATA = "data"; - - public FileImportCache(Context context) { - this.mContext = context; - } - - public void writeCache(ArrayList selectedEntries) throws IOException { - Bundle in = new Bundle(); - in.putParcelableArrayList(BUNDLE_DATA, selectedEntries); - File cacheDir = mContext.getCacheDir(); - if (cacheDir == null) { - // https://groups.google.com/forum/#!topic/android-developers/-694j87eXVU - throw new IOException("cache dir is null!"); - } - File tempFile = new File(mContext.getCacheDir(), FILENAME); - - FileOutputStream fos = new FileOutputStream(tempFile); - Parcel p = Parcel.obtain(); // creating empty parcel object - in.writeToParcel(p, 0); // saving bundle as parcel - fos.write(p.marshall()); // writing parcel to file - fos.flush(); - fos.close(); - } - - public List readCache() throws IOException { - Parcel parcel = Parcel.obtain(); // creating empty parcel object - Bundle out; - File cacheDir = mContext.getCacheDir(); - if (cacheDir == null) { - // https://groups.google.com/forum/#!topic/android-developers/-694j87eXVU - throw new IOException("cache dir is null!"); - } - - File tempFile = new File(cacheDir, FILENAME); - try { - FileInputStream fis = new FileInputStream(tempFile); - byte[] array = new byte[(int) fis.getChannel().size()]; - fis.read(array, 0, array.length); - fis.close(); - - parcel.unmarshall(array, 0, array.length); - parcel.setDataPosition(0); - out = parcel.readBundle(KeychainApplication.class.getClassLoader()); - out.putAll(out); - - return out.getParcelableArrayList(BUNDLE_DATA); - } finally { - parcel.recycle(); - // delete temp file - tempFile.delete(); - } - } -} diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/util/FileImportCache.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/util/FileImportCache.java new file mode 100644 index 000000000..e09cdd502 --- /dev/null +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/util/FileImportCache.java @@ -0,0 +1,179 @@ +/* + * Copyright (C) 2014 Dominik Schürmann + * + * 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 . + */ + +package org.sufficientlysecure.keychain.util; + +import android.content.Context; +import android.os.Parcel; +import android.os.Parcelable; + +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.KeychainApplication; +import org.sufficientlysecure.keychain.util.Log; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +/** + * When sending large data (over 1MB) through Androids Binder IPC you get + * JavaBinder E !!! FAILED BINDER TRANSACTION !!! + *

+ * To overcome this problem, we cache large Parcelables into a file in our private cache directory + * instead of sending them through IPC. + */ +public class FileImportCache { + + private Context mContext; + + private static final String FILENAME = "key_import.pcl"; + + public FileImportCache(Context context) { + this.mContext = context; + } + + public void writeCache(ArrayList selectedEntries) throws IOException { + writeCache(selectedEntries.iterator()); + } + + public void writeCache(Iterator it) throws IOException { + + File cacheDir = mContext.getCacheDir(); + if (cacheDir == null) { + // https://groups.google.com/forum/#!topic/android-developers/-694j87eXVU + throw new IOException("cache dir is null!"); + } + + File tempFile = new File(mContext.getCacheDir(), FILENAME); + + ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(tempFile)); + + while (it.hasNext()) { + E ring = it.next(); + Parcel p = Parcel.obtain(); // creating empty parcel object + p.writeParcelable(ring, 0); // saving bundle as parcel + oos.writeObject(p.marshall()); // writing parcel to file + p.recycle(); + } + + oos.close(); + + } + + public List readCacheIntoList() throws IOException { + ArrayList result = new ArrayList(); + Iterator it = readCache(); + while (it.hasNext()) { + result.add(it.next()); + } + return result; + } + + public Iterator readCache() throws IOException { + + File cacheDir = mContext.getCacheDir(); + if (cacheDir == null) { + // https://groups.google.com/forum/#!topic/android-developers/-694j87eXVU + throw new IOException("cache dir is null!"); + } + + final File tempFile = new File(cacheDir, FILENAME); + final ObjectInputStream ois = new ObjectInputStream(new FileInputStream(tempFile)); + + return new Iterator() { + + E mRing = null; + boolean closed = false; + + private void readNext() { + if (mRing != null || closed) { + Log.e(Constants.TAG, "err!"); + return; + } + + try { + if (ois.available() == 0) { + return; + } + + byte[] data = (byte[]) ois.readObject(); + Log.e(Constants.TAG, "bla"); + if (data == null) { + if (!closed) { + closed = true; + ois.close(); + tempFile.delete(); + } + return; + } + + Parcel parcel = Parcel.obtain(); // creating empty parcel object + parcel.unmarshall(data, 0, data.length); + parcel.setDataPosition(0); + mRing = parcel.readParcelable(KeychainApplication.class.getClassLoader()); + parcel.recycle(); + } catch (ClassNotFoundException e) { + Log.e(Constants.TAG, "Encountered ClassNotFoundException during cache read, this is a bug!"); + } catch (IOException e) { + Log.e(Constants.TAG, "Encountered IOException during cache read!"); + } + + } + + @Override + public boolean hasNext() { + readNext(); + return mRing != null; + } + + @Override + public E next() { + readNext(); + try { + return mRing; + } finally { + mRing = null; + } + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + + @Override + public void finalize() throws Throwable { + super.finalize(); + if (!closed) { + try { + ois.close(); + tempFile.delete(); + } catch (IOException e) { + // never mind + } + } + } + + }; + } +} -- cgit v1.2.3 From c0edaf9a5ea7629ebfcf2250cf5684370120bb17 Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Fri, 1 Aug 2014 16:49:41 +0200 Subject: make FileImportCache generic, iterable, and add unit test --- .../keychain/util/FileImportCacheTest.java | 54 ++++++++++++++++++++++ .../keychain/service/KeychainIntentService.java | 10 ++-- .../keychain/ui/ImportKeysActivity.java | 4 +- .../keychain/util/FileImportCache.java | 52 ++++++++++----------- 4 files changed, 89 insertions(+), 31 deletions(-) create mode 100644 OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/util/FileImportCacheTest.java diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/util/FileImportCacheTest.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/util/FileImportCacheTest.java new file mode 100644 index 000000000..b5708b46f --- /dev/null +++ b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/util/FileImportCacheTest.java @@ -0,0 +1,54 @@ +package org.sufficientlysecure.keychain.util; + +import android.os.Bundle; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.Robolectric; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.shadows.ShadowLog; + +import java.util.ArrayList; +import java.util.List; + +@RunWith(RobolectricTestRunner.class) +@org.robolectric.annotation.Config(emulateSdk = 18) // Robolectric doesn't yet support 19 +public class FileImportCacheTest { + + @Before + public void setUp() throws Exception { + ShadowLog.stream = System.out; + } + + @Test + public void testInputOutput() throws Exception { + + FileImportCache cache = new FileImportCache(Robolectric.application); + + ArrayList list = new ArrayList(); + + for (int i = 0; i < 50; i++) { + Bundle b = new Bundle(); + b.putInt("key1", i); + b.putString("key2", Integer.toString(i)); + list.add(b); + } + + // write to cache file + cache.writeCache(list); + + // read back + List last = cache.readCacheIntoList(); + + for (int i = 0; i < list.size(); i++) { + Assert.assertEquals("input values should be equal to output values", + list.get(i).getInt("key1"), last.get(i).getInt("key1")); + Assert.assertEquals("input values should be equal to output values", + list.get(i).getString("key2"), last.get(i).getString("key2")); + } + + } + +} diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java index 8d4717eeb..c87e490be 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java @@ -24,6 +24,7 @@ import android.net.Uri; import android.os.Bundle; import android.os.Message; import android.os.Messenger; +import android.os.Parcel; import android.os.RemoteException; import org.sufficientlysecure.keychain.Constants; @@ -31,7 +32,7 @@ import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.helper.FileHelper; import org.sufficientlysecure.keychain.helper.OtherHelper; import org.sufficientlysecure.keychain.helper.Preferences; -import org.sufficientlysecure.keychain.keyimport.FileImportCache; +import org.sufficientlysecure.keychain.util.FileImportCache; import org.sufficientlysecure.keychain.keyimport.HkpKeyserver; import org.sufficientlysecure.keychain.keyimport.ImportKeysListEntry; import org.sufficientlysecure.keychain.keyimport.KeybaseKeyserver; @@ -387,14 +388,16 @@ public class KeychainIntentService extends IntentService } } else if (ACTION_IMPORT_KEYRING.equals(action)) { try { + List entries; if (data.containsKey(IMPORT_KEY_LIST)) { // get entries from intent entries = data.getParcelableArrayList(IMPORT_KEY_LIST); } else { // get entries from cached file - FileImportCache cache = new FileImportCache(this); - entries = cache.readCache(); + FileImportCache cache = + new FileImportCache(this); + entries = cache.readCacheIntoList(); } PgpImportExport pgpImportExport = new PgpImportExport(this, this); @@ -523,6 +526,7 @@ public class KeychainIntentService extends IntentService Intent importIntent = new Intent(this, KeychainIntentService.class); importIntent.setAction(ACTION_IMPORT_KEYRING); + Bundle importData = new Bundle(); // This is not going through binder, nothing to fear of importData.putParcelableArrayList(IMPORT_KEY_LIST, keyRings); diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java index dbc557f9a..4a606a1b3 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java @@ -40,7 +40,7 @@ import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.helper.OtherHelper; import org.sufficientlysecure.keychain.helper.Preferences; -import org.sufficientlysecure.keychain.keyimport.FileImportCache; +import org.sufficientlysecure.keychain.util.FileImportCache; import org.sufficientlysecure.keychain.keyimport.ImportKeysListEntry; import org.sufficientlysecure.keychain.keyimport.ParcelableKeyRing; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; @@ -503,7 +503,7 @@ public class ImportKeysActivity extends ActionBarActivity { // to prevent Java Binder problems on heavy imports // read FileImportCache for more info. try { - FileImportCache cache = new FileImportCache(this); + FileImportCache cache = new FileImportCache(this); cache.writeCache(selectedEntries); intent.putExtra(KeychainIntentService.EXTRA_DATA, data); diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/util/FileImportCache.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/util/FileImportCache.java index e09cdd502..5a4bf5311 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/util/FileImportCache.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/util/FileImportCache.java @@ -23,14 +23,14 @@ import android.os.Parcelable; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.KeychainApplication; -import org.sufficientlysecure.keychain.util.Log; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -66,13 +66,14 @@ public class FileImportCache { File tempFile = new File(mContext.getCacheDir(), FILENAME); - ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(tempFile)); + DataOutputStream oos = new DataOutputStream(new FileOutputStream(tempFile)); while (it.hasNext()) { - E ring = it.next(); Parcel p = Parcel.obtain(); // creating empty parcel object - p.writeParcelable(ring, 0); // saving bundle as parcel - oos.writeObject(p.marshall()); // writing parcel to file + p.writeParcelable(it.next(), 0); // saving bundle as parcel + byte[] buf = p.marshall(); + oos.writeInt(buf.length); + oos.write(buf); p.recycle(); } @@ -98,44 +99,37 @@ public class FileImportCache { } final File tempFile = new File(cacheDir, FILENAME); - final ObjectInputStream ois = new ObjectInputStream(new FileInputStream(tempFile)); + final DataInputStream ois = new DataInputStream(new FileInputStream(tempFile)); return new Iterator() { E mRing = null; boolean closed = false; + byte[] buf = new byte[512]; private void readNext() { if (mRing != null || closed) { - Log.e(Constants.TAG, "err!"); return; } try { - if (ois.available() == 0) { - return; - } - byte[] data = (byte[]) ois.readObject(); - Log.e(Constants.TAG, "bla"); - if (data == null) { - if (!closed) { - closed = true; - ois.close(); - tempFile.delete(); - } - return; + int length = ois.readInt(); + while (buf.length < length) { + buf = new byte[buf.length * 2]; } + ois.readFully(buf, 0, length); Parcel parcel = Parcel.obtain(); // creating empty parcel object - parcel.unmarshall(data, 0, data.length); + parcel.unmarshall(buf, 0, length); parcel.setDataPosition(0); mRing = parcel.readParcelable(KeychainApplication.class.getClassLoader()); parcel.recycle(); - } catch (ClassNotFoundException e) { - Log.e(Constants.TAG, "Encountered ClassNotFoundException during cache read, this is a bug!"); + } catch (EOFException e) { + // aight + close(); } catch (IOException e) { - Log.e(Constants.TAG, "Encountered IOException during cache read!"); + Log.e(Constants.TAG, "Encountered IOException during cache read!", e); } } @@ -163,17 +157,23 @@ public class FileImportCache { @Override public void finalize() throws Throwable { + close(); super.finalize(); + } + + private void close() { if (!closed) { try { ois.close(); tempFile.delete(); } catch (IOException e) { - // never mind + // nvm } } + closed = true; } + }; } } -- cgit v1.2.3 From 827a958e123184ae70c2c5e5b10ab47f50ef1a52 Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Fri, 1 Aug 2014 17:00:08 +0200 Subject: remove debug output about security providers (cleaner unit tests) --- .../main/java/org/sufficientlysecure/keychain/KeychainApplication.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/KeychainApplication.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/KeychainApplication.java index dfd39b345..e70b134aa 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/KeychainApplication.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/KeychainApplication.java @@ -61,6 +61,7 @@ public class KeychainApplication extends Application { PRNGFixes.apply(); Log.d(Constants.TAG, "Bouncy Castle set and PRNG Fixes applied!"); + /* if (Constants.DEBUG) { Provider[] providers = Security.getProviders(); Log.d(Constants.TAG, "Installed Security Providers:"); @@ -68,6 +69,7 @@ public class KeychainApplication extends Application { Log.d(Constants.TAG, "provider class: " + p.getClass().getName()); } } + */ // Create APG directory on sdcard if not existing if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { -- cgit v1.2.3 From f555447011a4d975e87d99ddc5f512c3205c2211 Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Fri, 1 Aug 2014 17:36:34 +0200 Subject: fix dumb mistake in modifySecretKey --- .../keychain/pgp/PgpKeyOperationTest.java | 18 ++++++++---------- .../keychain/pgp/PgpKeyOperation.java | 2 +- .../keychain/pgp/UncachedPublicKey.java | 6 +----- 3 files changed, 10 insertions(+), 16 deletions(-) diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperationTest.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperationTest.java index 516d1ac63..0e0ec7ee2 100644 --- a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperationTest.java +++ b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperationTest.java @@ -34,6 +34,7 @@ import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; +import java.util.List; import java.util.Random; @RunWith(RobolectricTestRunner.class) @@ -202,8 +203,8 @@ public class PgpKeyOperationTest { Assert.assertEquals("number of user ids must be two", 2, ring.getPublicKey().getUnorderedUserIds().size()); - Assert.assertEquals("number of subkeys must be three", - 3, KeyringTestingHelper.itToList(ring.getPublicKeys()).size()); + List subkeys = KeyringTestingHelper.itToList(ring.getPublicKeys()); + Assert.assertEquals("number of subkeys must be three", 3, subkeys.size()); Assert.assertTrue("key ring should have been created in the last 120 seconds", ring.getPublicKey().getCreationTime().after(new Date(new Date().getTime()-1000*120))); @@ -211,24 +212,21 @@ public class PgpKeyOperationTest { Assert.assertNull("key ring should not expire", ring.getPublicKey().getExpiryTime()); - Iterator it = ring.getPublicKeys(); - Assert.assertEquals("first (master) key can certify", - KeyFlags.CERTIFY_OTHER, it.next().getKeyUsage()); + KeyFlags.CERTIFY_OTHER, subkeys.get(0).getKeyUsage()); - UncachedPublicKey signingKey = it.next(); Assert.assertEquals("second key can sign", - KeyFlags.SIGN_DATA, signingKey.getKeyUsage()); - ArrayList sigs = signingKey.getSignatures().next().getEmbeddedSignatures(); + KeyFlags.SIGN_DATA, subkeys.get(1).getKeyUsage()); + ArrayList sigs = subkeys.get(1).getSignatures().next().getEmbeddedSignatures(); Assert.assertEquals("signing key signature should have one embedded signature", 1, sigs.size()); Assert.assertEquals("embedded signature should be of primary key binding type", PGPSignature.PRIMARYKEY_BINDING, sigs.get(0).getSignatureType()); Assert.assertEquals("primary key binding signature issuer should be signing subkey", - signingKey.getKeyId(), sigs.get(0).getKeyId()); + subkeys.get(1).getKeyId(), sigs.get(0).getKeyId()); Assert.assertEquals("third key can encrypt", - KeyFlags.ENCRYPT_COMMS, it.next().getKeyUsage()); + KeyFlags.ENCRYPT_COMMS, subkeys.get(2).getKeyUsage()); } diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java index 861f93446..19b0d81b7 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java @@ -609,7 +609,7 @@ public class PgpKeyOperation { for (int i = 0; i < saveParcel.mAddSubKeys.size(); i++) { progress(R.string.progress_modify_subkeyadd, (i-1) * (100 / saveParcel.mAddSubKeys.size())); - SaveKeyringParcel.SubkeyAdd add = saveParcel.mAddSubKeys.get(0); + SaveKeyringParcel.SubkeyAdd add = saveParcel.mAddSubKeys.get(i); log.add(LogLevel.INFO, LogType.MSG_MF_SUBKEY_NEW, indent); if (add.mExpiry != null && new Date(add.mExpiry*1000).before(new Date())) { diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/UncachedPublicKey.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/UncachedPublicKey.java index 358b1c552..4a03d942b 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/UncachedPublicKey.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/UncachedPublicKey.java @@ -169,6 +169,7 @@ public class UncachedPublicKey { } @SuppressWarnings("unchecked") + // TODO make this safe public int getKeyUsage() { if(mCacheUsage == null) { mCacheUsage = 0; @@ -182,11 +183,6 @@ public class UncachedPublicKey { if (hashed != null) { mCacheUsage |= hashed.getKeyFlags(); } - - PGPSignatureSubpacketVector unhashed = sig.getUnhashedSubPackets(); - if (unhashed != null) { - mCacheUsage |= unhashed.getKeyFlags(); - } } } } -- cgit v1.2.3 From c9b028804cc4eed313ffe67baba3a60b02995166 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Fri, 1 Aug 2014 17:47:07 +0200 Subject: Add user id with dialog --- .../sufficientlysecure/keychain/pgp/KeyRing.java | 28 ++- .../keychain/ui/CreateKeyFinalFragment.java | 3 +- .../keychain/ui/EditKeyFragment.java | 44 +++- .../keychain/ui/adapter/SubkeysAdapter.java | 2 +- .../keychain/ui/adapter/UserIdsAdapter.java | 21 +- .../keychain/ui/adapter/UserIdsAddedAdapter.java | 181 ++++---------- .../ui/dialog/AddUserIdDialogFragment.java | 268 +++++++++++++++++++++ .../keychain/ui/widget/UserIdEditor.java | 2 +- .../src/main/res/layout/add_user_id_dialog.xml | 41 ++++ .../main/res/layout/create_key_input_fragment.xml | 1 + .../res/layout/edit_key_user_id_added_item.xml | 58 ----- .../src/main/res/layout/edit_key_user_id_item.xml | 2 +- .../src/main/res/layout/view_key_subkey_item.xml | 4 +- .../src/main/res/layout/view_key_user_id_item.xml | 22 +- OpenKeychain/src/main/res/values/strings.xml | 6 +- extern/openkeychain-api-lib | 2 +- extern/openpgp-api-lib | 2 +- extern/spongycastle | 2 +- 18 files changed, 458 insertions(+), 231 deletions(-) create mode 100644 OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/AddUserIdDialogFragment.java create mode 100644 OpenKeychain/src/main/res/layout/add_user_id_dialog.xml delete mode 100644 OpenKeychain/src/main/res/layout/edit_key_user_id_added_item.xml diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/KeyRing.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/KeyRing.java index ebc49ab05..7d11a20d3 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/KeyRing.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/KeyRing.java @@ -1,12 +1,15 @@ package org.sufficientlysecure.keychain.pgp; +import android.text.TextUtils; + import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; import java.util.regex.Matcher; import java.util.regex.Pattern; -/** An abstract KeyRing. - * +/** + * An abstract KeyRing. + *

* This is an abstract class for all KeyRing constructs. It serves as a common * denominator of available information, two implementations wrapping the same * keyring should in all cases agree on the output of all methods described @@ -14,7 +17,6 @@ import java.util.regex.Pattern; * * @see CanonicalizedKeyRing * @see org.sufficientlysecure.keychain.provider.CachedPublicKeyRing - * */ public abstract class KeyRing { @@ -77,4 +79,24 @@ public abstract class KeyRing { return result; } + /** + * Returns a composed user id. Returns null if name is null! + * + * @param name + * @param email + * @param comment + * @return + */ + public static String createUserId(String name, String email, String comment) { + String userId = name; // consider name a required value + if (userId != null && !TextUtils.isEmpty(comment)) { + userId += " (" + comment + ")"; + } + if (userId != null && !TextUtils.isEmpty(email)) { + userId += " <" + email + ">"; + } + + return userId; + } + } diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyFinalFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyFinalFragment.java index f9ed16cba..662ba4ce1 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyFinalFragment.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyFinalFragment.java @@ -35,6 +35,7 @@ import org.spongycastle.bcpg.sig.KeyFlags; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.helper.Preferences; +import org.sufficientlysecure.keychain.pgp.KeyRing; import org.sufficientlysecure.keychain.provider.KeychainContract; import org.sufficientlysecure.keychain.service.KeychainIntentService; import org.sufficientlysecure.keychain.service.KeychainIntentServiceHandler; @@ -171,7 +172,7 @@ public class CreateKeyFinalFragment extends Fragment { parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd(Constants.choice.algorithm.rsa, 4096, KeyFlags.CERTIFY_OTHER, null)); parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd(Constants.choice.algorithm.rsa, 4096, KeyFlags.SIGN_DATA, null)); parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd(Constants.choice.algorithm.rsa, 4096, KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE, null)); - String userId = mName + " <" + mEmail + ">"; + String userId = KeyRing.createUserId(mName, mEmail, null); parcel.mAddUserIds.add(userId); parcel.mNewPassphrase = mPassphrase; diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyFragment.java index 9083d1567..b76755bb2 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyFragment.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyFragment.java @@ -43,6 +43,8 @@ import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.compatibility.DialogFragmentWorkaround; import org.sufficientlysecure.keychain.helper.ActionBarHelper; import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKeyRing; +import org.sufficientlysecure.keychain.pgp.KeyRing; +import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; import org.sufficientlysecure.keychain.provider.KeychainContract; import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.service.KeychainIntentService; @@ -55,6 +57,7 @@ import org.sufficientlysecure.keychain.ui.adapter.SubkeysAdapter; import org.sufficientlysecure.keychain.ui.adapter.SubkeysAddedAdapter; import org.sufficientlysecure.keychain.ui.adapter.UserIdsAdapter; import org.sufficientlysecure.keychain.ui.adapter.UserIdsAddedAdapter; +import org.sufficientlysecure.keychain.ui.dialog.AddUserIdDialogFragment; import org.sufficientlysecure.keychain.ui.dialog.ChangeExpiryDialogFragment; import org.sufficientlysecure.keychain.ui.dialog.EditSubkeyDialogFragment; import org.sufficientlysecure.keychain.ui.dialog.EditUserIdDialogFragment; @@ -89,11 +92,10 @@ public class EditKeyFragment extends LoaderFragment implements private UserIdsAddedAdapter mUserIdsAddedAdapter; private SubkeysAddedAdapter mSubkeysAddedAdapter; - private ArrayList mUserIdsAddedData; - private Uri mDataUri; private SaveKeyringParcel mSaveKeyringParcel; + private String mPrimaryUserId; private String mCurrentPassphrase; @@ -173,8 +175,13 @@ public class EditKeyFragment extends LoaderFragment implements mSaveKeyringParcel = new SaveKeyringParcel(keyRing.getMasterKeyId(), keyRing.getUncachedKeyRing().getFingerprint()); + mPrimaryUserId = keyRing.getPrimaryUserIdWithFallback(); } catch (ProviderHelper.NotFoundException e) { - Log.e(Constants.TAG, "Keyring not found: " + e.getMessage(), e); + Log.e(Constants.TAG, "Keyring not found", e); + Toast.makeText(getActivity(), R.string.error_no_secret_key_found, Toast.LENGTH_SHORT).show(); + getActivity().finish(); + } catch (PgpGeneralException e) { + Log.e(Constants.TAG, "PgpGeneralException", e); Toast.makeText(getActivity(), R.string.error_no_secret_key_found, Toast.LENGTH_SHORT).show(); getActivity().finish(); } @@ -213,9 +220,8 @@ public class EditKeyFragment extends LoaderFragment implements } }); - // TODO: mUserIdsAddedData and SaveParcel from savedInstance?! - mUserIdsAddedData = new ArrayList(); - mUserIdsAddedAdapter = new UserIdsAddedAdapter(getActivity(), mUserIdsAddedData); + // TODO: SaveParcel from savedInstance?! + mUserIdsAddedAdapter = new UserIdsAddedAdapter(getActivity(), mSaveKeyringParcel.mAddUserIds); mUserIdsAddedList.setAdapter(mUserIdsAddedAdapter); mSubkeysAdapter = new SubkeysAdapter(getActivity(), null, 0, mSaveKeyringParcel); @@ -421,7 +427,29 @@ public class EditKeyFragment extends LoaderFragment implements } private void addUserId() { - mUserIdsAddedAdapter.add(new UserIdsAddedAdapter.UserIdModel()); + // Message is received after passphrase is cached + Handler returnHandler = new Handler() { + @Override + public void handleMessage(Message message) { + if (message.what == SetPassphraseDialogFragment.MESSAGE_OKAY) { + Bundle data = message.getData(); + + // add new user id + mUserIdsAddedAdapter.add(data + .getString(AddUserIdDialogFragment.MESSAGE_DATA_USER_ID)); + } + } + }; + + // Create a new Messenger for the communication back + Messenger messenger = new Messenger(returnHandler); + + // pre-fill out primary name + String predefinedName = KeyRing.splitUserId(mPrimaryUserId)[0]; + AddUserIdDialogFragment addUserIdDialog = AddUserIdDialogFragment.newInstance(messenger, + predefinedName); + + addUserIdDialog.show(getActivity().getSupportFragmentManager(), "addUserIdDialog"); } private void addSubkey() { @@ -451,8 +479,6 @@ public class EditKeyFragment extends LoaderFragment implements } private void save(String passphrase) { - mSaveKeyringParcel.mAddUserIds = mUserIdsAddedAdapter.getDataAsStringList(); - Log.d(Constants.TAG, "mSaveKeyringParcel.mAddUserIds: " + mSaveKeyringParcel.mAddUserIds); Log.d(Constants.TAG, "mSaveKeyringParcel.mNewPassphrase: " + mSaveKeyringParcel.mNewPassphrase); Log.d(Constants.TAG, "mSaveKeyringParcel.mRevokeUserIds: " + mSaveKeyringParcel.mRevokeUserIds); diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SubkeysAdapter.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SubkeysAdapter.java index e5dbebe01..c2a882fdb 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SubkeysAdapter.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/SubkeysAdapter.java @@ -114,7 +114,7 @@ public class SubkeysAdapter extends CursorAdapter { ImageView vEncryptIcon = (ImageView) view.findViewById(R.id.ic_encryptKey); ImageView vSignIcon = (ImageView) view.findViewById(R.id.ic_signKey); ImageView vRevokedKeyIcon = (ImageView) view.findViewById(R.id.ic_revokedKey); - ImageView vEditImage = (ImageView) view.findViewById(R.id.edit_image); + ImageView vEditImage = (ImageView) view.findViewById(R.id.user_id_item_edit_image); long keyId = cursor.getLong(INDEX_KEY_ID); String keyIdStr = PgpKeyHelper.convertKeyIdToHex(keyId); diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/UserIdsAdapter.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/UserIdsAdapter.java index 6d46f3c8f..ee3341c08 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/UserIdsAdapter.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/UserIdsAdapter.java @@ -102,11 +102,14 @@ public class UserIdsAdapter extends CursorAdapter implements AdapterView.OnItemC @Override public void bindView(View view, Context context, Cursor cursor) { - TextView vName = (TextView) view.findViewById(R.id.userId); - TextView vAddress = (TextView) view.findViewById(R.id.address); - TextView vComment = (TextView) view.findViewById(R.id.comment); - ImageView vVerified = (ImageView) view.findViewById(R.id.certified); - ImageView vEditImage = (ImageView) view.findViewById(R.id.edit_image); + TextView vName = (TextView) view.findViewById(R.id.user_id_item_name); + TextView vAddress = (TextView) view.findViewById(R.id.user_id_item_address); + TextView vComment = (TextView) view.findViewById(R.id.user_id_item_comment); + ImageView vVerified = (ImageView) view.findViewById(R.id.user_id_item_certified); + View vVerifiedLayout = view.findViewById(R.id.user_id_item_certified_layout); + ImageView vEditImage = (ImageView) view.findViewById(R.id.user_id_item_edit_image); + ImageView vDeleteButton = (ImageView) view.findViewById(R.id.user_id_item_delete_button); + vDeleteButton.setVisibility(View.GONE); // not used String userId = cursor.getString(INDEX_USER_ID); String[] splitUserId = KeyRing.splitUserId(userId); @@ -152,8 +155,10 @@ public class UserIdsAdapter extends CursorAdapter implements AdapterView.OnItemC } vEditImage.setVisibility(View.VISIBLE); + vVerifiedLayout.setVisibility(View.GONE); } else { vEditImage.setVisibility(View.GONE); + vVerifiedLayout.setVisibility(View.VISIBLE); } if (isRevoked) { @@ -211,7 +216,7 @@ public class UserIdsAdapter extends CursorAdapter implements AdapterView.OnItemC return; } - final CheckBox vCheckBox = (CheckBox) view.findViewById(R.id.checkBox); + final CheckBox vCheckBox = (CheckBox) view.findViewById(R.id.user_id_item_check_box); final int position = cursor.getPosition(); vCheckBox.setOnCheckedChangeListener(null); vCheckBox.setChecked(mCheckStates.get(position)); @@ -225,7 +230,7 @@ public class UserIdsAdapter extends CursorAdapter implements AdapterView.OnItemC } public void onItemClick(AdapterView adapter, View view, int position, long id) { - CheckBox box = ((CheckBox) view.findViewById(R.id.checkBox)); + CheckBox box = ((CheckBox) view.findViewById(R.id.user_id_item_check_box)); if (box != null) { box.toggle(); } @@ -251,7 +256,7 @@ public class UserIdsAdapter extends CursorAdapter implements AdapterView.OnItemC public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = mInflater.inflate(R.layout.view_key_user_id_item, null); // only need to do this once ever, since mShowCheckBoxes is final - view.findViewById(R.id.checkBox).setVisibility(mCheckStates != null ? View.VISIBLE : View.GONE); + view.findViewById(R.id.user_id_item_check_box).setVisibility(mCheckStates != null ? View.VISIBLE : View.GONE); return view; } diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/UserIdsAddedAdapter.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/UserIdsAddedAdapter.java index 3fe5574ee..15ac11e0b 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/UserIdsAddedAdapter.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/UserIdsAddedAdapter.java @@ -19,162 +19,65 @@ package org.sufficientlysecure.keychain.ui.adapter; import android.app.Activity; import android.content.Context; -import android.text.Editable; -import android.text.TextUtils; -import android.text.TextWatcher; -import android.util.Patterns; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; -import android.widget.AutoCompleteTextView; -import android.widget.EditText; +import android.widget.CheckBox; import android.widget.ImageButton; +import android.widget.ImageView; +import android.widget.TextView; import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.helper.ContactHelper; +import org.sufficientlysecure.keychain.pgp.KeyRing; -import java.util.ArrayList; import java.util.List; -import java.util.regex.Matcher; -public class UserIdsAddedAdapter extends ArrayAdapter { +public class UserIdsAddedAdapter extends ArrayAdapter { private LayoutInflater mInflater; - private Activity mActivity; - - private ArrayAdapter mAutoCompleteNameAdapter; - private ArrayAdapter mAutoCompleteEmailAdapter; // hold a private reference to the underlying data List - private List mData; - - public static class UserIdModel { - String name = ""; - String address = ""; - String comment = ""; - - @Override - public String toString() { - String userId = name; - if (!TextUtils.isEmpty(comment)) { - userId += " (" + comment + ")"; - } - if (!TextUtils.isEmpty(address)) { - userId += " <" + address + ">"; - } - return userId; - } - } + private List mData; - public UserIdsAddedAdapter(Activity activity, List data) { + public UserIdsAddedAdapter(Activity activity, List data) { super(activity, -1, data); - mActivity = activity; mInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mData = data; - mAutoCompleteNameAdapter = new ArrayAdapter - (mActivity, android.R.layout.simple_spinner_dropdown_item, - ContactHelper.getPossibleUserNames(mActivity) - ); - mAutoCompleteEmailAdapter = new ArrayAdapter - (mActivity, android.R.layout.simple_spinner_dropdown_item, - ContactHelper.getPossibleUserEmails(mActivity) - ); } - public ArrayList getDataAsStringList() { - ArrayList out = new ArrayList(); - for (UserIdModel id : mData) { - // ignore empty user ids - if (!TextUtils.isEmpty(id.toString())) { - out.add(id.toString()); - } - } - - return out; + public List getData() { + return mData; } static class ViewHolder { - public AutoCompleteTextView vAddress; - public AutoCompleteTextView vName; - public EditText vComment; + public TextView vAddress; + public TextView vName; + public TextView vComment; public ImageButton vDelete; // also hold a reference to the model item - public UserIdModel mModel; + public String mModel; } public View getView(final int position, View convertView, ViewGroup parent) { if (convertView == null) { // Not recycled, inflate a new view - convertView = mInflater.inflate(R.layout.edit_key_user_id_added_item, null); + convertView = mInflater.inflate(R.layout.view_key_user_id_item, null); final ViewHolder holder = new ViewHolder(); - holder.vAddress = (AutoCompleteTextView) convertView.findViewById(R.id.user_id_added_item_address); - holder.vName = (AutoCompleteTextView) convertView.findViewById(R.id.user_id_added_item_name); - holder.vComment = (EditText) convertView.findViewById(R.id.user_id_added_item_comment); - holder.vDelete = (ImageButton) convertView.findViewById(R.id.user_id_added_item_delete); - convertView.setTag(holder); - - holder.vAddress.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - } - - @Override - public void afterTextChanged(Editable s) { - // update referenced item in view holder - holder.mModel.address = s.toString(); - - // show icon on valid email addresses - if (holder.mModel.address.length() > 0) { - Matcher emailMatcher = Patterns.EMAIL_ADDRESS.matcher(holder.mModel.address); - if (emailMatcher.matches()) { - holder.vAddress.setCompoundDrawablesWithIntrinsicBounds(0, 0, - R.drawable.uid_mail_ok, 0); - } else { - holder.vAddress.setCompoundDrawablesWithIntrinsicBounds(0, 0, - R.drawable.uid_mail_bad, 0); - } - } else { - // remove drawable if email is empty - holder.vAddress.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); - } - } - }); - - holder.vName.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - } - - @Override - public void afterTextChanged(Editable s) { - // update referenced item in view holder - holder.mModel.name = s.toString(); - } - }); - - holder.vComment.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - } + holder.vAddress = (TextView) convertView.findViewById(R.id.user_id_item_address); + holder.vName = (TextView) convertView.findViewById(R.id.user_id_item_name); + holder.vComment = (TextView) convertView.findViewById(R.id.user_id_item_comment); + holder.vDelete = (ImageButton) convertView.findViewById(R.id.user_id_item_delete_button); + holder.vDelete.setVisibility(View.VISIBLE); // always visible + + // not used: + CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.user_id_item_check_box); + View certifiedLayout = convertView.findViewById(R.id.user_id_item_certified_layout); + ImageView editImage = (ImageView) convertView.findViewById(R.id.user_id_item_edit_image); + checkBox.setVisibility(View.GONE); + certifiedLayout.setVisibility(View.GONE); + editImage.setVisibility(View.GONE); - @Override - public void afterTextChanged(Editable s) { - // update referenced item in view holder - holder.mModel.comment = s.toString(); - } - }); + convertView.setTag(holder); holder.vDelete.setOnClickListener(new View.OnClickListener() { @Override @@ -183,22 +86,30 @@ public class UserIdsAddedAdapter extends ArrayAdapter + * + * 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 . + */ + +package org.sufficientlysecure.keychain.ui.dialog; + +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.DialogInterface.OnClickListener; +import android.os.Bundle; +import android.os.Message; +import android.os.Messenger; +import android.os.RemoteException; +import android.support.v4.app.DialogFragment; +import android.text.Editable; +import android.text.TextUtils; +import android.text.TextWatcher; +import android.util.Patterns; +import android.view.KeyEvent; +import android.view.LayoutInflater; +import android.view.View; +import android.view.inputmethod.EditorInfo; +import android.view.inputmethod.InputMethodManager; +import android.widget.ArrayAdapter; +import android.widget.AutoCompleteTextView; +import android.widget.Button; +import android.widget.EditText; +import android.widget.TextView; +import android.widget.TextView.OnEditorActionListener; + +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.helper.ContactHelper; +import org.sufficientlysecure.keychain.pgp.KeyRing; +import org.sufficientlysecure.keychain.util.Log; + +import java.util.regex.Matcher; + +public class AddUserIdDialogFragment extends DialogFragment implements OnEditorActionListener { + private static final String ARG_MESSENGER = "messenger"; + private static final String ARG_NAME = "name"; + + public static final int MESSAGE_OKAY = 1; + public static final int MESSAGE_CANCEL = 2; + + public static final String MESSAGE_DATA_USER_ID = "user_id"; + + private Messenger mMessenger; + private AutoCompleteTextView mName; + private AutoCompleteTextView mEmail; + private EditText mComment; + + public static AddUserIdDialogFragment newInstance(Messenger messenger, String predefinedName) { + + AddUserIdDialogFragment frag = new AddUserIdDialogFragment(); + Bundle args = new Bundle(); + args.putParcelable(ARG_MESSENGER, messenger); + args.putString(ARG_NAME, predefinedName); + frag.setArguments(args); + + return frag; + } + + /** + * Creates dialog + */ + @Override + public Dialog onCreateDialog(Bundle savedInstanceState) { + final Activity activity = getActivity(); + mMessenger = getArguments().getParcelable(ARG_MESSENGER); + String predefinedName = getArguments().getString(ARG_NAME); + + ArrayAdapter autoCompleteEmailAdapter = new ArrayAdapter + (getActivity(), android.R.layout.simple_spinner_dropdown_item, + ContactHelper.getPossibleUserEmails(getActivity()) + ); + + CustomAlertDialogBuilder alert = new CustomAlertDialogBuilder(activity); + + alert.setTitle(R.string.edit_key_action_add_identity); + + LayoutInflater inflater = activity.getLayoutInflater(); + View view = inflater.inflate(R.layout.add_user_id_dialog, null); + alert.setView(view); + + mName = (AutoCompleteTextView) view.findViewById(R.id.add_user_id_name); + mEmail = (AutoCompleteTextView) view.findViewById(R.id.add_user_id_address); + mComment = (EditText) view.findViewById(R.id.add_user_id_comment); + + mName.setText(predefinedName); + + mEmail.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + } + + @Override + public void afterTextChanged(Editable editable) { + String email = editable.toString(); + if (email.length() > 0) { + Matcher emailMatcher = Patterns.EMAIL_ADDRESS.matcher(email); + if (emailMatcher.matches()) { + mEmail.setCompoundDrawablesWithIntrinsicBounds(0, 0, + R.drawable.uid_mail_ok, 0); + } else { + mEmail.setCompoundDrawablesWithIntrinsicBounds(0, 0, + R.drawable.uid_mail_bad, 0); + } + } else { + // remove drawable if email is empty + mEmail.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); + } + } + }); + mEmail.setThreshold(1); // Start working from first character + mEmail.setAdapter(autoCompleteEmailAdapter); + + alert.setPositiveButton(android.R.string.ok, new OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + dismiss(); + + // return new user id back to activity + Bundle data = new Bundle(); + String userId = KeyRing.createUserId(mName.getText().toString(), + mEmail.getText().toString(), mComment.getText().toString()); + data.putString(MESSAGE_DATA_USER_ID, userId); + sendMessageToHandler(MESSAGE_OKAY, data); + } + }); + + alert.setNegativeButton(android.R.string.cancel, new OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + dialog.cancel(); + } + }); + + // Hack to open keyboard. + // This is the only method that I found to work across all Android versions + // http://turbomanage.wordpress.com/2012/05/02/show-soft-keyboard-automatically-when-edittext-receives-focus/ + // Notes: * onCreateView can't be used because we want to add buttons to the dialog + // * opening in onActivityCreated does not work on Android 4.4 + mEmail.setOnFocusChangeListener(new View.OnFocusChangeListener() { + @Override + public void onFocusChange(View v, boolean hasFocus) { + mEmail.post(new Runnable() { + @Override + public void run() { + InputMethodManager imm = (InputMethodManager) getActivity() + .getSystemService(Context.INPUT_METHOD_SERVICE); + imm.showSoftInput(mEmail, InputMethodManager.SHOW_IMPLICIT); + } + }); + } + }); + mEmail.requestFocus(); + + mComment.setImeActionLabel(getString(android.R.string.ok), EditorInfo.IME_ACTION_DONE); + mComment.setOnEditorActionListener(this); + + return alert.show(); + } + + @Override + public void onCancel(DialogInterface dialog) { + super.onCancel(dialog); + + dismiss(); + sendMessageToHandler(MESSAGE_CANCEL); + } + + @Override + public void onDismiss(DialogInterface dialog) { + super.onDismiss(dialog); + Log.d(Constants.TAG, "onDismiss"); + + // hide keyboard on dismiss + hideKeyboard(); + } + + private void hideKeyboard() { + InputMethodManager inputManager = (InputMethodManager) getActivity() + .getSystemService(Context.INPUT_METHOD_SERVICE); + + //check if no view has focus: + View v = getActivity().getCurrentFocus(); + if (v == null) + return; + + inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0); + } + + /** + * Associate the "done" button on the soft keyboard with the okay button in the view + */ + @Override + public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { + if (EditorInfo.IME_ACTION_DONE == actionId) { + AlertDialog dialog = ((AlertDialog) getDialog()); + Button bt = dialog.getButton(AlertDialog.BUTTON_POSITIVE); + + bt.performClick(); + return true; + } + return false; + } + + /** + * Send message back to handler which is initialized in a activity + * + * @param what Message integer you want to send + */ + private void sendMessageToHandler(Integer what) { + Message msg = Message.obtain(); + msg.what = what; + + try { + mMessenger.send(msg); + } catch (RemoteException e) { + Log.w(Constants.TAG, "Exception sending message, Is handler present?", e); + } catch (NullPointerException e) { + Log.w(Constants.TAG, "Messenger is null!", e); + } + } + + /** + * Send message back to handler which is initialized in a activity + * + * @param what Message integer you want to send + */ + private void sendMessageToHandler(Integer what, Bundle data) { + Message msg = Message.obtain(); + msg.what = what; + if (data != null) { + msg.setData(data); + } + + try { + mMessenger.send(msg); + } catch (RemoteException e) { + Log.w(Constants.TAG, "Exception sending message, Is handler present?", e); + } catch (NullPointerException e) { + Log.w(Constants.TAG, "Messenger is null!", e); + } + } + +} diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/UserIdEditor.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/UserIdEditor.java index 9b561f819..f50d2adc6 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/UserIdEditor.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/widget/UserIdEditor.java @@ -110,7 +110,7 @@ public class UserIdEditor extends LinearLayout implements Editor, OnClickListene mName = (EditText) findViewById(R.id.name); mName.addTextChangedListener(mTextWatcher); mEmail = (AutoCompleteTextView) findViewById(R.id.email); - mComment = (EditText) findViewById(R.id.comment); + mComment = (EditText) findViewById(R.id.user_id_item_comment); mComment.addTextChangedListener(mTextWatcher); diff --git a/OpenKeychain/src/main/res/layout/add_user_id_dialog.xml b/OpenKeychain/src/main/res/layout/add_user_id_dialog.xml new file mode 100644 index 000000000..2575db4ba --- /dev/null +++ b/OpenKeychain/src/main/res/layout/add_user_id_dialog.xml @@ -0,0 +1,41 @@ + + + + + + + + + + diff --git a/OpenKeychain/src/main/res/layout/create_key_input_fragment.xml b/OpenKeychain/src/main/res/layout/create_key_input_fragment.xml index 588cbb050..6e629573a 100644 --- a/OpenKeychain/src/main/res/layout/create_key_input_fragment.xml +++ b/OpenKeychain/src/main/res/layout/create_key_input_fragment.xml @@ -64,6 +64,7 @@ android:layout_height="wrap_content" android:layout_marginTop="8dp" android:layout_marginBottom="8dp" + android:imeOptions="actionNext" android:inputType="textPassword" android:hint="@string/label_passphrase" android:ems="10" diff --git a/OpenKeychain/src/main/res/layout/edit_key_user_id_added_item.xml b/OpenKeychain/src/main/res/layout/edit_key_user_id_added_item.xml deleted file mode 100644 index ef0e2626e..000000000 --- a/OpenKeychain/src/main/res/layout/edit_key_user_id_added_item.xml +++ /dev/null @@ -1,58 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/OpenKeychain/src/main/res/layout/edit_key_user_id_item.xml b/OpenKeychain/src/main/res/layout/edit_key_user_id_item.xml index 3454d3668..877ea77db 100644 --- a/OpenKeychain/src/main/res/layout/edit_key_user_id_item.xml +++ b/OpenKeychain/src/main/res/layout/edit_key_user_id_item.xml @@ -67,7 +67,7 @@ android:text="@string/label_comment" /> @@ -39,21 +40,21 @@ android:layout_weight="1"> + + diff --git a/OpenKeychain/src/main/res/values/strings.xml b/OpenKeychain/src/main/res/values/strings.xml index 2842eb8fc..98f6da186 100644 --- a/OpenKeychain/src/main/res/values/strings.xml +++ b/OpenKeychain/src/main/res/values/strings.xml @@ -311,9 +311,9 @@ modifying keyring… unlocking keyring… - adding user ids… - revoking user ids… - changing primary user id… + adding user IDs… + revoking user IDs… + changing primary user ID… modifying subkeys… revoking subkeys… adding subkeys… diff --git a/extern/openkeychain-api-lib b/extern/openkeychain-api-lib index 02cb8ad24..48941ca6e 160000 --- a/extern/openkeychain-api-lib +++ b/extern/openkeychain-api-lib @@ -1 +1 @@ -Subproject commit 02cb8ad24b780f3b97073f2526f83057c99d4243 +Subproject commit 48941ca6ec58c4583cdcf9d647ad5174925e2f28 diff --git a/extern/openpgp-api-lib b/extern/openpgp-api-lib index e515a4902..869ab96e6 160000 --- a/extern/openpgp-api-lib +++ b/extern/openpgp-api-lib @@ -1 +1 @@ -Subproject commit e515a49027fc5de36b8977cf8b096afc9838a9be +Subproject commit 869ab96e6dcd4821fd5360248429e49dae6fbaca diff --git a/extern/spongycastle b/extern/spongycastle index 9e4fb80c4..a68ebd1ff 160000 --- a/extern/spongycastle +++ b/extern/spongycastle @@ -1 +1 @@ -Subproject commit 9e4fb80c4f8efb8a0f8fd0c1cc1e74a421d1eb7e +Subproject commit a68ebd1ffc5af880903b2905c17e4f6ac0f13988 -- cgit v1.2.3 From aa5856bcb8f04116b3a08bbb8450ee1183553e01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Fri, 1 Aug 2014 17:53:57 +0200 Subject: Again update submodules --- extern/openkeychain-api-lib | 2 +- extern/openpgp-api-lib | 2 +- extern/spongycastle | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/extern/openkeychain-api-lib b/extern/openkeychain-api-lib index 48941ca6e..02cb8ad24 160000 --- a/extern/openkeychain-api-lib +++ b/extern/openkeychain-api-lib @@ -1 +1 @@ -Subproject commit 48941ca6ec58c4583cdcf9d647ad5174925e2f28 +Subproject commit 02cb8ad24b780f3b97073f2526f83057c99d4243 diff --git a/extern/openpgp-api-lib b/extern/openpgp-api-lib index 869ab96e6..e515a4902 160000 --- a/extern/openpgp-api-lib +++ b/extern/openpgp-api-lib @@ -1 +1 @@ -Subproject commit 869ab96e6dcd4821fd5360248429e49dae6fbaca +Subproject commit e515a49027fc5de36b8977cf8b096afc9838a9be diff --git a/extern/spongycastle b/extern/spongycastle index a68ebd1ff..9e4fb80c4 160000 --- a/extern/spongycastle +++ b/extern/spongycastle @@ -1 +1 @@ -Subproject commit a68ebd1ffc5af880903b2905c17e4f6ac0f13988 +Subproject commit 9e4fb80c4f8efb8a0f8fd0c1cc1e74a421d1eb7e -- cgit v1.2.3