Skip to content

Commit 6787d91

Browse files
tohojoAlexei Starovoitov
authored andcommitted
bpf: Fix hashtab overflow check on 32-bit arches
The hashtab code relies on roundup_pow_of_two() to compute the number of hash buckets, and contains an overflow check by checking if the resulting value is 0. However, on 32-bit arches, the roundup code itself can overflow by doing a 32-bit left-shift of an unsigned long value, which is undefined behaviour, so it is not guaranteed to truncate neatly. This was triggered by syzbot on the DEVMAP_HASH type, which contains the same check, copied from the hashtab code. So apply the same fix to hashtab, by moving the overflow check to before the roundup. Fixes: daaf427 ("bpf: fix arraymap NULL deref and missing overflow and zero size checks") Signed-off-by: Toke Høiland-Jørgensen <[email protected]> Message-ID: <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]>
1 parent 281d464 commit 6787d91

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

kernel/bpf/hashtab.c

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -499,7 +499,13 @@ static struct bpf_map *htab_map_alloc(union bpf_attr *attr)
499499
num_possible_cpus());
500500
}
501501

502-
/* hash table size must be power of 2 */
502+
/* hash table size must be power of 2; roundup_pow_of_two() can overflow
503+
* into UB on 32-bit arches, so check that first
504+
*/
505+
err = -E2BIG;
506+
if (htab->map.max_entries > 1UL << 31)
507+
goto free_htab;
508+
503509
htab->n_buckets = roundup_pow_of_two(htab->map.max_entries);
504510

505511
htab->elem_size = sizeof(struct htab_elem) +
@@ -509,10 +515,8 @@ static struct bpf_map *htab_map_alloc(union bpf_attr *attr)
509515
else
510516
htab->elem_size += round_up(htab->map.value_size, 8);
511517

512-
err = -E2BIG;
513-
/* prevent zero size kmalloc and check for u32 overflow */
514-
if (htab->n_buckets == 0 ||
515-
htab->n_buckets > U32_MAX / sizeof(struct bucket))
518+
/* check for u32 overflow */
519+
if (htab->n_buckets > U32_MAX / sizeof(struct bucket))
516520
goto free_htab;
517521

518522
err = bpf_map_init_elem_count(&htab->map);

0 commit comments

Comments
 (0)