Skip to contentSkip to conversation

sysctl: Disallow partial updates of miss-formatted sysctl vectors

PATCH In review Joel Granados 3 participants 21 messages Aug 14 – Aug 18

Subsystems (4)
lore
Share & tools
lore

Joel Granados

author maintainer
#0 lore raw

v2 cover sysctl: Disallow partial updates of miss-formatted sysctl vectors

What?
=====

Stage table->data when writing INT & ULONG ctl_tables. Commit staged data to kernel variable only when all the conversions have succeeded. This is applicable only to variables that represent a vector; paths pertaining to scalers are left unchanged. Notice that partial updates can still happen if less than the size of the vector are passed and correctly formatted.

This is the behavior we are protecting against:

  # echo "4 4 1 7" > /proc/sys/kernel/printk
  # echo "1 x" > /proc/sys/kernel/printk
  -bash: echo: write error: Invalid argument
  # cat /proc/sys/kernel/printk
  1 4 1 7    <- the write failed, the first element changed anyway

Why?
====
Allowing a partial change to a vector after returning from an erroneous proc_handler is just plain wrong. This should be handled within sysctl to avoid users having to do it for themselves [1].

Behavioral Changes
==================
1. A failed write will not update the vector
2. Vector writes can now fail with -ENOMEM

Testing
=======
This went through regular sysctl kunit and self test. Also is posted to 0-day.

I always find it difficult to know who wants to receive this. Please let me know if you want to be removed from the Cc/To.

Best

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

---
Changes in v2:
- Avoid doc compilation warnings related to apply_conv_on_vec function
- Initialize rc in testing to avoid a false positive when executing 0013 individually
- Link to v1: https://lore.kernel.org/r/[email protected]

---
Joel Granados (4):
sysctl: Split data conversion and file position handling
sysctl: Reject uint arrays before calling the general proc_vec
sysctl: Disallow partial updates for erroneous sysctl vectors
sysctl: Add 0013 to test partially updated vectors

 kernel/sysctl.c                          | 237 ++++++++++++++++++++-----------
 tools/testing/selftests/sysctl/sysctl.sh |  60 ++++++++
 2 files changed, 217 insertions(+), 80 deletions(-)

---
base-commit: 4c12287001da60f3c022bb25932aa7a5590fc0b1
change-id: 20260813-lklm-partial_ctlvec-bd8867b70d5c

Best regards,

Signature · 1 line
Joel Granados <[email protected]>
author maintainer
#1 lore raw

PATCH v2 1/4 sysctl: Split data conversion and file position handling

Apply the conversions to the data in a new helper function (apply_conv_on_vec) while file position handling and argument validation stay in the original function. Rename function to prov_vec (from do_proc_vec). This is a prep commit to isolate the logic that needs to change to prevent partial sysctl vector writes. No functional change intended

---
 kernel/sysctl.c | 211 +++++++++++++++++++++++++++++++++-----------------------
 1 file changed, 126 insertions(+), 85 deletions(-)
