Skip to contentSkip to conversation

Introduce a BPF helper to generate SYN cookies

PATCH Superseded Petar Penkov 7 participants 15 messages Jul 23, 2019 – Jul 24, 2019

Subsystems (7)

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

cover Introduce a BPF helper to generate SYN cookies

From: Petar Penkov <[email protected]>

This patch series introduces a BPF helper function that allows generating SYN cookies from BPF. Currently, this helper is enabled at both the TC hook and the XDP hook.

The first two patches in the series add/modify several TCP helper functions to allow for SKB-less operation, as is the case at the XDP hook.

The third patch introduces the bpf_tcp_gen_syncookie helper function which generates a SYN cookie for either XDP or TC programs. The return value of this function contains both the MSS value, encoded in the cookie, and the cookie itself.

The last three patches sync tools/ and add a test.

Changes since RFC:
1/ Cookie is returned in host order at Alexei's suggestion
2/ If cookies are not enabled via a sysctl, the helper function returns
-ENOENT instead of -EINVAL at Lorenz's suggestion
3/ Fixed documentation to properly reflect that MSS is 16 bits at
Lorenz's suggestion
4/ BPF helper requires TCP length to match ->doff field, rather than to simply
be no more than 20 bytes at Eric and Alexei's suggestion
5/ Packet type is looked up from the packet version field, rather than from the
socket. v4 packets are rejected on v6-only sockets but should work with dual stack listeners at Eric's suggestion
6/ Removed unnecessary net argument from helper function in patch 2 at
Lorenz's suggestion
7/ Changed test to only pass MSS option so we can convince the verifier that the
memory access is not out of bounds

Note that 7/ below illustrates the verifier might need to be extended to allow passing a variable tcph->doff to the helper function like below:

__u32 thlen = tcph->doff * 4;
if (thlen < sizeof(*tcph))

	return;

__s64 cookie = bpf_tcp_gen_syncookie(sk, ipv4h, 20, tcph, thlen);

Petar Penkov (6):
tcp: tcp_syn_flood_action read port from socket
tcp: add skb-less helpers to retrieve SYN cookie
bpf: add bpf_tcp_gen_syncookie helper
bpf: sync bpf.h to tools/
selftests/bpf: bpf_tcp_gen_syncookie->bpf_helpers selftests/bpf: add test for bpf_tcp_gen_syncookie

 include/net/tcp.h                             | 11 +++
 include/uapi/linux/bpf.h                      | 30 ++++++-
 net/core/filter.c                             | 73 ++++++++++++++++
 net/ipv4/tcp_input.c                          | 84 +++++++++++++++++--
 net/ipv4/tcp_ipv4.c                           |  8 ++
 net/ipv6/tcp_ipv6.c                           |  8 ++
 tools/include/uapi/linux/bpf.h                | 37 +++++++-
 tools/testing/selftests/bpf/bpf_helpers.h     |  3 +
 .../bpf/progs/test_tcp_check_syncookie_kern.c | 48 +++++++++--
 .../selftests/bpf/test_tcp_check_syncookie.sh |  3 +
 .../bpf/test_tcp_check_syncookie_user.c       | 61 ++++++++++++--
 11 files changed, 344 insertions(+), 22 deletions(-)
Signature · 1 line
2.22.0.657.g960e92d24f-goog
#1 lore raw

PATCH 1/6 tcp: tcp_syn_flood_action read port from socket

From: Petar Penkov <[email protected]>

This allows us to call this function before an SKB has been allocated.

---
 net/ipv4/tcp_input.c | 8 +++-----
 1 file changed, 3 insertions(+), 5 deletions(-)
net/ipv4/tcp_input.c +3 -5
index c21e8a22fb3b..8892df6de1d4 100644
@@ -6422,9 +6422,7 @@ EXPORT_SYMBOL(inet_reqsk_alloc);
 /*
  * Return true if a syncookie should be sent
  */
-static bool tcp_syn_flood_action(const struct sock *sk,
-				 const struct sk_buff *skb,
-				 const char *proto)
+static bool tcp_syn_flood_action(const struct sock *sk, const char *proto)
 {
 	struct request_sock_queue *queue = &inet_csk(sk)->icsk_accept_queue;
 	const char *msg = "Dropping request";
@@ -6444,7 +6442,7 @@ static bool tcp_syn_flood_action(const struct sock *sk,
 	    net->ipv4.sysctl_tcp_syncookies != 2 &&
 	    xchg(&queue->synflood_warned, 1) == 0)
 		net_info_ratelimited("%s: Possible SYN flooding on port %d. %s.  Check SNMP counters.\n",
-				     proto, ntohs(tcp_hdr(skb)->dest), msg);
+				     proto, sk->sk_num, msg);
 
 	return want_cookie;
 }
