Skip to contentSkip to conversation

sched_ext: Fix unbounded format string reads in the bstr kfuncs

PATCH Superseded Andrea Righi 2 participants 4 messages Nov 30

Subsystems (2)

v2 of 3 Superseded Latest is v3 →

lore
Share & tools
lore

Andrea Righi

author reviewer
#0 lore raw

PATCH v2 1/1 sched_ext: Fix unbounded format string reads in the bstr kfuncs

The format strings passed to the sched_ext bstr kfuncs are only checked by the verifier to be readable for a single byte, so an unterminated format makes bpf_bprintf_prepare() scan past the end of the BPF object [1].

Annotating them with __str would break compatibility in both directions, since common.bpf.h places the formats in writable .data. Instead, copy the format into a private kernel buffer with a bounded, fault-safe read and use only the copy for both preparation and formatting, leaving the kfunc prototypes and the BPF-side wrappers unchanged.

[1] https://lore.kernel.org/all/[email protected]

Changes in v2:
- Add a patch to disallow scx_bpf_dump_bstr() from tracing programs, preventing a nested call on the dumping CPU from overwriting the format snapshot of the outer call (Sashiko)
- Link to v1: https://lore.kernel.org/r/[email protected]

Andrea Righi (2):
sched_ext: Disallow scx_bpf_dump_bstr() from tracing programs
sched_ext: Fix unbounded format string reads in the bstr kfuncs

 kernel/sched/ext/ext.c      | 55 +++++++++++++++++++++++++++----------
 kernel/sched/ext/internal.h |  4 +++
 kernel/sched/ext/types.h    |  1 +
 3 files changed, 46 insertions(+), 14 deletions(-)
author reviewer
#1 lore raw

PATCH 1/2 sched_ext: Disallow scx_bpf_dump_bstr() from tracing programs

scx_bpf_dump_bstr() is in scx_kfunc_ids_any, so tracing programs can call it too. However, it's only meaningful from ops.dump(), ops.dump_cpu() and ops.dump_task(): called from any other CPU, it just aborts the scheduler.

Moreover, a tracing program running on the dumping CPU in the middle of another scx_bpf_dump_bstr() call (e.g., attached to a function invoked while formatting) can clobber the shared buffers in scx_dump_data that the outer call is still using, corrupting the dump output.

Add scx_bpf_dump_bstr() to scx_kfunc_ids_no_tracing, so that tracing programs calling it are rejected at load time.

Fixes 07814a9439a3 ("sched_ext: Print debug dump after an error exit")
---
 kernel/sched/ext/ext.c | 5 +++++
 1 file changed, 5 insertions(+)
kernel/sched/ext/ext.c +5 -0
index a4a93ed97f7b6..928652dbeb1b4 100644
@@ -12267,6 +12267,10 @@ static const struct btf_kfunc_id_set scx_kfunc_set_any = {
  * arbitrary tracing context. One that calls scx_bpf_cidperf_set() hits the
  * deadlock above.
  *
+ * scx_bpf_dump_bstr() is only meaningful from ops.dump*(). A tracing program
+ * can run on the dumping CPU in the middle of another scx_bpf_dump_bstr()
+ * call and clobber its shared format and line buffers.
+ *
  * Members must also stay in scx_kfunc_ids_any so that struct_ops and syscall
  * programs keep their access.
  */
@@ -12278,6 +12282,7 @@ BTF_ID_FLAGS(func, scx_bpf_sub_revoke, KF_IMPLICIT_ARGS)
 BTF_ID_FLAGS(func, scx_bpf_destroy_dsq, KF_IMPLICIT_ARGS)
 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_next, KF_ITER_NEXT | KF_RET_NULL)
 BTF_ID_FLAGS(func, bpf_iter_scx_dsq_destroy, KF_ITER_DESTROY)
