4.12 利用 __stack_chk_fail
这一节我们来看一下,在开启了 canary 的程序上,怎样利用 泄漏信息。
一个例子:
我们先注释掉最后一行:
$ gcc chk_fail.c
$ python -c 'print "A"*50' | ./a.out
argv[0]: ./a.out
*** stack smashing detected ***: ./a.out terminated
Aborted (core dumped)
可以看到默认情况下 argv[0]
是指向程序路径及名称的指针,然后错误信息中打印出了这个字符串。
然后解掉注释再来看一看:
$ python -c 'print "A"*50' | ./a.out
argv[0]: ./a.out
*** stack smashing detected ***: Hello World! terminated
Aborted (core dumped)
main 函数的反汇编结果如下:
所以当 canary 检查失败的时候,即产生栈溢出,覆盖掉了原来的 canary 的时候,函数不能正常返回,而是执行 __stack_chk_fail()
函数,打印出 argv[0]
指向的字符串。
Ubuntu 16.04 使用的是 libc-2.23,其 __stack_chk_fail()
函数如下:
// debug/stack_chk_fail.c
extern char **__libc_argv attribute_hidden;
void
__attribute__ ((noreturn))
{
__fortify_fail ("stack smashing detected");
}
调用函数 __fortify_fail()
:
// debug/fortify_fail.c
extern char **__libc_argv attribute_hidden;
__attribute__ ((noreturn)) internal_function
__fortify_fail (const char *msg)
{
/* The loop is added only to keep gcc happy. */
while (1)
__libc_message (2, "*** %s ***: %s terminated\n",
msg, __libc_argv[0] ?: "<unknown>");
}
libc_hidden_def (__fortify_fail)
__fortify_fail()
调用函数 __libc_message()
打印出错误信息和 argv[0]
。
环境变量 LIBC_FATAL_STDERR_
通过函数 __libc_secure_getenv
来读取,如果该变量没有被设置或者为空,即 \0
或 NULL
,错误信息 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
:
extern char **__libc_argv attribute_hidden;
void
__attribute__ ((noreturn))
__stack_chk_fail (void)
{
__fortify_fail_abort (false, "stack smashing detected");
}
strong_alias (__stack_chk_fail, __stack_chk_fail_local)
它使用了新函数 ,这个函数是在 这次提交中新增的:
void
__attribute__ ((noreturn))
__fortify_fail_abort (_Bool need_backtrace, const char *msg)
{
/* The loop is added only to keep gcc happy. Don't pass down
__libc_argv[0] if we aren't doing backtrace since __libc_argv[0]
may point to the corrupted stack. */
while (1)
__libc_message (need_backtrace ? (do_abort | do_backtrace) : do_abort,
"*** %s ***: %s terminated\n",
msg,
(need_backtrace && __libc_argv[0] != NULL
? __libc_argv[0] : "<unknown>"));
}
void
__attribute__ ((noreturn))
__fortify_fail (const char *msg)
{
__fortify_fail_abort (true, msg);
}
libc_hidden_def (__fortify_fail)
libc_hidden_def (__fortify_fail_abort)
就像下面这样: