Subject: [PATCH 6.1 0994/1146] igb: Do not free q_vector unless new one was allocated

From: Greg Kroah-Hartman <[email-masked]>
Date: Wed, 28 Dec 2022 15:42:13 +0100

From: Kees Cook <[email-masked]>

[ Upstream commit 0668716506ca66f90d395f36ccdaebc3e0e84801 ]

Avoid potential use-after-free condition under memory pressure. If the
kzalloc() fails, q_vector will be freed but left in the original
adapter->q_vector[v_idx] array position.

Cc: Jesse Brandeburg <[email-masked]>
Cc: Tony Nguyen <[email-masked]>
Cc: "David S. Miller" <[email-masked]>
Cc: Eric Dumazet <[email-masked]>
Cc: Jakub Kicinski <[email-masked]>
Cc: Paolo Abeni <[email-masked]>
Cc: [email-masked]
Cc: [email-masked]
Signed-off-by: Kees Cook <[email-masked]>
Reviewed-by: Michael J. Ruhl <[email-masked]>
Reviewed-by: Jacob Keller <[email-masked]>
Tested-by: Gurucharan <[email-masked]> (A Contingent worker at Intel)
Signed-off-by: Tony Nguyen <[email-masked]>
Signed-off-by: Sasha Levin <[email-masked]>
---
 drivers/net/ethernet/intel/igb/igb_main.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/drivers/net/ethernet/intel/igb/igb_main.c b/drivers/net/ethernet/intel/igb/igb_main.c
index 473158c09f1d..24a6ae19ad8e 100644
--- a/drivers/net/ethernet/intel/igb/igb_main.c
+++ b/drivers/net/ethernet/intel/igb/igb_main.c
@@ -1202,8 +1202,12 @@ static int igb_alloc_q_vector(struct igb_adapter *adapter,
 	if (!q_vector) {
 		q_vector = kzalloc(size, GFP_KERNEL);
 	} else if (size > ksize(q_vector)) {
-		kfree_rcu(q_vector, rcu);
-		q_vector = kzalloc(size, GFP_KERNEL);
+		struct igb_q_vector *new_q_vector;
+
+		new_q_vector = kzalloc(size, GFP_KERNEL);
+		if (new_q_vector)
+			kfree_rcu(q_vector, rcu);
+		q_vector = new_q_vector;
 	} else {
 		memset(q_vector, 0, size);
 	}
-- 
2.35.1