5.10.275-rc1 review
Subsystems (7)
Greg Kroah-Hartman
maintainerPATCH 223/1848 ipv4: start using dst_dev_rcu()
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Eric Dumazet <[email protected]>
[ Upstream commit 6ad8de3cefdb6ffa6708b21c567df0dbf82c43a8 ]
Change icmpv4_xrlim_allow(), ip_defrag() to prevent possible UAF.
Change ipmr_prepare_xmit(), ipmr_queue_fwd_xmit(), ip_mr_output(), ipv4_neigh_lookup() to use lockdep enabled dst_dev_rcu().
Conflicts:
net/ipv4/icmp.c net/ipv4/ip_fragment.c net/ipv4/ipmr.c net/ipv4/route.c
- Supply dst_dev_rcu() and skb_dst_dev_rcu() in include/net/dst.h; this baseline has neither helper. Use the checked READ_ONCE() definitions present in 5.15.y, without changing struct dst_entry or importing the broader dst->dev_rcu conversion. The patch is self-contained.
- Preserve the four-argument inet_getpeer_v4() and inet_putpeer() calls. Return before taking RCU for ICMP types exempt from rate limiting; release RCU on both the loopback and rate-limited paths.
- Keep ip_frag_queue(qp, skb) and ipq_put(qp). Add RCU protection before selecting the device and release it on both queue lookup outcomes.
- Use dst_dev_rcu() in the older ipmr_queue_xmit() implementation. Add the IPv4 cache-replay RCU wrapper from b07a9b26e2b1 ("ipmr: Always call ip{,6}_mr_forward() from RCU read-side critical section"), which this baseline lacks. RTNL alone does not satisfy the checked accessor.
- Nest ordinary RCU inside the existing RCU-BH section in neighbour lookup. dst_dev_rcu() checks ordinary RCU, while the older neighbour hash walkers still require BH protection via rcu_dereference_bh().
--- include/net/dst.h | 12 ++++++++++++ net/ipv4/icmp.c | 10 +++++++--- net/ipv4/ip_fragment.c | 9 +++++++-- net/ipv4/ipmr.c | 4 +++- net/ipv4/route.c | 5 ++++- 5 files changed, 33 insertions(+), 7 deletions(-)
include/net/dst.h +12 -0
@@ -547,6 +547,18 @@ static inline void skb_dst_update_pmtu_no_confirm(struct sk_buff *skb, u32 mtu) dst->ops->update_pmtu (dst,NULL , skb, mtu, false); } +static inline struct net_device *dst_dev_rcu (const struct dst_entry *dst) +{ +/* In the future, use rcu_dereference(dst->dev) */ +WARN_ON_ONCE (!rcu_read_lock_held ()); +return READ_ONCE (dst->dev); +} + +static inline struct net_device *skb_dst_dev_rcu (const struct sk_buff *skb) +{ +return dst_dev_rcu (skb_dst (skb)); +} +struct dst_entry *dst_blackhole_check (struct dst_entry *dst,u32 cookie);void dst_blackhole_update_pmtu (struct dst_entry *dst,struct sock *sk,struct sk_buff *skb,u32 mtu,bool confirm_neigh);
net/ipv4/icmp.c +7 -3
@@ -315,24 +315,28 @@ static bool icmpv4_xrlim_allow(struct net *net, struct rtable *rt, struct flowi4 *fl4, int type, int code) { struct dst_entry *dst = &rt->dst; +struct net_device *dev;struct inet_peer *peer;bool rc = true;int vif;if (icmpv4_mask_allow (net, type, code)) - goto out; +return true;/* No rate limit on loopback */ -if (dst->dev && (dst->dev->flags&IFF_LOOPBACK )) +rcu_read_lock (); + dev =dst_dev_rcu (dst); +if (dev && (dev->flags &IFF_LOOPBACK )) goto out; - vif =l3mdev_master_ifindex (dst->dev); + vif =l3mdev_master_ifindex_rcu (dev); peer =inet_getpeer_v4 (net->ipv4.peers, fl4->daddr, vif,1 ); rc =inet_peer_xrlim_allow (peer,READ_ONCE (net->ipv4.sysctl_icmp_ratelimit));if (peer)inet_putpeer (peer); out: +rcu_read_unlock ();return rc; }
net/ipv4/ip_fragment.c +7 -2
@@ -475,13 +475,16 @@ static int ip_frag_reasm(struct ipq *qp, struct sk_buff *skb,/* Process an incoming IP datagram fragment. */ int ip_defrag (struct net *net,struct sk_buff *skb,u32 user) { -struct net_device *dev = skb->dev ? :skb_dst (skb)->dev; -int vif =l3mdev_master_ifindex_rcu (dev); +struct net_device *dev;struct ipq *qp; +int vif;__IP_INC_STATS (net,IPSTATS_MIB_REASMREQDS );/* Lookup (or create) queue header */ +rcu_read_lock (); + dev = skb->dev ? :skb_dst_dev_rcu (skb); + vif =l3mdev_master_ifindex_rcu (dev); qp =ip_find (net,ip_hdr (skb), user, vif);if (qp) {int ret;
@@ -491,9 +494,11 @@ int ip_defrag(struct net *net, struct sk_buff *skb, u32 user) ret =ip_frag_queue (qp, skb);spin_unlock (&qp->q.lock); +rcu_read_unlock ();ipq_put (qp);return ret; } +rcu_read_unlock ();__IP_INC_STATS (net,IPSTATS_MIB_REASMFAILS );kfree_skb (skb);
net/ipv4/ipmr.c +3 -1
@@ -1012,7 +1012,9 @@ static void ipmr_cache_resolve(struct net *net, struct mr_table *mrt,rtnl_unicast (skb, net,NETLINK_CB (skb).portid); }else { +rcu_read_lock ();ip_mr_forward (net, mrt, skb->dev, skb, c,0 ); +rcu_read_unlock (); } } }
@@ -1870,7 +1872,7 @@ static void ipmr_queue_xmit(struct net *net, struct mr_table *mrt, goto out_free; } - dev = rt->dst.dev; + dev =dst_dev_rcu (&rt->dst);if (skb->len+encap >dst_mtu (&rt->dst) && (ntohs (iph->frag_off) &IP_DF )) {/* Do not fragment multicasts. Alas, IPv4 does not
net/ipv4/route.c +4 -1
@@ -446,10 +446,12 @@ static struct neighbour *ipv4_neigh_lookup(const struct dst_entry *dst, const void *daddr) { const struct rtable *rt = container_of(dst, struct rtable, dst); -struct net_device *dev = dst->dev; +struct net_device *dev;struct neighbour *n;rcu_read_lock_bh (); +rcu_read_lock (); + dev =dst_dev_rcu (dst);if (likely (rt->rt_gw_family ==AF_INET )) { n =ip_neigh_gw4 (dev, rt->rt_gw4);
@@ -465,6 +467,7 @@ static struct neighbour *ipv4_neigh_lookup(const struct dst_entry *dst,if (!IS_ERR (n) && !refcount_inc_not_zero (&n->refcnt)) n =NULL ; +rcu_read_unlock ();rcu_read_unlock_bh ();return n;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 224/1848 netfilter: nf_tables: fix use-after-free in nf_tables_addchain()
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Inseo An <[email protected]>
[ Upstream commit 71e99ee20fc3f662555118cf1159443250647533 ]
nf_tables_addchain() publishes the chain to table->chains via list_add_tail_rcu() (in nft_chain_add()) before registering hooks. If nf_tables_register_hook() then fails, the error path calls nft_chain_del() (list_del_rcu()) followed by nf_tables_chain_destroy() with no RCU grace period in between.
This creates two use-after-free conditions:
1) Control-plane: nf_tables_dump_chains() traverses table->chains under rcu_read_lock(). A concurrent dump can still be walking the chain when the error path frees it.
2) Packet path: for NFPROTO_INET, nf_register_net_hook() briefly installs the IPv4 hook before IPv6 registration fails. Packets entering nft_do_chain() via the transient IPv4 hook can still be dereferencing chain->blob_gen_X when the error path frees the chain.
Add synchronize_rcu() between nft_chain_del() and the chain destroy so that all RCU readers -- both dump threads and in-flight packet evaluation -- have finished before the chain is freed.
(cherry picked from commit 71e99ee20fc3f662555118cf1159443250647533)
Conflicts:
- Only race 2 can be observed in this codebase.
--- net/netfilter/nf_tables_api.c | 1 + 1 file changed, 1 insertion(+)
net/netfilter/nf_tables_api.c +1 -0
@@ -2372,6 +2372,7 @@ static int nf_tables_addchain(struct nft_ctx *ctx, u8 family, u8 genmask, err_use:nf_tables_unregister_hook (net, table, chain); err_destroy_chain: +synchronize_rcu ();nf_tables_chain_destroy (chain);return err;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 225/1848 KVM: nVMX: Put vmcs12 pages if nested VM-Enter fails due to invalid guest state
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
[ Upstream commit 2f2312c422fd2695da772cecb30c69994b795964 ]
Put all vmcs12 pages if KVM synthesizes a nested VM-Exit due to invalid guest while emulating VMLAUNCH or VMRESUME. The invalid guest state path doesn't use nested_vmx_vmexit() as that API is intended to be used if and only if L2 is active, and the open coded equivalent neglects to put the vmcs12 pages. Failure to put the vmcs12 pages leaks any pinned pages (and/or mappings) if L1 retries VMLAUNCH/VMRESUME.
Note, the !from_vmenter scenario doesn't suffer the same problem, as vmx_get_nested_state_pages() only gets/pins/maps the vmcs12 pages if L2 is active, i.e. if a "full" VM-Exit is guaranteed before KVM will retry getting vmcs12 pages.
--- arch/x86/kvm/vmx/nested.c | 8 ++++++++ 1 file changed, 8 insertions(+)
arch/x86/kvm/vmx/nested.c +8 -0
@@ -3514,6 +3514,14 @@ enum nvmx_vmentry_status nested_vmx_enter_non_root_mode(struct kvm_vcpu *vcpu,return NVMX_VMENTRY_VMEXIT ; } +if (vmx->nested.apic_access_page) { +kvm_release_page_clean (vmx->nested.apic_access_page); + vmx->nested.apic_access_page =NULL ; + } +kvm_vcpu_unmap (vcpu, &vmx->nested.virtual_apic_map, true); +kvm_vcpu_unmap (vcpu, &vmx->nested.pi_desc_map, true); + vmx->nested.pi_desc =NULL ; +load_vmcs12_host_state (vcpu, vmcs12); vmcs12->vm_exit_reason = exit_reason.full;if (enable_shadow_vmcs || vmx->nested.hv_evmcs)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 226/1848 sctp: auth: discard auth_chunk when skb_clone fails
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Qing Luo <[email protected]>
[ Upstream commit 9ae7ed101cf28613071ebfbc42668c8917a670cf ]
When processing AUTH + COOKIE-ECHO packets, if skb_clone() fails due to memory pressure, chunk->auth_chunk is NULL. The original code still sets chunk->auth = 1 and continues, leaving the COOKIE-ECHO to be processed without a valid auth_chunk for deferred verification.
Discard the AUTH chunk early via pdiscard when skb_clone() fails, so that the receive loop can continue processing remaining chunks in the inqueue instead of stalling the entire packet.
--- net/sctp/associola.c | 4 ++++ net/sctp/endpointola.c | 4 ++++ 2 files changed, 8 insertions(+)
net/sctp/associola.c +4 -0
@@ -1019,6 +1019,10 @@ static void sctp_assoc_bh_rcv(struct work_struct *work)if (next_hdr->type ==SCTP_CID_COOKIE_ECHO ) { chunk->auth_chunk =skb_clone (chunk->skb,GFP_ATOMIC ); +if (!chunk->auth_chunk) { + chunk->pdiscard =1 ; +continue ; + } chunk->auth =1 ;continue ; }
net/sctp/endpointola.c +4 -0
@@ -362,6 +362,10 @@ static void sctp_endpoint_bh_rcv(struct work_struct *work)if (next_hdr->type ==SCTP_CID_COOKIE_ECHO ) { chunk->auth_chunk =skb_clone (chunk->skb,GFP_ATOMIC ); +if (!chunk->auth_chunk) { + chunk->pdiscard =1 ; +continue ; + } chunk->auth =1 ;continue ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 227/1848 net/sched: sch_netem: fix out-of-bounds access in packet corruption
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yucheng Lu <[email protected]>
[ Upstream commit d64cb81dcbd54927515a7f65e5e24affdc73c14b ]
In netem_enqueue(), the packet corruption logic uses get_random_u32_below(skb_headlen(skb)) to select an index for modifying skb->data. When an AF_PACKET TX_RING sends fully non-linear packets over an IPIP tunnel, skb_headlen(skb) evaluates to 0.
Passing 0 to get_random_u32_below() takes the variable-ceil slow path which returns an unconstrained 32-bit random integer. Using this unconstrained value as an offset into skb->data results in an out-of-bounds memory access.
Fix this by verifying skb_headlen(skb) is non-zero before attempting to corrupt the linear data area. Fully non-linear packets will silently bypass the corruption logic.
Conflicts:
net/sched/sch_netem.c
--- net/sched/sch_netem.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
net/sched/sch_netem.c +3 -2
@@ -508,8 +508,9 @@ static int netem_enqueue(struct sk_buff *skb, struct Qdisc *sch, goto finish_segs; } - skb->data[prandom_u32 () %skb_headlen (skb)] ^= -1 <<(prandom_u32 () %8 ); +if (skb_headlen (skb)) + skb->data[prandom_u32 () %skb_headlen (skb)] ^= +1 << (prandom_u32 () %8 ); }if (unlikely (sch->q.qlen >= sch->limit)) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 228/1848 bpf: Fix UAF in sock clone early bailouts
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Matt Bobrowski <[email protected]>
[ Upstream commit 7cbd0c4cebe4c9f678d15e6b9ba975e1155a107f ]
Similar to recent commit 9b51a6155d14 ("bpf,fork: wipe ->bpf_storage before bailouts that access it"), sk_clone() performs an initial shallow copy of the socket field ->sk_bpf_storage via sock_copy() for the cloned socket newsk.
If sk_clone() bails out early (e.g. if sk_filter_charge() fails) prior to calling bpf_sk_storage_clone(), newsk->sk_bpf_storage still points to the parent socket's BPF local storage. When newsk is subsequently freed via sk_free(), the deallocation path (__sk_destruct() -> bpf_sk_storage_free()) destroys the parent socket's BPF local storage, leading to a use-after-free (UAF) on the parent socket.
Fix this by resetting newsk->sk_bpf_storage to NULL immediately after sock_copy() in sk_clone(), and remove the now redundant initialization from bpf_sk_storage_clone().
[ Imran: Backport to linux-5.10.y, linux-5.15.y, linux-6.1.y,
linux-6.6.y and linux-6.12.y. The same patch applies to all five branches. Conflict and context differences:
- net/core/bpf_sk_storage.c: upstream commit 0db4941d9dae ("bpf: Use rcu_read_lock_dont_migrate in bpf_sk_storage.c"), got merged in v6.19-rc1, and is not present in these branches. So the line following RCU_INIT_POINTER() in bpf_sk_storage_clone() still uses the old RCU api (rcu_read_lock()).
- net/core/sock.c: upstream commit 151b98d10ef7 ("net: Add sk_clone()."), merged in v6.19-rc1, moved the body of sk_clone_lock() into the new sk_clone(). That commit is not present in these branches, and the code relevant to this backport is still in sk_clone_lock().
In all five branches, sk_clone_lock() is the only caller of bpf_sk_storage_clone(), so taking the NULL initialisation out of that function is safe. ]
--- net/core/bpf_sk_storage.c | 2 -- net/core/sock.c | 3 +++ 2 files changed, 3 insertions(+), 2 deletions(-)
net/core/bpf_sk_storage.c +0 -2
@@ -190,8 +190,6 @@ int bpf_sk_storage_clone(const struct sock *sk, struct sock *newsk)struct bpf_local_storage_elem *selem;int ret =0 ; -RCU_INIT_POINTER (newsk->sk_bpf_storage,NULL ); -rcu_read_lock (); sk_storage =rcu_dereference (sk->sk_bpf_storage);
net/core/sock.c +3 -0
@@ -1914,6 +1914,9 @@ struct sock *sk_clone_lock(const struct sock *sk, const gfp_t priority)sock_copy (newsk, sk); newsk->sk_prot_creator = prot; +#ifdef CONFIG_BPF_SYSCALL +RCU_INIT_POINTER (newsk->sk_bpf_storage,NULL ); +#endif /* SANITY */ if (likely (newsk->sk_net_refcnt)) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 229/1848 net: sched: avoid qdisc_reset_all_tx_gt() vs dequeue race for lockless qdiscs
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Koichiro Den <[email protected]>
[ Upstream commit 7f083faf59d14c04e01ec05a7507f036c965acf8 ]
When shrinking the number of real tx queues, netif_set_real_num_tx_queues() calls qdisc_reset_all_tx_gt() to flush qdiscs for queues which will no longer be used.
qdisc_reset_all_tx_gt() currently serializes qdisc_reset() with qdisc_lock(). However, for lockless qdiscs, the dequeue path is serialized by qdisc_run_begin/end() using qdisc->seqlock instead, so qdisc_reset() can run concurrently with __qdisc_run() and free skbs while they are still being dequeued, leading to UAF.
Serialize qdisc_reset_all_tx_gt() against the lockless dequeue path by taking qdisc->seqlock for TCQ_F_NOLOCK qdiscs, matching the serialization model already used by dev_reset_queue().
Additionally clear QDISC_STATE_NON_EMPTY after reset so the qdisc state reflects an empty queue, avoiding needless re-scheduling.
Conflicts:
- include/net/sch_generic.h: retain the older qdisc state model. It has no __QDISC_STATE_DRAINING or QDISC_STATE_NON_EMPTY, so serialize reset with seqlock and clear __QDISC_STATE_MISSED, matching dev_reset_queue().
--- include/net/sch_generic.h | 9 +++++++++ 1 file changed, 9 insertions(+)
include/net/sch_generic.h +9 -0
@@ -745,13 +745,22 @@ static inline bool skb_skip_tc_classify(static inline void qdisc_reset_all_tx_gt (struct net_device *dev,unsigned int i) {struct Qdisc *qdisc; +bool nolock;for (; i < dev->num_tx_queues; i++) { qdisc =rtnl_dereference (netdev_get_tx_queue (dev, i)->qdisc);if (qdisc) { + nolock = qdisc->flags &TCQ_F_NOLOCK ; + +if (nolock) +spin_lock_bh (&qdisc->seqlock);spin_lock_bh (qdisc_lock (qdisc));qdisc_reset (qdisc);spin_unlock_bh (qdisc_lock (qdisc)); +if (nolock) { +clear_bit (__QDISC_STATE_MISSED, &qdisc->state); +spin_unlock_bh (&qdisc->seqlock); + } } } }
Greg Kroah-Hartman
maintainerPATCH 230/1848 net/sched: act_ife: do not consume the inner header on egress
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jamal Hadi Salim <[email protected]>
commit 498c631f9c6d74aad4bf43039fa3ce70ae9a8bb7 upstream.
The issue:tcf_ife_decode() unconditionally calls eth_type_trans(), which pulls ETH_HLEN. On egress this consumes the inner Ethernet header, and the device receives an skb whose data points to the L3 header:
- loopback_xmit() parses L3 data as Ethernet: the "ethertype" comes from the inner IPv4 source address, and the decapsulated packet is dropped or misparsed.
- a real NIC transmits the frame without its Ethernet header.
(The __skb_pull() BUG this used to trigger in loopback_xmit() when the remaining linear area was short is handled by "loopback: use eth_type_trans_careful()".)
The Fix:
Parse the inner Ethernet header with eth_type_trans() in both directions, then restore the egress data position and MAC length. On ingress the existing behavior is unchanged. On egress, push the inner Ethernet header back after parsing so the xmit path sees the original frame and later actions see a consistent network header.
Conditions to recreate the bug:
- egress tc filter on lo: action ife decode pipe;
- AF_PACKET SOCK_RAW frame: outer Ethernet with ETH_P_IFE, IFE metadata, inner Ethernet + a valid IPv4 ICMP echo request to a local address;
- before this patch, no echo is received; after it, the echo is delivered and answered.
--- net/sched/act_ife.c | 4 ++++ 1 file changed, 4 insertions(+)
net/sched/act_ife.c +4 -0
@@ -761,6 +761,10 @@ static int tcf_ife_decode(struct sk_buff skb->protocol =eth_type_trans (skb, skb->dev);skb_reset_network_header (skb); +if (!skb_at_tc_ingress (skb)) { +skb_push (skb,ETH_HLEN ); +skb_reset_mac_len (skb); + }return action; }
Greg Kroah-Hartman
maintainerPATCH 231/1848 Drivers: hv: vmbus: Bounds check the shared ring buffer indices
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kameron Carr <[email protected]>
commit 1d287c17cc5bfd6386fe0770999be410b248d021 upstream.
In a CoCo VM the host is untrusted. Since the VMBus ring buffer read and write indices live in shared memory, the guest has to treat both as potentially malicious.
hv_ringbuffer_write() copies into the ring at write_index with no bounds checking, so the host can make the guest write packet data at any offset up to 4 GiB past the start of the ring buffer. read_index matters too:
the available space derived from both indices is the only bound on how much is copied, and an out-of-range index can make it far larger than the ring.
The fix is to validate both indices before use and to use the validated snapshot instead of re-accessing. For invalid indices, hv_ringbuffer_write() logs and returns -EIO.
One re-read of write_index is left unchecked in this patch:hv_get_ring_bufferindices() fetches it again for the prev_indices trailer. The value is only returned to the host and is not used as an offset or length for indexing. Since this is not a security issue, it is addressed later in the series.
Open-coding the bytes available arithmetic keeps the fix free of prerequisites; a later patch refactors it into a helper function.
--- drivers/hv/ring_buffer.c | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-)
drivers/hv/ring_buffer.c +16 -13
@@ -67,15 +67,6 @@ static void hv_signal_on_write(u32 old_w } } -/* Get the next write location for the specified ring buffer. */ -static inline u32 -hv_get_next_write_location (struct hv_ring_buffer_info *ring_info) -{ -u32 next = ring_info->ring_buffer->write_index; - -return next; -} -/* Set the next write location for the specified ring buffer. */ static inline void hv_set_next_write_location(struct hv_ring_buffer_info *ring_info,
@@ -269,6 +260,7 @@ int hv_ringbuffer_write(struct vmbus_chau32 totalbytes_towrite =sizeof (u64);u32 next_write_location;u32 old_write; +u32 read_index;u64 prev_indices;unsigned long flags;struct hv_ring_buffer_info *outring_info = &channel->outbound;
@@ -283,7 +275,20 @@ int hv_ringbuffer_write(struct vmbus_chaspin_lock_irqsave (&outring_info->ring_lock, flags); - bytes_avail_towrite =hv_get_bytes_to_write (outring_info); + read_index =READ_ONCE (outring_info->ring_buffer->read_index); + old_write =READ_ONCE (outring_info->ring_buffer->write_index); +if (unlikely (read_index >= outring_info->ring_datasize || + old_write >= outring_info->ring_datasize)) { +spin_unlock_irqrestore (&outring_info->ring_lock, flags); +pr_err_ratelimited ("outbound ring indices out of range: relid %u read %u write %u size %u\n" , + channel->offermsg.child_relid, read_index, + old_write, outring_info->ring_datasize); +return -EIO ; + } + + bytes_avail_towrite = old_write >= read_index ? + outring_info->ring_datasize - (old_write - read_index) : + read_index - old_write;/* * If there is only room for the packet, assume it is full.
@@ -305,9 +310,7 @@ int hv_ringbuffer_write(struct vmbus_cha channel->out_full_flag = false;/* Write to the ring buffer */ - next_write_location =hv_get_next_write_location (outring_info); - - old_write = next_write_location; + next_write_location = old_write;for (i =0 ; i < kv_count; i++) { next_write_location = hv_copyto_ringbuffer(outring_info,
Greg Kroah-Hartman
maintainerPATCH 232/1848 backlight: qcom-wled: Fix NULL pointer dereference in wled_remove()
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Heidelberg <[email protected]>
commit 1dbd46d4b2fb416a8202b1a8e4ef9d0cadbe075f upstream.
wled_probe() doesn't set the driver data for the platform device. As a result, platform_get_drvdata() in wled_remove() will return NULL, and the first dereference of it crashes on unbind.
Set the platform device driver data in wled_probe().
--- drivers/video/backlight/qcom-wled.c | 1 + 1 file changed, 1 insertion(+)
drivers/video/backlight/qcom-wled.c +1 -0
@@ -1642,6 +1642,7 @@ static int wled_probe(struct platform_de wled->regmap = regmap; wled->dev = &pdev->dev; +platform_set_drvdata (pdev, wled); wled->version = (uintptr_t )of_device_get_match_data (&pdev->dev);if (!wled->version) {
Greg Kroah-Hartman
maintainerPATCH 233/1848 backlight: qcom-wled: Fix unbalanced OVP IRQ enable at probe
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Heidelberg <[email protected]>
commit 5eda6b51461932f9fd835ef9e4574650c69c4fe8 upstream.
wled_configure_ovp_irq() derives the initial state of the OVP interrupt from the hardware:
/* Keep OVP irq disabled until module is enabled */
if (!(val & WLED3_CTRL_REG_MOD_EN_MASK))
disable_irq(wled->ovp_irq);but wled->brightness, which is what the rest of the driver uses to tell whether the module is on, is left at zero.
On boards where the bootloader hands the kernel a lit backlight the two disagree. MOD_EN is already set, so the interrupt is left enabled, while wled_update_status() still believes the backlight is off and takes
if (!!brightness != !!wled->brightness)
rc = wled_module_enable(wled, !!brightness);on the first backlight update. wled_module_enable() then schedules wled_ovp_work(), which calls enable_irq() on the already enabled interrupt:
Unbalanced enable for IRQ 176
WARNING: CPU: 0 PID: 160 at kernel/irq/manage.c:774 __enable_irq+0x50/0x80 Hardware name: Xiaomi Pocophone F1 (DT) Workqueue: events wled_ovp_work Call trace: __enable_irq+0x50/0x80 enable_irq+0x48/0xa0 wled_ovp_work+0x18/0x24 process_one_work+0x1d0/0x350 worker_thread+0x13c/0x460 kthread+0x110/0x114 ret_from_fork+0x10/0x20
The bootloader is not the only way to get there. The readback runs after wledN_setup(), and wled4_setup() sets MOD_EN itself on the path where the sink configuration does not already match, as does the tail of wled_auto_string_detection(), which all three setup paths can reach through wled_auto_detection_at_init(). A cold-booted board with a dark panel can therefore reach the same disagreement.
Move the MOD_EN readback into wled_probe() and use it to seed wled->brightness, so the driver starts out agreeing with the hardware, and key the OVP interrupt off wled->brightness instead. The first backlight update then only reprograms the brightness registers and leaves both the module and the interrupt alone. The OVP interrupt also stays armed from probe whenever the module is already enabled, rather than being disabled at probe and only enabled once something writes brightness.
Note that a backlight update requesting brightness 0 before any non-zero one now really does turn the module off wherever MOD_EN was already set, where before it was silently ignored.
wled->brightness is seeded with default-brightness rather than the level the bootloader actually programmed, so the first update can still step the brightness. Reading that level back is version specific and is done in a follow-up, to keep this fix small enough to backport.
--- drivers/video/backlight/qcom-wled.c | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-)
drivers/video/backlight/qcom-wled.c +21 -11
@@ -1587,7 +1587,6 @@ static int wled_configure_ovp_irq(struct struct platform_device *pdev) {int rc; -u32 val; wled->ovp_irq =platform_get_irq_byname (pdev,"ovp" );if (wled->ovp_irq <0 ) {
@@ -1605,13 +1604,8 @@ static int wled_configure_ovp_irq(structreturn 0 ; } - rc =regmap_read (wled->regmap, wled->ctrl_addr + -WLED3_CTRL_REG_MOD_EN , &val); -if (rc <0 ) -return rc; - -/* Keep OVP irq disabled until module is enabled */ -if (!(val &WLED3_CTRL_REG_MOD_EN_MASK )) +/* Keep the OVP irq disabled until the module is enabled */ +if (!wled->brightness)disable_irq (wled->ovp_irq);return 0 ;
@@ -1627,6 +1621,7 @@ static int wled_probe(struct platform_destruct backlight_device *bl;struct wled *wled;struct regmap *regmap; +u32 mod_en;u32 val;int rc;
@@ -1697,6 +1692,24 @@ static int wled_probe(struct platform_deINIT_DELAYED_WORK (&wled->ovp_work, wled_ovp_work); + val =WLED_DEFAULT_BRIGHTNESS ; +of_property_read_u32 (pdev->dev.of_node,"default-brightness" , &val); + +/* +* The module may already be enabled, either by a bootloader that left +* the backlight lit or by the setup above. Record that, so that the +* first brightness update does not enable an already enabled module, +* and so that the OVP irq is armed from probe rather than from that +* first update. +*/ + rc =regmap_read (wled->regmap, wled->ctrl_addr +WLED3_CTRL_REG_MOD_EN , + &mod_en); +if (rc <0 ) +return rc; + +if (mod_en &WLED3_CTRL_REG_MOD_EN_MASK ) + wled->brightness = val; + rc =wled_configure_short_irq (wled, pdev);if (rc <0 )return rc;
@@ -1705,9 +1718,6 @@ static int wled_probe(struct platform_deif (rc <0 )return rc; - val =WLED_DEFAULT_BRIGHTNESS ; -of_property_read_u32 (pdev->dev.of_node,"default-brightness" , &val); -memset (&props,0 ,sizeof (struct backlight_properties )); props.type =BACKLIGHT_RAW ; props.brightness = val;
Greg Kroah-Hartman
maintainerPATCH 234/1848 backlight: qcom-wled: Fix WLED3 brightness register stride
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Heidelberg <[email protected]>
commit e60dc9c05e0f415ef8bc63b3179abdd49830a619 upstream.
WLED3 has a 16-bit brightness register pair per string, at 0x40 + 2*n, which is what the pm8941-wled driver wrote to:
rc = regmap_bulk_write(wled->regmap, wled->addr + WLED3_CTRL_REG_VAL_BASE + 2 * i, v, 2);
The restructuring for WLED3 turned that into WLED3_SINK_REG_BRIGHT(n), defined as 0x40 + n, so the two byte writes for consecutive strings
overlap: string 1 overwrites the MSB of string 0 with its own LSB, and with the default three strings only string 1 ends up with the requested value.
Use the 2 byte stride.
--- drivers/video/backlight/qcom-wled.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/video/backlight/qcom-wled.c +1 -1
@@ -59,7 +59,7 @@#define WLED3_SINK_REG_CURR_SINK_SHFT 5/* WLED3 specific per-'string' registers below */ -#define WLED3_SINK_REG_BRIGHT (n) (0x40 + n) +#define WLED3_SINK_REG_BRIGHT (n) (0x40 + (n * 0x2))#define WLED3_SINK_REG_STR_MOD_EN (n) (0x60 + (n * 0x10))#define WLED3_SINK_REG_STR_MOD_MASK BIT(7)
Greg Kroah-Hartman
maintainerPATCH 235/1848 gpio: dwapb: mask/unmask IRQ when disable/enale it
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: xiongxin <[email protected]>
commit 1cc3542c76acb5f59001e3e562eba672f1983355 upstream.
In the hardware implementation of the I2C HID driver based on DesignWare GPIO IRQ chip, when the user continues to use the I2C HID device in the suspend process, the I2C HID interrupt will be masked after the resume process is finished.
This is because the disable_irq()/enable_irq() of the DesignWare GPIO driver does not synchronize the IRQ mask register state. In normal use of the I2C HID procedure, the GPIO IRQ irq_mask()/irq_unmask() functions are called in pairs. In case of an exception, i2c_hid_core_suspend() calls disable_irq() to disable the GPIO IRQ. With low probability, this causes irq_unmask() to not be called, which causes the GPIO IRQ to be masked and not unmasked in enable_irq(), raising an exception.
Add synchronization to the masked register state in the dwapb_irq_enable()/dwapb_irq_disable() function. mask the GPIO IRQ before disabling it. After enabling the GPIO IRQ, unmask the IRQ.
--- drivers/gpio/gpio-dwapb.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
drivers/gpio/gpio-dwapb.c +8 -4
@@ -282,13 +282,15 @@ static void dwapb_irq_enable(struct irq_data *d) {struct gpio_chip *gc =irq_data_get_irq_chip_data (d);struct dwapb_gpio *gpio =to_dwapb_gpio (gc); +irq_hw_number_t hwirq =irqd_to_hwirq (d);unsigned long flags;u32 val;spin_lock_irqsave (&gc->bgpio_lock, flags); - val =dwapb_read (gpio,GPIO_INTEN ); - val |=BIT (irqd_to_hwirq (d)); + val =dwapb_read (gpio,GPIO_INTEN ) |BIT (hwirq);dwapb_write (gpio,GPIO_INTEN , val); + val =dwapb_read (gpio,GPIO_INTMASK ) & ~BIT (hwirq); +dwapb_write (gpio,GPIO_INTMASK , val);spin_unlock_irqrestore (&gc->bgpio_lock, flags); }
@@ -296,12 +298,14 @@ static void dwapb_irq_disable(struct irq_data *d) {struct gpio_chip *gc =irq_data_get_irq_chip_data (d);struct dwapb_gpio *gpio =to_dwapb_gpio (gc); +irq_hw_number_t hwirq =irqd_to_hwirq (d);unsigned long flags;u32 val;spin_lock_irqsave (&gc->bgpio_lock, flags); - val =dwapb_read (gpio,GPIO_INTEN ); - val &= ~BIT (irqd_to_hwirq (d)); + val =dwapb_read (gpio,GPIO_INTMASK ) |BIT (hwirq); +dwapb_write (gpio,GPIO_INTMASK , val); + val =dwapb_read (gpio,GPIO_INTEN ) & ~BIT (hwirq);dwapb_write (gpio,GPIO_INTEN , val);spin_unlock_irqrestore (&gc->bgpio_lock, flags); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 236/1848 x86/ioperm: Prevent NULL dereference on theoretical missing IO bitmap
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Li RongQing <[email protected]>
[ Upstream commit 2d36d3b451a94899db9c965adde15492ffe6027a ]
Outside the IOPL emulation path, the IO bitmap is always expected to be allocated when TIF_IO_BITMAP is set. The paranoid WARN_ON_ONCE() handles the case where the flag and the pointer got out of sync. In this theoretical scenario, which presumes some other bug in the code that triggers the WARN_ON_ONCe(), return early, instead of continuing and dereferencing a NULL pointer.
[ mingo: Clarified the changelog. ]
--- arch/x86/kernel/process.c | 1 + 1 file changed, 1 insertion(+)
arch/x86/kernel/process.c +1 -0
@@ -405,6 +405,7 @@ void native_tss_update_io_bitmap(void)if (WARN_ON_ONCE (!iobm)) {clear_thread_flag (TIF_IO_BITMAP );native_tss_invalidate_io_bitmap (); +return ; }/*
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 237/1848 wifi: b43: fix use-after-free in b43_bcma_remove()
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andreas Wendleder <[email protected]>
commit c6c8bc355657115664131b38c53c5ddf7d93b072 upstream.
b43_one_core_detach() frees the struct b43_wldev it is given the bus device of. b43_bcma_remove() then reads wldev->dev again to free the bus device, which is a read of freed memory.
b43_ssb_remove() does not have the problem: it takes a copy of wldev->dev at the start. Do the same here.
--- drivers/net/wireless/broadcom/b43/main.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/net/wireless/broadcom/b43/main.c +3 -2
@@ -5661,6 +5661,7 @@ static void b43_bcma_remove(struct bcma_ {struct b43_wldev *wldev =bcma_get_drvdata (core);struct b43_wl *wl = wldev->wl; +struct b43_bus_dev *dev = wldev->dev;/* We must cancel any work here before unregistering from ieee80211, * as the ieee80211 unreg will destroy the workqueue. */
@@ -5675,14 +5676,14 @@ static void b43_bcma_remove(struct bcma_ieee80211_unregister_hw (wl->hw); } -b43_one_core_detach (wldev->dev); +b43_one_core_detach (dev);/* Unregister HW RNG driver */ b43_rng_exit (wl);b43_leds_unregister (wl);ieee80211_free_hw (wl->hw); -kfree (wldev->dev); +kfree (dev); }static struct bcma_driver b43_bcma_driver = {
Greg Kroah-Hartman
maintainerPATCH 238/1848 SUNRPC: fix netns use-after-free in write_gssp()
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zijing Yin <[email protected]>
commit e7a8721b7edb54a157623f9e31d71345333b5fb9 upstream.
While fuzzing with a customized syzkaller, I hit a refcount warning in xprt_alloc(), reached from a write to /proc/net/rpc/use-gss-proxy:
refcount_t: addition on 0; use-after-free.
WARNING: lib/refcount.c:25 at refcount_warn_saturate+0xf8/0x120 CPU: 0 PID: 10404 Comm: syz.0.17 Not tainted 7.3.0-rc1-00096-gcfebfd3db73d Call Trace: <TASK> xprt_alloc+0x83f/0x9d0 xs_setup_xprt+0xaf/0x3c0 xs_setup_local+0x47/0x7f0 xprt_create_transport+0x16c/0x730 rpc_create+0x38e/0x7f0 gssp_rpc_create+0xe2/0x180 set_gssp_clnt+0xba/0x1b0 write_gssp+0x200/0x310 proc_reg_write+0x240/0x330 vfs_write+0x2aa/0x1050 ksys_write+0x12a/0x250 do_syscall_64+0x117/0x750 entry_SYSCALL_64_after_hwframe+0x77/0x7f </TASK>
create_use_gss_proxy_proc_entry() stores the struct net pointer as the proc entry's private data without taking a reference on it, and an open file descriptor does not pin the namespace either, as procfs only pins the proc_dir_entry. write_gssp() reads that pointer back with pde_data() and hands it to set_gssp_clnt(), which reaches xprt_init():
xprt->xprt_net = get_net_track(net, &xprt->ns_tracker, GFP_KERNEL);
get_net_track() -> get_net() -> refcount_inc() is unconditional, so rpc_create() assumes its caller holds a reference on args.net. write_gssp() does not.
Dropping the last ns.count reference does not make the file go away. __put_net() only queues cleanup_net() on a workqueue, and the remove_proc_entry() that fences off further writes runs from the rpcsec_gss pernet .exit method, that is, from inside cleanup_net(). A write landing between those two points increments a refcount that is already zero. cleanup_net() does not re-read ns.count, so the namespace is freed anyway and the rpc_xprt -- along with the AF_LOCAL socket opened for it -- is left pointing at freed memory. The resurrected count is visible to the rest of that teardown too: with CONFIG_IPV6_MROUTE the same cleanup_net() worker then trips !mr_can_free_table() in ip6mr_free_table(), which tests check_net() on the namespace it is freeing.
It reduces to opening /proc/net/rpc/use-gss-proxy inside a new network namespace, calling setns() back to the original one to drop the last reference, and then writing "1" to the still-open descriptor.
Take the reference in write_gssp() itself and refuse the write when the namespace is already gone. This is what procfs does for every other /proc/net file: get_proc_net() is maybe_get_net(PDE_NET(PDE(inode))) and seq_open_net() returns -ENXIO when it fails. PDE_NET() cannot be reused here because the parent directory /proc/net/rpc carries no namespace pointer. Adding a .pre_exit to rpcsec_gss_net_ops so the entry is removed earlier would only narrow the window, since pre_exit also runs from cleanup_net().
Live namespaces are unaffected: a write still returns the error from set_gssp_clnt(), a write of "2" still returns -EINVAL, and reads are untouched.
--- net/sunrpc/auth_gss/svcauth_gss.c | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-)
net/sunrpc/auth_gss/svcauth_gss.c +11 -3
@@ -1447,10 +1447,18 @@ static ssize_t write_gssp(struct file *freturn res;if (i !=1 )return -EINVAL ; + +/* +* Neither the proc entry nor an open descriptor pins @net, so it +* might already be dying when rpc_create() takes its reference. +*/ +if (!maybe_get_net (net)) +return -ENXIO ; + res =set_gssp_clnt (net); -if (res) -return res; - res =set_gss_proxy (net,1 ); +if (!res) + res =set_gss_proxy (net,1 ); +put_net (net);if (res)return res;return count;
Greg Kroah-Hartman
maintainerPATCH 239/1848 rapidio: mport_cdev: fix use-after-free in mport_mm_close()
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: James Kim <[email protected]>
commit 0f2cd84858e67cf8e02438bf28243bcdc67aa49a upstream.
A use-after-free vulnerability was identified in mport_mm_close() in drivers/rapidio/devices/rio_mport_cdev.c, identical to the pattern previously addressed in dma_req_free().
This is observable from userspace when an application creates an mmap mapping via the RapidIO character device and subsequently unmaps it (or terminates, triggering exit_mmap()). During munmap, mport_mm_close() is invoked and drops the mapping reference via kref_put().
If kref_put() drops the last reference, mport_release_mapping() is called, which frees the underlying rio_mport_mapping structure. The subsequent mutex_unlock() then dereferences map->md to unlock buf_mutex, leading to a use-after-free:
mport_mm_close()
-> mutex_lock(&map->md->buf_mutex);
...
-> kref_put(&map->ref, mport_release_mapping); /* map is freed */
-> mutex_unlock(&map->md->buf_mutex); /* UAF: map used */Fix this by caching map->md before kref_put() and using the cached pointer for mutex unlocking, ensuring that freed memory is not accessed.
--- drivers/rapidio/devices/rio_mport_cdev.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/rapidio/devices/rio_mport_cdev.c +3 -2
@@ -2185,11 +2185,12 @@ static void mport_mm_open(struct vm_areastatic void mport_mm_close (struct vm_area_struct *vma) {struct rio_mport_mapping *map = vma->vm_private_data; +struct mport_dev *md = map->md;rmcd_debug (MMAP ,"%pad" , &map->phys_addr); -mutex_lock (&map->md->buf_mutex); +mutex_lock (&md->buf_mutex);kref_put (&map->ref, mport_release_mapping); -mutex_unlock (&map->md->buf_mutex); +mutex_unlock (&md->buf_mutex); }static const struct vm_operations_struct vm_ops = {
Greg Kroah-Hartman
maintainerPATCH 240/1848 nvmet-fc: fix use-after-free in nvmet_fc_ls_create_connection()
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yehyeong Lee <[email protected]>
commit 2c29f8c9b9e598c09fa50aa02200136a107f6b3f upstream.
nvmet_fc_ls_create_connection() looks up the association with nvmet_fc_find_target_assoc(), which returns it with a reference held, and drops that reference as soon as the target queue has been allocated. iod->assoc is then dereferenced again by nvmet_fc_makeconnid() while building the connection id.
The queue only borrows the pointer and takes no reference of its own. Once the lookup reference is dropped the association is kept alive solely by the reference taken when it was created, so a disconnect LS or a remote port unregister running concurrently can free it before nvmet_fc_makeconnid() reads it:
BUG: KASAN: slab-use-after-free in nvmet_fc_handle_ls_rqst_work (drivers/nvme/target/fc.c:193 drivers/nvme/target/fc.c:1841 drivers/nvme/target/fc.c:1995 drivers/nvme/target/fc.c:2021) Read of size 8 at addr ffff888179f1b000 by task kworker/u9:2/1167 Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014 Workqueue: nvmet-wq nvmet_fc_handle_ls_rqst_work Call Trace: <TASK> dump_stack_lvl (lib/dump_stack.c:94 lib/dump_stack.c:120) print_report (mm/kasan/report.c:378 mm/kasan/report.c:482) kasan_report (mm/kasan/report.c:595) nvmet_fc_handle_ls_rqst_work (drivers/nvme/target/fc.c:193 drivers/nvme/target/fc.c:1841 drivers/nvme/target/fc.c:1995 drivers/nvme/target/fc.c:2021) process_scheduled_works (kernel/workqueue.c:3322 kernel/workqueue.c:3405) worker_thread (kernel/workqueue.c:3486) kthread (kernel/kthread.c:436) ret_from_fork (archkernel/process.c:158) ret_from_fork_asm (arch/x86/entry/entry_64.S:245) </TASK> Freed by task 1167 on cpu 0 at 405.998150s: kasan_save_track (mm/kasan/common.c:57 mm/kasan/common.c:78) kasan_save_free_info (mm/kasan/generic.c:584) __kasan_slab_free (mm/kasan/common.c:253 mm/kasan/common.c:285) kfree (include/linux/kasan.h:235 mm/slub.c:2705 mm/slub.c:6405 mm/slub.c:6720) nvmet_fc_handle_ls_rqst_work (drivers/nvme/target/fc.c:1808 drivers/nvme/target/fc.c:1995 drivers/nvme/target/fc.c:2021) process_scheduled_works (kernel/workqueue.c:3322 kernel/workqueue.c:3405) worker_thread (kernel/workqueue.c:3486) kthread (kernel/kthread.c:436) ret_from_fork (archkernel/process.c:158) ret_from_fork_asm (arch/x86/entry/entry_64.S:245) The buggy address belongs to the object at ffff888179f1b000 which belongs to the cache kmalloc-2k of size 2048
The buggy address is located 0 bytes inside of
freed 2048-byte region [ffff888179f1b000, ffff888179f1b800)
Hold the lookup reference until the response has been built, and drop it on the error path as well.
--- drivers/nvme/target/fc.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-)
drivers/nvme/target/fc.c +5 -3
@@ -1759,9 +1759,6 @@ nvmet_fc_ls_create_connection(struct nvm be16_to_cpu(rqst->connect_cmd.sqsize));if (!queue) ret =VERR_QUEUE_ALLOC_FAIL ; - -/* release get taken in nvmet_fc_find_target_assoc */ -nvmet_fc_tgt_a_put (iod->assoc); } }
@@ -1775,6 +1772,8 @@ nvmet_fc_ls_create_connection(struct nvm FCNVME_RJT_RC_INV_ASSOC :FCNVME_RJT_RC_LOGIC , FCNVME_RJT_EXP_NONE, 0); +if (iod->assoc) +nvmet_fc_tgt_a_put (iod->assoc);return ; }
@@ -1796,6 +1795,9 @@ nvmet_fc_ls_create_connection(struct nvm acc->connectid.connection_id =cpu_to_be64 (nvmet_fc_makeconnid (iod->assoc,be16_to_cpu (rqst->connect_cmd.qid))); + +/* release get taken in nvmet_fc_find_target_assoc */ +nvmet_fc_tgt_a_put (iod->assoc); }/*
Greg Kroah-Hartman
maintainerPATCH 241/1848 lockd: Fix use-after-free in nlmsvc_retry_blocked
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit f5b7634f0f213299a07b461fb10385c8639a4ab8 upstream.
nlmsvc_retry_blocked() examines the block at the head of nlm_blocked under nlm_blocked_lock, then releases the lock before calling nlmsvc_grant_blocked() or retry_deferred_block(). The nlm_blocked list reference is all that keeps the block alive across that window. nlmsvc_grant_blocked() does take one of its own, but not until after the lock has been dropped. Unmounting the nfsd filesystem while a lock request is still blocked reaches nlmsvc_traverse_blocks(), which drops the list reference and frees the block along with the nlm_rqst hanging off it.
BUG: KASAN: slab-use-after-free in nlm_async_call+0xd6/0x230
Read of size 8 at addr ffff88811b04c808 by task lockd/8377
nlm_async_call+0xd6/0x230
nlmsvc_retry_blocked+0x61c/0x800
lockd+0x144/0x1c0
Freed by task 8392:
nlmsvc_release_block+0x231/0x290
nlmsvc_traverse_blocks+0x139/0x1b0
nlm_traverse_files+0x1aa/0xa00
nlmsvc_free_host_resources+0x12/0x60
nlm_shutdown_hosts_net+0x127/0x280
lockd_down+0xd5/0x1c0Take a reference before releasing nlm_blocked_lock and drop it once the retry has run.
--- fs/lockd/svclock.c | 2 ++ 1 file changed, 2 insertions(+)
fs/lockd/svclock.c +2 -0
@@ -1014,6 +1014,7 @@ nlmsvc_retry_blocked(void) timeout = block->b_when - jiffies;break ; } +kref_get (&block->b_count);spin_unlock (&nlm_blocked_lock); dprintk("nlmsvc_retry_blocked(%p, when=%ld)\n",
@@ -1024,6 +1025,7 @@ nlmsvc_retry_blocked(void)retry_deferred_block (block); }else nlmsvc_grant_blocked (block); +nlmsvc_release_block (block);spin_lock (&nlm_blocked_lock); }spin_unlock (&nlm_blocked_lock);
Greg Kroah-Hartman
maintainerPATCH 242/1848 media: cx23885: Fix use-after-free in cx23885_finidev due to race condition
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pei Xiao <[email protected]>
commit 75016a992d9b03f5cc6df1414d1da35840d4feeb upstream.
In cx23885_v4l2_dev_notify_init, &dev->cx25840_work is bound with cx23885_av_work_handler, and &dev->ir_rx_work and &dev->ir_tx_work are bound with cx23885_ir_rx_work_handler and cx23885_ir_tx_work_handler. cx23885_irq can schedule these works on system_wq when an AV_CORE interrupt is received, and the IR subdevice can also schedule the IR works from its interrupt service routine via the v4l2_device notify callback.
If we remove the device, cx23885_finidev makes cleanup and the memory allocated for dev is released by kfree(dev), while the works mentioned above may still be pending or running. The sequence of operations that may lead to a UAF bug is as follows:
CPU0 CPU1
| cx23885_irq
| schedule_work(&dev->cx25840_work)
cx23885_finidev |
cx23885_input_fini(dev) |
cx23885_ir_fini(dev) |
cx23885_shutdown(dev) |
free_irq(pci_dev->irq, dev) |
pci_disable_device(pci_dev) |
cx23885_dev_unregister(dev) |
v4l2_device_unregister(v4l2_dev) |
kfree(dev) |
// dev is freed |
| cx23885_av_work_handler
| // use dev (use-after-free)Fix it by canceling the works after the IRQ handler that can schedule them has been stopped, and before proceeding with the remaining cleanup in cx23885_finidev.
Note that the flush_work() calls in cx23885_input_ir_stop() do not close this race: they only wait for works that are already queued or running at that moment, they do not prevent the IRQ handler, which is still registered at that point, from scheduling the works again afterwards, and they are skipped entirely when dev->sd_ir is NULL. The cancel_work_sync() calls are therefore placed after free_irq(), the only point at which no new work can be scheduled.
--- drivers/media/pci/cx23885/cx23885-core.c | 4 ++++ 1 file changed, 4 insertions(+)
drivers/media/pci/cx23885/cx23885-core.c +4 -0
@@ -2217,6 +2217,10 @@ static void cx23885_finidev(struct pci_d/* unregister stuff */ free_irq (pci_dev->irq, dev); +cancel_work_sync (&dev->cx25840_work); +cancel_work_sync (&dev->ir_rx_work); +cancel_work_sync (&dev->ir_tx_work); +pci_disable_device (pci_dev);cx23885_dev_unregister (dev);
Greg Kroah-Hartman
maintainerPATCH 243/1848 media: hackrf: fix use-after-free in hackrf_alloc_urbs() error path
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Anuj Bolewar <[email protected]>
commit 6802ad4b6b267dda02209b5811edac7825c8a5f6 upstream.
hackrf_alloc_urbs() frees the URBs it allocated so far when one allocation fails, but leaves the entries in dev->urb_list[] and dev->urbs_initialized untouched. The caller, hackrf_start_streaming(), then calls hackrf_free_urbs() on the error path, which walks dev->urbs_initialized entries and calls usb_free_urb() a second time on the already-freed URBs, causing a use-after-free (slab-use-after-free Write in usb_free_urb()).
Drop the redundant cleanup loop inside hackrf_alloc_urbs() and let hackrf_free_urbs(), which the caller already invokes on error, own the cleanup of the successfully allocated URBs.
--- drivers/media/usb/hackrf/hackrf.c | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-)
drivers/media/usb/hackrf/hackrf.c +2 -5
@@ -665,7 +665,7 @@ static int hackrf_free_urbs(struct hackrstatic int hackrf_alloc_urbs (struct hackrf_dev *dev,bool rcv) { -int i, j; +int i;unsigned int pipe;usb_complete_t complete;
@@ -681,11 +681,8 @@ static int hackrf_alloc_urbs(struct hackfor (i =0 ; i <MAX_BULK_BUFS ; i++) {dev_dbg (dev->dev,"alloc urb=%d\n" , i); dev->urb_list[i] =usb_alloc_urb (0 ,GFP_KERNEL ); -if (!dev->urb_list[i]) { -for (j =0 ; j < i; j++) -usb_free_urb (dev->urb_list[j]); +if (!dev->urb_list[i])return -ENOMEM ; - } usb_fill_bulk_urb(dev->urb_list[i], dev->udev, pipe,
Greg Kroah-Hartman
maintainerPATCH 244/1848 media: imon: fix use-after-free in display_close via dev_dbg
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Deepanshu Kartikey <[email protected]>
commit 118a3590a4080c71c565265b05b3f92e814d7647 upstream.
ictx->dev is a raw pointer to the usb_interface's embedded device. On disconnect, usb_disconnect() can drop the last reference on the interface and free it while a userspace fd for /dev/lcd0 is still open. When that fd is later closed, display_close() dereferences the now-freed ictx->dev via dev_dbg(), causing a use-after-free.
Remove the dev_dbg() calls that dereference ictx->dev in display_close() and free_imon_context(), rather than taking a reference on the device.
--- drivers/media/rc/imon.c | 5 ----- 1 file changed, 5 deletions(-)
drivers/media/rc/imon.c +0 -5
@@ -497,16 +497,12 @@ MODULE_PARM_DESC(pad_thresh, "Thresholdstatic void free_imon_context (struct imon_context *ictx) { -struct device *dev = ictx->dev; -usb_free_urb (ictx->tx_urb);WARN_ON (ictx->dev_present_intf0);usb_free_urb (ictx->rx_urb_intf0);WARN_ON (ictx->dev_present_intf1);usb_free_urb (ictx->rx_urb_intf1);kfree_rcu (ictx, rcu); - -dev_dbg (dev,"%s: iMON context freed\n" , __func__); }/*
@@ -582,7 +578,6 @@ static int display_close(struct inode *i retval = -EIO ; }else { ictx->display_isopen = false; -dev_dbg (ictx->dev,"display port closed\n" ); }mutex_unlock (&ictx->lock);
Greg Kroah-Hartman
maintainerPATCH 245/1848 apparmor: fix a use-after-free in aa_lookupn_ns()
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Binbin Deng <[email protected]>
commit f292873ceb4bd3a1a0f75f884361cd556e457692 upstream.
aa_lookupn_ns() takes a reference on the namespace it finds with aa_get_ns(), which is kref_get() on the reference count that the namespace is released through, without checking whether the namespace is still in use. A concurrent removal of a ":"-prefixed namespace looks the same namespace up and only then takes the parent lock to remove it, so the last reference can be dropped between the lookup and the aa_get_ns() call: the reference count then reports the increment on a zero count and the kernel classifies the following use of the object as a use-after-free. A user with CAP_MAC_ADMIN can trigger this by writing a ":<name>" removal and a ":<name>/<profile>" removal to /sys/kernel/security/apparmor/.remove concurrently.
refcount_t: addition on 0; use-after-free.
WARNING: lib/refcount.c:25 at refcount_warn_saturate+0xc0/0xe0, CPU#6 Call Trace: <TASK> aa_lookupn_ns+0xa9/0xc0 aa_remove_profiles+0x4fb/0x730 ? __kvmalloc_node_noprof+0x219/0x5c0 ? __pfx_aa_remove_profiles+0x10/0x10 ? aa_loaddata_alloc+0x65/0x1f0 ? _copy_from_user+0x2d/0x80 ? aa_loaddata_alloc+0x111/0x1f0 profile_remove+0x2ee/0x4a0 vfs_write+0x21e/0xcf0 ? rcu_core+0x29c/0x1740 ? timerqueue_linked_add+0x1f4/0x3d0 ? __pfx_vfs_write+0x10/0x10 ? mutex_lock+0x81/0xe0 ? __pfx_mutex_lock+0x10/0x10 ? __pfx_rcu_core+0x10/0x10 ? __pfx_hrtimer_update_next_event+0x10/0x10 ? mutex_unlock+0x7b/0xd0 ? fdget_pos+0x24d/0x4b0 ksys_write+0xf7/0x1c0 ? __pfx_ksys_write+0x10/0x10 ? restore_fpregs_from_fpstate+0x37/0xc0 do_syscall_64+0xf9/0x540 entry_SYSCALL_64_after_hwframe+0x77/0x7f </TASK>
Fix by rejecting a namespace whose reference count is zero.
--- security/apparmor/include/policy_ns.h | 16 ++++++++++++++++ security/apparmor/policy_ns.c | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-)
security/apparmor/include/policy_ns.h +16 -0
@@ -120,6 +120,22 @@ static inline struct aa_ns *aa_get_ns(st }/** +* aa_get_ns_not0 - increment references count on @ns found via lookup +* @ns: namespace to increment reference count of (MAYBE NULL) +* +* Returns: pointer to @ns, if @ns is NULL returns NULL, +* NULL if @ns is being freed +* Requires: @ns must be held with valid refcount when called +*/ +static inline struct aa_ns *aa_get_ns_not0 (struct aa_ns *ns) +{ +if (ns &&aa_get_profile_not0 (ns->unconfined)) +return ns; + +return NULL ; +} + +/** * aa_put_ns - decrement refcount on @ns * @ns: namespace to put reference of *
security/apparmor/policy_ns.c +1 -1
@@ -233,7 +233,7 @@ struct aa_ns *aa_lookupn_ns(struct aa_nsstruct aa_ns *ns =NULL ;rcu_read_lock (); - ns =aa_get_ns (__aa_lookupn_ns (view, name, n)); + ns =aa_get_ns_not0 (__aa_lookupn_ns (view, name, n));rcu_read_unlock ();return ns;
Greg Kroah-Hartman
maintainerPATCH 246/1848 ata: sata_fsl: Fix use-after-free of host_priv on probe() failure
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Niklas Cassel <[email protected]>
commit 70b1196740d61aabda13b2ad0e9c1dfa2ef9cfa3 upstream.
sata_fsl_host_stop() releases hcr_base and host_priv:
static void sata_fsl_host_stop(struct ata_host *host)
{
struct sata_fsl_host_priv *host_priv = host->private_data;
iounmap(host_priv->hcr_base);
kfree(host_priv);
}->host_stop() is called by the driver core through the ata_host_stop() devres action which ata_host_start() registers, so it is called both when the device is unbound and when probe() fails after the host has been started.
The error_exit_with_cleanup label of sata_fsl_probe() releases hcr_base and host_priv as well, and it is reachable from the two device_create_file() calls which are done after the host has been activated. In that case sata_fsl_host_stop() runs on an already freed host_priv, resulting in a use-after-free and a double iounmap()/kfree().
Add a separate error label for the failures happening after the host has been activated, which only detaches the host and leaves hcr_base and host_priv to sata_fsl_host_stop().
Note that ata_host_detach() is dropped from error_exit_with_cleanup, as that label is now only reachable while host is still NULL.
--- drivers/ata/sata_fsl.c | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-)
drivers/ata/sata_fsl.c +13 -5
@@ -1530,7 +1530,7 @@ static int sata_fsl_probe(struct platfor host_priv->intr_coalescing.attr.mode =S_IRUGO |S_IWUSR ; retval =device_create_file (host->dev, &host_priv->intr_coalescing);if (retval) - goto error_exit_with_cleanup; + goto error_exit_detach; host_priv->rx_watermark.show = fsl_sata_rx_watermark_show; host_priv->rx_watermark.store = fsl_sata_rx_watermark_store;
@@ -1540,16 +1540,24 @@ static int sata_fsl_probe(struct platfor retval =device_create_file (host->dev, &host_priv->rx_watermark);if (retval) {device_remove_file (&ofdev->dev, &host_priv->intr_coalescing); - goto error_exit_with_cleanup; + goto error_exit_detach; }return 0 ; -error_exit_with_cleanup: +error_exit_detach: +/* +* Once the host has been activated, hcr_base and host_priv are +* released by sata_fsl_host_stop(), which is called by the driver core +* through the ata_host_stop() devres action registered by +* ata_host_start(). Releasing them here as well would result in a +* double iounmap() and a use-after-free. +*/ +ata_host_detach (host); -if (host) -ata_host_detach (host); +return retval; +error_exit_with_cleanup:if (hcr_base)iounmap (hcr_base);kfree (host_priv);
Greg Kroah-Hartman
maintainerPATCH 247/1848 s390/probes: Fix wrong opcode for cgrb fixup
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Heiko Carstens <[email protected]>
commit d7ccab11a13475e656b9d2277900422c1bfc12c5 upstream.
The last byte of the cgrb instruction is 0xe4, however the probes code compares against 0xe6. Fix it.
--- arch/s390/lib/probes.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/s390/lib/probes.c +1 -1
@@ -99,8 +99,8 @@ int probe_get_fixup_type(u16 *insn)break ;case 0xec :switch (insn[2 ] &0xff ) { +case 0xe4 :/* cgrb */ case 0xe5 :/* clgrb */ -case 0xe6 :/* cgrb */ case 0xf6 :/* crb */ case 0xf7 :/* clrb */ case 0xfc :/* cgib */
Greg Kroah-Hartman
maintainerPATCH 248/1848 HID: wacom: Use hdev->product in wacom_setup_touch_input_capabilities
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lee Jones <[email protected]>
commit 86472508a7ef74b525e79a79d2d02d911a641d6b upstream.
Replace the lookup-dependent 'wacom_wac->shared->touch->product' references with 'hdev->product' inside wacom_setup_touch_input_capabilities() since 'hdev' is already available (via container_of) and represents the touch device itself.
--- drivers/hid/wacom_wac.c | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-)
drivers/hid/wacom_wac.c +9 -9
@@ -3870,8 +3870,8 @@ int wacom_setup_pen_input_capabilities(sint wacom_setup_touch_input_capabilities (struct input_dev *input_dev,struct wacom_wac *wacom_wac) { + struct hid_device *hdev = container_of(wacom_wac, struct wacom, wacom_wac)->hdev;struct wacom_features *features = &wacom_wac->features; -if (!(features->device_type &WACOM_DEVICETYPE_TOUCH ))return -ENODEV ;
@@ -3880,9 +3880,11 @@ int wacom_setup_touch_input_capabilitieselse __set_bit (INPUT_PROP_POINTER , input_dev->propbit); -if (features->type ==HID_GENERIC ) +if (features->type ==HID_GENERIC ) { +hid_dbg (hdev,"generic touch setup\n" );/* setup has already been done */ return 0 ; + } input_dev->evbit[0 ] |=BIT_MASK (EV_KEY ) |BIT_MASK (EV_ABS );__set_bit (BTN_TOUCH , input_dev->keybit);
@@ -3914,19 +3916,17 @@ int wacom_setup_touch_input_capabilities input_dev->evbit[0 ] |=BIT_MASK (EV_SW );__set_bit (SW_MUTE_DEVICE , input_dev->swbit); -if (wacom_wac->shared->touch->product ==0x361 ) { +if (hdev->product ==0x361 ) {input_set_abs_params (input_dev,ABS_MT_POSITION_X ,0 ,12440 ,4 ,0 );input_set_abs_params (input_dev,ABS_MT_POSITION_Y ,0 ,8640 ,4 ,0 ); - } -else if (wacom_wac->shared->touch->product ==0x360 ) { + }else if (hdev->product ==0x360 ) {input_set_abs_params (input_dev,ABS_MT_POSITION_X ,0 ,8960 ,4 ,0 );input_set_abs_params (input_dev,ABS_MT_POSITION_Y ,0 ,5920 ,4 ,0 ); - } -else if (wacom_wac->shared->touch->product ==0x393 ) { + }else if (hdev->product ==0x393 ) {input_set_abs_params (input_dev,ABS_MT_POSITION_X ,0 ,6400 ,4 ,0 ); input_set_abs_params(input_dev, ABS_MT_POSITION_Y,
@@ -3956,8 +3956,8 @@ int wacom_setup_touch_input_capabilities fallthrough;case WACOM_27QHDT : -if (wacom_wac->shared->touch->product ==0x32C || - wacom_wac->shared->touch->product ==0xF6 ) { +if (hdev->product ==0x32C || + hdev->product ==0xF6 ) { input_dev->evbit[0 ] |=BIT_MASK (EV_SW );__set_bit (SW_MUTE_DEVICE , input_dev->swbit); wacom_wac->has_mute_touch_switch = true;
Greg Kroah-Hartman
maintainerPATCH 249/1848 klist: avoid accesses after waking klist_remove()
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Karl Mehltretter <[email protected]>
commit 732e3e10234cbe302d0dcbaa98c91c66628209cb upstream.
klist_remove() waits until a node is unreferenced so that its caller can free the containing object. klist_release() currently publishes waiter->woken and wakes the waiter before its final accesses to the waiter and node. klist_remove() can then return, allowing its stack waiter and the containing object to be freed or reused while klist_release() is still running. In particular, bus_remove_driver() can free drv->p while __device_attach() walks the same bus klist with bus_for_each_drv().
On an arm64 Cortex-A72 system, an unpatched 7.2.0-rc3 kernel with CONFIG_PREEMPT_RT=y and CONFIG_KASAN=y reproduced the bug through the in-tree I2C/at24 path. KASAN reported a use-after-free in klist_dec_and_del() reached from klist_next()/bus_for_each_drv() while at24 was being unregistered.
Clear n_klist and take a task reference before publishing woken. Use release/acquire accesses for that publication and wake the referenced task. The task reference keeps the waiter task alive if it returns and exits before wake_up_process().
--- lib/klist.c | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-)
lib/klist.c +12 -4
@@ -36,6 +36,7 @@#include <linux/klist.h> #include <linux/export.h> #include <linux/sched.h> +#include <linux/sched/task.h> /* * Use the lowest bit of n_klist to mark deleted nodes and exclude
@@ -187,18 +188,24 @@ static void klist_release(struct kref *kWARN_ON (!knode_dead (n));list_del (&n->n_node); +knode_set_klist (n,NULL );spin_lock (&klist_remove_lock);list_for_each_entry_safe (waiter, tmp, &klist_remove_waiters, list) { +struct task_struct *p; +if (waiter->node != n)continue ; + p = waiter->process; +get_task_struct (p);list_del (&waiter->list); - waiter->woken =1 ; +/* Publish only after the final waiter and n accesses */ +smp_store_release (&waiter->woken,1 );mb (); -wake_up_process (waiter->process); +wake_up_process (p); +put_task_struct (p); }spin_unlock (&klist_remove_lock); -knode_set_klist (n,NULL ); }static int klist_dec_and_del (struct klist_node *n)
@@ -250,7 +257,8 @@ void klist_remove(struct klist_node *n)for (;;) {set_current_state (TASK_UNINTERRUPTIBLE ); -if (waiter.woken) +/* Pairs with the release store in klist_release() */ +if (smp_load_acquire (&waiter.woken))break ;schedule (); }
Greg Kroah-Hartman
maintainerPATCH 250/1848 fbdev: atmel_lcdfb: Prevent FIFO work after removal
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yibo Tan <[email protected]>
commit 20b3b97cf89cb381bf07516090d99399cc9b91fd upstream.
The LCD controller IRQ schedules sinfo->task to recover from a FIFO underflow. Probe currently requests the IRQ before initializing the work, so an early interrupt can schedule an uninitialized work item.
The probe error path and remove path cancel the work before freeing the IRQ. A FIFO-underflow interrupt can schedule the work again after that cancellation. framebuffer_release() may then free sinfo while the work is still pending.
KASAN reported a use-after-free in atmel_lcdfb_task() when an underflow interrupt occurred during removal. With the IRQ freed before the work was cancelled, the same test completed without a kernel diagnostic.
Initialize the work before requesting the IRQ. In both cleanup paths, free the IRQ before cancelling the work so that it cannot be scheduled again after cancellation.
--- drivers/video/fbdev/atmel_lcdfb.c | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-)
drivers/video/fbdev/atmel_lcdfb.c +5 -6
@@ -1171,6 +1171,9 @@ static int __init atmel_lcdfb_probe(stru/* Initialize PWM for contrast or backlight ("off") */ init_contrast (sinfo); +/* Some LCDC recovery operations require process context. */ +INIT_WORK (&sinfo->task, atmel_lcdfb_task); +/* interrupt */ ret =request_irq (sinfo->irq_base, atmel_lcdfb_interrupt,0 , pdev->name, info);if (ret) {
@@ -1178,10 +1181,6 @@ static int __init atmel_lcdfb_probe(stru goto unmap_mmio; } -/* Some operations on the LCDC might sleep and -* require a preemptible task context */ -INIT_WORK (&sinfo->task, atmel_lcdfb_task); - ret =atmel_lcdfb_init_fbinfo (sinfo);if (ret <0 ) {dev_err (dev,"init fbinfo failed: %d\n" , ret);
@@ -1217,8 +1216,8 @@ reset_drvdata:dev_set_drvdata (dev,NULL );fb_dealloc_cmap (&info->cmap); unregister_irqs: -cancel_work_sync (&sinfo->task);free_irq (sinfo->irq_base, info); +cancel_work_sync (&sinfo->task); unmap_mmio:exit_backlight (sinfo);iounmap (sinfo->mmio);
@@ -1255,6 +1254,7 @@ static int __exit atmel_lcdfb_remove(strreturn 0 ; sinfo = info->par; +free_irq (sinfo->irq_base, info);cancel_work_sync (&sinfo->task);exit_backlight (sinfo);atmel_lcdfb_power_control (sinfo,0 );
@@ -1263,7 +1263,6 @@ static int __exit atmel_lcdfb_remove(strclk_put (sinfo->lcdc_clk);clk_put (sinfo->bus_clk);fb_dealloc_cmap (&info->cmap); -free_irq (sinfo->irq_base, info);iounmap (sinfo->mmio);release_mem_region (info->fix.mmio_start, info->fix.mmio_len);if (platform_get_resource (pdev,IORESOURCE_MEM ,1 )) {
Greg Kroah-Hartman
maintainerPATCH 251/1848 fbdev: udlfb: dont rebuild the mode list while the framebuffer is in use
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Xiang Mei <[email protected]>
commit ac9cfa552102b8e80e88c2872e80dc9cb5f07dda upstream.
dlfb_setup_modes() frees info->modelist with fb_destroy_modelist() and rebuilds it, but fbcon holds raw pointers into that list in fb_display[i].mode and nothing un-publishes them the way do_unregister_framebuffer() and store_modes() do with fbcon_delete_modelist(). The function does refuse to install a new mode while the framebuffer has users (dlfb->fb_count != 0), but only after the list is already destroyed. Reached from the 0666 "edid" sysfs attribute, an unprivileged write to /sys/class/graphics/fb0/edid therefore fails with -EINVAL and still leaves every fb_display[i].mode dangling; the next console switch reads the freed fb_videomode in fb_videomode_to_var().
Test fb_count before touching the list. fbcon takes a reference through fbcon_open(), so that condition covers exactly the states in which fb_display[] points into the list, and the errno returned to userspace is unchanged.
BUG: KASAN: slab-use-after-free in fb_videomode_to_var (drivers/video/fbdev/core/modedb.c:905) Read of size 4 at addr ffff8880107b449c by task kworker/1:1/47 Workqueue: events console_callback Call Trace: fb_videomode_to_var (drivers/video/fbdev/core/modedb.c:905) display_to_var (drivers/video/fbdev/core/fbcon.c:998) fbcon_switch (drivers/video/fbdev/core/fbcon.c:2182) redraw_screen (drivers/tty/vt/vt.c:994) complete_change_console (drivers/tty/vt/vt_ioctl.c:1141) console_callback (drivers/tty/vt/vt.c:3358) process_one_work (kernel/workqueue.c:3396) worker_thread (kernel/workqueue.c:3479 kernel/workqueue.c:3560) kthread (kernel/kthread.c:436) ret_from_fork (arch/x86/kernel/process.c:158) ret_from_fork_asm (arch/x86/entry/entry_64.S:245) ... The buggy address is located 28 bytes inside of freed 96-byte region [ffff8880107b4480, ffff8880107b44e0)
--- drivers/video/fbdev/udlfb.c | 5 +++++ 1 file changed, 5 insertions(+)
drivers/video/fbdev/udlfb.c +5 -0
@@ -1335,6 +1335,11 @@ static int dlfb_setup_modes(struct dlfb_ goto error; } +if (dlfb->fb_count) { + result = -EINVAL ; + goto error; + } +fb_destroy_modelist (&info->modelist);memset (&info->monspecs,0 ,sizeof (info->monspecs));
Greg Kroah-Hartman
maintainerPATCH 252/1848 HID: hiddev: keep state alive through disconnect unlock
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yousef Alhouseen <[email protected]>
commit 03f449b5de36a25fc5eba7dabf2b4494389bdb91 upstream.
mutex_unlock() clears the mutex owner before taking its wait lock. A thread spinning in the final hiddev file release can acquire existancelock after hiddev_disconnect() clears the owner, then free hiddev before the disconnecting thread reaches the mutex wait lock. This causes a use-after-free in the mutex slow unlock path.
Give the connection and each open file an explicit reference. Drop each reference only after its existancelock critical section has completed, so neither unlock path can free the mutex while the other is still using it.
--- drivers/hid/usbhid/hiddev.c | 37 +++++++++++++++++++------------------ include/linux/hiddev.h | 2 ++ 2 files changed, 21 insertions(+), 18 deletions(-)
drivers/hid/usbhid/hiddev.c +19 -18
@@ -46,6 +46,12 @@ struct hiddev_list {struct mutex thread_lock; }; +static void hiddev_put (struct hiddev *hiddev) +{ +if (refcount_dec_and_test (&hiddev->refcount)) +kfree (hiddev); +} +/* * Find a report, given the report's type and ID. The ID can be specified * indirectly by REPORT_ID_FIRST (which returns the first report of the given
@@ -216,26 +222,21 @@ static int hiddev_fasync(int fd, structstatic int hiddev_release (struct inode * inode,struct file * file) {struct hiddev_list *list = file->private_data; +struct hiddev *hiddev = list->hiddev;unsigned long flags; -spin_lock_irqsave (&list->hiddev->list_lock, flags); +spin_lock_irqsave (&hiddev->list_lock, flags);list_del (&list->node); -spin_unlock_irqrestore (&list->hiddev->list_lock, flags); +spin_unlock_irqrestore (&hiddev->list_lock, flags); -mutex_lock (&list->hiddev->existancelock); -if (!--list->hiddev->open) { -if (list->hiddev->exist) { -hid_hw_close (list->hiddev->hid); -hid_hw_power (list->hiddev->hid,PM_HINT_NORMAL ); - }else { -mutex_unlock (&list->hiddev->existancelock); -kfree (list->hiddev); -vfree (list); -return 0 ; - } +mutex_lock (&hiddev->existancelock); +if (!--hiddev->open && hiddev->exist) { +hid_hw_close (hiddev->hid); +hid_hw_power (hiddev->hid,PM_HINT_NORMAL ); } -mutex_unlock (&list->hiddev->existancelock); +mutex_unlock (&hiddev->existancelock); +hiddev_put (hiddev);vfree (list);return 0 ;
@@ -270,6 +271,7 @@ static int __hiddev_open(struct hiddev *spin_unlock_irq (&hiddev->list_lock); file->private_data = list; +refcount_inc (&hiddev->refcount);return 0 ;
@@ -897,6 +899,7 @@ int hiddev_connect(struct hid_device *hiINIT_LIST_HEAD (&hiddev->list);spin_lock_init (&hiddev->list_lock);mutex_init (&hiddev->existancelock); +refcount_set (&hiddev->refcount,1 ); hid->hiddev = hiddev; hiddev->hid = hid; hiddev->exist =1 ;
@@ -937,9 +940,7 @@ void hiddev_disconnect(struct hid_deviceif (hiddev->open) {hid_hw_close (hiddev->hid);wake_up_interruptible (&hiddev->wait); -mutex_unlock (&hiddev->existancelock); - }else { -mutex_unlock (&hiddev->existancelock); -kfree (hiddev); } +mutex_unlock (&hiddev->existancelock); +hiddev_put (hiddev); }
include/linux/hiddev.h +2 -0
@@ -13,6 +13,7 @@#ifndef _HIDDEV_H#define _HIDDEV_H +#include <linux/refcount.h> #include <uapi/linux/hiddev.h>
@@ -24,6 +25,7 @@ struct hiddev {int minor;int exist;int open; +refcount_t refcount;struct mutex existancelock;wait_queue_head_t wait;struct hid_device *hid;
Greg Kroah-Hartman
maintainerPATCH 253/1848 io_uring/io-wq: save worker type before dropping its reference
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kyle Zeng <[email protected]>
commit 37e425460b7c41687e51e3254b1eb1d799da9614 upstream.
io_wq_cancel_tw_create() inspects cb->func after calling io_worker_cancel_cb(). For an existing worker, that call can drop the last worker reference and wake io_worker_exit(). If the canceling task is preempted, the worker can be unlinked and freed by kfree_rcu() before the callback function is inspected. KASAN reports a slab-use-after-free read in this path.
Save whether the callback belongs to an unpublished continuation worker while its reference is still held, then use the saved result for the conditional free. This preserves the existing accounting and frees only the worker allocated for the canceled continuation.
--- io_uring/io-wq.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-)
io_uring/io-wq.c +5 -3
@@ -1232,14 +1232,16 @@ static void io_wq_cancel_tw_create(strucwhile ((cb =task_work_cancel_match (wq->task, io_task_work_match, wq)) !=NULL ) {struct io_worker *worker; +bool free_worker; worker = container_of(cb, struct io_worker, create_work); -io_worker_cancel_cb (worker);/* * Only the worker continuation helper has worker allocated and -* hence needs freeing. +* hence needs freeing. Save this before dropping its reference. */ -if (cb->func == create_worker_cont) + free_worker = cb->func == create_worker_cont; +io_worker_cancel_cb (worker); +if (free_worker)kfree (worker); } }
Greg Kroah-Hartman
maintainerPATCH 254/1848 media: cx23885: unregister DVB bus when SP2 CI setup fails
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Myeonghun Pak <[email protected]>
commit 22f552ff726a82a086be4ef02ce5099a0e8624b6 upstream.
The DVBSKY S950C, DVBSKY T980C and TechnoTrend CT2-4500 CI paths register the DVB bus before attaching their SP2 CI client. If that client cannot be created, bound, or pinned, the current error path removes the I2C frontend components and only deallocates the frontend list, leaving the registered DVB adapter behind. Removing an I2C demod before unregistering the DVB bus can also expose the use-after-free ordering fixed for the normal remove path.
Unregister the DVB bus immediately when SP2 CI setup fails, before the existing I2C client cleanup. The bus helper empties the frontend list, so the later frontend deallocation has nothing left to release. Keep failures from vb2_dvb_register_bus() on the existing cleanup path. Also release an unbound SP2 client and propagate the actual I2C creation or CI registration error.
This issue was identified during our ongoing static-analysis research while reviewing kernel code.
--- drivers/media/pci/cx23885/cx23885-dvb.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-)
drivers/media/pci/cx23885/cx23885-dvb.c +10 -4
@@ -1160,8 +1160,12 @@ static int dvb_register_ci_mac(struct cx info.platform_data = &sp2_config;request_module (info.type); client_ci =i2c_new_client_device (&i2c_bus->i2c_adap, &info); -if (!i2c_client_has_driver (client_ci)) +if (IS_ERR (client_ci)) +return PTR_ERR (client_ci); +if (!client_ci->dev.driver) { +i2c_unregister_device (client_ci);return -ENODEV ; + }if (!try_module_get (client_ci->dev.driver->owner)) {i2c_unregister_device (client_ci);return -ENODEV ;
@@ -1204,7 +1208,7 @@ static int dvb_register(struct cx23885_tint (*p_set_voltage)(struct dvb_frontend *fe,enum fe_sec_voltage voltage) =NULL ;int mfe_shared =0 ;/* bus not shared by default */ -int ret; +int ret = -EINVAL ;/* Get the first frontend */ fe0 =vb2_dvb_get_frontend (&port->frontends,1 );
@@ -2586,8 +2590,10 @@ static int dvb_register(struct cx23885_t goto frontend_detach; ret =dvb_register_ci_mac (port); -if (ret) +if (ret) { +vb2_dvb_unregister_bus (&port->frontends); goto frontend_detach; + }return 0 ;
@@ -2618,7 +2624,7 @@ frontend_detach: port->gate_ctrl =NULL ;vb2_dvb_dealloc_frontends (&port->frontends); -return -EINVAL ; +return ret; }int cx23885_dvb_register (struct cx23885_tsport *port)
Greg Kroah-Hartman
maintainerPATCH 255/1848 media: gspca: use vb2_video_unregister_device() on disconnect
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shuangpeng Bai <[email protected]>
commit 3dbbbc3cafa2de377d9b97af4e35b8b6b5282047 upstream.
gspca uses vb2_fop_release(), but gspca_disconnect() only unregisters the video device. If the queue owner closes the device after USB disconnect, vb2_fop_release() releases the queue and invokes gspca_stop_streaming() at that point.
gspca_stream_off() calls subdriver stop callbacks and usb_set_interface() through gspca_dev->dev. By the time the late close runs, the USB core can have freed the usb_device, resulting in a use-after-free. This was observed as a KASAN use-after-free in sd_stopN().
Use vb2_video_unregister_device() so the queue is released and streaming is stopped synchronously during disconnect, while the usb_device is still valid. Since the helper takes the queue lock, which is usb_lock, call it after dropping that lock.
--- drivers/media/usb/gspca/gspca.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/media/usb/gspca/gspca.c +1 -2
@@ -1641,9 +1641,8 @@ void gspca_disconnect(struct usb_interfa#endif v4l2_device_disconnect (&gspca_dev->v4l2_dev); -video_unregister_device (&gspca_dev->vdev); -mutex_unlock (&gspca_dev->usb_lock); +vb2_video_unregister_device (&gspca_dev->vdev);/* (this will call gspca_release() immediately or on last close) */ v4l2_device_put (&gspca_dev->v4l2_dev);
Greg Kroah-Hartman
maintainerPATCH 256/1848 media: redrat3: fix UAF in probe error path leaving rc device registered
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rik van Riel <[email protected]>
commit af452b9e01331b5338a1e5141624f17607239207 upstream.
redrat3 stores its device name and phys path inside the main rr3 structure, and the rc device's device_name and input_phys point into rr3. When the RC device is registered, it keeps those pointers.
KASAN: slab-use-after-free in string_nocheck lib/vsprintf.c:648 Read of size 1 at addr ffff888051fda758 by task udevd/7464 Call Trace: string_nocheck lib/vsprintf.c:648 [inline] string+0x216/0x2d0 lib/vsprintf.c:730 vsnprintf+0x74a/0xef0 lib/vsprintf.c:2945 vscnprintf+0x41/0x90 lib/vsprintf.c:3014 sysfs_emit+0x10e/0x180 fs/sysfs/file.c:761 input_dev_show_name+0x58/0x70 drivers/input/input.c:1282 Allocated by task 10: redrat3_dev_probe+0x477/0x2570 drivers/media/rc/redrat3.c:1023 Freed by task 10: redrat3_delete drivers/media/rc/redrat3.c:466 [inline] redrat3_dev_probe+0x1bf4/0x2570 drivers/media/rc/redrat3.c:1124
Syzkaller triggers this via usb probing. It probes the RedRat3 USB interface, which calls redrat3_dev_probe() in redrat3.c. That function allocates rr3, then builds an rc device whose name points into rr3 via redrat3_init_rc_dev() in redrat3.c, and registers it with rc_register_device().
When the detector enable fails after the RC device is registered, the probe jumps to the led_free path. That path unregisters the LED but does not unregister the RC device before freeing rr3 via redrat3_delete() in redrat3.c. The RC device still holds device_name = rr3->name which is now freed.
Later udevd reads /sys/.../input device name via sysfs_emit() in file.c, which calls input_dev_show_name() in input.c, which emits dev->name which is the freed rr3->name.
When the detector enable fails after the RC device is registered, the error path must not leave the RC device registered. Make the probe error path clean up the same way redrat3_dev_disconnect() does.
This change should be safe because the RC device is fully registered at this point and its teardown via rc_unregister_device() is protected by the input device mutex, and rr3 is still alive during unregister so device_name remains valid until after unregister. The URBs are killed before rc_free, so no completion can run after rc is freed. No new lock ordering is introduced.
--- drivers/media/rc/redrat3.c | 4 ++++ 1 file changed, 4 insertions(+)
drivers/media/rc/redrat3.c +4 -0
@@ -977,6 +977,7 @@ static int redrat3_dev_probe(struct usb_struct device *dev = &intf->dev;struct usb_host_interface *uhi;struct redrat3_dev *rr3; +struct rc_dev *rc;struct usb_endpoint_descriptor *ep;struct usb_endpoint_descriptor *ep_narrow =NULL ;struct usb_endpoint_descriptor *ep_wide =NULL ;
@@ -1121,9 +1122,12 @@ static int redrat3_dev_probe(struct usb_return 0 ; led_free: +rc_unregister_device (rr3->rc);led_classdev_unregister (&rr3->led); redrat_free: + rc = rr3->rc;redrat3_delete (rr3, rr3->udev); +rc_free_device (rc); no_endpoints:return retval;
Greg Kroah-Hartman
maintainerPATCH 257/1848 usb: gadget: fix refcount underflow in gadgetfs_bind() error path
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nguyen Quang Le Kien <[email protected]>
commit cb3b441f2698455a48e9a023d5f7f4e3fcb94c73 upstream.
gadgetfs_bind() calls get_dev() only on the success path, but gadgetfs_unbind() called from the enomem error label unconditionally calls put_dev(). When bind fails (e.g. ENOMEM), put_dev() fires without a matching get_dev(), leaving the refcount unbalanced.
A subsequent close of the ep0 file descriptor calls dev_release() -> put_dev() which hits zero and frees the object; then gadgetfs_kill_sb() calls put_dev(the_device) again on the already-freed pointer, triggering a refcount underflow and use-after-free.
Fix by calling get_dev() at the start of gadgetfs_bind(), before any error path that invokes gadgetfs_unbind(), so the reference is always balanced regardless of whether bind succeeds or fails.
--- drivers/usb/gadget/legacy/inode.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/usb/gadget/legacy/inode.c +2 -1
@@ -1689,6 +1689,8 @@ static int gadgetfs_bind(struct usb_gadg dev->gadget = gadget; gadget->ep0->driver_data = dev; +get_dev (dev); +/* preallocate control response and buffer */ dev->req =usb_ep_alloc_request (gadget->ep0,GFP_KERNEL );if (!dev->req)
@@ -1703,7 +1705,6 @@ static int gadgetfs_bind(struct usb_gadgspin_lock_irq (&dev->lock); dev->state =STATE_DEV_UNCONNECTED ;spin_unlock_irq (&dev->lock); -get_dev (dev);return 0 ; enomem:
Greg Kroah-Hartman
maintainerPATCH 258/1848 ufs: use u64 for directory size in ufs_last_byte
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: YANXIN LI <[email protected]>
commit 1eff23433e73d7da4f9e3529d2701e34962b161f upstream.
ufs1_read_inode() and ufs2_read_inode() copy the untrusted 64-bit on-disk size into inode->i_size. ufs_last_byte() then truncates that value to an unsigned int before calculating the valid extent of a directory folio.
A directory size of exactly 4 GiB is truncated to zero. In ufs_find_entry(), subtracting the requested record length from that zero forms an endpoint almost 4 GiB beyond the mapped folio. A crafted UFS2 image produces:
BUG: KASAN: use-after-free in ufs_find_entry+0x583/0x6e0 [ufs] Read of size 1 ... ufs_find_entry ufs_inode_by_name ufs_lookup __lookup_slow path_lookupat
The KASAN classification reflects that the adjacent physical page was free; the source-level operation is an out-of-folio read. A controlled UFS1 test with CONFIG_UFS_FS_WRITE enabled also made ufs_find_entry() return a directory entry from an adjacent anonymous page. unlink() then passed that pointer to ufs_delete_entry(), which cleared the adjacent page's 3
2-bit d_ino. This write result reproduced three out of three times.
UFS normally requires a privileged mount path. A relevant boundary is a privileged automounter or image-processing service handling an attacker-supplied filesystem. The write primitive additionally requires UFS1 to be mounted read-write with CONFIG_UFS_FS_WRITE enabled; the read is reachable with read-only UFS2.
Keep the intermediate size arithmetic at 64 bits so non-final pages are bounded at PAGE_SIZE. With this change, the same controlled tests reach the real on-disk directory entry and produce no adjacent-page write or KASAN report. A reproducer and full validation logs are available on request.
The vulnerable helper is present in v7.2-rc3, v7.1, v6.18.38, v6.12.95, v6.6.111, and upstream master at 1229e2e57a5c. Runtime reproduction and fix validation were performed in an x86-64 QEMU guest running v7.2-rc3 with generic KASAN.
--- fs/ufs/dir.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/ufs/dir.c +1 -1
@@ -211,7 +211,7 @@ fail:static unsigned ufs_last_byte (struct inode *inode,unsigned long page_nr) { -unsigned last_byte = inode->i_size; +u64 last_byte = inode->i_size; last_byte -= page_nr <<PAGE_SHIFT ;if (last_byte >PAGE_SIZE )
Greg Kroah-Hartman
maintainerPATCH 259/1848 resource: report a devm_request_resource() conflict under the lock
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nickolai Zeldovich <[email protected]>
commit d2f7bdfdeac8137e942b32e0badc40e181127d7b upstream.
devm_request_resource() calls request_resource_conflict(), which takes resource_lock, tries to insert the new resource and returns a pointer to the conflicting resource after dropping the lock. The error message is then formatted from that pointer: conflict->name and the %pR argument read the name, start, end, flags and desc of a resource that nothing pins any more. The owner of the conflicting resource may call release_resource() and free it the moment the lock is dropped.
The conflicting resource normally belongs to another device. With two devices whose drivers claim overlapping regions (two PCI host bridges whose "ranges" windows overlap, two instances of a controller on the same aperture, or a stale claim an administrator is replacing), the following interleaving reads freed memory:
CPU 0: driver B probe CPU 1: driver A unbind
devm_request_resource(devB, root, resB)
request_resource_conflict()
write_lock(&resource_lock)
__request_resource() -> resA
write_unlock(&resource_lock)
devres_release_all(devA)
devm_resource_release()
release_resource(resA)
put_device() -> kfree(resA)
dev_err(..., resA->name, resA) use after freeBoth halves are reachable from userspace on any kernel: a write to the "unbind" file of the driver that holds the region and a write to the "bind" file of the driver that wants it. One in-tree path is drivers/pci/bus.c devm_request_pci_bus_resources(), called from host bridge probe for every bridge window; the windows are the embedded struct resource of kzalloc'ed resource_entry objects that pci_free_resource_list() frees when the other bridge is released. In the common case the "resource collision" message is garbled; with the slab object poisoned (CONFIG_SLUB_DEBUG) or reused, formatting conflict->name oopses, and KASAN reports a slab-use-after-free read in devm_request_resource(). All of this happens in a probe that is already failing with -EBUSY. The window is a few hundred instructions wide and exists only when two devices actually collide, so the race has not been observed outside of analysis.
Do the same here: take resource_lock, insert with __request_resource() and print the diagnostic while the lock still keeps the conflicting resource in the tree, then drop the lock. The return values and the devres handling are unchanged.
The change was built for x86_64 and RISC-V; the resource KUnit tests pass on both.
Found by formal verification of kernel/resource.c against the kernel binary.
--- kernel/resource.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-)
kernel/resource.c +7 -2
@@ -1464,10 +1464,15 @@ int devm_request_resource(struct device *ptr = new; - conflict =request_resource_conflict (root, new); -if (conflict) { +/* Report a conflict while the lock still keeps it in the tree. */ +write_lock (&resource_lock); + conflict =__request_resource (root, new); +if (conflict)dev_err (dev,"resource collision: %pR conflicts with %s %pR\n" , new, conflict->name, conflict); +write_unlock (&resource_lock); + +if (conflict) {devres_free (ptr);return -EBUSY ; }
Greg Kroah-Hartman
maintainerPATCH 260/1848 media: rc: fintek-cir: process a full RX buffer instead of overflowing it
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Weigang He <[email protected]>
commit d1febef1bcfa7bbc401729f994c375b91a833911 upstream.
fintek_get_rx_ir_data() drains the CIR RX FIFO into fintek->buf[], which holds RX_BUF_LEN (32) bytes, for as long as CIR_STATUS reports pending RX data:
do {
sample = fintek_cir_reg_read(fintek, CIR_RX_DATA);
...
fintek->buf[fintek->pkts] = sample;
fintek->pkts++;
...
} while (status & rx_irqs);Nothing bounds fintek->pkts. If the hardware reports data for more than RX_BUF_LEN reads in one interrupt, the loop writes past the end of buf[], starting with the pkts counter that follows it in struct fintek_dev.
Hand a full buffer to fintek_process_rx_ir_data(), which parses the samples and resets fintek->pkts, before storing the next sample. This keeps the parser state consistent and drops no samples. The loop still relies on the status register to terminate.
The driver does not document the hardware FIFO depth, so it is not known whether a working device can trigger this.
Found by static analysis tool CodeQL.
--- drivers/media/rc/fintek-cir.c | 4 ++++ 1 file changed, 4 insertions(+)
drivers/media/rc/fintek-cir.c +4 -0
@@ -340,6 +340,10 @@ static void fintek_get_rx_ir_data(struct sample =fintek_cir_reg_read (fintek,CIR_RX_DATA );fit_dbg ("%s: sample: 0x%02x" , __func__, sample); +/* Process a full buffer before storing the next sample. */ +if (fintek->pkts >=RX_BUF_LEN ) +fintek_process_rx_ir_data (fintek); + fintek->buf[fintek->pkts] = sample; fintek->pkts++;
Greg Kroah-Hartman
maintainerPATCH 261/1848 media: rc: mce_kbd: Fix inconsistent locking of keylock
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Young <[email protected]>
commit 29ee25fa9beb3232808e6d0b3e8ebfb0427cb820 upstream.
data->keylock is taken with spin_lock() in ir_mce_kbd_decode(), which runs in the raw IR decode kthread with local interrupts enabled, but with spin_lock_irqsave() in mce_kbd_rx_timeout(), the rx_timeout timer callback, which runs in softirq context.
If the decode kthread is holding keylock via spin_lock() when a timer interrupt fires on the same CPU and the softirq runs mce_kbd_rx_timeout(), the softirq spins forever waiting for a lock that only the now-preempted kthread can release, while the kthread cannot run again until the softirq gives up the CPU. This deadlocks the CPU.
--- drivers/media/rc/ir-mce_kbd-decoder.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/media/rc/ir-mce_kbd-decoder.c +3 -2
@@ -218,6 +218,7 @@ static int ir_mce_kbd_decode(struct rc_dstruct mce_kbd_dec *data = &dev->raw->mce_kbd;u32 scancode;unsigned long delay; +unsigned long flags;struct lirc_scancode lsc = {};if (!is_timing_event (ev)) {
@@ -318,7 +319,7 @@ again: scancode = data->body &0xffffff ;dev_dbg (&dev->dev,"keyboard data 0x%08x\n" , data->body); -spin_lock (&data->keylock); +spin_lock_irqsave (&data->keylock, flags);if (scancode) { delay =usecs_to_jiffies (dev->timeout) +msecs_to_jiffies (100 );
@@ -328,7 +329,7 @@ again: }/* Pass data to keyboard buffer parser */ ir_mce_kbd_process_keyboard_data (dev, scancode); -spin_unlock (&data->keylock); +spin_unlock_irqrestore (&data->keylock, flags); lsc.rc_proto =RC_PROTO_MCIR2_KBD ;break ;case MCIR2_MOUSE_NBITS :
Greg Kroah-Hartman
maintainerPATCH 262/1848 ocfs2/heartbeat: unlink live slots when their node is missing
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
commit 3ccd24c3f7a577b84a532cb027f1378385b82ef6 upstream.
o2hb_shutdown_slot() returns immediately when its node is no longer in the configfs registry. A slot can still be linked in o2hb_live_slots when that lookup fails. Region teardown or startup-error cleanup then frees the slot array without removing its embedded list member.
With the same peer live in another region, the next list update can follow a predecessor into the freed array. Reusing the node number can also make a later insertion encounter that stale member.
Always remove the slot under o2hb_live_lock, even when node lookup fails. Preserve aggregate membership accounting and the last-region DOWN
callback: the existing callback interface explicitly permits a NULL node for DOWN events. Only drop the node reference when lookup returned one. This closes both normal release and startup-abort paths without changing the publication or callback locking protocol.
Also require a configured node before admitting a new live slot in o2hb_check_slot(). The early live-bitmap check is not held through
admission: the last live slot in another region can be removed in between. Without a node, admission can then queue an UP event with a NULL argument and hit the event helper's BUG_ON. Existing live slots can still leave and generate NULL-node DOWN events.
A controlled probe-instrumented test reproduced this while stopping one of two regions after removing the peer from configfs. Its KASAN report includes:
BUG: KASAN: slab-use-after-free in __list_del_entry_valid_or_report+0x1e0/0x210 Read of size 8 at addr ffff888106a4ac60 by task o2hb-pmbd0058_b/497 Call Trace: <TASK> dump_stack_lvl+0x93/0xd0 print_report+0xce/0x630 kasan_report+0xe0/0x110 __list_del_entry_valid_or_report+0x1e0/0x210 o2hb_do_disk_heartbeat+0x1591/0x2c50 o2hb_thread+0x1ed/0xe70 kthread+0x351/0x460 ret_from_fork+0x659/0x940 ret_from_fork_asm+0x1a/0x30 </TASK> Allocated by task 491: kasan_save_stack+0x33/0x60 kasan_save_track+0x14/0x30 __kasan_kmalloc+0xaa/0xb0 __kmalloc_noprof+0x2de/0x780 o2hb_region_dev_store+0x7c2/0x1b60 configfs_write_iter+0x2f9/0x4f0 vfs_write+0x639/0x1010 ksys_write+0x111/0x200 do_syscall_64+0x114/0x620 entry_SYSCALL_64_after_hwframe+0x77/0x7f Freed by task 491: kasan_save_stack+0x33/0x60 kasan_save_track+0x14/0x30 kasan_save_free_info+0x3b/0x60 __kasan_slab_free+0x5f/0x80 kfree+0x308/0x580 o2hb_unmap_slot_data+0x1db/0x330 o2hb_region_release+0x14b/0x4f0 config_item_cleanup+0x14b/0x230 config_item_put+0x79/0x90 configfs_rmdir+0x58a/0x910 vfs_rmdir+0x2e8/0x820 filename_rmdir+0x3b1/0x520 __x64_sys_rmdir+0x4b/0x70 do_syscall_64+0x114/0x620 entry_SYSCALL_64_after_hwframe+0x77/0x7f
--- fs/ocfs2/cluster/heartbeat.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
fs/ocfs2/cluster/heartbeat.c +8 -4
@@ -822,8 +822,11 @@ static void o2hb_shutdown_slot(struct o2int queued =0 ; node =o2nm_get_node_by_num (slot->ds_node_num); -if (!node) -return ; +/* +* The node may have been removed from the node table while this +* region's slot is still linked. The list member must still be +* removed before the region releases its slot array. +*/ spin_lock (&o2hb_live_lock);if (!list_empty (&slot->ds_live_item)) {
@@ -845,7 +848,8 @@ static void o2hb_shutdown_slot(struct o2if (queued)o2hb_run_event_list (&event); -o2nm_node_put (node); +if (node) +o2nm_node_put (node); }static void o2hb_set_quorum_device (struct o2hb_region *reg)
@@ -980,7 +984,7 @@ static int o2hb_check_slot(struct o2hb_r fire_callbacks:/* dead nodes only come to life after some number of * changes at any time during their dead time */ -if (list_empty (&slot->ds_live_item) && +if (node &&list_empty (&slot->ds_live_item) && slot->ds_changed_samples >=O2HB_LIVE_THRESHOLD ) {mlog (ML_HEARTBEAT ,"Node %d (id 0x%llx) joined my region\n" , slot->ds_node_num, (long long )slot->ds_last_generation);
Greg Kroah-Hartman
maintainerPATCH 263/1848 ocfs2/dlm: hold a lock reference across grant AST enqueue
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
commit 71743471204e21113295c786e5cfa570294234a4 upstream.
A newly granted remote lock must remain alive until its grant AST is queued. dlmlock_master() publishes the lock on res->granted with its base and queue references, then drops res->spinlock before calling dlm_queue_ast(). The resource's reserved AST count does not retain the lock itself.
This can fail when a peer dies with an immediately grantable CREATE buffered on its socket. O2NET's node-down callback flushes receive work before DLM cleanup, but the flush only waits for work queued on entry. A data-ready callback that already selected the socket container can queue new receive work after the flush advances its work color. Socket shutdown does not discard bytes already queued for TCP receive.
The late receive work and DLM node-down cleanup can interleave as follows (the lock reference operations shown are before this fix):
Socket data-ready Node-down thread Receive worker ----------------- ---------------- --------------
o2net_data_ready()
select sc under
callback read lock
o2net_disconnect_node()
queue shutdown
begin flush; new color
queue sc_rx_work
in the new color
release callback lock
shutdown socket
flush returns
read buffered CREATE dlmlock_master()
lock res->spinlock add lock to granted unlock res->spinlock
DLM node-down cleanup
lock res->spinlock dlm_free_dead_locks()
unlink lock
put queue/base refs
free lock
unlock res->spinlock
dlm_queue_ast()
__dlm_queue_ast() read lock->lockres (use-after-free)
DLM cleanup holds res->spinlock while dlm_free_dead_locks() drops the queue and base references. The CREATE handler no longer holds that spinlock when __dlm_queue_ast() reads the lock, before taking its AST list reference.
Take a temporary lock reference under res->spinlock when a grant AST will be queued, and drop it after dlm_queue_ast(). This keeps the lock alive across cleanup until the AST path has taken its own reference, without reversing the existing AST/resource lock order.
KASAN report as below:
BUG: KASAN: slab-use-after-free in __dlm_queue_ast+0x8a4/0xc00
Read of size 8 at addr ffff88810ead5940 by task kworker/u16:3/52
CPU: 3 UID: 0 PID: 52 Comm: kworker/u16:3 Not tainted 7.3.0-rc4-next-20260921-pmb-bt-functional-v1+ #1 PREEMPT(lazy)
Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
Workqueue: o2net o2net_rx_until_empty
Call Trace:
<TASK>
dump_stack_lvl+0x93/0xd0
print_report+0xce/0x630
? __dlm_queue_ast+0x8a4/0xc00
? srso_alias_return_thunk+0x5/0xfbef5
? __virt_addr_valid+0x20e/0x420
? __dlm_queue_ast+0x8a4/0xc00
kasan_report+0xe0/0x110
? __dlm_queue_ast+0x8a4/0xc00
__dlm_queue_ast+0x8a4/0xc00
? srso_alias_return_thunk+0x5/0xfbef5
? srso_alias_return_thunk+0x5/0xfbef5
? do_raw_spin_lock+0x130/0x270
? __pfx___dlm_queue_ast+0x10/0x10
? __pfx_do_raw_spin_lock+0x10/0x10
? _raw_spin_unlock_irqrestore+0x45/0x60
? srso_alias_return_thunk+0x5/0xfbef5
? lockdep_hardirqs_on_prepare+0xeb/0x1a0
dlm_queue_ast+0x46/0x70
dlmlock_master+0x51f/0xf50
? __pfx_dlmlock_master+0x10/0x10
? dlm_create_lock_handler+0x2b2/0x870
? srso_alias_return_thunk+0x5/0xfbef5
? lock_release+0xc8/0x290
dlm_create_lock_handler+0x35b/0x870
? __pfx_dlm_create_lock_handler+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? srso_alias_return_thunk+0x5/0xfbef5
? trace_hardirqs_on+0x18/0x160
? srso_alias_return_thunk+0x5/0xfbef5
? kvm_clock_get_cycles+0x31/0x60
? srso_alias_return_thunk+0x5/0xfbef5
? __pfx_dlm_create_lock_handler+0x10/0x10
o2net_rx_until_empty+0x1dae/0x32c0
? reacquire_held_locks+0xdd/0x200
? __pfx_o2net_rx_until_empty+0x10/0x10
? lock_acquire+0x190/0x300
? process_one_work+0x935/0x1b40
? process_one_work+0x834/0x1b40
? srso_alias_return_thunk+0x5/0xfbef5
? lock_release+0xc8/0x290
? srso_alias_return_thunk+0x5/0xfbef5
process_one_work+0x9a8/0x1b40
? __pfx_process_one_work+0x10/0x10
? lock_acquire+0x190/0x300
? lock_is_held_type+0x8f/0x100
? srso_alias_return_thunk+0x5/0xfbef5
worker_thread+0x65c/0xe40
? srso_alias_return_thunk+0x5/0xfbef5
? __kthread_parkme+0x177/0x220
? srso_alias_return_thunk+0x5/0xfbef5
? __pfx_worker_thread+0x10/0x10
kthread+0x351/0x460
? srso_alias_return_thunk+0x5/0xfbef5
? __pfx_kthread+0x10/0x10
ret_from_fork+0x659/0x940
? __pfx_ret_from_fork+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? __switch_to+0x74f/0xf70
? __pfx_kthread+0x10/0x10
ret_from_fork_asm+0x1a/0x30
</TASK>
Allocated by task 52:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
__kasan_slab_alloc+0x89/0x90
kmem_cache_alloc_noprof+0x20b/0x5c0
dlm_new_lock+0x39/0x5f0
dlm_create_lock_handler+0x16e/0x870
o2net_rx_until_empty+0x1dae/0x32c0
process_one_work+0x9a8/0x1b40
worker_thread+0x65c/0xe40
kthread+0x351/0x460
ret_from_fork+0x659/0x940
ret_from_fork_asm+0x1a/0x30
Freed by task 603:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
kasan_save_free_info+0x3b/0x60
__kasan_slab_free+0x5f/0x80
kmem_cache_free+0x242/0x580
dlm_lock_release+0x1df/0x2f0
dlm_lock_put+0x51/0x80
__dlm_hb_node_down+0x15be/0x2710
dlm_hb_node_down_cb+0x6c/0xa0
o2hb_run_event_list+0x34a/0x500
o2hb_do_disk_heartbeat+0x1a07/0x2950
o2hb_thread+0x1ed/0xdc0
kthread+0x351/0x460
ret_from_fork+0x659/0x940
ret_from_fork_asm+0x1a/0x30
The buggy address belongs to the object at ffff88810ead5900
which belongs to the cache o2dlm_lock of size 184
The buggy address is located 64 bytes inside of
freed 184-byte region [ffff88810ead5900, ffff88810ead59b8)[Page and shadow memory dumps omitted.]
--- fs/ocfs2/dlm/dlmlock.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
fs/ocfs2/dlm/dlmlock.c +6 -2
@@ -140,6 +140,8 @@ static enum dlm_status dlmlock_master(st res->lockname.len)) { kick_thread = 1; call_ast = 1; + /* Keep the lock alive through AST enqueue. */ + dlm_lock_get(lock); } else { mlog(0, "%s: returning DLM_NORMAL to " "node %u for reco lock\n", dlm->name,
@@ -168,10 +170,12 @@ static enum dlm_status dlmlock_master(stwake_up (&res->wq);/* either queue the ast or release it */ -if (call_ast) +if (call_ast) {dlm_queue_ast (dlm, lock); -else +dlm_lock_put (lock); + }else {dlm_lockres_release_ast (dlm, res); + }dlm_lockres_calc_usage (dlm, res);if (kick_thread)
Greg Kroah-Hartman
maintainerPATCH 264/1848 ocfs2/dlm: hold the lookup reference across convert AST enqueue
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joseph Qi <[email protected]>
commit 125fe08ff6cfa064e1212f586f01993ee45c0330 upstream.
dlm_convert_lock_handler() drops the reference it took when it found the lock on res->granted at its leave label, one statement before it calls dlm_queue_ast(). dlm_free_dead_locks() takes res->spinlock and drops the list and base references, so a peer death landing in that gap leaves the handler's own put as the one that frees the lock, and __dlm_queue_ast() then reads lock->lockres from freed memory.
The handler is registered next to dlm_create_lock_handler(), so a convert message buffered on a dying peer's socket arrives on the same o2net receive work that o2net_disconnect_node() does not wait for. The two can interleave as follows, with the reference counts as they are before this fix:
Socket data-ready Node-down thread Receive worker ----------------- ---------------- --------------
o2net_data_ready()
select sc under
callback read lock
o2net_disconnect_node()
queue shutdown
begin flush; new color
queue sc_rx_work
in the new color
release callback lock
shutdown socket
flush returns
read buffered convert_lock dlm_convert_lock_handler()
find lock on res->granted dlm_lock_get() refs = 3 lock res->spinlock __dlmconvert_master()
call_ast = 1
unlock res->spinlock
DLM node-down cleanup
lock res->spinlock dlm_free_dead_locks()
unlink lock
put list ref refs = 2
put base ref refs = 1
unlock res->spinlock
dlm_lock_put() refs = 0
free lock
dlm_queue_ast()
__dlm_queue_ast() read lock->lockres (use-after-free)
__dlmconvert_master() only moves the lock between lists, so the count entering the gap is base, list and lookup. Drop the lookup reference after the AST is queued instead of before it and the race ends with the one __dlm_queue_ast() took, which dlm_flush_asts() releases later with ast_pending cleared and ast_list unlinked. No extra get is needed, and the normal case ends with the same count as before.
dlmconvert_master() has the same shape but is only reached from dlmlock() for a lock this node owns, which dlm_free_dead_locks() never matches.
--- fs/ocfs2/dlm/dlmconvert.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-)
fs/ocfs2/dlm/dlmconvert.c +7 -3
@@ -536,15 +536,19 @@ int dlm_convert_lock_handler(struct o2ne } leave: -if (lock) -dlm_lock_put (lock); -/* either queue the ast or release it, if reserved */ if (call_ast)dlm_queue_ast (dlm, lock);else if (ast_reserved)dlm_lockres_release_ast (dlm, res); +/* +* Keep the lock alive through AST enqueue: a concurrent +* dlm_free_dead_locks() drops the list and base references. +*/ +if (lock) +dlm_lock_put (lock); +if (kick_thread)dlm_kick_thread (dlm, res);
Greg Kroah-Hartman
maintainerPATCH 265/1848 ocfs2: cancel quota sync work before freeing quota info
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
commit 1dd1f005026d52642b994d63baa16b0b31f3b14f upstream.
OCFS2 quota info owns dqi_sync_work and must outlive both its timer and qsync_work_fn(). ocfs2_local_free_info() frees that owner without cancelling the work, relying on the quota suspend/disable wrappers.
Loading quotas on a read-only to read-write remount can successfully queue the work in ocfs2_global_read_info() and then fail while attaching a dquot to an existing inode in add_dquot_ref(). The quota core unwinds that failure directly through dquot_disable(), bypassing the OCFS2 wrapper:
Remount task (s_umount write) Timer/workqueue
ocfs2_global_read_info()
schedules dqi_sync_work
add_dquot_ref() returns an error
dquot_disable()
ocfs2_local_free_info()
frees oinfo
delayed-work timer expires qsync_work_fn() reads oinfo
The timer core can then write to the freed embedded timer, or qsync_work_fn() can read oinfo->dqi_gqinode before its s_umount trylock. The outer ocfs2_disable_quotas() cleanup skips the failed type because dquot_disable() has already cleared its loaded state.
Cancel dqi_sync_work synchronously at the start of ocfs2_local_free_info(), before dropping the global inode or freeing any owner state. The work is initialized whenever read_file_info() succeeds. dquot_disable() holds s_umount for write, so the callback skips its quota scan via down_read_trylock() and can finish without waiting for teardown. The synchronous cancel also handles its self-rearm.
KASAN report as below:
BUG: KASAN: slab-use-after-free in __run_timers+0x9e9/0xa10
Write of size 8 at addr ffff888111b0aad0 by task swapper/3/0
Call Trace:
<IRQ>
dump_stack_lvl+0x93/0xd0
print_report+0xce/0x630
? __run_timers+0x9e9/0xa10
? srso_alias_return_thunk+0x5/0xfbef5
? __virt_addr_valid+0x20e/0x420
? __run_timers+0x9e9/0xa10
kasan_report+0xe0/0x110
? __run_timers+0x9e9/0xa10
__run_timers+0x9e9/0xa10
? __pfx___run_timers+0x10/0x10
? __lock_acquire+0x5a3/0x2140
? __pfx_do_raw_spin_lock+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
timer_expire_remote+0xfa/0x160
? __pfx_timer_expire_remote+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? srso_alias_return_thunk+0x5/0xfbef5
? trace_hardirqs_on+0x18/0x160
tmigr_handle_remote_up+0x4ba/0x9d0
? __pfx_tmigr_handle_remote_up+0x10/0x10
? tmigr_handle_remote+0x21a/0x340
? srso_alias_return_thunk+0x5/0xfbef5
? lock_release+0xc8/0x290
? __pfx_tmigr_handle_remote_up+0x10/0x10
__walk_groups_from+0x5a/0x160
tmigr_handle_remote+0x24f/0x340
? __pfx_tmigr_handle_remote+0x10/0x10
? lock_acquire+0x190/0x300
? srso_alias_return_thunk+0x5/0xfbef5
? lock_release+0xc8/0x290
run_timer_softirq+0x222/0x270
? __pfx_run_timer_softirq+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? srso_alias_return_thunk+0x5/0xfbef5
? lockdep_hardirqs_on_prepare+0xb8/0x1a0
? srso_alias_return_thunk+0x5/0xfbef5
handle_softirqs+0x1fa/0x8d0
? __pfx_handle_softirqs+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? _raw_spin_unlock+0x23/0x40
? srso_alias_return_thunk+0x5/0xfbef5
? __hrtimer_rearm_deferred+0x1fb/0x5d0
__irq_exit_rcu+0x113/0x1e0
irq_exit_rcu+0xe/0x20
sysvec_apic_timer_interrupt+0x6c/0x80
</IRQ>
<TASK>
asm_sysvec_apic_timer_interrupt+0x1a/0x20
? ct_kernel_exit.constprop.0+0xc5/0xf0
? do_idle+0x3ae/0x650
default_idle+0x9/0x10
default_idle_call+0x6c/0xb0
do_idle+0x3ae/0x650
? cpuhp_online_idle+0x9c/0xb0
? __pfx_do_idle+0x10/0x10
? __entry_text_end+0x1020f6/0x1020f9
? lockdep_hardirqs_on_prepare+0xeb/0x1a0
? srso_alias_return_thunk+0x5/0xfbef5
? trace_hardirqs_on+0x18/0x160
? srso_alias_return_thunk+0x5/0xfbef5
cpu_startup_entry+0x54/0x60
start_secondary+0x223/0x2d0
? __pfx_start_secondary+0x10/0x10
common_startup_64+0x13e/0x158
</TASK>
Allocated by task 523:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
__kasan_kmalloc+0xaa/0xb0
__kmalloc_cache_noprof+0x28d/0x610
ocfs2_local_read_info+0x181/0x1580
dquot_load_quota_sb+0x69e/0x11c0
dquot_load_quota_inode+0x227/0x3e0
ocfs2_enable_quotas+0x27c/0x520
ocfs2_reconfigure+0x964/0xd00
reconfigure_super+0x3ca/0xa70
path_mount+0x141e/0x1e80
__x64_sys_mount+0x24b/0x2d0
do_syscall_64+0x114/0x620
entry_SYSCALL_64_after_hwframe+0x77/0x7f
Freed by task 523:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
kasan_save_free_info+0x3b/0x60
__kasan_slab_free+0x5f/0x80
kfree+0x308/0x580
ocfs2_local_free_info+0x47b/0x800
dquot_disable+0x5d9/0x17a0
dquot_load_quota_sb+0xd3c/0x11c0
dquot_load_quota_inode+0x227/0x3e0
ocfs2_enable_quotas+0x27c/0x520
ocfs2_reconfigure+0x964/0xd00
reconfigure_super+0x3ca/0xa70
path_mount+0x141e/0x1e80
__x64_sys_mount+0x24b/0x2d0
do_syscall_64+0x114/0x620
entry_SYSCALL_64_after_hwframe+0x77/0x7f
The buggy address belongs to the object at ffff888111b0a800
which belongs to the cache kmalloc-1k of size 1024
The buggy address is located 720 bytes inside of
freed 1024-byte region [ffff888111b0a800, ffff888111b0ac00)Host details, register and page dumps omitted.
--- fs/ocfs2/quota_local.c | 3 +++ 1 file changed, 3 insertions(+)
fs/ocfs2/quota_local.c +3 -0
@@ -813,6 +813,9 @@ static int ocfs2_local_free_info(structint mark_clean =1 , len;int status =0 ; +/* Quota-core error paths can bypass ocfs2_disable_quotas(). */ +cancel_delayed_work_sync (&oinfo->dqi_sync_work); +iput (oinfo->dqi_gqinode);ocfs2_simple_drop_lockres (OCFS2_SB (sb), &oinfo->dqi_gqlock);ocfs2_lock_res_free (&oinfo->dqi_gqlock);
Greg Kroah-Hartman
maintainerPATCH 266/1848 ocfs2: fix chunk number of the first chunk in a local quota file
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiaming Zhang <[email protected]>
commit 4effccfd50baee4f325694964aeee997dca7bd96 upstream.
Mounting a crafted OCFS2 image can corrupt kernel memory. When the local quota file header of such an image claims zero chunks, the first quota entry allocated during the mount gets a chunk number taken from a kernel pointer, and releasing that entry clears a bit far outside the chunk bitmap.
The write will corrupt the data stored at that address, and the corruption may lead to a system crash or damage unrelated data. Mounting requires CAP_SYS_ADMIN, so it takes an untrusted image, such as removable media or a loop mount of a file from elsewhere.
Since the chunk number comes from a kernel pointer, the address of the bit that gets cleared differs from boot to boot, and the issue has been reported under several titles:
- BUG: unable to handle kernel paging request in ocfs2_local_release_dquot
- KASAN: use-after-free Write in ocfs2_local_release_dquot
- KASAN: slab-out-of-bounds Write in ocfs2_local_release_dquot
- KASAN: slab-use-after-free Write in ocfs2_local_release_dquot
- KFENCE: use-after-free write in ocfs2_local_release_dquot
Note that none of these is a use-after-free in the quota code: the chunk and its buffer head are alive. The bit that gets cleared lies far outside the bitmap. KASAN and KFENCE name each report based on the object occupying that address, which explains why the same issue is reported under so many different titles. In the report I sent, the address fell in a free page, which KASAN labels use-after-free.
There are known reproducers. Both a syzkaller and a C reproducer are available from the Google Drive link [1] in my report thread. The issue was found by our modified syzkaller, not a theoretical thing found by an LLM. I have not seen it outside fuzzing, so it is not affecting me in the real world.
The local quota file in OCFS2 is divided into chunks, and each chunk begins with a header block holding a bitmap of the quota entries that chunk has handed out. Chunks are numbered from zero, and that number is used to convert the file offset of an entry back into a bit position in the bitmap. ocfs2_local_quota_add_chunk() appends a new chunk to the in-memory list and numbers it one past the chunk that was last:
list_add_tail(&chunk->qc_chunk, &oinfo->dqi_chunk); chunk->qc_num = list_entry(chunk->qc_chunk.prev, struct ocfs2_quota_chunk, qc_chunk)->qc_num + 1;
The predecessor is looked up after the new chunk is added to the list, so if the list was empty, the prev pointer is the list head itself. The head is the dqi_chunk member of struct ocfs2_mem_dqinfo and is not a chunk, so reading qc_num through it lands 16 bytes past the start of the head, on the dqi_gqinode pointer that follows it. The first chunk of the file is then numbered with the lower half of a kernel pointer instead of 0.
The list is empty when the local quota file header claims the file has no chunks. ocfs2_local_read_info() takes dqi_chunks from that header without validating it, so an image with dqi_chunks == 0 takes this path when the first quota entry is allocated.
ocfs2_create_local_dquot() turns the bad number into a file offset with ol_dqblk_off(), which shifts a 32-bit block number left by the block size bits, so the top bits of such a large block number are lost. ocfs2_local_release_dquot() turns the offset back into a bit index with ol_dqblk_chunk_off(), using the full chunk number, so the lost bits push that index far outside the bitmap, and clearing it corrupts unrelated memory.
Compute the chunk number before putting the chunk on the list, and use 0 when the list is empty.
--- fs/ocfs2/quota_local.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
fs/ocfs2/quota_local.c +6 -3
@@ -1071,10 +1071,13 @@ static struct ocfs2_quota_chunk *ocfs2_l goto out; } +if (list_empty (&oinfo->dqi_chunk)) + chunk->qc_num =0 ; +else + chunk->qc_num =list_entry (oinfo->dqi_chunk.prev, + struct ocfs2_quota_chunk, + qc_chunk)->qc_num +1 ;list_add_tail (&chunk->qc_chunk, &oinfo->dqi_chunk); - chunk->qc_num =list_entry (chunk->qc_chunk.prev, - struct ocfs2_quota_chunk, - qc_chunk)->qc_num +1 ; chunk->qc_headerbh = bh; *offset =0 ;return chunk;
Greg Kroah-Hartman
maintainerPATCH 267/1848 ocfs2: pin refcount trees before dropping the lookup lock
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
commit 8c714a074074af7ae59233c1fa6ef9d7aa710462 upstream.
A refcount tree returned to ocfs2_lock_refcount_tree() must stay alive until that caller releases its operation reference. However, ocfs2_get_refcount_tree() returns the cached pointer after dropping osb_lock, and the caller only takes its kref afterwards. The registry reference does not protect this gap from concurrent removal.
This can happen when another node frees a refcount root and reuses its block with a different generation while this mount retains the old cached tree. Two local operations on different inodes sharing the new root, such as data CoW and an external xattr update, can then look up the same stale tree. Their inode locks are independent, and both the REFCOUNT DLM lock and rf_sem are acquired after the first operation reference.
The following ordering is possible, with no other operation references:
Data CoW Xattr update
-------- ------------
Look up the old tree under
osb_lock, then drop osb_lock
Look up the same tree and take a kref Acquire the tree locks and read the
new on-disk generation
Erase the old tree under osb_lock Unlock and drop the operation kref Drop the registry kref, freeing tree
Take a kref through the
freed tree pointer
The final kref_get() accesses freed rf_getcnt storage, and subsequent accesses in ocfs2_lock_refcount_tree() also use the freed allocation.
Take the operation reference in ocfs2_get_refcount_tree() before releasing osb_lock, including when an insertion loses to another lookup. Removal must acquire the same lock, so it cannot drop the registry reference before the lookup has pinned the tree. Keep the existing unlock and error path puts. The two callers that already hold the refcount tree lock keep their borrowed lookup behavior and do not acquire an extra reference.
KASAN report as below:
BUG: KASAN: slab-use-after-free in ocfs2_lock_refcount_tree+0x94a/0x9b0
Read of size 4 at addr ffff888117212820 by task python3/497[Kernel and hardware identification omitted.]
Call Trace:
<TASK>
dump_stack_lvl+0x93/0xd0
print_report+0xce/0x630
? ocfs2_lock_refcount_tree+0x94a/0x9b0
? srso_alias_return_thunk+0x5/0xfbef5
? __virt_addr_valid+0x20e/0x420
? ocfs2_lock_refcount_tree+0x94a/0x9b0
kasan_report+0xe0/0x110
? ocfs2_lock_refcount_tree+0x94a/0x9b0
ocfs2_lock_refcount_tree+0x94a/0x9b0
? __pfx_ocfs2_lock_refcount_tree+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? ocfs2_refcount_cow+0x3b6/0xd90
? srso_alias_return_thunk+0x5/0xfbef5
? __kmalloc_cache_noprof+0x28d/0x610
? ocfs2_refcount_cow+0x3b6/0xd90
ocfs2_refcount_cow+0x410/0xd90
? __pfx_ocfs2_refcount_cow+0x10/0x10
? __pfx___might_resched+0x10/0x10
? down_write+0x11a/0x1f0
? __pfx_down_write+0x10/0x10
? ocfs2_inode_unlock+0x1a9/0x260
? __pfx_ocfs2_inode_unlock+0x10/0x10
? ocfs2_file_write_iter+0x1413/0x1d30
ocfs2_file_write_iter+0x157b/0x1d30
? __pfx_ocfs2_file_write_iter+0x10/0x10
? lock_acquire+0x190/0x300
? __x64_sys_pwrite64+0x1b7/0x220
? __pfx___might_resched+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? security_file_permission+0x26/0x80
? srso_alias_return_thunk+0x5/0xfbef5
? lock_is_held_type+0x8f/0x100
vfs_write+0x639/0x1010
? __pfx_ocfs2_file_write_iter+0x10/0x10
? lock_vma_under_rcu+0x154/0x4a0
? __pfx_vfs_write+0x10/0x10
? lock_release+0x121/0x290
? srso_alias_return_thunk+0x5/0xfbef5
__x64_sys_pwrite64+0x1b7/0x220
? __pfx___x64_sys_pwrite64+0x10/0x10
? irqentry_exit+0xbe/0x820
? srso_alias_return_thunk+0x5/0xfbef5
? trace_hardirqs_on_prepare+0x11d/0x150
? srso_alias_return_thunk+0x5/0xfbef5
do_syscall_64+0x114/0x620
entry_SYSCALL_64_after_hwframe+0x77/0x7f[Register dump omitted.]
</TASK>
Allocated by task 491:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
__kasan_kmalloc+0xaa/0xb0
__kmalloc_cache_noprof+0x28d/0x610
ocfs2_allocate_refcount_tree+0x49/0x1a0
ocfs2_create_refcount_tree+0x5d7/0x1630
ocfs2_attach_refcount_tree+0x57d/0x1100
__ocfs2_reflink.isra.0+0x1c4/0x1940
ocfs2_reflink+0x501/0x9b0
ocfs2_reflink_ioctl+0x6b2/0x920
ocfs2_ioctl+0x538/0x640
__x64_sys_ioctl+0x163/0x1d0
do_syscall_64+0x114/0x620
entry_SYSCALL_64_after_hwframe+0x77/0x7f
Freed by task 498:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
kasan_save_free_info+0x3b/0x60
__kasan_slab_free+0x5f/0x80
kfree+0x308/0x580
ocfs2_lock_refcount_tree+0x672/0x9b0
ocfs2_xattr_set+0x72c/0x2530
ocfs2_xattr_user_set+0xaf/0xf0
__vfs_setxattr+0x143/0x1b0
__vfs_setxattr_noperm+0x112/0x5b0
__vfs_setxattr_locked+0xfe/0x2b0
vfs_setxattr+0x13c/0x370
do_setxattr+0x128/0x170
filename_setxattr+0x147/0x190
path_setxattrat+0x1ac/0x260
__x64_sys_setxattr+0xcb/0x140
do_syscall_64+0x114/0x620
entry_SYSCALL_64_after_hwframe+0x77/0x7f
The buggy address belongs to the object at ffff888117212800
which belongs to the cache kmalloc-1k of size 1024
The buggy address is located 32 bytes inside of
freed 1024-byte region [ffff888117212800, ffff888117212c00)[Page and memory dumps omitted.]
--- fs/ocfs2/refcounttree.c | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-)
fs/ocfs2/refcounttree.c +9 -6
@@ -350,8 +350,10 @@ ocfs2_allocate_refcount_tree(struct ocfsreturn new; } +/* Callers without the refcount tree lock must request a reference. */ static int ocfs2_get_refcount_tree (struct ocfs2_super *osb,u64 rf_blkno, -struct ocfs2_refcount_tree **ret_tree) +struct ocfs2_refcount_tree **ret_tree, +bool get_ref) {int ret =0 ;struct ocfs2_refcount_tree *tree, *new =NULL ;
@@ -408,6 +410,8 @@ static int ocfs2_get_refcount_tree(struc new =NULL ; out: +if (get_ref) +ocfs2_refcount_tree_get (tree); *ret_tree = tree; osb->osb_ref_tree_lru = tree;
@@ -481,14 +485,12 @@ int ocfs2_lock_refcount_tree(struct ocfsstruct ocfs2_refcount_block *rb; again: - ret =ocfs2_get_refcount_tree (osb, ref_blkno, &tree); + ret =ocfs2_get_refcount_tree (osb, ref_blkno, &tree, true);if (ret) {mlog_errno (ret);return ret; } -ocfs2_refcount_tree_get (tree); - ret =__ocfs2_lock_refcount_tree (osb, tree, rw);if (ret) {mlog_errno (ret);
@@ -2332,7 +2334,8 @@ int ocfs2_decrease_refcount(struct inode goto out; } - ret =ocfs2_get_refcount_tree (OCFS2_SB (inode->i_sb), ref_blkno, &tree); + ret =ocfs2_get_refcount_tree (OCFS2_SB (inode->i_sb), ref_blkno, + &tree, false);if (ret) {mlog_errno (ret); goto out;
@@ -2567,7 +2570,7 @@ int ocfs2_prepare_refcount_change_for_deBUG_ON (!ocfs2_is_refcount_inode (inode)); ret =ocfs2_get_refcount_tree (OCFS2_SB (inode->i_sb), - refcount_loc, &tree); + refcount_loc, &tree, false);if (ret) {mlog_errno (ret); goto out;
Greg Kroah-Hartman
maintainerPATCH 268/1848 ovl: fix a torn path in ovl_get_redirect()
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit 2001cd7ca5560198131e46c6ca3c3472b06145c2 upstream.
A hard link of a metacopy file that races with a rename of an ancestor stores a redirect to the wrong lower file.
Each component of an absolute redirect must be the name that a dentry has in the parent that the walk continues with. ovl_get_redirect() copies the name under d_lock and calls dget_parent() after the unlock, and the callers for a hard link hold no lock that stops a rename across directories. A rename between the two steps combines the old name with the new parent.
With delays in ovl_get_redirect(), an unprivileged user hard-linked a metacopy file while renaming its ancestor to another directory, the stored redirect named another lower path, and after a remount the file showed the data of a root-only file.
Fix this by taking the parent first and checking it again under d_lock.
--- fs/overlayfs/dir.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)
fs/overlayfs/dir.c +13 -1
@@ -988,7 +988,19 @@ static char *ovl_get_redirect(struct denconst char *name;int thislen; +/* +* A rename can move d to another directory at any time. Hold +* d_lock to copy the name that d has in this very parent, or +* else the path mixes the old name with the new parent. +*/ + tmp =dget_parent (d);spin_lock (&d->d_lock); +if (unlikely (tmp != d->d_parent)) { +spin_unlock (&d->d_lock); +dput (tmp); +continue ; + } + name =ovl_dentry_get_redirect (d);if (name) { thislen =strlen (name);
@@ -1001,13 +1013,13 @@ static char *ovl_get_redirect(struct denif (thislen + (name[0 ] !='/' ) > buflen) { ret =ERR_PTR (-EXDEV );spin_unlock (&d->d_lock); +dput (tmp); goto out_put; } buflen -= thislen;memcpy (&buf[buflen], name, thislen);spin_unlock (&d->d_lock); - tmp =dget_parent (d);dput (d); d = tmp;
Greg Kroah-Hartman
maintainerPATCH 269/1848 ovl: read the nlink xattr of every indexed non-dir
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit eb644ed5c6d9afdb1554c41cef1f39d150fbc554 upstream.
With nfs_export=on, data written through a file handle to a lower file, i.e. a file that exists only in a lower layer of the overlay, can be lost on the next mount. A lookup of the file by name then returns -EIO. Also, a file with one name reports st_nlink 2 once it has been copied to the upper layer. After such a file is removed, its file handle can still open it until the next mount.
Before a lower file is changed for the first time, overlayfs copies it to the writable upper layer. This is called copy up.
The index directory is $workdir/index, where $workdir is the directory given by the workdir= option. Each entry is named after the file handle of a lower inode, so that overlayfs can get from the handle to the copied up inode.
With nfs_export=on, copy up indexes every non-directory: it copies the file to an entry in the index directory and then hard links that entry into the upper directory. The index entry is an extra link to the upper inode, so overlayfs stores the link count that users should see in the overlay.nlink xattr.
A file can also be opened by handle, either by an NFS client or by a process with CAP_DAC_READ_SEARCH calling open_by_handle_at(). If the file is not in the dcache, its overlay dentry is disconnected, i.e. it has no parent yet. Copy up then creates the index entry but no hard link in the upper directory. The index entry has i_nlink 1 and holds the only copy of the data written to the file.
ovl_get_nlink() reads the stored count. Its caller passes a default, which the function returns if there is no stored count. If the lower inode has i_nlink 1, the function returns the default without reading the xattr. That was correct as long as only lower files with multiple links were indexed.
On the next mount, ovl_verify_index() looks for orphans, i.e. index entries of files whose last name was removed. For an index entry with i_nlink 1, it passes a default of 0 to ovl_get_nlink() and treats a result of 0 as an orphan. Here the lower inode also has i_nlink 1, so the result is the default. ovl_indexdir_cleanup() then replaces the entry with a whiteout, which in the index marks a file as deleted. The written data is lost.
A lookup by name then returns -EIO, because a whiteout as the index entry of a lower file that still exists is a bad index.
ovl_get_inode() gets the wrong count the same way. Its default is the i_nlink of the upper inode, which includes the index entry, so a copied up file with one name reports st_nlink 2.
When that name is removed, the count drops to 1 rather than 0. ovl_nlink_end() replaces the index entry with a whiteout only at a count of 0, so the entry stays, and the handle of the removed file still opens it.
Reproduced by writing through open_by_handle_at() to an uncached lower file with one link. After a remount the data was lost, and the name returned EIO.
Fix this by adding an argument to ovl_get_nlink() that says whether the caller found an index entry, and by skipping the xattr only if the caller found none.
Known gaps:
- An index entry that a kernel without this patch left behind for a removed file now stays, and the handle of that file keeps working. The entry has i_nlink 1 and a stored count of 1, just like the entry of a file that was only written by handle. Without this patch, the next mount treated it as an orphan.
--- fs/overlayfs/inode.c | 14 +++++++++++--- fs/overlayfs/namei.c | 2 +- fs/overlayfs/overlayfs.h | 2 +- 3 files changed, 13 insertions(+), 5 deletions(-)
fs/overlayfs/inode.c +11 -3
@@ -742,7 +742,7 @@ int ovl_set_nlink_lower(struct dentry *d }unsigned int ovl_get_nlink (struct ovl_fs *ofs,struct dentry *lowerdentry, -struct dentry *upperdentry, +struct dentry *upperdentry,bool indexed,unsigned int fallback) {int nlink_diff;
@@ -750,7 +750,15 @@ unsigned int ovl_get_nlink(struct ovl_fschar buf[13 ];int err; -if (!lowerdentry || !upperdentry ||d_inode (lowerdentry)->i_nlink ==1 ) +if (!lowerdentry || !upperdentry) +return fallback; + +/* +* A lower inode with one link is not indexed on copy up, unless all +* files are indexed for NFS export. If the caller found an index entry, +* then the xattr holds the union nlink, whatever the lower nlink is. +*/ +if (!indexed &&d_inode (lowerdentry)->i_nlink ==1 )return fallback; err = ovl_do_getxattr(ofs, upperdentry, OVL_XATTR_NLINK,
@@ -1001,7 +1009,7 @@ struct inode *ovl_get_inode(struct super/* Recalculate nlink for non-dir due to indexing */ if (!is_dir) nlink =ovl_get_nlink (ofs, lowerdentry, upperdentry, - nlink); + oip->index, nlink);set_nlink (inode, nlink); ino = key->i_ino; }else {
fs/overlayfs/namei.c +1 -1
@@ -588,7 +588,7 @@ int ovl_verify_index(struct ovl_fs *ofs,if (err) goto fail; -if (ovl_get_nlink (ofs, origin.dentry, index,0 ) ==0 ) +if (ovl_get_nlink (ofs, origin.dentry, index, true,0 ) ==0 ) goto orphan; }
fs/overlayfs/overlayfs.h +1 -1
@@ -464,7 +464,7 @@ static inline bool ovl_dir_is_real(strucint ovl_set_nlink_upper (struct dentry *dentry);int ovl_set_nlink_lower (struct dentry *dentry);unsigned int ovl_get_nlink (struct ovl_fs *ofs,struct dentry *lowerdentry, -struct dentry *upperdentry, +struct dentry *upperdentry,bool indexed,unsigned int fallback);int ovl_setattr (struct dentry *dentry,struct iattr *attr); int ovl_getattr(const struct path *path, struct kstat *stat,
Greg Kroah-Hartman
maintainerPATCH 270/1848 xfs: check fork type against dabtree block magic number
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 43030b72a11a532e7e3c21ac84a8625425b4201b upstream.
LOLLM complains that we fail to flag dabtree blocks that should never be associated with the file fork -- data forks can't point to xattr leaves, and attr forks can't point to dirent blocks. Add the missing checks.
--- fs/xfs/scrub/dabtree.c | 12 ++++++++++++ 1 file changed, 12 insertions(+)
fs/xfs/scrub/dabtree.c +12 -0
@@ -392,6 +392,10 @@ xchk_da_btree_block( XFS_BLFT_ATTR_LEAF_BUF); blk->magic =XFS_ATTR_LEAF_MAGIC ; blk->hashval =xfs_attr_leaf_lasthash (blk->bp, pmaxrecs); +if (dargs->whichfork !=XFS_ATTR_FORK ) { +xchk_da_set_corrupt (ds, level); + goto out_freebp; + }if (ds->tree_level !=0 )xchk_da_set_corrupt (ds, level);break ;
@@ -401,6 +405,10 @@ xchk_da_btree_block( XFS_BLFT_DIR_LEAFN_BUF); blk->magic =XFS_DIR2_LEAFN_MAGIC ; blk->hashval =xfs_dir2_leaf_lasthash (ip, blk->bp, pmaxrecs); +if (dargs->whichfork !=XFS_DATA_FORK ) { +xchk_da_set_corrupt (ds, level); + goto out_freebp; + }if (ds->tree_level !=0 )xchk_da_set_corrupt (ds, level);break ;
@@ -410,6 +418,10 @@ xchk_da_btree_block( XFS_BLFT_DIR_LEAF1_BUF); blk->magic =XFS_DIR2_LEAF1_MAGIC ; blk->hashval =xfs_dir2_leaf_lasthash (ip, blk->bp, pmaxrecs); +if (dargs->whichfork !=XFS_DATA_FORK ) { +xchk_da_set_corrupt (ds, level); + goto out_freebp; + }if (ds->tree_level !=0 )xchk_da_set_corrupt (ds, level);break ;
Greg Kroah-Hartman
maintainerPATCH 271/1848 xfs: mark overfull dabtree node blocks as corrupt
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit f61c91a2e5994fa81141d6c06dadae1fed206018 upstream.
LOLLM observes that we need to range-check the dabtree node record count before using it to index an array. Fix that.
--- fs/xfs/scrub/dabtree.c | 4 ++++ 1 file changed, 4 insertions(+)
fs/xfs/scrub/dabtree.c +4 -0
@@ -433,6 +433,10 @@ xchk_da_btree_block( node = blk->bp->b_addr;xfs_da3_node_hdr_from_disk (ip->i_mount, &nodehdr, node); btree = nodehdr.btree; +if (nodehdr.count > dargs->geo->node_ents) { +xchk_da_set_corrupt (ds, level); + goto out_freebp; + } *pmaxrecs = nodehdr.count; blk->hashval =be32_to_cpu (btree[*pmaxrecs -1 ].hashval);if (level ==0 ) {
Greg Kroah-Hartman
maintainerPATCH 272/1848 net/sched: flower: Fix chain template offload
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ido Schimmel <[email protected]>
[ Upstream commit 32f2a0afa95fae0d1ceec2ff06e0e816939964b8 ]
When a qdisc is deleted from a net device the stack instructs the underlying driver to remove its flow offload callback from the associated filter block using the 'FLOW_BLOCK_UNBIND' command. The stack then continues to replay the removal of the filters in the block for this driver by iterating over the chains in the block and invoking the 'reoffload' operation of the classifier being used. In turn, the classifier in its 'reoffload' operation prepares and emits a 'FLOW_CLS_DESTROY' command for each filter.
However, the stack does not do the same for chain templates and the underlying driver never receives a 'FLOW_CLS_TMPLT_DESTROY' command when a qdisc is deleted. This results in a memory leak [1] which can be reproduced using [2].
Fix by introducing a 'tmplt_reoffload' operation and have the stack invoke it with the appropriate arguments as part of the replay. Implement the operation in the sole classifier that supports chain templates (flower) by emitting the 'FLOW_CLS_TMPLT_{CREATE,DESTROY}' command based on whether a flow offload callback is being bound to a filter block or being unbound from one.
As far as I can tell, the issue happens since cited commit which reordered tcf_block_offload_unbind() before tcf_block_flush_all_chains() in __tcf_block_put(). The order cannot be reversed as the filter block is expected to be freed after flushing all the chains.
[1]
unreferenced object 0xffff888107e28800 (size 2048):
comm "tc", pid 1079, jiffies 4294958525 (age 3074.287s) hex dump (first 32 bytes):
b1 a6 7c 11 81 88 ff ff e0 5b b3 10 81 88 ff ff ..|......[......
01 00 00 00 00 00 00 00 e0 aa b0 84 ff ff ff ff ................
backtrace:
[<ffffffff81c06a68>] __kmem_cache_alloc_node+0x1e8/0x320
[<ffffffff81ab374e>] __kmalloc+0x4e/0x90
[<ffffffff832aec6d>] mlxsw_sp_acl_ruleset_get+0x34d/0x7a0
[<ffffffff832bc195>] mlxsw_sp_flower_tmplt_create+0x145/0x180
[<ffffffff832b2e1a>] mlxsw_sp_flow_block_cb+0x1ea/0x280
[<ffffffff83a10613>] tc_setup_cb_call+0x183/0x340
[<ffffffff83a9f85a>] fl_tmplt_create+0x3da/0x4c0
[<ffffffff83a22435>] tc_ctl_chain+0xa15/0x1170
[<ffffffff838a863c>] rtnetlink_rcv_msg+0x3cc/0xed0
[<ffffffff83ac87f0>] netlink_rcv_skb+0x170/0x440
[<ffffffff83ac6270>] netlink_unicast+0x540/0x820
[<ffffffff83ac6e28>] netlink_sendmsg+0x8d8/0xda0
[<ffffffff83793def>] ____sys_sendmsg+0x30f/0xa80
[<ffffffff8379d29a>] ___sys_sendmsg+0x13a/0x1e0
[<ffffffff8379d50c>] __sys_sendmsg+0x11c/0x1f0
[<ffffffff843b9ce0>] do_syscall_64+0x40/0xe0
unreferenced object 0xffff88816d2c0400 (size 1024):
comm "tc", pid 1079, jiffies 4294958525 (age 3074.287s)
hex dump (first 32 bytes):
40 00 00 00 00 00 00 00 57 f6 38 be 00 00 00 00 @.......W.8.....
10 04 2c 6d 81 88 ff ff 10 04 2c 6d 81 88 ff ff ..,m......,m....
backtrace:
[<ffffffff81c06a68>] __kmem_cache_alloc_node+0x1e8/0x320
[<ffffffff81ab36c1>] __kmalloc_node+0x51/0x90
[<ffffffff81a8ed96>] kvmalloc_node+0xa6/0x1f0
[<ffffffff82827d03>] bucket_table_alloc.isra.0+0x83/0x460
[<ffffffff82828d2b>] rhashtable_init+0x43b/0x7c0
[<ffffffff832aed48>] mlxsw_sp_acl_ruleset_get+0x428/0x7a0
[<ffffffff832bc195>] mlxsw_sp_flower_tmplt_create+0x145/0x180
[<ffffffff832b2e1a>] mlxsw_sp_flow_block_cb+0x1ea/0x280
[<ffffffff83a10613>] tc_setup_cb_call+0x183/0x340
[<ffffffff83a9f85a>] fl_tmplt_create+0x3da/0x4c0
[<ffffffff83a22435>] tc_ctl_chain+0xa15/0x1170
[<ffffffff838a863c>] rtnetlink_rcv_msg+0x3cc/0xed0
[<ffffffff83ac87f0>] netlink_rcv_skb+0x170/0x440
[<ffffffff83ac6270>] netlink_unicast+0x540/0x820
[<ffffffff83ac6e28>] netlink_sendmsg+0x8d8/0xda0
[<ffffffff83793def>] ____sys_sendmsg+0x30f/0xa80[2]
# tc qdisc add dev swp1 clsact # tc chain add dev swp1 ingress proto ip chain 1 flower dst_ip 0.0.0.0/32 # tc qdisc del dev swp1 clsact # devlink dev reload pci/0000:06:00.0
--- include/net/sch_generic.h | 4 ++++ net/sched/cls_api.c | 9 ++++++++- net/sched/cls_flower.c | 23 +++++++++++++++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-)
include/net/sch_generic.h +4 -0
@@ -362,6 +362,10 @@ struct tcf_proto_ops {struct nlattr **tca, struct netlink_ext_ack *extack);void (*tmplt_destroy)(void *tmplt_priv); +void (*tmplt_reoffload)(struct tcf_chain *chain, +bool add, +flow_setup_cb_t *cb, +void *cb_priv);/* rtnetlink specific */ int (*dump)(struct net*, struct tcf_proto*, void *,
net/sched/cls_api.c +8 -1
@@ -1413,6 +1413,9 @@ tcf_block_playback_offloads(struct tcf_block *block, flow_setup_cb_t *cb, chain_prev = chain, chain = __tcf_get_next_chain(block, chain), tcf_chain_put(chain_prev)) { +if (chain->tmplt_ops && add) + chain->tmplt_ops->tmplt_reoffload (chain, true, cb, + cb_priv); for (tp = __tcf_get_next_proto(chain, NULL); tp; tp_prev = tp, tp = __tcf_get_next_proto(chain, tp),
@@ -1428,6 +1431,9 @@ tcf_block_playback_offloads(struct tcf_block *block, flow_setup_cb_t *cb, goto err_playback_remove; } } +if (chain->tmplt_ops && !add) + chain->tmplt_ops->tmplt_reoffload (chain, false, cb, + cb_priv); }return 0 ;
@@ -2773,7 +2779,8 @@ static int tc_chain_tmplt_add(struct tcf_chain *chain, struct net *net, ops =tcf_proto_lookup_ops (name, true, extack);if (IS_ERR (ops))return PTR_ERR (ops); -if (!ops->tmplt_create || !ops->tmplt_destroy || !ops->tmplt_dump) { +if (!ops->tmplt_create || !ops->tmplt_destroy || !ops->tmplt_dump || + !ops->tmplt_reoffload) {NL_SET_ERR_MSG (extack,"Chain templates are not supported with specified classifier" );module_put (ops->owner);return -EOPNOTSUPP ;
net/sched/cls_flower.c +23 -0
@@ -2414,6 +2414,28 @@ static void fl_tmplt_destroy(void *tmplt_priv)kfree (tmplt); } +static void fl_tmplt_reoffload (struct tcf_chain *chain,bool add, +flow_setup_cb_t *cb,void *cb_priv) +{ +struct fl_flow_tmplt *tmplt = chain->tmplt_priv; +struct flow_cls_offload cls_flower = {}; + + cls_flower.rule =flow_rule_alloc (0 ); +if (!cls_flower.rule) +return ; + + cls_flower.common.chain_index = chain->index; + cls_flower.command = add ?FLOW_CLS_TMPLT_CREATE : +FLOW_CLS_TMPLT_DESTROY ; + cls_flower.cookie = (unsigned long ) tmplt; + cls_flower.rule->match.dissector = &tmplt->dissector; + cls_flower.rule->match.mask = &tmplt->mask; + cls_flower.rule->match.key = &tmplt->dummy_key; + +cb (TC_SETUP_CLSFLOWER , &cls_flower, cb_priv); +kfree (cls_flower.rule); +} +static int fl_dump_key_val (struct sk_buff *skb,void *val,int val_type,void *mask,int mask_type,int len)
@@ -3219,6 +3241,7 @@ static struct tcf_proto_ops cls_fl_ops __read_mostly = { .bind_class = fl_bind_class, .tmplt_create = fl_tmplt_create, .tmplt_destroy = fl_tmplt_destroy, + .tmplt_reoffload = fl_tmplt_reoffload, .tmplt_dump = fl_tmplt_dump, .owner = THIS_MODULE, .flags = TCF_PROTO_OPS_DOIT_UNLOCKED,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 273/1848 ufs: fix ufs_read_cylinder() failure handling
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Al Viro <[email protected]>
commit 0bfd3e1078c537cd66a8addb1c01835de4234a4c upstream.
1) ufs_load_cylinder() should return NULL on ufs_read_cylinder() failures. ufs_error() is not enough. As it is, IO failure on attempt to read a part of cylinder group metadata is likely to end up with an oops.
2) we drop the wrong buffer heads when undoing sb_bread() on IO failure halfway through the read - we need to brelse() what we've got from sb_bread(), TYVM...
--- fs/ufs/cylinder.c | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-)
fs/ufs/cylinder.c +18 -13
@@ -26,7 +26,7 @@* Read cylinder group into cache. The memory space for ufs_cg_private_info * structure is already allocated during ufs_read_super. */ -static void ufs_read_cylinder (struct super_block * sb, +static bool ufs_read_cylinder (struct super_block *sb,unsigned cgno,unsigned bitmap_nr) {struct ufs_sb_info * sbi =UFS_SB (sb);
@@ -46,9 +46,11 @@ static void ufs_read_cylinder (struct super_block * sb,* We have already the first fragment of cylinder group block in buffer */ UCPI_UBH (ucpi)->bh[0 ] = sbi->s_ucg[cgno]; -for (i =1 ; i <UCPI_UBH (ucpi)->count; i++) -if (!(UCPI_UBH (ucpi)->bh[i] =sb_bread (sb,UCPI_UBH (ucpi)->fragment + i))) +for (i =1 ; i <UCPI_UBH (ucpi)->count; i++) { +UCPI_UBH (ucpi)->bh[i] =sb_bread (sb,UCPI_UBH (ucpi)->fragment + i); +if (!UCPI_UBH (ucpi)->bh[i]) goto failed; + } sbi->s_cgno[bitmap_nr] = cgno; ucpi->c_cgx =fs32_to_cpu (sb, ucg->cg_cgx);
@@ -77,13 +79,14 @@ static void ufs_read_cylinder (struct super_block * sb, goto failed; }UFSD ("EXIT\n" ); -return ; +return true; failed:for (j =1 ; j < i; j++) -brelse (sbi->s_ucg[j]); +brelse (UCPI_UBH (ucpi)->bh[j]); sbi->s_cgno[bitmap_nr] =UFS_CGNO_EMPTY ;ufs_error (sb,"ufs_read_cylinder" ,"can't read cylinder group block %u" , cgno); +return false; }/*
@@ -166,15 +169,14 @@ struct ufs_cg_private_info * ufs_load_cylinder (UFSD ("EXIT (FAILED)\n" );return NULL ; } -else { -UFSD ("EXIT\n" ); -return sbi->s_ucpi[cgno]; - } }else { -ufs_read_cylinder (sb, cgno, cgno); -UFSD ("EXIT\n" ); -return sbi->s_ucpi[cgno]; +if (unlikely (!ufs_read_cylinder (sb, cgno, cgno))) { +UFSD ("EXIT (FAILED)\n" ); +return NULL ; + } } +UFSD ("EXIT\n" ); +return sbi->s_ucpi[cgno]; }/* * Cylinder group number cg is in cache but it was not last used,
@@ -205,7 +207,10 @@ struct ufs_cg_private_info * ufs_load_cylinder ( sbi->s_ucpi[j] = sbi->s_ucpi[j-1 ]; } sbi->s_ucpi[0 ] = ucpi; -ufs_read_cylinder (sb, cgno,0 ); +if (unlikely (!ufs_read_cylinder (sb, cgno,0 ))) { +UFSD ("EXIT (FAILED)\n" ); +return NULL ; + } }UFSD ("EXIT\n" );return sbi->s_ucpi[0 ];
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 274/1848 media: usbtv: drop redundant device reference
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Johan Hovold <[email protected]>
[ Upstream commit dbc6798b80481a20f9aff671bc4d529eae63c9e8 ]
Driver core holds a reference to the USB interface and its parent USB device while the interface is bound to a driver and there is no need to take additional references unless the structures are needed after disconnect.
Drop the redundant device reference to reduce cargo culting, make it easier to spot drivers where an extra reference is needed, and reduce the risk of memory leaks when drivers fail to release it.
Stable-dep-of: cb705f75d03e ("media: usbtv: fix null-pointer dereference on disconnect")
--- drivers/media/usb/usbtv/usbtv-core.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-)
drivers/media/usb/usbtv/usbtv-core.c +1 -3
@@ -91,7 +91,7 @@ static int usbtv_probe(struct usb_interface *intf,if (usbtv ==NULL )return -ENOMEM ; usbtv->dev = dev; - usbtv->udev =usb_get_dev (interface_to_usbdev (intf)); + usbtv->udev =interface_to_usbdev (intf); usbtv->iso_size = size;
@@ -119,7 +119,6 @@ static int usbtv_probe(struct usb_interface *intf, usbtv_video_fail:usb_set_intfdata (intf,NULL ); -usb_put_dev (usbtv->udev);kfree (usbtv);return ret;
@@ -137,7 +136,6 @@ static void usbtv_disconnect(struct usb_interface *intf)usbtv_audio_free (usbtv);usbtv_video_free (usbtv); -usb_put_dev (usbtv->udev); usbtv->udev =NULL ;/* the usbtv structure will be deallocated when v4l2 will be
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 275/1848 media: usbtv: fix null-pointer dereference on disconnect
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aleksandr Nogikh <[email protected]>
[ Upstream commit cb705f75d03e946a4514488beb9e3bac9bcdb2e6 ]
A null-pointer dereference can occur in usb_make_path() when called from usbtv_querycap() (and other ioctl handlers) during device disconnection.
Oops: general protection fault, probably for non-canonical address 0xdffffc000000000a: 0000 [#1] SMP KASAN NOPTI KASAN: null-ptr-deref in range [0x0000000000000050-0x0000000000000057] RIP: 0010:usb_make_path include/linux/usb.h:985 [inline] RIP: 0010:usbtv_querycap+0x9c/0x100 drivers/media/usb/usbtv/usbtv-video.c:612 ... Call Trace: <TASK> v4l_querycap+0x236/0x470 drivers/media/v4l2-core/v4l2-ioctl.c:1106 __video_do_ioctl+0x8af/0xc70 drivers/media/v4l2-core/v4l2-ioctl.c:3133 video_usercopy+0x860/0x1430 drivers/media/v4l2-core/v4l2-ioctl.c:3475 v4l2_ioctl+0x18d/0x1e0 drivers/media/v4l2-core/v4l2-dev.c:366 vfs_ioctl fs/ioctl.c:51 [inline] __do_sys_ioctl fs/ioctl.c:597 [inline] __se_sys_ioctl+0xfc/0x170 fs/ioctl.c:583 do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline] do_syscall_64+0x174/0x580 arch/x86/entry/syscall_64.c:94
This happens due to a race condition between the USB device disconnect routine (usbtv_disconnect()) and V4L2 ioctls. When the device is disconnected, usbtv_disconnect() sets usbtv->udev = NULL without holding the usbtv->v4l2_lock mutex. Concurrently, an ioctl handler like usbtv_querycap() can be executing under the v4l2_lock and attempt to use usbtv->udev, leading to a crash.
To fix this, move the usbtv->udev = NULL assignment into usbtv_video_free() and protect it with mutex_lock(&usbtv->v4l2_lock). This ensures that no non-queue ioctl handler can run concurrently with the pointer being nullified. If an ioctl is already running, the mutex will block the disconnect path until the ioctl finishes. If an ioctl is blocked waiting for the lock, it will acquire it after the disconnect routine releases it, but will then check video_is_registered() (which was cleared by vb2_video_unregister_device()) and safely return -ENODEV.
Acquiring v4l2_lock after vb2_video_unregister_device() avoids reintroducing a historical deadlock issue, and usbtv_audio_free() remains safe as it is called before usbtv_video_free().
--- drivers/media/usb/usbtv/usbtv-core.c | 2 -- drivers/media/usb/usbtv/usbtv-video.c | 4 ++++ 2 files changed, 4 insertions(+), 2 deletions(-)
drivers/media/usb/usbtv/usbtv-core.c +0 -2
@@ -136,8 +136,6 @@ static void usbtv_disconnect(struct usb_interface *intf)usbtv_audio_free (usbtv);usbtv_video_free (usbtv); - usbtv->udev =NULL ; -/* the usbtv structure will be deallocated when v4l2 will be done using it */ v4l2_device_put (&usbtv->v4l2_dev);
drivers/media/usb/usbtv/usbtv-video.c +4 -0
@@ -966,5 +966,9 @@ void usbtv_video_free(struct usbtv *usbtv)vb2_video_unregister_device (&usbtv->vdev);v4l2_device_disconnect (&usbtv->v4l2_dev); +mutex_lock (&usbtv->v4l2_lock); + usbtv->udev =NULL ; +mutex_unlock (&usbtv->v4l2_lock); +v4l2_device_put (&usbtv->v4l2_dev); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 276/1848 xfs: reject out-of-range attribute value lengths in xfs_attr_copy_value
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aldo Ariel Panzardo <[email protected]>
commit 0643549ffecaeb716c0b75590a9b76dfa5eb35b3 upstream.
xfs_attr_copy_value() takes the value length as a signed int and, for a remote xattr, is handed args->rmtvaluelen. That field is filled from the on-disk __be32 xfs_attr_leaf_name_remote.valuelen in xfs_attr3_leaf_getvalue(), so a crafted length such as 0x80000000 is stored into the signed rmtvaluelen as a negative number.
The "buffer too small" guard in xfs_attr_copy_value() is a signed comparison:
if (args->valuelen < valuelen) return -ERANGE;
A negative valuelen therefore compares as smaller than the caller's buffer size, skips the -ERANGE path, and is then used as a copy length, leading to an out-of-bounds copy of a full remote block into a small getxattr(2) buffer on a mounted crafted image.
Reject a value length that is negative or larger than the maximum xattr size before it is used, so a bogus on-disk length can no longer slip through the value copier.
--- fs/xfs/libxfs/xfs_attr_leaf.c | 11 +++++++++++ 1 file changed, 11 insertions(+)
fs/xfs/libxfs/xfs_attr_leaf.c +11 -0
@@ -486,6 +486,17 @@ xfs_attr_copy_value( int valuelen) {/* +* A value length that is negative or larger than the maximum xattr +* size is on-disk corruption. The remote value length is an on-disk +* __be32 stored into the signed args->rmtvaluelen, so a crafted value +* such as 0x80000000 becomes negative and would slip past the +* "args->valuelen < valuelen" check below and be used as a copy +* length. Reject it before that can happen. +*/ +if (valuelen <0 || valuelen >XFS_XATTR_SIZE_MAX ) +return -EFSCORRUPTED ; + +/* * No copy if all we have to do is get the length */ if (!args->valuelen) {
Greg Kroah-Hartman
maintainerPATCH 277/1848 xfs: reject remote xattr entries with an out-of-range value length
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aldo Ariel Panzardo <[email protected]>
commit 15ccd92a782a0253f4a17895f3d3f71e5c1d1973 upstream.
xfs_attr3_leaf_verify_entry() validates a remote attribute entry's name but never bounds its on-disk value length (xfs_attr_leaf_name_remote. valuelen, a __be32). A crafted leaf with valuelen = 0x80000000 passes the verifier and the CRC.
That length is later assigned into the signed int args->rmtvaluelen (xfs_attr3_leaf_getvalue), becoming negative, which slips past the signed -ERANGE check in xfs_attr_copy_value(); a getxattr() with a small buffer then memcpy()s a full remote block into the small kvalue buffer (xfs_attr_rmtval_copyout) -- a heap out-of-bounds write with attacker-controlled content, from an unprivileged getxattr(2) on a mounted crafted image.
Reject remote entries whose value length exceeds XFS_XATTR_SIZE_MAX in the leaf verifier, so the malicious block is rejected at read time.
--- fs/xfs/libxfs/xfs_attr_leaf.c | 2 ++ 1 file changed, 2 insertions(+)
fs/xfs/libxfs/xfs_attr_leaf.c +2 -0
@@ -293,6 +293,8 @@ xfs_attr3_leaf_verify_entry(if (!(ent->flags &XFS_ATTR_INCOMPLETE ) && rentry->valueblk ==0 )return __this_address; +if (be32_to_cpu (rentry->valuelen) >XFS_XATTR_SIZE_MAX ) +return __this_address; }if (name_end > buf_end)
Greg Kroah-Hartman
maintainerPATCH 278/1848 xfs: check for fragments when full-extent sharing matches
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 95e213c1ddb40dfb0a8178ed35c9f29992a320e1 upstream.
LOLLM noticed that xchk_refcountbt_process_rmap_fragments returns early if there are enough rmap records that overlap the space referenced by a refcountbt record to match the refcount in that refcountbt record. Unfortunately, it never checks the fragment list in this case, so it won't find the discrepancy between the rmap and refcount btrees.
--- fs/xfs/scrub/refcount.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
fs/xfs/scrub/refcount.c +4 -1
@@ -157,8 +157,11 @@ xchk_refcountbt_process_rmap_fragments(xfs_nlink_t target_nr; target_nr = refchk->refcount - refchk->seen; -if (target_nr ==0 ) +if (target_nr ==0 ) { +if (!list_empty (&refchk->fragments)) + refchk->seen =0 ;return ; + }/* * There are (refchk->rc.rc_refcount - refchk->nr refcount)
Greg Kroah-Hartman
maintainerPATCH 279/1848 xfs: only written file data blocks can be shared
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 634b63baf05062988456a0bd5df2696c14ea2949 upstream.
LOLLM noticed that xchk_refcountbt_rmap_check (and its rt equivalent) will count any rmap owner towards the shared count. However, the only blocks that can be shared between xfs files are written file data blocks; and the only blocks that can have single-refcount entries are COW staging extents. Fix the checking code.
--- fs/xfs/scrub/refcount.c | 12 ++++++++++++ 1 file changed, 12 insertions(+)
fs/xfs/scrub/refcount.c +12 -0
@@ -112,6 +112,18 @@ xchk_refcountbt_rmap_check(return 0 ; } +/* +* The refcount btree should only have records for written file data +* blocks or for COW staging blocks. +*/ +if ((XFS_RMAP_NON_INODE_OWNER (rec->rm_owner) && + rec->rm_owner !=XFS_RMAP_OWN_COW ) || + (rec->rm_flags & (XFS_RMAP_ATTR_FORK |XFS_RMAP_BMBT_BLOCK | +XFS_RMAP_UNWRITTEN ))) { +xchk_btree_xref_set_corrupt (refchk->sc, cur,0 ); +return 0 ; + } +if (rec->rm_startblock <= refchk->bno && rm_last >= rc_last) {/* * The rmap overlaps the refcount record, so we can confirm
Greg Kroah-Hartman
maintainerPATCH 280/1848 xfs: opportunistically skip btree block checks
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit 4ce244b234c251963fca6dff9de6edf26a209d08 upstream.
LOLLM notices that both callers of xchk_btree_get_block will return early if *pblock is NULL after a successful return. However, xchk_btree_get_block itself can return 0 after flagging a corruption. There's no point in continuing after we've found a corruption, so null the pointer out.
--- fs/xfs/scrub/btree.c | 8 ++++++++ 1 file changed, 8 insertions(+)
fs/xfs/scrub/btree.c +8 -0
@@ -523,6 +523,14 @@ xchk_btree_get_block( level, *pbp);if (failed_at) {xchk_btree_set_corrupt (bs->sc, bs->cur, level); +/* +* The btree block fails basic checks, so we know it's corrupt. +* There's no need to continue looking for corruptions, so we +* null out pblock. If *pbp is non-null then it's also +* attached to the transaction so we won't leak it despite the +* 0 return code. +*/ + *pblock =NULL ;return 0 ; }if (*pbp)
Greg Kroah-Hartman
maintainerPATCH 281/1848 xfs: propagate errors while checking null siblings
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darrick J. Wong <[email protected]>
commit e5bde75a816b3549942f4b09a8bf09006b7ea9de upstream.
LOLLM observes that if xfs_da3_path_shift returns an error here, scrub doesn't handle it the way that it handles most runtime errors. Instead, it drops the error and keeps going, even though that's not how that's supposed to work. Fix that by calling xchk_da_process_error to set corruption flags and then jump out of the flow of execution.
--- fs/xfs/scrub/dabtree.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
fs/xfs/scrub/dabtree.c +3 -2
@@ -236,9 +236,10 @@ xchk_da_btree_block_check_sibling(if (sibling ==0 ) { error =xfs_da3_path_shift (ds->state, altpath, direction, false, &retval); -if (error ==0 && retval ==0 ) +if (!xchk_da_process_error (ds, level, &error)) + goto out; +if (retval ==0 )xchk_da_set_corrupt (ds, level); - error =0 ; goto out; }
Greg Kroah-Hartman
maintainerPATCH 282/1848 pNFS: Fix CB_NOTIFY_DEVICEID CHANGE to consume ndc_immediate
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Benjamin Coddington <[email protected]>
commit a0cb76dc3b2919af8257fc08b4f9a79a35442483 upstream.
decode_devicenotify_args() gated the trailing ndc_immediate on cbd_layout_type rather than cbd_notify_type, so the flag was never consumed and a multi-item cnda_changes<> misaligned after the first entry.
--- fs/nfs/callback_xdr.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/nfs/callback_xdr.c +1 -1
@@ -313,7 +313,7 @@ __be32 decode_devicenotify_args(struct smemcpy (dev->cbd_dev_id.data, p,NFS4_DEVICEID4_SIZE ); p +=XDR_QUADLEN (NFS4_DEVICEID4_SIZE ); -if (dev->cbd_layout_type ==NOTIFY_DEVICEID4_CHANGE ) { +if (dev->cbd_notify_type ==NOTIFY_DEVICEID4_CHANGE ) { p =xdr_inline_decode (xdr,sizeof (uint32_t ));if (unlikely (p ==NULL )) { status =htonl (NFS4ERR_BADXDR );
Greg Kroah-Hartman
maintainerPATCH 283/1848 pnfs/blocklayout: Complete a device upcall only on its own reply
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit acfbea6c5e27c68d6b6d12849eb2b7f8466ccf06 upstream.
bl_pipe_downcall() wakes bl_resolve_deviceid() on any write of the right size, without checking that blkmapd has read the upcall being replied to. A write that arrives first returns the waiter while its struct rpc_pipe_msg is still queued on the pipe, which then holds a list_head into a dead stack frame. Reaching the pipe takes root, so the trigger is a broken or hostile blkmapd.
The wait has two further defects. bl_resolve_deviceid() sets TASK_UNINTERRUPTIBLE only after rpc_queue_upcall() has made the message visible, so a reply that lands in between wakes a running task and the schedule() that follows sleeps forever holding bl_mutex. And nn->bl_mount_reply is never reset, so when the pipe purges an unread upcall the waiter takes the previous reply as its own.
Move the message into struct nfs_net, where bl_mutex already limits the pipe to one upcall per net namespace. Accept a reply only while blkmapd has read the whole message and no earlier reply has been taken, and reject any other write with -EINVAL. Wait for that reply on a completion so it cannot slip past the sleep, and check msg->errno before trusting it.
--- fs/nfs/blocklayout/blocklayout.h | 5 --- fs/nfs/blocklayout/rpc_pipefs.c | 58 ++++++++++++++++++++++++--------------- fs/nfs/netns.h | 5 ++- 3 files changed, 41 insertions(+), 27 deletions(-)
fs/nfs/blocklayout/blocklayout.h +0 -5
@@ -155,11 +155,6 @@ BLK_LSEG2EXT(struct pnfs_layout_segmentreturn BLK_LO2EXT (lseg->pls_layout); } -struct bl_pipe_msg { -struct rpc_pipe_msg msg; -wait_queue_head_t *bl_wq; -}; -struct bl_msg_hdr {u8 type;u16 totallen;/* length of entire message, including hdr itself */
fs/nfs/blocklayout/rpc_pipefs.c +37 -21
104 lines not on this page · raw message
fs/nfs/netns.h +4 -1
@@ -10,6 +10,8 @@#include <net/net_namespace.h> #include <net/netns/generic.h> #include <linux/sunrpc/stats.h> +#include <linux/sunrpc/rpc_pipe_fs.h> +#include <linux/completion.h> struct bl_dev_msg {int32_t status;
@@ -21,8 +23,9 @@ struct nfs_netns_client;struct nfs_net {struct cache_detail *nfs_dns_resolve;struct rpc_pipe *bl_device_pipe; +struct rpc_pipe_msg bl_pipe_msg;struct bl_dev_msg bl_mount_reply; -wait_queue_head_t bl_wq; +struct completion bl_done;struct mutex bl_mutex;struct list_head nfs_client_list;struct list_head nfs_volume_list;
Greg Kroah-Hartman
maintainerPATCH 284/1848 pnfs/blocklayout: Complete a device upcall when the pipe is closed
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit 2a25cc8e984610828a526086313b8a7aeefe507d upstream.
Once blkmapd has read a whole upcall, rpc_pipe_read() unlinks the message from every pipe list, so the purges in rpc_pipe_release() and rpc_close_pipes() no longer reach it. bl_upcall_ops supplies no .release_pipe callback, and bl_pipe_destroy_msg() returns without completing the upcall because a downcall is expected to follow. A daemon that exits between the read and the write therefore strands its waiter: bl_resolve_deviceid() sleeps in wait_for_completion() and never returns, and it holds nn->bl_mutex across that wait, so every later device resolution in the net namespace blocks behind it.
Add a .release_pipe that completes an upcall blkmapd has consumed and left unanswered. Completing an upcall retires it, so a message the framework has already purged is no longer in flight and is not completed a second time here.
--- fs/nfs/blocklayout/rpc_pipefs.c | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+)
fs/nfs/blocklayout/rpc_pipefs.c +21 -0
@@ -152,10 +152,31 @@ static void bl_pipe_destroy_msg(struct rcomplete (&nn->bl_done); } +/* +* An upcall blkmapd has consumed is off every pipe list, so the +* purges in rpc_pipe_release() and rpc_close_pipes() cannot reach it. +* No downcall can arrive once the pipe is closed; release its waiter +* here. +*/ +static void bl_release_pipe (struct inode *inode) +{ +struct nfs_net *nn =net_generic (inode->i_sb->s_fs_info, nfs_net_id); +struct rpc_pipe *pipe = nn->bl_device_pipe; + +spin_lock (&pipe->lock); +if (rpc_msg_is_inflight (&nn->bl_pipe_msg)) { + nn->bl_pipe_msg.copied =0 ; + nn->bl_pipe_msg.errno = -EPIPE ; +complete (&nn->bl_done); + } +spin_unlock (&pipe->lock); +} +static const struct rpc_pipe_ops bl_upcall_ops = { .upcall = rpc_pipe_generic_upcall, .downcall = bl_pipe_downcall, .destroy_msg = bl_pipe_destroy_msg, + .release_pipe = bl_release_pipe, }; static struct dentry *nfs4blocklayout_register_sb(struct super_block *sb,
Greg Kroah-Hartman
maintainerPATCH 285/1848 NFSv4.1/pnfs: suspend pNFS on NFS4ERR_TOOSMALL from LAYOUTGET
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Benjamin Coddington <[email protected]>
commit 28c950413605fb5b6cb3863c5e3274ea69701097 upstream.
If the layout for the requested range is larger than the size the client advertised in loga_maxcount, RFC 8881 Section 18.43.3 has the metadata server return NFS4ERR_TOOSMALL. The client caps loga_maxcount at a single page, so a flexfiles server that stripes a layout segment across several dozen data servers produces this error today.
The client has no handling for it: nfs4_stat_to_errno() maps the error to -ETOOSMALL during decode, which nothing in the layoutget path recognizes and nfs_error_is_fatal() does not consider fatal, so pnfs_update_layout() clears the layout fail bit and returns no segment. The I/O falls back to the MDS, but because no fail bit was set, every subsequent pageio attempt sends another LAYOUTGET that is doomed to the same NFS4ERR_TOOSMALL. Files whose layouts do not fit the reply buffer never use pNFS and pay an extra round trip on every pageio.
Map -ETOOSMALL to -EMSGSIZE in the layoutget exception handler and have pnfs_update_layout() treat it like NFS4ERR_LAYOUTUNAVAILABLE:
mark the layout mode as failed and fall back to I/O through the MDS.
--- fs/nfs/nfs4proc.c | 8 ++++++++ fs/nfs/pnfs.c | 2 ++ 2 files changed, 10 insertions(+)
fs/nfs/nfs4proc.c +8 -0
@@ -9452,6 +9452,14 @@ nfs4_layoutget_handle_exception(struct r status = -EOVERFLOW ; goto out;/* +* NFS4ERR_TOOSMALL means the layout for the requested range +* exceeds what the client advertised in loga_maxcount (see +* RFC8881 section 18.43.3). +*/ +case -ETOOSMALL : + status = -EMSGSIZE ; + goto out; +/* * NFS4ERR_LAYOUTTRYLATER is a conflict with another client * (or clients) writing to the same RAID stripe except when * the minlength argument is 0 (see RFC5661 section 18.43.3).
fs/nfs/pnfs.c +2 -0
@@ -2174,6 +2174,8 @@ lookup_again:break ;case -ENODATA :/* The server returned NFS4ERR_LAYOUTUNAVAILABLE */ +case -EMSGSIZE : +/* The layout exceeded loga_maxcount (NFS4ERR_TOOSMALL) */ pnfs_layout_set_fail_bit ( lo,pnfs_iomode_to_fail_bit (iomode)); lseg =NULL ;
Greg Kroah-Hartman
maintainerPATCH 286/1848 NFSv4/filelayout: Anchor page coalescing on pattern_offset
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Benjamin Coddington <[email protected]>
commit 7f2d221b01f356b6bb3bb6efef998f8b28339824 upstream.
filelayout_pg_test() bounds page coalescing to a single stripe unit using an offset relative to pls_range.offset, but the data server is selected by nfs4_fl_calc_j_index() using an offset relative to pattern_offset. When a segment's pattern_offset and range offset are not congruent modulo the stripe unit, the coalescing window is shifted off the DS-selection grid, so a coalesced I/O can straddle a stripe boundary and send the bytes past it to the wrong data server.
Anchor coalescing on pattern_offset to match nfs4_fl_calc_j_index(). Stripe-congruent segments, including the common whole-file pattern_offset 0 case, are unchanged.
--- fs/nfs/filelayout/filelayout.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
fs/nfs/filelayout/filelayout.c +4 -4
@@ -802,7 +802,7 @@ filelayout_pg_test(struct nfs_pageio_desunsigned int size;u64 p_stripe, r_stripe;u32 stripe_offset; -u64 segment_offset = pgio->pg_lseg->pls_range.offset; +u64 pattern_offset =FILELAYOUT_LSEG (pgio->pg_lseg)->pattern_offset;u32 stripe_unit =FILELAYOUT_LSEG (pgio->pg_lseg)->stripe_unit;/* calls nfs_generic_pg_test */
@@ -814,8 +814,8 @@ filelayout_pg_test(struct nfs_pageio_des/* see if req and prev are in the same stripe */ if (prev) { - p_stripe = (u64 )req_offset (prev) - segment_offset; - r_stripe = (u64 )req_offset (req) - segment_offset; + p_stripe = (u64 )req_offset (prev) - pattern_offset; + r_stripe = (u64 )req_offset (req) - pattern_offset;do_div (p_stripe, stripe_unit);do_div (r_stripe, stripe_unit);
@@ -824,7 +824,7 @@ filelayout_pg_test(struct nfs_pageio_des }/* calculate remaining bytes in the current stripe */ -div_u64_rem ((u64 )req_offset (req) - segment_offset, +div_u64_rem ((u64 )req_offset (req) - pattern_offset, stripe_unit, &stripe_offset);WARN_ON_ONCE (stripe_offset > stripe_unit);
Greg Kroah-Hartman
maintainerPATCH 287/1848 nfsd: clear XDR padding in GETXATTR replies
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aldo Ariel Panzardo <[email protected]>
commit daba58690339ae86f1ebeb5197aa1369fae37e57 upstream.
nfsd4_vbuf_to_stream() uses a raw memcpy() for the first fragment of an attribute value. xdr_reserve_space() aligns the reservation but does not initialize the extra bytes. If the complete value fits in that fragment, the loop that clears padding for the final fragment is never entered.
A remote client reading an attribute whose length is not a multiple of four can therefore receive one to three stale bytes from the response page.
Encode the first fragment with xdr_encode_opaque_fixed(), matching the final-fragment path and ensuring that any XDR padding is zeroed.
--- fs/nfsd/nfs4xdr.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/nfsd/nfs4xdr.c +1 -1
@@ -5044,7 +5044,7 @@ nfsd4_vbuf_to_stream(struct xdr_stream *if (!p)return nfserr_resource; -memcpy (p, buf, cplen); +xdr_encode_opaque_fixed (p, buf, cplen); buf += cplen; buflen -= cplen;
Greg Kroah-Hartman
maintainerPATCH 288/1848 NFSD: copy SETXATTR data from all XDR buffer segments
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aldo Ariel Panzardo <[email protected]>
commit b01319947c69b0e3ea0fcd4b675eb892f9cad8a0 upstream.
nfsd4_vbuf_from_vector() manually copies the head followed by whole pages starting at offset zero. This assumes that all remaining data starts at the beginning of the page array and that no data is stored in the tail.
However, nfsd4_decode_setxattr() passes an xdr_buf returned by xdr_stream_subsegment(). Such a sub-buffer can have a nonzero page_base and can span its page and tail segments. Ignoring that layout can copy the wrong bytes into the value passed to vfs_setxattr().
Use read_bytes_from_xdr_buf(), which observes the complete xdr_buf layout.
--- fs/nfsd/nfs4xdr.c | 19 +++---------------- 1 file changed, 3 insertions(+), 16 deletions(-)
fs/nfsd/nfs4xdr.c +3 -16
@@ -2117,10 +2117,8 @@ static __be32 nfsd4_vbuf_from_vector(struct nfsd4_compoundargs *argp, struct xdr_buf *xdr, char **bufp, u32 buflen) { - struct page **pages = xdr->pages; struct kvec *head = xdr->head; -char *tmp, *dp; -u32 len; +char *tmp;if (buflen <= head->iov_len) {/*
@@ -2135,19 +2133,8 @@ nfsd4_vbuf_from_vector(struct nfsd4_compif (tmp ==NULL )return nfserr_jukebox; - dp = tmp; -memcpy (dp, head->iov_base, head->iov_len); - buflen -= head->iov_len; - dp += head->iov_len; - -while (buflen >0 ) { - len =min_t (u32, buflen,PAGE_SIZE ); -memcpy (dp,page_address (*pages), len); - - buflen -= len; - dp += len; - pages++; - } +if (read_bytes_from_xdr_buf (xdr,0 , tmp, buflen)) +return nfserr_bad_xdr; *bufp = tmp;return 0 ;
Greg Kroah-Hartman
maintainerPATCH 289/1848 NFSD: Do not send CB_RECALL_ANY to NFSv4.0 clients
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit 95ff0c079b9cab91f2327beb4197a3bc48c71f55 upstream.
deleg_reaper() sends CB_RECALL_ANY to every ACTIVE client holding delegations, but CB_RECALL_ANY is an NFSv4.1 operation. An NFSv4.0 client's callback service accepts only CB_GETATTR and CB_RECALL, so it replies OP_ILLEGAL. The decoder maps the unexpected opnum to -EIO, and nfsd4_cb_done() marks the client's callback channel down.
Nothing brings the channel back. nfsd4_run_cb_work() sets NFSD4_CB_UP only for a minor version above zero, and the only nfsd4_probe_callback() call site an NFSv4.0 client reaches is nfsd4_setclientid_confirm(). One visit from the reaper therefore leaves the channel marked down until the client re-establishes its clientid. RENEW then returns NFS4ERR_CB_PATH_DOWN for as long as the client holds delegations. nfsd4_cb_channel_good() stops returning true, so the client is granted no further delegations.
Skip clients at minor version zero.
--- fs/nfsd/nfs4state.c | 2 ++ 1 file changed, 2 insertions(+)
fs/nfsd/nfs4state.c +2 -0
@@ -6390,6 +6390,8 @@ deleg_reaper(struct nfsd_net *nn)list_for_each_safe (pos, next, &nn->client_lru) { clp = list_entry(pos, struct nfs4_client, cl_lru); +if (clp->cl_minorversion ==0 ) +continue ;if (clp->cl_state !=NFSD4_ACTIVE )continue ;if (list_empty (&clp->cl_delegations))
Greg Kroah-Hartman
maintainerPATCH 290/1848 NFSD: Dont complete a cld upcall the daemon has not read
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit 7f4bf851aca4e18940ebf2bddf4ba6783802ee81 upstream.
cld_pipe_downcall() matches a reply to its upcall on the xid alone. A write that arrives before the daemon has read that upcall completes __cld_pipe_upcall() while its struct rpc_pipe_msg is still queued on the pipe. The waiter returns, its stack frame goes away, and the pipe keeps a list_head that points into it. The next rpc_queue_upcall() walks that pointer:
BUG: KASAN: vmalloc-out-of-bounds in __list_add_valid_or_report Read of size 8 at addr ffffc90007027950 by task syz.0.96/13066 __list_add_valid_or_report+0x6a/0x130 rpc_queue_upcall cld_pipe_upcall nfsd4_cld_grace_start nfsd4_cld_tracking_init
The pipe is mode 0600 in rpc_pipefs, so the trigger is a broken or hostile nfsdcld rather than an unprivileged task.
Record whether the daemon has consumed the whole message and complete only when it has. cld_pipe_destroy_msg() runs on every path by which the pipe releases a message, so it can maintain that flag under cn_lock. nfsdcld sends its -EINPROGRESS downcalls only after reading the upcall, so the new check does not break the GraceStart record stream.
--- fs/nfsd/nfs4recover.c | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-)
fs/nfsd/nfs4recover.c +20 -3
@@ -718,6 +718,8 @@ struct cld_upcall {struct list_head cu_list;struct cld_net *cu_net;struct completion cu_done; +/* daemon has read the whole upcall; protected by cn_lock */ +bool cu_inflight;union {struct cld_msg_hdr cu_hdr;struct cld_msg cu_msg;
@@ -877,6 +879,13 @@ cld_pipe_downcall(struct file *filp, conspin_lock (&cn->cn_lock);list_for_each_entry (tmp, &cn->cn_list, cu_list) {if (get_unaligned (&tmp->cu_u.cu_hdr.cm_xid) == xid) { +/* +* Completing now would return the waiter +* while its message is still queued on the +* pipe. +*/ +if (!tmp->cu_inflight) +break ; cup = tmp;if (status != -EINPROGRESS )list_del_init (&cup->cu_list);
@@ -885,9 +894,9 @@ cld_pipe_downcall(struct file *filp, con }spin_unlock (&cn->cn_lock); -/* couldn't find upcall? */ +/* no upcall to complete? */ if (!cup) { -dprintk ("%s: couldn't find upcall -- xid=%u\n" , __func__, xid); +dprintk ("%s: no completable upcall -- xid=%u\n" , __func__, xid);return -EINVAL ; }
@@ -907,8 +916,16 @@ cld_pipe_destroy_msg(struct rpc_pipe_msgstruct cld_msg *cmsg = msg->data; struct cld_upcall *cup = container_of(cmsg, struct cld_upcall, cu_u.cu_msg); +struct cld_net *cn = cup->cu_net; + +/* +* errno >= 0 means the daemon read the whole message and a +* downcall will complete the upcall. +*/ +spin_lock (&cn->cn_lock); + cup->cu_inflight = msg->errno >=0 ; +spin_unlock (&cn->cn_lock); -/* errno >= 0 means we got a downcall */ if (msg->errno >=0 )return ;
Greg Kroah-Hartman
maintainerPATCH 291/1848 nfsd: dont modify a session slot when replaying its cached reply
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ameer Hamza <[email protected]>
commit 2987838317501ff67b672ac2a441fe34b7729f3d upstream.
nfsd4_sequence() claims a session slot by setting NFSD4_SLOT_INUSE under nn->client_lock. A reply served from the slot's reply cache does not claim it, and that distinction lived only in cstate->status, which nfsd4_sequence() set to nfserr_replay_cache. Commit cc028a10a48c ("NFSD: Hoist status code encoding into XDR encoder functions") moved nfsd4_proc_compound()'s cstate->status assignment below the out:
label, and the replay path's goto out was the one path that relied on skipping it. The test in nfsd4_sequence_done() therefore no longer identifies a replay, and every replay now stores its reply and clears NFSD4_SLOT_INUSE as though it owned the slot.
NFSD4_SLOT_INUSE is the interlock: check_slot_seqid() rejects every sequence id for a slot that is in use, before replay_matches_cache() runs. A replay never sets it, so two replays can be in flight on the same slot at once. One can read slot->sl_cred under nn->client_lock while the other's completion frees and rebuilds it from the XDR encoder without that lock. Two completions can also collide with each other and release the same group_info twice. free_svc_cred() leaves cr_uid, cr_gid and cr_flavor intact, so the reader passes every earlier test in same_creds() and dereferences a NULL cr_group_info.
Quoted 1 line
From a 6.12.91 production server:
BUG: kernel NULL pointer dereference, address: 0000000000000004 CPU: 63 UID: 0 PID: 39015 Comm: nfsd RIP: 0010:same_creds+0x38/0xa0 [nfsd] RDX: 0000000000000000 Call Trace: nfsd4_sequence+0x6a8/0x910 [nfsd] nfsd4_proc_compound+0x345/0x670 [nfsd] nfsd_dispatch+0x100/0x220 [nfsd] svc_process_common+0x311/0x700 [sunrpc] svc_process+0x131/0x1c0 [sunrpc] svc_recv+0x7ef/0x9c0 [sunrpc] nfsd+0xa3/0x100 [nfsd] Kernel panic - not syncing: Fatal exception
Since v6.14 a live session's slot table can shrink, and the unowned store becomes a use-after-free write. nfsd4_sequence() defers the shrink while a slot is in use, but it tests NFSD4_SLOT_INUSE, which a replay does not set, so free_session_slots() can kfree() the slot the replay still holds in cstate->slot.
Record the claim in cstate->slot_owned when nfsd4_sequence() accepts a request and test that in nfsd4_sequence_done(), so only the request that claimed the slot updates its cached reply and clears NFSD4_SLOT_INUSE. svc_generic_init_request() zeroes the compound response before each request, so the flag starts clear.
--- fs/nfsd/nfs4state.c | 7 ++++++- fs/nfsd/xdr4.h | 1 + 2 files changed, 7 insertions(+), 1 deletion(-)
fs/nfsd/nfs4state.c +6 -1
@@ -4138,6 +4138,7 @@ nfsd4_sequence(struct svc_rqst *rqstp, s slot->sl_flags &= ~NFSD4_SLOT_CACHETHIS ; cstate->slot = slot; + cstate->slot_owned = true; cstate->session = session; cstate->clp = clp;
@@ -4170,7 +4171,11 @@ nfsd4_sequence_done(struct nfsd4_compounstruct nfsd4_compound_state *cs = &resp->cstate;if (nfsd4_has_session (cs)) { -if (cs->status != nfserr_replay_cache) { +/* +* Only the request that claimed the slot may update its +* cached reply and clear NFSD4_SLOT_INUSE. +*/ +if (cs->slot_owned) {nfsd4_store_cache_entry (resp); cs->slot->sl_flags &= ~NFSD4_SLOT_INUSE ; }
fs/nfsd/xdr4.h +1 -0
@@ -60,6 +60,7 @@ struct nfsd4_compound_state {struct nfsd4_slot *slot;int data_offset;bool spo_must_allowed; +bool slot_owned;size_t iovlen;u32 minorversion;__be32 status;
Greg Kroah-Hartman
maintainerPATCH 292/1848 NFSD: Fail a pool_threads read whose reply does not fit
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit e27c63245903402ccfdb46c576462981a7e032e3 upstream.
The reply to a pool_threads read is the list of per-pool thread counts, formatted into a buffer of SIMPLE_TRANSACTION_LIMIT bytes. snprintf() truncates its last write and strlen() measures only what fit, so a reply too long for that buffer ends mid-number with no terminating newline. A pool running 4096 threads is reported as 40. Nothing marks the reply as incomplete, so an administrator reads a plausible but wrong count.
Take snprintf()'s return value, which reports the truncation strlen() cannot see, and fail the read with -ENAMETOOLONG when the list does not fit. That is the errno svc_one_xprt_name() already returns for the same condition.
--- fs/nfsd/nfsctl.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
fs/nfsd/nfsctl.c +8 -4
@@ -460,7 +460,7 @@ static ssize_t write_pool_threads(structchar *mesg = buf;int i;int rv; -int len; +size_t len;int npools;int *nthreads;struct net *net =netns (file);
@@ -505,9 +505,13 @@ static ssize_t write_pool_threads(struct mesg = buf; size =SIMPLE_TRANSACTION_LIMIT ; -for (i =0 ; i < npools && size >0 ; i++) { -snprintf (mesg, size,"%d%c" , nthreads[i], (i == npools-1 ?'\n' :' ' )); - len =strlen (mesg); +for (i =0 ; i < npools; i++) { + len =snprintf (mesg, size,"%d%c" , nthreads[i], + (i == npools -1 ?'\n' :' ' )); +if (len >= size) { + rv = -ENAMETOOLONG ; + goto out_free; + } size -= len; mesg += len; }
Greg Kroah-Hartman
maintainerPATCH 293/1848 nfsd: Fix id-to-name cache entry leak in idtoname_parse()
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Wentao Liang <[email protected]>
commit 8ca3b74c0c447af17d0e27e76658a3d4cae3c5ba upstream.
idtoname_lookup() returns the id-to-name cache entry with a new reference. The name is parsed between the lookup and the update call, and when the parsed name is malformed (negative length or longer than IDMAP_NAMESZ), idtoname_parse() jumps to the error label without dropping the reference returned by idtoname_lookup(), leaking the cache entry.
Release the reference with cache_put() before taking the error exit.
--- fs/nfsd/nfs4idmap.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
fs/nfsd/nfs4idmap.c +3 -1
@@ -252,8 +252,10 @@ idtoname_parse(struct cache_detail *cd,/* Name */ error = -EINVAL ; len =qword_get (&buf, buf1,PAGE_SIZE ); -if (len <0 || len >=IDMAP_NAMESZ ) +if (len <0 || len >=IDMAP_NAMESZ ) { +cache_put (&res->h, cd); goto out; + }if (len ==0 )set_bit (CACHE_NEGATIVE , &ent.h.flags);else
Greg Kroah-Hartman
maintainerPATCH 294/1848 nfsd: hold cl_lock in client_has_openowners()
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang (Microsoft Security FORGE Labs) <[email protected]>
commit 5336899b5491eaa2ac22c2925d87daab2b140eb3 upstream.
client_has_openowners() walks clp->cl_openowners and reads so_stateids without clp->cl_lock. nfs4_put_stateowner() unhashes that openowner under cl_lock and then frees it, so a concurrent EXCHANGE_ID with mismatched creds can use-after-free the nfs4_openowner.
BUG: KASAN: slab-use-after-free in client_has_state+0x10a/0x140 fs/nfsd/nfs4state.c:3718 client_has_openowners() nfsd4_exchange_id nfsd4_proc_compound nfsd_dispatch svc_process
Take clp->cl_lock while client_has_openowners() walks the openowner list.
--- fs/nfsd/nfs4state.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-)
fs/nfsd/nfs4state.c +9 -3
@@ -3331,12 +3331,18 @@ nfsd4_set_ex_flags(struct nfs4_client *nstatic bool client_has_openowners (struct nfs4_client *clp) {struct nfs4_openowner *oo; +bool found = false; +spin_lock (&clp->cl_lock);list_for_each_entry (oo, &clp->cl_openowners, oo_perclient) { -if (!list_empty (&oo->oo_owner.so_stateids)) -return true; +if (!list_empty (&oo->oo_owner.so_stateids)) { + found = true; +break ; + } } -return false; +spin_unlock (&clp->cl_lock); + +return found; }static bool client_has_state (struct nfs4_client *clp)
Greg Kroah-Hartman
maintainerPATCH 295/1848 nfsd: honour client-provided attributes for NFS4_CREATE_EXCLUSIVE4_1
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: NeilBrown <[email protected]>
commit ddfabbc7840891e09cd500ab97c9cd36b650ec24 upstream.
When a file is created with a v4.1 OPEN which requests NFS4_CREATE_EXCLUSIVE4_1, the request can include attributes to be set. However when the mtime/atime are set to hold the verifier, the other ia_valid flags are cleared, so no attributes requested by the client are used.
This code was originally written for NFSv3 where NFS3_CREATE_EXCLUSIVE never includes attributes. When it was updated for v4.1, the fact that an exclusive create CAN include attributes was not handled properly.
--- fs/nfsd/nfs4proc.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
fs/nfsd/nfs4proc.c +2 -2
@@ -357,8 +357,8 @@ nfsd4_create_file(struct svc_rqst *rqstpif ((iap->ia_valid &ATTR_SIZE ) && (iap->ia_size ==0 )) iap->ia_valid &= ~ATTR_SIZE ;if (nfsd4_create_is_exclusive (open->op_createmode)) { - iap->ia_valid =ATTR_MTIME |ATTR_ATIME | -ATTR_MTIME_SET |ATTR_ATIME_SET ; + iap->ia_valid |=ATTR_MTIME |ATTR_ATIME | +ATTR_MTIME_SET |ATTR_ATIME_SET ; iap->ia_mtime.tv_sec = v_mtime; iap->ia_atime.tv_sec = v_atime; iap->ia_mtime.tv_nsec =0 ;
Greg Kroah-Hartman
maintainerPATCH 296/1848 nfsd: preflight SEQUENCE replies before accepting a slot
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jérémy Jean <[email protected]>
commit 35ff1a7a7e3835c3e974bc5c45d335897564ceae upstream.
nfsd4_sequence() narrows the reply buffer to the session's cached reply limit before it accepts the slot seqid. A client may negotiate ca_maxresponsesize_cached down to NFSD_MIN_HDR_SEQ_SZ, and nfsd4_alloc_slot() then gives every slot a zero-length sl_data[]. A COMPOUND tag can fill that narrowed buffer until it holds the SEQUENCE opcode but not the status word that follows. nfsd4_encode_operation() returns without running nfsd4_encode_sequence(), so cstate.data_offset stays zero. It leaves op->status at nfs_ok as well, so the COMPOUND is treated as having succeeded.
nfsd4_store_cache_entry() declines to cache a lone SEQUENCE that returned an error. That test reads the status the operation reported, so it passes here. The copy starts at offset zero and takes the whole reply, RPC and COMPOUND headers included, into the zero-length sl_data[]. The COMPOUND tag is copied along with it, so the client picks most of the bytes written past the end of the slot:
BUG: KASAN: slab-out-of-bounds in read_bytes_from_xdr_buf+0x1bc/0x390 Write of size 80 at addr ffff888003a549cd by task kunit_try_catch/24 __asan_memcpy+0x38/0x60 read_bytes_from_xdr_buf+0x1bc/0x390 nfsd4_sequence_done+0x5b0/0x810 nfs4svc_encode_compoundres+0x1bf/0x240
Check that the fixed-size SEQUENCE result, plus room for a following operation's error status, fits the negotiated limit before narrowing the buffer and consuming the slot seqid. The slot and its reply cache are left unchanged, as RFC 8881 Section 2.10.6.1.2 requires of an error returned from SEQUENCE.
--- fs/nfsd/nfs4state.c | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-)
fs/nfsd/nfs4state.c +18 -1
@@ -4050,6 +4050,7 @@ __be32 nfsd4_sequence(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, union nfsd4_op_u *u) { + struct nfsd4_compoundargs *args = rqstp->rq_argp;struct nfsd4_sequence *seq = &u->sequence;struct nfsd4_compoundres *resp = rqstp->rq_resp;struct xdr_stream *xdr = resp->xdr;
@@ -4059,6 +4060,7 @@ nfsd4_sequence(struct svc_rqst *rqstp, sstruct nfsd4_conn *conn;__be32 status;int buflen; +u32 maxlen, respsize;struct net *net =SVC_NET (rqstp);struct nfsd_net *nn =net_generic (net, nfsd_net_id);
@@ -4130,7 +4132,22 @@ nfsd4_sequence(struct svc_rqst *rqstp, s session->se_fchannel.maxresp_sz; status = (seq->cachethis) ? nfserr_rep_too_big_to_cache : nfserr_rep_too_big; -if (xdr_restrict_buflen (xdr, buflen - rqstp->rq_auth_slack)) +if (buflen < rqstp->rq_auth_slack) + goto out_put_session; + maxlen = buflen - rqstp->rq_auth_slack; + +/* +* A SEQUENCE result too large for maxlen never reaches +* nfsd4_encode_sequence(), so cstate.data_offset stays zero and +* the reply cache overruns the slot. +*/ + respsize =nfsd4_max_reply (rqstp, &args->ops[0 ]); +if (!nfsd4_last_compound_op (rqstp)) + respsize +=COMPOUND_ERR_SLACK_SPACE ; +if (xdr->buf->len + respsize > maxlen) + goto out_put_session; + +if (xdr_restrict_buflen (xdr, maxlen)) goto out_put_session;svc_reserve (rqstp, buflen);
Greg Kroah-Hartman
maintainerPATCH 297/1848 nfsd: propagate SETXATTR value decode errors
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aldo Ariel Panzardo <[email protected]>
commit cfcfe0b38a66bbc4122c78a2b75e1b97b3534761 upstream.
nfsd4_decode_setxattr() stores the status returned while assembling a non-empty attribute value, but then unconditionally returns nfs_ok. An allocation failure can therefore leave a NULL value buffer paired with a non-zero length and allow compound processing to continue.
Return the decoder status so that the operation stops on the original error.
--- fs/nfsd/nfs4xdr.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/nfsd/nfs4xdr.c +1 -1
@@ -2251,7 +2251,7 @@ nfsd4_decode_setxattr(struct nfsd4_compo &setxattr->setxa_buf, size); } -return nfs_ok; +return status; } static __be32
Greg Kroah-Hartman
maintainerPATCH 298/1848 NFSD: Reject an oversized principal hash from nfsdcld
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit dbed9418c48906dae1a7bc328fb3bc0d0d0020c8 upstream.
__cld_pipe_inprogress_downcall() takes the principal hash length from the daemon's GraceStart downcall without checking it against the cc_princhash payload it describes, which holds at most SHA256_DIGEST_SIZE bytes. The length is stored verbatim in the reclaim record, and nfsd4_cld_check_v2() later hands it to memcmp() against a digest array of SHA256_DIGEST_SIZE bytes on the stack. A length up to U8_MAX reads past the end of that array, and the stray bytes can only make the comparison fail, denying the client its reclaim. The pipe is mode 0600 in rpc_pipefs, so the trigger is a broken or hostile nfsdcld rather than an unprivileged task.
Reject a length larger than the wire field, as the existing check on the client name length does.
--- fs/nfsd/nfs4recover.c | 5 +++++ 1 file changed, 5 insertions(+)
fs/nfsd/nfs4recover.c +5 -0
@@ -800,6 +800,11 @@ __cld_pipe_inprogress_downcall(const str name.len = namelen;if (get_user (princhashlen, &ci->cc_princhash.cp_len))return -EFAULT ; +if (princhashlen >SHA256_DIGEST_SIZE ) { +dprintk ("%s: invalid princhashlen (%u)" , + __func__, princhashlen); +return -EINVAL ; + }if (princhashlen >0 ) { princhashcopy = memdup_user( &ci->cc_princhash.cp_data,
Greg Kroah-Hartman
maintainerPATCH 299/1848 nfsd: zero NFSv4 COMPOUND tag padding
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aldo Ariel Panzardo <[email protected]>
commit 3f1181cb09c85499286c7f462d93530b0ebcafcc upstream.
nfs4svc_encode_compoundres() copies the tag bytes into reserved XDR space and skips directly to the aligned end of the field. xdr_reserve_space() rounds the reservation up but does not initialize the padding bytes.
A remote client can choose a tag length that is not a multiple of four, causing one to three stale bytes from the response page to be returned in the COMPOUND reply.
Use xdr_encode_opaque_fixed() to copy the tag and clear its XDR padding.
--- fs/nfsd/nfs4xdr.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
fs/nfsd/nfs4xdr.c +1 -2
@@ -5545,8 +5545,7 @@ nfs4svc_encode_compoundres(struct svc_rq rqstp->rq_next_page = xdr->page_ptr +1 ; *p++ =htonl (resp->taglen); -memcpy (p, resp->tag, resp->taglen); - p +=XDR_QUADLEN (resp->taglen); + p =xdr_encode_opaque_fixed (p, resp->tag, resp->taglen); *p++ =htonl (resp->opcnt);nfsd4_sequence_done (resp);
Greg Kroah-Hartman
maintainerPATCH 300/1848 SUNRPC: keep the first error in svc_register()
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jeff Layton <[email protected]>
commit 9ed91d7c4698e611ea5bfca45076008def831fb3 upstream.
svc_register() assigns every pg_rpcbind_set() result to the same "error" variable and returns the last one, so a later result erases an earlier failure.
Keep the first error instead of the last.
--- net/sunrpc/svc.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
net/sunrpc/svc.c +6 -3
@@ -1100,13 +1100,16 @@ int svc_register(const struct svc_serv *for (progp = serv->sv_program; progp; progp = progp->pg_next) {for (i =0 ; i < progp->pg_nvers; i++) { +int ret; - error = progp->pg_rpcbind_set (net, progp, i, + ret = progp->pg_rpcbind_set (net, progp, i, family, proto, port); -if (error <0 ) { +if (ret <0 ) {printk (KERN_WARNING "svc: failed to register " "%sv%u RPC service (errno %d).\n" , - progp->pg_name, i, -error); + progp->pg_name, i, -ret); +if (!error) + error = ret;break ; } }
Greg Kroah-Hartman
maintainerPATCH 301/1848 sunrpc: pin gss module across auth_domain RCU free
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
commit b64d21116374688c33302a6704387c27d1156d72 upstream.
A gss auth_domain stores a raw pointer to svcauthops_gss in dom->flavour, and its release queues svcauth_gss_domain_release_rcu() via call_rcu(). Both live in auth_rpcgss.ko text, and nothing pins the module while a domain referencing it is reachable. rmmod auth_rpcgss can therefore unmap that text while an NFSD export still holds a reference to the domain.
The export cache is one such holder. When the export is finally released, the domain reference drops from module text:
svc_export_put()
auth_domain_put(exp->ex_client)
auth_domain_release()
dom->flavour->domain_release(dom) /* into module text */
svcauth_gss_domain_release()
call_rcu(&dom->rcu_head,
svcauth_gss_domain_release_rcu)Once auth_rpcgss is unloaded, the domain_release call lands in unmapped memory. The rcu_barrier() in exit_rpcsec_gss() does not
help: it waits only for callbacks already queued, and this one is not queued until the export goes away.
NFSD's NFSv4 objects import symbols from auth_rpcgss.ko, so only a server built without CONFIG_NFSD_V4 can unload auth_rpcgss while exports still name a gss domain.
Take a module reference in svcauth_gss_register_pseudoflavor() before publishing the domain and drop it at the end of svcauth_gss_domain_release_rcu(). The rcu_barrier() then holds the module image until this callback has returned.
--- net/sunrpc/auth_gss/svcauth_gss.c | 8 ++++++++ 1 file changed, 8 insertions(+)
net/sunrpc/auth_gss/svcauth_gss.c +8 -0
@@ -845,12 +845,18 @@ svcauth_gss_register_pseudoflavor(u32 ps new->h.flavour = &svcauthops_gss; new->pseudoflavor = pseudoflavor; +if (!try_module_get (svcauthops_gss.owner)) { + stat = -ENODEV ; + goto out_free_name; + } + test =auth_domain_lookup (name, &new->h);if (test != &new->h) {pr_warn ("svc: duplicate registration of gss pseudo flavour %s.\n" , name); stat = -EADDRINUSE ;auth_domain_put (test); +module_put (svcauthops_gss.owner); goto out_free_name; }return test;
@@ -1897,9 +1903,11 @@ svcauth_gss_domain_release_rcu(struct rc { struct auth_domain *dom = container_of(head, struct auth_domain, rcu_head); struct gss_domain *gd = container_of(dom, struct gss_domain, h); +struct module *owner = dom->flavour->owner;kfree (dom->name);kfree (gd); +module_put (owner); } static void
Greg Kroah-Hartman
maintainerPATCH 302/1848 SUNRPC: Reject a socket that already has an svc_sock attached
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chuck Lever <[email protected]>
commit 0995447b8059c4d23853cdcddbe789c4a2b6bb88 upstream.
Writing the same socket descriptor to /proc/fs/nfsd/portlist twice attaches a second svc_sock to one socket. svc_setup_socket() saves the socket's callbacks before installing its own, so the second attach records svc_write_space() as the old write_space callback. svc_udp_init() invokes that callback by way of svc_sock_setbufsize(), and svc_write_space() then calls itself until the kernel stack is exhausted:
BUG: TASK stack guard page was hit at ffffc900037d7ff8 svc_write_space+0x90/0x2b0 net/sunrpc/svcsock.c:429 svc_write_space+0xe6/0x2b0 net/sunrpc/svcsock.c:430 ... 700 more ... svc_sock_setbufsize+0x18d/0x220 net/sunrpc/svcsock.c:386 svc_udp_init net/sunrpc/svcsock.c:854 [inline] svc_setup_socket+0xb2f/0x1090 net/sunrpc/svcsock.c:1498 svc_addsock+0x2fd/0x760 net/sunrpc/svcsock.c:1547 __write_ports_addfd fs/nfsd/nfsctl.c:742 [inline] write_ports+0xa5b/0xcc0 fs/nfsd/nfsctl.c:861 nfsctl_transaction_write+0x106/0x1a0 fs/nfsd/nfsctl.c:112
svc_data_ready() and svc_tcp_state_change() chain through their saved callbacks the same way, so a TCP descriptor added twice recurses on the next incoming segment instead. Reaching any of this takes a writer on portlist, and the nfsd filesystem sets no FS_USERNS_MOUNT, so the reproducer needs CAP_SYS_ADMIN in the initial user namespace.
Reject a socket that already carries sk_user_data. svc_setup_socket() overwrites that field unconditionally, so a socket some other consumer has claimed is one NFSD would corrupt whether or not the callbacks recurse.
--- net/sunrpc/svcsock.c | 3 +++ 1 file changed, 3 insertions(+)
net/sunrpc/svcsock.c +3 -0
@@ -1380,6 +1380,9 @@ int svc_addsock(struct svc_serv *serv, s err = -EISCONN ;if (so->state >SS_UNCONNECTED ) goto out; + err = -EBUSY ; +if (so->sk->sk_user_data) + goto out; err = -ENOENT ;if (!try_module_get (THIS_MODULE )) goto out;
Greg Kroah-Hartman
maintainerPATCH 303/1848 sunrpc: treat empty auth.unix.gid replies as negative entries
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ameer Hamza <[email protected]>
commit a12cc0930235b86b934ade7c077a1935c2ac333d upstream.
When rpc.mountd cannot resolve a uid (getpwuid() or getgrouplist() failure, e.g. while winbind or sssd is briefly unreachable), it answers the auth.unix.gid upcall with zero groups. unix_gid_parse() installs that as a valid positive entry, and svcauth_unix_set_client() then replaces the credential's group list with the empty one on every request, RPCSEC_GSS included via svcauth_gss_set_client(). One failed lookup strips that uid of all supplementary groups on every export for up to mountd's configured TTL (30 minutes by default), long after the NSS backend has recovered.
mountd cannot send an empty list for a successful lookup, since getgrouplist(3) always includes at least the user's primary group, so a zero-group reply can only mean the lookup failed. Record it as a negative entry: unix_gid_find() then returns -ENOENT and svcauth_unix_set_client() keeps the groups the RPC credential already carries. This is the fallback that
commit 3fc605a2aa38 ("[PATCH] knfsd: allow the server to provide a gid list when using AUTH_UNIX authentication") promised when no answer is available, and the same state try_to_negate_entry() already creates when no listener holds the channel open.
--- net/sunrpc/svcauth_unix.c | 7 +++++++ 1 file changed, 7 insertions(+)
net/sunrpc/svcauth_unix.c +7 -0
@@ -544,6 +544,13 @@ static int unix_gid_parse(struct cache_dif (ugp) {struct cache_head *ch; ug.h.flags =0 ; +/* +* mountd sends at least the user's primary group on +* success, so an empty list can only mean the lookup +* failed. Keep the credential's own groups instead. +*/ +if (gids ==0 ) +set_bit (CACHE_NEGATIVE , &ug.h.flags); ug.h.expiry_time = expiry; ch = sunrpc_cache_update(cd, &ug.h, &ugp->h,
Greg Kroah-Hartman
maintainerPATCH 304/1848 KVM: x86: Zero reserved synic flags when delivering message to avoid stack leak
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
commit 2616f497506a772db53e7bb1024cde50b4c165e0 upstream.
Ensure all reserved flags are zeroed when setting the msg_pending flag as part of SynIC message delivery, as setting only msg_pending can leak seven bits of kernel stack data to the guest. E.g. gcc typically uses a bitwise-OR to set the msg_pending flag, without initializing the on-stack variable.
Precisely zero the flags, e.g. as opposed to zeroing the entire structure, to make it somewhat more obvious that the flags *need* to be zeroed. E.g. it would be quite easy to misread the initial read of guest memory and think that zeroing the entire structure is completely superfluous.
--- arch/x86/kvm/hyperv.c | 2 ++ 1 file changed, 2 insertions(+)
arch/x86/kvm/hyperv.c +2 -0
@@ -741,7 +741,9 @@ static int synic_deliver_msg(struct kvm_if (no_retry)return 0 ; + hv_hdr.message_flags.asu8 =0 ; hv_hdr.message_flags.msg_pending =1 ; + r = kvm_vcpu_write_guest_page(vcpu, msg_page_gfn, &hv_hdr.message_flags, msg_off +
Greg Kroah-Hartman
maintainerPATCH 305/1848 KVM: PPC: Fix get_d_signext() 12-bit displacement for paired-single D-form
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Amit Machhiwal <[email protected]>
commit 31895b0ff96778b524c74b43a108090581271603 upstream.
get_d_signext() has two compounding bugs since its introduction in 2010:
1. The extraction mask 0x8FF silently drops bits 8-10 of the 12-bit D field (PPC ISA bits 21-23), corrupting any displacement that has any of those bits set.
2. The sign-magnitude idiom "-(d & 0x7ff)" is wrong for two's-complement:
for D=0xFFC (encoding of -4) it returns -252 instead of -4.
Together these errors produce a wrong effective address for psq_l, psq_lu, psq_st, and psq_stu whenever the displacement is negative or is a positive value >= 0x100 with bits 8-10 set — essentially any real-world paired- single stack-relative access.
The D field occupies the bottom 12 bits of the instruction word (confirmed by the adjacent W and I extractions via inst_get_field(inst,16,16) and inst_get_field(inst,17,19)). Replace the open-coded logic with the standard sign_extend32(inst & 0xfff, 11), which correctly performs two's-complement sign extension from 12 bits to 32 bits.
--- arch/powerpc/kvm/book3s_paired_singles.c | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-)
arch/powerpc/kvm/book3s_paired_singles.c +1 -6
@@ -479,12 +479,7 @@ static bool kvmppc_inst_is_paired_singlestatic int get_d_signext (u32 inst) { -int d = inst &0x8ff ; - -if (d &0x800 ) -return -(d &0x7ff ); - -return (d &0x7ff ); +return sign_extend32 (inst &0xfff ,11 ); } static int kvmppc_ps_three_in(struct kvm_vcpu *vcpu, bool rc,
Greg Kroah-Hartman
maintainerPATCH 306/1848 HID: zydacron: validate key report length
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit 9932c9af185f8586e883d44ca562c12f4487c762 upstream.
The HID core invokes raw_event callbacks before validating the report length. zc_raw_event() verifies the report ID in byte zero and then reads the key code from byte one for report IDs 0x02 and 0x03 without checking that the second byte is present.
A one-byte report reproduced the issue under KASAN:
BUG: KASAN: slab-out-of-bounds in zc_raw_event+0x54c/0x580 Read of size 1 by task hidtrigger/93 Call Trace: zc_raw_event+0x54c/0x580 __hid_input_report+0x2ef/0x3a0 inject_store+0x479/0x490 [faketrans]
Require both the report ID and key code before processing the report.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw_event length validation to hid-asus.
--- drivers/hid/hid-zydacron.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-zydacron.c +3 -0
@@ -114,6 +114,9 @@ static int zc_raw_event(struct hid_devicunsigned key;unsigned short index; +if (size <2 ) +return 0 ; +if (report->id == data[0 ] && (hdev->claimed &HID_CLAIMED_INPUT )) {/* break keys */
Greg Kroah-Hartman
maintainerPATCH 307/1848 HID: core: Fix out-of-bounds left shift by 32 in s32ton()
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alan Stern <[email protected]>
commit 5fe63b415c636c7f4f6848a8e53bdd4bbf0c300d upstream.
Syzbot reported an out-of-bounds shift (32-bit integer shifted left by
32) in the s32ton() routine in the HID core. This routine converts a signed 32-bit integer to a signed n-bit integer, and it caps the value of n at 32. But when n == 32 there's no need to do anything; it can simply return the input value. This will avoid calculating (1 << n) when n is 32, which was the cause of the invalid shift.
--- drivers/hid/hid-core.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/hid/hid-core.c +2 -2
@@ -1360,8 +1360,8 @@ static u32 s32ton(__s32 value, unsignedif (!value || !n)return 0 ; -if (n >32 ) - n =32 ; +if (n >=32 ) +return (u32 ) value; a = value >> (n -1 );if (a && a !=-1 )
Greg Kroah-Hartman
maintainerPATCH 308/1848 HID: cougar: reject short special-key reports
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit c6c0df8a4b73a0d563c5e64de640ef5ff525fc82 upstream.
The HID core invokes raw_event callbacks before validating the report length. cougar_raw_event() reads the key code and action from offsets one and two without checking that those bytes are present. A short report on the special interface can therefore cause an out-of-bounds read.
Consume reports that do not contain the action field before accessing the fixed offsets, consistent with the callback's handling of other reports on the special interface.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw_event length validation to hid-asus.
--- drivers/hid/hid-cougar.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-cougar.c +3 -0
@@ -271,6 +271,9 @@ static int cougar_raw_event(struct hid_dif (!shared->enabled || !shared->input)return -EPERM ; +if (size <=COUGAR_FIELD_ACTION ) +return -EPERM ; + code = data[COUGAR_FIELD_CODE ]; action = data[COUGAR_FIELD_ACTION ];for (i =0 ; cougar_mapping[i][0 ]; i++) {
Greg Kroah-Hartman
maintainerPATCH 309/1848 HID: cp2112: validate response report lengths
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit fc54e71a063c0dcc4bceba6d0f71805a9b84082d upstream.
The HID core invokes raw_event callbacks before validating the report length. cp2112_raw_event() reads every field of a transfer status response without checking size. For a data response, it reads the length at offset two and copies that many bytes from offset three, again without ensuring that the input report contains them.
Require a complete transfer status structure. For data responses, first require the header and then ensure the clamped payload length fits in the received report before copying it.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw_event length validation to hid-asus.
--- drivers/hid/hid-cp2112.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-)
drivers/hid/hid-cp2112.c +8 -1
@@ -1424,6 +1424,9 @@ static int cp2112_raw_event(struct hid_dswitch (data[0 ]) {case CP2112_TRANSFER_STATUS_RESPONSE : +if (size <sizeof (*xfer)) +return 0 ; +hid_dbg (hdev,"xfer status: %02x %02x %04x %04x\n" , xfer->status0, xfer->status1,be16_to_cpu (xfer->retries),be16_to_cpu (xfer->length));
@@ -1457,11 +1460,16 @@ static int cp2112_raw_event(struct hid_datomic_set (&dev->xfer_avail,1 );break ;case CP2112_DATA_READ_RESPONSE : +if (size <3 ) +return 0 ; +hid_dbg (hdev,"read response: %02x %02x\n" , data[1 ], data[2 ]); dev->read_length = data[2 ];if (dev->read_length >sizeof (dev->read_data)) dev->read_length =sizeof (dev->read_data); +if (dev->read_length > size -3 ) +return 0 ;memcpy (dev->read_data, &data[3 ], dev->read_length);atomic_set (&dev->read_avail,1 );
@@ -1488,4 +1496,3 @@ module_hid_driver(cp2112_driver);MODULE_DESCRIPTION ("Silicon Labs HID USB to SMBus master bridge" );MODULE_AUTHOR ("David Barksdale <[email protected]>" );MODULE_LICENSE ("GPL" ); -
Greg Kroah-Hartman
maintainerPATCH 310/1848 HID: elo: reject short touchscreen reports
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit 1cb92fcb2ac344d78737e3c5cb7b061dfb2850b1 upstream.
The HID core invokes raw_event callbacks before validating the report length. elo_raw_event() only checks the first-byte packet marker before elo_process_data() reads coordinates, flags, and pressure through offset seven. A truncated packet beginning with the expected marker can therefore cause an out-of-bounds read.
Require the complete eight-byte SmartSet packet before parsing it.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw_event length validation to hid-asus.
--- drivers/hid/hid-elo.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-elo.c +3 -0
@@ -85,6 +85,9 @@ static int elo_raw_event(struct hid_deviif (!(hdev->claimed &HID_CLAIMED_INPUT ) ||list_empty (&hdev->inputs))return 0 ; +if (size <ELO_SMARTSET_PACKET_SIZE ) +return 0 ; + hidinput = list_first_entry(&hdev->inputs, struct hid_input, list);switch (report->id) {
Greg Kroah-Hartman
maintainerPATCH 311/1848 HID: logitech-dj: validate unnumbered keyboard reports
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit c2deafcb4c8227771f768d77ed3c0a489250e9b2 upstream.
The HID core invokes raw_event callbacks before validating the report length. For an unnumbered keyboard report, logi_dj_raw_event() uses the second byte as temporary storage while prepending a report ID. A one-byte report therefore makes both the initial write and the later restoration access data beyond the received report.
Reject unnumbered keyboard reports that do not provide the temporary byte.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw_event length validation to hid-asus.
--- drivers/hid/hid-logitech-dj.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-logitech-dj.c +3 -0
@@ -1601,6 +1601,9 @@ static int logi_dj_raw_event(struct hid_if (!hdev->report_enum[HID_INPUT_REPORT ].numbered) {if (djrcv_dev->unnumbered_application ==HID_GD_KEYBOARD ) { +if (size <2 ) +return false; +/* * For the keyboard, we can reuse the same report by * using the second byte which is constant in the USB
Greg Kroah-Hartman
maintainerPATCH 312/1848 HID: mcp2221: validate response report length
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit 1ae40774d386b7a51e4799200106429a7e14e8ec upstream.
MCP2221 responses are 64-byte reports, but mcp2221_raw_event() currently accepts any report of at least four bytes. Several response handlers read far beyond that minimum. In particular, the I2C status response reads offset 20 and copies ADC samples starting at offset 50. Other GPIO, SRAM, and flash response handlers also access fixed offsets beyond byte three.
The HID core invokes raw_event callbacks before validating the report length, so a truncated response can cause an out-of-bounds read. Require a complete protocol report before dispatching any response handler.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw_event length validation to hid-asus.
--- drivers/hid/hid-mcp2221.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/hid/hid-mcp2221.c +1 -1
@@ -739,7 +739,7 @@ static int mcp2221_raw_event(struct hid_u8 *buf;struct mcp2221 *mcp =hid_get_drvdata (hdev); -if (size <4 ) +if (size <sizeof (mcp->txbuf))return 0 ;switch (data[0 ]) {
Greg Kroah-Hartman
maintainerPATCH 313/1848 HID: quirks: Always poll the Anne Pro 2 with product ID a292
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Gabor Tanz <[email protected]>
commit cbc13a78a89d087252947d0a51048e576cfcb3ef upstream.
The wired Anne Pro 2 identifying as 04d9:a292 stops delivering keyboard input after a period of inactivity. Unplugging and reconnecting the keyboard restores input.
Keeping ObinsKit running prevents the problem. A read-only userspace reader that keeps USB HID interface 1 open also prevents it, as does usbhid.quirks=0x04d9:0xa292:0x00000400 without either application running.
Commit ca28aff0e1dc ("HID: quirks: Always poll Obins Anne Pro 2 keyboard") added HID_QUIRK_ALWAYS_POLL for product ID a293. The variant identifying as 04d9:a292 exhibits the same symptom. Apply the quirk to this product ID as well.
--- drivers/hid/hid-ids.h | 1 + drivers/hid/hid-quirks.c | 1 + 2 files changed, 2 insertions(+)
drivers/hid/hid-ids.h +1 -0
@@ -652,6 +652,7 @@#define USB_DEVICE_ID_HOLTEK_ALT_MOUSE_A081 0xa081#define USB_DEVICE_ID_HOLTEK_ALT_MOUSE_A0C2 0xa0c2#define USB_DEVICE_ID_HOLTEK_ALT_KEYBOARD_A096 0xa096 +#define USB_DEVICE_ID_HOLTEK_ALT_KEYBOARD_A292 0xa292#define USB_DEVICE_ID_HOLTEK_ALT_KEYBOARD_A293 0xa293#define USB_VENDOR_ID_IMATION 0x0718
drivers/hid/hid-quirks.c +1 -0
@@ -102,6 +102,7 @@ static const struct hid_device_id hid_qu { HID_USB_DEVICE(USB_VENDOR_ID_HAPP, USB_DEVICE_ID_UGCI_FIGHTING), HID_QUIRK_BADPAD | HID_QUIRK_MULTI_INPUT }, { HID_USB_DEVICE(USB_VENDOR_ID_HAPP, USB_DEVICE_ID_UGCI_FLYING), HID_QUIRK_BADPAD | HID_QUIRK_MULTI_INPUT }, { HID_USB_DEVICE(USB_VENDOR_ID_HOLTEK_ALT, USB_DEVICE_ID_HOLTEK_ALT_KEYBOARD_A096), HID_QUIRK_NO_INIT_REPORTS }, + { HID_USB_DEVICE(USB_VENDOR_ID_HOLTEK_ALT, USB_DEVICE_ID_HOLTEK_ALT_KEYBOARD_A292), HID_QUIRK_ALWAYS_POLL }, { HID_USB_DEVICE(USB_VENDOR_ID_HOLTEK_ALT, USB_DEVICE_ID_HOLTEK_ALT_KEYBOARD_A293), HID_QUIRK_ALWAYS_POLL }, { HID_USB_DEVICE(USB_VENDOR_ID_HP, USB_PRODUCT_ID_HP_LOGITECH_OEM_USB_OPTICAL_MOUSE_0A4A), HID_QUIRK_ALWAYS_POLL }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_HP, USB_PRODUCT_ID_HP_ELITE_PRESENTER_MOUSE_464A), HID_QUIRK_MULTI_INPUT },
Greg Kroah-Hartman
maintainerPATCH 314/1848 HID: roccat: isku: reject short button reports
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit 93e5f7f6189af76a2b2e2dfe647838a7b9f99d21 upstream.
The raw event callback runs before HID core validates and zero-pads the report. It passes the buffer to helpers which inspect data[0] and, for a button report, read the complete struct isku_report_button. A truncated report can therefore cause an out-of-bounds read.
Require enough data for the button report before calling either helper. Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw-event length validation to hid-asus.
--- drivers/hid/hid-roccat-isku.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-roccat-isku.c +3 -0
@@ -408,6 +408,9 @@ static int isku_raw_event(struct hid_devif (isku ==NULL )return 0 ; +if (size <sizeof (struct isku_report_button )) +return 0 ; +isku_keep_values_up_to_date (isku, data);if (isku->roccat_claimed)
Greg Kroah-Hartman
maintainerPATCH 315/1848 HID: roccat: koneplus: reject short button reports
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit d879e17a8b4c572c0b53b4e42a36849484e8f00c upstream.
The raw event callback runs before HID core validates and zero-pads the report. It passes the buffer to helpers which inspect data[0] and, for a button report, read the complete struct koneplus_mouse_report_button. A truncated report can therefore cause an out-of-bounds read.
Require enough data for the button report before calling either helper. Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw-event length validation to hid-asus.
--- drivers/hid/hid-roccat-koneplus.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-roccat-koneplus.c +3 -0
@@ -520,6 +520,9 @@ static int koneplus_raw_event(struct hidif (koneplus ==NULL )return 0 ; +if (size <sizeof (struct koneplus_mouse_report_button )) +return 0 ; +koneplus_keep_values_up_to_date (koneplus, data);if (koneplus->roccat_claimed)
Greg Kroah-Hartman
maintainerPATCH 316/1848 HID: roccat: konepure: reject short button reports
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit 1590b7c9bea0abe7a5d25dbfe06287c48c238a6f upstream.
The raw event callback runs before HID core validates and zero-pads the report. It reads the report number without checking the received length and passes matching data to roccat_report_event(), which copies a complete struct konepure_mouse_report_button. A truncated report can therefore cause an out-of-bounds read and expose adjacent data through the Roccat character device.
Require a complete button report before inspecting or forwarding it. Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw-event length validation to hid-asus.
--- drivers/hid/hid-roccat-konepure.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-roccat-konepure.c +3 -0
@@ -178,6 +178,9 @@ static int konepure_raw_event(struct hid != USB_INTERFACE_PROTOCOL_MOUSE)return 0 ; +if (size <sizeof (struct konepure_mouse_report_button )) +return 0 ; +if (data[0 ] !=KONEPURE_MOUSE_REPORT_NUMBER_BUTTON )return 0 ;
Greg Kroah-Hartman
maintainerPATCH 317/1848 HID: roccat: kovaplus: reject short button reports
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit e95917a606f486e46f5136fc1b72190742a091d6 upstream.
The raw event callback runs before HID core validates and zero-pads the report. It passes the buffer to helpers which inspect data[0] and read a complete struct kovaplus_mouse_report_button for button reports. A truncated report can therefore cause an out-of-bounds read.
Require enough data for the button report before calling either helper. Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw-event length validation to hid-asus.
--- drivers/hid/hid-roccat-kovaplus.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-roccat-kovaplus.c +3 -0
@@ -611,6 +611,9 @@ static int kovaplus_raw_event(struct hidif (kovaplus ==NULL )return 0 ; +if (size <sizeof (struct kovaplus_mouse_report_button )) +return 0 ; +kovaplus_keep_values_up_to_date (kovaplus, data);if (kovaplus->roccat_claimed)
Greg Kroah-Hartman
maintainerPATCH 318/1848 HID: roccat: pyra: reject short button reports
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit 493268f459bb6aeeecbc77f2204c11ad74d05213 upstream.
The raw event callback runs before HID core validates and zero-pads the report. It passes the buffer to helpers which inspect data[0] and read a complete struct pyra_mouse_event_button for button reports. A truncated report can therefore cause an out-of-bounds read.
Require enough data for the button report before calling either helper. Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw-event length validation to hid-asus.
--- drivers/hid/hid-roccat-pyra.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-roccat-pyra.c +3 -0
@@ -554,6 +554,9 @@ static int pyra_raw_event(struct hid_devif (pyra ==NULL )return 0 ; +if (size <sizeof (struct pyra_mouse_event_button )) +return 0 ; +pyra_keep_values_up_to_date (pyra, data);if (pyra->roccat_claimed)
Greg Kroah-Hartman
maintainerPATCH 319/1848 HID: roccat: ryos: reject short special reports
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit 02f3607d0beb82e76481568bf631235e6a319b47 upstream.
The raw event callback runs before HID core validates and zero-pads the report. It reads the report number without checking the received length and passes matching data to roccat_report_event(), which copies a complete struct ryos_report_special. A truncated report can therefore cause an out-of-bounds read and expose adjacent data through the Roccat character device.
Require a complete special report before inspecting or forwarding it. Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw-event length validation to hid-asus.
--- drivers/hid/hid-roccat-ryos.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-roccat-ryos.c +3 -0
@@ -186,6 +186,9 @@ static int ryos_raw_event(struct hid_dev != RYOS_USB_INTERFACE_PROTOCOL)return 0 ; +if (size <sizeof (struct ryos_report_special )) +return 0 ; +if (data[0 ] !=RYOS_REPORT_NUMBER_SPECIAL )return 0 ;
Greg Kroah-Hartman
maintainerPATCH 320/1848 HID: roccat: savu: reject short special reports
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiale Yao <[email protected]>
commit 76c51fdc825a0486f8d88ff896d39acec8f377b4 upstream.
The raw event callback runs before HID core validates and zero-pads the report. It passes the buffer to a helper which inspects data[0] and, for a special report, reads the complete struct savu_mouse_report_special. A truncated report can therefore cause an out-of-bounds read.
Require enough data for the special report before calling the helper. Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence") added the same kind of raw-event length validation to hid-asus.
--- drivers/hid/hid-roccat-savu.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/hid/hid-roccat-savu.c +3 -0
@@ -179,6 +179,9 @@ static int savu_raw_event(struct hid_devif (savu ==NULL )return 0 ; +if (size <sizeof (struct savu_mouse_report_special )) +return 0 ; +if (savu->roccat_claimed)savu_report_to_chrdev (savu, data);
Greg Kroah-Hartman
maintainerPATCH 321/1848 netfilter: conntrack: always lower timeout for non-closing RST packets
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pablo Neira Ayuso <[email protected]>
commit 73df81b38cb7f70a347a97370386378a86e53019 upstream.
The existing check might extend the timeout if the ESTABLISHED timeout has been tuned to be lower than UNACK via sysctl. Reported by sashiko.
--- net/netfilter/nf_conntrack_proto_tcp.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
net/netfilter/nf_conntrack_proto_tcp.c +2 -1
@@ -1135,7 +1135,8 @@ int nf_conntrack_tcp_packet(struct nf_co timeouts[new_state] > timeouts[TCP_CONNTRACK_RETRANS]) timeout = timeouts[TCP_CONNTRACK_RETRANS ]; else if (unlikely(index == TCP_RST_SET && - new_state == TCP_CONNTRACK_ESTABLISHED)) + new_state == TCP_CONNTRACK_ESTABLISHED) && + timeouts[new_state] > timeouts[TCP_CONNTRACK_UNACK]) timeout = timeouts[TCP_CONNTRACK_UNACK ]; else if ((ct->proto.tcp.seen[0].flags | ct->proto.tcp.seen[1].flags) & IP_CT_TCP_FLAG_DATA_UNACKNOWLEDGED &&
Greg Kroah-Hartman
maintainerPATCH 322/1848 tun: Require CAP_NET_ADMIN to attach to an ownerless device
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Woodhouse <[email protected]>
commit ffdf678dd16610e3f006dac904bd37c09684673c upstream.
Twenty years ago I made creating a tuntap device require CAP_NET_ADMIN in commit ca6bb5d7ab22 ("[NET]: Require CAP_NET_ADMIN to create tuntap devices.")
The idea was to allow the permissions on /dev/net/tun to be relaxed to 0666 and thus allow owners of tun devices assigned with TUNSETOWNER to actually open it and get at their devices.
What we missed at the time was that persistent devices with *no* owner were already essentially world-consumable, and anyone who could open the device node could also attach to those.
Even then, using persistent devices with no explicitly set owner — on the (false) presumption that CAP_NET_ADMIN would be required to open them — wasn't an egregious userspace bug. There are cases where it does make sense to separate the creation/configuration of the netdevice, from the process which shovels packets into it.
Since then, TUNSETGROUP was added a year later in commit 8c644623fe7e ("[NET]: Allow group ownership of TUN/TAP devices."). Its commit message noted that if both uid and gid are set, both have to match (in itself a bizarre choice) — but still not that with *neither* set, no permission at all was required.
Then in 2012 commit c8d68e6be1c3 ("tuntap: multiqueue support") allowed new queues to be attached to a device from the moment of its creation, with no way for userspace to close the race between creation and a subsequent TUNSET{OWNER,GROUP}.
In 2024, commit 3ca459eaba1bf ("tun: fix group permission check") tried to fix things to be saner: only require the user *or* the group to match, in line with standard POSIX permissions, and require CAP_NET_ADMIN if neither the user nor group authorised the access (although it put the CAP_NET_ADMIN check first, and would wrongly have reported the capability as having been used even when it was not).
That fix was reverted in commit a70c7b3cbc06 ("tun: revert fix group permission check") due to allegedly causing a regression in an selinux test suite which *expected* the attachment to succeed when authorised by none of user, group, nor CAP_NET_ADMIN:
https://lore.kernel.org/netdev/CAFqZXNtkCBT4f+PwyVRmQGoT3p1eVa01fCG_aNtpt6dakXncUg@mail.gmail.com/
We should not break UAPI. But we don't have to consider an selinux test case which deliberately exercises a security flaw to be UAPI worth preserving either. To which end, I have fixed it in selinux-testsuite commit b2f894f0016b ("tests/tun_tap: set an owner on the device for the relabel tests").
So: fix the lack of CAP_NET_ADMIN check on devices which *haven't* been assigned an owner or group, while leaving the weird tun ownership model as it was (user *and* group have to match, if both are set). If someone still wants to fix the latter (which wasn't actually the reason the previous attempt was reverted), they can do it under separate cover.
Permit attaching to an existing device only if an owner and/or group was set and the caller matches all that were set, or if the caller has CAP_NET_ADMIN. The only behavioural change is that a device with no owner or group now requires CAP_NET_ADMIN to attach — precisely the loophole we want to close.
And put the CAP_NET_ADMIN check in the right place this time.
--- drivers/net/tun.c | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-)
drivers/net/tun.c +9 -5
@@ -586,14 +586,18 @@ static u16 tun_select_queue(struct net_dreturn ret; } -static inline bool tun_not_capable (struct tun_struct *tun) +static inline bool tun_permitted (struct tun_struct *tun) {const struct cred *cred =current_cred ();struct net *net =dev_net (tun->dev); -return ((uid_valid (tun->owner) && !uid_eq (cred->euid, tun->owner)) || - (gid_valid (tun->group) && !in_egroup_p (tun->group))) && - !ns_capable (net->user_ns,CAP_NET_ADMIN ); +/* If both uid and gid are set, *both* must match */ +if ((uid_valid (tun->owner) ||gid_valid (tun->group)) && + (!uid_valid (tun->owner) ||uid_eq (cred->euid, tun->owner)) && + (!gid_valid (tun->group) ||in_egroup_p (tun->group))) +return true; + +return ns_capable (net->user_ns,CAP_NET_ADMIN ); }static void tun_set_real_num_queues (struct tun_struct *tun)
@@ -2786,7 +2790,7 @@ static int tun_set_iff(struct net *net, !!(tun->flags & IFF_MULTI_QUEUE))return -EINVAL ; -if (tun_not_capable (tun)) +if (!tun_permitted (tun))return -EPERM ; err =security_tun_dev_open (tun->security);if (err <0 )
Greg Kroah-Hartman
maintainerPATCH 323/1848 smb: client: fix early procfs exposure race
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fredric Cover <[email protected]>
[ Upstream commit 7b1afb631395c958993cda4631002258ef4151ea ]
Currently, init_cifs() calls cifs_proc_init() near the beginning of the function, before INIT_LIST_HEAD, leading to a momentarily uninitialized, but exposed, procfs. If a userspace process reads this empty procfs, iterating over a zeroed list_head leads to a NULL pointer dereference and a kernel oops/panic.
For example, if a delay is added between cifs_proc_init() and INIT_LIST_HEAD, and a userspace process is polling /proc/fs/cifs/DebugData, the following oops occurs:
BUG: kernel NULL pointer dereference, address: 0000000000000608 Oops: Oops: 0000 [#1] SMP PTI CPU: 0 UID: 0 PID: 3477 Comm: cat Not tainted 7.3.0-02212-g4df4d2a577db-dirty #6 PREEMPT(lazy) RIP: 0010:cifs_debug_data_proc_show+0x103/0xd80 [cifs] Call Trace: <TASK> ? seq_read_iter+0x86/0x400 ? seq_read_iter+0x86/0x400 seq_read_iter+0x183/0x400 proc_reg_read_iter+0x62/0x90 copy_splice_read+0x215/0x310 splice_file_to_pipe+0xec/0x1c0 do_splice+0x4b8/0x780 __se_sys_splice+0x18f/0x250 do_syscall_64+0x109/0x330 entry_SYSCALL_64_after_hwframe+0x77/0x7f </TASK>
Fix this by moving cifs_proc_init() down in init_cifs(), ensuring it runs only after all internal lists, locks, counters, and workqueues are fully ready, but before registering the filesystem. Update the error cleanup ladder and exit_cifs() to maintain proper LIFO order.
--- fs/cifs/cifsfs.c | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-)
fs/cifs/cifsfs.c +9 -11
@@ -1536,7 +1536,6 @@ static int __initinit_cifs (void) {int rc =0 ; -cifs_proc_init ();INIT_LIST_HEAD (&cifs_tcp_ses_list);#ifdef CONFIG_CIFS_DNOTIFY_EXPERIMENTAL /* unused temporarily */ INIT_LIST_HEAD (&GlobalDnotifyReqList);
@@ -1582,10 +1581,8 @@ init_cifs(void) } cifsiod_wq =alloc_workqueue ("cifsiod" ,WQ_FREEZABLE |WQ_MEM_RECLAIM ,0 ); -if (!cifsiod_wq) { - rc = -ENOMEM ; - goto out_clean_proc; - } +if (!cifsiod_wq) +return -ENOMEM ;/* * Consider in future setting limit!=0 maybe to min(num_of_cores - 1, 3)
@@ -1646,19 +1643,22 @@ init_cifs(void)if (rc) goto out_register_key_type; +cifs_proc_init (); + rc =register_filesystem (&cifs_fs_type);if (rc) - goto out_init_cifs_idmap; + goto out_clean_proc; rc =register_filesystem (&smb3_fs_type);if (rc) {unregister_filesystem (&cifs_fs_type); - goto out_init_cifs_idmap; + goto out_clean_proc; }return 0 ; -out_init_cifs_idmap: +out_clean_proc: +cifs_proc_clean ();exit_cifs_idmap (); out_register_key_type: #ifdef CONFIG_CIFS_UPCALL
@@ -1684,8 +1684,6 @@ init_cifs(void)destroy_workqueue (decrypt_wq); out_destroy_cifsiod_wq:destroy_workqueue (cifsiod_wq); -out_clean_proc: -cifs_proc_clean ();return rc; }
@@ -1695,6 +1693,7 @@ exit_cifs(void)cifs_dbg (NOISY ,"exit_smb3\n" );unregister_filesystem (&cifs_fs_type);unregister_filesystem (&smb3_fs_type); +cifs_proc_clean ();cifs_dfs_release_automount_timer ();exit_cifs_idmap ();#ifdef CONFIG_CIFS_UPCALL
@@ -1711,7 +1710,6 @@ exit_cifs(void)destroy_workqueue (decrypt_wq);destroy_workqueue (fileinfo_put_wq);destroy_workqueue (cifsiod_wq); -cifs_proc_clean (); }MODULE_AUTHOR ("Steve French" );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 324/1848 smb: client: do not pass a NULL buf to is_oplock_break()
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zikang Gao <[email protected]>
[ Upstream commit 2225ab306575e424b3dad2ee1be2521c89249d15 ]
receive_encrypted_read() sets *num_mids = 1 and never writes the caller's bufs[]. Offload returns -1 with *num_mids = 0, so the demultiplex thread skips the frame. The inline decrypt path returns 0 even when smb2_find_mid() fails.
cifs_demultiplex_thread() then treats mids[i] == NULL as an oplock break and calls is_oplock_break(bufs[i], server) with bufs[i] still NULL. smb2_is_valid_oplock_break() reads hdr.Command at offset 12 and oopses.
A large encrypted READ whose MessageId does not match is enough to panic cifsd.
Oops: general protection fault, probably for non-canonical address
0xdffffc0000000001: 0000 [#1] SMP KASAN PTI
KASAN: null-ptr-deref in range
[0x0000000000000008-0x000000000000000f]
CPU: 0 PID: 100 Comm: cifsd
RIP: smb2_is_valid_oplock_break+0xc8/0x2270 [cifs]
cifs_demultiplex_thread
Kernel panic - not syncing: Fatal exceptionReturn -1 when inline decrypt finds no mid, and skip is_oplock_break() plus the unknown-frame dump when bufs[i] is NULL. receive_encrypted_standard() already assigns bufs[*num_mids].
--- fs/cifs/connect.c | 4 +++- fs/cifs/smb2ops.c | 5 +++-- 2 files changed, 6 insertions(+), 3 deletions(-)
fs/cifs/connect.c +3 -1
@@ -1191,12 +1191,14 @@ cifs_demultiplex_thread(void *p) mids[i]->callback (mids[i]);cifs_mid_q_entry_release (mids[i]); - }else if (server->ops->is_oplock_break && + }else if (bufs[i] && server->ops->is_oplock_break && server->ops->is_oplock_break (bufs[i], server)) {smb2_add_credits_from_hdr (bufs[i], server);cifs_dbg (FYI ,"Received oplock break\n" ); }else { +if (!bufs[i]) +continue ;cifs_server_dbg (VFS ,"No task to wake, unknown frame received! NumMids %d\n" ,atomic_read (&midCount)); cifs_dump_mem("Received Data is: ", bufs[i],
fs/cifs/smb2ops.c +3 -2
@@ -4946,9 +4946,10 @@ receive_encrypted_read(struct TCP_Server_Info *server, struct mid_q_entry **mid, goto free_pages; *mid =smb2_find_mid (server, buf); -if (*mid ==NULL ) +if (*mid ==NULL ) {cifs_dbg (FYI ,"mid not found\n" ); -else { + rc =-1 ; + }else {cifs_dbg (FYI ,"mid found\n" ); (*mid)->decrypted = true; rc = handle_read_data(server, *mid, buf,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 325/1848 net/sched: sch_teql: fix use-after-free on lower qdisc drop
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: owen kwan <[email protected]>
[ Upstream commit 782d6bb8f9b8e9d8591181662222bf74cd3ecf79 ]
The issue: teql_master_xmit() tests the slave's ndo_start_xmit() return value against NETDEV_TX_OK alone. A slave that consumes the skb but returns an error code (rc < NET_XMIT_MASK, e.g. NET_XMIT_DROP) is treated as if the skb were still owned, so the loop restores skb->dev and calls __skb_pull() on it. A VLAN slave returns the result of dev_queue_xmit() from its ndo_start_xmit() (propagated since cbbef5e18307), and when the lower qdisc drops the packet that value is NET_XMIT_DROP after the skb has been freed, giving a use-after-free in teql_master_xmit().
The Fix: test for consumption with dev_xmit_complete(), which accepts NETDEV_TX_OK and every rc < NET_XMIT_MASK, matching other callers that need to distinguish consumed results from busy. Only NETDEV_TX_OK keeps the packet counted in tx_packets/tx_bytes and advances the slave; a consumed result that is neither a success nor NET_XMIT_CN ends the attempt and is charged to tx_dropped, so lower-qdisc drops are no longer reported as good transmits. NET_XMIT_CN is counted like success because it can accompany acceptance of the current packet: pfifo_head_drop drops the old head, enqueues the current skb and returns NET_XMIT_CN.
Conditions to recreate the bug:
With CONFIG_NET_SCH_TEQL,CONFIG_VLAN_8021Q and CONFIG_DUMMY enabled, add lkrdummy0 (dummy) and lkrvlan0 (VLAN id 37 on lkrdummy0); set a pfifo limit 0 root on lkrdummy0 and a teql0 root on lkrvlan0; bring teql0 up with an address and send one UDP packet to it. The VLAN xmit returns NET_XMIT_DROP from the lower qdisc while holding a freed skb.
--- net/sched/sch_teql.c | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-)
net/sched/sch_teql.c +9 -5
@@ -311,19 +311,23 @@ static netdev_tx_t teql_master_xmit(struct sk_buff *skb, struct net_device *dev)case 0 :if (__netif_tx_trylock (slave_txq)) {unsigned int length =qdisc_pkt_len (skb); +int rc =NETDEV_TX_BUSY ; skb->dev = slave; -if (!netif_xmit_frozen_or_stopped (slave_txq) && -netdev_start_xmit (skb, slave, slave_txq, false) == -NETDEV_TX_OK ) { -__netif_tx_unlock (slave_txq); +if (!netif_xmit_frozen_or_stopped (slave_txq)) + rc =netdev_start_xmit (skb, slave, slave_txq, false); +__netif_tx_unlock (slave_txq); +if (dev_xmit_complete (rc)) { +if (rc !=NETDEV_TX_OK && rc !=NET_XMIT_CN ) { + master->tx_dropped++; +return NETDEV_TX_OK ; + } master->slaves =NEXT_SLAVE (q);netif_wake_queue (dev); master->tx_packets++; master->tx_bytes += length;return NETDEV_TX_OK ; } -__netif_tx_unlock (slave_txq); }if (netif_xmit_stopped (netdev_get_tx_queue (dev,0 ))) busy =1 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 326/1848 net/sched: cls_flower: avoid stale mask references after delete
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yuhang Zheng <[email protected]>
[ Upstream commit 58f7989da6e715ce834ac861b7ba6ae9f9bdb098 ]
Flower releases a mask reference when a filter is removed from the classifier. The filter object can remain alive while dump, walk, or hardware reoffload paths hold a reference to it. Those paths can then dereference f->mask after the mask has already been released.
Keep the mask reference until the filter reference count reaches zero. Release the mask synchronously from the final __fl_put() while the caller still holds the tcf_proto reference, and leave the existing RCU work to free the mask. This keeps the mask available to every reader that still holds the filter.
The filter is still removed from the classifier indexes immediately. Therefore, a deleted filter can temporarily retain an otherwise empty mask; fl_delete() uses the handle IDR, rather than the mask list, to determine whether the classifier has become empty.
Failed mask assignment can leave fnew->mask as an error or borrowed pointer without an owned mask reference. Clear it before the common failure path so the final put cannot release an unowned reference.
This fix does not add fields, snapshots, or per-filter memory.
--- net/sched/cls_flower.c | 49 ++++++++++++++++++++++++------------------ 1 file changed, 28 insertions(+), 21 deletions(-)
net/sched/cls_flower.c +28 -21
@@ -498,15 +498,22 @@ static void fl_hw_update_stats(struct tcf_proto *tp, struct cls_fl_filter *f, cls_flower.stats.used_hw_stats_valid); } -static void __fl_put (struct cls_fl_filter *f) +static bool __fl_put (struct tcf_proto *tp,struct cls_fl_filter *f) { +bool last = false; +if (!refcount_dec_and_test (&f->refcnt)) -return ; +return false; + +if (f->mask) + last =fl_mask_put (fl_head_dereference (tp), f->mask);if (tcf_exts_get_net (&f->exts))tcf_queue_work (&f->rwork, fl_destroy_filter_work);else __fl_destroy_filter (f); + +return last; }static struct cls_fl_filter *__fl_get (struct cls_fl_head *head,u32 handle)
@@ -543,11 +550,10 @@ static int __fl_delete(struct tcf_proto *tp, struct cls_fl_filter *f,list_del_rcu (&f->list);spin_unlock (&tp->lock); - *last =fl_mask_put (head, f->mask);if (!tc_skip_hw (f->flags))fl_hw_destroy_filter (tp, f, rtnl_held, extack);tcf_unbind_filter (tp, &f->res); -__fl_put (f); + *last =__fl_put (tp, f);return 0 ; }
@@ -588,7 +594,7 @@ static void fl_put(struct tcf_proto *tp, void *arg) {struct cls_fl_filter *f = arg; -__fl_put (f); +__fl_put (tp, f); }static void *fl_get (struct tcf_proto *tp,u32 handle)
@@ -2042,12 +2048,14 @@ static int fl_change(struct net *net, struct sk_buff *in_skb, goto errout; err =fl_check_assign_mask (head, fnew, fold, mask); -if (err) +if (err) { + fnew->mask =NULL ; goto errout; + } err =fl_ht_insert_unique (fnew, fold, &in_ht);if (err) - goto errout_mask; + goto errout;if (!tc_skip_hw (fnew->flags)) { err =fl_hw_replace_filter (tp, fnew, rtnl_held, extack);
@@ -2099,7 +2107,6 @@ static int fl_change(struct net *net, struct sk_buff *in_skb,spin_unlock (&tp->lock); -fl_mask_put (head, fold->mask);if (!tc_skip_hw (fold->flags))fl_hw_destroy_filter (tp, fold, rtnl_held,NULL );tcf_unbind_filter (tp, &fold->res);
@@ -2107,7 +2114,7 @@ static int fl_change(struct net *net, struct sk_buff *in_skb,* after this. */ refcount_dec (&fold->refcnt); -__fl_put (fold); +__fl_put (tp, fold); }else {if (handle) {/* user specifies a handle and it doesn't exist */
@@ -2152,17 +2159,15 @@ static int fl_change(struct net *net, struct sk_buff *in_skb,if (in_ht)rhashtable_remove_fast (&fnew->mask->ht, &fnew->ht_node, fnew->mask->filter_ht_params); -errout_mask: -fl_mask_put (head, fnew->mask); errout: -__fl_put (fnew); +__fl_put (tp, fnew); errout_tb:kfree (tb); errout_mask_alloc:tcf_queue_work (&mask->rwork, fl_uninit_mask_free_work); errout_fold:if (fold) -__fl_put (fold); +__fl_put (tp, fold);return err; }
@@ -2175,8 +2180,10 @@ static int fl_delete(struct tcf_proto *tp, void *arg, bool *last,int err =0 ; err =__fl_delete (tp, f, &last_on_mask, rtnl_held, extack); - *last =list_empty (&head->masks); -__fl_put (f); +spin_lock (&tp->lock); + *last =idr_is_empty (&head->handle_idr); +spin_unlock (&tp->lock); +__fl_put (tp, f);return err; }
@@ -2198,12 +2205,12 @@ static void fl_walk(struct tcf_proto *tp, struct tcf_walker *arg,rcu_read_unlock ();if (arg->fn (tp, f, arg) <0 ) { -__fl_put (f); +__fl_put (tp, f); arg->stop =1 ;rcu_read_lock ();break ; } -__fl_put (f); +__fl_put (tp, f); arg->count++;rcu_read_lock (); }
@@ -2254,7 +2261,7 @@ static int fl_reoffload(struct tcf_proto *tp, bool add, flow_setup_cb_t *cb, cls_flower.rule =flow_rule_alloc (tcf_exts_num_actions (&f->exts));if (!cls_flower.rule) { -__fl_put (f); +__fl_put (tp, f);return -ENOMEM ; }
@@ -2272,7 +2279,7 @@ static int fl_reoffload(struct tcf_proto *tp, bool add, flow_setup_cb_t *cb,kfree (cls_flower.rule);if (tc_skip_sw (f->flags)) {NL_SET_ERR_MSG_MOD (extack,"Failed to setup flow action" ); -__fl_put (f); +__fl_put (tp, f);return err; } goto next_flow;
@@ -2288,11 +2295,11 @@ static int fl_reoffload(struct tcf_proto *tp, bool add, flow_setup_cb_t *cb,kfree (cls_flower.rule);if (err) { -__fl_put (f); +__fl_put (tp, f);return err; } next_flow: -__fl_put (f); +__fl_put (tp, f); }return 0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 327/1848 net/sched: fix packet reordering on requeue
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Antonio Quartulli <[email protected]>
[ Upstream commit 14368b9aa1017fee35d2589be7b17e0485c0f93e ]
dev_requeue_skb() appends requeued skbs to the tail of q->gso_skb, while dequeue_skb() takes them back one at a time from the head. If the driver returns NETDEV_TX_BUSY again for the first of them, it moves behind the skbs still parked there and is sent after them.
This showed up as heavy TCP reordering while benchmarking over veth,
which returns NETDEV_TX_BUSY whenever its ring is full since
commit dc82a33297fc ("veth: apply qdisc backpressure on full ptr_ring to reduce TX drops").
Requeue the skbs at the head of gso_skb, keeping their order. With 4 TCP streams over a veth pair with a pfifo qdisc, this removes about 1.3M out-of-order segments and 15-37k retransmits per 15 seconds, and raises throughput from about 40 to 76 Gbit/s.
--- net/sched/sch_generic.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-)
net/sched/sch_generic.c +10 -1
@@ -139,8 +139,11 @@ static inline void qdisc_enqueue_skb_bad_txq(struct Qdisc *q,static inline void dev_requeue_skb (struct sk_buff *skb,struct Qdisc *q) { +struct sk_buff_head requeue;spinlock_t *lock =NULL ; +__skb_queue_head_init (&requeue); +if (q->flags &TCQ_F_NOLOCK ) { lock =qdisc_lock (q);spin_lock (lock);
@@ -149,7 +152,7 @@ static inline void dev_requeue_skb(struct sk_buff *skb, struct Qdisc *q)while (skb) {struct sk_buff *next = skb->next; -__skb_queue_tail (&q->gso_skb, skb); +__skb_queue_tail (&requeue, skb);/* it's still part of the queue */ if (qdisc_is_percpu_stats (q)) {
@@ -164,6 +167,12 @@ static inline void dev_requeue_skb(struct sk_buff *skb, struct Qdisc *q) skb = next; } + +/* the skbs may come from the head of gso_skb, so put them back there: +* appending them would let the ones still parked overtake them +*/ +skb_queue_splice (&requeue, &q->gso_skb); +if (lock)spin_unlock (lock);__netif_schedule (q);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 328/1848 backlight: lm3630a_bl: Remove redundant flush_workqueue() calls
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Xu Wang <[email protected]>
[ Upstream commit adc122011125682932ef279d717153670feedde4 ]
'destroy_workqueue()' already drains the queue before destroying it, so there is no need to flush it explicitly.
Remove the redundant 'flush_workqueue()' calls.
Stable-dep-of: 2cf184caab8b ("backlight: lm3630a: Cancel delayed work before destroying workqueue")
--- drivers/video/backlight/lm3630a_bl.c | 1 - 1 file changed, 1 deletion(-)
drivers/video/backlight/lm3630a_bl.c +0 -1
@@ -593,7 +593,6 @@ static int lm3630a_remove(struct i2c_client *client)if (pchip->irq) {free_irq (pchip->irq, pchip); -flush_workqueue (pchip->irqthread);destroy_workqueue (pchip->irqthread); }return 0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 329/1848 backlight: lm3630a: Cancel delayed work before destroying workqueue
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Myeonghun Pak <[email protected]>
[ Upstream commit 2cf184caab8b406fdd9db126ee40d62418237456 ]
The interrupt handler queues delayed work to read the interrupt status. After free_irq() stops the producer, this work can still be waiting on its timer. destroy_workqueue() cannot drain delayed work that has not yet been queued by its timer, so the timer can outlive both the workqueue and the devm-allocated chip containing the work.
Cancel the delayed work synchronously after freeing the IRQ and before destroying the workqueue. This also waits for any running status read to finish before the chip's resources are released.
This issue was identified during our ongoing static-analysis research while reviewing kernel code.
--- drivers/video/backlight/lm3630a_bl.c | 1 + 1 file changed, 1 insertion(+)
drivers/video/backlight/lm3630a_bl.c +1 -0
@@ -593,6 +593,7 @@ static int lm3630a_remove(struct i2c_client *client)if (pchip->irq) {free_irq (pchip->irq, pchip); +cancel_delayed_work_sync (&pchip->work);destroy_workqueue (pchip->irqthread); }return 0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 330/1848 driver core: Limit the messages on a refused uevent
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
[ Upstream commit a01c8e5b1dff1ce489e6b339139e744db36b8bb3 ]
A write to a "uevent" file which is no valid action makes kobject_synth_uevent() print a warning and uevent_store() an error every time. This is generally considered a bad thing so rate limit these messages.
--- drivers/base/core.c | 4 +++- lib/kobject_uevent.c | 6 +++--- 2 files changed, 6 insertions(+), 4 deletions(-)
drivers/base/core.c +3 -1
@@ -2032,7 +2032,9 @@ static ssize_t uevent_store(struct device *dev, struct device_attribute *attr, rc =kobject_synth_uevent (&dev->kobj, buf, count);if (rc) { -dev_err (dev,"uevent: failed to send synthetic uevent\n" ); +dev_err_ratelimited (dev, +"uevent: failed to send synthetic uevent: %d\n" , + rc);return rc; }
lib/kobject_uevent.c +3 -3
@@ -224,9 +224,9 @@ int kobject_synth_uevent(struct kobject *kobj, const char *buf, size_t count) out:if (r) { devpath =kobject_get_path (kobj,GFP_KERNEL ); -pr_warn ("synth uevent: %s: %s\n" , - devpath ?:"unknown device" , - msg ?:"failed to send uevent" ); +pr_warn_ratelimited ("synth uevent: %s: %s\n" , + devpath ?:"unknown device" , + msg ?:"failed to send uevent" );kfree (devpath); }return r;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 331/1848 inet: reject unhashed sockets during established lookups
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hyunwoo Kim <[email protected]>
[ Upstream commit 4e2b3ef19e0e04adca38442f07dd6bc93c712bf1 ]
TCP established ehash lookups are lockless. The socket caches involved use SLAB_TYPESAFE_BY_RCU, so memory can be reused before an RCU reader that retained its old address has finished.
After a tuple match, __inet_lookup_established() and __inet6_lookup_established() acquire a reference and repeat the tuple check. They do not check whether the new object is hashed. If the address is reused for a socket with the same tuple, the lookup can acquire a reference to the new object and return it while its nulls node is unhashed.
A PoC that drives reuse with a SYN cookie request socket reproduced the crash. The new request socket is unhashed and has a NULL rsk_listener. A lookup that had loaded the address of the old request socket acquired the reference published by tcp_get_cookie_sock() and returned the new object. tcp_v4_rcv() then read sk_state through the NULL listener.
The resulting crash was:
BUG: kernel NULL pointer dereference, address: 0000000000000012 #PF: supervisor read access in kernel mode #PF: error_code(0x0000) - not-present page ... Oops: Oops: 0000 [#1] SMP NOPTI CPU: 4 UID: 0 PID: 0 Comm: swapper/4 Not tainted 7.3.0-00591-g0e135910deec #1 PREEMPT(lazy) ... RIP: 0010:tcp_v4_rcv+0x44e/0x1280 ... R10: 0000000000000001 R11: 00000000024ca8c0 R12: 0000000000000000 ... CR2: 0000000000000012 CR3: 0000000103d50004 CR4: 0000000000770ef0 ... Call Trace: <IRQ> ? raw_local_deliver+0xae/0x240 ip_protocol_deliver_rcu+0x2d/0x180 ip_local_deliver_finish+0x84/0x100 ip_sublist_rcv_finish+0x5f/0x70 ip_sublist_rcv+0x12a/0x1d0 ip_list_rcv+0xfd/0x130 __netif_receive_skb_list_core+0x223/0x250 netif_receive_skb_list_internal+0x1d2/0x2c0 ? try_fill_recv+0x39/0x7b0 napi_complete_done+0x74/0x170 virtnet_poll+0x445/0x600 __napi_poll+0x27/0x1e0 net_rx_action+0x2fe/0x3b0 handle_softirqs+0xc2/0x2c0 __irq_exit_rcu+0x74/0xd0 common_interrupt+0x7f/0x90 </IRQ> ... Kernel panic - not syncing: Fatal exception in interrupt
After taking a reference, check whether the nulls node is unhashed in both IPv4 and IPv6 established lookups. If it is unhashed or the tuple no longer matches, drop the reference and restart the lookup.
Lookups racing with the TIME_WAIT hashdance, or with a request being replaced by its child, now restart and find the new socket instead of returning the old one.
Request sockets that were never inserted into ehash can have a nonzero refcount, and a stale lookup can hold a transient reference. Therefore, when SYN cookie, Fast Open, and request migration paths fail after setting a nonzero refcount, release the references held by those paths with reqsk_put() instead of freeing the request directly.
[ Hyunwoo Kim: Request migration is not present in 5.10.y, so omit the
net/ipv4/inet_connection_sock.c changes. Keep the pre-rename INET_MATCH() function name used by 5.10.y. ]
--- net/ipv4/inet_hashtables.c | 5 +++-- net/ipv4/syncookies.c | 2 ++ net/ipv4/tcp_input.c | 4 +++- net/ipv6/inet6_hashtables.c | 4 +++- 4 files changed, 11 insertions(+), 4 deletions(-)
net/ipv4/inet_hashtables.c +3 -2
@@ -420,8 +420,9 @@ struct sock *__inet_lookup_established(struct net *net,if (likely (INET_MATCH (net, sk, acookie, ports, dif, sdif))) {if (unlikely (!refcount_inc_not_zero (&sk->sk_refcnt))) goto out; -if (unlikely (!INET_MATCH (net, sk, acookie, - ports, dif, sdif))) { +if (unlikely (hlist_nulls_unhashed_lockless (&sk->sk_nulls_node) || + !INET_MATCH (net, sk, acookie, ports, dif, + sdif))) {sock_gen_put (sk); goto begin; }
net/ipv4/syncookies.c +2 -0
@@ -217,6 +217,8 @@ struct sock *tcp_get_cookie_sock(struct sock *sk, struct sk_buff *skb,bh_unlock_sock (child);sock_put (child); +reqsk_put (req); +return NULL ; }__reqsk_free (req);
net/ipv4/tcp_input.c +3 -1
@@ -7009,7 +7009,9 @@ int tcp_conn_request(struct request_sock_ops *rsk_ops,if (!inet_csk_reqsk_queue_add (sk, req, fastopen_sk)) {bh_unlock_sock (fastopen_sk);sock_put (fastopen_sk); - goto drop_and_free; +/* tcp_disconnect() already dropped one reqsk ref. */ +reqsk_put (req); + goto drop; } sk->sk_data_ready (sk);bh_unlock_sock (fastopen_sk);
net/ipv6/inet6_hashtables.c +3 -1
@@ -77,7 +77,9 @@ struct sock *__inet6_lookup_established(struct net *net,if (unlikely (!refcount_inc_not_zero (&sk->sk_refcnt))) goto out; -if (unlikely (!inet6_match (net, sk, saddr, daddr, ports, dif, sdif))) { +if (unlikely (hlist_nulls_unhashed_lockless (&sk->sk_nulls_node) || + !inet6_match (net, sk, saddr, daddr, ports, dif, + sdif))) {sock_gen_put (sk); goto begin; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 332/1848 mm/hugetlb: fix use-after-free in hugetlb_mfill_atomic_pte()
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit d8a9cd7fd2fb01211430c933932da58839b8ca65 ]
Let's fix another instance where we use a folio after dropping the PTL, where someone else could e.g., MADV_DONTNEED it once we drop the PTL, making us trigger a use-after-free on the folio.
--- mm/hugetlb.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
mm/hugetlb.c +6 -1
@@ -4806,10 +4806,15 @@ int hugetlb_mcopy_atomic_pte(struct mm_struct *dst_mm,/* No need to invalidate - it was non-present before */ update_mmu_cache (dst_vma, dst_addr, dst_pte); -spin_unlock (ptl);set_page_huge_active (page);if (vm_shared)unlock_page (page); + +/* +* Hold the PTL until we're done with the page: the page table owns the +* page reference now. +*/ +spin_unlock (ptl); ret =0 ; out:return ret;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 333/1848 smb: client: fix warning in CIFSFindFirst()
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paulo Alcantara <[email protected]>
[ Upstream commit 032137fe136a6073dcc699ee15fa3fd05fd77f21 ]
This fixes the following warning reported by kernel test robot
fs/smb/client/cifssmb.c:4089 CIFSFindFirst() warn: missing error code? 'rc'
Stable-dep-of: 59131dd72f62 ("smb: client: fix use-after-free infoleak via the readdir resume name")
--- fs/cifs/cifssmb.c | 94 +++++++++++++++++++++-------------------------- 1 file changed, 42 insertions(+), 52 deletions(-)
fs/cifs/cifssmb.c +42 -52
@@ -4441,11 +4441,12 @@ CIFSFindFirst(const unsigned int xid, struct cifs_tcon *tcon,TRANSACTION2_FFIRST_REQ *pSMB =NULL ;TRANSACTION2_FFIRST_RSP *pSMBr =NULL ;T2_FFIRST_RSP_PARMS *parms; -int rc =0 ; +struct nls_table *nls_codepage; +unsigned int lnoff; +__u16 params, byte_count;int bytes_returned =0 ;int name_len, remap; -__u16 params, byte_count; -struct nls_table *nls_codepage; +int rc =0 ;cifs_dbg (FYI ,"In FindFirst for %s\n" , searchName);
@@ -4536,63 +4537,52 @@ CIFSFindFirst(const unsigned int xid, struct cifs_tcon *tcon, (struct smb_hdr *) pSMBr, &bytes_returned, 0);cifs_stats_inc (&tcon->stats.cifs_stats.num_ffirst); -if (rc) {/* BB add logic to retry regular search if Unix search -rejected unexpectedly by server */ -/* BB Add code to handle unsupported level rc */ +if (rc) { +/* +* BB: add logic to retry regular search if Unix search rejected +* unexpectedly by server. +*/ +/* BB: add code to handle unsupported level rc */ cifs_dbg (FYI ,"Error in FindFirst = %d\n" , rc); -cifs_buf_release (pSMB); - -/* BB eventually could optimize out free and realloc of buf */ -/* for this case */ +/* +* BB: eventually could optimize out free and realloc of buf for +* this case. +*/ if (rc == -EAGAIN ) goto findFirstRetry; - }else {/* decode response */ -/* BB remember to free buffer if error BB */ - rc =validate_t2 ((struct smb_t2_rsp *)pSMBr); -if (rc ==0 ) { -unsigned int lnoff; - -if (pSMBr->hdr.Flags2 &SMBFLG2_UNICODE ) - psrch_inf->unicode = true; -else - psrch_inf->unicode = false; - - psrch_inf->ntwrk_buf_start = (char *)pSMBr; - psrch_inf->smallBuf = false; - psrch_inf->srch_entries_start = - (char *) &pSMBr->hdr.Protocol + -le16_to_cpu (pSMBr->t2.DataOffset); - parms = (T2_FFIRST_RSP_PARMS *)((char *) &pSMBr->hdr.Protocol + -le16_to_cpu (pSMBr->t2.ParameterOffset)); - -if (parms->EndofSearch) - psrch_inf->endOfSearch = true; -else - psrch_inf->endOfSearch = false; +return rc; + } +/* decode response */ + rc =validate_t2 ((struct smb_t2_rsp *)pSMBr); +if (rc) { +cifs_buf_release (pSMB); +return rc; + } - psrch_inf->entries_in_buffer = -le16_to_cpu (parms->SearchCount); - psrch_inf->index_of_last_entry =2 /* skip . and .. */ + - psrch_inf->entries_in_buffer; - lnoff =le16_to_cpu (parms->LastNameOffset); -if (CIFSMaxBufSize < lnoff) { -cifs_dbg (VFS ,"ignoring corrupt resume name\n" ); - psrch_inf->last_entry =NULL ; -return rc; - } + psrch_inf->unicode = !!(pSMBr->hdr.Flags2 &SMBFLG2_UNICODE ); + psrch_inf->ntwrk_buf_start = (char *)pSMBr; + psrch_inf->smallBuf = false; + psrch_inf->srch_entries_start = (char *)&pSMBr->hdr.Protocol + +le16_to_cpu (pSMBr->t2.DataOffset); - psrch_inf->last_entry = psrch_inf->srch_entries_start + - lnoff; + parms = (T2_FFIRST_RSP_PARMS *)((char *)&pSMBr->hdr.Protocol + +le16_to_cpu (pSMBr->t2.ParameterOffset)); + psrch_inf->endOfSearch = !!parms->EndofSearch; -if (pnetfid) - *pnetfid = parms->SearchHandle; - }else { -cifs_buf_release (pSMB); - } + psrch_inf->entries_in_buffer =le16_to_cpu (parms->SearchCount); + psrch_inf->index_of_last_entry =2 /* skip . and .. */ + + psrch_inf->entries_in_buffer; + lnoff =le16_to_cpu (parms->LastNameOffset); +if (CIFSMaxBufSize < lnoff) { +cifs_dbg (VFS ,"ignoring corrupt resume name\n" ); + psrch_inf->last_entry =NULL ; + }else { + psrch_inf->last_entry = psrch_inf->srch_entries_start + lnoff; +if (pnetfid) + *pnetfid = parms->SearchHandle; } - -return rc; +return 0 ; } int CIFSFindNext(const unsigned int xid, struct cifs_tcon *tcon,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 334/1848 smb: client: fix warning in CIFSFindNext()
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paulo Alcantara <[email protected]>
[ Upstream commit 215533f888dcf18f7cfbbf520bdd52e67ac6265a ]
This fixes the following warning reported by kernel test robot
fs/smb/client/cifssmb.c:4216 CIFSFindNext() warn: missing error code? 'rc'
Stable-dep-of: 59131dd72f62 ("smb: client: fix use-after-free infoleak via the readdir resume name")
--- fs/cifs/cifssmb.c | 111 +++++++++++++++++++++------------------------- 1 file changed, 51 insertions(+), 60 deletions(-)
fs/cifs/cifssmb.c +51 -60
@@ -4592,11 +4592,12 @@ int CIFSFindNext(const unsigned int xid, struct cifs_tcon *tcon,TRANSACTION2_FNEXT_REQ *pSMB =NULL ;TRANSACTION2_FNEXT_RSP *pSMBr =NULL ;T2_FNEXT_RSP_PARMS *parms; -char *response_data; -int rc =0 ; -int bytes_returned;unsigned int name_len; +unsigned int lnoff;__u16 params, byte_count; +char *response_data; +int bytes_returned; +int rc =0 ;cifs_dbg (FYI ,"In FindNext\n" );
@@ -4641,8 +4642,8 @@ int CIFSFindNext(const unsigned int xid, struct cifs_tcon *tcon, pSMB->ResumeFileName[name_len] =0 ; pSMB->ResumeFileName[name_len+1 ] =0 ; }else { - rc = -EINVAL ; - goto FNext2_err_exit; +cifs_buf_release (pSMB); +return -EINVAL ; } byte_count = params +1 /* pad */ ; pSMB->TotalParameterCount =cpu_to_le16 (params);
@@ -4653,71 +4654,61 @@ int CIFSFindNext(const unsigned int xid, struct cifs_tcon *tcon, rc =SendReceive (xid, tcon->ses, (struct smb_hdr *) pSMB, (struct smb_hdr *) pSMBr, &bytes_returned,0 );cifs_stats_inc (&tcon->stats.cifs_stats.num_fnext); +if (rc) { +cifs_buf_release (pSMB);if (rc == -EBADF ) { psrch_inf->endOfSearch = true; -cifs_buf_release (pSMB); rc =0 ;/* search probably was closed at end of search*/ - }else + }else {cifs_dbg (FYI ,"FindNext returned = %d\n" , rc); - }else {/* decode response */ - rc =validate_t2 ((struct smb_t2_rsp *)pSMBr); - -if (rc ==0 ) { -unsigned int lnoff; - -/* BB fixme add lock for file (srch_info) struct here */ -if (pSMBr->hdr.Flags2 &SMBFLG2_UNICODE ) - psrch_inf->unicode = true; -else - psrch_inf->unicode = false; - response_data = (char *) &pSMBr->hdr.Protocol + -le16_to_cpu (pSMBr->t2.ParameterOffset); - parms = (T2_FNEXT_RSP_PARMS *)response_data; - response_data = (char *)&pSMBr->hdr.Protocol + -le16_to_cpu (pSMBr->t2.DataOffset); -if (psrch_inf->smallBuf) -cifs_small_buf_release ( - psrch_inf->ntwrk_buf_start); -else -cifs_buf_release (psrch_inf->ntwrk_buf_start); - psrch_inf->srch_entries_start = response_data; - psrch_inf->ntwrk_buf_start = (char *)pSMB; - psrch_inf->smallBuf = false; -if (parms->EndofSearch) - psrch_inf->endOfSearch = true; -else - psrch_inf->endOfSearch = false; - psrch_inf->entries_in_buffer = -le16_to_cpu (parms->SearchCount); - psrch_inf->index_of_last_entry += - psrch_inf->entries_in_buffer; - lnoff =le16_to_cpu (parms->LastNameOffset); -if (CIFSMaxBufSize < lnoff) { -cifs_dbg (VFS ,"ignoring corrupt resume name\n" ); - psrch_inf->last_entry =NULL ; -return rc; - }else - psrch_inf->last_entry = - psrch_inf->srch_entries_start + lnoff; - -/* cifs_dbg(FYI, "fnxt2 entries in buf %d index_of_last %d\n", -psrch_inf->entries_in_buffer, psrch_inf->index_of_last_entry); */ - -/* BB fixme add unlock here */ } +return rc; + } +/* decode response */ + rc =validate_t2 ((struct smb_t2_rsp *)pSMBr); +if (rc) { +cifs_buf_release (pSMB); +return rc; } +/* BB fixme add lock for file (srch_info) struct here */ + psrch_inf->unicode = !!(pSMBr->hdr.Flags2 &SMBFLG2_UNICODE ); + response_data = (char *)&pSMBr->hdr.Protocol + +le16_to_cpu (pSMBr->t2.ParameterOffset); + parms = (T2_FNEXT_RSP_PARMS *)response_data; + response_data = (char *)&pSMBr->hdr.Protocol + +le16_to_cpu (pSMBr->t2.DataOffset); -/* BB On error, should we leave previous search buf (and count and -last entry fields) intact or free the previous one? */ +if (psrch_inf->smallBuf) +cifs_small_buf_release (psrch_inf->ntwrk_buf_start); +else +cifs_buf_release (psrch_inf->ntwrk_buf_start); -/* Note: On -EAGAIN error only caller can retry on handle based calls -since file handle passed in no longer valid */ -FNext2_err_exit: -if (rc !=0 ) -cifs_buf_release (pSMB); -return rc; + psrch_inf->srch_entries_start = response_data; + psrch_inf->ntwrk_buf_start = (char *)pSMB; + psrch_inf->smallBuf = false; + psrch_inf->endOfSearch = !!parms->EndofSearch; + psrch_inf->entries_in_buffer =le16_to_cpu (parms->SearchCount); + psrch_inf->index_of_last_entry += psrch_inf->entries_in_buffer; + lnoff =le16_to_cpu (parms->LastNameOffset); +if (CIFSMaxBufSize < lnoff) { +cifs_dbg (VFS ,"ignoring corrupt resume name\n" ); + psrch_inf->last_entry =NULL ; + }else { + psrch_inf->last_entry = + psrch_inf->srch_entries_start + lnoff; + } +/* BB fixme add unlock here */ + +/* +* BB: On error, should we leave previous search buf +* (and count and last entry fields) intact or free the previous one? +* +* Note: On -EAGAIN error only caller can retry on handle based calls +* since file handle passed in no longer valid. +*/ +return 0 ; }int
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 335/1848 smb: client: fix use-after-free infoleak via the readdir resume name
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Diego Oliva <[email protected]>
[ Upstream commit 59131dd72f62b198fc9ea1489ad9d3573154f684 ]
CIFSFindNext() copies the resume name that cifs_save_resume_key() recorded from the last entry of the previous response into its request; psrch_inf->presume_name points into the response buffer that entry came from, and nothing ever clears it. find_cifs_entry() records a new name only from a response with a usable last entry, and cifs_readdir() only from an entry it walks to, so a response that carries no entries and leaves last_entry NULL, because CIFSFindFirst() or CIFSFindNext() rejected LastNameOffset, refreshes neither and presume_name keeps pointing into the previous response. That buffer has already been
released: by CIFSFindNext() before it installs the new response, or by find_cifs_entry() when it rewinds the search, which does not drop the name either and can then fail in initiate_cifs_search() before a new response replaces it. The next CIFSFindNext() then copies up to PATH_MAX - 1 bytes of the resume name out of the released buffer into its request and sends them to the server: a use-after-free read that leaks kernel memory to a malicious or compromised server, which can provoke it with a single FindNext response that carries no entries and a LastNameOffset above CIFSMaxBufSize, which is all the existing check rejects.
With KASAN enabled, a server that answers a listing that way gives:
CIFS: VFS: ignoring corrupt resume name
==================================================================
BUG: KASAN: slab-use-after-free in CIFSFindNext+0x8ca/0x14c0 Read of size 4080 at addr ffff88807c823f98 by task ls/83 CPU: 0 UID: 0 PID: 83 Comm: ls Tainted: G B 7.3.0-rc4-00457-gf14572c203d5 #69 PREEMPT(lazy) Tainted: [B]=BAD_PAGE Call Trace: <TASK> kasan_report+0xdf/0x1a0 kasan_check_range+0x10f/0x1e0 __asan_memcpy+0x23/0x60 CIFSFindNext+0x8ca/0x14c0 cifs_readdir+0xf51/0x29c0 iterate_dir+0x1c0/0x570 __x64_sys_getdents64+0x133/0x270 do_syscall_64+0x109/0x5d0 entry_SYSCALL_64_after_hwframe+0x77/0x7f </TASK> Allocated by task 83 on cpu 1 at 13.497119s: cifs_buf_get+0x36/0x90 smb_init+0x4f/0x110 CIFSFindNext+0xf7/0x14c0 cifs_readdir+0xf51/0x29c0 Freed by task 83 on cpu 0 at 13.584018s: cifs_buf_release+0x41/0x80 CIFSFindNext+0xfce/0x14c0 cifs_readdir+0xf51/0x29c0
The buggy address is located 16280 bytes inside of
freed 16588-byte region [ffff88807c820000, ffff88807c8240cc)
==================================================================
The same memcpy() first reads past the end of that object while it is still live, a slab-out-of-bounds read that the following patches bound; that is the taint the report above carries.
SMB1 is not negotiated by default; reaching this code requires an explicit vers=1.0 mount.
Clear presume_name and resume_name_len whenever a new response is installed and when the rewind path releases the search buffer, so that the name never outlives the buffer it points into, and reset resume_key with them, since it was taken from the same entry and would otherwise be sent with an empty name. A response without a usable last entry then continues the search with an empty resume name rather than a stale one; CIFSFindNext() skips the copy of a zero-length name so that it never runs on the NULL pointer.
The next patch in the series leaves last_entry NULL for a response that carries no entries, and bounds LastNameOffset against the received response rather than against CIFSMaxBufSize. Responses that are given a last entry today then take the path fixed here, so that patch must not be applied without this one.
--- fs/cifs/cifssmb.c | 11 ++++++++++- fs/cifs/readdir.c | 3 +++ 2 files changed, 13 insertions(+), 1 deletion(-)
fs/cifs/cifssmb.c +10 -1
@@ -4573,6 +4573,9 @@ CIFSFindFirst(const unsigned int xid, struct cifs_tcon *tcon, psrch_inf->entries_in_buffer =le16_to_cpu (parms->SearchCount); psrch_inf->index_of_last_entry =2 /* skip . and .. */ + psrch_inf->entries_in_buffer; + psrch_inf->presume_name =NULL ; + psrch_inf->resume_name_len =0 ; + psrch_inf->resume_key =0 ; lnoff =le16_to_cpu (parms->LastNameOffset);if (CIFSMaxBufSize < lnoff) {cifs_dbg (VFS ,"ignoring corrupt resume name\n" );
@@ -4636,7 +4639,10 @@ int CIFSFindNext(const unsigned int xid, struct cifs_tcon *tcon, name_len = psrch_inf->resume_name_len; params += name_len;if (name_len <PATH_MAX ) { -memcpy (pSMB->ResumeFileName, psrch_inf->presume_name, name_len); +if (name_len) { +memcpy (pSMB->ResumeFileName, + psrch_inf->presume_name, name_len); + } byte_count += name_len;/* 14 byte parm len above enough for 2 byte null terminator */ pSMB->ResumeFileName[name_len] =0 ;
@@ -4691,6 +4697,9 @@ int CIFSFindNext(const unsigned int xid, struct cifs_tcon *tcon, psrch_inf->endOfSearch = !!parms->EndofSearch; psrch_inf->entries_in_buffer =le16_to_cpu (parms->SearchCount); psrch_inf->index_of_last_entry += psrch_inf->entries_in_buffer; + psrch_inf->presume_name =NULL ; + psrch_inf->resume_name_len =0 ; + psrch_inf->resume_key =0 ; lnoff =le16_to_cpu (parms->LastNameOffset);if (CIFSMaxBufSize < lnoff) {cifs_dbg (VFS ,"ignoring corrupt resume name\n" );
fs/cifs/readdir.c +3 -0
@@ -759,6 +759,9 @@ find_cifs_entry(const unsigned int xid, struct cifs_tcon *tcon, loff_t pos, cfile->srch_inf.ntwrk_buf_start =NULL ; cfile->srch_inf.srch_entries_start =NULL ; cfile->srch_inf.last_entry =NULL ; + cfile->srch_inf.presume_name =NULL ; + cfile->srch_inf.resume_name_len =0 ; + cfile->srch_inf.resume_key =0 ; } rc =initiate_cifs_search (xid, file, full_path);if (rc) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 336/1848 smb: client: fix OOB last_entry pointer from unbounded LastNameOffset
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Diego Oliva <[email protected]>
[ Upstream commit 570c783a96f054dd3ac409a92772e9afb705d21c ]
CIFSFindFirst() and CIFSFindNext() locate the last entry of a TRANS2_FIND_FIRST2 or TRANS2_FIND_NEXT2 response by adding the LastNameOffset of the response parameters to the start of the data area, and store the result in psrch_inf->last_entry. MS-CIFS 2.2.6.2.2 defines that offset as the offset of the entry's file name; the client follows the reading of NT and Samba servers, which point it at the entry. LastNameOffset is only checked against CIFSMaxBufSize, which says nothing about the response actually received: validate_t2() lets the data area start up to 1024 bytes into the buffer, and SendReceive() copies at most CIFSMaxBufSize + MAX_CIFS_HDR_SIZE bytes of a response, 16468 by default, into a cifs_request allocation of CIFSMaxBufSize + MAX_SMB2_HDR_SIZE bytes, 16588 by default. The pointer itself can therefore be placed anywhere from the end of the received data to 820 bytes past the end of the allocation.
The read through that pointer is far larger than its displacement. find_cifs_entry() hands last_entry to cifs_save_resume_key() after every FindNext and after the FindFirst of a search rewind, and cifs_fill_dirent() takes the length of the name from the entry itself: a __le32 FileNameLength for most levels, a __u8 for SMB_FIND_FILE_INFO_STANDARD, and for SMB_FIND_FILE_UNIX the result of a scan for the terminating NUL over up to PATH_MAX + 1 UTF-16 units. The name is recorded as the resume name of the search, and the next CIFSFindNext() rejects only a recorded length of PATH_MAX or more before copying the name into the ResumeFileName of its request and sending it with the resume key taken from the same entry: up to 4 KiB of memory from past the end of the allocation leaks to the server, and for SMB_FIND_FILE_UNIX the NUL scan runs about twice as far before the length is even known. The entry does not have to lie outside the response for that either: a maximal response ends about 120 bytes before the end of the allocation, so an entry in its last bytes with a name just under PATH_MAX has nearly all of that name copied from past the allocation.
It needs nothing unusual from the client: a FindNext response that reports no entries and does not end the search makes find_cifs_entry() send the next FindNext at once, carrying whatever was parsed at LastNameOffset, and a search rewind can do the same after its FindFirst. SMB1 is not negotiated by default: this takes a malicious or compromised server, a mount of it with an explicit vers=1.0, which CONFIG_CIFS_ALLOW_INSECURE_LEGACY (default y) permits, and a directory listing on that mount.
With KASAN enabled, a response that places the last entry past the buffer, with a large DataOffset and a LastNameOffset near the end of its range, gives:
==================================================================
BUG: KASAN: slab-out-of-bounds in cifs_save_resume_key.isra.0+0x7aa/0x7f0 Read of size 4 at addr ffff88807b55c33b by task ls/83 CPU: 1 UID: 0 PID: 83 Comm: ls Not tainted 7.3.0-rc4-00457-gf14572c203d5 #69 PREEMPT(lazy) Call Trace: <TASK> kasan_report+0xdf/0x1a0 cifs_save_resume_key.isra.0+0x7aa/0x7f0 cifs_readdir+0x1ed6/0x29c0 iterate_dir+0x1c0/0x570 __x64_sys_getdents64+0x133/0x270 do_syscall_64+0x109/0x5d0 entry_SYSCALL_64_after_hwframe+0x77/0x7f </TASK> Allocated by task 83 on cpu 0 at 19.317556s: cifs_buf_get+0x36/0x90 smb_init+0x4f/0x110 CIFSFindNext+0xf7/0x14c0 cifs_readdir+0xf51/0x29c0 The buggy address belongs to the object at ffff88807b558000 which belongs to the cache cifs_request of size 16588 The buggy address is located 623 bytes to the right of allocated 16588-byte region [ffff88807b558000, ffff88807b55c0cc) ==================================================================
The four bytes read there are the FileNameLength of the entry, which cifs_fill_dirent() takes before anything checks where the entry lies.
Ignore the last entry when it does not start inside the received response or the response holds no entries; for a response without entries, last_entry pointed into or past its empty data area and cifs_save_resume_key() parsed whatever the buffer held there. The entry is bounded by the response that was received, which is what the buffer holds, rather than by the data area the response declares, which a later patch checks against the received length. Record the search handle before the last entry is examined, since a response without a usable last entry still carries the handle that the search is continued and closed with; leaving the assignment in the else branch would drop the handle of every response without entries.
This bounds where the last entry starts, not how far it is parsed: an entry that starts within the final bytes of the response still has its fixed part read past the end of the received data and its name, up to 4095 bytes, copied from past the end of the allocation, until the following patch bounds the parse itself. A response without a usable last entry continues the search with an empty resume name, since the preceding patch, "smb: client: fix use-after-free infoleak via the readdir resume name", drops the recorded name whenever a new response is installed. This patch applies on top of that one and relies on it: without it, every response rejected here would leave the previous name in place, pointing into a buffer that has been released.
A conforming server is not affected: the last entry lies inside the data area of the response.
--- fs/cifs/cifssmb.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-)
fs/cifs/cifssmb.c +10 -4
@@ -4576,14 +4576,17 @@ CIFSFindFirst(const unsigned int xid, struct cifs_tcon *tcon, psrch_inf->presume_name =NULL ; psrch_inf->resume_name_len =0 ; psrch_inf->resume_key =0 ; +if (pnetfid) + *pnetfid = parms->SearchHandle; lnoff =le16_to_cpu (parms->LastNameOffset); -if (CIFSMaxBufSize < lnoff) { +if (!psrch_inf->entries_in_buffer) { + psrch_inf->last_entry =NULL ; + }else if (psrch_inf->srch_entries_start + lnoff >= + psrch_inf->ntwrk_buf_start + bytes_returned) {cifs_dbg (VFS ,"ignoring corrupt resume name\n" ); psrch_inf->last_entry =NULL ; }else { psrch_inf->last_entry = psrch_inf->srch_entries_start + lnoff; -if (pnetfid) - *pnetfid = parms->SearchHandle; }return 0 ; }
@@ -4701,7 +4704,10 @@ int CIFSFindNext(const unsigned int xid, struct cifs_tcon *tcon, psrch_inf->resume_name_len =0 ; psrch_inf->resume_key =0 ; lnoff =le16_to_cpu (parms->LastNameOffset); -if (CIFSMaxBufSize < lnoff) { +if (!psrch_inf->entries_in_buffer) { + psrch_inf->last_entry =NULL ; + }else if (psrch_inf->srch_entries_start + lnoff >= + psrch_inf->ntwrk_buf_start + bytes_returned) {cifs_dbg (VFS ,"ignoring corrupt resume name\n" ); psrch_inf->last_entry =NULL ; }else {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 337/1848 HID: wacom: Redesign shared sibling data lifecycle
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lee Jones <[email protected]>
[ Upstream commit 480c9cb14ae81f8e112ff83f8778b3d7b9324dc8 ]
The Wacom driver coordinates state between sibling interfaces of the same physical device using a shared structure 'wacom_shared' inside 'wacom_hdev_data'. The driver kept a volatile representative pointer 'data->dev' pointing to a sibling 'hid_device' for physical path comparisons during sibling matching.
This pointer management is fragile. When the representative device is disconnected, wacom_remove_shared_data() failed to clear/update 'data->dev', leading to a Use-After-Free vulnerability when subsequent sibling probes dereference the dangling 'data->dev' pointer.
Resolve this issue by redesigning the sibling data lifecycle:
- Eliminate the volatile 'data->dev' representative pointer completely
- Redesign 'wacom_hdev_data' to store stable static copies of the required attributes upon first allocation: 'phys' path string, 'vendor', 'product' IDs and the sibling's 'device_type'
- Use these static attributes for stable sibling matching in wacom_are_sibling() and wacom_get_hdev_data()
This ensures sibling matching remains safe and stable even if individual siblings are dynamically added or removed.
To secure the lifecycle against concurrent probe/disconnect races:
- Switch kref_put() to kref_put_mutex() in wacom_remove_shared_data() to serialize refcount drops with list traversal and lookup
- Modify wacom_release_shared_data() to assume the list lock is already held
Also, do not accumulate the 'device_type' capability flag during subsequent sibling probes. Keeping only the first probed sibling's device_type exactly preserves the original sibling matching behavior without introducing side effects.
--- drivers/hid/wacom_sys.c | 70 +++++++++++++++++++++++++++-------------- 1 file changed, 46 insertions(+), 24 deletions(-)
drivers/hid/wacom_sys.c +46 -24
@@ -750,27 +750,47 @@ static void wacom_retrieve_hid_descriptor(struct hid_device *hdev,struct wacom_hdev_data {struct list_head list;struct kref kref; -struct hid_device *dev; +char phys[64 ]; +__u32 vendor; +__u32 product; +__u32 device_type;struct wacom_shared shared; }; +static bool wacom_compare_device_paths (struct hid_device *hdev_a, +const char *phys_b,char separator) +{ +const char *p1 =strrchr (hdev_a->phys, separator); +const char *p2 =strrchr (phys_b, separator); +int n1, n2; + +if (!p1 || !p2) +return false; + + n1 = p1 - hdev_a->phys; + n2 = p2 - phys_b; + +if (n1 != n2 || n1 <=0 || n2 <=0 ) +return false; + +return !strncmp (hdev_a->phys, phys_b, n1); +} +static LIST_HEAD (wacom_udev_list);static DEFINE_MUTEX (wacom_udev_list_lock);static bool wacom_are_sibling (struct hid_device *hdev, -struct hid_device *sibling) +struct wacom_hdev_data *data) {struct wacom *wacom =hid_get_drvdata (hdev);struct wacom_features *features = &wacom->wacom_wac.features; -struct wacom *sibling_wacom =hid_get_drvdata (sibling); -struct wacom_features *sibling_features = &sibling_wacom->wacom_wac.features;__u32 oVid = features->oVid ? features->oVid : hdev->vendor;__u32 oPid = features->oPid ? features->oPid : hdev->product;/* The defined oVid/oPid must match that of the sibling */ -if (features->oVid !=HID_ANY_ID && sibling->vendor != oVid) +if (features->oVid !=HID_ANY_ID && data->vendor != oVid)return false; -if (features->oPid !=HID_ANY_ID && sibling->product != oPid) +if (features->oPid !=HID_ANY_ID && data->product != oPid)return false;/*
@@ -778,11 +798,11 @@ static bool wacom_are_sibling(struct hid_device *hdev,* device path, while those with different VID/PID must share * the same physical parent device path. */ -if (hdev->vendor == sibling->vendor && hdev->product == sibling->product) { -if (!hid_compare_device_paths (hdev, sibling,'/' )) +if (hdev->vendor == data->vendor && hdev->product == data->product) { +if (!wacom_compare_device_paths (hdev, data->phys,'/' ))return false; }else { -if (!hid_compare_device_paths (hdev, sibling,'.' )) +if (!wacom_compare_device_paths (hdev, data->phys,'.' ))return false; }
@@ -795,7 +815,7 @@ static bool wacom_are_sibling(struct hid_device *hdev,* devices. */ if ((features->device_type &WACOM_DEVICETYPE_DIRECT ) && - !(sibling_features->device_type &WACOM_DEVICETYPE_DIRECT )) + !(data->device_type &WACOM_DEVICETYPE_DIRECT ))return false;/*
@@ -803,17 +823,17 @@ static bool wacom_are_sibling(struct hid_device *hdev,* devices. */ if (!(features->device_type &WACOM_DEVICETYPE_DIRECT ) && - (sibling_features->device_type &WACOM_DEVICETYPE_DIRECT )) + (data->device_type &WACOM_DEVICETYPE_DIRECT ))return false;/* Pen devices may only be siblings of touch devices */ if ((features->device_type &WACOM_DEVICETYPE_PEN ) && - !(sibling_features->device_type &WACOM_DEVICETYPE_TOUCH )) + !(data->device_type &WACOM_DEVICETYPE_TOUCH ))return false;/* Touch devices may only be siblings of pen devices */ if ((features->device_type &WACOM_DEVICETYPE_TOUCH ) && - !(sibling_features->device_type &WACOM_DEVICETYPE_PEN )) + !(data->device_type &WACOM_DEVICETYPE_PEN ))return false;/*
@@ -829,7 +849,7 @@ static struct wacom_hdev_data *wacom_get_hdev_data(struct hid_device *hdev)/* Try to find an already-probed interface from the same device */ list_for_each_entry (data, &wacom_udev_list, list) { -if (hid_compare_device_paths (hdev, data->dev,'/' )) { +if (wacom_compare_device_paths (hdev, data->phys,'/' )) {kref_get (&data->kref);return data; }
@@ -837,7 +857,7 @@ static struct wacom_hdev_data *wacom_get_hdev_data(struct hid_device *hdev)/* Fallback to finding devices that appear to be "siblings" */ list_for_each_entry (data, &wacom_udev_list, list) { -if (wacom_are_sibling (hdev, data->dev)) { +if (wacom_are_sibling (hdev, data)) {kref_get (&data->kref);return data; }
@@ -851,29 +871,28 @@ static void wacom_release_shared_data(struct kref *kref)struct wacom_hdev_data *data = container_of(kref, struct wacom_hdev_data, kref); -mutex_lock (&wacom_udev_list_lock);list_del (&data->list); -mutex_unlock (&wacom_udev_list_lock); -kfree (data); }static void wacom_remove_shared_data (void *res) { -struct wacom *wacom = res; +struct wacom *res_wacom = res;struct wacom_hdev_data *data; -struct wacom_wac *wacom_wac = &wacom->wacom_wac; +struct wacom_wac *wacom_wac = &res_wacom->wacom_wac;if (wacom_wac->shared) { data = container_of(wacom_wac->shared, struct wacom_hdev_data, shared); -if (wacom_wac->shared->touch == wacom->hdev) +if (wacom_wac->shared->touch == res_wacom->hdev) wacom_wac->shared->touch =NULL ; -else if (wacom_wac->shared->pen == wacom->hdev) +else if (wacom_wac->shared->pen == res_wacom->hdev) wacom_wac->shared->pen =NULL ; -kref_put (&data->kref, wacom_release_shared_data); +if (kref_put_mutex (&data->kref, wacom_release_shared_data, &wacom_udev_list_lock)) +mutex_unlock (&wacom_udev_list_lock); + wacom_wac->shared =NULL ; } }
@@ -896,7 +915,10 @@ static int wacom_add_shared_data(struct hid_device *hdev) }kref_init (&data->kref); - data->dev = hdev; +strscpy (data->phys, hdev->phys,sizeof (data->phys)); + data->vendor = hdev->vendor; + data->product = hdev->product; + data->device_type = wacom_wac->features.device_type;list_add_tail (&data->list, &wacom_udev_list); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 338/1848 genirq: Defer kfree(irqaction) until irq_thread_dtor() finishes
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Richard Patel <[email protected]>
[ Upstream commit d04adff6860587e843948b0c31174f8ae11b8dfe ]
When an interrupt thread exits abnormally via do_exit() (e.g. the interrupt handler oopses) without returning from irq_thread(), a concurrent call to free_irq() could free the irqaction before the irq_thread_dtor() exit task work runs.
irq thread (oopsed) free_irq()
------------------- ----------
do_exit()
exit_mm()
complete_vfork_done() -------> kthread_stop() returns
exit_files() ... kfree(action)
exit_task_work()
irq_thread_dtor()
action->... <- use-after-freeTrack the pending exit work with the IRQTF_EXIT_WORK thread flag, and have __free_irq() wait for the bit to clear before kfree().
irq_thread_dtor() only runs on irq_thread abnormal exit. If that dtor also faults, free_irq() will hang indefinitely, but double IRQ thread faults require a reboot anyways.
[ tglx: Add missing include ]
--- kernel/irq/internals.h | 2 ++ kernel/irq/manage.c | 32 ++++++++++++++++++++++---------- 2 files changed, 24 insertions(+), 10 deletions(-)
kernel/irq/internals.h +2 -0
@@ -30,6 +30,7 @@ extern struct irqaction chained_action;* IRQTF_AFFINITY - irq thread is requested to adjust affinity * IRQTF_FORCED_THREAD - irq action is force threaded * IRQTF_READY - signals that irq thread is ready +* IRQTF_EXIT_WORK - irq thread exit task_work is pending */ enum {IRQTF_RUNTHREAD ,
@@ -37,6 +38,7 @@ enum {IRQTF_AFFINITY ,IRQTF_FORCED_THREAD ,IRQTF_READY , + IRQTF_EXIT_WORK, };/*
kernel/irq/manage.c +22 -10
@@ -21,6 +21,7 @@#include <linux/sched/isolation.h> #include <uapi/linux/sched/types.h> #include <linux/task_work.h> +#include <linux/wait_bit.h> #include "internals.h"
@@ -1225,17 +1226,14 @@ static void wake_threads_waitq(struct irq_desc *desc)wake_up (&desc->wait_for_threads); } -static void irq_thread_dtor (struct callback_head *unused) +static void __irq_thread_dtor (struct irqaction *action) {struct task_struct *tsk = current;struct irq_desc *desc; -struct irqaction *action;if (WARN_ON_ONCE (!(current->flags &PF_EXITING )))return ; - action =kthread_data (tsk); -pr_err ("exiting task \"%s\" (%d) is an active IRQ thread (irq %d)\n" , tsk->comm, tsk->pid, action->irq);
@@ -1252,6 +1250,14 @@ static void irq_thread_dtor(struct callback_head *unused)irq_finalize_oneshot (desc, action); } +static void irq_thread_dtor (struct callback_head *unused) +{ +struct irqaction *action =kthread_data (current); + +__irq_thread_dtor (action); +clear_and_wake_up_bit (IRQTF_EXIT_WORK , &action->thread_flags); +} +static void irq_wake_secondary (struct irq_desc *desc,struct irqaction *action) {struct irqaction *secondary = action->secondary;
@@ -1308,6 +1314,7 @@ static int irq_thread(void *data)else handler_fn = irq_thread_fn; +set_bit (IRQTF_EXIT_WORK , &action->thread_flags);init_task_work (&on_exit_work, irq_thread_dtor);task_work_add (current, &on_exit_work,TWA_NONE );
@@ -1332,6 +1339,7 @@ static int irq_thread(void *data)* oneshot mask bit can be set. */ task_work_cancel_func (current, irq_thread_dtor); +clear_and_wake_up_bit (IRQTF_EXIT_WORK , &action->thread_flags);return 0 ; }
@@ -1863,6 +1871,13 @@ __setup_irq(unsigned int irq, struct irq_desc *desc, struct irqaction *new)return ret; } +static void irq_stop_thread (struct irqaction *action) +{ +kthread_stop (action->thread); +put_task_struct (action->thread); +wait_on_bit (&action->thread_flags,IRQTF_EXIT_WORK ,TASK_UNINTERRUPTIBLE ); +} +/* * Internal function to unregister an irqaction - used to free * regular and special interrupts that are part of the architecture.
@@ -1967,12 +1982,9 @@ static struct irqaction *__free_irq(struct irq_desc *desc, void *dev_id)* the same bit to a newly requested action. */ if (action->thread) { -kthread_stop (action->thread); -put_task_struct (action->thread); -if (action->secondary && action->secondary->thread) { -kthread_stop (action->secondary->thread); -put_task_struct (action->secondary->thread); - } +irq_stop_thread (action); +if (action->secondary && action->secondary->thread) +irq_stop_thread (action->secondary); }/* Last action releases resources */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 339/1848 staging: rtl8723bs: fix protected RX frame validation in decrypt path
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tianchu Chen <[email protected]>
[ Upstream commit 495cb31c791bdf3f9efef255a9587b05b0526c9d ]
The RX software decrypt path mishandles crafted protected frames from a malicious AP in two ways:
1) decryptor() never checks that a protected frame is long enough to hold the 802.11 header plus the per-cipher trailer. All of rtw_wep_decrypt(), rtw_tkip_decrypt() and rtw_aes_decrypt() compute
length = hdr.len - hdrlen - iv_len;
and act on the result, and recvframe_chkmic() similarly computes
datalen = hdr.len - hdrlen - iv_len - icv_len - 8;
for TKIP (the 8-byte Michael MIC is not accounted for in icv_len). A frame shorter than hdrlen + iv_len + icv_len (+ 8 for TKIP) underflows these unsigned subtractions, turning into a ~4 GiB iteration count in aes_decipher()/arc4_crypt()/rtw_seccalctkipmic() or a ~4 GiB crc32_le() length, causing out-of-bounds reads/writes of up to ~4 GiB starting from the rx skb. Reject such frames in decryptor() before touching the IV; this covers all three ciphers and the TKIP MIC check, and also keeps the unconditional iv[3] access within the frame.
2) validate_80211w_mgmt() keeps using the frame - two memcpys through the stale rx_data pointer and a pkt_len update - before checking whether decryptor() returned NULL. On decrypt failure (e.g. a unicast protected deauth/disassoc/action frame with a bad MIC, which this path always software-decrypts) the skb has already been freed, so this is a use-after-free read/write, and the caller's error path frees the frame a second time, drifting free_recvframe_cnt. Bail out immediately when decryptor() fails, freeing the temporary mgmt_DATA buffer first.
Discovered by Atuin - Automated Vulnerability Discovery Engine.
--- drivers/staging/rtl8723bs/core/rtw_recv.c | 25 ++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-)
drivers/staging/rtl8723bs/core/rtw_recv.c +20 -5
@@ -451,7 +451,21 @@ union recv_frame *decryptor(struct adapter *padapter, union recv_frame *precv_frRT_TRACE (_module_rtl871x_recv_c_, _drv_info_, ("prxstat->decrypted =%x prxattrib->encrypt = 0x%03x\n" , prxattrib->bdecrypted, prxattrib->encrypt));if (prxattrib->encrypt >0 ) { -u8 *iv = precv_frame->u.hdr.rx_data+prxattrib->hdrlen; +u8 *iv; +u32 min_len = prxattrib->hdrlen + prxattrib->iv_len + prxattrib->icv_len; + +/* TKIP appends an 8-byte Michael MIC that icv_len doesn't account for */ +if (prxattrib->encrypt == _TKIP_) + min_len +=8 ; + +/* a protected frame must be long enough to hold the IV and ICV/MIC */ +if (precv_frame->u.hdr.len < min_len) { +rtw_free_recvframe (precv_frame, + &padapter->recvpriv.free_recv_queue); +return NULL ; + } + + iv = precv_frame->u.hdr.rx_data + prxattrib->hdrlen; prxattrib->key_index = (((iv[3 ])>>6 )&0x3 );if (prxattrib->key_index >WEP_KEYS ) {
@@ -1426,6 +1440,11 @@ static sint validate_80211w_mgmt(struct adapter *adapter, union recv_frame *prec goto validate_80211w_fail; } precv_frame =decryptor (adapter, precv_frame); +if (!precv_frame) { +kfree (mgmt_DATA); +DBG_871X ("%s mgmt descrypt fail !!!!!!!!!\n" , __func__); + goto validate_80211w_fail; + }/* save actual management data frame body */ memcpy (mgmt_DATA, ptr+pattrib->hdrlen+pattrib->iv_len, data_len);/* overwrite the iv field */
@@ -1433,10 +1452,6 @@ static sint validate_80211w_mgmt(struct adapter *adapter, union recv_frame *prec/* remove the iv and icv length */ pattrib->pkt_len = pattrib->pkt_len - pattrib->iv_len - pattrib->icv_len;kfree (mgmt_DATA); -if (!precv_frame) { -DBG_871X ("%s mgmt descrypt fail !!!!!!!!!\n" , __func__); - goto validate_80211w_fail; - } }else if (IS_MCAST (GetAddr1Ptr (ptr)) && (subtype ==WIFI_DEAUTH || subtype ==WIFI_DISASSOC )) {sint BIP_ret = _SUCCESS;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 340/1848 xen-blkfront: unbind irq before tearing down ring and shadow requests
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yuchao Zhang <[email protected]>
[ Upstream commit f3e27b7955727a4d7c0e9264a2a209fbba788bdc ]
In blkif_free_ring(), the driver tears down the ring's persistent grants, shadow request arrays, and shared ring structure (xenbus_teardown_ring), and only calls unbind_from_irqhandler() at the very end.
While blkif_free_ring() is freeing persistent grants and clearing the shadow array, the event channel interrupt (blkif_interrupt) is still registered and active. If an interrupt arrives from the backend during this teardown window, blkif_interrupt() reads rinfo->ring.sring and, via blkif_completion(), accesses rinfo->shadow[id].grants_used and rinfo->shadow[id].sg. blkif_free_ring() tears these structures down without holding rinfo->ring_lock, and the handler only checks info->connected at entry, so this is a real race resulting in a use-after-free or NULL pointer dereference.
Fix this by moving unbind_from_irqhandler() to the beginning of blkif_free_ring(). Calling unbind_from_irqhandler() first frees the IRQ and synchronizes with any in-flight interrupt handlers on other CPUs before ring memory and shadow request structures are deallocated, matching the teardown order in drivers/net/xen-netfront.c.
Message-ID: <[email protected]>
--- drivers/block/xen-blkfront.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
drivers/block/xen-blkfront.c +8 -4
@@ -1276,6 +1276,14 @@ static void blkif_free_ring(struct blkfront_ring_info *rinfo)struct blkfront_info *info = rinfo->dev_info;int i, j, segs; +/* +* Interrupt teardown must be done ahead of freeing queue-related +* data, otherwise the interrupt handler can race with the cleanup. +*/ +if (rinfo->irq) +unbind_from_irqhandler (rinfo->irq, rinfo); + rinfo->evtchn = rinfo->irq =0 ; +/* * Remove indirect pages, this only happens when using indirect * descriptors but not persistent grants
@@ -1365,10 +1373,6 @@ static void blkif_free_ring(struct blkfront_ring_info *rinfo)free_pages_exact (rinfo->ring.sring, info->nr_ring_pages *XEN_PAGE_SIZE ); rinfo->ring.sring =NULL ; - -if (rinfo->irq) -unbind_from_irqhandler (rinfo->irq, rinfo); - rinfo->evtchn = rinfo->irq =0 ; }static void blkif_free (struct blkfront_info *info,int suspend)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 341/1848 serial: core: shut down initialized port on removal
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Igor Putko <[email protected]>
[ Upstream commit 810d467c11f0c85107874d08dfdd11acba6aa0c0 ]
When a serial port configured as a console is opened and subsequently closed, tty_port_shutdown() skips invoking port->ops->shutdown() because port->console is true. As a result, tty_port_initialized() remains true and the port's interrupt handler stays registered in the irq subsystem.
If the underlying device is later unbound or removed (e.g. via sysfs driver unbind or device hot-unplug), serial_core_remove_one_port() unregisters the console, frees uport->name via kfree(), and tears down the port without shutting it down or freeing its IRQ. Consequently, the irqaction descriptor remains registered in genirq with action->name pointing to freed memory.
This triggers a use-after-free read whenever genirq accesses action->name, such as when reading /proc/interrupts:
BUG: KASAN: slab-use-after-free in string+0x476/0x570 Call Trace: string+0x476/0x570 vsnprintf+0x422/0x1300 seq_printf+0x... show_interrupts+...
Fix this by acquiring port->mutex in serial_core_remove_one_port() after console unregistration, clearing port->console under the mutex to prevent data races with concurrent tty_port_shutdown(), and invoking uart_shutdown(NULL, state) if the port remains initialized. This ensures that port->ops->shutdown() is called and the IRQ is freed before kfree(uport->name).
--- drivers/tty/serial/serial_core.c | 7 +++++++ 1 file changed, 7 insertions(+)
drivers/tty/serial/serial_core.c +7 -0
@@ -3090,6 +3090,13 @@ int uart_remove_one_port(struct uart_driver *drv, struct uart_port *uport)if (uart_console (uport))unregister_console (uport->cons); +mutex_lock (&port->mutex); + port->console = false; + +if (tty_port_initialized (port)) +uart_shutdown (NULL , state); +mutex_unlock (&port->mutex); +/* * Free the port IO and memory resources, if any. */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 342/1848 ovl: set OVL_WHITEOUTS before publishing the upper dir
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
[ Upstream commit cbec8610ec5aaf35df50094ff639febc23f20773 ]
Listing a directory while it is copied up causes a use-after-free of the readdir cache.
A merge directory must never be iterated as a real upper directory:
that mode frees the cache in OVL_I(inode)->cache without looking at its refcount, while files opened in merged mode still use it. ovl_copy_up_workdir() publishes the upper dentry before it sets OVL_WHITEOUTS, and ovl_dir_open() samples both without a lock, so an open between the two stores finds the upper directory and takes it for a real one.
With a delay between the two stores, an unprivileged process that listed a directory during its copy-up saw only "." and "..", and its next getdents freed the readdir cache of another descriptor.
Fix this by setting OVL_WHITEOUTS before ovl_inode_update(), so that ovl_dir_reset() agrees with ovl_dir_open(), and by testing OVL_TYPE_MERGE() of the path type in ovl_dir_open(), so that an open that observes the upper dentry never iterates a merge dir as a real dir, regardless of the order in which it observes the flag.
--- fs/overlayfs/copy_up.c | 2 +- fs/overlayfs/readdir.c | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-)
fs/overlayfs/copy_up.c +1 -1
@@ -630,9 +630,9 @@ static int ovl_copy_up_workdir(struct ovl_copy_up_ctx *c)if (!c->metacopy)ovl_set_upperdata (d_inode (c->dentry)); inode =d_inode (c->dentry); -ovl_inode_update (inode, temp);if (S_ISDIR (inode->i_mode))ovl_set_flag (OVL_WHITEOUTS , inode); +ovl_inode_update (inode, temp); unlock:unlock_rename (c->workdir, c->destdir);
fs/overlayfs/readdir.c +2 -1
@@ -937,7 +937,8 @@ static int ovl_dir_open(struct inode *inode, struct file *file)return PTR_ERR (realfile); } od->realfile = realfile; - od->is_real =ovl_dir_is_real (file->f_path.dentry); + od->is_real = !OVL_TYPE_MERGE (type) && + !ovl_test_flag (OVL_WHITEOUTS , inode); od->is_upper =OVL_TYPE_UPPER (type); file->private_data = od;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 343/1848 scsi: dc395x: sync the waiting_timer before freeing the host
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fan Wu <[email protected]>
[ Upstream commit 0b1a79f2791a06f139dce5450e487307cf0e241f ]
The waiting_timer callback re-arms itself and takes the host lock. adapter_uninit() currently stops it with timer_delete(), which does not wait for a callback already running on another CPU. The final scsi_host_put() that frees the host (and the host lock the callback dereferences) runs right after adapter_uninit(), so a concurrent or just re-armed callback can fire after the free, leaving a potential use-after-free window.
Replace timer_delete() with timer_shutdown_sync() at the top of adapter_uninit(), before the host-lock section: the timer is dequeued, a running callback is waited for and rearming is blocked before the chip is halted, so it cannot fire at all once the adapter has ceased to function. Waiting outside the lock avoids the self-deadlock that would result from syncing a callback blocked on the lock we still hold.
No shutdown is needed for selto_timer because it has no reachable armer or callback.
This issue was found by an in-house static analysis tool.
--- drivers/scsi/dc395x.c | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-)
drivers/scsi/dc395x.c +4 -6
@@ -4456,13 +4456,11 @@ static void adapter_uninit_chip(struct AdapterCtlBlk *acb)static void adapter_uninit (struct AdapterCtlBlk *acb) {unsigned long flags; -DC395x_LOCK_IO (acb->scsi_host, flags); -/* remove timers */ -if (timer_pending (&acb->waiting_timer)) -del_timer (&acb->waiting_timer); -if (timer_pending (&acb->selto_timer)) -del_timer (&acb->selto_timer); +/* Drain the self-rearming timer; must not run under host_lock. */ +timer_delete_sync (&acb->waiting_timer); + +DC395x_LOCK_IO (acb->scsi_host, flags);adapter_uninit_chip (acb);adapter_remove_and_free_all_devices (acb);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 344/1848 phy: core: Fix race-condition between _of_phy_get() and try_module_get()
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bryan O'Donoghue <[email protected]>
[ Upstream commit 090055ee629523092688da42428558ba56d4272f ]
Sashiko asked during a patch review if the existing usage pattern had a race condition; specifically in of_phy_get() if it was possible between returning from _of_phy_get() and running try_module_get() that a module might be unbound leading to use-after-free.
Looking at the code this appears to be so, there is no linkage between the phy and module under a synchronisation primitive.
Using the phy_provider_mutex in phy_get() will ensure there is a link between the returned phy pointer and the module_get() bumping the module reference count.
Amend phy_get(), of_phy_get() and devm_of_phy_get_by_index() to fix the same usage pattern.
phy_provider_unregister() must take the phy_provider_mutex so amending phy_get()/of_phy_get() to take that same mutex guarantees there is no use-after-free.
--- drivers/phy/phy-core.c | 42 ++++++++++++++++++++++++++++-------------- 1 file changed, 28 insertions(+), 14 deletions(-)
drivers/phy/phy-core.c +28 -14
@@ -117,13 +117,13 @@ static struct phy *phy_find(struct device *dev, const char *con_id)const char *dev_id =dev_name (dev);struct phy_lookup *p, *pl =NULL ; -mutex_lock (&phy_provider_mutex); +lockdep_assert_held (&phy_provider_mutex); +list_for_each_entry (p, &phys, node)if (!strcmp (p->dev_id, dev_id) && !strcmp (p->con_id, con_id)) { pl = p;break ; } -mutex_unlock (&phy_provider_mutex);return pl ? pl->phy :ERR_PTR (-ENODEV ); }
@@ -504,6 +504,8 @@ static struct phy *_of_phy_get(struct device_node *np, int index)struct phy *phy =NULL ;struct of_phandle_args args; +lockdep_assert_held (&phy_provider_mutex); + ret =of_parse_phandle_with_args (np,"phys" ,"#phy-cells" , index, &args);if (ret)
@@ -515,11 +517,10 @@ static struct phy *_of_phy_get(struct device_node *np, int index) goto out_put_node; } -mutex_lock (&phy_provider_mutex); phy_provider =of_phy_provider_lookup (args.np);if (IS_ERR (phy_provider) || !try_module_get (phy_provider->owner)) { phy =ERR_PTR (-EPROBE_DEFER ); - goto out_unlock; + goto out_put_node; }if (!of_device_is_available (args.np)) {
@@ -533,8 +534,6 @@ static struct phy *_of_phy_get(struct device_node *np, int index) out_put_module:module_put (phy_provider->owner); -out_unlock: -mutex_unlock (&phy_provider_mutex); out_put_node:of_node_put (args.np);
@@ -558,15 +557,21 @@ struct phy *of_phy_get(struct device_node *np, const char *con_id)if (con_id) index =of_property_match_string (np,"phy-names" , con_id); +mutex_lock (&phy_provider_mutex); + phy =_of_phy_get (np, index);if (IS_ERR (phy)) -return phy; + goto out_unlock; -if (!try_module_get (phy->ops->owner)) -return ERR_PTR (-EPROBE_DEFER ); +if (!try_module_get (phy->ops->owner)) { + phy =ERR_PTR (-EPROBE_DEFER ); + goto out_unlock; + }get_device (&phy->dev); +out_unlock: +mutex_unlock (&phy_provider_mutex);return phy; }EXPORT_SYMBOL_GPL (of_phy_get);
@@ -678,6 +683,7 @@ struct phy *phy_get(struct device *dev, const char *string)return ERR_PTR (-EINVAL ); } +mutex_lock (&phy_provider_mutex);if (dev->of_node) { index =of_property_match_string (dev->of_node,"phy-names" , string);
@@ -686,10 +692,12 @@ struct phy *phy_get(struct device *dev, const char *string) phy =phy_find (dev, string); }if (IS_ERR (phy)) -return phy; + goto out_unlock; -if (!try_module_get (phy->ops->owner)) -return ERR_PTR (-EPROBE_DEFER ); +if (!try_module_get (phy->ops->owner)) { + phy =ERR_PTR (-EPROBE_DEFER ); + goto out_unlock; + }get_device (&phy->dev);
@@ -698,6 +706,8 @@ struct phy *phy_get(struct device *dev, const char *string)dev_dbg (dev,"failed to create device link to %s\n" ,dev_name (phy->dev.parent)); +out_unlock: +mutex_unlock (&phy_provider_mutex);return phy; }EXPORT_SYMBOL_GPL (phy_get);
@@ -837,15 +847,17 @@ struct phy *devm_of_phy_get_by_index(struct device *dev, struct device_node *np,if (!ptr)return ERR_PTR (-ENOMEM ); +mutex_lock (&phy_provider_mutex); phy =_of_phy_get (np, index);if (IS_ERR (phy)) {devres_free (ptr); -return phy; + goto out_unlock; }if (!try_module_get (phy->ops->owner)) {devres_free (ptr); -return ERR_PTR (-EPROBE_DEFER ); + phy =ERR_PTR (-EPROBE_DEFER ); + goto out_unlock; }get_device (&phy->dev);
@@ -858,6 +870,8 @@ struct phy *devm_of_phy_get_by_index(struct device *dev, struct device_node *np,dev_dbg (dev,"failed to create device link to %s\n" ,dev_name (phy->dev.parent)); +out_unlock: +mutex_unlock (&phy_provider_mutex);return phy; }EXPORT_SYMBOL_GPL (devm_of_phy_get_by_index);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 345/1848 media: rc: Fix ABBA deadlock by making locks more fine grained
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Young <[email protected]>
[ Upstream commit c6d68866ad8aa1e957a3e5a6ede971148f1e3d59 ]
The ir_raw_event_unregister() function takes the ir_raw_handler_lock first and then the rc_dev->lock. Other functions like change_protocol do this in the reverse order.
This means that an ir decoder module unload and writing to the protocol sysfs file can cause a deadlock.
ir_raw_handler_lock protects the client list, amongst other things. Split this out into a separate lock so we can ensure the locking order is always the same.
--- drivers/media/rc/rc-ir-raw.c | 40 +++++++++++++++++++++++------------- 1 file changed, 26 insertions(+), 14 deletions(-)
drivers/media/rc/rc-ir-raw.c +26 -14
@@ -10,7 +10,8 @@#include <linux/sched.h> #include "rc-core-priv.h" -/* Used to keep track of IR raw clients, protected by ir_raw_handler_lock */ +/* Used to keep track of IR raw clients, protected by ir_raw_client_lock */ +static DEFINE_MUTEX (ir_raw_client_lock);static LIST_HEAD (ir_raw_client_list);/* Used to handle IR raw handler extensions */
@@ -290,13 +291,6 @@ static int change_protocol(struct rc_dev *dev, u64 *rc_proto)return 0 ; } -static void ir_raw_disable_protocols (struct rc_dev *dev,u64 protocols) -{ -mutex_lock (&dev->lock); - dev->enabled_protocols &= ~protocols; -mutex_unlock (&dev->lock); -} -/** * ir_raw_gen_manchester() - Encode data with Manchester (bi-phase) modulation. * @ev: Pointer to pointer to next free event. *@ev is incremented for
@@ -634,15 +628,20 @@ int ir_raw_event_register(struct rc_dev *dev) {struct task_struct *thread; +/* Holding dev->lock could result in a dead-lock */ +#ifdef CONFIG_LOCKDEP +WARN_ON (debug_locks &&lockdep_is_held (&dev->lock)); +#endif + thread =kthread_run (ir_raw_event_thread, dev->raw,"rc%u" , dev->minor);if (IS_ERR (thread))return PTR_ERR (thread); dev->raw->thread = thread; -mutex_lock (&ir_raw_handler_lock); +mutex_lock (&ir_raw_client_lock);list_add_tail (&dev->raw->list, &ir_raw_client_list); -mutex_unlock (&ir_raw_handler_lock); +mutex_unlock (&ir_raw_client_lock);return 0 ; }
@@ -666,8 +665,10 @@ void ir_raw_event_unregister(struct rc_dev *dev)kthread_stop (dev->raw->thread);del_timer_sync (&dev->raw->edge_handle); -mutex_lock (&ir_raw_handler_lock); +mutex_lock (&ir_raw_client_lock);list_del (&dev->raw->list); + +mutex_lock (&ir_raw_handler_lock);list_for_each_entry (handler, &ir_raw_handler_list, list)if (handler->raw_unregister && (handler->protocols & dev->enabled_protocols))
@@ -683,6 +684,8 @@ void ir_raw_event_unregister(struct rc_dev *dev)* "device gone" is checked. */ mutex_unlock (&ir_raw_handler_lock); + +mutex_unlock (&ir_raw_client_lock); }/*
@@ -705,15 +708,24 @@ void ir_raw_handler_unregister(struct ir_raw_handler *ir_raw_handler)struct ir_raw_event_ctrl *raw;u64 protocols = ir_raw_handler->protocols; +mutex_lock (&ir_raw_client_lock); +mutex_lock (&ir_raw_handler_lock);list_del (&ir_raw_handler->list); +atomic64_andnot (protocols, &available_protocols); +mutex_unlock (&ir_raw_handler_lock); +list_for_each_entry (raw, &ir_raw_client_list, list) { +mutex_lock (&raw->dev->lock); +mutex_lock (&ir_raw_handler_lock);if (ir_raw_handler->raw_unregister && (raw->dev->enabled_protocols & protocols)) ir_raw_handler->raw_unregister (raw->dev); -ir_raw_disable_protocols (raw->dev, protocols); + raw->dev->enabled_protocols &= ~protocols; +mutex_unlock (&ir_raw_handler_lock); +mutex_unlock (&raw->dev->lock); } -atomic64_andnot (protocols, &available_protocols); -mutex_unlock (&ir_raw_handler_lock); + +mutex_unlock (&ir_raw_client_lock); }EXPORT_SYMBOL (ir_raw_handler_unregister);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 346/1848 ocfs2: snapshot dentry names in file and setattr traces
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang <[email protected]>
[ Upstream commit 8cd3ff30659775a6831c66687a69d2b83d163591 ]
Patch series "ocfs2: stabilize dentry names in file and setattr traces", v4.
Snapshot names at all six users of ocfs2__file_ops and at the separate setattr event. Patch 1 handles the five ordinary file-operation callers and setattr. Patch 2 handles release separately to preserve its locked open-count sample and take the snapshot outside that critical section.
The release explanation distinguishes its existing RCU lifetime coverage from name/length consistency. It does not claim that the ordinary callers' external-name UAF interleaving crosses the held inode spinlock. The release source change is unchanged from v3.
Patch 1 also removes the read callback's redundant NULL-inode check. The two patches apply independently and leave trace formats unchanged.
This patch (of 2):
The open, fsync, read, write and splice-read trace calls pass the live dentry name and length to the shared ocfs2__file_ops event class. ocfs2_setattr() passes the same unprotected arguments to its own event. Both events size and copy a __string field separately. A reference to the dentry does not pin the external storage backing an individual name.
With an event enabled, a caller can be preempted after loading the name pointer. A long-to-short rename can then replace the name and reclaim its old external allocation before the trace callback sizes or copies it, provided no other snapshot retains that allocation.
The setattr inode lock does not exclude every rename: a same-directory rename of a source directory need not take that directory's inode lock. It can therefore change the dentry name while setattr records its event. Inline names and separately loaded lengths can also change during trace record sizing and copying.
Take a dentry name snapshot around each of these six trace calls and pass both the string and length from the snapshot. Check event enablement before taking a snapshot. Keep the event classes and formats unchanged.
Also remove the redundant NULL-inode check in the read callback. file_inode() returns the open file's inode, which is already used by the trace call above the check.
The historical report below is from the read path.
KASAN report as below:
BUG: KASAN: slab-use-after-free in strlen+0x85/0xa0
Read of size 1 at addr ffff88810a5b2b18 by task python3/496 [CPU and host details omitted.]
Call Trace:
<TASK>
dump_stack_lvl+0x93/0xd0
print_report+0xce/0x630
? strlen+0x85/0xa0
? srso_alias_return_thunk+0x5/0xfbef5
? __virt_addr_valid+0x20e/0x420
? strlen+0x85/0xa0
kasan_report+0xe0/0x110
? strlen+0x85/0xa0
strlen+0x85/0xa0
trace_event_raw_event_ocfs2__file_ops+0xf0/0x480
? __pfx_trace_event_raw_event_ocfs2__file_ops+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? pmbd_probe_hit_cookie+0xe7/0x1c0
? srso_alias_return_thunk+0x5/0xfbef5
? __pfx_pmbd_probe_hit_cookie+0x10/0x10
ocfs2_file_read_iter+0x6cd/0xb30
? __pfx_ocfs2_file_read_iter+0x10/0x10
? selinux_file_permission+0x11d/0x540
? srso_alias_return_thunk+0x5/0xfbef5
? security_file_permission+0x26/0x80
vfs_read+0x7d2/0xc20
? __pfx_vfs_read+0x10/0x10
? srso_alias_return_thunk+0x5/0xfbef5
? __pfx_do_sys_openat2+0x10/0x10
ksys_read+0x111/0x200
? __pfx_ksys_read+0x10/0x10
? irqentry_exit+0xbe/0x820
? srso_alias_return_thunk+0x5/0xfbef5
? trace_hardirqs_on_prepare+0x11d/0x150
? srso_alias_return_thunk+0x5/0xfbef5
do_syscall_64+0x114/0x620
entry_SYSCALL_64_after_hwframe+0x77/0x7f
[User register dump omitted.]
</TASK>
Allocated by task 489:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
__kasan_kmalloc+0xaa/0xb0
__kmalloc_noprof+0x2de/0x780
__d_alloc+0x5fc/0x8c0
d_alloc_parallel+0x106/0x11d0
lookup_open+0x3ff/0x13e0
path_openat+0x95e/0x2020
do_file_open+0x21e/0x470
do_sys_openat2+0xf4/0x1b0
__x64_sys_openat+0x136/0x1e0
do_syscall_64+0x114/0x620
entry_SYSCALL_64_after_hwframe+0x77/0x7f
Freed by task 0:
kasan_save_stack+0x33/0x60
kasan_save_track+0x14/0x30
kasan_save_free_info+0x3b/0x60
__kasan_slab_free+0x5f/0x80
__rcu_free_sheaf_prepare+0x65/0x2a0
rcu_free_sheaf_nobarn+0x1d/0x50
rcu_core+0x6be/0x1ed0
handle_softirqs+0x1fa/0x8d0
__irq_exit_rcu+0x113/0x1e0
irq_exit_rcu+0xe/0x20
sysvec_apic_timer_interrupt+0x6c/0x80
asm_sysvec_apic_timer_interrupt+0x1a/0x20
The buggy address belongs to the object at ffff88810a5b2b00
which belongs to the cache kmalloc-rcl-192 of size 192
The buggy address is located 24 bytes inside of
freed 192-byte region [ffff88810a5b2b00, ffff88810a5b2bc0)
[Page and shadow-memory dumps omitted.]--- fs/ocfs2/file.c | 84 +++++++++++++++++++++++++++++++------------------ 1 file changed, 53 insertions(+), 31 deletions(-)
fs/ocfs2/file.c +53 -31
@@ -86,10 +86,17 @@ static int ocfs2_file_open(struct inode *inode, struct file *file)int mode = file->f_flags;struct ocfs2_inode_info *oi =OCFS2_I (inode); -trace_ocfs2_file_open (inode, file, file->f_path.dentry, - (unsigned long long )oi->ip_blkno, - file->f_path.dentry->d_name.len, - file->f_path.dentry->d_name.name, mode); +if (trace_ocfs2_file_open_enabled ()) { +struct dentry *dentry = file->f_path.dentry; +struct name_snapshot name; + +take_dentry_name_snapshot (&name, dentry); +trace_ocfs2_file_open (inode, file, dentry, + oi->ip_blkno, + name.name.len, name.name.name, + mode); +release_dentry_name_snapshot (&name); + }if (file->f_mode &FMODE_WRITE ) { status =dquot_initialize (inode);
@@ -175,11 +182,17 @@ static int ocfs2_sync_file(struct file *file, loff_t start, loff_t end,tid_t commit_tid;bool needs_barrier = false; -trace_ocfs2_sync_file (inode, file, file->f_path.dentry, - oi->ip_blkno, - file->f_path.dentry->d_name.len, - file->f_path.dentry->d_name.name, - (unsigned long long )datasync); +if (trace_ocfs2_sync_file_enabled ()) { +struct dentry *dentry = file->f_path.dentry; +struct name_snapshot name; + +take_dentry_name_snapshot (&name, dentry); +trace_ocfs2_sync_file (inode, file, dentry, + oi->ip_blkno, + name.name.len, name.name.name, + (unsigned long long )datasync); +release_dentry_name_snapshot (&name); + }if (ocfs2_is_hard_readonly (osb) ||ocfs2_is_soft_readonly (osb))return -EROFS ;
@@ -1130,15 +1143,19 @@ int ocfs2_setattr(struct dentry *dentry, struct iattr *attr)int had_lock;struct ocfs2_lock_holder oh; -trace_ocfs2_setattr (inode, dentry, - (unsigned long long )OCFS2_I (inode)->ip_blkno, - dentry->d_name.len, dentry->d_name.name, - attr->ia_valid, - attr->ia_valid &ATTR_MODE ? attr->ia_mode :0 , - attr->ia_valid &ATTR_UID ? +if (trace_ocfs2_setattr_enabled ()) { +struct name_snapshot name; + +take_dentry_name_snapshot (&name, dentry); +trace_ocfs2_setattr (inode, dentry,OCFS2_I (inode)->ip_blkno, + name.name.len, name.name.name, attr->ia_valid, + attr->ia_valid &ATTR_MODE ? attr->ia_mode :0 , + attr->ia_valid &ATTR_UID ?from_kuid (&init_user_ns, attr->ia_uid) :0 , - attr->ia_valid &ATTR_GID ? + attr->ia_valid &ATTR_GID ?from_kgid (&init_user_ns, attr->ia_gid) :0 ); +release_dentry_name_snapshot (&name); + }/* ensuring we don't even attempt to truncate a symlink */ if (S_ISLNK (inode->i_mode))
@@ -2383,11 +2400,17 @@ static ssize_t ocfs2_file_write_iter(struct kiocb *iocb,int direct_io = iocb->ki_flags &IOCB_DIRECT ?1 :0 ;int nowait = iocb->ki_flags &IOCB_NOWAIT ?1 :0 ; -trace_ocfs2_file_write_iter (inode, file, file->f_path.dentry, - (unsigned long long )OCFS2_I (inode)->ip_blkno, - file->f_path.dentry->d_name.len, - file->f_path.dentry->d_name.name, - (unsigned int )from->nr_segs);/* GRRRRR */ +if (trace_ocfs2_file_write_iter_enabled ()) { +struct dentry *dentry = file->f_path.dentry; +struct name_snapshot name; + +take_dentry_name_snapshot (&name, dentry); +trace_ocfs2_file_write_iter (inode, file, dentry, +OCFS2_I (inode)->ip_blkno, + name.name.len, name.name.name, + (unsigned int )from->nr_segs); +release_dentry_name_snapshot (&name); + }if (!direct_io && nowait)return -EOPNOTSUPP ;
@@ -2533,17 +2556,16 @@ static ssize_t ocfs2_file_read_iter(struct kiocb *iocb,int direct_io = iocb->ki_flags &IOCB_DIRECT ?1 :0 ;int nowait = iocb->ki_flags &IOCB_NOWAIT ?1 :0 ; -trace_ocfs2_file_read_iter (inode, filp, filp->f_path.dentry, - (unsigned long long )OCFS2_I (inode)->ip_blkno, - filp->f_path.dentry->d_name.len, - filp->f_path.dentry->d_name.name, - to->nr_segs);/* GRRRRR */ - +if (trace_ocfs2_file_read_iter_enabled ()) { +struct dentry *dentry = filp->f_path.dentry; +struct name_snapshot name; -if (!inode) { - ret = -EINVAL ; -mlog_errno (ret); - goto bail; +take_dentry_name_snapshot (&name, dentry); +trace_ocfs2_file_read_iter (inode, filp, dentry, +OCFS2_I (inode)->ip_blkno, + name.name.len, name.name.name, + to->nr_segs); +release_dentry_name_snapshot (&name); }if (!direct_io && nowait)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 347/1848 drm/nouveau: reject zero-size notifier object allocation
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zhenhao Wan <[email protected]>
[ Upstream commit 38125d38d850bd2fdd5d7840c3bd52d9d208995b ]
nouveau_abi16_ioctl_notifierobj_alloc() passes the userspace-controlled info->size to nvkm_mm_head() as both size_max and size_min without a lower bound. A zero size satisfies the allocator's "e - s < size_min" gate (size_min == 0 makes the unsigned comparison inert) and yields a zero-length node, after which
args.limit = ntfy->node->offset + ntfy->node->length - 1;
underflows (offset 0, length 0 -> 0xffffffff) into an oversized ~4 GiB DMA window. The dma object constructor only rejects start > limit, so the validly ordered [base, base + 0xffffffff] range passes and is programmed into the GPU DMA context. The ioctl is DRM_RENDER_ALLOW, so any render node client can trigger this on pre-Fermi hardware.
Reject a zero-size request before allocating anything.
--- drivers/gpu/drm/nouveau/nouveau_abi16.c | 4 ++++ 1 file changed, 4 insertions(+)
drivers/gpu/drm/nouveau/nouveau_abi16.c +4 -0
@@ -533,6 +533,10 @@ nouveau_abi16_ioctl_notifierobj_alloc(ABI16_IOCTL_ARGS)return nouveau_abi16_put (abi16, -EINVAL ); client = abi16->device.object.client; +/* zero size yields a zero-length node, underflowing args.limit */ +if (unlikely (!info->size)) +return nouveau_abi16_put (abi16, -EINVAL ); + chan =nouveau_abi16_chan (abi16, info->channel);if (!chan)return nouveau_abi16_put (abi16, -ENOENT );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 348/1848 media: streamzap: Add missing rc_unregister_device()
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Young <[email protected]>
[ Upstream commit 3982d2eeb1bdf7a9c14e4ff69015cb456f11da51 ]
If usb_submit_urb() fails during probe, then the error path is missing a call to rc_unregister_device(), which will leak various things like the input device.
--- drivers/media/rc/streamzap.c | 1 + 1 file changed, 1 insertion(+)
drivers/media/rc/streamzap.c +1 -0
@@ -405,6 +405,7 @@ static int streamzap_probe(struct usb_interface *intf,return 0 ; rc_submit_fail: +rc_unregister_device (sz->rdev);rc_free_device (sz->rdev);usb_set_intfdata (intf,NULL ); rc_dev_fail:
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 349/1848 media: redrat3: Ensure we dont read beyond the end of the packet
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Young <[email protected]>
[ Upstream commit cd49f62f4161c7340d9c9f53b67757575900c0bc ]
The length and offset is provided by the usb device, so it should be validated.
--- drivers/media/rc/redrat3.c | 16 ++++++++++++++++ 1 file changed, 16 insertions(+)
drivers/media/rc/redrat3.c +16 -0
@@ -358,8 +358,24 @@ static void redrat3_process_ir_data(struct redrat3_dev *rr3)/* process each rr3 encoded byte into an int */ sig_size =be16_to_cpu (rr3->irdata.sig_size); + +/* +* Note we are not checking if we are reading beyond the end of the +* packet which was sent, and reading stale data. If the device +* sends a packet which is short then we get garbage IR, but no +* out of bounds read. +*/ +if (sig_size >RR3_MAX_SIG_SIZE ) { +dev_err (dev,"length %u is incorrect\n" , sig_size); +return ; + } +for (i =0 ; i < sig_size; i++) { offset = rr3->irdata.sigdata[i]; +if (offset >=RR3_DRIVER_MAXLENS ) { +dev_err (dev,"offset %u is incorrect\n" , offset); +return ; + } val =get_unaligned_be16 (&rr3->irdata.lens[offset]);/* we should always get pulse/space/pulse/space samples */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 350/1848 media: redrat3: Ensure all urbs are suspended
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Young <[email protected]>
[ Upstream commit 1582f545273f2aa4eb4ee6f3a89b433f5c85c68f ]
Ensure that the learn urb is stopped before suspend.
--- drivers/media/rc/redrat3.c | 1 + 1 file changed, 1 insertion(+)
drivers/media/rc/redrat3.c +1 -0
@@ -1168,6 +1168,7 @@ static int redrat3_dev_suspend(struct usb_interface *intf, pm_message_t message)usb_kill_urb (rr3->narrow_urb);usb_kill_urb (rr3->wide_urb);usb_kill_urb (rr3->flash_urb); +usb_kill_urb (rr3->learn_urb);return 0 ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 351/1848 media: ir-hix5hd2: Ensure rdev is setup before interrupts are enabled
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Young <[email protected]>
[ Upstream commit f7509d2567cf92eeccc31c363a2e2ae43188930c ]
Once the interrupt handler is enabled, priv->rdev can be used. Ensure it is setup correctly so there is no race condition.
--- drivers/media/rc/ir-hix5hd2.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/media/rc/ir-hix5hd2.c +3 -2
@@ -318,6 +318,9 @@ static int hix5hd2_ir_probe(struct platform_device *pdev)if (ret <0 ) goto clkerr; + priv->rdev = rdev; + priv->dev = dev; +if (devm_request_irq (dev, priv->irq, hix5hd2_ir_rx_interrupt,0 , pdev->name, priv) <0 ) {dev_err (dev,"IRQ %d register failed\n" , priv->irq);
@@ -325,8 +328,6 @@ static int hix5hd2_ir_probe(struct platform_device *pdev) goto regerr; } - priv->rdev = rdev; - priv->dev = dev;platform_set_drvdata (pdev, priv);return ret;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 352/1848 ipc/mqueue: release notification resources during inode eviction
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daehyeon Ko <[email protected]>
[ Upstream commit eb85469f0dd69ca145d63117450e14c31f67f698 ]
mqueue_flush_file() removes an mq_notify() registration only when the closing task belongs to the thread group stored in notify_owner.
A task in a separate thread group created with CLONE_FILES can register SIGEV_THREAD notification and exit without closing the shared file table. If another thread group then unlinks and last-closes the queue, ->flush() skips the registration and inode eviction loses the only pointers to its resources.
The orphaned registration permanently retains the notification skb, its netlink socket, a pid reference and a user namespace reference. An unprivileged process can repeat the sequence with new queues and sockets.
No inode users remain during eviction. Remove any stale registration there after dropping info->lock, since netlink_sendskb() may release the final socket reference.
--- ipc/mqueue.c | 7 +++++++ 1 file changed, 7 insertions(+)
ipc/mqueue.c +7 -0
@@ -528,6 +528,13 @@ static void mqueue_evict_inode(struct inode *inode)list_add_tail (&msg->m_list, &tmp_msg);kfree (info->node_cache);spin_unlock (&info->lock); +/* +* A shared file table can let the notification owner exit without +* running ->flush(). No users of the inode remain during eviction, so +* tear down any stale notification after dropping info->lock because +* netlink_sendskb() may release the final socket reference. +*/ +remove_notification (info);list_for_each_entry_safe (msg, nmsg, &tmp_msg, m_list) {list_del (&msg->m_list);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 353/1848 remoteproc: elf_loader: Bound the section header table
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: HyeongJun An <[email protected]>
[ Upstream commit b32177ead5f8925aa66ceed2bd533a85196f4f0c ]
The rproc_elf_sanity_check() only checks the image is big enough to hold one section header. But find_table() walks e_shnum of them, and first dereferences the header at e_shstrndx to locate the section name table. Both fields are u16 and both come from the image, so an e_shstrndx of 65535 reads about 4 MB past the buffer.
The commit 9f9967fed9d0 ("soc: qcom: mdt_loader: Ensure we don't read past the ELF header") added the same check to the MDT loader, and says the header "is sanitized beforehand" under remoteproc. That is what this patch makes true.
Check e_shoff against the image size first, so the two bounds can use size_add() without an e_shoff above SIZE_MAX wrapping on 32-bit. The bounds are separate because e_shnum may be zero while find_table() still reads the e_shstrndx header.
--- drivers/remoteproc/remoteproc_elf_loader.c | 23 ++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-)
drivers/remoteproc/remoteproc_elf_loader.c +21 -2
@@ -46,8 +46,9 @@ int rproc_elf_sanity_check(struct rproc *rproc, const struct firmware *fw)struct elf32_hdr *ehdr;u32 elf_shdr_get_size;u64 phoff, shoff; +size_t shend;char class; -u16 phnum; +u16 phnum, shnum, shstrndx;if (!fw) {dev_err (dev,"failed to load %s\n" , name);
@@ -90,9 +91,27 @@ int rproc_elf_sanity_check(struct rproc *rproc, const struct firmware *fw) phoff =elf_hdr_get_e_phoff (class, fw->data); shoff =elf_hdr_get_e_shoff (class, fw->data); phnum =elf_hdr_get_e_phnum (class, fw->data); + shnum =elf_hdr_get_e_shnum (class, fw->data); + shstrndx =elf_hdr_get_e_shstrndx (class, fw->data); elf_shdr_get_size =elf_size_of_shdr (class); -if (fw->size < shoff + elf_shdr_get_size) { +/* keeps shoff in size_t range for the two bounds below */ +if (shoff > fw->size) { +dev_err (dev,"Section header table is out of bounds\n" ); +return -EINVAL ; + } + +if (shnum) { + shend =size_add (size_mul (elf_shdr_get_size, shnum), shoff); +if (shend > fw->size) { +dev_err (dev,"Section headers are out of bounds\n" ); +return -EINVAL ; + } + } + +/* find_table() reads the header at shstrndx even with no sections */ + shend =size_add (size_mul (elf_shdr_get_size, (size_t )shstrndx +1 ), shoff); +if (shend > fw->size) {dev_err (dev,"Image is too small\n" );return -EINVAL ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 354/1848 microblaze: reserve the ABI argument-home area in the signal frame
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ramin Moussavi <[email protected]>
[ Upstream commit c5947d28c20955de897eeb98430f96db0494f7d7 ]
The MicroBlaze procedure call standard reserves [r1+0] for the return address and lets a callee store its incoming register arguments r5..r10 into the caller-provided home slots at [r1+4]..[r1+24]. When the kernel enters a signal handler it sets r1 to point at struct rt_sigframe, whose leading member is the siginfo prepared for the handler. A handler that homes its arguments - which an unoptimised (-O0) build always does - therefore overwrites the first 24 bytes of that siginfo, so an SA_SIGINFO handler reads corrupted values. The stores stay within siginfo (128 bytes) and do not reach the ucontext behind it.
Reserve the home area by making a seven-word gap -- the return-address slot plus the six argument slots, 28 bytes -- the first member of struct rt_sigframe, so the handler's argument stores land in scratch space instead of clobbering siginfo.
Tested on qemu-system-microblazeel (petalogix-s3adsp1800) with the uClibc-ng NPTL test suite: tst-timer4, tst-timer5, tst-mqueue5 and tst-signal6 pass; before this change they failed because the handler clobbered the signal frame.
--- arch/microblaze/kernel/signal.c | 8 ++++++++ 1 file changed, 8 insertions(+)
arch/microblaze/kernel/signal.c +8 -0
@@ -49,6 +49,14 @@ struct sigframe { };struct rt_sigframe { +/* +* Home area for the handler's register arguments: the MicroBlaze +* ABI reserves [r1+0] for the return address and lets the callee +* store r5..r10 at [r1+4]..[r1+24], and r1 points at this frame +* when the handler is entered. Without the gap those stores +* corrupt frame->info. +*/ +unsigned long abi_gap[7 ];struct siginfo info;struct ucontext uc;unsigned long tramp[2 ];/* signal trampoline */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 355/1848 microblaze: dont clobber r3/r4 restored by rt_sigreturn
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ramin Moussavi <[email protected]>
[ Upstream commit da6829138a39fa3b9ec318ca54ff89af9d94d350 ]
ret_from_trap begins by storing the system call return values r3 and r4 back into the saved user pt_regs. That is right for an ordinary system call, but sys_rt_sigreturn() returns through the same path and has to be
transparent: restore_sigcontext() has just filled pt_regs from the signal frame, and every register must reach userspace exactly as saved. The two stores overwrite the restored r3/r4 with whatever the C function left in those registers.
Only r4 is actually lost, and that follows from how sigreturn is written everywhere rather than from chance. Architectures have sys_rt_sigreturn() return the restored return-value register precisely so that this writeback stores the restored value -- arm returns regs->ARM_r0, riscv and csky regs->a0, arc regs->r0 -- and microblaze does the same through *rval_p = regs->r3 in restore_sigcontext(). But the entry macros treat r3 and r4 as a pair, so ret_from_trap writes back two registers while a C function has only one return value; nothing carries the restored r4.
Commit 791d0a169b91 ("microblaze: Fix sys_rt_sigreturn_wrapper") introduced this in v2.6.37. The old wrapper saved r3/r4 before the call and reloaded them from pt_regs afterwards; switching brlid to brid removed the only point where they were reloaded, and the stores have been overwriting them ever since.
Fix it the way the sibling paths already behave: ret_from_irq and ret_from_exc restore the full register set and do not perform these stores at all. Label the instruction after the stores ret_from_trap_no_rval and enter there, biasing r15 by -8 so that the ABI return "rtsd r15, 8" lands on it; naming the entry rather than computing ret_from_trap + 8 keeps it correct if the number of stores ever changes. Restoring the old save/reload would work too, but costs four memory accesses and a branch to undo damage that is better not done.
Any value the compiler keeps in r4 across a signal is lost. The tightest windows are the lwx/swx compare-and-swap retry loops gcc emits for atomics:
in uClibc-ng's libc.so alone, 50 of 364 such loops hold the address in r4. This is not specific to one libc -- musl passes the address as "r"(p), and glibc has no microblaze atomic-machine.h and so uses gcc's __atomic builtins, which expand the same way. Triggering it needs threads plus a signal storm, which is why it survived 15 years.
Reproduced on qemu-system-microblazeel (petalogix-s3adsp1800) by running the uClibc-ng NPTL test tst-eintr1 40 times against an unchanged userspace:
on v7.2 built with gcc 16.2.0, 23 of 40 iterations died with SIGSEGV without this patch and 0 of 40 with it; on v7.0 built with gcc 12.5.0 the same comparison gave 6 of 40 against 0 of 40. The register dump of a failing iteration shows the signature: a zero r4 and a fault at address 0, while r3 came back intact.
--- arch/microblaze/kernel/entry.S | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-)
arch/microblaze/kernel/entry.S +16 -1
@@ -394,7 +394,13 @@ C_ENTRY(_user_exception): C_ENTRY(ret_from_trap): swi r3, r1, PT_R3 swi r4, r1, PT_R4 - +/* + * Entry point for returns that must not store r3/r4 back into pt_regs, + * i.e. rt_sigreturn, which has already restored them from the signal + * context. Reached as "rtsd r15, 8" with r15 set to this label minus 8, + * so it stays correct if the number of stores above ever changes. + */ +ret_from_trap_no_rval: lwi r11, r1, PT_MODE; /* See if returning to kernel mode, if so, skip resched &c. */ bnei r11, 2f;
@@ -478,6 +484,15 @@ C_ENTRY(ret_from_kernel_thread): C_ENTRY(sys_rt_sigreturn_wrapper): addik r30, r0, 0 /* no restarts */ + /* + * rt_sigreturn restores the full register set from the signal + * context, so it must skip the r3/r4 syscall-return stores at the + * head of ret_from_trap which would otherwise overwrite the + * just-restored r3/r4. Every C function returns with "rtsd r15, 8" + * -- the ABI return, where the 8 skips the caller's branch and its + * delay slot -- so bias r15 by -8 to land on ret_from_trap_no_rval. + */ + addik r15, r0, ret_from_trap_no_rval - 8 brid sys_rt_sigreturn /* Do real work */ addik r5, r1, 0; /* add user context as 1st arg */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 356/1848 microblaze: preserve the MSR carry flags across signals
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sam Price <[email protected]>
[ Upstream commit ca35dd21a5f8343f47a23e4e5b3f0ffccf76a4ae ]
setup_sigcontext() and restore_sigcontext() copy r0-r31, pc, ear, esr and fsr to and from the signal frame but never touch MSR. The interrupted MSR is therefore dropped from the signal context entirely: the handler's ucontext does not expose it, a handler cannot adjust the resumed arithmetic flags through uc_mcontext.regs.msr, and -- because restore_sigcontext() leaves regs->msr as whatever the rt_sigreturn trap left in it -- the interrupted context resumes with the carry produced by the syscall entry path (_user_exception does "addi r14, r14, 4", which writes carry), not with its own.
Other architectures round-trip the user-visible flags through the signal frame (arm's cpsr, csky's carry, x86's eflags), so a handler can both read and adjust the resumed flags; purely privileged status registers such as riscv's sstatus are left out. MicroBlaze should do the same for the user-writable bits.
Concretely, MSR[C] (carry) is lost across signal delivery. Code that keeps a live carry across a point where a signal can be delivered -- for example an lwx/swx compare-and-swap retry loop, between the swx and the carry test -- resumes with the handler's carry and mis-evaluates the result; the same failure class as the rt_sigreturn r3/r4 clobber, reached through a different register. Demonstrated under qemu-system-microblazeel (machine petalogix-s3adsp1800): a handler that sets MSR_C in uc_mcontext.regs.msr has no effect before this change (0 of 132 in-window signals propagated) and takes effect after (130 of 132).
Save MSR in setup_sigcontext() so the handler's ucontext exposes it. The signal frame is user-writable, so restore_sigcontext() must not restore it
verbatim: MicroBlaze packs the user-writable carry (MSR_C, MSR_CC) and the privileged control bits (MSR_UM, MSR_VM, MSR_IE, MSR_EE, ...) into the one register, and a verbatim restore would let userspace alter privileged return state -- rtbd derives the resumed mode from MSR_UMS/MSR_VMS. Restore only MSR_C | MSR_CC from the frame and keep the rest from the current regs->msr. This mirrors x86'srestore_sigcontext(), which masks the restored EFLAGS to FIX_EFLAGS for the same reason; arches whose status register is purely privileged (e.g. riscv sstatus) simply do not restore it at all.
Comment on the exposed MSR reworded: it is not read-only, restore_sigcontext() applies MSR_C|MSR_CC from the frame. Author's Signed-off-by kept; he agreed to comment and changelog cleanups.
--- arch/microblaze/kernel/signal.c | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+)
arch/microblaze/kernel/signal.c +18 -0
@@ -33,6 +33,7 @@#include <linux/linkage.h> #include <linux/tracehook.h> #include <asm/entry.h> +#include <asm/registers.h> #include <asm/ucontext.h> #include <linux/uaccess.h> #include <linux/syscalls.h>
@@ -81,6 +82,22 @@ static int restore_sigcontext(struct pt_regs *regs,COPY (pc);COPY (ear);COPY (esr);COPY (fsr);#undef COPY +/* +* The frame is user-writable, so restore only the user-writable +* status flags (carry) and keep the kernel-controlled MSR bits +* (UMS/VMS/IE/EE/...) from regs->msr: rtbd derives the resumed mode +* from UMS/VMS, so a verbatim restore would hand userspace the +* privileged return state. Same idea as x86 masking the restored +* EFLAGS to FIX_EFLAGS. +*/ + { +unsigned long msr; + + err |=__get_user (msr, &sc->regs.msr); + regs->msr = (regs->msr & ~(MSR_C |MSR_CC )) | + (msr & (MSR_C |MSR_CC )); + } + *rval_p = regs->r3;return err;
@@ -140,6 +157,7 @@ setup_sigcontext(struct sigcontext __user *sc, struct pt_regs *regs,COPY (r26);COPY (r27);COPY (r28);COPY (r29);COPY (r30);COPY (r31);COPY (pc);COPY (ear);COPY (esr);COPY (fsr); +COPY (msr);/* restore_sigcontext() accepts only carry state */ #undef COPY err |=__put_user (mask, &sc->oldmask);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 357/1848 memory: brcmstb_dpfe: Fix out-of-bounds access due to DCPU offset
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Justin Chen <[email protected]>
[ Upstream commit 7c0b82d087908765c6c7daeb06943e21b78d523e ]
On API v1/v2 boards, the DCPU coprocessor can steer kernel readl_relaxed() and writel_relaxed() to any address within 256 MB of the ioremapped DPFE dmem or regs base. The DCPU firmware provides a 28-bit offset which the driver adds to the ioremap base without any bounds checking in get_msg_ptr().
This allows a compromised DCPU firmware to trick the host kernel into reading or writing arbitrary memory-mapped I/O registers in vmalloc space. When combined with a root-writable sysfs file like dpfe_refresh, it provides an arbitrary MMIO write primitive. Similarly, world-readable sysfs files can be used to leak other devices' register contents.
Fix this by recording the resource_size() of the dmem and regs ioremaps at probe time, and rejecting any offset that, along with the largest field accessed (DRAM_VENDOR_ERROR + sizeof(u32)), exceeds the recorded mapping size.
--- drivers/memory/brcmstb_dpfe.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+)
drivers/memory/brcmstb_dpfe.c +15 -0
@@ -183,6 +183,8 @@ struct brcmstb_dpfe_priv {void __iomem *regs;void __iomem *dmem;void __iomem *imem; +resource_size_t regs_size; +resource_size_t dmem_size;struct device *dev;const struct dpfe_api *dpfe_api;struct mutex lock;
@@ -402,9 +404,14 @@ static void __iomem *get_msg_ptr(struct brcmstb_dpfe_priv *priv, u32 response,*/ switch (msg_type) {case 1 : +if (DCPU_MSG_RAM_START + offset +DRAM_VENDOR_ERROR + +sizeof (u32) > priv->regs_size) + goto bad_offset; ptr = priv->regs +DCPU_MSG_RAM_START + offset;break ;case 0 : +if (offset +DRAM_VENDOR_ERROR +sizeof (u32) > priv->dmem_size) + goto bad_offset; ptr = priv->dmem + offset;break ;default :
@@ -416,6 +423,12 @@ static void __iomem *get_msg_ptr(struct brcmstb_dpfe_priv *priv, u32 response, }return ptr; + +bad_offset: +dev_err (priv->dev,"DCPU returned out-of-range offset %#x\n" , offset); +if (buf && size) + *size =sprintf (buf,"ERROR: DCPU offset out of range\n" ); +return NULL ; }static void __finalize_command (struct brcmstb_dpfe_priv *priv)
@@ -877,6 +890,7 @@ static int brcmstb_dpfe_probe(struct platform_device *pdev)dev_err (dev,"couldn't map DCPU registers\n" );return -ENODEV ; } + priv->regs_size =resource_size (res); res =platform_get_resource_byname (pdev,IORESOURCE_MEM ,"dpfe-dmem" ); priv->dmem =devm_ioremap_resource (dev, res);
@@ -884,6 +898,7 @@ static int brcmstb_dpfe_probe(struct platform_device *pdev)dev_err (dev,"Couldn't map DCPU data memory\n" );return -ENOENT ; } + priv->dmem_size =resource_size (res); res =platform_get_resource_byname (pdev,IORESOURCE_MEM ,"dpfe-imem" ); priv->imem =devm_ioremap_resource (dev, res);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 358/1848 memory: brcmstb_dpfe: Bounds check DCPU-supplied MSG_ARG_COUNT
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Justin Chen <[email protected]>
[ Upstream commit 6b07f8c06caca015a0db69e3f323b5186469bc66 ]
A compromised or buggy DCPU coprocessor can make any user who reads world-readable /sys/devices/.../dpfe_info|dpfe_dram trigger a kernel stack out-of-bounds read of arbitrary extent. This bounds checks chksum_idx against MSG_FIELD_MAX after reading the response from DCPU message RAM.
--- drivers/memory/brcmstb_dpfe.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/memory/brcmstb_dpfe.c +2 -0
@@ -504,6 +504,8 @@ static int __send_command(struct brcmstb_dpfe_priv *priv, unsigned int cmd,for (i =0 ; i <MSG_FIELD_MAX ; i++) result[i] =readl_relaxed (regs +DCPU_MSG_RAM (i)); chksum_idx = result[MSG_ARG_COUNT ] +MSG_ARG_COUNT +1 ; +if (chksum_idx >=MSG_FIELD_MAX ) + ret = -EINVAL ; }/* Tell DCPU we are done */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 359/1848 wifi: rtw88: fix out-of-bounds CAM write when key table is full
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: イムティヤズ <[email protected]>
[ Upstream commit 10d58823cb44681466c022054030b8e68d94ce2f ]
In rtw_ops_set_key(), when the CAM table is full, rtw_sec_get_free_cam() returns RTW_MAX_SEC_CAM_NUM (32) because find_next_zero_bit()/find_first_zero_bit() return the bitmap size when no free slot exists. The bounds check compares the returned index with ">" against total_cam_num (32), so the invalid index 32 passes the check.
rtw_sec_write_cam() then indexes cam_table[32], an array declared with RTW_MAX_SEC_CAM_NUM (32) entries, causing an out-of-bounds write that corrupts the cam_map allocation bitmap. The write also sets bit 32 of cam_map, which overruns the bitmap as well.
Fix the off-by-one by rejecting indices >= total_cam_num.
Tested on: RTL8821CE (PCIe) on kernel 7.2.0-rc6-rtw88test-00059-g0d8395707651. The patched module loaded and associated to a WPA2 network; ping traffic passed with 0% packet loss. Reassociation and disconnect/reconnect cycles completed without errors, and the CAM table (debugfs dump_cam) showed valid key entries. The CAM-full boundary (28+ pairwise keys) requires an access point with 28+ clients and is not reachable in a single-client setup, so that path was verified by code inspection.
--- drivers/net/wireless/realtek/rtw88/mac80211.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/wireless/realtek/rtw88/mac80211.c +1 -1
@@ -499,7 +499,7 @@ static int rtw_ops_set_key(struct ieee80211_hw *hw, enum set_key_cmd cmd, hw_key_idx = key->keyidx; } -if (hw_key_idx > sec->total_cam_num) { +if (hw_key_idx >= sec->total_cam_num) { ret = -ENOSPC ; goto out; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 360/1848 wifi: ath11k: Fix possible memory leak in ath11k_dp_srng_setup()
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Abdun Nihaal <[email protected]>
[ Upstream commit 6132d70d0890c03546f6970893fd71938efb2a2f ]
In ath11k_dp_srng_setup(), the memory allocated for ring->vaddr_unaligned is not freed in the error paths that follow. Fix that by calling ath11k_dp_srng_cleanup() in those error paths.
Compile tested only. Issue found using a prototype static analysis tool built on the LLVM compiler infrastructure.
--- drivers/net/wireless/ath/ath11k/dp.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/net/wireless/ath/ath11k/dp.c +2 -0
@@ -288,12 +288,14 @@ int ath11k_dp_srng_setup(struct ath11k_base *ab, struct dp_srng *ring,case HAL_RXDMA_DIR_BUF :break ;default : +ath11k_dp_srng_cleanup (ab, ring);ath11k_warn (ab,"Not a valid ring type in dp :%d\n" , type);return -EINVAL ; } ret =ath11k_hal_srng_setup (ab, type, ring_num, mac_id, ¶ms);if (ret <0 ) { +ath11k_dp_srng_cleanup (ab, ring);ath11k_warn (ab,"failed to setup srng: %d ring_id %d\n" , ret, ring_num);return ret;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 361/1848 fs_pin: publish pins with RCU list helpers
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Karl Mehltretter <[email protected]>
[ Upstream commit 8d01d6b4c17c406f37a9b6edac93dfb858af30d0 ]
pin_insert() initializes a pin before adding it under pin_lock. The kill paths read the list heads under RCU without taking that lock. Plain hlist insertion does not publish the earlier initialization to those readers.
KCSAN weak-memory checking reported acct_on() callback initialization racing with pin_kill() after the superblock-list publication. The corresponding LKMM model permits the stale read with plain publication; the RCU release/acquire pair forbids it.
Use the RCU hlist add and dereference helpers for both pin lists.
--- fs/fs_pin.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-)
fs/fs_pin.c +5 -4
@@ -1,5 +1,6 @@// SPDX-License-Identifier: GPL-2.0 #include <linux/fs.h> +#include <linux/rculist.h> #include <linux/sched.h> #include <linux/slab.h> #include "internal.h"
@@ -22,8 +23,8 @@ void pin_remove(struct fs_pin *pin)void pin_insert (struct fs_pin *pin,struct vfsmount *m) {spin_lock (&pin_lock); -hlist_add_head (&pin->s_list, &m->mnt_sb->s_pins); -hlist_add_head (&pin->m_list, &real_mount (m)->mnt_pins); +hlist_add_head_rcu (&pin->s_list, &m->mnt_sb->s_pins); +hlist_add_head_rcu (&pin->m_list, &real_mount (m)->mnt_pins);spin_unlock (&pin_lock); }
@@ -73,7 +74,7 @@ void mnt_pin_kill(struct mount *m)while (1 ) {struct hlist_node *p;rcu_read_lock (); - p =READ_ONCE (m->mnt_pins.first); + p =rcu_dereference (hlist_first_rcu (&m->mnt_pins));if (!p) {rcu_read_unlock ();break ;
@@ -87,7 +88,7 @@ void group_pin_kill(struct hlist_head *p)while (1 ) {struct hlist_node *q;rcu_read_lock (); - q =READ_ONCE (p->first); + q =rcu_dereference (hlist_first_rcu (p));if (!q) {rcu_read_unlock ();break ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 362/1848 thermal: intel: powerclamp: Reject invalid window_size values
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Thorsten Blum <[email protected]>
[ Upstream commit 40989202104e498ff9adfb8c575d6cd159f13988 ]
window_size_set() sets ret to -EINVAL if new_window_size is outside the valid range, but then falls through and still updates window_size to the clamped value.
Return -EINVAL immediately and do not update window_size. Also drop the now-redundant clamp() call.
--- drivers/thermal/intel/intel_powerclamp.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/thermal/intel/intel_powerclamp.c +2 -1
@@ -154,9 +154,10 @@ static int window_size_set(const char *arg, const struct kernel_param *kp)pr_err ("Out of recommended window size %lu, between 2-10\n" , new_window_size); ret = -EINVAL ; + goto exit_win; } - window_size =clamp (new_window_size,2ul ,10ul ); + window_size = new_window_size;smp_mb (); exit_win:
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 363/1848 isofs: fix Rock Ridge CE extent validation on multisession media
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Baolin Liu <[email protected]>
[ Upstream commit 43de050fa4a31f7e7a73cf8974dcf6037e161a39 ]
Commit a36d990f5913 ("isofs: validate Rock Ridge CE continuation extent against volume size") compares the CE extent directly with s_nzones. The extent is an absolute block number, while s_nzones is the number of blocks relative to the selected ISO session. The comparison is therefore wrong when a multisession disc starts at a non-zero block.
isofs_get_last_session() selects the last session on multisession media, and its volume descriptors describe a volume beginning at that session's LBA.
For example, a session beginning at LBA 45447 with 64 blocks can contain a valid CE at absolute LBA 45467. The existing check rejects that CE, so the ER continuation record is not read, Rock Ridge is disabled, and the mount falls back to Joliet names.
Save the selected session start in filesystem-block units and validate the CE extent against the half-open interval [session_start, session_end). Scale the session length to the same block units and retain a separate block-device limit. The lower bound is intentional: accepting arbitrary blocks before the selected session could make a CE read data from a previous session or another filesystem on the device.
Only apply the bounds check when cont_extent is non-zero. A zero extent is the in-memory sentinel indicating that no CE continuation was found, rather than a request to read block zero.
For a single-session image, session_start is zero and the effective volume boundary remains unchanged.
Build-tested with:
make CONFIG_RUST= CONFIG_RUST_DRIVERS= fs/isofs/
--- fs/isofs/inode.c | 2 ++ fs/isofs/isofs.h | 2 ++ fs/isofs/rock.c | 11 +++++++++-- 3 files changed, 13 insertions(+), 2 deletions(-)
fs/isofs/inode.c +2 -0
@@ -861,6 +861,8 @@ static int isofs_fill_super(struct super_block *s, void *data, int silent)if (!sb_set_blocksize (s, orig_zonesize)) goto out_freesbi; + sbi->s_session_start = (sector_t )vol_desc_start << + (ISOFS_BLOCK_BITS - s->s_blocksize_bits); sbi->s_nls_iocharset =NULL ;#ifdef CONFIG_JOLIET
fs/isofs/isofs.h +2 -0
@@ -35,6 +35,8 @@ struct isofs_sb_info {unsigned long s_firstdatazone;unsigned long s_log_zone_size;unsigned long s_max_size; +/* Session start in filesystem block units. */ +sector_t s_session_start;int s_rock_offset;/* offset of SUSP fields within SU area */ s32 s_sbsector;
fs/isofs/rock.c +9 -2
@@ -9,6 +9,7 @@#include <linux/slab.h> #include <linux/pagemap.h> +#include <linux/blkdev.h> #include "isofs.h" #include "rock.h"
@@ -84,6 +85,10 @@ static void init_rock_state(struct rock_state *rs, struct inode *inode)*/ static int rock_continue (struct rock_state *rs) { +struct super_block *sb = rs->inode->i_sb; +struct isofs_sb_info *sbi =ISOFS_SB (sb); +sector_t session_end = sbi->s_session_start + + ((sector_t )sbi->s_nzones << (ISOFS_BLOCK_BITS - sb->s_blocksize_bits));int ret =1 ;int blocksize =1 << rs->inode->i_blkbits;const int min_de_size = offsetof(struct rock_ridge , u);
@@ -101,11 +106,13 @@ static int rock_continue(struct rock_state *rs) goto out; } -if ((unsigned )rs->cont_extent >=ISOFS_SB (rs->inode->i_sb)->s_nzones) { +if (rs->cont_extent && + (rs->cont_extent < sbi->s_session_start || + rs->cont_extent >= session_end)) {printk (KERN_NOTICE "rock: corrupted directory entry. " "extent=%u out of volume (nzones=%lu)\n" , (unsigned )rs->cont_extent, -ISOFS_SB (rs->inode->i_sb)->s_nzones); + sbi->s_nzones); ret = -EIO ; goto out; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 364/1848 media: cx231xx: Fix cleanup path on failure
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andi Shyti <[email protected]>
[ Upstream commit 6e30287eaf3e41b86dfb86df3b811526693d74b4 ]
If cx231xx_init_v4l2() fails the probe currently jumps to err_init, which only unregisters the V4L2 device. The analog devices and I2C resources are left registered while the driver state can be released.
A subsequent driver bind attempts to create the same I2C mux channel links and triggers a warning when the existing "channel-0" link is encountered. The remaining devices may also access released driver state. This produces the following warning
can't create symlink to channel 0
WARNING: drivers/i2c/i2c-mux.c:403 at i2c_mux_add_adapter+0xcd8/0xeb0
Call Trace:
i2c_mux_add_adapter+0xcdc/0xeb0
cx231xx_dev_init+0x2fb/0x1260
cx231xx_usb_probe+0xc48/0x2140
usb_probe_interface+0x657/0xc70
...Jump to err_video_alt instead, which performs the full device cleanup before unregistering the V4L2 device.
--- drivers/media/usb/cx231xx/cx231xx-cards.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/media/usb/cx231xx/cx231xx-cards.c +1 -1
@@ -1830,7 +1830,7 @@ static int cx231xx_usb_probe(struct usb_interface *interface, retval =cx231xx_init_v4l2 (dev, udev, interface, isoc_pipe);if (retval) - goto err_init; + goto err_video_alt;if (dev->current_pcb_config.ts1_source !=0xff ) {/* compute alternate max packet sizes for TS1 */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 365/1848 media: au0828: Free URBs when starting DVB streaming fails
In reply to Greg Kroah-Hartman5.10-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ruoyu Wang <[email protected]>
[ Upstream commit b8dd133d96a40012f4b67fd48d8ddd7306a3e024 ]
start_urb_transfer() stores each allocated URB in dev->urbs[], but sets urb_streaming only after all URBs have been submitted. If a later URB or transfer buffer allocation fails, earlier entries are left allocated. A submission failure calls stop_urb_transfer(), but that function returns immediately while urb_streaming is false, leaving both submitted and unsubmitted URBs behind.
Make stop_urb_transfer() release every populated slot regardless of the streaming flag and clear each slot after release. Route all start errors through this cleanup. usb_kill_urb() safely handles both submitted and unsubmitted URBs, while the existing preallocation check preserves the lifetime of shared transfer buffers.
This issue was found by a static analysis checker and confirmed by manual source review.
--- drivers/media/usb/au0828/au0828-dvb.c | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-)
drivers/media/usb/au0828/au0828-dvb.c +11 -8
@@ -163,9 +163,6 @@ static int stop_urb_transfer(struct au0828_dev *dev)dprintk (2 ,"%s()\n" , __func__); -if (!dev->urb_streaming) -return 0 ; -if (dev->bulk_timeout_running ==1 ) { dev->bulk_timeout_running =0 ;del_timer (&dev->bulk_timeout);
@@ -179,6 +176,7 @@ static int stop_urb_transfer(struct au0828_dev *dev)kfree (dev->urbs[i]->transfer_buffer);usb_free_urb (dev->urbs[i]); + dev->urbs[i] =NULL ; } }
@@ -200,8 +198,10 @@ static int start_urb_transfer(struct au0828_dev *dev)for (i =0 ; i <URB_COUNT ; i++) { dev->urbs[i] =usb_alloc_urb (0 ,GFP_KERNEL ); -if (!dev->urbs[i]) -return -ENOMEM ; +if (!dev->urbs[i]) { + ret = -ENOMEM ; + goto err; + } purb = dev->urbs[i];
@@ -217,7 +217,7 @@ static int start_urb_transfer(struct au0828_dev *dev) ret = -ENOMEM ;pr_err ("%s: failed big buffer allocation, err = %d\n" , __func__, ret); -return ret; + goto err; } purb->status = -EINPROGRESS ;
@@ -235,10 +235,9 @@ static int start_urb_transfer(struct au0828_dev *dev)for (i =0 ; i <URB_COUNT ; i++) { ret =usb_submit_urb (dev->urbs[i],GFP_ATOMIC );if (ret !=0 ) { -stop_urb_transfer (dev);pr_err ("%s: failed urb submission, err = %d\n" , __func__, ret); -return ret; + goto err; } }
@@ -249,6 +248,10 @@ static int start_urb_transfer(struct au0828_dev *dev) dev->bulk_timeout_running =1 ;return 0 ; + +err: +stop_urb_transfer (dev); +return ret; }static void au0828_start_transport (struct au0828_dev *dev)
Signature · 1 line
2.53.0