]> git.saurik.com Git - apple/security.git/blob - keychain/ckks/CKKSProcessReceivedKeysOperation.m
Security-58286.60.28.tar.gz
[apple/security.git] / keychain / ckks / CKKSProcessReceivedKeysOperation.m
1 /*
2 * Copyright (c) 2016 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 #import <AssertMacros.h>
25
26 #import "CKKSKeychainView.h"
27 #import "CKKSCurrentKeyPointer.h"
28 #import "CKKSKey.h"
29 #import "CKKSProcessReceivedKeysOperation.h"
30 #import "keychain/ckks/CloudKitCategories.h"
31
32 #if OCTAGON
33
34 @implementation CKKSProcessReceivedKeysOperation
35
36 - (instancetype)init {
37 return nil;
38 }
39 - (instancetype)initWithCKKSKeychainView:(CKKSKeychainView*)ckks {
40 if(self = [super init]) {
41 _ckks = ckks;
42 }
43 return self;
44 }
45
46 - (void) main {
47 // Synchronous, on some thread. Get back on the CKKS queue for SQL thread-safety.
48
49 // Take a strong reference.
50 CKKSKeychainView* ckks = self.ckks;
51 if(!ckks) {
52 secerror("ckkskeys: No CKKS object");
53 return;
54 }
55
56 if(self.cancelled) {
57 ckksinfo("ckkskey", ckks, "CKKSProcessReceivedKeysOperation cancelled, quitting");
58 return;
59 }
60
61 [ckks dispatchSyncWithAccountKeys: ^bool{
62 if(self.cancelled) {
63 ckksinfo("ckkskey", ckks, "CKKSProcessReceivedKeysOperation cancelled, quitting");
64 return false;
65 }
66
67 ckks.lastProcessReceivedKeysOperation = self;
68
69 NSError* error = nil;
70 CKKSKey* tlk = nil;
71 CKKSKey* topKey = nil;
72
73 // The synckeys table contains everything that's in CloudKit, if looked at correctly.
74 // Updates from CloudKit are marked 'remote'; everything else is 'local'.
75
76 // Step 1. Find all remote keys.
77 NSArray<CKKSKey*>* remoteKeys = [CKKSKey remoteKeys:ckks.zoneID error:&error];
78 if(!remoteKeys) {
79 ckkserror("ckkskey", ckks, "couldn't fetch list of remote keys: %@", error);
80 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateError withError:error];
81 return false;
82 }
83
84 if([remoteKeys count] == 0u) {
85 ckksnotice("ckkskey", ckks, "No remote keys? Quitting.");
86 // Not a ready state, more of a quizzical one? The key state machine will know what to do.
87 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateReady withError:error];
88 return false;
89 }
90
91 ckksinfo("ckkskey", ckks, "remote keys: %@", remoteKeys);
92
93 // current TLK record:
94 CKKSCurrentKeyPointer* currentTLKPointer = [CKKSCurrentKeyPointer tryFromDatabase: SecCKKSKeyClassTLK zoneID:ckks.zoneID error:&error];
95 CKKSCurrentKeyPointer* currentClassAPointer = [CKKSCurrentKeyPointer tryFromDatabase: SecCKKSKeyClassA zoneID:ckks.zoneID error:&error];
96 CKKSCurrentKeyPointer* currentClassCPointer = [CKKSCurrentKeyPointer tryFromDatabase: SecCKKSKeyClassC zoneID:ckks.zoneID error:&error];
97
98 // Do these pointers point at anything?
99 NSError* localerror = nil;
100 CKKSKey* suggestedTLK = currentTLKPointer.currentKeyUUID ? [CKKSKey tryFromDatabaseAnyState:currentTLKPointer.currentKeyUUID zoneID:ckks.zoneID error:&localerror] : nil;
101 CKKSKey* suggestedClassA = currentClassAPointer.currentKeyUUID ? [CKKSKey tryFromDatabaseAnyState:currentClassAPointer.currentKeyUUID zoneID:ckks.zoneID error:&localerror] : nil;
102 CKKSKey* suggestedClassC = currentClassCPointer.currentKeyUUID ? [CKKSKey tryFromDatabaseAnyState:currentClassCPointer.currentKeyUUID zoneID:ckks.zoneID error:&localerror] : nil;
103
104 if(!currentTLKPointer || !currentClassAPointer || !currentClassCPointer ||
105 !currentTLKPointer.currentKeyUUID || !currentClassAPointer.currentKeyUUID || !currentClassCPointer.currentKeyUUID ||
106 !suggestedTLK || !suggestedClassA || !suggestedClassC) {
107 ckkserror("ckkskey", ckks, "no current pointer for some keyclass: tlk:%@ a:%@ c:%@ %@ %@",
108 currentTLKPointer, currentClassAPointer, currentClassCPointer, error, localerror);
109 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateBadCurrentPointers withError:error];
110 return true;
111 }
112
113 for(CKKSKey* key in remoteKeys) {
114 // Find the active TLK.
115 if([key.uuid isEqualToString: currentTLKPointer.currentKeyUUID]) {
116 if([key wrapsSelf]) {
117 tlk = key;
118 } else {
119 ckkserror("ckkskey", ckks, "current TLK doesn't wrap itself: %@ %@", key, key.parentKeyUUID);
120 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateUnhealthy withError:error];
121 return true;
122 }
123 }
124 }
125
126 if(!tlk) {
127 ckkserror("ckkskey", ckks, "couldn't find active TLK: %@", currentTLKPointer);
128 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateUnhealthy withError:error];
129 return true;
130 }
131
132 // This key is our proposed TLK. Check with the CKKS object.
133 if(![ckks _onqueueWithAccountKeysCheckTLK: tlk error: &error]) {
134 // Was this error "I've never seen that TLK before in my life"? If so, enter the "wait for TLK sync" state.
135 if(error && [error.domain isEqualToString: @"securityd"] && error.code == errSecItemNotFound) {
136 ckksnotice("ckkskey", ckks, "Received a TLK which we don't have in the local keychain(%@). Entering waitfortlk.", tlk);
137 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateWaitForTLK withError:nil];
138 return true;
139 } else if(error && [ckks.lockStateTracker isLockedError:error]) {
140 // TODO: _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateError should handle this. But, we don't have tests, so, leave this in until 33204154
141 ckksnotice("ckkskey", ckks, "Received a TLK(%@), but keybag appears to be locked. Entering a waiting state.", tlk);
142 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateWaitForUnlock withError:nil];
143 return true;
144 } else {
145 // Otherwise, something has gone horribly wrong. enter error state.
146 ckkserror("ckkskey", ckks, "CKKS claims %@ is not a valid TLK: %@", tlk, error);
147 NSError* newError = [NSError errorWithDomain:CKKSErrorDomain code:CKKSInvalidTLK description:@"invalid TLK from CloudKit" underlying:error];
148 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateError withError:newError];
149 return true;
150 }
151 }
152
153 // Ensure that new keys wrap to the TLK.
154 for(CKKSKey* key in remoteKeys) {
155 if(key == tlk) {
156 continue;
157 }
158
159 topKey = [key topKeyInAnyState:&error];
160
161 if(error != nil || ![topKey.uuid isEqual: tlk.uuid]) {
162 ckkserror("ckkskey", ckks, "new key %@ is orphaned (%@)", key, error);
163 // TODO: possibly re-fetch. Maybe not an actual error state.
164 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateError
165 withError:[NSError errorWithDomain:CKKSErrorDomain
166 code:CKKSOrphanedKey
167 description:[NSString stringWithFormat:@"orphaned key(%@) in hierarchy", topKey]
168 underlying:error]];
169 return true;
170
171 }
172
173 // Okay, it wraps to the TLK. Can we unwrap it?
174 if(![key unwrapViaKeyHierarchy:&error] || error != nil) {
175 if(error && [ckks.lockStateTracker isLockedError:error]) {
176 ckksnotice("ckkskey", ckks, "Couldn't unwrap new key (%@), but keybag appears to be locked. Entering waitforunlock.", key);
177 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateWaitForUnlock withError:error];
178 return true;
179 } else {
180 ckkserror("ckkskey", ckks, "new key %@ claims to wrap to TLK, but we can't unwrap it: %@", topKey, error);
181 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateError
182 withError:[NSError errorWithDomain:CKKSErrorDomain
183 code:CKKSOrphanedKey
184 description:[NSString stringWithFormat:@"unwrappable key(%@) in hierarchy: %@", topKey, error]
185 underlying:error]];
186 return true;
187 }
188 }
189
190 ckksnotice("ckkskey", ckks, "New key %@ wraps to tlk %@", key, tlk);
191 }
192
193
194 // We're happy with this key hierarchy. Save it.
195 for(CKKSKey* key in remoteKeys) {
196 key.state = SecCKKSProcessedStateLocal;
197
198 if([key.uuid isEqualToString: currentClassAPointer.currentKeyUUID] ||
199 [key.uuid isEqualToString: currentClassCPointer.currentKeyUUID]) {
200 [key saveToDatabaseAsOnlyCurrentKeyForClassAndState: &error];
201 } else {
202 [key saveToDatabase: &error];
203 }
204
205 [key saveKeyMaterialToKeychain: &error];
206
207 if(error) {
208 ckkserror("ckkskey", ckks, "couldn't save newly local key %@ to database: %@", key, error);
209 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateError withError: error];
210 return false;
211 }
212 }
213
214 if(!error) {
215 ckksnotice("ckkskey", ckks, "Accepted new key hierarchy");
216 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateReady withError: nil];
217 } else {
218 ckkserror("ckkskey", ckks, "error accepting new key hierarchy: %@", error);
219 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateError withError: error];
220 }
221 return true;
222 }];
223 }
224
225 @end;
226
227 #endif