Buffer size checking for scanf* functions

Adhemerval Zanella adhemerval.zanella@linaro.org
Tue Jul 5 12:39:09 GMT 2022



> On 5 Jul 2022, at 04:31, Yair Lenga via Libc-help <libc-help@sourceware.org> wrote:
> 
> Hi,
> 
> Looking for feedback on the following age-old scanf problem: I'm trying to
> perform a "safe' scanf, which will avoid buffer overflow.
> 
> #define XSIZE 30
> char x[XSIZE] ;
> sscanf(input, "%29s", x) ;

You can adjust to use the old stringify macro trick instead:

--
$ cat<<EOF>test.c
#include <stdio.h>
int main (int argc, char *argv[])
{
#define XLEN 8
  char x[XLEN+1];
#define XSTRINPUT(size) STRINPUT (size)
#define STRINPUT(size)  "%" #size "s"
  sscanf (argv[1], XSTRINPUT (XLEN), x);

  printf ("x=%s\n", x);
  return 0;
}
EOF
$ gcc -Wall test.c -o test
$ ./test 1234567890
x=12345678
--

It has some limitations where you can’t evaluate neither arithmetic
operations on the macro (for instance XSTRINPTU (XLEN - 1)) nor use
compile directives like ’sizeof’.

> 
> With the common pitfall that anytime the size of X is changed, the format
> string MUST to be modified. One common approach, with glibc, is to use the
> 'm' modifier, switch x to char **x. However, this require code changes, and
> is not practical with my existing code base.
> 
> My question: is there any extension to allow scanf to take an extra
> argument (similar to the scanf_s proposal) - specifying the sizeof any
> string arguments ?
> sscanf(input, "%S", x, sizeof(x)) ;     // The 'S' require adding sizeof
> parameter ?

Currently glibc only provides the %m that accepts any input size and you 
can also use the a maximum field width (something like %128m). 

> 
> If there is no such extension - how hard it will be to implement. I know
> possible to define custom conversions for printf, I could not find anything
> for scanf. IF this will be built into 'glibc', there IF it will be embedded
> into the gcc format checks (2 big IFs), it can reduce the problems I (and I
> believe many other developers) face when using those functions.
> 

The glibc does not support hooks for scanf and I don’t think we will even
will, the printf hooks itself has some drawbacks (MT-safeness, etc.).  Also
scan_s and similar ‘enhanced’ functions from TR-24731 have not been widely 
implemented mainly because they do not actually improve much. Carlos and
Martim, both GNU developers, wrote a paper discussing the problems with
these interfaces [1].

In the end scanf family functions are just a really clunky interface with
a lot of pitfalls and I would advice you just rewrite it either avoid them
it or use the ‘%m’ extension otherwise.

[1] https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1967.htm


More information about the Libc-help mailing list