Fuzzers and static checkers might not detect when tcp_sk() is used with
a non tcp_sock structure.
This kind of mistake already happened a few times with MPTCP, when
wrongly using TCP-specific helpers with mptcp_sock pointers. On the
other hand, there are many 'tcp_xxx()' helpers that are taking a 'struct
sock' as arguments, and some of them are only looking at fields from
'struct sock', and nothing from 'struct tcp_sock'. It is then tempting
to use them with a 'struct mptcp_sock'.
So a new simple check is done when CONFIG_DEBUG_NET is enabled. tcp_sk()
is then used as an inlined function, like before commit e9d9da91548b
("tcp: preserve const qualifier in tcp_sk()").
Signed-off-by: Matthieu Baerts (NGI0) <matttbe@kernel.org>
---
include/linux/tcp.h | 9 +++++++++
1 file changed, 9 insertions(+)
diff --git a/include/linux/tcp.h b/include/linux/tcp.h
index 89b290d8c8dc..11413d0e3c1c 100644
--- a/include/linux/tcp.h
+++ b/include/linux/tcp.h
@@ -525,7 +525,16 @@ enum tsq_flags {
TCPF_ACK_DEFERRED = BIT(TCP_ACK_DEFERRED),
};
+#ifdef CONFIG_DEBUG_NET
+static inline struct tcp_sock *tcp_sk(const struct sock *sk)
+{
+ WARN_ON(sk->sk_protocol != IPPROTO_TCP);
+
+ return (struct tcp_sock *)sk;
+}
+#else
#define tcp_sk(ptr) container_of_const(ptr, struct tcp_sock, inet_conn.icsk_inet.sk)
+#endif
/* Variant of tcp_sk() upgrading a const sock to a read/write tcp socket.
* Used in context of (lockless) tcp listeners.
--
2.43.0