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