2 * Copyright (c) 2000-2001,2011-2014 Apple Inc. All Rights Reserved.
4 * The contents of this file constitute Original Code as defined in and are
5 * subject to the Apple Public Source License Version 1.2 (the 'License').
6 * You may not use this file except in compliance with the License. Please obtain
7 * a copy of the License at http://www.apple.com/publicsource and read it before
10 * This Original Code and all software distributed under the License are
11 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS
12 * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT
13 * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
14 * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the
15 * specific language governing rights and limitations under the License.
20 // SSDatabase.cpp - Security Server database object
22 #include "SSDatabase.h"
24 #include <security_cdsa_utilities/KeySchema.h>
25 #include <security_utilities/CSPDLTransaction.h>
26 #include <Security/SecBasePriv.h>
28 using namespace CssmClient
;
29 using namespace SecurityServer
;
31 const char *const SSDatabaseImpl::DBBlobRelationName
= "DBBlob";
34 SSDatabaseImpl::SSDatabaseImpl(ClientSession
&inClientSession
, const CssmClient::DL
&dl
,
35 const char *inDbName
, const CSSM_NET_ADDRESS
*inDbLocation
)
36 : Db::Impl(dl
, inDbName
, inDbLocation
), mClientSession(inClientSession
), mSSDbHandle(noDb
)
41 SSDatabaseImpl::~SSDatabaseImpl()
44 if (mSSDbHandle
!= noDb
)
45 mClientSession
.releaseDb(mSSDbHandle
);
52 SSDatabaseImpl::ssInsert(CSSM_DB_RECORDTYPE recordType
,
53 const CSSM_DB_RECORD_ATTRIBUTE_DATA
*attributes
,
54 const CSSM_DATA
*data
)
56 SSUniqueRecord
uniqueId(SSDatabase(this));
57 check(CSSM_DL_DataInsert(handle(), recordType
,
60 // Activate uniqueId so CSSM_DL_FreeUniqueRecord() gets called when it goes out of scope.
66 SSDatabaseImpl::authenticate(CSSM_DB_ACCESS_TYPE inAccessRequest
,
67 const CSSM_ACCESS_CREDENTIALS
*inAccessCredentials
)
69 mClientSession
.authenticateDb(dbHandle(), inAccessRequest
,
70 AccessCredentials::overlay(inAccessCredentials
));
74 SSDatabaseImpl::lock()
76 mClientSession
.lock(dbHandle());
81 SSDatabaseImpl::unlock()
83 mClientSession
.unlock(dbHandle());
87 SSDatabaseImpl::unlock(const CSSM_DATA
&password
)
89 mClientSession
.unlock(dbHandle(), CssmData::overlay(password
));
93 SSDatabaseImpl::stash()
95 mClientSession
.stashDb(dbHandle());
99 SSDatabaseImpl::stashCheck()
101 mClientSession
.stashDbCheck(dbHandle());
105 SSDatabaseImpl::getSettings(uint32
&outIdleTimeout
, bool &outLockOnSleep
)
107 DBParameters parameters
;
108 mClientSession
.getDbParameters(dbHandle(), parameters
);
109 outIdleTimeout
= parameters
.idleTimeout
;
110 outLockOnSleep
= parameters
.lockOnSleep
;
114 SSDatabaseImpl::setSettings(uint32 inIdleTimeout
, bool inLockOnSleep
)
116 DBParameters parameters
;
117 parameters
.idleTimeout
= inIdleTimeout
;
118 parameters
.lockOnSleep
= inLockOnSleep
;
119 mClientSession
.setDbParameters(dbHandle(), parameters
);
121 // Reencode the db blob.
122 CssmDataContainer
dbb(allocator());
123 mClientSession
.encodeDb(mSSDbHandle
, dbb
, allocator());
124 getDbBlobId()->modify(DBBlobRelationID
, NULL
, &dbb
, CSSM_DB_MODIFY_ATTRIBUTE_NONE
);
128 SSDatabaseImpl::isLocked()
130 return mClientSession
.isLocked(dbHandle());
134 SSDatabaseImpl::changePassphrase(const CSSM_ACCESS_CREDENTIALS
*cred
)
136 mClientSession
.changePassphrase(dbHandle(), AccessCredentials::overlay(cred
));
138 // Reencode the db blob.
139 CssmDataContainer
dbb(allocator());
140 mClientSession
.encodeDb(mSSDbHandle
, dbb
, allocator());
141 getDbBlobId()->modify(DBBlobRelationID
, NULL
, &dbb
, CSSM_DB_MODIFY_ATTRIBUTE_NONE
);
145 SSDatabaseImpl::dbHandle()
149 // re-establish the dbHandle with the SecurityServer
150 CssmDataContainer
dbb(allocator());
152 mSSDbHandle
= mClientSession
.decodeDb(mIdentifier
,
153 AccessCredentials::overlay(accessCredentials()), dbb
);
159 SSDatabaseImpl::commonCreate(const DLDbIdentifier
&dlDbIdentifier
, bool &autoCommit
)
161 mIdentifier
= dlDbIdentifier
;
162 // Set to false if autocommit should remain off after the create.
165 // OpenParameters to use
166 CSSM_APPLEDL_OPEN_PARAMETERS newOpenParameters
=
168 sizeof(CSSM_APPLEDL_OPEN_PARAMETERS
),
169 CSSM_APPLEDL_OPEN_PARAMETERS_VERSION
,
170 CSSM_FALSE
, // do not auto-commit
171 0 // mask - do not use following fields
174 // Get the original openParameters and apply them to the ones we
176 const CSSM_APPLEDL_OPEN_PARAMETERS
*inOpenParameters
=
177 reinterpret_cast<const CSSM_APPLEDL_OPEN_PARAMETERS
*>(openParameters());
178 if (inOpenParameters
)
180 switch (inOpenParameters
->version
)
183 if (inOpenParameters
->length
< sizeof(CSSM_APPLEDL_OPEN_PARAMETERS
))
184 CssmError::throwMe(CSSMERR_APPLEDL_INVALID_OPEN_PARAMETERS
);
186 newOpenParameters
.mask
= inOpenParameters
->mask
;
187 newOpenParameters
.mode
= inOpenParameters
->mode
;
190 //if (inOpenParameters->length < sizeof(CSSM_APPLEDL_OPEN_PARAMETERS_V0))
191 // CssmError::throwMe(CSSMERR_APPLEDL_INVALID_OPEN_PARAMETERS);
193 // This will determine whether we leave autocommit off or not.
194 autoCommit
= inOpenParameters
->autoCommit
== CSSM_FALSE
? false : true;
198 CssmError::throwMe(CSSMERR_APPLEDL_INVALID_OPEN_PARAMETERS
);
202 // Use the new openParameters
203 openParameters(&newOpenParameters
);
207 // Restore the original openparameters again.
208 openParameters(inOpenParameters
);
212 // Make sure restore the original openparameters again even if
214 openParameters(inOpenParameters
);
218 // @@@ The CSSM_DB_SCHEMA_ATTRIBUTE_INFO and CSSM_DB_SCHEMA_INDEX_INFO
219 // arguments should be optional.
220 createRelation(DBBlobRelationID
, DBBlobRelationName
,
221 0, (CSSM_DB_SCHEMA_ATTRIBUTE_INFO
*)42,
222 0, (CSSM_DB_SCHEMA_INDEX_INFO
*)42);
224 // @@@ Only iff not already in mDbInfo
225 createRelation(CSSM_DL_DB_RECORD_PUBLIC_KEY
, "CSSM_DL_DB_RECORD_PUBLIC_KEY",
226 KeySchema::KeySchemaAttributeCount
, KeySchema::KeySchemaAttributeList
,
227 KeySchema::KeySchemaIndexCount
, KeySchema::KeySchemaIndexList
);
229 // @@@ Only iff not already in mDbInfo
230 createRelation(CSSM_DL_DB_RECORD_PRIVATE_KEY
, "CSSM_DL_DB_RECORD_PRIVATE_KEY",
231 KeySchema::KeySchemaAttributeCount
, KeySchema::KeySchemaAttributeList
,
232 KeySchema::KeySchemaIndexCount
, KeySchema::KeySchemaIndexList
);
234 // @@@ Only iff not already in mDbInfo
235 createRelation(CSSM_DL_DB_RECORD_SYMMETRIC_KEY
, "CSSM_DL_DB_RECORD_SYMMETRIC_KEY",
236 KeySchema::KeySchemaAttributeCount
, KeySchema::KeySchemaAttributeList
,
237 KeySchema::KeySchemaIndexCount
, KeySchema::KeySchemaIndexList
);
241 SSDatabaseImpl::ssCreate(const DLDbIdentifier
&dlDbIdentifier
)
246 commonCreate(dlDbIdentifier
, autoCommit
);
248 DBParameters dbParameters
;
249 memset(&dbParameters
, 0, sizeof(DBParameters
));
250 dbParameters
.idleTimeout
= kDefaultIdleTimeout
;
251 dbParameters
.lockOnSleep
= kDefaultLockOnSleep
;
253 const AccessCredentials
*cred
= NULL
;
254 const AclEntryInput
*owner
= NULL
;
255 if (resourceControlContext())
257 cred
= AccessCredentials::overlay(resourceControlContext()->AccessCred
);
258 owner
= &AclEntryInput::overlay(resourceControlContext()->InitialAclEntry
);
260 mSSDbHandle
= mClientSession
.createDb(dlDbIdentifier
, cred
, owner
, dbParameters
);
261 CssmDataContainer
dbb(allocator());
262 mClientSession
.encodeDb(mSSDbHandle
, dbb
, allocator());
263 secnotice("integrity", "opening %s", name());
264 Db::Impl::insert(DBBlobRelationID
, NULL
, &dbb
);
267 passThrough(CSSM_APPLEFILEDL_COMMIT
, NULL
);
268 passThrough(CSSM_APPLEFILEDL_TOGGLE_AUTOCOMMIT
,
269 reinterpret_cast<const void *>(1));
274 if (e
.error
!= CSSMERR_DL_DATASTORE_ALREADY_EXISTS
)
288 SSDatabaseImpl::ssCreateWithBlob(const DLDbIdentifier
&dlDbIdentifier
, const CSSM_DATA
&blob
)
293 commonCreate(dlDbIdentifier
, autoCommit
);
294 secnotice("integrity", "opening %s", name());
295 Db::Impl::insert(DBBlobRelationID
, NULL
, &blob
);
298 passThrough(CSSM_APPLEFILEDL_COMMIT
, NULL
);
299 passThrough(CSSM_APPLEFILEDL_TOGGLE_AUTOCOMMIT
,
300 reinterpret_cast<const void *>(1));
311 SSDatabaseImpl::ssOpen(const DLDbIdentifier
&dlDbIdentifier
)
313 load(dlDbIdentifier
);
315 CssmDataContainer
dbb(allocator());
318 // Pull our version out of the database blob
319 mSSDbHandle
= mClientSession
.decodeDb(dlDbIdentifier
, AccessCredentials::overlay(accessCredentials()), dbb
);
323 SSDatabaseImpl::load(const DLDbIdentifier
&dlDbIdentifier
) {
324 mIdentifier
= dlDbIdentifier
;
327 CssmDataContainer
dbb(allocator());
330 secnotice("integrity", "loading %s", name());
334 SSDatabaseImpl::ssRecode(const CssmData
&dbHandleArray
, const CssmData
&agentData
)
336 // Start a transaction (Implies activate()).
337 passThrough(CSSM_APPLEFILEDL_TOGGLE_AUTOCOMMIT
, 0);
341 CssmDataContainer
dbb(allocator());
342 // Make sure mSSDbHandle is valid.
343 CssmClient::DbUniqueRecord dbBlobId
= getDbBlobId(&dbb
);
345 // re-establish the dbHandle with the SecurityServer
346 mSSDbHandle
= mClientSession
.decodeDb(mIdentifier
,
347 AccessCredentials::overlay(accessCredentials()), dbb
);
351 DbHandle successfulHdl
= mClientSession
.authenticateDbsForSync(dbHandleArray
, agentData
);
353 // Create a newDbHandle using the master secrets from the dbBlob we are
355 SecurityServer::DbHandle clonedDbHandle
=
356 mClientSession
.recodeDbForSync(successfulHdl
, mSSDbHandle
);
358 // @@@ If the dbb changed since we fetched it we should abort or
359 // retry the operation here.
361 recodeHelper(clonedDbHandle
, dbBlobId
);
363 // Commit the transaction to the db
364 passThrough(CSSM_APPLEFILEDL_COMMIT
, NULL
);
365 passThrough(CSSM_APPLEFILEDL_TOGGLE_AUTOCOMMIT
,
366 reinterpret_cast<const void *>(1));
370 // Something went wrong rollback the transaction
371 passThrough(CSSM_APPLEFILEDL_ROLLBACK
, NULL
);
372 passThrough(CSSM_APPLEFILEDL_TOGGLE_AUTOCOMMIT
,
373 reinterpret_cast<const void *>(1));
379 SSDatabaseImpl::recodeDbToVersion(uint32 newBlobVersion
) {
380 // Start a transaction (Implies activate()).
381 DLTransaction
transaction(handle());
386 secnotice("integrity", "is currently locked");
388 secnotice("integrity", "is already unlocked");
391 CssmDataContainer
dbb(allocator());
392 // Make sure mSSDbHandle is valid.
393 CssmClient::DbUniqueRecord dbBlobId
= getDbBlobId(&dbb
);
395 // always establish the dbHandle with the SecurityServer
396 mSSDbHandle
= mClientSession
.decodeDb(mIdentifier
, AccessCredentials::overlay(accessCredentials()), dbb
);
399 // Create a newDbHandle using the master secrets from the dbBlob we are recoding to.
400 secnotice("integrity", "recoding db with handle %d", mSSDbHandle
);
401 SecurityServer::DbHandle clonedDbHandle
= mClientSession
.recodeDbToVersion(newBlobVersion
, mSSDbHandle
);
402 secnotice("integrity", "received db with handle %d", clonedDbHandle
);
404 // @@@ If the dbb changed since we fetched it we should abort or
405 // retry the operation here.
407 uint32 newBlobVersion
= recodeHelper(clonedDbHandle
, dbBlobId
);
408 secnotice("integrity", "committing transaction %d", clonedDbHandle
);
410 // Commit the transaction to the db
411 transaction
.commit();
412 return newBlobVersion
;
421 SSDatabaseImpl::recodeFinished() {
422 mClientSession
.recodeFinished(mSSDbHandle
);
425 void SSDatabaseImpl::takeFileLock() {
427 // you're already in the middle of a file lock.
430 mTransaction
= new DLTransaction(handle());
431 passThrough(CSSM_APPLEFILEDL_TAKE_FILE_LOCK
, NULL
, NULL
);
434 void SSDatabaseImpl::releaseFileLock(bool success
) {
438 mTransaction
->commit();
440 // If we didn't commit, the destructor will roll back and re-enable autocommit
450 void SSDatabaseImpl::makeBackup() {
451 passThrough(CSSM_APPLEFILEDL_MAKE_BACKUP
, NULL
, NULL
);
454 void SSDatabaseImpl::makeCopy(const char* path
) {
455 passThrough(CSSM_APPLEFILEDL_MAKE_COPY
, path
, NULL
);
458 void SSDatabaseImpl::deleteFile() {
459 passThrough(CSSM_APPLEFILEDL_DELETE_FILE
, NULL
, NULL
);
462 SSDatabase
SSDatabaseImpl::ssCloneTo(const DLDbIdentifier
& dldbidentifier
) {
463 makeCopy(dldbidentifier
.dbName());
464 SSDatabase
db(mClientSession
, dl(), dldbidentifier
.dbName(), dldbidentifier
.dbLocation());
466 db
->load(dldbidentifier
);
467 db
->mSSDbHandle
= mClientSession
.cloneDb(dldbidentifier
, mSSDbHandle
);
474 uint32
SSDatabaseImpl::recodeHelper(SecurityServer::DbHandle clonedDbHandle
, CssmClient::DbUniqueRecord
& dbBlobId
) {
476 DbCursor
cursor(SSDatabase(this));
477 cursor
->recordType(CSSM_DL_DB_RECORD_ALL_KEYS
);
478 CssmDataContainer
keyBlob(allocator());
479 CssmClient::DbUniqueRecord keyBlobId
;
480 DbAttributes attributes
;
481 while (cursor
->next(&attributes
, &keyBlob
, keyBlobId
))
483 KeyHandle keyHandle
= 0;
485 // Decode the old key
486 CssmKey::Header header
;
487 keyHandle
= mClientSession
.decodeKey(mSSDbHandle
, keyBlob
, header
);
489 CssmDataContainer
newKeyBlob(mClientSession
.returnAllocator
);
490 mClientSession
.recodeKey(mSSDbHandle
, keyHandle
, clonedDbHandle
, newKeyBlob
);
491 mClientSession
.releaseKey(keyHandle
);
493 // Write the recoded key blob to the database
494 keyBlobId
->modify(attributes
.recordType(), NULL
, &newKeyBlob
,
495 CSSM_DB_MODIFY_ATTRIBUTE_NONE
);
496 } catch (CssmError cssme
) {
497 const char* errStr
= cssmErrorString(cssme
.error
);
498 secnotice("integrity", "corrupt item while recoding: %d %s", (int) cssme
.error
, errStr
);
499 secnotice("integrity", "deleting corrupt item");
502 keyBlobId
->deleteRecord();
505 // tell securityd not to worry about this key again
507 secnotice("integrity", "releasing corrupt key");
508 mClientSession
.releaseKey(keyHandle
);
509 } catch(CssmError cssme
) {
511 const char* errStr
= cssmErrorString(cssme
.error
);
512 secnotice("integrity", "couldn't release corrupt key: %d %s", (int) cssme
.error
, errStr
);
518 // Commit the new blob to securityd, reencode the db blob, release the
519 // cloned db handle and commit the new blob to the db.
520 CssmDataContainer
dbb(allocator());
521 secnotice("integrity", "committing %d", clonedDbHandle
);
522 mClientSession
.commitDbForSync(mSSDbHandle
, clonedDbHandle
,
524 dbBlobId
->modify(DBBlobRelationID
, NULL
, &dbb
,
525 CSSM_DB_MODIFY_ATTRIBUTE_NONE
);
526 return getDbVersionFromBlob(dbb
);
530 void SSDatabaseImpl::getRecordIdentifier(CSSM_DB_UNIQUE_RECORD_PTR uniqueRecord
, CSSM_DATA
&recordID
)
532 // the unique ID is composed of three uint32s (plus one filler word). Pull
533 // them out and byte swap them
534 recordID
.Length
= sizeof (uint32
) * kNumIDWords
;
535 recordID
.Data
= (uint8
*) allocator().malloc(recordID
.Length
);
538 uint32
* dest
= (uint32
*) recordID
.Data
;
539 uint32
* src
= (uint32
*) uniqueRecord
->RecordIdentifier
.Data
;
541 dest
[0] = htonl (src
[0]);
542 dest
[1] = htonl (src
[1]);
543 dest
[2] = htonl (src
[2]);
547 void SSDatabaseImpl::ssCopyBlob(CSSM_DATA
& data
)
549 // get the blob from the database
550 CssmDataContainer
dbb(allocator());
553 // copy the data back
554 data
.Data
= dbb
.Data
;
555 data
.Length
= dbb
.Length
;
557 // zap the return structure so that we don't get zapped when dbb goes out of scope...
563 SSDatabaseImpl::dbBlobVersion() {
564 CssmDataContainer
dbb(allocator());
566 return getDbVersionFromBlob(dbb
);
570 SSDatabaseImpl::getDbVersionFromBlob(const CssmData
& dbb
) {
571 DbBlob
* x
= Allocator::standard().malloc
<DbBlob
>(dbb
.length());
572 memcpy(x
, dbb
, dbb
.length());
573 uint32 version
= x
->version();
574 Allocator::standard().free(x
);
579 SSDatabaseImpl::newDbUniqueRecord()
581 return new SSUniqueRecordImpl(SSDatabase(this));
584 CssmClient::DbUniqueRecord
585 SSDatabaseImpl::getDbBlobId(CssmDataContainer
*dbb
)
587 CssmClient::DbUniqueRecord dbBlobId
;
589 DbCursor
cursor(SSDatabase(this));
590 cursor
->recordType(DBBlobRelationID
);
591 if (!cursor
->next(NULL
, dbb
, dbBlobId
))
592 CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT
);
599 SSUniqueRecordImpl::SSUniqueRecordImpl(const SSDatabase
&db
)
600 : DbUniqueRecord::Impl(db
)
604 SSUniqueRecordImpl::~SSUniqueRecordImpl()
609 SSUniqueRecordImpl::database() const
611 return parent
<SSDatabase
>();