XmppAxolotlMessage.java

  1package eu.siacs.conversations.crypto.axolotl;
  2
  3import android.util.Base64;
  4import android.util.Log;
  5import eu.siacs.conversations.Config;
  6import eu.siacs.conversations.utils.Compatibility;
  7import eu.siacs.conversations.xml.Element;
  8import eu.siacs.conversations.xmpp.Jid;
  9import java.security.InvalidAlgorithmParameterException;
 10import java.security.InvalidKeyException;
 11import java.security.NoSuchAlgorithmException;
 12import java.security.NoSuchProviderException;
 13import java.security.SecureRandom;
 14import java.util.ArrayList;
 15import java.util.List;
 16import javax.crypto.BadPaddingException;
 17import javax.crypto.Cipher;
 18import javax.crypto.IllegalBlockSizeException;
 19import javax.crypto.KeyGenerator;
 20import javax.crypto.NoSuchPaddingException;
 21import javax.crypto.SecretKey;
 22import javax.crypto.spec.IvParameterSpec;
 23import javax.crypto.spec.SecretKeySpec;
 24
 25public class XmppAxolotlMessage {
 26    public static final String CONTAINERTAG = "encrypted";
 27    private static final String HEADER = "header";
 28    private static final String SOURCEID = "sid";
 29    private static final String KEYTAG = "key";
 30    private static final String REMOTEID = "rid";
 31    private static final String IVTAG = "iv";
 32    private static final String PAYLOAD = "payload";
 33
 34    private static final String KEYTYPE = "AES";
 35    private static final String CIPHERMODE = "AES/GCM/NoPadding";
 36    private static final String PROVIDER = "BC";
 37    private final List<XmppAxolotlSession.AxolotlKey> keys;
 38    private final Jid from;
 39    private final int sourceDeviceId;
 40    private byte[] innerKey;
 41    private byte[] ciphertext = null;
 42    private byte[] authtagPlusInnerKey = null;
 43    private byte[] iv = null;
 44
 45    private XmppAxolotlMessage(final Element axolotlMessage, final Jid from)
 46            throws IllegalArgumentException {
 47        this.from = from;
 48        Element header = axolotlMessage.findChild(HEADER);
 49        try {
 50            this.sourceDeviceId = Integer.parseInt(header.getAttribute(SOURCEID));
 51        } catch (NumberFormatException e) {
 52            throw new IllegalArgumentException("invalid source id");
 53        }
 54        List<Element> keyElements = header.getChildren();
 55        this.keys = new ArrayList<>();
 56        for (Element keyElement : keyElements) {
 57            switch (keyElement.getName()) {
 58                case KEYTAG:
 59                    try {
 60                        int recipientId = Integer.parseInt(keyElement.getAttribute(REMOTEID));
 61                        byte[] key = Base64.decode(keyElement.getContent().trim(), Base64.DEFAULT);
 62                        boolean isPreKey = keyElement.getAttributeAsBoolean("prekey");
 63                        this.keys.add(
 64                                new XmppAxolotlSession.AxolotlKey(recipientId, key, isPreKey));
 65                    } catch (NumberFormatException e) {
 66                        throw new IllegalArgumentException("invalid remote id");
 67                    }
 68                    break;
 69                case IVTAG:
 70                    if (this.iv != null) {
 71                        throw new IllegalArgumentException("Duplicate iv entry");
 72                    }
 73                    iv = Base64.decode(keyElement.getContent().trim(), Base64.DEFAULT);
 74                    break;
 75                default:
 76                    Log.w(Config.LOGTAG, "Unexpected element in header: " + keyElement);
 77                    break;
 78            }
 79        }
 80        final Element payloadElement =
 81                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        if (plaintext == null) return;
150
151        try {
152            SecretKey secretKey = new SecretKeySpec(innerKey, KEYTYPE);
153            IvParameterSpec ivSpec = new IvParameterSpec(iv);
154            Cipher cipher =
155                    Compatibility.twentyEight()
156                            ? Cipher.getInstance(CIPHERMODE)
157                            : Cipher.getInstance(CIPHERMODE, PROVIDER);
158            cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
159            this.ciphertext =
160                    cipher.doFinal(
161                            Config.OMEMO_PADDING
162                                    ? getPaddedBytes(plaintext)
163                                    : plaintext.getBytes());
164            if (Config.PUT_AUTH_TAG_INTO_KEY && this.ciphertext != null) {
165                this.authtagPlusInnerKey = new byte[16 + 16];
166                byte[] ciphertext = new byte[this.ciphertext.length - 16];
167                System.arraycopy(this.ciphertext, 0, ciphertext, 0, ciphertext.length);
168                System.arraycopy(this.ciphertext, ciphertext.length, authtagPlusInnerKey, 16, 16);
169                System.arraycopy(this.innerKey, 0, authtagPlusInnerKey, 0, this.innerKey.length);
170                this.ciphertext = ciphertext;
171            }
172        } catch (NoSuchAlgorithmException
173                | NoSuchPaddingException
174                | InvalidKeyException
175                | IllegalBlockSizeException
176                | BadPaddingException
177                | NoSuchProviderException
178                | InvalidAlgorithmParameterException e) {
179            throw new CryptoFailedException(e);
180        }
181    }
182
183    public Jid getFrom() {
184        return this.from;
185    }
186
187    int getSenderDeviceId() {
188        return sourceDeviceId;
189    }
190
191    void addDevice(XmppAxolotlSession session) {
192        addDevice(session, false);
193    }
194
195    void addDevice(XmppAxolotlSession session, boolean ignoreSessionTrust) {
196        XmppAxolotlSession.AxolotlKey key;
197        if (authtagPlusInnerKey != null) {
198            key = session.processSending(authtagPlusInnerKey, ignoreSessionTrust);
199        } else {
200            key = session.processSending(innerKey, ignoreSessionTrust);
201        }
202        if (key != null) {
203            keys.add(key);
204        }
205    }
206
207    public byte[] getInnerKey() {
208        return innerKey;
209    }
210
211    public byte[] getIV() {
212        return this.iv;
213    }
214
215    public Element toElement() {
216        Element encryptionElement = new Element(CONTAINERTAG, AxolotlService.PEP_PREFIX);
217        Element headerElement = encryptionElement.addChild(HEADER);
218        headerElement.setAttribute(SOURCEID, sourceDeviceId);
219        for (XmppAxolotlSession.AxolotlKey key : keys) {
220            Element keyElement = new Element(KEYTAG);
221            keyElement.setAttribute(REMOTEID, key.deviceId);
222            if (key.prekey) {
223                keyElement.setAttribute("prekey", "true");
224            }
225            keyElement.setContent(Base64.encodeToString(key.key, Base64.NO_WRAP));
226            headerElement.addChild(keyElement);
227        }
228        headerElement.addChild(IVTAG).setContent(Base64.encodeToString(iv, Base64.NO_WRAP));
229        if (ciphertext != null) {
230            Element payload = encryptionElement.addChild(PAYLOAD);
231            payload.setContent(Base64.encodeToString(ciphertext, Base64.NO_WRAP));
232        }
233        return encryptionElement;
234    }
235
236    private byte[] unpackKey(XmppAxolotlSession session, Integer sourceDeviceId)
237            throws CryptoFailedException {
238        ArrayList<XmppAxolotlSession.AxolotlKey> possibleKeys = new ArrayList<>();
239        for (XmppAxolotlSession.AxolotlKey key : keys) {
240            if (key.deviceId == sourceDeviceId) {
241                possibleKeys.add(key);
242            }
243        }
244        if (possibleKeys.size() == 0) {
245            throw new NotEncryptedForThisDeviceException();
246        }
247        return session.processReceiving(possibleKeys);
248    }
249
250    XmppAxolotlKeyTransportMessage getParameters(XmppAxolotlSession session, Integer sourceDeviceId)
251            throws CryptoFailedException {
252        return new XmppAxolotlKeyTransportMessage(
253                session.getFingerprint(), unpackKey(session, sourceDeviceId), getIV());
254    }
255
256    public XmppAxolotlPlaintextMessage decrypt(XmppAxolotlSession session, Integer sourceDeviceId)
257            throws CryptoFailedException {
258        XmppAxolotlPlaintextMessage plaintextMessage = null;
259        byte[] key = unpackKey(session, sourceDeviceId);
260        if (key != null) {
261            try {
262                if (key.length < 32) {
263                    throw new OutdatedSenderException(
264                            "Key did not contain auth tag. Sender needs to update their OMEMO"
265                                    + " client");
266                }
267                final int authTagLength = key.length - 16;
268                byte[] newCipherText = new byte[key.length - 16 + ciphertext.length];
269                byte[] newKey = new byte[16];
270                System.arraycopy(ciphertext, 0, newCipherText, 0, ciphertext.length);
271                System.arraycopy(key, 16, newCipherText, ciphertext.length, authTagLength);
272                System.arraycopy(key, 0, newKey, 0, newKey.length);
273                ciphertext = newCipherText;
274                key = newKey;
275
276                final Cipher cipher =
277                        Compatibility.twentyEight()
278                                ? Cipher.getInstance(CIPHERMODE)
279                                : Cipher.getInstance(CIPHERMODE, PROVIDER);
280                SecretKeySpec keySpec = new SecretKeySpec(key, KEYTYPE);
281                IvParameterSpec ivSpec = new IvParameterSpec(iv);
282
283                cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
284
285                String plaintext = new String(cipher.doFinal(ciphertext));
286                plaintextMessage =
287                        new XmppAxolotlPlaintextMessage(
288                                Config.OMEMO_PADDING ? plaintext.trim() : plaintext,
289                                session.getFingerprint());
290
291            } catch (NoSuchAlgorithmException
292                    | NoSuchPaddingException
293                    | InvalidKeyException
294                    | InvalidAlgorithmParameterException
295                    | IllegalBlockSizeException
296                    | BadPaddingException
297                    | NoSuchProviderException e) {
298                throw new CryptoFailedException(e);
299            }
300        }
301        return plaintextMessage;
302    }
303
304    public static class XmppAxolotlPlaintextMessage {
305        private final String plaintext;
306        private final String fingerprint;
307
308        XmppAxolotlPlaintextMessage(String plaintext, String fingerprint) {
309            this.plaintext = plaintext;
310            this.fingerprint = fingerprint;
311        }
312
313        public String getPlaintext() {
314            return plaintext;
315        }
316
317        public String getFingerprint() {
318            return fingerprint;
319        }
320    }
321
322    public static class XmppAxolotlKeyTransportMessage {
323        private final String fingerprint;
324        private final byte[] key;
325        private final byte[] iv;
326
327        XmppAxolotlKeyTransportMessage(String fingerprint, byte[] key, byte[] iv) {
328            this.fingerprint = fingerprint;
329            this.key = key;
330            this.iv = iv;
331        }
332
333        public String getFingerprint() {
334            return fingerprint;
335        }
336
337        public byte[] getKey() {
338            return key;
339        }
340
341        public byte[] getIv() {
342            return iv;
343        }
344    }
345}