1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
use std::borrow::Cow;
use std::io;
use data_encoding::base64;
use rand::distributions::IndependentSample;
use rand::distributions::range::Range;
use rand::os::OsRng;
use rand::Rng;
use ring::digest::{digest, SHA256, Digest};
use ring::hmac::{SigningKey, SigningContext, sign};
use ring::pbkdf2::{HMAC_SHA256, derive};
use error::{Error, Kind, Field};
use super::DebugDigest;
const NONCE_LENGTH: usize = 24;
const SHA256_LEN: usize = 32;
fn parse_server_first(data: &str) -> Result<(&str, Vec<u8>, u16), Error> {
if data.len() < 2 {
return Err(Error::Protocol(Kind::ExpectedField(Field::Nonce)));
}
let mut parts = data.split(',').peekable();
match parts.peek() {
Some(part) if &part.as_bytes()[..2] == b"m=" => {
return Err(Error::UnsupportedExtension);
}
Some(_) => {}
None => {
return Err(Error::Protocol(Kind::ExpectedField(Field::Nonce)));
}
}
let nonce = match parts.next() {
Some(part) if &part.as_bytes()[..2] == b"r=" => &part[2..],
_ => {
return Err(Error::Protocol(Kind::ExpectedField(Field::Nonce)));
}
};
let salt = match parts.next() {
Some(part) if &part.as_bytes()[..2] == b"s=" => {
try!(base64::decode(part[2..].as_bytes())
.map_err(|_| Error::Protocol(Kind::InvalidField(Field::Salt))))
}
_ => {
return Err(Error::Protocol(Kind::ExpectedField(Field::Salt)));
}
};
let iterations = match parts.next() {
Some(part) if &part.as_bytes()[..2] == b"i=" => {
try!(part[2..]
.parse()
.map_err(|_| Error::Protocol(Kind::InvalidField(Field::Salt))))
}
_ => {
return Err(Error::Protocol(Kind::ExpectedField(Field::Iterations)));
}
};
Ok((nonce, salt, iterations))
}
#[derive(Debug)]
pub struct ClientFirst<'a> {
gs2header: Cow<'static, str>,
password: &'a str,
nonce: String,
authcid: &'a str,
}
impl<'a> ClientFirst<'a> {
pub fn new(authcid: &'a str, password: &'a str, authzid: Option<&'a str>) -> io::Result<Self> {
let rng = try!(OsRng::new());
Ok(Self::with_rng(authcid, password, authzid, rng))
}
pub fn with_rng<R: Rng>(authcid: &'a str,
password: &'a str,
authzid: Option<&'a str>,
mut rng: R)
-> Self {
let gs2header: Cow<'static, str> = match authzid {
Some(authzid) => format!("n,a={},", authzid).into(),
None => "n,,".into(),
};
let range = Range::new(33, 125);
let nonce: String = (0..NONCE_LENGTH)
.map(move |_| {
let x: u8 = range.ind_sample(&mut rng);
if x > 43 {
(x + 1) as char
} else {
x as char
}
})
.collect();
ClientFirst {
gs2header: gs2header,
password: password,
authcid: authcid,
nonce: nonce,
}
}
pub fn client_first(self) -> (ServerFirst<'a>, String) {
let escaped_authcid: Cow<'a, str> =
if self.authcid.chars().any(|chr| chr == ',' || chr == '=') {
self.authcid.into()
} else {
self.authcid.replace(',', "=2C").replace('=', "=3D").into()
};
let client_first_bare = format!("n={},r={}", escaped_authcid, self.nonce);
let client_first = format!("{}{}", self.gs2header, client_first_bare);
let server_first = ServerFirst {
gs2header: self.gs2header,
password: self.password,
client_nonce: self.nonce,
client_first_bare: client_first_bare,
};
(server_first, client_first)
}
}
#[derive(Debug)]
pub struct ServerFirst<'a> {
gs2header: Cow<'static, str>,
password: &'a str,
client_nonce: String,
client_first_bare: String,
}
impl<'a> ServerFirst<'a> {
pub fn handle_server_first(self, server_first: &str) -> Result<ClientFinal, Error> {
fn sign_slice(key: &SigningKey, slice: &[&[u8]]) -> Digest {
let mut signature_context = SigningContext::with_key(key);
for item in slice {
signature_context.update(item);
}
signature_context.sign()
}
let (nonce, salt, iterations) = try!(parse_server_first(server_first));
if !nonce.starts_with(&self.client_nonce) {
return Err(Error::Protocol(Kind::InvalidNonce));
}
let client_final_without_proof = format!("c={},r={}",
base64::encode(self.gs2header.as_bytes()),
nonce);
let auth_message = [self.client_first_bare.as_bytes(),
b",",
server_first.as_bytes(),
b",",
client_final_without_proof.as_bytes()];
let mut salted_password = [0u8; SHA256_LEN];
derive(&HMAC_SHA256,
iterations as usize,
&salt,
self.password.as_bytes(),
&mut salted_password);
let salted_password_signing_key = SigningKey::new(&SHA256, &salted_password);
let client_key = sign(&salted_password_signing_key, b"Client Key");
let server_key = sign(&salted_password_signing_key, b"Server Key");
let stored_key = digest(&SHA256, client_key.as_ref());
let stored_key_signing_key = SigningKey::new(&SHA256, stored_key.as_ref());
let client_signature = sign_slice(&stored_key_signing_key, &auth_message);
let server_signature_signing_key = SigningKey::new(&SHA256, server_key.as_ref());
let server_signature = sign_slice(&server_signature_signing_key, &auth_message);
let mut client_proof = [0u8; SHA256_LEN];
let xor_iter =
client_key.as_ref().iter().zip(client_signature.as_ref()).map(|(k, s)| k ^ s);
for (p, x) in client_proof.iter_mut().zip(xor_iter) {
*p = x
}
let client_final = format!("c={},r={},p={}",
base64::encode(self.gs2header.as_bytes()),
nonce,
base64::encode(&client_proof));
Ok(ClientFinal {
server_signature: DebugDigest(server_signature),
client_final: client_final,
})
}
}
#[derive(Debug)]
pub struct ClientFinal {
server_signature: DebugDigest,
client_final: String,
}
impl ClientFinal {
#[inline]
pub fn client_final(self) -> (ServerFinal, String) {
let server_final = ServerFinal { server_signature: self.server_signature };
(server_final, self.client_final)
}
}
#[derive(Debug)]
pub struct ServerFinal {
server_signature: DebugDigest,
}
impl ServerFinal {
pub fn handle_server_final(self, server_final: &str) -> Result<(), Error> {
if server_final.len() < 2 {
return Err(Error::Protocol(Kind::ExpectedField(Field::VerifyOrError)));
}
match &server_final[..2] {
"v=" => {
let verifier = try!(base64::decode(&server_final.as_bytes()[2..])
.map_err(|_| Error::Protocol(Kind::InvalidField(Field::VerifyOrError))));
if self.server_signature.as_ref() == &*verifier {
Ok(())
} else {
Err(Error::InvalidServer)
}
}
"e=" => Err(Error::Authentication(server_final[2..].to_string())),
_ => Err(Error::Protocol(Kind::ExpectedField(Field::VerifyOrError))),
}
}
}