xref: /xnu-8792.81.2/libsyscall/wrappers/spawn/posix_spawn_filtering.c (revision 19c3b8c28c31cb8130e034cfb5df6bf9ba342d90)
1 /*
2  * Copyright (c) 2021 Apple Inc. All rights reserved.
3  *
4  * @APPLE_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. Please obtain a copy of the License at
10  * http://www.opensource.apple.com/apsl/ and read it before using this
11  * file.
12  *
13  * The Original Code and all software distributed under the License are
14  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18  * Please see the License for the specific language governing rights and
19  * limitations under the License.
20  *
21  * @APPLE_LICENSE_HEADER_END@
22  */
23 
24 #include <spawn.h>
25 #include <spawn_private.h>
26 #include <sys/spawn_internal.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <strings.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <unistd.h>
33 
34 extern void __posix_spawnattr_init(struct _posix_spawnattr *psattrp);
35 
36 /*
37  * Actual syscall wrappers.
38  */
39 extern int __posix_spawn(pid_t * __restrict, const char * __restrict,
40     struct _posix_spawn_args_desc *, char *const argv[__restrict],
41     char *const envp[__restrict]);
42 extern int __execve(const char *fname, char * const *argp, char * const *envp);
43 extern int __open_nocancel(const char *path, int oflag, mode_t mode);
44 extern ssize_t __read_nocancel(int, void *, size_t);
45 extern int __close_nocancel(int fd);
46 
47 static const char *
_simple_getenv(char * const * envp,const char * var)48 _simple_getenv(char * const *envp, const char *var)
49 {
50 	size_t var_len = strlen(var);
51 
52 	for (char * const *p = envp; p && *p; p++) {
53 		size_t p_len = strlen(*p);
54 
55 		if (p_len >= var_len && memcmp(*p, var, var_len) == 0 &&
56 		    (*p)[var_len] == '=') {
57 			return &(*p)[var_len + 1];
58 		}
59 	}
60 
61 	return NULL;
62 }
63 
64 /*
65  * Read filtering rules from /usr/local/share/posix_spawn_filtering_rules, and
66  * if the target being launched matches, apply changes to the posix_spawn
67  * request. Example contents of the file:
68  *
69  * binary_name:Calculator
70  * binary_name:ld
71  * path_start:/opt/bin/
72  * add_env:DYLD_INSERT_LIBRARIES=/usr/lib/libgmalloc.dylib
73  * binpref:x86_64
74  * alt_rosetta:1
75  *
76  * In this case, if we're launching either Calculator or ld, or anything in
77  * /opt/bin (arbitrarily deep), DYLD_INSERT_LIBRARIES=/usr/lib/libgmalloc.dylib
78  * will be added to the environment of the target, it will be launched with
79  * x86_64 binpref, and alternative rosetta runtime.
80  *
81  * Unrecognized lines are silently skipped. All lines must be 1023 characters
82  * or shorter.
83  *
84  * We need to be careful in this codepath (and in all called functions) because
85  * we can be called as part of execve() and that's required to be
86  * async-signal-safe by POSIX. We're also replacing one syscall with multiple,
87  * so we need to watch out to preserve cancellation/EINTR semantics, and avoid
88  * changing errno.
89  */
90 static bool
evaluate_rules(const char * rules_file_path,const char * fname,char ** envs,size_t envs_capacity,char * env_storage,size_t env_storage_capacity,cpu_type_t * type,cpu_subtype_t * subtype,uint32_t * psa_options)91 evaluate_rules(const char *rules_file_path, const char *fname, char **envs,
92     size_t envs_capacity, char *env_storage, size_t env_storage_capacity,
93     cpu_type_t *type, cpu_subtype_t *subtype, uint32_t *psa_options)
94 {
95 	int saveerrno = errno;
96 	int fd = -1;
97 
98 	/*
99 	 * Preflight check on rules_file_path to avoid triggering sandbox reports in
100 	 * case the process doesn't have access. We don't care about TOCTOU here.
101 	 *
102 	 * access() does not have a cancellation point, so it's already nocancel.
103 	 */
104 	if (access(rules_file_path, R_OK) != 0) {
105 		errno = saveerrno;
106 		return false;
107 	}
108 
109 	while (1) {
110 		fd = __open_nocancel(rules_file_path, O_RDONLY | O_CLOEXEC, 0);
111 		if (fd >= 0) {
112 			break;
113 		}
114 		if (errno == EINTR) {
115 			continue;
116 		}
117 		errno = saveerrno;
118 		return false;
119 	}
120 
121 	const char *fname_basename = fname;
122 	const char *slash_pos;
123 	while ((slash_pos = strchr(fname_basename, '/')) != NULL) {
124 		fname_basename = slash_pos + 1;
125 	}
126 
127 	bool fname_matches = false;
128 
129 	char read_buffer[1024];
130 	size_t bytes = 0;
131 	while (1) {
132 		if (sizeof(read_buffer) - bytes <= 0) {
133 			break;
134 		}
135 
136 		bzero(read_buffer + bytes, sizeof(read_buffer) - bytes);
137 		size_t read_result = __read_nocancel(fd,
138 		    read_buffer + bytes, sizeof(read_buffer) - bytes);
139 
140 		if (read_result == 0) {
141 			break;
142 		} else if (read_result < 0) {
143 			if (errno == EINTR) {
144 				continue;
145 			} else {
146 				break;
147 			}
148 		}
149 		bytes += read_result;
150 
151 		while (bytes > 0) {
152 			char *newline_pos = memchr(read_buffer, '\n', bytes);
153 			if (newline_pos == NULL) {
154 				break;
155 			}
156 
157 			char *line = read_buffer;
158 			size_t line_length = newline_pos - read_buffer;
159 			*newline_pos = '\0';
160 
161 			/* 'line' now has a NUL-terminated string of 1023 chars max */
162 			if (memcmp(line, "binary_name:", strlen("binary_name:")) == 0) {
163 				char *binary_name = line + strlen("binary_name:");
164 				if (strcmp(fname_basename, binary_name) == 0) {
165 					fname_matches = true;
166 				}
167 			} else if (memcmp(line, "path_start:", strlen("path_start:")) == 0) {
168 				char *path_start = line + strlen("path_start:");
169 				if (strncmp(fname, path_start, strlen(path_start)) == 0) {
170 					fname_matches = true;
171 				}
172 			} else if (memcmp(line, "add_env:", strlen("add_env:")) == 0) {
173 				char *add_env = line + strlen("add_env:");
174 				size_t env_size = strlen(add_env) + 1;
175 				if (env_storage_capacity >= env_size && envs_capacity > 0) {
176 					memcpy(env_storage, add_env, env_size);
177 					envs[0] = env_storage;
178 
179 					envs += 1;
180 					envs_capacity -= 1;
181 					env_storage += env_size;
182 					env_storage_capacity -= env_size;
183 				}
184 			} else if (memcmp(line, "binpref:", strlen("binpref:")) == 0) {
185 				char *binpref = line + strlen("binpref:");
186 				if (strcmp(binpref, "x86_64") == 0) {
187 					*type = CPU_TYPE_X86_64;
188 					*subtype = CPU_SUBTYPE_ANY;
189 				}
190 			} else if (memcmp(line, "alt_rosetta:", strlen("alt_rosetta:")) == 0) {
191 				char *alt_rosetta = line + strlen("alt_rosetta:");
192 				if (strcmp(alt_rosetta, "1") == 0) {
193 					*psa_options |= PSA_OPTION_ALT_ROSETTA;
194 				}
195 			}
196 
197 			memmove(read_buffer, newline_pos + 1, sizeof(read_buffer) - line_length);
198 			bytes -= line_length + 1;
199 		}
200 	}
201 
202 	__close_nocancel(fd);
203 	errno = saveerrno;
204 	return fname_matches;
205 }
206 
207 /*
208  * Apply posix_spawn filtering rules, and invoke a possibly modified posix_spawn
209  * call. Returns true if the posix_spawn was handled/invoked (and populates the
210  * 'ret' outparam in that case), false if the filter does not apply and the
211  * caller should proceed to call posix_spawn/exec normally.
212  *
213  * We need to be careful in this codepath (and in all called functions) because
214  * we can be called as part of execve() and that's required to be
215  * async-signal-safe by POSIX. We're also replacing one syscall with multiple,
216  * so we need to watch out to preserve cancellation/EINTR semantics, and avoid
217  * changing errno.
218  */
219 __attribute__((visibility("hidden")))
220 bool
_posix_spawn_with_filter(pid_t * pid,const char * fname,char * const * argp,char * const * envp,struct _posix_spawn_args_desc * adp,int * ret)221 _posix_spawn_with_filter(pid_t *pid, const char *fname, char * const *argp,
222     char * const *envp, struct _posix_spawn_args_desc *adp, int *ret)
223 {
224 	/*
225 	 * For testing, the path to the rules file can be overridden with an env var.
226 	 * It's hard to get access to 'environ' or '_NSGetEnviron' here so instead
227 	 * peek into the envp arg of posix_spawn/exec, even though we should really
228 	 * inspect the parent's env instead. For testing only purposes, it's fine.
229 	 */
230 	const char *rules_file_path =
231 	    _simple_getenv(envp, "POSIX_SPAWN_FILTERING_RULES_PATH")
232 	    ?: "/usr/local/share/posix_spawn_filtering_rules";
233 
234 	/*
235 	 * Stack-allocated storage for extra env vars to add to the posix_spawn call.
236 	 * 16 env vars, and 1024 bytes total should be enough for everyone.
237 	 */
238   #define MAX_EXTRA_ENVS 16
239   #define MAX_ENV_STORAGE_SIZE 1024
240 	char env_storage[MAX_ENV_STORAGE_SIZE];
241 	bzero(env_storage, sizeof(env_storage));
242 	char *envs_to_add[MAX_EXTRA_ENVS];
243 	bzero(envs_to_add, sizeof(envs_to_add));
244 	cpu_type_t cputype_binpref = 0;
245 	cpu_subtype_t cpusubtype_binpref = 0;
246 	uint32_t psa_options = 0;
247 	bool should_apply_rules = evaluate_rules(rules_file_path, fname,
248 	    envs_to_add, sizeof(envs_to_add) / sizeof(envs_to_add[0]),
249 	    env_storage, sizeof(env_storage),
250 	    &cputype_binpref, &cpusubtype_binpref,
251 	    &psa_options);
252 
253 	if (!should_apply_rules) {
254 		return false;
255 	}
256 
257 	/*
258 	 * Create stack-allocated private copies of args_desc and spawnattr_t structs
259 	 * that we can modify.
260 	 */
261 	struct _posix_spawn_args_desc new_ad;
262 	bzero(&new_ad, sizeof(new_ad));
263 	struct _posix_spawnattr new_attr;
264 	__posix_spawnattr_init(&new_attr);
265 	if (adp != NULL) {
266 		memcpy(&new_ad, adp, sizeof(new_ad));
267 	}
268 	if (new_ad.attrp != NULL) {
269 		memcpy(&new_attr, new_ad.attrp, sizeof(new_attr));
270 	}
271 	new_ad.attrp = &new_attr;
272 
273 	/*
274 	 * Now 'new_ad' and 'new_attr' are always non-NULL and okay to be modified.
275 	 */
276 	if (cputype_binpref != 0) {
277 		for (int i = 0; i < NBINPREFS; i++) {
278 			new_attr.psa_binprefs[i] = 0;
279 			new_attr.psa_subcpuprefs[i] = CPU_SUBTYPE_ANY;
280 		}
281 		new_attr.psa_binprefs[0] = cputype_binpref;
282 		new_attr.psa_subcpuprefs[0] = cpusubtype_binpref;
283 	}
284 
285 	if (psa_options != 0) {
286 		new_attr.psa_options |= psa_options;
287 	}
288 
289 	/*
290 	 * Count old envs.
291 	 */
292 	size_t envp_count = 0;
293 	char *const *ep = envp;
294 	while (*ep++) {
295 		envp_count += 1;
296 	}
297 
298 	/*
299 	 * Count envs to add.
300 	 */
301 	size_t envs_to_add_count = 0;
302 	ep = envs_to_add;
303 	while (envs_to_add_count < MAX_EXTRA_ENVS && *ep++) {
304 		envs_to_add_count += 1;
305 	}
306 
307 	/*
308 	 * Make enough room for old and new envs plus NULL at the end.
309 	 */
310 	char *new_envp[envs_to_add_count + envp_count + 1];
311 
312 	/*
313 	 * Prepend the new envs so that they get picked up by Libc's getenv and common
314 	 * simple_getenv implementations. It's technically undefined what happens if
315 	 * a name occurs multiple times, but the common implementations pick the first
316 	 * entry.
317 	 */
318 	bzero(&new_envp[0], sizeof(new_envp));
319 	memcpy(&new_envp[0], &envs_to_add[0], envs_to_add_count * sizeof(void *));
320 	memcpy(&new_envp[envs_to_add_count], envp, envp_count * sizeof(void *));
321 
322 	*ret = __posix_spawn(pid, fname, &new_ad, argp, new_envp);
323 	return true;
324 }
325 
326 __attribute__((visibility("hidden")))
327 int
_execve_with_filter(const char * fname,char * const * argp,char * const * envp)328 _execve_with_filter(const char *fname, char * const *argp, char * const *envp)
329 {
330 	int ret = 0;
331 
332 	/*
333 	 * Rewrite the execve() call into a posix_spawn(SETEXEC) call. We need to be
334 	 * careful in this codepath (and in all called functions) because execve is
335 	 * required to be async-signal-safe by POSIX.
336 	 */
337 	struct _posix_spawn_args_desc ad;
338 	bzero(&ad, sizeof(ad));
339 
340 	struct _posix_spawnattr attr;
341 	__posix_spawnattr_init(&attr);
342 	attr.psa_flags |= POSIX_SPAWN_SETEXEC;
343 
344 	ad.attrp = &attr;
345 	ad.attr_size = sizeof(struct _posix_spawnattr);
346 
347 	if (_posix_spawn_with_filter(NULL, fname, argp, envp, &ad, &ret)) {
348 		if (ret == 0) {
349 			return 0;
350 		} else {
351 			errno = ret;
352 			return -1;
353 		}
354 	}
355 
356 	ret = __execve(fname, argp, envp);
357 	return ret;
358 }
359