xref: /xnu-8020.101.4/bsd/vfs/vfs_cprotect.c (revision e7776783b89a353188416a9a346c6cdb4928faad)
1 /*
2  * Copyright (c) 2015-2018 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 
29 #include <sys/cprotect.h>
30 #include <sys/malloc.h>
31 #include <sys/mount_internal.h>
32 #include <sys/filio.h>
33 #include <sys/content_protection.h>
34 #include <libkern/crypto/sha1.h>
35 #include <libkern/libkern.h>
36 //for write protection
37 #include <vm/vm_kern.h>
38 #include <vm/vm_map.h>
39 
40 #define PTR_ADD(type, base, offset)             (type)((uintptr_t)(base) + (offset))
41 
42 // -- struct cpx --
43 
44 /*
45  * This structure contains the unwrapped key and is passed to the lower layers.
46  * It is private so users must use the accessors declared in sys/cprotect.h
47  * to read/write it.
48  */
49 
50 // cpx_flags defined in cprotect.h
51 enum {
52 	CPX_SEP_WRAPPEDKEY                      = 0x01,
53 	CPX_IV_AES_CTX_INITIALIZED      = 0x02,
54 	CPX_USE_OFFSET_FOR_IV           = 0x04,
55 
56 	// Using AES IV context generated from key
57 	CPX_IV_AES_CTX_VFS                      = 0x08,
58 	CPX_SYNTHETIC_OFFSET_FOR_IV = 0x10,
59 	CPX_COMPOSITEKEY            = 0x20,
60 
61 	//write page protection
62 	CPX_WRITE_PROTECTABLE           = 0x40
63 };
64 
65 /*
66  * variable-length CPX structure. See fixed-length variant in cprotect.h
67  */
68 struct cpx {
69 #if DEBUG
70 	uint32_t                cpx_magic1;
71 #endif
72 	aes_encrypt_ctx         *cpx_iv_aes_ctx_ptr;// Pointer to context used for generating the IV
73 	cpx_flags_t             cpx_flags;
74 	uint16_t                cpx_max_key_len;
75 	uint16_t                cpx_key_len;
76 	//fixed length up to here.  cpx_cached_key is variable-length
77 	uint8_t                 cpx_cached_key[];
78 };
79 
80 /* Allows us to switch between CPX types */
81 typedef union cpxunion {
82 	struct cpx cpx_var;
83 	fcpx_t cpx_fixed;
84 } cpxunion_t;
85 
86 ZONE_DEFINE(cpx_zone, "cpx",
87     sizeof(struct fcpx), ZC_ZFREE_CLEARMEM);
88 ZONE_DEFINE(aes_ctz_zone, "AES ctx",
89     sizeof(aes_encrypt_ctx), ZC_ZFREE_CLEARMEM);
90 
91 // Note: see struct fcpx defined in sys/cprotect.h
92 
93 // -- cpx_t accessors --
94 
95 size_t
cpx_size(size_t key_len)96 cpx_size(size_t key_len)
97 {
98 	// This should pick up the 'magic' word in DEBUG for free.
99 	size_t size = sizeof(struct cpx) + key_len;
100 
101 	return size;
102 }
103 
104 size_t
cpx_sizex(const struct cpx * cpx)105 cpx_sizex(const struct cpx *cpx)
106 {
107 	return cpx_size(cpx->cpx_max_key_len);
108 }
109 
110 cpx_t
cpx_alloc(size_t key_len,bool needs_ctx)111 cpx_alloc(size_t key_len, bool needs_ctx)
112 {
113 	cpx_t cpx = NULL;
114 
115 #if CONFIG_KEYPAGE_WP
116 	/*
117 	 * Macs only use 1 key per volume, so force it into its own page.
118 	 * This way, we can write-protect as needed.
119 	 */
120 	size_t cpsize = cpx_size(key_len);
121 
122 	// silence warning for needs_ctx
123 	(void) needs_ctx;
124 
125 	if (cpsize < PAGE_SIZE) {
126 		/*
127 		 * Don't use MALLOC to allocate the page-sized structure.  Instead,
128 		 * use kmem_alloc to bypass KASAN since we are supplying our own
129 		 * unilateral write protection on this page. Note that kmem_alloc
130 		 * can block.
131 		 */
132 		if (kmem_alloc(kernel_map, (vm_offset_t *)&cpx, PAGE_SIZE, VM_KERN_MEMORY_FILE)) {
133 			/*
134 			 * returning NULL at this point (due to failed
135 			 * allocation) would just result in a panic.
136 			 *
137 			 * fall back to attempting a normal kalloc, and don't
138 			 * let the cpx get marked PROTECTABLE.
139 			 */
140 			cpx = kheap_alloc(KHEAP_DEFAULT, cpx_size(key_len), Z_WAITOK);
141 		} else {
142 			//mark the page as protectable, since kmem_alloc succeeded.
143 			cpx->cpx_flags |= CPX_WRITE_PROTECTABLE;
144 		}
145 	} else {
146 		panic("cpx_size too large ! (%lu)", cpsize);
147 	}
148 #else
149 	/* If key page write protection disabled, just switch to zalloc */
150 
151 	// error out if you try to request a key that's too big
152 	if (key_len > VFS_CP_MAX_CACHEBUFLEN) {
153 		return NULL;
154 	}
155 
156 	// the actual key array is fixed-length, but the amount of usable content can vary, via 'key_len'
157 	cpx = zalloc_flags(cpx_zone, Z_WAITOK | Z_ZERO);
158 
159 	// if our encryption type needs it, alloc the context
160 	if (needs_ctx) {
161 		cpx_alloc_ctx(cpx);
162 	}
163 
164 #endif
165 	cpx_init(cpx, key_len);
166 
167 	return cpx;
168 }
169 
170 int
cpx_alloc_ctx(cpx_t cpx)171 cpx_alloc_ctx(cpx_t cpx)
172 {
173 #if CONFIG_KEYPAGE_WP
174 	(void) cpx;
175 #else
176 	if (cpx->cpx_iv_aes_ctx_ptr) {
177 		// already allocated?
178 		return 0;
179 	}
180 
181 	cpx->cpx_iv_aes_ctx_ptr = zalloc_flags(aes_ctz_zone, Z_WAITOK | Z_ZERO);
182 #endif // CONFIG_KEYPAGE_WP
183 
184 	return 0;
185 }
186 
187 void
cpx_free_ctx(cpx_t cpx)188 cpx_free_ctx(cpx_t cpx)
189 {
190 #if CONFIG_KEYPAGE_WP
191 	(void) cpx;
192 # else
193 	if (cpx->cpx_iv_aes_ctx_ptr) {
194 		zfree(aes_ctz_zone, cpx->cpx_iv_aes_ctx_ptr);
195 	}
196 #endif // CONFIG_KEYPAGE_WP
197 }
198 
199 void
cpx_writeprotect(cpx_t cpx)200 cpx_writeprotect(cpx_t cpx)
201 {
202 #if CONFIG_KEYPAGE_WP
203 	void *cpxstart = (void*)cpx;
204 	void *cpxend = (void*)((uint8_t*)cpx + PAGE_SIZE);
205 	if (cpx->cpx_flags & CPX_WRITE_PROTECTABLE) {
206 		vm_map_protect(kernel_map, (vm_map_offset_t)cpxstart, (vm_map_offset_t)cpxend, (VM_PROT_READ), FALSE);
207 	}
208 #else
209 	(void) cpx;
210 #endif
211 	return;
212 }
213 
214 #if DEBUG
215 static const uint32_t cpx_magic1 = 0x7b787063;          // cpx{
216 static const uint32_t cpx_magic2 = 0x7870637d;          // }cpx
217 #endif
218 
219 void
cpx_free(cpx_t cpx)220 cpx_free(cpx_t cpx)
221 {
222 #if DEBUG
223 	assert(cpx->cpx_magic1 == cpx_magic1);
224 	assert(*PTR_ADD(uint32_t *, cpx, cpx_sizex(cpx) - 4) == cpx_magic2);
225 #endif
226 
227 #if CONFIG_KEYPAGE_WP
228 	/* unprotect the page before bzeroing */
229 	void *cpxstart = (void*)cpx;
230 	void *cpxend = (void*)((uint8_t*)cpx + PAGE_SIZE);
231 	if (cpx->cpx_flags & CPX_WRITE_PROTECTABLE) {
232 		vm_map_protect(kernel_map, (vm_map_offset_t)cpxstart, (vm_map_offset_t)cpxend, (VM_PROT_DEFAULT), FALSE);
233 
234 		//now zero the memory after un-protecting it
235 		bzero(cpx->cpx_cached_key, cpx->cpx_max_key_len);
236 
237 		//If we are here, then we used kmem_alloc to get the page. Must use kmem_free to drop it.
238 		kmem_free(kernel_map, (vm_offset_t)cpx, PAGE_SIZE);
239 		return;
240 	}
241 #else
242 	// free the context if it wasn't already freed
243 	cpx_free_ctx(cpx);
244 	zfree(cpx_zone, cpx);
245 	return;
246 #endif
247 }
248 
249 void
cpx_init(cpx_t cpx,size_t key_len)250 cpx_init(cpx_t cpx, size_t key_len)
251 {
252 #if DEBUG
253 	cpx->cpx_magic1 = cpx_magic1;
254 	*PTR_ADD(uint32_t *, cpx, cpx_size(key_len) - 4) = cpx_magic2;
255 #endif
256 	cpx->cpx_flags = 0;
257 	cpx->cpx_key_len = 0;
258 	assert(key_len <= UINT16_MAX);
259 	cpx->cpx_max_key_len = (uint16_t)key_len;
260 }
261 
262 bool
cpx_is_sep_wrapped_key(const struct cpx * cpx)263 cpx_is_sep_wrapped_key(const struct cpx *cpx)
264 {
265 	return ISSET(cpx->cpx_flags, CPX_SEP_WRAPPEDKEY);
266 }
267 
268 void
cpx_set_is_sep_wrapped_key(struct cpx * cpx,bool v)269 cpx_set_is_sep_wrapped_key(struct cpx *cpx, bool v)
270 {
271 	if (v) {
272 		SET(cpx->cpx_flags, CPX_SEP_WRAPPEDKEY);
273 	} else {
274 		CLR(cpx->cpx_flags, CPX_SEP_WRAPPEDKEY);
275 	}
276 }
277 
278 bool
cpx_is_composite_key(const struct cpx * cpx)279 cpx_is_composite_key(const struct cpx *cpx)
280 {
281 	return ISSET(cpx->cpx_flags, CPX_COMPOSITEKEY);
282 }
283 
284 void
cpx_set_is_composite_key(struct cpx * cpx,bool v)285 cpx_set_is_composite_key(struct cpx *cpx, bool v)
286 {
287 	if (v) {
288 		SET(cpx->cpx_flags, CPX_COMPOSITEKEY);
289 	} else {
290 		CLR(cpx->cpx_flags, CPX_COMPOSITEKEY);
291 	}
292 }
293 
294 bool
cpx_use_offset_for_iv(const struct cpx * cpx)295 cpx_use_offset_for_iv(const struct cpx *cpx)
296 {
297 	return ISSET(cpx->cpx_flags, CPX_USE_OFFSET_FOR_IV);
298 }
299 
300 void
cpx_set_use_offset_for_iv(struct cpx * cpx,bool v)301 cpx_set_use_offset_for_iv(struct cpx *cpx, bool v)
302 {
303 	if (v) {
304 		SET(cpx->cpx_flags, CPX_USE_OFFSET_FOR_IV);
305 	} else {
306 		CLR(cpx->cpx_flags, CPX_USE_OFFSET_FOR_IV);
307 	}
308 }
309 
310 bool
cpx_synthetic_offset_for_iv(const struct cpx * cpx)311 cpx_synthetic_offset_for_iv(const struct cpx *cpx)
312 {
313 	return ISSET(cpx->cpx_flags, CPX_SYNTHETIC_OFFSET_FOR_IV);
314 }
315 
316 void
cpx_set_synthetic_offset_for_iv(struct cpx * cpx,bool v)317 cpx_set_synthetic_offset_for_iv(struct cpx *cpx, bool v)
318 {
319 	if (v) {
320 		SET(cpx->cpx_flags, CPX_SYNTHETIC_OFFSET_FOR_IV);
321 	} else {
322 		CLR(cpx->cpx_flags, CPX_SYNTHETIC_OFFSET_FOR_IV);
323 	}
324 }
325 
326 uint16_t
cpx_max_key_len(const struct cpx * cpx)327 cpx_max_key_len(const struct cpx *cpx)
328 {
329 	return cpx->cpx_max_key_len;
330 }
331 
332 uint16_t
cpx_key_len(const struct cpx * cpx)333 cpx_key_len(const struct cpx *cpx)
334 {
335 	return cpx->cpx_key_len;
336 }
337 
338 void
cpx_set_key_len(struct cpx * cpx,uint16_t key_len)339 cpx_set_key_len(struct cpx *cpx, uint16_t key_len)
340 {
341 	cpx->cpx_key_len = key_len;
342 
343 	if (ISSET(cpx->cpx_flags, CPX_IV_AES_CTX_VFS)) {
344 		/*
345 		 * We assume that if the key length is being modified, the key
346 		 * has changed.  As a result, un-set any bits related to the
347 		 * AES context, if needed. They should be re-generated
348 		 * on-demand.
349 		 */
350 		CLR(cpx->cpx_flags, CPX_IV_AES_CTX_INITIALIZED | CPX_IV_AES_CTX_VFS);
351 	}
352 }
353 
354 bool
cpx_has_key(const struct cpx * cpx)355 cpx_has_key(const struct cpx *cpx)
356 {
357 	return cpx->cpx_key_len > 0;
358 }
359 
360 #pragma clang diagnostic push
361 #pragma clang diagnostic ignored "-Wcast-qual"
362 void *
cpx_key(const struct cpx * cpx)363 cpx_key(const struct cpx *cpx)
364 {
365 	return (void *)cpx->cpx_cached_key;
366 }
367 #pragma clang diagnostic pop
368 
369 void
cpx_set_aes_iv_key(struct cpx * cpx,void * iv_key)370 cpx_set_aes_iv_key(struct cpx *cpx, void *iv_key)
371 {
372 	if (cpx->cpx_iv_aes_ctx_ptr) {
373 		aes_encrypt_key128(iv_key, cpx->cpx_iv_aes_ctx_ptr);
374 		SET(cpx->cpx_flags, CPX_IV_AES_CTX_INITIALIZED | CPX_USE_OFFSET_FOR_IV);
375 		CLR(cpx->cpx_flags, CPX_IV_AES_CTX_VFS);
376 	}
377 }
378 
379 aes_encrypt_ctx *
cpx_iv_aes_ctx(struct cpx * cpx)380 cpx_iv_aes_ctx(struct cpx *cpx)
381 {
382 	if (ISSET(cpx->cpx_flags, CPX_IV_AES_CTX_INITIALIZED)) {
383 		return cpx->cpx_iv_aes_ctx_ptr;
384 	}
385 
386 	SHA1_CTX sha1ctxt;
387 	uint8_t digest[SHA_DIGEST_LENGTH]; /* Kiv */
388 
389 	/* First init the cp_cache_iv_key[] */
390 	SHA1Init(&sha1ctxt);
391 
392 	/*
393 	 * We can only use this when the keys are generated in the AP; As a result
394 	 * we only use the first 32 bytes of key length in the cache key
395 	 */
396 	SHA1Update(&sha1ctxt, cpx->cpx_cached_key, cpx->cpx_key_len);
397 	SHA1Final(digest, &sha1ctxt);
398 
399 	cpx_set_aes_iv_key(cpx, digest);
400 	SET(cpx->cpx_flags, CPX_IV_AES_CTX_VFS);
401 
402 	return cpx->cpx_iv_aes_ctx_ptr;
403 }
404 
405 void
cpx_flush(cpx_t cpx)406 cpx_flush(cpx_t cpx)
407 {
408 	bzero(cpx->cpx_cached_key, cpx->cpx_max_key_len);
409 	if (cpx->cpx_iv_aes_ctx_ptr) {
410 		bzero(cpx->cpx_iv_aes_ctx_ptr, sizeof(aes_encrypt_ctx));
411 	}
412 	cpx->cpx_flags = 0;
413 	cpx->cpx_key_len = 0;
414 }
415 
416 bool
cpx_can_copy(const struct cpx * src,const struct cpx * dst)417 cpx_can_copy(const struct cpx *src, const struct cpx *dst)
418 {
419 	return src->cpx_key_len <= dst->cpx_max_key_len;
420 }
421 
422 void
cpx_copy(const struct cpx * src,cpx_t dst)423 cpx_copy(const struct cpx *src, cpx_t dst)
424 {
425 	uint16_t key_len = cpx_key_len(src);
426 	cpx_set_key_len(dst, key_len);
427 	memcpy(cpx_key(dst), cpx_key(src), key_len);
428 	dst->cpx_flags = src->cpx_flags;
429 	if (ISSET(dst->cpx_flags, CPX_IV_AES_CTX_INITIALIZED)) {
430 		*(dst->cpx_iv_aes_ctx_ptr) = *(src->cpx_iv_aes_ctx_ptr); // deep copy
431 	}
432 }
433 
434 typedef struct {
435 	cp_lock_state_t state;
436 	int             valid_uuid;
437 	uuid_t          volume_uuid;
438 } cp_lock_vfs_callback_arg;
439 
440 static int
cp_lock_vfs_callback(mount_t mp,void * arg)441 cp_lock_vfs_callback(mount_t mp, void *arg)
442 {
443 	cp_lock_vfs_callback_arg *callback_arg = (cp_lock_vfs_callback_arg *)arg;
444 
445 	if (callback_arg->valid_uuid) {
446 		struct vfs_attr va;
447 		VFSATTR_INIT(&va);
448 		VFSATTR_WANTED(&va, f_uuid);
449 
450 		if (vfs_getattr(mp, &va, vfs_context_current())) {
451 			return 0;
452 		}
453 
454 		if (!VFSATTR_IS_SUPPORTED(&va, f_uuid)) {
455 			return 0;
456 		}
457 
458 		if (memcmp(va.f_uuid, callback_arg->volume_uuid, sizeof(uuid_t))) {
459 			return 0;
460 		}
461 	}
462 
463 	VFS_IOCTL(mp, FIODEVICELOCKED, (void *)(uintptr_t)callback_arg->state, 0, vfs_context_kernel());
464 	return 0;
465 }
466 
467 int
cp_key_store_action(cp_key_store_action_t action)468 cp_key_store_action(cp_key_store_action_t action)
469 {
470 	cp_lock_vfs_callback_arg callback_arg;
471 
472 	switch (action) {
473 	case CP_ACTION_LOCKED:
474 	case CP_ACTION_UNLOCKED:
475 		callback_arg.state = (action == CP_ACTION_LOCKED ? CP_LOCKED_STATE : CP_UNLOCKED_STATE);
476 		memset(callback_arg.volume_uuid, 0, sizeof(uuid_t));
477 		callback_arg.valid_uuid = 0;
478 		return vfs_iterate(0, cp_lock_vfs_callback, (void *)&callback_arg);
479 	default:
480 		return -1;
481 	}
482 }
483 
484 int
cp_key_store_action_for_volume(uuid_t volume_uuid,cp_key_store_action_t action)485 cp_key_store_action_for_volume(uuid_t volume_uuid, cp_key_store_action_t action)
486 {
487 	cp_lock_vfs_callback_arg callback_arg;
488 
489 	switch (action) {
490 	case CP_ACTION_LOCKED:
491 	case CP_ACTION_UNLOCKED:
492 		callback_arg.state = (action == CP_ACTION_LOCKED ? CP_LOCKED_STATE : CP_UNLOCKED_STATE);
493 		memcpy(callback_arg.volume_uuid, volume_uuid, sizeof(uuid_t));
494 		callback_arg.valid_uuid = 1;
495 		return vfs_iterate(0, cp_lock_vfs_callback, (void *)&callback_arg);
496 	default:
497 		return -1;
498 	}
499 }
500 
501 int
cp_is_valid_class(int isdir,int32_t protectionclass)502 cp_is_valid_class(int isdir, int32_t protectionclass)
503 {
504 	/*
505 	 * The valid protection classes are from 0 -> N
506 	 * We use a signed argument to detect unassigned values from
507 	 * directory entry creation time in HFS.
508 	 */
509 	if (isdir) {
510 		/* Directories are not allowed to have F, but they can have "NONE" */
511 		return (protectionclass >= PROTECTION_CLASS_DIR_NONE) &&
512 		       (protectionclass <= PROTECTION_CLASS_D);
513 	} else {
514 		return (protectionclass >= PROTECTION_CLASS_A) &&
515 		       (protectionclass <= PROTECTION_CLASS_F);
516 	}
517 }
518 
519 /*
520  * Parses versions of the form 12A316, i.e. <major><minor><revision> and
521  * returns a uint32_t in the form 0xaabbcccc where aa = <major>,
522  * bb = <ASCII char>, cccc = <revision>.
523  */
524 static cp_key_os_version_t
parse_os_version(const char * vers)525 parse_os_version(const char *vers)
526 {
527 	const char *p = vers;
528 
529 	int a = 0;
530 	while (*p >= '0' && *p <= '9') {
531 		a = a * 10 + *p - '0';
532 		++p;
533 	}
534 
535 	if (!a) {
536 		return 0;
537 	}
538 
539 	int b = *p++;
540 	if (!b) {
541 		return 0;
542 	}
543 
544 	int c = 0;
545 	while (*p >= '0' && *p <= '9') {
546 		c = c * 10 + *p - '0';
547 		++p;
548 	}
549 
550 	if (!c) {
551 		return 0;
552 	}
553 
554 	return (a & 0xff) << 24 | b << 16 | (c & 0xffff);
555 }
556 
557 cp_key_os_version_t
cp_os_version(void)558 cp_os_version(void)
559 {
560 	static cp_key_os_version_t cp_os_version;
561 
562 	if (cp_os_version) {
563 		return cp_os_version;
564 	}
565 
566 	if (!osversion[0]) {
567 		return 0;
568 	}
569 
570 	cp_os_version = parse_os_version(osversion);
571 	if (!cp_os_version) {
572 		printf("cp_os_version: unable to parse osversion `%s'\n", osversion);
573 		cp_os_version = 1;
574 	}
575 
576 	return cp_os_version;
577 }
578