001/**
002 *
003 * Copyright 2017 Paul Schaub
004 *
005 * This file is part of smack-omemo-signal.
006 *
007 * smack-omemo-signal is free software; you can redistribute it and/or modify
008 * it under the terms of the GNU General Public License as published by
009 * the Free Software Foundation; either version 3 of the License, or
010 * (at your option) any later version.
011 *
012 * This program is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
015 * GNU General Public License for more details.
016 *
017 * You should have received a copy of the GNU General Public License
018 * along with this program; if not, write to the Free Software Foundation,
019 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
020 */
021package org.jivesoftware.smackx.omemo.signal;
022
023import java.util.logging.Level;
024import java.util.logging.Logger;
025
026import org.jivesoftware.smackx.omemo.OmemoManager;
027import org.jivesoftware.smackx.omemo.OmemoStore;
028import org.jivesoftware.smackx.omemo.element.OmemoElement;
029import org.jivesoftware.smackx.omemo.exceptions.NoRawSessionException;
030import org.jivesoftware.smackx.omemo.internal.CiphertextTuple;
031import org.jivesoftware.smackx.omemo.internal.OmemoDevice;
032import org.jivesoftware.smackx.omemo.internal.OmemoSession;
033
034import org.whispersystems.libsignal.DuplicateMessageException;
035import org.whispersystems.libsignal.IdentityKey;
036import org.whispersystems.libsignal.IdentityKeyPair;
037import org.whispersystems.libsignal.InvalidKeyException;
038import org.whispersystems.libsignal.InvalidKeyIdException;
039import org.whispersystems.libsignal.InvalidMessageException;
040import org.whispersystems.libsignal.InvalidVersionException;
041import org.whispersystems.libsignal.LegacyMessageException;
042import org.whispersystems.libsignal.NoSessionException;
043import org.whispersystems.libsignal.SessionCipher;
044import org.whispersystems.libsignal.SignalProtocolAddress;
045import org.whispersystems.libsignal.UntrustedIdentityException;
046import org.whispersystems.libsignal.ecc.ECPublicKey;
047import org.whispersystems.libsignal.protocol.CiphertextMessage;
048import org.whispersystems.libsignal.protocol.PreKeySignalMessage;
049import org.whispersystems.libsignal.protocol.SignalMessage;
050import org.whispersystems.libsignal.state.PreKeyBundle;
051import org.whispersystems.libsignal.state.PreKeyRecord;
052import org.whispersystems.libsignal.state.SessionRecord;
053import org.whispersystems.libsignal.state.SignedPreKeyRecord;
054
055/**
056 * Concrete implementation of the OmemoSession using the Signal library.
057 *
058 * @author Paul Schaub
059 */
060public class SignalOmemoSession extends OmemoSession<IdentityKeyPair, IdentityKey, PreKeyRecord, SignedPreKeyRecord, SessionRecord, SignalProtocolAddress, ECPublicKey, PreKeyBundle, SessionCipher> {
061    private static final Logger LOGGER = Logger.getLogger(SignalOmemoSession.class.getName());
062
063    /**
064     * Constructor used when the remote user initialized the session using a PreKeyOmemoMessage.
065     *
066     * @param omemoManager  omemoManager
067     * @param omemoStore    omemoStoreConnector that can be used to get information from
068     * @param remoteContact omemoDevice of the remote contact
069     * @param identityKey   identityKey of the remote contact
070     */
071    SignalOmemoSession(OmemoManager omemoManager, OmemoStore<IdentityKeyPair, IdentityKey, PreKeyRecord, SignedPreKeyRecord, SessionRecord, SignalProtocolAddress, ECPublicKey, PreKeyBundle, SessionCipher> omemoStore,
072                       OmemoDevice remoteContact, IdentityKey identityKey) {
073        super(omemoManager, omemoStore, remoteContact, identityKey);
074    }
075
076    /**
077     * Constructor used when we initiate a new Session with the remote user.
078     *
079     * @param omemoManager  omemoManager
080     * @param omemoStore    omemoStore used to get information from
081     * @param remoteContact omemoDevice of the remote contact
082     */
083    SignalOmemoSession(OmemoManager omemoManager,
084                       OmemoStore<IdentityKeyPair, IdentityKey, PreKeyRecord, SignedPreKeyRecord, SessionRecord, SignalProtocolAddress, ECPublicKey, PreKeyBundle, SessionCipher> omemoStore,
085                       OmemoDevice remoteContact) {
086        super(omemoManager, omemoStore, remoteContact);
087    }
088
089    @Override
090    public SessionCipher createCipher(OmemoDevice contact) {
091        SignalOmemoStoreConnector connector = new SignalOmemoStoreConnector(omemoManager, omemoStore);
092        return new SessionCipher(connector, connector, connector, connector,
093                omemoStore.keyUtil().omemoDeviceAsAddress(contact));
094    }
095
096    @Override
097    public CiphertextTuple encryptMessageKey(byte[] messageKey) {
098        CiphertextMessage ciphertextMessage;
099        ciphertextMessage = cipher.encrypt(messageKey);
100        int type = (ciphertextMessage.getType() == CiphertextMessage.PREKEY_TYPE ?
101                OmemoElement.TYPE_OMEMO_PREKEY_MESSAGE : OmemoElement.TYPE_OMEMO_MESSAGE);
102        return new CiphertextTuple(ciphertextMessage.serialize(), type);
103    }
104
105    @Override
106    public byte[] decryptMessageKey(byte[] encryptedKey) throws NoRawSessionException {
107        byte[] decryptedKey = null;
108        try {
109            try {
110                PreKeySignalMessage message = new PreKeySignalMessage(encryptedKey);
111                if (!message.getPreKeyId().isPresent()) {
112                    LOGGER.log(Level.WARNING, "PreKeySignalMessage did not contain a PreKeyId");
113                    return null;
114                }
115                LOGGER.log(Level.INFO, "PreKeySignalMessage received, new session ID: " + message.getSignedPreKeyId() + "/" + message.getPreKeyId().get());
116                IdentityKey messageIdentityKey = message.getIdentityKey();
117                if (this.identityKey != null && !this.identityKey.equals(messageIdentityKey)) {
118                    LOGGER.log(Level.INFO, "Had session with fingerprint " + getFingerprint() +
119                            ", received message with different fingerprint " + omemoStore.keyUtil().getFingerprint(messageIdentityKey) +
120                            ". Silently drop the message.");
121                } else {
122                    this.identityKey = messageIdentityKey;
123                    decryptedKey = cipher.decrypt(message);
124                    this.preKeyId = message.getPreKeyId().get();
125                }
126            } catch (InvalidMessageException | InvalidVersionException e) {
127                SignalMessage message = new SignalMessage(encryptedKey);
128                decryptedKey = cipher.decrypt(message);
129            } catch (InvalidKeyIdException e) {
130                throw new NoRawSessionException(e);
131            }
132            catch (InvalidKeyException | UntrustedIdentityException e) {
133                LOGGER.log(Level.SEVERE, "Error decrypting message header, " + e.getClass().getName() + ": " + e.getMessage());
134            }
135        } catch (InvalidMessageException | NoSessionException e) {
136            throw new NoRawSessionException(e);
137        } catch (LegacyMessageException | DuplicateMessageException e) {
138            LOGGER.log(Level.SEVERE, "Error decrypting message header, " + e.getClass().getName() + ": " + e.getMessage());
139        }
140        return decryptedKey;
141    }
142}