4.12 利用 __stack_chk_fail

    这一节我们来看一下,在开启了 canary 的程序上,怎样利用 泄漏信息。

    一个例子:

    我们先注释掉最后一行:

    1. $ gcc chk_fail.c
    2. $ python -c 'print "A"*50' | ./a.out
    3. argv[0]: ./a.out
    4. *** stack smashing detected ***: ./a.out terminated
    5. Aborted (core dumped)

    可以看到默认情况下 argv[0] 是指向程序路径及名称的指针,然后错误信息中打印出了这个字符串。

    然后解掉注释再来看一看:

    1. $ python -c 'print "A"*50' | ./a.out
    2. argv[0]: ./a.out
    3. *** stack smashing detected ***: Hello World! terminated
    4. Aborted (core dumped)

    main 函数的反汇编结果如下:

    所以当 canary 检查失败的时候,即产生栈溢出,覆盖掉了原来的 canary 的时候,函数不能正常返回,而是执行 __stack_chk_fail() 函数,打印出 argv[0] 指向的字符串。

    Ubuntu 16.04 使用的是 libc-2.23,其 __stack_chk_fail() 函数如下:

    1. // debug/stack_chk_fail.c
    2. extern char **__libc_argv attribute_hidden;
    3. void
    4. __attribute__ ((noreturn))
    5. {
    6. __fortify_fail ("stack smashing detected");
    7. }

    调用函数 __fortify_fail()

    1. // debug/fortify_fail.c
    2. extern char **__libc_argv attribute_hidden;
    3. __attribute__ ((noreturn)) internal_function
    4. __fortify_fail (const char *msg)
    5. {
    6. /* The loop is added only to keep gcc happy. */
    7. while (1)
    8. __libc_message (2, "*** %s ***: %s terminated\n",
    9. msg, __libc_argv[0] ?: "<unknown>");
    10. }
    11. libc_hidden_def (__fortify_fail)

    __fortify_fail() 调用函数 __libc_message() 打印出错误信息和 argv[0]

    环境变量 LIBC_FATAL_STDERR_ 通过函数 __libc_secure_getenv 来读取,如果该变量没有被设置或者为空,即 \0NULL,错误信息 stderr 会被重定向到 _PATH_TTY,该值通常是 /dev/tty,因此会直接在当前终端打印出来,而不是传到 stderr。

    CTF 中就有这样一种题目,需要我们把 argv[0] 覆盖为 flag 的地址,并利用 __stack_chk_fail() 把flag 给打印出来。

    实例可以查看章节 6.1.13 和 6.1.14。

    最后我们来看一下 libc-2.25 里的 __stack_chk_fail

    1. extern char **__libc_argv attribute_hidden;
    2. void
    3. __attribute__ ((noreturn))
    4. __stack_chk_fail (void)
    5. {
    6. __fortify_fail_abort (false, "stack smashing detected");
    7. }
    8. strong_alias (__stack_chk_fail, __stack_chk_fail_local)

    它使用了新函数 ,这个函数是在 这次提交中新增的:

    1. void
    2. __attribute__ ((noreturn))
    3. __fortify_fail_abort (_Bool need_backtrace, const char *msg)
    4. {
    5. /* The loop is added only to keep gcc happy. Don't pass down
    6. __libc_argv[0] if we aren't doing backtrace since __libc_argv[0]
    7. may point to the corrupted stack. */
    8. while (1)
    9. __libc_message (need_backtrace ? (do_abort | do_backtrace) : do_abort,
    10. "*** %s ***: %s terminated\n",
    11. msg,
    12. (need_backtrace && __libc_argv[0] != NULL
    13. ? __libc_argv[0] : "<unknown>"));
    14. }
    15. void
    16. __attribute__ ((noreturn))
    17. __fortify_fail (const char *msg)
    18. {
    19. __fortify_fail_abort (true, msg);
    20. }
    21. libc_hidden_def (__fortify_fail)
    22. libc_hidden_def (__fortify_fail_abort)

    就像下面这样: