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        try {
150            SecretKey secretKey = new SecretKeySpec(innerKey, KEYTYPE);
151            IvParameterSpec ivSpec = new IvParameterSpec(iv);
152            Cipher cipher =
153                    Compatibility.twentyEight()
154                            ? Cipher.getInstance(CIPHERMODE)
155                            : Cipher.getInstance(CIPHERMODE, PROVIDER);
156            cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
157            this.ciphertext =
158                    cipher.doFinal(
159                            Config.OMEMO_PADDING
160                                    ? getPaddedBytes(plaintext)
161                                    : plaintext.getBytes());
162            if (Config.PUT_AUTH_TAG_INTO_KEY && this.ciphertext != null) {
163                this.authtagPlusInnerKey = new byte[16 + 16];
164                byte[] ciphertext = new byte[this.ciphertext.length - 16];
165                System.arraycopy(this.ciphertext, 0, ciphertext, 0, ciphertext.length);
166                System.arraycopy(this.ciphertext, ciphertext.length, authtagPlusInnerKey, 16, 16);
167                System.arraycopy(this.innerKey, 0, authtagPlusInnerKey, 0, this.innerKey.length);
168                this.ciphertext = ciphertext;
169            }
170        } catch (NoSuchAlgorithmException
171                | NoSuchPaddingException
172                | InvalidKeyException
173                | IllegalBlockSizeException
174                | BadPaddingException
175                | NoSuchProviderException
176                | InvalidAlgorithmParameterException e) {
177            throw new CryptoFailedException(e);
178        }
179    }
180
181    public Jid getFrom() {
182        return this.from;
183    }
184
185    int getSenderDeviceId() {
186        return sourceDeviceId;
187    }
188
189    void addDevice(XmppAxolotlSession session) {
190        addDevice(session, false);
191    }
192
193    void addDevice(XmppAxolotlSession session, boolean ignoreSessionTrust) {
194        XmppAxolotlSession.AxolotlKey key;
195        if (authtagPlusInnerKey != null) {
196            key = session.processSending(authtagPlusInnerKey, ignoreSessionTrust);
197        } else {
198            key = session.processSending(innerKey, ignoreSessionTrust);
199        }
200        if (key != null) {
201            keys.add(key);
202        }
203    }
204
205    public byte[] getInnerKey() {
206        return innerKey;
207    }
208
209    public byte[] getIV() {
210        return this.iv;
211    }
212
213    public Element toElement() {
214        Element encryptionElement = new Element(CONTAINERTAG, AxolotlService.PEP_PREFIX);
215        Element headerElement = encryptionElement.addChild(HEADER);
216        headerElement.setAttribute(SOURCEID, sourceDeviceId);
217        for (XmppAxolotlSession.AxolotlKey key : keys) {
218            Element keyElement = new Element(KEYTAG);
219            keyElement.setAttribute(REMOTEID, key.deviceId);
220            if (key.prekey) {
221                keyElement.setAttribute("prekey", "true");
222            }
223            keyElement.setContent(Base64.encodeToString(key.key, Base64.NO_WRAP));
224            headerElement.addChild(keyElement);
225        }
226        headerElement.addChild(IVTAG).setContent(Base64.encodeToString(iv, Base64.NO_WRAP));
227        if (ciphertext != null) {
228            Element payload = encryptionElement.addChild(PAYLOAD);
229            payload.setContent(Base64.encodeToString(ciphertext, Base64.NO_WRAP));
230        }
231        return encryptionElement;
232    }
233
234    private byte[] unpackKey(XmppAxolotlSession session, Integer sourceDeviceId)
235            throws CryptoFailedException {
236        ArrayList<XmppAxolotlSession.AxolotlKey> possibleKeys = new ArrayList<>();
237        for (XmppAxolotlSession.AxolotlKey key : keys) {
238            if (key.deviceId == sourceDeviceId) {
239                possibleKeys.add(key);
240            }
241        }
242        if (possibleKeys.size() == 0) {
243            throw new NotEncryptedForThisDeviceException();
244        }
245        return session.processReceiving(possibleKeys);
246    }
247
248    XmppAxolotlKeyTransportMessage getParameters(XmppAxolotlSession session, Integer sourceDeviceId)
249            throws CryptoFailedException {
250        return new XmppAxolotlKeyTransportMessage(
251                session.getFingerprint(), unpackKey(session, sourceDeviceId), getIV());
252    }
253
254    public XmppAxolotlPlaintextMessage decrypt(XmppAxolotlSession session, Integer sourceDeviceId)
255            throws CryptoFailedException {
256        XmppAxolotlPlaintextMessage plaintextMessage = null;
257        byte[] key = unpackKey(session, sourceDeviceId);
258        if (key != null) {
259            try {
260                if (key.length < 32) {
261                    throw new OutdatedSenderException(
262                            "Key did not contain auth tag. Sender needs to update their OMEMO"
263                                    + " client");
264                }
265                final int authTagLength = key.length - 16;
266                byte[] newCipherText = new byte[key.length - 16 + ciphertext.length];
267                byte[] newKey = new byte[16];
268                System.arraycopy(ciphertext, 0, newCipherText, 0, ciphertext.length);
269                System.arraycopy(key, 16, newCipherText, ciphertext.length, authTagLength);
270                System.arraycopy(key, 0, newKey, 0, newKey.length);
271                ciphertext = newCipherText;
272                key = newKey;
273
274                final Cipher cipher =
275                        Compatibility.twentyEight()
276                                ? Cipher.getInstance(CIPHERMODE)
277                                : Cipher.getInstance(CIPHERMODE, PROVIDER);
278                SecretKeySpec keySpec = new SecretKeySpec(key, KEYTYPE);
279                IvParameterSpec ivSpec = new IvParameterSpec(iv);
280
281                cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
282
283                String plaintext = new String(cipher.doFinal(ciphertext));
284                plaintextMessage =
285                        new XmppAxolotlPlaintextMessage(
286                                Config.OMEMO_PADDING ? plaintext.trim() : plaintext,
287                                session.getFingerprint());
288
289            } catch (NoSuchAlgorithmException
290                    | NoSuchPaddingException
291                    | InvalidKeyException
292                    | InvalidAlgorithmParameterException
293                    | IllegalBlockSizeException
294                    | BadPaddingException
295                    | NoSuchProviderException e) {
296                throw new CryptoFailedException(e);
297            }
298        }
299        return plaintextMessage;
300    }
301
302    public static class XmppAxolotlPlaintextMessage {
303        private final String plaintext;
304        private final String fingerprint;
305
306        XmppAxolotlPlaintextMessage(String plaintext, String fingerprint) {
307            this.plaintext = plaintext;
308            this.fingerprint = fingerprint;
309        }
310
311        public String getPlaintext() {
312            return plaintext;
313        }
314
315        public String getFingerprint() {
316            return fingerprint;
317        }
318    }
319
320    public static class XmppAxolotlKeyTransportMessage {
321        private final String fingerprint;
322        private final byte[] key;
323        private final byte[] iv;
324
325        XmppAxolotlKeyTransportMessage(String fingerprint, byte[] key, byte[] iv) {
326            this.fingerprint = fingerprint;
327            this.key = key;
328            this.iv = iv;
329        }
330
331        public String getFingerprint() {
332            return fingerprint;
333        }
334
335        public byte[] getKey() {
336            return key;
337        }
338
339        public byte[] getIv() {
340            return iv;
341        }
342    }
343}