Search in sources :

Example 1 with NoRawSessionException

use of org.jivesoftware.smackx.omemo.exceptions.NoRawSessionException in project Smack by igniterealtime.

the class OmemoService method onOmemoMessageStanzaReceived.

@Override
public void onOmemoMessageStanzaReceived(Stanza stanza, OmemoManager.LoggedInOmemoManager managerGuard) throws IOException {
    OmemoManager manager = managerGuard.get();
    // Avoid the ratchet being manipulated and the bundle being published multiple times simultaneously
    synchronized (manager) {
        OmemoDevice userDevice = manager.getOwnDevice();
        OmemoElement element = (OmemoElement) stanza.getExtensionElement(OmemoElement.NAME_ENCRYPTED, OmemoElement_VAxolotl.NAMESPACE);
        if (element == null) {
            return;
        }
        OmemoMessage.Received decrypted;
        BareJid sender;
        try {
            MultiUserChat muc = getMuc(manager.getConnection(), stanza.getFrom());
            if (muc != null) {
                Occupant occupant = muc.getOccupant(stanza.getFrom().asEntityFullJidIfPossible());
                if (occupant == null) {
                    LOGGER.log(Level.WARNING, "Cannot decrypt OMEMO MUC message; MUC Occupant is null.");
                    return;
                }
                Jid occupantJid = occupant.getJid();
                if (occupantJid == null) {
                    LOGGER.log(Level.WARNING, "Cannot decrypt OMEMO MUC message; Senders Jid is null. " + stanza.getFrom());
                    return;
                }
                sender = occupantJid.asBareJid();
                // try is for this
                decrypted = decryptMessage(managerGuard, sender, element);
                manager.notifyOmemoMucMessageReceived(muc, stanza, decrypted);
            } else {
                sender = stanza.getFrom().asBareJid();
                // and this
                decrypted = decryptMessage(managerGuard, sender, element);
                manager.notifyOmemoMessageReceived(stanza, decrypted);
            }
            if (decrypted.isPreKeyMessage() && OmemoConfiguration.getCompleteSessionWithEmptyMessage()) {
                LOGGER.log(Level.FINE, "Received a preKeyMessage from " + decrypted.getSenderDevice() + ".\n" + "Complete the session by sending an empty response message.");
                try {
                    sendRatchetUpdate(managerGuard, decrypted.getSenderDevice());
                } catch (CannotEstablishOmemoSessionException e) {
                    throw new AssertionError("Since we successfully received a message, we MUST be able to " + "establish a session. " + e);
                } catch (NoSuchAlgorithmException | InterruptedException | SmackException.NotConnectedException | SmackException.NoResponseException e) {
                    LOGGER.log(Level.WARNING, "Cannot send a ratchet update message.", e);
                }
            }
        } catch (NoRawSessionException e) {
            OmemoDevice device = e.getDeviceWithoutSession();
            LOGGER.log(Level.WARNING, "No raw session found for contact " + device + ". ", e);
            if (OmemoConfiguration.getRepairBrokenSessionsWithPreKeyMessages()) {
                repairBrokenSessionWithPreKeyMessage(managerGuard, device);
            }
        } catch (CorruptedOmemoKeyException | CryptoFailedException e) {
            LOGGER.log(Level.WARNING, "Could not decrypt incoming message: ", e);
        }
        // Upload fresh bundle.
        if (getOmemoStoreBackend().loadOmemoPreKeys(userDevice).size() < OmemoConstants.PRE_KEY_COUNT_PER_BUNDLE) {
            LOGGER.log(Level.FINE, "We used up a preKey. Upload a fresh bundle.");
            try {
                getOmemoStoreBackend().replenishKeys(userDevice);
                OmemoBundleElement bundleElement = getOmemoStoreBackend().packOmemoBundle(userDevice);
                publishBundle(manager.getConnection(), userDevice, bundleElement);
            } catch (CorruptedOmemoKeyException | InterruptedException | SmackException.NoResponseException | SmackException.NotConnectedException | XMPPException.XMPPErrorException | NotALeafNodeException e) {
                LOGGER.log(Level.WARNING, "Could not republish replenished bundle.", e);
            }
        }
    }
}
Also used : CryptoFailedException(org.jivesoftware.smackx.omemo.exceptions.CryptoFailedException) MultiUserChat(org.jivesoftware.smackx.muc.MultiUserChat) OmemoDevice(org.jivesoftware.smackx.omemo.internal.OmemoDevice) EntityBareJid(org.jxmpp.jid.EntityBareJid) Jid(org.jxmpp.jid.Jid) BareJid(org.jxmpp.jid.BareJid) NotALeafNodeException(org.jivesoftware.smackx.pubsub.PubSubException.NotALeafNodeException) EntityBareJid(org.jxmpp.jid.EntityBareJid) BareJid(org.jxmpp.jid.BareJid) Occupant(org.jivesoftware.smackx.muc.Occupant) NoRawSessionException(org.jivesoftware.smackx.omemo.exceptions.NoRawSessionException) MessageOrOmemoMessage(org.jivesoftware.smackx.omemo.util.MessageOrOmemoMessage) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) OmemoBundleElement(org.jivesoftware.smackx.omemo.element.OmemoBundleElement) CannotEstablishOmemoSessionException(org.jivesoftware.smackx.omemo.exceptions.CannotEstablishOmemoSessionException) CorruptedOmemoKeyException(org.jivesoftware.smackx.omemo.exceptions.CorruptedOmemoKeyException) OmemoElement(org.jivesoftware.smackx.omemo.element.OmemoElement)

