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 if (plaintext == null) return;
150
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}