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
#[cfg(test)]
mod integrity_test;
use crate::checks::*;
use crate::errors::*;
use crate::message::*;
use util::Error;
use std::fmt;
use crate::attributes::{nearest_padded_value_length, ATTR_FINGERPRINT, ATTR_MESSAGE_INTEGRITY};
use md5::{Digest, Md5};
use ring::hmac;
pub(crate) const CREDENTIALS_SEP: &str = ":";
#[derive(Default, Clone)]
pub struct MessageIntegrity(pub Vec<u8>);
fn new_hmac(key: &[u8], message: &[u8]) -> Vec<u8> {
let mac = hmac::Key::new(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, key);
hmac::sign(&mac, message).as_ref().to_vec()
}
impl fmt::Display for MessageIntegrity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "KEY: 0x{:x?}", self.0)
}
}
impl Setter for MessageIntegrity {
fn add_to(&self, m: &mut Message) -> Result<(), Error> {
for a in &m.attributes.0 {
if a.typ == ATTR_FINGERPRINT {
return Err(ERR_FINGERPRINT_BEFORE_INTEGRITY.clone());
}
}
let length = m.length;
m.length += (MESSAGE_INTEGRITY_SIZE + ATTRIBUTE_HEADER_SIZE) as u32;
m.write_length();
let v = new_hmac(&self.0, &m.raw);
m.length = length;
m.add(ATTR_MESSAGE_INTEGRITY, &v);
Ok(())
}
}
pub(crate) const MESSAGE_INTEGRITY_SIZE: usize = 20;
impl MessageIntegrity {
pub fn new_long_term_integrity(username: String, realm: String, password: String) -> Self {
let s = vec![username, realm, password].join(CREDENTIALS_SEP);
let mut h = Md5::new();
h.update(s.as_bytes());
MessageIntegrity(h.finalize().as_slice().to_vec())
}
pub fn new_short_term_integrity(password: String) -> Self {
MessageIntegrity(password.as_bytes().to_vec())
}
pub fn check(&self, m: &mut Message) -> Result<(), Error> {
let v = m.get(ATTR_MESSAGE_INTEGRITY)?;
let length = m.length as usize;
let mut after_integrity = false;
let mut size_reduced = 0;
for a in &m.attributes.0 {
if after_integrity {
size_reduced += nearest_padded_value_length(a.length as usize);
size_reduced += ATTRIBUTE_HEADER_SIZE;
}
if a.typ == ATTR_MESSAGE_INTEGRITY {
after_integrity = true;
}
}
m.length -= size_reduced as u32;
m.write_length();
let start_of_hmac = MESSAGE_HEADER_SIZE + m.length as usize
- (ATTRIBUTE_HEADER_SIZE + MESSAGE_INTEGRITY_SIZE);
let b = &m.raw[..start_of_hmac];
let expected = new_hmac(&self.0, b);
m.length = length as u32;
m.write_length();
check_hmac(&v, &expected)
}
}