Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

pid: Replace struct pid 1-element array with flex-array

For pid namespaces, struct pid uses a dynamically sized array member,
"numbers". This was implemented using the ancient 1-element fake
flexible array, which has been deprecated for decades.

Replace it with a C99 flexible array, refactor the array size
calculations to use struct_size(), and address elements via indexes.
Note that the static initializer (which defines a single element) works
as-is, and requires no special handling.

Without this, CONFIG_UBSAN_BOUNDS (and potentially
CONFIG_FORTIFY_SOURCE) will trigger bounds checks:

https://lore.kernel.org/lkml/20230517-bushaltestelle-super-e223978c1ba6@brauner

Cc: Christian Brauner <brauner@kernel.org>
Cc: Jan Kara <jack@suse.cz>
Cc: Jeff Xu <jeffxu@google.com>
Cc: Andreas Gruenbacher <agruenba@redhat.com>
Cc: Daniel Verkamp <dverkamp@chromium.org>
Cc: "Paul E. McKenney" <paulmck@kernel.org>
Cc: Jeff Xu <jeffxu@google.com>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Boqun Feng <boqun.feng@gmail.com>
Cc: Luis Chamberlain <mcgrof@kernel.org>
Cc: Frederic Weisbecker <frederic@kernel.org>
Reported-by: syzbot+ac3b41786a2d0565b6d5@syzkaller.appspotmail.com
[brauner: dropped unrelated changes and remove 0 with NULL cast]
Signed-off-by: Kees Cook <keescook@chromium.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>

authored by

Kees Cook and committed by
Linus Torvalds
b69f0aeb 112e7e21

+7 -4
+1 -1
include/linux/pid.h
··· 67 67 /* wait queue for pidfd notifications */ 68 68 wait_queue_head_t wait_pidfd; 69 69 struct rcu_head rcu; 70 - struct upid numbers[1]; 70 + struct upid numbers[]; 71 71 }; 72 72 73 73 extern struct pid init_struct_pid;
+5 -2
kernel/pid.c
··· 656 656 657 657 idr_init(&init_pid_ns.idr); 658 658 659 - init_pid_ns.pid_cachep = KMEM_CACHE(pid, 660 - SLAB_HWCACHE_ALIGN | SLAB_PANIC | SLAB_ACCOUNT); 659 + init_pid_ns.pid_cachep = kmem_cache_create("pid", 660 + struct_size((struct pid *)NULL, numbers, 1), 661 + __alignof__(struct pid), 662 + SLAB_HWCACHE_ALIGN | SLAB_PANIC | SLAB_ACCOUNT, 663 + NULL); 661 664 } 662 665 663 666 static struct file *__pidfd_fget(struct task_struct *task, int fd)
+1 -1
kernel/pid_namespace.c
··· 48 48 return kc; 49 49 50 50 snprintf(name, sizeof(name), "pid_%u", level + 1); 51 - len = sizeof(struct pid) + level * sizeof(struct upid); 51 + len = struct_size((struct pid *)NULL, numbers, level + 1); 52 52 mutex_lock(&pid_caches_mutex); 53 53 /* Name collision forces to do allocation under mutex. */ 54 54 if (!*pkc)