XmppAxolotlMessage.java

  1package eu.siacs.conversations.crypto.axolotl;
  2
  3import android.util.Base64;
  4import android.util.Log;
  5
  6import java.security.InvalidAlgorithmParameterException;
  7import java.security.InvalidKeyException;
  8import java.security.NoSuchAlgorithmException;
  9import java.security.NoSuchProviderException;
 10import java.security.SecureRandom;
 11import java.util.ArrayList;
 12import java.util.List;
 13
 14import javax.crypto.BadPaddingException;
 15import javax.crypto.Cipher;
 16import javax.crypto.IllegalBlockSizeException;
 17import javax.crypto.KeyGenerator;
 18import javax.crypto.NoSuchPaddingException;
 19import javax.crypto.SecretKey;
 20import javax.crypto.spec.IvParameterSpec;
 21import javax.crypto.spec.SecretKeySpec;
 22
 23import eu.siacs.conversations.Config;
 24import eu.siacs.conversations.utils.Compatibility;
 25import eu.siacs.conversations.xml.Element;
 26import eu.siacs.conversations.xmpp.Jid;
 27
 28public class XmppAxolotlMessage {
 29    public static final String CONTAINERTAG = "encrypted";
 30    private static final String HEADER = "header";
 31    private static final String SOURCEID = "sid";
 32    private static final String KEYTAG = "key";
 33    private static final String REMOTEID = "rid";
 34    private static final String IVTAG = "iv";
 35    private static final String PAYLOAD = "payload";
 36
 37    private static final String KEYTYPE = "AES";
 38    private static final String CIPHERMODE = "AES/GCM/NoPadding";
 39    private static final String PROVIDER = "BC";
 40    private final List<XmppAxolotlSession.AxolotlKey> keys;
 41    private final Jid from;
 42    private final int sourceDeviceId;
 43    private byte[] innerKey;
 44    private byte[] ciphertext = null;
 45    private byte[] authtagPlusInnerKey = null;
 46    private byte[] iv = null;
 47
 48    private XmppAxolotlMessage(final Element axolotlMessage, final Jid from) throws IllegalArgumentException {
 49        this.from = from;
 50        Element header = axolotlMessage.findChild(HEADER);
 51        try {
 52            this.sourceDeviceId = Integer.parseInt(header.getAttribute(SOURCEID));
 53        } catch (NumberFormatException e) {
 54            throw new IllegalArgumentException("invalid source id");
 55        }
 56        List<Element> keyElements = header.getChildren();
 57        this.keys = new ArrayList<>();
 58        for (Element keyElement : keyElements) {
 59            switch (keyElement.getName()) {
 60                case KEYTAG:
 61                    try {
 62                        int recipientId = Integer.parseInt(keyElement.getAttribute(REMOTEID));
 63                        byte[] key = Base64.decode(keyElement.getContent().trim(), Base64.DEFAULT);
 64                        boolean isPreKey = keyElement.getAttributeAsBoolean("prekey");
 65                        this.keys.add(new XmppAxolotlSession.AxolotlKey(recipientId, key, isPreKey));
 66                    } catch (NumberFormatException e) {
 67                        throw new IllegalArgumentException("invalid remote id");
 68                    }
 69                    break;
 70                case IVTAG:
 71                    if (this.iv != null) {
 72                        throw new IllegalArgumentException("Duplicate iv entry");
 73                    }
 74                    iv = Base64.decode(keyElement.getContent().trim(), Base64.DEFAULT);
 75                    break;
 76                default:
 77                    Log.w(Config.LOGTAG, "Unexpected element in header: " + keyElement.toString());
 78                    break;
 79            }
 80        }
 81        final Element payloadElement = axolotlMessage.findChildEnsureSingle(PAYLOAD, AxolotlService.PEP_PREFIX);
 82        if (payloadElement != null) {
 83            ciphertext = Base64.decode(payloadElement.getContent().trim(), Base64.DEFAULT);
 84        }
 85    }
 86
 87    XmppAxolotlMessage(Jid from, int sourceDeviceId) {
 88        this.from = from;
 89        this.sourceDeviceId = sourceDeviceId;
 90        this.keys = new ArrayList<>();
 91        this.iv = generateIv();
 92        this.innerKey = generateKey();
 93    }
 94
 95    public static int parseSourceId(final Element axolotlMessage) throws IllegalArgumentException {
 96        final Element header = axolotlMessage.findChild(HEADER);
 97        if (header == null) {
 98            throw new IllegalArgumentException("No header found");
 99        }
100        try {
101            return Integer.parseInt(header.getAttribute(SOURCEID));
102        } catch (NumberFormatException e) {
103            throw new IllegalArgumentException("invalid source id");
104        }
105    }
106
107    public static XmppAxolotlMessage fromElement(Element element, Jid from) {
108        return new XmppAxolotlMessage(element, from);
109    }
110
111    private static byte[] generateKey() {
112        try {
113            KeyGenerator generator = KeyGenerator.getInstance(KEYTYPE);
114            generator.init(128);
115            return generator.generateKey().getEncoded();
116        } catch (NoSuchAlgorithmException e) {
117            throw new IllegalStateException(e);
118        }
119    }
120
121    private static byte[] generateIv() {
122        final SecureRandom random = new SecureRandom();
123        final byte[] iv = new byte[12];
124        random.nextBytes(iv);
125        return iv;
126    }
127
128    private static byte[] getPaddedBytes(String plaintext) {
129        int plainLength = plaintext.getBytes().length;
130        int pad = Math.max(64, (plainLength / 32 + 1) * 32) - plainLength;
131        SecureRandom random = new SecureRandom();
132        int left = random.nextInt(pad);
133        int right = pad - left;
134        StringBuilder builder = new StringBuilder(plaintext);
135        for (int i = 0; i < left; ++i) {
136            builder.insert(0, random.nextBoolean() ? "\t" : " ");
137        }
138        for (int i = 0; i < right; ++i) {
139            builder.append(random.nextBoolean() ? "\t" : " ");
140        }
141        return builder.toString().getBytes();
142    }
143
144    public boolean hasPayload() {
145        return ciphertext != null;
146    }
147
148    void encrypt(final String plaintext) throws CryptoFailedException {
149        try {
150            SecretKey secretKey = new SecretKeySpec(innerKey, KEYTYPE);
151            IvParameterSpec ivSpec = new IvParameterSpec(iv);
152            Cipher cipher = Compatibility.twentyEight() ? Cipher.getInstance(CIPHERMODE) : Cipher.getInstance(CIPHERMODE, PROVIDER);
153            cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
154            this.ciphertext = cipher.doFinal(Config.OMEMO_PADDING ? getPaddedBytes(plaintext) : plaintext.getBytes());
155            if (Config.PUT_AUTH_TAG_INTO_KEY && this.ciphertext != null) {
156                this.authtagPlusInnerKey = new byte[16 + 16];
157                byte[] ciphertext = new byte[this.ciphertext.length - 16];
158                System.arraycopy(this.ciphertext, 0, ciphertext, 0, ciphertext.length);
159                System.arraycopy(this.ciphertext, ciphertext.length, authtagPlusInnerKey, 16, 16);
160                System.arraycopy(this.innerKey, 0, authtagPlusInnerKey, 0, this.innerKey.length);
161                this.ciphertext = ciphertext;
162            }
163        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
164                | IllegalBlockSizeException | BadPaddingException | NoSuchProviderException
165                | InvalidAlgorithmParameterException e) {
166            throw new CryptoFailedException(e);
167        }
168    }
169
170    public Jid getFrom() {
171        return this.from;
172    }
173
174    int getSenderDeviceId() {
175        return sourceDeviceId;
176    }
177
178    void addDevice(XmppAxolotlSession session) {
179        addDevice(session, false);
180    }
181
182    void addDevice(XmppAxolotlSession session, boolean ignoreSessionTrust) {
183        XmppAxolotlSession.AxolotlKey key;
184        if (authtagPlusInnerKey != null) {
185            key = session.processSending(authtagPlusInnerKey, ignoreSessionTrust);
186        } else {
187            key = session.processSending(innerKey, ignoreSessionTrust);
188        }
189        if (key != null) {
190            keys.add(key);
191        }
192    }
193
194    public byte[] getInnerKey() {
195        return innerKey;
196    }
197
198    public byte[] getIV() {
199        return this.iv;
200    }
201
202    public Element toElement() {
203        Element encryptionElement = new Element(CONTAINERTAG, AxolotlService.PEP_PREFIX);
204        Element headerElement = encryptionElement.addChild(HEADER);
205        headerElement.setAttribute(SOURCEID, sourceDeviceId);
206        for (XmppAxolotlSession.AxolotlKey key : keys) {
207            Element keyElement = new Element(KEYTAG);
208            keyElement.setAttribute(REMOTEID, key.deviceId);
209            if (key.prekey) {
210                keyElement.setAttribute("prekey", "true");
211            }
212            keyElement.setContent(Base64.encodeToString(key.key, Base64.NO_WRAP));
213            headerElement.addChild(keyElement);
214        }
215        headerElement.addChild(IVTAG).setContent(Base64.encodeToString(iv, Base64.NO_WRAP));
216        if (ciphertext != null) {
217            Element payload = encryptionElement.addChild(PAYLOAD);
218            payload.setContent(Base64.encodeToString(ciphertext, Base64.NO_WRAP));
219        }
220        return encryptionElement;
221    }
222
223    private byte[] unpackKey(XmppAxolotlSession session, Integer sourceDeviceId) throws CryptoFailedException {
224        ArrayList<XmppAxolotlSession.AxolotlKey> possibleKeys = new ArrayList<>();
225        for (XmppAxolotlSession.AxolotlKey key : keys) {
226            if (key.deviceId == sourceDeviceId) {
227                possibleKeys.add(key);
228            }
229        }
230        if (possibleKeys.size() == 0) {
231            throw new NotEncryptedForThisDeviceException();
232        }
233        return session.processReceiving(possibleKeys);
234    }
235
236    XmppAxolotlKeyTransportMessage getParameters(XmppAxolotlSession session, Integer sourceDeviceId) throws CryptoFailedException {
237        return new XmppAxolotlKeyTransportMessage(session.getFingerprint(), unpackKey(session, sourceDeviceId), getIV());
238    }
239
240    public XmppAxolotlPlaintextMessage decrypt(XmppAxolotlSession session, Integer sourceDeviceId) throws CryptoFailedException {
241        XmppAxolotlPlaintextMessage plaintextMessage = null;
242        byte[] key = unpackKey(session, sourceDeviceId);
243        if (key != null) {
244            try {
245                if (key.length < 32) {
246                    throw new OutdatedSenderException("Key did not contain auth tag. Sender needs to update their OMEMO client");
247                }
248                final int authTagLength = key.length - 16;
249                byte[] newCipherText = new byte[key.length - 16 + ciphertext.length];
250                byte[] newKey = new byte[16];
251                System.arraycopy(ciphertext, 0, newCipherText, 0, ciphertext.length);
252                System.arraycopy(key, 16, newCipherText, ciphertext.length, authTagLength);
253                System.arraycopy(key, 0, newKey, 0, newKey.length);
254                ciphertext = newCipherText;
255                key = newKey;
256
257                final Cipher cipher = Compatibility.twentyEight() ? Cipher.getInstance(CIPHERMODE) : Cipher.getInstance(CIPHERMODE, PROVIDER);
258                SecretKeySpec keySpec = new SecretKeySpec(key, KEYTYPE);
259                IvParameterSpec ivSpec = new IvParameterSpec(iv);
260
261                cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
262
263                String plaintext = new String(cipher.doFinal(ciphertext));
264                plaintextMessage = new XmppAxolotlPlaintextMessage(Config.OMEMO_PADDING ? plaintext.trim() : plaintext, session.getFingerprint());
265
266            } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
267                    | InvalidAlgorithmParameterException | IllegalBlockSizeException
268                    | BadPaddingException | NoSuchProviderException e) {
269                throw new CryptoFailedException(e);
270            }
271        }
272        return plaintextMessage;
273    }
274
275    public static class XmppAxolotlPlaintextMessage {
276        private final String plaintext;
277        private final String fingerprint;
278
279        XmppAxolotlPlaintextMessage(String plaintext, String fingerprint) {
280            this.plaintext = plaintext;
281            this.fingerprint = fingerprint;
282        }
283
284        public String getPlaintext() {
285            return plaintext;
286        }
287
288
289        public String getFingerprint() {
290            return fingerprint;
291        }
292    }
293
294    public static class XmppAxolotlKeyTransportMessage {
295        private final String fingerprint;
296        private final byte[] key;
297        private final byte[] iv;
298
299        XmppAxolotlKeyTransportMessage(String fingerprint, byte[] key, byte[] iv) {
300            this.fingerprint = fingerprint;
301            this.key = key;
302            this.iv = iv;
303        }
304
305        public String getFingerprint() {
306            return fingerprint;
307        }
308
309        public byte[] getKey() {
310            return key;
311        }
312
313        public byte[] getIv() {
314            return iv;
315        }
316    }
317}