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