Skip to contentSkip to conversation

Add skb + xdp dynptrs

PATCH Applied Joanne Koong 9 participants 50 messages Mar 1, 2023 – Apr 12, 2023

Subsystems (9)
lore
Share & tools
lore
#0 lore raw

v13 cover Add skb + xdp dynptrs

This patchset is the 2nd in the dynptr series. The 1st can be found here [0].

This patchset adds skb and xdp type dynptrs, which have two main benefits for packet parsing:
* allowing operations on sizes that are not statically known at compile-time (eg variable-sized accesses).
* more ergonomic and less brittle iteration through data (eg does not need manual if checking for being within bounds of data_end)

When comparing the differences in runtime for packet parsing without dynptrs vs. with dynptrs, there is no noticeable difference. Patch 9 contains more details as well as examples of how to use skb and xdp dynptrs.

[0] https://lore.kernel.org/bpf/[email protected]/

--
Changelog:

v12 = https://lore.kernel.org/bpf/[email protected]/
v12 -> v13:
* Fix missing { } for case statement

v11 = https://lore.kernel.org/bpf/[email protected]/
v11 -> v12:
* Change constant mem size checking to use "__szk" kfunc annotation for slices
* Use autoloading for success selftests

v10 = https://lore.kernel.org/bpf/[email protected]/
v10 -> v11:
* Reject bpf_dynptr_slice_rdwr() for non-writable progs at load time instead of runtime
* Add additional patch (__uninit kfunc annotation)
* Expand on documentation
* Add bpf_dynptr_write() calls for persisting writes in tests

v9 = https://lore.kernel.org/bpf/[email protected]/
v9 -> v10:
* Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr interface
* Add some more tests
* Split up patchset into more parts to make it easier to review

v8 = https://lore.kernel.org/bpf/[email protected]/
v8 -> v9:
* Fix dynptr_get_type() to check non-stack dynptrs

v7 = https://lore.kernel.org/bpf/[email protected]/
v7 -> v8:
* Change helpers to kfuncs
* Add 2 new patches (1/5 and 2/5)

v6 = https://lore.kernel.org/bpf/[email protected]/
v6 -> v7
* Change bpf_dynptr_data() to return read-only data slices if the skb prog is read-only (Martin)
* Add test "skb_invalid_write" to test that writes to rd-only data slices are rejected

v5 = https://lore.kernel.org/bpf/[email protected]/
v5 -> v6
* Address kernel test robot errors by static inlining

v4 = https://lore.kernel.org/bpf/[email protected]/
v4 -> v5
* Address kernel test robot errors for configs w/out CONFIG_NET set
* For data slices, return PTR_TO_MEM instead of PTR_TO_PACKET (Kumar)
* Split selftests into subtests (Andrii)
* Remove insn patching. Use rdonly and rdwr protos for dynptr skb construction (Andrii)
* bpf_dynptr_data() returns NULL for rd-only dynptrs. There will be a separate bpf_dynptr_data_rdonly() added later (Andrii and Kumar)

v3 = https://lore.kernel.org/bpf/[email protected]/
v3 -> v4
* Forgot to commit --amend the kernel test robot error fixups

v2 = https://lore.kernel.org/bpf/[email protected]/
v2 -> v3
* Fix kernel test robot build test errors

v1 = https://lore.kernel.org/bpf/[email protected]/
v1 -> v2
* Return data slices to rd-only skb dynptrs (Martin)
* bpf_dynptr_write allows writes to frags for skb dynptrs, but always invalidates associated data slices (Martin)
* Use switch casing instead of ifs (Andrii)
* Use 0xFD for experimental kind number in the selftest (Zvi)
* Put selftest conversions w/ dynptrs into new files (Alexei)
* Add new selftest "test_cls_redirect_dynptr.c"

Joanne Koong (10):
bpf: Support "sk_buff" and "xdp_buff" as valid kfunc arg types
bpf: Refactor process_dynptr_func
bpf: Allow initializing dynptrs in kfuncs
bpf: Define no-ops for externally called bpf dynptr functions
bpf: Refactor verifier dynptr into get_dynptr_arg_reg
bpf: Add __uninit kfunc annotation
bpf: Add skb dynptrs
bpf: Add xdp dynptrs
bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr selftests/bpf: tests for using dynptrs to parse skb and xdp buffers

 Documentation/bpf/kfuncs.rst                  |  17 +
 include/linux/bpf.h                           |  95 +-
 include/linux/bpf_verifier.h                  |   3 -
 include/linux/filter.h                        |  46 +
 include/uapi/linux/bpf.h                      |  18 +-
 kernel/bpf/btf.c                              |  22 +
 kernel/bpf/helpers.c                          | 221 +++-
 kernel/bpf/verifier.c                         | 415 ++++++--
 net/core/filter.c                             | 108 +-
 tools/include/uapi/linux/bpf.h                |  18 +-
 tools/testing/selftests/bpf/bpf_kfuncs.h      |  38 +
 .../selftests/bpf/prog_tests/cls_redirect.c   |  25 +
 .../testing/selftests/bpf/prog_tests/dynptr.c |  74 +-
 .../selftests/bpf/prog_tests/l4lb_all.c       |   2 +
 .../bpf/prog_tests/parse_tcp_hdr_opt.c        |  93 ++
 .../selftests/bpf/prog_tests/xdp_attach.c     |  11 +-
 .../testing/selftests/bpf/progs/dynptr_fail.c | 287 ++++-
 .../selftests/bpf/progs/dynptr_success.c      |  55 +-
 .../bpf/progs/test_cls_redirect_dynptr.c      | 980 ++++++++++++++++++
 .../bpf/progs/test_l4lb_noinline_dynptr.c     | 487 +++++++++
 .../bpf/progs/test_parse_tcp_hdr_opt.c        | 119 +++
 .../bpf/progs/test_parse_tcp_hdr_opt_dynptr.c | 114 ++
 .../selftests/bpf/progs/test_xdp_dynptr.c     | 257 +++++
 .../selftests/bpf/test_tcp_hdr_options.h      |   1 +
 24 files changed, 3320 insertions(+), 186 deletions(-)
 create mode 100644 tools/testing/selftests/bpf/bpf_kfuncs.h
 create mode 100644 tools/testing/selftests/bpf/prog_tests/parse_tcp_hdr_opt.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_cls_redirect_dynptr.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_l4lb_noinline_dynptr.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_parse_tcp_hdr_opt.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_parse_tcp_hdr_opt_dynptr.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_xdp_dynptr.c
Signature · 1 line
2.34.1
#1 lore raw

PATCH v13 1/10 bpf: Support "sk_buff" and "xdp_buff" as valid kfunc arg types

The bpf mirror of the in-kernel sk_buff and xdp_buff data structures are __sk_buff and xdp_md. Currently, when we pass in the program ctx to a kfunc where the program ctx is a skb or xdp buffer, we reject the program if the in-kernel definition is sk_buff/xdp_buff instead of __sk_buff/xdp_md.

This change allows "sk_buff <--> __sk_buff" and "xdp_buff <--> xdp_md" to be recognized as valid matches. The user program may pass in their program ctx as a __sk_buff or xdp_md, and the in-kernel definition of the kfunc may define this arg as a sk_buff or xdp_buff.

---
 kernel/bpf/btf.c | 4 ++++
 1 file changed, 4 insertions(+)
kernel/bpf/btf.c +4 -0
index fa22ec79ac0e..84cca8473873 100644
@@ -5683,6 +5683,10 @@ btf_get_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
 	 * int socket_filter_bpf_prog(struct __sk_buff *skb)
 	 * { // no fields of skb are ever used }
 	 */
+	if (strcmp(ctx_tname, "__sk_buff") == 0 && strcmp(tname, "sk_buff") == 0)
+		return ctx_type;
+	if (strcmp(ctx_tname, "xdp_md") == 0 && strcmp(tname, "xdp_buff") == 0)
+		return ctx_type;
 	if (strcmp(ctx_tname, tname)) {
 		/* bpf_user_pt_regs_t is a typedef, so resolve it to
 		 * underlying struct and check name again
Signature · 1 line
2.34.1
#2 lore raw

PATCH v13 2/10 bpf: Refactor process_dynptr_func

In reply to Joanne Koong

This change cleans up process_dynptr_func's flow to be more intuitive and updates some comments with more context.

---
 include/linux/bpf_verifier.h |  3 --
 kernel/bpf/verifier.c        | 62 ++++++++++++++++++------------------
 2 files changed, 31 insertions(+), 34 deletions(-)
include/linux/bpf_verifier.h +0 -3
index cf1bb1cf4a7b..b26ff2a8f63b 100644
@@ -616,9 +616,6 @@ int check_func_arg_reg_off(struct bpf_verifier_env *env,
 			   enum bpf_arg_type arg_type);
 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
 		   u32 regno, u32 mem_size);
-struct bpf_call_arg_meta;
-int process_dynptr_func(struct bpf_verifier_env *env, int regno,
-			enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta);
 
 /* this lives here instead of in bpf.h because it needs to dereference tgt_prog */
 static inline u64 bpf_trampoline_compute_key(const struct bpf_prog *tgt_prog,
kernel/bpf/verifier.c +31 -31

110 lines not on this page · raw message

Signature · 1 line
2.34.1
#3 lore raw

PATCH v13 3/10 bpf: Allow initializing dynptrs in kfuncs

In reply to Joanne Koong

This change allows kfuncs to take in an uninitialized dynptr as a parameter. Before this change, only helper functions could successfully use uninitialized dynptrs. This change moves the memory access check (including stack state growing and slot marking) into process_dynptr_func(), which both helpers and kfuncs call into.

---
 kernel/bpf/verifier.c | 67 ++++++++++++++-----------------------------
 1 file changed, 22 insertions(+), 45 deletions(-)
kernel/bpf/verifier.c +22 -45
index e0e00509846b..82e39fc5ed05 100644
@@ -268,7 +268,6 @@ struct bpf_call_arg_meta {
 	u32 ret_btf_id;
 	u32 subprogno;
 	struct btf_field *kptr_field;
-	u8 uninit_dynptr_regno;
 };
 
 struct btf *btf_vmlinux;
@@ -6225,10 +6224,11 @@ static int process_kptr_func(struct bpf_verifier_env *env, int regno,
  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
  */
-static int process_dynptr_func(struct bpf_verifier_env *env, int regno,
-			       enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta)
+static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
+			       enum bpf_arg_type arg_type)
 {
 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
+	int err;
 
 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
@@ -6254,23 +6254,23 @@ static int process_dynptr_func(struct bpf_verifier_env *env, int regno,
 	 *		 to.
 	 */
 	if (arg_type & MEM_UNINIT) {
+		int i;
+
 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
 			return -EINVAL;
 		}
 
-		/* We only support one dynptr being uninitialized at the moment,
-		 * which is sufficient for the helper functions we have right now.
-		 */
-		if (meta->uninit_dynptr_regno) {
-			verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
-			return -EFAULT;
+		/* we write BPF_DW bits (8 bytes) at a time */
+		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
+			err = check_mem_access(env, insn_idx, regno,
+					       i, BPF_DW, BPF_WRITE, -1, false);
+			if (err)
+				return err;
 		}
 
-		meta->uninit_dynptr_regno = regno;
+		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx);
 	} else /* MEM_RDONLY and None case from above */ {
-		int err;
-
 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
@@ -6306,10 +6306,8 @@ static int process_dynptr_func(struct bpf_verifier_env *env, int regno,
 		}
 
 		err = mark_dynptr_read(env, reg);
-		if (err)
-			return err;
 	}
-	return 0;
+	return err;
 }
 
 static bool arg_type_is_mem_size(enum bpf_arg_type type)
@@ -6719,7 +6717,8 @@ static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state
 
 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
 			  struct bpf_call_arg_meta *meta,
-			  const struct bpf_func_proto *fn)
+			  const struct bpf_func_proto *fn,
+			  int insn_idx)
 {
 	u32 regno = BPF_REG_1 + arg;
 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
@@ -6932,7 +6931,7 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
 		err = check_mem_size_reg(env, reg, regno, true, meta);
 		break;
 	case ARG_PTR_TO_DYNPTR:
-		err = process_dynptr_func(env, regno, arg_type, meta);
+		err = process_dynptr_func(env, regno, insn_idx, arg_type);
 		if (err)
 			return err;
 		break;
@@ -8218,7 +8217,7 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
 	meta.func_id = func_id;
 	/* check args */
 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
-		err = check_func_arg(env, i, &meta, fn);
+		err = check_func_arg(env, i, &meta, fn, insn_idx);
 		if (err)
 			return err;
 	}
@@ -8243,30 +8242,6 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
 
 	regs = cur_regs(env);
 
-	/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
-	 * be reinitialized by any dynptr helper. Hence, mark_stack_slots_dynptr
-	 * is safe to do directly.
-	 */
-	if (meta.uninit_dynptr_regno) {
-		if (regs[meta.uninit_dynptr_regno].type == CONST_PTR_TO_DYNPTR) {
-			verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be initialized\n");
-			return -EFAULT;
-		}
-		/* we write BPF_DW bits (8 bytes) at a time */
-		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
-			err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
-					       i, BPF_DW, BPF_WRITE, -1, false);
-			if (err)
-				return err;
-		}
-
-		err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
-					      fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
-					      insn_idx);
-		if (err)
-			return err;
-	}
-
 	if (meta.release_regno) {
 		err = -EINVAL;
 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
@@ -9475,7 +9450,8 @@ static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
 						  &meta->arg_rbtree_root.field);
 }
 
-static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta)
+static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
+			    int insn_idx)
 {
 	const char *func_name = meta->func_name, *ref_tname;
 	const struct btf *btf = meta->btf;
@@ -9672,7 +9648,8 @@ static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_
 				return -EINVAL;
 			}
 
-			ret = process_dynptr_func(env, regno, ARG_PTR_TO_DYNPTR | MEM_RDONLY, NULL);
+			ret = process_dynptr_func(env, regno, insn_idx,
+						  ARG_PTR_TO_DYNPTR | MEM_RDONLY);
 			if (ret < 0)
 				return ret;
 			break;
@@ -9880,7 +9857,7 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 	}
 
 	/* Check the arguments */
-	err = check_kfunc_args(env, &meta);
+	err = check_kfunc_args(env, &meta, insn_idx);
 	if (err < 0)
 		return err;
 	/* In case of release function, we get register number of refcounted
Signature · 1 line
2.34.1
#4 lore raw

Re: [PATCH v13 bpf-next 03/10] bpf: Allow initializing dynptrs in kfuncs

Quoted 51 lines · Joanne Koong

This change allows kfuncs to take in an uninitialized dynptr as a parameter. Before this change, only helper functions could successfully use uninitialized dynptrs. This change moves the memory access check (including stack state growing and slot marking) into process_dynptr_func(), which both helpers and kfuncs call into.

---
 kernel/bpf/verifier.c | 67 ++++++++++++++-----------------------------
 1 file changed, 22 insertions(+), 45 deletions(-)
kernel/bpf/verifier.c +5 -6
index e0e00509846b..82e39fc5ed05 100644
@@ -268,7 +268,6 @@ struct bpf_call_arg_meta {
 	u32 ret_btf_id;
 	u32 subprogno;
 	struct btf_field *kptr_field;
-	u8 uninit_dynptr_regno;
 };
 
 struct btf *btf_vmlinux;
@@ -6225,10 +6224,11 @@ static int process_kptr_func(struct bpf_verifier_env *env, int regno,
  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
  */
