net.rs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  1. //! A console without a network cable: the title reaches loopback only.
  2. //!
  3. //! Every way out of Winsock and WinHTTP a title can import or look up by
  4. //! name is vetted here; the rest of both DLLs is the host's own.
  5. //!
  6. //! * Connects (also by name, by list, `ConnectEx` from `WSAIoctl`) and
  7. //! datagram sends to anything but 127.0.0.0/8 and ::1 fail with
  8. //! `WSAENETUNREACH`.
  9. //! * Forward lookups other than `localhost` and IP literals fail with
  10. //! `WSAHOST_NOT_FOUND`; reverse lookups of other addresses come back
  11. //! numeric, or fail if a name is required, as with no network.
  12. //! * `WinHttpConnect` to a host that is not loopback fails with
  13. //! `ERROR_WINHTTP_CANNOT_CONNECT`, so no request (or WebSocket) handle can
  14. //! exist for one. Proxies are off and proxy auto-detection (WPAD, PAC
  15. //! downloads) fails with `ERROR_WINHTTP_AUTODETECTION_FAILED`.
  16. //! * A bind to all interfaces is narrowed to loopback, so nothing on the
  17. //! network can connect in.
  18. #![allow(non_snake_case)]
  19. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  20. #![allow(clippy::too_many_arguments)]
  21. use std::ffi::{CStr, c_char, c_void};
  22. use std::net::{IpAddr, SocketAddr};
  23. use std::sync::Mutex;
  24. use windows_sys::Win32::Foundation::SetLastError;
  25. use crate::modules::files::host;
  26. use crate::{HleExport, HleModule, hle_export};
  27. const SOCKET_ERROR: i32 = -1;
  28. const INVALID_SOCKET: Socket = !0;
  29. const WSAEINVAL: i32 = 10022;
  30. const WSAEADDRNOTAVAIL: i32 = 10049;
  31. const WSAENETUNREACH: i32 = 10051;
  32. const WSASERVICE_NOT_FOUND: i32 = 10108;
  33. const WSAHOST_NOT_FOUND: i32 = 11001;
  34. const ERROR_WINHTTP_CANNOT_CONNECT: u32 = 12029;
  35. const ERROR_WINHTTP_AUTODETECTION_FAILED: u32 = 12180;
  36. const AF_INET: u16 = 2;
  37. const AF_INET6: u16 = 23;
  38. const NI_NUMERICHOST: i32 = 0x02;
  39. const NI_NAMEREQD: i32 = 0x04;
  40. const SIO_GET_EXTENSION_FUNCTION_POINTER: u32 = 0xC800_0006;
  41. const SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER: u32 = 0xC800_0024;
  42. const WINHTTP_ACCESS_TYPE_NO_PROXY: u32 = 1;
  43. const WINHTTP_OPTION_PROXY: u32 = 38;
  44. #[repr(C)]
  45. #[derive(Clone, Copy, PartialEq, Eq)]
  46. struct Guid(u32, u16, u16, [u8; 8]);
  47. const WSAID_CONNECTEX: Guid = Guid(
  48. 0x25a2_07b9,
  49. 0xddf3,
  50. 0x4660,
  51. [0x8e, 0xe9, 0x76, 0xe5, 0x8c, 0x74, 0x06, 0x3e],
  52. );
  53. const WSAID_WSASENDMSG: Guid = Guid(
  54. 0xa441_e712,
  55. 0x754f,
  56. 0x43ca,
  57. [0x84, 0xa7, 0x0d, 0xee, 0x44, 0xcf, 0x60, 0x6d],
  58. );
  59. type Socket = usize;
  60. type Handle = *mut c_void;
  61. /// Logs `what` for `destination` the first time (no payload, ever).
  62. fn once(what: &'static str, destination: String) {
  63. static SEEN: Mutex<Vec<(&str, String)>> = Mutex::new(Vec::new());
  64. let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
  65. if !seen.iter().any(|(w, d)| *w == what && *d == destination) {
  66. tracing::info!(%destination, "{what}");
  67. seen.push((what, destination));
  68. }
  69. }
  70. fn wsa_error(code: i32) {
  71. host!("ws2_32.dll", "WSASetLastError": extern "system" fn(i32))(code);
  72. }
  73. fn narrow(text: *const c_char) -> Option<String> {
  74. (!text.is_null()).then(|| {
  75. // SAFETY: the title passes a NUL-terminated string.
  76. unsafe { CStr::from_ptr(text) }
  77. .to_string_lossy()
  78. .into_owned()
  79. })
  80. }
  81. fn wide(text: *const u16) -> Option<String> {
  82. // SAFETY: the title passes a NUL-terminated string or null.
  83. (!text.is_null()).then(|| unsafe {
  84. let len = (0..).take_while(|&i| *text.add(i) != 0).count();
  85. String::from_utf16_lossy(std::slice::from_raw_parts(text, len))
  86. })
  87. }
  88. /// An IPv4 or IPv6 `sockaddr` of `len` bytes.
  89. fn socket_addr(addr: *const u8, len: i32) -> Option<SocketAddr> {
  90. let len = usize::try_from(len).ok()?;
  91. if addr.is_null() || len < 4 {
  92. return None;
  93. }
  94. // SAFETY: the title passes `len` readable bytes.
  95. let b = unsafe { std::slice::from_raw_parts(addr, len) };
  96. let port = u16::from_be_bytes([b[2], b[3]]);
  97. match u16::from_le_bytes([b[0], b[1]]) {
  98. AF_INET if len >= 16 => Some((<[u8; 4]>::try_from(&b[4..8]).ok()?, port).into()),
  99. AF_INET6 if len >= 28 => Some((<[u8; 16]>::try_from(&b[8..24]).ok()?, port).into()),
  100. _ => None,
  101. }
  102. }
  103. /// A raw address of family `kind` (`gethostbyaddr` style).
  104. fn raw_ip(addr: *const c_char, len: i32, kind: i32) -> Option<IpAddr> {
  105. let len = usize::try_from(len).ok()?;
  106. if addr.is_null() {
  107. return None;
  108. }
  109. // SAFETY: the title passes `len` readable bytes.
  110. let b = unsafe { std::slice::from_raw_parts(addr.cast::<u8>(), len) };
  111. match (u16::try_from(kind).ok()?, len) {
  112. (AF_INET, 4..) => Some(<[u8; 4]>::try_from(&b[..4]).ok()?.into()),
  113. (AF_INET6, 16..) => Some(<[u8; 16]>::try_from(&b[..16]).ok()?.into()),
  114. _ => None,
  115. }
  116. }
  117. fn loopback(ip: IpAddr) -> bool {
  118. ip.to_canonical().is_loopback()
  119. }
  120. /// `localhost` or a loopback literal (bracketed IPv6 too).
  121. fn loopback_name(name: &str) -> bool {
  122. let bare = name.trim_start_matches('[').trim_end_matches(']');
  123. bare.eq_ignore_ascii_case("localhost") || bare.parse().is_ok_and(loopback)
  124. }
  125. fn shown(addr: Option<impl ToString>) -> String {
  126. addr.map_or_else(|| "not an IP address".into(), |a| a.to_string())
  127. }
  128. /// True for a loopback `sockaddr`; otherwise logs it and sets
  129. /// `WSAENETUNREACH`. Other address families count as off the machine.
  130. fn reachable(what: &'static str, addr: *const u8, len: i32) -> bool {
  131. match socket_addr(addr, len) {
  132. Some(a) if loopback(a.ip()) => true,
  133. a => {
  134. once(what, shown(a));
  135. wsa_error(WSAENETUNREACH);
  136. false
  137. }
  138. }
  139. }
  140. /// Connecting by name: only to loopback. A name would need a lookup
  141. /// (`WSAHOST_NOT_FOUND`), an address a route (`WSAENETUNREACH`).
  142. fn reachable_name(name: Option<String>) -> bool {
  143. match name {
  144. Some(name) if !loopback_name(&name) => {
  145. let literal = name.parse::<IpAddr>().is_ok();
  146. once("network connect blocked", name);
  147. wsa_error(if literal {
  148. WSAENETUNREACH
  149. } else {
  150. WSAHOST_NOT_FOUND
  151. });
  152. false
  153. }
  154. // No name: the host rejects the call itself.
  155. _ => true,
  156. }
  157. }
  158. /// Names answered without asking the network: none, `localhost`, IP
  159. /// literals (connecting to one is vetted separately).
  160. fn resolvable(name: Option<String>) -> bool {
  161. match name {
  162. Some(name)
  163. if !(name.is_empty()
  164. || name.eq_ignore_ascii_case("localhost")
  165. || name.parse::<IpAddr>().is_ok()) =>
  166. {
  167. once("network name lookup blocked", name);
  168. wsa_error(WSAHOST_NOT_FOUND);
  169. false
  170. }
  171. _ => true,
  172. }
  173. }
  174. /// Reverse lookups ask DNS unless the address is loopback.
  175. fn reverse_resolvable(ip: Option<IpAddr>) -> bool {
  176. match ip {
  177. Some(ip) if loopback(ip) => true,
  178. ip => {
  179. once("network reverse lookup blocked", shown(ip));
  180. false
  181. }
  182. }
  183. }
  184. /// `getnameinfo` flags that keep a host name lookup on the machine: the
  185. /// numeric form, as without a network, or `None` if a name is required.
  186. fn name_info_flags(sa: *const u8, len: i32, host_wanted: bool, flags: i32) -> Option<i32> {
  187. if !host_wanted
  188. || flags & NI_NUMERICHOST != 0
  189. || reverse_resolvable(socket_addr(sa, len).map(|a| a.ip()))
  190. {
  191. Some(flags)
  192. } else if flags & NI_NAMEREQD != 0 {
  193. wsa_error(WSAHOST_NOT_FOUND);
  194. None
  195. } else {
  196. Some(flags | NI_NUMERICHOST)
  197. }
  198. }
  199. // Connects.
  200. pub extern "system" fn connect(s: Socket, name: *const u8, len: i32) -> i32 {
  201. if !reachable("network connect blocked", name, len) {
  202. return SOCKET_ERROR;
  203. }
  204. host!("ws2_32.dll", "connect": extern "system" fn(Socket, *const u8, i32) -> i32)(s, name, len)
  205. }
  206. pub extern "system" fn WSAConnect(
  207. s: Socket,
  208. name: *const u8,
  209. len: i32,
  210. caller_data: *const c_void,
  211. callee_data: *mut c_void,
  212. sqos: *const c_void,
  213. gqos: *const c_void,
  214. ) -> i32 {
  215. if !reachable("network connect blocked", name, len) {
  216. return SOCKET_ERROR;
  217. }
  218. host!("ws2_32.dll", "WSAConnect": extern "system" fn(Socket, *const u8, i32, *const c_void, *mut c_void, *const c_void, *const c_void) -> i32)(
  219. s,
  220. name,
  221. len,
  222. caller_data,
  223. callee_data,
  224. sqos,
  225. gqos,
  226. )
  227. }
  228. pub extern "system" fn WSAConnectByNameA(
  229. s: Socket,
  230. node: *const c_char,
  231. service: *const c_char,
  232. local_len: *mut u32,
  233. local: *mut c_void,
  234. remote_len: *mut u32,
  235. remote: *mut c_void,
  236. timeout: *const c_void,
  237. reserved: *mut c_void,
  238. ) -> i32 {
  239. if !reachable_name(narrow(node)) {
  240. return 0;
  241. }
  242. host!("ws2_32.dll", "WSAConnectByNameA": extern "system" fn(Socket, *const c_char, *const c_char, *mut u32, *mut c_void, *mut u32, *mut c_void, *const c_void, *mut c_void) -> i32)(
  243. s, node, service, local_len, local, remote_len, remote, timeout, reserved,
  244. )
  245. }
  246. pub extern "system" fn WSAConnectByNameW(
  247. s: Socket,
  248. node: *const u16,
  249. service: *const u16,
  250. local_len: *mut u32,
  251. local: *mut c_void,
  252. remote_len: *mut u32,
  253. remote: *mut c_void,
  254. timeout: *const c_void,
  255. reserved: *mut c_void,
  256. ) -> i32 {
  257. if !reachable_name(wide(node)) {
  258. return 0;
  259. }
  260. host!("ws2_32.dll", "WSAConnectByNameW": extern "system" fn(Socket, *const u16, *const u16, *mut u32, *mut c_void, *mut u32, *mut c_void, *const c_void, *mut c_void) -> i32)(
  261. s, node, service, local_len, local, remote_len, remote, timeout, reserved,
  262. )
  263. }
  264. /// `SOCKET_ADDRESS`; a `SOCKET_ADDRESS_LIST` is an `i32` count, then these
  265. /// (pointer aligned).
  266. #[repr(C)]
  267. struct SocketAddress {
  268. addr: *const u8,
  269. len: i32,
  270. }
  271. /// Every candidate must be loopback.
  272. pub extern "system" fn WSAConnectByList(
  273. s: Socket,
  274. list: *const u8,
  275. local_len: *mut u32,
  276. local: *mut c_void,
  277. remote_len: *mut u32,
  278. remote: *mut c_void,
  279. timeout: *const c_void,
  280. reserved: *mut c_void,
  281. ) -> i32 {
  282. if !list.is_null() {
  283. // SAFETY: the title passes a `SOCKET_ADDRESS_LIST`.
  284. let entries = unsafe {
  285. let count = usize::try_from(list.cast::<i32>().read()).unwrap_or(0);
  286. std::slice::from_raw_parts(list.add(8).cast::<SocketAddress>(), count)
  287. };
  288. if !entries
  289. .iter()
  290. .all(|e| reachable("network connect blocked", e.addr, e.len))
  291. {
  292. return 0;
  293. }
  294. }
  295. host!("ws2_32.dll", "WSAConnectByList": extern "system" fn(Socket, *const u8, *mut u32, *mut c_void, *mut u32, *mut c_void, *const c_void, *mut c_void) -> i32)(
  296. s, list, local_len, local, remote_len, remote, timeout, reserved,
  297. )
  298. }
  299. pub extern "system" fn WSAJoinLeaf(
  300. s: Socket,
  301. name: *const u8,
  302. len: i32,
  303. caller_data: *const c_void,
  304. callee_data: *mut c_void,
  305. sqos: *const c_void,
  306. gqos: *const c_void,
  307. flags: u32,
  308. ) -> Socket {
  309. if !reachable("network connect blocked", name, len) {
  310. return INVALID_SOCKET;
  311. }
  312. host!("ws2_32.dll", "WSAJoinLeaf": extern "system" fn(Socket, *const u8, i32, *const c_void, *mut c_void, *const c_void, *const c_void, u32) -> Socket)(
  313. s,
  314. name,
  315. len,
  316. caller_data,
  317. callee_data,
  318. sqos,
  319. gqos,
  320. flags,
  321. )
  322. }
  323. /// `ConnectEx` as `WSAIoctl` hands it out: vetted, then the socket's own.
  324. extern "system" fn connect_ex(
  325. s: Socket,
  326. name: *const u8,
  327. len: i32,
  328. send: *const c_void,
  329. send_len: u32,
  330. sent: *mut u32,
  331. overlapped: *mut c_void,
  332. ) -> i32 {
  333. if !reachable("network connect blocked", name, len) {
  334. return 0;
  335. }
  336. let (mut real, mut size) = (0usize, 0u32);
  337. let ioctl = host!("ws2_32.dll", "WSAIoctl": extern "system" fn(Socket, u32, *const c_void, u32, *mut c_void, u32, *mut u32, *mut c_void, *const c_void) -> i32);
  338. let guid = WSAID_CONNECTEX;
  339. let found = ioctl(
  340. s,
  341. SIO_GET_EXTENSION_FUNCTION_POINTER,
  342. (&raw const guid).cast(),
  343. 16,
  344. (&raw mut real).cast(),
  345. 8,
  346. &mut size,
  347. std::ptr::null_mut(),
  348. std::ptr::null(),
  349. );
  350. if found != 0 || real == 0 {
  351. return 0;
  352. }
  353. // SAFETY: the provider's `ConnectEx` for this socket.
  354. let real = unsafe {
  355. std::mem::transmute::<
  356. usize,
  357. extern "system" fn(
  358. Socket,
  359. *const u8,
  360. i32,
  361. *const c_void,
  362. u32,
  363. *mut u32,
  364. *mut c_void,
  365. ) -> i32,
  366. >(real)
  367. };
  368. real(s, name, len, send, send_len, sent, overlapped)
  369. }
  370. /// The `ConnectEx` and `WSASendMsg` pointers it hands out are ours; the
  371. /// multi-pointer query (Registered I/O, whose `RIOSendEx` takes any
  372. /// address) is refused as by an old system. Other controls pass through.
  373. pub extern "system" fn WSAIoctl(
  374. s: Socket,
  375. code: u32,
  376. input: *const c_void,
  377. input_len: u32,
  378. output: *mut c_void,
  379. output_len: u32,
  380. returned: *mut u32,
  381. overlapped: *mut c_void,
  382. completion: *const c_void,
  383. ) -> i32 {
  384. if code == SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER {
  385. wsa_error(WSAEINVAL);
  386. return SOCKET_ERROR;
  387. }
  388. let result = host!("ws2_32.dll", "WSAIoctl": extern "system" fn(Socket, u32, *const c_void, u32, *mut c_void, u32, *mut u32, *mut c_void, *const c_void) -> i32)(
  389. s, code, input, input_len, output, output_len, returned, overlapped, completion,
  390. );
  391. if result == 0 && code == SIO_GET_EXTENSION_FUNCTION_POINTER && input_len >= 16 {
  392. // SAFETY: the host just read a GUID from `input` and wrote a pointer to `output`.
  393. unsafe {
  394. let ours = match input.cast::<Guid>().read_unaligned() {
  395. WSAID_CONNECTEX => connect_ex as *const () as usize,
  396. WSAID_WSASENDMSG => WSASendMsg as *const () as usize,
  397. _ => return result,
  398. };
  399. output.cast::<usize>().write_unaligned(ours);
  400. }
  401. }
  402. result
  403. }
  404. // Datagram sends.
  405. /// Without an address it sends to the connected peer, which `connect` vetted;
  406. /// so does a stream socket whatever `to` says (Winsock ignores it there).
  407. pub extern "system" fn sendto(
  408. s: Socket,
  409. buf: *const u8,
  410. len: i32,
  411. flags: i32,
  412. to: *const u8,
  413. to_len: i32,
  414. ) -> i32 {
  415. if !to.is_null() && !stream(s) && !reachable("network datagram blocked", to, to_len) {
  416. return SOCKET_ERROR;
  417. }
  418. host!("ws2_32.dll", "sendto": extern "system" fn(Socket, *const u8, i32, i32, *const u8, i32) -> i32)(
  419. s, buf, len, flags, to, to_len,
  420. )
  421. }
  422. pub extern "system" fn WSASendTo(
  423. s: Socket,
  424. buffers: *const c_void,
  425. count: u32,
  426. sent: *mut u32,
  427. flags: u32,
  428. to: *const u8,
  429. to_len: i32,
  430. overlapped: *mut c_void,
  431. completion: *const c_void,
  432. ) -> i32 {
  433. if !to.is_null() && !stream(s) && !reachable("network datagram blocked", to, to_len) {
  434. return SOCKET_ERROR;
  435. }
  436. host!("ws2_32.dll", "WSASendTo": extern "system" fn(Socket, *const c_void, u32, *mut u32, u32, *const u8, i32, *mut c_void, *const c_void) -> i32)(
  437. s, buffers, count, sent, flags, to, to_len, overlapped, completion,
  438. )
  439. }
  440. /// A connection-oriented socket, whose sends go to the peer `connect` vetted.
  441. fn stream(s: Socket) -> bool {
  442. const SOL_SOCKET: i32 = 0xffff;
  443. const SO_TYPE: i32 = 0x1008;
  444. const SOCK_STREAM: i32 = 1;
  445. let (mut kind, mut len) = (0i32, 4i32);
  446. let getsockopt = host!("ws2_32.dll", "getsockopt": extern "system" fn(Socket, i32, i32, *mut i32, *mut i32) -> i32);
  447. getsockopt(s, SOL_SOCKET, SO_TYPE, &mut kind, &mut len) == 0 && kind == SOCK_STREAM
  448. }
  449. /// The start of a `WSAMSG`: the destination.
  450. #[repr(C)]
  451. struct MessageName {
  452. name: *const u8,
  453. len: i32,
  454. }
  455. pub extern "system" fn WSASendMsg(
  456. s: Socket,
  457. message: *const c_void,
  458. flags: u32,
  459. sent: *mut u32,
  460. overlapped: *mut c_void,
  461. completion: *const c_void,
  462. ) -> i32 {
  463. // SAFETY: the title passes a `WSAMSG` or null.
  464. if let Some(m) = unsafe { message.cast::<MessageName>().as_ref() }
  465. && !m.name.is_null()
  466. && !reachable("network datagram blocked", m.name, m.len)
  467. {
  468. return SOCKET_ERROR;
  469. }
  470. host!("ws2_32.dll", "WSASendMsg": extern "system" fn(Socket, *const c_void, u32, *mut u32, *mut c_void, *const c_void) -> i32)(
  471. s, message, flags, sent, overlapped, completion,
  472. )
  473. }
  474. /// All interfaces become loopback, the only one an unplugged console has;
  475. /// any other address is not ours (`WSAEADDRNOTAVAIL`).
  476. // shortcut: `[::]` becomes `[::1]`, so a dual-stack listener no longer hears
  477. // 127.0.0.1; bind both families if a title relies on that.
  478. pub extern "system" fn bind(s: Socket, name: *const u8, len: i32) -> i32 {
  479. let host_bind = host!("ws2_32.dll", "bind": extern "system" fn(Socket, *const u8, i32) -> i32);
  480. match socket_addr(name, len) {
  481. Some(a) if loopback(a.ip()) => host_bind(s, name, len),
  482. Some(a) if a.ip().is_unspecified() => {
  483. once("network bind narrowed to loopback", a.to_string());
  484. // SAFETY: `socket_addr` checked `len` readable bytes.
  485. let mut local = unsafe { std::slice::from_raw_parts(name, len as usize) }.to_vec();
  486. match a {
  487. SocketAddr::V4(_) => local[4..8].copy_from_slice(&[127, 0, 0, 1]),
  488. SocketAddr::V6(_) => local[23] = 1,
  489. }
  490. host_bind(s, local.as_ptr(), len)
  491. }
  492. a => {
  493. once("network bind blocked", shown(a));
  494. wsa_error(WSAEADDRNOTAVAIL);
  495. SOCKET_ERROR
  496. }
  497. }
  498. }
  499. // Forward lookups.
  500. fn blocked_lookup(result: *mut *mut c_void) -> i32 {
  501. if !result.is_null() {
  502. // SAFETY: a non-null result points to the caller's output slot.
  503. unsafe { result.write(std::ptr::null_mut()) };
  504. }
  505. WSAHOST_NOT_FOUND
  506. }
  507. pub extern "system" fn getaddrinfo(
  508. node: *const c_char,
  509. service: *const c_char,
  510. hints: *const c_void,
  511. result: *mut *mut c_void,
  512. ) -> i32 {
  513. if !resolvable(narrow(node)) {
  514. return blocked_lookup(result);
  515. }
  516. host!("ws2_32.dll", "getaddrinfo": extern "system" fn(*const c_char, *const c_char, *const c_void, *mut *mut c_void) -> i32)(
  517. node, service, hints, result,
  518. )
  519. }
  520. pub extern "system" fn GetAddrInfoW(
  521. node: *const u16,
  522. service: *const u16,
  523. hints: *const c_void,
  524. result: *mut *mut c_void,
  525. ) -> i32 {
  526. if !resolvable(wide(node)) {
  527. return blocked_lookup(result);
  528. }
  529. host!("ws2_32.dll", "GetAddrInfoW": extern "system" fn(*const u16, *const u16, *const c_void, *mut *mut c_void) -> i32)(
  530. node, service, hints, result,
  531. )
  532. }
  533. pub extern "system" fn GetAddrInfoExA(
  534. name: *const c_char,
  535. service: *const c_char,
  536. namespace: u32,
  537. provider: *const c_void,
  538. hints: *const c_void,
  539. result: *mut *mut c_void,
  540. timeout: *const c_void,
  541. overlapped: *mut c_void,
  542. completion: *const c_void,
  543. handle: *mut Handle,
  544. ) -> i32 {
  545. if !resolvable(narrow(name)) {
  546. return blocked_lookup(result);
  547. }
  548. host!("ws2_32.dll", "GetAddrInfoExA": extern "system" fn(*const c_char, *const c_char, u32, *const c_void, *const c_void, *mut *mut c_void, *const c_void, *mut c_void, *const c_void, *mut Handle) -> i32)(
  549. name, service, namespace, provider, hints, result, timeout, overlapped, completion, handle,
  550. )
  551. }
  552. pub extern "system" fn GetAddrInfoExW(
  553. name: *const u16,
  554. service: *const u16,
  555. namespace: u32,
  556. provider: *const c_void,
  557. hints: *const c_void,
  558. result: *mut *mut c_void,
  559. timeout: *const c_void,
  560. overlapped: *mut c_void,
  561. completion: *const c_void,
  562. handle: *mut Handle,
  563. ) -> i32 {
  564. if !resolvable(wide(name)) {
  565. return blocked_lookup(result);
  566. }
  567. host!("ws2_32.dll", "GetAddrInfoExW": extern "system" fn(*const u16, *const u16, u32, *const c_void, *const c_void, *mut *mut c_void, *const c_void, *mut c_void, *const c_void, *mut Handle) -> i32)(
  568. name, service, namespace, provider, hints, result, timeout, overlapped, completion, handle,
  569. )
  570. }
  571. pub extern "system" fn gethostbyname(name: *const c_char) -> *mut c_void {
  572. if !resolvable(narrow(name)) {
  573. return std::ptr::null_mut();
  574. }
  575. host!("ws2_32.dll", "gethostbyname": extern "system" fn(*const c_char) -> *mut c_void)(name)
  576. }
  577. pub extern "system" fn WSAAsyncGetHostByName(
  578. window: Handle,
  579. message: u32,
  580. name: *const c_char,
  581. buf: *mut c_char,
  582. buf_len: i32,
  583. ) -> Handle {
  584. if !resolvable(narrow(name)) {
  585. return std::ptr::null_mut();
  586. }
  587. host!("ws2_32.dll", "WSAAsyncGetHostByName": extern "system" fn(Handle, u32, *const c_char, *mut c_char, i32) -> Handle)(
  588. window, message, name, buf, buf_len,
  589. )
  590. }
  591. /// Name-space queries (DNS, also network lists and Bluetooth) are refused
  592. /// as a console without a network answers them.
  593. // shortcut: local name spaces are refused too; pass those through if a title
  594. // needs one.
  595. pub extern "system" fn WSALookupServiceBeginA(
  596. _restrictions: *const c_void,
  597. _flags: u32,
  598. _lookup: *mut Handle,
  599. ) -> i32 {
  600. once("network name-space query blocked", "any".into());
  601. wsa_error(WSASERVICE_NOT_FOUND);
  602. SOCKET_ERROR
  603. }
  604. /// See [`WSALookupServiceBeginA`].
  605. pub extern "system" fn WSALookupServiceBeginW(
  606. restrictions: *const c_void,
  607. flags: u32,
  608. lookup: *mut Handle,
  609. ) -> i32 {
  610. WSALookupServiceBeginA(restrictions, flags, lookup)
  611. }
  612. // Reverse lookups.
  613. pub extern "system" fn gethostbyaddr(addr: *const c_char, len: i32, kind: i32) -> *mut c_void {
  614. if !reverse_resolvable(raw_ip(addr, len, kind)) {
  615. wsa_error(WSAHOST_NOT_FOUND);
  616. return std::ptr::null_mut();
  617. }
  618. host!("ws2_32.dll", "gethostbyaddr": extern "system" fn(*const c_char, i32, i32) -> *mut c_void)(
  619. addr, len, kind,
  620. )
  621. }
  622. pub extern "system" fn WSAAsyncGetHostByAddr(
  623. window: Handle,
  624. message: u32,
  625. addr: *const c_char,
  626. len: i32,
  627. kind: i32,
  628. buf: *mut c_char,
  629. buf_len: i32,
  630. ) -> Handle {
  631. if !reverse_resolvable(raw_ip(addr, len, kind)) {
  632. wsa_error(WSAHOST_NOT_FOUND);
  633. return std::ptr::null_mut();
  634. }
  635. host!("ws2_32.dll", "WSAAsyncGetHostByAddr": extern "system" fn(Handle, u32, *const c_char, i32, i32, *mut c_char, i32) -> Handle)(
  636. window, message, addr, len, kind, buf, buf_len,
  637. )
  638. }
  639. pub extern "system" fn getnameinfo(
  640. sa: *const u8,
  641. sa_len: i32,
  642. host: *mut c_char,
  643. host_len: u32,
  644. serv: *mut c_char,
  645. serv_len: u32,
  646. flags: i32,
  647. ) -> i32 {
  648. let Some(flags) = name_info_flags(sa, sa_len, !host.is_null(), flags) else {
  649. return WSAHOST_NOT_FOUND;
  650. };
  651. host!("ws2_32.dll", "getnameinfo": extern "system" fn(*const u8, i32, *mut c_char, u32, *mut c_char, u32, i32) -> i32)(
  652. sa, sa_len, host, host_len, serv, serv_len, flags,
  653. )
  654. }
  655. pub extern "system" fn GetNameInfoW(
  656. sa: *const u8,
  657. sa_len: i32,
  658. host: *mut u16,
  659. host_len: u32,
  660. serv: *mut u16,
  661. serv_len: u32,
  662. flags: i32,
  663. ) -> i32 {
  664. let Some(flags) = name_info_flags(sa, sa_len, !host.is_null(), flags) else {
  665. return WSAHOST_NOT_FOUND;
  666. };
  667. host!("ws2_32.dll", "GetNameInfoW": extern "system" fn(*const u8, i32, *mut u16, u32, *mut u16, u32, i32) -> i32)(
  668. sa, sa_len, host, host_len, serv, serv_len, flags,
  669. )
  670. }
  671. // WinHTTP.
  672. /// The one door to a server: requests, uploads and WebSockets all hang off
  673. /// the handle this returns.
  674. pub extern "system" fn WinHttpConnect(
  675. session: Handle,
  676. server: *const u16,
  677. port: u16,
  678. reserved: u32,
  679. ) -> Handle {
  680. if let Some(name) = wide(server)
  681. && !loopback_name(&name)
  682. {
  683. once("HTTP connection blocked", format!("{name}:{port}"));
  684. // SAFETY: no pointers.
  685. unsafe { SetLastError(ERROR_WINHTTP_CANNOT_CONNECT) };
  686. return std::ptr::null_mut();
  687. }
  688. host!("winhttp.dll", "WinHttpConnect": extern "system" fn(Handle, *const u16, u16, u32) -> Handle)(
  689. session, server, port, reserved,
  690. )
  691. }
  692. /// Sessions never use a proxy: only loopback is reachable, and a proxy
  693. /// (named, or found by auto-detection) would carry it off the machine.
  694. pub extern "system" fn WinHttpOpen(
  695. agent: *const u16,
  696. access: u32,
  697. _proxy: *const u16,
  698. _bypass: *const u16,
  699. flags: u32,
  700. ) -> Handle {
  701. if access != WINHTTP_ACCESS_TYPE_NO_PROXY {
  702. once("HTTP proxy ignored", format!("access type {access}"));
  703. }
  704. host!("winhttp.dll", "WinHttpOpen": extern "system" fn(*const u16, u32, *const u16, *const u16, u32) -> Handle)(
  705. agent,
  706. WINHTTP_ACCESS_TYPE_NO_PROXY,
  707. std::ptr::null(),
  708. std::ptr::null(),
  709. flags,
  710. )
  711. }
  712. /// See [`WinHttpOpen`]: a proxy set later is accepted and not used.
  713. pub extern "system" fn WinHttpSetOption(
  714. handle: Handle,
  715. option: u32,
  716. buffer: *const c_void,
  717. len: u32,
  718. ) -> i32 {
  719. if option == WINHTTP_OPTION_PROXY {
  720. once("HTTP proxy ignored", "WINHTTP_OPTION_PROXY".into());
  721. return 1;
  722. }
  723. host!("winhttp.dll", "WinHttpSetOption": extern "system" fn(Handle, u32, *const c_void, u32) -> i32)(
  724. handle, option, buffer, len,
  725. )
  726. }
  727. /// Proxy auto-detection asks the network (DHCP, DNS, a PAC download).
  728. fn no_auto_proxy() -> u32 {
  729. once("HTTP proxy auto-detection blocked", "WPAD/PAC".into());
  730. ERROR_WINHTTP_AUTODETECTION_FAILED
  731. }
  732. pub extern "system" fn WinHttpDetectAutoProxyConfigUrl(_flags: u32, _url: *mut *mut u16) -> i32 {
  733. // SAFETY: no pointers.
  734. unsafe { SetLastError(no_auto_proxy()) };
  735. 0
  736. }
  737. pub extern "system" fn WinHttpGetProxyForUrl(
  738. _session: Handle,
  739. _url: *const u16,
  740. _options: *const c_void,
  741. _info: *mut c_void,
  742. ) -> i32 {
  743. // SAFETY: no pointers.
  744. unsafe { SetLastError(no_auto_proxy()) };
  745. 0
  746. }
  747. pub extern "system" fn WinHttpGetProxyForUrlEx(
  748. _resolver: Handle,
  749. _url: *const u16,
  750. _options: *const c_void,
  751. _context: usize,
  752. ) -> u32 {
  753. no_auto_proxy()
  754. }
  755. pub extern "system" fn WinHttpGetProxyForUrlEx2(
  756. _resolver: Handle,
  757. _url: *const u16,
  758. _options: *const c_void,
  759. _selection_len: u32,
  760. _selection: *const u8,
  761. _context: usize,
  762. ) -> u32 {
  763. no_auto_proxy()
  764. }
  765. pub extern "system" fn WinHttpGetProxySettingsEx(
  766. _resolver: Handle,
  767. _kind: i32,
  768. _params: *const c_void,
  769. _context: usize,
  770. ) -> u32 {
  771. no_auto_proxy()
  772. }
  773. /// Winsock imports by ordinal; the Winsock 1.1 numbers are fixed.
  774. fn ordinal(name: &'static str, f: usize) -> HleExport {
  775. HleExport { name, address: f }
  776. }
  777. pub(crate) fn module() -> HleModule {
  778. HleModule {
  779. name: "net",
  780. dlls: &["ws2_32.dll", "winhttp.dll"],
  781. exports: vec![
  782. hle_export!(connect),
  783. hle_export!(WSAConnect),
  784. hle_export!(WSAConnectByNameA),
  785. hle_export!(WSAConnectByNameW),
  786. hle_export!(WSAConnectByList),
  787. hle_export!(WSAJoinLeaf),
  788. hle_export!(WSAIoctl),
  789. hle_export!(sendto),
  790. hle_export!(WSASendTo),
  791. hle_export!(WSASendMsg),
  792. hle_export!(bind),
  793. hle_export!(getaddrinfo),
  794. hle_export!(GetAddrInfoW),
  795. hle_export!(GetAddrInfoExA),
  796. hle_export!(GetAddrInfoExW),
  797. hle_export!(gethostbyname),
  798. hle_export!(WSAAsyncGetHostByName),
  799. hle_export!(WSALookupServiceBeginA),
  800. hle_export!(WSALookupServiceBeginW),
  801. hle_export!(gethostbyaddr),
  802. hle_export!(WSAAsyncGetHostByAddr),
  803. hle_export!(getnameinfo),
  804. hle_export!(GetNameInfoW),
  805. hle_export!(WinHttpConnect),
  806. hle_export!(WinHttpOpen),
  807. hle_export!(WinHttpSetOption),
  808. hle_export!(WinHttpDetectAutoProxyConfigUrl),
  809. hle_export!(WinHttpGetProxyForUrl),
  810. hle_export!(WinHttpGetProxyForUrlEx),
  811. hle_export!(WinHttpGetProxyForUrlEx2),
  812. hle_export!(WinHttpGetProxySettingsEx),
  813. ordinal("#2", bind as *const () as usize),
  814. ordinal("#4", connect as *const () as usize),
  815. ordinal("#20", sendto as *const () as usize),
  816. ordinal("#51", gethostbyaddr as *const () as usize),
  817. ordinal("#52", gethostbyname as *const () as usize),
  818. ordinal("#102", WSAAsyncGetHostByAddr as *const () as usize),
  819. ordinal("#103", WSAAsyncGetHostByName as *const () as usize),
  820. ],
  821. }
  822. }
  823. #[cfg(test)]
  824. mod tests {
  825. use super::*;
  826. use victory_pe::ImportSymbol;
  827. fn v4(ip: [u8; 4], port: u16) -> [u8; 16] {
  828. let mut a = [0u8; 16];
  829. a[..2].copy_from_slice(&AF_INET.to_le_bytes());
  830. a[2..4].copy_from_slice(&port.to_be_bytes());
  831. a[4..8].copy_from_slice(&ip);
  832. a
  833. }
  834. // TEST-NET-1 (192.0.2.0/24): never routed, and never tried here.
  835. const AWAY: [u8; 4] = [192, 0, 2, 1];
  836. const HOME: [u8; 4] = [127, 0, 0, 1];
  837. #[test]
  838. fn blocked_name_lookups_clear_the_result() {
  839. let ansi = c"blocked.invalid".as_ptr();
  840. let wide: Vec<u16> = "blocked.invalid\0".encode_utf16().collect();
  841. let wide = wide.as_ptr();
  842. let null = std::ptr::null();
  843. let null_mut = std::ptr::null_mut();
  844. let check = |lookup: &dyn Fn(*mut *mut c_void) -> i32| {
  845. let mut result = std::ptr::dangling_mut::<c_void>();
  846. assert_eq!(lookup(&mut result), WSAHOST_NOT_FOUND);
  847. assert!(result.is_null());
  848. assert_eq!(lookup(std::ptr::null_mut()), WSAHOST_NOT_FOUND);
  849. };
  850. check(&|result| getaddrinfo(ansi, std::ptr::null(), null, result));
  851. check(&|result| GetAddrInfoW(wide, std::ptr::null(), null, result));
  852. check(&|result| {
  853. GetAddrInfoExA(
  854. ansi,
  855. std::ptr::null(),
  856. 0,
  857. null,
  858. null,
  859. result,
  860. null,
  861. null_mut,
  862. null,
  863. std::ptr::null_mut(),
  864. )
  865. });
  866. check(&|result| {
  867. GetAddrInfoExW(
  868. wide,
  869. std::ptr::null(),
  870. 0,
  871. null,
  872. null,
  873. result,
  874. null,
  875. null_mut,
  876. null,
  877. std::ptr::null_mut(),
  878. )
  879. });
  880. }
  881. #[test]
  882. fn only_loopback_is_reachable() {
  883. // Also starts Winsock for the raw calls below.
  884. let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
  885. let port = listener.local_addr().unwrap().port();
  886. let socket = host!("ws2_32.dll", "socket": extern "system" fn(i32, i32, i32) -> Socket);
  887. let close = host!("ws2_32.dll", "closesocket": extern "system" fn(Socket) -> i32);
  888. let last_error = host!("ws2_32.dll", "WSAGetLastError": extern "system" fn() -> i32);
  889. let null = std::ptr::null_mut::<c_void>();
  890. // Connects.
  891. let s = socket(2, 1, 6);
  892. assert_ne!(s, INVALID_SOCKET);
  893. assert_eq!(connect(s, v4(AWAY, 80).as_ptr(), 16), SOCKET_ERROR);
  894. assert_eq!(last_error(), WSAENETUNREACH);
  895. let n = null.cast();
  896. assert_eq!(
  897. WSAConnectByNameA(
  898. s,
  899. c"example.com".as_ptr(),
  900. c"80".as_ptr(),
  901. n,
  902. null,
  903. n,
  904. null,
  905. null,
  906. null
  907. ),
  908. 0
  909. );
  910. assert_eq!(last_error(), WSAHOST_NOT_FOUND);
  911. assert_eq!(connect(s, v4(HOME, port).as_ptr(), 16), 0);
  912. listener.accept().unwrap();
  913. // A stream socket sends to its vetted peer whatever `to` says.
  914. assert_eq!(sendto(s, b"x".as_ptr(), 1, 0, v4(AWAY, 9).as_ptr(), 16), 1);
  915. close(s);
  916. // `ConnectEx` from `WSAIoctl` is the vetted one.
  917. let s = socket(2, 1, 6);
  918. let mut f = 0usize;
  919. let mut size = 0u32;
  920. let guid = WSAID_CONNECTEX;
  921. let got = WSAIoctl(
  922. s,
  923. SIO_GET_EXTENSION_FUNCTION_POINTER,
  924. (&raw const guid).cast(),
  925. 16,
  926. (&raw mut f).cast(),
  927. 8,
  928. &mut size,
  929. null,
  930. null,
  931. );
  932. assert_eq!((got, f), (0, connect_ex as *const () as usize));
  933. assert_eq!(
  934. connect_ex(s, v4(AWAY, 80).as_ptr(), 16, null, 0, n, null),
  935. 0
  936. );
  937. assert_eq!(last_error(), WSAENETUNREACH);
  938. close(s);
  939. // Datagram sends.
  940. let u = socket(2, 2, 17);
  941. assert_eq!(
  942. sendto(u, b"x".as_ptr(), 1, 0, v4(AWAY, 9).as_ptr(), 16),
  943. SOCKET_ERROR
  944. );
  945. assert_eq!(last_error(), WSAENETUNREACH);
  946. assert_eq!(
  947. sendto(u, b"x".as_ptr(), 1, 0, v4(HOME, port).as_ptr(), 16),
  948. 1
  949. );
  950. close(u);
  951. // Forward and reverse lookups.
  952. let mut result = null;
  953. assert_eq!(
  954. getaddrinfo(
  955. c"example.com".as_ptr(),
  956. std::ptr::null(),
  957. std::ptr::null(),
  958. &mut result
  959. ),
  960. WSAHOST_NOT_FOUND
  961. );
  962. let name: Vec<u16> = "example.com\0".encode_utf16().collect();
  963. assert_eq!(
  964. GetAddrInfoW(
  965. name.as_ptr(),
  966. std::ptr::null(),
  967. std::ptr::null(),
  968. &mut result
  969. ),
  970. WSAHOST_NOT_FOUND
  971. );
  972. let mut text = [0 as c_char; 64];
  973. let away = v4(AWAY, 80);
  974. assert_eq!(
  975. getnameinfo(
  976. away.as_ptr(),
  977. 16,
  978. text.as_mut_ptr(),
  979. 64,
  980. std::ptr::null_mut(),
  981. 0,
  982. 0
  983. ),
  984. 0
  985. );
  986. // SAFETY: NUL-terminated by `getnameinfo`.
  987. let numeric = unsafe { CStr::from_ptr(text.as_ptr()) };
  988. assert_eq!(numeric.to_str(), Ok("192.0.2.1"));
  989. assert_eq!(
  990. getnameinfo(
  991. away.as_ptr(),
  992. 16,
  993. text.as_mut_ptr(),
  994. 64,
  995. std::ptr::null_mut(),
  996. 0,
  997. NI_NAMEREQD
  998. ),
  999. WSAHOST_NOT_FOUND
  1000. );
  1001. assert!(gethostbyaddr(AWAY.as_ptr().cast(), 4, 2).is_null());
  1002. // WinHTTP.
  1003. assert!(WinHttpConnect(null, name.as_ptr(), 443, 0).is_null());
  1004. // SAFETY: no arguments.
  1005. let error = unsafe { windows_sys::Win32::Foundation::GetLastError() };
  1006. assert_eq!(error, ERROR_WINHTTP_CANNOT_CONNECT);
  1007. assert_eq!(
  1008. WinHttpGetProxyForUrlEx(null, name.as_ptr(), std::ptr::null(), 0),
  1009. ERROR_WINHTTP_AUTODETECTION_FAILED
  1010. );
  1011. // The ordinals we override name the functions they stand for.
  1012. let m = module();
  1013. for e in m.exports.iter().filter(|e| e.name.starts_with('#')) {
  1014. let named = m
  1015. .exports
  1016. .iter()
  1017. .find(|n| n.address == e.address && !n.name.starts_with('#'))
  1018. .unwrap();
  1019. let by_ordinal = ImportSymbol::Ordinal(e.name[1..].parse().unwrap());
  1020. assert_eq!(
  1021. crate::HostPolicy::default().resolve("ws2_32.dll", &by_ordinal),
  1022. crate::host::function("ws2_32.dll", named.name),
  1023. "{} is not {}",
  1024. e.name,
  1025. named.name
  1026. );
  1027. }
  1028. // Every override names a real export of its DLL. Some exports only
  1029. // exist on newer Windows (WinHttpGetProxySettingsEx is absent from
  1030. // Windows 10's winhttp.dll); the HLE supplies those itself, so skip
  1031. // them only when the host really lacks them.
  1032. const NEWER_WINDOWS_ONLY: &[&str] = &["WinHttpGetProxySettingsEx"];
  1033. for e in m.exports.iter().filter(|e| !e.name.starts_with('#')) {
  1034. let dll = if e.name.starts_with("WinHttp") {
  1035. "winhttp.dll"
  1036. } else {
  1037. "ws2_32.dll"
  1038. };
  1039. let present = crate::host::function(dll, e.name).is_some();
  1040. if !present && NEWER_WINDOWS_ONLY.contains(&e.name) {
  1041. continue;
  1042. }
  1043. assert!(present, "{dll} lacks {}", e.name);
  1044. }
  1045. }
  1046. }