我们如何知道用 exec() 启动的程序所需的最小堆栈大小?

How can we know the minimum stack size needed by a program launched with exec()?

为了避免 stack clash attacks against a program, we 尝试将 setrlimit(RLIMIT_STACK) 的堆栈大小限制设置为大约 2 MB。

这个限制可以满足我们程序自身的内部需求,但我们随后注意到,在具有这个新限制的某些系统上,exec() 外部程序的尝试开始失败。我们使用下面的测试程序调查的一个系统似乎具有 exec() 程序的最小堆栈大小略高于 4 MiB。

我的问题是,我们如何知道给定系统上堆栈大小的安全最小值,以便 exec() 不会失败?

我们不想在我们当前测试的所有系统上不再出现故障之前提出这个问题,因为随着程序移植到具有更高最低要求的较新系统类型,这可能会导致将来出现故障.

下面的 C 测试程序是根据 system(), but the lower-level symptom is a failure in the execl() 系统调用编写的。根据您测试的主机 OS,当您为被调用程序提供太少的堆栈 space 无法启动时,您会得到 errno == E2BIG 或被调用程序中的段错误。

构建:

$ CFLAGS="-std=c99 -D_POSIX_C_SOURCE=200809" make stacklim

此问题与“To check the E2BIG error condition in exec”无关,但我们的实际问题不同:我们对设置此限制导致的潜在可移植性问题感兴趣。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <unistd.h>

static enum try_code {
    raise_minimum,
    lower_maximum,
    failed_to_launch
}
try_stack_limit(rlim_t try)
{
    // Update the stack limit to the given value
    struct rlimit x;
    getrlimit(RLIMIT_STACK, &x);
    static int first_time = 1;
    if (first_time) {
        first_time = 0;
        printf("The default stack limit here is %llu bytes.\n", x.rlim_cur);
    }
    x.rlim_cur = try;
    setrlimit(RLIMIT_STACK, &x);

    // Test the limit with a do-nothing shell launch
    int status = system("exit");
    switch (status) {
        case 0: return lower_maximum;

        case -1:
            perror("Failed to start shell");
            return failed_to_launch;

        default:
            if (WIFEXITED(status) && WEXITSTATUS(status) == 127) {
                // system() couldn't run /bin/sh, so assume it was
                // because we set the stack limit too low.
                return raise_minimum;
            }
            else if (WIFSIGNALED(status)) {
                fprintf(stderr, "system() failed with signal %s.\n",
                        strsignal(WTERMSIG(status)));
                return failed_to_launch;
            }
            else {
                fprintf(stderr, "system() failed: %d.\n", status);
                return failed_to_launch;
            }
    }
}

int main(void)
{
    extern char **environ;
    size_t etot = 0;
    for (size_t i = 0; environ[i]; ++i) {
        etot += strlen(environ[i]) + 1;
    }
    printf("Environment size = %lu\n", etot + sizeof(char*));

    size_t tries = 0;
    rlim_t try = 1 * 1000 * 1000, min = 0, max = 0;
    while (1) {
        enum try_code code = try_stack_limit(try);
        switch (code) {
            case lower_maximum:
                // Call succeded, so lower max and try a lower limit.
                ++tries;
                max = try;
                printf("Lowered max to %llu bytes.\n", max);
                try = min + ((max - min) / 2);
                break;

            case failed_to_launch:
                if (tries == 0) {
                    // Our first try failed, so there may be a bug in
                    // the system() call.  Stop immediately.
                    return 2;
                }
                // Else, consider it a failure of the new limit, and
                // assume we need to limit it.

            case raise_minimum:
                // Call failed, so raise minimum and try a higher limit.
                ++tries;
                min = try > min ? try : min;
                rlim_t next = max ?
                        min + ((max - min) / 2) :
                        try * 2;
                if (next == try) {
                    printf("Min stack size here for exec is %llu.\n", max);
                    return 0;
                }
                else {
                    printf("Raising limit from %llu to %llu.\n", try, next);
                    try = next;
                }
                break;

            default:
                return 1;
        }
    }
}

您的程序已成功启动,因此您的程序被隐式地赋予了正确的堆栈大小以依次启动其他程序:在您的程序启动期间,在设置新的下限之前获取当前限制:

struct rlimit g_default_stack_limit;  /* put in global scope */
getrlimit(RLIMIT_STACK, &g_default_stack_limit);

struct rlimit our_stack_limit;
memcpy(&our_stack_limit, &g_default_stack_limit, sizeof(our_stack_limit));
our_stack_limit.rlim_cur = 2000000;   /* some lower value */
setrlimit(RLIMIT_STACK, &our_stack_limit);

然后在启动外部程序之前恢复该初始值,并在创建子 fork() 或程序的同步调用(例如通过 system())退出后重新应用新限制:

struct rlimit our_stack_limit;
getrlimit(RLIMIT_STACK, &our_stack_limit);
setrlimit(RLIMIT_STACK, &g_default_stack_limit);

if (system(...) == 0) {
    ....
}

setrlimit(RLIMIT_STACK, &our_stack_limit);

这个初始值可能是操作系统的默认值,也可能是调用您的程序的程序设置的限制。无论哪种方式,它几乎肯定是传递给您的程序依次调用的程序的正确起始值。

调用 exec() 时,调用进程的内存映射无效。它被更改以适应新的可执行文件。为新的可执行文件分配栈内存、堆内存、全局数据和代码内存。映射通常在 link 时定义,内存在调用 main()

之前由语言库分配

参考:http://man7.org/linux/man-pages/man2/execve.2.html