1#[cfg(test)]
14mod integrity_test;
15
16use crate::attributes::*;
17use crate::message::*;
18use crate::opaque::opaque_string;
19use crate::password_algorithm::{PASSWORD_ALGORITHM_MD5, PASSWORD_ALGORITHM_SHA256};
20use crypto::{CryptoError, HashAlgorithm, HmacAlgorithm, RTCCrypto, SecretVec, constant_time_eq};
21use shared::error::*;
22use std::fmt;
23
24pub(crate) const CREDENTIALS_SEP: &str = ":";
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
29pub enum IntegrityAlgorithm {
30 Sha1,
32 Sha256,
34}
35
36impl IntegrityAlgorithm {
37 #[must_use]
39 pub const fn attr_type(self) -> AttrType {
40 match self {
41 Self::Sha1 => ATTR_MESSAGE_INTEGRITY,
42 Self::Sha256 => ATTR_MESSAGE_INTEGRITY_SHA256,
43 }
44 }
45
46 #[must_use]
48 pub const fn tag_len(self) -> usize {
49 match self {
50 Self::Sha1 => MESSAGE_INTEGRITY_SIZE,
51 Self::Sha256 => MESSAGE_INTEGRITY_SHA256_SIZE,
52 }
53 }
54
55 const fn hmac(self) -> HmacAlgorithm {
56 match self {
57 Self::Sha1 => HmacAlgorithm::Sha1,
58 Self::Sha256 => HmacAlgorithm::Sha256,
59 }
60 }
61}
62
63pub const MESSAGE_INTEGRITY_SIZE: usize = 20;
65pub const MESSAGE_INTEGRITY_SHA256_SIZE: usize = 32;
67pub const MESSAGE_INTEGRITY_SHA256_MIN_SIZE: usize = 16;
69
70fn crypto_error(error: CryptoError) -> Error {
71 Error::Crypto(error.to_string())
72}
73
74fn hmac_input(m: &Message, start: usize, value_len: usize) -> Result<([u8; 2], &[u8], &[u8])> {
80 if start < MESSAGE_HEADER_SIZE || m.raw.len() < start {
81 return Err(Error::ErrUnexpectedHeaderEof);
82 }
83 let length = start - MESSAGE_HEADER_SIZE
84 + ATTRIBUTE_HEADER_SIZE
85 + nearest_padded_value_length(value_len);
86 let length = u16::try_from(length).map_err(|_| Error::ErrPacketTooBig)?;
87 Ok((length.to_be_bytes(), &m.raw[..2], &m.raw[4..start]))
88}
89
90fn add_integrity(
92 m: &mut Message,
93 algorithm: IntegrityAlgorithm,
94 tag_len: usize,
95 key: &[u8],
96 crypto: &dyn RTCCrypto,
97) -> Result<()> {
98 for a in &m.attributes.0 {
99 if a.typ == ATTR_FINGERPRINT {
102 return Err(Error::ErrFingerprintBeforeIntegrity);
103 }
104 }
105 let start = MESSAGE_HEADER_SIZE + m.length as usize;
106 let mut tag = vec![0_u8; algorithm.tag_len()];
107 {
108 let (length, type_field, rest) = hmac_input(m, start, tag_len)?;
109 crypto
112 .new_hmac(algorithm.hmac(), key)
113 .and_then(|mut mac| mac.sign(&[type_field, &length, rest], &mut tag))
114 .map_err(crypto_error)?;
115 }
116 m.add(algorithm.attr_type(), &tag[..tag_len]);
117 Ok(())
118}
119
120pub(crate) fn check_integrity(
123 m: &Message,
124 algorithm: IntegrityAlgorithm,
125 min_tag_len: usize,
126 key: &[u8],
127 crypto: &dyn RTCCrypto,
128) -> Result<()> {
129 let index = m
130 .position(algorithm.attr_type())
131 .ok_or(Error::ErrAttributeNotFound)?;
132 let value = &m.attributes.0[index].value;
133 let full = algorithm.tag_len();
134 if value.len() > full || value.len() < min_tag_len || !value.len().is_multiple_of(PADDING) {
137 return Err(Error::ErrIntegrityMismatch);
138 }
139 let (length, type_field, rest) = hmac_input(m, m.attribute_offset(index), value.len())?;
140 let input: [&[u8]; 3] = [type_field, &length, rest];
141 let mut mac = crypto
142 .new_hmac(algorithm.hmac(), key)
143 .map_err(crypto_error)?;
144 let result = if value.len() == full {
145 mac.verify(&input, value)
146 } else {
147 let mut tag = vec![0_u8; full];
148 mac.sign(&input, &mut tag).and_then(|()| {
149 if constant_time_eq(&tag[..value.len()], value) {
150 Ok(())
151 } else {
152 Err(CryptoError::AuthenticationFailed)
153 }
154 })
155 };
156 match result {
157 Ok(()) => Ok(()),
158 Err(CryptoError::AuthenticationFailed | CryptoError::InvalidTagLength { .. }) => {
159 Err(Error::ErrIntegrityMismatch)
160 }
161 Err(error) => Err(crypto_error(error)),
162 }
163}
164
165pub fn long_term_key(
182 algorithm: u16,
183 username: &str,
184 realm: &str,
185 password: &str,
186 crypto: &dyn RTCCrypto,
187) -> Result<Vec<u8>> {
188 let (hash, key_len) = match algorithm {
189 PASSWORD_ALGORITHM_MD5 => (HashAlgorithm::Md5, 16),
190 PASSWORD_ALGORITHM_SHA256 => (HashAlgorithm::Sha256, 32),
191 other => {
192 return Err(Error::Other(format!(
193 "password algorithm {other:#06x} is not supported"
194 )));
195 }
196 };
197 let credentials = SecretVec::new(
198 [
199 opaque_or_empty(username)?,
200 opaque_or_empty(realm)?,
201 opaque_or_empty(password)?,
202 ]
203 .join(CREDENTIALS_SEP)
204 .into_bytes(),
205 );
206 let key = crypto
207 .hash(hash, credentials.as_ref())
208 .map_err(crypto_error)?;
209 if key.len() != key_len {
210 return Err(Error::Crypto(format!(
211 "provider returned an invalid digest length: {}",
212 key.len()
213 )));
214 }
215 Ok(key)
216}
217
218fn opaque_or_empty(s: &str) -> Result<String> {
219 if s.is_empty() {
220 Ok(String::new())
221 } else {
222 opaque_string(s).map(|s| s.into_owned())
223 }
224}
225
226#[derive(Clone)]
230pub struct MessageIntegrity<'a> {
234 key: SecretVec,
235 crypto: &'a dyn RTCCrypto,
236}
237
238impl<'a> fmt::Display for MessageIntegrity<'a> {
239 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240 write!(
241 f,
242 "MESSAGE-INTEGRITY key: [REDACTED; {} bytes]",
243 self.key.len()
244 )
245 }
246}
247
248impl<'a> Setter for MessageIntegrity<'a> {
249 fn add_to(&self, m: &mut Message) -> Result<()> {
253 add_integrity(
254 m,
255 IntegrityAlgorithm::Sha1,
256 MESSAGE_INTEGRITY_SIZE,
257 self.key.as_ref(),
258 self.crypto,
259 )
260 }
261}
262
263impl<'a> MessageIntegrity<'a> {
264 #[must_use]
266 pub fn new_raw_integrity_with_provider(
267 key: impl Into<Vec<u8>>,
268 crypto: &'a dyn RTCCrypto,
269 ) -> Self {
270 Self {
271 key: SecretVec::new(key.into()),
272 crypto,
273 }
274 }
275
276 #[must_use]
282 pub fn new_short_term_integrity_with_provider(
283 password: String,
284 crypto: &'a dyn RTCCrypto,
285 ) -> Self {
286 Self::new_raw_integrity_with_provider(password.into_bytes(), crypto)
287 }
288
289 pub fn short_term(password: &str, crypto: &'a dyn RTCCrypto) -> Result<Self> {
296 let key = opaque_string(password)?.into_owned().into_bytes();
297 Ok(Self::new_raw_integrity_with_provider(key, crypto))
298 }
299
300 pub fn new_long_term_integrity_with_provider(
303 username: String,
304 realm: String,
305 password: String,
306 crypto: &'a dyn RTCCrypto,
307 ) -> Result<Self> {
308 let key = MessageIntegrity::long_term_integrity_key(username, realm, password, crypto)?;
309 Ok(Self::new_raw_integrity_with_provider(key, crypto))
310 }
311
312 pub fn long_term_integrity_key(
315 username: String,
316 realm: String,
317 password: String,
318 crypto: &'a dyn RTCCrypto,
319 ) -> Result<Vec<u8>> {
320 let password = SecretVec::new(password.into_bytes());
321 let password = std::str::from_utf8(password.as_ref())
322 .map_err(|_| Error::Other("the password is not UTF-8".to_owned()))?;
323 long_term_key(PASSWORD_ALGORITHM_MD5, &username, &realm, password, crypto)
324 }
325
326 pub fn check(m: &mut Message, key: &[u8], crypto: &dyn RTCCrypto) -> Result<()> {
335 check_integrity(
336 m,
337 IntegrityAlgorithm::Sha1,
338 MESSAGE_INTEGRITY_SIZE,
339 key,
340 crypto,
341 )
342 }
343}
344
345#[derive(Clone)]
351pub struct MessageIntegritySha256<'a> {
352 key: SecretVec,
353 tag_len: usize,
354 crypto: &'a dyn RTCCrypto,
355}
356
357impl<'a> fmt::Display for MessageIntegritySha256<'a> {
358 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
359 write!(
360 f,
361 "MESSAGE-INTEGRITY-SHA256 key: [REDACTED; {} bytes]",
362 self.key.len()
363 )
364 }
365}
366
367impl<'a> Setter for MessageIntegritySha256<'a> {
368 fn add_to(&self, m: &mut Message) -> Result<()> {
371 add_integrity(
372 m,
373 IntegrityAlgorithm::Sha256,
374 self.tag_len,
375 self.key.as_ref(),
376 self.crypto,
377 )
378 }
379}
380
381impl<'a> MessageIntegritySha256<'a> {
382 #[must_use]
384 pub fn new_raw(key: impl Into<Vec<u8>>, crypto: &'a dyn RTCCrypto) -> Self {
385 Self {
386 key: SecretVec::new(key.into()),
387 tag_len: MESSAGE_INTEGRITY_SHA256_SIZE,
388 crypto,
389 }
390 }
391
392 pub fn short_term(password: &str, crypto: &'a dyn RTCCrypto) -> Result<Self> {
399 let key = opaque_string(password)?.into_owned().into_bytes();
400 Ok(Self::new_raw(key, crypto))
401 }
402
403 pub fn long_term(
410 password_algorithm: u16,
411 username: &str,
412 realm: &str,
413 password: &str,
414 crypto: &'a dyn RTCCrypto,
415 ) -> Result<Self> {
416 let key = long_term_key(password_algorithm, username, realm, password, crypto)?;
417 Ok(Self::new_raw(key, crypto))
418 }
419
420 pub fn with_tag_len(mut self, tag_len: usize) -> Result<Self> {
427 if !(MESSAGE_INTEGRITY_SHA256_MIN_SIZE..=MESSAGE_INTEGRITY_SHA256_SIZE).contains(&tag_len)
428 || !tag_len.is_multiple_of(PADDING)
429 {
430 return Err(Error::ErrAttributeSizeInvalid);
431 }
432 self.tag_len = tag_len;
433 Ok(self)
434 }
435
436 pub fn check(m: &Message, key: &[u8], crypto: &dyn RTCCrypto) -> Result<()> {
446 Self::check_truncated(m, MESSAGE_INTEGRITY_SHA256_SIZE, key, crypto)
447 }
448
449 pub fn check_truncated(
456 m: &Message,
457 min_tag_len: usize,
458 key: &[u8],
459 crypto: &dyn RTCCrypto,
460 ) -> Result<()> {
461 check_integrity(
462 m,
463 IntegrityAlgorithm::Sha256,
464 min_tag_len.max(MESSAGE_INTEGRITY_SHA256_MIN_SIZE),
465 key,
466 crypto,
467 )
468 }
469}