Example 2 with NoRawSessionException

use of org.jivesoftware.smackx.omemo.exceptions.NoRawSessionException in project Smack by igniterealtime.

the class OmemoService method decryptMamQueryResult.

/**
 * Decrypt a possible OMEMO encrypted messages in a {@link MamManager.MamQuery}.
 * The returned list contains wrappers that either hold an {@link OmemoMessage} in case the message was decrypted
 * properly, otherwise it contains the message itself.
 *
 * @param managerGuard authenticated OmemoManager.
 * @param mamQuery Mam archive query
 * @return list of {@link MessageOrOmemoMessage MessageOrOmemoMessages}.
 *
 * @throws IOException if an I/O error occurred.
 */
List<MessageOrOmemoMessage> decryptMamQueryResult(OmemoManager.LoggedInOmemoManager managerGuard, MamManager.MamQuery mamQuery) throws IOException {
    List<MessageOrOmemoMessage> result = new ArrayList<>();
    for (Message message : mamQuery.getMessages()) {
        if (OmemoManager.stanzaContainsOmemoElement(message)) {
            OmemoElement element = (OmemoElement) message.getExtensionElement(OmemoElement.NAME_ENCRYPTED, OmemoConstants.OMEMO_NAMESPACE_V_AXOLOTL);
            // Decrypt OMEMO messages
            try {
                OmemoMessage.Received omemoMessage = decryptMessage(managerGuard, message.getFrom().asBareJid(), element);
                result.add(new MessageOrOmemoMessage(omemoMessage));
            } catch (NoRawSessionException | CorruptedOmemoKeyException | CryptoFailedException e) {
                LOGGER.log(Level.WARNING, "decryptMamQueryResult failed to decrypt message from " + message.getFrom() + " due to corrupted session/key: " + e.getMessage());
                result.add(new MessageOrOmemoMessage(message));
            }
        } else {
            // Wrap cleartext messages
            result.add(new MessageOrOmemoMessage(message));
        }
    }
    return result;
}
Also used : CryptoFailedException(org.jivesoftware.smackx.omemo.exceptions.CryptoFailedException) MessageOrOmemoMessage(org.jivesoftware.smackx.omemo.util.MessageOrOmemoMessage) MessageOrOmemoMessage(org.jivesoftware.smackx.omemo.util.MessageOrOmemoMessage) Message(org.jivesoftware.smack.packet.Message) NoRawSessionException(org.jivesoftware.smackx.omemo.exceptions.NoRawSessionException) ArrayList(java.util.ArrayList) MessageOrOmemoMessage(org.jivesoftware.smackx.omemo.util.MessageOrOmemoMessage) OmemoElement(org.jivesoftware.smackx.omemo.element.OmemoElement) CorruptedOmemoKeyException(org.jivesoftware.smackx.omemo.exceptions.CorruptedOmemoKeyException)

