IqParser.java

  1package eu.siacs.conversations.parser;
  2
  3import android.support.annotation.NonNull;
  4import android.util.Base64;
  5import android.util.Log;
  6import android.util.Pair;
  7
  8import org.whispersystems.libaxolotl.IdentityKey;
  9import org.whispersystems.libaxolotl.ecc.Curve;
 10import org.whispersystems.libaxolotl.ecc.ECPublicKey;
 11import org.whispersystems.libaxolotl.state.PreKeyBundle;
 12
 13import java.io.ByteArrayInputStream;
 14import java.security.cert.CertificateException;
 15import java.security.cert.CertificateFactory;
 16import java.security.cert.X509Certificate;
 17import java.util.ArrayList;
 18import java.util.Collection;
 19import java.util.HashMap;
 20import java.util.HashSet;
 21import java.util.List;
 22import java.util.Map;
 23import java.util.Set;
 24
 25import eu.siacs.conversations.Config;
 26import eu.siacs.conversations.crypto.axolotl.AxolotlService;
 27import eu.siacs.conversations.entities.Account;
 28import eu.siacs.conversations.entities.Contact;
 29import eu.siacs.conversations.services.XmppConnectionService;
 30import eu.siacs.conversations.xml.Namespace;
 31import eu.siacs.conversations.xml.Element;
 32import eu.siacs.conversations.xmpp.OnIqPacketReceived;
 33import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 34import eu.siacs.conversations.xmpp.jid.Jid;
 35import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 36
 37public class IqParser extends AbstractParser implements OnIqPacketReceived {
 38
 39	public IqParser(final XmppConnectionService service) {
 40		super(service);
 41	}
 42
 43	private void rosterItems(final Account account, final Element query) {
 44		final String version = query.getAttribute("ver");
 45		if (version != null) {
 46			account.getRoster().setVersion(version);
 47		}
 48		for (final Element item : query.getChildren()) {
 49			if (item.getName().equals("item")) {
 50				final Jid jid = item.getAttributeAsJid("jid");
 51				if (jid == null) {
 52					continue;
 53				}
 54				final String name = item.getAttribute("name");
 55				final String subscription = item.getAttribute("subscription");
 56				final Contact contact = account.getRoster().getContact(jid);
 57				boolean bothPre = contact.getOption(Contact.Options.TO) && contact.getOption(Contact.Options.FROM);
 58				if (!contact.getOption(Contact.Options.DIRTY_PUSH)) {
 59					contact.setServerName(name);
 60					contact.parseGroupsFromElement(item);
 61				}
 62				if (subscription != null) {
 63					if (subscription.equals("remove")) {
 64						contact.resetOption(Contact.Options.IN_ROSTER);
 65						contact.resetOption(Contact.Options.DIRTY_DELETE);
 66						contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
 67					} else {
 68						contact.setOption(Contact.Options.IN_ROSTER);
 69						contact.resetOption(Contact.Options.DIRTY_PUSH);
 70						contact.parseSubscriptionFromElement(item);
 71					}
 72				}
 73				boolean both = contact.getOption(Contact.Options.TO) && contact.getOption(Contact.Options.FROM);
 74				if ((both != bothPre) && both) {
 75					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": gained mutual presence subscription with "+contact.getJid());
 76					AxolotlService axolotlService = account.getAxolotlService();
 77					if (axolotlService != null) {
 78						axolotlService.clearErrorsInFetchStatusMap(contact.getJid());
 79					}
 80				}
 81				mXmppConnectionService.getAvatarService().clear(contact);
 82			}
 83		}
 84		mXmppConnectionService.updateConversationUi();
 85		mXmppConnectionService.updateRosterUi();
 86	}
 87
 88	public String avatarData(final IqPacket packet) {
 89		final Element pubsub = packet.findChild("pubsub",
 90				"http://jabber.org/protocol/pubsub");
 91		if (pubsub == null) {
 92			return null;
 93		}
 94		final Element items = pubsub.findChild("items");
 95		if (items == null) {
 96			return null;
 97		}
 98		return super.avatarData(items);
 99	}