-static int process_dynptr_func(struct bpf_verifier_env *env, int regno,
-			       enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta)
+static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
+			       enum bpf_arg_type arg_type)
 {
 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
+	int err;
 
 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
@@ -6254,23 +6254,23 @@ static int process_dynptr_func(struct bpf_verifier_env *env, int regno,
 	 *		 to.
 	 */
 	if (arg_type & MEM_UNINIT) {
+		int i;
+
 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
 			return -EINVAL;
 		}
 
-		/* We only support one dynptr being uninitialized at the moment,
-		 * which is sufficient for the helper functions we have right now.
-		 */

kernel/bpf/verifier.c static int process_dynptr_func(struct bpf_verifier_env *env, int regno, · line 6270

Quoted 10 lines
kernel/bpf/verifier.c +6 -3
-		if (meta->uninit_dynptr_regno) {
-			verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
-			return -EFAULT;
+		/* we write BPF_DW bits (8 bytes) at a time */
+		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
+			err = check_mem_access(env, insn_idx, regno,
+					       i, BPF_DW, BPF_WRITE, -1, false);
+			if (err)
+				return err;
 		}

I am not sure moving check_mem_access into process_dynptr_func is the right thing to do. Not sure if a problem already, but sooner or later it might be.

The side effects of the call should take effect on the current state only after we have gone through all arguments for the helper/kfunc call. In this case we will now do stack access while processing the dynptr arg, which may affect the state of stack we see through other memory arguments coming later.

I think it is better to do it after argument processing is done, similar to existing meta.access_size handling which is done after check_func_arg loop (for the same reasons).

Quoted 1 line

[...]

#5 lore raw

Re: [PATCH v13 bpf-next 03/10] bpf: Allow initializing dynptrs in kfuncs

Quoted 67 lines · Kumar Kartikeya Dwivedi
Quoted 51 lines · Joanne Koong

This change allows kfuncs to take in an uninitialized dynptr as a parameter. Before this change, only helper functions could successfully use uninitialized dynptrs. This change moves the memory access check (including stack state growing and slot marking) into process_dynptr_func(), which both helpers and kfuncs call into.

---
 kernel/bpf/verifier.c | 67 ++++++++++++++-----------------------------
 1 file changed, 22 insertions(+), 45 deletions(-)
kernel/bpf/verifier.c +5 -6
index e0e00509846b..82e39fc5ed05 100644
@@ -268,7 +268,6 @@ struct bpf_call_arg_meta {
      u32 ret_btf_id;
      u32 subprogno;
      struct btf_field *kptr_field;
-     u8 uninit_dynptr_regno;
 };
 
 struct btf *btf_vmlinux;
@@ -6225,10 +6224,11 @@ static int process_kptr_func(struct bpf_verifier_env *env, int regno,
  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
  */
-static int process_dynptr_func(struct bpf_verifier_env *env, int regno,
-                            enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta)
+static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
+                            enum bpf_arg_type arg_type)
 {
      struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
+     int err;
 
      /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
       * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
@@ -6254,23 +6254,23 @@ static int process_dynptr_func(struct bpf_verifier_env *env, int regno,
       *               to.
       */
      if (arg_type & MEM_UNINIT) {
+             int i;
+
              if (!is_dynptr_reg_valid_uninit(env, reg)) {
                      verbose(env, "Dynptr has to be an uninitialized dynptr\n");
                      return -EINVAL;
              }
 
-             /* We only support one dynptr being uninitialized at the moment,
-              * which is sufficient for the helper functions we have right now.
-              */

kernel/bpf/verifier.c static int process_dynptr_func(struct bpf_verifier_env *env, int regno, · line 6270

Quoted 10 lines
kernel/bpf/verifier.c +6 -3
-             if (meta->uninit_dynptr_regno) {
-                     verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
-                     return -EFAULT;
+             /* we write BPF_DW bits (8 bytes) at a time */
+             for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
+                     err = check_mem_access(env, insn_idx, regno,
+                                            i, BPF_DW, BPF_WRITE, -1, false);
+                     if (err)
+                             return err;
              }

I am not sure moving check_mem_access into process_dynptr_func is the right thing to do. Not sure if a problem already, but sooner or later it might be.

Quoted 9 lines

The side effects of the call should take effect on the current state only after we have gone through all arguments for the helper/kfunc call. In this case we will now do stack access while processing the dynptr arg, which may affect the state of stack we see through other memory arguments coming later.

I think it is better to do it after argument processing is done, similar to existing meta.access_size handling which is done after check_func_arg loop (for the same reasons).

Thanks for taking a look. I don't have a strong preference for either so if you do feel strongly about doing the check_mem_access() only after argument processing, I'm happy to change it. The check_mem_access() call on the dyntpr will mark only the dynptr stack slots, so I don't fully see how it may affect the state of stack through other memory arguments coming later, but I do see your point about keeping the logic more separated out.

Quoted 1 line
Quoted 1 line

[...]

#6 lore raw

Re: [PATCH v13 bpf-next 03/10] bpf: Allow initializing dynptrs in kfuncs

Quoted 80 lines · Joanne Koong
Quoted 67 lines · Kumar Kartikeya Dwivedi
Quoted 51 lines · Joanne Koong

This change allows kfuncs to take in an uninitialized dynptr as a parameter. Before this change, only helper functions could successfully use uninitialized dynptrs. This change moves the memory access check (including stack state growing and slot marking) into process_dynptr_func(), which both helpers and kfuncs call into.

---
 kernel/bpf/verifier.c | 67 ++++++++++++++-----------------------------
 1 file changed, 22 insertions(+), 45 deletions(-)
kernel/bpf/verifier.c +5 -6
index e0e00509846b..82e39fc5ed05 100644
@@ -268,7 +268,6 @@ struct bpf_call_arg_meta {
      u32 ret_btf_id;
      u32 subprogno;
      struct btf_field *kptr_field;
-     u8 uninit_dynptr_regno;
 };
 
 struct btf *btf_vmlinux;
@@ -6225,10 +6224,11 @@ static int process_kptr_func(struct bpf_verifier_env *env, int regno,
  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
  */
-static int process_dynptr_func(struct bpf_verifier_env *env, int regno,
-                            enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta)
+static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
+                            enum bpf_arg_type arg_type)
 {
      struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
+     int err;
 
      /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
       * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
@@ -6254,23 +6254,23 @@ static int process_dynptr_func(struct bpf_verifier_env *env, int regno,
       *               to.
       */
      if (arg_type & MEM_UNINIT) {
+             int i;
+
              if (!is_dynptr_reg_valid_uninit(env, reg)) {
                      verbose(env, "Dynptr has to be an uninitialized dynptr\n");
                      return -EINVAL;
              }
 
-             /* We only support one dynptr being uninitialized at the moment,
-              * which is sufficient for the helper functions we have right now.
-              */

kernel/bpf/verifier.c static int process_dynptr_func(struct bpf_verifier_env *env, int regno, · line 6270

Quoted 10 lines
kernel/bpf/verifier.c +6 -3
-             if (meta->uninit_dynptr_regno) {
-                     verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
-                     return -EFAULT;
+             /* we write BPF_DW bits (8 bytes) at a time */
+             for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
+                     err = check_mem_access(env, insn_idx, regno,
+                                            i, BPF_DW, BPF_WRITE, -1, false);
+                     if (err)
+                             return err;
              }

I am not sure moving check_mem_access into process_dynptr_func is the right thing to do. Not sure if a problem already, but sooner or later it might be.

Quoted 9 lines

The side effects of the call should take effect on the current state only after we have gone through all arguments for the helper/kfunc call. In this case we will now do stack access while processing the dynptr arg, which may affect the state of stack we see through other memory arguments coming later.

I think it is better to do it after argument processing is done, similar to existing meta.access_size handling which is done after check_func_arg loop (for the same reasons).

Quoted 7 lines

Thanks for taking a look. I don't have a strong preference for either so if you do feel strongly about doing the check_mem_access() only after argument processing, I'm happy to change it. The check_mem_access() call on the dyntpr will mark only the dynptr stack slots, so I don't fully see how it may affect the state of stack through other memory arguments coming later, but I do see your point about keeping the logic more separated out.

FWIW, I did a similar approach for iters as well. And I suspect it's not the only place where we do similar things while processing helper arguments, etc.

Let's keep this in mind, but I wouldn't necessarily go complicating code right now with more of "let's record some info for later" and then "ok, we recorded something before, let's act on it".

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

[...]

#7 lore raw

PATCH v13 4/10 bpf: Define no-ops for externally called bpf dynptr functions

In reply to Joanne Koong

Some bpf dynptr functions will be called from places where if CONFIG_BPF_SYSCALL is not set, then the dynptr function is undefined. For example, when skb type dynptrs are added in the next commit, dynptr functions are called from net/core/filter.c

This patch defines no-op implementations of these dynptr functions so that they do not break compilation by being an undefined reference.

---
 include/linux/bpf.h | 75 +++++++++++++++++++++++++++------------------
 1 file changed, 45 insertions(+), 30 deletions(-)
include/linux/bpf.h +45 -30
index 520b238abd5a..296841a31749 100644
@@ -1124,6 +1124,33 @@ static __always_inline __nocfi unsigned int bpf_dispatcher_nop_func(
 	return bpf_func(ctx, insnsi);
 }
 
+/* the implementation of the opaque uapi struct bpf_dynptr */
+struct bpf_dynptr_kern {
+	void *data;
+	/* Size represents the number of usable bytes of dynptr data.
+	 * If for example the offset is at 4 for a local dynptr whose data is
+	 * of type u64, the number of usable bytes is 4.
+	 *
+	 * The upper 8 bits are reserved. It is as follows:
+	 * Bits 0 - 23 = size
+	 * Bits 24 - 30 = dynptr type
+	 * Bit 31 = whether dynptr is read-only
+	 */
+	u32 size;
+	u32 offset;
+} __aligned(8);
+
+enum bpf_dynptr_type {
+	BPF_DYNPTR_TYPE_INVALID,
+	/* Points to memory that is local to the bpf program */
+	BPF_DYNPTR_TYPE_LOCAL,
+	/* Underlying data is a ringbuf record */
+	BPF_DYNPTR_TYPE_RINGBUF,
+};
+
+int bpf_dynptr_check_size(u32 size);
+u32 bpf_dynptr_get_size(const struct bpf_dynptr_kern *ptr);
+
 #ifdef CONFIG_BPF_JIT
 int bpf_trampoline_link_prog(struct bpf_tramp_link *link, struct bpf_trampoline *tr);
 int bpf_trampoline_unlink_prog(struct bpf_tramp_link *link, struct bpf_trampoline *tr);
@@ -2266,6 +2293,11 @@ static inline bool has_current_bpf_ctx(void)
 }
 
 void notrace bpf_prog_inc_misses_counter(struct bpf_prog *prog);
+
+void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data,
+		     enum bpf_dynptr_type type, u32 offset, u32 size);
+void bpf_dynptr_set_null(struct bpf_dynptr_kern *ptr);
+void bpf_dynptr_set_rdonly(struct bpf_dynptr_kern *ptr);
 #else /* !CONFIG_BPF_SYSCALL */
 static inline struct bpf_prog *bpf_prog_get(u32 ufd)
 {
@@ -2495,6 +2527,19 @@ static inline void bpf_prog_inc_misses_counter(struct bpf_prog *prog)
 static inline void bpf_cgrp_storage_free(struct cgroup *cgroup)
 {
 }
+
+static inline void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data,
+				   enum bpf_dynptr_type type, u32 offset, u32 size)
+{
+}
+
+static inline void bpf_dynptr_set_null(struct bpf_dynptr_kern *ptr)
+{
+}
+
+static inline void bpf_dynptr_set_rdonly(struct bpf_dynptr_kern *ptr)
+{
+}
 #endif /* CONFIG_BPF_SYSCALL */
 
 void __bpf_free_used_btfs(struct bpf_prog_aux *aux,
@@ -2913,36 +2958,6 @@ int bpf_bprintf_prepare(char *fmt, u32 fmt_size, const u64 *raw_args,
 			u32 num_args, struct bpf_bprintf_data *data);
 void bpf_bprintf_cleanup(struct bpf_bprintf_data *data);
 
-/* the implementation of the opaque uapi struct bpf_dynptr */
-struct bpf_dynptr_kern {
-	void *data;
-	/* Size represents the number of usable bytes of dynptr data.
-	 * If for example the offset is at 4 for a local dynptr whose data is
-	 * of type u64, the number of usable bytes is 4.
-	 *
-	 * The upper 8 bits are reserved. It is as follows:
-	 * Bits 0 - 23 = size
-	 * Bits 24 - 30 = dynptr type
-	 * Bit 31 = whether dynptr is read-only
-	 */
-	u32 size;
-	u32 offset;
-} __aligned(8);
-
-enum bpf_dynptr_type {
-	BPF_DYNPTR_TYPE_INVALID,
-	/* Points to memory that is local to the bpf program */
-	BPF_DYNPTR_TYPE_LOCAL,
-	/* Underlying data is a kernel-produced ringbuf record */
-	BPF_DYNPTR_TYPE_RINGBUF,
-};
-
-void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data,
-		     enum bpf_dynptr_type type, u32 offset, u32 size);
-void bpf_dynptr_set_null(struct bpf_dynptr_kern *ptr);
-int bpf_dynptr_check_size(u32 size);
-u32 bpf_dynptr_get_size(const struct bpf_dynptr_kern *ptr);
-
 #ifdef CONFIG_BPF_LSM
 void bpf_cgroup_atype_get(u32 attach_btf_id, int cgroup_atype);
 void bpf_cgroup_atype_put(int cgroup_atype);
Signature · 1 line
2.34.1
#8 lore raw

PATCH v13 5/10 bpf: Refactor verifier dynptr into get_dynptr_arg_reg

In reply to Joanne Koong

This commit refactors the logic for determining which register in a function is the dynptr into "get_dynptr_arg_reg". This will be used in the future when the dynptr reg for BPF_FUNC_dynptr_write will need to be obtained in order to support writes for skb dynptrs.

---
 kernel/bpf/verifier.c | 80 +++++++++++++++++++++++++++----------------
 1 file changed, 50 insertions(+), 30 deletions(-)
kernel/bpf/verifier.c +50 -30
index 82e39fc5ed05..8fd2f26a8977 100644
@@ -6689,6 +6689,28 @@ int check_func_arg_reg_off(struct bpf_verifier_env *env,
 	}
 }
 
+static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
+						const struct bpf_func_proto *fn,
+						struct bpf_reg_state *regs)
+{
+	struct bpf_reg_state *state = NULL;
+	int i;
+
+	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
+		if (arg_type_is_dynptr(fn->arg_type[i])) {
+			if (state) {
+				verbose(env, "verifier internal error: multiple dynptr args\n");
+				return NULL;
+			}
+			state = &regs[BPF_REG_1 + i];
+		}
+
+	if (!state)
+		verbose(env, "verifier internal error: no dynptr arg found\n");
+
+	return state;
+}
+
 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
 {
 	struct bpf_func_state *state = func(env, reg);
@@ -8326,43 +8348,41 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
 		}
 		break;
 	case BPF_FUNC_dynptr_data:
-		for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
-			if (arg_type_is_dynptr(fn->arg_type[i])) {
-				struct bpf_reg_state *reg = &regs[BPF_REG_1 + i];
-				int id, ref_obj_id;
-
-				if (meta.dynptr_id) {
-					verbose(env, "verifier internal error: meta.dynptr_id already set\n");
-					return -EFAULT;
-				}
-
-				if (meta.ref_obj_id) {
-					verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
-					return -EFAULT;
-				}
+	{
+		struct bpf_reg_state *reg;
+		int id, ref_obj_id;
 
-				id = dynptr_id(env, reg);
-				if (id < 0) {
-					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
-					return id;
-				}
+		reg = get_dynptr_arg_reg(env, fn, regs);
+		if (!reg)
+			return -EFAULT;
 
-				ref_obj_id = dynptr_ref_obj_id(env, reg);
-				if (ref_obj_id < 0) {
-					verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
-					return ref_obj_id;
-				}
 
-				meta.dynptr_id = id;
-				meta.ref_obj_id = ref_obj_id;
-				break;
-			}
+		if (meta.dynptr_id) {
+			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
+			return -EFAULT;
 		}
-		if (i == MAX_BPF_FUNC_REG_ARGS) {
-			verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
+		if (meta.ref_obj_id) {
+			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
 			return -EFAULT;
 		}
+
+		id = dynptr_id(env, reg);
+		if (id < 0) {
+			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
+			return id;
+		}
+
+		ref_obj_id = dynptr_ref_obj_id(env, reg);
+		if (ref_obj_id < 0) {
+			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
+			return ref_obj_id;
+		}
+
+		meta.dynptr_id = id;
+		meta.ref_obj_id = ref_obj_id;
+
 		break;
+	}
 	case BPF_FUNC_user_ringbuf_drain:
 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
 					set_user_ringbuf_callback_state);
Signature · 1 line
2.34.1
#9 lore raw

PATCH v13 6/10 bpf: Add __uninit kfunc annotation

In reply to Joanne Koong

This patch adds __uninit as a kfunc annotation.

This will be useful for scenarios such as for example in dynptrs, indicating whether the dynptr should be checked by the verifier as an initialized or an uninitialized dynptr.

Without this annotation, the alternative would be needing to hard-code in the verifier the specific kfunc to indicate that arg should be treated as an uninitialized arg.

---
 Documentation/bpf/kfuncs.rst | 17 +++++++++++++++++
 kernel/bpf/verifier.c        | 18 ++++++++++++++++--
 2 files changed, 33 insertions(+), 2 deletions(-)
Documentation/bpf/kfuncs.rst +17 -0
index 226313747be5..9a78533d25ac 100644
@@ -100,6 +100,23 @@ Hence, whenever a constant scalar argument is accepted by a kfunc which is not a
 size parameter, and the value of the constant matters for program safety, __k
 suffix should be used.
 
+2.2.2 __uninit Annotation
+--------------------
+
+This annotation is used to indicate that the argument will be treated as
+uninitialized.
+
+An example is given below::
+
+        __bpf_kfunc int bpf_dynptr_from_skb(..., struct bpf_dynptr_kern *ptr__uninit)
+        {
+        ...
+        }
+
+Here, the dynptr will be treated as an uninitialized dynptr. Without this
+annotation, the verifier will reject the program if the dynptr passed in is
+not initialized.
+
 .. _BPF_kfunc_nodef:
 
 2.3 Using an existing kernel function
kernel/bpf/verifier.c +16 -2
index 8fd2f26a8977..d052aa5800de 100644
@@ -8727,6 +8727,11 @@ static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param
 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
 }
 
+static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
+{
+	return __kfunc_param_match_suffix(btf, arg, "__uninit");
+}
+
 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
 					  const struct btf_param *arg,
 					  const char *name)
@@ -9662,17 +9667,26 @@ static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_
 				return ret;
 			break;
 		case KF_ARG_PTR_TO_DYNPTR:
+		{
+			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
+
 			if (reg->type != PTR_TO_STACK &&
 			    reg->type != CONST_PTR_TO_DYNPTR) {
 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
 				return -EINVAL;
 			}
 
-			ret = process_dynptr_func(env, regno, insn_idx,
-						  ARG_PTR_TO_DYNPTR | MEM_RDONLY);
+			if (reg->type == CONST_PTR_TO_DYNPTR)
+				dynptr_arg_type |= MEM_RDONLY;
+
+			if (is_kfunc_arg_uninit(btf, &args[i]))
+				dynptr_arg_type |= MEM_UNINIT;
+
+			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type);
 			if (ret < 0)
 				return ret;
 			break;
+		}
 		case KF_ARG_PTR_TO_LIST_HEAD:
 			if (reg->type != PTR_TO_MAP_VALUE &&
 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
Signature · 1 line
2.34.1
#10 lore raw

PATCH v13 7/10 bpf: Add skb dynptrs

In reply to Joanne Koong

Add skb dynptrs, which are dynptrs whose underlying pointer points to a skb. The dynptr acts on skb data. skb dynptrs have two main benefits. One is that they allow operations on sizes that are not statically known at compile-time (eg variable-sized accesses). Another is that parsing the packet data through dynptrs (instead of through direct access of skb->data and skb->data_end) can be more ergonomic and less brittle (eg does not need manual if checking for being within bounds of data_end).

For bpf prog types that don't support writes on skb data, the dynptr is read-only (bpf_dynptr_write() will return an error)

For reads and writes through the bpf_dynptr_read() and bpf_dynptr_write() interfaces, reading and writing from/to data in the head as well as from/to non-linear paged buffers is supported. Data slices through the bpf_dynptr_data API are not supported; instead bpf_dynptr_slice() and bpf_dynptr_slice_rdwr() (added in subsequent commit) should be used.

For examples of how skb dynptrs can be used, please see the attached selftests.

---
 include/linux/bpf.h            | 14 ++++++-
 include/linux/filter.h         | 18 ++++++++
 include/uapi/linux/bpf.h       | 13 +++++-
 kernel/bpf/btf.c               | 18 ++++++++
 kernel/bpf/helpers.c           | 76 +++++++++++++++++++++++++++-------
 kernel/bpf/verifier.c          | 61 +++++++++++++++++++++++++++
 net/core/filter.c              | 67 ++++++++++++++++++++++++++++++
 tools/include/uapi/linux/bpf.h | 13 +++++-
 8 files changed, 261 insertions(+), 19 deletions(-)
include/linux/bpf.h +13 -1
index 296841a31749..e7436d7615b0 100644
@@ -607,11 +607,14 @@ enum bpf_type_flag {
 	 */
 	NON_OWN_REF		= BIT(14 + BPF_BASE_TYPE_BITS),
 
+	/* DYNPTR points to sk_buff */
+	DYNPTR_TYPE_SKB		= BIT(15 + BPF_BASE_TYPE_BITS),
+
 	__BPF_TYPE_FLAG_MAX,
 	__BPF_TYPE_LAST_FLAG	= __BPF_TYPE_FLAG_MAX - 1,
 };
 
-#define DYNPTR_TYPE_FLAG_MASK	(DYNPTR_TYPE_LOCAL | DYNPTR_TYPE_RINGBUF)
+#define DYNPTR_TYPE_FLAG_MASK	(DYNPTR_TYPE_LOCAL | DYNPTR_TYPE_RINGBUF | DYNPTR_TYPE_SKB)
 
 /* Max number of base types. */
 #define BPF_BASE_TYPE_LIMIT	(1UL << BPF_BASE_TYPE_BITS)
@@ -1146,6 +1149,8 @@ enum bpf_dynptr_type {
 	BPF_DYNPTR_TYPE_LOCAL,
 	/* Underlying data is a ringbuf record */
 	BPF_DYNPTR_TYPE_RINGBUF,
+	/* Underlying data is a sk_buff */
+	BPF_DYNPTR_TYPE_SKB,
 };
 
 int bpf_dynptr_check_size(u32 size);
@@ -2846,6 +2851,8 @@ u32 bpf_sock_convert_ctx_access(enum bpf_access_type type,
 				struct bpf_insn *insn_buf,
 				struct bpf_prog *prog,
 				u32 *target_size);
+int bpf_dynptr_from_skb_rdonly(struct sk_buff *skb, u64 flags,
+			       struct bpf_dynptr_kern *ptr);
 #else
 static inline bool bpf_sock_common_is_valid_access(int off, int size,
 						   enum bpf_access_type type,
@@ -2867,6 +2874,11 @@ static inline u32 bpf_sock_convert_ctx_access(enum bpf_access_type type,
 {
 	return 0;
 }
+static inline int bpf_dynptr_from_skb_rdonly(struct sk_buff *skb, u64 flags,
+					     struct bpf_dynptr_kern *ptr)
+{
+	return -EOPNOTSUPP;
+}
 #endif
 
 #ifdef CONFIG_INET
include/linux/filter.h +18 -0
index 1727898f1641..de18e844d15e 100644
@@ -1542,4 +1542,22 @@ static __always_inline int __bpf_xdp_redirect_map(struct bpf_map *map, u64 index
 	return XDP_REDIRECT;
 }
 
+#ifdef CONFIG_NET
+int __bpf_skb_load_bytes(const struct sk_buff *skb, u32 offset, void *to, u32 len);
+int __bpf_skb_store_bytes(struct sk_buff *skb, u32 offset, const void *from,
+			  u32 len, u64 flags);
+#else /* CONFIG_NET */
+static inline int __bpf_skb_load_bytes(const struct sk_buff *skb, u32 offset,
+				       void *to, u32 len)
+{
+	return -EOPNOTSUPP;
+}
+
+static inline int __bpf_skb_store_bytes(struct sk_buff *skb, u32 offset,
+					const void *from, u32 len, u64 flags)
+{
+	return -EOPNOTSUPP;
+}
+#endif /* CONFIG_NET */
+
 #endif /* __LINUX_FILTER_H__ */
include/uapi/linux/bpf.h +11 -2
index 62ce1f5d1b1d..d0351d30e551 100644
@@ -5325,11 +5325,17 @@ union bpf_attr {
  *	Description
  *		Write *len* bytes from *src* into *dst*, starting from *offset*
  *		into *dst*.
- *		*flags* is currently unused.
+ *
+ *		*flags* must be 0 except for skb-type dynptrs.
+ *
+ *		For skb-type dynptrs:
+ *		    *  For *flags*, please see the flags accepted by
+ *		       **bpf_skb_store_bytes**\ ().
  *	Return
  *		0 on success, -E2BIG if *offset* + *len* exceeds the length
  *		of *dst*'s data, -EINVAL if *dst* is an invalid dynptr or if *dst*
- *		is a read-only dynptr or if *flags* is not 0.
+ *		is a read-only dynptr or if *flags* is not correct. For skb-type dynptrs,
+ *		other errors correspond to errors returned by **bpf_skb_store_bytes**\ ().
  *
  * void *bpf_dynptr_data(const struct bpf_dynptr *ptr, u32 offset, u32 len)
  *	Description
@@ -5337,6 +5343,9 @@ union bpf_attr {
  *
  *		*len* must be a statically known value. The returned data slice
  *		is invalidated whenever the dynptr is invalidated.
+ *
+ *		skb type dynptrs may not use bpf_dynptr_data. They should
+ *		instead use bpf_dynptr_slice and bpf_dynptr_slice_rdwr.
  *	Return
  *		Pointer to the underlying dynptr data, NULL if the dynptr is
  *		read-only, if the dynptr is invalid, or if the offset and length
kernel/bpf/btf.c +18 -0
index 84cca8473873..ef2d8969ed1f 100644
@@ -207,6 +207,11 @@ enum btf_kfunc_hook {
 	BTF_KFUNC_HOOK_TRACING,
 	BTF_KFUNC_HOOK_SYSCALL,
 	BTF_KFUNC_HOOK_FMODRET,
+	BTF_KFUNC_HOOK_CGROUP_SKB,
+	BTF_KFUNC_HOOK_SCHED_ACT,
+	BTF_KFUNC_HOOK_SK_SKB,
+	BTF_KFUNC_HOOK_SOCKET_FILTER,
+	BTF_KFUNC_HOOK_LWT,
 	BTF_KFUNC_HOOK_MAX,
 };
 
@@ -7708,6 +7713,19 @@ static int bpf_prog_type_to_kfunc_hook(enum bpf_prog_type prog_type)
 		return BTF_KFUNC_HOOK_TRACING;
 	case BPF_PROG_TYPE_SYSCALL:
 		return BTF_KFUNC_HOOK_SYSCALL;
+	case BPF_PROG_TYPE_CGROUP_SKB:
+		return BTF_KFUNC_HOOK_CGROUP_SKB;
+	case BPF_PROG_TYPE_SCHED_ACT:
+		return BTF_KFUNC_HOOK_SCHED_ACT;
+	case BPF_PROG_TYPE_SK_SKB:
+		return BTF_KFUNC_HOOK_SK_SKB;
+	case BPF_PROG_TYPE_SOCKET_FILTER:
+		return BTF_KFUNC_HOOK_SOCKET_FILTER;
+	case BPF_PROG_TYPE_LWT_OUT:
+	case BPF_PROG_TYPE_LWT_IN:
+	case BPF_PROG_TYPE_LWT_XMIT:
+	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
+		return BTF_KFUNC_HOOK_LWT;
 	default:
 		return BTF_KFUNC_HOOK_MAX;
 	}
kernel/bpf/helpers.c +62 -14

127 lines not on this page · raw message

kernel/bpf/verifier.c +61 -0

115 lines not on this page · raw message

net/core/filter.c +67 -0

82 lines not on this page · raw message

tools/include/uapi/linux/bpf.h +11 -2
index 62ce1f5d1b1d..d0351d30e551 100644
@@ -5325,11 +5325,17 @@ union bpf_attr {
  *	Description
  *		Write *len* bytes from *src* into *dst*, starting from *offset*
  *		into *dst*.
- *		*flags* is currently unused.
+ *
+ *		*flags* must be 0 except for skb-type dynptrs.
+ *
+ *		For skb-type dynptrs:
+ *		    *  For *flags*, please see the flags accepted by
+ *		       **bpf_skb_store_bytes**\ ().
  *	Return
  *		0 on success, -E2BIG if *offset* + *len* exceeds the length
  *		of *dst*'s data, -EINVAL if *dst* is an invalid dynptr or if *dst*
- *		is a read-only dynptr or if *flags* is not 0.
+ *		is a read-only dynptr or if *flags* is not correct. For skb-type dynptrs,
+ *		other errors correspond to errors returned by **bpf_skb_store_bytes**\ ().
  *
  * void *bpf_dynptr_data(const struct bpf_dynptr *ptr, u32 offset, u32 len)
  *	Description
@@ -5337,6 +5343,9 @@ union bpf_attr {
  *
  *		*len* must be a statically known value. The returned data slice
  *		is invalidated whenever the dynptr is invalidated.
+ *
+ *		skb type dynptrs may not use bpf_dynptr_data. They should
+ *		instead use bpf_dynptr_slice and bpf_dynptr_slice_rdwr.
  *	Return
  *		Pointer to the underlying dynptr data, NULL if the dynptr is
  *		read-only, if the dynptr is invalid, or if the offset and length
Signature · 1 line
2.34.1
#11 lore raw

PATCH v13 8/10 bpf: Add xdp dynptrs

In reply to Joanne Koong

Add xdp dynptrs, which are dynptrs whose underlying pointer points to a xdp_buff. The dynptr acts on xdp data. xdp dynptrs have two main benefits. One is that they allow operations on sizes that are not statically known at compile-time (eg variable-sized accesses). Another is that parsing the packet data through dynptrs (instead of through direct access of xdp->data and xdp->data_end) can be more ergonomic and less brittle (eg does not need manual if checking for being within bounds of data_end).

For reads and writes on the dynptr, this includes reading/writing from/to and across fragments. Data slices through the bpf_dynptr_data API are not supported; instead bpf_dynptr_slice() and bpf_dynptr_slice_rdwr() should be used.

For examples of how xdp dynptrs can be used, please see the attached selftests.

---
 include/linux/bpf.h            |  8 +++++++-
 include/linux/filter.h         | 14 +++++++++++++
 include/uapi/linux/bpf.h       |  2 +-
 kernel/bpf/helpers.c           |  9 ++++++++-
 kernel/bpf/verifier.c          | 10 +++++++++
 net/core/filter.c              | 37 ++++++++++++++++++++++++++++++++--
 tools/include/uapi/linux/bpf.h |  2 +-
 7 files changed, 76 insertions(+), 6 deletions(-)
include/linux/bpf.h +7 -1
index e7436d7615b0..23ec684e660d 100644
@@ -610,11 +610,15 @@ enum bpf_type_flag {
 	/* DYNPTR points to sk_buff */
 	DYNPTR_TYPE_SKB		= BIT(15 + BPF_BASE_TYPE_BITS),
 
+	/* DYNPTR points to xdp_buff */
+	DYNPTR_TYPE_XDP		= BIT(16 + BPF_BASE_TYPE_BITS),
+
 	__BPF_TYPE_FLAG_MAX,
 	__BPF_TYPE_LAST_FLAG	= __BPF_TYPE_FLAG_MAX - 1,
 };
 
-#define DYNPTR_TYPE_FLAG_MASK	(DYNPTR_TYPE_LOCAL | DYNPTR_TYPE_RINGBUF | DYNPTR_TYPE_SKB)
+#define DYNPTR_TYPE_FLAG_MASK	(DYNPTR_TYPE_LOCAL | DYNPTR_TYPE_RINGBUF | DYNPTR_TYPE_SKB \
+				 | DYNPTR_TYPE_XDP)
 
 /* Max number of base types. */
 #define BPF_BASE_TYPE_LIMIT	(1UL << BPF_BASE_TYPE_BITS)
@@ -1151,6 +1155,8 @@ enum bpf_dynptr_type {
 	BPF_DYNPTR_TYPE_RINGBUF,
 	/* Underlying data is a sk_buff */
 	BPF_DYNPTR_TYPE_SKB,
+	/* Underlying data is a xdp_buff */
+	BPF_DYNPTR_TYPE_XDP,
 };
 
 int bpf_dynptr_check_size(u32 size);
include/linux/filter.h +14 -0
index de18e844d15e..3f6992261ec5 100644
@@ -1546,6 +1546,8 @@ static __always_inline int __bpf_xdp_redirect_map(struct bpf_map *map, u64 index
 int __bpf_skb_load_bytes(const struct sk_buff *skb, u32 offset, void *to, u32 len);
 int __bpf_skb_store_bytes(struct sk_buff *skb, u32 offset, const void *from,
 			  u32 len, u64 flags);
+int __bpf_xdp_load_bytes(struct xdp_buff *xdp, u32 offset, void *buf, u32 len);
+int __bpf_xdp_store_bytes(struct xdp_buff *xdp, u32 offset, void *buf, u32 len);
 #else /* CONFIG_NET */
 static inline int __bpf_skb_load_bytes(const struct sk_buff *skb, u32 offset,
 				       void *to, u32 len)
@@ -1558,6 +1560,18 @@ static inline int __bpf_skb_store_bytes(struct sk_buff *skb, u32 offset,
 {
 	return -EOPNOTSUPP;
 }
+
+static inline int __bpf_xdp_load_bytes(struct xdp_buff *xdp, u32 offset,
+				       void *buf, u32 len)
+{
+	return -EOPNOTSUPP;
+}
+
+static inline int __bpf_xdp_store_bytes(struct xdp_buff *xdp, u32 offset,
+					void *buf, u32 len)
+{
+	return -EOPNOTSUPP;
+}
 #endif /* CONFIG_NET */
 
 #endif /* __LINUX_FILTER_H__ */
include/uapi/linux/bpf.h +1 -1
index d0351d30e551..faa304c926cf 100644
@@ -5344,7 +5344,7 @@ union bpf_attr {
  *		*len* must be a statically known value. The returned data slice
  *		is invalidated whenever the dynptr is invalidated.
  *
- *		skb type dynptrs may not use bpf_dynptr_data. They should
+ *		skb and xdp type dynptrs may not use bpf_dynptr_data. They should
  *		instead use bpf_dynptr_slice and bpf_dynptr_slice_rdwr.
  *	Return
  *		Pointer to the underlying dynptr data, NULL if the dynptr is
kernel/bpf/helpers.c +8 -1
index e8e2414d1587..114a875a05b1 100644
@@ -1530,6 +1530,8 @@ BPF_CALL_5(bpf_dynptr_read, void *, dst, u32, len, const struct bpf_dynptr_kern
 		return 0;
 	case BPF_DYNPTR_TYPE_SKB:
 		return __bpf_skb_load_bytes(src->data, src->offset + offset, dst, len);
+	case BPF_DYNPTR_TYPE_XDP:
+		return __bpf_xdp_load_bytes(src->data, src->offset + offset, dst, len);
 	default:
 		WARN_ONCE(true, "bpf_dynptr_read: unknown dynptr type %d\n", type);
 		return -EFAULT;
@@ -1576,6 +1578,10 @@ BPF_CALL_5(bpf_dynptr_write, const struct bpf_dynptr_kern *, dst, u32, offset, v
 	case BPF_DYNPTR_TYPE_SKB:
 		return __bpf_skb_store_bytes(dst->data, dst->offset + offset, src, len,
 					     flags);
+	case BPF_DYNPTR_TYPE_XDP:
+		if (flags)
+			return -EINVAL;
+		return __bpf_xdp_store_bytes(dst->data, dst->offset + offset, src, len);
 	default:
 		WARN_ONCE(true, "bpf_dynptr_write: unknown dynptr type %d\n", type);
 		return -EFAULT;
@@ -1615,7 +1621,8 @@ BPF_CALL_3(bpf_dynptr_data, const struct bpf_dynptr_kern *, ptr, u32, offset, u3
 	case BPF_DYNPTR_TYPE_RINGBUF:
 		return (unsigned long)(ptr->data + ptr->offset + offset);
 	case BPF_DYNPTR_TYPE_SKB:
-		/* skb dynptrs should use bpf_dynptr_slice / bpf_dynptr_slice_rdwr */
+	case BPF_DYNPTR_TYPE_XDP:
+		/* skb and xdp dynptrs should use bpf_dynptr_slice / bpf_dynptr_slice_rdwr */
 		return 0;
 	default:
 		WARN_ONCE(true, "bpf_dynptr_data: unknown dynptr type %d\n", type);
kernel/bpf/verifier.c +10 -0
index 4f5fce16543b..5e42946e53ab 100644
@@ -752,6 +752,8 @@ static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
 		return BPF_DYNPTR_TYPE_RINGBUF;
 	case DYNPTR_TYPE_SKB:
 		return BPF_DYNPTR_TYPE_SKB;
+	case DYNPTR_TYPE_XDP:
+		return BPF_DYNPTR_TYPE_XDP;
 	default:
 		return BPF_DYNPTR_TYPE_INVALID;
 	}
@@ -6300,6 +6302,9 @@ static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn
 			case DYNPTR_TYPE_SKB:
 				err_extra = "skb ";
 				break;
+			case DYNPTR_TYPE_XDP:
+				err_extra = "xdp ";
+				break;
 			default:
 				err_extra = "<unknown>";
 				break;
@@ -8943,6 +8948,7 @@ enum special_kfunc_type {
 	KF_bpf_rbtree_add,
 	KF_bpf_rbtree_first,
 	KF_bpf_dynptr_from_skb,
+	KF_bpf_dynptr_from_xdp,
 };
 
 BTF_SET_START(special_kfunc_set)
@@ -8958,6 +8964,7 @@ BTF_ID(func, bpf_rbtree_remove)
 BTF_ID(func, bpf_rbtree_add)
 BTF_ID(func, bpf_rbtree_first)
 BTF_ID(func, bpf_dynptr_from_skb)
+BTF_ID(func, bpf_dynptr_from_xdp)
 BTF_SET_END(special_kfunc_set)
 
 BTF_ID_LIST(special_kfunc_list)
@@ -8975,6 +8982,7 @@ BTF_ID(func, bpf_rbtree_remove)
 BTF_ID(func, bpf_rbtree_add)
 BTF_ID(func, bpf_rbtree_first)
 BTF_ID(func, bpf_dynptr_from_skb)
+BTF_ID(func, bpf_dynptr_from_xdp)
 
 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
 {
@@ -9731,6 +9739,8 @@ static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_
 
 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb])
 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
+			else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp])
+				dynptr_arg_type |= DYNPTR_TYPE_XDP;
 
 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type);
 			if (ret < 0)
net/core/filter.c +35 -2
index f3afa31a9b10..c692046fa7f6 100644
@@ -3839,7 +3839,7 @@ static const struct bpf_func_proto sk_skb_change_head_proto = {
 	.arg3_type	= ARG_ANYTHING,
 };
 
-BPF_CALL_1(bpf_xdp_get_buff_len, struct  xdp_buff*, xdp)
+BPF_CALL_1(bpf_xdp_get_buff_len, struct xdp_buff*, xdp)
 {
 	return xdp_get_buff_len(xdp);
 }
@@ -3999,6 +3999,11 @@ static const struct bpf_func_proto bpf_xdp_load_bytes_proto = {
 	.arg4_type	= ARG_CONST_SIZE,
 };
 
+int __bpf_xdp_load_bytes(struct xdp_buff *xdp, u32 offset, void *buf, u32 len)
+{
+	return ____bpf_xdp_load_bytes(xdp, offset, buf, len);
+}
+
 BPF_CALL_4(bpf_xdp_store_bytes, struct xdp_buff *, xdp, u32, offset,
 	   void *, buf, u32, len)
 {
@@ -4026,6 +4031,11 @@ static const struct bpf_func_proto bpf_xdp_store_bytes_proto = {
 	.arg4_type	= ARG_CONST_SIZE,
 };
 
+int __bpf_xdp_store_bytes(struct xdp_buff *xdp, u32 offset, void *buf, u32 len)
+{
+	return ____bpf_xdp_store_bytes(xdp, offset, buf, len);
+}
+
 static int bpf_xdp_frags_increase_tail(struct xdp_buff *xdp, int offset)
 {
 	struct skb_shared_info *sinfo = xdp_get_shared_info_from_buff(xdp);
@@ -11648,6 +11658,19 @@ __bpf_kfunc int bpf_dynptr_from_skb(struct sk_buff *skb, u64 flags,
 
 	return 0;
 }
+
+__bpf_kfunc int bpf_dynptr_from_xdp(struct xdp_buff *xdp, u64 flags,
+				    struct bpf_dynptr_kern *ptr__uninit)
+{
+	if (flags) {
+		bpf_dynptr_set_null(ptr__uninit);
+		return -EINVAL;
+	}
+
+	bpf_dynptr_init(ptr__uninit, xdp, BPF_DYNPTR_TYPE_XDP, 0, xdp_get_buff_len(xdp));
+
+	return 0;
+}
 __diag_pop();
 
 int bpf_dynptr_from_skb_rdonly(struct sk_buff *skb, u64 flags,
@@ -11668,11 +11691,20 @@ BTF_SET8_START(bpf_kfunc_check_set_skb)
 BTF_ID_FLAGS(func, bpf_dynptr_from_skb)
 BTF_SET8_END(bpf_kfunc_check_set_skb)
 
+BTF_SET8_START(bpf_kfunc_check_set_xdp)
+BTF_ID_FLAGS(func, bpf_dynptr_from_xdp)
+BTF_SET8_END(bpf_kfunc_check_set_xdp)
+
 static const struct btf_kfunc_id_set bpf_kfunc_set_skb = {
 	.owner = THIS_MODULE,
 	.set = &bpf_kfunc_check_set_skb,
 };
 
+static const struct btf_kfunc_id_set bpf_kfunc_set_xdp = {
+	.owner = THIS_MODULE,
+	.set = &bpf_kfunc_check_set_xdp,
+};
+
 static int __init bpf_kfunc_init(void)
 {
 	int ret;
@@ -11685,6 +11717,7 @@ static int __init bpf_kfunc_init(void)
 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_LWT_OUT, &bpf_kfunc_set_skb);
 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_LWT_IN, &bpf_kfunc_set_skb);
 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_LWT_XMIT, &bpf_kfunc_set_skb);
-	return ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_LWT_SEG6LOCAL, &bpf_kfunc_set_skb);
+	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_LWT_SEG6LOCAL, &bpf_kfunc_set_skb);
+	return ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_XDP, &bpf_kfunc_set_xdp);
 }
 late_initcall(bpf_kfunc_init);
tools/include/uapi/linux/bpf.h +1 -1
index d0351d30e551..faa304c926cf 100644
@@ -5344,7 +5344,7 @@ union bpf_attr {
  *		*len* must be a statically known value. The returned data slice
  *		is invalidated whenever the dynptr is invalidated.
  *
- *		skb type dynptrs may not use bpf_dynptr_data. They should
+ *		skb and xdp type dynptrs may not use bpf_dynptr_data. They should
  *		instead use bpf_dynptr_slice and bpf_dynptr_slice_rdwr.
  *	Return
  *		Pointer to the underlying dynptr data, NULL if the dynptr is
Signature · 1 line
2.34.1
#12 lore raw

PATCH v13 9/10 bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr

In reply to Joanne Koong

Two new kfuncs are added, bpf_dynptr_slice and bpf_dynptr_slice_rdwr. The user must pass in a buffer to store the contents of the data slice if a direct pointer to the data cannot be obtained.

For skb and xdp type dynptrs, these two APIs are the only way to obtain a data slice. However, for other types of dynptrs, there is no difference between bpf_dynptr_slice(_rdwr) and bpf_dynptr_data.

For skb type dynptrs, the data is copied into the user provided buffer if any of the data is not in the linear portion of the skb. For xdp type dynptrs, the data is copied into the user provided buffer if the data is between xdp frags.

If the skb is cloned and a call to bpf_dynptr_data_rdwr is made, then the skb will be uncloned (see bpf_unclone_prologue()).

Please note that any bpf_dynptr_write() automatically invalidates any prior data slices of the skb dynptr. This is because the skb may be cloned or may need to pull its paged buffer into the head. As such, any bpf_dynptr_write() will automatically have its prior data slices invalidated, even if the write is to data in the skb head of an uncloned skb. Please note as well that any other helper calls that change the underlying packet buffer (eg bpf_skb_pull_data()) invalidates any data slices of the skb dynptr as well, for the same reasons.

---
 include/linux/filter.h         |  14 ++++
 include/uapi/linux/bpf.h       |   5 ++
 kernel/bpf/helpers.c           | 138 +++++++++++++++++++++++++++++++++
 kernel/bpf/verifier.c          | 127 +++++++++++++++++++++++++++++-
 net/core/filter.c              |   6 +-
 tools/include/uapi/linux/bpf.h |   5 ++
 6 files changed, 288 insertions(+), 7 deletions(-)
include/linux/filter.h +14 -0
index 3f6992261ec5..efa5d4a1677e 100644
@@ -1548,6 +1548,9 @@ int __bpf_skb_store_bytes(struct sk_buff *skb, u32 offset, const void *from,
 			  u32 len, u64 flags);
 int __bpf_xdp_load_bytes(struct xdp_buff *xdp, u32 offset, void *buf, u32 len);
 int __bpf_xdp_store_bytes(struct xdp_buff *xdp, u32 offset, void *buf, u32 len);
+void *bpf_xdp_pointer(struct xdp_buff *xdp, u32 offset, u32 len);
+void bpf_xdp_copy_buf(struct xdp_buff *xdp, unsigned long off,
+		      void *buf, unsigned long len, bool flush);
 #else /* CONFIG_NET */
 static inline int __bpf_skb_load_bytes(const struct sk_buff *skb, u32 offset,
 				       void *to, u32 len)
@@ -1572,6 +1575,17 @@ static inline int __bpf_xdp_store_bytes(struct xdp_buff *xdp, u32 offset,
 {
 	return -EOPNOTSUPP;
 }
+
+static inline void *bpf_xdp_pointer(struct xdp_buff *xdp, u32 offset, u32 len)
+{
+	return NULL;
+}
+
+static inline void *bpf_xdp_copy_buf(struct xdp_buff *xdp, unsigned long off, void *buf,
+				     unsigned long len, bool flush)
+{
+	return NULL;
+}
 #endif /* CONFIG_NET */
 
 #endif /* __LINUX_FILTER_H__ */
include/uapi/linux/bpf.h +5 -0
index faa304c926cf..c9699304aed2 100644
@@ -5329,6 +5329,11 @@ union bpf_attr {
  *		*flags* must be 0 except for skb-type dynptrs.
  *
  *		For skb-type dynptrs:
+ *		    *  All data slices of the dynptr are automatically
+ *		       invalidated after **bpf_dynptr_write**\ (). This is
+ *		       because writing may pull the skb and change the
+ *		       underlying packet buffer.
+ *
  *		    *  For *flags*, please see the flags accepted by
  *		       **bpf_skb_store_bytes**\ ().
  *	Return
kernel/bpf/helpers.c +138 -0

150 lines not on this page · raw message

kernel/bpf/verifier.c +123 -4

211 lines not on this page · raw message

net/core/filter.c +3 -3
index c692046fa7f6..8f3124e06133 100644
@@ -3894,8 +3894,8 @@ static const struct bpf_func_proto bpf_xdp_adjust_head_proto = {
 	.arg2_type	= ARG_ANYTHING,
 };
 
-static void bpf_xdp_copy_buf(struct xdp_buff *xdp, unsigned long off,
-			     void *buf, unsigned long len, bool flush)
+void bpf_xdp_copy_buf(struct xdp_buff *xdp, unsigned long off,
+		      void *buf, unsigned long len, bool flush)
 {
 	unsigned long ptr_len, ptr_off = 0;
 	skb_frag_t *next_frag, *end_frag;
@@ -3941,7 +3941,7 @@ static void bpf_xdp_copy_buf(struct xdp_buff *xdp, unsigned long off,
 	}
 }
 
-static void *bpf_xdp_pointer(struct xdp_buff *xdp, u32 offset, u32 len)
+void *bpf_xdp_pointer(struct xdp_buff *xdp, u32 offset, u32 len)
 {
 	struct skb_shared_info *sinfo = xdp_get_shared_info_from_buff(xdp);
 	u32 size = xdp->data_end - xdp->data;
tools/include/uapi/linux/bpf.h +5 -0
index faa304c926cf..c9699304aed2 100644
@@ -5329,6 +5329,11 @@ union bpf_attr {
  *		*flags* must be 0 except for skb-type dynptrs.
  *
  *		For skb-type dynptrs:
+ *		    *  All data slices of the dynptr are automatically
+ *		       invalidated after **bpf_dynptr_write**\ (). This is
+ *		       because writing may pull the skb and change the
+ *		       underlying packet buffer.
+ *
  *		    *  For *flags*, please see the flags accepted by
  *		       **bpf_skb_store_bytes**\ ().
  *	Return
Signature · 1 line
2.34.1
#13 lore raw

Re: [PATCH v13 bpf-next 09/10] bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr

Thank you for the patch! Perhaps something to improve:

Hi Joanne,

Thank you for the patch! Perhaps something to improve:

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

url:    https://github.com/intel-lab-lkp/linux/commits/Joanne-Koong/bpf-Support-sk_buff-and-xdp_buff-as-valid-kfunc-arg-types/20230301-235341
base:   https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git master
patch link:    https://lore.kernel.org/r/20230301154953.641654-10-joannelkoong%40gmail.com
patch subject: [PATCH v13 bpf-next 09/10] bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr
config: microblaze-randconfig-s043-20230302 (https://download.01.org/0day-ci/archive/20230302/[email protected]/config)
compiler: microblaze-linux-gcc (GCC) 12.1.0

reproduce:
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross
chmod +x ~/bin/make.cross
# apt-get install sparse
# sparse version: v0.6.4-39-gce1a6720-dirty
# https://github.com/intel-lab-lkp/linux/commit/ab021cad431168baaba04ed320003be30f4deb34
git remote add linux-review https://github.com/intel-lab-lkp/linux
git fetch --no-tags linux-review Joanne-Koong/bpf-Support-sk_buff-and-xdp_buff-as-valid-kfunc-arg-types/20230301-235341
git checkout ab021cad431168baaba04ed320003be30f4deb34
# save the config file
mkdir build_dir && cp config build_dir/.config
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0 make.cross C=1 CF='-fdiagnostic-prefix -D__CHECK_ENDIAN__' O=build_dir ARCH=microblaze olddefconfig COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0 make.cross C=1 CF='-fdiagnostic-prefix -D__CHECK_ENDIAN__' O=build_dir ARCH=microblaze SHELL=/bin/bash kernel/bpf/

If you fix the issue, kindly add following tag where applicable
| Reported-by: kernel test robot <[email protected]>
| Link: https://lore.kernel.org/oe-kbuild-all/[email protected]/

sparse warnings: (new ones prefixed by >>)

>> kernel/bpf/helpers.c:2231:24: sparse: sparse: Using plain integer as NULL pointer

kernel/bpf/helpers.c:2235:24: sparse: sparse: Using plain integer as NULL pointer kernel/bpf/helpers.c:2256:24: sparse: sparse: Using plain integer as NULL pointer kernel/bpf/helpers.c:2305:24: sparse: sparse: Using plain integer as NULL pointer kernel/bpf/helpers.c:2342:18: sparse: sparse: context imbalance in 'bpf_rcu_read_lock' - wrong count at exit kernel/bpf/helpers.c:2347:18: sparse: sparse: context imbalance in 'bpf_rcu_read_unlock' - unexpected unlock

vim +2231 kernel/bpf/helpers.c

2195
2196 /**
2197 * bpf_dynptr_slice - Obtain a read-only pointer to the dynptr data.
2198 *
2199 * For non-skb and non-xdp type dynptrs, there is no difference between
2200 * bpf_dynptr_slice and bpf_dynptr_data.
2201 *
2202 * If the intention is to write to the data slice, please use
2203 * bpf_dynptr_slice_rdwr.
2204 *
2205 * The user must check that the returned pointer is not null before using it.
2206 *
2207 * Please note that in the case of skb and xdp dynptrs, bpf_dynptr_slice
2208 * does not change the underlying packet data pointers, so a call to
2209 * bpf_dynptr_slice will not invalidate any ctx->data/data_end pointers in
2210 * the bpf program.
2211 *
2212 * @ptr: The dynptr whose data slice to retrieve
2213 * @offset: Offset into the dynptr
2214 * @buffer: User-provided buffer to copy contents into
2215 * @buffer__szk: Size (in bytes) of the buffer. This is the length of the
2216 * requested slice. This must be a constant.
2217 *
2218 * @returns: NULL if the call failed (eg invalid dynptr), pointer to a read-only
2219 * data slice (can be either direct pointer to the data or a pointer to the user
2220 * provided buffer, with its contents containing the data, if unable to obtain
2221 * direct pointer)
2222 */
2223 __bpf_kfunc void *bpf_dynptr_slice(const struct bpf_dynptr_kern *ptr, u32 offset,
2224 void *buffer, u32 buffer__szk)
2225 {
2226 enum bpf_dynptr_type type;
2227 u32 len = buffer__szk;
2228 int err;
2229
2230 if (!ptr->data)

> 2231			return 0;

2232
2233 err = bpf_dynptr_check_off_len(ptr, offset, len);
2234 if (err)
2235 return 0;
2236
2237 type = bpf_dynptr_get_type(ptr);
2238
2239 switch (type) {
2240 case BPF_DYNPTR_TYPE_LOCAL:
2241 case BPF_DYNPTR_TYPE_RINGBUF:
2242 return ptr->data + ptr->offset + offset;
2243 case BPF_DYNPTR_TYPE_SKB:
2244 return skb_header_pointer(ptr->data, ptr->offset + offset, len, buffer);
2245 case BPF_DYNPTR_TYPE_XDP:
2246 {
2247 void *xdp_ptr = bpf_xdp_pointer(ptr->data, ptr->offset + offset, len);
2248 if (xdp_ptr)
2249 return xdp_ptr;
2250
2251 bpf_xdp_copy_buf(ptr->data, ptr->offset + offset, buffer, len, false);
2252 return buffer;
2253 }
2254 default:
2255 WARN_ONCE(true, "unknown dynptr type %d\n", type);
2256 return 0;
2257 }
2258 }
2259

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests
#14 lore raw

Re: [PATCH v13 bpf-next 09/10] bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr

Quoted 31 lines · kernel test robot

Hi Joanne,

Thank you for the patch! Perhaps something to improve:

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

url:    https://github.com/intel-lab-lkp/linux/commits/Joanne-Koong/bpf-Support-sk_buff-and-xdp_buff-as-valid-kfunc-arg-types/20230301-235341
base:   https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git master
patch link:    https://lore.kernel.org/r/20230301154953.641654-10-joannelkoong%40gmail.com
patch subject: [PATCH v13 bpf-next 09/10] bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr
config: microblaze-randconfig-s043-20230302 (https://download.01.org/0day-ci/archive/20230302/[email protected]/config)
compiler: microblaze-linux-gcc (GCC) 12.1.0

reproduce:
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross
chmod +x ~/bin/make.cross
# apt-get install sparse
# sparse version: v0.6.4-39-gce1a6720-dirty
# https://github.com/intel-lab-lkp/linux/commit/ab021cad431168baaba04ed320003be30f4deb34
git remote add linux-review https://github.com/intel-lab-lkp/linux
git fetch --no-tags linux-review Joanne-Koong/bpf-Support-sk_buff-and-xdp_buff-as-valid-kfunc-arg-types/20230301-235341
git checkout ab021cad431168baaba04ed320003be30f4deb34
# save the config file
mkdir build_dir && cp config build_dir/.config
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0 make.cross C=1 CF='-fdiagnostic-prefix -D__CHECK_ENDIAN__' O=build_dir ARCH=microblaze olddefconfig COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-12.1.0 make.cross C=1 CF='-fdiagnostic-prefix -D__CHECK_ENDIAN__' O=build_dir ARCH=microblaze SHELL=/bin/bash kernel/bpf/

If you fix the issue, kindly add following tag where applicable
| Reported-by: kernel test robot <[email protected]>
| Link: https://lore.kernel.org/oe-kbuild-all/[email protected]/

Quoted 5 lines

sparse warnings: (new ones prefixed by >>)

Quoted 1 line
Quoted 1 line

kernel/bpf/helpers.c:2231:24: sparse: sparse: Using plain integer as NULL pointer

kernel/bpf/helpers.c:2235:24: sparse: sparse: Using plain integer as NULL pointer kernel/bpf/helpers.c:2256:24: sparse: sparse: Using plain integer as NULL pointer kernel/bpf/helpers.c:2305:24: sparse: sparse: Using plain integer as NULL pointer

Argh, sorry about that. I'll submit a follow-up for returning NULL instead of 0.

Quoted 74 lines

kernel/bpf/helpers.c:2342:18: sparse: sparse: context imbalance in 'bpf_rcu_read_lock' - wrong count at exit kernel/bpf/helpers.c:2347:18: sparse: sparse: context imbalance in 'bpf_rcu_read_unlock' - unexpected unlock

vim +2231 kernel/bpf/helpers.c

2195
2196 /**

  2197   * bpf_dynptr_slice - Obtain a read-only pointer to the dynptr data.
  2198   *
  2199   * For non-skb and non-xdp type dynptrs, there is no difference between
  2200   * bpf_dynptr_slice and bpf_dynptr_data.
  2201   *
  2202   * If the intention is to write to the data slice, please use
  2203   * bpf_dynptr_slice_rdwr.
  2204   *
  2205   * The user must check that the returned pointer is not null before using it.
  2206   *
  2207   * Please note that in the case of skb and xdp dynptrs, bpf_dynptr_slice
  2208   * does not change the underlying packet data pointers, so a call to
  2209   * bpf_dynptr_slice will not invalidate any ctx->data/data_end pointers in
  2210   * the bpf program.
  2211   *
  2212   * @ptr: The dynptr whose data slice to retrieve
  2213   * @offset: Offset into the dynptr
  2214   * @buffer: User-provided buffer to copy contents into
  2215   * @buffer__szk: Size (in bytes) of the buffer. This is the length of the
  2216   * requested slice. This must be a constant.
  2217   *
  2218   * @returns: NULL if the call failed (eg invalid dynptr), pointer to a read-only
  2219   * data slice (can be either direct pointer to the data or a pointer to the user
  2220   * provided buffer, with its contents containing the data, if unable to obtain
  2221   * direct pointer)
  2222   */
  2223  __bpf_kfunc void *bpf_dynptr_slice(const struct bpf_dynptr_kern *ptr, u32 offset,
  2224                                     void *buffer, u32 buffer__szk)
  2225  {
  2226          enum bpf_dynptr_type type;
  2227          u32 len = buffer__szk;
  2228          int err;

2229
2230 if (!ptr->data)

Quoted 1 line

2231 return 0;

2232
2233 err = bpf_dynptr_check_off_len(ptr, offset, len);
2234 if (err)
2235 return 0;
2236
2237 type = bpf_dynptr_get_type(ptr);
2238

  2239          switch (type) {
  2240          case BPF_DYNPTR_TYPE_LOCAL:
  2241          case BPF_DYNPTR_TYPE_RINGBUF:

2242 return ptr->data + ptr->offset + offset;
2243 case BPF_DYNPTR_TYPE_SKB:
2244 return skb_header_pointer(ptr->data, ptr->offset + offset, len, buffer);
2245 case BPF_DYNPTR_TYPE_XDP:
2246 {
2247 void *xdp_ptr = bpf_xdp_pointer(ptr->data, ptr->offset + offset, len);
2248 if (xdp_ptr)
2249 return xdp_ptr;
2250
2251 bpf_xdp_copy_buf(ptr->data, ptr->offset + offset, buffer, len, false);
2252 return buffer;
2253 }
2254 default:
2255 WARN_ONCE(true, "unknown dynptr type %d\n", type);
2256 return 0;
2257 }
2258 }
2259

--
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests

#15 lore raw

Re: [PATCH v13 bpf-next 09/10] bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr

In reply to Joanne Koong
Quoted 25 lines · Joanne Koong

Two new kfuncs are added, bpf_dynptr_slice and bpf_dynptr_slice_rdwr. The user must pass in a buffer to store the contents of the data slice if a direct pointer to the data cannot be obtained.

For skb and xdp type dynptrs, these two APIs are the only way to obtain a data slice. However, for other types of dynptrs, there is no difference between bpf_dynptr_slice(_rdwr) and bpf_dynptr_data.

For skb type dynptrs, the data is copied into the user provided buffer if any of the data is not in the linear portion of the skb. For xdp type dynptrs, the data is copied into the user provided buffer if the data is between xdp frags.

If the skb is cloned and a call to bpf_dynptr_data_rdwr is made, then the skb will be uncloned (see bpf_unclone_prologue()).

Please note that any bpf_dynptr_write() automatically invalidates any prior data slices of the skb dynptr. This is because the skb may be cloned or may need to pull its paged buffer into the head. As such, any bpf_dynptr_write() will automatically have its prior data slices invalidated, even if the write is to data in the skb head of an uncloned skb. Please note as well that any other helper calls that change the underlying packet buffer (eg bpf_skb_pull_data()) invalidates any data slices of the skb dynptr as well, for the same reasons.

Quoted 2 lines

---

Sorry for chiming in late.

I see one potential hole in bpf_dynptr_slice_rdwr. If the returned pointer is actually pointing to the stack (but verified as a PTR_TO_MEM in verifier state), we won't reflect changes to the stack state in the verifier for writes happening through it.

For the worst case scenario, this will basically allow overwriting values of spilled pointers and doing arbitrary kernel memory reads/writes. This is only an issue when bpf_dynptr_slice_rdwr at runtime returns a pointer to the supplied buffer residing on program stack. To verify, by forcing the memcpy to buffer for skb_header_pointer I was able to make it dereference a garbage value for l4lb_all selftest.

kernel/bpf/helpers.c +12 -3
@@ -2253,7 +2253,13 @@ __bpf_kfunc void *bpf_dynptr_slice(const struct bpf_dynptr_kern *ptr, u32 offset
 	case BPF_DYNPTR_TYPE_RINGBUF:
 		return ptr->data + ptr->offset + offset;
 	case BPF_DYNPTR_TYPE_SKB:
-		return skb_header_pointer(ptr->data, ptr->offset + offset, len, buffer);
+	{
+		void *p = skb_header_pointer(ptr->data, ptr->offset + offset, len, buffer);
+		if (p == buffer)
+			return p;
+		memcpy(buffer, p, len);
+		return buffer;
+	}
 
--- a/tools/testing/selftests/bpf/progs/test_l4lb_noinline_dynptr.c
+++ b/tools/testing/selftests/bpf/progs/test_l4lb_noinline_dynptr.c
@@ -470,7 +470,10 @@ int balancer_ingress(struct __sk_buff *ctx)
 	eth = bpf_dynptr_slice_rdwr(&ptr, 0, buffer, sizeof(buffer));
 	if (!eth)
 		return TC_ACT_SHOT;
-	eth_proto = eth->eth_proto;
+	*(void **)buffer = ctx;
+	*(void **)eth = (void *)0xdeadbeef;
+	ctx = *(void **)buffer;
+	eth_proto = eth->eth_proto + ctx->len;
 	if (eth_proto == bpf_htons(ETH_P_IP))
 		err = process_packet(&ptr, eth, nh_off, false, ctx);
 

I think the proper fix is to treat it as a separate return type distinct from PTR_TO_MEM like PTR_TO_MEM_OR_PKT (or handle PTR_TO_MEM | DYNPTR_* specially), fork verifier state whenever there is a write, so that one path verifies it as PTR_TO_PACKET, while another as PTR_TO_STACK (if buffer was a stack ptr). I think for the rest it's not a problem, but there are allow_ptr_leak checks applied to PTR_TO_STACK and PTR_TO_MAP_VALUE, so that needs to be rechecked. Then we ensure that program is safe in either path.

Also we need to fix regsafe to not consider other PTR_TO_MEMs equivalent to such a pointer. We could also fork verifier states on return, to verify either path separately right from the point following the call instruction.

Any other ideas welcome.

#16 lore raw

Re: [PATCH v13 bpf-next 09/10] bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr

Quoted 62 lines · Kumar Kartikeya Dwivedi
Quoted 25 lines · Joanne Koong

Two new kfuncs are added, bpf_dynptr_slice and bpf_dynptr_slice_rdwr. The user must pass in a buffer to store the contents of the data slice if a direct pointer to the data cannot be obtained.

For skb and xdp type dynptrs, these two APIs are the only way to obtain a data slice. However, for other types of dynptrs, there is no difference between bpf_dynptr_slice(_rdwr) and bpf_dynptr_data.

For skb type dynptrs, the data is copied into the user provided buffer if any of the data is not in the linear portion of the skb. For xdp type dynptrs, the data is copied into the user provided buffer if the data is between xdp frags.

If the skb is cloned and a call to bpf_dynptr_data_rdwr is made, then the skb will be uncloned (see bpf_unclone_prologue()).

Please note that any bpf_dynptr_write() automatically invalidates any prior data slices of the skb dynptr. This is because the skb may be cloned or may need to pull its paged buffer into the head. As such, any bpf_dynptr_write() will automatically have its prior data slices invalidated, even if the write is to data in the skb head of an uncloned skb. Please note as well that any other helper calls that change the underlying packet buffer (eg bpf_skb_pull_data()) invalidates any data slices of the skb dynptr as well, for the same reasons.

Quoted 2 lines

---

Sorry for chiming in late.

I see one potential hole in bpf_dynptr_slice_rdwr. If the returned pointer is actually pointing to the stack (but verified as a PTR_TO_MEM in verifier state), we won't reflect changes to the stack state in the verifier for writes happening through it.

For the worst case scenario, this will basically allow overwriting values of spilled pointers and doing arbitrary kernel memory reads/writes. This is only an issue when bpf_dynptr_slice_rdwr at runtime returns a pointer to the supplied buffer residing on program stack. To verify, by forcing the memcpy to buffer for skb_header_pointer I was able to make it dereference a garbage value for l4lb_all selftest.

kernel/bpf/helpers.c +7 -1
@@ -2253,7 +2253,13 @@ __bpf_kfunc void *bpf_dynptr_slice(const struct bpf_dynptr_kern *ptr, u32 offset
        case BPF_DYNPTR_TYPE_RINGBUF:
                return ptr->data + ptr->offset + offset;
        case BPF_DYNPTR_TYPE_SKB:
-               return skb_header_pointer(ptr->data, ptr->offset + offset, len, buffer);
+       {
+               void *p = skb_header_pointer(ptr->data, ptr->offset + offset, len, buffer);
+               if (p == buffer)
+                       return p;
+               memcpy(buffer, p, len);
+               return buffer;
+       }
 

tools/testing/selftests/bpf/progs/test_l4lb_noinline_dynptr.c int balancer_ingress(struct __sk_buff *ctx) · line 473

Quoted 5 lines
tools/testing/selftests/bpf/progs/test_l4lb_noinline_dynptr.c +1 -1
@@ -470,7 +470,10 @@ int balancer_ingress(struct __sk_buff *ctx)
        eth = bpf_dynptr_slice_rdwr(&ptr, 0, buffer, sizeof(buffer));
        if (!eth)
                return TC_ACT_SHOT;
-       eth_proto = eth->eth_proto;
+       *(void **)buffer = ctx;

Great catch.
To fix the issue I think we should simply disallow such stack abuse. The compiler won't be spilling registers into C array on the stack.
This manual spill/fill is exploiting verifier logic. After bpf_dynptr_slice_rdwr() we can mark all slots of the buffer as STACK_POISON or some better name and reject spill into such slots.

Quoted 14 lines
tools/testing/selftests/bpf/progs/test_l4lb_noinline_dynptr.c +3 -0
+       *(void **)eth = (void *)0xdeadbeef;
+       ctx = *(void **)buffer;
+       eth_proto = eth->eth_proto + ctx->len;
        if (eth_proto == bpf_htons(ETH_P_IP))
                err = process_packet(&ptr, eth, nh_off, false, ctx);
 

I think the proper fix is to treat it as a separate return type distinct from PTR_TO_MEM like PTR_TO_MEM_OR_PKT (or handle PTR_TO_MEM | DYNPTR_* specially), fork verifier state whenever there is a write, so that one path verifies it as PTR_TO_PACKET, while another as PTR_TO_STACK (if buffer was a stack ptr). I think for the rest it's not a problem, but there are allow_ptr_leak checks applied to PTR_TO_STACK and PTR_TO_MAP_VALUE, so that needs to be rechecked. Then we ensure that program is safe in either path.

Quoted 3 lines

Also we need to fix regsafe to not consider other PTR_TO_MEMs equivalent to such a pointer. We could also fork verifier states on return, to verify either path separately right from the point following the call instruction.

This is too complex imo.

#17 lore raw

Re: [PATCH v13 bpf-next 09/10] bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr

Quoted 70 lines · Alexei Starovoitov
Quoted 62 lines · Kumar Kartikeya Dwivedi
Quoted 25 lines · Joanne Koong

Two new kfuncs are added, bpf_dynptr_slice and bpf_dynptr_slice_rdwr. The user must pass in a buffer to store the contents of the data slice if a direct pointer to the data cannot be obtained.

For skb and xdp type dynptrs, these two APIs are the only way to obtain a data slice. However, for other types of dynptrs, there is no difference between bpf_dynptr_slice(_rdwr) and bpf_dynptr_data.

For skb type dynptrs, the data is copied into the user provided buffer if any of the data is not in the linear portion of the skb. For xdp type dynptrs, the data is copied into the user provided buffer if the data is between xdp frags.

If the skb is cloned and a call to bpf_dynptr_data_rdwr is made, then the skb will be uncloned (see bpf_unclone_prologue()).

Please note that any bpf_dynptr_write() automatically invalidates any prior data slices of the skb dynptr. This is because the skb may be cloned or may need to pull its paged buffer into the head. As such, any bpf_dynptr_write() will automatically have its prior data slices invalidated, even if the write is to data in the skb head of an uncloned skb. Please note as well that any other helper calls that change the underlying packet buffer (eg bpf_skb_pull_data()) invalidates any data slices of the skb dynptr as well, for the same reasons.

Quoted 2 lines

---

Sorry for chiming in late.

I see one potential hole in bpf_dynptr_slice_rdwr. If the returned pointer is actually pointing to the stack (but verified as a PTR_TO_MEM in verifier state), we won't reflect changes to the stack state in the verifier for writes happening through it.

For the worst case scenario, this will basically allow overwriting values of spilled pointers and doing arbitrary kernel memory reads/writes. This is only an issue when bpf_dynptr_slice_rdwr at runtime returns a pointer to the supplied buffer residing on program stack. To verify, by forcing the memcpy to buffer for skb_header_pointer I was able to make it dereference a garbage value for l4lb_all selftest.

kernel/bpf/helpers.c +7 -1
@@ -2253,7 +2253,13 @@ __bpf_kfunc void *bpf_dynptr_slice(const struct bpf_dynptr_kern *ptr, u32 offset
        case BPF_DYNPTR_TYPE_RINGBUF:
                return ptr->data + ptr->offset + offset;
        case BPF_DYNPTR_TYPE_SKB:
-               return skb_header_pointer(ptr->data, ptr->offset + offset, len, buffer);
+       {
+               void *p = skb_header_pointer(ptr->data, ptr->offset + offset, len, buffer);
+               if (p == buffer)
+                       return p;
+               memcpy(buffer, p, len);
+               return buffer;
+       }
 

tools/testing/selftests/bpf/progs/test_l4lb_noinline_dynptr.c int balancer_ingress(struct __sk_buff *ctx) · line 473

Quoted 5 lines
tools/testing/selftests/bpf/progs/test_l4lb_noinline_dynptr.c +1 -1
@@ -470,7 +470,10 @@ int balancer_ingress(struct __sk_buff *ctx)
        eth = bpf_dynptr_slice_rdwr(&ptr, 0, buffer, sizeof(buffer));
        if (!eth)
                return TC_ACT_SHOT;
-       eth_proto = eth->eth_proto;
+       *(void **)buffer = ctx;
Quoted 9 lines

Great catch.
To fix the issue I think we should simply disallow such stack abuse. The compiler won't be spilling registers into C array on the stack.
This manual spill/fill is exploiting verifier logic. After bpf_dynptr_slice_rdwr() we can mark all slots of the buffer as STACK_POISON or some better name and reject spill into such slots.

I agree this is simpler, but I'm not sure it will work properly. Verifier won't know when the lifetime of the buffer ends, so if we disallow spills until its written over it's going to be a pain for users.

Something like:

for (...) {
	char buf[64];
	bpf_dynptr_slice_rdwr(..., buf, 64);
	...
}

.. and then compiler decides to spill something where buf was located on stack outside the for loop. The verifier can't know when buf goes out of scope to unpoison the slots.

Quoted 14 lines
Quoted 14 lines
tools/testing/selftests/bpf/progs/test_l4lb_noinline_dynptr.c +3 -0
+       *(void **)eth = (void *)0xdeadbeef;
+       ctx = *(void **)buffer;
+       eth_proto = eth->eth_proto + ctx->len;
        if (eth_proto == bpf_htons(ETH_P_IP))
                err = process_packet(&ptr, eth, nh_off, false, ctx);
 

I think the proper fix is to treat it as a separate return type distinct from PTR_TO_MEM like PTR_TO_MEM_OR_PKT (or handle PTR_TO_MEM | DYNPTR_* specially), fork verifier state whenever there is a write, so that one path verifies it as PTR_TO_PACKET, while another as PTR_TO_STACK (if buffer was a stack ptr). I think for the rest it's not a problem, but there are allow_ptr_leak checks applied to PTR_TO_STACK and PTR_TO_MAP_VALUE, so that needs to be rechecked. Then we ensure that program is safe in either path.

Quoted 5 lines
Quoted 3 lines

Also we need to fix regsafe to not consider other PTR_TO_MEMs equivalent to such a pointer. We could also fork verifier states on return, to verify either path separately right from the point following the call instruction.

This is too complex imo.

A better way to phrase this is to verify with R0 = PTR_TO_PACKET in one path, and push_stack with R0 = buffer's reg->type + size set to len in the other path for exploration later. In terms of verifier infra everything is there already, it just needs to analyze both cases which fall into the regular code handling the reg->type's. Probably then no adjustments to regsafe are needed either. It's like exploring branch instructions.

#18 lore raw

Re: [PATCH v13 bpf-next 09/10] bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr

Quoted 94 lines · Kumar Kartikeya Dwivedi
Quoted 70 lines · Alexei Starovoitov
Quoted 62 lines · Kumar Kartikeya Dwivedi
Quoted 25 lines · Joanne Koong

Two new kfuncs are added, bpf_dynptr_slice and bpf_dynptr_slice_rdwr. The user must pass in a buffer to store the contents of the data slice if a direct pointer to the data cannot be obtained.

For skb and xdp type dynptrs, these two APIs are the only way to obtain a data slice. However, for other types of dynptrs, there is no difference between bpf_dynptr_slice(_rdwr) and bpf_dynptr_data.

For skb type dynptrs, the data is copied into the user provided buffer if any of the data is not in the linear portion of the skb. For xdp type dynptrs, the data is copied into the user provided buffer if the data is between xdp frags.

If the skb is cloned and a call to bpf_dynptr_data_rdwr is made, then the skb will be uncloned (see bpf_unclone_prologue()).

Please note that any bpf_dynptr_write() automatically invalidates any prior data slices of the skb dynptr. This is because the skb may be cloned or may need to pull its paged buffer into the head. As such, any bpf_dynptr_write() will automatically have its prior data slices invalidated, even if the write is to data in the skb head of an uncloned skb. Please note as well that any other helper calls that change the underlying packet buffer (eg bpf_skb_pull_data()) invalidates any data slices of the skb dynptr as well, for the same reasons.

Quoted 2 lines

---

Sorry for chiming in late.

I see one potential hole in bpf_dynptr_slice_rdwr. If the returned pointer is actually pointing to the stack (but verified as a PTR_TO_MEM in verifier state), we won't reflect changes to the stack state in the verifier for writes happening through it.

For the worst case scenario, this will basically allow overwriting values of spilled pointers and doing arbitrary kernel memory reads/writes. This is only an issue when bpf_dynptr_slice_rdwr at runtime returns a pointer to the supplied buffer residing on program stack. To verify, by forcing the memcpy to buffer for skb_header_pointer I was able to make it dereference a garbage value for l4lb_all selftest.

kernel/bpf/helpers.c +7 -1
@@ -2253,7 +2253,13 @@ __bpf_kfunc void *bpf_dynptr_slice(const struct bpf_dynptr_kern *ptr, u32 offset
        case BPF_DYNPTR_TYPE_RINGBUF:
                return ptr->data + ptr->offset + offset;
        case BPF_DYNPTR_TYPE_SKB:
-               return skb_header_pointer(ptr->data, ptr->offset + offset, len, buffer);
+       {
+               void *p = skb_header_pointer(ptr->data, ptr->offset + offset, len, buffer);
+               if (p == buffer)
+                       return p;
+               memcpy(buffer, p, len);
+               return buffer;
+       }
 

tools/testing/selftests/bpf/progs/test_l4lb_noinline_dynptr.c int balancer_ingress(struct __sk_buff *ctx) · line 473

Quoted 5 lines
tools/testing/selftests/bpf/progs/test_l4lb_noinline_dynptr.c +1 -1
@@ -470,7 +470,10 @@ int balancer_ingress(struct __sk_buff *ctx)
        eth = bpf_dynptr_slice_rdwr(&ptr, 0, buffer, sizeof(buffer));
        if (!eth)
                return TC_ACT_SHOT;
-       eth_proto = eth->eth_proto;
+       *(void **)buffer = ctx;
Quoted 9 lines

Great catch.
To fix the issue I think we should simply disallow such stack abuse. The compiler won't be spilling registers into C array on the stack.
This manual spill/fill is exploiting verifier logic. After bpf_dynptr_slice_rdwr() we can mark all slots of the buffer as STACK_POISON or some better name and reject spill into such slots.

I agree this is simpler, but I'm not sure it will work properly. Verifier won't know when the lifetime of the buffer ends, so if we disallow spills until its written over it's going to be a pain for users.

Something like:

for (...) {
        char buf[64];
        bpf_dynptr_slice_rdwr(..., buf, 64);
        ...
}
Quoted 3 lines

.. and then compiler decides to spill something where buf was located on stack outside the for loop. The verifier can't know when buf goes out of scope to unpoison the slots.

You're saying the "verifier doesn't know when buf ...". The same applies to the compiler. It has no visibility into what bpf_dynptr_slice_rdwr is doing.
So it never spills into a declared C array
as I tried to explain in the previous reply. Spill/fill slots are always invisible to C. (unless of course you do pointer arithmetic asm style)

Quoted 18 lines
Quoted 18 lines
Quoted 17 lines
tools/testing/selftests/bpf/progs/test_l4lb_noinline_dynptr.c +3 -0
+       *(void **)eth = (void *)0xdeadbeef;
+       ctx = *(void **)buffer;
+       eth_proto = eth->eth_proto + ctx->len;
        if (eth_proto == bpf_htons(ETH_P_IP))
                err = process_packet(&ptr, eth, nh_off, false, ctx);
 

I think the proper fix is to treat it as a separate return type distinct from PTR_TO_MEM like PTR_TO_MEM_OR_PKT (or handle PTR_TO_MEM | DYNPTR_* specially), fork verifier state whenever there is a write, so that one path verifies it as PTR_TO_PACKET, while another as PTR_TO_STACK (if buffer was a stack ptr). I think for the rest it's not a problem, but there are allow_ptr_leak checks applied to PTR_TO_STACK and PTR_TO_MAP_VALUE, so that needs to be rechecked. Then we ensure that program is safe in either path.

Also we need to fix regsafe to not consider other PTR_TO_MEMs equivalent to such a pointer. We could also fork verifier states on return, to verify either path separately right from the point following the call instruction.

Quoted 8 lines
Quoted 1 line

This is too complex imo.

A better way to phrase this is to verify with R0 = PTR_TO_PACKET in one path, and push_stack with R0 = buffer's reg->type + size set to len in the other path for exploration later. In terms of verifier infra everything is there already, it just needs to analyze both cases which fall into the regular code handling the reg->type's. Probably then no adjustments to regsafe are needed either. It's like exploring branch instructions.

I still don't like it. There is no reason to go a complex path when much simpler suffices.

#19 lore raw

Re: [PATCH v13 bpf-next 09/10] bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr

Quoted 95 lines · Alexei Starovoitov
Quoted 94 lines · Kumar Kartikeya Dwivedi
Quoted 70 lines · Alexei Starovoitov
Quoted 62 lines · Kumar Kartikeya Dwivedi
Quoted 25 lines · Joanne Koong

Two new kfuncs are added, bpf_dynptr_slice and bpf_dynptr_slice_rdwr. The user must pass in a buffer to store the contents of the data slice if a direct pointer to the data cannot be obtained.

For skb and xdp type dynptrs, these two APIs are the only way to obtain a data slice. However, for other types of dynptrs, there is no difference between bpf_dynptr_slice(_rdwr) and bpf_dynptr_data.

For skb type dynptrs, the data is copied into the user provided buffer if any of the data is not in the linear portion of the skb. For xdp type dynptrs, the data is copied into the user provided buffer if the data is between xdp frags.

If the skb is cloned and a call to bpf_dynptr_data_rdwr is made, then the skb will be uncloned (see bpf_unclone_prologue()).

Please note that any bpf_dynptr_write() automatically invalidates any prior data slices of the skb dynptr. This is because the skb may be cloned or may need to pull its paged buffer into the head. As such, any bpf_dynptr_write() will automatically have its prior data slices invalidated, even if the write is to data in the skb head of an uncloned skb. Please note as well that any other helper calls that change the underlying packet buffer (eg bpf_skb_pull_data()) invalidates any data slices of the skb dynptr as well, for the same reasons.

Quoted 2 lines

---

Sorry for chiming in late.

I see one potential hole in bpf_dynptr_slice_rdwr. If the returned pointer is actually pointing to the stack (but verified as a PTR_TO_MEM in verifier state), we won't reflect changes to the stack state in the verifier for writes happening through it.

For the worst case scenario, this will basically allow overwriting values of spilled pointers and doing arbitrary kernel memory reads/writes. This is only an issue when bpf_dynptr_slice_rdwr at runtime returns a pointer to the supplied buffer residing on program stack. To verify, by forcing the memcpy to buffer for skb_header_pointer I was able to make it dereference a garbage value for l4lb_all selftest.

kernel/bpf/helpers.c +7 -1
@@ -2253,7 +2253,13 @@ __bpf_kfunc void *bpf_dynptr_slice(const struct bpf_dynptr_kern *ptr, u32 offset
        case BPF_DYNPTR_TYPE_RINGBUF:
                return ptr->data + ptr->offset + offset;
        case BPF_DYNPTR_TYPE_SKB:
-               return skb_header_pointer(ptr->data, ptr->offset + offset, len, buffer);
+       {
+               void *p = skb_header_pointer(ptr->data, ptr->offset + offset, len, buffer);
+               if (p == buffer)
+                       return p;
+               memcpy(buffer, p, len);
+               return buffer;
+       }
 

tools/testing/selftests/bpf/progs/test_l4lb_noinline_dynptr.c int balancer_ingress(struct __sk_buff *ctx) · line 473

Quoted 5 lines
tools/testing/selftests/bpf/progs/test_l4lb_noinline_dynptr.c +1 -1
@@ -470,7 +470,10 @@ int balancer_ingress(struct __sk_buff *ctx)
        eth = bpf_dynptr_slice_rdwr(&ptr, 0, buffer, sizeof(buffer));
        if (!eth)
                return TC_ACT_SHOT;
-       eth_proto = eth->eth_proto;
+       *(void **)buffer = ctx;
Quoted 9 lines

Great catch.
To fix the issue I think we should simply disallow such stack abuse. The compiler won't be spilling registers into C array on the stack.
This manual spill/fill is exploiting verifier logic. After bpf_dynptr_slice_rdwr() we can mark all slots of the buffer as STACK_POISON or some better name and reject spill into such slots.

I agree this is simpler, but I'm not sure it will work properly. Verifier won't know when the lifetime of the buffer ends, so if we disallow spills until its written over it's going to be a pain for users.

Something like:

for (...) {
        char buf[64];
        bpf_dynptr_slice_rdwr(..., buf, 64);
        ...
}
Quoted 7 lines
Quoted 3 lines

.. and then compiler decides to spill something where buf was located on stack outside the for loop. The verifier can't know when buf goes out of scope to unpoison the slots.

You're saying the "verifier doesn't know when buf ...". The same applies to the compiler. It has no visibility into what bpf_dynptr_slice_rdwr is doing.

That is true, it can't assume anything about the side effects. But I am talking about the point in the program when the buffer object no longer lives. Use of the escaped pointer to such an object any longer is UB. The compiler is well within its rights to reuse its stack storage at that point, including for spilling registers. Which is why "outside the for loop" in my earlier reply.

Quoted 4 lines

So it never spills into a declared C array
as I tried to explain in the previous reply. Spill/fill slots are always invisible to C. (unless of course you do pointer arithmetic asm style)

When the declared array's lifetime ends, it can.
https://godbolt.org/z/Ez7v4xfnv

The 2nd call to bar as part of unrolled loop happens with fp-8, then it calls baz, spills r0 to fp-8, and calls bar again with fp-8.

If such a stack slot is STACK_POISON, verifier will reject this program.

Quoted 30 lines
Quoted 19 lines
Quoted 19 lines
Quoted 18 lines
tools/testing/selftests/bpf/progs/test_l4lb_noinline_dynptr.c +3 -0
+       *(void **)eth = (void *)0xdeadbeef;
+       ctx = *(void **)buffer;
+       eth_proto = eth->eth_proto + ctx->len;
        if (eth_proto == bpf_htons(ETH_P_IP))
                err = process_packet(&ptr, eth, nh_off, false, ctx);
 

I think the proper fix is to treat it as a separate return type distinct from PTR_TO_MEM like PTR_TO_MEM_OR_PKT (or handle PTR_TO_MEM | DYNPTR_* specially), fork verifier state whenever there is a write, so that one path verifies it as PTR_TO_PACKET, while another as PTR_TO_STACK (if buffer was a stack ptr). I think for the rest it's not a problem, but there are allow_ptr_leak checks applied to PTR_TO_STACK and PTR_TO_MAP_VALUE, so that needs to be rechecked. Then we ensure that program is safe in either path.

Also we need to fix regsafe to not consider other PTR_TO_MEMs equivalent to such a pointer. We could also fork verifier states on return, to verify either path separately right from the point following the call instruction.

Quoted 8 lines
Quoted 1 line

This is too complex imo.

A better way to phrase this is to verify with R0 = PTR_TO_PACKET in one path, and push_stack with R0 = buffer's reg->type + size set to len in the other path for exploration later. In terms of verifier infra everything is there already, it just needs to analyze both cases which fall into the regular code handling the reg->type's. Probably then no adjustments to regsafe are needed either. It's like exploring branch instructions.

I still don't like it. There is no reason to go a complex path when much simpler suffices.

#20 lore raw

Re: [PATCH v13 bpf-next 09/10] bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr

Quoted 116 lines · Kumar Kartikeya Dwivedi
Quoted 95 lines · Alexei Starovoitov
Quoted 94 lines · Kumar Kartikeya Dwivedi
Quoted 70 lines · Alexei Starovoitov
Quoted 62 lines · Kumar Kartikeya Dwivedi
Quoted 25 lines · Joanne Koong

Two new kfuncs are added, bpf_dynptr_slice and bpf_dynptr_slice_rdwr. The user must pass in a buffer to store the contents of the data slice if a direct pointer to the data cannot be obtained.

For skb and xdp type dynptrs, these two APIs are the only way to obtain a data slice. However, for other types of dynptrs, there is no difference between bpf_dynptr_slice(_rdwr) and bpf_dynptr_data.

For skb type dynptrs, the data is copied into the user provided buffer if any of the data is not in the linear portion of the skb. For xdp type dynptrs, the data is copied into the user provided buffer if the data is between xdp frags.

If the skb is cloned and a call to bpf_dynptr_data_rdwr is made, then the skb will be uncloned (see bpf_unclone_prologue()).

Please note that any bpf_dynptr_write() automatically invalidates any prior data slices of the skb dynptr. This is because the skb may be cloned or may need to pull its paged buffer into the head. As such, any bpf_dynptr_write() will automatically have its prior data slices invalidated, even if the write is to data in the skb head of an uncloned skb. Please note as well that any other helper calls that change the underlying packet buffer (eg bpf_skb_pull_data()) invalidates any data slices of the skb dynptr as well, for the same reasons.

Quoted 2 lines

---

Sorry for chiming in late.

I see one potential hole in bpf_dynptr_slice_rdwr. If the returned pointer is actually pointing to the stack (but verified as a PTR_TO_MEM in verifier state), we won't reflect changes to the stack state in the verifier for writes happening through it.

For the worst case scenario, this will basically allow overwriting values of spilled pointers and doing arbitrary kernel memory reads/writes. This is only an issue when bpf_dynptr_slice_rdwr at runtime returns a pointer to the supplied buffer residing on program stack. To verify, by forcing the memcpy to buffer for skb_header_pointer I was able to make it dereference a garbage value for l4lb_all selftest.

kernel/bpf/helpers.c +7 -1
@@ -2253,7 +2253,13 @@ __bpf_kfunc void *bpf_dynptr_slice(const struct bpf_dynptr_kern *ptr, u32 offset
        case BPF_DYNPTR_TYPE_RINGBUF:
                return ptr->data + ptr->offset + offset;
        case BPF_DYNPTR_TYPE_SKB:
-               return skb_header_pointer(ptr->data, ptr->offset + offset, len, buffer);
+       {
+               void *p = skb_header_pointer(ptr->data, ptr->offset + offset, len, buffer);
+               if (p == buffer)
+                       return p;
+               memcpy(buffer, p, len);
+               return buffer;
+       }
 

tools/testing/selftests/bpf/progs/test_l4lb_noinline_dynptr.c int balancer_ingress(struct __sk_buff *ctx) · line 473

Quoted 5 lines
tools/testing/selftests/bpf/progs/test_l4lb_noinline_dynptr.c +1 -1
@@ -470,7 +470,10 @@ int balancer_ingress(struct __sk_buff *ctx)
        eth = bpf_dynptr_slice_rdwr(&ptr, 0, buffer, sizeof(buffer));
        if (!eth)
                return TC_ACT_SHOT;
-       eth_proto = eth->eth_proto;
+       *(void **)buffer = ctx;
Quoted 9 lines

Great catch.
To fix the issue I think we should simply disallow such stack abuse. The compiler won't be spilling registers into C array on the stack.
This manual spill/fill is exploiting verifier logic. After bpf_dynptr_slice_rdwr() we can mark all slots of the buffer as STACK_POISON or some better name and reject spill into such slots.

I agree this is simpler, but I'm not sure it will work properly. Verifier won't know when the lifetime of the buffer ends, so if we disallow spills until its written over it's going to be a pain for users.

Something like:

for (...) {
        char buf[64];
        bpf_dynptr_slice_rdwr(..., buf, 64);
        ...
}
Quoted 7 lines
Quoted 3 lines

.. and then compiler decides to spill something where buf was located on stack outside the for loop. The verifier can't know when buf goes out of scope to unpoison the slots.

You're saying the "verifier doesn't know when buf ...". The same applies to the compiler. It has no visibility into what bpf_dynptr_slice_rdwr is doing.

That is true, it can't assume anything about the side effects. But I am talking about the point in the program when the buffer object no longer lives. Use of the escaped pointer to such an object any longer is UB. The compiler is well within its rights to reuse its stack storage at that point, including for spilling registers. Which is why "outside the for loop" in my earlier reply.

Quoted 4 lines

So it never spills into a declared C array
as I tried to explain in the previous reply. Spill/fill slots are always invisible to C. (unless of course you do pointer arithmetic asm style)

Quoted 38 lines

When the declared array's lifetime ends, it can.
https://godbolt.org/z/Ez7v4xfnv

The 2nd call to bar as part of unrolled loop happens with fp-8, then it calls baz, spills r0 to fp-8, and calls bar again with fp-8.

If such a stack slot is STACK_POISON, verifier will reject this program.

Quoted 30 lines
Quoted 19 lines
Quoted 19 lines
Quoted 18 lines
tools/testing/selftests/bpf/progs/test_l4lb_noinline_dynptr.c +3 -0
+       *(void **)eth = (void *)0xdeadbeef;
+       ctx = *(void **)buffer;
+       eth_proto = eth->eth_proto + ctx->len;
        if (eth_proto == bpf_htons(ETH_P_IP))
                err = process_packet(&ptr, eth, nh_off, false, ctx);
 

I think the proper fix is to treat it as a separate return type distinct from PTR_TO_MEM like PTR_TO_MEM_OR_PKT (or handle PTR_TO_MEM | DYNPTR_* specially), fork verifier state whenever there is a write, so that one path verifies it as PTR_TO_PACKET, while another as PTR_TO_STACK (if buffer was a stack ptr). I think for the rest it's not a problem, but there are allow_ptr_leak checks applied to PTR_TO_STACK and PTR_TO_MAP_VALUE, so that needs to be rechecked. Then we ensure that program is safe in either path.

Also we need to fix regsafe to not consider other PTR_TO_MEMs equivalent to such a pointer. We could also fork verifier states on return, to verify either path separately right from the point following the call instruction.

Quoted 8 lines
Quoted 1 line

This is too complex imo.

A better way to phrase this is to verify with R0 = PTR_TO_PACKET in one path, and push_stack with R0 = buffer's reg->type + size set to len in the other path for exploration later. In terms of verifier infra everything is there already, it just needs to analyze both cases which fall into the regular code handling the reg->type's. Probably then no adjustments to regsafe are needed either. It's like exploring branch instructions.

I still don't like it. There is no reason to go a complex path when much simpler suffices.

This issue you are discussing is the reason we don't support bpf_dynptr_from_mem() taking PTR_TO_STACK (which is a pity, but we postponed it initially).

I've been thinking about something along the lines of STACK_POISON, but remembering associated id/ref_obj_id. When ref is released, turn STACK_POISON to STACK_MISC. If it's bpf_dynptr_slice_rdrw() or bpf_dynptr_from_mem(), which don't have ref_obj_id, they still have ID associated with returned pointer, so can we somehow incorporate that?

#21 lore raw

Re: [PATCH v13 bpf-next 09/10] bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr

Quoted 32 lines · Andrii Nakryiko
Quoted 32 lines
Quoted 13 lines
Quoted 13 lines

I agree this is simpler, but I'm not sure it will work properly. Verifier won't know when the lifetime of the buffer ends, so if we disallow spills until its written over it's going to be a pain for users.

Something like:

for (...) {
        char buf[64];
        bpf_dynptr_slice_rdwr(..., buf, 64);
        ...
}
Quoted 7 lines
Quoted 3 lines

.. and then compiler decides to spill something where buf was located on stack outside the for loop. The verifier can't know when buf goes out of scope to unpoison the slots.

You're saying the "verifier doesn't know when buf ...". The same applies to the compiler. It has no visibility into what bpf_dynptr_slice_rdwr is doing.

That is true, it can't assume anything about the side effects. But I am talking about the point in the program when the buffer object no longer lives. Use of the escaped pointer to such an object any longer is UB. The compiler is well within its rights to reuse its stack storage at that point, including for spilling registers. Which is why "outside the for loop" in my earlier reply.

Quoted 4 lines

So it never spills into a declared C array
as I tried to explain in the previous reply. Spill/fill slots are always invisible to C. (unless of course you do pointer arithmetic asm style)

Quoted 5 lines
Quoted 5 lines

When the declared array's lifetime ends, it can.
https://godbolt.org/z/Ez7v4xfnv

The 2nd call to bar as part of unrolled loop happens with fp-8, then it calls baz, spills r0 to fp-8, and calls bar again with fp-8.

Right. If user writes such program and does explicit store of spillable pointer into a stack.
I was talking about compiler generated spill/fill and I still believe that compiler will not be reusing variable's stack memory for them.

Quoted 2 lines
Quoted 2 lines

If such a stack slot is STACK_POISON, verifier will reject this program.

Yes and I think it's an ok trade-off.
The user has to specifically code such program to hit this issue. I don't think we will see this in practice.
If we do we can consider a more complex fix.

Quoted 36 lines
Quoted 29 lines
Quoted 29 lines
Quoted 28 lines
Quoted 16 lines
Quoted 16 lines
kernel/bpf/helpers.c +3 -0
+       *(void **)eth = (void *)0xdeadbeef;
+       ctx = *(void **)buffer;
+       eth_proto = eth->eth_proto + ctx->len;
        if (eth_proto == bpf_htons(ETH_P_IP))
                err = process_packet(&ptr, eth, nh_off, false, ctx);

I think the proper fix is to treat it as a separate return type distinct from PTR_TO_MEM like PTR_TO_MEM_OR_PKT (or handle PTR_TO_MEM | DYNPTR_* specially), fork verifier state whenever there is a write, so that one path verifies it as PTR_TO_PACKET, while another as PTR_TO_STACK (if buffer was a stack ptr). I think for the rest it's not a problem, but there are allow_ptr_leak checks applied to PTR_TO_STACK and PTR_TO_MAP_VALUE, so that needs to be rechecked. Then we ensure that program is safe in either path.

Quoted 5 lines
Quoted 3 lines

Also we need to fix regsafe to not consider other PTR_TO_MEMs equivalent to such a pointer. We could also fork verifier states on return, to verify either path separately right from the point following the call instruction.

This is too complex imo.

A better way to phrase this is to verify with R0 = PTR_TO_PACKET in one path, and push_stack with R0 = buffer's reg->type + size set to len in the other path for exploration later. In terms of verifier infra everything is there already, it just needs to analyze both cases which fall into the regular code handling the reg->type's. Probably then no adjustments to regsafe are needed either. It's like exploring branch instructions.

Quoted 2 lines
Quoted 2 lines

I still don't like it. There is no reason to go a complex path when much simpler suffices.

This issue you are discussing is the reason we don't support bpf_dynptr_from_mem() taking PTR_TO_STACK (which is a pity, but we postponed it initially).

Quoted 5 lines

I've been thinking about something along the lines of STACK_POISON, but remembering associated id/ref_obj_id. When ref is released, turn STACK_POISON to STACK_MISC. If it's bpf_dynptr_slice_rdrw() or bpf_dynptr_from_mem(), which don't have ref_obj_id, they still have ID associated with returned pointer, so can we somehow incorporate that?

There is dynptr_id in PTR_TO_MEM that is used by destroy_if_dynptr_stack_slot(), but I don't see how we can use it to help this case.
imo plain STACK_POISON that is overwriteable by STACK_MISC/STACK_ZERO should be good enough in practice.

We can potentially do some liveness trick. When PTR_TO_MEM with dynptr_id becomes REG_LIVE_DONE we can convert STACK_POISON. But I'd go with the simplest approach first.

#22 lore raw

Re: [PATCH v13 bpf-next 09/10] bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr

Quoted 46 lines · Alexei Starovoitov
Quoted 32 lines · Andrii Nakryiko
Quoted 32 lines
Quoted 13 lines
Quoted 13 lines

I agree this is simpler, but I'm not sure it will work properly. Verifier won't know when the lifetime of the buffer ends, so if we disallow spills until its written over it's going to be a pain for users.

Something like:

for (...) {
        char buf[64];
        bpf_dynptr_slice_rdwr(..., buf, 64);
        ...
}
Quoted 7 lines
Quoted 3 lines

.. and then compiler decides to spill something where buf was located on stack outside the for loop. The verifier can't know when buf goes out of scope to unpoison the slots.

You're saying the "verifier doesn't know when buf ...". The same applies to the compiler. It has no visibility into what bpf_dynptr_slice_rdwr is doing.

That is true, it can't assume anything about the side effects. But I am talking about the point in the program when the buffer object no longer lives. Use of the escaped pointer to such an object any longer is UB. The compiler is well within its rights to reuse its stack storage at that point, including for spilling registers. Which is why "outside the for loop" in my earlier reply.

Quoted 4 lines

So it never spills into a declared C array
as I tried to explain in the previous reply. Spill/fill slots are always invisible to C. (unless of course you do pointer arithmetic asm style)

Quoted 5 lines
Quoted 5 lines

When the declared array's lifetime ends, it can.
https://godbolt.org/z/Ez7v4xfnv

The 2nd call to bar as part of unrolled loop happens with fp-8, then it calls baz, spills r0 to fp-8, and calls bar again with fp-8.

Right. If user writes such program and does explicit store of spillable pointer into a stack.
I was talking about compiler generated spill/fill and I still believe that compiler will not be reusing variable's stack memory for them.

Quoted 1 line
Quoted 1 line
Quoted 6 lines
Quoted 1 line
Quoted 1 line

If such a stack slot is STACK_POISON, verifier will reject this program.

Yes and I think it's an ok trade-off.
The user has to specifically code such program to hit this issue. I don't think we will see this in practice.
If we do we can consider a more complex fix.

I was just debugging (a completely unrelated) issue where two completely independent functions, with different local variables, were reusing the same stack slots just because of them being inlined in parent functions. So stack reuse happens all the time, unfortunately. It's not always obvious or malicious.

Quoted 43 lines
Quoted 37 lines
Quoted 30 lines
Quoted 30 lines
Quoted 29 lines
Quoted 17 lines
Quoted 17 lines
(quoted diff) +3 -0
+       *(void **)eth = (void *)0xdeadbeef;
+       ctx = *(void **)buffer;
+       eth_proto = eth->eth_proto + ctx->len;
        if (eth_proto == bpf_htons(ETH_P_IP))
                err = process_packet(&ptr, eth, nh_off, false, ctx);

I think the proper fix is to treat it as a separate return type distinct from PTR_TO_MEM like PTR_TO_MEM_OR_PKT (or handle PTR_TO_MEM | DYNPTR_* specially), fork verifier state whenever there is a write, so that one path verifies it as PTR_TO_PACKET, while another as PTR_TO_STACK (if buffer was a stack ptr). I think for the rest it's not a problem, but there are allow_ptr_leak checks applied to PTR_TO_STACK and PTR_TO_MAP_VALUE, so that needs to be rechecked. Then we ensure that program is safe in either path.

Quoted 5 lines
Quoted 3 lines

Also we need to fix regsafe to not consider other PTR_TO_MEMs equivalent to such a pointer. We could also fork verifier states on return, to verify either path separately right from the point following the call instruction.

This is too complex imo.

A better way to phrase this is to verify with R0 = PTR_TO_PACKET in one path, and push_stack with R0 = buffer's reg->type + size set to len in the other path for exploration later. In terms of verifier infra everything is there already, it just needs to analyze both cases which fall into the regular code handling the reg->type's. Probably then no adjustments to regsafe are needed either. It's like exploring branch instructions.

Quoted 2 lines
Quoted 2 lines

I still don't like it. There is no reason to go a complex path when much simpler suffices.

This issue you are discussing is the reason we don't support bpf_dynptr_from_mem() taking PTR_TO_STACK (which is a pity, but we postponed it initially).

Quoted 5 lines

I've been thinking about something along the lines of STACK_POISON, but remembering associated id/ref_obj_id. When ref is released, turn STACK_POISON to STACK_MISC. If it's bpf_dynptr_slice_rdrw() or bpf_dynptr_from_mem(), which don't have ref_obj_id, they still have ID associated with returned pointer, so can we somehow incorporate that?

Quoted 4 lines

There is dynptr_id in PTR_TO_MEM that is used by destroy_if_dynptr_stack_slot(), but I don't see how we can use it to help this case.
imo plain STACK_POISON that is overwriteable by STACK_MISC/STACK_ZERO should be good enough in practice.

That's basically what I'm proposing, except when this overwrite happens we have to go and invalidate all the PTR_TO_MEM references that are pointing to that stack slot. E.g., in the below case (assuming we allow LOCAL dynptr to be constructed from stack)

char buf[256], *p;
struct bpf_dynptr dptr;

bpf_dynptr_from_mem(buf, buf+256, &dptr);

p = bpf_dynptr_data(&dptr, 128, 16); /* get 16-byte slice into buf, at offset 128 */

/* buf[128] through buf[128+16] are STACK_POISON */

buf[128] = 123;

So here is where the problem happens. Should we invalidate just p here? Or entire dptr? Haven't thought much about details, but something like that. It was getting messy when we started to think about this with Joanne.

Quoted 3 lines

We can potentially do some liveness trick. When PTR_TO_MEM with dynptr_id becomes REG_LIVE_DONE we can convert STACK_POISON. But I'd go with the simplest approach first.

#23 lore raw

Re: [PATCH v13 bpf-next 09/10] bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr

Quoted 122 lines · Andrii Nakryiko
Quoted 46 lines · Alexei Starovoitov
Quoted 32 lines · Andrii Nakryiko
Quoted 32 lines
Quoted 13 lines
Quoted 13 lines

I agree this is simpler, but I'm not sure it will work properly. Verifier won't know when the lifetime of the buffer ends, so if we disallow spills until its written over it's going to be a pain for users.

Something like:

for (...) {
        char buf[64];
        bpf_dynptr_slice_rdwr(..., buf, 64);
        ...
}
Quoted 7 lines
Quoted 3 lines

.. and then compiler decides to spill something where buf was located on stack outside the for loop. The verifier can't know when buf goes out of scope to unpoison the slots.

You're saying the "verifier doesn't know when buf ...". The same applies to the compiler. It has no visibility into what bpf_dynptr_slice_rdwr is doing.

That is true, it can't assume anything about the side effects. But I am talking about the point in the program when the buffer object no longer lives. Use of the escaped pointer to such an object any longer is UB. The compiler is well within its rights to reuse its stack storage at that point, including for spilling registers. Which is why "outside the for loop" in my earlier reply.

Quoted 4 lines

So it never spills into a declared C array
as I tried to explain in the previous reply. Spill/fill slots are always invisible to C. (unless of course you do pointer arithmetic asm style)

Quoted 5 lines
Quoted 5 lines

When the declared array's lifetime ends, it can.
https://godbolt.org/z/Ez7v4xfnv

The 2nd call to bar as part of unrolled loop happens with fp-8, then it calls baz, spills r0 to fp-8, and calls bar again with fp-8.

Right. If user writes such program and does explicit store of spillable pointer into a stack.
I was talking about compiler generated spill/fill and I still believe that compiler will not be reusing variable's stack memory for them.

Quoted 1 line
Quoted 1 line
Quoted 6 lines
Quoted 1 line
Quoted 1 line

If such a stack slot is STACK_POISON, verifier will reject this program.

Yes and I think it's an ok trade-off.
The user has to specifically code such program to hit this issue. I don't think we will see this in practice.
If we do we can consider a more complex fix.

I was just debugging (a completely unrelated) issue where two completely independent functions, with different local variables, were reusing the same stack slots just because of them being inlined in parent functions. So stack reuse happens all the time, unfortunately. It's not always obvious or malicious.

Quoted 43 lines
Quoted 37 lines
Quoted 30 lines
Quoted 30 lines
Quoted 29 lines
Quoted 17 lines
Quoted 17 lines
(quoted diff) +3 -0
+       *(void **)eth = (void *)0xdeadbeef;
+       ctx = *(void **)buffer;
+       eth_proto = eth->eth_proto + ctx->len;
        if (eth_proto == bpf_htons(ETH_P_IP))
                err = process_packet(&ptr, eth, nh_off, false, ctx);

I think the proper fix is to treat it as a separate return type distinct from PTR_TO_MEM like PTR_TO_MEM_OR_PKT (or handle PTR_TO_MEM | DYNPTR_* specially), fork verifier state whenever there is a write, so that one path verifies it as PTR_TO_PACKET, while another as PTR_TO_STACK (if buffer was a stack ptr). I think for the rest it's not a problem, but there are allow_ptr_leak checks applied to PTR_TO_STACK and PTR_TO_MAP_VALUE, so that needs to be rechecked. Then we ensure that program is safe in either path.

Quoted 5 lines
Quoted 3 lines

Also we need to fix regsafe to not consider other PTR_TO_MEMs equivalent to such a pointer. We could also fork verifier states on return, to verify either path separately right from the point following the call instruction.

This is too complex imo.

A better way to phrase this is to verify with R0 = PTR_TO_PACKET in one path, and push_stack with R0 = buffer's reg->type + size set to len in the other path for exploration later. In terms of verifier infra everything is there already, it just needs to analyze both cases which fall into the regular code handling the reg->type's. Probably then no adjustments to regsafe are needed either. It's like exploring branch instructions.

Quoted 2 lines
Quoted 2 lines

I still don't like it. There is no reason to go a complex path when much simpler suffices.

This issue you are discussing is the reason we don't support bpf_dynptr_from_mem() taking PTR_TO_STACK (which is a pity, but we postponed it initially).

Quoted 5 lines

I've been thinking about something along the lines of STACK_POISON, but remembering associated id/ref_obj_id. When ref is released, turn STACK_POISON to STACK_MISC. If it's bpf_dynptr_slice_rdrw() or bpf_dynptr_from_mem(), which don't have ref_obj_id, they still have ID associated with returned pointer, so can we somehow incorporate that?

Quoted 4 lines

There is dynptr_id in PTR_TO_MEM that is used by destroy_if_dynptr_stack_slot(), but I don't see how we can use it to help this case.
imo plain STACK_POISON that is overwriteable by STACK_MISC/STACK_ZERO should be good enough in practice.

That's basically what I'm proposing, except when this overwrite happens we have to go and invalidate all the PTR_TO_MEM references that are pointing to that stack slot. E.g., in the below case (assuming we allow LOCAL dynptr to be constructed from stack)

char buf[256], *p;
struct bpf_dynptr dptr;

bpf_dynptr_from_mem(buf, buf+256, &dptr);

p = bpf_dynptr_data(&dptr, 128, 16); /* get 16-byte slice into buf, at offset 128 */

Quoted 9 lines

/* buf[128] through buf[128+16] are STACK_POISON */

buf[128] = 123;

So here is where the problem happens. Should we invalidate just p here? Or entire dptr? Haven't thought much about details, but something like that. It was getting messy when we started to think about this with Joanne.

I think there's also the option (for your particular case) to conservatively mark the entire range a dynptr pointing to stack represents as STACK_MISC whenever a *write* happens (through bpf_dynptr_write or pointers obtained using bpf_dynptr_data). We do know exact memory start and length when creating the dynptr, right?

If somebody tries to be funky, e.g. by doing a spill and then trying to overwrite its value, the entire range becomes STACK_MISC, so reload would just mark the reg as unknown. You can be a bit smarter when you know the exact start and length of stack memory e.g. bpf_dynptr_data pointer points to, but I'm unsure that will be needed.

Otherwise things work as normal, users can spill stuff to the stack if they wants, and as long as they are not writing through the dynptr again, we don't remark the entire range STACK_MISC. If that was the last use of dynptr and it went out of scope, things work normally. If not, the dynptr and its buffer should still be in scope so it won't be the compiler doing something funny spilling stuff into it, only the user.

Due to STACK_INVALID complications over-eager remarking as STACK_MISC might only make sense for privileged programs, but otherwise I think this is ok.

Am I missing something important?

#24 lore raw

Re: [PATCH v13 bpf-next 09/10] bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr

In reply to Andrii Nakryiko
Quoted 56 lines · Andrii Nakryiko
Quoted 46 lines · Alexei Starovoitov
Quoted 32 lines · Andrii Nakryiko
Quoted 32 lines
Quoted 13 lines
Quoted 13 lines

I agree this is simpler, but I'm not sure it will work properly. Verifier won't know when the lifetime of the buffer ends, so if we disallow spills until its written over it's going to be a pain for users.

Something like:

for (...) {
        char buf[64];
        bpf_dynptr_slice_rdwr(..., buf, 64);
        ...
}
Quoted 7 lines
Quoted 3 lines

.. and then compiler decides to spill something where buf was located on stack outside the for loop. The verifier can't know when buf goes out of scope to unpoison the slots.

You're saying the "verifier doesn't know when buf ...". The same applies to the compiler. It has no visibility into what bpf_dynptr_slice_rdwr is doing.

That is true, it can't assume anything about the side effects. But I am talking about the point in the program when the buffer object no longer lives. Use of the escaped pointer to such an object any longer is UB. The compiler is well within its rights to reuse its stack storage at that point, including for spilling registers. Which is why "outside the for loop" in my earlier reply.

Quoted 4 lines

So it never spills into a declared C array
as I tried to explain in the previous reply. Spill/fill slots are always invisible to C. (unless of course you do pointer arithmetic asm style)

Quoted 5 lines
Quoted 5 lines

When the declared array's lifetime ends, it can.
https://godbolt.org/z/Ez7v4xfnv

The 2nd call to bar as part of unrolled loop happens with fp-8, then it calls baz, spills r0 to fp-8, and calls bar again with fp-8.

Right. If user writes such program and does explicit store of spillable pointer into a stack.
I was talking about compiler generated spill/fill and I still believe that compiler will not be reusing variable's stack memory for them.

Quoted 1 line
Quoted 1 line
Quoted 6 lines
Quoted 1 line
Quoted 1 line

If such a stack slot is STACK_POISON, verifier will reject this program.

Yes and I think it's an ok trade-off.
The user has to specifically code such program to hit this issue. I don't think we will see this in practice.
If we do we can consider a more complex fix.

Quoted 5 lines

I was just debugging (a completely unrelated) issue where two completely independent functions, with different local variables, were reusing the same stack slots just because of them being inlined in parent functions. So stack reuse happens all the time, unfortunately. It's not always obvious or malicious.

Right. Stack reuse happens for variables all the time. I'm still arguing that compile internal spill/fill is coming from different slots.

When clang compiles the kernel it prints:
../kernel/bpf/verifier.c:18017:5: warning: stack frame size (2296) exceeds limit (2048) in 'bpf_check' [-Wframe-larger-than]
int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)

    ^

572/2296 (24.91%) spills, 1724/2296 (75.09%) variables

spills and variables are different areas.

Quoted 61 lines
Quoted 43 lines
Quoted 37 lines
Quoted 30 lines
Quoted 30 lines
Quoted 29 lines
Quoted 17 lines
Quoted 17 lines
(quoted diff) +3 -0
+       *(void **)eth = (void *)0xdeadbeef;
+       ctx = *(void **)buffer;
+       eth_proto = eth->eth_proto + ctx->len;
        if (eth_proto == bpf_htons(ETH_P_IP))
                err = process_packet(&ptr, eth, nh_off, false, ctx);

I think the proper fix is to treat it as a separate return type distinct from PTR_TO_MEM like PTR_TO_MEM_OR_PKT (or handle PTR_TO_MEM | DYNPTR_* specially), fork verifier state whenever there is a write, so that one path verifies it as PTR_TO_PACKET, while another as PTR_TO_STACK (if buffer was a stack ptr). I think for the rest it's not a problem, but there are allow_ptr_leak checks applied to PTR_TO_STACK and PTR_TO_MAP_VALUE, so that needs to be rechecked. Then we ensure that program is safe in either path.

Quoted 5 lines
Quoted 3 lines

Also we need to fix regsafe to not consider other PTR_TO_MEMs equivalent to such a pointer. We could also fork verifier states on return, to verify either path separately right from the point following the call instruction.

This is too complex imo.

A better way to phrase this is to verify with R0 = PTR_TO_PACKET in one path, and push_stack with R0 = buffer's reg->type + size set to len in the other path for exploration later. In terms of verifier infra everything is there already, it just needs to analyze both cases which fall into the regular code handling the reg->type's. Probably then no adjustments to regsafe are needed either. It's like exploring branch instructions.

Quoted 2 lines
Quoted 2 lines

I still don't like it. There is no reason to go a complex path when much simpler suffices.

This issue you are discussing is the reason we don't support bpf_dynptr_from_mem() taking PTR_TO_STACK (which is a pity, but we postponed it initially).

Quoted 5 lines

I've been thinking about something along the lines of STACK_POISON, but remembering associated id/ref_obj_id. When ref is released, turn STACK_POISON to STACK_MISC. If it's bpf_dynptr_slice_rdrw() or bpf_dynptr_from_mem(), which don't have ref_obj_id, they still have ID associated with returned pointer, so can we somehow incorporate that?

Quoted 4 lines

There is dynptr_id in PTR_TO_MEM that is used by destroy_if_dynptr_stack_slot(), but I don't see how we can use it to help this case.
imo plain STACK_POISON that is overwriteable by STACK_MISC/STACK_ZERO should be good enough in practice.

That's basically what I'm proposing, except when this overwrite happens we have to go and invalidate all the PTR_TO_MEM references that are pointing to that stack slot. E.g., in the below case (assuming we allow LOCAL dynptr to be constructed from stack)

char buf[256], *p;
struct bpf_dynptr dptr;

bpf_dynptr_from_mem(buf, buf+256, &dptr);

p = bpf_dynptr_data(&dptr, 128, 16); /* get 16-byte slice into buf, at offset 128 */

Quoted 8 lines

/* buf[128] through buf[128+16] are STACK_POISON */

buf[128] = 123;

So here is where the problem happens. Should we invalidate just p here? Or entire dptr? Haven't thought much about details, but something like that. It was getting messy when we started to think about this with Joanne.

Let's table dynptr_from_mem for a second and solve bpf_dynptr_slice_rdrw first, since I'm getting confused.

For bpf_dynptr_slice_rdrw we can mark buffer[] in stack as poisoned with dynptr_id == R0's PTR_TO_MEM dynptr_id. Then as soon as first spillable reg touches that poisoned stack area we can invalidate all PTR_TO_MEM's with that dynptr_id.

#25 lore raw

Re: [PATCH v13 bpf-next 09/10] bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr

Quoted 148 lines · Alexei Starovoitov
Quoted 56 lines · Andrii Nakryiko
Quoted 46 lines · Alexei Starovoitov
Quoted 32 lines · Andrii Nakryiko
Quoted 32 lines
Quoted 13 lines
Quoted 13 lines

I agree this is simpler, but I'm not sure it will work properly. Verifier won't know when the lifetime of the buffer ends, so if we disallow spills until its written over it's going to be a pain for users.

Something like:

for (...) {
        char buf[64];
        bpf_dynptr_slice_rdwr(..., buf, 64);
        ...
}
Quoted 7 lines
Quoted 3 lines

.. and then compiler decides to spill something where buf was located on stack outside the for loop. The verifier can't know when buf goes out of scope to unpoison the slots.

You're saying the "verifier doesn't know when buf ...". The same applies to the compiler. It has no visibility into what bpf_dynptr_slice_rdwr is doing.

That is true, it can't assume anything about the side effects. But I am talking about the point in the program when the buffer object no longer lives. Use of the escaped pointer to such an object any longer is UB. The compiler is well within its rights to reuse its stack storage at that point, including for spilling registers. Which is why "outside the for loop" in my earlier reply.

Quoted 4 lines

So it never spills into a declared C array
as I tried to explain in the previous reply. Spill/fill slots are always invisible to C. (unless of course you do pointer arithmetic asm style)

Quoted 5 lines
Quoted 5 lines

When the declared array's lifetime ends, it can.
https://godbolt.org/z/Ez7v4xfnv

The 2nd call to bar as part of unrolled loop happens with fp-8, then it calls baz, spills r0 to fp-8, and calls bar again with fp-8.

Right. If user writes such program and does explicit store of spillable pointer into a stack.
I was talking about compiler generated spill/fill and I still believe that compiler will not be reusing variable's stack memory for them.

Quoted 1 line
Quoted 1 line
Quoted 6 lines
Quoted 1 line
Quoted 1 line

If such a stack slot is STACK_POISON, verifier will reject this program.

Yes and I think it's an ok trade-off.
The user has to specifically code such program to hit this issue. I don't think we will see this in practice.
If we do we can consider a more complex fix.

Quoted 5 lines

I was just debugging (a completely unrelated) issue where two completely independent functions, with different local variables, were reusing the same stack slots just because of them being inlined in parent functions. So stack reuse happens all the time, unfortunately. It's not always obvious or malicious.

Right. Stack reuse happens for variables all the time. I'm still arguing that compile internal spill/fill is coming from different slots.

When clang compiles the kernel it prints:
../kernel/bpf/verifier.c:18017:5: warning: stack frame size (2296) exceeds limit (2048) in 'bpf_check' [-Wframe-larger-than]
int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)

    ^

572/2296 (24.91%) spills, 1724/2296 (75.09%) variables

spills and variables are different areas.

Quoted 61 lines
Quoted 43 lines
Quoted 37 lines
Quoted 30 lines
Quoted 30 lines
Quoted 29 lines
Quoted 17 lines
Quoted 17 lines
(quoted diff) +3 -0
+       *(void **)eth = (void *)0xdeadbeef;
+       ctx = *(void **)buffer;
+       eth_proto = eth->eth_proto + ctx->len;
        if (eth_proto == bpf_htons(ETH_P_IP))
                err = process_packet(&ptr, eth, nh_off, false, ctx);

I think the proper fix is to treat it as a separate return type distinct from PTR_TO_MEM like PTR_TO_MEM_OR_PKT (or handle PTR_TO_MEM | DYNPTR_* specially), fork verifier state whenever there is a write, so that one path verifies it as PTR_TO_PACKET, while another as PTR_TO_STACK (if buffer was a stack ptr). I think for the rest it's not a problem, but there are allow_ptr_leak checks applied to PTR_TO_STACK and PTR_TO_MAP_VALUE, so that needs to be rechecked. Then we ensure that program is safe in either path.

Quoted 5 lines
Quoted 3 lines

Also we need to fix regsafe to not consider other PTR_TO_MEMs equivalent to such a pointer. We could also fork verifier states on return, to verify either path separately right from the point following the call instruction.

This is too complex imo.

A better way to phrase this is to verify with R0 = PTR_TO_PACKET in one path, and push_stack with R0 = buffer's reg->type + size set to len in the other path for exploration later. In terms of verifier infra everything is there already, it just needs to analyze both cases which fall into the regular code handling the reg->type's. Probably then no adjustments to regsafe are needed either. It's like exploring branch instructions.

Quoted 2 lines
Quoted 2 lines

I still don't like it. There is no reason to go a complex path when much simpler suffices.

This issue you are discussing is the reason we don't support bpf_dynptr_from_mem() taking PTR_TO_STACK (which is a pity, but we postponed it initially).

Quoted 5 lines

I've been thinking about something along the lines of STACK_POISON, but remembering associated id/ref_obj_id. When ref is released, turn STACK_POISON to STACK_MISC. If it's bpf_dynptr_slice_rdrw() or bpf_dynptr_from_mem(), which don't have ref_obj_id, they still have ID associated with returned pointer, so can we somehow incorporate that?

Quoted 4 lines

There is dynptr_id in PTR_TO_MEM that is used by destroy_if_dynptr_stack_slot(), but I don't see how we can use it to help this case.
imo plain STACK_POISON that is overwriteable by STACK_MISC/STACK_ZERO should be good enough in practice.

That's basically what I'm proposing, except when this overwrite happens we have to go and invalidate all the PTR_TO_MEM references that are pointing to that stack slot. E.g., in the below case (assuming we allow LOCAL dynptr to be constructed from stack)

char buf[256], *p;
struct bpf_dynptr dptr;

bpf_dynptr_from_mem(buf, buf+256, &dptr);

p = bpf_dynptr_data(&dptr, 128, 16); /* get 16-byte slice into buf, at offset 128 */

Quoted 8 lines

/* buf[128] through buf[128+16] are STACK_POISON */

buf[128] = 123;

So here is where the problem happens. Should we invalidate just p here? Or entire dptr? Haven't thought much about details, but something like that. It was getting messy when we started to think about this with Joanne.

Quoted 7 lines

Let's table dynptr_from_mem for a second and solve bpf_dynptr_slice_rdrw first, since I'm getting confused.

For bpf_dynptr_slice_rdrw we can mark buffer[] in stack as poisoned with dynptr_id == R0's PTR_TO_MEM dynptr_id. Then as soon as first spillable reg touches that poisoned stack area we can invalidate all PTR_TO_MEM's with that dynptr_id.

Okay, this makes sense to me. are you already currently working or planning to work on a fix for this Kumar, or should i take a stab at it?

#26 lore raw

Re: [PATCH v13 bpf-next 09/10] bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr

Quoted 153 lines · Joanne Koong
Quoted 151 lines · Alexei Starovoitov
Quoted 56 lines · Andrii Nakryiko
Quoted 46 lines · Alexei Starovoitov
Quoted 32 lines · Andrii Nakryiko
Quoted 32 lines
Quoted 13 lines
Quoted 13 lines

I agree this is simpler, but I'm not sure it will work properly. Verifier won't know when the lifetime of the buffer ends, so if we disallow spills until its written over it's going to be a pain for users.

Something like:

for (...) {
        char buf[64];
        bpf_dynptr_slice_rdwr(..., buf, 64);
        ...
}
Quoted 7 lines
Quoted 3 lines

.. and then compiler decides to spill something where buf was located on stack outside the for loop. The verifier can't know when buf goes out of scope to unpoison the slots.

You're saying the "verifier doesn't know when buf ...". The same applies to the compiler. It has no visibility into what bpf_dynptr_slice_rdwr is doing.

That is true, it can't assume anything about the side effects. But I am talking about the point in the program when the buffer object no longer lives. Use of the escaped pointer to such an object any longer is UB. The compiler is well within its rights to reuse its stack storage at that point, including for spilling registers. Which is why "outside the for loop" in my earlier reply.

Quoted 4 lines

So it never spills into a declared C array
as I tried to explain in the previous reply. Spill/fill slots are always invisible to C. (unless of course you do pointer arithmetic asm style)

Quoted 5 lines
Quoted 5 lines

When the declared array's lifetime ends, it can.
https://godbolt.org/z/Ez7v4xfnv

The 2nd call to bar as part of unrolled loop happens with fp-8, then it calls baz, spills r0 to fp-8, and calls bar again with fp-8.

Right. If user writes such program and does explicit store of spillable pointer into a stack.
I was talking about compiler generated spill/fill and I still believe that compiler will not be reusing variable's stack memory for them.

Quoted 1 line
Quoted 1 line
Quoted 6 lines
Quoted 1 line
Quoted 1 line

If such a stack slot is STACK_POISON, verifier will reject this program.

Yes and I think it's an ok trade-off.
The user has to specifically code such program to hit this issue. I don't think we will see this in practice.
If we do we can consider a more complex fix.

Quoted 5 lines

I was just debugging (a completely unrelated) issue where two completely independent functions, with different local variables, were reusing the same stack slots just because of them being inlined in parent functions. So stack reuse happens all the time, unfortunately. It's not always obvious or malicious.

Right. Stack reuse happens for variables all the time. I'm still arguing that compile internal spill/fill is coming from different slots.

When clang compiles the kernel it prints:
../kernel/bpf/verifier.c:18017:5: warning: stack frame size (2296) exceeds limit (2048) in 'bpf_check' [-Wframe-larger-than]
int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)

    ^

572/2296 (24.91%) spills, 1724/2296 (75.09%) variables

spills and variables are different areas.

Quoted 61 lines
Quoted 43 lines
Quoted 37 lines
Quoted 30 lines
Quoted 30 lines
Quoted 29 lines
Quoted 17 lines
Quoted 17 lines
(quoted diff) +3 -0
+       *(void **)eth = (void *)0xdeadbeef;
+       ctx = *(void **)buffer;
+       eth_proto = eth->eth_proto + ctx->len;
        if (eth_proto == bpf_htons(ETH_P_IP))
                err = process_packet(&ptr, eth, nh_off, false, ctx);

I think the proper fix is to treat it as a separate return type distinct from PTR_TO_MEM like PTR_TO_MEM_OR_PKT (or handle PTR_TO_MEM | DYNPTR_* specially), fork verifier state whenever there is a write, so that one path verifies it as PTR_TO_PACKET, while another as PTR_TO_STACK (if buffer was a stack ptr). I think for the rest it's not a problem, but there are allow_ptr_leak checks applied to PTR_TO_STACK and PTR_TO_MAP_VALUE, so that needs to be rechecked. Then we ensure that program is safe in either path.

Quoted 5 lines
Quoted 3 lines

Also we need to fix regsafe to not consider other PTR_TO_MEMs equivalent to such a pointer. We could also fork verifier states on return, to verify either path separately right from the point following the call instruction.

This is too complex imo.

A better way to phrase this is to verify with R0 = PTR_TO_PACKET in one path, and push_stack with R0 = buffer's reg->type + size set to len in the other path for exploration later. In terms of verifier infra everything is there already, it just needs to analyze both cases which fall into the regular code handling the reg->type's. Probably then no adjustments to regsafe are needed either. It's like exploring branch instructions.

Quoted 2 lines
Quoted 2 lines

I still don't like it. There is no reason to go a complex path when much simpler suffices.

This issue you are discussing is the reason we don't support bpf_dynptr_from_mem() taking PTR_TO_STACK (which is a pity, but we postponed it initially).

Quoted 5 lines

I've been thinking about something along the lines of STACK_POISON, but remembering associated id/ref_obj_id. When ref is released, turn STACK_POISON to STACK_MISC. If it's bpf_dynptr_slice_rdrw() or bpf_dynptr_from_mem(), which don't have ref_obj_id, they still have ID associated with returned pointer, so can we somehow incorporate that?

Quoted 4 lines

There is dynptr_id in PTR_TO_MEM that is used by destroy_if_dynptr_stack_slot(), but I don't see how we can use it to help this case.
imo plain STACK_POISON that is overwriteable by STACK_MISC/STACK_ZERO should be good enough in practice.

That's basically what I'm proposing, except when this overwrite happens we have to go and invalidate all the PTR_TO_MEM references that are pointing to that stack slot. E.g., in the below case (assuming we allow LOCAL dynptr to be constructed from stack)

char buf[256], *p;
struct bpf_dynptr dptr;

bpf_dynptr_from_mem(buf, buf+256, &dptr);

p = bpf_dynptr_data(&dptr, 128, 16); /* get 16-byte slice into buf, at offset 128 */

Quoted 8 lines

/* buf[128] through buf[128+16] are STACK_POISON */

buf[128] = 123;

So here is where the problem happens. Should we invalidate just p here? Or entire dptr? Haven't thought much about details, but something like that. It was getting messy when we started to think about this with Joanne.

Let's table dynptr_from_mem for a second and solve bpf_dynptr_slice_rdrw first, since I'm getting confused.

Quoted 8 lines
Quoted 4 lines

For bpf_dynptr_slice_rdrw we can mark buffer[] in stack as poisoned with dynptr_id == R0's PTR_TO_MEM dynptr_id. Then as soon as first spillable reg touches that poisoned stack area we can invalidate all PTR_TO_MEM's with that dynptr_id.

Okay, this makes sense to me. are you already currently working or planning to work on a fix for this Kumar, or should i take a stab at it?

I'm not planning to do so, so go ahead. One more thing I noticed just now is that we probably need to update regsafe to perform a check_ids comparison for dynptr_id for dynptr PTR_TO_MEMs? It was not a problem back when f8064ab90d66 ("bpf: Invalidate slices on destruction of dynptrs on stack") was added but 567da5d253cd ("bpf: improve regsafe() checks for PTR_TO_{MEM,BUF,TP_BUFFER}") added PTR_TO_MEM in the switch statement.

#27 lore raw

Re: [PATCH v13 bpf-next 09/10] bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr

Quoted 164 lines · Kumar Kartikeya Dwivedi
Quoted 153 lines · Joanne Koong
Quoted 151 lines · Alexei Starovoitov
Quoted 56 lines · Andrii Nakryiko
Quoted 46 lines · Alexei Starovoitov
Quoted 32 lines · Andrii Nakryiko
Quoted 32 lines
Quoted 13 lines
Quoted 13 lines

I agree this is simpler, but I'm not sure it will work properly. Verifier won't know when the lifetime of the buffer ends, so if we disallow spills until its written over it's going to be a pain for users.

Something like:

for (...) {
        char buf[64];
        bpf_dynptr_slice_rdwr(..., buf, 64);
        ...
}
Quoted 7 lines
Quoted 3 lines

.. and then compiler decides to spill something where buf was located on stack outside the for loop. The verifier can't know when buf goes out of scope to unpoison the slots.

You're saying the "verifier doesn't know when buf ...". The same applies to the compiler. It has no visibility into what bpf_dynptr_slice_rdwr is doing.

That is true, it can't assume anything about the side effects. But I am talking about the point in the program when the buffer object no longer lives. Use of the escaped pointer to such an object any longer is UB. The compiler is well within its rights to reuse its stack storage at that point, including for spilling registers. Which is why "outside the for loop" in my earlier reply.

Quoted 4 lines

So it never spills into a declared C array
as I tried to explain in the previous reply. Spill/fill slots are always invisible to C. (unless of course you do pointer arithmetic asm style)

Quoted 5 lines
Quoted 5 lines

When the declared array's lifetime ends, it can.
https://godbolt.org/z/Ez7v4xfnv

The 2nd call to bar as part of unrolled loop happens with fp-8, then it calls baz, spills r0 to fp-8, and calls bar again with fp-8.

Right. If user writes such program and does explicit store of spillable pointer into a stack.
I was talking about compiler generated spill/fill and I still believe that compiler will not be reusing variable's stack memory for them.

Quoted 1 line
Quoted 1 line
Quoted 6 lines
Quoted 1 line
Quoted 1 line

If such a stack slot is STACK_POISON, verifier will reject this program.

Yes and I think it's an ok trade-off.
The user has to specifically code such program to hit this issue. I don't think we will see this in practice.
If we do we can consider a more complex fix.

Quoted 5 lines

I was just debugging (a completely unrelated) issue where two completely independent functions, with different local variables, were reusing the same stack slots just because of them being inlined in parent functions. So stack reuse happens all the time, unfortunately. It's not always obvious or malicious.

Right. Stack reuse happens for variables all the time. I'm still arguing that compile internal spill/fill is coming from different slots.

When clang compiles the kernel it prints:
../kernel/bpf/verifier.c:18017:5: warning: stack frame size (2296) exceeds limit (2048) in 'bpf_check' [-Wframe-larger-than]
int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)

    ^

572/2296 (24.91%) spills, 1724/2296 (75.09%) variables

spills and variables are different areas.

Quoted 61 lines
Quoted 43 lines
Quoted 37 lines
Quoted 30 lines
Quoted 30 lines
Quoted 29 lines
Quoted 17 lines
Quoted 17 lines
(quoted diff) +3 -0
+       *(void **)eth = (void *)0xdeadbeef;
+       ctx = *(void **)buffer;
+       eth_proto = eth->eth_proto + ctx->len;
        if (eth_proto == bpf_htons(ETH_P_IP))
                err = process_packet(&ptr, eth, nh_off, false, ctx);

I think the proper fix is to treat it as a separate return type distinct from PTR_TO_MEM like PTR_TO_MEM_OR_PKT (or handle PTR_TO_MEM | DYNPTR_* specially), fork verifier state whenever there is a write, so that one path verifies it as PTR_TO_PACKET, while another as PTR_TO_STACK (if buffer was a stack ptr). I think for the rest it's not a problem, but there are allow_ptr_leak checks applied to PTR_TO_STACK and PTR_TO_MAP_VALUE, so that needs to be rechecked. Then we ensure that program is safe in either path.

Quoted 5 lines
Quoted 3 lines

Also we need to fix regsafe to not consider other PTR_TO_MEMs equivalent to such a pointer. We could also fork verifier states on return, to verify either path separately right from the point following the call instruction.

This is too complex imo.

A better way to phrase this is to verify with R0 = PTR_TO_PACKET in one path, and push_stack with R0 = buffer's reg->type + size set to len in the other path for exploration later. In terms of verifier infra everything is there already, it just needs to analyze both cases which fall into the regular code handling the reg->type's. Probably then no adjustments to regsafe are needed either. It's like exploring branch instructions.

Quoted 2 lines
Quoted 2 lines

I still don't like it. There is no reason to go a complex path when much simpler suffices.

This issue you are discussing is the reason we don't support bpf_dynptr_from_mem() taking PTR_TO_STACK (which is a pity, but we postponed it initially).

Quoted 5 lines

I've been thinking about something along the lines of STACK_POISON, but remembering associated id/ref_obj_id. When ref is released, turn STACK_POISON to STACK_MISC. If it's bpf_dynptr_slice_rdrw() or bpf_dynptr_from_mem(), which don't have ref_obj_id, they still have ID associated with returned pointer, so can we somehow incorporate that?

Quoted 4 lines

There is dynptr_id in PTR_TO_MEM that is used by destroy_if_dynptr_stack_slot(), but I don't see how we can use it to help this case.
imo plain STACK_POISON that is overwriteable by STACK_MISC/STACK_ZERO should be good enough in practice.

That's basically what I'm proposing, except when this overwrite happens we have to go and invalidate all the PTR_TO_MEM references that are pointing to that stack slot. E.g., in the below case (assuming we allow LOCAL dynptr to be constructed from stack)

char buf[256], *p;
struct bpf_dynptr dptr;

bpf_dynptr_from_mem(buf, buf+256, &dptr);

p = bpf_dynptr_data(&dptr, 128, 16); /* get 16-byte slice into buf, at offset 128 */

Quoted 8 lines

/* buf[128] through buf[128+16] are STACK_POISON */

buf[128] = 123;

So here is where the problem happens. Should we invalidate just p here? Or entire dptr? Haven't thought much about details, but something like that. It was getting messy when we started to think about this with Joanne.

Let's table dynptr_from_mem for a second and solve bpf_dynptr_slice_rdrw first, since I'm getting confused.

Quoted 8 lines
Quoted 4 lines

For bpf_dynptr_slice_rdrw we can mark buffer[] in stack as poisoned with dynptr_id == R0's PTR_TO_MEM dynptr_id. Then as soon as first spillable reg touches that poisoned stack area we can invalidate all PTR_TO_MEM's with that dynptr_id.

Okay, this makes sense to me. are you already currently working or planning to work on a fix for this Kumar, or should i take a stab at it?

Quoted 6 lines

I'm not planning to do so, so go ahead. One more thing I noticed just now is that we probably need to update regsafe to perform a check_ids comparison for dynptr_id for dynptr PTR_TO_MEMs? It was not a problem back when f8064ab90d66 ("bpf: Invalidate slices on destruction of dynptrs on stack") was added but 567da5d253cd ("bpf: improve regsafe() checks for PTR_TO_{MEM,BUF,TP_BUFFER}") added PTR_TO_MEM in the switch statement.

I can take care of this. But I really would like to avoid these special cases of extra dynptr_id, exactly for reasons like this omitted check.

What do people think about generalizing current ref_obj_id to be more like "lifetime id" (to borrow Rust terminology a bit), which would be an object (which might or might not be a tracked reference) defining the scope/lifetime of the current register (whatever it represents).

I haven't looked through code much, but I've been treating ref_obj_id as that already in my thinking before, and it seems to be a better approach than having a special-case of dynptr_id.

Thoughts?

#28 lore raw

Re: [PATCH v13 bpf-next 09/10] bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr

Quoted 4 lines · Andrii Nakryiko
Quoted 1 line · Kumar Kartikeya Dwivedi

[...]

Quoted 25 lines
Quoted 9 lines
Quoted 8 lines
Quoted 4 lines

For bpf_dynptr_slice_rdrw we can mark buffer[] in stack as poisoned with dynptr_id == R0's PTR_TO_MEM dynptr_id. Then as soon as first spillable reg touches that poisoned stack area we can invalidate all PTR_TO_MEM's with that dynptr_id.

Okay, this makes sense to me. are you already currently working or planning to work on a fix for this Kumar, or should i take a stab at it?

Quoted 6 lines

I'm not planning to do so, so go ahead. One more thing I noticed just now is that we probably need to update regsafe to perform a check_ids comparison for dynptr_id for dynptr PTR_TO_MEMs? It was not a problem back when f8064ab90d66 ("bpf: Invalidate slices on destruction of dynptrs on stack") was added but 567da5d253cd ("bpf: improve regsafe() checks for PTR_TO_{MEM,BUF,TP_BUFFER}") added PTR_TO_MEM in the switch statement.

I can take care of this. But I really would like to avoid these special cases of extra dynptr_id, exactly for reasons like this omitted check.

What do people think about generalizing current ref_obj_id to be more like "lifetime id" (to borrow Rust terminology a bit), which would be an object (which might or might not be a tracked reference) defining the scope/lifetime of the current register (whatever it represents).

Quoted 5 lines

I haven't looked through code much, but I've been treating ref_obj_id as that already in my thinking before, and it seems to be a better approach than having a special-case of dynptr_id.

Thoughts?

Thanks for taking care of this (and apologies for the late reply). i think the dynptr_id field would still be needed in this case to associate a slice with a dynptr, so that when a dynptr is invalidated its slices get invalidated as well. I'm not sure we could get away with just having ref_obj_id symbolize that in the case where the underlying object is a tracked reference, because for example, it seems like a dynptr would need both a unique reference id to the object (so that if for example there are two dynptrs pointing to the same object, they will both be assignedthe same reference id so the object can't for example be freed twice) and also its own dynptr id so that its slices get invalidated if the dynptr is invalidated

#29 lore raw

Re: [PATCH v13 bpf-next 09/10] bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr

Quoted 39 lines · Joanne Koong
Quoted 4 lines · Andrii Nakryiko
Quoted 1 line · Kumar Kartikeya Dwivedi

[...]

Quoted 25 lines
Quoted 9 lines
Quoted 8 lines
Quoted 4 lines

For bpf_dynptr_slice_rdrw we can mark buffer[] in stack as poisoned with dynptr_id == R0's PTR_TO_MEM dynptr_id. Then as soon as first spillable reg touches that poisoned stack area we can invalidate all PTR_TO_MEM's with that dynptr_id.

Okay, this makes sense to me. are you already currently working or planning to work on a fix for this Kumar, or should i take a stab at it?

Quoted 6 lines

I'm not planning to do so, so go ahead. One more thing I noticed just now is that we probably need to update regsafe to perform a check_ids comparison for dynptr_id for dynptr PTR_TO_MEMs? It was not a problem back when f8064ab90d66 ("bpf: Invalidate slices on destruction of dynptrs on stack") was added but 567da5d253cd ("bpf: improve regsafe() checks for PTR_TO_{MEM,BUF,TP_BUFFER}") added PTR_TO_MEM in the switch statement.

I can take care of this. But I really would like to avoid these special cases of extra dynptr_id, exactly for reasons like this omitted check.

What do people think about generalizing current ref_obj_id to be more like "lifetime id" (to borrow Rust terminology a bit), which would be an object (which might or might not be a tracked reference) defining the scope/lifetime of the current register (whatever it represents).

Quoted 5 lines

I haven't looked through code much, but I've been treating ref_obj_id as that already in my thinking before, and it seems to be a better approach than having a special-case of dynptr_id.

Thoughts?

Quoted 11 lines

Thanks for taking care of this (and apologies for the late reply). i think the dynptr_id field would still be needed in this case to associate a slice with a dynptr, so that when a dynptr is invalidated its slices get invalidated as well. I'm not sure we could get away with just having ref_obj_id symbolize that in the case where the underlying object is a tracked reference, because for example, it seems like a dynptr would need both a unique reference id to the object (so that if for example there are two dynptrs pointing to the same object, they will both be assignedthe same reference id so the object can't for example be freed twice) and also its own dynptr id so that its slices get invalidated if the dynptr is invalidated

Can you elaborate on specific example? Because let's say dynptr is created from some refcounted object. Then that dynptr's id field will be a unique "dynptr id", dynptr's ref_obj_id will point to that refcounted object from which we derived dynptr itself. And then when we create slices from dynptrs, then each slice gets its own unique id, but records dynptr's id as slice's ref_obj_id. So we end up with this hierarchy of id + ref_obj_id forming a tree.

Or am I missing something?

I want to take a look at simplifying this at some point, so I'll know more details once I start digging into code. Right now I still fail to see why we need a third ID for dynptr.

#30 lore raw

Re: [PATCH v13 bpf-next 09/10] bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr

Quoted 61 lines · Andrii Nakryiko
Quoted 39 lines · Joanne Koong
Quoted 4 lines · Andrii Nakryiko
Quoted 1 line · Kumar Kartikeya Dwivedi

[...]

Quoted 25 lines
Quoted 9 lines
Quoted 8 lines
Quoted 4 lines

For bpf_dynptr_slice_rdrw we can mark buffer[] in stack as poisoned with dynptr_id == R0's PTR_TO_MEM dynptr_id. Then as soon as first spillable reg touches that poisoned stack area we can invalidate all PTR_TO_MEM's with that dynptr_id.

Okay, this makes sense to me. are you already currently working or planning to work on a fix for this Kumar, or should i take a stab at it?

Quoted 6 lines

I'm not planning to do so, so go ahead. One more thing I noticed just now is that we probably need to update regsafe to perform a check_ids comparison for dynptr_id for dynptr PTR_TO_MEMs? It was not a problem back when f8064ab90d66 ("bpf: Invalidate slices on destruction of dynptrs on stack") was added but 567da5d253cd ("bpf: improve regsafe() checks for PTR_TO_{MEM,BUF,TP_BUFFER}") added PTR_TO_MEM in the switch statement.

I can take care of this. But I really would like to avoid these special cases of extra dynptr_id, exactly for reasons like this omitted check.

What do people think about generalizing current ref_obj_id to be more like "lifetime id" (to borrow Rust terminology a bit), which would be an object (which might or might not be a tracked reference) defining the scope/lifetime of the current register (whatever it represents).

Quoted 5 lines

I haven't looked through code much, but I've been treating ref_obj_id as that already in my thinking before, and it seems to be a better approach than having a special-case of dynptr_id.

Thoughts?

Quoted 11 lines

Thanks for taking care of this (and apologies for the late reply). i think the dynptr_id field would still be needed in this case to associate a slice with a dynptr, so that when a dynptr is invalidated its slices get invalidated as well. I'm not sure we could get away with just having ref_obj_id symbolize that in the case where the underlying object is a tracked reference, because for example, it seems like a dynptr would need both a unique reference id to the object (so that if for example there are two dynptrs pointing to the same object, they will both be assignedthe same reference id so the object can't for example be freed twice) and also its own dynptr id so that its slices get invalidated if the dynptr is invalidated

Can you elaborate on specific example? Because let's say dynptr is created from some refcounted object. Then that dynptr's id field will be a unique "dynptr id", dynptr's ref_obj_id will point to that refcounted object from which we derived dynptr itself. And then when we create slices from dynptrs, then each slice gets its own unique id, but records dynptr's id as slice's ref_obj_id. So we end up with this hierarchy of id + ref_obj_id forming a tree.

Quoted 5 lines

Or am I missing something?

I want to take a look at simplifying this at some point, so I'll know more details once I start digging into code. Right now I still fail to see why we need a third ID for dynptr.

My mental model is that
* dynptr's ref_obj_id is set whenver there's a refcounted object (right now, only ringbuf dynptrs are refcounted), to enforce that the reference gets released by the time the program exits (dynptr ref_obj_id is set in mark_stack_slots_dynptr())
* dynptr's dynptr id is set for all dynptrs, so that if a dynptr gets overwritten/invalidated, all slices for that dynptr get invalidated (dynptr id is set in mark_dynptr_stack_regs(), called in mark_stack_slots_dynptr())
* when there's a data slice, both the slice's dynptr id and ref_obj_id get set to the dynptr's dynptr id and ref_obj_id, so that the slice gets invalidated when either the dynptr is released or when the dynptr is overwritten (two separate cases) (the slice's dynptr id and ref obj id get set in check_helper_call()). The data slice also has its own unique id, but this is to handle the case where the data slice may be null.

"And then when we create slices from dynptrs, then each slice gets its own unique id, but records dynptr's id as slice's ref_obj_id. So we end up with this hierarchy of id + ref_obj_id forming a tree." I don't think I'm following the tree part. I think it records the dynptr's id as slice's id (and dynptr's ref obj id as slice's ref obj id) in check_helper_call().

"Right now I still fail to see why we need a third ID for dynptr". I think for dynptrs, there are two IDs:
state->stack[spi].spilled_ptr.ref_obj_id and state->stack[spi].spilled_ptr.id (where ref_obj_id is used to invalidate slices when dynptr is released and id is used to invalidates slices when dynptr is overwritten), and then for dynptr slices there are 3 IDs: reg->id, reg->dynptr_id, reg->ref_obj_id (where id is used for the data slice returning NULL case, and ref_obj_id / dynptr_id are used when dynptrs are invalidated).

#31 lore raw

Re: [PATCH v13 bpf-next 09/10] bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr

Quoted 70 lines · Joanne Koong
Quoted 61 lines · Andrii Nakryiko
Quoted 39 lines · Joanne Koong
Quoted 4 lines · Andrii Nakryiko
Quoted 1 line · Kumar Kartikeya Dwivedi

[...]

Quoted 25 lines
Quoted 9 lines
Quoted 8 lines
Quoted 4 lines

For bpf_dynptr_slice_rdrw we can mark buffer[] in stack as poisoned with dynptr_id == R0's PTR_TO_MEM dynptr_id. Then as soon as first spillable reg touches that poisoned stack area we can invalidate all PTR_TO_MEM's with that dynptr_id.

Okay, this makes sense to me. are you already currently working or planning to work on a fix for this Kumar, or should i take a stab at it?

Quoted 6 lines

I'm not planning to do so, so go ahead. One more thing I noticed just now is that we probably need to update regsafe to perform a check_ids comparison for dynptr_id for dynptr PTR_TO_MEMs? It was not a problem back when f8064ab90d66 ("bpf: Invalidate slices on destruction of dynptrs on stack") was added but 567da5d253cd ("bpf: improve regsafe() checks for PTR_TO_{MEM,BUF,TP_BUFFER}") added PTR_TO_MEM in the switch statement.

I can take care of this. But I really would like to avoid these special cases of extra dynptr_id, exactly for reasons like this omitted check.

What do people think about generalizing current ref_obj_id to be more like "lifetime id" (to borrow Rust terminology a bit), which would be an object (which might or might not be a tracked reference) defining the scope/lifetime of the current register (whatever it represents).

Quoted 5 lines

I haven't looked through code much, but I've been treating ref_obj_id as that already in my thinking before, and it seems to be a better approach than having a special-case of dynptr_id.

Thoughts?

Quoted 11 lines

Thanks for taking care of this (and apologies for the late reply). i think the dynptr_id field would still be needed in this case to associate a slice with a dynptr, so that when a dynptr is invalidated its slices get invalidated as well. I'm not sure we could get away with just having ref_obj_id symbolize that in the case where the underlying object is a tracked reference, because for example, it seems like a dynptr would need both a unique reference id to the object (so that if for example there are two dynptrs pointing to the same object, they will both be assignedthe same reference id so the object can't for example be freed twice) and also its own dynptr id so that its slices get invalidated if the dynptr is invalidated

Can you elaborate on specific example? Because let's say dynptr is created from some refcounted object. Then that dynptr's id field will be a unique "dynptr id", dynptr's ref_obj_id will point to that refcounted object from which we derived dynptr itself. And then when we create slices from dynptrs, then each slice gets its own unique id, but records dynptr's id as slice's ref_obj_id. So we end up with this hierarchy of id + ref_obj_id forming a tree.

Quoted 5 lines

Or am I missing something?

I want to take a look at simplifying this at some point, so I'll know more details once I start digging into code. Right now I still fail to see why we need a third ID for dynptr.

Quoted 9 lines

My mental model is that
* dynptr's ref_obj_id is set whenver there's a refcounted object (right now, only ringbuf dynptrs are refcounted), to enforce that the reference gets released by the time the program exits (dynptr ref_obj_id is set in mark_stack_slots_dynptr())
* dynptr's dynptr id is set for all dynptrs, so that if a dynptr gets overwritten/invalidated, all slices for that dynptr get invalidated (dynptr id is set in mark_dynptr_stack_regs(), called in mark_stack_slots_dynptr())

yeah, I understand that's how it works today and what the semantics of ref_obj_id is. But I'm saying that we should look at whether we can revise ref_obj_id semantics and generalize it to be "ID of the <object> whose lifetime we are bound to". This refcount part could be optional (again, will know for sure when I get to writing the code).

I'll get to this in time and will validate my own preconceptions. I don't think we should spend too much time discussing this in abstract right now.

Quoted 24 lines

* when there's a data slice, both the slice's dynptr id and ref_obj_id get set to the dynptr's dynptr id and ref_obj_id, so that the slice gets invalidated when either the dynptr is released or when the dynptr is overwritten (two separate cases) (the slice's dynptr id and ref obj id get set in check_helper_call()). The data slice also has its own unique id, but this is to handle the case where the data slice may be null.

"And then when we create slices from dynptrs, then each slice gets its own unique id, but records dynptr's id as slice's ref_obj_id. So we end up with this hierarchy of id + ref_obj_id forming a tree." I don't think I'm following the tree part. I think it records the dynptr's id as slice's id (and dynptr's ref obj id as slice's ref obj id) in check_helper_call().

"Right now I still fail to see why we need a third ID for dynptr". I think for dynptrs, there are two IDs:
state->stack[spi].spilled_ptr.ref_obj_id and state->stack[spi].spilled_ptr.id (where ref_obj_id is used to invalidate slices when dynptr is released and id is used to invalidates slices when dynptr is overwritten), and then for dynptr slices there are 3 IDs: reg->id, reg->dynptr_id, reg->ref_obj_id (where id is used for the data slice returning NULL case, and ref_obj_id / dynptr_id are used when dynptrs are invalidated).

#32 lore raw

Re: [PATCH v13 bpf-next 09/10] bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr

In reply to Alexei Starovoitov
Quoted 36 lines · Alexei Starovoitov
Quoted 35 lines · Andrii Nakryiko
Quoted 35 lines
Quoted 13 lines
Quoted 13 lines

I agree this is simpler, but I'm not sure it will work properly. Verifier won't know when the lifetime of the buffer ends, so if we disallow spills until its written over it's going to be a pain for users.

Something like:

for (...) {
        char buf[64];
        bpf_dynptr_slice_rdwr(..., buf, 64);
        ...
}
Quoted 7 lines
Quoted 3 lines

.. and then compiler decides to spill something where buf was located on stack outside the for loop. The verifier can't know when buf goes out of scope to unpoison the slots.

You're saying the "verifier doesn't know when buf ...". The same applies to the compiler. It has no visibility into what bpf_dynptr_slice_rdwr is doing.

That is true, it can't assume anything about the side effects. But I am talking about the point in the program when the buffer object no longer lives. Use of the escaped pointer to such an object any longer is UB. The compiler is well within its rights to reuse its stack storage at that point, including for spilling registers. Which is why "outside the for loop" in my earlier reply.

Quoted 4 lines

So it never spills into a declared C array
as I tried to explain in the previous reply. Spill/fill slots are always invisible to C. (unless of course you do pointer arithmetic asm style)

When the declared array's lifetime ends, it can.
https://godbolt.org/z/Ez7v4xfnv

Quoted 8 lines
Quoted 2 lines
Quoted 2 lines

The 2nd call to bar as part of unrolled loop happens with fp-8, then it calls baz, spills r0 to fp-8, and calls bar again with fp-8.

Right. If user writes such program and does explicit store of spillable pointer into a stack.
I was talking about compiler generated spill/fill and I still believe that compiler will not be reusing variable's stack memory for them.

But that example on godbolt is about the _compiler_ doing spill into a variable's stack memory, once it is dead. There is no explicit store to spill from the user happening there.

Maybe buffer in explicit program scope {} is not that common, but always_inline functions will have a similar effect, since they introduce a scope out of which poisoned buffer's storage can be reused.

Quoted 1 line

[...]

#33 lore raw

Re: [PATCH v13 bpf-next 09/10] bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr

Quoted 47 lines · Kumar Kartikeya Dwivedi
Quoted 36 lines · Alexei Starovoitov
Quoted 35 lines · Andrii Nakryiko
Quoted 35 lines
Quoted 13 lines
Quoted 13 lines

I agree this is simpler, but I'm not sure it will work properly. Verifier won't know when the lifetime of the buffer ends, so if we disallow spills until its written over it's going to be a pain for users.

Something like:

for (...) {
        char buf[64];
        bpf_dynptr_slice_rdwr(..., buf, 64);
        ...
}
Quoted 7 lines
Quoted 3 lines

.. and then compiler decides to spill something where buf was located on stack outside the for loop. The verifier can't know when buf goes out of scope to unpoison the slots.

You're saying the "verifier doesn't know when buf ...". The same applies to the compiler. It has no visibility into what bpf_dynptr_slice_rdwr is doing.

That is true, it can't assume anything about the side effects. But I am talking about the point in the program when the buffer object no longer lives. Use of the escaped pointer to such an object any longer is UB. The compiler is well within its rights to reuse its stack storage at that point, including for spilling registers. Which is why "outside the for loop" in my earlier reply.

Quoted 4 lines

So it never spills into a declared C array
as I tried to explain in the previous reply. Spill/fill slots are always invisible to C. (unless of course you do pointer arithmetic asm style)

When the declared array's lifetime ends, it can.
https://godbolt.org/z/Ez7v4xfnv

Quoted 8 lines
Quoted 2 lines
Quoted 2 lines

The 2nd call to bar as part of unrolled loop happens with fp-8, then it calls baz, spills r0 to fp-8, and calls bar again with fp-8.

Right. If user writes such program and does explicit store of spillable pointer into a stack.
I was talking about compiler generated spill/fill and I still believe that compiler will not be reusing variable's stack memory for them.

Quoted 3 lines

But that example on godbolt is about the _compiler_ doing spill into a variable's stack memory, once it is dead. There is no explicit store to spill from the user happening there.

Where do you see it?
It's
p = baz();
and subsequent &p.
That is user requested store.
Your example has other undefined behavior.
I tweaked it like this for clarity:
https://godbolt.org/z/qhcKdeWjb

#34 lore raw

PATCH v13 10/10 selftests/bpf: tests for using dynptrs to parse skb and xdp buffers

In reply to Joanne Koong

Test skb and xdp dynptr functionality in the following ways:

1) progs/test_cls_redirect_dynptr.c
* Rewrite "progs/test_cls_redirect.c" test to use dynptrs to parse skb data

* This is a great example of how dynptrs can be used to simplify a lot of the parsing logic for non-statically known values.

When measuring the user + system time between the original version vs. using dynptrs, and averaging the time for 10 runs (using "time ./test_progs -t cls_redirect"):
original version: 0.092 sec
with dynptrs: 0.078 sec

2) progs/test_xdp_dynptr.c
* Rewrite "progs/test_xdp.c" test to use dynptrs to parse xdp data

When measuring the user + system time between the original version vs. using dynptrs, and averaging the time for 10 runs (using "time ./test_progs -t xdp_attach"):
original version: 0.118 sec
with dynptrs: 0.094 sec

3) progs/test_l4lb_noinline_dynptr.c
* Rewrite "progs/test_l4lb_noinline.c" test to use dynptrs to parse skb data

When measuring the user + system time between the original version vs. using dynptrs, and averaging the time for 10 runs (using "time ./test_progs -t l4lb_all"):
original version: 0.062 sec
with dynptrs: 0.081 sec

For number of processed verifier instructions:
original version: 6268 insns
with dynptrs: 2588 insns

4) progs/test_parse_tcp_hdr_opt_dynptr.c
* Add sample code for parsing tcp hdr opt lookup using dynptrs. This logic is lifted from a real-world use case of packet parsing in katran [0], a layer 4 load balancer. The original version "progs/test_parse_tcp_hdr_opt.c" (not using dynptrs) is included here as well, for comparison.

When measuring the user + system time between the original version vs. using dynptrs, and averaging the time for 10 runs (using "time ./test_progs -t parse_tcp_hdr_opt"):
original version: 0.031 sec
with dynptrs: 0.045 sec

5) progs/dynptr_success.c
* Add test case "test_skb_readonly" for testing attempts at writes on a prog type with read-only skb ctx.
* Add "test_dynptr_skb_data" for testing that bpf_dynptr_data isn't supported for skb progs.

6) progs/dynptr_fail.c
* Add test cases "skb_invalid_data_slice{1,2,3,4}" and "xdp_invalid_data_slice{1,2}" for testing that helpers that modify the underlying packet buffer automatically invalidate the associated data slice.
* Add test cases "skb_invalid_ctx" and "xdp_invalid_ctx" for testing that prog types that do not support bpf_dynptr_from_skb/xdp don't have access to the API.
* Add test case "dynptr_slice_var_len{1,2}" for testing that variable-sized len can't be passed in to bpf_dynptr_slice
* Add test case "skb_invalid_slice_write" for testing that writes to a read-only data slice are rejected by the verifier.
* Add test case "data_slice_out_of_bounds_skb" for testing that writes to an area outside the slice are rejected.
* Add test case "invalid_slice_rdwr_rdonly" for testing that prog types that don't allow writes to packet data don't accept any calls to bpf_dynptr_slice_rdwr.

[0] https://github.com/facebookincubator/katran/blob/main/katran/lib/bpf/pckt_parsing.h

---
 tools/testing/selftests/bpf/bpf_kfuncs.h      |  38 +
 .../selftests/bpf/prog_tests/cls_redirect.c   |  25 +
 .../testing/selftests/bpf/prog_tests/dynptr.c |  74 +-
 .../selftests/bpf/prog_tests/l4lb_all.c       |   2 +
 .../bpf/prog_tests/parse_tcp_hdr_opt.c        |  93 ++
 .../selftests/bpf/prog_tests/xdp_attach.c     |  11 +-
 .../testing/selftests/bpf/progs/dynptr_fail.c | 287 ++++-
 .../selftests/bpf/progs/dynptr_success.c      |  55 +-
 .../bpf/progs/test_cls_redirect_dynptr.c      | 980 ++++++++++++++++++
 .../bpf/progs/test_l4lb_noinline_dynptr.c     | 487 +++++++++
 .../bpf/progs/test_parse_tcp_hdr_opt.c        | 119 +++
 .../bpf/progs/test_parse_tcp_hdr_opt_dynptr.c | 114 ++
 .../selftests/bpf/progs/test_xdp_dynptr.c     | 257 +++++
 .../selftests/bpf/test_tcp_hdr_options.h      |   1 +
 14 files changed, 2520 insertions(+), 23 deletions(-)
 create mode 100644 tools/testing/selftests/bpf/bpf_kfuncs.h
 create mode 100644 tools/testing/selftests/bpf/prog_tests/parse_tcp_hdr_opt.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_cls_redirect_dynptr.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_l4lb_noinline_dynptr.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_parse_tcp_hdr_opt.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_parse_tcp_hdr_opt_dynptr.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_xdp_dynptr.c
tools/testing/selftests/bpf/bpf_kfuncs.h new file +38 -0
new file mode 100644
index 000000000000..8c993ec8ceea
@@ -0,0 +1,38 @@
+#ifndef __BPF_KFUNCS__
+#define __BPF_KFUNCS__
+
+/* Description
+ *  Initializes an skb-type dynptr
+ * Returns
+ *  Error code
+ */
+extern int bpf_dynptr_from_skb(struct __sk_buff *skb, __u64 flags,
+    struct bpf_dynptr *ptr__uninit) __ksym;
+
+/* Description
+ *  Initializes an xdp-type dynptr
+ * Returns
+ *  Error code
+ */
+extern int bpf_dynptr_from_xdp(struct xdp_md *xdp, __u64 flags,
+			       struct bpf_dynptr *ptr__uninit) __ksym;
+
+/* Description
+ *  Obtain a read-only pointer to the dynptr's data
+ * Returns
+ *  Either a direct pointer to the dynptr data or a pointer to the user-provided
+ *  buffer if unable to obtain a direct pointer
+ */
+extern void *bpf_dynptr_slice(const struct bpf_dynptr *ptr, __u32 offset,
+			      void *buffer, __u32 buffer__szk) __ksym;
+
+/* Description
+ *  Obtain a read-write pointer to the dynptr's data
+ * Returns
+ *  Either a direct pointer to the dynptr data or a pointer to the user-provided
+ *  buffer if unable to obtain a direct pointer
+ */
+extern void *bpf_dynptr_slice_rdwr(const struct bpf_dynptr *ptr, __u32 offset,
+			      void *buffer, __u32 buffer__szk) __ksym;
+
+#endif
tools/testing/selftests/bpf/prog_tests/cls_redirect.c +25 -0
index 224f016b0a53..2a55f717fc07 100644
@@ -13,6 +13,7 @@
 
 #include "progs/test_cls_redirect.h"
 #include "test_cls_redirect.skel.h"
+#include "test_cls_redirect_dynptr.skel.h"
 #include "test_cls_redirect_subprogs.skel.h"
 
 #define ENCAP_IP INADDR_LOOPBACK
@@ -446,6 +447,28 @@ static void test_cls_redirect_common(struct bpf_program *prog)
 	close_fds((int *)conns, sizeof(conns) / sizeof(conns[0][0]));
 }
 
+static void test_cls_redirect_dynptr(void)
+{
+	struct test_cls_redirect_dynptr *skel;
+	int err;
+
+	skel = test_cls_redirect_dynptr__open();
+	if (!ASSERT_OK_PTR(skel, "skel_open"))
+		return;
+
+	skel->rodata->ENCAPSULATION_IP = htonl(ENCAP_IP);
+	skel->rodata->ENCAPSULATION_PORT = htons(ENCAP_PORT);
+
+	err = test_cls_redirect_dynptr__load(skel);
+	if (!ASSERT_OK(err, "skel_load"))
+		goto cleanup;
+
+	test_cls_redirect_common(skel->progs.cls_redirect);
+
+cleanup:
+	test_cls_redirect_dynptr__destroy(skel);
+}
+
 static void test_cls_redirect_inlined(void)
 {
 	struct test_cls_redirect *skel;
@@ -496,4 +519,6 @@ void test_cls_redirect(void)
 		test_cls_redirect_inlined();
 	if (test__start_subtest("cls_redirect_subprogs"))
 		test_cls_redirect_subprogs();
+	if (test__start_subtest("cls_redirect_dynptr"))
+		test_cls_redirect_dynptr();
 }
tools/testing/selftests/bpf/prog_tests/dynptr.c +58 -16

111 lines not on this page · raw message

tools/testing/selftests/bpf/prog_tests/l4lb_all.c +2 -0
index 9c1a18573ffd..1eab286b14fe 100644
@@ -93,4 +93,6 @@ void test_l4lb_all(void)
 		test_l4lb("test_l4lb.bpf.o");
 	if (test__start_subtest("l4lb_noinline"))
 		test_l4lb("test_l4lb_noinline.bpf.o");
+	if (test__start_subtest("l4lb_noinline_dynptr"))
+		test_l4lb("test_l4lb_noinline_dynptr.bpf.o");
 }
tools/testing/selftests/bpf/prog_tests/parse_tcp_hdr_opt.c new file +93 -0

93 lines not on this page · raw message

tools/testing/selftests/bpf/prog_tests/xdp_attach.c +9 -2
index d4cd9f873c14..fa3cac5488f5 100644
@@ -4,11 +4,10 @@
 #define IFINDEX_LO 1
 #define XDP_FLAGS_REPLACE		(1U << 4)
 
-void serial_test_xdp_attach(void)
+static void test_xdp_attach(const char *file)
 {
 	__u32 duration = 0, id1, id2, id0 = 0, len;
 	struct bpf_object *obj1, *obj2, *obj3;
-	const char *file = "./test_xdp.bpf.o";
 	struct bpf_prog_info info = {};
 	int err, fd1, fd2, fd3;
 	LIBBPF_OPTS(bpf_xdp_attach_opts, opts);
@@ -85,3 +84,11 @@ void serial_test_xdp_attach(void)
 out_1:
 	bpf_object__close(obj1);
 }
+
+void serial_test_xdp_attach(void)
+{
+	if (test__start_subtest("xdp_attach"))
+		test_xdp_attach("./test_xdp.bpf.o");
+	if (test__start_subtest("xdp_attach_dynptr"))
+		test_xdp_attach("./test_xdp_dynptr.bpf.o");
+}
tools/testing/selftests/bpf/progs/dynptr_fail.c +286 -1

321 lines not on this page · raw message

tools/testing/selftests/bpf/progs/dynptr_success.c +51 -4

82 lines not on this page · raw message

tools/testing/selftests/bpf/progs/test_cls_redirect_dynptr.c new file +980 -0

980 lines not on this page · raw message

tools/testing/selftests/bpf/progs/test_l4lb_noinline_dynptr.c new file +487 -0

487 lines not on this page · raw message

tools/testing/selftests/bpf/progs/test_parse_tcp_hdr_opt.c new file +119 -0

119 lines not on this page · raw message

tools/testing/selftests/bpf/progs/test_parse_tcp_hdr_opt_dynptr.c new file +114 -0

114 lines not on this page · raw message

tools/testing/selftests/bpf/progs/test_xdp_dynptr.c new file +257 -0

257 lines not on this page · raw message

tools/testing/selftests/bpf/test_tcp_hdr_options.h +1 -0
index 6118e3ab61fc..56c9f8a3ad3d 100644
@@ -50,6 +50,7 @@ struct linum_err {
 
 #define TCPOPT_EOL		0
 #define TCPOPT_NOP		1
+#define TCPOPT_MSS		2
 #define TCPOPT_WINDOW		3
 #define TCPOPT_EXP		254
 
Signature · 1 line
2.34.1
#35 lore raw

Re: [PATCH v13 bpf-next 10/10] selftests/bpf: tests for using dynptrs to parse skb and xdp buffers

Quoted 6 lines · Joanne Koong

5) progs/dynptr_success.c
* Add test case "test_skb_readonly" for testing attempts at writes on a prog type with read-only skb ctx.
* Add "test_dynptr_skb_data" for testing that bpf_dynptr_data isn't supported for skb progs.

I added
+dynptr/test_dynptr_skb_data
+dynptr/test_skb_readonly
to DENYLIST.s390x and applied.

Thank you so much for all the hard work to make it happen. Great milestone!

#36 lore raw

Re: [PATCH v13 bpf-next 10/10] selftests/bpf: tests for using dynptrs to parse skb and xdp buffers

Quoted 14 lines · Alexei Starovoitov
Quoted 6 lines · Joanne Koong

5) progs/dynptr_success.c
* Add test case "test_skb_readonly" for testing attempts at writes on a prog type with read-only skb ctx.
* Add "test_dynptr_skb_data" for testing that bpf_dynptr_data isn't supported for skb progs.

I added

(quoted diff) +2 -0
+dynptr/test_dynptr_skb_data
+dynptr/test_skb_readonly

to DENYLIST.s390x and applied.

Quoted 2 lines

Thank you so much for all the hard work to make it happen. Great milestone!

Yep, a lot of iterators work is made much easier thanks to the foundations laid by your (Joanne's) dynptr work. Thank you!

#37 lore raw

Re: [PATCH v13 bpf-next 10/10] selftests/bpf: tests for using dynptrs to parse skb and xdp buffers

In reply to Alexei Starovoitov
Quoted 12 lines · Alexei Starovoitov
Quoted 6 lines · Joanne Koong

5) progs/dynptr_success.c
* Add test case "test_skb_readonly" for testing attempts at writes on a prog type with read-only skb ctx.
* Add "test_dynptr_skb_data" for testing that bpf_dynptr_data isn't supported for skb progs.

I added

(quoted diff) +2 -0
+dynptr/test_dynptr_skb_data
+dynptr/test_skb_readonly
Quoted 1 line

to DENYLIST.s390x and applied.

Thanks, I'm still not sure why s390x cannot load these programs. It is being loaded in the same way as other tests like test_parse_tcp_hdr_opt() are loading programs. I will keep looking some more into this

Quoted 3 lines

Thank you so much for all the hard work to make it happen. Great milestone!

Thank you to you, Andrii, Martin, Kumar, Jakub, and Toke (and kernel test robot :P) for all your reviews and feedback on this patchset! It was all extremely helpful

#38 lore raw

Re: [PATCH v13 bpf-next 10/10] selftests/bpf: tests for using dynptrs to parse skb and xdp buffers

Quoted 11 lines · Joanne Koong
Quoted 9 lines · Alexei Starovoitov
Quoted 6 lines · Joanne Koong

5) progs/dynptr_success.c
* Add test case "test_skb_readonly" for testing attempts at writes on a prog type with read-only skb ctx.
* Add "test_dynptr_skb_data" for testing that bpf_dynptr_data isn't supported for skb progs.