kernel/sysctl.c +126 -85
index f7b75985d5420a522a316d1fade40dc7fbe60455..47a92cbbcb69cd361a18dba6606ae6ae8f86b5e2 100644
@@ -595,7 +595,7 @@ static int do_proc_int_conv_minmax(bool *negp, unsigned long *u_ptr, int *k_ptr,
 static const char proc_wspace_sep[] = { ' ', '\t', '\n' };
 
 /*
- * Element type processed by do_proc_vec(). The tag selects the element size
+ * Element type processed by proc_vec(). The tag selects the element size
  * and signedness, and it selects which member of union proc_vec_conv is live.
  */
 enum proc_vec_type {
@@ -605,7 +605,7 @@ enum proc_vec_type {
 };
 
 /*
- * Converter passed to do_proc_vec(). Only the member matching the
+ * Converter passed to proc_vec(). Only the member matching the
  * enum proc_vec_type tag is ever read, so every dispatch stays fully typed and
  * no void * converter pointer is needed.
  */
@@ -637,101 +637,142 @@ static int proc_vec_conv(enum proc_vec_type type, union proc_vec_conv conv,
 	return -EINVAL;
 }
 
-/*
- * Read/write a vector of @type elements. The element size and signedness are
- * derived from @type, so a single runtime function replaces the per-type
- * variants. table->data is walked as raw bytes (@i) advanced by @size; the
- * converter performs the actual typed load/store.
+/**
+ * apply_conv_on_vec - Apply converter function on data vector
+ *
+ * @conv: The converter to be applied
+ * @table: The sysctl table
+ * @data_type: Type used in converter appliation (INT, UINT or ULONG)
+ * @data_size: Number of data elements.
+ * @conv_dir: %TRUE if this is a write to the sysctl file
+ * @buf_nbyte: Number of bytes for buf
+ * @buf: The user buffer
+ * @buf_left_final: Number of outstanding (non converted) bytes.
+ *
+ * Element signedness is derived from @data_type. table->data is walked
+ * as raw bytes (@data) advanced by @data_size; the converter performs
+ * the actual typed load/store. Sets buf_left_final to the number of
+ * bytes that where left outstanding after conversion. Can be > 0.
+ *
+ * Returns: %0 on success. Non-zero on error.
  */
-static int do_proc_vec(const struct ctl_table *table, int dir,
-		       void *buffer, size_t *lenp, loff_t *ppos,
-		       enum proc_vec_type type, union proc_vec_conv conv)
+static int apply_conv_on_vec(const union proc_vec_conv conv,
+			     const struct ctl_table *table,
+			     const enum proc_vec_type data_type,
+			     const size_t data_size, const int conv_dir,
+			     const size_t buf_nbyte, void *buf,
+			     size_t *buf_left_final)
 {
-	int vleft, first = 1, err = 0;
-	size_t left, size;
-	bool is_unsigned;
-	char *i, *p;
+	int vec_left, first = 1, err = 0;
+	size_t buf_left;
+	char *data, *p;
+	bool is_unsigned = data_type == PROC_VEC_UINT || data_type == PROC_VEC_ULONG;
 
-	switch (type) {
-	case PROC_VEC_INT:
-		size = sizeof(int);
-		is_unsigned = false;
-		break;
-	case PROC_VEC_UINT:
-		size = sizeof(uint);
-		is_unsigned = true;
-		break;
-	case PROC_VEC_ULONG:
-		size = sizeof(ulong);
-		is_unsigned = true;
-		break;
-	default:
-		return -EINVAL;
-	}
-
-	if (!table->data || !table->maxlen || !*lenp ||
-	    (*ppos && SYSCTL_KERN_TO_USER(dir))) {
-		*lenp = 0;
-		return 0;
-	}
-
-	i = table->data;
-	vleft = table->maxlen / size;
-	left = *lenp;
-
-	/* uint arrays are not supported, *Do not* add support for them. */
-	if (type == PROC_VEC_UINT && vleft != 1)
-		return -EINVAL;
-
-	if (SYSCTL_USER_TO_KERN(dir)) {
-		if (proc_first_pos_non_zero_ignore(ppos, table))
-			goto out;
+	data = table->data;
+	vec_left = table->maxlen / data_size;
+	buf_left = buf_nbyte;
 
-		if (left > PAGE_SIZE - 1)
-			left = PAGE_SIZE - 1;
-		p = buffer;
+	if (SYSCTL_USER_TO_KERN(conv_dir)) {
+		if (buf_left > PAGE_SIZE - 1)
+			buf_left = PAGE_SIZE - 1;
+		p = buf;
 	}
 
-	for (; left && vleft--; i += size, first = 0) {
+	for (; buf_left && vec_left--; data += data_size, first = 0) {
 		unsigned long lval;
 		bool neg = false;
 
-		if (SYSCTL_USER_TO_KERN(dir)) {
-			proc_skip_spaces(&p, &left);
+		if (SYSCTL_USER_TO_KERN(conv_dir)) {
+			proc_skip_spaces(&p, &buf_left);
 
-			if (!left)
+			if (!buf_left)
 				break;
-			err = proc_get_long(&p, &left, &lval, &neg,
+			err = proc_get_long(&p, &buf_left, &lval, &neg,
 					    proc_wspace_sep,
 					    sizeof(proc_wspace_sep), NULL);
 			if (!err && neg && is_unsigned)
 				err = -EINVAL;
 			if (err)
 				break;
-			if (proc_vec_conv(type, conv, &neg, &lval, i, dir, table)) {
+			if (proc_vec_conv(data_type, conv, &neg, &lval, data, conv_dir, table)) {
 				err = -EINVAL;
 				break;
 			}
 		} else {
-			if (proc_vec_conv(type, conv, &neg, &lval, i, dir, table)) {
+			if (proc_vec_conv(data_type, conv, &neg, &lval, data, conv_dir, table)) {
 				err = -EINVAL;
 				break;
 			}
 			if (!first)
-				proc_put_char(&buffer, &left, '\t');
-			proc_put_long(&buffer, &left, lval, neg);
+				proc_put_char(&buf, &buf_left, '\t');
+			proc_put_long(&buf, &buf_left, lval, neg);
 		}
 	}
 
-	if (SYSCTL_KERN_TO_USER(dir) && !first && left && !err)
-		proc_put_char(&buffer, &left, '\n');
-	if (SYSCTL_USER_TO_KERN(dir) && !err && left)
-		proc_skip_spaces(&p, &left);
-	if (SYSCTL_USER_TO_KERN(dir) && first)
+	if (SYSCTL_KERN_TO_USER(conv_dir) && !first && buf_left && !err)
+		proc_put_char(&buf, &buf_left, '\n');
+	if (SYSCTL_USER_TO_KERN(conv_dir) && !err && buf_left)
+		proc_skip_spaces(&p, &buf_left);
+	if (SYSCTL_USER_TO_KERN(conv_dir) && first)
 		return err ? : -EINVAL;
-	*lenp -= left;
+	*buf_left_final = buf_left;
+
+	return err;
+}
+
+/* Read/write a vector of @type elements. */
+static int proc_vec(const struct ctl_table *table, int dir, void *buffer,
+		    size_t *lenp, loff_t *ppos, enum proc_vec_type type,
+		    union proc_vec_conv conv)
+{
+	int err = 0;
+	size_t data_size, left_nbyte = SIZE_MAX;
+
+	switch (type) {
+	case PROC_VEC_INT:
+		data_size = sizeof(int);
+		break;
+	case PROC_VEC_UINT:
+		data_size = sizeof(uint);
+		break;
+	case PROC_VEC_ULONG:
+		data_size = sizeof(ulong);
+		break;
+	default:
+		return -EINVAL;
+	}
+
+	if (!table->data || !table->maxlen || !*lenp ||
+	    (*ppos && SYSCTL_KERN_TO_USER(dir))) {
+		*lenp = 0;
+		return 0;
+	}
+
+	/* uint arrays are not supported, *Do not* add support for them. */
+	if (type == PROC_VEC_UINT && (table->maxlen / data_size) != 1)
+		return -EINVAL;
+
+	if (SYSCTL_USER_TO_KERN(dir)) {
+		if (proc_first_pos_non_zero_ignore(ppos, table))
+			goto out;
+	}
+
+	err = apply_conv_on_vec(conv, table, type, data_size, dir, *lenp, buffer,
+				&left_nbyte);
+
+	/*
+	 * An unchanged left_nbyte signals a write with no parsed element; which
+	 * is an error. Using SIZE_MAX to detect this error is possible because:
+	 * 1. lenp is bounded by KMALLOC_MAX_SIZE in proc_sys_call_handler
+	 * 2. lenp could never be SIZE_MAX as it is a "ridiculous" (exabyte) allocation.
+	 */
+	if (left_nbyte == SIZE_MAX)
+		return err;
+
+	*lenp -= left_nbyte;
 out:
 	*ppos += *lenp;
+
 	return err;
 }
 
@@ -760,8 +801,8 @@ int proc_douintvec_conv(const struct ctl_table *table, int dir, void *buffer,
 	if (!conv)
 		conv = do_proc_uint_conv;
 
-	return do_proc_vec(table, dir, buffer, lenp, ppos, PROC_VEC_UINT,
-			   (union proc_vec_conv){ .uint_conv = conv });
+	return proc_vec(table, dir, buffer, lenp, ppos, PROC_VEC_UINT,
+			(union proc_vec_conv){ .uint_conv = conv });
 }
 
 /**
@@ -820,8 +861,8 @@ int proc_dobool(const struct ctl_table *table, int dir, void *buffer,
 int proc_dointvec(const struct ctl_table *table, int dir, void *buffer,
 		  size_t *lenp, loff_t *ppos)
 {
-	return do_proc_vec(table, dir, buffer, lenp, ppos, PROC_VEC_INT,
-			   (union proc_vec_conv){ .int_conv = do_proc_int_conv });
+	return proc_vec(table, dir, buffer, lenp, ppos, PROC_VEC_INT,
+			(union proc_vec_conv){ .int_conv = do_proc_int_conv });
 }
 
 /**
@@ -840,8 +881,8 @@ int proc_dointvec(const struct ctl_table *table, int dir, void *buffer,
 int proc_douintvec(const struct ctl_table *table, int dir, void *buffer,
 		size_t *lenp, loff_t *ppos)
 {
-	return do_proc_vec(table, dir, buffer, lenp, ppos, PROC_VEC_UINT,
-			   (union proc_vec_conv){ .uint_conv = do_proc_uint_conv });
+	return proc_vec(table, dir, buffer, lenp, ppos, PROC_VEC_UINT,
+			(union proc_vec_conv){ .uint_conv = do_proc_uint_conv });
 }
 
 /**
@@ -864,8 +905,8 @@ int proc_douintvec(const struct ctl_table *table, int dir, void *buffer,
 int proc_dointvec_minmax(const struct ctl_table *table, int dir,
 		  void *buffer, size_t *lenp, loff_t *ppos)
 {
-	return do_proc_vec(table, dir, buffer, lenp, ppos, PROC_VEC_INT,
-			   (union proc_vec_conv){ .int_conv = do_proc_int_conv_minmax });
+	return proc_vec(table, dir, buffer, lenp, ppos, PROC_VEC_INT,
+			(union proc_vec_conv){ .int_conv = do_proc_int_conv_minmax });
 }
 
 /**
@@ -891,8 +932,8 @@ int proc_dointvec_minmax(const struct ctl_table *table, int dir,
 int proc_douintvec_minmax(const struct ctl_table *table, int dir,
 			  void *buffer, size_t *lenp, loff_t *ppos)
 {
-	return do_proc_vec(table, dir, buffer, lenp, ppos, PROC_VEC_UINT,
-			   (union proc_vec_conv){ .uint_conv = do_proc_uint_conv_minmax });
+	return proc_vec(table, dir, buffer, lenp, ppos, PROC_VEC_UINT,
+			(union proc_vec_conv){ .uint_conv = do_proc_uint_conv_minmax });
 }
 
 /**
@@ -935,8 +976,8 @@ int proc_dou8vec_minmax(const struct ctl_table *table, int dir,
 		tmp.extra2 = (unsigned int *) &max;
 
 	val = READ_ONCE(*data);
-	res = do_proc_vec(&tmp, dir, buffer, lenp, ppos, PROC_VEC_UINT,
-			  (union proc_vec_conv){ .uint_conv = do_proc_uint_conv_minmax });
+	res = proc_vec(&tmp, dir, buffer, lenp, ppos, PROC_VEC_UINT,
+		       (union proc_vec_conv){ .uint_conv = do_proc_uint_conv_minmax });
 	if (res)
 		return res;
 	if (SYSCTL_USER_TO_KERN(dir))
@@ -1066,8 +1107,8 @@ int proc_doulongvec_conv(const struct ctl_table *table, int dir,
 				int (*conv)(bool *negp, ulong *u_ptr, ulong *k_ptr,
 					    int dir, const struct ctl_table *table))
 {
-	return do_proc_vec(table, dir, buffer, lenp, ppos, PROC_VEC_ULONG,
-			   (union proc_vec_conv){ .ulong_conv = conv });
+	return proc_vec(table, dir, buffer, lenp, ppos, PROC_VEC_ULONG,
+			(union proc_vec_conv){ .ulong_conv = conv });
 }
 
 /**
@@ -1087,10 +1128,10 @@ int proc_doulongvec_conv(const struct ctl_table *table, int dir,
  * Returns: %0 on success.
  */
 int proc_doulongvec_minmax(const struct ctl_table *table, int dir,
-			   void *buffer, size_t *lenp, loff_t *ppos)
+		void *buffer, size_t *lenp, loff_t *ppos)
 {
-	return do_proc_vec(table, dir, buffer, lenp, ppos, PROC_VEC_ULONG,
-			   (union proc_vec_conv){ .ulong_conv = do_proc_ulong_conv });
+	return proc_vec(table, dir, buffer, lenp, ppos, PROC_VEC_ULONG,
+			(union proc_vec_conv){ .ulong_conv = do_proc_ulong_conv });
 }
 
 /**
@@ -1114,8 +1155,8 @@ int proc_dointvec_conv(const struct ctl_table *table, int dir, void *buffer,
 {
 	if (!conv)
 		conv = do_proc_int_conv;
-	return do_proc_vec(table, dir, buffer, lenp, ppos, PROC_VEC_INT,
-			   (union proc_vec_conv){ .int_conv = conv });
+	return proc_vec(table, dir, buffer, lenp, ppos, PROC_VEC_INT,
+			(union proc_vec_conv){ .int_conv = conv });
 }
 
 /**
Signature · 1 line
2.50.1
Reviewed-by on v2 1/4
#2 lore raw

Re: [PATCH v2 1/4] sysctl: Split data conversion and file position handling

Quoted 1 line

Rename function to prov_vec (from do_proc_vec).

s/prov_vec/proc_vec/, the diff renames it to proc_vec.

Also the SIZE_MAX comment in proc_vec() only talks about the no parsed element case, but after 3/4 a kmemdup failure leaves left_nbyte unset too (it goes to out before buf_left_final gets written). So the sentinel covers -ENOMEM as well, a line saying so would help.

The split itself is fine, so with the typo fixed:

Thanks!

author maintainer
#3 lore raw

Re: [PATCH v2 1/4] sysctl: Split data conversion and file position handling

Quoted 11 lines · Bradley Morgan
Quoted 1 line

Rename function to prov_vec (from do_proc_vec).

s/prov_vec/proc_vec/, the diff renames it to proc_vec.

Also the SIZE_MAX comment in proc_vec() only talks about the no parsed element case, but after 3/4 a kmemdup failure leaves left_nbyte unset too (it goes to out before buf_left_final gets written). So the sentinel covers -ENOMEM as well, a line saying so would help.

The split itself is fine, so with the typo fixed:

This comment is more about why it is OK to use SIZE_MAX. The case where kmemdup fails falls into the "no elements parsed".

Thx for the review.

Quoted 3 lines

Thanks!

author maintainer
#4 lore raw

PATCH v2 2/4 sysctl: Reject uint arrays before calling the general proc_vec

In reply to Joel Granados

Move the UINT vector size check to proc_douintvec_conv; the function that routes UINT types only. Route all the UINT calls (including proc_dou8vec_minmax) through proc_douintvec_conv.

UINT proc handlers that incorrectly define maxlen will now return -EINVAL instead of 0 in the cases where data is missing, lenp is 0 or ppos is 0. Note that maxlen == 0 is not considered as miss-defined.

---
 kernel/sysctl.c | 17 +++++++----------
 1 file changed, 7 insertions(+), 10 deletions(-)
kernel/sysctl.c +7 -10
index 47a92cbbcb69cd361a18dba6606ae6ae8f86b5e2..7e9024899be6d5971752dd5639ab4b806a899081 100644
@@ -748,10 +748,6 @@ static int proc_vec(const struct ctl_table *table, int dir, void *buffer,
 		return 0;
 	}
 
-	/* uint arrays are not supported, *Do not* add support for them. */
-	if (type == PROC_VEC_UINT && (table->maxlen / data_size) != 1)
-		return -EINVAL;
-
 	if (SYSCTL_USER_TO_KERN(dir)) {
 		if (proc_first_pos_non_zero_ignore(ppos, table))
 			goto out;
@@ -797,6 +793,9 @@ int proc_douintvec_conv(const struct ctl_table *table, int dir, void *buffer,
 			int (*conv)(bool *negp, ulong *u_ptr, uint *k_ptr,
 				    int dir, const struct ctl_table *table))
 {
+	/* uint arrays are not supported, *Do not* add support for them. */
+	if (table->maxlen && (table->maxlen / sizeof(uint)) != 1)
+		return -EINVAL;
 
 	if (!conv)
 		conv = do_proc_uint_conv;
@@ -881,8 +880,7 @@ int proc_dointvec(const struct ctl_table *table, int dir, void *buffer,
 int proc_douintvec(const struct ctl_table *table, int dir, void *buffer,
 		size_t *lenp, loff_t *ppos)
 {
-	return proc_vec(table, dir, buffer, lenp, ppos, PROC_VEC_UINT,
-			(union proc_vec_conv){ .uint_conv = do_proc_uint_conv });
+	return proc_douintvec_conv(table, dir, buffer, lenp, ppos, do_proc_uint_conv);
 }
 
 /**
@@ -932,8 +930,8 @@ int proc_dointvec_minmax(const struct ctl_table *table, int dir,
 int proc_douintvec_minmax(const struct ctl_table *table, int dir,
 			  void *buffer, size_t *lenp, loff_t *ppos)
 {
-	return proc_vec(table, dir, buffer, lenp, ppos, PROC_VEC_UINT,
-			(union proc_vec_conv){ .uint_conv = do_proc_uint_conv_minmax });
+	return proc_douintvec_conv(table, dir, buffer, lenp, ppos,
+				   do_proc_uint_conv_minmax);
 }
 
 /**
@@ -976,8 +974,7 @@ int proc_dou8vec_minmax(const struct ctl_table *table, int dir,
 		tmp.extra2 = (unsigned int *) &max;
 
 	val = READ_ONCE(*data);
-	res = proc_vec(&tmp, dir, buffer, lenp, ppos, PROC_VEC_UINT,
-		       (union proc_vec_conv){ .uint_conv = do_proc_uint_conv_minmax });
+	res = proc_douintvec_minmax(&tmp, dir, buffer, lenp, ppos);
 	if (res)
 		return res;
 	if (SYSCTL_USER_TO_KERN(dir))
Signature · 1 line
2.50.1
author maintainer
#6 lore raw

PATCH v2 3/4 sysctl: Disallow partial updates for erroneous sysctl vectors

In reply to Joel Granados

When updating the kernel sysctl vectors there is a chance that not all vector elements are updated due to erroneous input. Use a staging variable that holds a copy of the vector and commits to the actual table->data only when all input is successfully updated.

The staging is only for vectors; cases where table->data points to a variable should not be staged as they will not be updated on input error. PROC_VEC_UINT is not included because UINT arrays are not allowed.

Replace first with nr_conv, incremented where first was cleared. first is exactly nr_conv == 0, and the counter doubles as the number of elements to publish.

Example of behavior that is being prevented:

  # echo "4 4 1 7" > /proc/sys/kernel/printk
  # echo "1 x" > /proc/sys/kernel/printk
  -bash: echo: write error: Invalid argument
  # cat /proc/sys/kernel/printk
  1 4 1 7 <- incorrect

It should be unchanged ("4 4 1 7") on error.

---
 kernel/sysctl.c | 65 +++++++++++++++++++++++++++++++++++++++++++++------------
 1 file changed, 52 insertions(+), 13 deletions(-)
kernel/sysctl.c +52 -13
index 7e9024899be6d5971752dd5639ab4b806a899081..25577ffc2801267cc69df60a1064ada9efd4b97d 100644
@@ -637,6 +637,26 @@ static int proc_vec_conv(enum proc_vec_type type, union proc_vec_conv conv,
 	return -EINVAL;
 }
 
+static int commit_conv_vec(const enum proc_vec_type data_type, void *dst,
+			    const void *src, size_t nr)
+{
+	size_t i;
+
+	switch (data_type) {
+	case PROC_VEC_INT:
+		for (i = 0; i < nr; i++)
+			WRITE_ONCE(((int *)dst)[i], ((const int *)src)[i]);
+		return 0;
+
+	case PROC_VEC_ULONG:
+		for (i = 0; i < nr; i++)
+			WRITE_ONCE(((ulong *)dst)[i], ((const ulong *)src)[i]);
+		return 0;
+	default:
+		return -EINVAL;
+	}
+}
+
 /**
  * apply_conv_on_vec - Apply converter function on data vector
  *
@@ -663,22 +683,31 @@ static int apply_conv_on_vec(const union proc_vec_conv conv,
 			     const size_t buf_nbyte, void *buf,
 			     size_t *buf_left_final)
 {
-	int vec_left, first = 1, err = 0;
-	size_t buf_left;
-	char *data, *p;
+	int vec_left, err = 0;
+	size_t buf_left, nr_conv = 0;
+	char *data, *data_stage = NULL, *p;
 	bool is_unsigned = data_type == PROC_VEC_UINT || data_type == PROC_VEC_ULONG;
 
-	data = table->data;
-	vec_left = table->maxlen / data_size;
 	buf_left = buf_nbyte;
 
+	data = table->data;
 	if (SYSCTL_USER_TO_KERN(conv_dir)) {
 		if (buf_left > PAGE_SIZE - 1)
 			buf_left = PAGE_SIZE - 1;
 		p = buf;
+
+		if (table->maxlen > data_size) {
+			data_stage = kmemdup(table->data, table->maxlen, GFP_KERNEL);
+			if (!data_stage) {
+				err = -ENOMEM;
+				goto out;
+			}
+			data = data_stage;
+		}
 	}
 
-	for (; buf_left && vec_left--; data += data_size, first = 0) {
+	vec_left = table->maxlen / data_size;
+	for (; buf_left && vec_left--; data += data_size, nr_conv++) {
 		unsigned long lval;
 		bool neg = false;
 
@@ -703,20 +732,30 @@ static int apply_conv_on_vec(const union proc_vec_conv conv,
 				err = -EINVAL;
 				break;
 			}
-			if (!first)
+			if (nr_conv)
 				proc_put_char(&buf, &buf_left, '\t');
 			proc_put_long(&buf, &buf_left, lval, neg);
 		}
 	}
 
-	if (SYSCTL_KERN_TO_USER(conv_dir) && !first && buf_left && !err)
-		proc_put_char(&buf, &buf_left, '\n');
-	if (SYSCTL_USER_TO_KERN(conv_dir) && !err && buf_left)
-		proc_skip_spaces(&p, &buf_left);
-	if (SYSCTL_USER_TO_KERN(conv_dir) && first)
-		return err ? : -EINVAL;
+	if (SYSCTL_USER_TO_KERN(conv_dir)) {
+		if (!err && buf_left)
+			proc_skip_spaces(&p, &buf_left);
+		if (!nr_conv) {
+			err = err ? : -EINVAL;
+			goto out;
+		}
+		if (!err && data_stage)
+			err = commit_conv_vec(data_type, table->data, data_stage, nr_conv);
+	} else {
+		if (nr_conv && buf_left && !err)
+			proc_put_char(&buf, &buf_left, '\n');
+	}
+
 	*buf_left_final = buf_left;
 
+out:
+	kfree(data_stage);
 	return err;
 }
 
Signature · 1 line
2.50.1
Reviewed-by on v2 3/4
#7 lore raw

Re: [PATCH v2 3/4] sysctl: Disallow partial updates for erroneous sysctl vectors

commit_conv_vec() writes the elements one by one, so a reader can still see a mix of old and new values while the loop runs. Same as before this series, so no regression, but the changelog could say this doesn't make the write atomic either. Otherwise someone later will expect the vector to change all at once.

The copy is limited by table->maxlen and only vectors pay for it.

Fine by me.

Thanks!

author maintainer
#8 lore raw

Re: [PATCH v2 3/4] sysctl: Disallow partial updates for erroneous sysctl vectors

Quoted 5 lines · Bradley Morgan

commit_conv_vec() writes the elements one by one, so a reader can still see a mix of old and new values while the loop runs. Same as before this series, so no regression, but the changelog could say this doesn't make the write atomic either. Otherwise someone later will expect the vector to change all at once.

Seems reasonable: here is what I added to the commit message:

"
... This (The staging vector) does **not** make the write atomic as a reader can still see a partially updated vector.

...
"

Best

Joel

Quoted 7 lines

The copy is limited by table->maxlen and only vectors pay for it.

Fine by me.

Thanks!

#9 lore raw

Re: [PATCH v2 3/4] sysctl: Disallow partial updates for erroneous sysctl vectors

Quoted 7 lines · Joel Granados
Quoted 5 lines · Bradley Morgan

commit_conv_vec() writes the elements one by one, so a reader can still see a mix of old and new values while the loop runs. Same as before this series, so no regression, but the changelog could say this doesn't make the write atomic either. Otherwise someone later will expect the vector to change all at once.

Quoted 8 lines

Seems reasonable: here is what I added to the commit message:

"
... This (The staging vector) does **not** make the write atomic as a reader
can still see a partially updated vector.

Good enough.

Quoted 15 lines

...
"

Best

Joel

Quoted 7 lines

The copy is limited by table->maxlen and only vectors pay for it.

Fine by me.

Thanks!

Thanks!

#10 lore raw

Re: [PATCH v2 3/4] sysctl: Disallow partial updates for erroneous sysctl vectors

Quoted 12 lines · Bradley Morgan
Quoted 10 lines · Joel Granados
Quoted 5 lines · Bradley Morgan

commit_conv_vec() writes the elements one by one, so a reader can still see a mix of old and new values while the loop runs. Same as before this series, so no regression, but the changelog could say this doesn't make the write atomic either. Otherwise someone later will expect the vector to change all at once.

Seems reasonable: here is what I added to the commit message:

Quoted 8 lines
Quoted 5 lines

"
... This (The staging vector) does **not** make the write atomic as a reader
can still see a partially updated vector.

Good enough.

Hmm. Removed a folk off CC:

** Address not found **

Your message wasn't delivered to [email protected] because the address couldn't be found, or is unable to receive mail.

Learn more here: https://support.google.com/mail/?p=NoSuchUser

The response was:

The email account that you tried to reach does not exist. Please try double-checking the recipient's email address for typos or unnecessary spaces. For more information, go to
https://support.google.com/mail/?p=NoSuchUser

:(

Quoted 11 lines
Quoted 11 lines

...
"

Best

Joel

Quoted 3 lines

The copy is limited by table->maxlen and only vectors pay for it.

Quoted 7 lines
Quoted 5 lines
Quoted 4 lines

Fine by me.

Thanks!

Thanks!

Thanks!

author maintainer
#11 lore raw

PATCH v2 4/4 sysctl: Add 0013 to test partially updated vectors

In reply to Joel Granados

Add coverage for partially updated sysctl vectors with test 0013. It makes sure that the sysctl vector is unchanged when one of the elements is not valid.

---
 tools/testing/selftests/sysctl/sysctl.sh | 60 ++++++++++++++++++++++++++++++++
 1 file changed, 60 insertions(+)
tools/testing/selftests/sysctl/sysctl.sh +60 -0
index b2d8bd9026a721e96c26be20069f7f87b06a5cf7..dc8674455284612dfe898944b886d856fb8ab3fe 100755
@@ -4,6 +4,7 @@
 
 # This performs a series tests against the proc sysctl interface.
 
+# shellcheck disable=SC2317
 # Kselftest framework requirement - SKIP code is 4.
 ksft_skip=4
 
@@ -12,6 +13,9 @@ TEST_DRIVER="test_${TEST_NAME}"
 TEST_DIR=$(dirname $0)
 TEST_FILE=$(mktemp)
 
+# initialize for individual tests
+rc=0
+
 # This represents
 #
 # TEST_ID:TEST_COUNT:ENABLED:TARGET:SKIP_NO_TARGET
@@ -37,6 +41,7 @@ ALL_TESTS="$ALL_TESTS 0009:1:1:unregister_error:0"
 ALL_TESTS="$ALL_TESTS 0010:1:1:mnt/mnt_error:0"
 ALL_TESTS="$ALL_TESTS 0011:1:1:empty_add:0"
 ALL_TESTS="$ALL_TESTS 0012:1:1:u8_valid:0"
+ALL_TESTS="$ALL_TESTS 0013:1:1:int_0003:1"
 
 function allow_user_defaults()
 {
@@ -196,6 +201,18 @@ verify_diff_w()
 	return $?
 }
 
+# Verify that an erroneous ($2) update fails and does not change TARGET
+verify_no_partial_update()
+{
+	TEST_STR="$1"
+	echo -n "$TEST_STR" > "$TARGET"
+
+	if echo -n "$2" > "$TARGET" 2> /dev/null; then
+		return 1
+	fi
+	verify_diff_w "${TARGET}"
+}
+
 test_rc()
 {
 	if [[ $rc != 0 ]]; then
@@ -501,6 +518,40 @@ run_limit_digit_int_array()
 	test_rc
 }
 
+# You used an int array and one of the elements is not acceptable
+run_int_array_no_partial_update()
+{
+	echo -n "Testing invalid array element does not partially update ... "
+        # Expect failure because of 3rd element (abc).
+	if ! verify_no_partial_update "1 2 3 4" "10 20 abc 40"; then
+		echo "FAIL" >&2
+		rc=1
+	else
+		echo "OK"
+	fi
+	test_rc
+
+	echo -n "Testing out of range array element does not partially update ... "
+        # Expect failure because of 3rd element (greater than int)
+	if ! verify_no_partial_update "1 2 3 4" "10 20 $((INT_MAX + 1)) 40"; then
+		echo "FAIL" >&2
+		rc=1
+	else
+		echo "OK"
+	fi
+	test_rc
+
+	echo -n "Testing invalid first array element does not update ... "
+        # Expect failure of 1st element
+	if ! verify_no_partial_update "1 2 3 4" "abc 20 30 40"; then
+		echo "FAIL" >&2
+		rc=1
+	else
+		echo "OK"
+	fi
+	test_rc
+}
+
 # You are using an unsigned int
 run_limit_digit_uint()
 {
@@ -880,6 +931,14 @@ sysctl_test_0012()
 	return 0
 }
 
+sysctl_test_0013()
+{
+	TARGET="${SYSCTL}/$(get_test_target 0013)"
+	reset_vals
+
+	run_int_array_no_partial_update
+}
+
 list_tests()
 {
 	echo "Test ID list:"
@@ -900,6 +959,7 @@ list_tests()
 	echo "0010 x $(get_test_count 0010) - tests sysct mount point"
 	echo "0011 x $(get_test_count 0011) - tests empty directories"
 	echo "0012 x $(get_test_count 0012) - tests range check for u8 proc_handler"
+	echo "0013 x $(get_test_count 0013) - tests partially update vectors on error"
 }
 
 usage()
Signature · 1 line
2.50.1
Reviewed-by on v2 4/4
#12 lore raw

Re: [PATCH v2 4/4] sysctl: Add 0013 to test partially updated vectors

The test covers the parse error, the out of range value and the first value failing. That's the right coverage.

The shellcheck disable should say why. The test functions are only called through the dispatch string, so shellcheck thinks they are unreachable.

run_int_array_no_partial_update() uses spaces for its comment lines while the code uses tabs.

reset_vals() has no case for int_0003, so sysctl_test_0013 calls it for nothing. Drop the call or add a case for int_0003.

Nits aside, the test does what it should:

Thanks!

author maintainer
#13 lore raw

Re: [PATCH v2 4/4] sysctl: Add 0013 to test partially updated vectors

Quoted 6 lines · Bradley Morgan

The test covers the parse error, the out of range value and the first value failing. That's the right coverage.

The shellcheck disable should say why. The test functions are only called through the dispatch string, so shellcheck thinks they are unreachable.

I expect to remove this in the new sysctl selftests.

Quoted 3 lines

run_int_array_no_partial_update() uses spaces for its comment lines while the code uses tabs.

good catch

Quoted 3 lines

reset_vals() has no case for int_0003, so sysctl_test_0013 calls it for nothing. Drop the call or add a case for int_0003.

The TARGET is reset to "". right?

I'm reluctant to do more work on the sysctl.sh file as everything will probably be replaced.

Thx

Best

Quoted 5 lines

Nits aside, the test does what it should:

Thanks!

#14 lore raw

Re: [PATCH v2 4/4] sysctl: Add 0013 to test partially updated vectors

Quoted 10 lines · Joel Granados
Quoted 6 lines · Bradley Morgan

The test covers the parse error, the out of range value and the first value failing. That's the right coverage.

The shellcheck disable should say why. The test functions are only called through the dispatch string, so shellcheck thinks they are unreachable.

I expect to remove this in the new sysctl selftests.

Quoted 1 line
Quoted 9 lines
Quoted 2 lines

run_int_array_no_partial_update() uses spaces for its comment lines while the code uses tabs.

good catch

Quoted 3 lines

reset_vals() has no case for int_0003, so sysctl_test_0013 calls it for nothing. Drop the call or add a case for int_0003.

The TARGET is reset to "". right?

From what I recall! note I review loads of kernel/ files, I'll rant a little below, some of it is related. Heh.

Quoted 12 lines

I'm reluctant to do more work on the sysctl.sh file as everything will probably be replaced.

Thx

Best

Quoted 5 lines

Nits aside, the test does what it should:

Thanks!

RANT:

I've been thinking, I hate clicking on the stupid mailto links on lore just to review a patch, I need to be CCed in most kernel/ patches anyway. I already am, but im mostly a "pity" CC, because I spent time reviewing patch, and like, I ask people all the time to CC me on most kernel/ patches they do, but that's negligible..

I have knowledge On sysctl, id love to wonder why I don't even get_maintainers catch yet. (And if I do, I don't even get CCed! Omg..!

I really hope one day I get either reviewer or get_maintainers CCed so I don't have to go through this headache each and every time I bloody review!

Sorry for that rant, I tend to think out loud. (Or overthink)

Thanks!

maintainer
#15 lore raw
In reply to Joel Granados
Quoted 7 lines · On Fri, 14 Aug 2026 12:41:11 +0200 Joel Granados <[email protected]>…

What?
=====

Stage table->data when writing INT & ULONG ctl_tables. Commit staged data to kernel variable only when all the conversions have succeeded. This is applicable only to variables that represent a vector; paths pertaining to scalers are left unchanged. Notice that partial updates

"scalars"

Quoted 10 lines

can still happen if less than the size of the vector are passed and correctly formatted.

This is the behavior we are protecting against:

  # echo "4 4 1 7" > /proc/sys/kernel/printk
  # echo "1 x" > /proc/sys/kernel/printk
  -bash: echo: write error: Invalid argument
  # cat /proc/sys/kernel/printk
  1 4 1 7    <- the write failed, the first element changed anyway

I like the change.

Quoted 10 lines

Why?
====
Allowing a partial change to a vector after returning from an erroneous proc_handler is just plain wrong. This should be handled within sysctl to avoid users having to do it for themselves [1].

Behavioral Changes
==================
1. A failed write will not update the vector
2. Vector writes can now fail with -ENOMEM

Yeah, this improves Linux.

Quoted 7 lines

Testing
=======
This went through regular sysctl kunit and self test. Also is posted to 0-day.

I always find it difficult to know who wants to receive this. Please let me know if you want to be removed from the Cc/To.

Sashiko said one thing:

	https://sashiko.dev/#/patchset/[email protected]
author maintainer
#16 lore raw
Quoted 11 lines · Andrew Morton
Quoted 7 lines · On Fri, 14 Aug 2026 12:41:11 +0200 Joel Granados <[email protected]>…

What?
=====

Stage table->data when writing INT & ULONG ctl_tables. Commit staged data to kernel variable only when all the conversions have succeeded. This is applicable only to variables that represent a vector; paths pertaining to scalers are left unchanged. Notice that partial updates

"scalars"

Will change in the cover letter (If/when I send the next version). It wont actually show up in upstream as this is just in the cover letter.

Quoted 32 lines
Quoted 11 lines

can still happen if less than the size of the vector are passed and correctly formatted.

This is the behavior we are protecting against:

  # echo "4 4 1 7" > /proc/sys/kernel/printk
  # echo "1 x" > /proc/sys/kernel/printk
  -bash: echo: write error: Invalid argument
  # cat /proc/sys/kernel/printk
  1 4 1 7    <- the write failed, the first element changed anyway

I like the change.

Quoted 10 lines

Why?
====
Allowing a partial change to a vector after returning from an erroneous proc_handler is just plain wrong. This should be handled within sysctl to avoid users having to do it for themselves [1].

Behavioral Changes
==================
1. A failed write will not update the vector
2. Vector writes can now fail with -ENOMEM

Yeah, this improves Linux.

Quoted 5 lines

Testing
=======
This went through regular sysctl kunit and self test. Also is posted to 0-day.

Quoted 5 lines
Quoted 2 lines

I always find it difficult to know who wants to receive this. Please let me know if you want to be removed from the Cc/To.

Sashiko said one thing:

	https://sashiko.dev/#/patchset/[email protected]

The tests that keep on giving :).

I'm already working on a replacement for the sysctl selftests and prefer to leave these as they are and address them in the new version if they persist.

Thx for the feedback

Best

Joel

Reviewed-by Tested-by on the v2 series
#17 lore raw
In reply to Joel Granados

Copy it, only write back once every value converted. That's the right way to do this. Went through the whole series against the tree, notes in the patch replies.

Some nits on the series:
- "miss-formatted" in the subject. mis-formatted, or just malformed.
- akpm's scalars nit still applies.
- Sashiko saw something on this one (akpm linked it).

Otherwise fine by me, the split is clean.

also

Thanks!

author maintainer
#18 lore raw
Quoted 4 lines · Bradley Morgan

Copy it, only write back once every value converted. That's the right way to do this. Went through the whole series against the tree, notes in the patch replies.

Your feedback was useful, but it was riddled with a *lot* of hand waving. Please be succinct and to the point. The previous paragraph is not needed.

Quoted 3 lines

Some nits on the series:
- "miss-formatted" in the subject. mis-formatted, or just malformed.

Note that this comment is missing the why. It is good to know why you want the change

Quoted 2 lines

- akpm's scalars nit still applies.
- Sashiko saw something on this one (akpm linked it).

In my opinion this is just noise. If you see that I have missed a comment, call me out on it. If you have additional information, answer to reviewers mail.

Quoted 8 lines

Otherwise fine by me, the split is clean.

also

How did you test? And what where your results?

Best

#19 lore raw
Quoted 22 lines · Joel Granados
Quoted 4 lines · Bradley Morgan

Copy it, only write back once every value converted. That's the right way to do this. Went through the whole series against the tree, notes in the patch replies.

Your feedback was useful, but it was riddled with a *lot* of hand waving. Please be succinct and to the point. The previous paragraph is not needed.

Quoted 3 lines

Some nits on the series:
- "miss-formatted" in the subject. mis-formatted, or just malformed.

Note that this comment is missing the why. It is good to know why you want the change

Quoted 2 lines

- akpm's scalars nit still applies.
- Sashiko saw something on this one (akpm linked it).

In my opinion this is just noise. If you see that I have missed a comment, call me out on it. If you have additional information, answer to reviewers mail.

Quoted 1 line
Quoted 9 lines
Quoted 7 lines

Otherwise fine by me, the split is clean.

also

How did you test? And what where your results?

Built and booted the latest kernel. Its the summer holidays, I can do all this, it's magical

Quoted 2 lines

Best

Thanks!

author maintainer
#20 lore raw
In reply to Joel Granados
Quoted 9 lines · Joel Granados

What?
=====

Stage table->data when writing INT & ULONG ctl_tables. Commit staged data to kernel variable only when all the conversions have succeeded. This is applicable only to variables that represent a vector; paths pertaining to scalers are left unchanged. Notice that partial updates can still happen if less than the size of the vector are passed and correctly formatted.

... snip ...

Quoted 5 lines

sysctl: Split data conversion and file position handling
sysctl: Reject uint arrays before calling the general proc_vec
sysctl: Disallow partial updates for erroneous sysctl vectors
sysctl: Add 0013 to test partially updated vectors

Quoted 12 lines
 kernel/sysctl.c                          | 237 ++++++++++++++++++++-----------
 tools/testing/selftests/sysctl/sysctl.sh |  60 ++++++++
 2 files changed, 217 insertions(+), 80 deletions(-)

---
base-commit: 4c12287001da60f3c022bb25932aa7a5590fc0b1
change-id: 20260813-lklm-partial_ctlvec-bd8867b70d5c

Best regards,

Signature · 1 line
Joel Granados <[email protected]>

I feel the superficial changes mentioned in the review (up until now) do not merit me sending a V3. The modified tree is here [1].

Best

[1] https://git.kernel.org/pub/scm/linux/kernel/git/joel.granados/linux.git/log/?h=jag/partial_ctlvec