xref: /xnu-8792.81.2/tests/imm_pinned_control_port.c (revision 19c3b8c28c31cb8130e034cfb5df6bf9ba342d90)
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <darwintest.h>
5 #include <mach/mach.h>
6 #include <mach/mach_vm.h>
7 #include <excserver.h>
8 #include <sys/sysctl.h>
9 #include <spawn.h>
10 #include <signal.h>
11 #include <TargetConditionals.h>
12 
13 #define MAX_ARGV 3
14 #define EXC_CODE_SHIFT 32
15 #define EXC_GUARD_TYPE_SHIFT 29
16 #define MAX_TEST_NUM 21
17 
18 #define TASK_EXC_GUARD_MP_DELIVER 0x10
19 
20 extern char **environ;
21 static uint64_t exception_code = 0;
22 static exception_type_t exception_taken = 0;
23 
24 #define IKOT_TASK_CONTROL               2
25 
26 #ifndef kGUARD_EXC_INVALID_OPTIONS
27 #define kGUARD_EXC_INVALID_OPTIONS 3
28 #endif
29 
30 /*
31  * This test verifies behaviors of immovable/pinned task/thread ports.
32  *
33  * 1. Compare and verifies port names of mach_{task, thread}_self(),
34  * {TASK, THREAD}_KERNEL_PORT, and ports returned from task_threads()
35  * and processor_set_tasks().
36  * 2. Make sure correct exceptions are raised resulting from moving immovable
37  * task/thread control, read and inspect ports.
38  * 3. Make sure correct exceptions are raised resulting from deallocating pinned
39  * task/thread control ports.
40  * 4. Make sure immovable ports cannot be stashed:
41  * rdar://70585367 (Disallow immovable port stashing with *_set_special_port() and mach_port_register())
42  */
43 T_GLOBAL_META(
44 	T_META_NAMESPACE("xnu.ipc"),
45 	T_META_RADAR_COMPONENT_NAME("xnu"),
46 	T_META_RADAR_COMPONENT_VERSION("IPC"),
47 	T_META_RUN_CONCURRENTLY(TRUE));
48 
49 static uint64_t soft_exception_code[] = {
50 	EXC_GUARD, // Soft crash delivered as EXC_CORPSE_NOTIFY
51 	EXC_GUARD,
52 	EXC_GUARD,
53 	EXC_GUARD,
54 	EXC_GUARD,
55 	EXC_GUARD,
56 	EXC_GUARD,
57 
58 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_IMMOVABLE,
59 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_IMMOVABLE,
60 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_IMMOVABLE,
61 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_IMMOVABLE,
62 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_IMMOVABLE,
63 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_IMMOVABLE,
64 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_IMMOVABLE,
65 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_IMMOVABLE,
66 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_IMMOVABLE,
67 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_IMMOVABLE,
68 
69 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_INVALID_OPTIONS,
70 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_INVALID_OPTIONS,
71 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_INVALID_OPTIONS,
72 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_INVALID_OPTIONS,
73 };
74 
75 static uint64_t hard_exception_code[] = {
76 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_MOD_REFS,
77 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_MOD_REFS,
78 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_MOD_REFS,
79 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_MOD_REFS,
80 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_MOD_REFS,
81 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_MOD_REFS,
82 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_MOD_REFS,
83 
84 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_IMMOVABLE,
85 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_IMMOVABLE,
86 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_IMMOVABLE,
87 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_IMMOVABLE,
88 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_IMMOVABLE,
89 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_IMMOVABLE,
90 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_IMMOVABLE,
91 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_IMMOVABLE,
92 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_IMMOVABLE,
93 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_IMMOVABLE,
94 
95 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_INVALID_OPTIONS,
96 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_INVALID_OPTIONS,
97 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_INVALID_OPTIONS,
98 	(GUARD_TYPE_MACH_PORT << EXC_GUARD_TYPE_SHIFT) | kGUARD_EXC_INVALID_OPTIONS,
99 };
100 
101 kern_return_t
catch_mach_exception_raise_state(mach_port_t exception_port,exception_type_t exception,const mach_exception_data_t code,mach_msg_type_number_t code_count,int * flavor,const thread_state_t old_state,mach_msg_type_number_t old_state_count,thread_state_t new_state,mach_msg_type_number_t * new_state_count)102 catch_mach_exception_raise_state(mach_port_t exception_port,
103     exception_type_t exception,
104     const mach_exception_data_t code,
105     mach_msg_type_number_t code_count,
106     int * flavor,
107     const thread_state_t old_state,
108     mach_msg_type_number_t old_state_count,
109     thread_state_t new_state,
110     mach_msg_type_number_t * new_state_count)
111 {
112 #pragma unused(exception_port, exception, code, code_count, flavor, old_state, old_state_count, new_state, new_state_count)
113 	T_FAIL("Unsupported catch_mach_exception_raise_state");
114 	return KERN_NOT_SUPPORTED;
115 }
116 
117 kern_return_t
catch_mach_exception_raise_state_identity(mach_port_t exception_port,mach_port_t thread,mach_port_t task,exception_type_t exception,mach_exception_data_t code,mach_msg_type_number_t code_count,int * flavor,thread_state_t old_state,mach_msg_type_number_t old_state_count,thread_state_t new_state,mach_msg_type_number_t * new_state_count)118 catch_mach_exception_raise_state_identity(mach_port_t exception_port,
119     mach_port_t thread,
120     mach_port_t task,
121     exception_type_t exception,
122     mach_exception_data_t code,
123     mach_msg_type_number_t code_count,
124     int * flavor,
125     thread_state_t old_state,
126     mach_msg_type_number_t old_state_count,
127     thread_state_t new_state,
128     mach_msg_type_number_t * new_state_count)
129 {
130 #pragma unused(exception_port, thread, task, exception, code, code_count, flavor, old_state, old_state_count, new_state, new_state_count)
131 	T_FAIL("Unsupported catch_mach_exception_raise_state_identity");
132 	return KERN_NOT_SUPPORTED;
133 }
134 
135 kern_return_t
catch_mach_exception_raise(mach_port_t exception_port,mach_port_t thread,mach_port_t task,exception_type_t exception,mach_exception_data_t code,mach_msg_type_number_t code_count)136 catch_mach_exception_raise(mach_port_t exception_port,
137     mach_port_t thread,
138     mach_port_t task,
139     exception_type_t exception,
140     mach_exception_data_t code,
141     mach_msg_type_number_t code_count)
142 {
143 #pragma unused(exception_port, code_count)
144 	pid_t pid;
145 	kern_return_t kr = pid_for_task(task, &pid);
146 	T_EXPECT_MACH_SUCCESS(kr, "pid_for_task");
147 	T_LOG("Crashing child pid: %d, continuing...\n", pid);
148 
149 	kr = mach_port_deallocate(mach_task_self(), thread);
150 	T_QUIET; T_EXPECT_MACH_SUCCESS(kr, "mach_port_deallocate");
151 	kr = mach_port_deallocate(mach_task_self(), task);
152 	T_QUIET; T_EXPECT_MACH_SUCCESS(kr, "mach_port_deallocate");
153 
154 	T_LOG("Caught exception type: %d code: 0x%llx", exception, *((uint64_t*)code));
155 	if (exception == EXC_GUARD || exception == EXC_CORPSE_NOTIFY) {
156 		exception_taken = exception;
157 		exception_code = *((uint64_t *)code);
158 	} else {
159 		T_FAIL("Unexpected exception");
160 	}
161 	return KERN_SUCCESS;
162 }
163 
164 static void *
exception_server_thread(void * arg)165 exception_server_thread(void *arg)
166 {
167 	kern_return_t kr;
168 	mach_port_t exc_port = *(mach_port_t *)arg;
169 
170 	/* Handle exceptions on exc_port */
171 	kr = mach_msg_server_once(mach_exc_server, 4096, exc_port, 0);
172 	T_QUIET; T_EXPECT_MACH_SUCCESS(kr, "mach_msg_server_once");
173 
174 	return NULL;
175 }
176 
177 static mach_port_t
alloc_exception_port(void)178 alloc_exception_port(void)
179 {
180 	kern_return_t kret;
181 	mach_port_t exc_port = MACH_PORT_NULL;
182 	mach_port_t task = mach_task_self();
183 
184 	kret = mach_port_allocate(task, MACH_PORT_RIGHT_RECEIVE, &exc_port);
185 	T_QUIET; T_EXPECT_MACH_SUCCESS(kret, "mach_port_allocate exc_port");
186 
187 	kret = mach_port_insert_right(task, exc_port, exc_port, MACH_MSG_TYPE_MAKE_SEND);
188 	T_QUIET; T_EXPECT_MACH_SUCCESS(kret, "mach_port_insert_right exc_port");
189 
190 	return exc_port;
191 }
192 
193 static void
test_immovable_port_stashing(void)194 test_immovable_port_stashing(void)
195 {
196 	kern_return_t kr;
197 	mach_port_t port;
198 
199 	kr = task_set_special_port(mach_task_self(), TASK_BOOTSTRAP_PORT, mach_task_self());
200 	T_EXPECT_EQ(kr, KERN_INVALID_RIGHT, "should disallow task_set_special_port() with immovable port");
201 
202 	kr = thread_set_special_port(mach_thread_self(), THREAD_KERNEL_PORT, mach_thread_self());
203 	T_EXPECT_EQ(kr, KERN_INVALID_RIGHT, "should disallow task_set_special_port() with immovable port");
204 
205 	mach_port_t stash[1] = {mach_task_self()};
206 	kr = mach_ports_register(mach_task_self(), stash, 1);
207 	T_EXPECT_EQ(kr, KERN_INVALID_RIGHT, "should disallow mach_ports_register() with immovable port");
208 
209 	T_QUIET; T_ASSERT_MACH_SUCCESS(mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &port), "mach_port_allocate");
210 	T_QUIET; T_ASSERT_MACH_SUCCESS(mach_port_insert_right(mach_task_self(), port, port, MACH_MSG_TYPE_MAKE_SEND), "mach_port_insert_right");
211 
212 	stash[0] = port;
213 	kr = mach_ports_register(mach_task_self(), stash, 1);
214 	T_EXPECT_MACH_SUCCESS(kr, "mach_ports_register() should succeed with movable port");
215 }
216 
217 static void
test_task_thread_port_values(void)218 test_task_thread_port_values(void)
219 {
220 	T_LOG("Compare various task/thread control port values\n");
221 	kern_return_t kr;
222 	mach_port_t port, th_self;
223 	thread_array_t threadList;
224 	mach_msg_type_number_t threadCount = 0;
225 	boolean_t found_self = false;
226 	processor_set_name_array_t psets;
227 	processor_set_t        pset_priv;
228 	task_array_t taskList;
229 	mach_msg_type_number_t pcnt = 0, tcnt = 0;
230 	mach_port_t host = mach_host_self();
231 
232 	/* Compare with task/thread_get_special_port() */
233 	kr = task_get_special_port(mach_task_self(), TASK_KERNEL_PORT, &port);
234 	T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "task_get_special_port() - TASK_KERNEL_PORT");
235 	T_EXPECT_NE(port, mach_task_self(), "TASK_KERNEL_PORT should not match mach_task_self()");
236 	mach_port_deallocate(mach_task_self(), port);
237 
238 	kr = task_for_pid(mach_task_self(), getpid(), &port);
239 	T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "task_for_pid()");
240 	T_EXPECT_EQ(port, mach_task_self(), "task_for_pid(self) should match mach_task_self()");
241 	mach_port_deallocate(mach_task_self(), port);
242 
243 	th_self = mach_thread_self();
244 	kr = thread_get_special_port(th_self, THREAD_KERNEL_PORT, &port);
245 	T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "thread_get_special_port() - THREAD_KERNEL_PORT");
246 	T_EXPECT_NE(port, th_self, "THREAD_KERNEL_PORT should not match mach_thread_self()");
247 	mach_port_deallocate(mach_task_self(), port);
248 
249 	/* Make sure task_threads() return immovable thread ports */
250 	kr = task_threads(mach_task_self(), &threadList, &threadCount);
251 	T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "task_threads()");
252 	T_QUIET; T_ASSERT_GE(threadCount, 1, "should have at least 1 thread");
253 
254 	for (size_t i = 0; i < threadCount; i++) {
255 		if (th_self == threadList[i]) { /* th_self is immovable */
256 			found_self = true;
257 			break;
258 		}
259 	}
260 
261 	T_EXPECT_TRUE(found_self, "task_threads() should return immovable thread self");
262 
263 	for (size_t i = 0; i < threadCount; i++) {
264 		mach_port_deallocate(mach_task_self(), threadList[i]);
265 	}
266 
267 	if (threadCount > 0) {
268 		mach_vm_deallocate(mach_task_self(),
269 		    (mach_vm_address_t)threadList,
270 		    threadCount * sizeof(mach_port_t));
271 	}
272 
273 	mach_port_deallocate(mach_task_self(), th_self);
274 
275 	/* Make sure processor_set_tasks() return immovable task self */
276 	kr = host_processor_sets(host, &psets, &pcnt);
277 	T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "host_processor_sets");
278 	T_QUIET; T_ASSERT_GE(pcnt, 1, "should have at least 1 processor set");
279 
280 	kr = host_processor_set_priv(host, psets[0], &pset_priv);
281 	T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "host_processor_set_priv");
282 	for (size_t i = 0; i < pcnt; i++) {
283 		mach_port_deallocate(mach_task_self(), psets[i]);
284 	}
285 	mach_port_deallocate(mach_task_self(), host);
286 	vm_deallocate(mach_task_self(), (vm_address_t)psets, (vm_size_t)pcnt * sizeof(mach_port_t));
287 
288 	kr = processor_set_tasks_with_flavor(pset_priv, TASK_FLAVOR_CONTROL, &taskList, &tcnt);
289 	T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "processor_set_tasks_with_flavor");
290 	T_QUIET; T_ASSERT_GE(tcnt, 1, "should have at least 1 task");
291 	mach_port_deallocate(mach_task_self(), pset_priv);
292 
293 	found_self = false;
294 	for (size_t i = 0; i < tcnt; i++) {
295 		if (taskList[i] == mach_task_self()) {
296 			found_self = true;
297 			break;
298 		}
299 	}
300 
301 	T_EXPECT_TRUE(found_self, " processor_set_tasks() should return immovable task self");
302 
303 	for (size_t i = 0; i < tcnt; i++) {
304 		mach_port_deallocate(mach_task_self(), taskList[i]);
305 	}
306 
307 	if (tcnt > 0) {
308 		mach_vm_deallocate(mach_task_self(),
309 		    (mach_vm_address_t)taskList,
310 		    tcnt * sizeof(mach_port_t));
311 	}
312 }
313 
314 T_DECL(imm_pinned_control_port, "Test pinned & immovable task and thread control ports",
315     T_META_IGNORECRASHES(".*pinned_rights_child.*"),
316     T_META_CHECK_LEAKS(false))
317 {
318 	uint32_t task_exc_guard = 0;
319 	size_t te_size = sizeof(&task_exc_guard);
320 	posix_spawnattr_t       attrs;
321 	char *test_prog_name = "./imm_pinned_control_port_crasher";
322 	char *child_args[MAX_ARGV];
323 	pid_t client_pid = 0;
324 	uint32_t opts = 0;
325 	uint64_t *test_exception_code;
326 	size_t size = sizeof(&opts);
327 	mach_port_t exc_port;
328 	pthread_t s_exc_thread;
329 	uint64_t exc_id;
330 
331 	T_LOG("Check if task_exc_guard exception has been enabled\n");
332 	int ret = sysctlbyname("kern.task_exc_guard_default", &task_exc_guard, &te_size, NULL, 0);
333 	T_ASSERT_EQ(ret, 0, "sysctlbyname");
334 
335 	if (!(task_exc_guard & TASK_EXC_GUARD_MP_DELIVER)) {
336 		T_SKIP("task_exc_guard exception is not enabled");
337 	}
338 
339 	T_LOG("Check if immovable control port has been enabled\n");
340 	ret = sysctlbyname("kern.ipc_control_port_options", &opts, &size, NULL, 0);
341 
342 	if (!ret && (opts & 0x8) != 0x8) {
343 		T_SKIP("hard immovable control port isn't enabled");
344 	}
345 
346 	if (!ret && (opts & 0x2)) {
347 		T_LOG("Hard pinning enforcement is on.");
348 		test_exception_code = hard_exception_code;
349 	} else {
350 		T_LOG("Hard pinning enforcement is off.");
351 		test_exception_code = soft_exception_code;
352 	}
353 
354 
355 	/* first, try out comparing various task/thread ports */
356 	test_task_thread_port_values();
357 
358 	/* try stashing immovable ports: rdar://70585367 */
359 	test_immovable_port_stashing();
360 
361 	/* spawn a child and see if EXC_GUARD are correctly generated */
362 	for (int i = 0; i < MAX_TEST_NUM; i++) {
363 		/* Create the exception port for the child */
364 		exc_port = alloc_exception_port();
365 		T_QUIET; T_ASSERT_NE(exc_port, MACH_PORT_NULL, "Create a new exception port");
366 
367 		/* Create exception serving thread */
368 		ret = pthread_create(&s_exc_thread, NULL, exception_server_thread, &exc_port);
369 		T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "pthread_create exception_server_thread");
370 
371 		/* Initialize posix_spawn attributes */
372 		posix_spawnattr_init(&attrs);
373 
374 		int err = posix_spawnattr_setexceptionports_np(&attrs, EXC_MASK_GUARD | EXC_MASK_CORPSE_NOTIFY, exc_port,
375 		    (exception_behavior_t) (EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES), 0);
376 		T_QUIET; T_ASSERT_POSIX_SUCCESS(err, "posix_spawnattr_setflags");
377 
378 		child_args[0] = test_prog_name;
379 		char test_num[10];
380 		sprintf(test_num, "%d", i);
381 		child_args[1] = test_num;
382 		child_args[2] = NULL;
383 
384 		T_LOG("========== Spawning new child ==========");
385 		err = posix_spawn(&client_pid, child_args[0], NULL, &attrs, &child_args[0], environ);
386 		T_ASSERT_POSIX_SUCCESS(err, "posix_spawn control_port_options_client = %d test_num = %d", client_pid, i);
387 
388 		/* try extracting child task port: rdar://71744817
389 		 * Moved to tests/extract_right_soft_fail.c
390 		 */
391 		// test_extract_immovable_task_port(client_pid);
392 
393 		int child_status;
394 		/* Wait for child and check for exception */
395 		if (-1 == waitpid(-1, &child_status, 0)) {
396 			T_FAIL("waitpid: child mia");
397 		}
398 
399 		if (WIFEXITED(child_status) && WEXITSTATUS(child_status)) {
400 			T_FAIL("Child exited with status = %x", child_status);
401 			T_END;
402 		}
403 
404 		sleep(1);
405 		kill(1, SIGKILL);
406 
407 		ret = pthread_join(s_exc_thread, NULL);
408 		T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "pthread_join");
409 
410 		if (exception_taken == EXC_GUARD) {
411 			exc_id = exception_code >> EXC_CODE_SHIFT;
412 		} else {
413 			exc_id = exception_code;
414 		}
415 
416 		T_LOG("Exception code: Received code = 0x%llx Expected code = 0x%llx", exc_id, test_exception_code[i]);
417 		T_EXPECT_EQ(exc_id, test_exception_code[i], "Exception code: Received == Expected");
418 	}
419 }
420