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