• UNIX文件的权限之“设置用户ID位”


       用stat函数可以获取一个文件的状态信息,原型是这样的:

    int stat(const char *path, struct stat *buf);

      其中结构体stat的结构:

    struct stat {
                   dev_t     st_dev;     /* ID of device containing file */
                   ino_t     st_ino;     /* inode number */
                   mode_t    st_mode;    /* protection */
                   nlink_t   st_nlink;   /* number of hard links */
                   uid_t     st_uid;     /* user ID of owner */
                   gid_t     st_gid;     /* group ID of owner */
                   dev_t     st_rdev;    /* device ID (if special file) */
                   off_t     st_size;    /* total size, in bytes */
                   blksize_t st_blksize; /* blocksize for file system I/O */
                   blkcnt_t  st_blocks;  /* number of 512B blocks allocated */
                   time_t    st_atime;   /* time of last access */
                   time_t    st_mtime;   /* time of last modification */
                   time_t    st_ctime;   /* time of last status change */
               };

        从传出的参数buf中可以拿到用st_uid,st_gid 表示的文件所有者ID,和文件所有者所在的组ID。

      在UNIX进程中也有几组ID的概念。分别是实际用户ID,实际用户组ID,有效用户ID和有效用户组ID等等。当我们开始一个进程是,通常这个进程的有效用户ID就是这个进程的实际ID(比如我用eric用户登录,这个有效用户就我eric对应的ID)。然而当“设置用户ID位”打开以后,有效ID就是进程的程序文件对应的所有者的ID。

      

    $ls -l 1.txt
    -rw------- 1 root root 16  4月 29 14:31 1.txt

      当前目录下面有一个文件“1.txt”是所有者root,并且只有root具有读和写权限。

     1 int main()
     2 {
     3     int fd;
     4     if((fd=open("1.txt",O_RDONLY)) == -1)
     5     {
     6         printf("Open failed.
    ");
     7         exit(-1);
     8     }
     9     char buf[1024]={0};
    10     read(fd,buf,1024);
    11     printf(buf);
    12     printf("
    ");
    13 }

      首先我在终端里使用su命令使用root用户。gcc read.c -omain。得到main程序。

       

    # gcc read.c -omain
    # exit
    exit
    $ main
    Open failed.

      显然main的所有者也是root,但是main程序依旧不可以打开“1.txt”,这是因为main启动后这个进程的有效ID是进程的实际用户ID(也就是eric账户的ID),而“1.txt”只对root用户具有读写权限,所以open失败。

      把main的设置用户ID位打开可以用shell指令: chmod u+s main

      我用的是c程序,主要代码如下:

    1         struct stat buf = {0};
    2         stat("main",&buf);
    3         buf.st_mode |= S_ISUID;
    4         chmod("main",buf.st_mode);

      执行后,main的“设置用户ID位”就打开了。再在非root终端下 执行main程序 就可以成功的读出 1.txt的内容 

    $ main
    ilovecpp.com

      

    个人觉得linux权限设计还是比较合理的,虽然这里main程序可以运行时是已所有者root的权限,但是这需要root用户的授权:打开这个程序文件的“set uid bit”(设置用户ID位)。只要在打开这个set uid bit 时充分考虑到这个程序存在的风险。当然授权需谨慎。O(∩_∩)O

  • 相关阅读:
    推荐6款优秀的海外免费杀毒软件 附下载链接
    30个高质量的Psd设计文件分享
    45个设计师们不常见的html5和css3漂亮模板
    40个极简WordPress主题
    makfile中 override 与 +=联合作用的验证
    对 makefile 中 flavor 函数的学习体会
    GNU make manual 翻译( 一百六十七)
    对 makefile 中 override 优先级的学习体会
    GNU make manual 翻译( 一百六十五)
    GNU make manual 翻译( 一百六十六)
  • 原文地址:https://www.cnblogs.com/ittinybird/p/4466171.html
Copyright © 2020-2023  润新知