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]\n",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]\n",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\"\n", chrootdir);
        if(chroot(chrootdir) < 0)
            FatalError("Can not chroot to %s\n", chrootdir);
        if(chdir("/") < 0)
            FatalError("Can not chdir to \"/\"\n");

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

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


posted @ 2017-08-15 09:11  习惯就好233  阅读(586)  评论(0编辑  收藏  举报