您的位置:首页 > 运维架构 > Linux

Linux普通用户操作root资源

2015-12-15 17:36 459 查看
了解了Linux下文件的SUID和SGID后我们就可以解释为什么普通用户也能调用/usr/bin/passwd命令来修改/etc/passwd了。

[root@RD224 uid_gid]# ll /usr/bin/passwd /etc/passwd
-rw-r--r--  1 root root  1738 Dec 10 08:40 /etc/passwd
-r-s--x--x  1 root root 27728 Jun 17  2005 /usr/bin/passwd
如上/etc/passwd文件只有root用户才有写权限,其他用户只有读权限,但普通用户却可以passwd修改自己的密码。原因就在/usr/bin/passwd的属性s,见我另一篇博文Linux uid gid

一般情况下,如果是一个可执行文件, 那么在执行时, 一般该文件只拥有调用该文件的用户具有的权限. 而setuid, setgid 可以来改变这种设置。比如我们自己开发的一个程序,里头有用到root才会操控的资源,比如让PC重启。我们可以在普通用户下开发编译,然后切到root用户下将可执行文件属主改为root,将其权限加上SUID,这样切到普通用户下运行这个程序就可以得到我们想要的功能了。

/* # ScriptName: transeuid.c
# Author: JH Gao <gaopenghigh@gmail.com>
# Create Date: 2012-06-05
# Function: transmit euid and egid to other scripts
# since shell/python/... scripts can't get suid permission in Linux
# usage: transeuid xxx.sh par1 par2 par3
# xxx.sh will get the euid and egid from transeuid
# ******************************************************************** */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define BUFFSIZE 1024

/*
* usually euid is the uid who run the program
* but when stick is setted to the program
* euid is the uid or the program's owner
*/
int main(int argc, char *argv[]) {
char *cmd = malloc(BUFFSIZE);
// set uid and gid to euid and egid
setuid(geteuid());
setgid(getegid());
cmd = argv[1];
int i = 0;
for(i = 0;i < argc - 1;i++) {
argv[i] = argv[i+1];
}
argv[argc-1] = NULL
// search $PATH find this cmd and run it with pars:argv
if (execvp(cmd, argv)) {
printf("error");
free(cmd);
exit(1);
}
free(cmd);
}
编译这个程序,在给这个程序设置希望取得的用户,再设置suid,然后就可以用这个用户的权限执行脚本或命令了:

$ gcc -t transeuid transeuid.c
$ sudo chown root transeuid
$ sudo chmod +s transeuid
$ ./transeuid ls /root /home详见Linux下获取root权限的c程序
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  linux