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