100
101	public Element getItem(final IqPacket packet) {
102		final Element pubsub = packet.findChild("pubsub",
103				"http://jabber.org/protocol/pubsub");
104		if (pubsub == null) {
105			return null;
106		}
107		final Element items = pubsub.findChild("items");
108		if (items == null) {
109			return null;
110		}
111		return items.findChild("item");
112	}
113
114	@NonNull
115	public Set<Integer> deviceIds(final Element item) {
116		Set<Integer> deviceIds = new HashSet<>();
117		if (item != null) {
118			final Element list = item.findChild("list");
119			if (list != null) {
120				for (Element device : list.getChildren()) {
121					if (!device.getName().equals("device")) {
122						continue;
123					}
124					try {
125						Integer id = Integer.valueOf(device.getAttribute("id"));
126						deviceIds.add(id);
127					} catch (NumberFormatException e) {
128						Log.e(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Encountered invalid <device> node in PEP ("+e.getMessage()+"):" + device.toString()+ ", skipping...");
129						continue;
130					}
131				}
132			}
133		}
134		return deviceIds;
135	}
136
137	public Integer signedPreKeyId(final Element bundle) {
138		final Element signedPreKeyPublic = bundle.findChild("signedPreKeyPublic");
139		if(signedPreKeyPublic == null) {
140			return null;
141		}
142		try {
143			return Integer.valueOf(signedPreKeyPublic.getAttribute("signedPreKeyId"));
144		} catch (NumberFormatException e) {
145			return null;
146		}
147	}
148
149	public ECPublicKey signedPreKeyPublic(final Element bundle) {
150		ECPublicKey publicKey = null;
151		final Element signedPreKeyPublic = bundle.findChild("signedPreKeyPublic");
152		if(signedPreKeyPublic == null) {
153			return null;
154		}
155		try {
156			publicKey = Curve.decodePoint(Base64.decode(signedPreKeyPublic.getContent(),Base64.DEFAULT), 0);
157		} catch (Throwable e) {
158			Log.e(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Invalid signedPreKeyPublic in PEP: " + e.getMessage());
159		}
160		return publicKey;
161	}
162
163	public byte[] signedPreKeySignature(final Element bundle) {
164		final Element signedPreKeySignature = bundle.findChild("signedPreKeySignature");
165		if(signedPreKeySignature == null) {
166			return null;
167		}
168		try {
169			return Base64.decode(signedPreKeySignature.getContent(), Base64.DEFAULT);
170		} catch (Throwable e) {
171			Log.e(Config.LOGTAG,AxolotlService.LOGPREFIX+" : Invalid base64 in signedPreKeySignature");
172			return null;
173		}
174	}
175
176	public IdentityKey identityKey(final Element bundle) {
177		IdentityKey identityKey = null;
178		final Element identityKeyElement = bundle.findChild("identityKey");
179		if(identityKeyElement == null) {
180			return null;
181		}
182		try {
183			identityKey = new IdentityKey(Base64.decode(identityKeyElement.getContent(), Base64.DEFAULT), 0);
184		} catch (Throwable e) {
185			Log.e(Config.LOGTAG,AxolotlService.LOGPREFIX+" : "+"Invalid identityKey in PEP: "+e.getMessage());
186		}
187		return identityKey;
188	}
189
190	public Map<Integer, ECPublicKey> preKeyPublics(final IqPacket packet) {
191		Map<Integer, ECPublicKey> preKeyRecords = new HashMap<>();
192		Element item = getItem(packet);
193		if (item == null) {
194			Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Couldn't find <item> in bundle IQ packet: " + packet);
195			return null;
196		}
197		final Element bundleElement = item.findChild("bundle");
198		if(bundleElement == null) {
199			return null;
200		}
201		final Element prekeysElement = bundleElement.findChild("prekeys");
202		if(prekeysElement == null) {
203			Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Couldn't find <prekeys> in bundle IQ packet: " + packet);
204			return null;
205		}
206		for(Element preKeyPublicElement : prekeysElement.getChildren()) {
207			if(!preKeyPublicElement.getName().equals("preKeyPublic")){
208				Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Encountered unexpected tag in prekeys list: " + preKeyPublicElement);
209				continue;
210			}
211			Integer preKeyId = null;
212			try {
213				preKeyId = Integer.valueOf(preKeyPublicElement.getAttribute("preKeyId"));
214				final ECPublicKey preKeyPublic = Curve.decodePoint(Base64.decode(preKeyPublicElement.getContent(), Base64.DEFAULT), 0);
215				preKeyRecords.put(preKeyId, preKeyPublic);
216			} catch (NumberFormatException e) {
217				Log.e(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"could not parse preKeyId from preKey "+preKeyPublicElement.toString());
218			} catch (Throwable e) {
219				Log.e(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Invalid preKeyPublic (ID="+preKeyId+") in PEP: "+ e.getMessage()+", skipping...");
220			}
221		}
222		return preKeyRecords;
223	}
224
225	public Pair<X509Certificate[],byte[]> verification(final IqPacket packet) {
226		Element item = getItem(packet);
227		Element verification = item != null ? item.findChild("verification",AxolotlService.PEP_PREFIX) : null;
228		Element chain = verification != null ? verification.findChild("chain") : null;
229		Element signature = verification != null ? verification.findChild("signature") : null;
230		if (chain != null && signature != null) {
231			List<Element> certElements = chain.getChildren();
232			X509Certificate[] certificates = new X509Certificate[certElements.size()];
233			try {
234				CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
235				int i = 0;
236				for(Element cert : certElements) {
237					certificates[i] = (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(Base64.decode(cert.getContent(),Base64.DEFAULT)));
238					++i;
239				}
240				return new Pair<>(certificates,Base64.decode(signature.getContent(),Base64.DEFAULT));
241			} catch (CertificateException e) {
242				return null;
243			}
244		} else {
245			return null;
246		}
247	}
248
249	public PreKeyBundle bundle(final IqPacket bundle) {
250		Element bundleItem = getItem(bundle);
251		if(bundleItem == null) {
252			return null;
253		}
254		final Element bundleElement = bundleItem.findChild("bundle");
255		if(bundleElement == null) {
256			return null;
257		}
258		ECPublicKey signedPreKeyPublic = signedPreKeyPublic(bundleElement);
259		Integer signedPreKeyId = signedPreKeyId(bundleElement);
260		byte[] signedPreKeySignature = signedPreKeySignature(bundleElement);
261		IdentityKey identityKey = identityKey(bundleElement);
262		if(signedPreKeyId == null || signedPreKeyPublic == null || identityKey == null) {
263			return null;
264		}
265
266		return new PreKeyBundle(0, 0, 0, null,
267				signedPreKeyId, signedPreKeyPublic, signedPreKeySignature, identityKey);
268	}
269
270	public List<PreKeyBundle> preKeys(final IqPacket preKeys) {
271		List<PreKeyBundle> bundles = new ArrayList<>();
272		Map<Integer, ECPublicKey> preKeyPublics = preKeyPublics(preKeys);
273		if ( preKeyPublics != null) {
274			for (Integer preKeyId : preKeyPublics.keySet()) {
275				ECPublicKey preKeyPublic = preKeyPublics.get(preKeyId);
276				bundles.add(new PreKeyBundle(0, 0, preKeyId, preKeyPublic,
277						0, null, null, null));
278			}
279		}
280
281		return bundles;
282	}
283
284	@Override
285	public void onIqPacketReceived(final Account account, final IqPacket packet) {
286		final boolean isGet = packet.getType() == IqPacket.TYPE.GET;
287		if (packet.getType() == IqPacket.TYPE.ERROR || packet.getType() == IqPacket.TYPE.TIMEOUT) {
288			return;
289		} else if (packet.hasChild("query", Namespace.ROSTER) && packet.fromServer(account)) {
290			final Element query = packet.findChild("query");
291			// If this is in response to a query for the whole roster:
292			if (packet.getType() == IqPacket.TYPE.RESULT) {
293				account.getRoster().markAllAsNotInRoster();
294			}
295			this.rosterItems(account, query);
296		} else if ((packet.hasChild("block", Namespace.BLOCKING) || packet.hasChild("blocklist", Namespace.BLOCKING)) &&
297				packet.fromServer(account)) {
298			// Block list or block push.
299			Log.d(Config.LOGTAG, "Received blocklist update from server");
300			final Element blocklist = packet.findChild("blocklist", Namespace.BLOCKING);
301			final Element block = packet.findChild("block", Namespace.BLOCKING);
302			final Collection<Element> items = blocklist != null ? blocklist.getChildren() :
303				(block != null ? block.getChildren() : null);
304			// If this is a response to a blocklist query, clear the block list and replace with the new one.
305			// Otherwise, just update the existing blocklist.
306			if (packet.getType() == IqPacket.TYPE.RESULT) {
307				account.clearBlocklist();
308				account.getXmppConnection().getFeatures().setBlockListRequested(true);
309			}
310			if (items != null) {
311				final Collection<Jid> jids = new ArrayList<>(items.size());
312				// Create a collection of Jids from the packet
313				for (final Element item : items) {
314					if (item.getName().equals("item")) {
315						final Jid jid = item.getAttributeAsJid("jid");
316						if (jid != null) {
317							jids.add(jid);
318						}
319					}
320				}
321				account.getBlocklist().addAll(jids);
322				if (packet.getType() == IqPacket.TYPE.SET) {
323					boolean removed = false;
324					for(Jid jid : jids) {
325						removed |= mXmppConnectionService.removeBlockedConversations(account,jid);
326					}
327					if (removed) {
328						mXmppConnectionService.updateConversationUi();
329					}
330				}
331			}
332			// Update the UI
333			mXmppConnectionService.updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
334			if (packet.getType() == IqPacket.TYPE.SET) {
335				final IqPacket response = packet.generateResponse(IqPacket.TYPE.RESULT);
336				mXmppConnectionService.sendIqPacket(account, response, null);
337			}
338		} else if (packet.hasChild("unblock", Namespace.BLOCKING) &&
339				packet.fromServer(account) && packet.getType() == IqPacket.TYPE.SET) {
340			Log.d(Config.LOGTAG, "Received unblock update from server");
341			final Collection<Element> items = packet.findChild("unblock", Namespace.BLOCKING).getChildren();
342			if (items.size() == 0) {
343				// No children to unblock == unblock all
344				account.getBlocklist().clear();
345			} else {
346				final Collection<Jid> jids = new ArrayList<>(items.size());
347				for (final Element item : items) {
348					if (item.getName().equals("item")) {
349						final Jid jid = item.getAttributeAsJid("jid");
350						if (jid != null) {
351							jids.add(jid);
352						}
353					}
354				}
355				account.getBlocklist().removeAll(jids);
356			}
357			mXmppConnectionService.updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
358			final IqPacket response = packet.generateResponse(IqPacket.TYPE.RESULT);
359			mXmppConnectionService.sendIqPacket(account, response, null);
360		} else if (packet.hasChild("open", "http://jabber.org/protocol/ibb")
361				|| packet.hasChild("data", "http://jabber.org/protocol/ibb")
362				|| packet.hasChild("close","http://jabber.org/protocol/ibb")) {
363			mXmppConnectionService.getJingleConnectionManager()
364				.deliverIbbPacket(account, packet);
365		} else if (packet.hasChild("query", "http://jabber.org/protocol/disco#info")) {
366			final IqPacket response = mXmppConnectionService.getIqGenerator().discoResponse(packet);
367			mXmppConnectionService.sendIqPacket(account, response, null);
368		} else if (packet.hasChild("query","jabber:iq:version") && isGet) {
369			final IqPacket response = mXmppConnectionService.getIqGenerator().versionResponse(packet);
370			mXmppConnectionService.sendIqPacket(account,response,null);
371		} else if (packet.hasChild("ping", "urn:xmpp:ping") && isGet) {
372			final IqPacket response = packet.generateResponse(IqPacket.TYPE.RESULT);
373			mXmppConnectionService.sendIqPacket(account, response, null);
374		} else if (packet.hasChild("time","urn:xmpp:time") && isGet) {
375			final IqPacket response;
376			if (mXmppConnectionService.useTorToConnect()) {
377				response = packet.generateResponse(IqPacket.TYPE.ERROR);
378				final Element error = response.addChild("error");
379				error.setAttribute("type","cancel");
380				error.addChild("not-allowed","urn:ietf:params:xml:ns:xmpp-stanzas");
381			} else {
382				response = mXmppConnectionService.getIqGenerator().entityTimeResponse(packet);
383			}
384			mXmppConnectionService.sendIqPacket(account,response, null);
385		} else {
386			if (packet.getType() == IqPacket.TYPE.GET || packet.getType() == IqPacket.TYPE.SET) {
387				final IqPacket response = packet.generateResponse(IqPacket.TYPE.ERROR);
388				final Element error = response.addChild("error");
389				error.setAttribute("type", "cancel");
390				error.addChild("feature-not-implemented","urn:ietf:params:xml:ns:xmpp-stanzas");
391				account.getXmppConnection().sendIqPacket(response, null);
392			}
393		}
394	}
395
396}