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>
40 SecKeychainMDSInstall()
44 Security::MDSClient::Directory d
;
51 SecKeychainGetTypeID(void)
55 return gTypes().KeychainImpl
.typeID
;
57 END_SECAPI1(_kCFRuntimeNotATypeID
)
62 SecKeychainGetVersion(UInt32
*returnVers
)
67 *returnVers
= 0x02028000;
73 SecKeychainOpen(const char *pathName
, SecKeychainRef
*keychainRef
)
77 RequiredParam(keychainRef
)=globals().storageManager
.make(pathName
, false)->handle();
84 SecKeychainOpenWithGuid(const CSSM_GUID
*guid
, uint32 subserviceId
, uint32 subserviceType
, const char* dbName
,
85 const CSSM_NET_ADDRESS
*dbLocation
, SecKeychainRef
*keychain
)
89 // range check parameters
91 RequiredParam (dbName
);
93 // create a DLDbIdentifier that describes what should be opened
94 const CSSM_VERSION
*version
= NULL
;
95 const CssmSubserviceUid
ssuid(*guid
, version
, subserviceId
, subserviceType
);
96 DLDbIdentifier
dLDbIdentifier(ssuid
, dbName
, dbLocation
);
98 // make a keychain from the supplied info
99 RequiredParam(keychain
) = globals().storageManager
.makeKeychain(dLDbIdentifier
, false)->handle ();
106 SecKeychainCreate(const char *pathName
, UInt32 passwordLength
, const void *password
,
107 Boolean promptUser
, SecAccessRef initialAccess
, SecKeychainRef
*keychainRef
)
111 KCThrowParamErrIf_(!pathName
);
112 Keychain keychain
= globals().storageManager
.make(pathName
);
114 // @@@ the call to StorageManager::make above leaves keychain the the cache.
115 // If the create below fails we should probably remove it.
120 KCThrowParamErrIf_(!password
);
121 keychain
->create(passwordLength
, password
);
124 RequiredParam(keychainRef
)=keychain
->handle();
131 SecKeychainDelete(SecKeychainRef keychainOrArray
)
135 KCThrowIf_(!keychainOrArray
, errSecInvalidKeychain
);
136 StorageManager::KeychainList keychains
;
137 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
139 globals().storageManager
.remove(keychains
, true);
146 SecKeychainSetSettings(SecKeychainRef keychainRef
, const SecKeychainSettings
*newSettings
)
150 Keychain keychain
= Keychain::optional(keychainRef
);
151 if (newSettings
->version
==SEC_KEYCHAIN_SETTINGS_VERS1
)
153 UInt32 lockInterval
=newSettings
->lockInterval
;
154 bool lockOnSleep
=newSettings
->lockOnSleep
;
155 keychain
->setSettings(lockInterval
, lockOnSleep
);
163 SecKeychainCopySettings(SecKeychainRef keychainRef
, SecKeychainSettings
*outSettings
)
167 Keychain keychain
= Keychain::optional(keychainRef
);
168 if (outSettings
->version
==SEC_KEYCHAIN_SETTINGS_VERS1
)
173 keychain
->getSettings(lockInterval
, lockOnSleep
);
174 outSettings
->lockInterval
=lockInterval
;
175 outSettings
->lockOnSleep
=lockOnSleep
;
183 SecKeychainUnlock(SecKeychainRef keychainRef
, UInt32 passwordLength
, const void *password
, Boolean usePassword
)
187 Keychain keychain
= Keychain::optional(keychainRef
);
190 keychain
->unlock(CssmData(const_cast<void *>(password
), passwordLength
));
199 SecKeychainLock(SecKeychainRef keychainRef
)
203 Keychain keychain
= Keychain::optional(keychainRef
);
211 SecKeychainLockAll(void)
215 globals().storageManager
.lockAll();
221 OSStatus
SecKeychainResetLogin(UInt32 passwordLength
, const void* password
, Boolean resetSearchList
)
225 // Get the current user (using fallback method if necessary)
227 char* uName
= getenv("USER");
228 string userName
= uName
? uName
: "";
229 if ( userName
.length() == 0 )
231 uid_t uid
= geteuid();
232 if (!uid
) uid
= getuid();
233 struct passwd
*pw
= getpwuid(uid
); // fallback case...
235 userName
= pw
->pw_name
;
238 if ( userName
.length() == 0 ) // did we ultimately get one?
239 MacOSError::throwMe(errAuthorizationInternal
);
241 SecurityServer::ClientSession().resetKeyStorePassphrase(password
? CssmData(const_cast<void *>(password
), passwordLength
) : CssmData());
245 // Clear the plist and move aside (rename) the existing login.keychain
246 globals().storageManager
.resetKeychain(resetSearchList
);
248 // Create the login keychain without UI
249 globals().storageManager
.login((UInt32
)userName
.length(), userName
.c_str(), passwordLength
, password
);
251 // Set it as the default
252 Keychain keychain
= globals().storageManager
.loginKeychain();
253 globals().storageManager
.defaultKeychain(keychain
);
257 // Create the login keychain, prompting for password
258 // (implicitly calls resetKeychain, login, and defaultKeychain)
259 globals().storageManager
.makeLoginAuthUI(NULL
);
262 // Post a "list changed" event after a reset, so apps can refresh their list.
263 // Make sure we are not holding mLock when we post this event.
264 KCEventNotifier::PostKeychainEvent(kSecKeychainListChangedEvent
);
270 SecKeychainCopyDefault(SecKeychainRef
*keychainRef
)
274 RequiredParam(keychainRef
)=globals().storageManager
.defaultKeychain()->handle();
281 SecKeychainSetDefault(SecKeychainRef keychainRef
)
285 globals().storageManager
.defaultKeychain(Keychain::optional(keychainRef
));
290 OSStatus
SecKeychainCopySearchList(CFArrayRef
*searchList
)
294 RequiredParam(searchList
);
295 StorageManager
&smr
= globals().storageManager
;
296 StorageManager::KeychainList keychainList
;
297 smr
.getSearchList(keychainList
);
298 *searchList
= smr
.convertFromKeychainList(keychainList
);
303 OSStatus
SecKeychainSetSearchList(CFArrayRef searchList
)
307 RequiredParam(searchList
);
308 StorageManager
&smr
= globals().storageManager
;
309 StorageManager::KeychainList keychainList
;
310 smr
.convertToKeychainList(searchList
, keychainList
);
311 smr
.setSearchList(keychainList
);
316 OSStatus
SecKeychainCopyDomainDefault(SecPreferencesDomain domain
, SecKeychainRef
*keychainRef
)
320 RequiredParam(keychainRef
)=globals().storageManager
.defaultKeychain(domain
)->handle();
325 OSStatus
SecKeychainSetDomainDefault(SecPreferencesDomain domain
, SecKeychainRef keychainRef
)
329 globals().storageManager
.defaultKeychain(domain
, Keychain::optional(keychainRef
));
334 OSStatus
SecKeychainCopyDomainSearchList(SecPreferencesDomain domain
, CFArrayRef
*searchList
)
338 RequiredParam(searchList
);
339 StorageManager
&smr
= globals().storageManager
;
340 StorageManager::KeychainList keychainList
;
341 smr
.getSearchList(domain
, keychainList
);
342 *searchList
= smr
.convertFromKeychainList(keychainList
);
347 OSStatus
SecKeychainSetDomainSearchList(SecPreferencesDomain domain
, CFArrayRef searchList
)
351 RequiredParam(searchList
);
352 StorageManager
&smr
= globals().storageManager
;
353 StorageManager::KeychainList keychainList
;
354 smr
.convertToKeychainList(searchList
, keychainList
);
355 smr
.setSearchList(domain
, keychainList
);
360 OSStatus
SecKeychainSetPreferenceDomain(SecPreferencesDomain domain
)
364 globals().storageManager
.domain(domain
);
369 OSStatus
SecKeychainGetPreferenceDomain(SecPreferencesDomain
*domain
)
373 *domain
= globals().storageManager
.domain();
380 SecKeychainGetStatus(SecKeychainRef keychainRef
, SecKeychainStatus
*keychainStatus
)
384 RequiredParam(keychainStatus
) = (SecKeychainStatus
)Keychain::optional(keychainRef
)->status();
391 SecKeychainGetPath(SecKeychainRef keychainRef
, UInt32
*ioPathLength
, char *pathName
)
395 RequiredParam(pathName
);
396 RequiredParam(ioPathLength
);
398 const char *name
= Keychain::optional(keychainRef
)->name();
399 UInt32 nameLen
= (UInt32
)strlen(name
);
400 UInt32 callersLen
= *ioPathLength
;
401 *ioPathLength
= nameLen
;
402 if (nameLen
+1 > callersLen
) // if the client's buffer is too small (including null-termination), throw
403 return errSecBufferTooSmall
;
404 strncpy(pathName
, name
, nameLen
);
405 pathName
[nameLen
] = 0;
406 *ioPathLength
= nameLen
; // set the length.
414 SecKeychainListGetCount(void)
418 return globals().storageManager
.size();
426 SecKeychainListCopyKeychainAtIndex(UInt16 index
, SecKeychainRef
*keychainRef
)
430 KeychainCore::StorageManager
&smgr
=KeychainCore::globals().storageManager
;
431 RequiredParam(keychainRef
)=smgr
[index
]->handle();
439 SecKeychainListRemoveKeychain(SecKeychainRef
*keychainRef
)
443 Required(keychainRef
);
444 Keychain keychain
= Keychain::optional(*keychainRef
);
445 StorageManager::KeychainList keychainList
;
446 keychainList
.push_back(keychain
);
447 globals().storageManager
.remove(keychainList
);
455 SecKeychainAttributeInfoForItemID(SecKeychainRef keychainRef
, UInt32 itemID
, SecKeychainAttributeInfo
**info
)
459 Keychain keychain
= Keychain::optional(keychainRef
);
460 keychain
->getAttributeInfoForItemID(itemID
, info
);
467 SecKeychainFreeAttributeInfo(SecKeychainAttributeInfo
*info
)
471 KeychainImpl::freeAttributeInfo(info
);
478 SecKeychainAddCallback(SecKeychainCallback callbackFunction
, SecKeychainEventMask eventMask
, void* userContext
)
482 RequiredParam(callbackFunction
);
483 CCallbackMgr::AddCallback(callbackFunction
,eventMask
,userContext
);
490 SecKeychainRemoveCallback(SecKeychainCallback callbackFunction
)
494 RequiredParam(callbackFunction
);
495 CCallbackMgr::RemoveCallback(callbackFunction
);
501 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
)
505 KCThrowParamErrIf_(passwordLength
!=0 && passwordData
==NULL
);
506 // @@@ Get real itemClass
507 Item
item(kSecInternetPasswordItemClass
, 'aapl', passwordLength
, passwordData
, false);
509 if (serverName
&& serverNameLength
)
511 CssmData
server(const_cast<void *>(reinterpret_cast<const void *>(serverName
)), serverNameLength
);
512 item
->setAttribute(Schema::attributeInfo(kSecServerItemAttr
), server
);
513 // use server name as default label
514 item
->setAttribute(Schema::attributeInfo(kSecLabelItemAttr
), server
);
517 if (accountName
&& accountNameLength
)
519 CssmData
account(const_cast<void *>(reinterpret_cast<const void *>(accountName
)), accountNameLength
);
520 item
->setAttribute(Schema::attributeInfo(kSecAccountItemAttr
), account
);
523 if (securityDomain
&& securityDomainLength
)
524 item
->setAttribute(Schema::attributeInfo(kSecSecurityDomainItemAttr
),
525 CssmData(const_cast<void *>(reinterpret_cast<const void *>(securityDomain
)), securityDomainLength
));
527 item
->setAttribute(Schema::attributeInfo(kSecPortItemAttr
), UInt32(port
));
528 item
->setAttribute(Schema::attributeInfo(kSecProtocolItemAttr
), protocol
);
529 item
->setAttribute(Schema::attributeInfo(kSecAuthenticationTypeItemAttr
), authenticationType
);
531 if (path
&& pathLength
)
532 item
->setAttribute(Schema::attributeInfo(kSecPathItemAttr
),
533 CssmData(const_cast<void *>(reinterpret_cast<const void *>(path
)), pathLength
));
535 Keychain keychain
= nil
;
538 keychain
= Keychain::optional(keychainRef
);
539 if ( !keychain
->exists() )
541 MacOSError::throwMe(errSecNoSuchKeychain
); // Might be deleted or not available at this time.
546 keychain
= globals().storageManager
.defaultKeychainUI(item
);
552 *itemRef
= item
->handle();
559 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
)
564 StorageManager::KeychainList keychains
;
565 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
566 KCCursor
cursor(keychains
, kSecInternetPasswordItemClass
, NULL
);
568 if (serverName
&& serverNameLength
)
570 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecServerItemAttr
),
571 CssmData(const_cast<char *>(serverName
), serverNameLength
));
574 if (securityDomain
&& securityDomainLength
)
576 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecSecurityDomainItemAttr
),
577 CssmData (const_cast<char*>(securityDomain
), securityDomainLength
));
580 if (accountName
&& accountNameLength
)
582 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecAccountItemAttr
),
583 CssmData (const_cast<char*>(accountName
), accountNameLength
));
588 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecPortItemAttr
),
594 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecProtocolItemAttr
),
598 if (authenticationType
)
600 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecAuthenticationTypeItemAttr
),
604 if (path
&& pathLength
)
606 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecPathItemAttr
), path
);
610 if (!cursor
->next(item
))
611 return errSecItemNotFound
;
613 // Get its data (only if necessary)
614 if (passwordData
|| passwordLength
)
616 CssmDataContainer outData
;
617 item
->getData(outData
);
618 *passwordLength
=(UInt32
)outData
.length();
620 *passwordData
=outData
.data();
625 *itemRef
=item
->handle();
632 SecKeychainAddGenericPassword(SecKeychainRef keychainRef
, UInt32 serviceNameLength
, const char *serviceName
, UInt32 accountNameLength
, const char *accountName
, UInt32 passwordLength
, const void *passwordData
, SecKeychainItemRef
*itemRef
)
636 KCThrowParamErrIf_(passwordLength
!=0 && passwordData
==NULL
);
637 // @@@ Get real itemClass
639 Item
item(kSecGenericPasswordItemClass
, 'aapl', passwordLength
, passwordData
, false);
641 if (serviceName
&& serviceNameLength
)
643 CssmData
service(const_cast<void *>(reinterpret_cast<const void *>(serviceName
)), serviceNameLength
);
644 item
->setAttribute(Schema::attributeInfo(kSecServiceItemAttr
), service
);
645 // use service name as default label (UNLESS the service is iTools and we have an account name [3787371])
646 const char *iTools
= "iTools";
647 if (accountNameLength
&& serviceNameLength
==strlen(iTools
) && !memcmp(serviceName
, iTools
, serviceNameLength
))
649 CssmData
account(const_cast<void *>(reinterpret_cast<const void *>(accountName
)), accountNameLength
);
650 item
->setAttribute(Schema::attributeInfo(kSecLabelItemAttr
), account
);
654 item
->setAttribute(Schema::attributeInfo(kSecLabelItemAttr
), service
);
658 if (accountName
&& accountNameLength
)
660 CssmData
account(const_cast<void *>(reinterpret_cast<const void *>(accountName
)), accountNameLength
);
661 item
->setAttribute(Schema::attributeInfo(kSecAccountItemAttr
), account
);
664 Keychain keychain
= nil
;
667 keychain
= Keychain::optional(keychainRef
);
668 if ( !keychain
->exists() )
670 MacOSError::throwMe(errSecNoSuchKeychain
); // Might be deleted or not available at this time.
675 keychain
= globals().storageManager
.defaultKeychainUI(item
);
680 *itemRef
= item
->handle();
687 SecKeychainFindGenericPassword(CFTypeRef keychainOrArray
, UInt32 serviceNameLength
, const char *serviceName
, UInt32 accountNameLength
, const char *accountName
, UInt32
*passwordLength
, void **passwordData
, SecKeychainItemRef
*itemRef
)
692 StorageManager::KeychainList keychains
;
693 globals().storageManager
.optionalSearchList(keychainOrArray
, keychains
);
694 KCCursor
cursor(keychains
, kSecGenericPasswordItemClass
, NULL
);
696 if (serviceName
&& serviceNameLength
)
698 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecServiceItemAttr
),
699 CssmData(const_cast<char *>(serviceName
), serviceNameLength
));
702 if (accountName
&& accountNameLength
)
704 cursor
->add(CSSM_DB_EQUAL
, Schema::attributeInfo(kSecAccountItemAttr
),
705 CssmData(const_cast<char *>(accountName
), accountNameLength
));
709 if (!cursor
->next(item
))
710 return errSecItemNotFound
;
712 // Get its data (only if necessary)
713 if (passwordData
|| passwordLength
)
715 CssmDataContainer outData
;
716 item
->getData(outData
);
717 *passwordLength
=(UInt32
)outData
.length();
719 *passwordData
=outData
.data();
724 *itemRef
=item
->handle();
731 SecKeychainSetUserInteractionAllowed(Boolean state
)
735 globals().setUserInteractionAllowed(state
);
742 SecKeychainGetUserInteractionAllowed(Boolean
*state
)
746 Required(state
)=globals().getUserInteractionAllowed();
753 SecKeychainGetDLDBHandle(SecKeychainRef keychainRef
, CSSM_DL_DB_HANDLE
*dldbHandle
)
757 RequiredParam(dldbHandle
);
759 Keychain keychain
= Keychain::optional(keychainRef
);
760 *dldbHandle
= keychain
->database()->handle();
767 SecKeychainGetCSPHandle(SecKeychainRef keychainRef
, CSSM_CSP_HANDLE
*cspHandle
)
771 RequiredParam(cspHandle
);
773 Keychain keychain
= Keychain::optional(keychainRef
);
774 *cspHandle
= keychain
->csp()->handle();
781 SecKeychainCopyAccess(SecKeychainRef keychainRef
, SecAccessRef
*accessRef
)
785 MacOSError::throwMe(errSecUnimplemented
);//%%%for now
792 SecKeychainSetAccess(SecKeychainRef keychainRef
, SecAccessRef accessRef
)
796 MacOSError::throwMe(errSecUnimplemented
);//%%%for now
802 #pragma mark ---- Private API ----
806 SecKeychainChangePassword(SecKeychainRef keychainRef
, UInt32 oldPasswordLength
, const void *oldPassword
, UInt32 newPasswordLength
, const void *newPassword
)
810 Keychain keychain
= Keychain::optional(keychainRef
);
811 keychain
->changePassphrase (oldPasswordLength
, oldPassword
, newPasswordLength
, newPassword
);
818 SecKeychainCopyLogin(SecKeychainRef
*keychainRef
)
822 RequiredParam(keychainRef
)=globals().storageManager
.loginKeychain()->handle();
829 SecKeychainLogin(UInt32 nameLength
, const void* name
, UInt32 passwordLength
, const void* password
)
836 globals().storageManager
.login(nameLength
, name
, passwordLength
, password
);
838 globals().storageManager
.stashLogin();
841 catch (CommonError
&e
)
843 if (e
.osStatus() == CSSMERR_DL_OPERATION_AUTH_DENIED
)
845 return errSecAuthFailed
;
856 OSStatus
SecKeychainStash()
862 globals().storageManager
.stashKeychain();
864 catch (CommonError
&e
)
866 if (e
.osStatus() == CSSMERR_DL_OPERATION_AUTH_DENIED
)
868 return errSecAuthFailed
;
884 globals().storageManager
.logout();
889 /* (non-exported C utility routine) 'Makes' a keychain based on a full path
891 static Keychain
make(const char *name
)
893 return globals().storageManager
.make(name
);
896 /* 'Makes' a keychain based on a full path for legacy "KC" CoreServices APIs.
897 Note this version doesn't take an accessRef or password.
898 The "KC" create API takes a keychainRef...
900 OSStatus
SecKeychainMakeFromFullPath(const char *fullPathName
, SecKeychainRef
*keychainRef
)
903 RequiredParam(fullPathName
);
904 RequiredParam(keychainRef
)=make(fullPathName
)->handle();
909 /* Determines if the keychainRef is a valid keychain.
911 OSStatus
SecKeychainIsValid(SecKeychainRef keychainRef
, Boolean
* isValid
)
915 if (KeychainImpl::optional(keychainRef
)->dlDbIdentifier().ssuid().guid() == gGuidAppleCSPDL
)
920 /* Removes a keychain from the keychain search list for legacy "KC" CoreServices APIs.
922 OSStatus
SecKeychainRemoveFromSearchList(SecKeychainRef keychainRef
)
925 StorageManager::KeychainList singleton
;
926 singleton
.push_back(KeychainImpl::required(keychainRef
));
927 globals().storageManager
.remove(singleton
);
931 /* Create a keychain based on a keychain Ref for legacy "KC" CoreServices APIs.
933 OSStatus
SecKeychainCreateNew(SecKeychainRef keychainRef
, UInt32 passwordLength
, const char* inPassword
)
936 RequiredParam(inPassword
);
937 KeychainImpl::required(keychainRef
)->create(passwordLength
, inPassword
);
941 /* Modify a keychain so that it can be synchronized.
943 OSStatus
SecKeychainRecodeKeychain(SecKeychainRef keychainRef
, CFArrayRef dbBlobArray
, CFDataRef extraData
)
947 // do error checking for required parameters
948 RequiredParam(dbBlobArray
);
949 RequiredParam(extraData
);
951 const CssmData
extraCssmData(const_cast<UInt8
*>(CFDataGetBytePtr(extraData
)),
952 CFDataGetLength(extraData
));
954 CFIndex dbBlobArrayCount
= CFArrayGetCount(dbBlobArray
);
955 size_t space
= sizeof(uint8
) + (dbBlobArrayCount
* sizeof(SecurityServer::DbHandle
));
956 void *dataPtr
= (void*)malloc(space
);
958 return errSecAllocate
;
960 // Get a DbHandle(IPCDbHandle) from securityd for each blob in the array that we'll authenticate with.
962 uint8
* sizePtr
= (uint8
*)dataPtr
;
963 *sizePtr
= dbBlobArrayCount
;
964 SecurityServer::DbHandle
*currDbHandle
= (SecurityServer::DbHandle
*)(sizePtr
+1);
966 SecurityServer::ClientSession
ss(Allocator::standard(), Allocator::standard());
967 for (index
=0; index
< dbBlobArrayCount
; index
++)
969 CFDataRef cfBlobData
= (CFDataRef
)CFArrayGetValueAtIndex(dbBlobArray
, index
);
970 const CssmData
thisKCData(const_cast<UInt8
*>(CFDataGetBytePtr(cfBlobData
)), CFDataGetLength(cfBlobData
));
972 // Since it's to a DbHandle that's not on our disk (it came from user's iDisk),
973 // it's OK to use the mIdentifier and access credentials of the keychain we're recoding.
975 Keychain kc
= KeychainImpl::required(keychainRef
);
976 *currDbHandle
= ss
.decodeDb(kc
->dlDbIdentifier(), kc
->defaultCredentials(), thisKCData
); /* returns a DbHandle (IPCDbHandle) */
981 Keychain keychain
= Keychain::optional(keychainRef
);
982 const CssmData
data(const_cast<UInt8
*>((uint8
*)dataPtr
), space
);
983 Boolean recodeFailed
= false;
985 int errCode
=errSecSuccess
;
989 keychain
->recode(data
, extraCssmData
);
993 errCode
= e
.osStatus();
998 errCode
= ue
.unixError();
1001 currDbHandle
= (SecurityServer::DbHandle
*)(sizePtr
+1);
1002 for (index
=0; index
< dbBlobArrayCount
; index
++)
1004 ss
.releaseDb(*currDbHandle
);
1018 OSStatus
SecKeychainCopySignature(SecKeychainRef keychainRef
, CFDataRef
*keychainSignature
)
1022 // do error checking for required parameters
1023 RequiredParam(keychainSignature
);
1025 // make a keychain object "wrapper" for this keychain ref
1026 Keychain keychain
= Keychain::optional(keychainRef
);
1027 CssmAutoData
data(keychain
->database()->allocator());
1028 keychain
->copyBlob(data
.get());
1030 // get the cssmDBBlob
1031 const SecurityServer::DbBlob
*cssmDBBlob
=
1032 data
.get().interpretedAs
<const SecurityServer::DbBlob
>();
1034 // convert from CDSA standards to CF standards
1035 *keychainSignature
= CFDataCreate(kCFAllocatorDefault
,
1036 cssmDBBlob
->randomSignature
.bytes
,
1037 sizeof(SecurityServer::DbBlob::Signature
));
1042 OSStatus
SecKeychainCopyBlob(SecKeychainRef keychainRef
, CFDataRef
*dbBlob
)
1046 // do error checking for required parameters
1047 RequiredParam(dbBlob
);
1049 // make a keychain object "wrapper" for this keychain ref
1050 Keychain keychain
= Keychain::optional(keychainRef
);
1051 CssmAutoData
data(keychain
->database()->allocator());
1052 keychain
->copyBlob(data
.get());
1054 // convert from CDSA standards to CF standards
1055 *dbBlob
= CFDataCreate(kCFAllocatorDefault
, data
, data
.length());
1060 // make a new keychain with pre-existing secrets
1061 OSStatus
SecKeychainCreateWithBlob(const char* fullPathName
, CFDataRef dbBlob
, SecKeychainRef
*kcRef
)
1065 KCThrowParamErrIf_(!fullPathName
);
1066 KCThrowParamErrIf_(!dbBlob
);
1068 Keychain keychain
= globals().storageManager
.make(fullPathName
);
1070 CssmData
blob(const_cast<unsigned char *>(CFDataGetBytePtr(dbBlob
)), CFDataGetLength(dbBlob
));
1072 // @@@ the call to StorageManager::make above leaves keychain the the cache.
1073 // If the create below fails we should probably remove it.
1074 keychain
->createWithBlob(blob
);
1076 RequiredParam(kcRef
)=keychain
->handle();
1083 // add a non-file based DB to the keychain list
1084 OSStatus
SecKeychainAddDBToKeychainList (SecPreferencesDomain domain
, const char* dbName
,
1085 const CSSM_GUID
*guid
, uint32 subServiceType
)
1089 RequiredParam(dbName
);
1090 StorageManager
&smr
= globals().storageManager
;
1091 smr
.addToDomainList(domain
, dbName
, *guid
, subServiceType
);
1096 // determine if a non-file based DB is in the keychain list
1097 OSStatus
SecKeychainDBIsInKeychainList (SecPreferencesDomain domain
, const char* dbName
,
1098 const CSSM_GUID
*guid
, uint32 subServiceType
)
1101 RequiredParam(dbName
);
1102 StorageManager
&smr
= globals().storageManager
;
1103 smr
.isInDomainList(domain
, dbName
, *guid
, subServiceType
);
1107 // remove a non-file based DB from the keychain list
1108 OSStatus
SecKeychainRemoveDBFromKeychainList (SecPreferencesDomain domain
, const char* dbName
,
1109 const CSSM_GUID
*guid
, uint32 subServiceType
)
1112 RequiredParam(dbName
);
1113 StorageManager
&smr
= globals().storageManager
;
1114 smr
.removeFromDomainList(domain
, dbName
, *guid
, subServiceType
);
1119 // set server mode -- must be called before any other Sec* etc. call
1120 void SecKeychainSetServerMode()
1127 OSStatus
SecKeychainSetBatchMode (SecKeychainRef kcRef
, Boolean mode
, Boolean rollback
)
1130 RequiredParam(kcRef
);
1131 Keychain keychain
= Keychain::optional(kcRef
);
1132 keychain
->setBatchMode(mode
, rollback
);
1138 OSStatus
SecKeychainCleanupHandles()
1141 END_SECAPI
// which causes the handle cache cleanup routine to run
1144 OSStatus
SecKeychainVerifyKeyStorePassphrase(uint32_t retries
)
1147 SecurityServer::ClientSession().verifyKeyStorePassphrase(retries
);
1151 OSStatus
SecKeychainChangeKeyStorePassphrase()
1154 SecurityServer::ClientSession().changeKeyStorePassphrase();
1158 static OSStatus
SecKeychainGetMasterKey(SecKeychainRef userKeychainRef
, CFDataRef
*masterKey
, CFStringRef password
)
1162 // make a keychain object "wrapper" for this keychain ref
1163 Keychain keychain
= Keychain::optional(userKeychainRef
);
1165 CssmClient::Db db
= keychain
->database();
1167 // create the keychain, using appropriate credentials
1168 Allocator
&alloc
= db
->allocator();
1169 AutoCredentials
cred(alloc
); // will leak, but we're quitting soon :-)
1171 char passphrase
[1024];
1172 CFStringGetCString(password
, passphrase
, sizeof(passphrase
), kCFStringEncodingUTF8
);
1174 // use this passphrase
1175 cred
+= TypedList(alloc
, CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK
,
1176 new(alloc
) ListElement(CSSM_SAMPLE_TYPE_PASSWORD
),
1177 new(alloc
) ListElement(StringData(passphrase
)));
1178 db
->accessCredentials(&cred
);
1180 CSSM_DL_DB_HANDLE dlDb
= db
->handle();
1181 CssmData dlDbData
= CssmData::wrap(dlDb
);
1183 KeySpec
spec(CSSM_KEYUSE_ANY
,
1184 CSSM_KEYATTR_RETURN_REF
| CSSM_KEYATTR_EXTRACTABLE
);
1186 DeriveKey
derive(keychain
->csp(), CSSM_ALGID_KEYCHAIN_KEY
, CSSM_ALGID_3DES_3KEY
, 3 * 64);
1187 derive(&dlDbData
, spec
, refKey
);
1189 // now extract the raw keybits
1191 WrapKey
wrap(keychain
->csp(), CSSM_ALGID_NONE
);
1192 wrap(refKey
, rawKey
);
1194 *masterKey
= CFDataCreate(kCFAllocatorDefault
, rawKey
.keyData(), rawKey
.length());
1200 OSStatus
SecKeychainStoreUnlockKey(SecKeychainRef userKeychainRef
, SecKeychainRef systemKeychainRef
, CFStringRef username
, CFStringRef password
) {
1201 SecTrustedApplicationRef itemPath
;
1202 SecAccessRef ourAccessRef
= NULL
;
1204 OSStatus result
= errSecParam
;
1206 CFDataRef masterKey
= NULL
;
1207 result
= SecKeychainGetMasterKey(userKeychainRef
, &masterKey
, password
);
1208 if (errSecSuccess
!= result
) {
1212 result
= SecKeychainStash();
1213 if (errSecSuccess
!= result
) {
1214 if (NULL
!= masterKey
) CFRelease(masterKey
);
1218 CFMutableArrayRef trustedApplications
= CFArrayCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeArrayCallBacks
);
1219 if ( noErr
== SecTrustedApplicationCreateApplicationGroup("com.apple.security.auto-login", NULL
, &itemPath
) && itemPath
)
1220 CFArrayAppendValue(trustedApplications
, itemPath
);
1222 if ( trustedApplications
&& (CFArrayGetCount(trustedApplications
) > 0)) {
1223 if (errSecSuccess
== (result
= SecAccessCreate(CFSTR("Auto-Login applications"), trustedApplications
, &ourAccessRef
))) {
1224 if (NULL
== systemKeychainRef
) {
1225 SecKeychainCopyDomainDefault(kSecPreferencesDomainSystem
, &systemKeychainRef
);
1228 const void *queryKeys
[] = { kSecClass
,
1233 const void *queryValues
[] = { kSecClassGenericPassword
,
1234 CFSTR("com.apple.loginwindow.auto-login"),
1239 const void *updateKeys
[] = { kSecAttrAccess
,
1242 const void *updateValues
[] = { ourAccessRef
,
1246 CFDictionaryRef query
= CFDictionaryCreate(kCFAllocatorDefault
, queryKeys
, queryValues
, sizeof(queryValues
)/sizeof(*queryValues
), &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
1247 CFDictionaryRef update
= CFDictionaryCreate(kCFAllocatorDefault
, updateKeys
, updateValues
, sizeof(updateValues
)/sizeof(*updateValues
), &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
1249 result
= SecItemUpdate(query
, update
);
1251 if (errSecSuccess
!= result
) {
1252 const void *addKeys
[] = { kSecClass
,
1259 const void *addValues
[] = { kSecClassGenericPassword
,
1260 CFSTR("com.apple.loginwindow.auto-login"),
1267 CFDictionaryRef add
= CFDictionaryCreate(kCFAllocatorDefault
, addKeys
, addValues
, sizeof(addValues
)/sizeof(*addValues
), &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
1268 result
= SecItemAdd(add
, NULL
);
1269 if (NULL
!= add
) CFRelease(add
);
1272 if (NULL
!= query
) CFRelease(query
);
1273 if (NULL
!= update
) CFRelease(update
);
1277 if (NULL
!= masterKey
) CFRelease(masterKey
);
1278 if (NULL
!= trustedApplications
) CFRelease(trustedApplications
);
1279 if (NULL
!= ourAccessRef
) CFRelease(ourAccessRef
);
1280 if (NULL
!= systemKeychainRef
) CFRelease(systemKeychainRef
);