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
)
66 recordType(Schema::recordTypeFor(itemClass
));
68 if (!attrList
) // No additional selectionPredicates: we are done
71 conjunctive(dbConjunctive
);
72 const SecKeychainAttribute
*end
=&attrList
->attr
[attrList
->count
];
73 // Add all the attrs in attrs list to the cursor.
74 for (const SecKeychainAttribute
*attr
=attrList
->attr
; attr
!= end
; ++attr
)
76 const CSSM_DB_ATTRIBUTE_INFO
*temp
;
78 if (attr
->tag
<' ') // ok, is this a key schema? Handle differently, just because we can...
80 temp
= gKeyAttributeLookupTable
[attr
->tag
];
84 temp
= &Schema::attributeInfo(attr
->tag
);
86 const CssmDbAttributeInfo
&info
= *temp
;
87 void *buf
= attr
->data
;
88 UInt32 length
= attr
->length
;
91 // XXX This code is duplicated in NewItemImpl::setAttribute()
92 // Convert a 4 or 8 byte TIME_DATE to a CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE
93 // style attribute value.
94 if (info
.format() == CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE
)
96 if (length
== sizeof(UInt32
))
98 MacSecondsToTimeString(*reinterpret_cast<const UInt32
*>(buf
),
103 else if (length
== sizeof(SInt64
))
105 MacLongDateTimeToTimeString(*reinterpret_cast<const SInt64
*>(buf
),
111 add(dbOperator
,info
, CssmData(buf
,length
));
115 KCCursorImpl::KCCursorImpl(const StorageManager::KeychainList
&searchList
, const SecKeychainAttributeList
*attrList
) :
116 mSearchList(searchList
),
117 mCurrent(mSearchList
.begin()),
119 mDeleteInvalidRecords(false),
120 mIsNewKeychain(true),
121 mMutex(Mutex::recursive
)
123 if (!attrList
) // No additional selectionPredicates: we are done
126 conjunctive(CSSM_DB_AND
);
127 bool foundClassAttribute
=false;
128 const SecKeychainAttribute
*end
=&attrList
->attr
[attrList
->count
];
129 // Add all the attrs in attrs list to the cursor.
130 for (const SecKeychainAttribute
*attr
=attrList
->attr
; attr
!= end
; ++attr
)
132 if (attr
->tag
!=kSecClassItemAttr
) // a regular attribute
134 const CssmDbAttributeInfo
&info
= Schema::attributeInfo(attr
->tag
);
135 void *buf
= attr
->data
;
136 UInt32 length
= attr
->length
;
137 uint8 timeString
[16];
139 // XXX This code is duplicated in NewItemImpl::setAttribute()
140 // Convert a 4 or 8 byte TIME_DATE to a CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE
141 // style attribute value.
142 if (info
.format() == CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE
)
144 if (length
== sizeof(UInt32
))
146 MacSecondsToTimeString(*reinterpret_cast<const UInt32
*>(buf
),
151 else if (length
== sizeof(SInt64
))
153 MacLongDateTimeToTimeString(*reinterpret_cast<const SInt64
*>(buf
),
159 add(CSSM_DB_EQUAL
,info
, CssmData(buf
,length
));
164 // the class attribute
165 if (foundClassAttribute
|| attr
->length
!= sizeof(SecItemClass
))
166 MacOSError::throwMe(errSecParam
); // We have 2 different 'clas' attributes
168 recordType(Schema::recordTypeFor(*reinterpret_cast<SecItemClass
*>(attr
->data
)));
169 foundClassAttribute
=true;
173 KCCursorImpl::~KCCursorImpl() throw()
177 //static ModuleNexus<Mutex> gActivationMutex;
180 KCCursorImpl::next(Item
&item
)
182 StLock
<Mutex
>_(mMutex
);
183 DbAttributes dbAttributes
;
184 DbUniqueRecord uniqueId
;
189 Item tempItem
= NULL
;
193 // Do the newKeychain dance before we check our done status
194 newKeychain(mCurrent
);
196 if (mCurrent
== mSearchList
.end())
198 // If we got always failed when calling mDbCursor->next return the error from
199 // the last call to mDbCursor->next now
200 if (mAllFailed
&& status
)
201 CssmError::throwMe(status
);
203 // No more keychains to search so we are done.
209 // StLock<Mutex> _(gActivationMutex()); // force serialization of cursor creation
210 Keychain
&kc
= *mCurrent
;
211 Mutex
* mutex
= kc
->getKeychainMutex();
212 StLock
<Mutex
> _(*mutex
);
213 (*mCurrent
)->database()->activate();
214 mDbCursor
= DbCursor((*mCurrent
)->database(), *this);
216 catch(const CommonError
&err
)
219 mIsNewKeychain
= true;
223 Keychain
&kc
= *mCurrent
;
225 // Grab a read lock on the keychain
226 StReadWriteLock
__(*(kc
->getKeychainReadWriteLock()), StReadWriteLock::Read
);
228 Mutex
* mutex
= kc
->getKeychainMutex();
229 StLock
<Mutex
> _(*mutex
);
234 // Clear out existing attributes first!
235 // (the previous iteration may have left attributes from a different schema)
236 dbAttributes
.clear();
238 gotRecord
= mDbCursor
->next(&dbAttributes
, NULL
, uniqueId
);
241 catch(const CommonError
&err
)
243 // Catch the last error we get and move on to the next keychain
244 // This error will be returned when we reach the end of our keychain list
245 // iff all calls to KCCursorImpl::next failed
246 status
= err
.osStatus();
248 dbAttributes
.invalidate();
252 // Catch all other errors
253 status
= errSecItemNotFound
;
257 // If we did not get a record from the current keychain or the current
258 // keychain did not exist skip to the next keychain in the list.
262 mDbCursor
= DbCursor();
263 // we'd like to call newKeychain(mCurrent) here, but to avoid deadlock
264 // we need to drop the current keychain's mutex first. Use this silly
265 // hack to void the stack Mutex object.
266 mIsNewKeychain
= true;
270 // If doing a search for all records, skip the db blob added by the CSPDL
271 if (dbAttributes
.recordType() == CSSM_DL_DB_RECORD_METADATA
&&
272 mDbCursor
->recordType() == CSSM_DL_DB_RECORD_ANY
)
275 // Filter out group keys at this layer
276 if (dbAttributes
.recordType() == CSSM_DL_DB_RECORD_SYMMETRIC_KEY
)
278 bool groupKey
= false;
281 // fetch the key label attribute, if it exists
282 dbAttributes
.add(KeySchema::Label
);
283 Db
db((*mCurrent
)->database());
284 CSSM_RETURN getattr_result
= CSSM_DL_DataGetFromUniqueRecordId(db
->handle(), uniqueId
, &dbAttributes
, NULL
);
285 if (getattr_result
== CSSM_OK
)
287 CssmDbAttributeData
*label
= dbAttributes
.find(KeySchema::Label
);
291 if (attrData
.length() > 4 && !memcmp(attrData
.data(), "ssgp", 4))
296 dbAttributes
.invalidate();
306 // Go though Keychain since item might already exist.
307 // This might throw a CSSMERR_DL_RECORD_NOT_FOUND or be otherwise invalid. If we're supposed to delete these items, delete them...
309 tempItem
= (*mCurrent
)->item(dbAttributes
.recordType(), uniqueId
);
310 } catch(CssmError cssme
) {
311 if (mDeleteInvalidRecords
) {
312 // This is an invalid record for some reason; delete it and restart the loop
313 const char* errStr
= cssmErrorString(cssme
.error
);
314 secnotice("integrity", "deleting corrupt record because: %d %s", (int) cssme
.error
, errStr
);
316 deleteInvalidRecord(uniqueId
);
317 // if deleteInvalidRecord doesn't throw, we want to restart the loop
330 // If we reach here, we've found an item
334 void KCCursorImpl::deleteInvalidRecord(DbUniqueRecord
& uniqueId
) {
335 // This might throw a RECORD_NOT_FOUND. Handle that, because we don't care if we're trying to delete the item.
337 uniqueId
->deleteRecord();
338 } catch(CssmError delcssme
) {
339 if (delcssme
.osStatus() == CSSMERR_DL_RECORD_NOT_FOUND
) {
340 secnotice("integrity", "couldn't delete nonexistent record (this is okay)");
349 bool KCCursorImpl::mayDelete()
351 if (mDbCursor
.get() != NULL
)
353 return mDbCursor
->isIdle();
361 void KCCursorImpl::setDeleteInvalidRecords(bool deleteRecord
) {
362 mDeleteInvalidRecords
= deleteRecord
;
365 void KCCursorImpl::newKeychain(StorageManager::KeychainList::iterator kcIter
) {
366 if(!mIsNewKeychain
) {
367 // We've already been called on this keychain, don't bother.
371 if(kcIter
!= mSearchList
.end()) {
372 (*kcIter
)->performKeychainUpgradeIfNeeded();
376 // Mark down that this function has been called
377 mIsNewKeychain
= false;