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