@@ -6487,7 +6485,7 @@ int tcp_conn_request(struct request_sock_ops *rsk_ops,
 	 */
 	if ((net->ipv4.sysctl_tcp_syncookies == 2 ||
 	     inet_csk_reqsk_queue_is_full(sk)) && !isn) {
-		want_cookie = tcp_syn_flood_action(sk, skb, rsk_ops->slab_name);
+		want_cookie = tcp_syn_flood_action(sk, rsk_ops->slab_name);
 		if (!want_cookie)
 			goto drop;
 	}
Signature · 1 line
2.22.0.657.g960e92d24f-goog
#2 lore raw

PATCH 2/6 tcp: add skb-less helpers to retrieve SYN cookie

In reply to Petar Penkov

From: Petar Penkov <[email protected]>

This patch allows generation of a SYN cookie before an SKB has been allocated, as is the case at XDP.

---
 include/net/tcp.h    | 11 +++++++
 net/ipv4/tcp_input.c | 76 ++++++++++++++++++++++++++++++++++++++++++++
 net/ipv4/tcp_ipv4.c  |  8 +++++
 net/ipv6/tcp_ipv6.c  |  8 +++++
 4 files changed, 103 insertions(+)
include/net/tcp.h +11 -0
index cca3c59b98bf..a128e22c0d5d 100644
@@ -414,6 +414,17 @@ void tcp_parse_options(const struct net *net, const struct sk_buff *skb,
 		       int estab, struct tcp_fastopen_cookie *foc);
 const u8 *tcp_parse_md5sig_option(const struct tcphdr *th);
 
+/*
+ *	BPF SKB-less helpers
+ */
+u16 tcp_v4_get_syncookie(struct sock *sk, struct iphdr *iph,
+			 struct tcphdr *tch, u32 *cookie);
+u16 tcp_v6_get_syncookie(struct sock *sk, struct ipv6hdr *iph,
+			 struct tcphdr *tch, u32 *cookie);
+u16 tcp_get_syncookie(struct request_sock_ops *rsk_ops,
+		      const struct tcp_request_sock_ops *af_ops,
+		      struct sock *sk, void *iph, struct tcphdr *tch,
+		      u32 *cookie);
 /*
  *	TCP v4 functions exported for the inet6 API
  */
net/ipv4/tcp_input.c +76 -0

88 lines not on this page · raw message

net/ipv4/tcp_ipv4.c +8 -0
index d57641cb3477..0e06e59784bd 100644
@@ -1515,6 +1515,14 @@ static struct sock *tcp_v4_cookie_check(struct sock *sk, struct sk_buff *skb)
 	return sk;
 }
 
