Search code examples
buffer-overflowstack-overflow

Why does fgets fail when I use 0 as FILE* to read from stdin in rop chain?


I am making a rop chain to call fgets with stdin as input to be able to make a basic stackoverflow.

But my issue is that when I call fgets with 0 as third argument (for stdin) fgets crash at

 <fgets+49>       mov    ecx, DWORD PTR [esi]

where esi is the third argument I control, why does it crash ? With 0 it should not try to read the content of it and just read from stdin, no ?

The useful part of my ropchain looks like :

fgets.plt
pop_pop_pop_ret
buffer
0x500
0

I have no idea why it doesn't work the call made is something like :

_IO_fgets(buf=0xf7f77000, n=0x500, fp=0x0)

Thanks


Solution

  • You're confusing stdio files (FILE*, a high-level interface to files) and file descriptors (a number). fgets is an stdio function and takes a FILE* as an argument. Standard input is file descriptor 0, but stdin in the stdio interface. Likewise standard output is 1 and stdout, and standard error is 2 and stderr.

    Passing 0 (or any small integer) where fgets expects a FILE* causes the program to attempt to dereference this value as an address, which fails (for 0, which is a null pointer, it fails with a segmentation fault; depending on the architecture, values that aren't a multiple of the word size may fail with a bus error or an illegal instruction).