zoukankan      html  css  js  c++  java
  • 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. */
        }

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


    无欲速,无见小利。欲速,则不达;见小利,则大事不成。
  • 相关阅读:
    吉他音阶笔记(以C调为基准)
    小程序页面跳转问题
    Adobe-premierej剪辑视频分辨率问题及格式转换画面质量分辨率
    关于ps抠图问题,制作公章,公章的复制
    premiere视频剪辑关于导出视屏分辨率的问题
    最后一个单词的长度
    10.两个链表的交叉
    软件工程——个人总结
    软件工程——团队专业4
    软件工程——团队答辩
  • 原文地址:https://www.cnblogs.com/ch122633/p/7363243.html
Copyright © 2011-2022 走看看