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				if (!contact.getOption(Contact.Options.DIRTY_PUSH)) {
 58					contact.setServerName(name);
 59					contact.parseGroupsFromElement(item);
 60				}
 61				if (subscription != null) {
 62					if (subscription.equals("remove")) {
 63						contact.resetOption(Contact.Options.IN_ROSTER);
 64						contact.resetOption(Contact.Options.DIRTY_DELETE);
 65						contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
 66					} else {
 67						contact.setOption(Contact.Options.IN_ROSTER);
 68						contact.resetOption(Contact.Options.DIRTY_PUSH);
 69						contact.parseSubscriptionFromElement(item);
 70					}
 71				}
 72				mXmppConnectionService.getAvatarService().clear(contact);
 73			}
 74		}
 75		mXmppConnectionService.updateConversationUi();
 76		mXmppConnectionService.updateRosterUi();
 77	}
 78
 79	public String avatarData(final IqPacket packet) {
 80		final Element pubsub = packet.findChild("pubsub",
 81				"http://jabber.org/protocol/pubsub");
 82		if (pubsub == null) {
 83			return null;
 84		}
 85		final Element items = pubsub.findChild("items");
 86		if (items == null) {
 87			return null;
 88		}
 89		return super.avatarData(items);
 90	}
 91
 92	public Element getItem(final IqPacket packet) {
 93		final Element pubsub = packet.findChild("pubsub",
 94				"http://jabber.org/protocol/pubsub");
 95		if (pubsub == null) {
 96			return null;
 97		}
 98		final Element items = pubsub.findChild("items");
 99		if (items == null) {
100			return null;
101		}
102		return items.findChild("item");
103	}
104
105	@NonNull
106	public Set<Integer> deviceIds(final Element item) {
107		Set<Integer> deviceIds = new HashSet<>();
108		if (item != null) {
109			final Element list = item.findChild("list");
110			if (list != null) {
111				for (Element device : list.getChildren()) {
112					if (!device.getName().equals("device")) {
113						continue;
114					}
115					try {
116						Integer id = Integer.valueOf(device.getAttribute("id"));
117						deviceIds.add(id);
118					} catch (NumberFormatException e) {
119						Log.e(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Encountered invalid <device> node in PEP ("+e.getMessage()+"):" + device.toString()+ ", skipping...");
120						continue;
121					}
122				}
123			}
124		}
125		return deviceIds;
126	}
127
128	public Integer signedPreKeyId(final Element bundle) {
129		final Element signedPreKeyPublic = bundle.findChild("signedPreKeyPublic");
130		if(signedPreKeyPublic == null) {
131			return null;
132		}
133		return Integer.valueOf(signedPreKeyPublic.getAttribute("signedPreKeyId"));
134	}
135
136	public ECPublicKey signedPreKeyPublic(final Element bundle) {
137		ECPublicKey publicKey = null;
138		final Element signedPreKeyPublic = bundle.findChild("signedPreKeyPublic");
139		if(signedPreKeyPublic == null) {
140			return null;
141		}
142		try {
143			publicKey = Curve.decodePoint(Base64.decode(signedPreKeyPublic.getContent(),Base64.DEFAULT), 0);
144		} catch (Throwable e) {
145			Log.e(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Invalid signedPreKeyPublic in PEP: " + e.getMessage());
146		}
147		return publicKey;
148	}
149
150	public byte[] signedPreKeySignature(final Element bundle) {
151		final Element signedPreKeySignature = bundle.findChild("signedPreKeySignature");
152		if(signedPreKeySignature == null) {
153			return null;
154		}
155		try {
156			return Base64.decode(signedPreKeySignature.getContent(), Base64.DEFAULT);
157		} catch (Throwable e) {
158			Log.e(Config.LOGTAG,AxolotlService.LOGPREFIX+" : Invalid base64 in signedPreKeySignature");
159			return null;
160		}
161	}
162
163	public IdentityKey identityKey(final Element bundle) {
164		IdentityKey identityKey = null;
165		final Element identityKeyElement = bundle.findChild("identityKey");
166		if(identityKeyElement == null) {
167			return null;
168		}
169		try {
170			identityKey = new IdentityKey(Base64.decode(identityKeyElement.getContent(), Base64.DEFAULT), 0);
171		} catch (Throwable e) {
172			Log.e(Config.LOGTAG,AxolotlService.LOGPREFIX+" : "+"Invalid identityKey in PEP: "+e.getMessage());
173		}
174		return identityKey;
175	}
176
177	public Map<Integer, ECPublicKey> preKeyPublics(final IqPacket packet) {
178		Map<Integer, ECPublicKey> preKeyRecords = new HashMap<>();
179		Element item = getItem(packet);
180		if (item == null) {
181			Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Couldn't find <item> in bundle IQ packet: " + packet);
182			return null;
183		}
184		final Element bundleElement = item.findChild("bundle");
185		if(bundleElement == null) {
186			return null;
187		}
188		final Element prekeysElement = bundleElement.findChild("prekeys");
189		if(prekeysElement == null) {
190			Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Couldn't find <prekeys> in bundle IQ packet: " + packet);
191			return null;
192		}
193		for(Element preKeyPublicElement : prekeysElement.getChildren()) {
194			if(!preKeyPublicElement.getName().equals("preKeyPublic")){
195				Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Encountered unexpected tag in prekeys list: " + preKeyPublicElement);
196				continue;
197			}
198			Integer preKeyId = Integer.valueOf(preKeyPublicElement.getAttribute("preKeyId"));
199			try {
200				ECPublicKey preKeyPublic = Curve.decodePoint(Base64.decode(preKeyPublicElement.getContent(), Base64.DEFAULT), 0);
201				preKeyRecords.put(preKeyId, preKeyPublic);
202			} catch (Throwable e) {
203				Log.e(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Invalid preKeyPublic (ID="+preKeyId+") in PEP: "+ e.getMessage()+", skipping...");
204				continue;
205			}
206		}
207		return preKeyRecords;
208	}
209
210	public Pair<X509Certificate[],byte[]> verification(final IqPacket packet) {
211		Element item = getItem(packet);
212		Element verification = item != null ? item.findChild("verification",AxolotlService.PEP_PREFIX) : null;
213		Element chain = verification != null ? verification.findChild("chain") : null;
214		Element signature = verification != null ? verification.findChild("signature") : null;
215		if (chain != null && signature != null) {
216			List<Element> certElements = chain.getChildren();
217			X509Certificate[] certificates = new X509Certificate[certElements.size()];
218			try {
219				CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
220				int i = 0;
221				for(Element cert : certElements) {
222					certificates[i] = (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(Base64.decode(cert.getContent(),Base64.DEFAULT)));
223					++i;
224				}
225				return new Pair<>(certificates,Base64.decode(signature.getContent(),Base64.DEFAULT));
226			} catch (CertificateException e) {
227				return null;
228			}
229		} else {
230			return null;
231		}
232	}
233
234	public PreKeyBundle bundle(final IqPacket bundle) {
235		Element bundleItem = getItem(bundle);
236		if(bundleItem == null) {
237			return null;
238		}
239		final Element bundleElement = bundleItem.findChild("bundle");
240		if(bundleElement == null) {
241			return null;
242		}
243		ECPublicKey signedPreKeyPublic = signedPreKeyPublic(bundleElement);
244		Integer signedPreKeyId = signedPreKeyId(bundleElement);
245		byte[] signedPreKeySignature = signedPreKeySignature(bundleElement);
246		IdentityKey identityKey = identityKey(bundleElement);
247		if(signedPreKeyPublic == null || identityKey == null) {
248			return null;
249		}
250
251		return new PreKeyBundle(0, 0, 0, null,
252				signedPreKeyId, signedPreKeyPublic, signedPreKeySignature, identityKey);
253	}
254
255	public List<PreKeyBundle> preKeys(final IqPacket preKeys) {
256		List<PreKeyBundle> bundles = new ArrayList<>();
257		Map<Integer, ECPublicKey> preKeyPublics = preKeyPublics(preKeys);
258		if ( preKeyPublics != null) {
259			for (Integer preKeyId : preKeyPublics.keySet()) {
260				ECPublicKey preKeyPublic = preKeyPublics.get(preKeyId);
261				bundles.add(new PreKeyBundle(0, 0, preKeyId, preKeyPublic,
262						0, null, null, null));
263			}
264		}
265
266		return bundles;
267	}
268
269	@Override
270	public void onIqPacketReceived(final Account account, final IqPacket packet) {
271		if (packet.getType() == IqPacket.TYPE.ERROR || packet.getType() == IqPacket.TYPE.TIMEOUT) {
272			return;
273		} else if (packet.hasChild("query", Xmlns.ROSTER) && packet.fromServer(account)) {
274			final Element query = packet.findChild("query");
275			// If this is in response to a query for the whole roster:
276			if (packet.getType() == IqPacket.TYPE.RESULT) {
277				account.getRoster().markAllAsNotInRoster();
278			}
279			this.rosterItems(account, query);
280		} else if ((packet.hasChild("block", Xmlns.BLOCKING) || packet.hasChild("blocklist", Xmlns.BLOCKING)) &&
281				packet.fromServer(account)) {
282			// Block list or block push.
283			Log.d(Config.LOGTAG, "Received blocklist update from server");
284			final Element blocklist = packet.findChild("blocklist", Xmlns.BLOCKING);
285			final Element block = packet.findChild("block", Xmlns.BLOCKING);
286			final Collection<Element> items = blocklist != null ? blocklist.getChildren() :
287				(block != null ? block.getChildren() : null);
288			// If this is a response to a blocklist query, clear the block list and replace with the new one.
289			// Otherwise, just update the existing blocklist.
290			if (packet.getType() == IqPacket.TYPE.RESULT) {
291				account.clearBlocklist();
292				account.getXmppConnection().getFeatures().setBlockListRequested(true);
293			}
294			if (items != null) {
295				final Collection<Jid> jids = new ArrayList<>(items.size());
296				// Create a collection of Jids from the packet
297				for (final Element item : items) {
298					if (item.getName().equals("item")) {
299						final Jid jid = item.getAttributeAsJid("jid");
300						if (jid != null) {
301							jids.add(jid);
302						}
303					}
304				}
305				account.getBlocklist().addAll(jids);
306			}
307			// Update the UI
308			mXmppConnectionService.updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
309		} else if (packet.hasChild("unblock", Xmlns.BLOCKING) &&
310				packet.fromServer(account) && packet.getType() == IqPacket.TYPE.SET) {
311			Log.d(Config.LOGTAG, "Received unblock update from server");
312			final Collection<Element> items = packet.findChild("unblock", Xmlns.BLOCKING).getChildren();
313			if (items.size() == 0) {
314				// No children to unblock == unblock all
315				account.getBlocklist().clear();
316			} else {
317				final Collection<Jid> jids = new ArrayList<>(items.size());
318				for (final Element item : items) {
319					if (item.getName().equals("item")) {
320						final Jid jid = item.getAttributeAsJid("jid");
321						if (jid != null) {
322							jids.add(jid);
323						}
324					}
325				}
326				account.getBlocklist().removeAll(jids);
327			}
328			mXmppConnectionService.updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
329		} else if (packet.hasChild("open", "http://jabber.org/protocol/ibb")
330				|| packet.hasChild("data", "http://jabber.org/protocol/ibb")) {
331			mXmppConnectionService.getJingleConnectionManager()
332				.deliverIbbPacket(account, packet);
333		} else if (packet.hasChild("query", "http://jabber.org/protocol/disco#info")) {
334			final IqPacket response = mXmppConnectionService.getIqGenerator().discoResponse(packet);
335			mXmppConnectionService.sendIqPacket(account, response, null);
336		} else if (packet.hasChild("query","jabber:iq:version")) {
337			final IqPacket response = mXmppConnectionService.getIqGenerator().versionResponse(packet);
338			mXmppConnectionService.sendIqPacket(account,response,null);
339		} else if (packet.hasChild("ping", "urn:xmpp:ping")) {
340			final IqPacket response = packet.generateResponse(IqPacket.TYPE.RESULT);
341			mXmppConnectionService.sendIqPacket(account, response, null);
342		} else {
343			if (packet.getType() == IqPacket.TYPE.GET || packet.getType() == IqPacket.TYPE.SET) {
344				final IqPacket response = packet.generateResponse(IqPacket.TYPE.ERROR);
345				final Element error = response.addChild("error");
346				error.setAttribute("type", "cancel");
347				error.addChild("feature-not-implemented","urn:ietf:params:xml:ns:xmpp-stanzas");
348				account.getXmppConnection().sendIqPacket(response, null);
349			}
350		}
351	}
352
353}