git: 488bf4473772 - main - netipsec: Do not leak the SAH when an SA is cloned

From: R. Christian McDonald <rcm_at_FreeBSD.org>
Date: Mon, 09 Nov 2026 15:31:37 UTC
The branch main has been updated by rcm:

URL: https://cgit.FreeBSD.org/src/commit/?id=488bf44737722c27f2e93b5347648e76e86540df

commit 488bf44737722c27f2e93b5347648e76e86540df
Author:     R. Christian McDonald <rcm@FreeBSD.org>
AuthorDate: 2026-11-09 15:30:12 +0000
Commit:     R. Christian McDonald <rcm@FreeBSD.org>
CommitDate: 2026-11-09 15:30:12 +0000

    netipsec: Do not leak the SAH when an SA is cloned
    
    key_updateaddresses() gives the clone of an SA a new SAH reference when
    the SA index comes from key_newsah() or key_getsah(), but nothing
    releases the reference of the old SA: key_delsav() leaves the SAH alone,
    because key_unlinksav() normally releases it, and an SA that is replaced
    never goes through that.  The SAH then stays allocated for good, after
    its SAs are flushed and after the vnet is destroyed, as an SADB_UPDATE
    with a new address does each time an IKE daemon moves an SA.
    
    The old SA cannot release the reference when it is replaced, since a
    sender that still holds it reads its SAH.  Release it in key_delsav()
    instead.  When only the NAT-T config changes, the clone used to take over
    the reference of the old SA; take a new one in that case as well, so that
    every SA holds its own.
    
    Reviewed by:            kib, markj
    MFC after:              1 week
    Sponsored by:           Rubicon Communications, LLC ("Netgate")
    Differential Revision:  https://reviews.freebsd.org/D61101
---
 sys/netipsec/key.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)

diff --git a/sys/netipsec/key.c b/sys/netipsec/key.c
index 06cb748bf2a7..a2563689798f 100644
--- a/sys/netipsec/key.c
+++ b/sys/netipsec/key.c
@@ -3284,7 +3284,8 @@ key_delsav(struct secasvar *sav)
 		rm_destroy(sav->lock);
 		free(sav->lock, M_IPSEC_MISC);
 		uma_zfree_pcpu(ipsec_key_lft_zone, sav->lft_c);
-	}
+	} else
+		key_freesah(&sav->sah);
 #ifdef IPSEC_OFFLOAD
 	/* XXXKIB should this be moved to key_cleansav()? */
 	uma_zfree_pcpu(ipsec_key_lft_zone, sav->accel_lft_sw);
@@ -5504,9 +5505,12 @@ key_updateaddresses(struct socket *so, struct mbuf *m,
 	}
 	/*
 	 * isnew == 1 -> @sah was referenced by key_getsah().
-	 * isnew == 0 -> we use the same @sah, that was used by @sav,
-	 *	and we use its reference for @newsav.
+	 * isnew == 0 -> we use the same @sah, that was used by @sav.
+	 * @sav keeps its own reference until key_delsav(): a sender that
+	 * still holds @sav reads its SAH.
 	 */
+	if (isnew == 0)
+		SAH_ADDREF(sah);
 	SECASVAR_WLOCK(sav);
 	/* XXX: replace cntr with pointer? */
 	newsav->cntr = sav->cntr;