Skip to contentSkip to conversation

New BPF helpers to accelerate synproxy

PATCH Superseded Maxim Mikityanskiy 2 participants 22 messages May 3, 2022 – May 19, 2022

Subsystems (9)

v9 of 10 Superseded Latest is v10 →

lore
Share & tools
lore
#0 lore raw

v9 cover New BPF helpers to accelerate synproxy

The first patch of this series is a documentation fix.

The second patch allows BPF helpers to accept memory regions of fixed size without doing runtime size checks.

The two next patches add new functionality that allows XDP to accelerate iptables synproxy.

v1 of this series [1] used to include a patch that exposed conntrack lookup to BPF using stable helpers. It was superseded by series [2] by Kumar Kartikeya Dwivedi, which implements this functionality using unstable helpers.

The third patch adds new helpers to issue and check SYN cookies without binding to a socket, which is useful in the synproxy scenario.

The fourth patch adds a selftest, which includes an XDP program and a userspace control application. The XDP program uses socketless SYN cookie helpers and queries conntrack status instead of socket status. The userspace control application allows to tune parameters of the XDP program. This program also serves as a minimal example of usage of the new functionality.

The last patch exposes the new helpers to TC BPF.

The draft of the new functionality was presented on Netdev 0x15 [3].

v2 changes:

Split into two series, submitted bugfixes to bpf, dropped the conntrack patches, implemented the timestamp cookie in BPF using bpf_loop, dropped the timestamp cookie patch.

v3 changes:

Moved some patches from bpf to bpf-next, dropped the patch that changed error codes, split the new helpers into IPv4/IPv6, added verifier functionality to accept memory regions of fixed size.

v4 changes:

Converted the selftest to the test_progs runner. Replaced some deprecated functions in xdp_synproxy userspace helper.

v5 changes:

Fixed a bug in the selftest. Added questionable functionality to support new helpers in TC BPF, added selftests for it.

v6 changes:

Wrap the new helpers themselves into #ifdef CONFIG_SYN_COOKIES, replaced fclose with pclose and fixed the MSS for IPv6 in the selftest.

v7 changes:

Fixed the off-by-one error in indices, changed the section name to "xdp", added missing kernel config options to vmtest in CI.

v8 changes:

Properly rebased, dropped the first patch (the same change was applied by someone else), updated the cover letter.

v9 changes:

Fixed selftests for no_alu32.

[1]: https://lore.kernel.org/bpf/[email protected]/t/
[2]: https://lore.kernel.org/bpf/[email protected]/
[3]: https://netdevconf.info/0x15/session.html?Accelerating-synproxy-with-XDP

Maxim Mikityanskiy (5):
bpf: Fix documentation of th_len in bpf_tcp_{gen,check}_syncookie
bpf: Allow helpers to accept pointers with a fixed size
bpf: Add helpers to issue and check SYN cookies in XDP
bpf: Add selftests for raw syncookie helpers
bpf: Allow the new syncookie helpers to work with SKBs

 include/linux/bpf.h                           |  10 +
 include/net/tcp.h                             |   1 +
 include/uapi/linux/bpf.h                      |  88 +-
 kernel/bpf/verifier.c                         |  26 +-
 net/core/filter.c                             | 128 +++
 net/ipv4/tcp_input.c                          |   3 +-
 scripts/bpf_doc.py                            |   4 +
 tools/include/uapi/linux/bpf.h                |  88 +-
 tools/testing/selftests/bpf/.gitignore        |   1 +
 tools/testing/selftests/bpf/Makefile          |   5 +-
 .../selftests/bpf/prog_tests/xdp_synproxy.c   | 144 +++
 .../selftests/bpf/progs/xdp_synproxy_kern.c   | 819 ++++++++++++++++++
 tools/testing/selftests/bpf/xdp_synproxy.c    | 466 ++++++++++
 13 files changed, 1761 insertions(+), 22 deletions(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c
 create mode 100644 tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c
 create mode 100644 tools/testing/selftests/bpf/xdp_synproxy.c
Signature · 1 line
2.30.2
#1 lore raw

PATCH v9 1/5 bpf: Fix documentation of th_len in bpf_tcp_{gen,check}_syncookie

bpf_tcp_gen_syncookie expects the full length of the TCP header (with all options), and bpf_tcp_check_syncookie accepts lengths bigger than sizeof(struct tcphdr). Fix the documentation that says these lengths should be exactly sizeof(struct tcphdr).

While at it, fix a typo in the name of struct ipv6hdr.

---
 include/uapi/linux/bpf.h       | 10 ++++++----
 tools/include/uapi/linux/bpf.h | 10 ++++++----
 2 files changed, 12 insertions(+), 8 deletions(-)
include/uapi/linux/bpf.h +6 -4
index 444fe6f1cf35..4dd9e34f2a60 100644
@@ -3587,10 +3587,11 @@ union bpf_attr {
  *
  * 		*iph* points to the start of the IPv4 or IPv6 header, while
  * 		*iph_len* contains **sizeof**\ (**struct iphdr**) or
- * 		**sizeof**\ (**struct ip6hdr**).
+ * 		**sizeof**\ (**struct ipv6hdr**).
  *
  * 		*th* points to the start of the TCP header, while *th_len*
- * 		contains **sizeof**\ (**struct tcphdr**).
+ *		contains the length of the TCP header (at least
+ *		**sizeof**\ (**struct tcphdr**)).
  * 	Return
  * 		0 if *iph* and *th* are a valid SYN cookie ACK, or a negative
  * 		error otherwise.
@@ -3773,10 +3774,11 @@ union bpf_attr {
  *
  *		*iph* points to the start of the IPv4 or IPv6 header, while
  *		*iph_len* contains **sizeof**\ (**struct iphdr**) or
- *		**sizeof**\ (**struct ip6hdr**).
+ *		**sizeof**\ (**struct ipv6hdr**).
  *
  *		*th* points to the start of the TCP header, while *th_len*
- *		contains the length of the TCP header.
+ *		contains the length of the TCP header with options (at least
+ *		**sizeof**\ (**struct tcphdr**)).
  *	Return
  *		On success, lower 32 bits hold the generated SYN cookie in
  *		followed by 16 bits which hold the MSS value for that cookie,
tools/include/uapi/linux/bpf.h +6 -4
index 444fe6f1cf35..4dd9e34f2a60 100644
@@ -3587,10 +3587,11 @@ union bpf_attr {
  *
  * 		*iph* points to the start of the IPv4 or IPv6 header, while
  * 		*iph_len* contains **sizeof**\ (**struct iphdr**) or
- * 		**sizeof**\ (**struct ip6hdr**).
+ * 		**sizeof**\ (**struct ipv6hdr**).
  *
  * 		*th* points to the start of the TCP header, while *th_len*
- * 		contains **sizeof**\ (**struct tcphdr**).
+ *		contains the length of the TCP header (at least
+ *		**sizeof**\ (**struct tcphdr**)).
  * 	Return
  * 		0 if *iph* and *th* are a valid SYN cookie ACK, or a negative
  * 		error otherwise.
@@ -3773,10 +3774,11 @@ union bpf_attr {
  *
  *		*iph* points to the start of the IPv4 or IPv6 header, while
  *		*iph_len* contains **sizeof**\ (**struct iphdr**) or
- *		**sizeof**\ (**struct ip6hdr**).
+ *		**sizeof**\ (**struct ipv6hdr**).
  *
  *		*th* points to the start of the TCP header, while *th_len*
- *		contains the length of the TCP header.
+ *		contains the length of the TCP header with options (at least
+ *		**sizeof**\ (**struct tcphdr**)).
  *	Return
  *		On success, lower 32 bits hold the generated SYN cookie in
  *		followed by 16 bits which hold the MSS value for that cookie,
Signature · 1 line
2.30.2
#2 lore raw

PATCH v9 2/5 bpf: Allow helpers to accept pointers with a fixed size

In reply to Maxim Mikityanskiy

Before this commit, the BPF verifier required ARG_PTR_TO_MEM arguments to be followed by ARG_CONST_SIZE holding the size of the memory region. The helpers had to check that size in runtime.

There are cases where the size expected by a helper is a compile-time constant. Checking it in runtime is an unnecessary overhead and waste of BPF registers.

This commit allows helpers to accept ARG_PTR_TO_MEM arguments without the corresponding ARG_CONST_SIZE, given that they define the memory region size in struct bpf_func_proto.

---
 include/linux/bpf.h   | 10 ++++++++++
 kernel/bpf/verifier.c | 26 +++++++++++++++-----------
 2 files changed, 25 insertions(+), 11 deletions(-)
include/linux/bpf.h +10 -0
index be94833d390a..255ae3652225 100644
@@ -514,6 +514,16 @@ struct bpf_func_proto {
 		};
 		u32 *arg_btf_id[5];
 	};
+	union {
+		struct {
+			size_t arg1_size;
+			size_t arg2_size;
+			size_t arg3_size;
+			size_t arg4_size;
+			size_t arg5_size;
+		};
+		size_t arg_size[5];
+	};
 	int *ret_btf_id; /* return value btf_id */
 	bool (*allowed)(const struct bpf_prog *prog);
 };
kernel/bpf/verifier.c +15 -11
index 813f6ee80419..57fcf2e82f30 100644
@@ -5843,6 +5843,11 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
 		 * next is_mem_size argument below.
 		 */
 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
+		if (fn->arg_size[arg]) {
+			err = check_helper_mem_access(env, regno,
+						      fn->arg_size[arg], false,
+						      meta);
+		}
 	} else if (arg_type_is_mem_size(arg_type)) {
 		bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
 
@@ -6186,13 +6191,12 @@ static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
 	return count <= 1;
 }
 
-static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
-				    enum bpf_arg_type arg_next)
+static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
 {
-	return (arg_type_is_mem_ptr(arg_curr) &&
-	        !arg_type_is_mem_size(arg_next)) ||
-	       (!arg_type_is_mem_ptr(arg_curr) &&
-		arg_type_is_mem_size(arg_next));
+	if (arg_type_is_mem_ptr(fn->arg_type[arg]))
+		return arg_type_is_mem_size(fn->arg_type[arg + 1]) ==
+			!!fn->arg_size[arg];
+	return arg_type_is_mem_size(fn->arg_type[arg + 1]) || fn->arg_size[arg];
 }
 
 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
@@ -6203,11 +6207,11 @@ static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
 	 * helper function specification.
 	 */
 	if (arg_type_is_mem_size(fn->arg1_type) ||
-	    arg_type_is_mem_ptr(fn->arg5_type)  ||
-	    check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
-	    check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
-	    check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
-	    check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
+	    (arg_type_is_mem_ptr(fn->arg5_type) && !fn->arg5_size) ||
+	    check_args_pair_invalid(fn, 0) ||
+	    check_args_pair_invalid(fn, 1) ||
+	    check_args_pair_invalid(fn, 2) ||
+	    check_args_pair_invalid(fn, 3))
 		return false;
 
 	return true;
Signature · 1 line
2.30.2
#4 lore raw

PATCH v9 3/5 bpf: Add helpers to issue and check SYN cookies in XDP

In reply to Maxim Mikityanskiy

The new helpers bpf_tcp_raw_{gen,check}_syncookie_ipv{4,6} allow an XDP program to generate SYN cookies in response to TCP SYN packets and to check those cookies upon receiving the first ACK packet (the final packet of the TCP handshake).

Unlike bpf_tcp_{gen,check}_syncookie these new helpers don't need a listening socket on the local machine, which allows to use them together with synproxy to accelerate SYN cookie generation.

---
 include/net/tcp.h              |   1 +
 include/uapi/linux/bpf.h       |  78 ++++++++++++++++++++++
 net/core/filter.c              | 118 +++++++++++++++++++++++++++++++++
 net/ipv4/tcp_input.c           |   3 +-
 scripts/bpf_doc.py             |   4 ++
 tools/include/uapi/linux/bpf.h |  78 ++++++++++++++++++++++
 6 files changed, 281 insertions(+), 1 deletion(-)
include/net/tcp.h +1 -0
index 94a52ad1101c..45aafc28ce00 100644
@@ -432,6 +432,7 @@ u16 tcp_v4_get_syncookie(struct sock *sk, struct iphdr *iph,
 			 struct tcphdr *th, u32 *cookie);
 u16 tcp_v6_get_syncookie(struct sock *sk, struct ipv6hdr *iph,
 			 struct tcphdr *th, u32 *cookie);
+u16 tcp_parse_mss_option(const struct tcphdr *th, u16 user_mss);
 u16 tcp_get_syncookie_mss(struct request_sock_ops *rsk_ops,
 			  const struct tcp_request_sock_ops *af_ops,
 			  struct sock *sk, struct tcphdr *th);
include/uapi/linux/bpf.h +78 -0

90 lines not on this page · raw message

net/core/filter.c +118 -0

130 lines not on this page · raw message

net/ipv4/tcp_input.c +2 -1
index daff631b9486..1eca6be492c8 100644
@@ -3963,7 +3963,7 @@ static bool smc_parse_options(const struct tcphdr *th,
 /* Try to parse the MSS option from the TCP header. Return 0 on failure, clamped
  * value on success.
  */
-static u16 tcp_parse_mss_option(const struct tcphdr *th, u16 user_mss)
+u16 tcp_parse_mss_option(const struct tcphdr *th, u16 user_mss)
 {
 	const unsigned char *ptr = (const unsigned char *)(th + 1);
 	int length = (th->doff * 4) - sizeof(struct tcphdr);
@@ -4002,6 +4002,7 @@ static u16 tcp_parse_mss_option(const struct tcphdr *th, u16 user_mss)
 	}
 	return mss;
 }
+EXPORT_SYMBOL_GPL(tcp_parse_mss_option);
 
 /* Look for tcp options. Normally only called on SYN and SYNACK packets.
  * But, this can also be called on packets in the established flow when
scripts/bpf_doc.py +4 -0
index 096625242475..3d0b65e6dea7 100755
@@ -633,6 +633,8 @@ class PrinterHelpers(Printer):
             'struct socket',
             'struct file',
             'struct bpf_timer',
+            'struct iphdr',
+            'struct ipv6hdr',
     ]
     known_types = {
             '...',
@@ -682,6 +684,8 @@ class PrinterHelpers(Printer):
             'struct socket',
             'struct file',
             'struct bpf_timer',
+            'struct iphdr',
+            'struct ipv6hdr',
     }
     mapped_types = {
             'u8': '__u8',
tools/include/uapi/linux/bpf.h +78 -0

90 lines not on this page · raw message

Signature · 1 line
2.30.2
#8 lore raw

PATCH v9 4/5 bpf: Add selftests for raw syncookie helpers

In reply to Maxim Mikityanskiy

This commit adds selftests for the new BPF helpers:
bpf_tcp_raw_{gen,check}_syncookie_ipv{4,6}.

xdp_synproxy_kern.c is a BPF program that generates SYN cookies on allowed TCP ports and sends SYNACKs to clients, accelerating synproxy iptables module.

xdp_synproxy.c is a userspace control application that allows to configure the following options in runtime: list of allowed ports, MSS, window scale, TTL.

A selftest is added to prog_tests that leverages the above programs to test the functionality of the new helpers.

---
 tools/testing/selftests/bpf/.gitignore        |   1 +
 tools/testing/selftests/bpf/Makefile          |   5 +-
 .../selftests/bpf/prog_tests/xdp_synproxy.c   | 109 +++
 .../selftests/bpf/progs/xdp_synproxy_kern.c   | 750 ++++++++++++++++++
 tools/testing/selftests/bpf/xdp_synproxy.c    | 418 ++++++++++
 5 files changed, 1281 insertions(+), 2 deletions(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c
 create mode 100644 tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c
 create mode 100644 tools/testing/selftests/bpf/xdp_synproxy.c
tools/testing/selftests/bpf/.gitignore +1 -0
index 595565eb68c0..ca2f47f45670 100644
@@ -43,3 +43,4 @@ test_cpp
 *.tmp
 xdpxceiver
 xdp_redirect_multi
+xdp_synproxy
tools/testing/selftests/bpf/Makefile +3 -2
index bafdc5373a13..8ae602843b16 100644
@@ -82,9 +82,9 @@ TEST_PROGS_EXTENDED := with_addr.sh \
 TEST_GEN_PROGS_EXTENDED = test_sock_addr test_skb_cgroup_id_user \
 	flow_dissector_load test_flow_dissector test_tcp_check_syncookie_user \
 	test_lirc_mode2_user xdping test_cpp runqslower bench bpf_testmod.ko \
-	xdpxceiver xdp_redirect_multi
+	xdpxceiver xdp_redirect_multi xdp_synproxy
 
-TEST_CUSTOM_PROGS = $(OUTPUT)/urandom_read
+TEST_CUSTOM_PROGS = $(OUTPUT)/urandom_read $(OUTPUT)/xdp_synproxy
 
 # Emit succinct information message describing current building step
 # $1 - generic step name (e.g., CC, LINK, etc);
@@ -500,6 +500,7 @@ TRUNNER_EXTRA_SOURCES := test_progs.c cgroup_helpers.c trace_helpers.c	\
 			 cap_helpers.c
 TRUNNER_EXTRA_FILES := $(OUTPUT)/urandom_read $(OUTPUT)/bpf_testmod.ko	\
 		       $(OUTPUT)/liburandom_read.so			\
+		       $(OUTPUT)/xdp_synproxy				\
 		       ima_setup.sh					\
 		       $(wildcard progs/btf_dump_test_case_*.c)
 TRUNNER_BPF_BUILD_RULE := CLANG_BPF_BUILD_RULE
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +109 -0

109 lines not on this page · raw message

tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +750 -0

750 lines not on this page · raw message

tools/testing/selftests/bpf/xdp_synproxy.c new file +418 -0

418 lines not on this page · raw message

Signature · 1 line
2.30.2
#13 lore raw

PATCH v9 5/5 bpf: Allow the new syncookie helpers to work with SKBs

In reply to Maxim Mikityanskiy

This commits allows the new BPF helpers to work in SKB context (in TC BPF programs): bpf_tcp_raw_{gen,check}_syncookie_ipv{4,6}.

The sample application and selftest are updated to support the TC mode. It's not the recommended mode of operation, because the SKB is already created at this point, and it's unlikely that the BPF program will provide any substantional speedup compared to regular SYN cookies or synproxy.

---
 net/core/filter.c                             |  10 ++
 .../selftests/bpf/prog_tests/xdp_synproxy.c   |  53 +++++--
 .../selftests/bpf/progs/xdp_synproxy_kern.c   | 141 +++++++++++++-----
 tools/testing/selftests/bpf/xdp_synproxy.c    |  94 +++++++++---
 4 files changed, 230 insertions(+), 68 deletions(-)
net/core/filter.c +10 -0
index 7efeee6c7624..f8fe9aea545f 100644
@@ -7905,6 +7905,16 @@ tc_cls_act_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
 		return &bpf_sk_assign_proto;
 	case BPF_FUNC_skb_set_tstamp:
 		return &bpf_skb_set_tstamp_proto;
+#ifdef CONFIG_SYN_COOKIES
+	case BPF_FUNC_tcp_raw_gen_syncookie_ipv4:
+		return &bpf_tcp_raw_gen_syncookie_ipv4_proto;
+	case BPF_FUNC_tcp_raw_gen_syncookie_ipv6:
+		return &bpf_tcp_raw_gen_syncookie_ipv6_proto;
+	case BPF_FUNC_tcp_raw_check_syncookie_ipv4:
+		return &bpf_tcp_raw_check_syncookie_ipv4_proto;
+	case BPF_FUNC_tcp_raw_check_syncookie_ipv6:
+		return &bpf_tcp_raw_check_syncookie_ipv6_proto;
+#endif
 #endif
 	default:
 		return bpf_sk_base_func_proto(func_id);
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c +44 -9

98 lines not on this page · raw message

tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c +105 -36

215 lines not on this page · raw message

tools/testing/selftests/bpf/xdp_synproxy.c +71 -23

174 lines not on this page · raw message

Signature · 1 line
2.30.2
#3 lore raw

Re: [PATCH bpf-next v9 2/5] bpf: Allow helpers to accept pointers with a fixed size

In reply to Maxim Mikityanskiy
Quoted 5 lines · Maxim Mikityanskiy

Before this commit, the BPF verifier required ARG_PTR_TO_MEM arguments to be followed by ARG_CONST_SIZE holding the size of the memory region. The helpers had to check that size in runtime.

Quoted 7 lines

There are cases where the size expected by a helper is a compile-time constant. Checking it in runtime is an unnecessary overhead and waste of BPF registers.

This commit allows helpers to accept ARG_PTR_TO_MEM arguments without the corresponding ARG_CONST_SIZE, given that they define the memory region size in struct bpf_func_proto.

I think it's much less confusing and cleaner to have ARG_PTR_TO_FIXED_SIZE_MEM (or whatever similar name), instead of adding special casing to ARG_PTR_TO_MEM.

Quoted 16 lines
---
 include/linux/bpf.h   | 10 ++++++++++
 kernel/bpf/verifier.c | 26 +++++++++++++++-----------
 2 files changed, 25 insertions(+), 11 deletions(-)
include/linux/bpf.h +0 -0
index be94833d390a..255ae3652225 100644
@@ -514,6 +514,16 @@ struct bpf_func_proto {
                };
                u32 *arg_btf_id[5];
        };

include/linux/bpf.h struct bpf_func_proto { · line 526

Quoted 10 lines
include/linux/bpf.h +10 -0
+       union {
+               struct {
+                       size_t arg1_size;
+                       size_t arg2_size;
+                       size_t arg3_size;
+                       size_t arg4_size;
+                       size_t arg5_size;
+               };
+               size_t arg_size[5];
+       };

We have almost 250 instances of struct bpf_func_proto variables:

$ rg 'const struct bpf_func_proto.* = \{' | wc -l
244

You are adding 40 bytes to it just to use it for 1-2 special prototypes. It is quite expensive, IMHO, to increase vmlinux image size by 10KB just for this.

Should we reuse arg_btf_id union (same argument won't be PTR_TO_BTF_ID and PTR_TO_FIXED_SIZE_MEM, right)? Or alternatively special-case those few prototypes in verifier code directly when trying to fetch memory size?

Quoted 3 lines
include/linux/bpf.h +0 -0
        int *ret_btf_id; /* return value btf_id */
        bool (*allowed)(const struct bpf_prog *prog);
 };

