2 * Copyright (c) 2000-2008 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@
26 // kcdatabase - software database container implementation.
28 // General implementation notes:
29 // This leverages LocalDatabase/LocalKey for cryptography, and adds the
30 // storage coder/decoder logic that implements "keychain" databases in their
31 // intricately choreographed dance between securityd and the AppleCSPDL.
32 // As always, Database objects are lifetime-bound to their Process referent;
33 // they can also be destroyed explicitly with a client release call.
34 // DbCommons are reference-held by their Databases, with one extra special
35 // reference (from the Session) introduced when the database unlocks, and
36 // removed when it locks again. That way, an unused DbCommon dies when it
37 // is locked or when the Session dies, whichever happens earlier.
38 // There is (as yet) no global-scope Database object for Keychain databases.
40 #include "kcdatabase.h"
41 #include "agentquery.h"
45 #include "notifications.h"
46 #include <vector> // @@@ 4003540 workaround
47 #include <security_agent_client/agentclient.h>
48 #include <security_cdsa_utilities/acl_any.h> // for default owner ACLs
49 #include <security_cdsa_utilities/cssmendian.h>
50 #include <security_cdsa_client/wrapkey.h>
51 #include <security_cdsa_client/genkey.h>
52 #include <security_cdsa_client/signclient.h>
53 #include <security_cdsa_client/cryptoclient.h>
54 #include <security_cdsa_client/macclient.h>
55 #include <securityd_client/dictionary.h>
56 #include <security_utilities/endian.h>
57 #include "securityd_service/securityd_service/securityd_service_client.h"
58 #include <AssertMacros.h>
61 void unflattenKey(const CssmData
&flatKey
, CssmKey
&rawKey
); //>> make static method on KeychainDatabase
64 unlock_keybag(KeychainDbCommon
& dbCommon
, const void * secret
, int secret_len
)
68 if (!dbCommon
.isLoginKeychain()) return 0;
70 service_context_t context
= dbCommon
.session().get_current_service_context();
72 // try to unlock first if not found then load/create or unlock
73 // loading should happen when the kb common object is created
74 // if it doesn't exist yet then the unlock will fail and we'll create everything
75 rc
= service_client_kb_unlock(&context
, secret
, secret_len
);
76 if (rc
== KB_BagNotLoaded
) {
77 if (service_client_kb_load(&context
) == KB_BagNotFound
) {
78 rc
= service_client_kb_create(&context
, secret
, secret_len
);
80 rc
= service_client_kb_unlock(&context
, secret
, secret_len
);
84 if (rc
!= 0) { // if we just upgraded make sure we swap the encryption key to the password
85 if (!dbCommon
.session().keybagGetState(session_keybag_check_master_key
)) {
86 CssmAutoData
encKey(Allocator::standard(Allocator::sensitive
));
87 dbCommon
.get_encryption_key(encKey
);
88 if ((rc
= service_client_kb_unlock(&context
, encKey
.data(), (int)encKey
.length())) == 0) {
89 rc
= service_client_kb_change_secret(&context
, encKey
.data(), (int)encKey
.length(), secret
, secret_len
);
93 CssmAutoData
masterKey(Allocator::standard(Allocator::sensitive
));
94 masterKey
= dbCommon
.masterKey()->keyData();
95 if ((rc
= service_client_kb_unlock(&context
, masterKey
.data(), (int)masterKey
.length())) == 0) {
96 rc
= service_client_kb_change_secret(&context
, masterKey
.data(), (int)masterKey
.length(), secret
, secret_len
);
100 if (rc
!= 0) { // if a login.keychain password exists but doesnt on the keybag update it
102 if ((secret_len
> 0) && service_client_kb_is_locked(&context
, NULL
, &no_pin
) == 0) {
104 syslog(LOG_ERR
, "Updating iCloud keychain passphrase for uid %d", dbCommon
.session().originatorUid());
105 service_client_kb_change_secret(&context
, NULL
, 0, secret
, secret_len
);
109 } // session_keybag_check_master_key
113 dbCommon
.session().keybagSetState(session_keybag_unlocked
|session_keybag_loaded
|session_keybag_check_master_key
);
115 syslog(LOG_ERR
, "Failed to unlock iCloud keychain for uid %d", dbCommon
.session().originatorUid());
122 change_secret_on_keybag(KeychainDbCommon
& dbCommon
, const void * secret
, int secret_len
, const void * new_secret
, int new_secret_len
)
124 if (!dbCommon
.isLoginKeychain()) return;
126 service_context_t context
= dbCommon
.session().get_current_service_context();
128 // if a login.keychain doesn't exist yet it comes into securityd as a create then change_secret
129 // we need to create the keybag in this case if it doesn't exist
130 if (service_client_kb_change_secret(&context
, secret
, secret_len
, new_secret
, new_secret_len
) == KB_BagNotLoaded
) {
131 if (service_client_kb_load(&context
) == KB_BagNotFound
) {
132 service_client_kb_create(&context
, new_secret
, new_secret_len
);
138 // Create a Database object from initial parameters (create operation)
140 KeychainDatabase::KeychainDatabase(const DLDbIdentifier
&id
, const DBParameters
¶ms
, Process
&proc
,
141 const AccessCredentials
*cred
, const AclEntryPrototype
*owner
)
142 : LocalDatabase(proc
), mValidData(false), mSecret(Allocator::standard(Allocator::sensitive
)), mSaveSecret(false), version(0), mBlob(NULL
)
144 // save a copy of the credentials for later access control
145 mCred
= DataWalkers::copy(cred
, Allocator::standard());
147 // create a new random signature to complete the DLDbIdentifier
148 DbBlob::Signature newSig
;
149 Server::active().random(newSig
.bytes
);
150 DbIdentifier
ident(id
, newSig
);
152 // create common block and initialize
153 RefPointer
<KeychainDbCommon
> newCommon
= new KeychainDbCommon(proc
.session(), ident
);
154 StLock
<Mutex
> _(*newCommon
);
156 // new common is now visible (in ident-map) but we hold its lock
158 // establish the new master secret
159 establishNewSecrets(cred
, SecurityAgent::newDatabase
);
161 // set initial database parameters
162 common().mParams
= params
;
164 // the common is "unlocked" now
165 common().makeNewSecrets();
167 // establish initial ACL
169 acl().cssmSetInitial(*owner
);
171 acl().cssmSetInitial(new AnyAclSubject());
174 // for now, create the blob immediately
177 proc
.addReference(*this);
179 // this new keychain is unlocked; make it so
182 SECURITYD_KEYCHAIN_CREATE(&common(), (char*)this->dbName(), this);
187 // Create a Database object from a database blob (decoding)
189 KeychainDatabase::KeychainDatabase(const DLDbIdentifier
&id
, const DbBlob
*blob
, Process
&proc
,
190 const AccessCredentials
*cred
)
191 : LocalDatabase(proc
), mValidData(false), mSecret(Allocator::standard(Allocator::sensitive
)), mSaveSecret(false), version(0), mBlob(NULL
)
195 // save a copy of the credentials for later access control
196 mCred
= DataWalkers::copy(cred
, Allocator::standard());
197 mBlob
= blob
->copy();
199 // check to see if we already know about this database
200 DbIdentifier
ident(id
, blob
->randomSignature
);
201 Session
&session
= process().session();
202 StLock
<Mutex
> _(session
);
203 if (KeychainDbCommon
*dbcom
=
204 session
.findFirst
<KeychainDbCommon
, const DbIdentifier
&>(&KeychainDbCommon::identifier
, ident
)) {
206 //@@@ arbitrate sequence number here, perhaps update common().mParams
207 SECURITYD_KEYCHAIN_JOIN(&common(), (char*)this->dbName(), this);
209 // DbCommon not present; make a new one
210 parent(*new KeychainDbCommon(proc
.session(), ident
));
211 common().mParams
= blob
->params
;
212 SECURITYD_KEYCHAIN_MAKE(&common(), (char*)this->dbName(), this);
213 // this DbCommon is locked; no timer or reference setting
215 proc
.addReference(*this);
221 // Special-purpose constructor for keychain synchronization. Copies an
222 // existing keychain but uses the operational keys from secretsBlob. The
223 // new KeychainDatabase will silently replace the existing KeychainDatabase
224 // as soon as the client declares that re-encoding of all keychain items is
225 // finished. This is a little perilous since it allows a client to dictate
226 // securityd state, but we try to ensure that only the client that started
227 // the re-encoding can declare it done.
229 KeychainDatabase::KeychainDatabase(KeychainDatabase
&src
, Process
&proc
, DbHandle dbToClone
)
230 : LocalDatabase(proc
), mValidData(false), mSecret(Allocator::standard(Allocator::sensitive
)), mSaveSecret(false), version(0), mBlob(NULL
)
232 mCred
= DataWalkers::copy(src
.mCred
, Allocator::standard());
234 // Give this KeychainDatabase a temporary name
235 std::string newDbName
= std::string("////") + std::string(src
.identifier().dbName());
236 DLDbIdentifier
newDLDbIdent(src
.identifier().dlDbIdentifier().ssuid(), newDbName
.c_str(), src
.identifier().dlDbIdentifier().dbLocation());
237 DbIdentifier
ident(newDLDbIdent
, src
.identifier());
239 // create common block and initialize
240 RefPointer
<KeychainDbCommon
> newCommon
= new KeychainDbCommon(proc
.session(), ident
);
241 StLock
<Mutex
> _(*newCommon
);
244 // set initial database parameters from the source keychain
245 common().mParams
= src
.common().mParams
;
247 // establish the source keychain's master secret as ours
248 // @@@ NB: this is a v. 0.1 assumption. We *should* trigger new UI
249 // that offers the user the option of using the existing password
250 // or choosing a new one. That would require a new
251 // SecurityAgentQuery type, new UI, and--possibly--modifications to
252 // ensure that the new password is available here to generate the
253 // new master secret.
254 src
.unlockDb(); // precaution for masterKey()
255 common().setup(src
.blob(), src
.common().masterKey());
257 // import the operational secrets
258 RefPointer
<KeychainDatabase
> srcKC
= Server::keychain(dbToClone
);
259 common().importSecrets(srcKC
->common());
261 // import source keychain's ACL
262 CssmData pubAcl
, privAcl
;
263 src
.acl().exportBlob(pubAcl
, privAcl
);
264 importBlob(pubAcl
.data(), privAcl
.data());
265 src
.acl().allocator
.free(pubAcl
);
266 src
.acl().allocator
.free(privAcl
);
268 // indicate that this keychain should be allowed to do some otherwise
269 // risky things required for copying, like re-encoding keys
270 mRecodingSource
= &src
;
272 common().setUnlocked();
277 proc
.addReference(*this);
278 secdebug("SSdb", "database %s(%p) created as copy, common at %p",
279 common().dbName(), this, &common());
283 // Destroy a Database
285 KeychainDatabase::~KeychainDatabase()
287 secdebug("KCdb", "deleting database %s(%p) common %p",
288 common().dbName(), this, &common());
289 Allocator::standard().free(mCred
);
290 Allocator::standard().free(mBlob
);
295 // Basic Database virtual implementations
297 KeychainDbCommon
&KeychainDatabase::common() const
299 return parent
<KeychainDbCommon
>();
302 const char *KeychainDatabase::dbName() const
304 return common().dbName();
307 bool KeychainDatabase::transient() const
309 return false; // has permanent store
312 AclKind
KeychainDatabase::aclKind() const
317 Database
*KeychainDatabase::relatedDatabase()
323 static inline KeychainKey
&myKey(Key
*key
)
325 return *safe_cast
<KeychainKey
*>(key
);
330 // (Re-)Authenticate the database. This changes the stored credentials.
332 void KeychainDatabase::authenticate(CSSM_DB_ACCESS_TYPE mode
,
333 const AccessCredentials
*cred
)
335 StLock
<Mutex
> _(common());
337 // the (Apple specific) RESET bit means "lock the database now"
339 case CSSM_DB_ACCESS_RESET
:
340 secdebug("KCdb", "%p ACCESS_RESET triggers keychain lock", this);
344 // store the new credentials for future use
345 secdebug("KCdb", "%p authenticate stores new database credentials", this);
346 AccessCredentials
*newCred
= DataWalkers::copy(cred
, Allocator::standard());
347 Allocator::standard().free(mCred
);
354 // Make a new KeychainKey.
355 // If PERMANENT is off, make a temporary key instead.
356 // The db argument allows you to create for another KeychainDatabase (only);
357 // it defaults to ourselves.
359 RefPointer
<Key
> KeychainDatabase::makeKey(Database
&db
, const CssmKey
&newKey
,
360 uint32 moreAttributes
, const AclEntryPrototype
*owner
)
363 if (moreAttributes
& CSSM_KEYATTR_PERMANENT
)
364 return new KeychainKey(db
, newKey
, moreAttributes
, owner
);
366 return process().makeTemporaryKey(newKey
, moreAttributes
, owner
);
369 RefPointer
<Key
> KeychainDatabase::makeKey(const CssmKey
&newKey
,
370 uint32 moreAttributes
, const AclEntryPrototype
*owner
)
372 return makeKey(*this, newKey
, moreAttributes
, owner
);
377 // Return the database blob, recalculating it as needed.
379 DbBlob
*KeychainDatabase::blob()
381 StLock
<Mutex
> _(common());
383 makeUnlocked(); // unlock to get master secret
384 encode(); // (re)encode blob if needed
386 activity(); // reset timeout
387 assert(validBlob()); // better have a valid blob now...
393 // Encode the current database as a blob.
394 // Note that this returns memory we own and keep.
395 // Caller must hold common lock.
397 void KeychainDatabase::encode()
399 DbBlob
*blob
= common().encode(*this);
400 Allocator::standard().free(mBlob
);
402 version
= common().version
;
403 secdebug("KCdb", "encoded database %p common %p(%s) version %u params=(%u,%u)",
404 this, &common(), dbName(), version
,
405 common().mParams
.idleTimeout
, common().mParams
.lockOnSleep
);
410 // Change the passphrase on a database
412 void KeychainDatabase::changePassphrase(const AccessCredentials
*cred
)
414 // get and hold the common lock (don't let other threads break in here)
415 StLock
<Mutex
> _(common());
417 // establish OLD secret - i.e. unlock the database
418 //@@@ do we want to leave the final lock state alone?
419 if (common().isLoginKeychain()) mSaveSecret
= true;
422 // establish NEW secret
423 establishNewSecrets(cred
, SecurityAgent::changePassphrase
);
424 if (mSecret
) { mSecret
.reset(); }
426 common().invalidateBlob(); // blob state changed
427 secdebug("KCdb", "Database %s(%p) master secret changed", common().dbName(), this);
428 encode(); // force rebuild of local blob
430 // send out a notification
431 notify(kNotificationEventPassphraseChanged
);
433 // I guess this counts as an activity
438 // Second stage of keychain synchronization: overwrite the original keychain's
439 // (this KeychainDatabase's) operational secrets
441 void KeychainDatabase::commitSecretsForSync(KeychainDatabase
&cloneDb
)
443 StLock
<Mutex
> _(common());
445 // try to detect spoofing
446 if (cloneDb
.mRecodingSource
!= this)
447 CssmError::throwMe(CSSM_ERRCODE_INVALID_DB_HANDLE
);
449 // in case we autolocked since starting the sync
450 makeUnlocked(); // call this because we already own the lock
451 cloneDb
.unlockDb(); // we may not own the lock here, so calling unlockDb will lock the cloneDb's common lock
453 // Decode all keys whose handles refer to this on-disk keychain so that
454 // if the holding client commits the key back to disk, it's encoded with
455 // the new operational secrets. The recoding client *must* hold a write
456 // lock for the on-disk keychain from the moment it starts recoding key
457 // items until after this call.
459 // @@@ This specific implementation is a workaround for 4003540.
460 std::vector
<U32HandleObject::Handle
> handleList
;
461 U32HandleObject::findAllRefs
<KeychainKey
>(handleList
);
462 size_t count
= handleList
.size();
464 for (unsigned int n
= 0; n
< count
; ++n
) {
465 RefPointer
<KeychainKey
> kckey
=
466 U32HandleObject::findRefAndLock
<KeychainKey
>(handleList
[n
], CSSMERR_CSP_INVALID_KEY_REFERENCE
);
467 StLock
<Mutex
> _(*kckey
/*, true*/);
468 if (kckey
->database().global().identifier() == identifier()) {
469 kckey
->key(); // force decode
470 kckey
->invalidateBlob();
471 secdebug("kcrecode", "changed extant key %p (proc %d)",
472 &*kckey
, kckey
->process().pid());
477 // it is now safe to replace the old op secrets
478 common().importSecrets(cloneDb
.common());
479 common().invalidateBlob();
484 // Extract the database master key as a proper Key object.
486 RefPointer
<Key
> KeychainDatabase::extractMasterKey(Database
&db
,
487 const AccessCredentials
*cred
, const AclEntryPrototype
*owner
,
488 uint32 usage
, uint32 attrs
)
490 // get and hold common lock
491 StLock
<Mutex
> _(common());
493 // force lock to require re-validation of credentials
496 // unlock to establish master secret
499 // extract the raw cryptographic key
500 CssmClient::WrapKey
wrap(Server::csp(), CSSM_ALGID_NONE
);
502 wrap(common().masterKey(), key
);
504 // make the key object and return it
505 return makeKey(db
, key
, attrs
& LocalKey::managedAttributes
, owner
);
510 // Unlock this database (if needed) by obtaining the master secret in some
511 // suitable way and then proceeding to unlock with it.
512 // Does absolutely nothing if the database is already unlocked.
513 // The makeUnlocked forms are identical except the assume the caller already
514 // holds the common lock.
516 void KeychainDatabase::unlockDb()
518 StLock
<Mutex
> _(common());
522 void KeychainDatabase::makeUnlocked()
524 return makeUnlocked(mCred
);
527 void KeychainDatabase::makeUnlocked(const AccessCredentials
*cred
)
530 secdebug("KCdb", "%p(%p) unlocking for makeUnlocked()", this, &common());
531 assert(mBlob
|| (mValidData
&& common().hasMaster()));
532 establishOldSecrets(cred
);
533 common().setUnlocked(); // mark unlocked
534 } else if (common().isLoginKeychain()) {
536 service_context_t context
= common().session().get_current_service_context();
537 if ((service_client_kb_is_locked(&context
, &locked
, NULL
) == 0) && locked
) {
538 StSyncLock
<Mutex
, Mutex
> uisync(common().uiLock(), common());
539 QueryKeybagPassphrase
keybagQuery(common().session(), 3);
540 keybagQuery
.inferHints(Server::process());
541 if (keybagQuery
.query() != SecurityAgent::noReason
) {
542 syslog(LOG_NOTICE
, "failed to unlock iCloud keychain");
546 if (!mValidData
) { // need to decode to get our ACLs, master secret available
547 secdebug("KCdb", "%p(%p) is unlocked; decoding for makeUnlocked()", this, &common());
549 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED
);
556 // Invoke the securityd_service to retrieve the keychain master
557 // key from the AppleFDEKeyStore.
559 void KeychainDatabase::stashDbCheck()
561 CssmAutoData
masterKey(Allocator::standard(Allocator::sensitive
));
562 CssmAutoData
encKey(Allocator::standard(Allocator::sensitive
));
566 void * stash_key
= NULL
;
567 int stash_key_len
= 0;
568 service_context_t context
= common().session().get_current_service_context();
569 rc
= service_client_stash_get_key(&context
, &stash_key
, &stash_key_len
);
572 masterKey
.copy(CssmData((void *)stash_key
,stash_key_len
));
573 memset(stash_key
, 0, stash_key_len
);
577 CssmError::throwMe(rc
);
581 StLock
<Mutex
> _(common());
583 // Now establish it as the keychain master key
584 CssmClient::Key
key(Server::csp(), masterKey
.get());
585 CssmKey::Header
&hdr
= key
.header();
586 hdr
.keyClass(CSSM_KEYCLASS_SESSION_KEY
);
587 hdr
.algorithm(CSSM_ALGID_3DES_3KEY_EDE
);
588 hdr
.usage(CSSM_KEYUSE_ANY
);
589 hdr
.blobType(CSSM_KEYBLOB_RAW
);
590 hdr
.blobFormat(CSSM_KEYBLOB_RAW_FORMAT_OCTET_STRING
);
591 common().setup(mBlob
, key
);
594 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED
);
596 common().get_encryption_key(encKey
);
599 // when upgrading from pre-10.9 create a keybag if it doesn't exist with the encryption key
600 // only do this after we have verified the master key unlocks the login.keychain
601 if (service_client_kb_load(&context
) == KB_BagNotFound
) {
602 service_client_kb_create(&context
, encKey
.data(), (int)encKey
.length());
607 // Get the keychain master key and invoke the securityd_service
608 // to stash it in the AppleFDEKeyStore ready for commit to the
611 void KeychainDatabase::stashDb()
613 CssmAutoData
data(Allocator::standard(Allocator::sensitive
));
616 StLock
<Mutex
> _(common());
618 if (!common().isValid()) {
619 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY
);
622 CssmKey key
= common().masterKey();
623 data
.copy(key
.keyData());
626 service_context_t context
= common().session().get_current_service_context();
627 int rc
= service_client_stash_set_key(&context
, data
.data(), (int)data
.length());
628 if (rc
!= 0) CssmError::throwMe(rc
);
632 // The following unlock given an explicit passphrase, rather than using
633 // (special cred sample based) default procedures.
635 void KeychainDatabase::unlockDb(const CssmData
&passphrase
)
637 StLock
<Mutex
> _(common());
638 makeUnlocked(passphrase
);
641 void KeychainDatabase::makeUnlocked(const CssmData
&passphrase
)
644 if (decode(passphrase
))
647 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED
);
648 } else if (!mValidData
) { // need to decode to get our ACLs, passphrase available
650 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED
);
653 if (common().isLoginKeychain()) {
655 service_context_t context
= common().session().get_current_service_context();
656 if (!common().session().keybagGetState(session_keybag_check_master_key
) || ((service_client_kb_is_locked(&context
, &locked
, NULL
) == 0) && locked
)) {
657 unlock_keybag(common(), passphrase
.data(), (int)passphrase
.length());
667 // Nonthrowing passphrase-based unlock. This returns false if unlock failed.
668 // Note that this requires an explicitly given passphrase.
669 // Caller must hold common lock.
671 bool KeychainDatabase::decode(const CssmData
&passphrase
)
674 common().setup(mBlob
, passphrase
);
675 bool success
= decode();
676 if (success
&& common().isLoginKeychain()) {
677 unlock_keybag(common(), passphrase
.data(), (int)passphrase
.length());
684 // Given the established master secret, decode the working keys and other
685 // functional secrets for this database. Return false (do NOT throw) if
686 // the decode fails. Call this in low(er) level code once you established
689 bool KeychainDatabase::decode()
692 assert(common().hasMaster());
693 void *privateAclBlob
;
694 if (common().unlockDb(mBlob
, &privateAclBlob
)) {
696 acl().importBlob(mBlob
->publicAclBlob(), privateAclBlob
);
699 Allocator::standard().free(privateAclBlob
);
702 secdebug("KCdb", "%p decode failed", this);
708 // Given an AccessCredentials for this database, wring out the existing primary
709 // database secret by whatever means necessary.
710 // On entry, caller must hold the database common lock. It will be held
711 // throughout except when user interaction is required. User interaction
712 // requires relinquishing the database common lock and taking the UI lock. On
713 // return from user interaction, the UI lock is relinquished and the database
714 // common lock must be reacquired. At no time may the caller hold both locks.
715 // On exit, the crypto core has its master secret. If things go wrong,
716 // we will throw a suitable exception. Note that encountering any malformed
717 // credential sample will throw, but this is not guaranteed -- don't assume
718 // that NOT throwing means creds is entirely well-formed (it may just be good
719 // enough to work THIS time).
722 // Walk through the creds. Fish out those credentials (in order) that
723 // are for unlock processing (they have no ACL subject correspondents),
724 // and (try to) obey each in turn, until one produces a valid secret
725 // or you run out. If no special samples are found at all, interpret that as
726 // "use the system global default," which happens to be hard-coded right here.
728 void KeychainDatabase::establishOldSecrets(const AccessCredentials
*creds
)
730 bool forSystem
= this->belongsToSystem(); // this keychain belongs to the system security domain
732 // attempt system-keychain unlock
734 SystemKeychainKey
systemKeychain(kSystemUnlockFile
);
735 if (systemKeychain
.matches(mBlob
->randomSignature
)) {
736 secdebug("KCdb", "%p attempting system unlock", this);
737 common().setup(mBlob
, CssmClient::Key(Server::csp(), systemKeychain
.key(), true));
743 list
<CssmSample
> samples
;
744 if (creds
&& creds
->samples().collect(CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK
, samples
)) {
745 for (list
<CssmSample
>::iterator it
= samples
.begin(); it
!= samples
.end(); it
++) {
746 TypedList
&sample
= *it
;
747 sample
.checkProper();
748 switch (sample
.type()) {
749 // interactively prompt the user - no additional data
750 case CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT
:
752 if (interactiveUnlock())
756 // try to use an explicitly given passphrase - Data:passphrase
757 case CSSM_SAMPLE_TYPE_PASSWORD
:
758 if (sample
.length() != 2)
759 CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE
);
760 secdebug("KCdb", "%p attempting passphrase unlock", this);
761 if (decode(sample
[1]))
764 // try to open with a given master key - Data:CSP or KeyHandle, Data:CssmKey
765 case CSSM_SAMPLE_TYPE_SYMMETRIC_KEY
:
766 case CSSM_SAMPLE_TYPE_ASYMMETRIC_KEY
:
768 secdebug("KCdb", "%p attempting explicit key unlock", this);
769 common().setup(mBlob
, keyFromCreds(sample
, 4));
773 // explicitly defeat the default action but don't try anything in particular
774 case CSSM_WORDID_CANCELED
:
775 secdebug("KCdb", "%p defeat default action", this);
778 // Unknown sub-sample for unlocking.
779 // If we wanted to be fascist, we could now do
780 // CssmError::throwMe(CSSM_ERRCODE_SAMPLE_VALUE_NOT_SUPPORTED);
781 // But instead we try to be tolerant and continue on.
782 // This DOES however count as an explicit attempt at specifying unlock,
783 // so we will no longer try the default case below...
784 secdebug("KCdb", "%p unknown sub-sample unlock (%d) ignored", this, sample
.type());
793 if (interactiveUnlock())
798 // out of options - no secret obtained
799 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED
);
802 bool KeychainDatabase::interactiveUnlock()
804 secdebug("KCdb", "%p attempting interactive unlock", this);
805 SecurityAgent::Reason reason
= SecurityAgent::noReason
;
806 QueryUnlock
query(*this);
807 // take UI interlock and release DbCommon lock (to avoid deadlocks)
808 StSyncLock
<Mutex
, Mutex
> uisync(common().uiLock(), common());
810 // now that we have the UI lock, interact unless another thread unlocked us first
812 query
.inferHints(Server::process());
814 if (mSaveSecret
&& reason
== SecurityAgent::noReason
) {
815 query
.retrievePassword(mSecret
);
819 secdebug("KCdb", "%p was unlocked during uiLock delay", this);
822 if (common().isLoginKeychain()) {
824 service_context_t context
= common().session().get_current_service_context();
825 if ((service_client_kb_is_locked(&context
, &locked
, NULL
) == 0) && locked
) {
826 QueryKeybagNewPassphrase
keybagQuery(common().session());
827 keybagQuery
.inferHints(Server::process());
828 CssmAutoData
pass(Allocator::standard(Allocator::sensitive
));
829 CssmAutoData
oldPass(Allocator::standard(Allocator::sensitive
));
830 SecurityAgent::Reason queryReason
= keybagQuery
.query(oldPass
, pass
);
831 if (queryReason
== SecurityAgent::noReason
) {
832 service_client_kb_change_secret(&context
, oldPass
.data(), (int)oldPass
.length(), pass
.data(), (int)pass
.length());
833 } else if (queryReason
== SecurityAgent::resettingPassword
) {
834 query
.retrievePassword(pass
);
835 service_client_kb_reset(&context
, pass
.data(), (int)pass
.length());
841 return reason
== SecurityAgent::noReason
;
846 // Same thing, but obtain a new secret somehow and set it into the common.
848 void KeychainDatabase::establishNewSecrets(const AccessCredentials
*creds
, SecurityAgent::Reason reason
)
850 list
<CssmSample
> samples
;
851 if (creds
&& creds
->samples().collect(CSSM_SAMPLE_TYPE_KEYCHAIN_CHANGE_LOCK
, samples
)) {
852 for (list
<CssmSample
>::iterator it
= samples
.begin(); it
!= samples
.end(); it
++) {
853 TypedList
&sample
= *it
;
854 sample
.checkProper();
855 switch (sample
.type()) {
856 // interactively prompt the user
857 case CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT
:
859 secdebug("KCdb", "%p specified interactive passphrase", this);
860 QueryNewPassphrase
query(*this, reason
);
861 StSyncLock
<Mutex
, Mutex
> uisync(common().uiLock(), common());
862 query
.inferHints(Server::process());
863 CssmAutoData
passphrase(Allocator::standard(Allocator::sensitive
));
864 CssmAutoData
oldPassphrase(Allocator::standard(Allocator::sensitive
));
865 if (query(oldPassphrase
, passphrase
) == SecurityAgent::noReason
) {
866 common().setup(NULL
, passphrase
);
867 change_secret_on_keybag(common(), oldPassphrase
.data(), (int)oldPassphrase
.length(), passphrase
.data(), (int)passphrase
.length());
872 // try to use an explicitly given passphrase
873 case CSSM_SAMPLE_TYPE_PASSWORD
:
875 secdebug("KCdb", "%p specified explicit passphrase", this);
876 if (sample
.length() != 2)
877 CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE
);
878 common().setup(NULL
, sample
[1]);
879 if (common().isLoginKeychain()) {
880 CssmAutoData
oldPassphrase(Allocator::standard(Allocator::sensitive
));
881 list
<CssmSample
> oldSamples
;
882 creds
->samples().collect(CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK
, oldSamples
);
883 for (list
<CssmSample
>::iterator oit
= oldSamples
.begin(); oit
!= oldSamples
.end(); oit
++) {
884 TypedList
&tmpList
= *oit
;
885 tmpList
.checkProper();
886 if (tmpList
.type() == CSSM_SAMPLE_TYPE_PASSWORD
) {
887 if (tmpList
.length() == 2) {
888 oldPassphrase
= tmpList
[1].data();
892 if (!oldPassphrase
.length() && mSecret
&& mSecret
.length()) {
893 oldPassphrase
= mSecret
;
895 change_secret_on_keybag(common(), oldPassphrase
.data(), (int)oldPassphrase
.length(), sample
[1].data().data(), (int)sample
[1].data().length());
899 // try to open with a given master key
900 case CSSM_WORDID_SYMMETRIC_KEY
:
901 case CSSM_SAMPLE_TYPE_ASYMMETRIC_KEY
:
902 secdebug("KCdb", "%p specified explicit master key", this);
903 common().setup(NULL
, keyFromCreds(sample
, 3));
905 // explicitly defeat the default action but don't try anything in particular
906 case CSSM_WORDID_CANCELED
:
907 secdebug("KCdb", "%p defeat default action", this);
910 // Unknown sub-sample for acquiring new secret.
911 // If we wanted to be fascist, we could now do
912 // CssmError::throwMe(CSSM_ERRCODE_SAMPLE_VALUE_NOT_SUPPORTED);
913 // But instead we try to be tolerant and continue on.
914 // This DOES however count as an explicit attempt at specifying unlock,
915 // so we will no longer try the default case below...
916 secdebug("KCdb", "%p unknown sub-sample acquisition (%d) ignored",
917 this, sample
.type());
922 // default action -- interactive (only)
923 QueryNewPassphrase
query(*this, reason
);
924 StSyncLock
<Mutex
, Mutex
> uisync(common().uiLock(), common());
925 query
.inferHints(Server::process());
926 CssmAutoData
passphrase(Allocator::standard(Allocator::sensitive
));
927 CssmAutoData
oldPassphrase(Allocator::standard(Allocator::sensitive
));
928 if (query(oldPassphrase
, passphrase
) == SecurityAgent::noReason
) {
929 common().setup(NULL
, passphrase
);
930 change_secret_on_keybag(common(), oldPassphrase
.data(), (int)oldPassphrase
.length(), passphrase
.data(), (int)passphrase
.length());
935 // out of options - no secret obtained
936 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED
);
941 // Given a (truncated) Database credentials TypedList specifying a master key,
942 // locate the key and return a reference to it.
944 CssmClient::Key
KeychainDatabase::keyFromCreds(const TypedList
&sample
, unsigned int requiredLength
)
946 // decode TypedList structure (sample type; Data:CSPHandle; Data:CSSM_KEY)
947 assert(sample
.type() == CSSM_SAMPLE_TYPE_SYMMETRIC_KEY
|| sample
.type() == CSSM_SAMPLE_TYPE_ASYMMETRIC_KEY
);
948 if (sample
.length() != requiredLength
949 || sample
[1].type() != CSSM_LIST_ELEMENT_DATUM
950 || sample
[2].type() != CSSM_LIST_ELEMENT_DATUM
951 || (requiredLength
== 4 && sample
[3].type() != CSSM_LIST_ELEMENT_DATUM
))
952 CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE
);
953 KeyHandle
&handle
= *sample
[1].data().interpretedAs
<KeyHandle
>(CSSM_ERRCODE_INVALID_SAMPLE_VALUE
);
954 // We used to be able to check the length but supporting multiple client
955 // architectures dishes that (sizeof(CSSM_KEY) varies due to alignment and
956 // field-size differences). The decoding in the transition layer should
957 // serve as a sufficient garbling check anyway.
958 if (sample
[2].data().data() == NULL
)
959 CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE
);
960 CssmKey
&key
= *sample
[2].data().interpretedAs
<CssmKey
>();
962 if (key
.header().cspGuid() == gGuidAppleCSPDL
) {
963 // handleOrKey is a SecurityServer KeyHandle; ignore key argument
964 return safer_cast
<LocalKey
&>(*Server::key(handle
));
966 if (sample
.type() == CSSM_SAMPLE_TYPE_ASYMMETRIC_KEY
) {
968 Contents (see DefaultCredentials::unlockKey in libsecurity_keychain/defaultcreds.cpp)
970 sample[0] sample type
971 sample[1] csp handle for master or wrapping key; is really a keyhandle
972 sample[2] masterKey [not used since securityd cannot interpret; use sample[1] handle instead]
973 sample[3] UnlockReferralRecord data, in this case the flattened symmetric key
976 // RefPointer<Key> Server::key(KeyHandle key)
977 KeyHandle keyhandle
= *sample
[1].data().interpretedAs
<KeyHandle
>(CSSM_ERRCODE_INVALID_SAMPLE_VALUE
);
978 CssmData
&flattenedKey
= sample
[3].data();
979 RefPointer
<Key
> unwrappingKey
= Server::key(keyhandle
);
980 Database
&db
=unwrappingKey
->database();
982 CssmKey rawWrappedKey
;
983 unflattenKey(flattenedKey
, rawWrappedKey
);
985 RefPointer
<Key
> masterKey
;
986 CssmData emptyDescriptiveData
;
987 const AccessCredentials
*cred
= NULL
;
988 const AclEntryPrototype
*owner
= NULL
;
989 CSSM_KEYUSE usage
= CSSM_KEYUSE_ANY
;
990 CSSM_KEYATTR_FLAGS attrs
= CSSM_KEYATTR_EXTRACTABLE
; //CSSM_KEYATTR_RETURN_REF |
992 // Get default credentials for unwrappingKey (the one on the token)
993 // Copied from Statics::Statics() in libsecurity_keychain/aclclient.cpp
994 // Following KeyItem::getCredentials, one sees that the "operation" parameter
995 // e.g. "CSSM_ACL_AUTHORIZATION_DECRYPT" is ignored
996 Allocator
&alloc
= Allocator::standard();
997 AutoCredentials
promptCred(alloc
, 3);// enable interactive prompting
999 // promptCred: a credential permitting user prompt confirmations
1001 // a KEYCHAIN_PROMPT sample, both by itself and in a THRESHOLD
1002 // a PROMPTED_PASSWORD sample
1003 promptCred
.sample(0) = TypedList(alloc
, CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT
);
1004 promptCred
.sample(1) = TypedList(alloc
, CSSM_SAMPLE_TYPE_THRESHOLD
,
1005 new(alloc
) ListElement(TypedList(alloc
, CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT
)));
1006 promptCred
.sample(2) = TypedList(alloc
, CSSM_SAMPLE_TYPE_PROMPTED_PASSWORD
,
1007 new(alloc
) ListElement(alloc
, CssmData()));
1009 // This unwrap object is here just to provide a context
1010 CssmClient::UnwrapKey
unwrap(Server::csp(), CSSM_ALGID_NONE
); //ok to lie about csp here
1011 unwrap
.mode(CSSM_ALGMODE_NONE
);
1012 unwrap
.padding(CSSM_PADDING_PKCS1
);
1013 unwrap
.cred(promptCred
);
1014 unwrap
.add(CSSM_ATTRIBUTE_WRAPPED_KEY_FORMAT
, uint32(CSSM_KEYBLOB_WRAPPED_FORMAT_PKCS7
));
1015 Security::Context
*tmpContext
;
1016 CSSM_CC_HANDLE CCHandle
= unwrap
.handle();
1017 /*CSSM_RETURN rx = */ CSSM_GetContext (CCHandle
, (CSSM_CONTEXT_PTR
*)&tmpContext
);
1019 // OK, this is skanky but necessary. We overwrite fields in the context struct
1021 tmpContext
->ContextType
= CSSM_ALGCLASS_ASYMMETRIC
;
1022 tmpContext
->AlgorithmType
= CSSM_ALGID_RSA
;
1024 db
.unwrapKey(*tmpContext
, cred
, owner
, unwrappingKey
, NULL
, usage
, attrs
,
1025 rawWrappedKey
, masterKey
, emptyDescriptiveData
);
1027 Allocator::standard().free(rawWrappedKey
.KeyData
.Data
);
1029 return safer_cast
<LocalKey
&>(*masterKey
).key();
1033 // not a KeyHandle reference; use key as a raw key
1034 if (key
.header().blobType() != CSSM_KEYBLOB_RAW
)
1035 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_REFERENCE
);
1036 if (key
.header().keyClass() != CSSM_KEYCLASS_SESSION_KEY
)
1037 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_CLASS
);
1038 return CssmClient::Key(Server::csp(), key
, true);
1042 void unflattenKey(const CssmData
&flatKey
, CssmKey
&rawKey
)
1044 // unflatten the raw input key naively: key header then key data
1045 // We also convert it back to host byte order
1046 // A CSSM_KEY is a CSSM_KEYHEADER followed by a CSSM_DATA
1048 // Now copy: header, then key struct, then key data
1049 memcpy(&rawKey
.KeyHeader
, flatKey
.Data
, sizeof(CSSM_KEYHEADER
));
1050 memcpy(&rawKey
.KeyData
, flatKey
.Data
+ sizeof(CSSM_KEYHEADER
), sizeof(CSSM_DATA
));
1051 const uint32 keyDataLength
= flatKey
.length() - sizeof(CSSM_KEY
);
1052 rawKey
.KeyData
.Data
= Allocator::standard().malloc
<uint8
>(keyDataLength
);
1053 rawKey
.KeyData
.Length
= keyDataLength
;
1054 memcpy(rawKey
.KeyData
.Data
, flatKey
.Data
+ sizeof(CSSM_KEY
), keyDataLength
);
1055 Security::n2hi(rawKey
.KeyHeader
); // convert it to host byte order
1060 // Verify a putative database passphrase.
1061 // If the database is already unlocked, just check the passphrase.
1062 // Otherwise, unlock with that passphrase and report success.
1063 // Caller must hold the common lock.
1065 bool KeychainDatabase::validatePassphrase(const CssmData
&passphrase
) const
1067 if (common().hasMaster()) {
1068 // verify against known secret
1069 return common().validatePassphrase(passphrase
);
1071 // no master secret - perform "blind" unlock to avoid actual unlock
1073 DatabaseCryptoCore test
;
1074 test
.setup(mBlob
, passphrase
);
1075 test
.decodeCore(mBlob
, NULL
);
1085 // Lock this database
1087 void KeychainDatabase::lockDb()
1094 // Given a Key for this database, encode it into a blob and return it.
1096 KeyBlob
*KeychainDatabase::encodeKey(const CssmKey
&key
, const CssmData
&pubAcl
, const CssmData
&privAcl
)
1098 bool inTheClear
= false;
1099 if((key
.keyClass() == CSSM_KEYCLASS_PUBLIC_KEY
) &&
1100 !(key
.attribute(CSSM_KEYATTR_PUBLIC_KEY_ENCRYPT
))) {
1103 StLock
<Mutex
> _(common());
1107 // tell the cryptocore to form the key blob
1108 return common().encodeKeyCore(key
, pubAcl
, privAcl
, inTheClear
);
1113 // Given a "blobbed" key for this database, decode it into its real
1114 // key object and (re)populate its ACL.
1116 void KeychainDatabase::decodeKey(KeyBlob
*blob
, CssmKey
&key
, void * &pubAcl
, void * &privAcl
)
1118 StLock
<Mutex
> _(common());
1120 if(!blob
->isClearText())
1121 makeUnlocked(); // we need our keys
1123 common().decodeKeyCore(blob
, key
, pubAcl
, privAcl
);
1124 // memory protocol: pubAcl points into blob; privAcl was allocated
1130 // Given a KeychainKey (that implicitly belongs to another keychain),
1131 // return it encoded using this keychain's operational secrets.
1133 KeyBlob
*KeychainDatabase::recodeKey(KeychainKey
&oldKey
)
1135 if (mRecodingSource
!= &oldKey
.referent
<KeychainDatabase
>()) {
1136 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY
);
1138 oldKey
.instantiateAcl(); // make sure key is decoded
1139 CssmData publicAcl
, privateAcl
;
1140 oldKey
.exportBlob(publicAcl
, privateAcl
);
1141 // NB: blob's memory belongs to caller, not the common
1144 * Make sure the new key is in the same cleartext/encrypted state.
1146 bool inTheClear
= false;
1147 assert(oldKey
.blob());
1148 if(oldKey
.blob() && oldKey
.blob()->isClearText()) {
1152 KeyBlob
*blob
= common().encodeKeyCore(oldKey
.cssmKey(), publicAcl
, privateAcl
, inTheClear
);
1153 oldKey
.acl().allocator
.free(publicAcl
);
1154 oldKey
.acl().allocator
.free(privateAcl
);
1160 // Modify database parameters
1162 void KeychainDatabase::setParameters(const DBParameters
¶ms
)
1164 StLock
<Mutex
> _(common());
1166 common().mParams
= params
;
1167 common().invalidateBlob(); // invalidate old blobs
1168 activity(); // (also resets the timeout timer)
1169 secdebug("KCdb", "%p common %p(%s) set params=(%u,%u)",
1170 this, &common(), dbName(), params
.idleTimeout
, params
.lockOnSleep
);
1175 // Retrieve database parameters
1177 void KeychainDatabase::getParameters(DBParameters
¶ms
)
1179 StLock
<Mutex
> _(common());
1181 params
= common().mParams
;
1182 //activity(); // getting parameters does not reset the idle timer
1187 // RIGHT NOW, database ACLs are attached to the database.
1188 // This will soon move upstairs.
1190 SecurityServerAcl
&KeychainDatabase::acl()
1197 // Intercept ACL change requests and reset blob validity
1199 void KeychainDatabase::instantiateAcl()
1201 StLock
<Mutex
> _(common());
1205 void KeychainDatabase::changedAcl()
1207 StLock
<Mutex
> _(common());
1213 // Check an incoming DbBlob for basic viability
1215 void KeychainDatabase::validateBlob(const DbBlob
*blob
)
1217 // perform basic validation on the blob
1219 blob
->validate(CSSMERR_APPLEDL_INVALID_DATABASE_BLOB
);
1220 switch (blob
->version()) {
1221 #if defined(COMPAT_OSX_10_0)
1222 case DbBlob::version_MacOS_10_0
:
1225 case DbBlob::version_MacOS_10_1
:
1228 CssmError::throwMe(CSSMERR_APPLEDL_INCOMPATIBLE_DATABASE_BLOB
);
1234 // Debugging support
1236 #if defined(DEBUGDUMP)
1238 void KeychainDbCommon::dumpNode()
1240 PerSession::dumpNode();
1241 uint32 sig
; memcpy(&sig
, &mIdentifier
.signature(), sizeof(sig
));
1242 Debug::dump(" %s[%8.8x]", mIdentifier
.dbName(), sig
);
1244 Debug::dump(" locked");
1246 time_t whenTime
= time_t(when());
1247 Debug::dump(" unlocked(%24.24s/%.2g)", ctime(&whenTime
),
1248 (when() - Time::now()).seconds());
1250 Debug::dump(" params=(%u,%u)", mParams
.idleTimeout
, mParams
.lockOnSleep
);
1253 void KeychainDatabase::dumpNode()
1255 PerProcess::dumpNode();
1256 Debug::dump(" %s vers=%u",
1257 mValidData
? " data" : " nodata", version
);
1259 uint32 sig
; memcpy(&sig
, &mBlob
->randomSignature
, sizeof(sig
));
1260 Debug::dump(" blob=%p[%8.8x]", mBlob
, sig
);
1262 Debug::dump(" noblob");
1270 // DbCommon basic features
1272 KeychainDbCommon::KeychainDbCommon(Session
&ssn
, const DbIdentifier
&id
)
1273 : LocalDbCommon(ssn
), sequence(0), version(1), mIdentifier(id
),
1274 mIsLocked(true), mValidParams(false), mLoginKeychain(false)
1276 // match existing DbGlobal or create a new one
1278 Server
&server
= Server::active();
1279 StLock
<Mutex
> _(server
);
1280 if (KeychainDbGlobal
*dbglobal
=
1281 server
.findFirst
<KeychainDbGlobal
, const DbIdentifier
&>(&KeychainDbGlobal::identifier
, identifier())) {
1283 secdebug("KCdb", "%p linking to existing DbGlobal %p", this, dbglobal
);
1285 // DbGlobal not present; make a new one
1286 parent(*new KeychainDbGlobal(identifier()));
1287 secdebug("KCdb", "%p linking to new DbGlobal %p", this, &global());
1290 // link lifetime to the Session
1291 session().addReference(*this);
1293 if (strcasestr(id
.dbName(), "login.keychain") != NULL
) {
1294 mLoginKeychain
= true;
1298 if (mLoginKeychain
&& !session().keybagGetState(session_keybag_loaded
)) {
1299 service_context_t context
= session().get_current_service_context();
1300 if (service_client_kb_load(&context
) == 0) {
1301 session().keybagSetState(session_keybag_loaded
);
1306 KeychainDbCommon::~KeychainDbCommon()
1308 SECURITYD_KEYCHAIN_RELEASE(this, (char*)this->dbName());
1310 // explicitly unschedule ourselves
1311 Server::active().clearTimer(this);
1312 if (mLoginKeychain
) {
1313 session().keybagClearState(session_keybag_unlocked
);
1317 KeychainDbGlobal
&KeychainDbCommon::global() const
1319 return parent
<KeychainDbGlobal
>();
1323 void KeychainDbCommon::select()
1326 void KeychainDbCommon::unselect()
1331 void KeychainDbCommon::makeNewSecrets()
1333 // we already have a master key (right?)
1334 assert(hasMaster());
1336 // tell crypto core to generate the use keys
1337 DatabaseCryptoCore::generateNewSecrets();
1339 // we're now officially "unlocked"; set the timer
1345 // All unlocking activity ultimately funnels through this method.
1346 // This unlocks a DbCommon using the secrets setup in its crypto core
1347 // component, and performs all the housekeeping needed to represent
1348 // the state change.
1349 // Returns true if unlock was successful, false if it failed due to
1350 // invalid/insufficient secrets. Throws on other errors.
1352 bool KeychainDbCommon::unlockDb(DbBlob
*blob
, void **privateAclBlob
)
1355 // Tell the cryptocore to (try to) decode itself. This will fail
1356 // in an astonishing variety of ways if the passphrase is wrong.
1357 assert(hasMaster());
1358 decodeCore(blob
, privateAclBlob
);
1359 secdebug("KCdb", "%p unlock successful", this);
1361 secdebug("KCdb", "%p unlock failed", this);
1365 // get the database parameters only if we haven't got them yet
1366 if (!mValidParams
) {
1367 mParams
= blob
->params
;
1368 n2hi(mParams
.idleTimeout
);
1369 mValidParams
= true; // sticky
1372 bool isLocked
= mIsLocked
;
1374 setUnlocked(); // mark unlocked
1377 // broadcast unlock notification, but only if we were previously locked
1378 notify(kNotificationEventUnlocked
);
1379 SECURITYD_KEYCHAIN_UNLOCK(this, (char*)this->dbName());
1384 void KeychainDbCommon::setUnlocked()
1386 session().addReference(*this); // active/held
1387 mIsLocked
= false; // mark unlocked
1388 activity(); // set timeout timer
1392 void KeychainDbCommon::lockDb()
1396 StLock
<Mutex
> _(*this);
1398 DatabaseCryptoCore::invalidate();
1399 notify(kNotificationEventLocked
);
1400 SECURITYD_KEYCHAIN_LOCK(this, (char*)this->dbName());
1401 Server::active().clearTimer(this);
1403 mIsLocked
= true; // mark locked
1406 // this call may destroy us if we have no databases anymore
1407 session().removeReference(*this);
1411 if (mLoginKeychain
&& lock
) {
1412 service_context_t context
= session().get_current_service_context();
1413 service_client_kb_lock(&context
);
1414 session().keybagClearState(session_keybag_unlocked
);
1419 DbBlob
*KeychainDbCommon::encode(KeychainDatabase
&db
)
1421 assert(!isLocked()); // must have been unlocked by caller
1423 // export database ACL to blob form
1424 CssmData pubAcl
, privAcl
;
1425 db
.acl().exportBlob(pubAcl
, privAcl
);
1427 // tell the cryptocore to form the blob
1429 form
.randomSignature
= identifier();
1430 form
.sequence
= sequence
;
1431 form
.params
= mParams
;
1432 h2ni(form
.params
.idleTimeout
);
1434 assert(hasMaster());
1435 DbBlob
*blob
= encodeCore(form
, pubAcl
, privAcl
);
1438 db
.acl().allocator
.free(pubAcl
);
1439 db
.acl().allocator
.free(privAcl
);
1445 // Perform deferred lock processing for a database.
1447 void KeychainDbCommon::action()
1449 secdebug("KCdb", "common %s(%p) locked by timer", dbName(), this);
1453 void KeychainDbCommon::activity()
1456 secdebug("KCdb", "setting DbCommon %p timer to %d",
1457 this, int(mParams
.idleTimeout
));
1458 Server::active().setTimer(this, Time::Interval(int(mParams
.idleTimeout
)));
1462 void KeychainDbCommon::sleepProcessing()
1464 secdebug("KCdb", "common %s(%p) sleep-lock processing", dbName(), this);
1465 StLock
<Mutex
> _(*this);
1466 if (mParams
.lockOnSleep
)
1470 void KeychainDbCommon::lockProcessing()
1477 // We consider a keychain to belong to the system domain if it resides
1478 // in /Library/Keychains. That's not exactly fool-proof, but we don't
1479 // currently have any internal markers to interrogate.
1481 bool KeychainDbCommon::belongsToSystem() const
1483 if (const char *name
= this->dbName())
1484 return !strncmp(name
, "/Library/Keychains/", 19);
1490 // Keychain global objects
1492 KeychainDbGlobal::KeychainDbGlobal(const DbIdentifier
&id
)
1497 KeychainDbGlobal::~KeychainDbGlobal()
1499 secdebug("KCdb", "DbGlobal %p destroyed", this);