next up previous
Next: Double check strings used Up: Setuid applications Previous: Do not trust argv[0]

Do not trust file descriptors 0, 1, 2

Here's a bug that affected SVGAlib based applications. SVGAlib used to be a fairly popular library for doing graphics on Linux without involving the slow X protocol (slow in the context of 50 MHz i486 processors...). For example, the Linux port of the game DOOM used this library. Nowadays, SVGAlib has faded into oblivion, and the world is a better place.

Applications linked against SVGAlib had to be setuid root, because the graphics operations were done via direct interaction with the graphics hardware.

Thus, the very first thing SVGAlib did was opening /dev/kmem, a special device file that gives the application direct access to all kernel memory. Afterwards, it dropped root privilege immediately. This is as safe as you can get with this type of application, except for one little glitch.

The interesting part was when you closed file descriptor 2 before starting an SVGAlib application. In this case, when SVGAlib opened /dev/kmem, the file descriptor for this file would be 2, which is normally attached to standard error output.

Any subsequent error message printed through stderr would be written directly into kernel memory, because stderr is always attached to file descriptor 2.

You should therefore make it a habit to ensure that file descriptors 0, 1, and 2 are valid, right at the start of your main procedure and before you do anything else. One common approach is:

    while (1) {
        int     fd;

        fd = open("/dev/null", O_RDWR);
        if (fd < 0)
            exit(EX_OSERR);
        if (fd > 2) {
            close(fd);
            break;
        }
    }


next up previous
Next: Double check strings used Up: Setuid applications Previous: Do not trust argv[0]
Olaf Kirch 2002-01-16