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

Linux setuid 实践

2015-06-05 14:55 561 查看

Linux setuid 实践

之前接触过setuid,但是没有深入思考,今天读《Unix编程艺术》,觉得瞬间为这种设计所折服,所以总结一下。一般在设计系统时,为了安全,总是试图使用最小权限模型,除非迫不得已需要特权来访问系统,否则不该信任用户代码。Unix中访问控制是基于用户和组的,所以setuid/setgid正是为了给当前进程设置用户/组ID,从而赋予相应的权限。

Under Unix, programs that must be run by ordinary users, but must have write access to security-critical system resources, get that access through a feature called the setuid bit. Executable files are the smallest unit of code that can hold a setuid bit; thus, every line of code in a setuid executable must be trusted. (Well-written setuid programs, however, take all necessary privileged actions first and then drop their privileges back to user level for the remainder of their existence.)

Usually a setuid program only needs its privileges for one or a small handful of operations. It is often possible to break up such a program into cooperating processes, a smaller one that needs setuid and a larger one that does not. When we can do this, only the code in the smaller program has to be trusted. It is in significant part because this kind of partitioning and delegation is possible that Unix has a better security track record than its competitors.

–《Unix编程艺术》

读完了APUE之后,决定实践一下。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>   // open()

#include <errno.h>
#include <string.h>  // strerror()

int main(){
    int fd;
    setuid(0); // become the superuser to open the master file
    fd = open("/etc/shadow", O_RDONLY);
    setuid(-1); // give up the privelige
    if(fd < 0){
        printf("open error! %s(errno=%d)\n", strerror(errno), errno);
        exit(-1);
    }
    // do something with fd
    return 0;
}


如果没有setuid root,则会报错!

open error! Operation not permitted(errno=1)

但是仅有setuid root也是不行的,需要将可执行程序设置SID,其实这里也按时了setuid的应用场景,就是把需要特权的指令限制在一定范围,拥有者是root,但是设置了setuid bit之后,其他用户也可以执行。运行效果如下:



系统种这样的程序也有不少:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: