Good morning,
I find out a strange and bad beaviour in functions from scanf() family when reading one-byte int variable in MinGW, Cygwin and Borland/Embarcadero C environments (on Windows, on Linux this doesn't happen). This bug is corelated with MSVCRT library which isn't written in C99 standard (it's written in C89 i think).
So, the point is, when you're reading one byte using scanf() function, AND you are using %hhu format specifier, you have Integer Overflow bug in your code, because MinGW links to old MSVCRT (C89 version) even if you compile with -std=c99 parameter.
This works, because scanf() in old MSVCRT library doesn't know "h" format specifier. BUT! The problem is, that scanf try to interpret format specifier anyway, omits unsupported "h" specifier and it's loading full integer ("u") to memory (it should omit not supported part of format - whole "%hhu" format part, not just only "h"). The C99 specification says on 361 page: "If a conversion specification is invalid, the behavior is undefined." - but it is WRONG, because the behaviour SHOULD BE DEFINED AS OMITING THE WHOLE UNSUPPORTED PART OF FORMAT (not only single specifier, but whole part).
In exploit (in attachment), compiler doesn't even display warnings (event if you compile program with -std=c99 and -Wextra parameters). I compile using that command:
gcc main.c -o main.exe -Wextra
Here is my article about this topic (in Polish language, english version is writting now):
https://lukashp.pl/Hacking/Hack-Artykuly/Odkrycie_Integer_overflow_w_funkcjach_z_rodziny_scanf_w_MinGW_Cygwin_Embarcadero_C_i_innych_srodowiskach_przy_wczytywaniu_liczby_do_char_a
Last edit: Lukas Wyporek 2017-03-05
As you note,
scanf()is provided by MSVCRT.DLL ... a Microsoft product. You are correct that it isn't C99, (because, in reality, Microsoft have never supported that).Read the MSDN documentation; that's what you must code to. This is a "won't fix", because the reality is that it's a "can't fix" -- the implementation isn't open source, or free software; it's a Microsoft product which we cannot alter, (unless someone has sufficient incentive to provide a complete replacement implementation, and since
scanf()is such an appallingly dreadful choice of API anyway, few have).Hi, thank you for your time.
But MinGW can display warnings about this as it does with other problems. It should be resolved that way when we can't fix MSVCRT.DLL library.
Only to the extent that upstream GCC supports it. You need to direct a request for that to the GCC maintainers ... not to us.