Example 3 with NoRawSessionException

use of org.jivesoftware.smackx.omemo.exceptions.NoRawSessionException in project Smack by igniterealtime.

the class OmemoService method onOmemoCarbonCopyReceived.

@Override
public void onOmemoCarbonCopyReceived(CarbonExtension.Direction direction, Message carbonCopy, Message wrappingMessage, OmemoManager.LoggedInOmemoManager managerGuard) throws IOException {
    OmemoManager manager = managerGuard.get();
    // Avoid the ratchet being manipulated and the bundle being published multiple times simultaneously
    synchronized (manager) {
        OmemoDevice userDevice = manager.getOwnDevice();
        OmemoElement element = (OmemoElement) carbonCopy.getExtensionElement(OmemoElement.NAME_ENCRYPTED, OmemoElement_VAxolotl.NAMESPACE);
        if (element == null) {
            return;
        }
        OmemoMessage.Received decrypted;
        BareJid sender = carbonCopy.getFrom().asBareJid();
        try {
            decrypted = decryptMessage(managerGuard, sender, element);
            manager.notifyOmemoCarbonCopyReceived(direction, carbonCopy, wrappingMessage, decrypted);
            if (decrypted.isPreKeyMessage() && OmemoConfiguration.getCompleteSessionWithEmptyMessage()) {
                LOGGER.log(Level.FINE, "Received a preKeyMessage in a carbon copy from " + decrypted.getSenderDevice() + ".\n" + "Complete the session by sending an empty response message.");
                try {
                    sendRatchetUpdate(managerGuard, decrypted.getSenderDevice());
                } catch (CannotEstablishOmemoSessionException e) {
                    throw new AssertionError("Since we successfully received a message, we MUST be able to " + "establish a session. " + e);
                } catch (NoSuchAlgorithmException | InterruptedException | SmackException.NotConnectedException | SmackException.NoResponseException e) {
                    LOGGER.log(Level.WARNING, "Cannot send a ratchet update message.", e);
                }
            }
        } catch (NoRawSessionException e) {
            OmemoDevice device = e.getDeviceWithoutSession();
            LOGGER.log(Level.WARNING, "No raw session found for contact " + device + ". ", e);
            if (OmemoConfiguration.getRepairBrokenSessionsWithPreKeyMessages()) {
                repairBrokenSessionWithPreKeyMessage(managerGuard, device);
            }
        } catch (CorruptedOmemoKeyException | CryptoFailedException e) {
            LOGGER.log(Level.WARNING, "Could not decrypt incoming carbon copy: ", e);
        }
        // Upload fresh bundle.
        if (getOmemoStoreBackend().loadOmemoPreKeys(userDevice).size() < OmemoConstants.PRE_KEY_COUNT_PER_BUNDLE) {
            LOGGER.log(Level.FINE, "We used up a preKey. Upload a fresh bundle.");
            try {
                getOmemoStoreBackend().replenishKeys(userDevice);
                OmemoBundleElement bundleElement = getOmemoStoreBackend().packOmemoBundle(userDevice);
                publishBundle(manager.getConnection(), userDevice, bundleElement);
            } catch (CorruptedOmemoKeyException | InterruptedException | SmackException.NoResponseException | SmackException.NotConnectedException | XMPPException.XMPPErrorException | NotALeafNodeException e) {
                LOGGER.log(Level.WARNING, "Could not republish replenished bundle.", e);
            }
        }
    }
}
Also used : CryptoFailedException(org.jivesoftware.smackx.omemo.exceptions.CryptoFailedException) OmemoDevice(org.jivesoftware.smackx.omemo.internal.OmemoDevice) NotALeafNodeException(org.jivesoftware.smackx.pubsub.PubSubException.NotALeafNodeException) EntityBareJid(org.jxmpp.jid.EntityBareJid) BareJid(org.jxmpp.jid.BareJid) NoRawSessionException(org.jivesoftware.smackx.omemo.exceptions.NoRawSessionException) MessageOrOmemoMessage(org.jivesoftware.smackx.omemo.util.MessageOrOmemoMessage) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) OmemoBundleElement(org.jivesoftware.smackx.omemo.element.OmemoBundleElement) CannotEstablishOmemoSessionException(org.jivesoftware.smackx.omemo.exceptions.CannotEstablishOmemoSessionException) CorruptedOmemoKeyException(org.jivesoftware.smackx.omemo.exceptions.CorruptedOmemoKeyException) OmemoElement(org.jivesoftware.smackx.omemo.element.OmemoElement)

