]> git.saurik.com Git - apple/security.git/blob - keychain/ot/OTVouchWithBottleOperation.m
Security-59754.80.3.tar.gz
[apple/security.git] / keychain / ot / OTVouchWithBottleOperation.m
1 /*
2 * Copyright (c) 2018 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 #if OCTAGON
25
26 #import <utilities/debugging.h>
27
28 #import "keychain/ot/OTVouchWithBottleOperation.h"
29 #import "keychain/ot/OTClientStateMachine.h"
30 #import "keychain/ot/OTCuttlefishContext.h"
31 #import "keychain/ot/OTFetchCKKSKeysOperation.h"
32 #import "keychain/ot/OTStates.h"
33
34 #import "keychain/TrustedPeersHelper/TrustedPeersHelperProtocol.h"
35 #import "keychain/ot/ObjCImprovements.h"
36
37 @interface OTVouchWithBottleOperation ()
38 @property OTOperationDependencies* deps;
39
40 @property NSOperation* finishedOp;
41 @end
42
43 @implementation OTVouchWithBottleOperation
44 @synthesize intendedState = _intendedState;
45
46 - (instancetype)initWithDependencies:(OTOperationDependencies*)dependencies
47 intendedState:(OctagonState*)intendedState
48 errorState:(OctagonState*)errorState
49 bottleID:(NSString*)bottleID
50 entropy:(NSData*)entropy
51 bottleSalt:(NSString*)bottleSalt
52 saveVoucher:(BOOL)saveVoucher
53 {
54 if((self = [super init])) {
55 _deps = dependencies;
56 _intendedState = intendedState;
57 _nextState = errorState;
58
59 _bottleID = bottleID;
60 _entropy = entropy;
61 _bottleSalt = bottleSalt;
62
63 _saveVoucher = saveVoucher;
64 }
65 return self;
66 }
67
68 - (void)groupStart
69 {
70 secnotice("octagon", "creating voucher using a bottle with escrow record id: %@", self.bottleID);
71
72 self.finishedOp = [[NSOperation alloc] init];
73 [self dependOnBeforeGroupFinished:self.finishedOp];
74
75 if(self.bottleSalt != nil) {
76 secnotice("octagon", "using passed in altdsid, altdsid is: %@", self.bottleSalt);
77 } else{
78 NSError *error = nil;
79
80 NSString* altDSID = [self.deps.authKitAdapter primaryiCloudAccountAltDSID:&error];
81 if(altDSID){
82 secnotice("octagon", "fetched altdsid is: %@", altDSID);
83 self.bottleSalt = altDSID;
84 }
85 else {
86 secnotice("octagon", "authkit doesn't know about the altdsid, using stored value: %@", error);
87
88 NSError* accountError = nil;
89 OTAccountMetadataClassC* account = [self.deps.stateHolder loadOrCreateAccountMetadata:&accountError];
90
91 if(account && !accountError) {
92 secnotice("octagon", "retrieved account, altdsid is: %@", account.altDSID);
93 self.bottleSalt = account.altDSID;
94 }
95 if(accountError || !account){
96 secerror("failed to rerieve account object: %@", accountError);
97 }
98 }
99 }
100
101 // Preflight the vouch: this will tell us the peerID of the recovering peer.
102 // Then, filter the tlkShares array to include only tlks sent to that peer.
103 WEAKIFY(self);
104 [self.deps.cuttlefishXPCWrapper preflightVouchWithBottleWithContainer:self.deps.containerName
105 context:self.deps.contextID
106 bottleID:self.bottleID
107 reply:^(NSString * _Nullable peerID,
108 TPSyncingPolicy* peerSyncingPolicy,
109 BOOL refetchWasNeeded,
110 NSError * _Nullable error) {
111 STRONGIFY(self);
112 [[CKKSAnalytics logger] logResultForEvent:OctagonEventPreflightVouchWithBottle hardFailure:true result:error];
113
114 if(error || !peerID) {
115 secerror("octagon: Error preflighting voucher using bottle: %@", error);
116 self.error = error;
117 [self runBeforeGroupFinished:self.finishedOp];
118 return;
119 }
120
121 secnotice("octagon", "Bottle %@ is for peerID %@", self.bottleID, peerID);
122
123 // Tell CKKS to spin up the new views and policy
124 // But, do not persist this view set! We'll do that when we actually manager to join
125 [self.deps.viewManager setCurrentSyncingPolicy:peerSyncingPolicy];
126
127 [self proceedWithPeerID:peerID refetchWasNeeded:refetchWasNeeded];
128 }];
129 }
130
131 - (void)proceedWithPeerID:(NSString*)peerID refetchWasNeeded:(BOOL)refetchWasNeeded
132 {
133 WEAKIFY(self);
134
135 // After a vouch, we also want to acquire all TLKs that the bottled peer might have had
136 OTFetchCKKSKeysOperation* fetchKeysOp = [[OTFetchCKKSKeysOperation alloc] initWithDependencies:self.deps
137 refetchNeeded:refetchWasNeeded];
138 [self runBeforeGroupFinished:fetchKeysOp];
139
140 CKKSResultOperation* proceedWithKeys = [CKKSResultOperation named:@"bottle-tlks"
141 withBlock:^{
142 STRONGIFY(self);
143
144 NSMutableArray<CKKSTLKShare*>* filteredTLKShares = [NSMutableArray array];
145 for(CKKSTLKShare* share in fetchKeysOp.tlkShares) {
146 // If we didn't get a peerID, just pass every tlkshare and hope for the best
147 if(peerID == nil || [share.receiverPeerID isEqualToString:peerID]) {
148 [filteredTLKShares addObject:share];
149 }
150 }
151
152 if(fetchKeysOp.viewsTimedOutWithoutKeysets.count > 0) {
153 // At least one view failed to find a keyset in time.
154 // Set up a retry with this bottle, once CKKS is done fetching
155 secnotice("octagon", "Timed out fetching key hierarchy for CKKS views; marking for TLK recovery follow up: %@", fetchKeysOp.viewsTimedOutWithoutKeysets);
156 OctagonPendingFlag* flag = [[OctagonPendingFlag alloc] initWithFlag:OctagonFlagAttemptBottleTLKExtraction
157 after:self.deps.viewManager.zoneChangeFetcher.inflightFetch];
158 [self.deps.flagHandler handlePendingFlag:flag];
159 }
160
161 [self proceedWithKeys:fetchKeysOp.viewKeySets filteredTLKShares:filteredTLKShares];
162 }];
163
164 [proceedWithKeys addDependency:fetchKeysOp];
165 [self runBeforeGroupFinished:proceedWithKeys];
166 }
167
168
169 - (void)noteMetric:(NSString*)metric count:(int64_t)count
170 {
171 NSString* metricName = [NSString stringWithFormat:@"%@%lld", metric, count];
172
173 [[CKKSAnalytics logger] logResultForEvent:metricName
174 hardFailure:NO
175 result:nil];
176
177 [[CKKSAnalytics logger] setDateProperty:[NSDate date] forKey:metricName];
178 [[CKKSAnalytics logger] setNumberProperty:[[NSNumber alloc]initWithLong:count] forKey:metric];
179 }
180
181 - (void)proceedWithKeys:(NSArray<CKKSKeychainBackedKeySet*>*)viewKeySets filteredTLKShares:(NSArray<CKKSTLKShare*>*)tlkShares
182 {
183 WEAKIFY(self);
184
185 [self.deps.cuttlefishXPCWrapper vouchWithBottleWithContainer:self.deps.containerName
186 context:self.deps.contextID
187 bottleID:self.bottleID
188 entropy:self.entropy
189 bottleSalt:self.bottleSalt
190 tlkShares:tlkShares
191 reply:^(NSData * _Nullable voucher,
192 NSData * _Nullable voucherSig,
193 int64_t uniqueTLKsRecovered,
194 int64_t totalTLKSharesRecovered,
195 NSError * _Nullable error) {
196 STRONGIFY(self);
197 [[CKKSAnalytics logger] logResultForEvent:OctagonEventVoucherWithBottle hardFailure:true result:error];
198
199 if(error){
200 secerror("octagon: Error preparing voucher using bottle: %@", error);
201 self.error = error;
202 [self runBeforeGroupFinished:self.finishedOp];
203 return;
204 }
205
206 //collect TLK count metrics
207 [self noteMetric:OctagonAnalyticsBottledUniqueTLKsRecovered count:uniqueTLKsRecovered];
208 [self noteMetric:OctagonAnalyticsBottledTotalTLKSharesRecovered count:totalTLKSharesRecovered];
209 [self noteMetric:OctagonAnalyticsBottledTotalTLKShares count:tlkShares.count];
210
211 NSMutableSet<NSString*>* uniqueTLKsWithShares = [NSMutableSet set];
212 for (CKKSTLKShare* share in tlkShares) {
213 [uniqueTLKsWithShares addObject:share.tlkUUID];
214 }
215
216 [self noteMetric:OctagonAnalyticsBottledUniqueTLKsWithSharesCount count:uniqueTLKsWithShares.count];
217
218 NSMutableDictionary *views = [NSMutableDictionary dictionary];
219 for (CKKSTLKShare *share in tlkShares) {
220 views[share.zoneID] = share.zoneID;
221 }
222 [self noteMetric:OctagonAnalyticsBottledTLKUniqueViewCount count:views.count];
223
224 self.voucher = voucher;
225 self.voucherSig = voucherSig;
226
227 if(self.saveVoucher) {
228 secnotice("octagon", "Saving voucher for later use...");
229 NSError* saveError = nil;
230 [self.deps.stateHolder persistAccountChanges:^OTAccountMetadataClassC * _Nullable(OTAccountMetadataClassC * _Nonnull metadata) {
231 metadata.voucher = voucher;
232 metadata.voucherSignature = voucherSig;
233 return metadata;
234 } error:&saveError];
235 if(saveError) {
236 secnotice("octagon", "unable to save voucher: %@", saveError);
237 [self runBeforeGroupFinished:self.finishedOp];
238 return;
239 }
240 }
241
242 secnotice("octagon", "Successfully vouched with a bottle: %@, %@", voucher, voucherSig);
243 self.nextState = self.intendedState;
244 [self runBeforeGroupFinished:self.finishedOp];
245 }];
246 }
247
248 @end
249
250 #endif // OCTAGON