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之後,其他用戶也可以執行。運行效果如下:
    這裏寫圖片描述

系統種這樣的程序也有不少:
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章