XmppAxolotlMessage.java

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