自定义“PT_INTERP”解释器会导致分段错误吗?

自定义“PT_INTERP”解释器会导致分段错误吗?

读完后关于通过更改PT_INTERP为自定义解释器来执行任意程序的文章,我尝试在本地进行实验:

$ cat flag.c
#include <stdio.h>

int main(int argc, char **argv) {
    printf("Hello World!\n");
    return 0;
}
$ gcc -static flag.c -o flag
$ cat solution.c
const char interp_section[] __attribute__((section(".interp"))) = "./flag";
$ gcc -s -fno-ident -Wl,--build-id=none -Wl,-e,0 -static -nostdlib solution.c -o solution
$ ./solution
Segmentation fault
$ ./flag
Hello World!

这个PT_INTERP程序头包含一个路径,这是我们的ELF将运行的解释器(可执行文件)的路径

既然solutionrequests./flag作为其解释器,为什么不./flag运行并打印消息“Hello World”,何时solution执行?相反,会发生分段错误,这与本文中的行为不同。

如何成功注册并执行自定义解释器PT_INTERP

$ readelf -l solution

Elf file type is EXEC (Executable file)
Entry point 0x0
There are 4 program headers, starting at offset 64

Program Headers:
  Type           Offset             VirtAddr           PhysAddr
                 FileSiz            MemSiz              Flags  Align
  PHDR           0x0000000000000040 0x0000000000400040 0x0000000000400040
                 0x00000000000000e0 0x00000000000000e0  R      0x8
  INTERP         0x0000000000000120 0x0000000000400120 0x0000000000400120
                 0x0000000000000007 0x0000000000000007  R      0x1
      [Requesting program interpreter: ./flag]
  LOAD           0x0000000000000000 0x0000000000400000 0x0000000000400000
                 0x0000000000000127 0x0000000000000127  R      0x1000
  GNU_STACK      0x0000000000000000 0x0000000000000000 0x0000000000000000
                 0x0000000000000000 0x0000000000000000  RW     0x10

 Section to Segment mapping:
  Segment Sections...
   00
   01     .interp
   02     .interp
   03

答案1

如果你运行dmesg,你应该看到类似的东西

(solution): Uhuuh, elf segment at 0000000000400000 requested but the memory is mapped already

原因是flagsolution都有一个位于 0x400000 的段。

避免这种情况的快速方法是使用二进制tinyelf helloworld作为flag;它没有冲突的部分,一切正常。

改编 TinyELF 示例,将其写入flag.c

#include <asm/unistd.h>

long syscall(long n,
             long a1, long a2, long a3, long a4, long a5, long a6);

void _start() {
  syscall(__NR_write, 1, (long) "Hello World!\n", 13, 0, 0, 0);
  syscall(__NR_exit, 0, 0, 0, 0, 0, 0);
}

long syscall(long n, long a1, long a2, long a3, long a4, long a5, long a6) {
  asm volatile ("movq %4, %%r10;"
                                "movq %5, %%r8;"
                                "movq %6, %%r9;"
                                "syscall;"

                : "=a"(n)
                : "a"(n), "D"(a1), "S"(a2), "d"(a3),
                  "r"(a4), "r"(a5), "r"(a6)
                : "%r10", "%r8", "%r9");
  return n;
}

构建如下:

gcc -nostartfiles -nostdlib flag.c -o flag

然后solution你已有的二进制文件就可以工作了。

相关内容