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

tools: iio: iio_generic_buffer: Fix some integer type and calculation

In function size_from_channelarray(), the return value 'bytes' is defined
as int type. However, the calcution of 'bytes' in this function is designed
to use the unsigned int type. So it is necessary to change 'bytes' type to
unsigned int to avoid integer overflow.

The size_from_channelarray() is called in main() function, its return value
is directly multipled by 'buf_len' and then used as the malloc() parameter.
The 'buf_len' is completely controllable by user, thus a multiplication
overflow may occur here. This could allocate an unexpected small area.

Signed-off-by: Chenyuan Mi <michenyuan@huawei.com>
Link: https://lore.kernel.org/r/20230725092407.62545-1-michenyuan@huawei.com
Signed-off-by: Jonathan Cameron <Jonathan.Cameron@huawei.com>

authored by

Chenyuan Mi and committed by
Jonathan Cameron
49d73631 9afc8c6d

+13 -4
+13 -4
tools/iio/iio_generic_buffer.c
··· 51 51 * Has the side effect of filling the channels[i].location values used 52 52 * in processing the buffer output. 53 53 **/ 54 - static int size_from_channelarray(struct iio_channel_info *channels, int num_channels) 54 + static unsigned int size_from_channelarray(struct iio_channel_info *channels, int num_channels) 55 55 { 56 - int bytes = 0; 56 + unsigned int bytes = 0; 57 57 int i = 0; 58 58 59 59 while (i < num_channels) { ··· 348 348 ssize_t read_size; 349 349 int dev_num = -1, trig_num = -1; 350 350 char *buffer_access = NULL; 351 - int scan_size; 351 + unsigned int scan_size; 352 352 int noevents = 0; 353 353 int notrigger = 0; 354 354 char *dummy; ··· 674 674 } 675 675 676 676 scan_size = size_from_channelarray(channels, num_channels); 677 - data = malloc(scan_size * buf_len); 677 + 678 + size_t total_buf_len = scan_size * buf_len; 679 + 680 + if (scan_size > 0 && total_buf_len / scan_size != buf_len) { 681 + ret = -EFAULT; 682 + perror("Integer overflow happened when calculate scan_size * buf_len"); 683 + goto error; 684 + } 685 + 686 + data = malloc(total_buf_len); 678 687 if (!data) { 679 688 ret = -ENOMEM; 680 689 goto error;