Skip to contentSkip to conversation

psp: support rekeying psp protected tcp connections

PATCH Superseded Daniel Zahka 2 participants 11 messages Nov 16 – Nov 18

Subsystems (6)

v4 of 5 Superseded Latest is v5 →

lore
Share & tools
lore

Daniel Zahka

author maintainer
#0 lore raw

v4 cover psp: support rekeying psp protected tcp connections

A note on v3 and later:
To keep this series short, I have split off some of the content that appeared in v2, and also have planned future work that will make this feature more robust, but not necessary to start. Here is the current queue of follow up series:
1. core tracked tx-key-count stat and SADB drain test case (from v2). I see this as able to stand alone as a series, and I also would like to report key deletion errors, but will have to touch mlx5 for that.
2. core to end grace period if BQL is stalled. I think this deserves its own series for human discussion.
3. Rate limiting rekey uAPIs. This has been suggusted by the bot, but whether or not it is needed depends on a bit on the deployment model.

Original cover letter:

The PSP architecture spec states the need for rekeying connections in the event of a device key rotation. After a device key rotation has occurred, a new rx derived key needs to be generated and sent out to the other end of the connection sometime before the next device key rotation occurs.

Because PSP connections involve two different keys at each endpoint, one for decrypting ingress traffic, and one for encrypting egress traffic, there are two types of rekeying events that need to be supported. From the perspective of one endpoint of the connection:

1. rx rekey: we need to allocate a new spi + decryption key pair to provide to our peer.

2. tx rekey: our peer has provided us with a new spi + encryption key pair which we should use for encrypting traffic immediately.

In the case of rx rekeying, there is a period where it makes sense to accept packets authenticated from either the previous or current spi. To deal with that, we allow a psp_assoc to remember the last spi that was valid on a socket due to a rekey. If authentication state does not match the most recent assoc, the stored state from the previous assoc will be tried.

In the case of tx rekeying, as soon as we install the new tx key, we have no use for the previous one, and it can be disposed of immediately. The only catch is in the case where hw uses a key handle in tx descriptor state, as opposed to inlining the key directly. In this case, psp core needs to be sure that any of these unaccounted for references to key state are gone by the time it tries to sync a deleted key to hw.

To deal with this race condition, we introduce a different path to key deletion for psp_assocs removed from the socket during a tx rekey. psp core will use bql byte counters filled out by the driver to determine a conservative grace period where key handles can be disposed of.

Lastly, some test cases for rekeying are included that go through key rotations and rekeying.

There are some packetdrill tests that are queued for upstreaming [1].

Future work can include a time based rate limit on the rx-assoc/tx-assoc uAPIs to prevent an untrusted user from creating lots of wasted PSP assocs and consuming SPIs, SADB space, etc. For now, users should use network namespaces, or otherwise not present PSP devices to users that could abuse this.

[1]: https://github.com/danieldzahka/packetdrill/commits/psp-rekey/

---
Changes in v4:
- selftests: drv-net: psp: factor out psp connection setup
- drop closing the data socket on conn_setup_psp() failure; preexisting and not needed by the series
- selftests: drv-net: psp: add rekey tests
- reuse _recv_careful() and _req_echo() now in net-next instead of redefining them
- Link to v3: https://lore.kernel.org/r/[email protected]

Changes in v3:
- psp: support rx rekey operation
- move the replaced assoc to psd->stale_assocs, so a rotation racing with its free doesn't count it in stale-events
- drop the requirement that the new rx spi has the opposite phase bit from the previous one
- keep prev_generation valid across a rotation when the prev SPI is from the same generation
- document rx rekey in the rx-assoc op doc in psp.yaml
- psp: support tx rekey operation
- move the replaced assoc to psd->stale_assocs, so a rotation racing with its free doesn't count the socket twice in stale-events
- document that the previous rx SPI also stops being accepted once its device key is rotated out
- drop the claim that the peer accepts both the old and new SPI after a tx rekey
- document tx rekey in the tx-assoc op doc in psp.yaml
- psp: defer tx key deletions for SADB drivers
- document that Tx descriptors must be completed or discarded before psp_dev_unregister()
- selftests: drv-net: psp: factor out psp connection setup
- take key lengths from the kernel's rx-assoc reply instead of a per-version table
- close the data socket in psp_responder if conn_setup_psp() fails
- selftests: drv-net: psp: add rekey tests
- drop test for rx rekey rejected without a device key rotation
- fail fast in _recv_careful() if the peer closes the connection
- in the basic rekey tests, run traffic across a rotation before the rekey, and rotate again after it to verify the new key is in use
- drop unneeded key rotation from rekey_rx_version_mismatch()
- carry the key length in the responder's assoc message instead of deriving it from the version
- psp: add core tracked stat for outstanding tx keys
- moved to a follow-up series
- selftests: drv-net: psp: add a tx rekey drain test for SADB drivers
- moved to a follow-up series
- Link to v2: https://lore.kernel.org/r/[email protected]

Changes in v2:
- psp: support rx rekey operation
- copy old rx state by value instead of pointer to prev
- place non-datapath fields at end of struct psp_assoc
- disallow rx rekey when socket is not in full psp state, or dev/version doesn't match
- require the new rx spi to have the opposite phase bit from the previous one
- psp: support tx rekey operation
- place new assoc on pas->assocs list instead of psd->active_assocs
- disallow tx rekey when socket is not in full psp state
- document rekeying in psp.rst
- reject tx rekey on SADB devices until deferred tx key deletion lands
- psp: defer tx key deletions for SADB drivers
- replaces "psp: add driver api for deferred tx key deletion"
- use bql byte counters instead of driver callback for grace periods
- only defer tx key deletion when socket outlives psp_assoc
- document driver requirements in psp.rst
- allow tx rekey on SADB devices
- psp: add core tracked stat for outstanding tx keys
- replaces "psp: add core tracked stats for deferred key deletion"
- drop grace-periods stat
- rename tx-key-cnt to tx-key-count, only report it for SADB drivers
- warn about outstanding tx keys in psp_dev_unregister()
- selftests: drv-net: psp: factor out psp connection setup
- split psp_responder conn_setup_psp() into rx_assoc() and tx_assoc()
- drop Reviewed-by from Willem due to psp_responder changes
- selftests: drv-net: psp: add rekey tests
- add tests for rekeys rejected due to psp state and version mismatch
- add test for rx rekey rejected without a device key rotation
- add rx-assoc, tx-assoc, and key-rotate rpcs to psp_responder
- selftests: drv-net: psp: add a tx rekey drain test for SADB drivers
- new patch
- mlx5: psp: implement deferred tx key deletion
- dropped, bql based grace periods need no driver callback
- Link to v1: https://lore.kernel.org/r/[email protected]

To: Daniel Zahka <[email protected]>
To: Jakub Kicinski <[email protected]>
To: Willem de Bruijn <[email protected]>
To: David S. Miller <[email protected]>
To: Eric Dumazet <[email protected]>
To: Paolo Abeni <[email protected]>
To: Simon Horman <[email protected]>
To: Jonathan Corbet <[email protected]>
To: Shuah Khan <[email protected]>
To: Randy Dunlap <[email protected]>
To: Donald Hunter <[email protected]>
To: Andrew Lunn <[email protected]>
To: Shuah Khan <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]

---
Daniel Zahka (5):
psp: support rx rekey operation
psp: support tx rekey operation
psp: defer tx key deletions for SADB drivers
selftests: drv-net: psp: factor out psp connection setup
selftests: drv-net: psp: add rekey tests

 Documentation/netlink/specs/psp.yaml               |   8 +-
 Documentation/networking/psp.rst                   |  68 +++++-
 include/net/psp/functions.h                        |  10 +-
 include/net/psp/types.h                            |  35 ++-
 net/psp/Kconfig                                    |   1 +
 net/psp/Makefile                                   |   2 +-
 net/psp/psp.h                                      |   8 +-
 net/psp/psp_deferred_del.c                         | 231 +++++++++++++++++++
 net/psp/psp_main.c                                 |  22 +-
 net/psp/psp_sock.c                                 | 114 +++++++++-
 tools/testing/selftests/drivers/net/psp.py         | 251 ++++++++++++++++++++-
 .../testing/selftests/drivers/net/psp_responder.c  | 192 ++++++++++++++--
 12 files changed, 886 insertions(+), 56 deletions(-)

---
base-commit: 7ccc5e05043b1bb84326b19a2b05938d8f7a2ae6
change-id: 20260202-psp-3c8e2f65c5c4

Best regards,

Signature · 1 line
Daniel Zahka <[email protected]>
author maintainer
#1 lore raw

PATCH v4 1/5 psp: support rx rekey operation

Support updating the rx PSP state used by a socket. This is most useful to do after a device key rotation has occurred and the key being used by the peer will become stale after the next device key rotation.

Create a new psp_assoc for the socket to use that contains the same tx state, but with new rx state. Copy the previous rx state to use as a fallback while the peer is in the process of switching to the new key.

skbs matching the current rx spi and generation or the previous rx spi and generation will be accepted. It might be reasonable to stop accepting skbs on the previous state after seeing skbs with the new state and after waiting a grace period, but that is not implemented for now.

