2 * Copyright (c) 2000-2009,2012-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@
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_cdsa_utilities/acl_any.h> // for default owner ACLs
48 #include <security_cdsa_utilities/cssmendian.h>
49 #include <security_cdsa_client/wrapkey.h>
50 #include <security_cdsa_client/genkey.h>
51 #include <security_cdsa_client/signclient.h>
52 #include <security_cdsa_client/cryptoclient.h>
53 #include <security_cdsa_client/macclient.h>
54 #include <securityd_client/dictionary.h>
55 #include <security_utilities/endian.h>
56 #include "securityd_service/securityd_service/securityd_service_client.h"
57 #include <AssertMacros.h>
59 #include <sys/sysctl.h>
60 #include <sys/kauth.h>
63 #include <corecrypto/ccmode_siv.h>
66 void unflattenKey(const CssmData
&flatKey
, CssmKey
&rawKey
); //>> make static method on KeychainDatabase
71 KeychainDbCommon::CommonSet
KeychainDbCommon::mCommonSet
;
72 ReadWriteLock
KeychainDbCommon::mRWCommonLock
;
74 // Process is using a cached effective uid, login window switches uid after the intial connection
75 static void get_process_euid(pid_t pid
, uid_t
* out_euid
)
77 if (!out_euid
) return;
79 struct kinfo_proc proc_info
= {};
80 int mib
[] = {CTL_KERN
, KERN_PROC
, KERN_PROC_PID
, pid
};
81 size_t len
= sizeof(struct kinfo_proc
);
83 ret
= sysctl(mib
, (sizeof(mib
)/sizeof(int)), &proc_info
, &len
, NULL
, 0);
86 if ((ret
== 0) && (proc_info
.kp_eproc
.e_ucred
.cr_uid
!= 0)) {
87 *out_euid
= proc_info
.kp_eproc
.e_ucred
.cr_uid
;
92 unlock_keybag(KeychainDatabase
& db
, const void * secret
, int secret_len
)
96 if (!db
.common().isLoginKeychain()) return 0;
98 service_context_t context
= db
.common().session().get_current_service_context();
100 // login window attempts to change the password before a session has a uid
101 if (context
.s_uid
== AU_DEFAUDITID
) {
102 get_process_euid(db
.process().pid(), &context
.s_uid
);
105 // try to unlock first if not found then load/create or unlock
106 // loading should happen when the kb common object is created
107 // if it doesn't exist yet then the unlock will fail and we'll create everything
108 rc
= service_client_kb_unlock(&context
, secret
, secret_len
);
109 if (rc
== KB_BagNotLoaded
) {
110 if (service_client_kb_load(&context
) == KB_BagNotFound
) {
111 rc
= service_client_kb_create(&context
, secret
, secret_len
);
113 rc
= service_client_kb_unlock(&context
, secret
, secret_len
);
117 if (rc
!= 0) { // if we just upgraded make sure we swap the encryption key to the password
118 if (!db
.common().session().keybagGetState(session_keybag_check_master_key
)) {
119 CssmAutoData
encKey(Allocator::standard(Allocator::sensitive
));
120 db
.common().get_encryption_key(encKey
);
121 if ((rc
= service_client_kb_unlock(&context
, encKey
.data(), (int)encKey
.length())) == 0) {
122 rc
= service_client_kb_change_secret(&context
, encKey
.data(), (int)encKey
.length(), secret
, secret_len
);
125 if (rc
!= 0) { // if a login.keychain password exists but doesnt on the keybag update it
127 if ((secret_len
> 0) && service_client_kb_is_locked(&context
, NULL
, &no_pin
) == 0) {
129 syslog(LOG_ERR
, "Updating iCloud keychain passphrase for uid %d", context
.s_uid
);
130 service_client_kb_change_secret(&context
, NULL
, 0, secret
, secret_len
);
134 } // session_keybag_check_master_key
138 db
.common().session().keybagSetState(session_keybag_unlocked
|session_keybag_loaded
|session_keybag_check_master_key
);
140 syslog(LOG_ERR
, "Failed to unlock iCloud keychain for uid %d", context
.s_uid
);
147 change_secret_on_keybag(KeychainDatabase
& db
, const void * secret
, int secret_len
, const void * new_secret
, int new_secret_len
)
149 if (!db
.common().isLoginKeychain()) return;
151 service_context_t context
= db
.common().session().get_current_service_context();
153 // login window attempts to change the password before a session has a uid
154 if (context
.s_uid
== AU_DEFAUDITID
) {
155 get_process_euid(db
.process().pid(), &context
.s_uid
);
158 // if a login.keychain doesn't exist yet it comes into securityd as a create then change_secret
159 // we need to create the keybag in this case if it doesn't exist
160 int rc
= service_client_kb_change_secret(&context
, secret
, secret_len
, new_secret
, new_secret_len
);
161 if (rc
== KB_BagNotLoaded
) {
162 if (service_client_kb_load(&context
) == KB_BagNotFound
) {
163 rc
= service_client_kb_create(&context
, new_secret
, new_secret_len
);
165 rc
= service_client_kb_change_secret(&context
, secret
, secret_len
, new_secret
, new_secret_len
);
169 // this makes it possible to restore a deleted keybag on condition it still exists in kernel
170 if (rc
!= KB_Success
) {
171 service_client_kb_save(&context
);
174 // if for some reason we are locked lets unlock so later we don't try and throw up SecurityAgent dialog
176 if ((service_client_kb_is_locked(&context
, &locked
, NULL
) == KB_Success
) && locked
) {
177 rc
= service_client_kb_unlock(&context
, new_secret
, new_secret_len
);
178 if (rc
!= KB_Success
) {
179 syslog(LOG_ERR
, "Failed to unlock iCloud keychain for uid %d (%d)", context
.s_uid
, (int)rc
);
184 // Attempt to unlock the keybag with a AccessCredentials password.
185 // Honors UI disabled flags from clients set in the cred before prompt.
187 unlock_keybag_with_cred(KeychainDatabase
&db
, const AccessCredentials
*cred
){
188 list
<CssmSample
> samples
;
189 if (cred
&& cred
->samples().collect(CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK
, samples
)) {
190 for (list
<CssmSample
>::iterator it
= samples
.begin(); it
!= samples
.end(); it
++) {
191 TypedList
&sample
= *it
;
192 sample
.checkProper();
193 switch (sample
.type()) {
194 // interactively prompt the user - no additional data
195 case CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT
: {
196 StSyncLock
<Mutex
, Mutex
> uisync(db
.common().uiLock(), db
.common());
197 // Once we get the ui lock, check whether another thread has already unlocked keybag
199 service_context_t context
= db
.common().session().get_current_service_context();
200 if ((service_client_kb_is_locked(&context
, &locked
, NULL
) == 0) && locked
) {
201 QueryKeybagPassphrase
keybagQuery(db
.common().session(), 3);
202 keybagQuery
.inferHints(Server::process());
203 if (keybagQuery
.query() == SecurityAgent::noReason
) {
208 // another thread already unlocked the keybag
213 // try to use an explicitly given passphrase - Data:passphrase
214 case CSSM_SAMPLE_TYPE_PASSWORD
: {
215 if (sample
.length() != 2)
216 CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE
);
217 secinfo("KCdb", "attempting passphrase unlock of keybag");
218 if (unlock_keybag(db
, sample
[1].data().data(), (int)sample
[1].data().length())) {
224 // Unknown sub-sample for unlocking.
225 secinfo("KCdb", "keybag: unknown sub-sample unlock (%d) ignored", sample
.type());
235 // Create a Database object from initial parameters (create operation)
237 KeychainDatabase::KeychainDatabase(const DLDbIdentifier
&id
, const DBParameters
¶ms
, Process
&proc
,
238 const AccessCredentials
*cred
, const AclEntryPrototype
*owner
)
239 : LocalDatabase(proc
), mValidData(false), mSecret(Allocator::standard(Allocator::sensitive
)), mSaveSecret(false), version(0), mBlob(NULL
), mRecoded(false)
241 // save a copy of the credentials for later access control
242 mCred
= DataWalkers::copy(cred
, Allocator::standard());
244 // create a new random signature to complete the DLDbIdentifier
245 DbBlob::Signature newSig
;
246 Server::active().random(newSig
.bytes
);
247 DbIdentifier
ident(id
, newSig
);
249 // create common block and initialize
250 // Since this is a creation step, figure out the correct blob version for this database
251 RefPointer
<KeychainDbCommon
> newCommon
= new KeychainDbCommon(proc
.session(), ident
, CommonBlob::getCurrentVersionForDb(ident
.dbName()));
252 newCommon
->initializeKeybag();
254 StLock
<Mutex
> _(*newCommon
);
257 // new common is now visible (in ident-map) but we hold its lock
259 // establish the new master secret
260 establishNewSecrets(cred
, SecurityAgent::newDatabase
);
262 // set initial database parameters
263 common().mParams
= params
;
265 // the common is "unlocked" now
266 common().makeNewSecrets();
268 // establish initial ACL
270 acl().cssmSetInitial(*owner
);
272 acl().cssmSetInitial(new AnyAclSubject());
275 // for now, create the blob immediately
278 proc
.addReference(*this);
280 // this new keychain is unlocked; make it so
283 secinfo("KCdb", "creating keychain %p %s with common %p", this, (char*)this->dbName(), &common());
288 // Create a Database object from a database blob (decoding)
290 KeychainDatabase::KeychainDatabase(const DLDbIdentifier
&id
, const DbBlob
*blob
, Process
&proc
,
291 const AccessCredentials
*cred
)
292 : LocalDatabase(proc
), mValidData(false), mSecret(Allocator::standard(Allocator::sensitive
)), mSaveSecret(false), version(0), mBlob(NULL
), mRecoded(false)
296 // save a copy of the credentials for later access control
297 mCred
= DataWalkers::copy(cred
, Allocator::standard());
298 mBlob
= blob
->copy();
300 // check to see if we already know about this database
301 DbIdentifier
ident(id
, blob
->randomSignature
);
302 Session
&session
= process().session();
303 RefPointer
<KeychainDbCommon
> com
;
304 secinfo("kccommon", "looking for a common at %s", ident
.dbName());
305 if (KeychainDbCommon::find(ident
, session
, com
)) {
307 secinfo("KCdb", "joining keychain %p %s with common %p", this, (char*)this->dbName(), &common());
309 // DbCommon not present; make a new one
310 secinfo("kccommon", "no common found");
312 common().mParams
= blob
->params
;
313 secinfo("KCdb", "making keychain %p %s with common %p", this, (char*)this->dbName(), &common());
314 // this DbCommon is locked; no timer or reference setting
316 proc
.addReference(*this);
319 void KeychainDbCommon::insert()
321 StReadWriteLock
_(mRWCommonLock
, StReadWriteLock::Write
);
325 void KeychainDbCommon::insertHoldingLock()
327 mCommonSet
.insert(this);
332 // find or make a DbCommon. Returns true if an existing one was found and used.
333 bool KeychainDbCommon::find(const DbIdentifier
&ident
, Session
&session
, RefPointer
<KeychainDbCommon
> &common
, uint32 requestedVersion
, KeychainDbCommon
* cloneFrom
)
335 // Prepare to drop the mRWCommonLock.
337 StReadWriteLock
_(mRWCommonLock
, StReadWriteLock::Read
);
338 for (CommonSet::const_iterator it
= mCommonSet
.begin(); it
!= mCommonSet
.end(); ++it
) {
339 if (&session
== &(*it
)->session() && ident
== (*it
)->identifier()) {
341 secinfo("kccommon", "found a common for %s at %p", ident
.dbName(), common
.get());
347 // not found. Grab the write lock, ensure that nobody has beaten us to adding,
348 // and then create a DbCommon and add it to the map.
350 StReadWriteLock
_(mRWCommonLock
, StReadWriteLock::Write
);
351 for (CommonSet::const_iterator it
= mCommonSet
.begin(); it
!= mCommonSet
.end(); ++it
) {
352 if (&session
== &(*it
)->session() && ident
== (*it
)->identifier()) {
354 secinfo("kccommon", "found a common for %s at %p", ident
.dbName(), common
.get());
361 common
= new KeychainDbCommon(session
, ident
, *cloneFrom
);
362 } else if(requestedVersion
!= CommonBlob::version_none
) {
363 common
= new KeychainDbCommon(session
, ident
, requestedVersion
);
365 common
= new KeychainDbCommon(session
, ident
);
368 secinfo("kccommon", "made a new common for %s at %p", ident
.dbName(), common
.get());
370 // Can't call insert() here, because it grabs the write lock (which we have).
371 common
->insertHoldingLock();
373 common
->initializeKeybag();
379 // Special-purpose constructor for keychain synchronization. Copies an
380 // existing keychain but uses the operational keys from secretsBlob. The
381 // new KeychainDatabase will silently replace the existing KeychainDatabase
382 // as soon as the client declares that re-encoding of all keychain items is
383 // finished. This is a little perilous since it allows a client to dictate
384 // securityd state, but we try to ensure that only the client that started
385 // the re-encoding can declare it done.
387 KeychainDatabase::KeychainDatabase(KeychainDatabase
&src
, Process
&proc
, DbHandle dbToClone
)
388 : LocalDatabase(proc
), mValidData(false), mSecret(Allocator::standard(Allocator::sensitive
)), mSaveSecret(false), version(0), mBlob(NULL
), mRecoded(false)
390 mCred
= DataWalkers::copy(src
.mCred
, Allocator::standard());
392 // Give this KeychainDatabase a temporary name
393 std::string newDbName
= std::string("////") + std::string(src
.identifier().dbName());
394 DLDbIdentifier
newDLDbIdent(src
.identifier().dlDbIdentifier().ssuid(), newDbName
.c_str(), src
.identifier().dlDbIdentifier().dbLocation());
395 DbIdentifier
ident(newDLDbIdent
, src
.identifier());
397 // create common block and initialize
398 RefPointer
<KeychainDbCommon
> newCommon
= new KeychainDbCommon(proc
.session(), ident
);
399 newCommon
->initializeKeybag();
400 StLock
<Mutex
> _(*newCommon
);
404 // set initial database parameters from the source keychain
405 common().mParams
= src
.common().mParams
;
407 // establish the source keychain's master secret as ours
408 // @@@ NB: this is a v. 0.1 assumption. We *should* trigger new UI
409 // that offers the user the option of using the existing password
410 // or choosing a new one. That would require a new
411 // SecurityAgentQuery type, new UI, and--possibly--modifications to
412 // ensure that the new password is available here to generate the
413 // new master secret.
414 src
.unlockDb(false); // precaution for masterKey()
415 common().setup(src
.blob(), src
.common().masterKey());
417 // import the operational secrets
418 RefPointer
<KeychainDatabase
> srcKC
= Server::keychain(dbToClone
);
419 common().importSecrets(srcKC
->common());
421 // import source keychain's ACL
422 CssmData pubAcl
, privAcl
;
423 src
.acl().exportBlob(pubAcl
, privAcl
);
424 importBlob(pubAcl
.data(), privAcl
.data());
425 src
.acl().allocator
.free(pubAcl
);
426 src
.acl().allocator
.free(privAcl
);
428 // indicate that this keychain should be allowed to do some otherwise
429 // risky things required for copying, like re-encoding keys
430 mRecodingSource
= &src
;
432 common().setUnlocked();
437 proc
.addReference(*this);
438 secinfo("SSdb", "database %s(%p) created as copy, common at %p",
439 common().dbName(), this, &common());
442 // Make a new KeychainDatabase from an old one, but have a completely different location
443 KeychainDatabase::KeychainDatabase(const DLDbIdentifier
& id
, KeychainDatabase
&src
, Process
&proc
)
444 : LocalDatabase(proc
), mValidData(false), mSecret(Allocator::standard(Allocator::sensitive
)), mSaveSecret(false), version(0), mBlob(NULL
), mRecoded(false)
446 mCred
= DataWalkers::copy(src
.mCred
, Allocator::standard());
448 DbIdentifier
ident(id
, src
.identifier());
450 // create common block and initialize
451 RefPointer
<KeychainDbCommon
> newCommon
;
452 if(KeychainDbCommon::find(ident
, process().session(), newCommon
, CommonBlob::version_none
, &src
.common())) {
453 // A common already existed. Write over it, but note that everything may go horribly from here on out.
454 secinfo("kccommon", "Found common where we didn't expect. Possible strange behavior ahead.");
455 newCommon
->cloneFrom(src
.common());
458 StLock
<Mutex
> _(*newCommon
);
461 // set initial database parameters from the source keychain
462 common().mParams
= src
.common().mParams
;
464 // import source keychain's ACL
465 CssmData pubAcl
, privAcl
;
466 src
.acl().exportBlob(pubAcl
, privAcl
);
467 importBlob(pubAcl
.data(), privAcl
.data());
468 src
.acl().allocator
.free(pubAcl
);
469 src
.acl().allocator
.free(privAcl
);
471 // Copy the source database's blob, if possible
473 mBlob
= src
.mBlob
->copy();
474 version
= src
.version
;
477 // We've copied everything we can from our source. If they were valid, so are we.
478 mValidData
= src
.mValidData
;
480 proc
.addReference(*this);
481 secinfo("SSdb", "database %s(%p) created as expected clone, common at %p", common().dbName(), this, &common());
485 // Make a new KeychainDatabase from an old one, but have entirely new operational secrets
486 KeychainDatabase::KeychainDatabase(uint32 requestedVersion
, KeychainDatabase
&src
, Process
&proc
)
487 : LocalDatabase(proc
), mValidData(false), mSecret(Allocator::standard(Allocator::sensitive
)), mSaveSecret(false), version(0), mBlob(NULL
), mRecoded(false)
489 mCred
= DataWalkers::copy(src
.mCred
, Allocator::standard());
491 // Give this KeychainDatabase a temporary name
492 // this must canonicalize to a different path than the original DB, otherwise another process opening the existing DB wil find this new KeychainDbCommon
493 // and call decodeCore with the old blob, overwriting the new secrets and wreaking havoc
494 std::string newDbName
= std::string("////") + std::string(src
.identifier().dbName()) + std::string("_com.apple.security.keychain.migrating");
495 DLDbIdentifier
newDLDbIdent(src
.identifier().dlDbIdentifier().ssuid(), newDbName
.c_str(), src
.identifier().dlDbIdentifier().dbLocation());
496 DbIdentifier
ident(newDLDbIdent
, src
.identifier());
498 // hold the lock for src's common during this operation (to match locking common locking order with KeychainDatabase::recodeKey)
499 StLock
<Mutex
> __(src
.common());
501 // create common block and initialize
502 RefPointer
<KeychainDbCommon
> newCommon
;
503 if(KeychainDbCommon::find(ident
, process().session(), newCommon
, requestedVersion
)) {
504 // A common already existed here. Write over it, but note that everything may go horribly from here on out.
505 secinfo("kccommon", "Found common where we didn't expect. Possible strange behavior ahead.");
506 newCommon
->cloneFrom(src
.common(), requestedVersion
);
508 newCommon
->initializeKeybag();
509 StLock
<Mutex
> _(*newCommon
);
512 // We want to re-use the master secrets from the source database (and so the
513 // same password), but reroll new operational secrets.
515 // Copy the master secret over...
516 src
.unlockDb(false); // precaution
518 common().setup(src
.blob(), src
.common().masterKey(), false); // keep the new common's version intact
520 // set initial database parameters from the source keychain
521 common().mParams
= src
.common().mParams
;
523 // and make new operational secrets
524 common().makeNewSecrets();
526 // import source keychain's ACL
527 CssmData pubAcl
, privAcl
;
528 src
.acl().exportBlob(pubAcl
, privAcl
);
529 importBlob(pubAcl
.data(), privAcl
.data());
530 src
.acl().allocator
.free(pubAcl
);
531 src
.acl().allocator
.free(privAcl
);
533 // indicate that this keychain should be allowed to do some otherwise
534 // risky things required for copying, like re-encoding keys
535 mRecodingSource
= &src
;
537 common().setUnlocked();
542 proc
.addReference(*this);
543 secinfo("SSdb", "database %s(%p) created as expected copy, common at %p",
544 common().dbName(), this, &common());
548 // Destroy a Database
550 KeychainDatabase::~KeychainDatabase()
552 secinfo("KCdb", "deleting database %s(%p) common %p",
553 common().dbName(), this, &common());
554 Allocator::standard().free(mCred
);
555 Allocator::standard().free(mBlob
);
560 // Basic Database virtual implementations
562 KeychainDbCommon
&KeychainDatabase::common() const
564 return parent
<KeychainDbCommon
>();
567 const char *KeychainDatabase::dbName() const
569 return common().dbName();
572 bool KeychainDatabase::transient() const
574 return false; // has permanent store
577 AclKind
KeychainDatabase::aclKind() const
582 Database
*KeychainDatabase::relatedDatabase()
588 // (Re-)Authenticate the database. This changes the stored credentials.
590 void KeychainDatabase::authenticate(CSSM_DB_ACCESS_TYPE mode
,
591 const AccessCredentials
*cred
)
593 StLock
<Mutex
> _(common());
595 // the (Apple specific) RESET bit means "lock the database now"
597 case CSSM_DB_ACCESS_RESET
:
598 secinfo("KCdb", "%p ACCESS_RESET triggers keychain lock", this);
602 // store the new credentials for future use
603 secinfo("KCdb", "%p authenticate stores new database credentials", this);
604 AccessCredentials
*newCred
= DataWalkers::copy(cred
, Allocator::standard());
605 Allocator::standard().free(mCred
);
612 // Make a new KeychainKey.
613 // If PERMANENT is off, make a temporary key instead.
614 // The db argument allows you to create for another KeychainDatabase (only);
615 // it defaults to ourselves.
617 RefPointer
<Key
> KeychainDatabase::makeKey(Database
&db
, const CssmKey
&newKey
,
618 uint32 moreAttributes
, const AclEntryPrototype
*owner
)
621 if (moreAttributes
& CSSM_KEYATTR_PERMANENT
)
622 return new KeychainKey(db
, newKey
, moreAttributes
, owner
);
624 return process().makeTemporaryKey(newKey
, moreAttributes
, owner
);
627 RefPointer
<Key
> KeychainDatabase::makeKey(const CssmKey
&newKey
,
628 uint32 moreAttributes
, const AclEntryPrototype
*owner
)
630 return makeKey(*this, newKey
, moreAttributes
, owner
);
635 // Return the database blob, recalculating it as needed.
637 DbBlob
*KeychainDatabase::blob()
639 StLock
<Mutex
> _(common());
641 makeUnlocked(false); // unlock to get master secret
642 encode(); // (re)encode blob if needed
644 activity(); // reset timeout
645 assert(validBlob()); // better have a valid blob now...
651 // Encode the current database as a blob.
652 // Note that this returns memory we own and keep.
653 // Caller must hold common lock.
655 void KeychainDatabase::encode()
657 DbBlob
*blob
= common().encode(*this);
658 Allocator::standard().free(mBlob
);
660 version
= common().version
;
661 secinfo("KCdb", "encoded database %p common %p(%s) version %u params=(%u,%u)",
662 this, &common(), dbName(), version
,
663 common().mParams
.idleTimeout
, common().mParams
.lockOnSleep
);
668 // Change the passphrase on a database
670 void KeychainDatabase::changePassphrase(const AccessCredentials
*cred
)
672 // get and hold the common lock (don't let other threads break in here)
673 StLock
<Mutex
> _(common());
675 // establish OLD secret - i.e. unlock the database
676 //@@@ do we want to leave the final lock state alone?
677 if (common().isLoginKeychain()) mSaveSecret
= true;
678 makeUnlocked(cred
, false);
680 // establish NEW secret
681 if(!establishNewSecrets(cred
, SecurityAgent::changePassphrase
)) {
682 secinfo("KCdb", "Old and new passphrases are the same. Database %s(%p) master secret did not change.",
683 common().dbName(), this);
686 if (mSecret
) { mSecret
.reset(); }
688 common().invalidateBlob(); // blob state changed
689 secinfo("KCdb", "Database %s(%p) master secret changed", common().dbName(), this);
690 encode(); // force rebuild of local blob
692 // send out a notification
693 notify(kNotificationEventPassphraseChanged
);
695 // I guess this counts as an activity
700 // Second stage of keychain synchronization: overwrite the original keychain's
701 // (this KeychainDatabase's) operational secrets
703 void KeychainDatabase::commitSecretsForSync(KeychainDatabase
&cloneDb
)
705 StLock
<Mutex
> _(common());
707 // try to detect spoofing
708 if (cloneDb
.mRecodingSource
!= this)
709 CssmError::throwMe(CSSM_ERRCODE_INVALID_DB_HANDLE
);
711 // in case we autolocked since starting the sync
712 makeUnlocked(false); // call this because we already own the lock
713 cloneDb
.unlockDb(false); // we may not own the lock here, so calling unlockDb will lock the cloneDb's common lock
715 // Decode all keys whose handles refer to this on-disk keychain so that
716 // if the holding client commits the key back to disk, it's encoded with
717 // the new operational secrets. The recoding client *must* hold a write
718 // lock for the on-disk keychain from the moment it starts recoding key
719 // items until after this call.
721 // @@@ This specific implementation is a workaround for 4003540.
722 std::vector
<U32HandleObject::Handle
> handleList
;
723 U32HandleObject::findAllRefs
<KeychainKey
>(handleList
);
724 size_t count
= handleList
.size();
726 for (unsigned int n
= 0; n
< count
; ++n
) {
727 RefPointer
<KeychainKey
> kckey
=
728 U32HandleObject::findRefAndLock
<KeychainKey
>(handleList
[n
], CSSMERR_CSP_INVALID_KEY_REFERENCE
);
729 StLock
<Mutex
> _(*kckey
/*, true*/);
730 if (kckey
->database().global().identifier() == identifier()) {
731 kckey
->key(); // force decode
732 kckey
->invalidateBlob();
733 secinfo("kcrecode", "changed extant key %p (proc %d)",
734 &*kckey
, kckey
->process().pid());
739 // mark down that we just recoded
742 // it is now safe to replace the old op secrets
743 common().importSecrets(cloneDb
.common());
744 common().invalidateBlob();
749 // Extract the database master key as a proper Key object.
751 RefPointer
<Key
> KeychainDatabase::extractMasterKey(Database
&db
,
752 const AccessCredentials
*cred
, const AclEntryPrototype
*owner
,
753 uint32 usage
, uint32 attrs
)
755 // get and hold common lock
756 StLock
<Mutex
> _(common());
758 // force lock to require re-validation of credentials
761 // unlock to establish master secret
764 // extract the raw cryptographic key
765 CssmClient::WrapKey
wrap(Server::csp(), CSSM_ALGID_NONE
);
767 wrap(common().masterKey(), key
);
769 // make the key object and return it
770 return makeKey(db
, key
, attrs
& LocalKey::managedAttributes
, owner
);
775 // Unlock this database (if needed) by obtaining the master secret in some
776 // suitable way and then proceeding to unlock with it.
777 // Does absolutely nothing if the database is already unlocked.
778 // The makeUnlocked forms are identical except the assume the caller already
779 // holds the common lock.
781 void KeychainDatabase::unlockDb(bool unlockKeybag
)
783 StLock
<Mutex
> _(common());
784 makeUnlocked(unlockKeybag
);
787 void KeychainDatabase::makeUnlocked(bool unlockKeybag
)
789 return makeUnlocked(mCred
, unlockKeybag
);
792 void KeychainDatabase::makeUnlocked(const AccessCredentials
*cred
, bool unlockKeybag
)
795 secnotice("KCdb", "%p(%p) unlocking for makeUnlocked()", this, &common());
796 assert(mBlob
|| (mValidData
&& common().hasMaster()));
797 establishOldSecrets(cred
);
798 common().setUnlocked(); // mark unlocked
799 if (common().isLoginKeychain()) {
800 CssmKey master
= common().masterKey();
802 CssmClient::WrapKey
wrap(Server::csp(), CSSM_ALGID_NONE
);
803 wrap(master
, rawMaster
);
805 service_context_t context
= common().session().get_current_service_context();
806 service_client_stash_load_key(&context
, rawMaster
.keyData(), (int)rawMaster
.length());
808 } else if (unlockKeybag
&& common().isLoginKeychain()) {
810 service_context_t context
= common().session().get_current_service_context();
811 if ((service_client_kb_is_locked(&context
, &locked
, NULL
) == 0) && locked
) {
812 if (!unlock_keybag_with_cred(*this, cred
)) {
813 syslog(LOG_NOTICE
, "failed to unlock iCloud keychain");
817 if (!mValidData
) { // need to decode to get our ACLs, master secret available
818 secnotice("KCdb", "%p(%p) is unlocked; decoding for makeUnlocked()", this, &common());
820 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED
);
827 // Invoke the securityd_service to retrieve the keychain master
828 // key from the AppleFDEKeyStore.
830 void KeychainDatabase::stashDbCheck()
832 CssmAutoData
masterKey(Allocator::standard(Allocator::sensitive
));
833 CssmAutoData
encKey(Allocator::standard(Allocator::sensitive
));
837 void * stash_key
= NULL
;
838 int stash_key_len
= 0;
839 service_context_t context
= common().session().get_current_service_context();
840 rc
= service_client_stash_get_key(&context
, &stash_key
, &stash_key_len
);
843 masterKey
.copy(CssmData((void *)stash_key
,stash_key_len
));
844 memset(stash_key
, 0, stash_key_len
);
848 secnotice("KCdb", "failed to get stash from securityd_service: %d", (int)rc
);
849 CssmError::throwMe(rc
);
853 StLock
<Mutex
> _(common());
855 // Now establish it as the keychain master key
856 CssmClient::Key
key(Server::csp(), masterKey
.get());
857 CssmKey::Header
&hdr
= key
.header();
858 hdr
.keyClass(CSSM_KEYCLASS_SESSION_KEY
);
859 hdr
.algorithm(CSSM_ALGID_3DES_3KEY_EDE
);
860 hdr
.usage(CSSM_KEYUSE_ANY
);
861 hdr
.blobType(CSSM_KEYBLOB_RAW
);
862 hdr
.blobFormat(CSSM_KEYBLOB_RAW_FORMAT_OCTET_STRING
);
863 common().setup(mBlob
, key
);
866 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED
);
868 common().get_encryption_key(encKey
);
871 // when upgrading from pre-10.9 create a keybag if it doesn't exist with the encryption key
872 // only do this after we have verified the master key unlocks the login.keychain
873 if (service_client_kb_load(&context
) == KB_BagNotFound
) {
874 service_client_kb_create(&context
, encKey
.data(), (int)encKey
.length());
879 // Get the keychain master key and invoke the securityd_service
880 // to stash it in the AppleFDEKeyStore ready for commit to the
883 void KeychainDatabase::stashDb()
885 CssmAutoData
data(Allocator::standard(Allocator::sensitive
));
888 StLock
<Mutex
> _(common());
890 if (!common().isValid()) {
891 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY
);
894 CssmKey key
= common().masterKey();
895 data
.copy(key
.keyData());
898 service_context_t context
= common().session().get_current_service_context();
899 int rc
= service_client_stash_set_key(&context
, data
.data(), (int)data
.length());
900 if (rc
!= 0) CssmError::throwMe(rc
);
904 // The following unlock given an explicit passphrase, rather than using
905 // (special cred sample based) default procedures.
907 void KeychainDatabase::unlockDb(const CssmData
&passphrase
, bool unlockKeybag
)
909 StLock
<Mutex
> _(common());
910 makeUnlocked(passphrase
, unlockKeybag
);
913 void KeychainDatabase::makeUnlocked(const CssmData
&passphrase
, bool unlockKeybag
)
916 if (decode(passphrase
))
919 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED
);
920 } else if (!mValidData
) { // need to decode to get our ACLs, passphrase available
922 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED
);
925 if (unlockKeybag
&& common().isLoginKeychain()) {
927 service_context_t context
= common().session().get_current_service_context();
928 if (!common().session().keybagGetState(session_keybag_check_master_key
) || ((service_client_kb_is_locked(&context
, &locked
, NULL
) == 0) && locked
)) {
929 unlock_keybag(*this, passphrase
.data(), (int)passphrase
.length());
939 // Nonthrowing passphrase-based unlock. This returns false if unlock failed.
940 // Note that this requires an explicitly given passphrase.
941 // Caller must hold common lock.
943 bool KeychainDatabase::decode(const CssmData
&passphrase
)
946 common().setup(mBlob
, passphrase
);
947 bool success
= decode();
948 if (success
&& common().isLoginKeychain()) {
949 unlock_keybag(*this, passphrase
.data(), (int)passphrase
.length());
956 // Given the established master secret, decode the working keys and other
957 // functional secrets for this database. Return false (do NOT throw) if
958 // the decode fails. Call this in low(er) level code once you established
961 bool KeychainDatabase::decode()
964 assert(common().hasMaster());
965 void *privateAclBlob
;
966 if (common().unlockDb(mBlob
, &privateAclBlob
)) {
968 acl().importBlob(mBlob
->publicAclBlob(), privateAclBlob
);
971 Allocator::standard().free(privateAclBlob
);
974 secinfo("KCdb", "%p decode failed", this);
980 // Given an AccessCredentials for this database, wring out the existing primary
981 // database secret by whatever means necessary.
982 // On entry, caller must hold the database common lock. It will be held
983 // throughout except when user interaction is required. User interaction
984 // requires relinquishing the database common lock and taking the UI lock. On
985 // return from user interaction, the UI lock is relinquished and the database
986 // common lock must be reacquired. At no time may the caller hold both locks.
987 // On exit, the crypto core has its master secret. If things go wrong,
988 // we will throw a suitable exception. Note that encountering any malformed
989 // credential sample will throw, but this is not guaranteed -- don't assume
990 // that NOT throwing means creds is entirely well-formed (it may just be good
991 // enough to work THIS time).
994 // Walk through the creds. Fish out those credentials (in order) that
995 // are for unlock processing (they have no ACL subject correspondents),
996 // and (try to) obey each in turn, until one produces a valid secret
997 // or you run out. If no special samples are found at all, interpret that as
998 // "use the system global default," which happens to be hard-coded right here.
1000 void KeychainDatabase::establishOldSecrets(const AccessCredentials
*creds
)
1002 bool forSystem
= this->belongsToSystem(); // this keychain belongs to the system security domain
1004 // attempt system-keychain unlock
1006 SystemKeychainKey
systemKeychain(kSystemUnlockFile
);
1007 if (systemKeychain
.matches(mBlob
->randomSignature
)) {
1008 secinfo("KCdb", "%p attempting system unlock", this);
1009 common().setup(mBlob
, CssmClient::Key(Server::csp(), systemKeychain
.key(), true));
1015 list
<CssmSample
> samples
;
1016 if (creds
&& creds
->samples().collect(CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK
, samples
)) {
1017 for (list
<CssmSample
>::iterator it
= samples
.begin(); it
!= samples
.end(); it
++) {
1018 TypedList
&sample
= *it
;
1019 sample
.checkProper();
1020 switch (sample
.type()) {
1021 // interactively prompt the user - no additional data
1022 case CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT
:
1024 if (interactiveUnlock())
1028 // try to use an explicitly given passphrase - Data:passphrase
1029 case CSSM_SAMPLE_TYPE_PASSWORD
:
1030 if (sample
.length() != 2)
1031 CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE
);
1032 secinfo("KCdb", "%p attempting passphrase unlock", this);
1033 if (decode(sample
[1]))
1036 // try to open with a given master key - Data:CSP or KeyHandle, Data:CssmKey
1037 case CSSM_SAMPLE_TYPE_SYMMETRIC_KEY
:
1038 case CSSM_SAMPLE_TYPE_ASYMMETRIC_KEY
:
1040 secinfo("KCdb", "%p attempting explicit key unlock", this);
1041 common().setup(mBlob
, keyFromCreds(sample
, 4));
1046 case CSSM_SAMPLE_TYPE_KEYBAG_KEY
:
1048 secinfo("KCdb", "%p attempting keybag key unlock", this);
1049 common().setup(mBlob
, keyFromKeybag(sample
));
1054 // explicitly defeat the default action but don't try anything in particular
1055 case CSSM_WORDID_CANCELED
:
1056 secinfo("KCdb", "%p defeat default action", this);
1059 // Unknown sub-sample for unlocking.
1060 // If we wanted to be fascist, we could now do
1061 // CssmError::throwMe(CSSM_ERRCODE_SAMPLE_VALUE_NOT_SUPPORTED);
1062 // But instead we try to be tolerant and continue on.
1063 // This DOES however count as an explicit attempt at specifying unlock,
1064 // so we will no longer try the default case below...
1065 secinfo("KCdb", "%p unknown sub-sample unlock (%d) ignored", this, sample
.type());
1074 if (interactiveUnlock())
1079 // out of options - no secret obtained
1080 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED
);
1084 // This function is almost identical to establishOldSecrets, but:
1085 // 1. It will never prompt the user; these credentials either work or they don't
1086 // 2. It will not change the secrets of this database
1088 // TODO: These two functions should probably be refactored to something nicer.
1089 bool KeychainDatabase::checkCredentials(const AccessCredentials
*creds
) {
1091 list
<CssmSample
> samples
;
1092 if (creds
&& creds
->samples().collect(CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK
, samples
)) {
1093 for (list
<CssmSample
>::iterator it
= samples
.begin(); it
!= samples
.end(); it
++) {
1094 TypedList
&sample
= *it
;
1095 sample
.checkProper();
1096 switch (sample
.type()) {
1097 // interactively prompt the user - no additional data
1098 case CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT
:
1099 // do nothing, because this function will never prompt the user
1100 secinfo("integrity", "%p ignoring keychain prompt", this);
1102 // try to use an explicitly given passphrase - Data:passphrase
1103 case CSSM_SAMPLE_TYPE_PASSWORD
:
1104 if (sample
.length() != 2)
1105 CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE
);
1106 secinfo("integrity", "%p checking passphrase", this);
1107 if(validatePassphrase(sample
[1])) {
1111 // try to open with a given master key - Data:CSP or KeyHandle, Data:CssmKey
1112 case CSSM_SAMPLE_TYPE_SYMMETRIC_KEY
:
1113 case CSSM_SAMPLE_TYPE_ASYMMETRIC_KEY
:
1115 secinfo("integrity", "%p attempting explicit key unlock", this);
1117 CssmClient::Key checkKey
= keyFromCreds(sample
, 4);
1118 if(common().validateKey(checkKey
)) {
1122 // ignore all problems in keyFromCreds
1123 secinfo("integrity", "%p caught error", this);
1130 // out of options - credentials don't match
1134 uint32_t KeychainDatabase::interactiveUnlockAttempts
= 0;
1136 bool KeychainDatabase::interactiveUnlock()
1138 secinfo("KCdb", "%p attempting interactive unlock", this);
1139 interactiveUnlockAttempts
++;
1141 SecurityAgent::Reason reason
= SecurityAgent::noReason
;
1142 QueryUnlock
query(*this);
1143 // take UI interlock and release DbCommon lock (to avoid deadlocks)
1144 StSyncLock
<Mutex
, Mutex
> uisync(common().uiLock(), common());
1146 // now that we have the UI lock, interact unless another thread unlocked us first
1148 query
.inferHints(Server::process());
1150 if (mSaveSecret
&& reason
== SecurityAgent::noReason
) {
1151 query
.retrievePassword(mSecret
);
1155 secinfo("KCdb", "%p was unlocked during uiLock delay", this);
1158 if (common().isLoginKeychain()) {
1159 bool locked
= false;
1160 service_context_t context
= common().session().get_current_service_context();
1161 if ((service_client_kb_is_locked(&context
, &locked
, NULL
) == 0) && locked
) {
1162 QueryKeybagNewPassphrase
keybagQuery(common().session());
1163 keybagQuery
.inferHints(Server::process());
1164 CssmAutoData
pass(Allocator::standard(Allocator::sensitive
));
1165 CssmAutoData
oldPass(Allocator::standard(Allocator::sensitive
));
1166 SecurityAgent::Reason queryReason
= keybagQuery
.query(oldPass
, pass
);
1167 if (queryReason
== SecurityAgent::noReason
) {
1168 service_client_kb_change_secret(&context
, oldPass
.data(), (int)oldPass
.length(), pass
.data(), (int)pass
.length());
1169 } else if (queryReason
== SecurityAgent::resettingPassword
) {
1170 query
.retrievePassword(pass
);
1171 service_client_kb_reset(&context
, pass
.data(), (int)pass
.length());
1177 return reason
== SecurityAgent::noReason
;
1180 uint32_t KeychainDatabase::getInteractiveUnlockAttempts() {
1181 if (csr_check(CSR_ALLOW_APPLE_INTERNAL
)) {
1182 // Not an internal install; don't answer
1185 return interactiveUnlockAttempts
;
1191 // Same thing, but obtain a new secret somehow and set it into the common.
1193 bool KeychainDatabase::establishNewSecrets(const AccessCredentials
*creds
, SecurityAgent::Reason reason
)
1195 list
<CssmSample
> samples
;
1196 if (creds
&& creds
->samples().collect(CSSM_SAMPLE_TYPE_KEYCHAIN_CHANGE_LOCK
, samples
)) {
1197 for (list
<CssmSample
>::iterator it
= samples
.begin(); it
!= samples
.end(); it
++) {
1198 TypedList
&sample
= *it
;
1199 sample
.checkProper();
1200 switch (sample
.type()) {
1201 // interactively prompt the user
1202 case CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT
:
1204 secinfo("KCdb", "%p specified interactive passphrase", this);
1205 QueryNewPassphrase
query(*this, reason
);
1206 StSyncLock
<Mutex
, Mutex
> uisync(common().uiLock(), common());
1207 query
.inferHints(Server::process());
1208 CssmAutoData
passphrase(Allocator::standard(Allocator::sensitive
));
1209 CssmAutoData
oldPassphrase(Allocator::standard(Allocator::sensitive
));
1210 if (query(oldPassphrase
, passphrase
) == SecurityAgent::noReason
) {
1211 common().setup(NULL
, passphrase
);
1212 change_secret_on_keybag(*this, oldPassphrase
.data(), (int)oldPassphrase
.length(), passphrase
.data(), (int)passphrase
.length());
1217 // try to use an explicitly given passphrase
1218 case CSSM_SAMPLE_TYPE_PASSWORD
:
1220 secinfo("KCdb", "%p specified explicit passphrase", this);
1221 if (sample
.length() != 2)
1222 CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE
);
1223 if (common().isLoginKeychain()) {
1224 CssmAutoData
oldPassphrase(Allocator::standard(Allocator::sensitive
));
1225 list
<CssmSample
> oldSamples
;
1226 creds
->samples().collect(CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK
, oldSamples
);
1227 for (list
<CssmSample
>::iterator oit
= oldSamples
.begin(); oit
!= oldSamples
.end(); oit
++) {
1228 TypedList
&tmpList
= *oit
;
1229 tmpList
.checkProper();
1230 if (tmpList
.type() == CSSM_SAMPLE_TYPE_PASSWORD
) {
1231 if (tmpList
.length() == 2) {
1232 oldPassphrase
= tmpList
[1].data();
1236 if (!oldPassphrase
.length() && mSecret
&& mSecret
.length()) {
1237 oldPassphrase
= mSecret
;
1239 if ((oldPassphrase
.length() == sample
[1].data().length()) &&
1240 !memcmp(oldPassphrase
.data(), sample
[1].data().data(), oldPassphrase
.length()) &&
1241 oldPassphrase
.length()) {
1242 // don't change master key if the passwords are the same
1245 common().setup(NULL
, sample
[1]);
1246 change_secret_on_keybag(*this, oldPassphrase
.data(), (int)oldPassphrase
.length(), sample
[1].data().data(), (int)sample
[1].data().length());
1249 common().setup(NULL
, sample
[1]);
1253 // try to open with a given master key
1254 case CSSM_WORDID_SYMMETRIC_KEY
:
1255 case CSSM_SAMPLE_TYPE_ASYMMETRIC_KEY
:
1256 secinfo("KCdb", "%p specified explicit master key", this);
1257 common().setup(NULL
, keyFromCreds(sample
, 3));
1259 // explicitly defeat the default action but don't try anything in particular
1260 case CSSM_WORDID_CANCELED
:
1261 secinfo("KCdb", "%p defeat default action", this);
1264 // Unknown sub-sample for acquiring new secret.
1265 // If we wanted to be fascist, we could now do
1266 // CssmError::throwMe(CSSM_ERRCODE_SAMPLE_VALUE_NOT_SUPPORTED);
1267 // But instead we try to be tolerant and continue on.
1268 // This DOES however count as an explicit attempt at specifying unlock,
1269 // so we will no longer try the default case below...
1270 secinfo("KCdb", "%p unknown sub-sample acquisition (%d) ignored",
1271 this, sample
.type());
1276 // default action -- interactive (only)
1277 QueryNewPassphrase
query(*this, reason
);
1278 StSyncLock
<Mutex
, Mutex
> uisync(common().uiLock(), common());
1279 query
.inferHints(Server::process());
1280 CssmAutoData
passphrase(Allocator::standard(Allocator::sensitive
));
1281 CssmAutoData
oldPassphrase(Allocator::standard(Allocator::sensitive
));
1282 if (query(oldPassphrase
, passphrase
) == SecurityAgent::noReason
) {
1283 common().setup(NULL
, passphrase
);
1284 change_secret_on_keybag(*this, oldPassphrase
.data(), (int)oldPassphrase
.length(), passphrase
.data(), (int)passphrase
.length());
1289 // out of options - no secret obtained
1290 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED
);
1295 // Given a (truncated) Database credentials TypedList specifying a master key,
1296 // locate the key and return a reference to it.
1298 CssmClient::Key
KeychainDatabase::keyFromCreds(const TypedList
&sample
, unsigned int requiredLength
)
1300 // decode TypedList structure (sample type; Data:CSPHandle; Data:CSSM_KEY)
1301 assert(sample
.type() == CSSM_SAMPLE_TYPE_SYMMETRIC_KEY
|| sample
.type() == CSSM_SAMPLE_TYPE_ASYMMETRIC_KEY
);
1302 if (sample
.length() != requiredLength
1303 || sample
[1].type() != CSSM_LIST_ELEMENT_DATUM
1304 || sample
[2].type() != CSSM_LIST_ELEMENT_DATUM
1305 || (requiredLength
== 4 && sample
[3].type() != CSSM_LIST_ELEMENT_DATUM
))
1306 CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE
);
1307 KeyHandle
&handle
= *sample
[1].data().interpretedAs
<KeyHandle
>(CSSM_ERRCODE_INVALID_SAMPLE_VALUE
);
1308 // We used to be able to check the length but supporting multiple client
1309 // architectures dishes that (sizeof(CSSM_KEY) varies due to alignment and
1310 // field-size differences). The decoding in the transition layer should
1311 // serve as a sufficient garbling check anyway.
1312 if (sample
[2].data().data() == NULL
)
1313 CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE
);
1314 CssmKey
&key
= *sample
[2].data().interpretedAs
<CssmKey
>();
1316 if (key
.header().cspGuid() == gGuidAppleCSPDL
) {
1317 // handleOrKey is a SecurityServer KeyHandle; ignore key argument
1318 return safer_cast
<LocalKey
&>(*Server::key(handle
));
1320 if (sample
.type() == CSSM_SAMPLE_TYPE_ASYMMETRIC_KEY
) {
1322 Contents (see DefaultCredentials::unlockKey in libsecurity_keychain/defaultcreds.cpp)
1324 sample[0] sample type
1325 sample[1] csp handle for master or wrapping key; is really a keyhandle
1326 sample[2] masterKey [not used since securityd cannot interpret; use sample[1] handle instead]
1327 sample[3] UnlockReferralRecord data, in this case the flattened symmetric key
1330 // RefPointer<Key> Server::key(KeyHandle key)
1331 KeyHandle keyhandle
= *sample
[1].data().interpretedAs
<KeyHandle
>(CSSM_ERRCODE_INVALID_SAMPLE_VALUE
);
1332 CssmData
&flattenedKey
= sample
[3].data();
1333 RefPointer
<Key
> unwrappingKey
= Server::key(keyhandle
);
1334 Database
&db
=unwrappingKey
->database();
1336 CssmKey rawWrappedKey
;
1337 unflattenKey(flattenedKey
, rawWrappedKey
);
1339 RefPointer
<Key
> masterKey
;
1340 CssmData emptyDescriptiveData
;
1341 const AccessCredentials
*cred
= NULL
;
1342 const AclEntryPrototype
*owner
= NULL
;
1343 CSSM_KEYUSE usage
= CSSM_KEYUSE_ANY
;
1344 CSSM_KEYATTR_FLAGS attrs
= CSSM_KEYATTR_EXTRACTABLE
; //CSSM_KEYATTR_RETURN_REF |
1346 // Get default credentials for unwrappingKey (the one on the token)
1347 // Copied from Statics::Statics() in libsecurity_keychain/aclclient.cpp
1348 // Following KeyItem::getCredentials, one sees that the "operation" parameter
1349 // e.g. "CSSM_ACL_AUTHORIZATION_DECRYPT" is ignored
1350 Allocator
&alloc
= Allocator::standard();
1351 AutoCredentials
promptCred(alloc
, 3);// enable interactive prompting
1353 // promptCred: a credential permitting user prompt confirmations
1355 // a KEYCHAIN_PROMPT sample, both by itself and in a THRESHOLD
1356 // a PROMPTED_PASSWORD sample
1357 promptCred
.sample(0) = TypedList(alloc
, CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT
);
1358 promptCred
.sample(1) = TypedList(alloc
, CSSM_SAMPLE_TYPE_THRESHOLD
,
1359 new(alloc
) ListElement(TypedList(alloc
, CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT
)));
1360 promptCred
.sample(2) = TypedList(alloc
, CSSM_SAMPLE_TYPE_PROMPTED_PASSWORD
,
1361 new(alloc
) ListElement(alloc
, CssmData()));
1363 // This unwrap object is here just to provide a context
1364 CssmClient::UnwrapKey
unwrap(Server::csp(), CSSM_ALGID_NONE
); //ok to lie about csp here
1365 unwrap
.mode(CSSM_ALGMODE_NONE
);
1366 unwrap
.padding(CSSM_PADDING_PKCS1
);
1367 unwrap
.cred(promptCred
);
1368 unwrap
.add(CSSM_ATTRIBUTE_WRAPPED_KEY_FORMAT
, uint32(CSSM_KEYBLOB_WRAPPED_FORMAT_PKCS7
));
1369 Security::Context
*tmpContext
;
1370 CSSM_CC_HANDLE CCHandle
= unwrap
.handle();
1371 /*CSSM_RETURN rx = */ CSSM_GetContext (CCHandle
, (CSSM_CONTEXT_PTR
*)&tmpContext
);
1373 // OK, this is skanky but necessary. We overwrite fields in the context struct
1375 tmpContext
->ContextType
= CSSM_ALGCLASS_ASYMMETRIC
;
1376 tmpContext
->AlgorithmType
= CSSM_ALGID_RSA
;
1378 db
.unwrapKey(*tmpContext
, cred
, owner
, unwrappingKey
, NULL
, usage
, attrs
,
1379 rawWrappedKey
, masterKey
, emptyDescriptiveData
);
1381 Allocator::standard().free(rawWrappedKey
.KeyData
.Data
);
1383 return safer_cast
<LocalKey
&>(*masterKey
).key();
1385 else if (sample
.type() == CSSM_SAMPLE_TYPE_SYMMETRIC_KEY
&& sample
.length() == 4 && sample
[3].data().length() > 0) {
1387 Contents (see MasterKeyUnlockCredentials in libsecurity_cdsa_client/lib/aclclient.cpp)
1389 sample[0] sample type
1390 sample[1] 0, since we don't have a valid handle
1391 sample[2] CssmKey of the masterKey [can't immediately use since it includes a CSSM_DATA struct with pointers]
1392 sample[3] flattened symmetric master key, including the key data
1395 // Fix up key to include actual data
1396 CssmData
&flattenedKey
= sample
[3].data();
1397 unflattenKey(flattenedKey
, key
);
1399 // Check that we have a reasonable key
1400 if (key
.header().blobType() != CSSM_KEYBLOB_RAW
) {
1401 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_REFERENCE
);
1403 if (key
.header().keyClass() != CSSM_KEYCLASS_SESSION_KEY
) {
1404 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_CLASS
);
1407 // bring the key into the CSP and return it
1408 return CssmClient::Key(Server::csp(), key
, true);
1410 // not a KeyHandle reference; use key as a raw key
1411 if (key
.header().blobType() != CSSM_KEYBLOB_RAW
)
1412 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_REFERENCE
);
1413 if (key
.header().keyClass() != CSSM_KEYCLASS_SESSION_KEY
)
1414 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_CLASS
);
1415 return CssmClient::Key(Server::csp(), key
, true);
1419 void unflattenKey(const CssmData
&flatKey
, CssmKey
&rawKey
)
1421 // The format we're expecting is a CSSM_KEY followed by the actual key data:
1422 // CSSM_KEY : KEY DATA
1423 // which is approximately:
1424 // h2ni(CSSM_KEYHEADER) : 4 bytes padding : CSSM_DATA{?:?} : KEY BYTES
1426 // Note that CSSM_KEY includes a CSSM_DATA struct, which we will ignore as it has pointers.
1427 // The pointer and length will be set to whatever key data follows the CSSM_KEY in rawKey.
1429 // unflatten the raw input key naively: key header then key data
1430 // We also convert it back to host byte order
1431 // A CSSM_KEY is a CSSM_KEYHEADER followed by a CSSM_DATA
1433 // Now copy: header, then key struct, then key data
1434 memcpy(&rawKey
.KeyHeader
, flatKey
.Data
, sizeof(CSSM_KEYHEADER
));
1435 memcpy(&rawKey
.KeyData
, flatKey
.Data
+ sizeof(CSSM_KEYHEADER
), sizeof(CSSM_DATA
));
1436 size_t keyDataLength
= flatKey
.length() - sizeof(CSSM_KEY
);
1437 rawKey
.KeyData
.Data
= Allocator::standard().malloc
<uint8
>(keyDataLength
);
1438 rawKey
.KeyData
.Length
= keyDataLength
;
1439 memcpy(rawKey
.KeyData
.Data
, flatKey
.Data
+ sizeof(CSSM_KEY
), keyDataLength
);
1440 Security::n2hi(rawKey
.KeyHeader
); // convert it to host byte order
1444 KeychainDatabase::keyFromKeybag(const TypedList
&sample
)
1446 service_context_t context
;
1447 uint8_t *session_key
;
1448 int session_key_size
;
1450 const struct ccmode_siv
*mode
= ccaes_siv_decrypt_mode();
1451 const size_t session_key_wrapped_len
= 40;
1452 const size_t version_len
= 1, nonce_len
= 16;
1453 uint8_t *decrypted_data
;
1454 size_t decrypted_len
;
1456 assert(sample
.type() == CSSM_SAMPLE_TYPE_KEYBAG_KEY
);
1458 CssmData
&unlock_token
= sample
[2].data();
1460 context
= common().session().get_current_service_context();
1461 rc
= service_client_kb_unwrap_key(&context
, unlock_token
.data(), session_key_wrapped_len
, key_class_ak
, (void **)&session_key
, &session_key_size
);
1463 CssmError::throwMe(CSSM_ERRCODE_INVALID_CRYPTO_DATA
);
1466 uint8_t *indata
= (uint8_t *)unlock_token
.data() + session_key_wrapped_len
;
1467 size_t inlen
= unlock_token
.length() - session_key_wrapped_len
;
1469 decrypted_len
= ccsiv_plaintext_size(mode
, inlen
- (version_len
+ nonce_len
));
1470 decrypted_data
= (uint8_t *)calloc(1, decrypted_len
);
1472 ccsiv_ctx_decl(mode
->size
, ctx
);
1474 rc
= ccsiv_init(mode
, ctx
, session_key_size
, session_key
);
1475 if (rc
!= 0) CssmError::throwMe(CSSM_ERRCODE_INVALID_CRYPTO_DATA
);
1476 rc
= ccsiv_set_nonce(mode
, ctx
, nonce_len
, indata
+ version_len
);
1477 if (rc
!= 0) CssmError::throwMe(CSSM_ERRCODE_INVALID_CRYPTO_DATA
);
1478 rc
= ccsiv_aad(mode
, ctx
, 1, indata
);
1479 if (rc
!= 0) CssmError::throwMe(CSSM_ERRCODE_INVALID_CRYPTO_DATA
);
1480 rc
= ccsiv_crypt(mode
, ctx
, inlen
- (version_len
+ nonce_len
), indata
+ version_len
+ nonce_len
, decrypted_data
);
1481 if (rc
!= 0) CssmError::throwMe(CSSM_ERRCODE_INVALID_CRYPTO_DATA
);
1483 ccsiv_ctx_clear(mode
->size
, ctx
);
1485 //free(decrypted_data);
1487 return makeRawKey(decrypted_data
, decrypted_len
, CSSM_ALGID_3DES_3KEY_EDE
, CSSM_KEYUSE_ENCRYPT
| CSSM_KEYUSE_DECRYPT
);
1490 // adapted from DatabaseCryptoCore::makeRawKey
1491 CssmClient::Key
KeychainDatabase::makeRawKey(void *data
, size_t length
,
1492 CSSM_ALGORITHMS algid
, CSSM_KEYUSE usage
)
1496 key
.header().BlobType
= CSSM_KEYBLOB_RAW
;
1497 key
.header().Format
= CSSM_KEYBLOB_RAW_FORMAT_OCTET_STRING
;
1498 key
.header().AlgorithmId
= algid
;
1499 key
.header().KeyClass
= CSSM_KEYCLASS_SESSION_KEY
;
1500 key
.header().KeyUsage
= usage
;
1501 key
.header().KeyAttr
= 0;
1502 key
.KeyData
= CssmData(data
, length
);
1504 // unwrap it into the CSP (but keep it raw)
1505 CssmClient::UnwrapKey
unwrap(Server::csp(), CSSM_ALGID_NONE
);
1506 CssmKey unwrappedKey
;
1507 CssmData descriptiveData
;
1509 CssmClient::KeySpec(CSSM_KEYUSE_ANY
, CSSM_KEYATTR_RETURN_DATA
| CSSM_KEYATTR_EXTRACTABLE
),
1510 unwrappedKey
, &descriptiveData
, NULL
);
1511 return CssmClient::Key(Server::csp(), unwrappedKey
);
1515 // Verify a putative database passphrase.
1516 // If the database is already unlocked, just check the passphrase.
1517 // Otherwise, unlock with that passphrase and report success.
1518 // Caller must hold the common lock.
1520 bool KeychainDatabase::validatePassphrase(const CssmData
&passphrase
) const
1522 if (common().hasMaster()) {
1523 // verify against known secret
1524 return common().validatePassphrase(passphrase
);
1526 // no master secret - perform "blind" unlock to avoid actual unlock
1528 DatabaseCryptoCore test
;
1529 test
.setup(mBlob
, passphrase
);
1530 test
.decodeCore(mBlob
, NULL
);
1540 // Lock this database
1542 void KeychainDatabase::lockDb()
1549 // Given a Key for this database, encode it into a blob and return it.
1551 KeyBlob
*KeychainDatabase::encodeKey(const CssmKey
&key
, const CssmData
&pubAcl
, const CssmData
&privAcl
)
1553 bool inTheClear
= false;
1554 if((key
.keyClass() == CSSM_KEYCLASS_PUBLIC_KEY
) &&
1555 !(key
.attribute(CSSM_KEYATTR_PUBLIC_KEY_ENCRYPT
))) {
1558 StLock
<Mutex
> _(common());
1560 makeUnlocked(false);
1562 // tell the cryptocore to form the key blob
1563 return common().encodeKeyCore(key
, pubAcl
, privAcl
, inTheClear
);
1568 // Given a "blobbed" key for this database, decode it into its real
1569 // key object and (re)populate its ACL.
1571 void KeychainDatabase::decodeKey(KeyBlob
*blob
, CssmKey
&key
, void * &pubAcl
, void * &privAcl
)
1573 StLock
<Mutex
> _(common());
1575 if(!blob
->isClearText())
1576 makeUnlocked(false); // we need our keys
1578 common().decodeKeyCore(blob
, key
, pubAcl
, privAcl
);
1579 // memory protocol: pubAcl points into blob; privAcl was allocated
1585 // Given a KeychainKey (that implicitly belongs to another keychain),
1586 // return it encoded using this keychain's operational secrets.
1588 KeyBlob
*KeychainDatabase::recodeKey(KeychainKey
&oldKey
)
1590 if (mRecodingSource
!= &oldKey
.referent
<KeychainDatabase
>()) {
1591 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY
);
1594 // To protect this operation, we need to take the mutex for both our common and the remote key's common in some defined order.
1595 // Grab the common being cloned (oldKey's) first, and then the common receiving the recoding (ours).
1596 StLock
<Mutex
> _ (oldKey
.referent
<KeychainDatabase
>().common());
1597 StLock
<Mutex
> __(common());
1599 oldKey
.instantiateAcl(); // make sure key is decoded
1600 CssmData publicAcl
, privateAcl
;
1601 oldKey
.exportBlob(publicAcl
, privateAcl
);
1602 // NB: blob's memory belongs to caller, not the common
1605 * Make sure the new key is in the same cleartext/encrypted state.
1607 bool inTheClear
= false;
1608 assert(oldKey
.blob());
1609 if(oldKey
.blob() && oldKey
.blob()->isClearText()) {
1613 KeyBlob
*blob
= common().encodeKeyCore(oldKey
.cssmKey(), publicAcl
, privateAcl
, inTheClear
);
1614 oldKey
.acl().allocator
.free(publicAcl
);
1615 oldKey
.acl().allocator
.free(privateAcl
);
1621 // Modify database parameters
1623 void KeychainDatabase::setParameters(const DBParameters
¶ms
)
1625 StLock
<Mutex
> _(common());
1626 makeUnlocked(false);
1627 common().mParams
= params
;
1628 common().invalidateBlob(); // invalidate old blobs
1629 activity(); // (also resets the timeout timer)
1630 secinfo("KCdb", "%p common %p(%s) set params=(%u,%u)",
1631 this, &common(), dbName(), params
.idleTimeout
, params
.lockOnSleep
);
1636 // Retrieve database parameters
1638 void KeychainDatabase::getParameters(DBParameters
¶ms
)
1640 StLock
<Mutex
> _(common());
1641 makeUnlocked(false);
1642 params
= common().mParams
;
1643 //activity(); // getting parameters does not reset the idle timer
1648 // RIGHT NOW, database ACLs are attached to the database.
1649 // This will soon move upstairs.
1651 SecurityServerAcl
&KeychainDatabase::acl()
1658 // Intercept ACL change requests and reset blob validity
1660 void KeychainDatabase::instantiateAcl()
1662 StLock
<Mutex
> _(common());
1663 makeUnlocked(false);
1666 void KeychainDatabase::changedAcl()
1668 StLock
<Mutex
> _(common());
1674 // Check an incoming DbBlob for basic viability
1676 void KeychainDatabase::validateBlob(const DbBlob
*blob
)
1678 // perform basic validation on the blob
1680 blob
->validate(CSSMERR_APPLEDL_INVALID_DATABASE_BLOB
);
1681 switch (blob
->version()) {
1682 #if defined(COMPAT_OSX_10_0)
1683 case DbBlob::version_MacOS_10_0
:
1686 case DbBlob::version_MacOS_10_1
:
1688 case DbBlob::version_partition
:
1691 CssmError::throwMe(CSSMERR_APPLEDL_INCOMPATIBLE_DATABASE_BLOB
);
1696 // Check if this database is currently recoding
1698 bool KeychainDatabase::isRecoding()
1700 secnotice("integrity", "recoding source: %p", mRecodingSource
.get());
1701 return (mRecodingSource
.get() != NULL
|| mRecoded
);
1705 // Mark ourselves as no longer recoding
1707 void KeychainDatabase::recodeFinished()
1709 secnotice("integrity", "recoding finished");
1710 mRecodingSource
= NULL
;
1716 // Debugging support
1718 #if defined(DEBUGDUMP)
1720 void KeychainDbCommon::dumpNode()
1722 PerSession::dumpNode();
1723 uint32 sig
; memcpy(&sig
, &mIdentifier
.signature(), sizeof(sig
));
1724 Debug::dump(" %s[%8.8x]", mIdentifier
.dbName(), sig
);
1726 Debug::dump(" locked");
1728 time_t whenTime
= time_t(when());
1729 Debug::dump(" unlocked(%24.24s/%.2g)", ctime(&whenTime
),
1730 (when() - Time::now()).seconds());
1732 Debug::dump(" params=(%u,%u)", mParams
.idleTimeout
, mParams
.lockOnSleep
);
1735 void KeychainDatabase::dumpNode()
1737 PerProcess::dumpNode();
1738 Debug::dump(" %s vers=%u",
1739 mValidData
? " data" : " nodata", version
);
1741 uint32 sig
; memcpy(&sig
, &mBlob
->randomSignature
, sizeof(sig
));
1742 Debug::dump(" blob=%p[%8.8x]", mBlob
, sig
);
1744 Debug::dump(" noblob");
1752 // DbCommon basic features
1754 KeychainDbCommon::KeychainDbCommon(Session
&ssn
, const DbIdentifier
&id
, uint32 requestedVersion
)
1755 : LocalDbCommon(ssn
), DatabaseCryptoCore(requestedVersion
), sequence(0), version(1), mIdentifier(id
),
1756 mIsLocked(true), mValidParams(false), mLoginKeychain(false)
1758 // match existing DbGlobal or create a new one
1760 Server
&server
= Server::active();
1761 StLock
<Mutex
> _(server
);
1762 if (KeychainDbGlobal
*dbglobal
=
1763 server
.findFirst
<KeychainDbGlobal
, const DbIdentifier
&>(&KeychainDbGlobal::identifier
, identifier())) {
1765 secinfo("KCdb", "%p linking to existing DbGlobal %p", this, dbglobal
);
1767 // DbGlobal not present; make a new one
1768 parent(*new KeychainDbGlobal(identifier()));
1769 secinfo("KCdb", "%p linking to new DbGlobal %p", this, &global());
1772 // link lifetime to the Session
1773 session().addReference(*this);
1775 if (strcasestr(id
.dbName(), "login.keychain") != NULL
) {
1776 mLoginKeychain
= true;
1781 void KeychainDbCommon::initializeKeybag() {
1782 if (mLoginKeychain
&& !session().keybagGetState(session_keybag_loaded
)) {
1783 service_context_t context
= session().get_current_service_context();
1784 if (service_client_kb_load(&context
) == 0) {
1785 session().keybagSetState(session_keybag_loaded
);
1790 KeychainDbCommon::KeychainDbCommon(Session
&ssn
, const DbIdentifier
&id
, KeychainDbCommon
& toClone
)
1791 : LocalDbCommon(ssn
), DatabaseCryptoCore(toClone
.mBlobVersion
), sequence(toClone
.sequence
), mParams(toClone
.mParams
), version(toClone
.version
),
1792 mIdentifier(id
), mIsLocked(toClone
.mIsLocked
), mValidParams(toClone
.mValidParams
), mLoginKeychain(toClone
.mLoginKeychain
)
1797 Server
&server
= Server::active();
1798 StLock
<Mutex
> _(server
);
1799 if (KeychainDbGlobal
*dbglobal
=
1800 server
.findFirst
<KeychainDbGlobal
, const DbIdentifier
&>(&KeychainDbGlobal::identifier
, identifier())) {
1802 secinfo("KCdb", "%p linking to existing DbGlobal %p", this, dbglobal
);
1804 // DbGlobal not present; make a new one
1805 parent(*new KeychainDbGlobal(identifier()));
1806 secinfo("KCdb", "%p linking to new DbGlobal %p", this, &global());
1808 session().addReference(*this);
1812 KeychainDbCommon::~KeychainDbCommon()
1814 secinfo("KCdb", "releasing keychain %p %s", this, (char*)this->dbName());
1816 // explicitly unschedule ourselves
1817 Server::active().clearTimer(this);
1818 if (mLoginKeychain
) {
1819 session().keybagClearState(session_keybag_unlocked
);
1821 // remove ourselves from mCommonSet
1825 void KeychainDbCommon::cloneFrom(KeychainDbCommon
& toClone
, uint32 requestedVersion
) {
1826 // don't clone the mIdentifier
1827 sequence
= toClone
.sequence
;
1828 mParams
= toClone
.mParams
;
1829 version
= toClone
.version
;
1830 mIsLocked
= toClone
.mIsLocked
;
1831 mValidParams
= toClone
.mValidParams
;
1832 mLoginKeychain
= toClone
.mLoginKeychain
;
1834 DatabaseCryptoCore::initializeFrom(toClone
, requestedVersion
);
1837 void KeychainDbCommon::kill()
1839 StReadWriteLock
_(mRWCommonLock
, StReadWriteLock::Write
);
1840 mCommonSet
.erase(this);
1843 KeychainDbGlobal
&KeychainDbCommon::global() const
1845 return parent
<KeychainDbGlobal
>();
1849 void KeychainDbCommon::select()
1852 void KeychainDbCommon::unselect()
1857 void KeychainDbCommon::makeNewSecrets()
1859 // we already have a master key (right?)
1860 assert(hasMaster());
1862 // tell crypto core to generate the use keys
1863 DatabaseCryptoCore::generateNewSecrets();
1865 // we're now officially "unlocked"; set the timer
1871 // All unlocking activity ultimately funnels through this method.
1872 // This unlocks a DbCommon using the secrets setup in its crypto core
1873 // component, and performs all the housekeeping needed to represent
1874 // the state change.
1875 // Returns true if unlock was successful, false if it failed due to
1876 // invalid/insufficient secrets. Throws on other errors.
1878 bool KeychainDbCommon::unlockDb(DbBlob
*blob
, void **privateAclBlob
)
1881 // Tell the cryptocore to (try to) decode itself. This will fail
1882 // in an astonishing variety of ways if the passphrase is wrong.
1883 assert(hasMaster());
1884 decodeCore(blob
, privateAclBlob
);
1885 secinfo("KCdb", "%p unlock successful", this);
1887 secinfo("KCdb", "%p unlock failed", this);
1891 // get the database parameters only if we haven't got them yet
1892 if (!mValidParams
) {
1893 mParams
= blob
->params
;
1894 n2hi(mParams
.idleTimeout
);
1895 mValidParams
= true; // sticky
1898 bool isLocked
= mIsLocked
;
1900 setUnlocked(); // mark unlocked
1903 // broadcast unlock notification, but only if we were previously locked
1904 notify(kNotificationEventUnlocked
);
1905 secinfo("KCdb", "unlocking keychain %p %s", this, (char*)this->dbName());
1910 void KeychainDbCommon::setUnlocked()
1912 session().addReference(*this); // active/held
1913 mIsLocked
= false; // mark unlocked
1914 activity(); // set timeout timer
1918 void KeychainDbCommon::lockDb()
1921 StLock
<Mutex
> _(*this);
1923 DatabaseCryptoCore::invalidate();
1924 notify(kNotificationEventLocked
);
1925 secinfo("KCdb", "locking keychain %p %s", this, (char*)this->dbName());
1926 Server::active().clearTimer(this);
1928 mIsLocked
= true; // mark locked
1930 // this call may destroy us if we have no databases anymore
1931 session().removeReference(*this);
1937 DbBlob
*KeychainDbCommon::encode(KeychainDatabase
&db
)
1939 assert(!isLocked()); // must have been unlocked by caller
1941 // export database ACL to blob form
1942 CssmData pubAcl
, privAcl
;
1943 db
.acl().exportBlob(pubAcl
, privAcl
);
1945 // tell the cryptocore to form the blob
1947 form
.randomSignature
= identifier();
1948 form
.sequence
= sequence
;
1949 form
.params
= mParams
;
1950 h2ni(form
.params
.idleTimeout
);
1952 assert(hasMaster());
1953 DbBlob
*blob
= encodeCore(form
, pubAcl
, privAcl
);
1956 db
.acl().allocator
.free(pubAcl
);
1957 db
.acl().allocator
.free(privAcl
);
1963 // Perform deferred lock processing for a database.
1965 void KeychainDbCommon::action()
1967 secinfo("KCdb", "common %s(%p) locked by timer", dbName(), this);
1971 void KeychainDbCommon::activity()
1974 secinfo("KCdb", "setting DbCommon %p timer to %d",
1975 this, int(mParams
.idleTimeout
));
1976 Server::active().setTimer(this, Time::Interval(int(mParams
.idleTimeout
)));
1980 void KeychainDbCommon::sleepProcessing()
1982 secinfo("KCdb", "common %s(%p) sleep-lock processing", dbName(), this);
1983 if (mParams
.lockOnSleep
&& !isDefaultSystemKeychain()) {
1984 StLock
<Mutex
> _(*this);
1989 void KeychainDbCommon::lockProcessing()
1996 // We consider a keychain to belong to the system domain if it resides
1997 // in /Library/Keychains. That's not exactly fool-proof, but we don't
1998 // currently have any internal markers to interrogate.
2000 bool KeychainDbCommon::belongsToSystem() const
2002 if (const char *name
= this->dbName())
2003 return !strncmp(name
, "/Library/Keychains/", 19);
2007 bool KeychainDbCommon::isDefaultSystemKeychain() const
2009 // /Library/Keychains/System.keychain (34)
2010 if (const char *name
= this->dbName())
2011 return !strncmp(name
, "/Library/Keychains/System.keychain", 34);
2016 // Keychain global objects
2018 KeychainDbGlobal::KeychainDbGlobal(const DbIdentifier
&id
)
2023 KeychainDbGlobal::~KeychainDbGlobal()
2025 secinfo("KCdb", "DbGlobal %p destroyed", this);