]> git.saurik.com Git - apple/security.git/blob - keychain/ckks/CKKSProcessReceivedKeysOperation.m
Security-58286.41.2.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
31 #if OCTAGON
32
33 @implementation CKKSProcessReceivedKeysOperation
34
35 - (instancetype)init {
36 return nil;
37 }
38 - (instancetype)initWithCKKSKeychainView:(CKKSKeychainView*)ckks {
39 if(self = [super init]) {
40 _ckks = ckks;
41 }
42 return self;
43 }
44
45 - (void) main {
46 // Synchronous, on some thread. Get back on the CKKS queue for SQL thread-safety.
47
48 // Take a strong reference.
49 CKKSKeychainView* ckks = self.ckks;
50 if(!ckks) {
51 secerror("ckkskeys: No CKKS object");
52 return;
53 }
54
55 if(self.cancelled) {
56 ckksinfo("ckkskey", ckks, "CKKSProcessReceivedKeysOperation cancelled, quitting");
57 return;
58 }
59
60 [ckks dispatchSyncWithAccountKeys: ^bool{
61 if(self.cancelled) {
62 ckksinfo("ckkskey", ckks, "CKKSProcessReceivedKeysOperation cancelled, quitting");
63 return false;
64 }
65
66 ckks.lastProcessReceivedKeysOperation = self;
67
68 NSError* error = nil;
69 CKKSKey* tlk = nil;
70 CKKSKey* topKey = nil;
71
72 // The synckeys table contains everything that's in CloudKit, if looked at correctly.
73 // Updates from CloudKit are marked 'remote'; everything else is 'local'.
74
75 // Step 1. Find all remote keys.
76 NSArray<CKKSKey*>* remoteKeys = [CKKSKey remoteKeys:ckks.zoneID error:&error];
77 if(!remoteKeys) {
78 ckkserror("ckkskey", ckks, "couldn't fetch list of remote keys: %@", error);
79 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateError withError:error];
80 return false;
81 }
82
83 if([remoteKeys count] == 0u) {
84 ckksnotice("ckkskey", ckks, "No remote keys? Quitting.");
85 // Not a ready state, more of a quizzical one? The key state machine will know what to do.
86 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateReady withError:error];
87 return false;
88 }
89
90 ckksinfo("ckkskey", ckks, "remote keys: %@", remoteKeys);
91
92 // current TLK record:
93 CKKSCurrentKeyPointer* currentTLKPointer = [CKKSCurrentKeyPointer tryFromDatabase: SecCKKSKeyClassTLK zoneID:ckks.zoneID error:&error];
94 CKKSCurrentKeyPointer* currentClassAPointer = [CKKSCurrentKeyPointer tryFromDatabase: SecCKKSKeyClassA zoneID:ckks.zoneID error:&error];
95 CKKSCurrentKeyPointer* currentClassCPointer = [CKKSCurrentKeyPointer tryFromDatabase: SecCKKSKeyClassC zoneID:ckks.zoneID error:&error];
96
97 // Do these pointers point at anything?
98 NSError* localerror = nil;
99 CKKSKey* suggestedTLK = currentTLKPointer.currentKeyUUID ? [CKKSKey tryFromDatabaseAnyState:currentTLKPointer.currentKeyUUID zoneID:ckks.zoneID error:&localerror] : nil;
100 CKKSKey* suggestedClassA = currentClassAPointer.currentKeyUUID ? [CKKSKey tryFromDatabaseAnyState:currentClassAPointer.currentKeyUUID zoneID:ckks.zoneID error:&localerror] : nil;
101 CKKSKey* suggestedClassC = currentClassCPointer.currentKeyUUID ? [CKKSKey tryFromDatabaseAnyState:currentClassCPointer.currentKeyUUID zoneID:ckks.zoneID error:&localerror] : nil;
102
103 if(!currentTLKPointer || !currentClassAPointer || !currentClassCPointer ||
104 !currentTLKPointer.currentKeyUUID || !currentClassAPointer.currentKeyUUID || !currentClassCPointer.currentKeyUUID ||
105 !suggestedTLK || !suggestedClassA || !suggestedClassC) {
106 ckkserror("ckkskey", ckks, "no current pointer for some keyclass: tlk:%@ a:%@ c:%@ %@ %@",
107 currentTLKPointer, currentClassAPointer, currentClassCPointer, error, localerror);
108 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateBadCurrentPointers withError:error];
109 return true;
110 }
111
112 for(CKKSKey* key in remoteKeys) {
113 // Find the active TLK.
114 if([key.uuid isEqualToString: currentTLKPointer.currentKeyUUID]) {
115 if([key wrapsSelf]) {
116 tlk = key;
117 } else {
118 ckkserror("ckkskey", ckks, "current TLK doesn't wrap itself: %@", key);
119 // TODO: re-fetch?
120 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateReady withError:error];
121 return true;
122 }
123 }
124 }
125
126 if(!tlk) {
127 ckkserror("ckkskey", ckks, "couldn't find active TLK: %@", currentTLKPointer);
128 // TODO: re-fetch?
129 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateReady withError:error];
130 return true;
131 }
132
133 // This key is our proposed TLK. Check with the CKKS object.
134 if(![ckks _onqueueWithAccountKeysCheckTLK: tlk error: &error]) {
135 // Was this error "I've never seen that TLK before in my life"? If so, enter the "wait for TLK sync" state.
136 if(error && [error.domain isEqualToString: @"securityd"] && error.code == errSecItemNotFound) {
137 ckksnotice("ckkskey", ckks, "Received a TLK which we don't have in the local keychain(%@). Entering waitfortlk.", tlk);
138 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateWaitForTLK withError:nil];
139 return true;
140 } else if(error && [ckks.lockStateTracker isLockedError:error]) {
141 // TODO: _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateError should handle this. But, we don't have tests, so, leave this in until 33204154
142 ckksnotice("ckkskey", ckks, "Received a TLK(%@), but keybag appears to be locked. Entering a waiting state.", tlk);
143 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateWaitForUnlock withError:nil];
144 return true;
145 } else {
146 // Otherwise, something has gone horribly wrong. enter error state.
147 ckkserror("ckkskey", ckks, "CKKS claims %@ is not a valid TLK: %@", tlk, error);
148 NSError* newError = nil;
149 if(error) {
150 newError = [NSError errorWithDomain: @"securityd" code:0 userInfo:@{NSLocalizedDescriptionKey: @"invalid TLK from CloudKit", NSUnderlyingErrorKey: error}];
151 } else {
152 newError = [NSError errorWithDomain: @"securityd" code:0 userInfo:@{NSLocalizedDescriptionKey: @"invalid TLK from CloudKit (unknown error)"}];
153 }
154 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateError withError:newError];
155 return true;
156 }
157 }
158
159 // Ensure that new keys wrap to the TLK.
160 for(CKKSKey* key in remoteKeys) {
161 if(key == tlk) {
162 continue;
163 }
164
165 topKey = [key topKeyInAnyState:&error];
166
167 if(error != nil || ![topKey.uuid isEqual: tlk.uuid]) {
168 ckkserror("ckkskey", ckks, "new key %@ is orphaned (%@)", key, error);
169 // TODO: possibly re-fetch. Maybe not an actual error state.
170 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateError withError: error ? error : [NSError errorWithDomain: @"securityd" code:0 userInfo:@{NSLocalizedDescriptionKey: @"orphaned key in hierarchy", NSUnderlyingErrorKey: error}]];
171 return true;
172 }
173
174 // Okay, it wraps to the TLK. Can we unwrap it?
175 if(![key unwrapViaKeyHierarchy:&error] || error != nil) {
176 ckkserror("ckkskey", ckks, "new key %@ claims to wrap to TLK, but we can't unwrap it: %@", topKey, error);
177 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateError withError: error ? error : [NSError errorWithDomain: @"securityd" code:0 userInfo:@{NSLocalizedDescriptionKey: @"orphaned/couldn't unwrap key in hierarchy", NSUnderlyingErrorKey: error}]];
178 return true;
179 }
180
181 ckksnotice("ckkskey", ckks, "New key %@ wraps to tlk %@", key, tlk);
182 }
183
184
185 // We're happy with this key hierarchy. Save it.
186 for(CKKSKey* key in remoteKeys) {
187 key.state = SecCKKSProcessedStateLocal;
188
189 if([key.uuid isEqualToString: currentClassAPointer.currentKeyUUID] ||
190 [key.uuid isEqualToString: currentClassCPointer.currentKeyUUID]) {
191 [key saveToDatabaseAsOnlyCurrentKeyForClassAndState: &error];
192 } else {
193 [key saveToDatabase: &error];
194 }
195
196 [key saveKeyMaterialToKeychain: &error];
197
198 if(error) {
199 ckkserror("ckkskey", ckks, "couldn't save newly local key %@ to database: %@", key, error);
200 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateError withError: error];
201 return false;
202 }
203 }
204
205 if(!error) {
206 ckksnotice("ckkskey", ckks, "Accepted new key hierarchy");
207 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateReady withError: nil];
208 } else {
209 ckkserror("ckkskey", ckks, "error accepting new key hierarchy: %@", error);
210 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateError withError: error];
211 }
212 return true;
213 }];
214 }
215
216 @end;
217
218 #endif