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