frno7 / linux

Linux 2.2, 2.6, 3.x, 4.x and 5.x kernels for the PlayStation 2.
Other
84 stars 5 forks source link

sscanf: Fix integer overflow with sscanf field width #31

Closed frno7 closed 2 years ago

frno7 commented 4 years ago

Fix 53809751ac230a3611b5cdd375f3389f3207d471 where sscanf overflows integers with simple strings such as dates. As an example, consider

        int r = sscanf("20190523123456", "%4d%2d%2d%2d%2d%2d",
                &year, &month, &day,
                &hour, &minute, &second);

        printk("%d %04d-%02d-%2d %02d:%02d:%02d\n",
                r,
                year, month, day,
                hour, minute, second);

On a 32-bit machine this prints

        6 0000-05-23 12:34:56

where the year is zero, and not 2019 as expected. The reason is that sscanf attempts to read 20190523123456 as a whole integer, and then divide it with 1010 to obtain 2019, which obviously fails. Of course, 64-bit machines fail similarly on longer numerical strings.

The idea for a fix is to have a variant of _parse_integer() called _parse_integer_end(), with the ability to stop consuming digits. The functions

        simple_{strtol,strtoll,strtoul,strtoull}()

now have the corresponding

        sscanf_{strtol,strtoll,strtoul,strtoull}()

taking a field width into account. Perhaps such a fix could be a starting-point to clean-up the integer parsers? Also, it seems to be a good idea to make a test suite for sscanf.

frno7 commented 4 years ago

Commit d3638dc253d3afa321a318eb5d1e91ad3cb0f720 is a provisional fix. Post to the kernel mailing list. Reply from Jan Beulich.

frno7 commented 4 years ago

These are the affected lines when reading the ROMVER file:

https://github.com/frno7/linux/blob/044d39c3dc12690ede9f7c42243da3047eaa8310/arch/mips/ps2/rom.c#L381-L384

frno7 commented 2 years ago

This bug has been fixed in commit 900fdc4573766dd43b847b4f54bd4a1ee2bc7360.