2 * Copyright (c) 2013-2014 Apple Inc. All Rights Reserved.
4 * @APPLE_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. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
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.
21 * @APPLE_LICENSE_HEADER_END@
26 #include <AssertMacros.h>
27 #include "SOSAccountPriv.h"
28 #include "SOSPeerInfoCollections.h"
29 #include "SOSTransport.h"
30 #import "keychain/SecureObjectSync/SOSAccountTrust.h"
31 #import "keychain/SecureObjectSync/SOSAccountTrustClassic+Circle.h"
33 #define kPublicKeyAvailable "com.apple.security.publickeyavailable"
35 // MARK: User Credential management
39 // List of things to do
40 // Update myFullPeerInfo in circle if needed
41 // Fix iCloud Identity if needed
42 // Gen sign if private key changed
44 bool SOSAccountGenerationSignatureUpdate(SOSAccount* account, CFErrorRef *error) {
46 SecKeyRef priv_key = SOSAccountGetPrivateCredential(account, error);
47 require_quiet(priv_key, bail);
49 [account.trust generationSignatureUpdateWith:account key:priv_key];
56 /* this one is meant to be local - not published over KVS. */
57 static bool SOSAccountPeerSignatureUpdate(SOSAccount* account, SecKeyRef privKey, CFErrorRef *error) {
58 SOSFullPeerInfoRef identity = NULL;
59 SOSAccountTrustClassic *trust = account.trust;
60 identity = trust.fullPeerInfo;
62 return identity && SOSFullPeerInfoUpgradeSignatures(identity, privKey, error);
66 void SOSAccountPurgePrivateCredential(SOSAccount* account)
68 secnotice("circleOps", "Purging private account credential");
70 if(account.accountPrivateKey)
72 account.accountPrivateKey = NULL;
74 if(account._password_tmp)
76 account._password_tmp = NULL;
78 if (account.user_private_timer) {
79 dispatch_source_cancel(account.user_private_timer);
80 account.user_private_timer = NULL;
81 xpc_transaction_end();
83 if (account.lock_notification_token != NOTIFY_TOKEN_INVALID) {
84 notify_cancel(account.lock_notification_token);
85 account.lock_notification_token = NOTIFY_TOKEN_INVALID;
90 static void SOSAccountSetTrustedUserPublicKey(SOSAccount* account, bool public_was_trusted, SecKeyRef privKey)
93 SecKeyRef publicKey = SecKeyCreatePublicFromPrivate(privKey);
95 if (account.accountKey && account.accountKeyIsTrusted && CFEqual(publicKey, account.accountKey)) {
96 CFReleaseNull(publicKey);
100 if(public_was_trusted && account.accountKey) {
101 account.previousAccountKey = account.accountKey;
104 account.accountKey = publicKey;
105 account.accountKeyIsTrusted = true;
107 if(!account.previousAccountKey) {
108 account.previousAccountKey = account.accountKey;
111 CFReleaseNull(publicKey);
113 secnotice("circleOps", "trusting new public key: %@", account.accountKey);
114 notify_post(kPublicKeyAvailable);
117 void SOSAccountSetUnTrustedUserPublicKey(SOSAccount* account, SecKeyRef publicKey) {
118 if(account.accountKeyIsTrusted && account.accountKey) {
119 secnotice("circleOps", "Moving : %@ to previousAccountKey", account.accountKey);
120 account.previousAccountKey = account.accountKey;
123 account.accountKey = publicKey;
124 account.accountKeyIsTrusted = false;
126 if(!account.previousAccountKey) {
127 account.previousAccountKey = account.accountKey;
130 secnotice("circleOps", "not trusting new public key: %@", account.accountKey);
134 static void SOSAccountSetPrivateCredential(SOSAccount* account, SecKeyRef private, CFDataRef password) {
136 return SOSAccountPurgePrivateCredential(account);
138 secnotice("circleOps", "setting new private credential");
140 account.accountPrivateKey = private;
143 account._password_tmp = [[NSData alloc] initWithData:(__bridge NSData * _Nonnull)(password)];
145 account._password_tmp = NULL;
148 bool resume_timer = false;
149 if (!account.user_private_timer) {
150 xpc_transaction_begin();
152 account.user_private_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, account.queue);
153 dispatch_source_set_event_handler(account.user_private_timer, ^{
154 secnotice("keygen", "Timing out, purging private account credential");
155 SOSAccountPurgePrivateCredential(account);
157 int lockNotification;
159 notify_register_dispatch(kUserKeybagStateChangeNotification, &lockNotification, account.queue, ^(int token) {
161 CFErrorRef lockCheckError = NULL;
163 if (!SecAKSGetIsLocked(&locked, &lockCheckError)) {
164 secerror("Checking for locked after change failed: %@", lockCheckError);
168 SOSAccountPurgePrivateCredential(account);
171 [account setLock_notification_token:lockNotification];
174 SOSAccountRestartPrivateCredentialTimer(account);
177 dispatch_resume(account.user_private_timer);
180 void SOSAccountRestartPrivateCredentialTimer(SOSAccount* account)
182 if (account.user_private_timer) {
183 // (Re)set the timer's fire time to now + 10 minutes with a 5 second fuzz factor.
184 dispatch_time_t purgeTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * 60 * NSEC_PER_SEC));
185 dispatch_source_set_timer(account.user_private_timer, purgeTime, DISPATCH_TIME_FOREVER, (int64_t)(5 * NSEC_PER_SEC));
189 SecKeyRef SOSAccountGetPrivateCredential(SOSAccount* account, CFErrorRef* error)
191 if (account.accountPrivateKey == NULL) {
192 SOSCreateError(kSOSErrorPrivateKeyAbsent, CFSTR("Private Key not available - failed to prompt user recently"), NULL, error);
194 return account.accountPrivateKey;
197 CFDataRef SOSAccountGetCachedPassword(SOSAccount* account, CFErrorRef* error)
199 if (account._password_tmp == NULL) {
200 secnotice("circleOps", "Password cache expired");
202 return (__bridge CFDataRef)(account._password_tmp);
204 static NSString *SOSUserCredentialAccount = @"SOSUserCredential";
205 static NSString *SOSUserCredentialAccessGroup = @"com.apple.security.sos-usercredential";
207 void SOSAccountStashAccountKey(SOSAccount* account)
210 SecKeyRef user_private = account.accountPrivateKey;
211 NSData *data = CFBridgingRelease(SecKeyCopyExternalRepresentation(user_private, NULL));
216 NSDictionary *attributes = @{
217 (__bridge id)kSecClass : (__bridge id)kSecClassInternetPassword,
218 (__bridge id)kSecAttrAccount : SOSUserCredentialAccount,
219 (__bridge id)kSecAttrIsInvisible : @YES,
220 (__bridge id)kSecAttrAccessible : (__bridge id)kSecAttrAccessibleWhenUnlocked,
221 (__bridge id)kSecAttrAccessGroup : SOSUserCredentialAccessGroup,
222 (__bridge id)kSecAttrSysBound : @(kSecSecAttrSysBoundPreserveDuringRestore),
223 (__bridge id)kSecValueData : data,
226 status = SecItemAdd((__bridge CFDictionaryRef)attributes, NULL);
228 if (status == errSecDuplicateItem) {
230 (__bridge id)kSecClass : (__bridge id)kSecClassInternetPassword,
231 (__bridge id)kSecAttrAccount : SOSUserCredentialAccount,
232 (__bridge id)kSecAttrAccessGroup : SOSUserCredentialAccessGroup,
233 (__bridge id)kSecUseDataProtectionKeychain : @YES,
236 status = SecItemUpdate((__bridge CFDictionaryRef)attributes, (__bridge CFDictionaryRef)@{
237 (__bridge id)kSecValueData : data,
238 (__bridge id)kSecAttrSysBound : @(kSecSecAttrSysBoundPreserveDuringRestore)
242 secnotice("circleOps", "Failed to update user private key to keychain: %d", (int)status);
244 } else if (status != 0) {
245 secnotice("circleOps", "Failed to add user private key to keychain: %d", (int)status);
249 secnotice("circleOps", "Stored user private key stashed local keychain");
255 SecKeyRef SOSAccountCopyStashedUserPrivateKey(SOSAccount* account, CFErrorRef *error)
257 SecKeyRef key = NULL;
258 CFDataRef data = NULL;
261 NSDictionary *attributes = @{
262 (__bridge id)kSecClass : (__bridge id)kSecClassInternetPassword,
263 (__bridge id)kSecAttrAccount : SOSUserCredentialAccount,
264 (__bridge id)kSecAttrAccessGroup : SOSUserCredentialAccessGroup,
265 (__bridge id)kSecReturnData : @YES,
266 (__bridge id)kSecMatchLimit : (__bridge id)kSecMatchLimitOne,
269 status = SecItemCopyMatching((__bridge CFDictionaryRef)attributes, (CFTypeRef *)&data);
271 SecError(status, error, CFSTR("Failed fetching account credential: %d"), (int)status);
275 NSDictionary *keyAttributes = @{
276 (__bridge id)kSecAttrKeyClass : (__bridge id)kSecAttrKeyClassPrivate,
277 (__bridge id)kSecAttrKeyType : (__bridge id)kSecAttrKeyTypeEC,
281 key = SecKeyCreateWithData(data, (__bridge CFDictionaryRef)keyAttributes, error);
287 SecKeyRef SOSAccountGetTrustedPublicCredential(SOSAccount* account, CFErrorRef* error)
289 if (account.accountKey == NULL || account.accountKeyIsTrusted == false) {
290 SOSCreateError(kSOSErrorPublicKeyAbsent, CFSTR("Public Key isn't available. The iCloud Password must be provided to the syncing subsystem to repair this."), NULL, error);
293 return account.accountKey;
296 bool SOSAccountHasPublicKey(SOSAccount* account, CFErrorRef* error)
298 return SOSAccountGetTrustedPublicCredential(account, error);
301 static void sosAccountSetTrustedCredentials(SOSAccount* account, CFDataRef user_password, SecKeyRef user_private, bool public_was_trusted) {
302 if(!SOSAccountFullPeerInfoVerify(account, user_private, NULL)){
303 (void) SOSAccountPeerSignatureUpdate(account, user_private, NULL);
305 SOSAccountSetTrustedUserPublicKey(account, public_was_trusted, user_private);
306 SOSAccountSetPrivateCredential(account, user_private, user_password);
307 SOSAccountCheckForAlwaysOnViews(account);
310 static SecKeyRef sosAccountCreateKeyIfPasswordIsCorrect(SOSAccount* account, CFDataRef user_password, CFErrorRef *error) {
311 SecKeyRef user_private = NULL;
312 require_quiet(account.accountKey && account.accountKeyDerivationParamters, errOut);
313 user_private = SOSUserKeygen(user_password, (__bridge CFDataRef)(account.accountKeyDerivationParamters), error);
314 require_quiet(user_private, errOut);
316 require_action_quiet(SOSAccountValidateAccountCredential(account, user_private, error), errOut, CFReleaseNull(user_private));
321 static bool sosAccountValidatePasswordOrFail(SOSAccount* account, CFDataRef user_password, CFErrorRef *error) {
322 SecKeyRef privKey = sosAccountCreateKeyIfPasswordIsCorrect(account, user_password, error);
324 if(account.accountKeyDerivationParamters) debugDumpUserParameters(CFSTR("sosAccountValidatePasswordOrFail"), (__bridge CFDataRef)(account.accountKeyDerivationParamters));
325 SOSCreateError(kSOSErrorWrongPassword, CFSTR("Could not create correct key with password."), NULL, error);
328 sosAccountSetTrustedCredentials(account, user_password, privKey, account.accountKeyIsTrusted);
329 CFReleaseNull(privKey);
333 void SOSAccountSetParameters(SOSAccount* account, CFDataRef parameters) {
334 account.accountKeyDerivationParamters = (__bridge NSData *) parameters;
337 bool SOSAccountValidateAccountCredential(SOSAccount* account, SecKeyRef accountPrivateKey, CFErrorRef *error)
340 SecKeyRef publicCandidate = SecKeyCreatePublicFromPrivate(accountPrivateKey);
342 if(CFEqualSafe(account.accountKey, publicCandidate)) {
345 CFErrorRef localError = NULL;
346 CFStringRef accountHpub = SOSCopyIDOfKey(account.accountKey, NULL);
347 CFStringRef candidateHpub = SOSCopyIDOfKey(publicCandidate, NULL);
348 SOSCreateErrorWithFormat(kSOSErrorWrongPassword, NULL, &localError, NULL, CFSTR("Password generated pubkey doesn't match - candidate: %@ known: %@"), candidateHpub, accountHpub);
349 secnotice("circleop", "%@", localError);
354 CFReleaseNull(localError);
356 CFReleaseNull(accountHpub);
357 CFReleaseNull(candidateHpub);
359 CFReleaseNull(publicCandidate);
363 bool SOSAccountAssertStashedAccountCredential(SOSAccount* account, CFErrorRef *error)
365 SecKeyRef accountPrivateKey = NULL, publicCandidate = NULL;
368 require_action(account.accountKey, fail, SOSCreateError(kSOSErrorWrongPassword, CFSTR("account public key missing, can't check stashed copy"), NULL, error));
369 require_action(account.accountKeyIsTrusted, fail, SOSCreateError(kSOSErrorWrongPassword, CFSTR("public key no not valid, can't check stashed copy"), NULL, error));
371 accountPrivateKey = SOSAccountCopyStashedUserPrivateKey(account, error);
372 require_action_quiet(accountPrivateKey, fail, secnotice("circleOps", "Looked for a stashed private key, didn't find one"));
374 require(SOSAccountValidateAccountCredential(account, accountPrivateKey, error), fail);
376 sosAccountSetTrustedCredentials(account, NULL, accountPrivateKey, true);
380 CFReleaseSafe(publicCandidate);
381 CFReleaseSafe(accountPrivateKey);
388 bool SOSAccountAssertUserCredentials(SOSAccount* account, CFStringRef user_account, CFDataRef user_password, CFErrorRef *error)
390 bool public_was_trusted = account.accountKeyIsTrusted;
391 account.accountKeyIsTrusted = false;
392 SecKeyRef user_private = NULL;
393 CFDataRef parameters = NULL;
395 // if this succeeds, skip to the end. Success will update account.accountKeyIsTrusted by side-effect.
396 require_quiet(!sosAccountValidatePasswordOrFail(account, user_password, error), recordCred);
398 // We may or may not have parameters here.
399 // In any case we tried using them and they didn't match
400 // So forget all that and start again, assume we're the first to push anything useful.
402 if (CFDataGetLength(user_password) > 20) {
403 secwarning("Long password (>20 byte utf8) being used to derive account key – this may be a PET by mistake!!");
406 parameters = SOSUserKeyCreateGenerateParameters(error);
407 require_quiet(user_private = SOSUserKeygen(user_password, parameters, error), errOut);
408 SOSAccountSetParameters(account, parameters);
409 sosAccountSetTrustedCredentials(account, user_password, user_private, public_was_trusted);
411 CFErrorRef publishError = NULL;
412 if (!SOSAccountPublishCloudParameters(account, &publishError)) {
413 secerror("Failed to publish new cloud parameters: %@", publishError);
416 CFReleaseNull(publishError);
418 SOSAccountStashAccountKey(account);
419 SOSAccountSetValue(account, kSOSAccountName, user_account, NULL);
421 CFReleaseNull(parameters);
422 CFReleaseNull(user_private);
423 secnotice("circleop", "Setting account.key_interests_need_updating to true in SOSAccountAssertUserCredentials");
424 account.key_interests_need_updating = true;
425 return account.accountKeyIsTrusted;
429 bool SOSAccountTryUserCredentials(SOSAccount* account, CFStringRef user_account, CFDataRef user_password, CFErrorRef *error) {
430 bool success = sosAccountValidatePasswordOrFail(account, user_password, error);
432 SOSAccountStashAccountKey(account);
433 SOSAccountSetValue(account, kSOSAccountName, user_account, NULL);
435 secnotice("circleop", "Setting account.key_interests_need_updating to true in SOSAccountTryUserCredentials");
436 account.key_interests_need_updating = true;
440 bool SOSAccountTryUserPrivateKey(SOSAccount* account, SecKeyRef user_private, CFErrorRef *error) {
441 bool retval = SOSAccountValidateAccountCredential(account, user_private, error);
443 secnotice("circleOps", "Failed to accept provided user_private as credential");
446 sosAccountSetTrustedCredentials(account, NULL, user_private, account.accountKeyIsTrusted);
447 SOSAccountStashAccountKey(account);
448 secnotice("circleop", "Setting account.key_interests_need_updating to true in SOSAccountTryUserPrivateKey");
449 account.key_interests_need_updating = true;
450 secnotice("circleOps", "Accepted provided user_private as credential");
454 bool SOSAccountRetryUserCredentials(SOSAccount* account) {
455 CFDataRef cachedPassword = SOSAccountGetCachedPassword(account, NULL);
456 if (cachedPassword == NULL)
459 * SOSAccountTryUserCredentials reset the cached password internally,
460 * so we must have a retain of the password over SOSAccountTryUserCredentials().
462 CFRetain(cachedPassword);
463 bool res = SOSAccountTryUserCredentials(account, NULL, cachedPassword, NULL);
464 CFRelease(cachedPassword);