net.rs 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  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. pub extern "system" fn getaddrinfo(
  501. node: *const c_char,
  502. service: *const c_char,
  503. hints: *const c_void,
  504. result: *mut *mut c_void,
  505. ) -> i32 {
  506. if !resolvable(narrow(node)) {
  507. return WSAHOST_NOT_FOUND;
  508. }
  509. host!("ws2_32.dll", "getaddrinfo": extern "system" fn(*const c_char, *const c_char, *const c_void, *mut *mut c_void) -> i32)(
  510. node, service, hints, result,
  511. )
  512. }
  513. pub extern "system" fn GetAddrInfoW(
  514. node: *const u16,
  515. service: *const u16,
  516. hints: *const c_void,
  517. result: *mut *mut c_void,
  518. ) -> i32 {
  519. if !resolvable(wide(node)) {
  520. return WSAHOST_NOT_FOUND;
  521. }
  522. host!("ws2_32.dll", "GetAddrInfoW": extern "system" fn(*const u16, *const u16, *const c_void, *mut *mut c_void) -> i32)(
  523. node, service, hints, result,
  524. )
  525. }
  526. pub extern "system" fn GetAddrInfoExA(
  527. name: *const c_char,
  528. service: *const c_char,
  529. namespace: u32,
  530. provider: *const c_void,
  531. hints: *const c_void,
  532. result: *mut *mut c_void,
  533. timeout: *const c_void,
  534. overlapped: *mut c_void,
  535. completion: *const c_void,
  536. handle: *mut Handle,
  537. ) -> i32 {
  538. if !resolvable(narrow(name)) {
  539. return WSAHOST_NOT_FOUND;
  540. }
  541. 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)(
  542. name, service, namespace, provider, hints, result, timeout, overlapped, completion, handle,
  543. )
  544. }
  545. pub extern "system" fn GetAddrInfoExW(
  546. name: *const u16,
  547. service: *const u16,
  548. namespace: u32,
  549. provider: *const c_void,
  550. hints: *const c_void,
  551. result: *mut *mut c_void,
  552. timeout: *const c_void,
  553. overlapped: *mut c_void,
  554. completion: *const c_void,
  555. handle: *mut Handle,
  556. ) -> i32 {
  557. if !resolvable(wide(name)) {
  558. return WSAHOST_NOT_FOUND;
  559. }
  560. 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)(
  561. name, service, namespace, provider, hints, result, timeout, overlapped, completion, handle,
  562. )
  563. }
  564. pub extern "system" fn gethostbyname(name: *const c_char) -> *mut c_void {
  565. if !resolvable(narrow(name)) {
  566. return std::ptr::null_mut();
  567. }
  568. host!("ws2_32.dll", "gethostbyname": extern "system" fn(*const c_char) -> *mut c_void)(name)
  569. }
  570. pub extern "system" fn WSAAsyncGetHostByName(
  571. window: Handle,
  572. message: u32,
  573. name: *const c_char,
  574. buf: *mut c_char,
  575. buf_len: i32,
  576. ) -> Handle {
  577. if !resolvable(narrow(name)) {
  578. return std::ptr::null_mut();
  579. }
  580. host!("ws2_32.dll", "WSAAsyncGetHostByName": extern "system" fn(Handle, u32, *const c_char, *mut c_char, i32) -> Handle)(
  581. window, message, name, buf, buf_len,
  582. )
  583. }
  584. /// Name-space queries (DNS, also network lists and Bluetooth) are refused
  585. /// as a console without a network answers them.
  586. // shortcut: local name spaces are refused too; pass those through if a title
  587. // needs one.
  588. pub extern "system" fn WSALookupServiceBeginA(
  589. _restrictions: *const c_void,
  590. _flags: u32,
  591. _lookup: *mut Handle,
  592. ) -> i32 {
  593. once("network name-space query blocked", "any".into());
  594. wsa_error(WSASERVICE_NOT_FOUND);
  595. SOCKET_ERROR
  596. }
  597. /// See [`WSALookupServiceBeginA`].
  598. pub extern "system" fn WSALookupServiceBeginW(
  599. restrictions: *const c_void,
  600. flags: u32,
  601. lookup: *mut Handle,
  602. ) -> i32 {
  603. WSALookupServiceBeginA(restrictions, flags, lookup)
  604. }
  605. // Reverse lookups.
  606. pub extern "system" fn gethostbyaddr(addr: *const c_char, len: i32, kind: i32) -> *mut c_void {
  607. if !reverse_resolvable(raw_ip(addr, len, kind)) {
  608. wsa_error(WSAHOST_NOT_FOUND);
  609. return std::ptr::null_mut();
  610. }
  611. host!("ws2_32.dll", "gethostbyaddr": extern "system" fn(*const c_char, i32, i32) -> *mut c_void)(
  612. addr, len, kind,
  613. )
  614. }
  615. pub extern "system" fn WSAAsyncGetHostByAddr(
  616. window: Handle,
  617. message: u32,
  618. addr: *const c_char,
  619. len: i32,
  620. kind: i32,
  621. buf: *mut c_char,
  622. buf_len: i32,
  623. ) -> Handle {
  624. if !reverse_resolvable(raw_ip(addr, len, kind)) {
  625. wsa_error(WSAHOST_NOT_FOUND);
  626. return std::ptr::null_mut();
  627. }
  628. host!("ws2_32.dll", "WSAAsyncGetHostByAddr": extern "system" fn(Handle, u32, *const c_char, i32, i32, *mut c_char, i32) -> Handle)(
  629. window, message, addr, len, kind, buf, buf_len,
  630. )
  631. }
  632. pub extern "system" fn getnameinfo(
  633. sa: *const u8,
  634. sa_len: i32,
  635. host: *mut c_char,
  636. host_len: u32,
  637. serv: *mut c_char,
  638. serv_len: u32,
  639. flags: i32,
  640. ) -> i32 {
  641. let Some(flags) = name_info_flags(sa, sa_len, !host.is_null(), flags) else {
  642. return WSAHOST_NOT_FOUND;
  643. };
  644. host!("ws2_32.dll", "getnameinfo": extern "system" fn(*const u8, i32, *mut c_char, u32, *mut c_char, u32, i32) -> i32)(
  645. sa, sa_len, host, host_len, serv, serv_len, flags,
  646. )
  647. }
  648. pub extern "system" fn GetNameInfoW(
  649. sa: *const u8,
  650. sa_len: i32,
  651. host: *mut u16,
  652. host_len: u32,
  653. serv: *mut u16,
  654. serv_len: u32,
  655. flags: i32,
  656. ) -> i32 {
  657. let Some(flags) = name_info_flags(sa, sa_len, !host.is_null(), flags) else {
  658. return WSAHOST_NOT_FOUND;
  659. };
  660. host!("ws2_32.dll", "GetNameInfoW": extern "system" fn(*const u8, i32, *mut u16, u32, *mut u16, u32, i32) -> i32)(
  661. sa, sa_len, host, host_len, serv, serv_len, flags,
  662. )
  663. }
  664. // WinHTTP.
  665. /// The one door to a server: requests, uploads and WebSockets all hang off
  666. /// the handle this returns.
  667. pub extern "system" fn WinHttpConnect(
  668. session: Handle,
  669. server: *const u16,
  670. port: u16,
  671. reserved: u32,
  672. ) -> Handle {
  673. if let Some(name) = wide(server)
  674. && !loopback_name(&name)
  675. {
  676. once("HTTP connection blocked", format!("{name}:{port}"));
  677. // SAFETY: no pointers.
  678. unsafe { SetLastError(ERROR_WINHTTP_CANNOT_CONNECT) };
  679. return std::ptr::null_mut();
  680. }
  681. host!("winhttp.dll", "WinHttpConnect": extern "system" fn(Handle, *const u16, u16, u32) -> Handle)(
  682. session, server, port, reserved,
  683. )
  684. }
  685. /// Sessions never use a proxy: only loopback is reachable, and a proxy
  686. /// (named, or found by auto-detection) would carry it off the machine.
  687. pub extern "system" fn WinHttpOpen(
  688. agent: *const u16,
  689. access: u32,
  690. _proxy: *const u16,
  691. _bypass: *const u16,
  692. flags: u32,
  693. ) -> Handle {
  694. if access != WINHTTP_ACCESS_TYPE_NO_PROXY {
  695. once("HTTP proxy ignored", format!("access type {access}"));
  696. }
  697. host!("winhttp.dll", "WinHttpOpen": extern "system" fn(*const u16, u32, *const u16, *const u16, u32) -> Handle)(
  698. agent,
  699. WINHTTP_ACCESS_TYPE_NO_PROXY,
  700. std::ptr::null(),
  701. std::ptr::null(),
  702. flags,
  703. )
  704. }
  705. /// See [`WinHttpOpen`]: a proxy set later is accepted and not used.
  706. pub extern "system" fn WinHttpSetOption(
  707. handle: Handle,
  708. option: u32,
  709. buffer: *const c_void,
  710. len: u32,
  711. ) -> i32 {
  712. if option == WINHTTP_OPTION_PROXY {
  713. once("HTTP proxy ignored", "WINHTTP_OPTION_PROXY".into());
  714. return 1;
  715. }
  716. host!("winhttp.dll", "WinHttpSetOption": extern "system" fn(Handle, u32, *const c_void, u32) -> i32)(
  717. handle, option, buffer, len,
  718. )
  719. }
  720. /// Proxy auto-detection asks the network (DHCP, DNS, a PAC download).
  721. fn no_auto_proxy() -> u32 {
  722. once("HTTP proxy auto-detection blocked", "WPAD/PAC".into());
  723. ERROR_WINHTTP_AUTODETECTION_FAILED
  724. }
  725. pub extern "system" fn WinHttpDetectAutoProxyConfigUrl(_flags: u32, _url: *mut *mut u16) -> i32 {
  726. // SAFETY: no pointers.
  727. unsafe { SetLastError(no_auto_proxy()) };
  728. 0
  729. }
  730. pub extern "system" fn WinHttpGetProxyForUrl(
  731. _session: Handle,
  732. _url: *const u16,
  733. _options: *const c_void,
  734. _info: *mut c_void,
  735. ) -> i32 {
  736. // SAFETY: no pointers.
  737. unsafe { SetLastError(no_auto_proxy()) };
  738. 0
  739. }
  740. pub extern "system" fn WinHttpGetProxyForUrlEx(
  741. _resolver: Handle,
  742. _url: *const u16,
  743. _options: *const c_void,
  744. _context: usize,
  745. ) -> u32 {
  746. no_auto_proxy()
  747. }
  748. pub extern "system" fn WinHttpGetProxyForUrlEx2(
  749. _resolver: Handle,
  750. _url: *const u16,
  751. _options: *const c_void,
  752. _selection_len: u32,
  753. _selection: *const u8,
  754. _context: usize,
  755. ) -> u32 {
  756. no_auto_proxy()
  757. }
  758. pub extern "system" fn WinHttpGetProxySettingsEx(
  759. _resolver: Handle,
  760. _kind: i32,
  761. _params: *const c_void,
  762. _context: usize,
  763. ) -> u32 {
  764. no_auto_proxy()
  765. }
  766. /// Winsock imports by ordinal; the Winsock 1.1 numbers are fixed.
  767. fn ordinal(name: &'static str, f: usize) -> HleExport {
  768. HleExport { name, address: f }
  769. }
  770. pub(crate) fn module() -> HleModule {
  771. HleModule {
  772. name: "net",
  773. dlls: &["ws2_32.dll", "winhttp.dll"],
  774. exports: vec![
  775. hle_export!(connect),
  776. hle_export!(WSAConnect),
  777. hle_export!(WSAConnectByNameA),
  778. hle_export!(WSAConnectByNameW),
  779. hle_export!(WSAConnectByList),
  780. hle_export!(WSAJoinLeaf),
  781. hle_export!(WSAIoctl),
  782. hle_export!(sendto),
  783. hle_export!(WSASendTo),
  784. hle_export!(WSASendMsg),
  785. hle_export!(bind),
  786. hle_export!(getaddrinfo),
  787. hle_export!(GetAddrInfoW),
  788. hle_export!(GetAddrInfoExA),
  789. hle_export!(GetAddrInfoExW),
  790. hle_export!(gethostbyname),
  791. hle_export!(WSAAsyncGetHostByName),
  792. hle_export!(WSALookupServiceBeginA),
  793. hle_export!(WSALookupServiceBeginW),
  794. hle_export!(gethostbyaddr),
  795. hle_export!(WSAAsyncGetHostByAddr),
  796. hle_export!(getnameinfo),
  797. hle_export!(GetNameInfoW),
  798. hle_export!(WinHttpConnect),
  799. hle_export!(WinHttpOpen),
  800. hle_export!(WinHttpSetOption),
  801. hle_export!(WinHttpDetectAutoProxyConfigUrl),
  802. hle_export!(WinHttpGetProxyForUrl),
  803. hle_export!(WinHttpGetProxyForUrlEx),
  804. hle_export!(WinHttpGetProxyForUrlEx2),
  805. hle_export!(WinHttpGetProxySettingsEx),
  806. ordinal("#2", bind as *const () as usize),
  807. ordinal("#4", connect as *const () as usize),
  808. ordinal("#20", sendto as *const () as usize),
  809. ordinal("#51", gethostbyaddr as *const () as usize),
  810. ordinal("#52", gethostbyname as *const () as usize),
  811. ordinal("#102", WSAAsyncGetHostByAddr as *const () as usize),
  812. ordinal("#103", WSAAsyncGetHostByName as *const () as usize),
  813. ],
  814. }
  815. }
  816. #[cfg(test)]
  817. mod tests {
  818. use super::*;
  819. use victory_pe::ImportSymbol;
  820. fn v4(ip: [u8; 4], port: u16) -> [u8; 16] {
  821. let mut a = [0u8; 16];
  822. a[..2].copy_from_slice(&AF_INET.to_le_bytes());
  823. a[2..4].copy_from_slice(&port.to_be_bytes());
  824. a[4..8].copy_from_slice(&ip);
  825. a
  826. }
  827. // TEST-NET-1 (192.0.2.0/24): never routed, and never tried here.
  828. const AWAY: [u8; 4] = [192, 0, 2, 1];
  829. const HOME: [u8; 4] = [127, 0, 0, 1];
  830. #[test]
  831. fn only_loopback_is_reachable() {
  832. // Also starts Winsock for the raw calls below.
  833. let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
  834. let port = listener.local_addr().unwrap().port();
  835. let socket = host!("ws2_32.dll", "socket": extern "system" fn(i32, i32, i32) -> Socket);
  836. let close = host!("ws2_32.dll", "closesocket": extern "system" fn(Socket) -> i32);
  837. let last_error = host!("ws2_32.dll", "WSAGetLastError": extern "system" fn() -> i32);
  838. let null = std::ptr::null_mut::<c_void>();
  839. // Connects.
  840. let s = socket(2, 1, 6);
  841. assert_ne!(s, INVALID_SOCKET);
  842. assert_eq!(connect(s, v4(AWAY, 80).as_ptr(), 16), SOCKET_ERROR);
  843. assert_eq!(last_error(), WSAENETUNREACH);
  844. let n = null.cast();
  845. assert_eq!(
  846. WSAConnectByNameA(
  847. s,
  848. c"example.com".as_ptr(),
  849. c"80".as_ptr(),
  850. n,
  851. null,
  852. n,
  853. null,
  854. null,
  855. null
  856. ),
  857. 0
  858. );
  859. assert_eq!(last_error(), WSAHOST_NOT_FOUND);
  860. assert_eq!(connect(s, v4(HOME, port).as_ptr(), 16), 0);
  861. listener.accept().unwrap();
  862. // A stream socket sends to its vetted peer whatever `to` says.
  863. assert_eq!(sendto(s, b"x".as_ptr(), 1, 0, v4(AWAY, 9).as_ptr(), 16), 1);
  864. close(s);
  865. // `ConnectEx` from `WSAIoctl` is the vetted one.
  866. let s = socket(2, 1, 6);
  867. let mut f = 0usize;
  868. let mut size = 0u32;
  869. let guid = WSAID_CONNECTEX;
  870. let got = WSAIoctl(
  871. s,
  872. SIO_GET_EXTENSION_FUNCTION_POINTER,
  873. (&raw const guid).cast(),
  874. 16,
  875. (&raw mut f).cast(),
  876. 8,
  877. &mut size,
  878. null,
  879. null,
  880. );
  881. assert_eq!((got, f), (0, connect_ex as *const () as usize));
  882. assert_eq!(
  883. connect_ex(s, v4(AWAY, 80).as_ptr(), 16, null, 0, n, null),
  884. 0
  885. );
  886. assert_eq!(last_error(), WSAENETUNREACH);
  887. close(s);
  888. // Datagram sends.
  889. let u = socket(2, 2, 17);
  890. assert_eq!(
  891. sendto(u, b"x".as_ptr(), 1, 0, v4(AWAY, 9).as_ptr(), 16),
  892. SOCKET_ERROR
  893. );
  894. assert_eq!(last_error(), WSAENETUNREACH);
  895. assert_eq!(
  896. sendto(u, b"x".as_ptr(), 1, 0, v4(HOME, port).as_ptr(), 16),
  897. 1
  898. );
  899. close(u);
  900. // Forward and reverse lookups.
  901. let mut result = null;
  902. assert_eq!(
  903. getaddrinfo(
  904. c"example.com".as_ptr(),
  905. std::ptr::null(),
  906. std::ptr::null(),
  907. &mut result
  908. ),
  909. WSAHOST_NOT_FOUND
  910. );
  911. let name: Vec<u16> = "example.com\0".encode_utf16().collect();
  912. assert_eq!(
  913. GetAddrInfoW(
  914. name.as_ptr(),
  915. std::ptr::null(),
  916. std::ptr::null(),
  917. &mut result
  918. ),
  919. WSAHOST_NOT_FOUND
  920. );
  921. let mut text = [0 as c_char; 64];
  922. let away = v4(AWAY, 80);
  923. assert_eq!(
  924. getnameinfo(
  925. away.as_ptr(),
  926. 16,
  927. text.as_mut_ptr(),
  928. 64,
  929. std::ptr::null_mut(),
  930. 0,
  931. 0
  932. ),
  933. 0
  934. );
  935. // SAFETY: NUL-terminated by `getnameinfo`.
  936. let numeric = unsafe { CStr::from_ptr(text.as_ptr()) };
  937. assert_eq!(numeric.to_str(), Ok("192.0.2.1"));
  938. assert_eq!(
  939. getnameinfo(
  940. away.as_ptr(),
  941. 16,
  942. text.as_mut_ptr(),
  943. 64,
  944. std::ptr::null_mut(),
  945. 0,
  946. NI_NAMEREQD
  947. ),
  948. WSAHOST_NOT_FOUND
  949. );
  950. assert!(gethostbyaddr(AWAY.as_ptr().cast(), 4, 2).is_null());
  951. // WinHTTP.
  952. assert!(WinHttpConnect(null, name.as_ptr(), 443, 0).is_null());
  953. // SAFETY: no arguments.
  954. let error = unsafe { windows_sys::Win32::Foundation::GetLastError() };
  955. assert_eq!(error, ERROR_WINHTTP_CANNOT_CONNECT);
  956. assert_eq!(
  957. WinHttpGetProxyForUrlEx(null, name.as_ptr(), std::ptr::null(), 0),
  958. ERROR_WINHTTP_AUTODETECTION_FAILED
  959. );
  960. // The ordinals we override name the functions they stand for.
  961. let m = module();
  962. for e in m.exports.iter().filter(|e| e.name.starts_with('#')) {
  963. let named = m
  964. .exports
  965. .iter()
  966. .find(|n| n.address == e.address && !n.name.starts_with('#'))
  967. .unwrap();
  968. let by_ordinal = ImportSymbol::Ordinal(e.name[1..].parse().unwrap());
  969. assert_eq!(
  970. crate::HostPolicy::default().resolve("ws2_32.dll", &by_ordinal),
  971. crate::host::function("ws2_32.dll", named.name),
  972. "{} is not {}",
  973. e.name,
  974. named.name
  975. );
  976. }
  977. // Every override names a real export of its DLL. Some exports only
  978. // exist on newer Windows (WinHttpGetProxySettingsEx is absent from
  979. // Windows 10's winhttp.dll); the HLE supplies those itself, so skip
  980. // them only when the host really lacks them.
  981. const NEWER_WINDOWS_ONLY: &[&str] = &["WinHttpGetProxySettingsEx"];
  982. for e in m.exports.iter().filter(|e| !e.name.starts_with('#')) {
  983. let dll = if e.name.starts_with("WinHttp") {
  984. "winhttp.dll"
  985. } else {
  986. "ws2_32.dll"
  987. };
  988. let present = crate::host::function(dll, e.name).is_some();
  989. if !present && NEWER_WINDOWS_ONLY.contains(&e.name) {
  990. continue;
  991. }
  992. assert!(
  993. present,
  994. "{dll} lacks {}",
  995. e.name
  996. );
  997. }
  998. }
  999. }