1// Copyright (c) 2017 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7use crate::data_forms::DataForm;
8use crate::disco::{DiscoInfoQuery, DiscoInfoResult, Feature, Identity};
9use crate::error::Error;
10use crate::hashes::{Algo, Hash};
11use crate::ns;
12use crate::presence::PresencePayload;
13use base64;
14use blake2::VarBlake2b;
15use digest::{Digest, Input, VariableOutput};
16use minidom::Element;
17use sha1::Sha1;
18use sha2::{Sha256, Sha512};
19use sha3::{Sha3_256, Sha3_512};
20use try_from::TryFrom;
21
22/// Represents a capability hash for a given client.
23#[derive(Debug, Clone)]
24pub struct Caps {
25 /// Deprecated list of additional feature bundles.
26 pub ext: Option<String>,
27
28 /// A URI identifying an XMPP application.
29 pub node: String,
30
31 /// The hash of that application’s
32 /// [disco#info](../disco/struct.DiscoInfoResult.html).
33 ///
34 /// Warning: This protocol is insecure, you may want to switch to
35 /// [ecaps2](../ecaps2/index.html) instead, see [this
36 /// email](https://mail.jabber.org/pipermail/security/2009-July/000812.html).
37 pub hash: Hash,
38}
39
40impl PresencePayload for Caps {}
41
42impl TryFrom<Element> for Caps {
43 type Err = Error;
44
45 fn try_from(elem: Element) -> Result<Caps, Error> {
46 check_self!(elem, "c", CAPS, "caps");
47 check_no_children!(elem, "caps");
48 check_no_unknown_attributes!(elem, "caps", ["hash", "ver", "ext", "node"]);
49 let ver: String = get_attr!(elem, "ver", required);
50 let hash = Hash {
51 algo: get_attr!(elem, "hash", required),
52 hash: base64::decode(&ver)?,
53 };
54 Ok(Caps {
55 ext: get_attr!(elem, "ext", optional),
56 node: get_attr!(elem, "node", required),
57 hash: hash,
58 })
59 }
60}
61
62impl From<Caps> for Element {
63 fn from(caps: Caps) -> Element {
64 Element::builder("c")
65 .ns(ns::CAPS)
66 .attr("ext", caps.ext)
67 .attr("hash", caps.hash.algo)
68 .attr("node", caps.node)
69 .attr("ver", base64::encode(&caps.hash.hash))
70 .build()
71 }
72}
73
74fn compute_item(field: &str) -> Vec<u8> {
75 let mut bytes = field.as_bytes().to_vec();
76 bytes.push(b'<');
77 bytes
78}
79
80fn compute_items<T, F: Fn(&T) -> Vec<u8>>(things: &[T], encode: F) -> Vec<u8> {
81 let mut string: Vec<u8> = vec![];
82 let mut accumulator: Vec<Vec<u8>> = vec![];
83 for thing in things {
84 let bytes = encode(thing);
85 accumulator.push(bytes);
86 }
87 // This works using the expected i;octet collation.
88 accumulator.sort();
89 for mut bytes in accumulator {
90 string.append(&mut bytes);
91 }
92 string
93}
94
95fn compute_features(features: &[Feature]) -> Vec<u8> {
96 compute_items(features, |feature| compute_item(&feature.var))
97}
98
99fn compute_identities(identities: &[Identity]) -> Vec<u8> {
100 compute_items(identities, |identity| {
101 let lang = identity.lang.clone().unwrap_or_default();
102 let name = identity.name.clone().unwrap_or_default();
103 let string = format!("{}/{}/{}/{}", identity.category, identity.type_, lang, name);
104 let bytes = string.as_bytes();
105 let mut vec = Vec::with_capacity(bytes.len());
106 vec.extend_from_slice(bytes);
107 vec.push(b'<');
108 vec
109 })
110}
111
112fn compute_extensions(extensions: &[DataForm]) -> Vec<u8> {
113 compute_items(extensions, |extension| {
114 let mut bytes = vec![];
115 // TODO: maybe handle the error case?
116 if let Some(ref form_type) = extension.form_type {
117 bytes.extend_from_slice(form_type.as_bytes());
118 }
119 bytes.push(b'<');
120 for field in extension.fields.clone() {
121 if field.var == "FORM_TYPE" {
122 continue;
123 }
124 bytes.append(&mut compute_item(&field.var));
125 bytes.append(&mut compute_items(&field.values, |value| {
126 compute_item(value)
127 }));
128 }
129 bytes
130 })
131}
132
133/// Applies the caps algorithm on the provided disco#info result, to generate
134/// the hash input.
135///
136/// Warning: This protocol is insecure, you may want to switch to
137/// [ecaps2](../ecaps2/index.html) instead, see [this
138/// email](https://mail.jabber.org/pipermail/security/2009-July/000812.html).
139pub fn compute_disco(disco: &DiscoInfoResult) -> Vec<u8> {
140 let identities_string = compute_identities(&disco.identities);
141 let features_string = compute_features(&disco.features);
142 let extensions_string = compute_extensions(&disco.extensions);
143
144 let mut final_string = vec![];
145 final_string.extend(identities_string);
146 final_string.extend(features_string);
147 final_string.extend(extensions_string);
148 final_string
149}
150
151fn get_hash_vec(hash: &[u8]) -> Vec<u8> {
152 let mut vec = Vec::with_capacity(hash.len());
153 vec.extend_from_slice(hash);
154 vec
155}
156
157/// Hashes the result of [compute_disco()] with one of the supported [hash
158/// algorithms](../hashes/enum.Algo.html).
159pub fn hash_caps(data: &[u8], algo: Algo) -> Result<Hash, String> {
160 Ok(Hash {
161 hash: match algo {
162 Algo::Sha_1 => {
163 let hash = Sha1::digest(data);
164 get_hash_vec(hash.as_slice())
165 }
166 Algo::Sha_256 => {
167 let hash = Sha256::digest(data);
168 get_hash_vec(hash.as_slice())
169 }
170 Algo::Sha_512 => {
171 let hash = Sha512::digest(data);
172 get_hash_vec(hash.as_slice())
173 }
174 Algo::Sha3_256 => {
175 let hash = Sha3_256::digest(data);
176 get_hash_vec(hash.as_slice())
177 }
178 Algo::Sha3_512 => {
179 let hash = Sha3_512::digest(data);
180 get_hash_vec(hash.as_slice())
181 }
182 Algo::Blake2b_256 => {
183 let mut hasher = VarBlake2b::new(32).unwrap();
184 hasher.input(data);
185 hasher.vec_result()
186 }
187 Algo::Blake2b_512 => {
188 let mut hasher = VarBlake2b::new(64).unwrap();
189 hasher.input(data);
190 hasher.vec_result()
191 }
192 Algo::Unknown(algo) => return Err(format!("Unknown algorithm: {}.", algo)),
193 },
194 algo: algo,
195 })
196}
197
198/// Helper function to create the query for the disco#info corresponding to a
199/// caps hash.
200pub fn query_caps(caps: Caps) -> DiscoInfoQuery {
201 DiscoInfoQuery {
202 node: Some(format!("{}#{}", caps.node, base64::encode(&caps.hash.hash))),
203 }
204}
205
206#[cfg(test)]
207mod tests {
208 use super::*;
209 use crate::caps;
210 use base64;
211
212 #[cfg(target_pointer_width = "32")]
213 #[test]
214 fn test_size() {
215 assert_size!(Caps, 52);
216 }
217
218 #[cfg(target_pointer_width = "64")]
219 #[test]
220 fn test_size() {
221 assert_size!(Caps, 104);
222 }
223
224 #[test]
225 fn test_parse() {
226 let elem: Element = "<c xmlns='http://jabber.org/protocol/caps' hash='sha-256' node='coucou' ver='K1Njy3HZBThlo4moOD5gBGhn0U0oK7/CbfLlIUDi6o4='/>".parse().unwrap();
227 let caps = Caps::try_from(elem).unwrap();
228 assert_eq!(caps.node, String::from("coucou"));
229 assert_eq!(caps.hash.algo, Algo::Sha_256);
230 assert_eq!(
231 caps.hash.hash,
232 base64::decode("K1Njy3HZBThlo4moOD5gBGhn0U0oK7/CbfLlIUDi6o4=").unwrap()
233 );
234 }
235
236 #[cfg(not(feature = "compat"))]
237 #[test]
238 fn test_invalid_child() {
239 let elem: Element = "<c xmlns='http://jabber.org/protocol/caps'><hash xmlns='urn:xmpp:hashes:2' algo='sha-256'>K1Njy3HZBThlo4moOD5gBGhn0U0oK7/CbfLlIUDi6o4=</hash></c>".parse().unwrap();
240 let error = Caps::try_from(elem).unwrap_err();
241 let message = match error {
242 Error::ParseError(string) => string,
243 _ => panic!(),
244 };
245 assert_eq!(message, "Unknown child in caps element.");
246 }
247
248 #[test]
249 fn test_simple() {
250 let elem: Element = "<query xmlns='http://jabber.org/protocol/disco#info'><identity category='client' type='pc'/><feature var='http://jabber.org/protocol/disco#info'/></query>".parse().unwrap();
251 let disco = DiscoInfoResult::try_from(elem).unwrap();
252 let caps = caps::compute_disco(&disco);
253 assert_eq!(caps.len(), 50);
254 }
255
256 #[test]
257 fn test_xep_5_2() {
258 let elem: Element = r#"
259<query xmlns='http://jabber.org/protocol/disco#info'
260 node='http://psi-im.org#q07IKJEyjvHSyhy//CH0CxmKi8w='>
261 <identity category='client' name='Exodus 0.9.1' type='pc'/>
262 <feature var='http://jabber.org/protocol/caps'/>
263 <feature var='http://jabber.org/protocol/disco#info'/>
264 <feature var='http://jabber.org/protocol/disco#items'/>
265 <feature var='http://jabber.org/protocol/muc'/>
266</query>
267"#
268 .parse()
269 .unwrap();
270
271 let data = b"client/pc//Exodus 0.9.1<http://jabber.org/protocol/caps<http://jabber.org/protocol/disco#info<http://jabber.org/protocol/disco#items<http://jabber.org/protocol/muc<";
272 let mut expected = Vec::with_capacity(data.len());
273 expected.extend_from_slice(data);
274 let disco = DiscoInfoResult::try_from(elem).unwrap();
275 let caps = caps::compute_disco(&disco);
276 assert_eq!(caps, expected);
277
278 let sha_1 = caps::hash_caps(&caps, Algo::Sha_1).unwrap();
279 assert_eq!(
280 sha_1.hash,
281 base64::decode("QgayPKawpkPSDYmwT/WM94uAlu0=").unwrap()
282 );
283 }
284
285 #[test]
286 fn test_xep_5_3() {
287 let elem: Element = r#"
288<query xmlns='http://jabber.org/protocol/disco#info'
289 node='http://psi-im.org#q07IKJEyjvHSyhy//CH0CxmKi8w='>
290 <identity xml:lang='en' category='client' name='Psi 0.11' type='pc'/>
291 <identity xml:lang='el' category='client' name='Ψ 0.11' type='pc'/>
292 <feature var='http://jabber.org/protocol/caps'/>
293 <feature var='http://jabber.org/protocol/disco#info'/>
294 <feature var='http://jabber.org/protocol/disco#items'/>
295 <feature var='http://jabber.org/protocol/muc'/>
296 <x xmlns='jabber:x:data' type='result'>
297 <field var='FORM_TYPE' type='hidden'>
298 <value>urn:xmpp:dataforms:softwareinfo</value>
299 </field>
300 <field var='ip_version'>
301 <value>ipv4</value>
302 <value>ipv6</value>
303 </field>
304 <field var='os'>
305 <value>Mac</value>
306 </field>
307 <field var='os_version'>
308 <value>10.5.1</value>
309 </field>
310 <field var='software'>
311 <value>Psi</value>
312 </field>
313 <field var='software_version'>
314 <value>0.11</value>
315 </field>
316 </x>
317</query>
318"#
319 .parse()
320 .unwrap();
321 let data = b"client/pc/el/\xce\xa8 0.11<client/pc/en/Psi 0.11<http://jabber.org/protocol/caps<http://jabber.org/protocol/disco#info<http://jabber.org/protocol/disco#items<http://jabber.org/protocol/muc<urn:xmpp:dataforms:softwareinfo<ip_version<ipv4<ipv6<os<Mac<os_version<10.5.1<software<Psi<software_version<0.11<";
322 let mut expected = Vec::with_capacity(data.len());
323 expected.extend_from_slice(data);
324 let disco = DiscoInfoResult::try_from(elem).unwrap();
325 let caps = caps::compute_disco(&disco);
326 assert_eq!(caps, expected);
327
328 let sha_1 = caps::hash_caps(&caps, Algo::Sha_1).unwrap();
329 assert_eq!(
330 sha_1.hash,
331 base64::decode("q07IKJEyjvHSyhy//CH0CxmKi8w=").unwrap()
332 );
333 }
334}