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