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