[...]

#5 lore raw

Re: [PATCH bpf-next v9 3/5] bpf: Add helpers to issue and check SYN cookies in XDP

In reply to Maxim Mikityanskiy
Quoted 75 lines · Maxim Mikityanskiy

The new helpers bpf_tcp_raw_{gen,check}_syncookie_ipv{4,6} allow an XDP program to generate SYN cookies in response to TCP SYN packets and to check those cookies upon receiving the first ACK packet (the final packet of the TCP handshake).

Unlike bpf_tcp_{gen,check}_syncookie these new helpers don't need a listening socket on the local machine, which allows to use them together with synproxy to accelerate SYN cookie generation.

---
 include/net/tcp.h              |   1 +
 include/uapi/linux/bpf.h       |  78 ++++++++++++++++++++++
 net/core/filter.c              | 118 +++++++++++++++++++++++++++++++++
 net/ipv4/tcp_input.c           |   3 +-
 scripts/bpf_doc.py             |   4 ++
 tools/include/uapi/linux/bpf.h |  78 ++++++++++++++++++++++
 6 files changed, 281 insertions(+), 1 deletion(-)
include/net/tcp.h +1 -0
index 94a52ad1101c..45aafc28ce00 100644
@@ -432,6 +432,7 @@ u16 tcp_v4_get_syncookie(struct sock *sk, struct iphdr *iph,
                         struct tcphdr *th, u32 *cookie);
 u16 tcp_v6_get_syncookie(struct sock *sk, struct ipv6hdr *iph,
                         struct tcphdr *th, u32 *cookie);
+u16 tcp_parse_mss_option(const struct tcphdr *th, u16 user_mss);
 u16 tcp_get_syncookie_mss(struct request_sock_ops *rsk_ops,
                          const struct tcp_request_sock_ops *af_ops,
                          struct sock *sk, struct tcphdr *th);
