find inode number of a file using C code

好久不见. 提交于 2020-01-02 03:32:04

问题


I have program, say name giverootAccess. This program can receive a file name in the current directory (where giverootAccess resides) as a command-line argument. Then the file will get the root access. The file can be an executable or a shell script.

Now the problem is that, A hacker can get root access by redirecting the request to bash. I want to restrict a user to give root access only on those files inside the directory where giverootAccess resides. hacker can redirect file name to unwanted programs and hence get the root permission.

So I need a mechanism to uniquely identify a file, not by its name (as it can be mimicked and hacked). Is inode can be used for this purpose?

My plan is, when the application installs, I will store the inodes of all the files in the directory and whenever somebody runs the giverootAccess with a file name, I will check the file name and its inodes are matching with stored one. If matching, then only giverootAccess program actually give root access to the file.

Do you have any other simple mechanism to do this job ?


回答1:


You can use file descriptor to get the inode number, use this code :

int fd, inode;  
fd = open("/path/to/your/file", YOUR_DESIRED_OPEN_MODE);

if (fd < 0) {  
    // some error occurred while opening the file  
    // use [perror("Error opening the file");] to get error description
}  

struct stat file_stat;  
int ret;  
ret = fstat (fd, &file_stat);  
if (ret < 0) {  
   // error getting file stat  
} 

inode = file_stat.st_ino;  // inode now contains inode number of the file with descriptor fd  

// Use your inode number
// ...

fstat is a system call that is used to determine information about a file based on its file descriptor. It is described here

stat is a structure that contains meta information of a file and is described here
to use stat structure and fstat system call you should add #include <sys/stat.h> to your code.




回答2:


You can find the inode number of a file using stat: http://linux.die.net/man/2/stat




回答3:


You can find the inode number using the stat() system call. However, if you are using a non ext system like FAT32 and NTFS, the inode table will dynamically generated. Which means that the inode numbers may change and the application should not rely on it.



来源:https://stackoverflow.com/questions/9480568/find-inode-number-of-a-file-using-c-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!