Quoted 9 lines
Quoted 4 lines

I added

(quoted diff) +2 -0
+dynptr/test_dynptr_skb_data
+dynptr/test_skb_readonly

to DENYLIST.s390x and applied.

Thanks, I'm still not sure why s390x cannot load these programs. It is being loaded in the same way as other tests like test_parse_tcp_hdr_opt() are loading programs. I will keep looking some more into this

Hi,

I believe the culprit is:

    insn->imm = BPF_CALL_IMM(bpf_dynptr_from_skb_rdonly);

s390x needs to know the kfunc model in order to emit the call (like i386), but after this assignment it's no longer possible to look it up in kfunc_tab by insn->imm. x86_64 does not need this, because its ABI is exactly the same as BPF ABI.

The simplest solution seems to be adding an artificial kfunc_desc like this:

    {
        .func_model = desc->func_model,  /* model must be compatible */
	.func_id = 0,                    /* unused at this point */
        .imm = insn->imm,                /* new target */
        .offset = 0,                     /* unused at this point */
    }

here and also after this assignment:

    insn->imm = BPF_CALL_IMM(xdp_kfunc);

What do you think?

[...]

Best regards,
Ilya

#39 lore raw

Re: [PATCH v13 bpf-next 10/10] selftests/bpf: tests for using dynptrs to parse skb and xdp buffers

