gpt4 book ai didi

c - 在c中使用所有者的文件权限打开文件

转载 作者:太空宇宙 更新时间:2023-11-04 08:47:28 25 4
gpt4 key购买 nike

我需要用 C 编写一个程序来打开一个文本文件并打印内容。但是,它需要能够读取和打印只有所有者有权读取的文件,即使其他人运行该程序也是如此。我不知道如何获得所有者的读取权限。

我的问题措辞不佳,让我更具体一点。我需要制作两个程序,一个只正常读取文本文件,另一个可以读取具有所有者权限的文本文件。

这里是普通的文件读取程序,read_unprivileged.c

#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>

int main(int argc, char *argv[])
{
FILE *fp;
char ch;
char *filename = argv[1];

fp = fopen(filename, "r"); //lets you read file

if(fp == NULL){
printf("File is null!");
}

while( ( ch = fgetc(fp) ) != EOF ){
printf("%c",ch);
}
fclose(fp);
return 0;
}

这里是应该能够读取具有所有者权限的文件(除了突出显示的行之外,其他都是一样的),read_privileged.c

#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>

int main(int argc, char *argv[])
{
FILE *fp;
char ch;
char *filename = argv[1];

setreuid(geteuid(), getuid());
fp = fopen(filename, "r"); //lets you read file
setreuid(geteuid(), getuid());

if(fp == NULL){
printf("File is null!");
}

while( ( ch = fgetc(fp) ) != EOF ){
printf("%c",ch);
}
fclose(fp);
return 0;
}

所以有问题的文件只能由所有者(我)读取。

-rwx------ secret.txt

当我(所有者)调用它时,这两个程序都可以读取文件,正如它们应该的那样。所以我这样做: chmod 4755 read_privileged.c chmod 4755 read_unprivileged.c

当其中任何一个编译成 a.out 时,a.out 文件都没有 userid 位。

-rwxr-xr-x a.out

当我以另一个用户身份运行编译后的 a.out 时,两者都不起作用。但是,如果我这样做:

chmod 4755 a.out

它们都有效,我想这违背了目的(因为 read_unprivileged 有效但不应该)。我不明白为什么可执行文件会失去特权,以及为什么设置setreuid(geteuid(), getuid());不起作用。

最佳答案

在 unix 系统上,生成的可执行文件需要设置 s 位。这可以由 root 用户或拥有该文件的用户完成(他还必须拥有可执行文件)。

如果 root 和文件所有者都没有协助您执行此操作,则您无权读取该文件。

让我假设您的程序文件名为 readit 并且已由文件所有者编译。文件所有者现在必须执行 chmod +s readit。这样做之后,启动程序(由任何用户)会将有效用户 ID 设置为文件所有者的用户 ID。

不过要小心。设置了 s 位的程序是入侵尝试的热门目标。

关于c - 在c中使用所有者的文件权限打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21151881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com