1 /*
2  * Copyright (c) 2019 Alexey Dobriyan <adobriyan@gmail.com>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16 /*
17  * Fork and exec tiny 1 page executable which precisely controls its VM.
18  * Test /proc/$PID/maps
19  * Test /proc/$PID/smaps
20  * Test /proc/$PID/smaps_rollup
21  * Test /proc/$PID/statm
22  *
23  * FIXME require CONFIG_TMPFS which can be disabled
24  * FIXME test other values from "smaps"
25  * FIXME support other archs
26  */
27 #undef NDEBUG
28 #include <assert.h>
29 #include <errno.h>
30 #include <sched.h>
31 #include <signal.h>
32 #include <stdbool.h>
33 #include <stdint.h>
34 #include <stdio.h>
35 #include <string.h>
36 #include <stdlib.h>
37 #include <sys/mount.h>
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 #include <sys/wait.h>
41 #include <fcntl.h>
42 #include <unistd.h>
43 #include <sys/syscall.h>
44 #include <sys/uio.h>
45 #include <linux/kdev_t.h>
46 #include <sys/time.h>
47 #include <sys/resource.h>
48 
49 static inline long sys_execveat(int dirfd, const char *pathname, char **argv, char **envp, int flags)
50 {
51 	return syscall(SYS_execveat, dirfd, pathname, argv, envp, flags);
52 }
53 
54 static void make_private_tmp(void)
55 {
56 	if (unshare(CLONE_NEWNS) == -1) {
57 		if (errno == ENOSYS || errno == EPERM) {
58 			exit(4);
59 		}
60 		exit(1);
61 	}
62 	if (mount(NULL, "/", NULL, MS_PRIVATE|MS_REC, NULL) == -1) {
63 		exit(1);
64 	}
65 	if (mount(NULL, "/tmp", "tmpfs", 0, NULL) == -1) {
66 		exit(1);
67 	}
68 }
69 
70 static pid_t pid = -1;
71 static void ate(void)
72 {
73 	if (pid > 0) {
74 		kill(pid, SIGTERM);
75 	}
76 }
77 
78 struct elf64_hdr {
79 	uint8_t e_ident[16];
80 	uint16_t e_type;
81 	uint16_t e_machine;
82 	uint32_t e_version;
83 	uint64_t e_entry;
84 	uint64_t e_phoff;
85 	uint64_t e_shoff;
86 	uint32_t e_flags;
87 	uint16_t e_ehsize;
88 	uint16_t e_phentsize;
89 	uint16_t e_phnum;
90 	uint16_t e_shentsize;
91 	uint16_t e_shnum;
92 	uint16_t e_shstrndx;
93 };
94 
95 struct elf64_phdr {
96 	uint32_t p_type;
97 	uint32_t p_flags;
98 	uint64_t p_offset;
99 	uint64_t p_vaddr;
100 	uint64_t p_paddr;
101 	uint64_t p_filesz;
102 	uint64_t p_memsz;
103 	uint64_t p_align;
104 };
105 
106 #ifdef __x86_64__
107 #define PAGE_SIZE 4096
108 #define VADDR (1UL << 32)
109 #define MAPS_OFFSET 73
110 
111 #define syscall	0x0f, 0x05
112 #define mov_rdi(x)	\
113 	0x48, 0xbf,	\
114 	(x)&0xff, ((x)>>8)&0xff, ((x)>>16)&0xff, ((x)>>24)&0xff,	\
115 	((x)>>32)&0xff, ((x)>>40)&0xff, ((x)>>48)&0xff, ((x)>>56)&0xff
116 
117 #define mov_rsi(x)	\
118 	0x48, 0xbe,	\
119 	(x)&0xff, ((x)>>8)&0xff, ((x)>>16)&0xff, ((x)>>24)&0xff,	\
120 	((x)>>32)&0xff, ((x)>>40)&0xff, ((x)>>48)&0xff, ((x)>>56)&0xff
121 
122 #define mov_eax(x)	\
123 	0xb8, (x)&0xff, ((x)>>8)&0xff, ((x)>>16)&0xff, ((x)>>24)&0xff
124 
125 static const uint8_t payload[] = {
126 	/* Casually unmap stack, vDSO and everything else. */
127 	/* munmap */
128 	mov_rdi(VADDR + 4096),
129 	mov_rsi((1ULL << 47) - 4096 - VADDR - 4096),
130 	mov_eax(11),
131 	syscall,
132 
133 	/* Ping parent. */
134 	/* write(0, &c, 1); */
135 	0x31, 0xff,					/* xor edi, edi */
136 	0x48, 0x8d, 0x35, 0x00, 0x00, 0x00, 0x00,	/* lea rsi, [rip] */
137 	0xba, 0x01, 0x00, 0x00, 0x00,			/* mov edx, 1 */
138 	mov_eax(1),
139 	syscall,
140 
141 	/* 1: pause(); */
142 	mov_eax(34),
143 	syscall,
144 
145 	0xeb, 0xf7,	/* jmp 1b */
146 };
147 
148 static int make_exe(const uint8_t *payload, size_t len)
149 {
150 	struct elf64_hdr h;
151 	struct elf64_phdr ph;
152 
153 	struct iovec iov[3] = {
154 		{&h, sizeof(struct elf64_hdr)},
155 		{&ph, sizeof(struct elf64_phdr)},
156 		{(void *)payload, len},
157 	};
158 	int fd, fd1;
159 	char buf[64];
160 
161 	memset(&h, 0, sizeof(h));
162 	h.e_ident[0] = 0x7f;
163 	h.e_ident[1] = 'E';
164 	h.e_ident[2] = 'L';
165 	h.e_ident[3] = 'F';
166 	h.e_ident[4] = 2;
167 	h.e_ident[5] = 1;
168 	h.e_ident[6] = 1;
169 	h.e_ident[7] = 0;
170 	h.e_type = 2;
171 	h.e_machine = 0x3e;
172 	h.e_version = 1;
173 	h.e_entry = VADDR + sizeof(struct elf64_hdr) + sizeof(struct elf64_phdr);
174 	h.e_phoff = sizeof(struct elf64_hdr);
175 	h.e_shoff = 0;
176 	h.e_flags = 0;
177 	h.e_ehsize = sizeof(struct elf64_hdr);
178 	h.e_phentsize = sizeof(struct elf64_phdr);
179 	h.e_phnum = 1;
180 	h.e_shentsize = 0;
181 	h.e_shnum = 0;
182 	h.e_shstrndx = 0;
183 
184 	memset(&ph, 0, sizeof(ph));
185 	ph.p_type = 1;
186 	ph.p_flags = (1<<2)|1;
187 	ph.p_offset = 0;
188 	ph.p_vaddr = VADDR;
189 	ph.p_paddr = 0;
190 	ph.p_filesz = sizeof(struct elf64_hdr) + sizeof(struct elf64_phdr) + len;
191 	ph.p_memsz = sizeof(struct elf64_hdr) + sizeof(struct elf64_phdr) + len;
192 	ph.p_align = 4096;
193 
194 	fd = openat(AT_FDCWD, "/tmp", O_WRONLY|O_EXCL|O_TMPFILE, 0700);
195 	if (fd == -1) {
196 		exit(1);
197 	}
198 
199 	if (writev(fd, iov, 3) != sizeof(struct elf64_hdr) + sizeof(struct elf64_phdr) + len) {
200 		exit(1);
201 	}
202 
203 	/* Avoid ETXTBSY on exec. */
204 	snprintf(buf, sizeof(buf), "/proc/self/fd/%u", fd);
205 	fd1 = open(buf, O_RDONLY|O_CLOEXEC);
206 	close(fd);
207 
208 	return fd1;
209 }
210 #endif
211 
212 static bool g_vsyscall = false;
213 
214 static const char str_vsyscall[] =
215 "ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]\n";
216 
217 #ifdef __x86_64__
218 /*
219  * vsyscall page can't be unmapped, probe it with memory load.
220  */
221 static void vsyscall(void)
222 {
223 	pid_t pid;
224 	int wstatus;
225 
226 	pid = fork();
227 	if (pid < 0) {
228 		fprintf(stderr, "fork, errno %d\n", errno);
229 		exit(1);
230 	}
231 	if (pid == 0) {
232 		struct rlimit rlim = {0, 0};
233 		(void)setrlimit(RLIMIT_CORE, &rlim);
234 		*(volatile int *)0xffffffffff600000UL;
235 		exit(0);
236 	}
237 	wait(&wstatus);
238 	if (WIFEXITED(wstatus)) {
239 		g_vsyscall = true;
240 	}
241 }
242 
243 int main(void)
244 {
245 	int pipefd[2];
246 	int exec_fd;
247 
248 	vsyscall();
249 
250 	atexit(ate);
251 
252 	make_private_tmp();
253 
254 	/* Reserve fd 0 for 1-byte pipe ping from child. */
255 	close(0);
256 	if (open("/", O_RDONLY|O_DIRECTORY|O_PATH) != 0) {
257 		return 1;
258 	}
259 
260 	exec_fd = make_exe(payload, sizeof(payload));
261 
262 	if (pipe(pipefd) == -1) {
263 		return 1;
264 	}
265 	if (dup2(pipefd[1], 0) != 0) {
266 		return 1;
267 	}
268 
269 	pid = fork();
270 	if (pid == -1) {
271 		return 1;
272 	}
273 	if (pid == 0) {
274 		sys_execveat(exec_fd, "", NULL, NULL, AT_EMPTY_PATH);
275 		return 1;
276 	}
277 
278 	char _;
279 	if (read(pipefd[0], &_, 1) != 1) {
280 		return 1;
281 	}
282 
283 	struct stat st;
284 	if (fstat(exec_fd, &st) == -1) {
285 		return 1;
286 	}
287 
288 	/* Generate "head -n1 /proc/$PID/maps" */
289 	char buf0[256];
290 	memset(buf0, ' ', sizeof(buf0));
291 	int len = snprintf(buf0, sizeof(buf0),
292 			"%08lx-%08lx r-xp 00000000 %02lx:%02lx %llu",
293 			VADDR, VADDR + PAGE_SIZE,
294 			MAJOR(st.st_dev), MINOR(st.st_dev),
295 			(unsigned long long)st.st_ino);
296 	buf0[len] = ' ';
297 	snprintf(buf0 + MAPS_OFFSET, sizeof(buf0) - MAPS_OFFSET,
298 		 "/tmp/#%llu (deleted)\n", (unsigned long long)st.st_ino);
299 
300 	/* Test /proc/$PID/maps */
301 	{
302 		const size_t len = strlen(buf0) + (g_vsyscall ? strlen(str_vsyscall) : 0);
303 		char buf[256];
304 		ssize_t rv;
305 		int fd;
306 
307 		snprintf(buf, sizeof(buf), "/proc/%u/maps", pid);
308 		fd = open(buf, O_RDONLY);
309 		if (fd == -1) {
310 			return 1;
311 		}
312 		rv = read(fd, buf, sizeof(buf));
313 		assert(rv == len);
314 		assert(memcmp(buf, buf0, strlen(buf0)) == 0);
315 		if (g_vsyscall) {
316 			assert(memcmp(buf + strlen(buf0), str_vsyscall, strlen(str_vsyscall)) == 0);
317 		}
318 	}
319 
320 	/* Test /proc/$PID/smaps */
321 	{
322 		char buf[4096];
323 		ssize_t rv;
324 		int fd;
325 
326 		snprintf(buf, sizeof(buf), "/proc/%u/smaps", pid);
327 		fd = open(buf, O_RDONLY);
328 		if (fd == -1) {
329 			return 1;
330 		}
331 		rv = read(fd, buf, sizeof(buf));
332 		assert(0 <= rv && rv <= sizeof(buf));
333 
334 		assert(rv >= strlen(buf0));
335 		assert(memcmp(buf, buf0, strlen(buf0)) == 0);
336 
337 #define RSS1 "Rss:                   4 kB\n"
338 #define RSS2 "Rss:                   0 kB\n"
339 #define PSS1 "Pss:                   4 kB\n"
340 #define PSS2 "Pss:                   0 kB\n"
341 		assert(memmem(buf, rv, RSS1, strlen(RSS1)) ||
342 		       memmem(buf, rv, RSS2, strlen(RSS2)));
343 		assert(memmem(buf, rv, PSS1, strlen(PSS1)) ||
344 		       memmem(buf, rv, PSS2, strlen(PSS2)));
345 
346 		static const char *S[] = {
347 			"Size:                  4 kB\n",
348 			"KernelPageSize:        4 kB\n",
349 			"MMUPageSize:           4 kB\n",
350 			"Anonymous:             0 kB\n",
351 			"AnonHugePages:         0 kB\n",
352 			"Shared_Hugetlb:        0 kB\n",
353 			"Private_Hugetlb:       0 kB\n",
354 			"Locked:                0 kB\n",
355 		};
356 		int i;
357 
358 		for (i = 0; i < sizeof(S)/sizeof(S[0]); i++) {
359 			assert(memmem(buf, rv, S[i], strlen(S[i])));
360 		}
361 
362 		if (g_vsyscall) {
363 			assert(memmem(buf, rv, str_vsyscall, strlen(str_vsyscall)));
364 		}
365 	}
366 
367 	/* Test /proc/$PID/smaps_rollup */
368 	{
369 		char bufr[256];
370 		memset(bufr, ' ', sizeof(bufr));
371 		len = snprintf(bufr, sizeof(bufr),
372 				"%08lx-%08lx ---p 00000000 00:00 0",
373 				VADDR, VADDR + PAGE_SIZE);
374 		bufr[len] = ' ';
375 		snprintf(bufr + MAPS_OFFSET, sizeof(bufr) - MAPS_OFFSET,
376 			 "[rollup]\n");
377 
378 		char buf[1024];
379 		ssize_t rv;
380 		int fd;
381 
382 		snprintf(buf, sizeof(buf), "/proc/%u/smaps_rollup", pid);
383 		fd = open(buf, O_RDONLY);
384 		if (fd == -1) {
385 			return 1;
386 		}
387 		rv = read(fd, buf, sizeof(buf));
388 		assert(0 <= rv && rv <= sizeof(buf));
389 
390 		assert(rv >= strlen(bufr));
391 		assert(memcmp(buf, bufr, strlen(bufr)) == 0);
392 
393 		assert(memmem(buf, rv, RSS1, strlen(RSS1)) ||
394 		       memmem(buf, rv, RSS2, strlen(RSS2)));
395 		assert(memmem(buf, rv, PSS1, strlen(PSS1)) ||
396 		       memmem(buf, rv, PSS2, strlen(PSS2)));
397 
398 		static const char *S[] = {
399 			"Anonymous:             0 kB\n",
400 			"AnonHugePages:         0 kB\n",
401 			"Shared_Hugetlb:        0 kB\n",
402 			"Private_Hugetlb:       0 kB\n",
403 			"Locked:                0 kB\n",
404 		};
405 		int i;
406 
407 		for (i = 0; i < sizeof(S)/sizeof(S[0]); i++) {
408 			assert(memmem(buf, rv, S[i], strlen(S[i])));
409 		}
410 	}
411 
412 	/* Test /proc/$PID/statm */
413 	{
414 		char buf[64];
415 		ssize_t rv;
416 		int fd;
417 
418 		snprintf(buf, sizeof(buf), "/proc/%u/statm", pid);
419 		fd = open(buf, O_RDONLY);
420 		if (fd == -1) {
421 			return 1;
422 		}
423 		rv = read(fd, buf, sizeof(buf));
424 		assert(rv == 7 * 2);
425 
426 		assert(buf[0] == '1');	/* ->total_vm */
427 		assert(buf[1] == ' ');
428 		assert(buf[2] == '0' || buf[2] == '1');	/* rss */
429 		assert(buf[3] == ' ');
430 		assert(buf[4] == '0' || buf[2] == '1');	/* file rss */
431 		assert(buf[5] == ' ');
432 		assert(buf[6] == '1');	/* ELF executable segments */
433 		assert(buf[7] == ' ');
434 		assert(buf[8] == '0');
435 		assert(buf[9] == ' ');
436 		assert(buf[10] == '0');	/* ->data_vm + ->stack_vm */
437 		assert(buf[11] == ' ');
438 		assert(buf[12] == '0');
439 		assert(buf[13] == '\n');
440 	}
441 
442 	return 0;
443 }
444 #else
445 int main(void)
446 {
447 	return 4;
448 }
449 #endif
450