stun_rs/attributes/stun/
password_algorithms.rs

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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use crate::attributes::stun::PasswordAlgorithm;
use crate::attributes::{stunt_attribute, DecodeAttributeValue, EncodeAttributeValue};
use crate::common::{check_buffer_boundaries, fill_padding_value, padding};
use crate::context::{AttributeDecoderContext, AttributeEncoderContext};
use crate::StunError;
use std::rc::Rc;

//  0                   1                   2                   3
//  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  |         Algorithm 1           | Algorithm 1 Parameters Length |
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  |                    Algorithm 1 Parameters (variable)
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  |         Algorithm 2           | Algorithm 2 Parameters Length |
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  |                    Algorithm 2 Parameters (variable)
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  |                                                             ...

const PASSWORD_ALGORITHMS: u16 = 0x8002;

/// The [`PasswordAlgorithms`] attribute may be present in requests and
/// responses.  It contains the list of algorithms that the server can
/// use to derive the long-term password.
///
/// # Examples
///```rust
/// # use stun_rs::attributes::stun::{PasswordAlgorithm, PasswordAlgorithms};
/// # use stun_rs::{Algorithm, AlgorithmId};
/// // Creates an empty password algorithms attribute
/// let mut attr = PasswordAlgorithms::default();
/// assert_eq!(attr.iter().count(), 0);
///
/// // Adds a password algorithm attribute
/// attr.add(PasswordAlgorithm::new(Algorithm::from(AlgorithmId::MD5)));
/// assert_eq!(attr.iter().count(), 1);
///```
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct PasswordAlgorithms {
    algorithms: Rc<Vec<PasswordAlgorithm>>,
}

impl PasswordAlgorithms {
    /// Adds a new password algorithm.
    pub fn add(&mut self, algorithm: PasswordAlgorithm) {
        Rc::get_mut(&mut self.algorithms).unwrap().push(algorithm);
    }

    /// Return the array of password attributes
    pub fn password_algorithms(&self) -> &[PasswordAlgorithm] {
        &self.algorithms
    }

    /// Returns an iterator over the passwords attributes.
    pub fn iter(&self) -> impl Iterator<Item = &PasswordAlgorithm> {
        self.algorithms.iter()
    }
}

impl IntoIterator for PasswordAlgorithms {
    type Item = PasswordAlgorithm;
    type IntoIter = std::vec::IntoIter<PasswordAlgorithm>;

    fn into_iter(self) -> Self::IntoIter {
        self.algorithms.clone().as_ref().clone().into_iter()
    }
}

impl From<Vec<PasswordAlgorithm>> for PasswordAlgorithms {
    fn from(v: Vec<PasswordAlgorithm>) -> Self {
        Self {
            algorithms: Rc::new(v),
        }
    }
}

impl DecodeAttributeValue for PasswordAlgorithms {
    fn decode(ctx: AttributeDecoderContext) -> Result<(Self, usize), StunError> {
        let mut attr = PasswordAlgorithms::default();

        let raw_msg = ctx.decoded_message();
        let raw_value = ctx.raw_value();

        let mut size = 0;
        let mut total_size = 0;
        while total_size < raw_value.len() {
            total_size += padding(size);
            check_buffer_boundaries(raw_value, total_size)?;
            let attr_ctx =
                AttributeDecoderContext::new(ctx.context(), raw_msg, &raw_value[total_size..]);
            let (val, len) = PasswordAlgorithm::decode(attr_ctx)?;
            attr.add(val);
            total_size += len;
            size = len;
        }

        Ok((attr, total_size))
    }
}

impl EncodeAttributeValue for PasswordAlgorithms {
    fn encode(&self, mut ctx: AttributeEncoderContext) -> Result<usize, StunError> {
        let mut it = self.algorithms.iter().peekable();
        let mut size = 0;

        while let Some(attr) = it.next() {
            let len;
            {
                let raw_msg = ctx.encoded_message();
                let raw_value = ctx.raw_value_mut();
                check_buffer_boundaries(raw_value, size)?;
                let attr_ctx = AttributeEncoderContext::new(None, raw_msg, &mut raw_value[size..]);
                len = attr.encode(attr_ctx)?;
                size += len;
            }
            if it.peek().is_some() {
                let padding = padding(len);
                let padding_value = ctx.context().unwrap_or_default().padding();
                let raw_value = ctx.raw_value_mut();
                fill_padding_value(&mut raw_value[size..], padding, padding_value)?;
                size += padding;
            }
        }

        Ok(size)
    }
}

