• chroot()使用


        好多的程序,都有使用chroot来是程序chroot到一个目录下面,来保护文件系统,今天在看snort代码的时候,看到了实现,就贴出一个测试程序来,实际上是比较简单的。

        chroot()在linux下面需要使用root权限,这一点需要注意了。

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

    int main(void)
    {
        char chroot_path[] = "/tmp";
        char *pwd;
        int ret;

        /*chroot 需要root权限*/
        ret = chroot(chroot_path);
        if (ret != 0) {
            perror("chroot:");
            exit(-1);
        }
        pwd = getcwd(NULL, 80);
        printf("After chroot,getcwd is [%s] ",pwd);
        free(pwd);

        /*可以建立/tmp/test,测试一下是否可以改变目录 /tmp/test <==> /test*/
        ret = chdir("/test");
        if( ret < 0 )
        {
                perror("chdir /test");
                //exit(-1);
        }
        else
             /*由于chroot之后,当前工作目录还没有改变,所以需要再调用chdir来改变到/目录*/
             if( chdir("/") < 0 )
             {
                     perror("chdir /");
                     exit(-1);
             }

        pwd = getcwd(NULL, 80);
        printf("After chdir /,getcwd is [%s] ",pwd);
        free(pwd);

        return 0;
    }

    以普通用户的身份运行程序:
    wangyao@fisherman:~$ ./a.out
    chroot:: Operation not permitted
    以root用户运行,刚开始/tmp下面没有test目录:
    fisherman:/home/wangyao# ./a.out
    After chroot,getcwd is [/home/wangyao]
    chdir /test: No such file or directory
    After chdir /,getcwd is [/home/wangyao]
    fisherman:/home/wangyao# mkdir -p /tmp/test
    fisherman:/home/wangyao# ./a.out
    After chroot,getcwd is [/home/wangyao]
    After chdir /,getcwd is [/]
    fisherman:/home/wangyao#

    chroot()执行成功之后,根目录是进行了切换,但是当前工作目录没有变化,还是chroot()之前的,需要再一次调用chdir()来实现更改当前工作目录,如果chdir失败,当前工作目录不变。

    snort中的一段代码:
       /* Don't need root privs anymore, so lets drop ownership
         * and chroot if requested....
         */

        if(chrootdir != NULL)
        {
            if(chdir(chrootdir) < 0)
                FatalError("Can not chdir to "%s" ", chrootdir);
            if(chroot(chrootdir) < 0)
                FatalError("Can not chroot to %s ", chrootdir);
            if(chdir("/") < 0)
                FatalError("Can not chdir to "/" ");

            free(chrootdir);
            chrootdir = NULL;        /* we don't need chrootdir anymore so all
                                      * other routines should use fullpath. */
        }

    以后写程序的时候,尤其是网络程序的时候,可以加上这个特性 :-)


    无欲速,无见小利。欲速,则不达;见小利,则大事不成。
  • 相关阅读:
    将已排序的数组乱序
    Roadmap!!
    测试
    最大对称字串
    约瑟夫环问题
    大家好
    MYSQL数据库导入SQL文件出现乱码如何解决
    Hibernate缓存
    Spring备忘四(涵盖Spring2.5)
    Struts2 Hello,Wold
  • 原文地址:https://www.cnblogs.com/ch122633/p/7363243.html
Copyright © 2020-2023  润新知