1 /*
2 * Copyright (c) 2021 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28
29 #include <darwintest.h>
30 #include <ptrauth.h>
31 #include <stdbool.h>
32 #include <stdlib.h>
33 #include <unistd.h>
34 #include <mach/mach.h>
35 #include <mach/exception.h>
36 #include <mach/thread_status.h>
37 #include <sys/types.h>
38 #include <sys/sysctl.h>
39 #include <sys/code_signing.h>
40 #include <TargetConditionals.h>
41 #include <mach/semaphore.h>
42
43 #if __arm64__
44 #define EXCEPTION_THREAD_STATE ARM_THREAD_STATE64
45 #define EXCEPTION_THREAD_STATE_COUNT ARM_THREAD_STATE64_COUNT
46 #elif __arm__
47 #define EXCEPTION_THREAD_STATE ARM_THREAD_STATE
48 #define EXCEPTION_THREAD_STATE_COUNT ARM_THREAD_STATE_COUNT
49 #elif __x86_64__
50 #define EXCEPTION_THREAD_STATE x86_THREAD_STATE
51 #define EXCEPTION_THREAD_STATE_COUNT x86_THREAD_STATE_COUNT
52 #else
53 #error Unsupported architecture
54 #endif
55
56 #if __arm64e__
57 #define TARGET_CPU_ARM64E true
58 #else
59 #define TARGET_CPU_ARM64E false
60 #endif
61
62 T_GLOBAL_META(
63 T_META_NAMESPACE("xnu.ipc"),
64 T_META_RADAR_COMPONENT_NAME("xnu"),
65 T_META_RADAR_COMPONENT_VERSION("IPC"),
66 T_META_RUN_CONCURRENTLY(true),
67 T_META_TAG_VM_PREFERRED);
68
69 /**
70 * mach_exc_server() is a MIG-generated function that verifies the message
71 * that was received is indeed a mach exception and then calls
72 * catch_mach_exception_raise_state() to handle the exception.
73 */
74 extern boolean_t mach_exc_server(mach_msg_header_t *, mach_msg_header_t *);
75
76 extern kern_return_t
77 catch_mach_exception_raise(
78 mach_port_t exception_port,
79 mach_port_t thread,
80 mach_port_t task,
81 exception_type_t type,
82 exception_data_t codes,
83 mach_msg_type_number_t code_count);
84
85 extern kern_return_t
86 catch_mach_exception_raise_state(
87 mach_port_t exception_port,
88 exception_type_t type,
89 exception_data_t codes,
90 mach_msg_type_number_t code_count,
91 int *flavor,
92 thread_state_t in_state,
93 mach_msg_type_number_t in_state_count,
94 thread_state_t out_state,
95 mach_msg_type_number_t *out_state_count);
96
97 extern kern_return_t
98 catch_mach_exception_raise_state_identity(
99 mach_port_t exception_port,
100 mach_port_t thread,
101 mach_port_t task,
102 exception_type_t type,
103 exception_data_t codes,
104 mach_msg_type_number_t code_count,
105 int *flavor,
106 thread_state_t in_state,
107 mach_msg_type_number_t in_state_count,
108 thread_state_t out_state,
109 mach_msg_type_number_t *out_state_count);
110
111 extern kern_return_t
112 catch_mach_exception_raise_identity_protected(
113 __unused mach_port_t exception_port,
114 uint64_t thread_id,
115 mach_port_t task_id_token,
116 exception_type_t exception,
117 mach_exception_data_t codes,
118 mach_msg_type_number_t codeCnt);
119
120 /**
121 * This has to be defined for linking purposes, but it's unused.
122 */
123 kern_return_t
catch_mach_exception_raise(mach_port_t exception_port,mach_port_t thread,mach_port_t task,exception_type_t type,exception_data_t codes,mach_msg_type_number_t code_count)124 catch_mach_exception_raise(
125 mach_port_t exception_port,
126 mach_port_t thread,
127 mach_port_t task,
128 exception_type_t type,
129 exception_data_t codes,
130 mach_msg_type_number_t code_count)
131 {
132 #pragma unused(exception_port, thread, task, type, codes, code_count)
133 T_FAIL("Triggered catch_mach_exception_raise() which shouldn't happen...");
134 __builtin_unreachable();
135 }
136
137 kern_return_t
catch_mach_exception_raise_identity_protected(__unused mach_port_t exception_port,uint64_t thread_id,mach_port_t task_id_token,exception_type_t exception,mach_exception_data_t codes,mach_msg_type_number_t codeCnt)138 catch_mach_exception_raise_identity_protected(
139 __unused mach_port_t exception_port,
140 uint64_t thread_id,
141 mach_port_t task_id_token,
142 exception_type_t exception,
143 mach_exception_data_t codes,
144 mach_msg_type_number_t codeCnt)
145 {
146 #pragma unused(exception_port, thread_id, task_id_token, exception, codes, codeCnt)
147 T_FAIL("Triggered catch_mach_exception_raise_identity_protected() which shouldn't happen...");
148 __builtin_unreachable();
149 }
150
151 /**
152 * This has to be defined for linking purposes, but it's unused.
153 */
154 kern_return_t
catch_mach_exception_raise_state(mach_port_t exception_port,exception_type_t type,exception_data_t codes,mach_msg_type_number_t code_count,int * flavor,thread_state_t in_state,mach_msg_type_number_t in_state_count,thread_state_t out_state,mach_msg_type_number_t * out_state_count)155 catch_mach_exception_raise_state(
156 mach_port_t exception_port,
157 exception_type_t type,
158 exception_data_t codes,
159 mach_msg_type_number_t code_count,
160 int *flavor,
161 thread_state_t in_state,
162 mach_msg_type_number_t in_state_count,
163 thread_state_t out_state,
164 mach_msg_type_number_t *out_state_count)
165 {
166 #pragma unused(exception_port, type, codes, code_count, flavor, in_state, in_state_count, out_state, out_state_count)
167 T_FAIL("Triggered catch_mach_exception_raise_state() which shouldn't happen...");
168 __builtin_unreachable();
169 }
170
171 static int exception_count = 0;
172 static int reset_diversifier = 0;
173 static semaphore_t semaphore;
174
175 /*
176 * Since the test needs to change the opaque field in
177 * thread struct, the test redefines the thread struct
178 * here. This is just for test purposes, this should not
179 * be done anywhere else.
180 */
181 struct test_user_thread_state_64 {
182 __uint64_t __x[29]; /* General purpose registers x0-x28 */
183 void* __opaque_fp; /* Frame pointer x29 */
184 void* __opaque_lr; /* Link register x30 */
185 void* __opaque_sp; /* Stack pointer x31 */
186 void* __opaque_pc; /* Program counter */
187 __uint32_t __cpsr; /* Current program status register */
188 __uint32_t __opaque_flags; /* Flags describing structure format */
189 };
190 #define __TEST_USER_THREAD_STATE64_FLAGS_KERNEL_SIGNED_PC 0x4
191
192 /**
193 * Called by mach_exc_server() to handle the exception.
194 * The first time this is called, it will modify the pc
195 * but keep the kernel signed bit. Next time this is called
196 * it will modify the pc and remove the kernel signed bit.
197 */
198 kern_return_t
catch_mach_exception_raise_state_identity(mach_port_t exception_port __unused,mach_port_t thread __unused,mach_port_t task __unused,exception_type_t type __unused,exception_data_t codes __unused,mach_msg_type_number_t code_count __unused,int * flavor,thread_state_t in_state,mach_msg_type_number_t in_state_count,thread_state_t out_state,mach_msg_type_number_t * out_state_count)199 catch_mach_exception_raise_state_identity(
200 mach_port_t exception_port __unused,
201 mach_port_t thread __unused,
202 mach_port_t task __unused,
203 exception_type_t type __unused,
204 exception_data_t codes __unused,
205 mach_msg_type_number_t code_count __unused,
206 int *flavor,
207 thread_state_t in_state,
208 mach_msg_type_number_t in_state_count,
209 thread_state_t out_state,
210 mach_msg_type_number_t *out_state_count)
211 {
212 T_LOG("Caught a mach exception %d!\n", type);
213 exception_count++;
214
215 /* There should only be two code values. */
216 T_QUIET; T_ASSERT_EQ(code_count, 2, "Two code values were provided with the mach exception");
217
218 /**
219 * The code values should be 64-bit since MACH_EXCEPTION_CODES was specified
220 * when setting the exception port.
221 */
222 mach_exception_data_t codes_64 = (mach_exception_data_t)(void *)codes;
223 T_LOG("Mach exception codes[0]: %#llx, codes[1]: %#llx\n", codes_64[0], codes_64[1]);
224
225 if (type == EXC_CRASH) {
226 T_LOG("Received a crash notification, signaling main thread and returning\n");
227 T_ASSERT_MACH_SUCCESS(semaphore_signal(semaphore), "semaphore_signal");
228 return KERN_SUCCESS;
229 }
230
231 /* Verify that we're receiving the expected thread state flavor. */
232 T_QUIET; T_ASSERT_EQ(*flavor, EXCEPTION_THREAD_STATE, "The thread state flavor is EXCEPTION_THREAD_STATE");
233 T_QUIET; T_ASSERT_EQ(in_state_count, EXCEPTION_THREAD_STATE_COUNT, "The thread state count is EXCEPTION_THREAD_STATE_COUNT");
234
235 /**
236 * Increment the PC by the 4 so the thread doesn't cause
237 * another exception when it resumes.
238 */
239 *out_state_count = in_state_count; /* size of state object in 32-bit words */
240 memcpy((void*)out_state, (void*)in_state, in_state_count * 4);
241
242 #if __arm64__
243 arm_thread_state64_t *state = (arm_thread_state64_t*)(void *)out_state;
244 struct test_user_thread_state_64 *test_state = (struct test_user_thread_state_64 *)(void *)out_state;
245 uint32_t userland_diversifier = test_state->__opaque_flags & 0xff000000;
246
247 void *pc = (void*)(arm_thread_state64_get_pc(*state) + 4);
248 /* Have to sign the new PC value when pointer authentication is enabled. */
249 T_LOG("Userland diversifier for thread state is 0x%x\n", userland_diversifier);
250 T_LOG("pc for thread state is 0x%p\n", pc);
251 T_QUIET; T_ASSERT_NE(userland_diversifier, 0, "Userland diversifier is non zero");
252
253 pc = ptrauth_sign_unauthenticated(pc, ptrauth_key_function_pointer, 0);
254 arm_thread_state64_set_pc_fptr(*state, pc);
255
256 /* Use the set and get lr, fp and sp function to make sure it compiles */
257 arm_thread_state64_set_lr_fptr(*state, arm_thread_state64_get_lr_fptr(*state));
258 arm_thread_state64_set_sp(*state, arm_thread_state64_get_sp(*state));
259 arm_thread_state64_set_fp(*state, arm_thread_state64_get_fp(*state));
260 #endif
261
262 if (reset_diversifier == 0) {
263 if (exception_count == 1) {
264 #if __arm64__
265 /* Set the kernel signed bit, so kernel ignores the new PC */
266 test_state->__opaque_flags |= __TEST_USER_THREAD_STATE64_FLAGS_KERNEL_SIGNED_PC;
267 T_LOG("Set the kernel signed flag on the thread state");
268 #else
269 T_LOG("Not on arm64, Not doing anything");
270 #endif
271 } else if (exception_count == 2) {
272 T_LOG("Not clearing the kernel signed bit, this should be the last exception");
273 } else {
274 T_FAIL("Received more than 2 exceptions, failing the test");
275 return KERN_FAILURE;
276 }
277 } else {
278 if (exception_count == 1) {
279 #if __arm64__
280 /* Set the user diversifier to zero and resign the pc */
281 test_state->__opaque_flags &= 0x00ffffff;
282 arm_thread_state64_set_pc_fptr(*state, pc);
283 T_LOG("Set the diversifier to zero and signed the pc, this should crash on return");
284 #else
285 T_LOG("Not on arm64, Not doing anything");
286 #endif
287 } else {
288 /* Avoid crash looping by propagating the child crash to report crash */
289 T_FAIL("Received more than 2 exceptions, failing the test");
290 T_ASSERT_MACH_SUCCESS(semaphore_signal(semaphore), "semaphore_signal");
291 return KERN_FAILURE;
292 }
293 }
294
295 /* Return KERN_SUCCESS to tell the kernel to keep running the victim thread. */
296 return KERN_SUCCESS;
297 }
298
299 static mach_port_t
create_exception_port_behavior64(exception_mask_t exception_mask,exception_behavior_t behavior)300 create_exception_port_behavior64(exception_mask_t exception_mask, exception_behavior_t behavior)
301 {
302 mach_port_t exc_port = MACH_PORT_NULL;
303 mach_port_t task = mach_task_self();
304 kern_return_t kr = KERN_SUCCESS;
305
306 if (behavior != EXCEPTION_STATE_IDENTITY && behavior != EXCEPTION_IDENTITY_PROTECTED) {
307 T_FAIL("Currently only EXCEPTION_STATE_IDENTITY and EXCEPTION_IDENTITY_PROTECTED are implemented");
308 }
309
310 /* Create the mach port the exception messages will be sent to. */
311 kr = mach_port_allocate(task, MACH_PORT_RIGHT_RECEIVE, &exc_port);
312 T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "Allocated mach exception port");
313
314 /**
315 * Insert a send right into the exception port that the kernel will use to
316 * send the exception thread the exception messages.
317 */
318 kr = mach_port_insert_right(task, exc_port, exc_port, MACH_MSG_TYPE_MAKE_SEND);
319 T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "Inserted a SEND right into the exception port");
320
321 /* Tell the kernel what port to send exceptions to. */
322 kr = task_set_exception_ports(
323 task,
324 exception_mask,
325 exc_port,
326 (exception_behavior_t)(behavior | (exception_behavior_t)MACH_EXCEPTION_CODES),
327 EXCEPTION_THREAD_STATE);
328 T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "Set the exception port to my custom handler");
329
330 return exc_port;
331 }
332
333 static mach_port_t __unused
create_exception_port(exception_mask_t exception_mask)334 create_exception_port(exception_mask_t exception_mask)
335 {
336 return create_exception_port_behavior64(exception_mask, EXCEPTION_STATE_IDENTITY);
337 }
338
339 /**
340 * Thread to handle the mach exception.
341 *
342 * @param arg The exception port to wait for a message on.
343 */
344 static void *
exc_server_thread(void * arg)345 exc_server_thread(void *arg)
346 {
347 mach_port_t exc_port = (mach_port_t)arg;
348 kern_return_t kr;
349
350 /**
351 * mach_msg_server_once is a helper function provided by libsyscall that
352 * handles creating mach messages, blocks waiting for a message on the
353 * exception port, calls mach_exc_server() to handle the exception, and
354 * sends a reply based on the return value of mach_exc_server().
355 */
356 #define MACH_MSG_REPLY_SIZE 4096
357 kr = mach_msg_server(mach_exc_server, MACH_MSG_REPLY_SIZE, exc_port, 0);
358 T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "Received mach exception message");
359
360 pthread_exit((void*)0);
361 __builtin_unreachable();
362 }
363
364 static void __unused
run_exception_handler(mach_port_t exc_port)365 run_exception_handler(mach_port_t exc_port)
366 {
367 pthread_t exc_thread;
368
369 /* Spawn the exception server's thread. */
370 int err = pthread_create(&exc_thread, (pthread_attr_t*)0, exc_server_thread, (void *)(unsigned long long)exc_port);
371 T_QUIET; T_ASSERT_POSIX_ZERO(err, "Spawned exception server thread");
372
373 /* No need to wait for the exception server to be joined when it exits. */
374 pthread_detach(exc_thread);
375 }
376
377 T_DECL(kernel_signed_pac_thread_state, "Test that kernel signed thread state given to exception ignores the pc",
378 T_META_ENABLED(TARGET_CPU_ARM64E)
379 )
380 {
381 mach_port_t exc_port = create_exception_port(EXC_MASK_BAD_ACCESS);
382
383 int expected_exception = 2;
384 exception_count = 0;
385
386 run_exception_handler(exc_port);
387 *(void *volatile*)0 = 0;
388
389 if (exception_count != expected_exception) {
390 T_FAIL("Expected %d exceptions, received %d", expected_exception, exception_count);
391 } else {
392 T_LOG("TEST PASSED");
393 }
394 T_END;
395 }
396
397 T_DECL(user_signed_pac_thread_state,
398 "Test that user signed thread state given to exception works with correct diversifier",
399 T_META_ENABLED(false && TARGET_CPU_ARM64E /* rdar://133955889 */))
400 {
401 mach_port_t exc_port = create_exception_port(EXC_MASK_BAD_ACCESS | EXC_MASK_CRASH);
402 T_ASSERT_MACH_SUCCESS(semaphore_create(mach_task_self(), &semaphore,
403 SYNC_POLICY_FIFO, 0), "semaphore_create");
404
405 exception_count = 0;
406 int expected_exception = 2;
407
408 run_exception_handler(exc_port);
409
410 /* Set the reset diversifier variable */
411 reset_diversifier = 1;
412 pid_t child_pid = fork();
413
414 if (child_pid == 0) {
415 *(void *volatile*)0 = 0;
416 T_FAIL("Child should have been terminated, but it did not");
417 }
418
419 T_ASSERT_MACH_SUCCESS(semaphore_wait(semaphore), "semaphore_wait");
420
421 if (exception_count != expected_exception) {
422 T_FAIL("Expected %d exceptions, received %d", expected_exception, exception_count);
423 } else {
424 T_LOG("TEST PASSED");
425 }
426 T_END;
427 }
428