]> git.saurik.com Git - apple/securityd.git/blob - src/kcdatabase.cpp
securityd-55199.2.tar.gz
[apple/securityd.git] / src / kcdatabase.cpp
1 /*
2 * Copyright (c) 2000-2008 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24
25 //
26 // kcdatabase - software database container implementation.
27 //
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.
39 //
40 #include "kcdatabase.h"
41 #include "agentquery.h"
42 #include "kckey.h"
43 #include "server.h"
44 #include "session.h"
45 #include "notifications.h"
46 #include <vector> // @@@ 4003540 workaround
47 #include <security_agent_client/agentclient.h>
48 #include <security_cdsa_utilities/acl_any.h> // for default owner ACLs
49 #include <security_cdsa_utilities/cssmendian.h>
50 #include <security_cdsa_client/wrapkey.h>
51 #include <security_cdsa_client/genkey.h>
52 #include <security_cdsa_client/signclient.h>
53 #include <security_cdsa_client/cryptoclient.h>
54 #include <security_cdsa_client/macclient.h>
55 #include <securityd_client/dictionary.h>
56 #include <security_utilities/endian.h>
57 #include "securityd_service/securityd_service/securityd_service_client.h"
58 #include <AssertMacros.h>
59 #include <syslog.h>
60
61 void unflattenKey(const CssmData &flatKey, CssmKey &rawKey); //>> make static method on KeychainDatabase
62
63 static int
64 unlock_keybag(KeychainDbCommon & dbCommon, const void * secret, int secret_len)
65 {
66 int rc = -1;
67
68 if (!dbCommon.isLoginKeychain()) return 0;
69
70 service_context_t context = dbCommon.session().get_current_service_context();
71
72 // try to unlock first if not found then load/create or unlock
73 // loading should happen when the kb common object is created
74 // if it doesn't exist yet then the unlock will fail and we'll create everything
75 rc = service_client_kb_unlock(&context, secret, secret_len);
76 if (rc == KB_BagNotLoaded) {
77 if (service_client_kb_load(&context) == KB_BagNotFound) {
78 rc = service_client_kb_create(&context, secret, secret_len);
79 } else {
80 rc = service_client_kb_unlock(&context, secret, secret_len);
81 }
82 }
83
84 if (rc != 0) { // if we just upgraded make sure we swap the encryption key to the password
85 if (!dbCommon.session().keybagGetState(session_keybag_check_master_key)) {
86 CssmAutoData encKey(Allocator::standard(Allocator::sensitive));
87 dbCommon.get_encryption_key(encKey);
88 if ((rc = service_client_kb_unlock(&context, encKey.data(), (int)encKey.length())) == 0) {
89 rc = service_client_kb_change_secret(&context, encKey.data(), (int)encKey.length(), secret, secret_len);
90 }
91
92 if (rc != 0) {
93 CssmAutoData masterKey(Allocator::standard(Allocator::sensitive));
94 masterKey = dbCommon.masterKey()->keyData();
95 if ((rc = service_client_kb_unlock(&context, masterKey.data(), (int)masterKey.length())) == 0) {
96 rc = service_client_kb_change_secret(&context, masterKey.data(), (int)masterKey.length(), secret, secret_len);
97 }
98 }
99
100 if (rc != 0) { // if a login.keychain password exists but doesnt on the keybag update it
101 bool no_pin = false;
102 if ((secret_len > 0) && service_client_kb_is_locked(&context, NULL, &no_pin) == 0) {
103 if (no_pin) {
104 syslog(LOG_ERR, "Updating iCloud keychain passphrase for uid %d", dbCommon.session().originatorUid());
105 service_client_kb_change_secret(&context, NULL, 0, secret, secret_len);
106 }
107 }
108 }
109 } // session_keybag_check_master_key
110 }
111
112 if (rc == 0) {
113 dbCommon.session().keybagSetState(session_keybag_unlocked|session_keybag_loaded|session_keybag_check_master_key);
114 } else {
115 syslog(LOG_ERR, "Failed to unlock iCloud keychain for uid %d", dbCommon.session().originatorUid());
116 }
117
118 return rc;
119 }
120
121 static void
122 change_secret_on_keybag(KeychainDbCommon & dbCommon, const void * secret, int secret_len, const void * new_secret, int new_secret_len)
123 {
124 if (!dbCommon.isLoginKeychain()) return;
125
126 service_context_t context = dbCommon.session().get_current_service_context();
127
128 // if a login.keychain doesn't exist yet it comes into securityd as a create then change_secret
129 // we need to create the keybag in this case if it doesn't exist
130 if (service_client_kb_change_secret(&context, secret, secret_len, new_secret, new_secret_len) == KB_BagNotLoaded) {
131 if (service_client_kb_load(&context) == KB_BagNotFound) {
132 service_client_kb_create(&context, new_secret, new_secret_len);
133 }
134 }
135 }
136
137 //
138 // Create a Database object from initial parameters (create operation)
139 //
140 KeychainDatabase::KeychainDatabase(const DLDbIdentifier &id, const DBParameters &params, Process &proc,
141 const AccessCredentials *cred, const AclEntryPrototype *owner)
142 : LocalDatabase(proc), mValidData(false), mSecret(Allocator::standard(Allocator::sensitive)), mSaveSecret(false), version(0), mBlob(NULL)
143 {
144 // save a copy of the credentials for later access control
145 mCred = DataWalkers::copy(cred, Allocator::standard());
146
147 // create a new random signature to complete the DLDbIdentifier
148 DbBlob::Signature newSig;
149 Server::active().random(newSig.bytes);
150 DbIdentifier ident(id, newSig);
151
152 // create common block and initialize
153 RefPointer<KeychainDbCommon> newCommon = new KeychainDbCommon(proc.session(), ident);
154 StLock<Mutex> _(*newCommon);
155 parent(*newCommon);
156 // new common is now visible (in ident-map) but we hold its lock
157
158 // establish the new master secret
159 establishNewSecrets(cred, SecurityAgent::newDatabase);
160
161 // set initial database parameters
162 common().mParams = params;
163
164 // the common is "unlocked" now
165 common().makeNewSecrets();
166
167 // establish initial ACL
168 if (owner)
169 acl().cssmSetInitial(*owner);
170 else
171 acl().cssmSetInitial(new AnyAclSubject());
172 mValidData = true;
173
174 // for now, create the blob immediately
175 encode();
176
177 proc.addReference(*this);
178
179 // this new keychain is unlocked; make it so
180 activity();
181
182 SECURITYD_KEYCHAIN_CREATE(&common(), (char*)this->dbName(), this);
183 }
184
185
186 //
187 // Create a Database object from a database blob (decoding)
188 //
189 KeychainDatabase::KeychainDatabase(const DLDbIdentifier &id, const DbBlob *blob, Process &proc,
190 const AccessCredentials *cred)
191 : LocalDatabase(proc), mValidData(false), mSecret(Allocator::standard(Allocator::sensitive)), mSaveSecret(false), version(0), mBlob(NULL)
192 {
193 validateBlob(blob);
194
195 // save a copy of the credentials for later access control
196 mCred = DataWalkers::copy(cred, Allocator::standard());
197 mBlob = blob->copy();
198
199 // check to see if we already know about this database
200 DbIdentifier ident(id, blob->randomSignature);
201 Session &session = process().session();
202 StLock<Mutex> _(session);
203 if (KeychainDbCommon *dbcom =
204 session.findFirst<KeychainDbCommon, const DbIdentifier &>(&KeychainDbCommon::identifier, ident)) {
205 parent(*dbcom);
206 //@@@ arbitrate sequence number here, perhaps update common().mParams
207 SECURITYD_KEYCHAIN_JOIN(&common(), (char*)this->dbName(), this);
208 } else {
209 // DbCommon not present; make a new one
210 parent(*new KeychainDbCommon(proc.session(), ident));
211 common().mParams = blob->params;
212 SECURITYD_KEYCHAIN_MAKE(&common(), (char*)this->dbName(), this);
213 // this DbCommon is locked; no timer or reference setting
214 }
215 proc.addReference(*this);
216 }
217
218
219 // recode/clone:
220 //
221 // Special-purpose constructor for keychain synchronization. Copies an
222 // existing keychain but uses the operational keys from secretsBlob. The
223 // new KeychainDatabase will silently replace the existing KeychainDatabase
224 // as soon as the client declares that re-encoding of all keychain items is
225 // finished. This is a little perilous since it allows a client to dictate
226 // securityd state, but we try to ensure that only the client that started
227 // the re-encoding can declare it done.
228 //
229 KeychainDatabase::KeychainDatabase(KeychainDatabase &src, Process &proc, DbHandle dbToClone)
230 : LocalDatabase(proc), mValidData(false), mSecret(Allocator::standard(Allocator::sensitive)), mSaveSecret(false), version(0), mBlob(NULL)
231 {
232 mCred = DataWalkers::copy(src.mCred, Allocator::standard());
233
234 // Give this KeychainDatabase a temporary name
235 std::string newDbName = std::string("////") + std::string(src.identifier().dbName());
236 DLDbIdentifier newDLDbIdent(src.identifier().dlDbIdentifier().ssuid(), newDbName.c_str(), src.identifier().dlDbIdentifier().dbLocation());
237 DbIdentifier ident(newDLDbIdent, src.identifier());
238
239 // create common block and initialize
240 RefPointer<KeychainDbCommon> newCommon = new KeychainDbCommon(proc.session(), ident);
241 StLock<Mutex> _(*newCommon);
242 parent(*newCommon);
243
244 // set initial database parameters from the source keychain
245 common().mParams = src.common().mParams;
246
247 // establish the source keychain's master secret as ours
248 // @@@ NB: this is a v. 0.1 assumption. We *should* trigger new UI
249 // that offers the user the option of using the existing password
250 // or choosing a new one. That would require a new
251 // SecurityAgentQuery type, new UI, and--possibly--modifications to
252 // ensure that the new password is available here to generate the
253 // new master secret.
254 src.unlockDb(); // precaution for masterKey()
255 common().setup(src.blob(), src.common().masterKey());
256
257 // import the operational secrets
258 RefPointer<KeychainDatabase> srcKC = Server::keychain(dbToClone);
259 common().importSecrets(srcKC->common());
260
261 // import source keychain's ACL
262 CssmData pubAcl, privAcl;
263 src.acl().exportBlob(pubAcl, privAcl);
264 importBlob(pubAcl.data(), privAcl.data());
265 src.acl().allocator.free(pubAcl);
266 src.acl().allocator.free(privAcl);
267
268 // indicate that this keychain should be allowed to do some otherwise
269 // risky things required for copying, like re-encoding keys
270 mRecodingSource = &src;
271
272 common().setUnlocked();
273 mValidData = true;
274
275 encode();
276
277 proc.addReference(*this);
278 secdebug("SSdb", "database %s(%p) created as copy, common at %p",
279 common().dbName(), this, &common());
280 }
281
282 //
283 // Destroy a Database
284 //
285 KeychainDatabase::~KeychainDatabase()
286 {
287 secdebug("KCdb", "deleting database %s(%p) common %p",
288 common().dbName(), this, &common());
289 Allocator::standard().free(mCred);
290 Allocator::standard().free(mBlob);
291 }
292
293
294 //
295 // Basic Database virtual implementations
296 //
297 KeychainDbCommon &KeychainDatabase::common() const
298 {
299 return parent<KeychainDbCommon>();
300 }
301
302 const char *KeychainDatabase::dbName() const
303 {
304 return common().dbName();
305 }
306
307 bool KeychainDatabase::transient() const
308 {
309 return false; // has permanent store
310 }
311
312 AclKind KeychainDatabase::aclKind() const
313 {
314 return dbAcl;
315 }
316
317 Database *KeychainDatabase::relatedDatabase()
318 {
319 return this;
320 }
321
322
323 static inline KeychainKey &myKey(Key *key)
324 {
325 return *safe_cast<KeychainKey *>(key);
326 }
327
328
329 //
330 // (Re-)Authenticate the database. This changes the stored credentials.
331 //
332 void KeychainDatabase::authenticate(CSSM_DB_ACCESS_TYPE mode,
333 const AccessCredentials *cred)
334 {
335 StLock<Mutex> _(common());
336
337 // the (Apple specific) RESET bit means "lock the database now"
338 switch (mode) {
339 case CSSM_DB_ACCESS_RESET:
340 secdebug("KCdb", "%p ACCESS_RESET triggers keychain lock", this);
341 common().lockDb();
342 break;
343 default:
344 // store the new credentials for future use
345 secdebug("KCdb", "%p authenticate stores new database credentials", this);
346 AccessCredentials *newCred = DataWalkers::copy(cred, Allocator::standard());
347 Allocator::standard().free(mCred);
348 mCred = newCred;
349 }
350 }
351
352
353 //
354 // Make a new KeychainKey.
355 // If PERMANENT is off, make a temporary key instead.
356 // The db argument allows you to create for another KeychainDatabase (only);
357 // it defaults to ourselves.
358 //
359 RefPointer<Key> KeychainDatabase::makeKey(Database &db, const CssmKey &newKey,
360 uint32 moreAttributes, const AclEntryPrototype *owner)
361 {
362
363 if (moreAttributes & CSSM_KEYATTR_PERMANENT)
364 return new KeychainKey(db, newKey, moreAttributes, owner);
365 else
366 return process().makeTemporaryKey(newKey, moreAttributes, owner);
367 }
368
369 RefPointer<Key> KeychainDatabase::makeKey(const CssmKey &newKey,
370 uint32 moreAttributes, const AclEntryPrototype *owner)
371 {
372 return makeKey(*this, newKey, moreAttributes, owner);
373 }
374
375
376 //
377 // Return the database blob, recalculating it as needed.
378 //
379 DbBlob *KeychainDatabase::blob()
380 {
381 StLock<Mutex> _(common());
382 if (!validBlob()) {
383 makeUnlocked(); // unlock to get master secret
384 encode(); // (re)encode blob if needed
385 }
386 activity(); // reset timeout
387 assert(validBlob()); // better have a valid blob now...
388 return mBlob;
389 }
390
391
392 //
393 // Encode the current database as a blob.
394 // Note that this returns memory we own and keep.
395 // Caller must hold common lock.
396 //
397 void KeychainDatabase::encode()
398 {
399 DbBlob *blob = common().encode(*this);
400 Allocator::standard().free(mBlob);
401 mBlob = blob;
402 version = common().version;
403 secdebug("KCdb", "encoded database %p common %p(%s) version %u params=(%u,%u)",
404 this, &common(), dbName(), version,
405 common().mParams.idleTimeout, common().mParams.lockOnSleep);
406 }
407
408
409 //
410 // Change the passphrase on a database
411 //
412 void KeychainDatabase::changePassphrase(const AccessCredentials *cred)
413 {
414 // get and hold the common lock (don't let other threads break in here)
415 StLock<Mutex> _(common());
416
417 // establish OLD secret - i.e. unlock the database
418 //@@@ do we want to leave the final lock state alone?
419 if (common().isLoginKeychain()) mSaveSecret = true;
420 makeUnlocked(cred);
421
422 // establish NEW secret
423 establishNewSecrets(cred, SecurityAgent::changePassphrase);
424 if (mSecret) { mSecret.reset(); }
425 mSaveSecret = false;
426 common().invalidateBlob(); // blob state changed
427 secdebug("KCdb", "Database %s(%p) master secret changed", common().dbName(), this);
428 encode(); // force rebuild of local blob
429
430 // send out a notification
431 notify(kNotificationEventPassphraseChanged);
432
433 // I guess this counts as an activity
434 activity();
435 }
436
437 //
438 // Second stage of keychain synchronization: overwrite the original keychain's
439 // (this KeychainDatabase's) operational secrets
440 //
441 void KeychainDatabase::commitSecretsForSync(KeychainDatabase &cloneDb)
442 {
443 StLock<Mutex> _(common());
444
445 // try to detect spoofing
446 if (cloneDb.mRecodingSource != this)
447 CssmError::throwMe(CSSM_ERRCODE_INVALID_DB_HANDLE);
448
449 // in case we autolocked since starting the sync
450 makeUnlocked(); // call this because we already own the lock
451 cloneDb.unlockDb(); // we may not own the lock here, so calling unlockDb will lock the cloneDb's common lock
452
453 // Decode all keys whose handles refer to this on-disk keychain so that
454 // if the holding client commits the key back to disk, it's encoded with
455 // the new operational secrets. The recoding client *must* hold a write
456 // lock for the on-disk keychain from the moment it starts recoding key
457 // items until after this call.
458 //
459 // @@@ This specific implementation is a workaround for 4003540.
460 std::vector<U32HandleObject::Handle> handleList;
461 U32HandleObject::findAllRefs<KeychainKey>(handleList);
462 size_t count = handleList.size();
463 if (count > 0) {
464 for (unsigned int n = 0; n < count; ++n) {
465 RefPointer<KeychainKey> kckey =
466 U32HandleObject::findRefAndLock<KeychainKey>(handleList[n], CSSMERR_CSP_INVALID_KEY_REFERENCE);
467 StLock<Mutex> _(*kckey/*, true*/);
468 if (kckey->database().global().identifier() == identifier()) {
469 kckey->key(); // force decode
470 kckey->invalidateBlob();
471 secdebug("kcrecode", "changed extant key %p (proc %d)",
472 &*kckey, kckey->process().pid());
473 }
474 }
475 }
476
477 // it is now safe to replace the old op secrets
478 common().importSecrets(cloneDb.common());
479 common().invalidateBlob();
480 }
481
482
483 //
484 // Extract the database master key as a proper Key object.
485 //
486 RefPointer<Key> KeychainDatabase::extractMasterKey(Database &db,
487 const AccessCredentials *cred, const AclEntryPrototype *owner,
488 uint32 usage, uint32 attrs)
489 {
490 // get and hold common lock
491 StLock<Mutex> _(common());
492
493 // force lock to require re-validation of credentials
494 lockDb();
495
496 // unlock to establish master secret
497 makeUnlocked();
498
499 // extract the raw cryptographic key
500 CssmClient::WrapKey wrap(Server::csp(), CSSM_ALGID_NONE);
501 CssmKey key;
502 wrap(common().masterKey(), key);
503
504 // make the key object and return it
505 return makeKey(db, key, attrs & LocalKey::managedAttributes, owner);
506 }
507
508
509 //
510 // Unlock this database (if needed) by obtaining the master secret in some
511 // suitable way and then proceeding to unlock with it.
512 // Does absolutely nothing if the database is already unlocked.
513 // The makeUnlocked forms are identical except the assume the caller already
514 // holds the common lock.
515 //
516 void KeychainDatabase::unlockDb()
517 {
518 StLock<Mutex> _(common());
519 makeUnlocked();
520 }
521
522 void KeychainDatabase::makeUnlocked()
523 {
524 return makeUnlocked(mCred);
525 }
526
527 void KeychainDatabase::makeUnlocked(const AccessCredentials *cred)
528 {
529 if (isLocked()) {
530 secdebug("KCdb", "%p(%p) unlocking for makeUnlocked()", this, &common());
531 assert(mBlob || (mValidData && common().hasMaster()));
532 establishOldSecrets(cred);
533 common().setUnlocked(); // mark unlocked
534 } else if (common().isLoginKeychain()) {
535 bool locked = false;
536 service_context_t context = common().session().get_current_service_context();
537 if ((service_client_kb_is_locked(&context, &locked, NULL) == 0) && locked) {
538 StSyncLock<Mutex, Mutex> uisync(common().uiLock(), common());
539 QueryKeybagPassphrase keybagQuery(common().session(), 3);
540 keybagQuery.inferHints(Server::process());
541 if (keybagQuery.query() != SecurityAgent::noReason) {
542 syslog(LOG_NOTICE, "failed to unlock iCloud keychain");
543 }
544 }
545 }
546 if (!mValidData) { // need to decode to get our ACLs, master secret available
547 secdebug("KCdb", "%p(%p) is unlocked; decoding for makeUnlocked()", this, &common());
548 if (!decode())
549 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED);
550 }
551 assert(!isLocked());
552 assert(mValidData);
553 }
554
555 //
556 // Invoke the securityd_service to retrieve the keychain master
557 // key from the AppleFDEKeyStore.
558 //
559 void KeychainDatabase::stashDbCheck()
560 {
561 CssmAutoData masterKey(Allocator::standard(Allocator::sensitive));
562 CssmAutoData encKey(Allocator::standard(Allocator::sensitive));
563
564 // Fetch the key
565 int rc = 0;
566 void * stash_key = NULL;
567 int stash_key_len = 0;
568 service_context_t context = common().session().get_current_service_context();
569 rc = service_client_stash_get_key(&context, &stash_key, &stash_key_len);
570 if (rc == 0) {
571 if (stash_key) {
572 masterKey.copy(CssmData((void *)stash_key,stash_key_len));
573 memset(stash_key, 0, stash_key_len);
574 free(stash_key);
575 }
576 } else {
577 CssmError::throwMe(rc);
578 }
579
580 {
581 StLock<Mutex> _(common());
582
583 // Now establish it as the keychain master key
584 CssmClient::Key key(Server::csp(), masterKey.get());
585 CssmKey::Header &hdr = key.header();
586 hdr.keyClass(CSSM_KEYCLASS_SESSION_KEY);
587 hdr.algorithm(CSSM_ALGID_3DES_3KEY_EDE);
588 hdr.usage(CSSM_KEYUSE_ANY);
589 hdr.blobType(CSSM_KEYBLOB_RAW);
590 hdr.blobFormat(CSSM_KEYBLOB_RAW_FORMAT_OCTET_STRING);
591 common().setup(mBlob, key);
592
593 if (!decode())
594 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED);
595
596 common().get_encryption_key(encKey);
597 }
598
599 // when upgrading from pre-10.9 create a keybag if it doesn't exist with the encryption key
600 // only do this after we have verified the master key unlocks the login.keychain
601 if (service_client_kb_load(&context) == KB_BagNotFound) {
602 service_client_kb_create(&context, encKey.data(), (int)encKey.length());
603 }
604 }
605
606 //
607 // Get the keychain master key and invoke the securityd_service
608 // to stash it in the AppleFDEKeyStore ready for commit to the
609 // NVRAM blob.
610 //
611 void KeychainDatabase::stashDb()
612 {
613 CssmAutoData data(Allocator::standard(Allocator::sensitive));
614
615 {
616 StLock<Mutex> _(common());
617
618 if (!common().isValid()) {
619 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY);
620 }
621
622 CssmKey key = common().masterKey();
623 data.copy(key.keyData());
624 }
625
626 service_context_t context = common().session().get_current_service_context();
627 int rc = service_client_stash_set_key(&context, data.data(), (int)data.length());
628 if (rc != 0) CssmError::throwMe(rc);
629 }
630
631 //
632 // The following unlock given an explicit passphrase, rather than using
633 // (special cred sample based) default procedures.
634 //
635 void KeychainDatabase::unlockDb(const CssmData &passphrase)
636 {
637 StLock<Mutex> _(common());
638 makeUnlocked(passphrase);
639 }
640
641 void KeychainDatabase::makeUnlocked(const CssmData &passphrase)
642 {
643 if (isLocked()) {
644 if (decode(passphrase))
645 return;
646 else
647 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED);
648 } else if (!mValidData) { // need to decode to get our ACLs, passphrase available
649 if (!decode())
650 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED);
651 }
652
653 if (common().isLoginKeychain()) {
654 bool locked = false;
655 service_context_t context = common().session().get_current_service_context();
656 if (!common().session().keybagGetState(session_keybag_check_master_key) || ((service_client_kb_is_locked(&context, &locked, NULL) == 0) && locked)) {
657 unlock_keybag(common(), passphrase.data(), (int)passphrase.length());
658 }
659 }
660
661 assert(!isLocked());
662 assert(mValidData);
663 }
664
665
666 //
667 // Nonthrowing passphrase-based unlock. This returns false if unlock failed.
668 // Note that this requires an explicitly given passphrase.
669 // Caller must hold common lock.
670 //
671 bool KeychainDatabase::decode(const CssmData &passphrase)
672 {
673 assert(mBlob);
674 common().setup(mBlob, passphrase);
675 bool success = decode();
676 if (success && common().isLoginKeychain()) {
677 unlock_keybag(common(), passphrase.data(), (int)passphrase.length());
678 }
679 return success;
680 }
681
682
683 //
684 // Given the established master secret, decode the working keys and other
685 // functional secrets for this database. Return false (do NOT throw) if
686 // the decode fails. Call this in low(er) level code once you established
687 // the master key.
688 //
689 bool KeychainDatabase::decode()
690 {
691 assert(mBlob);
692 assert(common().hasMaster());
693 void *privateAclBlob;
694 if (common().unlockDb(mBlob, &privateAclBlob)) {
695 if (!mValidData) {
696 acl().importBlob(mBlob->publicAclBlob(), privateAclBlob);
697 mValidData = true;
698 }
699 Allocator::standard().free(privateAclBlob);
700 return true;
701 }
702 secdebug("KCdb", "%p decode failed", this);
703 return false;
704 }
705
706
707 //
708 // Given an AccessCredentials for this database, wring out the existing primary
709 // database secret by whatever means necessary.
710 // On entry, caller must hold the database common lock. It will be held
711 // throughout except when user interaction is required. User interaction
712 // requires relinquishing the database common lock and taking the UI lock. On
713 // return from user interaction, the UI lock is relinquished and the database
714 // common lock must be reacquired. At no time may the caller hold both locks.
715 // On exit, the crypto core has its master secret. If things go wrong,
716 // we will throw a suitable exception. Note that encountering any malformed
717 // credential sample will throw, but this is not guaranteed -- don't assume
718 // that NOT throwing means creds is entirely well-formed (it may just be good
719 // enough to work THIS time).
720 //
721 // How this works:
722 // Walk through the creds. Fish out those credentials (in order) that
723 // are for unlock processing (they have no ACL subject correspondents),
724 // and (try to) obey each in turn, until one produces a valid secret
725 // or you run out. If no special samples are found at all, interpret that as
726 // "use the system global default," which happens to be hard-coded right here.
727 //
728 void KeychainDatabase::establishOldSecrets(const AccessCredentials *creds)
729 {
730 bool forSystem = this->belongsToSystem(); // this keychain belongs to the system security domain
731
732 // attempt system-keychain unlock
733 if (forSystem) {
734 SystemKeychainKey systemKeychain(kSystemUnlockFile);
735 if (systemKeychain.matches(mBlob->randomSignature)) {
736 secdebug("KCdb", "%p attempting system unlock", this);
737 common().setup(mBlob, CssmClient::Key(Server::csp(), systemKeychain.key(), true));
738 if (decode())
739 return;
740 }
741 }
742
743 list<CssmSample> samples;
744 if (creds && creds->samples().collect(CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK, samples)) {
745 for (list<CssmSample>::iterator it = samples.begin(); it != samples.end(); it++) {
746 TypedList &sample = *it;
747 sample.checkProper();
748 switch (sample.type()) {
749 // interactively prompt the user - no additional data
750 case CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT:
751 if (!forSystem) {
752 if (interactiveUnlock())
753 return;
754 }
755 break;
756 // try to use an explicitly given passphrase - Data:passphrase
757 case CSSM_SAMPLE_TYPE_PASSWORD:
758 if (sample.length() != 2)
759 CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE);
760 secdebug("KCdb", "%p attempting passphrase unlock", this);
761 if (decode(sample[1]))
762 return;
763 break;
764 // try to open with a given master key - Data:CSP or KeyHandle, Data:CssmKey
765 case CSSM_SAMPLE_TYPE_SYMMETRIC_KEY:
766 case CSSM_SAMPLE_TYPE_ASYMMETRIC_KEY:
767 assert(mBlob);
768 secdebug("KCdb", "%p attempting explicit key unlock", this);
769 common().setup(mBlob, keyFromCreds(sample, 4));
770 if (decode())
771 return;
772 break;
773 // explicitly defeat the default action but don't try anything in particular
774 case CSSM_WORDID_CANCELED:
775 secdebug("KCdb", "%p defeat default action", this);
776 break;
777 default:
778 // Unknown sub-sample for unlocking.
779 // If we wanted to be fascist, we could now do
780 // CssmError::throwMe(CSSM_ERRCODE_SAMPLE_VALUE_NOT_SUPPORTED);
781 // But instead we try to be tolerant and continue on.
782 // This DOES however count as an explicit attempt at specifying unlock,
783 // so we will no longer try the default case below...
784 secdebug("KCdb", "%p unknown sub-sample unlock (%d) ignored", this, sample.type());
785 break;
786 }
787 }
788 } else {
789 // default action
790 assert(mBlob);
791
792 if (!forSystem) {
793 if (interactiveUnlock())
794 return;
795 }
796 }
797
798 // out of options - no secret obtained
799 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED);
800 }
801
802 bool KeychainDatabase::interactiveUnlock()
803 {
804 secdebug("KCdb", "%p attempting interactive unlock", this);
805 SecurityAgent::Reason reason = SecurityAgent::noReason;
806 QueryUnlock query(*this);
807 // take UI interlock and release DbCommon lock (to avoid deadlocks)
808 StSyncLock<Mutex, Mutex> uisync(common().uiLock(), common());
809
810 // now that we have the UI lock, interact unless another thread unlocked us first
811 if (isLocked()) {
812 query.inferHints(Server::process());
813 reason = query();
814 if (mSaveSecret && reason == SecurityAgent::noReason) {
815 query.retrievePassword(mSecret);
816 }
817 query.disconnect();
818 } else {
819 secdebug("KCdb", "%p was unlocked during uiLock delay", this);
820 }
821
822 if (common().isLoginKeychain()) {
823 bool locked = false;
824 service_context_t context = common().session().get_current_service_context();
825 if ((service_client_kb_is_locked(&context, &locked, NULL) == 0) && locked) {
826 QueryKeybagNewPassphrase keybagQuery(common().session());
827 keybagQuery.inferHints(Server::process());
828 CssmAutoData pass(Allocator::standard(Allocator::sensitive));
829 CssmAutoData oldPass(Allocator::standard(Allocator::sensitive));
830 SecurityAgent::Reason queryReason = keybagQuery.query(oldPass, pass);
831 if (queryReason == SecurityAgent::noReason) {
832 service_client_kb_change_secret(&context, oldPass.data(), (int)oldPass.length(), pass.data(), (int)pass.length());
833 } else if (queryReason == SecurityAgent::resettingPassword) {
834 query.retrievePassword(pass);
835 service_client_kb_reset(&context, pass.data(), (int)pass.length());
836 }
837
838 }
839 }
840
841 return reason == SecurityAgent::noReason;
842 }
843
844
845 //
846 // Same thing, but obtain a new secret somehow and set it into the common.
847 //
848 void KeychainDatabase::establishNewSecrets(const AccessCredentials *creds, SecurityAgent::Reason reason)
849 {
850 list<CssmSample> samples;
851 if (creds && creds->samples().collect(CSSM_SAMPLE_TYPE_KEYCHAIN_CHANGE_LOCK, samples)) {
852 for (list<CssmSample>::iterator it = samples.begin(); it != samples.end(); it++) {
853 TypedList &sample = *it;
854 sample.checkProper();
855 switch (sample.type()) {
856 // interactively prompt the user
857 case CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT:
858 {
859 secdebug("KCdb", "%p specified interactive passphrase", this);
860 QueryNewPassphrase query(*this, reason);
861 StSyncLock<Mutex, Mutex> uisync(common().uiLock(), common());
862 query.inferHints(Server::process());
863 CssmAutoData passphrase(Allocator::standard(Allocator::sensitive));
864 CssmAutoData oldPassphrase(Allocator::standard(Allocator::sensitive));
865 if (query(oldPassphrase, passphrase) == SecurityAgent::noReason) {
866 common().setup(NULL, passphrase);
867 change_secret_on_keybag(common(), oldPassphrase.data(), (int)oldPassphrase.length(), passphrase.data(), (int)passphrase.length());
868 return;
869 }
870 }
871 break;
872 // try to use an explicitly given passphrase
873 case CSSM_SAMPLE_TYPE_PASSWORD:
874 {
875 secdebug("KCdb", "%p specified explicit passphrase", this);
876 if (sample.length() != 2)
877 CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE);
878 common().setup(NULL, sample[1]);
879 if (common().isLoginKeychain()) {
880 CssmAutoData oldPassphrase(Allocator::standard(Allocator::sensitive));
881 list<CssmSample> oldSamples;
882 creds->samples().collect(CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK, oldSamples);
883 for (list<CssmSample>::iterator oit = oldSamples.begin(); oit != oldSamples.end(); oit++) {
884 TypedList &tmpList = *oit;
885 tmpList.checkProper();
886 if (tmpList.type() == CSSM_SAMPLE_TYPE_PASSWORD) {
887 if (tmpList.length() == 2) {
888 oldPassphrase = tmpList[1].data();
889 }
890 }
891 }
892 if (!oldPassphrase.length() && mSecret && mSecret.length()) {
893 oldPassphrase = mSecret;
894 }
895 change_secret_on_keybag(common(), oldPassphrase.data(), (int)oldPassphrase.length(), sample[1].data().data(), (int)sample[1].data().length());
896 }
897 return;
898 }
899 // try to open with a given master key
900 case CSSM_WORDID_SYMMETRIC_KEY:
901 case CSSM_SAMPLE_TYPE_ASYMMETRIC_KEY:
902 secdebug("KCdb", "%p specified explicit master key", this);
903 common().setup(NULL, keyFromCreds(sample, 3));
904 return;
905 // explicitly defeat the default action but don't try anything in particular
906 case CSSM_WORDID_CANCELED:
907 secdebug("KCdb", "%p defeat default action", this);
908 break;
909 default:
910 // Unknown sub-sample for acquiring new secret.
911 // If we wanted to be fascist, we could now do
912 // CssmError::throwMe(CSSM_ERRCODE_SAMPLE_VALUE_NOT_SUPPORTED);
913 // But instead we try to be tolerant and continue on.
914 // This DOES however count as an explicit attempt at specifying unlock,
915 // so we will no longer try the default case below...
916 secdebug("KCdb", "%p unknown sub-sample acquisition (%d) ignored",
917 this, sample.type());
918 break;
919 }
920 }
921 } else {
922 // default action -- interactive (only)
923 QueryNewPassphrase query(*this, reason);
924 StSyncLock<Mutex, Mutex> uisync(common().uiLock(), common());
925 query.inferHints(Server::process());
926 CssmAutoData passphrase(Allocator::standard(Allocator::sensitive));
927 CssmAutoData oldPassphrase(Allocator::standard(Allocator::sensitive));
928 if (query(oldPassphrase, passphrase) == SecurityAgent::noReason) {
929 common().setup(NULL, passphrase);
930 change_secret_on_keybag(common(), oldPassphrase.data(), (int)oldPassphrase.length(), passphrase.data(), (int)passphrase.length());
931 return;
932 }
933 }
934
935 // out of options - no secret obtained
936 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED);
937 }
938
939
940 //
941 // Given a (truncated) Database credentials TypedList specifying a master key,
942 // locate the key and return a reference to it.
943 //
944 CssmClient::Key KeychainDatabase::keyFromCreds(const TypedList &sample, unsigned int requiredLength)
945 {
946 // decode TypedList structure (sample type; Data:CSPHandle; Data:CSSM_KEY)
947 assert(sample.type() == CSSM_SAMPLE_TYPE_SYMMETRIC_KEY || sample.type() == CSSM_SAMPLE_TYPE_ASYMMETRIC_KEY);
948 if (sample.length() != requiredLength
949 || sample[1].type() != CSSM_LIST_ELEMENT_DATUM
950 || sample[2].type() != CSSM_LIST_ELEMENT_DATUM
951 || (requiredLength == 4 && sample[3].type() != CSSM_LIST_ELEMENT_DATUM))
952 CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE);
953 KeyHandle &handle = *sample[1].data().interpretedAs<KeyHandle>(CSSM_ERRCODE_INVALID_SAMPLE_VALUE);
954 // We used to be able to check the length but supporting multiple client
955 // architectures dishes that (sizeof(CSSM_KEY) varies due to alignment and
956 // field-size differences). The decoding in the transition layer should
957 // serve as a sufficient garbling check anyway.
958 if (sample[2].data().data() == NULL)
959 CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE);
960 CssmKey &key = *sample[2].data().interpretedAs<CssmKey>();
961
962 if (key.header().cspGuid() == gGuidAppleCSPDL) {
963 // handleOrKey is a SecurityServer KeyHandle; ignore key argument
964 return safer_cast<LocalKey &>(*Server::key(handle));
965 } else
966 if (sample.type() == CSSM_SAMPLE_TYPE_ASYMMETRIC_KEY) {
967 /*
968 Contents (see DefaultCredentials::unlockKey in libsecurity_keychain/defaultcreds.cpp)
969
970 sample[0] sample type
971 sample[1] csp handle for master or wrapping key; is really a keyhandle
972 sample[2] masterKey [not used since securityd cannot interpret; use sample[1] handle instead]
973 sample[3] UnlockReferralRecord data, in this case the flattened symmetric key
974 */
975
976 // RefPointer<Key> Server::key(KeyHandle key)
977 KeyHandle keyhandle = *sample[1].data().interpretedAs<KeyHandle>(CSSM_ERRCODE_INVALID_SAMPLE_VALUE);
978 CssmData &flattenedKey = sample[3].data();
979 RefPointer<Key> unwrappingKey = Server::key(keyhandle);
980 Database &db=unwrappingKey->database();
981
982 CssmKey rawWrappedKey;
983 unflattenKey(flattenedKey, rawWrappedKey);
984
985 RefPointer<Key> masterKey;
986 CssmData emptyDescriptiveData;
987 const AccessCredentials *cred = NULL;
988 const AclEntryPrototype *owner = NULL;
989 CSSM_KEYUSE usage = CSSM_KEYUSE_ANY;
990 CSSM_KEYATTR_FLAGS attrs = CSSM_KEYATTR_EXTRACTABLE; //CSSM_KEYATTR_RETURN_REF |
991
992 // Get default credentials for unwrappingKey (the one on the token)
993 // Copied from Statics::Statics() in libsecurity_keychain/aclclient.cpp
994 // Following KeyItem::getCredentials, one sees that the "operation" parameter
995 // e.g. "CSSM_ACL_AUTHORIZATION_DECRYPT" is ignored
996 Allocator &alloc = Allocator::standard();
997 AutoCredentials promptCred(alloc, 3);// enable interactive prompting
998
999 // promptCred: a credential permitting user prompt confirmations
1000 // contains:
1001 // a KEYCHAIN_PROMPT sample, both by itself and in a THRESHOLD
1002 // a PROMPTED_PASSWORD sample
1003 promptCred.sample(0) = TypedList(alloc, CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT);
1004 promptCred.sample(1) = TypedList(alloc, CSSM_SAMPLE_TYPE_THRESHOLD,
1005 new(alloc) ListElement(TypedList(alloc, CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT)));
1006 promptCred.sample(2) = TypedList(alloc, CSSM_SAMPLE_TYPE_PROMPTED_PASSWORD,
1007 new(alloc) ListElement(alloc, CssmData()));
1008
1009 // This unwrap object is here just to provide a context
1010 CssmClient::UnwrapKey unwrap(Server::csp(), CSSM_ALGID_NONE); //ok to lie about csp here
1011 unwrap.mode(CSSM_ALGMODE_NONE);
1012 unwrap.padding(CSSM_PADDING_PKCS1);
1013 unwrap.cred(promptCred);
1014 unwrap.add(CSSM_ATTRIBUTE_WRAPPED_KEY_FORMAT, uint32(CSSM_KEYBLOB_WRAPPED_FORMAT_PKCS7));
1015 Security::Context *tmpContext;
1016 CSSM_CC_HANDLE CCHandle = unwrap.handle();
1017 /*CSSM_RETURN rx = */ CSSM_GetContext (CCHandle, (CSSM_CONTEXT_PTR *)&tmpContext);
1018
1019 // OK, this is skanky but necessary. We overwrite fields in the context struct
1020
1021 tmpContext->ContextType = CSSM_ALGCLASS_ASYMMETRIC;
1022 tmpContext->AlgorithmType = CSSM_ALGID_RSA;
1023
1024 db.unwrapKey(*tmpContext, cred, owner, unwrappingKey, NULL, usage, attrs,
1025 rawWrappedKey, masterKey, emptyDescriptiveData);
1026
1027 Allocator::standard().free(rawWrappedKey.KeyData.Data);
1028
1029 return safer_cast<LocalKey &>(*masterKey).key();
1030 }
1031 else
1032 {
1033 // not a KeyHandle reference; use key as a raw key
1034 if (key.header().blobType() != CSSM_KEYBLOB_RAW)
1035 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_REFERENCE);
1036 if (key.header().keyClass() != CSSM_KEYCLASS_SESSION_KEY)
1037 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_CLASS);
1038 return CssmClient::Key(Server::csp(), key, true);
1039 }
1040 }
1041
1042 void unflattenKey(const CssmData &flatKey, CssmKey &rawKey)
1043 {
1044 // unflatten the raw input key naively: key header then key data
1045 // We also convert it back to host byte order
1046 // A CSSM_KEY is a CSSM_KEYHEADER followed by a CSSM_DATA
1047
1048 // Now copy: header, then key struct, then key data
1049 memcpy(&rawKey.KeyHeader, flatKey.Data, sizeof(CSSM_KEYHEADER));
1050 memcpy(&rawKey.KeyData, flatKey.Data + sizeof(CSSM_KEYHEADER), sizeof(CSSM_DATA));
1051 const uint32 keyDataLength = flatKey.length() - sizeof(CSSM_KEY);
1052 rawKey.KeyData.Data = Allocator::standard().malloc<uint8>(keyDataLength);
1053 rawKey.KeyData.Length = keyDataLength;
1054 memcpy(rawKey.KeyData.Data, flatKey.Data + sizeof(CSSM_KEY), keyDataLength);
1055 Security::n2hi(rawKey.KeyHeader); // convert it to host byte order
1056 }
1057
1058
1059 //
1060 // Verify a putative database passphrase.
1061 // If the database is already unlocked, just check the passphrase.
1062 // Otherwise, unlock with that passphrase and report success.
1063 // Caller must hold the common lock.
1064 //
1065 bool KeychainDatabase::validatePassphrase(const CssmData &passphrase) const
1066 {
1067 if (common().hasMaster()) {
1068 // verify against known secret
1069 return common().validatePassphrase(passphrase);
1070 } else {
1071 // no master secret - perform "blind" unlock to avoid actual unlock
1072 try {
1073 DatabaseCryptoCore test;
1074 test.setup(mBlob, passphrase);
1075 test.decodeCore(mBlob, NULL);
1076 return true;
1077 } catch (...) {
1078 return false;
1079 }
1080 }
1081 }
1082
1083
1084 //
1085 // Lock this database
1086 //
1087 void KeychainDatabase::lockDb()
1088 {
1089 common().lockDb();
1090 }
1091
1092
1093 //
1094 // Given a Key for this database, encode it into a blob and return it.
1095 //
1096 KeyBlob *KeychainDatabase::encodeKey(const CssmKey &key, const CssmData &pubAcl, const CssmData &privAcl)
1097 {
1098 bool inTheClear = false;
1099 if((key.keyClass() == CSSM_KEYCLASS_PUBLIC_KEY) &&
1100 !(key.attribute(CSSM_KEYATTR_PUBLIC_KEY_ENCRYPT))) {
1101 inTheClear = true;
1102 }
1103 StLock<Mutex> _(common());
1104 if(!inTheClear)
1105 makeUnlocked();
1106
1107 // tell the cryptocore to form the key blob
1108 return common().encodeKeyCore(key, pubAcl, privAcl, inTheClear);
1109 }
1110
1111
1112 //
1113 // Given a "blobbed" key for this database, decode it into its real
1114 // key object and (re)populate its ACL.
1115 //
1116 void KeychainDatabase::decodeKey(KeyBlob *blob, CssmKey &key, void * &pubAcl, void * &privAcl)
1117 {
1118 StLock<Mutex> _(common());
1119
1120 if(!blob->isClearText())
1121 makeUnlocked(); // we need our keys
1122
1123 common().decodeKeyCore(blob, key, pubAcl, privAcl);
1124 // memory protocol: pubAcl points into blob; privAcl was allocated
1125
1126 activity();
1127 }
1128
1129 //
1130 // Given a KeychainKey (that implicitly belongs to another keychain),
1131 // return it encoded using this keychain's operational secrets.
1132 //
1133 KeyBlob *KeychainDatabase::recodeKey(KeychainKey &oldKey)
1134 {
1135 if (mRecodingSource != &oldKey.referent<KeychainDatabase>()) {
1136 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY);
1137 }
1138 oldKey.instantiateAcl(); // make sure key is decoded
1139 CssmData publicAcl, privateAcl;
1140 oldKey.exportBlob(publicAcl, privateAcl);
1141 // NB: blob's memory belongs to caller, not the common
1142
1143 /*
1144 * Make sure the new key is in the same cleartext/encrypted state.
1145 */
1146 bool inTheClear = false;
1147 assert(oldKey.blob());
1148 if(oldKey.blob() && oldKey.blob()->isClearText()) {
1149 /* careful....*/
1150 inTheClear = true;
1151 }
1152 KeyBlob *blob = common().encodeKeyCore(oldKey.cssmKey(), publicAcl, privateAcl, inTheClear);
1153 oldKey.acl().allocator.free(publicAcl);
1154 oldKey.acl().allocator.free(privateAcl);
1155 return blob;
1156 }
1157
1158
1159 //
1160 // Modify database parameters
1161 //
1162 void KeychainDatabase::setParameters(const DBParameters &params)
1163 {
1164 StLock<Mutex> _(common());
1165 makeUnlocked();
1166 common().mParams = params;
1167 common().invalidateBlob(); // invalidate old blobs
1168 activity(); // (also resets the timeout timer)
1169 secdebug("KCdb", "%p common %p(%s) set params=(%u,%u)",
1170 this, &common(), dbName(), params.idleTimeout, params.lockOnSleep);
1171 }
1172
1173
1174 //
1175 // Retrieve database parameters
1176 //
1177 void KeychainDatabase::getParameters(DBParameters &params)
1178 {
1179 StLock<Mutex> _(common());
1180 makeUnlocked();
1181 params = common().mParams;
1182 //activity(); // getting parameters does not reset the idle timer
1183 }
1184
1185
1186 //
1187 // RIGHT NOW, database ACLs are attached to the database.
1188 // This will soon move upstairs.
1189 //
1190 SecurityServerAcl &KeychainDatabase::acl()
1191 {
1192 return *this;
1193 }
1194
1195
1196 //
1197 // Intercept ACL change requests and reset blob validity
1198 //
1199 void KeychainDatabase::instantiateAcl()
1200 {
1201 StLock<Mutex> _(common());
1202 makeUnlocked();
1203 }
1204
1205 void KeychainDatabase::changedAcl()
1206 {
1207 StLock<Mutex> _(common());
1208 version = 0;
1209 }
1210
1211
1212 //
1213 // Check an incoming DbBlob for basic viability
1214 //
1215 void KeychainDatabase::validateBlob(const DbBlob *blob)
1216 {
1217 // perform basic validation on the blob
1218 assert(blob);
1219 blob->validate(CSSMERR_APPLEDL_INVALID_DATABASE_BLOB);
1220 switch (blob->version()) {
1221 #if defined(COMPAT_OSX_10_0)
1222 case DbBlob::version_MacOS_10_0:
1223 break;
1224 #endif
1225 case DbBlob::version_MacOS_10_1:
1226 break;
1227 default:
1228 CssmError::throwMe(CSSMERR_APPLEDL_INCOMPATIBLE_DATABASE_BLOB);
1229 }
1230 }
1231
1232
1233 //
1234 // Debugging support
1235 //
1236 #if defined(DEBUGDUMP)
1237
1238 void KeychainDbCommon::dumpNode()
1239 {
1240 PerSession::dumpNode();
1241 uint32 sig; memcpy(&sig, &mIdentifier.signature(), sizeof(sig));
1242 Debug::dump(" %s[%8.8x]", mIdentifier.dbName(), sig);
1243 if (isLocked()) {
1244 Debug::dump(" locked");
1245 } else {
1246 time_t whenTime = time_t(when());
1247 Debug::dump(" unlocked(%24.24s/%.2g)", ctime(&whenTime),
1248 (when() - Time::now()).seconds());
1249 }
1250 Debug::dump(" params=(%u,%u)", mParams.idleTimeout, mParams.lockOnSleep);
1251 }
1252
1253 void KeychainDatabase::dumpNode()
1254 {
1255 PerProcess::dumpNode();
1256 Debug::dump(" %s vers=%u",
1257 mValidData ? " data" : " nodata", version);
1258 if (mBlob) {
1259 uint32 sig; memcpy(&sig, &mBlob->randomSignature, sizeof(sig));
1260 Debug::dump(" blob=%p[%8.8x]", mBlob, sig);
1261 } else {
1262 Debug::dump(" noblob");
1263 }
1264 }
1265
1266 #endif //DEBUGDUMP
1267
1268
1269 //
1270 // DbCommon basic features
1271 //
1272 KeychainDbCommon::KeychainDbCommon(Session &ssn, const DbIdentifier &id)
1273 : LocalDbCommon(ssn), sequence(0), version(1), mIdentifier(id),
1274 mIsLocked(true), mValidParams(false), mLoginKeychain(false)
1275 {
1276 // match existing DbGlobal or create a new one
1277 {
1278 Server &server = Server::active();
1279 StLock<Mutex> _(server);
1280 if (KeychainDbGlobal *dbglobal =
1281 server.findFirst<KeychainDbGlobal, const DbIdentifier &>(&KeychainDbGlobal::identifier, identifier())) {
1282 parent(*dbglobal);
1283 secdebug("KCdb", "%p linking to existing DbGlobal %p", this, dbglobal);
1284 } else {
1285 // DbGlobal not present; make a new one
1286 parent(*new KeychainDbGlobal(identifier()));
1287 secdebug("KCdb", "%p linking to new DbGlobal %p", this, &global());
1288 }
1289
1290 // link lifetime to the Session
1291 session().addReference(*this);
1292
1293 if (strcasestr(id.dbName(), "login.keychain") != NULL) {
1294 mLoginKeychain = true;
1295 }
1296 }
1297
1298 if (mLoginKeychain && !session().keybagGetState(session_keybag_loaded)) {
1299 service_context_t context = session().get_current_service_context();
1300 if (service_client_kb_load(&context) == 0) {
1301 session().keybagSetState(session_keybag_loaded);
1302 }
1303 }
1304 }
1305
1306 KeychainDbCommon::~KeychainDbCommon()
1307 {
1308 SECURITYD_KEYCHAIN_RELEASE(this, (char*)this->dbName());
1309
1310 // explicitly unschedule ourselves
1311 Server::active().clearTimer(this);
1312 if (mLoginKeychain) {
1313 session().keybagClearState(session_keybag_unlocked);
1314 }
1315 }
1316
1317 KeychainDbGlobal &KeychainDbCommon::global() const
1318 {
1319 return parent<KeychainDbGlobal>();
1320 }
1321
1322
1323 void KeychainDbCommon::select()
1324 { this->ref(); }
1325
1326 void KeychainDbCommon::unselect()
1327 { this->unref(); }
1328
1329
1330
1331 void KeychainDbCommon::makeNewSecrets()
1332 {
1333 // we already have a master key (right?)
1334 assert(hasMaster());
1335
1336 // tell crypto core to generate the use keys
1337 DatabaseCryptoCore::generateNewSecrets();
1338
1339 // we're now officially "unlocked"; set the timer
1340 setUnlocked();
1341 }
1342
1343
1344 //
1345 // All unlocking activity ultimately funnels through this method.
1346 // This unlocks a DbCommon using the secrets setup in its crypto core
1347 // component, and performs all the housekeeping needed to represent
1348 // the state change.
1349 // Returns true if unlock was successful, false if it failed due to
1350 // invalid/insufficient secrets. Throws on other errors.
1351 //
1352 bool KeychainDbCommon::unlockDb(DbBlob *blob, void **privateAclBlob)
1353 {
1354 try {
1355 // Tell the cryptocore to (try to) decode itself. This will fail
1356 // in an astonishing variety of ways if the passphrase is wrong.
1357 assert(hasMaster());
1358 decodeCore(blob, privateAclBlob);
1359 secdebug("KCdb", "%p unlock successful", this);
1360 } catch (...) {
1361 secdebug("KCdb", "%p unlock failed", this);
1362 return false;
1363 }
1364
1365 // get the database parameters only if we haven't got them yet
1366 if (!mValidParams) {
1367 mParams = blob->params;
1368 n2hi(mParams.idleTimeout);
1369 mValidParams = true; // sticky
1370 }
1371
1372 bool isLocked = mIsLocked;
1373
1374 setUnlocked(); // mark unlocked
1375
1376 if (isLocked) {
1377 // broadcast unlock notification, but only if we were previously locked
1378 notify(kNotificationEventUnlocked);
1379 SECURITYD_KEYCHAIN_UNLOCK(this, (char*)this->dbName());
1380 }
1381 return true;
1382 }
1383
1384 void KeychainDbCommon::setUnlocked()
1385 {
1386 session().addReference(*this); // active/held
1387 mIsLocked = false; // mark unlocked
1388 activity(); // set timeout timer
1389 }
1390
1391
1392 void KeychainDbCommon::lockDb()
1393 {
1394 bool lock = false;
1395 {
1396 StLock<Mutex> _(*this);
1397 if (!isLocked()) {
1398 DatabaseCryptoCore::invalidate();
1399 notify(kNotificationEventLocked);
1400 SECURITYD_KEYCHAIN_LOCK(this, (char*)this->dbName());
1401 Server::active().clearTimer(this);
1402
1403 mIsLocked = true; // mark locked
1404 lock = true;
1405
1406 // this call may destroy us if we have no databases anymore
1407 session().removeReference(*this);
1408 }
1409 }
1410
1411 if (mLoginKeychain && lock) {
1412 service_context_t context = session().get_current_service_context();
1413 service_client_kb_lock(&context);
1414 session().keybagClearState(session_keybag_unlocked);
1415 }
1416 }
1417
1418
1419 DbBlob *KeychainDbCommon::encode(KeychainDatabase &db)
1420 {
1421 assert(!isLocked()); // must have been unlocked by caller
1422
1423 // export database ACL to blob form
1424 CssmData pubAcl, privAcl;
1425 db.acl().exportBlob(pubAcl, privAcl);
1426
1427 // tell the cryptocore to form the blob
1428 DbBlob form;
1429 form.randomSignature = identifier();
1430 form.sequence = sequence;
1431 form.params = mParams;
1432 h2ni(form.params.idleTimeout);
1433
1434 assert(hasMaster());
1435 DbBlob *blob = encodeCore(form, pubAcl, privAcl);
1436
1437 // clean up and go
1438 db.acl().allocator.free(pubAcl);
1439 db.acl().allocator.free(privAcl);
1440 return blob;
1441 }
1442
1443
1444 //
1445 // Perform deferred lock processing for a database.
1446 //
1447 void KeychainDbCommon::action()
1448 {
1449 secdebug("KCdb", "common %s(%p) locked by timer", dbName(), this);
1450 lockDb();
1451 }
1452
1453 void KeychainDbCommon::activity()
1454 {
1455 if (!isLocked()) {
1456 secdebug("KCdb", "setting DbCommon %p timer to %d",
1457 this, int(mParams.idleTimeout));
1458 Server::active().setTimer(this, Time::Interval(int(mParams.idleTimeout)));
1459 }
1460 }
1461
1462 void KeychainDbCommon::sleepProcessing()
1463 {
1464 secdebug("KCdb", "common %s(%p) sleep-lock processing", dbName(), this);
1465 StLock<Mutex> _(*this);
1466 if (mParams.lockOnSleep)
1467 lockDb();
1468 }
1469
1470 void KeychainDbCommon::lockProcessing()
1471 {
1472 lockDb();
1473 }
1474
1475
1476 //
1477 // We consider a keychain to belong to the system domain if it resides
1478 // in /Library/Keychains. That's not exactly fool-proof, but we don't
1479 // currently have any internal markers to interrogate.
1480 //
1481 bool KeychainDbCommon::belongsToSystem() const
1482 {
1483 if (const char *name = this->dbName())
1484 return !strncmp(name, "/Library/Keychains/", 19);
1485 return false;
1486 }
1487
1488
1489 //
1490 // Keychain global objects
1491 //
1492 KeychainDbGlobal::KeychainDbGlobal(const DbIdentifier &id)
1493 : mIdentifier(id)
1494 {
1495 }
1496
1497 KeychainDbGlobal::~KeychainDbGlobal()
1498 {
1499 secdebug("KCdb", "DbGlobal %p destroyed", this);
1500 }