1
0
Fork 0
mirror of https://github.com/vanitasvitae/Smack.git synced 2024-11-27 14:32:06 +01:00

Refactor API

This commit is contained in:
Paul Schaub 2018-06-20 11:02:30 +02:00
parent e23cf88082
commit ffbfae9856
14 changed files with 521 additions and 138 deletions

View file

@ -158,6 +158,9 @@ public final class FileUtils {
}
public static void deleteDirectory(File root) {
if (!root.exists()) {
return;
}
File[] currList;
Stack<File> stack = new Stack<>();
stack.push(root);
@ -176,4 +179,25 @@ public final class FileUtils {
}
}
}
/**
* Returns a {@link File} pointing to a temporary directory. On unix like systems this might be {@code /tmp}
* for example.
* If {@code suffix} is not null, the returned file points to {@code <temp>/suffix}.
*
* @param suffix optional path suffix
* @return temp directory
*/
public static File getTempDir(String suffix) {
String temp = System.getProperty("java.io.tmpdir");
if (temp == null) {
temp = "tmp";
}
if (suffix == null) {
return new File(temp);
} else {
return new File(temp, suffix);
}
}
}

View file

@ -126,7 +126,7 @@ public class PainlessOpenPgpProvider implements OpenPgpProvider {
try {
toEncrypted = PGPainless.createEncryptor()
.onOutputStream(encryptedBytes)
.toRecipients(new ArrayList<>(encryptionKeys.values()).toArray(new PGPPublicKeyRing[]{}))
.toRecipients(new ArrayList<>(encryptionKeys.values()).toArray(new PGPPublicKeyRing[] {}))
.usingSecureAlgorithms()
.signWith(secretKeyRingProtector, signingKey)
.noArmor();
@ -201,12 +201,12 @@ public class PainlessOpenPgpProvider implements OpenPgpProvider {
@Override
public DecryptedBytesAndMetadata decrypt(byte[] bytes, BareJid sender, final SmackMissingOpenPgpPublicKeyCallback missingPublicKeyCallback)
throws MissingOpenPgpKeyPairException, SmackOpenPgpException, IOException {
throws MissingOpenPgpKeyPairException, SmackOpenPgpException {
PGPSecretKeyRingCollection secretKeyRings;
try {
secretKeyRings = getStore().getSecretKeyRings(owner);
} catch (PGPException e) {
} catch (PGPException | IOException e) {
LOGGER.log(Level.INFO, "Could not get secret keys of user " + owner);
throw new MissingOpenPgpKeyPairException(owner, getStore().getPrimaryOpenPgpKeyPairFingerprint());
}
@ -222,7 +222,7 @@ public class PainlessOpenPgpProvider implements OpenPgpProvider {
PGPPublicKeyRingCollection publicKeyRings;
try {
publicKeyRings = getStore().getPublicKeyRings(sender);
} catch (PGPException e) {
} catch (PGPException | IOException e) {
LOGGER.log(Level.INFO, "Could not get public keys of sender " + sender.toString(), e);
if (missingPublicKeyCallback != null) {
// TODO: Handle missing key
@ -239,7 +239,11 @@ public class PainlessOpenPgpProvider implements OpenPgpProvider {
}
}
return decryptImpl(bytes, secretKeyRings, protector, trustedKeys);
try {
return decryptImpl(bytes, secretKeyRings, protector, trustedKeys);
} catch (IOException e) {
throw new SmackOpenPgpException(e);
}
}
DecryptedBytesAndMetadata decryptImpl(byte[] bytes, PGPSecretKeyRingCollection decryptionKeys,

View file

@ -0,0 +1,91 @@
/**
*
* Copyright 2018 Paul Schaub.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.ox.bouncycastle;
import java.io.File;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Collections;
import java.util.Date;
import org.jivesoftware.smack.util.stringencoder.Base64;
import org.jivesoftware.smackx.ox.element.PubkeyElement;
import org.jivesoftware.smackx.ox.exception.MissingOpenPgpPublicKeyException;
import org.jivesoftware.smackx.ox.exception.MissingUserIdOnKeyException;
import org.jivesoftware.smackx.ox.exception.SmackOpenPgpException;
import org.jivesoftware.smackx.ox.util.KeyBytesAndFingerprint;
import de.vanitasvitae.crypto.pgpainless.key.UnprotectedKeysProtector;
import org.bouncycastle.openpgp.PGPException;
import org.junit.Test;
import org.jxmpp.jid.BareJid;
import org.jxmpp.jid.JidTestUtil;
public class DryOxEncryptionTest extends OxTestSuite {
private static File getTempDir(String suffix) {
String temp = System.getProperty("java.io.tmpdir");
if (temp == null) {
temp = "tmp";
}
if (suffix == null) {
return new File(temp);
} else {
return new File(temp, suffix);
}
}
@Test
public void dryEncryptionTest()
throws PGPException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException,
IOException, SmackOpenPgpException, MissingUserIdOnKeyException, MissingOpenPgpPublicKeyException {
BareJid alice = JidTestUtil.BARE_JID_1;
BareJid bob = JidTestUtil.BARE_JID_2;
File alicePath = getTempDir("ox-alice");
File bobPath = getTempDir("ox-bob");
FileBasedPainlessOpenPgpStore aliceStore = new FileBasedPainlessOpenPgpStore(alicePath, new UnprotectedKeysProtector());
FileBasedPainlessOpenPgpStore bobStore = new FileBasedPainlessOpenPgpStore(bobPath, new UnprotectedKeysProtector());
PainlessOpenPgpProvider aliceProvider = new PainlessOpenPgpProvider(alice, aliceStore);
PainlessOpenPgpProvider bobProvider = new PainlessOpenPgpProvider(bob, bobStore);
KeyBytesAndFingerprint aliceKey = aliceProvider.generateOpenPgpKeyPair(alice);
KeyBytesAndFingerprint bobKey = bobProvider.generateOpenPgpKeyPair(bob);
aliceProvider.importSecretKey(alice, aliceKey.getBytes());
bobProvider.importSecretKey(bob, bobKey.getBytes());
PubkeyElement alicePub = new PubkeyElement(new PubkeyElement.PubkeyDataElement(
Base64.encode(aliceStore.getPublicKeyRingBytes(alice, aliceKey.getFingerprint()))),
new Date());
PubkeyElement bobPub = new PubkeyElement(new PubkeyElement.PubkeyDataElement(
Base64.encode(bobStore.getPublicKeyRingBytes(bob, bobKey.getFingerprint()))),
new Date());
aliceProvider.importPublicKey(bob, Base64.decode(bobPub.getDataElement().getB64Data()));
bobProvider.importPublicKey(alice, Base64.decode(alicePub.getDataElement().getB64Data()));
aliceStore.setAnnouncedKeysFingerprints(bob, Collections.singletonMap(bobKey.getFingerprint(), new Date()));
bobStore.setAnnouncedKeysFingerprints(alice, Collections.singletonMap(aliceKey.getFingerprint(), new Date()));
}
}

View file

@ -1,5 +1,22 @@
/**
*
* Copyright 2018 Paul Schaub.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.ox.bouncycastle;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertTrue;
import java.io.File;
@ -7,30 +24,35 @@ import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.util.Arrays;
import java.util.Collections;
import org.jivesoftware.smack.test.util.SmackTestSuite;
import org.jivesoftware.smack.util.FileUtils;
import de.vanitasvitae.crypto.pgpainless.PGPainless;
import de.vanitasvitae.crypto.pgpainless.key.UnprotectedKeysProtector;
import de.vanitasvitae.crypto.pgpainless.key.generation.type.length.RsaLength;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import de.vanitasvitae.crypto.pgpainless.util.BCUtil;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPPublicKeyRingCollection;
import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.bouncycastle.openpgp.PGPSecretKeyRingCollection;
import org.junit.Before;
import org.junit.Test;
import org.jxmpp.jid.BareJid;
import org.jxmpp.jid.impl.JidCreate;
import org.jxmpp.stringprep.XmppStringprepException;
public class FileBasedPainlessOpenPgpStoreTest extends SmackTestSuite {
public class FileBasedPainlessOpenPgpStoreTest extends OxTestSuite {
private static final File basePath;
private static final BareJid alice;
private static final BareJid bob;
private FileBasedPainlessOpenPgpStore store;
static {
String userHome = System.getProperty("user.home");
if (userHome != null) {
@ -46,22 +68,45 @@ public class FileBasedPainlessOpenPgpStoreTest extends SmackTestSuite {
} catch (XmppStringprepException e) {
throw new AssertionError(e);
}
}
Security.addProvider(new BouncyCastleProvider());
@Before
public void deleteStore() {
FileUtils.deleteDirectory(basePath);
this.store = new FileBasedPainlessOpenPgpStore(basePath, new UnprotectedKeysProtector());
}
@Test
public void storeSecretKeyRingsTest()
throws PGPException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException,
IOException {
FileBasedPainlessOpenPgpStore store = new FileBasedPainlessOpenPgpStore(basePath, new UnprotectedKeysProtector());
PGPSecretKeyRing secretKey = PGPainless.generateKeyRing().simpleRsaKeyRing("xmpp:" + alice.toString(), RsaLength._3072);
PGPSecretKeyRingCollection saving = new PGPSecretKeyRingCollection(Collections.singleton(secretKey));
store.storeSecretKeyRing(alice, saving);
PGPSecretKeyRingCollection restored = store.getSecretKeyRings(alice);
FileBasedPainlessOpenPgpStore store2 = new FileBasedPainlessOpenPgpStore(basePath, new UnprotectedKeysProtector());
PGPSecretKeyRingCollection restored = store2.getSecretKeyRings(alice);
assertTrue(Arrays.equals(saving.getEncoded(), restored.getEncoded()));
}
@Test
public void storePublicKeyRingTest()
throws PGPException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException,
IOException {
PGPSecretKeyRing secretKeys = PGPainless.generateKeyRing().simpleRsaKeyRing("xmpp:" + alice.toString(), RsaLength._3072);
PGPPublicKeyRing publicKeys = BCUtil.publicKeyRingFromSecretKeyRing(secretKeys);
for (PGPSecretKey k : secretKeys) {
assertEquals(publicKeys.getPublicKey(k.getKeyID()), k.getPublicKey());
}
PGPPublicKeyRingCollection saving = new PGPPublicKeyRingCollection(Collections.singleton(publicKeys));
store.storePublicKeyRing(alice, saving);
FileBasedPainlessOpenPgpStore store2 = new FileBasedPainlessOpenPgpStore(basePath, new UnprotectedKeysProtector());
PGPPublicKeyRingCollection restored = store2.getPublicKeyRings(alice);
assertTrue(Arrays.equals(saving.getEncoded(), restored.getEncoded()));
}
}

View file

@ -0,0 +1,33 @@
/**
*
* Copyright 2018 Paul Schaub.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.ox.bouncycastle;
import java.security.Security;
import org.jivesoftware.smack.test.util.SmackTestSuite;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.BeforeClass;
public abstract class OxTestSuite extends SmackTestSuite {
@BeforeClass
public static void registerProvider() {
Security.removeProvider("BC");
Security.addProvider(new BouncyCastleProvider());
}
}

View file

@ -16,39 +16,23 @@
*/
package org.jivesoftware.smackx.ox;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jivesoftware.smack.Manager;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.chat2.Chat;
import org.jivesoftware.smack.chat2.ChatManager;
import org.jivesoftware.smack.chat2.IncomingChatMessageListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.util.stringencoder.Base64;
import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
import org.jivesoftware.smackx.ox.chat.OpenPgpEncryptedChat;
import org.jivesoftware.smackx.ox.chat.OpenPgpFingerprints;
import org.jivesoftware.smackx.ox.chat.OpenPgpMessage;
import org.jivesoftware.smackx.ox.element.OpenPgpContentElement;
import org.jivesoftware.smackx.ox.element.OpenPgpElement;
import org.jivesoftware.smackx.ox.chat.OpenPgpContact;
import org.jivesoftware.smackx.ox.element.SigncryptElement;
import org.jivesoftware.smackx.ox.exception.MissingOpenPgpKeyPairException;
import org.jivesoftware.smackx.ox.exception.SmackOpenPgpException;
import org.jivesoftware.smackx.ox.listener.OpenPgpEncryptedMessageListener;
import org.jivesoftware.smackx.ox.util.DecryptedBytesAndMetadata;
import org.jivesoftware.smackx.ox.listener.OxMessageListener;
import org.jivesoftware.smackx.ox.listener.internal.SigncryptElementReceivedListener;
import org.jxmpp.jid.BareJid;
import org.jxmpp.jid.EntityBareJid;
import org.xmlpull.v1.XmlPullParserException;
/**
* Entry point of Smacks API for XEP-0374: OpenPGP for XMPP: Instant Messaging.
@ -56,24 +40,18 @@ import org.xmlpull.v1.XmlPullParserException;
* @see <a href="https://xmpp.org/extensions/xep-0374.html">
* XEP-0374: OpenPGP for XMPP: Instant Messaging</a>
*/
public final class OXInstantMessagingManager extends Manager {
public final class OXInstantMessagingManager extends Manager implements SigncryptElementReceivedListener {
public static final String NAMESPACE_0 = "urn:xmpp:openpgp:im:0";
private static final Logger LOGGER = Logger.getLogger(OXInstantMessagingManager.class.getName());
private static final Map<XMPPConnection, OXInstantMessagingManager> INSTANCES = new WeakHashMap<>();
private final OpenPgpManager openPgpManager;
private final ChatManager chatManager;
private final Set<OpenPgpEncryptedMessageListener> chatMessageListeners = new HashSet<>();
private final Map<BareJid, OpenPgpEncryptedChat> chats = new HashMap<>();
private final Set<OxMessageListener> oxMessageListeners = new HashSet<>();
private OXInstantMessagingManager(final XMPPConnection connection) {
super(connection);
this.openPgpManager = OpenPgpManager.getInstanceFor(connection);
this.chatManager = ChatManager.getInstanceFor(connection);
chatManager.addIncomingListener(incomingChatMessageListener);
OpenPgpManager.getInstanceFor(connection).addSigncryptReceivedListener(this);
announceSupportForOxInstantMessaging();
}
public static OXInstantMessagingManager getInstanceFor(XMPPConnection connection) {
@ -109,83 +87,33 @@ public final class OXInstantMessagingManager extends Manager {
}
/**
* Start an encrypted chat with {@code jid}.
* The chat is encrypted with OpenPGP for XMPP: Instant Messaging (XEP-0374).
* Determine, whether a contact announces support for XEP-0374: OpenPGP for XMPP: Instant Messaging.
*
* @see <a href="https://xmpp.org/extensions/xep-0374.html">XEP-0374: OpenPGP for XMPP: Instant Messaging</a>
* @param jid {@link BareJid} of the contact.
* @return {@link OpenPgpEncryptedChat} with the contact.
* @throws SmackOpenPgpException if something happens while gathering fingerprints.
* @throws InterruptedException
* @param contact {@link OpenPgpContact} in question.
* @return true if contact announces support, otherwise false.
* @throws XMPPException.XMPPErrorException
* @throws SmackException.NotConnectedException
* @throws InterruptedException
* @throws SmackException.NoResponseException
*/
public OpenPgpEncryptedChat chatWith(EntityBareJid jid)
throws SmackOpenPgpException, InterruptedException, XMPPException.XMPPErrorException,
SmackException.NotConnectedException, SmackException.NoResponseException {
public boolean contactSupportsOxInstantMessaging(OpenPgpContact contact)
throws XMPPException.XMPPErrorException, SmackException.NotConnectedException, InterruptedException,
SmackException.NoResponseException {
return contactSupportsOxInstantMessaging(contact.getJidOfChatPartner().asBareJid());
}
OpenPgpEncryptedChat encryptedChat = chats.get(jid);
public boolean addOxMessageListener(OxMessageListener listener) {
return oxMessageListeners.add(listener);
}
if (encryptedChat == null) {
OpenPgpFingerprints theirKeys = openPgpManager.determineContactsKeys(jid);
OpenPgpFingerprints ourKeys = openPgpManager.determineContactsKeys(connection().getUser().asBareJid());
Chat chat = chatManager.chatWith(jid);
encryptedChat = new OpenPgpEncryptedChat(openPgpManager.getOpenPgpProvider(), chat, ourKeys, theirKeys);
chats.put(jid, encryptedChat);
public boolean removeOxMessageListener(OxMessageListener listener) {
return oxMessageListeners.remove(listener);
}
@Override
public void signcryptElementReceived(OpenPgpContact contact, Message originalMessage, SigncryptElement signcryptElement) {
for (OxMessageListener listener : oxMessageListeners) {
listener.newIncomingOxMessage(contact, originalMessage, signcryptElement);
}
return encryptedChat;
}
public boolean addOpenPgpEncryptedMessageListener(OpenPgpEncryptedMessageListener listener) {
return chatMessageListeners.add(listener);
}
public boolean removeOpenPgpEncryptedMessageListener(OpenPgpEncryptedMessageListener listener) {
return chatMessageListeners.remove(listener);
}
private final IncomingChatMessageListener incomingChatMessageListener =
new IncomingChatMessageListener() {
@Override
public void newIncomingMessage(EntityBareJid from, Message message, Chat chat) {
OpenPgpElement element = message.getExtension(OpenPgpElement.ELEMENT, OpenPgpElement.NAMESPACE);
if (element == null) {
return;
}
OpenPgpProvider provider = openPgpManager.getOpenPgpProvider();
byte[] decoded = Base64.decode(element.getEncryptedBase64MessageContent());
try {
OpenPgpEncryptedChat encryptedChat = chatWith(from);
DecryptedBytesAndMetadata decryptedBytes = provider.decrypt(decoded, from.asBareJid(), null);
OpenPgpMessage openPgpMessage = new OpenPgpMessage(decryptedBytes.getBytes(),
new OpenPgpMessage.Metadata(decryptedBytes.getDecryptionKey(),
decryptedBytes.getVerifiedSignatures()));
OpenPgpContentElement contentElement = openPgpMessage.getOpenPgpContentElement();
if (openPgpMessage.getState() != OpenPgpMessage.State.signcrypt) {
LOGGER.log(Level.WARNING, "Decrypted content is not a signcrypt element. Ignore it.");
return;
}
SigncryptElement signcryptElement = (SigncryptElement) contentElement;
for (OpenPgpEncryptedMessageListener l : chatMessageListeners) {
l.newIncomingOxMessage(from, message, signcryptElement, encryptedChat);
}
} catch (SmackOpenPgpException e) {
LOGGER.log(Level.WARNING, "Could not start chat with " + from, e);
} catch (InterruptedException | XMPPException.XMPPErrorException | SmackException.NotConnectedException | SmackException.NoResponseException e) {
LOGGER.log(Level.WARNING, "Something went wrong.", e);
} catch (MissingOpenPgpKeyPairException e) {
LOGGER.log(Level.WARNING, "Could not decrypt message " + message.getStanzaId() + ": Missing secret key", e);
} catch (XmlPullParserException | IOException e) {
LOGGER.log(Level.WARNING, "Could not parse decrypted content element", e);
}
}
};
}

View file

@ -29,6 +29,7 @@ import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
@ -39,6 +40,9 @@ import org.jivesoftware.smack.Manager;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.chat2.Chat;
import org.jivesoftware.smack.chat2.ChatManager;
import org.jivesoftware.smack.chat2.IncomingChatMessageListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.util.Async;
import org.jivesoftware.smack.util.stringencoder.Base64;
@ -47,15 +51,24 @@ import org.jivesoftware.smackx.ox.callback.AskForBackupCodeCallback;
import org.jivesoftware.smackx.ox.callback.DisplayBackupCodeCallback;
import org.jivesoftware.smackx.ox.callback.SecretKeyBackupSelectionCallback;
import org.jivesoftware.smackx.ox.callback.SecretKeyRestoreSelectionCallback;
import org.jivesoftware.smackx.ox.chat.OpenPgpContact;
import org.jivesoftware.smackx.ox.chat.OpenPgpFingerprints;
import org.jivesoftware.smackx.ox.element.CryptElement;
import org.jivesoftware.smackx.ox.element.OpenPgpContentElement;
import org.jivesoftware.smackx.ox.element.OpenPgpElement;
import org.jivesoftware.smackx.ox.element.PubkeyElement;
import org.jivesoftware.smackx.ox.element.PublicKeysListElement;
import org.jivesoftware.smackx.ox.element.SecretkeyElement;
import org.jivesoftware.smackx.ox.element.SignElement;
import org.jivesoftware.smackx.ox.element.SigncryptElement;
import org.jivesoftware.smackx.ox.exception.InvalidBackupCodeException;
import org.jivesoftware.smackx.ox.exception.MissingOpenPgpKeyPairException;
import org.jivesoftware.smackx.ox.exception.MissingOpenPgpPublicKeyException;
import org.jivesoftware.smackx.ox.exception.MissingUserIdOnKeyException;
import org.jivesoftware.smackx.ox.exception.SmackOpenPgpException;
import org.jivesoftware.smackx.ox.listener.internal.CryptElementReceivedListener;
import org.jivesoftware.smackx.ox.listener.internal.SignElementReceivedListener;
import org.jivesoftware.smackx.ox.listener.internal.SigncryptElementReceivedListener;
import org.jivesoftware.smackx.ox.util.KeyBytesAndFingerprint;
import org.jivesoftware.smackx.ox.util.PubSubDelegate;
import org.jivesoftware.smackx.pep.PEPListener;
@ -69,6 +82,7 @@ import org.jivesoftware.smackx.pubsub.PubSubManager;
import org.jxmpp.jid.BareJid;
import org.jxmpp.jid.EntityBareJid;
import org.xmlpull.v1.XmlPullParserException;
public final class OpenPgpManager extends Manager {
@ -84,6 +98,12 @@ public final class OpenPgpManager extends Manager {
*/
private OpenPgpProvider provider;
private final Map<BareJid, OpenPgpContact> openPgpCapableContacts = new HashMap<>();
private final Set<SigncryptElementReceivedListener> signcryptElementReceivedListeners = new HashSet<>();
private final Set<SignElementReceivedListener> signElementReceivedListeners = new HashSet<>();
private final Set<CryptElementReceivedListener> cryptElementReceivedListeners = new HashSet<>();
/**
* Private constructor to avoid instantiation without putting the object into {@code INSTANCES}.
*
@ -91,6 +111,7 @@ public final class OpenPgpManager extends Manager {
*/
private OpenPgpManager(XMPPConnection connection) {
super(connection);
ChatManager.getInstanceFor(connection).addIncomingListener(incomingOpenPgpMessageListener);
}
/**
@ -154,16 +175,7 @@ public final class OpenPgpManager extends Manager {
OpenPgpV4Fingerprint primaryFingerprint = getOurFingerprint();
if (primaryFingerprint == null) {
KeyBytesAndFingerprint bytesAndFingerprint = provider.generateOpenPgpKeyPair(ourJid);
primaryFingerprint = bytesAndFingerprint.getFingerprint();
// This should never throw, since we set our jid literally one line above this comment.
try {
provider.importSecretKey(ourJid, bytesAndFingerprint.getBytes());
} catch (MissingUserIdOnKeyException e) {
throw new AssertionError(e);
}
primaryFingerprint = generateAndImportKeyPair(ourJid);
}
// Create <pubkey/> element
@ -183,6 +195,22 @@ public final class OpenPgpManager extends Manager {
.addFeature(PEP_NODE_PUBLIC_KEYS_NOTIFY);
}
public OpenPgpV4Fingerprint generateAndImportKeyPair(BareJid ourJid)
throws NoSuchAlgorithmException, IOException, InvalidAlgorithmParameterException, NoSuchProviderException,
SmackOpenPgpException {
KeyBytesAndFingerprint bytesAndFingerprint = provider.generateOpenPgpKeyPair(ourJid);
OpenPgpV4Fingerprint fingerprint = bytesAndFingerprint.getFingerprint();
// This should never throw, since we set our jid literally one line above this comment.
try {
provider.importSecretKey(ourJid, bytesAndFingerprint.getBytes());
} catch (MissingUserIdOnKeyException e) {
throw new AssertionError(e);
}
return fingerprint;
}
/**
* Return the upper-case hex encoded OpenPGP v4 fingerprint of our key pair.
*
@ -193,6 +221,38 @@ public final class OpenPgpManager extends Manager {
return provider.getStore().getPrimaryOpenPgpKeyPairFingerprint();
}
/**
* Return an OpenPGP capable contact.
* This object can be used as an entry point to OpenPGP related API.
*
* @param jid {@link BareJid} of the contact.
* @return {@link OpenPgpContact}.
* @throws SmackOpenPgpException if something happens while gathering fingerprints.
* @throws InterruptedException
* @throws XMPPException.XMPPErrorException
* @throws SmackException.NotConnectedException
* @throws SmackException.NoResponseException
*/
public OpenPgpContact getOpenPgpContact(EntityBareJid jid)
throws SmackOpenPgpException, InterruptedException, XMPPException.XMPPErrorException,
SmackException.NotConnectedException, SmackException.NoResponseException,
SmackException.NotLoggedInException {
throwIfNotAuthenticated();
OpenPgpContact openPgpContact = openPgpCapableContacts.get(jid);
if (openPgpContact == null) {
OpenPgpFingerprints theirKeys = determineContactsKeys(jid);
OpenPgpFingerprints ourKeys = determineContactsKeys(connection().getUser().asBareJid());
Chat chat = ChatManager.getInstanceFor(connection()).chatWith(jid);
openPgpContact = new OpenPgpContact(getOpenPgpProvider(), chat, ourKeys, theirKeys);
openPgpCapableContacts.put(jid, openPgpContact);
}
return openPgpContact;
}
/**
* Determine, if we can sync secret keys using private PEP nodes as described in the XEP.
* Requirements on the server side are support for PEP and support for the whitelist access model of PubSub.
@ -304,7 +364,7 @@ public final class OpenPgpManager extends Manager {
* @throws SmackException.NotConnectedException
* @throws SmackException.NoResponseException
*/
public OpenPgpFingerprints determineContactsKeys(BareJid jid)
private OpenPgpFingerprints determineContactsKeys(BareJid jid)
throws SmackOpenPgpException, InterruptedException, XMPPException.XMPPErrorException,
SmackException.NotConnectedException, SmackException.NoResponseException {
Set<OpenPgpV4Fingerprint> announced = provider.getStore().getAnnouncedKeysFingerprints(jid).keySet();
@ -381,6 +441,60 @@ public final class OpenPgpManager extends Manager {
}
};
private final IncomingChatMessageListener incomingOpenPgpMessageListener =
new IncomingChatMessageListener() {
@Override
public void newIncomingMessage(EntityBareJid from, Message message, Chat chat) {
OpenPgpElement element = message.getExtension(OpenPgpElement.ELEMENT, OpenPgpElement.NAMESPACE);
if (element == null) {
// Message does not contain an OpenPgpElement -> discard
return;
}
OpenPgpContact contact;
try {
contact = getOpenPgpContact(from);
} catch (SmackOpenPgpException | InterruptedException | XMPPException.XMPPErrorException |
SmackException.NotLoggedInException | SmackException.NotConnectedException |
SmackException.NoResponseException e) {
LOGGER.log(Level.WARNING, "Could not begin encrypted chat with " + from, e);
return;
}
OpenPgpContentElement contentElement = null;
try {
contentElement = contact.receive(element);
} catch (SmackOpenPgpException e) {
LOGGER.log(Level.WARNING, "Could not decrypt incoming OpenPGP encrypted message", e);
} catch (XmlPullParserException | IOException e) {
LOGGER.log(Level.WARNING, "Invalid XML content of incoming OpenPGP encrypted message", e);
} catch (MissingOpenPgpKeyPairException e) {
LOGGER.log(Level.WARNING, "Could not decrypt incoming OpenPGP encrypted message due to missing secret key", e);
}
if (contentElement instanceof SigncryptElement) {
for (SigncryptElementReceivedListener l : signcryptElementReceivedListeners) {
l.signcryptElementReceived(contact, message, (SigncryptElement) contentElement);
}
return;
}
if (contentElement instanceof SignElement) {
for (SignElementReceivedListener l : signElementReceivedListeners) {
l.signElementReceived(contact, message, (SignElement) contentElement);
}
return;
}
if (contentElement instanceof CryptElement) {
for (CryptElementReceivedListener l : cryptElementReceivedListeners) {
l.cryptElementReceived(contact, message, (CryptElement) contentElement);
}
return;
}
}
};
/*
Private stuff.
*/
@ -453,6 +567,30 @@ public final class OpenPgpManager extends Manager {
return new SecretkeyElement(Base64.encode(encrypted));
}
void addSigncryptReceivedListener(SigncryptElementReceivedListener listener) {
signcryptElementReceivedListeners.add(listener);
}
void removeSigncryptElementReceivedListener(SigncryptElementReceivedListener listener) {
signcryptElementReceivedListeners.remove(listener);
}
void addSignElementReceivedListener(SignElementReceivedListener listener) {
signElementReceivedListeners.add(listener);
}
void removeSignElementReceivedListener(SignElementReceivedListener listener) {
signElementReceivedListeners.remove(listener);
}
void addCryptElementReceivedListener(CryptElementReceivedListener listener) {
cryptElementReceivedListeners.add(listener);
}
void removeCryptElementReceivedListener(CryptElementReceivedListener listener) {
cryptElementReceivedListeners.remove(listener);
}
/**
* Throw an {@link IllegalStateException} if no {@link OpenPgpProvider} is set.
* The OpenPgpProvider is used to process information related to RFC-4880.

View file

@ -117,7 +117,7 @@ public interface OpenPgpProvider {
* the message.
*/
DecryptedBytesAndMetadata decrypt(byte[] bytes, BareJid sender, SmackMissingOpenPgpPublicKeyCallback missingPublicKeyCallback)
throws MissingOpenPgpKeyPairException, SmackOpenPgpException, IOException;
throws MissingOpenPgpKeyPairException, SmackOpenPgpException;
byte[] symmetricallyEncryptWithPassword(byte[] bytes, String password) throws SmackOpenPgpException, IOException;

View file

@ -31,16 +31,20 @@ import org.jivesoftware.smackx.eme.element.ExplicitMessageEncryptionElement;
import org.jivesoftware.smackx.hints.element.StoreHint;
import org.jivesoftware.smackx.ox.OpenPgpProvider;
import org.jivesoftware.smackx.ox.OpenPgpV4Fingerprint;
import org.jivesoftware.smackx.ox.element.OpenPgpContentElement;
import org.jivesoftware.smackx.ox.element.OpenPgpElement;
import org.jivesoftware.smackx.ox.element.SigncryptElement;
import org.jivesoftware.smackx.ox.exception.MissingOpenPgpKeyPairException;
import org.jivesoftware.smackx.ox.exception.MissingOpenPgpPublicKeyException;
import org.jivesoftware.smackx.ox.exception.SmackOpenPgpException;
import org.jivesoftware.smackx.ox.util.DecryptedBytesAndMetadata;
import org.jxmpp.jid.BareJid;
import org.jxmpp.jid.EntityBareJid;
import org.jxmpp.jid.Jid;
import org.xmlpull.v1.XmlPullParserException;
public class OpenPgpEncryptedChat {
public class OpenPgpContact {
private final Chat chat;
private final OpenPgpFingerprints contactsFingerprints;
@ -48,10 +52,10 @@ public class OpenPgpEncryptedChat {
private final OpenPgpProvider cryptoProvider;
private final OpenPgpV4Fingerprint singingKey;
public OpenPgpEncryptedChat(OpenPgpProvider cryptoProvider,
Chat chat,
OpenPgpFingerprints ourFingerprints,
OpenPgpFingerprints contactsFingerprints) {
public OpenPgpContact(OpenPgpProvider cryptoProvider,
Chat chat,
OpenPgpFingerprints ourFingerprints,
OpenPgpFingerprints contactsFingerprints) {
this.cryptoProvider = cryptoProvider;
this.chat = chat;
this.singingKey = cryptoProvider.getStore().getPrimaryOpenPgpKeyPairFingerprint();
@ -59,6 +63,14 @@ public class OpenPgpEncryptedChat {
this.contactsFingerprints = contactsFingerprints;
}
public EntityBareJid getJidOfChatPartner() {
return chat.getXmppAddressOfChatPartner();
}
public OpenPgpFingerprints getContactsFingerprints() {
return contactsFingerprints;
}
public void send(Message message, List<ExtensionElement> payload)
throws MissingOpenPgpKeyPairException, SmackException.NotConnectedException, InterruptedException,
SmackOpenPgpException, IOException {
@ -103,6 +115,19 @@ public class OpenPgpEncryptedChat {
send(message, payload);
}
public OpenPgpContentElement receive(OpenPgpElement element)
throws XmlPullParserException, MissingOpenPgpKeyPairException, SmackOpenPgpException, IOException {
byte[] decoded = Base64.decode(element.getEncryptedBase64MessageContent());
DecryptedBytesAndMetadata decryptedBytes = cryptoProvider.decrypt(decoded, getJidOfChatPartner(), null);
OpenPgpMessage openPgpMessage = new OpenPgpMessage(decryptedBytes.getBytes(),
new OpenPgpMessage.Metadata(decryptedBytes.getDecryptionKey(),
decryptedBytes.getVerifiedSignatures()));
return openPgpMessage.getOpenPgpContentElement();
}
private MultiMap<BareJid, OpenPgpV4Fingerprint> oursAndRecipientFingerprints() {
MultiMap<BareJid, OpenPgpV4Fingerprint> fingerprints = new MultiMap<>();
for (OpenPgpV4Fingerprint f : contactsFingerprints.getActiveKeys()) {

View file

@ -17,13 +17,11 @@
package org.jivesoftware.smackx.ox.listener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smackx.ox.chat.OpenPgpEncryptedChat;
import org.jivesoftware.smackx.ox.chat.OpenPgpContact;
import org.jivesoftware.smackx.ox.element.OpenPgpElement;
import org.jivesoftware.smackx.ox.element.SigncryptElement;
import org.jxmpp.jid.EntityBareJid;
public interface OpenPgpEncryptedMessageListener {
public interface OxMessageListener {
/**
* This method gets invoked, whenever an OX-IM encrypted message gets received.
@ -31,13 +29,11 @@ public interface OpenPgpEncryptedMessageListener {
* @see <a href="https://xmpp.org/extensions/xep-0374.html">
* XEP-0374: OpenPGP for XMPP: Instant Messaging (OX-IM)</a>
*
* @param from sender of the message.
* @param contact {@link OpenPgpContact} which sent the message.
* @param originalMessage the received message that is carrying the encrypted {@link OpenPgpElement}.
* @param decryptedPayload decrypted {@link SigncryptElement} which is carrying the payload.
* @param chat {@link OpenPgpEncryptedChat} which is the context of the message.
*/
void newIncomingOxMessage(EntityBareJid from,
void newIncomingOxMessage(OpenPgpContact contact,
Message originalMessage,
SigncryptElement decryptedPayload,
OpenPgpEncryptedChat chat);
SigncryptElement decryptedPayload);
}

View file

@ -0,0 +1,26 @@
/**
*
* Copyright 2018 Paul Schaub.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.ox.listener.internal;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smackx.ox.chat.OpenPgpContact;
import org.jivesoftware.smackx.ox.element.CryptElement;
public interface CryptElementReceivedListener {
void cryptElementReceived(OpenPgpContact contact, Message originalMessage, CryptElement cryptElement);
}

View file

@ -0,0 +1,27 @@
/**
*
* Copyright 2018 Paul Schaub.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.ox.listener.internal;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smackx.ox.chat.OpenPgpContact;
import org.jivesoftware.smackx.ox.element.SignElement;
public interface SignElementReceivedListener {
void signElementReceived(OpenPgpContact contact, Message originalMessage, SignElement signElement);
}

View file

@ -0,0 +1,26 @@
/**
*
* Copyright 2018 Paul Schaub.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.ox.listener.internal;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smackx.ox.chat.OpenPgpContact;
import org.jivesoftware.smackx.ox.element.SigncryptElement;
public interface SigncryptElementReceivedListener {
void signcryptElementReceived(OpenPgpContact contact, Message originalMessage, SigncryptElement signcryptElement);
}

View file

@ -0,0 +1,20 @@
/**
*
* Copyright 2018 Paul Schaub.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal OpenPgpContentElement listeners for XEP-0373: OpenPGP for XMPP.
*/
package org.jivesoftware.smackx.ox.listener.internal;