]> git.saurik.com Git - apple/xnu.git/blame - bsd/kern/ubc_subr.c
xnu-7195.81.3.tar.gz
[apple/xnu.git] / bsd / kern / ubc_subr.c
CommitLineData
1c79356b 1/*
f427ee49 2 * Copyright (c) 1999-2020 Apple Inc. All rights reserved.
1c79356b 3 *
2d21ac55 4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
0a7de745 5 *
2d21ac55
A
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.
0a7de745 14 *
2d21ac55
A
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
0a7de745 17 *
2d21ac55
A
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
8f6c56a5
A
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
2d21ac55
A
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.
0a7de745 25 *
2d21ac55 26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
1c79356b 27 */
0a7de745 28/*
1c79356b
A
29 * File: ubc_subr.c
30 * Author: Umesh Vaishampayan [umeshv@apple.com]
31 * 05-Aug-1999 umeshv Created.
32 *
33 * Functions related to Unified Buffer cache.
34 *
0b4e3aa0
A
35 * Caller of UBC functions MUST have a valid reference on the vnode.
36 *
0a7de745 37 */
1c79356b 38
1c79356b
A
39#include <sys/types.h>
40#include <sys/param.h>
41#include <sys/systm.h>
42#include <sys/lock.h>
91447636
A
43#include <sys/mman.h>
44#include <sys/mount_internal.h>
45#include <sys/vnode_internal.h>
46#include <sys/ubc_internal.h>
1c79356b 47#include <sys/ucred.h>
91447636
A
48#include <sys/proc_internal.h>
49#include <sys/kauth.h>
1c79356b 50#include <sys/buf.h>
13fec989 51#include <sys/user.h>
2d21ac55 52#include <sys/codesign.h>
fe8ab488
A
53#include <sys/codedir_internal.h>
54#include <sys/fsevents.h>
c18c124e 55#include <sys/fcntl.h>
f427ee49 56#include <sys/reboot.h>
1c79356b
A
57
58#include <mach/mach_types.h>
59#include <mach/memory_object_types.h>
91447636
A
60#include <mach/memory_object_control.h>
61#include <mach/vm_map.h>
b0d623f7 62#include <mach/mach_vm.h>
91447636 63#include <mach/upl.h>
1c79356b 64
91447636 65#include <kern/kern_types.h>
2d21ac55 66#include <kern/kalloc.h>
1c79356b 67#include <kern/zalloc.h>
13fec989 68#include <kern/thread.h>
5ba3f43e 69#include <vm/pmap.h>
91447636
A
70#include <vm/vm_kern.h>
71#include <vm/vm_protos.h> /* last */
1c79356b 72
2d21ac55 73#include <libkern/crypto/sha1.h>
3e170ce0 74#include <libkern/crypto/sha2.h>
39236c6e 75#include <libkern/libkern.h>
f427ee49 76#include <libkern/ptrauth_utils.h>
39236c6e 77
593a1d5f 78#include <security/mac_framework.h>
fe8ab488 79#include <stdbool.h>
f427ee49 80#include <stdatomic.h>
593a1d5f 81
2d21ac55
A
82/* XXX These should be in a BSD accessible Mach header, but aren't. */
83extern kern_return_t memory_object_pages_resident(memory_object_control_t,
0a7de745
A
84 boolean_t *);
85extern kern_return_t memory_object_signed(memory_object_control_t control,
86 boolean_t is_signed);
87extern boolean_t memory_object_is_signed(memory_object_control_t);
cb323159
A
88extern void memory_object_mark_trusted(
89 memory_object_control_t control);
6d2010ae 90
d9a64523
A
91/* XXX Same for those. */
92
2d21ac55
A
93extern void Debugger(const char *message);
94
95
96/* XXX no one uses this interface! */
97kern_return_t ubc_page_op_with_control(
0a7de745
A
98 memory_object_control_t control,
99 off_t f_offset,
100 int ops,
101 ppnum_t *phys_entryp,
102 int *flagsp);
2d21ac55
A
103
104
1c79356b
A
105#if DIAGNOSTIC
106#if defined(assert)
b0d623f7 107#undef assert
1c79356b
A
108#endif
109#define assert(cond) \
2d21ac55 110 ((void) ((cond) ? 0 : panic("Assert failed: %s", # cond)))
1c79356b
A
111#else
112#include <kern/assert.h>
113#endif /* DIAGNOSTIC */
114
2d21ac55 115static int ubc_info_init_internal(struct vnode *vp, int withfsize, off_t filesize);
0c530ab8 116static int ubc_umcallback(vnode_t, void *);
0c530ab8 117static int ubc_msync_internal(vnode_t, off_t, off_t, off_t *, int, int *);
2d21ac55 118static void ubc_cs_free(struct ubc_info *uip);
b4c24cb9 119
39037602 120static boolean_t ubc_cs_supports_multilevel_hash(struct cs_blob *blob);
d9a64523 121static kern_return_t ubc_cs_convert_to_multilevel_hash(struct cs_blob *blob);
39037602 122
f427ee49
A
123ZONE_DECLARE(ubc_info_zone, "ubc_info zone", sizeof(struct ubc_info),
124 ZC_NOENCRYPT | ZC_ZFREE_CLEARMEM);
0a7de745 125static uint32_t cs_blob_generation_count = 1;
2d21ac55
A
126
127/*
128 * CODESIGNING
129 * Routines to navigate code signing data structures in the kernel...
130 */
b0d623f7
A
131
132extern int cs_debug;
133
0a7de745 134#define PAGE_SHIFT_4K (12)
fe8ab488 135
2d21ac55
A
136static boolean_t
137cs_valid_range(
138 const void *start,
139 const void *end,
140 const void *lower_bound,
141 const void *upper_bound)
142{
143 if (upper_bound < lower_bound ||
144 end < start) {
145 return FALSE;
146 }
147
148 if (start < lower_bound ||
149 end > upper_bound) {
150 return FALSE;
151 }
152
153 return TRUE;
154}
155
3e170ce0
A
156typedef void (*cs_md_init)(void *ctx);
157typedef void (*cs_md_update)(void *ctx, const void *data, size_t size);
158typedef void (*cs_md_final)(void *hash, void *ctx);
159
160struct cs_hash {
0a7de745
A
161 uint8_t cs_type; /* type code as per code signing */
162 size_t cs_size; /* size of effective hash (may be truncated) */
163 size_t cs_digest_size;/* size of native hash */
164 cs_md_init cs_init;
165 cs_md_update cs_update;
166 cs_md_final cs_final;
3e170ce0
A
167};
168
0a7de745
A
169uint8_t
170cs_hash_type(
171 struct cs_hash const * const cs_hash)
5ba3f43e 172{
0a7de745 173 return cs_hash->cs_type;
5ba3f43e
A
174}
175
d190cdc3 176static const struct cs_hash cs_hash_sha1 = {
0a7de745
A
177 .cs_type = CS_HASHTYPE_SHA1,
178 .cs_size = CS_SHA1_LEN,
179 .cs_digest_size = SHA_DIGEST_LENGTH,
180 .cs_init = (cs_md_init)SHA1Init,
181 .cs_update = (cs_md_update)SHA1Update,
182 .cs_final = (cs_md_final)SHA1Final,
3e170ce0
A
183};
184#if CRYPTO_SHA2
d190cdc3 185static const struct cs_hash cs_hash_sha256 = {
0a7de745
A
186 .cs_type = CS_HASHTYPE_SHA256,
187 .cs_size = SHA256_DIGEST_LENGTH,
188 .cs_digest_size = SHA256_DIGEST_LENGTH,
189 .cs_init = (cs_md_init)SHA256_Init,
190 .cs_update = (cs_md_update)SHA256_Update,
191 .cs_final = (cs_md_final)SHA256_Final,
3e170ce0 192};
d190cdc3 193static const struct cs_hash cs_hash_sha256_truncate = {
0a7de745
A
194 .cs_type = CS_HASHTYPE_SHA256_TRUNCATED,
195 .cs_size = CS_SHA256_TRUNCATED_LEN,
196 .cs_digest_size = SHA256_DIGEST_LENGTH,
197 .cs_init = (cs_md_init)SHA256_Init,
198 .cs_update = (cs_md_update)SHA256_Update,
199 .cs_final = (cs_md_final)SHA256_Final,
3e170ce0 200};
d190cdc3 201static const struct cs_hash cs_hash_sha384 = {
0a7de745
A
202 .cs_type = CS_HASHTYPE_SHA384,
203 .cs_size = SHA384_DIGEST_LENGTH,
204 .cs_digest_size = SHA384_DIGEST_LENGTH,
205 .cs_init = (cs_md_init)SHA384_Init,
206 .cs_update = (cs_md_update)SHA384_Update,
207 .cs_final = (cs_md_final)SHA384_Final,
490019cf 208};
3e170ce0 209#endif
39037602 210
d190cdc3 211static struct cs_hash const *
3e170ce0
A
212cs_find_md(uint8_t type)
213{
214 if (type == CS_HASHTYPE_SHA1) {
215 return &cs_hash_sha1;
216#if CRYPTO_SHA2
217 } else if (type == CS_HASHTYPE_SHA256) {
218 return &cs_hash_sha256;
219 } else if (type == CS_HASHTYPE_SHA256_TRUNCATED) {
220 return &cs_hash_sha256_truncate;
490019cf
A
221 } else if (type == CS_HASHTYPE_SHA384) {
222 return &cs_hash_sha384;
3e170ce0
A
223#endif
224 }
225 return NULL;
226}
227
228union cs_hash_union {
0a7de745
A
229 SHA1_CTX sha1ctxt;
230 SHA256_CTX sha256ctx;
231 SHA384_CTX sha384ctx;
3e170ce0
A
232};
233
234
2d21ac55 235/*
490019cf
A
236 * Choose among different hash algorithms.
237 * Higher is better, 0 => don't use at all.
2d21ac55 238 */
d190cdc3 239static const uint32_t hashPriorities[] = {
490019cf
A
240 CS_HASHTYPE_SHA1,
241 CS_HASHTYPE_SHA256_TRUNCATED,
242 CS_HASHTYPE_SHA256,
243 CS_HASHTYPE_SHA384,
244};
b0d623f7 245
490019cf
A
246static unsigned int
247hash_rank(const CS_CodeDirectory *cd)
248{
249 uint32_t type = cd->hashType;
250 unsigned int n;
2d21ac55 251
0a7de745
A
252 for (n = 0; n < sizeof(hashPriorities) / sizeof(hashPriorities[0]); ++n) {
253 if (hashPriorities[n] == type) {
490019cf 254 return n + 1;
0a7de745
A
255 }
256 }
257 return 0; /* not supported */
2d21ac55
A
258}
259
260
261/*
262 * Locating a page hash
263 */
264static const unsigned char *
265hashes(
266 const CS_CodeDirectory *cd,
3e170ce0
A
267 uint32_t page,
268 size_t hash_len,
269 const char *lower_bound,
270 const char *upper_bound)
2d21ac55
A
271{
272 const unsigned char *base, *top, *hash;
b0d623f7 273 uint32_t nCodeSlots = ntohl(cd->nCodeSlots);
2d21ac55
A
274
275 assert(cs_valid_range(cd, cd + 1, lower_bound, upper_bound));
276
0a7de745 277 if ((ntohl(cd->version) >= CS_SUPPORTSSCATTER) && (ntohl(cd->scatterOffset))) {
b0d623f7 278 /* Get first scatter struct */
39236c6e 279 const SC_Scatter *scatter = (const SC_Scatter*)
0a7de745
A
280 ((const char*)cd + ntohl(cd->scatterOffset));
281 uint32_t hashindex = 0, scount, sbase = 0;
b0d623f7
A
282 /* iterate all scatter structs */
283 do {
0a7de745
A
284 if ((const char*)scatter > (const char*)cd + ntohl(cd->length)) {
285 if (cs_debug) {
b0d623f7
A
286 printf("CODE SIGNING: Scatter extends past Code Directory\n");
287 }
288 return NULL;
289 }
0a7de745 290
b0d623f7
A
291 scount = ntohl(scatter->count);
292 uint32_t new_base = ntohl(scatter->base);
293
294 /* last scatter? */
295 if (scount == 0) {
296 return NULL;
297 }
0a7de745
A
298
299 if ((hashindex > 0) && (new_base <= sbase)) {
300 if (cs_debug) {
b0d623f7 301 printf("CODE SIGNING: unordered Scatter, prev base %d, cur base %d\n",
0a7de745 302 sbase, new_base);
b0d623f7 303 }
0a7de745 304 return NULL; /* unordered scatter array */
b0d623f7
A
305 }
306 sbase = new_base;
307
308 /* this scatter beyond page we're looking for? */
309 if (sbase > page) {
310 return NULL;
311 }
0a7de745
A
312
313 if (sbase + scount >= page) {
314 /* Found the scatter struct that is
b0d623f7
A
315 * referencing our page */
316
317 /* base = address of first hash covered by scatter */
0a7de745
A
318 base = (const unsigned char *)cd + ntohl(cd->hashOffset) +
319 hashindex * hash_len;
b0d623f7 320 /* top = address of first hash after this scatter */
3e170ce0 321 top = base + scount * hash_len;
0a7de745
A
322 if (!cs_valid_range(base, top, lower_bound,
323 upper_bound) ||
b0d623f7
A
324 hashindex > nCodeSlots) {
325 return NULL;
326 }
0a7de745 327
b0d623f7
A
328 break;
329 }
0a7de745
A
330
331 /* this scatter struct is before the page we're looking
b0d623f7 332 * for. Iterate. */
0a7de745 333 hashindex += scount;
b0d623f7 334 scatter++;
0a7de745
A
335 } while (1);
336
3e170ce0 337 hash = base + (page - sbase) * hash_len;
b0d623f7
A
338 } else {
339 base = (const unsigned char *)cd + ntohl(cd->hashOffset);
3e170ce0 340 top = base + nCodeSlots * hash_len;
b0d623f7
A
341 if (!cs_valid_range(base, top, lower_bound, upper_bound) ||
342 page > nCodeSlots) {
343 return NULL;
344 }
345 assert(page < nCodeSlots);
2d21ac55 346
3e170ce0 347 hash = base + page * hash_len;
b0d623f7 348 }
0a7de745 349
3e170ce0 350 if (!cs_valid_range(hash, hash + hash_len,
0a7de745 351 lower_bound, upper_bound)) {
2d21ac55
A
352 hash = NULL;
353 }
354
355 return hash;
356}
39236c6e
A
357
358/*
359 * cs_validate_codedirectory
360 *
361 * Validate that pointers inside the code directory to make sure that
362 * all offsets and lengths are constrained within the buffer.
363 *
364 * Parameters: cd Pointer to code directory buffer
365 * length Length of buffer
366 *
367 * Returns: 0 Success
368 * EBADEXEC Invalid code signature
369 */
370
371static int
372cs_validate_codedirectory(const CS_CodeDirectory *cd, size_t length)
373{
d190cdc3 374 struct cs_hash const *hashtype;
39236c6e 375
0a7de745 376 if (length < sizeof(*cd)) {
39236c6e 377 return EBADEXEC;
0a7de745
A
378 }
379 if (ntohl(cd->magic) != CSMAGIC_CODEDIRECTORY) {
39236c6e 380 return EBADEXEC;
0a7de745
A
381 }
382 if (cd->pageSize < PAGE_SHIFT_4K || cd->pageSize > PAGE_SHIFT) {
39236c6e 383 return EBADEXEC;
0a7de745 384 }
3e170ce0 385 hashtype = cs_find_md(cd->hashType);
0a7de745 386 if (hashtype == NULL) {
39236c6e 387 return EBADEXEC;
0a7de745 388 }
39236c6e 389
0a7de745 390 if (cd->hashSize != hashtype->cs_size) {
3e170ce0 391 return EBADEXEC;
0a7de745 392 }
3e170ce0 393
0a7de745 394 if (length < ntohl(cd->hashOffset)) {
39236c6e 395 return EBADEXEC;
0a7de745 396 }
39236c6e
A
397
398 /* check that nSpecialSlots fits in the buffer in front of hashOffset */
0a7de745 399 if (ntohl(cd->hashOffset) / hashtype->cs_size < ntohl(cd->nSpecialSlots)) {
39236c6e 400 return EBADEXEC;
0a7de745 401 }
39236c6e
A
402
403 /* check that codeslots fits in the buffer */
0a7de745 404 if ((length - ntohl(cd->hashOffset)) / hashtype->cs_size < ntohl(cd->nCodeSlots)) {
39236c6e 405 return EBADEXEC;
0a7de745 406 }
39236c6e 407
0a7de745
A
408 if (ntohl(cd->version) >= CS_SUPPORTSSCATTER && cd->scatterOffset) {
409 if (length < ntohl(cd->scatterOffset)) {
39236c6e 410 return EBADEXEC;
0a7de745 411 }
39236c6e 412
3e170ce0 413 const SC_Scatter *scatter = (const SC_Scatter *)
0a7de745 414 (((const uint8_t *)cd) + ntohl(cd->scatterOffset));
39236c6e
A
415 uint32_t nPages = 0;
416
417 /*
418 * Check each scatter buffer, since we don't know the
419 * length of the scatter buffer array, we have to
420 * check each entry.
421 */
0a7de745 422 while (1) {
39236c6e 423 /* check that the end of each scatter buffer in within the length */
0a7de745 424 if (((const uint8_t *)scatter) + sizeof(scatter[0]) > (const uint8_t *)cd + length) {
39236c6e 425 return EBADEXEC;
0a7de745 426 }
39236c6e 427 uint32_t scount = ntohl(scatter->count);
0a7de745 428 if (scount == 0) {
39236c6e 429 break;
0a7de745
A
430 }
431 if (nPages + scount < nPages) {
39236c6e 432 return EBADEXEC;
0a7de745 433 }
39236c6e
A
434 nPages += scount;
435 scatter++;
436
437 /* XXX check that basees doesn't overlap */
438 /* XXX check that targetOffset doesn't overlap */
439 }
440#if 0 /* rdar://12579439 */
0a7de745 441 if (nPages != ntohl(cd->nCodeSlots)) {
39236c6e 442 return EBADEXEC;
0a7de745 443 }
39236c6e
A
444#endif
445 }
446
0a7de745 447 if (length < ntohl(cd->identOffset)) {
39236c6e 448 return EBADEXEC;
0a7de745 449 }
39236c6e
A
450
451 /* identifier is NUL terminated string */
452 if (cd->identOffset) {
3e170ce0 453 const uint8_t *ptr = (const uint8_t *)cd + ntohl(cd->identOffset);
0a7de745 454 if (memchr(ptr, 0, length - ntohl(cd->identOffset)) == NULL) {
39236c6e 455 return EBADEXEC;
0a7de745 456 }
39236c6e
A
457 }
458
fe8ab488
A
459 /* team identifier is NULL terminated string */
460 if (ntohl(cd->version) >= CS_SUPPORTSTEAMID && ntohl(cd->teamOffset)) {
0a7de745 461 if (length < ntohl(cd->teamOffset)) {
fe8ab488 462 return EBADEXEC;
0a7de745 463 }
fe8ab488 464
3e170ce0 465 const uint8_t *ptr = (const uint8_t *)cd + ntohl(cd->teamOffset);
0a7de745 466 if (memchr(ptr, 0, length - ntohl(cd->teamOffset)) == NULL) {
fe8ab488 467 return EBADEXEC;
0a7de745 468 }
fe8ab488
A
469 }
470
f427ee49
A
471 /* linkage is variable length binary data */
472 if (ntohl(cd->version) >= CS_SUPPORTSLINKAGE && cd->linkageHashType != 0) {
473 const uintptr_t ptr = (uintptr_t)cd + ntohl(cd->linkageOffset);
474 const uintptr_t ptr_end = ptr + ntohl(cd->linkageSize);
475
476 if (ptr_end < ptr || ptr < (uintptr_t)cd || ptr_end > (uintptr_t)cd + length) {
477 return EBADEXEC;
478 }
479 }
480
481
39236c6e
A
482 return 0;
483}
484
485/*
486 *
487 */
488
489static int
490cs_validate_blob(const CS_GenericBlob *blob, size_t length)
491{
0a7de745 492 if (length < sizeof(CS_GenericBlob) || length < ntohl(blob->length)) {
39236c6e 493 return EBADEXEC;
0a7de745 494 }
39236c6e
A
495 return 0;
496}
497
498/*
499 * cs_validate_csblob
500 *
501 * Validate that superblob/embedded code directory to make sure that
502 * all internal pointers are valid.
503 *
504 * Will validate both a superblob csblob and a "raw" code directory.
505 *
506 *
507 * Parameters: buffer Pointer to code signature
508 * length Length of buffer
509 * rcd returns pointer to code directory
510 *
511 * Returns: 0 Success
512 * EBADEXEC Invalid code signature
513 */
514
515static int
813fb2f6
A
516cs_validate_csblob(
517 const uint8_t *addr,
d9a64523 518 const size_t blob_size,
813fb2f6
A
519 const CS_CodeDirectory **rcd,
520 const CS_GenericBlob **rentitlements)
39236c6e 521{
813fb2f6 522 const CS_GenericBlob *blob;
39236c6e 523 int error;
d9a64523 524 size_t length;
39236c6e
A
525
526 *rcd = NULL;
39037602 527 *rentitlements = NULL;
39236c6e 528
813fb2f6 529 blob = (const CS_GenericBlob *)(const void *)addr;
813fb2f6
A
530
531 length = blob_size;
39236c6e 532 error = cs_validate_blob(blob, length);
0a7de745 533 if (error) {
39236c6e 534 return error;
0a7de745 535 }
39236c6e
A
536 length = ntohl(blob->length);
537
538 if (ntohl(blob->magic) == CSMAGIC_EMBEDDED_SIGNATURE) {
490019cf
A
539 const CS_SuperBlob *sb;
540 uint32_t n, count;
541 const CS_CodeDirectory *best_cd = NULL;
542 unsigned int best_rank = 0;
5ba3f43e
A
543#if PLATFORM_WatchOS
544 const CS_CodeDirectory *sha1_cd = NULL;
545#endif
39236c6e 546
0a7de745 547 if (length < sizeof(CS_SuperBlob)) {
39236c6e 548 return EBADEXEC;
0a7de745 549 }
39236c6e 550
490019cf
A
551 sb = (const CS_SuperBlob *)blob;
552 count = ntohl(sb->count);
553
39236c6e 554 /* check that the array of BlobIndex fits in the rest of the data */
0a7de745 555 if ((length - sizeof(CS_SuperBlob)) / sizeof(CS_BlobIndex) < count) {
39236c6e 556 return EBADEXEC;
0a7de745 557 }
39236c6e
A
558
559 /* now check each BlobIndex */
560 for (n = 0; n < count; n++) {
561 const CS_BlobIndex *blobIndex = &sb->index[n];
490019cf
A
562 uint32_t type = ntohl(blobIndex->type);
563 uint32_t offset = ntohl(blobIndex->offset);
0a7de745 564 if (length < offset) {
39236c6e 565 return EBADEXEC;
0a7de745 566 }
39236c6e
A
567
568 const CS_GenericBlob *subBlob =
0a7de745 569 (const CS_GenericBlob *)(const void *)(addr + offset);
39236c6e 570
490019cf 571 size_t subLength = length - offset;
39236c6e 572
0a7de745 573 if ((error = cs_validate_blob(subBlob, subLength)) != 0) {
39236c6e 574 return error;
0a7de745 575 }
39236c6e
A
576 subLength = ntohl(subBlob->length);
577
578 /* extra validation for CDs, that is also returned */
490019cf
A
579 if (type == CSSLOT_CODEDIRECTORY || (type >= CSSLOT_ALTERNATE_CODEDIRECTORIES && type < CSSLOT_ALTERNATE_CODEDIRECTORY_LIMIT)) {
580 const CS_CodeDirectory *candidate = (const CS_CodeDirectory *)subBlob;
0a7de745 581 if ((error = cs_validate_codedirectory(candidate, subLength)) != 0) {
39236c6e 582 return error;
0a7de745 583 }
490019cf 584 unsigned int rank = hash_rank(candidate);
0a7de745 585 if (cs_debug > 3) {
490019cf 586 printf("CodeDirectory type %d rank %d at slot 0x%x index %d\n", candidate->hashType, (int)rank, (int)type, (int)n);
0a7de745 587 }
490019cf
A
588 if (best_cd == NULL || rank > best_rank) {
589 best_cd = candidate;
590 best_rank = rank;
39037602 591
0a7de745 592 if (cs_debug > 2) {
39037602 593 printf("using CodeDirectory type %d (rank %d)\n", (int)best_cd->hashType, best_rank);
0a7de745 594 }
39037602 595 *rcd = best_cd;
490019cf
A
596 } else if (best_cd != NULL && rank == best_rank) {
597 /* repeat of a hash type (1:1 mapped to ranks), illegal and suspicious */
39037602
A
598 printf("multiple hash=%d CodeDirectories in signature; rejecting\n", best_cd->hashType);
599 return EBADEXEC;
600 }
5ba3f43e
A
601#if PLATFORM_WatchOS
602 if (candidate->hashType == CS_HASHTYPE_SHA1) {
603 if (sha1_cd != NULL) {
604 printf("multiple sha1 CodeDirectories in signature; rejecting\n");
605 return EBADEXEC;
606 }
607 sha1_cd = candidate;
608 }
609#endif
39037602
A
610 } else if (type == CSSLOT_ENTITLEMENTS) {
611 if (ntohl(subBlob->magic) != CSMAGIC_EMBEDDED_ENTITLEMENTS) {
612 return EBADEXEC;
613 }
614 if (*rentitlements != NULL) {
615 printf("multiple entitlements blobs\n");
490019cf
A
616 return EBADEXEC;
617 }
39037602 618 *rentitlements = subBlob;
39236c6e
A
619 }
620 }
621
5ba3f43e
A
622#if PLATFORM_WatchOS
623 /* To keep watchOS fast enough, we have to resort to sha1 for
624 * some code.
625 *
626 * At the time of writing this comment, known sha1 attacks are
627 * collision attacks (not preimage or second preimage
628 * attacks), which do not apply to platform binaries since
629 * they have a fixed hash in the trust cache. Given this
630 * property, we only prefer sha1 code directories for adhoc
631 * signatures, which always have to be in a trust cache to be
632 * valid (can-load-cdhash does not exist for watchOS). Those
633 * are, incidentally, also the platform binaries, for which we
634 * care about the performance hit that sha256 would bring us.
635 *
636 * Platform binaries may still contain a (not chosen) sha256
637 * code directory, which keeps software updates that switch to
638 * sha256-only small.
639 */
640
641 if (*rcd != NULL && sha1_cd != NULL && (ntohl(sha1_cd->flags) & CS_ADHOC)) {
642 if (sha1_cd->flags != (*rcd)->flags) {
643 printf("mismatched flags between hash %d (flags: %#x) and sha1 (flags: %#x) cd.\n",
0a7de745 644 (int)(*rcd)->hashType, (*rcd)->flags, sha1_cd->flags);
5ba3f43e
A
645 *rcd = NULL;
646 return EBADEXEC;
647 }
648
649 *rcd = sha1_cd;
650 }
651#endif
39236c6e 652 } else if (ntohl(blob->magic) == CSMAGIC_CODEDIRECTORY) {
0a7de745 653 if ((error = cs_validate_codedirectory((const CS_CodeDirectory *)(const void *)addr, length)) != 0) {
39236c6e 654 return error;
0a7de745 655 }
39236c6e
A
656 *rcd = (const CS_CodeDirectory *)blob;
657 } else {
658 return EBADEXEC;
659 }
660
0a7de745 661 if (*rcd == NULL) {
39236c6e 662 return EBADEXEC;
0a7de745 663 }
39236c6e
A
664
665 return 0;
666}
667
668/*
669 * cs_find_blob_bytes
670 *
671 * Find an blob from the superblob/code directory. The blob must have
672 * been been validated by cs_validate_csblob() before calling
3e170ce0 673 * this. Use csblob_find_blob() instead.
0a7de745 674 *
39236c6e
A
675 * Will also find a "raw" code directory if its stored as well as
676 * searching the superblob.
677 *
678 * Parameters: buffer Pointer to code signature
679 * length Length of buffer
680 * type type of blob to find
681 * magic the magic number for that blob
682 *
683 * Returns: pointer Success
684 * NULL Buffer not found
685 */
686
3e170ce0
A
687const CS_GenericBlob *
688csblob_find_blob_bytes(const uint8_t *addr, size_t length, uint32_t type, uint32_t magic)
39236c6e 689{
3e170ce0 690 const CS_GenericBlob *blob = (const CS_GenericBlob *)(const void *)addr;
39236c6e
A
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++) {
0a7de745 697 if (ntohl(sb->index[n].type) != type) {
39236c6e 698 continue;
0a7de745 699 }
39236c6e 700 uint32_t offset = ntohl(sb->index[n].offset);
0a7de745 701 if (length - sizeof(const CS_GenericBlob) < offset) {
39236c6e 702 return NULL;
0a7de745 703 }
3e170ce0 704 blob = (const CS_GenericBlob *)(const void *)(addr + offset);
0a7de745 705 if (ntohl(blob->magic) != magic) {
39236c6e 706 continue;
0a7de745 707 }
39236c6e
A
708 return blob;
709 }
710 } else if (type == CSSLOT_CODEDIRECTORY
0a7de745
A
711 && ntohl(blob->magic) == CSMAGIC_CODEDIRECTORY
712 && magic == CSMAGIC_CODEDIRECTORY) {
39236c6e 713 return blob;
0a7de745 714 }
39236c6e
A
715 return NULL;
716}
717
718
fe8ab488 719const CS_GenericBlob *
3e170ce0 720csblob_find_blob(struct cs_blob *csblob, uint32_t type, uint32_t magic)
39236c6e 721{
0a7de745 722 if ((csblob->csb_flags & CS_VALID) == 0) {
39236c6e 723 return NULL;
0a7de745 724 }
3e170ce0 725 return csblob_find_blob_bytes((const uint8_t *)csblob->csb_mem_kaddr, csblob->csb_mem_size, type, magic);
39236c6e
A
726}
727
728static const uint8_t *
3e170ce0 729find_special_slot(const CS_CodeDirectory *cd, size_t slotsize, uint32_t slot)
39236c6e
A
730{
731 /* there is no zero special slot since that is the first code slot */
0a7de745 732 if (ntohl(cd->nSpecialSlots) < slot || slot == 0) {
39236c6e 733 return NULL;
0a7de745 734 }
39236c6e 735
0a7de745 736 return (const uint8_t *)cd + ntohl(cd->hashOffset) - (slotsize * slot);
39236c6e
A
737}
738
3e170ce0 739static uint8_t cshash_zero[CS_HASH_MAX_SIZE] = { 0 };
39236c6e 740
6d2010ae 741int
3e170ce0 742csblob_get_entitlements(struct cs_blob *csblob, void **out_start, size_t *out_length)
6d2010ae 743{
3e170ce0 744 uint8_t computed_hash[CS_HASH_MAX_SIZE];
39236c6e
A
745 const CS_GenericBlob *entitlements;
746 const CS_CodeDirectory *code_dir;
39236c6e 747 const uint8_t *embedded_hash;
3e170ce0 748 union cs_hash_union context;
39236c6e
A
749
750 *out_start = NULL;
751 *out_length = 0;
752
0a7de745
A
753 if (csblob->csb_hashtype == NULL || csblob->csb_hashtype->cs_digest_size > sizeof(computed_hash)) {
754 return EBADEXEC;
755 }
39236c6e 756
490019cf 757 code_dir = csblob->csb_cd;
39236c6e 758
39037602
A
759 if ((csblob->csb_flags & CS_VALID) == 0) {
760 entitlements = NULL;
761 } else {
762 entitlements = csblob->csb_entitlements_blob;
763 }
3e170ce0 764 embedded_hash = find_special_slot(code_dir, csblob->csb_hashtype->cs_size, CSSLOT_ENTITLEMENTS);
39236c6e
A
765
766 if (embedded_hash == NULL) {
0a7de745 767 if (entitlements) {
39236c6e 768 return EBADEXEC;
0a7de745 769 }
39236c6e 770 return 0;
490019cf
A
771 } else if (entitlements == NULL) {
772 if (memcmp(embedded_hash, cshash_zero, csblob->csb_hashtype->cs_size) != 0) {
773 return EBADEXEC;
774 } else {
775 return 0;
776 }
6d2010ae 777 }
39236c6e 778
3e170ce0
A
779 csblob->csb_hashtype->cs_init(&context);
780 csblob->csb_hashtype->cs_update(&context, entitlements, ntohl(entitlements->length));
781 csblob->csb_hashtype->cs_final(computed_hash, &context);
782
0a7de745 783 if (memcmp(computed_hash, embedded_hash, csblob->csb_hashtype->cs_size) != 0) {
39236c6e 784 return EBADEXEC;
0a7de745 785 }
39236c6e 786
3e170ce0 787 *out_start = __DECONST(void *, entitlements);
39236c6e
A
788 *out_length = ntohl(entitlements->length);
789
790 return 0;
791}
792
6d2010ae 793/*
3e170ce0
A
794 * CODESIGNING
795 * End of routines to navigate code signing data structures in the kernel.
6d2010ae
A
796 */
797
798
2d21ac55 799
1c79356b 800/*
2d21ac55
A
801 * ubc_info_init
802 *
803 * Allocate and attach an empty ubc_info structure to a vnode
804 *
805 * Parameters: vp Pointer to the vnode
806 *
807 * Returns: 0 Success
808 * vnode_size:ENOMEM Not enough space
809 * vnode_size:??? Other error from vnode_getattr
810 *
1c79356b
A
811 */
812int
813ubc_info_init(struct vnode *vp)
91447636 814{
0a7de745 815 return ubc_info_init_internal(vp, 0, 0);
91447636 816}
2d21ac55
A
817
818
819/*
820 * ubc_info_init_withsize
821 *
822 * Allocate and attach a sized ubc_info structure to a vnode
823 *
824 * Parameters: vp Pointer to the vnode
825 * filesize The size of the file
826 *
827 * Returns: 0 Success
828 * vnode_size:ENOMEM Not enough space
829 * vnode_size:??? Other error from vnode_getattr
830 */
91447636
A
831int
832ubc_info_init_withsize(struct vnode *vp, off_t filesize)
833{
0a7de745 834 return ubc_info_init_internal(vp, 1, filesize);
91447636
A
835}
836
2d21ac55
A
837
838/*
839 * ubc_info_init_internal
840 *
841 * Allocate and attach a ubc_info structure to a vnode
842 *
843 * Parameters: vp Pointer to the vnode
844 * withfsize{0,1} Zero if the size should be obtained
845 * from the vnode; otherwise, use filesize
846 * filesize The size of the file, if withfsize == 1
847 *
848 * Returns: 0 Success
849 * vnode_size:ENOMEM Not enough space
850 * vnode_size:??? Other error from vnode_getattr
851 *
852 * Notes: We call a blocking zalloc(), and the zone was created as an
853 * expandable and collectable zone, so if no memory is available,
854 * it is possible for zalloc() to block indefinitely. zalloc()
855 * may also panic if the zone of zones is exhausted, since it's
856 * NOT expandable.
857 *
858 * We unconditionally call vnode_pager_setup(), even if this is
859 * a reuse of a ubc_info; in that case, we should probably assert
860 * that it does not already have a pager association, but do not.
861 *
862 * Since memory_object_create_named() can only fail from receiving
863 * an invalid pager argument, the explicit check and panic is
864 * merely precautionary.
865 */
866static int
867ubc_info_init_internal(vnode_t vp, int withfsize, off_t filesize)
1c79356b 868{
0a7de745 869 struct ubc_info *uip;
1c79356b 870 void * pager;
1c79356b
A
871 int error = 0;
872 kern_return_t kret;
0b4e3aa0 873 memory_object_control_t control;
1c79356b 874
91447636 875 uip = vp->v_ubcinfo;
1c79356b 876
2d21ac55
A
877 /*
878 * If there is not already a ubc_info attached to the vnode, we
879 * attach one; otherwise, we will reuse the one that's there.
880 */
91447636 881 if (uip == UBC_INFO_NULL) {
1c79356b 882 uip = (struct ubc_info *) zalloc(ubc_info_zone);
91447636
A
883 bzero((char *)uip, sizeof(struct ubc_info));
884
1c79356b 885 uip->ui_vnode = vp;
91447636 886 uip->ui_flags = UI_INITED;
1c79356b
A
887 uip->ui_ucred = NOCRED;
888 }
1c79356b
A
889 assert(uip->ui_flags != UI_NONE);
890 assert(uip->ui_vnode == vp);
891
1c79356b
A
892 /* now set this ubc_info in the vnode */
893 vp->v_ubcinfo = uip;
91447636 894
2d21ac55
A
895 /*
896 * Allocate a pager object for this vnode
897 *
898 * XXX The value of the pager parameter is currently ignored.
899 * XXX Presumably, this API changed to avoid the race between
900 * XXX setting the pager and the UI_HASPAGER flag.
901 */
1c79356b
A
902 pager = (void *)vnode_pager_setup(vp, uip->ui_pager);
903 assert(pager);
91447636 904
2d21ac55
A
905 /*
906 * Explicitly set the pager into the ubc_info, after setting the
907 * UI_HASPAGER flag.
908 */
91447636
A
909 SET(uip->ui_flags, UI_HASPAGER);
910 uip->ui_pager = pager;
1c79356b
A
911
912 /*
91447636 913 * Note: We can not use VNOP_GETATTR() to get accurate
2d21ac55
A
914 * value of ui_size because this may be an NFS vnode, and
915 * nfs_getattr() can call vinvalbuf(); if this happens,
916 * ubc_info is not set up to deal with that event.
1c79356b
A
917 * So use bogus size.
918 */
919
1c79356b 920 /*
0b4e3aa0
A
921 * create a vnode - vm_object association
922 * memory_object_create_named() creates a "named" reference on the
923 * memory object we hold this reference as long as the vnode is
924 * "alive." Since memory_object_create_named() took its own reference
925 * on the vnode pager we passed it, we can drop the reference
926 * vnode_pager_setup() returned here.
1c79356b 927 */
0b4e3aa0 928 kret = memory_object_create_named(pager,
0a7de745
A
929 (memory_object_size_t)uip->ui_size, &control);
930 vnode_pager_deallocate(pager);
931 if (kret != KERN_SUCCESS) {
0b4e3aa0 932 panic("ubc_info_init: memory_object_create_named returned %d", kret);
0a7de745 933 }
1c79356b 934
0b4e3aa0 935 assert(control);
0a7de745
A
936 uip->ui_control = control; /* cache the value of the mo control */
937 SET(uip->ui_flags, UI_HASOBJREF); /* with a named reference */
2d21ac55 938
91447636 939 if (withfsize == 0) {
91447636 940 /* initialize the size */
2d21ac55 941 error = vnode_size(vp, &uip->ui_size, vfs_context_current());
0a7de745 942 if (error) {
91447636 943 uip->ui_size = 0;
0a7de745 944 }
91447636
A
945 } else {
946 uip->ui_size = filesize;
947 }
0a7de745 948 vp->v_lflag |= VNAMED_UBC; /* vnode has a named ubc reference */
1c79356b 949
0a7de745 950 return error;
1c79356b
A
951}
952
2d21ac55
A
953
954/*
955 * ubc_info_free
956 *
957 * Free a ubc_info structure
958 *
959 * Parameters: uip A pointer to the ubc_info to free
960 *
961 * Returns: (void)
962 *
963 * Notes: If there is a credential that has subsequently been associated
964 * with the ubc_info via a call to ubc_setcred(), the reference
965 * to the credential is dropped.
966 *
967 * It's actually impossible for a ubc_info.ui_control to take the
968 * value MEMORY_OBJECT_CONTROL_NULL.
969 */
0b4e3aa0
A
970static void
971ubc_info_free(struct ubc_info *uip)
1c79356b 972{
0c530ab8
A
973 if (IS_VALID_CRED(uip->ui_ucred)) {
974 kauth_cred_unref(&uip->ui_ucred);
1c79356b 975 }
0b4e3aa0 976
0a7de745 977 if (uip->ui_control != MEMORY_OBJECT_CONTROL_NULL) {
0b4e3aa0 978 memory_object_control_deallocate(uip->ui_control);
0a7de745
A
979 }
980
91447636 981 cluster_release(uip);
2d21ac55 982 ubc_cs_free(uip);
0b4e3aa0 983
2d21ac55 984 zfree(ubc_info_zone, uip);
1c79356b
A
985 return;
986}
987
2d21ac55 988
0b4e3aa0
A
989void
990ubc_info_deallocate(struct ubc_info *uip)
991{
0a7de745 992 ubc_info_free(uip);
0b4e3aa0
A
993}
994
0a7de745
A
995errno_t
996mach_to_bsd_errno(kern_return_t mach_err)
fe8ab488
A
997{
998 switch (mach_err) {
999 case KERN_SUCCESS:
1000 return 0;
1001
1002 case KERN_INVALID_ADDRESS:
1003 case KERN_INVALID_ARGUMENT:
1004 case KERN_NOT_IN_SET:
1005 case KERN_INVALID_NAME:
1006 case KERN_INVALID_TASK:
1007 case KERN_INVALID_RIGHT:
1008 case KERN_INVALID_VALUE:
1009 case KERN_INVALID_CAPABILITY:
1010 case KERN_INVALID_HOST:
1011 case KERN_MEMORY_PRESENT:
1012 case KERN_INVALID_PROCESSOR_SET:
1013 case KERN_INVALID_POLICY:
1014 case KERN_ALREADY_WAITING:
1015 case KERN_DEFAULT_SET:
1016 case KERN_EXCEPTION_PROTECTED:
1017 case KERN_INVALID_LEDGER:
1018 case KERN_INVALID_MEMORY_CONTROL:
1019 case KERN_INVALID_SECURITY:
1020 case KERN_NOT_DEPRESSED:
1021 case KERN_LOCK_OWNED:
1022 case KERN_LOCK_OWNED_SELF:
1023 return EINVAL;
1024
1025 case KERN_PROTECTION_FAILURE:
1026 case KERN_NOT_RECEIVER:
1027 case KERN_NO_ACCESS:
1028 case KERN_POLICY_STATIC:
1029 return EACCES;
1030
1031 case KERN_NO_SPACE:
1032 case KERN_RESOURCE_SHORTAGE:
1033 case KERN_UREFS_OVERFLOW:
1034 case KERN_INVALID_OBJECT:
1035 return ENOMEM;
1036
1037 case KERN_FAILURE:
1038 return EIO;
1039
1040 case KERN_MEMORY_FAILURE:
1041 case KERN_POLICY_LIMIT:
1042 case KERN_CODESIGN_ERROR:
1043 return EPERM;
1044
1045 case KERN_MEMORY_ERROR:
1046 return EBUSY;
1047
1048 case KERN_ALREADY_IN_SET:
1049 case KERN_NAME_EXISTS:
1050 case KERN_RIGHT_EXISTS:
1051 return EEXIST;
1052
1053 case KERN_ABORTED:
1054 return EINTR;
1055
1056 case KERN_TERMINATED:
1057 case KERN_LOCK_SET_DESTROYED:
1058 case KERN_LOCK_UNSTABLE:
1059 case KERN_SEMAPHORE_DESTROYED:
1060 return ENOENT;
1061
1062 case KERN_RPC_SERVER_TERMINATED:
1063 return ECONNRESET;
1064
1065 case KERN_NOT_SUPPORTED:
1066 return ENOTSUP;
1067
1068 case KERN_NODE_DOWN:
1069 return ENETDOWN;
1070
1071 case KERN_NOT_WAITING:
1072 return ENOENT;
1073
1074 case KERN_OPERATION_TIMED_OUT:
1075 return ETIMEDOUT;
1076
1077 default:
1078 return EIO;
1079 }
1080}
2d21ac55 1081
1c79356b 1082/*
fe8ab488 1083 * ubc_setsize_ex
2d21ac55 1084 *
fe8ab488 1085 * Tell the VM that the the size of the file represented by the vnode has
2d21ac55
A
1086 * changed
1087 *
fe8ab488
A
1088 * Parameters: vp The vp whose backing file size is
1089 * being changed
1090 * nsize The new size of the backing file
1091 * opts Options
1092 *
1093 * Returns: EINVAL for new size < 0
1094 * ENOENT if no UBC info exists
1095 * EAGAIN if UBC_SETSIZE_NO_FS_REENTRY option is set and new_size < old size
1096 * Other errors (mapped to errno_t) returned by VM functions
1097 *
1098 * Notes: This function will indicate success if the new size is the
1099 * same or larger than the old size (in this case, the
1100 * remainder of the file will require modification or use of
1101 * an existing upl to access successfully).
1102 *
1103 * This function will fail if the new file size is smaller,
1104 * and the memory region being invalidated was unable to
1105 * actually be invalidated and/or the last page could not be
1106 * flushed, if the new size is not aligned to a page
1107 * boundary. This is usually indicative of an I/O error.
1c79356b 1108 */
0a7de745
A
1109errno_t
1110ubc_setsize_ex(struct vnode *vp, off_t nsize, ubc_setsize_opts_t opts)
1c79356b 1111{
0a7de745 1112 off_t osize; /* ui_size before change */
1c79356b
A
1113 off_t lastpg, olastpgend, lastoff;
1114 struct ubc_info *uip;
0b4e3aa0 1115 memory_object_control_t control;
2d21ac55 1116 kern_return_t kret = KERN_SUCCESS;
1c79356b 1117
0a7de745 1118 if (nsize < (off_t)0) {
fe8ab488 1119 return EINVAL;
0a7de745 1120 }
1c79356b 1121
0a7de745 1122 if (!UBCINFOEXISTS(vp)) {
fe8ab488 1123 return ENOENT;
0a7de745 1124 }
1c79356b
A
1125
1126 uip = vp->v_ubcinfo;
2d21ac55 1127 osize = uip->ui_size;
fe8ab488 1128
0a7de745 1129 if (ISSET(opts, UBC_SETSIZE_NO_FS_REENTRY) && nsize < osize) {
fe8ab488 1130 return EAGAIN;
0a7de745 1131 }
fe8ab488 1132
2d21ac55
A
1133 /*
1134 * Update the size before flushing the VM
1135 */
1c79356b
A
1136 uip->ui_size = nsize;
1137
0a7de745 1138 if (nsize >= osize) { /* Nothing more to do */
6d2010ae
A
1139 if (nsize > osize) {
1140 lock_vnode_and_post(vp, NOTE_EXTEND);
1141 }
1142
fe8ab488 1143 return 0;
b0d623f7 1144 }
1c79356b
A
1145
1146 /*
1147 * When the file shrinks, invalidate the pages beyond the
1148 * new size. Also get rid of garbage beyond nsize on the
2d21ac55
A
1149 * last page. The ui_size already has the nsize, so any
1150 * subsequent page-in will zero-fill the tail properly
1c79356b 1151 */
1c79356b
A
1152 lastpg = trunc_page_64(nsize);
1153 olastpgend = round_page_64(osize);
0b4e3aa0
A
1154 control = uip->ui_control;
1155 assert(control);
1c79356b
A
1156 lastoff = (nsize & PAGE_MASK_64);
1157
2d21ac55 1158 if (lastoff) {
0a7de745
A
1159 upl_t upl;
1160 upl_page_info_t *pl;
2d21ac55 1161
fe8ab488 1162 /*
2d21ac55 1163 * new EOF ends up in the middle of a page
fe8ab488 1164 * zero the tail of this page if it's currently
2d21ac55
A
1165 * present in the cache
1166 */
b226f5e5 1167 kret = ubc_create_upl_kernel(vp, lastpg, PAGE_SIZE, &upl, &pl, UPL_SET_LITE | UPL_WILL_MODIFY, VM_KERN_MEMORY_FILE);
fe8ab488 1168
0a7de745
A
1169 if (kret != KERN_SUCCESS) {
1170 panic("ubc_setsize: ubc_create_upl (error = %d)\n", kret);
1171 }
2d21ac55 1172
0a7de745
A
1173 if (upl_valid_page(pl, 0)) {
1174 cluster_zero(upl, (uint32_t)lastoff, PAGE_SIZE - (uint32_t)lastoff, NULL);
1175 }
2d21ac55
A
1176
1177 ubc_upl_abort_range(upl, 0, PAGE_SIZE, UPL_ABORT_FREE_ON_EMPTY);
1c79356b 1178
2d21ac55
A
1179 lastpg += PAGE_SIZE_64;
1180 }
1181 if (olastpgend > lastpg) {
0a7de745 1182 int flags;
b0d623f7 1183
0a7de745 1184 if (lastpg == 0) {
b0d623f7 1185 flags = MEMORY_OBJECT_DATA_FLUSH_ALL;
0a7de745 1186 } else {
b0d623f7 1187 flags = MEMORY_OBJECT_DATA_FLUSH;
0a7de745 1188 }
fe8ab488 1189 /*
2d21ac55
A
1190 * invalidate the pages beyond the new EOF page
1191 *
1192 */
fe8ab488 1193 kret = memory_object_lock_request(control,
0a7de745
A
1194 (memory_object_offset_t)lastpg,
1195 (memory_object_size_t)(olastpgend - lastpg), NULL, NULL,
1196 MEMORY_OBJECT_RETURN_NONE, flags, VM_PROT_NO_CHANGE);
1197 if (kret != KERN_SUCCESS) {
1198 printf("ubc_setsize: invalidate failed (error = %d)\n", kret);
1199 }
2d21ac55 1200 }
fe8ab488 1201 return mach_to_bsd_errno(kret);
1c79356b
A
1202}
1203
fe8ab488 1204// Returns true for success
0a7de745
A
1205int
1206ubc_setsize(vnode_t vp, off_t nsize)
fe8ab488
A
1207{
1208 return ubc_setsize_ex(vp, nsize, 0) == 0;
1209}
2d21ac55 1210
1c79356b 1211/*
2d21ac55
A
1212 * ubc_getsize
1213 *
1214 * Get the size of the file assocated with the specified vnode
1215 *
1216 * Parameters: vp The vnode whose size is of interest
1217 *
1218 * Returns: 0 There is no ubc_info associated with
1219 * this vnode, or the size is zero
1220 * !0 The size of the file
1221 *
1222 * Notes: Using this routine, it is not possible for a caller to
1223 * successfully distinguish between a vnode associate with a zero
1224 * length file, and a vnode with no associated ubc_info. The
1225 * caller therefore needs to not care, or needs to ensure that
1226 * they have previously successfully called ubc_info_init() or
1227 * ubc_info_init_withsize().
1c79356b
A
1228 */
1229off_t
1230ubc_getsize(struct vnode *vp)
1231{
91447636 1232 /* people depend on the side effect of this working this way
0a7de745 1233 * as they call this for directory
1c79356b 1234 */
0a7de745
A
1235 if (!UBCINFOEXISTS(vp)) {
1236 return (off_t)0;
1237 }
1238 return vp->v_ubcinfo->ui_size;
1c79356b
A
1239}
1240
2d21ac55 1241
1c79356b 1242/*
2d21ac55
A
1243 * ubc_umount
1244 *
fe8ab488 1245 * Call ubc_msync(vp, 0, EOF, NULL, UBC_PUSHALL) on all the vnodes for this
2d21ac55
A
1246 * mount point
1247 *
1248 * Parameters: mp The mount point
1249 *
1250 * Returns: 0 Success
1251 *
1252 * Notes: There is no failure indication for this function.
1253 *
1254 * This function is used in the unmount path; since it may block
1255 * I/O indefinitely, it should not be used in the forced unmount
1256 * path, since a device unavailability could also block that
1257 * indefinitely.
1258 *
1259 * Because there is no device ejection interlock on USB, FireWire,
1260 * or similar devices, it's possible that an ejection that begins
1261 * subsequent to the vnode_iterate() completing, either on one of
1262 * those devices, or a network mount for which the server quits
1263 * responding, etc., may cause the caller to block indefinitely.
1c79356b 1264 */
0b4e3aa0 1265__private_extern__ int
1c79356b
A
1266ubc_umount(struct mount *mp)
1267{
91447636 1268 vnode_iterate(mp, 0, ubc_umcallback, 0);
0a7de745 1269 return 0;
1c79356b
A
1270}
1271
2d21ac55
A
1272
1273/*
1274 * ubc_umcallback
1275 *
1276 * Used by ubc_umount() as an internal implementation detail; see ubc_umount()
1277 * and vnode_iterate() for details of implementation.
1278 */
91447636
A
1279static int
1280ubc_umcallback(vnode_t vp, __unused void * args)
1c79356b 1281{
91447636 1282 if (UBCINFOEXISTS(vp)) {
91447636 1283 (void) ubc_msync(vp, (off_t)0, ubc_getsize(vp), NULL, UBC_PUSHALL);
1c79356b 1284 }
0a7de745 1285 return VNODE_RETURNED;
1c79356b
A
1286}
1287
91447636 1288
2d21ac55
A
1289/*
1290 * ubc_getcred
1291 *
1292 * Get the credentials currently active for the ubc_info associated with the
1293 * vnode.
1294 *
1295 * Parameters: vp The vnode whose ubc_info credentials
1296 * are to be retrieved
1297 *
1298 * Returns: !NOCRED The credentials
1299 * NOCRED If there is no ubc_info for the vnode,
1300 * or if there is one, but it has not had
1301 * any credentials associated with it via
1302 * a call to ubc_setcred()
1303 */
91447636 1304kauth_cred_t
1c79356b
A
1305ubc_getcred(struct vnode *vp)
1306{
0a7de745
A
1307 if (UBCINFOEXISTS(vp)) {
1308 return vp->v_ubcinfo->ui_ucred;
1309 }
1c79356b 1310
0a7de745 1311 return NOCRED;
1c79356b
A
1312}
1313
2d21ac55
A
1314
1315/*
1316 * ubc_setthreadcred
1317 *
1318 * If they are not already set, set the credentials of the ubc_info structure
1319 * associated with the vnode to those of the supplied thread; otherwise leave
1320 * them alone.
1321 *
1322 * Parameters: vp The vnode whose ubc_info creds are to
1323 * be set
1324 * p The process whose credentials are to
1325 * be used, if not running on an assumed
1326 * credential
1327 * thread The thread whose credentials are to
1328 * be used
1329 *
1330 * Returns: 1 This vnode has no associated ubc_info
1331 * 0 Success
1332 *
1333 * Notes: This function takes a proc parameter to account for bootstrap
1334 * issues where a task or thread may call this routine, either
1335 * before credentials have been initialized by bsd_init(), or if
1336 * there is no BSD info asscoiate with a mach thread yet. This
1337 * is known to happen in both the initial swap and memory mapping
1338 * calls.
1339 *
1340 * This function is generally used only in the following cases:
1341 *
1342 * o a memory mapped file via the mmap() system call
2d21ac55
A
1343 * o a swap store backing file
1344 * o subsequent to a successful write via vn_write()
1345 *
1346 * The information is then used by the NFS client in order to
1347 * cons up a wire message in either the page-in or page-out path.
1348 *
1349 * There are two potential problems with the use of this API:
1350 *
1351 * o Because the write path only set it on a successful
1352 * write, there is a race window between setting the
1353 * credential and its use to evict the pages to the
1354 * remote file server
1355 *
1356 * o Because a page-in may occur prior to a write, the
1357 * credential may not be set at this time, if the page-in
fe8ab488 1358 * is not the result of a mapping established via mmap().
2d21ac55
A
1359 *
1360 * In both these cases, this will be triggered from the paging
1361 * path, which will instead use the credential of the current
1362 * process, which in this case is either the dynamic_pager or
1363 * the kernel task, both of which utilize "root" credentials.
1364 *
1365 * This may potentially permit operations to occur which should
1366 * be denied, or it may cause to be denied operations which
1367 * should be permitted, depending on the configuration of the NFS
1368 * server.
1369 */
13fec989 1370int
2d21ac55 1371ubc_setthreadcred(struct vnode *vp, proc_t p, thread_t thread)
13fec989
A
1372{
1373 struct ubc_info *uip;
1374 kauth_cred_t credp;
2d21ac55 1375 struct uthread *uthread = get_bsdthread_info(thread);
13fec989 1376
0a7de745
A
1377 if (!UBCINFOEXISTS(vp)) {
1378 return 1;
1379 }
13fec989
A
1380
1381 vnode_lock(vp);
1382
1383 uip = vp->v_ubcinfo;
1384 credp = uip->ui_ucred;
1385
0c530ab8 1386 if (!IS_VALID_CRED(credp)) {
13fec989
A
1387 /* use per-thread cred, if assumed identity, else proc cred */
1388 if (uthread == NULL || (uthread->uu_flag & UT_SETUID) == 0) {
1389 uip->ui_ucred = kauth_cred_proc_ref(p);
1390 } else {
1391 uip->ui_ucred = uthread->uu_ucred;
1392 kauth_cred_ref(uip->ui_ucred);
1393 }
0a7de745 1394 }
13fec989
A
1395 vnode_unlock(vp);
1396
0a7de745 1397 return 0;
13fec989
A
1398}
1399
2d21ac55 1400
1c79356b 1401/*
2d21ac55
A
1402 * ubc_setcred
1403 *
1404 * If they are not already set, set the credentials of the ubc_info structure
1405 * associated with the vnode to those of the process; otherwise leave them
1406 * alone.
1407 *
1408 * Parameters: vp The vnode whose ubc_info creds are to
1409 * be set
1410 * p The process whose credentials are to
1411 * be used
1412 *
1413 * Returns: 0 This vnode has no associated ubc_info
1414 * 1 Success
1415 *
1416 * Notes: The return values for this function are inverted from nearly
1417 * all other uses in the kernel.
1418 *
1419 * See also ubc_setthreadcred(), above.
1420 *
1421 * This function is considered deprecated, and generally should
1422 * not be used, as it is incompatible with per-thread credentials;
1423 * it exists for legacy KPI reasons.
1424 *
0a7de745 1425 * DEPRECATION: ubc_setcred() is being deprecated. Please use
2d21ac55 1426 * ubc_setthreadcred() instead.
1c79356b 1427 */
1c79356b 1428int
2d21ac55 1429ubc_setcred(struct vnode *vp, proc_t p)
1c79356b
A
1430{
1431 struct ubc_info *uip;
91447636 1432 kauth_cred_t credp;
1c79356b 1433
2d21ac55 1434 /* If there is no ubc_info, deny the operation */
0a7de745
A
1435 if (!UBCINFOEXISTS(vp)) {
1436 return 0;
1437 }
1c79356b 1438
2d21ac55
A
1439 /*
1440 * Check to see if there is already a credential reference in the
1441 * ubc_info; if there is not, take one on the supplied credential.
1442 */
91447636 1443 vnode_lock(vp);
91447636 1444 uip = vp->v_ubcinfo;
1c79356b 1445 credp = uip->ui_ucred;
0c530ab8 1446 if (!IS_VALID_CRED(credp)) {
91447636 1447 uip->ui_ucred = kauth_cred_proc_ref(p);
0a7de745 1448 }
91447636 1449 vnode_unlock(vp);
1c79356b 1450
0a7de745 1451 return 1;
1c79356b
A
1452}
1453
2d21ac55
A
1454/*
1455 * ubc_getpager
1456 *
1457 * Get the pager associated with the ubc_info associated with the vnode.
1458 *
1459 * Parameters: vp The vnode to obtain the pager from
1460 *
1461 * Returns: !VNODE_PAGER_NULL The memory_object_t for the pager
1462 * VNODE_PAGER_NULL There is no ubc_info for this vnode
1463 *
1464 * Notes: For each vnode that has a ubc_info associated with it, that
1465 * ubc_info SHALL have a pager associated with it, so in the
1466 * normal case, it's impossible to return VNODE_PAGER_NULL for
1467 * a vnode with an associated ubc_info.
1468 */
0b4e3aa0 1469__private_extern__ memory_object_t
1c79356b
A
1470ubc_getpager(struct vnode *vp)
1471{
0a7de745
A
1472 if (UBCINFOEXISTS(vp)) {
1473 return vp->v_ubcinfo->ui_pager;
1474 }
1c79356b 1475
0a7de745 1476 return 0;
1c79356b
A
1477}
1478
2d21ac55 1479
1c79356b 1480/*
2d21ac55
A
1481 * ubc_getobject
1482 *
1483 * Get the memory object control associated with the ubc_info associated with
1484 * the vnode
1485 *
1486 * Parameters: vp The vnode to obtain the memory object
1487 * from
1488 * flags DEPRECATED
1489 *
1490 * Returns: !MEMORY_OBJECT_CONTROL_NULL
1491 * MEMORY_OBJECT_CONTROL_NULL
1492 *
1493 * Notes: Historically, if the flags were not "do not reactivate", this
1494 * function would look up the memory object using the pager if
1495 * it did not exist (this could be the case if the vnode had
1496 * been previously reactivated). The flags would also permit a
1497 * hold to be requested, which would have created an object
1498 * reference, if one had not already existed. This usage is
1499 * deprecated, as it would permit a race between finding and
1500 * taking the reference vs. a single reference being dropped in
1501 * another thread.
1c79356b 1502 */
0b4e3aa0 1503memory_object_control_t
91447636 1504ubc_getobject(struct vnode *vp, __unused int flags)
1c79356b 1505{
0a7de745
A
1506 if (UBCINFOEXISTS(vp)) {
1507 return vp->v_ubcinfo->ui_control;
1508 }
1c79356b 1509
0a7de745 1510 return MEMORY_OBJECT_CONTROL_NULL;
1c79356b
A
1511}
1512
2d21ac55
A
1513/*
1514 * ubc_blktooff
1515 *
1516 * Convert a given block number to a memory backing object (file) offset for a
1517 * given vnode
1518 *
1519 * Parameters: vp The vnode in which the block is located
1520 * blkno The block number to convert
1521 *
1522 * Returns: !-1 The offset into the backing object
1523 * -1 There is no ubc_info associated with
1524 * the vnode
1525 * -1 An error occurred in the underlying VFS
1526 * while translating the block to an
1527 * offset; the most likely cause is that
1528 * the caller specified a block past the
1529 * end of the file, but this could also be
1530 * any other error from VNOP_BLKTOOFF().
1531 *
1532 * Note: Representing the error in band loses some information, but does
1533 * not occlude a valid offset, since an off_t of -1 is normally
1534 * used to represent EOF. If we had a more reliable constant in
1535 * our header files for it (i.e. explicitly cast to an off_t), we
1536 * would use it here instead.
1537 */
1c79356b 1538off_t
91447636 1539ubc_blktooff(vnode_t vp, daddr64_t blkno)
1c79356b 1540{
2d21ac55 1541 off_t file_offset = -1;
1c79356b
A
1542 int error;
1543
2d21ac55
A
1544 if (UBCINFOEXISTS(vp)) {
1545 error = VNOP_BLKTOOFF(vp, blkno, &file_offset);
0a7de745 1546 if (error) {
2d21ac55 1547 file_offset = -1;
0a7de745 1548 }
2d21ac55 1549 }
1c79356b 1550
0a7de745 1551 return file_offset;
1c79356b 1552}
0b4e3aa0 1553
2d21ac55
A
1554
1555/*
1556 * ubc_offtoblk
1557 *
1558 * Convert a given offset in a memory backing object into a block number for a
1559 * given vnode
1560 *
1561 * Parameters: vp The vnode in which the offset is
1562 * located
1563 * offset The offset into the backing object
1564 *
1565 * Returns: !-1 The returned block number
1566 * -1 There is no ubc_info associated with
1567 * the vnode
1568 * -1 An error occurred in the underlying VFS
1569 * while translating the block to an
1570 * offset; the most likely cause is that
1571 * the caller specified a block past the
1572 * end of the file, but this could also be
1573 * any other error from VNOP_OFFTOBLK().
1574 *
1575 * Note: Representing the error in band loses some information, but does
1576 * not occlude a valid block number, since block numbers exceed
1577 * the valid range for offsets, due to their relative sizes. If
1578 * we had a more reliable constant than -1 in our header files
1579 * for it (i.e. explicitly cast to an daddr64_t), we would use it
1580 * here instead.
1581 */
91447636
A
1582daddr64_t
1583ubc_offtoblk(vnode_t vp, off_t offset)
1c79356b 1584{
2d21ac55 1585 daddr64_t blkno = -1;
0b4e3aa0 1586 int error = 0;
1c79356b 1587
2d21ac55
A
1588 if (UBCINFOEXISTS(vp)) {
1589 error = VNOP_OFFTOBLK(vp, offset, &blkno);
0a7de745 1590 if (error) {
2d21ac55 1591 blkno = -1;
0a7de745 1592 }
2d21ac55 1593 }
1c79356b 1594
0a7de745 1595 return blkno;
1c79356b
A
1596}
1597
2d21ac55
A
1598
1599/*
1600 * ubc_pages_resident
1601 *
1602 * Determine whether or not a given vnode has pages resident via the memory
1603 * object control associated with the ubc_info associated with the vnode
1604 *
1605 * Parameters: vp The vnode we want to know about
1606 *
1607 * Returns: 1 Yes
1608 * 0 No
1609 */
1c79356b 1610int
91447636 1611ubc_pages_resident(vnode_t vp)
1c79356b 1612{
0a7de745
A
1613 kern_return_t kret;
1614 boolean_t has_pages_resident;
1615
1616 if (!UBCINFOEXISTS(vp)) {
1617 return 0;
1618 }
1619
2d21ac55
A
1620 /*
1621 * The following call may fail if an invalid ui_control is specified,
1622 * or if there is no VM object associated with the control object. In
1623 * either case, reacting to it as if there were no pages resident will
1624 * result in correct behavior.
1625 */
91447636 1626 kret = memory_object_pages_resident(vp->v_ubcinfo->ui_control, &has_pages_resident);
0a7de745
A
1627
1628 if (kret != KERN_SUCCESS) {
1629 return 0;
1630 }
1631
1632 if (has_pages_resident == TRUE) {
1633 return 1;
1634 }
1635
1636 return 0;
91447636 1637}
1c79356b 1638
0b4e3aa0 1639/*
2d21ac55
A
1640 * ubc_msync
1641 *
1642 * Clean and/or invalidate a range in the memory object that backs this vnode
1643 *
1644 * Parameters: vp The vnode whose associated ubc_info's
1645 * associated memory object is to have a
1646 * range invalidated within it
1647 * beg_off The start of the range, as an offset
1648 * end_off The end of the range, as an offset
1649 * resid_off The address of an off_t supplied by the
1650 * caller; may be set to NULL to ignore
1651 * flags See ubc_msync_internal()
1652 *
1653 * Returns: 0 Success
1654 * !0 Failure; an errno is returned
1655 *
1656 * Implicit Returns:
1657 * *resid_off, modified If non-NULL, the contents are ALWAYS
1658 * modified; they are initialized to the
1659 * beg_off, and in case of an I/O error,
1660 * the difference between beg_off and the
1661 * current value will reflect what was
1662 * able to be written before the error
1663 * occurred. If no error is returned, the
1664 * value of the resid_off is undefined; do
1665 * NOT use it in place of end_off if you
1666 * intend to increment from the end of the
1667 * last call and call iteratively.
1668 *
1669 * Notes: see ubc_msync_internal() for more detailed information.
1670 *
0b4e3aa0 1671 */
91447636
A
1672errno_t
1673ubc_msync(vnode_t vp, off_t beg_off, off_t end_off, off_t *resid_off, int flags)
0b4e3aa0 1674{
0a7de745 1675 int retval;
91447636 1676 int io_errno = 0;
0b4e3aa0 1677
0a7de745
A
1678 if (resid_off) {
1679 *resid_off = beg_off;
1680 }
1681
1682 retval = ubc_msync_internal(vp, beg_off, end_off, resid_off, flags, &io_errno);
0b4e3aa0 1683
0a7de745
A
1684 if (retval == 0 && io_errno == 0) {
1685 return EINVAL;
1686 }
1687 return io_errno;
91447636 1688}
0b4e3aa0 1689
1c79356b 1690
1c79356b 1691/*
fe8ab488
A
1692 * ubc_msync_internal
1693 *
2d21ac55
A
1694 * Clean and/or invalidate a range in the memory object that backs this vnode
1695 *
1696 * Parameters: vp The vnode whose associated ubc_info's
1697 * associated memory object is to have a
1698 * range invalidated within it
1699 * beg_off The start of the range, as an offset
1700 * end_off The end of the range, as an offset
1701 * resid_off The address of an off_t supplied by the
1702 * caller; may be set to NULL to ignore
1703 * flags MUST contain at least one of the flags
1704 * UBC_INVALIDATE, UBC_PUSHDIRTY, or
1705 * UBC_PUSHALL; if UBC_PUSHDIRTY is used,
1706 * UBC_SYNC may also be specified to cause
1707 * this function to block until the
1708 * operation is complete. The behavior
1709 * of UBC_SYNC is otherwise undefined.
1710 * io_errno The address of an int to contain the
1711 * errno from a failed I/O operation, if
1712 * one occurs; may be set to NULL to
1713 * ignore
1714 *
1715 * Returns: 1 Success
1716 * 0 Failure
1717 *
1718 * Implicit Returns:
1719 * *resid_off, modified The contents of this offset MAY be
1720 * modified; in case of an I/O error, the
1721 * difference between beg_off and the
1722 * current value will reflect what was
1723 * able to be written before the error
1724 * occurred.
1725 * *io_errno, modified The contents of this offset are set to
1726 * an errno, if an error occurs; if the
1727 * caller supplies an io_errno parameter,
1728 * they should be careful to initialize it
1729 * to 0 before calling this function to
1730 * enable them to distinguish an error
1731 * with a valid *resid_off from an invalid
1732 * one, and to avoid potentially falsely
1733 * reporting an error, depending on use.
1734 *
1735 * Notes: If there is no ubc_info associated with the vnode supplied,
1736 * this function immediately returns success.
1737 *
1738 * If the value of end_off is less than or equal to beg_off, this
1739 * function immediately returns success; that is, end_off is NOT
1740 * inclusive.
1741 *
1742 * IMPORTANT: one of the flags UBC_INVALIDATE, UBC_PUSHDIRTY, or
1743 * UBC_PUSHALL MUST be specified; that is, it is NOT possible to
1744 * attempt to block on in-progress I/O by calling this function
1745 * with UBC_PUSHDIRTY, and then later call it with just UBC_SYNC
1746 * in order to block pending on the I/O already in progress.
1747 *
1748 * The start offset is truncated to the page boundary and the
1749 * size is adjusted to include the last page in the range; that
1750 * is, end_off on exactly a page boundary will not change if it
1751 * is rounded, and the range of bytes written will be from the
1752 * truncate beg_off to the rounded (end_off - 1).
1c79356b 1753 */
91447636
A
1754static int
1755ubc_msync_internal(vnode_t vp, off_t beg_off, off_t end_off, off_t *resid_off, int flags, int *io_errno)
1c79356b 1756{
0a7de745
A
1757 memory_object_size_t tsize;
1758 kern_return_t kret;
91447636
A
1759 int request_flags = 0;
1760 int flush_flags = MEMORY_OBJECT_RETURN_NONE;
0a7de745
A
1761
1762 if (!UBCINFOEXISTS(vp)) {
1763 return 0;
1764 }
1765 if ((flags & (UBC_INVALIDATE | UBC_PUSHDIRTY | UBC_PUSHALL)) == 0) {
1766 return 0;
1767 }
1768 if (end_off <= beg_off) {
1769 return 1;
1770 }
1771
1772 if (flags & UBC_INVALIDATE) {
1773 /*
91447636
A
1774 * discard the resident pages
1775 */
1776 request_flags = (MEMORY_OBJECT_DATA_FLUSH | MEMORY_OBJECT_DATA_NO_CHANGE);
0a7de745 1777 }
1c79356b 1778
0a7de745
A
1779 if (flags & UBC_SYNC) {
1780 /*
91447636 1781 * wait for all the I/O to complete before returning
55e303ae 1782 */
0a7de745
A
1783 request_flags |= MEMORY_OBJECT_IO_SYNC;
1784 }
55e303ae 1785
0a7de745
A
1786 if (flags & UBC_PUSHDIRTY) {
1787 /*
91447636
A
1788 * we only return the dirty pages in the range
1789 */
0a7de745
A
1790 flush_flags = MEMORY_OBJECT_RETURN_DIRTY;
1791 }
0b4e3aa0 1792
0a7de745
A
1793 if (flags & UBC_PUSHALL) {
1794 /*
2d21ac55
A
1795 * then return all the interesting pages in the range (both
1796 * dirty and precious) to the pager
91447636 1797 */
0a7de745
A
1798 flush_flags = MEMORY_OBJECT_RETURN_ALL;
1799 }
0b4e3aa0 1800
91447636
A
1801 beg_off = trunc_page_64(beg_off);
1802 end_off = round_page_64(end_off);
1803 tsize = (memory_object_size_t)end_off - beg_off;
b4c24cb9 1804
91447636
A
1805 /* flush and/or invalidate pages in the range requested */
1806 kret = memory_object_lock_request(vp->v_ubcinfo->ui_control,
0a7de745
A
1807 beg_off, tsize,
1808 (memory_object_offset_t *)resid_off,
1809 io_errno, flush_flags, request_flags,
1810 VM_PROT_NO_CHANGE);
1811
1812 return (kret == KERN_SUCCESS) ? 1 : 0;
1c79356b
A
1813}
1814
1c79356b
A
1815
1816/*
fe8ab488 1817 * ubc_map
2d21ac55
A
1818 *
1819 * Explicitly map a vnode that has an associate ubc_info, and add a reference
1820 * to it for the ubc system, if there isn't one already, so it will not be
1821 * recycled while it's in use, and set flags on the ubc_info to indicate that
1822 * we have done this
1823 *
1824 * Parameters: vp The vnode to map
1825 * flags The mapping flags for the vnode; this
1826 * will be a combination of one or more of
1827 * PROT_READ, PROT_WRITE, and PROT_EXEC
1828 *
1829 * Returns: 0 Success
1830 * EPERM Permission was denied
1831 *
1832 * Notes: An I/O reference on the vnode must already be held on entry
1833 *
1834 * If there is no ubc_info associated with the vnode, this function
1835 * will return success.
1836 *
1837 * If a permission error occurs, this function will return
1838 * failure; all other failures will cause this function to return
1839 * success.
1840 *
1841 * IMPORTANT: This is an internal use function, and its symbols
1842 * are not exported, hence its error checking is not very robust.
1843 * It is primarily used by:
1844 *
1845 * o mmap(), when mapping a file
2d21ac55
A
1846 * o When mapping a shared file (a shared library in the
1847 * shared segment region)
1848 * o When loading a program image during the exec process
1849 *
1850 * ...all of these uses ignore the return code, and any fault that
1851 * results later because of a failure is handled in the fix-up path
1852 * of the fault handler. The interface exists primarily as a
1853 * performance hint.
1854 *
1855 * Given that third party implementation of the type of interfaces
1856 * that would use this function, such as alternative executable
1857 * formats, etc., are unsupported, this function is not exported
1858 * for general use.
1859 *
1860 * The extra reference is held until the VM system unmaps the
1861 * vnode from its own context to maintain a vnode reference in
1862 * cases like open()/mmap()/close(), which leave the backing
1863 * object referenced by a mapped memory region in a process
1864 * address space.
1c79356b 1865 */
91447636
A
1866__private_extern__ int
1867ubc_map(vnode_t vp, int flags)
1c79356b
A
1868{
1869 struct ubc_info *uip;
91447636
A
1870 int error = 0;
1871 int need_ref = 0;
2d21ac55 1872 int need_wakeup = 0;
1c79356b 1873
91447636 1874 if (UBCINFOEXISTS(vp)) {
2d21ac55
A
1875 vnode_lock(vp);
1876 uip = vp->v_ubcinfo;
1877
1878 while (ISSET(uip->ui_flags, UI_MAPBUSY)) {
1879 SET(uip->ui_flags, UI_MAPWAITING);
1880 (void) msleep(&uip->ui_flags, &vp->v_lock,
0a7de745 1881 PRIBIO, "ubc_map", NULL);
2d21ac55
A
1882 }
1883 SET(uip->ui_flags, UI_MAPBUSY);
1884 vnode_unlock(vp);
1885
1886 error = VNOP_MMAP(vp, flags, vfs_context_current());
1c79356b 1887
39037602
A
1888 /*
1889 * rdar://problem/22587101 required that we stop propagating
0a7de745 1890 * EPERM up the stack. Otherwise, we would have to funnel up
39037602 1891 * the error at all the call sites for memory_object_map().
0a7de745 1892 * The risk is in having to undo the map/object/entry state at
39037602
A
1893 * all these call sites. It would also affect more than just mmap()
1894 * e.g. vm_remap().
1895 *
1896 * if (error != EPERM)
0a7de745 1897 * error = 0;
39037602
A
1898 */
1899
1900 error = 0;
1c79356b 1901
2d21ac55 1902 vnode_lock_spin(vp);
1c79356b 1903
2d21ac55 1904 if (error == 0) {
0a7de745
A
1905 if (!ISSET(uip->ui_flags, UI_ISMAPPED)) {
1906 need_ref = 1;
1907 }
91447636 1908 SET(uip->ui_flags, (UI_WASMAPPED | UI_ISMAPPED));
22ba694c
A
1909 if (flags & PROT_WRITE) {
1910 SET(uip->ui_flags, UI_MAPPEDWRITE);
1911 }
2d21ac55
A
1912 }
1913 CLR(uip->ui_flags, UI_MAPBUSY);
55e303ae 1914
2d21ac55
A
1915 if (ISSET(uip->ui_flags, UI_MAPWAITING)) {
1916 CLR(uip->ui_flags, UI_MAPWAITING);
1917 need_wakeup = 1;
55e303ae 1918 }
2d21ac55 1919 vnode_unlock(vp);
b4c24cb9 1920
0a7de745 1921 if (need_wakeup) {
2d21ac55 1922 wakeup(&uip->ui_flags);
0a7de745 1923 }
2d21ac55 1924
39037602
A
1925 if (need_ref) {
1926 /*
1927 * Make sure we get a ref as we can't unwind from here
1928 */
0a7de745 1929 if (vnode_ref_ext(vp, 0, VNODE_REF_FORCE)) {
39037602 1930 panic("%s : VNODE_REF_FORCE failed\n", __FUNCTION__);
0a7de745 1931 }
cb323159
A
1932 /*
1933 * Vnodes that are on "unreliable" media (like disk
1934 * images, network filesystems, 3rd-party filesystems,
1935 * and possibly external devices) could see their
1936 * contents be changed via the backing store without
1937 * triggering copy-on-write, so we can't fully rely
1938 * on copy-on-write and might have to resort to
1939 * copy-on-read to protect "privileged" processes and
1940 * prevent privilege escalation.
1941 *
1942 * The root filesystem is considered "reliable" because
1943 * there's not much point in trying to protect
1944 * ourselves from such a vulnerability and the extra
1945 * cost of copy-on-read (CPU time and memory pressure)
1946 * could result in some serious regressions.
1947 */
1948 if (vp->v_mount != NULL &&
1949 ((vp->v_mount->mnt_flag & MNT_ROOTFS) ||
1950 vnode_on_reliable_media(vp))) {
1951 /*
1952 * This vnode is deemed "reliable" so mark
1953 * its VM object as "trusted".
1954 */
1955 memory_object_mark_trusted(uip->ui_control);
1956 } else {
1957// 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);
1958 }
39037602 1959 }
2d21ac55 1960 }
0a7de745 1961 return error;
0b4e3aa0
A
1962}
1963
2d21ac55 1964
0b4e3aa0 1965/*
2d21ac55
A
1966 * ubc_destroy_named
1967 *
1968 * Destroy the named memory object associated with the ubc_info control object
1969 * associated with the designated vnode, if there is a ubc_info associated
1970 * with the vnode, and a control object is associated with it
1971 *
1972 * Parameters: vp The designated vnode
1973 *
1974 * Returns: (void)
1975 *
1976 * Notes: This function is called on vnode termination for all vnodes,
1977 * and must therefore not assume that there is a ubc_info that is
1978 * associated with the vnode, nor that there is a control object
1979 * associated with the ubc_info.
1980 *
1981 * If all the conditions necessary are present, this function
1982 * calls memory_object_destory(), which will in turn end up
1983 * calling ubc_unmap() to release any vnode references that were
1984 * established via ubc_map().
1985 *
1986 * IMPORTANT: This is an internal use function that is used
1987 * exclusively by the internal use function vclean().
0b4e3aa0 1988 */
2d21ac55
A
1989__private_extern__ void
1990ubc_destroy_named(vnode_t vp)
0b4e3aa0
A
1991{
1992 memory_object_control_t control;
0b4e3aa0
A
1993 struct ubc_info *uip;
1994 kern_return_t kret;
1995
2d21ac55 1996 if (UBCINFOEXISTS(vp)) {
0a7de745 1997 uip = vp->v_ubcinfo;
2d21ac55
A
1998
1999 /* Terminate the memory object */
2000 control = ubc_getobject(vp, UBC_HOLDOBJECT);
2001 if (control != MEMORY_OBJECT_CONTROL_NULL) {
0a7de745
A
2002 kret = memory_object_destroy(control, 0);
2003 if (kret != KERN_SUCCESS) {
2004 panic("ubc_destroy_named: memory_object_destroy failed");
2005 }
0b4e3aa0
A
2006 }
2007 }
1c79356b
A
2008}
2009
0b4e3aa0 2010
1c79356b 2011/*
2d21ac55
A
2012 * ubc_isinuse
2013 *
2014 * Determine whether or not a vnode is currently in use by ubc at a level in
2015 * excess of the requested busycount
2016 *
2017 * Parameters: vp The vnode to check
2018 * busycount The threshold busy count, used to bias
2019 * the count usually already held by the
2020 * caller to avoid races
2021 *
2022 * Returns: 1 The vnode is in use over the threshold
2023 * 0 The vnode is not in use over the
2024 * threshold
2025 *
2026 * Notes: Because the vnode is only held locked while actually asking
2027 * the use count, this function only represents a snapshot of the
2028 * current state of the vnode. If more accurate information is
2029 * required, an additional busycount should be held by the caller
2030 * and a non-zero busycount used.
2031 *
2032 * If there is no ubc_info associated with the vnode, this
2033 * function will report that the vnode is not in use by ubc.
1c79356b
A
2034 */
2035int
91447636 2036ubc_isinuse(struct vnode *vp, int busycount)
1c79356b 2037{
0a7de745
A
2038 if (!UBCINFOEXISTS(vp)) {
2039 return 0;
2040 }
2041 return ubc_isinuse_locked(vp, busycount, 0);
1c79356b
A
2042}
2043
91447636 2044
2d21ac55
A
2045/*
2046 * ubc_isinuse_locked
2047 *
2048 * Determine whether or not a vnode is currently in use by ubc at a level in
2049 * excess of the requested busycount
2050 *
2051 * Parameters: vp The vnode to check
2052 * busycount The threshold busy count, used to bias
2053 * the count usually already held by the
2054 * caller to avoid races
2055 * locked True if the vnode is already locked by
2056 * the caller
2057 *
2058 * Returns: 1 The vnode is in use over the threshold
2059 * 0 The vnode is not in use over the
2060 * threshold
2061 *
2062 * Notes: If the vnode is not locked on entry, it is locked while
2063 * actually asking the use count. If this is the case, this
2064 * function only represents a snapshot of the current state of
2065 * the vnode. If more accurate information is required, the
2066 * vnode lock should be held by the caller, otherwise an
2067 * additional busycount should be held by the caller and a
2068 * non-zero busycount used.
2069 *
2070 * If there is no ubc_info associated with the vnode, this
2071 * function will report that the vnode is not in use by ubc.
2072 */
1c79356b 2073int
91447636 2074ubc_isinuse_locked(struct vnode *vp, int busycount, int locked)
1c79356b 2075{
91447636 2076 int retval = 0;
1c79356b 2077
9bccf70c 2078
0a7de745 2079 if (!locked) {
b0d623f7 2080 vnode_lock_spin(vp);
0a7de745 2081 }
1c79356b 2082
0a7de745 2083 if ((vp->v_usecount - vp->v_kusecount) > busycount) {
91447636 2084 retval = 1;
0a7de745 2085 }
91447636 2086
0a7de745 2087 if (!locked) {
91447636 2088 vnode_unlock(vp);
0a7de745
A
2089 }
2090 return retval;
1c79356b
A
2091}
2092
91447636 2093
1c79356b 2094/*
2d21ac55
A
2095 * ubc_unmap
2096 *
2097 * Reverse the effects of a ubc_map() call for a given vnode
2098 *
2099 * Parameters: vp vnode to unmap from ubc
2100 *
2101 * Returns: (void)
2102 *
2103 * Notes: This is an internal use function used by vnode_pager_unmap().
2104 * It will attempt to obtain a reference on the supplied vnode,
2105 * and if it can do so, and there is an associated ubc_info, and
2106 * the flags indicate that it was mapped via ubc_map(), then the
2107 * flag is cleared, the mapping removed, and the reference taken
2108 * by ubc_map() is released.
2109 *
2110 * IMPORTANT: This MUST only be called by the VM
2111 * to prevent race conditions.
1c79356b 2112 */
0b4e3aa0 2113__private_extern__ void
1c79356b
A
2114ubc_unmap(struct vnode *vp)
2115{
2116 struct ubc_info *uip;
0a7de745
A
2117 int need_rele = 0;
2118 int need_wakeup = 0;
b0d623f7 2119
0a7de745
A
2120 if (vnode_getwithref(vp)) {
2121 return;
2122 }
1c79356b 2123
91447636 2124 if (UBCINFOEXISTS(vp)) {
fe8ab488
A
2125 bool want_fsevent = false;
2126
91447636 2127 vnode_lock(vp);
91447636 2128 uip = vp->v_ubcinfo;
2d21ac55
A
2129
2130 while (ISSET(uip->ui_flags, UI_MAPBUSY)) {
2131 SET(uip->ui_flags, UI_MAPWAITING);
2132 (void) msleep(&uip->ui_flags, &vp->v_lock,
0a7de745 2133 PRIBIO, "ubc_unmap", NULL);
2d21ac55
A
2134 }
2135 SET(uip->ui_flags, UI_MAPBUSY);
2136
91447636 2137 if (ISSET(uip->ui_flags, UI_ISMAPPED)) {
0a7de745 2138 if (ISSET(uip->ui_flags, UI_MAPPEDWRITE)) {
fe8ab488 2139 want_fsevent = true;
0a7de745 2140 }
fe8ab488 2141
91447636 2142 need_rele = 1;
fe8ab488
A
2143
2144 /*
2145 * We want to clear the mapped flags after we've called
2146 * VNOP_MNOMAP to avoid certain races and allow
2147 * VNOP_MNOMAP to call ubc_is_mapped_writable.
2148 */
91447636
A
2149 }
2150 vnode_unlock(vp);
fe8ab488 2151
91447636 2152 if (need_rele) {
0a7de745 2153 vfs_context_t ctx = vfs_context_current();
fe8ab488 2154
0a7de745 2155 (void)VNOP_MNOMAP(vp, ctx);
fe8ab488
A
2156
2157#if CONFIG_FSE
0a7de745
A
2158 /*
2159 * Why do we want an fsevent here? Normally the
2160 * content modified fsevent is posted when a file is
2161 * closed and only if it's written to via conventional
2162 * means. It's perfectly legal to close a file and
2163 * keep your mappings and we don't currently track
2164 * whether it was written to via a mapping.
2165 * Therefore, we need to post an fsevent here if the
2166 * file was mapped writable. This may result in false
2167 * events, i.e. we post a notification when nothing
2168 * has really changed.
2169 */
2170 if (want_fsevent && need_fsevent(FSE_CONTENT_MODIFIED, vp)) {
2171 add_fsevent(FSE_CONTENT_MODIFIED, ctx,
2172 FSE_ARG_VNODE, vp,
2173 FSE_ARG_DONE);
2174 }
fe8ab488
A
2175#endif
2176
0a7de745 2177 vnode_rele(vp);
91447636 2178 }
2d21ac55
A
2179
2180 vnode_lock_spin(vp);
2181
0a7de745 2182 if (need_rele) {
fe8ab488 2183 CLR(uip->ui_flags, UI_ISMAPPED | UI_MAPPEDWRITE);
0a7de745 2184 }
fe8ab488 2185
2d21ac55 2186 CLR(uip->ui_flags, UI_MAPBUSY);
fe8ab488 2187
2d21ac55
A
2188 if (ISSET(uip->ui_flags, UI_MAPWAITING)) {
2189 CLR(uip->ui_flags, UI_MAPWAITING);
2190 need_wakeup = 1;
2191 }
2192 vnode_unlock(vp);
2193
0a7de745
A
2194 if (need_wakeup) {
2195 wakeup(&uip->ui_flags);
2196 }
91447636
A
2197 }
2198 /*
2199 * the drop of the vnode ref will cleanup
2200 */
2201 vnode_put(vp);
0b4e3aa0
A
2202}
2203
2d21ac55
A
2204
2205/*
2206 * ubc_page_op
2207 *
2208 * Manipulate individual page state for a vnode with an associated ubc_info
2209 * with an associated memory object control.
2210 *
2211 * Parameters: vp The vnode backing the page
2212 * f_offset A file offset interior to the page
2213 * ops The operations to perform, as a bitmap
2214 * (see below for more information)
2215 * phys_entryp The address of a ppnum_t; may be NULL
2216 * to ignore
2217 * flagsp A pointer to an int to contain flags;
2218 * may be NULL to ignore
2219 *
2220 * Returns: KERN_SUCCESS Success
2221 * KERN_INVALID_ARGUMENT If the memory object control has no VM
2222 * object associated
2223 * KERN_INVALID_OBJECT If UPL_POP_PHYSICAL and the object is
2224 * not physically contiguous
2225 * KERN_INVALID_OBJECT If !UPL_POP_PHYSICAL and the object is
2226 * physically contiguous
2227 * KERN_FAILURE If the page cannot be looked up
2228 *
2229 * Implicit Returns:
2230 * *phys_entryp (modified) If phys_entryp is non-NULL and
2231 * UPL_POP_PHYSICAL
2232 * *flagsp (modified) If flagsp is non-NULL and there was
2233 * !UPL_POP_PHYSICAL and a KERN_SUCCESS
2234 *
2235 * Notes: For object boundaries, it is considerably more efficient to
2236 * ensure that f_offset is in fact on a page boundary, as this
2237 * will avoid internal use of the hash table to identify the
2238 * page, and would therefore skip a number of early optimizations.
2239 * Since this is a page operation anyway, the caller should try
2240 * to pass only a page aligned offset because of this.
2241 *
2242 * *flagsp may be modified even if this function fails. If it is
2243 * modified, it will contain the condition of the page before the
2244 * requested operation was attempted; these will only include the
2245 * bitmap flags, and not the PL_POP_PHYSICAL, UPL_POP_DUMP,
2246 * UPL_POP_SET, or UPL_POP_CLR bits.
2247 *
2248 * The flags field may contain a specific operation, such as
2249 * UPL_POP_PHYSICAL or UPL_POP_DUMP:
2250 *
2251 * o UPL_POP_PHYSICAL Fail if not contiguous; if
2252 * *phys_entryp and successful, set
2253 * *phys_entryp
2254 * o UPL_POP_DUMP Dump the specified page
2255 *
2256 * Otherwise, it is treated as a bitmap of one or more page
2257 * operations to perform on the final memory object; allowable
2258 * bit values are:
2259 *
2260 * o UPL_POP_DIRTY The page is dirty
2261 * o UPL_POP_PAGEOUT The page is paged out
2262 * o UPL_POP_PRECIOUS The page is precious
2263 * o UPL_POP_ABSENT The page is absent
2264 * o UPL_POP_BUSY The page is busy
2265 *
2266 * If the page status is only being queried and not modified, then
2267 * not other bits should be specified. However, if it is being
2268 * modified, exactly ONE of the following bits should be set:
2269 *
2270 * o UPL_POP_SET Set the current bitmap bits
2271 * o UPL_POP_CLR Clear the current bitmap bits
2272 *
2273 * Thus to effect a combination of setting an clearing, it may be
2274 * necessary to call this function twice. If this is done, the
2275 * set should be used before the clear, since clearing may trigger
2276 * a wakeup on the destination page, and if the page is backed by
2277 * an encrypted swap file, setting will trigger the decryption
2278 * needed before the wakeup occurs.
2279 */
0b4e3aa0
A
2280kern_return_t
2281ubc_page_op(
0a7de745
A
2282 struct vnode *vp,
2283 off_t f_offset,
2284 int ops,
2285 ppnum_t *phys_entryp,
2286 int *flagsp)
0b4e3aa0 2287{
0a7de745 2288 memory_object_control_t control;
0b4e3aa0
A
2289
2290 control = ubc_getobject(vp, UBC_FLAGS_NONE);
0a7de745 2291 if (control == MEMORY_OBJECT_CONTROL_NULL) {
0b4e3aa0 2292 return KERN_INVALID_ARGUMENT;
0a7de745 2293 }
0b4e3aa0 2294
0a7de745
A
2295 return memory_object_page_op(control,
2296 (memory_object_offset_t)f_offset,
2297 ops,
2298 phys_entryp,
2299 flagsp);
0b4e3aa0 2300}
2d21ac55
A
2301
2302
2303/*
2304 * ubc_range_op
2305 *
2306 * Manipulate page state for a range of memory for a vnode with an associated
2307 * ubc_info with an associated memory object control, when page level state is
2308 * not required to be returned from the call (i.e. there are no phys_entryp or
2309 * flagsp parameters to this call, and it takes a range which may contain
2310 * multiple pages, rather than an offset interior to a single page).
2311 *
2312 * Parameters: vp The vnode backing the page
2313 * f_offset_beg A file offset interior to the start page
2314 * f_offset_end A file offset interior to the end page
2315 * ops The operations to perform, as a bitmap
2316 * (see below for more information)
2317 * range The address of an int; may be NULL to
2318 * ignore
2319 *
2320 * Returns: KERN_SUCCESS Success
2321 * KERN_INVALID_ARGUMENT If the memory object control has no VM
2322 * object associated
2323 * KERN_INVALID_OBJECT If the object is physically contiguous
2324 *
2325 * Implicit Returns:
2326 * *range (modified) If range is non-NULL, its contents will
2327 * be modified to contain the number of
2328 * bytes successfully operated upon.
2329 *
2330 * Notes: IMPORTANT: This function cannot be used on a range that
2331 * consists of physically contiguous pages.
2332 *
2333 * For object boundaries, it is considerably more efficient to
2334 * ensure that f_offset_beg and f_offset_end are in fact on page
2335 * boundaries, as this will avoid internal use of the hash table
2336 * to identify the page, and would therefore skip a number of
2337 * early optimizations. Since this is an operation on a set of
2338 * pages anyway, the caller should try to pass only a page aligned
2339 * offsets because of this.
2340 *
2341 * *range will be modified only if this function succeeds.
2342 *
2343 * The flags field MUST contain a specific operation; allowable
2344 * values are:
2345 *
2346 * o UPL_ROP_ABSENT Returns the extent of the range
2347 * presented which is absent, starting
2348 * with the start address presented
2349 *
2350 * o UPL_ROP_PRESENT Returns the extent of the range
2351 * presented which is present (resident),
2352 * starting with the start address
2353 * presented
2354 * o UPL_ROP_DUMP Dump the pages which are found in the
2355 * target object for the target range.
2356 *
2357 * IMPORTANT: For UPL_ROP_ABSENT and UPL_ROP_PRESENT; if there are
2358 * multiple regions in the range, only the first matching region
2359 * is returned.
2360 */
55e303ae
A
2361kern_return_t
2362ubc_range_op(
0a7de745
A
2363 struct vnode *vp,
2364 off_t f_offset_beg,
2365 off_t f_offset_end,
55e303ae
A
2366 int ops,
2367 int *range)
2368{
0a7de745 2369 memory_object_control_t control;
55e303ae
A
2370
2371 control = ubc_getobject(vp, UBC_FLAGS_NONE);
0a7de745 2372 if (control == MEMORY_OBJECT_CONTROL_NULL) {
55e303ae 2373 return KERN_INVALID_ARGUMENT;
0a7de745 2374 }
55e303ae 2375
0a7de745
A
2376 return memory_object_range_op(control,
2377 (memory_object_offset_t)f_offset_beg,
2378 (memory_object_offset_t)f_offset_end,
2379 ops,
2380 range);
55e303ae 2381}
2d21ac55
A
2382
2383
2384/*
2385 * ubc_create_upl
2386 *
2387 * Given a vnode, cause the population of a portion of the vm_object; based on
2388 * the nature of the request, the pages returned may contain valid data, or
2389 * they may be uninitialized.
2390 *
2391 * Parameters: vp The vnode from which to create the upl
2392 * f_offset The start offset into the backing store
2393 * represented by the vnode
2394 * bufsize The size of the upl to create
2395 * uplp Pointer to the upl_t to receive the
2396 * created upl; MUST NOT be NULL
2397 * plp Pointer to receive the internal page
2398 * list for the created upl; MAY be NULL
2399 * to ignore
2400 *
2401 * Returns: KERN_SUCCESS The requested upl has been created
2402 * KERN_INVALID_ARGUMENT The bufsize argument is not an even
2403 * multiple of the page size
2404 * KERN_INVALID_ARGUMENT There is no ubc_info associated with
2405 * the vnode, or there is no memory object
0a7de745 2406 * control associated with the ubc_info
2d21ac55
A
2407 * memory_object_upl_request:KERN_INVALID_VALUE
2408 * The supplied upl_flags argument is
2409 * invalid
2410 * Implicit Returns:
0a7de745 2411 * *uplp (modified)
2d21ac55
A
2412 * *plp (modified) If non-NULL, the value of *plp will be
2413 * modified to point to the internal page
2414 * list; this modification may occur even
2415 * if this function is unsuccessful, in
2416 * which case the contents may be invalid
2417 *
2418 * Note: If successful, the returned *uplp MUST subsequently be freed
2419 * via a call to ubc_upl_commit(), ubc_upl_commit_range(),
2420 * ubc_upl_abort(), or ubc_upl_abort_range().
2421 */
0b4e3aa0 2422kern_return_t
5ba3f43e 2423ubc_create_upl_external(
0a7de745
A
2424 struct vnode *vp,
2425 off_t f_offset,
2426 int bufsize,
2427 upl_t *uplp,
2428 upl_page_info_t **plp,
2429 int uplflags)
5ba3f43e 2430{
0a7de745 2431 return ubc_create_upl_kernel(vp, f_offset, bufsize, uplp, plp, uplflags, vm_tag_bt());
5ba3f43e
A
2432}
2433
2434kern_return_t
2435ubc_create_upl_kernel(
0a7de745
A
2436 struct vnode *vp,
2437 off_t f_offset,
2438 int bufsize,
2439 upl_t *uplp,
2440 upl_page_info_t **plp,
2441 int uplflags,
5ba3f43e 2442 vm_tag_t tag)
0b4e3aa0 2443{
0a7de745
A
2444 memory_object_control_t control;
2445 kern_return_t kr;
b0d623f7 2446
0a7de745 2447 if (plp != NULL) {
b0d623f7 2448 *plp = NULL;
0a7de745 2449 }
b0d623f7 2450 *uplp = NULL;
0a7de745
A
2451
2452 if (bufsize & 0xfff) {
0b4e3aa0 2453 return KERN_INVALID_ARGUMENT;
0a7de745 2454 }
0b4e3aa0 2455
0a7de745 2456 if (bufsize > MAX_UPL_SIZE_BYTES) {
6d2010ae 2457 return KERN_INVALID_ARGUMENT;
0a7de745 2458 }
6d2010ae 2459
b0d623f7 2460 if (uplflags & (UPL_UBC_MSYNC | UPL_UBC_PAGEOUT | UPL_UBC_PAGEIN)) {
b0d623f7
A
2461 if (uplflags & UPL_UBC_MSYNC) {
2462 uplflags &= UPL_RET_ONLY_DIRTY;
2463
2464 uplflags |= UPL_COPYOUT_FROM | UPL_CLEAN_IN_PLACE |
0a7de745 2465 UPL_SET_INTERNAL | UPL_SET_LITE;
b0d623f7
A
2466 } else if (uplflags & UPL_UBC_PAGEOUT) {
2467 uplflags &= UPL_RET_ONLY_DIRTY;
2468
0a7de745 2469 if (uplflags & UPL_RET_ONLY_DIRTY) {
b0d623f7 2470 uplflags |= UPL_NOBLOCK;
0a7de745 2471 }
b0d623f7
A
2472
2473 uplflags |= UPL_FOR_PAGEOUT | UPL_CLEAN_IN_PLACE |
0a7de745 2474 UPL_COPYOUT_FROM | UPL_SET_INTERNAL | UPL_SET_LITE;
b0d623f7 2475 } else {
316670eb 2476 uplflags |= UPL_RET_ONLY_ABSENT |
0a7de745
A
2477 UPL_NO_SYNC | UPL_CLEAN_IN_PLACE |
2478 UPL_SET_INTERNAL | UPL_SET_LITE;
316670eb
A
2479
2480 /*
2481 * if the requested size == PAGE_SIZE, we don't want to set
2482 * the UPL_NOBLOCK since we may be trying to recover from a
2483 * previous partial pagein I/O that occurred because we were low
2484 * on memory and bailed early in order to honor the UPL_NOBLOCK...
2485 * since we're only asking for a single page, we can block w/o fear
2486 * of tying up pages while waiting for more to become available
2487 */
0a7de745 2488 if (bufsize > PAGE_SIZE) {
316670eb 2489 uplflags |= UPL_NOBLOCK;
0a7de745 2490 }
b0d623f7
A
2491 }
2492 } else {
55e303ae 2493 uplflags &= ~UPL_FOR_PAGEOUT;
55e303ae 2494
b0d623f7
A
2495 if (uplflags & UPL_WILL_BE_DUMPED) {
2496 uplflags &= ~UPL_WILL_BE_DUMPED;
0a7de745
A
2497 uplflags |= (UPL_NO_SYNC | UPL_SET_INTERNAL);
2498 } else {
2499 uplflags |= (UPL_NO_SYNC | UPL_CLEAN_IN_PLACE | UPL_SET_INTERNAL);
2500 }
b0d623f7
A
2501 }
2502 control = ubc_getobject(vp, UBC_FLAGS_NONE);
0a7de745 2503 if (control == MEMORY_OBJECT_CONTROL_NULL) {
0b4e3aa0 2504 return KERN_INVALID_ARGUMENT;
0a7de745 2505 }
0b4e3aa0 2506
5ba3f43e 2507 kr = memory_object_upl_request(control, f_offset, bufsize, uplp, NULL, NULL, uplflags, tag);
0a7de745 2508 if (kr == KERN_SUCCESS && plp != NULL) {
b0d623f7 2509 *plp = UPL_GET_INTERNAL_PAGE_LIST(*uplp);
0a7de745 2510 }
0b4e3aa0
A
2511 return kr;
2512}
0a7de745
A
2513
2514
2d21ac55
A
2515/*
2516 * ubc_upl_maxbufsize
2517 *
2518 * Return the maximum bufsize ubc_create_upl( ) will take.
2519 *
2520 * Parameters: none
2521 *
2522 * Returns: maximum size buffer (in bytes) ubc_create_upl( ) will take.
2523 */
0a7de745 2524upl_size_t
2d21ac55
A
2525ubc_upl_maxbufsize(
2526 void)
2527{
0a7de745 2528 return MAX_UPL_SIZE_BYTES;
2d21ac55 2529}
0b4e3aa0 2530
2d21ac55
A
2531/*
2532 * ubc_upl_map
2533 *
2534 * Map the page list assocated with the supplied upl into the kernel virtual
2535 * address space at the virtual address indicated by the dst_addr argument;
2536 * the entire upl is mapped
2537 *
2538 * Parameters: upl The upl to map
2539 * dst_addr The address at which to map the upl
2540 *
2541 * Returns: KERN_SUCCESS The upl has been mapped
2542 * KERN_INVALID_ARGUMENT The upl is UPL_NULL
2543 * KERN_FAILURE The upl is already mapped
2544 * vm_map_enter:KERN_INVALID_ARGUMENT
2545 * A failure code from vm_map_enter() due
2546 * to an invalid argument
2547 */
0b4e3aa0
A
2548kern_return_t
2549ubc_upl_map(
0a7de745
A
2550 upl_t upl,
2551 vm_offset_t *dst_addr)
0b4e3aa0 2552{
0a7de745 2553 return vm_upl_map(kernel_map, upl, dst_addr);
0b4e3aa0
A
2554}
2555
2556
2d21ac55
A
2557/*
2558 * ubc_upl_unmap
2559 *
2560 * Unmap the page list assocated with the supplied upl from the kernel virtual
2561 * address space; the entire upl is unmapped.
2562 *
2563 * Parameters: upl The upl to unmap
2564 *
2565 * Returns: KERN_SUCCESS The upl has been unmapped
2566 * KERN_FAILURE The upl is not currently mapped
2567 * KERN_INVALID_ARGUMENT If the upl is UPL_NULL
2568 */
0b4e3aa0
A
2569kern_return_t
2570ubc_upl_unmap(
0a7de745 2571 upl_t upl)
0b4e3aa0 2572{
0a7de745 2573 return vm_upl_unmap(kernel_map, upl);
0b4e3aa0
A
2574}
2575
2d21ac55
A
2576
2577/*
2578 * ubc_upl_commit
2579 *
2580 * Commit the contents of the upl to the backing store
2581 *
2582 * Parameters: upl The upl to commit
2583 *
2584 * Returns: KERN_SUCCESS The upl has been committed
2585 * KERN_INVALID_ARGUMENT The supplied upl was UPL_NULL
2586 * KERN_FAILURE The supplied upl does not represent
2587 * device memory, and the offset plus the
2588 * size would exceed the actual size of
2589 * the upl
2590 *
2591 * Notes: In practice, the only return value for this function should be
2592 * KERN_SUCCESS, unless there has been data structure corruption;
2593 * since the upl is deallocated regardless of success or failure,
2594 * there's really nothing to do about this other than panic.
2595 *
2596 * IMPORTANT: Use of this function should not be mixed with use of
2597 * ubc_upl_commit_range(), due to the unconditional deallocation
2598 * by this function.
2599 */
0b4e3aa0
A
2600kern_return_t
2601ubc_upl_commit(
0a7de745 2602 upl_t upl)
0b4e3aa0 2603{
0a7de745
A
2604 upl_page_info_t *pl;
2605 kern_return_t kr;
0b4e3aa0
A
2606
2607 pl = UPL_GET_INTERNAL_PAGE_LIST(upl);
fe8ab488 2608 kr = upl_commit(upl, pl, MAX_UPL_SIZE_BYTES >> PAGE_SHIFT);
0b4e3aa0
A
2609 upl_deallocate(upl);
2610 return kr;
1c79356b
A
2611}
2612
0b4e3aa0 2613
2d21ac55
A
2614/*
2615 * ubc_upl_commit
2616 *
2617 * Commit the contents of the specified range of the upl to the backing store
2618 *
2619 * Parameters: upl The upl to commit
2620 * offset The offset into the upl
2621 * size The size of the region to be committed,
2622 * starting at the specified offset
2623 * flags commit type (see below)
2624 *
2625 * Returns: KERN_SUCCESS The range has been committed
2626 * KERN_INVALID_ARGUMENT The supplied upl was UPL_NULL
2627 * KERN_FAILURE The supplied upl does not represent
2628 * device memory, and the offset plus the
2629 * size would exceed the actual size of
2630 * the upl
2631 *
2632 * Notes: IMPORTANT: If the commit is successful, and the object is now
2633 * empty, the upl will be deallocated. Since the caller cannot
2634 * check that this is the case, the UPL_COMMIT_FREE_ON_EMPTY flag
2635 * should generally only be used when the offset is 0 and the size
2636 * is equal to the upl size.
2637 *
2638 * The flags argument is a bitmap of flags on the rage of pages in
2639 * the upl to be committed; allowable flags are:
2640 *
2641 * o UPL_COMMIT_FREE_ON_EMPTY Free the upl when it is
2642 * both empty and has been
2643 * successfully committed
2644 * o UPL_COMMIT_CLEAR_DIRTY Clear each pages dirty
2645 * bit; will prevent a
2646 * later pageout
2647 * o UPL_COMMIT_SET_DIRTY Set each pages dirty
2648 * bit; will cause a later
2649 * pageout
2650 * o UPL_COMMIT_INACTIVATE Clear each pages
2651 * reference bit; the page
2652 * will not be accessed
2653 * o UPL_COMMIT_ALLOW_ACCESS Unbusy each page; pages
2654 * become busy when an
2655 * IOMemoryDescriptor is
2656 * mapped or redirected,
2657 * and we have to wait for
2658 * an IOKit driver
2659 *
2660 * The flag UPL_COMMIT_NOTIFY_EMPTY is used internally, and should
2661 * not be specified by the caller.
2662 *
2663 * The UPL_COMMIT_CLEAR_DIRTY and UPL_COMMIT_SET_DIRTY flags are
2664 * mutually exclusive, and should not be combined.
2665 */
0b4e3aa0
A
2666kern_return_t
2667ubc_upl_commit_range(
0a7de745
A
2668 upl_t upl,
2669 upl_offset_t offset,
2670 upl_size_t size,
2671 int flags)
0b4e3aa0 2672{
0a7de745
A
2673 upl_page_info_t *pl;
2674 boolean_t empty;
2675 kern_return_t kr;
0b4e3aa0 2676
0a7de745 2677 if (flags & UPL_COMMIT_FREE_ON_EMPTY) {
0b4e3aa0 2678 flags |= UPL_COMMIT_NOTIFY_EMPTY;
0a7de745 2679 }
0b4e3aa0 2680
593a1d5f
A
2681 if (flags & UPL_COMMIT_KERNEL_ONLY_FLAGS) {
2682 return KERN_INVALID_ARGUMENT;
2683 }
2684
0b4e3aa0
A
2685 pl = UPL_GET_INTERNAL_PAGE_LIST(upl);
2686
2687 kr = upl_commit_range(upl, offset, size, flags,
0a7de745 2688 pl, MAX_UPL_SIZE_BYTES >> PAGE_SHIFT, &empty);
0b4e3aa0 2689
0a7de745 2690 if ((flags & UPL_COMMIT_FREE_ON_EMPTY) && empty) {
0b4e3aa0 2691 upl_deallocate(upl);
0a7de745 2692 }
0b4e3aa0
A
2693
2694 return kr;
2695}
2d21ac55
A
2696
2697
2698/*
2699 * ubc_upl_abort_range
2700 *
2701 * Abort the contents of the specified range of the specified upl
2702 *
2703 * Parameters: upl The upl to abort
2704 * offset The offset into the upl
2705 * size The size of the region to be aborted,
2706 * starting at the specified offset
2707 * abort_flags abort type (see below)
2708 *
2709 * Returns: KERN_SUCCESS The range has been aborted
2710 * KERN_INVALID_ARGUMENT The supplied upl was UPL_NULL
2711 * KERN_FAILURE The supplied upl does not represent
2712 * device memory, and the offset plus the
2713 * size would exceed the actual size of
2714 * the upl
2715 *
2716 * Notes: IMPORTANT: If the abort is successful, and the object is now
2717 * empty, the upl will be deallocated. Since the caller cannot
2718 * check that this is the case, the UPL_ABORT_FREE_ON_EMPTY flag
2719 * should generally only be used when the offset is 0 and the size
2720 * is equal to the upl size.
2721 *
2722 * The abort_flags argument is a bitmap of flags on the range of
2723 * pages in the upl to be aborted; allowable flags are:
2724 *
2725 * o UPL_ABORT_FREE_ON_EMPTY Free the upl when it is both
2726 * empty and has been successfully
2727 * aborted
2728 * o UPL_ABORT_RESTART The operation must be restarted
2729 * o UPL_ABORT_UNAVAILABLE The pages are unavailable
2730 * o UPL_ABORT_ERROR An I/O error occurred
2731 * o UPL_ABORT_DUMP_PAGES Just free the pages
2732 * o UPL_ABORT_NOTIFY_EMPTY RESERVED
2733 * o UPL_ABORT_ALLOW_ACCESS RESERVED
2734 *
2735 * The UPL_ABORT_NOTIFY_EMPTY is an internal use flag and should
2736 * not be specified by the caller. It is intended to fulfill the
2737 * same role as UPL_COMMIT_NOTIFY_EMPTY does in the function
2738 * ubc_upl_commit_range(), but is never referenced internally.
2739 *
2740 * The UPL_ABORT_ALLOW_ACCESS is defined, but neither set nor
2741 * referenced; do not use it.
2742 */
0b4e3aa0
A
2743kern_return_t
2744ubc_upl_abort_range(
0a7de745
A
2745 upl_t upl,
2746 upl_offset_t offset,
2747 upl_size_t size,
2748 int abort_flags)
0b4e3aa0 2749{
0a7de745
A
2750 kern_return_t kr;
2751 boolean_t empty = FALSE;
0b4e3aa0 2752
0a7de745 2753 if (abort_flags & UPL_ABORT_FREE_ON_EMPTY) {
0b4e3aa0 2754 abort_flags |= UPL_ABORT_NOTIFY_EMPTY;
0a7de745 2755 }
0b4e3aa0
A
2756
2757 kr = upl_abort_range(upl, offset, size, abort_flags, &empty);
2758
0a7de745 2759 if ((abort_flags & UPL_ABORT_FREE_ON_EMPTY) && empty) {
0b4e3aa0 2760 upl_deallocate(upl);
0a7de745 2761 }
0b4e3aa0
A
2762
2763 return kr;
2764}
2765
2d21ac55
A
2766
2767/*
2768 * ubc_upl_abort
2769 *
2770 * Abort the contents of the specified upl
2771 *
2772 * Parameters: upl The upl to abort
2773 * abort_type abort type (see below)
2774 *
2775 * Returns: KERN_SUCCESS The range has been aborted
2776 * KERN_INVALID_ARGUMENT The supplied upl was UPL_NULL
2777 * KERN_FAILURE The supplied upl does not represent
2778 * device memory, and the offset plus the
2779 * size would exceed the actual size of
2780 * the upl
2781 *
2782 * Notes: IMPORTANT: If the abort is successful, and the object is now
2783 * empty, the upl will be deallocated. Since the caller cannot
2784 * check that this is the case, the UPL_ABORT_FREE_ON_EMPTY flag
2785 * should generally only be used when the offset is 0 and the size
2786 * is equal to the upl size.
2787 *
2788 * The abort_type is a bitmap of flags on the range of
2789 * pages in the upl to be aborted; allowable flags are:
2790 *
2791 * o UPL_ABORT_FREE_ON_EMPTY Free the upl when it is both
2792 * empty and has been successfully
2793 * aborted
2794 * o UPL_ABORT_RESTART The operation must be restarted
2795 * o UPL_ABORT_UNAVAILABLE The pages are unavailable
2796 * o UPL_ABORT_ERROR An I/O error occurred
2797 * o UPL_ABORT_DUMP_PAGES Just free the pages
2798 * o UPL_ABORT_NOTIFY_EMPTY RESERVED
2799 * o UPL_ABORT_ALLOW_ACCESS RESERVED
2800 *
2801 * The UPL_ABORT_NOTIFY_EMPTY is an internal use flag and should
2802 * not be specified by the caller. It is intended to fulfill the
2803 * same role as UPL_COMMIT_NOTIFY_EMPTY does in the function
2804 * ubc_upl_commit_range(), but is never referenced internally.
2805 *
2806 * The UPL_ABORT_ALLOW_ACCESS is defined, but neither set nor
2807 * referenced; do not use it.
2808 */
0b4e3aa0
A
2809kern_return_t
2810ubc_upl_abort(
0a7de745
A
2811 upl_t upl,
2812 int abort_type)
0b4e3aa0 2813{
0a7de745 2814 kern_return_t kr;
0b4e3aa0
A
2815
2816 kr = upl_abort(upl, abort_type);
2817 upl_deallocate(upl);
2818 return kr;
2819}
2820
2d21ac55
A
2821
2822/*
2823 * ubc_upl_pageinfo
2824 *
2825 * Retrieve the internal page list for the specified upl
2826 *
2827 * Parameters: upl The upl to obtain the page list from
2828 *
2829 * Returns: !NULL The (upl_page_info_t *) for the page
2830 * list internal to the upl
2831 * NULL Error/no page list associated
2832 *
2833 * Notes: IMPORTANT: The function is only valid on internal objects
2834 * where the list request was made with the UPL_INTERNAL flag.
2835 *
2836 * This function is a utility helper function, since some callers
2837 * may not have direct access to the header defining the macro,
2838 * due to abstraction layering constraints.
2839 */
0b4e3aa0
A
2840upl_page_info_t *
2841ubc_upl_pageinfo(
0a7de745
A
2842 upl_t upl)
2843{
2844 return UPL_GET_INTERNAL_PAGE_LIST(upl);
0b4e3aa0 2845}
91447636 2846
91447636 2847
0a7de745 2848int
fe8ab488 2849UBCINFOEXISTS(const struct vnode * vp)
91447636 2850{
0a7de745 2851 return (vp) && ((vp)->v_type == VREG) && ((vp)->v_ubcinfo != UBC_INFO_NULL);
91447636
A
2852}
2853
2d21ac55 2854
316670eb
A
2855void
2856ubc_upl_range_needed(
0a7de745
A
2857 upl_t upl,
2858 int index,
2859 int count)
316670eb
A
2860{
2861 upl_range_needed(upl, index, count);
2862}
2863
0a7de745
A
2864boolean_t
2865ubc_is_mapped(const struct vnode *vp, boolean_t *writable)
fe8ab488 2866{
0a7de745 2867 if (!UBCINFOEXISTS(vp) || !ISSET(vp->v_ubcinfo->ui_flags, UI_ISMAPPED)) {
fe8ab488 2868 return FALSE;
0a7de745
A
2869 }
2870 if (writable) {
fe8ab488 2871 *writable = ISSET(vp->v_ubcinfo->ui_flags, UI_MAPPEDWRITE);
0a7de745 2872 }
fe8ab488
A
2873 return TRUE;
2874}
2875
0a7de745
A
2876boolean_t
2877ubc_is_mapped_writable(const struct vnode *vp)
fe8ab488
A
2878{
2879 boolean_t writable;
2880 return ubc_is_mapped(vp, &writable) && writable;
2881}
2882
316670eb 2883
2d21ac55
A
2884/*
2885 * CODE SIGNING
2886 */
f427ee49
A
2887static atomic_size_t cs_blob_size = 0;
2888static atomic_uint_fast32_t cs_blob_count = 0;
2889static atomic_size_t cs_blob_size_peak = 0;
2890static atomic_size_t cs_blob_size_max = 0;
2891static atomic_uint_fast32_t cs_blob_count_peak = 0;
2892
2893SYSCTL_UINT(_vm, OID_AUTO, cs_blob_count, CTLFLAG_RD | CTLFLAG_LOCKED, &cs_blob_count, 0, "Current number of code signature blobs");
2894SYSCTL_ULONG(_vm, OID_AUTO, cs_blob_size, CTLFLAG_RD | CTLFLAG_LOCKED, &cs_blob_size, "Current size of all code signature blobs");
2895SYSCTL_UINT(_vm, OID_AUTO, cs_blob_count_peak, CTLFLAG_RD | CTLFLAG_LOCKED, &cs_blob_count_peak, 0, "Peak number of code signature blobs");
2896SYSCTL_ULONG(_vm, OID_AUTO, cs_blob_size_peak, CTLFLAG_RD | CTLFLAG_LOCKED, &cs_blob_size_peak, "Peak size of code signature blobs");
2897SYSCTL_ULONG(_vm, OID_AUTO, cs_blob_size_max, CTLFLAG_RD | CTLFLAG_LOCKED, &cs_blob_size_max, "Size of biggest code signature blob");
2d21ac55 2898
3e170ce0
A
2899/*
2900 * Function: csblob_parse_teamid
2901 *
2902 * Description: This function returns a pointer to the team id
0a7de745
A
2903 * stored within the codedirectory of the csblob.
2904 * If the codedirectory predates team-ids, it returns
2905 * NULL.
2906 * This does not copy the name but returns a pointer to
2907 * it within the CD. Subsequently, the CD must be
2908 * available when this is used.
2909 */
3e170ce0
A
2910
2911static const char *
2912csblob_parse_teamid(struct cs_blob *csblob)
2913{
2914 const CS_CodeDirectory *cd;
2915
490019cf 2916 cd = csblob->csb_cd;
3e170ce0 2917
0a7de745 2918 if (ntohl(cd->version) < CS_SUPPORTSTEAMID) {
3e170ce0 2919 return NULL;
0a7de745 2920 }
3e170ce0 2921
0a7de745 2922 if (cd->teamOffset == 0) {
3e170ce0 2923 return NULL;
0a7de745 2924 }
3e170ce0
A
2925
2926 const char *name = ((const char *)cd) + ntohl(cd->teamOffset);
0a7de745 2927 if (cs_debug > 1) {
3e170ce0 2928 printf("found team-id %s in cdblob\n", name);
0a7de745 2929 }
3e170ce0
A
2930
2931 return name;
2932}
2933
39236c6e 2934
593a1d5f
A
2935kern_return_t
2936ubc_cs_blob_allocate(
0a7de745
A
2937 vm_offset_t *blob_addr_p,
2938 vm_size_t *blob_size_p)
593a1d5f 2939{
0a7de745 2940 kern_return_t kr = KERN_FAILURE;
593a1d5f 2941
d9a64523
A
2942 {
2943 *blob_addr_p = (vm_offset_t) kalloc_tag(*blob_size_p, VM_KERN_MEMORY_SECURITY);
2944
2945 if (*blob_addr_p == 0) {
2946 kr = KERN_NO_SPACE;
2947 } else {
2948 kr = KERN_SUCCESS;
2949 }
593a1d5f 2950 }
d9a64523 2951
593a1d5f
A
2952 return kr;
2953}
2954
2955void
2956ubc_cs_blob_deallocate(
0a7de745
A
2957 vm_offset_t blob_addr,
2958 vm_size_t blob_size)
593a1d5f 2959{
d9a64523 2960 {
0a7de745 2961 kfree(blob_addr, blob_size);
d9a64523 2962 }
39037602
A
2963}
2964
2965/*
2966 * Some codesigned files use a lowest common denominator page size of
2967 * 4KiB, but can be used on systems that have a runtime page size of
2968 * 16KiB. Since faults will only occur on 16KiB ranges in
2969 * cs_validate_range(), we can convert the original Code Directory to
2970 * a multi-level scheme where groups of 4 hashes are combined to form
2971 * a new hash, which represents 16KiB in the on-disk file. This can
2972 * reduce the wired memory requirement for the Code Directory by
2973 * 75%. Care must be taken for binaries that use the "fourk" VM pager
2974 * for unaligned access, which may still attempt to validate on
2975 * non-16KiB multiples for compatibility with 3rd party binaries.
2976 */
2977static boolean_t
f427ee49 2978ubc_cs_supports_multilevel_hash(struct cs_blob *blob __unused)
39037602
A
2979{
2980 const CS_CodeDirectory *cd;
2981
0a7de745 2982
39037602
A
2983 /*
2984 * Only applies to binaries that ship as part of the OS,
2985 * primarily the shared cache.
2986 */
2987 if (!blob->csb_platform_binary || blob->csb_teamid != NULL) {
2988 return FALSE;
2989 }
2990
2991 /*
2992 * If the runtime page size matches the code signing page
2993 * size, there is no work to do.
2994 */
2995 if (PAGE_SHIFT <= blob->csb_hash_pageshift) {
2996 return FALSE;
2997 }
2998
2999 cd = blob->csb_cd;
3000
3001 /*
3002 * There must be a valid integral multiple of hashes
3003 */
3004 if (ntohl(cd->nCodeSlots) & (PAGE_MASK >> blob->csb_hash_pageshift)) {
3005 return FALSE;
3006 }
3007
3008 /*
3009 * Scatter lists must also have ranges that have an integral number of hashes
3010 */
3011 if ((ntohl(cd->version) >= CS_SUPPORTSSCATTER) && (ntohl(cd->scatterOffset))) {
39037602 3012 const SC_Scatter *scatter = (const SC_Scatter*)
0a7de745 3013 ((const char*)cd + ntohl(cd->scatterOffset));
39037602
A
3014 /* iterate all scatter structs to make sure they are all aligned */
3015 do {
3016 uint32_t sbase = ntohl(scatter->base);
3017 uint32_t scount = ntohl(scatter->count);
3018
3019 /* last scatter? */
3020 if (scount == 0) {
3021 break;
3022 }
3023
3024 if (sbase & (PAGE_MASK >> blob->csb_hash_pageshift)) {
3025 return FALSE;
3026 }
3027
3028 if (scount & (PAGE_MASK >> blob->csb_hash_pageshift)) {
3029 return FALSE;
3030 }
3031
3032 scatter++;
0a7de745 3033 } while (1);
39037602
A
3034 }
3035
3036 /* Covered range must be a multiple of the new page size */
3037 if (ntohl(cd->codeLimit) & PAGE_MASK) {
3038 return FALSE;
3039 }
3040
3041 /* All checks pass */
3042 return TRUE;
3043}
3044
3045/*
d9a64523
A
3046 * Given a cs_blob with an already chosen best code directory, this
3047 * function allocates memory and copies into it only the blobs that
3048 * will be needed by the kernel, namely the single chosen code
3049 * directory (and not any of its alternatives) and the entitlement
3050 * blob.
3051 *
3052 * This saves significant memory with agile signatures, and additional
3053 * memory for 3rd Party Code because we also omit the CMS blob.
3054 *
3055 * To support multilevel and other potential code directory rewriting,
3056 * the size of a new code directory can be specified. Since that code
3057 * directory will replace the existing code directory,
3058 * ubc_cs_reconstitute_code_signature does not copy the original code
3059 * directory when a size is given, and the caller must fill it in.
39037602 3060 */
d9a64523
A
3061static int
3062ubc_cs_reconstitute_code_signature(struct cs_blob const *blob, vm_size_t optional_new_cd_size,
0a7de745
A
3063 vm_address_t *new_blob_addr_p, vm_size_t *new_blob_size_p,
3064 CS_CodeDirectory **new_cd_p, CS_GenericBlob const **new_entitlements_p)
39037602 3065{
0a7de745
A
3066 const CS_CodeDirectory *old_cd, *cd;
3067 CS_CodeDirectory *new_cd;
39037602
A
3068 const CS_GenericBlob *entitlements;
3069 vm_offset_t new_blob_addr;
3070 vm_size_t new_blob_size;
3071 vm_size_t new_cdsize;
0a7de745
A
3072 kern_return_t kr;
3073 int error;
39037602
A
3074
3075 old_cd = blob->csb_cd;
3076
d9a64523 3077 new_cdsize = optional_new_cd_size != 0 ? optional_new_cd_size : htonl(old_cd->length);
39037602
A
3078
3079 new_blob_size = sizeof(CS_SuperBlob);
3080 new_blob_size += sizeof(CS_BlobIndex);
3081 new_blob_size += new_cdsize;
3082
3083 if (blob->csb_entitlements_blob) {
3084 /* We need to add a slot for the entitlements */
3085 new_blob_size += sizeof(CS_BlobIndex);
3086 new_blob_size += ntohl(blob->csb_entitlements_blob->length);
3087 }
3088
3089 kr = ubc_cs_blob_allocate(&new_blob_addr, &new_blob_size);
3090 if (kr != KERN_SUCCESS) {
3091 if (cs_debug > 1) {
3092 printf("CODE SIGNING: Failed to allocate memory for new Code Signing Blob: %d\n",
0a7de745 3093 kr);
39037602 3094 }
d9a64523 3095 return ENOMEM;
39037602
A
3096 }
3097
0a7de745 3098 CS_SuperBlob *new_superblob;
39037602
A
3099
3100 new_superblob = (CS_SuperBlob *)new_blob_addr;
3101 new_superblob->magic = htonl(CSMAGIC_EMBEDDED_SIGNATURE);
3102 new_superblob->length = htonl((uint32_t)new_blob_size);
3103 if (blob->csb_entitlements_blob) {
0a7de745 3104 vm_size_t ent_offset, cd_offset;
39037602
A
3105
3106 cd_offset = sizeof(CS_SuperBlob) + 2 * sizeof(CS_BlobIndex);
3107 ent_offset = cd_offset + new_cdsize;
3108
3109 new_superblob->count = htonl(2);
3110 new_superblob->index[0].type = htonl(CSSLOT_CODEDIRECTORY);
3111 new_superblob->index[0].offset = htonl((uint32_t)cd_offset);
3112 new_superblob->index[1].type = htonl(CSSLOT_ENTITLEMENTS);
3113 new_superblob->index[1].offset = htonl((uint32_t)ent_offset);
3114
3115 memcpy((void *)(new_blob_addr + ent_offset), blob->csb_entitlements_blob, ntohl(blob->csb_entitlements_blob->length));
3116
3117 new_cd = (CS_CodeDirectory *)(new_blob_addr + cd_offset);
3118 } else {
d9a64523
A
3119 // Blob is the code directory, directly.
3120 new_cd = (CS_CodeDirectory *)new_blob_addr;
3121 }
39037602 3122
d9a64523
A
3123 if (optional_new_cd_size == 0) {
3124 // Copy code directory, and revalidate.
3125 memcpy(new_cd, old_cd, new_cdsize);
39037602 3126
d9a64523 3127 vm_size_t length = new_blob_size;
39037602 3128
d9a64523
A
3129 error = cs_validate_csblob((const uint8_t *)new_blob_addr, length, &cd, &entitlements);
3130
3131 if (error) {
3132 printf("CODE SIGNING: Failed to validate new Code Signing Blob: %d\n",
0a7de745 3133 error);
d9a64523
A
3134
3135 ubc_cs_blob_deallocate(new_blob_addr, new_blob_size);
3136 return error;
3137 }
3138 *new_entitlements_p = entitlements;
3139 } else {
3140 // Caller will fill out and validate code directory.
3141 memset(new_cd, 0, new_cdsize);
3142 *new_entitlements_p = NULL;
3143 }
3144
3145 *new_blob_addr_p = new_blob_addr;
3146 *new_blob_size_p = new_blob_size;
3147 *new_cd_p = new_cd;
3148
3149 return 0;
3150}
3151
3152static int
3153ubc_cs_convert_to_multilevel_hash(struct cs_blob *blob)
3154{
0a7de745
A
3155 const CS_CodeDirectory *old_cd, *cd;
3156 CS_CodeDirectory *new_cd;
d9a64523
A
3157 const CS_GenericBlob *entitlements;
3158 vm_offset_t new_blob_addr;
3159 vm_size_t new_blob_size;
3160 vm_size_t new_cdsize;
0a7de745 3161 int error;
d9a64523 3162
0a7de745 3163 uint32_t hashes_per_new_hash_shift = (uint32_t)(PAGE_SHIFT - blob->csb_hash_pageshift);
d9a64523
A
3164
3165 if (cs_debug > 1) {
3166 printf("CODE SIGNING: Attempting to convert Code Directory for %lu -> %lu page shift\n",
0a7de745 3167 (unsigned long)blob->csb_hash_pageshift, (unsigned long)PAGE_SHIFT);
d9a64523
A
3168 }
3169
3170 old_cd = blob->csb_cd;
3171
3172 /* Up to the hashes, we can copy all data */
3173 new_cdsize = ntohl(old_cd->hashOffset);
3174 new_cdsize += (ntohl(old_cd->nCodeSlots) >> hashes_per_new_hash_shift) * old_cd->hashSize;
3175
3176 error = ubc_cs_reconstitute_code_signature(blob, new_cdsize,
0a7de745
A
3177 &new_blob_addr, &new_blob_size, &new_cd,
3178 &entitlements);
d9a64523
A
3179 if (error != 0) {
3180 printf("CODE SIGNING: Failed to reconsitute code signature: %d\n", error);
3181 return error;
39037602
A
3182 }
3183
3184 memcpy(new_cd, old_cd, ntohl(old_cd->hashOffset));
3185
3186 /* Update fields in the Code Directory structure */
3187 new_cd->length = htonl((uint32_t)new_cdsize);
3188
3189 uint32_t nCodeSlots = ntohl(new_cd->nCodeSlots);
3190 nCodeSlots >>= hashes_per_new_hash_shift;
3191 new_cd->nCodeSlots = htonl(nCodeSlots);
3192
f427ee49 3193 new_cd->pageSize = (uint8_t)PAGE_SHIFT; /* Not byte-swapped */
39037602
A
3194
3195 if ((ntohl(new_cd->version) >= CS_SUPPORTSSCATTER) && (ntohl(new_cd->scatterOffset))) {
3196 SC_Scatter *scatter = (SC_Scatter*)
0a7de745 3197 ((char *)new_cd + ntohl(new_cd->scatterOffset));
39037602
A
3198 /* iterate all scatter structs to scale their counts */
3199 do {
3200 uint32_t scount = ntohl(scatter->count);
3201 uint32_t sbase = ntohl(scatter->base);
3202
3203 /* last scatter? */
3204 if (scount == 0) {
3205 break;
3206 }
3207
3208 scount >>= hashes_per_new_hash_shift;
3209 scatter->count = htonl(scount);
3210
3211 sbase >>= hashes_per_new_hash_shift;
3212 scatter->base = htonl(sbase);
3213
3214 scatter++;
0a7de745 3215 } while (1);
39037602
A
3216 }
3217
3218 /* For each group of hashes, hash them together */
3219 const unsigned char *src_base = (const unsigned char *)old_cd + ntohl(old_cd->hashOffset);
3220 unsigned char *dst_base = (unsigned char *)new_cd + ntohl(new_cd->hashOffset);
3221
3222 uint32_t hash_index;
3223 for (hash_index = 0; hash_index < nCodeSlots; hash_index++) {
0a7de745 3224 union cs_hash_union mdctx;
39037602
A
3225
3226 uint32_t source_hash_len = old_cd->hashSize << hashes_per_new_hash_shift;
3227 const unsigned char *src = src_base + hash_index * source_hash_len;
3228 unsigned char *dst = dst_base + hash_index * new_cd->hashSize;
3229
3230 blob->csb_hashtype->cs_init(&mdctx);
3231 blob->csb_hashtype->cs_update(&mdctx, src, source_hash_len);
3232 blob->csb_hashtype->cs_final(dst, &mdctx);
3233 }
3234
d9a64523
A
3235 error = cs_validate_csblob((const uint8_t *)new_blob_addr, new_blob_size, &cd, &entitlements);
3236 if (error != 0) {
d9a64523 3237 printf("CODE SIGNING: Failed to validate new Code Signing Blob: %d\n",
0a7de745 3238 error);
39037602
A
3239
3240 ubc_cs_blob_deallocate(new_blob_addr, new_blob_size);
d9a64523 3241 return error;
39037602
A
3242 }
3243
0a7de745 3244 /* New Code Directory is ready for use, swap it out in the blob structure */
39037602
A
3245 ubc_cs_blob_deallocate(blob->csb_mem_kaddr, blob->csb_mem_size);
3246
3247 blob->csb_mem_size = new_blob_size;
3248 blob->csb_mem_kaddr = new_blob_addr;
3249 blob->csb_cd = cd;
3250 blob->csb_entitlements_blob = entitlements;
3251
3252 /* The blob has some cached attributes of the Code Directory, so update those */
3253
f427ee49 3254 blob->csb_hash_firstlevel_pageshift = blob->csb_hash_pageshift; /* Save the original page size */
39037602 3255
39037602
A
3256 blob->csb_hash_pageshift = PAGE_SHIFT;
3257 blob->csb_end_offset = ntohl(cd->codeLimit);
0a7de745 3258 if ((ntohl(cd->version) >= CS_SUPPORTSSCATTER) && (ntohl(cd->scatterOffset))) {
39037602 3259 const SC_Scatter *scatter = (const SC_Scatter*)
0a7de745 3260 ((const char*)cd + ntohl(cd->scatterOffset));
39037602
A
3261 blob->csb_start_offset = ((off_t)ntohl(scatter->base)) * PAGE_SIZE;
3262 } else {
3263 blob->csb_start_offset = 0;
3264 }
d9a64523
A
3265
3266 return 0;
593a1d5f 3267}
39236c6e 3268
d9a64523
A
3269/*
3270 * Validate the code signature blob, create a struct cs_blob wrapper
3271 * and return it together with a pointer to the chosen code directory
3272 * and entitlements blob.
3273 *
3274 * Note that this takes ownership of the memory as addr, mainly because
3275 * this function can actually replace the passed in blob with another
3276 * one, e.g. when performing multilevel hashing optimization.
3277 */
2d21ac55 3278int
d9a64523
A
3279cs_blob_create_validated(
3280 vm_address_t * const addr,
3281 vm_size_t size,
3282 struct cs_blob ** const ret_blob,
0a7de745 3283 CS_CodeDirectory const ** const ret_cd)
91447636 3284{
0a7de745
A
3285 struct cs_blob *blob;
3286 int error = EINVAL;
2d21ac55 3287 const CS_CodeDirectory *cd;
39037602 3288 const CS_GenericBlob *entitlements;
0a7de745
A
3289 union cs_hash_union mdctx;
3290 size_t length;
15129b1c 3291
0a7de745
A
3292 if (ret_blob) {
3293 *ret_blob = NULL;
3294 }
2d21ac55 3295
0a7de745 3296 blob = (struct cs_blob *) kalloc(sizeof(struct cs_blob));
2d21ac55
A
3297 if (blob == NULL) {
3298 return ENOMEM;
3299 }
3300
2d21ac55 3301 /* fill in the new blob */
2d21ac55
A
3302 blob->csb_mem_size = size;
3303 blob->csb_mem_offset = 0;
39037602 3304 blob->csb_mem_kaddr = *addr;
39236c6e 3305 blob->csb_flags = 0;
5ba3f43e 3306 blob->csb_signer_type = CS_SIGNER_TYPE_UNKNOWN;
fe8ab488 3307 blob->csb_platform_binary = 0;
3e170ce0 3308 blob->csb_platform_path = 0;
fe8ab488 3309 blob->csb_teamid = NULL;
f427ee49
A
3310#if CONFIG_SUPPLEMENTAL_SIGNATURES
3311 blob->csb_supplement_teamid = NULL;
3312#endif
39037602
A
3313 blob->csb_entitlements_blob = NULL;
3314 blob->csb_entitlements = NULL;
d9a64523
A
3315 blob->csb_reconstituted = false;
3316
39037602
A
3317 /* Transfer ownership. Even on error, this function will deallocate */
3318 *addr = 0;
3319
2d21ac55
A
3320 /*
3321 * Validate the blob's contents
3322 */
813fb2f6
A
3323 length = (size_t) size;
3324 error = cs_validate_csblob((const uint8_t *)blob->csb_mem_kaddr,
0a7de745 3325 length, &cd, &entitlements);
39236c6e 3326 if (error) {
0a7de745 3327 if (cs_debug) {
39236c6e 3328 printf("CODESIGNING: csblob invalid: %d\n", error);
0a7de745 3329 }
813fb2f6
A
3330 /*
3331 * The vnode checker can't make the rest of this function
3332 * succeed if csblob validation failed, so bail */
3333 goto out;
2d21ac55 3334 } else {
3e170ce0
A
3335 const unsigned char *md_base;
3336 uint8_t hash[CS_HASH_MAX_SIZE];
3337 int md_size;
f427ee49 3338 vm_offset_t hash_pagemask;
3e170ce0 3339
490019cf 3340 blob->csb_cd = cd;
39037602 3341 blob->csb_entitlements_blob = entitlements; /* may be NULL, not yet validated */
3e170ce0 3342 blob->csb_hashtype = cs_find_md(cd->hashType);
0a7de745 3343 if (blob->csb_hashtype == NULL || blob->csb_hashtype->cs_digest_size > sizeof(hash)) {
3e170ce0 3344 panic("validated CodeDirectory but unsupported type");
0a7de745 3345 }
39037602
A
3346
3347 blob->csb_hash_pageshift = cd->pageSize;
f427ee49
A
3348 hash_pagemask = (1U << cd->pageSize) - 1;
3349 blob->csb_hash_firstlevel_pageshift = 0;
39236c6e 3350 blob->csb_flags = (ntohl(cd->flags) & CS_ALLOWED_MACHO) | CS_VALID;
f427ee49 3351 blob->csb_end_offset = (((vm_offset_t)ntohl(cd->codeLimit) + hash_pagemask) & ~hash_pagemask);
0a7de745 3352 if ((ntohl(cd->version) >= CS_SUPPORTSSCATTER) && (ntohl(cd->scatterOffset))) {
39236c6e 3353 const SC_Scatter *scatter = (const SC_Scatter*)
0a7de745 3354 ((const char*)cd + ntohl(cd->scatterOffset));
f427ee49 3355 blob->csb_start_offset = ((off_t)ntohl(scatter->base)) * (1U << blob->csb_hash_pageshift);
b0d623f7 3356 } else {
3e170ce0 3357 blob->csb_start_offset = 0;
b0d623f7 3358 }
3e170ce0
A
3359 /* compute the blob's cdhash */
3360 md_base = (const unsigned char *) cd;
3361 md_size = ntohl(cd->length);
3362
3363 blob->csb_hashtype->cs_init(&mdctx);
3364 blob->csb_hashtype->cs_update(&mdctx, md_base, md_size);
3365 blob->csb_hashtype->cs_final(hash, &mdctx);
3366
3367 memcpy(blob->csb_cdhash, hash, CS_CDHASH_LEN);
f427ee49
A
3368 blob->csb_cdhash_signature = ptrauth_utils_sign_blob_generic(blob->csb_cdhash,
3369 sizeof(blob->csb_cdhash),
3370 OS_PTRAUTH_DISCRIMINATOR("cs_blob.csb_cd_signature"),
3371 PTRAUTH_ADDR_DIVERSIFY);
3372
3373#if CONFIG_SUPPLEMENTAL_SIGNATURES
3374 blob->csb_linkage_hashtype = NULL;
3375 if (ntohl(cd->version) >= CS_SUPPORTSLINKAGE && cd->linkageHashType != 0 &&
3376 ntohl(cd->linkageSize) >= CS_CDHASH_LEN) {
3377 blob->csb_linkage_hashtype = cs_find_md(cd->linkageHashType);
3378
3379 if (blob->csb_linkage_hashtype != NULL) {
3380 memcpy(blob->csb_linkage, (uint8_t const*)cd + ntohl(cd->linkageOffset),
3381 CS_CDHASH_LEN);
3382 }
3383 }
3384#endif
2d21ac55
A
3385 }
3386
0a7de745 3387 error = 0;
d9a64523
A
3388
3389out:
0a7de745
A
3390 if (error != 0) {
3391 cs_blob_free(blob);
3392 blob = NULL;
3393 cd = NULL;
3394 }
3395
3396 if (ret_blob != NULL) {
3397 *ret_blob = blob;
3398 }
3399 if (ret_cd != NULL) {
3400 *ret_cd = cd;
3401 }
3402
3403 return error;
d9a64523
A
3404}
3405
3406/*
3407 * Free a cs_blob previously created by cs_blob_create_validated.
3408 */
3409void
3410cs_blob_free(
0a7de745 3411 struct cs_blob * const blob)
d9a64523 3412{
0a7de745
A
3413 if (blob != NULL) {
3414 if (blob->csb_mem_kaddr) {
3415 ubc_cs_blob_deallocate(blob->csb_mem_kaddr, blob->csb_mem_size);
3416 blob->csb_mem_kaddr = 0;
3417 }
3418 if (blob->csb_entitlements != NULL) {
3419 osobject_release(blob->csb_entitlements);
3420 blob->csb_entitlements = NULL;
3421 }
3422 (kfree)(blob, sizeof(*blob));
3423 }
d9a64523 3424}
f427ee49
A
3425#if CONFIG_SUPPLEMENTAL_SIGNATURES
3426static void
3427cs_blob_supplement_free(struct cs_blob * const blob)
3428{
3429 if (blob != NULL) {
3430 if (blob->csb_supplement_teamid != NULL) {
3431 vm_size_t teamid_size = strlen(blob->csb_supplement_teamid) + 1;
3432 kfree(blob->csb_supplement_teamid, teamid_size);
3433 blob->csb_supplement_teamid = NULL;
3434 }
3435 cs_blob_free(blob);
3436 }
3437}
3438#endif
3439
3440static void
3441ubc_cs_blob_adjust_statistics(struct cs_blob const *blob)
3442{
3443 /* Note that the atomic ops are not enough to guarantee
3444 * correctness: If a blob with an intermediate size is inserted
3445 * concurrently, we can lose a peak value assignment. But these
3446 * statistics are only advisory anyway, so we're not going to
3447 * employ full locking here. (Consequently, we are also okay with
3448 * relaxed ordering of those accesses.)
3449 */
3450
3451 unsigned int new_cs_blob_count = os_atomic_add(&cs_blob_count, 1, relaxed);
3452 if (new_cs_blob_count > os_atomic_load(&cs_blob_count_peak, relaxed)) {
3453 os_atomic_store(&cs_blob_count_peak, new_cs_blob_count, relaxed);
3454 }
3455
3456 size_t new_cs_blob_size = os_atomic_add(&cs_blob_size, blob->csb_mem_size, relaxed);
3457
3458 if (new_cs_blob_size > os_atomic_load(&cs_blob_size_peak, relaxed)) {
3459 os_atomic_store(&cs_blob_size_peak, new_cs_blob_size, relaxed);
3460 }
3461 if (blob->csb_mem_size > os_atomic_load(&cs_blob_size_max, relaxed)) {
3462 os_atomic_store(&cs_blob_size_max, blob->csb_mem_size, relaxed);
3463 }
3464}
d9a64523
A
3465
3466int
3467ubc_cs_blob_add(
0a7de745 3468 struct vnode *vp,
f427ee49 3469 uint32_t platform,
0a7de745 3470 cpu_type_t cputype,
f427ee49 3471 cpu_subtype_t cpusubtype,
0a7de745
A
3472 off_t base_offset,
3473 vm_address_t *addr,
3474 vm_size_t size,
d9a64523 3475 struct image_params *imgp,
0a7de745
A
3476 __unused int flags,
3477 struct cs_blob **ret_blob)
d9a64523 3478{
0a7de745
A
3479 kern_return_t kr;
3480 struct ubc_info *uip;
f427ee49 3481 struct cs_blob *blob = NULL, *oblob = NULL;
0a7de745 3482 int error;
d9a64523 3483 CS_CodeDirectory const *cd;
0a7de745
A
3484 off_t blob_start_offset, blob_end_offset;
3485 boolean_t record_mtime;
d9a64523
A
3486
3487 record_mtime = FALSE;
0a7de745
A
3488 if (ret_blob) {
3489 *ret_blob = NULL;
3490 }
3491
3492 /* Create the struct cs_blob wrapper that will be attached to the vnode.
3493 * Validates the passed in blob in the process. */
3494 error = cs_blob_create_validated(addr, size, &blob, &cd);
3495
3496 if (error != 0) {
d9a64523 3497 printf("malform code signature blob: %d\n", error);
0a7de745
A
3498 return error;
3499 }
d9a64523 3500
0a7de745 3501 blob->csb_cpu_type = cputype;
f427ee49 3502 blob->csb_cpu_subtype = cpusubtype & ~CPU_SUBTYPE_MASK;
d9a64523
A
3503 blob->csb_base_offset = base_offset;
3504
3505 /*
593a1d5f
A
3506 * Let policy module check whether the blob's signature is accepted.
3507 */
3508#if CONFIG_MACF
0a7de745 3509 unsigned int cs_flags = blob->csb_flags;
5ba3f43e 3510 unsigned int signer_type = blob->csb_signer_type;
f427ee49 3511 error = mac_vnode_check_signature(vp, blob, imgp, &cs_flags, &signer_type, flags, platform);
0a7de745 3512 blob->csb_flags = cs_flags;
5ba3f43e 3513 blob->csb_signer_type = signer_type;
39037602 3514
fe8ab488 3515 if (error) {
0a7de745 3516 if (cs_debug) {
fe8ab488 3517 printf("check_signature[pid: %d], error = %d\n", current_proc()->p_pid, error);
0a7de745 3518 }
593a1d5f 3519 goto out;
fe8ab488 3520 }
39037602 3521 if ((flags & MAC_VNODE_CHECK_DYLD_SIM) && !(blob->csb_flags & CS_PLATFORM_BINARY)) {
0a7de745 3522 if (cs_debug) {
c18c124e 3523 printf("check_signature[pid: %d], is not apple signed\n", current_proc()->p_pid);
0a7de745 3524 }
c18c124e
A
3525 error = EPERM;
3526 goto out;
3527 }
5ba3f43e
A
3528#endif
3529
d9a64523
A
3530#if CONFIG_ENFORCE_SIGNED_CODE
3531 /*
3532 * Reconstitute code signature
3533 */
3534 {
3535 vm_address_t new_mem_kaddr = 0;
3536 vm_size_t new_mem_size = 0;
3537
3538 CS_CodeDirectory *new_cd = NULL;
3539 CS_GenericBlob const *new_entitlements = NULL;
3540
3541 error = ubc_cs_reconstitute_code_signature(blob, 0,
0a7de745
A
3542 &new_mem_kaddr, &new_mem_size,
3543 &new_cd, &new_entitlements);
d9a64523
A
3544
3545 if (error != 0) {
3546 printf("failed code signature reconstitution: %d\n", error);
3547 goto out;
3548 }
3549
3550 ubc_cs_blob_deallocate(blob->csb_mem_kaddr, blob->csb_mem_size);
3551
3552 blob->csb_mem_kaddr = new_mem_kaddr;
3553 blob->csb_mem_size = new_mem_size;
3554 blob->csb_cd = new_cd;
3555 blob->csb_entitlements_blob = new_entitlements;
3556 blob->csb_reconstituted = true;
3557 }
d9a64523
A
3558#endif
3559
3560
39037602 3561 if (blob->csb_flags & CS_PLATFORM_BINARY) {
0a7de745 3562 if (cs_debug > 1) {
fe8ab488 3563 printf("check_signature[pid: %d]: platform binary\n", current_proc()->p_pid);
0a7de745 3564 }
fe8ab488 3565 blob->csb_platform_binary = 1;
39037602 3566 blob->csb_platform_path = !!(blob->csb_flags & CS_PLATFORM_PATH);
fe8ab488
A
3567 } else {
3568 blob->csb_platform_binary = 0;
3e170ce0
A
3569 blob->csb_platform_path = 0;
3570 blob->csb_teamid = csblob_parse_teamid(blob);
fe8ab488 3571 if (cs_debug > 1) {
0a7de745 3572 if (blob->csb_teamid) {
fe8ab488 3573 printf("check_signature[pid: %d]: team-id is %s\n", current_proc()->p_pid, blob->csb_teamid);
0a7de745 3574 } else {
fe8ab488 3575 printf("check_signature[pid: %d]: no team-id\n", current_proc()->p_pid);
0a7de745 3576 }
fe8ab488
A
3577 }
3578 }
39037602 3579
2d21ac55
A
3580 /*
3581 * Validate the blob's coverage
3582 */
3583 blob_start_offset = blob->csb_base_offset + blob->csb_start_offset;
3584 blob_end_offset = blob->csb_base_offset + blob->csb_end_offset;
3585
cf7d32b8
A
3586 if (blob_start_offset >= blob_end_offset ||
3587 blob_start_offset < 0 ||
3588 blob_end_offset <= 0) {
2d21ac55
A
3589 /* reject empty or backwards blob */
3590 error = EINVAL;
3591 goto out;
3592 }
3593
39037602 3594 if (ubc_cs_supports_multilevel_hash(blob)) {
d9a64523
A
3595 error = ubc_cs_convert_to_multilevel_hash(blob);
3596 if (error != 0) {
3597 printf("failed multilevel hash conversion: %d\n", error);
3598 goto out;
3599 }
3600 blob->csb_reconstituted = true;
39037602
A
3601 }
3602
2d21ac55 3603 vnode_lock(vp);
0a7de745 3604 if (!UBCINFOEXISTS(vp)) {
2d21ac55
A
3605 vnode_unlock(vp);
3606 error = ENOENT;
3607 goto out;
3608 }
3609 uip = vp->v_ubcinfo;
3610
3611 /* check if this new blob overlaps with an existing blob */
3612 for (oblob = uip->cs_blobs;
0a7de745
A
3613 oblob != NULL;
3614 oblob = oblob->csb_next) {
3615 off_t oblob_start_offset, oblob_end_offset;
3616
3617 if (blob->csb_signer_type != oblob->csb_signer_type) { // signer type needs to be the same for slices
3618 vnode_unlock(vp);
3619 error = EALREADY;
3620 goto out;
3621 } else if (blob->csb_platform_binary) { //platform binary needs to be the same for app slices
3622 if (!oblob->csb_platform_binary) {
3623 vnode_unlock(vp);
3624 error = EALREADY;
3625 goto out;
3626 }
3627 } else if (blob->csb_teamid) { //teamid binary needs to be the same for app slices
3628 if (oblob->csb_platform_binary ||
fe8ab488
A
3629 oblob->csb_teamid == NULL ||
3630 strcmp(oblob->csb_teamid, blob->csb_teamid) != 0) {
3631 vnode_unlock(vp);
3632 error = EALREADY;
3633 goto out;
3634 }
0a7de745
A
3635 } else { // non teamid binary needs to be the same for app slices
3636 if (oblob->csb_platform_binary ||
3637 oblob->csb_teamid != NULL) {
fe8ab488
A
3638 vnode_unlock(vp);
3639 error = EALREADY;
3640 goto out;
3641 }
0a7de745 3642 }
2d21ac55 3643
0a7de745
A
3644 oblob_start_offset = (oblob->csb_base_offset +
3645 oblob->csb_start_offset);
3646 oblob_end_offset = (oblob->csb_base_offset +
3647 oblob->csb_end_offset);
3648 if (blob_start_offset >= oblob_end_offset ||
3649 blob_end_offset <= oblob_start_offset) {
3650 /* no conflict with this existing blob */
3651 } else {
3652 /* conflict ! */
3653 if (blob_start_offset == oblob_start_offset &&
3654 blob_end_offset == oblob_end_offset &&
3655 blob->csb_mem_size == oblob->csb_mem_size &&
3656 blob->csb_flags == oblob->csb_flags &&
3657 (blob->csb_cpu_type == CPU_TYPE_ANY ||
3658 oblob->csb_cpu_type == CPU_TYPE_ANY ||
3659 blob->csb_cpu_type == oblob->csb_cpu_type) &&
3660 !bcmp(blob->csb_cdhash,
3661 oblob->csb_cdhash,
3662 CS_CDHASH_LEN)) {
3663 /*
3664 * We already have this blob:
3665 * we'll return success but
3666 * throw away the new blob.
3667 */
3668 if (oblob->csb_cpu_type == CPU_TYPE_ANY) {
3669 /*
3670 * The old blob matches this one
3671 * but doesn't have any CPU type.
3672 * Update it with whatever the caller
3673 * provided this time.
3674 */
3675 oblob->csb_cpu_type = cputype;
3676 }
3677
3678 /* The signature is still accepted, so update the
3679 * generation count. */
3680 uip->cs_add_gen = cs_blob_generation_count;
3681
3682 vnode_unlock(vp);
3683 if (ret_blob) {
3684 *ret_blob = oblob;
3685 }
3686 error = EAGAIN;
3687 goto out;
3688 } else {
3689 /* different blob: reject the new one */
3690 vnode_unlock(vp);
3691 error = EALREADY;
3692 goto out;
3693 }
3694 }
2d21ac55
A
3695 }
3696
fe8ab488 3697
2d21ac55
A
3698 /* mark this vnode's VM object as having "signed pages" */
3699 kr = memory_object_signed(uip->ui_control, TRUE);
3700 if (kr != KERN_SUCCESS) {
3701 vnode_unlock(vp);
3702 error = ENOENT;
3703 goto out;
3704 }
3705
15129b1c
A
3706 if (uip->cs_blobs == NULL) {
3707 /* loading 1st blob: record the file's current "modify time" */
3708 record_mtime = TRUE;
3709 }
3710
fe8ab488
A
3711 /* set the generation count for cs_blobs */
3712 uip->cs_add_gen = cs_blob_generation_count;
3713
2d21ac55
A
3714 /*
3715 * Add this blob to the list of blobs for this vnode.
3716 * We always add at the front of the list and we never remove a
3717 * blob from the list, so ubc_cs_get_blobs() can return whatever
3718 * the top of the list was and that list will remain valid
3719 * while we validate a page, even after we release the vnode's lock.
3720 */
3721 blob->csb_next = uip->cs_blobs;
3722 uip->cs_blobs = blob;
3723
f427ee49 3724 ubc_cs_blob_adjust_statistics(blob);
2d21ac55 3725
c331a0be 3726 if (cs_debug > 1) {
2d21ac55 3727 proc_t p;
39236c6e 3728 const char *name = vnode_getname_printable(vp);
2d21ac55
A
3729 p = current_proc();
3730 printf("CODE SIGNING: proc %d(%s) "
0a7de745
A
3731 "loaded %s signatures for file (%s) "
3732 "range 0x%llx:0x%llx flags 0x%x\n",
3733 p->p_pid, p->p_comm,
3734 blob->csb_cpu_type == -1 ? "detached" : "embedded",
3735 name,
3736 blob->csb_base_offset + blob->csb_start_offset,
3737 blob->csb_base_offset + blob->csb_end_offset,
3738 blob->csb_flags);
39236c6e 3739 vnode_putname_printable(name);
2d21ac55
A
3740 }
3741
2d21ac55
A
3742 vnode_unlock(vp);
3743
15129b1c
A
3744 if (record_mtime) {
3745 vnode_mtime(vp, &uip->cs_mtime, vfs_context_current());
3746 }
3747
0a7de745 3748 if (ret_blob) {
3e170ce0 3749 *ret_blob = blob;
0a7de745 3750 }
3e170ce0 3751
0a7de745 3752 error = 0; /* success ! */
2d21ac55
A
3753
3754out:
3755 if (error) {
0a7de745 3756 if (cs_debug) {
fe8ab488 3757 printf("check_signature[pid: %d]: error = %d\n", current_proc()->p_pid, error);
0a7de745 3758 }
fe8ab488 3759
0a7de745 3760 cs_blob_free(blob);
2d21ac55
A
3761 }
3762
3763 if (error == EAGAIN) {
3764 /*
0a7de745 3765 * See above: error is EAGAIN if we were asked
2d21ac55
A
3766 * to add an existing blob again. We cleaned the new
3767 * blob and we want to return success.
3768 */
3769 error = 0;
2d21ac55
A
3770 }
3771
3772 return error;
91447636
A
3773}
3774
f427ee49
A
3775#if CONFIG_SUPPLEMENTAL_SIGNATURES
3776int
3777ubc_cs_blob_add_supplement(
3778 struct vnode *vp,
3779 struct vnode *orig_vp,
3780 off_t base_offset,
3781 vm_address_t *addr,
3782 vm_size_t size,
3783 struct cs_blob **ret_blob)
3784{
3785 kern_return_t kr;
3786 struct ubc_info *uip, *orig_uip;
3787 int error;
3788 struct cs_blob *blob, *orig_blob;
3789 CS_CodeDirectory const *cd;
3790 off_t blob_start_offset, blob_end_offset;
3791
3792 if (ret_blob) {
3793 *ret_blob = NULL;
3794 }
3795
3796 /* Create the struct cs_blob wrapper that will be attached to the vnode.
3797 * Validates the passed in blob in the process. */
3798 error = cs_blob_create_validated(addr, size, &blob, &cd);
3799
3800 if (error != 0) {
3801 printf("malformed code signature supplement blob: %d\n", error);
3802 return error;
3803 }
3804
3805 blob->csb_cpu_type = -1;
3806 blob->csb_base_offset = base_offset;
3807
3808 blob->csb_reconstituted = false;
3809
3810 vnode_lock(orig_vp);
3811 if (!UBCINFOEXISTS(orig_vp)) {
3812 vnode_unlock(orig_vp);
3813 error = ENOENT;
3814 goto out;
3815 }
3816
3817 orig_uip = orig_vp->v_ubcinfo;
3818
3819 /* check that the supplement's linked cdhash matches a cdhash of
3820 * the target image.
3821 */
3822
3823 if (blob->csb_linkage_hashtype == NULL) {
3824 proc_t p;
3825 const char *iname = vnode_getname_printable(vp);
3826 p = current_proc();
3827
3828 printf("CODE SIGNING: proc %d(%s) supplemental signature for file (%s) "
3829 "is not a supplemental.\n",
3830 p->p_pid, p->p_comm, iname);
3831
3832 error = EINVAL;
3833
3834 vnode_putname_printable(iname);
3835 vnode_unlock(orig_vp);
3836 goto out;
3837 }
3838
3839 for (orig_blob = orig_uip->cs_blobs; orig_blob != NULL;
3840 orig_blob = orig_blob->csb_next) {
3841 ptrauth_utils_auth_blob_generic(orig_blob->csb_cdhash,
3842 sizeof(orig_blob->csb_cdhash),
3843 OS_PTRAUTH_DISCRIMINATOR("cs_blob.csb_cd_signature"),
3844 PTRAUTH_ADDR_DIVERSIFY,
3845 orig_blob->csb_cdhash_signature);
3846 if (orig_blob->csb_hashtype == blob->csb_linkage_hashtype &&
3847 memcmp(orig_blob->csb_cdhash, blob->csb_linkage, CS_CDHASH_LEN) == 0) {
3848 // Found match!
3849 break;
3850 }
3851 }
3852
3853 if (orig_blob == NULL) {
3854 // Not found.
3855
3856 proc_t p;
3857 const char *iname = vnode_getname_printable(vp);
3858 p = current_proc();
3859
3860 printf("CODE SIGNING: proc %d(%s) supplemental signature for file (%s) "
3861 "does not match any attached cdhash.\n",
3862 p->p_pid, p->p_comm, iname);
3863
3864 error = ESRCH;
3865
3866 vnode_putname_printable(iname);
3867 vnode_unlock(orig_vp);
3868 goto out;
3869 }
3870
3871 vnode_unlock(orig_vp);
3872
3873 // validate the signature against policy!
3874#if CONFIG_MACF
3875 unsigned int signer_type = blob->csb_signer_type;
3876 error = mac_vnode_check_supplemental_signature(vp, blob, orig_vp, orig_blob, &signer_type);
3877 blob->csb_signer_type = signer_type;
3878
3879
3880 if (error) {
3881 if (cs_debug) {
3882 printf("check_supplemental_signature[pid: %d], error = %d\n", current_proc()->p_pid, error);
3883 }
3884 goto out;
3885 }
3886#endif
3887
3888 // We allowed the supplemental signature blob so
3889 // copy the platform bit or team-id from the linked signature and whether or not the original is developer code
3890 blob->csb_platform_binary = 0;
3891 blob->csb_platform_path = 0;
3892 if (orig_blob->csb_platform_binary == 1) {
3893 blob->csb_platform_binary = orig_blob->csb_platform_binary;
3894 blob->csb_platform_path = orig_blob->csb_platform_path;
3895 } else if (orig_blob->csb_teamid != NULL) {
3896 vm_size_t teamid_size = strlen(orig_blob->csb_teamid) + 1;
3897 blob->csb_supplement_teamid = kalloc(teamid_size);
3898 if (blob->csb_supplement_teamid == NULL) {
3899 error = ENOMEM;
3900 goto out;
3901 }
3902 strlcpy(blob->csb_supplement_teamid, orig_blob->csb_teamid, teamid_size);
3903 }
3904 blob->csb_flags = (orig_blob->csb_flags & CS_DEV_CODE);
3905
3906 // Validate the blob's coverage
3907 blob_start_offset = blob->csb_base_offset + blob->csb_start_offset;
3908 blob_end_offset = blob->csb_base_offset + blob->csb_end_offset;
3909
3910 if (blob_start_offset >= blob_end_offset || blob_start_offset < 0 || blob_end_offset <= 0) {
3911 /* reject empty or backwards blob */
3912 error = EINVAL;
3913 goto out;
3914 }
3915
3916 vnode_lock(vp);
3917 if (!UBCINFOEXISTS(vp)) {
3918 vnode_unlock(vp);
3919 error = ENOENT;
3920 goto out;
3921 }
3922 uip = vp->v_ubcinfo;
3923
3924 struct cs_blob *existing = uip->cs_blob_supplement;
3925 if (existing != NULL) {
3926 if (blob->csb_hashtype == existing->csb_hashtype &&
3927 memcmp(blob->csb_cdhash, existing->csb_cdhash, CS_CDHASH_LEN) == 0) {
3928 error = EAGAIN; // non-fatal
3929 } else {
3930 error = EALREADY; // fatal
3931 }
3932
3933 vnode_unlock(vp);
3934 goto out;
3935 }
3936
3937 /* Unlike regular cs_blobs, we only ever support one supplement. */
3938 blob->csb_next = NULL;
3939 uip->cs_blob_supplement = blob;
3940
3941 /* mark this vnode's VM object as having "signed pages" */
3942 kr = memory_object_signed(uip->ui_control, TRUE);
3943 if (kr != KERN_SUCCESS) {
3944 vnode_unlock(vp);
3945 error = ENOENT;
3946 goto out;
3947 }
3948
3949 vnode_unlock(vp);
3950
3951 /* We still adjust statistics even for supplemental blobs, as they
3952 * consume memory just the same. */
3953 ubc_cs_blob_adjust_statistics(blob);
3954
3955 if (cs_debug > 1) {
3956 proc_t p;
3957 const char *name = vnode_getname_printable(vp);
3958 p = current_proc();
3959 printf("CODE SIGNING: proc %d(%s) "
3960 "loaded supplemental signature for file (%s) "
3961 "range 0x%llx:0x%llx\n",
3962 p->p_pid, p->p_comm,
3963 name,
3964 blob->csb_base_offset + blob->csb_start_offset,
3965 blob->csb_base_offset + blob->csb_end_offset);
3966 vnode_putname_printable(name);
3967 }
3968
3969 if (ret_blob) {
3970 *ret_blob = blob;
3971 }
3972
3973 error = 0; // Success!
3974out:
3975 if (error) {
3976 if (cs_debug) {
3977 printf("ubc_cs_blob_add_supplement[pid: %d]: error = %d\n", current_proc()->p_pid, error);
3978 }
3979
3980 cs_blob_supplement_free(blob);
3981 }
3982
3983 if (error == EAGAIN) {
3984 /* We were asked to add an existing blob.
3985 * We cleaned up and ignore the attempt. */
3986 error = 0;
3987 }
3988
3989 return error;
3990}
3991#endif
3992
3993
3994
3e170ce0
A
3995void
3996csvnode_print_debug(struct vnode *vp)
3997{
0a7de745
A
3998 const char *name = NULL;
3999 struct ubc_info *uip;
3e170ce0
A
4000 struct cs_blob *blob;
4001
4002 name = vnode_getname_printable(vp);
4003 if (name) {
4004 printf("csvnode: name: %s\n", name);
4005 vnode_putname_printable(name);
4006 }
4007
4008 vnode_lock_spin(vp);
4009
0a7de745 4010 if (!UBCINFOEXISTS(vp)) {
3e170ce0
A
4011 blob = NULL;
4012 goto out;
4013 }
4014
4015 uip = vp->v_ubcinfo;
4016 for (blob = uip->cs_blobs; blob != NULL; blob = blob->csb_next) {
4017 printf("csvnode: range: %lu -> %lu flags: 0x%08x platform: %s path: %s team: %s\n",
0a7de745
A
4018 (unsigned long)blob->csb_start_offset,
4019 (unsigned long)blob->csb_end_offset,
4020 blob->csb_flags,
4021 blob->csb_platform_binary ? "yes" : "no",
4022 blob->csb_platform_path ? "yes" : "no",
4023 blob->csb_teamid ? blob->csb_teamid : "<NO-TEAM>");
3e170ce0
A
4024 }
4025
4026out:
4027 vnode_unlock(vp);
3e170ce0
A
4028}
4029
f427ee49
A
4030#if CONFIG_SUPPLEMENTAL_SIGNATURES
4031struct cs_blob *
4032ubc_cs_blob_get_supplement(
4033 struct vnode *vp,
4034 off_t offset)
4035{
4036 struct cs_blob *blob;
4037 off_t offset_in_blob;
4038
4039 vnode_lock_spin(vp);
4040
4041 if (!UBCINFOEXISTS(vp)) {
4042 blob = NULL;
4043 goto out;
4044 }
4045
4046 blob = vp->v_ubcinfo->cs_blob_supplement;
4047
4048 if (blob == NULL) {
4049 // no supplemental blob
4050 goto out;
4051 }
4052
4053
4054 if (offset != -1) {
4055 offset_in_blob = offset - blob->csb_base_offset;
4056 if (offset_in_blob < blob->csb_start_offset || offset_in_blob >= blob->csb_end_offset) {
4057 // not actually covered by this blob
4058 blob = NULL;
4059 }
4060 }
4061
4062out:
4063 vnode_unlock(vp);
4064
4065 return blob;
4066}
4067#endif
4068
2d21ac55
A
4069struct cs_blob *
4070ubc_cs_blob_get(
0a7de745
A
4071 struct vnode *vp,
4072 cpu_type_t cputype,
f427ee49 4073 cpu_subtype_t cpusubtype,
0a7de745 4074 off_t offset)
91447636 4075{
0a7de745
A
4076 struct ubc_info *uip;
4077 struct cs_blob *blob;
2d21ac55
A
4078 off_t offset_in_blob;
4079
4080 vnode_lock_spin(vp);
4081
0a7de745 4082 if (!UBCINFOEXISTS(vp)) {
2d21ac55
A
4083 blob = NULL;
4084 goto out;
4085 }
4086
4087 uip = vp->v_ubcinfo;
4088 for (blob = uip->cs_blobs;
0a7de745
A
4089 blob != NULL;
4090 blob = blob->csb_next) {
f427ee49 4091 if (cputype != -1 && blob->csb_cpu_type == cputype && (cpusubtype == -1 || blob->csb_cpu_subtype == (cpusubtype & ~CPU_SUBTYPE_MASK))) {
2d21ac55
A
4092 break;
4093 }
4094 if (offset != -1) {
4095 offset_in_blob = offset - blob->csb_base_offset;
4096 if (offset_in_blob >= blob->csb_start_offset &&
4097 offset_in_blob < blob->csb_end_offset) {
4098 /* our offset is covered by this blob */
4099 break;
4100 }
4101 }
4102 }
4103
4104out:
4105 vnode_unlock(vp);
4106
4107 return blob;
91447636 4108}
2d21ac55
A
4109
4110static void
4111ubc_cs_free(
0a7de745 4112 struct ubc_info *uip)
91447636 4113{
0a7de745 4114 struct cs_blob *blob, *next_blob;
2d21ac55
A
4115
4116 for (blob = uip->cs_blobs;
0a7de745
A
4117 blob != NULL;
4118 blob = next_blob) {
2d21ac55 4119 next_blob = blob->csb_next;
f427ee49
A
4120 os_atomic_add(&cs_blob_count, -1, relaxed);
4121 os_atomic_add(&cs_blob_size, -blob->csb_mem_size, relaxed);
d9a64523 4122 cs_blob_free(blob);
2d21ac55 4123 }
6d2010ae
A
4124#if CHECK_CS_VALIDATION_BITMAP
4125 ubc_cs_validation_bitmap_deallocate( uip->ui_vnode );
4126#endif
2d21ac55 4127 uip->cs_blobs = NULL;
f427ee49
A
4128#if CONFIG_SUPPLEMENTAL_SIGNATURES
4129 if (uip->cs_blob_supplement != NULL) {
4130 blob = uip->cs_blob_supplement;
4131 os_atomic_add(&cs_blob_count, -1, relaxed);
4132 os_atomic_add(&cs_blob_size, -blob->csb_mem_size, relaxed);
4133 cs_blob_supplement_free(uip->cs_blob_supplement);
4134 uip->cs_blob_supplement = NULL;
4135 }
4136#endif
91447636 4137}
2d21ac55 4138
fe8ab488
A
4139/* check cs blob generation on vnode
4140 * returns:
4141 * 0 : Success, the cs_blob attached is current
4142 * ENEEDAUTH : Generation count mismatch. Needs authentication again.
4143 */
4144int
4145ubc_cs_generation_check(
0a7de745 4146 struct vnode *vp)
fe8ab488
A
4147{
4148 int retval = ENEEDAUTH;
4149
4150 vnode_lock_spin(vp);
4151
4152 if (UBCINFOEXISTS(vp) && vp->v_ubcinfo->cs_add_gen == cs_blob_generation_count) {
4153 retval = 0;
4154 }
4155
4156 vnode_unlock(vp);
4157 return retval;
4158}
4159
4160int
4161ubc_cs_blob_revalidate(
0a7de745 4162 struct vnode *vp,
c18c124e 4163 struct cs_blob *blob,
39037602 4164 struct image_params *imgp,
f427ee49
A
4165 int flags,
4166 uint32_t platform
fe8ab488
A
4167 )
4168{
4169 int error = 0;
fe8ab488 4170 const CS_CodeDirectory *cd = NULL;
39037602 4171 const CS_GenericBlob *entitlements = NULL;
813fb2f6 4172 size_t size;
fe8ab488
A
4173 assert(vp != NULL);
4174 assert(blob != NULL);
4175
813fb2f6
A
4176 size = blob->csb_mem_size;
4177 error = cs_validate_csblob((const uint8_t *)blob->csb_mem_kaddr,
0a7de745 4178 size, &cd, &entitlements);
fe8ab488
A
4179 if (error) {
4180 if (cs_debug) {
4181 printf("CODESIGNING: csblob invalid: %d\n", error);
4182 }
4183 goto out;
4184 }
4185
0a7de745
A
4186 unsigned int cs_flags = (ntohl(cd->flags) & CS_ALLOWED_MACHO) | CS_VALID;
4187 unsigned int signer_type = CS_SIGNER_TYPE_UNKNOWN;
d9a64523
A
4188
4189 if (blob->csb_reconstituted) {
4190 /*
4191 * Code signatures that have been modified after validation
4192 * cannot be revalidated inline from their in-memory blob.
4193 *
4194 * That's okay, though, because the only path left that relies
4195 * on revalidation of existing in-memory blobs is the legacy
4196 * detached signature database path, which only exists on macOS,
4197 * which does not do reconstitution of any kind.
4198 */
4199 if (cs_debug) {
4200 printf("CODESIGNING: revalidate: not inline revalidating reconstituted signature.\n");
4201 }
4202
4203 /*
4204 * EAGAIN tells the caller that they may reread the code
4205 * signature and try attaching it again, which is the same
4206 * thing they would do if there was no cs_blob yet in the
4207 * first place.
4208 *
4209 * Conveniently, after ubc_cs_blob_add did a successful
4210 * validation, it will detect that a matching cs_blob (cdhash,
4211 * offset, arch etc.) already exists, and return success
4212 * without re-adding a cs_blob to the vnode.
4213 */
4214 return EAGAIN;
4215 }
4216
fe8ab488
A
4217 /* callout to mac_vnode_check_signature */
4218#if CONFIG_MACF
f427ee49 4219 error = mac_vnode_check_signature(vp, blob, imgp, &cs_flags, &signer_type, flags, platform);
fe8ab488 4220 if (cs_debug && error) {
0a7de745 4221 printf("revalidate: check_signature[pid: %d], error = %d\n", current_proc()->p_pid, error);
fe8ab488 4222 }
39037602
A
4223#else
4224 (void)flags;
5ba3f43e 4225 (void)signer_type;
fe8ab488
A
4226#endif
4227
4228 /* update generation number if success */
4229 vnode_lock_spin(vp);
0a7de745 4230 blob->csb_flags = cs_flags;
5ba3f43e 4231 blob->csb_signer_type = signer_type;
fe8ab488 4232 if (UBCINFOEXISTS(vp)) {
0a7de745 4233 if (error == 0) {
fe8ab488 4234 vp->v_ubcinfo->cs_add_gen = cs_blob_generation_count;
0a7de745 4235 } else {
fe8ab488 4236 vp->v_ubcinfo->cs_add_gen = 0;
0a7de745 4237 }
fe8ab488
A
4238 }
4239
4240 vnode_unlock(vp);
4241
4242out:
4243 return error;
4244}
4245
4246void
4247cs_blob_reset_cache()
4248{
4249 /* incrementing odd no by 2 makes sure '0' is never reached. */
4250 OSAddAtomic(+2, &cs_blob_generation_count);
4251 printf("Reseting cs_blob cache from all vnodes. \n");
4252}
4253
2d21ac55
A
4254struct cs_blob *
4255ubc_get_cs_blobs(
0a7de745 4256 struct vnode *vp)
91447636 4257{
0a7de745
A
4258 struct ubc_info *uip;
4259 struct cs_blob *blobs;
2d21ac55 4260
b0d623f7
A
4261 /*
4262 * No need to take the vnode lock here. The caller must be holding
4263 * a reference on the vnode (via a VM mapping or open file descriptor),
4264 * so the vnode will not go away. The ubc_info stays until the vnode
4265 * goes away. And we only modify "blobs" by adding to the head of the
4266 * list.
4267 * The ubc_info could go away entirely if the vnode gets reclaimed as
4268 * part of a forced unmount. In the case of a code-signature validation
4269 * during a page fault, the "paging_in_progress" reference on the VM
4270 * object guarantess that the vnode pager (and the ubc_info) won't go
4271 * away during the fault.
4272 * Other callers need to protect against vnode reclaim by holding the
4273 * vnode lock, for example.
4274 */
2d21ac55 4275
0a7de745 4276 if (!UBCINFOEXISTS(vp)) {
2d21ac55
A
4277 blobs = NULL;
4278 goto out;
4279 }
4280
4281 uip = vp->v_ubcinfo;
4282 blobs = uip->cs_blobs;
4283
4284out:
2d21ac55 4285 return blobs;
91447636 4286}
2d21ac55 4287
f427ee49
A
4288#if CONFIG_SUPPLEMENTAL_SIGNATURES
4289struct cs_blob *
4290ubc_get_cs_supplement(
4291 struct vnode *vp)
4292{
4293 struct ubc_info *uip;
4294 struct cs_blob *blob;
4295
4296 /*
4297 * No need to take the vnode lock here. The caller must be holding
4298 * a reference on the vnode (via a VM mapping or open file descriptor),
4299 * so the vnode will not go away. The ubc_info stays until the vnode
4300 * goes away.
4301 * The ubc_info could go away entirely if the vnode gets reclaimed as
4302 * part of a forced unmount. In the case of a code-signature validation
4303 * during a page fault, the "paging_in_progress" reference on the VM
4304 * object guarantess that the vnode pager (and the ubc_info) won't go
4305 * away during the fault.
4306 * Other callers need to protect against vnode reclaim by holding the
4307 * vnode lock, for example.
4308 */
4309
4310 if (!UBCINFOEXISTS(vp)) {
4311 blob = NULL;
4312 goto out;
4313 }
4314
4315 uip = vp->v_ubcinfo;
4316 blob = uip->cs_blob_supplement;
4317
4318out:
4319 return blob;
4320}
4321#endif
4322
4323
15129b1c
A
4324void
4325ubc_get_cs_mtime(
0a7de745
A
4326 struct vnode *vp,
4327 struct timespec *cs_mtime)
15129b1c 4328{
0a7de745 4329 struct ubc_info *uip;
15129b1c 4330
0a7de745 4331 if (!UBCINFOEXISTS(vp)) {
15129b1c
A
4332 cs_mtime->tv_sec = 0;
4333 cs_mtime->tv_nsec = 0;
4334 return;
4335 }
4336
4337 uip = vp->v_ubcinfo;
4338 cs_mtime->tv_sec = uip->cs_mtime.tv_sec;
4339 cs_mtime->tv_nsec = uip->cs_mtime.tv_nsec;
4340}
4341
2d21ac55
A
4342unsigned long cs_validate_page_no_hash = 0;
4343unsigned long cs_validate_page_bad_hash = 0;
39037602
A
4344static boolean_t
4345cs_validate_hash(
0a7de745
A
4346 struct cs_blob *blobs,
4347 memory_object_t pager,
4348 memory_object_offset_t page_offset,
4349 const void *data,
4350 vm_size_t *bytes_processed,
4351 unsigned *tainted)
91447636 4352{
0a7de745
A
4353 union cs_hash_union mdctx;
4354 struct cs_hash const *hashtype = NULL;
4355 unsigned char actual_hash[CS_HASH_MAX_SIZE];
4356 unsigned char expected_hash[CS_HASH_MAX_SIZE];
4357 boolean_t found_hash;
4358 struct cs_blob *blob;
4359 const CS_CodeDirectory *cd;
4360 const unsigned char *hash;
4361 boolean_t validated;
4362 off_t offset; /* page offset in the file */
4363 size_t size;
4364 off_t codeLimit = 0;
4365 const char *lower_bound, *upper_bound;
4366 vm_offset_t kaddr, blob_addr;
2d21ac55
A
4367
4368 /* retrieve the expected hash */
4369 found_hash = FALSE;
2d21ac55
A
4370
4371 for (blob = blobs;
0a7de745
A
4372 blob != NULL;
4373 blob = blob->csb_next) {
2d21ac55
A
4374 offset = page_offset - blob->csb_base_offset;
4375 if (offset < blob->csb_start_offset ||
4376 offset >= blob->csb_end_offset) {
4377 /* our page is not covered by this blob */
4378 continue;
4379 }
4380
39037602 4381 /* blob data has been released */
2d21ac55
A
4382 kaddr = blob->csb_mem_kaddr;
4383 if (kaddr == 0) {
39037602 4384 continue;
2d21ac55 4385 }
39236c6e 4386
2d21ac55 4387 blob_addr = kaddr + blob->csb_mem_offset;
2d21ac55
A
4388 lower_bound = CAST_DOWN(char *, blob_addr);
4389 upper_bound = lower_bound + blob->csb_mem_size;
0a7de745 4390
490019cf 4391 cd = blob->csb_cd;
2d21ac55 4392 if (cd != NULL) {
3e170ce0 4393 /* all CD's that have been injected is already validated */
b0d623f7 4394
3e170ce0 4395 hashtype = blob->csb_hashtype;
0a7de745 4396 if (hashtype == NULL) {
3e170ce0 4397 panic("unknown hash type ?");
0a7de745
A
4398 }
4399 if (hashtype->cs_digest_size > sizeof(actual_hash)) {
3e170ce0 4400 panic("hash size too large");
0a7de745 4401 }
f427ee49 4402 if (offset & ((1U << blob->csb_hash_pageshift) - 1)) {
39037602 4403 panic("offset not aligned to cshash boundary");
0a7de745 4404 }
3e170ce0 4405
2d21ac55 4406 codeLimit = ntohl(cd->codeLimit);
39236c6e 4407
0a7de745
A
4408 hash = hashes(cd, (uint32_t)(offset >> blob->csb_hash_pageshift),
4409 hashtype->cs_size,
4410 lower_bound, upper_bound);
cf7d32b8 4411 if (hash != NULL) {
490019cf 4412 bcopy(hash, expected_hash, hashtype->cs_size);
cf7d32b8
A
4413 found_hash = TRUE;
4414 }
2d21ac55 4415
2d21ac55
A
4416 break;
4417 }
4418 }
4419
4420 if (found_hash == FALSE) {
4421 /*
4422 * We can't verify this page because there is no signature
4423 * for it (yet). It's possible that this part of the object
4424 * is not signed, or that signatures for that part have not
4425 * been loaded yet.
4426 * Report that the page has not been validated and let the
4427 * caller decide if it wants to accept it or not.
4428 */
4429 cs_validate_page_no_hash++;
4430 if (cs_debug > 1) {
4431 printf("CODE SIGNING: cs_validate_page: "
0a7de745
A
4432 "mobj %p off 0x%llx: no hash to validate !?\n",
4433 pager, page_offset);
2d21ac55
A
4434 }
4435 validated = FALSE;
c18c124e 4436 *tainted = 0;
2d21ac55 4437 } else {
c18c124e
A
4438 *tainted = 0;
4439
f427ee49 4440 size = (1U << blob->csb_hash_pageshift);
39037602
A
4441 *bytes_processed = size;
4442
fe8ab488 4443 const uint32_t *asha1, *esha1;
b0d623f7 4444 if ((off_t)(offset + size) > codeLimit) {
2d21ac55
A
4445 /* partial page at end of segment */
4446 assert(offset < codeLimit);
f427ee49 4447 size = (size_t) (codeLimit & (size - 1));
c18c124e 4448 *tainted |= CS_VALIDATE_NX;
2d21ac55 4449 }
3e170ce0
A
4450
4451 hashtype->cs_init(&mdctx);
39037602 4452
f427ee49 4453 if (blob->csb_hash_firstlevel_pageshift) {
39037602
A
4454 const unsigned char *partial_data = (const unsigned char *)data;
4455 size_t i;
0a7de745
A
4456 for (i = 0; i < size;) {
4457 union cs_hash_union partialctx;
39037602 4458 unsigned char partial_digest[CS_HASH_MAX_SIZE];
f427ee49 4459 size_t partial_size = MIN(size - i, (1U << blob->csb_hash_firstlevel_pageshift));
39037602
A
4460
4461 hashtype->cs_init(&partialctx);
4462 hashtype->cs_update(&partialctx, partial_data, partial_size);
4463 hashtype->cs_final(partial_digest, &partialctx);
4464
4465 /* Update cumulative multi-level hash */
4466 hashtype->cs_update(&mdctx, partial_digest, hashtype->cs_size);
4467 partial_data = partial_data + partial_size;
4468 i += partial_size;
4469 }
4470 } else {
4471 hashtype->cs_update(&mdctx, data, size);
4472 }
3e170ce0 4473 hashtype->cs_final(actual_hash, &mdctx);
2d21ac55 4474
fe8ab488
A
4475 asha1 = (const uint32_t *) actual_hash;
4476 esha1 = (const uint32_t *) expected_hash;
4477
490019cf 4478 if (bcmp(expected_hash, actual_hash, hashtype->cs_size) != 0) {
2d21ac55
A
4479 if (cs_debug) {
4480 printf("CODE SIGNING: cs_validate_page: "
0a7de745
A
4481 "mobj %p off 0x%llx size 0x%lx: "
4482 "actual [0x%x 0x%x 0x%x 0x%x 0x%x] != "
4483 "expected [0x%x 0x%x 0x%x 0x%x 0x%x]\n",
4484 pager, page_offset, size,
4485 asha1[0], asha1[1], asha1[2],
4486 asha1[3], asha1[4],
4487 esha1[0], esha1[1], esha1[2],
4488 esha1[3], esha1[4]);
2d21ac55
A
4489 }
4490 cs_validate_page_bad_hash++;
c18c124e 4491 *tainted |= CS_VALIDATE_TAINTED;
2d21ac55 4492 } else {
39236c6e 4493 if (cs_debug > 10) {
2d21ac55 4494 printf("CODE SIGNING: cs_validate_page: "
0a7de745
A
4495 "mobj %p off 0x%llx size 0x%lx: "
4496 "SHA1 OK\n",
4497 pager, page_offset, size);
2d21ac55 4498 }
2d21ac55
A
4499 }
4500 validated = TRUE;
4501 }
0a7de745 4502
2d21ac55 4503 return validated;
91447636
A
4504}
4505
39037602
A
4506boolean_t
4507cs_validate_range(
0a7de745
A
4508 struct vnode *vp,
4509 memory_object_t pager,
4510 memory_object_offset_t page_offset,
4511 const void *data,
4512 vm_size_t dsize,
4513 unsigned *tainted)
39037602
A
4514{
4515 vm_size_t offset_in_range;
4516 boolean_t all_subranges_validated = TRUE; /* turn false if any subrange fails */
4517
4518 struct cs_blob *blobs = ubc_get_cs_blobs(vp);
4519
f427ee49
A
4520#if CONFIG_SUPPLEMENTAL_SIGNATURES
4521 if (blobs == NULL && proc_is_translated(current_proc())) {
4522 struct cs_blob *supp = ubc_get_cs_supplement(vp);
4523
4524 if (supp != NULL) {
4525 blobs = supp;
4526 } else {
4527 return FALSE;
4528 }
4529 }
4530#endif
4531
4532
4533
39037602
A
4534 *tainted = 0;
4535
4536 for (offset_in_range = 0;
0a7de745
A
4537 offset_in_range < dsize;
4538 /* offset_in_range updated based on bytes processed */) {
39037602
A
4539 unsigned subrange_tainted = 0;
4540 boolean_t subrange_validated;
4541 vm_size_t bytes_processed = 0;
4542
4543 subrange_validated = cs_validate_hash(blobs,
0a7de745
A
4544 pager,
4545 page_offset + offset_in_range,
4546 (const void *)((const char *)data + offset_in_range),
4547 &bytes_processed,
4548 &subrange_tainted);
39037602
A
4549
4550 *tainted |= subrange_tainted;
4551
4552 if (bytes_processed == 0) {
4553 /* Cannote make forward progress, so return an error */
4554 all_subranges_validated = FALSE;
4555 break;
4556 } else if (subrange_validated == FALSE) {
4557 all_subranges_validated = FALSE;
4558 /* Keep going to detect other types of failures in subranges */
4559 }
4560
4561 offset_in_range += bytes_processed;
4562 }
4563
4564 return all_subranges_validated;
4565}
4566
f427ee49
A
4567void
4568cs_validate_page(
4569 struct vnode *vp,
4570 memory_object_t pager,
4571 memory_object_offset_t page_offset,
4572 const void *data,
4573 int *validated_p,
4574 int *tainted_p,
4575 int *nx_p)
4576{
4577 vm_size_t offset_in_page;
4578 struct cs_blob *blobs;
4579
4580 blobs = ubc_get_cs_blobs(vp);
4581
4582#if CONFIG_SUPPLEMENTAL_SIGNATURES
4583 if (blobs == NULL && proc_is_translated(current_proc())) {
4584 struct cs_blob *supp = ubc_get_cs_supplement(vp);
4585
4586 if (supp != NULL) {
4587 blobs = supp;
4588 }
4589 }
4590#endif
4591
4592 *validated_p = VMP_CS_ALL_FALSE;
4593 *tainted_p = VMP_CS_ALL_FALSE;
4594 *nx_p = VMP_CS_ALL_FALSE;
4595
4596 for (offset_in_page = 0;
4597 offset_in_page < PAGE_SIZE;
4598 /* offset_in_page updated based on bytes processed */) {
4599 unsigned subrange_tainted = 0;
4600 boolean_t subrange_validated;
4601 vm_size_t bytes_processed = 0;
4602 int sub_bit;
4603
4604 subrange_validated = cs_validate_hash(blobs,
4605 pager,
4606 page_offset + offset_in_page,
4607 (const void *)((const char *)data + offset_in_page),
4608 &bytes_processed,
4609 &subrange_tainted);
4610
4611 if (bytes_processed == 0) {
4612 /* 4k chunk not code-signed: try next one */
4613 offset_in_page += FOURK_PAGE_SIZE;
4614 continue;
4615 }
4616 if (offset_in_page == 0 &&
4617 bytes_processed > PAGE_SIZE - FOURK_PAGE_SIZE) {
4618 /* all processed: no 4k granularity */
4619 if (subrange_validated) {
4620 *validated_p = VMP_CS_ALL_TRUE;
4621 }
4622 if (subrange_tainted & CS_VALIDATE_TAINTED) {
4623 *tainted_p = VMP_CS_ALL_TRUE;
4624 }
4625 if (subrange_tainted & CS_VALIDATE_NX) {
4626 *nx_p = VMP_CS_ALL_TRUE;
4627 }
4628 break;
4629 }
4630 /* we only handle 4k or 16k code-signing granularity... */
4631 assertf(bytes_processed <= FOURK_PAGE_SIZE,
4632 "vp %p blobs %p offset 0x%llx + 0x%llx bytes_processed 0x%llx\n",
4633 vp, blobs, (uint64_t)page_offset,
4634 (uint64_t)offset_in_page, (uint64_t)bytes_processed);
4635 sub_bit = 1 << (offset_in_page >> FOURK_PAGE_SHIFT);
4636 if (subrange_validated) {
4637 *validated_p |= sub_bit;
4638 }
4639 if (subrange_tainted & CS_VALIDATE_TAINTED) {
4640 *tainted_p |= sub_bit;
4641 }
4642 if (subrange_tainted & CS_VALIDATE_NX) {
4643 *nx_p |= sub_bit;
4644 }
4645 /* go to next 4k chunk */
4646 offset_in_page += FOURK_PAGE_SIZE;
4647 }
4648
4649 return;
4650}
4651
2d21ac55
A
4652int
4653ubc_cs_getcdhash(
0a7de745
A
4654 vnode_t vp,
4655 off_t offset,
4656 unsigned char *cdhash)
2d21ac55 4657{
0a7de745
A
4658 struct cs_blob *blobs, *blob;
4659 off_t rel_offset;
4660 int ret;
b0d623f7
A
4661
4662 vnode_lock(vp);
2d21ac55
A
4663
4664 blobs = ubc_get_cs_blobs(vp);
4665 for (blob = blobs;
0a7de745
A
4666 blob != NULL;
4667 blob = blob->csb_next) {
2d21ac55
A
4668 /* compute offset relative to this blob */
4669 rel_offset = offset - blob->csb_base_offset;
4670 if (rel_offset >= blob->csb_start_offset &&
4671 rel_offset < blob->csb_end_offset) {
4672 /* this blob does cover our "offset" ! */
4673 break;
4674 }
4675 }
4676
4677 if (blob == NULL) {
4678 /* we didn't find a blob covering "offset" */
b0d623f7
A
4679 ret = EBADEXEC; /* XXX any better error ? */
4680 } else {
4681 /* get the SHA1 hash of that blob */
f427ee49
A
4682 ptrauth_utils_auth_blob_generic(blob->csb_cdhash,
4683 sizeof(blob->csb_cdhash),
4684 OS_PTRAUTH_DISCRIMINATOR("cs_blob.csb_cd_signature"),
4685 PTRAUTH_ADDR_DIVERSIFY,
4686 blob->csb_cdhash_signature);
0a7de745 4687 bcopy(blob->csb_cdhash, cdhash, sizeof(blob->csb_cdhash));
b0d623f7 4688 ret = 0;
2d21ac55
A
4689 }
4690
b0d623f7 4691 vnode_unlock(vp);
2d21ac55 4692
b0d623f7 4693 return ret;
2d21ac55 4694}
6d2010ae 4695
39037602
A
4696boolean_t
4697ubc_cs_is_range_codesigned(
0a7de745
A
4698 vnode_t vp,
4699 mach_vm_offset_t start,
4700 mach_vm_size_t size)
39037602 4701{
0a7de745
A
4702 struct cs_blob *csblob;
4703 mach_vm_offset_t blob_start;
4704 mach_vm_offset_t blob_end;
39037602
A
4705
4706 if (vp == NULL) {
4707 /* no file: no code signature */
4708 return FALSE;
4709 }
4710 if (size == 0) {
4711 /* no range: no code signature */
4712 return FALSE;
4713 }
4714 if (start + size < start) {
4715 /* overflow */
4716 return FALSE;
4717 }
4718
f427ee49 4719 csblob = ubc_cs_blob_get(vp, -1, -1, start);
39037602
A
4720 if (csblob == NULL) {
4721 return FALSE;
4722 }
4723
4724 /*
4725 * We currently check if the range is covered by a single blob,
4726 * which should always be the case for the dyld shared cache.
4727 * If we ever want to make this routine handle other cases, we
4728 * would have to iterate if the blob does not cover the full range.
4729 */
4730 blob_start = (mach_vm_offset_t) (csblob->csb_base_offset +
0a7de745 4731 csblob->csb_start_offset);
39037602 4732 blob_end = (mach_vm_offset_t) (csblob->csb_base_offset +
0a7de745 4733 csblob->csb_end_offset);
39037602
A
4734 if (blob_start > start || blob_end < (start + size)) {
4735 /* range not fully covered by this code-signing blob */
4736 return FALSE;
4737 }
4738
4739 return TRUE;
4740}
4741
6d2010ae 4742#if CHECK_CS_VALIDATION_BITMAP
0a7de745
A
4743#define stob(s) (((atop_64(round_page_64(s))) + 07) >> 3)
4744extern boolean_t root_fs_upgrade_try;
6d2010ae
A
4745
4746/*
4747 * Should we use the code-sign bitmap to avoid repeated code-sign validation?
4748 * Depends:
4749 * a) Is the target vnode on the root filesystem?
4750 * b) Has someone tried to mount the root filesystem read-write?
4751 * If answers are (a) yes AND (b) no, then we can use the bitmap.
4752 */
0a7de745 4753#define USE_CODE_SIGN_BITMAP(vp) ( (vp != NULL) && (vp->v_mount != NULL) && (vp->v_mount->mnt_flag & MNT_ROOTFS) && !root_fs_upgrade_try)
6d2010ae
A
4754kern_return_t
4755ubc_cs_validation_bitmap_allocate(
0a7de745 4756 vnode_t vp)
6d2010ae 4757{
0a7de745 4758 kern_return_t kr = KERN_SUCCESS;
6d2010ae 4759 struct ubc_info *uip;
0a7de745
A
4760 char *target_bitmap;
4761 vm_object_size_t bitmap_size;
6d2010ae 4762
0a7de745 4763 if (!USE_CODE_SIGN_BITMAP(vp) || (!UBCINFOEXISTS(vp))) {
6d2010ae
A
4764 kr = KERN_INVALID_ARGUMENT;
4765 } else {
4766 uip = vp->v_ubcinfo;
4767
0a7de745 4768 if (uip->cs_valid_bitmap == NULL) {
6d2010ae 4769 bitmap_size = stob(uip->ui_size);
0a7de745 4770 target_bitmap = (char*) kalloc((vm_size_t)bitmap_size );
6d2010ae
A
4771 if (target_bitmap == 0) {
4772 kr = KERN_NO_SPACE;
4773 } else {
4774 kr = KERN_SUCCESS;
4775 }
0a7de745 4776 if (kr == KERN_SUCCESS) {
6d2010ae
A
4777 memset( target_bitmap, 0, (size_t)bitmap_size);
4778 uip->cs_valid_bitmap = (void*)target_bitmap;
4779 uip->cs_valid_bitmap_size = bitmap_size;
4780 }
4781 }
4782 }
4783 return kr;
4784}
4785
4786kern_return_t
0a7de745
A
4787ubc_cs_check_validation_bitmap(
4788 vnode_t vp,
4789 memory_object_offset_t offset,
4790 int optype)
6d2010ae 4791{
0a7de745 4792 kern_return_t kr = KERN_SUCCESS;
6d2010ae 4793
0a7de745 4794 if (!USE_CODE_SIGN_BITMAP(vp) || !UBCINFOEXISTS(vp)) {
6d2010ae
A
4795 kr = KERN_INVALID_ARGUMENT;
4796 } else {
4797 struct ubc_info *uip = vp->v_ubcinfo;
0a7de745 4798 char *target_bitmap = uip->cs_valid_bitmap;
6d2010ae 4799
0a7de745
A
4800 if (target_bitmap == NULL) {
4801 kr = KERN_INVALID_ARGUMENT;
6d2010ae 4802 } else {
0a7de745 4803 uint64_t bit, byte;
6d2010ae
A
4804 bit = atop_64( offset );
4805 byte = bit >> 3;
4806
0a7de745
A
4807 if (byte > uip->cs_valid_bitmap_size) {
4808 kr = KERN_INVALID_ARGUMENT;
6d2010ae 4809 } else {
6d2010ae
A
4810 if (optype == CS_BITMAP_SET) {
4811 target_bitmap[byte] |= (1 << (bit & 07));
4812 kr = KERN_SUCCESS;
4813 } else if (optype == CS_BITMAP_CLEAR) {
4814 target_bitmap[byte] &= ~(1 << (bit & 07));
4815 kr = KERN_SUCCESS;
4816 } else if (optype == CS_BITMAP_CHECK) {
0a7de745 4817 if (target_bitmap[byte] & (1 << (bit & 07))) {
6d2010ae
A
4818 kr = KERN_SUCCESS;
4819 } else {
4820 kr = KERN_FAILURE;
4821 }
4822 }
4823 }
4824 }
4825 }
4826 return kr;
4827}
4828
4829void
4830ubc_cs_validation_bitmap_deallocate(
0a7de745 4831 vnode_t vp)
6d2010ae
A
4832{
4833 struct ubc_info *uip;
0a7de745
A
4834 void *target_bitmap;
4835 vm_object_size_t bitmap_size;
6d2010ae 4836
0a7de745 4837 if (UBCINFOEXISTS(vp)) {
6d2010ae
A
4838 uip = vp->v_ubcinfo;
4839
0a7de745 4840 if ((target_bitmap = uip->cs_valid_bitmap) != NULL) {
6d2010ae
A
4841 bitmap_size = uip->cs_valid_bitmap_size;
4842 kfree( target_bitmap, (vm_size_t) bitmap_size );
4843 uip->cs_valid_bitmap = NULL;
4844 }
4845 }
4846}
4847#else
0a7de745
A
4848kern_return_t
4849ubc_cs_validation_bitmap_allocate(__unused vnode_t vp)
4850{
6d2010ae
A
4851 return KERN_INVALID_ARGUMENT;
4852}
4853
0a7de745
A
4854kern_return_t
4855ubc_cs_check_validation_bitmap(
4856 __unused struct vnode *vp,
6d2010ae 4857 __unused memory_object_offset_t offset,
0a7de745
A
4858 __unused int optype)
4859{
6d2010ae
A
4860 return KERN_INVALID_ARGUMENT;
4861}
4862
0a7de745
A
4863void
4864ubc_cs_validation_bitmap_deallocate(__unused vnode_t vp)
4865{
6d2010ae
A
4866 return;
4867}
4868#endif /* CHECK_CS_VALIDATION_BITMAP */
d9a64523 4869