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