+u16 tcp_v4_get_syncookie(struct sock *sk, struct iphdr *iph,
+			 struct tcphdr *tch, u32 *cookie)
+{
+	return tcp_get_syncookie(&tcp_request_sock_ops,
+				 &tcp_request_sock_ipv4_ops, sk, iph, tch,
+				 cookie);
+}
+
 /* The socket must have it's spinlock held when we get
  * here, unless it is a TCP_LISTEN socket.
  *
net/ipv6/tcp_ipv6.c +8 -0
index 5da069e91cac..102f68c3152d 100644
@@ -1063,6 +1063,14 @@ static struct sock *tcp_v6_cookie_check(struct sock *sk, struct sk_buff *skb)
 	return sk;
 }
 
+u16 tcp_v6_get_syncookie(struct sock *sk, struct ipv6hdr *iph,
+			 struct tcphdr *tch, u32 *cookie)
+{
+	return tcp_get_syncookie(&tcp6_request_sock_ops,
+				 &tcp_request_sock_ipv6_ops, sk, iph, tch,
+				 cookie);
+}
+
 static int tcp_v6_conn_request(struct sock *sk, struct sk_buff *skb)
 {
 	if (skb->protocol == htons(ETH_P_IP))
Signature · 1 line
2.22.0.657.g960e92d24f-goog
#3 lore raw

Re: [bpf-next 2/6] tcp: add skb-less helpers to retrieve SYN cookie

Thank you for the patch! Yet something to improve:

Hi Petar,

Thank you for the patch! Yet something to improve:

[auto build test ERROR on bpf-next/master]

url:    https://github.com/0day-ci/linux/commits/Petar-Penkov/Introduce-a-BPF-helper-to-generate-SYN-cookies/20190723-235628
base:   https://kernel.googlesource.com/pub/scm/linux/kernel/git/bpf/bpf-next.git master
config: x86_64-randconfig-e004-201929 (attached as .config)
compiler: gcc-7 (Debian 7.4.0-10) 7.4.0
reproduce:
        # save the attached .config to linux build tree
        make ARCH=x86_64 

If you fix the issue, kindly add following tag

All errors (new ones prefixed by >>):

ld: net/ipv4/tcp_input.o: in function `tcp_get_syncookie':

>> net/ipv4/tcp_input.c:6538: undefined reference to `__cookie_v6_init_sequence'

vim +6538 net/ipv4/tcp_input.c

6509
6510 u16 tcp_get_syncookie(struct request_sock_ops *rsk_ops,

  6511			      const struct tcp_request_sock_ops *af_ops,
  6512			      struct sock *sk, void *iph, struct tcphdr *th,
  6513			      u32 *cookie)
  6514	{
  6515		u16 mss = 0;
  6516	#ifdef CONFIG_SYN_COOKIES
  6517		bool is_v4 = rsk_ops->family == AF_INET;
  6518		struct tcp_sock *tp = tcp_sk(sk);
  6519	
  6520		if (sock_net(sk)->ipv4.sysctl_tcp_syncookies != 2 &&
  6521		    !inet_csk_reqsk_queue_is_full(sk))
  6522			return 0;
  6523	
  6524		if (!tcp_syn_flood_action(sk, rsk_ops->slab_name))
  6525			return 0;
  6526	
  6527		if (sk_acceptq_is_full(sk)) {
  6528			NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
  6529			return 0;
  6530		}
  6531	
  6532		mss = tcp_parse_mss_option(th, tp->rx_opt.user_mss);
  6533		if (!mss)
  6534			mss = af_ops->mss_clamp;
  6535	
  6536		tcp_synq_overflow(sk);
  6537		*cookie = is_v4 ? __cookie_v4_init_sequence(iph, th, &mss)
> 6538				: __cookie_v6_init_sequence(iph, th, &mss);

6539 #endif
6540 return mss;
6541 }
6542

---
0-DAY kernel test infrastructure Open Source Technology Center
https://lists.01.org/pipermail/kbuild-all Intel Corporation

#4 lore raw

Re: [bpf-next 2/6] tcp: add skb-less helpers to retrieve SYN cookie

In reply to Petar Penkov
Thank you for the patch! Yet something to improve:

Hi Petar,

Thank you for the patch! Yet something to improve:

[auto build test ERROR on bpf-next/master]

url:    https://github.com/0day-ci/linux/commits/Petar-Penkov/Introduce-a-BPF-helper-to-generate-SYN-cookies/20190723-235628
base:   https://kernel.googlesource.com/pub/scm/linux/kernel/git/bpf/bpf-next.git master
config: parisc-c8000_defconfig (attached as .config)
compiler: hppa64-linux-gcc (GCC) 7.4.0

reproduce:
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross chmod +x ~/bin/make.cross
# save the attached .config to linux build tree
GCC_VERSION=7.4.0 make.cross ARCH=parisc

If you fix the issue, kindly add following tag

All errors (new ones prefixed by >>):

hppa64-linux-ld: arch/parisc/kernel/entry.o(.text.hot+0x22b8): cannot reach preempt_schedule_irq
arch/parisc/kernel/entry.o: In function `intr_do_preempt':
(.text.hot+0x22b8): relocation truncated to fit: R_PARISC_PCREL22F against symbol preempt_schedule_irq' defined in .sched.text section in kernel/sched/core.o net/ipv4/tcp_input.o: In function .LC240':

>> (.data.rel.ro+0x718): undefined reference to `__cookie_v6_init_sequence'

---
0-DAY kernel test infrastructure Open Source Technology Center
https://lists.01.org/pipermail/kbuild-all Intel Corporation

#5 lore raw

PATCH 3/6 bpf: add bpf_tcp_gen_syncookie helper

In reply to Petar Penkov

From: Petar Penkov <[email protected]>

This helper function allows BPF programs to try to generate SYN cookies, given a reference to a listener socket. The function works from XDP and with an skb context since bpf_skc_lookup_tcp can lookup a socket in both cases.

---
 include/uapi/linux/bpf.h | 30 ++++++++++++++++-
 net/core/filter.c        | 73 ++++++++++++++++++++++++++++++++++++++++
 2 files changed, 102 insertions(+), 1 deletion(-)
include/uapi/linux/bpf.h +29 -1
index 6f68438aa4ed..20baee7b2219 100644
@@ -2713,6 +2713,33 @@ union bpf_attr {
  *		**-EPERM** if no permission to send the *sig*.
  *
  *		**-EAGAIN** if bpf program can try again.
+ *
+ * s64 bpf_tcp_gen_syncookie(struct bpf_sock *sk, void *iph, u32 iph_len, struct tcphdr *th, u32 th_len)
+ *	Description
+ *		Try to issue a SYN cookie for the packet with corresponding
+ *		IP/TCP headers, *iph* and *th*, on the listening socket in *sk*.
+ *
+ *		*iph* points to the start of the IPv4 or IPv6 header, while
+ *		*iph_len* contains **sizeof**\ (**struct iphdr**) or
+ *		**sizeof**\ (**struct ip6hdr**).
+ *
+ *		*th* points to the start of the TCP header, while *th_len*
+ *		contains the length of the TCP header.
+ *
+ *	Return
+ *		On success, lower 32 bits hold the generated SYN cookie in
+ *		followed by 16 bits which hold the MSS value for that cookie,
+ *		and the top 16 bits are unused.
+ *
+ *		On failure, the returned value is one of the following:
+ *
+ *		**-EINVAL** SYN cookie cannot be issued due to error
+ *
+ *		**-ENOENT** SYN cookie should not be issued (no SYN flood)
+ *
+ *		**-ENOTSUPP** kernel configuration does not enable SYN cookies
+ *
+ *		**-EPROTONOSUPPORT** IP packet version is not 4 or 6
  */
 #define __BPF_FUNC_MAPPER(FN)		\
 	FN(unspec),			\
