001/**
002 *
003 * Copyright 2017 Paul Schaub
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smackx.omemo;
018
019import java.io.IOException;
020import java.nio.charset.StandardCharsets;
021import java.util.ArrayList;
022import java.util.List;
023import java.util.logging.Level;
024import java.util.logging.Logger;
025
026import javax.crypto.BadPaddingException;
027import javax.crypto.IllegalBlockSizeException;
028
029import org.jivesoftware.smackx.omemo.element.OmemoElement;
030import org.jivesoftware.smackx.omemo.element.OmemoKeyElement;
031import org.jivesoftware.smackx.omemo.exceptions.CorruptedOmemoKeyException;
032import org.jivesoftware.smackx.omemo.exceptions.CryptoFailedException;
033import org.jivesoftware.smackx.omemo.exceptions.MultipleCryptoFailedException;
034import org.jivesoftware.smackx.omemo.exceptions.NoRawSessionException;
035import org.jivesoftware.smackx.omemo.exceptions.UntrustedOmemoIdentityException;
036import org.jivesoftware.smackx.omemo.internal.CipherAndAuthTag;
037import org.jivesoftware.smackx.omemo.internal.CiphertextTuple;
038import org.jivesoftware.smackx.omemo.internal.OmemoDevice;
039
040public abstract class OmemoRatchet<T_IdKeyPair, T_IdKey, T_PreKey, T_SigPreKey, T_Sess, T_Addr, T_ECPub, T_Bundle, T_Ciph> {
041    private static final Logger LOGGER = Logger.getLogger(OmemoRatchet.class.getName());
042
043    protected final OmemoManager omemoManager;
044    protected final OmemoStore<T_IdKeyPair, T_IdKey, T_PreKey, T_SigPreKey, T_Sess, T_Addr, T_ECPub, T_Bundle, T_Ciph> store;
045
046    /**
047     * Constructor.
048     *
049     * @param omemoManager omemoManager
050     * @param store omemoStore
051     */
052    public OmemoRatchet(OmemoManager omemoManager,
053                        OmemoStore<T_IdKeyPair, T_IdKey, T_PreKey, T_SigPreKey, T_Sess, T_Addr, T_ECPub, T_Bundle, T_Ciph> store) {
054        this.omemoManager = omemoManager;
055        this.store = store;
056    }
057
058    /**
059     * Decrypt a double-ratchet-encrypted message key.
060     *
061     * @param sender sender of the message.
062     * @param encryptedKey key encrypted with the ratchet of the sender.
063     * @return decrypted message key.
064     *
065     * @throws CorruptedOmemoKeyException if the OMEMO key is corrupted.
066     * @throws NoRawSessionException when no double ratchet session was found.
067     * @throws CryptoFailedException if the OMEMO cryptography failed.
068     * @throws UntrustedOmemoIdentityException if the OMEMO identity is not trusted.
069     * @throws IOException if an I/O error occurred.
070     */
071    public abstract byte[] doubleRatchetDecrypt(OmemoDevice sender, byte[] encryptedKey)
072            throws CorruptedOmemoKeyException, NoRawSessionException, CryptoFailedException,
073            UntrustedOmemoIdentityException, IOException;
074
075    /**
076     * Encrypt a messageKey with the double ratchet session of the recipient.
077     *
078     * @param recipient recipient of the message.
079     * @param messageKey key we want to encrypt.
080     * @return encrypted message key.
081     */
082    public abstract CiphertextTuple doubleRatchetEncrypt(OmemoDevice recipient, byte[] messageKey);
083
084    /**
085     * Try to decrypt the transported message key using the double ratchet session.
086     *
087     * @param element omemoElement
088     * @return tuple of cipher generated from the unpacked message key and the auth-tag
089     *
090     * @throws CryptoFailedException if decryption using the double ratchet fails
091     * @throws NoRawSessionException if we have no session, but the element was NOT a PreKeyMessage
092     * @throws IOException if an I/O error occurred.
093     */
094    CipherAndAuthTag retrieveMessageKeyAndAuthTag(OmemoDevice sender, OmemoElement element) throws CryptoFailedException,
095            NoRawSessionException, IOException {
096        int keyId = omemoManager.getDeviceId();
097        byte[] unpackedKey = null;
098        List<CryptoFailedException> decryptExceptions = new ArrayList<>();
099        List<OmemoKeyElement> keys = element.getHeader().getKeys();
100
101        boolean preKey = false;
102
103        // Find key with our ID.
104        for (OmemoKeyElement k : keys) {
105            if (k.getId() == keyId) {
106                try {
107                    unpackedKey = doubleRatchetDecrypt(sender, k.getData());
108                    preKey = k.isPreKey();
109                    break;
110                } catch (CryptoFailedException e) {
111                    // There might be multiple keys with our id, but we can only decrypt one.
112                    // So we can't throw the exception, when decrypting the first duplicate which is not for us.
113                    decryptExceptions.add(e);
114                } catch (CorruptedOmemoKeyException e) {
115                    decryptExceptions.add(new CryptoFailedException(e));
116                } catch (UntrustedOmemoIdentityException e) {
117                    LOGGER.log(Level.WARNING, "Received message from " + sender + " contained unknown identityKey. Ignore message.", e);
118                }
119            }
120        }
121
122        if (unpackedKey == null) {
123            if (!decryptExceptions.isEmpty()) {
124                throw MultipleCryptoFailedException.from(decryptExceptions);
125            }
126
127            throw new CryptoFailedException("Transported key could not be decrypted, since no suitable message key " +
128                    "was provided. Provides keys: " + keys);
129        }
130
131        // Split in AES auth-tag and key
132        byte[] messageKey = new byte[16];
133        byte[] authTag = null;
134
135        if (unpackedKey.length == 32) {
136            authTag = new byte[16];
137            // copy key part into messageKey
138            System.arraycopy(unpackedKey, 0, messageKey, 0, 16);
139            // copy tag part into authTag
140            System.arraycopy(unpackedKey, 16, authTag, 0, 16);
141        } else if (element.isKeyTransportElement() && unpackedKey.length == 16) {
142            messageKey = unpackedKey;
143        } else {
144            throw new CryptoFailedException("MessageKey has wrong length: "
145                    + unpackedKey.length + ". Probably legacy auth tag format.");
146        }
147
148        return new CipherAndAuthTag(messageKey, element.getHeader().getIv(), authTag, preKey);
149    }
150
151    /**
152     * Use the symmetric key in cipherAndAuthTag to decrypt the payload of the omemoMessage.
153     * The decrypted payload will be the body of the returned Message.
154     *
155     * @param element omemoElement containing a payload.
156     * @param cipherAndAuthTag cipher and authentication tag.
157     * @return decrypted plain text.
158     *
159     * @throws CryptoFailedException if decryption using AES key fails.
160     */
161    static String decryptMessageElement(OmemoElement element, CipherAndAuthTag cipherAndAuthTag)
162            throws CryptoFailedException {
163        if (!element.isMessageElement()) {
164            throw new IllegalArgumentException("decryptMessageElement cannot decrypt OmemoElement which is no MessageElement!");
165        }
166
167        if (cipherAndAuthTag.getAuthTag() == null || cipherAndAuthTag.getAuthTag().length != 16) {
168            throw new CryptoFailedException("AuthenticationTag is null or has wrong length: "
169                    + (cipherAndAuthTag.getAuthTag() == null ? "null" : cipherAndAuthTag.getAuthTag().length));
170        }
171
172        byte[] encryptedBody = payloadAndAuthTag(element, cipherAndAuthTag.getAuthTag());
173
174        try {
175            String plaintext = new String(cipherAndAuthTag.getCipher().doFinal(encryptedBody), StandardCharsets.UTF_8);
176            return plaintext;
177        } catch (IllegalBlockSizeException | BadPaddingException e) {
178            throw new CryptoFailedException("decryptMessageElement could not decipher message body: "
179                    + e.getMessage());
180        }
181    }
182
183    /**
184     * Return the concatenation of the payload of the OmemoElement and the given auth tag.
185     *
186     * @param element omemoElement (message element)
187     * @param authTag authTag
188     * @return payload + authTag
189     */
190    static byte[] payloadAndAuthTag(OmemoElement element, byte[] authTag) {
191        if (!element.isMessageElement()) {
192            throw new IllegalArgumentException("OmemoElement has no payload.");
193        }
194
195        byte[] payload = new byte[element.getPayload().length + authTag.length];
196        System.arraycopy(element.getPayload(), 0, payload, 0, element.getPayload().length);
197        System.arraycopy(authTag, 0, payload, element.getPayload().length, authTag.length);
198        return payload;
199    }
200
201}