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.utils.Xmlns;
 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		return Integer.valueOf(signedPreKeyPublic.getAttribute("signedPreKeyId"));
143	}
144
145	public ECPublicKey signedPreKeyPublic(final Element bundle) {
146		ECPublicKey publicKey = null;
147		final Element signedPreKeyPublic = bundle.findChild("signedPreKeyPublic");
148		if(signedPreKeyPublic == null) {
149			return null;
150		}
151		try {
152			publicKey = Curve.decodePoint(Base64.decode(signedPreKeyPublic.getContent(),Base64.DEFAULT), 0);
153		} catch (Throwable e) {
154			Log.e(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Invalid signedPreKeyPublic in PEP: " + e.getMessage());
155		}
156		return publicKey;
157	}
158
159	public byte[] signedPreKeySignature(final Element bundle) {
160		final Element signedPreKeySignature = bundle.findChild("signedPreKeySignature");
161		if(signedPreKeySignature == null) {
162			return null;
163		}
164		try {
165			return Base64.decode(signedPreKeySignature.getContent(), Base64.DEFAULT);
166		} catch (Throwable e) {
167			Log.e(Config.LOGTAG,AxolotlService.LOGPREFIX+" : Invalid base64 in signedPreKeySignature");
168			return null;
169		}
170	}
171
172	public IdentityKey identityKey(final Element bundle) {
173		IdentityKey identityKey = null;
174		final Element identityKeyElement = bundle.findChild("identityKey");
175		if(identityKeyElement == null) {
176			return null;
177		}
178		try {
179			identityKey = new IdentityKey(Base64.decode(identityKeyElement.getContent(), Base64.DEFAULT), 0);
180		} catch (Throwable e) {
181			Log.e(Config.LOGTAG,AxolotlService.LOGPREFIX+" : "+"Invalid identityKey in PEP: "+e.getMessage());
182		}
183		return identityKey;
184	}
185
186	public Map<Integer, ECPublicKey> preKeyPublics(final IqPacket packet) {
187		Map<Integer, ECPublicKey> preKeyRecords = new HashMap<>();
188		Element item = getItem(packet);
189		if (item == null) {
190			Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Couldn't find <item> in bundle IQ packet: " + packet);
191			return null;
192		}
193		final Element bundleElement = item.findChild("bundle");
194		if(bundleElement == null) {
195			return null;
196		}
197		final Element prekeysElement = bundleElement.findChild("prekeys");
198		if(prekeysElement == null) {
199			Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Couldn't find <prekeys> in bundle IQ packet: " + packet);
200			return null;
201		}
202		for(Element preKeyPublicElement : prekeysElement.getChildren()) {
203			if(!preKeyPublicElement.getName().equals("preKeyPublic")){
204				Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Encountered unexpected tag in prekeys list: " + preKeyPublicElement);
205				continue;
206			}
207			Integer preKeyId = Integer.valueOf(preKeyPublicElement.getAttribute("preKeyId"));
208			try {
209				ECPublicKey preKeyPublic = Curve.decodePoint(Base64.decode(preKeyPublicElement.getContent(), Base64.DEFAULT), 0);
210				preKeyRecords.put(preKeyId, preKeyPublic);
211			} catch (Throwable e) {
212				Log.e(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Invalid preKeyPublic (ID="+preKeyId+") in PEP: "+ e.getMessage()+", skipping...");
213				continue;
214			}
215		}
216		return preKeyRecords;
217	}
218
219	public Pair<X509Certificate[],byte[]> verification(final IqPacket packet) {
220		Element item = getItem(packet);
221		Element verification = item != null ? item.findChild("verification",AxolotlService.PEP_PREFIX) : null;
222		Element chain = verification != null ? verification.findChild("chain") : null;
223		Element signature = verification != null ? verification.findChild("signature") : null;
224		if (chain != null && signature != null) {
225			List<Element> certElements = chain.getChildren();
226			X509Certificate[] certificates = new X509Certificate[certElements.size()];
227			try {
228				CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
229				int i = 0;
230				for(Element cert : certElements) {
231					certificates[i] = (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(Base64.decode(cert.getContent(),Base64.DEFAULT)));
232					++i;
233				}
234				return new Pair<>(certificates,Base64.decode(signature.getContent(),Base64.DEFAULT));
235			} catch (CertificateException e) {
236				return null;
237			}
238		} else {
239			return null;
240		}
241	}
242
243	public PreKeyBundle bundle(final IqPacket bundle) {
244		Element bundleItem = getItem(bundle);
245		if(bundleItem == null) {
246			return null;
247		}
248		final Element bundleElement = bundleItem.findChild("bundle");
249		if(bundleElement == null) {
250			return null;
251		}
252		ECPublicKey signedPreKeyPublic = signedPreKeyPublic(bundleElement);
253		Integer signedPreKeyId = signedPreKeyId(bundleElement);
254		byte[] signedPreKeySignature = signedPreKeySignature(bundleElement);
255		IdentityKey identityKey = identityKey(bundleElement);
256		if(signedPreKeyPublic == null || identityKey == null) {
257			return null;
258		}
259
260		return new PreKeyBundle(0, 0, 0, null,
261				signedPreKeyId, signedPreKeyPublic, signedPreKeySignature, identityKey);
262	}
263
264	public List<PreKeyBundle> preKeys(final IqPacket preKeys) {
265		List<PreKeyBundle> bundles = new ArrayList<>();
266		Map<Integer, ECPublicKey> preKeyPublics = preKeyPublics(preKeys);
267		if ( preKeyPublics != null) {
268			for (Integer preKeyId : preKeyPublics.keySet()) {
269				ECPublicKey preKeyPublic = preKeyPublics.get(preKeyId);
270				bundles.add(new PreKeyBundle(0, 0, preKeyId, preKeyPublic,
271						0, null, null, null));
272			}
273		}
274
275		return bundles;
276	}
277
278	@Override
279	public void onIqPacketReceived(final Account account, final IqPacket packet) {
280		final boolean isGet = packet.getType() == IqPacket.TYPE.GET;
281		if (packet.getType() == IqPacket.TYPE.ERROR || packet.getType() == IqPacket.TYPE.TIMEOUT) {
282			return;
283		} else if (packet.hasChild("query", Xmlns.ROSTER) && packet.fromServer(account)) {
284			final Element query = packet.findChild("query");
285			// If this is in response to a query for the whole roster:
286			if (packet.getType() == IqPacket.TYPE.RESULT) {
287				account.getRoster().markAllAsNotInRoster();
288			}
289			this.rosterItems(account, query);
290		} else if ((packet.hasChild("block", Xmlns.BLOCKING) || packet.hasChild("blocklist", Xmlns.BLOCKING)) &&
291				packet.fromServer(account)) {
292			// Block list or block push.
293			Log.d(Config.LOGTAG, "Received blocklist update from server");
294			final Element blocklist = packet.findChild("blocklist", Xmlns.BLOCKING);
295			final Element block = packet.findChild("block", Xmlns.BLOCKING);
296			final Collection<Element> items = blocklist != null ? blocklist.getChildren() :
297				(block != null ? block.getChildren() : null);
298			// If this is a response to a blocklist query, clear the block list and replace with the new one.
299			// Otherwise, just update the existing blocklist.
300			if (packet.getType() == IqPacket.TYPE.RESULT) {
301				account.clearBlocklist();
302				account.getXmppConnection().getFeatures().setBlockListRequested(true);
303			}
304			if (items != null) {
305				final Collection<Jid> jids = new ArrayList<>(items.size());
306				// Create a collection of Jids from the packet
307				for (final Element item : items) {
308					if (item.getName().equals("item")) {
309						final Jid jid = item.getAttributeAsJid("jid");
310						if (jid != null) {
311							jids.add(jid);
312						}
313					}
314				}
315				account.getBlocklist().addAll(jids);
316			}
317			// Update the UI
318			mXmppConnectionService.updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
319			if (packet.getType() == IqPacket.TYPE.SET) {
320				final IqPacket response = packet.generateResponse(IqPacket.TYPE.RESULT);
321				mXmppConnectionService.sendIqPacket(account, response, null);
322			}
323		} else if (packet.hasChild("unblock", Xmlns.BLOCKING) &&
324				packet.fromServer(account) && packet.getType() == IqPacket.TYPE.SET) {
325			Log.d(Config.LOGTAG, "Received unblock update from server");
326			final Collection<Element> items = packet.findChild("unblock", Xmlns.BLOCKING).getChildren();
327			if (items.size() == 0) {
328				// No children to unblock == unblock all
329				account.getBlocklist().clear();
330			} else {
331				final Collection<Jid> jids = new ArrayList<>(items.size());
332				for (final Element item : items) {
333					if (item.getName().equals("item")) {
334						final Jid jid = item.getAttributeAsJid("jid");
335						if (jid != null) {
336							jids.add(jid);
337						}
338					}
339				}
340				account.getBlocklist().removeAll(jids);
341			}
342			mXmppConnectionService.updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
343			final IqPacket response = packet.generateResponse(IqPacket.TYPE.RESULT);
344			mXmppConnectionService.sendIqPacket(account, response, null);
345		} else if (packet.hasChild("open", "http://jabber.org/protocol/ibb")
346				|| packet.hasChild("data", "http://jabber.org/protocol/ibb")) {
347			mXmppConnectionService.getJingleConnectionManager()
348				.deliverIbbPacket(account, packet);
349		} else if (packet.hasChild("query", "http://jabber.org/protocol/disco#info")) {
350			final IqPacket response = mXmppConnectionService.getIqGenerator().discoResponse(packet);
351			mXmppConnectionService.sendIqPacket(account, response, null);
352		} else if (packet.hasChild("query","jabber:iq:version") && isGet) {
353			final IqPacket response = mXmppConnectionService.getIqGenerator().versionResponse(packet);
354			mXmppConnectionService.sendIqPacket(account,response,null);
355		} else if (packet.hasChild("ping", "urn:xmpp:ping") && isGet) {
356			final IqPacket response = packet.generateResponse(IqPacket.TYPE.RESULT);
357			mXmppConnectionService.sendIqPacket(account, response, null);
358		} else if (packet.hasChild("time","urn:xmpp:time") && isGet) {
359			final IqPacket response;
360			if (mXmppConnectionService.useTorToConnect()) {
361				response = packet.generateResponse(IqPacket.TYPE.ERROR);
362				final Element error = response.addChild("error");
363				error.setAttribute("type","cancel");
364				error.addChild("not-allowed","urn:ietf:params:xml:ns:xmpp-stanzas");
365			} else {
366				response = mXmppConnectionService.getIqGenerator().entityTimeResponse(packet);
367			}
368			mXmppConnectionService.sendIqPacket(account,response, null);
369		} else {
370			if (packet.getType() == IqPacket.TYPE.GET || packet.getType() == IqPacket.TYPE.SET) {
371				final IqPacket response = packet.generateResponse(IqPacket.TYPE.ERROR);
372				final Element error = response.addChild("error");
373				error.setAttribute("type", "cancel");
374				error.addChild("feature-not-implemented","urn:ietf:params:xml:ns:xmpp-stanzas");
375				account.getXmppConnection().sendIqPacket(response, null);
376			}
377		}
378	}
379
380}