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