1package eu.siacs.conversations.crypto.axolotl;
2
3import android.util.Base64;
4import android.util.Log;
5
6import org.whispersystems.libaxolotl.protocol.CiphertextMessage;
7
8import java.security.InvalidAlgorithmParameterException;
9import java.security.InvalidKeyException;
10import java.security.NoSuchAlgorithmException;
11import java.security.NoSuchProviderException;
12import java.security.SecureRandom;
13import java.util.HashMap;
14import java.util.List;
15import java.util.Map;
16
17import javax.crypto.BadPaddingException;
18import javax.crypto.Cipher;
19import javax.crypto.IllegalBlockSizeException;
20import javax.crypto.KeyGenerator;
21import javax.crypto.NoSuchPaddingException;
22import javax.crypto.SecretKey;
23import javax.crypto.spec.IvParameterSpec;
24import javax.crypto.spec.SecretKeySpec;
25
26import eu.siacs.conversations.Config;
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[] 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 } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
170 | IllegalBlockSizeException | BadPaddingException | NoSuchProviderException
171 | InvalidAlgorithmParameterException e) {
172 throw new CryptoFailedException(e);
173 }
174 }
175
176 private static byte[] getPaddedBytes(String plaintext) {
177 int plainLength = plaintext.getBytes().length;
178 int pad = Math.max(64,(plainLength / 32 + 1) * 32) - plainLength;
179 SecureRandom random = new SecureRandom();
180 int left = random.nextInt(pad);
181 int right = pad - left;
182 StringBuilder builder = new StringBuilder(plaintext);
183 for(int i = 0; i < left; ++i) {
184 builder.insert(0,random.nextBoolean() ? "\t" : " ");
185 }
186 for(int i = 0; i < right; ++i) {
187 builder.append(random.nextBoolean() ? "\t" : " ");
188 }
189 return builder.toString().getBytes();
190 }
191
192 public Jid getFrom() {
193 return this.from;
194 }
195
196 public int getSenderDeviceId() {
197 return sourceDeviceId;
198 }
199
200 public byte[] getCiphertext() {
201 return ciphertext;
202 }
203
204 public void addDevice(XmppAxolotlSession session) {
205 XmppAxolotlSession.AxolotlKey key = session.processSending(innerKey);
206 if (key != null) {
207 keys.put(session.getRemoteAddress().getDeviceId(), key);
208 }
209 }
210
211 public byte[] getInnerKey() {
212 return innerKey;
213 }
214
215 public byte[] getIV() {
216 return this.iv;
217 }
218
219 public Element toElement() {
220 Element encryptionElement = new Element(CONTAINERTAG, AxolotlService.PEP_PREFIX);
221 Element headerElement = encryptionElement.addChild(HEADER);
222 headerElement.setAttribute(SOURCEID, sourceDeviceId);
223 for (Map.Entry<Integer, XmppAxolotlSession.AxolotlKey> keyEntry : keys.entrySet()) {
224 Element keyElement = new Element(KEYTAG);
225 keyElement.setAttribute(REMOTEID, keyEntry.getKey());
226 if (keyEntry.getValue().prekey) {
227 keyElement.setAttribute("prekey","true");
228 }
229 keyElement.setContent(Base64.encodeToString(keyEntry.getValue().key, Base64.NO_WRAP));
230 headerElement.addChild(keyElement);
231 }
232 headerElement.addChild(IVTAG).setContent(Base64.encodeToString(iv, Base64.NO_WRAP));
233 if (ciphertext != null) {
234 Element payload = encryptionElement.addChild(PAYLOAD);
235 payload.setContent(Base64.encodeToString(ciphertext, Base64.NO_WRAP));
236 }
237 return encryptionElement;
238 }
239
240 private byte[] unpackKey(XmppAxolotlSession session, Integer sourceDeviceId) {
241 XmppAxolotlSession.AxolotlKey encryptedKey = keys.get(sourceDeviceId);
242 return (encryptedKey != null) ? session.processReceiving(encryptedKey) : null;
243 }
244
245 public XmppAxolotlKeyTransportMessage getParameters(XmppAxolotlSession session, Integer sourceDeviceId) {
246 byte[] key = unpackKey(session, sourceDeviceId);
247 return (key != null)
248 ? new XmppAxolotlKeyTransportMessage(session.getFingerprint(), key, getIV())
249 : null;
250 }
251
252 public XmppAxolotlPlaintextMessage decrypt(XmppAxolotlSession session, Integer sourceDeviceId) throws CryptoFailedException {
253 XmppAxolotlPlaintextMessage plaintextMessage = null;
254 byte[] key = unpackKey(session, sourceDeviceId);
255 if (key != null) {
256 try {
257 Cipher cipher = Cipher.getInstance(CIPHERMODE, PROVIDER);
258 SecretKeySpec keySpec = new SecretKeySpec(key, KEYTYPE);
259 IvParameterSpec ivSpec = new IvParameterSpec(iv);
260
261 cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
262
263 String plaintext = new String(cipher.doFinal(ciphertext));
264 plaintextMessage = new XmppAxolotlPlaintextMessage(Config.OMEMO_PADDING ? plaintext.trim() : plaintext, session.getFingerprint());
265
266 } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
267 | InvalidAlgorithmParameterException | IllegalBlockSizeException
268 | BadPaddingException | NoSuchProviderException e) {
269 throw new CryptoFailedException(e);
270 }
271 }
272 return plaintextMessage;
273 }
274}