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 throw new IllegalStateException(e);
119 }
120 }
121
122 private static byte[] generateIv() {
123 final SecureRandom random = new SecureRandom();
124 final byte[] iv = new byte[12];
125 random.nextBytes(iv);
126 return iv;
127 }
128
129 private static byte[] getPaddedBytes(String plaintext) {
130 int plainLength = plaintext.getBytes().length;
131 int pad = Math.max(64, (plainLength / 32 + 1) * 32) - plainLength;
132 SecureRandom random = new SecureRandom();
133 int left = random.nextInt(pad);
134 int right = pad - left;
135 StringBuilder builder = new StringBuilder(plaintext);
136 for (int i = 0; i < left; ++i) {
137 builder.insert(0, random.nextBoolean() ? "\t" : " ");
138 }
139 for (int i = 0; i < right; ++i) {
140 builder.append(random.nextBoolean() ? "\t" : " ");
141 }
142 return builder.toString().getBytes();
143 }
144
145 public boolean hasPayload() {
146 return ciphertext != null;
147 }
148
149 void encrypt(String plaintext) throws CryptoFailedException {
150 try {
151 SecretKey secretKey = new SecretKeySpec(innerKey, KEYTYPE);
152 IvParameterSpec ivSpec = new IvParameterSpec(iv);
153 Cipher cipher = Compatibility.twentyEight() ? Cipher.getInstance(CIPHERMODE) : Cipher.getInstance(CIPHERMODE, PROVIDER);
154 cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
155 this.ciphertext = cipher.doFinal(Config.OMEMO_PADDING ? getPaddedBytes(plaintext) : plaintext.getBytes());
156 if (Config.PUT_AUTH_TAG_INTO_KEY && this.ciphertext != null) {
157 this.authtagPlusInnerKey = new byte[16 + 16];
158 byte[] ciphertext = new byte[this.ciphertext.length - 16];
159 System.arraycopy(this.ciphertext, 0, ciphertext, 0, ciphertext.length);
160 System.arraycopy(this.ciphertext, ciphertext.length, authtagPlusInnerKey, 16, 16);
161 System.arraycopy(this.innerKey, 0, authtagPlusInnerKey, 0, this.innerKey.length);
162 this.ciphertext = ciphertext;
163 }
164 } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
165 | IllegalBlockSizeException | BadPaddingException | NoSuchProviderException
166 | InvalidAlgorithmParameterException e) {
167 throw new CryptoFailedException(e);
168 }
169 }
170
171 public Jid getFrom() {
172 return this.from;
173 }
174
175 int getSenderDeviceId() {
176 return sourceDeviceId;
177 }
178
179 void addDevice(XmppAxolotlSession session) {
180 addDevice(session, false);
181 }
182
183 void addDevice(XmppAxolotlSession session, boolean ignoreSessionTrust) {
184 XmppAxolotlSession.AxolotlKey key;
185 if (authtagPlusInnerKey != null) {
186 key = session.processSending(authtagPlusInnerKey, ignoreSessionTrust);
187 } else {
188 key = session.processSending(innerKey, ignoreSessionTrust);
189 }
190 if (key != null) {
191 keys.add(key);
192 }
193 }
194
195 public byte[] getInnerKey() {
196 return innerKey;
197 }
198
199 public byte[] getIV() {
200 return this.iv;
201 }
202
203 public Element toElement() {
204 Element encryptionElement = new Element(CONTAINERTAG, AxolotlService.PEP_PREFIX);
205 Element headerElement = encryptionElement.addChild(HEADER);
206 headerElement.setAttribute(SOURCEID, sourceDeviceId);
207 for (XmppAxolotlSession.AxolotlKey key : keys) {
208 Element keyElement = new Element(KEYTAG);
209 keyElement.setAttribute(REMOTEID, key.deviceId);
210 if (key.prekey) {
211 keyElement.setAttribute("prekey", "true");
212 }
213 keyElement.setContent(Base64.encodeToString(key.key, Base64.NO_WRAP));
214 headerElement.addChild(keyElement);
215 }
216 headerElement.addChild(IVTAG).setContent(Base64.encodeToString(iv, Base64.NO_WRAP));
217 if (ciphertext != null) {
218 Element payload = encryptionElement.addChild(PAYLOAD);
219 payload.setContent(Base64.encodeToString(ciphertext, Base64.NO_WRAP));
220 }
221 return encryptionElement;
222 }
223
224 private byte[] unpackKey(XmppAxolotlSession session, Integer sourceDeviceId) throws CryptoFailedException {
225 ArrayList<XmppAxolotlSession.AxolotlKey> possibleKeys = new ArrayList<>();
226 for (XmppAxolotlSession.AxolotlKey key : keys) {
227 if (key.deviceId == sourceDeviceId) {
228 possibleKeys.add(key);
229 }
230 }
231 if (possibleKeys.size() == 0) {
232 throw new NotEncryptedForThisDeviceException();
233 }
234 return session.processReceiving(possibleKeys);
235 }
236
237 XmppAxolotlKeyTransportMessage getParameters(XmppAxolotlSession session, Integer sourceDeviceId) throws CryptoFailedException {
238 return new XmppAxolotlKeyTransportMessage(session.getFingerprint(), unpackKey(session, sourceDeviceId), getIV());
239 }
240
241 public XmppAxolotlPlaintextMessage decrypt(XmppAxolotlSession session, Integer sourceDeviceId) throws CryptoFailedException {
242 XmppAxolotlPlaintextMessage plaintextMessage = null;
243 byte[] key = unpackKey(session, sourceDeviceId);
244 if (key != null) {
245 try {
246 if (key.length < 32) {
247 throw new OutdatedSenderException("Key did not contain auth tag. Sender needs to update their OMEMO client");
248 }
249 final int authTagLength = key.length - 16;
250 byte[] newCipherText = new byte[key.length - 16 + ciphertext.length];
251 byte[] newKey = new byte[16];
252 System.arraycopy(ciphertext, 0, newCipherText, 0, ciphertext.length);
253 System.arraycopy(key, 16, newCipherText, ciphertext.length, authTagLength);
254 System.arraycopy(key, 0, newKey, 0, newKey.length);
255 ciphertext = newCipherText;
256 key = newKey;
257
258 final Cipher cipher = Compatibility.twentyEight() ? Cipher.getInstance(CIPHERMODE) : Cipher.getInstance(CIPHERMODE, PROVIDER);
259 SecretKeySpec keySpec = new SecretKeySpec(key, KEYTYPE);
260 IvParameterSpec ivSpec = new IvParameterSpec(iv);
261
262 cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
263
264 String plaintext = new String(cipher.doFinal(ciphertext));
265 plaintextMessage = new XmppAxolotlPlaintextMessage(Config.OMEMO_PADDING ? plaintext.trim() : plaintext, session.getFingerprint());
266
267 } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
268 | InvalidAlgorithmParameterException | IllegalBlockSizeException
269 | BadPaddingException | NoSuchProviderException e) {
270 throw new CryptoFailedException(e);
271 }
272 }
273 return plaintextMessage;
274 }
275
276 public static class XmppAxolotlPlaintextMessage {
277 private final String plaintext;
278 private final String fingerprint;
279
280 XmppAxolotlPlaintextMessage(String plaintext, String fingerprint) {
281 this.plaintext = plaintext;
282 this.fingerprint = fingerprint;
283 }
284
285 public String getPlaintext() {
286 return plaintext;
287 }
288
289
290 public String getFingerprint() {
291 return fingerprint;
292 }
293 }
294
295 public static class XmppAxolotlKeyTransportMessage {
296 private final String fingerprint;
297 private final byte[] key;
298 private final byte[] iv;
299
300 XmppAxolotlKeyTransportMessage(String fingerprint, byte[] key, byte[] iv) {
301 this.fingerprint = fingerprint;
302 this.key = key;
303 this.iv = iv;
304 }
305
306 public String getFingerprint() {
307 return fingerprint;
308 }
309
310 public byte[] getKey() {
311 return key;
312 }
313
314 public byte[] getIv() {
315 return iv;
316 }
317 }
318}