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(formatBuf
, (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()
436 void KeychainImpl::aboutToDestruct()
438 // remove me from the global cache, we are done
439 // fprintf(stderr, "Destructing keychain object\n");
440 DLDbIdentifier identifier
= dlDbIdentifier();
441 globals().storageManager
.removeKeychain(identifier
, this);
445 KeychainImpl::operator ==(const KeychainImpl
&keychain
) const
447 return dlDbIdentifier() == keychain
.dlDbIdentifier();
451 KeychainImpl::createCursor(SecItemClass itemClass
, const SecKeychainAttributeList
*attrList
)
453 StLock
<Mutex
>_(mMutex
);
455 StorageManager::KeychainList keychains
;
456 keychains
.push_back(Keychain(this));
457 return KCCursor(keychains
, itemClass
, attrList
);
461 KeychainImpl::createCursor(const SecKeychainAttributeList
*attrList
)
463 StLock
<Mutex
>_(mMutex
);
465 StorageManager::KeychainList keychains
;
466 keychains
.push_back(Keychain(this));
467 return KCCursor(keychains
, attrList
);
471 KeychainImpl::create(UInt32 passwordLength
, const void *inPassword
)
473 StLock
<Mutex
>_(mMutex
);
481 Allocator
&alloc
= Allocator::standard();
483 // @@@ Share this instance
485 const CssmData
password(const_cast<void *>(inPassword
), passwordLength
);
486 AclFactory::PasswordChangeCredentials
pCreds (password
, alloc
);
487 AclFactory::AnyResourceContext
rcc(pCreds
);
490 // Now that we've created, trigger setting the defaultCredentials
494 void KeychainImpl::create(ConstStringPtr inPassword
)
496 StLock
<Mutex
>_(mMutex
);
499 create(static_cast<UInt32
>(inPassword
[0]), &inPassword
[1]);
505 KeychainImpl::create()
507 StLock
<Mutex
>_(mMutex
);
509 AclFactory aclFactory
;
510 AclFactory::AnyResourceContext
rcc(aclFactory
.unlockCred());
513 // Now that we've created, trigger setting the defaultCredentials
517 void KeychainImpl::createWithBlob(CssmData
&blob
)
519 StLock
<Mutex
>_(mMutex
);
521 mDb
->dbInfo(&Schema::DBInfo
);
522 AclFactory aclFactory
;
523 AclFactory::AnyResourceContext
rcc(aclFactory
.unlockCred());
524 mDb
->resourceControlContext (&rcc
);
527 mDb
->createWithBlob(blob
);
531 mDb
->resourceControlContext(NULL
);
535 mDb
->resourceControlContext(NULL
);
536 mDb
->dbInfo(NULL
); // Clear the schema (to not break an open call later)
537 globals().storageManager
.created(Keychain(this));
539 KCEventNotifier::PostKeychainEvent (kSecKeychainListChangedEvent
, this, NULL
);
543 KeychainImpl::create(const ResourceControlContext
*rcc
)
545 StLock
<Mutex
>_(mMutex
);
547 mDb
->dbInfo(&Schema::DBInfo
); // Set the schema (to force a create)
548 mDb
->resourceControlContext(rcc
);
555 mDb
->resourceControlContext(NULL
);
556 mDb
->dbInfo(NULL
); // Clear the schema (to not break an open call later)
559 mDb
->resourceControlContext(NULL
);
560 mDb
->dbInfo(NULL
); // Clear the schema (to not break an open call later)
561 globals().storageManager
.created(Keychain(this));
567 StLock
<Mutex
>_(mMutex
);
575 StLock
<Mutex
>_(mMutex
);
581 KeychainImpl::unlock()
583 StLock
<Mutex
>_(mMutex
);
589 KeychainImpl::unlock(const CssmData
&password
)
591 StLock
<Mutex
>_(mMutex
);
593 mDb
->unlock(password
);
597 KeychainImpl::unlock(ConstStringPtr password
)
599 StLock
<Mutex
>_(mMutex
);
603 const CssmData
data(const_cast<unsigned char *>(&password
[1]), password
[0]);
611 KeychainImpl::stash()
613 StLock
<Mutex
>_(mMutex
);
619 KeychainImpl::stashCheck()
621 StLock
<Mutex
>_(mMutex
);
627 KeychainImpl::getSettings(uint32
&outIdleTimeOut
, bool &outLockOnSleep
)
629 StLock
<Mutex
>_(mMutex
);
631 mDb
->getSettings(outIdleTimeOut
, outLockOnSleep
);
635 KeychainImpl::setSettings(uint32 inIdleTimeOut
, bool inLockOnSleep
)
637 StLock
<Mutex
>_(mMutex
);
639 // The .Mac syncing code only makes sense for the AppleFile CSP/DL,
640 // but other DLs such as the OCSP and LDAP DLs do not expose a way to
641 // change settings or the password. To make a minimal change that only affects
642 // the smartcard case, we only look for that CSP/DL
644 bool isSmartcard
= (mDb
->dl()->guid() == gGuidAppleSdCSPDL
);
646 // get the old keychain blob so that we can tell .Mac to resync it
647 CssmAutoData
oldBlob(mDb
->allocator());
649 mDb
->copyBlob(oldBlob
.get());
651 mDb
->setSettings(inIdleTimeOut
, inLockOnSleep
);
655 KeychainImpl::changePassphrase(UInt32 oldPasswordLength
, const void *oldPassword
,
656 UInt32 newPasswordLength
, const void *newPassword
)
658 StLock
<Mutex
>_(mMutex
);
660 secnotice("KCspi", "Attempting to change passphrase for %s", mDb
->name());
662 bool isSmartcard
= (mDb
->dl()->guid() == gGuidAppleSdCSPDL
);
664 TrackingAllocator
allocator(Allocator::standard());
665 AutoCredentials cred
= AutoCredentials(allocator
);
669 const CssmData
&oldPass
= *new(allocator
) CssmData(const_cast<void *>(oldPassword
), oldPasswordLength
);
670 TypedList
&oldList
= *new(allocator
) TypedList(allocator
, CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK
);
671 oldList
.append(new(allocator
) ListElement(CSSM_SAMPLE_TYPE_PASSWORD
));
672 oldList
.append(new(allocator
) ListElement(oldPass
));
678 const CssmData
&newPass
= *new(allocator
) CssmData(const_cast<void *>(newPassword
), newPasswordLength
);
679 TypedList
&newList
= *new(allocator
) TypedList(allocator
, CSSM_SAMPLE_TYPE_KEYCHAIN_CHANGE_LOCK
);
680 newList
.append(new(allocator
) ListElement(CSSM_SAMPLE_TYPE_PASSWORD
));
681 newList
.append(new(allocator
) ListElement(newPass
));
685 // get the old keychain blob so that we can tell .Mac to resync it
686 CssmAutoData
oldBlob(mDb
->allocator());
688 mDb
->copyBlob(oldBlob
.get());
690 mDb
->changePassphrase(&cred
);
694 KeychainImpl::changePassphrase(ConstStringPtr oldPassword
, ConstStringPtr newPassword
)
696 StLock
<Mutex
>_(mMutex
);
698 const void *oldPtr
, *newPtr
;
699 UInt32 oldLen
, newLen
;
702 oldLen
= oldPassword
[0];
703 oldPtr
= oldPassword
+ 1;
713 newLen
= newPassword
[0];
714 newPtr
= newPassword
+ 1;
722 changePassphrase(oldLen
, oldPtr
, newLen
, newPtr
);
726 KeychainImpl::authenticate(const CSSM_ACCESS_CREDENTIALS
*cred
)
728 StLock
<Mutex
>_(mMutex
);
731 MacOSError::throwMe(errSecNoSuchKeychain
);
733 MacOSError::throwMe(errSecUnimplemented
);
737 KeychainImpl::status() const
739 StLock
<Mutex
>_(mMutex
);
741 // @@@ We should figure out the read/write status though a DL passthrough
742 // or some other way. Also should locked be unlocked read only or just
744 return (mDb
->isLocked() ? 0 : kSecUnlockStateStatus
| kSecWritePermStatus
)
745 | kSecReadPermStatus
;
749 KeychainImpl::exists()
751 StLock
<Mutex
>_(mMutex
);
757 // Ok to leave the mDb open since it will get closed when it goes away.
759 catch (const CssmError
&e
)
761 if (e
.osStatus() != CSSMERR_DL_DATASTORE_DOESNOT_EXIST
)
770 KeychainImpl::isActive() const
772 return mDb
->isActive();
775 void KeychainImpl::completeAdd(Item
&inItem
, PrimaryKey
&primaryKey
)
777 // The inItem shouldn't be in the cache yet
778 assert(!inItem
->inCache());
780 // Insert inItem into mDbItemMap with key primaryKey. p.second will be
781 // true if it got inserted. If not p.second will be false and p.first
782 // will point to the current entry with key primaryKey.
783 StLock
<Mutex
> _(mDbItemMapMutex
);
784 pair
<DbItemMap::iterator
, bool> p
=
785 mDbItemMap
.insert(DbItemMap::value_type(primaryKey
, inItem
.get()));
788 // There was already an ItemImpl * in mDbItemMap with key
789 // primaryKey. Remove it, and try the add again.
790 ItemImpl
*oldItem
= p
.first
->second
;
792 // @@@ If this happens we are breaking our API contract of
793 // uniquifying items. We really need to insert the item into the
794 // map before we start the add. And have the item be in an
795 // "is being added" state.
796 secnotice("keychain", "add of new item %p somehow replaced %p",
797 inItem
.get(), oldItem
);
799 mDbItemMap
.erase(p
.first
);
800 oldItem
->inCache(false);
801 forceRemoveFromCache(oldItem
);
802 mDbItemMap
.insert(DbItemMap::value_type(primaryKey
, inItem
.get()));
805 inItem
->inCache(true);
809 KeychainImpl::addCopy(Item
&inItem
)
811 StLock
<Mutex
>_(mMutex
);
813 Keychain
keychain(this);
814 PrimaryKey primaryKey
= inItem
->addWithCopyInfo(keychain
, true);
815 completeAdd(inItem
, primaryKey
);
816 postEvent(kSecAddEvent
, inItem
);
820 KeychainImpl::add(Item
&inItem
)
822 StLock
<Mutex
>_(mMutex
);
824 Keychain
keychain(this);
825 PrimaryKey primaryKey
= inItem
->add(keychain
);
826 completeAdd(inItem
, primaryKey
);
827 postEvent(kSecAddEvent
, inItem
);
831 KeychainImpl::didUpdate(const Item
&inItem
, PrimaryKey
&oldPK
,
834 // If the primary key hasn't changed we don't need to update mDbItemMap.
837 // If inItem isn't in the cache we don't need to update mDbItemMap.
838 assert(inItem
->inCache());
839 if (inItem
->inCache())
841 StLock
<Mutex
> _(mDbItemMapMutex
);
842 // First remove the entry for inItem in mDbItemMap with key oldPK.
843 DbItemMap::iterator it
= mDbItemMap
.find(oldPK
);
844 if (it
!= mDbItemMap
.end() && (ItemImpl
*) it
->second
== inItem
.get())
845 mDbItemMap
.erase(it
);
847 // Insert inItem into mDbItemMap with key newPK. p.second will be
848 // true if it got inserted. If not p.second will be false and
849 // p.first will point to the current entry with key newPK.
850 pair
<DbItemMap::iterator
, bool> p
=
851 mDbItemMap
.insert(DbItemMap::value_type(newPK
, inItem
.get()));
854 // There was already an ItemImpl * in mDbItemMap with key
855 // primaryKey. Remove it, and try the add again.
856 ItemImpl
*oldItem
= p
.first
->second
;
858 // @@@ If this happens we are breaking our API contract of
859 // uniquifying items. We really need to insert the item into
860 // the map with the new primary key before we start the update.
861 // And have the item be in an "is being updated" state.
862 secnotice("keychain", "update of item %p somehow replaced %p",
863 inItem
.get(), oldItem
);
865 mDbItemMap
.erase(p
.first
);
866 oldItem
->inCache(false);
867 forceRemoveFromCache(oldItem
);
868 mDbItemMap
.insert(DbItemMap::value_type(newPK
, inItem
.get()));
873 // Item updates now are technically a delete and re-add, so post these events instead of kSecUpdateEvent
874 postEvent(kSecDeleteEvent
, inItem
, oldPK
);
875 postEvent(kSecAddEvent
, inItem
);
879 KeychainImpl::deleteItem(Item
&inoutItem
)
881 StLock
<Mutex
>_(mMutex
);
884 // item must be persistent
885 if (!inoutItem
->isPersistent())
886 MacOSError::throwMe(errSecInvalidItemRef
);
888 secinfo("kcnotify", "starting deletion of item %p", inoutItem
.get());
890 DbUniqueRecord uniqueId
= inoutItem
->dbUniqueRecord();
891 PrimaryKey primaryKey
= inoutItem
->primaryKey();
892 uniqueId
->deleteRecord();
894 // Move the item from mDbItemMap to mDbDeletedItemMap. We need the item
895 // to give to the client process when we receive the kSecDeleteEvent
896 // notification, but if that notification never arrives, we don't want
897 // the item hanging around. When didDeleteItem is called by CCallbackMgr,
898 // we'll remove all traces of the item.
900 if (inoutItem
->inCache()) {
901 StLock
<Mutex
> _(mDbItemMapMutex
);
902 StLock
<Mutex
> __(mDbDeletedItemMapMutex
);
903 // Only look for it if it's in the cache
904 DbItemMap::iterator it
= mDbItemMap
.find(primaryKey
);
906 if (it
!= mDbItemMap
.end() && (ItemImpl
*) it
->second
== inoutItem
.get()) {
907 mDbDeletedItemMap
.insert(DbItemMap::value_type(primaryKey
, it
->second
));
908 mDbItemMap
.erase(it
);
912 // Post the notification for the item deletion with
913 // the primaryKey obtained when the item still existed
916 postEvent(kSecDeleteEvent
, inoutItem
);
919 void KeychainImpl::changeDatabase(CssmClient::Db db
)
921 StLock
<Mutex
>_(mDbMutex
);
923 mDb
->defaultCredentials(this);
930 StLock
<Mutex
>_(mMutex
);
932 if (!(mDb
->dl()->subserviceMask() & CSSM_SERVICE_CSP
))
933 MacOSError::throwMe(errSecInvalidKeychain
);
935 // Try to cast first to a CSPDL to handle case where we don't have an SSDb
938 CssmClient::CSPDL
cspdl(dynamic_cast<CssmClient::CSPDLImpl
*>(&*mDb
->dl()));
943 SSDbImpl
* impl
= dynamic_cast<SSDbImpl
*>(&(*mDb
));
946 CssmError::throwMe(CSSMERR_CSSM_INVALID_POINTER
);
955 KeychainImpl::makePrimaryKey(CSSM_DB_RECORDTYPE recordType
, DbUniqueRecord
&uniqueId
)
957 StLock
<Mutex
>_(mMutex
);
959 DbAttributes
primaryKeyAttrs(uniqueId
->database());
960 primaryKeyAttrs
.recordType(recordType
);
961 gatherPrimaryKeyAttributes(primaryKeyAttrs
);
962 uniqueId
->get(&primaryKeyAttrs
, NULL
);
963 return PrimaryKey(primaryKeyAttrs
);
967 KeychainImpl::makePrimaryKey(CSSM_DB_RECORDTYPE recordType
, DbAttributes
* currentAttributes
)
969 StLock
<Mutex
>_(mMutex
);
971 DbAttributes primaryKeyAttrs
;
972 primaryKeyAttrs
.recordType(recordType
);
973 gatherPrimaryKeyAttributes(primaryKeyAttrs
);
975 for(int i
= 0; i
< primaryKeyAttrs
.size(); i
++) {
976 CssmDbAttributeData
& attr
= primaryKeyAttrs
[i
];
978 CssmDbAttributeData
* actual
= currentAttributes
->find(attr
.info());
980 attr
.set(*actual
, Allocator::standard());
983 return PrimaryKey(primaryKeyAttrs
);
986 const CssmAutoDbRecordAttributeInfo
&
987 KeychainImpl::primaryKeyInfosFor(CSSM_DB_RECORDTYPE recordType
)
989 StLock
<Mutex
>_(mMutex
);
993 return keychainSchema()->primaryKeyInfosFor(recordType
);
995 catch (const CommonError
&error
)
997 switch (error
.osStatus())
999 case errSecNoSuchClass
:
1000 case CSSMERR_DL_INVALID_RECORDTYPE
:
1002 return keychainSchema()->primaryKeyInfosFor(recordType
);
1009 void KeychainImpl::gatherPrimaryKeyAttributes(DbAttributes
& primaryKeyAttrs
)
1011 StLock
<Mutex
> _(mMutex
);
1013 const CssmAutoDbRecordAttributeInfo
&infos
=
1014 primaryKeyInfosFor(primaryKeyAttrs
.recordType());
1016 // @@@ fix this to not copy info.
1017 for (uint32 i
= 0; i
< infos
.size(); i
++)
1018 primaryKeyAttrs
.add(infos
.at(i
));
1022 KeychainImpl::_lookupItem(const PrimaryKey
&primaryKey
)
1024 StLock
<Mutex
> _(mDbItemMapMutex
);
1025 DbItemMap::iterator it
= mDbItemMap
.find(primaryKey
);
1026 if (it
!= mDbItemMap
.end())
1035 KeychainImpl::_lookupDeletedItemOnly(const PrimaryKey
&primaryKey
)
1037 StLock
<Mutex
> _(mDbDeletedItemMapMutex
);
1038 DbItemMap::iterator it
= mDbDeletedItemMap
.find(primaryKey
);
1039 if (it
!= mDbDeletedItemMap
.end())
1048 KeychainImpl::item(const PrimaryKey
&primaryKey
)
1050 StLock
<Mutex
>_(mMutex
);
1052 // Lookup the item in the map while holding the apiLock.
1053 ItemImpl
*itemImpl
= _lookupItem(primaryKey
);
1055 return Item(itemImpl
);
1060 // We didn't find it so create a new item with just a keychain and
1061 // a primary key. Some other thread might have beaten
1062 // us to creating this item and adding it to the cache. If that
1063 // happens we retry the lookup.
1064 return Item(this, primaryKey
);
1066 catch (const MacOSError
&e
)
1068 // If the item creation failed because some other thread already
1069 // inserted this item into the cache we retry the lookup.
1070 if (e
.osStatus() == errSecDuplicateItem
)
1072 // Lookup the item in the map while holding the apiLock.
1073 ItemImpl
*itemImpl
= _lookupItem(primaryKey
);
1075 return Item(itemImpl
);
1080 // Check for an item that may have been deleted.
1082 KeychainImpl::itemdeleted(const PrimaryKey
& primaryKey
) {
1083 StLock
<Mutex
>_(mMutex
);
1085 Item i
= _lookupDeletedItemOnly(primaryKey
);
1089 return item(primaryKey
);
1095 KeychainImpl::item(CSSM_DB_RECORDTYPE recordType
, DbUniqueRecord
&uniqueId
)
1097 StLock
<Mutex
>_(mMutex
);
1099 PrimaryKey primaryKey
= makePrimaryKey(recordType
, uniqueId
);
1101 // Lookup the item in the map while holding the apiLock.
1102 ItemImpl
*itemImpl
= _lookupItem(primaryKey
);
1106 return Item(itemImpl
);
1112 // We didn't find it so create a new item with a keychain, a primary key
1113 // and a DbUniqueRecord. However since we aren't holding
1114 // globals().apiLock anymore some other thread might have beaten
1115 // us to creating this item and adding it to the cache. If that
1116 // happens we retry the lookup.
1117 return Item(this, primaryKey
, uniqueId
);
1119 catch (const MacOSError
&e
)
1121 // If the item creation failed because some other thread already
1122 // inserted this item into the cache we retry the lookup.
1123 if (e
.osStatus() == errSecDuplicateItem
)
1125 // Lookup the item in the map while holding the apiLock.
1126 ItemImpl
*itemImpl
= _lookupItem(primaryKey
);
1128 return Item(itemImpl
);
1135 KeychainImpl::keychainSchema()
1137 StLock
<Mutex
>_(mMutex
);
1138 if (!mKeychainSchema
)
1139 mKeychainSchema
= KeychainSchema(mDb
);
1141 return mKeychainSchema
;
1144 void KeychainImpl::resetSchema()
1146 mKeychainSchema
= NULL
; // re-fetch it from db next time
1150 // Called from DbItemImpl's constructor (so it is only partially constructed),
1151 // add it to the map.
1153 KeychainImpl::addItem(const PrimaryKey
&primaryKey
, ItemImpl
*dbItemImpl
)
1155 StLock
<Mutex
>_(mMutex
);
1157 // The dbItemImpl shouldn't be in the cache yet
1158 assert(!dbItemImpl
->inCache());
1160 // Insert dbItemImpl into mDbItemMap with key primaryKey. p.second will
1161 // be true if it got inserted. If not p.second will be false and p.first
1162 // will point to the current entry with key primaryKey.
1163 StLock
<Mutex
> __(mDbItemMapMutex
);
1164 pair
<DbItemMap::iterator
, bool> p
=
1165 mDbItemMap
.insert(DbItemMap::value_type(primaryKey
, dbItemImpl
));
1169 // There was already an ItemImpl * in mDbItemMap with key primaryKey.
1170 // There is a race condition here when being called in multiple threads
1171 // We might have added an item using add and received a notification at
1173 MacOSError::throwMe(errSecDuplicateItem
);
1176 dbItemImpl
->inCache(true);
1180 KeychainImpl::didDeleteItem(ItemImpl
*inItemImpl
)
1182 StLock
<Mutex
>_(mMutex
);
1184 // Called by CCallbackMgr
1185 secinfo("kcnotify", "%p notified that item %p was deleted", this, inItemImpl
);
1186 removeItem(inItemImpl
->primaryKey(), inItemImpl
);
1190 KeychainImpl::removeItem(const PrimaryKey
&primaryKey
, ItemImpl
*inItemImpl
)
1192 StLock
<Mutex
>_(mMutex
);
1194 // If inItemImpl isn't in the cache to begin with we are done.
1195 if (!inItemImpl
->inCache())
1199 StLock
<Mutex
> _(mDbItemMapMutex
);
1200 DbItemMap::iterator it
= mDbItemMap
.find(primaryKey
);
1201 if (it
!= mDbItemMap
.end() && (ItemImpl
*) it
->second
== inItemImpl
) {
1202 mDbItemMap
.erase(it
);
1204 } // drop mDbItemMapMutex
1207 StLock
<Mutex
> _(mDbDeletedItemMapMutex
);
1208 DbItemMap::iterator it
= mDbDeletedItemMap
.find(primaryKey
);
1209 if (it
!= mDbDeletedItemMap
.end() && (ItemImpl
*) it
->second
== inItemImpl
) {
1210 mDbDeletedItemMap
.erase(it
);
1212 } // drop mDbDeletedItemMapMutex
1214 inItemImpl
->inCache(false);
1218 KeychainImpl::forceRemoveFromCache(ItemImpl
* inItemImpl
) {
1220 // Wrap all this in a try-block and ignore all errors - we're trying to clean up these maps
1222 StLock
<Mutex
> _(mDbItemMapMutex
);
1223 for(DbItemMap::iterator it
= mDbItemMap
.begin(); it
!= mDbItemMap
.end(); ) {
1224 if(it
->second
== inItemImpl
) {
1225 // Increment the iterator, but use its pre-increment value for the erase
1226 it
->second
->inCache(false);
1227 mDbItemMap
.erase(it
++);
1232 } // drop mDbItemMapMutex
1235 StLock
<Mutex
> _(mDbDeletedItemMapMutex
);
1236 for(DbItemMap::iterator it
= mDbDeletedItemMap
.begin(); it
!= mDbDeletedItemMap
.end(); ) {
1237 if(it
->second
== inItemImpl
) {
1238 // Increment the iterator, but use its pre-increment value for the erase
1239 it
->second
->inCache(false);
1240 mDbDeletedItemMap
.erase(it
++);
1245 } // drop mDbDeletedItemMapMutex
1246 } catch(UnixError ue
) {
1247 secnotice("keychain", "caught UnixError: %d %s", ue
.unixError(), ue
.what());
1248 } catch (CssmError cssme
) {
1249 const char* errStr
= cssmErrorString(cssme
.error
);
1250 secnotice("keychain", "caught CssmError: %d %s", (int) cssme
.error
, errStr
);
1251 } catch (MacOSError mose
) {
1252 secnotice("keychain", "MacOSError: %d", (int)mose
.osStatus());
1254 secnotice("keychain", "Unknown error");
1259 KeychainImpl::getAttributeInfoForItemID(CSSM_DB_RECORDTYPE itemID
,
1260 SecKeychainAttributeInfo
**Info
)
1262 StLock
<Mutex
>_(mMutex
);
1266 keychainSchema()->getAttributeInfoForRecordType(itemID
, Info
);
1268 catch (const CommonError
&error
)
1270 switch (error
.osStatus())
1272 case errSecNoSuchClass
:
1273 case CSSMERR_DL_INVALID_RECORDTYPE
:
1275 keychainSchema()->getAttributeInfoForRecordType(itemID
, Info
);
1283 KeychainImpl::freeAttributeInfo(SecKeychainAttributeInfo
*Info
)
1291 KeychainImpl::attributeInfoFor(CSSM_DB_RECORDTYPE recordType
, UInt32 tag
)
1293 StLock
<Mutex
>_(mMutex
);
1297 return keychainSchema()->attributeInfoFor(recordType
, tag
);
1299 catch (const CommonError
&error
)
1301 switch (error
.osStatus())
1303 case errSecNoSuchClass
:
1304 case CSSMERR_DL_INVALID_RECORDTYPE
:
1306 return keychainSchema()->attributeInfoFor(recordType
, tag
);
1314 KeychainImpl::recode(const CssmData
&data
, const CssmData
&extraData
)
1316 StLock
<Mutex
>_(mMutex
);
1318 mDb
->recode(data
, extraData
);
1322 KeychainImpl::copyBlob(CssmData
&data
)
1324 StLock
<Mutex
>_(mMutex
);
1326 mDb
->copyBlob(data
);
1330 KeychainImpl::setBatchMode(Boolean mode
, Boolean rollback
)
1332 StLock
<Mutex
>_(mMutex
);
1334 mDb
->setBatchMode(mode
, rollback
);
1335 mIsInBatchMode
= mode
;
1338 if (!rollback
) // was batch mode being turned off without an abort?
1341 EventBuffer::iterator it
= mEventBuffer
->begin();
1342 while (it
!= mEventBuffer
->end())
1344 PrimaryKey primaryKey
;
1347 primaryKey
= it
->item
->primaryKey();
1350 KCEventNotifier::PostKeychainEvent(it
->kcEvent
, mDb
->dlDbIdentifier(), primaryKey
);
1357 // notify that a keychain has changed in too many ways to count
1358 KCEventNotifier::PostKeychainEvent((SecKeychainEvent
) kSecKeychainLeftBatchModeEvent
);
1359 mEventBuffer
->clear();
1363 KCEventNotifier::PostKeychainEvent((SecKeychainEvent
) kSecKeychainEnteredBatchModeEvent
);
1367 KeychainImpl::postEvent(SecKeychainEvent kcEvent
, ItemImpl
* item
)
1369 postEvent(kcEvent
, item
, NULL
);
1373 KeychainImpl::postEvent(SecKeychainEvent kcEvent
, ItemImpl
* item
, PrimaryKey pk
)
1375 PrimaryKey primaryKey
;
1380 StLock
<Mutex
>_(mMutex
);
1384 primaryKey
= item
->primaryKey();
1388 if (!mIsInBatchMode
)
1390 KCEventNotifier::PostKeychainEvent(kcEvent
, mDb
->dlDbIdentifier(), primaryKey
);
1394 StLock
<Mutex
>_(mMutex
);
1397 it
.kcEvent
= kcEvent
;
1403 mEventBuffer
->push_back (it
);
1407 void KeychainImpl::tickle() {
1408 if(!mSuppressTickle
) {
1409 globals().storageManager
.tickleKeychain(this);
1414 bool KeychainImpl::performKeychainUpgradeIfNeeded() {
1415 // Grab this keychain's mutex.
1416 StLock
<Mutex
>_(mMutex
);
1418 if(!globals().integrityProtection()) {
1419 secnotice("integrity", "skipping upgrade for %s due to global integrity protection being disabled", mDb
->name());
1423 // We need a CSP database for 'upgrade' to be meaningful
1424 if((mDb
->dl()->subserviceMask() & CSSM_SERVICE_CSP
) == 0) {
1428 // We only want to upgrade file-based Apple keychains. Check the GUID.
1429 if(mDb
->dl()->guid() != gGuidAppleCSPDL
) {
1430 secinfo("integrity", "skipping upgrade for %s due to guid mismatch\n", mDb
->name());
1434 // If we've already attempted an upgrade on this keychain, don't bother again
1435 if(mAttemptedUpgrade
) {
1439 // Don't upgrade the System root certificate keychain (to make old tp code happy)
1440 if(strncmp(mDb
->name(), SYSTEM_ROOT_STORE_PATH
, strlen(SYSTEM_ROOT_STORE_PATH
)) == 0) {
1441 secinfo("integrity", "skipping upgrade for %s\n", mDb
->name());
1445 uint32 dbBlobVersion
= SecurityServer::DbBlob::version_MacOS_10_0
;
1448 dbBlobVersion
= mDb
->dbBlobVersion();
1449 } catch (CssmError cssme
) {
1450 if(cssme
.error
== CSSMERR_DL_DATASTORE_DOESNOT_EXIST
) {
1451 // oh well! We tried to get the blob version of a database
1452 // that doesn't exist. It doesn't need migration, so do nothing.
1453 secnotice("integrity", "dbBlobVersion() failed for a non-existent database");
1456 // Some other error occurred. We can't upgrade this keychain, so fail.
1457 const char* errStr
= cssmErrorString(cssme
.error
);
1458 secnotice("integrity", "dbBlobVersion() failed for a CssmError: %d %s", (int) cssme
.error
, errStr
);
1462 secnotice("integrity", "dbBlobVersion() failed for an unknown reason");
1468 // Check the location of this keychain
1469 string path
= mDb
->name();
1470 string keychainDbPath
= StorageManager::makeKeychainDbFilename(path
);
1472 bool inHomeLibraryKeychains
= StorageManager::pathInHomeLibraryKeychains(path
);
1474 string keychainDbSuffix
= "-db";
1475 bool endsWithKeychainDb
= (path
.size() > keychainDbSuffix
.size() && (0 == path
.compare(path
.size() - keychainDbSuffix
.size(), keychainDbSuffix
.size(), keychainDbSuffix
)));
1477 bool isSystemKeychain
= (0 == path
.compare("/Library/Keychains/System.keychain"));
1479 bool result
= false;
1481 if(inHomeLibraryKeychains
&& endsWithKeychainDb
&& dbBlobVersion
== SecurityServer::DbBlob::version_MacOS_10_0
) {
1482 // something has gone horribly wrong: an old-versioned keychain has a .keychain-db name. Rename it.
1483 string basePath
= path
;
1484 basePath
.erase(basePath
.end()-3, basePath
.end());
1486 attemptKeychainRename(path
, basePath
, dbBlobVersion
);
1488 // If we moved to a good path, we might still want to perform the upgrade. Update our variables.
1492 dbBlobVersion
= mDb
->dbBlobVersion();
1493 } catch (CssmError cssme
) {
1494 const char* errStr
= cssmErrorString(cssme
.error
);
1495 secnotice("integrity", "dbBlobVersion() after a rename failed for a CssmError: %d %s", (int) cssme
.error
, errStr
);
1498 secnotice("integrity", "dbBlobVersion() failed for an unknown reason after a rename");
1502 endsWithKeychainDb
= (path
.size() > keychainDbSuffix
.size() && (0 == path
.compare(path
.size() - keychainDbSuffix
.size(), keychainDbSuffix
.size(), keychainDbSuffix
)));
1503 keychainDbPath
= StorageManager::makeKeychainDbFilename(path
);
1504 secnotice("integrity", "after rename, our database thinks that it is %s", path
.c_str());
1507 // Migrate an old keychain in ~/Library/Keychains
1508 if(inHomeLibraryKeychains
&& dbBlobVersion
!= SecurityServer::DbBlob::version_partition
&& !endsWithKeychainDb
) {
1509 // We can only attempt to migrate an unlocked keychain.
1510 if(mDb
->isLocked()) {
1511 // However, it's possible that while we weren't doing any keychain operations, someone upgraded the keychain,
1512 // and then locked it. No way around hitting the filesystem here: check for the existence of a new file and,
1513 // if no new file exists, quit.
1514 DLDbIdentifier mungedDLDbIdentifier
= StorageManager::mungeDLDbIdentifier(mDb
->dlDbIdentifier(), false);
1515 string
mungedPath(mungedDLDbIdentifier
.dbName());
1517 // If this matches the file we already have, skip the upgrade. Otherwise, continue.
1518 if(mungedPath
== path
) {
1519 secnotice("integrity", "skipping upgrade for locked keychain %s\n", mDb
->name());
1524 result
= keychainMigration(path
, dbBlobVersion
, keychainDbPath
, SecurityServer::DbBlob::version_partition
);
1525 } else if(inHomeLibraryKeychains
&& dbBlobVersion
== SecurityServer::DbBlob::version_partition
&& !endsWithKeychainDb
) {
1526 // This is a new-style keychain with the wrong name, try to rename it
1527 attemptKeychainRename(path
, keychainDbPath
, dbBlobVersion
);
1529 } else if(isSystemKeychain
&& dbBlobVersion
== SecurityServer::DbBlob::version_partition
) {
1530 // Try to "unupgrade" the system keychain, to clean up our old issues
1531 secnotice("integrity", "attempting downgrade for %s version %d (%d %d %d)", path
.c_str(), dbBlobVersion
, inHomeLibraryKeychains
, endsWithKeychainDb
, isSystemKeychain
);
1533 // First step: acquire the credentials to allow for ACL modification
1534 SecurityServer::SystemKeychainKey
skk(kSystemUnlockFile
);
1536 // We've managed to read the key; now, create credentials using it
1537 CssmClient::Key
systemKeychainMasterKey(csp(), skk
.key(), true);
1538 CssmClient::AclFactory::MasterKeyUnlockCredentials
creds(systemKeychainMasterKey
, Allocator::standard(Allocator::sensitive
));
1540 // Attempt the downgrade, using our master key as the ACL override
1541 result
= keychainMigration(path
, dbBlobVersion
, path
, SecurityServer::DbBlob::version_MacOS_10_0
, creds
.getAccessCredentials());
1543 secnotice("integrity", "Couldn't read System.keychain key, skipping update");
1546 secinfo("integrity", "not attempting migration for %s version %d (%d %d %d)", path
.c_str(), dbBlobVersion
, inHomeLibraryKeychains
, endsWithKeychainDb
, isSystemKeychain
);
1548 // Since we don't believe any migration needs to be done here, mark the
1549 // migration as "attempted" to short-circuit future checks.
1550 mAttemptedUpgrade
= true;
1553 // We might have changed our location on disk. Let StorageManager know.
1554 globals().storageManager
.registerKeychainImpl(this);
1556 // 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
1558 string pattern
= path
+ "_*_backup";
1560 secnotice("integrity", "globbing for %s", pattern
.c_str());
1561 int globresult
= glob(pattern
.c_str(), GLOB_MARK
, NULL
, &pglob
);
1562 if(globresult
== 0) {
1563 secnotice("integrity", "glob: %lu results", pglob
.gl_pathc
);
1564 if(pglob
.gl_pathc
> 10) {
1565 // There are more than 10 backup files, indicating a problem.
1566 // Delete all but one of them. Under rdar://23950408, they should all be identical.
1567 secnotice("integrity", "saving backup file: %s", pglob
.gl_pathv
[0]);
1568 for(int i
= 1; i
< pglob
.gl_pathc
; i
++) {
1569 secnotice("integrity", "cleaning up backup file: %s", pglob
.gl_pathv
[i
]);
1570 // ignore return code; this is a best-effort cleanup
1571 unlink(pglob
.gl_pathv
[i
]);
1576 bool pathExists
= (::stat(path
.c_str(), &st
) == 0);
1577 bool keychainDbPathExists
= (::stat(keychainDbPath
.c_str(), &st
) == 0);
1579 if(!pathExists
&& keychainDbPathExists
&& pglob
.gl_pathc
>= 1) {
1580 // We have a file at keychainDbPath, no file at path, and at least one backup keychain file.
1582 // Move the backup file to path, to simulate the current "split-world" view,
1583 // which copies from path to keychainDbPath, then modifies keychainDbPath.
1584 secnotice("integrity", "moving backup file %s to %s", pglob
.gl_pathv
[0], path
.c_str());
1585 ::rename(pglob
.gl_pathv
[0], path
.c_str());
1595 bool KeychainImpl::keychainMigration(const string oldPath
, const uint32 dbBlobVersion
, const string newPath
, const uint32 newBlobVersion
, const AccessCredentials
*cred
) {
1596 secnotice("integrity", "going to migrate %s at version %d to", oldPath
.c_str(), dbBlobVersion
);
1597 secnotice("integrity", " %s at version %d", newPath
.c_str(), newBlobVersion
);
1599 // We need to opportunistically perform the upgrade/reload dance.
1601 // If the keychain is unlocked, try to upgrade it.
1602 // In either case, reload the database from disk.
1604 // Try to grab the keychain mutex (although we should already have it)
1605 StLock
<Mutex
>_(mMutex
);
1607 // Take the file lock on the existing database. We don't need to commit this txion, because we're not planning to
1608 // change the original keychain.
1609 FileLockTransaction
fileLockmDb(mDb
);
1611 // Let's reload this keychain to see if someone changed it on disk
1612 globals().storageManager
.reloadKeychain(this);
1614 bool result
= false;
1617 // We can only attempt an upgrade if the keychain is currently unlocked
1618 // There's a TOCTTOU issue here, but it's going to be rare in practice, and the upgrade will simply fail.
1619 if(!mDb
->isLocked()) {
1620 secnotice("integrity", "have a plan to migrate database %s", mDb
->name());
1621 // Database blob is out of date. Attempt a migration.
1622 uint32 convertedVersion
= attemptKeychainMigration(oldPath
, dbBlobVersion
, newPath
, newBlobVersion
, cred
);
1623 if(convertedVersion
== newBlobVersion
) {
1624 secnotice("integrity", "conversion succeeded");
1627 secnotice("integrity", "conversion failed, keychain is still %d", convertedVersion
);
1630 secnotice("integrity", "keychain is locked, can't upgrade");
1632 } catch (CssmError cssme
) {
1633 const char* errStr
= cssmErrorString(cssme
.error
);
1634 secnotice("integrity", "caught CssmError: %d %s", (int) cssme
.error
, errStr
);
1636 // Something went wrong, but don't worry about it.
1637 secnotice("integrity", "caught unknown error");
1640 // No matter if the migrator succeeded, we need to reload this keychain from disk.
1641 secnotice("integrity", "reloading keychain after migration");
1642 globals().storageManager
.reloadKeychain(this);
1643 secnotice("integrity", "database %s is now version %d", mDb
->name(), mDb
->dbBlobVersion());
1648 // Make sure you have this keychain's mutex and write lock when you call this function!
1649 uint32
KeychainImpl::attemptKeychainMigration(const string oldPath
, const uint32 oldBlobVersion
, const string newPath
, const uint32 newBlobVersion
, const AccessCredentials
* cred
) {
1650 if(mDb
->dbBlobVersion() == newBlobVersion
) {
1651 // Someone else upgraded this, hurray!
1652 secnotice("integrity", "reloaded keychain version %d, quitting", mDb
->dbBlobVersion());
1653 return newBlobVersion
;
1656 mAttemptedUpgrade
= true;
1657 uint32 newDbVersion
= oldBlobVersion
;
1659 if( (oldBlobVersion
== SecurityServer::DbBlob::version_MacOS_10_0
&& newBlobVersion
== SecurityServer::DbBlob::version_partition
) ||
1660 (oldBlobVersion
== SecurityServer::DbBlob::version_partition
&& newBlobVersion
== SecurityServer::DbBlob::version_MacOS_10_0
&& cred
!= NULL
)) {
1661 // Here's the upgrade outline:
1663 // 1. Make a copy of the keychain with the new file path
1664 // 2. Open that keychain database.
1665 // 3. Recode it to use the new version.
1666 // 4. Notify the StorageManager that the DLDB identifier for this keychain has changed.
1668 // If we're creating a new keychain file, on failure, try to delete the new file. Otherwise,
1669 // everyone will try to use it.
1671 secnotice("integrity", "attempting migration from version %d to %d", oldBlobVersion
, newBlobVersion
);
1674 bool newFile
= (oldPath
!= newPath
);
1677 DLDbIdentifier
dldbi(dlDbIdentifier().ssuid(), newPath
.c_str(), dlDbIdentifier().dbLocation());
1679 secnotice("integrity", "creating a new keychain at %s", newPath
.c_str());
1680 db
= mDb
->cloneTo(dldbi
);
1682 secnotice("integrity", "using old keychain at %s", newPath
.c_str());
1685 FileLockTransaction
fileLockDb(db
);
1688 // since we're creating a completely new file, if this migration fails, delete the new file
1689 fileLockDb
.setDeleteOnFailure();
1692 // Let the upgrade begin.
1693 newDbVersion
= db
->recodeDbToVersion(newBlobVersion
);
1694 if(newDbVersion
!= newBlobVersion
) {
1695 // Recoding failed. Don't proceed.
1696 secnotice("integrity", "recodeDbToVersion failed, version is still %d", newDbVersion
);
1697 return newDbVersion
;
1700 secnotice("integrity", "recoded db successfully, adding extra integrity");
1702 Keychain
keychain(db
);
1704 // Breaking abstraction, but what're you going to do?
1705 // Don't upgrade this keychain, since we just upgraded the DB
1706 // But the DB won't return any new data until the txion commits
1707 keychain
->mAttemptedUpgrade
= true;
1708 keychain
->mSuppressTickle
= true;
1710 SecItemClass classes
[] = {kSecGenericPasswordItemClass
,
1711 kSecInternetPasswordItemClass
,
1712 kSecPublicKeyItemClass
,
1713 kSecPrivateKeyItemClass
,
1714 kSecSymmetricKeyItemClass
};
1716 for(int i
= 0; i
< sizeof(classes
) / sizeof(classes
[0]); i
++) {
1718 KCCursor kcc
= keychain
->createCursor(classes
[i
], NULL
);
1720 // During recoding, we might have deleted some corrupt keys.
1721 // Because of this, we might have zombie SSGroup records left in
1722 // the database that have no matching key. Tell the KCCursor to
1723 // delete these if found.
1724 // This will also try to suppress any other invalid items.
1725 kcc
->setDeleteInvalidRecords(true);
1727 while(kcc
->next(item
)) {
1729 if(newBlobVersion
== SecurityServer::DbBlob::version_partition
) {
1730 // Force the item to set integrity. The keychain is confused about its version because it hasn't written to disk yet,
1731 // but if we've reached this point, the keychain supports integrity.
1732 item
->setIntegrity(true);
1733 } else if(newBlobVersion
== SecurityServer::DbBlob::version_MacOS_10_0
) {
1734 // We're downgrading this keychain. Pass in whatever credentials our caller thinks will allow this ACL modification.
1735 item
->removeIntegrity(cred
);
1737 } catch(CssmError cssme
) {
1738 // During recoding, we might have deleted some corrupt keys. Because of this, we might have zombie SSGroup records left in
1739 // the database that have no matching key. If we get a DL_RECORD_NOT_FOUND error, delete the matching item record.
1740 if (cssme
.osStatus() == CSSMERR_DL_RECORD_NOT_FOUND
) {
1741 secnotice("integrity", "deleting corrupt (Not Found) record");
1742 keychain
->deleteItem(item
);
1743 } else if(cssme
.osStatus() == CSSMERR_CSP_INVALID_KEY
) {
1744 secnotice("integrity", "deleting corrupt key record");
1745 keychain
->deleteItem(item
);
1753 // Tell securityd we're done with the upgrade, to re-enable all protections
1754 db
->recodeFinished();
1756 // If we reach here, tell the file locks to commit the transaction and return the new blob version
1757 fileLockDb
.success();
1759 secnotice("integrity", "success, returning version %d", newDbVersion
);
1760 return newDbVersion
;
1761 } catch(UnixError ue
) {
1762 secnotice("integrity", "caught UnixError: %d %s", ue
.unixError(), ue
.what());
1763 } catch (CssmError cssme
) {
1764 const char* errStr
= cssmErrorString(cssme
.error
);
1765 secnotice("integrity", "caught CssmError: %d %s", (int) cssme
.error
, errStr
);
1766 } catch (MacOSError mose
) {
1767 secnotice("integrity", "MacOSError: %d", (int)mose
.osStatus());
1768 } catch (const std::bad_cast
& e
) {
1769 secnotice("integrity", "***** bad cast: %s", e
.what());
1771 // We failed to migrate. We won't commit the transaction, so the blob on-disk stays the same.
1772 secnotice("integrity", "***** unknown error");
1775 secnotice("integrity", "no migration path for %s at version %d to", oldPath
.c_str(), oldBlobVersion
);
1776 secnotice("integrity", " %s at version %d", newPath
.c_str(), newBlobVersion
);
1777 return oldBlobVersion
;
1780 // If we reached here, the migration failed. Return the old version.
1781 return oldBlobVersion
;
1784 void KeychainImpl::attemptKeychainRename(const string oldPath
, const string newPath
, uint32 blobVersion
) {
1785 secnotice("integrity", "attempting to rename keychain (%d) from %s to %s", blobVersion
, oldPath
.c_str(), newPath
.c_str());
1787 // Take the file lock on this database, so other people won't try to move it before we do
1788 // NOTE: during a migration from a v256 to a v512 keychain, the db is first copied from the .keychain to the
1789 // .keychain-db path. Other non-migrating processes, if they open the keychain, enter this function to
1790 // try to move it back. These will attempt to take the .keychain-db file lock, but they will not succeed
1791 // until the migration is finished. Once they acquire that, they might try to take the .keychain file lock.
1792 // This is technically lock inversion, but deadlocks will not happen since the migrating process creates the
1793 // .keychain-db file lock before creating the .keychain-db file, so other processes will not try to grab the
1794 // .keychain-db lock in this function before the migrating process already has it.
1795 FileLockTransaction
fileLockmDb(mDb
);
1797 // first, check if someone renamed this keychain while we were grabbing the file lock
1798 globals().storageManager
.reloadKeychain(this);
1800 uint32 dbBlobVersion
= SecurityServer::DbBlob::version_MacOS_10_0
;
1803 dbBlobVersion
= mDb
->dbBlobVersion();
1805 secnotice("integrity", "dbBlobVersion() failed for an unknown reason while renaming, aborting rename");
1809 if(dbBlobVersion
!= blobVersion
) {
1810 secnotice("integrity", "database version changed while we were grabbing the file lock; aborting rename");
1814 if(oldPath
!= mDb
->name()) {
1815 secnotice("integrity", "database location changed while we were grabbing the file lock; aborting rename");
1819 // we're still at the original location and version; go ahead and do the move
1820 globals().storageManager
.rename(this, newPath
.c_str());
1823 Keychain::Keychain()
1825 dispatch_once(&SecKeychainSystemKeychainChecked
, ^{
1826 check_system_keychain();
1830 Keychain::~Keychain()
1837 Keychain::optional(SecKeychainRef handle
)
1840 return KeychainImpl::required(handle
);
1842 return globals().storageManager
.defaultKeychain();
1846 CFIndex
KeychainCore::GetKeychainRetainCount(Keychain
& kc
)
1848 CFTypeRef ref
= kc
->handle(false);
1849 return CFGetRetainCount(ref
);
1854 // Create default credentials for this keychain.
1855 // This is triggered upon default open (i.e. a Db::activate() with no set credentials).
1857 // This function embodies the "default credentials" logic for Keychain-layer databases.
1859 const AccessCredentials
*
1860 KeychainImpl::makeCredentials()
1862 return defaultCredentials();
1866 const AccessCredentials
*
1867 KeychainImpl::defaultCredentials()
1869 StLock
<Mutex
>_(mMutex
);
1871 // Use custom unlock credentials for file keychains which have a referral
1872 // record and the standard credentials for all others.
1874 if (mDb
->dl()->guid() == gGuidAppleCSPDL
&& mCustomUnlockCreds(mDb
))
1875 return &mCustomUnlockCreds
;
1877 if (mDb
->dl()->guid() == gGuidAppleSdCSPDL
)
1878 return globals().smartcardCredentials();
1880 return globals().keychainCredentials();
1885 bool KeychainImpl::mayDelete()
1890 bool KeychainImpl::hasIntegrityProtection() {
1891 StLock
<Mutex
>_(mMutex
);
1893 // This keychain only supports integrity if there's a database attached, that database is an Apple CSPDL, and the blob version is high enough
1894 if(mDb
&& (mDb
->dl()->guid() == gGuidAppleCSPDL
)) {
1895 if(mDb
->dbBlobVersion() >= SecurityServer::DbBlob::version_partition
) {
1898 secnotice("integrity", "keychain blob version does not support integrity");
1902 secnotice("integrity", "keychain guid does not support integrity");