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