Hacking - The Art of Exploitation, 2nd Edition

(Romina) #1
Programming 83

strcpy(buffer, argv[1]); // Copy into buffer.


printf("[DEBUG] buffer @ %p: \'%s\'\n", buffer, buffer);
printf("[DEBUG] datafile @ %p: \'%s\'\n", datafile, datafile);


strncat(buffer, "\n", 1); // Add a newline on the end.


// Opening file
fd = open(datafile, O_WRONLY|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR);
if(fd == -1)
fatal("in main() while opening file");
printf("[DEBUG] file descriptor is %d\n", fd);
// Writing data
if(write(fd, buffer, strlen(buffer)) == -1)
fatal("in main() while writing buffer to file");
// Closing file
if(close(fd) == -1)
fatal("in main() while closing file");


printf("Note has been saved.\n");
free(buffer);
free(datafile);
}


// A function to display an error message and then exit
void fatal(char *message) {
char error_message[100];


strcpy(error_message, "[!!] Fatal Error ");
strncat(error_message, message, 83);
perror(error_message);
exit(-1);
}


// An error-checked malloc() wrapper function
void ec_malloc(unsigned int size) {
void
ptr;
ptr = malloc(size);
if(ptr == NULL)
fatal("in ec_malloc() on memory allocation");
return ptr;
}


Besides the strange-looking flags used in the open() function, most of this


code should be readable. There are also a few standard functions that we


haven’t used before. The strlen() function accepts a string and returns its


length. It’s used in combination with the write() function, since it needs to


know how many bytes to write. The perror() function is short for print error and is


used in fatal() to print an additional error message (if it exists) before exiting.


reader@hacking:~/booksrc $ gcc -o simplenote simplenote.c
reader@hacking:~/booksrc $ ./simplenote
Usage: ./simplenote <data to add to /tmp/notes>

Free download pdf