2 * Copyright (c) 2000-2004,2012 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 File: StorageManager.cpp
28 Contains: Working with multiple keychains
32 #include "StorageManager.h"
33 #include "KCEventNotifier.h"
35 #include <Security/cssmapple.h>
36 #include <sys/types.h>
37 #include <sys/param.h>
43 //#include <Security/AuthorizationTags.h>
44 //#include <Security/AuthSession.h>
45 #include <security_utilities/debugging.h>
46 #include <security_keychain/SecCFTypes.h>
47 //#include <Security/SecurityAgentClient.h>
48 #include <securityd_client/ssclient.h>
49 #include <Security/AuthorizationTags.h>
50 #include <Security/AuthorizationTagsPriv.h>
51 #include <Security/SecTask.h>
52 #include <security_keychain/SecCFTypes.h>
53 #include "TrustSettingsSchema.h"
55 //%%% add this to AuthorizationTagsPriv.h later
56 #ifndef AGENT_HINT_LOGIN_KC_SUPPRESS_RESET_PANEL
57 #define AGENT_HINT_LOGIN_KC_SUPPRESS_RESET_PANEL "loginKCCreate:suppressResetPanel"
64 using namespace CssmClient
;
65 using namespace KeychainCore
;
67 #define kLoginKeychainPathPrefix "~/Library/Keychains/"
68 #define kUserLoginKeychainPath "~/Library/Keychains/login.keychain"
69 #define kEmptyKeychainSizeInBytes 20460
71 //-----------------------------------------------------------------------------------
73 static SecPreferencesDomain
defaultPreferenceDomain()
75 SessionAttributeBits sessionAttrs
;
77 secdebug("servermode", "StorageManager initialized in server mode");
78 sessionAttrs
= sessionIsRoot
;
80 MacOSError::check(SessionGetInfo(callerSecuritySession
, NULL
, &sessionAttrs
));
83 // If this is the root session, use system preferences.
84 // (In SecurityServer debug mode, you'll get a (fake) root session
85 // that has graphics access. Ignore that to help testing.)
86 if ((sessionAttrs
& sessionIsRoot
)
87 IFDEBUG( && !(sessionAttrs
& sessionHasGraphicAccess
))) {
88 secdebug("storagemgr", "using system preferences");
89 return kSecPreferencesDomainSystem
;
92 // otherwise, use normal (user) preferences
93 return kSecPreferencesDomainUser
;
96 static bool isAppSandboxed()
99 SecTaskRef task
= SecTaskCreateFromSelf(NULL
);
101 CFTypeRef appSandboxValue
= SecTaskCopyValueForEntitlement(task
,
102 CFSTR("com.apple.security.app-sandbox"), NULL
);
103 if(appSandboxValue
!= NULL
) {
105 CFRelease(appSandboxValue
);
112 static bool shouldAddToSearchList(const DLDbIdentifier
&dLDbIdentifier
)
114 // Creation of a private keychain should not modify the search list: rdar://13529331
115 // However, we want to ensure the login and System keychains are in
116 // the search list if that is not the case when they are created.
117 // Note that App Sandbox apps may not modify the list in either case.
119 bool loginOrSystemKeychain
= false;
120 const char *dbname
= dLDbIdentifier
.dbName();
122 if ((!strcmp(dbname
, "/Library/Keychains/System.keychain")) ||
123 (strstr(dbname
, "/login.keychain")) ) {
124 loginOrSystemKeychain
= true;
127 return (loginOrSystemKeychain
&& !isAppSandboxed());
131 StorageManager::StorageManager() :
132 mSavedList(defaultPreferenceDomain()),
133 mCommonList(kSecPreferencesDomainCommon
),
134 mDomain(kSecPreferencesDomainUser
),
135 mMutex(Mutex::recursive
)
141 StorageManager::getStorageManagerMutex()
143 return &mKeychainMapMutex
;
148 StorageManager::keychain(const DLDbIdentifier
&dLDbIdentifier
)
150 StLock
<Mutex
>_(mKeychainMapMutex
);
155 KeychainMap::iterator it
= mKeychains
.find(dLDbIdentifier
);
156 if (it
!= mKeychains
.end())
158 if (it
->second
== NULL
) // cleared by weak reference?
160 mKeychains
.erase(it
);
169 secdebug("servermode", "keychain reference in server mode");
173 // The keychain is not in our cache. Create it.
174 Module
module(dLDbIdentifier
.ssuid().guid());
176 if (dLDbIdentifier
.ssuid().subserviceType() & CSSM_SERVICE_CSP
)
177 dl
= SSCSPDL(module);
181 dl
->subserviceId(dLDbIdentifier
.ssuid().subserviceId());
182 dl
->version(dLDbIdentifier
.ssuid().version());
183 Db
db(dl
, dLDbIdentifier
.dbName());
185 Keychain
keychain(db
);
186 // Add the keychain to the cache.
187 mKeychains
.insert(KeychainMap::value_type(dLDbIdentifier
, &*keychain
));
188 keychain
->inCache(true);
194 StorageManager::removeKeychain(const DLDbIdentifier
&dLDbIdentifier
,
195 KeychainImpl
*keychainImpl
)
197 // Lock the recursive mutex
199 StLock
<Mutex
>_(mKeychainMapMutex
);
201 KeychainMap::iterator it
= mKeychains
.find(dLDbIdentifier
);
202 if (it
!= mKeychains
.end() && (KeychainImpl
*) it
->second
== keychainImpl
)
203 mKeychains
.erase(it
);
205 keychainImpl
->inCache(false);
209 StorageManager::didRemoveKeychain(const DLDbIdentifier
&dLDbIdentifier
)
211 // Lock the recursive mutex
213 StLock
<Mutex
>_(mKeychainMapMutex
);
215 KeychainMap::iterator it
= mKeychains
.find(dLDbIdentifier
);
216 if (it
!= mKeychains
.end())
218 if (it
->second
!= NULL
) // did we get zapped by weak reference destruction
220 KeychainImpl
*keychainImpl
= it
->second
;
221 keychainImpl
->inCache(false);
224 mKeychains
.erase(it
);
228 // Create keychain if it doesn't exist, and optionally add it to the search list.
230 StorageManager::makeKeychain(const DLDbIdentifier
&dLDbIdentifier
, bool add
)
232 StLock
<Mutex
>_(mKeychainMapMutex
);
234 Keychain theKeychain
= keychain(dLDbIdentifier
);
236 bool updateList
= (add
&& shouldAddToSearchList(dLDbIdentifier
));
240 mSavedList
.revert(false);
241 DLDbList searchList
= mSavedList
.searchList();
242 if (find(searchList
.begin(), searchList
.end(), dLDbIdentifier
) != searchList
.end())
243 return theKeychain
; // theKeychain is already in the searchList.
245 mCommonList
.revert(false);
246 searchList
= mCommonList
.searchList();
247 if (find(searchList
.begin(), searchList
.end(), dLDbIdentifier
) != searchList
.end())
248 return theKeychain
; // theKeychain is already in the commonList don't add it to the searchList.
250 // If theKeychain doesn't exist don't bother adding it to the search list yet.
251 if (!theKeychain
->exists())
254 // theKeychain exists and is not in our search list, so add it to the
256 mSavedList
.revert(true);
257 mSavedList
.add(dLDbIdentifier
);
264 // Make sure we are not holding mStorageManagerLock anymore when we
266 KCEventNotifier::PostKeychainEvent(kSecKeychainListChangedEvent
);
272 // Be notified a Keychain just got created.
274 StorageManager::created(const Keychain
&keychain
)
276 StLock
<Mutex
>_(mKeychainMapMutex
);
278 DLDbIdentifier dLDbIdentifier
= keychain
->dlDbIdentifier();
279 bool defaultChanged
= false;
280 bool updateList
= shouldAddToSearchList(dLDbIdentifier
);
284 mSavedList
.revert(true);
285 // If we don't have a default Keychain yet. Make the newly created
286 // keychain the default.
287 if (!mSavedList
.defaultDLDbIdentifier())
289 mSavedList
.defaultDLDbIdentifier(dLDbIdentifier
);
290 defaultChanged
= true;
293 // Add the keychain to the search list prefs.
294 mSavedList
.add(dLDbIdentifier
);
297 // Make sure we are not holding mLock when we post these events.
298 KCEventNotifier::PostKeychainEvent(kSecKeychainListChangedEvent
);
303 KCEventNotifier::PostKeychainEvent(kSecDefaultChangedEvent
, dLDbIdentifier
);
308 StorageManager::createCursor(SecItemClass itemClass
,
309 const SecKeychainAttributeList
*attrList
)
311 StLock
<Mutex
>_(mMutex
);
313 KeychainList searchList
;
314 getSearchList(searchList
);
315 return KCCursor(searchList
, itemClass
, attrList
);
319 StorageManager::createCursor(const SecKeychainAttributeList
*attrList
)
321 StLock
<Mutex
>_(mMutex
);
323 KeychainList searchList
;
324 getSearchList(searchList
);
325 return KCCursor(searchList
, attrList
);
329 StorageManager::lockAll()
331 StLock
<Mutex
>_(mMutex
);
333 SecurityServer::ClientSession
ss(Allocator::standard(), Allocator::standard());
338 StorageManager::defaultKeychain()
340 StLock
<Mutex
>_(mMutex
);
342 Keychain theKeychain
;
346 mSavedList
.revert(false);
347 DLDbIdentifier
defaultDLDbIdentifier(mSavedList
.defaultDLDbIdentifier());
348 if (defaultDLDbIdentifier
)
350 theKeychain
= keychain(defaultDLDbIdentifier
);
351 ref
= theKeychain
->handle(false);
355 if (theKeychain
/* && theKeychain->exists() */)
358 MacOSError::throwMe(errSecNoDefaultKeychain
);
362 StorageManager::defaultKeychain(const Keychain
&keychain
)
364 StLock
<Mutex
>_(mMutex
);
366 // Only set a keychain as the default if we own it and can read/write it,
367 // and our uid allows modifying the directory for that preference domain.
368 if (!keychainOwnerPermissionsValidForDomain(keychain
->name(), mDomain
))
369 MacOSError::throwMe(errSecWrPerm
);
371 DLDbIdentifier oldDefaultId
;
372 DLDbIdentifier
newDefaultId(keychain
->dlDbIdentifier());
374 oldDefaultId
= mSavedList
.defaultDLDbIdentifier();
375 mSavedList
.revert(true);
376 mSavedList
.defaultDLDbIdentifier(newDefaultId
);
380 if (!(oldDefaultId
== newDefaultId
))
382 // Make sure we are not holding mLock when we post this event.
383 KCEventNotifier::PostKeychainEvent(kSecDefaultChangedEvent
, newDefaultId
);
388 StorageManager::defaultKeychain(SecPreferencesDomain domain
)
390 StLock
<Mutex
>_(mMutex
);
392 if (domain
== kSecPreferencesDomainDynamic
)
393 MacOSError::throwMe(errSecInvalidPrefsDomain
);
395 if (domain
== mDomain
)
396 return defaultKeychain();
399 DLDbIdentifier
defaultDLDbIdentifier(DLDbListCFPref(domain
).defaultDLDbIdentifier());
400 if (defaultDLDbIdentifier
)
401 return keychain(defaultDLDbIdentifier
);
403 MacOSError::throwMe(errSecNoDefaultKeychain
);
408 StorageManager::defaultKeychain(SecPreferencesDomain domain
, const Keychain
&keychain
)
410 StLock
<Mutex
>_(mMutex
);
412 if (domain
== kSecPreferencesDomainDynamic
)
413 MacOSError::throwMe(errSecInvalidPrefsDomain
);
415 if (domain
== mDomain
)
416 defaultKeychain(keychain
);
418 DLDbListCFPref(domain
).defaultDLDbIdentifier(keychain
->dlDbIdentifier());
422 StorageManager::loginKeychain()
424 StLock
<Mutex
>_(mMutex
);
426 Keychain theKeychain
;
428 mSavedList
.revert(false);
429 DLDbIdentifier
loginDLDbIdentifier(mSavedList
.loginDLDbIdentifier());
430 if (loginDLDbIdentifier
)
432 theKeychain
= keychain(loginDLDbIdentifier
);
436 if (theKeychain
&& theKeychain
->exists())
439 MacOSError::throwMe(errSecNoSuchKeychain
);
443 StorageManager::loginKeychain(Keychain keychain
)
445 StLock
<Mutex
>_(mMutex
);
447 mSavedList
.revert(true);
448 mSavedList
.loginDLDbIdentifier(keychain
->dlDbIdentifier());
453 StorageManager::size()
455 StLock
<Mutex
>_(mMutex
);
457 mSavedList
.revert(false);
458 mCommonList
.revert(false);
459 return mSavedList
.searchList().size() + mCommonList
.searchList().size();
463 StorageManager::at(unsigned int ix
)
465 StLock
<Mutex
>_(mMutex
);
467 mSavedList
.revert(false);
468 DLDbList dLDbList
= mSavedList
.searchList();
469 if (ix
< dLDbList
.size())
471 return keychain(dLDbList
[ix
]);
475 ix
-= dLDbList
.size();
476 mCommonList
.revert(false);
477 DLDbList commonList
= mCommonList
.searchList();
478 if (ix
>= commonList
.size())
479 MacOSError::throwMe(errSecInvalidKeychain
);
481 return keychain(commonList
[ix
]);
486 StorageManager::operator[](unsigned int ix
)
488 StLock
<Mutex
>_(mMutex
);
493 void StorageManager::rename(Keychain keychain
, const char* newName
)
496 StLock
<Mutex
>_(mKeychainMapMutex
);
498 bool changedDefault
= false;
499 DLDbIdentifier newDLDbIdentifier
;
501 mSavedList
.revert(true);
502 DLDbIdentifier defaultId
= mSavedList
.defaultDLDbIdentifier();
504 // Find the keychain object for the given ref
505 DLDbIdentifier dLDbIdentifier
= keychain
->dlDbIdentifier();
507 // Actually rename the database on disk.
508 keychain
->database()->rename(newName
);
510 if (dLDbIdentifier
== defaultId
)
513 newDLDbIdentifier
= keychain
->dlDbIdentifier();
514 // Rename the keychain in the search list.
515 mSavedList
.rename(dLDbIdentifier
, newDLDbIdentifier
);
517 // If this was the default keychain change it accordingly
519 mSavedList
.defaultDLDbIdentifier(newDLDbIdentifier
);
523 // we aren't worried about a weak reference here, because we have to
524 // hold a lock on an item in order to do the rename
526 // Now update the Keychain cache
527 if (keychain
->inCache())
529 KeychainMap::iterator it
= mKeychains
.find(dLDbIdentifier
);
530 if (it
!= mKeychains
.end() && (KeychainImpl
*) it
->second
== keychain
.get())
532 // Remove the keychain from the cache under its old
534 mKeychains
.erase(it
);
538 // If we renamed this keychain on top of an existing one we should
539 // drop the old one from the cache.
540 KeychainMap::iterator it
= mKeychains
.find(newDLDbIdentifier
);
541 if (it
!= mKeychains
.end())
543 Keychain
oldKeychain(it
->second
);
544 oldKeychain
->inCache(false);
545 // @@@ Ideally we should invalidate or fault this keychain object.
548 if (keychain
->inCache())
550 // If the keychain wasn't in the cache to being with let's not put
551 // it there now. There was probably a good reason it wasn't in it.
552 // If the keychain was in the cache, update it to use
553 // newDLDbIdentifier.
554 mKeychains
.insert(KeychainMap::value_type(newDLDbIdentifier
,
559 // Make sure we are not holding mLock when we post these events.
560 KCEventNotifier::PostKeychainEvent(kSecKeychainListChangedEvent
);
563 KCEventNotifier::PostKeychainEvent(kSecDefaultChangedEvent
,
567 void StorageManager::renameUnique(Keychain keychain
, CFStringRef newName
)
569 StLock
<Mutex
>_(mMutex
);
571 bool doneCreating
= false;
575 char newNameCString
[MAXPATHLEN
];
576 if ( CFStringGetCString(newName
, newNameCString
, MAXPATHLEN
, kCFStringEncodingUTF8
) ) // make sure it fits in MAXPATHLEN, etc.
578 // Construct the new name...
580 CFMutableStringRef newNameCFStr
= NULL
;
581 newNameCFStr
= CFStringCreateMutable(NULL
, MAXPATHLEN
);
584 CFStringAppendFormat(newNameCFStr
, NULL
, CFSTR("%s%d"), newNameCString
, index
);
585 CFStringAppend(newNameCFStr
, CFSTR(kKeychainSuffix
)); // add .keychain
586 char toUseBuff2
[MAXPATHLEN
];
587 if ( CFStringGetCString(newNameCFStr
, toUseBuff2
, MAXPATHLEN
, kCFStringEncodingUTF8
) ) // make sure it fits in MAXPATHLEN, etc.
590 if ( lstat(toUseBuff2
, &filebuf
) )
592 rename(keychain
, toUseBuff2
);
594 kcList
.push_back(keychain
);
595 remove(kcList
, false);
602 doneCreating
= true; // failure to get c string.
603 CFRelease(newNameCFStr
);
606 doneCreating
= false; // failure to create mutable string.
609 doneCreating
= false; // failure to get the string (i.e. > MAXPATHLEN?)
611 while (!doneCreating
&& index
!= INT_MAX
);
614 #define KEYCHAIN_SYNC_KEY CFSTR("KeychainSyncList")
615 #define KEYCHAIN_SYNC_DOMAIN CFSTR("com.apple.keychainsync")
617 static CFStringRef
MakeExpandedPath (const char* path
)
619 std::string name
= DLDbListCFPref::ExpandTildesInPath (std::string (path
));
620 CFStringRef expanded
= CFStringCreateWithCString (NULL
, name
.c_str (), 0);
624 void StorageManager::removeKeychainFromSyncList (const DLDbIdentifier
&id
)
626 StLock
<Mutex
>_(mMutex
);
628 // make a CFString of our identifier
629 const char* idname
= id
.dbName ();
635 CFRef
<CFStringRef
> idString
= MakeExpandedPath (idname
);
637 // check and see if this keychain is in the keychain syncing list
639 (CFArrayRef
) CFPreferencesCopyValue (KEYCHAIN_SYNC_KEY
,
640 KEYCHAIN_SYNC_DOMAIN
,
641 kCFPreferencesCurrentUser
,
642 kCFPreferencesAnyHost
);
648 // make a mutable copy of the dictionary
649 CFRef
<CFMutableArrayRef
> mtValue
= CFArrayCreateMutableCopy (NULL
, 0, value
);
652 // walk the array, looking for the value
654 CFIndex limit
= CFArrayGetCount (mtValue
.get());
657 for (i
= 0; i
< limit
; ++i
)
659 CFDictionaryRef idx
= (CFDictionaryRef
) CFArrayGetValueAtIndex (mtValue
.get(), i
);
660 CFStringRef v
= (CFStringRef
) CFDictionaryGetValue (idx
, CFSTR("DbName"));
663 return; // something is really wrong if this is taken
666 char* stringBuffer
= NULL
;
667 const char* pathString
= CFStringGetCStringPtr(v
, 0);
670 CFIndex maxLen
= CFStringGetMaximumSizeForEncoding(CFStringGetLength(v
), kCFStringEncodingUTF8
) + 1;
671 stringBuffer
= (char*) malloc(maxLen
);
672 CFStringGetCString(v
, stringBuffer
, maxLen
, kCFStringEncodingUTF8
);
673 pathString
= stringBuffer
;
676 CFStringRef vExpanded
= MakeExpandedPath(pathString
);
677 CFComparisonResult result
= CFStringCompare (vExpanded
, idString
.get(), 0);
678 if (stringBuffer
!= NULL
)
683 CFRelease (vExpanded
);
687 CFArrayRemoveValueAtIndex (mtValue
.get(), i
);
696 CFShow (mtValue
.get());
699 CFPreferencesSetValue (KEYCHAIN_SYNC_KEY
,
701 KEYCHAIN_SYNC_DOMAIN
,
702 kCFPreferencesCurrentUser
,
703 kCFPreferencesAnyHost
);
704 CFPreferencesSynchronize (KEYCHAIN_SYNC_DOMAIN
, kCFPreferencesCurrentUser
, kCFPreferencesAnyHost
);
708 void StorageManager::remove(const KeychainList
&kcsToRemove
, bool deleteDb
)
710 StLock
<Mutex
>_(mMutex
);
712 bool unsetDefault
= false;
713 bool updateList
= (!isAppSandboxed());
717 mSavedList
.revert(true);
718 DLDbIdentifier defaultId
= mSavedList
.defaultDLDbIdentifier();
719 for (KeychainList::const_iterator ix
= kcsToRemove
.begin();
720 ix
!= kcsToRemove
.end(); ++ix
)
722 // Find the keychain object for the given ref
723 Keychain theKeychain
= *ix
;
724 DLDbIdentifier dLDbIdentifier
= theKeychain
->dlDbIdentifier();
726 // Remove it from the saved list
727 mSavedList
.remove(dLDbIdentifier
);
728 if (dLDbIdentifier
== defaultId
)
733 removeKeychainFromSyncList (dLDbIdentifier
);
735 // Now remove it from the cache
736 removeKeychain(dLDbIdentifier
, theKeychain
.get());
741 mSavedList
.defaultDLDbIdentifier(DLDbIdentifier());
748 // Delete the actual databases without holding any locks.
749 for (KeychainList::const_iterator ix
= kcsToRemove
.begin();
750 ix
!= kcsToRemove
.end(); ++ix
)
752 (*ix
)->database()->deleteDb();
757 // Make sure we are not holding mLock when we post these events.
758 KCEventNotifier::PostKeychainEvent(kSecKeychainListChangedEvent
);
762 KCEventNotifier::PostKeychainEvent(kSecDefaultChangedEvent
);
766 StorageManager::getSearchList(KeychainList
&keychainList
)
768 // hold the global lock since we make keychain objects in this function
770 // to do: each of the items in this list must be retained, otherwise mayhem will occur
771 StLock
<Mutex
>_(mMutex
);
774 keychainList
.clear();
778 mSavedList
.revert(false);
779 mCommonList
.revert(false);
781 // Merge mSavedList, mDynamicList and mCommonList
782 DLDbList dLDbList
= mSavedList
.searchList();
783 DLDbList dynamicList
= mDynamicList
.searchList();
784 DLDbList commonList
= mCommonList
.searchList();
786 result
.reserve(dLDbList
.size() + dynamicList
.size() + commonList
.size());
789 for (DLDbList::const_iterator it
= dynamicList
.begin();
790 it
!= dynamicList
.end(); ++it
)
792 Keychain k
= keychain(*it
);
796 for (DLDbList::const_iterator it
= dLDbList
.begin();
797 it
!= dLDbList
.end(); ++it
)
799 Keychain k
= keychain(*it
);
803 for (DLDbList::const_iterator it
= commonList
.begin();
804 it
!= commonList
.end(); ++it
)
806 Keychain k
= keychain(*it
);
811 keychainList
.swap(result
);
815 StorageManager::setSearchList(const KeychainList
&keychainList
)
817 StLock
<Mutex
>_(mMutex
);
819 DLDbList commonList
= mCommonList
.searchList();
821 // Strip out the common list part from the end of the search list.
822 KeychainList::const_iterator it_end
= keychainList
.end();
823 DLDbList::const_reverse_iterator end_common
= commonList
.rend();
824 for (DLDbList::const_reverse_iterator it_common
= commonList
.rbegin(); it_common
!= end_common
; ++it_common
)
826 // Eliminate common entries from the end of the passed in keychainList.
827 if (it_end
== keychainList
.begin())
831 if (!((*it_end
)->dlDbIdentifier() == *it_common
))
838 /* it_end now points one past the last element in keychainList which is not in commonList. */
839 DLDbList searchList
, oldSearchList(mSavedList
.searchList());
840 for (KeychainList::const_iterator it
= keychainList
.begin(); it
!= it_end
; ++it
)
842 searchList
.push_back((*it
)->dlDbIdentifier());
846 // Set the current searchlist to be what was passed in, the old list will be freed
847 // upon exit of this stackframe.
848 mSavedList
.revert(true);
849 mSavedList
.searchList(searchList
);
853 if (!(oldSearchList
== searchList
))
855 // Make sure we are not holding mLock when we post this event.
856 KCEventNotifier::PostKeychainEvent(kSecKeychainListChangedEvent
);
861 StorageManager::getSearchList(SecPreferencesDomain domain
, KeychainList
&keychainList
)
863 StLock
<Mutex
>_(mMutex
);
866 keychainList
.clear();
870 if (domain
== kSecPreferencesDomainDynamic
)
872 convertList(keychainList
, mDynamicList
.searchList());
874 else if (domain
== mDomain
)
876 mSavedList
.revert(false);
877 convertList(keychainList
, mSavedList
.searchList());
881 convertList(keychainList
, DLDbListCFPref(domain
).searchList());
885 void StorageManager::forceUserSearchListReread()
887 mSavedList
.forceUserSearchListReread();
891 StorageManager::setSearchList(SecPreferencesDomain domain
, const KeychainList
&keychainList
)
893 StLock
<Mutex
>_(mMutex
);
895 if (domain
== kSecPreferencesDomainDynamic
)
896 MacOSError::throwMe(errSecInvalidPrefsDomain
);
899 convertList(searchList
, keychainList
);
901 if (domain
== mDomain
)
903 DLDbList
oldSearchList(mSavedList
.searchList());
905 // Set the current searchlist to be what was passed in, the old list will be freed
906 // upon exit of this stackframe.
907 mSavedList
.revert(true);
908 mSavedList
.searchList(searchList
);
912 if (!(oldSearchList
== searchList
))
914 KCEventNotifier::PostKeychainEvent(kSecKeychainListChangedEvent
);
919 DLDbListCFPref(domain
).searchList(searchList
);
924 StorageManager::domain(SecPreferencesDomain domain
)
926 StLock
<Mutex
>_(mMutex
);
928 if (domain
== kSecPreferencesDomainDynamic
)
929 MacOSError::throwMe(errSecInvalidPrefsDomain
);
931 if (domain
== mDomain
)
937 case kSecPreferencesDomainSystem
:
938 secdebug("storagemgr", "switching to system domain"); break;
939 case kSecPreferencesDomainUser
:
940 secdebug("storagemgr", "switching to user domain (uid %d)", getuid()); break;
942 secdebug("storagemgr", "switching to weird prefs domain %d", domain
); break;
947 mSavedList
.set(domain
);
951 StorageManager::optionalSearchList(CFTypeRef keychainOrArray
, KeychainList
&keychainList
)
953 StLock
<Mutex
>_(mMutex
);
955 if (!keychainOrArray
)
956 getSearchList(keychainList
);
959 CFTypeID typeID
= CFGetTypeID(keychainOrArray
);
960 if (typeID
== CFArrayGetTypeID())
961 convertToKeychainList(CFArrayRef(keychainOrArray
), keychainList
);
962 else if (typeID
== gTypes().KeychainImpl
.typeID
)
963 keychainList
.push_back(KeychainImpl::required(SecKeychainRef(keychainOrArray
)));
965 MacOSError::throwMe(errSecParam
);
971 StorageManager::convertToKeychainList(CFArrayRef keychainArray
, KeychainList
&keychainList
)
973 CFIndex count
= CFArrayGetCount(keychainArray
);
977 KeychainList
keychains(count
);
978 for (CFIndex ix
= 0; ix
< count
; ++ix
)
980 keychains
[ix
] = KeychainImpl::required(SecKeychainRef(CFArrayGetValueAtIndex(keychainArray
, ix
)));
983 keychainList
.swap(keychains
);
987 StorageManager::convertFromKeychainList(const KeychainList
&keychainList
)
989 CFRef
<CFMutableArrayRef
> keychainArray(CFArrayCreateMutable(NULL
, keychainList
.size(), &kCFTypeArrayCallBacks
));
991 for (KeychainList::const_iterator ix
= keychainList
.begin(); ix
!= keychainList
.end(); ++ix
)
993 SecKeychainRef keychainRef
= (*ix
)->handle();
994 CFArrayAppendValue(keychainArray
, keychainRef
);
995 CFRelease(keychainRef
);
998 // Counter the CFRelease that CFRef<> is about to do when keychainArray goes out of scope.
999 CFRetain(keychainArray
);
1000 return keychainArray
;
1003 void StorageManager::convertList(DLDbList
&ids
, const KeychainList
&kcs
)
1006 result
.reserve(kcs
.size());
1007 for (KeychainList::const_iterator ix
= kcs
.begin(); ix
!= kcs
.end(); ++ix
)
1009 result
.push_back((*ix
)->dlDbIdentifier());
1014 void StorageManager::convertList(KeychainList
&kcs
, const DLDbList
&ids
)
1016 StLock
<Mutex
>_(mMutex
);
1018 KeychainList result
;
1019 result
.reserve(ids
.size());
1021 for (DLDbList::const_iterator ix
= ids
.begin(); ix
!= ids
.end(); ++ix
)
1022 result
.push_back(keychain(*ix
));
1027 #pragma mark ____ Login Functions ____
1029 void StorageManager::login(AuthorizationRef authRef
, UInt32 nameLength
, const char* name
)
1031 StLock
<Mutex
>_(mMutex
);
1033 AuthorizationItemSet
* info
= NULL
;
1034 OSStatus result
= AuthorizationCopyInfo(authRef
, NULL
, &info
); // get the results of the copy rights call.
1035 Boolean created
= false;
1036 if ( result
== errSecSuccess
&& info
->count
)
1038 // Grab the password from the auth context (info) and create the keychain...
1040 AuthorizationItem
* currItem
= info
->items
;
1041 for (UInt32 index
= 1; index
<= info
->count
; index
++) //@@@plugin bug won't return a specific context.
1043 if (strcmp(currItem
->name
, kAuthorizationEnvironmentPassword
) == 0)
1045 // creates the login keychain with the specified password
1048 login(nameLength
, name
, (UInt32
)currItem
->valueLength
, currItem
->value
);
1060 AuthorizationFreeItemSet(info
);
1063 MacOSError::throwMe(errAuthorizationInternal
);
1066 void StorageManager::login(ConstStringPtr name
, ConstStringPtr password
)
1068 StLock
<Mutex
>_(mMutex
);
1070 if ( name
== NULL
|| password
== NULL
)
1071 MacOSError::throwMe(errSecParam
);
1073 login(name
[0], name
+ 1, password
[0], password
+ 1);
1076 void StorageManager::login(UInt32 nameLength
, const void *name
,
1077 UInt32 passwordLength
, const void *password
)
1079 if (passwordLength
!= 0 && password
== NULL
)
1081 secdebug("KCLogin", "StorageManager::login: invalid argument (NULL password)");
1082 MacOSError::throwMe(errSecParam
);
1085 DLDbIdentifier loginDLDbIdentifier
;
1087 mSavedList
.revert(true);
1088 loginDLDbIdentifier
= mSavedList
.loginDLDbIdentifier();
1091 secdebug("KCLogin", "StorageManager::login: loginDLDbIdentifier is %s", (loginDLDbIdentifier
) ? loginDLDbIdentifier
.dbName() : "<NULL>");
1092 if (!loginDLDbIdentifier
)
1093 MacOSError::throwMe(errSecNoSuchKeychain
);
1096 //***************************************************************
1097 // gather keychain information
1098 //***************************************************************
1101 int uid
= geteuid();
1102 struct passwd
*pw
= getpwuid(uid
);
1104 secdebug("KCLogin", "StorageManager::login: invalid argument (NULL uid)");
1105 MacOSError::throwMe(errSecParam
);
1107 char *userName
= pw
->pw_name
;
1109 // make keychain path strings
1110 std::string keychainPath
= DLDbListCFPref::ExpandTildesInPath(kLoginKeychainPathPrefix
);
1111 std::string shortnameKeychain
= keychainPath
+ userName
;
1112 std::string shortnameDotKeychain
= shortnameKeychain
+ ".keychain";
1113 std::string loginDotKeychain
= keychainPath
+ "login.keychain";
1114 std::string loginRenamed1Keychain
= keychainPath
+ "login_renamed1.keychain";
1116 // check for existence of keychain files
1117 bool shortnameKeychainExists
= false;
1118 bool shortnameDotKeychainExists
= false;
1119 bool loginKeychainExists
= false;
1120 bool loginRenamed1KeychainExists
= false;
1124 stat_result
= ::stat(shortnameKeychain
.c_str(), &st
);
1125 shortnameKeychainExists
= (stat_result
== 0);
1126 stat_result
= ::stat(shortnameDotKeychain
.c_str(), &st
);
1127 shortnameDotKeychainExists
= (stat_result
== 0);
1128 stat_result
= ::stat(loginDotKeychain
.c_str(), &st
);
1129 loginKeychainExists
= (stat_result
== 0);
1130 stat_result
= ::stat(loginRenamed1Keychain
.c_str(), &st
);
1131 loginRenamed1KeychainExists
= (stat_result
== 0);
1134 bool loginUnlocked
= false;
1136 // make the keychain identifiers
1137 CSSM_VERSION version
= {0, 0};
1138 DLDbIdentifier shortnameDLDbIdentifier
= DLDbListCFPref::makeDLDbIdentifier(gGuidAppleCSPDL
, version
, 0, CSSM_SERVICE_CSP
| CSSM_SERVICE_DL
, shortnameKeychain
.c_str(), NULL
);
1139 DLDbIdentifier shortnameDotDLDbIdentifier
= DLDbListCFPref::makeDLDbIdentifier(gGuidAppleCSPDL
, version
, 0, CSSM_SERVICE_CSP
| CSSM_SERVICE_DL
, shortnameDotKeychain
.c_str(), NULL
);
1140 DLDbIdentifier loginRenamed1DLDbIdentifier
= DLDbListCFPref::makeDLDbIdentifier(gGuidAppleCSPDL
, version
, 0, CSSM_SERVICE_CSP
| CSSM_SERVICE_DL
, loginRenamed1Keychain
.c_str(), NULL
);
1142 //***************************************************************
1143 // make file renaming changes first
1144 //***************************************************************
1146 // if "~/Library/Keychains/shortname" exists, we need to migrate it forward;
1147 // either to login.keychain if there isn't already one, otherwise to shortname.keychain
1148 if (shortnameKeychainExists
) {
1149 int rename_stat
= 0;
1150 if (loginKeychainExists
) {
1152 int tmp_result
= ::stat(loginDotKeychain
.c_str(), &st
);
1153 if (tmp_result
== 0) {
1154 if (st
.st_size
<= kEmptyKeychainSizeInBytes
) {
1155 tmp_result
= ::unlink(loginDotKeychain
.c_str());
1156 rename_stat
= ::rename(shortnameKeychain
.c_str(), loginDotKeychain
.c_str());
1157 shortnameKeychainExists
= (rename_stat
!= 0);
1161 if (shortnameKeychainExists
) {
1162 if (loginKeychainExists
&& !shortnameDotKeychainExists
) {
1163 rename_stat
= ::rename(shortnameKeychain
.c_str(), shortnameDotKeychain
.c_str());
1164 shortnameDotKeychainExists
= (rename_stat
== 0);
1165 } else if (!loginKeychainExists
) {
1166 rename_stat
= ::rename(shortnameKeychain
.c_str(), loginDotKeychain
.c_str());
1167 loginKeychainExists
= (rename_stat
== 0);
1169 // we have all 3 keychains: login.keychain, shortname, and shortname.keychain.
1170 // on Leopard we never want a shortname keychain, so we must move it aside.
1171 char pathbuf
[MAXPATHLEN
];
1172 std::string shortnameRenamedXXXKeychain
= keychainPath
;
1173 shortnameRenamedXXXKeychain
+= userName
;
1174 shortnameRenamedXXXKeychain
+= "_renamed_XXX.keychain";
1175 ::strlcpy(pathbuf
, shortnameRenamedXXXKeychain
.c_str(), sizeof(pathbuf
));
1176 ::mkstemps(pathbuf
, 9); // 9 == strlen(".keychain")
1177 rename_stat
= ::rename(shortnameKeychain
.c_str(), pathbuf
);
1178 shortnameKeychainExists
= (rename_stat
!= 0);
1181 if (rename_stat
!= 0) {
1182 MacOSError::throwMe(errno
);
1186 //***************************************************************
1187 // handle special case where user previously reset the keychain
1188 //***************************************************************
1189 // Since 9A581, we have changed the definition of kKeychainRenamedSuffix from "_renamed" to "_renamed_".
1190 // Therefore, if "login_renamed1.keychain" exists and there is no plist, the user may have run into a
1191 // prior upgrade issue and clicked Reset. If we can successfully unlock login_renamed1.keychain with the
1192 // supplied password, then we will attempt to rename it to login.keychain if that file is empty, or with
1193 // "shortname.keychain" if it is not.
1195 if (loginRenamed1KeychainExists
&& (!loginKeychainExists
||
1196 (mSavedList
.searchList().size() == 1 && mSavedList
.member(loginDLDbIdentifier
)) )) {
1199 Keychain
loginRenamed1KC(keychain(loginRenamed1DLDbIdentifier
));
1200 secdebug("KCLogin", "Attempting to unlock %s with %d-character password",
1201 (loginRenamed1KC
) ? loginRenamed1KC
->name() : "<NULL>", (unsigned int)passwordLength
);
1202 loginRenamed1KC
->unlock(CssmData(const_cast<void *>(password
), passwordLength
));
1203 // if we get here, we unlocked it
1204 if (loginKeychainExists
) {
1206 int tmp_result
= ::stat(loginDotKeychain
.c_str(), &st
);
1207 if (tmp_result
== 0) {
1208 if (st
.st_size
<= kEmptyKeychainSizeInBytes
) {
1209 tmp_result
= ::unlink(loginDotKeychain
.c_str());
1210 tmp_result
= ::rename(loginRenamed1Keychain
.c_str(), loginDotKeychain
.c_str());
1211 } else if (!shortnameDotKeychainExists
) {
1212 tmp_result
= ::rename(loginRenamed1Keychain
.c_str(), shortnameDotKeychain
.c_str());
1213 shortnameDotKeychainExists
= (tmp_result
== 0);
1215 throw 1; // can't do anything with it except move it out of the way
1219 int tmp_result
= ::rename(loginRenamed1Keychain
.c_str(), loginDotKeychain
.c_str());
1220 loginKeychainExists
= (tmp_result
== 0);
1225 // we failed to unlock the login_renamed1.keychain file with the login password.
1226 // move it aside so we don't try to deal with it again.
1227 char pathbuf
[MAXPATHLEN
];
1228 std::string loginRenamedXXXKeychain
= keychainPath
;
1229 loginRenamedXXXKeychain
+= "login_renamed_XXX.keychain";
1230 ::strlcpy(pathbuf
, loginRenamedXXXKeychain
.c_str(), sizeof(pathbuf
));
1231 ::mkstemps(pathbuf
, 9); // 9 == strlen(".keychain")
1232 ::rename(loginRenamed1Keychain
.c_str(), pathbuf
);
1236 // if login.keychain does not exist at this point, create it
1237 if (!loginKeychainExists
) {
1238 Keychain
theKeychain(keychain(loginDLDbIdentifier
));
1239 secdebug("KCLogin", "Creating login keychain %s", (loginDLDbIdentifier
) ? loginDLDbIdentifier
.dbName() : "<NULL>");
1240 theKeychain
->create(passwordLength
, password
);
1241 secdebug("KCLogin", "Login keychain created successfully");
1242 loginKeychainExists
= true;
1243 // Set the prefs for this new login keychain.
1244 loginKeychain(theKeychain
);
1245 // Login Keychain does not lock on sleep nor lock after timeout by default.
1246 theKeychain
->setSettings(INT_MAX
, false);
1247 loginUnlocked
= true;
1248 mSavedList
.revert(true);
1251 //***************************************************************
1252 // make plist changes after files have been renamed or created
1253 //***************************************************************
1255 // if the shortname keychain exists in the search list, either rename or remove the entry
1256 if (mSavedList
.member(shortnameDLDbIdentifier
)) {
1257 if (shortnameDotKeychainExists
&& !mSavedList
.member(shortnameDotDLDbIdentifier
)) {
1258 // change shortname to shortname.keychain (login.keychain will be added later if not present)
1259 secdebug("KCLogin", "Renaming %s to %s in keychain search list",
1260 (shortnameDLDbIdentifier
) ? shortnameDLDbIdentifier
.dbName() : "<NULL>",
1261 (shortnameDotDLDbIdentifier
) ? shortnameDotDLDbIdentifier
.dbName() : "<NULL>");
1262 mSavedList
.rename(shortnameDLDbIdentifier
, shortnameDotDLDbIdentifier
);
1263 } else if (!mSavedList
.member(loginDLDbIdentifier
)) {
1264 // change shortname to login.keychain
1265 secdebug("KCLogin", "Renaming %s to %s in keychain search list",
1266 (shortnameDLDbIdentifier
) ? shortnameDLDbIdentifier
.dbName() : "<NULL>",
1267 (loginDLDbIdentifier
) ? loginDLDbIdentifier
.dbName() : "<NULL>");
1268 mSavedList
.rename(shortnameDLDbIdentifier
, loginDLDbIdentifier
);
1270 // already have login.keychain in list, and renaming to shortname.keychain isn't an option,
1271 // so just remove the entry
1272 secdebug("KCLogin", "Removing %s from keychain search list", (shortnameDLDbIdentifier
) ? shortnameDLDbIdentifier
.dbName() : "<NULL>");
1273 mSavedList
.remove(shortnameDLDbIdentifier
);
1276 // note: save() will cause the plist to be unlinked if the only remaining entry is for login.keychain
1278 mSavedList
.revert(true);
1281 // make sure that login.keychain is in the search list
1282 if (!mSavedList
.member(loginDLDbIdentifier
)) {
1283 secdebug("KCLogin", "Adding %s to keychain search list", (loginDLDbIdentifier
) ? loginDLDbIdentifier
.dbName() : "<NULL>");
1284 mSavedList
.add(loginDLDbIdentifier
);
1286 mSavedList
.revert(true);
1289 // if we have a shortname.keychain, always include it in the plist (after login.keychain)
1290 if (shortnameDotKeychainExists
&& !mSavedList
.member(shortnameDotDLDbIdentifier
)) {
1291 mSavedList
.add(shortnameDotDLDbIdentifier
);
1293 mSavedList
.revert(true);
1296 // make sure that the default keychain is in the search list; if not, reset the default to login.keychain
1297 if (!mSavedList
.member(mSavedList
.defaultDLDbIdentifier())) {
1298 secdebug("KCLogin", "Changing default keychain to %s", (loginDLDbIdentifier
) ? loginDLDbIdentifier
.dbName() : "<NULL>");
1299 mSavedList
.defaultDLDbIdentifier(loginDLDbIdentifier
);
1301 mSavedList
.revert(true);
1304 //***************************************************************
1305 // auto-unlock the login keychain(s)
1306 //***************************************************************
1307 // all our preflight fixups are finally done, so we can now attempt to unlock the login keychain
1309 OSStatus loginResult
= errSecSuccess
;
1310 if (!loginUnlocked
) {
1313 Keychain
theKeychain(keychain(loginDLDbIdentifier
));
1314 secdebug("KCLogin", "Attempting to unlock login keychain \"%s\" with %d-character password",
1315 (theKeychain
) ? theKeychain
->name() : "<NULL>", (unsigned int)passwordLength
);
1316 theKeychain
->unlock(CssmData(const_cast<void *>(password
), passwordLength
));
1317 loginUnlocked
= true;
1319 catch(const CssmError
&e
)
1321 loginResult
= e
.osStatus(); // save this result
1325 // if "shortname.keychain" exists and is in the search list, attempt to auto-unlock it with the same password
1326 if (shortnameDotKeychainExists
&& mSavedList
.member(shortnameDotDLDbIdentifier
)) {
1329 Keychain
shortnameDotKC(keychain(shortnameDotDLDbIdentifier
));
1330 secdebug("KCLogin", "Attempting to unlock %s",
1331 (shortnameDotKC
) ? shortnameDotKC
->name() : "<NULL>");
1332 shortnameDotKC
->unlock(CssmData(const_cast<void *>(password
), passwordLength
));
1334 catch(const CssmError
&e
)
1336 // ignore; failure to unlock this keychain is not considered an error
1340 if (loginResult
!= errSecSuccess
) {
1341 MacOSError::throwMe(loginResult
);
1345 void StorageManager::stashLogin()
1347 OSStatus loginResult
= errSecSuccess
;
1349 DLDbIdentifier loginDLDbIdentifier
;
1351 mSavedList
.revert(true);
1352 loginDLDbIdentifier
= mSavedList
.loginDLDbIdentifier();
1355 secdebug("KCLogin", "StorageManager::stash: loginDLDbIdentifier is %s", (loginDLDbIdentifier
) ? loginDLDbIdentifier
.dbName() : "<NULL>");
1356 if (!loginDLDbIdentifier
)
1357 MacOSError::throwMe(errSecNoSuchKeychain
);
1362 Keychain
theKeychain(keychain(loginDLDbIdentifier
));
1363 secdebug("KCLogin", "Attempting to use stash for login keychain \"%s\"",
1364 (theKeychain
) ? theKeychain
->name() : "<NULL>");
1365 theKeychain
->stashCheck();
1367 catch(const CssmError
&e
)
1369 loginResult
= e
.osStatus(); // save this result
1373 if (loginResult
!= errSecSuccess
) {
1374 MacOSError::throwMe(loginResult
);
1378 void StorageManager::stashKeychain()
1380 OSStatus loginResult
= errSecSuccess
;
1382 DLDbIdentifier loginDLDbIdentifier
;
1384 mSavedList
.revert(true);
1385 loginDLDbIdentifier
= mSavedList
.loginDLDbIdentifier();
1388 secdebug("KCLogin", "StorageManager::stash: loginDLDbIdentifier is %s", (loginDLDbIdentifier
) ? loginDLDbIdentifier
.dbName() : "<NULL>");
1389 if (!loginDLDbIdentifier
)
1390 MacOSError::throwMe(errSecNoSuchKeychain
);
1394 Keychain
theKeychain(keychain(loginDLDbIdentifier
));
1395 secdebug("KCLogin", "Attempting to stash login keychain \"%s\"",
1396 (theKeychain
) ? theKeychain
->name() : "<NULL>");
1397 theKeychain
->stash();
1399 catch(const CssmError
&e
)
1401 loginResult
= e
.osStatus(); // save this result
1405 if (loginResult
!= errSecSuccess
) {
1406 MacOSError::throwMe(loginResult
);
1410 void StorageManager::logout()
1412 // nothing left to do here
1415 void StorageManager::changeLoginPassword(ConstStringPtr oldPassword
, ConstStringPtr newPassword
)
1417 StLock
<Mutex
>_(mMutex
);
1419 loginKeychain()->changePassphrase(oldPassword
, newPassword
);
1420 secdebug("KClogin", "Changed login keychain password successfully");
1424 void StorageManager::changeLoginPassword(UInt32 oldPasswordLength
, const void *oldPassword
, UInt32 newPasswordLength
, const void *newPassword
)
1426 StLock
<Mutex
>_(mMutex
);
1428 loginKeychain()->changePassphrase(oldPasswordLength
, oldPassword
, newPasswordLength
, newPassword
);
1429 secdebug("KClogin", "Changed login keychain password successfully");
1432 // Clear out the keychain search list and rename the existing login.keychain.
1434 void StorageManager::resetKeychain(Boolean resetSearchList
)
1436 StLock
<Mutex
>_(mMutex
);
1438 // Clear the keychain search list.
1441 if ( resetSearchList
)
1443 StorageManager::KeychainList keychainList
;
1444 setSearchList(keychainList
);
1446 // Get a reference to the existing login keychain...
1447 // If we don't have one, we throw (not requiring a rename).
1449 Keychain keychain
= loginKeychain();
1451 // Rename the existing login.keychain (i.e. put it aside).
1453 CFMutableStringRef newName
= NULL
;
1454 newName
= CFStringCreateMutable(NULL
, 0);
1455 CFStringRef currName
= NULL
;
1456 currName
= CFStringCreateWithCString(NULL
, keychain
->name(), kCFStringEncodingUTF8
);
1457 if ( newName
&& currName
)
1459 CFStringAppend(newName
, currName
);
1460 CFStringRef kcSuffix
= CFSTR(kKeychainSuffix
);
1461 if ( CFStringHasSuffix(newName
, kcSuffix
) ) // remove the .keychain extension
1463 CFRange suffixRange
= CFStringFind(newName
, kcSuffix
, 0);
1464 CFStringFindAndReplace(newName
, kcSuffix
, CFSTR(""), suffixRange
, 0);
1466 CFStringAppend(newName
, CFSTR(kKeychainRenamedSuffix
)); // add "_renamed_"
1469 renameUnique(keychain
, newName
);
1473 // we need to release 'newName' & 'currName'
1475 } // else, let the login call report a duplicate
1479 CFRelease(currName
);
1483 // We either don't have a login keychain, or there was a
1484 // failure to rename the existing one.
1488 #pragma mark ____ File Related ____
1490 Keychain
StorageManager::make(const char *pathName
)
1492 return make(pathName
, true);
1495 Keychain
StorageManager::make(const char *pathName
, bool add
)
1497 StLock
<Mutex
>_(mMutex
);
1499 string fullPathName
;
1500 if ( pathName
[0] == '/' )
1501 fullPathName
= pathName
;
1504 // Get Home directory from environment.
1507 case kSecPreferencesDomainUser
:
1509 const char *homeDir
= getenv("HOME");
1510 if (homeDir
== NULL
)
1512 // If $HOME is unset get the current user's home directory
1513 // from the passwd file.
1514 uid_t uid
= geteuid();
1515 if (!uid
) uid
= getuid();
1516 struct passwd
*pw
= getpwuid(uid
);
1518 MacOSError::throwMe(errSecParam
);
1519 homeDir
= pw
->pw_dir
;
1521 fullPathName
= homeDir
;
1524 case kSecPreferencesDomainSystem
:
1528 assert(false); // invalid domain for this
1531 fullPathName
+= "/Library/Keychains/";
1532 fullPathName
+= pathName
;
1535 const CSSM_NET_ADDRESS
*DbLocation
= NULL
; // NULL for keychains
1536 const CSSM_VERSION
*version
= NULL
;
1537 uint32 subserviceId
= 0;
1538 CSSM_SERVICE_TYPE subserviceType
= CSSM_SERVICE_DL
| CSSM_SERVICE_CSP
;
1539 const CssmSubserviceUid
ssuid(gGuidAppleCSPDL
, version
,
1540 subserviceId
, subserviceType
);
1541 DLDbIdentifier
dLDbIdentifier(ssuid
, fullPathName
.c_str(), DbLocation
);
1542 return makeKeychain(dLDbIdentifier
, add
);
1545 Keychain
StorageManager::makeLoginAuthUI(const Item
*item
)
1547 StLock
<Mutex
>_(mMutex
);
1549 // Create a login/default keychain for the user using UI.
1550 // The user can cancel out of the operation, or create a new login keychain.
1551 // If auto-login is turned off, the user will be asked for their login password.
1553 OSStatus result
= errSecSuccess
;
1554 Keychain keychain
; // We return this keychain.
1556 // Set up the Auth ref to bring up UI.
1558 AuthorizationItem
*currItem
, *authEnvirItemArrayPtr
= NULL
;
1559 AuthorizationRef authRef
= NULL
;
1562 result
= AuthorizationCreate(NULL
, NULL
, kAuthorizationFlagDefaults
, &authRef
);
1564 MacOSError::throwMe(result
);
1566 AuthorizationEnvironment envir
;
1567 envir
.count
= 6; // up to 6 hints can be used.
1568 authEnvirItemArrayPtr
= (AuthorizationItem
*)malloc(sizeof(AuthorizationItem
) * envir
.count
);
1569 if ( !authEnvirItemArrayPtr
)
1570 MacOSError::throwMe(errAuthorizationInternal
);
1572 currItem
= envir
.items
= authEnvirItemArrayPtr
;
1575 // 1st Hint (optional): The keychain item's account attribute string.
1576 // When item is specified, we assume an 'add' operation is being attempted.
1579 SecKeychainAttribute attr
= { kSecAccountItemAttr
, 255, &buff
};
1584 (*item
)->getAttribute(attr
, &actLen
);
1588 actLen
= 0; // This item didn't have the account attribute, so don't display one in the UI.
1591 currItem
->name
= AGENT_HINT_ATTR_NAME
; // name str that identifies this hint as attr name
1592 if ( actLen
) // Fill in the hint if we have an account attr
1594 if ( actLen
>= sizeof(buff
) )
1595 buff
[sizeof(buff
)-1] = 0;
1598 currItem
->valueLength
= strlen(buff
)+1;
1599 currItem
->value
= buff
;
1603 currItem
->valueLength
= 0;
1604 currItem
->value
= NULL
;
1606 currItem
->flags
= 0;
1609 // 2nd Hint (optional): The item's keychain full path.
1612 char* currDefaultName
= NULL
;
1615 currDefaultName
= (char*)defaultKeychain()->name(); // Use the name if we have it.
1616 currItem
->name
= AGENT_HINT_LOGIN_KC_NAME
; // Name str that identifies this hint as kc path
1617 currItem
->valueLength
= (currDefaultName
) ? strlen(currDefaultName
) : 0;
1618 currItem
->value
= (currDefaultName
) ? (void*)currDefaultName
: (void*)"";
1619 currItem
->flags
= 0;
1628 // 3rd Hint (required): check if curr default keychain is unavailable.
1629 // This is determined by the parent not existing.
1631 currItem
->name
= AGENT_HINT_LOGIN_KC_EXISTS_IN_KC_FOLDER
;
1632 Boolean loginUnavail
= false;
1635 Keychain defaultKC
= defaultKeychain();
1636 if ( !defaultKC
->exists() )
1637 loginUnavail
= true;
1639 catch(...) // login.keychain not present
1642 currItem
->valueLength
= sizeof(Boolean
);
1643 currItem
->value
= (void*)&loginUnavail
;
1644 currItem
->flags
= 0;
1647 // 4th Hint (required): userName
1650 currItem
->name
= AGENT_HINT_LOGIN_KC_USER_NAME
;
1651 char* uName
= getenv("USER");
1652 string userName
= uName
? uName
: "";
1653 if ( userName
.length() == 0 )
1655 uid_t uid
= geteuid();
1656 if (!uid
) uid
= getuid();
1657 struct passwd
*pw
= getpwuid(uid
); // fallback case...
1659 userName
= pw
->pw_name
;
1662 if ( userName
.length() == 0 ) // did we ultimately get one?
1663 MacOSError::throwMe(errAuthorizationInternal
);
1665 currItem
->value
= (void*)userName
.c_str();
1666 currItem
->valueLength
= userName
.length();
1667 currItem
->flags
= 0;
1670 // 5th Hint (required): flags if user has more than 1 keychain (used for a later warning when reset to default).
1673 currItem
->name
= AGENT_HINT_LOGIN_KC_USER_HAS_OTHER_KCS_STR
;
1674 Boolean moreThanOneKCExists
= false;
1676 // if item is NULL, then this is a user-initiated full reset
1677 if (item
&& mSavedList
.searchList().size() > 1)
1678 moreThanOneKCExists
= true;
1680 currItem
->value
= &moreThanOneKCExists
;
1681 currItem
->valueLength
= sizeof(Boolean
);
1682 currItem
->flags
= 0;
1685 // 6th Hint (required): If no item is involved, this is a user-initiated full reset.
1686 // We want to suppress the "do you want to reset to defaults?" panel in this case.
1689 currItem
->name
= AGENT_HINT_LOGIN_KC_SUPPRESS_RESET_PANEL
;
1690 Boolean suppressResetPanel
= (item
== NULL
) ? TRUE
: FALSE
;
1691 currItem
->valueLength
= sizeof(Boolean
);
1692 currItem
->value
= (void*)&suppressResetPanel
;
1693 currItem
->flags
= 0;
1696 // Set up the auth rights and make the auth call.
1698 AuthorizationItem authItem
= { LOGIN_KC_CREATION_RIGHT
, 0 , NULL
, 0 };
1699 AuthorizationRights rights
= { 1, &authItem
};
1700 AuthorizationFlags flags
= kAuthorizationFlagDefaults
| kAuthorizationFlagInteractionAllowed
| kAuthorizationFlagExtendRights
;
1701 result
= AuthorizationCopyRights(authRef
, &rights
, &envir
, flags
, NULL
);
1703 MacOSError::throwMe(result
);
1706 resetKeychain(true); // Clears the plist, moves aside existing login.keychain
1708 catch (...) // can throw if no existing login.keychain is found
1711 login(authRef
, (UInt32
)userName
.length(), userName
.c_str()); // Create login.keychain
1712 keychain
= loginKeychain(); // Get newly-created login keychain
1713 defaultKeychain(keychain
); // Set it to be the default
1715 free(authEnvirItemArrayPtr
);
1716 AuthorizationFree(authRef
, kAuthorizationFlagDefaults
);
1721 // clean up allocations, then rethrow error
1722 if ( authEnvirItemArrayPtr
)
1723 free(authEnvirItemArrayPtr
);
1725 AuthorizationFree(authRef
, kAuthorizationFlagDefaults
);
1732 Keychain
StorageManager::defaultKeychainUI(Item
&item
)
1734 StLock
<Mutex
>_(mMutex
);
1736 Keychain returnedKeychain
;
1739 returnedKeychain
= defaultKeychain(); // If we have one, return it.
1740 if ( returnedKeychain
->exists() )
1741 return returnedKeychain
;
1743 catch(...) // We could have one, but it isn't available (i.e. on a un-mounted volume).
1746 if ( globals().getUserInteractionAllowed() )
1748 returnedKeychain
= makeLoginAuthUI(&item
); // If no Keychains is present, one will be created.
1749 if ( !returnedKeychain
)
1750 MacOSError::throwMe(errSecInvalidKeychain
); // Something went wrong...
1753 MacOSError::throwMe(errSecInteractionNotAllowed
); // If UI isn't allowed, return an error.
1755 return returnedKeychain
;
1759 StorageManager::addToDomainList(SecPreferencesDomain domain
,
1760 const char* dbName
, const CSSM_GUID
&guid
, uint32 subServiceType
)
1762 StLock
<Mutex
>_(mMutex
);
1764 if (domain
== kSecPreferencesDomainDynamic
)
1765 MacOSError::throwMe(errSecInvalidPrefsDomain
);
1767 // make the identifier
1768 CSSM_VERSION version
= {0, 0};
1769 DLDbIdentifier id
= DLDbListCFPref::makeDLDbIdentifier (guid
, version
, 0,
1770 subServiceType
, dbName
, NULL
);
1772 if (domain
== mDomain
)
1774 // manipulate the user's list
1776 mSavedList
.revert(true);
1781 KCEventNotifier::PostKeychainEvent(kSecKeychainListChangedEvent
);
1785 // manipulate the other list
1786 DLDbListCFPref(domain
).add(id
);
1791 StorageManager::isInDomainList(SecPreferencesDomain domain
,
1792 const char* dbName
, const CSSM_GUID
&guid
, uint32 subServiceType
)
1794 StLock
<Mutex
>_(mMutex
);
1796 if (domain
== kSecPreferencesDomainDynamic
)
1797 MacOSError::throwMe(errSecInvalidPrefsDomain
);
1799 CSSM_VERSION version
= {0, 0};
1800 DLDbIdentifier id
= DLDbListCFPref::makeDLDbIdentifier (guid
, version
, 0,
1801 subServiceType
, dbName
, NULL
);
1803 // determine the list to search
1805 if (domain
== mDomain
)
1807 result
= mSavedList
.member(id
);
1811 result
= DLDbListCFPref(domain
).member(id
);
1817 MacOSError::throwMe(errSecNoSuchKeychain
);
1822 StorageManager::removeFromDomainList(SecPreferencesDomain domain
,
1823 const char* dbName
, const CSSM_GUID
&guid
, uint32 subServiceType
)
1825 StLock
<Mutex
>_(mMutex
);
1827 if (domain
== kSecPreferencesDomainDynamic
)
1828 MacOSError::throwMe(errSecInvalidPrefsDomain
);
1830 // make the identifier
1831 CSSM_VERSION version
= {0, 0};
1832 DLDbIdentifier id
= DLDbListCFPref::makeDLDbIdentifier (guid
, version
, 0,
1833 subServiceType
, dbName
, NULL
);
1835 if (domain
== mDomain
)
1837 // manipulate the user's list
1839 mSavedList
.revert(true);
1840 mSavedList
.remove(id
);
1844 KCEventNotifier::PostKeychainEvent(kSecKeychainListChangedEvent
);
1848 // manipulate the other list
1849 DLDbListCFPref(domain
).remove(id
);
1854 StorageManager::keychainOwnerPermissionsValidForDomain(const char* path
, SecPreferencesDomain domain
)
1858 const char* sysPrefDir
= "/Library/Preferences";
1859 const char* errMsg
= "Will not set default";
1860 char* mustOwnDir
= NULL
;
1861 struct passwd
* pw
= NULL
;
1864 uid_t uid
= geteuid();
1865 if (!uid
) uid
= getuid();
1867 // our (e)uid must own the appropriate preferences or home directory
1868 // for the specified preference domain whose default we will be modifying
1870 case kSecPreferencesDomainUser
:
1871 mustOwnDir
= getenv("HOME");
1872 if (mustOwnDir
== NULL
) {
1874 if (!pw
) return false;
1875 mustOwnDir
= pw
->pw_dir
;
1878 case kSecPreferencesDomainSystem
:
1879 mustOwnDir
= (char*)sysPrefDir
;
1881 case kSecPreferencesDomainCommon
:
1882 mustOwnDir
= (char*)sysPrefDir
;
1888 if (mustOwnDir
!= NULL
) {
1890 if ( (stat(mustOwnDir
, &dsb
) != 0) || (dsb
.st_uid
!= uid
) ) {
1891 fprintf(stderr
, "%s: UID=%d does not own directory %s\n", errMsg
, (int)uid
, mustOwnDir
);
1892 mustOwnDir
= NULL
; // will return below after calling endpwent()
1899 if (mustOwnDir
== NULL
)
1902 // check that file actually exists
1903 if (stat(path
, &sb
) != 0) {
1904 fprintf(stderr
, "%s: file %s does not exist\n", errMsg
, path
);
1909 if (sb
.st_flags
& (SF_IMMUTABLE
| UF_IMMUTABLE
)) {
1910 fprintf(stderr
, "%s: file %s is immutable\n", errMsg
, path
);
1915 if (sb
.st_uid
!= uid
) {
1916 fprintf(stderr
, "%s: file %s is owned by UID=%d, but we have UID=%d\n",
1917 errMsg
, path
, (int)sb
.st_uid
, (int)uid
);
1923 perms
|= 0600; // must have owner read/write permission set
1924 if (sb
.st_mode
!= perms
) {
1925 fprintf(stderr
, "%s: file %s does not have the expected permissions\n", errMsg
, path
);
1929 // user owns file and can read/write it