Hacking: The Art of Exploitation 读书笔记(二)C文件I/O

来源:互联网 发布:手机淘宝一排三个图片 编辑:程序博客网 时间:2024/04/30 11:39
File descriptor:

fd = open( ‘file’, access_mode, permissions)write( fd, buffer, strlen(buffer) )read( fd, &buffer, length )close( fd )lseek( fd, length* -1, SEEK_CUR ): move the read position forward from the current position by length * -1


fcntl.h: access mode
O_RDONLY: read
O_WRONLY: write
O_RDWR: read&write

O_APPEND: write data at the end of file
O_TRUNC: if exits, truncate the file to 0 length
O_CREAT: create if it doesn’t exist

sys/stat.h: file permissions for newly created file
S_IRUSR 
S_IWUSR
S_IXUSR: execute
S_IRGRP
S_IWGRP
S_IXGRP
S_IROTH: other
S_IWOTH
S_IXOTH

reader@hacking:~/booksrc $ ls -l /etc/passwd simplenote*
-rw-r--r-- 1 root root         1424 2007-09-06 09:45 /etc/passwd
-rwxr-xr-x 1 reader reader 8457 2007-09-07 02:51 simplenote
-rw------- 1 reader reader 1872 2007-09-07 02:51 simplenote.c

First, the user read/write/execute permissions are displayed, using r for read, w for write, x for execute, and - for off. The next three characters display the group permissions, and the last three characters are for the other permissions.

If every bit is unique: bit OR = add
chmod 731 = (4|2|1) (2|1) (1)
chmod 731 = (4+2+1) (2+1) (1)


代码示例:
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <fcntl.h>#include <sys/stat.h>void usage(char *prog_name, char *filename){        printf("Usage: %s <data to add to %s>\n", prog_name, filename);        exit(0);}void fatale(char *);void *ec_malloc(unsigned int size);int main(int argc, char *argv[]){        int fd;        char *buffer, *datafile;        buffer = (char *)ec_malloc(100);        datafile = (char *)ec_malloc(20);        strcpy(datafile, "/tmp/notes");        if(argc<2)                usage(argv[0], datafile);        strcpy(buffer, argv[1]);        printf("[DEBUG] buffer   @ %p: \'%s\'\n", buffer, buffer);        printf("[DEBUG] datafile @ %p: \'%S\'\n", datafile, datafile);        strncat(buffer, "\n", 1);        // opening        fd = open(datafile, O_WRONLY|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR);        if(close(fd) == -1)                fatal("in main() while closing file");        printf("Note has been saved.\n");        free(buffer);        free(datafile);}void fatal(char *message){        char error_message[100];        strcpy(error_message, "[!!]Fatal Error");        strncat(error_message, message, 83);        perror(error_message);        exit(-1);}void *ec_malloc(unsigned int size){        void *ptr;        ptr = malloc(size);        if(ptr == NULL)                fatal("in ec_malloc on memory allocation");        return ptr;}


0 0