1use crate::{protobuf as p, AuthSnapshot};
6use anyhow::{ensure, Result};
7use zeroize::Zeroize;
8
9const MAX_AUTH_BYTES: usize = 1024 * 1024;
10const MAX_ENTRIES: usize = 4096;
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub enum CallHostPolicy {
14 Ordinary,
16 AxSelected,
19}
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum CallHostRoute {
25 ConferenceJoin,
26 ConferenceAddMembers,
27 AppAuth,
28 RingingAck,
29 Transfer,
30 Invite,
31 Cancel,
32 LiveSync,
33}
34impl CallHostRoute {
35 pub const fn command(self) -> u16 {
36 match self {
37 Self::ConferenceJoin => 14754,
38 Self::ConferenceAddMembers => 10857,
39 Self::AppAuth => 7994,
40 Self::RingingAck => 8069,
41 Self::Transfer => 11421,
42 Self::Invite => 10342,
43 Self::Cancel => 9332,
44 Self::LiveSync => 9262,
45 }
46 }
47 pub const fn path(self) -> &'static str {
48 match self {
49 Self::ConferenceJoin => "/cgi-bin/micromsg-bin/voipilinkjoin",
50 Self::ConferenceAddMembers => "/cgi-bin/micromsg-bin/voipilinkaddmember",
51 Self::AppAuth => "/cgi-bin/micromsg-bin/mm_ilink_cloud_app_auth",
52 Self::RingingAck => "/cgi-bin/micromsg-bin/voipilinkack",
53 Self::Transfer => "/cgi-bin/micromsg-bin/mmilinktransfer",
54 Self::Invite => "/cgi-bin/micromsg-bin/voipilinkinvite",
55 Self::Cancel => "/cgi-bin/micromsg-bin/voipilinkcancel",
56 Self::LiveSync => "/cgi-bin/micromsg-bin/voipilinklivesync",
57 }
58 }
59}
60pub fn is_teardown_request(route: CallHostRoute, common: &[u8]) -> Result<bool> {
64 if route == CallHostRoute::Cancel {
65 return Ok(true);
66 }
67 is_terminal_transfer(route, common, super::signaling::CallOperation::Exit)
68}
69pub fn is_reject_request(route: CallHostRoute, common: &[u8]) -> Result<bool> {
72 is_terminal_transfer(route, common, super::signaling::CallOperation::Reject)
73}
74fn is_terminal_transfer(
75 route: CallHostRoute,
76 common: &[u8],
77 operation: super::signaling::CallOperation,
78) -> Result<bool> {
79 if route != CallHostRoute::Transfer {
80 return Ok(false);
81 }
82 let command = operation.command_id();
83 let rejecting = operation == super::signaling::CallOperation::Reject;
84 let common = super::signaling::CommonRequest::decode(common)?;
85 if !common.unknown_fields.is_empty() {
86 return Ok(false);
87 }
88 let body = common
89 .body
90 .ok_or_else(|| anyhow::anyhow!("Missing call transfer body"))?;
91 let delegate = Fields::decode(&body)?;
92 if delegate.0.iter().any(|f| !(1..=5).contains(&f.number))
93 || delegate.required_u64(1)? != 1901
94 || delegate.required_u64(2)? != u64::from(command)
95 || delegate.required_bytes(3)? != b"wechat"
96 || delegate.required_bytes(4)? != operation.path().as_bytes()
97 {
98 return Ok(false);
99 }
100 let frame = super::app_frame::TaskFrame::decode(delegate.required_bytes(5)?, command)?;
101 const INTEGER_KEYS: &[u32] = &[
102 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 17, 18, 20, 21, 22, 23, 25, 26, 28, 29, 30, 31,
103 ];
104 if frame.command != command
105 || frame.integers.keys().any(|n| !INTEGER_KEYS.contains(n))
106 || frame.strings.keys().any(|n| ![14, 24, 27].contains(n))
107 || frame.integers.get(&1) != Some(&1)
108 || frame.integers.get(&26) != Some(&4)
109 || [7, 8, 21, 25]
110 .iter()
111 .any(|n| frame.integers.get(n) != Some(&0))
112 || frame.strings.get(&24).map(Vec::as_slice) != Some(b"wechat")
113 || frame.strings.get(&27).is_none_or(Vec::is_empty)
114 {
115 return Ok(false);
116 }
117 let clear = zeroize::Zeroizing::new(super::app_frame::lz4_decode(&frame.payload, 64 * 1024)?);
118 let cloud = Fields::decode(&clear)?;
119 if cloud.0.iter().any(|f| ![1, 2].contains(&f.number)) {
120 return Ok(false);
121 }
122 let base = Fields::decode(cloud.required_bytes(1)?)?;
123 let uin = base.required_u64(1)?;
124 if base.0.iter().any(|f| ![1, 2, 3].contains(&f.number))
125 || uin == 0
126 || base.required_bytes(2)?.is_empty()
127 || i32::try_from(base.required_u64(3)?).is_err()
128 || frame.integers.get(&2) != Some(&uin)
129 || frame.integers.get(&22) != Some(&uin)
130 {
131 return Ok(false);
132 }
133 let exit = Fields::decode(cloud.required_bytes(2)?)?;
134 let last_field = if rejecting { 6 } else { 8 };
135 if exit.0.iter().any(|f| !(1..=last_field).contains(&f.number))
136 || exit.required_bytes(1)?.is_empty()
137 || exit.required_bytes(2)?.is_empty()
138 || exit.required_u64(3)? == 0
139 || exit.required_u64(4)? == 0
140 || [5, 6].iter().any(|n| {
141 exit.required_u64(*n)
142 .map_or(true, |v| u32::try_from(v).is_err())
143 })
144 || if rejecting {
145 exit.required_u64(6)? != 1
146 } else {
147 u32::try_from(exit.required_u64(7)?).is_err() || exit.required_u64(8)? > 1
148 }
149 {
150 return Ok(false);
151 }
152 let sdk = Fields::decode(exit.required_bytes(1)?)?;
153 if sdk.0.iter().any(|f| ![1, 2].contains(&f.number))
154 || u32::try_from(sdk.required_u64(1)?).is_err()
155 || sdk.required_bytes(2)?.is_empty()
156 || std::str::from_utf8(sdk.required_bytes(2)?).is_err()
157 {
158 return Ok(false);
159 }
160 let group = Fields::decode(exit.required_bytes(2)?)?;
161 if group.0.iter().any(|f| !(1..=7).contains(&f.number))
162 || group.required_bytes(1)? != b"wechat"
163 || !matches!(group.required_bytes(3)?, b"voip-2p" | b"voip-mt")
164 || group.required_u64(5)? != 1
165 {
166 return Ok(false);
167 }
168 if let Some(value) = crate::protobuf::optional(&group.0, 2)? {
169 if !matches!(value, crate::protobuf::Value::Varint(_)) {
170 return Ok(false);
171 }
172 }
173 for field in [4, 6] {
174 if let Some(value) = group.optional_bytes(field)? {
175 if value.len() > 1024 || std::str::from_utf8(value).is_err() {
176 return Ok(false);
177 }
178 }
179 }
180 group.optional_u32(7)?;
181 Ok(true)
182}
183
184impl From<super::personal::HostOperation> for CallHostRoute {
185 fn from(value: super::personal::HostOperation) -> Self {
186 match value {
187 super::personal::HostOperation::RingingAck => Self::RingingAck,
188 super::personal::HostOperation::Invite => Self::Invite,
189 super::personal::HostOperation::ConferenceAddMembers => Self::ConferenceAddMembers,
190 super::personal::HostOperation::Cancel => Self::Cancel,
191 super::personal::HostOperation::LiveSync => Self::LiveSync,
192 }
193 }
194}
195
196pub fn selected_policy(snapshot: &AuthSnapshot, command: u16) -> Result<CallHostPolicy> {
201 ensure!(
202 matches!(
203 command,
204 7994 | 8069 | 11421 | 10342 | 9332 | 9262 | 14754 | 10857
205 ),
206 "Unsupported call host command"
207 );
208 let root = Fields::decode(&snapshot.response)?;
209 let base = Fields::decode(root.required_bytes(1)?)?;
210 ensure!(
211 i32::try_from(base.required_u64(1)? as i64)? == 0,
212 "Rejected call auth snapshot"
213 );
214 let mask = u32::try_from(root.required_u64(2)?)?;
215 ensure!(
216 mask == snapshot.update_mask,
217 "Call auth snapshot mask mismatch"
218 );
219 if mask & 8 == 0 {
220 return Ok(CallHostPolicy::Ordinary);
221 }
222 let Some(section) = root.optional_bytes(6)? else {
223 return Ok(CallHostPolicy::Ordinary);
224 };
225 let list = Fields::decode(section)?;
226 let mut count = 0;
227 let mut selected = CallHostPolicy::Ordinary;
228 for field in &list.0 {
229 if field.number != 2 {
230 continue;
231 }
232 count += 1;
233 ensure!(count <= MAX_ENTRIES, "Too many call host auth entries");
234 let p::Value::Bytes(raw) = &field.value else {
235 anyhow::bail!("Invalid call host auth entry wire type");
236 };
237 let entry = Fields::decode(raw)?;
238 entry.optional_u32(1)?;
240 let cgi = entry.optional_u32(4)?;
241 entry.optional_bytes(3)?;
242 for number in [2, 5] {
243 let nested = Fields::decode(entry.optional_bytes(number)?.unwrap_or_default())?;
244 nested.optional_bytes(2)?;
246 }
247 if cgi == u32::from(command) {
248 selected = CallHostPolicy::AxSelected;
249 }
250 }
251 Ok(selected)
252}
253
254struct Fields(Vec<p::Field>);
258impl Fields {
259 fn decode(raw: &[u8]) -> Result<Self> {
260 ensure!(raw.len() <= MAX_AUTH_BYTES, "Call auth snapshot too large");
261 let result = Self(p::decode(raw)?);
262 ensure!(result.0.len() <= MAX_ENTRIES, "Too many call auth fields");
263 Ok(result)
264 }
265 fn optional_bytes(&self, number: u32) -> Result<Option<&[u8]>> {
266 p::optional_data(&self.0, number)
267 }
268 fn required_bytes(&self, number: u32) -> Result<&[u8]> {
269 self.optional_bytes(number)?
270 .ok_or_else(|| anyhow::anyhow!("Missing call auth bytes field {number}"))
271 }
272 fn required_u64(&self, number: u32) -> Result<u64> {
273 match p::optional(&self.0, number)? {
274 Some(p::Value::Varint(value)) => Ok(*value),
275 _ => anyhow::bail!("Missing or invalid call auth integer {number}"),
276 }
277 }
278 fn optional_u32(&self, number: u32) -> Result<u32> {
279 match p::optional(&self.0, number)? {
280 None => Ok(0),
281 Some(p::Value::Varint(value)) => Ok(u32::try_from(*value)?),
282 _ => anyhow::bail!("Invalid call auth scalar {number}"),
283 }
284 }
285}
286impl Drop for Fields {
287 fn drop(&mut self) {
288 for field in &mut self.0 {
289 if let p::Value::Bytes(bytes) = &mut field.value {
290 bytes.zeroize();
291 }
292 }
293 }
294}
295
296#[cfg(test)]
297mod tests {
298 use super::*;
299 fn snapshot(mask: u32, selected: u32) -> AuthSnapshot {
300 let entry = p::message(&[p::uint(4, u64::from(selected))]).unwrap();
301 let list = p::bytes(2, &entry);
302 let mut snapshot = AuthSnapshot::default();
303 snapshot.update_mask = mask;
304 snapshot.response = p::message(&[
305 p::bytes(1, &[8, 0]),
306 p::uint(2, u64::from(mask)),
307 p::bytes(6, &list),
308 ])
309 .unwrap();
310 snapshot
311 }
312 #[test]
313 fn active_exact_command_selects_ax_and_unrelated_command_does_not() {
314 let state = snapshot(8, 7994);
315 assert_eq!(
316 selected_policy(&state, 7994).unwrap(),
317 CallHostPolicy::AxSelected
318 );
319 assert_eq!(
320 selected_policy(&state, 10342).unwrap(),
321 CallHostPolicy::Ordinary
322 );
323 let mut retained = snapshot(0, 7994);
324 retained.ax_auth = vec![0xff; 32];
325 assert_eq!(
326 selected_policy(&retained, 7994).unwrap(),
327 CallHostPolicy::Ordinary
328 );
329 retained.update_mask = 8;
330 assert!(selected_policy(&retained, 7994).is_err());
331 assert!(selected_policy(&AuthSnapshot::default(), 7994).is_err());
332 }
333
334 #[test]
335 fn additional_invitations_keep_their_route_policy_and_nonterminal_authority() {
336 let selected = snapshot(8, 10857);
337 assert_eq!(
338 selected_policy(&selected, 10857).unwrap(),
339 CallHostPolicy::AxSelected
340 );
341 assert_eq!(
342 selected_policy(&selected, 10342).unwrap(),
343 CallHostPolicy::Ordinary
344 );
345 assert_eq!(CallHostRoute::ConferenceAddMembers.command(), 10857);
346 assert_eq!(
347 CallHostRoute::ConferenceAddMembers.path(),
348 "/cgi-bin/micromsg-bin/voipilinkaddmember"
349 );
350 assert!(!is_teardown_request(CallHostRoute::ConferenceAddMembers, &[]).unwrap());
351 assert!(!is_reject_request(CallHostRoute::ConferenceAddMembers, &[]).unwrap());
352 }
353
354 #[test]
355 fn expired_scope_transfer_exception_requires_matching_exit_frames() {
356 fn request(delegate: u64, path: &[u8], task: u32) -> Vec<u8> {
357 request_override(delegate, path, task, None)
358 }
359 fn request_override(
360 delegate: u64,
361 path: &[u8],
362 task: u32,
363 extra: Option<(u32, u64)>,
364 ) -> Vec<u8> {
365 let sdk = crate::protobuf::message(&[
366 crate::protobuf::uint(1, 0x050000cb),
367 crate::protobuf::bytes(2, b"0x1000000"),
368 ])
369 .unwrap();
370 let group = crate::protobuf::message(&[
371 crate::protobuf::bytes(1, b"wechat"),
372 crate::protobuf::uint(2, 99),
373 crate::protobuf::bytes(3, b"voip-2p"),
374 crate::protobuf::bytes(4, b"group"),
375 crate::protobuf::uint(5, 1),
376 crate::protobuf::bytes(6, b""),
377 crate::protobuf::uint(7, 0),
378 ])
379 .unwrap();
380 let mut terminal = vec![
381 crate::protobuf::bytes(1, &sdk),
382 crate::protobuf::bytes(2, &group),
383 crate::protobuf::uint(3, 7),
384 crate::protobuf::uint(4, 9),
385 crate::protobuf::uint(5, 0),
386 crate::protobuf::uint(6, 1),
387 ];
388 if delegate != 3095 {
389 terminal.extend([crate::protobuf::uint(7, 0), crate::protobuf::uint(8, 1)]);
390 }
391 let exit = crate::protobuf::message(&terminal).unwrap();
392 let base = crate::protobuf::message(&[
393 crate::protobuf::uint(1, 17),
394 crate::protobuf::bytes(2, b"Ldevice"),
395 crate::protobuf::uint(3, 1),
396 ])
397 .unwrap();
398 let cloud = crate::protobuf::message(&[
399 crate::protobuf::bytes(1, &base),
400 crate::protobuf::bytes(2, &exit),
401 ])
402 .unwrap();
403 let mut integers = std::collections::BTreeMap::from([
404 (1, 1),
405 (2, 17),
406 (7, 0),
407 (8, 0),
408 (21, 0),
409 (22, 17),
410 (25, 0),
411 (26, 4),
412 ]);
413 if let Some((field, value)) = extra {
414 integers.insert(field, value);
415 }
416 let frame = super::super::app_frame::TaskFrame {
417 command: task,
418 integers,
419 strings: std::collections::BTreeMap::from([
420 (24, b"wechat".to_vec()),
421 (27, b"server".to_vec()),
422 ]),
423 payload: super::super::app_frame::lz4_literal(&cloud).unwrap(),
424 }
425 .encode()
426 .unwrap();
427 let body = crate::protobuf::message(&[
428 crate::protobuf::uint(1, 1901),
429 crate::protobuf::uint(2, delegate),
430 crate::protobuf::bytes(3, b"wechat"),
431 crate::protobuf::bytes(4, path),
432 crate::protobuf::bytes(5, &frame),
433 ])
434 .unwrap();
435 super::super::signaling::CommonRequest {
436 base_request: Some(vec![]),
437 body: Some(body),
438 unknown_fields: vec![],
439 }
440 .encode()
441 .unwrap()
442 }
443 let exit = super::super::signaling::CallOperation::Exit
444 .path()
445 .as_bytes();
446 let join = super::super::signaling::CallOperation::Join
447 .path()
448 .as_bytes();
449 assert!(is_teardown_request(CallHostRoute::Transfer, &request(3380, exit, 3380)).unwrap());
450 for raw in [
451 request(3361, join, 3361),
452 request(3380, join, 3380),
453 request(3380, exit, 3361),
454 request(3361, exit, 3380),
455 ] {
456 assert!(!is_teardown_request(CallHostRoute::Transfer, &raw).unwrap_or(false));
457 }
458 for extra in [(99, 0), (7, 11), (26, 0)] {
459 assert!(!is_teardown_request(
460 CallHostRoute::Transfer,
461 &request_override(3380, exit, 3380, Some(extra))
462 )
463 .unwrap_or(false));
464 }
465 let reject = super::super::signaling::CallOperation::Reject
466 .path()
467 .as_bytes();
468 assert!(is_reject_request(CallHostRoute::Transfer, &request(3095, reject, 3095)).unwrap());
469 assert!(
470 !is_teardown_request(CallHostRoute::Transfer, &request(3095, reject, 3095)).unwrap()
471 );
472 for raw in [
473 request(3380, exit, 3380),
474 request(3095, join, 3095),
475 request(3095, reject, 3361),
476 ] {
477 assert!(!is_reject_request(CallHostRoute::Transfer, &raw).unwrap_or(false));
478 }
479 for extra in [(99, 0), (7, 11), (26, 0)] {
480 assert!(!is_reject_request(
481 CallHostRoute::Transfer,
482 &request_override(3095, reject, 3095, Some(extra))
483 )
484 .unwrap_or(false));
485 }
486 assert!(!is_teardown_request(CallHostRoute::AppAuth, &[]).unwrap());
487 assert!(is_teardown_request(CallHostRoute::Transfer, &[0xff]).is_err());
488 }
489}