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	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 SparseArray<>();
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 SparseArray<>();
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 boolean hasPayload() {
164		return ciphertext != null;
165	}
166
167	public void encrypt(String plaintext) throws CryptoFailedException {
168		try {
169			SecretKey secretKey = new SecretKeySpec(innerKey, KEYTYPE);
170			IvParameterSpec ivSpec = new IvParameterSpec(iv);
171			Cipher cipher = Cipher.getInstance(CIPHERMODE, PROVIDER);
172			cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
173			this.ciphertext = cipher.doFinal(Config.OMEMO_PADDING ? getPaddedBytes(plaintext) : plaintext.getBytes());
174			if (Config.PUT_AUTH_TAG_INTO_KEY && this.ciphertext != null) {
175				this.authtagPlusInnerKey = new byte[16+16];
176				byte[] ciphertext = new byte[this.ciphertext.length - 16];
177				System.arraycopy(this.ciphertext,0,ciphertext,0,ciphertext.length);
178				System.arraycopy(this.ciphertext,ciphertext.length,authtagPlusInnerKey,16,16);
179				System.arraycopy(this.innerKey,0,authtagPlusInnerKey,0,this.innerKey.length);
180				this.ciphertext = ciphertext;
181			}
182		} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
183				| IllegalBlockSizeException | BadPaddingException | NoSuchProviderException
184				| InvalidAlgorithmParameterException e) {
185			throw new CryptoFailedException(e);
186		}
187	}
188
189	private static byte[] getPaddedBytes(String plaintext) {
190		int plainLength = plaintext.getBytes().length;
191		int pad = Math.max(64,(plainLength / 32 + 1) * 32) - plainLength;
192		SecureRandom random = new SecureRandom();
193		int left = random.nextInt(pad);
194		int right = pad - left;
195		StringBuilder builder = new StringBuilder(plaintext);
196		for(int i = 0; i < left; ++i) {
197			builder.insert(0,random.nextBoolean() ? "\t" : " ");
198		}
199		for(int i = 0; i < right; ++i) {
200			builder.append(random.nextBoolean() ? "\t" : " ");
201		}
202		return builder.toString().getBytes();
203	}
204
205	public Jid getFrom() {
206		return this.from;
207	}
208
209	public int getSenderDeviceId() {
210		return sourceDeviceId;
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(int i = 0; i < keys.size(); ++i) {
238			Element keyElement = new Element(KEYTAG);
239			keyElement.setAttribute(REMOTEID, keys.keyAt(i));
240			if (keys.valueAt(i).prekey) {
241				keyElement.setAttribute("prekey","true");
242			}
243			keyElement.setContent(Base64.encodeToString(keys.valueAt(i).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) throws CryptoFailedException {
255		XmppAxolotlSession.AxolotlKey encryptedKey = keys.get(sourceDeviceId);
256		if (encryptedKey == null) {
257			throw new CryptoFailedException("Message was not encrypted for this device");
258		}
259		return session.processReceiving(encryptedKey);
260	}
261
262	public XmppAxolotlKeyTransportMessage getParameters(XmppAxolotlSession session, Integer sourceDeviceId) throws CryptoFailedException {
263		return new XmppAxolotlKeyTransportMessage(session.getFingerprint(), unpackKey(session, sourceDeviceId), getIV());
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				if (key.length >= 32) {
272					int authtaglength = key.length - 16;
273					Log.d(Config.LOGTAG,"found auth tag as part of omemo key");
274					byte[] newCipherText = new byte[key.length - 16  + ciphertext.length];
275					byte[] newKey = new byte[16];
276					System.arraycopy(ciphertext, 0, newCipherText, 0, ciphertext.length);
277					System.arraycopy(key, 16, newCipherText, ciphertext.length, authtaglength);
278					System.arraycopy(key,0,newKey,0,newKey.length);
279					ciphertext = newCipherText;
280					key = newKey;
281				}
282
283				Cipher cipher = Cipher.getInstance(CIPHERMODE, PROVIDER);
284				SecretKeySpec keySpec = new SecretKeySpec(key, KEYTYPE);
285				IvParameterSpec ivSpec = new IvParameterSpec(iv);
286
287				cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
288
289				String plaintext = new String(cipher.doFinal(ciphertext));
290				plaintextMessage = new XmppAxolotlPlaintextMessage(Config.OMEMO_PADDING ? plaintext.trim() : plaintext, session.getFingerprint());
291
292			} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
293					| InvalidAlgorithmParameterException | IllegalBlockSizeException
294					| BadPaddingException | NoSuchProviderException e) {
295				throw new CryptoFailedException(e);
296			}
297		}
298		return plaintextMessage;
299	}
300}