2 * Copyright (c) 2000-2004,2011-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@
24 #include <Security/SecKeychain.h>
25 #include <Security/SecKeychainPriv.h>
26 #include <security_keychain/KCCursor.h>
27 #include <security_cdsa_utilities/cssmdata.h>
28 #include <security_cdsa_client/wrapkey.h>
29 #include <security_keychain/KCExceptions.h>
30 #include <securityd_client/ssblob.h>
31 #include <Security/SecAccess.h>
32 #include <Security/SecTrustedApplicationPriv.h>
33 #include "SecBridge.h"
34 #include "CCallbackMgr.h"
35 #include <security_cdsa_utilities/Schema.h>
36 #include <security_cdsa_client/mdsclient.h>
38 #include <os/activity.h>
39 #include <Security/AuthorizationTagsPriv.h>
40 #include <Security/Authorization.h>
41 #include "TokenLogin.h"
44 SecKeychainMDSInstall()
47 os_activity_t activity
= os_activity_create("SecKeychainMDSInstall", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
48 os_activity_scope(activity
);
51 Security::MDSClient::Directory d
;
58 SecKeychainGetTypeID(void)
62 return gTypes().KeychainImpl
.typeID
;
64 END_SECAPI1(_kCFRuntimeNotATypeID
)
69 SecKeychainGetVersion(UInt32
*returnVers
)
74 *returnVers
= 0x02028000;
80 SecKeychainOpen(const char *pathName
, SecKeychainRef
*keychainRef
)
83 os_activity_t activity
= os_activity_create("SecKeychainOpen", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
84 os_activity_scope(activity
);
87 RequiredParam(keychainRef
)=globals().storageManager
.make(pathName
, false)->handle();
94 SecKeychainOpenWithGuid(const CSSM_GUID
*guid
, uint32 subserviceId
, uint32 subserviceType
, const char* dbName
,
95 const CSSM_NET_ADDRESS
*dbLocation
, SecKeychainRef
*keychain
)
98 os_activity_t activity
= os_activity_create("SecKeychainOpenWithGuid", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
99 os_activity_scope(activity
);
100 os_release(activity
);
102 // range check parameters
103 RequiredParam (guid
);
104 RequiredParam (dbName
);
106 // create a DLDbIdentifier that describes what should be opened
107 const CSSM_VERSION
*version
= NULL
;
108 const CssmSubserviceUid
ssuid(*guid
, version
, subserviceId
, subserviceType
);
109 DLDbIdentifier
dLDbIdentifier(ssuid
, dbName
, dbLocation
);
111 // make a keychain from the supplied info
112 RequiredParam(keychain
) = globals().storageManager
.makeKeychain(dLDbIdentifier
, false, false)->handle ();
119 SecKeychainCreate(const char *pathName
, UInt32 passwordLength
, const void *password
,
120 Boolean promptUser
, SecAccessRef initialAccess
, SecKeychainRef
*keychainRef
)
123 os_activity_t activity
= os_activity_create("SecKeychainCreate", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
124 os_activity_scope(activity
);
125 os_release(activity
);
127 KCThrowParamErrIf_(!pathName
);
128 Keychain keychain
= globals().storageManager
.make(pathName
, true, true);
130 // @@@ the call to StorageManager::make above leaves keychain the the cache.
131 // If the create below fails we should probably remove it.
136 KCThrowParamErrIf_(!password
);
137 keychain
->create(passwordLength
, password
);
140 RequiredParam(keychainRef
)=keychain
->handle();
147 SecKeychainDelete(SecKeychainRef keychainOrArray
)
150 os_activity_t activity
= os_activity_create("SecKeychainDelete", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
151 os_activity_scope(activity
);
152 os_release(activity
);
154 KCThrowIf_(!keychainOrArray
, errSecInvalidKeychain
);
155 StorageManager::KeychainList keychains
;
156 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
158 globals().storageManager
.remove(keychains
, true);
165 SecKeychainSetSettings(SecKeychainRef keychainRef
, const SecKeychainSettings
*newSettings
)
168 os_activity_t activity
= os_activity_create("SecKeychainSetSettings", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
169 os_activity_scope(activity
);
170 os_release(activity
);
172 Keychain keychain
= Keychain::optional(keychainRef
);
173 if (newSettings
->version
==SEC_KEYCHAIN_SETTINGS_VERS1
)
175 UInt32 lockInterval
=newSettings
->lockInterval
;
176 bool lockOnSleep
=newSettings
->lockOnSleep
;
177 keychain
->setSettings(lockInterval
, lockOnSleep
);
185 SecKeychainCopySettings(SecKeychainRef keychainRef
, SecKeychainSettings
*outSettings
)
188 os_activity_t activity
= os_activity_create("SecKeychainCopySettings", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
189 os_activity_scope(activity
);
190 os_release(activity
);
192 Keychain keychain
= Keychain::optional(keychainRef
);
193 if (outSettings
->version
==SEC_KEYCHAIN_SETTINGS_VERS1
)
198 keychain
->getSettings(lockInterval
, lockOnSleep
);
199 outSettings
->lockInterval
=lockInterval
;
200 outSettings
->lockOnSleep
=lockOnSleep
;
208 SecKeychainUnlock(SecKeychainRef keychainRef
, UInt32 passwordLength
, const void *password
, Boolean usePassword
)
211 os_activity_t activity
= os_activity_create("SecKeychainUnlock", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
212 os_activity_scope(activity
);
213 os_release(activity
);
215 Keychain keychain
= Keychain::optional(keychainRef
);
218 keychain
->unlock(CssmData(const_cast<void *>(password
), passwordLength
));
227 SecKeychainLock(SecKeychainRef keychainRef
)
230 os_activity_t activity
= os_activity_create("SecKeychainLock", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
231 os_activity_scope(activity
);
232 os_release(activity
);
234 Keychain keychain
= Keychain::optional(keychainRef
);
242 SecKeychainLockAll(void)
245 os_activity_t activity
= os_activity_create("SecKeychainLockAll", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
246 os_activity_scope(activity
);
247 os_release(activity
);
249 globals().storageManager
.lockAll();
255 OSStatus
SecKeychainResetLogin(UInt32 passwordLength
, const void* password
, Boolean resetSearchList
)
258 os_activity_t activity
= os_activity_create("SecKeychainResetLogin", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
259 os_activity_scope(activity
);
260 os_release(activity
);
262 // Get the current user (using fallback method if necessary)
264 char* uName
= getenv("USER");
265 string userName
= uName
? uName
: "";
266 if ( userName
.length() == 0 )
268 uid_t uid
= geteuid();
269 if (!uid
) uid
= getuid();
270 struct passwd
*pw
= getpwuid(uid
); // fallback case...
272 userName
= pw
->pw_name
;
275 if ( userName
.length() == 0 ) // did we ultimately get one?
276 MacOSError::throwMe(errAuthorizationInternal
);
278 SecurityServer::ClientSession().resetKeyStorePassphrase(password
? CssmData(const_cast<void *>(password
), passwordLength
) : CssmData());
282 // Clear the plist and move aside (rename) the existing login.keychain
283 globals().storageManager
.resetKeychain(resetSearchList
);
285 // Create the login keychain without UI
286 globals().storageManager
.login((UInt32
)userName
.length(), userName
.c_str(), passwordLength
, password
, true);
288 // Set it as the default
289 Keychain keychain
= globals().storageManager
.loginKeychain();
290 globals().storageManager
.defaultKeychain(keychain
);
294 // Create the login keychain, prompting for password
295 // (implicitly calls resetKeychain, login, and defaultKeychain)
296 globals().storageManager
.makeLoginAuthUI(NULL
, true);
299 // Post a "list changed" event after a reset, so apps can refresh their list.
300 // Make sure we are not holding mLock when we post this event.
301 KCEventNotifier::PostKeychainEvent(kSecKeychainListChangedEvent
);
307 SecKeychainCopyDefault(SecKeychainRef
*keychainRef
)
311 RequiredParam(keychainRef
)=globals().storageManager
.defaultKeychain()->handle();
318 SecKeychainSetDefault(SecKeychainRef keychainRef
)
321 os_activity_t activity
= os_activity_create("SecKeychainSetDefault", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
322 os_activity_scope(activity
);
323 os_release(activity
);
325 globals().storageManager
.defaultKeychain(Keychain::optional(keychainRef
));
330 OSStatus
SecKeychainCopySearchList(CFArrayRef
*searchList
)
333 os_activity_t activity
= os_activity_create("SecKeychainCopySearchList", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
334 os_activity_scope(activity
);
335 os_release(activity
);
337 RequiredParam(searchList
);
338 StorageManager
&smr
= globals().storageManager
;
339 StorageManager::KeychainList keychainList
;
340 smr
.getSearchList(keychainList
);
341 *searchList
= smr
.convertFromKeychainList(keychainList
);
346 OSStatus
SecKeychainSetSearchList(CFArrayRef searchList
)
349 os_activity_t activity
= os_activity_create("SecKeychainSetSearchList", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
350 os_activity_scope(activity
);
351 os_release(activity
);
353 RequiredParam(searchList
);
354 StorageManager
&smr
= globals().storageManager
;
355 StorageManager::KeychainList keychainList
;
356 smr
.convertToKeychainList(searchList
, keychainList
);
357 smr
.setSearchList(keychainList
);
362 OSStatus
SecKeychainCopyDomainDefault(SecPreferencesDomain domain
, SecKeychainRef
*keychainRef
)
365 os_activity_t activity
= os_activity_create("SecKeychainCopyDomainDefault", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
366 os_activity_scope(activity
);
367 os_release(activity
);
369 RequiredParam(keychainRef
)=globals().storageManager
.defaultKeychain(domain
)->handle();
374 OSStatus
SecKeychainSetDomainDefault(SecPreferencesDomain domain
, SecKeychainRef keychainRef
)
377 os_activity_t activity
= os_activity_create("SecKeychainSetDomainDefault", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
378 os_activity_scope(activity
);
379 os_release(activity
);
381 globals().storageManager
.defaultKeychain(domain
, Keychain::optional(keychainRef
));
386 OSStatus
SecKeychainCopyDomainSearchList(SecPreferencesDomain domain
, CFArrayRef
*searchList
)
390 RequiredParam(searchList
);
391 StorageManager
&smr
= globals().storageManager
;
392 StorageManager::KeychainList keychainList
;
393 smr
.getSearchList(domain
, keychainList
);
394 *searchList
= smr
.convertFromKeychainList(keychainList
);
399 OSStatus
SecKeychainSetDomainSearchList(SecPreferencesDomain domain
, CFArrayRef searchList
)
402 os_activity_t activity
= os_activity_create("SecKeychainSetDomainSearchList", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
403 os_activity_scope(activity
);
404 os_release(activity
);
406 RequiredParam(searchList
);
407 StorageManager
&smr
= globals().storageManager
;
408 StorageManager::KeychainList keychainList
;
409 smr
.convertToKeychainList(searchList
, keychainList
);
410 smr
.setSearchList(domain
, keychainList
);
415 OSStatus
SecKeychainSetPreferenceDomain(SecPreferencesDomain domain
)
418 os_activity_t activity
= os_activity_create("SecKeychainSetPreferenceDomain", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
419 os_activity_scope(activity
);
420 os_release(activity
);
422 globals().storageManager
.domain(domain
);
427 OSStatus
SecKeychainGetPreferenceDomain(SecPreferencesDomain
*domain
)
430 os_activity_t activity
= os_activity_create("SecKeychainGetPreferenceDomain", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
431 os_activity_scope(activity
);
432 os_release(activity
);
434 *domain
= globals().storageManager
.domain();
441 SecKeychainGetStatus(SecKeychainRef keychainRef
, SecKeychainStatus
*keychainStatus
)
445 RequiredParam(keychainStatus
) = (SecKeychainStatus
)Keychain::optional(keychainRef
)->status();
452 SecKeychainGetPath(SecKeychainRef keychainRef
, UInt32
*ioPathLength
, char *pathName
)
456 RequiredParam(pathName
);
457 RequiredParam(ioPathLength
);
459 const char *name
= Keychain::optional(keychainRef
)->name();
460 UInt32 nameLen
= (UInt32
)strlen(name
);
461 UInt32 callersLen
= *ioPathLength
;
462 *ioPathLength
= nameLen
;
463 if (nameLen
+1 > callersLen
) // if the client's buffer is too small (including null-termination), throw
464 return errSecBufferTooSmall
;
465 strncpy(pathName
, name
, nameLen
);
466 pathName
[nameLen
] = 0;
467 *ioPathLength
= nameLen
; // set the length.
473 SecKeychainGetKeychainVersion(SecKeychainRef keychainRef
, UInt32
* version
)
477 RequiredParam(version
);
479 *version
= Keychain::optional(keychainRef
)->database()->dbBlobVersion();
485 SecKeychainAttemptMigrationWithMasterKey(SecKeychainRef keychain
, UInt32 version
, const char* masterKeyFilename
)
488 os_activity_t activity
= os_activity_create("SecKeychainAttemptMigrationWithMasterKey", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
489 os_activity_scope(activity
);
490 os_release(activity
);
492 RequiredParam(masterKeyFilename
);
493 Keychain kc
= Keychain::optional(keychain
);
495 SecurityServer::SystemKeychainKey
keychainKey(masterKeyFilename
);
496 if(keychainKey
.valid()) {
497 // We've managed to read the key; now, create credentials using it
498 string path
= kc
->name();
500 CssmClient::Key
keychainMasterKey(kc
->csp(), keychainKey
.key(), true);
501 CssmClient::AclFactory::MasterKeyUnlockCredentials
creds(keychainMasterKey
, Allocator::standard(Allocator::sensitive
));
503 // Attempt the migrate, using our master key as the ACL override
504 bool result
= kc
->keychainMigration(path
, kc
->database()->dbBlobVersion(), path
, version
, creds
.getAccessCredentials());
508 return (kc
->database()->dbBlobVersion() == version
? errSecSuccess
: errSecBadReq
);
519 SecKeychainListGetCount(void)
523 return globals().storageManager
.size();
531 SecKeychainListCopyKeychainAtIndex(UInt16 index
, SecKeychainRef
*keychainRef
)
535 KeychainCore::StorageManager
&smgr
=KeychainCore::globals().storageManager
;
536 RequiredParam(keychainRef
)=smgr
[index
]->handle();
544 SecKeychainListRemoveKeychain(SecKeychainRef
*keychainRef
)
548 Required(keychainRef
);
549 Keychain keychain
= Keychain::optional(*keychainRef
);
550 StorageManager::KeychainList keychainList
;
551 keychainList
.push_back(keychain
);
552 globals().storageManager
.remove(keychainList
);
560 SecKeychainAttributeInfoForItemID(SecKeychainRef keychainRef
, UInt32 itemID
, SecKeychainAttributeInfo
**info
)
564 Keychain keychain
= Keychain::optional(keychainRef
);
565 keychain
->getAttributeInfoForItemID(itemID
, info
);
572 SecKeychainFreeAttributeInfo(SecKeychainAttributeInfo
*info
)
576 KeychainImpl::freeAttributeInfo(info
);
583 SecKeychainAddCallback(SecKeychainCallback callbackFunction
, SecKeychainEventMask eventMask
, void* userContext
)
586 os_activity_t activity
= os_activity_create("SecKeychainAddCallback", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
587 os_activity_scope(activity
);
588 os_release(activity
);
590 RequiredParam(callbackFunction
);
591 CCallbackMgr::AddCallback(callbackFunction
,eventMask
,userContext
);
598 SecKeychainRemoveCallback(SecKeychainCallback callbackFunction
)
601 os_activity_t activity
= os_activity_create("SecKeychainRemoveCallback", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
602 os_activity_scope(activity
);
603 os_release(activity
);
605 RequiredParam(callbackFunction
);
606 CCallbackMgr::RemoveCallback(callbackFunction
);
612 SecKeychainAddInternetPassword(SecKeychainRef keychainRef
, UInt32 serverNameLength
, const char *serverName
, UInt32 securityDomainLength
, const char *securityDomain
, UInt32 accountNameLength
, const char *accountName
, UInt32 pathLength
, const char *path
, UInt16 port
, SecProtocolType protocol
, SecAuthenticationType authenticationType
, UInt32 passwordLength
, const void *passwordData
, SecKeychainItemRef
*itemRef
)
615 os_activity_t activity
= os_activity_create("SecKeychainAddInternetPassword", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
616 os_activity_scope(activity
);
617 os_release(activity
);
619 KCThrowParamErrIf_(passwordLength
!=0 && passwordData
==NULL
);
620 // @@@ Get real itemClass
621 Item
item(kSecInternetPasswordItemClass
, 'aapl', passwordLength
, passwordData
, false);
623 if (serverName
&& serverNameLength
)
625 CssmData
server(const_cast<void *>(reinterpret_cast<const void *>(serverName
)), serverNameLength
);
626 item
->setAttribute(Schema::attributeInfo(kSecServerItemAttr
), server
);
627 // use server name as default label
628 item
->setAttribute(Schema::attributeInfo(kSecLabelItemAttr
), server
);
631 if (accountName
&& accountNameLength
)
633 CssmData
account(const_cast<void *>(reinterpret_cast<const void *>(accountName
)), accountNameLength
);
634 item
->setAttribute(Schema::attributeInfo(kSecAccountItemAttr
), account
);
637 if (securityDomain
&& securityDomainLength
)
638 item
->setAttribute(Schema::attributeInfo(kSecSecurityDomainItemAttr
),
639 CssmData(const_cast<void *>(reinterpret_cast<const void *>(securityDomain
)), securityDomainLength
));
641 item
->setAttribute(Schema::attributeInfo(kSecPortItemAttr
), UInt32(port
));
642 item
->setAttribute(Schema::attributeInfo(kSecProtocolItemAttr
), protocol
);
643 item
->setAttribute(Schema::attributeInfo(kSecAuthenticationTypeItemAttr
), authenticationType
);
645 if (path
&& pathLength
)
646 item
->setAttribute(Schema::attributeInfo(kSecPathItemAttr
),
647 CssmData(const_cast<void *>(reinterpret_cast<const void *>(path
)), pathLength
));
649 Keychain keychain
= nil
;
652 keychain
= Keychain::optional(keychainRef
);
653 if ( !keychain
->exists() )
655 MacOSError::throwMe(errSecNoSuchKeychain
); // Might be deleted or not available at this time.
660 keychain
= globals().storageManager
.defaultKeychainUI(item
);
666 *itemRef
= item
->handle();
673 SecKeychainFindInternetPassword(CFTypeRef keychainOrArray
, UInt32 serverNameLength
, const char *serverName
, UInt32 securityDomainLength
, const char *securityDomain
, UInt32 accountNameLength
, const char *accountName
, UInt32 pathLength
, const char *path
, UInt16 port
, SecProtocolType protocol
, SecAuthenticationType authenticationType
, UInt32
*passwordLength
, void **passwordData
, SecKeychainItemRef
*itemRef
)
677 os_activity_t activity
= os_activity_create("SecKeychainFindInternetPassword", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
678 os_activity_scope(activity
);
679 os_release(activity
);
681 StorageManager::KeychainList keychains
;
682 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
683 KCCursor
cursor(keychains
, kSecInternetPasswordItemClass
, NULL
);
685 if (serverName
&& serverNameLength
)
687 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecServerItemAttr
),
688 CssmData(const_cast<char *>(serverName
), serverNameLength
));
691 if (securityDomain
&& securityDomainLength
)
693 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecSecurityDomainItemAttr
),
694 CssmData (const_cast<char*>(securityDomain
), securityDomainLength
));
697 if (accountName
&& accountNameLength
)
699 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecAccountItemAttr
),
700 CssmData (const_cast<char*>(accountName
), accountNameLength
));
705 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecPortItemAttr
),
711 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecProtocolItemAttr
),
715 if (authenticationType
)
717 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecAuthenticationTypeItemAttr
),
721 if (path
&& pathLength
)
723 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecPathItemAttr
), path
);
727 if (!cursor
->next(item
))
728 return errSecItemNotFound
;
730 // Get its data (only if necessary)
731 if (passwordData
|| passwordLength
)
733 CssmDataContainer outData
;
734 item
->getData(outData
);
735 if (passwordLength
) {
736 *passwordLength
=(UInt32
)outData
.length();
740 *passwordData
=outData
.data();
746 *itemRef
=item
->handle();
753 SecKeychainAddGenericPassword(SecKeychainRef keychainRef
, UInt32 serviceNameLength
, const char *serviceName
, UInt32 accountNameLength
, const char *accountName
, UInt32 passwordLength
, const void *passwordData
, SecKeychainItemRef
*itemRef
)
756 os_activity_t activity
= os_activity_create("SecKeychainAddGenericPassword", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
757 os_activity_scope(activity
);
758 os_release(activity
);
760 KCThrowParamErrIf_(passwordLength
!=0 && passwordData
==NULL
);
761 // @@@ Get real itemClass
763 Item
item(kSecGenericPasswordItemClass
, 'aapl', passwordLength
, passwordData
, false);
765 if (serviceName
&& serviceNameLength
)
767 CssmData
service(const_cast<void *>(reinterpret_cast<const void *>(serviceName
)), serviceNameLength
);
768 item
->setAttribute(Schema::attributeInfo(kSecServiceItemAttr
), service
);
769 item
->setAttribute(Schema::attributeInfo(kSecLabelItemAttr
), service
);
772 if (accountName
&& accountNameLength
)
774 CssmData
account(const_cast<void *>(reinterpret_cast<const void *>(accountName
)), accountNameLength
);
775 item
->setAttribute(Schema::attributeInfo(kSecAccountItemAttr
), account
);
778 Keychain keychain
= nil
;
781 keychain
= Keychain::optional(keychainRef
);
782 if ( !keychain
->exists() )
784 MacOSError::throwMe(errSecNoSuchKeychain
); // Might be deleted or not available at this time.
789 keychain
= globals().storageManager
.defaultKeychainUI(item
);
794 *itemRef
= item
->handle();
801 SecKeychainFindGenericPassword(CFTypeRef keychainOrArray
, UInt32 serviceNameLength
, const char *serviceName
, UInt32 accountNameLength
, const char *accountName
, UInt32
*passwordLength
, void **passwordData
, SecKeychainItemRef
*itemRef
)
805 os_activity_t activity
= os_activity_create("SecKeychainFindGenericPassword", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
806 os_activity_scope(activity
);
807 os_release(activity
);
809 StorageManager::KeychainList keychains
;
810 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
811 KCCursor
cursor(keychains
, kSecGenericPasswordItemClass
, NULL
);
813 if (serviceName
&& serviceNameLength
)
815 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecServiceItemAttr
),
816 CssmData(const_cast<char *>(serviceName
), serviceNameLength
));
819 if (accountName
&& accountNameLength
)
821 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecAccountItemAttr
),
822 CssmData(const_cast<char *>(accountName
), accountNameLength
));
826 if (!cursor
->next(item
))
827 return errSecItemNotFound
;
829 // Get its data (only if necessary)
830 if (passwordData
|| passwordLength
)
832 CssmDataContainer outData
;
833 item
->getData(outData
);
834 if (passwordLength
) {
835 *passwordLength
=(UInt32
)outData
.length();
839 *passwordData
=outData
.data();
845 *itemRef
=item
->handle();
852 SecKeychainSetUserInteractionAllowed(Boolean state
)
856 globals().setUserInteractionAllowed(state
);
863 SecKeychainGetUserInteractionAllowed(Boolean
*state
)
867 Required(state
)=globals().getUserInteractionAllowed();
874 SecKeychainGetDLDBHandle(SecKeychainRef keychainRef
, CSSM_DL_DB_HANDLE
*dldbHandle
)
877 os_activity_t activity
= os_activity_create("SecKeychainGetDLDBHandle", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
878 os_activity_scope(activity
);
879 os_release(activity
);
881 RequiredParam(dldbHandle
);
883 Keychain keychain
= Keychain::optional(keychainRef
);
884 *dldbHandle
= keychain
->database()->handle();
889 static ModuleNexus
<Mutex
> gSecReturnedKeyCSPsMutex
;
890 static std::set
<CssmClient::CSP
> gSecReturnedKeychainCSPs
;
893 SecKeychainGetCSPHandle(SecKeychainRef keychainRef
, CSSM_CSP_HANDLE
*cspHandle
)
897 RequiredParam(cspHandle
);
899 Keychain keychain
= Keychain::optional(keychainRef
);
901 // Once we vend this handle, we can no longer delete this CSP object via RAII (and thus call CSSM_ModuleDetach on the CSP).
902 // Keep a global pointer to it to force the CSP to stay live forever.
903 CssmClient::CSP returnedKeychainCSP
= keychain
->csp();
905 StLock
<Mutex
> _(gSecReturnedKeyCSPsMutex());
906 gSecReturnedKeychainCSPs
.insert(returnedKeychainCSP
);
908 *cspHandle
= returnedKeychainCSP
->handle();
915 SecKeychainCopyAccess(SecKeychainRef keychainRef
, SecAccessRef
*accessRef
)
919 MacOSError::throwMe(errSecUnimplemented
);//%%%for now
926 SecKeychainSetAccess(SecKeychainRef keychainRef
, SecAccessRef accessRef
)
930 MacOSError::throwMe(errSecUnimplemented
);//%%%for now
936 #pragma mark ---- Private API ----
940 SecKeychainChangePassword(SecKeychainRef keychainRef
, UInt32 oldPasswordLength
, const void *oldPassword
, UInt32 newPasswordLength
, const void *newPassword
)
943 os_activity_t activity
= os_activity_create("SecKeychainChangePassword", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
944 os_activity_scope(activity
);
945 os_release(activity
);
947 Keychain keychain
= Keychain::optional(keychainRef
);
948 keychain
->changePassphrase (oldPasswordLength
, oldPassword
, newPasswordLength
, newPassword
);
955 SecKeychainCopyLogin(SecKeychainRef
*keychainRef
)
958 os_activity_t activity
= os_activity_create("SecKeychainCopyLogin", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
959 os_activity_scope(activity
);
960 os_release(activity
);
962 RequiredParam(keychainRef
)=globals().storageManager
.loginKeychain()->handle();
969 SecKeychainLogin(UInt32 nameLength
, const void* name
, UInt32 passwordLength
, const void* password
)
972 os_activity_t activity
= os_activity_create("SecKeychainLogin", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
973 os_activity_scope(activity
);
974 os_release(activity
);
979 globals().storageManager
.login(nameLength
, name
, passwordLength
, password
, false);
981 globals().storageManager
.stashLogin();
984 catch (CommonError
&e
)
986 secnotice("KCLogin", "SecKeychainLogin failed: %d, password was%s supplied", (int)e
.osStatus(), password
?"":" not");
987 if (e
.osStatus() == CSSMERR_DL_OPERATION_AUTH_DENIED
)
989 return errSecAuthFailed
;
998 __secapiresult
=errSecInternalComponent
;
1000 secnotice("KCLogin", "SecKeychainLogin result: %d, password was%s supplied", (int)__secapiresult
, password
?"":" not");
1005 OSStatus
SecKeychainStash()
1008 os_activity_t activity
= os_activity_create("SecKeychainStash", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
1009 os_activity_scope(activity
);
1010 os_release(activity
);
1014 globals().storageManager
.stashKeychain();
1016 catch (CommonError
&e
)
1018 if (e
.osStatus() == CSSMERR_DL_OPERATION_AUTH_DENIED
)
1020 return errSecAuthFailed
;
1024 return e
.osStatus();
1035 os_activity_t activity
= os_activity_create("SecKeychainLogout", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
1036 os_activity_scope(activity
);
1037 os_release(activity
);
1039 globals().storageManager
.logout();
1044 /* (non-exported C utility routine) 'Makes' a keychain based on a full path
1046 static Keychain
make(const char *name
)
1048 return globals().storageManager
.make(name
);
1051 /* 'Makes' a keychain based on a full path for legacy "KC" CoreServices APIs.
1052 Note this version doesn't take an accessRef or password.
1053 The "KC" create API takes a keychainRef...
1055 OSStatus
SecKeychainMakeFromFullPath(const char *fullPathName
, SecKeychainRef
*keychainRef
)
1058 RequiredParam(fullPathName
);
1059 RequiredParam(keychainRef
)=make(fullPathName
)->handle();
1064 /* Determines if the keychainRef is a valid keychain.
1066 OSStatus
SecKeychainIsValid(SecKeychainRef keychainRef
, Boolean
* isValid
)
1070 if (KeychainImpl::optional(keychainRef
)->dlDbIdentifier().ssuid().guid() == gGuidAppleCSPDL
)
1075 /* Removes a keychain from the keychain search list for legacy "KC" CoreServices APIs.
1077 OSStatus
SecKeychainRemoveFromSearchList(SecKeychainRef keychainRef
)
1080 os_activity_t activity
= os_activity_create("SecKeychainRemoveFromSearchList", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
1081 os_activity_scope(activity
);
1082 os_release(activity
);
1083 StorageManager::KeychainList singleton
;
1084 singleton
.push_back(KeychainImpl::required(keychainRef
));
1085 globals().storageManager
.remove(singleton
);
1089 /* Create a keychain based on a keychain Ref for legacy "KC" CoreServices APIs.
1091 OSStatus
SecKeychainCreateNew(SecKeychainRef keychainRef
, UInt32 passwordLength
, const char* inPassword
)
1094 os_activity_t activity
= os_activity_create("SecKeychainCreateNew", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
1095 os_activity_scope(activity
);
1096 os_release(activity
);
1097 RequiredParam(inPassword
);
1098 KeychainImpl::required(keychainRef
)->create(passwordLength
, inPassword
);
1102 /* Modify a keychain so that it can be synchronized.
1104 OSStatus
SecKeychainRecodeKeychain(SecKeychainRef keychainRef
, CFArrayRef dbBlobArray
, CFDataRef extraData
)
1107 os_activity_t activity
= os_activity_create("SecKeychainRecodeKeychain", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
1108 os_activity_scope(activity
);
1109 os_release(activity
);
1111 // do error checking for required parameters
1112 RequiredParam(dbBlobArray
);
1113 RequiredParam(extraData
);
1115 const CssmData
extraCssmData(const_cast<UInt8
*>(CFDataGetBytePtr(extraData
)),
1116 CFDataGetLength(extraData
));
1118 CFIndex dbBlobArrayCount
= CFArrayGetCount(dbBlobArray
);
1119 size_t space
= sizeof(uint8
) + (dbBlobArrayCount
* sizeof(SecurityServer::DbHandle
));
1120 void *dataPtr
= (void*)malloc(space
);
1122 return errSecAllocate
;
1124 // Get a DbHandle(IPCDbHandle) from securityd for each blob in the array that we'll authenticate with.
1126 uint8
* sizePtr
= (uint8
*)dataPtr
;
1127 *sizePtr
= dbBlobArrayCount
;
1128 SecurityServer::DbHandle
*currDbHandle
= (SecurityServer::DbHandle
*)(sizePtr
+1);
1130 SecurityServer::ClientSession
ss(Allocator::standard(), Allocator::standard());
1131 for (index
=0; index
< dbBlobArrayCount
; index
++)
1133 CFDataRef cfBlobData
= (CFDataRef
)CFArrayGetValueAtIndex(dbBlobArray
, index
);
1134 const CssmData
thisKCData(const_cast<UInt8
*>(CFDataGetBytePtr(cfBlobData
)), CFDataGetLength(cfBlobData
));
1136 // Since it's to a DbHandle that's not on our disk (it came from user's iDisk),
1137 // it's OK to use the mIdentifier and access credentials of the keychain we're recoding.
1139 Keychain kc
= KeychainImpl::required(keychainRef
);
1140 *currDbHandle
= ss
.decodeDb(kc
->dlDbIdentifier(), kc
->defaultCredentials(), thisKCData
); /* returns a DbHandle (IPCDbHandle) */
1145 Keychain keychain
= Keychain::optional(keychainRef
);
1146 const CssmData
data(const_cast<UInt8
*>((uint8
*)dataPtr
), space
);
1147 Boolean recodeFailed
= false;
1149 int errCode
=errSecSuccess
;
1153 keychain
->recode(data
, extraCssmData
);
1155 catch (MacOSError e
)
1157 errCode
= e
.osStatus();
1158 recodeFailed
= true;
1160 catch (UnixError ue
)
1162 errCode
= ue
.unixError();
1165 currDbHandle
= (SecurityServer::DbHandle
*)(sizePtr
+1);
1166 for (index
=0; index
< dbBlobArrayCount
; index
++)
1168 ss
.releaseDb(*currDbHandle
);
1182 OSStatus
SecKeychainCopySignature(SecKeychainRef keychainRef
, CFDataRef
*keychainSignature
)
1185 os_activity_t activity
= os_activity_create("SecKeychainCopySignature", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
1186 os_activity_scope(activity
);
1187 os_release(activity
);
1189 // do error checking for required parameters
1190 RequiredParam(keychainSignature
);
1192 // make a keychain object "wrapper" for this keychain ref
1193 Keychain keychain
= Keychain::optional(keychainRef
);
1194 CssmAutoData
data(keychain
->database()->allocator());
1195 keychain
->copyBlob(data
.get());
1197 // get the cssmDBBlob
1198 const SecurityServer::DbBlob
*cssmDBBlob
=
1199 data
.get().interpretedAs
<const SecurityServer::DbBlob
>();
1201 // convert from CDSA standards to CF standards
1202 *keychainSignature
= CFDataCreate(kCFAllocatorDefault
,
1203 cssmDBBlob
->randomSignature
.bytes
,
1204 sizeof(SecurityServer::DbBlob::Signature
));
1209 OSStatus
SecKeychainCopyBlob(SecKeychainRef keychainRef
, CFDataRef
*dbBlob
)
1212 os_activity_t activity
= os_activity_create("SecKeychainCopyBlob", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
1213 os_activity_scope(activity
);
1214 os_release(activity
);
1216 // do error checking for required parameters
1217 RequiredParam(dbBlob
);
1219 // make a keychain object "wrapper" for this keychain ref
1220 Keychain keychain
= Keychain::optional(keychainRef
);
1221 CssmAutoData
data(keychain
->database()->allocator());
1222 keychain
->copyBlob(data
.get());
1224 // convert from CDSA standards to CF standards
1225 *dbBlob
= CFDataCreate(kCFAllocatorDefault
, data
, data
.length());
1230 // make a new keychain with pre-existing secrets
1231 OSStatus
SecKeychainCreateWithBlob(const char* fullPathName
, CFDataRef dbBlob
, SecKeychainRef
*kcRef
)
1234 os_activity_t activity
= os_activity_create("SecKeychainCreateWithBlob", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
1235 os_activity_scope(activity
);
1236 os_release(activity
);
1238 KCThrowParamErrIf_(!fullPathName
);
1239 KCThrowParamErrIf_(!dbBlob
);
1241 Keychain keychain
= globals().storageManager
.make(fullPathName
);
1243 CssmData
blob(const_cast<unsigned char *>(CFDataGetBytePtr(dbBlob
)), CFDataGetLength(dbBlob
));
1245 // @@@ the call to StorageManager::make above leaves keychain the the cache.
1246 // If the create below fails we should probably remove it.
1247 keychain
->createWithBlob(blob
);
1249 RequiredParam(kcRef
)=keychain
->handle();
1256 // add a non-file based DB to the keychain list
1257 OSStatus
SecKeychainAddDBToKeychainList (SecPreferencesDomain domain
, const char* dbName
,
1258 const CSSM_GUID
*guid
, uint32 subServiceType
)
1261 os_activity_t activity
= os_activity_create("SecKeychainAddDBToKeychainList", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
1262 os_activity_scope(activity
);
1263 os_release(activity
);
1265 RequiredParam(dbName
);
1266 StorageManager
&smr
= globals().storageManager
;
1267 smr
.addToDomainList(domain
, dbName
, *guid
, subServiceType
);
1272 // determine if a non-file based DB is in the keychain list
1273 OSStatus
SecKeychainDBIsInKeychainList (SecPreferencesDomain domain
, const char* dbName
,
1274 const CSSM_GUID
*guid
, uint32 subServiceType
)
1277 RequiredParam(dbName
);
1278 StorageManager
&smr
= globals().storageManager
;
1279 smr
.isInDomainList(domain
, dbName
, *guid
, subServiceType
);
1283 // remove a non-file based DB from the keychain list
1284 OSStatus
SecKeychainRemoveDBFromKeychainList (SecPreferencesDomain domain
, const char* dbName
,
1285 const CSSM_GUID
*guid
, uint32 subServiceType
)
1288 os_activity_t activity
= os_activity_create("SecKeychainRemoveDBFromKeychainList", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
1289 os_activity_scope(activity
);
1290 os_release(activity
);
1291 RequiredParam(dbName
);
1292 StorageManager
&smr
= globals().storageManager
;
1293 smr
.removeFromDomainList(domain
, dbName
, *guid
, subServiceType
);
1298 // set server mode -- must be called before any other Sec* etc. call
1299 void SecKeychainSetServerMode()
1306 OSStatus
SecKeychainSetBatchMode (SecKeychainRef kcRef
, Boolean mode
, Boolean rollback
)
1309 os_activity_t activity
= os_activity_create("SecKeychainSetBatchMode", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
1310 os_activity_scope(activity
);
1311 os_release(activity
);
1312 RequiredParam(kcRef
);
1313 Keychain keychain
= Keychain::optional(kcRef
);
1314 keychain
->setBatchMode(mode
, rollback
);
1320 OSStatus
SecKeychainCleanupHandles()
1323 END_SECAPI
// which causes the handle cache cleanup routine to run
1326 OSStatus
SecKeychainVerifyKeyStorePassphrase(uint32_t retries
)
1329 os_activity_t activity
= os_activity_create("SecKeychainVerifyKeyStorePassphrase", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
1330 os_activity_scope(activity
);
1331 os_release(activity
);
1332 SecurityServer::ClientSession().verifyKeyStorePassphrase(retries
);
1336 OSStatus
SecKeychainChangeKeyStorePassphrase()
1339 os_activity_t activity
= os_activity_create("SecKeychainChangeKeyStorePassphrase", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
1340 os_activity_scope(activity
);
1341 os_release(activity
);
1342 SecurityServer::ClientSession().changeKeyStorePassphrase();
1346 static OSStatus
SecKeychainGetMasterKey(SecKeychainRef userKeychainRef
, CFDataRef
*masterKey
, CFStringRef password
)
1349 os_activity_t activity
= os_activity_create("SecKeychainGetMasterKey", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
1350 os_activity_scope(activity
);
1351 os_release(activity
);
1353 // make a keychain object "wrapper" for this keychain ref
1354 Keychain keychain
= Keychain::optional(userKeychainRef
);
1356 CssmClient::Db db
= keychain
->database();
1358 // create the keychain, using appropriate credentials
1359 Allocator
&alloc
= db
->allocator();
1360 AutoCredentials
cred(alloc
); // will leak, but we're quitting soon :-)
1362 char passphrase
[1024];
1363 CFStringGetCString(password
, passphrase
, sizeof(passphrase
), kCFStringEncodingUTF8
);
1365 // use this passphrase
1366 cred
+= TypedList(alloc
, CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK
,
1367 new(alloc
) ListElement(CSSM_SAMPLE_TYPE_PASSWORD
),
1368 new(alloc
) ListElement(StringData(passphrase
)));
1369 db
->authenticate(CSSM_DB_ACCESS_READ
, &cred
);
1371 CSSM_DL_DB_HANDLE dlDb
= db
->handle();
1372 CssmData dlDbData
= CssmData::wrap(dlDb
);
1374 KeySpec
spec(CSSM_KEYUSE_ANY
,
1375 CSSM_KEYATTR_RETURN_REF
| CSSM_KEYATTR_EXTRACTABLE
);
1377 DeriveKey
derive(keychain
->csp(), CSSM_ALGID_KEYCHAIN_KEY
, CSSM_ALGID_3DES_3KEY
, 3 * 64);
1378 derive(&dlDbData
, spec
, refKey
);
1380 // now extract the raw keybits
1382 WrapKey
wrap(keychain
->csp(), CSSM_ALGID_NONE
);
1383 wrap(refKey
, rawKey
);
1385 *masterKey
= CFDataCreate(kCFAllocatorDefault
, rawKey
.keyData(), rawKey
.length());
1390 static const char *kAutologinPWFilePath
= "/etc/kcpassword";
1391 static const uint32_t kObfuscatedPasswordSizeMultiple
= 12;
1392 static const uint32_t buffer_size
= 512;
1393 static const uint8_t kObfuscationKey
[] = {0x7d, 0x89, 0x52, 0x23, 0xd2, 0xbc, 0xdd, 0xea, 0xa3, 0xb9, 0x1f};
1395 static void obfuscate(void *buffer
, size_t bufferLength
)
1397 uint8_t *pBuf
= (uint8_t *) buffer
;
1398 const uint8_t *pKey
= kObfuscationKey
, *eKey
= pKey
+ sizeof( kObfuscationKey
);
1400 while (bufferLength
--) {
1401 *pBuf
= *pBuf
^ *pKey
;
1405 pKey
= kObfuscationKey
;
1409 static bool _SASetAutologinPW(CFStringRef inAutologinPW
)
1411 bool result
= false;
1414 // Delete the kcpassword file if it exists already
1415 if (stat(kAutologinPWFilePath
, &sb
) == 0)
1416 unlink( kAutologinPWFilePath
);
1418 // NIL incoming password ==> clear auto login password (above) without setting a new one. In other words: turn auto login off.
1419 if (inAutologinPW
!= NULL
) {
1420 char buffer
[buffer_size
];
1421 const char *pwAsUTF8String
= CFStringGetCStringPtr(inAutologinPW
, kCFStringEncodingUTF8
);
1422 if (pwAsUTF8String
== NULL
) {
1423 if (CFStringGetCString(inAutologinPW
, buffer
, buffer_size
, kCFStringEncodingUTF8
)) pwAsUTF8String
= buffer
;
1426 if (pwAsUTF8String
!= NULL
) {
1427 size_t pwLength
= strlen(pwAsUTF8String
) + 1;
1428 size_t obfuscatedPWLength
;
1429 char *obfuscatedPWBuffer
;
1431 // The size of the obfuscated password should be the smallest multiple of
1432 // kObfuscatedPasswordSizeMultiple greater than or equal to pwLength.
1433 obfuscatedPWLength
= (((pwLength
- 1) / kObfuscatedPasswordSizeMultiple
) + 1) * kObfuscatedPasswordSizeMultiple
;
1434 obfuscatedPWBuffer
= (char *) malloc(obfuscatedPWLength
);
1436 // Copy the password (including null terminator) to beginning of obfuscatedPWBuffer
1437 bcopy(pwAsUTF8String
, obfuscatedPWBuffer
, pwLength
);
1439 // Pad remainder of obfuscatedPWBuffer with random bytes
1442 char *endOfBuffer
= obfuscatedPWBuffer
+ obfuscatedPWLength
;
1444 for (p
= obfuscatedPWBuffer
+ pwLength
; p
< endOfBuffer
; ++p
)
1445 *p
= random() & 0x000000FF;
1448 obfuscate(obfuscatedPWBuffer
, obfuscatedPWLength
);
1450 int pwFile
= open(kAutologinPWFilePath
, O_CREAT
| O_WRONLY
| O_NOFOLLOW
, S_IRUSR
| S_IWUSR
);
1452 size_t wrote
= write(pwFile
, obfuscatedPWBuffer
, obfuscatedPWLength
);
1453 if (wrote
== obfuscatedPWLength
)
1458 chmod(kAutologinPWFilePath
, S_IRUSR
| S_IWUSR
);
1459 free(obfuscatedPWBuffer
);
1466 OSStatus
SecKeychainStoreUnlockKey(SecKeychainRef userKeychainRef
, SecKeychainRef systemKeychainRef
, CFStringRef username
, CFStringRef password
) {
1467 SecTrustedApplicationRef itemPath
;
1468 SecAccessRef ourAccessRef
= NULL
;
1470 OSStatus result
= errSecParam
;
1472 if (userKeychainRef
== NULL
) {
1473 // We don't have a specific user keychain, fall back
1474 if (_SASetAutologinPW(password
))
1475 result
= errSecSuccess
;
1480 CFDataRef masterKey
= NULL
;
1481 result
= SecKeychainGetMasterKey(userKeychainRef
, &masterKey
, password
);
1482 if (errSecSuccess
!= result
) {
1486 result
= SecKeychainStash();
1487 if (errSecSuccess
!= result
) {
1488 if (masterKey
!= NULL
) CFRelease(masterKey
);
1492 CFMutableArrayRef trustedApplications
= CFArrayCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeArrayCallBacks
);
1493 if (noErr
== SecTrustedApplicationCreateApplicationGroup("com.apple.security.auto-login", NULL
, &itemPath
) && itemPath
)
1494 CFArrayAppendValue(trustedApplications
, itemPath
);
1496 if (trustedApplications
&& (CFArrayGetCount(trustedApplications
) > 0)) {
1497 if (errSecSuccess
== (result
= SecAccessCreate(CFSTR("Auto-Login applications"), trustedApplications
, &ourAccessRef
))) {
1498 SecKeychainRef internalSystemKeychainRef
= NULL
;
1499 if (NULL
== systemKeychainRef
) {
1500 SecKeychainCopyDomainDefault(kSecPreferencesDomainSystem
, &internalSystemKeychainRef
);
1502 internalSystemKeychainRef
= systemKeychainRef
;
1505 const void *queryKeys
[] = { kSecClass
,
1510 const void *queryValues
[] = { kSecClassGenericPassword
,
1511 CFSTR("com.apple.loginwindow.auto-login"),
1513 internalSystemKeychainRef
,
1516 const void *updateKeys
[] = { kSecAttrAccess
,
1519 const void *updateValues
[] = { ourAccessRef
,
1523 CFDictionaryRef query
= CFDictionaryCreate(kCFAllocatorDefault
, queryKeys
, queryValues
, sizeof(queryValues
)/sizeof(*queryValues
), &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
1524 CFDictionaryRef update
= CFDictionaryCreate(kCFAllocatorDefault
, updateKeys
, updateValues
, sizeof(updateValues
)/sizeof(*updateValues
), &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
1526 result
= SecItemUpdate(query
, update
);
1528 if (errSecSuccess
!= result
) {
1529 const void *addKeys
[] = { kSecClass
,
1536 const void *addValues
[] = { kSecClassGenericPassword
,
1537 CFSTR("com.apple.loginwindow.auto-login"),
1539 internalSystemKeychainRef
,
1544 CFDictionaryRef add
= CFDictionaryCreate(kCFAllocatorDefault
, addKeys
, addValues
, sizeof(addValues
)/sizeof(*addValues
), &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
1545 result
= SecItemAdd(add
, NULL
);
1546 if (NULL
!= add
) CFRelease(add
);
1549 if (NULL
!= query
) CFRelease(query
);
1550 if (NULL
!= update
) CFRelease(update
);
1552 // If the caller wanted us to locate the system keychain reference, it's okay to go ahead and free our magically created one
1553 if (systemKeychainRef
== NULL
) CFRelease(internalSystemKeychainRef
);
1557 if (NULL
!= masterKey
) CFRelease(masterKey
);
1558 if (NULL
!= trustedApplications
) CFRelease(trustedApplications
);
1559 if (NULL
!= ourAccessRef
) CFRelease(ourAccessRef
);
1564 OSStatus
SecKeychainGetUserPromptAttempts(uint32_t * attempts
)
1567 os_activity_t activity
= os_activity_create("SecKeychainGetUserPromptAttempts", OS_ACTIVITY_CURRENT
, OS_ACTIVITY_FLAG_IF_NONE_PRESENT
);
1568 os_activity_scope(activity
);
1569 os_release(activity
);
1572 SecurityServer::ClientSession().getUserPromptAttempts(*attempts
);
1578 OSStatus
SecKeychainStoreUnlockKeyWithPubKeyHash(CFDataRef pubKeyHash
, CFStringRef tokenID
, CFDataRef wrapPubKeyHash
,
1579 SecKeychainRef userKeychain
, CFStringRef password
)
1581 CFRef
<CFStringRef
> pwd
;
1584 if (password
== NULL
|| CFStringGetLength(password
) == 0) {
1585 AuthorizationRef authorizationRef
;
1586 result
= AuthorizationCreate(NULL
, NULL
, kAuthorizationFlagDefaults
, &authorizationRef
);
1587 if (result
!= errAuthorizationSuccess
) {
1588 secnotice("SecKeychain", "failed to create authorization");
1592 AuthorizationItem myItems
= {"com.apple.ctk.pair", 0, NULL
, 0};
1593 AuthorizationRights myRights
= {1, &myItems
};
1594 AuthorizationRights
*authorizedRights
= NULL
;
1596 char pathName
[PATH_MAX
];
1597 UInt32 pathLength
= PATH_MAX
;
1598 result
= SecKeychainGetPath(userKeychain
, &pathLength
, pathName
);
1599 if (result
!= errSecSuccess
) {
1600 secnotice("SecKeychain", "failed to create authorization");
1604 Boolean checkPwd
= TRUE
;
1605 Boolean ignoreSession
= TRUE
;
1606 AuthorizationItem envItems
[] = {
1607 {AGENT_HINT_KEYCHAIN_PATH
, pathLength
, pathName
, 0},
1608 {AGENT_HINT_KEYCHAIN_CHECK
, sizeof(checkPwd
), &checkPwd
},
1609 {AGENT_HINT_IGNORE_SESSION
, sizeof(ignoreSession
), &ignoreSession
}
1612 AuthorizationEnvironment environment
= {3, envItems
};
1613 AuthorizationFlags flags
= kAuthorizationFlagDefaults
| kAuthorizationFlagInteractionAllowed
| kAuthorizationFlagExtendRights
;
1614 result
= AuthorizationCopyRights(authorizationRef
, &myRights
, &environment
, flags
, &authorizedRights
);
1615 if (authorizedRights
)
1616 AuthorizationFreeItemSet(authorizedRights
);
1618 if (result
== errAuthorizationSuccess
) {
1619 AuthorizationItemSet
*items
;
1620 result
= AuthorizationCopyInfo(authorizationRef
, kAuthorizationEnvironmentPassword
, &items
);
1621 if (result
== errAuthorizationSuccess
) {
1622 if (items
->count
> 0) {
1623 pwd
= CFStringCreateWithCString(kCFAllocatorDefault
, (const char *)items
->items
[0].value
, kCFStringEncodingUTF8
);
1625 AuthorizationFreeItemSet(items
);
1628 AuthorizationFree(authorizationRef
, kAuthorizationFlagDefaults
);
1629 if (result
!= errAuthorizationSuccess
) {
1630 secnotice("SecKeychain", "did not get authorization to pair the card");
1638 secnotice("SecKeychain", "did not get kcpass");
1639 return errSecInternalComponent
;
1642 CFRef
<CFDataRef
> masterKey
;
1643 result
= SecKeychainGetMasterKey(userKeychain
, masterKey
.take(), pwd
);
1644 if (result
!= errSecSuccess
) {
1645 secnotice("SecKeychain", "Failed to get master key: %d", (int) result
);
1649 CFRef
<CFDataRef
> scBlob
;
1650 result
= TokenLoginGetScBlob(wrapPubKeyHash
, tokenID
, pwd
, scBlob
.take());
1651 if (result
!= errSecSuccess
) {
1652 secnotice("SecKeychain", "Failed to get stash: %d", (int) result
);
1656 result
= TokenLoginCreateLoginData(tokenID
, pubKeyHash
, wrapPubKeyHash
, masterKey
, scBlob
);
1657 if (result
!= errSecSuccess
) {
1658 secnotice("SecKeychain", "Failed to create login data: %d", (int) result
);
1662 secnotice("SecKeychain", "SecKeychainStoreUnlockKeyWithPubKeyHash result %d", (int) result
);
1666 OSStatus
SecKeychainEraseUnlockKeyWithPubKeyHash(CFDataRef pubKeyHash
)
1668 OSStatus result
= TokenLoginDeleteUnlockData(pubKeyHash
);
1669 if (result
!= errSecSuccess
) {
1670 secnotice("SecKeychain", "Failed to erase stored wrapped unlock key: %d", (int) result
);