Example 4 with NoRawSessionException

use of org.jivesoftware.smackx.omemo.exceptions.NoRawSessionException in project Smack by igniterealtime.

the class OmemoService method decryptStanza.

/**
 * Decrypt the OmemoElement inside the given Stanza and return it.
 * Return null if something goes wrong.
 *
 * @param stanza stanza
 * @param managerGuard authenticated OmemoManager
 * @return decrypted OmemoMessage or null
 *
 * @throws IOException if an I/O error occurred.
 */
OmemoMessage.Received decryptStanza(Stanza stanza, OmemoManager.LoggedInOmemoManager managerGuard) throws IOException {
    OmemoManager manager = managerGuard.get();
    // Avoid the ratchet being manipulated and the bundle being published multiple times simultaneously
    synchronized (manager) {
        OmemoDevice userDevice = manager.getOwnDevice();
        OmemoElement element = (OmemoElement) stanza.getExtensionElement(OmemoElement.NAME_ENCRYPTED, OmemoElement_VAxolotl.NAMESPACE);
        if (element == null) {
            return null;
        }
        OmemoMessage.Received decrypted = null;
        BareJid sender;
        try {
            MultiUserChat muc = getMuc(manager.getConnection(), stanza.getFrom());
            if (muc != null) {
                Occupant occupant = muc.getOccupant(stanza.getFrom().asEntityFullJidIfPossible());
                Jid occupantJid = occupant.getJid();
                if (occupantJid == null) {
                    LOGGER.log(Level.WARNING, "MUC message received, but there is no way to retrieve the senders Jid. " + stanza.getFrom());
                    return null;
                }
                sender = occupantJid.asBareJid();
                // try is for this
                decrypted = decryptMessage(managerGuard, sender, element);
            } else {
                sender = stanza.getFrom().asBareJid();
                // and this
                decrypted = decryptMessage(managerGuard, sender, element);
            }
            if (decrypted.isPreKeyMessage() && OmemoConfiguration.getCompleteSessionWithEmptyMessage()) {
                LOGGER.log(Level.FINE, "Received a preKeyMessage from " + decrypted.getSenderDevice() + ".\n" + "Complete the session by sending an empty response message.");
                try {
                    sendRatchetUpdate(managerGuard, decrypted.getSenderDevice());
                } catch (CannotEstablishOmemoSessionException e) {
                    throw new AssertionError("Since we successfully received a message, we MUST be able to " + "establish a session. " + e);
                } catch (NoSuchAlgorithmException | InterruptedException | SmackException.NotConnectedException | SmackException.NoResponseException e) {
                    LOGGER.log(Level.WARNING, "Cannot send a ratchet update message.", e);
                }
            }
        } catch (NoRawSessionException e) {
            OmemoDevice device = e.getDeviceWithoutSession();
            LOGGER.log(Level.WARNING, "No raw session found for contact " + device + ". ", e);
        } catch (CorruptedOmemoKeyException | CryptoFailedException e) {
            LOGGER.log(Level.WARNING, "Could not decrypt incoming message: ", e);
        }
        // Upload fresh bundle.
        if (getOmemoStoreBackend().loadOmemoPreKeys(userDevice).size() < OmemoConstants.PRE_KEY_COUNT_PER_BUNDLE) {
            LOGGER.log(Level.FINE, "We used up a preKey. Upload a fresh bundle.");
            try {
                getOmemoStoreBackend().replenishKeys(userDevice);
                OmemoBundleElement bundleElement = getOmemoStoreBackend().packOmemoBundle(userDevice);
                publishBundle(manager.getConnection(), userDevice, bundleElement);
            } catch (CorruptedOmemoKeyException | InterruptedException | SmackException.NoResponseException | SmackException.NotConnectedException | XMPPException.XMPPErrorException | NotALeafNodeException e) {
                LOGGER.log(Level.WARNING, "Could not republish replenished bundle.", e);
            }
        }
        return decrypted;
    }
}
Also used : CryptoFailedException(org.jivesoftware.smackx.omemo.exceptions.CryptoFailedException) MultiUserChat(org.jivesoftware.smackx.muc.MultiUserChat) OmemoDevice(org.jivesoftware.smackx.omemo.internal.OmemoDevice) EntityBareJid(org.jxmpp.jid.EntityBareJid) Jid(org.jxmpp.jid.Jid) BareJid(org.jxmpp.jid.BareJid) NotALeafNodeException(org.jivesoftware.smackx.pubsub.PubSubException.NotALeafNodeException) EntityBareJid(org.jxmpp.jid.EntityBareJid) BareJid(org.jxmpp.jid.BareJid) Occupant(org.jivesoftware.smackx.muc.Occupant) NoRawSessionException(org.jivesoftware.smackx.omemo.exceptions.NoRawSessionException) MessageOrOmemoMessage(org.jivesoftware.smackx.omemo.util.MessageOrOmemoMessage) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) OmemoBundleElement(org.jivesoftware.smackx.omemo.element.OmemoBundleElement) CannotEstablishOmemoSessionException(org.jivesoftware.smackx.omemo.exceptions.CannotEstablishOmemoSessionException) CorruptedOmemoKeyException(org.jivesoftware.smackx.omemo.exceptions.CorruptedOmemoKeyException) OmemoElement(org.jivesoftware.smackx.omemo.element.OmemoElement)