Quoted 44 lines · Ilya Leoshkevich
Quoted 11 lines · Joanne Koong
Quoted 9 lines · Alexei Starovoitov
Quoted 6 lines · Joanne Koong

5) progs/dynptr_success.c
* Add test case "test_skb_readonly" for testing attempts at writes on a prog type with read-only skb ctx.
* Add "test_dynptr_skb_data" for testing that bpf_dynptr_data isn't supported for skb progs.

Quoted 9 lines
Quoted 4 lines

I added

(quoted diff) +2 -0
+dynptr/test_dynptr_skb_data
+dynptr/test_skb_readonly

to DENYLIST.s390x and applied.

Thanks, I'm still not sure why s390x cannot load these programs. It is being loaded in the same way as other tests like test_parse_tcp_hdr_opt() are loading programs. I will keep looking some more into this

Hi,

I believe the culprit is:

    insn->imm = BPF_CALL_IMM(bpf_dynptr_from_skb_rdonly);

s390x needs to know the kfunc model in order to emit the call (like i386), but after this assignment it's no longer possible to look it up in kfunc_tab by insn->imm. x86_64 does not need this, because its ABI is exactly the same as BPF ABI.

The simplest solution seems to be adding an artificial kfunc_desc like this:

    {
        .func_model = desc->func_model,  /* model must be compatible */
        .func_id = 0,                    /* unused at this point */
        .imm = insn->imm,                /* new target */
        .offset = 0,                     /* unused at this point */
    }
