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@
29 #include "KCEventNotifier.h"
30 #include "Keychains.h"
35 #include <security_cdsa_utilities/Schema.h>
36 #include <security_cdsa_client/keychainacl.h>
37 #include <security_cdsa_utilities/cssmacl.h>
38 #include <security_cdsa_utilities/cssmdb.h>
39 #include <security_utilities/trackingallocator.h>
40 #include <security_utilities/FileLockTransaction.h>
41 #include <security_keychain/SecCFTypes.h>
42 #include <securityd_client/ssblob.h>
43 #include <Security/TrustSettingsSchema.h>
45 #include "SecKeychainPriv.h"
47 #include <Security/SecKeychainItemPriv.h>
48 #include <CoreFoundation/CoreFoundation.h>
49 #include "DLDbListCFPref.h"
52 #include <sys/param.h>
55 #include <sys/socket.h>
57 #include <sys/types.h>
60 static dispatch_once_t SecKeychainSystemKeychainChecked
;
62 OSStatus
SecKeychainSystemKeychainCheckWouldDeadlock()
64 dispatch_once(&SecKeychainSystemKeychainChecked
, ^{});
68 using namespace KeychainCore
;
69 using namespace CssmClient
;
72 typedef struct EventItem
74 SecKeychainEvent kcEvent
;
78 typedef std::list
<EventItem
> EventBufferSuper
;
79 class EventBuffer
: public EventBufferSuper
83 virtual ~EventBuffer ();
87 EventBuffer::~EventBuffer ()
96 KeychainSchemaImpl::KeychainSchemaImpl(const Db
&db
) : mMutex(Mutex::recursive
)
98 DbCursor
relations(db
);
99 relations
->recordType(CSSM_DL_DB_SCHEMA_INFO
);
100 DbAttributes
relationRecord(db
, 1);
101 relationRecord
.add(Schema::RelationID
);
102 DbUniqueRecord
outerUniqueId(db
);
104 while (relations
->next(&relationRecord
, NULL
, outerUniqueId
))
106 DbUniqueRecord
uniqueId(db
);
108 uint32 relationID
= relationRecord
.at(0);
109 if (CSSM_DB_RECORDTYPE_SCHEMA_START
<= relationID
110 && relationID
< CSSM_DB_RECORDTYPE_SCHEMA_END
)
113 // Create a cursor on the SCHEMA_ATTRIBUTES table for records with
114 // RelationID == relationID
115 DbCursor
attributes(db
);
116 attributes
->recordType(CSSM_DL_DB_SCHEMA_ATTRIBUTES
);
117 attributes
->add(CSSM_DB_EQUAL
, Schema::RelationID
, relationID
);
119 // Set up a record for retriving the SCHEMA_ATTRIBUTES
120 DbAttributes
attributeRecord(db
, 2);
121 attributeRecord
.add(Schema::AttributeFormat
);
122 attributeRecord
.add(Schema::AttributeID
);
124 RelationInfoMap
&rim
= mDatabaseInfoMap
[relationID
];
125 while (attributes
->next(&attributeRecord
, NULL
, uniqueId
))
126 rim
[attributeRecord
.at(1)] = attributeRecord
.at(0);
128 // Create a cursor on the CSSM_DL_DB_SCHEMA_INDEXES table for records
129 // with RelationID == relationID
130 DbCursor
indexes(db
);
131 indexes
->recordType(CSSM_DL_DB_SCHEMA_INDEXES
);
132 indexes
->conjunctive(CSSM_DB_AND
);
133 indexes
->add(CSSM_DB_EQUAL
, Schema::RelationID
, relationID
);
134 indexes
->add(CSSM_DB_EQUAL
, Schema::IndexType
,
135 uint32(CSSM_DB_INDEX_UNIQUE
));
137 // Set up a record for retriving the SCHEMA_INDEXES
138 DbAttributes
indexRecord(db
, 1);
139 indexRecord
.add(Schema::AttributeID
);
141 CssmAutoDbRecordAttributeInfo
&infos
=
142 *new CssmAutoDbRecordAttributeInfo();
144 insert(PrimaryKeyInfoMap::value_type(relationID
, &infos
));
145 infos
.DataRecordType
= relationID
;
146 while (indexes
->next(&indexRecord
, NULL
, uniqueId
))
148 CssmDbAttributeInfo
&info
= infos
.add();
149 info
.AttributeNameFormat
= CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER
;
150 info
.Label
.AttributeID
= indexRecord
.at(0);
151 // @@@ Might insert bogus value if DB is corrupt
152 info
.AttributeFormat
= rim
[info
.Label
.AttributeID
];
157 KeychainSchemaImpl::~KeychainSchemaImpl()
161 map
<CSSM_DB_RECORDTYPE
, CssmAutoDbRecordAttributeInfo
*>::iterator it
= mPrimaryKeyInfoMap
.begin();
162 while (it
!= mPrimaryKeyInfoMap
.end())
167 // for_each_map_delete(mPrimaryKeyInfoMap.begin(), mPrimaryKeyInfoMap.end());
174 const KeychainSchemaImpl::RelationInfoMap
&
175 KeychainSchemaImpl::relationInfoMapFor(CSSM_DB_RECORDTYPE recordType
) const
177 DatabaseInfoMap::const_iterator dit
= mDatabaseInfoMap
.find(recordType
);
178 if (dit
== mDatabaseInfoMap
.end())
179 MacOSError::throwMe(errSecNoSuchClass
);
183 bool KeychainSchemaImpl::hasRecordType (CSSM_DB_RECORDTYPE recordType
) const
185 DatabaseInfoMap::const_iterator it
= mDatabaseInfoMap
.find(recordType
);
186 return it
!= mDatabaseInfoMap
.end();
190 KeychainSchemaImpl::hasAttribute(CSSM_DB_RECORDTYPE recordType
, uint32 attributeId
) const
194 const RelationInfoMap
&rmap
= relationInfoMapFor(recordType
);
195 RelationInfoMap::const_iterator rit
= rmap
.find(attributeId
);
196 return rit
!= rmap
.end();
198 catch (MacOSError result
)
200 if (result
.osStatus () == errSecNoSuchClass
)
211 CSSM_DB_ATTRIBUTE_FORMAT
212 KeychainSchemaImpl::attributeFormatFor(CSSM_DB_RECORDTYPE recordType
, uint32 attributeId
) const
214 const RelationInfoMap
&rmap
= relationInfoMapFor(recordType
);
215 RelationInfoMap::const_iterator rit
= rmap
.find(attributeId
);
216 if (rit
== rmap
.end())
217 MacOSError::throwMe(errSecNoSuchAttr
);
223 KeychainSchemaImpl::attributeInfoFor(CSSM_DB_RECORDTYPE recordType
, uint32 attributeId
) const
225 CSSM_DB_ATTRIBUTE_INFO info
;
226 info
.AttributeFormat
= attributeFormatFor(recordType
, attributeId
);
227 info
.AttributeNameFormat
= CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER
;
228 info
.Label
.AttributeID
= attributeId
;
234 KeychainSchemaImpl::getAttributeInfoForRecordType(CSSM_DB_RECORDTYPE recordType
, SecKeychainAttributeInfo
**Info
) const
236 const RelationInfoMap
&rmap
= relationInfoMapFor(recordType
);
238 SecKeychainAttributeInfo
*theList
=reinterpret_cast<SecKeychainAttributeInfo
*>(malloc(sizeof(SecKeychainAttributeInfo
)));
240 size_t capacity
=rmap
.size();
241 UInt32
*tagBuf
=reinterpret_cast<UInt32
*>(malloc(capacity
*sizeof(UInt32
)));
242 UInt32
*formatBuf
=reinterpret_cast<UInt32
*>(malloc(capacity
*sizeof(UInt32
)));
246 for (RelationInfoMap::const_iterator rit
= rmap
.begin(); rit
!= rmap
.end(); ++rit
)
251 if (capacity
<= i
) capacity
= i
+ 1;
252 tagBuf
=reinterpret_cast<UInt32
*>(realloc(tagBuf
, (capacity
*sizeof(UInt32
))));
253 formatBuf
=reinterpret_cast<UInt32
*>(realloc(tagBuf
, (capacity
*sizeof(UInt32
))));
255 tagBuf
[i
]=rit
->first
;
256 formatBuf
[i
++]=rit
->second
;
261 theList
->format
=formatBuf
;
266 const CssmAutoDbRecordAttributeInfo
&
267 KeychainSchemaImpl::primaryKeyInfosFor(CSSM_DB_RECORDTYPE recordType
) const
269 PrimaryKeyInfoMap::const_iterator it
;
270 it
= mPrimaryKeyInfoMap
.find(recordType
);
272 if (it
== mPrimaryKeyInfoMap
.end())
273 MacOSError::throwMe(errSecNoSuchClass
); // @@@ Not really but whatever.
279 KeychainSchemaImpl::operator <(const KeychainSchemaImpl
&other
) const
281 return mDatabaseInfoMap
< other
.mDatabaseInfoMap
;
285 KeychainSchemaImpl::operator ==(const KeychainSchemaImpl
&other
) const
287 return mDatabaseInfoMap
== other
.mDatabaseInfoMap
;
291 KeychainSchemaImpl::didCreateRelation(CSSM_DB_RECORDTYPE relationID
,
292 const char *inRelationName
,
293 uint32 inNumberOfAttributes
,
294 const CSSM_DB_SCHEMA_ATTRIBUTE_INFO
*pAttributeInfo
,
295 uint32 inNumberOfIndexes
,
296 const CSSM_DB_SCHEMA_INDEX_INFO
*pIndexInfo
)
298 StLock
<Mutex
>_(mMutex
);
300 if (CSSM_DB_RECORDTYPE_SCHEMA_START
<= relationID
301 && relationID
< CSSM_DB_RECORDTYPE_SCHEMA_END
)
304 // if our schema is already in the map, return
305 if (mPrimaryKeyInfoMap
.find(relationID
) != mPrimaryKeyInfoMap
.end())
310 RelationInfoMap
&rim
= mDatabaseInfoMap
[relationID
];
311 for (uint32 ix
= 0; ix
< inNumberOfAttributes
; ++ix
)
312 rim
[pAttributeInfo
[ix
].AttributeId
] = pAttributeInfo
[ix
].DataType
;
314 CssmAutoDbRecordAttributeInfo
*infos
= new CssmAutoDbRecordAttributeInfo();
317 insert(PrimaryKeyInfoMap::value_type(relationID
, infos
));
318 infos
->DataRecordType
= relationID
;
319 for (uint32 ix
= 0; ix
< inNumberOfIndexes
; ++ix
)
320 if (pIndexInfo
[ix
].IndexType
== CSSM_DB_INDEX_UNIQUE
)
322 CssmDbAttributeInfo
&info
= infos
->add();
323 info
.AttributeNameFormat
= CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER
;
324 info
.Label
.AttributeID
= pIndexInfo
[ix
].AttributeId
;
325 info
.AttributeFormat
= rim
[info
.Label
.AttributeID
];
331 KeychainSchema::~KeychainSchema()
340 SecKeychainEvent eventCode
;
341 PrimaryKey primaryKey
;
343 typedef std::list
<Event
> EventList
;
345 #define SYSTEM_KEYCHAIN_CHECK_UNIX_BASE_NAME "/var/run/systemkeychaincheck"
346 #define SYSTEM_KEYCHAIN_CHECK_UNIX_DOMAIN_SOCKET_NAME (SYSTEM_KEYCHAIN_CHECK_UNIX_BASE_NAME ".socket")
347 #define SYSTEM_KEYCHAIN_CHECK_COMPLETE_FILE_NAME (SYSTEM_KEYCHAIN_CHECK_UNIX_BASE_NAME ".done")
349 static void check_system_keychain()
351 // sadly we can't use XPC here, XPC_DOMAIN_TYPE_SYSTEM doesn't exist yet. Also xpc-helper uses the
352 // keychain API (I assume for checking codesign things). So we use Unix Domain Sockets.
354 // NOTE: if we hit a system error we attempt to log it, and then just don't check the system keychain.
355 // In theory a system might be able to recover from this state if we let it try to muddle along, and
356 // past behaviour didn't even try this hard to do the keychain check. In particular we could be in a
357 // sandbox'ed process. So we just do our best and let another process try again.
359 struct stat keycheck_file_info
;
360 if (stat(SYSTEM_KEYCHAIN_CHECK_COMPLETE_FILE_NAME
, &keycheck_file_info
) < 0) {
361 int server_fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
363 syslog(LOG_ERR
, "Can't get socket (%m) system keychain may be unchecked");
367 struct sockaddr_un keychain_check_server_address
;
368 keychain_check_server_address
.sun_family
= AF_UNIX
;
369 if (strlcpy(keychain_check_server_address
.sun_path
, SYSTEM_KEYCHAIN_CHECK_UNIX_DOMAIN_SOCKET_NAME
, sizeof(keychain_check_server_address
.sun_path
)) > sizeof(keychain_check_server_address
.sun_path
)) {
370 // It would be nice if we could compile time assert this
371 syslog(LOG_ERR
, "Socket path too long, max length %lu, your length %lu", (unsigned long)sizeof(keychain_check_server_address
.sun_path
), (unsigned long)strlen(SYSTEM_KEYCHAIN_CHECK_UNIX_DOMAIN_SOCKET_NAME
));
375 keychain_check_server_address
.sun_len
= SUN_LEN(&keychain_check_server_address
);
377 int rc
= connect(server_fd
, (struct sockaddr
*)&keychain_check_server_address
, keychain_check_server_address
.sun_len
);
379 syslog(LOG_ERR
, "Can not connect to %s: %m", SYSTEM_KEYCHAIN_CHECK_UNIX_DOMAIN_SOCKET_NAME
);
384 // this read lets us block until the EOF comes, we don't ever get a byte (and if we do, we don't care about it)
386 ssize_t read_size
= read(server_fd
, &byte
, 1);
388 syslog(LOG_ERR
, "Error reading from system keychain checker: %m");
399 KeychainImpl::KeychainImpl(const Db
&db
)
400 : mCacheTimer(NULL
), mSuppressTickle(false), mAttemptedUpgrade(false), mDbItemMapMutex(Mutex::recursive
), mDbDeletedItemMapMutex(Mutex::recursive
),
401 mInCache(false), mDb(db
), mCustomUnlockCreds (this), mIsInBatchMode (false), mMutex(Mutex::recursive
)
403 dispatch_once(&SecKeychainSystemKeychainChecked
, ^{
404 check_system_keychain();
406 mDb
->defaultCredentials(this); // install activation hook
407 mEventBuffer
= new EventBuffer
;
410 KeychainImpl::~KeychainImpl()
414 // Remove ourselves from the cache if we are in it.
415 // fprintf(stderr, "Removing %p from storage manager cache.\n", handle(false));
416 globals().storageManager
.removeKeychain(dlDbIdentifier(), this);
425 KeychainImpl::getMutexForObject() const
427 return globals().storageManager
.getStorageManagerMutex();
431 KeychainImpl::getKeychainMutex()
437 KeychainImpl::getKeychainReadWriteLock()
442 void KeychainImpl::aboutToDestruct()
444 // remove me from the global cache, we are done
445 // fprintf(stderr, "Destructing keychain object\n");
446 DLDbIdentifier identifier
= dlDbIdentifier();
447 globals().storageManager
.removeKeychain(identifier
, this);
451 KeychainImpl::operator ==(const KeychainImpl
&keychain
) const
453 return dlDbIdentifier() == keychain
.dlDbIdentifier();
457 KeychainImpl::createCursor(SecItemClass itemClass
, const SecKeychainAttributeList
*attrList
)
459 StLock
<Mutex
>_(mMutex
);
461 StorageManager::KeychainList keychains
;
462 keychains
.push_back(Keychain(this));
463 return KCCursor(keychains
, itemClass
, attrList
);
467 KeychainImpl::createCursor(const SecKeychainAttributeList
*attrList
)
469 StLock
<Mutex
>_(mMutex
);
471 StorageManager::KeychainList keychains
;
472 keychains
.push_back(Keychain(this));
473 return KCCursor(keychains
, attrList
);
477 KeychainImpl::create(UInt32 passwordLength
, const void *inPassword
)
479 StLock
<Mutex
>_(mMutex
);
487 Allocator
&alloc
= Allocator::standard();
489 // @@@ Share this instance
491 const CssmData
password(const_cast<void *>(inPassword
), passwordLength
);
492 AclFactory::PasswordChangeCredentials
pCreds (password
, alloc
);
493 AclFactory::AnyResourceContext
rcc(pCreds
);
496 // Now that we've created, trigger setting the defaultCredentials
500 void KeychainImpl::create(ConstStringPtr inPassword
)
502 StLock
<Mutex
>_(mMutex
);
505 create(static_cast<UInt32
>(inPassword
[0]), &inPassword
[1]);
511 KeychainImpl::create()
513 StLock
<Mutex
>_(mMutex
);
515 AclFactory aclFactory
;
516 AclFactory::AnyResourceContext
rcc(aclFactory
.unlockCred());
519 // Now that we've created, trigger setting the defaultCredentials
523 void KeychainImpl::createWithBlob(CssmData
&blob
)
525 StLock
<Mutex
>_(mMutex
);
527 mDb
->dbInfo(&Schema::DBInfo
);
528 AclFactory aclFactory
;
529 AclFactory::AnyResourceContext
rcc(aclFactory
.unlockCred());
530 mDb
->resourceControlContext (&rcc
);
533 mDb
->createWithBlob(blob
);
537 mDb
->resourceControlContext(NULL
);
541 mDb
->resourceControlContext(NULL
);
542 mDb
->dbInfo(NULL
); // Clear the schema (to not break an open call later)
543 globals().storageManager
.created(Keychain(this));
545 KCEventNotifier::PostKeychainEvent (kSecKeychainListChangedEvent
, this, NULL
);
549 KeychainImpl::create(const ResourceControlContext
*rcc
)
551 StLock
<Mutex
>_(mMutex
);
553 mDb
->dbInfo(&Schema::DBInfo
); // Set the schema (to force a create)
554 mDb
->resourceControlContext(rcc
);
561 mDb
->resourceControlContext(NULL
);
562 mDb
->dbInfo(NULL
); // Clear the schema (to not break an open call later)
565 mDb
->resourceControlContext(NULL
);
566 mDb
->dbInfo(NULL
); // Clear the schema (to not break an open call later)
567 globals().storageManager
.created(Keychain(this));
573 StLock
<Mutex
>_(mMutex
);
581 StLock
<Mutex
>_(mMutex
);
587 KeychainImpl::unlock()
589 StLock
<Mutex
>_(mMutex
);
595 KeychainImpl::unlock(const CssmData
&password
)
597 StLock
<Mutex
>_(mMutex
);
599 mDb
->unlock(password
);
603 KeychainImpl::unlock(ConstStringPtr password
)
605 StLock
<Mutex
>_(mMutex
);
609 const CssmData
data(const_cast<unsigned char *>(&password
[1]), password
[0]);
617 KeychainImpl::stash()
619 StLock
<Mutex
>_(mMutex
);
625 KeychainImpl::stashCheck()
627 StLock
<Mutex
>_(mMutex
);
633 KeychainImpl::getSettings(uint32
&outIdleTimeOut
, bool &outLockOnSleep
)
635 StLock
<Mutex
>_(mMutex
);
637 mDb
->getSettings(outIdleTimeOut
, outLockOnSleep
);
641 KeychainImpl::setSettings(uint32 inIdleTimeOut
, bool inLockOnSleep
)
643 StLock
<Mutex
>_(mMutex
);
645 // The .Mac syncing code only makes sense for the AppleFile CSP/DL,
646 // but other DLs such as the OCSP and LDAP DLs do not expose a way to
647 // change settings or the password. To make a minimal change that only affects
648 // the smartcard case, we only look for that CSP/DL
650 bool isSmartcard
= (mDb
->dl()->guid() == gGuidAppleSdCSPDL
);
652 // get the old keychain blob so that we can tell .Mac to resync it
653 CssmAutoData
oldBlob(mDb
->allocator());
655 mDb
->copyBlob(oldBlob
.get());
657 mDb
->setSettings(inIdleTimeOut
, inLockOnSleep
);
661 KeychainImpl::changePassphrase(UInt32 oldPasswordLength
, const void *oldPassword
,
662 UInt32 newPasswordLength
, const void *newPassword
)
664 StLock
<Mutex
>_(mMutex
);
666 bool isSmartcard
= (mDb
->dl()->guid() == gGuidAppleSdCSPDL
);
668 TrackingAllocator
allocator(Allocator::standard());
669 AutoCredentials cred
= AutoCredentials(allocator
);
672 const CssmData
&oldPass
= *new(allocator
) CssmData(const_cast<void *>(oldPassword
), oldPasswordLength
);
673 TypedList
&oldList
= *new(allocator
) TypedList(allocator
, CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK
);
674 oldList
.append(new(allocator
) ListElement(CSSM_SAMPLE_TYPE_PASSWORD
));
675 oldList
.append(new(allocator
) ListElement(oldPass
));
681 const CssmData
&newPass
= *new(allocator
) CssmData(const_cast<void *>(newPassword
), newPasswordLength
);
682 TypedList
&newList
= *new(allocator
) TypedList(allocator
, CSSM_SAMPLE_TYPE_KEYCHAIN_CHANGE_LOCK
);
683 newList
.append(new(allocator
) ListElement(CSSM_SAMPLE_TYPE_PASSWORD
));
684 newList
.append(new(allocator
) ListElement(newPass
));
688 // get the old keychain blob so that we can tell .Mac to resync it
689 CssmAutoData
oldBlob(mDb
->allocator());
691 mDb
->copyBlob(oldBlob
.get());
693 mDb
->changePassphrase(&cred
);
697 KeychainImpl::changePassphrase(ConstStringPtr oldPassword
, ConstStringPtr newPassword
)
699 StLock
<Mutex
>_(mMutex
);
701 const void *oldPtr
, *newPtr
;
702 UInt32 oldLen
, newLen
;
705 oldLen
= oldPassword
[0];
706 oldPtr
= oldPassword
+ 1;
716 newLen
= newPassword
[0];
717 newPtr
= newPassword
+ 1;
725 changePassphrase(oldLen
, oldPtr
, newLen
, newPtr
);
729 KeychainImpl::authenticate(const CSSM_ACCESS_CREDENTIALS
*cred
)
731 StLock
<Mutex
>_(mMutex
);
734 MacOSError::throwMe(errSecNoSuchKeychain
);
736 MacOSError::throwMe(errSecUnimplemented
);
740 KeychainImpl::status() const
742 // @@@ We should figure out the read/write status though a DL passthrough
743 // or some other way. Also should locked be unlocked read only or just
745 return (mDb
->isLocked() ? 0 : kSecUnlockStateStatus
| kSecWritePermStatus
)
746 | kSecReadPermStatus
;
750 KeychainImpl::exists()
752 StLock
<Mutex
>_(mMutex
);
758 // Ok to leave the mDb open since it will get closed when it goes away.
760 catch (const CssmError
&e
)
762 if (e
.osStatus() != CSSMERR_DL_DATASTORE_DOESNOT_EXIST
)
771 KeychainImpl::isActive() const
773 return mDb
->isActive();
776 void KeychainImpl::completeAdd(Item
&inItem
, PrimaryKey
&primaryKey
)
778 // The inItem shouldn't be in the cache yet
779 assert(!inItem
->inCache());
781 // Insert inItem into mDbItemMap with key primaryKey. p.second will be
782 // true if it got inserted. If not p.second will be false and p.first
783 // will point to the current entry with key primaryKey.
784 StLock
<Mutex
> _(mDbItemMapMutex
);
785 pair
<DbItemMap::iterator
, bool> p
=
786 mDbItemMap
.insert(DbItemMap::value_type(primaryKey
, inItem
.get()));
789 // There was already an ItemImpl * in mDbItemMap with key
790 // primaryKey. Remove it, and try the add again.
791 ItemImpl
*oldItem
= p
.first
->second
;
793 // @@@ If this happens we are breaking our API contract of
794 // uniquifying items. We really need to insert the item into the
795 // map before we start the add. And have the item be in an
796 // "is being added" state.
797 secnotice("keychain", "add of new item %p somehow replaced %p",
798 inItem
.get(), oldItem
);
800 mDbItemMap
.erase(p
.first
);
801 oldItem
->inCache(false);
802 forceRemoveFromCache(oldItem
);
803 mDbItemMap
.insert(DbItemMap::value_type(primaryKey
, inItem
.get()));
806 inItem
->inCache(true);
810 KeychainImpl::addCopy(Item
&inItem
)
812 Keychain
keychain(this);
813 PrimaryKey primaryKey
= inItem
->addWithCopyInfo(keychain
, true);
814 completeAdd(inItem
, primaryKey
);
815 postEvent(kSecAddEvent
, inItem
);
819 KeychainImpl::add(Item
&inItem
)
821 Keychain
keychain(this);
822 PrimaryKey primaryKey
= inItem
->add(keychain
);
823 completeAdd(inItem
, primaryKey
);
824 postEvent(kSecAddEvent
, inItem
);
828 KeychainImpl::didUpdate(const Item
&inItem
, PrimaryKey
&oldPK
,
831 // If the primary key hasn't changed we don't need to update mDbItemMap.
834 // If inItem isn't in the cache we don't need to update mDbItemMap.
835 assert(inItem
->inCache());
836 if (inItem
->inCache())
838 StLock
<Mutex
> _(mDbItemMapMutex
);
839 // First remove the entry for inItem in mDbItemMap with key oldPK.
840 DbItemMap::iterator it
= mDbItemMap
.find(oldPK
);
841 if (it
!= mDbItemMap
.end() && (ItemImpl
*) it
->second
== inItem
.get())
842 mDbItemMap
.erase(it
);
844 // Insert inItem into mDbItemMap with key newPK. p.second will be
845 // true if it got inserted. If not p.second will be false and
846 // p.first will point to the current entry with key newPK.
847 pair
<DbItemMap::iterator
, bool> p
=
848 mDbItemMap
.insert(DbItemMap::value_type(newPK
, inItem
.get()));
851 // There was already an ItemImpl * in mDbItemMap with key
852 // primaryKey. Remove it, and try the add again.
853 ItemImpl
*oldItem
= p
.first
->second
;
855 // @@@ If this happens we are breaking our API contract of
856 // uniquifying items. We really need to insert the item into
857 // the map with the new primary key before we start the update.
858 // And have the item be in an "is being updated" state.
859 secnotice("keychain", "update of item %p somehow replaced %p",
860 inItem
.get(), oldItem
);
862 mDbItemMap
.erase(p
.first
);
863 oldItem
->inCache(false);
864 forceRemoveFromCache(oldItem
);
865 mDbItemMap
.insert(DbItemMap::value_type(newPK
, inItem
.get()));
870 // Item updates now are technically a delete and re-add, so post these events instead of kSecUpdateEvent
871 postEvent(kSecDeleteEvent
, inItem
, oldPK
);
872 postEvent(kSecAddEvent
, inItem
);
876 KeychainImpl::deleteItem(Item
&inoutItem
)
879 // item must be persistent
880 if (!inoutItem
->isPersistent())
881 MacOSError::throwMe(errSecInvalidItemRef
);
883 secinfo("kcnotify", "starting deletion of item %p", inoutItem
.get());
885 DbUniqueRecord uniqueId
= inoutItem
->dbUniqueRecord();
886 PrimaryKey primaryKey
= inoutItem
->primaryKey();
887 uniqueId
->deleteRecord();
889 // Move the item from mDbItemMap to mDbDeletedItemMap. We need the item
890 // to give to the client process when we receive the kSecDeleteEvent
891 // notification, but if that notification never arrives, we don't want
892 // the item hanging around. When didDeleteItem is called by CCallbackMgr,
893 // we'll remove all traces of the item.
895 if (inoutItem
->inCache()) {
896 StLock
<Mutex
> _(mDbItemMapMutex
);
897 StLock
<Mutex
> __(mDbDeletedItemMapMutex
);
898 // Only look for it if it's in the cache
899 DbItemMap::iterator it
= mDbItemMap
.find(primaryKey
);
901 if (it
!= mDbItemMap
.end() && (ItemImpl
*) it
->second
== inoutItem
.get()) {
902 mDbDeletedItemMap
.insert(DbItemMap::value_type(primaryKey
, it
->second
));
903 mDbItemMap
.erase(it
);
907 // Post the notification for the item deletion with
908 // the primaryKey obtained when the item still existed
911 postEvent(kSecDeleteEvent
, inoutItem
);
914 void KeychainImpl::changeDatabase(CssmClient::Db db
)
916 StLock
<Mutex
>_(mDbMutex
);
918 mDb
->defaultCredentials(this);
925 StLock
<Mutex
>_(mMutex
);
927 if (!mDb
->dl()->subserviceMask() & CSSM_SERVICE_CSP
)
928 MacOSError::throwMe(errSecInvalidKeychain
);
930 // Try to cast first to a CSPDL to handle case where we don't have an SSDb
933 CssmClient::CSPDL
cspdl(dynamic_cast<CssmClient::CSPDLImpl
*>(&*mDb
->dl()));
938 SSDbImpl
* impl
= dynamic_cast<SSDbImpl
*>(&(*mDb
));
941 CssmError::throwMe(CSSMERR_CSSM_INVALID_POINTER
);
950 KeychainImpl::makePrimaryKey(CSSM_DB_RECORDTYPE recordType
, DbUniqueRecord
&uniqueId
)
952 StLock
<Mutex
>_(mMutex
);
954 DbAttributes
primaryKeyAttrs(uniqueId
->database());
955 primaryKeyAttrs
.recordType(recordType
);
956 gatherPrimaryKeyAttributes(primaryKeyAttrs
);
957 uniqueId
->get(&primaryKeyAttrs
, NULL
);
958 return PrimaryKey(primaryKeyAttrs
);
962 KeychainImpl::makePrimaryKey(CSSM_DB_RECORDTYPE recordType
, DbAttributes
* currentAttributes
)
964 StLock
<Mutex
>_(mMutex
);
966 DbAttributes primaryKeyAttrs
;
967 primaryKeyAttrs
.recordType(recordType
);
968 gatherPrimaryKeyAttributes(primaryKeyAttrs
);
970 for(int i
= 0; i
< primaryKeyAttrs
.size(); i
++) {
971 CssmDbAttributeData
& attr
= primaryKeyAttrs
[i
];
973 CssmDbAttributeData
* actual
= currentAttributes
->find(attr
.info());
975 attr
.set(*actual
, Allocator::standard());
978 return PrimaryKey(primaryKeyAttrs
);
981 const CssmAutoDbRecordAttributeInfo
&
982 KeychainImpl::primaryKeyInfosFor(CSSM_DB_RECORDTYPE recordType
)
984 StLock
<Mutex
>_(mMutex
);
988 return keychainSchema()->primaryKeyInfosFor(recordType
);
990 catch (const CommonError
&error
)
992 switch (error
.osStatus())
994 case errSecNoSuchClass
:
995 case CSSMERR_DL_INVALID_RECORDTYPE
:
997 return keychainSchema()->primaryKeyInfosFor(recordType
);
1004 void KeychainImpl::gatherPrimaryKeyAttributes(DbAttributes
& primaryKeyAttrs
)
1006 StLock
<Mutex
> _(mMutex
);
1008 const CssmAutoDbRecordAttributeInfo
&infos
=
1009 primaryKeyInfosFor(primaryKeyAttrs
.recordType());
1011 // @@@ fix this to not copy info.
1012 for (uint32 i
= 0; i
< infos
.size(); i
++)
1013 primaryKeyAttrs
.add(infos
.at(i
));
1017 KeychainImpl::_lookupItem(const PrimaryKey
&primaryKey
)
1019 StLock
<Mutex
> _(mDbItemMapMutex
);
1020 DbItemMap::iterator it
= mDbItemMap
.find(primaryKey
);
1021 if (it
!= mDbItemMap
.end())
1030 KeychainImpl::_lookupDeletedItemOnly(const PrimaryKey
&primaryKey
)
1032 StLock
<Mutex
> _(mDbDeletedItemMapMutex
);
1033 DbItemMap::iterator it
= mDbDeletedItemMap
.find(primaryKey
);
1034 if (it
!= mDbDeletedItemMap
.end())
1043 KeychainImpl::item(const PrimaryKey
&primaryKey
)
1045 StLock
<Mutex
>_(mMutex
);
1047 // Lookup the item in the map while holding the apiLock.
1048 ItemImpl
*itemImpl
= _lookupItem(primaryKey
);
1050 return Item(itemImpl
);
1055 // We didn't find it so create a new item with just a keychain and
1056 // a primary key. Some other thread might have beaten
1057 // us to creating this item and adding it to the cache. If that
1058 // happens we retry the lookup.
1059 return Item(this, primaryKey
);
1061 catch (const MacOSError
&e
)
1063 // If the item creation failed because some other thread already
1064 // inserted this item into the cache we retry the lookup.
1065 if (e
.osStatus() == errSecDuplicateItem
)
1067 // Lookup the item in the map while holding the apiLock.
1068 ItemImpl
*itemImpl
= _lookupItem(primaryKey
);
1070 return Item(itemImpl
);
1075 // Check for an item that may have been deleted.
1077 KeychainImpl::itemdeleted(const PrimaryKey
& primaryKey
) {
1078 StLock
<Mutex
>_(mMutex
);
1080 Item i
= _lookupDeletedItemOnly(primaryKey
);
1084 return item(primaryKey
);
1090 KeychainImpl::item(CSSM_DB_RECORDTYPE recordType
, DbUniqueRecord
&uniqueId
)
1092 StLock
<Mutex
>_(mMutex
);
1094 PrimaryKey primaryKey
= makePrimaryKey(recordType
, uniqueId
);
1096 // Lookup the item in the map while holding the apiLock.
1097 ItemImpl
*itemImpl
= _lookupItem(primaryKey
);
1101 return Item(itemImpl
);
1107 // We didn't find it so create a new item with a keychain, a primary key
1108 // and a DbUniqueRecord. However since we aren't holding
1109 // globals().apiLock anymore some other thread might have beaten
1110 // us to creating this item and adding it to the cache. If that
1111 // happens we retry the lookup.
1112 return Item(this, primaryKey
, uniqueId
);
1114 catch (const MacOSError
&e
)
1116 // If the item creation failed because some other thread already
1117 // inserted this item into the cache we retry the lookup.
1118 if (e
.osStatus() == errSecDuplicateItem
)
1120 // Lookup the item in the map while holding the apiLock.
1121 ItemImpl
*itemImpl
= _lookupItem(primaryKey
);
1123 return Item(itemImpl
);
1130 KeychainImpl::keychainSchema()
1132 StLock
<Mutex
>_(mMutex
);
1133 if (!mKeychainSchema
)
1134 mKeychainSchema
= KeychainSchema(mDb
);
1136 return mKeychainSchema
;
1139 void KeychainImpl::resetSchema()
1141 mKeychainSchema
= NULL
; // re-fetch it from db next time
1145 // Called from DbItemImpl's constructor (so it is only partially constructed),
1146 // add it to the map.
1148 KeychainImpl::addItem(const PrimaryKey
&primaryKey
, ItemImpl
*dbItemImpl
)
1150 StLock
<Mutex
>_(mMutex
);
1152 // The dbItemImpl shouldn't be in the cache yet
1153 assert(!dbItemImpl
->inCache());
1155 // Insert dbItemImpl into mDbItemMap with key primaryKey. p.second will
1156 // be true if it got inserted. If not p.second will be false and p.first
1157 // will point to the current entry with key primaryKey.
1158 StLock
<Mutex
> __(mDbItemMapMutex
);
1159 pair
<DbItemMap::iterator
, bool> p
=
1160 mDbItemMap
.insert(DbItemMap::value_type(primaryKey
, dbItemImpl
));
1164 // There was already an ItemImpl * in mDbItemMap with key primaryKey.
1165 // There is a race condition here when being called in multiple threads
1166 // We might have added an item using add and received a notification at
1168 MacOSError::throwMe(errSecDuplicateItem
);
1171 dbItemImpl
->inCache(true);
1175 KeychainImpl::didDeleteItem(ItemImpl
*inItemImpl
)
1177 StLock
<Mutex
>_(mMutex
);
1179 // Called by CCallbackMgr
1180 secinfo("kcnotify", "%p notified that item %p was deleted", this, inItemImpl
);
1181 removeItem(inItemImpl
->primaryKey(), inItemImpl
);
1185 KeychainImpl::removeItem(const PrimaryKey
&primaryKey
, ItemImpl
*inItemImpl
)
1187 StLock
<Mutex
>_(mMutex
);
1189 // If inItemImpl isn't in the cache to begin with we are done.
1190 if (!inItemImpl
->inCache())
1194 StLock
<Mutex
> _(mDbItemMapMutex
);
1195 DbItemMap::iterator it
= mDbItemMap
.find(primaryKey
);
1196 if (it
!= mDbItemMap
.end() && (ItemImpl
*) it
->second
== inItemImpl
) {
1197 mDbItemMap
.erase(it
);
1199 } // drop mDbItemMapMutex
1202 StLock
<Mutex
> _(mDbDeletedItemMapMutex
);
1203 DbItemMap::iterator it
= mDbDeletedItemMap
.find(primaryKey
);
1204 if (it
!= mDbDeletedItemMap
.end() && (ItemImpl
*) it
->second
== inItemImpl
) {
1205 mDbDeletedItemMap
.erase(it
);
1207 } // drop mDbDeletedItemMapMutex
1209 inItemImpl
->inCache(false);
1213 KeychainImpl::forceRemoveFromCache(ItemImpl
* inItemImpl
) {
1215 // Wrap all this in a try-block and ignore all errors - we're trying to clean up these maps
1217 StLock
<Mutex
> _(mDbItemMapMutex
);
1218 for(DbItemMap::iterator it
= mDbItemMap
.begin(); it
!= mDbItemMap
.end(); ) {
1219 if(it
->second
== inItemImpl
) {
1220 // Increment the iterator, but use its pre-increment value for the erase
1221 it
->second
->inCache(false);
1222 mDbItemMap
.erase(it
++);
1227 } // drop mDbItemMapMutex
1230 StLock
<Mutex
> _(mDbDeletedItemMapMutex
);
1231 for(DbItemMap::iterator it
= mDbDeletedItemMap
.begin(); it
!= mDbDeletedItemMap
.end(); ) {
1232 if(it
->second
== inItemImpl
) {
1233 // Increment the iterator, but use its pre-increment value for the erase
1234 it
->second
->inCache(false);
1235 mDbDeletedItemMap
.erase(it
++);
1240 } // drop mDbDeletedItemMapMutex
1241 } catch(UnixError ue
) {
1242 secnotice("keychain", "caught UnixError: %d %s", ue
.unixError(), ue
.what());
1243 } catch (CssmError cssme
) {
1244 const char* errStr
= cssmErrorString(cssme
.error
);
1245 secnotice("keychain", "caught CssmError: %d %s", (int) cssme
.error
, errStr
);
1246 } catch (MacOSError mose
) {
1247 secnotice("keychain", "MacOSError: %d", (int)mose
.osStatus());
1249 secnotice("keychain", "Unknown error");
1254 KeychainImpl::getAttributeInfoForItemID(CSSM_DB_RECORDTYPE itemID
,
1255 SecKeychainAttributeInfo
**Info
)
1257 StLock
<Mutex
>_(mMutex
);
1261 keychainSchema()->getAttributeInfoForRecordType(itemID
, Info
);
1263 catch (const CommonError
&error
)
1265 switch (error
.osStatus())
1267 case errSecNoSuchClass
:
1268 case CSSMERR_DL_INVALID_RECORDTYPE
:
1270 keychainSchema()->getAttributeInfoForRecordType(itemID
, Info
);
1278 KeychainImpl::freeAttributeInfo(SecKeychainAttributeInfo
*Info
)
1286 KeychainImpl::attributeInfoFor(CSSM_DB_RECORDTYPE recordType
, UInt32 tag
)
1288 StLock
<Mutex
>_(mMutex
);
1292 return keychainSchema()->attributeInfoFor(recordType
, tag
);
1294 catch (const CommonError
&error
)
1296 switch (error
.osStatus())
1298 case errSecNoSuchClass
:
1299 case CSSMERR_DL_INVALID_RECORDTYPE
:
1301 return keychainSchema()->attributeInfoFor(recordType
, tag
);
1309 KeychainImpl::recode(const CssmData
&data
, const CssmData
&extraData
)
1311 StLock
<Mutex
>_(mMutex
);
1313 mDb
->recode(data
, extraData
);
1317 KeychainImpl::copyBlob(CssmData
&data
)
1319 StLock
<Mutex
>_(mMutex
);
1321 mDb
->copyBlob(data
);
1325 KeychainImpl::setBatchMode(Boolean mode
, Boolean rollback
)
1327 StLock
<Mutex
>_(mMutex
);
1329 mDb
->setBatchMode(mode
, rollback
);
1330 mIsInBatchMode
= mode
;
1333 if (!rollback
) // was batch mode being turned off without an abort?
1336 EventBuffer::iterator it
= mEventBuffer
->begin();
1337 while (it
!= mEventBuffer
->end())
1339 PrimaryKey primaryKey
;
1342 primaryKey
= it
->item
->primaryKey();
1345 KCEventNotifier::PostKeychainEvent(it
->kcEvent
, mDb
->dlDbIdentifier(), primaryKey
);
1352 // notify that a keychain has changed in too many ways to count
1353 KCEventNotifier::PostKeychainEvent(kSecKeychainLeftBatchModeEvent
);
1354 mEventBuffer
->clear();
1358 KCEventNotifier::PostKeychainEvent(kSecKeychainEnteredBatchModeEvent
);
1362 KeychainImpl::postEvent(SecKeychainEvent kcEvent
, ItemImpl
* item
)
1364 postEvent(kcEvent
, item
, NULL
);
1368 KeychainImpl::postEvent(SecKeychainEvent kcEvent
, ItemImpl
* item
, PrimaryKey pk
)
1370 PrimaryKey primaryKey
;
1375 StLock
<Mutex
>_(mMutex
);
1379 primaryKey
= item
->primaryKey();
1383 if (!mIsInBatchMode
)
1385 KCEventNotifier::PostKeychainEvent(kcEvent
, mDb
->dlDbIdentifier(), primaryKey
);
1389 StLock
<Mutex
>_(mMutex
);
1392 it
.kcEvent
= kcEvent
;
1398 mEventBuffer
->push_back (it
);
1402 void KeychainImpl::tickle() {
1403 if(!mSuppressTickle
) {
1404 globals().storageManager
.tickleKeychain(this);
1409 bool KeychainImpl::performKeychainUpgradeIfNeeded() {
1410 // Grab this keychain's mutex. This might not be sufficient, since the
1411 // keychain might have outstanding cursors. We'll grab the RWLock later if needed.
1412 StLock
<Mutex
>_(mMutex
);
1414 if(!globals().integrityProtection()) {
1415 secnotice("integrity", "skipping upgrade for %s due to global integrity protection being disabled", mDb
->name());
1419 // We need a CSP database for 'upgrade' to be meaningful
1420 if((mDb
->dl()->subserviceMask() & CSSM_SERVICE_CSP
) == 0) {
1424 // We only want to upgrade file-based Apple keychains. Check the GUID.
1425 if(mDb
->dl()->guid() != gGuidAppleCSPDL
) {
1426 secnotice("integrity", "skipping upgrade for %s due to guid mismatch\n", mDb
->name());
1430 // If we've already attempted an upgrade on this keychain, don't bother again
1431 if(mAttemptedUpgrade
) {
1435 // Don't upgrade the System root certificate keychain (to make old tp code happy)
1436 if(strncmp(mDb
->name(), SYSTEM_ROOT_STORE_PATH
, strlen(SYSTEM_ROOT_STORE_PATH
)) == 0) {
1437 secnotice("integrity", "skipping upgrade for %s\n", mDb
->name());
1441 uint32 dbBlobVersion
= SecurityServer::DbBlob::version_MacOS_10_0
;
1444 dbBlobVersion
= mDb
->dbBlobVersion();
1445 } catch (CssmError cssme
) {
1446 if(cssme
.error
== CSSMERR_DL_DATASTORE_DOESNOT_EXIST
) {
1447 // oh well! We tried to get the blob version of a database
1448 // that doesn't exist. It doesn't need migration, so do nothing.
1449 secnotice("integrity", "dbBlobVersion() failed for a non-existent database");
1452 // Some other error occurred. We can't upgrade this keychain, so fail.
1453 const char* errStr
= cssmErrorString(cssme
.error
);
1454 secnotice("integrity", "dbBlobVersion() failed for a CssmError: %d %s", (int) cssme
.error
, errStr
);
1458 secnotice("integrity", "dbBlobVersion() failed for an unknown reason");
1464 // Check the location of this keychain
1465 string path
= mDb
->name();
1466 string keychainDbPath
= StorageManager::makeKeychainDbFilename(path
);
1468 bool inHomeLibraryKeychains
= StorageManager::pathInHomeLibraryKeychains(path
);
1470 string keychainDbSuffix
= "-db";
1471 bool endsWithKeychainDb
= (path
.size() > keychainDbSuffix
.size() && (0 == path
.compare(path
.size() - keychainDbSuffix
.size(), keychainDbSuffix
.size(), keychainDbSuffix
)));
1473 bool isSystemKeychain
= (0 == path
.compare("/Library/Keychains/System.keychain"));
1475 bool result
= false;
1477 if(inHomeLibraryKeychains
&& endsWithKeychainDb
&& dbBlobVersion
== SecurityServer::DbBlob::version_MacOS_10_0
) {
1478 // something has gone horribly wrong: an old-versioned keychain has a .keychain-db name. Rename it.
1479 string basePath
= path
;
1480 basePath
.erase(basePath
.end()-3, basePath
.end());
1482 attemptKeychainRename(path
, basePath
, dbBlobVersion
);
1484 // If we moved to a good path, we might still want to perform the upgrade. Update our variables.
1488 dbBlobVersion
= mDb
->dbBlobVersion();
1489 } catch (CssmError cssme
) {
1490 const char* errStr
= cssmErrorString(cssme
.error
);
1491 secnotice("integrity", "dbBlobVersion() after a rename failed for a CssmError: %d %s", (int) cssme
.error
, errStr
);
1494 secnotice("integrity", "dbBlobVersion() failed for an unknown reason after a rename");
1498 endsWithKeychainDb
= (path
.size() > keychainDbSuffix
.size() && (0 == path
.compare(path
.size() - keychainDbSuffix
.size(), keychainDbSuffix
.size(), keychainDbSuffix
)));
1499 keychainDbPath
= StorageManager::makeKeychainDbFilename(path
);
1500 secnotice("integrity", "after rename, our database thinks that it is %s", path
.c_str());
1503 // Migrate an old keychain in ~/Library/Keychains
1504 if(inHomeLibraryKeychains
&& dbBlobVersion
!= SecurityServer::DbBlob::version_partition
&& !endsWithKeychainDb
) {
1505 // We can only attempt to migrate an unlocked keychain.
1506 if(mDb
->isLocked()) {
1507 // However, it's possible that while we weren't doing any keychain operations, someone upgraded the keychain,
1508 // and then locked it. No way around hitting the filesystem here: check for the existence of a new file and,
1509 // if no new file exists, quit.
1510 DLDbIdentifier mungedDLDbIdentifier
= StorageManager::mungeDLDbIdentifier(mDb
->dlDbIdentifier(), false);
1511 string
mungedPath(mungedDLDbIdentifier
.dbName());
1513 // If this matches the file we already have, skip the upgrade. Otherwise, continue.
1514 if(mungedPath
== path
) {
1515 secnotice("integrity", "skipping upgrade for locked keychain %s\n", mDb
->name());
1520 result
= keychainMigration(path
, dbBlobVersion
, keychainDbPath
, SecurityServer::DbBlob::version_partition
);
1521 } else if(inHomeLibraryKeychains
&& dbBlobVersion
== SecurityServer::DbBlob::version_partition
&& !endsWithKeychainDb
) {
1522 // This is a new-style keychain with the wrong name, try to rename it
1523 attemptKeychainRename(path
, keychainDbPath
, dbBlobVersion
);
1525 } else if(isSystemKeychain
&& dbBlobVersion
== SecurityServer::DbBlob::version_partition
) {
1526 // Try to "unupgrade" the system keychain, to clean up our old issues
1527 secnotice("integrity", "attempting downgrade for %s version %d (%d %d %d)", path
.c_str(), dbBlobVersion
, inHomeLibraryKeychains
, endsWithKeychainDb
, isSystemKeychain
);
1529 // First step: acquire the credentials to allow for ACL modification
1530 SecurityServer::SystemKeychainKey
skk(kSystemUnlockFile
);
1532 // We've managed to read the key; now, create credentials using it
1533 CssmClient::Key
systemKeychainMasterKey(csp(), skk
.key(), true);
1534 CssmClient::AclFactory::MasterKeyUnlockCredentials
creds(systemKeychainMasterKey
, Allocator::standard(Allocator::sensitive
));
1536 // Attempt the downgrade, using our master key as the ACL override
1537 result
= keychainMigration(path
, dbBlobVersion
, path
, SecurityServer::DbBlob::version_MacOS_10_0
, creds
.getAccessCredentials());
1539 secnotice("integrity", "Couldn't read System.keychain key, skipping update");
1542 secnotice("integrity", "not attempting migration for %s version %d (%d %d %d)", path
.c_str(), dbBlobVersion
, inHomeLibraryKeychains
, endsWithKeychainDb
, isSystemKeychain
);
1544 // Since we don't believe any migration needs to be done here, mark the
1545 // migration as "attempted" to short-circuit future checks.
1546 mAttemptedUpgrade
= true;
1549 // We might have changed our location on disk. Let StorageManager know.
1550 globals().storageManager
.registerKeychainImpl(this);
1552 // if we attempted a migration, try to clean up leftover files from <rdar://problem/23950408> XARA backup have provided me with 12GB of login keychain copies
1554 string pattern
= path
+ "_*_backup";
1556 secnotice("integrity", "globbing for %s", pattern
.c_str());
1557 int globresult
= glob(pattern
.c_str(), GLOB_MARK
, NULL
, &pglob
);
1558 if(globresult
== 0) {
1559 secnotice("integrity", "glob: %lu results", pglob
.gl_pathc
);
1560 if(pglob
.gl_pathc
> 10) {
1561 // There are more than 10 backup files, indicating a problem.
1562 // Delete all but one of them. Under rdar://23950408, they should all be identical.
1563 secnotice("integrity", "saving backup file: %s", pglob
.gl_pathv
[0]);
1564 for(int i
= 1; i
< pglob
.gl_pathc
; i
++) {
1565 secnotice("integrity", "cleaning up backup file: %s", pglob
.gl_pathv
[i
]);
1566 // ignore return code; this is a best-effort cleanup
1567 unlink(pglob
.gl_pathv
[i
]);
1572 bool pathExists
= (::stat(path
.c_str(), &st
) == 0);
1573 bool keychainDbPathExists
= (::stat(keychainDbPath
.c_str(), &st
) == 0);
1575 if(!pathExists
&& keychainDbPathExists
&& pglob
.gl_pathc
>= 1) {
1576 // We have a file at keychainDbPath, no file at path, and at least one backup keychain file.
1578 // Move the backup file to path, to simulate the current "split-world" view,
1579 // which copies from path to keychainDbPath, then modifies keychainDbPath.
1580 secnotice("integrity", "moving backup file %s to %s", pglob
.gl_pathv
[0], path
.c_str());
1581 ::rename(pglob
.gl_pathv
[0], path
.c_str());
1591 bool KeychainImpl::keychainMigration(const string oldPath
, const uint32 dbBlobVersion
, const string newPath
, const uint32 newBlobVersion
, const AccessCredentials
*cred
) {
1592 secnotice("integrity", "going to migrate %s at version %d to", oldPath
.c_str(), dbBlobVersion
);
1593 secnotice("integrity", " %s at version %d", newPath
.c_str(), newBlobVersion
);
1595 // We need to opportunistically perform the upgrade/reload dance.
1597 // If the keychain is unlocked, try to upgrade it.
1598 // In either case, reload the database from disk.
1599 // We need this keychain's read/write lock.
1601 // Try to grab the keychain write lock.
1602 StReadWriteLock
lock(mRWLock
, StReadWriteLock::TryWrite
);
1604 // If we didn't manage to grab the lock, there's readers out there
1605 // currently reading this keychain. Abort the upgrade.
1606 if(!lock
.isLocked()) {
1607 secnotice("integrity", "couldn't get read-write lock, aborting upgrade");
1611 // Take the file lock on the existing database. We don't need to commit this txion, because we're not planning to
1612 // change the original keychain.
1613 FileLockTransaction
fileLockmDb(mDb
);
1615 // Let's reload this keychain to see if someone changed it on disk
1616 globals().storageManager
.reloadKeychain(this);
1618 bool result
= false;
1621 // We can only attempt an upgrade if the keychain is currently unlocked
1622 // There's a TOCTTOU issue here, but it's going to be rare in practice, and the upgrade will simply fail.
1623 if(!mDb
->isLocked()) {
1624 secnotice("integrity", "have a plan to migrate database %s", mDb
->name());
1625 // Database blob is out of date. Attempt a migration.
1626 uint32 convertedVersion
= attemptKeychainMigration(oldPath
, dbBlobVersion
, newPath
, newBlobVersion
, cred
);
1627 if(convertedVersion
== newBlobVersion
) {
1628 secnotice("integrity", "conversion succeeded");
1631 secnotice("integrity", "conversion failed, keychain is still %d", convertedVersion
);
1634 secnotice("integrity", "keychain is locked, can't upgrade");
1636 } catch (CssmError cssme
) {
1637 const char* errStr
= cssmErrorString(cssme
.error
);
1638 secnotice("integrity", "caught CssmError: %d %s", (int) cssme
.error
, errStr
);
1640 // Something went wrong, but don't worry about it.
1641 secnotice("integrity", "caught unknown error");
1644 // No matter if the migrator succeeded, we need to reload this keychain from disk.
1645 secnotice("integrity", "reloading keychain after migration");
1646 globals().storageManager
.reloadKeychain(this);
1647 secnotice("integrity", "database %s is now version %d", mDb
->name(), mDb
->dbBlobVersion());
1652 // Make sure you have this keychain's mutex and write lock when you call this function!
1653 uint32
KeychainImpl::attemptKeychainMigration(const string oldPath
, const uint32 oldBlobVersion
, const string newPath
, const uint32 newBlobVersion
, const AccessCredentials
* cred
) {
1654 if(mDb
->dbBlobVersion() == newBlobVersion
) {
1655 // Someone else upgraded this, hurray!
1656 secnotice("integrity", "reloaded keychain version %d, quitting", mDb
->dbBlobVersion());
1657 return newBlobVersion
;
1660 mAttemptedUpgrade
= true;
1661 uint32 newDbVersion
= oldBlobVersion
;
1663 if( (oldBlobVersion
== SecurityServer::DbBlob::version_MacOS_10_0
&& newBlobVersion
== SecurityServer::DbBlob::version_partition
) ||
1664 (oldBlobVersion
== SecurityServer::DbBlob::version_partition
&& newBlobVersion
== SecurityServer::DbBlob::version_MacOS_10_0
&& cred
!= NULL
)) {
1665 // Here's the upgrade outline:
1667 // 1. Make a copy of the keychain with the new file path
1668 // 2. Open that keychain database.
1669 // 3. Recode it to use the new version.
1670 // 4. Notify the StorageManager that the DLDB identifier for this keychain has changed.
1672 // If we're creating a new keychain file, on failure, try to delete the new file. Otherwise,
1673 // everyone will try to use it.
1675 secnotice("integrity", "attempting migration from version %d to %d", oldBlobVersion
, newBlobVersion
);
1678 bool newFile
= (oldPath
!= newPath
);
1681 DLDbIdentifier
dldbi(dlDbIdentifier().ssuid(), newPath
.c_str(), dlDbIdentifier().dbLocation());
1683 secnotice("integrity", "creating a new keychain at %s", newPath
.c_str());
1684 db
= mDb
->cloneTo(dldbi
);
1686 secnotice("integrity", "using old keychain at %s", newPath
.c_str());
1689 FileLockTransaction
fileLockDb(db
);
1692 // since we're creating a completely new file, if this migration fails, delete the new file
1693 fileLockDb
.setDeleteOnFailure();
1696 // Let the upgrade begin.
1697 newDbVersion
= db
->recodeDbToVersion(newBlobVersion
);
1698 if(newDbVersion
!= newBlobVersion
) {
1699 // Recoding failed. Don't proceed.
1700 secnotice("integrity", "recodeDbToVersion failed, version is still %d", newDbVersion
);
1701 return newDbVersion
;
1704 secnotice("integrity", "recoded db successfully, adding extra integrity");
1706 Keychain
keychain(db
);
1708 // Breaking abstraction, but what're you going to do?
1709 // Don't upgrade this keychain, since we just upgraded the DB
1710 // But the DB won't return any new data until the txion commits
1711 keychain
->mAttemptedUpgrade
= true;
1712 keychain
->mSuppressTickle
= true;
1714 SecItemClass classes
[] = {kSecGenericPasswordItemClass
,
1715 kSecInternetPasswordItemClass
,
1716 kSecPublicKeyItemClass
,
1717 kSecPrivateKeyItemClass
,
1718 kSecSymmetricKeyItemClass
};
1720 for(int i
= 0; i
< sizeof(classes
) / sizeof(classes
[0]); i
++) {
1722 KCCursor kcc
= keychain
->createCursor(classes
[i
], NULL
);
1724 // During recoding, we might have deleted some corrupt keys.
1725 // Because of this, we might have zombie SSGroup records left in
1726 // the database that have no matching key. Tell the KCCursor to
1727 // delete these if found.
1728 // This will also try to suppress any other invalid items.
1729 kcc
->setDeleteInvalidRecords(true);
1731 while(kcc
->next(item
)) {
1733 if(newBlobVersion
== SecurityServer::DbBlob::version_partition
) {
1734 // Force the item to set integrity. The keychain is confused about its version because it hasn't written to disk yet,
1735 // but if we've reached this point, the keychain supports integrity.
1736 item
->setIntegrity(true);
1737 } else if(newBlobVersion
== SecurityServer::DbBlob::version_MacOS_10_0
) {
1738 // We're downgrading this keychain. Pass in whatever credentials our caller thinks will allow this ACL modification.
1739 item
->removeIntegrity(cred
);
1741 } catch(CssmError cssme
) {
1742 // During recoding, we might have deleted some corrupt keys. Because of this, we might have zombie SSGroup records left in
1743 // the database that have no matching key. If we get a DL_RECORD_NOT_FOUND error, delete the matching item record.
1744 if (cssme
.osStatus() == CSSMERR_DL_RECORD_NOT_FOUND
) {
1745 secnotice("integrity", "deleting corrupt (Not Found) record");
1746 keychain
->deleteItem(item
);
1754 // Tell securityd we're done with the upgrade, to re-enable all protections
1755 db
->recodeFinished();
1757 // If we reach here, tell the file locks to commit the transaction and return the new blob version
1758 fileLockDb
.success();
1760 secnotice("integrity", "success, returning version %d", newDbVersion
);
1761 return newDbVersion
;
1762 } catch(UnixError ue
) {
1763 secnotice("integrity", "caught UnixError: %d %s", ue
.unixError(), ue
.what());
1764 } catch (CssmError cssme
) {
1765 const char* errStr
= cssmErrorString(cssme
.error
);
1766 secnotice("integrity", "caught CssmError: %d %s", (int) cssme
.error
, errStr
);
1767 } catch (MacOSError mose
) {
1768 secnotice("integrity", "MacOSError: %d", (int)mose
.osStatus());
1769 } catch (const std::bad_cast
& e
) {
1770 secnotice("integrity", "***** bad cast: %s", e
.what());
1772 // We failed to migrate. We won't commit the transaction, so the blob on-disk stays the same.
1773 secnotice("integrity", "***** unknown error");
1776 secnotice("integrity", "no migration path for %s at version %d to", oldPath
.c_str(), oldBlobVersion
);
1777 secnotice("integrity", " %s at version %d", newPath
.c_str(), newBlobVersion
);
1778 return oldBlobVersion
;
1781 // If we reached here, the migration failed. Return the old version.
1782 return oldBlobVersion
;
1785 void KeychainImpl::attemptKeychainRename(const string oldPath
, const string newPath
, uint32 blobVersion
) {
1786 secnotice("integrity", "attempting to rename keychain (%d) from %s to %s", blobVersion
, oldPath
.c_str(), newPath
.c_str());
1788 // Take the file lock on this database, so other people won't try to move it before we do
1789 // NOTE: during a migration from a v256 to a v512 keychain, the db is first copied from the .keychain to the
1790 // .keychain-db path. Other non-migrating processes, if they open the keychain, enter this function to
1791 // try to move it back. These will attempt to take the .keychain-db file lock, but they will not succeed
1792 // until the migration is finished. Once they acquire that, they might try to take the .keychain file lock.
1793 // This is technically lock inversion, but deadlocks will not happen since the migrating process creates the
1794 // .keychain-db file lock before creating the .keychain-db file, so other processes will not try to grab the
1795 // .keychain-db lock in this function before the migrating process already has it.
1796 FileLockTransaction
fileLockmDb(mDb
);
1798 // first, check if someone renamed this keychain while we were grabbing the file lock
1799 globals().storageManager
.reloadKeychain(this);
1801 uint32 dbBlobVersion
= SecurityServer::DbBlob::version_MacOS_10_0
;
1804 dbBlobVersion
= mDb
->dbBlobVersion();
1806 secnotice("integrity", "dbBlobVersion() failed for an unknown reason while renaming, aborting rename");
1810 if(dbBlobVersion
!= blobVersion
) {
1811 secnotice("integrity", "database version changed while we were grabbing the file lock; aborting rename");
1815 if(oldPath
!= mDb
->name()) {
1816 secnotice("integrity", "database location changed while we were grabbing the file lock; aborting rename");
1820 // we're still at the original location and version; go ahead and do the move
1821 globals().storageManager
.rename(this, newPath
.c_str());
1824 Keychain::Keychain()
1826 dispatch_once(&SecKeychainSystemKeychainChecked
, ^{
1827 check_system_keychain();
1831 Keychain::~Keychain()
1838 Keychain::optional(SecKeychainRef handle
)
1841 return KeychainImpl::required(handle
);
1843 return globals().storageManager
.defaultKeychain();
1847 CFIndex
KeychainCore::GetKeychainRetainCount(Keychain
& kc
)
1849 CFTypeRef ref
= kc
->handle(false);
1850 return CFGetRetainCount(ref
);
1855 // Create default credentials for this keychain.
1856 // This is triggered upon default open (i.e. a Db::activate() with no set credentials).
1858 // This function embodies the "default credentials" logic for Keychain-layer databases.
1860 const AccessCredentials
*
1861 KeychainImpl::makeCredentials()
1863 return defaultCredentials();
1867 const AccessCredentials
*
1868 KeychainImpl::defaultCredentials()
1870 StLock
<Mutex
>_(mMutex
);
1872 // Use custom unlock credentials for file keychains which have a referral
1873 // record and the standard credentials for all others.
1875 if (mDb
->dl()->guid() == gGuidAppleCSPDL
&& mCustomUnlockCreds(mDb
))
1876 return &mCustomUnlockCreds
;
1878 if (mDb
->dl()->guid() == gGuidAppleSdCSPDL
)
1879 return globals().smartcardCredentials();
1881 return globals().keychainCredentials();
1886 bool KeychainImpl::mayDelete()
1891 bool KeychainImpl::hasIntegrityProtection() {
1892 // This keychain only supports integrity if there's a database attached, that database is an Apple CSPDL, and the blob version is high enough
1893 if(mDb
&& (mDb
->dl()->guid() == gGuidAppleCSPDL
)) {
1894 if(mDb
->dbBlobVersion() >= SecurityServer::DbBlob::version_partition
) {
1897 secnotice("integrity", "keychain blob version does not support integrity");
1901 secnotice("integrity", "keychain guid does not support integrity");