Question

I found this source in Jon Erickson's book, Hacking: The Art of Exploitation,

userid = getuid(); // get the real user ID
// Writing data
if(write(fd, &userid, 4) == -1)  // write user ID before note data
    fatal("in main() while writing userid to file");
write(fd, "\n", 1); // terminate line

I tried to compile this code, and found that on the file I write, userid (which is what I write in the code above) is not right; they just wrote strange character (I think is not important to write it here). So the problem is I am trying to pass an int to a function which required char *, because of that the result on file I want to write is false.

So this is a bug, right?

Was it helpful?

Solution

The write() function expects a void * for its buffer; it writes arbitrary binary data. If you need conversion to string, use printf().

You don't show the declaration of userid, but the write() line should be written as:

if (write(fd, &userid, sizeof(userid)) != sizeof(userid))

This will detect short writes (unlikely to be a problem for an integer type) and other problems, and works correctly regardless of the type of userid. The original version of the line is arguably buggy, therefore. Otherwise, the bug seems to be in your expectations rather than the code per se.

OTHER TIPS

No, it's not a bug, rather it's a misunderstanding on your part. The write call will just write what's in memory, the binary representation. You would need something like fprintf to get a readable version.

For example, the binary representation of 7 may be the four bytes 0, 0, 0 and 7, which are unlikely to look like the textual representation, a single byte 55 (assuming ASCII).

It's also a bad idea to hardcode type lengths like 4 for an integer since that's not portable. Better would be to use something like sizeof(userid).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top