---
v3:
- move the replaced assoc to psd->stale_assocs, so a rotation racing with its free doesn't count it in stale-events
- drop the requirement that the new rx spi has the opposite phase bit from the previous one
- keep prev_generation valid across a rotation when the prev SPI is from the same generation
- document rx rekey in the rx-assoc op doc in psp.yaml

v2:
- copy old rx state by value instead of pointer to prev
- place non-datapath fields at end of struct psp_assoc
- disallow rx rekey when socket is not in full psp state, or dev/version doesn't match.
- require the new rx spi to have the opposite phase bit from the previous one

---
 Documentation/netlink/specs/psp.yaml |  4 ++-
 Documentation/networking/psp.rst     | 23 ++++++++++++++--
 include/net/psp/functions.h          | 10 ++++---
 include/net/psp/types.h              | 17 +++++++++++-
 net/psp/psp.h                        |  3 ++-
 net/psp/psp_sock.c                   | 52 +++++++++++++++++++++++++++++++++---
 6 files changed, 96 insertions(+), 13 deletions(-)
Documentation/netlink/specs/psp.yaml +3 -1
index f3266763c325..d5713f5d1af7 100644
@@ -265,7 +265,9 @@ operations:
 
     -
       name: rx-assoc
-      doc: Allocate a new Rx key + SPI pair, associate it with a socket.
+      doc: |
+        Allocate a new Rx key + SPI pair, associate it with a socket.
+        If the socket already has PSP state, rekey its Rx direction.
       attribute-set: assoc
       do:
         request:
Documentation/networking/psp.rst +21 -2
index 0f9b6b73f244..fab797506b0a 100644
@@ -140,14 +140,33 @@ The PSP assoc state of a socket is not reset when the connection is
 torn down. ``connect()`` on a socket that has PSP assoc state will
 return ``-EINVAL``.
 
+Rekeying
+--------
+
+A connection which has completed the exchange described above and is
+in the "PSP Full" state can be rekeyed in place without being torn
+down, using the same netlink calls as in connection setup.
+
+``rx-assoc`` allocates a new Rx key and SPI, which should be passed
+to the peer exactly as during the initial exchange. The SPI which was
+in use before the rekey remains acceptable on the socket until the
+next Rx rekey, or until the device key it was derived from has been
+rotated out, so packets the peer sent before it learned the new SPI
+are still received.
+
+A rekey is rejected with ``-EINVAL`` if it would change the PSP device
+or the PSP version of the association. It is rejected with ``-EBUSY``
+if the socket has not completed its initial exchange in both
+directions.
+
 Rotation notifications
 ----------------------
 
 The rotations of device key happen asynchronously and are usually
 performed by management daemons, not under application control.
 The PSP netlink family will generate a notification whenever keys
-are rotated. The applications are expected to re-establish connections
-before keys are rotated again.
+are rotated. Applications are expected to rekey their connections,
+as described above, before device keys are rotated again.
 
 Kernel implementation
 =====================
include/net/psp/functions.h +6 -4
index 410adb6718c1..5a7a518b9579 100644
@@ -77,10 +77,12 @@ psp_is_allowed_nondata(struct sk_buff *skb, struct psp_assoc *pas)
 static inline bool
 psp_pse_matches_pas(struct psp_skb_ext *pse, struct psp_assoc *pas)
 {
-	return pse && pas->rx.spi == pse->spi &&
-	       pas->generation == pse->generation &&
-	       pas->version == pse->version &&
-	       pas->dev_id == pse->dev_id;
+	return pse && pas->version == pse->version &&
+	       pas->dev_id == pse->dev_id &&
+	       ((pas->rx.spi == pse->spi &&
+		 pas->generation == pse->generation) ||
+		(pas->prev_spi && pas->prev_spi == pse->spi &&
+		 pas->prev_generation == pse->generation));
 }
 
 static inline enum skb_drop_reason
include/net/psp/types.h +16 -1
index b8905efbd604..9eb89d2d680c 100644
@@ -3,6 +3,7 @@
 #ifndef __NET_PSP_H
 #define __NET_PSP_H
 
+#include <linux/bits.h>
 #include <linux/mutex.h>
 #include <linux/refcount.h>
 #include <net/net_trackers.h>