@@ -2824,7 +2851,8 @@ union bpf_attr {
 	FN(strtoul),			\
 	FN(sk_storage_get),		\
 	FN(sk_storage_delete),		\
-	FN(send_signal),
+	FN(send_signal),		\
+	FN(tcp_gen_syncookie),
 
 /* integer value in 'imm' field of BPF_CALL instruction selects which helper
  * function eBPF program intends to call
net/core/filter.c +73 -0

91 lines not on this page · raw message

Signature · 1 line
2.22.0.657.g960e92d24f-goog
#6 lore raw

Re: [bpf-next 3/6] bpf: add bpf_tcp_gen_syncookie helper

Quoted 47 lines · Petar Penkov

From: Petar Penkov <[email protected]>

This helper function allows BPF programs to try to generate SYN cookies, given a reference to a listener socket. The function works from XDP and with an skb context since bpf_skc_lookup_tcp can lookup a socket in both cases.

---
 include/uapi/linux/bpf.h | 30 ++++++++++++++++-
 net/core/filter.c        | 73 ++++++++++++++++++++++++++++++++++++++++
 2 files changed, 102 insertions(+), 1 deletion(-)
include/uapi/linux/bpf.h +25 -0
index 6f68438aa4ed..20baee7b2219 100644
@@ -2713,6 +2713,33 @@ union bpf_attr {
  *		**-EPERM** if no permission to send the *sig*.
  *
  *		**-EAGAIN** if bpf program can try again.
+ *
+ * s64 bpf_tcp_gen_syncookie(struct bpf_sock *sk, void *iph, u32 iph_len, struct tcphdr *th, u32 th_len)
+ *	Description
+ *		Try to issue a SYN cookie for the packet with corresponding
+ *		IP/TCP headers, *iph* and *th*, on the listening socket in *sk*.
+ *
+ *		*iph* points to the start of the IPv4 or IPv6 header, while
+ *		*iph_len* contains **sizeof**\ (**struct iphdr**) or
+ *		**sizeof**\ (**struct ip6hdr**).
+ *
+ *		*th* points to the start of the TCP header, while *th_len*
+ *		contains the length of the TCP header.
+ *
+ *	Return
+ *		On success, lower 32 bits hold the generated SYN cookie in
+ *		followed by 16 bits which hold the MSS value for that cookie,
+ *		and the top 16 bits are unused.
+ *
+ *		On failure, the returned value is one of the following:
+ *
+ *		**-EINVAL** SYN cookie cannot be issued due to error
+ *
+ *		**-ENOENT** SYN cookie should not be issued (no SYN flood)
+ *
+ *		**-ENOTSUPP** kernel configuration does not enable SYN
Quoted 1 line

cookies

nit: This should be EOPNOTSUPP - the other one is for NFS...

Quoted 67 lines

+ *
+ * **-EPROTONOSUPPORT** IP packet version is not 4 or 6
*/
#define __BPF_FUNC_MAPPER(FN) \

include/uapi/linux/bpf.h +2 -1
 	FN(unspec),			\
@@ -2824,7 +2851,8 @@ union bpf_attr {
 	FN(strtoul),			\
 	FN(sk_storage_get),		\
 	FN(sk_storage_delete),		\
-	FN(send_signal),
+	FN(send_signal),		\
+	FN(tcp_gen_syncookie),
 
 /* integer value in 'imm' field of BPF_CALL instruction selects which helper
  * function eBPF program intends to call
net/core/filter.c +44 -0
index 47f6386fb17a..92114271eff6 100644
@@ -5850,6 +5850,75 @@ static const struct bpf_func_proto bpf_tcp_check_syncookie_proto = {
 	.arg5_type	= ARG_CONST_SIZE,
 };
 
+BPF_CALL_5(bpf_tcp_gen_syncookie, struct sock *, sk, void *, iph, u32, iph_len,
+	   struct tcphdr *, th, u32, th_len)
+{
+#ifdef CONFIG_SYN_COOKIES
+	u32 cookie;
+	u16 mss;
+
+	if (unlikely(th_len < sizeof(*th) || th_len != th->doff * 4))
+		return -EINVAL;
+
+	if (sk->sk_protocol != IPPROTO_TCP || sk->sk_state != TCP_LISTEN)
+		return -EINVAL;
+
+	if (!sock_net(sk)->ipv4.sysctl_tcp_syncookies)
+		return -ENOENT;
+
+	if (!th->syn || th->ack || th->fin || th->rst)
+		return -EINVAL;
+
+	if (unlikely(iph_len < sizeof(struct iphdr)))
+		return -EINVAL;
+
+	/* Both struct iphdr and struct ipv6hdr have the version field at the
+	 * same offset so we can cast to the shorter header (struct iphdr).
+	 */
+	switch (((struct iphdr *)iph)->version) {
+	case 4:
+		if (sk->sk_family == AF_INET6 && sk->sk_ipv6only)
+			return -EINVAL;
+
+		mss = tcp_v4_get_syncookie(sk, iph, th, &cookie);
+		break;
+
+#if IS_BUILTIN(CONFIG_IPV6)
+	case 6:
+		if (unlikely(iph_len < sizeof(struct ipv6hdr)))
+			return -EINVAL;
+
+		if (sk->sk_family != AF_INET6)
+			return -EINVAL;
+
+		mss = tcp_v6_get_syncookie(sk, iph, th, &cookie);
+		break;
+#endif /* CONFIG_IPV6 */

net/core/filter.c static const struct bpf_func_proto bpf_tcp_check_syncookie_proto = { · line 5906

Quoted 10 lines
net/core/filter.c +10 -0
+
+	default:
+		return -EPROTONOSUPPORT;
+	}
+	if (mss <= 0)
+		return -ENOENT;
+
+	return cookie | ((u64)mss << 32);
+#else
+	return -ENOTSUPP;

See above

Quoted 38 lines
net/core/filter.c +19 -0
+#endif /* CONFIG_SYN_COOKIES */
+}
+
+static const struct bpf_func_proto bpf_tcp_gen_syncookie_proto = {
+	.func		= bpf_tcp_gen_syncookie,
+	.gpl_only	= true, /* __cookie_v*_init_sequence() is GPL */
+	.pkt_access	= true,
+	.ret_type	= RET_INTEGER,
+	.arg1_type	= ARG_PTR_TO_SOCK_COMMON,
+	.arg2_type	= ARG_PTR_TO_MEM,
+	.arg3_type	= ARG_CONST_SIZE,
+	.arg4_type	= ARG_PTR_TO_MEM,
+	.arg5_type	= ARG_CONST_SIZE,
+};
+
 #endif /* CONFIG_INET */
 
 bool bpf_helper_changes_pkt_data(void *func)
@@ -6135,6 +6204,8 @@ tc_cls_act_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
 		return &bpf_tcp_check_syncookie_proto;
 	case BPF_FUNC_skb_ecn_set_ce:
 		return &bpf_skb_ecn_set_ce_proto;
+	case BPF_FUNC_tcp_gen_syncookie:
+		return &bpf_tcp_gen_syncookie_proto;
 #endif
 	default:
 		return bpf_base_func_proto(func_id);
@@ -6174,6 +6245,8 @@ xdp_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
 		return &bpf_xdp_skc_lookup_tcp_proto;
 	case BPF_FUNC_tcp_check_syncookie:
 		return &bpf_tcp_check_syncookie_proto;
+	case BPF_FUNC_tcp_gen_syncookie:
+		return &bpf_tcp_gen_syncookie_proto;
 #endif
 	default:
 		return bpf_base_func_proto(func_id);
Signature · 1 line
2.22.0.657.g960e92d24f-goog
#7 lore raw

Re: [bpf-next 3/6] bpf: add bpf_tcp_gen_syncookie helper

Quoted 45 lines · Toke Høiland-Jørgensen
Quoted 42 lines · Petar Penkov

From: Petar Penkov <[email protected]>

This helper function allows BPF programs to try to generate SYN cookies, given a reference to a listener socket. The function works from XDP and with an skb context since bpf_skc_lookup_tcp can lookup a socket in both cases.

---
 include/uapi/linux/bpf.h | 30 ++++++++++++++++-
 net/core/filter.c        | 73 ++++++++++++++++++++++++++++++++++++++++
 2 files changed, 102 insertions(+), 1 deletion(-)
include/uapi/linux/bpf.h +20 -0
index 6f68438aa4ed..20baee7b2219 100644
@@ -2713,6 +2713,33 @@ union bpf_attr {
  *           **-EPERM** if no permission to send the *sig*.
  *
  *           **-EAGAIN** if bpf program can try again.
+ *
+ * s64 bpf_tcp_gen_syncookie(struct bpf_sock *sk, void *iph, u32 iph_len, struct tcphdr *th, u32 th_len)
+ *   Description
+ *           Try to issue a SYN cookie for the packet with corresponding
+ *           IP/TCP headers, *iph* and *th*, on the listening socket in *sk*.
+ *
+ *           *iph* points to the start of the IPv4 or IPv6 header, while
+ *           *iph_len* contains **sizeof**\ (**struct iphdr**) or
+ *           **sizeof**\ (**struct ip6hdr**).
+ *
+ *           *th* points to the start of the TCP header, while *th_len*
+ *           contains the length of the TCP header.
+ *
+ *   Return
+ *           On success, lower 32 bits hold the generated SYN cookie in
+ *           followed by 16 bits which hold the MSS value for that cookie,
+ *           and the top 16 bits are unused.
+ *
+ *           On failure, the returned value is one of the following:
+ *
Quoted 8 lines
Quoted 6 lines
include/uapi/linux/bpf.h +5 -0
+ *           **-EINVAL** SYN cookie cannot be issued due to error
+ *
+ *           **-ENOENT** SYN cookie should not be issued (no SYN flood)
+ *
+ *           **-ENOTSUPP** kernel configuration does not enable SYN

cookies

nit: This should be EOPNOTSUPP - the other one is for NFS...

Will correct this in a v2, thanks for catching that!

Quoted 119 lines
Quoted 68 lines

+ *
+ * **-EPROTONOSUPPORT** IP packet version is not 4 or 6
*/

 #define __BPF_FUNC_MAPPER(FN)                \
      FN(unspec),                     \
include/uapi/linux/bpf.h +2 -1
@@ -2824,7 +2851,8 @@ union bpf_attr {
      FN(strtoul),                    \
      FN(sk_storage_get),             \
      FN(sk_storage_delete),          \
-     FN(send_signal),
+     FN(send_signal),                \
+     FN(tcp_gen_syncookie),
 
 /* integer value in 'imm' field of BPF_CALL instruction selects which helper
  * function eBPF program intends to call
net/core/filter.c +44 -0
index 47f6386fb17a..92114271eff6 100644
@@ -5850,6 +5850,75 @@ static const struct bpf_func_proto bpf_tcp_check_syncookie_proto = {
      .arg5_type      = ARG_CONST_SIZE,
 };
 
+BPF_CALL_5(bpf_tcp_gen_syncookie, struct sock *, sk, void *, iph, u32, iph_len,
+        struct tcphdr *, th, u32, th_len)
+{
+#ifdef CONFIG_SYN_COOKIES
+     u32 cookie;
+     u16 mss;
+
+     if (unlikely(th_len < sizeof(*th) || th_len != th->doff * 4))
+             return -EINVAL;
+
+     if (sk->sk_protocol != IPPROTO_TCP || sk->sk_state != TCP_LISTEN)
+             return -EINVAL;
+
+     if (!sock_net(sk)->ipv4.sysctl_tcp_syncookies)
+             return -ENOENT;
+
+     if (!th->syn || th->ack || th->fin || th->rst)
+             return -EINVAL;
+
+     if (unlikely(iph_len < sizeof(struct iphdr)))
+             return -EINVAL;
+
+     /* Both struct iphdr and struct ipv6hdr have the version field at the
+      * same offset so we can cast to the shorter header (struct iphdr).
+      */
+     switch (((struct iphdr *)iph)->version) {
+     case 4:
+             if (sk->sk_family == AF_INET6 && sk->sk_ipv6only)
+                     return -EINVAL;
+
+             mss = tcp_v4_get_syncookie(sk, iph, th, &cookie);
+             break;
+
+#if IS_BUILTIN(CONFIG_IPV6)
+     case 6:
+             if (unlikely(iph_len < sizeof(struct ipv6hdr)))
+                     return -EINVAL;
+
+             if (sk->sk_family != AF_INET6)
+                     return -EINVAL;
+
+             mss = tcp_v6_get_syncookie(sk, iph, th, &cookie);
+             break;
+#endif /* CONFIG_IPV6 */

net/core/filter.c static const struct bpf_func_proto bpf_tcp_check_syncookie_proto = { · line 5906

Quoted 10 lines
net/core/filter.c +10 -0
+
+     default:
+             return -EPROTONOSUPPORT;
+     }
+     if (mss <= 0)
+             return -ENOENT;
+
+     return cookie | ((u64)mss << 32);
+#else
+     return -ENOTSUPP;

See above

Quoted 38 lines
net/core/filter.c +19 -1
+#endif /* CONFIG_SYN_COOKIES */
+}
+
+static const struct bpf_func_proto bpf_tcp_gen_syncookie_proto = {
+     .func           = bpf_tcp_gen_syncookie,
+     .gpl_only       = true, /* __cookie_v*_init_sequence() is GPL */
+     .pkt_access     = true,
+     .ret_type       = RET_INTEGER,
+     .arg1_type      = ARG_PTR_TO_SOCK_COMMON,
+     .arg2_type      = ARG_PTR_TO_MEM,
+     .arg3_type      = ARG_CONST_SIZE,
+     .arg4_type      = ARG_PTR_TO_MEM,
+     .arg5_type      = ARG_CONST_SIZE,
+};
+
 #endif /* CONFIG_INET */
 
 bool bpf_helper_changes_pkt_data(void *func)
@@ -6135,6 +6204,8 @@ tc_cls_act_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
              return &bpf_tcp_check_syncookie_proto;
      case BPF_FUNC_skb_ecn_set_ce:
              return &bpf_skb_ecn_set_ce_proto;
+     case BPF_FUNC_tcp_gen_syncookie:
+             return &bpf_tcp_gen_syncookie_proto;
 #endif
      default:
              return bpf_base_func_proto(func_id);
@@ -6174,6 +6245,8 @@ xdp_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
              return &bpf_xdp_skc_lookup_tcp_proto;
      case BPF_FUNC_tcp_check_syncookie:
              return &bpf_tcp_check_syncookie_proto;
+     case BPF_FUNC_tcp_gen_syncookie:
+             return &bpf_tcp_gen_syncookie_proto;
 #endif
      default:
              return bpf_base_func_proto(func_id);
--

2.22.0.657.g960e92d24f-goog

#8 lore raw

PATCH 4/6 bpf: sync bpf.h to tools/

In reply to Petar Penkov

From: Petar Penkov <[email protected]>

Sync updated documentation for bpf_redirect_map.

Sync the bpf_tcp_gen_syncookie helper function definition with the one in tools/uapi.

---
 tools/include/uapi/linux/bpf.h | 37 +++++++++++++++++++++++++++++++---
 1 file changed, 34 insertions(+), 3 deletions(-)
tools/include/uapi/linux/bpf.h +34 -3
index f506c68b2612..20baee7b2219 100644
@@ -1571,8 +1571,11 @@ union bpf_attr {
  * 		but this is only implemented for native XDP (with driver
  * 		support) as of this writing).
  *
- * 		All values for *flags* are reserved for future usage, and must
- * 		be left at zero.
+ * 		The lower two bits of *flags* are used as the return code if
+ * 		the map lookup fails. This is so that the return value can be
+ * 		one of the XDP program return codes up to XDP_TX, as chosen by
+ * 		the caller. Any higher bits in the *flags* argument must be
+ * 		unset.
  *
  * 		When used to redirect packets to net devices, this helper
  * 		provides a high performance increase over **bpf_redirect**\ ().
@@ -2710,6 +2713,33 @@ union bpf_attr {
  *		**-EPERM** if no permission to send the *sig*.
  *
  *		**-EAGAIN** if bpf program can try again.
+ *
+ * s64 bpf_tcp_gen_syncookie(struct bpf_sock *sk, void *iph, u32 iph_len, struct tcphdr *th, u32 th_len)
+ *	Description
+ *		Try to issue a SYN cookie for the packet with corresponding
+ *		IP/TCP headers, *iph* and *th*, on the listening socket in *sk*.
+ *
+ *		*iph* points to the start of the IPv4 or IPv6 header, while
+ *		*iph_len* contains **sizeof**\ (**struct iphdr**) or
+ *		**sizeof**\ (**struct ip6hdr**).
+ *
+ *		*th* points to the start of the TCP header, while *th_len*
+ *		contains the length of the TCP header.
+ *
+ *	Return
+ *		On success, lower 32 bits hold the generated SYN cookie in
+ *		followed by 16 bits which hold the MSS value for that cookie,
+ *		and the top 16 bits are unused.
+ *
+ *		On failure, the returned value is one of the following:
+ *
+ *		**-EINVAL** SYN cookie cannot be issued due to error
+ *
+ *		**-ENOENT** SYN cookie should not be issued (no SYN flood)
+ *
+ *		**-ENOTSUPP** kernel configuration does not enable SYN cookies
+ *
+ *		**-EPROTONOSUPPORT** IP packet version is not 4 or 6
  */
 #define __BPF_FUNC_MAPPER(FN)		\
 	FN(unspec),			\
@@ -2821,7 +2851,8 @@ union bpf_attr {
 	FN(strtoul),			\
 	FN(sk_storage_get),		\
 	FN(sk_storage_delete),		\
-	FN(send_signal),
+	FN(send_signal),		\
+	FN(tcp_gen_syncookie),
 
 /* integer value in 'imm' field of BPF_CALL instruction selects which helper
  * function eBPF program intends to call
Signature · 1 line
2.22.0.657.g960e92d24f-goog
#9 lore raw

PATCH 5/6 selftests/bpf: bpf_tcp_gen_syncookie->bpf_helpers

In reply to Petar Penkov

From: Petar Penkov <[email protected]>

Expose bpf_tcp_gen_syncookie to selftests.

---
 tools/testing/selftests/bpf/bpf_helpers.h | 3 +++
 1 file changed, 3 insertions(+)
tools/testing/selftests/bpf/bpf_helpers.h +3 -0
index 5a3d92c8bec8..19f01e967402 100644
@@ -228,6 +228,9 @@ static void *(*bpf_sk_storage_get)(void *map, struct bpf_sock *sk,
 static int (*bpf_sk_storage_delete)(void *map, struct bpf_sock *sk) =
 	(void *)BPF_FUNC_sk_storage_delete;
 static int (*bpf_send_signal)(unsigned sig) = (void *)BPF_FUNC_send_signal;
+static long long (*bpf_tcp_gen_syncookie)(struct bpf_sock *sk, void *ip,
+					  int ip_len, void *tcp, int tcp_len) =
+	(void *) BPF_FUNC_tcp_gen_syncookie;
 
 /* llvm builtin functions that eBPF C program may use to
  * emit BPF_LD_ABS and BPF_LD_IND instructions
Signature · 1 line
2.22.0.657.g960e92d24f-goog
#10 lore raw

PATCH 6/6 selftests/bpf: add test for bpf_tcp_gen_syncookie

In reply to Petar Penkov

From: Petar Penkov <[email protected]>

Modify the existing bpf_tcp_check_syncookie test to also generate a SYN cookie, pass the packet to the kernel, and verify that the two cookies are the same (and both valid). Since cloned SKBs are skipped during generic XDP, this test does not issue a SYN cookie when run in XDP mode. We therefore only check that a valid SYN cookie was issued at the TC hook.

Additionally, verify that the MSS for that SYN cookie is within expected range.

---
 .../bpf/progs/test_tcp_check_syncookie_kern.c | 48 +++++++++++++--
 .../selftests/bpf/test_tcp_check_syncookie.sh |  3 +
 .../bpf/test_tcp_check_syncookie_user.c       | 61 ++++++++++++++++---
 3 files changed, 99 insertions(+), 13 deletions(-)
tools/testing/selftests/bpf/progs/test_tcp_check_syncookie_kern.c +43 -5
index 1ab095bcacd8..d8803dfa8d32 100644
@@ -19,10 +19,29 @@
 struct bpf_map_def SEC("maps") results = {
 	.type = BPF_MAP_TYPE_ARRAY,
 	.key_size = sizeof(__u32),
-	.value_size = sizeof(__u64),
-	.max_entries = 1,
+	.value_size = sizeof(__u32),
+	.max_entries = 3,
 };
 
+static __always_inline __s64 gen_syncookie(void *data_end, struct bpf_sock *sk,
+					   void *iph, __u32 ip_size,
+					   struct tcphdr *tcph)
+{
+	__u32 thlen = tcph->doff * 4;
+
+	if (tcph->syn && !tcph->ack) {
+		// packet should only have an MSS option
+		if (thlen != 24)
+			return 0;
+
+		if ((void *)tcph + thlen > data_end)
+			return 0;
+
+		return bpf_tcp_gen_syncookie(sk, iph, ip_size, tcph, thlen);
+	}
+	return 0;
+}
+
 static __always_inline void check_syncookie(void *ctx, void *data,
 					    void *data_end)
 {
@@ -33,8 +52,10 @@ static __always_inline void check_syncookie(void *ctx, void *data,
 	struct ipv6hdr *ipv6h;
 	struct tcphdr *tcph;
 	int ret;
+	__u32 key_mss = 2;
+	__u32 key_gen = 1;
 	__u32 key = 0;
-	__u64 value = 1;
+	__s64 seq_mss;
 
 	ethh = data;
 	if (ethh + 1 > data_end)
@@ -66,6 +87,9 @@ static __always_inline void check_syncookie(void *ctx, void *data,
 		if (sk->state != BPF_TCP_LISTEN)
 			goto release;
 
+		seq_mss = gen_syncookie(data_end, sk, ipv4h, sizeof(*ipv4h),
+					tcph);
+
 		ret = bpf_tcp_check_syncookie(sk, ipv4h, sizeof(*ipv4h),
 					      tcph, sizeof(*tcph));
 		break;
@@ -95,6 +119,9 @@ static __always_inline void check_syncookie(void *ctx, void *data,
 		if (sk->state != BPF_TCP_LISTEN)
 			goto release;
 
+		seq_mss = gen_syncookie(data_end, sk, ipv6h, sizeof(*ipv6h),
+					tcph);
+
 		ret = bpf_tcp_check_syncookie(sk, ipv6h, sizeof(*ipv6h),
 					      tcph, sizeof(*tcph));
 		break;
@@ -103,8 +130,19 @@ static __always_inline void check_syncookie(void *ctx, void *data,
 		return;
 	}
 
-	if (ret == 0)
-		bpf_map_update_elem(&results, &key, &value, 0);
+	if (seq_mss > 0) {
+		__u32 cookie = (__u32)seq_mss;
+		__u32 mss = seq_mss >> 32;
+
+		bpf_map_update_elem(&results, &key_gen, &cookie, 0);
+		bpf_map_update_elem(&results, &key_mss, &mss, 0);
+	}
+
+	if (ret == 0) {
+		__u32 cookie = bpf_ntohl(tcph->ack_seq) - 1;
+
+		bpf_map_update_elem(&results, &key, &cookie, 0);
+	}
 
 release:
 	bpf_sk_release(sk);
tools/testing/selftests/bpf/test_tcp_check_syncookie.sh +3 -0
index d48e51716d19..9b3617d770a5 100755
@@ -37,6 +37,9 @@ setup()
 	ns1_exec ip link set lo up
 
 	ns1_exec sysctl -w net.ipv4.tcp_syncookies=2
+	ns1_exec sysctl -w net.ipv4.tcp_window_scaling=0
+	ns1_exec sysctl -w net.ipv4.tcp_timestamps=0
+	ns1_exec sysctl -w net.ipv4.tcp_sack=0
 
 	wait_for_ip 127.0.0.1
 	wait_for_ip ::1
tools/testing/selftests/bpf/test_tcp_check_syncookie_user.c +53 -8

121 lines not on this page · raw message

Signature · 1 line
2.22.0.657.g960e92d24f-goog
#11 lore raw

Re: [bpf-next 6/6] selftests/bpf: add test for bpf_tcp_gen_syncookie

tools/testing/selftests/bpf/progs/test_tcp_check_syncookie_kern.c line 35

Quoted 10 lines · Petar Penkov
tools/testing/selftests/bpf/progs/test_tcp_check_syncookie_kern.c +10 -0
+static __always_inline __s64 gen_syncookie(void *data_end, struct bpf_sock *sk,
+                                          void *iph, __u32 ip_size,
+                                          struct tcphdr *tcph)
+{
+       __u32 thlen = tcph->doff * 4;
+
+       if (tcph->syn && !tcph->ack) {
+               // packet should only have an MSS option
+               if (thlen != 24)
+                       return 0;

Just for my own understanding: without this the verifier complains since thlen is not a known value, even though it is in bounds due to the check below?

Quoted 9 lines
tools/testing/selftests/bpf/progs/test_tcp_check_syncookie_kern.c +9 -0
+
+               if ((void *)tcph + thlen > data_end)
+                       return 0;
+
+               return bpf_tcp_gen_syncookie(sk, iph, ip_size, tcph, thlen);
+       }
+       return 0;
+}
+
Signature · 4 lines
Lorenz Bauer  |  Systems Engineer
6th Floor, County Hall/The Riverside Building, SE1 7PB, UK

www.cloudflare.com
#12 lore raw

Re: [bpf-next 6/6] selftests/bpf: add test for bpf_tcp_gen_syncookie

Quoted 14 lines · Lorenz Bauer

tools/testing/selftests/bpf/progs/test_tcp_check_syncookie_kern.c line 35

Quoted 10 lines · Petar Penkov
tools/testing/selftests/bpf/progs/test_tcp_check_syncookie_kern.c +10 -0
+static __always_inline __s64 gen_syncookie(void *data_end, struct bpf_sock *sk,
+                                          void *iph, __u32 ip_size,
+                                          struct tcphdr *tcph)
+{
+       __u32 thlen = tcph->doff * 4;
+
+       if (tcph->syn && !tcph->ack) {
+               // packet should only have an MSS option
+               if (thlen != 24)
+                       return 0;

Just for my own understanding: without this the verifier complains since thlen is not a known value, even though it is in bounds due to the check below?

the verifier understands only constant part of the packet pointer. Without additional 'if' above the statement:
if ((void *)tcph + thlen > data_end)
will add variables length 'thlen' to pkt pointer which will become another pkt pointer (with different id).
That pointer would need 'pkt + const_range > data_end' to have valid access.

We hit this issue in the past when folks wanted to use bpf_csum_diff() helper with variable size.
It's possible to extend the verifier to support that but it's intrusive, since variable part would need to passed around to a bunch of check* functions. I think it's tricky, but doable. Looking forward to patches :)

Quoted 15 lines
Quoted 9 lines
tools/testing/selftests/bpf/progs/test_tcp_check_syncookie_kern.c +9 -0
+
+               if ((void *)tcph + thlen > data_end)
+                       return 0;
+
+               return bpf_tcp_gen_syncookie(sk, iph, ip_size, tcph, thlen);
+       }
+       return 0;
+}
+
Signature · 4 lines
Lorenz Bauer  |  Systems Engineer
6th Floor, County Hall/The Riverside Building, SE1 7PB, UK

www.cloudflare.com
#13 lore raw
In reply to Petar Penkov
Quoted 6 lines · Petar Penkov

From: Petar Penkov <[email protected]>

This patch series introduces a BPF helper function that allows generating SYN cookies from BPF. Currently, this helper is enabled at both the TC hook and the XDP hook.

Please provide performance numbers ?

We want to know if we increase performance under synflood, or if it does not change, or even decrease ;)

Thanks.

Reviewed-by on the v1 series
#14 lore raw
In reply to Petar Penkov
Quoted 10 lines · Petar Penkov

From: Petar Penkov <[email protected]>

This patch series introduces a BPF helper function that allows generating SYN cookies from BPF. Currently, this helper is enabled at both the TC hook and the XDP hook.

The first two patches in the series add/modify several TCP helper functions to allow for SKB-less operation, as is the case at the XDP hook.

Quoted 6 lines

The third patch introduces the bpf_tcp_gen_syncookie helper function which generates a SYN cookie for either XDP or TC programs. The return value of this function contains both the MSS value, encoded in the cookie, and the cookie itself.

The last three patches sync tools/ and add a test.

Signature · 4 lines
Lorenz Bauer  |  Systems Engineer
6th Floor, County Hall/The Riverside Building, SE1 7PB, UK

www.cloudflare.com