Skip to main content

wechat_protocol/calls/
host_transport.rs

1//! Call-specific ordinary reply policy and non-sensitive transport diagnostics.
2//! A verified host transport may return either owned ordinary key mode. This
3//! does not change request selection or authorize Ax/app/media key substitution.
4
5use crate::{business, crypto, AccountState, MAX_MESSAGE_BYTES};
6use openssl::symm::Mode;
7use zeroize::Zeroizing;
8
9/// A pre-answer LiveSync was superseded locally. The transport may have sent
10/// it, but its reply must never update the room cursor or account state.
11#[derive(Debug)]
12pub struct CallLiveSyncInterrupted;
13impl std::fmt::Display for CallLiveSyncInterrupted {
14    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
15        f.write_str("Incoming LiveSync was interrupted for Answer")
16    }
17}
18impl std::error::Error for CallLiveSyncInterrupted {}
19
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub enum CallHostStage {
22    Route,
23    Handshake,
24    Prepare,
25    Exchange,
26    Decode,
27}
28impl CallHostStage {
29    pub const fn as_str(self) -> &'static str {
30        match self {
31            Self::Route => "route",
32            Self::Handshake => "handshake",
33            Self::Prepare => "prepare",
34            Self::Exchange => "exchange",
35            Self::Decode => "decode",
36        }
37    }
38}
39
40/// Only fixed labels and optional numeric protocol/status codes are retained.
41/// Underlying error text, hosts, response bytes and keys are never included.
42#[derive(Clone, Debug, PartialEq, Eq)]
43pub struct CallHostRpcError {
44    pub stage: CallHostStage,
45    pub code: &'static str,
46    pub value: Option<i64>,
47    pub crypto_step: Option<&'static str>,
48}
49impl std::fmt::Display for CallHostRpcError {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        write!(f, "Call host {} failed: {}", self.stage.as_str(), self.code)?;
52        if let Some(value) = self.value {
53            write!(f, " ({value})")?;
54        }
55        if let Some(step) = self.crypto_step {
56            write!(f, " [{step}]")?;
57        }
58        Ok(())
59    }
60}
61impl std::error::Error for CallHostRpcError {}
62impl CallHostRpcError {
63    pub(crate) fn new(stage: CallHostStage, code: &'static str, value: Option<i64>) -> Self {
64        Self {
65            stage,
66            code,
67            value,
68            crypto_step: None,
69        }
70    }
71    /// False only when the call request is known not to have been submitted.
72    /// Exchange/decode failures remain uncertain, including connection timeouts.
73    pub fn may_have_submitted(&self) -> bool {
74        matches!(self.stage, CallHostStage::Exchange | CallHostStage::Decode)
75            && self.code != "unsupported_route"
76    }
77    pub(crate) fn from_cause(stage: CallHostStage, cause: &anyhow::Error) -> Self {
78        let mut result = Self::new(stage, "rejected", None);
79        result.crypto_step = cause.chain().find_map(|error| {
80            Some(match error.to_string().as_str() {
81                "MMTLS key generation" => "key_generation",
82                "MMTLS public key encoding" => "public_key_encoding",
83                "MMTLS hello random" => "hello_random",
84                "MMTLS shared secret derivation" => "shared_secret_derivation",
85                "MMTLS handshake key derivation" => "handshake_key_derivation",
86                "MMTLS signature record authentication" => "signature_record_authentication",
87                "MMTLS signature verification" => "signature_verification",
88                "MMTLS ticket record authentication" => "ticket_record_authentication",
89                "MMTLS finished record authentication" => "finished_record_authentication",
90                "MMTLS application key derivation" => "application_key_derivation",
91                "MMTLS noop record sealing" => "noop_record_sealing",
92                "MMTLS noop record authentication" => "noop_record_authentication",
93                _ => return None,
94            })
95        });
96        if cause.is::<crate::mmtls::UnsupportedNativeRoute>() {
97            result.code = "unsupported_route";
98        } else if let Some(http) = cause.downcast_ref::<reqwest::Error>() {
99            result.code = if http.is_timeout() {
100                "timeout"
101            } else if http.is_connect() {
102                "connect"
103            } else if let Some(status) = http.status() {
104                result.value = Some(i64::from(status.as_u16()));
105                "http_status"
106            } else {
107                "http_transport"
108            };
109        } else if let Some(io) = cause.downcast_ref::<std::io::Error>() {
110            result.code = match io.kind() {
111                std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock => "timeout",
112                std::io::ErrorKind::ConnectionRefused => "connection_refused",
113                std::io::ErrorKind::ConnectionReset => "connection_reset",
114                std::io::ErrorKind::UnexpectedEof => "unexpected_eof",
115                std::io::ErrorKind::PermissionDenied => "permission_denied",
116                std::io::ErrorKind::ConnectionAborted => "connection_aborted",
117                std::io::ErrorKind::NetworkUnreachable => "network_unreachable",
118                std::io::ErrorKind::HostUnreachable => "host_unreachable",
119                std::io::ErrorKind::AddrNotAvailable => "address_unavailable",
120                std::io::ErrorKind::BrokenPipe => "broken_pipe",
121                _ => "io",
122            };
123        } else if cause.is::<openssl::error::ErrorStack>() {
124            result.code = "openssl_crypto";
125        } else if let Some((code, value)) = cause
126            .chain()
127            .find_map(|error| known_transport_literal(&error.to_string()))
128        {
129            result.code = code;
130            result.value = value;
131        }
132        result
133    }
134}
135
136// Only exact messages emitted by the maintained session/framing/crypto checks
137// are admitted. Formatting unknown errors is transient; none of that text is
138// returned or persisted. Context strings and payload-bearing suffixes cannot
139// become diagnostic labels.
140fn known_transport_literal(message: &str) -> Option<(&'static str, Option<i64>)> {
141    let code = match message {
142        "Unsupported native server host" => "host_policy",
143        "Invalid receive budget" => "receive_budget_configuration",
144        "Invalid MMTLS timeout" => "timeout_configuration",
145        "Native connection failed" => "connect_failed",
146        "MMTLS deadline exceeded" => "deadline",
147        "MMTLS connection closed" => "connection_closed",
148        "Unexpected MMTLS header" => "record_header",
149        "Receive overflow" | "MMTLS receive budget exceeded" => "receive_budget",
150        "Server returned MMTLS alert" => "server_alert",
151        "Expected handshake" => "expected_server_hello",
152        "Unsupported ServerHello" => "server_hello_selection",
153        "Unoffered key" => "unoffered_key",
154        "Duplicate extension" => "duplicate_extension",
155        "Invalid ECDH point" => "ecdh_point",
156        "Invalid MMTLS P256 shared secret width" => "shared_secret_width",
157        "Missing ECDH selection" => "missing_ecdh_selection",
158        "Missing certificate selection" => "missing_certificate_selection",
159        "Expected signature record" => "expected_signature_record",
160        "Unsupported MMTLS certificate version" => "certificate_version",
161        "Unoffered MMTLS pin" => "unoffered_pin",
162        "Unsupported signature pin curve" => "signature_curve",
163        "Pinned server signature verification failed" => "signature_verification",
164        "Expected ticket record" => "expected_ticket_record",
165        "Expected tickets" => "expected_tickets",
166        "Invalid ticket count" => "ticket_count",
167        "Invalid shortlink ticket" => "ticket_shape",
168        "Expected Finished" => "expected_finished_record",
169        "Server Finished verification failed" => "finished_verification",
170        "Expected NOOP reply" => "expected_noop_record",
171        "Unexpected NOOP reply" => "noop_reply",
172        "Truncated structure" => "truncated_structure",
173        "Integer too wide" => "integer_width",
174        "Trailing structure bytes" => "trailing_structure",
175        "Unexpected handshake message" => "handshake_message",
176        "Missing authentication tag" => "authentication_tag_missing",
177        "Invalid IV" | "Invalid GCM nonce" => "iv_shape",
178        "Invalid GCM key" | "Expected AES192 key" => "key_shape",
179        "Invalid GCM envelope" => "gcm_envelope",
180        "Invalid HKDF size" => "hkdf_size",
181        "Invalid MMTLS record" => "record_shape",
182        "Section too large" | "MMTLS plaintext too large" | "Payload too large" => "request_size",
183        "Shortlink receive budget exceeded" | "Shortlink plaintext too large" => {
184            "shortlink_reply_size"
185        }
186        "Invalid shortlink header" => "shortlink_header",
187        "Invalid shortlink sequence" => "shortlink_sequence",
188        "Unsupported shortlink selection" => "shortlink_selection",
189        "Unsupported shortlink extensions" => "shortlink_extensions",
190        "Shortlink Finished failed" => "shortlink_finished",
191        "Unexpected shortlink close" => "shortlink_close",
192        "Invalid longlink envelope" => "longlink_envelope",
193        _ => {
194            let value = message.strip_prefix("Native shortlink HTTP status ")?;
195            if value.len() != 3 || !value.bytes().all(|byte| byte.is_ascii_digit()) {
196                return None;
197            }
198            let status = value.parse::<u16>().ok()?;
199            return (100..=599)
200                .contains(&status)
201                .then_some(("http_status", Some(i64::from(status))));
202        }
203    };
204    Some((code, None))
205}
206fn decode_error(code: &'static str, value: Option<i64>) -> CallHostRpcError {
207    CallHostRpcError::new(CallHostStage::Decode, code, value)
208}
209
210/// Only call after authenticated MMTLS has verified these bytes. Keys belong to
211/// the same exclusively borrowed account state used to prepare this request;
212/// account/logout generation admission remains the embedding actor's job.
213/// Cookies are returned only after all envelope, decryption and length checks.
214pub(crate) fn decode_verified_reply(
215    state: &AccountState,
216    cgi: u16,
217    input: &[u8],
218) -> Result<(Vec<u8>, Vec<u8>), CallHostRpcError> {
219    if input.len() > MAX_MESSAGE_BYTES {
220        return Err(decode_error("reply_size", None));
221    }
222    let envelope = business::split(input).map_err(|_| decode_error("envelope", None))?;
223    if envelope.return_code != 0 {
224        return Err(decode_error(
225            "business_return",
226            Some(i64::from(envelope.return_code)),
227        ));
228    }
229    if envelope.cgi != u64::from(cgi) {
230        return Err(decode_error("command", None));
231    }
232    if ![1, 2].contains(&envelope.compression) {
233        return Err(decode_error(
234            "compression",
235            Some(i64::from(envelope.compression)),
236        ));
237    }
238    let body = Zeroizing::new(
239        match envelope.encryption {
240            13 if state.response_key.len() == 24 => {
241                crypto::envelope_open(&envelope.payload, &state.response_key, b"")
242            }
243            5 if state.session_key.len() == 16 => {
244                crypto::cbc(&envelope.payload, &state.session_key, Mode::Decrypt)
245            }
246            5 | 13 => {
247                return Err(decode_error(
248                    "response_key",
249                    Some(i64::from(envelope.encryption)),
250                ))
251            }
252            mode => return Err(decode_error("encryption_mode", Some(i64::from(mode)))),
253        }
254        .map_err(|_| decode_error("decrypt", Some(i64::from(envelope.encryption))))?,
255    );
256    if body.len() != envelope.pre_encryption_length {
257        return Err(decode_error("decrypted_length", None));
258    }
259    let plain = Zeroizing::new(if envelope.compression == 1 {
260        crypto::inflate(&body).map_err(|_| decode_error("inflate", None))?
261    } else {
262        body.to_vec()
263    });
264    if plain.len() != envelope.original_length {
265        return Err(decode_error("plaintext_length", None));
266    }
267    Ok((plain.to_vec(), envelope.cookie))
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273    fn state() -> AccountState {
274        AccountState {
275            schema: 1,
276            device: crate::DeviceProfile {
277                device_id: vec![b'x'; 16],
278                device_type: "Linux".into(),
279                client_version: -227271398,
280            },
281            uin: 1,
282            own_username: "synthetic".into(),
283            cookie: vec![],
284            session_key: vec![7; 16],
285            request_key: vec![8; 24],
286            response_key: vec![9; 24],
287            auto_auth_key: vec![],
288            key_info: vec![],
289            database_password: vec![],
290            auth_snapshot: crate::AuthSnapshot::default(),
291            long_host: "long.weixin.qq.com".into(),
292            short_host: "short.weixin.qq.com".into(),
293        }
294    }
295    // Response-header construction is independent of the request packer. Its
296    // five varints follow CGI, original size, encrypted-plain size, reserveds.
297    fn reply(state: &AccountState, cgi: u16, mode: u8, compressed: bool) -> Vec<u8> {
298        let plain = b"synthetic call reply";
299        let body = if compressed {
300            crypto::deflate(plain).unwrap()
301        } else {
302            plain.to_vec()
303        };
304        let cipher = match mode {
305            13 => crypto::envelope_seal(&body, &state.response_key, b"", [3; 12]).unwrap(),
306            _ => crypto::cbc(&body, &state.session_key, Mode::Encrypt).unwrap(),
307        };
308        let cookie = b"new";
309        let mut tail = Vec::new();
310        for n in [u64::from(cgi), plain.len() as u64, body.len() as u64, 0, 0] {
311            tail.extend(crate::protobuf::varint(n));
312        }
313        let size = 10 + cookie.len() + tail.len();
314        assert!(size < 64);
315        let flags = (u16::from(mode) << 12)
316            | ((cookie.len() as u16) << 8)
317            | ((size as u16) << 2)
318            | if compressed { 1 } else { 2 };
319        let mut raw = flags.to_le_bytes().to_vec();
320        raw.extend(0i32.to_be_bytes());
321        raw.extend(state.uin.to_be_bytes());
322        raw.extend(cookie);
323        raw.extend(tail);
324        raw.extend(cipher);
325        raw
326    }
327    #[test]
328    fn call_reply_mode_is_independent_while_generic_policy_stays_strict() {
329        let mut s = state();
330        let generic = business::AuthenticatedPacket::prepare(&s, 7994, b"request").unwrap();
331        let origin_reply = reply(&s, 7994, 5, false);
332        assert!(generic
333            .decode_verified_transport_reply(&origin_reply)
334            .is_err());
335        assert_eq!(
336            decode_verified_reply(&s, 7994, &origin_reply).unwrap(),
337            (b"synthetic call reply".to_vec(), b"new".to_vec())
338        );
339        for compressed in [false, true] {
340            assert_eq!(
341                decode_verified_reply(&s, 7994, &reply(&s, 7994, 13, compressed))
342                    .unwrap()
343                    .0,
344                b"synthetic call reply"
345            );
346        }
347        s.request_key.clear();
348        s.response_key.clear();
349        let generic_origin = business::AuthenticatedPacket::prepare(&s, 7994, b"request").unwrap();
350        let main_reply = reply(&state(), 7994, 13, false);
351        assert!(generic_origin
352            .decode_verified_transport_reply(&main_reply)
353            .is_err());
354        assert_eq!(
355            decode_verified_reply(&s, 7994, &main_reply)
356                .unwrap_err()
357                .code,
358            "response_key"
359        );
360    }
361    #[test]
362    fn wrong_owned_keys_commands_modes_and_lengths_do_not_admit_cookie() {
363        let s = state();
364        for mode in [5, 13] {
365            let packet = reply(&s, 7994, mode, false);
366            let mut wrong = state();
367            wrong.session_key.fill(0);
368            wrong.response_key.fill(0);
369            assert_eq!(
370                decode_verified_reply(&wrong, 7994, &packet)
371                    .unwrap_err()
372                    .code,
373                "decrypt"
374            );
375        }
376        assert_eq!(
377            decode_verified_reply(&s, 8069, &reply(&s, 7994, 5, false))
378                .unwrap_err()
379                .code,
380            "command"
381        );
382        assert_eq!(
383            decode_verified_reply(&s, 7994, &reply(&s, 7994, 11, false))
384                .unwrap_err()
385                .value,
386            Some(11)
387        );
388        let mut short = reply(&s, 7994, 13, false);
389        short.pop();
390        assert_eq!(
391            decode_verified_reply(&s, 7994, &short).unwrap_err().code,
392            "decrypt"
393        );
394    }
395    #[test]
396    fn diagnostics_never_copy_underlying_error_text() {
397        let error = CallHostRpcError::from_cause(
398            CallHostStage::Handshake,
399            &anyhow::anyhow!("synthetic-private-key-and-body"),
400        );
401        assert_eq!(error.to_string(), "Call host handshake failed: rejected");
402        let timeout = anyhow::Error::new(std::io::Error::from(std::io::ErrorKind::TimedOut));
403        assert_eq!(
404            CallHostRpcError::from_cause(CallHostStage::Exchange, &timeout).code,
405            "timeout"
406        );
407        assert!(
408            CallHostRpcError::from_cause(CallHostStage::Exchange, &timeout).may_have_submitted()
409        );
410        assert!(!error.may_have_submitted());
411        let rejected = crate::mmtls::validate_short_route("/bad").unwrap_err();
412        let diagnostic = CallHostRpcError::from_cause(CallHostStage::Exchange, &rejected);
413        assert_eq!(diagnostic.code, "unsupported_route");
414        assert!(!diagnostic.may_have_submitted());
415    }
416
417    #[test]
418    fn crypto_diagnostics_preserve_only_fixed_phase_labels() {
419        let cause = anyhow::Error::new(openssl::error::ErrorStack::get())
420            .context("MMTLS signature record authentication")
421            .context("synthetic private response and credentials");
422        let diagnostic = CallHostRpcError::from_cause(CallHostStage::Handshake, &cause);
423        assert_eq!(diagnostic.code, "openssl_crypto");
424        assert_eq!(
425            diagnostic.crypto_step,
426            Some("signature_record_authentication")
427        );
428        assert!(!diagnostic.to_string().contains("private"));
429        assert!(!diagnostic.may_have_submitted());
430    }
431}