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	public int getSenderDeviceId() {
222		return sourceDeviceId;
223	}
224
225	public void addDevice(XmppAxolotlSession session) {
226		XmppAxolotlSession.AxolotlKey key;
227		if (authtagPlusInnerKey != null) {
228			key = session.processSending(authtagPlusInnerKey);
229		} else {
230			key = session.processSending(innerKey);
231		}
232		if (key != null) {
233			keys.put(session.getRemoteAddress().getDeviceId(), key);
234		}
235	}
236
237	public byte[] getInnerKey() {
238		return innerKey;
239	}
240
241	public byte[] getIV() {
242		return this.iv;
243	}
244
245	public Element toElement() {
246		Element encryptionElement = new Element(CONTAINERTAG, AxolotlService.PEP_PREFIX);
247		Element headerElement = encryptionElement.addChild(HEADER);
248		headerElement.setAttribute(SOURCEID, sourceDeviceId);
249		for(int i = 0; i < keys.size(); ++i) {
250			Element keyElement = new Element(KEYTAG);
251			keyElement.setAttribute(REMOTEID, keys.keyAt(i));
252			if (keys.valueAt(i).prekey) {
253				keyElement.setAttribute("prekey","true");
254			}
255			keyElement.setContent(Base64.encodeToString(keys.valueAt(i).key, Base64.NO_WRAP));
256			headerElement.addChild(keyElement);
257		}
258		headerElement.addChild(IVTAG).setContent(Base64.encodeToString(iv, Base64.NO_WRAP));
259		if (ciphertext != null) {
260			Element payload = encryptionElement.addChild(PAYLOAD);
261			payload.setContent(Base64.encodeToString(ciphertext, Base64.NO_WRAP));
262		}
263		return encryptionElement;
264	}
265
266	private byte[] unpackKey(XmppAxolotlSession session, Integer sourceDeviceId) throws CryptoFailedException {
267		XmppAxolotlSession.AxolotlKey encryptedKey = keys.get(sourceDeviceId);
268		if (encryptedKey == null) {
269			throw new CryptoFailedException("Message was not encrypted for this device");
270		}
271		return session.processReceiving(encryptedKey);
272	}
273
274	public XmppAxolotlKeyTransportMessage getParameters(XmppAxolotlSession session, Integer sourceDeviceId) throws CryptoFailedException {
275		return new XmppAxolotlKeyTransportMessage(session.getFingerprint(), unpackKey(session, sourceDeviceId), getIV());
276	}
277
278	public XmppAxolotlPlaintextMessage decrypt(XmppAxolotlSession session, Integer sourceDeviceId) throws CryptoFailedException {
279		XmppAxolotlPlaintextMessage plaintextMessage = null;
280		byte[] key = unpackKey(session, sourceDeviceId);
281		if (key != null) {
282			try {
283				if (key.length >= 32) {
284					int authtaglength = key.length - 16;
285					Log.d(Config.LOGTAG,"found auth tag as part of omemo key");
286					byte[] newCipherText = new byte[key.length - 16  + ciphertext.length];
287					byte[] newKey = new byte[16];
288					System.arraycopy(ciphertext, 0, newCipherText, 0, ciphertext.length);
289					System.arraycopy(key, 16, newCipherText, ciphertext.length, authtaglength);
290					System.arraycopy(key,0,newKey,0,newKey.length);
291					ciphertext = newCipherText;
292					key = newKey;
293				}
294
295				Cipher cipher = Cipher.getInstance(CIPHERMODE, PROVIDER);
296				SecretKeySpec keySpec = new SecretKeySpec(key, KEYTYPE);
297				IvParameterSpec ivSpec = new IvParameterSpec(iv);
298
299				cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
300
301				String plaintext = new String(cipher.doFinal(ciphertext));
302				plaintextMessage = new XmppAxolotlPlaintextMessage(Config.OMEMO_PADDING ? plaintext.trim() : plaintext, session.getFingerprint());
303
304			} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
305					| InvalidAlgorithmParameterException | IllegalBlockSizeException
306					| BadPaddingException | NoSuchProviderException e) {
307				throw new CryptoFailedException(e);
308			}
309		}
310		return plaintextMessage;
311	}
312}