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