1// Copyright (c) 2018 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 std::collections::BTreeMap;
8
9use try_from::TryFrom;
10use minidom::Element;
11use error::Error;
12use ns;
13
14use helpers::Base64;
15
16generate_attribute!(
17 /// The list of available SASL mechanisms.
18 Mechanism, "mechanism", {
19 /// Uses no hashing mechanism and transmit the password in clear to the
20 /// server, using a single step.
21 Plain => "PLAIN",
22
23 /// Challenge-based mechanism using HMAC and SHA-1, allows both the
24 /// client and the server to avoid having to store the password in
25 /// clear.
26 ///
27 /// See https://tools.ietf.org/html/rfc5802
28 ScramSha1 => "SCRAM-SHA-1",
29
30 /// Same as [ScramSha1](#structfield.ScramSha1), with the addition of
31 /// channel binding.
32 ScramSha1Plus => "SCRAM-SHA-1-PLUS",
33
34 /// Same as [ScramSha1](#structfield.ScramSha1), but using SHA-256
35 /// instead of SHA-1 as the hash function.
36 ScramSha256 => "SCRAM-SHA-256",
37
38 /// Same as [ScramSha256](#structfield.ScramSha256), with the addition
39 /// of channel binding.
40 ScramSha256Plus => "SCRAM-SHA-256-PLUS",
41
42 /// Creates a temporary JID on login, which will be destroyed on
43 /// disconnect.
44 Anonymous => "ANONYMOUS",
45 }
46);
47
48generate_element!(
49 /// The first step of the SASL process, selecting the mechanism and sending
50 /// the first part of the handshake.
51 Auth, "auth", SASL,
52 attributes: [
53 /// The mechanism used.
54 mechanism: Mechanism = "mechanism" => required
55 ],
56 text: (
57 /// The content of the handshake.
58 data: Base64<Vec<u8>>
59 )
60);
61
62generate_element!(
63 /// In case the mechanism selected at the [auth](struct.Auth.html) step
64 /// requires a second step, the server sends this element with additional
65 /// data.
66 Challenge, "challenge", SASL,
67 text: (
68 /// The challenge data.
69 data: Base64<Vec<u8>>
70 )
71);
72
73generate_element!(
74 /// In case the mechanism selected at the [auth](struct.Auth.html) step
75 /// requires a second step, this contains the client’s response to the
76 /// server’s [challenge](struct.Challenge.html).
77 Response, "response", SASL,
78 text: (
79 /// The response data.
80 data: Base64<Vec<u8>>
81 )
82);
83
84generate_empty_element!(
85 /// Sent by the client at any point after [auth](struct.Auth.html) if it
86 /// wants to cancel the current authentication process.
87 Abort, "abort", SASL
88);
89
90generate_element!(
91 /// Sent by the server on SASL success.
92 Success, "success", SASL,
93 text: (
94 /// Possible data sent on success.
95 data: Base64<Vec<u8>>
96 )
97);
98
99generate_element_enum!(
100 /// List of possible failure conditions for SASL.
101 DefinedCondition, "defined-condition", SASL, {
102 /// The client aborted the authentication with
103 /// [abort](struct.Abort.html).
104 Aborted => "aborted",
105
106 /// The account the client is trying to authenticate against has been
107 /// disabled.
108 AccountDisabled => "account-disabled",
109
110 /// The credentials for this account have expired.
111 CredentialsExpired => "credentials-expired",
112
113 /// You must enable StartTLS or use direct TLS before using this
114 /// authentication mechanism.
115 EncryptionRequired => "encryption-required",
116
117 /// The base64 data sent by the client is invalid.
118 IncorrectEncoding => "incorrect-encoding",
119
120 /// The authzid provided by the client is invalid.
121 InvalidAuthzid => "invalid-authzid",
122
123 /// The client tried to use an invalid mechanism, or none.
124 InvalidMechanism => "invalid-mechanism",
125
126 /// The client sent a bad request.
127 MalformedRequest => "malformed-request",
128
129 /// The mechanism selected is weaker than what the server allows.
130 MechanismTooWeak => "mechanism-too-weak",
131
132 /// The credentials provided are invalid.
133 NotAuthorized => "not-authorized",
134
135 /// The server encountered an issue which may be fixed later, the
136 /// client should retry at some point.
137 TemporaryAuthFailure => "temporary-auth-failure",
138 }
139);
140
141type Lang = String;
142
143/// Sent by the server on SASL failure.
144#[derive(Debug, Clone)]
145pub struct Failure {
146 /// One of the allowed defined-conditions for SASL.
147 pub defined_condition: DefinedCondition,
148
149 /// A human-readable explanation for the failure.
150 pub texts: BTreeMap<Lang, String>,
151}
152
153impl TryFrom<Element> for Failure {
154 type Err = Error;
155
156 fn try_from(root: Element) -> Result<Failure, Error> {
157 check_self!(root, "failure", SASL);
158 check_no_attributes!(root, "failure");
159
160 let mut defined_condition = None;
161 let mut texts = BTreeMap::new();
162
163 for child in root.children() {
164 if child.is("text", ns::SASL) {
165 check_no_unknown_attributes!(child, "text", ["xml:lang"]);
166 check_no_children!(child, "text");
167 let lang = get_attr!(child, "xml:lang", default);
168 if texts.insert(lang, child.text()).is_some() {
169 return Err(Error::ParseError("Text element present twice for the same xml:lang in failure element."));
170 }
171 } else if child.has_ns(ns::SASL) {
172 if defined_condition.is_some() {
173 return Err(Error::ParseError("Failure must not have more than one defined-condition."));
174 }
175 check_no_attributes!(child, "defined-condition");
176 check_no_children!(child, "defined-condition");
177 let condition = match DefinedCondition::try_from(child.clone()) {
178 Ok(condition) => condition,
179 // TODO: do we really want to eat this error?
180 Err(_) => DefinedCondition::NotAuthorized,
181 };
182 defined_condition = Some(condition);
183 } else {
184 return Err(Error::ParseError("Unknown element in Failure."));
185 }
186 }
187 let defined_condition = defined_condition.ok_or(Error::ParseError("Failure must have a defined-condition."))?;
188
189 Ok(Failure {
190 defined_condition: defined_condition,
191 texts: texts,
192 })
193 }
194}
195
196impl From<Failure> for Element {
197 fn from(failure: Failure) -> Element {
198 Element::builder("failure")
199 .ns(ns::SASL)
200 .append(failure.defined_condition)
201 .append(failure.texts.into_iter().map(|(lang, text)| {
202 Element::builder("text")
203 .ns(ns::SASL)
204 .attr("xml:lang", lang)
205 .append(text)
206 .build()
207 }).collect::<Vec<_>>())
208 .build()
209 }
210}
211
212#[cfg(test)]
213mod tests {
214 use super::*;
215 use try_from::TryFrom;
216 use minidom::Element;
217
218 #[test]
219 fn test_size() {
220 assert_size!(Mechanism, 1);
221 assert_size!(Auth, 32);
222 assert_size!(Challenge, 24);
223 assert_size!(Response, 24);
224 assert_size!(Abort, 0);
225 assert_size!(Success, 24);
226 assert_size!(DefinedCondition, 1);
227 assert_size!(Failure, 32);
228 }
229
230 #[test]
231 fn test_simple() {
232 let elem: Element = "<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'/>".parse().unwrap();
233 let auth = Auth::try_from(elem).unwrap();
234 assert_eq!(auth.mechanism, Mechanism::Plain);
235 assert!(auth.data.is_empty());
236 }
237
238 #[test]
239 fn section_6_5_1() {
240 let elem: Element = "<failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'><aborted/></failure>".parse().unwrap();
241 let failure = Failure::try_from(elem).unwrap();
242 assert_eq!(failure.defined_condition, DefinedCondition::Aborted);
243 assert!(failure.texts.is_empty());
244 }
245
246 #[test]
247 fn section_6_5_2() {
248 let elem: Element = "<failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>
249 <account-disabled/>
250 <text xml:lang='en'>Call 212-555-1212 for assistance.</text>
251 </failure>".parse().unwrap();
252 let failure = Failure::try_from(elem).unwrap();
253 assert_eq!(failure.defined_condition, DefinedCondition::AccountDisabled);
254 assert_eq!(failure.texts["en"], String::from("Call 212-555-1212 for assistance."));
255 }
256}