impl crate::attributes::AsVerifiable for PasswordAlgorithms {}

stunt_attribute!(PasswordAlgorithms, PASSWORD_ALGORITHMS);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::StunErrorType;
    use crate::StunAttribute;
    use crate::{Algorithm, AlgorithmId};

    #[test]
    fn constructor() {
        let mut attr = PasswordAlgorithms::default();
        assert_eq!(attr.iter().count(), 0);

        attr.add(PasswordAlgorithm::new(Algorithm::from(AlgorithmId::MD5)));
        assert_eq!(attr.iter().count(), 1);

        attr.add(PasswordAlgorithm::new(Algorithm::from(AlgorithmId::SHA256)));
        assert_eq!(attr.iter().count(), 2);

        let mut iter = attr.password_algorithms().iter();
        let algorithm = iter.next().expect("Expected algorithm");
        assert_eq!(algorithm.algorithm(), AlgorithmId::MD5);

        let algorithm = iter.next().expect("Expected algorithm");
        assert_eq!(algorithm.algorithm(), AlgorithmId::SHA256);

        // No more attributes expected
        assert!(iter.next().is_none());

        let attributes = vec![
            PasswordAlgorithm::new(Algorithm::from(AlgorithmId::MD5)),
            PasswordAlgorithm::new(Algorithm::from(AlgorithmId::SHA256)),
        ];
        let attr_1 = PasswordAlgorithms::from(attributes);

        assert_eq!(attr, attr_1);
    }

    #[test]
    fn decode_password_algorithms_attribute_value() {
        let dummy_msg = [];
        let buffer = [];
        let ctx = AttributeDecoderContext::new(None, &dummy_msg, &buffer);
        let (attr, size) =
            PasswordAlgorithms::decode(ctx).expect("Could not decode PasswordAlgorithms");
        assert_eq!(attr.into_iter().len(), 0);
        assert_eq!(size, 0);

        let buffer = [0x00, 0x01, 0x00, 0x00];
        let ctx = AttributeDecoderContext::new(None, &dummy_msg, &buffer);
        let (attr, size) =
            PasswordAlgorithms::decode(ctx).expect("Could not decode PasswordAlgorithms");
        assert_eq!(attr.into_iter().len(), 1);
        assert_eq!(size, 4);

        let buffer = [0x00, 0x01, 0x00, 0x02, 0x01, 0x02];
        let ctx = AttributeDecoderContext::new(None, &dummy_msg, &buffer);
        let (attr, size) =
            PasswordAlgorithms::decode(ctx).expect("Could not decode PasswordAlgorithms");
        assert_eq!(attr.into_iter().len(), 1);
        assert_eq!(size, 6);

        // First algorithm attribute has 2 bytes of padding at the positions 6 and 7
        let buffer = [
            0x00, 0x01, 0x00, 0x02, 0x01, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x03,
        ];
        let ctx = AttributeDecoderContext::new(None, &dummy_msg, &buffer);
        let (attr, size) =
            PasswordAlgorithms::decode(ctx).expect("Could not decode PasswordAlgorithms");
        assert_eq!(attr.into_iter().len(), 2);
        assert_eq!(size, 13);
    }

    #[test]
    fn decode_password_algorithms_attribute_value_error() {
        let dummy_msg = [];
        let buffer = [0x00, 0x01, 0x00, 0x01];
        let ctx = AttributeDecoderContext::new(None, &dummy_msg, &buffer);
        assert_eq!(
            PasswordAlgorithms::decode(ctx).expect_err("Error expected"),
            StunErrorType::SmallBuffer
        );

        let buffer = [0x00, 0x01, 0x00, 0x00, 0x23];
        let ctx = AttributeDecoderContext::new(None, &dummy_msg, &buffer);
        assert_eq!(
            PasswordAlgorithms::decode(ctx).expect_err("Error expected"),
            StunErrorType::SmallBuffer
        );
    }

    #[test]
    fn decode_password_algorithms_attribute() {
        let dummy_msg = [];
        let buffer = [0x00, 0x01, 0x00, 0x00];
        let ctx = AttributeDecoderContext::new(None, &dummy_msg, &buffer);
        let (attr, size) =
            PasswordAlgorithms::decode(ctx).expect("Could not decode PasswordAlgorithms");
        assert_eq!(size, 4);
        let mut iter = attr.into_iter();
        assert_eq!(iter.len(), 1);
        let val = iter
            .next()
            .expect("Can not get password algorithm attribute");
        assert_eq!(val.algorithm(), AlgorithmId::MD5);

        let buffer = [0x00, 0x01, 0x00, 0x02, 0x01, 0x02];
        let ctx = AttributeDecoderContext::new(None, &dummy_msg, &buffer);
        let (attr, size) =
            PasswordAlgorithms::decode(ctx).expect("Could not decode PasswordAlgorithms");
        assert_eq!(size, 6);
        let mut iter = attr.into_iter();
        assert_eq!(iter.len(), 1);
        let val = iter
            .next()
            .expect("Can not get password algorithm attribute");
        assert_eq!(val.algorithm(), AlgorithmId::MD5);
        assert_eq!(val.parameters(), Some([0x01, 0x02].as_slice()));

        // First algorithm attribute has 2 bytes of padding
        let buffer = [
            0x00, 0x01, 0x00, 0x02, 0x01, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x03,
        ];
        let ctx = AttributeDecoderContext::new(None, &dummy_msg, &buffer);
        let (attr, size) =
            PasswordAlgorithms::decode(ctx).expect("Could not decode PasswordAlgorithms");
        assert_eq!(size, 13);
        let mut iter = attr.into_iter();
        assert_eq!(iter.len(), 2);

        let val = iter
            .next()
            .expect("Can not get password algorithm attribute");
        assert_eq!(val.algorithm(), AlgorithmId::MD5);
        assert_eq!(val.parameters(), Some([0x01, 0x02].as_slice()));

        let val = iter
            .next()
            .expect("Can not get password algorithm attribute");
        assert_eq!(val.algorithm(), AlgorithmId::SHA256);
        assert_eq!(val.parameters(), Some([0x03].as_slice()));
    }

    #[test]
    fn decode_password_algorithms_attribute_error() {
        let dummy_msg = [];
        let buffer = [0x00, 0x01, 0x00];
        let ctx = AttributeDecoderContext::new(None, &dummy_msg, &buffer);
        let result = PasswordAlgorithms::decode(ctx);
        assert_eq!(
            result.expect_err("Error expected"),
            StunErrorType::SmallBuffer
        );
    }

    #[test]
    fn encode_password_algorithms_attribute_value() {
        let dummy_msg: [u8; 0] = [0x0; 0];
        let mut buffer = [];
        let attr = PasswordAlgorithms::default();
        let ctx = AttributeEncoderContext::new(None, &dummy_msg, &mut buffer);
        let result = attr.encode(ctx);
        assert_eq!(result, Ok(0));

        let mut buffer: [u8; 4] = [0x0; 4];
        let mut attr = PasswordAlgorithms::default();
        attr.add(PasswordAlgorithm::new(Algorithm::from(AlgorithmId::MD5)));
        let ctx = AttributeEncoderContext::new(None, &dummy_msg, &mut buffer);
        let result = attr.encode(ctx);
        let expected_buffer = [0x00, 0x01, 0x00, 0x00];
        assert_eq!(result, Ok(4));
        assert_eq!(&buffer[..], &expected_buffer[..]);

        let mut buffer: [u8; 6] = [0x0; 6];
        let mut attr = PasswordAlgorithms::default();
        let params = [0x01, 0x02];
        let algorithm = Algorithm::new(AlgorithmId::MD5, params.as_ref());
        attr.add(PasswordAlgorithm::new(algorithm));
        let ctx = AttributeEncoderContext::new(None, &dummy_msg, &mut buffer);
        let result = attr.encode(ctx);
        let expected_buffer = [0x00, 0x01, 0x00, 0x02, 0x01, 0x02];
        assert_eq!(result, Ok(6));
        assert_eq!(&buffer[..], &expected_buffer[..]);

        // Add two PASSWORD-AGORITHM attributes, the first one must fill 2 bytes of padding
        let mut buffer: [u8; 13] = [0x0; 13];
        let mut attr = PasswordAlgorithms::default();
        let algorithm = Algorithm::new(AlgorithmId::MD5, params.as_ref());
        attr.add(PasswordAlgorithm::new(algorithm));

        let params = [0x03];
        let algorithm = Algorithm::new(AlgorithmId::SHA256, params.as_ref());
        attr.add(PasswordAlgorithm::new(algorithm));
        let ctx = AttributeEncoderContext::new(None, &dummy_msg, &mut buffer);
        let result = attr.encode(ctx);
        let expected_buffer = [
            0x00, 0x01, 0x00, 0x02, 0x01, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x03,
        ];
        assert_eq!(result, Ok(13));
        assert_eq!(&buffer[..], &expected_buffer[..]);
    }

    #[test]
    fn encode_password_algorithms_attribute_value_error() {
        let dummy_msg: [u8; 0] = [0x0; 0];
        let mut buffer = [];
        let mut attr = PasswordAlgorithms::default();
        attr.add(PasswordAlgorithm::new(Algorithm::from(AlgorithmId::MD5)));
        let ctx = AttributeEncoderContext::new(None, &dummy_msg, &mut buffer);
        let result = attr.encode(ctx);
        assert_eq!(
            result.expect_err("Error expected"),
            StunErrorType::SmallBuffer
        );

        let mut buffer: [u8; 3] = [0x0; 3];
        let mut attr = PasswordAlgorithms::default();
        attr.add(PasswordAlgorithm::new(Algorithm::from(AlgorithmId::MD5)));
        let ctx = AttributeEncoderContext::new(None, &dummy_msg, &mut buffer);
        let result = attr.encode(ctx);
        assert_eq!(
            result.expect_err("Error expected"),
            StunErrorType::SmallBuffer
        );
    }

    #[test]
    fn encode_password_algorithms_attribute() {
        let dummy_msg: [u8; 0] = [];
        let mut buffer = [];
        let attr = PasswordAlgorithms::default();
        let ctx = AttributeEncoderContext::new(None, &dummy_msg, &mut buffer);
        let result = attr.encode(ctx);
        let expected_buffer: [u8; 0] = [];
        assert_eq!(result, Ok(0));
        assert_eq!(&buffer[..], &expected_buffer[..]);

        let mut buffer: [u8; 4] = [0x0; 4];
        let mut attr = PasswordAlgorithms::default();
        attr.add(PasswordAlgorithm::new(Algorithm::from(AlgorithmId::MD5)));
        let ctx = AttributeEncoderContext::new(None, &dummy_msg, &mut buffer);
        let result = attr.encode(ctx);
        let expected_buffer = [0x00, 0x01, 0x00, 0x00];
        assert_eq!(result, Ok(4));
        assert_eq!(&buffer[..], &expected_buffer[..]);

        let mut buffer: [u8; 13] = [0x0; 13];
        let params = [0x01, 0x02];
        let mut attr = PasswordAlgorithms::default();
        let algorithm = Algorithm::new(AlgorithmId::MD5, params.as_ref());
        attr.add(PasswordAlgorithm::new(algorithm));

        let params = [0x03];
        let algorithm = Algorithm::new(AlgorithmId::SHA256, params.as_ref());
        attr.add(PasswordAlgorithm::new(algorithm));

        let ctx = AttributeEncoderContext::new(None, &dummy_msg, &mut buffer);
        let result = attr.encode(ctx);
        let expected_buffer = [
            0x00, 0x01, 0x00, 0x02, 0x01, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x03,
        ];
        assert_eq!(result, Ok(13));
        assert_eq!(&buffer[..], &expected_buffer[..]);
    }

    #[test]
    fn encode_password_algorithms_attribute_error() {
        let dummy_msg: [u8; 0] = [0x0; 0];

        let mut buffer: [u8; 3] = [0x0; 3];
        let mut attr = PasswordAlgorithms::default();
        attr.add(PasswordAlgorithm::new(Algorithm::from(AlgorithmId::MD5)));
        let ctx = AttributeEncoderContext::new(None, &dummy_msg, &mut buffer);
        let result = attr.encode(ctx);
        assert_eq!(
            result.expect_err("Error expected"),
            StunErrorType::SmallBuffer
        );
    }

    #[test]
    fn password_algorithms_attribute() {
        let attr = StunAttribute::PasswordAlgorithms(PasswordAlgorithms::default());
        assert!(attr.is_password_algorithms());
        assert!(attr.as_password_algorithms().is_ok());
        assert!(attr.as_unknown().is_err());

        assert!(!attr.attribute_type().is_comprehension_required());
        assert!(attr.attribute_type().is_comprehension_optional());

        let dbg_fmt = format!("{:?}", attr);
        assert_eq!(
            "PasswordAlgorithms(PasswordAlgorithms { algorithms: [] })",
            dbg_fmt
        );
    }
}