wechat_protocol/
sticker.rs1use anyhow::{ensure, Result};
3use serde::{Deserialize, Serialize};
4use std::{
5 io::Read,
6 net::{IpAddr, ToSocketAddrs},
7 time::Duration,
8};
9pub use wechat_media::{inspect_image, ImageInspection};
10#[derive(Clone, Serialize, Deserialize)]
11pub struct StickerDescriptor {
12 pub url: String,
13 pub expected_bytes: u64,
14 pub expected_md5: String,
15 pub expires_at: Option<u64>,
16}
17pub(super) fn public_ip(ip: IpAddr) -> bool {
18 match ip {
19 IpAddr::V4(v) => {
20 let [a, b, c, _] = v.octets();
21 super::public_ipv4(v) && !(a == 192 && b == 88 && c == 99)
22 }
23 IpAddr::V6(v) => {
24 let s = v.segments();
25 s[0] & 0xe000 == 0x2000
26 && !(s[0] == 0x2001 && (s[1] < 0x0200 || s[1] == 0x0db8))
27 && s[0] != 0x2002
28 && !(s[0] == 0x3fff && s[1] & 0xf000 == 0)
29 }
30 }
31}
32pub const STICKER_HOSTS: &[&str] = &["snsvideo.c2c.wechat.com", "wxapp.tc.qq.com"];
38
39pub fn validate_sticker_url(value: &str) -> Result<reqwest::Url> {
40 ensure!(
41 value.len() <= 8192 && !value.chars().any(|c| c.is_control()),
42 "sticker_source_not_allowed"
43 );
44 let url =
45 reqwest::Url::parse(value).map_err(|_| anyhow::anyhow!("sticker_source_not_allowed"))?;
46 ensure!(
47 ["http", "https"].contains(&url.scheme())
48 && url
49 .host_str()
50 .is_some_and(|host| STICKER_HOSTS.contains(&host))
51 && url.username().is_empty()
52 && url.password().is_none()
53 && url.fragment().is_none()
54 && url
55 .port()
56 .is_none_or(|p| p == if url.scheme() == "https" { 443 } else { 80 }),
57 "sticker_source_not_allowed"
58 );
59 Ok(url)
60}
61pub fn fetch_sticker(
62 descriptor: &StickerDescriptor,
63 mut progress: impl FnMut(u64, Option<u64>) -> Result<()>,
64) -> Result<(Vec<u8>, ImageInspection)> {
65 ensure!(
66 descriptor.expected_bytes > 0 && descriptor.expected_bytes <= 16 * 1024 * 1024,
67 "sticker_metadata_invalid"
68 );
69 if let Some(expiry) = descriptor.expires_at {
70 ensure!(expiry > crate::wire::unix_time()? as u64, "media_expired");
71 }
72 fetch_sticker_source(
73 &descriptor.url,
74 &descriptor.expected_md5,
75 Some(descriptor.expected_bytes),
76 &mut progress,
77 )
78}
79
80pub fn fetch_sticker_original(
83 url: &str,
84 expected_md5: &str,
85 progress: impl FnMut(u64, Option<u64>) -> Result<()>,
86) -> Result<(Vec<u8>, ImageInspection)> {
87 fetch_sticker_source(url, expected_md5, None, progress)
88}
89fn fetch_sticker_source(
90 url: &str,
91 expected_md5: &str,
92 expected_bytes: Option<u64>,
93 mut progress: impl FnMut(u64, Option<u64>) -> Result<()>,
94) -> Result<(Vec<u8>, ImageInspection)> {
95 let url = validate_sticker_url(url)?;
96 ensure!(
97 expected_md5.len() == 32 && expected_md5.bytes().all(|b| b.is_ascii_hexdigit()),
98 "sticker_metadata_invalid"
99 );
100 progress(0, expected_bytes)?;
101 let host = url
102 .host_str()
103 .ok_or_else(|| anyhow::anyhow!("sticker_source_not_allowed"))?;
104 let port = if url.scheme() == "https" { 443 } else { 80 };
105 let addresses = (host, port)
106 .to_socket_addrs()
107 .map_err(|_| anyhow::anyhow!("sticker_dns_failed"))?
108 .collect::<Vec<_>>();
109 ensure!(
110 !addresses.is_empty()
111 && addresses.len() <= 64
112 && addresses.iter().all(|a| public_ip(a.ip())),
113 "sticker_source_dns_not_public"
114 );
115 let address = addresses
116 .iter()
117 .find(|a| a.is_ipv4())
118 .or_else(|| addresses.first())
119 .unwrap();
120 let client = reqwest::blocking::Client::builder()
121 .timeout(Duration::from_secs(20))
122 .connect_timeout(Duration::from_secs(5))
123 .redirect(reqwest::redirect::Policy::none())
124 .no_proxy()
125 .resolve(host, *address)
126 .build()?;
127 let mut response = client
128 .get(url)
129 .header("Accept-Encoding", "identity")
130 .send()
131 .map_err(|_| anyhow::anyhow!("sticker_fetch_failed"))?;
132 ensure!(
133 response.status() == 200,
134 "sticker_http_status_{}",
135 response.status().as_u16()
136 );
137 ensure!(
138 response
139 .headers()
140 .get("content-encoding")
141 .is_none_or(|v| v.as_bytes().eq_ignore_ascii_case(b"identity")),
142 "sticker_content_encoding_refused"
143 );
144 if let Some(length) = response.content_length() {
145 ensure!(length <= 16 * 1024 * 1024, "sticker_response_too_large");
146 }
147 let mut bytes = vec![];
148 let mut chunk = [0u8; 65536];
149 loop {
150 progress(bytes.len() as u64, expected_bytes)?;
151 let n = response
152 .read(&mut chunk)
153 .map_err(|_| anyhow::anyhow!("sticker_fetch_failed"))?;
154 if n == 0 {
155 break;
156 }
157 bytes.extend_from_slice(&chunk[..n]);
158 ensure!(
159 bytes.len() <= 16 * 1024 * 1024,
160 "sticker_response_too_large"
161 );
162 }
163 ensure!(
164 expected_bytes.is_none_or(|length| bytes.len() as u64 == length)
165 && hex::encode(crate::crypto::md5(&bytes)).eq_ignore_ascii_case(expected_md5),
166 "media_integrity_failed"
167 );
168 let inspection = inspect_image(&bytes)?;
169 Ok((bytes, inspection))
170}
171#[cfg(test)]
172mod tests {
173 use super::*;
174 #[test]
175 fn both_receiving_transports_are_allowed() {
176 for u in [
177 "https://snsvideo.c2c.wechat.com/x",
178 "http://wxapp.tc.qq.com/275/20304/stodownload?m=318341a160b08b297892a0e5741cc553&filekey=3035020101042130&bizid=1023",
179 "https://wxapp.tc.qq.com:443/x",
180 ] {
181 assert!(validate_sticker_url(u).is_ok(), "{u}");
182 }
183 for u in [
184 "http://wxapp.tc.qq.com.evil/x",
185 "https://wxapp.tc.qq.com.cn/x",
186 "http://evil.tc.qq.com/x",
187 "http://wxapp.tc.qq.com:8080/x",
188 ] {
189 assert!(validate_sticker_url(u).is_err(), "{u}");
190 }
191 }
192
193 #[test]
194 fn url_and_network_sources_are_strict() {
195 for u in [
196 "https://127.0.0.1/x",
197 "https://snsvideo.c2c.wechat.com.evil/x",
198 "https://user@snsvideo.c2c.wechat.com/x",
199 "https://snsvideo.c2c.wechat.com:444/x",
200 "https://snsvideo.c2c.wechat.com/x#fragment",
201 ] {
202 assert!(validate_sticker_url(u).is_err());
203 }
204 for ip in ["127.0.0.1", "10.0.0.1", "::1", "2001:db8::1"] {
205 assert!(!public_ip(ip.parse().unwrap()));
206 }
207 }
208}