Quoted 5 lines

here and also after this assignment:

    insn->imm = BPF_CALL_IMM(xdp_kfunc);

What do you think?

Ohh interesting! This makes sense to me. In particular, you're referring to the bpf_jit_find_kfunc_model() call in bpf_jit_insn() (in arch/s390/net/bpf_jit_comp.c) as the one that fails out whenever insn->imm gets set, correct?

I like your proposed solution, I agree that this looks like the simplest, though maybe we should replace the existing kfunc_desc instead of adding it so we don't have to deal with the edge case of reaching MAX_KFUNC_DESCS? To get the func model of the new insn->imm, it seems pretty straightforward, it looks like we can just use btf_distill_func_proto(). or call add_kfunc_call() directly, which would do everything needed, but adds an additional unnecessary sort and more overhead for replacing (eg we'd need to first swap the old kfunc_desc with the last tab->descs[tab->nr_descs] entry and then delete the old kfunc_desc before adding the new one). What are your thoughts?

Quoted 5 lines

[...]

Best regards,
Ilya

#40 lore raw

Re: [PATCH v13 bpf-next 10/10] selftests/bpf: tests for using dynptrs to parse skb and xdp buffers

Quoted 57 lines · Joanne Koong
Quoted 55 lines · Ilya Leoshkevich
Quoted 14 lines · Joanne Koong
Quoted 12 lines · Alexei Starovoitov
Quoted 8 lines · Joanne Koong

