]> git.saurik.com Git - apple/securityd.git/blob - src/kcdatabase.cpp
securityd-26674.tar.gz
[apple/securityd.git] / src / kcdatabase.cpp
1 /*
2 * Copyright (c) 2000-2001 Apple Computer, 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_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
57
58 //
59 // Create a Database object from initial parameters (create operation)
60 //
61 KeychainDatabase::KeychainDatabase(const DLDbIdentifier &id, const DBParameters &params, Process &proc,
62 const AccessCredentials *cred, const AclEntryPrototype *owner)
63 : LocalDatabase(proc), mValidData(false), version(0), mBlob(NULL)
64 {
65 // save a copy of the credentials for later access control
66 mCred = DataWalkers::copy(cred, Allocator::standard());
67
68 // create a new random signature to complete the DLDbIdentifier
69 DbBlob::Signature newSig;
70 Server::active().random(newSig.bytes);
71 DbIdentifier ident(id, newSig);
72
73 // create common block and initialize
74 RefPointer<KeychainDbCommon> newCommon = new KeychainDbCommon(proc.session(), ident);
75 StLock<Mutex> _(*newCommon);
76 parent(*newCommon);
77 // new common is now visible (in ident-map) but we hold its lock
78
79 // establish the new master secret
80 establishNewSecrets(cred, SecurityAgent::newDatabase);
81
82 // set initial database parameters
83 common().mParams = params;
84
85 // the common is "unlocked" now
86 common().makeNewSecrets();
87
88 // establish initial ACL
89 if (owner)
90 acl().cssmSetInitial(*owner);
91 else
92 acl().cssmSetInitial(new AnyAclSubject());
93 mValidData = true;
94
95 // for now, create the blob immediately
96 encode();
97
98 proc.addReference(*this);
99
100 // this new keychain is unlocked; make it so
101 activity();
102
103 secdebug("KCdb", "database %s(%p) created, common at %p",
104 common().dbName(), this, &common());
105 }
106
107
108 //
109 // Create a Database object from a database blob (decoding)
110 //
111 KeychainDatabase::KeychainDatabase(const DLDbIdentifier &id, const DbBlob *blob, Process &proc,
112 const AccessCredentials *cred)
113 : LocalDatabase(proc), mValidData(false), version(0)
114 {
115 validateBlob(blob);
116
117 // save a copy of the credentials for later access control
118 mCred = DataWalkers::copy(cred, Allocator::standard());
119 mBlob = blob->copy();
120
121 // check to see if we already know about this database
122 DbIdentifier ident(id, blob->randomSignature);
123 Session &session = process().session();
124 StLock<Mutex> _(session);
125 if (KeychainDbCommon *dbcom =
126 session.findFirst<KeychainDbCommon, const DbIdentifier &>(&KeychainDbCommon::identifier, ident)) {
127 parent(*dbcom);
128 //@@@ arbitrate sequence number here, perhaps update common().mParams
129 secdebug("KCdb",
130 "open database %s(%p) version %lx at known common %p",
131 common().dbName(), this, blob->version(), &common());
132 } else {
133 // DbCommon not present; make a new one
134 parent(*new KeychainDbCommon(proc.session(), ident));
135 common().mParams = blob->params;
136 secdebug("KCdb", "open database %s(%p) version %lx with new common %p",
137 common().dbName(), this, blob->version(), &common());
138 // this DbCommon is locked; no timer or reference setting
139 }
140 proc.addReference(*this);
141 }
142
143
144 //
145 // Special-purpose constructor for keychain synchronization. Copies an
146 // existing keychain but uses the operational keys from secretsBlob. The
147 // new KeychainDatabase will silently replace the existing KeychainDatabase
148 // as soon as the client declares that re-encoding of all keychain items is
149 // finished. This is a little perilous since it allows a client to dictate
150 // securityd state, but we try to ensure that only the client that started
151 // the re-encoding can declare it done.
152 //
153 KeychainDatabase::KeychainDatabase(KeychainDatabase &src, Process &proc,
154 const DbBlob *secretsBlob, const CssmData &agentData)
155 : LocalDatabase(proc), mValidData(false), version(0), mBlob(NULL)
156 {
157 validateBlob(secretsBlob);
158
159 // get the passphrase to unlock secretsBlob
160 QueryDBBlobSecret query;
161 query.inferHints(proc);
162 query.addHint(AGENT_HINT_KCSYNC_DICT, agentData.data(), agentData.length());
163 DatabaseCryptoCore keysCore;
164 if (query(keysCore, secretsBlob) != SecurityAgent::noReason)
165 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED);
166 // keysCore is now ready to yield its secrets to us
167
168 mCred = DataWalkers::copy(src.mCred, Allocator::standard());
169
170 // Give this KeychainDatabase a temporary name
171 std::string newDbName = std::string("////") + std::string(src.identifier().dbName());
172 DLDbIdentifier newDLDbIdent(src.identifier().dlDbIdentifier().ssuid(), newDbName.c_str(), src.identifier().dlDbIdentifier().dbLocation());
173 DbIdentifier ident(newDLDbIdent, src.identifier());
174
175 // create common block and initialize
176 RefPointer<KeychainDbCommon> newCommon = new KeychainDbCommon(proc.session(), ident);
177 StLock<Mutex> _(*newCommon);
178 parent(*newCommon);
179
180 // set initial database parameters from the source keychain
181 common().mParams = src.common().mParams;
182
183 // establish the source keychain's master secret as ours
184 // @@@ NB: this is a v. 0.1 assumption. We *should* trigger new UI
185 // that offers the user the option of using the existing password
186 // or choosing a new one. That would require a new
187 // SecurityAgentQuery type, new UI, and--possibly--modifications to
188 // ensure that the new password is available here to generate the
189 // new master secret.
190 src.unlockDb(); // precaution for masterKey()
191 common().setup(src.blob(), src.common().masterKey());
192
193 // import the operational secrets
194 common().importSecrets(keysCore);
195
196 // import source keychain's ACL
197 CssmData pubAcl, privAcl;
198 src.acl().exportBlob(pubAcl, privAcl);
199 importBlob(pubAcl.data(), privAcl.data());
200 src.acl().allocator.free(pubAcl);
201 src.acl().allocator.free(privAcl);
202
203 // indicate that this keychain should be allowed to do some otherwise
204 // risky things required for copying, like re-encoding keys
205 mRecodingSource = &src;
206
207 common().setUnlocked();
208 mValidData = true;
209
210 encode();
211
212 proc.addReference(*this);
213 secdebug("SSdb", "database %s(%p) created as copy, common at %p",
214 common().dbName(), this, &common());
215 }
216
217
218 //
219 // Destroy a Database
220 //
221 KeychainDatabase::~KeychainDatabase()
222 {
223 secdebug("KCdb", "deleting database %s(%p) common %p",
224 common().dbName(), this, &common());
225 Allocator::standard().free(mCred);
226 Allocator::standard().free(mBlob);
227 }
228
229
230 //
231 // Basic Database virtual implementations
232 //
233 KeychainDbCommon &KeychainDatabase::common() const
234 {
235 return parent<KeychainDbCommon>();
236 }
237
238 const char *KeychainDatabase::dbName() const
239 {
240 return common().dbName();
241 }
242
243 bool KeychainDatabase::transient() const
244 {
245 return false; // has permanent store
246 }
247
248 AclKind KeychainDatabase::aclKind() const
249 {
250 return dbAcl;
251 }
252
253 Database *KeychainDatabase::relatedDatabase()
254 {
255 return this;
256 }
257
258
259 static inline KeychainKey &myKey(Key *key)
260 {
261 return *safe_cast<KeychainKey *>(key);
262 }
263
264
265 //
266 // (Re-)Authenticate the database. This changes the stored credentials.
267 //
268 void KeychainDatabase::authenticate(CSSM_DB_ACCESS_TYPE mode,
269 const AccessCredentials *cred)
270 {
271 StLock<Mutex> _(common());
272
273 // the (Apple specific) RESET bit means "lock the database now"
274 switch (mode) {
275 case CSSM_DB_ACCESS_RESET:
276 secdebug("KCdb", "%p ACCESS_RESET triggers keychain lock", this);
277 common().lockDb();
278 break;
279 default:
280 // store the new credentials for future use
281 secdebug("KCdb", "%p authenticate stores new database credentials", this);
282 AccessCredentials *newCred = DataWalkers::copy(cred, Allocator::standard());
283 Allocator::standard().free(mCred);
284 mCred = newCred;
285 }
286 }
287
288
289 //
290 // Make a new KeychainKey.
291 // If PERMANENT is off, make a temporary key instead.
292 // The db argument allows you to create for another KeychainDatabase (only);
293 // it defaults to ourselves.
294 //
295 RefPointer<Key> KeychainDatabase::makeKey(Database &db, const CssmKey &newKey,
296 uint32 moreAttributes, const AclEntryPrototype *owner)
297 {
298
299 if (moreAttributes & CSSM_KEYATTR_PERMANENT)
300 return new KeychainKey(db, newKey, moreAttributes, owner);
301 else
302 return process().makeTemporaryKey(newKey, moreAttributes, owner);
303 }
304
305 RefPointer<Key> KeychainDatabase::makeKey(const CssmKey &newKey,
306 uint32 moreAttributes, const AclEntryPrototype *owner)
307 {
308 return makeKey(*this, newKey, moreAttributes, owner);
309 }
310
311
312 //
313 // Return the database blob, recalculating it as needed.
314 //
315 DbBlob *KeychainDatabase::blob()
316 {
317 StLock<Mutex> _(common());
318 if (!validBlob()) {
319 makeUnlocked(); // unlock to get master secret
320 encode(); // (re)encode blob if needed
321 }
322 activity(); // reset timeout
323 assert(validBlob()); // better have a valid blob now...
324 return mBlob;
325 }
326
327
328 //
329 // Encode the current database as a blob.
330 // Note that this returns memory we own and keep.
331 // Caller must hold common lock.
332 //
333 void KeychainDatabase::encode()
334 {
335 DbBlob *blob = common().encode(*this);
336 Allocator::standard().free(mBlob);
337 mBlob = blob;
338 version = common().version;
339 secdebug("KCdb", "encoded database %p common %p(%s) version %ld params=(%ld,%d)",
340 this, &common(), dbName(), version,
341 common().mParams.idleTimeout, common().mParams.lockOnSleep);
342 }
343
344
345 //
346 // Change the passphrase on a database
347 //
348 void KeychainDatabase::changePassphrase(const AccessCredentials *cred)
349 {
350 // get and hold the common lock (don't let other threads break in here)
351 StLock<Mutex> _(common());
352
353 // establish OLD secret - i.e. unlock the database
354 //@@@ do we want to leave the final lock state alone?
355 makeUnlocked(cred);
356
357 // establish NEW secret
358 establishNewSecrets(cred, SecurityAgent::changePassphrase);
359 common().invalidateBlob(); // blob state changed
360 secdebug("KCdb", "Database %s(%p) master secret changed", common().dbName(), this);
361 encode(); // force rebuild of local blob
362
363 // send out a notification
364 notify(kNotificationEventPassphraseChanged);
365
366 // I guess this counts as an activity
367 activity();
368 }
369
370 //
371 // Second stage of keychain synchronization: overwrite the original keychain's
372 // (this KeychainDatabase's) operational secrets
373 //
374 void KeychainDatabase::commitSecretsForSync(KeychainDatabase &cloneDb)
375 {
376 StLock<Mutex> _(common());
377
378 // try to detect spoofing
379 if (cloneDb.mRecodingSource != this)
380 CssmError::throwMe(CSSM_ERRCODE_INVALID_DB_HANDLE);
381
382 // in case we autolocked since starting the sync
383 unlockDb();
384 cloneDb.unlockDb();
385
386 // Decode all keys whose handles refer to this on-disk keychain so that
387 // if the holding client commits the key back to disk, it's encoded with
388 // the new operational secrets. The recoding client *must* hold a write
389 // lock for the on-disk keychain from the moment it starts recoding key
390 // items until after this call.
391 //
392 // @@@ This specific implementation is a workaround for 4003540.
393 std::vector<CSSM_HANDLE> handleList;
394 HandleObject::findAllRefs<KeychainKey>(handleList);
395 size_t count = handleList.size();
396 if (count > 0) {
397 for (unsigned int n = 0; n < count; ++n) {
398 RefPointer<KeychainKey> kckey =
399 HandleObject::findRefAndLock<KeychainKey>(handleList[n], CSSMERR_CSP_INVALID_KEY_REFERENCE);
400 StLock<Mutex> _(*kckey/*, true*/);
401 if (kckey->database().global().identifier() == identifier()) {
402 kckey->key(); // force decode
403 kckey->invalidateBlob();
404 secdebug("kcrecode", "changed extant key %p (proc %d)",
405 &*kckey, kckey->process().pid());
406 }
407 }
408 }
409
410 // it is now safe to replace the old op secrets
411 common().importSecrets(cloneDb.common());
412 common().invalidateBlob();
413 }
414
415
416 //
417 // Extract the database master key as a proper Key object.
418 //
419 RefPointer<Key> KeychainDatabase::extractMasterKey(Database &db,
420 const AccessCredentials *cred, const AclEntryPrototype *owner,
421 uint32 usage, uint32 attrs)
422 {
423 // get and hold common lock
424 StLock<Mutex> _(common());
425
426 // force lock to require re-validation of credentials
427 lockDb();
428
429 // unlock to establish master secret
430 makeUnlocked();
431
432 // extract the raw cryptographic key
433 CssmClient::WrapKey wrap(Server::csp(), CSSM_ALGID_NONE);
434 CssmKey key;
435 wrap(common().masterKey(), key);
436
437 // make the key object and return it
438 return makeKey(db, key, attrs & LocalKey::managedAttributes, owner);
439 }
440
441
442 //
443 // Unlock this database (if needed) by obtaining the master secret in some
444 // suitable way and then proceeding to unlock with it.
445 // Does absolutely nothing if the database is already unlocked.
446 // The makeUnlocked forms are identical except the assume the caller already
447 // holds the common lock.
448 //
449 void KeychainDatabase::unlockDb()
450 {
451 StLock<Mutex> _(common());
452 makeUnlocked();
453 }
454
455 void KeychainDatabase::makeUnlocked()
456 {
457 return makeUnlocked(mCred);
458 }
459
460 void KeychainDatabase::makeUnlocked(const AccessCredentials *cred)
461 {
462 if (isLocked()) {
463 secdebug("KCdb", "%p(%p) unlocking for makeUnlocked()", this, &common());
464 assert(mBlob || (mValidData && common().hasMaster()));
465 establishOldSecrets(cred);
466 common().setUnlocked(); // mark unlocked
467 } else if (!mValidData) { // need to decode to get our ACLs, master secret available
468 secdebug("KCdb", "%p(%p) is unlocked; decoding for makeUnlocked()", this, &common());
469 if (!decode())
470 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED);
471 }
472 assert(!isLocked());
473 assert(mValidData);
474 }
475
476
477 //
478 // The following unlock given an explicit passphrase, rather than using
479 // (special cred sample based) default procedures.
480 //
481 void KeychainDatabase::unlockDb(const CssmData &passphrase)
482 {
483 StLock<Mutex> _(common());
484 makeUnlocked(passphrase);
485 }
486
487 void KeychainDatabase::makeUnlocked(const CssmData &passphrase)
488 {
489 if (isLocked()) {
490 if (decode(passphrase))
491 return;
492 else
493 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED);
494 } else if (!mValidData) { // need to decode to get our ACLs, passphrase available
495 if (!decode())
496 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED);
497 }
498 assert(!isLocked());
499 assert(mValidData);
500 }
501
502
503 //
504 // Nonthrowing passphrase-based unlock. This returns false if unlock failed.
505 // Note that this requires an explicitly given passphrase.
506 // Caller must hold common lock.
507 //
508 bool KeychainDatabase::decode(const CssmData &passphrase)
509 {
510 assert(mBlob);
511 common().setup(mBlob, passphrase);
512 return decode();
513 }
514
515
516 //
517 // Given the established master secret, decode the working keys and other
518 // functional secrets for this database. Return false (do NOT throw) if
519 // the decode fails. Call this in low(er) level code once you established
520 // the master key.
521 //
522 bool KeychainDatabase::decode()
523 {
524 assert(mBlob);
525 assert(common().hasMaster());
526 void *privateAclBlob;
527 if (common().unlockDb(mBlob, &privateAclBlob)) {
528 if (!mValidData) {
529 acl().importBlob(mBlob->publicAclBlob(), privateAclBlob);
530 mValidData = true;
531 }
532 Allocator::standard().free(privateAclBlob);
533 return true;
534 }
535 secdebug("KCdb", "%p decode failed", this);
536 return false;
537 }
538
539
540 //
541 // Given an AccessCredentials for this database, wring out the existing primary
542 // database secret by whatever means necessary.
543 // On entry, caller must hold the database common lock. It will be held
544 // throughout except when user interaction is required. User interaction
545 // requires relinquishing the database common lock and taking the UI lock. On
546 // return from user interaction, the UI lock is relinquished and the database
547 // common lock must be reacquired. At no time may the caller hold both locks.
548 // On exit, the crypto core has its master secret. If things go wrong,
549 // we will throw a suitable exception. Note that encountering any malformed
550 // credential sample will throw, but this is not guaranteed -- don't assume
551 // that NOT throwing means creds is entirely well-formed (it may just be good
552 // enough to work THIS time).
553 //
554 // How this works:
555 // Walk through the creds. Fish out those credentials (in order) that
556 // are for unlock processing (they have no ACL subject correspondents),
557 // and (try to) obey each in turn, until one produces a valid secret
558 // or you run out. If no special samples are found at all, interpret that as
559 // "use the system global default," which happens to be hard-coded right here.
560 //
561 void KeychainDatabase::establishOldSecrets(const AccessCredentials *creds)
562 {
563 list<CssmSample> samples;
564 if (creds && creds->samples().collect(CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK, samples)) {
565 for (list<CssmSample>::iterator it = samples.begin(); it != samples.end(); it++) {
566 TypedList &sample = *it;
567 sample.checkProper();
568 switch (sample.type()) {
569 // interactively prompt the user - no additional data
570 case CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT:
571 {
572 secdebug("KCdb", "%p attempting interactive unlock", this);
573 QueryUnlock query(*this);
574 // Holding DB common lock during UI will deadlock securityd
575 StSyncLock<Mutex, Mutex> uisync(common().uiLock(), common());
576 query.inferHints(Server::process());
577 if (query() == SecurityAgent::noReason)
578 return;
579 }
580 break;
581 // try to use an explicitly given passphrase - Data:passphrase
582 case CSSM_SAMPLE_TYPE_PASSWORD:
583 if (sample.length() != 2)
584 CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE);
585 secdebug("KCdb", "%p attempting passphrase unlock", this);
586 if (decode(sample[1]))
587 return;
588 break;
589 // try to open with a given master key - Data:CSP or KeyHandle, Data:CssmKey
590 case CSSM_WORDID_SYMMETRIC_KEY:
591 assert(mBlob);
592 secdebug("KCdb", "%p attempting explicit key unlock", this);
593 common().setup(mBlob, keyFromCreds(sample, 4));
594 if (decode())
595 return;
596 break;
597 // explicitly defeat the default action but don't try anything in particular
598 case CSSM_WORDID_CANCELED:
599 secdebug("KCdb", "%p defeat default action", this);
600 break;
601 default:
602 // Unknown sub-sample for unlocking.
603 // If we wanted to be fascist, we could now do
604 // CssmError::throwMe(CSSM_ERRCODE_SAMPLE_VALUE_NOT_SUPPORTED);
605 // But instead we try to be tolerant and continue on.
606 // This DOES however count as an explicit attempt at specifying unlock,
607 // so we will no longer try the default case below...
608 secdebug("KCdb", "%p unknown sub-sample unlock (%ld) ignored", this, sample.type());
609 break;
610 }
611 }
612 } else {
613 // default action
614 assert(mBlob);
615
616 // attempt system-keychain unlock
617 SystemKeychainKey systemKeychain(kSystemUnlockFile);
618 if (systemKeychain.matches(mBlob->randomSignature)) {
619 secdebug("KCdb", "%p attempting system unlock", this);
620 common().setup(mBlob, CssmClient::Key(Server::csp(), systemKeychain.key(), true));
621 if (decode())
622 return;
623 }
624
625 QueryUnlock query(*this);
626 // attempt interactive unlock
627 StSyncLock<Mutex, Mutex> uisync(common().uiLock(), common());
628 query.inferHints(Server::process());
629 if (query() == SecurityAgent::noReason)
630 return;
631 }
632
633 // out of options - no secret obtained
634 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED);
635 }
636
637
638 //
639 // Same thing, but obtain a new secret somehow and set it into the common.
640 //
641 void KeychainDatabase::establishNewSecrets(const AccessCredentials *creds, SecurityAgent::Reason reason)
642 {
643 list<CssmSample> samples;
644 if (creds && creds->samples().collect(CSSM_SAMPLE_TYPE_KEYCHAIN_CHANGE_LOCK, samples)) {
645 for (list<CssmSample>::iterator it = samples.begin(); it != samples.end(); it++) {
646 TypedList &sample = *it;
647 sample.checkProper();
648 switch (sample.type()) {
649 // interactively prompt the user
650 case CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT:
651 {
652 secdebug("KCdb", "%p specified interactive passphrase", this);
653 QueryNewPassphrase query(*this, reason);
654 StSyncLock<Mutex, Mutex> uisync(common().uiLock(), common());
655 query.inferHints(Server::process());
656 CssmAutoData passphrase(Allocator::standard(Allocator::sensitive));
657 if (query(passphrase) == SecurityAgent::noReason) {
658 common().setup(NULL, passphrase);
659 return;
660 }
661 }
662 break;
663 // try to use an explicitly given passphrase
664 case CSSM_SAMPLE_TYPE_PASSWORD:
665 secdebug("KCdb", "%p specified explicit passphrase", this);
666 if (sample.length() != 2)
667 CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE);
668 common().setup(NULL, sample[1]);
669 return;
670 // try to open with a given master key
671 case CSSM_WORDID_SYMMETRIC_KEY:
672 secdebug("KCdb", "%p specified explicit master key", this);
673 common().setup(NULL, keyFromCreds(sample, 3));
674 return;
675 // explicitly defeat the default action but don't try anything in particular
676 case CSSM_WORDID_CANCELED:
677 secdebug("KCdb", "%p defeat default action", this);
678 break;
679 default:
680 // Unknown sub-sample for acquiring new secret.
681 // If we wanted to be fascist, we could now do
682 // CssmError::throwMe(CSSM_ERRCODE_SAMPLE_VALUE_NOT_SUPPORTED);
683 // But instead we try to be tolerant and continue on.
684 // This DOES however count as an explicit attempt at specifying unlock,
685 // so we will no longer try the default case below...
686 secdebug("KCdb", "%p unknown sub-sample acquisition (%ld) ignored",
687 this, sample.type());
688 break;
689 }
690 }
691 } else {
692 // default action -- interactive (only)
693 QueryNewPassphrase query(*this, reason);
694 StSyncLock<Mutex, Mutex> uisync(common().uiLock(), common());
695 query.inferHints(Server::process());
696 CssmAutoData passphrase(Allocator::standard(Allocator::sensitive));
697 if (query(passphrase) == SecurityAgent::noReason) {
698 common().setup(NULL, passphrase);
699 return;
700 }
701 }
702
703 // out of options - no secret obtained
704 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED);
705 }
706
707
708 //
709 // Given a (truncated) Database credentials TypedList specifying a master key,
710 // locate the key and return a reference to it.
711 //
712 CssmClient::Key KeychainDatabase::keyFromCreds(const TypedList &sample, unsigned int requiredLength)
713 {
714 // decode TypedList structure (sample type; Data:CSPHandle; Data:CSSM_KEY)
715 assert(sample.type() == CSSM_WORDID_SYMMETRIC_KEY);
716 if (sample.length() != requiredLength
717 || sample[1].type() != CSSM_LIST_ELEMENT_DATUM
718 || sample[2].type() != CSSM_LIST_ELEMENT_DATUM
719 || (requiredLength == 4 && sample[3].type() != CSSM_LIST_ELEMENT_DATUM))
720 CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE);
721 CSSM_CSP_HANDLE &handle = *sample[1].data().interpretedAs<CSSM_CSP_HANDLE>(CSSM_ERRCODE_INVALID_SAMPLE_VALUE);
722 CssmKey &key = *sample[2].data().interpretedAs<CssmKey>(CSSM_ERRCODE_INVALID_SAMPLE_VALUE);
723
724 if (key.header().cspGuid() == gGuidAppleCSPDL) {
725 // handleOrKey is a SecurityServer KeyHandle; ignore key argument
726 return safer_cast<LocalKey &>(*Server::key(handle));
727 } else {
728 // not a KeyHandle reference; use key as a raw key
729 if (key.header().blobType() != CSSM_KEYBLOB_RAW)
730 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_REFERENCE);
731 if (key.header().keyClass() != CSSM_KEYCLASS_SESSION_KEY)
732 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_CLASS);
733 return CssmClient::Key(Server::csp(), key, true);
734 }
735 }
736
737
738 //
739 // Verify a putative database passphrase.
740 // If the database is already unlocked, just check the passphrase.
741 // Otherwise, unlock with that passphrase and report success.
742 // Caller must hold the common lock.
743 //
744 bool KeychainDatabase::validatePassphrase(const CssmData &passphrase) const
745 {
746 if (common().hasMaster()) {
747 // verify against known secret
748 return common().validatePassphrase(passphrase);
749 } else {
750 // no master secret - perform "blind" unlock to avoid actual unlock
751 try {
752 DatabaseCryptoCore test;
753 test.setup(mBlob, passphrase);
754 test.decodeCore(mBlob, NULL);
755 return true;
756 } catch (...) {
757 return false;
758 }
759 }
760 }
761
762
763 //
764 // Lock this database
765 //
766 void KeychainDatabase::lockDb()
767 {
768 common().lockDb();
769 }
770
771
772 //
773 // Given a Key for this database, encode it into a blob and return it.
774 //
775 KeyBlob *KeychainDatabase::encodeKey(const CssmKey &key, const CssmData &pubAcl, const CssmData &privAcl)
776 {
777 unlockDb();
778
779 // tell the cryptocore to form the key blob
780 return common().encodeKeyCore(key, pubAcl, privAcl);
781 }
782
783
784 //
785 // Given a "blobbed" key for this database, decode it into its real
786 // key object and (re)populate its ACL.
787 //
788 void KeychainDatabase::decodeKey(KeyBlob *blob, CssmKey &key, void * &pubAcl, void * &privAcl)
789 {
790 unlockDb(); // we need our keys
791
792 common().decodeKeyCore(blob, key, pubAcl, privAcl);
793 // memory protocol: pubAcl points into blob; privAcl was allocated
794
795 activity();
796 }
797
798 //
799 // Given a KeychainKey (that implicitly belongs to another keychain),
800 // return it encoded using this keychain's operational secrets.
801 //
802 KeyBlob *KeychainDatabase::recodeKey(KeychainKey &oldKey)
803 {
804 if (mRecodingSource != &oldKey.referent<KeychainDatabase>()) {
805 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY);
806 }
807 oldKey.instantiateAcl(); // make sure key is decoded
808 CssmData publicAcl, privateAcl;
809 oldKey.exportBlob(publicAcl, privateAcl);
810 // NB: blob's memory belongs to caller, not the common
811 KeyBlob *blob = common().encodeKeyCore(oldKey.cssmKey(), publicAcl, privateAcl);
812 oldKey.acl().allocator.free(publicAcl);
813 oldKey.acl().allocator.free(privateAcl);
814 return blob;
815 }
816
817
818 //
819 // Modify database parameters
820 //
821 void KeychainDatabase::setParameters(const DBParameters &params)
822 {
823 StLock<Mutex> _(common());
824 makeUnlocked();
825 common().mParams = params;
826 common().invalidateBlob(); // invalidate old blobs
827 activity(); // (also resets the timeout timer)
828 secdebug("KCdb", "%p common %p(%s) set params=(%ld,%d)",
829 this, &common(), dbName(), params.idleTimeout, params.lockOnSleep);
830 }
831
832
833 //
834 // Retrieve database parameters
835 //
836 void KeychainDatabase::getParameters(DBParameters &params)
837 {
838 StLock<Mutex> _(common());
839 makeUnlocked();
840 params = common().mParams;
841 //activity(); // getting parameters does not reset the idle timer
842 }
843
844
845 //
846 // RIGHT NOW, database ACLs are attached to the database.
847 // This will soon move upstairs.
848 //
849 SecurityServerAcl &KeychainDatabase::acl()
850 {
851 return *this;
852 }
853
854
855 //
856 // Intercept ACL change requests and reset blob validity
857 //
858 void KeychainDatabase::instantiateAcl()
859 {
860 StLock<Mutex> _(common());
861 makeUnlocked();
862 }
863
864 void KeychainDatabase::changedAcl()
865 {
866 StLock<Mutex> _(common());
867 version = 0;
868 }
869
870
871 //
872 // Check an incoming DbBlob for basic viability
873 //
874 void KeychainDatabase::validateBlob(const DbBlob *blob)
875 {
876 // perform basic validation on the blob
877 assert(blob);
878 blob->validate(CSSMERR_APPLEDL_INVALID_DATABASE_BLOB);
879 switch (blob->version()) {
880 #if defined(COMPAT_OSX_10_0)
881 case DbBlob::version_MacOS_10_0:
882 break;
883 #endif
884 case DbBlob::version_MacOS_10_1:
885 break;
886 default:
887 CssmError::throwMe(CSSMERR_APPLEDL_INCOMPATIBLE_DATABASE_BLOB);
888 }
889 }
890
891
892 //
893 // Debugging support
894 //
895 #if defined(DEBUGDUMP)
896
897 void KeychainDbCommon::dumpNode()
898 {
899 PerSession::dumpNode();
900 uint32 sig; memcpy(&sig, &mIdentifier.signature(), sizeof(sig));
901 Debug::dump(" %s[%8.8lx]", mIdentifier.dbName(), sig);
902 if (isLocked()) {
903 Debug::dump(" locked");
904 } else {
905 time_t whenTime = time_t(when());
906 Debug::dump(" unlocked(%24.24s/%.2g)", ctime(&whenTime),
907 (when() - Time::now()).seconds());
908 }
909 Debug::dump(" params=(%ld,%d)", mParams.idleTimeout, mParams.lockOnSleep);
910 }
911
912 void KeychainDatabase::dumpNode()
913 {
914 PerProcess::dumpNode();
915 Debug::dump(" %s vers=%ld",
916 mValidData ? " data" : " nodata", version);
917 if (mBlob) {
918 uint32 sig; memcpy(&sig, &mBlob->randomSignature, sizeof(sig));
919 Debug::dump(" blob=%p[%8.8lx]", mBlob, sig);
920 } else {
921 Debug::dump(" noblob");
922 }
923 }
924
925 #endif //DEBUGDUMP
926
927
928 //
929 // DbCommon basic features
930 //
931 KeychainDbCommon::KeychainDbCommon(Session &ssn, const DbIdentifier &id)
932 : LocalDbCommon(ssn), sequence(0), version(1), mIdentifier(id),
933 mIsLocked(true), mValidParams(false)
934 {
935 // match existing DbGlobal or create a new one
936 Server &server = Server::active();
937 StLock<Mutex> _(server);
938 if (KeychainDbGlobal *dbglobal =
939 server.findFirst<KeychainDbGlobal, const DbIdentifier &>(&KeychainDbGlobal::identifier, identifier())) {
940 parent(*dbglobal);
941 secdebug("KCdb", "%p linking to existing DbGlobal %p", this, dbglobal);
942 } else {
943 // DbGlobal not present; make a new one
944 parent(*new KeychainDbGlobal(identifier()));
945 secdebug("KCdb", "%p linking to new DbGlobal %p", this, &global());
946 }
947
948 // link lifetime to the Session
949 session().addReference(*this);
950 }
951
952 KeychainDbCommon::~KeychainDbCommon()
953 {
954 secdebug("KCdb", "DbCommon %p destroyed", this);
955
956 // explicitly unschedule ourselves
957 Server::active().clearTimer(this);
958 }
959
960 KeychainDbGlobal &KeychainDbCommon::global() const
961 {
962 return parent<KeychainDbGlobal>();
963 }
964
965
966 void KeychainDbCommon::makeNewSecrets()
967 {
968 // we already have a master key (right?)
969 assert(hasMaster());
970
971 // tell crypto core to generate the use keys
972 DatabaseCryptoCore::generateNewSecrets();
973
974 // we're now officially "unlocked"; set the timer
975 setUnlocked();
976 }
977
978
979 //
980 // All unlocking activity ultimately funnels through this method.
981 // This unlocks a DbCommon using the secrets setup in its crypto core
982 // component, and performs all the housekeeping needed to represent
983 // the state change.
984 // Returns true if unlock was successful, false if it failed due to
985 // invalid/insufficient secrets. Throws on other errors.
986 //
987 bool KeychainDbCommon::unlockDb(DbBlob *blob, void **privateAclBlob)
988 {
989 try {
990 // Tell the cryptocore to (try to) decode itself. This will fail
991 // in an astonishing variety of ways if the passphrase is wrong.
992 assert(hasMaster());
993 decodeCore(blob, privateAclBlob);
994 secdebug("KCdb", "%p unlock successful", this);
995 } catch (...) {
996 secdebug("KCdb", "%p unlock failed", this);
997 return false;
998 }
999
1000 // get the database parameters only if we haven't got them yet
1001 if (!mValidParams) {
1002 mParams = blob->params;
1003 n2hi(mParams.idleTimeout);
1004 mValidParams = true; // sticky
1005 }
1006
1007 setUnlocked(); // mark unlocked
1008
1009 // broadcast unlock notification
1010 notify(kNotificationEventUnlocked);
1011 return true;
1012 }
1013
1014 void KeychainDbCommon::setUnlocked()
1015 {
1016 session().addReference(*this); // active/held
1017 mIsLocked = false; // mark unlocked
1018 activity(); // set timeout timer
1019 }
1020
1021
1022 void KeychainDbCommon::lockDb()
1023 {
1024 StLock<Mutex> _(*this);
1025 if (!isLocked()) {
1026 secdebug("KCdb", "common %s(%p) locking", dbName(), this);
1027 DatabaseCryptoCore::invalidate();
1028 notify(kNotificationEventLocked);
1029 Server::active().clearTimer(this);
1030
1031 mIsLocked = true; // mark locked
1032
1033 // this call may destroy us if we have no databases anymore
1034 session().removeReference(*this);
1035 }
1036 }
1037
1038
1039 DbBlob *KeychainDbCommon::encode(KeychainDatabase &db)
1040 {
1041 assert(!isLocked()); // must have been unlocked by caller
1042
1043 // export database ACL to blob form
1044 CssmData pubAcl, privAcl;
1045 db.acl().exportBlob(pubAcl, privAcl);
1046
1047 // tell the cryptocore to form the blob
1048 DbBlob form;
1049 form.randomSignature = identifier();
1050 form.sequence = sequence;
1051 form.params = mParams;
1052 h2ni(form.params.idleTimeout);
1053
1054 assert(hasMaster());
1055 DbBlob *blob = encodeCore(form, pubAcl, privAcl);
1056
1057 // clean up and go
1058 db.acl().allocator.free(pubAcl);
1059 db.acl().allocator.free(privAcl);
1060 return blob;
1061 }
1062
1063
1064 //
1065 // Send a keychain-related notification event about this keychain
1066 //
1067 void KeychainDbCommon::notify(NotificationEvent event)
1068 {
1069 // form the data (encoded DLDbIdentifier)
1070 NameValueDictionary nvd;
1071 NameValueDictionary::MakeNameValueDictionaryFromDLDbIdentifier(identifier(), nvd);
1072 CssmData data;
1073 nvd.Export(data);
1074
1075 // inject notification into Security event system
1076 Listener::notify(kNotificationDomainDatabase, event, data);
1077
1078 // clean up
1079 free (data.data());
1080 }
1081
1082
1083 //
1084 // Perform deferred lock processing for a database.
1085 //
1086 void KeychainDbCommon::action()
1087 {
1088 secdebug("KCdb", "common %s(%p) locked by timer", dbName(), this);
1089 lockDb();
1090 }
1091
1092 void KeychainDbCommon::activity()
1093 {
1094 if (!isLocked()) {
1095 secdebug("KCdb", "setting DbCommon %p timer to %d",
1096 this, int(mParams.idleTimeout));
1097 Server::active().setTimer(this, Time::Interval(int(mParams.idleTimeout)));
1098 }
1099 }
1100
1101 void KeychainDbCommon::sleepProcessing()
1102 {
1103 secdebug("KCdb", "common %s(%p) sleep-lock processing", dbName(), this);
1104 StLock<Mutex> _(*this);
1105 if (mParams.lockOnSleep)
1106 lockDb();
1107 }
1108
1109 void KeychainDbCommon::lockProcessing()
1110 {
1111 lockDb();
1112 }
1113
1114
1115 //
1116 // Keychain global objects
1117 //
1118 KeychainDbGlobal::KeychainDbGlobal(const DbIdentifier &id)
1119 : mIdentifier(id)
1120 {
1121 }
1122
1123 KeychainDbGlobal::~KeychainDbGlobal()
1124 {
1125 secdebug("KCdb", "DbGlobal %p destroyed", this);
1126 }