1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <darwintest.h>
5 #include <spawn.h>
6 #include <mach/mach.h>
7 #include <sys/sysctl.h>
8 #include <signal.h>
9 #include "excserver_protect_state.h"
10 #include "../osfmk/ipc/ipc_init.h"
11 #include "../osfmk/mach/port.h"
12 #include "../osfmk/kern/exc_guard.h"
13 #include "exc_helpers.h"
14 #include <sys/code_signing.h>
15 #include "cs_helpers.h"
16 #include <TargetConditionals.h>
17
18 #define MAX_TEST_NUM 10
19 #define MAX_ARGV 3
20
21 extern char **environ;
22 static mach_exception_data_type_t received_exception_code = 0;
23 static exception_type_t exception_taken = 0;
24
25 /*
26 * This test infrastructure is inspired from imm_pinned_control_port.c.
27 * It verifies no reply port security semantics are violated.
28 *
29 * 1. The rcv right of the port would be marked immovable.
30 */
31 T_GLOBAL_META(
32 T_META_NAMESPACE("xnu.ipc"),
33 T_META_RADAR_COMPONENT_NAME("xnu"),
34 T_META_RADAR_COMPONENT_VERSION("IPC"),
35 T_META_TIMEOUT(10),
36 T_META_RUN_CONCURRENTLY(TRUE));
37
38 static mach_port_t
alloc_exception_port(void)39 alloc_exception_port(void)
40 {
41 kern_return_t kret;
42 mach_port_t exc_port = MACH_PORT_NULL;
43 mach_port_t task = mach_task_self();
44
45 kret = mach_port_allocate(task, MACH_PORT_RIGHT_RECEIVE, &exc_port);
46 T_QUIET; T_EXPECT_MACH_SUCCESS(kret, "mach_port_allocate exc_port");
47
48 kret = mach_port_insert_right(task, exc_port, exc_port, MACH_MSG_TYPE_MAKE_SEND);
49 T_QUIET; T_EXPECT_MACH_SUCCESS(kret, "mach_port_insert_right exc_port");
50
51 return exc_port;
52 }
53
54 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)55 catch_mach_exception_raise_state(mach_port_t exception_port,
56 exception_type_t exception,
57 const mach_exception_data_t code,
58 mach_msg_type_number_t code_count,
59 int * flavor,
60 const thread_state_t old_state,
61 mach_msg_type_number_t old_state_count,
62 thread_state_t new_state,
63 mach_msg_type_number_t * new_state_count)
64 {
65 #pragma unused(exception_port, exception, code, code_count, flavor, old_state, old_state_count, new_state, new_state_count)
66 T_FAIL("Unsupported catch_mach_exception_raise_state");
67 return KERN_NOT_SUPPORTED;
68 }
69
70 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)71 catch_mach_exception_raise_state_identity(mach_port_t exception_port,
72 mach_port_t thread,
73 mach_port_t task,
74 exception_type_t exception,
75 mach_exception_data_t code,
76 mach_msg_type_number_t code_count,
77 int * flavor,
78 thread_state_t old_state,
79 mach_msg_type_number_t old_state_count,
80 thread_state_t new_state,
81 mach_msg_type_number_t * new_state_count)
82 {
83 #pragma unused(exception_port, thread, task, exception, code, code_count, flavor, old_state, old_state_count, new_state, new_state_count)
84 T_FAIL("Unsupported catch_mach_exception_raise_state_identity");
85 return KERN_NOT_SUPPORTED;
86 }
87
88 kern_return_t
catch_mach_exception_raise_state_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,__unused int * flavor,__unused thread_state_t old_state,__unused mach_msg_type_number_t old_state_count,__unused thread_state_t new_state,__unused mach_msg_type_number_t * new_state_count)89 catch_mach_exception_raise_state_identity_protected(
90 __unused mach_port_t exception_port,
91 uint64_t thread_id,
92 mach_port_t task_id_token,
93 exception_type_t exception,
94 mach_exception_data_t codes,
95 mach_msg_type_number_t codeCnt,
96 __unused int * flavor,
97 __unused thread_state_t old_state,
98 __unused mach_msg_type_number_t old_state_count,
99 __unused thread_state_t new_state,
100 __unused mach_msg_type_number_t * new_state_count)
101 {
102 #pragma unused(exception_port, thread_id, task_id_token, exception, codes, codeCnt)
103
104 T_FAIL("Unsupported catch_mach_exception_raise_state_identity_protected");
105 return KERN_NOT_SUPPORTED;
106 }
107
108 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)109 catch_mach_exception_raise_identity_protected(
110 __unused mach_port_t exception_port,
111 uint64_t thread_id,
112 mach_port_t task_id_token,
113 exception_type_t exception,
114 mach_exception_data_t codes,
115 mach_msg_type_number_t codeCnt)
116 {
117 #pragma unused(exception_port, thread_id, task_id_token)
118
119 T_ASSERT_GT_UINT(codeCnt, 0, "CodeCnt");
120
121 T_LOG("Caught exception type: %d code: 0x%llx", exception, codes[0]);
122 exception_taken = exception;
123 if (exception == EXC_GUARD) {
124 received_exception_code = EXC_GUARD_DECODE_GUARD_FLAVOR((uint64_t)codes[0]);
125 } else {
126 T_FAIL("Unexpected exception");
127 }
128 return KERN_SUCCESS;
129 }
130
131 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)132 catch_mach_exception_raise(mach_port_t exception_port,
133 mach_port_t thread,
134 mach_port_t task,
135 exception_type_t exception,
136 mach_exception_data_t code,
137 mach_msg_type_number_t code_count)
138 {
139 #pragma unused(exception_port, thread, task, exception, code, code_count)
140 T_FAIL("Unsupported catch_mach_exception_raise_state_identity");
141 return KERN_NOT_SUPPORTED;
142 }
143
144 static void *
exception_server_thread(void * arg)145 exception_server_thread(void *arg)
146 {
147 kern_return_t kr;
148 mach_port_t exc_port = *(mach_port_t *)arg;
149
150 /* Handle exceptions on exc_port */
151 kr = mach_msg_server_once(mach_exc_server, 4096, exc_port, 0);
152 T_QUIET; T_EXPECT_MACH_SUCCESS(kr, "mach_msg_server_once");
153
154 return NULL;
155 }
156
157 static void
reply_port_defense(const bool thirdparty_hardened,int test_index,mach_exception_data_type_t expected_exception_code,bool triggers_exception)158 reply_port_defense(const bool thirdparty_hardened, int test_index, mach_exception_data_type_t expected_exception_code, bool triggers_exception)
159 {
160 int ret = 0;
161
162 uint32_t task_exc_guard = 0;
163 size_t te_size = sizeof(&task_exc_guard);
164
165 /* Test that the behavior is the same between these two */
166 char *test_prog_name = thirdparty_hardened ?
167 "./reply_port_defense_client_3P_hardened" : "./reply_port_defense_client";
168 char *child_args[MAX_ARGV];
169 pid_t client_pid = 0;
170 posix_spawnattr_t attrs;
171
172 pthread_t s_exc_thread;
173 mach_port_t exc_port;
174
175 T_LOG("Check if task_exc_guard exception has been enabled\n");
176 ret = sysctlbyname("kern.task_exc_guard_default", &task_exc_guard, &te_size, NULL, 0);
177 T_ASSERT_EQ(ret, 0, "sysctlbyname");
178
179 if (!(task_exc_guard & TASK_EXC_GUARD_MP_DELIVER)) {
180 T_SKIP("task_exc_guard exception is not enabled");
181 }
182
183 exc_port = alloc_exception_port();
184 T_QUIET; T_ASSERT_NE(exc_port, MACH_PORT_NULL, "Create a new exception port");
185
186 /* Create exception serving thread */
187 ret = pthread_create(&s_exc_thread, NULL, exception_server_thread, &exc_port);
188 T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "pthread_create exception_server_thread");
189
190 /* Initialize posix_spawn attributes */
191 posix_spawnattr_init(&attrs);
192
193 /*
194 * It is allowed for us to set an exception port because we are entitled test process.
195 * If you are using this code as an example for platform binaries,
196 * use `EXCEPTION_IDENTITY_PROTECTED` instead of `EXCEPTION_DEFAULT`
197 */
198 int err = posix_spawnattr_setexceptionports_np(&attrs, EXC_MASK_GUARD, exc_port,
199 (exception_behavior_t) (EXCEPTION_IDENTITY_PROTECTED | MACH_EXCEPTION_CODES), 0);
200 T_QUIET; T_ASSERT_POSIX_SUCCESS(err, "posix_spawnattr_setflags");
201
202 child_args[0] = test_prog_name;
203 char test_num[10];
204 sprintf(test_num, "%d", test_index);
205 child_args[1] = test_num;
206 child_args[2] = NULL;
207
208 T_LOG("========== Spawning new child ==========");
209 err = posix_spawn(&client_pid, child_args[0], NULL, &attrs, &child_args[0], environ);
210 T_ASSERT_POSIX_SUCCESS(err, "posix_spawn reply_port_defense_client = %d", client_pid);
211
212 int child_status;
213 /* Wait for child and check for exception */
214 if (-1 == waitpid(-1, &child_status, 0)) {
215 T_FAIL("%s waitpid: child", strerror(errno));
216 }
217 if (WIFEXITED(child_status) && WEXITSTATUS(child_status)) {
218 T_FAIL("Child exited with status = 0x%x", child_status);
219 }
220 sleep(1);
221 kill(1, SIGKILL);
222 if (triggers_exception) {
223 ret = pthread_join(s_exc_thread, NULL);
224 T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "pthread_join");
225 }
226
227 mach_port_deallocate(mach_task_self(), exc_port);
228
229 T_LOG("Exception code: Received code = 0x%llx Expected code = 0x%llx", received_exception_code, expected_exception_code);
230 T_EXPECT_EQ(received_exception_code, expected_exception_code, "Exception code: Received == Expected");
231 }
232
233 T_DECL(reply_port_defense,
234 "Test reply port semantics violations",
235 T_META_IGNORECRASHES(".*reply_port_defense_client.*"),
236 T_META_CHECK_LEAKS(false),
237 T_META_TAG_VM_NOT_PREFERRED) {
238 bool triggers_exception = true;
239 /* The first test is setup as moving immovable receive right of a reply port. */
240 reply_port_defense(true, 0, kGUARD_EXC_IMMOVABLE, triggers_exception);
241 reply_port_defense(false, 0, kGUARD_EXC_IMMOVABLE, triggers_exception);
242
243 int rp_defense_max_test_idx = 3;
244 /* Run the reply_port_defense tests 1, 2, and 3 */
245 mach_exception_data_type_t expected_exception_code = kGUARD_EXC_INVALID_RIGHT;
246 for (int i = 1; i <= rp_defense_max_test_idx; i++) {
247 reply_port_defense(true, i, expected_exception_code, triggers_exception);
248 reply_port_defense(false, i, expected_exception_code, triggers_exception);
249 }
250 }
251
252 T_DECL(test_move_provisional_reply_port,
253 "provisional reply ports are movable",
254 T_META_IGNORECRASHES(".*reply_port_defense_client.*"),
255 T_META_CHECK_LEAKS(false),
256 T_META_ENABLED(TARGET_OS_OSX || TARGET_OS_BRIDGE)) {
257 int test_num = 4;
258 mach_exception_data_type_t expected_exception_code = 0;
259 bool triggers_exception = false;
260
261 reply_port_defense(true, test_num, expected_exception_code, triggers_exception);
262 reply_port_defense(false, test_num, expected_exception_code, triggers_exception);
263 }
264
265 T_DECL(test_unentitled_thread_set_exception_ports,
266 "thread_set_exception_ports should fail without an entitlement",
267 T_META_IGNORECRASHES(".*reply_port_defense_client.*"),
268 T_META_CHECK_LEAKS(false)) {
269 int test_num = 5;
270 mach_exception_data_type_t expected_exception_code = kGUARD_EXC_EXCEPTION_BEHAVIOR_ENFORCE;
271 bool triggers_exception = true;
272
273 #if TARGET_OS_OSX
274 T_SKIP("Test disabled on macOS due to SIP disabled and AMFI boot args usage on BATS");
275 /*
276 * CS_CONFIG_GET_OUT_OF_MY_WAY (enabled via AMFI boot-args)
277 * disables this security feature. This boot-arg previously
278 * caused a headache for developers on macos, who frequently use it for
279 * testing purposes, because all of their 3rd party apps will
280 * crash due to being treated as platform code. Unfortunately
281 * BATS runs with this boot-arg enabled.
282 */
283 code_signing_config_t cs_config = 0;
284 size_t cs_config_size = sizeof(cs_config);
285 sysctlbyname("security.codesigning.config", &cs_config, &cs_config_size, NULL, 0);
286 if (cs_config & CS_CONFIG_GET_OUT_OF_MY_WAY) {
287 expected_exception_code = 0;
288 triggers_exception = false;
289 T_LOG("task identity security policy for thread_set_exception_ports"
290 " disabled due to AMFI boot-args.");
291 } else
292 #endif /* TARGET_OS_OSX */
293 {
294 T_LOG("task identity security policy for thread_set_exception_ports enabled");
295 }
296
297 reply_port_defense(true, test_num, expected_exception_code, triggers_exception);
298 reply_port_defense(false, test_num, expected_exception_code, triggers_exception);
299 }
300
301 T_DECL(test_unentitled_thread_set_state,
302 "thread_set_state should fail without an entitlement",
303 T_META_IGNORECRASHES(".*reply_port_defense_client.*"),
304 T_META_CHECK_LEAKS(false),
305 T_META_ENABLED(false /* rdar://133955889 */))
306 {
307 int test_num = 6;
308 mach_exception_data_type_t expected_exception_code = (mach_exception_data_type_t)kGUARD_EXC_THREAD_SET_STATE;
309 bool triggers_exception = true;
310
311 #if TARGET_OS_OSX
312 T_SKIP("Test disabled on macOS due to mach hardening opt out");
313 #endif /* TARGET_OS_OSX */
314
315 reply_port_defense(true, test_num, expected_exception_code, triggers_exception);
316 reply_port_defense(false, test_num, expected_exception_code, triggers_exception);
317 }
318
319 T_DECL(unentitled_set_exception_ports_pass,
320 "set_exception_ports should succeed",
321 T_META_IGNORECRASHES(".*reply_port_defense_client.*"),
322 T_META_CHECK_LEAKS(false)) {
323 int test_num = 7;
324 mach_exception_data_type_t expected_exception_code = (mach_exception_data_type_t)0;
325 bool triggers_exception = false;
326 reply_port_defense(true, test_num, expected_exception_code, triggers_exception);
327 reply_port_defense(false, test_num, expected_exception_code, triggers_exception);
328 }
329
330
331 T_DECL(kobject_reply_port_defense,
332 "sending messages to kobjects without a proper reply port should crash",
333 T_META_IGNORECRASHES(".*reply_port_defense_client.*"),
334 T_META_CHECK_LEAKS(false),
335 T_META_ENABLED(!TARGET_OS_OSX)) { /* disable on macOS due to BATS boot-args */
336 int test_num = 9;
337 #if __x86_64__
338 mach_exception_data_type_t expected_exception_code = (mach_exception_data_type_t)kGUARD_EXC_REQUIRE_REPLY_PORT_SEMANTICS;
339 #else
340 mach_exception_data_type_t expected_exception_code = (mach_exception_data_type_t)kGUARD_EXC_SEND_INVALID_REPLY;
341 #endif
342 bool triggers_exception = true;
343 reply_port_defense(true, test_num, expected_exception_code, triggers_exception);
344 reply_port_defense(false, test_num, expected_exception_code, triggers_exception);
345 }
346
347 T_DECL(test_alloc_provisional_reply_port,
348 "1p is not allowed to create provisional reply ports on iOS+",
349 T_META_IGNORECRASHES(".*reply_port_defense_client.*"),
350 T_META_CHECK_LEAKS(false),
351 T_META_ENABLED(!TARGET_OS_OSX && !TARGET_OS_BRIDGE && !TARGET_OS_XR)) {
352 int test_num = 10;
353 mach_exception_data_type_t expected_exception_code = kGUARD_EXC_PROVISIONAL_REPLY_PORT;
354 bool triggers_exception = true;
355
356 /* rdar://136996362 (iOS+ telemetry for restricting 1P usage of provisional reply port) */
357 reply_port_defense(true, test_num, expected_exception_code, triggers_exception);
358 reply_port_defense(false, test_num, expected_exception_code, triggers_exception);
359 }
360