Skip to content

Commit 393397f

Browse files
Hou TaoAlexei Starovoitov
authored andcommitted
bpf: Check the validity of nr_words in bpf_iter_bits_new()
Check the validity of nr_words in bpf_iter_bits_new(). Without this check, when multiplication overflow occurs for nr_bits (e.g., when nr_words = 0x0400-0001, nr_bits becomes 64), stack corruption may occur due to bpf_probe_read_kernel_common(..., nr_bytes = 0x2000-0008). Fix it by limiting the maximum value of nr_words to 511. The value is derived from the current implementation of BPF memory allocator. To ensure compatibility if the BPF memory allocator's size limitation changes in the future, use the helper bpf_mem_alloc_check_size() to check whether nr_bytes is too larger. And return -E2BIG instead of -ENOMEM for oversized nr_bytes. Fixes: 4665415 ("bpf: Add bits iterator") Signed-off-by: Hou Tao <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Alexei Starovoitov <[email protected]>
1 parent 62a898b commit 393397f

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

kernel/bpf/helpers.c

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2851,6 +2851,8 @@ struct bpf_iter_bits {
28512851
__u64 __opaque[2];
28522852
} __aligned(8);
28532853

2854+
#define BITS_ITER_NR_WORDS_MAX 511
2855+
28542856
struct bpf_iter_bits_kern {
28552857
union {
28562858
unsigned long *bits;
@@ -2865,7 +2867,8 @@ struct bpf_iter_bits_kern {
28652867
* @it: The new bpf_iter_bits to be created
28662868
* @unsafe_ptr__ign: A pointer pointing to a memory area to be iterated over
28672869
* @nr_words: The size of the specified memory area, measured in 8-byte units.
2868-
* Due to the limitation of memalloc, it can't be greater than 512.
2870+
* The maximum value of @nr_words is @BITS_ITER_NR_WORDS_MAX. This limit may be
2871+
* further reduced by the BPF memory allocator implementation.
28692872
*
28702873
* This function initializes a new bpf_iter_bits structure for iterating over
28712874
* a memory area which is specified by the @unsafe_ptr__ign and @nr_words. It
@@ -2892,6 +2895,8 @@ bpf_iter_bits_new(struct bpf_iter_bits *it, const u64 *unsafe_ptr__ign, u32 nr_w
28922895

28932896
if (!unsafe_ptr__ign || !nr_words)
28942897
return -EINVAL;
2898+
if (nr_words > BITS_ITER_NR_WORDS_MAX)
2899+
return -E2BIG;
28952900

28962901
/* Optimization for u64 mask */
28972902
if (nr_bits == 64) {
@@ -2903,6 +2908,9 @@ bpf_iter_bits_new(struct bpf_iter_bits *it, const u64 *unsafe_ptr__ign, u32 nr_w
29032908
return 0;
29042909
}
29052910

2911+
if (bpf_mem_alloc_check_size(false, nr_bytes))
2912+
return -E2BIG;
2913+
29062914
/* Fallback to memalloc */
29072915
kit->bits = bpf_mem_alloc(&bpf_global_ma, nr_bytes);
29082916
if (!kit->bits)

0 commit comments

Comments
 (0)