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