James wrote:
> # The second way is to close file descriptor 2, and re-open another
> # file/device with that number within your program.
>
> will C let you do that? cos what'd happen if you closed stdout and
> forgot to re-open one and then did a printf().
If and when printf() calls write() (remember that printf() is
buffered, and won't always call write() straightaway), write will
indicate an error (EBADF).
> And you can't open random file descriptors
No, but you can use open() then dup2() to use a specific descriptor.
> (although if you just closed fd 2 a call to open() should use
> that...)
Yep.
This can be a security issue. Consider the following sequence of
events:
Someone executes a setuid program with one of the descriptors (e.g.
stderr) closed, e.g. with
setuidprog ... 2>&-
The program then open()s some file for writing (specifically, an
important system file which has restricted permissions). This file
will be associated with descriptor 2. For whatever reason (e.g.
invalid user-supplied data), the program writes an error message to
stderr (either directly, or by calling some library function which
generates convenient error messages upon failure).
The net result is that the program has written random junk (or, if the
error message includes some user-supplied data, specific data) to a
privileged file.
I recall there being some talk about adding a check to the Linux
kernel so that setuid/setgid binaries will refuse to run if any of the
standard descriptors are initially closed. I don't know if this has
been done yet.
--
Glynn Clements <[EMAIL PROTECTED]>