]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_keychain/lib/KCCursor.cpp
d6b6e3326219c9c1b2f1d5a7b9fbb3d51811906e
[apple/security.git] / OSX / libsecurity_keychain / lib / KCCursor.cpp
1 /*
2 * Copyright (c) 2000-2004,2011-2014 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
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
11 * file.
12 *
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.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24
25 //
26 // KCCursor.cpp
27 //
28
29 #include "KCCursor.h"
30
31 #include "Item.h"
32 #include <security_cdsa_utilities/Schema.h>
33 #include <security_cdsa_utilities/KeySchema.h>
34 #include "cssmdatetime.h"
35 #include "Globals.h"
36 #include "StorageManager.h"
37 #include <Security/SecKeychainItemPriv.h>
38 #include <SecBase.h>
39 #include <Security/SecBasePriv.h>
40
41 using namespace KeychainCore;
42 using namespace CssmClient;
43 using namespace CSSMDateTimeUtils;
44
45 using namespace KeySchema;
46
47 // define a table of our attributes for easy lookup
48 static const CSSM_DB_ATTRIBUTE_INFO* gKeyAttributeLookupTable[] =
49 {
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
53 };
54
55 //
56 // KCCursorImpl
57 //
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()),
61 mAllFailed(true),
62 mDeleteInvalidRecords(false),
63 mIsNewKeychain(true),
64 mMutex(Mutex::recursive)
65 {
66 recordType(Schema::recordTypeFor(itemClass));
67
68 if (!attrList) // No additional selectionPredicates: we are done
69 return;
70
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)
75 {
76 const CSSM_DB_ATTRIBUTE_INFO *temp;
77
78 if (attr->tag <' ') // ok, is this a key schema? Handle differently, just because we can...
79 {
80 temp = gKeyAttributeLookupTable[attr->tag];
81 }
82 else
83 {
84 temp = &Schema::attributeInfo(attr->tag);
85 }
86 const CssmDbAttributeInfo &info = *temp;
87 void *buf = attr->data;
88 UInt32 length = attr->length;
89 uint8 timeString[16];
90
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)
95 {
96 if (length == sizeof(UInt32))
97 {
98 MacSecondsToTimeString(*reinterpret_cast<const UInt32 *>(buf),
99 16, &timeString);
100 buf = &timeString;
101 length = 16;
102 }
103 else if (length == sizeof(SInt64))
104 {
105 MacLongDateTimeToTimeString(*reinterpret_cast<const SInt64 *>(buf),
106 16, &timeString);
107 buf = &timeString;
108 length = 16;
109 }
110 }
111 add(dbOperator ,info, CssmData(buf,length));
112 }
113 }
114
115 KCCursorImpl::KCCursorImpl(const StorageManager::KeychainList &searchList, const SecKeychainAttributeList *attrList) :
116 mSearchList(searchList),
117 mCurrent(mSearchList.begin()),
118 mAllFailed(true),
119 mDeleteInvalidRecords(false),
120 mIsNewKeychain(true),
121 mMutex(Mutex::recursive)
122 {
123 if (!attrList) // No additional selectionPredicates: we are done
124 return;
125
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)
131 {
132 if (attr->tag!=kSecClassItemAttr) // a regular attribute
133 {
134 const CssmDbAttributeInfo &info = Schema::attributeInfo(attr->tag);
135 void *buf = attr->data;
136 UInt32 length = attr->length;
137 uint8 timeString[16];
138
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)
143 {
144 if (length == sizeof(UInt32))
145 {
146 MacSecondsToTimeString(*reinterpret_cast<const UInt32 *>(buf),
147 16, &timeString);
148 buf = &timeString;
149 length = 16;
150 }
151 else if (length == sizeof(SInt64))
152 {
153 MacLongDateTimeToTimeString(*reinterpret_cast<const SInt64 *>(buf),
154 16, &timeString);
155 buf = &timeString;
156 length = 16;
157 }
158 }
159 add(CSSM_DB_EQUAL,info, CssmData(buf,length));
160
161 continue;
162 }
163
164 // the class attribute
165 if (foundClassAttribute || attr->length != sizeof(SecItemClass))
166 MacOSError::throwMe(errSecParam); // We have 2 different 'clas' attributes
167
168 recordType(Schema::recordTypeFor(*reinterpret_cast<SecItemClass *>(attr->data)));
169 foundClassAttribute=true;
170 }
171 }
172
173 KCCursorImpl::~KCCursorImpl() throw()
174 {
175 }
176
177 //static ModuleNexus<Mutex> gActivationMutex;
178
179 bool
180 KCCursorImpl::next(Item &item)
181 {
182 StLock<Mutex>_(mMutex);
183 DbAttributes dbAttributes;
184 DbUniqueRecord uniqueId;
185 OSStatus status = 0;
186
187 for (;;)
188 {
189 Item tempItem = NULL;
190 {
191 while (!mDbCursor)
192 {
193 // Do the newKeychain dance before we check our done status
194 newKeychain(mCurrent);
195
196 if (mCurrent == mSearchList.end())
197 {
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);
202
203 // No more keychains to search so we are done.
204 return false;
205 }
206
207 try
208 {
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);
215 }
216 catch(const CommonError &err)
217 {
218 ++mCurrent;
219 mIsNewKeychain = true;
220 }
221 }
222
223 Keychain &kc = *mCurrent;
224
225 // Grab a read lock on the keychain
226 StReadWriteLock __(*(kc->getKeychainReadWriteLock()), StReadWriteLock::Read);
227
228 Mutex* mutex = kc->getKeychainMutex();
229 StLock<Mutex> _(*mutex);
230
231 bool gotRecord;
232 try
233 {
234 // Clear out existing attributes first!
235 // (the previous iteration may have left attributes from a different schema)
236 dbAttributes.clear();
237
238 gotRecord = mDbCursor->next(&dbAttributes, NULL, uniqueId);
239 mAllFailed = false;
240 }
241 catch(const CommonError &err)
242 {
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();
247 gotRecord = false;
248 dbAttributes.invalidate();
249 }
250 catch(...)
251 {
252 // Catch all other errors
253 status = errSecItemNotFound;
254 gotRecord = false;
255 }
256
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.
259 if (!gotRecord)
260 {
261 ++mCurrent;
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;
267 continue;
268 }
269
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)
273 continue;
274
275 // Filter out group keys at this layer
276 if (dbAttributes.recordType() == CSSM_DL_DB_RECORD_SYMMETRIC_KEY)
277 {
278 bool groupKey = false;
279 try
280 {
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)
286 {
287 CssmDbAttributeData *label = dbAttributes.find(KeySchema::Label);
288 CssmData attrData;
289 if (label)
290 attrData = *label;
291 if (attrData.length() > 4 && !memcmp(attrData.data(), "ssgp", 4))
292 groupKey = true;
293 }
294 else
295 {
296 dbAttributes.invalidate();
297 }
298 }
299 catch (...) {}
300
301 if (groupKey)
302 continue;
303 }
304
305 // Create the Item
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...
308 try {
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);
315
316 deleteInvalidRecord(uniqueId);
317 // if deleteInvalidRecord doesn't throw, we want to restart the loop
318 continue;
319 } else {
320 throw;
321 }
322 }
323 }
324
325 item = tempItem;
326
327 break;
328 }
329
330 // If we reach here, we've found an item
331 return true;
332 }
333
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.
336 try {
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)");
341 } else {
342 throw;
343 }
344 }
345 }
346
347
348
349 bool KCCursorImpl::mayDelete()
350 {
351 if (mDbCursor.get() != NULL)
352 {
353 return mDbCursor->isIdle();
354 }
355 else
356 {
357 return true;
358 }
359 }
360
361 void KCCursorImpl::setDeleteInvalidRecords(bool deleteRecord) {
362 mDeleteInvalidRecords = deleteRecord;
363 }
364
365 void KCCursorImpl::newKeychain(StorageManager::KeychainList::iterator kcIter) {
366 if(!mIsNewKeychain) {
367 // We've already been called on this keychain, don't bother.
368 return;
369 }
370
371 if(kcIter != mSearchList.end()) {
372 (*kcIter)->performKeychainUpgradeIfNeeded();
373 (*kcIter)->tickle();
374 }
375
376 // Mark down that this function has been called
377 mIsNewKeychain = false;
378 }