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
:
198 Okay, this is messy. We need to hold the common lock to be certain we're modifying the world
199 as we intend. But UI ^ common, and QueryKeybagPassphrase::query() has tons of side effects by necessity,
200 so just confirm that the operation did what we wanted after the fact.
202 bool query_success
= false;
203 bool unlock_success
= false;
207 StSyncLock
<Mutex
, Mutex
> uisync(db
.common().uiLock(), db
.common());
208 // Once we get the ui lock, check whether another thread has already unlocked keybag
210 query_success
= false;
211 service_context_t context
= db
.common().session().get_current_service_context();
212 if ((service_client_kb_is_locked(&context
, &locked
, NULL
) == 0) && locked
) {
213 QueryKeybagPassphrase
keybagQuery(db
.common().session(), 3);
214 keybagQuery
.inferHints(Server::process());
215 if (keybagQuery
.query() == SecurityAgent::noReason
) {
216 query_success
= true;
219 // another thread already unlocked the keybag
220 query_success
= true; // NOT unlock_success because we have the wrong lock
222 } // StSyncLock goes out of scope, we have common lock again
224 service_context_t context
= db
.common().session().get_current_service_context();
225 if ((service_client_kb_is_locked(&context
, &locked
, NULL
) == 0) && !locked
) {
226 unlock_success
= true;
229 secnotice("KCdb", "Unlocking the keybag again (threading?)");
232 } while (query_success
&& !unlock_success
);
235 // try to use an explicitly given passphrase - Data:passphrase
236 case CSSM_SAMPLE_TYPE_PASSWORD
: {
237 if (sample
.length() != 2)
238 CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE
);
239 secinfo("KCdb", "attempting passphrase unlock of keybag");
240 if (unlock_keybag(db
, sample
[1].data().data(), (int)sample
[1].data().length())) {
246 // Unknown sub-sample for unlocking.
247 secinfo("KCdb", "keybag: unknown sub-sample unlock (%d) ignored", sample
.type());
257 // Create a Database object from initial parameters (create operation)
259 KeychainDatabase::KeychainDatabase(const DLDbIdentifier
&id
, const DBParameters
¶ms
, Process
&proc
,
260 const AccessCredentials
*cred
, const AclEntryPrototype
*owner
)
261 : LocalDatabase(proc
), mValidData(false), mSecret(Allocator::standard(Allocator::sensitive
)), mSaveSecret(false), version(0), mBlob(NULL
), mRecoded(false)
263 // save a copy of the credentials for later access control
264 mCred
= DataWalkers::copy(cred
, Allocator::standard());
266 // create a new random signature to complete the DLDbIdentifier
267 DbBlob::Signature newSig
;
268 Server::active().random(newSig
.bytes
);
269 DbIdentifier
ident(id
, newSig
);
271 // create common block and initialize
272 // Since this is a creation step, figure out the correct blob version for this database
273 RefPointer
<KeychainDbCommon
> newCommon
= new KeychainDbCommon(proc
.session(), ident
, CommonBlob::getCurrentVersionForDb(ident
.dbName()));
274 newCommon
->initializeKeybag();
276 StLock
<Mutex
> _(*newCommon
);
279 // new common is now visible (in ident-map) but we hold its lock
281 // establish the new master secret
282 establishNewSecrets(cred
, SecurityAgent::newDatabase
);
284 // set initial database parameters
285 common().mParams
= params
;
287 // the common is "unlocked" now
288 common().makeNewSecrets();
290 // establish initial ACL
292 acl().cssmSetInitial(*owner
);
294 acl().cssmSetInitial(new AnyAclSubject());
297 // for now, create the blob immediately
300 proc
.addReference(*this);
302 // this new keychain is unlocked; make it so
305 secinfo("KCdb", "creating keychain %p %s with common %p", this, (char*)this->dbName(), &common());
310 // Create a Database object from a database blob (decoding)
312 KeychainDatabase::KeychainDatabase(const DLDbIdentifier
&id
, const DbBlob
*blob
, Process
&proc
,
313 const AccessCredentials
*cred
)
314 : LocalDatabase(proc
), mValidData(false), mSecret(Allocator::standard(Allocator::sensitive
)), mSaveSecret(false), version(0), mBlob(NULL
), mRecoded(false)
318 // save a copy of the credentials for later access control
319 mCred
= DataWalkers::copy(cred
, Allocator::standard());
320 mBlob
= blob
->copy();
322 // check to see if we already know about this database
323 DbIdentifier
ident(id
, blob
->randomSignature
);
324 Session
&session
= process().session();
325 RefPointer
<KeychainDbCommon
> com
;
326 secinfo("kccommon", "looking for a common at %s", ident
.dbName());
327 if (KeychainDbCommon::find(ident
, session
, com
)) {
329 secinfo("KCdb", "joining keychain %p %s with common %p", this, (char*)this->dbName(), &common());
331 // DbCommon not present; make a new one
332 secinfo("kccommon", "no common found");
334 common().mParams
= blob
->params
;
335 secinfo("KCdb", "making keychain %p %s with common %p", this, (char*)this->dbName(), &common());
336 // this DbCommon is locked; no timer or reference setting
338 proc
.addReference(*this);
341 void KeychainDbCommon::insert()
343 StReadWriteLock
_(mRWCommonLock
, StReadWriteLock::Write
);
347 void KeychainDbCommon::insertHoldingLock()
349 mCommonSet
.insert(this);
354 // find or make a DbCommon. Returns true if an existing one was found and used.
355 bool KeychainDbCommon::find(const DbIdentifier
&ident
, Session
&session
, RefPointer
<KeychainDbCommon
> &common
, uint32 requestedVersion
, KeychainDbCommon
* cloneFrom
)
357 // Prepare to drop the mRWCommonLock.
359 StReadWriteLock
_(mRWCommonLock
, StReadWriteLock::Read
);
360 for (CommonSet::const_iterator it
= mCommonSet
.begin(); it
!= mCommonSet
.end(); ++it
) {
361 if (&session
== &(*it
)->session() && ident
== (*it
)->identifier()) {
363 secinfo("kccommon", "found a common for %s at %p", ident
.dbName(), common
.get());
369 // not found. Grab the write lock, ensure that nobody has beaten us to adding,
370 // and then create a DbCommon and add it to the map.
372 StReadWriteLock
_(mRWCommonLock
, StReadWriteLock::Write
);
373 for (CommonSet::const_iterator it
= mCommonSet
.begin(); it
!= mCommonSet
.end(); ++it
) {
374 if (&session
== &(*it
)->session() && ident
== (*it
)->identifier()) {
376 secinfo("kccommon", "found a common for %s at %p", ident
.dbName(), common
.get());
383 common
= new KeychainDbCommon(session
, ident
, *cloneFrom
);
384 } else if(requestedVersion
!= CommonBlob::version_none
) {
385 common
= new KeychainDbCommon(session
, ident
, requestedVersion
);
387 common
= new KeychainDbCommon(session
, ident
);
390 secinfo("kccommon", "made a new common for %s at %p", ident
.dbName(), common
.get());
392 // Can't call insert() here, because it grabs the write lock (which we have).
393 common
->insertHoldingLock();
395 common
->initializeKeybag();
401 // Special-purpose constructor for keychain synchronization. Copies an
402 // existing keychain but uses the operational keys from secretsBlob. The
403 // new KeychainDatabase will silently replace the existing KeychainDatabase
404 // as soon as the client declares that re-encoding of all keychain items is
405 // finished. This is a little perilous since it allows a client to dictate
406 // securityd state, but we try to ensure that only the client that started
407 // the re-encoding can declare it done.
409 KeychainDatabase::KeychainDatabase(KeychainDatabase
&src
, Process
&proc
, DbHandle dbToClone
)
410 : LocalDatabase(proc
), mValidData(false), mSecret(Allocator::standard(Allocator::sensitive
)), mSaveSecret(false), version(0), mBlob(NULL
), mRecoded(false)
412 mCred
= DataWalkers::copy(src
.mCred
, Allocator::standard());
414 // Give this KeychainDatabase a temporary name
415 std::string newDbName
= std::string("////") + std::string(src
.identifier().dbName());
416 DLDbIdentifier
newDLDbIdent(src
.identifier().dlDbIdentifier().ssuid(), newDbName
.c_str(), src
.identifier().dlDbIdentifier().dbLocation());
417 DbIdentifier
ident(newDLDbIdent
, src
.identifier());
419 // create common block and initialize
420 RefPointer
<KeychainDbCommon
> newCommon
= new KeychainDbCommon(proc
.session(), ident
);
421 newCommon
->initializeKeybag();
422 StLock
<Mutex
> _(*newCommon
);
426 // set initial database parameters from the source keychain
427 common().mParams
= src
.common().mParams
;
429 // establish the source keychain's master secret as ours
430 // @@@ NB: this is a v. 0.1 assumption. We *should* trigger new UI
431 // that offers the user the option of using the existing password
432 // or choosing a new one. That would require a new
433 // SecurityAgentQuery type, new UI, and--possibly--modifications to
434 // ensure that the new password is available here to generate the
435 // new master secret.
436 src
.unlockDb(false); // precaution for masterKey()
437 common().setup(src
.blob(), src
.common().masterKey());
439 // import the operational secrets
440 RefPointer
<KeychainDatabase
> srcKC
= Server::keychain(dbToClone
);
441 common().importSecrets(srcKC
->common());
443 // import source keychain's ACL
444 CssmData pubAcl
, privAcl
;
445 src
.acl().exportBlob(pubAcl
, privAcl
);
446 importBlob(pubAcl
.data(), privAcl
.data());
447 src
.acl().allocator
.free(pubAcl
);
448 src
.acl().allocator
.free(privAcl
);
450 // indicate that this keychain should be allowed to do some otherwise
451 // risky things required for copying, like re-encoding keys
452 mRecodingSource
= &src
;
454 common().setUnlocked();
459 proc
.addReference(*this);
460 secinfo("SSdb", "database %s(%p) created as copy, common at %p",
461 common().dbName(), this, &common());
464 // Make a new KeychainDatabase from an old one, but have a completely different location
465 KeychainDatabase::KeychainDatabase(const DLDbIdentifier
& id
, KeychainDatabase
&src
, Process
&proc
)
466 : LocalDatabase(proc
), mValidData(false), mSecret(Allocator::standard(Allocator::sensitive
)), mSaveSecret(false), version(0), mBlob(NULL
), mRecoded(false)
468 mCred
= DataWalkers::copy(src
.mCred
, Allocator::standard());
470 DbIdentifier
ident(id
, src
.identifier());
472 // create common block and initialize
473 RefPointer
<KeychainDbCommon
> newCommon
;
474 if(KeychainDbCommon::find(ident
, process().session(), newCommon
, CommonBlob::version_none
, &src
.common())) {
475 // A common already existed. Write over it, but note that everything may go horribly from here on out.
476 secinfo("kccommon", "Found common where we didn't expect. Possible strange behavior ahead.");
477 newCommon
->cloneFrom(src
.common());
480 StLock
<Mutex
> _(*newCommon
);
483 // set initial database parameters from the source keychain
484 common().mParams
= src
.common().mParams
;
486 // import source keychain's ACL
487 CssmData pubAcl
, privAcl
;
488 src
.acl().exportBlob(pubAcl
, privAcl
);
489 importBlob(pubAcl
.data(), privAcl
.data());
490 src
.acl().allocator
.free(pubAcl
);
491 src
.acl().allocator
.free(privAcl
);
493 // Copy the source database's blob, if possible
495 mBlob
= src
.mBlob
->copy();
496 version
= src
.version
;
499 // We've copied everything we can from our source. If they were valid, so are we.
500 mValidData
= src
.mValidData
;
502 proc
.addReference(*this);
503 secinfo("SSdb", "database %s(%p) created as expected clone, common at %p", common().dbName(), this, &common());
507 // Make a new KeychainDatabase from an old one, but have entirely new operational secrets
508 KeychainDatabase::KeychainDatabase(uint32 requestedVersion
, KeychainDatabase
&src
, Process
&proc
)
509 : LocalDatabase(proc
), mValidData(false), mSecret(Allocator::standard(Allocator::sensitive
)), mSaveSecret(false), version(0), mBlob(NULL
), mRecoded(false)
511 mCred
= DataWalkers::copy(src
.mCred
, Allocator::standard());
513 // Give this KeychainDatabase a temporary name
514 // this must canonicalize to a different path than the original DB, otherwise another process opening the existing DB wil find this new KeychainDbCommon
515 // and call decodeCore with the old blob, overwriting the new secrets and wreaking havoc
516 std::string newDbName
= std::string("////") + std::string(src
.identifier().dbName()) + std::string("_com.apple.security.keychain.migrating");
517 DLDbIdentifier
newDLDbIdent(src
.identifier().dlDbIdentifier().ssuid(), newDbName
.c_str(), src
.identifier().dlDbIdentifier().dbLocation());
518 DbIdentifier
ident(newDLDbIdent
, src
.identifier());
520 // hold the lock for src's common during this operation (to match locking common locking order with KeychainDatabase::recodeKey)
521 StLock
<Mutex
> __(src
.common());
523 // create common block and initialize
524 RefPointer
<KeychainDbCommon
> newCommon
;
525 if(KeychainDbCommon::find(ident
, process().session(), newCommon
, requestedVersion
)) {
526 // A common already existed here. Write over it, but note that everything may go horribly from here on out.
527 secinfo("kccommon", "Found common where we didn't expect. Possible strange behavior ahead.");
528 newCommon
->cloneFrom(src
.common(), requestedVersion
);
530 newCommon
->initializeKeybag();
531 StLock
<Mutex
> _(*newCommon
);
534 // We want to re-use the master secrets from the source database (and so the
535 // same password), but reroll new operational secrets.
537 // Copy the master secret over...
538 src
.unlockDb(false); // precaution
540 common().setup(src
.blob(), src
.common().masterKey(), false); // keep the new common's version intact
542 // set initial database parameters from the source keychain
543 common().mParams
= src
.common().mParams
;
545 // and make new operational secrets
546 common().makeNewSecrets();
548 // import source keychain's ACL
549 CssmData pubAcl
, privAcl
;
550 src
.acl().exportBlob(pubAcl
, privAcl
);
551 importBlob(pubAcl
.data(), privAcl
.data());
552 src
.acl().allocator
.free(pubAcl
);
553 src
.acl().allocator
.free(privAcl
);
555 // indicate that this keychain should be allowed to do some otherwise
556 // risky things required for copying, like re-encoding keys
557 mRecodingSource
= &src
;
559 common().setUnlocked();
564 proc
.addReference(*this);
565 secinfo("SSdb", "database %s(%p) created as expected copy, common at %p",
566 common().dbName(), this, &common());
570 // Destroy a Database
572 KeychainDatabase::~KeychainDatabase()
574 secinfo("KCdb", "deleting database %s(%p) common %p",
575 common().dbName(), this, &common());
576 Allocator::standard().free(mCred
);
577 Allocator::standard().free(mBlob
);
582 // Basic Database virtual implementations
584 KeychainDbCommon
&KeychainDatabase::common() const
586 return parent
<KeychainDbCommon
>();
589 const char *KeychainDatabase::dbName() const
591 return common().dbName();
594 bool KeychainDatabase::transient() const
596 return false; // has permanent store
599 AclKind
KeychainDatabase::aclKind() const
604 Database
*KeychainDatabase::relatedDatabase()
610 // (Re-)Authenticate the database. This changes the stored credentials.
612 void KeychainDatabase::authenticate(CSSM_DB_ACCESS_TYPE mode
,
613 const AccessCredentials
*cred
)
615 StLock
<Mutex
> _(common());
617 // the (Apple specific) RESET bit means "lock the database now"
619 case CSSM_DB_ACCESS_RESET
:
620 secinfo("KCdb", "%p ACCESS_RESET triggers keychain lock", this);
624 // store the new credentials for future use
625 secinfo("KCdb", "%p authenticate stores new database credentials", this);
626 AccessCredentials
*newCred
= DataWalkers::copy(cred
, Allocator::standard());
627 Allocator::standard().free(mCred
);
634 // Make a new KeychainKey.
635 // If PERMANENT is off, make a temporary key instead.
636 // The db argument allows you to create for another KeychainDatabase (only);
637 // it defaults to ourselves.
639 RefPointer
<Key
> KeychainDatabase::makeKey(Database
&db
, const CssmKey
&newKey
,
640 uint32 moreAttributes
, const AclEntryPrototype
*owner
)
642 StLock
<Mutex
> lock(common());
643 if (moreAttributes
& CSSM_KEYATTR_PERMANENT
)
644 return new KeychainKey(db
, newKey
, moreAttributes
, owner
);
646 return process().makeTemporaryKey(newKey
, moreAttributes
, owner
);
649 RefPointer
<Key
> KeychainDatabase::makeKey(const CssmKey
&newKey
,
650 uint32 moreAttributes
, const AclEntryPrototype
*owner
)
652 return makeKey(*this, newKey
, moreAttributes
, owner
);
657 // Return the database blob, recalculating it as needed.
659 DbBlob
*KeychainDatabase::blob()
661 StLock
<Mutex
> _(common());
663 makeUnlocked(false); // unlock to get master secret
664 encode(); // (re)encode blob if needed
666 activity(); // reset timeout
667 assert(validBlob()); // better have a valid blob now...
673 // Encode the current database as a blob.
674 // Note that this returns memory we own and keep.
675 // Caller must hold common lock.
677 void KeychainDatabase::encode()
679 DbBlob
*blob
= common().encode(*this);
680 Allocator::standard().free(mBlob
);
682 version
= common().version
;
683 secinfo("KCdb", "encoded database %p common %p(%s) version %u params=(%u,%u)",
684 this, &common(), dbName(), version
,
685 common().mParams
.idleTimeout
, common().mParams
.lockOnSleep
);
690 // Change the passphrase on a database
692 void KeychainDatabase::changePassphrase(const AccessCredentials
*cred
)
694 // get and hold the common lock (don't let other threads break in here)
695 StLock
<Mutex
> _(common());
697 // establish OLD secret - i.e. unlock the database
698 //@@@ do we want to leave the final lock state alone?
699 if (common().isLoginKeychain()) mSaveSecret
= true;
700 makeUnlocked(cred
, false);
702 // establish NEW secret
703 if(!establishNewSecrets(cred
, SecurityAgent::changePassphrase
)) {
704 secinfo("KCdb", "Old and new passphrases are the same. Database %s(%p) master secret did not change.",
705 common().dbName(), this);
708 if (mSecret
) { mSecret
.reset(); }
710 common().invalidateBlob(); // blob state changed
711 secinfo("KCdb", "Database %s(%p) master secret changed", common().dbName(), this);
712 encode(); // force rebuild of local blob
714 // send out a notification
715 notify(kNotificationEventPassphraseChanged
);
717 // I guess this counts as an activity
722 // Second stage of keychain synchronization: overwrite the original keychain's
723 // (this KeychainDatabase's) operational secrets
725 void KeychainDatabase::commitSecretsForSync(KeychainDatabase
&cloneDb
)
727 StLock
<Mutex
> _(common());
729 // try to detect spoofing
730 if (cloneDb
.mRecodingSource
!= this)
731 CssmError::throwMe(CSSM_ERRCODE_INVALID_DB_HANDLE
);
733 // in case we autolocked since starting the sync
734 makeUnlocked(false); // call this because we already own the lock
735 cloneDb
.unlockDb(false); // we may not own the lock here, so calling unlockDb will lock the cloneDb's common lock
737 // Decode all keys whose handles refer to this on-disk keychain so that
738 // if the holding client commits the key back to disk, it's encoded with
739 // the new operational secrets. The recoding client *must* hold a write
740 // lock for the on-disk keychain from the moment it starts recoding key
741 // items until after this call.
743 // @@@ This specific implementation is a workaround for 4003540.
744 std::vector
<U32HandleObject::Handle
> handleList
;
745 U32HandleObject::findAllRefs
<KeychainKey
>(handleList
);
746 size_t count
= handleList
.size();
748 for (unsigned int n
= 0; n
< count
; ++n
) {
749 RefPointer
<KeychainKey
> kckey
=
750 U32HandleObject::findRefAndLock
<KeychainKey
>(handleList
[n
], CSSMERR_CSP_INVALID_KEY_REFERENCE
);
751 StLock
<Mutex
> _(*kckey
/*, true*/);
752 if (kckey
->database().global().identifier() == identifier()) {
753 kckey
->key(); // force decode
754 kckey
->invalidateBlob();
755 secinfo("kcrecode", "changed extant key %p (proc %d)",
756 &*kckey
, kckey
->process().pid());
761 // mark down that we just recoded
764 // it is now safe to replace the old op secrets
765 common().importSecrets(cloneDb
.common());
766 common().invalidateBlob();
771 // Extract the database master key as a proper Key object.
773 RefPointer
<Key
> KeychainDatabase::extractMasterKey(Database
&db
,
774 const AccessCredentials
*cred
, const AclEntryPrototype
*owner
,
775 uint32 usage
, uint32 attrs
)
777 // get and hold common lock
778 StLock
<Mutex
> _(common());
780 // force lock to require re-validation of credentials
783 // unlock to establish master secret
786 // extract the raw cryptographic key
787 CssmClient::WrapKey
wrap(Server::csp(), CSSM_ALGID_NONE
);
789 wrap(common().masterKey(), key
);
791 // make the key object and return it
792 return makeKey(db
, key
, attrs
& LocalKey::managedAttributes
, owner
);
797 // Unlock this database (if needed) by obtaining the master secret in some
798 // suitable way and then proceeding to unlock with it.
799 // Does absolutely nothing if the database is already unlocked.
800 // The makeUnlocked forms are identical except the assume the caller already
801 // holds the common lock.
803 void KeychainDatabase::unlockDb(bool unlockKeybag
)
805 StLock
<Mutex
> _(common());
806 makeUnlocked(unlockKeybag
);
809 void KeychainDatabase::makeUnlocked(bool unlockKeybag
)
811 return makeUnlocked(mCred
, unlockKeybag
);
814 void KeychainDatabase::makeUnlocked(const AccessCredentials
*cred
, bool unlockKeybag
)
817 secnotice("KCdb", "%p(%p) unlocking for makeUnlocked()", this, &common());
818 assert(mBlob
|| (mValidData
&& common().hasMaster()));
819 bool asking_again
= false;
822 secnotice("KCdb", "makeUnlocked: establishing old secrets again (threading?)");
824 establishOldSecrets(cred
);
826 } while (!common().hasMaster());
827 common().setUnlocked(); // mark unlocked
828 if (common().isLoginKeychain()) {
829 CssmKey master
= common().masterKey();
831 CssmClient::WrapKey
wrap(Server::csp(), CSSM_ALGID_NONE
);
832 wrap(master
, rawMaster
);
834 service_context_t context
= common().session().get_current_service_context();
835 service_client_stash_load_key(&context
, rawMaster
.keyData(), (int)rawMaster
.length());
837 } else if (unlockKeybag
&& common().isLoginKeychain()) {
839 service_context_t context
= common().session().get_current_service_context();
840 if ((service_client_kb_is_locked(&context
, &locked
, NULL
) == 0) && locked
) {
841 if (!unlock_keybag_with_cred(*this, cred
)) {
842 syslog(LOG_NOTICE
, "failed to unlock iCloud keychain");
846 if (!mValidData
) { // need to decode to get our ACLs, master secret available
847 secnotice("KCdb", "%p(%p) is unlocked; decoding for makeUnlocked()", this, &common());
849 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED
);
856 // Invoke the securityd_service to retrieve the keychain master
857 // key from the AppleFDEKeyStore.
859 void KeychainDatabase::stashDbCheck()
861 CssmAutoData
masterKey(Allocator::standard(Allocator::sensitive
));
862 CssmAutoData
encKey(Allocator::standard(Allocator::sensitive
));
866 void * stash_key
= NULL
;
867 int stash_key_len
= 0;
868 service_context_t context
= common().session().get_current_service_context();
869 rc
= service_client_stash_get_key(&context
, &stash_key
, &stash_key_len
);
872 masterKey
.copy(CssmData((void *)stash_key
,stash_key_len
));
873 memset(stash_key
, 0, stash_key_len
);
877 secnotice("KCdb", "failed to get stash from securityd_service: %d", (int)rc
);
878 CssmError::throwMe(rc
);
882 StLock
<Mutex
> _(common());
884 // Now establish it as the keychain master key
885 CssmClient::Key
key(Server::csp(), masterKey
.get());
886 CssmKey::Header
&hdr
= key
.header();
887 hdr
.keyClass(CSSM_KEYCLASS_SESSION_KEY
);
888 hdr
.algorithm(CSSM_ALGID_3DES_3KEY_EDE
);
889 hdr
.usage(CSSM_KEYUSE_ANY
);
890 hdr
.blobType(CSSM_KEYBLOB_RAW
);
891 hdr
.blobFormat(CSSM_KEYBLOB_RAW_FORMAT_OCTET_STRING
);
892 common().setup(mBlob
, key
);
895 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED
);
897 common().get_encryption_key(encKey
);
900 // when upgrading from pre-10.9 create a keybag if it doesn't exist with the encryption key
901 // only do this after we have verified the master key unlocks the login.keychain
902 if (service_client_kb_load(&context
) == KB_BagNotFound
) {
903 service_client_kb_create(&context
, encKey
.data(), (int)encKey
.length());
908 // Get the keychain master key and invoke the securityd_service
909 // to stash it in the AppleFDEKeyStore ready for commit to the
912 void KeychainDatabase::stashDb()
914 CssmAutoData
data(Allocator::standard(Allocator::sensitive
));
917 StLock
<Mutex
> _(common());
919 if (!common().isValid()) {
920 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY
);
923 CssmKey key
= common().masterKey();
924 data
.copy(key
.keyData());
927 service_context_t context
= common().session().get_current_service_context();
928 int rc
= service_client_stash_set_key(&context
, data
.data(), (int)data
.length());
929 if (rc
!= 0) CssmError::throwMe(rc
);
933 // The following unlock given an explicit passphrase, rather than using
934 // (special cred sample based) default procedures.
936 void KeychainDatabase::unlockDb(const CssmData
&passphrase
, bool unlockKeybag
)
938 StLock
<Mutex
> _(common());
939 makeUnlocked(passphrase
, unlockKeybag
);
942 void KeychainDatabase::makeUnlocked(const CssmData
&passphrase
, bool unlockKeybag
)
945 if (decode(passphrase
))
948 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED
);
949 } else if (!mValidData
) { // need to decode to get our ACLs, passphrase available
951 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED
);
954 if (unlockKeybag
&& common().isLoginKeychain()) {
956 service_context_t context
= common().session().get_current_service_context();
957 if (!common().session().keybagGetState(session_keybag_check_master_key
) || ((service_client_kb_is_locked(&context
, &locked
, NULL
) == 0) && locked
)) {
958 unlock_keybag(*this, passphrase
.data(), (int)passphrase
.length());
968 // Nonthrowing passphrase-based unlock. This returns false if unlock failed.
969 // Note that this requires an explicitly given passphrase.
970 // Caller must hold common lock.
972 bool KeychainDatabase::decode(const CssmData
&passphrase
)
975 common().setup(mBlob
, passphrase
);
976 bool success
= decode();
977 if (success
&& common().isLoginKeychain()) {
978 unlock_keybag(*this, passphrase
.data(), (int)passphrase
.length());
985 // Given the established master secret, decode the working keys and other
986 // functional secrets for this database. Return false (do NOT throw) if
987 // the decode fails. Call this in low(er) level code once you established
990 bool KeychainDatabase::decode()
993 assert(common().hasMaster());
994 void *privateAclBlob
;
995 if (common().unlockDb(mBlob
, &privateAclBlob
)) {
997 acl().importBlob(mBlob
->publicAclBlob(), privateAclBlob
);
1000 Allocator::standard().free(privateAclBlob
);
1003 secinfo("KCdb", "%p decode failed", this);
1009 // Given an AccessCredentials for this database, wring out the existing primary
1010 // database secret by whatever means necessary.
1011 // On entry, caller must hold the database common lock. It will be held
1012 // throughout except when user interaction is required. User interaction
1013 // requires relinquishing the database common lock and taking the UI lock. On
1014 // return from user interaction, the UI lock is relinquished and the database
1015 // common lock must be reacquired. At no time may the caller hold both locks.
1016 // On exit, the crypto core has its master secret. If things go wrong,
1017 // we will throw a suitable exception. Note that encountering any malformed
1018 // credential sample will throw, but this is not guaranteed -- don't assume
1019 // that NOT throwing means creds is entirely well-formed (it may just be good
1020 // enough to work THIS time).
1023 // Walk through the creds. Fish out those credentials (in order) that
1024 // are for unlock processing (they have no ACL subject correspondents),
1025 // and (try to) obey each in turn, until one produces a valid secret
1026 // or you run out. If no special samples are found at all, interpret that as
1027 // "use the system global default," which happens to be hard-coded right here.
1029 void KeychainDatabase::establishOldSecrets(const AccessCredentials
*creds
)
1031 bool forSystem
= this->belongsToSystem(); // this keychain belongs to the system security domain
1033 // attempt system-keychain unlock
1035 SystemKeychainKey
systemKeychain(kSystemUnlockFile
);
1036 if (systemKeychain
.matches(mBlob
->randomSignature
)) {
1037 secinfo("KCdb", "%p attempting system unlock", this);
1038 common().setup(mBlob
, CssmClient::Key(Server::csp(), systemKeychain
.key(), true));
1044 list
<CssmSample
> samples
;
1045 if (creds
&& creds
->samples().collect(CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK
, samples
)) {
1046 for (list
<CssmSample
>::iterator it
= samples
.begin(); it
!= samples
.end(); it
++) {
1047 TypedList
&sample
= *it
;
1048 sample
.checkProper();
1049 switch (sample
.type()) {
1050 // interactively prompt the user - no additional data
1051 case CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT
:
1053 if (interactiveUnlock())
1057 // try to use an explicitly given passphrase - Data:passphrase
1058 case CSSM_SAMPLE_TYPE_PASSWORD
:
1059 if (sample
.length() != 2)
1060 CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE
);
1061 secinfo("KCdb", "%p attempting passphrase unlock", this);
1062 if (decode(sample
[1]))
1065 // try to open with a given master key - Data:CSP or KeyHandle, Data:CssmKey
1066 case CSSM_SAMPLE_TYPE_SYMMETRIC_KEY
:
1067 case CSSM_SAMPLE_TYPE_ASYMMETRIC_KEY
:
1069 secinfo("KCdb", "%p attempting explicit key unlock", this);
1070 common().setup(mBlob
, keyFromCreds(sample
, 4));
1075 case CSSM_SAMPLE_TYPE_KEYBAG_KEY
:
1077 secinfo("KCdb", "%p attempting keybag key unlock", this);
1078 common().setup(mBlob
, keyFromKeybag(sample
));
1083 // explicitly defeat the default action but don't try anything in particular
1084 case CSSM_WORDID_CANCELED
:
1085 secinfo("KCdb", "%p defeat default action", this);
1088 // Unknown sub-sample for unlocking.
1089 // If we wanted to be fascist, we could now do
1090 // CssmError::throwMe(CSSM_ERRCODE_SAMPLE_VALUE_NOT_SUPPORTED);
1091 // But instead we try to be tolerant and continue on.
1092 // This DOES however count as an explicit attempt at specifying unlock,
1093 // so we will no longer try the default case below...
1094 secinfo("KCdb", "%p unknown sub-sample unlock (%d) ignored", this, sample
.type());
1103 if (interactiveUnlock())
1108 // out of options - no secret obtained
1109 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED
);
1113 // This function is almost identical to establishOldSecrets, but:
1114 // 1. It will never prompt the user; these credentials either work or they don't
1115 // 2. It will not change the secrets of this database
1117 // TODO: These two functions should probably be refactored to something nicer.
1118 bool KeychainDatabase::checkCredentials(const AccessCredentials
*creds
) {
1120 list
<CssmSample
> samples
;
1121 if (creds
&& creds
->samples().collect(CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK
, samples
)) {
1122 for (list
<CssmSample
>::iterator it
= samples
.begin(); it
!= samples
.end(); it
++) {
1123 TypedList
&sample
= *it
;
1124 sample
.checkProper();
1125 switch (sample
.type()) {
1126 // interactively prompt the user - no additional data
1127 case CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT
:
1128 // do nothing, because this function will never prompt the user
1129 secinfo("integrity", "%p ignoring keychain prompt", this);
1131 // try to use an explicitly given passphrase - Data:passphrase
1132 case CSSM_SAMPLE_TYPE_PASSWORD
:
1133 if (sample
.length() != 2)
1134 CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE
);
1135 secinfo("integrity", "%p checking passphrase", this);
1136 if(validatePassphrase(sample
[1])) {
1140 // try to open with a given master key - Data:CSP or KeyHandle, Data:CssmKey
1141 case CSSM_SAMPLE_TYPE_SYMMETRIC_KEY
:
1142 case CSSM_SAMPLE_TYPE_ASYMMETRIC_KEY
:
1144 secinfo("integrity", "%p attempting explicit key unlock", this);
1146 CssmClient::Key checkKey
= keyFromCreds(sample
, 4);
1147 if(common().validateKey(checkKey
)) {
1151 // ignore all problems in keyFromCreds
1152 secinfo("integrity", "%p caught error", this);
1159 // out of options - credentials don't match
1163 uint32_t KeychainDatabase::interactiveUnlockAttempts
= 0;
1165 // This does UI so needs the UI lock. It also interacts with the common, so needs the common lock. But can't have both at once!
1166 // Try to hold the UI lock for the smallest amount of time possible while having the common lock where needed.
1167 bool KeychainDatabase::interactiveUnlock()
1169 secinfo("KCdb", "%p attempting interactive unlock", this);
1170 interactiveUnlockAttempts
++;
1172 SecurityAgent::Reason reason
= SecurityAgent::noReason
;
1173 QueryUnlock
query(*this);
1176 query
.inferHints(Server::process());
1177 StSyncLock
<Mutex
, Mutex
> uisync(common().uiLock(), common());
1180 if (mSaveSecret
&& reason
== SecurityAgent::noReason
) {
1181 query
.retrievePassword(mSecret
);
1185 secinfo("KCdb", "%p was unlocked during uiLock delay", this);
1188 if (common().isLoginKeychain()) {
1189 bool locked
= false;
1190 service_context_t context
= common().session().get_current_service_context();
1191 if ((service_client_kb_is_locked(&context
, &locked
, NULL
) == 0) && locked
) {
1192 QueryKeybagNewPassphrase
keybagQuery(common().session());
1193 keybagQuery
.inferHints(Server::process());
1194 CssmAutoData
pass(Allocator::standard(Allocator::sensitive
));
1195 CssmAutoData
oldPass(Allocator::standard(Allocator::sensitive
));
1196 StSyncLock
<Mutex
, Mutex
> uisync(common().uiLock(), common());
1197 SecurityAgent::Reason queryReason
= keybagQuery
.query(oldPass
, pass
);
1199 if (queryReason
== SecurityAgent::noReason
) {
1200 service_client_kb_change_secret(&context
, oldPass
.data(), (int)oldPass
.length(), pass
.data(), (int)pass
.length());
1201 } else if (queryReason
== SecurityAgent::resettingPassword
) {
1202 query
.retrievePassword(pass
);
1203 service_client_kb_reset(&context
, pass
.data(), (int)pass
.length());
1209 return reason
== SecurityAgent::noReason
;
1212 uint32_t KeychainDatabase::getInteractiveUnlockAttempts() {
1213 if (csr_check(CSR_ALLOW_APPLE_INTERNAL
)) {
1214 // Not an internal install; don't answer
1217 return interactiveUnlockAttempts
;
1223 // Same thing, but obtain a new secret somehow and set it into the common.
1225 bool KeychainDatabase::establishNewSecrets(const AccessCredentials
*creds
, SecurityAgent::Reason reason
)
1227 list
<CssmSample
> samples
;
1228 if (creds
&& creds
->samples().collect(CSSM_SAMPLE_TYPE_KEYCHAIN_CHANGE_LOCK
, samples
)) {
1229 for (list
<CssmSample
>::iterator it
= samples
.begin(); it
!= samples
.end(); it
++) {
1230 TypedList
&sample
= *it
;
1231 sample
.checkProper();
1232 switch (sample
.type()) {
1233 // interactively prompt the user
1234 case CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT
:
1236 secinfo("KCdb", "%p specified interactive passphrase", this);
1237 QueryNewPassphrase
query(*this, reason
);
1238 StSyncLock
<Mutex
, Mutex
> uisync(common().uiLock(), common());
1239 query
.inferHints(Server::process());
1240 CssmAutoData
passphrase(Allocator::standard(Allocator::sensitive
));
1241 CssmAutoData
oldPassphrase(Allocator::standard(Allocator::sensitive
));
1242 SecurityAgent::Reason
reason(query(oldPassphrase
, passphrase
));
1244 if (reason
== SecurityAgent::noReason
) {
1245 common().setup(NULL
, passphrase
);
1246 change_secret_on_keybag(*this, oldPassphrase
.data(), (int)oldPassphrase
.length(), passphrase
.data(), (int)passphrase
.length());
1251 // try to use an explicitly given passphrase
1252 case CSSM_SAMPLE_TYPE_PASSWORD
:
1254 secinfo("KCdb", "%p specified explicit passphrase", this);
1255 if (sample
.length() != 2)
1256 CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE
);
1257 if (common().isLoginKeychain()) {
1258 CssmAutoData
oldPassphrase(Allocator::standard(Allocator::sensitive
));
1259 list
<CssmSample
> oldSamples
;
1260 creds
->samples().collect(CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK
, oldSamples
);
1261 for (list
<CssmSample
>::iterator oit
= oldSamples
.begin(); oit
!= oldSamples
.end(); oit
++) {
1262 TypedList
&tmpList
= *oit
;
1263 tmpList
.checkProper();
1264 if (tmpList
.type() == CSSM_SAMPLE_TYPE_PASSWORD
) {
1265 if (tmpList
.length() == 2) {
1266 oldPassphrase
= tmpList
[1].data();
1270 if (!oldPassphrase
.length() && mSecret
&& mSecret
.length()) {
1271 oldPassphrase
= mSecret
;
1273 if ((oldPassphrase
.length() == sample
[1].data().length()) &&
1274 !memcmp(oldPassphrase
.data(), sample
[1].data().data(), oldPassphrase
.length()) &&
1275 oldPassphrase
.length()) {
1276 // don't change master key if the passwords are the same
1279 common().setup(NULL
, sample
[1]);
1280 change_secret_on_keybag(*this, oldPassphrase
.data(), (int)oldPassphrase
.length(), sample
[1].data().data(), (int)sample
[1].data().length());
1283 common().setup(NULL
, sample
[1]);
1287 // try to open with a given master key
1288 case CSSM_WORDID_SYMMETRIC_KEY
:
1289 case CSSM_SAMPLE_TYPE_ASYMMETRIC_KEY
:
1290 secinfo("KCdb", "%p specified explicit master key", this);
1291 common().setup(NULL
, keyFromCreds(sample
, 3));
1293 // explicitly defeat the default action but don't try anything in particular
1294 case CSSM_WORDID_CANCELED
:
1295 secinfo("KCdb", "%p defeat default action", this);
1298 // Unknown sub-sample for acquiring new secret.
1299 // If we wanted to be fascist, we could now do
1300 // CssmError::throwMe(CSSM_ERRCODE_SAMPLE_VALUE_NOT_SUPPORTED);
1301 // But instead we try to be tolerant and continue on.
1302 // This DOES however count as an explicit attempt at specifying unlock,
1303 // so we will no longer try the default case below...
1304 secinfo("KCdb", "%p unknown sub-sample acquisition (%d) ignored",
1305 this, sample
.type());
1310 // default action -- interactive (only)
1311 QueryNewPassphrase
query(*this, reason
);
1312 StSyncLock
<Mutex
, Mutex
> uisync(common().uiLock(), common());
1313 query
.inferHints(Server::process());
1314 CssmAutoData
passphrase(Allocator::standard(Allocator::sensitive
));
1315 CssmAutoData
oldPassphrase(Allocator::standard(Allocator::sensitive
));
1316 SecurityAgent::Reason
reason(query(oldPassphrase
, passphrase
));
1318 if (reason
== SecurityAgent::noReason
) {
1319 common().setup(NULL
, passphrase
);
1320 change_secret_on_keybag(*this, oldPassphrase
.data(), (int)oldPassphrase
.length(), passphrase
.data(), (int)passphrase
.length());
1325 // out of options - no secret obtained
1326 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED
);
1331 // Given a (truncated) Database credentials TypedList specifying a master key,
1332 // locate the key and return a reference to it.
1334 CssmClient::Key
KeychainDatabase::keyFromCreds(const TypedList
&sample
, unsigned int requiredLength
)
1336 // decode TypedList structure (sample type; Data:CSPHandle; Data:CSSM_KEY)
1337 assert(sample
.type() == CSSM_SAMPLE_TYPE_SYMMETRIC_KEY
|| sample
.type() == CSSM_SAMPLE_TYPE_ASYMMETRIC_KEY
);
1338 if (sample
.length() != requiredLength
1339 || sample
[1].type() != CSSM_LIST_ELEMENT_DATUM
1340 || sample
[2].type() != CSSM_LIST_ELEMENT_DATUM
1341 || (requiredLength
== 4 && sample
[3].type() != CSSM_LIST_ELEMENT_DATUM
))
1342 CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE
);
1343 KeyHandle
&handle
= *sample
[1].data().interpretedAs
<KeyHandle
>(CSSM_ERRCODE_INVALID_SAMPLE_VALUE
);
1344 // We used to be able to check the length but supporting multiple client
1345 // architectures dishes that (sizeof(CSSM_KEY) varies due to alignment and
1346 // field-size differences). The decoding in the transition layer should
1347 // serve as a sufficient garbling check anyway.
1348 if (sample
[2].data().data() == NULL
)
1349 CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE
);
1350 CssmKey
&key
= *sample
[2].data().interpretedAs
<CssmKey
>();
1352 if (key
.header().cspGuid() == gGuidAppleCSPDL
) {
1353 // handleOrKey is a SecurityServer KeyHandle; ignore key argument
1354 return safer_cast
<LocalKey
&>(*Server::key(handle
));
1356 if (sample
.type() == CSSM_SAMPLE_TYPE_ASYMMETRIC_KEY
) {
1358 Contents (see DefaultCredentials::unlockKey in libsecurity_keychain/defaultcreds.cpp)
1360 sample[0] sample type
1361 sample[1] csp handle for master or wrapping key; is really a keyhandle
1362 sample[2] masterKey [not used since securityd cannot interpret; use sample[1] handle instead]
1363 sample[3] UnlockReferralRecord data, in this case the flattened symmetric key
1366 // RefPointer<Key> Server::key(KeyHandle key)
1367 KeyHandle keyhandle
= *sample
[1].data().interpretedAs
<KeyHandle
>(CSSM_ERRCODE_INVALID_SAMPLE_VALUE
);
1368 CssmData
&flattenedKey
= sample
[3].data();
1369 RefPointer
<Key
> unwrappingKey
= Server::key(keyhandle
);
1370 Database
&db
=unwrappingKey
->database();
1372 CssmKey rawWrappedKey
;
1373 unflattenKey(flattenedKey
, rawWrappedKey
);
1375 RefPointer
<Key
> masterKey
;
1376 CssmData emptyDescriptiveData
;
1377 const AccessCredentials
*cred
= NULL
;
1378 const AclEntryPrototype
*owner
= NULL
;
1379 CSSM_KEYUSE usage
= CSSM_KEYUSE_ANY
;
1380 CSSM_KEYATTR_FLAGS attrs
= CSSM_KEYATTR_EXTRACTABLE
; //CSSM_KEYATTR_RETURN_REF |
1382 // Get default credentials for unwrappingKey (the one on the token)
1383 // Copied from Statics::Statics() in libsecurity_keychain/aclclient.cpp
1384 // Following KeyItem::getCredentials, one sees that the "operation" parameter
1385 // e.g. "CSSM_ACL_AUTHORIZATION_DECRYPT" is ignored
1386 Allocator
&alloc
= Allocator::standard();
1387 AutoCredentials
promptCred(alloc
, 3);// enable interactive prompting
1389 // promptCred: a credential permitting user prompt confirmations
1391 // a KEYCHAIN_PROMPT sample, both by itself and in a THRESHOLD
1392 // a PROMPTED_PASSWORD sample
1393 promptCred
.sample(0) = TypedList(alloc
, CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT
);
1394 promptCred
.sample(1) = TypedList(alloc
, CSSM_SAMPLE_TYPE_THRESHOLD
,
1395 new(alloc
) ListElement(TypedList(alloc
, CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT
)));
1396 promptCred
.sample(2) = TypedList(alloc
, CSSM_SAMPLE_TYPE_PROMPTED_PASSWORD
,
1397 new(alloc
) ListElement(alloc
, CssmData()));
1399 // This unwrap object is here just to provide a context
1400 CssmClient::UnwrapKey
unwrap(Server::csp(), CSSM_ALGID_NONE
); //ok to lie about csp here
1401 unwrap
.mode(CSSM_ALGMODE_NONE
);
1402 unwrap
.padding(CSSM_PADDING_PKCS1
);
1403 unwrap
.cred(promptCred
);
1404 unwrap
.add(CSSM_ATTRIBUTE_WRAPPED_KEY_FORMAT
, uint32(CSSM_KEYBLOB_WRAPPED_FORMAT_PKCS7
));
1405 Security::Context
*tmpContext
;
1406 CSSM_CC_HANDLE CCHandle
= unwrap
.handle();
1407 /*CSSM_RETURN rx = */ CSSM_GetContext (CCHandle
, (CSSM_CONTEXT_PTR
*)&tmpContext
);
1409 // OK, this is skanky but necessary. We overwrite fields in the context struct
1411 tmpContext
->ContextType
= CSSM_ALGCLASS_ASYMMETRIC
;
1412 tmpContext
->AlgorithmType
= CSSM_ALGID_RSA
;
1414 db
.unwrapKey(*tmpContext
, cred
, owner
, unwrappingKey
, NULL
, usage
, attrs
,
1415 rawWrappedKey
, masterKey
, emptyDescriptiveData
);
1417 Allocator::standard().free(rawWrappedKey
.KeyData
.Data
);
1419 return safer_cast
<LocalKey
&>(*masterKey
).key();
1421 else if (sample
.type() == CSSM_SAMPLE_TYPE_SYMMETRIC_KEY
&& sample
.length() == 4 && sample
[3].data().length() > 0) {
1423 Contents (see MasterKeyUnlockCredentials in libsecurity_cdsa_client/lib/aclclient.cpp)
1425 sample[0] sample type
1426 sample[1] 0, since we don't have a valid handle
1427 sample[2] CssmKey of the masterKey [can't immediately use since it includes a CSSM_DATA struct with pointers]
1428 sample[3] flattened symmetric master key, including the key data
1431 // Fix up key to include actual data
1432 CssmData
&flattenedKey
= sample
[3].data();
1433 unflattenKey(flattenedKey
, key
);
1435 // Check that we have a reasonable key
1436 if (key
.header().blobType() != CSSM_KEYBLOB_RAW
) {
1437 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_REFERENCE
);
1439 if (key
.header().keyClass() != CSSM_KEYCLASS_SESSION_KEY
) {
1440 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_CLASS
);
1443 // bring the key into the CSP and return it
1444 return CssmClient::Key(Server::csp(), key
, true);
1446 // not a KeyHandle reference; use key as a raw key
1447 if (key
.header().blobType() != CSSM_KEYBLOB_RAW
)
1448 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_REFERENCE
);
1449 if (key
.header().keyClass() != CSSM_KEYCLASS_SESSION_KEY
)
1450 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_CLASS
);
1451 return CssmClient::Key(Server::csp(), key
, true);
1455 void unflattenKey(const CssmData
&flatKey
, CssmKey
&rawKey
)
1457 // The format we're expecting is a CSSM_KEY followed by the actual key data:
1458 // CSSM_KEY : KEY DATA
1459 // which is approximately:
1460 // h2ni(CSSM_KEYHEADER) : 4 bytes padding : CSSM_DATA{?:?} : KEY BYTES
1462 // Note that CSSM_KEY includes a CSSM_DATA struct, which we will ignore as it has pointers.
1463 // The pointer and length will be set to whatever key data follows the CSSM_KEY in rawKey.
1465 // unflatten the raw input key naively: key header then key data
1466 // We also convert it back to host byte order
1467 // A CSSM_KEY is a CSSM_KEYHEADER followed by a CSSM_DATA
1469 // Now copy: header, then key struct, then key data
1470 memcpy(&rawKey
.KeyHeader
, flatKey
.Data
, sizeof(CSSM_KEYHEADER
));
1471 memcpy(&rawKey
.KeyData
, flatKey
.Data
+ sizeof(CSSM_KEYHEADER
), sizeof(CSSM_DATA
));
1472 size_t keyDataLength
= flatKey
.length() - sizeof(CSSM_KEY
);
1473 rawKey
.KeyData
.Data
= Allocator::standard().malloc
<uint8
>(keyDataLength
);
1474 rawKey
.KeyData
.Length
= keyDataLength
;
1475 memcpy(rawKey
.KeyData
.Data
, flatKey
.Data
+ sizeof(CSSM_KEY
), keyDataLength
);
1476 Security::n2hi(rawKey
.KeyHeader
); // convert it to host byte order
1480 KeychainDatabase::keyFromKeybag(const TypedList
&sample
)
1482 service_context_t context
;
1483 uint8_t *session_key
;
1484 int session_key_size
;
1486 const struct ccmode_siv
*mode
= ccaes_siv_decrypt_mode();
1487 const size_t session_key_wrapped_len
= 40;
1488 const size_t version_len
= 1, nonce_len
= 16;
1489 uint8_t *decrypted_data
;
1490 size_t decrypted_len
;
1492 assert(sample
.type() == CSSM_SAMPLE_TYPE_KEYBAG_KEY
);
1494 CssmData
&unlock_token
= sample
[2].data();
1496 context
= common().session().get_current_service_context();
1497 rc
= service_client_kb_unwrap_key(&context
, unlock_token
.data(), session_key_wrapped_len
, key_class_ak
, (void **)&session_key
, &session_key_size
);
1499 CssmError::throwMe(CSSM_ERRCODE_INVALID_CRYPTO_DATA
);
1502 uint8_t *indata
= (uint8_t *)unlock_token
.data() + session_key_wrapped_len
;
1503 size_t inlen
= unlock_token
.length() - session_key_wrapped_len
;
1505 decrypted_len
= ccsiv_plaintext_size(mode
, inlen
- (version_len
+ nonce_len
));
1506 decrypted_data
= (uint8_t *)calloc(1, decrypted_len
);
1508 ccsiv_ctx_decl(mode
->size
, ctx
);
1510 rc
= ccsiv_init(mode
, ctx
, session_key_size
, session_key
);
1511 if (rc
!= 0) CssmError::throwMe(CSSM_ERRCODE_INVALID_CRYPTO_DATA
);
1512 rc
= ccsiv_set_nonce(mode
, ctx
, nonce_len
, indata
+ version_len
);
1513 if (rc
!= 0) CssmError::throwMe(CSSM_ERRCODE_INVALID_CRYPTO_DATA
);
1514 rc
= ccsiv_aad(mode
, ctx
, 1, indata
);
1515 if (rc
!= 0) CssmError::throwMe(CSSM_ERRCODE_INVALID_CRYPTO_DATA
);
1516 rc
= ccsiv_crypt(mode
, ctx
, inlen
- (version_len
+ nonce_len
), indata
+ version_len
+ nonce_len
, decrypted_data
);
1517 if (rc
!= 0) CssmError::throwMe(CSSM_ERRCODE_INVALID_CRYPTO_DATA
);
1519 ccsiv_ctx_clear(mode
->size
, ctx
);
1521 //free(decrypted_data);
1523 return makeRawKey(decrypted_data
, decrypted_len
, CSSM_ALGID_3DES_3KEY_EDE
, CSSM_KEYUSE_ENCRYPT
| CSSM_KEYUSE_DECRYPT
);
1526 // adapted from DatabaseCryptoCore::makeRawKey
1527 CssmClient::Key
KeychainDatabase::makeRawKey(void *data
, size_t length
,
1528 CSSM_ALGORITHMS algid
, CSSM_KEYUSE usage
)
1532 key
.header().BlobType
= CSSM_KEYBLOB_RAW
;
1533 key
.header().Format
= CSSM_KEYBLOB_RAW_FORMAT_OCTET_STRING
;
1534 key
.header().AlgorithmId
= algid
;
1535 key
.header().KeyClass
= CSSM_KEYCLASS_SESSION_KEY
;
1536 key
.header().KeyUsage
= usage
;
1537 key
.header().KeyAttr
= 0;
1538 key
.KeyData
= CssmData(data
, length
);
1540 // unwrap it into the CSP (but keep it raw)
1541 CssmClient::UnwrapKey
unwrap(Server::csp(), CSSM_ALGID_NONE
);
1542 CssmKey unwrappedKey
;
1543 CssmData descriptiveData
;
1545 CssmClient::KeySpec(CSSM_KEYUSE_ANY
, CSSM_KEYATTR_RETURN_DATA
| CSSM_KEYATTR_EXTRACTABLE
),
1546 unwrappedKey
, &descriptiveData
, NULL
);
1547 return CssmClient::Key(Server::csp(), unwrappedKey
);
1551 // Verify a putative database passphrase.
1552 // If the database is already unlocked, just check the passphrase.
1553 // Otherwise, unlock with that passphrase and report success.
1554 // Caller must hold the common lock.
1556 bool KeychainDatabase::validatePassphrase(const CssmData
&passphrase
) const
1558 if (common().hasMaster()) {
1559 // verify against known secret
1560 return common().validatePassphrase(passphrase
);
1562 // no master secret - perform "blind" unlock to avoid actual unlock
1564 DatabaseCryptoCore test
;
1565 test
.setup(mBlob
, passphrase
);
1566 test
.decodeCore(mBlob
, NULL
);
1576 // Lock this database
1578 void KeychainDatabase::lockDb()
1585 // Given a Key for this database, encode it into a blob and return it.
1587 KeyBlob
*KeychainDatabase::encodeKey(const CssmKey
&key
, const CssmData
&pubAcl
, const CssmData
&privAcl
)
1589 bool inTheClear
= false;
1590 if((key
.keyClass() == CSSM_KEYCLASS_PUBLIC_KEY
) &&
1591 !(key
.attribute(CSSM_KEYATTR_PUBLIC_KEY_ENCRYPT
))) {
1594 StLock
<Mutex
> _(common());
1596 makeUnlocked(false);
1598 // tell the cryptocore to form the key blob
1599 return common().encodeKeyCore(key
, pubAcl
, privAcl
, inTheClear
);
1604 // Given a "blobbed" key for this database, decode it into its real
1605 // key object and (re)populate its ACL.
1607 void KeychainDatabase::decodeKey(KeyBlob
*blob
, CssmKey
&key
, void * &pubAcl
, void * &privAcl
)
1609 StLock
<Mutex
> _(common());
1611 if(!blob
->isClearText())
1612 makeUnlocked(false); // we need our keys
1614 common().decodeKeyCore(blob
, key
, pubAcl
, privAcl
);
1615 // memory protocol: pubAcl points into blob; privAcl was allocated
1621 // Given a KeychainKey (that implicitly belongs to another keychain),
1622 // return it encoded using this keychain's operational secrets.
1624 KeyBlob
*KeychainDatabase::recodeKey(KeychainKey
&oldKey
)
1626 if (mRecodingSource
!= &oldKey
.referent
<KeychainDatabase
>()) {
1627 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY
);
1630 // To protect this operation, we need to take the mutex for both our common and the remote key's common in some defined order.
1631 // Grab the common being cloned (oldKey's) first, and then the common receiving the recoding (ours).
1632 StLock
<Mutex
> _ (oldKey
.referent
<KeychainDatabase
>().common());
1633 StLock
<Mutex
> __(common());
1635 oldKey
.instantiateAcl(); // make sure key is decoded
1636 CssmData publicAcl
, privateAcl
;
1637 oldKey
.exportBlob(publicAcl
, privateAcl
);
1638 // NB: blob's memory belongs to caller, not the common
1641 * Make sure the new key is in the same cleartext/encrypted state.
1643 bool inTheClear
= false;
1644 assert(oldKey
.blob());
1645 if(oldKey
.blob() && oldKey
.blob()->isClearText()) {
1649 KeyBlob
*blob
= common().encodeKeyCore(oldKey
.cssmKey(), publicAcl
, privateAcl
, inTheClear
);
1650 oldKey
.acl().allocator
.free(publicAcl
);
1651 oldKey
.acl().allocator
.free(privateAcl
);
1657 // Modify database parameters
1659 void KeychainDatabase::setParameters(const DBParameters
¶ms
)
1661 StLock
<Mutex
> _(common());
1662 makeUnlocked(false);
1663 common().mParams
= params
;
1664 common().invalidateBlob(); // invalidate old blobs
1665 activity(); // (also resets the timeout timer)
1666 secinfo("KCdb", "%p common %p(%s) set params=(%u,%u)",
1667 this, &common(), dbName(), params
.idleTimeout
, params
.lockOnSleep
);
1672 // Retrieve database parameters
1674 void KeychainDatabase::getParameters(DBParameters
¶ms
)
1676 StLock
<Mutex
> _(common());
1677 makeUnlocked(false);
1678 params
= common().mParams
;
1679 //activity(); // getting parameters does not reset the idle timer
1684 // RIGHT NOW, database ACLs are attached to the database.
1685 // This will soon move upstairs.
1687 SecurityServerAcl
&KeychainDatabase::acl()
1694 // Intercept ACL change requests and reset blob validity
1696 void KeychainDatabase::instantiateAcl()
1698 StLock
<Mutex
> _(common());
1699 makeUnlocked(false);
1702 void KeychainDatabase::changedAcl()
1704 StLock
<Mutex
> _(common());
1710 // Check an incoming DbBlob for basic viability
1712 void KeychainDatabase::validateBlob(const DbBlob
*blob
)
1714 // perform basic validation on the blob
1716 blob
->validate(CSSMERR_APPLEDL_INVALID_DATABASE_BLOB
);
1717 if (blob
->startCryptoBlob
> blob
->totalLength
) {
1718 CssmError::throwMe(CSSMERR_APPLEDL_INVALID_DATABASE_BLOB
);
1720 switch (blob
->version()) {
1721 #if defined(COMPAT_OSX_10_0)
1722 case DbBlob::version_MacOS_10_0
:
1725 case DbBlob::version_MacOS_10_1
:
1727 case DbBlob::version_partition
:
1730 CssmError::throwMe(CSSMERR_APPLEDL_INCOMPATIBLE_DATABASE_BLOB
);
1735 // Check if this database is currently recoding
1737 bool KeychainDatabase::isRecoding()
1739 secnotice("integrity", "recoding source: %p", mRecodingSource
.get());
1740 return (mRecodingSource
.get() != NULL
|| mRecoded
);
1744 // Mark ourselves as no longer recoding
1746 void KeychainDatabase::recodeFinished()
1748 secnotice("integrity", "recoding finished");
1749 mRecodingSource
= NULL
;
1755 // Debugging support
1757 #if defined(DEBUGDUMP)
1759 void KeychainDbCommon::dumpNode()
1761 PerSession::dumpNode();
1762 uint32 sig
; memcpy(&sig
, &mIdentifier
.signature(), sizeof(sig
));
1763 Debug::dump(" %s[%8.8x]", mIdentifier
.dbName(), sig
);
1765 Debug::dump(" locked");
1767 time_t whenTime
= time_t(when());
1768 Debug::dump(" unlocked(%24.24s/%.2g)", ctime(&whenTime
),
1769 (when() - Time::now()).seconds());
1771 Debug::dump(" params=(%u,%u)", mParams
.idleTimeout
, mParams
.lockOnSleep
);
1774 void KeychainDatabase::dumpNode()
1776 PerProcess::dumpNode();
1777 Debug::dump(" %s vers=%u",
1778 mValidData
? " data" : " nodata", version
);
1780 uint32 sig
; memcpy(&sig
, &mBlob
->randomSignature
, sizeof(sig
));
1781 Debug::dump(" blob=%p[%8.8x]", mBlob
, sig
);
1783 Debug::dump(" noblob");
1791 // DbCommon basic features
1793 KeychainDbCommon::KeychainDbCommon(Session
&ssn
, const DbIdentifier
&id
, uint32 requestedVersion
)
1794 : LocalDbCommon(ssn
), DatabaseCryptoCore(requestedVersion
), sequence(0), version(1), mIdentifier(id
),
1795 mIsLocked(true), mValidParams(false), mLoginKeychain(false)
1797 // match existing DbGlobal or create a new one
1799 Server
&server
= Server::active();
1800 StLock
<Mutex
> _(server
);
1801 if (KeychainDbGlobal
*dbglobal
=
1802 server
.findFirst
<KeychainDbGlobal
, const DbIdentifier
&>(&KeychainDbGlobal::identifier
, identifier())) {
1804 secinfo("KCdb", "%p linking to existing DbGlobal %p", this, dbglobal
);
1806 // DbGlobal not present; make a new one
1807 parent(*new KeychainDbGlobal(identifier()));
1808 secinfo("KCdb", "%p linking to new DbGlobal %p", this, &global());
1811 // link lifetime to the Session
1812 session().addReference(*this);
1814 if (strcasestr(id
.dbName(), "login.keychain") != NULL
) {
1815 mLoginKeychain
= true;
1820 void KeychainDbCommon::initializeKeybag() {
1821 if (mLoginKeychain
&& !session().keybagGetState(session_keybag_loaded
)) {
1822 service_context_t context
= session().get_current_service_context();
1823 if (service_client_kb_load(&context
) == 0) {
1824 session().keybagSetState(session_keybag_loaded
);
1829 KeychainDbCommon::KeychainDbCommon(Session
&ssn
, const DbIdentifier
&id
, KeychainDbCommon
& toClone
)
1830 : LocalDbCommon(ssn
), DatabaseCryptoCore(toClone
.mBlobVersion
), sequence(toClone
.sequence
), mParams(toClone
.mParams
), version(toClone
.version
),
1831 mIdentifier(id
), mIsLocked(toClone
.mIsLocked
), mValidParams(toClone
.mValidParams
), mLoginKeychain(toClone
.mLoginKeychain
)
1836 Server
&server
= Server::active();
1837 StLock
<Mutex
> _(server
);
1838 if (KeychainDbGlobal
*dbglobal
=
1839 server
.findFirst
<KeychainDbGlobal
, const DbIdentifier
&>(&KeychainDbGlobal::identifier
, identifier())) {
1841 secinfo("KCdb", "%p linking to existing DbGlobal %p", this, dbglobal
);
1843 // DbGlobal not present; make a new one
1844 parent(*new KeychainDbGlobal(identifier()));
1845 secinfo("KCdb", "%p linking to new DbGlobal %p", this, &global());
1847 session().addReference(*this);
1851 KeychainDbCommon::~KeychainDbCommon()
1853 secinfo("KCdb", "releasing keychain %p %s", this, (char*)this->dbName());
1855 // explicitly unschedule ourselves
1856 Server::active().clearTimer(this);
1857 if (mLoginKeychain
) {
1858 session().keybagClearState(session_keybag_unlocked
);
1860 // remove ourselves from mCommonSet
1864 void KeychainDbCommon::cloneFrom(KeychainDbCommon
& toClone
, uint32 requestedVersion
) {
1865 // don't clone the mIdentifier
1866 sequence
= toClone
.sequence
;
1867 mParams
= toClone
.mParams
;
1868 version
= toClone
.version
;
1869 mIsLocked
= toClone
.mIsLocked
;
1870 mValidParams
= toClone
.mValidParams
;
1871 mLoginKeychain
= toClone
.mLoginKeychain
;
1873 DatabaseCryptoCore::initializeFrom(toClone
, requestedVersion
);
1876 void KeychainDbCommon::kill()
1878 StReadWriteLock
_(mRWCommonLock
, StReadWriteLock::Write
);
1879 mCommonSet
.erase(this);
1882 KeychainDbGlobal
&KeychainDbCommon::global() const
1884 return parent
<KeychainDbGlobal
>();
1888 void KeychainDbCommon::select()
1891 void KeychainDbCommon::unselect()
1896 void KeychainDbCommon::makeNewSecrets()
1898 // we already have a master key (right?)
1899 assert(hasMaster());
1901 // tell crypto core to generate the use keys
1902 DatabaseCryptoCore::generateNewSecrets();
1904 // we're now officially "unlocked"; set the timer
1910 // All unlocking activity ultimately funnels through this method.
1911 // This unlocks a DbCommon using the secrets setup in its crypto core
1912 // component, and performs all the housekeeping needed to represent
1913 // the state change.
1914 // Returns true if unlock was successful, false if it failed due to
1915 // invalid/insufficient secrets. Throws on other errors.
1917 bool KeychainDbCommon::unlockDb(DbBlob
*blob
, void **privateAclBlob
)
1920 // Tell the cryptocore to (try to) decode itself. This will fail
1921 // in an astonishing variety of ways if the passphrase is wrong.
1922 assert(hasMaster());
1923 decodeCore(blob
, privateAclBlob
);
1924 secinfo("KCdb", "%p unlock successful", this);
1926 secinfo("KCdb", "%p unlock failed", this);
1930 // get the database parameters only if we haven't got them yet
1931 if (!mValidParams
) {
1932 mParams
= blob
->params
;
1933 n2hi(mParams
.idleTimeout
);
1934 mValidParams
= true; // sticky
1937 bool isLocked
= mIsLocked
;
1939 setUnlocked(); // mark unlocked
1942 // broadcast unlock notification, but only if we were previously locked
1943 notify(kNotificationEventUnlocked
);
1944 secinfo("KCdb", "unlocking keychain %p %s", this, (char*)this->dbName());
1949 void KeychainDbCommon::setUnlocked()
1951 session().addReference(*this); // active/held
1952 mIsLocked
= false; // mark unlocked
1953 activity(); // set timeout timer
1957 void KeychainDbCommon::lockDb()
1960 StLock
<Mutex
> _(*this);
1962 DatabaseCryptoCore::invalidate();
1963 notify(kNotificationEventLocked
);
1964 secinfo("KCdb", "locking keychain %p %s", this, (char*)this->dbName());
1965 Server::active().clearTimer(this);
1967 mIsLocked
= true; // mark locked
1969 // this call may destroy us if we have no databases anymore
1970 session().removeReference(*this);
1976 DbBlob
*KeychainDbCommon::encode(KeychainDatabase
&db
)
1978 assert(!isLocked()); // must have been unlocked by caller
1980 // export database ACL to blob form
1981 CssmData pubAcl
, privAcl
;
1982 db
.acl().exportBlob(pubAcl
, privAcl
);
1984 // tell the cryptocore to form the blob
1986 form
.randomSignature
= identifier();
1987 form
.sequence
= sequence
;
1988 form
.params
= mParams
;
1989 h2ni(form
.params
.idleTimeout
);
1991 assert(hasMaster());
1992 DbBlob
*blob
= encodeCore(form
, pubAcl
, privAcl
);
1995 db
.acl().allocator
.free(pubAcl
);
1996 db
.acl().allocator
.free(privAcl
);
2002 // Perform deferred lock processing for a database.
2004 void KeychainDbCommon::action()
2006 secinfo("KCdb", "common %s(%p) locked by timer", dbName(), this);
2010 void KeychainDbCommon::activity()
2013 secinfo("KCdb", "setting DbCommon %p timer to %d",
2014 this, int(mParams
.idleTimeout
));
2015 Server::active().setTimer(this, Time::Interval(int(mParams
.idleTimeout
)));
2019 void KeychainDbCommon::sleepProcessing()
2021 secinfo("KCdb", "common %s(%p) sleep-lock processing", dbName(), this);
2022 if (mParams
.lockOnSleep
&& !isDefaultSystemKeychain()) {
2023 StLock
<Mutex
> _(*this);
2028 void KeychainDbCommon::lockProcessing()
2035 // We consider a keychain to belong to the system domain if it resides
2036 // in /Library/Keychains. That's not exactly fool-proof, but we don't
2037 // currently have any internal markers to interrogate.
2039 bool KeychainDbCommon::belongsToSystem() const
2041 if (const char *name
= this->dbName())
2042 return !strncmp(name
, "/Library/Keychains/", 19);
2046 bool KeychainDbCommon::isDefaultSystemKeychain() const
2048 // /Library/Keychains/System.keychain (34)
2049 if (const char *name
= this->dbName())
2050 return !strncmp(name
, "/Library/Keychains/System.keychain", 34);
2055 // Keychain global objects
2057 KeychainDbGlobal::KeychainDbGlobal(const DbIdentifier
&id
)
2062 KeychainDbGlobal::~KeychainDbGlobal()
2064 secinfo("KCdb", "DbGlobal %p destroyed", this);