Skip to main content

xmpp_parsers/
hashes.rs

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 alloc::borrow::Cow;
8use core::{
9    fmt::Write,
10    num::ParseIntError,
11    ops::{Deref, DerefMut},
12    str::FromStr,
13};
14
15use xso::{error::Error, text::Base64, AsXml, AsXmlText, FromXml, FromXmlText};
16
17use base64::{engine::general_purpose::STANDARD as Base64Engine, Engine};
18use minidom::IntoAttributeValue;
19
20use crate::ns;
21
22/// List of the algorithms we support, or Unknown.
23#[allow(non_camel_case_types)]
24#[derive(Debug, Clone, PartialEq, Eq, Hash)]
25pub enum Algo {
26    /// The Secure Hash Algorithm 1, with known vulnerabilities, do not use it.
27    ///
28    /// See <https://www.rfc-editor.org/rfc/rfc3174>
29    Sha_1,
30
31    /// The Secure Hash Algorithm 2, in its 256-bit version.
32    ///
33    /// See <https://www.rfc-editor.org/rfc/rfc6234>
34    Sha_256,
35
36    /// The Secure Hash Algorithm 2, in its 512-bit version.
37    ///
38    /// See <https://www.rfc-editor.org/rfc/rfc6234>
39    Sha_512,
40
41    /// The Secure Hash Algorithm 3, based on Keccak, in its 256-bit version.
42    ///
43    /// See <https://keccak.team/files/Keccak-submission-3.pdf>
44    Sha3_256,
45
46    /// The Secure Hash Algorithm 3, based on Keccak, in its 512-bit version.
47    ///
48    /// See <https://keccak.team/files/Keccak-submission-3.pdf>
49    Sha3_512,
50
51    /// The BLAKE2 hash algorithm, for a 256-bit output.
52    ///
53    /// See <https://www.rfc-editor.org/rfc/rfc7693>
54    Blake2b_256,
55
56    /// The BLAKE2 hash algorithm, for a 512-bit output.
57    ///
58    /// See <https://www.rfc-editor.org/rfc/rfc7693>
59    Blake2b_512,
60
61    /// An unknown hash not in this list, you can probably reject it.
62    Unknown(String),
63}
64
65impl FromStr for Algo {
66    type Err = Error;
67
68    fn from_str(s: &str) -> Result<Algo, Error> {
69        Ok(match s {
70            "" => return Err(Error::Other("'algo' argument can’t be empty.")),
71
72            "sha-1" => Algo::Sha_1,
73            "sha-256" => Algo::Sha_256,
74            "sha-512" => Algo::Sha_512,
75            "sha3-256" => Algo::Sha3_256,
76            "sha3-512" => Algo::Sha3_512,
77            "blake2b-256" => Algo::Blake2b_256,
78            "blake2b-512" => Algo::Blake2b_512,
79            value => Algo::Unknown(value.to_owned()),
80        })
81    }
82}
83
84impl From<Algo> for String {
85    fn from(algo: Algo) -> String {
86        String::from(match algo {
87            Algo::Sha_1 => "sha-1",
88            Algo::Sha_256 => "sha-256",
89            Algo::Sha_512 => "sha-512",
90            Algo::Sha3_256 => "sha3-256",
91            Algo::Sha3_512 => "sha3-512",
92            Algo::Blake2b_256 => "blake2b-256",
93            Algo::Blake2b_512 => "blake2b-512",
94            Algo::Unknown(text) => return text,
95        })
96    }
97}
98
99impl FromXmlText for Algo {
100    fn from_xml_text(value: String) -> Result<Self, Error> {
101        value.parse().map_err(Error::text_parse_error)
102    }
103}
104
105impl AsXmlText for Algo {
106    fn as_xml_text(&self) -> Result<Cow<'_, str>, Error> {
107        Ok(Cow::Borrowed(match self {
108            Algo::Sha_1 => "sha-1",
109            Algo::Sha_256 => "sha-256",
110            Algo::Sha_512 => "sha-512",
111            Algo::Sha3_256 => "sha3-256",
112            Algo::Sha3_512 => "sha3-512",
113            Algo::Blake2b_256 => "blake2b-256",
114            Algo::Blake2b_512 => "blake2b-512",
115            Algo::Unknown(text) => text.as_str(),
116        }))
117    }
118}
119
120impl IntoAttributeValue for Algo {
121    fn into_attribute_value(self) -> Option<String> {
122        Some(String::from(self))
123    }
124}
125
126/// This element represents a hash of some data, defined by the hash
127/// algorithm used and the computed value.
128#[derive(FromXml, AsXml, PartialEq, Debug, Clone)]
129#[xml(namespace = ns::HASHES, name = "hash")]
130pub struct Hash {
131    /// The algorithm used to create this hash.
132    #[xml(attribute)]
133    pub algo: Algo,
134
135    /// The hash value, as a vector of bytes.
136    #[xml(text = Base64)]
137    pub hash: Vec<u8>,
138}
139
140impl Hash {
141    /// Creates a [struct@Hash] element with the given algo and data.
142    pub fn new(algo: Algo, hash: Vec<u8>) -> Hash {
143        Hash { algo, hash }
144    }
145
146    /// Like [new](#method.new) but takes base64-encoded data before decoding
147    /// it.
148    pub fn from_base64(algo: Algo, hash: &str) -> Result<Hash, Error> {
149        Ok(Hash::new(
150            algo,
151            Base64Engine.decode(hash).map_err(Error::text_parse_error)?,
152        ))
153    }
154
155    /// Like [new](#method.new) but takes hex-encoded data before decoding it.
156    pub fn from_hex(algo: Algo, hex: &str) -> Result<Hash, ParseIntError> {
157        let mut bytes = vec![];
158        for i in 0..hex.len() / 2 {
159            let byte = u8::from_str_radix(&hex[2 * i..2 * i + 2], 16)?;
160            bytes.push(byte);
161        }
162        Ok(Hash::new(algo, bytes))
163    }
164
165    /// Like [new](#method.new) but takes hex-encoded data before decoding it.
166    pub fn from_colon_separated_hex(algo: Algo, hex: &str) -> Result<Hash, ParseIntError> {
167        let mut bytes = vec![];
168        for i in 0..(1 + hex.len()) / 3 {
169            let byte = u8::from_str_radix(&hex[3 * i..3 * i + 2], 16)?;
170            if 3 * i + 2 < hex.len() {
171                assert_eq!(&hex[3 * i + 2..3 * i + 3], ":");
172            }
173            bytes.push(byte);
174        }
175        Ok(Hash::new(algo, bytes))
176    }
177
178    /// Formats this hash into base64.
179    pub fn to_base64(&self) -> String {
180        Base64Engine.encode(&self.hash[..])
181    }
182
183    /// Formats this hash into hexadecimal.
184    pub fn to_hex(&self) -> String {
185        let mut hex = String::with_capacity(self.hash.len() * 2);
186        for byte in &self.hash {
187            write!(&mut hex, "{:02x}", byte).unwrap();
188        }
189        hex
190    }
191
192    /// Formats this hash into colon-separated hexadecimal.
193    pub fn to_colon_separated_hex(&self) -> String {
194        self.hash
195            .iter()
196            .map(|byte| format!("{:02x}", byte))
197            .collect::<Vec<_>>()
198            .join(":")
199    }
200}
201
202/// Helper for parsing and serialising a SHA-1 attribute.
203#[derive(Debug, Clone, PartialEq)]
204pub struct Sha1HexAttribute(Hash);
205
206impl FromStr for Sha1HexAttribute {
207    type Err = ParseIntError;
208
209    fn from_str(hex: &str) -> Result<Self, Self::Err> {
210        let hash = Hash::from_hex(Algo::Sha_1, hex)?;
211        Ok(Sha1HexAttribute(hash))
212    }
213}
214
215impl FromXmlText for Sha1HexAttribute {
216    fn from_xml_text(s: String) -> Result<Self, xso::error::Error> {
217        Self::from_str(&s).map_err(xso::error::Error::text_parse_error)
218    }
219}
220
221impl AsXmlText for Sha1HexAttribute {
222    fn as_xml_text(&self) -> Result<Cow<'_, str>, xso::error::Error> {
223        Ok(Cow::Owned(self.to_hex()))
224    }
225}
226
227impl IntoAttributeValue for Sha1HexAttribute {
228    fn into_attribute_value(self) -> Option<String> {
229        Some(self.to_hex())
230    }
231}
232
233impl DerefMut for Sha1HexAttribute {
234    fn deref_mut(&mut self) -> &mut Self::Target {
235        &mut self.0
236    }
237}
238
239impl Deref for Sha1HexAttribute {
240    type Target = Hash;
241
242    fn deref(&self) -> &Self::Target {
243        &self.0
244    }
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250    use minidom::Element;
251    use xso::error::FromElementError;
252
253    #[cfg(target_pointer_width = "32")]
254    #[test]
255    fn test_size() {
256        assert_size!(Algo, 12);
257        assert_size!(Hash, 24);
258    }
259
260    #[cfg(target_pointer_width = "64")]
261    #[test]
262    fn test_size() {
263        assert_size!(Algo, 24);
264        assert_size!(Hash, 48);
265    }
266
267    #[test]
268    fn test_simple() {
269        let elem: Element = "<hash xmlns='urn:xmpp:hashes:2' algo='sha-256'>2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU=</hash>".parse().unwrap();
270        let hash = Hash::try_from(elem).unwrap();
271        assert_eq!(hash.algo, Algo::Sha_256);
272        assert_eq!(
273            hash.hash,
274            Base64Engine
275                .decode("2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU=")
276                .unwrap()
277        );
278    }
279
280    #[test]
281    fn value_serialisation() {
282        let elem: Element = "<hash xmlns='urn:xmpp:hashes:2' algo='sha-256'>2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU=</hash>".parse().unwrap();
283        let hash = Hash::try_from(elem).unwrap();
284        assert_eq!(
285            hash.to_base64(),
286            "2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU="
287        );
288        assert_eq!(
289            hash.to_hex(),
290            "d976ab9b04e53710c0324bf29a5a17dd2e7e55bca536b26dfe5e50c8f6be6285"
291        );
292        assert_eq!(hash.to_colon_separated_hex(), "d9:76:ab:9b:04:e5:37:10:c0:32:4b:f2:9a:5a:17:dd:2e:7e:55:bc:a5:36:b2:6d:fe:5e:50:c8:f6:be:62:85");
293    }
294
295    #[test]
296    fn test_unknown() {
297        let elem: Element = "<replace xmlns='urn:xmpp:message-correct:0'/>"
298            .parse()
299            .unwrap();
300        let error = Hash::try_from(elem.clone()).unwrap_err();
301        let returned_elem = match error {
302            FromElementError::Mismatch(elem) => elem,
303            _ => panic!(),
304        };
305        assert_eq!(elem, returned_elem);
306    }
307
308    #[test]
309    #[cfg_attr(not(feature = "pedantic"), should_panic = "Result::unwrap_err")]
310    fn test_invalid_child() {
311        let elem: Element = "<hash xmlns='urn:xmpp:hashes:2' algo='sha-1'><coucou/></hash>"
312            .parse()
313            .unwrap();
314        let error = Hash::try_from(elem).unwrap_err();
315        let message = match error {
316            FromElementError::Invalid(Error::Other(string)) => string,
317            _ => panic!(),
318        };
319        assert_eq!(message, "Unknown child in Hash element.");
320    }
321}