hw/xen, i386/xen: security and robustness fixes
cover hw/xen, i386/xen: security and robustness fixes
From: David Woodhouse <[email protected]>
Addressing the backlog of mostly AI-discovered issues in the KVM/Xen support.
Disclaimer: The fixes here were diagnosed by AI, fixed by AI, the commit messages written by AI, and all the testing done by AI. And then the new things which I would *never* have found if I'd have to do all the typing myself were also fixed the same way. All under my close direction, occasionally completely redirecting the way it wanted to do things and rewriting its prose from scratch — but still AI first.
You can stop reading now if that's a problem. I was hoping to see the policy changes¹ go in first and send these fixes afterwards, but that still hasn't happened. Nevertheless, I have neither the time nor the inclination to do a complete clean room implementation with my own meat fingers. Take it or leave it, or tell me to wait for the official policy change.
This fixes:
• CVE-2026-61403: xen_xenstore get_req() copies a full header length regardless of how much was already consumed, so a guest feeding the header in two parts overshoots req_offset and the next length calculation underflows: a guest-controlled linear heap overwrite.
• CVE-2026-123069: the per-vCPU Xen timers survive ACPI ejection of their vCPU, with the freed CPUState as the callback opaque.
• CVE-2026-123070: PHYSDEVOP_eoi and irq_status_query index the PIRQ tables with no bounds check (OOB read).
• CVE-2026-123071: the xen-console output trim underflows when the frontend sets a small enough 'limit' — up to ~2 KiB of guest-controlled bytes written *before* the buffer.
• CVE-2026-123072: xen-9p-backend re-reads the guest's ring indices after validating the request, so the iovecs can reach up to 1 MiB past the end of the ring mapping (OOB read, disclosable via Twrite).
• CVE-2026-123074: grant copy segments weren't validated against the page size. I don't believe this one is guest-reachable in-tree (xen-block already bounds its segments), so this is hardening to match Xen's GNTST_bad_copy_arg.
(CVE-2026-123073 was also assigned from the same combined report, but it's simply a duplicate of CVE-2026-61403 above. I think that wants rejecting.)
Followed by a handful of other issues found on the journey, including the XenBus InitWait ordering regression reported by Mark Syms².
Patches 20-21 fix the two Coverity CIDs (1527403, 1507603) and conflict textually with the lock-guard conversion recently posted³. That conversion doesn't actually fix the bug that Coverity was whining about, so I'd suggest these go first.
Testing: each original report's reproducer triggers its ASan signature on the unfixed tree and is clean with the fix applied; the KVM/Xen functional tests pass; a real Fedora guest with PV console and disk survives kexec soft-reset cycles (although that surfaces a handful of kexec and kdump issues which I'm looking at separately).
¹ https://lists.gnu.org/archive/html/qemu-devel/2026-09/msg00260.html
² https://lore.kernel.org/qemu-devel/[email protected]
³ https://lore.kernel.org/qemu-devel/[email protected]
David Woodhouse (21):
hw/xen: Fix partial request header handling in emulated XenStore i386/xen: Don't resample GSI when per-vCPU upcall vector is in use i386/xen: Free Xen vCPU timers when a vCPU is destroyed hw/xen: Publish backend features before setting state to InitWait hw/i386/kvm/xen_gnttab: Fix error handling in xen_be_gnttab_map_refs() hw/xen: Validate grant copy segments against the page size hw/i386/kvm/xen_evtchn: Validate PIRQ numbers in physdev operations hw/i386/kvm/xen_evtchn: Fix off-by-one in do_remove_pci_vector() i386/xen: Don't inject event on invalid port in qmp_xen_event_inject() hw/i386/kvm/xen_evtchn: Reuse existing backend port in find_be_port() hw/i386/kvm/xen: Don't leak gnttab handle on reset hw/i386/kvm/xen_xenstore: Apply offset before truncation in
xs_append_strings()
hw/char/xen_console: Fix buffer trim when size exceeds twice the limit hw/9pfs/xen-9p-backend: Use validated snapshot for request iovecs hw/9pfs/xen-9p-backend: Validate the request header size field hw/9pfs/xen-9p-backend: Validate frontend-supplied connect parameters hw/9pfs/xen-9p-backend: Close event channel handle on disconnect hw/net/xen_nic: Bound the TX and RX rings' producer index hw/xen: Bound the rep count of PIO and MMIO ioreqs hw/i386/kvm/xen_evtchn: Hold port_lock for whole of bind_pirq_op hw/i386/kvm/xen_evtchn: Allow unmapping an emulated MSI PIRQ
hw/9pfs/xen-9p-backend.c | 65 +++++++++++++++++-------------- hw/char/xen_console.c | 20 +++++++--- hw/i386/kvm/xen_evtchn.c | 59 ++++++++++++++++++---------- hw/i386/kvm/xen_gnttab.c | 22 ++++++++++- hw/i386/kvm/xen_primary_console.c | 3 ++ hw/i386/kvm/xen_xenstore.c | 31 +++++++++------ hw/net/xen_nic.c | 9 ++++- hw/xen/xen-bus.c | 16 +++++++- hw/xen/xen-hvm-common.c | 19 ++++++++- hw/xen/xen-operations.c | 11 ++++++ target/i386/kvm/kvm.c | 6 +++ target/i386/kvm/xen-emu.c | 49 ++++++++++++++++++++++- target/i386/kvm/xen-emu.h | 1 + 13 files changed, 235 insertions(+), 76 deletions(-)
Signature · 1 line
2.43.0
PATCH 1/21 hw/xen: Fix partial request header handling in emulated XenStore
From: David Woodhouse <[email protected]>
When a XenStore request header is only partially received, QEMU copies XENSTORE_HEADER_SIZE bytes instead of only the remaining header bytes.
Fix the length calculation to copy only the missing part of the header.
--- hw/i386/kvm/xen_xenstore.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
hw/i386/kvm/xen_xenstore.c +1 -1
@@ -1218,7 +1218,7 @@ static unsigned int get_req(XenXenstoreState *s)if (s->req_offset <XENSTORE_HEADER_SIZE ) {void *ptr = s->req_data + s->req_offset; -unsigned int len =XENSTORE_HEADER_SIZE ; +unsigned int len =XENSTORE_HEADER_SIZE - s->req_offset;unsigned int copylen =copy_from_ring (s, ptr, len); copied += copylen;
Signature · 1 line
2.43.0
PATCH 2/21 i386/xen: Don't resample GSI when per-vCPU upcall vector is in use
In reply to David WoodhouseFrom: David Woodhouse <[email protected]>
The callback_via GSI (or PCI INTx) and the per-vCPU upcall vector are mutually exclusive delivery mechanisms for Xen event channel upcalls. Xen itself will never assert the callback GSI for a vCPU which has a per-vCPU upcall vector configured.
When the interrupt is acked, QEMU's resampling logic reasserts the GSI if evtchn_upcall_pending is still set. If the guest has configured a per-vCPU upcall vector, events are delivered through that vector and the GSI is unexpected; a guest which receives both the vector upcall and a spurious GSI interrupt for the same event can crash. This was observed in production with Windows guests on a different VMM which implements the same resampling logic.
If a per-vCPU upcall vector is configured, don't resample the GSI; just deassert it.
--- target/i386/kvm/xen-emu.c | 7 +++++++ 1 file changed, 7 insertions(+)
target/i386/kvm/xen-emu.c +7 -0
@@ -435,6 +435,13 @@ void kvm_xen_maybe_deassert_callback(CPUState *cs)return ; } +if (env->xen_vcpu_callback_vector) { +BQL_LOCK_GUARD (); + env->xen_callback_asserted = false; +xen_evtchn_set_callback_level (0 ); +return ; + } +/* If the evtchn_upcall_pending flag is cleared, turn the GSI off. */ if (!vi->evtchn_upcall_pending) {bql_lock ();
Signature · 1 line
2.43.0
PATCH 3/21 i386/xen: Free Xen vCPU timers when a vCPU is destroyed
In reply to David WoodhouseFrom: David Woodhouse <[email protected]>
kvm_xen_init_vcpu() allocates the per-vCPU timers with the CPUState as callback opaque, and nothing freed them on vCPU destruction. So a guest could arm the periodic timer for a vCPU (VCPUOP_set_periodic_timer always reaches QEMU; the kernel doesn't handle it) and eject that vCPU via ACPI hotplug, leaving the armed timer pointing at a freed X86CPU.
Free both timers in kvm_xen_destroy_vcpu(), called from kvm_arch_destroy_vcpu(). That runs under the BQL, as do the timer callbacks, so it cannot race an in-flight callback. It *can* race a timer hypercall from another vCPU — hypercalls don't take the BQL, which is why xen_timers_lock exists — so clear the pointers under that lock and have the periodic timer paths return -ENOENT when the timer is gone, as for a nonexistent vCPU. The singleshot ops act only on the calling vCPU, so cannot race its destruction.
Also move the timer_del() in do_set_periodic_timer() inside the lock, where it should have been all along.
--- target/i386/kvm/kvm.c | 6 ++++++ target/i386/kvm/xen-emu.c | 36 ++++++++++++++++++++++++++++++++++-- target/i386/kvm/xen-emu.h | 1 + 3 files changed, 41 insertions(+), 2 deletions(-)
target/i386/kvm/kvm.c +6 -0
@@ -2556,6 +2556,12 @@ int kvm_arch_destroy_vcpu(CPUState *cs)X86CPU *cpu =X86_CPU (cs);CPUX86State *env = &cpu->env; +#ifdef CONFIG_XEN_EMU +if (cs->kvm_state->xen_version) { +kvm_xen_destroy_vcpu (cs); + } +#endif +g_free (env->xsave_buf);g_free (cpu->kvm_msr_buf);
target/i386/kvm/xen-emu.c +34 -2
@@ -276,6 +276,28 @@ int kvm_xen_init_vcpu(CPUState *cs)return 0 ; } +void kvm_xen_destroy_vcpu (CPUState *cs) +{ +CPUX86State *env = &X86_CPU (cs)->env; + +/* +* This runs on the vCPU's own thread with the BQL held, and the +* timer callbacks run from the main loop thread also with the BQL +* held, so freeing the timers cannot race against an in-flight +* callback. It *can* race against a Xen hypercall from another +* vCPU targeting this one (hypercalls are handled without the +* BQL), so clear the pointers under xen_timers_lock to let those +* paths observe the vCPU's demise. +*/ +QEMU_LOCK_GUARD (&env->xen_timers_lock); + +timer_free (env->xen_singleshot_timer); + env->xen_singleshot_timer =NULL ; + +timer_free (env->xen_periodic_timer); + env->xen_periodic_timer =NULL ; +} +uint32_t kvm_xen_get_caps (void ) {return kvm_state->xen_caps;
@@ -1079,10 +1101,15 @@ static int do_set_periodic_timer(CPUState *target, uint64_t period_ns)CPUX86State *tenv = &X86_CPU (target)->env;int64_t qemu_now; -timer_del (tenv->xen_periodic_timer); -qemu_mutex_lock (&tenv->xen_timers_lock); +if (!tenv->xen_periodic_timer) { +qemu_mutex_unlock (&tenv->xen_timers_lock); +return -ENOENT ; + } + +timer_del (tenv->xen_periodic_timer); + qemu_now =qemu_clock_get_ns (QEMU_CLOCK_VIRTUAL );timer_mod_ns (tenv->xen_periodic_timer, qemu_now + period_ns); tenv->xen_periodic_timer_period = period_ns;
@@ -1120,6 +1147,11 @@ static int vcpuop_stop_periodic_timer(CPUState *target)qemu_mutex_lock (&tenv->xen_timers_lock); +if (!tenv->xen_periodic_timer) { +qemu_mutex_unlock (&tenv->xen_timers_lock); +return -ENOENT ; + } +timer_del (tenv->xen_periodic_timer); tenv->xen_periodic_timer_period =0 ;
target/i386/kvm/xen-emu.h +1 -0
@@ -25,6 +25,7 @@int kvm_xen_init (KVMState *s,uint32_t hypercall_msr);int kvm_xen_init_vcpu (CPUState *cs); +void kvm_xen_destroy_vcpu (CPUState *cs);int kvm_xen_handle_exit (X86CPU *cpu,struct kvm_xen_exit *exit);int kvm_put_xen_state (CPUState *cs);int kvm_get_xen_state (CPUState *cs);
Signature · 1 line
2.43.0
PATCH 4/21 hw/xen: Publish backend features before setting state to InitWait
In reply to David WoodhouseFrom: David Woodhouse <[email protected]>
The XenbusStateInitWait transition tells the frontend that the backend's parameters are readable, but xen_device_realize() set it before calling the implementation's realize method — which is what writes the feature nodes ('max-ring-page-order' et al. for xen-block, 'feature-rx-copy' for xen-net).
Linux blkfront reads 'max-ring-page-order' with xenbus_read_unsigned():
no wait, no retry, default 0. Lose the race and it silently negotiates a single-page ring — 32 request slots instead of 256. A device hot-plugged into a running guest loses essentially every time; at boot the frontend doesn't come looking until long after realize finished. Netfront reads its feature nodes the same way.
Commit 240cc11369fc ("hw/xen: Avoid crash when backend watch fires too early") introduced this by moving the realize call after the block of code which both populates the initial xenstore nodes *and* sets InitWait. The crash it fixed was real — xen-block's realize processes watch events via blkconf_geometry()'s aio_poll(), and the handlers fell over when the nodes didn't yet exist — but only the node population needed to come first.
So keep the node population and the 'online' write before realize, and move only the InitWait transition after it. A watch event during realize now finds the frontend in Initialising and no backend 'state' node, which the handlers tolerate; none of the three realize implementations reads the backend state. Verified against the original 2023 crash reproducer as well as the ring-order negotiation.
--- hw/xen/xen-bus.c | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-)
hw/xen/xen-bus.c +15 -1
@@ -1082,7 +1082,6 @@ static void xen_device_realize(DeviceState *dev, Error **errp)xen_device_backend_printf (xendev,"hotplug-status" ,"connected" );xen_device_backend_set_online (xendev, true); -xen_device_backend_set_state (xendev, XenbusStateInitWait);if (!xen_device_frontend_exists (xendev)) { xen_device_frontend_printf(xendev, "backend", "%s",
@@ -1093,6 +1092,19 @@ static void xen_device_realize(DeviceState *dev, Error **errp)xen_device_frontend_set_state (xendev, XenbusStateInitialising, true); } +/* +* The implementation's realize method may write feature nodes to +* the backend area (e.g. 'max-ring-page-order' for xen-block, +* 'feature-rx-copy' for xen-net). It must be called after the +* backend and frontend areas are populated, because it can invoke +* aio_poll() (e.g. through blkconf_geometry()) and thus process +* watch events which need to read the 'state' nodes. But it must +* be called *before* the backend state is set to InitWait below, +* because InitWait is the frontend's cue that the backend's +* feature nodes can be read; a frontend which reads them promptly +* (as Linux blkfront and netfront do, without waiting or retrying) +* must not find them missing. +*/ if (xendev_class->realize) { xendev_class->realize (xendev, errp);if (*errp) {
@@ -1100,6 +1112,8 @@ static void xen_device_realize(DeviceState *dev, Error **errp) } } +xen_device_backend_set_state (xendev, XenbusStateInitWait); + xendev->exit.notify = xen_device_exit;qemu_add_exit_notifier (&xendev->exit);return ;
Signature · 1 line
2.43.0
PATCH 5/21 hw/i386/kvm/xen_gnttab: Fix error handling in xen_be_gnttab_map_refs()
In reply to David WoodhouseFrom: David Woodhouse <[email protected]>
When the grant's target page cannot be mapped, the failure path calls gnt_unref(), which asserts that the map_track[] refcount is non-zero — but the refcount was only incremented after a successful mapping. Take the reference as soon as gnt_ref() succeeds, so the failure path stays balanced.
Refuse writable mappings, including a write upgrade of an existing mapping, when the underlying memory region is read-only, and set errno when the upgrade fails.
--- hw/i386/kvm/xen_gnttab.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-)
hw/i386/kvm/xen_gnttab.c +10 -2
@@ -363,7 +363,9 @@ static void *xen_be_gnttab_map_refs(struct xengntdev_handle *xgt, act =g_hash_table_lookup (xgt->active_maps,GINT_TO_POINTER (refs[0 ]));if (act) {if ((prot &PROT_WRITE ) && !(act->prot &PROT_WRITE )) { -if (gnt_ref (s, refs[0 ], prot) ==INVALID_GPA ) { +if (act->mrs.readonly || +gnt_ref (s, refs[0 ], prot) ==INVALID_GPA ) { + errno =EINVAL ;return NULL ; } act->prot |=PROT_WRITE ;
@@ -376,12 +378,19 @@ static void *xen_be_gnttab_map_refs(struct xengntdev_handle *xgt,return NULL ; } +/* +* Keep the map_track[] count balanced with the gnt_unref() in the +* failure path below, which asserts that it never underflows. +*/ + s->map_track[refs[0 ]]++; + act = g_new0(struct active_ref, 1); act->prot = prot; act->refcnt =1 ; act->mrs =memory_region_find (get_system_memory (), gpa,XEN_PAGE_SIZE );if (act->mrs.mr && + !(act->mrs.readonly && (prot &PROT_WRITE )) && !int128_lt (act->mrs.size,int128_make64 (XEN_PAGE_SIZE )) &&memory_region_get_ram_addr (act->mrs.mr) !=RAM_ADDR_INVALID ) { act->virtaddr = qemu_map_ram_ptr(act->mrs.mr->ram_block,
@@ -394,7 +403,6 @@ static void *xen_be_gnttab_map_refs(struct xengntdev_handle *xgt,return NULL ; } - s->map_track[refs[0 ]]++;g_hash_table_insert (xgt->active_maps,GINT_TO_POINTER (refs[0 ]), act); }
Signature · 1 line
2.43.0
PATCH 6/21 hw/xen: Validate grant copy segments against the page size
In reply to David WoodhouseFrom: David Woodhouse <[email protected]>
Reject a grant copy segment whose offset and length reach beyond the granted page, matching Xen's GNTST_bad_copy_arg behaviour, in both the emulated gnttab backend and the libxengnttab fallback. The only current caller, xen-block, already bounds its segments to a single page.
--- hw/i386/kvm/xen_gnttab.c | 10 ++++++++++ hw/xen/xen-operations.c | 11 +++++++++++ 2 files changed, 21 insertions(+)
hw/i386/kvm/xen_gnttab.c +10 -0
@@ -473,6 +473,16 @@ static int xen_be_gnttab_copy(struct xengntdev_handle *xgt, bool to_domain,void *page;uint32_t ref = to_domain ? seg->dest.foreign.ref : seg->source.foreign.ref; +off_t offset = to_domain ? seg->dest.foreign.offset : + seg->source.foreign.offset; + +if (offset <0 || offset >XEN_PAGE_SIZE || + seg->len >XEN_PAGE_SIZE - offset) { +if (errp) { +error_setg (errp,"grant copy segment out of page bounds" ); + } +return -EINVAL ; + } page =xen_be_gnttab_map_refs (xgt,1 , domid, &ref, prot);if (!page) {
hw/xen/xen-operations.c +11 -0
@@ -50,6 +50,17 @@ static int libxengnttab_fallback_grant_copy(xengnttab_handle *xgt,for (i =0 ; i < nr_segs; i++) {XenGrantCopySegment *seg = &segs[i]; +off_t offset = to_domain ? seg->dest.foreign.offset : + seg->source.foreign.offset; + +if (offset <0 || offset >XEN_PAGE_SIZE || + seg->len >XEN_PAGE_SIZE - offset) { +if (errp) { +error_setg (errp,"grant copy segment out of page bounds" ); + } + rc = -EINVAL ; + goto done; + } refs[i] = to_domain ? seg->dest.foreign.ref : seg->source.foreign.ref;
Signature · 1 line
2.43.0
PATCH 7/21 hw/i386/kvm/xen_evtchn: Validate PIRQ numbers in physdev operations
In reply to David WoodhouseFrom: David Woodhouse <[email protected]>
xen_physdev_eoi_pirq() and xen_physdev_query_pirq() used the given PIRQ number to index the PIRQ tables without checking it against nr_pirqs. Reject out-of-range values, and reject PIRQ 0 in bind_pirq and map_pirq. PIRQs 0-15 are reserved for the initial domain's identity claims of the legacy ISA IRQs — the allocators, Xen's and ours alike, never hand them out — and an HVM guest has no such claim. QEMU's gsi_pirq[] and MSI target lookups both treat 0 as "no PIRQ", so a guest-mapped pirq 0 could never deliver anything; better to refuse it than to create a silently dead mapping.
--- hw/i386/kvm/xen_evtchn.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-)
hw/i386/kvm/xen_evtchn.c +10 -2
@@ -1283,7 +1283,7 @@ int xen_evtchn_bind_pirq_op(struct evtchn_bind_pirq *pirq)return -ENOTSUP ; } -if (pirq->pirq >= s->nr_pirqs) { +if (!pirq->pirq || pirq->pirq >= s->nr_pirqs) {return -EINVAL ; }
@@ -1877,7 +1877,7 @@ int xen_physdev_map_pirq(struct physdev_map_pirq *map)return pirq; } map->pirq = pirq; - }else if (pirq >= s->nr_pirqs) { + }else if (!pirq || pirq >= s->nr_pirqs) {return -EINVAL ; }else {/*
@@ -1958,6 +1958,10 @@ int xen_physdev_eoi_pirq(struct physdev_eoi *eoi)return -ENOTSUP ; } +if (pirq <0 || pirq >= s->nr_pirqs) { +return -EINVAL ; + } +BQL_LOCK_GUARD ();QEMU_LOCK_GUARD (&s->port_lock);
@@ -1990,6 +1994,10 @@ int xen_physdev_query_pirq(struct physdev_irq_status_query *query)return -ENOTSUP ; } +if (pirq <0 || pirq >= s->nr_pirqs) { +return -EINVAL ; + } +BQL_LOCK_GUARD ();QEMU_LOCK_GUARD (&s->port_lock);
Signature · 1 line
2.43.0
PATCH 8/21 hw/i386/kvm/xen_evtchn: Fix off-by-one in do_remove_pci_vector()
In reply to David WoodhouseFrom: David Woodhouse <[email protected]>
The empty-word optimisation advanced pirq by 64 on top of the loop increment, so the first PIRQ of the following word was never examined and could retain a stale device binding after the device was removed.
--- hw/i386/kvm/xen_evtchn.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
hw/i386/kvm/xen_evtchn.c +1 -1
@@ -1701,7 +1701,7 @@ static void do_remove_pci_vector(XenEvtchnState *s, PCIDevice *dev, int vector,* and cache lines). */ if (!(pirq &63 ) && !(pirq_inuse_word (s, pirq))) { - pirq +=64 ; + pirq +=63 ;continue ; }if (except_pirq && pirq == except_pirq) {
Signature · 1 line
2.43.0
PATCH 9/21 i386/xen: Don't inject event on invalid port in qmp_xen_event_inject()
In reply to David WoodhouseFrom: David Woodhouse <[email protected]>
qmp_xen_event_inject() reported the invalid port with error_setg() but then carried on regardless, passing it to set_port_pending(). Return after setting the error.
--- hw/i386/kvm/xen_evtchn.c | 1 + 1 file changed, 1 insertion(+)
hw/i386/kvm/xen_evtchn.c +1 -0
@@ -2342,6 +2342,7 @@ void qmp_xen_event_inject(uint32_t port, Error **errp)if (!valid_port (port)) {error_setg (errp,"Invalid port %u" , port); +return ; }QEMU_LOCK_GUARD (&s->port_lock);
Signature · 1 line
2.43.0
Re: [PATCH v1 09/21] i386/xen: Don't inject event on invalid port in qmp_xen_event_inject()
Quoted 6 lines · David Woodhouse
From: David Woodhouse <[email protected]>
qmp_xen_event_inject()reported the invalid port witherror_setg()but then carried on regardless, passing it toset_port_pending(). Return after setting the error.
Quoted 7 lines
Fixes 507cb64d6e66 ("i386/xen: add monitor commands to test event injection")Reported-by Hui Peng <[email protected]>Signed-off-by David Woodhouse <[email protected]>--- hw/i386/kvm/xen_evtchn.c | 1 + 1 file changed, 1 insertion(+)
PATCH 10/21 hw/i386/kvm/xen_evtchn: Reuse existing backend port in find_be_port()
In reply to David WoodhouseFrom: David Woodhouse <[email protected]>
After a guest soft reset, close_port() clears only the guest side of an interdomain port; the backend handle still owns its be_handles[] slot. Binding again then allocated a fresh slot each time, leaking the old one — and leaving a dangling entry if the handle is later closed. Reuse the slot the handle already owns.
--- hw/i386/kvm/xen_evtchn.c | 10 ++++++++++ 1 file changed, 10 insertions(+)
hw/i386/kvm/xen_evtchn.c +10 -0
@@ -2052,6 +2052,16 @@ static int find_be_port(XenEvtchnState *s, struct xenevtchn_handle *xc) {int i; +/* +* A handle may still own a backend port from before a guest soft reset; +* close_port() clears only the guest side. Reuse it rather than leaking +* the old slot and allocating a second one. +*/ +if (xc->be_port && xc->be_port <EVTCHN_2L_NR_CHANNELS && + s->be_handles[xc->be_port] == xc) { +return xc->be_port; + } +for (i =1 ; i <EVTCHN_2L_NR_CHANNELS ; i++) {if (!s->be_handles[i]) { s->be_handles[i] = xc;
Signature · 1 line
2.43.0
PATCH 11/21 hw/i386/kvm/xen: Don't leak gnttab handle on reset
In reply to David WoodhouseFrom: David Woodhouse <[email protected]>
xen_xenstore_reset() and xen_primary_console_reset() open a new gnttab handle without closing the previous one, leaking it and its mappings on each guest soft reset. Close the old handle first; closing unmaps any remaining refs.
--- hw/i386/kvm/xen_primary_console.c | 3 +++ hw/i386/kvm/xen_xenstore.c | 3 +++ 2 files changed, 6 insertions(+)
hw/i386/kvm/xen_primary_console.c +3 -0
@@ -184,6 +184,9 @@ int xen_primary_console_reset(void)trace_xen_primary_console_reset (s->guest_port); +if (s->gt) { +qemu_xen_gnttab_close (s->gt); + } s->gt =qemu_xen_gnttab_open ();uint32_t xs_gntref =GNTTAB_RESERVED_CONSOLE ; s->granted_xs = qemu_xen_gnttab_map_refs(s->gt, 1, xen_domid, &xs_gntref,
hw/i386/kvm/xen_xenstore.c +3 -0
@@ -1490,6 +1490,9 @@ int xen_xenstore_reset(void)* first place. Map the grant anyway, mostly for cosmetic purposes so * it *looks* like it's in use in the guest-visible grant table. */ +if (s->gt) { +qemu_xen_gnttab_close (s->gt); + } s->gt =qemu_xen_gnttab_open ();uint32_t xs_gntref =GNTTAB_RESERVED_XENSTORE ; s->granted_xs = qemu_xen_gnttab_map_refs(s->gt, 1, xen_domid, &xs_gntref,
Signature · 1 line
2.43.0
PATCH 12/21 hw/i386/kvm/xen_xenstore: Apply offset before truncation in xs_append_strings()
In reply to David WoodhouseFrom: David Woodhouse <[email protected]>
Truncating a string to the remaining payload space before applying the requested starting offset corrupts the offset accounting, so XS_DIRECTORY_PART returned wrong data for non-zero offsets. Skip to the offset first, then check what fits.
--- hw/i386/kvm/xen_xenstore.c | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-)
hw/i386/kvm/xen_xenstore.c +15 -11
@@ -614,6 +614,21 @@ static void xs_append_strings(XenXenstoreState *s, struct xsd_sockmsg *rsp,size_t len =strlen (l->data) +1 ;/* Including the NUL termination */ char *str = l->data; +/* +* Skip to the requested offset before checking what fits, so that +* truncation does not corrupt the offset accounting. +*/ +if (start) { +if (start >= len) { + start -= len; +continue ; + } + + str += start; + len -= start; + start =0 ; + } +if (rsp->len + len >XENSTORE_PAYLOAD_MAX ) {if (truncate) { len =XENSTORE_PAYLOAD_MAX - rsp->len;
@@ -626,17 +641,6 @@ static void xs_append_strings(XenXenstoreState *s, struct xsd_sockmsg *rsp, } } -if (start) { -if (start >= len) { - start -= len; -continue ; - } - - str += start; - len -= start; - start =0 ; - } -memcpy (&rsp_data[rsp->len], str, len); rsp->len += len; }
Signature · 1 line
2.43.0
PATCH 13/21 hw/char/xen_console: Fix buffer trim when size exceeds twice the limit
In reply to David WoodhouseFrom: David Woodhouse <[email protected]>
In buffer_append() we handle a full buffer by discarding bytes from the *middle*, preserving the oldest and the newest data. When the overflow exceeded the max capacity (a limit set by the guest), the memmove() destination was miscalculated and ended up before the start of the buffer. In that case there is no older data worth preserving anyway; just keep the newest max_capacity bytes.
--- hw/char/xen_console.c | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-)
hw/char/xen_console.c +14 -6
@@ -89,17 +89,25 @@ static bool buffer_append(XenConsole *con)if (buffer->max_capacity && buffer->size > buffer->max_capacity) { -/* Discard the middle of the data. */ - +/* +* Discard the middle of the data: keep the head of the buffer +* up to where the overflowing data will be moved down to end +* at max_capacity, and the newest 'keep' bytes. If the buffer +* has grown to more than twice max_capacity (the frontend may +* set an arbitrarily small 'limit'), there is no head to keep +* and the newest max_capacity bytes alone remain. +*/ size_t over = buffer->size - buffer->max_capacity; -uint8_t *maxpos = buffer->data + buffer->max_capacity; +size_t keep =MIN (over, buffer->max_capacity); -memmove (maxpos - over, maxpos, over); +memmove (buffer->data + buffer->max_capacity - keep, + buffer->data + buffer->size - keep, keep); buffer->data =g_realloc (buffer->data, buffer->max_capacity); buffer->size = buffer->capacity = buffer->max_capacity; -if (buffer->consumed > buffer->max_capacity - over) - buffer->consumed = buffer->max_capacity - over; +if (buffer->consumed > buffer->max_capacity - keep) { + buffer->consumed = buffer->max_capacity - keep; + } }return true; }
Signature · 1 line
2.43.0
PATCH 14/21 hw/9pfs/xen-9p-backend: Use validated snapshot for request iovecs
In reply to David WoodhouseFrom: David Woodhouse <[email protected]>
xen_9pfs_out_sg() re-read the consumer index from the shared ring page when building the request iovecs, so with an index the validation in xen_9pfs_receive() never saw, the iovecs can reach past the end of the ring mapping. Reconstruct the index from the out_cons/out_size snapshot taken at validation time, and split the iovecs purely against the ring size.
--- hw/9pfs/xen-9p-backend.c | 43 ++++++++++++++++++---------------------- 1 file changed, 19 insertions(+), 24 deletions(-)
hw/9pfs/xen-9p-backend.c +19 -24
@@ -105,34 +105,29 @@ static void xen_9pfs_out_sg(Xen9pfsRing *ring, int *num, uint32_t idx) { -RING_IDX cons, prod, masked_prod, masked_cons; - - cons = ring->intf->out_cons; - prod = ring->intf->out_prod; -xen_rmb (); - masked_prod =xen_9pfs_mask (prod,XEN_FLEX_RING_SIZE (ring->ring_order)); - masked_cons =xen_9pfs_mask (cons,XEN_FLEX_RING_SIZE (ring->ring_order)); - -if (masked_cons < masked_prod) { +RING_IDX cons, masked_cons; +RING_IDX ring_size =XEN_FLEX_RING_SIZE (ring->ring_order); + +/* +* Use the consumer index and request size snapshotted when the +* request was validated in xen_9pfs_receive(). Do not re-read the +* index from the shared page: the guest may have changed it since +* validation, and out_size (bounded by the ring size at validation +* time) could then reach past the end of the ring mapping. +*/ + cons = ring->out_cons - ring->out_size; + masked_cons =xen_9pfs_mask (cons, ring_size); + +if (ring->out_size <= ring_size - masked_cons) { out_sg[0 ].iov_base = ring->ring.out + masked_cons; out_sg[0 ].iov_len = ring->out_size; *num =1 ; }else { -if (ring->out_size > - (XEN_FLEX_RING_SIZE (ring->ring_order) - masked_cons)) { - out_sg[0 ].iov_base = ring->ring.out + masked_cons; - out_sg[0 ].iov_len =XEN_FLEX_RING_SIZE (ring->ring_order) - - masked_cons; - out_sg[1 ].iov_base = ring->ring.out; - out_sg[1 ].iov_len = ring->out_size - - (XEN_FLEX_RING_SIZE (ring->ring_order) - - masked_cons); - *num =2 ; - }else { - out_sg[0 ].iov_base = ring->ring.out + masked_cons; - out_sg[0 ].iov_len = ring->out_size; - *num =1 ; - } + out_sg[0 ].iov_base = ring->ring.out + masked_cons; + out_sg[0 ].iov_len = ring_size - masked_cons; + out_sg[1 ].iov_base = ring->ring.out; + out_sg[1 ].iov_len = ring->out_size - (ring_size - masked_cons); + *num =2 ; } }
Signature · 1 line
2.43.0
PATCH 15/21 hw/9pfs/xen-9p-backend: Validate the request header size field
In reply to David WoodhouseFrom: David Woodhouse <[email protected]>
A request whose header declares a size smaller than the header itself was accepted, submitting a zero-length PDU and advancing nothing, to be re-processed on every ring kick. Reject it instead. Set inprogress only once a request is accepted, so returning early on a half-arrived or malformed request no longer wedges the ring until disconnect.
--- hw/9pfs/xen-9p-backend.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-)
hw/9pfs/xen-9p-backend.c +10 -2
@@ -314,7 +314,6 @@ static int xen_9pfs_receive(Xen9pfsRing *ring)if (queued <sizeof (h)) {return 0 ; } - ring->inprogress = true; masked_prod =xen_9pfs_mask (prod,XEN_FLEX_RING_SIZE (ring->ring_order)); masked_cons =xen_9pfs_mask (cons,XEN_FLEX_RING_SIZE (ring->ring_order));
@@ -322,9 +321,18 @@ static int xen_9pfs_receive(Xen9pfsRing *ring)xen_9pfs_read_packet ((uint8_t *) &h, ring->ring.out,sizeof (h), masked_prod, &masked_cons,XEN_FLEX_RING_SIZE (ring->ring_order)); -if (queued <le32_to_cpu (h.size_le)) { +/* +* A size smaller than the header itself is malformed; returning +* with inprogress still clear means it is simply ignored until the +* guest fixes up the ring contents. Do not set inprogress before +* the request is accepted, or a half-arrived request would wedge +* the ring forever. +*/ +if (le32_to_cpu (h.size_le) <sizeof (h) || + queued <le32_to_cpu (h.size_le)) {return 0 ; } + ring->inprogress = true;/* cannot fail, because we only handle one request per ring at a time */ pdu =pdu_alloc (&ring->priv->state);
Signature · 1 line
2.43.0
PATCH 16/21 hw/9pfs/xen-9p-backend: Validate frontend-supplied connect parameters
In reply to David WoodhouseFrom: David Woodhouse <[email protected]>
The ring order is read from the guest-shared interface page into a signed int, so a large value became negative and bypassed the MAX_RING_ORDER check, leading to an undefined shift. Keep it unsigned. Treat any negative return from the event channel bind as failure, not just -1, and fail the connect if the frontend provides no 'tag' key rather than passing NULL into the fsdev layer.
--- hw/9pfs/xen-9p-backend.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-)
hw/9pfs/xen-9p-backend.c +5 -2
@@ -453,7 +453,7 @@ static int xen_9pfs_connect(struct XenLegacyDevice *xendev) xen_9pdev->rings =g_new0 (Xen9pfsRing, xen_9pdev->num_rings);for (i =0 ; i < xen_9pdev->num_rings; i++) {char *str; -int ring_order; +uint32_t ring_order; xen_9pdev->rings[i].priv = xen_9pdev; xen_9pdev->rings[i].evtchn =-1 ;
@@ -515,7 +515,7 @@ static int xen_9pfs_connect(struct XenLegacyDevice *xendev) (xen_9pdev->rings[i].evtchndev, xendev->dom, xen_9pdev->rings[i].evtchn); -if (xen_9pdev->rings[i].local_port ==-1 ) { +if (xen_9pdev->rings[i].local_port <0 ) {xen_pv_printf (xendev,0 ,"xenevtchn_bind_interdomain failed port=%d\n" , xen_9pdev->rings[i].evtchn);
@@ -531,6 +531,9 @@ static int xen_9pfs_connect(struct XenLegacyDevice *xendev) xen_9pdev->id = s->fsconf.fsdev_id =g_strdup_printf ("xen9p%d" , xendev->dev); xen_9pdev->tag = s->fsconf.tag =xenstore_read_fe_str (xendev,"tag" ); +if (!xen_9pdev->tag) { + goto out; + } fsdev =qemu_opts_create (qemu_find_opts ("fsdev" ), s->fsconf.tag,1 ,NULL );
Signature · 1 line
2.43.0
PATCH 17/21 hw/9pfs/xen-9p-backend: Close event channel handle on disconnect
In reply to David WoodhouseFrom: David Woodhouse <[email protected]>
Disconnect only unbound the port, then dropped the pointer, leaking the handle and its file descriptor on every disconnect/reconnect cycle. Close the handle; closing also unbinds.
--- hw/9pfs/xen-9p-backend.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
hw/9pfs/xen-9p-backend.c +1 -2
@@ -392,8 +392,7 @@ static void xen_9pfs_disconnect(struct XenLegacyDevice *xendev)if (xen_9pdev->rings[i].evtchndev !=NULL ) {qemu_set_fd_handler (qemu_xen_evtchn_fd (xen_9pdev->rings[i].evtchndev),NULL ,NULL ,NULL ); -qemu_xen_evtchn_unbind (xen_9pdev->rings[i].evtchndev, - xen_9pdev->rings[i].local_port); +qemu_xen_evtchn_close (xen_9pdev->rings[i].evtchndev); xen_9pdev->rings[i].evtchndev =NULL ; }if (xen_9pdev->rings[i].data !=NULL ) {
Signature · 1 line
2.43.0
PATCH 18/21 hw/net/xen_nic: Bound the TX and RX rings' producer index
In reply to David WoodhouseFrom: David Woodhouse <[email protected]>
net_tx_packets() consumed requests until req_cons caught up with the raw req_prod from the shared ring. A bogus req_prod made the loop process up to 2^32 stale slots while holding the BQL. Check RING_REQUEST_PROD_OVERFLOW on both rings, as xen-block already does.
--- hw/net/xen_nic.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-)
hw/net/xen_nic.c +8 -1
@@ -138,6 +138,12 @@ static bool net_tx_packets(struct XenNetDev *netdev) rp = netdev->tx_ring.sring->req_prod;xen_rmb ();/* Ensure we see queued requests up to 'rp'. */ +if (RING_REQUEST_PROD_OVERFLOW (&netdev->tx_ring, rp)) { +qemu_log_mask (LOG_GUEST_ERROR ,"vif%u: bad req_prod %u\n" , + netdev->dev, rp); +break ; + } +while ((rc != rp)) {if (RING_REQUEST_CONS_OVERFLOW (&netdev->tx_ring, rc)) {break ;
@@ -268,7 +274,8 @@ static ssize_t net_rx_packet(NetClientState *nc, const uint8_t *buf, size_t size rp = netdev->rx_ring.sring->req_prod;xen_rmb ();/* Ensure we see queued requests up to 'rp'. */ -if (rc == rp ||RING_REQUEST_CONS_OVERFLOW (&netdev->rx_ring, rc)) { +if (rc == rp ||RING_REQUEST_PROD_OVERFLOW (&netdev->rx_ring, rp) || +RING_REQUEST_CONS_OVERFLOW (&netdev->rx_ring, rc)) {return 0 ; }if (size >XEN_PAGE_SIZE -NET_IP_ALIGN ) {
Signature · 1 line
2.43.0
PATCH 19/21 hw/xen: Bound the rep count of PIO and MMIO ioreqs
In reply to David WoodhouseFrom: David Woodhouse <[email protected]>
cpu_ioreq_pio() and cpu_ioreq_move() iterated req->count times with no upper bound, so a count of UINT32_MAX kept the vCPU handler thread spinning through four billion iterations. Xen's instruction emulator clips a rep batch to at most 4096 repetitions (hvmemul_virtual_to_linear() and hvmemul_linear_to_phys() both apply that bound before an ioreq is sent), so reject larger counts as malformed, and reject a zero size, as the other framing checks here already do.
--- hw/xen/xen-hvm-common.c | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-)
hw/xen/xen-hvm-common.c +17 -2
@@ -321,10 +321,20 @@ void cpu_ioreq_pio(ioreq_t *req)trace_cpu_ioreq_pio (req, req->dir, req->df, req->data_is_ptr, req->addr, req->data, req->count, req->size); -if (req->size >sizeof (uint32_t )) { +if (req->size ==0 || req->size >sizeof (uint32_t )) {hw_error ("PIO: bad size (%u)" , req->size); } +/* +* Xen's instruction emulator clips a rep batch to at most 4096 +* repetitions (hvmemul_virtual_to_linear(), hvmemul_linear_to_phys()), +* so the count of a well-formed ioreq is bounded. Don't spin for +* 2^32 iterations on a corrupted one. +*/ +if (req->data_is_ptr && req->count >4096 ) { +hw_error ("PIO: bad count (%u)" , req->count); + } +if (req->dir ==IOREQ_READ ) {if (!req->data_is_ptr) { req->data =do_inp (req->addr, req->size);
@@ -361,10 +371,15 @@ static void cpu_ioreq_move(ioreq_t *req)trace_cpu_ioreq_move (req, req->dir, req->df, req->data_is_ptr, req->addr, req->data, req->count, req->size); -if (req->size >sizeof (req->data)) { +if (req->size ==0 || req->size >sizeof (req->data)) {hw_error ("MMIO: bad size (%u)" , req->size); } +/* As for PIO: Xen clips a rep batch to at most 4096 repetitions. */ +if (req->count >4096 ) { +hw_error ("MMIO: bad count (%u)" , req->count); + } +if (!req->data_is_ptr) {if (req->dir ==IOREQ_READ ) {for (i =0 ; i < req->count; i++) {
Signature · 1 line
2.43.0
PATCH 20/21 hw/i386/kvm/xen_evtchn: Hold port_lock for whole of bind_pirq_op
In reply to David WoodhouseFrom: David Woodhouse <[email protected]>
The check for an existing binding read s->pirq[].port before taking port_lock, and the allocation wrote it after. The BQL serialises the writers in practice, but holding port_lock across the check and the allocation is clearly correct and lets Coverity see it too.
The region now under the lock is pure port_table/pirq bookkeeping. The MSI unmask and kvm_update_msi_routes_all() calls must remain outside port_lock: they can re-enter via the MSI translate function, which takes port_lock itself. The PIRQ→evtchn→GSI delivery paths have further BQL/port_lock ordering constraints — see the comments in xen_evtchn_set_callback_level() and xen_evtchn_set_gsi().
Resolves: Coverity CID 1527403
--- hw/i386/kvm/xen_evtchn.c | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-)
hw/i386/kvm/xen_evtchn.c +11 -14
@@ -1289,24 +1289,21 @@ int xen_evtchn_bind_pirq_op(struct evtchn_bind_pirq *pirq)BQL_LOCK_GUARD (); -if (s->pirq[pirq->pirq].port) { -return -EBUSY ; - } + WITH_QEMU_LOCK_GUARD(&s->port_lock) { +if (s->pirq[pirq->pirq].port) { +return -EBUSY ; + } -qemu_mutex_lock (&s->port_lock); + ret =allocate_port (s,0 , EVTCHNSTAT_pirq, pirq->pirq, + &pirq->port); +if (ret) { +return ret; + } - ret =allocate_port (s,0 , EVTCHNSTAT_pirq, pirq->pirq, - &pirq->port); -if (ret) { -qemu_mutex_unlock (&s->port_lock); -return ret; + s->pirq[pirq->pirq].port = pirq->port; +trace_kvm_xen_bind_pirq (pirq->pirq, pirq->port); } - s->pirq[pirq->pirq].port = pirq->port; -trace_kvm_xen_bind_pirq (pirq->pirq, pirq->port); - -qemu_mutex_unlock (&s->port_lock); -/* * Need to do the unmask outside port_lock because it may call * back into the MSI translate function.
Signature · 1 line
2.43.0
PATCH 21/21 hw/i386/kvm/xen_evtchn: Allow unmapping an emulated MSI PIRQ
In reply to David WoodhouseFrom: David Woodhouse <[email protected]>
The "unmap GSI PIRQs only" check rejected every negative gsi, which includes IRQ_MSI_EMU, so the later IRQ_MSI_EMU branch that flushes the KVM MSI routes was unreachable and guests could never unmap an MSI PIRQ. Xen permits it: physdev_unmap_pirq() on a domain with HVM pirqs routes emulated-IRQ pirqs through unmap_domain_pirq_emuirq(), which succeeds for MSI emuirqs. Let IRQ_MSI_EMU through; the existing unreachable branch then does the route flush as originally intended.
Resolves: Coverity CID 1507603
--- hw/i386/kvm/xen_evtchn.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-)
hw/i386/kvm/xen_evtchn.c +5 -3
@@ -1925,13 +1925,15 @@ int xen_physdev_unmap_pirq(struct physdev_unmap_pirq *unmap) gsi = s->pirq[pirq].gsi; -/* We can only unmap GSI PIRQs */ -if (gsi <0 ) { +/* We can only unmap GSI PIRQs and emulated MSIs */ +if (gsi <0 && gsi !=IRQ_MSI_EMU ) {qemu_mutex_unlock (&s->port_lock);return -EINVAL ; } - s->gsi_pirq[gsi] =0 ; +if (gsi >=0 ) { + s->gsi_pirq[gsi] =0 ; + } s->pirq[pirq].gsi =IRQ_UNBOUND ;/* Doesn't actually matter because: */ pirq_inuse_word (s, pirq) &= ~pirq_inuse_bit (pirq);
Signature · 1 line
2.43.0