fix(libkernel): fail recvmsg with EFAULT on guest memory it cannot read or write #7675
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/7675"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from boykopovar/AnyPS5. Originally posted by valenciana-nc on 2026-10-18T21:36:56Z.
What
recvmsg_nid_postfixread themsghdrand the iovec array, and wrote the received data, the sender address and themsghdrresults, with only null checks. This PR makes those copies fail withEFAULTinstead of faulting. It checks only the bytes that are actually read or written.msghdrand the iovec array are copied in before use. On Linux this usesprocess_vm_readvon the process itself. On Windows it usesVirtualQuery, requiring committed, readable pages. On macOS it usesmach_vm_read_overwriteon the current task. If the header or iovec array is unmapped, or on aPROT_NONE/PAGE_NOACCESSpage, the call fails withEFAULTbefore anything is received.nameLength,controlLengthandflagsare written underGuestArena::HostWrite, covering exactly the bytes written. On Linux this usesprocess_vm_writev; on macOS it usesmach_vm_writeon the current task. On Windows,VirtualQuerymust report a writable page after the guard opens, so an armed write-watched view is still accepted. A read-only or unmapped destination fails withEFAULT.guest_udpregression in the previous head (nameLength = UINT32_MAXon a 32-byte buffer, or a 1 GiB iovec over a 16-byte buffer).soreceive_dgram,soreceive_generic) but keeps unread stream data. The libkernel technical debt file records this and that a Linuxprocess_vm_*error other thanEFAULTthrows. The unchecked macOS-copy gap has been removed.This replaces the previous
CommittedRangecheck (mincore/MEM_COMMIT), which caused theguest_udpregression and did not catch inaccessible mapped pages.This overlaps #7090 (SCM_RIGHTS), which also changes
recvmsg_nid_postfix. Whichever PR merges second will need a rebase.Tested
Latest follow-up: rebased onto
mainb106f6f8c(including merged #7672), Release,BUILD_TESTING=ON.guest_recvmsg_memory,guest_socket_pair,guest_udp,guest_tcp,guest_socket_timeoutsand the 14guest_socket_host_write_*tests.guest_recvmsg_memory,guest_socket_pair,guest_udp,guest_tcp,guest_socket_timeouts.guest_recvmsg_memoryCTest entry runs the memory-fault cases independently (guest_socket_pair_tests recvmsg-memory). It can run even when an earlier, unrelated socketpair check fails on macOS.mainbaseline on Windows and Linux. The earlier fail-on-main check with this PR's tests and unmodifiedUdp.cppsegfaults on both platforms.a373e85e5: the Windows guest suite passed (one Vulkan-absence test skipped); Linux had only two failures also present on its baseline. Those broad suites were not rerun for this follow-up.CheckReceiveMessageFaultsincore/libs/tests/GuestSocketPair.cppruns on both platforms. It uses flexible memory with a writable, a read-only and a no-access page:EFAULT, datagram still queued: header at0x1000, header on the no-access page, iovec array at0x1000, iovec array on the no-access page.EFAULTafter the receive: iovec base at0x1000, iovec base on the no-access page, iovec base on the read-only page, name at0x1000, name on the read-only page, header on the read-only page. Nothing is left queued afterwards.nameLength = UINT32_MAX: 16 bytes are written and the rest of the buffer is untouched.Not run locally: macOS. The Mach implementation follows @jotitadev's independently run macOS probe/review; a rerun of this exact head is requested. No local macOS build or write-watch result is claimed.
Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-18T21:48:28Z.
One remaining pointer-validation gap:
MessageLength(message)runs before the new per-baseHostWritechecks, and it directly readsmessage->iov[i]. A non-null forgedmessage->iovcan therefore fault or read outside guest memory before any iovec-base validation occurs. Could the iovec descriptor array itself be safely copied/validated as guest-readable beforeMessageLengthand the receive loop use it? A regression with an out-of-arena or inaccessible iovec-array pointer would cover this path.Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-18T21:49:59Z.
More important,
HostWrite::Open()is not itself a guest-range validator. On Linux,GuestArenaBeginHostWrite_nid_postfixcalls the write-watch hook and then unconditionally returnstrue; on Windows,WindowsMappings::BeginHostWritealso returnstruewhen the pointer is not in any tracked view. Thus an out-of-arenaiov[i].basecan pass this guard and still be copied to as a host pointer. Please pair the write-watch guard with an actual guest-range/committed-range validation (including thenameandmsghdrdestinations), and add an out-of-arena pointer test. The descriptor-array read I noted above is a separate instance of the same trust-boundary issue.Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-18T22:08:24Z.
Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.
main)core/libs/prx/libkernel/Socket/src/Udp.cppL1376Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.
core/libs/prx/libkernel/CMakeLists.txtcore/libs/prx/libkernel/CMakeLists.txtcore/libs/prx/libkernel/Socket/src/Udp.cppcore/libs/tests/GuestSocketPair.cppdocs/dev/debt/libkernel.mdcore/libs/prx/libkernel/CMakeLists.txtcore/libs/tests/GuestSocketPair.cppdocs/dev/debt/libkernel.mdcore/libs/prx/libkernel/CMakeLists.txtdocs/dev/debt/libkernel.mdcore/libs/prx/libkernel/CMakeLists.txtdocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mdcore/libs/prx/libkernel/CMakeLists.txtcore/libs/prx/libkernel/CMakeLists.txtcore/libs/prx/libkernel/Socket/src/Udp.cppdocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mdcore/libs/prx/libkernel/Socket/src/Udp.cppdocs/dev/debt/libkernel.mdcore/libs/prx/libkernel/Socket/src/Udp.cppdocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mdcore/libs/prx/libkernel/CMakeLists.txtcore/libs/prx/libkernel/Socket/src/Udp.cppcore/libs/prx/libkernel/CMakeLists.txtcore/libs/prx/libkernel/Socket/src/Udp.cppcore/libs/tests/GuestSocketPair.cppdocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mdcore/libs/prx/libkernel/Socket/src/Udp.cppdocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mddocs/dev/debt/libkernel.mdImported from boykopovar/AnyPS5. Originally posted by LeandroLP23 on 2026-10-18T22:33:46Z.
Windows build and run, since the description has a syntax check only. Radeon 860M (RDNA 3.5, driver 32.0.13058.8001), Windows 11 26300, WinLibs GCC 15.2.0 r7, Release,
BUILD_TESTING=ON. Build:main8a456334fwith #7677, #7673, #7671, #7666, #7676, #7675, #7672, #7668, #7664 and #7658 merged together (each merge clean, built once).The build is clean. The full
guest_*run on that build: 474 of 476 pass, withguest_video_out_wqhd_detection_no_vulkanskipped. The 2 failures,guest_sysarchandguest_offline_imports, come from #7658 in the same build: they fail with #7658 alone and pass without it. I didn't check which of them reach the changed function, and no test checks the new buffer validation itself.AI-assisted
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-18T22:35:37Z.
Thanks for posting the Windows run. The 474/476 result is useful for the composed tree, with the two failures attributed to #7658. As you noted, it does not exercise the new recvmsg validation path, so it does not resolve the concrete guest-pointer issues from my earlier comments: the iovec array is read before validation, and
HostWrite::Open()does not reject pointers outside tracked guest ranges. A focused test for an invalid iovec-array pointer and an out-of-arena output pointer would directly cover those cases.Imported from boykopovar/AnyPS5. Originally posted by valenciana-nc on 2026-10-18T23:35:49Z.
All three points addressed in the latest push:
1. Iovec array validated before
MessageLength. The descriptor array range (iovLength * sizeof(GuestIovec), with the< 0 || > 1024bound checked first so the size computation is safe) is now verified beforeMessageLengthreadsmessage->iov[i]. A forgedmessage->iovfails withEFAULTinstead of faulting.2.
HostWritenow paired with committed-range validation. New file-localCommittedRange(pointer, bytes):mincoreover the page-aligned range on POSIX,VirtualQueryrequiringMEM_COMMITon every page on Windows. Every output destination — the msghdr struct itself, eachiov[i].base, andname— gets the committed check plus theHostWriteguard, all validated up front before any packet is waited on or received (guards stay alive in astd::dequethrough the copies, same pattern as libSceNet'ssceNetRecvmsg).One deliberate design call: I used committed-range rather than strict guest-arena containment. A
GuestArenaContainsrequirement would reject legitimate stack buffers — the existingGuestSocketPairtests pass stack-allocated msghdr/iov/data to this exact entry point (as dorecv/recvfrom/read, and real titles routinely dorecvmsg(fd, &stack_msg, 0)). The committed check rejects exactly the forged/unmapped pointers while preserving that calling convention.3. Focused tests added in
core/libs/tests/GuestSocketPair.cpp: forged iovec-array pointer, forged iovec base, and forged name pointer — each must return-1/EFAULT. On the pre-fix code the first segfaults inMessageLengthand the others fault on the copy, so they cover the reported paths. The WindowsVirtualQuerypath is implemented but not executed here (no Windows machine); the new guest tests are Linux-side.'Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-18T23:50:38Z.
I think the new
CommittedRangestill lets inaccessible-but-mapped pointers through. On POSIX,mincorereports mapping/residency and does not establish that a range is readable or writable; on Windows,MEM_COMMITlikewise includesPAGE_NOACCESSand read-only pages.recvmsgthen dereferences the iovec array or writes to the output range, so aPROT_NONE/PAGE_NOACCESSiovec array can still fault before returningEFAULT, and a read-only output page can fault duringmemcpy. Could the check verify the required page protections (read for the descriptor array, write for outputs), with focused inaccessible-mapped-range tests on each platform?Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-19T00:01:07Z.
Review: COMMENTED
Linux run of
f5ef1c1cb. It breaksguest_udp.Machine: Linux x86_64, i7-8700, Ubuntu 26.04, GCC 15.2, Release,
BUILD_TESTING=ON, full build.Head
f5ef1c1cbmerged ontomain84c1a4d9a(clean merge).guest_udpaborts with this head, 3 of 3 runs.mainpasses, and so did the previous heada482f911b. With theRequirecalls numbered, it stops atGuestUdp.cpp:94:recvmsg(receiver, &message, 0)returns -1 with errno 14. That check runs in the loop over name capacities{0, 1, 2, addressSize - 1, addressSize, 32, UINT32_MAX}on a 32-bytestd::array.CommittedRange(message->name, message->nameLength)checks the capacity the caller declares, not the bytesrecvmsgwrites, and an oversized capacity is valid input that the test covers. The iovec lengths are checked the same way. A probe on a Unix datagram pair, sending 4 bytes each time:mainf5ef1c1cbnameLength = 32nameLength = UINT32_MAXiov[0].base,length = 1 GiBmessage,iov[0].baseormessage->iov=0x1000(unmapped)message->iovoriov[0].baseon aPROT_NONEpageiov[0].baseon aPROT_READpageThe last two rows match @MarcZX10's point about
mincore.The new
guest_socket_paircases pass. With onlyGuestSocketPair.cppfrom this PR,mainsegfaults, so the new cases do cover the crash.Non-GPU suite (
ctest -E "^agc|gpu|vulkan|video_out"): 738/739. The one failure isguest_udp;mainis 739/739.Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
Imported from boykopovar/AnyPS5. Originally posted by valenciana-nc on 2026-10-19T01:37:01Z.
Thanks, both. Reworked in 3cb4ae859.
@jotitadev: the
guest_udpregression is fixed. Only the bytes that are actually copied are checked now:min(nameLength, address size)bytes;I reproduced your abort with
f5ef1c1cbon Linux, andguest_udppasses with the new head. From your probe table, the oversizednameLengthand the 1 GiB iovec now return the received count. An unmapped header, iovec array or base returnsEFAULT.@MarcZX10:
CommittedRange(mincore/MEM_COMMIT) is gone. Reading the header and iovec array, and every write, now go through checked copies:process_vm_readv/process_vm_writevon the process itself. The kernel applies the page protections, soPROT_NONEandPROT_READpages returnEFAULTinstead of faulting.VirtualQuerywith read or write protection masks. The write check runs afterHostWriteopens, so armed write-watched views still pass.CheckReceiveMessageFaultsinGuestSocketPair.cppcovers read-only and no-access pages on both platforms.Trade-off: an output fault is found after the host receive, so the data is dropped. FreeBSD also drops a datagram on a copy fault, but keeps unread stream data. The libkernel technical debt file records this, along with the unchecked copies on macOS. Results are in the description. A receive into write-watched memory was not exercised on Linux, because userfaultfd write protection was not available in my environment.
Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-19T02:42:50Z.
Review: COMMENTED
macOS run of
3cb4ae859. The newCheckReceiveMessageFaultscrashes on a macOS host, and XNU has a checked-copy equivalent that makes it pass.Machine: Apple M2 Max, macOS 27.2, Xcode 27 clang, Release,
BUILD_TESTING=ON, x86_64 under Rosetta. Not main:maindoes not build on macOS yet, so the base ismaina373e85e5+ mugurc'sci/macos-series-2(91e4eccaf) + the macOS bits of #7332. The PR diff applied cleanly on top (git apply -3). I rebuilt and ran the socket tests (ctest -R 'guest_(socket|udp|tcp|sendfile)', 14 tests).guest_udppasses with this head. The regression fromf5ef1c1cbis gone on macOS too.guest_socket_pairaborts on macOS both with and without this PR, at an existing check:shutdown(SHUT_RD)on the peer aftershutdown(SHUT_WR)returnsENOTCONNon XNU. That abort comes beforeCheckReceiveMessageFaults, so the full test never reaches the new cases. I ran them on their own with a local test-only patch that callsCheckReceiveMessageFaults()first:0x1000. On macOSReadGuestandWriteGuestfall through to plainmemcpy. The debt entry says the copies are unchecked on macOS, but the test is not gated, so it crashes on a macOS host.XNU primitives, standalone probe (arm64 native and x86_64 Rosetta give the same results).
mach_vm_read_overwriteandmach_vm_writeonmach_task_self()behave likeprocess_vm_readv/process_vm_writev:mach_vm_read_overwritemach_vm_writePROT_READpageKERN_INVALID_ADDRESS, page unchangedPROT_NONEpageKERN_INVALID_ADDRESSKERN_INVALID_ADDRESS0x1000KERN_INVALID_ADDRESSKERN_INVALID_ADDRESSPROT_NONEKERN_INVALID_ADDRESSKERN_INVALID_ADDRESSWith an
__APPLE__branch that uses those two calls (below), every case inCheckReceiveMessageFaultspasses on macOS. The other socket tests show the same results as base: 13/14, with only the pre-existingguest_socket_pairabort.So there are two options: use this branch and drop "unchecked on macOS" from the debt entry, or gate
CheckReceiveMessageFaultsoff on__APPLE__. I did not test a receive into write-watched memory on macOS, and I did not test an arm64 build of the tree.Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-19T10:28:17Z.
Review: COMMENTED
Linux rerun of
3cb4ae859with the same probe as my report onf5ef1c1cb.Machine: Linux x86_64, i7-8700, Ubuntu 26.04, GCC 15.2, Release,
BUILD_TESTING=ON, full build. Head3cb4ae859merged ontomain8816fd772(clean merge).guest_udppasses again, 3 of 3 runs directly and under ctest. The socket tests pass (12/12) and the non-GPU suite is 775/775, same asmain.guest_socket_paironmain(library unchanged) segfaults, so the new cases cover the change.recvmsgon a socketpair with a 4-byte message):f5ef1c1cb3cb4ae859message,message->iovoriov[0].baseat0x1000EFAULTEFAULTmessage->iovon aPROT_NONEpageEFAULTiov[0].baseon aPROT_NONEpageEFAULTiov[0].baseon aPROT_READpageEFAULTnameLength = UINT32_MAXEFAULTmainEFAULTmainSo on Linux both the regression and the mapped-but-inaccessible cases are fixed. The macOS point from my other comment (plain
memcpythere) is unchanged by this head.Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
Imported from boykopovar/AnyPS5. Originally posted by valenciana-nc on 2026-10-19T12:31:12Z.
@jotitadev thanks for the macOS probe and Linux rerun. Addressed in
f7fd9dbf9, rebased ontomainb106f6f8c(including the concurrent merge of #7672):ReadGuestnow usesmach_vm_read_overwriteon macOS;WriteGuestusesmach_vm_write, under the existing host-write guard. The unchecked macOS fallback is gone, and that gap is removed from the debt entry.guest_recvmsg_memory(guest_socket_pair_tests recvmsg-memory), so the memory-fault checks can run independently of the earliershutdownassertion you identified. Added an explicit no-access iovec-base case too.Locally: 19/19 focused socket tests pass on Windows (GCC 15.2 r7), and 5/5 on Linux (GCC 14.2). I cannot run macOS here, so I am not claiming a macOS build or execution result. Could you rerun
ctest -R '^guest_recvmsg_memory$' --output-on-failureon your macOS build? No test-only reorder should be needed now.AI-assisted: yes.