Example 5 with NoRawSessionException

use of org.jivesoftware.smackx.omemo.exceptions.NoRawSessionException in project Smack by igniterealtime.

the class SignalOmemoRatchet method doubleRatchetDecrypt.

@Override
public byte[] doubleRatchetDecrypt(OmemoDevice sender, byte[] encryptedKey) throws CorruptedOmemoKeyException, NoRawSessionException, CryptoFailedException, UntrustedOmemoIdentityException, IOException {
    SessionCipher cipher = getCipher(sender);
    byte[] decryptedKey;
    // Try to handle the message as a PreKeySignalMessage...
    try {
        PreKeySignalMessage preKeyMessage = new PreKeySignalMessage(encryptedKey);
        if (!preKeyMessage.getPreKeyId().isPresent()) {
            throw new CryptoFailedException("PreKeyMessage did not contain a preKeyId.");
        }
        IdentityKey messageIdentityKey = preKeyMessage.getIdentityKey();
        IdentityKey previousIdentityKey = store.loadOmemoIdentityKey(storeConnector.getOurDevice(), sender);
        if (previousIdentityKey != null && !previousIdentityKey.getFingerprint().equals(messageIdentityKey.getFingerprint())) {
            throw new UntrustedOmemoIdentityException(sender, store.keyUtil().getFingerprintOfIdentityKey(previousIdentityKey), store.keyUtil().getFingerprintOfIdentityKey(messageIdentityKey));
        }
        try {
            decryptedKey = cipher.decrypt(preKeyMessage);
        } catch (UntrustedIdentityException e) {
            throw new AssertionError("Signals trust management MUST be disabled.");
        } catch (LegacyMessageException | InvalidKeyException e) {
            throw new CryptoFailedException(e);
        } catch (InvalidKeyIdException e) {
            throw new NoRawSessionException(sender, e);
        } catch (DuplicateMessageException e) {
            LOGGER.log(Level.INFO, "Decryption of PreKeyMessage from " + sender + " failed, since the message has been decrypted before.");
            return null;
        }
    } catch (InvalidVersionException | InvalidMessageException noPreKeyMessage) {
        // ...if that fails, handle it as a SignalMessage
        try {
            SignalMessage message = new SignalMessage(encryptedKey);
            decryptedKey = getCipher(sender).decrypt(message);
        } catch (UntrustedIdentityException e) {
            throw new AssertionError("Signals trust management MUST be disabled.");
        } catch (InvalidMessageException | NoSessionException e) {
            throw new NoRawSessionException(sender, e);
        } catch (LegacyMessageException e) {
            throw new CryptoFailedException(e);
        } catch (DuplicateMessageException e1) {
            LOGGER.log(Level.INFO, "Decryption of SignalMessage from " + sender + " failed, since the message has been decrypted before.");
            return null;
        }
    }
    return decryptedKey;
}
Also used : CryptoFailedException(org.jivesoftware.smackx.omemo.exceptions.CryptoFailedException) InvalidMessageException(org.whispersystems.libsignal.InvalidMessageException) IdentityKey(org.whispersystems.libsignal.IdentityKey) UntrustedIdentityException(org.whispersystems.libsignal.UntrustedIdentityException) PreKeySignalMessage(org.whispersystems.libsignal.protocol.PreKeySignalMessage) SignalMessage(org.whispersystems.libsignal.protocol.SignalMessage) InvalidVersionException(org.whispersystems.libsignal.InvalidVersionException) NoRawSessionException(org.jivesoftware.smackx.omemo.exceptions.NoRawSessionException) InvalidKeyException(org.whispersystems.libsignal.InvalidKeyException) PreKeySignalMessage(org.whispersystems.libsignal.protocol.PreKeySignalMessage) DuplicateMessageException(org.whispersystems.libsignal.DuplicateMessageException) InvalidKeyIdException(org.whispersystems.libsignal.InvalidKeyIdException) LegacyMessageException(org.whispersystems.libsignal.LegacyMessageException) SessionCipher(org.whispersystems.libsignal.SessionCipher) UntrustedOmemoIdentityException(org.jivesoftware.smackx.omemo.exceptions.UntrustedOmemoIdentityException)

