XmppAxolotlMessage.java

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