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.libsignal.IdentityKey;
9import org.whispersystems.libsignal.ecc.Curve;
10import org.whispersystems.libsignal.ecc.ECPublicKey;
11import org.whispersystems.libsignal.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.InvalidJid;
33import eu.siacs.conversations.xmpp.OnIqPacketReceived;
34import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
35import eu.siacs.conversations.xmpp.stanzas.IqPacket;
36import rocks.xmpp.addr.Jid;
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 = InvalidJid.getNullForInvalid(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 ("remove".equals(subscription)) {
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 boolean both = contact.getOption(Contact.Options.TO) && contact.getOption(Contact.Options.FROM);
73 if ((both != bothPre) && both) {
74 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": gained mutual presence subscription with "+contact.getJid());
75 AxolotlService axolotlService = account.getAxolotlService();
76 if (axolotlService != null) {
77 axolotlService.clearErrorsInFetchStatusMap(contact.getJid());
78 }
79 }
80 mXmppConnectionService.getAvatarService().clear(contact);
81 }
82 }
83 mXmppConnectionService.updateConversationUi();
84 mXmppConnectionService.updateRosterUi();
85 mXmppConnectionService.getShortcutService().refresh();
86 mXmppConnectionService.syncRoster(account);
87 }
88
89 public String avatarData(final IqPacket packet) {
90 final Element pubsub = packet.findChild("pubsub", Namespace.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", Namespace.PUBSUB);
103 if (pubsub == null) {
104 return null;
105 }
106 final Element items = pubsub.findChild("items");
107 if (items == null) {
108 return null;
109 }
110 return items.findChild("item");
111 }
112
113 @NonNull
114 public Set<Integer> deviceIds(final Element item) {
115 Set<Integer> deviceIds = new HashSet<>();
116 if (item != null) {
117 final Element list = item.findChild("list");
118 if (list != null) {
119 for (Element device : list.getChildren()) {
120 if (!device.getName().equals("device")) {
121 continue;
122 }
123 try {
124 Integer id = Integer.valueOf(device.getAttribute("id"));
125 deviceIds.add(id);
126 } catch (NumberFormatException e) {
127 Log.e(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Encountered invalid <device> node in PEP ("+e.getMessage()+"):" + device.toString()+ ", skipping...");
128 continue;
129 }
130 }
131 }
132 }
133 return deviceIds;
134 }
135
136 public Integer signedPreKeyId(final Element bundle) {
137 final Element signedPreKeyPublic = bundle.findChild("signedPreKeyPublic");
138 if(signedPreKeyPublic == null) {
139 return null;
140 }
141 try {
142 return Integer.valueOf(signedPreKeyPublic.getAttribute("signedPreKeyId"));
143 } catch (NumberFormatException e) {
144 return null;
145 }
146 }
147
148 public ECPublicKey signedPreKeyPublic(final Element bundle) {
149 ECPublicKey publicKey = null;
150 final Element signedPreKeyPublic = bundle.findChild("signedPreKeyPublic");
151 if(signedPreKeyPublic == null) {
152 return null;
153 }
154 try {
155 publicKey = Curve.decodePoint(Base64.decode(signedPreKeyPublic.getContent(),Base64.DEFAULT), 0);
156 } catch (Throwable e) {
157 Log.e(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Invalid signedPreKeyPublic in PEP: " + e.getMessage());
158 }
159 return publicKey;
160 }
161
162 public byte[] signedPreKeySignature(final Element bundle) {
163 final Element signedPreKeySignature = bundle.findChild("signedPreKeySignature");
164 if(signedPreKeySignature == null) {
165 return null;
166 }
167 try {
168 return Base64.decode(signedPreKeySignature.getContent(), Base64.DEFAULT);
169 } catch (Throwable e) {
170 Log.e(Config.LOGTAG,AxolotlService.LOGPREFIX+" : Invalid base64 in signedPreKeySignature");
171 return null;
172 }
173 }
174
175 public IdentityKey identityKey(final Element bundle) {
176 IdentityKey identityKey = null;
177 final Element identityKeyElement = bundle.findChild("identityKey");
178 if(identityKeyElement == null) {
179 return null;
180 }
181 try {
182 identityKey = new IdentityKey(Base64.decode(identityKeyElement.getContent(), Base64.DEFAULT), 0);
183 } catch (Throwable e) {
184 Log.e(Config.LOGTAG,AxolotlService.LOGPREFIX+" : "+"Invalid identityKey in PEP: "+e.getMessage());
185 }
186 return identityKey;
187 }
188
189 public Map<Integer, ECPublicKey> preKeyPublics(final IqPacket packet) {
190 Map<Integer, ECPublicKey> preKeyRecords = new HashMap<>();
191 Element item = getItem(packet);
192 if (item == null) {
193 Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Couldn't find <item> in bundle IQ packet: " + packet);
194 return null;
195 }
196 final Element bundleElement = item.findChild("bundle");
197 if(bundleElement == null) {
198 return null;
199 }
200 final Element prekeysElement = bundleElement.findChild("prekeys");
201 if(prekeysElement == null) {
202 Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Couldn't find <prekeys> in bundle IQ packet: " + packet);
203 return null;
204 }
205 for(Element preKeyPublicElement : prekeysElement.getChildren()) {
206 if(!preKeyPublicElement.getName().equals("preKeyPublic")){
207 Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Encountered unexpected tag in prekeys list: " + preKeyPublicElement);
208 continue;
209 }
210 Integer preKeyId = null;
211 try {
212 preKeyId = Integer.valueOf(preKeyPublicElement.getAttribute("preKeyId"));
213 final ECPublicKey preKeyPublic = Curve.decodePoint(Base64.decode(preKeyPublicElement.getContent(), Base64.DEFAULT), 0);
214 preKeyRecords.put(preKeyId, preKeyPublic);
215 } catch (NumberFormatException e) {
216 Log.e(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"could not parse preKeyId from preKey "+preKeyPublicElement.toString());
217 } catch (Throwable e) {
218 Log.e(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Invalid preKeyPublic (ID="+preKeyId+") in PEP: "+ e.getMessage()+", skipping...");
219 }
220 }
221 return preKeyRecords;
222 }
223
224 public Pair<X509Certificate[],byte[]> verification(final IqPacket packet) {
225 Element item = getItem(packet);
226 Element verification = item != null ? item.findChild("verification",AxolotlService.PEP_PREFIX) : null;
227 Element chain = verification != null ? verification.findChild("chain") : null;
228 Element signature = verification != null ? verification.findChild("signature") : null;
229 if (chain != null && signature != null) {
230 List<Element> certElements = chain.getChildren();
231 X509Certificate[] certificates = new X509Certificate[certElements.size()];
232 try {
233 CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
234 int i = 0;
235 for(Element cert : certElements) {
236 certificates[i] = (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(Base64.decode(cert.getContent(),Base64.DEFAULT)));
237 ++i;
238 }
239 return new Pair<>(certificates,Base64.decode(signature.getContent(),Base64.DEFAULT));
240 } catch (CertificateException e) {
241 return null;
242 }
243 } else {
244 return null;
245 }
246 }
247
248 public PreKeyBundle bundle(final IqPacket bundle) {
249 Element bundleItem = getItem(bundle);
250 if(bundleItem == null) {
251 return null;
252 }
253 final Element bundleElement = bundleItem.findChild("bundle");
254 if(bundleElement == null) {
255 return null;
256 }
257 ECPublicKey signedPreKeyPublic = signedPreKeyPublic(bundleElement);
258 Integer signedPreKeyId = signedPreKeyId(bundleElement);
259 byte[] signedPreKeySignature = signedPreKeySignature(bundleElement);
260 IdentityKey identityKey = identityKey(bundleElement);
261 if(signedPreKeyId == null || signedPreKeyPublic == null || identityKey == null) {
262 return null;
263 }
264
265 return new PreKeyBundle(0, 0, 0, null,
266 signedPreKeyId, signedPreKeyPublic, signedPreKeySignature, identityKey);
267 }
268
269 public List<PreKeyBundle> preKeys(final IqPacket preKeys) {
270 List<PreKeyBundle> bundles = new ArrayList<>();
271 Map<Integer, ECPublicKey> preKeyPublics = preKeyPublics(preKeys);
272 if ( preKeyPublics != null) {
273 for (Integer preKeyId : preKeyPublics.keySet()) {
274 ECPublicKey preKeyPublic = preKeyPublics.get(preKeyId);
275 bundles.add(new PreKeyBundle(0, 0, preKeyId, preKeyPublic,
276 0, null, null, null));
277 }
278 }
279
280 return bundles;
281 }
282
283 @Override
284 public void onIqPacketReceived(final Account account, final IqPacket packet) {
285 final boolean isGet = packet.getType() == IqPacket.TYPE.GET;
286 if (packet.getType() == IqPacket.TYPE.ERROR || packet.getType() == IqPacket.TYPE.TIMEOUT) {
287 return;
288 }
289 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 = InvalidJid.getNullForInvalid(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 = InvalidJid.getNullForInvalid(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(account, 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() || account.isOnion()) {
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}