函数名 setuid - set user identity(设置用户ID)
#include <sys/types.h>
#include <unistd.h>
函数 int setuid(uid_t uid);
描述 setuid() sets the effective user ID of the calling process. If the effective UID of the caller is root, the real UID and saved set-user-ID
返回值 On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
说明:
只有root用户才能调用成功setuid()函数来设置执行目前进程的用户ID,那么当root用户将调用setuid()成功后,此进程的用户ID不再是root用户的识别码,此后,再调用此函数就会失败。(举个例子:就好像只有有媳妇的人(具有root权限)的人才有机会休掉自己的老婆,成为单身,那么假设你休掉老婆后你再想休掉老婆是不可能的,因为你没老婆了。).
如果只是想暂时丢弃root权限稍后还想重新获取root权限,那么必须调用seteuid()函数。
给段代码:
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<sys/types.h> void Show_Uid() { printf("The UID is [%d] \n",getuid()); } int main(void) { int uid = 5000; Show_Uid(); //调用setuid之前查看UID if(setuid(uid) < 0) perror("set UID error"); Show_Uid(); //设置UID之后 if(setuid(2000) < 0) //再次调用setuid设置UID perror("set UID error"); Show_Uid(); //设置UID之后 return 0; }
用root权限执行
real uid : 0
ffective uid : 0
real uid : 5000
ffective uid : 5000
setuid error: Operation not permitted //因为上边将用户ID设置成5000,虽然以root权限运行,但是该进程的UID已经为5000,所以执行失败
real uid : 5000
ffective uid : 5000
普通用户执行
real uid : 1000
ffective uid : 1000
setuid error: Operation not permitted
real uid : 1000
ffective uid : 1000
setuid error: Operation not permitted
real uid : 1000
ffective uid : 1000
附加说明:一般在编写具 setuid root 的程序时, 为减少此类程序带来的系统安全风险, 在使用完root 权限后建议马上执行setuid(getuid());来抛弃root 权限. 此外, 进程uid 和euid 不一致时Linux 系统将不会产生core dump.(摘自于:http://c.biancheng.net/cpp/html/226.html)
函数名:setgid - set group identity(设置组ID)
SYNOPSIS
#include <sys/types.h>
#include <unistd.h>
int setgid(gid_t gid);
DESCRIPTION
setgid() sets the effective group ID of the calling process. If the caller is the superuser, the real GID and saved set-group-ID are also
set.
函数说明:setgid()用来将目前进程的真实组识别码(real gid)设成参数gid 值. 如果是以超级用户身份执行此调用, 则real、effective 与savedgid 都会设成参数gid。(摘自于:http://c.biancheng.net/cpp/html/226.html)
返回值:设置成功则返回0, 失败则返回-1, 错误代码存于errno 中.
错误代码:
EPERM:并非以超级用户身份调用, 而且参数gid 并非进程的effective gid 或saved gid 值之一.
如有理解错误,请及时指出,谢谢