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@
32 #include <security_cdsa_utilities/Schema.h>
33 #include <security_cdsa_utilities/KeySchema.h>
34 #include "cssmdatetime.h"
36 #include "StorageManager.h"
37 #include <Security/SecKeychainItemPriv.h>
39 #include <Security/SecBasePriv.h>
41 using namespace KeychainCore
;
42 using namespace CssmClient
;
43 using namespace CSSMDateTimeUtils
;
45 using namespace KeySchema
;
47 // define a table of our attributes for easy lookup
48 static const CSSM_DB_ATTRIBUTE_INFO
* gKeyAttributeLookupTable
[] =
50 &KeyClass
, &PrintName
, &Alias
, &Permanent
, &Private
, &Modifiable
, &Label
, &ApplicationTag
, &KeyCreator
,
51 &KeyType
, &KeySizeInBits
, &EffectiveKeySize
, &StartDate
, &EndDate
, &Sensitive
, &AlwaysSensitive
, &Extractable
,
52 &NeverExtractable
, &Encrypt
, &Decrypt
, &Derive
, &Sign
, &Verify
, &SignRecover
, &VerifyRecover
, &Wrap
, &Unwrap
58 KCCursorImpl::KCCursorImpl(const StorageManager::KeychainList
&searchList
, SecItemClass itemClass
, const SecKeychainAttributeList
*attrList
, CSSM_DB_CONJUNCTIVE dbConjunctive
, CSSM_DB_OPERATOR dbOperator
) :
59 mSearchList(searchList
),
60 mCurrent(mSearchList
.begin()),
62 mDeleteInvalidRecords(false),
64 mMutex(Mutex::recursive
),
65 mKeychainReadLock(NULL
)
67 recordType(Schema::recordTypeFor(itemClass
));
69 if (!attrList
) // No additional selectionPredicates: we are done
72 conjunctive(dbConjunctive
);
73 const SecKeychainAttribute
*end
=&attrList
->attr
[attrList
->count
];
74 // Add all the attrs in attrs list to the cursor.
75 for (const SecKeychainAttribute
*attr
=attrList
->attr
; attr
!= end
; ++attr
)
77 const CSSM_DB_ATTRIBUTE_INFO
*temp
;
79 if (attr
->tag
<' ') // ok, is this a key schema? Handle differently, just because we can...
81 temp
= gKeyAttributeLookupTable
[attr
->tag
];
85 temp
= &Schema::attributeInfo(attr
->tag
);
87 const CssmDbAttributeInfo
&info
= *temp
;
88 void *buf
= attr
->data
;
89 UInt32 length
= attr
->length
;
92 // XXX This code is duplicated in NewItemImpl::setAttribute()
93 // Convert a 4 or 8 byte TIME_DATE to a CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE
94 // style attribute value.
95 if (info
.format() == CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE
)
97 if (length
== sizeof(UInt32
))
99 MacSecondsToTimeString(*reinterpret_cast<const UInt32
*>(buf
),
104 else if (length
== sizeof(SInt64
))
106 MacLongDateTimeToTimeString(*reinterpret_cast<const SInt64
*>(buf
),
112 add(dbOperator
,info
, CssmData(buf
,length
));
116 KCCursorImpl::KCCursorImpl(const StorageManager::KeychainList
&searchList
, const SecKeychainAttributeList
*attrList
) :
117 mSearchList(searchList
),
118 mCurrent(mSearchList
.begin()),
120 mDeleteInvalidRecords(false),
121 mIsNewKeychain(true),
122 mMutex(Mutex::recursive
),
123 mKeychainReadLock(NULL
)
125 if (!attrList
) // No additional selectionPredicates: we are done
128 conjunctive(CSSM_DB_AND
);
129 bool foundClassAttribute
=false;
130 const SecKeychainAttribute
*end
=&attrList
->attr
[attrList
->count
];
131 // Add all the attrs in attrs list to the cursor.
132 for (const SecKeychainAttribute
*attr
=attrList
->attr
; attr
!= end
; ++attr
)
134 if (attr
->tag
!=kSecClassItemAttr
) // a regular attribute
136 const CssmDbAttributeInfo
&info
= Schema::attributeInfo(attr
->tag
);
137 void *buf
= attr
->data
;
138 UInt32 length
= attr
->length
;
139 uint8 timeString
[16];
141 // XXX This code is duplicated in NewItemImpl::setAttribute()
142 // Convert a 4 or 8 byte TIME_DATE to a CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE
143 // style attribute value.
144 if (info
.format() == CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE
)
146 if (length
== sizeof(UInt32
))
148 MacSecondsToTimeString(*reinterpret_cast<const UInt32
*>(buf
),
153 else if (length
== sizeof(SInt64
))
155 MacLongDateTimeToTimeString(*reinterpret_cast<const SInt64
*>(buf
),
161 add(CSSM_DB_EQUAL
,info
, CssmData(buf
,length
));
166 // the class attribute
167 if (foundClassAttribute
|| attr
->length
!= sizeof(SecItemClass
))
168 MacOSError::throwMe(errSecParam
); // We have 2 different 'clas' attributes
170 recordType(Schema::recordTypeFor(*reinterpret_cast<SecItemClass
*>(attr
->data
)));
171 foundClassAttribute
=true;
175 KCCursorImpl::~KCCursorImpl() throw()
177 if(mKeychainReadLock
) {
178 delete mKeychainReadLock
;
182 //static ModuleNexus<Mutex> gActivationMutex;
185 KCCursorImpl::next(Item
&item
)
187 StLock
<Mutex
>_(mMutex
);
188 DbAttributes dbAttributes
;
189 DbUniqueRecord uniqueId
;
194 Item tempItem
= NULL
;
198 // Do the newKeychain dance before we check our done status
199 newKeychain(mCurrent
);
201 if (mCurrent
== mSearchList
.end())
203 // If we got always failed when calling mDbCursor->next return the error from
204 // the last call to mDbCursor->next now
205 if (mAllFailed
&& status
)
206 CssmError::throwMe(status
);
208 // No more keychains to search so we are done.
214 // StLock<Mutex> _(gActivationMutex()); // force serialization of cursor creation
215 Keychain
&kc
= *mCurrent
;
216 Mutex
* mutex
= kc
->getKeychainMutex();
217 StLock
<Mutex
> _(*mutex
);
218 (*mCurrent
)->database()->activate();
219 mDbCursor
= DbCursor((*mCurrent
)->database(), *this);
221 catch(const CommonError
&err
)
224 mIsNewKeychain
= true;
228 Keychain
&kc
= *mCurrent
;
229 Mutex
* mutex
= kc
->getKeychainMutex();
230 StLock
<Mutex
> _(*mutex
);
235 // Clear out existing attributes first!
236 // (the previous iteration may have left attributes from a different schema)
237 dbAttributes
.clear();
239 gotRecord
= mDbCursor
->next(&dbAttributes
, NULL
, uniqueId
);
242 catch(const CommonError
&err
)
244 // Catch the last error we get and move on to the next keychain
245 // This error will be returned when we reach the end of our keychain list
246 // iff all calls to KCCursorImpl::next failed
247 status
= err
.osStatus();
249 dbAttributes
.invalidate();
253 // Catch all other errors
254 status
= errSecItemNotFound
;
258 // If we did not get a record from the current keychain or the current
259 // keychain did not exist skip to the next keychain in the list.
263 mDbCursor
= DbCursor();
264 // we'd like to call newKeychain(mCurrent) here, but to avoid deadlock
265 // we need to drop the current keychain's mutex first. Use this silly
266 // hack to void the stack Mutex object.
267 mIsNewKeychain
= true;
271 // If doing a search for all records, skip the db blob added by the CSPDL
272 if (dbAttributes
.recordType() == CSSM_DL_DB_RECORD_METADATA
&&
273 mDbCursor
->recordType() == CSSM_DL_DB_RECORD_ANY
)
276 // Filter out group keys at this layer
277 if (dbAttributes
.recordType() == CSSM_DL_DB_RECORD_SYMMETRIC_KEY
)
279 bool groupKey
= false;
282 // fetch the key label attribute, if it exists
283 dbAttributes
.add(KeySchema::Label
);
284 Db
db((*mCurrent
)->database());
285 CSSM_RETURN getattr_result
= CSSM_DL_DataGetFromUniqueRecordId(db
->handle(), uniqueId
, &dbAttributes
, NULL
);
286 if (getattr_result
== CSSM_OK
)
288 CssmDbAttributeData
*label
= dbAttributes
.find(KeySchema::Label
);
292 if (attrData
.length() > 4 && !memcmp(attrData
.data(), "ssgp", 4))
297 dbAttributes
.invalidate();
307 // Go though Keychain since item might already exist.
308 // This might throw a CSSMERR_DL_RECORD_NOT_FOUND or be otherwise invalid. If we're supposed to delete these items, delete them...
310 tempItem
= (*mCurrent
)->item(dbAttributes
.recordType(), uniqueId
);
311 } catch(CssmError cssme
) {
312 if (mDeleteInvalidRecords
) {
313 // This is an invalid record for some reason; delete it and restart the loop
314 const char* errStr
= cssmErrorString(cssme
.error
);
315 secnotice("integrity", "deleting corrupt record because: %d %s", (int) cssme
.error
, errStr
);
317 deleteInvalidRecord(uniqueId
);
318 // if deleteInvalidRecord doesn't throw, we want to restart the loop
325 // release the Keychain lock before checking item integrity to avoid deadlock
332 // If we reach here, we've found an item
336 void KCCursorImpl::deleteInvalidRecord(DbUniqueRecord
& uniqueId
) {
337 // This might throw a RECORD_NOT_FOUND. Handle that, because we don't care if we're trying to delete the item.
339 uniqueId
->deleteRecord();
340 } catch(CssmError delcssme
) {
341 if (delcssme
.osStatus() == CSSMERR_DL_RECORD_NOT_FOUND
) {
342 secnotice("integrity", "couldn't delete nonexistent record (this is okay)");
351 bool KCCursorImpl::mayDelete()
353 if (mDbCursor
.get() != NULL
)
355 return mDbCursor
->isIdle();
363 void KCCursorImpl::setDeleteInvalidRecords(bool deleteRecord
) {
364 mDeleteInvalidRecords
= deleteRecord
;
367 void KCCursorImpl::newKeychain(StorageManager::KeychainList::iterator kcIter
) {
368 if(!mIsNewKeychain
) {
369 // We've already been called on this keychain, don't bother.
373 // Always lose the last keychain's lock
374 if(mKeychainReadLock
) {
375 delete mKeychainReadLock
;
376 mKeychainReadLock
= NULL
;
379 if(kcIter
!= mSearchList
.end()) {
380 (*kcIter
)->performKeychainUpgradeIfNeeded();
383 // Grab a read lock on the keychain
384 mKeychainReadLock
= new StReadWriteLock(*((*kcIter
)->getKeychainReadWriteLock()), StReadWriteLock::Read
);
387 // Mark down that this function has been called
388 mIsNewKeychain
= false;