Aggregations

CryptoFailedException (org.jivesoftware.smackx.omemo.exceptions.CryptoFailedException)5 NoRawSessionException (org.jivesoftware.smackx.omemo.exceptions.NoRawSessionException)5 OmemoElement (org.jivesoftware.smackx.omemo.element.OmemoElement)4 CorruptedOmemoKeyException (org.jivesoftware.smackx.omemo.exceptions.CorruptedOmemoKeyException)4 MessageOrOmemoMessage (org.jivesoftware.smackx.omemo.util.MessageOrOmemoMessage)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 OmemoBundleElement (org.jivesoftware.smackx.omemo.element.OmemoBundleElement)3 CannotEstablishOmemoSessionException (org.jivesoftware.smackx.omemo.exceptions.CannotEstablishOmemoSessionException)3 OmemoDevice (org.jivesoftware.smackx.omemo.internal.OmemoDevice)3 NotALeafNodeException (org.jivesoftware.smackx.pubsub.PubSubException.NotALeafNodeException)3 BareJid (org.jxmpp.jid.BareJid)3 EntityBareJid (org.jxmpp.jid.EntityBareJid)3 MultiUserChat (org.jivesoftware.smackx.muc.MultiUserChat)2 Occupant (org.jivesoftware.smackx.muc.Occupant)2 Jid (org.jxmpp.jid.Jid)2 ArrayList (java.util.ArrayList)1 Message (org.jivesoftware.smack.packet.Message)1 UntrustedOmemoIdentityException (org.jivesoftware.smackx.omemo.exceptions.UntrustedOmemoIdentityException)1 DuplicateMessageException (org.whispersystems.libsignal.DuplicateMessageException)1 IdentityKey (org.whispersystems.libsignal.IdentityKey)1