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