2 * Copyright (c) 2000-2015 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
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.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
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.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
30 #include <sys/mount.h>
31 #include <sys/random.h>
32 #include <sys/xattr.h>
33 #include <sys/vnode_if.h>
34 #include <sys/fcntl.h>
35 #include <libkern/OSByteOrder.h>
36 #include <libkern/crypto/sha1.h>
38 #include <sys/kauth.h>
39 #include <sys/sysctl.h>
41 #include <uuid/uuid.h>
44 #include "hfs_cnode.h"
45 #include "hfs_fsctl.h"
46 #include "hfs_cprotect.h"
47 #include "hfs_iokit.h"
49 #if HFS_CONFIG_KEY_ROLL
50 #include "hfs_key_roll.h"
53 #define PTR_ADD(type, base, offset) (type)((uintptr_t)(base) + (offset))
55 extern int (**hfs_vnodeop_p
) (void *);
58 * CP private functions
60 static int cp_root_major_vers(mount_t mp
);
61 static int cp_getxattr(cnode_t
*, struct hfsmount
*hfsmp
, struct cprotect
**);
62 static void cp_entry_dealloc(hfsmount_t
*hfsmp
, struct cprotect
*entry
);
63 static int cp_restore_keys(struct cprotect
*, struct hfsmount
*hfsmp
, struct cnode
*);
64 static int cp_lock_vnode_callback(vnode_t
, void *);
65 static int cp_vnode_is_eligible (vnode_t
);
66 static int cp_check_access (cnode_t
*cp
, struct hfsmount
*hfsmp
, int vnop
);
67 static int cp_unwrap(struct hfsmount
*, struct cprotect
*, struct cnode
*);
68 static void cp_init_access(aks_cred_t access
, struct cnode
*cp
);
70 // -- cp_key_pair accessors --
72 void cpkp_init(cp_key_pair_t
*cpkp
, uint16_t max_pers_key_len
,
73 uint16_t max_cached_key_len
)
75 cpkp
->cpkp_max_pers_key_len
= max_pers_key_len
;
76 cpkp
->cpkp_pers_key_len
= 0;
77 cpx_init(cpkp_cpx(cpkp
), max_cached_key_len
);
79 // Default to using offsets
80 cpx_set_use_offset_for_iv(cpkp_cpx(cpkp
), true);
83 uint16_t cpkp_max_pers_key_len(const cp_key_pair_t
*cpkp
)
85 return cpkp
->cpkp_max_pers_key_len
;
88 uint16_t cpkp_pers_key_len(const cp_key_pair_t
*cpkp
)
90 return cpkp
->cpkp_pers_key_len
;
93 static bool cpkp_has_pers_key(const cp_key_pair_t
*cpkp
)
95 return cpkp
->cpkp_pers_key_len
> 0;
98 static void *cpkp_pers_key(const cp_key_pair_t
*cpkp
)
100 return PTR_ADD(void *, &cpkp
->cpkp_cpx
, cpx_sizex(cpkp_cpx(cpkp
)));
103 static void cpkp_set_pers_key_len(cp_key_pair_t
*cpkp
, uint16_t key_len
)
105 if (key_len
> cpkp
->cpkp_max_pers_key_len
)
106 panic("hfs_cprotect: key too big!");
107 cpkp
->cpkp_pers_key_len
= key_len
;
110 #pragma clang diagnostic push
111 #pragma clang diagnostic ignored "-Wcast-qual"
112 cpx_t
cpkp_cpx(const cp_key_pair_t
*cpkp
)
114 // Cast to remove const qualifier
115 return (cpx_t
)&cpkp
->cpkp_cpx
;
117 #pragma clang diagnostic pop
119 size_t cpkp_size(uint16_t pers_key_len
, uint16_t cached_key_len
)
121 return sizeof(cp_key_pair_t
) + pers_key_len
+ cpx_size(cached_key_len
);
124 size_t cpkp_sizex(const cp_key_pair_t
*cpkp
)
126 return cpkp_size(cpkp
->cpkp_max_pers_key_len
, cpx_max_key_len(cpkp_cpx(cpkp
)));
129 void cpkp_flush(cp_key_pair_t
*cpkp
)
131 cpx_flush(cpkp_cpx(cpkp
));
132 cpkp
->cpkp_pers_key_len
= 0;
133 bzero(cpkp_pers_key(cpkp
), cpkp
->cpkp_max_pers_key_len
);
136 bool cpkp_can_copy(const cp_key_pair_t
*src
, const cp_key_pair_t
*dst
)
138 return (cpkp_pers_key_len(src
) <= dst
->cpkp_max_pers_key_len
139 && cpx_can_copy(cpkp_cpx(src
), cpkp_cpx(dst
)));
142 void cpkp_copy(const cp_key_pair_t
*src
, cp_key_pair_t
*dst
)
144 const uint16_t key_len
= cpkp_pers_key_len(src
);
145 cpkp_set_pers_key_len(dst
, key_len
);
146 memcpy(cpkp_pers_key(dst
), cpkp_pers_key(src
), key_len
);
147 cpx_copy(cpkp_cpx(src
), cpkp_cpx(dst
));
152 bool cp_is_supported_version(uint16_t vers
)
154 return vers
== CP_VERS_4
|| vers
== CP_VERS_5
;
158 * Return the appropriate key and, if requested, the physical offset and
159 * maximum length for a particular I/O operation.
161 void cp_io_params(__unused hfsmount_t
*hfsmp
, cprotect_t cpr
,
162 __unused off_rsrc_t off_rsrc
,
163 __unused
int direction
, cp_io_params_t
*io_params
)
165 #if HFS_CONFIG_KEY_ROLL
166 hfs_cp_key_roll_ctx_t
*ckr
= cpr
->cp_key_roll_ctx
;
168 if (ckr
&& off_rsrc
< ckr
->ckr_off_rsrc
) {
170 * When we're in the process of rolling an extent, ckr_off_rsrc will
171 * indicate the end of the extent.
173 const off_rsrc_t roll_loc
= ckr
->ckr_off_rsrc
174 - hfs_blk_to_bytes(ckr
->ckr_roll_extent
.blockCount
,
177 if (off_rsrc
< roll_loc
) {
178 io_params
->max_len
= roll_loc
- off_rsrc
;
179 io_params
->phys_offset
= -1;
182 * We should never get reads to the extent we're rolling
183 * because the pages should be locked in the UBC. If we
184 * did get reads it's not obvious what the right thing to
185 * do is either: we could read from the old location, but
186 * we might have written later data to the new location,
187 * or we could read from the new location, but data might
188 * not have been written there yet.
190 * Note that whilst raw encrypted reads don't lock any
191 * pages, or take a cluster_read_direct lock, the call to
192 * hfs_key_roll_up_to in hfs_vnop_read will have ensured
193 * that the file has been rolled beyond the offset being
194 * read so this path should never be taken in that case.
196 hfs_assert(direction
== VNODE_WRITE
);
198 // For release builds, just in case...
199 if (direction
== VNODE_READ
) {
200 // Use the old key and offset
204 io_params
->max_len
= ckr
->ckr_off_rsrc
- off_rsrc
;
205 io_params
->phys_offset
= hfs_blk_to_bytes(ckr
->ckr_roll_extent
.startBlock
,
206 hfsmp
->blockSize
) + off_rsrc
- roll_loc
;
210 io_params
->cpx
= cpkp_cpx(&ckr
->ckr_keys
);
217 io_params
->max_len
= INT64_MAX
;
218 io_params
->phys_offset
= -1;
219 io_params
->cpx
= cpkp_cpx(&cpr
->cp_keys
);
222 static void cp_flush_cached_keys(cprotect_t cpr
)
224 cpx_flush(cpkp_cpx(&cpr
->cp_keys
));
225 #if HFS_CONFIG_KEY_ROLL
226 if (cpr
->cp_key_roll_ctx
)
227 cpx_flush(cpkp_cpx(&cpr
->cp_key_roll_ctx
->ckr_keys
));
231 static bool cp_needs_pers_key(cprotect_t cpr
)
233 if (CP_CLASS(cpr
->cp_pclass
) == PROTECTION_CLASS_F
)
234 return !cpx_has_key(cpkp_cpx(&cpr
->cp_keys
));
236 return !cpkp_has_pers_key(&cpr
->cp_keys
);
239 static cp_key_revision_t
cp_initial_key_revision(__unused hfsmount_t
*hfsmp
)
244 cp_key_revision_t
cp_next_key_revision(cp_key_revision_t rev
)
246 rev
= (rev
+ 0x0100) ^ (mach_absolute_time() & 0xff);
253 * Allocate and initialize a cprotect blob for a new cnode.
254 * Called from hfs_getnewvnode: cnode is locked exclusive.
256 * Read xattr data off the cnode. Then, if conditions permit,
257 * unwrap the file key and cache it in the cprotect blob.
260 cp_entry_init(struct cnode
*cp
, struct mount
*mp
)
262 struct cprotect
*entry
= NULL
;
264 struct hfsmount
*hfsmp
= VFSTOHFS(mp
);
267 * The cnode should be locked at this point, regardless of whether or not
268 * we are creating a new item in the namespace or vending a vnode on behalf
269 * of lookup. The only time we tell getnewvnode to skip the lock is when
270 * constructing a resource fork vnode. But a resource fork vnode must come
271 * after the regular data fork cnode has already been constructed.
273 if (!cp_fs_protected (mp
)) {
274 cp
->c_cpentry
= NULL
;
278 if (!S_ISREG(cp
->c_mode
) && !S_ISDIR(cp
->c_mode
)) {
279 cp
->c_cpentry
= NULL
;
283 if (hfsmp
->hfs_running_cp_major_vers
== 0) {
284 panic ("hfs cp: no running mount point version! ");
287 hfs_assert(cp
->c_cpentry
== NULL
);
289 error
= cp_getxattr(cp
, hfsmp
, &entry
);
290 if (error
== ENOATTR
) {
292 * Normally, we should always have a CP EA for a file or directory that
293 * we are initializing here. However, there are some extenuating circumstances,
294 * such as the root directory immediately following a newfs_hfs.
296 * As a result, we leave code here to deal with an ENOATTR which will always
297 * default to a 'D/NONE' key, though we don't expect to use it much.
299 cp_key_class_t target_class
= PROTECTION_CLASS_D
;
301 if (S_ISDIR(cp
->c_mode
)) {
302 target_class
= PROTECTION_CLASS_DIR_NONE
;
305 cp_key_revision_t key_revision
= cp_initial_key_revision(hfsmp
);
307 /* allow keybag to override our class preferences */
308 error
= cp_new (&target_class
, hfsmp
, cp
, cp
->c_mode
, CP_KEYWRAP_DIFFCLASS
,
309 key_revision
, (cp_new_alloc_fn
)cp_entry_alloc
, (void **)&entry
);
311 entry
->cp_pclass
= target_class
;
312 entry
->cp_key_os_version
= cp_os_version();
313 entry
->cp_key_revision
= key_revision
;
314 error
= cp_setxattr (cp
, entry
, hfsmp
, cp
->c_fileid
, XATTR_CREATE
);
320 * a) error was not ENOATTR (we got something bad from the getxattr call)
321 * b) we encountered an error setting the xattr above.
322 * c) we failed to generate a new cprotect data structure.
328 cp
->c_cpentry
= entry
;
332 entry
->cp_backing_cnode
= cp
;
336 cp_entry_destroy(hfsmp
, entry
);
338 cp
->c_cpentry
= NULL
;
347 * Generate a keyless cprotect structure for use with the new AppleKeyStore kext.
348 * Since the kext is now responsible for vending us both wrapped/unwrapped keys
349 * we need to create a keyless xattr upon file / directory creation. When we have the inode value
350 * and the file/directory is established, then we can ask it to generate keys. Note that
351 * this introduces a potential race; If the device is locked and the wrapping
352 * keys are purged between the time we call this function and the time we ask it to generate
353 * keys for us, we could have to fail the open(2) call and back out the entry.
356 int cp_setup_newentry (struct hfsmount
*hfsmp
, struct cnode
*dcp
,
357 cp_key_class_t suppliedclass
, mode_t cmode
,
358 struct cprotect
**tmpentry
)
361 struct cprotect
*entry
= NULL
;
362 uint32_t target_class
= hfsmp
->default_cp_class
;
363 suppliedclass
= CP_CLASS(suppliedclass
);
365 if (hfsmp
->hfs_running_cp_major_vers
== 0) {
366 panic ("CP: major vers not set in mount!");
369 if (S_ISDIR (cmode
)) {
373 /* Decide the target class. Input argument takes priority. */
374 if (cp_is_valid_class (isdir
, suppliedclass
)) {
375 /* caller supplies -1 if it was not specified so we will default to the mount point value */
376 target_class
= suppliedclass
;
378 * One exception, F is never valid for a directory
379 * because its children may inherit and userland will be
380 * unable to read/write to the files.
383 if (target_class
== PROTECTION_CLASS_F
) {
391 * If no valid class was supplied, behave differently depending on whether or not
392 * the item being created is a file or directory.
395 * If parent directory has a non-zero class, use that.
396 * If parent directory has a zero class (not set), then attempt to
397 * apply the mount point default.
400 * Directories always inherit from the parent; if the parent
401 * has a NONE class set, then we can continue to use that.
403 if ((dcp
) && (dcp
->c_cpentry
)) {
404 uint32_t parentclass
= CP_CLASS(dcp
->c_cpentry
->cp_pclass
);
405 /* If the parent class is not valid, default to the mount point value */
406 if (cp_is_valid_class(1, parentclass
)) {
408 target_class
= parentclass
;
410 else if (parentclass
!= PROTECTION_CLASS_DIR_NONE
) {
411 /* files can inherit so long as it's not NONE */
412 target_class
= parentclass
;
415 /* Otherwise, we already defaulted to the mount point's default */
419 /* Generate the cprotect to vend out */
420 entry
= cp_entry_alloc(NULL
, 0, 0, NULL
);
427 * We don't have keys yet, so fill in what we can. At this point
428 * this blob has no keys and it has no backing xattr. We just know the
431 entry
->cp_flags
= CP_NO_XATTR
;
432 /* Note this is only the effective class */
433 entry
->cp_pclass
= target_class
;
440 * Set up an initial key/class pair for a disassociated cprotect entry.
441 * This function is used to generate transient keys that will never be
442 * written to disk. We use class F for this since it provides the exact
443 * semantics that are needed here. Because we never attach this blob to
444 * a cnode directly, we take a pointer to the cprotect struct.
446 * This function is primarily used in the HFS FS truncation codepath
447 * where we may rely on AES symmetry to relocate encrypted data from
448 * one spot in the disk to another.
450 int cpx_gentempkeys(cpx_t
*pcpx
, __unused
struct hfsmount
*hfsmp
)
452 cpx_t cpx
= cpx_alloc(CP_MAX_KEYSIZE
);
454 cpx_set_key_len(cpx
, CP_MAX_KEYSIZE
);
455 read_random(cpx_key(cpx
), CP_MAX_KEYSIZE
);
456 cpx_set_use_offset_for_iv(cpx
, true);
464 * Tear down and clear a cprotect blob for a closing file.
465 * Called at hfs_reclaim_cnode: cnode is locked exclusive.
468 cp_entry_destroy(hfsmount_t
*hfsmp
, struct cprotect
*entry_ptr
)
470 if (entry_ptr
== NULL
) {
471 /* nothing to clean up */
474 cp_entry_dealloc(hfsmp
, entry_ptr
);
479 cp_fs_protected (mount_t mnt
)
481 return (vfs_flags(mnt
) & MNT_CPROTECT
);
486 * Return a pointer to underlying cnode if there is one for this vnode.
487 * Done without taking cnode lock, inspecting only vnode state.
490 cp_get_protected_cnode(struct vnode
*vp
)
492 if (!cp_vnode_is_eligible(vp
)) {
496 if (!cp_fs_protected(VTOVFS(vp
))) {
497 /* mount point doesn't support it */
501 return vnode_fsnode(vp
);
506 * Sets *class to persistent class associated with vnode,
510 cp_vnode_getclass(struct vnode
*vp
, cp_key_class_t
*class)
512 struct cprotect
*entry
;
515 int took_truncate_lock
= 0;
516 struct hfsmount
*hfsmp
= NULL
;
518 /* Is this an interesting vp? */
519 if (!cp_vnode_is_eligible (vp
)) {
523 /* Is the mount point formatted for content protection? */
524 if (!cp_fs_protected(VTOVFS(vp
))) {
532 * Take the truncate lock up-front in shared mode because we may need
533 * to manipulate the CP blob. Pend lock events until we're done here.
535 hfs_lock_truncate (cp
, HFS_SHARED_LOCK
, HFS_LOCK_DEFAULT
);
536 took_truncate_lock
= 1;
539 * We take only the shared cnode lock up-front. If it turns out that
540 * we need to manipulate the CP blob to write a key out, drop the
541 * shared cnode lock and acquire an exclusive lock.
543 error
= hfs_lock(cp
, HFS_SHARED_LOCK
, HFS_LOCK_DEFAULT
);
545 hfs_unlock_truncate(cp
, HFS_LOCK_DEFAULT
);
549 /* pull the class from the live entry */
550 entry
= cp
->c_cpentry
;
553 panic("Content Protection: uninitialized cnode %p", cp
);
556 /* Note that we may not have keys yet, but we know the target class. */
559 *class = CP_CLASS(entry
->cp_pclass
);
562 if (took_truncate_lock
) {
563 hfs_unlock_truncate(cp
, HFS_LOCK_DEFAULT
);
571 * Sets persistent class for this file or directory.
572 * If vnode cannot be protected (system file, non-regular file, non-hfs), EBADF.
573 * If the new class can't be accessed now, EPERM.
574 * Otherwise, record class and re-wrap key if the mount point is content-protected.
577 cp_vnode_setclass(struct vnode
*vp
, cp_key_class_t newclass
)
580 struct cprotect
*entry
= 0;
582 int took_truncate_lock
= 0;
583 struct hfsmount
*hfsmp
= NULL
;
586 if (vnode_isdir (vp
)) {
590 /* Ensure we only use the effective class here */
591 newclass
= CP_CLASS(newclass
);
593 if (!cp_is_valid_class(isdir
, newclass
)) {
594 printf("hfs: CP: cp_setclass called with invalid class %d\n", newclass
);
598 /* Is this an interesting vp? */
599 if (!cp_vnode_is_eligible(vp
)) {
603 /* Is the mount point formatted for content protection? */
604 if (!cp_fs_protected(VTOVFS(vp
))) {
609 if (hfsmp
->hfs_flags
& HFS_READ_ONLY
) {
614 * Take the cnode truncate lock exclusive because we want to manipulate the
615 * CP blob. The lock-event handling code is doing the same. This also forces
616 * all pending IOs to drain before we can re-write the persistent and cache keys.
619 hfs_lock_truncate (cp
, HFS_EXCLUSIVE_LOCK
, HFS_LOCK_DEFAULT
);
620 took_truncate_lock
= 1;
623 * The truncate lock is not sufficient to guarantee the CP blob
624 * isn't being used. We must wait for existing writes to finish.
626 vnode_waitforwrites(vp
, 0, 0, 0, "cp_vnode_setclass");
628 if (hfs_lock(cp
, HFS_EXCLUSIVE_LOCK
, HFS_LOCK_DEFAULT
)) {
632 entry
= cp
->c_cpentry
;
639 * re-wrap per-file key with new class.
640 * Generate an entirely new key if switching to F.
642 if (vnode_isreg(vp
)) {
644 * The vnode is a file. Before proceeding with the re-wrap, we need
645 * to unwrap the keys before proceeding. This is to ensure that
646 * the destination class's properties still work appropriately for the
647 * target class (since B allows I/O but an unwrap prior to the next unlock
648 * will not be allowed).
650 if (!cpx_has_key(cpkp_cpx(&entry
->cp_keys
))) {
651 error
= cp_restore_keys (entry
, hfsmp
, cp
);
657 if (newclass
== PROTECTION_CLASS_F
) {
658 /* Verify that file is blockless if switching to class F */
659 if (cp
->c_datafork
->ff_size
> 0) {
665 cprotect_t new_entry
= cp_entry_alloc(NULL
, 0, CP_MAX_KEYSIZE
, &cpkp
);
672 /* newclass is only the effective class */
673 new_entry
->cp_pclass
= newclass
;
674 new_entry
->cp_key_os_version
= cp_os_version();
675 new_entry
->cp_key_revision
= cp_next_key_revision(entry
->cp_key_revision
);
677 cpx_t cpx
= cpkp_cpx(cpkp
);
679 /* Class F files are not wrapped, so they continue to use MAX_KEYSIZE */
680 cpx_set_key_len(cpx
, CP_MAX_KEYSIZE
);
681 read_random (cpx_key(cpx
), CP_MAX_KEYSIZE
);
683 cp_replace_entry(hfsmp
, cp
, new_entry
);
689 /* Deny the setclass if file is to be moved from F to something else */
690 if (entry
->cp_pclass
== PROTECTION_CLASS_F
) {
695 if (!cpkp_has_pers_key(&entry
->cp_keys
)) {
696 struct cprotect
*new_entry
= NULL
;
698 * We want to fail if we can't wrap to the target class. By not setting
699 * CP_KEYWRAP_DIFFCLASS, we tell keygeneration that if it can't wrap
700 * to 'newclass' then error out.
703 error
= cp_generate_keys (hfsmp
, cp
, newclass
, flags
, &new_entry
);
705 cp_replace_entry (hfsmp
, cp
, new_entry
);
707 /* Bypass the setxattr code below since generate_keys does it for us */
711 cprotect_t new_entry
;
712 error
= cp_rewrap(cp
, hfsmp
, &newclass
, &entry
->cp_keys
, entry
,
713 (cp_new_alloc_fn
)cp_entry_alloc
, (void **)&new_entry
);
715 /* we didn't have perms to set this class. leave file as-is and error out */
719 #if HFS_CONFIG_KEY_ROLL
720 hfs_cp_key_roll_ctx_t
*new_key_roll_ctx
= NULL
;
721 if (entry
->cp_key_roll_ctx
) {
722 error
= cp_rewrap(cp
, hfsmp
, &newclass
, &entry
->cp_key_roll_ctx
->ckr_keys
,
723 entry
->cp_key_roll_ctx
,
724 (cp_new_alloc_fn
)hfs_key_roll_ctx_alloc
,
725 (void **)&new_key_roll_ctx
);
728 cp_entry_dealloc(hfsmp
, new_entry
);
732 new_entry
->cp_key_roll_ctx
= new_key_roll_ctx
;
736 new_entry
->cp_pclass
= newclass
;
738 cp_replace_entry(hfsmp
, cp
, new_entry
);
741 else if (vnode_isdir(vp
)) {
742 /* For directories, just update the pclass. newclass is only effective class */
743 entry
->cp_pclass
= newclass
;
747 /* anything else, just error out */
753 * We get here if the new class was F, or if we were re-wrapping a cprotect that already
754 * existed. If the keys were never generated, then they'll skip the setxattr calls.
757 error
= cp_setxattr(cp
, cp
->c_cpentry
, VTOHFS(vp
), 0, XATTR_REPLACE
);
758 if (error
== ENOATTR
) {
759 error
= cp_setxattr(cp
, cp
->c_cpentry
, VTOHFS(vp
), 0, XATTR_CREATE
);
764 if (took_truncate_lock
) {
765 hfs_unlock_truncate (cp
, HFS_LOCK_DEFAULT
);
772 int cp_vnode_transcode(vnode_t vp
, cp_key_t
*k
)
775 struct cprotect
*entry
= 0;
777 int took_truncate_lock
= 0;
778 struct hfsmount
*hfsmp
= NULL
;
780 /* Structures passed between HFS and AKS */
781 struct aks_cred_s access_in
;
782 struct aks_wrapped_key_s wrapped_key_in
, wrapped_key_out
;
784 /* Is this an interesting vp? */
785 if (!cp_vnode_is_eligible(vp
)) {
789 /* Is the mount point formatted for content protection? */
790 if (!cp_fs_protected(VTOVFS(vp
))) {
798 * Take the cnode truncate lock exclusive because we want to manipulate the
799 * CP blob. The lock-event handling code is doing the same. This also forces
800 * all pending IOs to drain before we can re-write the persistent and cache keys.
802 hfs_lock_truncate (cp
, HFS_EXCLUSIVE_LOCK
, HFS_LOCK_DEFAULT
);
803 took_truncate_lock
= 1;
805 if (hfs_lock(cp
, HFS_EXCLUSIVE_LOCK
, HFS_LOCK_DEFAULT
)) {
809 entry
= cp
->c_cpentry
;
815 /* Send the per-file key in wrapped form for re-wrap with the current class information
816 * Send NULLs in the output parameters of the wrapper() and AKS will do the rest.
817 * Don't need to process any outputs, so just clear the locks and pass along the error. */
818 if (vnode_isreg(vp
)) {
820 /* Picked up the following from cp_wrap().
821 * If needed, more comments available there. */
823 if (CP_CLASS(entry
->cp_pclass
) == PROTECTION_CLASS_F
) {
828 cp_init_access(&access_in
, cp
);
830 bzero(&wrapped_key_in
, sizeof(wrapped_key_in
));
831 bzero(&wrapped_key_out
, sizeof(wrapped_key_out
));
833 cp_key_pair_t
*cpkp
= &entry
->cp_keys
;
835 #if HFS_CONFIG_KEY_ROLL
836 if (entry
->cp_key_roll_ctx
)
837 cpkp
= &entry
->cp_key_roll_ctx
->ckr_keys
;
840 wrapped_key_in
.key
= cpkp_pers_key(cpkp
);
841 wrapped_key_in
.key_len
= cpkp_pers_key_len(cpkp
);
843 if (!wrapped_key_in
.key_len
) {
848 /* Use the actual persistent class when talking to AKS */
849 wrapped_key_in
.dp_class
= entry
->cp_pclass
;
850 wrapped_key_out
.key
= k
->key
;
851 wrapped_key_out
.key_len
= k
->len
;
853 error
= hfs_backup_key(&access_in
,
860 k
->len
= wrapped_key_out
.key_len
;
864 if (took_truncate_lock
) {
865 hfs_unlock_truncate (cp
, HFS_LOCK_DEFAULT
);
873 * Check permission for the given operation (read, write) on this node.
874 * Additionally, if the node needs work, do it:
875 * - create a new key for the file if one hasn't been set before
876 * - write out the xattr if it hasn't already been saved
877 * - unwrap the key if needed
879 * Takes cnode lock, and upgrades to exclusive if modifying cprotect.
881 * Note that this function does *NOT* take the cnode truncate lock. This is because
882 * the thread calling us may already have the truncate lock. It is not necessary
883 * because either we successfully finish this function before the keys are tossed
884 * and the IO will fail, or the keys are tossed and then this function will fail.
885 * Either way, the cnode lock still ultimately guards the keys. We only rely on the
886 * truncate lock to protect us against tossing the keys as a cluster call is in-flight.
889 cp_handle_vnop(struct vnode
*vp
, int vnop
, int ioflag
)
891 struct cprotect
*entry
;
893 struct hfsmount
*hfsmp
= NULL
;
894 struct cnode
*cp
= NULL
;
897 * First, do validation against the vnode before proceeding any further:
898 * Is this vnode originating from a valid content-protected filesystem ?
900 if (cp_vnode_is_eligible(vp
) == 0) {
902 * It is either not HFS or not a file/dir. Just return success. This is a valid
903 * case if servicing i/o against another filesystem type from VFS
908 if (cp_fs_protected (VTOVFS(vp
)) == 0) {
910 * The underlying filesystem does not support content protection. This is also
911 * a valid case. Simply return success.
917 * At this point, we know we have a HFS vnode that backs a file or directory on a
918 * filesystem that supports content protection
922 if ((error
= hfs_lock(cp
, HFS_SHARED_LOCK
, HFS_LOCK_DEFAULT
))) {
926 entry
= cp
->c_cpentry
;
930 * If this cnode is not content protected, simply return success.
931 * Note that this function is called by all I/O-based call sites
932 * when CONFIG_PROTECT is enabled during XNU building.
936 * All files should have cprotect structs. It's possible to encounter
937 * a directory from a V2.0 CP system but all files should have protection
940 if (vnode_isreg(vp
)) {
958 if ((error
= cp_check_access(cp
, hfsmp
, vnop
))) {
959 /* check for raw encrypted access before bailing out */
960 if ((ioflag
& IO_ENCRYPTED
)
961 #if HFS_CONFIG_KEY_ROLL
962 // If we're rolling, we need the keys
963 && !hfs_is_key_rolling(cp
)
965 && (vnop
== CP_READ_ACCESS
)) {
967 * read access only + asking for the raw encrypted bytes
968 * is legitimate, so reset the error value to 0
977 if (!ISSET(entry
->cp_flags
, CP_NO_XATTR
)) {
978 if (!S_ISREG(cp
->c_mode
))
981 // If we have a persistent key and the cached key, we're done
982 if (!cp_needs_pers_key(entry
)
983 && cpx_has_key(cpkp_cpx(&entry
->cp_keys
))) {
988 /* upgrade to exclusive lock */
989 if (lck_rw_lock_shared_to_exclusive(&cp
->c_rwlock
) == FALSE
) {
990 if ((error
= hfs_lock(cp
, HFS_EXCLUSIVE_LOCK
, HFS_LOCK_DEFAULT
))) {
994 cp
->c_lockowner
= current_thread();
997 /* generate new keys if none have ever been saved */
998 if (cp_needs_pers_key(entry
)) {
999 struct cprotect
*newentry
= NULL
;
1001 * It's ok if this ends up being wrapped in a different class than 'pclass'.
1002 * class modification is OK here.
1004 uint32_t flags
= CP_KEYWRAP_DIFFCLASS
;
1006 error
= cp_generate_keys (hfsmp
, cp
, CP_CLASS(cp
->c_cpentry
->cp_pclass
), flags
, &newentry
);
1008 cp_replace_entry (hfsmp
, cp
, newentry
);
1016 /* unwrap keys if needed */
1017 if (!cpx_has_key(cpkp_cpx(&entry
->cp_keys
))) {
1018 if ((vnop
== CP_READ_ACCESS
) && (ioflag
& IO_ENCRYPTED
)) {
1019 /* no need to try to restore keys; they are not going to be used */
1023 error
= cp_restore_keys(entry
, hfsmp
, cp
);
1030 /* write out the xattr if it's new */
1031 if (entry
->cp_flags
& CP_NO_XATTR
)
1032 error
= cp_setxattr(cp
, entry
, VTOHFS(cp
->c_vp
), 0, XATTR_CREATE
);
1042 static void cp_log_eperm (struct vnode
* vp
, int pclass
, boolean_t create
) {
1043 char procname
[256] = {};
1044 const char *fname
= "unknown";
1045 const char *dbgop
= "open";
1047 int ppid
= proc_selfpid();
1048 /* selfname does a strlcpy so we're OK */
1049 proc_selfname(procname
, sizeof(procname
));
1050 if (vp
&& vp
->v_name
) {
1051 /* steal from the namecache */
1059 printf("proc %s (pid %d) class %d, op: %s failure @ file %s\n", procname
, ppid
, pclass
, dbgop
, fname
);
1066 cp_handle_open(struct vnode
*vp
, int mode
)
1068 struct cnode
*cp
= NULL
;
1069 struct cprotect
*entry
= NULL
;
1070 struct hfsmount
*hfsmp
;
1073 /* If vnode not eligible, just return success */
1074 if (!cp_vnode_is_eligible(vp
)) {
1078 /* If mount point not properly set up, then also return success */
1079 if (!cp_fs_protected(VTOVFS(vp
))) {
1085 // Allow if raw encrypted mode requested
1086 if (ISSET(mode
, FENCRYPTED
)) {
1087 #if HFS_CONFIG_KEY_ROLL
1088 // If we're rolling, we need the keys
1089 hfs_lock_always(cp
, HFS_SHARED_LOCK
);
1090 bool rolling
= hfs_is_key_rolling(cp
);
1098 if (ISSET(mode
, FUNENCRYPTED
)) {
1102 /* We know the vnode is in a valid state. Acquire cnode and validate */
1105 if ((error
= hfs_lock(cp
, HFS_EXCLUSIVE_LOCK
, HFS_LOCK_DEFAULT
))) {
1109 entry
= cp
->c_cpentry
;
1110 if (entry
== NULL
) {
1112 * If the mount is protected and we couldn't get a cprotect for this vnode,
1113 * then it's not valid for opening.
1115 if (vnode_isreg(vp
)) {
1121 if (!S_ISREG(cp
->c_mode
))
1125 * Does the cnode have keys yet? If not, then generate them.
1127 if (cp_needs_pers_key(entry
)) {
1128 struct cprotect
*newentry
= NULL
;
1129 /* Allow the keybag to override our class preferences */
1130 uint32_t flags
= CP_KEYWRAP_DIFFCLASS
;
1131 error
= cp_generate_keys (hfsmp
, cp
, CP_CLASS(cp
->c_cpentry
->cp_pclass
), flags
, &newentry
);
1133 cp_replace_entry (hfsmp
, cp
, newentry
);
1142 * We want to minimize the number of unwraps that we'll have to do since
1143 * the cost can vary, depending on the platform we're running.
1145 switch (CP_CLASS(entry
->cp_pclass
)) {
1146 case PROTECTION_CLASS_B
:
1147 if (mode
& O_CREAT
) {
1149 * Class B always allows creation. Since O_CREAT was passed through
1150 * we infer that this was a newly created vnode/cnode. Even though a potential
1151 * race exists when multiple threads attempt to create/open a particular
1152 * file, only one can "win" and actually create it. VFS will unset the
1153 * O_CREAT bit on the loser.
1155 * Note that skipping the unwrap check here is not a security issue --
1156 * we have to unwrap the key permanently upon the first I/O.
1161 if (cpx_has_key(cpkp_cpx(&entry
->cp_keys
)) && !ISSET(mode
, FENCRYPTED
)) {
1163 * For a class B file, attempt the unwrap if we have the key in
1165 * The device could have just transitioned into the lock state, and
1166 * this vnode may not yet have been purged from the vnode cache (which would
1169 struct aks_cred_s access_in
;
1170 struct aks_wrapped_key_s wrapped_key_in
;
1172 cp_init_access(&access_in
, cp
);
1173 bzero(&wrapped_key_in
, sizeof(wrapped_key_in
));
1174 wrapped_key_in
.key
= cpkp_pers_key(&entry
->cp_keys
);
1175 wrapped_key_in
.key_len
= cpkp_pers_key_len(&entry
->cp_keys
);
1176 /* Use the persistent class when talking to AKS */
1177 wrapped_key_in
.dp_class
= entry
->cp_pclass
;
1178 error
= hfs_unwrap_key(&access_in
, &wrapped_key_in
, NULL
);
1184 /* otherwise, fall through to attempt the unwrap/restore */
1185 case PROTECTION_CLASS_A
:
1186 case PROTECTION_CLASS_C
:
1188 * At this point, we know that we need to attempt an unwrap if needed; we want
1189 * to makes sure that open(2) fails properly if the device is either just-locked
1190 * or never made it past first unlock. Since the keybag serializes access to the
1191 * unwrapping keys for us and only calls our VFS callback once they've been purged,
1192 * we will get here in two cases:
1194 * A) we're in a window before the wrapping keys are purged; this is OK since when they get
1195 * purged, the vnode will get flushed if needed.
1197 * B) The keys are already gone. In this case, the restore_keys call below will fail.
1199 * Since this function is bypassed entirely if we're opening a raw encrypted file,
1200 * we can always attempt the restore.
1202 if (!cpx_has_key(cpkp_cpx(&entry
->cp_keys
))) {
1203 error
= cp_restore_keys(entry
, hfsmp
, cp
);
1212 case PROTECTION_CLASS_D
:
1221 if ((hfsmp
->hfs_cp_verbose
) && (error
== EPERM
)) {
1222 cp_log_eperm (vp
, CP_CLASS(entry
->cp_pclass
), false);
1234 * Gets the EA we set on the root folder (fileid 1) to get information about the
1235 * version of Content Protection that was used to write to this filesystem.
1236 * Note that all multi-byte fields are written to disk little endian so they must be
1237 * converted to native endian-ness as needed.
1240 cp_getrootxattr(struct hfsmount
* hfsmp
, struct cp_root_xattr
*outxattr
)
1245 * We allow for an extra 64 bytes to cater for upgrades. This wouldn't
1246 * be necessary if the xattr routines just returned what we asked for.
1248 size_t bufsize
= roundup(sizeof(struct cp_root_xattr
) + 64, 64);
1252 hfs_assert(outxattr
);
1254 buf
= hfs_malloc(bufsize
);
1256 uio_t uio
= uio_create(1, 0, UIO_SYSSPACE
, UIO_READ
);
1258 uio_addiov(uio
, CAST_USER_ADDR_T(buf
), bufsize
);
1260 size_t attrsize
= bufsize
;
1262 struct vnop_getxattr_args args
= {
1264 .a_name
= CONTENT_PROTECTION_XATTR_NAME
,
1268 error
= hfs_getxattr_internal(NULL
, &args
, hfsmp
, 1);
1276 if (attrsize
< CP_ROOT_XATTR_MIN_LEN
) {
1277 error
= HFS_EINCONSISTENT
;
1281 const struct cp_root_xattr
*xattr
= buf
;
1283 bzero(outxattr
, sizeof(*outxattr
));
1285 /* Now convert the multi-byte fields to native endianness */
1286 outxattr
->major_version
= OSSwapLittleToHostInt16(xattr
->major_version
);
1287 outxattr
->minor_version
= OSSwapLittleToHostInt16(xattr
->minor_version
);
1288 outxattr
->flags
= OSSwapLittleToHostInt64(xattr
->flags
);
1290 if (outxattr
->major_version
>= CP_VERS_5
) {
1291 if (attrsize
< sizeof(struct cp_root_xattr
)) {
1292 error
= HFS_EINCONSISTENT
;
1295 #if HFS_CONFIG_KEY_ROLL
1296 outxattr
->auto_roll_min_version
= OSSwapLittleToHostInt32(xattr
->auto_roll_min_version
);
1297 outxattr
->auto_roll_max_version
= OSSwapLittleToHostInt32(xattr
->auto_roll_max_version
);
1302 hfs_free(buf
, bufsize
);
1308 * Sets the EA we set on the root folder (fileid 1) to get information about the
1309 * version of Content Protection that was used to write to this filesystem.
1310 * Note that all multi-byte fields are written to disk little endian so they must be
1311 * converted to little endian as needed.
1313 * This will be written to the disk when it detects the EA is not there, or when we need
1314 * to make a modification to the on-disk version that can be done in-place.
1317 cp_setrootxattr(struct hfsmount
*hfsmp
, struct cp_root_xattr
*newxattr
)
1320 struct vnop_setxattr_args args
;
1324 args
.a_name
= CONTENT_PROTECTION_XATTR_NAME
;
1325 args
.a_uio
= NULL
; //pass data ptr instead
1327 args
.a_context
= NULL
; //no context needed, only done from mount.
1329 const uint64_t flags
= newxattr
->flags
;
1331 /* Now convert the multi-byte fields to little endian before writing to disk. */
1332 newxattr
->flags
= OSSwapHostToLittleInt64(newxattr
->flags
);
1334 int xattr_size
= sizeof(struct cp_root_xattr
);
1336 #if HFS_CONFIG_KEY_ROLL
1337 bool upgraded
= false;
1339 if (newxattr
->auto_roll_min_version
|| newxattr
->auto_roll_max_version
) {
1340 if (newxattr
->major_version
< CP_VERS_5
) {
1341 printf("hfs: upgrading to cp version %u\n", CP_CURRENT_VERS
);
1343 newxattr
->major_version
= CP_CURRENT_VERS
;
1344 newxattr
->minor_version
= CP_MINOR_VERS
;
1349 newxattr
->auto_roll_min_version
= OSSwapHostToLittleInt32(newxattr
->auto_roll_min_version
);
1350 newxattr
->auto_roll_max_version
= OSSwapHostToLittleInt32(newxattr
->auto_roll_max_version
);
1351 } else if (newxattr
->major_version
== CP_VERS_4
)
1352 xattr_size
= offsetof(struct cp_root_xattr
, auto_roll_min_version
);
1355 newxattr
->major_version
= OSSwapHostToLittleInt16(newxattr
->major_version
);
1356 newxattr
->minor_version
= OSSwapHostToLittleInt16(newxattr
->minor_version
);
1358 error
= hfs_setxattr_internal(NULL
, (caddr_t
)newxattr
,
1359 xattr_size
, &args
, hfsmp
, 1);
1362 hfsmp
->cproot_flags
= flags
;
1363 #if HFS_CONFIG_KEY_ROLL
1365 hfsmp
->hfs_running_cp_major_vers
= CP_CURRENT_VERS
;
1374 * Stores new xattr data on the cnode.
1375 * cnode lock held exclusive (if available).
1377 * This function is also invoked during file creation.
1379 int cp_setxattr(struct cnode
*cp
, struct cprotect
*entry
, struct hfsmount
*hfsmp
,
1380 uint32_t fileid
, int options
)
1383 cp_key_pair_t
*cpkp
= &entry
->cp_keys
;
1384 #if HFS_CONFIG_KEY_ROLL
1385 bool rolling
= entry
->cp_key_roll_ctx
!= NULL
;
1387 if (rolling
&& entry
->cp_key_roll_ctx
->ckr_off_rsrc
== INT64_MAX
) {
1388 // We've finished rolling, but we still have the context
1390 cpkp
= &entry
->cp_key_roll_ctx
->ckr_keys
;
1394 if (hfsmp
->hfs_flags
& HFS_READ_ONLY
) {
1398 if (hfsmp
->hfs_running_cp_major_vers
< CP_CURRENT_VERS
) {
1400 printf("hfs: upgrading to cp version %u\n", CP_CURRENT_VERS
);
1402 struct cp_root_xattr root_xattr
;
1404 error
= cp_getrootxattr(hfsmp
, &root_xattr
);
1408 root_xattr
.major_version
= CP_CURRENT_VERS
;
1409 root_xattr
.minor_version
= CP_MINOR_VERS
;
1411 error
= cp_setrootxattr(hfsmp
, &root_xattr
);
1415 hfsmp
->hfs_running_cp_major_vers
= CP_CURRENT_VERS
;
1418 struct cp_xattr_v5
*xattr
;
1419 xattr
= hfs_malloc(sizeof(*xattr
));
1421 xattr
->xattr_major_version
= OSSwapHostToLittleConstInt16(CP_VERS_5
);
1422 xattr
->xattr_minor_version
= OSSwapHostToLittleConstInt16(CP_MINOR_VERS
);
1424 #if HFS_CONFIG_KEY_ROLL
1426 xattr
->flags
|= CP_XAF_KEY_ROLLING
;
1428 xattr
->persistent_class
= OSSwapHostToLittleInt32(entry
->cp_pclass
);
1429 xattr
->key_os_version
= OSSwapHostToLittleInt32(entry
->cp_key_os_version
);
1430 xattr
->key_revision
= OSSwapHostToLittleInt16(entry
->cp_key_revision
);
1432 uint16_t key_len
= cpkp_pers_key_len(cpkp
);
1433 xattr
->key_len
= OSSwapHostToLittleInt16(key_len
);
1434 memcpy(xattr
->persistent_key
, cpkp_pers_key(cpkp
), key_len
);
1436 size_t xattr_len
= offsetof(struct cp_xattr_v5
, persistent_key
) + key_len
;
1438 #if HFS_CONFIG_KEY_ROLL
1440 struct cp_roll_info
*roll_info
= PTR_ADD(struct cp_roll_info
*, xattr
, xattr_len
);
1442 roll_info
->off_rsrc
= OSSwapHostToLittleInt64(entry
->cp_key_roll_ctx
->ckr_off_rsrc
);
1444 key_len
= cpkp_pers_key_len(&entry
->cp_key_roll_ctx
->ckr_keys
);
1445 roll_info
->key_len
= OSSwapHostToLittleInt16(key_len
);
1447 memcpy(roll_info
->key
, cpkp_pers_key(&entry
->cp_key_roll_ctx
->ckr_keys
), key_len
);
1449 xattr_len
+= offsetof(struct cp_roll_info
, key
) + key_len
;
1453 struct vnop_setxattr_args args
= {
1454 .a_vp
= cp
? cp
->c_vp
: NULL
,
1455 .a_name
= CONTENT_PROTECTION_XATTR_NAME
,
1456 .a_options
= options
,
1457 .a_context
= vfs_context_current(),
1460 error
= hfs_setxattr_internal(cp
, xattr
, xattr_len
, &args
, hfsmp
, fileid
);
1462 hfs_free(xattr
, sizeof(*xattr
));
1465 entry
->cp_flags
&= ~CP_NO_XATTR
;
1472 * Used by an fcntl to query the underlying FS for its content protection version #
1476 cp_get_root_major_vers(vnode_t vp
, uint32_t *level
)
1479 struct hfsmount
*hfsmp
= NULL
;
1480 struct mount
*mp
= NULL
;
1484 /* check if it supports content protection */
1485 if (cp_fs_protected(mp
) == 0) {
1489 hfsmp
= VFSTOHFS(mp
);
1490 /* figure out the level */
1492 err
= cp_root_major_vers(mp
);
1495 *level
= hfsmp
->hfs_running_cp_major_vers
;
1497 /* in error case, cp_root_major_vers will just return EINVAL. Use that */
1502 /* Used by fcntl to query default protection level of FS */
1503 int cp_get_default_level (struct vnode
*vp
, uint32_t *level
) {
1505 struct hfsmount
*hfsmp
= NULL
;
1506 struct mount
*mp
= NULL
;
1510 /* check if it supports content protection */
1511 if (cp_fs_protected(mp
) == 0) {
1515 hfsmp
= VFSTOHFS(mp
);
1516 /* figure out the default */
1518 *level
= hfsmp
->default_cp_class
;
1522 /********************
1524 *******************/
1527 cp_root_major_vers(mount_t mp
)
1530 struct cp_root_xattr xattr
;
1531 struct hfsmount
*hfsmp
= NULL
;
1533 hfsmp
= vfs_fsprivate(mp
);
1534 err
= cp_getrootxattr (hfsmp
, &xattr
);
1537 hfsmp
->hfs_running_cp_major_vers
= xattr
.major_version
;
1547 cp_vnode_is_eligible(struct vnode
*vp
)
1549 return !vnode_issystem(vp
) && (vnode_isreg(vp
) || vnode_isdir(vp
));
1553 static const uint32_t cp_magic1
= 0x7b727063; // cpr{
1554 static const uint32_t cp_magic2
= 0x7270637d; // }cpr
1558 cp_entry_alloc(cprotect_t old
, uint16_t pers_key_len
,
1559 uint16_t cached_key_len
, cp_key_pair_t
**pcpkp
)
1561 struct cprotect
*cp_entry
;
1563 if (pers_key_len
> CP_MAX_WRAPPEDKEYSIZE
)
1566 size_t size
= (sizeof(struct cprotect
) - sizeof(cp_key_pair_t
)
1567 + cpkp_size(pers_key_len
, cached_key_len
));
1570 size
+= 4; // Extra for magic2
1573 cp_entry
= hfs_malloc(size
);
1576 memcpy(cp_entry
, old
, offsetof(struct cprotect
, cp_keys
));
1578 #if HFS_CONFIG_KEY_ROLL
1579 // We don't copy the key roll context
1580 cp_entry
->cp_key_roll_ctx
= NULL
;
1583 bzero(cp_entry
, offsetof(struct cprotect
, cp_keys
));
1587 cp_entry
->cp_magic1
= cp_magic1
;
1588 *PTR_ADD(uint32_t *, cp_entry
, size
- 4) = cp_magic2
;
1591 cpkp_init(&cp_entry
->cp_keys
, pers_key_len
, cached_key_len
);
1594 * If we've been passed the old entry, then we are in the process of
1595 * rewrapping in which case we need to copy the cached key. This is
1596 * important for class B files when the device is locked because we
1597 * won't be able to unwrap whilst in this state, yet we still need the
1601 cpx_copy(cpkp_cpx(&old
->cp_keys
), cpkp_cpx(&cp_entry
->cp_keys
));
1604 *pcpkp
= &cp_entry
->cp_keys
;
1610 cp_entry_dealloc(__unused hfsmount_t
*hfsmp
, struct cprotect
*entry
)
1612 #if HFS_CONFIG_KEY_ROLL
1613 hfs_release_key_roll_ctx(hfsmp
, entry
);
1616 cpkp_flush(&entry
->cp_keys
);
1618 size_t entry_size
= (sizeof(struct cprotect
) - sizeof(cp_key_pair_t
)
1619 + cpkp_sizex(&entry
->cp_keys
));
1622 hfs_assert(entry
->cp_magic1
== cp_magic1
);
1623 hfs_assert(*PTR_ADD(uint32_t *, entry
, (sizeof(struct cprotect
) - sizeof(cp_key_pair_t
)
1624 + cpkp_sizex(&entry
->cp_keys
) == cp_magic2
)));
1626 entry_size
+= 4; // Extra for magic2
1629 hfs_free(entry
, entry_size
);
1632 static int cp_read_xattr_v4(__unused hfsmount_t
*hfsmp
, struct cp_xattr_v4
*xattr
,
1633 size_t xattr_len
, cprotect_t
*pcpr
, cp_getxattr_options_t options
)
1635 /* Endian swap the multi-byte fields into host endianness from L.E. */
1636 xattr
->xattr_major_version
= OSSwapLittleToHostInt16(xattr
->xattr_major_version
);
1637 xattr
->xattr_minor_version
= OSSwapLittleToHostInt16(xattr
->xattr_minor_version
);
1638 xattr
->key_size
= OSSwapLittleToHostInt32(xattr
->key_size
);
1639 xattr
->flags
= OSSwapLittleToHostInt32(xattr
->flags
);
1640 xattr
->persistent_class
= OSSwapLittleToHostInt32(xattr
->persistent_class
);
1641 xattr
->key_os_version
= OSSwapLittleToHostInt32(xattr
->key_os_version
);
1644 * Prevent a buffer overflow, and validate the key length obtained from the
1645 * EA. If it's too big, then bail out, because the EA can't be trusted at this
1648 if (xattr
->key_size
> CP_MAX_WRAPPEDKEYSIZE
)
1649 return HFS_EINCONSISTENT
;
1651 size_t min_len
= offsetof(struct cp_xattr_v4
, persistent_key
) + xattr
->key_size
;
1652 if (xattr_len
< min_len
)
1653 return HFS_EINCONSISTENT
;
1656 * Class F files have no backing key; their keylength should be 0,
1657 * though they should have the proper flags set.
1659 * A request to instantiate a CP for a class F file should result
1660 * in a bzero'd cp that just says class F, with key_flushed set.
1662 if (CP_CLASS(xattr
->persistent_class
) == PROTECTION_CLASS_F
1663 || ISSET(xattr
->flags
, CP_XAF_NEEDS_KEYS
)) {
1664 xattr
->key_size
= 0;
1667 /* set up entry with information from xattr */
1668 cp_key_pair_t
*cpkp
;
1671 if (ISSET(options
, CP_GET_XATTR_BASIC_INFO
)) {
1672 /* caller passed in a pre-allocated structure to get the basic info */
1674 bzero(entry
, offsetof(struct cprotect
, cp_keys
));
1677 entry
= cp_entry_alloc(NULL
, xattr
->key_size
, CP_MAX_CACHEBUFLEN
, &cpkp
);
1680 entry
->cp_pclass
= xattr
->persistent_class
;
1681 entry
->cp_key_os_version
= xattr
->key_os_version
;
1684 if (!ISSET(options
, CP_GET_XATTR_BASIC_INFO
)) {
1685 if (xattr
->key_size
) {
1686 cpkp_set_pers_key_len(cpkp
, xattr
->key_size
);
1687 memcpy(cpkp_pers_key(cpkp
), xattr
->persistent_key
, xattr
->key_size
);
1692 else if (xattr
->key_size
) {
1693 SET(entry
->cp_flags
, CP_HAS_A_KEY
);
1699 int cp_read_xattr_v5(hfsmount_t
*hfsmp
, struct cp_xattr_v5
*xattr
,
1700 size_t xattr_len
, cprotect_t
*pcpr
, cp_getxattr_options_t options
)
1702 if (xattr
->xattr_major_version
== OSSwapHostToLittleConstInt16(CP_VERS_4
)) {
1703 return cp_read_xattr_v4(hfsmp
, (struct cp_xattr_v4
*)xattr
, xattr_len
, pcpr
, options
);
1706 xattr
->xattr_major_version
= OSSwapLittleToHostInt16(xattr
->xattr_major_version
);
1708 if (xattr
->xattr_major_version
!= CP_VERS_5
) {
1709 printf("hfs: cp_getxattr: unsupported xattr version %d\n",
1710 xattr
->xattr_major_version
);
1714 size_t min_len
= offsetof(struct cp_xattr_v5
, persistent_key
);
1716 if (xattr_len
< min_len
)
1717 return HFS_EINCONSISTENT
;
1719 xattr
->xattr_minor_version
= OSSwapLittleToHostInt16(xattr
->xattr_minor_version
);
1720 xattr
->flags
= OSSwapLittleToHostInt32(xattr
->flags
);
1721 xattr
->persistent_class
= OSSwapLittleToHostInt32(xattr
->persistent_class
);
1722 xattr
->key_os_version
= OSSwapLittleToHostInt32(xattr
->key_os_version
);
1723 xattr
->key_revision
= OSSwapLittleToHostInt16(xattr
->key_revision
);
1724 xattr
->key_len
= OSSwapLittleToHostInt16(xattr
->key_len
);
1726 uint16_t pers_key_len
= xattr
->key_len
;
1728 min_len
+= pers_key_len
;
1729 if (xattr_len
< min_len
)
1730 return HFS_EINCONSISTENT
;
1732 #if HFS_CONFIG_KEY_ROLL
1733 struct cp_roll_info
*roll_info
= NULL
;
1735 if (ISSET(xattr
->flags
, CP_XAF_KEY_ROLLING
)) {
1736 roll_info
= PTR_ADD(struct cp_roll_info
*, xattr
, min_len
);
1738 min_len
+= offsetof(struct cp_roll_info
, key
);
1740 if (xattr_len
< min_len
)
1741 return HFS_EINCONSISTENT
;
1743 roll_info
->off_rsrc
= OSSwapLittleToHostInt64(roll_info
->off_rsrc
);
1745 if (roll_info
->off_rsrc
% hfsmp
->blockSize
)
1746 return HFS_EINCONSISTENT
;
1748 roll_info
->key_len
= OSSwapLittleToHostInt16(roll_info
->key_len
);
1750 min_len
+= roll_info
->key_len
;
1751 if (xattr_len
< min_len
)
1752 return HFS_EINCONSISTENT
;
1756 cp_key_pair_t
*cpkp
;
1760 * If option CP_GET_XATTR_BASIC_INFO is set, we only return basic
1761 * information about the file's protection (and not the key) and
1762 * we store the result in the structure the caller passed to us.
1764 if (ISSET(options
, CP_GET_XATTR_BASIC_INFO
)) {
1766 bzero(entry
, offsetof(struct cprotect
, cp_keys
));
1767 #if HFS_CONFIG_KEY_ROLL
1768 if (ISSET(xattr
->flags
, CP_XAF_KEY_ROLLING
)) {
1769 SET(entry
->cp_flags
, CP_KEY_IS_ROLLING
);
1773 entry
= cp_entry_alloc(NULL
, xattr
->key_len
, CP_MAX_CACHEBUFLEN
, &cpkp
);
1776 entry
->cp_pclass
= xattr
->persistent_class
;
1777 entry
->cp_key_os_version
= xattr
->key_os_version
;
1778 entry
->cp_key_revision
= xattr
->key_revision
;
1780 if (!ISSET(options
, CP_GET_XATTR_BASIC_INFO
)) {
1781 if (xattr
->key_len
) {
1782 cpkp_set_pers_key_len(cpkp
, xattr
->key_len
);
1783 memcpy(cpkp_pers_key(cpkp
), xattr
->persistent_key
, xattr
->key_len
);
1786 #if HFS_CONFIG_KEY_ROLL
1788 entry
->cp_key_roll_ctx
= hfs_key_roll_ctx_alloc(NULL
, roll_info
->key_len
,
1789 CP_MAX_CACHEBUFLEN
, &cpkp
);
1791 entry
->cp_key_roll_ctx
->ckr_off_rsrc
= roll_info
->off_rsrc
;
1793 if (roll_info
->key_len
) {
1794 cpkp_set_pers_key_len(cpkp
, roll_info
->key_len
);
1795 memcpy(cpkp_pers_key(cpkp
), roll_info
->key
, roll_info
->key_len
);
1802 else if (xattr
->key_len
) {
1803 SET(entry
->cp_flags
, CP_HAS_A_KEY
);
1810 * Initializes a new cprotect entry with xattr data from the cnode.
1811 * cnode lock held shared
1814 cp_getxattr(struct cnode
*cp
, struct hfsmount
*hfsmp
, cprotect_t
*outentry
)
1817 struct cp_xattr_v5
*xattr
;
1819 xattr
= hfs_malloc(xattr_len
= sizeof(*xattr
));
1821 int error
= hfs_xattr_read(cp
->c_vp
, CONTENT_PROTECTION_XATTR_NAME
,
1825 if (xattr_len
< CP_XATTR_MIN_LEN
)
1826 error
= HFS_EINCONSISTENT
;
1828 error
= cp_read_xattr_v5(hfsmp
, xattr
, xattr_len
, outentry
, 0);
1832 if (error
&& error
!= ENOATTR
) {
1833 printf("cp_getxattr: bad cp xattr (%d):\n", error
);
1834 for (size_t i
= 0; i
< xattr_len
; ++i
)
1835 printf("%02x ", ((uint8_t *)xattr
)[i
]);
1840 hfs_free(xattr
, sizeof(*xattr
));
1846 * If permitted, restore entry's unwrapped key from the persistent key.
1847 * If not, clear key and set CP_KEY_FLUSHED.
1848 * cnode lock held exclusive
1851 cp_restore_keys(struct cprotect
*entry
, struct hfsmount
*hfsmp
, struct cnode
*cp
)
1855 error
= cp_unwrap(hfsmp
, entry
, cp
);
1857 cp_flush_cached_keys(entry
);
1863 void cp_device_locked_callback(mount_t mp
, cp_lock_state_t state
)
1865 struct hfsmount
*hfsmp
;
1868 * When iterating the various mount points that may
1869 * be present on a content-protected device, we need to skip
1870 * those that do not have it enabled.
1872 if (!cp_fs_protected(mp
)) {
1876 hfsmp
= VFSTOHFS(mp
);
1878 hfsmp
->hfs_cp_lock_state
= state
;
1880 if (state
== CP_LOCKED_STATE
) {
1882 * We respond only to lock events. Since cprotect structs
1883 * decrypt/restore keys lazily, the unlock events don't
1884 * actually cause anything to happen.
1886 vnode_iterate(mp
, 0, cp_lock_vnode_callback
, (void *)(uintptr_t)state
);
1891 * Deny access to protected files if keys have been locked.
1894 cp_check_access(struct cnode
*cp
, struct hfsmount
*hfsmp
, int vnop __unused
)
1899 * For now it's OK to examine the state variable here without
1900 * holding the HFS lock. This is only a short-circuit; if the state
1901 * transitions (or is in transition) after we examine this field, we'd
1902 * have to handle that anyway.
1904 if (hfsmp
->hfs_cp_lock_state
== CP_UNLOCKED_STATE
) {
1908 if (!cp
->c_cpentry
) {
1909 /* unprotected node */
1913 if (!S_ISREG(cp
->c_mode
)) {
1917 /* Deny all access for class A files */
1918 switch (CP_CLASS(cp
->c_cpentry
->cp_pclass
)) {
1919 case PROTECTION_CLASS_A
: {
1932 * Respond to a lock or unlock event.
1933 * On lock: clear out keys from memory, then flush file contents.
1934 * On unlock: nothing (function not called).
1937 cp_lock_vnode_callback(struct vnode
*vp
, void *arg
)
1940 struct cprotect
*entry
= NULL
;
1943 unsigned long action
= 0;
1944 int took_truncate_lock
= 0;
1946 error
= vnode_getwithref (vp
);
1954 * When cleaning cnodes due to a lock event, we must
1955 * take the truncate lock AND the cnode lock. By taking
1956 * the truncate lock here, we force (nearly) all pending IOs
1957 * to drain before we can acquire the truncate lock. All HFS cluster
1958 * io calls except for swapfile IO need to acquire the truncate lock
1959 * prior to calling into the cluster layer.
1961 hfs_lock_truncate (cp
, HFS_EXCLUSIVE_LOCK
, HFS_LOCK_DEFAULT
);
1962 took_truncate_lock
= 1;
1964 hfs_lock(cp
, HFS_EXCLUSIVE_LOCK
, HFS_LOCK_ALLOW_NOEXISTS
);
1966 entry
= cp
->c_cpentry
;
1968 /* unprotected vnode: not a regular file */
1972 action
= (unsigned long) arg
;
1974 case CP_LOCKED_STATE
: {
1976 if (CP_CLASS(entry
->cp_pclass
) != PROTECTION_CLASS_A
||
1979 * There is no change at lock for other classes than A.
1980 * B is kept in memory for writing, and class F (for VM) does
1981 * not have a wrapped key, so there is no work needed for
1982 * wrapping/unwrapping.
1984 * Note that 'class F' is relevant here because if
1985 * hfs_vnop_strategy does not take the cnode lock
1986 * to protect the cp blob across IO operations, we rely
1987 * implicitly on the truncate lock to be held when doing IO.
1988 * The only case where the truncate lock is not held is during
1989 * swapfile IO because HFS just funnels the VNOP_PAGEOUT
1990 * directly to cluster_pageout.
1995 /* Before doing anything else, zero-fill sparse ranges as needed */
1996 ctx
= vfs_context_current();
1997 (void) hfs_filedone (vp
, ctx
, 0);
1999 /* first, sync back dirty pages */
2001 ubc_msync (vp
, 0, ubc_getsize(vp
), NULL
, UBC_PUSHALL
| UBC_INVALIDATE
| UBC_SYNC
);
2002 hfs_lock (cp
, HFS_EXCLUSIVE_LOCK
, HFS_LOCK_ALLOW_NOEXISTS
);
2005 * There was a concern here(9206856) about flushing keys before nand layer is done using them.
2006 * But since we are using ubc_msync with UBC_SYNC, it blocks until all IO is completed.
2007 * Once IOFS caches or is done with these keys, it calls the completion routine in IOSF.
2008 * Which in turn calls buf_biodone() and eventually unblocks ubc_msync()
2009 * Also verified that the cached data in IOFS is overwritten by other data, and there
2010 * is no key leakage in that layer.
2013 cp_flush_cached_keys(entry
);
2015 /* some write may have arrived in the mean time. dump those pages */
2019 ubc_msync (vp
, 0, ubc_getsize(vp
), NULL
, UBC_INVALIDATE
| UBC_SYNC
);
2022 case CP_UNLOCKED_STATE
: {
2027 panic("Content Protection: unknown lock action %lu\n", action
);
2035 if (took_truncate_lock
) {
2036 hfs_unlock_truncate (cp
, HFS_LOCK_DEFAULT
);
2047 * Generate a new wrapped key based on the existing cache key.
2051 cp_rewrap(struct cnode
*cp
, __unused hfsmount_t
*hfsmp
,
2052 cp_key_class_t
*newclass
, cp_key_pair_t
*cpkp
, const void *old_holder
,
2053 cp_new_alloc_fn alloc_fn
, void **pholder
)
2055 struct cprotect
*entry
= cp
->c_cpentry
;
2057 uint8_t new_persistent_key
[CP_MAX_WRAPPEDKEYSIZE
];
2058 unsigned keylen
= CP_MAX_WRAPPEDKEYSIZE
;
2060 const cp_key_class_t key_class
= CP_CLASS(*newclass
);
2062 /* Structures passed between HFS and AKS */
2063 struct aks_cred_s access_in
;
2064 struct aks_wrapped_key_s wrapped_key_in
;
2065 struct aks_wrapped_key_s wrapped_key_out
;
2068 * PROTECTION_CLASS_F is in-use by VM swapfile; it represents a transient
2069 * key that is only good as long as the file is open. There is no
2070 * wrapped key, so there isn't anything to wrap.
2072 if (key_class
== PROTECTION_CLASS_F
) {
2076 cp_init_access(&access_in
, cp
);
2078 bzero(&wrapped_key_in
, sizeof(wrapped_key_in
));
2079 wrapped_key_in
.key
= cpkp_pers_key(cpkp
);
2080 wrapped_key_in
.key_len
= cpkp_pers_key_len(cpkp
);
2081 /* Use the persistent class when talking to AKS */
2082 wrapped_key_in
.dp_class
= entry
->cp_pclass
;
2084 bzero(&wrapped_key_out
, sizeof(wrapped_key_out
));
2085 wrapped_key_out
.key
= new_persistent_key
;
2086 wrapped_key_out
.key_len
= keylen
;
2089 * inode is passed here to find the backup bag wrapped blob
2090 * from userspace. This lookup will occur shortly after creation
2091 * and only if the file still exists. Beyond this lookup the
2092 * inode is not used. Technically there is a race, we practically
2095 error
= hfs_rewrap_key(&access_in
,
2096 key_class
, /* new class */
2100 keylen
= wrapped_key_out
.key_len
;
2104 * Verify that AKS returned to us a wrapped key of the
2105 * target class requested.
2107 /* Get the effective class here */
2108 cp_key_class_t effective
= CP_CLASS(wrapped_key_out
.dp_class
);
2109 if (effective
!= key_class
) {
2111 * Fail the operation if defaults or some other enforcement
2112 * dictated that the class be wrapped differently.
2115 /* TODO: Invalidate the key when 12170074 unblocked */
2119 /* Allocate a new cpentry */
2120 cp_key_pair_t
*new_cpkp
;
2121 *pholder
= alloc_fn(old_holder
, keylen
, CP_MAX_CACHEBUFLEN
, &new_cpkp
);
2123 /* copy the new key into the entry */
2124 cpkp_set_pers_key_len(new_cpkp
, keylen
);
2125 memcpy(cpkp_pers_key(new_cpkp
), new_persistent_key
, keylen
);
2127 /* Actually record/store what AKS reported back, not the effective class stored in newclass */
2128 *newclass
= wrapped_key_out
.dp_class
;
2137 static int cpkp_unwrap(cnode_t
*cp
, cp_key_class_t key_class
, cp_key_pair_t
*cpkp
)
2140 uint8_t iv_key
[CP_IV_KEYSIZE
];
2141 cpx_t cpx
= cpkp_cpx(cpkp
);
2143 /* Structures passed between HFS and AKS */
2144 struct aks_cred_s access_in
;
2145 struct aks_wrapped_key_s wrapped_key_in
;
2146 struct aks_raw_key_s key_out
;
2148 cp_init_access(&access_in
, cp
);
2150 bzero(&wrapped_key_in
, sizeof(wrapped_key_in
));
2151 wrapped_key_in
.key
= cpkp_pers_key(cpkp
);
2152 wrapped_key_in
.key_len
= cpkp_max_pers_key_len(cpkp
);
2153 /* Use the persistent class when talking to AKS */
2154 wrapped_key_in
.dp_class
= key_class
;
2156 bzero(&key_out
, sizeof(key_out
));
2157 key_out
.iv_key
= iv_key
;
2158 key_out
.key
= cpx_key(cpx
);
2160 * The unwrapper should validate/set the key length for
2161 * the IV key length and the cache key length, however we need
2162 * to supply the correct buffer length so that AKS knows how
2163 * many bytes it has to work with.
2165 key_out
.iv_key_len
= CP_IV_KEYSIZE
;
2166 key_out
.key_len
= cpx_max_key_len(cpx
);
2168 error
= hfs_unwrap_key(&access_in
, &wrapped_key_in
, &key_out
);
2170 if (key_out
.key_len
== 0 || key_out
.key_len
> CP_MAX_CACHEBUFLEN
) {
2171 panic ("cp_unwrap: invalid key length! (%ul)\n", key_out
.key_len
);
2174 if (key_out
.iv_key_len
!= CP_IV_KEYSIZE
)
2175 panic ("cp_unwrap: invalid iv key length! (%ul)\n", key_out
.iv_key_len
);
2177 cpx_set_key_len(cpx
, key_out
.key_len
);
2179 cpx_set_aes_iv_key(cpx
, iv_key
);
2180 cpx_set_is_sep_wrapped_key(cpx
, ISSET(key_out
.flags
, AKS_RAW_KEY_WRAPPEDKEY
));
2189 cp_unwrap(__unused
struct hfsmount
*hfsmp
, struct cprotect
*entry
, struct cnode
*cp
)
2192 * PROTECTION_CLASS_F is in-use by VM swapfile; it represents a transient
2193 * key that is only good as long as the file is open. There is no
2194 * wrapped key, so there isn't anything to unwrap.
2196 if (CP_CLASS(entry
->cp_pclass
) == PROTECTION_CLASS_F
) {
2200 int error
= cpkp_unwrap(cp
, entry
->cp_pclass
, &entry
->cp_keys
);
2202 #if HFS_CONFIG_KEY_ROLL
2203 if (!error
&& entry
->cp_key_roll_ctx
) {
2204 error
= cpkp_unwrap(cp
, entry
->cp_pclass
, &entry
->cp_key_roll_ctx
->ckr_keys
);
2206 cpx_flush(cpkp_cpx(&entry
->cp_keys
));
2216 * Take a cnode that has already been initialized and establish persistent and
2217 * cache keys for it at this time. Note that at the time this is called, the
2218 * directory entry has already been created and we are holding the cnode lock
2222 int cp_generate_keys (struct hfsmount
*hfsmp
, struct cnode
*cp
, cp_key_class_t targetclass
,
2223 uint32_t keyflags
, struct cprotect
**newentry
)
2227 struct cprotect
*newcp
= NULL
;
2230 /* Target class must be an effective class only */
2231 targetclass
= CP_CLASS(targetclass
);
2233 /* Validate that it has a cprotect already */
2234 if (cp
->c_cpentry
== NULL
) {
2235 /* We can't do anything if it shouldn't be protected. */
2239 /* Asserts for the underlying cprotect */
2240 if (cp
->c_cpentry
->cp_flags
& CP_NO_XATTR
) {
2241 /* should already have an xattr by this point. */
2246 if (S_ISREG(cp
->c_mode
)) {
2247 if (!cp_needs_pers_key(cp
->c_cpentry
)) {
2253 cp_key_revision_t key_revision
= cp_initial_key_revision(hfsmp
);
2255 error
= cp_new (&targetclass
, hfsmp
, cp
, cp
->c_mode
, keyflags
, key_revision
,
2256 (cp_new_alloc_fn
)cp_entry_alloc
, (void **)&newcp
);
2259 * Key generation failed. This is not necessarily fatal
2260 * since the device could have transitioned into the lock
2261 * state before we called this.
2267 newcp
->cp_pclass
= targetclass
;
2268 newcp
->cp_key_os_version
= cp_os_version();
2269 newcp
->cp_key_revision
= key_revision
;
2272 * If we got here, then we have a new cprotect.
2273 * Attempt to write the new one out.
2275 error
= cp_setxattr (cp
, newcp
, hfsmp
, cp
->c_fileid
, XATTR_REPLACE
);
2278 /* Tear down the new cprotect; Tell MKB that it's invalid. Bail out */
2279 /* TODO: rdar://12170074 needs to be fixed before we can tell MKB */
2281 cp_entry_destroy(hfsmp
, newcp
);
2287 * If we get here then we can assert that:
2288 * 1) generated wrapped/unwrapped keys.
2289 * 2) wrote the new keys to disk.
2290 * 3) cprotect is ready to go.
2300 void cp_replace_entry (hfsmount_t
*hfsmp
, struct cnode
*cp
, struct cprotect
*newentry
)
2302 if (cp
->c_cpentry
) {
2303 #if HFS_CONFIG_KEY_ROLL
2304 // Transfer the tentative reservation
2305 if (cp
->c_cpentry
->cp_key_roll_ctx
&& newentry
->cp_key_roll_ctx
) {
2306 newentry
->cp_key_roll_ctx
->ckr_tentative_reservation
2307 = cp
->c_cpentry
->cp_key_roll_ctx
->ckr_tentative_reservation
;
2309 cp
->c_cpentry
->cp_key_roll_ctx
->ckr_tentative_reservation
= NULL
;
2313 cp_entry_destroy (hfsmp
, cp
->c_cpentry
);
2315 cp
->c_cpentry
= newentry
;
2316 newentry
->cp_backing_cnode
= cp
;
2325 * Given a double-pointer to a cprotect, generate keys (either in-kernel or from keystore),
2326 * allocate a cprotect, and vend it back to the caller.
2328 * Additionally, decide if keys are even needed -- directories get cprotect data structures
2329 * but they do not have keys.
2334 cp_new(cp_key_class_t
*newclass_eff
, __unused
struct hfsmount
*hfsmp
, struct cnode
*cp
,
2335 mode_t cmode
, int32_t keyflags
, cp_key_revision_t key_revision
,
2336 cp_new_alloc_fn alloc_fn
, void **pholder
)
2339 uint8_t new_key
[CP_MAX_CACHEBUFLEN
];
2340 unsigned new_key_len
= CP_MAX_CACHEBUFLEN
; /* AKS tell us the proper key length, how much of this is used */
2341 uint8_t new_persistent_key
[CP_MAX_WRAPPEDKEYSIZE
];
2342 unsigned new_persistent_len
= CP_MAX_WRAPPEDKEYSIZE
;
2343 uint8_t iv_key
[CP_IV_KEYSIZE
];
2344 unsigned iv_key_len
= CP_IV_KEYSIZE
;
2346 cp_key_class_t key_class
= CP_CLASS(*newclass_eff
);
2348 /* Structures passed between HFS and AKS */
2349 struct aks_cred_s access_in
;
2350 struct aks_wrapped_key_s wrapped_key_out
;
2351 struct aks_raw_key_s key_out
;
2353 /* Sanity check that it's a file or directory here */
2354 if (!(S_ISREG(cmode
)) && !(S_ISDIR(cmode
))) {
2359 * Step 1: Generate Keys if needed.
2361 * For class F files, the kernel provides the key.
2362 * PROTECTION_CLASS_F is in-use by VM swapfile; it represents a transient
2363 * key that is only good as long as the file is open. There is no
2364 * wrapped key, so there isn't anything to wrap.
2366 * For class A->D files, the key store provides the key
2368 * For Directories, we only give them a class ; no keys.
2370 if (S_ISDIR (cmode
)) {
2372 new_persistent_len
= 0;
2378 /* Must be a file */
2379 if (key_class
== PROTECTION_CLASS_F
) {
2380 /* class F files are not wrapped; they can still use the max key size */
2381 new_key_len
= CP_MAX_KEYSIZE
;
2382 read_random (&new_key
[0], new_key_len
);
2383 new_persistent_len
= 0;
2389 * The keystore is provided the file ID so that it can associate
2390 * the wrapped backup blob with this key from userspace. This
2391 * lookup occurs after successful file creation. Beyond this, the
2392 * file ID is not used. Note that there is a potential race here if
2393 * the file ID is re-used.
2395 cp_init_access(&access_in
, cp
);
2397 bzero(&key_out
, sizeof(key_out
));
2398 key_out
.key
= new_key
;
2399 key_out
.iv_key
= iv_key
;
2401 * AKS will override our key length fields, but we need to supply
2402 * the length of the buffer in those length fields so that
2403 * AKS knows hoa many bytes it has to work with.
2405 key_out
.key_len
= new_key_len
;
2406 key_out
.iv_key_len
= iv_key_len
;
2408 bzero(&wrapped_key_out
, sizeof(wrapped_key_out
));
2409 wrapped_key_out
.key
= new_persistent_key
;
2410 wrapped_key_out
.key_len
= new_persistent_len
;
2412 access_in
.key_revision
= key_revision
;
2414 error
= hfs_new_key(&access_in
,
2420 /* keybag returned failure */
2425 /* Now sanity-check the output from new_key */
2426 if (key_out
.key_len
== 0 || key_out
.key_len
> CP_MAX_CACHEBUFLEN
) {
2427 panic ("cp_new: invalid key length! (%ul) \n", key_out
.key_len
);
2430 if (key_out
.iv_key_len
!= CP_IV_KEYSIZE
) {
2431 panic ("cp_new: invalid iv key length! (%ul) \n", key_out
.iv_key_len
);
2435 * AKS is allowed to override our preferences and wrap with a
2436 * different class key for policy reasons. If we were told that
2437 * any class other than the one specified is unacceptable then error out
2438 * if that occurred. Check that the effective class returned by
2439 * AKS is the same as our effective new class
2441 if (CP_CLASS(wrapped_key_out
.dp_class
) != key_class
) {
2442 if (!ISSET(keyflags
, CP_KEYWRAP_DIFFCLASS
)) {
2444 /* TODO: When 12170074 fixed, release/invalidate the key! */
2449 *newclass_eff
= wrapped_key_out
.dp_class
;
2450 new_key_len
= key_out
.key_len
;
2451 iv_key_len
= key_out
.iv_key_len
;
2452 new_persistent_len
= wrapped_key_out
.key_len
;
2454 /* Is the key a SEP wrapped key? */
2455 if (key_out
.flags
& AKS_RAW_KEY_WRAPPEDKEY
) {
2462 * Step 2: allocate cprotect and initialize it.
2465 cp_key_pair_t
*cpkp
;
2466 *pholder
= alloc_fn(NULL
, new_persistent_len
, new_key_len
, &cpkp
);
2467 if (*pholder
== NULL
) {
2471 /* Copy the cache key & IV keys into place if needed. */
2472 if (new_key_len
> 0) {
2473 cpx_t cpx
= cpkp_cpx(cpkp
);
2475 cpx_set_key_len(cpx
, new_key_len
);
2476 memcpy(cpx_key(cpx
), new_key
, new_key_len
);
2478 /* Initialize the IV key */
2479 if (key_class
!= PROTECTION_CLASS_F
)
2480 cpx_set_aes_iv_key(cpx
, iv_key
);
2482 cpx_set_is_sep_wrapped_key(cpx
, iswrapped
);
2484 if (new_persistent_len
> 0) {
2485 cpkp_set_pers_key_len(cpkp
, new_persistent_len
);
2486 memcpy(cpkp_pers_key(cpkp
), new_persistent_key
, new_persistent_len
);
2493 if ((hfsmp
->hfs_cp_verbose
) && (error
== EPERM
)) {
2494 /* Only introspect the data fork */
2495 cp_log_eperm (cp
->c_vp
, *newclass_eff
, true);
2504 /* Initialize the aks_cred_t structure passed to AKS */
2505 static void cp_init_access(aks_cred_t access
, struct cnode
*cp
)
2507 vfs_context_t context
= vfs_context_current();
2508 kauth_cred_t cred
= vfs_context_ucred(context
);
2509 proc_t proc
= vfs_context_proc(context
);
2510 struct hfsmount
*hfsmp
;
2514 bzero(access
, sizeof(*access
));
2521 //leave the struct bzeroed.
2527 hfs_getvoluuid(hfsmp
, hfs_uuid
);
2529 /* Note: HFS uses 32-bit fileID, even though inode is a 64-bit value */
2530 access
->inode
= cp
->c_fileid
;
2531 access
->pid
= proc_pid(proc
);
2532 access
->uid
= kauth_cred_getuid(cred
);
2533 uuid_copy (access
->volume_uuid
, hfs_uuid
);
2536 access
->key_revision
= cp
->c_cpentry
->cp_key_revision
;
2541 #if HFS_CONFIG_KEY_ROLL
2543 errno_t
cp_set_auto_roll(hfsmount_t
*hfsmp
,
2544 const hfs_key_auto_roll_args_t
*args
)
2546 // 64 bytes should be OK on the stack
2547 _Static_assert(sizeof(struct cp_root_xattr
) < 64, "cp_root_xattr too big!");
2549 struct cp_root_xattr xattr
;
2552 ret
= cp_getrootxattr(hfsmp
, &xattr
);
2556 ret
= hfs_start_transaction(hfsmp
);
2560 xattr
.auto_roll_min_version
= args
->min_key_os_version
;
2561 xattr
.auto_roll_max_version
= args
->max_key_os_version
;
2563 bool roll_old_class_gen
= ISSET(args
->flags
, HFS_KEY_AUTO_ROLL_OLD_CLASS_GENERATION
);
2565 if (roll_old_class_gen
)
2566 SET(xattr
.flags
, CP_ROOT_AUTO_ROLL_OLD_CLASS_GENERATION
);
2568 CLR(xattr
.flags
, CP_ROOT_AUTO_ROLL_OLD_CLASS_GENERATION
);
2570 ret
= cp_setrootxattr(hfsmp
, &xattr
);
2572 errno_t ret2
= hfs_end_transaction(hfsmp
);
2580 hfs_lock_mount(hfsmp
);
2581 hfsmp
->hfs_auto_roll_min_key_os_version
= args
->min_key_os_version
;
2582 hfsmp
->hfs_auto_roll_max_key_os_version
= args
->max_key_os_version
;
2583 hfs_unlock_mount(hfsmp
);
2588 bool cp_should_auto_roll(hfsmount_t
*hfsmp
, cprotect_t cpr
)
2590 if (cpr
->cp_key_roll_ctx
) {
2595 // Only automatically roll class A, B & C
2596 if (CP_CLASS(cpr
->cp_pclass
) < PROTECTION_CLASS_A
2597 || CP_CLASS(cpr
->cp_pclass
) > PROTECTION_CLASS_C
) {
2601 if (!cpkp_has_pers_key(&cpr
->cp_keys
))
2605 * Remember, the class generation stored in HFS+ is updated at the *end*,
2606 * so it's old if it matches the generation we have stored.
2608 if (ISSET(hfsmp
->cproot_flags
, CP_ROOT_AUTO_ROLL_OLD_CLASS_GENERATION
)
2609 && cp_get_crypto_generation(cpr
->cp_pclass
) == hfsmp
->cp_crypto_generation
) {
2613 if (!hfsmp
->hfs_auto_roll_min_key_os_version
2614 && !hfsmp
->hfs_auto_roll_max_key_os_version
) {
2615 // No minimum or maximum set
2619 if (hfsmp
->hfs_auto_roll_min_key_os_version
2620 && cpr
->cp_key_os_version
< hfsmp
->hfs_auto_roll_min_key_os_version
) {
2625 if (hfsmp
->hfs_auto_roll_max_key_os_version
2626 && cpr
->cp_key_os_version
>= hfsmp
->hfs_auto_roll_max_key_os_version
) {
2627 // Greater than maximum
2634 #endif // HFS_CONFIG_KEY_ROLL
2636 errno_t
cp_handle_strategy(buf_t bp
)
2638 vnode_t vp
= buf_vnode(bp
);
2641 if (bufattr_rawencrypted(buf_attr(bp
))
2642 || !(cp
= cp_get_protected_cnode(vp
))
2643 || !cp
->c_cpentry
) {
2649 * For filesystem resize, we may not have access to the underlying
2650 * file's cache key for whatever reason (device may be locked).
2651 * However, we do not need it since we are going to use the
2652 * temporary HFS-wide resize key which is generated once we start
2653 * relocating file content. If this file's I/O should be done
2654 * using the resize key, it will have been supplied already, so do
2655 * not attach the file's cp blob to the buffer.
2657 if (ISSET(cp
->c_cpentry
->cp_flags
, CP_RELOCATION_INFLIGHT
))
2660 #if HFS_CONFIG_KEY_ROLL
2662 * We don't require any locks here. Pages will be locked so no
2663 * key rolling can take place until this I/O has completed.
2665 if (!cp
->c_cpentry
->cp_key_roll_ctx
)
2669 cpx_t cpx
= cpkp_cpx(&cp
->c_cpentry
->cp_keys
);
2671 if (cpx_has_key(cpx
)) {
2672 bufattr_setcpx(buf_attr(bp
), cpx
);
2678 * We rely mostly (see note below) upon the truncate lock to
2679 * protect the CP cache key from getting tossed prior to our IO
2680 * finishing here. Nearly all cluster io calls to manipulate file
2681 * payload from HFS take the truncate lock before calling into the
2682 * cluster layer to ensure the file size does not change, or that
2683 * they have exclusive right to change the EOF of the file. That
2684 * same guarantee protects us here since the code that deals with
2685 * CP lock events must now take the truncate lock before doing
2688 * If you want to change content protection structures, then the
2689 * truncate lock is not sufficient; you must take the truncate
2690 * lock and then wait for outstanding writes to complete. This is
2691 * necessary because asynchronous I/O only holds the truncate lock
2692 * whilst I/O is being queued.
2694 * One exception should be the VM swapfile IO, because HFS will
2695 * funnel the VNOP_PAGEOUT directly into a cluster_pageout call
2696 * for the swapfile code only without holding the truncate lock.
2697 * This is because individual swapfiles are maintained at
2698 * fixed-length sizes by the VM code. In non-swapfile IO we use
2699 * PAGEOUT_V2 semantics which allow us to create our own UPL and
2700 * thus take the truncate lock before calling into the cluster
2701 * layer. In that case, however, we are not concerned with the CP
2702 * blob being wiped out in the middle of the IO because there
2703 * isn't anything to toss; the VM swapfile key stays in-core as
2704 * long as the file is open.
2707 off_rsrc_t off_rsrc
= off_rsrc_make(buf_lblkno(bp
) * GetLogicalBlockSize(vp
),
2709 cp_io_params_t io_params
;
2713 * We want to take the cnode lock here and because the vnode write
2714 * count is a pseudo-lock, we need to do something to preserve
2715 * lock ordering; the cnode lock comes before the write count.
2716 * Ideally, the write count would be incremented after the
2717 * strategy routine returns, but that becomes complicated if the
2718 * strategy routine where to call buf_iodone before returning.
2719 * For now, we drop the write count here and then pick it up again
2722 if (!ISSET(buf_flags(bp
), B_READ
) && !ISSET(buf_flags(bp
), B_RAW
))
2723 vnode_writedone(vp
);
2725 hfs_lock_always(cp
, HFS_SHARED_LOCK
);
2726 cp_io_params(VTOHFS(vp
), cp
->c_cpentry
, off_rsrc
,
2727 ISSET(buf_flags(bp
), B_READ
) ? VNODE_READ
: VNODE_WRITE
,
2732 * Last chance: If this data protected I/O does not have unwrapped
2733 * keys present, then try to get them. We already know that it
2734 * should, by this point.
2736 if (!cpx_has_key(io_params
.cpx
)) {
2737 int io_op
= ( (buf_flags(bp
) & B_READ
) ? CP_READ_ACCESS
: CP_WRITE_ACCESS
);
2738 errno_t error
= cp_handle_vnop(vp
, io_op
, 0);
2741 * We have to be careful here. By this point in the I/O
2742 * path, VM or the cluster engine has prepared a buf_t
2743 * with the proper file offsets and all the rest, so
2744 * simply erroring out will result in us leaking this
2745 * particular buf_t. We need to properly decorate the
2746 * buf_t just as buf_strategy would so as to make it
2747 * appear that the I/O errored out with the particular
2750 if (!ISSET(buf_flags(bp
), B_READ
) && !ISSET(buf_flags(bp
), B_RAW
))
2751 vnode_startwrite(vp
);
2752 buf_seterror (bp
, error
);
2757 hfs_lock_always(cp
, HFS_SHARED_LOCK
);
2758 cp_io_params(VTOHFS(vp
), cp
->c_cpentry
, off_rsrc
,
2759 ISSET(buf_flags(bp
), B_READ
) ? VNODE_READ
: VNODE_WRITE
,
2764 hfs_assert(buf_count(bp
) <= io_params
.max_len
);
2765 bufattr_setcpx(buf_attr(bp
), io_params
.cpx
);
2767 if (!ISSET(buf_flags(bp
), B_READ
) && !ISSET(buf_flags(bp
), B_RAW
))
2768 vnode_startwrite(vp
);
2773 #endif /* CONFIG_PROTECT */