Skip to main content

wechat_protocol/
mmtls.rs

1//! Fresh pinned MMTLS handshake and authenticated shortlink exchange.
2use crate::crypto::*;
3use anyhow::{ensure, Context, Result};
4use openssl::{memcmp, nid::Nid};
5use serde::{Deserialize, Serialize};
6use std::{
7    io::{Read, Write},
8    net::TcpStream,
9    time::{Duration, Instant},
10};
11use zeroize::Zeroize;
12
13pub const VERSION: u16 = 0xf104;
14const MAX_RECORD_PLAINTEXT: usize = u16::MAX as usize - 16;
15pub struct Cursor<'a> {
16    bytes: &'a [u8],
17    offset: usize,
18}
19impl<'a> Cursor<'a> {
20    pub fn new(bytes: &'a [u8]) -> Self {
21        Self { bytes, offset: 0 }
22    }
23    pub fn take(&mut self, n: usize) -> Result<&'a [u8]> {
24        ensure!(n <= self.bytes.len() - self.offset, "Truncated structure");
25        let b = &self.bytes[self.offset..self.offset + n];
26        self.offset += n;
27        Ok(b)
28    }
29    pub fn uint(&mut self, n: usize) -> Result<u64> {
30        ensure!(n <= 8, "Integer too wide");
31        Ok(self.take(n)?.iter().fold(0, |a, &b| (a << 8) | b as u64))
32    }
33    pub fn sized(&mut self, width: usize) -> Result<&'a [u8]> {
34        let n = usize::try_from(self.uint(width)?)?;
35        self.take(n)
36    }
37    pub fn end(&self) -> Result<()> {
38        ensure!(self.offset == self.bytes.len(), "Trailing structure bytes");
39        Ok(())
40    }
41}
42pub fn section(b: &[u8]) -> Vec<u8> {
43    [(b.len() as u32).to_be_bytes().as_slice(), b].concat()
44}
45fn sized(b: &[u8]) -> Result<Vec<u8>> {
46    ensure!(b.len() <= u16::MAX as usize, "Section too large");
47    Ok([(b.len() as u16).to_be_bytes().as_slice(), b].concat())
48}
49#[derive(Clone)]
50pub struct Record {
51    pub header: [u8; 5],
52    pub body: Vec<u8>,
53}
54pub fn frame(kind: u8, body: &[u8]) -> Result<Vec<u8>> {
55    ensure!(
56        (0x15..=0x19).contains(&kind) && body.len() <= 65535,
57        "Invalid MMTLS record"
58    );
59    Ok([
60        vec![kind],
61        VERSION.to_be_bytes().to_vec(),
62        (body.len() as u16).to_be_bytes().to_vec(),
63        body.to_vec(),
64    ]
65    .concat())
66}
67pub fn nonce(iv: &[u8], sequence: u64) -> Result<[u8; 12]> {
68    ensure!(iv.len() == 12, "Invalid IV");
69    let mut b: [u8; 12] = iv.try_into()?;
70    for (i, v) in sequence.to_be_bytes().iter().enumerate() {
71        b[i + 4] ^= v;
72    }
73    Ok(b)
74}
75pub fn seal(kind: u8, plain: &[u8], key: &[u8], iv: &[u8], sequence: u64) -> Result<Vec<u8>> {
76    ensure!(
77        plain.len() <= MAX_RECORD_PLAINTEXT,
78        "MMTLS plaintext too large"
79    );
80    let header = frame(kind, &vec![0; plain.len() + 16])?[..5].to_vec();
81    let aad = [sequence.to_be_bytes().as_slice(), &header].concat();
82    let (cipher, tag) = gcm_seal(key, &nonce(iv, sequence)?, &aad, plain)?;
83    Ok([header, cipher, tag.to_vec()].concat())
84}
85pub fn open(record: &Record, key: &[u8], iv: &[u8], sequence: u64) -> Result<Vec<u8>> {
86    ensure!(record.body.len() >= 16, "Missing authentication tag");
87    let n = record.body.len() - 16;
88    gcm_open(
89        key,
90        &nonce(iv, sequence)?,
91        &[sequence.to_be_bytes().as_slice(), &record.header].concat(),
92        &record.body[..n],
93        &record.body[n..],
94    )
95}
96struct Traffic {
97    client_key: Vec<u8>,
98    server_key: Vec<u8>,
99    client_iv: Vec<u8>,
100    server_iv: Vec<u8>,
101}
102impl Drop for Traffic {
103    fn drop(&mut self) {
104        self.client_key.zeroize();
105        self.server_key.zeroize();
106        self.client_iv.zeroize();
107        self.server_iv.zeroize();
108    }
109}
110fn traffic(secret: &[u8], label: &str, transcript: &[u8]) -> Result<Traffic> {
111    let mut b = expand(
112        secret,
113        &[label.as_bytes(), &sha256(transcript)].concat(),
114        56,
115    )?;
116    let t = Traffic {
117        client_key: b[..16].to_vec(),
118        server_key: b[16..32].to_vec(),
119        client_iv: b[32..44].to_vec(),
120        server_iv: b[44..].to_vec(),
121    };
122    b.zeroize();
123    Ok(t)
124}
125fn handshake_secret(shared_x: &[u8]) -> Result<Vec<u8>> {
126    ensure!(
127        shared_x.len() == 32,
128        "Invalid MMTLS P256 shared secret width"
129    );
130    // The P256 coordinate has a fixed width. A leading zero is part of the
131    // shared secret and must participate in the key schedule.
132    Ok(sha256(shared_x))
133}
134fn signed_payload(bytes: &[u8], kind: u8) -> Result<Vec<u8>> {
135    let mut top = Cursor::new(bytes);
136    let mut body = Cursor::new(top.sized(4)?);
137    top.end()?;
138    ensure!(body.uint(1)? == kind as u64, "Unexpected handshake message");
139    let value = body.sized(2)?.to_vec();
140    body.end()?;
141    Ok(value)
142}
143
144#[derive(Clone, Serialize, Deserialize)]
145pub struct Ticket {
146    pub kind: u8,
147    pub lifetime: u32,
148    pub reserved: u32,
149    pub nonce: Vec<u8>,
150    pub opaque: Vec<u8>,
151}
152#[derive(Clone, Serialize, Deserialize)]
153pub struct ShortSession {
154    pub access_psk: Vec<u8>,
155    pub ticket: Ticket,
156}
157impl Drop for ShortSession {
158    fn drop(&mut self) {
159        self.access_psk.zeroize();
160        self.ticket.opaque.zeroize();
161        self.ticket.nonce.zeroize();
162    }
163}
164
165/// Longest reuse of one short-link ticket, even when its lifetime is longer.
166const SHORT_LINK_MAX_REUSE: Duration = Duration::from_secs(3600);
167/// Stop reusing a ticket this long before its advertised lifetime ends.
168const SHORT_LINK_EXPIRY_MARGIN: Duration = Duration::from_secs(60);
169
170/// The short-link resumption ticket an account's owner reuses between
171/// requests. The long-link handshake issues an access PSK and ticket with a
172/// lifetime; short-link requests present it, so a new long-link handshake is
173/// only needed when no ticket is cached for the host, the cached one is near
174/// the end of its lifetime, or a short exchange that used it failed. Held only
175/// in memory and zeroized with the session when replaced.
176#[derive(Default)]
177pub(crate) struct ShortLinkCache {
178    entry: std::sync::Mutex<Option<(String, ShortSession, Instant)>>,
179}
180impl ShortLinkCache {
181    /// A clone of the cached ticket for `host` while it is still reusable.
182    pub(crate) fn get(&self, host: &str) -> Option<ShortSession> {
183        self.get_at(host, Instant::now())
184    }
185    fn get_at(&self, host: &str, now: Instant) -> Option<ShortSession> {
186        let entry = self.entry.lock().ok()?;
187        let (cached_host, session, issued) = entry.as_ref()?;
188        let lifetime = Duration::from_secs(u64::from(session.ticket.lifetime))
189            .saturating_sub(SHORT_LINK_EXPIRY_MARGIN)
190            .min(SHORT_LINK_MAX_REUSE);
191        (cached_host == host && now.saturating_duration_since(*issued) < lifetime)
192            .then(|| session.clone())
193    }
194    /// Remember the ticket a long-link handshake to `host` just issued.
195    pub(crate) fn put(&self, host: &str, session: ShortSession) {
196        self.put_at(host, session, Instant::now());
197    }
198    fn put_at(&self, host: &str, session: ShortSession, issued: Instant) {
199        if let Ok(mut entry) = self.entry.lock() {
200            *entry = Some((host.to_string(), session, issued));
201        }
202    }
203    /// Forget the cached ticket so the next request performs a handshake.
204    pub(crate) fn invalidate(&self) {
205        if let Ok(mut entry) = self.entry.lock() {
206            *entry = None;
207        }
208    }
209}
210pub struct Session {
211    socket: TcpStream,
212    deadline: Instant,
213    received: usize,
214    receive_budget: usize,
215    pub short: ShortSession,
216    pub certificate_region: u32,
217    pub certificate_version: u32,
218    traffic: Traffic,
219    outgoing: u64,
220    incoming: u64,
221    record_pending: Vec<u8>,
222    application_pending: LonglinkDecoder,
223}
224
225fn host_valid(name: &str) -> bool {
226    !name.is_empty()
227        && name.len() <= 253
228        && name.is_ascii()
229        && name.split('.').all(|s| {
230            !s.is_empty()
231                && s.len() <= 63
232                && s.bytes()
233                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
234                && !s.starts_with('-')
235                && !s.ends_with('-')
236        })
237        && (name.ends_with(".wechat.com") || name.ends_with(".weixin.qq.com"))
238}
239pub fn validate_host(name: &str) -> Result<()> {
240    ensure!(host_valid(name), "Unsupported native server host");
241    Ok(())
242}
243fn read_exact_deadline(
244    socket: &mut TcpStream,
245    mut bytes: &mut [u8],
246    deadline: Instant,
247) -> Result<()> {
248    while !bytes.is_empty() {
249        let remaining = deadline.saturating_duration_since(Instant::now());
250        ensure!(!remaining.is_zero(), "MMTLS deadline exceeded");
251        socket.set_read_timeout(Some(remaining))?;
252        match socket.read(bytes) {
253            Ok(0) => anyhow::bail!("MMTLS connection closed"),
254            Ok(n) => bytes = &mut bytes[n..],
255            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
256            Err(e) => return Err(e.into()),
257        }
258    }
259    Ok(())
260}
261fn read_record(
262    socket: &mut TcpStream,
263    deadline: Instant,
264    received: &mut usize,
265    budget: usize,
266) -> Result<Record> {
267    let mut h = [0; 5];
268    read_exact_deadline(socket, &mut h, deadline)?;
269    ensure!(
270        (0x15..=0x19).contains(&h[0]) && u16::from_be_bytes([h[1], h[2]]) == VERSION,
271        "Unexpected MMTLS header"
272    );
273    let n = u16::from_be_bytes([h[3], h[4]]) as usize;
274    *received = received
275        .checked_add(n + 5)
276        .ok_or_else(|| anyhow::anyhow!("Receive overflow"))?;
277    ensure!(*received <= budget, "MMTLS receive budget exceeded");
278    let mut body = vec![0; n];
279    read_exact_deadline(socket, &mut body, deadline)?;
280    ensure!(h[0] != 0x15, "Server returned MMTLS alert");
281    Ok(Record { header: h, body })
282}
283
284impl Session {
285    pub fn connect(host: &str, timeout: Duration, receive_budget: usize) -> Result<Self> {
286        validate_host(host)?;
287        ensure!(
288            (1024..=crate::MAX_MESSAGE_BYTES).contains(&receive_budget),
289            "Invalid receive budget"
290        );
291        ensure!(
292            !timeout.is_zero() && timeout <= Duration::from_secs(120),
293            "Invalid MMTLS timeout"
294        );
295        let deadline = Instant::now() + timeout;
296        // Resolver and connect are constrained by the caller's blocking worker. Socket
297        // read/write deadlines bound every subsequent protocol operation.
298        use std::net::ToSocketAddrs;
299        let addresses = (host, 80).to_socket_addrs()?;
300        let mut socket = None;
301        for addr in addresses {
302            let remaining = deadline.saturating_duration_since(Instant::now());
303            if remaining.is_zero() {
304                break;
305            }
306            if let Ok(s) = TcpStream::connect_timeout(&addr, remaining) {
307                socket = Some(s);
308                break;
309            }
310        }
311        let mut socket = socket.ok_or_else(|| anyhow::anyhow!("Native connection failed"))?;
312        socket.set_write_timeout(Some(timeout))?;
313        let keys = [
314            Ecdh::generate(Nid::X9_62_PRIME256V1).context("MMTLS key generation")?,
315            Ecdh::generate(Nid::X9_62_PRIME256V1).context("MMTLS key generation")?,
316        ];
317        let mut shares = vec![];
318        for (i, k) in keys.iter().enumerate() {
319            let point = k.public().context("MMTLS public key encoding")?;
320            shares.extend(section(
321                &[((i + 5) as u32).to_be_bytes().to_vec(), sized(&point)?].concat(),
322            ));
323        }
324        let mut extra = vec![0; 4];
325        extra.push(2);
326        extra.extend(5u32.to_be_bytes());
327        extra.extend(1000u32.to_be_bytes());
328        let extension = section(&[0x10u16.to_be_bytes().to_vec(), vec![2], shares, extra].concat());
329        let hello = section(
330            &[
331                vec![1],
332                VERSION.to_le_bytes().to_vec(),
333                vec![1],
334                0xc02bu16.to_be_bytes().to_vec(),
335                random::<32>().context("MMTLS hello random")?.to_vec(),
336                crate::wire::unix_time()?.to_be_bytes().to_vec(),
337                section(&[vec![1], extension].concat()),
338            ]
339            .concat(),
340        );
341        socket.write_all(&frame(0x16, &hello)?)?;
342        let mut received = 0;
343        let server_record = read_record(&mut socket, deadline, &mut received, receive_budget)?;
344        ensure!(server_record.header[0] == 0x16, "Expected handshake");
345        let server = parse_server_hello(&server_record.body)?;
346        let index = server
347            .key_id
348            .checked_sub(5)
349            .ok_or_else(|| anyhow::anyhow!("Unoffered key"))? as usize;
350        ensure!(index < 2, "Unoffered key");
351        let mut x = keys[index]
352            .derive(&server.point)
353            .context("MMTLS shared secret derivation")?;
354        let mut secret = handshake_secret(&x)?;
355        x.zeroize();
356        let mut transcript = [hello, server_record.body].concat();
357        let handshake = traffic(&secret, "handshake key expansion", &transcript)
358            .context("MMTLS handshake key derivation")?;
359        let r = read_record(&mut socket, deadline, &mut received, receive_budget)?;
360        ensure!(r.header[0] == 0x16, "Expected signature record");
361        let signature_body = open(&r, &handshake.server_key, &handshake.server_iv, 1)
362            .context("MMTLS signature record authentication")?;
363        let signature = signed_payload(&signature_body, 0x0f)?;
364        let pins: serde_json::Value =
365            serde_json::from_str(include_str!("../fixtures/mmtls-public-keys.json"))?;
366        let pin = pins["profiles"]
367            .as_array()
368            .unwrap()
369            .iter()
370            .find(|p| p["version"].as_u64() == Some(server.version as u64))
371            .ok_or_else(|| anyhow::anyhow!("Unsupported MMTLS certificate version"))?;
372        ensure!([5, 1000].contains(&server.version), "Unoffered MMTLS pin");
373        verify_signature(
374            pin["ecdsaPEM"].as_str().unwrap(),
375            &sha256(&transcript),
376            &signature,
377        )
378        .context("MMTLS signature verification")?;
379        transcript.extend(signature_body);
380        let r = read_record(&mut socket, deadline, &mut received, receive_budget)?;
381        ensure!(r.header[0] == 0x16, "Expected ticket record");
382        let ticket_body = open(&r, &handshake.server_key, &handshake.server_iv, 2)
383            .context("MMTLS ticket record authentication")?;
384        let tickets = parse_tickets(&ticket_body)?;
385        let access_psk = expand(
386            &secret,
387            &[b"PSK_ACCESS".as_slice(), &sha256(&transcript)].concat(),
388            32,
389        )?;
390        transcript.extend(ticket_body);
391        let r = read_record(&mut socket, deadline, &mut received, receive_budget)?;
392        ensure!(r.header[0] == 0x16, "Expected Finished");
393        let finish = signed_payload(
394            &open(&r, &handshake.server_key, &handshake.server_iv, 3)
395                .context("MMTLS finished record authentication")?,
396            0x14,
397        )?;
398        let expected = hmac(
399            &expand(&secret, b"server finished", 32)?,
400            &sha256(&transcript),
401        )?;
402        ensure!(
403            finish.len() == expected.len() && memcmp::eq(&finish, &expected),
404            "Server Finished verification failed"
405        );
406        let client_finish = hmac(
407            &expand(&secret, b"client finished", 32)?,
408            &sha256(&transcript),
409        )?;
410        socket.write_all(&seal(
411            0x16,
412            &section(&[vec![0x14], sized(&client_finish)?].concat()),
413            &handshake.client_key,
414            &handshake.client_iv,
415            1,
416        )?)?;
417        let mut expanded = expand(
418            &secret,
419            &[b"expanded secret".as_slice(), &sha256(&transcript)].concat(),
420            32,
421        )?;
422        let application = traffic(&expanded, "application data key expansion", &transcript)
423            .context("MMTLS application key derivation")?;
424        secret.zeroize();
425        expanded.zeroize();
426        let noop = pack_longlink(6, u32::MAX, &[])?;
427        socket.write_all(
428            &seal(
429                0x17,
430                &noop,
431                &application.client_key,
432                &application.client_iv,
433                2,
434            )
435            .context("MMTLS noop record sealing")?,
436        )?;
437        let r = read_record(&mut socket, deadline, &mut received, receive_budget)?;
438        ensure!(r.header[0] == 0x17, "Expected NOOP reply");
439        let p = unpack_longlink(
440            &open(&r, &application.server_key, &application.server_iv, 4)
441                .context("MMTLS noop record authentication")?,
442        )?;
443        ensure!(
444            p.command == 0x3b9aca06 && p.sequence == u32::MAX && p.payload.is_empty(),
445            "Unexpected NOOP reply"
446        );
447        Ok(Self {
448            socket,
449            deadline,
450            received,
451            receive_budget,
452            short: ShortSession {
453                access_psk,
454                ticket: tickets[0].clone(),
455            },
456            certificate_region: server.region,
457            certificate_version: server.version,
458            traffic: application,
459            outgoing: 3,
460            incoming: 5,
461            record_pending: Vec::new(),
462            application_pending: LonglinkDecoder {
463                pending: Vec::new(),
464                max_payload: receive_budget,
465            },
466        })
467    }
468    pub fn send_application(&mut self, command: u32, sequence: u32, payload: &[u8]) -> Result<()> {
469        let bytes = seal(
470            0x17,
471            &pack_longlink(command, sequence, payload)?,
472            &self.traffic.client_key,
473            &self.traffic.client_iv,
474            self.outgoing,
475        )?;
476        self.socket.write_all(&bytes)?;
477        self.outgoing = self
478            .outgoing
479            .checked_add(1)
480            .ok_or_else(|| anyhow::anyhow!("Sequence exhausted"))?;
481        Ok(())
482    }
483    pub fn receive_application(&mut self) -> Result<Longlink> {
484        let r = read_record(
485            &mut self.socket,
486            self.deadline,
487            &mut self.received,
488            self.receive_budget,
489        )?;
490        ensure!(r.header[0] == 0x17, "Expected application record");
491        let plain = open(
492            &r,
493            &self.traffic.server_key,
494            &self.traffic.server_iv,
495            self.incoming,
496        )?;
497        self.incoming = self
498            .incoming
499            .checked_add(1)
500            .ok_or_else(|| anyhow::anyhow!("Sequence exhausted"))?;
501        unpack_longlink(&plain)
502    }
503
504    /// A bounded idle wait on an established connection. Partial encrypted
505    /// records and application packets survive a timeout; MMTLS record
506    /// boundaries need not coincide with longlink packet boundaries.
507    pub fn poll_application(&mut self, timeout: Duration) -> Result<Option<Longlink>> {
508        ensure!(
509            !timeout.is_zero() && timeout <= Duration::from_secs(120),
510            "Invalid longlink poll timeout"
511        );
512        let deadline = Instant::now() + timeout;
513        loop {
514            if let Some(packet) = self.application_pending.next_packet()? {
515                return Ok(Some(packet));
516            }
517            if self.record_pending.len() >= 5 {
518                let h: [u8; 5] = self.record_pending[..5].try_into()?;
519                ensure!(
520                    (0x15..=0x19).contains(&h[0]) && u16::from_be_bytes([h[1], h[2]]) == VERSION,
521                    "Unexpected MMTLS header"
522                );
523                let n = u16::from_be_bytes([h[3], h[4]]) as usize;
524                if self.record_pending.len() >= n + 5 {
525                    ensure!(h[0] == 0x17, "Unexpected persistent MMTLS record");
526                    let record = Record {
527                        header: h,
528                        body: self.record_pending[5..n + 5].to_vec(),
529                    };
530                    let plain = open(
531                        &record,
532                        &self.traffic.server_key,
533                        &self.traffic.server_iv,
534                        self.incoming,
535                    )?;
536                    self.incoming = self
537                        .incoming
538                        .checked_add(1)
539                        .ok_or_else(|| anyhow::anyhow!("Sequence exhausted"))?;
540                    self.record_pending.drain(..n + 5);
541                    self.application_pending.feed(&plain)?;
542                    continue;
543                }
544            }
545            let remaining = deadline.saturating_duration_since(Instant::now());
546            if remaining.is_zero() {
547                return Ok(None);
548            }
549            self.socket.set_read_timeout(Some(remaining))?;
550            let mut bytes = [0u8; 65540];
551            match self.socket.read(&mut bytes) {
552                Ok(0) => anyhow::bail!("MMTLS connection closed"),
553                Ok(n) => {
554                    // At most one incomplete record precedes a socket read.
555                    ensure!(
556                        self.record_pending.len() + n <= 131080,
557                        "MMTLS pending record limit"
558                    );
559                    self.record_pending.extend_from_slice(&bytes[..n]);
560                }
561                Err(e)
562                    if matches!(
563                        e.kind(),
564                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
565                    ) =>
566                {
567                    return Ok(None)
568                }
569                Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
570                Err(e) => return Err(e.into()),
571            }
572        }
573    }
574}
575struct ServerHello {
576    key_id: u32,
577    point: Vec<u8>,
578    region: u32,
579    version: u32,
580}
581fn parse_server_hello(bytes: &[u8]) -> Result<ServerHello> {
582    let mut top = Cursor::new(bytes);
583    let mut b = Cursor::new(top.sized(4)?);
584    top.end()?;
585    ensure!(
586        b.uint(1)? == 2 && b.take(2)? == VERSION.to_le_bytes() && b.uint(2)? == 0xc02b,
587        "Unsupported ServerHello"
588    );
589    b.take(32)?;
590    let mut e = Cursor::new(b.sized(4)?);
591    b.end()?;
592    let count = e.uint(1)?;
593    let mut seen = std::collections::HashSet::new();
594    let mut share = None;
595    let mut cert = None;
596    for _ in 0..count {
597        let mut x = Cursor::new(e.sized(4)?);
598        let kind = x.uint(2)?;
599        ensure!(seen.insert(kind), "Duplicate extension");
600        match kind {
601            0x11 => {
602                let id = x.uint(4)? as u32;
603                let point = x.sized(2)?.to_vec();
604                ensure!(point.len() == 65 && point[0] == 4, "Invalid ECDH point");
605                x.end()?;
606                share = Some((id, point));
607            }
608            0x13 => {
609                let region = x.uint(4)? as u32;
610                let version = x.uint(4)? as u32;
611                x.end()?;
612                cert = Some((region, version));
613            }
614            _ => {}
615        }
616    }
617    e.end()?;
618    let (key_id, point) = share.ok_or_else(|| anyhow::anyhow!("Missing ECDH selection"))?;
619    let (region, version) = cert.ok_or_else(|| anyhow::anyhow!("Missing certificate selection"))?;
620    Ok(ServerHello {
621        key_id,
622        point,
623        region,
624        version,
625    })
626}
627fn parse_tickets(input: &[u8]) -> Result<Vec<Ticket>> {
628    let mut top = Cursor::new(input);
629    let mut b = Cursor::new(top.sized(4)?);
630    top.end()?;
631    ensure!(b.uint(1)? == 4, "Expected tickets");
632    let count = b.uint(1)?;
633    ensure!((1..=4).contains(&count), "Invalid ticket count");
634    let mut out = vec![];
635    for _ in 0..count {
636        let mut t = Cursor::new(b.sized(4)?);
637        let kind = t.uint(1)? as u8;
638        let lifetime = t.uint(4)? as u32;
639        t.sized(2)?;
640        let reserved = t.uint(4)? as u32;
641        let nonce = t.sized(2)?.to_vec();
642        let opaque = t.sized(2)?.to_vec();
643        t.end()?;
644        ensure!(
645            nonce.len() == 12 && !opaque.is_empty(),
646            "Invalid shortlink ticket"
647        );
648        out.push(Ticket {
649            kind,
650            lifetime,
651            reserved,
652            nonce,
653            opaque,
654        });
655    }
656    b.end()?;
657    Ok(out)
658}
659pub struct Longlink {
660    pub command: u32,
661    pub sequence: u32,
662    pub payload: Vec<u8>,
663}
664struct LonglinkDecoder {
665    pending: Vec<u8>,
666    max_payload: usize,
667}
668impl Default for LonglinkDecoder {
669    fn default() -> Self {
670        Self {
671            pending: Vec::new(),
672            max_payload: crate::MAX_MESSAGE_BYTES,
673        }
674    }
675}
676impl LonglinkDecoder {
677    fn feed(&mut self, bytes: &[u8]) -> Result<()> {
678        ensure!(
679            self.pending.len().saturating_add(bytes.len()) <= self.max_payload + 65540,
680            "Longlink pending packet limit"
681        );
682        self.pending.extend_from_slice(bytes);
683        Ok(())
684    }
685    fn next_packet(&mut self) -> Result<Option<Longlink>> {
686        if self.pending.len() < 4 {
687            return Ok(None);
688        }
689        let n = u32::from_be_bytes(self.pending[..4].try_into()?) as usize;
690        ensure!(
691            (16..=self.max_payload + 16).contains(&n),
692            "Invalid longlink packet length"
693        );
694        if self.pending.len() >= 8 {
695            ensure!(
696                self.pending[4..8] == [0, 16, 0, 1],
697                "Invalid longlink envelope"
698            );
699        }
700        if self.pending.len() < n {
701            return Ok(None);
702        }
703        let packet = unpack_longlink(&self.pending[..n])?;
704        self.pending.drain(..n);
705        Ok(Some(packet))
706    }
707}
708pub fn pack_longlink(command: u32, sequence: u32, payload: &[u8]) -> Result<Vec<u8>> {
709    ensure!(payload.len() <= 65503, "Longlink body too large");
710    Ok([
711        ((16 + payload.len()) as u32).to_be_bytes().to_vec(),
712        0x10u16.to_be_bytes().to_vec(),
713        1u16.to_be_bytes().to_vec(),
714        command.to_be_bytes().to_vec(),
715        sequence.to_be_bytes().to_vec(),
716        payload.to_vec(),
717    ]
718    .concat())
719}
720pub fn unpack_longlink(input: &[u8]) -> Result<Longlink> {
721    let mut c = Cursor::new(input);
722    ensure!(
723        c.uint(4)? == input.len() as u64 && c.uint(2)? == 0x10 && c.uint(2)? == 1,
724        "Invalid longlink envelope"
725    );
726    let command = c.uint(4)? as u32;
727    let sequence = c.uint(4)? as u32;
728    let payload = c.take(input.len() - 16)?.to_vec();
729    Ok(Longlink {
730        command,
731        sequence,
732        payload,
733    })
734}
735
736/// A route rejected locally before any short-link request bytes are submitted.
737#[derive(Debug)]
738pub(crate) struct UnsupportedNativeRoute;
739impl std::fmt::Display for UnsupportedNativeRoute {
740    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
741        f.write_str("Unsupported native route")
742    }
743}
744impl std::error::Error for UnsupportedNativeRoute {}
745pub(crate) fn validate_short_route(path: &str) -> Result<()> {
746    let ordinary = path.starts_with("/cgi-bin/micromsg-bin/")
747        && path
748            .bytes()
749            .all(|b| b.is_ascii_alphanumeric() || b == b'/' || b == b'-');
750    if ordinary || path == "/cgi-bin/micromsg-bin/mm_ilink_cloud_app_auth" {
751        Ok(())
752    } else {
753        Err(UnsupportedNativeRoute.into())
754    }
755}
756
757pub fn short_exchange(
758    session: &ShortSession,
759    host: &str,
760    path: &str,
761    payload: &[u8],
762    timeout: Duration,
763) -> Result<Vec<u8>> {
764    let (hello, extensions, wire) = prepare_short_exchange(session, host, path, payload)?;
765    let client = reqwest::blocking::Client::builder()
766        .timeout(timeout)
767        .connect_timeout(timeout.min(Duration::from_secs(10)))
768        .redirect(reqwest::redirect::Policy::none())
769        .no_proxy()
770        .build()?;
771    let mut response = client
772        .post(format!(
773            "http://{host}/mmtls/{}",
774            hex::encode(random::<4>()?)
775        ))
776        .header("Content-Type", "application/octet-stream")
777        .header("User-Agent", "MicroMessenger Client")
778        .header("Upgrade", "mmtls")
779        .header("Accept", "*/*")
780        .header("Cache-Control", "no-cache")
781        .header("Connection", "close")
782        .body(wire)
783        .send()?;
784    ensure!(
785        response.status() == 200,
786        "Native shortlink HTTP status {}",
787        response.status().as_u16()
788    );
789    let mut bytes = Vec::new();
790    response
791        .by_ref()
792        .take((crate::MAX_MESSAGE_BYTES + 1) as u64)
793        .read_to_end(&mut bytes)?;
794    ensure!(
795        bytes.len() <= crate::MAX_MESSAGE_BYTES,
796        "Shortlink receive budget exceeded"
797    );
798    decode_short_reply(&bytes, session, &hello, &extensions)
799}
800fn prepare_short_exchange(
801    session: &ShortSession,
802    host: &str,
803    path: &str,
804    payload: &[u8],
805) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
806    validate_host(host)?;
807    validate_short_route(path)?;
808    ensure!(
809        payload.len() <= crate::MAX_MESSAGE_BYTES,
810        "Payload too large"
811    );
812    let (hello, extensions) = early_hello(&session.ticket)?;
813    let keys = expand(
814        &session.access_psk,
815        &[b"early data key expansion".as_slice(), &sha256(&hello)].concat(),
816        28,
817    )?;
818    let route = section(
819        &[
820            sized(path.as_bytes())?,
821            sized(host.as_bytes())?,
822            section(payload),
823        ]
824        .concat(),
825    );
826    let mut wire = [
827        frame(0x19, &hello)?,
828        seal(0x19, &extensions, &keys[..16], &keys[16..], 1)?,
829    ]
830    .concat();
831    // The route is one application message, but large encrypted upload chunks
832    // span records. Every data record and the close use consecutive nonces.
833    let mut sequence = 2;
834    for chunk in route.chunks(MAX_RECORD_PLAINTEXT) {
835        wire.extend(seal(0x17, chunk, &keys[..16], &keys[16..], sequence)?);
836        sequence += 1;
837    }
838    wire.extend(seal(
839        0x15,
840        &section(&[0, 1, 1]),
841        &keys[..16],
842        &keys[16..],
843        sequence,
844    )?);
845    Ok((hello, extensions, wire))
846}
847
848/// The pre-answer poll can stop waiting without applying a late reply.
849pub(crate) async fn short_exchange_interruptible(
850    session: &ShortSession,
851    host: &str,
852    path: &str,
853    payload: &[u8],
854    timeout: Duration,
855) -> Result<Vec<u8>> {
856    let (hello, extensions, wire) = prepare_short_exchange(session, host, path, payload)?;
857    let client = reqwest::Client::builder()
858        .timeout(timeout)
859        .connect_timeout(timeout.min(Duration::from_secs(10)))
860        .redirect(reqwest::redirect::Policy::none())
861        .no_proxy()
862        .build()?;
863    let mut response = client
864        .post(format!(
865            "http://{host}/mmtls/{}",
866            hex::encode(random::<4>()?)
867        ))
868        .header("Content-Type", "application/octet-stream")
869        .header("User-Agent", "MicroMessenger Client")
870        .header("Upgrade", "mmtls")
871        .header("Accept", "*/*")
872        .header("Cache-Control", "no-cache")
873        .header("Connection", "close")
874        .body(wire)
875        .send()
876        .await?;
877    ensure!(
878        response.status() == 200,
879        "Native shortlink HTTP status {}",
880        response.status().as_u16()
881    );
882    let mut bytes = Vec::new();
883    while let Some(chunk) = response.chunk().await? {
884        ensure!(
885            chunk.len() <= crate::MAX_MESSAGE_BYTES - bytes.len(),
886            "Shortlink receive budget exceeded"
887        );
888        bytes.extend_from_slice(&chunk);
889    }
890    decode_short_reply(&bytes, session, &hello, &extensions)
891}
892fn early_hello(ticket: &Ticket) -> Result<(Vec<u8>, Vec<u8>)> {
893    ensure!(
894        ticket.nonce.len() == 12 && !ticket.opaque.is_empty(),
895        "Invalid short ticket"
896    );
897    let now = crate::wire::unix_time()?;
898    let encoded = [
899        vec![ticket.kind],
900        ticket.lifetime.to_be_bytes().to_vec(),
901        sized(&[])?,
902        ticket.reserved.to_be_bytes().to_vec(),
903        sized(&ticket.nonce)?,
904        sized(&ticket.opaque)?,
905    ]
906    .concat();
907    let ext = section(&[0x0fu16.to_be_bytes().to_vec(), vec![1], section(&encoded)].concat());
908    let hello = section(
909        &[
910            vec![1],
911            VERSION.to_le_bytes().to_vec(),
912            vec![1],
913            0xa8u16.to_be_bytes().to_vec(),
914            random::<32>()?.to_vec(),
915            now.to_be_bytes().to_vec(),
916            section(&[vec![1], ext].concat()),
917        ]
918        .concat(),
919    );
920    let extensions = section(
921        &[
922            vec![8],
923            section(
924                &[
925                    vec![1],
926                    section(&[0x12u16.to_be_bytes().to_vec(), now.to_be_bytes().to_vec()].concat()),
927                ]
928                .concat(),
929            ),
930        ]
931        .concat(),
932    );
933    Ok((hello, extensions))
934}
935fn decode_short_reply(
936    input: &[u8],
937    session: &ShortSession,
938    hello: &[u8],
939    extensions: &[u8],
940) -> Result<Vec<u8>> {
941    let mut c = Cursor::new(input);
942    let mut records = vec![];
943    while c.offset < input.len() {
944        let h: [u8; 5] = c.take(5)?.try_into()?;
945        ensure!(
946            (0x15..=0x19).contains(&h[0]) && u16::from_be_bytes([h[1], h[2]]) == VERSION,
947            "Invalid shortlink header"
948        );
949        records.push(Record {
950            header: h,
951            body: c.take(u16::from_be_bytes([h[3], h[4]]) as usize)?.to_vec(),
952        });
953    }
954    ensure!(
955        records.len() >= 4
956            && records[0].header[0] == 0x16
957            && records[1].header[0] == 0x16
958            && records.last().unwrap().header[0] == 0x15
959            && records[2..records.len() - 1]
960                .iter()
961                .all(|r| r.header[0] == 0x17),
962        "Invalid shortlink sequence"
963    );
964    let server = &records[0];
965    let mut top = Cursor::new(&server.body);
966    let mut b = Cursor::new(top.sized(4)?);
967    top.end()?;
968    ensure!(
969        b.uint(1)? == 2 && b.take(2)? == VERSION.to_le_bytes() && b.uint(2)? == 0xa8,
970        "Unsupported shortlink selection"
971    );
972    b.take(32)?;
973    let mut e = Cursor::new(b.sized(4)?);
974    b.end()?;
975    ensure!(e.uint(1)? == 0, "Unsupported shortlink extensions");
976    e.end()?;
977    let transcript = [hello, extensions, &server.body].concat();
978    let keys = expand(
979        &session.access_psk,
980        &[b"handshake key expansion".as_slice(), &sha256(&transcript)].concat(),
981        28,
982    )?;
983    let finish = signed_payload(&open(&records[1], &keys[..16], &keys[16..], 1)?, 0x14)?;
984    let expected = hmac(
985        &expand(&session.access_psk, b"server finished", 32)?,
986        &sha256(&transcript),
987    )?;
988    ensure!(
989        finish.len() == expected.len() && memcmp::eq(&finish, &expected),
990        "Shortlink Finished failed"
991    );
992    let mut plain = vec![];
993    for (i, r) in records[2..records.len() - 1].iter().enumerate() {
994        plain.extend(open(r, &keys[..16], &keys[16..], i as u64 + 2)?);
995        ensure!(
996            plain.len() <= crate::MAX_MESSAGE_BYTES,
997            "Shortlink plaintext too large"
998        );
999    }
1000    ensure!(
1001        open(
1002            records.last().unwrap(),
1003            &keys[..16],
1004            &keys[16..],
1005            records.len() as u64 - 1
1006        )? == section(&[0, 1, 1]),
1007        "Unexpected shortlink close"
1008    );
1009    Ok(plain)
1010}
1011
1012#[cfg(test)]
1013mod tests {
1014    #[test]
1015    fn short_link_tickets_are_reused_per_host_within_their_lifetime() {
1016        use super::*;
1017        let session = |lifetime: u32| ShortSession {
1018            access_psk: vec![0x42; 32],
1019            ticket: Ticket {
1020                kind: 1,
1021                lifetime,
1022                reserved: 0,
1023                nonce: vec![0; 12],
1024                opaque: vec![1],
1025            },
1026        };
1027        let start = Instant::now();
1028        let cache = ShortLinkCache::default();
1029        assert!(cache.get_at("long.example", start).is_none());
1030        cache.put_at("long.example", session(600), start);
1031        let reused = cache
1032            .get_at("long.example", start + Duration::from_secs(539))
1033            .expect("reused inside the lifetime margin");
1034        assert_eq!(reused.access_psk, vec![0x42; 32]);
1035        // Another host, the expiry margin and invalidation all force a handshake.
1036        assert!(cache.get_at("other.example", start).is_none());
1037        assert!(cache
1038            .get_at("long.example", start + Duration::from_secs(540))
1039            .is_none());
1040        cache.invalidate();
1041        assert!(cache.get_at("long.example", start).is_none());
1042        // Reuse is capped at an hour, and a ticket without lifetime is not reused.
1043        cache.put_at("long.example", session(86_400), start);
1044        assert!(cache
1045            .get_at("long.example", start + Duration::from_secs(3599))
1046            .is_some());
1047        assert!(cache
1048            .get_at("long.example", start + Duration::from_secs(3600))
1049            .is_none());
1050        cache.put_at("long.example", session(0), start);
1051        assert!(cache.get_at("long.example", start).is_none());
1052    }
1053    #[test]
1054    fn short_requests_split_large_uploads_and_authenticate_the_close_sequence() {
1055        let session = ShortSession {
1056            access_psk: vec![0x42; 32],
1057            ticket: Ticket {
1058                kind: 1,
1059                lifetime: 3600,
1060                reserved: 0,
1061                nonce: vec![0x24; 12],
1062                opaque: vec![0x17; 32],
1063            },
1064        };
1065        for size in [0, 60_000, 98_400, 200_000] {
1066            let payload = vec![0xa5; size];
1067            let (hello, extensions, wire) = prepare_short_exchange(
1068                &session,
1069                "short.weixin.qq.com",
1070                "/cgi-bin/micromsg-bin/mmemojiupload",
1071                &payload,
1072            )
1073            .unwrap();
1074            let keys = expand(
1075                &session.access_psk,
1076                &[b"early data key expansion".as_slice(), &sha256(&hello)].concat(),
1077                28,
1078            )
1079            .unwrap();
1080            let mut cursor = Cursor::new(&wire);
1081            let mut records = Vec::new();
1082            while cursor.offset < wire.len() {
1083                let header: [u8; 5] = cursor.take(5).unwrap().try_into().unwrap();
1084                let length = u16::from_be_bytes([header[3], header[4]]) as usize;
1085                records.push(Record {
1086                    header,
1087                    body: cursor.take(length).unwrap().to_vec(),
1088                });
1089            }
1090            assert_eq!(records[0].header[0], 0x19);
1091            assert_eq!(records[0].body, hello);
1092            assert_eq!(
1093                open(&records[1], &keys[..16], &keys[16..], 1).unwrap(),
1094                extensions
1095            );
1096            let mut route = Vec::new();
1097            for (sequence, record) in records[2..records.len() - 1].iter().enumerate() {
1098                assert_eq!(record.header[0], 0x17);
1099                route.extend(open(record, &keys[..16], &keys[16..], sequence as u64 + 2).unwrap());
1100            }
1101            let expected = section(
1102                &[
1103                    sized(b"/cgi-bin/micromsg-bin/mmemojiupload").unwrap(),
1104                    sized(b"short.weixin.qq.com").unwrap(),
1105                    section(&payload),
1106                ]
1107                .concat(),
1108            );
1109            assert_eq!(route, expected);
1110            let close = records.last().unwrap();
1111            assert_eq!(close.header[0], 0x15);
1112            assert_eq!(
1113                open(close, &keys[..16], &keys[16..], records.len() as u64 - 1).unwrap(),
1114                section(&[0, 1, 1])
1115            );
1116            assert!(open(close, &keys[..16], &keys[16..], records.len() as u64).is_err());
1117            if size <= 60_000 {
1118                assert_eq!(records.len(), 4);
1119            } else {
1120                assert!(records.len() > 4);
1121            }
1122        }
1123    }
1124
1125    #[test]
1126    fn fresh_handshake_secret_requires_the_selected_p256_width() {
1127        for wrong in [0, 28, 31, 33] {
1128            assert!(handshake_secret(&vec![1; wrong]).is_err());
1129        }
1130        assert_eq!(handshake_secret(&[1; 32]).unwrap(), sha256(&[1; 32]));
1131    }
1132    #[test]
1133    fn zero_prefixed_p256_secret_authenticates_an_independent_server_record() {
1134        // Synthetic P256 private scalars 1 and 379. The shared coordinate and
1135        // record were calculated independently using Python cryptography,
1136        // hashlib and hmac. No account data or captured traffic is used.
1137        let own = Ecdh::from_private(Nid::X9_62_PRIME256V1, &[1]).unwrap();
1138        let peer = Ecdh::from_private(Nid::X9_62_PRIME256V1, &[1, 123]).unwrap();
1139        let shared = own.derive(&peer.public().unwrap()).unwrap();
1140        assert_eq!(
1141            hex::encode(&shared),
1142            "005543894af3d00ed7d740abdbd75c96b06877b787db5f70eea78b90a8d7c00a"
1143        );
1144        let keys = traffic(
1145            &handshake_secret(&shared).unwrap(),
1146            "handshake key expansion",
1147            b"synthetic client hellosynthetic server hello",
1148        )
1149        .unwrap();
1150        let wire = hex::decode("16f10400314bbd4e0fa2f28903e143496cf3f42dd756b3e792e8359afb180b5bfaff820fcb03742b63ba60e98e9e3ac32f99f851f031").unwrap();
1151        let record = Record {
1152            header: wire[..5].try_into().unwrap(),
1153            body: wire[5..].to_vec(),
1154        };
1155        assert_eq!(
1156            open(&record, &keys.server_key, &keys.server_iv, 1).unwrap(),
1157            b"synthetic server signature record"
1158        );
1159        assert!(open(&record, &keys.server_key, &keys.server_iv, 2).is_err());
1160        let mut tampered = record;
1161        *tampered.body.last_mut().unwrap() ^= 1;
1162        assert!(open(&tampered, &keys.server_key, &keys.server_iv, 1).is_err());
1163    }
1164    #[test]
1165    fn exact_call_app_auth_route_does_not_admit_arbitrary_route_bytes() {
1166        assert!(validate_short_route("/cgi-bin/micromsg-bin/mm_ilink_cloud_app_auth").is_ok());
1167        assert!(validate_short_route("/cgi-bin/micromsg-bin/heartbeat").is_ok());
1168        assert!(validate_short_route("/cgi-bin/micromsg-bin/voipilinkack").is_ok());
1169        for bad in [
1170            "/cgi-bin/micromsg-bin/another_route",
1171            "/cgi-bin/micromsg-bin/mm_ilink_cloud_app_auth/extra",
1172            "/cgi-bin/micromsg-bin/mm_ilink_cloud_app_auth?x=1",
1173            "/cgi-bin/micromsg-bin/mm_ilink_cloud_app_auth#x",
1174            "/cgi-bin/micromsg-bin/mm_ilink_cloud_app_auth\r\nX: y",
1175            "/cgi-bin/micromsg-bin/mm_ilink_cloud_app_auth\0",
1176            "/cgi-bin/micromsg-bin/%2e%2e",
1177            "/cgi-bin/micromsg-bin/../x",
1178            "/cgi-bin/micromsg-bin/\\x",
1179            "/cgi-bin/micromsg-bin/音",
1180            "http://example.test/cgi-bin/micromsg-bin/heartbeat",
1181        ] {
1182            assert!(validate_short_route(bad)
1183                .unwrap_err()
1184                .is::<UnsupportedNativeRoute>());
1185        }
1186    }
1187    use super::*;
1188    #[test]
1189    fn longlink_frames_can_split_or_share_records_and_reject_bad_lengths_early() {
1190        let a = pack_longlink(24, 0, &6u32.to_be_bytes()).unwrap();
1191        let b = pack_longlink(1000000238, 23, &[2; 256]).unwrap();
1192        let both = [a.as_slice(), b.as_slice()].concat();
1193        for cut in 0..a.len() {
1194            let mut decoder = LonglinkDecoder::default();
1195            decoder.feed(&both[..cut]).unwrap();
1196            assert!(decoder.next_packet().unwrap().is_none());
1197            decoder.feed(&both[cut..]).unwrap();
1198            assert_eq!(decoder.next_packet().unwrap().unwrap().command, 24);
1199            assert_eq!(decoder.next_packet().unwrap().unwrap().sequence, 23);
1200            assert!(decoder.next_packet().unwrap().is_none());
1201        }
1202        for n in [0u32, 15, (crate::MAX_MESSAGE_BYTES + 17) as u32, u32::MAX] {
1203            let mut decoder = LonglinkDecoder::default();
1204            decoder.feed(&n.to_be_bytes()).unwrap();
1205            assert!(decoder.next_packet().is_err());
1206        }
1207        let mut invalid = a.clone();
1208        invalid[7] = 2;
1209        let mut decoder = LonglinkDecoder::default();
1210        decoder.feed(&invalid[..8]).unwrap();
1211        assert!(decoder.next_packet().is_err());
1212        let mut limited = LonglinkDecoder {
1213            pending: Vec::new(),
1214            max_payload: 128,
1215        };
1216        limited.feed(&b[..4]).unwrap();
1217        assert!(limited.next_packet().is_err());
1218        let payload = vec![7; 200_000];
1219        let large = [
1220            (payload.len() as u32 + 16).to_be_bytes().to_vec(),
1221            vec![0, 16, 0, 1],
1222            1000000121u32.to_be_bytes().to_vec(),
1223            9u32.to_be_bytes().to_vec(),
1224            payload.clone(),
1225        ]
1226        .concat();
1227        let mut decoder = LonglinkDecoder::default();
1228        for part in large.chunks(20_000) {
1229            decoder.feed(part).unwrap();
1230        }
1231        assert_eq!(decoder.next_packet().unwrap().unwrap().payload, payload);
1232    }
1233    #[test]
1234    fn encrypted_idle_timeout_keeps_partial_record_and_packet_bytes() {
1235        use std::{net::TcpListener, sync::mpsc, thread};
1236        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1237        let socket = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
1238        let (mut peer, _) = listener.accept().unwrap();
1239        let first = pack_longlink(24, 0, &6u32.to_be_bytes()).unwrap();
1240        let second = pack_longlink(1000000006, u32::MAX, &[]).unwrap();
1241        let key = vec![1; 16];
1242        let iv = vec![2; 12];
1243        let r1 = seal(0x17, &first[..10], &key, &iv, 5).unwrap();
1244        let r2 = seal(0x17, &[first[10..].to_vec(), second].concat(), &key, &iv, 6).unwrap();
1245        let mut corrupt = seal(0x17, &first, &key, &iv, 7).unwrap();
1246        *corrupt.last_mut().unwrap() ^= 1;
1247        let (sent, observed) = mpsc::channel();
1248        let (resume, waiting) = mpsc::channel();
1249        let writer = thread::spawn(move || {
1250            peer.write_all(&r1[..3]).unwrap();
1251            sent.send(()).unwrap();
1252            waiting.recv().unwrap();
1253            peer.write_all(&r1[3..]).unwrap();
1254            peer.write_all(&r2).unwrap();
1255            peer.write_all(&corrupt).unwrap();
1256        });
1257        let mut session = Session {
1258            socket,
1259            deadline: Instant::now(),
1260            received: 0,
1261            receive_budget: 1024,
1262            short: ShortSession {
1263                access_psk: vec![],
1264                ticket: Ticket {
1265                    kind: 1,
1266                    lifetime: 0,
1267                    reserved: 0,
1268                    nonce: vec![],
1269                    opaque: vec![],
1270                },
1271            },
1272            certificate_region: 0,
1273            certificate_version: 0,
1274            traffic: Traffic {
1275                client_key: key.clone(),
1276                server_key: key,
1277                client_iv: iv.clone(),
1278                server_iv: iv,
1279            },
1280            outgoing: 3,
1281            incoming: 5,
1282            record_pending: Vec::new(),
1283            application_pending: LonglinkDecoder::default(),
1284        };
1285        observed.recv().unwrap();
1286        assert!(session
1287            .poll_application(Duration::from_millis(10))
1288            .unwrap()
1289            .is_none());
1290        assert_eq!(session.record_pending.len(), 3);
1291        resume.send(()).unwrap();
1292        assert_eq!(
1293            session
1294                .poll_application(Duration::from_secs(1))
1295                .unwrap()
1296                .unwrap()
1297                .command,
1298            24
1299        );
1300        assert_eq!(
1301            session
1302                .poll_application(Duration::from_secs(1))
1303                .unwrap()
1304                .unwrap()
1305                .sequence,
1306            u32::MAX
1307        );
1308        assert!(session.poll_application(Duration::from_secs(1)).is_err());
1309        assert_eq!(session.incoming, 7);
1310        writer.join().unwrap();
1311    }
1312    #[test]
1313    fn published_mmtls_vector() {
1314        let key = hex::decode("29b37affd98238fb0370c564d8fa992e").unwrap();
1315        let wire_nonce = hex::decode("36ee037a258fbb83ca1f9762").unwrap();
1316        let base = nonce(&wire_nonce, 1).unwrap();
1317        let plain = hex::decode(
1318            "0000002314002009d6fc43a65a48dd64e3b6846562d13752f5abc2cb254539906ecd429df71082",
1319        )
1320        .unwrap();
1321        let expected=hex::decode("16f1040037e4bdea652cd80a273fd2ef549df4c87c1083c23f658fcc2d4152d163bc809f35a56fd0f4a62caa138d765a086eec02e21704892a981cf7").unwrap();
1322        assert_eq!(seal(0x16, &plain, &key, &base, 1).unwrap(), expected);
1323        let r = Record {
1324            header: expected[..5].try_into().unwrap(),
1325            body: expected[5..].to_vec(),
1326        };
1327        assert_eq!(open(&r, &key, &base, 1).unwrap(), plain);
1328        assert!(open(&r, &key, &base, 2).is_err());
1329    }
1330    #[test]
1331    fn hosts_restricted() {
1332        for s in [
1333            "localhost",
1334            "127.0.0.1",
1335            "long.weixin.qq.com.attacker.org",
1336            "-x.wechat.com",
1337            "x.wechat.com:80",
1338        ] {
1339            assert!(validate_host(s).is_err());
1340        }
1341        assert!(validate_host("long.weixin.qq.com").is_ok());
1342    }
1343    #[test]
1344    fn malformed_envelopes() {
1345        assert!(unpack_longlink(&[]).is_err());
1346        assert!(parse_server_hello(&[0; 4]).is_err());
1347        let mut v = pack_longlink(6, 123, &[1, 2]).unwrap();
1348        v[3] ^= 1;
1349        assert!(unpack_longlink(&v).is_err());
1350    }
1351}