5) progs/dynptr_success.c
   * Add test case "test_skb_readonly" for testing attempts at writes
     on a prog type with read-only skb ctx.
   * Add "test_dynptr_skb_data" for testing that bpf_dynptr_data isn't
     supported for skb progs.

Quoted 11 lines
Quoted 4 lines

I added

(quoted diff) +2 -0
+dynptr/test_dynptr_skb_data
+dynptr/test_skb_readonly

to DENYLIST.s390x and applied.

Thanks, I'm still not sure why s390x cannot load these programs. It is
being loaded in the same way as other tests like test_parse_tcp_hdr_opt() are loading programs. I will keep looking
some more into this

Hi,

I believe the culprit is:

    insn->imm = BPF_CALL_IMM(bpf_dynptr_from_skb_rdonly);

s390x needs to know the kfunc model in order to emit the call (like i386), but after this assignment it's no longer possible to look it up in kfunc_tab by insn->imm. x86_64 does not need this, because its
ABI is exactly the same as BPF ABI.

The simplest solution seems to be adding an artificial kfunc_desc like this:

    {
        .func_model = desc->func_model,  /* model must be compatible */
        .func_id = 0,                    /* unused at this point */ .imm = insn->imm,                /* new target */ .offset = 0,                     /* unused at this point */ }

