使用 C 代码查找文件的 inode 编号 [英] find inode number of a file using C code

查看:62
本文介绍了使用 C 代码查找文件的 inode 编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有程序,说名字 giverootAccess.该程序可以接收当前目录(giverootAccess 所在的目录)中的文件名作为命令行参数.然后该文件将获得根访问权限.该文件可以是可执行文件或 shell 脚本.

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.

现在的问题是,黑客可以通过将请求重定向到 bash 来获得 root 访问权限.我想限制用户仅对 giverootAccess 所在目录中的那些文件授予 root 访问权限.黑客可以将文件名重定向到不需要的程序,从而获得 root 权限.

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.

所以我需要一种机制来唯一标识一个文件,而不是通过它的名称(因为它可以被模仿和黑客攻击).inode 是否可以用于此目的?

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?

我的计划是,当应用程序安装时,我会将所有文件的 inode 存储在目录中,每当有人使用文件名运行 giverootAccess 时,我将检查文件名及其 inode 是否与存储的 inode 匹配.如果匹配,则只有 giverootAccess 程序实际授予对文件的 root 访问权限.

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 ?

推荐答案

可以使用文件描述符来获取 inode 编号,使用此代码:

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 是一个系统调用,用于根据文件描述符确定有关文件的信息.这里

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

stat 是一个包含文件元信息的结构,被描述为 这里
要使用 stat 结构和 fstat 系统调用,您应该将 #include <sys/stat.h> 添加到您的代码中.

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.

这篇关于使用 C 代码查找文件的 inode 编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