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.entities.Conversation;
 30import eu.siacs.conversations.services.XmppConnectionService;
 31import eu.siacs.conversations.xml.Namespace;
 32import eu.siacs.conversations.xml.Element;
 33import eu.siacs.conversations.xmpp.OnIqPacketReceived;
 34import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 35import eu.siacs.conversations.xmpp.jid.Jid;
 36import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 37
 38public class IqParser extends AbstractParser implements OnIqPacketReceived {
 39
 40	public IqParser(final XmppConnectionService service) {
 41		super(service);
 42	}
 43
 44	private void rosterItems(final Account account, final Element query) {
 45		final String version = query.getAttribute("ver");
 46		if (version != null) {
 47			account.getRoster().setVersion(version);
 48		}
 49		for (final Element item : query.getChildren()) {
 50			if (item.getName().equals("item")) {
 51				final Jid jid = item.getAttributeAsJid("jid");
 52				if (jid == null) {
 53					continue;
 54				}
 55				final String name = item.getAttribute("name");
 56				final String subscription = item.getAttribute("subscription");
 57				final Contact contact = account.getRoster().getContact(jid);
 58				boolean bothPre = contact.getOption(Contact.Options.TO) && contact.getOption(Contact.Options.FROM);
 59				if (!contact.getOption(Contact.Options.DIRTY_PUSH)) {
 60					contact.setServerName(name);
 61					contact.parseGroupsFromElement(item);
 62				}
 63				if (subscription != null) {
 64					if (subscription.equals("remove")) {
 65						contact.resetOption(Contact.Options.IN_ROSTER);
 66						contact.resetOption(Contact.Options.DIRTY_DELETE);
 67						contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
 68					} else {
 69						contact.setOption(Contact.Options.IN_ROSTER);
 70						contact.resetOption(Contact.Options.DIRTY_PUSH);
 71						contact.parseSubscriptionFromElement(item);
 72					}
 73				}
 74				boolean both = contact.getOption(Contact.Options.TO) && contact.getOption(Contact.Options.FROM);
 75				if ((both != bothPre) && both) {
 76					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": gained mutual presence subscription with "+contact.getJid());
 77					AxolotlService axolotlService = account.getAxolotlService();
 78					if (axolotlService != null) {
 79						axolotlService.clearErrorsInFetchStatusMap(contact.getJid());
 80					}
 81				}
 82				mXmppConnectionService.getAvatarService().clear(contact);
 83			}
 84		}
 85		mXmppConnectionService.updateConversationUi();
 86		mXmppConnectionService.updateRosterUi();
 87	}
 88
 89	public String avatarData(final IqPacket packet) {
 90		final Element pubsub = packet.findChild("pubsub",
 91				"http://jabber.org/protocol/pubsub");
 92		if (pubsub == null) {
 93			return null;
 94		}
 95		final Element items = pubsub.findChild("items");
 96		if (items == null) {
 97			return null;
 98		}
 99		return super.avatarData(items);
100	}
101
102	public Element getItem(final IqPacket packet) {
103		final Element pubsub = packet.findChild("pubsub",
104				"http://jabber.org/protocol/pubsub");
105		if (pubsub == null) {
106			return null;
107		}
108		final Element items = pubsub.findChild("items");
109		if (items == null) {
110			return null;
111		}
112		return items.findChild("item");
113	}
114
115	@NonNull
116	public Set<Integer> deviceIds(final Element item) {
117		Set<Integer> deviceIds = new HashSet<>();
118		if (item != null) {
119			final Element list = item.findChild("list");
120			if (list != null) {
121				for (Element device : list.getChildren()) {
122					if (!device.getName().equals("device")) {
123						continue;
124					}
125					try {
126						Integer id = Integer.valueOf(device.getAttribute("id"));
127						deviceIds.add(id);
128					} catch (NumberFormatException e) {
129						Log.e(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Encountered invalid <device> node in PEP ("+e.getMessage()+"):" + device.toString()+ ", skipping...");
130						continue;
131					}
132				}
133			}
134		}
135		return deviceIds;
136	}
137
138	public Integer signedPreKeyId(final Element bundle) {
139		final Element signedPreKeyPublic = bundle.findChild("signedPreKeyPublic");
140		if(signedPreKeyPublic == null) {
141			return null;
142		}
143		try {
144			return Integer.valueOf(signedPreKeyPublic.getAttribute("signedPreKeyId"));
145		} catch (NumberFormatException e) {
146			return null;
147		}
148	}
149
150	public ECPublicKey signedPreKeyPublic(final Element bundle) {
151		ECPublicKey publicKey = null;
152		final Element signedPreKeyPublic = bundle.findChild("signedPreKeyPublic");
153		if(signedPreKeyPublic == null) {
154			return null;
155		}
156		try {
157			publicKey = Curve.decodePoint(Base64.decode(signedPreKeyPublic.getContent(),Base64.DEFAULT), 0);
158		} catch (Throwable e) {
159			Log.e(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Invalid signedPreKeyPublic in PEP: " + e.getMessage());
160		}
161		return publicKey;
162	}
163
164	public byte[] signedPreKeySignature(final Element bundle) {
165		final Element signedPreKeySignature = bundle.findChild("signedPreKeySignature");
166		if(signedPreKeySignature == null) {
167			return null;
168		}
169		try {
170			return Base64.decode(signedPreKeySignature.getContent(), Base64.DEFAULT);
171		} catch (Throwable e) {
172			Log.e(Config.LOGTAG,AxolotlService.LOGPREFIX+" : Invalid base64 in signedPreKeySignature");
173			return null;
174		}
175	}
176
177	public IdentityKey identityKey(final Element bundle) {
178		IdentityKey identityKey = null;
179		final Element identityKeyElement = bundle.findChild("identityKey");
180		if(identityKeyElement == null) {
181			return null;
182		}
183		try {
184			identityKey = new IdentityKey(Base64.decode(identityKeyElement.getContent(), Base64.DEFAULT), 0);
185		} catch (Throwable e) {
186			Log.e(Config.LOGTAG,AxolotlService.LOGPREFIX+" : "+"Invalid identityKey in PEP: "+e.getMessage());
187		}
188		return identityKey;
189	}
190
191	public Map<Integer, ECPublicKey> preKeyPublics(final IqPacket packet) {
192		Map<Integer, ECPublicKey> preKeyRecords = new HashMap<>();
193		Element item = getItem(packet);
194		if (item == null) {
195			Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Couldn't find <item> in bundle IQ packet: " + packet);
196			return null;
197		}
198		final Element bundleElement = item.findChild("bundle");
199		if(bundleElement == null) {
200			return null;
201		}
202		final Element prekeysElement = bundleElement.findChild("prekeys");
203		if(prekeysElement == null) {
204			Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Couldn't find <prekeys> in bundle IQ packet: " + packet);
205			return null;
206		}
207		for(Element preKeyPublicElement : prekeysElement.getChildren()) {
208			if(!preKeyPublicElement.getName().equals("preKeyPublic")){
209				Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Encountered unexpected tag in prekeys list: " + preKeyPublicElement);
210				continue;
211			}
212			Integer preKeyId = null;
213			try {
214				preKeyId = Integer.valueOf(preKeyPublicElement.getAttribute("preKeyId"));
215				final ECPublicKey preKeyPublic = Curve.decodePoint(Base64.decode(preKeyPublicElement.getContent(), Base64.DEFAULT), 0);
216				preKeyRecords.put(preKeyId, preKeyPublic);
217			} catch (NumberFormatException e) {
218				Log.e(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"could not parse preKeyId from preKey "+preKeyPublicElement.toString());
219			} catch (Throwable e) {
220				Log.e(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Invalid preKeyPublic (ID="+preKeyId+") in PEP: "+ e.getMessage()+", skipping...");
221			}
222		}
223		return preKeyRecords;
224	}
225
226	public Pair<X509Certificate[],byte[]> verification(final IqPacket packet) {
227		Element item = getItem(packet);
228		Element verification = item != null ? item.findChild("verification",AxolotlService.PEP_PREFIX) : null;
229		Element chain = verification != null ? verification.findChild("chain") : null;
230		Element signature = verification != null ? verification.findChild("signature") : null;
231		if (chain != null && signature != null) {
232			List<Element> certElements = chain.getChildren();
233			X509Certificate[] certificates = new X509Certificate[certElements.size()];
234			try {
235				CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
236				int i = 0;
237				for(Element cert : certElements) {
238					certificates[i] = (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(Base64.decode(cert.getContent(),Base64.DEFAULT)));
239					++i;
240				}
241				return new Pair<>(certificates,Base64.decode(signature.getContent(),Base64.DEFAULT));
242			} catch (CertificateException e) {
243				return null;
244			}
245		} else {
246			return null;
247		}
248	}
249
250	public PreKeyBundle bundle(final IqPacket bundle) {
251		Element bundleItem = getItem(bundle);
252		if(bundleItem == null) {
253			return null;
254		}
255		final Element bundleElement = bundleItem.findChild("bundle");
256		if(bundleElement == null) {
257			return null;
258		}
259		ECPublicKey signedPreKeyPublic = signedPreKeyPublic(bundleElement);
260		Integer signedPreKeyId = signedPreKeyId(bundleElement);
261		byte[] signedPreKeySignature = signedPreKeySignature(bundleElement);
262		IdentityKey identityKey = identityKey(bundleElement);
263		if(signedPreKeyId == null || signedPreKeyPublic == null || identityKey == null) {
264			return null;
265		}
266
267		return new PreKeyBundle(0, 0, 0, null,
268				signedPreKeyId, signedPreKeyPublic, signedPreKeySignature, identityKey);
269	}
270
271	public List<PreKeyBundle> preKeys(final IqPacket preKeys) {
272		List<PreKeyBundle> bundles = new ArrayList<>();
273		Map<Integer, ECPublicKey> preKeyPublics = preKeyPublics(preKeys);
274		if ( preKeyPublics != null) {
275			for (Integer preKeyId : preKeyPublics.keySet()) {
276				ECPublicKey preKeyPublic = preKeyPublics.get(preKeyId);
277				bundles.add(new PreKeyBundle(0, 0, preKeyId, preKeyPublic,
278						0, null, null, null));
279			}
280		}
281
282		return bundles;
283	}
284
285	@Override
286	public void onIqPacketReceived(final Account account, final IqPacket packet) {
287		final boolean isGet = packet.getType() == IqPacket.TYPE.GET;
288		if (packet.getType() == IqPacket.TYPE.ERROR || packet.getType() == IqPacket.TYPE.TIMEOUT) {
289			return;
290		} else if (packet.hasChild("query", Namespace.ROSTER) && packet.fromServer(account)) {
291			final Element query = packet.findChild("query");
292			// If this is in response to a query for the whole roster:
293			if (packet.getType() == IqPacket.TYPE.RESULT) {
294				account.getRoster().markAllAsNotInRoster();
295			}
296			this.rosterItems(account, query);
297		} else if ((packet.hasChild("block", Namespace.BLOCKING) || packet.hasChild("blocklist", Namespace.BLOCKING)) &&
298				packet.fromServer(account)) {
299			// Block list or block push.
300			Log.d(Config.LOGTAG, "Received blocklist update from server");
301			final Element blocklist = packet.findChild("blocklist", Namespace.BLOCKING);
302			final Element block = packet.findChild("block", Namespace.BLOCKING);
303			final Collection<Element> items = blocklist != null ? blocklist.getChildren() :
304				(block != null ? block.getChildren() : null);
305			// If this is a response to a blocklist query, clear the block list and replace with the new one.
306			// Otherwise, just update the existing blocklist.
307			if (packet.getType() == IqPacket.TYPE.RESULT) {
308				account.clearBlocklist();
309				account.getXmppConnection().getFeatures().setBlockListRequested(true);
310			}
311			if (items != null) {
312				final Collection<Jid> jids = new ArrayList<>(items.size());
313				// Create a collection of Jids from the packet
314				for (final Element item : items) {
315					if (item.getName().equals("item")) {
316						final Jid jid = item.getAttributeAsJid("jid");
317						if (jid != null) {
318							jids.add(jid);
319						}
320					}
321				}
322				account.getBlocklist().addAll(jids);
323				if (packet.getType() == IqPacket.TYPE.SET) {
324					for(Jid jid : jids) {
325						Conversation conversation = mXmppConnectionService.find(account,jid);
326						if (conversation != null) {
327							mXmppConnectionService.markRead(conversation);
328						}
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}