xref: /xnu-12377.1.9/bsd/kern/ubc_subr.c (revision f6217f891ac0bb64f3d375211650a4c1ff8ca1ea)
1 /*
2  * Copyright (c) 1999-2020 Apple 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  *	File:	ubc_subr.c
30  *	Author:	Umesh Vaishampayan [[email protected]]
31  *		05-Aug-1999	umeshv	Created.
32  *
33  *	Functions related to Unified Buffer cache.
34  *
35  * Caller of UBC functions MUST have a valid reference on the vnode.
36  *
37  */
38 
39 #include <sys/types.h>
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/lock.h>
43 #include <sys/mman.h>
44 #include <sys/mount_internal.h>
45 #include <sys/vnode_internal.h>
46 #include <sys/ubc_internal.h>
47 #include <sys/ucred.h>
48 #include <sys/proc_internal.h>
49 #include <sys/kauth.h>
50 #include <sys/buf.h>
51 #include <sys/user.h>
52 #include <sys/codesign.h>
53 #include <sys/codedir_internal.h>
54 #include <sys/fsevents.h>
55 #include <sys/fcntl.h>
56 #include <sys/reboot.h>
57 #include <sys/code_signing.h>
58 
59 #include <mach/mach_types.h>
60 #include <mach/memory_object_types.h>
61 #include <mach/memory_object_control.h>
62 #include <mach/vm_map.h>
63 #include <mach/mach_vm.h>
64 #include <mach/upl.h>
65 
66 #include <kern/kern_types.h>
67 #include <kern/kalloc.h>
68 #include <kern/zalloc.h>
69 #include <kern/thread.h>
70 #include <vm/pmap.h>
71 #include <vm/vm_pageout.h>
72 #include <vm/vm_map.h>
73 #include <vm/vm_upl.h>
74 #include <vm/vm_kern_xnu.h>
75 #include <vm/vm_protos.h> /* last */
76 #include <vm/vm_ubc.h>
77 
78 #include <libkern/crypto/sha1.h>
79 #include <libkern/crypto/sha2.h>
80 #include <libkern/libkern.h>
81 
82 #include <security/mac_framework.h>
83 #include <stdbool.h>
84 #include <stdatomic.h>
85 #include <libkern/amfi/amfi.h>
86 
87 extern void Debugger(const char *message);
88 
89 #if DIAGNOSTIC
90 #if defined(assert)
91 #undef assert
92 #endif
93 #define assert(cond)    \
94     ((void) ((cond) ? 0 : panic("Assert failed: %s", # cond)))
95 #else
96 #include <kern/assert.h>
97 #endif /* DIAGNOSTIC */
98 
99 static int ubc_info_init_internal(struct vnode *vp, int withfsize, off_t filesize);
100 static int ubc_umcallback(vnode_t, void *);
101 static int ubc_msync_internal(vnode_t, off_t, off_t, off_t *, int, int *);
102 static void ubc_cs_free(struct ubc_info *uip);
103 
104 static boolean_t ubc_cs_supports_multilevel_hash(struct cs_blob *blob);
105 static kern_return_t ubc_cs_convert_to_multilevel_hash(struct cs_blob *blob);
106 
107 ZONE_DEFINE_TYPE(ubc_info_zone, "ubc_info zone", struct ubc_info,
108     ZC_ZFREE_CLEARMEM);
109 static uint32_t cs_blob_generation_count = 1;
110 
111 /*
112  * CODESIGNING
113  * Routines to navigate code signing data structures in the kernel...
114  */
115 
116 ZONE_DEFINE_ID(ZONE_ID_CS_BLOB, "cs_blob zone", struct cs_blob,
117     ZC_READONLY | ZC_ZFREE_CLEARMEM);
118 
119 extern int cs_debug;
120 
121 #define PAGE_SHIFT_4K           (12)
122 
123 static boolean_t
cs_valid_range(const void * start,const void * end,const void * lower_bound,const void * upper_bound)124 cs_valid_range(
125 	const void *start,
126 	const void *end,
127 	const void *lower_bound,
128 	const void *upper_bound)
129 {
130 	if (upper_bound < lower_bound ||
131 	    end < start) {
132 		return FALSE;
133 	}
134 
135 	if (start < lower_bound ||
136 	    end > upper_bound) {
137 		return FALSE;
138 	}
139 
140 	return TRUE;
141 }
142 
143 typedef void (*cs_md_init)(void *ctx);
144 typedef void (*cs_md_update)(void *ctx, const void *data, size_t size);
145 typedef void (*cs_md_final)(void *hash, void *ctx);
146 
147 struct cs_hash {
148 	uint8_t             cs_type;    /* type code as per code signing */
149 	size_t              cs_size;    /* size of effective hash (may be truncated) */
150 	size_t              cs_digest_size;/* size of native hash */
151 	cs_md_init          cs_init;
152 	cs_md_update        cs_update;
153 	cs_md_final         cs_final;
154 };
155 
156 uint8_t
cs_hash_type(struct cs_hash const * const cs_hash)157 cs_hash_type(
158 	struct cs_hash const * const cs_hash)
159 {
160 	return cs_hash->cs_type;
161 }
162 
163 static const struct cs_hash cs_hash_sha1 = {
164 	.cs_type = CS_HASHTYPE_SHA1,
165 	.cs_size = CS_SHA1_LEN,
166 	.cs_digest_size = SHA_DIGEST_LENGTH,
167 	.cs_init = (cs_md_init)SHA1Init,
168 	.cs_update = (cs_md_update)SHA1Update,
169 	.cs_final = (cs_md_final)SHA1Final,
170 };
171 #if CRYPTO_SHA2
172 static const struct cs_hash cs_hash_sha256 = {
173 	.cs_type = CS_HASHTYPE_SHA256,
174 	.cs_size = SHA256_DIGEST_LENGTH,
175 	.cs_digest_size = SHA256_DIGEST_LENGTH,
176 	.cs_init = (cs_md_init)SHA256_Init,
177 	.cs_update = (cs_md_update)SHA256_Update,
178 	.cs_final = (cs_md_final)SHA256_Final,
179 };
180 static const struct cs_hash cs_hash_sha256_truncate = {
181 	.cs_type = CS_HASHTYPE_SHA256_TRUNCATED,
182 	.cs_size = CS_SHA256_TRUNCATED_LEN,
183 	.cs_digest_size = SHA256_DIGEST_LENGTH,
184 	.cs_init = (cs_md_init)SHA256_Init,
185 	.cs_update = (cs_md_update)SHA256_Update,
186 	.cs_final = (cs_md_final)SHA256_Final,
187 };
188 static const struct cs_hash cs_hash_sha384 = {
189 	.cs_type = CS_HASHTYPE_SHA384,
190 	.cs_size = SHA384_DIGEST_LENGTH,
191 	.cs_digest_size = SHA384_DIGEST_LENGTH,
192 	.cs_init = (cs_md_init)SHA384_Init,
193 	.cs_update = (cs_md_update)SHA384_Update,
194 	.cs_final = (cs_md_final)SHA384_Final,
195 };
196 #endif
197 
198 static struct cs_hash const *
cs_find_md(uint8_t type)199 cs_find_md(uint8_t type)
200 {
201 	if (type == CS_HASHTYPE_SHA1) {
202 		return &cs_hash_sha1;
203 #if CRYPTO_SHA2
204 	} else if (type == CS_HASHTYPE_SHA256) {
205 		return &cs_hash_sha256;
206 	} else if (type == CS_HASHTYPE_SHA256_TRUNCATED) {
207 		return &cs_hash_sha256_truncate;
208 	} else if (type == CS_HASHTYPE_SHA384) {
209 		return &cs_hash_sha384;
210 #endif
211 	}
212 	return NULL;
213 }
214 
215 union cs_hash_union {
216 	SHA1_CTX                sha1ctxt;
217 	SHA256_CTX              sha256ctx;
218 	SHA384_CTX              sha384ctx;
219 };
220 
221 
222 /*
223  * Choose among different hash algorithms.
224  * Higher is better, 0 => don't use at all.
225  */
226 static const uint32_t hashPriorities[] = {
227 	CS_HASHTYPE_SHA1,
228 	CS_HASHTYPE_SHA256_TRUNCATED,
229 	CS_HASHTYPE_SHA256,
230 	CS_HASHTYPE_SHA384,
231 };
232 
233 static unsigned int
hash_rank(const CS_CodeDirectory * cd)234 hash_rank(const CS_CodeDirectory *cd)
235 {
236 	uint32_t type = cd->hashType;
237 	unsigned int n;
238 
239 	for (n = 0; n < sizeof(hashPriorities) / sizeof(hashPriorities[0]); ++n) {
240 		if (hashPriorities[n] == type) {
241 			return n + 1;
242 		}
243 	}
244 	return 0;       /* not supported */
245 }
246 
247 
248 /*
249  * Locating a page hash
250  */
251 static const unsigned char *
hashes(const CS_CodeDirectory * cd,uint32_t page,size_t hash_len,const char * lower_bound,const char * upper_bound)252 hashes(
253 	const CS_CodeDirectory *cd,
254 	uint32_t page,
255 	size_t hash_len,
256 	const char *lower_bound,
257 	const char *upper_bound)
258 {
259 	const unsigned char *base, *top, *hash;
260 	uint32_t nCodeSlots = ntohl(cd->nCodeSlots);
261 
262 	assert(cs_valid_range(cd, cd + 1, lower_bound, upper_bound));
263 
264 	if ((ntohl(cd->version) >= CS_SUPPORTSSCATTER) && (ntohl(cd->scatterOffset))) {
265 		/* Get first scatter struct */
266 		const SC_Scatter *scatter = (const SC_Scatter*)
267 		    ((const char*)cd + ntohl(cd->scatterOffset));
268 		uint32_t hashindex = 0, scount, sbase = 0;
269 		/* iterate all scatter structs */
270 		do {
271 			if ((const char*)scatter > (const char*)cd + ntohl(cd->length)) {
272 				if (cs_debug) {
273 					printf("CODE SIGNING: Scatter extends past Code Directory\n");
274 				}
275 				return NULL;
276 			}
277 
278 			scount = ntohl(scatter->count);
279 			uint32_t new_base = ntohl(scatter->base);
280 
281 			/* last scatter? */
282 			if (scount == 0) {
283 				return NULL;
284 			}
285 
286 			if ((hashindex > 0) && (new_base <= sbase)) {
287 				if (cs_debug) {
288 					printf("CODE SIGNING: unordered Scatter, prev base %d, cur base %d\n",
289 					    sbase, new_base);
290 				}
291 				return NULL;    /* unordered scatter array */
292 			}
293 			sbase = new_base;
294 
295 			/* this scatter beyond page we're looking for? */
296 			if (sbase > page) {
297 				return NULL;
298 			}
299 
300 			if (sbase + scount >= page) {
301 				/* Found the scatter struct that is
302 				 * referencing our page */
303 
304 				/* base = address of first hash covered by scatter */
305 				base = (const unsigned char *)cd + ntohl(cd->hashOffset) +
306 				    hashindex * hash_len;
307 				/* top = address of first hash after this scatter */
308 				top = base + scount * hash_len;
309 				if (!cs_valid_range(base, top, lower_bound,
310 				    upper_bound) ||
311 				    hashindex > nCodeSlots) {
312 					return NULL;
313 				}
314 
315 				break;
316 			}
317 
318 			/* this scatter struct is before the page we're looking
319 			 * for. Iterate. */
320 			hashindex += scount;
321 			scatter++;
322 		} while (1);
323 
324 		hash = base + (page - sbase) * hash_len;
325 	} else {
326 		base = (const unsigned char *)cd + ntohl(cd->hashOffset);
327 		top = base + nCodeSlots * hash_len;
328 		if (!cs_valid_range(base, top, lower_bound, upper_bound) ||
329 		    page > nCodeSlots) {
330 			return NULL;
331 		}
332 		assert(page < nCodeSlots);
333 
334 		hash = base + page * hash_len;
335 	}
336 
337 	if (!cs_valid_range(hash, hash + hash_len,
338 	    lower_bound, upper_bound)) {
339 		hash = NULL;
340 	}
341 
342 	return hash;
343 }
344 
345 /*
346  * cs_validate_codedirectory
347  *
348  * Validate that pointers inside the code directory to make sure that
349  * all offsets and lengths are constrained within the buffer.
350  *
351  * Parameters:	cd			Pointer to code directory buffer
352  *		length			Length of buffer
353  *
354  * Returns:	0			Success
355  *		EBADEXEC		Invalid code signature
356  */
357 
358 static int
cs_validate_codedirectory(const CS_CodeDirectory * cd,size_t length)359 cs_validate_codedirectory(const CS_CodeDirectory *cd, size_t length)
360 {
361 	struct cs_hash const *hashtype;
362 
363 	if (length < sizeof(*cd)) {
364 		return EBADEXEC;
365 	}
366 	if (ntohl(cd->magic) != CSMAGIC_CODEDIRECTORY) {
367 		return EBADEXEC;
368 	}
369 	if ((cd->pageSize != PAGE_SHIFT_4K) && (cd->pageSize != PAGE_SHIFT)) {
370 		printf("disallowing unsupported code signature page shift: %u\n", cd->pageSize);
371 		return EBADEXEC;
372 	}
373 	hashtype = cs_find_md(cd->hashType);
374 	if (hashtype == NULL) {
375 		return EBADEXEC;
376 	}
377 
378 	if (cd->hashSize != hashtype->cs_size) {
379 		return EBADEXEC;
380 	}
381 
382 	if (length < ntohl(cd->hashOffset)) {
383 		return EBADEXEC;
384 	}
385 
386 	/* check that nSpecialSlots fits in the buffer in front of hashOffset */
387 	if (ntohl(cd->hashOffset) / hashtype->cs_size < ntohl(cd->nSpecialSlots)) {
388 		return EBADEXEC;
389 	}
390 
391 	/* check that codeslots fits in the buffer */
392 	if ((length - ntohl(cd->hashOffset)) / hashtype->cs_size < ntohl(cd->nCodeSlots)) {
393 		return EBADEXEC;
394 	}
395 
396 	if (ntohl(cd->version) >= CS_SUPPORTSSCATTER && cd->scatterOffset) {
397 		if (length < ntohl(cd->scatterOffset)) {
398 			return EBADEXEC;
399 		}
400 
401 		const SC_Scatter *scatter = (const SC_Scatter *)
402 		    (((const uint8_t *)cd) + ntohl(cd->scatterOffset));
403 		uint32_t nPages = 0;
404 
405 		/*
406 		 * Check each scatter buffer, since we don't know the
407 		 * length of the scatter buffer array, we have to
408 		 * check each entry.
409 		 */
410 		while (1) {
411 			/* check that the end of each scatter buffer in within the length */
412 			if (((const uint8_t *)scatter) + sizeof(scatter[0]) > (const uint8_t *)cd + length) {
413 				return EBADEXEC;
414 			}
415 			uint32_t scount = ntohl(scatter->count);
416 			if (scount == 0) {
417 				break;
418 			}
419 			if (nPages + scount < nPages) {
420 				return EBADEXEC;
421 			}
422 			nPages += scount;
423 			scatter++;
424 
425 			/* XXX check that basees doesn't overlap */
426 			/* XXX check that targetOffset doesn't overlap */
427 		}
428 #if 0 /* rdar://12579439 */
429 		if (nPages != ntohl(cd->nCodeSlots)) {
430 			return EBADEXEC;
431 		}
432 #endif
433 	}
434 
435 	if (length < ntohl(cd->identOffset)) {
436 		return EBADEXEC;
437 	}
438 
439 	/* identifier is NUL terminated string */
440 	if (cd->identOffset) {
441 		const uint8_t *ptr = (const uint8_t *)cd + ntohl(cd->identOffset);
442 		if (memchr(ptr, 0, length - ntohl(cd->identOffset)) == NULL) {
443 			return EBADEXEC;
444 		}
445 	}
446 
447 	/* team identifier is NULL terminated string */
448 	if (ntohl(cd->version) >= CS_SUPPORTSTEAMID && ntohl(cd->teamOffset)) {
449 		if (length < ntohl(cd->teamOffset)) {
450 			return EBADEXEC;
451 		}
452 
453 		const uint8_t *ptr = (const uint8_t *)cd + ntohl(cd->teamOffset);
454 		if (memchr(ptr, 0, length - ntohl(cd->teamOffset)) == NULL) {
455 			return EBADEXEC;
456 		}
457 	}
458 
459 	/* linkage is variable length binary data */
460 	if (ntohl(cd->version) >= CS_SUPPORTSLINKAGE && cd->linkageHashType != 0) {
461 		const uintptr_t ptr = (uintptr_t)cd + ntohl(cd->linkageOffset);
462 		const uintptr_t ptr_end = ptr + ntohl(cd->linkageSize);
463 
464 		if (ptr_end < ptr || ptr < (uintptr_t)cd || ptr_end > (uintptr_t)cd + length) {
465 			return EBADEXEC;
466 		}
467 	}
468 
469 
470 	return 0;
471 }
472 
473 /*
474  *
475  */
476 
477 static int
cs_validate_blob(const CS_GenericBlob * blob,size_t length)478 cs_validate_blob(const CS_GenericBlob *blob, size_t length)
479 {
480 	if (length < sizeof(CS_GenericBlob) || length < ntohl(blob->length)) {
481 		return EBADEXEC;
482 	}
483 	return 0;
484 }
485 
486 /*
487  * cs_validate_csblob
488  *
489  * Validate that superblob/embedded code directory to make sure that
490  * all internal pointers are valid.
491  *
492  * Will validate both a superblob csblob and a "raw" code directory.
493  *
494  *
495  * Parameters:	buffer			Pointer to code signature
496  *		length			Length of buffer
497  *		rcd			returns pointer to code directory
498  *
499  * Returns:	0			Success
500  *		EBADEXEC		Invalid code signature
501  */
502 
503 static int
cs_validate_csblob(const uint8_t * addr,const size_t blob_size,const CS_CodeDirectory ** rcd,const CS_GenericBlob ** rentitlements,const CS_GenericBlob ** rder_entitlements)504 cs_validate_csblob(
505 	const uint8_t *addr,
506 	const size_t blob_size,
507 	const CS_CodeDirectory **rcd,
508 	const CS_GenericBlob **rentitlements,
509 	const CS_GenericBlob **rder_entitlements)
510 {
511 	const CS_GenericBlob *blob;
512 	int error;
513 	size_t length;
514 	const CS_GenericBlob *self_constraint = NULL;
515 	const CS_GenericBlob *parent_constraint = NULL;
516 	const CS_GenericBlob *responsible_proc_constraint = NULL;
517 	const CS_GenericBlob *library_constraint = NULL;
518 
519 	*rcd = NULL;
520 	*rentitlements = NULL;
521 	*rder_entitlements = NULL;
522 
523 	blob = (const CS_GenericBlob *)(const void *)addr;
524 
525 	length = blob_size;
526 	error = cs_validate_blob(blob, length);
527 	if (error) {
528 		return error;
529 	}
530 	length = ntohl(blob->length);
531 
532 	if (ntohl(blob->magic) == CSMAGIC_EMBEDDED_SIGNATURE) {
533 		const CS_SuperBlob *sb;
534 		uint32_t n, count;
535 		const CS_CodeDirectory *best_cd = NULL;
536 		unsigned int best_rank = 0;
537 
538 		if (length < sizeof(CS_SuperBlob)) {
539 			return EBADEXEC;
540 		}
541 
542 		sb = (const CS_SuperBlob *)blob;
543 		count = ntohl(sb->count);
544 
545 		/* check that the array of BlobIndex fits in the rest of the data */
546 		if ((length - sizeof(CS_SuperBlob)) / sizeof(CS_BlobIndex) < count) {
547 			return EBADEXEC;
548 		}
549 
550 		/* now check each BlobIndex */
551 		for (n = 0; n < count; n++) {
552 			const CS_BlobIndex *blobIndex = &sb->index[n];
553 			uint32_t type = ntohl(blobIndex->type);
554 			uint32_t offset = ntohl(blobIndex->offset);
555 			if (length < offset) {
556 				return EBADEXEC;
557 			}
558 
559 			const CS_GenericBlob *subBlob =
560 			    (const CS_GenericBlob *)(const void *)(addr + offset);
561 
562 			size_t subLength = length - offset;
563 
564 			if ((error = cs_validate_blob(subBlob, subLength)) != 0) {
565 				return error;
566 			}
567 			subLength = ntohl(subBlob->length);
568 
569 			/* extra validation for CDs, that is also returned */
570 			if (type == CSSLOT_CODEDIRECTORY || (type >= CSSLOT_ALTERNATE_CODEDIRECTORIES && type < CSSLOT_ALTERNATE_CODEDIRECTORY_LIMIT)) {
571 				const CS_CodeDirectory *candidate = (const CS_CodeDirectory *)subBlob;
572 				if ((error = cs_validate_codedirectory(candidate, subLength)) != 0) {
573 					return error;
574 				}
575 				unsigned int rank = hash_rank(candidate);
576 				if (cs_debug > 3) {
577 					printf("CodeDirectory type %d rank %d at slot 0x%x index %d\n", candidate->hashType, (int)rank, (int)type, (int)n);
578 				}
579 				if (best_cd == NULL || rank > best_rank) {
580 					best_cd = candidate;
581 					best_rank = rank;
582 
583 					if (cs_debug > 2) {
584 						printf("using CodeDirectory type %d (rank %d)\n", (int)best_cd->hashType, best_rank);
585 					}
586 					*rcd = best_cd;
587 				} else if (best_cd != NULL && rank == best_rank) {
588 					/* repeat of a hash type (1:1 mapped to ranks), illegal and suspicious */
589 					printf("multiple hash=%d CodeDirectories in signature; rejecting\n", best_cd->hashType);
590 					return EBADEXEC;
591 				}
592 			} else if (type == CSSLOT_ENTITLEMENTS) {
593 				if (ntohl(subBlob->magic) != CSMAGIC_EMBEDDED_ENTITLEMENTS) {
594 					return EBADEXEC;
595 				}
596 				if (*rentitlements != NULL) {
597 					printf("multiple entitlements blobs\n");
598 					return EBADEXEC;
599 				}
600 				*rentitlements = subBlob;
601 			} else if (type == CSSLOT_DER_ENTITLEMENTS) {
602 				if (ntohl(subBlob->magic) != CSMAGIC_EMBEDDED_DER_ENTITLEMENTS) {
603 					return EBADEXEC;
604 				}
605 				if (*rder_entitlements != NULL) {
606 					printf("multiple der entitlements blobs\n");
607 					return EBADEXEC;
608 				}
609 				*rder_entitlements = subBlob;
610 			} else if (type == CSSLOT_LAUNCH_CONSTRAINT_SELF) {
611 				if (ntohl(subBlob->magic) != CSMAGIC_EMBEDDED_LAUNCH_CONSTRAINT) {
612 					return EBADEXEC;
613 				}
614 				if (self_constraint != NULL) {
615 					printf("multiple self constraint blobs\n");
616 					return EBADEXEC;
617 				}
618 				self_constraint = subBlob;
619 			} else if (type == CSSLOT_LAUNCH_CONSTRAINT_PARENT) {
620 				if (ntohl(subBlob->magic) != CSMAGIC_EMBEDDED_LAUNCH_CONSTRAINT) {
621 					return EBADEXEC;
622 				}
623 				if (parent_constraint != NULL) {
624 					printf("multiple parent constraint blobs\n");
625 					return EBADEXEC;
626 				}
627 				parent_constraint = subBlob;
628 			} else if (type == CSSLOT_LAUNCH_CONSTRAINT_RESPONSIBLE) {
629 				if (ntohl(subBlob->magic) != CSMAGIC_EMBEDDED_LAUNCH_CONSTRAINT) {
630 					return EBADEXEC;
631 				}
632 				if (responsible_proc_constraint != NULL) {
633 					printf("multiple responsible process constraint blobs\n");
634 					return EBADEXEC;
635 				}
636 				responsible_proc_constraint = subBlob;
637 			} else if (type == CSSLOT_LIBRARY_CONSTRAINT) {
638 				if (ntohl(subBlob->magic) != CSMAGIC_EMBEDDED_LAUNCH_CONSTRAINT) {
639 					return EBADEXEC;
640 				}
641 				if (library_constraint != NULL) {
642 					printf("multiple library constraint blobs\n");
643 					return EBADEXEC;
644 				}
645 				library_constraint = subBlob;
646 			}
647 		}
648 	} else if (ntohl(blob->magic) == CSMAGIC_CODEDIRECTORY) {
649 		if ((error = cs_validate_codedirectory((const CS_CodeDirectory *)(const void *)addr, length)) != 0) {
650 			return error;
651 		}
652 		*rcd = (const CS_CodeDirectory *)blob;
653 	} else {
654 		return EBADEXEC;
655 	}
656 
657 	if (*rcd == NULL) {
658 		return EBADEXEC;
659 	}
660 
661 	return 0;
662 }
663 
664 /*
665  * cs_find_blob_bytes
666  *
667  * Find an blob from the superblob/code directory. The blob must have
668  * been been validated by cs_validate_csblob() before calling
669  * this. Use csblob_find_blob() instead.
670  *
671  * Will also find a "raw" code directory if its stored as well as
672  * searching the superblob.
673  *
674  * Parameters:	buffer			Pointer to code signature
675  *		length			Length of buffer
676  *		type			type of blob to find
677  *		magic			the magic number for that blob
678  *
679  * Returns:	pointer			Success
680  *		NULL			Buffer not found
681  */
682 
683 const CS_GenericBlob *
csblob_find_blob_bytes(const uint8_t * addr,size_t length,uint32_t type,uint32_t magic)684 csblob_find_blob_bytes(const uint8_t *addr, size_t length, uint32_t type, uint32_t magic)
685 {
686 	const CS_GenericBlob *blob = (const CS_GenericBlob *)(const void *)addr;
687 
688 	if ((addr + length) < addr) {
689 		panic("CODE SIGNING: CS Blob length overflow for addr: %p", addr);
690 	}
691 
692 	if (ntohl(blob->magic) == CSMAGIC_EMBEDDED_SIGNATURE) {
693 		const CS_SuperBlob *sb = (const CS_SuperBlob *)blob;
694 		size_t n, count = ntohl(sb->count);
695 
696 		for (n = 0; n < count; n++) {
697 			if (ntohl(sb->index[n].type) != type) {
698 				continue;
699 			}
700 			uint32_t offset = ntohl(sb->index[n].offset);
701 			if (length - sizeof(const CS_GenericBlob) < offset) {
702 				return NULL;
703 			}
704 			blob = (const CS_GenericBlob *)(const void *)(addr + offset);
705 			if (ntohl(blob->magic) != magic) {
706 				continue;
707 			}
708 			if (((vm_address_t)blob + ntohl(blob->length)) < (vm_address_t)blob) {
709 				panic("CODE SIGNING: CS Blob length overflow for blob at: %p", blob);
710 			} else if (((vm_address_t)blob + ntohl(blob->length)) > (vm_address_t)(addr + length)) {
711 				continue;
712 			}
713 			return blob;
714 		}
715 	} else if (type == CSSLOT_CODEDIRECTORY && ntohl(blob->magic) == CSMAGIC_CODEDIRECTORY
716 	    && magic == CSMAGIC_CODEDIRECTORY) {
717 		if (((vm_address_t)blob + ntohl(blob->length)) < (vm_address_t)blob) {
718 			panic("CODE SIGNING: CS Blob length overflow for code directory blob at: %p", blob);
719 		} else if (((vm_address_t)blob + ntohl(blob->length)) > (vm_address_t)(addr + length)) {
720 			return NULL;
721 		}
722 		return blob;
723 	}
724 	return NULL;
725 }
726 
727 
728 const CS_GenericBlob *
csblob_find_blob(struct cs_blob * csblob,uint32_t type,uint32_t magic)729 csblob_find_blob(struct cs_blob *csblob, uint32_t type, uint32_t magic)
730 {
731 	if ((csblob->csb_flags & CS_VALID) == 0) {
732 		return NULL;
733 	}
734 	return csblob_find_blob_bytes((const uint8_t *)csblob->csb_mem_kaddr, csblob->csb_mem_size, type, magic);
735 }
736 
737 static const uint8_t *
find_special_slot(const CS_CodeDirectory * cd,size_t slotsize,uint32_t slot)738 find_special_slot(const CS_CodeDirectory *cd, size_t slotsize, uint32_t slot)
739 {
740 	/* there is no zero special slot since that is the first code slot */
741 	if (ntohl(cd->nSpecialSlots) < slot || slot == 0) {
742 		return NULL;
743 	}
744 
745 	return (const uint8_t *)cd + ntohl(cd->hashOffset) - (slotsize * slot);
746 }
747 
748 static uint8_t cshash_zero[CS_HASH_MAX_SIZE] = { 0 };
749 
750 static int
csblob_find_special_slot_blob(struct cs_blob * csblob,uint32_t slot,uint32_t magic,const CS_GenericBlob ** out_start,size_t * out_length)751 csblob_find_special_slot_blob(struct cs_blob* csblob, uint32_t slot, uint32_t magic, const CS_GenericBlob **out_start, size_t *out_length)
752 {
753 	uint8_t computed_hash[CS_HASH_MAX_SIZE];
754 	const CS_GenericBlob *blob;
755 	const CS_CodeDirectory *code_dir;
756 	const uint8_t *embedded_hash;
757 	union cs_hash_union context;
758 
759 	if (out_start) {
760 		*out_start = NULL;
761 	}
762 	if (out_length) {
763 		*out_length = 0;
764 	}
765 
766 	if (csblob->csb_hashtype == NULL || csblob->csb_hashtype->cs_digest_size > sizeof(computed_hash)) {
767 		return EBADEXEC;
768 	}
769 
770 	code_dir = csblob->csb_cd;
771 
772 	blob = csblob_find_blob_bytes((const uint8_t *)csblob->csb_mem_kaddr, csblob->csb_mem_size, slot, magic);
773 
774 	embedded_hash = find_special_slot(code_dir, csblob->csb_hashtype->cs_size, slot);
775 
776 	if (embedded_hash == NULL) {
777 		if (blob) {
778 			return EBADEXEC;
779 		}
780 		return 0;
781 	} else if (blob == NULL) {
782 		if (memcmp(embedded_hash, cshash_zero, csblob->csb_hashtype->cs_size) != 0) {
783 			return EBADEXEC;
784 		} else {
785 			return 0;
786 		}
787 	}
788 
789 	csblob->csb_hashtype->cs_init(&context);
790 	csblob->csb_hashtype->cs_update(&context, blob, ntohl(blob->length));
791 	csblob->csb_hashtype->cs_final(computed_hash, &context);
792 
793 	if (memcmp(computed_hash, embedded_hash, csblob->csb_hashtype->cs_size) != 0) {
794 		return EBADEXEC;
795 	}
796 	if (out_start) {
797 		*out_start = blob;
798 	}
799 	if (out_length) {
800 		*out_length = ntohl(blob->length);
801 	}
802 
803 	return 0;
804 }
805 
806 int
csblob_get_entitlements(struct cs_blob * csblob,void ** out_start,size_t * out_length)807 csblob_get_entitlements(struct cs_blob *csblob, void **out_start, size_t *out_length)
808 {
809 	uint8_t computed_hash[CS_HASH_MAX_SIZE];
810 	const CS_GenericBlob *entitlements;
811 	const CS_CodeDirectory *code_dir;
812 	const uint8_t *embedded_hash;
813 	union cs_hash_union context;
814 
815 	*out_start = NULL;
816 	*out_length = 0;
817 
818 	if (csblob->csb_hashtype == NULL || csblob->csb_hashtype->cs_digest_size > sizeof(computed_hash)) {
819 		return EBADEXEC;
820 	}
821 
822 	code_dir = csblob->csb_cd;
823 
824 	if ((csblob->csb_flags & CS_VALID) == 0) {
825 		entitlements = NULL;
826 	} else {
827 		entitlements = csblob->csb_entitlements_blob;
828 	}
829 	embedded_hash = find_special_slot(code_dir, csblob->csb_hashtype->cs_size, CSSLOT_ENTITLEMENTS);
830 
831 	if (embedded_hash == NULL) {
832 		if (entitlements) {
833 			return EBADEXEC;
834 		}
835 		return 0;
836 	} else if (entitlements == NULL) {
837 		if (memcmp(embedded_hash, cshash_zero, csblob->csb_hashtype->cs_size) != 0) {
838 			return EBADEXEC;
839 		} else {
840 			return 0;
841 		}
842 	}
843 
844 	csblob->csb_hashtype->cs_init(&context);
845 	csblob->csb_hashtype->cs_update(&context, entitlements, ntohl(entitlements->length));
846 	csblob->csb_hashtype->cs_final(computed_hash, &context);
847 
848 	if (memcmp(computed_hash, embedded_hash, csblob->csb_hashtype->cs_size) != 0) {
849 		return EBADEXEC;
850 	}
851 
852 	*out_start = __DECONST(void *, entitlements);
853 	*out_length = ntohl(entitlements->length);
854 
855 	return 0;
856 }
857 
858 const CS_GenericBlob*
csblob_get_der_entitlements_unsafe(struct cs_blob * csblob)859 csblob_get_der_entitlements_unsafe(struct cs_blob * csblob)
860 {
861 	if ((csblob->csb_flags & CS_VALID) == 0) {
862 		return NULL;
863 	}
864 
865 	return csblob->csb_der_entitlements_blob;
866 }
867 
868 int
csblob_get_der_entitlements(struct cs_blob * csblob,const CS_GenericBlob ** out_start,size_t * out_length)869 csblob_get_der_entitlements(struct cs_blob *csblob, const CS_GenericBlob **out_start, size_t *out_length)
870 {
871 	uint8_t computed_hash[CS_HASH_MAX_SIZE];
872 	const CS_GenericBlob *der_entitlements;
873 	const CS_CodeDirectory *code_dir;
874 	const uint8_t *embedded_hash;
875 	union cs_hash_union context;
876 
877 	*out_start = NULL;
878 	*out_length = 0;
879 
880 	if (csblob->csb_hashtype == NULL || csblob->csb_hashtype->cs_digest_size > sizeof(computed_hash)) {
881 		return EBADEXEC;
882 	}
883 
884 	code_dir = csblob->csb_cd;
885 
886 	if ((csblob->csb_flags & CS_VALID) == 0) {
887 		der_entitlements = NULL;
888 	} else {
889 		der_entitlements = csblob->csb_der_entitlements_blob;
890 	}
891 	embedded_hash = find_special_slot(code_dir, csblob->csb_hashtype->cs_size, CSSLOT_DER_ENTITLEMENTS);
892 
893 	if (embedded_hash == NULL) {
894 		if (der_entitlements) {
895 			return EBADEXEC;
896 		}
897 		return 0;
898 	} else if (der_entitlements == NULL) {
899 		if (memcmp(embedded_hash, cshash_zero, csblob->csb_hashtype->cs_size) != 0) {
900 			return EBADEXEC;
901 		} else {
902 			return 0;
903 		}
904 	}
905 
906 	csblob->csb_hashtype->cs_init(&context);
907 	csblob->csb_hashtype->cs_update(&context, der_entitlements, ntohl(der_entitlements->length));
908 	csblob->csb_hashtype->cs_final(computed_hash, &context);
909 
910 	if (memcmp(computed_hash, embedded_hash, csblob->csb_hashtype->cs_size) != 0) {
911 		return EBADEXEC;
912 	}
913 
914 	*out_start = der_entitlements;
915 	*out_length = ntohl(der_entitlements->length);
916 
917 	return 0;
918 }
919 
920 static bool
ubc_cs_blob_pagewise_allocate(__unused vm_size_t size)921 ubc_cs_blob_pagewise_allocate(
922 	__unused vm_size_t size)
923 {
924 #if CODE_SIGNING_MONITOR
925 	/* If the monitor isn't enabled, then we don't need to page-align */
926 	if (csm_enabled() == false) {
927 		return false;
928 	}
929 
930 	/*
931 	 * Small allocations can be maanged by the monitor itself. We only need to allocate
932 	 * page-wise when it is a sufficiently large allocation and the monitor cannot manage
933 	 * it on its own.
934 	 */
935 	if (size <= csm_signature_size_limit()) {
936 		return false;
937 	}
938 
939 	return true;
940 #else
941 	/* Without a monitor, we never need to page align */
942 	return false;
943 #endif /* CODE_SIGNING_MONITOR */
944 }
945 
946 int
csblob_register_profile(__unused struct cs_blob * csblob,__unused cs_profile_register_t * profile)947 csblob_register_profile(
948 	__unused struct cs_blob *csblob,
949 	__unused cs_profile_register_t *profile)
950 {
951 #if CODE_SIGNING_MONITOR
952 	/* Profiles only need to be registered for monitor environments */
953 	assert(profile->data != NULL);
954 	assert(profile->size != 0);
955 	assert(csblob != NULL);
956 
957 	kern_return_t kr = csm_register_provisioning_profile(
958 		profile->uuid,
959 		profile->data, profile->size);
960 
961 	if ((kr != KERN_SUCCESS) && (kr != KERN_ALREADY_IN_SET)) {
962 		if (kr == KERN_NOT_SUPPORTED) {
963 			return 0;
964 		}
965 		return EPERM;
966 	}
967 
968 	/* Attempt to trust the profile */
969 	kr = csm_trust_provisioning_profile(
970 		profile->uuid,
971 		profile->sig_data, profile->sig_size);
972 
973 	if (kr != KERN_SUCCESS) {
974 		return EPERM;
975 	}
976 
977 	/* Associate the profile with the monitor's signature object */
978 	kr = csm_associate_provisioning_profile(
979 		csblob->csb_csm_obj,
980 		profile->uuid);
981 
982 	if (kr != KERN_SUCCESS) {
983 		return EPERM;
984 	}
985 
986 	return 0;
987 #else
988 	return 0;
989 #endif /* CODE_SIGNING_MONITOR */
990 }
991 
992 int
csblob_register_profile_uuid(struct cs_blob * csblob,const uuid_t profile_uuid,void * profile_addr,vm_size_t profile_size)993 csblob_register_profile_uuid(
994 	struct cs_blob *csblob,
995 	const uuid_t profile_uuid,
996 	void *profile_addr,
997 	vm_size_t profile_size)
998 {
999 	cs_profile_register_t profile = {
1000 		.sig_data = NULL,
1001 		.sig_size = 0,
1002 		.data = profile_addr,
1003 		.size = profile_size
1004 	};
1005 
1006 	/* Copy the provided UUID */
1007 	memcpy(profile.uuid, profile_uuid, sizeof(profile.uuid));
1008 
1009 	return csblob_register_profile(csblob, &profile);
1010 }
1011 
1012 /*
1013  * CODESIGNING
1014  * End of routines to navigate code signing data structures in the kernel.
1015  */
1016 
1017 
1018 
1019 /*
1020  * ubc_info_init
1021  *
1022  * Allocate and attach an empty ubc_info structure to a vnode
1023  *
1024  * Parameters:	vp			Pointer to the vnode
1025  *
1026  * Returns:	0			Success
1027  *	vnode_size:ENOMEM		Not enough space
1028  *	vnode_size:???			Other error from vnode_getattr
1029  *
1030  */
1031 int
ubc_info_init(struct vnode * vp)1032 ubc_info_init(struct vnode *vp)
1033 {
1034 	return ubc_info_init_internal(vp, 0, 0);
1035 }
1036 
1037 
1038 /*
1039  * ubc_info_init_withsize
1040  *
1041  * Allocate and attach a sized ubc_info structure to a vnode
1042  *
1043  * Parameters:	vp			Pointer to the vnode
1044  *		filesize		The size of the file
1045  *
1046  * Returns:	0			Success
1047  *	vnode_size:ENOMEM		Not enough space
1048  *	vnode_size:???			Other error from vnode_getattr
1049  */
1050 int
ubc_info_init_withsize(struct vnode * vp,off_t filesize)1051 ubc_info_init_withsize(struct vnode *vp, off_t filesize)
1052 {
1053 	return ubc_info_init_internal(vp, 1, filesize);
1054 }
1055 
1056 
1057 /*
1058  * ubc_info_init_internal
1059  *
1060  * Allocate and attach a ubc_info structure to a vnode
1061  *
1062  * Parameters:	vp			Pointer to the vnode
1063  *		withfsize{0,1}		Zero if the size should be obtained
1064  *					from the vnode; otherwise, use filesize
1065  *		filesize		The size of the file, if withfsize == 1
1066  *
1067  * Returns:	0			Success
1068  *	vnode_size:ENOMEM		Not enough space
1069  *	vnode_size:???			Other error from vnode_getattr
1070  *
1071  * Notes:	We call a blocking zalloc(), and the zone was created as an
1072  *		expandable and collectable zone, so if no memory is available,
1073  *		it is possible for zalloc() to block indefinitely.  zalloc()
1074  *		may also panic if the zone of zones is exhausted, since it's
1075  *		NOT expandable.
1076  *
1077  *		We unconditionally call vnode_pager_setup(), even if this is
1078  *		a reuse of a ubc_info; in that case, we should probably assert
1079  *		that it does not already have a pager association, but do not.
1080  *
1081  *		Since memory_object_create_named() can only fail from receiving
1082  *		an invalid pager argument, the explicit check and panic is
1083  *		merely precautionary.
1084  */
1085 static int
ubc_info_init_internal(vnode_t vp,int withfsize,off_t filesize)1086 ubc_info_init_internal(vnode_t vp, int withfsize, off_t filesize)
1087 {
1088 	struct ubc_info *uip;
1089 	void *  pager;
1090 	int error = 0;
1091 	kern_return_t kret;
1092 	memory_object_control_t control;
1093 
1094 	uip = vp->v_ubcinfo;
1095 
1096 	/*
1097 	 * If there is not already a ubc_info attached to the vnode, we
1098 	 * attach one; otherwise, we will reuse the one that's there.
1099 	 */
1100 	if (uip == UBC_INFO_NULL) {
1101 		uip = zalloc_flags(ubc_info_zone, Z_WAITOK | Z_ZERO);
1102 
1103 		uip->ui_vnode = vp;
1104 		uip->ui_flags = UI_INITED;
1105 		uip->ui_ucred = NOCRED;
1106 	}
1107 	assert(uip->ui_flags != UI_NONE);
1108 	assert(uip->ui_vnode == vp);
1109 
1110 	/* now set this ubc_info in the vnode */
1111 	vp->v_ubcinfo = uip;
1112 
1113 	/*
1114 	 * Allocate a pager object for this vnode
1115 	 *
1116 	 * XXX The value of the pager parameter is currently ignored.
1117 	 * XXX Presumably, this API changed to avoid the race between
1118 	 * XXX setting the pager and the UI_HASPAGER flag.
1119 	 */
1120 	pager = (void *)vnode_pager_setup(vp, uip->ui_pager);
1121 	assert(pager);
1122 
1123 	/*
1124 	 * Explicitly set the pager into the ubc_info, after setting the
1125 	 * UI_HASPAGER flag.
1126 	 */
1127 	SET(uip->ui_flags, UI_HASPAGER);
1128 	uip->ui_pager = pager;
1129 
1130 	/*
1131 	 * Note: We can not use VNOP_GETATTR() to get accurate
1132 	 * value of ui_size because this may be an NFS vnode, and
1133 	 * nfs_getattr() can call vinvalbuf(); if this happens,
1134 	 * ubc_info is not set up to deal with that event.
1135 	 * So use bogus size.
1136 	 */
1137 
1138 	/*
1139 	 * create a vnode - vm_object association
1140 	 * memory_object_create_named() creates a "named" reference on the
1141 	 * memory object we hold this reference as long as the vnode is
1142 	 * "alive."  Since memory_object_create_named() took its own reference
1143 	 * on the vnode pager we passed it, we can drop the reference
1144 	 * vnode_pager_setup() returned here.
1145 	 */
1146 	kret = memory_object_create_named(pager,
1147 	    (memory_object_size_t)uip->ui_size, &control);
1148 	vnode_pager_deallocate(pager);
1149 	if (kret != KERN_SUCCESS) {
1150 		panic("ubc_info_init: memory_object_create_named returned %d", kret);
1151 	}
1152 
1153 	assert(control);
1154 	uip->ui_control = control;      /* cache the value of the mo control */
1155 	SET(uip->ui_flags, UI_HASOBJREF);       /* with a named reference */
1156 
1157 	if (withfsize == 0) {
1158 		/* initialize the size */
1159 		error = vnode_size(vp, &uip->ui_size, vfs_context_current());
1160 		if (error) {
1161 			uip->ui_size = 0;
1162 		}
1163 	} else {
1164 		uip->ui_size = filesize;
1165 	}
1166 	vp->v_lflag |= VNAMED_UBC;      /* vnode has a named ubc reference */
1167 
1168 	return error;
1169 }
1170 
1171 
1172 /*
1173  * ubc_info_free
1174  *
1175  * Free a ubc_info structure
1176  *
1177  * Parameters:	uip			A pointer to the ubc_info to free
1178  *
1179  * Returns:	(void)
1180  *
1181  * Notes:	If there is a credential that has subsequently been associated
1182  *		with the ubc_info, the reference to the credential is dropped.
1183  *
1184  *		It's actually impossible for a ubc_info.ui_control to take the
1185  *		value MEMORY_OBJECT_CONTROL_NULL.
1186  */
1187 static void
ubc_info_free(struct ubc_info * uip)1188 ubc_info_free(struct ubc_info *uip)
1189 {
1190 	if (IS_VALID_CRED(uip->ui_ucred)) {
1191 		kauth_cred_unref(&uip->ui_ucred);
1192 	}
1193 
1194 	if (uip->ui_control != MEMORY_OBJECT_CONTROL_NULL) {
1195 		memory_object_control_deallocate(uip->ui_control);
1196 	}
1197 
1198 	cluster_release(uip);
1199 	ubc_cs_free(uip);
1200 
1201 	zfree(ubc_info_zone, uip);
1202 	return;
1203 }
1204 
1205 
1206 void
ubc_info_deallocate(struct ubc_info * uip)1207 ubc_info_deallocate(struct ubc_info *uip)
1208 {
1209 	ubc_info_free(uip);
1210 }
1211 
1212 /*
1213  * ubc_setsize_ex
1214  *
1215  * Tell the VM that the the size of the file represented by the vnode has
1216  * changed
1217  *
1218  * Parameters:	vp	   The vp whose backing file size is
1219  *					   being changed
1220  *				nsize  The new size of the backing file
1221  *				opts   Options
1222  *
1223  * Returns:	EINVAL for new size < 0
1224  *			ENOENT if no UBC info exists
1225  *          EAGAIN if UBC_SETSIZE_NO_FS_REENTRY option is set and new_size < old size
1226  *          Other errors (mapped to errno_t) returned by VM functions
1227  *
1228  * Notes:   This function will indicate success if the new size is the
1229  *		    same or larger than the old size (in this case, the
1230  *		    remainder of the file will require modification or use of
1231  *		    an existing upl to access successfully).
1232  *
1233  *		    This function will fail if the new file size is smaller,
1234  *		    and the memory region being invalidated was unable to
1235  *		    actually be invalidated and/or the last page could not be
1236  *		    flushed, if the new size is not aligned to a page
1237  *		    boundary.  This is usually indicative of an I/O error.
1238  */
1239 errno_t
ubc_setsize_ex(struct vnode * vp,off_t nsize,ubc_setsize_opts_t opts)1240 ubc_setsize_ex(struct vnode *vp, off_t nsize, ubc_setsize_opts_t opts)
1241 {
1242 	off_t osize;    /* ui_size before change */
1243 	off_t lastpg, olastpgend, lastoff;
1244 	struct ubc_info *uip;
1245 	memory_object_control_t control;
1246 	kern_return_t kret = KERN_SUCCESS;
1247 
1248 	if (nsize < (off_t)0) {
1249 		return EINVAL;
1250 	}
1251 
1252 	if (!UBCINFOEXISTS(vp)) {
1253 		return ENOENT;
1254 	}
1255 
1256 	uip = vp->v_ubcinfo;
1257 	osize = uip->ui_size;
1258 
1259 	if (ISSET(opts, UBC_SETSIZE_NO_FS_REENTRY) && nsize < osize) {
1260 		return EAGAIN;
1261 	}
1262 
1263 	/*
1264 	 * Update the size before flushing the VM
1265 	 */
1266 	uip->ui_size = nsize;
1267 
1268 	if (nsize >= osize) {   /* Nothing more to do */
1269 		if (nsize > osize) {
1270 			lock_vnode_and_post(vp, NOTE_EXTEND);
1271 		}
1272 
1273 		return 0;
1274 	}
1275 
1276 	/*
1277 	 * When the file shrinks, invalidate the pages beyond the
1278 	 * new size. Also get rid of garbage beyond nsize on the
1279 	 * last page. The ui_size already has the nsize, so any
1280 	 * subsequent page-in will zero-fill the tail properly
1281 	 */
1282 	lastpg = trunc_page_64(nsize);
1283 	olastpgend = round_page_64(osize);
1284 	control = uip->ui_control;
1285 	assert(control);
1286 	lastoff = (nsize & PAGE_MASK_64);
1287 
1288 	if (lastoff) {
1289 		upl_t           upl;
1290 		upl_page_info_t *pl;
1291 
1292 		/*
1293 		 * new EOF ends up in the middle of a page
1294 		 * zero the tail of this page if it's currently
1295 		 * present in the cache
1296 		 */
1297 		kret = ubc_create_upl_kernel(vp, lastpg, PAGE_SIZE, &upl, &pl, UPL_SET_LITE | UPL_WILL_MODIFY, VM_KERN_MEMORY_FILE);
1298 
1299 		if (kret != KERN_SUCCESS) {
1300 			panic("ubc_setsize: ubc_create_upl (error = %d)", kret);
1301 		}
1302 
1303 		if (upl_valid_page(pl, 0)) {
1304 			cluster_zero(upl, (uint32_t)lastoff, PAGE_SIZE - (uint32_t)lastoff, NULL);
1305 		}
1306 
1307 		ubc_upl_abort_range(upl, 0, PAGE_SIZE, UPL_ABORT_FREE_ON_EMPTY);
1308 
1309 		lastpg += PAGE_SIZE_64;
1310 	}
1311 	if (olastpgend > lastpg) {
1312 		int     flags;
1313 
1314 		if (lastpg == 0) {
1315 			flags = MEMORY_OBJECT_DATA_FLUSH_ALL;
1316 		} else {
1317 			flags = MEMORY_OBJECT_DATA_FLUSH;
1318 		}
1319 		/*
1320 		 * invalidate the pages beyond the new EOF page
1321 		 *
1322 		 */
1323 		kret = memory_object_lock_request(control,
1324 		    (memory_object_offset_t)lastpg,
1325 		    (memory_object_size_t)(olastpgend - lastpg), NULL, NULL,
1326 		    MEMORY_OBJECT_RETURN_NONE, flags, VM_PROT_NO_CHANGE);
1327 		if (kret != KERN_SUCCESS) {
1328 			printf("ubc_setsize: invalidate failed (error = %d)\n", kret);
1329 		}
1330 	}
1331 	return mach_to_bsd_errno(kret);
1332 }
1333 
1334 // Returns true for success
1335 int
ubc_setsize(vnode_t vp,off_t nsize)1336 ubc_setsize(vnode_t vp, off_t nsize)
1337 {
1338 	return ubc_setsize_ex(vp, nsize, 0) == 0;
1339 }
1340 
1341 /*
1342  * ubc_getsize
1343  *
1344  * Get the size of the file assocated with the specified vnode
1345  *
1346  * Parameters:	vp			The vnode whose size is of interest
1347  *
1348  * Returns:	0			There is no ubc_info associated with
1349  *					this vnode, or the size is zero
1350  *		!0			The size of the file
1351  *
1352  * Notes:	Using this routine, it is not possible for a caller to
1353  *		successfully distinguish between a vnode associate with a zero
1354  *		length file, and a vnode with no associated ubc_info.  The
1355  *		caller therefore needs to not care, or needs to ensure that
1356  *		they have previously successfully called ubc_info_init() or
1357  *		ubc_info_init_withsize().
1358  */
1359 off_t
ubc_getsize(struct vnode * vp)1360 ubc_getsize(struct vnode *vp)
1361 {
1362 	/* people depend on the side effect of this working this way
1363 	 * as they call this for directory
1364 	 */
1365 	if (!UBCINFOEXISTS(vp)) {
1366 		return (off_t)0;
1367 	}
1368 	return vp->v_ubcinfo->ui_size;
1369 }
1370 
1371 
1372 /*
1373  * ubc_umount
1374  *
1375  * Call ubc_msync(vp, 0, EOF, NULL, UBC_PUSHALL) on all the vnodes for this
1376  * mount point
1377  *
1378  * Parameters:	mp			The mount point
1379  *
1380  * Returns:	0			Success
1381  *
1382  * Notes:	There is no failure indication for this function.
1383  *
1384  *		This function is used in the unmount path; since it may block
1385  *		I/O indefinitely, it should not be used in the forced unmount
1386  *		path, since a device unavailability could also block that
1387  *		indefinitely.
1388  *
1389  *		Because there is no device ejection interlock on USB, FireWire,
1390  *		or similar devices, it's possible that an ejection that begins
1391  *		subsequent to the vnode_iterate() completing, either on one of
1392  *		those devices, or a network mount for which the server quits
1393  *		responding, etc., may cause the caller to block indefinitely.
1394  */
1395 __private_extern__ int
ubc_umount(struct mount * mp)1396 ubc_umount(struct mount *mp)
1397 {
1398 	vnode_iterate(mp, 0, ubc_umcallback, 0);
1399 	return 0;
1400 }
1401 
1402 
1403 /*
1404  * ubc_umcallback
1405  *
1406  * Used by ubc_umount() as an internal implementation detail; see ubc_umount()
1407  * and vnode_iterate() for details of implementation.
1408  */
1409 static int
ubc_umcallback(vnode_t vp,__unused void * args)1410 ubc_umcallback(vnode_t vp, __unused void * args)
1411 {
1412 	if (UBCINFOEXISTS(vp)) {
1413 		(void) ubc_msync(vp, (off_t)0, ubc_getsize(vp), NULL, UBC_PUSHALL);
1414 	}
1415 	return VNODE_RETURNED;
1416 }
1417 
1418 
1419 /*
1420  * ubc_getcred
1421  *
1422  * Get the credentials currently active for the ubc_info associated with the
1423  * vnode.
1424  *
1425  * Parameters:	vp			The vnode whose ubc_info credentials
1426  *					are to be retrieved
1427  *
1428  * Returns:	!NOCRED			The credentials
1429  *		NOCRED			If there is no ubc_info for the vnode,
1430  *					or if there is one, but it has not had
1431  *					any credentials associated with it.
1432  */
1433 kauth_cred_t
ubc_getcred(struct vnode * vp)1434 ubc_getcred(struct vnode *vp)
1435 {
1436 	if (UBCINFOEXISTS(vp)) {
1437 		return vp->v_ubcinfo->ui_ucred;
1438 	}
1439 
1440 	return NOCRED;
1441 }
1442 
1443 
1444 /*
1445  * ubc_setthreadcred
1446  *
1447  * If they are not already set, set the credentials of the ubc_info structure
1448  * associated with the vnode to those of the supplied thread; otherwise leave
1449  * them alone.
1450  *
1451  * Parameters:	vp			The vnode whose ubc_info creds are to
1452  *					be set
1453  *		p			The process whose credentials are to
1454  *					be used, if not running on an assumed
1455  *					credential
1456  *		thread			The thread whose credentials are to
1457  *					be used
1458  *
1459  * Returns:	1			This vnode has no associated ubc_info
1460  *		0			Success
1461  *
1462  * Notes:	This function is generally used only in the following cases:
1463  *
1464  *		o	a memory mapped file via the mmap() system call
1465  *		o	a swap store backing file
1466  *		o	subsequent to a successful write via vn_write()
1467  *
1468  *		The information is then used by the NFS client in order to
1469  *		cons up a wire message in either the page-in or page-out path.
1470  *
1471  *		There are two potential problems with the use of this API:
1472  *
1473  *		o	Because the write path only set it on a successful
1474  *			write, there is a race window between setting the
1475  *			credential and its use to evict the pages to the
1476  *			remote file server
1477  *
1478  *		o	Because a page-in may occur prior to a write, the
1479  *			credential may not be set at this time, if the page-in
1480  *			is not the result of a mapping established via mmap().
1481  *
1482  *		In both these cases, this will be triggered from the paging
1483  *		path, which will instead use the credential of the current
1484  *		process, which in this case is either the dynamic_pager or
1485  *		the kernel task, both of which utilize "root" credentials.
1486  *
1487  *		This may potentially permit operations to occur which should
1488  *		be denied, or it may cause to be denied operations which
1489  *		should be permitted, depending on the configuration of the NFS
1490  *		server.
1491  */
1492 int
ubc_setthreadcred(struct vnode * vp,proc_t p,thread_t thread)1493 ubc_setthreadcred(struct vnode *vp, proc_t p, thread_t thread)
1494 {
1495 #pragma unused(p, thread)
1496 	assert(p == current_proc());
1497 	assert(thread == current_thread());
1498 
1499 	return ubc_setcred(vp, kauth_cred_get());
1500 }
1501 
1502 
1503 /*
1504  * ubc_setcred
1505  *
1506  * If they are not already set, set the credentials of the ubc_info structure
1507  * associated with the vnode to those specified; otherwise leave them
1508  * alone.
1509  *
1510  * Parameters:	vp			The vnode whose ubc_info creds are to
1511  *					be set
1512  *		ucred			The credentials to use
1513  *
1514  * Returns:	0			This vnode has no associated ubc_info
1515  *		1			Success
1516  *
1517  * Notes:	The return values for this function are inverted from nearly
1518  *		all other uses in the kernel.
1519  *
1520  *		See also ubc_setthreadcred(), above.
1521  */
1522 int
ubc_setcred(struct vnode * vp,kauth_cred_t ucred)1523 ubc_setcred(struct vnode *vp, kauth_cred_t ucred)
1524 {
1525 	struct ubc_info *uip;
1526 
1527 	/* If there is no ubc_info, deny the operation */
1528 	if (!UBCINFOEXISTS(vp)) {
1529 		return 0;
1530 	}
1531 
1532 	/*
1533 	 * Check to see if there is already a credential reference in the
1534 	 * ubc_info; if there is not, take one on the supplied credential.
1535 	 */
1536 	vnode_lock(vp);
1537 	uip = vp->v_ubcinfo;
1538 	if (!IS_VALID_CRED(uip->ui_ucred)) {
1539 		kauth_cred_ref(ucred);
1540 		uip->ui_ucred = ucred;
1541 	}
1542 	vnode_unlock(vp);
1543 
1544 	return 1;
1545 }
1546 
1547 /*
1548  * ubc_getpager
1549  *
1550  * Get the pager associated with the ubc_info associated with the vnode.
1551  *
1552  * Parameters:	vp			The vnode to obtain the pager from
1553  *
1554  * Returns:	!VNODE_PAGER_NULL	The memory_object_t for the pager
1555  *		VNODE_PAGER_NULL	There is no ubc_info for this vnode
1556  *
1557  * Notes:	For each vnode that has a ubc_info associated with it, that
1558  *		ubc_info SHALL have a pager associated with it, so in the
1559  *		normal case, it's impossible to return VNODE_PAGER_NULL for
1560  *		a vnode with an associated ubc_info.
1561  */
1562 __private_extern__ memory_object_t
ubc_getpager(struct vnode * vp)1563 ubc_getpager(struct vnode *vp)
1564 {
1565 	if (UBCINFOEXISTS(vp)) {
1566 		return vp->v_ubcinfo->ui_pager;
1567 	}
1568 
1569 	return 0;
1570 }
1571 
1572 
1573 /*
1574  * ubc_getobject
1575  *
1576  * Get the memory object control associated with the ubc_info associated with
1577  * the vnode
1578  *
1579  * Parameters:	vp			The vnode to obtain the memory object
1580  *					from
1581  *		flags			DEPRECATED
1582  *
1583  * Returns:	!MEMORY_OBJECT_CONTROL_NULL
1584  *		MEMORY_OBJECT_CONTROL_NULL
1585  *
1586  * Notes:	Historically, if the flags were not "do not reactivate", this
1587  *		function would look up the memory object using the pager if
1588  *		it did not exist (this could be the case if the vnode had
1589  *		been previously reactivated).  The flags would also permit a
1590  *		hold to be requested, which would have created an object
1591  *		reference, if one had not already existed.  This usage is
1592  *		deprecated, as it would permit a race between finding and
1593  *		taking the reference vs. a single reference being dropped in
1594  *		another thread.
1595  */
1596 memory_object_control_t
ubc_getobject(struct vnode * vp,__unused int flags)1597 ubc_getobject(struct vnode *vp, __unused int flags)
1598 {
1599 	if (UBCINFOEXISTS(vp)) {
1600 		return vp->v_ubcinfo->ui_control;
1601 	}
1602 
1603 	return MEMORY_OBJECT_CONTROL_NULL;
1604 }
1605 
1606 /*
1607  * ubc_blktooff
1608  *
1609  * Convert a given block number to a memory backing object (file) offset for a
1610  * given vnode
1611  *
1612  * Parameters:	vp			The vnode in which the block is located
1613  *		blkno			The block number to convert
1614  *
1615  * Returns:	!-1			The offset into the backing object
1616  *		-1			There is no ubc_info associated with
1617  *					the vnode
1618  *		-1			An error occurred in the underlying VFS
1619  *					while translating the block to an
1620  *					offset; the most likely cause is that
1621  *					the caller specified a block past the
1622  *					end of the file, but this could also be
1623  *					any other error from VNOP_BLKTOOFF().
1624  *
1625  * Note:	Representing the error in band loses some information, but does
1626  *		not occlude a valid offset, since an off_t of -1 is normally
1627  *		used to represent EOF.  If we had a more reliable constant in
1628  *		our header files for it (i.e. explicitly cast to an off_t), we
1629  *		would use it here instead.
1630  */
1631 off_t
ubc_blktooff(vnode_t vp,daddr64_t blkno)1632 ubc_blktooff(vnode_t vp, daddr64_t blkno)
1633 {
1634 	off_t file_offset = -1;
1635 	int error;
1636 
1637 	if (UBCINFOEXISTS(vp)) {
1638 		error = VNOP_BLKTOOFF(vp, blkno, &file_offset);
1639 		if (error) {
1640 			file_offset = -1;
1641 		}
1642 	}
1643 
1644 	return file_offset;
1645 }
1646 
1647 
1648 /*
1649  * ubc_offtoblk
1650  *
1651  * Convert a given offset in a memory backing object into a block number for a
1652  * given vnode
1653  *
1654  * Parameters:	vp			The vnode in which the offset is
1655  *					located
1656  *		offset			The offset into the backing object
1657  *
1658  * Returns:	!-1			The returned block number
1659  *		-1			There is no ubc_info associated with
1660  *					the vnode
1661  *		-1			An error occurred in the underlying VFS
1662  *					while translating the block to an
1663  *					offset; the most likely cause is that
1664  *					the caller specified a block past the
1665  *					end of the file, but this could also be
1666  *					any other error from VNOP_OFFTOBLK().
1667  *
1668  * Note:	Representing the error in band loses some information, but does
1669  *		not occlude a valid block number, since block numbers exceed
1670  *		the valid range for offsets, due to their relative sizes.  If
1671  *		we had a more reliable constant than -1 in our header files
1672  *		for it (i.e. explicitly cast to an daddr64_t), we would use it
1673  *		here instead.
1674  */
1675 daddr64_t
ubc_offtoblk(vnode_t vp,off_t offset)1676 ubc_offtoblk(vnode_t vp, off_t offset)
1677 {
1678 	daddr64_t blkno = -1;
1679 	int error = 0;
1680 
1681 	if (UBCINFOEXISTS(vp)) {
1682 		error = VNOP_OFFTOBLK(vp, offset, &blkno);
1683 		if (error) {
1684 			blkno = -1;
1685 		}
1686 	}
1687 
1688 	return blkno;
1689 }
1690 
1691 
1692 /*
1693  * ubc_pages_resident
1694  *
1695  * Determine whether or not a given vnode has pages resident via the memory
1696  * object control associated with the ubc_info associated with the vnode
1697  *
1698  * Parameters:	vp			The vnode we want to know about
1699  *
1700  * Returns:	1			Yes
1701  *		0			No
1702  */
1703 int
ubc_pages_resident(vnode_t vp)1704 ubc_pages_resident(vnode_t vp)
1705 {
1706 	kern_return_t           kret;
1707 	boolean_t                       has_pages_resident;
1708 
1709 	if (!UBCINFOEXISTS(vp)) {
1710 		return 0;
1711 	}
1712 
1713 	/*
1714 	 * The following call may fail if an invalid ui_control is specified,
1715 	 * or if there is no VM object associated with the control object.  In
1716 	 * either case, reacting to it as if there were no pages resident will
1717 	 * result in correct behavior.
1718 	 */
1719 	kret = memory_object_pages_resident(vp->v_ubcinfo->ui_control, &has_pages_resident);
1720 
1721 	if (kret != KERN_SUCCESS) {
1722 		return 0;
1723 	}
1724 
1725 	if (has_pages_resident == TRUE) {
1726 		return 1;
1727 	}
1728 
1729 	return 0;
1730 }
1731 
1732 /*
1733  * ubc_msync
1734  *
1735  * Clean and/or invalidate a range in the memory object that backs this vnode
1736  *
1737  * Parameters:	vp			The vnode whose associated ubc_info's
1738  *					associated memory object is to have a
1739  *					range invalidated within it
1740  *		beg_off			The start of the range, as an offset
1741  *		end_off			The end of the range, as an offset
1742  *		resid_off		The address of an off_t supplied by the
1743  *					caller; may be set to NULL to ignore
1744  *		flags			See ubc_msync_internal()
1745  *
1746  * Returns:	0			Success
1747  *		!0			Failure; an errno is returned
1748  *
1749  * Implicit Returns:
1750  *		*resid_off, modified	If non-NULL, the  contents are ALWAYS
1751  *					modified; they are initialized to the
1752  *					beg_off, and in case of an I/O error,
1753  *					the difference between beg_off and the
1754  *					current value will reflect what was
1755  *					able to be written before the error
1756  *					occurred.  If no error is returned, the
1757  *					value of the resid_off is undefined; do
1758  *					NOT use it in place of end_off if you
1759  *					intend to increment from the end of the
1760  *					last call and call iteratively.
1761  *
1762  * Notes:	see ubc_msync_internal() for more detailed information.
1763  *
1764  */
1765 errno_t
ubc_msync(vnode_t vp,off_t beg_off,off_t end_off,off_t * resid_off,int flags)1766 ubc_msync(vnode_t vp, off_t beg_off, off_t end_off, off_t *resid_off, int flags)
1767 {
1768 	int retval;
1769 	int io_errno = 0;
1770 
1771 	if (resid_off) {
1772 		*resid_off = beg_off;
1773 	}
1774 
1775 	retval = ubc_msync_internal(vp, beg_off, end_off, resid_off, flags, &io_errno);
1776 
1777 	if (retval == 0 && io_errno == 0) {
1778 		return EINVAL;
1779 	}
1780 	return io_errno;
1781 }
1782 
1783 
1784 /*
1785  * ubc_msync_internal
1786  *
1787  * Clean and/or invalidate a range in the memory object that backs this vnode
1788  *
1789  * Parameters:	vp			The vnode whose associated ubc_info's
1790  *					associated memory object is to have a
1791  *					range invalidated within it
1792  *		beg_off			The start of the range, as an offset
1793  *		end_off			The end of the range, as an offset
1794  *		resid_off		The address of an off_t supplied by the
1795  *					caller; may be set to NULL to ignore
1796  *		flags			MUST contain at least one of the flags
1797  *					UBC_INVALIDATE, UBC_PUSHDIRTY, or
1798  *					UBC_PUSHALL; if UBC_PUSHDIRTY is used,
1799  *					UBC_SYNC may also be specified to cause
1800  *					this function to block until the
1801  *					operation is complete.  The behavior
1802  *					of UBC_SYNC is otherwise undefined.
1803  *		io_errno		The address of an int to contain the
1804  *					errno from a failed I/O operation, if
1805  *					one occurs; may be set to NULL to
1806  *					ignore
1807  *
1808  * Returns:	1			Success
1809  *		0			Failure
1810  *
1811  * Implicit Returns:
1812  *		*resid_off, modified	The contents of this offset MAY be
1813  *					modified; in case of an I/O error, the
1814  *					difference between beg_off and the
1815  *					current value will reflect what was
1816  *					able to be written before the error
1817  *					occurred.
1818  *		*io_errno, modified	The contents of this offset are set to
1819  *					an errno, if an error occurs; if the
1820  *					caller supplies an io_errno parameter,
1821  *					they should be careful to initialize it
1822  *					to 0 before calling this function to
1823  *					enable them to distinguish an error
1824  *					with a valid *resid_off from an invalid
1825  *					one, and to avoid potentially falsely
1826  *					reporting an error, depending on use.
1827  *
1828  * Notes:	If there is no ubc_info associated with the vnode supplied,
1829  *		this function immediately returns success.
1830  *
1831  *		If the value of end_off is less than or equal to beg_off, this
1832  *		function immediately returns success; that is, end_off is NOT
1833  *		inclusive.
1834  *
1835  *		IMPORTANT: one of the flags UBC_INVALIDATE, UBC_PUSHDIRTY, or
1836  *		UBC_PUSHALL MUST be specified; that is, it is NOT possible to
1837  *		attempt to block on in-progress I/O by calling this function
1838  *		with UBC_PUSHDIRTY, and then later call it with just UBC_SYNC
1839  *		in order to block pending on the I/O already in progress.
1840  *
1841  *		The start offset is truncated to the page boundary and the
1842  *		size is adjusted to include the last page in the range; that
1843  *		is, end_off on exactly a page boundary will not change if it
1844  *		is rounded, and the range of bytes written will be from the
1845  *		truncate beg_off to the rounded (end_off - 1).
1846  */
1847 static int
ubc_msync_internal(vnode_t vp,off_t beg_off,off_t end_off,off_t * resid_off,int flags,int * io_errno)1848 ubc_msync_internal(vnode_t vp, off_t beg_off, off_t end_off, off_t *resid_off, int flags, int *io_errno)
1849 {
1850 	memory_object_size_t    tsize;
1851 	kern_return_t           kret;
1852 	int request_flags = 0;
1853 	int flush_flags   = MEMORY_OBJECT_RETURN_NONE;
1854 
1855 	if (!UBCINFOEXISTS(vp)) {
1856 		return 0;
1857 	}
1858 	if ((flags & (UBC_INVALIDATE | UBC_PUSHDIRTY | UBC_PUSHALL)) == 0) {
1859 		return 0;
1860 	}
1861 	if (end_off <= beg_off) {
1862 		return 1;
1863 	}
1864 
1865 	if (flags & UBC_INVALIDATE) {
1866 		/*
1867 		 * discard the resident pages
1868 		 */
1869 		request_flags = (MEMORY_OBJECT_DATA_FLUSH | MEMORY_OBJECT_DATA_NO_CHANGE);
1870 	}
1871 
1872 	if (flags & UBC_SYNC) {
1873 		/*
1874 		 * wait for all the I/O to complete before returning
1875 		 */
1876 		request_flags |= MEMORY_OBJECT_IO_SYNC;
1877 	}
1878 
1879 	if (flags & UBC_PUSHDIRTY) {
1880 		/*
1881 		 * we only return the dirty pages in the range
1882 		 */
1883 		flush_flags = MEMORY_OBJECT_RETURN_DIRTY;
1884 	}
1885 
1886 	if (flags & UBC_PUSHALL) {
1887 		/*
1888 		 * then return all the interesting pages in the range (both
1889 		 * dirty and precious) to the pager
1890 		 */
1891 		flush_flags = MEMORY_OBJECT_RETURN_ALL;
1892 	}
1893 
1894 	beg_off = trunc_page_64(beg_off);
1895 	end_off = round_page_64(end_off);
1896 	tsize   = (memory_object_size_t)end_off - beg_off;
1897 
1898 	/* flush and/or invalidate pages in the range requested */
1899 	kret = memory_object_lock_request(vp->v_ubcinfo->ui_control,
1900 	    beg_off, tsize,
1901 	    (memory_object_offset_t *)resid_off,
1902 	    io_errno, flush_flags, request_flags,
1903 	    VM_PROT_NO_CHANGE);
1904 
1905 	return (kret == KERN_SUCCESS) ? 1 : 0;
1906 }
1907 
1908 
1909 /*
1910  * ubc_map
1911  *
1912  * Explicitly map a vnode that has an associate ubc_info, and add a reference
1913  * to it for the ubc system, if there isn't one already, so it will not be
1914  * recycled while it's in use, and set flags on the ubc_info to indicate that
1915  * we have done this
1916  *
1917  * Parameters:	vp			The vnode to map
1918  *		flags			The mapping flags for the vnode; this
1919  *					will be a combination of one or more of
1920  *					PROT_READ, PROT_WRITE, and PROT_EXEC
1921  *
1922  * Returns:	0			Success
1923  *		EPERM			Permission was denied
1924  *
1925  * Notes:	An I/O reference on the vnode must already be held on entry
1926  *
1927  *		If there is no ubc_info associated with the vnode, this function
1928  *		will return success.
1929  *
1930  *		If a permission error occurs, this function will return
1931  *		failure; all other failures will cause this function to return
1932  *		success.
1933  *
1934  *		IMPORTANT: This is an internal use function, and its symbols
1935  *		are not exported, hence its error checking is not very robust.
1936  *		It is primarily used by:
1937  *
1938  *		o	mmap(), when mapping a file
1939  *		o	When mapping a shared file (a shared library in the
1940  *			shared segment region)
1941  *		o	When loading a program image during the exec process
1942  *
1943  *		...all of these uses ignore the return code, and any fault that
1944  *		results later because of a failure is handled in the fix-up path
1945  *		of the fault handler.  The interface exists primarily as a
1946  *		performance hint.
1947  *
1948  *		Given that third party implementation of the type of interfaces
1949  *		that would use this function, such as alternative executable
1950  *		formats, etc., are unsupported, this function is not exported
1951  *		for general use.
1952  *
1953  *		The extra reference is held until the VM system unmaps the
1954  *		vnode from its own context to maintain a vnode reference in
1955  *		cases like open()/mmap()/close(), which leave the backing
1956  *		object referenced by a mapped memory region in a process
1957  *		address space.
1958  */
1959 __private_extern__ int
ubc_map(vnode_t vp,int flags)1960 ubc_map(vnode_t vp, int flags)
1961 {
1962 	struct ubc_info *uip;
1963 	int error = 0;
1964 	int need_ref = 0;
1965 	int need_wakeup = 0;
1966 
1967 	if (UBCINFOEXISTS(vp)) {
1968 		vnode_lock(vp);
1969 		uip = vp->v_ubcinfo;
1970 
1971 		while (ISSET(uip->ui_flags, UI_MAPBUSY)) {
1972 			SET(uip->ui_flags, UI_MAPWAITING);
1973 			(void) msleep(&uip->ui_flags, &vp->v_lock,
1974 			    PRIBIO, "ubc_map", NULL);
1975 		}
1976 		SET(uip->ui_flags, UI_MAPBUSY);
1977 		vnode_unlock(vp);
1978 
1979 		error = VNOP_MMAP(vp, flags, vfs_context_current());
1980 
1981 		/*
1982 		 * rdar://problem/22587101 required that we stop propagating
1983 		 * EPERM up the stack. Otherwise, we would have to funnel up
1984 		 * the error at all the call sites for memory_object_map().
1985 		 * The risk is in having to undo the map/object/entry state at
1986 		 * all these call sites. It would also affect more than just mmap()
1987 		 * e.g. vm_remap().
1988 		 *
1989 		 *	if (error != EPERM)
1990 		 *              error = 0;
1991 		 */
1992 
1993 		error = 0;
1994 
1995 		vnode_lock_spin(vp);
1996 
1997 		if (error == 0) {
1998 			if (!ISSET(uip->ui_flags, UI_ISMAPPED)) {
1999 				need_ref = 1;
2000 			}
2001 			SET(uip->ui_flags, (UI_WASMAPPED | UI_ISMAPPED));
2002 			if (flags & PROT_WRITE) {
2003 				SET(uip->ui_flags, (UI_WASMAPPEDWRITE | UI_MAPPEDWRITE));
2004 			}
2005 		}
2006 		CLR(uip->ui_flags, UI_MAPBUSY);
2007 
2008 		if (ISSET(uip->ui_flags, UI_MAPWAITING)) {
2009 			CLR(uip->ui_flags, UI_MAPWAITING);
2010 			need_wakeup = 1;
2011 		}
2012 		vnode_unlock(vp);
2013 
2014 		if (need_wakeup) {
2015 			wakeup(&uip->ui_flags);
2016 		}
2017 
2018 		if (need_ref) {
2019 			/*
2020 			 * Make sure we get a ref as we can't unwind from here
2021 			 */
2022 			if (vnode_ref_ext(vp, 0, VNODE_REF_FORCE)) {
2023 				panic("%s : VNODE_REF_FORCE failed", __FUNCTION__);
2024 			}
2025 			/*
2026 			 * Vnodes that are on "unreliable" media (like disk
2027 			 * images, network filesystems, 3rd-party filesystems,
2028 			 * and possibly external devices) could see their
2029 			 * contents be changed via the backing store without
2030 			 * triggering copy-on-write, so we can't fully rely
2031 			 * on copy-on-write and might have to resort to
2032 			 * copy-on-read to protect "privileged" processes and
2033 			 * prevent privilege escalation.
2034 			 *
2035 			 * The root filesystem is considered "reliable" because
2036 			 * there's not much point in trying to protect
2037 			 * ourselves from such a vulnerability and the extra
2038 			 * cost of copy-on-read (CPU time and memory pressure)
2039 			 * could result in some serious regressions.
2040 			 */
2041 			if (vp->v_mount != NULL &&
2042 			    ((vp->v_mount->mnt_flag & MNT_ROOTFS) ||
2043 			    vnode_on_reliable_media(vp))) {
2044 				/*
2045 				 * This vnode is deemed "reliable" so mark
2046 				 * its VM object as "trusted".
2047 				 */
2048 				memory_object_mark_trusted(uip->ui_control);
2049 			} else {
2050 //				printf("BUGGYCOW: %s:%d vp %p \"%s\" in mnt %p \"%s\" is untrusted\n", __FUNCTION__, __LINE__, vp, vp->v_name, vp->v_mount, vp->v_mount->mnt_vnodecovered->v_name);
2051 			}
2052 		}
2053 	}
2054 	return error;
2055 }
2056 
2057 
2058 /*
2059  * ubc_destroy_named
2060  *
2061  * Destroy the named memory object associated with the ubc_info control object
2062  * associated with the designated vnode, if there is a ubc_info associated
2063  * with the vnode, and a control object is associated with it
2064  *
2065  * Parameters:	vp			The designated vnode
2066  *
2067  * Returns:	(void)
2068  *
2069  * Notes:	This function is called on vnode termination for all vnodes,
2070  *		and must therefore not assume that there is a ubc_info that is
2071  *		associated with the vnode, nor that there is a control object
2072  *		associated with the ubc_info.
2073  *
2074  *		If all the conditions necessary are present, this function
2075  *		calls memory_object_destory(), which will in turn end up
2076  *		calling ubc_unmap() to release any vnode references that were
2077  *		established via ubc_map().
2078  *
2079  *		IMPORTANT: This is an internal use function that is used
2080  *		exclusively by the internal use function vclean().
2081  */
2082 __private_extern__ void
ubc_destroy_named(vnode_t vp,vm_object_destroy_reason_t reason)2083 ubc_destroy_named(vnode_t vp, vm_object_destroy_reason_t reason)
2084 {
2085 	memory_object_control_t control;
2086 	struct ubc_info *uip;
2087 	kern_return_t kret;
2088 
2089 	if (UBCINFOEXISTS(vp)) {
2090 		uip = vp->v_ubcinfo;
2091 
2092 		/* Terminate the memory object  */
2093 		control = ubc_getobject(vp, UBC_HOLDOBJECT);
2094 		if (control != MEMORY_OBJECT_CONTROL_NULL) {
2095 			kret = memory_object_destroy(control, reason);
2096 			if (kret != KERN_SUCCESS) {
2097 				panic("ubc_destroy_named: memory_object_destroy failed");
2098 			}
2099 		}
2100 	}
2101 }
2102 
2103 
2104 /*
2105  * ubc_isinuse
2106  *
2107  * Determine whether or not a vnode is currently in use by ubc at a level in
2108  * excess of the requested busycount
2109  *
2110  * Parameters:	vp			The vnode to check
2111  *		busycount		The threshold busy count, used to bias
2112  *					the count usually already held by the
2113  *					caller to avoid races
2114  *
2115  * Returns:	1			The vnode is in use over the threshold
2116  *		0			The vnode is not in use over the
2117  *					threshold
2118  *
2119  * Notes:	Because the vnode is only held locked while actually asking
2120  *		the use count, this function only represents a snapshot of the
2121  *		current state of the vnode.  If more accurate information is
2122  *		required, an additional busycount should be held by the caller
2123  *		and a non-zero busycount used.
2124  *
2125  *		If there is no ubc_info associated with the vnode, this
2126  *		function will report that the vnode is not in use by ubc.
2127  */
2128 int
ubc_isinuse(struct vnode * vp,int busycount)2129 ubc_isinuse(struct vnode *vp, int busycount)
2130 {
2131 	if (!UBCINFOEXISTS(vp)) {
2132 		return 0;
2133 	}
2134 	return ubc_isinuse_locked(vp, busycount, 0);
2135 }
2136 
2137 
2138 /*
2139  * ubc_isinuse_locked
2140  *
2141  * Determine whether or not a vnode is currently in use by ubc at a level in
2142  * excess of the requested busycount
2143  *
2144  * Parameters:	vp			The vnode to check
2145  *		busycount		The threshold busy count, used to bias
2146  *					the count usually already held by the
2147  *					caller to avoid races
2148  *		locked			True if the vnode is already locked by
2149  *					the caller
2150  *
2151  * Returns:	1			The vnode is in use over the threshold
2152  *		0			The vnode is not in use over the
2153  *					threshold
2154  *
2155  * Notes:	If the vnode is not locked on entry, it is locked while
2156  *		actually asking the use count.  If this is the case, this
2157  *		function only represents a snapshot of the current state of
2158  *		the vnode.  If more accurate information is required, the
2159  *		vnode lock should be held by the caller, otherwise an
2160  *		additional busycount should be held by the caller and a
2161  *		non-zero busycount used.
2162  *
2163  *		If there is no ubc_info associated with the vnode, this
2164  *		function will report that the vnode is not in use by ubc.
2165  */
2166 int
ubc_isinuse_locked(struct vnode * vp,int busycount,int locked)2167 ubc_isinuse_locked(struct vnode *vp, int busycount, int locked)
2168 {
2169 	int retval = 0;
2170 
2171 
2172 	if (!locked) {
2173 		vnode_lock_spin(vp);
2174 	}
2175 
2176 	if ((vp->v_usecount - vp->v_kusecount) > busycount) {
2177 		retval = 1;
2178 	}
2179 
2180 	if (!locked) {
2181 		vnode_unlock(vp);
2182 	}
2183 	return retval;
2184 }
2185 
2186 
2187 /*
2188  * ubc_unmap
2189  *
2190  * Reverse the effects of a ubc_map() call for a given vnode
2191  *
2192  * Parameters:	vp			vnode to unmap from ubc
2193  *
2194  * Returns:	(void)
2195  *
2196  * Notes:	This is an internal use function used by vnode_pager_unmap().
2197  *		It will attempt to obtain a reference on the supplied vnode,
2198  *		and if it can do so, and there is an associated ubc_info, and
2199  *		the flags indicate that it was mapped via ubc_map(), then the
2200  *		flag is cleared, the mapping removed, and the reference taken
2201  *		by ubc_map() is released.
2202  *
2203  *		IMPORTANT: This MUST only be called by the VM
2204  *		to prevent race conditions.
2205  */
2206 __private_extern__ void
ubc_unmap(struct vnode * vp)2207 ubc_unmap(struct vnode *vp)
2208 {
2209 	struct ubc_info *uip;
2210 	int     need_rele = 0;
2211 	int     need_wakeup = 0;
2212 
2213 	if (vnode_getwithref(vp)) {
2214 		return;
2215 	}
2216 
2217 	if (UBCINFOEXISTS(vp)) {
2218 		bool want_fsevent = false;
2219 
2220 		vnode_lock(vp);
2221 		uip = vp->v_ubcinfo;
2222 
2223 		while (ISSET(uip->ui_flags, UI_MAPBUSY)) {
2224 			SET(uip->ui_flags, UI_MAPWAITING);
2225 			(void) msleep(&uip->ui_flags, &vp->v_lock,
2226 			    PRIBIO, "ubc_unmap", NULL);
2227 		}
2228 		SET(uip->ui_flags, UI_MAPBUSY);
2229 
2230 		if (ISSET(uip->ui_flags, UI_ISMAPPED)) {
2231 			if (ISSET(uip->ui_flags, UI_MAPPEDWRITE)) {
2232 				want_fsevent = true;
2233 			}
2234 
2235 			need_rele = 1;
2236 
2237 			/*
2238 			 * We want to clear the mapped flags after we've called
2239 			 * VNOP_MNOMAP to avoid certain races and allow
2240 			 * VNOP_MNOMAP to call ubc_is_mapped_writable.
2241 			 */
2242 		}
2243 		vnode_unlock(vp);
2244 
2245 		if (need_rele) {
2246 			vfs_context_t ctx = vfs_context_current();
2247 
2248 			(void)VNOP_MNOMAP(vp, ctx);
2249 
2250 #if CONFIG_FSE
2251 			/*
2252 			 * Why do we want an fsevent here?  Normally the
2253 			 * content modified fsevent is posted when a file is
2254 			 * closed and only if it's written to via conventional
2255 			 * means.  It's perfectly legal to close a file and
2256 			 * keep your mappings and we don't currently track
2257 			 * whether it was written to via a mapping.
2258 			 * Therefore, we need to post an fsevent here if the
2259 			 * file was mapped writable.  This may result in false
2260 			 * events, i.e. we post a notification when nothing
2261 			 * has really changed.
2262 			 */
2263 			if (want_fsevent && need_fsevent(FSE_CONTENT_MODIFIED, vp)) {
2264 				add_fsevent(FSE_CONTENT_MODIFIED_NO_HLINK, ctx,
2265 				    FSE_ARG_VNODE, vp,
2266 				    FSE_ARG_DONE);
2267 			}
2268 #endif
2269 
2270 			vnode_rele(vp);
2271 		}
2272 
2273 		vnode_lock_spin(vp);
2274 
2275 		if (need_rele) {
2276 			CLR(uip->ui_flags, UI_ISMAPPED | UI_MAPPEDWRITE);
2277 		}
2278 
2279 		CLR(uip->ui_flags, UI_MAPBUSY);
2280 
2281 		if (ISSET(uip->ui_flags, UI_MAPWAITING)) {
2282 			CLR(uip->ui_flags, UI_MAPWAITING);
2283 			need_wakeup = 1;
2284 		}
2285 		vnode_unlock(vp);
2286 
2287 		if (need_wakeup) {
2288 			wakeup(&uip->ui_flags);
2289 		}
2290 	}
2291 	/*
2292 	 * the drop of the vnode ref will cleanup
2293 	 */
2294 	vnode_put(vp);
2295 }
2296 
2297 
2298 /*
2299  * ubc_page_op
2300  *
2301  * Manipulate individual page state for a vnode with an associated ubc_info
2302  * with an associated memory object control.
2303  *
2304  * Parameters:	vp			The vnode backing the page
2305  *		f_offset		A file offset interior to the page
2306  *		ops			The operations to perform, as a bitmap
2307  *					(see below for more information)
2308  *		phys_entryp		The address of a ppnum_t; may be NULL
2309  *					to ignore
2310  *		flagsp			A pointer to an int to contain flags;
2311  *					may be NULL to ignore
2312  *
2313  * Returns:	KERN_SUCCESS		Success
2314  *		KERN_INVALID_ARGUMENT	If the memory object control has no VM
2315  *					object associated
2316  *		KERN_INVALID_OBJECT	If UPL_POP_PHYSICAL and the object is
2317  *					not physically contiguous
2318  *		KERN_INVALID_OBJECT	If !UPL_POP_PHYSICAL and the object is
2319  *					physically contiguous
2320  *		KERN_FAILURE		If the page cannot be looked up
2321  *
2322  * Implicit Returns:
2323  *		*phys_entryp (modified)	If phys_entryp is non-NULL and
2324  *					UPL_POP_PHYSICAL
2325  *		*flagsp (modified)	If flagsp is non-NULL and there was
2326  *					!UPL_POP_PHYSICAL and a KERN_SUCCESS
2327  *
2328  * Notes:	For object boundaries, it is considerably more efficient to
2329  *		ensure that f_offset is in fact on a page boundary, as this
2330  *		will avoid internal use of the hash table to identify the
2331  *		page, and would therefore skip a number of early optimizations.
2332  *		Since this is a page operation anyway, the caller should try
2333  *		to pass only a page aligned offset because of this.
2334  *
2335  *		*flagsp may be modified even if this function fails.  If it is
2336  *		modified, it will contain the condition of the page before the
2337  *		requested operation was attempted; these will only include the
2338  *		bitmap flags, and not the PL_POP_PHYSICAL, UPL_POP_DUMP,
2339  *		UPL_POP_SET, or UPL_POP_CLR bits.
2340  *
2341  *		The flags field may contain a specific operation, such as
2342  *		UPL_POP_PHYSICAL or UPL_POP_DUMP:
2343  *
2344  *		o	UPL_POP_PHYSICAL	Fail if not contiguous; if
2345  *						*phys_entryp and successful, set
2346  *						*phys_entryp
2347  *		o	UPL_POP_DUMP		Dump the specified page
2348  *
2349  *		Otherwise, it is treated as a bitmap of one or more page
2350  *		operations to perform on the final memory object; allowable
2351  *		bit values are:
2352  *
2353  *		o	UPL_POP_DIRTY		The page is dirty
2354  *		o	UPL_POP_PAGEOUT		The page is paged out
2355  *		o	UPL_POP_PRECIOUS	The page is precious
2356  *		o	UPL_POP_ABSENT		The page is absent
2357  *		o	UPL_POP_BUSY		The page is busy
2358  *
2359  *		If the page status is only being queried and not modified, then
2360  *		not other bits should be specified.  However, if it is being
2361  *		modified, exactly ONE of the following bits should be set:
2362  *
2363  *		o	UPL_POP_SET		Set the current bitmap bits
2364  *		o	UPL_POP_CLR		Clear the current bitmap bits
2365  *
2366  *		Thus to effect a combination of setting an clearing, it may be
2367  *		necessary to call this function twice.  If this is done, the
2368  *		set should be used before the clear, since clearing may trigger
2369  *		a wakeup on the destination page, and if the page is backed by
2370  *		an encrypted swap file, setting will trigger the decryption
2371  *		needed before the wakeup occurs.
2372  */
2373 kern_return_t
ubc_page_op(struct vnode * vp,off_t f_offset,int ops,ppnum_t * phys_entryp,int * flagsp)2374 ubc_page_op(
2375 	struct vnode    *vp,
2376 	off_t           f_offset,
2377 	int             ops,
2378 	ppnum_t *phys_entryp,
2379 	int             *flagsp)
2380 {
2381 	memory_object_control_t         control;
2382 
2383 	control = ubc_getobject(vp, UBC_FLAGS_NONE);
2384 	if (control == MEMORY_OBJECT_CONTROL_NULL) {
2385 		return KERN_INVALID_ARGUMENT;
2386 	}
2387 
2388 	return memory_object_page_op(control,
2389 	           (memory_object_offset_t)f_offset,
2390 	           ops,
2391 	           phys_entryp,
2392 	           flagsp);
2393 }
2394 
2395 
2396 /*
2397  * ubc_range_op
2398  *
2399  * Manipulate page state for a range of memory for a vnode with an associated
2400  * ubc_info with an associated memory object control, when page level state is
2401  * not required to be returned from the call (i.e. there are no phys_entryp or
2402  * flagsp parameters to this call, and it takes a range which may contain
2403  * multiple pages, rather than an offset interior to a single page).
2404  *
2405  * Parameters:	vp			The vnode backing the page
2406  *		f_offset_beg		A file offset interior to the start page
2407  *		f_offset_end		A file offset interior to the end page
2408  *		ops			The operations to perform, as a bitmap
2409  *					(see below for more information)
2410  *		range			The address of an int; may be NULL to
2411  *					ignore
2412  *
2413  * Returns:	KERN_SUCCESS		Success
2414  *		KERN_INVALID_ARGUMENT	If the memory object control has no VM
2415  *					object associated
2416  *		KERN_INVALID_OBJECT	If the object is physically contiguous
2417  *
2418  * Implicit Returns:
2419  *		*range (modified)	If range is non-NULL, its contents will
2420  *					be modified to contain the number of
2421  *					bytes successfully operated upon.
2422  *
2423  * Notes:	IMPORTANT: This function cannot be used on a range that
2424  *		consists of physically contiguous pages.
2425  *
2426  *		For object boundaries, it is considerably more efficient to
2427  *		ensure that f_offset_beg and f_offset_end are in fact on page
2428  *		boundaries, as this will avoid internal use of the hash table
2429  *		to identify the page, and would therefore skip a number of
2430  *		early optimizations.  Since this is an operation on a set of
2431  *		pages anyway, the caller should try to pass only a page aligned
2432  *		offsets because of this.
2433  *
2434  *		*range will be modified only if this function succeeds.
2435  *
2436  *		The flags field MUST contain a specific operation; allowable
2437  *		values are:
2438  *
2439  *		o	UPL_ROP_ABSENT	Returns the extent of the range
2440  *					presented which is absent, starting
2441  *					with the start address presented
2442  *
2443  *		o	UPL_ROP_PRESENT	Returns the extent of the range
2444  *					presented which is present (resident),
2445  *					starting with the start address
2446  *					presented
2447  *		o	UPL_ROP_DUMP	Dump the pages which are found in the
2448  *					target object for the target range.
2449  *
2450  *		IMPORTANT: For UPL_ROP_ABSENT and UPL_ROP_PRESENT; if there are
2451  *		multiple regions in the range, only the first matching region
2452  *		is returned.
2453  */
2454 kern_return_t
ubc_range_op(struct vnode * vp,off_t f_offset_beg,off_t f_offset_end,int ops,int * range)2455 ubc_range_op(
2456 	struct vnode    *vp,
2457 	off_t           f_offset_beg,
2458 	off_t           f_offset_end,
2459 	int             ops,
2460 	int             *range)
2461 {
2462 	memory_object_control_t         control;
2463 
2464 	control = ubc_getobject(vp, UBC_FLAGS_NONE);
2465 	if (control == MEMORY_OBJECT_CONTROL_NULL) {
2466 		return KERN_INVALID_ARGUMENT;
2467 	}
2468 
2469 	return memory_object_range_op(control,
2470 	           (memory_object_offset_t)f_offset_beg,
2471 	           (memory_object_offset_t)f_offset_end,
2472 	           ops,
2473 	           range);
2474 }
2475 
2476 
2477 /*
2478  * ubc_create_upl
2479  *
2480  * Given a vnode, cause the population of a portion of the vm_object; based on
2481  * the nature of the request, the pages returned may contain valid data, or
2482  * they may be uninitialized.
2483  *
2484  * Parameters:	vp			The vnode from which to create the upl
2485  *		f_offset		The start offset into the backing store
2486  *					represented by the vnode
2487  *		bufsize			The size of the upl to create
2488  *		uplp			Pointer to the upl_t to receive the
2489  *					created upl; MUST NOT be NULL
2490  *		plp			Pointer to receive the internal page
2491  *					list for the created upl; MAY be NULL
2492  *					to ignore
2493  *
2494  * Returns:	KERN_SUCCESS		The requested upl has been created
2495  *		KERN_INVALID_ARGUMENT	The bufsize argument is not an even
2496  *					multiple of the page size
2497  *		KERN_INVALID_ARGUMENT	There is no ubc_info associated with
2498  *					the vnode, or there is no memory object
2499  *					control associated with the ubc_info
2500  *	memory_object_upl_request:KERN_INVALID_VALUE
2501  *					The supplied upl_flags argument is
2502  *					invalid
2503  * Implicit Returns:
2504  *		*uplp (modified)
2505  *		*plp (modified)		If non-NULL, the value of *plp will be
2506  *					modified to point to the internal page
2507  *					list; this modification may occur even
2508  *					if this function is unsuccessful, in
2509  *					which case the contents may be invalid
2510  *
2511  * Note:	If successful, the returned *uplp MUST subsequently be freed
2512  *		via a call to ubc_upl_commit(), ubc_upl_commit_range(),
2513  *		ubc_upl_abort(), or ubc_upl_abort_range().
2514  */
2515 kern_return_t
ubc_create_upl_external(struct vnode * vp,off_t f_offset,int bufsize,upl_t * uplp,upl_page_info_t ** plp,int uplflags)2516 ubc_create_upl_external(
2517 	struct vnode    *vp,
2518 	off_t           f_offset,
2519 	int             bufsize,
2520 	upl_t           *uplp,
2521 	upl_page_info_t **plp,
2522 	int             uplflags)
2523 {
2524 	return ubc_create_upl_kernel(vp, f_offset, bufsize, uplp, plp, uplflags, vm_tag_bt());
2525 }
2526 
2527 kern_return_t
ubc_create_upl_kernel(struct vnode * vp,off_t f_offset,int bufsize,upl_t * uplp,upl_page_info_t ** plp,int uplflags,vm_tag_t tag)2528 ubc_create_upl_kernel(
2529 	struct vnode    *vp,
2530 	off_t           f_offset,
2531 	int             bufsize,
2532 	upl_t           *uplp,
2533 	upl_page_info_t **plp,
2534 	int             uplflags,
2535 	vm_tag_t tag)
2536 {
2537 	memory_object_control_t         control;
2538 	kern_return_t                   kr;
2539 
2540 	if (plp != NULL) {
2541 		*plp = NULL;
2542 	}
2543 	*uplp = NULL;
2544 
2545 	if (bufsize & 0xfff) {
2546 		return KERN_INVALID_ARGUMENT;
2547 	}
2548 
2549 	if (bufsize > MAX_UPL_SIZE_BYTES) {
2550 		return KERN_INVALID_ARGUMENT;
2551 	}
2552 
2553 	if (uplflags & (UPL_UBC_MSYNC | UPL_UBC_PAGEOUT | UPL_UBC_PAGEIN)) {
2554 		if (uplflags & UPL_UBC_MSYNC) {
2555 			uplflags &= UPL_RET_ONLY_DIRTY;
2556 
2557 			uplflags |= UPL_COPYOUT_FROM | UPL_CLEAN_IN_PLACE |
2558 			    UPL_SET_INTERNAL | UPL_SET_LITE;
2559 		} else if (uplflags & UPL_UBC_PAGEOUT) {
2560 			uplflags &= UPL_RET_ONLY_DIRTY;
2561 
2562 			if (uplflags & UPL_RET_ONLY_DIRTY) {
2563 				uplflags |= UPL_NOBLOCK;
2564 			}
2565 
2566 			uplflags |= UPL_FOR_PAGEOUT | UPL_CLEAN_IN_PLACE |
2567 			    UPL_COPYOUT_FROM | UPL_SET_INTERNAL | UPL_SET_LITE;
2568 		} else {
2569 			uplflags |= UPL_RET_ONLY_ABSENT |
2570 			    UPL_NO_SYNC | UPL_CLEAN_IN_PLACE |
2571 			    UPL_SET_INTERNAL | UPL_SET_LITE;
2572 
2573 			/*
2574 			 * if the requested size == PAGE_SIZE, we don't want to set
2575 			 * the UPL_NOBLOCK since we may be trying to recover from a
2576 			 * previous partial pagein I/O that occurred because we were low
2577 			 * on memory and bailed early in order to honor the UPL_NOBLOCK...
2578 			 * since we're only asking for a single page, we can block w/o fear
2579 			 * of tying up pages while waiting for more to become available
2580 			 */
2581 			if (bufsize > PAGE_SIZE) {
2582 				uplflags |= UPL_NOBLOCK;
2583 			}
2584 		}
2585 	} else {
2586 		uplflags &= ~UPL_FOR_PAGEOUT;
2587 
2588 		if (uplflags & UPL_WILL_BE_DUMPED) {
2589 			uplflags &= ~UPL_WILL_BE_DUMPED;
2590 			uplflags |= (UPL_NO_SYNC | UPL_SET_INTERNAL);
2591 		} else {
2592 			uplflags |= (UPL_NO_SYNC | UPL_CLEAN_IN_PLACE | UPL_SET_INTERNAL);
2593 		}
2594 	}
2595 	control = ubc_getobject(vp, UBC_FLAGS_NONE);
2596 	if (control == MEMORY_OBJECT_CONTROL_NULL) {
2597 		return KERN_INVALID_ARGUMENT;
2598 	}
2599 
2600 	kr = memory_object_upl_request(control, f_offset, bufsize, uplp, NULL, NULL, uplflags, tag);
2601 	if (kr == KERN_SUCCESS && plp != NULL) {
2602 		*plp = UPL_GET_INTERNAL_PAGE_LIST(*uplp);
2603 	}
2604 	return kr;
2605 }
2606 
2607 
2608 /*
2609  * ubc_upl_maxbufsize
2610  *
2611  * Return the maximum bufsize ubc_create_upl( ) will take.
2612  *
2613  * Parameters:	none
2614  *
2615  * Returns:	maximum size buffer (in bytes) ubc_create_upl( ) will take.
2616  */
2617 upl_size_t
ubc_upl_maxbufsize(void)2618 ubc_upl_maxbufsize(
2619 	void)
2620 {
2621 	return MAX_UPL_SIZE_BYTES;
2622 }
2623 
2624 /*
2625  * ubc_upl_map
2626  *
2627  * Map the page list assocated with the supplied upl into the kernel virtual
2628  * address space at the virtual address indicated by the dst_addr argument;
2629  * the entire upl is mapped
2630  *
2631  * Parameters:	upl			The upl to map
2632  *		dst_addr		The address at which to map the upl
2633  *
2634  * Returns:	KERN_SUCCESS		The upl has been mapped
2635  *		KERN_INVALID_ARGUMENT	The upl is UPL_NULL
2636  *		KERN_FAILURE		The upl is already mapped
2637  *	vm_map_enter:KERN_INVALID_ARGUMENT
2638  *					A failure code from vm_map_enter() due
2639  *					to an invalid argument
2640  */
2641 kern_return_t
ubc_upl_map(upl_t upl,vm_offset_t * dst_addr)2642 ubc_upl_map(
2643 	upl_t           upl,
2644 	vm_offset_t     *dst_addr)
2645 {
2646 	return vm_upl_map(kernel_map, upl, dst_addr);
2647 }
2648 
2649 /*
2650  * ubc_upl_map_range:- similar to ubc_upl_map but the focus is on a range
2651  * of the UPL. Takes an offset, size, and protection so that only a  part
2652  * of the UPL can be mapped with the right protections.
2653  */
2654 kern_return_t
ubc_upl_map_range(upl_t upl,vm_offset_t offset_to_map,vm_size_t size_to_map,vm_prot_t prot_to_map,vm_offset_t * dst_addr)2655 ubc_upl_map_range(
2656 	upl_t           upl,
2657 	vm_offset_t     offset_to_map,
2658 	vm_size_t       size_to_map,
2659 	vm_prot_t       prot_to_map,
2660 	vm_offset_t     *dst_addr)
2661 {
2662 	return vm_upl_map_range(kernel_map, upl, offset_to_map, size_to_map, prot_to_map, dst_addr);
2663 }
2664 
2665 
2666 /*
2667  * ubc_upl_unmap
2668  *
2669  * Unmap the page list assocated with the supplied upl from the kernel virtual
2670  * address space; the entire upl is unmapped.
2671  *
2672  * Parameters:	upl			The upl to unmap
2673  *
2674  * Returns:	KERN_SUCCESS		The upl has been unmapped
2675  *		KERN_FAILURE		The upl is not currently mapped
2676  *		KERN_INVALID_ARGUMENT	If the upl is UPL_NULL
2677  */
2678 kern_return_t
ubc_upl_unmap(upl_t upl)2679 ubc_upl_unmap(
2680 	upl_t   upl)
2681 {
2682 	return vm_upl_unmap(kernel_map, upl);
2683 }
2684 
2685 /*
2686  * ubc_upl_unmap_range:- similar to ubc_upl_unmap but the focus is
2687  * on part of the UPL that is mapped. The offset and size parameter
2688  * specifies what part of the UPL needs to be unmapped.
2689  *
2690  * Note: Currrently offset & size are unused as we always initiate the unmap from the
2691  * very beginning of the UPL's mapping and track the mapped size in the UPL. But we
2692  * might want to allow unmapping a UPL in the middle, for example, and we can use the
2693  * offset + size parameters for that purpose.
2694  */
2695 kern_return_t
ubc_upl_unmap_range(upl_t upl,vm_offset_t offset_to_unmap,vm_size_t size_to_unmap)2696 ubc_upl_unmap_range(
2697 	upl_t   upl,
2698 	vm_offset_t     offset_to_unmap,
2699 	vm_size_t       size_to_unmap)
2700 {
2701 	return vm_upl_unmap_range(kernel_map, upl, offset_to_unmap, size_to_unmap);
2702 }
2703 
2704 
2705 /*
2706  * ubc_upl_commit
2707  *
2708  * Commit the contents of the upl to the backing store
2709  *
2710  * Parameters:	upl			The upl to commit
2711  *
2712  * Returns:	KERN_SUCCESS		The upl has been committed
2713  *		KERN_INVALID_ARGUMENT	The supplied upl was UPL_NULL
2714  *		KERN_FAILURE		The supplied upl does not represent
2715  *					device memory, and the offset plus the
2716  *					size would exceed the actual size of
2717  *					the upl
2718  *
2719  * Notes:	In practice, the only return value for this function should be
2720  *		KERN_SUCCESS, unless there has been data structure corruption;
2721  *		since the upl is deallocated regardless of success or failure,
2722  *		there's really nothing to do about this other than panic.
2723  *
2724  *		IMPORTANT: Use of this function should not be mixed with use of
2725  *		ubc_upl_commit_range(), due to the unconditional deallocation
2726  *		by this function.
2727  */
2728 kern_return_t
ubc_upl_commit(upl_t upl)2729 ubc_upl_commit(
2730 	upl_t                   upl)
2731 {
2732 	upl_page_info_t *pl;
2733 	kern_return_t   kr;
2734 
2735 	pl = UPL_GET_INTERNAL_PAGE_LIST(upl);
2736 	kr = upl_commit(upl, pl, MAX_UPL_SIZE_BYTES >> PAGE_SHIFT);
2737 	upl_deallocate(upl);
2738 	return kr;
2739 }
2740 
2741 
2742 /*
2743  * ubc_upl_commit
2744  *
2745  * Commit the contents of the specified range of the upl to the backing store
2746  *
2747  * Parameters:	upl			The upl to commit
2748  *		offset			The offset into the upl
2749  *		size			The size of the region to be committed,
2750  *					starting at the specified offset
2751  *		flags			commit type (see below)
2752  *
2753  * Returns:	KERN_SUCCESS		The range has been committed
2754  *		KERN_INVALID_ARGUMENT	The supplied upl was UPL_NULL
2755  *		KERN_FAILURE		The supplied upl does not represent
2756  *					device memory, and the offset plus the
2757  *					size would exceed the actual size of
2758  *					the upl
2759  *
2760  * Notes:	IMPORTANT: If the commit is successful, and the object is now
2761  *		empty, the upl will be deallocated.  Since the caller cannot
2762  *		check that this is the case, the UPL_COMMIT_FREE_ON_EMPTY flag
2763  *		should generally only be used when the offset is 0 and the size
2764  *		is equal to the upl size.
2765  *
2766  *		The flags argument is a bitmap of flags on the rage of pages in
2767  *		the upl to be committed; allowable flags are:
2768  *
2769  *		o	UPL_COMMIT_FREE_ON_EMPTY	Free the upl when it is
2770  *							both empty and has been
2771  *							successfully committed
2772  *		o	UPL_COMMIT_CLEAR_DIRTY		Clear each pages dirty
2773  *							bit; will prevent a
2774  *							later pageout
2775  *		o	UPL_COMMIT_SET_DIRTY		Set each pages dirty
2776  *							bit; will cause a later
2777  *							pageout
2778  *		o	UPL_COMMIT_INACTIVATE		Clear each pages
2779  *							reference bit; the page
2780  *							will not be accessed
2781  *		o	UPL_COMMIT_ALLOW_ACCESS		Unbusy each page; pages
2782  *							become busy when an
2783  *							IOMemoryDescriptor is
2784  *							mapped or redirected,
2785  *							and we have to wait for
2786  *							an IOKit driver
2787  *
2788  *		The flag UPL_COMMIT_NOTIFY_EMPTY is used internally, and should
2789  *		not be specified by the caller.
2790  *
2791  *		The UPL_COMMIT_CLEAR_DIRTY and UPL_COMMIT_SET_DIRTY flags are
2792  *		mutually exclusive, and should not be combined.
2793  */
2794 kern_return_t
ubc_upl_commit_range(upl_t upl,upl_offset_t offset,upl_size_t size,int flags)2795 ubc_upl_commit_range(
2796 	upl_t                   upl,
2797 	upl_offset_t            offset,
2798 	upl_size_t              size,
2799 	int                             flags)
2800 {
2801 	upl_page_info_t *pl;
2802 	boolean_t               empty;
2803 	kern_return_t   kr;
2804 
2805 	if (flags & UPL_COMMIT_FREE_ON_EMPTY) {
2806 		flags |= UPL_COMMIT_NOTIFY_EMPTY;
2807 	}
2808 
2809 	if (flags & UPL_COMMIT_KERNEL_ONLY_FLAGS) {
2810 		return KERN_INVALID_ARGUMENT;
2811 	}
2812 
2813 	pl = UPL_GET_INTERNAL_PAGE_LIST(upl);
2814 
2815 	kr = upl_commit_range(upl, offset, size, flags,
2816 	    pl, MAX_UPL_SIZE_BYTES >> PAGE_SHIFT, &empty);
2817 
2818 	if ((flags & UPL_COMMIT_FREE_ON_EMPTY) && empty) {
2819 		upl_deallocate(upl);
2820 	}
2821 
2822 	return kr;
2823 }
2824 
2825 
2826 /*
2827  * ubc_upl_abort_range
2828  *
2829  * Abort the contents of the specified range of the specified upl
2830  *
2831  * Parameters:	upl			The upl to abort
2832  *		offset			The offset into the upl
2833  *		size			The size of the region to be aborted,
2834  *					starting at the specified offset
2835  *		abort_flags		abort type (see below)
2836  *
2837  * Returns:	KERN_SUCCESS		The range has been aborted
2838  *		KERN_INVALID_ARGUMENT	The supplied upl was UPL_NULL
2839  *		KERN_FAILURE		The supplied upl does not represent
2840  *					device memory, and the offset plus the
2841  *					size would exceed the actual size of
2842  *					the upl
2843  *
2844  * Notes:	IMPORTANT: If the abort is successful, and the object is now
2845  *		empty, the upl will be deallocated.  Since the caller cannot
2846  *		check that this is the case, the UPL_ABORT_FREE_ON_EMPTY flag
2847  *		should generally only be used when the offset is 0 and the size
2848  *		is equal to the upl size.
2849  *
2850  *		The abort_flags argument is a bitmap of flags on the range of
2851  *		pages in the upl to be aborted; allowable flags are:
2852  *
2853  *		o	UPL_ABORT_FREE_ON_EMPTY	Free the upl when it is both
2854  *						empty and has been successfully
2855  *						aborted
2856  *		o	UPL_ABORT_RESTART	The operation must be restarted
2857  *		o	UPL_ABORT_UNAVAILABLE	The pages are unavailable
2858  *		o	UPL_ABORT_ERROR		An I/O error occurred
2859  *		o	UPL_ABORT_DUMP_PAGES	Just free the pages
2860  *		o	UPL_ABORT_NOTIFY_EMPTY	RESERVED
2861  *		o	UPL_ABORT_ALLOW_ACCESS	RESERVED
2862  *
2863  *		The UPL_ABORT_NOTIFY_EMPTY is an internal use flag and should
2864  *		not be specified by the caller.  It is intended to fulfill the
2865  *		same role as UPL_COMMIT_NOTIFY_EMPTY does in the function
2866  *		ubc_upl_commit_range(), but is never referenced internally.
2867  *
2868  *		The UPL_ABORT_ALLOW_ACCESS is defined, but neither set nor
2869  *		referenced; do not use it.
2870  */
2871 kern_return_t
ubc_upl_abort_range(upl_t upl,upl_offset_t offset,upl_size_t size,int abort_flags)2872 ubc_upl_abort_range(
2873 	upl_t                   upl,
2874 	upl_offset_t            offset,
2875 	upl_size_t              size,
2876 	int                             abort_flags)
2877 {
2878 	kern_return_t   kr;
2879 	boolean_t               empty = FALSE;
2880 
2881 	if (abort_flags & UPL_ABORT_FREE_ON_EMPTY) {
2882 		abort_flags |= UPL_ABORT_NOTIFY_EMPTY;
2883 	}
2884 
2885 	kr = upl_abort_range(upl, offset, size, abort_flags, &empty);
2886 
2887 	if ((abort_flags & UPL_ABORT_FREE_ON_EMPTY) && empty) {
2888 		upl_deallocate(upl);
2889 	}
2890 
2891 	return kr;
2892 }
2893 
2894 
2895 /*
2896  * ubc_upl_abort
2897  *
2898  * Abort the contents of the specified upl
2899  *
2900  * Parameters:	upl			The upl to abort
2901  *		abort_type		abort type (see below)
2902  *
2903  * Returns:	KERN_SUCCESS		The range has been aborted
2904  *		KERN_INVALID_ARGUMENT	The supplied upl was UPL_NULL
2905  *		KERN_FAILURE		The supplied upl does not represent
2906  *					device memory, and the offset plus the
2907  *					size would exceed the actual size of
2908  *					the upl
2909  *
2910  * Notes:	IMPORTANT: If the abort is successful, and the object is now
2911  *		empty, the upl will be deallocated.  Since the caller cannot
2912  *		check that this is the case, the UPL_ABORT_FREE_ON_EMPTY flag
2913  *		should generally only be used when the offset is 0 and the size
2914  *		is equal to the upl size.
2915  *
2916  *		The abort_type is a bitmap of flags on the range of
2917  *		pages in the upl to be aborted; allowable flags are:
2918  *
2919  *		o	UPL_ABORT_FREE_ON_EMPTY	Free the upl when it is both
2920  *						empty and has been successfully
2921  *						aborted
2922  *		o	UPL_ABORT_RESTART	The operation must be restarted
2923  *		o	UPL_ABORT_UNAVAILABLE	The pages are unavailable
2924  *		o	UPL_ABORT_ERROR		An I/O error occurred
2925  *		o	UPL_ABORT_DUMP_PAGES	Just free the pages
2926  *		o	UPL_ABORT_NOTIFY_EMPTY	RESERVED
2927  *		o	UPL_ABORT_ALLOW_ACCESS	RESERVED
2928  *
2929  *		The UPL_ABORT_NOTIFY_EMPTY is an internal use flag and should
2930  *		not be specified by the caller.  It is intended to fulfill the
2931  *		same role as UPL_COMMIT_NOTIFY_EMPTY does in the function
2932  *		ubc_upl_commit_range(), but is never referenced internally.
2933  *
2934  *		The UPL_ABORT_ALLOW_ACCESS is defined, but neither set nor
2935  *		referenced; do not use it.
2936  */
2937 kern_return_t
ubc_upl_abort(upl_t upl,int abort_type)2938 ubc_upl_abort(
2939 	upl_t                   upl,
2940 	int                             abort_type)
2941 {
2942 	kern_return_t   kr;
2943 
2944 	kr = upl_abort(upl, abort_type);
2945 	upl_deallocate(upl);
2946 	return kr;
2947 }
2948 
2949 
2950 /*
2951  * ubc_upl_pageinfo
2952  *
2953  *  Retrieve the internal page list for the specified upl
2954  *
2955  * Parameters:	upl			The upl to obtain the page list from
2956  *
2957  * Returns:	!NULL			The (upl_page_info_t *) for the page
2958  *					list internal to the upl
2959  *		NULL			Error/no page list associated
2960  *
2961  * Notes:	IMPORTANT: The function is only valid on internal objects
2962  *		where the list request was made with the UPL_INTERNAL flag.
2963  *
2964  *		This function is a utility helper function, since some callers
2965  *		may not have direct access to the header defining the macro,
2966  *		due to abstraction layering constraints.
2967  */
2968 upl_page_info_t *
ubc_upl_pageinfo(upl_t upl)2969 ubc_upl_pageinfo(
2970 	upl_t                   upl)
2971 {
2972 	return UPL_GET_INTERNAL_PAGE_LIST(upl);
2973 }
2974 
2975 
2976 int
UBCINFOEXISTS(const struct vnode * vp)2977 UBCINFOEXISTS(const struct vnode * vp)
2978 {
2979 	return (vp) && ((vp)->v_type == VREG) && ((vp)->v_ubcinfo != UBC_INFO_NULL);
2980 }
2981 
2982 
2983 void
ubc_upl_range_needed(upl_t upl,int index,int count)2984 ubc_upl_range_needed(
2985 	upl_t           upl,
2986 	int             index,
2987 	int             count)
2988 {
2989 	upl_range_needed(upl, index, count);
2990 }
2991 
2992 boolean_t
ubc_is_mapped(const struct vnode * vp,boolean_t * writable)2993 ubc_is_mapped(const struct vnode *vp, boolean_t *writable)
2994 {
2995 	if (!UBCINFOEXISTS(vp) || !ISSET(vp->v_ubcinfo->ui_flags, UI_ISMAPPED)) {
2996 		return FALSE;
2997 	}
2998 	if (writable) {
2999 		*writable = ISSET(vp->v_ubcinfo->ui_flags, UI_MAPPEDWRITE);
3000 	}
3001 	return TRUE;
3002 }
3003 
3004 boolean_t
ubc_is_mapped_writable(const struct vnode * vp)3005 ubc_is_mapped_writable(const struct vnode *vp)
3006 {
3007 	boolean_t writable;
3008 	return ubc_is_mapped(vp, &writable) && writable;
3009 }
3010 
3011 boolean_t
ubc_was_mapped(const struct vnode * vp,boolean_t * writable)3012 ubc_was_mapped(const struct vnode *vp, boolean_t *writable)
3013 {
3014 	if (!UBCINFOEXISTS(vp) || !ISSET(vp->v_ubcinfo->ui_flags, UI_WASMAPPED)) {
3015 		return FALSE;
3016 	}
3017 	if (writable) {
3018 		*writable = ISSET(vp->v_ubcinfo->ui_flags, UI_WASMAPPEDWRITE);
3019 	}
3020 	return TRUE;
3021 }
3022 
3023 boolean_t
ubc_was_mapped_writable(const struct vnode * vp)3024 ubc_was_mapped_writable(const struct vnode *vp)
3025 {
3026 	boolean_t writable;
3027 	return ubc_was_mapped(vp, &writable) && writable;
3028 }
3029 
3030 
3031 /*
3032  * CODE SIGNING
3033  */
3034 static atomic_size_t cs_blob_size = 0;
3035 static atomic_uint_fast32_t cs_blob_count = 0;
3036 static atomic_size_t cs_blob_size_peak = 0;
3037 static atomic_size_t cs_blob_size_max = 0;
3038 static atomic_uint_fast32_t cs_blob_count_peak = 0;
3039 
3040 SYSCTL_UINT(_vm, OID_AUTO, cs_blob_count, CTLFLAG_RD | CTLFLAG_LOCKED, &cs_blob_count, 0, "Current number of code signature blobs");
3041 SYSCTL_ULONG(_vm, OID_AUTO, cs_blob_size, CTLFLAG_RD | CTLFLAG_LOCKED, &cs_blob_size, "Current size of all code signature blobs");
3042 SYSCTL_UINT(_vm, OID_AUTO, cs_blob_count_peak, CTLFLAG_RD | CTLFLAG_LOCKED, &cs_blob_count_peak, 0, "Peak number of code signature blobs");
3043 SYSCTL_ULONG(_vm, OID_AUTO, cs_blob_size_peak, CTLFLAG_RD | CTLFLAG_LOCKED, &cs_blob_size_peak, "Peak size of code signature blobs");
3044 SYSCTL_ULONG(_vm, OID_AUTO, cs_blob_size_max, CTLFLAG_RD | CTLFLAG_LOCKED, &cs_blob_size_max, "Size of biggest code signature blob");
3045 
3046 /*
3047  * Function: csblob_parse_teamid
3048  *
3049  * Description: This function returns a pointer to the team id
3050  *               stored within the codedirectory of the csblob.
3051  *               If the codedirectory predates team-ids, it returns
3052  *               NULL.
3053  *               This does not copy the name but returns a pointer to
3054  *               it within the CD. Subsequently, the CD must be
3055  *               available when this is used.
3056  */
3057 
3058 static const char *
csblob_parse_teamid(struct cs_blob * csblob)3059 csblob_parse_teamid(struct cs_blob *csblob)
3060 {
3061 	const CS_CodeDirectory *cd;
3062 
3063 	cd = csblob->csb_cd;
3064 
3065 	if (ntohl(cd->version) < CS_SUPPORTSTEAMID) {
3066 		return NULL;
3067 	}
3068 
3069 	if (cd->teamOffset == 0) {
3070 		return NULL;
3071 	}
3072 
3073 	const char *name = ((const char *)cd) + ntohl(cd->teamOffset);
3074 	if (cs_debug > 1) {
3075 		printf("found team-id %s in cdblob\n", name);
3076 	}
3077 
3078 	return name;
3079 }
3080 
3081 kern_return_t
ubc_cs_blob_allocate(vm_offset_t * blob_addr_p,vm_size_t * blob_size_p)3082 ubc_cs_blob_allocate(
3083 	vm_offset_t     *blob_addr_p,
3084 	vm_size_t       *blob_size_p)
3085 {
3086 	kern_return_t   kr = KERN_FAILURE;
3087 	vm_size_t       allocation_size = 0;
3088 
3089 	if (!blob_addr_p || !blob_size_p) {
3090 		return KERN_INVALID_ARGUMENT;
3091 	}
3092 	allocation_size = *blob_size_p;
3093 
3094 	if (ubc_cs_blob_pagewise_allocate(allocation_size) == true) {
3095 		/* Round up to page size */
3096 		allocation_size = round_page(allocation_size);
3097 
3098 		/* Allocate page-wise */
3099 		kr = kmem_alloc(
3100 			kernel_map,
3101 			blob_addr_p,
3102 			allocation_size,
3103 			KMA_KOBJECT | KMA_DATA | KMA_ZERO,
3104 			VM_KERN_MEMORY_SECURITY);
3105 	} else {
3106 		*blob_addr_p = (vm_offset_t)kalloc_data_tag(
3107 			allocation_size,
3108 			Z_WAITOK | Z_ZERO,
3109 			VM_KERN_MEMORY_SECURITY);
3110 
3111 		assert(*blob_addr_p != 0);
3112 		kr = KERN_SUCCESS;
3113 	}
3114 
3115 	if (kr == KERN_SUCCESS) {
3116 		*blob_size_p = allocation_size;
3117 	}
3118 
3119 	return kr;
3120 }
3121 
3122 void
ubc_cs_blob_deallocate(vm_offset_t blob_addr,vm_size_t blob_size)3123 ubc_cs_blob_deallocate(
3124 	vm_offset_t     blob_addr,
3125 	vm_size_t       blob_size)
3126 {
3127 	if (ubc_cs_blob_pagewise_allocate(blob_size) == true) {
3128 		kmem_free(kernel_map, blob_addr, blob_size);
3129 	} else {
3130 		kfree_data(blob_addr, blob_size);
3131 	}
3132 }
3133 
3134 /*
3135  * Some codesigned files use a lowest common denominator page size of
3136  * 4KiB, but can be used on systems that have a runtime page size of
3137  * 16KiB. Since faults will only occur on 16KiB ranges in
3138  * cs_validate_range(), we can convert the original Code Directory to
3139  * a multi-level scheme where groups of 4 hashes are combined to form
3140  * a new hash, which represents 16KiB in the on-disk file.  This can
3141  * reduce the wired memory requirement for the Code Directory by
3142  * 75%.
3143  */
3144 static boolean_t
ubc_cs_supports_multilevel_hash(struct cs_blob * blob __unused)3145 ubc_cs_supports_multilevel_hash(struct cs_blob *blob __unused)
3146 {
3147 	const CS_CodeDirectory *cd;
3148 
3149 #if CODE_SIGNING_MONITOR
3150 	// TODO: <rdar://problem/30954826>
3151 	if (csm_enabled() == true) {
3152 		return FALSE;
3153 	}
3154 #endif
3155 
3156 	/*
3157 	 * Only applies to binaries that ship as part of the OS,
3158 	 * primarily the shared cache.
3159 	 */
3160 	if (!blob->csb_platform_binary || blob->csb_teamid != NULL) {
3161 		return FALSE;
3162 	}
3163 
3164 	/*
3165 	 * If the runtime page size matches the code signing page
3166 	 * size, there is no work to do.
3167 	 */
3168 	if (PAGE_SHIFT <= blob->csb_hash_pageshift) {
3169 		return FALSE;
3170 	}
3171 
3172 	cd = blob->csb_cd;
3173 
3174 	/*
3175 	 * There must be a valid integral multiple of hashes
3176 	 */
3177 	if (ntohl(cd->nCodeSlots) & (PAGE_MASK >> blob->csb_hash_pageshift)) {
3178 		return FALSE;
3179 	}
3180 
3181 	/*
3182 	 * Scatter lists must also have ranges that have an integral number of hashes
3183 	 */
3184 	if ((ntohl(cd->version) >= CS_SUPPORTSSCATTER) && (ntohl(cd->scatterOffset))) {
3185 		const SC_Scatter *scatter = (const SC_Scatter*)
3186 		    ((const char*)cd + ntohl(cd->scatterOffset));
3187 		/* iterate all scatter structs to make sure they are all aligned */
3188 		do {
3189 			uint32_t sbase = ntohl(scatter->base);
3190 			uint32_t scount = ntohl(scatter->count);
3191 
3192 			/* last scatter? */
3193 			if (scount == 0) {
3194 				break;
3195 			}
3196 
3197 			if (sbase & (PAGE_MASK >> blob->csb_hash_pageshift)) {
3198 				return FALSE;
3199 			}
3200 
3201 			if (scount & (PAGE_MASK >> blob->csb_hash_pageshift)) {
3202 				return FALSE;
3203 			}
3204 
3205 			scatter++;
3206 		} while (1);
3207 	}
3208 
3209 	/* Covered range must be a multiple of the new page size */
3210 	if (ntohl(cd->codeLimit) & PAGE_MASK) {
3211 		return FALSE;
3212 	}
3213 
3214 	/* All checks pass */
3215 	return TRUE;
3216 }
3217 
3218 /*
3219  * Reconstruct a cs_blob with the code signature fields. This helper function
3220  * is useful because a lot of things often change the base address of the code
3221  * signature blob, which requires reconstructing some of the other pointers
3222  * within.
3223  */
3224 static errno_t
ubc_cs_blob_reconstruct(struct cs_blob * cs_blob,const vm_address_t signature_addr,const vm_address_t signature_size,const vm_offset_t code_directory_offset)3225 ubc_cs_blob_reconstruct(
3226 	struct cs_blob *cs_blob,
3227 	const vm_address_t signature_addr,
3228 	const vm_address_t signature_size,
3229 	const vm_offset_t code_directory_offset)
3230 {
3231 	const CS_CodeDirectory *code_directory = NULL;
3232 
3233 	/* Setup the signature blob address */
3234 	cs_blob->csb_mem_kaddr = (void*)signature_addr;
3235 	cs_blob->csb_mem_size = signature_size;
3236 
3237 	/* Setup the code directory in the blob */
3238 	code_directory = (const CS_CodeDirectory*)(signature_addr + code_directory_offset);
3239 	cs_blob->csb_cd = code_directory;
3240 
3241 	/* Setup the XML entitlements */
3242 	cs_blob->csb_entitlements_blob = csblob_find_blob_bytes(
3243 		(uint8_t*)signature_addr,
3244 		signature_size,
3245 		CSSLOT_ENTITLEMENTS,
3246 		CSMAGIC_EMBEDDED_ENTITLEMENTS);
3247 
3248 	/* Setup the DER entitlements */
3249 	cs_blob->csb_der_entitlements_blob = csblob_find_blob_bytes(
3250 		(uint8_t*)signature_addr,
3251 		signature_size,
3252 		CSSLOT_DER_ENTITLEMENTS,
3253 		CSMAGIC_EMBEDDED_DER_ENTITLEMENTS);
3254 
3255 	return 0;
3256 }
3257 
3258 /*
3259  * Given a validated cs_blob, we reformat the structure to only include
3260  * the blobs which are required by the kernel for our current platform.
3261  * This saves significant memory with agile signatures.
3262  *
3263  * To support rewriting the code directory, potentially through
3264  * multilevel hashes, we provide a mechanism to allocate a code directory
3265  * of a specified size and zero it out --> caller can fill it in.
3266  *
3267  * We don't need to perform a lot of overflow checks as the assumption
3268  * here is that the cs_blob has already been validated.
3269  */
3270 static errno_t
ubc_cs_reconstitute_code_signature(const struct cs_blob * const blob,vm_address_t * const ret_mem_kaddr,vm_size_t * const ret_mem_size,vm_size_t code_directory_size,CS_CodeDirectory ** const code_directory)3271 ubc_cs_reconstitute_code_signature(
3272 	const struct cs_blob * const blob,
3273 	vm_address_t * const ret_mem_kaddr,
3274 	vm_size_t * const ret_mem_size,
3275 	vm_size_t code_directory_size,
3276 	CS_CodeDirectory ** const code_directory
3277 	)
3278 {
3279 	vm_address_t new_blob_addr = 0;
3280 	vm_size_t new_blob_size = 0;
3281 	vm_size_t new_code_directory_size = 0;
3282 	const CS_GenericBlob *best_code_directory = NULL;
3283 	const CS_GenericBlob *first_code_directory = NULL;
3284 	const CS_GenericBlob *der_entitlements_blob = NULL;
3285 	const CS_GenericBlob *entitlements_blob = NULL;
3286 	const CS_GenericBlob *cms_blob = NULL;
3287 	const CS_GenericBlob *launch_constraint_self = NULL;
3288 	const CS_GenericBlob *launch_constraint_parent = NULL;
3289 	const CS_GenericBlob *launch_constraint_responsible = NULL;
3290 	const CS_GenericBlob *library_constraint = NULL;
3291 	CS_SuperBlob *superblob = NULL;
3292 	uint32_t num_blobs = 0;
3293 	uint32_t blob_index = 0;
3294 	uint32_t blob_offset = 0;
3295 	kern_return_t ret;
3296 	int err;
3297 
3298 	if (!blob) {
3299 		if (cs_debug > 1) {
3300 			printf("CODE SIGNING: CS Blob passed in is NULL\n");
3301 		}
3302 		return EINVAL;
3303 	}
3304 
3305 	best_code_directory = (const CS_GenericBlob*)blob->csb_cd;
3306 	if (!best_code_directory) {
3307 		/* This case can never happen, and it is a sign of bad things */
3308 		panic("CODE SIGNING: Validated CS Blob has no code directory");
3309 	}
3310 
3311 	new_code_directory_size = code_directory_size;
3312 	if (new_code_directory_size == 0) {
3313 		new_code_directory_size = ntohl(best_code_directory->length);
3314 	}
3315 
3316 	/*
3317 	 * A code signature can contain multiple code directories, each of which contains hashes
3318 	 * of pages based on a hashing algorithm. The kernel selects which hashing algorithm is
3319 	 * the strongest, and consequently, marks one of these code directories as the best
3320 	 * matched one. More often than not, the best matched one is _not_ the first one.
3321 	 *
3322 	 * However, the CMS blob which cryptographically verifies the code signature is only
3323 	 * signed against the first code directory. Therefore, if the CMS blob is present, we also
3324 	 * need the first code directory to be able to verify it. Given this, we organize the
3325 	 * new cs_blob as following order:
3326 	 *
3327 	 * 1. best code directory
3328 	 * 2. DER encoded entitlements blob (if present)
3329 	 * 3. launch constraint self (if present)
3330 	 * 4. launch constraint parent (if present)
3331 	 * 5. launch constraint responsible (if present)
3332 	 * 6. library constraint (if present)
3333 	 * 7. entitlements blob (if present)
3334 	 * 8. cms blob (if present)
3335 	 * 9. first code directory (if not already the best match, and if cms blob is present)
3336 	 *
3337 	 * This order is chosen deliberately, as later on, we expect to get rid of the CMS blob
3338 	 * and the first code directory once their verification is complete.
3339 	 */
3340 
3341 	/* Storage for the super blob header */
3342 	new_blob_size += sizeof(CS_SuperBlob);
3343 
3344 	/* Guaranteed storage for the best code directory */
3345 	new_blob_size += sizeof(CS_BlobIndex);
3346 	new_blob_size += new_code_directory_size;
3347 	num_blobs += 1;
3348 
3349 	/* Conditional storage for the DER entitlements blob */
3350 	der_entitlements_blob = blob->csb_der_entitlements_blob;
3351 	if (der_entitlements_blob) {
3352 		new_blob_size += sizeof(CS_BlobIndex);
3353 		new_blob_size += ntohl(der_entitlements_blob->length);
3354 		num_blobs += 1;
3355 	}
3356 
3357 	/* Conditional storage for the launch constraints self blob */
3358 	launch_constraint_self = csblob_find_blob_bytes(
3359 		(const uint8_t *)blob->csb_mem_kaddr,
3360 		blob->csb_mem_size,
3361 		CSSLOT_LAUNCH_CONSTRAINT_SELF,
3362 		CSMAGIC_EMBEDDED_LAUNCH_CONSTRAINT);
3363 	if (launch_constraint_self) {
3364 		new_blob_size += sizeof(CS_BlobIndex);
3365 		new_blob_size += ntohl(launch_constraint_self->length);
3366 		num_blobs += 1;
3367 	}
3368 
3369 	/* Conditional storage for the launch constraints parent blob */
3370 	launch_constraint_parent = csblob_find_blob_bytes(
3371 		(const uint8_t *)blob->csb_mem_kaddr,
3372 		blob->csb_mem_size,
3373 		CSSLOT_LAUNCH_CONSTRAINT_PARENT,
3374 		CSMAGIC_EMBEDDED_LAUNCH_CONSTRAINT);
3375 	if (launch_constraint_parent) {
3376 		new_blob_size += sizeof(CS_BlobIndex);
3377 		new_blob_size += ntohl(launch_constraint_parent->length);
3378 		num_blobs += 1;
3379 	}
3380 
3381 	/* Conditional storage for the launch constraints responsible blob */
3382 	launch_constraint_responsible = csblob_find_blob_bytes(
3383 		(const uint8_t *)blob->csb_mem_kaddr,
3384 		blob->csb_mem_size,
3385 		CSSLOT_LAUNCH_CONSTRAINT_RESPONSIBLE,
3386 		CSMAGIC_EMBEDDED_LAUNCH_CONSTRAINT);
3387 	if (launch_constraint_responsible) {
3388 		new_blob_size += sizeof(CS_BlobIndex);
3389 		new_blob_size += ntohl(launch_constraint_responsible->length);
3390 		num_blobs += 1;
3391 	}
3392 
3393 	/* Conditional storage for the library constraintsblob */
3394 	library_constraint = csblob_find_blob_bytes(
3395 		(const uint8_t *)blob->csb_mem_kaddr,
3396 		blob->csb_mem_size,
3397 		CSSLOT_LIBRARY_CONSTRAINT,
3398 		CSMAGIC_EMBEDDED_LAUNCH_CONSTRAINT);
3399 	if (library_constraint) {
3400 		new_blob_size += sizeof(CS_BlobIndex);
3401 		new_blob_size += ntohl(library_constraint->length);
3402 		num_blobs += 1;
3403 	}
3404 
3405 	/* Conditional storage for the entitlements blob */
3406 	entitlements_blob = blob->csb_entitlements_blob;
3407 	if (entitlements_blob) {
3408 		new_blob_size += sizeof(CS_BlobIndex);
3409 		new_blob_size += ntohl(entitlements_blob->length);
3410 		num_blobs += 1;
3411 	}
3412 
3413 	/* Conditional storage for the CMS blob */
3414 	cms_blob = csblob_find_blob_bytes((const uint8_t *)blob->csb_mem_kaddr, blob->csb_mem_size, CSSLOT_SIGNATURESLOT, CSMAGIC_BLOBWRAPPER);
3415 	if (cms_blob) {
3416 		new_blob_size += sizeof(CS_BlobIndex);
3417 		new_blob_size += ntohl(cms_blob->length);
3418 		num_blobs += 1;
3419 	}
3420 
3421 	/*
3422 	 * Conditional storage for the first code directory.
3423 	 * This is only needed if a CMS blob exists and the best code directory isn't already
3424 	 * the first one. It is an error if we find a CMS blob but do not find a first code directory.
3425 	 */
3426 	if (cms_blob) {
3427 		first_code_directory = csblob_find_blob_bytes((const uint8_t *)blob->csb_mem_kaddr, blob->csb_mem_size, CSSLOT_CODEDIRECTORY, CSMAGIC_CODEDIRECTORY);
3428 		if (first_code_directory == best_code_directory) {
3429 			/* We don't need the first code directory anymore, since the best one is already it */
3430 			first_code_directory = NULL;
3431 		} else if (first_code_directory) {
3432 			new_blob_size += sizeof(CS_BlobIndex);
3433 			new_blob_size += ntohl(first_code_directory->length);
3434 			num_blobs += 1;
3435 		} else {
3436 			printf("CODE SIGNING: Invalid CS Blob: found CMS blob but not a first code directory\n");
3437 			return EINVAL;
3438 		}
3439 	}
3440 
3441 	/*
3442 	 * The blob size could be rouded up to page size here, so we keep a copy
3443 	 * of the actual superblob length as well.
3444 	 */
3445 	vm_size_t new_blob_allocation_size = new_blob_size;
3446 	ret = ubc_cs_blob_allocate(&new_blob_addr, &new_blob_allocation_size);
3447 	if (ret != KERN_SUCCESS) {
3448 		printf("CODE SIGNING: Failed to allocate memory for new code signing blob: %d\n", ret);
3449 		return ENOMEM;
3450 	}
3451 
3452 	/*
3453 	 * Fill out the superblob header and then all the blobs in the order listed
3454 	 * above.
3455 	 */
3456 	superblob = (CS_SuperBlob*)new_blob_addr;
3457 	superblob->magic = htonl(CSMAGIC_EMBEDDED_SIGNATURE);
3458 	superblob->length = htonl((uint32_t)new_blob_size);
3459 	superblob->count = htonl(num_blobs);
3460 
3461 	blob_index = 0;
3462 	blob_offset = sizeof(CS_SuperBlob) + (num_blobs * sizeof(CS_BlobIndex));
3463 
3464 	/* Best code directory */
3465 	superblob->index[blob_index].offset = htonl(blob_offset);
3466 	if (first_code_directory) {
3467 		superblob->index[blob_index].type = htonl(CSSLOT_ALTERNATE_CODEDIRECTORIES);
3468 	} else {
3469 		superblob->index[blob_index].type = htonl(CSSLOT_CODEDIRECTORY);
3470 	}
3471 
3472 	if (code_directory_size > 0) {
3473 		/* We zero out the code directory, as we expect the caller to fill it in */
3474 		memset((void*)(new_blob_addr + blob_offset), 0, new_code_directory_size);
3475 	} else {
3476 		memcpy((void*)(new_blob_addr + blob_offset), best_code_directory, new_code_directory_size);
3477 	}
3478 
3479 	if (code_directory) {
3480 		*code_directory = (CS_CodeDirectory*)(new_blob_addr + blob_offset);
3481 	}
3482 	blob_offset += new_code_directory_size;
3483 
3484 	/* DER entitlements blob */
3485 	if (der_entitlements_blob) {
3486 		blob_index += 1;
3487 		superblob->index[blob_index].offset = htonl(blob_offset);
3488 		superblob->index[blob_index].type = htonl(CSSLOT_DER_ENTITLEMENTS);
3489 
3490 		memcpy((void*)(new_blob_addr + blob_offset), der_entitlements_blob, ntohl(der_entitlements_blob->length));
3491 		blob_offset += ntohl(der_entitlements_blob->length);
3492 	}
3493 
3494 	/* Launch constraints self blob */
3495 	if (launch_constraint_self) {
3496 		blob_index += 1;
3497 		superblob->index[blob_index].offset = htonl(blob_offset);
3498 		superblob->index[blob_index].type = htonl(CSSLOT_LAUNCH_CONSTRAINT_SELF);
3499 
3500 		memcpy(
3501 			(void*)(new_blob_addr + blob_offset),
3502 			launch_constraint_self,
3503 			ntohl(launch_constraint_self->length));
3504 
3505 		blob_offset += ntohl(launch_constraint_self->length);
3506 	}
3507 
3508 	/* Launch constraints parent blob */
3509 	if (launch_constraint_parent) {
3510 		blob_index += 1;
3511 		superblob->index[blob_index].offset = htonl(blob_offset);
3512 		superblob->index[blob_index].type = htonl(CSSLOT_LAUNCH_CONSTRAINT_PARENT);
3513 
3514 		memcpy(
3515 			(void*)(new_blob_addr + blob_offset),
3516 			launch_constraint_parent,
3517 			ntohl(launch_constraint_parent->length));
3518 
3519 		blob_offset += ntohl(launch_constraint_parent->length);
3520 	}
3521 
3522 	/* Launch constraints responsible blob */
3523 	if (launch_constraint_responsible) {
3524 		blob_index += 1;
3525 		superblob->index[blob_index].offset = htonl(blob_offset);
3526 		superblob->index[blob_index].type = htonl(CSSLOT_LAUNCH_CONSTRAINT_RESPONSIBLE);
3527 
3528 		memcpy(
3529 			(void*)(new_blob_addr + blob_offset),
3530 			launch_constraint_responsible,
3531 			ntohl(launch_constraint_responsible->length));
3532 
3533 		blob_offset += ntohl(launch_constraint_responsible->length);
3534 	}
3535 
3536 	/* library constraints blob */
3537 	if (library_constraint) {
3538 		blob_index += 1;
3539 		superblob->index[blob_index].offset = htonl(blob_offset);
3540 		superblob->index[blob_index].type = htonl(CSSLOT_LIBRARY_CONSTRAINT);
3541 
3542 		memcpy(
3543 			(void*)(new_blob_addr + blob_offset),
3544 			library_constraint,
3545 			ntohl(library_constraint->length));
3546 
3547 		blob_offset += ntohl(library_constraint->length);
3548 	}
3549 
3550 	/* Entitlements blob */
3551 	if (entitlements_blob) {
3552 		blob_index += 1;
3553 		superblob->index[blob_index].offset = htonl(blob_offset);
3554 		superblob->index[blob_index].type = htonl(CSSLOT_ENTITLEMENTS);
3555 
3556 		memcpy((void*)(new_blob_addr + blob_offset), entitlements_blob, ntohl(entitlements_blob->length));
3557 		blob_offset += ntohl(entitlements_blob->length);
3558 	}
3559 
3560 	/* CMS blob */
3561 	if (cms_blob) {
3562 		blob_index += 1;
3563 		superblob->index[blob_index].offset = htonl(blob_offset);
3564 		superblob->index[blob_index].type = htonl(CSSLOT_SIGNATURESLOT);
3565 		memcpy((void*)(new_blob_addr + blob_offset), cms_blob, ntohl(cms_blob->length));
3566 		blob_offset += ntohl(cms_blob->length);
3567 	}
3568 
3569 	/* First code directory */
3570 	if (first_code_directory) {
3571 		blob_index += 1;
3572 		superblob->index[blob_index].offset = htonl(blob_offset);
3573 		superblob->index[blob_index].type = htonl(CSSLOT_CODEDIRECTORY);
3574 		memcpy((void*)(new_blob_addr + blob_offset), first_code_directory, ntohl(first_code_directory->length));
3575 		blob_offset += ntohl(first_code_directory->length);
3576 	}
3577 
3578 	/*
3579 	 * We only validate the blob in case we copied in the best code directory.
3580 	 * In case the code directory size we were passed in wasn't 0, we memset the best
3581 	 * code directory to 0 and expect the caller to fill it in. In the same spirit, we
3582 	 * expect the caller to validate the code signature after they fill in the code
3583 	 * directory.
3584 	 */
3585 	if (code_directory_size == 0) {
3586 		const CS_CodeDirectory *validated_code_directory = NULL;
3587 		const CS_GenericBlob *validated_entitlements_blob = NULL;
3588 		const CS_GenericBlob *validated_der_entitlements_blob = NULL;
3589 
3590 		ret = cs_validate_csblob(
3591 			(const uint8_t *)superblob,
3592 			new_blob_size,
3593 			&validated_code_directory,
3594 			&validated_entitlements_blob,
3595 			&validated_der_entitlements_blob);
3596 
3597 		if (ret) {
3598 			printf("unable to validate reconstituted cs_blob: %d\n", ret);
3599 			err = EINVAL;
3600 			goto fail;
3601 		}
3602 	}
3603 
3604 	if (ret_mem_kaddr) {
3605 		*ret_mem_kaddr = new_blob_addr;
3606 	}
3607 	if (ret_mem_size) {
3608 		*ret_mem_size = new_blob_allocation_size;
3609 	}
3610 
3611 	return 0;
3612 
3613 fail:
3614 	ubc_cs_blob_deallocate(new_blob_addr, new_blob_allocation_size);
3615 	return err;
3616 }
3617 
3618 /*
3619  * We use this function to clear out unnecessary bits from the code signature
3620  * blob which are no longer needed. We free these bits and give them back to
3621  * the kernel. This is needed since reconstitution includes extra data which is
3622  * needed only for verification but has no point in keeping afterwards.
3623  *
3624  * This results in significant memory reduction, especially for 3rd party apps
3625  * since we also get rid of the CMS blob.
3626  */
3627 static errno_t
ubc_cs_reconstitute_code_signature_2nd_stage(struct cs_blob * blob)3628 ubc_cs_reconstitute_code_signature_2nd_stage(
3629 	struct cs_blob *blob
3630 	)
3631 {
3632 	kern_return_t ret = KERN_FAILURE;
3633 	const CS_GenericBlob *launch_constraint_self = NULL;
3634 	const CS_GenericBlob *launch_constraint_parent = NULL;
3635 	const CS_GenericBlob *launch_constraint_responsible = NULL;
3636 	const CS_GenericBlob *library_constraint = NULL;
3637 	CS_SuperBlob *superblob = NULL;
3638 	uint32_t num_blobs = 0;
3639 	vm_size_t last_needed_blob_offset = 0;
3640 	vm_offset_t code_directory_offset = 0;
3641 
3642 	/*
3643 	 * Ordering of blobs we need to keep:
3644 	 * 1. Code directory
3645 	 * 2. DER encoded entitlements (if present)
3646 	 * 3. Launch constraints self (if present)
3647 	 * 4. Launch constraints parent (if present)
3648 	 * 5. Launch constraints responsible (if present)
3649 	 * 6. Library constraints (if present)
3650 	 *
3651 	 * We need to clear out the remaining page after these blobs end, and fix up
3652 	 * the superblob for the changes. Things gets a little more complicated for
3653 	 * blobs which may not have been kmem_allocated. For those, we simply just
3654 	 * allocate the new required space and copy into it.
3655 	 */
3656 
3657 	if (blob == NULL) {
3658 		printf("NULL blob passed in for 2nd stage reconstitution\n");
3659 		return EINVAL;
3660 	}
3661 	assert(blob->csb_reconstituted == true);
3662 
3663 	/* Ensure we're not page-wise allocated when in this function */
3664 	assert(ubc_cs_blob_pagewise_allocate(blob->csb_mem_size) == false);
3665 
3666 	if (!blob->csb_cd) {
3667 		/* This case can never happen, and it is a sign of bad things */
3668 		panic("validated cs_blob has no code directory");
3669 	}
3670 	superblob = (CS_SuperBlob*)blob->csb_mem_kaddr;
3671 
3672 	num_blobs = 1;
3673 	last_needed_blob_offset = ntohl(superblob->index[0].offset) + ntohl(blob->csb_cd->length);
3674 
3675 	/* Check for DER entitlements */
3676 	if (blob->csb_der_entitlements_blob) {
3677 		num_blobs += 1;
3678 		last_needed_blob_offset += ntohl(blob->csb_der_entitlements_blob->length);
3679 	}
3680 
3681 	/* Check for launch constraints self */
3682 	launch_constraint_self = csblob_find_blob_bytes(
3683 		(const uint8_t *)blob->csb_mem_kaddr,
3684 		blob->csb_mem_size,
3685 		CSSLOT_LAUNCH_CONSTRAINT_SELF,
3686 		CSMAGIC_EMBEDDED_LAUNCH_CONSTRAINT);
3687 	if (launch_constraint_self) {
3688 		num_blobs += 1;
3689 		last_needed_blob_offset += ntohl(launch_constraint_self->length);
3690 	}
3691 
3692 	/* Check for launch constraints parent */
3693 	launch_constraint_parent = csblob_find_blob_bytes(
3694 		(const uint8_t *)blob->csb_mem_kaddr,
3695 		blob->csb_mem_size,
3696 		CSSLOT_LAUNCH_CONSTRAINT_PARENT,
3697 		CSMAGIC_EMBEDDED_LAUNCH_CONSTRAINT);
3698 	if (launch_constraint_parent) {
3699 		num_blobs += 1;
3700 		last_needed_blob_offset += ntohl(launch_constraint_parent->length);
3701 	}
3702 
3703 	/* Check for launch constraints responsible */
3704 	launch_constraint_responsible = csblob_find_blob_bytes(
3705 		(const uint8_t *)blob->csb_mem_kaddr,
3706 		blob->csb_mem_size,
3707 		CSSLOT_LAUNCH_CONSTRAINT_RESPONSIBLE,
3708 		CSMAGIC_EMBEDDED_LAUNCH_CONSTRAINT);
3709 	if (launch_constraint_responsible) {
3710 		num_blobs += 1;
3711 		last_needed_blob_offset += ntohl(launch_constraint_responsible->length);
3712 	}
3713 
3714 	/* Check for library constraint */
3715 	library_constraint = csblob_find_blob_bytes(
3716 		(const uint8_t *)blob->csb_mem_kaddr,
3717 		blob->csb_mem_size,
3718 		CSSLOT_LIBRARY_CONSTRAINT,
3719 		CSMAGIC_EMBEDDED_LAUNCH_CONSTRAINT);
3720 	if (library_constraint) {
3721 		num_blobs += 1;
3722 		last_needed_blob_offset += ntohl(library_constraint->length);
3723 	}
3724 
3725 	superblob->count = htonl(num_blobs);
3726 	superblob->length = htonl((uint32_t)last_needed_blob_offset);
3727 
3728 	/*
3729 	 * There is a chance that the code directory is marked within the superblob as an
3730 	 * alternate code directory. This happens when the first code directory isn't the
3731 	 * best one chosen by the kernel, so to be able to access both the first and the best,
3732 	 * we save the best one as an alternate one. Since we're getting rid of the first one
3733 	 * here, we mark the best one as the first one.
3734 	 */
3735 	superblob->index[0].type = htonl(CSSLOT_CODEDIRECTORY);
3736 
3737 	vm_address_t new_superblob = 0;
3738 	vm_size_t new_superblob_size = last_needed_blob_offset;
3739 
3740 	ret = ubc_cs_blob_allocate(&new_superblob, &new_superblob_size);
3741 	if (ret != KERN_SUCCESS) {
3742 		printf("unable to allocate memory for 2nd stage reconstitution: %d\n", ret);
3743 		return ENOMEM;
3744 	}
3745 	assert(new_superblob_size == last_needed_blob_offset);
3746 
3747 	/* Calculate the code directory offset */
3748 	code_directory_offset = (vm_offset_t)blob->csb_cd - (vm_offset_t)blob->csb_mem_kaddr;
3749 
3750 	/* Copy in the updated superblob into the new memory */
3751 	memcpy((void*)new_superblob, superblob, new_superblob_size);
3752 
3753 	/* Free the old code signature and old memory */
3754 	ubc_cs_blob_deallocate((vm_offset_t)blob->csb_mem_kaddr, blob->csb_mem_size);
3755 
3756 	/* Reconstruct critical fields in the blob object */
3757 	ubc_cs_blob_reconstruct(
3758 		blob,
3759 		new_superblob,
3760 		new_superblob_size,
3761 		code_directory_offset);
3762 
3763 	/* XML entitlements should've been removed */
3764 	assert(blob->csb_entitlements_blob == NULL);
3765 
3766 	const CS_CodeDirectory *validated_code_directory = NULL;
3767 	const CS_GenericBlob *validated_entitlements_blob = NULL;
3768 	const CS_GenericBlob *validated_der_entitlements_blob = NULL;
3769 
3770 	ret = cs_validate_csblob(
3771 		(const uint8_t*)blob->csb_mem_kaddr,
3772 		blob->csb_mem_size,
3773 		&validated_code_directory,
3774 		&validated_entitlements_blob,
3775 		&validated_der_entitlements_blob);
3776 	if (ret) {
3777 		printf("unable to validate code signature after 2nd stage reconstitution: %d\n", ret);
3778 		return EINVAL;
3779 	}
3780 
3781 	return 0;
3782 }
3783 
3784 static int
ubc_cs_convert_to_multilevel_hash(struct cs_blob * blob)3785 ubc_cs_convert_to_multilevel_hash(struct cs_blob *blob)
3786 {
3787 	const CS_CodeDirectory  *old_cd, *cd;
3788 	CS_CodeDirectory        *new_cd;
3789 	const CS_GenericBlob *entitlements;
3790 	const CS_GenericBlob *der_entitlements;
3791 	vm_offset_t     new_blob_addr;
3792 	vm_size_t       new_blob_size;
3793 	vm_size_t       new_cdsize;
3794 	int                             error;
3795 
3796 	uint32_t                hashes_per_new_hash_shift = (uint32_t)(PAGE_SHIFT - blob->csb_hash_pageshift);
3797 
3798 	if (cs_debug > 1) {
3799 		printf("CODE SIGNING: Attempting to convert Code Directory for %lu -> %lu page shift\n",
3800 		    (unsigned long)blob->csb_hash_pageshift, (unsigned long)PAGE_SHIFT);
3801 	}
3802 
3803 	old_cd = blob->csb_cd;
3804 
3805 	/* Up to the hashes, we can copy all data */
3806 	new_cdsize  = ntohl(old_cd->hashOffset);
3807 	new_cdsize += (ntohl(old_cd->nCodeSlots) >> hashes_per_new_hash_shift) * old_cd->hashSize;
3808 
3809 	error = ubc_cs_reconstitute_code_signature(blob, &new_blob_addr, &new_blob_size, new_cdsize, &new_cd);
3810 	if (error != 0) {
3811 		printf("CODE SIGNING: Failed to reconsitute code signature: %d\n", error);
3812 		return error;
3813 	}
3814 	entitlements = csblob_find_blob_bytes((uint8_t*)new_blob_addr, new_blob_size, CSSLOT_ENTITLEMENTS, CSMAGIC_EMBEDDED_ENTITLEMENTS);
3815 	der_entitlements = csblob_find_blob_bytes((uint8_t*)new_blob_addr, new_blob_size, CSSLOT_DER_ENTITLEMENTS, CSMAGIC_EMBEDDED_DER_ENTITLEMENTS);
3816 
3817 	memcpy(new_cd, old_cd, ntohl(old_cd->hashOffset));
3818 
3819 	/* Update fields in the Code Directory structure */
3820 	new_cd->length = htonl((uint32_t)new_cdsize);
3821 
3822 	uint32_t nCodeSlots = ntohl(new_cd->nCodeSlots);
3823 	nCodeSlots >>= hashes_per_new_hash_shift;
3824 	new_cd->nCodeSlots = htonl(nCodeSlots);
3825 
3826 	new_cd->pageSize = (uint8_t)PAGE_SHIFT; /* Not byte-swapped */
3827 
3828 	if ((ntohl(new_cd->version) >= CS_SUPPORTSSCATTER) && (ntohl(new_cd->scatterOffset))) {
3829 		SC_Scatter *scatter = (SC_Scatter*)
3830 		    ((char *)new_cd + ntohl(new_cd->scatterOffset));
3831 		/* iterate all scatter structs to scale their counts */
3832 		do {
3833 			uint32_t scount = ntohl(scatter->count);
3834 			uint32_t sbase  = ntohl(scatter->base);
3835 
3836 			/* last scatter? */
3837 			if (scount == 0) {
3838 				break;
3839 			}
3840 
3841 			scount >>= hashes_per_new_hash_shift;
3842 			scatter->count = htonl(scount);
3843 
3844 			sbase >>= hashes_per_new_hash_shift;
3845 			scatter->base = htonl(sbase);
3846 
3847 			scatter++;
3848 		} while (1);
3849 	}
3850 
3851 	/* For each group of hashes, hash them together */
3852 	const unsigned char *src_base = (const unsigned char *)old_cd + ntohl(old_cd->hashOffset);
3853 	unsigned char *dst_base = (unsigned char *)new_cd + ntohl(new_cd->hashOffset);
3854 
3855 	uint32_t hash_index;
3856 	for (hash_index = 0; hash_index < nCodeSlots; hash_index++) {
3857 		union cs_hash_union     mdctx;
3858 
3859 		uint32_t source_hash_len = old_cd->hashSize << hashes_per_new_hash_shift;
3860 		const unsigned char *src = src_base + hash_index * source_hash_len;
3861 		unsigned char *dst = dst_base + hash_index * new_cd->hashSize;
3862 
3863 		blob->csb_hashtype->cs_init(&mdctx);
3864 		blob->csb_hashtype->cs_update(&mdctx, src, source_hash_len);
3865 		blob->csb_hashtype->cs_final(dst, &mdctx);
3866 	}
3867 
3868 	error = cs_validate_csblob((const uint8_t *)new_blob_addr, new_blob_size, &cd, &entitlements, &der_entitlements);
3869 	if (error != 0) {
3870 		printf("CODE SIGNING: Failed to validate new Code Signing Blob: %d\n",
3871 		    error);
3872 
3873 		ubc_cs_blob_deallocate(new_blob_addr, new_blob_size);
3874 		return error;
3875 	}
3876 
3877 	/* New Code Directory is ready for use, swap it out in the blob structure */
3878 	ubc_cs_blob_deallocate((vm_offset_t)blob->csb_mem_kaddr, blob->csb_mem_size);
3879 
3880 	blob->csb_mem_size = new_blob_size;
3881 	blob->csb_mem_kaddr = (void *)new_blob_addr;
3882 	blob->csb_cd = cd;
3883 	blob->csb_entitlements_blob = NULL;
3884 
3885 	blob->csb_der_entitlements_blob = der_entitlements; /* may be NULL, not yet validated */
3886 	blob->csb_reconstituted = true;
3887 
3888 	/* The blob has some cached attributes of the Code Directory, so update those */
3889 
3890 	blob->csb_hash_firstlevel_pageshift = blob->csb_hash_pageshift; /* Save the original page size */
3891 
3892 	blob->csb_hash_pageshift = PAGE_SHIFT;
3893 	blob->csb_end_offset = ntohl(cd->codeLimit);
3894 	if ((ntohl(cd->version) >= CS_SUPPORTSSCATTER) && (ntohl(cd->scatterOffset))) {
3895 		const SC_Scatter *scatter = (const SC_Scatter*)
3896 		    ((const char*)cd + ntohl(cd->scatterOffset));
3897 		blob->csb_start_offset = ((off_t)ntohl(scatter->base)) * PAGE_SIZE;
3898 	} else {
3899 		blob->csb_start_offset = 0;
3900 	}
3901 
3902 	return 0;
3903 }
3904 
3905 static void
cs_blob_cleanup(struct cs_blob * blob)3906 cs_blob_cleanup(struct cs_blob *blob)
3907 {
3908 	if (blob->csb_entitlements != NULL) {
3909 		amfi->OSEntitlements_invalidate(blob->csb_entitlements);
3910 		osobject_release(blob->csb_entitlements);
3911 		blob->csb_entitlements = NULL;
3912 	}
3913 
3914 #if CODE_SIGNING_MONITOR
3915 	if (blob->csb_csm_obj != NULL) {
3916 		/* Unconditionally remove any profiles we may have associated */
3917 		csm_disassociate_provisioning_profile(blob->csb_csm_obj);
3918 
3919 		kern_return_t kr = csm_unregister_code_signature(blob->csb_csm_obj);
3920 		if (kr == KERN_SUCCESS) {
3921 			/*
3922 			 * If the code signature was monitor managed, the monitor will have freed it
3923 			 * itself in the unregistration call. It means we do not need to free the data
3924 			 * over here.
3925 			 */
3926 			if (blob->csb_csm_managed) {
3927 				blob->csb_mem_kaddr = NULL;
3928 				blob->csb_mem_size = 0;
3929 			}
3930 		} else if (kr == KERN_ABORTED) {
3931 			/*
3932 			 * The code-signing-monitor refused to unregister the code signature. It means
3933 			 * whatever memory was backing the code signature may not have been released, and
3934 			 * attempting to free it down below will not be successful. As a result, all we
3935 			 * can do is prevent the kernel from touching the data.
3936 			 */
3937 			blob->csb_mem_kaddr = NULL;
3938 			blob->csb_mem_size = 0;
3939 		}
3940 	}
3941 
3942 	/* Unconditionally remove references to the monitor */
3943 	blob->csb_csm_obj = NULL;
3944 	blob->csb_csm_managed = false;
3945 #endif
3946 
3947 	if (blob->csb_mem_kaddr) {
3948 		ubc_cs_blob_deallocate((vm_offset_t)blob->csb_mem_kaddr, blob->csb_mem_size);
3949 	}
3950 	blob->csb_mem_kaddr = NULL;
3951 	blob->csb_mem_size = 0;
3952 }
3953 
3954 static void
cs_blob_ro_free(struct cs_blob * blob)3955 cs_blob_ro_free(struct cs_blob *blob)
3956 {
3957 	struct cs_blob tmp;
3958 
3959 	if (blob != NULL) {
3960 		/*
3961 		 * cs_blob_cleanup clears fields, so we need to pass it a
3962 		 * mutable copy.
3963 		 */
3964 		tmp = *blob;
3965 		cs_blob_cleanup(&tmp);
3966 
3967 		zfree_ro(ZONE_ID_CS_BLOB, blob);
3968 	}
3969 }
3970 
3971 /*
3972  * Free a cs_blob previously created by cs_blob_create_validated.
3973  */
3974 void
cs_blob_free(struct cs_blob * blob)3975 cs_blob_free(
3976 	struct cs_blob *blob)
3977 {
3978 	cs_blob_ro_free(blob);
3979 }
3980 
3981 static int
cs_blob_init_validated(vm_address_t * const addr,vm_size_t size,struct cs_blob * blob,CS_CodeDirectory const ** const ret_cd)3982 cs_blob_init_validated(
3983 	vm_address_t * const addr,
3984 	vm_size_t size,
3985 	struct cs_blob *blob,
3986 	CS_CodeDirectory const ** const ret_cd)
3987 {
3988 	int error = EINVAL;
3989 	const CS_CodeDirectory *cd = NULL;
3990 	const CS_GenericBlob *entitlements = NULL;
3991 	const CS_GenericBlob *der_entitlements = NULL;
3992 	union cs_hash_union mdctx;
3993 	size_t length;
3994 
3995 	bzero(blob, sizeof(*blob));
3996 
3997 	/* fill in the new blob */
3998 	blob->csb_mem_size = size;
3999 	blob->csb_mem_offset = 0;
4000 	blob->csb_mem_kaddr = (void *)*addr;
4001 	blob->csb_flags = 0;
4002 	blob->csb_signer_type = CS_SIGNER_TYPE_UNKNOWN;
4003 	blob->csb_platform_binary = 0;
4004 	blob->csb_platform_path = 0;
4005 	blob->csb_teamid = NULL;
4006 #if CONFIG_SUPPLEMENTAL_SIGNATURES
4007 	blob->csb_supplement_teamid = NULL;
4008 #endif
4009 	blob->csb_entitlements_blob = NULL;
4010 	blob->csb_der_entitlements_blob = NULL;
4011 	blob->csb_entitlements = NULL;
4012 #if CODE_SIGNING_MONITOR
4013 	blob->csb_csm_obj = NULL;
4014 	blob->csb_csm_managed = false;
4015 #endif
4016 	blob->csb_reconstituted = false;
4017 	blob->csb_validation_category = CS_VALIDATION_CATEGORY_INVALID;
4018 
4019 	/* Transfer ownership. Even on error, this function will deallocate */
4020 	*addr = 0;
4021 
4022 	/*
4023 	 * Validate the blob's contents
4024 	 */
4025 	length = (size_t) size;
4026 	error = cs_validate_csblob((const uint8_t *)blob->csb_mem_kaddr,
4027 	    length, &cd, &entitlements, &der_entitlements);
4028 	if (error) {
4029 		if (cs_debug) {
4030 			printf("CODESIGNING: csblob invalid: %d\n", error);
4031 		}
4032 		/*
4033 		 * The vnode checker can't make the rest of this function
4034 		 * succeed if csblob validation failed, so bail */
4035 		goto out;
4036 	} else {
4037 		const unsigned char *md_base;
4038 		uint8_t hash[CS_HASH_MAX_SIZE];
4039 		int md_size;
4040 		vm_offset_t hash_pagemask;
4041 
4042 		blob->csb_cd = cd;
4043 		blob->csb_entitlements_blob = entitlements; /* may be NULL, not yet validated */
4044 		blob->csb_der_entitlements_blob = der_entitlements; /* may be NULL, not yet validated */
4045 		blob->csb_hashtype = cs_find_md(cd->hashType);
4046 		if (blob->csb_hashtype == NULL || blob->csb_hashtype->cs_digest_size > sizeof(hash)) {
4047 			panic("validated CodeDirectory but unsupported type");
4048 		}
4049 
4050 		blob->csb_hash_pageshift = cd->pageSize;
4051 		hash_pagemask = (1U << cd->pageSize) - 1;
4052 		blob->csb_hash_firstlevel_pageshift = 0;
4053 		blob->csb_flags = (ntohl(cd->flags) & CS_ALLOWED_MACHO) | CS_VALID;
4054 		blob->csb_end_offset = (((vm_offset_t)ntohl(cd->codeLimit) + hash_pagemask) & ~hash_pagemask);
4055 		if ((ntohl(cd->version) >= CS_SUPPORTSSCATTER) && (ntohl(cd->scatterOffset))) {
4056 			const SC_Scatter *scatter = (const SC_Scatter*)
4057 			    ((const char*)cd + ntohl(cd->scatterOffset));
4058 			blob->csb_start_offset = ((off_t)ntohl(scatter->base)) * (1U << blob->csb_hash_pageshift);
4059 		} else {
4060 			blob->csb_start_offset = 0;
4061 		}
4062 		/* compute the blob's cdhash */
4063 		md_base = (const unsigned char *) cd;
4064 		md_size = ntohl(cd->length);
4065 
4066 		blob->csb_hashtype->cs_init(&mdctx);
4067 		blob->csb_hashtype->cs_update(&mdctx, md_base, md_size);
4068 		blob->csb_hashtype->cs_final(hash, &mdctx);
4069 
4070 		memcpy(blob->csb_cdhash, hash, CS_CDHASH_LEN);
4071 
4072 #if CONFIG_SUPPLEMENTAL_SIGNATURES
4073 		blob->csb_linkage_hashtype = NULL;
4074 		if (ntohl(cd->version) >= CS_SUPPORTSLINKAGE && cd->linkageHashType != 0 &&
4075 		    ntohl(cd->linkageSize) >= CS_CDHASH_LEN) {
4076 			blob->csb_linkage_hashtype = cs_find_md(cd->linkageHashType);
4077 
4078 			if (blob->csb_linkage_hashtype != NULL) {
4079 				memcpy(blob->csb_linkage, (uint8_t const*)cd + ntohl(cd->linkageOffset),
4080 				    CS_CDHASH_LEN);
4081 			}
4082 		}
4083 #endif
4084 	}
4085 
4086 	error = 0;
4087 
4088 out:
4089 	if (error != 0) {
4090 		cs_blob_cleanup(blob);
4091 		blob = NULL;
4092 		cd = NULL;
4093 	}
4094 
4095 	if (ret_cd != NULL) {
4096 		*ret_cd = cd;
4097 	}
4098 
4099 	return error;
4100 }
4101 
4102 /*
4103  * Validate the code signature blob, create a struct cs_blob wrapper
4104  * and return it together with a pointer to the chosen code directory
4105  * and entitlements blob.
4106  *
4107  * Note that this takes ownership of the memory as addr, mainly because
4108  * this function can actually replace the passed in blob with another
4109  * one, e.g. when performing multilevel hashing optimization.
4110  */
4111 int
cs_blob_create_validated(vm_address_t * const addr,vm_size_t size,struct cs_blob ** const ret_blob,CS_CodeDirectory const ** const ret_cd)4112 cs_blob_create_validated(
4113 	vm_address_t * const            addr,
4114 	vm_size_t                       size,
4115 	struct cs_blob ** const         ret_blob,
4116 	CS_CodeDirectory const ** const     ret_cd)
4117 {
4118 	struct cs_blob blob = {};
4119 	struct cs_blob *ro_blob;
4120 	int error;
4121 
4122 	if (ret_blob) {
4123 		*ret_blob = NULL;
4124 	}
4125 
4126 	if ((error = cs_blob_init_validated(addr, size, &blob, ret_cd)) != 0) {
4127 		return error;
4128 	}
4129 
4130 	if (ret_blob != NULL) {
4131 		ro_blob = zalloc_ro(ZONE_ID_CS_BLOB, Z_WAITOK | Z_NOFAIL);
4132 		zalloc_ro_update_elem(ZONE_ID_CS_BLOB, ro_blob, &blob);
4133 		*ret_blob = ro_blob;
4134 	}
4135 
4136 	return error;
4137 }
4138 
4139 #if CONFIG_SUPPLEMENTAL_SIGNATURES
4140 static void
cs_blob_supplement_free(struct cs_blob * const blob)4141 cs_blob_supplement_free(struct cs_blob * const blob)
4142 {
4143 	void *teamid;
4144 
4145 	if (blob != NULL) {
4146 		if (blob->csb_supplement_teamid != NULL) {
4147 			teamid = blob->csb_supplement_teamid;
4148 			vm_size_t teamid_size = strlen(blob->csb_supplement_teamid) + 1;
4149 			kfree_data(teamid, teamid_size);
4150 		}
4151 		cs_blob_ro_free(blob);
4152 	}
4153 }
4154 #endif
4155 
4156 static void
ubc_cs_blob_adjust_statistics(struct cs_blob const * blob)4157 ubc_cs_blob_adjust_statistics(struct cs_blob const *blob)
4158 {
4159 	/* Note that the atomic ops are not enough to guarantee
4160 	 * correctness: If a blob with an intermediate size is inserted
4161 	 * concurrently, we can lose a peak value assignment. But these
4162 	 * statistics are only advisory anyway, so we're not going to
4163 	 * employ full locking here. (Consequently, we are also okay with
4164 	 * relaxed ordering of those accesses.)
4165 	 */
4166 
4167 	unsigned int new_cs_blob_count = os_atomic_add(&cs_blob_count, 1, relaxed);
4168 	if (new_cs_blob_count > os_atomic_load(&cs_blob_count_peak, relaxed)) {
4169 		os_atomic_store(&cs_blob_count_peak, new_cs_blob_count, relaxed);
4170 	}
4171 
4172 	size_t new_cs_blob_size = os_atomic_add(&cs_blob_size, blob->csb_mem_size, relaxed);
4173 
4174 	if (new_cs_blob_size > os_atomic_load(&cs_blob_size_peak, relaxed)) {
4175 		os_atomic_store(&cs_blob_size_peak, new_cs_blob_size, relaxed);
4176 	}
4177 	if (blob->csb_mem_size > os_atomic_load(&cs_blob_size_max, relaxed)) {
4178 		os_atomic_store(&cs_blob_size_max, blob->csb_mem_size, relaxed);
4179 	}
4180 }
4181 
4182 static void
cs_blob_set_cpu_type(struct cs_blob * blob,cpu_type_t cputype)4183 cs_blob_set_cpu_type(struct cs_blob *blob, cpu_type_t cputype)
4184 {
4185 	zalloc_ro_update_field(ZONE_ID_CS_BLOB, blob, csb_cpu_type, &cputype);
4186 }
4187 
4188 __abortlike
4189 static void
panic_cs_blob_backref_mismatch(struct cs_blob * blob,struct vnode * vp)4190 panic_cs_blob_backref_mismatch(struct cs_blob *blob, struct vnode *vp)
4191 {
4192 	panic("cs_blob vnode backref mismatch: blob=%p, vp=%p, "
4193 	    "blob->csb_vnode=%p", blob, vp, blob->csb_vnode);
4194 }
4195 
4196 void
cs_blob_require(struct cs_blob * blob,vnode_t vp)4197 cs_blob_require(struct cs_blob *blob, vnode_t vp)
4198 {
4199 	zone_require_ro(ZONE_ID_CS_BLOB, sizeof(struct cs_blob), blob);
4200 
4201 	if (vp != NULL && __improbable(blob->csb_vnode != vp)) {
4202 		panic_cs_blob_backref_mismatch(blob, vp);
4203 	}
4204 }
4205 
4206 #if CODE_SIGNING_MONITOR
4207 
4208 /**
4209  * Independently verify the authenticity of the code signature through the monitor
4210  * environment. This is required as otherwise the monitor won't allow associations
4211  * of the code signature with address spaces.
4212  *
4213  * Once we've verified the code signature, we no longer need to keep around any
4214  * provisioning profiles we may have registered with it. AMFI associates profiles
4215  * with the monitor during its validation (which happens before the monitor's).
4216  */
4217 static errno_t
verify_code_signature_monitor(struct cs_blob * cs_blob)4218 verify_code_signature_monitor(
4219 	struct cs_blob *cs_blob)
4220 {
4221 	kern_return_t ret = KERN_DENIED;
4222 
4223 	ret = csm_verify_code_signature(cs_blob->csb_csm_obj, &cs_blob->csb_csm_trust_level);
4224 	if ((ret != KERN_SUCCESS) && (ret != KERN_NOT_SUPPORTED)) {
4225 		printf("unable to verify code signature with monitor: %d\n", ret);
4226 		return EPERM;
4227 	}
4228 
4229 	ret = csm_disassociate_provisioning_profile(cs_blob->csb_csm_obj);
4230 	if ((ret != KERN_SUCCESS) && (ret != KERN_NOT_FOUND) && (ret != KERN_NOT_SUPPORTED)) {
4231 		printf("unable to disassociate profile from code signature: %d\n", ret);
4232 		return EPERM;
4233 	}
4234 
4235 	/* Associate the OSEntitlements kernel object with the monitor */
4236 	ret = csm_associate_os_entitlements(cs_blob->csb_csm_obj, cs_blob->csb_entitlements);
4237 	if ((ret != KERN_SUCCESS) && (ret != KERN_NOT_SUPPORTED)) {
4238 		printf("unable to associate OSEntitlements with monitor: %d\n", ret);
4239 		return EPERM;
4240 	}
4241 
4242 	return 0;
4243 }
4244 
4245 /**
4246  * Register the code signature with the code signing monitor environment. This
4247  * will effectively make the blob data immutable, either because the blob memory
4248  * will be allocated and managed directory by the monitor, or because the monitor
4249  * will lockdown the memory associated with the blob.
4250  */
4251 static errno_t
register_code_signature_monitor(struct vnode * vnode,struct cs_blob * cs_blob,vm_offset_t code_directory_offset)4252 register_code_signature_monitor(
4253 	struct vnode *vnode,
4254 	struct cs_blob *cs_blob,
4255 	vm_offset_t code_directory_offset)
4256 {
4257 	kern_return_t ret = KERN_DENIED;
4258 	vm_address_t monitor_signature_addr = 0;
4259 	void *monitor_sig_object = NULL;
4260 	const char *vnode_path_ptr = NULL;
4261 
4262 	/*
4263 	 * Attempt to resolve the path for this vnode and pass it in to the code
4264 	 * signing monitor during registration.
4265 	 */
4266 	int vnode_path_len = MAXPATHLEN;
4267 	char *vnode_path = kalloc_data(vnode_path_len, Z_WAITOK);
4268 
4269 	/*
4270 	 * Taking a reference on the vnode recursively can sometimes lead to a
4271 	 * deadlock on the system. Since we already have a vnode pointer, it means
4272 	 * the caller performed a vnode lookup, which implicitly takes a reference
4273 	 * on the vnode. However, there is more than just having a reference on a
4274 	 * vnode which is important. vnode's also have an iocount, and we must only
4275 	 * access a vnode which has an iocount of greater than 0. Thankfully, all
4276 	 * the conditions which lead to calling this function ensure that this
4277 	 * vnode is safe to access here.
4278 	 *
4279 	 * For more details: rdar://105819068.
4280 	 */
4281 	errno_t error = vn_getpath(vnode, vnode_path, &vnode_path_len);
4282 	if (error == 0) {
4283 		vnode_path_ptr = vnode_path;
4284 	}
4285 
4286 	ret = csm_register_code_signature(
4287 		(vm_address_t)cs_blob->csb_mem_kaddr,
4288 		cs_blob->csb_mem_size,
4289 		code_directory_offset,
4290 		vnode_path_ptr,
4291 		&monitor_sig_object,
4292 		&monitor_signature_addr);
4293 
4294 	kfree_data(vnode_path, MAXPATHLEN);
4295 	vnode_path_ptr = NULL;
4296 
4297 	if (ret == KERN_SUCCESS) {
4298 		/* Reconstruct the cs_blob if the monitor used its own allocation */
4299 		if (monitor_signature_addr != (vm_address_t)cs_blob->csb_mem_kaddr) {
4300 			vm_address_t monitor_signature_size = cs_blob->csb_mem_size;
4301 
4302 			/* Free the old memory for the blob */
4303 			ubc_cs_blob_deallocate(
4304 				(vm_address_t)cs_blob->csb_mem_kaddr,
4305 				cs_blob->csb_mem_size);
4306 
4307 			/* Reconstruct critical fields in the blob object */
4308 			ubc_cs_blob_reconstruct(
4309 				cs_blob,
4310 				monitor_signature_addr,
4311 				monitor_signature_size,
4312 				code_directory_offset);
4313 
4314 			/* Mark the signature as monitor managed */
4315 			cs_blob->csb_csm_managed = true;
4316 		}
4317 	} else if (ret != KERN_NOT_SUPPORTED) {
4318 		printf("unable to register code signature with monitor: %d\n", ret);
4319 		return EPERM;
4320 	}
4321 
4322 	/* Save the monitor handle for the signature object -- may be NULL */
4323 	cs_blob->csb_csm_obj = monitor_sig_object;
4324 
4325 	return 0;
4326 }
4327 
4328 #endif /* CODE_SIGNING_MONITOR */
4329 
4330 static errno_t
validate_main_binary_check(struct cs_blob * csblob,cs_blob_add_flags_t csblob_add_flags)4331 validate_main_binary_check(
4332 	struct cs_blob *csblob,
4333 	cs_blob_add_flags_t csblob_add_flags)
4334 {
4335 #if XNU_TARGET_OS_OSX
4336 	(void)csblob;
4337 	(void)csblob_add_flags;
4338 	return 0;
4339 #else
4340 	const CS_CodeDirectory *first_cd = NULL;
4341 	const CS_CodeDirectory *alt_cd = NULL;
4342 	uint64_t exec_seg_flags = 0;
4343 	uint32_t slot = CSSLOT_CODEDIRECTORY;
4344 
4345 	/* Nothing to enforce if we're allowing main binaries */
4346 	if ((csblob_add_flags & CS_BLOB_ADD_ALLOW_MAIN_BINARY) != 0) {
4347 		return 0;
4348 	}
4349 
4350 	first_cd = (const CS_CodeDirectory*)csblob_find_blob(csblob, slot, CSMAGIC_CODEDIRECTORY);
4351 	if ((first_cd != NULL) && (ntohl(first_cd->version) >= CS_SUPPORTSEXECSEG)) {
4352 		exec_seg_flags |= ntohll(first_cd->execSegFlags);
4353 	}
4354 
4355 	for (uint32_t i = 0; i < CSSLOT_ALTERNATE_CODEDIRECTORY_MAX; i++) {
4356 		slot = CSSLOT_ALTERNATE_CODEDIRECTORIES + i;
4357 		alt_cd = (const CS_CodeDirectory*)csblob_find_blob(csblob, slot, CSMAGIC_CODEDIRECTORY);
4358 		if ((alt_cd == NULL) || (ntohl(alt_cd->version) < CS_SUPPORTSEXECSEG)) {
4359 			continue;
4360 		}
4361 		exec_seg_flags |= ntohll(alt_cd->execSegFlags);
4362 	}
4363 
4364 	if ((exec_seg_flags & CS_EXECSEG_MAIN_BINARY) != 0) {
4365 		return EBADEXEC;
4366 	}
4367 	return 0;
4368 #endif /* XNU_TARGET_OS_OSX */
4369 }
4370 
4371 /**
4372  * Accelerate entitlements for a code signature object. When we have a code
4373  * signing monitor, this acceleration is done within the monitor which then
4374  * passes back a CoreEntitlements query context the kernel can use. When we
4375  * don't have a code signing monitor, we accelerate the queries within the
4376  * kernel memory itself.
4377  *
4378  * This function must be called when the storage for the code signature can
4379  * no longer change.
4380  */
4381 static errno_t
accelerate_entitlement_queries(struct cs_blob * cs_blob)4382 accelerate_entitlement_queries(
4383 	struct cs_blob *cs_blob)
4384 {
4385 	kern_return_t ret = KERN_NOT_SUPPORTED;
4386 
4387 #if CODE_SIGNING_MONITOR
4388 	CEQueryContext_t ce_ctx = NULL;
4389 	const char *signing_id = NULL;
4390 
4391 	ret = csm_accelerate_entitlements(cs_blob->csb_csm_obj, &ce_ctx);
4392 	if ((ret != KERN_SUCCESS) && (ret != KERN_NOT_SUPPORTED)) {
4393 		printf("unable to accelerate entitlements through the monitor: %d\n", ret);
4394 		return EPERM;
4395 	}
4396 
4397 	if (ret == KERN_SUCCESS) {
4398 		/* Call cannot not fail at this stage */
4399 		ret = csm_acquire_signing_identifier(cs_blob->csb_csm_obj, &signing_id);
4400 		assert(ret == KERN_SUCCESS);
4401 
4402 		/* Adjust the OSEntitlements context with AMFI */
4403 		ret = amfi->OSEntitlements.adjustContextWithMonitor(
4404 			cs_blob->csb_entitlements,
4405 			ce_ctx,
4406 			cs_blob->csb_csm_obj,
4407 			signing_id,
4408 			cs_blob->csb_flags);
4409 		if (ret != KERN_SUCCESS) {
4410 			printf("unable to adjust OSEntitlements context with monitor: %d\n", ret);
4411 			return EPERM;
4412 		}
4413 
4414 		return 0;
4415 	}
4416 #endif
4417 
4418 	/*
4419 	 * If we reach here, then either we don't have a code signing monitor, or
4420 	 * the code signing monitor isn't enabled for code signing, in which case,
4421 	 * AMFI is going to accelerate the entitlements context and adjust its
4422 	 * context on its own.
4423 	 */
4424 	assert(ret == KERN_NOT_SUPPORTED);
4425 
4426 	ret = amfi->OSEntitlements.adjustContextWithoutMonitor(
4427 		cs_blob->csb_entitlements,
4428 		cs_blob);
4429 
4430 	if (ret != KERN_SUCCESS) {
4431 		printf("unable to adjust OSEntitlements context without monitor: %d\n", ret);
4432 		return EPERM;
4433 	}
4434 
4435 	return 0;
4436 }
4437 
4438 /**
4439  * Ensure and validate that some security critical code signing blobs haven't
4440  * been stripped off from the code signature. This can happen if an attacker
4441  * chose to load a code signature sans these critical blobs, or if there is a
4442  * bug in reconstitution logic which remove these blobs from the code signature.
4443  */
4444 static errno_t
validate_auxiliary_signed_blobs(struct cs_blob * cs_blob)4445 validate_auxiliary_signed_blobs(
4446 	struct cs_blob *cs_blob)
4447 {
4448 	struct cs_blob_identifier {
4449 		uint32_t cs_slot;
4450 		uint32_t cs_magic;
4451 	};
4452 
4453 	const struct cs_blob_identifier identifiers[] = {
4454 		{CSSLOT_LAUNCH_CONSTRAINT_SELF, CSMAGIC_EMBEDDED_LAUNCH_CONSTRAINT},
4455 		{CSSLOT_LAUNCH_CONSTRAINT_PARENT, CSMAGIC_EMBEDDED_LAUNCH_CONSTRAINT},
4456 		{CSSLOT_LAUNCH_CONSTRAINT_RESPONSIBLE, CSMAGIC_EMBEDDED_LAUNCH_CONSTRAINT},
4457 		{CSSLOT_LIBRARY_CONSTRAINT, CSMAGIC_EMBEDDED_LAUNCH_CONSTRAINT}
4458 	};
4459 	const uint32_t num_identifiers = sizeof(identifiers) / sizeof(identifiers[0]);
4460 
4461 	for (uint32_t i = 0; i < num_identifiers; i++) {
4462 		errno_t err = csblob_find_special_slot_blob(
4463 			cs_blob,
4464 			identifiers[i].cs_slot,
4465 			identifiers[i].cs_magic,
4466 			NULL,
4467 			NULL);
4468 
4469 		if (err != 0) {
4470 			printf("unable to validate security-critical blob: %d [%u|%u]\n",
4471 			    err, identifiers[i].cs_slot, identifiers[i].cs_magic);
4472 
4473 			return EPERM;
4474 		}
4475 	}
4476 
4477 	return 0;
4478 }
4479 
4480 /**
4481  * Setup multi-level hashing for the code signature. This isn't supported on most
4482  * shipping devices, but on ones where it is, it can result in significant savings
4483  * of memory from the code signature standpoint.
4484  *
4485  * Multi-level hashing is used to condense the code directory hashes in order to
4486  * improve memory consumption. We take four 4K page hashes, and condense them into
4487  * a single 16K hash, hence reducing the space consumed by the code directory by
4488  * about ~75%.
4489  */
4490 static errno_t
setup_multilevel_hashing(struct cs_blob * cs_blob)4491 setup_multilevel_hashing(
4492 	struct cs_blob *cs_blob)
4493 {
4494 	code_signing_monitor_type_t monitor_type = CS_MONITOR_TYPE_NONE;
4495 	errno_t err = -1;
4496 
4497 	/*
4498 	 * When we have a code signing monitor, we do not support multi-level hashing
4499 	 * since the code signature data is expected to be locked within memory which
4500 	 * cannot be written to by the kernel.
4501 	 *
4502 	 * Even when the code signing monitor isn't explicitly enabled, there are other
4503 	 * reasons for not performing multi-level hashing. For instance, Rosetta creates
4504 	 * issues with multi-level hashing on Apple Silicon Macs.
4505 	 */
4506 	code_signing_configuration(&monitor_type, NULL);
4507 	if (monitor_type != CS_MONITOR_TYPE_NONE) {
4508 		return 0;
4509 	}
4510 
4511 	/* We need to check if multi-level hashing is supported for this blob */
4512 	if (ubc_cs_supports_multilevel_hash(cs_blob) == false) {
4513 		return 0;
4514 	}
4515 
4516 	err = ubc_cs_convert_to_multilevel_hash(cs_blob);
4517 	if (err != 0) {
4518 		printf("unable to setup multi-level hashing: %d\n", err);
4519 		return err;
4520 	}
4521 
4522 	assert(cs_blob->csb_reconstituted == true);
4523 	return 0;
4524 }
4525 
4526 /**
4527  * Once code signature validation is complete, we can remove even more blobs from the
4528  * code signature as they are no longer needed. This goes on to conserve even more
4529  * system memory.
4530  */
4531 static errno_t
reconstitute_code_signature_2nd_stage(struct cs_blob * cs_blob)4532 reconstitute_code_signature_2nd_stage(
4533 	struct cs_blob *cs_blob)
4534 {
4535 	kern_return_t ret = KERN_NOT_SUPPORTED;
4536 	errno_t err = EPERM;
4537 
4538 	/* If we never reconstituted before, we won't be reconstituting again */
4539 	if (cs_blob->csb_reconstituted == false) {
4540 		return 0;
4541 	}
4542 
4543 #if CODE_SIGNING_MONITOR
4544 	/*
4545 	 * When we have a code signing monitor, the code signature is immutable until the
4546 	 * monitor decides to unlock parts of it. Therefore, 2nd stage reconstitution takes
4547 	 * place in the monitor when we have a monitor available.
4548 	 *
4549 	 * If the monitor isn't enforcing code signing (in which case the code signature is
4550 	 * NOT immutable), then we perform 2nd stage reconstitution within the kernel itself.
4551 	 */
4552 	vm_address_t unneeded_addr = 0;
4553 	vm_size_t unneeded_size = 0;
4554 
4555 	ret = csm_reconstitute_code_signature(
4556 		cs_blob->csb_csm_obj,
4557 		&unneeded_addr,
4558 		&unneeded_size);
4559 
4560 	if ((ret == KERN_SUCCESS) && unneeded_addr && unneeded_size) {
4561 		/* Free the unneded part of the blob */
4562 		kmem_free(kernel_map, unneeded_addr, unneeded_size);
4563 
4564 		/* Adjust the size in the blob object */
4565 		cs_blob->csb_mem_size -= unneeded_size;
4566 	}
4567 #endif
4568 
4569 	if (ret == KERN_SUCCESS) {
4570 		goto success;
4571 	} else if (ret != KERN_NOT_SUPPORTED) {
4572 		/*
4573 		 * A monitor environment is available, and it failed in performing 2nd stage
4574 		 * reconstitution. This is a fatal issue for code signing validation.
4575 		 */
4576 		printf("unable to reconstitute code signature through monitor: %d\n", ret);
4577 		return EPERM;
4578 	}
4579 
4580 	/* No monitor available if we reached here */
4581 	err = ubc_cs_reconstitute_code_signature_2nd_stage(cs_blob);
4582 	if (err != 0) {
4583 		return err;
4584 	}
4585 
4586 success:
4587 	/*
4588 	 * Regardless of whether we are performing 2nd stage reconstitution in the monitor
4589 	 * or in the kernel, we remove references to XML entitlements from the blob here.
4590 	 * None of the 2nd stage reconstitution code ever keeps these around, and they have
4591 	 * been explicitly deprecated and disallowed.
4592 	 */
4593 	cs_blob->csb_entitlements_blob = NULL;
4594 
4595 	return 0;
4596 }
4597 
4598 /**
4599  * A code signature blob often contains blob which aren't needed in the kernel. Since
4600  * the code signature is wired into kernel memory for the time it is used, it behooves
4601  * us to remove any blobs we have no need for in order to conserve memory.
4602  *
4603  * Some platforms support copying the entire SuperBlob stored in kernel memory into
4604  * userspace memory through the "csops" system call. There is an expectation that when
4605  * this happens, all the blobs which were a part of the code signature are copied in
4606  * to userspace memory. As a result, these platforms cannot reconstitute the code
4607  * signature since, or rather, these platforms cannot remove blobs from the signature,
4608  * thereby making reconstitution useless.
4609  */
4610 static errno_t
reconstitute_code_signature(struct cs_blob * cs_blob)4611 reconstitute_code_signature(
4612 	struct cs_blob *cs_blob)
4613 {
4614 	CS_CodeDirectory *code_directory = NULL;
4615 	vm_address_t signature_addr = 0;
4616 	vm_size_t signature_size = 0;
4617 	vm_offset_t code_directory_offset = 0;
4618 	bool platform_supports_reconstitution = false;
4619 
4620 #if CONFIG_CODE_SIGNATURE_RECONSTITUTION
4621 	platform_supports_reconstitution = true;
4622 #endif
4623 
4624 	/*
4625 	 * We can skip reconstitution if the code signing monitor isn't available or not
4626 	 * enabled. But if we do have a monitor, then reconsitution becomes required, as
4627 	 * there is an expectation of performing 2nd stage reconstitution through the
4628 	 * monitor itself.
4629 	 */
4630 	if (platform_supports_reconstitution == false) {
4631 #if CODE_SIGNING_MONITOR
4632 		if (csm_enabled() == true) {
4633 			printf("reconstitution required when code signing monitor is enabled\n");
4634 			return EPERM;
4635 		}
4636 #endif
4637 		return 0;
4638 	}
4639 
4640 	errno_t err = ubc_cs_reconstitute_code_signature(
4641 		cs_blob,
4642 		&signature_addr,
4643 		&signature_size,
4644 		0,
4645 		&code_directory);
4646 
4647 	if (err != 0) {
4648 		printf("unable to reconstitute code signature: %d\n", err);
4649 		return err;
4650 	}
4651 
4652 	/* Calculate the code directory offset */
4653 	code_directory_offset = (vm_offset_t)code_directory - signature_addr;
4654 
4655 	/* Reconstitution allocates new memory -- free the old one */
4656 	ubc_cs_blob_deallocate((vm_address_t)cs_blob->csb_mem_kaddr, cs_blob->csb_mem_size);
4657 
4658 	/* Reconstruct critical fields in the blob object */
4659 	ubc_cs_blob_reconstruct(
4660 		cs_blob,
4661 		signature_addr,
4662 		signature_size,
4663 		code_directory_offset);
4664 
4665 	/* Mark the object as reconstituted */
4666 	cs_blob->csb_reconstituted = true;
4667 
4668 	return 0;
4669 }
4670 
4671 int
ubc_cs_blob_add(struct vnode * vp,uint32_t platform,cpu_type_t cputype,cpu_subtype_t cpusubtype,off_t base_offset,vm_address_t * addr,vm_size_t size,struct image_params * imgp,__unused int flags,struct cs_blob ** ret_blob,cs_blob_add_flags_t csblob_add_flags)4672 ubc_cs_blob_add(
4673 	struct vnode    *vp,
4674 	uint32_t        platform,
4675 	cpu_type_t      cputype,
4676 	cpu_subtype_t   cpusubtype,
4677 	off_t           base_offset,
4678 	vm_address_t    *addr,
4679 	vm_size_t       size,
4680 	struct image_params *imgp,
4681 	__unused int    flags,
4682 	struct cs_blob  **ret_blob,
4683 	cs_blob_add_flags_t csblob_add_flags)
4684 {
4685 	ptrauth_generic_signature_t cs_blob_sig = {0};
4686 	struct ubc_info *uip = NULL;
4687 	struct cs_blob tmp_blob = {0};
4688 	struct cs_blob *blob_ro = NULL;
4689 	struct cs_blob *oblob = NULL;
4690 	CS_CodeDirectory const *cd = NULL;
4691 	off_t blob_start_offset = 0;
4692 	off_t blob_end_offset = 0;
4693 	boolean_t record_mtime = false;
4694 	kern_return_t kr = KERN_DENIED;
4695 	errno_t error = -1;
4696 
4697 #if HAS_APPLE_PAC
4698 	void *signed_entitlements = NULL;
4699 #if CODE_SIGNING_MONITOR
4700 	void *signed_monitor_obj = NULL;
4701 #endif
4702 #endif
4703 
4704 	if (ret_blob) {
4705 		*ret_blob = NULL;
4706 	}
4707 
4708 	/*
4709 	 * Create the struct cs_blob abstract data type which will get attached to
4710 	 * the vnode object. This function also validates the structural integrity
4711 	 * of the code signature blob being passed in.
4712 	 *
4713 	 * We initialize a temporary blob whose contents are then copied into an RO
4714 	 * blob which we allocate from the read-only allocator.
4715 	 */
4716 	error = cs_blob_init_validated(addr, size, &tmp_blob, &cd);
4717 	if (error != 0) {
4718 		printf("unable to create a validated cs_blob object: %d\n", error);
4719 		return error;
4720 	}
4721 
4722 	tmp_blob.csb_cpu_type = cputype;
4723 	tmp_blob.csb_cpu_subtype = cpusubtype & ~CPU_SUBTYPE_MASK;
4724 	tmp_blob.csb_base_offset = base_offset;
4725 
4726 	/* Perform 1st stage reconstitution */
4727 	error = reconstitute_code_signature(&tmp_blob);
4728 	if (error != 0) {
4729 		goto out;
4730 	}
4731 
4732 	/*
4733 	 * There is a strong design pattern we have to follow carefully within this
4734 	 * function. Since we're storing the struct cs_blob within RO-allocated
4735 	 * memory, it is immutable to modifications from within the kernel itself.
4736 	 *
4737 	 * However, before the contents of the blob are transferred to the immutable
4738 	 * cs_blob, they are kept on the stack. In order to protect against a kernel
4739 	 * R/W attacker, we must protect this stack variable. Most importantly, any
4740 	 * code paths which can block for a while must compute a PAC signature over
4741 	 * the stack variable, then perform the blocking operation, and then ensure
4742 	 * that the PAC signature over the stack variable is still valid to ensure
4743 	 * that an attacker did not overwrite contents of the blob by introducing a
4744 	 * maliciously long blocking operation, giving them the time required to go
4745 	 * and overwrite the contents of the blob.
4746 	 *
4747 	 * The most important fields to protect here are the OSEntitlements and the
4748 	 * code signing monitor object references. For these ones, we keep around
4749 	 * extra signed pointers diversified against the read-only blobs' memory
4750 	 * and then update the stack variable with these before updating the full
4751 	 * read-only blob.
4752 	 */
4753 
4754 	blob_ro = zalloc_ro(ZONE_ID_CS_BLOB, Z_WAITOK | Z_NOFAIL);
4755 	assert(blob_ro != NULL);
4756 
4757 	tmp_blob.csb_ro_addr = blob_ro;
4758 	tmp_blob.csb_vnode = vp;
4759 
4760 	/* AMFI needs to see the current blob state at the RO address */
4761 	zalloc_ro_update_elem(ZONE_ID_CS_BLOB, blob_ro, &tmp_blob);
4762 
4763 #if CODE_SIGNING_MONITOR
4764 	error = register_code_signature_monitor(
4765 		vp,
4766 		&tmp_blob,
4767 		(vm_offset_t)tmp_blob.csb_cd - (vm_offset_t)tmp_blob.csb_mem_kaddr);
4768 
4769 	if (error != 0) {
4770 		goto out;
4771 	}
4772 
4773 #if HAS_APPLE_PAC
4774 	signed_monitor_obj = ptrauth_sign_unauthenticated(
4775 		tmp_blob.csb_csm_obj,
4776 		ptrauth_key_process_independent_data,
4777 		ptrauth_blend_discriminator(&blob_ro->csb_csm_obj,
4778 		OS_PTRAUTH_DISCRIMINATOR("cs_blob.csb_csm_obj")));
4779 #endif /* HAS_APPLE_PAC */
4780 
4781 #endif /* CODE_SIGNING_MONITOR */
4782 
4783 	/*
4784 	 * Ensure that we're honoring the main binary policy check on platforms which
4785 	 * require it. We perform this check at this stage to ensure the blob we're
4786 	 * looking at has been locked down by a code signing monitor if the system
4787 	 * has one.
4788 	 */
4789 	error = validate_main_binary_check(&tmp_blob, csblob_add_flags);
4790 	if (error != 0) {
4791 		printf("failed to verify main binary policy: %d\n", error);
4792 		goto out;
4793 	}
4794 
4795 #if CONFIG_MACF
4796 	unsigned int cs_flags = tmp_blob.csb_flags;
4797 	unsigned int signer_type = tmp_blob.csb_signer_type;
4798 
4799 	error = mac_vnode_check_signature(
4800 		vp,
4801 		&tmp_blob,
4802 		imgp,
4803 		&cs_flags,
4804 		&signer_type,
4805 		flags,
4806 		platform);
4807 
4808 	if (error != 0) {
4809 		printf("validation of code signature failed through MACF policy: %d\n", error);
4810 		goto out;
4811 	}
4812 
4813 #if HAS_APPLE_PAC
4814 	signed_entitlements = ptrauth_sign_unauthenticated(
4815 		tmp_blob.csb_entitlements,
4816 		ptrauth_key_process_independent_data,
4817 		ptrauth_blend_discriminator(&blob_ro->csb_entitlements,
4818 		OS_PTRAUTH_DISCRIMINATOR("cs_blob.csb_entitlements")));
4819 #endif
4820 
4821 	tmp_blob.csb_flags = cs_flags;
4822 	tmp_blob.csb_signer_type = signer_type;
4823 
4824 	if (tmp_blob.csb_flags & CS_PLATFORM_BINARY) {
4825 		tmp_blob.csb_platform_binary = 1;
4826 		tmp_blob.csb_platform_path = !!(tmp_blob.csb_flags & CS_PLATFORM_PATH);
4827 		tmp_blob.csb_teamid = NULL;
4828 	} else {
4829 		tmp_blob.csb_platform_binary = 0;
4830 		tmp_blob.csb_platform_path = 0;
4831 	}
4832 
4833 	if ((flags & MAC_VNODE_CHECK_DYLD_SIM) && !tmp_blob.csb_platform_binary) {
4834 		printf("dyld simulator runtime is not apple signed: proc: %d\n",
4835 		    proc_getpid(current_proc()));
4836 
4837 		error = EPERM;
4838 		goto out;
4839 	}
4840 #endif /* CONFIG_MACF */
4841 
4842 #if CODE_SIGNING_MONITOR
4843 	error = verify_code_signature_monitor(&tmp_blob);
4844 	if (error != 0) {
4845 		goto out;
4846 	}
4847 #endif
4848 
4849 	/* Perform 2nd stage reconstitution */
4850 	error = reconstitute_code_signature_2nd_stage(&tmp_blob);
4851 	if (error != 0) {
4852 		goto out;
4853 	}
4854 
4855 	/* Setup any multi-level hashing for the code signature */
4856 	error = setup_multilevel_hashing(&tmp_blob);
4857 	if (error != 0) {
4858 		goto out;
4859 	}
4860 
4861 	/* Ensure security critical auxiliary blobs still exist */
4862 	error = validate_auxiliary_signed_blobs(&tmp_blob);
4863 	if (error != 0) {
4864 		goto out;
4865 	}
4866 
4867 	/*
4868 	 * Accelerate the entitlement queries for this code signature. This must
4869 	 * be done only after we know that the code signature pointers within the
4870 	 * struct cs_blob aren't going to be shifted around anymore, which is why
4871 	 * this acceleration is done after setting up multilevel hashing, since
4872 	 * that is the last part of signature validation which can shift the code
4873 	 * signature around.
4874 	 */
4875 	error = accelerate_entitlement_queries(&tmp_blob);
4876 	if (error != 0) {
4877 		goto out;
4878 	}
4879 
4880 	/*
4881 	 * Parse and set the Team ID for this code signature. This only needs to
4882 	 * happen when the signature isn't marked as platform. Like above, this
4883 	 * has to happen after we know the pointers within struct cs_blob aren't
4884 	 * going to be shifted anymore.
4885 	 */
4886 	if ((tmp_blob.csb_flags & CS_PLATFORM_BINARY) == 0) {
4887 		tmp_blob.csb_teamid = csblob_parse_teamid(&tmp_blob);
4888 	}
4889 
4890 	/*
4891 	 * Validate the code signing blob's coverage. Ideally, we can just do this
4892 	 * in the beginning, right after structural validation, however, multilevel
4893 	 * hashing can change some offets.
4894 	 */
4895 	blob_start_offset = tmp_blob.csb_base_offset + tmp_blob.csb_start_offset;
4896 	blob_end_offset = tmp_blob.csb_base_offset + tmp_blob.csb_end_offset;
4897 	if (blob_start_offset >= blob_end_offset) {
4898 		error = EINVAL;
4899 		goto out;
4900 	} else if (blob_start_offset < 0 || blob_end_offset <= 0) {
4901 		error = EINVAL;
4902 		goto out;
4903 	}
4904 
4905 	/*
4906 	 * The vnode_lock, linked list traversal, and marking of the memory object as
4907 	 * signed can all be blocking operations. Compute a PAC over the tmp_blob.
4908 	 */
4909 	cs_blob_sig = ptrauth_utils_sign_blob_generic(
4910 		&tmp_blob,
4911 		sizeof(tmp_blob),
4912 		OS_PTRAUTH_DISCRIMINATOR("ubc_cs_blob_add.blocking_op0"),
4913 		PTRAUTH_ADDR_DIVERSIFY);
4914 
4915 	vnode_lock(vp);
4916 	if (!UBCINFOEXISTS(vp)) {
4917 		vnode_unlock(vp);
4918 		error = ENOENT;
4919 		goto out;
4920 	}
4921 	uip = vp->v_ubcinfo;
4922 
4923 	/* check if this new blob overlaps with an existing blob */
4924 	for (oblob = ubc_get_cs_blobs(vp);
4925 	    oblob != NULL;
4926 	    oblob = oblob->csb_next) {
4927 		off_t oblob_start_offset, oblob_end_offset;
4928 
4929 		if (tmp_blob.csb_signer_type != oblob->csb_signer_type) {  // signer type needs to be the same for slices
4930 			vnode_unlock(vp);
4931 			error = EALREADY;
4932 			goto out;
4933 		} else if (tmp_blob.csb_platform_binary) {  //platform binary needs to be the same for app slices
4934 			if (!oblob->csb_platform_binary) {
4935 				vnode_unlock(vp);
4936 				error = EALREADY;
4937 				goto out;
4938 			}
4939 		} else if (tmp_blob.csb_teamid) {  //teamid binary needs to be the same for app slices
4940 			if (oblob->csb_platform_binary ||
4941 			    oblob->csb_teamid == NULL ||
4942 			    strcmp(oblob->csb_teamid, tmp_blob.csb_teamid) != 0) {
4943 				vnode_unlock(vp);
4944 				error = EALREADY;
4945 				goto out;
4946 			}
4947 		} else {  // non teamid binary needs to be the same for app slices
4948 			if (oblob->csb_platform_binary ||
4949 			    oblob->csb_teamid != NULL) {
4950 				vnode_unlock(vp);
4951 				error = EALREADY;
4952 				goto out;
4953 			}
4954 		}
4955 
4956 		oblob_start_offset = (oblob->csb_base_offset +
4957 		    oblob->csb_start_offset);
4958 		oblob_end_offset = (oblob->csb_base_offset +
4959 		    oblob->csb_end_offset);
4960 		if (blob_start_offset >= oblob_end_offset ||
4961 		    blob_end_offset <= oblob_start_offset) {
4962 			/* no conflict with this existing blob */
4963 		} else {
4964 			/* conflict ! */
4965 			if (blob_start_offset == oblob_start_offset &&
4966 			    blob_end_offset == oblob_end_offset &&
4967 			    tmp_blob.csb_mem_size == oblob->csb_mem_size &&
4968 			    tmp_blob.csb_flags == oblob->csb_flags &&
4969 			    (tmp_blob.csb_cpu_type == CPU_TYPE_ANY ||
4970 			    oblob->csb_cpu_type == CPU_TYPE_ANY ||
4971 			    tmp_blob.csb_cpu_type == oblob->csb_cpu_type) &&
4972 			    !bcmp(tmp_blob.csb_cdhash,
4973 			    oblob->csb_cdhash,
4974 			    CS_CDHASH_LEN)) {
4975 				/*
4976 				 * We already have this blob:
4977 				 * we'll return success but
4978 				 * throw away the new blob.
4979 				 */
4980 				if (oblob->csb_cpu_type == CPU_TYPE_ANY) {
4981 					/*
4982 					 * The old blob matches this one
4983 					 * but doesn't have any CPU type.
4984 					 * Update it with whatever the caller
4985 					 * provided this time.
4986 					 */
4987 					cs_blob_set_cpu_type(oblob, cputype);
4988 				}
4989 
4990 				/* The signature is still accepted, so update the
4991 				 * generation count. */
4992 				uip->cs_add_gen = cs_blob_generation_count;
4993 
4994 				vnode_unlock(vp);
4995 				if (ret_blob) {
4996 					*ret_blob = oblob;
4997 				}
4998 				error = EAGAIN;
4999 				goto out;
5000 			} else {
5001 				/* different blob: reject the new one */
5002 				vnode_unlock(vp);
5003 				error = EALREADY;
5004 				goto out;
5005 			}
5006 		}
5007 	}
5008 
5009 	/* mark this vnode's VM object as having "signed pages" */
5010 	kr = memory_object_signed(uip->ui_control, TRUE);
5011 	if (kr != KERN_SUCCESS) {
5012 		vnode_unlock(vp);
5013 		error = ENOENT;
5014 		goto out;
5015 	}
5016 
5017 	if (uip->cs_blobs == NULL) {
5018 		/* loading 1st blob: record the file's current "modify time" */
5019 		record_mtime = TRUE;
5020 	}
5021 
5022 	/* set the generation count for cs_blobs */
5023 	uip->cs_add_gen = cs_blob_generation_count;
5024 
5025 	/* Authenticate the PAC signature after blocking operation */
5026 	ptrauth_utils_auth_blob_generic(
5027 		&tmp_blob,
5028 		sizeof(tmp_blob),
5029 		OS_PTRAUTH_DISCRIMINATOR("ubc_cs_blob_add.blocking_op0"),
5030 		PTRAUTH_ADDR_DIVERSIFY,
5031 		cs_blob_sig);
5032 
5033 	/* Update the system statistics for code signatures blobs */
5034 	ubc_cs_blob_adjust_statistics(&tmp_blob);
5035 
5036 	/* Update the list pointer to reference other blobs for this vnode */
5037 	tmp_blob.csb_next = uip->cs_blobs;
5038 
5039 #if HAS_APPLE_PAC
5040 	/*
5041 	 * Update all the critical pointers in the blob with the RO diversified
5042 	 * values before updating the read-only blob with the full contents of
5043 	 * the struct cs_blob. We need to use memcpy here as otherwise a simple
5044 	 * assignment will cause the compiler to re-sign using the stack variable
5045 	 * as the address diversifier.
5046 	 */
5047 	memcpy((void*)&tmp_blob.csb_entitlements, &signed_entitlements, sizeof(void*));
5048 #if CODE_SIGNING_MONITOR
5049 	memcpy((void*)&tmp_blob.csb_csm_obj, &signed_monitor_obj, sizeof(void*));
5050 #endif
5051 #endif
5052 	zalloc_ro_update_elem(ZONE_ID_CS_BLOB, blob_ro, &tmp_blob);
5053 
5054 	/* Add a fence to ensure writes to the blob are visible on all threads */
5055 	os_atomic_thread_fence(seq_cst);
5056 
5057 	/*
5058 	 * Add the cs_blob to the front of the list of blobs for this vnode. We
5059 	 * add to the front of the list, and we never remove a blob from the list
5060 	 * which means ubc_cs_get_blobs can return whatever the top of the list
5061 	 * is, while still keeping the list valid. Useful for if we validate a
5062 	 * page while adding in a new blob for this vnode.
5063 	 */
5064 	uip->cs_blobs = blob_ro;
5065 
5066 	/* Make sure to reload pointer from uip to double check */
5067 	if (uip->cs_blobs->csb_next) {
5068 		zone_require_ro(ZONE_ID_CS_BLOB, sizeof(struct cs_blob), uip->cs_blobs->csb_next);
5069 	}
5070 
5071 	if (cs_debug > 1) {
5072 		proc_t p;
5073 		const char *name = vnode_getname_printable(vp);
5074 		p = current_proc();
5075 		printf("CODE SIGNING: proc %d(%s) "
5076 		    "loaded %s signatures for file (%s) "
5077 		    "range 0x%llx:0x%llx flags 0x%x\n",
5078 		    proc_getpid(p), p->p_comm,
5079 		    blob_ro->csb_cpu_type == -1 ? "detached" : "embedded",
5080 		    name,
5081 		    blob_ro->csb_base_offset + blob_ro->csb_start_offset,
5082 		    blob_ro->csb_base_offset + blob_ro->csb_end_offset,
5083 		    blob_ro->csb_flags);
5084 		vnode_putname_printable(name);
5085 	}
5086 
5087 	vnode_unlock(vp);
5088 
5089 	if (record_mtime) {
5090 		vnode_mtime(vp, &uip->cs_mtime, vfs_context_current());
5091 	}
5092 
5093 	if (ret_blob) {
5094 		*ret_blob = blob_ro;
5095 	}
5096 
5097 	error = 0;      /* success ! */
5098 
5099 out:
5100 	if (error) {
5101 		if (error != EAGAIN) {
5102 			printf("check_signature[pid: %d]: error = %d\n", proc_getpid(current_proc()), error);
5103 		}
5104 
5105 		cs_blob_cleanup(&tmp_blob);
5106 		if (blob_ro) {
5107 			zfree_ro(ZONE_ID_CS_BLOB, blob_ro);
5108 		}
5109 	}
5110 
5111 	if (error == EAGAIN) {
5112 		/*
5113 		 * See above:  error is EAGAIN if we were asked
5114 		 * to add an existing blob again.  We cleaned the new
5115 		 * blob and we want to return success.
5116 		 */
5117 		error = 0;
5118 	}
5119 
5120 	return error;
5121 }
5122 
5123 #if CONFIG_SUPPLEMENTAL_SIGNATURES
5124 int
ubc_cs_blob_add_supplement(struct vnode * vp,struct vnode * orig_vp,off_t base_offset,vm_address_t * addr,vm_size_t size,struct cs_blob ** ret_blob)5125 ubc_cs_blob_add_supplement(
5126 	struct vnode    *vp,
5127 	struct vnode    *orig_vp,
5128 	off_t           base_offset,
5129 	vm_address_t    *addr,
5130 	vm_size_t       size,
5131 	struct cs_blob  **ret_blob)
5132 {
5133 	kern_return_t           kr;
5134 	struct ubc_info         *uip, *orig_uip;
5135 	int                     error;
5136 	struct cs_blob          tmp_blob;
5137 	struct cs_blob          *orig_blob;
5138 	struct cs_blob          *blob_ro = NULL;
5139 	CS_CodeDirectory const *cd;
5140 	off_t                   blob_start_offset, blob_end_offset;
5141 
5142 	if (ret_blob) {
5143 		*ret_blob = NULL;
5144 	}
5145 
5146 	/* Create the struct cs_blob wrapper that will be attached to the vnode.
5147 	 * Validates the passed in blob in the process. */
5148 	error = cs_blob_init_validated(addr, size, &tmp_blob, &cd);
5149 
5150 	if (error != 0) {
5151 		printf("malformed code signature supplement blob: %d\n", error);
5152 		return error;
5153 	}
5154 
5155 	tmp_blob.csb_cpu_type = -1;
5156 	tmp_blob.csb_base_offset = base_offset;
5157 
5158 	tmp_blob.csb_reconstituted = false;
5159 
5160 	vnode_lock(orig_vp);
5161 	if (!UBCINFOEXISTS(orig_vp)) {
5162 		vnode_unlock(orig_vp);
5163 		error = ENOENT;
5164 		goto out;
5165 	}
5166 
5167 	orig_uip = orig_vp->v_ubcinfo;
5168 
5169 	/* check that the supplement's linked cdhash matches a cdhash of
5170 	 * the target image.
5171 	 */
5172 
5173 	if (tmp_blob.csb_linkage_hashtype == NULL) {
5174 		proc_t p;
5175 		const char *iname = vnode_getname_printable(vp);
5176 		p = current_proc();
5177 
5178 		printf("CODE SIGNING: proc %d(%s) supplemental signature for file (%s) "
5179 		    "is not a supplemental.\n",
5180 		    proc_getpid(p), p->p_comm, iname);
5181 
5182 		error = EINVAL;
5183 
5184 		vnode_putname_printable(iname);
5185 		vnode_unlock(orig_vp);
5186 		goto out;
5187 	}
5188 	bool found_but_not_valid = false;
5189 	for (orig_blob = ubc_get_cs_blobs(orig_vp); orig_blob != NULL;
5190 	    orig_blob = orig_blob->csb_next) {
5191 		if (orig_blob->csb_hashtype == tmp_blob.csb_linkage_hashtype &&
5192 		    memcmp(orig_blob->csb_cdhash, tmp_blob.csb_linkage, CS_CDHASH_LEN) == 0) {
5193 			// Found match!
5194 			found_but_not_valid = ((orig_blob->csb_flags & CS_VALID) != CS_VALID);
5195 			break;
5196 		}
5197 	}
5198 
5199 	if (orig_blob == NULL || found_but_not_valid) {
5200 		// Not found.
5201 
5202 		proc_t p;
5203 		const char *iname = vnode_getname_printable(vp);
5204 		p = current_proc();
5205 
5206 		error = (orig_blob == NULL) ? ESRCH : EPERM;
5207 
5208 		printf("CODE SIGNING: proc %d(%s) supplemental signature for file (%s) "
5209 		    "does not match any attached cdhash (error: %d).\n",
5210 		    proc_getpid(p), p->p_comm, iname, error);
5211 
5212 		vnode_putname_printable(iname);
5213 		vnode_unlock(orig_vp);
5214 		goto out;
5215 	}
5216 
5217 	vnode_unlock(orig_vp);
5218 
5219 	blob_ro = zalloc_ro(ZONE_ID_CS_BLOB, Z_WAITOK | Z_NOFAIL);
5220 	tmp_blob.csb_ro_addr = blob_ro;
5221 	tmp_blob.csb_vnode = vp;
5222 
5223 	/* AMFI needs to see the current blob state at the RO address. */
5224 	zalloc_ro_update_elem(ZONE_ID_CS_BLOB, blob_ro, &tmp_blob);
5225 
5226 	// validate the signature against policy!
5227 #if CONFIG_MACF
5228 	unsigned int signer_type = tmp_blob.csb_signer_type;
5229 	error = mac_vnode_check_supplemental_signature(vp, &tmp_blob, orig_vp, orig_blob, &signer_type);
5230 
5231 	tmp_blob.csb_signer_type = signer_type;
5232 
5233 	if (error) {
5234 		if (cs_debug) {
5235 			printf("check_supplemental_signature[pid: %d], error = %d\n", proc_getpid(current_proc()), error);
5236 		}
5237 		goto out;
5238 	}
5239 #endif
5240 
5241 	// We allowed the supplemental signature blob so
5242 	// copy the platform bit or team-id from the linked signature and whether or not the original is developer code
5243 	tmp_blob.csb_platform_binary = 0;
5244 	tmp_blob.csb_platform_path = 0;
5245 	if (orig_blob->csb_platform_binary == 1) {
5246 		tmp_blob.csb_platform_binary = orig_blob->csb_platform_binary;
5247 		tmp_blob.csb_platform_path = orig_blob->csb_platform_path;
5248 	} else if (orig_blob->csb_teamid != NULL) {
5249 		vm_size_t teamid_size = strlen(orig_blob->csb_teamid) + 1;
5250 		tmp_blob.csb_supplement_teamid = kalloc_data(teamid_size, Z_WAITOK);
5251 		if (tmp_blob.csb_supplement_teamid == NULL) {
5252 			error = ENOMEM;
5253 			goto out;
5254 		}
5255 		strlcpy(tmp_blob.csb_supplement_teamid, orig_blob->csb_teamid, teamid_size);
5256 	}
5257 	tmp_blob.csb_flags = (orig_blob->csb_flags & CS_DEV_CODE);
5258 
5259 	// Validate the blob's coverage
5260 	blob_start_offset = tmp_blob.csb_base_offset + tmp_blob.csb_start_offset;
5261 	blob_end_offset = tmp_blob.csb_base_offset + tmp_blob.csb_end_offset;
5262 
5263 	if (blob_start_offset >= blob_end_offset || blob_start_offset < 0 || blob_end_offset <= 0) {
5264 		/* reject empty or backwards blob */
5265 		error = EINVAL;
5266 		goto out;
5267 	}
5268 
5269 	vnode_lock(vp);
5270 	if (!UBCINFOEXISTS(vp)) {
5271 		vnode_unlock(vp);
5272 		error = ENOENT;
5273 		goto out;
5274 	}
5275 	uip = vp->v_ubcinfo;
5276 
5277 	struct cs_blob *existing = uip->cs_blob_supplement;
5278 	if (existing != NULL) {
5279 		if (tmp_blob.csb_hashtype == existing->csb_hashtype &&
5280 		    memcmp(tmp_blob.csb_cdhash, existing->csb_cdhash, CS_CDHASH_LEN) == 0) {
5281 			error = EAGAIN; // non-fatal
5282 		} else {
5283 			error = EALREADY; // fatal
5284 		}
5285 
5286 		vnode_unlock(vp);
5287 		goto out;
5288 	}
5289 
5290 	/* mark this vnode's VM object as having "signed pages" */
5291 	kr = memory_object_signed(uip->ui_control, TRUE);
5292 	if (kr != KERN_SUCCESS) {
5293 		vnode_unlock(vp);
5294 		error = ENOENT;
5295 		goto out;
5296 	}
5297 
5298 
5299 	/* We still adjust statistics even for supplemental blobs, as they
5300 	 * consume memory just the same. */
5301 	ubc_cs_blob_adjust_statistics(&tmp_blob);
5302 	/* Unlike regular cs_blobs, we only ever support one supplement. */
5303 	tmp_blob.csb_next = NULL;
5304 	zalloc_ro_update_elem(ZONE_ID_CS_BLOB, blob_ro, &tmp_blob);
5305 
5306 	os_atomic_thread_fence(seq_cst); // Fence to prevent reordering here
5307 	uip->cs_blob_supplement = blob_ro;
5308 
5309 	/* Make sure to reload pointer from uip to double check */
5310 	if (__improbable(uip->cs_blob_supplement->csb_next)) {
5311 		panic("csb_next does not match expected NULL value");
5312 	}
5313 
5314 	vnode_unlock(vp);
5315 
5316 
5317 	if (cs_debug > 1) {
5318 		proc_t p;
5319 		const char *name = vnode_getname_printable(vp);
5320 		p = current_proc();
5321 		printf("CODE SIGNING: proc %d(%s) "
5322 		    "loaded supplemental signature for file (%s) "
5323 		    "range 0x%llx:0x%llx\n",
5324 		    proc_getpid(p), p->p_comm,
5325 		    name,
5326 		    blob_ro->csb_base_offset + blob_ro->csb_start_offset,
5327 		    blob_ro->csb_base_offset + blob_ro->csb_end_offset);
5328 		vnode_putname_printable(name);
5329 	}
5330 
5331 	if (ret_blob) {
5332 		*ret_blob = blob_ro;
5333 	}
5334 
5335 	error = 0; // Success!
5336 out:
5337 	if (error) {
5338 		if (cs_debug) {
5339 			printf("ubc_cs_blob_add_supplement[pid: %d]: error = %d\n", proc_getpid(current_proc()), error);
5340 		}
5341 
5342 		cs_blob_cleanup(&tmp_blob);
5343 		if (blob_ro) {
5344 			zfree_ro(ZONE_ID_CS_BLOB, blob_ro);
5345 		}
5346 	}
5347 
5348 	if (error == EAGAIN) {
5349 		/* We were asked to add an existing blob.
5350 		 * We cleaned up and ignore the attempt. */
5351 		error = 0;
5352 	}
5353 
5354 	return error;
5355 }
5356 #endif
5357 
5358 
5359 
5360 void
csvnode_print_debug(struct vnode * vp)5361 csvnode_print_debug(struct vnode *vp)
5362 {
5363 	const char      *name = NULL;
5364 	struct ubc_info *uip;
5365 	struct cs_blob *blob;
5366 
5367 	name = vnode_getname_printable(vp);
5368 	if (name) {
5369 		printf("csvnode: name: %s\n", name);
5370 		vnode_putname_printable(name);
5371 	}
5372 
5373 	vnode_lock_spin(vp);
5374 
5375 	if (!UBCINFOEXISTS(vp)) {
5376 		blob = NULL;
5377 		goto out;
5378 	}
5379 
5380 	uip = vp->v_ubcinfo;
5381 	for (blob = uip->cs_blobs; blob != NULL; blob = blob->csb_next) {
5382 		printf("csvnode: range: %lu -> %lu flags: 0x%08x platform: %s path: %s team: %s\n",
5383 		    (unsigned long)blob->csb_start_offset,
5384 		    (unsigned long)blob->csb_end_offset,
5385 		    blob->csb_flags,
5386 		    blob->csb_platform_binary ? "yes" : "no",
5387 		    blob->csb_platform_path ? "yes" : "no",
5388 		    blob->csb_teamid ? blob->csb_teamid : "<NO-TEAM>");
5389 	}
5390 
5391 out:
5392 	vnode_unlock(vp);
5393 }
5394 
5395 #if CONFIG_SUPPLEMENTAL_SIGNATURES
5396 struct cs_blob *
ubc_cs_blob_get_supplement(struct vnode * vp,off_t offset)5397 ubc_cs_blob_get_supplement(
5398 	struct vnode    *vp,
5399 	off_t           offset)
5400 {
5401 	struct cs_blob *blob;
5402 	off_t offset_in_blob;
5403 
5404 	vnode_lock_spin(vp);
5405 
5406 	if (!UBCINFOEXISTS(vp)) {
5407 		blob = NULL;
5408 		goto out;
5409 	}
5410 
5411 	blob = vp->v_ubcinfo->cs_blob_supplement;
5412 
5413 	if (blob == NULL) {
5414 		// no supplemental blob
5415 		goto out;
5416 	}
5417 
5418 
5419 	if (offset != -1) {
5420 		offset_in_blob = offset - blob->csb_base_offset;
5421 		if (offset_in_blob < blob->csb_start_offset || offset_in_blob >= blob->csb_end_offset) {
5422 			// not actually covered by this blob
5423 			blob = NULL;
5424 		}
5425 	}
5426 
5427 out:
5428 	vnode_unlock(vp);
5429 
5430 	return blob;
5431 }
5432 #endif
5433 
5434 struct cs_blob *
ubc_cs_blob_get(struct vnode * vp,cpu_type_t cputype,cpu_subtype_t cpusubtype,off_t offset)5435 ubc_cs_blob_get(
5436 	struct vnode    *vp,
5437 	cpu_type_t      cputype,
5438 	cpu_subtype_t   cpusubtype,
5439 	off_t           offset)
5440 {
5441 	struct cs_blob  *blob;
5442 	off_t offset_in_blob;
5443 
5444 	vnode_lock_spin(vp);
5445 
5446 	if (!UBCINFOEXISTS(vp)) {
5447 		blob = NULL;
5448 		goto out;
5449 	}
5450 
5451 	for (blob = ubc_get_cs_blobs(vp);
5452 	    blob != NULL;
5453 	    blob = blob->csb_next) {
5454 		if (cputype != -1 && blob->csb_cpu_type == cputype && (cpusubtype == -1 || blob->csb_cpu_subtype == (cpusubtype & ~CPU_SUBTYPE_MASK))) {
5455 			break;
5456 		}
5457 		if (offset != -1) {
5458 			offset_in_blob = offset - blob->csb_base_offset;
5459 			if (offset_in_blob >= blob->csb_start_offset &&
5460 			    offset_in_blob < blob->csb_end_offset) {
5461 				/* our offset is covered by this blob */
5462 				break;
5463 			}
5464 		}
5465 	}
5466 
5467 out:
5468 	vnode_unlock(vp);
5469 
5470 	return blob;
5471 }
5472 
5473 void
ubc_cs_free_and_vnode_unlock(vnode_t vp)5474 ubc_cs_free_and_vnode_unlock(
5475 	vnode_t vp)
5476 {
5477 	struct ubc_info *uip = vp->v_ubcinfo;
5478 	struct cs_blob  *cs_blobs, *blob, *next_blob;
5479 
5480 	if (!(uip->ui_flags & UI_CSBLOBINVALID)) {
5481 		vnode_unlock(vp);
5482 		return;
5483 	}
5484 
5485 	uip->ui_flags &= ~UI_CSBLOBINVALID;
5486 
5487 	cs_blobs = uip->cs_blobs;
5488 	uip->cs_blobs = NULL;
5489 
5490 #if CHECK_CS_VALIDATION_BITMAP
5491 	ubc_cs_validation_bitmap_deallocate( uip );
5492 #endif
5493 
5494 #if CONFIG_SUPPLEMENTAL_SIGNATURES
5495 	struct cs_blob  *cs_blob_supplement = uip->cs_blob_supplement;
5496 	uip->cs_blob_supplement = NULL;
5497 #endif
5498 
5499 	vnode_unlock(vp);
5500 
5501 	for (blob = cs_blobs;
5502 	    blob != NULL;
5503 	    blob = next_blob) {
5504 		next_blob = blob->csb_next;
5505 		os_atomic_add(&cs_blob_count, -1, relaxed);
5506 		os_atomic_add(&cs_blob_size, -blob->csb_mem_size, relaxed);
5507 		cs_blob_ro_free(blob);
5508 	}
5509 
5510 #if CONFIG_SUPPLEMENTAL_SIGNATURES
5511 	if (cs_blob_supplement != NULL) {
5512 		os_atomic_add(&cs_blob_count, -1, relaxed);
5513 		os_atomic_add(&cs_blob_size, -cs_blob_supplement->csb_mem_size, relaxed);
5514 		cs_blob_supplement_free(cs_blob_supplement);
5515 	}
5516 #endif
5517 }
5518 
5519 static void
ubc_cs_free(struct ubc_info * uip)5520 ubc_cs_free(
5521 	struct ubc_info *uip)
5522 {
5523 	struct cs_blob  *blob, *next_blob;
5524 
5525 	for (blob = uip->cs_blobs;
5526 	    blob != NULL;
5527 	    blob = next_blob) {
5528 		next_blob = blob->csb_next;
5529 		os_atomic_add(&cs_blob_count, -1, relaxed);
5530 		os_atomic_add(&cs_blob_size, -blob->csb_mem_size, relaxed);
5531 		cs_blob_ro_free(blob);
5532 	}
5533 #if CHECK_CS_VALIDATION_BITMAP
5534 	ubc_cs_validation_bitmap_deallocate( uip );
5535 #endif
5536 	uip->cs_blobs = NULL;
5537 #if CONFIG_SUPPLEMENTAL_SIGNATURES
5538 	if (uip->cs_blob_supplement != NULL) {
5539 		blob = uip->cs_blob_supplement;
5540 		os_atomic_add(&cs_blob_count, -1, relaxed);
5541 		os_atomic_add(&cs_blob_size, -blob->csb_mem_size, relaxed);
5542 		cs_blob_supplement_free(uip->cs_blob_supplement);
5543 		uip->cs_blob_supplement = NULL;
5544 	}
5545 #endif
5546 }
5547 
5548 /* check cs blob generation on vnode
5549  * returns:
5550  *    0         : Success, the cs_blob attached is current
5551  *    ENEEDAUTH : Generation count mismatch. Needs authentication again.
5552  */
5553 int
ubc_cs_generation_check(struct vnode * vp)5554 ubc_cs_generation_check(
5555 	struct vnode    *vp)
5556 {
5557 	int retval = ENEEDAUTH;
5558 
5559 	vnode_lock_spin(vp);
5560 
5561 	if (UBCINFOEXISTS(vp) && vp->v_ubcinfo->cs_add_gen == cs_blob_generation_count) {
5562 		retval = 0;
5563 	}
5564 
5565 	vnode_unlock(vp);
5566 	return retval;
5567 }
5568 
5569 int
ubc_cs_blob_revalidate(struct vnode * vp,struct cs_blob * blob,struct image_params * imgp,int flags,uint32_t platform)5570 ubc_cs_blob_revalidate(
5571 	struct vnode    *vp,
5572 	struct cs_blob *blob,
5573 	struct image_params *imgp,
5574 	int flags,
5575 	uint32_t platform
5576 	)
5577 {
5578 	int error = 0;
5579 	const CS_CodeDirectory *cd = NULL;
5580 	const CS_GenericBlob *entitlements = NULL;
5581 	const CS_GenericBlob *der_entitlements = NULL;
5582 	size_t size;
5583 	assert(vp != NULL);
5584 	assert(blob != NULL);
5585 
5586 	if ((blob->csb_flags & CS_VALID) == 0) {
5587 		// If the blob attached to the vnode was invalidated, don't try to revalidate it
5588 		// Blob invalidation only occurs when the file that the blob is attached to is
5589 		// opened for writing, giving us a signal that the file is modified.
5590 		printf("CODESIGNING: can not re-validate a previously invalidated blob, reboot or create a new file.\n");
5591 		error = EPERM;
5592 		goto out;
5593 	}
5594 
5595 	size = blob->csb_mem_size;
5596 	error = cs_validate_csblob((const uint8_t *)blob->csb_mem_kaddr,
5597 	    size, &cd, &entitlements, &der_entitlements);
5598 	if (error) {
5599 		if (cs_debug) {
5600 			printf("CODESIGNING: csblob invalid: %d\n", error);
5601 		}
5602 		goto out;
5603 	}
5604 
5605 	unsigned int cs_flags = (ntohl(cd->flags) & CS_ALLOWED_MACHO) | CS_VALID;
5606 	unsigned int signer_type = CS_SIGNER_TYPE_UNKNOWN;
5607 
5608 	if (blob->csb_reconstituted) {
5609 		/*
5610 		 * Code signatures that have been modified after validation
5611 		 * cannot be revalidated inline from their in-memory blob.
5612 		 *
5613 		 * That's okay, though, because the only path left that relies
5614 		 * on revalidation of existing in-memory blobs is the legacy
5615 		 * detached signature database path, which only exists on macOS,
5616 		 * which does not do reconstitution of any kind.
5617 		 */
5618 		if (cs_debug) {
5619 			printf("CODESIGNING: revalidate: not inline revalidating reconstituted signature.\n");
5620 		}
5621 
5622 		/*
5623 		 * EAGAIN tells the caller that they may reread the code
5624 		 * signature and try attaching it again, which is the same
5625 		 * thing they would do if there was no cs_blob yet in the
5626 		 * first place.
5627 		 *
5628 		 * Conveniently, after ubc_cs_blob_add did a successful
5629 		 * validation, it will detect that a matching cs_blob (cdhash,
5630 		 * offset, arch etc.) already exists, and return success
5631 		 * without re-adding a cs_blob to the vnode.
5632 		 */
5633 		return EAGAIN;
5634 	}
5635 
5636 	/* callout to mac_vnode_check_signature */
5637 #if CONFIG_MACF
5638 	error = mac_vnode_check_signature(vp, blob, imgp, &cs_flags, &signer_type, flags, platform);
5639 	if (cs_debug && error) {
5640 		printf("revalidate: check_signature[pid: %d], error = %d\n", proc_getpid(current_proc()), error);
5641 	}
5642 #else
5643 	(void)flags;
5644 	(void)signer_type;
5645 #endif
5646 
5647 	/* update generation number if success */
5648 	vnode_lock_spin(vp);
5649 	struct cs_signer_info signer_info = {
5650 		.csb_flags = cs_flags,
5651 		.csb_signer_type = signer_type
5652 	};
5653 	zalloc_ro_update_field(ZONE_ID_CS_BLOB, blob, csb_signer_info, &signer_info);
5654 	if (UBCINFOEXISTS(vp)) {
5655 		if (error == 0) {
5656 			vp->v_ubcinfo->cs_add_gen = cs_blob_generation_count;
5657 		} else {
5658 			vp->v_ubcinfo->cs_add_gen = 0;
5659 		}
5660 	}
5661 
5662 	vnode_unlock(vp);
5663 
5664 out:
5665 	return error;
5666 }
5667 
5668 void
cs_blob_reset_cache()5669 cs_blob_reset_cache()
5670 {
5671 	/* incrementing odd no by 2 makes sure '0' is never reached. */
5672 	OSAddAtomic(+2, &cs_blob_generation_count);
5673 	printf("Reseting cs_blob cache from all vnodes. \n");
5674 }
5675 
5676 struct cs_blob *
ubc_get_cs_blobs(struct vnode * vp)5677 ubc_get_cs_blobs(
5678 	struct vnode    *vp)
5679 {
5680 	struct ubc_info *uip;
5681 	struct cs_blob  *blobs;
5682 
5683 	/*
5684 	 * No need to take the vnode lock here.  The caller must be holding
5685 	 * a reference on the vnode (via a VM mapping or open file descriptor),
5686 	 * so the vnode will not go away.  The ubc_info stays until the vnode
5687 	 * goes away.  And we only modify "blobs" by adding to the head of the
5688 	 * list.
5689 	 * The ubc_info could go away entirely if the vnode gets reclaimed as
5690 	 * part of a forced unmount.  In the case of a code-signature validation
5691 	 * during a page fault, the "paging_in_progress" reference on the VM
5692 	 * object guarantess that the vnode pager (and the ubc_info) won't go
5693 	 * away during the fault.
5694 	 * Other callers need to protect against vnode reclaim by holding the
5695 	 * vnode lock, for example.
5696 	 */
5697 
5698 	if (!UBCINFOEXISTS(vp)) {
5699 		blobs = NULL;
5700 		goto out;
5701 	}
5702 
5703 	uip = vp->v_ubcinfo;
5704 	blobs = uip->cs_blobs;
5705 	if (blobs != NULL) {
5706 		cs_blob_require(blobs, vp);
5707 	}
5708 
5709 out:
5710 	return blobs;
5711 }
5712 
5713 #if CONFIG_SUPPLEMENTAL_SIGNATURES
5714 struct cs_blob *
ubc_get_cs_supplement(struct vnode * vp)5715 ubc_get_cs_supplement(
5716 	struct vnode    *vp)
5717 {
5718 	struct ubc_info *uip;
5719 	struct cs_blob  *blob;
5720 
5721 	/*
5722 	 * No need to take the vnode lock here.  The caller must be holding
5723 	 * a reference on the vnode (via a VM mapping or open file descriptor),
5724 	 * so the vnode will not go away.  The ubc_info stays until the vnode
5725 	 * goes away.
5726 	 * The ubc_info could go away entirely if the vnode gets reclaimed as
5727 	 * part of a forced unmount.  In the case of a code-signature validation
5728 	 * during a page fault, the "paging_in_progress" reference on the VM
5729 	 * object guarantess that the vnode pager (and the ubc_info) won't go
5730 	 * away during the fault.
5731 	 * Other callers need to protect against vnode reclaim by holding the
5732 	 * vnode lock, for example.
5733 	 */
5734 
5735 	if (!UBCINFOEXISTS(vp)) {
5736 		blob = NULL;
5737 		goto out;
5738 	}
5739 
5740 	uip = vp->v_ubcinfo;
5741 	blob = uip->cs_blob_supplement;
5742 	if (blob != NULL) {
5743 		cs_blob_require(blob, vp);
5744 	}
5745 
5746 out:
5747 	return blob;
5748 }
5749 #endif
5750 
5751 
5752 void
ubc_get_cs_mtime(struct vnode * vp,struct timespec * cs_mtime)5753 ubc_get_cs_mtime(
5754 	struct vnode    *vp,
5755 	struct timespec *cs_mtime)
5756 {
5757 	struct ubc_info *uip;
5758 
5759 	if (!UBCINFOEXISTS(vp)) {
5760 		cs_mtime->tv_sec = 0;
5761 		cs_mtime->tv_nsec = 0;
5762 		return;
5763 	}
5764 
5765 	uip = vp->v_ubcinfo;
5766 	cs_mtime->tv_sec = uip->cs_mtime.tv_sec;
5767 	cs_mtime->tv_nsec = uip->cs_mtime.tv_nsec;
5768 }
5769 
5770 unsigned long cs_validate_page_no_hash = 0;
5771 unsigned long cs_validate_page_bad_hash = 0;
5772 static boolean_t
cs_validate_hash(struct cs_blob * blobs,memory_object_t pager,memory_object_offset_t page_offset,const void * data,vm_size_t * bytes_processed,unsigned * tainted)5773 cs_validate_hash(
5774 	struct cs_blob          *blobs,
5775 	memory_object_t         pager,
5776 	memory_object_offset_t  page_offset,
5777 	const void              *data,
5778 	vm_size_t               *bytes_processed,
5779 	unsigned                *tainted)
5780 {
5781 	union cs_hash_union     mdctx;
5782 	struct cs_hash const    *hashtype = NULL;
5783 	unsigned char           actual_hash[CS_HASH_MAX_SIZE];
5784 	unsigned char           expected_hash[CS_HASH_MAX_SIZE];
5785 	boolean_t               found_hash;
5786 	struct cs_blob          *blob;
5787 	const CS_CodeDirectory  *cd;
5788 	const unsigned char     *hash;
5789 	boolean_t               validated;
5790 	off_t                   offset; /* page offset in the file */
5791 	size_t                  size;
5792 	off_t                   codeLimit = 0;
5793 	const char              *lower_bound, *upper_bound;
5794 	vm_offset_t             kaddr, blob_addr;
5795 
5796 	/* retrieve the expected hash */
5797 	found_hash = FALSE;
5798 
5799 	for (blob = blobs;
5800 	    blob != NULL;
5801 	    blob = blob->csb_next) {
5802 		offset = page_offset - blob->csb_base_offset;
5803 		if (offset < blob->csb_start_offset ||
5804 		    offset >= blob->csb_end_offset) {
5805 			/* our page is not covered by this blob */
5806 			continue;
5807 		}
5808 
5809 		/* blob data has been released */
5810 		kaddr = (vm_offset_t)blob->csb_mem_kaddr;
5811 		if (kaddr == 0) {
5812 			continue;
5813 		}
5814 
5815 		blob_addr = kaddr + blob->csb_mem_offset;
5816 		lower_bound = CAST_DOWN(char *, blob_addr);
5817 		upper_bound = lower_bound + blob->csb_mem_size;
5818 
5819 		cd = blob->csb_cd;
5820 		if (cd != NULL) {
5821 			/* all CD's that have been injected is already validated */
5822 
5823 			hashtype = blob->csb_hashtype;
5824 			if (hashtype == NULL) {
5825 				panic("unknown hash type ?");
5826 			}
5827 			if (hashtype->cs_digest_size > sizeof(actual_hash)) {
5828 				panic("hash size too large");
5829 			}
5830 			if (offset & ((1U << blob->csb_hash_pageshift) - 1)) {
5831 				panic("offset not aligned to cshash boundary");
5832 			}
5833 
5834 			codeLimit = ntohl(cd->codeLimit);
5835 
5836 			hash = hashes(cd, (uint32_t)(offset >> blob->csb_hash_pageshift),
5837 			    hashtype->cs_size,
5838 			    lower_bound, upper_bound);
5839 			if (hash != NULL) {
5840 				bcopy(hash, expected_hash, hashtype->cs_size);
5841 				found_hash = TRUE;
5842 			}
5843 
5844 			break;
5845 		}
5846 	}
5847 
5848 	if (found_hash == FALSE) {
5849 		/*
5850 		 * We can't verify this page because there is no signature
5851 		 * for it (yet).  It's possible that this part of the object
5852 		 * is not signed, or that signatures for that part have not
5853 		 * been loaded yet.
5854 		 * Report that the page has not been validated and let the
5855 		 * caller decide if it wants to accept it or not.
5856 		 */
5857 		cs_validate_page_no_hash++;
5858 		if (cs_debug > 1) {
5859 			printf("CODE SIGNING: cs_validate_page: "
5860 			    "mobj %p off 0x%llx: no hash to validate !?\n",
5861 			    pager, page_offset);
5862 		}
5863 		validated = FALSE;
5864 		*tainted = 0;
5865 	} else {
5866 		*tainted = 0;
5867 
5868 		size = (1U << blob->csb_hash_pageshift);
5869 		*bytes_processed = size;
5870 
5871 		const uint32_t *asha1, *esha1;
5872 		if ((off_t)(offset + size) > codeLimit) {
5873 			/* partial page at end of segment */
5874 			assert(offset < codeLimit);
5875 			size = (size_t) (codeLimit & (size - 1));
5876 			*tainted |= CS_VALIDATE_NX;
5877 		}
5878 
5879 		hashtype->cs_init(&mdctx);
5880 
5881 		if (blob->csb_hash_firstlevel_pageshift) {
5882 			const unsigned char *partial_data = (const unsigned char *)data;
5883 			size_t i;
5884 			for (i = 0; i < size;) {
5885 				union cs_hash_union     partialctx;
5886 				unsigned char partial_digest[CS_HASH_MAX_SIZE];
5887 				size_t partial_size = MIN(size - i, (1U << blob->csb_hash_firstlevel_pageshift));
5888 
5889 				hashtype->cs_init(&partialctx);
5890 				hashtype->cs_update(&partialctx, partial_data, partial_size);
5891 				hashtype->cs_final(partial_digest, &partialctx);
5892 
5893 				/* Update cumulative multi-level hash */
5894 				hashtype->cs_update(&mdctx, partial_digest, hashtype->cs_size);
5895 				partial_data = partial_data + partial_size;
5896 				i += partial_size;
5897 			}
5898 		} else {
5899 			hashtype->cs_update(&mdctx, data, size);
5900 		}
5901 		hashtype->cs_final(actual_hash, &mdctx);
5902 
5903 		asha1 = (const uint32_t *) actual_hash;
5904 		esha1 = (const uint32_t *) expected_hash;
5905 
5906 		if (bcmp(expected_hash, actual_hash, hashtype->cs_size) != 0) {
5907 			if (cs_debug) {
5908 				printf("CODE SIGNING: cs_validate_page: "
5909 				    "mobj %p off 0x%llx size 0x%lx: "
5910 				    "actual [0x%x 0x%x 0x%x 0x%x 0x%x] != "
5911 				    "expected [0x%x 0x%x 0x%x 0x%x 0x%x]\n",
5912 				    pager, page_offset, size,
5913 				    asha1[0], asha1[1], asha1[2],
5914 				    asha1[3], asha1[4],
5915 				    esha1[0], esha1[1], esha1[2],
5916 				    esha1[3], esha1[4]);
5917 			}
5918 			cs_validate_page_bad_hash++;
5919 			*tainted |= CS_VALIDATE_TAINTED;
5920 		} else {
5921 			if (cs_debug > 10) {
5922 				printf("CODE SIGNING: cs_validate_page: "
5923 				    "mobj %p off 0x%llx size 0x%lx: "
5924 				    "SHA1 OK\n",
5925 				    pager, page_offset, size);
5926 			}
5927 		}
5928 		validated = TRUE;
5929 	}
5930 
5931 	return validated;
5932 }
5933 
5934 boolean_t
cs_validate_range(struct vnode * vp,memory_object_t pager,memory_object_offset_t page_offset,const void * data,vm_size_t dsize,unsigned * tainted)5935 cs_validate_range(
5936 	struct vnode    *vp,
5937 	memory_object_t         pager,
5938 	memory_object_offset_t  page_offset,
5939 	const void              *data,
5940 	vm_size_t               dsize,
5941 	unsigned                *tainted)
5942 {
5943 	vm_size_t offset_in_range;
5944 	boolean_t all_subranges_validated = TRUE; /* turn false if any subrange fails */
5945 
5946 	struct cs_blob *blobs = ubc_get_cs_blobs(vp);
5947 
5948 #if CONFIG_SUPPLEMENTAL_SIGNATURES
5949 	if (blobs == NULL && proc_is_translated(current_proc())) {
5950 		struct cs_blob *supp = ubc_get_cs_supplement(vp);
5951 
5952 		if (supp != NULL) {
5953 			blobs = supp;
5954 		} else {
5955 			return FALSE;
5956 		}
5957 	}
5958 #endif
5959 
5960 #if DEVELOPMENT || DEBUG
5961 	code_signing_config_t cs_config = 0;
5962 
5963 	/*
5964 	 * This exemption is specifically useful for systems which want to avoid paying
5965 	 * the cost of verifying the integrity of pages, since that is done by computing
5966 	 * hashes, which can take some time.
5967 	 */
5968 	code_signing_configuration(NULL, &cs_config);
5969 	if (cs_config & CS_CONFIG_INTEGRITY_SKIP) {
5970 		*tainted = 0;
5971 
5972 		/* Return early to avoid paying the cost of hashing */
5973 		return true;
5974 	}
5975 #endif
5976 
5977 	*tainted = 0;
5978 
5979 	for (offset_in_range = 0;
5980 	    offset_in_range < dsize;
5981 	    /* offset_in_range updated based on bytes processed */) {
5982 		unsigned subrange_tainted = 0;
5983 		boolean_t subrange_validated;
5984 		vm_size_t bytes_processed = 0;
5985 
5986 		subrange_validated = cs_validate_hash(blobs,
5987 		    pager,
5988 		    page_offset + offset_in_range,
5989 		    (const void *)((const char *)data + offset_in_range),
5990 		    &bytes_processed,
5991 		    &subrange_tainted);
5992 
5993 		*tainted |= subrange_tainted;
5994 
5995 		if (bytes_processed == 0) {
5996 			/* Cannote make forward progress, so return an error */
5997 			all_subranges_validated = FALSE;
5998 			break;
5999 		} else if (subrange_validated == FALSE) {
6000 			all_subranges_validated = FALSE;
6001 			/* Keep going to detect other types of failures in subranges */
6002 		}
6003 
6004 		offset_in_range += bytes_processed;
6005 	}
6006 
6007 	return all_subranges_validated;
6008 }
6009 
6010 void
cs_validate_page(struct vnode * vp,memory_object_t pager,memory_object_offset_t page_offset,const void * data,int * validated_p,int * tainted_p,int * nx_p)6011 cs_validate_page(
6012 	struct vnode            *vp,
6013 	memory_object_t         pager,
6014 	memory_object_offset_t  page_offset,
6015 	const void              *data,
6016 	int                     *validated_p,
6017 	int                     *tainted_p,
6018 	int                     *nx_p)
6019 {
6020 	vm_size_t offset_in_page;
6021 	struct cs_blob *blobs;
6022 
6023 	blobs = ubc_get_cs_blobs(vp);
6024 
6025 #if CONFIG_SUPPLEMENTAL_SIGNATURES
6026 	if (blobs == NULL && proc_is_translated(current_proc())) {
6027 		struct cs_blob *supp = ubc_get_cs_supplement(vp);
6028 
6029 		if (supp != NULL) {
6030 			blobs = supp;
6031 		}
6032 	}
6033 #endif
6034 
6035 #if DEVELOPMENT || DEBUG
6036 	code_signing_config_t cs_config = 0;
6037 
6038 	/*
6039 	 * This exemption is specifically useful for systems which want to avoid paying
6040 	 * the cost of verifying the integrity of pages, since that is done by computing
6041 	 * hashes, which can take some time.
6042 	 */
6043 	code_signing_configuration(NULL, &cs_config);
6044 	if (cs_config & CS_CONFIG_INTEGRITY_SKIP) {
6045 		*validated_p = VMP_CS_ALL_TRUE;
6046 		*tainted_p = VMP_CS_ALL_FALSE;
6047 		*nx_p = VMP_CS_ALL_FALSE;
6048 
6049 		/* Return early to avoid paying the cost of hashing */
6050 		return;
6051 	}
6052 #endif
6053 
6054 	*validated_p = VMP_CS_ALL_FALSE;
6055 	*tainted_p = VMP_CS_ALL_FALSE;
6056 	*nx_p = VMP_CS_ALL_FALSE;
6057 
6058 	for (offset_in_page = 0;
6059 	    offset_in_page < PAGE_SIZE;
6060 	    /* offset_in_page updated based on bytes processed */) {
6061 		unsigned subrange_tainted = 0;
6062 		boolean_t subrange_validated;
6063 		vm_size_t bytes_processed = 0;
6064 		int sub_bit;
6065 
6066 		subrange_validated = cs_validate_hash(blobs,
6067 		    pager,
6068 		    page_offset + offset_in_page,
6069 		    (const void *)((const char *)data + offset_in_page),
6070 		    &bytes_processed,
6071 		    &subrange_tainted);
6072 
6073 		if (bytes_processed == 0) {
6074 			/* 4k chunk not code-signed: try next one */
6075 			offset_in_page += FOURK_PAGE_SIZE;
6076 			continue;
6077 		}
6078 		if (offset_in_page == 0 &&
6079 		    bytes_processed > PAGE_SIZE - FOURK_PAGE_SIZE) {
6080 			/* all processed: no 4k granularity */
6081 			if (subrange_validated) {
6082 				*validated_p = VMP_CS_ALL_TRUE;
6083 			}
6084 			if (subrange_tainted & CS_VALIDATE_TAINTED) {
6085 				*tainted_p = VMP_CS_ALL_TRUE;
6086 			}
6087 			if (subrange_tainted & CS_VALIDATE_NX) {
6088 				*nx_p = VMP_CS_ALL_TRUE;
6089 			}
6090 			break;
6091 		}
6092 		/* we only handle 4k or 16k code-signing granularity... */
6093 		assertf(bytes_processed <= FOURK_PAGE_SIZE,
6094 		    "vp %p blobs %p offset 0x%llx + 0x%llx bytes_processed 0x%llx\n",
6095 		    vp, blobs, (uint64_t)page_offset,
6096 		    (uint64_t)offset_in_page, (uint64_t)bytes_processed);
6097 		sub_bit = 1 << (offset_in_page >> FOURK_PAGE_SHIFT);
6098 		if (subrange_validated) {
6099 			*validated_p |= sub_bit;
6100 		}
6101 		if (subrange_tainted & CS_VALIDATE_TAINTED) {
6102 			*tainted_p |= sub_bit;
6103 		}
6104 		if (subrange_tainted & CS_VALIDATE_NX) {
6105 			*nx_p |= sub_bit;
6106 		}
6107 		/* go to next 4k chunk */
6108 		offset_in_page += FOURK_PAGE_SIZE;
6109 	}
6110 
6111 	return;
6112 }
6113 
6114 int
ubc_cs_getcdhash(vnode_t vp,off_t offset,unsigned char * cdhash,uint8_t * type)6115 ubc_cs_getcdhash(
6116 	vnode_t         vp,
6117 	off_t           offset,
6118 	unsigned char   *cdhash,
6119 	uint8_t         *type)
6120 {
6121 	struct cs_blob  *blobs, *blob;
6122 	off_t           rel_offset;
6123 	int             ret;
6124 
6125 	vnode_lock(vp);
6126 
6127 	blobs = ubc_get_cs_blobs(vp);
6128 	for (blob = blobs;
6129 	    blob != NULL;
6130 	    blob = blob->csb_next) {
6131 		/* compute offset relative to this blob */
6132 		rel_offset = offset - blob->csb_base_offset;
6133 		if (rel_offset >= blob->csb_start_offset &&
6134 		    rel_offset < blob->csb_end_offset) {
6135 			/* this blob does cover our "offset" ! */
6136 			break;
6137 		}
6138 	}
6139 
6140 	if (blob == NULL) {
6141 		/* we didn't find a blob covering "offset" */
6142 		ret = EBADEXEC; /* XXX any better error ? */
6143 	} else {
6144 		/* get the CDHash of that blob */
6145 		bcopy(blob->csb_cdhash, cdhash, sizeof(blob->csb_cdhash));
6146 
6147 		/* get the type of the CDHash */
6148 		if (type != NULL) {
6149 			*type = blob->csb_cd->hashType;
6150 		}
6151 
6152 		ret = 0;
6153 	}
6154 
6155 	vnode_unlock(vp);
6156 
6157 	return ret;
6158 }
6159 
6160 boolean_t
ubc_cs_is_range_codesigned(vnode_t vp,mach_vm_offset_t start,mach_vm_size_t size)6161 ubc_cs_is_range_codesigned(
6162 	vnode_t                 vp,
6163 	mach_vm_offset_t        start,
6164 	mach_vm_size_t          size)
6165 {
6166 	struct cs_blob          *csblob;
6167 	mach_vm_offset_t        blob_start;
6168 	mach_vm_offset_t        blob_end;
6169 
6170 	if (vp == NULL) {
6171 		/* no file: no code signature */
6172 		return FALSE;
6173 	}
6174 	if (size == 0) {
6175 		/* no range: no code signature */
6176 		return FALSE;
6177 	}
6178 	if (start + size < start) {
6179 		/* overflow */
6180 		return FALSE;
6181 	}
6182 
6183 	csblob = ubc_cs_blob_get(vp, -1, -1, start);
6184 	if (csblob == NULL) {
6185 		return FALSE;
6186 	}
6187 
6188 	/*
6189 	 * We currently check if the range is covered by a single blob,
6190 	 * which should always be the case for the dyld shared cache.
6191 	 * If we ever want to make this routine handle other cases, we
6192 	 * would have to iterate if the blob does not cover the full range.
6193 	 */
6194 	blob_start = (mach_vm_offset_t) (csblob->csb_base_offset +
6195 	    csblob->csb_start_offset);
6196 	blob_end = (mach_vm_offset_t) (csblob->csb_base_offset +
6197 	    csblob->csb_end_offset);
6198 	if (blob_start > start || blob_end < (start + size)) {
6199 		/* range not fully covered by this code-signing blob */
6200 		return FALSE;
6201 	}
6202 
6203 	return TRUE;
6204 }
6205 
6206 #if CHECK_CS_VALIDATION_BITMAP
6207 #define stob(s) (((atop_64(round_page_64(s))) + 07) >> 3)
6208 extern  boolean_t       root_fs_upgrade_try;
6209 
6210 /*
6211  * Should we use the code-sign bitmap to avoid repeated code-sign validation?
6212  * Depends:
6213  * a) Is the target vnode on the root filesystem?
6214  * b) Has someone tried to mount the root filesystem read-write?
6215  * If answers are (a) yes AND (b) no, then we can use the bitmap.
6216  */
6217 #define USE_CODE_SIGN_BITMAP(vp)        ( (vp != NULL) && (vp->v_mount != NULL) && (vp->v_mount->mnt_flag & MNT_ROOTFS) && !root_fs_upgrade_try)
6218 kern_return_t
ubc_cs_validation_bitmap_allocate(vnode_t vp)6219 ubc_cs_validation_bitmap_allocate(
6220 	vnode_t         vp)
6221 {
6222 	kern_return_t   kr = KERN_SUCCESS;
6223 	struct ubc_info *uip;
6224 	char            *target_bitmap;
6225 	vm_object_size_t        bitmap_size;
6226 
6227 	if (!USE_CODE_SIGN_BITMAP(vp) || (!UBCINFOEXISTS(vp))) {
6228 		kr = KERN_INVALID_ARGUMENT;
6229 	} else {
6230 		uip = vp->v_ubcinfo;
6231 
6232 		if (uip->cs_valid_bitmap == NULL) {
6233 			bitmap_size = stob(uip->ui_size);
6234 			target_bitmap = (char*) kalloc_data((vm_size_t)bitmap_size, Z_WAITOK | Z_ZERO);
6235 			if (target_bitmap == 0) {
6236 				kr = KERN_NO_SPACE;
6237 			} else {
6238 				kr = KERN_SUCCESS;
6239 			}
6240 			if (kr == KERN_SUCCESS) {
6241 				uip->cs_valid_bitmap = (void*)target_bitmap;
6242 				uip->cs_valid_bitmap_size = bitmap_size;
6243 			}
6244 		}
6245 	}
6246 	return kr;
6247 }
6248 
6249 kern_return_t
ubc_cs_check_validation_bitmap(vnode_t vp,memory_object_offset_t offset,int optype)6250 ubc_cs_check_validation_bitmap(
6251 	vnode_t                 vp,
6252 	memory_object_offset_t          offset,
6253 	int                     optype)
6254 {
6255 	kern_return_t   kr = KERN_SUCCESS;
6256 
6257 	if (!USE_CODE_SIGN_BITMAP(vp) || !UBCINFOEXISTS(vp)) {
6258 		kr = KERN_INVALID_ARGUMENT;
6259 	} else {
6260 		struct ubc_info *uip = vp->v_ubcinfo;
6261 		char            *target_bitmap = uip->cs_valid_bitmap;
6262 
6263 		if (target_bitmap == NULL) {
6264 			kr = KERN_INVALID_ARGUMENT;
6265 		} else {
6266 			uint64_t        bit, byte;
6267 			bit = atop_64( offset );
6268 			byte = bit >> 3;
6269 
6270 			if (byte > uip->cs_valid_bitmap_size) {
6271 				kr = KERN_INVALID_ARGUMENT;
6272 			} else {
6273 				if (optype == CS_BITMAP_SET) {
6274 					target_bitmap[byte] |= (1 << (bit & 07));
6275 					kr = KERN_SUCCESS;
6276 				} else if (optype == CS_BITMAP_CLEAR) {
6277 					target_bitmap[byte] &= ~(1 << (bit & 07));
6278 					kr = KERN_SUCCESS;
6279 				} else if (optype == CS_BITMAP_CHECK) {
6280 					if (target_bitmap[byte] & (1 << (bit & 07))) {
6281 						kr = KERN_SUCCESS;
6282 					} else {
6283 						kr = KERN_FAILURE;
6284 					}
6285 				}
6286 			}
6287 		}
6288 	}
6289 	return kr;
6290 }
6291 
6292 void
ubc_cs_validation_bitmap_deallocate(struct ubc_info * uip)6293 ubc_cs_validation_bitmap_deallocate(
6294 	struct ubc_info *uip)
6295 {
6296 	if (uip->cs_valid_bitmap != NULL) {
6297 		kfree_data(uip->cs_valid_bitmap, (vm_size_t)uip->cs_valid_bitmap_size);
6298 		uip->cs_valid_bitmap = NULL;
6299 	}
6300 }
6301 #else
6302 kern_return_t
ubc_cs_validation_bitmap_allocate(__unused vnode_t vp)6303 ubc_cs_validation_bitmap_allocate(__unused vnode_t vp)
6304 {
6305 	return KERN_INVALID_ARGUMENT;
6306 }
6307 
6308 kern_return_t
ubc_cs_check_validation_bitmap(__unused struct vnode * vp,__unused memory_object_offset_t offset,__unused int optype)6309 ubc_cs_check_validation_bitmap(
6310 	__unused struct vnode *vp,
6311 	__unused memory_object_offset_t offset,
6312 	__unused int optype)
6313 {
6314 	return KERN_INVALID_ARGUMENT;
6315 }
6316 
6317 void
ubc_cs_validation_bitmap_deallocate(__unused struct ubc_info * uip)6318 ubc_cs_validation_bitmap_deallocate(__unused struct ubc_info *uip)
6319 {
6320 	return;
6321 }
6322 #endif /* CHECK_CS_VALIDATION_BITMAP */
6323 
6324 #if CODE_SIGNING_MONITOR
6325 
6326 kern_return_t
cs_associate_blob_with_mapping(void * pmap,vm_map_offset_t start,vm_map_size_t size,vm_object_offset_t offset,void * blobs_p)6327 cs_associate_blob_with_mapping(
6328 	void                    *pmap,
6329 	vm_map_offset_t         start,
6330 	vm_map_size_t           size,
6331 	vm_object_offset_t      offset,
6332 	void                    *blobs_p)
6333 {
6334 	off_t                   blob_start_offset, blob_end_offset;
6335 	kern_return_t           kr;
6336 	struct cs_blob          *blobs, *blob;
6337 	vm_offset_t             kaddr;
6338 	void                    *monitor_sig_obj = NULL;
6339 
6340 	if (csm_enabled() == false) {
6341 		return KERN_NOT_SUPPORTED;
6342 	}
6343 
6344 	blobs = (struct cs_blob *)blobs_p;
6345 
6346 	for (blob = blobs;
6347 	    blob != NULL;
6348 	    blob = blob->csb_next) {
6349 		blob_start_offset = (blob->csb_base_offset +
6350 		    blob->csb_start_offset);
6351 		blob_end_offset = (blob->csb_base_offset +
6352 		    blob->csb_end_offset);
6353 		if ((off_t) offset < blob_start_offset ||
6354 		    (off_t) offset >= blob_end_offset ||
6355 		    (off_t) (offset + size) <= blob_start_offset ||
6356 		    (off_t) (offset + size) > blob_end_offset) {
6357 			continue;
6358 		}
6359 
6360 		kaddr = (vm_offset_t)blob->csb_mem_kaddr;
6361 		if (kaddr == 0) {
6362 			/* blob data has been released */
6363 			continue;
6364 		}
6365 
6366 		monitor_sig_obj = blob->csb_csm_obj;
6367 		if (monitor_sig_obj == NULL) {
6368 			continue;
6369 		}
6370 
6371 		break;
6372 	}
6373 
6374 	if (monitor_sig_obj != NULL) {
6375 		vm_offset_t segment_offset = offset - blob_start_offset;
6376 		kr = csm_associate_code_signature(pmap, monitor_sig_obj, start, size, segment_offset);
6377 	} else {
6378 		kr = KERN_CODESIGN_ERROR;
6379 	}
6380 
6381 	return kr;
6382 }
6383 
6384 #endif /* CODE_SIGNING_MONITOR */
6385