@@ -78,7 +79,8 @@ struct psp_assoc_dev {
  * @active_assocs:	list of registered associations
  * @prev_assocs:	associations which use old (but still usable)
  *			device key
- * @stale_assocs:	associations which use a rotated out key
+ * @stale_assocs:	associations which use a rotated out key, or were
+ *			superseded by a rekey
  *
  * @stats:	statistics maintained by the core
  * @stats.rotations:	See stats attr key-rotations
@@ -152,6 +154,15 @@ struct psp_key_parsed {
 	u8 key[PSP_MAX_KEY];
 };
 
+/**
+ * enum psp_assoc_flags - flags of struct psp_assoc
+ * @PSP_ASSOC_SKIP_TX_KEY_DEL: Do not delete Tx key from psp_dev. It was
+ *	copied to a newer psp_assoc during an Rx rekey.
+ */
+enum psp_assoc_flags {
+	PSP_ASSOC_SKIP_TX_KEY_DEL	= BIT(0),
+};
+
 struct psp_assoc {
 	struct psp_dev *psd;
 
@@ -159,6 +170,10 @@ struct psp_assoc {
 	u8 generation;
 	u8 version;
 	u8 peer_tx;
+	u8 prev_generation;
+	u8 flags; /* Slow path, protected by psd->lock */
+
+	__be32 prev_spi;
 
 	u32 upgrade_seq;
 
net/psp/psp.h +2 -1
index b123c2427905..92d7b92acaed 100644
@@ -63,7 +63,8 @@ static inline bool psp_dev_has_sadb(struct psp_dev *psd)
 static inline bool psp_assoc_needs_tx_key_del(struct psp_assoc *pas)
 {
 	lockdep_assert_held(&pas->psd->lock);
-	return psp_dev_has_sadb(pas->psd) && pas->tx.spi;
+	return psp_dev_has_sadb(pas->psd) && pas->tx.spi &&
+	       !(pas->flags & PSP_ASSOC_SKIP_TX_KEY_DEL);
 }
 
 #endif /* __PSP_PSP_H */
net/psp/psp_sock.c +48 -4

82 lines not on this page · raw message

Signature · 1 line
2.52.1
#2 lore raw

Re: [PATCH net-next v4 1/5] psp: support rx rekey operation

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you…

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you respin.

Low priority / nit picks for your consideration:

- [Low] At this commit, Documentation/networking/psp.rst says a PSP Full connection can be rekeyed in place 'using the same netlink calls as in…
- [Low] The new field pas->prev_generation is written with a plain read- modify-write (pas->prev_generation |= ~PSP_GEN_VALID_MASK) in…

--

psp: support rx rekey operation

This commit lets rx-assoc run on a socket that already has PSP state. It creates a new psp_assoc that keeps the existing Tx state and gets new Rx state. The previous Rx SPI and generation are kept as a fallback, so packets the peer sends with the old key are still accepted until the next Rx rekey or device key rotation.

Quoted 5 lines
Documentation/networking/psp.rst +0 -0
index 0f9b6b73f2447..fab797506b0a9 100644

Documentation/networking/psp.rst The PSP assoc state of a socket is not reset when the connection is · line 148

Quoted 9 lines
Documentation/networking/psp.rst +6 -0
@@ -140,14 +140,33 @@ The PSP assoc state of a socket is not reset when the connection is
 torn down. ``connect()`` on a socket that has PSP assoc state will
 return ``-EINVAL``.
 
+Rekeying
+--------
+
+A connection which has completed the exchange described above and is
+in the "PSP Full" state can be rekeyed in place without being torn
+down, using the same netlink calls as in connection setup.

[Severity: Low]
Is this accurate at this point in the series?

To finish the rekey, the peer has to install the new SPI and key with tx-assoc. At this commit, psp_sock_assoc_set_tx() in net/psp/psp_sock.c still rejects tx-assoc on a socket that already has a Tx key:

	if (pas->tx.spi) {
		NL_SET_ERR_MSG(extack, "Tx key already set");
		err = -EBUSY;
		goto exit_unlock;
	}

An application on a kernel at exactly this commit that follows this text, or the updated "Applications are expected to rekey their connections" wording in the Rotation notifications section, would get -EBUSY from tx-assoc on the peer.

Later patches in the series close this gap:

- "psp: support tx rekey operation" replaces this branch with a call to psp_sock_tx_rekey().
- "psp: defer tx key deletions for SADB drivers" removes the temporary -EOPNOTSUPP for SADB drivers.
- "selftests: drv-net: psp: add rekey tests" adds test coverage.

The final psp.rst also documents the tx-assoc rekey path.

Could the documentation changes move to the tx rekey patch, so that the docs match the code at each commit?

[ ... ]

Quoted 4 lines
net/psp/psp_sock.c +0 -0
index f2cba3fa3a235..c1e38845f08c3 100644

[ ... ]

Quoted 8 lines
net/psp/psp_sock.c +2 -0
@@ -302,8 +333,21 @@ void psp_assocs_key_rotated(struct psp_dev *psd)
 	 */
 	list_for_each_entry_safe(pas, next, &psd->prev_assocs, assocs_list) {
 		pas->generation |= ~PSP_GEN_VALID_MASK;
+		pas->prev_generation |= ~PSP_GEN_VALID_MASK;
 		psd->stats.stales++;
 	}
+

net/psp/psp_sock.c void psp_assocs_key_rotated(struct psp_dev *psd) · line 349

Quoted 10 lines
net/psp/psp_sock.c +10 -0
+	/* Don't allow SPI from two generations ago to alias one from the
+	 * current generation. Rx rekeying under the same device key generation
+	 * is currently permitted, so skip if the previous SPI is from just one
+	 * generation ago.
+	 */
+	list_for_each_entry(pas, &psd->active_assocs, assocs_list) {
+		if ((pas->rx.spi ^ pas->prev_spi) &
+		    cpu_to_be32(PSP_SPI_KEY_PHASE))
+			pas->prev_generation |= ~PSP_GEN_VALID_MASK;
+	}

[Severity: Low]
Should these updates to pas->prev_generation use WRITE_ONCE(), with a matching READ_ONCE() on the reader side?

psp_assocs_key_rotated() holds only psd->lock here. The field is read without that lock in psp_pse_matches_pas():

	(pas->prev_spi && pas->prev_spi == pse->spi &&
	 pas->prev_generation == pse->generation));

There are two paths to that reader, and neither takes psd->lock:

- __psp_sk_rx_policy_check() from tcp_v4_do_rcv()/tcp_v6_do_rcv(), under the socket lock.
- psp_twsk_rx_policy_check() from tcp_v4_rcv()/tcp_v6_rcv() and tcp_timewait_state_process(), under RCU only.

These are compound read-modify-write stores, so KCSAN can report them even with CONFIG_KCSAN_ASSUME_PLAIN_WRITES_ATOMIC.

pas->generation already uses the same unannotated pattern. This patch adds a new field and a new writer loop over assocs that are attached to live sockets.

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261116-psp-v4-0-1a599df2aefa%40gmail.com
author maintainer
#3 lore raw

PATCH v4 2/5 psp: support tx rekey operation

In reply to Daniel Zahka

The tx rekey operation creates a new psp_assoc with the same rx state, but with new tx state. The new association is spliced into the socket with RCU to be used immediately in the tx path.

Drivers that use on-device tx key storage need additional logic to delay key deletion until after any in-flight users of the key have been drained, so return -EOPNOTSUPP for now.

---
v3:
- move the replaced assoc to psd->stale_assocs, so a rotation racing with its free doesn't count the socket twice in stale-events
- document that the previous rx SPI also stops being accepted once its device key is rotated out
- drop the claim that the peer accepts both the old and new SPI after a tx rekey
- document tx rekey in the tx-assoc op doc in psp.yaml

v2:
- place new assoc on pas->assocs list instead of psd->active assocs list
- reject tx rekey on SADB devices until deferred tx key deletion lands

---
 Documentation/netlink/specs/psp.yaml |  4 ++-
 Documentation/networking/psp.rst     |  5 +++-
 net/psp/psp_sock.c                   | 57 ++++++++++++++++++++++++++++++++----
 3 files changed, 58 insertions(+), 8 deletions(-)
Documentation/netlink/specs/psp.yaml +3 -1
index d5713f5d1af7..f6af1a510d17 100644
@@ -283,7 +283,9 @@ operations:
         post: psp-device-unlock
     -
       name: tx-assoc
-      doc: Add a PSP Tx association.
+      doc: |
+        Add a PSP Tx association.
+        If the socket already has a Tx association, rekey its Tx direction.
       attribute-set: assoc
       do:
         request:
Documentation/networking/psp.rst +4 -1
index fab797506b0a..43f222b38d3d 100644
@@ -145,7 +145,8 @@ Rekeying
 
 A connection which has completed the exchange described above and is
 in the "PSP Full" state can be rekeyed in place without being torn
-down, using the same netlink calls as in connection setup.
+down. The Tx and Rx directions are rekeyed separately using the same
+netlink calls as in connection setup.
 
 ``rx-assoc`` allocates a new Rx key and SPI, which should be passed
 to the peer exactly as during the initial exchange. The SPI which was
@@ -154,6 +155,8 @@ next Rx rekey, or until the device key it was derived from has been
 rotated out, so packets the peer sent before it learned the new SPI
 are still received.
 
+``tx-assoc`` installs a new Tx key, which takes effect immediately.
+
 A rekey is rejected with ``-EINVAL`` if it would change the PSP device
 or the PSP version of the association. It is rejected with ``-EBUSY``
 if the socket has not completed its initial exchange in both
net/psp/psp_sock.c +51 -6

70 lines not on this page · raw message

Signature · 1 line
2.52.1
#4 lore raw

Re: [PATCH net-next v4 2/5] psp: support tx rekey operation

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you…

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you respin.

Low priority / nit picks for your consideration:

- [Low] In the commit "psp: support tx rekey operation", the documentation and the code disagree.

Pre-existing issues:
- [Low] Retired PSP key material is freed without being zeroized.

--

psp: support tx rekey operation

This commit lets tx-assoc be called on a socket that already has a Tx key. A new psp_assoc is allocated with the same Rx state and the new Tx key, then published to the socket with rcu_assign_pointer(). For now, devices that store Tx keys on the device (SADB) get -EOPNOTSUPP.

Quoted 9 lines
net/psp/psp_sock.c +1 -0
index c1e38845f08c3..d497f41c483e1 100644
@@ -280,6 +280,53 @@ psp_sock_set_tx_key(struct sock *sk, struct psp_dev *psd, struct psp_assoc *pas,
 	return err;
 }
 
+static int

net/psp/psp_sock.c psp_sock_set_tx_key(struct sock *sk, struct psp_dev *psd, struct psp_assoc *pas, · line 293

Quoted 10 lines
net/psp/psp_sock.c +10 -0
+psp_sock_tx_rekey(struct sock *sk, struct psp_dev *psd, struct psp_assoc *pas,
+		  struct psp_key_parsed *key, struct netlink_ext_ack *extack)
+{
+	struct psp_assoc *new;
+	int err;
+
+	if (psp_dev_has_sadb(psd)) {
+		NL_SET_ERR_MSG(extack, "Tx rekey not supported on this device");
+		return -EOPNOTSUPP;
+	}

[Severity: Low]
Should the documentation updated in this patch mention this restriction?

The tx-assoc doc in psp.yaml now says, with no condition:

If the socket already has a Tx association, rekey its Tx direction.

psp.rst says tx-assoc "installs a new Tx key, which takes effect immediately". The only rekey errors it lists are -EINVAL and -EBUSY.

psp_dev_has_sadb() is true for mlx5, which sets
.tx_key_del = mlx5e_psp_assoc_del. So at this commit, a Tx rekey on the only in-tree hardware driver always fails with -EOPNOTSUPP, and the docs never mention that errno.

The next patch in the series, "psp: defer tx key deletions for SADB drivers", removes this check and adds deferred Tx key deletion. After it, the code and the docs agree. The mismatch only exists between these two patches, and the commit message calls it out ("return -EOPNOTSUPP for now").

Quoted 4 lines
net/psp/psp_sock.c +4 -0
+	if (!pas->peer_tx) {
+		NL_SET_ERR_MSG(extack, "Socket PSP state is not fully established");
+		return -EBUSY;
+	}

[ ... ]

Quoted 4 lines
net/psp/psp_sock.c +4 -0
+	memcpy(&new->rx, &pas->rx, sizeof(new->rx));
+
+	err = psp_assoc_set_tx(psd, new, key, extack);
+	if (err) {

net/psp/psp_sock.c psp_sock_set_tx_key(struct sock *sk, struct psp_dev *psd, struct psp_assoc *pas, · line 325

Quoted 10 lines
net/psp/psp_sock.c +10 -0
+		kfree(new);
+		return err;
+	}
+
+	psp_dev_get(new->psd);
+	list_add(&new->assocs_list, &pas->assocs_list);
+	list_move(&pas->assocs_list, &psd->stale_assocs);
+
+	rcu_assign_pointer(sk->psp_assoc, new);
+	psp_assoc_put(pas);

[Severity: Low]
This isn't a bug introduced by this patch, but should the retired key material be wiped before it is freed?

The replaced association still holds the old Tx key in pas->tx and the Rx key in pas->rx. It is released through:

psp_assoc_put()
call_rcu(&pas->rcu, psp_assoc_free_queue)

    psp_assoc_free()
      kfree(pas);

The kfree(new) on the psp_assoc_set_tx() error path also frees an object that already holds a copy of the live Rx key.

Neither path uses kfree_sensitive() or memzero_explicit(), so the keys stay in freed slab memory until that memory is reused. Since a rekey can now happen while the connection stays up, this can repeat many times on one socket.

The same pattern already existed before this patch, in psp_assoc_free() and in the kfree(dummy) in psp_dev_tx_key_add(). Nothing in net/psp zeroizes key material today. Reading these keys would also need a separate kernel memory disclosure bug.

Quoted 3 lines

int psp_sock_assoc_set_tx(struct sock *sk, struct psp_dev *psd,

net/psp/psp_sock.c +0 -0
 			  u32 version, struct psp_key_parsed *key,
 			  struct netlink_ext_ack *extack)

[ ... ]

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261116-psp-v4-0-1a599df2aefa%40gmail.com
author maintainer
#5 lore raw

PATCH v4 3/5 psp: defer tx key deletions for SADB drivers

In reply to Daniel Zahka

Devices that store tx keys in an SADB can hold references to key handles in tx descriptor state. PSP core needs to make sure all of these tx descriptors have been completed before calling psp_dev_tx_key_del(). Before rekeying, this was ensured by skbs holding references to skb->sk, and sk->psp_assoc being cleared only in the socket destructor.

Rekeying introduces a code path where a psp_assoc is detached from its socket and may be freed while the socket is still alive. This means skbs may exist in the driver ring that were rendered into descriptors using that old psp_assoc. We cannot delete the key from the SADB until we know these descriptors have been completed.

After a psp_assoc has all references drained (refcount and rcu), PSP core records the BQL queued count for each active TX queue and starts a descriptor grace period. It then polls the queued and completed byte counts until all data outstanding at the start of the grace period has completed. After that point, any keys queued for deletion before the start of the grace period can be deleted from the SADB.

Make CONFIG_INET_PSP depend on CONFIG_BQL.

Drivers which install Tx keys must meet the requirements in Documentation/networking/psp.rst.

Regarding lock ordering: the order of taking psp_dev::lock before net_device::lock was established in commit 1e6e0cec0dab ("net/mlx5e:
psp: Make PSP steering config dynamic"). SADB drivers must not call psp_dev_unregister() with the netdev instance lock held.

Adding a time based rate limit per socket for tx-assoc to prevent wasting SADB or deferred deletion queue space is possible for future work. For now, users should avoid presenting PSP devices to users they don't trust to abuse this.

---
v3:
- document that Tx descriptors must be completed or discarded before psp_dev_unregister()

v2:
- move grace period mechanism to use bql instead of driver callback.
- allow tx rekey on SADB devices

---
 Documentation/networking/psp.rst |  42 +++++++
 include/net/psp/types.h          |  18 +++
 net/psp/Kconfig                  |   1 +
 net/psp/Makefile                 |   2 +-
 net/psp/psp.h                    |   5 +
 net/psp/psp_deferred_del.c       | 231 +++++++++++++++++++++++++++++++++++++++
 net/psp/psp_main.c               |  22 +++-
 net/psp/psp_sock.c               |  13 ++-
 8 files changed, 325 insertions(+), 9 deletions(-)
Documentation/networking/psp.rst +42 -0
index 43f222b38d3d..ceb1e232317f 100644
@@ -202,6 +202,48 @@ Drivers must use ``psp_skb_get_assoc_rcu()`` to check if PSP Tx offload
 was requested for given skb. On Rx drivers should allocate and populate
 the ``SKB_EXT_PSP`` skb extension, and set the skb->decrypted bit to 1.
 
+Deferred Tx key deletion
+~~~~~~~~~~~~~~~~~~~~~~~~
+
+Drivers which implement ``tx_key_add`` and ``tx_key_del`` may hold key
+references in their Tx rings, so PSP core waits until descriptors
+containing these references are completed before removing the key from
+the underlying device. PSP core uses accounting based on Byte Queue Limits
+(BQL) to wait for a suitable grace period before asking the driver to
+remove the key.
+
+Drivers which implement the Tx key callbacks must meet the following
+requirements:
+
+* The driver must be "ops locked"
+  (see Documentation/networking/netdevices.rst).
+* A PSP skb accepted by ``ndo_start_xmit()`` must remain socket-owned until
+  every Tx descriptor referencing its PSP key has been completed or otherwise
+  made incapable of using the key. The driver must not orphan the skb before
+  that point. Otherwise, the socket destructor may free the Tx key while key
+  references remain in the Tx ring.
+* Every PSP packet accepted by ``ndo_start_xmit()`` must be included in BQL
+  queued bytecount before the function returns.
+* Completion bytecounts must exactly match enqueue bytecounts and preserve
+  queue order. A later packet must not be reported as completed while an earlier
+  packet can still reference its key.
+* Before calling ``dql_reset()`` on a queue, the driver must ensure that all
+  outstanding descriptors containing key references have been completed or
+  discarded. If called under the netdev instance lock, then descriptors can
+  remain outstanding after the reset as long as they are completed or
+  discarded before the instance lock is released.
+* When decreasing ``real_num_tx_queues``, the driver must ensure that every
+  outstanding descriptor on the queues at or above the new Tx queue count
+  has been completed or otherwise made incapable of using its PSP key
+  before the netdev instance lock is released.
+* The BQL state of a queue below ``real_num_tx_queues`` must reflect all
+  bytes completed or be reset after the queue has been quiesced. Failure to
+  do so will stall the grace period algorithm.
+* Before calling ``psp_dev_unregister()``, the driver must ensure that all
+  outstanding Tx descriptors containing key references have been completed
+  or discarded. PSP core deletes all remaining Tx keys during
+  unregistration without waiting for a grace period.
+
 Kernel implementation notes
 ---------------------------
 
include/net/psp/types.h +18 -0
index 9eb89d2d680c..f3e1fe97224e 100644
@@ -6,6 +6,7 @@
 #include <linux/bits.h>
 #include <linux/mutex.h>
 #include <linux/refcount.h>
+#include <linux/workqueue.h>
 #include <net/net_trackers.h>
 
 struct netlink_ext_ack;
@@ -81,6 +82,11 @@ struct psp_assoc_dev {
  *			device key
  * @stale_assocs:	associations which use a rotated out key, or were
  *			superseded by a rekey
+ * @tx_del:		deferred TX key deletion state
+ * @tx_del.active:	TX keys to be deleted after the current grace period
+ * @tx_del.next:	TX keys queued for deletion during current grace period
+ * @tx_del.work:	delayed work item for periodic grace period checking
+ * @tx_del.txq_state:	TX queue state for deferred deletion grace periods
  *
  * @stats:	statistics maintained by the core
  * @stats.rotations:	See stats attr key-rotations
@@ -110,6 +116,13 @@ struct psp_dev {
 	struct list_head prev_assocs;
 	struct list_head stale_assocs;
 
+	struct {
+		struct list_head active;
+		struct list_head next;
+		struct delayed_work work;
+		struct psp_txq_state *txq_state;
+	} tx_del;
+
 	struct {
 		unsigned long rotations;
 		unsigned long stales;
@@ -158,9 +171,14 @@ struct psp_key_parsed {
  * enum psp_assoc_flags - flags of struct psp_assoc
  * @PSP_ASSOC_SKIP_TX_KEY_DEL: Do not delete Tx key from psp_dev. It was
  *	copied to a newer psp_assoc during an Rx rekey.
+ * @PSP_ASSOC_DEFER_TX_KEY_DEL: Send Tx key to psp_dev's deferred deletion
+ *	queue. This psp_assoc was detached from its socket during a Tx rekey
+ *	and requires device descriptor state referencing this key to be
+ *	drained.
  */
 enum psp_assoc_flags {
 	PSP_ASSOC_SKIP_TX_KEY_DEL	= BIT(0),
+	PSP_ASSOC_DEFER_TX_KEY_DEL	= BIT(1),
 };
 
 struct psp_assoc {
net/psp/Kconfig +1 -0
index 84d6b0f25460..36c12493784f 100644
@@ -5,6 +5,7 @@
 config INET_PSP
 	bool "PSP Security Protocol support"
 	depends on INET
+	depends on BQL
 	select SKB_DECRYPTED
 	select SKB_EXTENSIONS
 	select SOCK_VALIDATE_XMIT
net/psp/Makefile +1 -1
index eb5ff3c5bfb2..40decd8fe050 100644
@@ -2,4 +2,4 @@
 
 obj-$(CONFIG_INET_PSP) += psp.o
 
-psp-y := psp_main.o psp_nl.o psp_sock.o psp-nl-gen.o
+psp-y := psp_main.o psp_nl.o psp_sock.o psp_deferred_del.o psp-nl-gen.o
net/psp/psp.h +5 -0
index 92d7b92acaed..0cfc82c6c711 100644
@@ -18,6 +18,11 @@ int psp_dev_check_access(struct psp_dev *psd, struct net *net, bool admin);
 bool psp_has_assoc_dev_in_ns(struct psp_dev *psd, struct net *net);
 int psp_attach_netdev_notifier(void);
 
+int psp_deferred_del_init(struct psp_dev *psd);
+void psp_deferred_del_stop(struct psp_dev *psd);
+void psp_deferred_del_uninit(struct psp_dev *psd, bool unpublished);
+void psp_deferred_del_queue(struct psp_dev *psd, struct psp_assoc *pas);
+
 void psp_nl_notify_dev(struct psp_dev *psd, u32 cmd);
 void psp_nl_notify_disassoc(struct psp_dev *psd, struct net *net);
 
net/psp/psp_deferred_del.c new file +231 -0

231 lines not on this page · raw message

net/psp/psp_main.c +19 -3
index 273b010d2355..e118b8019e7e 100644
@@ -3,8 +3,10 @@
 #include <linux/bitfield.h>
 #include <linux/list.h>
 #include <linux/netdevice.h>
+#include <linux/slab.h>
 #include <linux/xarray.h>
 #include <net/net_namespace.h>
+#include <net/netdev_lock.h>
 #include <net/psp.h>
 #include <net/udp.h>
 
@@ -70,7 +72,8 @@ psp_dev_create(struct net_device *netdev,
 		    !psd_ops->rx_spi_alloc ||
 		    !psd_ops->get_stats ||
 		    (!psd_ops->tx_key_add != !psd_ops->tx_key_del) ||
-		    (psd_caps->assoc_drv_spc && !psd_ops->tx_key_add)))
+		    (psd_caps->assoc_drv_spc && !psd_ops->tx_key_add) ||
+		    (psd_ops->tx_key_add && !netdev_need_ops_lock(netdev))))
 		return ERR_PTR(-EINVAL);
 
 	psd = kzalloc_obj(*psd);
@@ -89,13 +92,16 @@ psp_dev_create(struct net_device *netdev,
 	INIT_LIST_HEAD(&psd->stale_assocs);
 	refcount_set(&psd->refcnt, 1);
 
+	err = psp_deferred_del_init(psd);
+	if (err)
+		goto err_free_psd;
+
 	mutex_lock(&psp_devs_lock);
 	err = xa_alloc_cyclic(&psp_devs, &psd->id, psd, xa_limit_16b,
 			      &last_id, GFP_KERNEL);
 	if (err) {
 		mutex_unlock(&psp_devs_lock);
-		kfree(psd);
-		return ERR_PTR(err);
+		goto err_uninit_deferred_del;
 	}
 	mutex_lock(&psd->lock);
 	mutex_unlock(&psp_devs_lock);
@@ -111,6 +117,12 @@ psp_dev_create(struct net_device *netdev,
 	mutex_unlock(&psd->lock);
 
 	return psd;
+
+err_uninit_deferred_del:
+	psp_deferred_del_uninit(psd, true);
+err_free_psd:
+	kfree(psd);
+	return ERR_PTR(err);
 }
 EXPORT_SYMBOL(psp_dev_create);
 
@@ -133,6 +145,8 @@ void psp_dev_unregister(struct psp_dev *psd)
 	struct psp_assoc_dev *entry, *entry_tmp;
 	struct psp_assoc *pas, *next;
 
+	psp_deferred_del_stop(psd);
+
 	mutex_lock(&psp_devs_lock);
 	mutex_lock(&psd->lock);
 
@@ -145,6 +159,8 @@ void psp_dev_unregister(struct psp_dev *psd)
 	xa_store(&psp_devs, psd->id, NULL, GFP_KERNEL);
 	mutex_unlock(&psp_devs_lock);
 
+	psp_deferred_del_uninit(psd, false);
+
 	list_splice_init(&psd->active_assocs, &psd->prev_assocs);
 	list_splice_init(&psd->prev_assocs, &psd->stale_assocs);
 	list_for_each_entry_safe(pas, next, &psd->stale_assocs, assocs_list) {
net/psp/psp_sock.c +8 -5
index d497f41c483e..48bffe088c79 100644
@@ -114,8 +114,14 @@ static void psp_assoc_free(struct work_struct *work)
 
 	mutex_lock(&psd->lock);
 	if (psp_dev_is_registered(psd)) {
-		if (psp_assoc_needs_tx_key_del(pas))
+		if (psp_assoc_needs_tx_key_del(pas)) {
+			if (pas->flags & PSP_ASSOC_DEFER_TX_KEY_DEL) {
+				psp_deferred_del_queue(psd, pas);
+				mutex_unlock(&psd->lock);
+				return;
+			}
 			psp_dev_tx_key_del(psd, pas);
+		}
 		list_del(&pas->assocs_list);
 	}
 	mutex_unlock(&psd->lock);
@@ -287,10 +293,6 @@ psp_sock_tx_rekey(struct sock *sk, struct psp_dev *psd, struct psp_assoc *pas,
 	struct psp_assoc *new;
 	int err;
 
-	if (psp_dev_has_sadb(psd)) {
-		NL_SET_ERR_MSG(extack, "Tx rekey not supported on this device");
-		return -EOPNOTSUPP;
-	}
 	if (!pas->peer_tx) {
 		NL_SET_ERR_MSG(extack, "Socket PSP state is not fully established");
 		return -EBUSY;
@@ -322,6 +324,7 @@ psp_sock_tx_rekey(struct sock *sk, struct psp_dev *psd, struct psp_assoc *pas,
 	list_move(&pas->assocs_list, &psd->stale_assocs);
 
 	rcu_assign_pointer(sk->psp_assoc, new);
+	pas->flags |= PSP_ASSOC_DEFER_TX_KEY_DEL;
 	psp_assoc_put(pas);
 
 	return 0;
Signature · 1 line
2.52.1
#6 lore raw

Re: [PATCH net-next v4 3/5] psp: defer tx key deletions for SADB drivers

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider.

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider.

Critical: 0 · High: 0 · Medium: 2 · Low: 2

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [Medium] The new PSP_ASSOC_DEFER_TX_KEY_DEL path in psp_assoc_free() (net/psp/psp_sock.c:118-121) gives up its only psd reference before…
- [Medium] Removing the SADB check in psp_sock_tx_rekey() lets any non- admin user who can reach the PSP device rekey one established TCP…
- [Low] The commit message never says that this patch turns on Tx rekey for SADB devices.
- [Low] The patch adds a lock-context rule for SADB drivers that only the commit message states: they must not call psp_dev_unregister() with…

--

psp: defer tx key deletions for SADB drivers

This commit adds a deferred deletion queue for Tx keys on SADB devices. A key detached by a Tx rekey is removed from the device only after a BQL-based descriptor grace period, which a delayed work item checks by snapshotting per-queue num_queued and polling num_completed. It also makes INET_PSP depend on BQL, requires ops-locked netdevs for SADB drivers, and drops the check that rejected Tx rekey on SADB devices.

Quoted 5 lines
Documentation/networking/psp.rst +0 -0
index 43f222b38d3d4..ceb1e232317fc 100644
@@ -202,6 +202,48 @@ Drivers must use ``psp_skb_get_assoc_rcu()`` to check if PSP Tx offload

[ ... ]

Documentation/networking/psp.rst Drivers must use ``psp_skb_get_assoc_rcu()`` to check if PSP Tx offload · line 245

Quoted 4 lines
Documentation/networking/psp.rst +4 -0
+* Before calling ``psp_dev_unregister()``, the driver must ensure that all
+  outstanding Tx descriptors containing key references have been completed
+  or discarded. PSP core deletes all remaining Tx keys during
+  unregistration without waiting for a grace period.

[Severity: Low]
Should this list also say that psp_dev_unregister() must not be called with the netdev instance lock held? The commit message states that rule. It is not in this list or in the psp_dev_unregister() kernel-doc, and nothing asserts it.

psp_dev_unregister() now starts with:

psp_dev_unregister()
psp_deferred_del_stop()

    disable_delayed_work_sync(&psd->tx_del.work)

and psp_deferred_del_work() takes the locks in this order:

	mutex_lock(&psd->lock);
	netdev_lock(psd->main_netdev);

Suppose a driver calls psp_dev_unregister() while holding main_netdev->lock, and the work is blocked in netdev_lock(). Wouldn't disable_delayed_work_sync() then wait forever?

Even with the work idle, the later mutex_lock(&psd->lock) in psp_dev_unregister() would run under the netdev lock. That inverts the lock order the work uses.

mlx5 complies today, because mlx5e_nic_disable() drops the netdev lock before mlx5e_psp_unregister().

Could the rule go in this list with the other requirements? Something like lockdep_assert_not_held(&psd->main_netdev->lock) in psp_dev_unregister() would also match the ops-lock WARN_ON check in psp_dev_create().

[ ... ]

Quoted 5 lines
net/psp/psp_sock.c +0 -0
index d497f41c483e1..48bffe088c79b 100644

net/psp/psp_sock.c static void psp_assoc_free(struct work_struct *work) · line 122

Quoted 10 lines
net/psp/psp_sock.c +6 -1
@@ -114,8 +114,14 @@ static void psp_assoc_free(struct work_struct *work)
 
 	mutex_lock(&psd->lock);
 	if (psp_dev_is_registered(psd)) {
-		if (psp_assoc_needs_tx_key_del(pas))
+		if (psp_assoc_needs_tx_key_del(pas)) {
+			if (pas->flags & PSP_ASSOC_DEFER_TX_KEY_DEL) {
+				psp_deferred_del_queue(psd, pas);
+				mutex_unlock(&psd->lock);
+				return;
+			}

[Severity: Medium]
Once pas is on psd->tx_del.next, its psd reference belongs to the deferred queue. This path keeps no reference of its own across mutex_unlock(&psd->lock). Can psd be torn down while this thread is still inside mutex_unlock()?

Documentation/locking/mutex-design.rst says mutex_unlock() may access the mutex after releasing ownership, so the caller has to keep the mutex alive until it returns. When there is a waiter, __mutex_unlock_slowpath() releases ownership and then still takes lock->wait_lock and calls debug_mutex_unlock(lock).

A possible sequence:

CPU1 (psp_assoc_free work) CPU2 (psp_dev_unregister)
psp_deferred_del_queue(psd, pas)
mutex_unlock(&psd->lock) mutex_lock(&psd->lock) succeeds
still in slowpath psp_deferred_del_uninit()

                                     psp_dev_put(psd)
                                   mutex_unlock(&psd->lock)
                                   psp_dev_put(psd)
                                     psp_dev_free()
                                       mutex_destroy(&psd->lock)
                                       kfree_rcu(psd, rcu)

debug_mutex_unlock(lock)

In the current tree, guard(preempt)() in __mutex_unlock_slowpath() and kfree_rcu() keep the memory valid. Under CONFIG_DEBUG_MUTEXES, though, mutex_destroy() clears lock->magic, so DEBUG_LOCKS_WARN_ON(lock->magic != lock) can fire.

The old non-deferred path only called psp_dev_put(psd) after mutex_unlock(). Would it work to take psp_dev_get(psd) before queueing and call psp_dev_put(psd) after the unlock? Another option is for the deferred queue to take its own reference.

[ ... ]

net/psp/psp_sock.c psp_sock_tx_rekey(struct sock *sk, struct psp_dev *psd, struct psp_assoc *pas, · line 293

Quoted 8 lines
net/psp/psp_sock.c +0 -4
@@ -287,10 +293,6 @@ psp_sock_tx_rekey(struct sock *sk, struct psp_dev *psd, struct psp_assoc *pas,
 	struct psp_assoc *new;
 	int err;
 
-	if (psp_dev_has_sadb(psd)) {
-		NL_SET_ERR_MSG(extack, "Tx rekey not supported on this device");
-		return -EOPNOTSUPP;
-	}

[Severity: Low]
Removing this check turns on Tx rekey for SADB devices, but the commit message doesn't say so. The subject is "defer tx key deletions for SADB drivers". The only explicit mention, "allow tx rekey on SADB devices", is in the v2 changelog below the --- line, so it won't be in the applied commit.

The body also says:

"Rekeying introduces a code path where a psp_assoc is detached from its socket and may be freed while the socket is still alive."

That reads as though the path was already reachable on SADB devices, but this patch is what makes it reachable.

mlx5 is the only in-tree SADB driver: mlx5_psp_ops sets tx_key_add and tx_key_del. With no driver changes, PSP_CMD_TX_ASSOC on an established mlx5 socket used to return -EOPNOTSUPP and now installs a new SADB key.

Could the commit message state this behavior change directly, and say whether mlx5 was checked against the new psp.rst driver requirements?

[Severity: Medium]
With this check gone, can a non-admin user use up the device SADB by rekeying one socket in a loop?

PSP_CMD_TX_ASSOC has no GENL_ADMIN_PERM, and psp_assoc_device_get_locked() calls psp_dev_check_access(psd, net, false). Each rekey goes through:

psp_sock_tx_rekey()
psp_assoc_set_tx()

    psp_dev_tx_key_add()
      mlx5e_psp_assoc_add()

The old assoc is then flagged PSP_ASSOC_DEFER_TX_KEY_DEL. After RCU, psp_deferred_del_queue() appends it to psd->tx_del.next with no count or cap:

	list_move_tail(&pas->assocs_list, &psd->tx_del.next);
	schedule_delayed_work(&psd->tx_del.work, 0);

psp_deferred_del_work() frees keys only after a full BQL grace period, polled every PSP_TX_GRACE_POLL_MS (1000 ms). Keys queued while a period is active wait for the next one. If any queue below real_num_tx_queues stops completing BQL bytes, the list keeps growing until psp_dev_unregister().

Before this patch, each socket used at most one SADB Tx entry. Now one socket can hold about rekey rate times (RCU grace period plus 1-2 s) entries. The SADB is a hardware resource shared across namespaces, so tx_key_add could start failing for other users. The pas allocation is charged via GFP_KERNEL_ACCOUNT, but SADB capacity is not.

The commit message acknowledges the missing rate limit and suggests not exposing PSP devices to untrusted users. However, devices in init_net are reachable by all of its users, and there is no knob to restrict tx-assoc.

Would it make sense to add a per-socket or per-device bound on outstanding deferred keys in this change?

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261116-psp-v4-0-1a599df2aefa%40gmail.com
author maintainer
#7 lore raw

Re: [PATCH net-next v4 3/5] psp: defer tx key deletions for SADB drivers

Quoted 113 lines · netdev-bot+sashiko

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider.

Critical: 0 · High: 0 · Medium: 2 · Low: 2

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [Medium] The new PSP_ASSOC_DEFER_TX_KEY_DEL path in psp_assoc_free() (net/psp/psp_sock.c:118-121) gives up its only psd reference before…
- [Medium] Removing the SADB check in psp_sock_tx_rekey() lets any non- admin user who can reach the PSP device rekey one established TCP…
- [Low] The commit message never says that this patch turns on Tx rekey for SADB devices.
- [Low] The patch adds a lock-context rule for SADB drivers that only the commit message states: they must not call psp_dev_unregister() with…

--

psp: defer tx key deletions for SADB drivers

This commit adds a deferred deletion queue for Tx keys on SADB devices. A key detached by a Tx rekey is removed from the device only after a BQL-based descriptor grace period, which a delayed work item checks by snapshotting per-queue num_queued and polling num_completed. It also makes INET_PSP depend on BQL, requires ops-locked netdevs for SADB drivers, and drops the check that rejected Tx rekey on SADB devices.

Quoted 5 lines
Documentation/networking/psp.rst +0 -0
index 43f222b38d3d4..ceb1e232317fc 100644
@@ -202,6 +202,48 @@ Drivers must use ``psp_skb_get_assoc_rcu()`` to check if PSP Tx offload

[ ... ]

Documentation/networking/psp.rst Drivers must use ``psp_skb_get_assoc_rcu()`` to check if PSP Tx offload · line 245

Quoted 4 lines
Documentation/networking/psp.rst +4 -0
+* Before calling ``psp_dev_unregister()``, the driver must ensure that all
+  outstanding Tx descriptors containing key references have been completed
+  or discarded. PSP core deletes all remaining Tx keys during
+  unregistration without waiting for a grace period.

[Severity: Low]
Should this list also say that psp_dev_unregister() must not be called with the netdev instance lock held? The commit message states that rule. It is not in this list or in the psp_dev_unregister() kernel-doc, and nothing asserts it.

psp_dev_unregister() now starts with:

psp_dev_unregister()
psp_deferred_del_stop()

    disable_delayed_work_sync(&psd->tx_del.work)

and psp_deferred_del_work() takes the locks in this order:

	mutex_lock(&psd->lock);
	netdev_lock(psd->main_netdev);

Suppose a driver calls psp_dev_unregister() while holding main_netdev->lock, and the work is blocked in netdev_lock(). Wouldn't disable_delayed_work_sync() then wait forever?

Even with the work idle, the later mutex_lock(&psd->lock) in psp_dev_unregister() would run under the netdev lock. That inverts the lock order the work uses.

mlx5 complies today, because mlx5e_nic_disable() drops the netdev lock before mlx5e_psp_unregister().

Could the rule go in this list with the other requirements? Something like lockdep_assert_not_held(&psd->main_netdev->lock) in psp_dev_unregister() would also match the ops-lock WARN_ON check in psp_dev_create().

[ ... ]

Quoted 5 lines
net/psp/psp_sock.c +0 -0
index d497f41c483e1..48bffe088c79b 100644

net/psp/psp_sock.c static void psp_assoc_free(struct work_struct *work) · line 122

Quoted 10 lines
net/psp/psp_sock.c +6 -1
@@ -114,8 +114,14 @@ static void psp_assoc_free(struct work_struct *work)
 
 	mutex_lock(&psd->lock);
 	if (psp_dev_is_registered(psd)) {
-		if (psp_assoc_needs_tx_key_del(pas))
+		if (psp_assoc_needs_tx_key_del(pas)) {
+			if (pas->flags & PSP_ASSOC_DEFER_TX_KEY_DEL) {
+				psp_deferred_del_queue(psd, pas);
+				mutex_unlock(&psd->lock);
+				return;
+			}

[Severity: Medium]
Once pas is on psd->tx_del.next, its psd reference belongs to the deferred queue. This path keeps no reference of its own across mutex_unlock(&psd->lock). Can psd be torn down while this thread is still inside mutex_unlock()?

Documentation/locking/mutex-design.rst says mutex_unlock() may access the mutex after releasing ownership, so the caller has to keep the mutex alive until it returns. When there is a waiter, __mutex_unlock_slowpath() releases ownership and then still takes lock->wait_lock and calls debug_mutex_unlock(lock).

A possible sequence:

CPU1 (psp_assoc_free work) CPU2 (psp_dev_unregister)
psp_deferred_del_queue(psd, pas)
mutex_unlock(&psd->lock) mutex_lock(&psd->lock) succeeds
still in slowpath psp_deferred_del_uninit()

Quoted 8 lines
                                     psp_dev_put(psd)
                                   mutex_unlock(&psd->lock)
                                   psp_dev_put(psd)
                                     psp_dev_free()
                                       mutex_destroy(&psd->lock)
                                       kfree_rcu(psd, rcu)

debug_mutex_unlock(lock)

Ah TIL. I was a bit naive that mutex_unlock() can still be running while the next waiter enters the critical section.

pw-bot: cr

author maintainer
#8 lore raw

PATCH v4 4/5 selftests: drv-net: psp: factor out psp connection setup

In reply to Daniel Zahka

Lift out connection setup and PSP assoc uapi code in psp.py and responder, so that the key exchange sequence can be used in other test cases that start with a key exchange, but might choose to perform additional tx/rx assoc calls afterwards.

---
v4:
- drop closing the data socket on conn_setup_psp() failure; preexisting and not needed by the series

v3:
- take key lengths from the kernel's rx-assoc reply instead of a per-version table
- close the data socket in psp_responder if conn_setup_psp() fails

---
 tools/testing/selftests/drivers/net/psp.py         | 14 ++++-
 .../testing/selftests/drivers/net/psp_responder.c  | 73 ++++++++++++++--------
 2 files changed, 59 insertions(+), 28 deletions(-)
tools/testing/selftests/drivers/net/psp.py +11 -3
index c114d2245135..ce0ab6666603 100755
@@ -467,10 +467,11 @@ def assoc_twice(cfg):
             ksft_eq(len(tx), 0)
 
 
-def _data_basic_send(cfg, version, ipver):
-    """ Test basic data send """
-    _init_psp_dev(cfg)
+def _establish_psp_conn(cfg, version, ipver=None):
+    """Establish a PSP connection and return after key exchange
 
+    Requires _init_psp_dev() to have been called first.
+    """
     # Version 0 is required by spec, don't let it skip
     if version:
         name = cfg.pspnl.consts["version"].entries_by_val[version].name
@@ -495,7 +496,14 @@ def _data_basic_send(cfg, version, ipver):
                         "version": version,
                         "tx-key": tx,
                         "sock-fd": s.fileno()})
+    return s
+
+
+def _data_basic_send(cfg, version, ipver):
+    """ Test basic data send """
+    _init_psp_dev(cfg)
 
+    s = _establish_psp_conn(cfg, version, ipver)
     data_len = _send_careful(cfg, s, 100)
     _check_data_rx(cfg, data_len)
     _req_echo(cfg, s)
tools/testing/selftests/drivers/net/psp_responder.c +48 -25

103 lines not on this page · raw message

Signature · 1 line
2.52.1
author maintainer
#9 lore raw

PATCH v4 5/5 selftests: drv-net: psp: add rekey tests

In reply to Daniel Zahka

Add testcases for rekeying psp connections.

Tests include coverage for different cases where rx-assoc and tx-assoc should fail based on mismatched psp version and psp state.

Add rpc endpoints for tx-assoc, rx-assoc, and key-rotate netlink calls to the psp_responder.

---
v4:
- reuse _recv_careful() and _req_echo() now in net-next instead of redefining them

v3:
- drop test for rx rekey rejected without a device key rotation
- fail fast in _recv_careful() if the peer closes the connection
- in the basic rekey tests, run traffic across a rotation before the rekey, and rotate again after it to verify the new key is in use
- drop unneeded key rotation from rekey_rx_version_mismatch()
- carry the key length in the responder's assoc message instead of deriving it from the version

v2:
- add tests for rekeys rejected due to psp state and version mismatch
- add test for rx rekey rejected without a device key rotation
- add rx-assoc, tx-assoc, and key-rotate rpcs to psp_responder

---
 tools/testing/selftests/drivers/net/psp.py         | 237 ++++++++++++++++++++-
 .../testing/selftests/drivers/net/psp_responder.c  | 119 +++++++++++
 2 files changed, 353 insertions(+), 3 deletions(-)
tools/testing/selftests/drivers/net/psp.py +234 -3
index ce0ab6666603..bd0283f9c9c0 100755
@@ -28,6 +28,10 @@ from lib.py import ip
 TCP_ULP = 31
 
 
+_PSP_MAX_KEY_LEN = 32
+_PSP_ASSOC_MSG = f'!IBB2x{_PSP_MAX_KEY_LEN}s'
+
+
 def _get_outq(s):
     one = b'\0' * 4
     outq = fcntl.ioctl(s.fileno(), termios.TIOCOUTQ, one)
@@ -80,6 +84,33 @@ def _close_psp_conn(cfg, s):
     _close_conn(cfg, s)
 
 
+def _recv_all(s, target):
+    data = b''
+    while len(data) < target:
+        chunk = s.recv(target - len(data))
+        if not chunk:
+            raise KsftFailEx(f"peer closed after {len(data)} of {target} bytes")
+        data += chunk
+    return data
+
+
+def _remote_rx_assoc(cfg):
+    _send_with_ack(cfg, b'rx assoc\0')
+    msg = _recv_all(cfg.comm_sock, struct.calcsize(_PSP_ASSOC_MSG))
+    spi, version, key_len, key = struct.unpack(_PSP_ASSOC_MSG, msg)
+    return version, {'spi': spi, 'key': key[:key_len]}
+
+
+def _remote_tx_assoc(cfg, version, rx):
+    msg = struct.pack(_PSP_ASSOC_MSG, rx['spi'], version, len(rx['key']),
+                      rx['key'])
+    _send_with_ack(cfg, b'tx assoc\0' + msg)
+
+
+def _remote_key_rotate(cfg):
+    _send_with_ack(cfg, b'key rotate\0')
+
+
 def _spi_xchg(s, rx):
     s.send(struct.pack('I', rx['spi']) + rx['key'])
     tx = s.recv(4 + len(rx['key']))
@@ -126,7 +157,10 @@ def _recv_careful(s, target, timeout=2):
     end = time.monotonic() + timeout
     while time.monotonic() < end:
         try:
-            data += s.recv(target - len(data), socket.MSG_DONTWAIT)
+            chunk = s.recv(target - len(data), socket.MSG_DONTWAIT)
+            if not chunk:
+                raise KsftFailEx(f"peer closed after {len(data)} of {target} bytes")
+            data += chunk
             if len(data) == target:
                 return data
         except BlockingIOError:
@@ -150,6 +184,21 @@ def _check_data_outq(s, exp_len, force_wait=False):
     ksft_eq(outq, exp_len)
 
 
+def _psp_txrx(cfg, s, rounds, sent=0):
+    """Send data both ways, and return the total bytes sent to the peer"""
+    sent += _send_careful(cfg, s, rounds)
+    _check_data_rx(cfg, sent)
+    _req_echo(cfg, s)
+    return sent
+
+
+def _require_version(cfg, version):
+    """Skip the test unless the device supports the given PSP version"""
+    name = cfg.pspnl.consts["version"].entries_by_val[version].name
+    if name not in cfg.psp_info['psp-versions-cap']:
+        raise KsftSkipEx("PSP version not supported", name)
+
+
 def _get_stat(cfg, key):
     return cfg.pspnl.get_stats({'dev-id': cfg.psp_dev_id})[key]
 
@@ -510,6 +559,186 @@ def _data_basic_send(cfg, version, ipver):
     _close_psp_conn(cfg, s)
 
 
+def _rekey_rx(cfg, s, version, sent):
+    """Rekey the Rx direction, running traffic after each step"""
+    rx_assoc = cfg.pspnl.rx_assoc({"version": version,
+                                   "dev-id": cfg.psp_dev_id,
+                                   "sock-fd": s.fileno()})
+    sent = _psp_txrx(cfg, s, 1, sent)
+
+    _remote_tx_assoc(cfg, version, rx_assoc['rx-key'])
+    return _psp_txrx(cfg, s, 1, sent)
+
+
+def _rekey_tx(cfg, s, sent):
+    """Rekey the Tx direction, running traffic after each step"""
+    version, tx = _remote_rx_assoc(cfg)
+    sent = _psp_txrx(cfg, s, 1, sent)
+
+    cfg.pspnl.tx_assoc({"dev-id": cfg.psp_dev_id,
+                        "version": version,
+                        "tx-key": tx,
+                        "sock-fd": s.fileno()})
+    return _psp_txrx(cfg, s, 1, sent)
+
+
+def rekey_rx_incomplete(cfg):
+    """Test rejecting Rx rekey until the PSP connection is established"""
+    psp_ver = 0
+    _init_psp_dev(cfg)
+
+    with _make_lo_conn() as s:
+        assoc = cfg.pspnl.rx_assoc({"version": psp_ver,
+                                    "dev-id": cfg.psp_dev_id,
+                                    "sock-fd": s.fileno()})
+
+        # Reject rekey before Tx state is configured.
+        with ksft_raises(NlError) as cm:
+            cfg.pspnl.rx_assoc({"version": psp_ver,
+                                "dev-id": cfg.psp_dev_id,
+                                "sock-fd": s.fileno()})
+        ksft_eq(cm.exception.nl_msg.error, -errno.EBUSY)
+
+        cfg.pspnl.tx_assoc({"dev-id": cfg.psp_dev_id,
+                            "version": psp_ver,
+                            "tx-key": assoc['rx-key'],
+                            "sock-fd": s.fileno()})
+
+        # Reject rekey until authenticated PSP traffic has been received.
+        with ksft_raises(NlError) as cm:
+            cfg.pspnl.rx_assoc({"version": psp_ver,
+                                "dev-id": cfg.psp_dev_id,
+                                "sock-fd": s.fileno()})
+        ksft_eq(cm.exception.nl_msg.error, -errno.EBUSY)
+
+
+def rekey_tx_incomplete(cfg):
+    """Test rejecting Tx rekey until the PSP connection is established"""
+    psp_ver = 0
+    _init_psp_dev(cfg)
+
+    with _make_lo_conn() as s:
+        assoc = cfg.pspnl.rx_assoc({"version": psp_ver,
+                                    "dev-id": cfg.psp_dev_id,
+                                    "sock-fd": s.fileno()})
+
+        cfg.pspnl.tx_assoc({"dev-id": cfg.psp_dev_id,
+                            "version": psp_ver,
+                            "tx-key": assoc['rx-key'],
+                            "sock-fd": s.fileno()})
+
+        # Reject rekey until authenticated PSP traffic has been received.
+        with ksft_raises(NlError) as cm:
+            cfg.pspnl.tx_assoc({"dev-id": cfg.psp_dev_id,
+                                "version": psp_ver,
+                                "tx-key": assoc['rx-key'],
+                                "sock-fd": s.fileno()})
+        ksft_eq(cm.exception.nl_msg.error, -errno.EBUSY)
+
+
+def rekey_rx_version_mismatch(cfg):
+    """Test rejecting an Rx rekey whose version does not match socket state"""
+    _init_psp_dev(cfg)
+    _require_version(cfg, 1)
+
+    s = _establish_psp_conn(cfg, 0)
+    try:
+        _psp_txrx(cfg, s, 1)
+
+        with ksft_raises(NlError) as cm:
+            cfg.pspnl.rx_assoc({"dev-id": cfg.psp_dev_id,
+                                "version": 1,
+                                "sock-fd": s.fileno()})
+        ksft_eq(cm.exception.nl_msg.error, -errno.EINVAL)
+    finally:
+        _close_psp_conn(cfg, s)
+
+
+def rekey_tx_version_mismatch(cfg):
+    """Test rejecting a Tx rekey whose version does not match socket state"""
+    _init_psp_dev(cfg)
+    _require_version(cfg, 1)
+
+    s = _establish_psp_conn(cfg, 0)
+    try:
+        _psp_txrx(cfg, s, 1)
+
+        with ksft_raises(NlError) as cm:
+            cfg.pspnl.tx_assoc({"dev-id": cfg.psp_dev_id,
+                                "version": 1,
+                                "tx-key": {'spi': 0x12345678,
+                                           'key': b'\xa5' * 32},
+                                "sock-fd": s.fileno()})
+        ksft_eq(cm.exception.nl_msg.error, -errno.EINVAL)
+    finally:
+        _close_psp_conn(cfg, s)
+
+
+def _get_psp_ver_variants():
+    for ver in range(4):
+        yield KsftNamedVariant(f"v{ver}", ver)
+
+
+@ksft_variants(_get_psp_ver_variants())
+def rekey_rx_basic(cfg, version):
+    """Test rekeying the Rx key of an established connection"""
+    _init_psp_dev(cfg)
+
+    s = _establish_psp_conn(cfg, version)
+    try:
+        data_len = _psp_txrx(cfg, s, 1)
+        cfg.pspnl.key_rotate({"id": cfg.psp_dev_id})
+        data_len = _psp_txrx(cfg, s, 1, data_len)
+        data_len = _rekey_rx(cfg, s, version, data_len)
+        cfg.pspnl.key_rotate({"id": cfg.psp_dev_id})
+        _psp_txrx(cfg, s, 1, data_len)
+    finally:
+        _close_psp_conn(cfg, s)
+
+
+@ksft_variants(_get_psp_ver_variants())
+def rekey_tx_basic(cfg, version):
+    """Test rekeying the Tx key of an established connection"""
+    _init_psp_dev(cfg)
+
+    s = _establish_psp_conn(cfg, version)
+    try:
+        data_len = _psp_txrx(cfg, s, 1)
+        _remote_key_rotate(cfg)
+        data_len = _psp_txrx(cfg, s, 1, data_len)
+        data_len = _rekey_tx(cfg, s, data_len)
+        _remote_key_rotate(cfg)
+        _psp_txrx(cfg, s, 1, data_len)
+    finally:
+        _close_psp_conn(cfg, s)
+
+
+@ksft_variants(_get_psp_ver_variants())
+def rekey_both_sides(cfg, version):
+    """Test rekeying both directions"""
+    _init_psp_dev(cfg)
+
+    s = _establish_psp_conn(cfg, version)
+    try:
+        data_len = _psp_txrx(cfg, s, 10)
+
+        cfg.pspnl.key_rotate({"id": cfg.psp_dev_id})
+        _remote_key_rotate(cfg)
+
+        # first, rx then tx
+        data_len = _rekey_rx(cfg, s, version, data_len)
+        data_len = _rekey_tx(cfg, s, data_len)
+
+        cfg.pspnl.key_rotate({"id": cfg.psp_dev_id})
+        _remote_key_rotate(cfg)
+
+        # now, tx then rx
+        data_len = _rekey_tx(cfg, s, data_len)
+        _rekey_rx(cfg, s, version, data_len)
+    finally:
+        _close_psp_conn(cfg, s)
+
+
 def __bad_xfer_do(cfg, s, tx, version='hdr0-aes-gcm-128'):
     # Make sure we accept the ACK for the SPI before we seal with the bad assoc
     _check_data_outq(s, 0)
@@ -1203,7 +1432,8 @@ def main() -> None:
                                                           cfg.comm_port),
                                                          timeout=1)
 
-                cases = [data_basic_send, data_mss_adjust]
+                cases = [data_basic_send, data_mss_adjust,
+                         rekey_rx_basic, rekey_tx_basic, rekey_both_sides]
 
                 if has_cont:
                     cases += [
@@ -1219,7 +1449,8 @@ def main() -> None:
                     ]
 
                 ksft_run(cases=cases, globs=globals(),
-                         case_pfx={"dev_", "data_", "assoc_", "removal_"},
+                         case_pfx={"dev_", "data_", "assoc_", "rekey_",
+                                   "removal_"},
                          args=(cfg, ))
 
                 cfg.comm_sock.send(b"exit\0")
tools/testing/selftests/drivers/net/psp_responder.c +119 -0

161 lines not on this page · raw message

Signature · 1 line
2.52.1
#10 lore raw

Re: [PATCH net-next v4 5/5] selftests: drv-net: psp: add rekey tests

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you…

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you respin.

Low priority / nit picks for your consideration:

- [Low] The patch changes the existing shared helper _recv_careful() in tools/testing/selftests/drivers/net/psp.py, and the commit message…

--

selftests: drv-net: psp: add rekey tests

This commit adds selftests for rekeying PSP connections. The tests cover rx-assoc and tx-assoc rejections caused by a PSP version mismatch or by the PSP state. It also adds rx-assoc, tx-assoc and key-rotate RPC endpoints to psp_responder.

Quoted 4 lines
tools/testing/selftests/drivers/net/psp.py +0 -0
index ce0ab66666030..bd0283f9c9c02 100755

[ ... ]

tools/testing/selftests/drivers/net/psp.py def _recv_careful(s, target, timeout=2): · line 166

Quoted 12 lines
tools/testing/selftests/drivers/net/psp.py +4 -1
@@ -126,7 +157,10 @@ def _recv_careful(s, target, timeout=2):
     end = time.monotonic() + timeout
     while time.monotonic() < end:
         try:
-            data += s.recv(target - len(data), socket.MSG_DONTWAIT)
+            chunk = s.recv(target - len(data), socket.MSG_DONTWAIT)
+            if not chunk:
+                raise KsftFailEx(f"peer closed after {len(data)} of {target} bytes")
+            data += chunk
             if len(data) == target:
                 return data
         except BlockingIOError:

[Severity: Low]
This isn't a bug, but this hunk changes _recv_careful(), a helper that existed before this patch. The commit message doesn't mention it.

Existing tests reach it through _req_echo(), for example _data_basic_send(). So the change affects more than the new rekey tests:

    _req_echo()
        ksft_eq(_recv_careful(s, 5), b'echo\0')

Before this patch, when the peer closed the socket, recv() returned b''. The loop then spun without sleeping until the 2 second timeout and failed with "short read, got N of M bytes".

With this patch it fails at once with "peer closed after N of M bytes".

The only place this is described is the v3 note "fail fast in _recv_careful() if the peer closes the connection". That note is below the --- line, so it won't be kept in git history.

Could the commit message say that _recv_careful() now fails fast when the peer closes the connection? Alternatively, this could go in a separate patch.

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261116-psp-v4-0-1a599df2aefa%40gmail.com