gpt4 book ai didi

c++ - 为什么 exec() 在 chroot() 之后不工作?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:23:20 29 4
gpt4 key购买 nike

我正在研究 exec 系列函数,我看到了一个非常奇怪的行为:它们似乎在 chroot() 系统调用后不起作用。

这是来自联机帮助页的相关引述:

Special semantics for execlp() and execvp()

The execlp(), execvp(), and execvpe() functions duplicate the actions of the shell in searching for an executable file if the specified filename does not contain a slash (/) character. The file is sought in the colon-separated list of directory pathnames specified in the PATH envi‐ ronment variable. If this variable isn't defined, the path list defaults to the current directory followed by the list of directories returned by confstr(_CS_PATH). (This confstr(3) call typically returns the value "/bin:/usr/bin".)

If the specified filename includes a slash character, then PATH is ignored, and the file at the specified pathname is executed.

这是理论,现在让我们看看它是如何表现的:

  • 我有 prog.c 文件,它将由 execlp 执行:

    #include <stdio.h>

    int main()
    {
    puts("works!");
    return 0;
    }
  • 我有 exec.c 文件,它将尝试执行 prog:

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <string.h>
    #include <errno.h>
    #include <dirent.h>

    int main(int argc, char* const argv[])
    {
    const char path[] = "/home/zaffy/cool";

    if (argc < 2)
    return 1;

    if (argc > 2 && (chdir(path) || chroot(path)))
    {
    printf("Cannot chroot(%s): %s\n", path, strerror(errno));
    return 1;
    }

    /* Clear our environment, including PATH */
    clearenv();

    if (execlp(argv[1], argv[1], NULL))
    {
    printf("Cannot execlp(%s): %s\n", argv[1], strerror(errno));

    /* Well, we failed... let's see
    contents of the current root */
    struct dirent* entry;
    DIR* dir = opendir("/");
    while ( (entry = readdir(dir)) )
    printf("%s\n", entry->d_name);
    closedir(dir);
    }

    return 0;
    }
  • 所有测试都在 /home/zaffy/cool 中完成:

    /home/zaffy/cool
    ├── exec
    ├── exec.c
    ├── prog
    └── prog.c

测试一:不调用 chroot 执行:

# /home/zaffy/cool/exec /home/zaffy/cool/prog
works!

测试二:调用 chroot 执行:

# /home/zaffy/cool/exec /prog 1
Cannot execlp(/prog): No such file or directory
.
..
prog.c
prog
exec.c
exec

我很困惑!根据手册页,如果我已将绝对路径传递给 execlp,则不应在 PATH 中搜索,或者如果未设置 PATH,它也应该设置为当前目录,所以我看不到这里的问题。

该文件确实存在并且可用!即使我在 execlp 之前使用 fopenfopen 会找到并打开文件,但 execlp 仍然发出错误没有这样的文件或目录。

你知道为什么会这样吗?为什么 exec() 在 chroot() 之后不起作用?

最佳答案

您的问题很可能是您尝试执行的程序是动态链接的,并且动态链接器不存在于 chroot 环境的 /lib 中。这将导致 ENOENT(没有这样的文件或目录)错误。但是,仅仅单独添加它是无济于事的。您需要动态链接程序所依赖的所有其他文件,包括共享库和任何必要的配置/表/等。这些库需要的文件。

关于c++ - 为什么 exec() 在 chroot() 之后不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24342758/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com