+BTF_ID_FLAGS(func, scx_bpf_dump_bstr, KF_IMPLICIT_ARGS)
 BTF_KFUNCS_END(scx_kfunc_ids_no_tracing)
 
 /*
Signature · 1 line
2.56.1
author reviewer
#2 lore raw

PATCH 2/2 sched_ext: Fix unbounded format string reads in the bstr kfuncs

In reply to Andrea Righi

The format string arguments of the sched_ext bstr kfuncs (scx_bpf_exit_bstr(), scx_bpf_error_bstr(), scx_bpf_dump_bstr() and scx_bpf_sub_kill_bstr()) are passed to bpf_bprintf_prepare() with a UINT_MAX length. The verifier only checks that the pointer is readable for a single byte, so an unterminated format makes strnchr() scan past the end of the BPF object, possibly into unmapped memory. If the scan covers more than INT_MAX bytes before finding a NUL, it can also overflow the int index of the parsing loop.

Moreover, the format usually lives in a writable .data map, so it can be modified by the BPF program between bpf_bprintf_prepare() and bstr_printf(), making the latter interpret arguments that have not been validated and prepared.

Fix this by taking a snapshot of the format into a private kernel buffer using a bounded, fault-safe read and using only the snapshot for both preparation and formatting. Formats of SCX_BSTR_FMT_LEN (1024) bytes or more, including the NUL, are rejected with -E2BIG, which doesn't affect any realistic format, as messages are already limited to SCX_EXIT_MSG_LEN.

The snapshot is too large for the stack (these kfuncs can run in NMI), so store it next to the existing output buffers, which already have a single user at any time: scx_exit_info (per scheduler, written only by the winner of scx_claim_exit()) for the exit path, and scx_bstr_buf (serialized by scx_dump_lock) for the dump path.

Note that the bounded read may still access memory beyond the BPF object up to SCX_BSTR_FMT_LEN bytes. This is not a concern, since loading a struct_ops program requires CAP_PERFMON, which already allows reading arbitrary kernel memory via bpf_probe_read_kernel_str().

The kfunc prototypes and the BPF-side wrappers are unchanged, so existing BPF schedulers keep working on fixed kernels and newly built ones keep working on older kernels.

Fixes f0e1a0643a59 ("sched_ext: Implement BPF extensible scheduler class")
Cc [email protected] # v6.12+
---
 kernel/sched/ext/ext.c      | 50 ++++++++++++++++++++++++++-----------
 kernel/sched/ext/internal.h |  4 +++
 kernel/sched/ext/types.h    |  1 +
 3 files changed, 41 insertions(+), 14 deletions(-)
kernel/sched/ext/ext.c +36 -14
index 928652dbeb1b4..c98a01eba04f1 100644
@@ -7389,6 +7389,7 @@ void scx_bypass(struct scx_sched *sch, bool bypass)
 static void free_exit_info(struct scx_exit_info *ei)
 {
 	kvfree(ei->dump);
+	kfree(ei->fmt);
 	kfree(ei->msg);
 	kfree(ei->bt);
 	kfree(ei);
@@ -7405,9 +7406,10 @@ static struct scx_exit_info *alloc_exit_info(size_t exit_dump_len)
 	ei->exit_cpu = -1;
 	ei->bt = kzalloc_objs(ei->bt[0], SCX_EXIT_BT_LEN);
 	ei->msg = kzalloc(SCX_EXIT_MSG_LEN, GFP_KERNEL);
+	ei->fmt = kzalloc(SCX_BSTR_FMT_LEN, GFP_KERNEL);
 	ei->dump = kvzalloc(exit_dump_len, GFP_KERNEL);
 
-	if (!ei->bt || !ei->msg || !ei->dump) {
+	if (!ei->bt || !ei->msg || !ei->fmt || !ei->dump) {
 		free_exit_info(ei);
 		return NULL;
 	}
@@ -11355,14 +11357,35 @@ __bpf_kfunc void scx_bpf_reenqueue_local___v2(const struct bpf_prog_aux *aux)
 
 __bpf_kfunc_end_defs();
 
-__printf(5, 0)
-static s32 __bstr_format(struct scx_sched *sch, u64 *data_buf, char *line_buf,
-			 size_t line_size, char *fmt, unsigned long long *data,
-			 u32 data__sz)
+/*
+ * @fmt may be unterminated and writable by BPF, use only the bounded copy in
+ * @dst to prepare and format the string.
+ */
+static s32 scx_snapshot_fmt(char *dst, size_t size, const char *fmt)
+{
+	long ret = strncpy_from_kernel_nofault(dst, fmt, size);
+
+	if (ret < 0)
+		return ret;
+	/* @size means truncated or NUL in the last byte, reject both */
+	if (ret == size)
+		return -E2BIG;
+	return 0;
+}
+
+static s32 __bstr_format(struct scx_sched *sch, u64 *data_buf, char *fmt_buf,
+			 char *line_buf, size_t line_size, const char *fmt,
+			 unsigned long long *data, u32 data__sz)
 {
 	struct bpf_bprintf_data bprintf_data = { .get_bin_args = true };
 	s32 ret;
 
+	ret = scx_snapshot_fmt(fmt_buf, SCX_BSTR_FMT_LEN, fmt);
+	if (ret < 0) {
+		scx_error(sch, "failed to read format string (%d)", ret);
+		return ret;
+	}
+
 	if (data__sz % 8 || data__sz > MAX_BPRINTF_VARARGS * 8 ||
 	    (data__sz && !data)) {
 		scx_error(sch, "invalid data=%p and data__sz=%u", (void *)data, data__sz);
@@ -11375,18 +11398,17 @@ static s32 __bstr_format(struct scx_sched *sch, u64 *data_buf, char *line_buf,
 		return ret;
 	}
 
-	ret = bpf_bprintf_prepare(fmt, UINT_MAX, data_buf, data__sz / 8,
-				  &bprintf_data);
+	ret = bpf_bprintf_prepare(fmt_buf, SCX_BSTR_FMT_LEN, data_buf,
+				  data__sz / 8, &bprintf_data);
 	if (ret < 0) {
 		scx_error(sch, "format preparation failed (%d)", ret);
 		return ret;
 	}
 
-	ret = bstr_printf(line_buf, line_size, fmt,
-			  bprintf_data.bin_args);
+	ret = bstr_printf(line_buf, line_size, fmt_buf, bprintf_data.bin_args);
 	bpf_bprintf_cleanup(&bprintf_data);
 	if (ret < 0) {
-		scx_error(sch, "(\"%s\", %p, %u) failed to format", fmt, data, data__sz);
+		scx_error(sch, "(\"%s\", %p, %u) failed to format", fmt_buf, data, data__sz);
 		return ret;
 	}
 
@@ -11417,8 +11439,8 @@ bool scx_exit_bstr(struct scx_sched *sch, enum scx_exit_kind kind,
 	if (!scx_claim_exit(sch, kind))
 		return false;
 
-	ret = __bstr_format(fmt_blame, data_buf, ei->msg, SCX_EXIT_MSG_LEN,
-			    fmt, data, data__sz);
+	ret = __bstr_format(fmt_blame, data_buf, ei->fmt, ei->msg,
+			    SCX_EXIT_MSG_LEN, fmt, data, data__sz);
 	if (ret < 0)
 		scnprintf(ei->msg, SCX_EXIT_MSG_LEN,
 			  "exit message formatting failed (%d)", ret);
@@ -11513,11 +11535,11 @@ __bpf_kfunc void scx_bpf_dump_bstr(char *fmt, unsigned long long *data,
 	}
 
 	/* append the formatted string to the line buf */
-	ret = __bstr_format(sch, buf->data, buf->line + dd->cursor,
+	ret = __bstr_format(sch, buf->data, buf->fmt, buf->line + dd->cursor,
 			    sizeof(buf->line) - dd->cursor, fmt, data, data__sz);
 	if (ret < 0) {
 		scx_dump_line(dd->s, "%s[!] (\"%s\", %p, %u) failed to format (%d)",
-			      dd->prefix, fmt, data, data__sz, ret);
+			      dd->prefix, buf->fmt, data, data__sz, ret);
 		return;
 	}
 
kernel/sched/ext/internal.h +4 -0
index c77f62cd7bc9a..9fa3bc0913beb 100644
@@ -124,6 +124,9 @@ struct scx_exit_info {
 	/* informational message */
 	char			*msg;
 
+	/* snapshot of the BPF-supplied format string for @msg */
+	char			*fmt;
+
 	/* debug dump */
 	char			*dump;
 };
@@ -2251,6 +2254,7 @@ struct scx_enable_cmd {
 /* string formatting from BPF */
 struct scx_bstr_buf {
 	u64			data[MAX_BPRINTF_VARARGS];
+	char			fmt[SCX_BSTR_FMT_LEN];
 	char			line[SCX_EXIT_MSG_LEN];
 };
 
kernel/sched/ext/types.h +1 -0
index 38514d6bf1495..6450e94cc8405 100644
@@ -36,6 +36,7 @@ enum scx_consts {
 
 	SCX_EXIT_BT_LEN			= 64,
 	SCX_EXIT_MSG_LEN		= 1024,
+	SCX_BSTR_FMT_LEN		= 1024,
 	SCX_EXIT_DUMP_DFL_LEN		= 32768,
 
 	SCX_CPUPERF_ONE			= SCHED_CAPACITY_SCALE,
Signature · 1 line
2.56.1
#3 lore raw
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] sched_ext: missing re-entrancy guard in scx_bpf_dump_bstr() for stable --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] sched_ext: missing re-entrancy guard in scx_bpf_dump_bstr() for stable
--

commit 96c34c3723cdfae7a173919614dbc82435b3aff5
Author: Andrea Righi <[email protected]>

sched_ext: Fix unbounded format string reads in the bstr kfuncs

This commit copies BPF format strings into a bounded kernel buffer via strncpy_from_kernel_nofault() before calling bpf_bprintf_prepare() and bstr_printf().

Quoted 4 lines
kernel/sched/ext/ext.c +0 -0
index 27502dcae0433..7483b10587a90 100644

[ ... ]

Quoted 23 lines
kernel/sched/ext/ext.c +4 -5
@@ -11303,18 +11326,17 @@ static s32 __bstr_format(struct scx_sched *sch, u64 *data_buf, char *line_buf,
 		return ret;
 	}
 
-	ret = bpf_bprintf_prepare(fmt, UINT_MAX, data_buf, data__sz / 8,
-				  &bprintf_data);
+	ret = bpf_bprintf_prepare(fmt_buf, SCX_BSTR_FMT_LEN, data_buf,
+				  data__sz / 8, &bprintf_data);
 	if (ret < 0) {
 		scx_error(sch, "format preparation failed (%d)", ret);
 		return ret;
 	}
 
-	ret = bstr_printf(line_buf, line_size, fmt,
-			  bprintf_data.bin_args);
+	ret = bstr_printf(line_buf, line_size, fmt_buf, bprintf_data.bin_args);
 	bpf_bprintf_cleanup(&bprintf_data);
 	if (ret < 0) {
-		scx_error(sch, "(\"%s\", %p, %u) failed to format", fmt, data, data__sz);
+		scx_error(sch, "(\"%s\", %p, %u) failed to format", fmt_buf, data, data__sz);
 		return ret;
 	}
 

[ ... ]

kernel/sched/ext/ext.c __bpf_kfunc void scx_bpf_dump_bstr(char *fmt, unsigned long long *data, · line 11472

Quoted 13 lines
kernel/sched/ext/ext.c +2 -2
@@ -11441,11 +11463,11 @@ __bpf_kfunc void scx_bpf_dump_bstr(char *fmt, unsigned long long *data,
 	}
 
 	/* append the formatted string to the line buf */
-	ret = __bstr_format(sch, buf->data, buf->line + dd->cursor,
+	ret = __bstr_format(sch, buf->data, buf->fmt, buf->line + dd->cursor,
 			    sizeof(buf->line) - dd->cursor, fmt, data, data__sz);
 	if (ret < 0) {
 		scx_dump_line(dd->s, "%s[!] (\"%s\", %p, %u) failed to format (%d)",
-			      dd->prefix, fmt, data, data__sz, ret);
+			      dd->prefix, buf->fmt, data, data__sz, ret);
 		return;
 	}

[Severity: Medium]
As reported by Tejun Heo on v1 [1], can re-entering scx_bpf_dump_bstr() on dd->cpu overwrite the shared buf->fmt and cause a NULL pointer dereference in bstr_printf()?

scx_bpf_dump_bstr() (fmt="hello", data__sz=0)
__bstr_format()

    scx_snapshot_fmt(buf->fmt, ..., "hello")
    bpf_bprintf_prepare(buf->fmt, ..., num_args=0, &bprintf_data)
      bprintf_data.bin_args = NULL
    <fexit/bpf_bprintf_prepare or IRQ/NMI tracing prog on dd->cpu>
      scx_bpf_dump_bstr() (fmt="%s", data__sz=8)
        __bstr_format()
          scx_snapshot_fmt(buf->fmt, ..., "%s")
          ...
    bstr_printf(..., buf->fmt, bprintf_data.bin_args)
      <-- dereferences NULL bin_args for "%s"

The earlier commit "sched_ext: Disallow scx_bpf_dump_bstr() from tracing programs" in this series blocks tracing callers via scx_kfunc_ids_no_tracing, which was added in the current cycle. However, this commit is tagged for v6.12+ stable trees where scx_kfunc_ids_no_tracing does not exist, so scx_bpf_dump_bstr() still needs an in-function re-entrancy guard around __bstr_format() (such as a busy flag in scx_dump_data or temporarily clearing dd->cpu).

[1] https://lore.kernel.org/r/[email protected]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2