Linux setuid 实践

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之后,其他用户也可以执行。运行效果如下:
    这里写图片描述

系统种这样的程序也有不少:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值