1use std::collections::HashMap;
19use std::fmt;
20
21use aes::Aes128;
22use aes::cipher::{Block, BlockCipherEncrypt, KeyInit};
23use base64::Engine as _;
24use hmac::{Hmac, Mac};
25use sha1::Sha1;
26
27type HmacSha1 = Hmac<Sha1>;
28
29fn auth_mac(key: &[u8; AUTH_KEY_LEN]) -> HmacSha1 {
36 let mut block = hmac::digest::Key::<HmacSha1>::default();
37 block[..AUTH_KEY_LEN].copy_from_slice(key);
38 <HmacSha1 as hmac::digest::KeyInit>::new(&block)
39}
40
41const MASTER_KEY_LEN: usize = 16;
42const MASTER_SALT_LEN: usize = 14;
43const AUTH_KEY_LEN: usize = 20;
44const REPLAY_WINDOW: u64 = 64;
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49#[non_exhaustive]
50pub enum SrtpSuite {
51 AesCm128HmacSha1_80,
53 AesCm128HmacSha1_32,
55}
56
57impl SrtpSuite {
58 pub fn name(self) -> &'static str {
60 match self {
61 Self::AesCm128HmacSha1_80 => "AES_CM_128_HMAC_SHA1_80",
62 Self::AesCm128HmacSha1_32 => "AES_CM_128_HMAC_SHA1_32",
63 }
64 }
65
66 pub fn from_name(name: &str) -> Option<Self> {
68 match name {
69 "AES_CM_128_HMAC_SHA1_80" => Some(Self::AesCm128HmacSha1_80),
70 "AES_CM_128_HMAC_SHA1_32" => Some(Self::AesCm128HmacSha1_32),
71 _ => None,
72 }
73 }
74
75 pub fn tag_len(self) -> usize {
77 match self {
78 Self::AesCm128HmacSha1_80 => 10,
79 Self::AesCm128HmacSha1_32 => 4,
80 }
81 }
82}
83
84#[derive(Clone, PartialEq, Eq)]
86pub struct MasterKey {
87 key: [u8; MASTER_KEY_LEN],
88 salt: [u8; MASTER_SALT_LEN],
89}
90
91impl MasterKey {
92 pub fn new(key: [u8; MASTER_KEY_LEN], salt: [u8; MASTER_SALT_LEN]) -> Self {
94 Self { key, salt }
95 }
96
97 pub fn generate() -> std::io::Result<Self> {
99 let mut bytes = [0u8; MASTER_KEY_LEN + MASTER_SALT_LEN];
100 getrandom::fill(&mut bytes).map_err(std::io::Error::other)?;
101 Self::from_bytes(&bytes).ok_or_else(|| {
102 std::io::Error::other("generated key material is not a master key and salt long")
103 })
104 }
105
106 fn from_bytes(bytes: &[u8]) -> Option<Self> {
107 if bytes.len() != MASTER_KEY_LEN + MASTER_SALT_LEN {
108 return None;
109 }
110 Some(Self {
111 key: bytes[..MASTER_KEY_LEN].try_into().ok()?,
112 salt: bytes[MASTER_KEY_LEN..].try_into().ok()?,
113 })
114 }
115
116 pub fn to_inline(&self) -> String {
118 let mut bytes = Vec::with_capacity(MASTER_KEY_LEN + MASTER_SALT_LEN);
119 bytes.extend_from_slice(&self.key);
120 bytes.extend_from_slice(&self.salt);
121 base64::engine::general_purpose::STANDARD.encode(bytes)
122 }
123
124 pub fn from_inline(inline: &str) -> Option<Self> {
128 let inline = inline.strip_prefix("inline:").unwrap_or(inline);
129 let mut parts = inline.split('|');
130 let key = parts.next()?;
131 for part in parts {
132 if part.contains(':') {
133 return None; }
135 }
136 let bytes = base64::engine::general_purpose::STANDARD.decode(key).ok()?;
137 Self::from_bytes(&bytes)
138 }
139}
140
141impl fmt::Debug for MasterKey {
142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143 f.write_str("MasterKey([redacted])")
144 }
145}
146
147#[derive(Debug, Clone, PartialEq, Eq)]
149pub struct CryptoAttribute {
150 pub tag: u32,
152 pub suite: SrtpSuite,
154 pub key: MasterKey,
156}
157
158impl CryptoAttribute {
159 pub fn parse(value: &str) -> Option<Self> {
163 let value = value.strip_prefix("a=crypto:").unwrap_or(value);
164 let mut parts = value.split_whitespace();
165 let tag = parts.next()?.parse().ok()?;
166 let suite = SrtpSuite::from_name(parts.next()?)?;
167 let key_params = parts.next()?;
168 if key_params.contains(';') {
170 return None;
171 }
172 let key = MasterKey::from_inline(key_params)?;
173 if parts.next().is_some() {
176 return None;
177 }
178 Some(Self { tag, suite, key })
179 }
180
181 pub fn to_value(&self) -> String {
183 format!(
184 "{} {} inline:{}",
185 self.tag,
186 self.suite.name(),
187 self.key.to_inline()
188 )
189 }
190}
191
192#[derive(Debug, Clone, Copy, PartialEq, Eq)]
194#[non_exhaustive]
195pub enum SrtpError {
196 Malformed,
198 AuthenticationFailed,
200 Replayed,
202}
203
204impl fmt::Display for SrtpError {
205 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
206 f.write_str(match self {
207 Self::Malformed => "malformed SRTP packet",
208 Self::AuthenticationFailed => "SRTP authentication failed",
209 Self::Replayed => "replayed SRTP packet",
210 })
211 }
212}
213
214impl std::error::Error for SrtpError {}
215
216struct SessionKeys {
218 cipher_key: [u8; MASTER_KEY_LEN],
219 salt: [u8; MASTER_SALT_LEN],
220 auth_key: [u8; AUTH_KEY_LEN],
221}
222
223impl SessionKeys {
224 fn derive(master: &MasterKey) -> Self {
225 Self {
226 cipher_key: derive(master, 0x00),
227 auth_key: derive(master, 0x01),
228 salt: derive(master, 0x02),
229 }
230 }
231}
232
233fn derive<const N: usize>(master: &MasterKey, label: u8) -> [u8; N] {
236 let cipher = Aes128::new(&master.key.into());
237 let blocks: Vec<[u8; 16]> = (0..N.div_ceil(16))
238 .map(|i| {
239 let counter: [u8; 16] = std::array::from_fn(|j| match j {
240 7 => master.salt[j] ^ label,
241 j if j < MASTER_SALT_LEN => master.salt[j],
242 14 => (i >> 8) as u8,
243 _ => i as u8,
244 });
245 let mut block = Block::<Aes128>::from(counter);
246 cipher.encrypt_block(&mut block);
247 block.into()
248 })
249 .collect();
250 std::array::from_fn(|k| blocks[k / 16][k % 16])
251}
252
253#[derive(Default)]
255struct Inbound {
256 roc: u32,
257 highest_seq: u16,
258 newest: u64,
260 seen: u64,
261}
262
263#[derive(Default)]
265struct Outbound {
266 roc: u32,
267 last_seq: Option<u16>,
268}
269
270pub struct SrtpSession {
273 suite: SrtpSuite,
274 keys: SessionKeys,
275 cipher: Aes128,
276 outbound: HashMap<u32, Outbound>,
277 inbound: HashMap<u32, Inbound>,
278}
279
280impl fmt::Debug for SrtpSession {
281 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282 f.debug_struct("SrtpSession")
283 .field("suite", &self.suite)
284 .finish_non_exhaustive()
285 }
286}
287
288impl SrtpSession {
289 pub fn new(suite: SrtpSuite, key: &MasterKey) -> Self {
291 let keys = SessionKeys::derive(key);
292 let cipher = Aes128::new(&keys.cipher_key.into());
293 Self {
294 suite,
295 keys,
296 cipher,
297 outbound: HashMap::new(),
298 inbound: HashMap::new(),
299 }
300 }
301
302 pub fn protect(&mut self, rtp: &[u8]) -> Option<Vec<u8>> {
305 let header = header_len(rtp)?;
306 let (seq, ssrc) = seq_ssrc(rtp);
307 let state = self.outbound.entry(ssrc).or_default();
308 if let Some(last) = state.last_seq
309 && seq < last
310 && last - seq > 0x8000
311 {
312 state.roc = state.roc.wrapping_add(1);
313 }
314 state.last_seq = Some(seq);
315 let roc = state.roc;
316 let index = (u64::from(roc) << 16) | u64::from(seq);
317
318 let mut packet = rtp.to_vec();
319 self.keystream(ssrc, index, &mut packet[header..]);
320 let tag = self.tag(&packet, roc);
321 packet.extend_from_slice(&tag[..self.suite.tag_len()]);
322 Some(packet)
323 }
324
325 pub fn unprotect(&mut self, srtp: &[u8]) -> Result<Vec<u8>, SrtpError> {
327 let tag_len = self.suite.tag_len();
328 if srtp.len() < tag_len {
329 return Err(SrtpError::Malformed);
330 }
331 let (authenticated, tag) = srtp.split_at(srtp.len() - tag_len);
332 let header = header_len(authenticated).ok_or(SrtpError::Malformed)?;
333 let (seq, ssrc) = seq_ssrc(authenticated);
334
335 let (roc, index) = match self.inbound.get(&ssrc) {
336 Some(state) => {
337 let roc = estimate_roc(state.roc, state.highest_seq, seq);
338 let index = (u64::from(roc) << 16) | u64::from(seq);
339 if is_replay(state, index) {
340 return Err(SrtpError::Replayed);
341 }
342 (roc, index)
343 }
344 None => (0, u64::from(seq)),
345 };
346
347 let mut mac = auth_mac(&self.keys.auth_key);
348 mac.update(authenticated);
349 mac.update(&roc.to_be_bytes());
350 mac.verify_truncated_left(tag)
351 .map_err(|_| SrtpError::AuthenticationFailed)?;
352
353 let mut packet = authenticated.to_vec();
354 self.keystream(ssrc, index, &mut packet[header..]);
355 self.accept(ssrc, roc, seq, index);
356 Ok(packet)
357 }
358
359 fn accept(&mut self, ssrc: u32, roc: u32, seq: u16, index: u64) {
362 let state = self.inbound.entry(ssrc).or_insert_with(|| Inbound {
363 roc,
364 highest_seq: seq,
365 newest: index,
366 seen: 0,
367 });
368 if index > state.newest {
369 let shift = index - state.newest;
370 state.seen = if shift >= REPLAY_WINDOW {
371 0
372 } else {
373 state.seen << shift
374 };
375 state.newest = index;
376 state.roc = roc;
377 state.highest_seq = seq;
378 }
379 let behind = state.newest - index;
380 state.seen |= 1 << behind;
381 }
382
383 fn keystream(&self, ssrc: u32, index: u64, data: &mut [u8]) {
385 let mut counter = [0u8; 16];
386 counter[..MASTER_SALT_LEN].copy_from_slice(&self.keys.salt);
387 for (i, b) in ssrc.to_be_bytes().iter().enumerate() {
388 counter[4 + i] ^= b;
389 }
390 for (i, b) in index.to_be_bytes()[2..].iter().enumerate() {
391 counter[8 + i] ^= b;
392 }
393 for chunk in data.chunks_mut(16) {
394 let mut block = Block::<Aes128>::from(counter);
395 self.cipher.encrypt_block(&mut block);
396 for (d, k) in chunk.iter_mut().zip(block.iter()) {
397 *d ^= k;
398 }
399 let next = u16::from_be_bytes([counter[14], counter[15]]).wrapping_add(1);
400 counter[14..].copy_from_slice(&next.to_be_bytes());
401 }
402 }
403
404 fn tag(&self, authenticated: &[u8], roc: u32) -> [u8; 20] {
405 let mut mac = auth_mac(&self.keys.auth_key);
406 mac.update(authenticated);
407 mac.update(&roc.to_be_bytes());
408 mac.finalize().into_bytes().into()
409 }
410}
411
412fn header_len(packet: &[u8]) -> Option<usize> {
414 if packet.len() < 12 || packet[0] >> 6 != 2 {
415 return None;
416 }
417 let mut len = 12 + usize::from(packet[0] & 0x0F) * 4;
418 if packet[0] & 0x10 != 0 {
419 let words = packet.get(len + 2..len + 4)?;
420 len += 4 + usize::from(u16::from_be_bytes([words[0], words[1]])) * 4;
421 }
422 (len <= packet.len()).then_some(len)
423}
424
425fn seq_ssrc(packet: &[u8]) -> (u16, u32) {
426 (
427 u16::from_be_bytes([packet[2], packet[3]]),
428 u32::from_be_bytes([packet[8], packet[9], packet[10], packet[11]]),
429 )
430}
431
432fn estimate_roc(roc: u32, highest: u16, seq: u16) -> u32 {
435 if highest < 0x8000 {
436 if seq > highest && seq - highest > 0x8000 {
437 roc.wrapping_sub(1)
438 } else {
439 roc
440 }
441 } else if highest - 0x8000 > seq {
442 roc.wrapping_add(1)
443 } else {
444 roc
445 }
446}
447
448fn is_replay(state: &Inbound, index: u64) -> bool {
449 if index > state.newest {
450 return false;
451 }
452 let behind = state.newest - index;
453 behind >= REPLAY_WINDOW || state.seen & (1 << behind) != 0
454}
455
456#[cfg(test)]
457mod tests {
458 use super::*;
459
460 fn hex(s: &str) -> Vec<u8> {
461 let s: String = s.split_whitespace().collect();
462 (0..s.len())
463 .step_by(2)
464 .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
465 .collect()
466 }
467
468 fn rfc_master() -> MasterKey {
469 let bytes = hex("E1F97A0D3E018BE0D64FA32C06DE4139 0EC675AD498AFEEBB6960B3AABE6");
470 MasterKey::from_bytes(&bytes).unwrap()
471 }
472
473 #[test]
475 fn auth_mac_matches_hmac_keyed_by_the_bare_key() {
476 let key: [u8; AUTH_KEY_LEN] = hex("CEBE321F6FF7716B6FD4AB49AF256A156D38BAA4")
477 .try_into()
478 .unwrap();
479 let mut padded = auth_mac(&key);
480 padded.update(b"authenticated portion");
481 let mut bare = <HmacSha1 as hmac::digest::KeyInit>::new_from_slice(&key).unwrap();
482 bare.update(b"authenticated portion");
483 assert_eq!(padded.finalize().into_bytes(), bare.finalize().into_bytes());
484 }
485
486 #[test]
488 fn key_derivation_matches_rfc_3711() {
489 let keys = SessionKeys::derive(&rfc_master());
490 assert_eq!(
491 keys.cipher_key.to_vec(),
492 hex("C61E7A93744F39EE10734AFE3FF7A087")
493 );
494 assert_eq!(keys.salt.to_vec(), hex("30CBBC08863D8C85D49DB34A9AE1"));
495 assert_eq!(
496 keys.auth_key.to_vec(),
497 hex("CEBE321F6FF7716B6FD4AB49AF256A156D38BAA4")
498 );
499 }
500
501 #[test]
503 fn keystream_matches_rfc_3711() {
504 let key: [u8; 16] = hex("2B7E151628AED2A6ABF7158809CF4F3C").try_into().unwrap();
505 let salt: [u8; 14] = hex("F0F1F2F3F4F5F6F7F8F9FAFBFCFD").try_into().unwrap();
506 let session = SrtpSession {
507 suite: SrtpSuite::AesCm128HmacSha1_80,
508 keys: SessionKeys {
509 cipher_key: key,
510 salt,
511 auth_key: [0; AUTH_KEY_LEN],
512 },
513 cipher: Aes128::new(&key.into()),
514 outbound: HashMap::new(),
515 inbound: HashMap::new(),
516 };
517 let mut stream = [0u8; 48];
518 session.keystream(0, 0, &mut stream);
519 assert_eq!(
520 stream.to_vec(),
521 hex("E03EAD0935C95E80E166B16DD92B4EB4 \
522 D23513162B02D0F72A43A2FE4A5F97AB \
523 41E95B3BB0A2E8DD477901E4FCA894C0")
524 );
525 }
526
527 #[test]
530 fn protects_the_reference_packet() {
531 let plain = hex("800f1234 decafbad cafebabe abababab abababab abababab abababab");
532 let expected = hex(
533 "800f1234 decafbad cafebabe 4e55dc4c e79978d8 8ca4d215 949d2402 \
534 b78d6acc 99ea179b 8dbb",
535 );
536 let mut sender = SrtpSession::new(SrtpSuite::AesCm128HmacSha1_80, &rfc_master());
537 assert_eq!(sender.protect(&plain).unwrap(), expected);
538
539 let mut receiver = SrtpSession::new(SrtpSuite::AesCm128HmacSha1_80, &rfc_master());
540 assert_eq!(receiver.unprotect(&expected).unwrap(), plain);
541 }
542
543 fn rtp(seq: u16, payload: &[u8]) -> Vec<u8> {
544 let mut packet = vec![0x80, 0x00];
545 packet.extend_from_slice(&seq.to_be_bytes());
546 packet.extend_from_slice(&[0, 0, 0, 160]);
547 packet.extend_from_slice(&0x1234_5678u32.to_be_bytes());
548 packet.extend_from_slice(payload);
549 packet
550 }
551
552 #[test]
553 fn a_tampered_or_replayed_packet_is_refused() {
554 let key = MasterKey::generate().unwrap();
555 for suite in [
556 SrtpSuite::AesCm128HmacSha1_80,
557 SrtpSuite::AesCm128HmacSha1_32,
558 ] {
559 let mut tx = SrtpSession::new(suite, &key);
560 let mut rx = SrtpSession::new(suite, &key);
561 let packet = tx.protect(&rtp(7, b"hello")).unwrap();
562 assert_eq!(packet.len(), 12 + 5 + suite.tag_len());
563 assert_ne!(&packet[12..17], b"hello", "the payload is encrypted");
564
565 let mut tampered = packet.clone();
566 tampered[13] ^= 1;
567 assert_eq!(
568 rx.unprotect(&tampered),
569 Err(SrtpError::AuthenticationFailed)
570 );
571
572 assert_eq!(rx.unprotect(&packet).unwrap(), rtp(7, b"hello"));
573 assert_eq!(rx.unprotect(&packet), Err(SrtpError::Replayed));
574
575 let other =
576 SrtpSession::new(suite, &MasterKey::generate().unwrap()).protect(&rtp(8, b"x"));
577 assert_eq!(
578 rx.unprotect(&other.unwrap()),
579 Err(SrtpError::AuthenticationFailed),
580 "a packet under another key"
581 );
582 }
583 }
584
585 #[test]
586 fn the_rollover_counter_follows_a_sequence_wrap() {
587 let key = MasterKey::generate().unwrap();
588 let suite = SrtpSuite::AesCm128HmacSha1_80;
589 let mut tx = SrtpSession::new(suite, &key);
590 let mut rx = SrtpSession::new(suite, &key);
591 let mut seq: u16 = 65_530;
592 for n in 0..20u8 {
593 let packet = tx.protect(&rtp(seq, &[n; 4])).unwrap();
594 assert_eq!(
595 rx.unprotect(&packet).unwrap(),
596 rtp(seq, &[n; 4]),
597 "seq {seq}"
598 );
599 seq = seq.wrapping_add(1);
600 }
601 assert_eq!(tx.outbound[&0x1234_5678].roc, 1);
602 assert_eq!(rx.inbound[&0x1234_5678].roc, 1);
603
604 let mut tx = SrtpSession::new(suite, &key);
607 let mut rx = SrtpSession::new(suite, &key);
608 let early = tx.protect(&rtp(65_534, b"a")).unwrap();
609 let late = tx.protect(&rtp(65_535, b"b")).unwrap();
610 let wrapped = tx.protect(&rtp(0, b"c")).unwrap();
611 assert!(rx.unprotect(&early).is_ok());
612 assert!(rx.unprotect(&wrapped).is_ok());
613 assert_eq!(rx.unprotect(&late).unwrap(), rtp(65_535, b"b"));
614 assert_eq!(rx.unprotect(&late), Err(SrtpError::Replayed));
615 }
616
617 #[test]
618 fn a_crypto_line_round_trips() {
619 let line = "1 AES_CM_128_HMAC_SHA1_80 inline:4fl6DT4Bi+DWT6MsBt5BOQ7Gda1Jiv7rtpYLOqvm|2^20";
620 let attribute = CryptoAttribute::parse(line).unwrap();
621 assert_eq!(attribute.tag, 1);
622 assert_eq!(attribute.suite, SrtpSuite::AesCm128HmacSha1_80);
623 assert_eq!(attribute.key, rfc_master());
624 assert_eq!(
625 CryptoAttribute::parse(&attribute.to_value()).unwrap(),
626 attribute
627 );
628 assert!(
629 !format!("{attribute:?}").contains("4fl6DT4B"),
630 "keys never print"
631 );
632
633 assert_eq!(
634 CryptoAttribute::parse(
635 "1 F8_128_HMAC_SHA1_80 inline:4fl6DT4Bi+DWT6MsBt5BOQ7Gda1Jiv7rtpYLOqvm"
636 ),
637 None
638 );
639 assert_eq!(
640 CryptoAttribute::parse(
641 "1 AES_CM_128_HMAC_SHA1_80 inline:4fl6DT4Bi+DWT6MsBt5BOQ7Gda1Jiv7rtpYLOqvm|2^20|1:4"
642 ),
643 None,
644 "an MKI"
645 );
646 assert_eq!(
647 CryptoAttribute::parse(
648 "1 AES_CM_128_HMAC_SHA1_80 inline:4fl6DT4Bi+DWT6MsBt5BOQ7Gda1Jiv7rtpYLOqvm KDR=1"
649 ),
650 None,
651 "a session parameter"
652 );
653 }
654}