🗑️

自分自身に埋め込まれたファイルを自分で読み出す実行バイナリ

に公開
2025/08/26

ファイルをspecialセクションに埋め込んで、実行バイナリとリンクし、実行バイナリが自分自身の特定セクションを参照して、またファイルに書き出す例。

linux環境を前提にしている

実験
$ ls
sample.c
$ # 入力にするファイルを生成
$ echo "Hello elf sections." > sample.txt
$ ls
sample.c  sample.txt
$ # ファイルを`.special`セクションに埋め込んだオブジェクトファイルを作成
$ # .dataに埋め込まれるので、.dataをrename
$ objcopy --input binary --output elf64-x86-64 --rename-section .data=.special sample.txt sample.o
$ # オブジェクトファイルと自分自身の`.special`セクションを読み出すCコードをリンク
$ # コードは下に添付してある
$ gcc sample.c sample.o -o sample
/opt/rh/gcc-toolset-13/root/usr/libexec/gcc/x86_64-redhat-linux/13/ld: warning: sample.o: missing .note.GNU-stack section implies executable stack
/opt/rh/gcc-toolset-13/root/usr/libexec/gcc/x86_64-redhat-linux/13/ld: NOTE: This behaviour is deprecated and will be removed in a future version of the linker
$ # 実行するとファイルが出てくる
$ ./sample
.special section size: 20 bytes
$ # 生成したファイルと同じファイルが読み出せた
$ cat special_section_data
Hello elf sections.
$ cat sample.txt 
Hello elf sections.
sample.c
#include <elf.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>

int main(void) {
  int fd = open("/proc/self/exe", O_RDONLY);
  if (fd < 0) {
    perror("open");
    return 1;
  }

  struct stat st;
  if (fstat(fd, &st) < 0) {
    perror("fstat");
    close(fd);
    return 1;
  }

  void *map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
  if (map == MAP_FAILED) {
    perror("mmap");
    close(fd);
    return 1;
  }

  close(fd);

  Elf64_Ehdr *ehdr = (Elf64_Ehdr *)map;
  Elf64_Shdr *shdr = (Elf64_Shdr *)((char *)map + ehdr->e_shoff);
  const char *shstrtab = (char *)map + shdr[ehdr->e_shstrndx].sh_offset;

  for (int i = 0; i < ehdr->e_shnum; i++) {
    const char *name = shstrtab + shdr[i].sh_name;
    if (strcmp(name, ".special") == 0) {
      unsigned char *data = (unsigned char *)map + shdr[i].sh_offset;
      printf(".special section size: %lu bytes\n", shdr[i].sh_size);

      /* 例: ファイルに書き出す */
      FILE *f = fopen("special_section_data", "w");
      fwrite(data, 1, shdr[i].sh_size, f);
      fclose(f);

      break;
    }
  }

  munmap(map, st.st_size);
  return 0;
}

メモ

以下を挟めば、.note.GNU-stackセクションに関する警告を消せる。明示的にstackを空にすると安全らしい。

objcopy \
    --add-section .note.GNU-stack=/dev/null \
    --set-section-flags .note.GNU-stack=contents \
   sample.o sample.o 

Discussion