git: b9f6b6685558 - stable/13 - pf: always mark states as unlinked before detaching them

From: Kristof Provost <kp_at_FreeBSD.org>
Date: Thu, 16 May 2024 12:02:42 UTC
The branch stable/13 has been updated by kp:

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

commit b9f6b668555849a8d6d322b803264404d65615cd
Author:     Kristof Provost <kp@FreeBSD.org>
AuthorDate: 2024-05-06 07:43:49 +0000
Commit:     Kristof Provost <kp@FreeBSD.org>
CommitDate: 2024-05-16 07:40:35 +0000

    pf: always mark states as unlinked before detaching them
    
    Users have reported crashes in pf_test_state_udp() where at least one state key
    is NULL.
    
    That suggests that pf_detach_state() ran concurrently with pf_test_state_udp().
    pf_test_state_udp() holds the state lock (aka the id lock), but
    pf_detach_state() does not.
    The intent is that detached states are not returned by STATE_LOOKUP/
    pf_find_state(), as the state's timeout is set to PFTM_UNLINKED and thus
    pf_find_state() does not find the state.
    
    There are other paths to pf_detach_state() (outside of pf_unlink_state())
    though, where we did not set the timeout to PFTM_UNLINKED. Fix those, and assert
    that the timeout is set correctly when we enter pf_detach_state().
    
    MFC after:      1 week
    See also:       https://redmine.pfsense.org/issues/15413
    Sponsored by:   Rubicon Communications, LLC ("Netgate")
    Differential Revision:  https://reviews.freebsd.org/D45101
    
    (cherry picked from commit 301ec2cebb6a3e472af39eb7b98c3b7ff88e04b0)
---
 sys/netpfil/pf/pf.c | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/sys/netpfil/pf/pf.c b/sys/netpfil/pf/pf.c
index 1fd5803117bd..2c171514e946 100644
--- a/sys/netpfil/pf/pf.c
+++ b/sys/netpfil/pf/pf.c
@@ -1283,6 +1283,7 @@ keyattach:
 						    sk : NULL);
 						printf("\n");
 					}
+					s->timeout = PFTM_UNLINKED;
 					PF_HASHROW_UNLOCK(ih);
 					KEYS_UNLOCK();
 					uma_zfree(V_pf_state_key_z, sk);
@@ -1350,6 +1351,8 @@ pf_detach_state(struct pf_kstate *s)
 	struct pf_state_key *sks = s->key[PF_SK_STACK];
 	struct pf_keyhash *kh;
 
+	MPASS(s->timeout >= PFTM_MAX);
+
 	pf_sctp_multihome_detach_addr(s);
 
 	if (sks != NULL) {
@@ -1478,6 +1481,7 @@ pf_state_insert(struct pfi_kkif *kif, struct pfi_kkif *orig_kif,
 			break;
 
 	if (cur != NULL) {
+		s->timeout = PFTM_UNLINKED;
 		PF_HASHROW_UNLOCK(ih);
 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
 			printf("pf: state ID collision: "