here and also after this assignment:

    insn->imm = BPF_CALL_IMM(xdp_kfunc);

Quoted 7 lines
Quoted 1 line

What do you think?

Ohh interesting! This makes sense to me. In particular, you're referring to the bpf_jit_find_kfunc_model() call in bpf_jit_insn() (in
arch/s390/net/bpf_jit_comp.c) as the one that fails out whenever insn->imm gets set, correct?

Precisely.

Quoted 4 lines

I like your proposed solution, I agree that this looks like the simplest, though maybe we should replace the existing kfunc_desc instead of adding it so we don't have to deal with the edge case of reaching MAX_KFUNC_DESCS? To get the func model of the new insn->imm,

I wonder whether replacement is safe? This would depend on the following functions returning the same value for the same inputs:

- may_access_direct_pkt_data() - this looks ok;
- bpf_dev_bound_resolve_kfunc() - I'm not so sure, any insights?

If it's not, then MAX_KFUNC_DESCS indeed becomes a concern.

Quoted 7 lines

it seems pretty straightforward, it looks like we can just use btf_distill_func_proto(). or call add_kfunc_call() directly, which would do everything needed, but adds an additional unnecessary sort and more overhead for replacing (eg we'd need to first swap the old kfunc_desc with the last tab->descs[tab->nr_descs] entry and then delete the old kfunc_desc before adding the new one). What are your thoughts?

Is there a way to find BTF by function pointer?
IIUC bpf_dev_bound_resolve_kfunc() can return many different things, and btf_distill_func_proto() and add_kfunc_call() need BTF. A straightforward way that immediately comes to mind is to do kallsyms lookup and then resolve by name, but this sounds clumsy.

I've been looking into this in context of fixing (kfunc __bpf_call_base) not fitting into 32 bits on s390x. A solution that would solve both problems that I'm currently thinking about is to associate

struct {
    struct btf_func_model *m;
    unsigned long addr;
} kfunc_callee;

with every insn - during verification it could live in bpf_insn_aux_data, during jiting in bpf_prog, and afterwards it can be freed. Any thoughts about this?

#41 lore raw

Re: [PATCH v13 bpf-next 10/10] selftests/bpf: tests for using dynptrs to parse skb and xdp buffers

Quoted 74 lines · Ilya Leoshkevich
Quoted 57 lines · Joanne Koong
Quoted 55 lines · Ilya Leoshkevich
Quoted 14 lines · Joanne Koong
Quoted 12 lines · Alexei Starovoitov
Quoted 8 lines · Joanne Koong

5) progs/dynptr_success.c
* Add test case "test_skb_readonly" for testing attempts
at writes
on a prog type with read-only skb ctx.
* Add "test_dynptr_skb_data" for testing that
bpf_dynptr_data isn't
supported for skb progs.