include/uapi/linux/bpf.h +34 -0
index 4dd9e34f2a60..5e611d898302 100644
@@ -5156,6 +5156,80 @@ union bpf_attr {
  *             if not NULL, is a reference which must be released using its
  *             corresponding release function, or moved into a BPF map before
  *             program exit.
+ *
+ * s64 bpf_tcp_raw_gen_syncookie_ipv4(struct iphdr *iph, struct tcphdr *th, u32 th_len)
+ *     Description
+ *             Try to issue a SYN cookie for the packet with corresponding
+ *             IPv4/TCP headers, *iph* and *th*, without depending on a
+ *             listening socket.
+ *
+ *             *iph* points to the IPv4 header.
+ *
+ *             *th* points to the start of the TCP header, while *th_len*
+ *             contains the length of the TCP header (at least
+ *             **sizeof**\ (**struct tcphdr**)).
+ *     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** if *th_len* is invalid.
+ *
+ * s64 bpf_tcp_raw_gen_syncookie_ipv6(struct ipv6hdr *iph, struct tcphdr *th, u32 th_len)
+ *     Description
+ *             Try to issue a SYN cookie for the packet with corresponding
+ *             IPv6/TCP headers, *iph* and *th*, without depending on a
+ *             listening socket.
+ *
+ *             *iph* points to the IPv6 header.
+ *
+ *             *th* points to the start of the TCP header, while *th_len*
+ *             contains the length of the TCP header (at least
+ *             **sizeof**\ (**struct tcphdr**)).
+ *     Return
+ *             On success, lower 32 bits hold the generated SYN cookie in

include/uapi/linux/bpf.h union bpf_attr { · line 5202

Quoted 10 lines
include/uapi/linux/bpf.h +10 -0
+ *             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** if *th_len* is invalid.
+ *
+ *             **-EPROTONOSUPPORT** if CONFIG_IPV6 is not builtin.
+ *
+ * int bpf_tcp_raw_check_syncookie_ipv4(struct iphdr *iph, struct tcphdr *th)

Note that all existing helpers that just return error or 0 on success return long. Please use long for consistency.

Quoted 5 lines
include/uapi/linux/bpf.h +5 -0
+ *     Description
+ *             Check whether *iph* and *th* contain a valid SYN cookie ACK
+ *             without depending on a listening socket.
+ *
+ *             *iph* points to the IPv4 header.

include/uapi/linux/bpf.h union bpf_attr { · line 5217

Quoted 10 lines
include/uapi/linux/bpf.h +10 -0
+ *
+ *             *th* points to the TCP header.
+ *     Return
+ *             0 if *iph* and *th* are a valid SYN cookie ACK.
+ *
+ *             On failure, the returned value is one of the following:
+ *
+ *             **-EACCES** if the SYN cookie is not valid.
+ *
+ * int bpf_tcp_raw_check_syncookie_ipv6(struct ipv6hdr *iph, struct tcphdr *th)

same

Quoted 15 lines
include/uapi/linux/bpf.h +15 -0
+ *     Description
+ *             Check whether *iph* and *th* contain a valid SYN cookie ACK
+ *             without depending on a listening socket.
+ *
+ *             *iph* points to the IPv6 header.
+ *
+ *             *th* points to the TCP header.
+ *     Return
+ *             0 if *iph* and *th* are a valid SYN cookie ACK.
+ *
+ *             On failure, the returned value is one of the following:
+ *
+ *             **-EACCES** if the SYN cookie is not valid.
+ *
+ *             **-EPROTONOSUPPORT** if CONFIG_IPV6 is not builtin.

[...]

#9 lore raw

Re: [PATCH bpf-next v9 4/5] bpf: Add selftests for raw syncookie helpers

In reply to Maxim Mikityanskiy
Quoted 12 lines · Maxim Mikityanskiy

This commit adds selftests for the new BPF helpers:
bpf_tcp_raw_{gen,check}_syncookie_ipv{4,6}.

xdp_synproxy_kern.c is a BPF program that generates SYN cookies on allowed TCP ports and sends SYNACKs to clients, accelerating synproxy iptables module.

xdp_synproxy.c is a userspace control application that allows to configure the following options in runtime: list of allowed ports, MSS, window scale, TTL.

Quoted 6 lines

A selftest is added to prog_tests that leverages the above programs to test the functionality of the new helpers.

---

selftests should use "selftests/bpf: " subject prefix, not "bpf: ", please update so it's more obvious that this patch touches selftests and not kernel-side BPF functionality.

Quoted 36 lines
 tools/testing/selftests/bpf/.gitignore        |   1 +
 tools/testing/selftests/bpf/Makefile          |   5 +-
 .../selftests/bpf/prog_tests/xdp_synproxy.c   | 109 +++
 .../selftests/bpf/progs/xdp_synproxy_kern.c   | 750 ++++++++++++++++++
 tools/testing/selftests/bpf/xdp_synproxy.c    | 418 ++++++++++
 5 files changed, 1281 insertions(+), 2 deletions(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c
 create mode 100644 tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c
 create mode 100644 tools/testing/selftests/bpf/xdp_synproxy.c
tools/testing/selftests/bpf/.gitignore +1 -0
index 595565eb68c0..ca2f47f45670 100644
@@ -43,3 +43,4 @@ test_cpp
 *.tmp
 xdpxceiver
 xdp_redirect_multi
+xdp_synproxy
tools/testing/selftests/bpf/Makefile +2 -2
index bafdc5373a13..8ae602843b16 100644
@@ -82,9 +82,9 @@ TEST_PROGS_EXTENDED := with_addr.sh \
 TEST_GEN_PROGS_EXTENDED = test_sock_addr test_skb_cgroup_id_user \
        flow_dissector_load test_flow_dissector test_tcp_check_syncookie_user \
        test_lirc_mode2_user xdping test_cpp runqslower bench bpf_testmod.ko \
-       xdpxceiver xdp_redirect_multi
+       xdpxceiver xdp_redirect_multi xdp_synproxy
 
-TEST_CUSTOM_PROGS = $(OUTPUT)/urandom_read
+TEST_CUSTOM_PROGS = $(OUTPUT)/urandom_read $(OUTPUT)/xdp_synproxy
 
 # Emit succinct information message describing current building step
 # $1 - generic step name (e.g., CC, LINK, etc);

tools/testing/selftests/bpf/Makefile TRUNNER_EXTRA_SOURCES := test_progs.c cgroup_helpers.c trace_helpers.c \ · line 503

Quoted 4 lines
tools/testing/selftests/bpf/Makefile +1 -0
@@ -500,6 +500,7 @@ TRUNNER_EXTRA_SOURCES := test_progs.c cgroup_helpers.c trace_helpers.c      \
                         cap_helpers.c
 TRUNNER_EXTRA_FILES := $(OUTPUT)/urandom_read $(OUTPUT)/bpf_testmod.ko \
                       $(OUTPUT)/liburandom_read.so                     \
+                      $(OUTPUT)/xdp_synproxy                           \

this is the right way to make external binary available to test_progs flavors, but is there anything inherently requiring external binary instead of having a helper function doing the same? urandom_read has to be a separate binary.

Quoted 42 lines
tools/testing/selftests/bpf/Makefile +0 -0
                       ima_setup.sh                                     \
                       $(wildcard progs/btf_dump_test_case_*.c)
 TRUNNER_BPF_BUILD_RULE := CLANG_BPF_BUILD_RULE
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +33 -0
new file mode 100644
index 000000000000..e08b28e25047
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <test_progs.h>
+#include <network_helpers.h>
+
+#define SYS(cmd) ({ \
+       if (!ASSERT_OK(system(cmd), (cmd))) \
+               goto out; \
+})
+
+#define SYS_OUT(cmd) ({ \
+       FILE *f = popen((cmd), "r"); \
+       if (!ASSERT_OK_PTR(f, (cmd))) \
+               goto out; \
+       f; \
+})
+
+static bool expect_str(char *buf, size_t size, const char *str)
+{
+       if (size != strlen(str))
+               return false;
+       return !memcmp(buf, str, size);
+}
+
+void test_xdp_synproxy(void)
+{
+       int server_fd = -1, client_fd = -1, accept_fd = -1;
+       struct nstoken *ns = NULL;
+       FILE *ctrl_file = NULL;
+       char buf[1024];
+       size_t size;
+
+       SYS("ip netns add synproxy");
+

tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c line 42

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +9 -0
+       SYS("ip link add tmp0 type veth peer name tmp1");
+       SYS("ip link set tmp1 netns synproxy");
+       SYS("ip link set tmp0 up");
+       SYS("ip addr replace 198.18.0.1/24 dev tmp0");
 
+
+       // When checksum offload is enabled, the XDP program sees wrong
+       // checksums and drops packets.
+       SYS("ethtool -K tmp0 tx off");
+       // Workaround required for veth.

don't use C++ comments, please stick to /* */

Quoted 13 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +13 -0
+       SYS("ip link set tmp0 xdp object xdp_dummy.o section xdp 2> /dev/null");
+
+       ns = open_netns("synproxy");
+       if (!ASSERT_OK_PTR(ns, "setns"))
+               goto out;
+
+       SYS("ip link set lo up");
+       SYS("ip link set tmp1 up");
+       SYS("ip addr replace 198.18.0.2/24 dev tmp1");
+       SYS("sysctl -w net.ipv4.tcp_syncookies=2");
+       SYS("sysctl -w net.ipv4.tcp_timestamps=1");
+       SYS("sysctl -w net.netfilter.nf_conntrack_tcp_loose=0");
+       SYS("iptables -t raw -I PREROUTING \

tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c line 65

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +10 -0
+           -i tmp1 -p tcp -m tcp --syn --dport 8080 -j CT --notrack");
+       SYS("iptables -t filter -A INPUT \
+           -i tmp1 -p tcp -m tcp --dport 8080 -m state --state INVALID,UNTRACKED \
+           -j SYNPROXY --sack-perm --timestamp --wscale 7 --mss 1460");
+       SYS("iptables -t filter -A INPUT \
+           -i tmp1 -m state --state INVALID -j DROP");
+
+       ctrl_file = SYS_OUT("./xdp_synproxy --iface tmp1 --ports 8080 --single \
+                           --mss4 1460 --mss6 1440 --wscale 7 --ttl 64");
+       size = fread(buf, 1, sizeof(buf), ctrl_file);

buf is uninitialized so if fread fail strlen() can cause SIGSEGV or some other failure mode

Quoted 19 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +19 -0
+       pclose(ctrl_file);
+       if (!ASSERT_TRUE(expect_str(buf, size, "Total SYNACKs generated: 0\n"),
+                        "initial SYNACKs"))
+               goto out;
+
+       server_fd = start_server(AF_INET, SOCK_STREAM, "198.18.0.2", 8080, 0);
+       if (!ASSERT_GE(server_fd, 0, "start_server"))
+               goto out;
+
+       close_netns(ns);
+       ns = NULL;
+
+       client_fd = connect_to_fd(server_fd, 10000);
+       if (!ASSERT_GE(client_fd, 0, "connect_to_fd"))
+               goto out;
+
+       accept_fd = accept(server_fd, NULL, NULL);
+       if (!ASSERT_GE(accept_fd, 0, "accept"))
+               goto out;

tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c line 94

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +10 -0
+
+       ns = open_netns("synproxy");
+       if (!ASSERT_OK_PTR(ns, "setns"))
+               goto out;
+
+       ctrl_file = SYS_OUT("./xdp_synproxy --iface tmp1 --single");
+       size = fread(buf, 1, sizeof(buf), ctrl_file);
+       pclose(ctrl_file);
+       if (!ASSERT_TRUE(expect_str(buf, size, "Total SYNACKs generated: 1\n"),
+                        "SYNACKs after connection"))

please use ASSERT_STREQ instead, same above

Quoted 21 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +15 -0
+               goto out;
+
+out:
+       if (accept_fd >= 0)
+               close(accept_fd);
+       if (client_fd >= 0)
+               close(client_fd);
+       if (server_fd >= 0)
+               close(server_fd);
+       if (ns)
+               close_netns(ns);
+
+       system("ip link del tmp0");
+       system("ip netns del synproxy");
+}
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +0 -0
new file mode 100644
index 000000000000..9ae85b189072

tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c line 1

Quoted 1 line
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +1 -0
@@ -0,0 +1,750 @@
+// SPDX-License-Identifier: GPL-2.0 OR Linux-OpenIB

Can you please elaborate on what Linux-OpenIB license is and why GPL-2.0 isn't enough? We usually have GPL-2.0 or LGPL-2.1 OR BSD-2-Clause

Quoted 8 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +8 -0
+/* Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. */
+
+#include "vmlinux.h"
+
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_endian.h>
+#include <asm/errno.h>
+

[...]

tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c line 111

Quoted 12 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +12 -0
+
+static __always_inline __u16 csum_tcpudp_magic(__be32 saddr, __be32 daddr,
+                                              __u32 len, __u8 proto,
+                                              __u32 csum)
+{
+       __u64 s = csum;
+
+       s += (__u32)saddr;
+       s += (__u32)daddr;
+#if defined(__BIG_ENDIAN__)
+       s += proto + len;
+#elif defined(__LITTLE_ENDIAN__)

I've got few nudges in libbpf code base previously to use

#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__

instead (I don't remember the exact reason now, but there was a reason). Let's do the same here for consistency?

Quoted 12 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +12 -0
+       s += (proto + len) << 8;
+#else
+#error Unknown endian
+#endif
+       s = (s & 0xffffffff) + (s >> 32);
+       s = (s & 0xffffffff) + (s >> 32);
+
+       return csum_fold((__u32)s);
+}
+
+static __always_inline __u16 csum_ipv6_magic(const struct in6_addr *saddr,
+                                            const struct in6_addr *daddr,

tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c line 133

Quoted 10 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +10 -0
+                                            __u32 len, __u8 proto, __u32 csum)
+{
+       __u64 sum = csum;
+       int i;
+
+#pragma unroll
+       for (i = 0; i < 4; i++)
+               sum += (__u32)saddr->in6_u.u6_addr32[i];
+
+#pragma unroll

why unroll? BPF verifier handles such loops just fine, even if compiler decides to not unroll them

Quoted 4 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +4 -0
+       for (i = 0; i < 4; i++)
+               sum += (__u32)daddr->in6_u.u6_addr32[i];
+
+       // Don't combine additions to avoid 32-bit overflow.

tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c line 147

Quoted 10 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +10 -0
+       sum += bpf_htonl(len);
+       sum += bpf_htonl(proto);
+
+       sum = (sum & 0xffffffff) + (sum >> 32);
+       sum = (sum & 0xffffffff) + (sum >> 32);
+
+       return csum_fold((__u32)sum);
+}
+
+static __always_inline __u64 tcp_clock_ns(void)

__always_inline isn't mandatory, you can just have static __u64 tcp_clock_ns() here and let compiler decide on inlining? same for below

Quoted 14 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +14 -0
+{
+       return bpf_ktime_get_ns();
+}
+
+static __always_inline __u32 tcp_ns_to_ts(__u64 ns)
+{
+       return ns / (NSEC_PER_SEC / TCP_TS_HZ);
+}
+
+static __always_inline __u32 tcp_time_stamp_raw(void)
+{
+       return tcp_ns_to_ts(tcp_clock_ns());
+}
+

[...]

Quoted 14 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +14 -0
+static __always_inline void values_inc_synacks(void)
+{
+       __u32 key = 1;
+       __u32 *value;
+
+       value = bpf_map_lookup_elem(&values, &key);
+       if (value)
+               __sync_fetch_and_add(value, 1);
+}
+
+static __always_inline bool check_port_allowed(__u16 port)
+{
+       __u32 i;
+

tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c line 310

Quoted 10 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +10 -0
+       for (i = 0; i < MAX_ALLOWED_PORTS; i++) {
+               __u32 key = i;
+               __u16 *value;
+
+               value = bpf_map_lookup_elem(&allowed_ports, &key);
+
+               if (!value)
+                       break;
+               // 0 is a terminator value. Check it first to avoid matching on
+               // a forbidden port == 0 and returning true.

please no C++ comments (everywhere)

Quoted 10 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +10 -0
+               if (*value == 0)
+                       break;
+
+               if (*value == port)
+                       return true;
+       }
+
+       return false;
+}
+

[...]

#14 lore raw

Re: [PATCH bpf-next v9 5/5] bpf: Allow the new syncookie helpers to work with SKBs

In reply to Maxim Mikityanskiy
Quoted 10 lines · Maxim Mikityanskiy

This commits allows the new BPF helpers to work in SKB context (in TC BPF programs): bpf_tcp_raw_{gen,check}_syncookie_ipv{4,6}.

The sample application and selftest are updated to support the TC mode. It's not the recommended mode of operation, because the SKB is already created at this point, and it's unlikely that the BPF program will provide any substantional speedup compared to regular SYN cookies or synproxy.

Quoted 7 lines
---
 net/core/filter.c                             |  10 ++
 .../selftests/bpf/prog_tests/xdp_synproxy.c   |  53 +++++--
 .../selftests/bpf/progs/xdp_synproxy_kern.c   | 141 +++++++++++++-----
 tools/testing/selftests/bpf/xdp_synproxy.c    |  94 +++++++++---

please split selftests and kernel code into separate patches (and use selftests/bpf: prefix for selftests)

Quoted 2 lines
 4 files changed, 230 insertions(+), 68 deletions(-)

[...]

Quoted 14 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c +5 -1
@@ -87,7 +112,11 @@ void test_xdp_synproxy(void)
        if (!ASSERT_OK_PTR(ns, "setns"))
                goto out;
 
-       ctrl_file = SYS_OUT("./xdp_synproxy --iface tmp1 --single");
+       if (xdp)
+               ctrl_file = SYS_OUT("./xdp_synproxy --iface tmp1 --single");
+       else
+               ctrl_file = SYS_OUT("./xdp_synproxy --prog %s --single",
+                                   prog_id);
        size = fread(buf, 1, sizeof(buf), ctrl_file);
        pclose(ctrl_file);
        if (!ASSERT_TRUE(expect_str(buf, size, "Total SYNACKs generated: 1\n"),

tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c void test_xdp_synproxy(void) · line 143

Quoted 8 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c +5 -0
@@ -107,3 +136,9 @@ void test_xdp_synproxy(void)
        system("ip link del tmp0");
        system("ip netns del synproxy");
 }
+
+void test_xdp_synproxy(void)
+{
+       test_synproxy(true);
+       test_synproxy(false);

let's model this as subtests instead? See test__start_subtest() use in other selftests

Quoted 9 lines
(quoted diff) +1 -0
+}
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c +0 -0
index 9ae85b189072..f70b5f776dcf 100644
@@ -7,6 +7,9 @@
 #include <bpf/bpf_endian.h>
 #include <asm/errno.h>
 

[...]

Quoted 7 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c +1 -0
@@ -201,21 +220,50 @@ static int syncookie_attach(const char *argv0, unsigned int ifindex)
                fprintf(stderr, "Error: bpf_obj_get_info_by_fd: %s\n", strerror(-err));
                goto out;
        }
+       attached_tc = tc;
        attached_prog_id = info.id;
        signal(SIGINT, cleanup);

tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c static int syncookie_attach(const char *argv0, unsigned int ifindex) · line 228

Quoted 10 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c +2 -7
        signal(SIGTERM, cleanup);
-       err = bpf_xdp_attach(ifindex, prog_fd, XDP_FLAGS_UPDATE_IF_NOEXIST, NULL);
-       if (err < 0) {
-               fprintf(stderr, "Error: bpf_set_link_xdp_fd: %s\n", strerror(-err));
-               signal(SIGINT, SIG_DFL);
-               signal(SIGTERM, SIG_DFL);
-               attached_prog_id = 0;
-               goto out;
+       if (tc) {
+               DECLARE_LIBBPF_OPTS(bpf_tc_hook, hook,

nit: LIBBPF_OPTS is shorter, DECLARE_LIBBPF_OPTS is discouraged

Quoted 7 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c +7 -0
+                                   .ifindex = ifindex,
+                                   .attach_point = BPF_TC_INGRESS);
+               DECLARE_LIBBPF_OPTS(bpf_tc_opts, opts,
+                                   .handle = 1,
+                                   .priority = 1,
+                                   .prog_fd = prog_fd);
+

[...]

#15 lore raw
In reply to Maxim Mikityanskiy
Quoted 73 lines · Maxim Mikityanskiy

The first patch of this series is a documentation fix.

The second patch allows BPF helpers to accept memory regions of fixed size without doing runtime size checks.

The two next patches add new functionality that allows XDP to accelerate iptables synproxy.

v1 of this series [1] used to include a patch that exposed conntrack lookup to BPF using stable helpers. It was superseded by series [2] by Kumar Kartikeya Dwivedi, which implements this functionality using unstable helpers.

The third patch adds new helpers to issue and check SYN cookies without binding to a socket, which is useful in the synproxy scenario.

The fourth patch adds a selftest, which includes an XDP program and a userspace control application. The XDP program uses socketless SYN cookie helpers and queries conntrack status instead of socket status. The userspace control application allows to tune parameters of the XDP program. This program also serves as a minimal example of usage of the new functionality.

The last patch exposes the new helpers to TC BPF.

The draft of the new functionality was presented on Netdev 0x15 [3].

v2 changes:

Split into two series, submitted bugfixes to bpf, dropped the conntrack patches, implemented the timestamp cookie in BPF using bpf_loop, dropped the timestamp cookie patch.

v3 changes:

Moved some patches from bpf to bpf-next, dropped the patch that changed error codes, split the new helpers into IPv4/IPv6, added verifier functionality to accept memory regions of fixed size.

v4 changes:

Converted the selftest to the test_progs runner. Replaced some deprecated functions in xdp_synproxy userspace helper.

v5 changes:

Fixed a bug in the selftest. Added questionable functionality to support new helpers in TC BPF, added selftests for it.

v6 changes:

Wrap the new helpers themselves into #ifdef CONFIG_SYN_COOKIES, replaced fclose with pclose and fixed the MSS for IPv6 in the selftest.

v7 changes:

Fixed the off-by-one error in indices, changed the section name to "xdp", added missing kernel config options to vmtest in CI.

v8 changes:

Properly rebased, dropped the first patch (the same change was applied by someone else), updated the cover letter.

v9 changes:

Fixed selftests for no_alu32.

[1]: https://lore.kernel.org/bpf/[email protected]/t/
[2]: https://lore.kernel.org/bpf/[email protected]/
[3]: https://netdevconf.info/0x15/session.html?Accelerating-synproxy-with-XDP

Quoted 7 lines

Maxim Mikityanskiy (5):
bpf: Fix documentation of th_len in bpf_tcp_{gen,check}_syncookie
bpf: Allow helpers to accept pointers with a fixed size
bpf: Add helpers to issue and check SYN cookies in XDP
bpf: Add selftests for raw syncookie helpers
bpf: Allow the new syncookie helpers to work with SKBs

Is it expected that your selftests will fail on s390x? Please check [0]

[0] https://github.com/kernel-patches/bpf/runs/6277764463?check_suite_focus=true#step:6:6130

Quoted 21 lines
 include/linux/bpf.h                           |  10 +
 include/net/tcp.h                             |   1 +
 include/uapi/linux/bpf.h                      |  88 +-
 kernel/bpf/verifier.c                         |  26 +-
 net/core/filter.c                             | 128 +++
 net/ipv4/tcp_input.c                          |   3 +-
 scripts/bpf_doc.py                            |   4 +
 tools/include/uapi/linux/bpf.h                |  88 +-
 tools/testing/selftests/bpf/.gitignore        |   1 +
 tools/testing/selftests/bpf/Makefile          |   5 +-
 .../selftests/bpf/prog_tests/xdp_synproxy.c   | 144 +++
 .../selftests/bpf/progs/xdp_synproxy_kern.c   | 819 ++++++++++++++++++
 tools/testing/selftests/bpf/xdp_synproxy.c    | 466 ++++++++++
 13 files changed, 1761 insertions(+), 22 deletions(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c
 create mode 100644 tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c
 create mode 100644 tools/testing/selftests/bpf/xdp_synproxy.c

--
2.30.2

#6 lore raw

Re: [PATCH bpf-next v9 3/5] bpf: Add helpers to issue and check SYN cookies in XDP

In reply to Andrii Nakryiko
Quoted 81 lines · Andrii Nakryiko
Quoted 80 lines · Maxim Mikityanskiy

The new helpers bpf_tcp_raw_{gen,check}_syncookie_ipv{4,6} allow an XDP program to generate SYN cookies in response to TCP SYN packets and to check those cookies upon receiving the first ACK packet (the final packet of the TCP handshake).

Unlike bpf_tcp_{gen,check}_syncookie these new helpers don't need a listening socket on the local machine, which allows to use them together with synproxy to accelerate SYN cookie generation.

---
  include/net/tcp.h              |   1 +
  include/uapi/linux/bpf.h       |  78 ++++++++++++++++++++++
  net/core/filter.c              | 118 +++++++++++++++++++++++++++++++++
  net/ipv4/tcp_input.c           |   3 +-
  scripts/bpf_doc.py             |   4 ++
  tools/include/uapi/linux/bpf.h |  78 ++++++++++++++++++++++
  6 files changed, 281 insertions(+), 1 deletion(-)
include/net/tcp.h +1 -0
index 94a52ad1101c..45aafc28ce00 100644
@@ -432,6 +432,7 @@ u16 tcp_v4_get_syncookie(struct sock *sk, struct iphdr *iph,
                          struct tcphdr *th, u32 *cookie);
  u16 tcp_v6_get_syncookie(struct sock *sk, struct ipv6hdr *iph,
                          struct tcphdr *th, u32 *cookie);
+u16 tcp_parse_mss_option(const struct tcphdr *th, u16 user_mss);
  u16 tcp_get_syncookie_mss(struct request_sock_ops *rsk_ops,
                           const struct tcp_request_sock_ops *af_ops,
                           struct sock *sk, struct tcphdr *th);
include/uapi/linux/bpf.h +39 -0
index 4dd9e34f2a60..5e611d898302 100644
@@ -5156,6 +5156,80 @@ union bpf_attr {
   *             if not NULL, is a reference which must be released using its
   *             corresponding release function, or moved into a BPF map before
   *             program exit.
+ *
+ * s64 bpf_tcp_raw_gen_syncookie_ipv4(struct iphdr *iph, struct tcphdr *th, u32 th_len)
+ *     Description
+ *             Try to issue a SYN cookie for the packet with corresponding
+ *             IPv4/TCP headers, *iph* and *th*, without depending on a
+ *             listening socket.
+ *
+ *             *iph* points to the IPv4 header.
+ *
+ *             *th* points to the start of the TCP header, while *th_len*
+ *             contains the length of the TCP header (at least
+ *             **sizeof**\ (**struct tcphdr**)).
+ *     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** if *th_len* is invalid.
+ *
+ * s64 bpf_tcp_raw_gen_syncookie_ipv6(struct ipv6hdr *iph, struct tcphdr *th, u32 th_len)
+ *     Description
+ *             Try to issue a SYN cookie for the packet with corresponding
+ *             IPv6/TCP headers, *iph* and *th*, without depending on a
+ *             listening socket.
+ *
+ *             *iph* points to the IPv6 header.
+ *
+ *             *th* points to the start of the TCP header, while *th_len*
+ *             contains the length of the TCP header (at least
+ *             **sizeof**\ (**struct tcphdr**)).
+ *     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

include/uapi/linux/bpf.h union bpf_attr { · line 5202

Quoted 5 lines
include/uapi/linux/bpf.h +5 -0
+ *             **-EINVAL** if *th_len* is invalid.
+ *
+ *             **-EPROTONOSUPPORT** if CONFIG_IPV6 is not builtin.
+ *
+ * int bpf_tcp_raw_check_syncookie_ipv4(struct iphdr *iph, struct tcphdr *th)

Note that all existing helpers that just return error or 0 on success return long. Please use long for consistency.

OK. There are some existing helpers that return int, though: bpf_inode_storage_delete, bpf_get_retval, bpf_set_retval. They should probably be fixed by someone as well.

Quoted 35 lines
Quoted 5 lines
include/uapi/linux/bpf.h +5 -0
+ *     Description
+ *             Check whether *iph* and *th* contain a valid SYN cookie ACK
+ *             without depending on a listening socket.
+ *
+ *             *iph* points to the IPv4 header.

include/uapi/linux/bpf.h union bpf_attr { · line 5217

Quoted 10 lines
include/uapi/linux/bpf.h +10 -0
+ *
+ *             *th* points to the TCP header.
+ *     Return
+ *             0 if *iph* and *th* are a valid SYN cookie ACK.
+ *
+ *             On failure, the returned value is one of the following:
+ *
+ *             **-EACCES** if the SYN cookie is not valid.
+ *
+ * int bpf_tcp_raw_check_syncookie_ipv6(struct ipv6hdr *iph, struct tcphdr *th)

same

Quoted 15 lines
include/uapi/linux/bpf.h +15 -0
+ *     Description
+ *             Check whether *iph* and *th* contain a valid SYN cookie ACK
+ *             without depending on a listening socket.
+ *
+ *             *iph* points to the IPv6 header.
+ *
+ *             *th* points to the TCP header.
+ *     Return
+ *             0 if *iph* and *th* are a valid SYN cookie ACK.
+ *
+ *             On failure, the returned value is one of the following:
+ *
+ *             **-EACCES** if the SYN cookie is not valid.
+ *
+ *             **-EPROTONOSUPPORT** if CONFIG_IPV6 is not builtin.

[...]

#10 lore raw

Re: [PATCH bpf-next v9 4/5] bpf: Add selftests for raw syncookie helpers

In reply to Andrii Nakryiko
Quoted 57 lines · Andrii Nakryiko
Quoted 12 lines · Maxim Mikityanskiy

This commit adds selftests for the new BPF helpers:
bpf_tcp_raw_{gen,check}_syncookie_ipv{4,6}.

xdp_synproxy_kern.c is a BPF program that generates SYN cookies on allowed TCP ports and sends SYNACKs to clients, accelerating synproxy iptables module.

xdp_synproxy.c is a userspace control application that allows to configure the following options in runtime: list of allowed ports, MSS, window scale, TTL.

Quoted 6 lines

A selftest is added to prog_tests that leverages the above programs to test the functionality of the new helpers.

---

selftests should use "selftests/bpf: " subject prefix, not "bpf: ", please update so it's more obvious that this patch touches selftests and not kernel-side BPF functionality.

Quoted 33 lines
  tools/testing/selftests/bpf/.gitignore        |   1 +
  tools/testing/selftests/bpf/Makefile          |   5 +-
  .../selftests/bpf/prog_tests/xdp_synproxy.c   | 109 +++
  .../selftests/bpf/progs/xdp_synproxy_kern.c   | 750 ++++++++++++++++++
  tools/testing/selftests/bpf/xdp_synproxy.c    | 418 ++++++++++
  5 files changed, 1281 insertions(+), 2 deletions(-)

create mode 100644 tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c create mode 100644 tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c create mode 100644 tools/testing/selftests/bpf/xdp_synproxy.c

tools/testing/selftests/bpf/.gitignore +1 -0
index 595565eb68c0..ca2f47f45670 100644
@@ -43,3 +43,4 @@ test_cpp
  *.tmp
  xdpxceiver
  xdp_redirect_multi
+xdp_synproxy
tools/testing/selftests/bpf/Makefile +2 -2
index bafdc5373a13..8ae602843b16 100644
@@ -82,9 +82,9 @@ TEST_PROGS_EXTENDED := with_addr.sh \
  TEST_GEN_PROGS_EXTENDED = test_sock_addr test_skb_cgroup_id_user \
         flow_dissector_load test_flow_dissector test_tcp_check_syncookie_user \
         test_lirc_mode2_user xdping test_cpp runqslower bench bpf_testmod.ko \
-       xdpxceiver xdp_redirect_multi
+       xdpxceiver xdp_redirect_multi xdp_synproxy
 
-TEST_CUSTOM_PROGS = $(OUTPUT)/urandom_read
+TEST_CUSTOM_PROGS = $(OUTPUT)/urandom_read $(OUTPUT)/xdp_synproxy
 
Quoted 12 lines

tools/testing/selftests/bpf/Makefile TRUNNER_EXTRA_SOURCES := test_progs.c cgroup_helpers.c trace_helpers.c \ · line 503

Quoted 7 lines
tools/testing/selftests/bpf/Makefile +1 -0
  # Emit succinct information message describing current building step
  # $1 - generic step name (e.g., CC, LINK, etc);
@@ -500,6 +500,7 @@ TRUNNER_EXTRA_SOURCES := test_progs.c cgroup_helpers.c trace_helpers.c      \
                          cap_helpers.c
  TRUNNER_EXTRA_FILES := $(OUTPUT)/urandom_read $(OUTPUT)/bpf_testmod.ko \
                        $(OUTPUT)/liburandom_read.so                     \
+                      $(OUTPUT)/xdp_synproxy                           \

this is the right way to make external binary available to test_progs flavors, but is there anything inherently requiring external binary instead of having a helper function doing the same? urandom_read has to be a separate binary.

If you remember v1, it used to be a sample, but I was asked to convert it to a selftest, because samples are deprecated. The intention of having this separate binary is to have a sample reference implementation that can be used in real-world scenarios with minor or no changes.

Quoted 73 lines
Quoted 42 lines
tools/testing/selftests/bpf/Makefile +0 -0
                        ima_setup.sh                                     \
                        $(wildcard progs/btf_dump_test_case_*.c)
  TRUNNER_BPF_BUILD_RULE := CLANG_BPF_BUILD_RULE
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +33 -0
new file mode 100644
index 000000000000..e08b28e25047
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <test_progs.h>
+#include <network_helpers.h>
+
+#define SYS(cmd) ({ \
+       if (!ASSERT_OK(system(cmd), (cmd))) \
+               goto out; \
+})
+
+#define SYS_OUT(cmd) ({ \
+       FILE *f = popen((cmd), "r"); \
+       if (!ASSERT_OK_PTR(f, (cmd))) \
+               goto out; \
+       f; \
+})
+
+static bool expect_str(char *buf, size_t size, const char *str)
+{
+       if (size != strlen(str))
+               return false;
+       return !memcmp(buf, str, size);
+}
+
+void test_xdp_synproxy(void)
+{
+       int server_fd = -1, client_fd = -1, accept_fd = -1;
+       struct nstoken *ns = NULL;
+       FILE *ctrl_file = NULL;
+       char buf[1024];
+       size_t size;
+
+       SYS("ip netns add synproxy");
+

tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c line 42

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +9 -0
+       SYS("ip link add tmp0 type veth peer name tmp1");
+       SYS("ip link set tmp1 netns synproxy");
+       SYS("ip link set tmp0 up");
+       SYS("ip addr replace 198.18.0.1/24 dev tmp0");
 
+
+       // When checksum offload is enabled, the XDP program sees wrong
+       // checksums and drops packets.
+       SYS("ethtool -K tmp0 tx off");
+       // Workaround required for veth.

don't use C++ comments, please stick to /* */

Quoted 18 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +18 -0
+       SYS("ip link set tmp0 xdp object xdp_dummy.o section xdp 2> /dev/null");
+
+       ns = open_netns("synproxy");
+       if (!ASSERT_OK_PTR(ns, "setns"))
+               goto out;
+
+       SYS("ip link set lo up");
+       SYS("ip link set tmp1 up");
+       SYS("ip addr replace 198.18.0.2/24 dev tmp1");
+       SYS("sysctl -w net.ipv4.tcp_syncookies=2");
+       SYS("sysctl -w net.ipv4.tcp_timestamps=1");
+       SYS("sysctl -w net.netfilter.nf_conntrack_tcp_loose=0");
+       SYS("iptables -t raw -I PREROUTING \
+           -i tmp1 -p tcp -m tcp --syn --dport 8080 -j CT --notrack");
+       SYS("iptables -t filter -A INPUT \
+           -i tmp1 -p tcp -m tcp --dport 8080 -m state --state INVALID,UNTRACKED \
+           -j SYNPROXY --sack-perm --timestamp --wscale 7 --mss 1460");
+       SYS("iptables -t filter -A INPUT \
Quoted 8 lines

tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c line 65

Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +5 -0
+           -i tmp1 -m state --state INVALID -j DROP");
+
+       ctrl_file = SYS_OUT("./xdp_synproxy --iface tmp1 --ports 8080 --single \
+                           --mss4 1460 --mss6 1440 --wscale 7 --ttl 64");
+       size = fread(buf, 1, sizeof(buf), ctrl_file);

buf is uninitialized so if fread fail strlen() can cause SIGSEGV or some other failure mode

No, it will exit on the assert below (size won't be equal to strlen(str)).

Quoted 24 lines
Quoted 24 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +23 -0
+       pclose(ctrl_file);
+       if (!ASSERT_TRUE(expect_str(buf, size, "Total SYNACKs generated: 0\n"),
+                        "initial SYNACKs"))
+               goto out;
+
+       server_fd = start_server(AF_INET, SOCK_STREAM, "198.18.0.2", 8080, 0);
+       if (!ASSERT_GE(server_fd, 0, "start_server"))
+               goto out;
+
+       close_netns(ns);
+       ns = NULL;
+
+       client_fd = connect_to_fd(server_fd, 10000);
+       if (!ASSERT_GE(client_fd, 0, "connect_to_fd"))
+               goto out;
+
+       accept_fd = accept(server_fd, NULL, NULL);
+       if (!ASSERT_GE(accept_fd, 0, "accept"))
+               goto out;
+
+       ns = open_netns("synproxy");
+       if (!ASSERT_OK_PTR(ns, "setns"))
+               goto out;
Quoted 8 lines

tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c line 94

Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +6 -0
+
+       ctrl_file = SYS_OUT("./xdp_synproxy --iface tmp1 --single");
+       size = fread(buf, 1, sizeof(buf), ctrl_file);
+       pclose(ctrl_file);
+       if (!ASSERT_TRUE(expect_str(buf, size, "Total SYNACKs generated: 1\n"),
+                        "SYNACKs after connection"))

please use ASSERT_STREQ instead, same above

It doesn't fit here for two reasons:

* It doesn't consider size (and ignoring size will cause a UB on errors because of the uninitialized buf).

* buf is not '\0'-terminated, and ASSERT_STREQ uses strcmp.

Quoted 19 lines
Quoted 19 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +15 -0
+               goto out;
+
+out:
+       if (accept_fd >= 0)
+               close(accept_fd);
+       if (client_fd >= 0)
+               close(client_fd);
+       if (server_fd >= 0)
+               close(server_fd);
+       if (ns)
+               close_netns(ns);
+
+       system("ip link del tmp0");
+       system("ip netns del synproxy");
+}
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +0 -0
new file mode 100644
index 000000000000..9ae85b189072
Quoted 8 lines

tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c line 1

Quoted 4 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +1 -0
@@ -0,0 +1,750 @@
+// SPDX-License-Identifier: GPL-2.0 OR Linux-OpenIB

Can you please elaborate on what Linux-OpenIB license is and why GPL-2.0 isn't enough? We usually have GPL-2.0 or LGPL-2.1 OR BSD-2-Clause

That's the license boilerplate we use in the mlx5e driver. I'll check with the relevant people whether we can submit it as GPL-2.0 solely.

Quoted 26 lines
Quoted 8 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +8 -0
+/* Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. */
+
+#include "vmlinux.h"
+
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_endian.h>
+#include <asm/errno.h>
+

[...]

tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c line 111

Quoted 12 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +12 -0
+
+static __always_inline __u16 csum_tcpudp_magic(__be32 saddr, __be32 daddr,
+                                              __u32 len, __u8 proto,
+                                              __u32 csum)
+{
+       __u64 s = csum;
+
+       s += (__u32)saddr;
+       s += (__u32)daddr;
+#if defined(__BIG_ENDIAN__)
+       s += proto + len;
+#elif defined(__LITTLE_ENDIAN__)

I've got few nudges in libbpf code base previously to use

Quoted 5 lines

#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__

instead (I don't remember the exact reason now, but there was a reason). Let's do the same here for consistency?

OK.

samples/bpf/xdpsock_user.c also still uses __BIG_ENDIAN__.

Quoted 17 lines
Quoted 17 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +17 -0
+       s += (proto + len) << 8;
+#else
+#error Unknown endian
+#endif
+       s = (s & 0xffffffff) + (s >> 32);
+       s = (s & 0xffffffff) + (s >> 32);
+
+       return csum_fold((__u32)s);
+}
+
+static __always_inline __u16 csum_ipv6_magic(const struct in6_addr *saddr,
+                                            const struct in6_addr *daddr,
+                                            __u32 len, __u8 proto, __u32 csum)
+{
+       __u64 sum = csum;
+       int i;
+
Quoted 8 lines

tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c line 133

Quoted 5 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +5 -0
+#pragma unroll
+       for (i = 0; i < 4; i++)
+               sum += (__u32)saddr->in6_u.u6_addr32[i];
+
+#pragma unroll

why unroll? BPF verifier handles such loops just fine, even if compiler decides to not unroll them

Optimization, see csum_ipv6_magic in net/ipv6/ip6_checksum.c that has this loop unrolled manually.

Quoted 10 lines
Quoted 10 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +10 -0
+       for (i = 0; i < 4; i++)
+               sum += (__u32)daddr->in6_u.u6_addr32[i];
+
+       // Don't combine additions to avoid 32-bit overflow.
+       sum += bpf_htonl(len);
+       sum += bpf_htonl(proto);
+
+       sum = (sum & 0xffffffff) + (sum >> 32);
+       sum = (sum & 0xffffffff) + (sum >> 32);
+
Quoted 8 lines

tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c line 147

Quoted 4 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +4 -0
+       return csum_fold((__u32)sum);
+}
+
+static __always_inline __u64 tcp_clock_ns(void)

__always_inline isn't mandatory, you can just have static __u64 tcp_clock_ns() here and let compiler decide on inlining? same for below

Do you mean just these three functions, or all functions below, or actually all functions in this file?

It's not mandatory, but these are simple one-liners, it would be unpleasant to waste an extra call in performance-critical code if the compiler decides not to inline them.

Quoted 56 lines
Quoted 14 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +14 -0
+{
+       return bpf_ktime_get_ns();
+}
+
+static __always_inline __u32 tcp_ns_to_ts(__u64 ns)
+{
+       return ns / (NSEC_PER_SEC / TCP_TS_HZ);
+}
+
+static __always_inline __u32 tcp_time_stamp_raw(void)
+{
+       return tcp_ns_to_ts(tcp_clock_ns());
+}
+

[...]

Quoted 14 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +14 -0
+static __always_inline void values_inc_synacks(void)
+{
+       __u32 key = 1;
+       __u32 *value;
+
+       value = bpf_map_lookup_elem(&values, &key);
+       if (value)
+               __sync_fetch_and_add(value, 1);
+}
+
+static __always_inline bool check_port_allowed(__u16 port)
+{
+       __u32 i;
+

tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c line 310

Quoted 10 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +10 -0
+       for (i = 0; i < MAX_ALLOWED_PORTS; i++) {
+               __u32 key = i;
+               __u16 *value;
+
+               value = bpf_map_lookup_elem(&allowed_ports, &key);
+
+               if (!value)
+                       break;
+               // 0 is a terminator value. Check it first to avoid matching on
+               // a forbidden port == 0 and returning true.

please no C++ comments (everywhere)

Quoted 10 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +10 -0
+               if (*value == 0)
+                       break;
+
+               if (*value == port)
+                       return true;
+       }
+
+       return false;
+}
+

[...]

#16 lore raw
In reply to Andrii Nakryiko
Quoted 82 lines · Andrii Nakryiko
Quoted 73 lines · Maxim Mikityanskiy

The first patch of this series is a documentation fix.

The second patch allows BPF helpers to accept memory regions of fixed size without doing runtime size checks.

The two next patches add new functionality that allows XDP to accelerate iptables synproxy.

v1 of this series [1] used to include a patch that exposed conntrack lookup to BPF using stable helpers. It was superseded by series [2] by Kumar Kartikeya Dwivedi, which implements this functionality using unstable helpers.

The third patch adds new helpers to issue and check SYN cookies without binding to a socket, which is useful in the synproxy scenario.

The fourth patch adds a selftest, which includes an XDP program and a userspace control application. The XDP program uses socketless SYN cookie helpers and queries conntrack status instead of socket status. The userspace control application allows to tune parameters of the XDP program. This program also serves as a minimal example of usage of the new functionality.

The last patch exposes the new helpers to TC BPF.

The draft of the new functionality was presented on Netdev 0x15 [3].

v2 changes:

Split into two series, submitted bugfixes to bpf, dropped the conntrack patches, implemented the timestamp cookie in BPF using bpf_loop, dropped the timestamp cookie patch.

v3 changes:

Moved some patches from bpf to bpf-next, dropped the patch that changed error codes, split the new helpers into IPv4/IPv6, added verifier functionality to accept memory regions of fixed size.

v4 changes:

Converted the selftest to the test_progs runner. Replaced some deprecated functions in xdp_synproxy userspace helper.

v5 changes:

Fixed a bug in the selftest. Added questionable functionality to support new helpers in TC BPF, added selftests for it.

v6 changes:

Wrap the new helpers themselves into #ifdef CONFIG_SYN_COOKIES, replaced fclose with pclose and fixed the MSS for IPv6 in the selftest.

v7 changes:

Fixed the off-by-one error in indices, changed the section name to "xdp", added missing kernel config options to vmtest in CI.

v8 changes:

Properly rebased, dropped the first patch (the same change was applied by someone else), updated the cover letter.

v9 changes:

Fixed selftests for no_alu32.

[1]: https://lore.kernel.org/bpf/[email protected]/t/
[2]: https://lore.kernel.org/bpf/[email protected]/
[3]: https://netdevconf.info/0x15/session.html?Accelerating-synproxy-with-XDP

Quoted 7 lines

Maxim Mikityanskiy (5):
bpf: Fix documentation of th_len in bpf_tcp_{gen,check}_syncookie
bpf: Allow helpers to accept pointers with a fixed size
bpf: Add helpers to issue and check SYN cookies in XDP
bpf: Add selftests for raw syncookie helpers
bpf: Allow the new syncookie helpers to work with SKBs

Quoted 1 line

Is it expected that your selftests will fail on s390x? Please check [0]

I see it fails with:

test_synproxy:FAIL:ethtool -K tmp0 tx off unexpected error: 32512 (errno 2)

errno 2 is ENOENT, probably the ethtool binary is missing from the s390x image? When reviewing v6, you said you added ethtool to the CI image. Maybe it was added to x86_64 only? Could you add it to s390x?

[1]: https://patchwork.kernel.org/project/netdevbpf/patch/[email protected]/

Quoted 23 lines
   [0] https://github.com/kernel-patches/bpf/runs/6277764463?check_suite_focus=true#step:6:6130
Quoted 21 lines
  include/linux/bpf.h                           |  10 +
  include/net/tcp.h                             |   1 +
  include/uapi/linux/bpf.h                      |  88 +-
  kernel/bpf/verifier.c                         |  26 +-
  net/core/filter.c                             | 128 +++
  net/ipv4/tcp_input.c                          |   3 +-
  scripts/bpf_doc.py                            |   4 +
  tools/include/uapi/linux/bpf.h                |  88 +-
  tools/testing/selftests/bpf/.gitignore        |   1 +
  tools/testing/selftests/bpf/Makefile          |   5 +-
  .../selftests/bpf/prog_tests/xdp_synproxy.c   | 144 +++
  .../selftests/bpf/progs/xdp_synproxy_kern.c   | 819 ++++++++++++++++++
  tools/testing/selftests/bpf/xdp_synproxy.c    | 466 ++++++++++
  13 files changed, 1761 insertions(+), 22 deletions(-)

create mode 100644 tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c create mode 100644 tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c create mode 100644 tools/testing/selftests/bpf/xdp_synproxy.c

--
2.30.2

#17 lore raw
Quoted 86 lines · Maxim Mikityanskiy
Quoted 82 lines · Andrii Nakryiko
Quoted 73 lines · Maxim Mikityanskiy

The first patch of this series is a documentation fix.

The second patch allows BPF helpers to accept memory regions of fixed size without doing runtime size checks.

The two next patches add new functionality that allows XDP to accelerate iptables synproxy.

v1 of this series [1] used to include a patch that exposed conntrack lookup to BPF using stable helpers. It was superseded by series [2] by Kumar Kartikeya Dwivedi, which implements this functionality using unstable helpers.

The third patch adds new helpers to issue and check SYN cookies without binding to a socket, which is useful in the synproxy scenario.

The fourth patch adds a selftest, which includes an XDP program and a userspace control application. The XDP program uses socketless SYN cookie helpers and queries conntrack status instead of socket status. The userspace control application allows to tune parameters of the XDP program. This program also serves as a minimal example of usage of the new functionality.

The last patch exposes the new helpers to TC BPF.

The draft of the new functionality was presented on Netdev 0x15 [3].

v2 changes:

Split into two series, submitted bugfixes to bpf, dropped the conntrack patches, implemented the timestamp cookie in BPF using bpf_loop, dropped the timestamp cookie patch.

v3 changes:

Moved some patches from bpf to bpf-next, dropped the patch that changed error codes, split the new helpers into IPv4/IPv6, added verifier functionality to accept memory regions of fixed size.

v4 changes:

Converted the selftest to the test_progs runner. Replaced some deprecated functions in xdp_synproxy userspace helper.

v5 changes:

Fixed a bug in the selftest. Added questionable functionality to support new helpers in TC BPF, added selftests for it.

v6 changes:

Wrap the new helpers themselves into #ifdef CONFIG_SYN_COOKIES, replaced fclose with pclose and fixed the MSS for IPv6 in the selftest.

v7 changes:

Fixed the off-by-one error in indices, changed the section name to "xdp", added missing kernel config options to vmtest in CI.

v8 changes:

Properly rebased, dropped the first patch (the same change was applied by someone else), updated the cover letter.

v9 changes:

Fixed selftests for no_alu32.

[1]: https://lore.kernel.org/bpf/[email protected]/t/
[2]: https://lore.kernel.org/bpf/[email protected]/
[3]: https://netdevconf.info/0x15/session.html?Accelerating-synproxy-with-XDP

Quoted 7 lines

Maxim Mikityanskiy (5):
bpf: Fix documentation of th_len in bpf_tcp_{gen,check}_syncookie
bpf: Allow helpers to accept pointers with a fixed size
bpf: Add helpers to issue and check SYN cookies in XDP
bpf: Add selftests for raw syncookie helpers
bpf: Allow the new syncookie helpers to work with SKBs

Quoted 1 line

Is it expected that your selftests will fail on s390x? Please check [0]

Quoted 8 lines

I see it fails with:

test_synproxy:FAIL:ethtool -K tmp0 tx off unexpected error: 32512 (errno 2)

errno 2 is ENOENT, probably the ethtool binary is missing from the s390x image? When reviewing v6, you said you added ethtool to the CI image. Maybe it was added to x86_64 only? Could you add it to s390x?

Could be that it was outdated in s390x, but with [0] just merged in it should have pretty recent one.

[0] https://github.com/libbpf/ci/pull/16

Quoted 27 lines

[1]:
https://patchwork.kernel.org/project/netdevbpf/patch/[email protected]/

Quoted 23 lines
   [0] https://github.com/kernel-patches/bpf/runs/6277764463?check_suite_focus=true#step:6:6130
Quoted 21 lines
  include/linux/bpf.h                           |  10 +
  include/net/tcp.h                             |   1 +
  include/uapi/linux/bpf.h                      |  88 +-
  kernel/bpf/verifier.c                         |  26 +-
  net/core/filter.c                             | 128 +++
  net/ipv4/tcp_input.c                          |   3 +-
  scripts/bpf_doc.py                            |   4 +
  tools/include/uapi/linux/bpf.h                |  88 +-
  tools/testing/selftests/bpf/.gitignore        |   1 +
  tools/testing/selftests/bpf/Makefile          |   5 +-
  .../selftests/bpf/prog_tests/xdp_synproxy.c   | 144 +++
  .../selftests/bpf/progs/xdp_synproxy_kern.c   | 819 ++++++++++++++++++
  tools/testing/selftests/bpf/xdp_synproxy.c    | 466 ++++++++++
  13 files changed, 1761 insertions(+), 22 deletions(-)

create mode 100644 tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c create mode 100644 tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c create mode 100644 tools/testing/selftests/bpf/xdp_synproxy.c

--
2.30.2

#7 lore raw

Re: [PATCH bpf-next v9 3/5] bpf: Add helpers to issue and check SYN cookies in XDP

In reply to Maxim Mikityanskiy
Quoted 92 lines · Maxim Mikityanskiy
Quoted 81 lines · Andrii Nakryiko
Quoted 80 lines · Maxim Mikityanskiy

The new helpers bpf_tcp_raw_{gen,check}_syncookie_ipv{4,6} allow an XDP program to generate SYN cookies in response to TCP SYN packets and to check those cookies upon receiving the first ACK packet (the final packet of the TCP handshake).

Unlike bpf_tcp_{gen,check}_syncookie these new helpers don't need a listening socket on the local machine, which allows to use them together with synproxy to accelerate SYN cookie generation.

---
  include/net/tcp.h              |   1 +
  include/uapi/linux/bpf.h       |  78 ++++++++++++++++++++++
  net/core/filter.c              | 118 +++++++++++++++++++++++++++++++++
  net/ipv4/tcp_input.c           |   3 +-
  scripts/bpf_doc.py             |   4 ++
  tools/include/uapi/linux/bpf.h |  78 ++++++++++++++++++++++
  6 files changed, 281 insertions(+), 1 deletion(-)
include/net/tcp.h +1 -0
index 94a52ad1101c..45aafc28ce00 100644
@@ -432,6 +432,7 @@ u16 tcp_v4_get_syncookie(struct sock *sk, struct iphdr *iph,
                          struct tcphdr *th, u32 *cookie);
  u16 tcp_v6_get_syncookie(struct sock *sk, struct ipv6hdr *iph,
                          struct tcphdr *th, u32 *cookie);
+u16 tcp_parse_mss_option(const struct tcphdr *th, u16 user_mss);
  u16 tcp_get_syncookie_mss(struct request_sock_ops *rsk_ops,
                           const struct tcp_request_sock_ops *af_ops,
                           struct sock *sk, struct tcphdr *th);
include/uapi/linux/bpf.h +39 -0
index 4dd9e34f2a60..5e611d898302 100644
@@ -5156,6 +5156,80 @@ union bpf_attr {
   *             if not NULL, is a reference which must be released using its
   *             corresponding release function, or moved into a BPF map before
   *             program exit.
+ *
+ * s64 bpf_tcp_raw_gen_syncookie_ipv4(struct iphdr *iph, struct tcphdr *th, u32 th_len)
+ *     Description
+ *             Try to issue a SYN cookie for the packet with corresponding
+ *             IPv4/TCP headers, *iph* and *th*, without depending on a
+ *             listening socket.
+ *
+ *             *iph* points to the IPv4 header.
+ *
+ *             *th* points to the start of the TCP header, while *th_len*
+ *             contains the length of the TCP header (at least
+ *             **sizeof**\ (**struct tcphdr**)).
+ *     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** if *th_len* is invalid.
+ *
+ * s64 bpf_tcp_raw_gen_syncookie_ipv6(struct ipv6hdr *iph, struct tcphdr *th, u32 th_len)
+ *     Description
+ *             Try to issue a SYN cookie for the packet with corresponding
+ *             IPv6/TCP headers, *iph* and *th*, without depending on a
+ *             listening socket.
+ *
+ *             *iph* points to the IPv6 header.
+ *
+ *             *th* points to the start of the TCP header, while *th_len*
+ *             contains the length of the TCP header (at least
+ *             **sizeof**\ (**struct tcphdr**)).
+ *     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

include/uapi/linux/bpf.h union bpf_attr { · line 5202

Quoted 5 lines
include/uapi/linux/bpf.h +5 -0
+ *             **-EINVAL** if *th_len* is invalid.
+ *
+ *             **-EPROTONOSUPPORT** if CONFIG_IPV6 is not builtin.
+ *
+ * int bpf_tcp_raw_check_syncookie_ipv4(struct iphdr *iph, struct tcphdr *th)

Note that all existing helpers that just return error or 0 on success return long. Please use long for consistency.

Quoted 4 lines

OK. There are some existing helpers that return int, though:
bpf_inode_storage_delete, bpf_get_retval, bpf_set_retval. They should probably be fixed by someone as well.

Yep, they probably should, thanks for pointing missed cases out!

Quoted 36 lines
Quoted 35 lines
Quoted 5 lines
include/uapi/linux/bpf.h +5 -0
+ *     Description
+ *             Check whether *iph* and *th* contain a valid SYN cookie ACK
+ *             without depending on a listening socket.
+ *
+ *             *iph* points to the IPv4 header.

include/uapi/linux/bpf.h union bpf_attr { · line 5217

Quoted 10 lines
include/uapi/linux/bpf.h +10 -0
+ *
+ *             *th* points to the TCP header.
+ *     Return
+ *             0 if *iph* and *th* are a valid SYN cookie ACK.
+ *
+ *             On failure, the returned value is one of the following:
+ *
+ *             **-EACCES** if the SYN cookie is not valid.
+ *
+ * int bpf_tcp_raw_check_syncookie_ipv6(struct ipv6hdr *iph, struct tcphdr *th)

same

Quoted 15 lines
include/uapi/linux/bpf.h +15 -0
+ *     Description
+ *             Check whether *iph* and *th* contain a valid SYN cookie ACK
+ *             without depending on a listening socket.
+ *
+ *             *iph* points to the IPv6 header.
+ *
+ *             *th* points to the TCP header.
+ *     Return
+ *             0 if *iph* and *th* are a valid SYN cookie ACK.
+ *
+ *             On failure, the returned value is one of the following:
+ *
+ *             **-EACCES** if the SYN cookie is not valid.
+ *
+ *             **-EPROTONOSUPPORT** if CONFIG_IPV6 is not builtin.

[...]

#11 lore raw

Re: [PATCH bpf-next v9 4/5] bpf: Add selftests for raw syncookie helpers

In reply to Maxim Mikityanskiy
Quoted 72 lines · Maxim Mikityanskiy
Quoted 57 lines · Andrii Nakryiko
Quoted 12 lines · Maxim Mikityanskiy

This commit adds selftests for the new BPF helpers:
bpf_tcp_raw_{gen,check}_syncookie_ipv{4,6}.

xdp_synproxy_kern.c is a BPF program that generates SYN cookies on allowed TCP ports and sends SYNACKs to clients, accelerating synproxy iptables module.

xdp_synproxy.c is a userspace control application that allows to configure the following options in runtime: list of allowed ports, MSS, window scale, TTL.

Quoted 6 lines

A selftest is added to prog_tests that leverages the above programs to test the functionality of the new helpers.

---

selftests should use "selftests/bpf: " subject prefix, not "bpf: ", please update so it's more obvious that this patch touches selftests and not kernel-side BPF functionality.

Quoted 33 lines
  tools/testing/selftests/bpf/.gitignore        |   1 +
  tools/testing/selftests/bpf/Makefile          |   5 +-
  .../selftests/bpf/prog_tests/xdp_synproxy.c   | 109 +++
  .../selftests/bpf/progs/xdp_synproxy_kern.c   | 750 ++++++++++++++++++
  tools/testing/selftests/bpf/xdp_synproxy.c    | 418 ++++++++++
  5 files changed, 1281 insertions(+), 2 deletions(-)

create mode 100644 tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c create mode 100644 tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c create mode 100644 tools/testing/selftests/bpf/xdp_synproxy.c

tools/testing/selftests/bpf/.gitignore +1 -0
index 595565eb68c0..ca2f47f45670 100644
@@ -43,3 +43,4 @@ test_cpp
  *.tmp
  xdpxceiver
  xdp_redirect_multi
+xdp_synproxy
tools/testing/selftests/bpf/Makefile +2 -2
index bafdc5373a13..8ae602843b16 100644
@@ -82,9 +82,9 @@ TEST_PROGS_EXTENDED := with_addr.sh \
  TEST_GEN_PROGS_EXTENDED = test_sock_addr test_skb_cgroup_id_user \
         flow_dissector_load test_flow_dissector test_tcp_check_syncookie_user \
         test_lirc_mode2_user xdping test_cpp runqslower bench bpf_testmod.ko \
-       xdpxceiver xdp_redirect_multi
+       xdpxceiver xdp_redirect_multi xdp_synproxy
 
-TEST_CUSTOM_PROGS = $(OUTPUT)/urandom_read
+TEST_CUSTOM_PROGS = $(OUTPUT)/urandom_read $(OUTPUT)/xdp_synproxy
 
Quoted 12 lines

tools/testing/selftests/bpf/Makefile TRUNNER_EXTRA_SOURCES := test_progs.c cgroup_helpers.c trace_helpers.c \ · line 503

Quoted 7 lines
tools/testing/selftests/bpf/Makefile +1 -0
  # Emit succinct information message describing current building step
  # $1 - generic step name (e.g., CC, LINK, etc);
@@ -500,6 +500,7 @@ TRUNNER_EXTRA_SOURCES := test_progs.c cgroup_helpers.c trace_helpers.c      \
                          cap_helpers.c
  TRUNNER_EXTRA_FILES := $(OUTPUT)/urandom_read $(OUTPUT)/bpf_testmod.ko \
                        $(OUTPUT)/liburandom_read.so                     \
+                      $(OUTPUT)/xdp_synproxy                           \

this is the right way to make external binary available to test_progs flavors, but is there anything inherently requiring external binary instead of having a helper function doing the same? urandom_read has to be a separate binary.

Quoted 5 lines

If you remember v1, it used to be a sample, but I was asked to convert it to a selftest, because samples are deprecated. The intention of having this separate binary is to have a sample reference implementation that can be used in real-world scenarios with minor or no changes.

Ok, I'll let others chime in if they care enough about this. Selftests are first and foremost a test and not an almost production-ready collection of tools, but fine by me.

Quoted 82 lines
Quoted 73 lines
Quoted 42 lines
tools/testing/selftests/bpf/Makefile +0 -0
                        ima_setup.sh                                     \
                        $(wildcard progs/btf_dump_test_case_*.c)
  TRUNNER_BPF_BUILD_RULE := CLANG_BPF_BUILD_RULE
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +33 -0
new file mode 100644
index 000000000000..e08b28e25047
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <test_progs.h>
+#include <network_helpers.h>
+
+#define SYS(cmd) ({ \
+       if (!ASSERT_OK(system(cmd), (cmd))) \
+               goto out; \
+})
+
+#define SYS_OUT(cmd) ({ \
+       FILE *f = popen((cmd), "r"); \
+       if (!ASSERT_OK_PTR(f, (cmd))) \
+               goto out; \
+       f; \
+})
+
+static bool expect_str(char *buf, size_t size, const char *str)
+{
+       if (size != strlen(str))
+               return false;
+       return !memcmp(buf, str, size);
+}
+
+void test_xdp_synproxy(void)
+{
+       int server_fd = -1, client_fd = -1, accept_fd = -1;
+       struct nstoken *ns = NULL;
+       FILE *ctrl_file = NULL;
+       char buf[1024];
+       size_t size;
+
+       SYS("ip netns add synproxy");
+

tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c line 42

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +9 -0
+       SYS("ip link add tmp0 type veth peer name tmp1");
+       SYS("ip link set tmp1 netns synproxy");
+       SYS("ip link set tmp0 up");
+       SYS("ip addr replace 198.18.0.1/24 dev tmp0");
 
+
+       // When checksum offload is enabled, the XDP program sees wrong
+       // checksums and drops packets.
+       SYS("ethtool -K tmp0 tx off");
+       // Workaround required for veth.

don't use C++ comments, please stick to /* */

Quoted 18 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +18 -0
+       SYS("ip link set tmp0 xdp object xdp_dummy.o section xdp 2> /dev/null");
+
+       ns = open_netns("synproxy");
+       if (!ASSERT_OK_PTR(ns, "setns"))
+               goto out;
+
+       SYS("ip link set lo up");
+       SYS("ip link set tmp1 up");
+       SYS("ip addr replace 198.18.0.2/24 dev tmp1");
+       SYS("sysctl -w net.ipv4.tcp_syncookies=2");
+       SYS("sysctl -w net.ipv4.tcp_timestamps=1");
+       SYS("sysctl -w net.netfilter.nf_conntrack_tcp_loose=0");
+       SYS("iptables -t raw -I PREROUTING \
+           -i tmp1 -p tcp -m tcp --syn --dport 8080 -j CT --notrack");
+       SYS("iptables -t filter -A INPUT \
+           -i tmp1 -p tcp -m tcp --dport 8080 -m state --state INVALID,UNTRACKED \
+           -j SYNPROXY --sack-perm --timestamp --wscale 7 --mss 1460");
+       SYS("iptables -t filter -A INPUT \
Quoted 8 lines

tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c line 65

Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +5 -0
+           -i tmp1 -m state --state INVALID -j DROP");
+
+       ctrl_file = SYS_OUT("./xdp_synproxy --iface tmp1 --ports 8080 --single \
+                           --mss4 1460 --mss6 1440 --wscale 7 --ttl 64");
+       size = fread(buf, 1, sizeof(buf), ctrl_file);

buf is uninitialized so if fread fail strlen() can cause SIGSEGV or some other failure mode

Quoted 1 line

No, it will exit on the assert below (size won't be equal to strlen(str)).

it's better to use ASSERT_STREQ() which will also emit expected and actual strings if they don't match. So maybe check size first, and then ASSERT_STREQ() instead of custom expect_str() "helper"?

Quoted 34 lines
Quoted 25 lines
Quoted 25 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +23 -0
+       pclose(ctrl_file);
+       if (!ASSERT_TRUE(expect_str(buf, size, "Total SYNACKs generated: 0\n"),
+                        "initial SYNACKs"))
+               goto out;
+
+       server_fd = start_server(AF_INET, SOCK_STREAM, "198.18.0.2", 8080, 0);
+       if (!ASSERT_GE(server_fd, 0, "start_server"))
+               goto out;
+
+       close_netns(ns);
+       ns = NULL;
+
+       client_fd = connect_to_fd(server_fd, 10000);
+       if (!ASSERT_GE(client_fd, 0, "connect_to_fd"))
+               goto out;
+
+       accept_fd = accept(server_fd, NULL, NULL);
+       if (!ASSERT_GE(accept_fd, 0, "accept"))
+               goto out;
+
+       ns = open_netns("synproxy");
+       if (!ASSERT_OK_PTR(ns, "setns"))
+               goto out;
Quoted 8 lines

tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c line 94

Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +6 -0
+
+       ctrl_file = SYS_OUT("./xdp_synproxy --iface tmp1 --single");
+       size = fread(buf, 1, sizeof(buf), ctrl_file);
+       pclose(ctrl_file);
+       if (!ASSERT_TRUE(expect_str(buf, size, "Total SYNACKs generated: 1\n"),
+                        "SYNACKs after connection"))

please use ASSERT_STREQ instead, same above

Quoted 6 lines

It doesn't fit here for two reasons:

* It doesn't consider size (and ignoring size will cause a UB on errors because of the uninitialized buf).

* buf is not '\0'-terminated, and ASSERT_STREQ uses strcmp.

can it be non-zero-terminated in normal case? see above about checking for errors separately

Quoted 29 lines
Quoted 20 lines
Quoted 20 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +15 -0
+               goto out;
+
+out:
+       if (accept_fd >= 0)
+               close(accept_fd);
+       if (client_fd >= 0)
+               close(client_fd);
+       if (server_fd >= 0)
+               close(server_fd);
+       if (ns)
+               close_netns(ns);
+
+       system("ip link del tmp0");
+       system("ip netns del synproxy");
+}
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +0 -0
new file mode 100644
index 000000000000..9ae85b189072
Quoted 8 lines

tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c line 1

Quoted 4 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +1 -0
@@ -0,0 +1,750 @@
+// SPDX-License-Identifier: GPL-2.0 OR Linux-OpenIB

Can you please elaborate on what Linux-OpenIB license is and why GPL-2.0 isn't enough? We usually have GPL-2.0 or LGPL-2.1 OR BSD-2-Clause

Quoted 3 lines

That's the license boilerplate we use in the mlx5e driver. I'll check with the relevant people whether we can submit it as GPL-2.0 solely.

ok

Quoted 84 lines
Quoted 26 lines
Quoted 8 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +8 -0
+/* Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. */
+
+#include "vmlinux.h"
+
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_endian.h>
+#include <asm/errno.h>
+

[...]

tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c line 111

Quoted 12 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +12 -0
+
+static __always_inline __u16 csum_tcpudp_magic(__be32 saddr, __be32 daddr,
+                                              __u32 len, __u8 proto,
+                                              __u32 csum)
+{
+       __u64 s = csum;
+
+       s += (__u32)saddr;
+       s += (__u32)daddr;
+#if defined(__BIG_ENDIAN__)
+       s += proto + len;
+#elif defined(__LITTLE_ENDIAN__)

I've got few nudges in libbpf code base previously to use

Quoted 5 lines

#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__

instead (I don't remember the exact reason now, but there was a reason). Let's do the same here for consistency?

OK.

samples/bpf/xdpsock_user.c also still uses __BIG_ENDIAN__.

Quoted 17 lines
Quoted 17 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +17 -0
+       s += (proto + len) << 8;
+#else
+#error Unknown endian
+#endif
+       s = (s & 0xffffffff) + (s >> 32);
+       s = (s & 0xffffffff) + (s >> 32);
+
+       return csum_fold((__u32)s);
+}
+
+static __always_inline __u16 csum_ipv6_magic(const struct in6_addr *saddr,
+                                            const struct in6_addr *daddr,
+                                            __u32 len, __u8 proto, __u32 csum)
+{
+       __u64 sum = csum;
+       int i;
+
Quoted 8 lines

tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c line 133

Quoted 5 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +5 -0
+#pragma unroll
+       for (i = 0; i < 4; i++)
+               sum += (__u32)saddr->in6_u.u6_addr32[i];
+
+#pragma unroll

why unroll? BPF verifier handles such loops just fine, even if compiler decides to not unroll them

Optimization, see csum_ipv6_magic in net/ipv6/ip6_checksum.c that has this loop unrolled manually.

Quoted 10 lines
Quoted 10 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +10 -0
+       for (i = 0; i < 4; i++)
+               sum += (__u32)daddr->in6_u.u6_addr32[i];
+
+       // Don't combine additions to avoid 32-bit overflow.
+       sum += bpf_htonl(len);
+       sum += bpf_htonl(proto);
+
+       sum = (sum & 0xffffffff) + (sum >> 32);
+       sum = (sum & 0xffffffff) + (sum >> 32);
+
Quoted 8 lines

tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c line 147

Quoted 4 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +4 -0
+       return csum_fold((__u32)sum);
+}
+
+static __always_inline __u64 tcp_clock_ns(void)

__always_inline isn't mandatory, you can just have static __u64 tcp_clock_ns() here and let compiler decide on inlining? same for below

Quoted 7 lines

Do you mean just these three functions, or all functions below, or actually all functions in this file?

It's not mandatory, but these are simple one-liners, it would be unpleasant to waste an extra call in performance-critical code if the compiler decides not to inline them.

my point was that it's not mandatory anymore. Given this is a hybrid high-performance sample and selftest, I don't care. If it was just a test, there is no point in micro-optimizing this (similar for loop unrolling).

Quoted 17 lines
Quoted 17 lines
Quoted 14 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +14 -0
+{
+       return bpf_ktime_get_ns();
+}
+
+static __always_inline __u32 tcp_ns_to_ts(__u64 ns)
+{
+       return ns / (NSEC_PER_SEC / TCP_TS_HZ);
+}
+
+static __always_inline __u32 tcp_time_stamp_raw(void)
+{
+       return tcp_ns_to_ts(tcp_clock_ns());
+}
+

[...]

[...]

#12 lore raw

Re: [PATCH bpf-next v9 4/5] bpf: Add selftests for raw syncookie helpers

Quoted 165 lines · Andrii Nakryiko
Quoted 72 lines · Maxim Mikityanskiy
Quoted 57 lines · Andrii Nakryiko
Quoted 12 lines · Maxim Mikityanskiy

This commit adds selftests for the new BPF helpers:
bpf_tcp_raw_{gen,check}_syncookie_ipv{4,6}.

xdp_synproxy_kern.c is a BPF program that generates SYN cookies on allowed TCP ports and sends SYNACKs to clients, accelerating synproxy iptables module.

xdp_synproxy.c is a userspace control application that allows to configure the following options in runtime: list of allowed ports, MSS, window scale, TTL.

Quoted 6 lines

A selftest is added to prog_tests that leverages the above programs to test the functionality of the new helpers.

---

selftests should use "selftests/bpf: " subject prefix, not "bpf: ", please update so it's more obvious that this patch touches selftests and not kernel-side BPF functionality.

Quoted 33 lines
   tools/testing/selftests/bpf/.gitignore        |   1 +
   tools/testing/selftests/bpf/Makefile          |   5 +-
   .../selftests/bpf/prog_tests/xdp_synproxy.c   | 109 +++
   .../selftests/bpf/progs/xdp_synproxy_kern.c   | 750 ++++++++++++++++++
   tools/testing/selftests/bpf/xdp_synproxy.c    | 418 ++++++++++
   5 files changed, 1281 insertions(+), 2 deletions(-)

create mode 100644 tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c create mode 100644 tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c create mode 100644 tools/testing/selftests/bpf/xdp_synproxy.c

tools/testing/selftests/bpf/.gitignore +1 -0
index 595565eb68c0..ca2f47f45670 100644
@@ -43,3 +43,4 @@ test_cpp
   *.tmp
   xdpxceiver
   xdp_redirect_multi
+xdp_synproxy
tools/testing/selftests/bpf/Makefile +2 -2
index bafdc5373a13..8ae602843b16 100644
@@ -82,9 +82,9 @@ TEST_PROGS_EXTENDED := with_addr.sh \
   TEST_GEN_PROGS_EXTENDED = test_sock_addr test_skb_cgroup_id_user \
          flow_dissector_load test_flow_dissector test_tcp_check_syncookie_user \
          test_lirc_mode2_user xdping test_cpp runqslower bench bpf_testmod.ko \
-       xdpxceiver xdp_redirect_multi
+       xdpxceiver xdp_redirect_multi xdp_synproxy
 
-TEST_CUSTOM_PROGS = $(OUTPUT)/urandom_read
+TEST_CUSTOM_PROGS = $(OUTPUT)/urandom_read $(OUTPUT)/xdp_synproxy
 
Quoted 12 lines

tools/testing/selftests/bpf/Makefile TRUNNER_EXTRA_SOURCES := test_progs.c cgroup_helpers.c trace_helpers.c \ · line 503

Quoted 7 lines
tools/testing/selftests/bpf/Makefile +1 -0
   # Emit succinct information message describing current building step
   # $1 - generic step name (e.g., CC, LINK, etc);
@@ -500,6 +500,7 @@ TRUNNER_EXTRA_SOURCES := test_progs.c cgroup_helpers.c trace_helpers.c      \
                           cap_helpers.c
   TRUNNER_EXTRA_FILES := $(OUTPUT)/urandom_read $(OUTPUT)/bpf_testmod.ko \
                         $(OUTPUT)/liburandom_read.so                     \
+                      $(OUTPUT)/xdp_synproxy                           \

this is the right way to make external binary available to test_progs flavors, but is there anything inherently requiring external binary instead of having a helper function doing the same? urandom_read has to be a separate binary.

Quoted 5 lines

If you remember v1, it used to be a sample, but I was asked to convert it to a selftest, because samples are deprecated. The intention of having this separate binary is to have a sample reference implementation that can be used in real-world scenarios with minor or no changes.

Ok, I'll let others chime in if they care enough about this. Selftests are first and foremost a test and not an almost production-ready collection of tools, but fine by me.

Quoted 82 lines
Quoted 81 lines
Quoted 42 lines
tools/testing/selftests/bpf/Makefile +0 -0
                         ima_setup.sh                                     \
                         $(wildcard progs/btf_dump_test_case_*.c)
   TRUNNER_BPF_BUILD_RULE := CLANG_BPF_BUILD_RULE
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +33 -0
new file mode 100644
index 000000000000..e08b28e25047
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <test_progs.h>
+#include <network_helpers.h>
+
+#define SYS(cmd) ({ \
+       if (!ASSERT_OK(system(cmd), (cmd))) \
+               goto out; \
+})
+
+#define SYS_OUT(cmd) ({ \
+       FILE *f = popen((cmd), "r"); \
+       if (!ASSERT_OK_PTR(f, (cmd))) \
+               goto out; \
+       f; \
+})
+
+static bool expect_str(char *buf, size_t size, const char *str)
+{
+       if (size != strlen(str))
+               return false;
+       return !memcmp(buf, str, size);
+}
+
+void test_xdp_synproxy(void)
+{
+       int server_fd = -1, client_fd = -1, accept_fd = -1;
+       struct nstoken *ns = NULL;
+       FILE *ctrl_file = NULL;
+       char buf[1024];
+       size_t size;
+
+       SYS("ip netns add synproxy");
+

tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c line 42

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +9 -0
+       SYS("ip link add tmp0 type veth peer name tmp1");
+       SYS("ip link set tmp1 netns synproxy");
+       SYS("ip link set tmp0 up");
+       SYS("ip addr replace 198.18.0.1/24 dev tmp0");
 
+
+       // When checksum offload is enabled, the XDP program sees wrong
+       // checksums and drops packets.
+       SYS("ethtool -K tmp0 tx off");
+       // Workaround required for veth.

don't use C++ comments, please stick to /* */

Quoted 13 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +13 -0
+       SYS("ip link set tmp0 xdp object xdp_dummy.o section xdp 2> /dev/null");
+
+       ns = open_netns("synproxy");
+       if (!ASSERT_OK_PTR(ns, "setns"))
+               goto out;
+
+       SYS("ip link set lo up");
+       SYS("ip link set tmp1 up");
+       SYS("ip addr replace 198.18.0.2/24 dev tmp1");
+       SYS("sysctl -w net.ipv4.tcp_syncookies=2");
+       SYS("sysctl -w net.ipv4.tcp_timestamps=1");
+       SYS("sysctl -w net.netfilter.nf_conntrack_tcp_loose=0");
+       SYS("iptables -t raw -I PREROUTING \

tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c line 65

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +10 -0
+           -i tmp1 -p tcp -m tcp --syn --dport 8080 -j CT --notrack");
+       SYS("iptables -t filter -A INPUT \
+           -i tmp1 -p tcp -m tcp --dport 8080 -m state --state INVALID,UNTRACKED \
+           -j SYNPROXY --sack-perm --timestamp --wscale 7 --mss 1460");
+       SYS("iptables -t filter -A INPUT \
+           -i tmp1 -m state --state INVALID -j DROP");
+
+       ctrl_file = SYS_OUT("./xdp_synproxy --iface tmp1 --ports 8080 --single \
+                           --mss4 1460 --mss6 1440 --wscale 7 --ttl 64");
+       size = fread(buf, 1, sizeof(buf), ctrl_file);

buf is uninitialized so if fread fail strlen() can cause SIGSEGV or some other failure mode

Quoted 5 lines
Quoted 1 line

No, it will exit on the assert below (size won't be equal to strlen(str)).

it's better to use ASSERT_STREQ() which will also emit expected and actual strings if they don't match. So maybe check size first, and then ASSERT_STREQ() instead of custom expect_str() "helper"?

See below, the command's output is not a string.

If I extend my expect_str function to print the expected and actual outputs, would that work for you?

Quoted 36 lines
Quoted 36 lines
Quoted 25 lines
Quoted 25 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +23 -0
+       pclose(ctrl_file);
+       if (!ASSERT_TRUE(expect_str(buf, size, "Total SYNACKs generated: 0\n"),
+                        "initial SYNACKs"))
+               goto out;
+
+       server_fd = start_server(AF_INET, SOCK_STREAM, "198.18.0.2", 8080, 0);
+       if (!ASSERT_GE(server_fd, 0, "start_server"))
+               goto out;
+
+       close_netns(ns);
+       ns = NULL;
+
+       client_fd = connect_to_fd(server_fd, 10000);
+       if (!ASSERT_GE(client_fd, 0, "connect_to_fd"))
+               goto out;
+
+       accept_fd = accept(server_fd, NULL, NULL);
+       if (!ASSERT_GE(accept_fd, 0, "accept"))
+               goto out;
+
+       ns = open_netns("synproxy");
+       if (!ASSERT_OK_PTR(ns, "setns"))
+               goto out;
Quoted 8 lines

tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c line 94

Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +6 -0
+
+       ctrl_file = SYS_OUT("./xdp_synproxy --iface tmp1 --single");
+       size = fread(buf, 1, sizeof(buf), ctrl_file);
+       pclose(ctrl_file);
+       if (!ASSERT_TRUE(expect_str(buf, size, "Total SYNACKs generated: 1\n"),
+                        "SYNACKs after connection"))

please use ASSERT_STREQ instead, same above

It doesn't fit here for two reasons:

Quoted 7 lines
Quoted 4 lines

* It doesn't consider size (and ignoring size will cause a UB on errors because of the uninitialized buf).

* buf is not '\0'-terminated, and ASSERT_STREQ uses strcmp.

can it be non-zero-terminated in normal case? see above about checking for errors separately

fread(buf, x, y, file) just reads up to x*y bytes into buf. It doesn't treat it as a zero-terminated string, it can be any binary sequence of bytes. So, yes, in normal case it's going to be some printable characters WITHOUT any terminating '\0' (no one prints a '\0' to the terminal in normal cases). In bad cases it could be anything, including '\0' in the middle of the buffer, which would terminate strcmp early and can cause false positives.

Quoted 151 lines
Quoted 29 lines
Quoted 20 lines
Quoted 20 lines
tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c new file +15 -0
+               goto out;
+
+out:
+       if (accept_fd >= 0)
+               close(accept_fd);
+       if (client_fd >= 0)
+               close(client_fd);
+       if (server_fd >= 0)
+               close(server_fd);
+       if (ns)
+               close_netns(ns);
+
+       system("ip link del tmp0");
+       system("ip netns del synproxy");
+}
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +0 -0
new file mode 100644
index 000000000000..9ae85b189072
Quoted 8 lines

tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c line 1

Quoted 4 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +1 -0
@@ -0,0 +1,750 @@
+// SPDX-License-Identifier: GPL-2.0 OR Linux-OpenIB

Can you please elaborate on what Linux-OpenIB license is and why GPL-2.0 isn't enough? We usually have GPL-2.0 or LGPL-2.1 OR BSD-2-Clause

Quoted 3 lines

That's the license boilerplate we use in the mlx5e driver. I'll check with the relevant people whether we can submit it as GPL-2.0 solely.

ok

Quoted 84 lines
Quoted 26 lines
Quoted 8 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +8 -0
+/* Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. */
+
+#include "vmlinux.h"
+
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_endian.h>
+#include <asm/errno.h>
+

[...]

tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c line 111

Quoted 12 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +12 -0
+
+static __always_inline __u16 csum_tcpudp_magic(__be32 saddr, __be32 daddr,
+                                              __u32 len, __u8 proto,
+                                              __u32 csum)
+{
+       __u64 s = csum;
+
+       s += (__u32)saddr;
+       s += (__u32)daddr;
+#if defined(__BIG_ENDIAN__)
+       s += proto + len;
+#elif defined(__LITTLE_ENDIAN__)

I've got few nudges in libbpf code base previously to use

Quoted 5 lines

#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__

instead (I don't remember the exact reason now, but there was a reason). Let's do the same here for consistency?

OK.

samples/bpf/xdpsock_user.c also still uses __BIG_ENDIAN__.

Quoted 17 lines
Quoted 17 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +17 -0
+       s += (proto + len) << 8;
+#else
+#error Unknown endian
+#endif
+       s = (s & 0xffffffff) + (s >> 32);
+       s = (s & 0xffffffff) + (s >> 32);
+
+       return csum_fold((__u32)s);
+}
+
+static __always_inline __u16 csum_ipv6_magic(const struct in6_addr *saddr,
+                                            const struct in6_addr *daddr,
+                                            __u32 len, __u8 proto, __u32 csum)
+{
+       __u64 sum = csum;
+       int i;
+
Quoted 8 lines

tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c line 133

Quoted 5 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +5 -0
+#pragma unroll
+       for (i = 0; i < 4; i++)
+               sum += (__u32)saddr->in6_u.u6_addr32[i];
+
+#pragma unroll

why unroll? BPF verifier handles such loops just fine, even if compiler decides to not unroll them

Optimization, see csum_ipv6_magic in net/ipv6/ip6_checksum.c that has this loop unrolled manually.

Quoted 10 lines
Quoted 10 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +10 -0
+       for (i = 0; i < 4; i++)
+               sum += (__u32)daddr->in6_u.u6_addr32[i];
+
+       // Don't combine additions to avoid 32-bit overflow.
+       sum += bpf_htonl(len);
+       sum += bpf_htonl(proto);
+
+       sum = (sum & 0xffffffff) + (sum >> 32);
+       sum = (sum & 0xffffffff) + (sum >> 32);
+
Quoted 8 lines

tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c line 147

Quoted 4 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +4 -0
+       return csum_fold((__u32)sum);
+}
+
+static __always_inline __u64 tcp_clock_ns(void)

__always_inline isn't mandatory, you can just have static __u64 tcp_clock_ns() here and let compiler decide on inlining? same for below

Quoted 7 lines

Do you mean just these three functions, or all functions below, or actually all functions in this file?

It's not mandatory, but these are simple one-liners, it would be unpleasant to waste an extra call in performance-critical code if the compiler decides not to inline them.

my point was that it's not mandatory anymore. Given this is a hybrid high-performance sample and selftest, I don't care. If it was just a test, there is no point in micro-optimizing this (similar for loop unrolling).

Quoted 17 lines
Quoted 17 lines
Quoted 14 lines
tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c new file +14 -0
+{
+       return bpf_ktime_get_ns();
+}
+
+static __always_inline __u32 tcp_ns_to_ts(__u64 ns)
+{
+       return ns / (NSEC_PER_SEC / TCP_TS_HZ);
+}
+
+static __always_inline __u32 tcp_time_stamp_raw(void)
+{
+       return tcp_ns_to_ts(tcp_clock_ns());
+}
+

[...]

[...]

#18 lore raw
In reply to Andrii Nakryiko
Quoted 91 lines · Andrii Nakryiko
Quoted 90 lines · Maxim Mikityanskiy
Quoted 82 lines · Andrii Nakryiko
Quoted 73 lines · Maxim Mikityanskiy

The first patch of this series is a documentation fix.

The second patch allows BPF helpers to accept memory regions of fixed size without doing runtime size checks.

The two next patches add new functionality that allows XDP to accelerate iptables synproxy.

v1 of this series [1] used to include a patch that exposed conntrack lookup to BPF using stable helpers. It was superseded by series [2] by Kumar Kartikeya Dwivedi, which implements this functionality using unstable helpers.

The third patch adds new helpers to issue and check SYN cookies without binding to a socket, which is useful in the synproxy scenario.

The fourth patch adds a selftest, which includes an XDP program and a userspace control application. The XDP program uses socketless SYN cookie helpers and queries conntrack status instead of socket status. The userspace control application allows to tune parameters of the XDP program. This program also serves as a minimal example of usage of the new functionality.

The last patch exposes the new helpers to TC BPF.

The draft of the new functionality was presented on Netdev 0x15 [3].

v2 changes:

Split into two series, submitted bugfixes to bpf, dropped the conntrack patches, implemented the timestamp cookie in BPF using bpf_loop, dropped the timestamp cookie patch.

v3 changes:

Moved some patches from bpf to bpf-next, dropped the patch that changed error codes, split the new helpers into IPv4/IPv6, added verifier functionality to accept memory regions of fixed size.

v4 changes:

Converted the selftest to the test_progs runner. Replaced some deprecated functions in xdp_synproxy userspace helper.

v5 changes:

Fixed a bug in the selftest. Added questionable functionality to support new helpers in TC BPF, added selftests for it.

v6 changes:

Wrap the new helpers themselves into #ifdef CONFIG_SYN_COOKIES, replaced fclose with pclose and fixed the MSS for IPv6 in the selftest.

v7 changes:

Fixed the off-by-one error in indices, changed the section name to "xdp", added missing kernel config options to vmtest in CI.

v8 changes:

Properly rebased, dropped the first patch (the same change was applied by someone else), updated the cover letter.

v9 changes:

Fixed selftests for no_alu32.

[1]: https://lore.kernel.org/bpf/[email protected]/t/
[2]: https://lore.kernel.org/bpf/[email protected]/
[3]: https://netdevconf.info/0x15/session.html?Accelerating-synproxy-with-XDP

Quoted 7 lines

Maxim Mikityanskiy (5):
bpf: Fix documentation of th_len in bpf_tcp_{gen,check}_syncookie
bpf: Allow helpers to accept pointers with a fixed size
bpf: Add helpers to issue and check SYN cookies in XDP
bpf: Add selftests for raw syncookie helpers
bpf: Allow the new syncookie helpers to work with SKBs

Quoted 1 line

Is it expected that your selftests will fail on s390x? Please check [0]

I see it fails with:

test_synproxy:FAIL:ethtool -K tmp0 tx off unexpected error: 32512 (errno 2)

Quoted 7 lines
Quoted 4 lines

errno 2 is ENOENT, probably the ethtool binary is missing from the s390x image? When reviewing v6, you said you added ethtool to the CI image. Maybe it was added to x86_64 only? Could you add it to s390x?

Could be that it was outdated in s390x, but with [0] just merged in it should have pretty recent one.

Do you mean the image was outdated and didn't contain ethtool? Or ethtool was in the image, but was outdated? If the latter, I would expect it to work, this specific ethtool command has worked for ages.

Quoted 29 lines
   [0] https://github.com/libbpf/ci/pull/16
Quoted 27 lines

[1]:
https://patchwork.kernel.org/project/netdevbpf/patch/[email protected]/

Quoted 23 lines
    [0] https://github.com/kernel-patches/bpf/runs/6277764463?check_suite_focus=true#step:6:6130
Quoted 21 lines
   include/linux/bpf.h                           |  10 +
   include/net/tcp.h                             |   1 +
   include/uapi/linux/bpf.h                      |  88 +-
   kernel/bpf/verifier.c                         |  26 +-
   net/core/filter.c                             | 128 +++
   net/ipv4/tcp_input.c                          |   3 +-
   scripts/bpf_doc.py                            |   4 +
   tools/include/uapi/linux/bpf.h                |  88 +-
   tools/testing/selftests/bpf/.gitignore        |   1 +
   tools/testing/selftests/bpf/Makefile          |   5 +-
   .../selftests/bpf/prog_tests/xdp_synproxy.c   | 144 +++
   .../selftests/bpf/progs/xdp_synproxy_kern.c   | 819 ++++++++++++++++++
   tools/testing/selftests/bpf/xdp_synproxy.c    | 466 ++++++++++
   13 files changed, 1761 insertions(+), 22 deletions(-)

create mode 100644 tools/testing/selftests/bpf/prog_tests/xdp_synproxy.c create mode 100644 tools/testing/selftests/bpf/progs/xdp_synproxy_kern.c create mode 100644 tools/testing/selftests/bpf/xdp_synproxy.c

--
2.30.2

#19 lore raw
Quoted 16 lines · Maxim Mikityanskiy
Quoted 15 lines · Andrii Nakryiko
Quoted 13 lines · Maxim Mikityanskiy
Quoted 2 lines · Andrii Nakryiko

Is it expected that your selftests will fail on s390x? Please check [0]

I see it fails with:

test_synproxy:FAIL:ethtool -K tmp0 tx off unexpected error: 32512 (errno 2)

errno 2 is ENOENT, probably the ethtool binary is missing from the s390x image? When reviewing v6, you said you added ethtool to the CI image. Maybe it was added to x86_64 only? Could you add it to s390x?

Quoted 4 lines
Quoted 2 lines

Could be that it was outdated in s390x, but with [0] just merged in it should have pretty recent one.

Do you mean the image was outdated and didn't contain ethtool? Or ethtool was in the image, but was outdated? If the latter, I would expect it to work, this specific ethtool command has worked for ages.

Hi Andrii,

Could you reply this question? I need to understand whether I need to make any changes to the CI before resubmitting.

Thanks,
Max

#20 lore raw
Quoted 17 lines · Maxim Mikityanskiy
Quoted 16 lines · Maxim Mikityanskiy
Quoted 15 lines · Andrii Nakryiko
Quoted 13 lines · Maxim Mikityanskiy
Quoted 2 lines · Andrii Nakryiko

Is it expected that your selftests will fail on s390x? Please check [0]

I see it fails with:

test_synproxy:FAIL:ethtool -K tmp0 tx off unexpected error: 32512 (errno 2)

errno 2 is ENOENT, probably the ethtool binary is missing from the s390x image? When reviewing v6, you said you added ethtool to the CI image. Maybe it was added to x86_64 only? Could you add it to s390x?

Quoted 8 lines
Quoted 4 lines
Quoted 2 lines

Could be that it was outdated in s390x, but with [0] just merged in it should have pretty recent one.

Do you mean the image was outdated and didn't contain ethtool? Or ethtool was in the image, but was outdated? If the latter, I would expect it to work, this specific ethtool command has worked for ages.

Hi Andrii,

Could you reply this question? I need to understand whether I need to make any changes to the CI before resubmitting.

I brought up a s390x VM to run the test locally, and there are two issues with the latest (2022-05-09) s390x image:

1. It lacks stdbuf. stdbuf is used by tools/testing/selftests/bpf/vmtest.sh to run any test, and this is clearly broken. Hence two questions:

1.1. How does CI work without stdbuf in the image? I thought it used the same vmtest.sh script, is that right?

1.2. Who can add stdbuf to the image (to fix local runs)?

2. It lacks iptables needed by my test, so if I resubmit my series, it will fail on the CI again. Who can add iptables to the image?

I also compared the old (2021-03-24) and the new (2022-05-09) s390x images, and ethtool was indeed added only after my submission, so that explains the current CI error.

Quoted 2 lines

Thanks,
Max

#21 lore raw
Quoted 38 lines · Maxim Mikityanskiy
Quoted 24 lines · Maxim Mikityanskiy
Quoted 23 lines · Maxim Mikityanskiy
Quoted 21 lines · Andrii Nakryiko
Quoted 8 lines · Maxim Mikityanskiy
Quoted 3 lines · Andrii Nakryiko

Is it expected that your selftests will fail on s390x? Please check
[0]

I see it fails with:

Quoted 8 lines

test_synproxy:FAIL:ethtool -K tmp0 tx off unexpected error: 32512 (errno 2)

errno 2 is ENOENT, probably the ethtool binary is missing from the s390x
image? When reviewing v6, you said you added ethtool to the CI image. Maybe it was added to x86_64 only? Could you add it to s390x?

Could be that it was outdated in s390x, but with [0] just merged in it should have pretty recent one.

Quoted 8 lines
Quoted 3 lines

Do you mean the image was outdated and didn't contain ethtool? Or ethtool was in the image, but was outdated? If the latter, I would expect it to work, this specific ethtool command has worked for ages.

Hi Andrii,

Could you reply this question? I need to understand whether I need to make any changes to the CI before resubmitting.

I brought up a s390x VM to run the test locally, and there are two issues with the latest (2022-05-09) s390x image:

Quoted 6 lines

1. It lacks stdbuf. stdbuf is used by tools/testing/selftests/bpf/vmtest.sh to run any test, and this is clearly broken. Hence two questions:

1.1. How does CI work without stdbuf in the image? I thought it used the same vmtest.sh script, is that right?

no, CI doesn't use vmtest.sh. vmtest.sh is an approximation of what CI is doing, but it doesn't share the code/scripts (it does use the same kernel config and VM image, though)

Quoted 3 lines

1.2. Who can add stdbuf to the image (to fix local runs)?

For s390x things I usually ping Ilya. Ilya, can you help here please?

Quoted 2 lines

2. It lacks iptables needed by my test, so if I resubmit my series, it will fail on the CI again. Who can add iptables to the image?

Ditto, I'll defer to Ilya for this.

Quoted 8 lines

I also compared the old (2021-03-24) and the new (2022-05-09) s390x images, and ethtool was indeed added only after my submission, so that explains the current CI error.

Quoted 2 lines

Thanks,
Max