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
use crate::{option::*, protection_profile::*};
use shared::error::{Error, Result};
/// RFC 5764 exporter label used to derive SRTP master keys and salts from DTLS.
pub const LABEL_EXTRACTOR_DTLS_SRTP: &str = "EXTRACTOR-dtls_srtp";
/// SessionKeys bundles the keys required to setup an SRTP session
///
/// The keys and salts are zeroized when the value is dropped, and `Debug` prints their lengths
/// only (RFC 3711 section 3.2.1: master keys are kept secret; RFC 7714 section 13.1: keys and
/// salts are erased when no longer needed).
#[derive(Default, Clone, zeroize::Zeroize, zeroize::ZeroizeOnDrop)]
pub struct SessionKeys {
/// The master key used to protect outbound packets.
pub local_master_key: Vec<u8>,
/// The master salt used to protect outbound packets.
pub local_master_salt: Vec<u8>,
/// The master key used to unprotect inbound packets.
pub remote_master_key: Vec<u8>,
/// The master salt used to unprotect inbound packets.
pub remote_master_salt: Vec<u8>,
}
impl std::fmt::Debug for SessionKeys {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SessionKeys")
.field(
"local_master_key",
&format_args!("[REDACTED; {}]", self.local_master_key.len()),
)
.field(
"local_master_salt",
&format_args!("[REDACTED; {}]", self.local_master_salt.len()),
)
.field(
"remote_master_key",
&format_args!("[REDACTED; {}]", self.remote_master_key.len()),
)
.field(
"remote_master_salt",
&format_args!("[REDACTED; {}]", self.remote_master_salt.len()),
)
.finish()
}
}
/// Config is used to configure a session.
/// The top-level integration exports keying material from DTLS and installs it here, or callers
/// can directly pass the keys themselves.
/// After a Config is passed to a session it must not be modified.
#[derive(Default)]
pub struct Config {
/// The master keys and salts for both directions.
pub keys: SessionKeys,
/// The negotiated protection profile, which fixes the cipher and tag lengths.
pub profile: ProtectionProfile,
//LoggerFactory: logging.LoggerFactory
/// List of local/remote context options.
/// Replay protection is on by default, for every context: one created with `None` uses a
/// window of [`DEFAULT_REPLAY_PROTECTION_WINDOW`] (64) packets. A context only checks for
/// replays when it unprotects, so the local options matter only to a context used that way.
pub local_rtp_options: Option<ContextOption>,
/// Replay-protection options for the inbound RTP context. Enabled by default.
pub remote_rtp_options: Option<ContextOption>,
/// Replay-protection options for the outbound RTCP context.
pub local_rtcp_options: Option<ContextOption>,
/// Replay-protection options for the inbound RTCP context. Enabled by default.
pub remote_rtcp_options: Option<ContextOption>,
}
impl Config {
/// Returns the exact number of DTLS exporter bytes required by this profile.
#[must_use]
pub fn keying_material_len(&self) -> usize {
let key_len = self.profile.key_len();
let salt_len = self.profile.salt_len();
(key_len * 2) + (salt_len * 2)
}
/// Splits DTLS-SRTP exporter output into local and remote master keys and salts according to
/// RFC 5764.
///
/// # Errors
///
/// Returns an error unless `keying_material` has exactly [`Self::keying_material_len`] bytes.
pub fn set_session_keys_from_keying_material(
&mut self,
keying_material: &[u8],
is_client: bool,
) -> Result<()> {
let expected = self.keying_material_len();
if keying_material.len() != expected {
return Err(Error::Other(format!(
"invalid DTLS-SRTP keying material length: expected {expected}, got {}",
keying_material.len()
)));
}
let key_len = self.profile.key_len();
let salt_len = self.profile.salt_len();
let (client_write_key, rest) = keying_material.split_at(key_len);
let (server_write_key, rest) = rest.split_at(key_len);
let (client_write_salt, server_write_salt) = rest.split_at(salt_len);
let (local_key, local_salt, remote_key, remote_salt) = if is_client {
(
client_write_key,
client_write_salt,
server_write_key,
server_write_salt,
)
} else {
(
server_write_key,
server_write_salt,
client_write_key,
client_write_salt,
)
};
// Dropping the previous keys zeroizes them.
self.keys = SessionKeys {
local_master_key: local_key.to_vec(),
local_master_salt: local_salt.to_vec(),
remote_master_key: remote_key.to_vec(),
remote_master_salt: remote_salt.to_vec(),
};
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn material(len: usize) -> Vec<u8> {
(0..len).map(|value| value as u8).collect()
}
/// RFC 5764 section 4.2: the exporter gives 2 * (SRTPSecurityParams.master_key_len +
/// SRTPSecurityParams.master_salt_len) bytes, split as client key, server key, client salt,
/// server salt. The lengths are the RFCs' (RFC 5764 4.1.2 for the AES-CM and NULL
/// profiles: 128-bit keys, 112-bit salts; RFC 7714 section 14.2 for AES-GCM: 128 or 256-bit
/// keys, 96-bit salts), written out here rather than taken from the code under test, for
/// every profile with a DTLS-SRTP code point.
#[test]
fn rejects_keying_material_with_the_wrong_length() {
let profiles = [
(ProtectionProfile::Aes128CmHmacSha1_80, 16, 14, 60),
(ProtectionProfile::Aes128CmHmacSha1_32, 16, 14, 60),
(ProtectionProfile::NullHmacSha1_80, 16, 14, 60),
(ProtectionProfile::NullHmacSha1_32, 16, 14, 60),
(ProtectionProfile::AeadAes128Gcm, 16, 12, 56),
(ProtectionProfile::AeadAes256Gcm, 32, 12, 88),
];
for (profile, key, salt, total) in profiles {
assert!(profile.dtls_srtp_id().is_some(), "{profile:?}");
let mut config = Config {
profile,
..Default::default()
};
assert_eq!(config.keying_material_len(), total, "{profile:?}");
for actual in [0, total - 1, total + 1, 2 * total] {
let error = config
.set_session_keys_from_keying_material(&material(actual), true)
.expect_err("a length other than the profile's is refused");
match error {
Error::Other(message) => assert_eq!(
message,
format!(
"invalid DTLS-SRTP keying material length: expected {total}, got {actual}"
),
"{profile:?}"
),
other => panic!("{profile:?}: {other:?}"),
}
// Nothing was installed.
assert!(
config.keys.local_master_key.is_empty()
&& config.keys.local_master_salt.is_empty()
&& config.keys.remote_master_key.is_empty()
&& config.keys.remote_master_salt.is_empty(),
"{profile:?}"
);
}
// The exact length is taken and split where RFC 5764 4.2 says.
let bytes = material(total);
config
.set_session_keys_from_keying_material(&bytes, true)
.expect("the profile's length");
assert_eq!(config.keys.local_master_key, bytes[..key], "{profile:?}");
assert_eq!(
config.keys.remote_master_key,
bytes[key..2 * key],
"{profile:?}"
);
assert_eq!(
config.keys.local_master_salt,
bytes[2 * key..2 * key + salt],
"{profile:?}"
);
assert_eq!(
config.keys.remote_master_salt,
bytes[2 * key + salt..],
"{profile:?}"
);
}
}
/// RFC 3711 section 3.2.1, RFC 7714 section 13.1: key bytes never reach a log through
/// `Debug`.
#[test]
fn session_keys_debug_output_holds_no_key_bytes() {
let mut config = Config {
profile: ProtectionProfile::Aes128CmHmacSha1_80,
..Default::default()
};
let bytes: Vec<u8> = (0..config.keying_material_len())
.map(|value| 0xA0 + value as u8)
.collect();
config
.set_session_keys_from_keying_material(&bytes, true)
.unwrap();
assert_eq!(
format!("{:?}", config.keys),
"SessionKeys { local_master_key: [REDACTED; 16], local_master_salt: [REDACTED; 14], \
remote_master_key: [REDACTED; 16], remote_master_salt: [REDACTED; 14] }"
);
}
#[test]
fn assigns_client_and_server_material_by_role() -> Result<()> {
let mut client = Config {
profile: ProtectionProfile::Aes128CmHmacSha1_80,
..Default::default()
};
let bytes = material(client.keying_material_len());
client.set_session_keys_from_keying_material(&bytes, true)?;
let mut server = Config {
profile: client.profile,
..Default::default()
};
server.set_session_keys_from_keying_material(&bytes, false)?;
assert_eq!(client.keys.local_master_key, server.keys.remote_master_key);
assert_eq!(
client.keys.local_master_salt,
server.keys.remote_master_salt
);
assert_eq!(client.keys.remote_master_key, server.keys.local_master_key);
assert_eq!(
client.keys.remote_master_salt,
server.keys.local_master_salt
);
Ok(())
}
}