Quoted 11 lines
Quoted 4 lines

I added

(quoted diff) +2 -0
+dynptr/test_dynptr_skb_data
+dynptr/test_skb_readonly

to DENYLIST.s390x and applied.

Thanks, I'm still not sure why s390x cannot load these programs. It is
being loaded in the same way as other tests like test_parse_tcp_hdr_opt() are loading programs. I will keep looking
some more into this

Hi,

I believe the culprit is:

    insn->imm = BPF_CALL_IMM(bpf_dynptr_from_skb_rdonly);

s390x needs to know the kfunc model in order to emit the call (like i386), but after this assignment it's no longer possible to look it up in kfunc_tab by insn->imm. x86_64 does not need this, because its
ABI is exactly the same as BPF ABI.

The simplest solution seems to be adding an artificial kfunc_desc like this:

    {
        .func_model = desc->func_model,  /* model must be
compatible */
        .func_id = 0,                    /* unused at this point */
        .imm = insn->imm,                /* new target */
        .offset = 0,                     /* unused at this point */
    }

here and also after this assignment:

    insn->imm = BPF_CALL_IMM(xdp_kfunc);
Quoted 7 lines
Quoted 1 line

What do you think?

Ohh interesting! This makes sense to me. In particular, you're referring to the bpf_jit_find_kfunc_model() call in bpf_jit_insn() (in
arch/s390/net/bpf_jit_comp.c) as the one that fails out whenever insn->imm gets set, correct?

Precisely.

Quoted 4 lines

I like your proposed solution, I agree that this looks like the simplest, though maybe we should replace the existing kfunc_desc instead of adding it so we don't have to deal with the edge case of reaching MAX_KFUNC_DESCS? To get the func model of the new insn->imm,

Quoted 5 lines

I wonder whether replacement is safe? This would depend on the following functions returning the same value for the same inputs:

- may_access_direct_pkt_data() - this looks ok;
- bpf_dev_bound_resolve_kfunc() - I'm not so sure, any insights?

For the bpf_dev_bound_resolve_kfunc() case (in fixup_kfunc_call()), I think directly replacing the kfunc_desc here is okay because bpf_dev_bound_resolve_kfunc() is findingthe target device-specific version of the kfunc (if it exists) to replace the generic version of the kfunc with, and we're using that target device-specific version of the kfunc as the new updated insn->imm to call

Quoted 11 lines

If it's not, then MAX_KFUNC_DESCS indeed becomes a concern.

Quoted 7 lines

it seems pretty straightforward, it looks like we can just use btf_distill_func_proto(). or call add_kfunc_call() directly, which would do everything needed, but adds an additional unnecessary sort and more overhead for replacing (eg we'd need to first swap the old kfunc_desc with the last tab->descs[tab->nr_descs] entry and then delete the old kfunc_desc before adding the new one). What are your thoughts?

Quoted 6 lines

Is there a way to find BTF by function pointer?
IIUC bpf_dev_bound_resolve_kfunc() can return many different things, and btf_distill_func_proto() and add_kfunc_call() need BTF. A straightforward way that immediately comes to mind is to do kallsyms lookup and then resolve by name, but this sounds clumsy.

I'm not sure whether there's a way to find the function's BTF by its pointer, but I think maybe we can use the vmlinux btf (which we can get through the bpf_get_btf_vmlinux() api) to get the func proto?

Quoted 4 lines

I've been looking into this in context of fixing (kfunc __bpf_call_base) not fitting into 32 bits on s390x. A solution that

Sorry, I'm not fully understanding - can you elaborate a little on what the issue is? why doesn't the __bpf_call_base address fit on s390x? my understanding is that s390x is a 64-bit architecture?

Quoted 11 lines

would solve both problems that I'm currently thinking about is to associate

struct {
    struct btf_func_model *m;
    unsigned long addr;
} kfunc_callee;

with every insn - during verification it could live in bpf_insn_aux_data, during jiting in bpf_prog, and afterwards it can be freed. Any thoughts about this?

#42 lore raw

Re: [PATCH v13 bpf-next 10/10] selftests/bpf: tests for using dynptrs to parse skb and xdp buffers

Quoted 94 lines · Joanne Koong
Quoted 84 lines · Ilya Leoshkevich
Quoted 66 lines · Joanne Koong
Quoted 63 lines · Ilya Leoshkevich
Quoted 15 lines · Joanne Koong
Quoted 13 lines · Alexei Starovoitov
Quoted 9 lines · Joanne Koong

5) progs/dynptr_success.c
   * Add test case "test_skb_readonly" for testing attempts
at writes
     on a prog type with read-only skb ctx.
   * Add "test_dynptr_skb_data" for testing that bpf_dynptr_data isn't
     supported for skb progs.

Quoted 12 lines
Quoted 4 lines

I added

(quoted diff) +2 -0
+dynptr/test_dynptr_skb_data
+dynptr/test_skb_readonly

to DENYLIST.s390x and applied.

Thanks, I'm still not sure why s390x cannot load these programs.
It is
being loaded in the same way as other tests like test_parse_tcp_hdr_opt() are loading programs. I will keep looking
some more into this

Hi,

I believe the culprit is:

    insn->imm = BPF_CALL_IMM(bpf_dynptr_from_skb_rdonly);

s390x needs to know the kfunc model in order to emit the call (like
i386), but after this assignment it's no longer possible to look it
up in kfunc_tab by insn->imm. x86_64 does not need this, because
its
ABI is exactly the same as BPF ABI.

The simplest solution seems to be adding an artificial kfunc_desc
like this:

    {
        .func_model = desc->func_model,  /* model must be compatible */
        .func_id = 0,                    /* unused at this point */
        .imm = insn->imm,                /* new target */ .offset = 0,                     /* unused at this point */
    }

here and also after this assignment:

    insn->imm = BPF_CALL_IMM(xdp_kfunc);

Quoted 8 lines
Quoted 1 line

What do you think?

Ohh interesting! This makes sense to me. In particular, you're referring to the bpf_jit_find_kfunc_model() call in bpf_jit_insn()
(in
arch/s390/net/bpf_jit_comp.c) as the one that fails out whenever insn->imm gets set, correct?

Precisely.

Quoted 5 lines

I like your proposed solution, I agree that this looks like the simplest, though maybe we should replace the existing kfunc_desc instead of adding it so we don't have to deal with the edge case of
reaching MAX_KFUNC_DESCS? To get the func model of the new insn-

Quoted 7 lines
Quoted 1 line
Quoted 1 line

imm,

I wonder whether replacement is safe? This would depend on the following functions returning the same value for the same inputs:

- may_access_direct_pkt_data() - this looks ok;
- bpf_dev_bound_resolve_kfunc() - I'm not so sure, any insights?

Quoted 7 lines

For the bpf_dev_bound_resolve_kfunc() case (in fixup_kfunc_call()), I think directly replacing the kfunc_desc here is okay because bpf_dev_bound_resolve_kfunc() is findingthe target device-specific version of the kfunc (if it exists) to replace the generic version of the kfunc with, and we're using that target device-specific version of
the kfunc as the new updated insn->imm to call

I'm worried that its return value is going to change while we are doing the rewriting. It looks as if __bpf_offload_dev_netdev_unregister() can cause this. So if we have two instructions that use the same generic kfunc, they may end up pointing to two different device-specific kfuncs, and the kfunc_tab will contain only one of the two.

This sounds dangerous, but maybe I don't see some safeguard that already prevents or mitigates the effects of this?

Stanislav, could you as the bpf_dev_bound_resolve_kfunc() author give your opinion please? I've seen your comment:

+ /* We don't hold bpf_devs_lock while resolving several

+        * kfuncs and can race with the unregister_netdevice().
+        * We rely on bpf_dev_bound_match() check at attach
+        * to render this program unusable.
+        */

and I'm wondering whether you meant bpf_prog_dev_bound_match(), and whether it protects against the ABA problem, i.e., if __bpf_offload_dev_netdev_unregister() is called twice, and we get aux->offload and aux->offload->netdev at the same addresses?

Quoted 23 lines
Quoted 14 lines

If it's not, then MAX_KFUNC_DESCS indeed becomes a concern.

Quoted 11 lines

it seems pretty straightforward, it looks like we can just use btf_distill_func_proto(). or call add_kfunc_call() directly, which
would do everything needed, but adds an additional unnecessary sort
and more overhead for replacing (eg we'd need to first swap the old
kfunc_desc with the last tab->descs[tab->nr_descs] entry and then delete the old kfunc_desc before adding the new one). What are your
thoughts?

Quoted 8 lines

Is there a way to find BTF by function pointer? IIUC bpf_dev_bound_resolve_kfunc() can return many different things,
and btf_distill_func_proto() and add_kfunc_call() need BTF. A straightforward way that immediately comes to mind is to do kallsyms
lookup and then resolve by name, but this sounds clumsy.

Quoted 3 lines

I'm not sure whether there's a way to find the function's BTF by its pointer, but I think maybe we can use the vmlinux btf (which we can get through the bpf_get_btf_vmlinux() api) to get the func proto?

The device-specific function may come from a kernel module (e.g., veth). But on second thought we don't need this at all; we should really just take func_model of the generic function, that we already have. If it is not the same as the model of the device-specific function, it must be a bug.

Quoted 6 lines
Quoted 2 lines

I've been looking into this in context of fixing (kfunc __bpf_call_base) not fitting into 32 bits on s390x. A solution that

Sorry, I'm not fully understanding - can you elaborate a little on what the issue is? why doesn't the __bpf_call_base address fit on s390x? my understanding is that s390x is a 64-bit architecture?

On s390x modules and kernel are far away from each other, so BPF_CALL_IMM() may return ~40 significant bits. This makes the insn->imm rewriting trick unusable, because insn->imm is just 32 bits and cannot be extended. There is even a safeguard against this in add_kfunc_call() ("address of kernel function %s is out of range" check).

I had a patch that kept BTF ID in insn->imm, but it was decided that since it required adjusting several JITs, we should not be doing it.

When the s390x JIT sees a kfunc call, it needs to find the respective kfunc's address and model. Normally this is done using kfunc_tab lookup. kfunc_tab is indexed by insn->imm values, which we cannot use for reasons outlined above. Hence the idea below: create another (unfortunately much less memory-efficient) kfunc_tab indexed by insn numbers.

Conveniently, this would also solve the problem that we are seeing here.

Quoted 11 lines
Quoted 11 lines

would solve both problems that I'm currently thinking about is to associate

struct {
    struct btf_func_model *m;
    unsigned long addr;
} kfunc_callee;

with every insn - during verification it could live in bpf_insn_aux_data, during jiting in bpf_prog, and afterwards it can be freed. Any thoughts about this?

#43 lore raw

Re: [PATCH v13 bpf-next 10/10] selftests/bpf: tests for using dynptrs to parse skb and xdp buffers

Quoted 123 lines · Ilya Leoshkevich
Quoted 94 lines · Joanne Koong
Quoted 84 lines · Ilya Leoshkevich
Quoted 66 lines · Joanne Koong
Quoted 63 lines · Ilya Leoshkevich
Quoted 15 lines · Joanne Koong
Quoted 13 lines · Alexei Starovoitov
Quoted 9 lines · Joanne Koong

5) progs/dynptr_success.c
* Add test case "test_skb_readonly" for testing
attempts
at writes
on a prog type with read-only skb ctx.
* Add "test_dynptr_skb_data" for testing that
bpf_dynptr_data isn't
supported for skb progs.

Quoted 12 lines
Quoted 4 lines

I added

(quoted diff) +2 -0
+dynptr/test_dynptr_skb_data
+dynptr/test_skb_readonly

to DENYLIST.s390x and applied.

Thanks, I'm still not sure why s390x cannot load these programs.
It is
being loaded in the same way as other tests like test_parse_tcp_hdr_opt() are loading programs. I will keep looking
some more into this

Hi,

I believe the culprit is:

    insn->imm = BPF_CALL_IMM(bpf_dynptr_from_skb_rdonly);

s390x needs to know the kfunc model in order to emit the call (like
i386), but after this assignment it's no longer possible to look it
up in kfunc_tab by insn->imm. x86_64 does not need this, because
its
ABI is exactly the same as BPF ABI.

The simplest solution seems to be adding an artificial kfunc_desc
like this:

    {
        .func_model = desc->func_model,  /* model must be

compatible */
.func_id = 0, /* unused at this
point */
.imm = insn->imm, /* new target */
.offset = 0, /* unused at this
point */

    }

here and also after this assignment:

    insn->imm = BPF_CALL_IMM(xdp_kfunc);
Quoted 8 lines
Quoted 1 line

What do you think?

Ohh interesting! This makes sense to me. In particular, you're referring to the bpf_jit_find_kfunc_model() call in bpf_jit_insn()
(in
arch/s390/net/bpf_jit_comp.c) as the one that fails out whenever insn->imm gets set, correct?

Precisely.

Quoted 5 lines

I like your proposed solution, I agree that this looks like the simplest, though maybe we should replace the existing kfunc_desc instead of adding it so we don't have to deal with the edge case of
reaching MAX_KFUNC_DESCS? To get the func model of the new insn-

Quoted 7 lines
Quoted 1 line
Quoted 1 line

imm,

I wonder whether replacement is safe? This would depend on the following functions returning the same value for the same inputs:

- may_access_direct_pkt_data() - this looks ok;
- bpf_dev_bound_resolve_kfunc() - I'm not so sure, any insights?

Quoted 7 lines

For the bpf_dev_bound_resolve_kfunc() case (in fixup_kfunc_call()), I think directly replacing the kfunc_desc here is okay because bpf_dev_bound_resolve_kfunc() is findingthe target device-specific version of the kfunc (if it exists) to replace the generic version of the kfunc with, and we're using that target device-specific version of
the kfunc as the new updated insn->imm to call

I'm worried that its return value is going to change while we are doing the rewriting. It looks as if __bpf_offload_dev_netdev_unregister() can cause this. So if we have two instructions that use the same generic kfunc, they may end up pointing to two different device-specific kfuncs, and the kfunc_tab will contain only one of the two.

This sounds dangerous, but maybe I don't see some safeguard that already prevents or mitigates the effects of this?

Stanislav, could you as the bpf_dev_bound_resolve_kfunc() author give your opinion please? I've seen your comment:

(quoted diff) +5 -0
+       /* We don't hold bpf_devs_lock while resolving several
+        * kfuncs and can race with the unregister_netdevice().
+        * We rely on bpf_dev_bound_match() check at attach
+        * to render this program unusable.
+        */
Quoted 4 lines

and I'm wondering whether you meant bpf_prog_dev_bound_match(), and whether it protects against the ABA problem, i.e., if __bpf_offload_dev_netdev_unregister() is called twice, and we get aux->offload and aux->offload->netdev at the same addresses?

Yes, the comment is talking about bpf_prog_dev_bound_match during attach time. When __bpf_offload_dev_netdev_unregister races with our prog load (which is being loaded for some specific netdev), bpf_prog_dev_bound_match check during attach time should render this program un-attach-able / unusable (since the original netdev, for which this prog has been loaded, is gone).

But going back to s390 issue: so basically, rewriting imm for kfuncs early in the verifier prevents jit from being able to call bpf_jit_find_kfunc_model? Did I get that correctly?
Adding kfunc_desc seems like a nice hack, but I liked your previous series which pushed that imm resolution down to the jits better :-( For the xdp_kfunc case though, if you were to go the extra kfunc_desc route, adding the one that it's been resolved to is fine. If we race with __bpf_offload_dev_netdev_unregister, the prog will be unusable anyway (due to that dev_bound_match check); so if it fails ealer somewhere in the jit - doesn't seem like a big deal to me. Hope that helps.

Quoted 72 lines
Quoted 23 lines
Quoted 14 lines

If it's not, then MAX_KFUNC_DESCS indeed becomes a concern.

Quoted 11 lines

it seems pretty straightforward, it looks like we can just use btf_distill_func_proto(). or call add_kfunc_call() directly, which
would do everything needed, but adds an additional unnecessary sort
and more overhead for replacing (eg we'd need to first swap the old
kfunc_desc with the last tab->descs[tab->nr_descs] entry and then delete the old kfunc_desc before adding the new one). What are your
thoughts?

Quoted 8 lines

Is there a way to find BTF by function pointer? IIUC bpf_dev_bound_resolve_kfunc() can return many different things,
and btf_distill_func_proto() and add_kfunc_call() need BTF. A straightforward way that immediately comes to mind is to do kallsyms
lookup and then resolve by name, but this sounds clumsy.

Quoted 3 lines

I'm not sure whether there's a way to find the function's BTF by its pointer, but I think maybe we can use the vmlinux btf (which we can get through the bpf_get_btf_vmlinux() api) to get the func proto?

The device-specific function may come from a kernel module (e.g., veth). But on second thought we don't need this at all; we should really just take func_model of the generic function, that we already have. If it is not the same as the model of the device-specific function, it must be a bug.

Quoted 6 lines
Quoted 2 lines

I've been looking into this in context of fixing (kfunc __bpf_call_base) not fitting into 32 bits on s390x. A solution that

Sorry, I'm not fully understanding - can you elaborate a little on what the issue is? why doesn't the __bpf_call_base address fit on s390x? my understanding is that s390x is a 64-bit architecture?

On s390x modules and kernel are far away from each other, so BPF_CALL_IMM() may return ~40 significant bits. This makes the insn->imm rewriting trick unusable, because insn->imm is just 32 bits and cannot be extended. There is even a safeguard against this in add_kfunc_call() ("address of kernel function %s is out of range" check).

I had a patch that kept BTF ID in insn->imm, but it was decided that since it required adjusting several JITs, we should not be doing it.

When the s390x JIT sees a kfunc call, it needs to find the respective kfunc's address and model. Normally this is done using kfunc_tab lookup. kfunc_tab is indexed by insn->imm values, which we cannot use for reasons outlined above. Hence the idea below: create another (unfortunately much less memory-efficient) kfunc_tab indexed by insn numbers.

Conveniently, this would also solve the problem that we are seeing here.

Quoted 11 lines
Quoted 11 lines

would solve both problems that I'm currently thinking about is to associate

struct {
    struct btf_func_model *m;
    unsigned long addr;
} kfunc_callee;

with every insn - during verification it could live in bpf_insn_aux_data, during jiting in bpf_prog, and afterwards it can be freed. Any thoughts about this?

#44 lore raw

Re: [PATCH v13 bpf-next 10/10] selftests/bpf: tests for using dynptrs to parse skb and xdp buffers

Quoted 14 lines · Stanislav Fomichev
Quoted 6 lines

and I'm wondering whether you meant bpf_prog_dev_bound_match(), and whether it protects against the ABA problem, i.e., if __bpf_offload_dev_netdev_unregister() is called twice, and we get aux->offload and aux->offload->netdev at the same addresses?

Yes, the comment is talking about bpf_prog_dev_bound_match during attach time. When __bpf_offload_dev_netdev_unregister races with our prog load (which is being loaded for some specific netdev), bpf_prog_dev_bound_match check during attach time should render this program un-attach-able / unusable (since the original netdev, for which this prog has been loaded, is gone).

Quoted 5 lines

But going back to s390 issue: so basically, rewriting imm for kfuncs early in the verifier prevents jit from being able to call bpf_jit_find_kfunc_model? Did I get that correctly? Adding kfunc_desc seems like a nice hack, but I liked your previous series which pushed that imm resolution down to the jits better :-(

Me too. All I was saying is to do without hacking through all JITs. More or less what v2 version was doing instead all-arch change in v3.

#45 lore raw
In reply to Joanne Koong
This series was applied to bpf/bpf-next.git (master) by Alexei Starovoitov <[email protected]>:

Hello:

This series was applied to bpf/bpf-next.git (master) by Alexei Starovoitov <[email protected]>:

Quoted 10 lines · On Wed, 1 Mar 2023 07:49:43 -0800 you wrote:

This patchset is the 2nd in the dynptr series. The 1st can be found here [0].

This patchset adds skb and xdp type dynptrs, which have two main benefits for packet parsing:
* allowing operations on sizes that are not statically known at compile-time (eg variable-sized accesses).
* more ergonomic and less brittle iteration through data (eg does not need manual if checking for being within bounds of data_end)

[...]

Here is the summary with links:
- [v13,bpf-next,01/10] bpf: Support "sk_buff" and "xdp_buff" as valid kfunc arg types

    https://git.kernel.org/bpf/bpf-next/c/2f4643934670
  - [v13,bpf-next,02/10] bpf: Refactor process_dynptr_func
    https://git.kernel.org/bpf/bpf-next/c/7e0dac2807e6
  - [v13,bpf-next,03/10] bpf: Allow initializing dynptrs in kfuncs
    https://git.kernel.org/bpf/bpf-next/c/1d18feb2c915
  - [v13,bpf-next,04/10] bpf: Define no-ops for externally called bpf dynptr functions
    https://git.kernel.org/bpf/bpf-next/c/8357b366cbb0
  - [v13,bpf-next,05/10] bpf: Refactor verifier dynptr into get_dynptr_arg_reg
    https://git.kernel.org/bpf/bpf-next/c/485ec51ef976
  - [v13,bpf-next,06/10] bpf: Add __uninit kfunc annotation
    https://git.kernel.org/bpf/bpf-next/c/d96d937d7c5c
  - [v13,bpf-next,07/10] bpf: Add skb dynptrs
    https://git.kernel.org/bpf/bpf-next/c/b5964b968ac6
  - [v13,bpf-next,08/10] bpf: Add xdp dynptrs
    https://git.kernel.org/bpf/bpf-next/c/05421aecd4ed
  - [v13,bpf-next,09/10] bpf: Add bpf_dynptr_slice and bpf_dynptr_slice_rdwr
    https://git.kernel.org/bpf/bpf-next/c/66e3a13e7c2c
  - [v13,bpf-next,10/10] selftests/bpf: tests for using dynptrs to parse skb and xdp buffers
    https://git.kernel.org/bpf/bpf-next/c/cfa7b011894d

You are awesome, thank you!

Signature · 2 lines
Deet-doot-dot, I am a bot.
https://korg.docs.kernel.org/patchwork/pwbot.html
maintainer
#46 lore raw
In reply to Joanne Koong
Quoted 9 lines · On Wed, 1 Mar 2023 07:49:43 -0800 Joanne Koong wrote:

This patchset is the 2nd in the dynptr series. The 1st can be found here [0].

This patchset adds skb and xdp type dynptrs, which have two main benefits for packet parsing:
* allowing operations on sizes that are not statically known at compile-time (eg variable-sized accesses).
* more ergonomic and less brittle iteration through data (eg does not need manual if checking for being within bounds of data_end)

Quoted 3 lines

When comparing the differences in runtime for packet parsing without dynptrs vs. with dynptrs, there is no noticeable difference. Patch 9 contains more details as well as examples of how to use skb and xdp dynptrs.

Oddly I see an error trying to build net-next with clang 15.0.7, but I'm 90% sure that it built yesterday, has anyone seen:

../kernel/bpf/verifier.c:10298:24: error: array index 16 is past the end of the array (which contains 16 elements) [-Werror,-Warray-bounds]

                                   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
                                                   ^                  ~~~~~~~~~~~~~~~~~~~~~~~~

../kernel/bpf/verifier.c:9150:1: note: array 'special_kfunc_list' declared here BTF_ID_LIST(special_kfunc_list)
^
../include/linux/btf_ids.h:207:27: note: expanded from macro 'BTF_ID_LIST'

#define BTF_ID_LIST(name) static u32 __maybe_unused name[16];
                          ^

1 error generated.

#47 lore raw
Quoted 11 lines · Jakub Kicinski
Quoted 9 lines · On Wed, 1 Mar 2023 07:49:43 -0800 Joanne Koong wrote:

This patchset is the 2nd in the dynptr series. The 1st can be found here [0].

This patchset adds skb and xdp type dynptrs, which have two main benefits for packet parsing:
* allowing operations on sizes that are not statically known at compile-time (eg variable-sized accesses).
* more ergonomic and less brittle iteration through data (eg does not need manual if checking for being within bounds of data_end)

Quoted 6 lines
Quoted 3 lines

When comparing the differences in runtime for packet parsing without dynptrs vs. with dynptrs, there is no noticeable difference. Patch 9 contains more details as well as examples of how to use skb and xdp dynptrs.

Oddly I see an error trying to build net-next with clang 15.0.7, but I'm 90% sure that it built yesterday, has anyone seen:

yep, it was fixed in bpf-next:

2d5bcdcda879 ("bpf: Increase size of BTF_ID_LIST without CONFIG_DEBUG_INFO_BTF again")

Quoted 11 lines

../kernel/bpf/verifier.c:10298:24: error: array index 16 is past the end of the array (which contains 16 elements) [-Werror,-Warray-bounds]

                                   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
                                                   ^                  ~~~~~~~~~~~~~~~~~~~~~~~~

../kernel/bpf/verifier.c:9150:1: note: array 'special_kfunc_list' declared here BTF_ID_LIST(special_kfunc_list)
^
../include/linux/btf_ids.h:207:27: note: expanded from macro 'BTF_ID_LIST'

#define BTF_ID_LIST(name) static u32 __maybe_unused name[16];
                          ^

1 error generated.

maintainer
#48 lore raw
Quoted 15 lines · On Wed, 8 Mar 2023 09:08:09 -0800 Andrii Nakryiko wrote:
Quoted 14 lines · Jakub Kicinski
Quoted 12 lines · On Wed, 1 Mar 2023 07:49:43 -0800 Joanne Koong wrote:

This patchset is the 2nd in the dynptr series. The 1st can be found here [0].

This patchset adds skb and xdp type dynptrs, which have two main benefits for packet parsing:
* allowing operations on sizes that are not statically known at compile-time (eg variable-sized accesses).
* more ergonomic and less brittle iteration through data (eg does not need manual if checking for being within bounds of data_end)

When comparing the differences in runtime for packet parsing without dynptrs vs. with dynptrs, there is no noticeable difference. Patch 9 contains more details as well as examples of how to use skb and xdp dynptrs.

Quoted 7 lines
Quoted 2 lines

Oddly I see an error trying to build net-next with clang 15.0.7, but I'm 90% sure that it built yesterday, has anyone seen:

yep, it was fixed in bpf-next:

2d5bcdcda879 ("bpf: Increase size of BTF_ID_LIST without CONFIG_DEBUG_INFO_BTF again")

Perfect, thanks! Could you get that to us ASAP, please?

#49 lore raw
Quoted 20 lines · Jakub Kicinski
Quoted 18 lines · On Wed, 8 Mar 2023 09:08:09 -0800 Andrii Nakryiko wrote:
Quoted 16 lines · Jakub Kicinski
Quoted 9 lines · On Wed, 1 Mar 2023 07:49:43 -0800 Joanne Koong wrote:

This patchset is the 2nd in the dynptr series. The 1st can be found here [0].

This patchset adds skb and xdp type dynptrs, which have two main benefits for packet parsing:
* allowing operations on sizes that are not statically known at compile-time (eg variable-sized accesses).
* more ergonomic and less brittle iteration through data (eg does not need manual if checking for being within bounds of data_end)

Quoted 3 lines

When comparing the differences in runtime for packet parsing without dynptrs vs. with dynptrs, there is no noticeable difference. Patch 9 contains more details as well as examples of how to use skb and xdp dynptrs.

Oddly I see an error trying to build net-next with clang 15.0.7, but I'm 90% sure that it built yesterday, has anyone seen:

Quoted 6 lines
Quoted 4 lines

yep, it was fixed in bpf-next:

2d5bcdcda879 ("bpf: Increase size of BTF_ID_LIST without CONFIG_DEBUG_INFO_BTF again")

Perfect, thanks! Could you get that to us ASAP, please?

yep, will send PR soon