]> git.saurik.com Git - apple/security.git/blob - securityd/src/kcdatabase.cpp
Security-58286.200.222.tar.gz
[apple/security.git] / securityd / src / kcdatabase.cpp
1 /*
2 * Copyright (c) 2000-2009,2012-2014 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_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>
58 #include <syslog.h>
59 #include <sys/sysctl.h>
60 #include <sys/kauth.h>
61 #include <sys/csr.h>
62 __BEGIN_DECLS
63 #include <corecrypto/ccmode_siv.h>
64 __END_DECLS
65
66 void unflattenKey(const CssmData &flatKey, CssmKey &rawKey); //>> make static method on KeychainDatabase
67
68 //
69 // Static members
70 //
71 KeychainDbCommon::CommonSet KeychainDbCommon::mCommonSet;
72 ReadWriteLock KeychainDbCommon::mRWCommonLock;
73
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)
76 {
77 if (!out_euid) return;
78
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);
82 int ret;
83 ret = sysctl(mib, (sizeof(mib)/sizeof(int)), &proc_info, &len, NULL, 0);
84
85 // don't allow root
86 if ((ret == 0) && (proc_info.kp_eproc.e_ucred.cr_uid != 0)) {
87 *out_euid = proc_info.kp_eproc.e_ucred.cr_uid;
88 }
89 }
90
91 static int
92 unlock_keybag(KeychainDatabase & db, const void * secret, int secret_len)
93 {
94 int rc = -1;
95
96 if (!db.common().isLoginKeychain()) return 0;
97
98 service_context_t context = db.common().session().get_current_service_context();
99
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);
103 }
104
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);
112 } else {
113 rc = service_client_kb_unlock(&context, secret, secret_len);
114 }
115 }
116
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);
123 }
124
125 if (rc != 0) { // if a login.keychain password exists but doesnt on the keybag update it
126 bool no_pin = false;
127 if ((secret_len > 0) && service_client_kb_is_locked(&context, NULL, &no_pin) == 0) {
128 if (no_pin) {
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);
131 }
132 }
133 }
134 } // session_keybag_check_master_key
135 }
136
137 if (rc == 0) {
138 db.common().session().keybagSetState(session_keybag_unlocked|session_keybag_loaded|session_keybag_check_master_key);
139 } else {
140 syslog(LOG_ERR, "Failed to unlock iCloud keychain for uid %d", context.s_uid);
141 }
142
143 return rc;
144 }
145
146 static void
147 change_secret_on_keybag(KeychainDatabase & db, const void * secret, int secret_len, const void * new_secret, int new_secret_len)
148 {
149 if (!db.common().isLoginKeychain()) return;
150
151 service_context_t context = db.common().session().get_current_service_context();
152
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);
156 }
157
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);
164 } else {
165 rc = service_client_kb_change_secret(&context, secret, secret_len, new_secret, new_secret_len);
166 }
167 }
168
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);
172 }
173
174 // if for some reason we are locked lets unlock so later we don't try and throw up SecurityAgent dialog
175 bool locked = false;
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);
180 }
181 }
182 }
183
184 // Attempt to unlock the keybag with a AccessCredentials password.
185 // Honors UI disabled flags from clients set in the cred before prompt.
186 static bool
187 unlock_keybag_with_cred(KeychainDatabase &db, const AccessCredentials *cred){
188 list<CssmSample> samples;
189 if (cred && cred->samples().collect(CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK, samples)) {
190 for (list<CssmSample>::iterator it = samples.begin(); it != samples.end(); it++) {
191 TypedList &sample = *it;
192 sample.checkProper();
193 switch (sample.type()) {
194 // interactively prompt the user - no additional data
195 case CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT:
196 {
197 /*
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.
201 */
202 bool query_success = false;
203 bool unlock_success = false;
204 bool looped = false;
205 do {
206 {
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
209 bool locked = false;
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;
217 }
218 } else {
219 // another thread already unlocked the keybag
220 query_success = true; // NOT unlock_success because we have the wrong lock
221 }
222 } // StSyncLock goes out of scope, we have common lock again
223 bool locked = false;
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;
227 }
228 if (looped) {
229 secnotice("KCdb", "Unlocking the keybag again (threading?)");
230 }
231 looped = true;
232 } while (query_success && !unlock_success);
233 }
234 break;
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())) {
241 return true;
242 }
243 break;
244 }
245 default: {
246 // Unknown sub-sample for unlocking.
247 secinfo("KCdb", "keybag: unknown sub-sample unlock (%d) ignored", sample.type());
248 break;
249 }
250 }
251 }
252 }
253 return false;
254 }
255
256 //
257 // Create a Database object from initial parameters (create operation)
258 //
259 KeychainDatabase::KeychainDatabase(const DLDbIdentifier &id, const DBParameters &params, 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)
262 {
263 // save a copy of the credentials for later access control
264 mCred = DataWalkers::copy(cred, Allocator::standard());
265
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);
270
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();
275
276 StLock<Mutex> _(*newCommon);
277 parent(*newCommon);
278 newCommon->insert();
279 // new common is now visible (in ident-map) but we hold its lock
280
281 // establish the new master secret
282 establishNewSecrets(cred, SecurityAgent::newDatabase);
283
284 // set initial database parameters
285 common().mParams = params;
286
287 // the common is "unlocked" now
288 common().makeNewSecrets();
289
290 // establish initial ACL
291 if (owner)
292 acl().cssmSetInitial(*owner);
293 else
294 acl().cssmSetInitial(new AnyAclSubject());
295 mValidData = true;
296
297 // for now, create the blob immediately
298 encode();
299
300 proc.addReference(*this);
301
302 // this new keychain is unlocked; make it so
303 activity();
304
305 secinfo("KCdb", "creating keychain %p %s with common %p", this, (char*)this->dbName(), &common());
306 }
307
308
309 //
310 // Create a Database object from a database blob (decoding)
311 //
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)
315 {
316 validateBlob(blob);
317
318 // save a copy of the credentials for later access control
319 mCred = DataWalkers::copy(cred, Allocator::standard());
320 mBlob = blob->copy();
321
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)) {
328 parent(*com);
329 secinfo("KCdb", "joining keychain %p %s with common %p", this, (char*)this->dbName(), &common());
330 } else {
331 // DbCommon not present; make a new one
332 secinfo("kccommon", "no common found");
333 parent(*com);
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
337 }
338 proc.addReference(*this);
339 }
340
341 void KeychainDbCommon::insert()
342 {
343 StReadWriteLock _(mRWCommonLock, StReadWriteLock::Write);
344 insertHoldingLock();
345 }
346
347 void KeychainDbCommon::insertHoldingLock()
348 {
349 mCommonSet.insert(this);
350 }
351
352
353
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)
356 {
357 // Prepare to drop the mRWCommonLock.
358 {
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()) {
362 common = *it;
363 secinfo("kccommon", "found a common for %s at %p", ident.dbName(), common.get());
364 return true;
365 }
366 }
367 }
368
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.
371 {
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()) {
375 common = *it;
376 secinfo("kccommon", "found a common for %s at %p", ident.dbName(), common.get());
377 return true;
378 }
379 }
380
381 // not found
382 if(cloneFrom) {
383 common = new KeychainDbCommon(session, ident, *cloneFrom);
384 } else if(requestedVersion != CommonBlob::version_none) {
385 common = new KeychainDbCommon(session, ident, requestedVersion);
386 } else {
387 common = new KeychainDbCommon(session, ident);
388 }
389
390 secinfo("kccommon", "made a new common for %s at %p", ident.dbName(), common.get());
391
392 // Can't call insert() here, because it grabs the write lock (which we have).
393 common->insertHoldingLock();
394 }
395 common->initializeKeybag();
396 return false;
397 }
398
399 // recode/clone:
400 //
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.
408 //
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)
411 {
412 mCred = DataWalkers::copy(src.mCred, Allocator::standard());
413
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());
418
419 // create common block and initialize
420 RefPointer<KeychainDbCommon> newCommon = new KeychainDbCommon(proc.session(), ident);
421 newCommon->initializeKeybag();
422 StLock<Mutex> _(*newCommon);
423 parent(*newCommon);
424 newCommon->insert();
425
426 // set initial database parameters from the source keychain
427 common().mParams = src.common().mParams;
428
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());
438
439 // import the operational secrets
440 RefPointer<KeychainDatabase> srcKC = Server::keychain(dbToClone);
441 common().importSecrets(srcKC->common());
442
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);
449
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;
453
454 common().setUnlocked();
455 mValidData = true;
456
457 encode();
458
459 proc.addReference(*this);
460 secinfo("SSdb", "database %s(%p) created as copy, common at %p",
461 common().dbName(), this, &common());
462 }
463
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)
467 {
468 mCred = DataWalkers::copy(src.mCred, Allocator::standard());
469
470 DbIdentifier ident(id, src.identifier());
471
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());
478 }
479
480 StLock<Mutex> _(*newCommon);
481 parent(*newCommon);
482
483 // set initial database parameters from the source keychain
484 common().mParams = src.common().mParams;
485
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);
492
493 // Copy the source database's blob, if possible
494 if(src.mBlob) {
495 mBlob = src.mBlob->copy();
496 version = src.version;
497 }
498
499 // We've copied everything we can from our source. If they were valid, so are we.
500 mValidData = src.mValidData;
501
502 proc.addReference(*this);
503 secinfo("SSdb", "database %s(%p) created as expected clone, common at %p", common().dbName(), this, &common());
504 }
505
506
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)
510 {
511 mCred = DataWalkers::copy(src.mCred, Allocator::standard());
512
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());
519
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());
522
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);
529 }
530 newCommon->initializeKeybag();
531 StLock<Mutex> _(*newCommon);
532 parent(*newCommon);
533
534 // We want to re-use the master secrets from the source database (and so the
535 // same password), but reroll new operational secrets.
536
537 // Copy the master secret over...
538 src.unlockDb(false); // precaution
539
540 common().setup(src.blob(), src.common().masterKey(), false); // keep the new common's version intact
541
542 // set initial database parameters from the source keychain
543 common().mParams = src.common().mParams;
544
545 // and make new operational secrets
546 common().makeNewSecrets();
547
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);
554
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;
558
559 common().setUnlocked();
560 mValidData = true;
561
562 encode();
563
564 proc.addReference(*this);
565 secinfo("SSdb", "database %s(%p) created as expected copy, common at %p",
566 common().dbName(), this, &common());
567 }
568
569 //
570 // Destroy a Database
571 //
572 KeychainDatabase::~KeychainDatabase()
573 {
574 secinfo("KCdb", "deleting database %s(%p) common %p",
575 common().dbName(), this, &common());
576 Allocator::standard().free(mCred);
577 Allocator::standard().free(mBlob);
578 }
579
580
581 //
582 // Basic Database virtual implementations
583 //
584 KeychainDbCommon &KeychainDatabase::common() const
585 {
586 return parent<KeychainDbCommon>();
587 }
588
589 const char *KeychainDatabase::dbName() const
590 {
591 return common().dbName();
592 }
593
594 bool KeychainDatabase::transient() const
595 {
596 return false; // has permanent store
597 }
598
599 AclKind KeychainDatabase::aclKind() const
600 {
601 return dbAcl;
602 }
603
604 Database *KeychainDatabase::relatedDatabase()
605 {
606 return this;
607 }
608
609 //
610 // (Re-)Authenticate the database. This changes the stored credentials.
611 //
612 void KeychainDatabase::authenticate(CSSM_DB_ACCESS_TYPE mode,
613 const AccessCredentials *cred)
614 {
615 StLock<Mutex> _(common());
616
617 // the (Apple specific) RESET bit means "lock the database now"
618 switch (mode) {
619 case CSSM_DB_ACCESS_RESET:
620 secinfo("KCdb", "%p ACCESS_RESET triggers keychain lock", this);
621 common().lockDb();
622 break;
623 default:
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);
628 mCred = newCred;
629 }
630 }
631
632
633 //
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.
638 //
639 RefPointer<Key> KeychainDatabase::makeKey(Database &db, const CssmKey &newKey,
640 uint32 moreAttributes, const AclEntryPrototype *owner)
641 {
642 StLock<Mutex> lock(common());
643 if (moreAttributes & CSSM_KEYATTR_PERMANENT)
644 return new KeychainKey(db, newKey, moreAttributes, owner);
645 else
646 return process().makeTemporaryKey(newKey, moreAttributes, owner);
647 }
648
649 RefPointer<Key> KeychainDatabase::makeKey(const CssmKey &newKey,
650 uint32 moreAttributes, const AclEntryPrototype *owner)
651 {
652 return makeKey(*this, newKey, moreAttributes, owner);
653 }
654
655
656 //
657 // Return the database blob, recalculating it as needed.
658 //
659 DbBlob *KeychainDatabase::blob()
660 {
661 StLock<Mutex> _(common());
662 if (!validBlob()) {
663 makeUnlocked(false); // unlock to get master secret
664 encode(); // (re)encode blob if needed
665 }
666 activity(); // reset timeout
667 assert(validBlob()); // better have a valid blob now...
668 return mBlob;
669 }
670
671
672 //
673 // Encode the current database as a blob.
674 // Note that this returns memory we own and keep.
675 // Caller must hold common lock.
676 //
677 void KeychainDatabase::encode()
678 {
679 DbBlob *blob = common().encode(*this);
680 Allocator::standard().free(mBlob);
681 mBlob = blob;
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);
686 }
687
688
689 //
690 // Change the passphrase on a database
691 //
692 void KeychainDatabase::changePassphrase(const AccessCredentials *cred)
693 {
694 // get and hold the common lock (don't let other threads break in here)
695 StLock<Mutex> _(common());
696
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);
701
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);
706 return;
707 }
708 if (mSecret) { mSecret.reset(); }
709 mSaveSecret = false;
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
713
714 // send out a notification
715 notify(kNotificationEventPassphraseChanged);
716
717 // I guess this counts as an activity
718 activity();
719 }
720
721 //
722 // Second stage of keychain synchronization: overwrite the original keychain's
723 // (this KeychainDatabase's) operational secrets
724 //
725 void KeychainDatabase::commitSecretsForSync(KeychainDatabase &cloneDb)
726 {
727 StLock<Mutex> _(common());
728
729 // try to detect spoofing
730 if (cloneDb.mRecodingSource != this)
731 CssmError::throwMe(CSSM_ERRCODE_INVALID_DB_HANDLE);
732
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
736
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.
742 //
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();
747 if (count > 0) {
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());
757 }
758 }
759 }
760
761 // mark down that we just recoded
762 mRecoded = true;
763
764 // it is now safe to replace the old op secrets
765 common().importSecrets(cloneDb.common());
766 common().invalidateBlob();
767 }
768
769
770 //
771 // Extract the database master key as a proper Key object.
772 //
773 RefPointer<Key> KeychainDatabase::extractMasterKey(Database &db,
774 const AccessCredentials *cred, const AclEntryPrototype *owner,
775 uint32 usage, uint32 attrs)
776 {
777 // get and hold common lock
778 StLock<Mutex> _(common());
779
780 // force lock to require re-validation of credentials
781 lockDb();
782
783 // unlock to establish master secret
784 makeUnlocked(false);
785
786 // extract the raw cryptographic key
787 CssmClient::WrapKey wrap(Server::csp(), CSSM_ALGID_NONE);
788 CssmKey key;
789 wrap(common().masterKey(), key);
790
791 // make the key object and return it
792 return makeKey(db, key, attrs & LocalKey::managedAttributes, owner);
793 }
794
795
796 //
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.
802 //
803 void KeychainDatabase::unlockDb(bool unlockKeybag)
804 {
805 StLock<Mutex> _(common());
806 makeUnlocked(unlockKeybag);
807 }
808
809 void KeychainDatabase::makeUnlocked(bool unlockKeybag)
810 {
811 return makeUnlocked(mCred, unlockKeybag);
812 }
813
814 void KeychainDatabase::makeUnlocked(const AccessCredentials *cred, bool unlockKeybag)
815 {
816 if (isLocked()) {
817 secnotice("KCdb", "%p(%p) unlocking for makeUnlocked()", this, &common());
818 assert(mBlob || (mValidData && common().hasMaster()));
819 bool asking_again = false;
820 do {
821 if (asking_again) {
822 secnotice("KCdb", "makeUnlocked: establishing old secrets again (threading?)");
823 }
824 establishOldSecrets(cred);
825 asking_again = true;
826 } while (!common().hasMaster());
827 common().setUnlocked(); // mark unlocked
828 if (common().isLoginKeychain()) {
829 CssmKey master = common().masterKey();
830 CssmKey rawMaster;
831 CssmClient::WrapKey wrap(Server::csp(), CSSM_ALGID_NONE);
832 wrap(master, rawMaster);
833
834 service_context_t context = common().session().get_current_service_context();
835 service_client_stash_load_key(&context, rawMaster.keyData(), (int)rawMaster.length());
836 }
837 } else if (unlockKeybag && common().isLoginKeychain()) {
838 bool locked = false;
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");
843 }
844 }
845 }
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());
848 if (!decode())
849 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED);
850 }
851 assert(!isLocked());
852 assert(mValidData);
853 }
854
855 //
856 // Invoke the securityd_service to retrieve the keychain master
857 // key from the AppleFDEKeyStore.
858 //
859 void KeychainDatabase::stashDbCheck()
860 {
861 CssmAutoData masterKey(Allocator::standard(Allocator::sensitive));
862 CssmAutoData encKey(Allocator::standard(Allocator::sensitive));
863
864 // Fetch the key
865 int rc = 0;
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);
870 if (rc == 0) {
871 if (stash_key) {
872 masterKey.copy(CssmData((void *)stash_key,stash_key_len));
873 memset(stash_key, 0, stash_key_len);
874 free(stash_key);
875 }
876 } else {
877 secnotice("KCdb", "failed to get stash from securityd_service: %d", (int)rc);
878 CssmError::throwMe(rc);
879 }
880
881 {
882 StLock<Mutex> _(common());
883
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);
893
894 if (!decode())
895 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED);
896
897 common().get_encryption_key(encKey);
898 }
899
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());
904 }
905 }
906
907 //
908 // Get the keychain master key and invoke the securityd_service
909 // to stash it in the AppleFDEKeyStore ready for commit to the
910 // NVRAM blob.
911 //
912 void KeychainDatabase::stashDb()
913 {
914 CssmAutoData data(Allocator::standard(Allocator::sensitive));
915
916 {
917 StLock<Mutex> _(common());
918
919 if (!common().isValid()) {
920 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY);
921 }
922
923 CssmKey key = common().masterKey();
924 data.copy(key.keyData());
925 }
926
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);
930 }
931
932 //
933 // The following unlock given an explicit passphrase, rather than using
934 // (special cred sample based) default procedures.
935 //
936 void KeychainDatabase::unlockDb(const CssmData &passphrase, bool unlockKeybag)
937 {
938 StLock<Mutex> _(common());
939 makeUnlocked(passphrase, unlockKeybag);
940 }
941
942 void KeychainDatabase::makeUnlocked(const CssmData &passphrase, bool unlockKeybag)
943 {
944 if (isLocked()) {
945 if (decode(passphrase))
946 return;
947 else
948 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED);
949 } else if (!mValidData) { // need to decode to get our ACLs, passphrase available
950 if (!decode())
951 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED);
952 }
953
954 if (unlockKeybag && common().isLoginKeychain()) {
955 bool locked = false;
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());
959 }
960 }
961
962 assert(!isLocked());
963 assert(mValidData);
964 }
965
966
967 //
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.
971 //
972 bool KeychainDatabase::decode(const CssmData &passphrase)
973 {
974 assert(mBlob);
975 common().setup(mBlob, passphrase);
976 bool success = decode();
977 if (success && common().isLoginKeychain()) {
978 unlock_keybag(*this, passphrase.data(), (int)passphrase.length());
979 }
980 return success;
981 }
982
983
984 //
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
988 // the master key.
989 //
990 bool KeychainDatabase::decode()
991 {
992 assert(mBlob);
993 assert(common().hasMaster());
994 void *privateAclBlob;
995 if (common().unlockDb(mBlob, &privateAclBlob)) {
996 if (!mValidData) {
997 acl().importBlob(mBlob->publicAclBlob(), privateAclBlob);
998 mValidData = true;
999 }
1000 Allocator::standard().free(privateAclBlob);
1001 return true;
1002 }
1003 secinfo("KCdb", "%p decode failed", this);
1004 return false;
1005 }
1006
1007
1008 //
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).
1021 //
1022 // How this works:
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.
1028 //
1029 void KeychainDatabase::establishOldSecrets(const AccessCredentials *creds)
1030 {
1031 bool forSystem = this->belongsToSystem(); // this keychain belongs to the system security domain
1032
1033 // attempt system-keychain unlock
1034 if (forSystem) {
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));
1039 if (decode())
1040 return;
1041 }
1042 }
1043
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:
1052 if (!forSystem) {
1053 if (interactiveUnlock())
1054 return;
1055 }
1056 break;
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]))
1063 return;
1064 break;
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:
1068 assert(mBlob);
1069 secinfo("KCdb", "%p attempting explicit key unlock", this);
1070 common().setup(mBlob, keyFromCreds(sample, 4));
1071 if (decode()) {
1072 return;
1073 }
1074 break;
1075 case CSSM_SAMPLE_TYPE_KEYBAG_KEY:
1076 assert(mBlob);
1077 secinfo("KCdb", "%p attempting keybag key unlock", this);
1078 common().setup(mBlob, keyFromKeybag(sample));
1079 if (decode()) {
1080 return;
1081 }
1082 break;
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);
1086 break;
1087 default:
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());
1095 break;
1096 }
1097 }
1098 } else {
1099 // default action
1100 assert(mBlob);
1101
1102 if (!forSystem) {
1103 if (interactiveUnlock())
1104 return;
1105 }
1106 }
1107
1108 // out of options - no secret obtained
1109 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED);
1110 }
1111
1112 //
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
1116 //
1117 // TODO: These two functions should probably be refactored to something nicer.
1118 bool KeychainDatabase::checkCredentials(const AccessCredentials *creds) {
1119
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);
1130 break;
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])) {
1137 return true;
1138 }
1139 break;
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:
1143 assert(mBlob);
1144 secinfo("integrity", "%p attempting explicit key unlock", this);
1145 try {
1146 CssmClient::Key checkKey = keyFromCreds(sample, 4);
1147 if(common().validateKey(checkKey)) {
1148 return true;
1149 }
1150 } catch(...) {
1151 // ignore all problems in keyFromCreds
1152 secinfo("integrity", "%p caught error", this);
1153 }
1154 break;
1155 }
1156 }
1157 }
1158
1159 // out of options - credentials don't match
1160 return false;
1161 }
1162
1163 uint32_t KeychainDatabase::interactiveUnlockAttempts = 0;
1164
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()
1168 {
1169 secinfo("KCdb", "%p attempting interactive unlock", this);
1170 interactiveUnlockAttempts++;
1171
1172 SecurityAgent::Reason reason = SecurityAgent::noReason;
1173 QueryUnlock query(*this);
1174
1175 if (isLocked()) {
1176 query.inferHints(Server::process());
1177 StSyncLock<Mutex, Mutex> uisync(common().uiLock(), common());
1178 reason = query();
1179 uisync.unlock();
1180 if (mSaveSecret && reason == SecurityAgent::noReason) {
1181 query.retrievePassword(mSecret);
1182 }
1183 query.disconnect();
1184 } else {
1185 secinfo("KCdb", "%p was unlocked during uiLock delay", this);
1186 }
1187
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);
1198 uisync.unlock();
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());
1204 }
1205
1206 }
1207 }
1208
1209 return reason == SecurityAgent::noReason;
1210 }
1211
1212 uint32_t KeychainDatabase::getInteractiveUnlockAttempts() {
1213 if (csr_check(CSR_ALLOW_APPLE_INTERNAL)) {
1214 // Not an internal install; don't answer
1215 return 0;
1216 } else {
1217 return interactiveUnlockAttempts;
1218 }
1219 }
1220
1221
1222 //
1223 // Same thing, but obtain a new secret somehow and set it into the common.
1224 //
1225 bool KeychainDatabase::establishNewSecrets(const AccessCredentials *creds, SecurityAgent::Reason reason)
1226 {
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:
1235 {
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));
1243 uisync.unlock();
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());
1247 return true;
1248 }
1249 }
1250 break;
1251 // try to use an explicitly given passphrase
1252 case CSSM_SAMPLE_TYPE_PASSWORD:
1253 {
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();
1267 }
1268 }
1269 }
1270 if (!oldPassphrase.length() && mSecret && mSecret.length()) {
1271 oldPassphrase = mSecret;
1272 }
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
1277 return false;
1278 }
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());
1281 }
1282 else {
1283 common().setup(NULL, sample[1]);
1284 }
1285 return true;
1286 }
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));
1292 return true;
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);
1296 break;
1297 default:
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());
1306 break;
1307 }
1308 }
1309 } else {
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));
1317 uisync.unlock();
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());
1321 return true;
1322 }
1323 }
1324
1325 // out of options - no secret obtained
1326 CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED);
1327 }
1328
1329
1330 //
1331 // Given a (truncated) Database credentials TypedList specifying a master key,
1332 // locate the key and return a reference to it.
1333 //
1334 CssmClient::Key KeychainDatabase::keyFromCreds(const TypedList &sample, unsigned int requiredLength)
1335 {
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>();
1351
1352 if (key.header().cspGuid() == gGuidAppleCSPDL) {
1353 // handleOrKey is a SecurityServer KeyHandle; ignore key argument
1354 return safer_cast<LocalKey &>(*Server::key(handle));
1355 } else
1356 if (sample.type() == CSSM_SAMPLE_TYPE_ASYMMETRIC_KEY) {
1357 /*
1358 Contents (see DefaultCredentials::unlockKey in libsecurity_keychain/defaultcreds.cpp)
1359
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
1364 */
1365
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();
1371
1372 CssmKey rawWrappedKey;
1373 unflattenKey(flattenedKey, rawWrappedKey);
1374
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 |
1381
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
1388
1389 // promptCred: a credential permitting user prompt confirmations
1390 // contains:
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()));
1398
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);
1408
1409 // OK, this is skanky but necessary. We overwrite fields in the context struct
1410
1411 tmpContext->ContextType = CSSM_ALGCLASS_ASYMMETRIC;
1412 tmpContext->AlgorithmType = CSSM_ALGID_RSA;
1413
1414 db.unwrapKey(*tmpContext, cred, owner, unwrappingKey, NULL, usage, attrs,
1415 rawWrappedKey, masterKey, emptyDescriptiveData);
1416
1417 Allocator::standard().free(rawWrappedKey.KeyData.Data);
1418
1419 return safer_cast<LocalKey &>(*masterKey).key();
1420 }
1421 else if (sample.type() == CSSM_SAMPLE_TYPE_SYMMETRIC_KEY && sample.length() == 4 && sample[3].data().length() > 0) {
1422 /*
1423 Contents (see MasterKeyUnlockCredentials in libsecurity_cdsa_client/lib/aclclient.cpp)
1424
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
1429 */
1430
1431 // Fix up key to include actual data
1432 CssmData &flattenedKey = sample[3].data();
1433 unflattenKey(flattenedKey, key);
1434
1435 // Check that we have a reasonable key
1436 if (key.header().blobType() != CSSM_KEYBLOB_RAW) {
1437 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_REFERENCE);
1438 }
1439 if (key.header().keyClass() != CSSM_KEYCLASS_SESSION_KEY) {
1440 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_CLASS);
1441 }
1442
1443 // bring the key into the CSP and return it
1444 return CssmClient::Key(Server::csp(), key, true);
1445 } else {
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);
1452 }
1453 }
1454
1455 void unflattenKey(const CssmData &flatKey, CssmKey &rawKey)
1456 {
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
1461 //
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.
1464
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
1468
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
1477 }
1478
1479 CssmClient::Key
1480 KeychainDatabase::keyFromKeybag(const TypedList &sample)
1481 {
1482 service_context_t context;
1483 uint8_t *session_key;
1484 int session_key_size;
1485 int rc;
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;
1491
1492 assert(sample.type() == CSSM_SAMPLE_TYPE_KEYBAG_KEY);
1493
1494 CssmData &unlock_token = sample[2].data();
1495
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);
1498 if (rc != 0) {
1499 CssmError::throwMe(CSSM_ERRCODE_INVALID_CRYPTO_DATA);
1500 }
1501
1502 uint8_t *indata = (uint8_t *)unlock_token.data() + session_key_wrapped_len;
1503 size_t inlen = unlock_token.length() - session_key_wrapped_len;
1504
1505 decrypted_len = ccsiv_plaintext_size(mode, inlen - (version_len + nonce_len));
1506 decrypted_data = (uint8_t *)calloc(1, decrypted_len);
1507
1508 ccsiv_ctx_decl(mode->size, ctx);
1509
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);
1518
1519 ccsiv_ctx_clear(mode->size, ctx);
1520
1521 //free(decrypted_data);
1522 free(session_key);
1523 return makeRawKey(decrypted_data, decrypted_len, CSSM_ALGID_3DES_3KEY_EDE, CSSM_KEYUSE_ENCRYPT | CSSM_KEYUSE_DECRYPT);
1524 }
1525
1526 // adapted from DatabaseCryptoCore::makeRawKey
1527 CssmClient::Key KeychainDatabase::makeRawKey(void *data, size_t length,
1528 CSSM_ALGORITHMS algid, CSSM_KEYUSE usage)
1529 {
1530 // build a fake key
1531 CssmKey key;
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);
1539
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;
1544 unwrap(key,
1545 CssmClient::KeySpec(CSSM_KEYUSE_ANY, CSSM_KEYATTR_RETURN_DATA | CSSM_KEYATTR_EXTRACTABLE),
1546 unwrappedKey, &descriptiveData, NULL);
1547 return CssmClient::Key(Server::csp(), unwrappedKey);
1548 }
1549
1550 //
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.
1555 //
1556 bool KeychainDatabase::validatePassphrase(const CssmData &passphrase) const
1557 {
1558 if (common().hasMaster()) {
1559 // verify against known secret
1560 return common().validatePassphrase(passphrase);
1561 } else {
1562 // no master secret - perform "blind" unlock to avoid actual unlock
1563 try {
1564 DatabaseCryptoCore test;
1565 test.setup(mBlob, passphrase);
1566 test.decodeCore(mBlob, NULL);
1567 return true;
1568 } catch (...) {
1569 return false;
1570 }
1571 }
1572 }
1573
1574
1575 //
1576 // Lock this database
1577 //
1578 void KeychainDatabase::lockDb()
1579 {
1580 common().lockDb();
1581 }
1582
1583
1584 //
1585 // Given a Key for this database, encode it into a blob and return it.
1586 //
1587 KeyBlob *KeychainDatabase::encodeKey(const CssmKey &key, const CssmData &pubAcl, const CssmData &privAcl)
1588 {
1589 bool inTheClear = false;
1590 if((key.keyClass() == CSSM_KEYCLASS_PUBLIC_KEY) &&
1591 !(key.attribute(CSSM_KEYATTR_PUBLIC_KEY_ENCRYPT))) {
1592 inTheClear = true;
1593 }
1594 StLock<Mutex> _(common());
1595 if(!inTheClear)
1596 makeUnlocked(false);
1597
1598 // tell the cryptocore to form the key blob
1599 return common().encodeKeyCore(key, pubAcl, privAcl, inTheClear);
1600 }
1601
1602
1603 //
1604 // Given a "blobbed" key for this database, decode it into its real
1605 // key object and (re)populate its ACL.
1606 //
1607 void KeychainDatabase::decodeKey(KeyBlob *blob, CssmKey &key, void * &pubAcl, void * &privAcl)
1608 {
1609 StLock<Mutex> _(common());
1610
1611 if(!blob->isClearText())
1612 makeUnlocked(false); // we need our keys
1613
1614 common().decodeKeyCore(blob, key, pubAcl, privAcl);
1615 // memory protocol: pubAcl points into blob; privAcl was allocated
1616
1617 activity();
1618 }
1619
1620 //
1621 // Given a KeychainKey (that implicitly belongs to another keychain),
1622 // return it encoded using this keychain's operational secrets.
1623 //
1624 KeyBlob *KeychainDatabase::recodeKey(KeychainKey &oldKey)
1625 {
1626 if (mRecodingSource != &oldKey.referent<KeychainDatabase>()) {
1627 CssmError::throwMe(CSSMERR_CSP_INVALID_KEY);
1628 }
1629
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());
1634
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
1639
1640 /*
1641 * Make sure the new key is in the same cleartext/encrypted state.
1642 */
1643 bool inTheClear = false;
1644 assert(oldKey.blob());
1645 if(oldKey.blob() && oldKey.blob()->isClearText()) {
1646 /* careful....*/
1647 inTheClear = true;
1648 }
1649 KeyBlob *blob = common().encodeKeyCore(oldKey.cssmKey(), publicAcl, privateAcl, inTheClear);
1650 oldKey.acl().allocator.free(publicAcl);
1651 oldKey.acl().allocator.free(privateAcl);
1652 return blob;
1653 }
1654
1655
1656 //
1657 // Modify database parameters
1658 //
1659 void KeychainDatabase::setParameters(const DBParameters &params)
1660 {
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);
1668 }
1669
1670
1671 //
1672 // Retrieve database parameters
1673 //
1674 void KeychainDatabase::getParameters(DBParameters &params)
1675 {
1676 StLock<Mutex> _(common());
1677 makeUnlocked(false);
1678 params = common().mParams;
1679 //activity(); // getting parameters does not reset the idle timer
1680 }
1681
1682
1683 //
1684 // RIGHT NOW, database ACLs are attached to the database.
1685 // This will soon move upstairs.
1686 //
1687 SecurityServerAcl &KeychainDatabase::acl()
1688 {
1689 return *this;
1690 }
1691
1692
1693 //
1694 // Intercept ACL change requests and reset blob validity
1695 //
1696 void KeychainDatabase::instantiateAcl()
1697 {
1698 StLock<Mutex> _(common());
1699 makeUnlocked(false);
1700 }
1701
1702 void KeychainDatabase::changedAcl()
1703 {
1704 StLock<Mutex> _(common());
1705 version = 0;
1706 }
1707
1708
1709 //
1710 // Check an incoming DbBlob for basic viability
1711 //
1712 void KeychainDatabase::validateBlob(const DbBlob *blob)
1713 {
1714 // perform basic validation on the blob
1715 assert(blob);
1716 blob->validate(CSSMERR_APPLEDL_INVALID_DATABASE_BLOB);
1717 if (blob->startCryptoBlob > blob->totalLength) {
1718 CssmError::throwMe(CSSMERR_APPLEDL_INVALID_DATABASE_BLOB);
1719 }
1720 switch (blob->version()) {
1721 #if defined(COMPAT_OSX_10_0)
1722 case DbBlob::version_MacOS_10_0:
1723 break;
1724 #endif
1725 case DbBlob::version_MacOS_10_1:
1726 break;
1727 case DbBlob::version_partition:
1728 break;
1729 default:
1730 CssmError::throwMe(CSSMERR_APPLEDL_INCOMPATIBLE_DATABASE_BLOB);
1731 }
1732 }
1733
1734 //
1735 // Check if this database is currently recoding
1736 //
1737 bool KeychainDatabase::isRecoding()
1738 {
1739 secnotice("integrity", "recoding source: %p", mRecodingSource.get());
1740 return (mRecodingSource.get() != NULL || mRecoded);
1741 }
1742
1743 //
1744 // Mark ourselves as no longer recoding
1745 //
1746 void KeychainDatabase::recodeFinished()
1747 {
1748 secnotice("integrity", "recoding finished");
1749 mRecodingSource = NULL;
1750 mRecoded = false;
1751 }
1752
1753
1754 //
1755 // Debugging support
1756 //
1757 #if defined(DEBUGDUMP)
1758
1759 void KeychainDbCommon::dumpNode()
1760 {
1761 PerSession::dumpNode();
1762 uint32 sig; memcpy(&sig, &mIdentifier.signature(), sizeof(sig));
1763 Debug::dump(" %s[%8.8x]", mIdentifier.dbName(), sig);
1764 if (isLocked()) {
1765 Debug::dump(" locked");
1766 } else {
1767 time_t whenTime = time_t(when());
1768 Debug::dump(" unlocked(%24.24s/%.2g)", ctime(&whenTime),
1769 (when() - Time::now()).seconds());
1770 }
1771 Debug::dump(" params=(%u,%u)", mParams.idleTimeout, mParams.lockOnSleep);
1772 }
1773
1774 void KeychainDatabase::dumpNode()
1775 {
1776 PerProcess::dumpNode();
1777 Debug::dump(" %s vers=%u",
1778 mValidData ? " data" : " nodata", version);
1779 if (mBlob) {
1780 uint32 sig; memcpy(&sig, &mBlob->randomSignature, sizeof(sig));
1781 Debug::dump(" blob=%p[%8.8x]", mBlob, sig);
1782 } else {
1783 Debug::dump(" noblob");
1784 }
1785 }
1786
1787 #endif //DEBUGDUMP
1788
1789
1790 //
1791 // DbCommon basic features
1792 //
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)
1796 {
1797 // match existing DbGlobal or create a new one
1798 {
1799 Server &server = Server::active();
1800 StLock<Mutex> _(server);
1801 if (KeychainDbGlobal *dbglobal =
1802 server.findFirst<KeychainDbGlobal, const DbIdentifier &>(&KeychainDbGlobal::identifier, identifier())) {
1803 parent(*dbglobal);
1804 secinfo("KCdb", "%p linking to existing DbGlobal %p", this, dbglobal);
1805 } else {
1806 // DbGlobal not present; make a new one
1807 parent(*new KeychainDbGlobal(identifier()));
1808 secinfo("KCdb", "%p linking to new DbGlobal %p", this, &global());
1809 }
1810
1811 // link lifetime to the Session
1812 session().addReference(*this);
1813
1814 if (strcasestr(id.dbName(), "login.keychain") != NULL) {
1815 mLoginKeychain = true;
1816 }
1817 }
1818 }
1819
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);
1825 }
1826 }
1827 }
1828
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)
1832 {
1833 cloneFrom(toClone);
1834
1835 {
1836 Server &server = Server::active();
1837 StLock<Mutex> _(server);
1838 if (KeychainDbGlobal *dbglobal =
1839 server.findFirst<KeychainDbGlobal, const DbIdentifier &>(&KeychainDbGlobal::identifier, identifier())) {
1840 parent(*dbglobal);
1841 secinfo("KCdb", "%p linking to existing DbGlobal %p", this, dbglobal);
1842 } else {
1843 // DbGlobal not present; make a new one
1844 parent(*new KeychainDbGlobal(identifier()));
1845 secinfo("KCdb", "%p linking to new DbGlobal %p", this, &global());
1846 }
1847 session().addReference(*this);
1848 }
1849 }
1850
1851 KeychainDbCommon::~KeychainDbCommon()
1852 {
1853 secinfo("KCdb", "releasing keychain %p %s", this, (char*)this->dbName());
1854
1855 // explicitly unschedule ourselves
1856 Server::active().clearTimer(this);
1857 if (mLoginKeychain) {
1858 session().keybagClearState(session_keybag_unlocked);
1859 }
1860 // remove ourselves from mCommonSet
1861 kill();
1862 }
1863
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;
1872
1873 DatabaseCryptoCore::initializeFrom(toClone, requestedVersion);
1874 }
1875
1876 void KeychainDbCommon::kill()
1877 {
1878 StReadWriteLock _(mRWCommonLock, StReadWriteLock::Write);
1879 mCommonSet.erase(this);
1880 }
1881
1882 KeychainDbGlobal &KeychainDbCommon::global() const
1883 {
1884 return parent<KeychainDbGlobal>();
1885 }
1886
1887
1888 void KeychainDbCommon::select()
1889 { this->ref(); }
1890
1891 void KeychainDbCommon::unselect()
1892 { this->unref(); }
1893
1894
1895
1896 void KeychainDbCommon::makeNewSecrets()
1897 {
1898 // we already have a master key (right?)
1899 assert(hasMaster());
1900
1901 // tell crypto core to generate the use keys
1902 DatabaseCryptoCore::generateNewSecrets();
1903
1904 // we're now officially "unlocked"; set the timer
1905 setUnlocked();
1906 }
1907
1908
1909 //
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.
1916 //
1917 bool KeychainDbCommon::unlockDb(DbBlob *blob, void **privateAclBlob)
1918 {
1919 try {
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);
1925 } catch (...) {
1926 secinfo("KCdb", "%p unlock failed", this);
1927 return false;
1928 }
1929
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
1935 }
1936
1937 bool isLocked = mIsLocked;
1938
1939 setUnlocked(); // mark unlocked
1940
1941 if (isLocked) {
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());
1945 }
1946 return true;
1947 }
1948
1949 void KeychainDbCommon::setUnlocked()
1950 {
1951 session().addReference(*this); // active/held
1952 mIsLocked = false; // mark unlocked
1953 activity(); // set timeout timer
1954 }
1955
1956
1957 void KeychainDbCommon::lockDb()
1958 {
1959 {
1960 StLock<Mutex> _(*this);
1961 if (!isLocked()) {
1962 DatabaseCryptoCore::invalidate();
1963 notify(kNotificationEventLocked);
1964 secinfo("KCdb", "locking keychain %p %s", this, (char*)this->dbName());
1965 Server::active().clearTimer(this);
1966
1967 mIsLocked = true; // mark locked
1968
1969 // this call may destroy us if we have no databases anymore
1970 session().removeReference(*this);
1971 }
1972 }
1973 }
1974
1975
1976 DbBlob *KeychainDbCommon::encode(KeychainDatabase &db)
1977 {
1978 assert(!isLocked()); // must have been unlocked by caller
1979
1980 // export database ACL to blob form
1981 CssmData pubAcl, privAcl;
1982 db.acl().exportBlob(pubAcl, privAcl);
1983
1984 // tell the cryptocore to form the blob
1985 DbBlob form;
1986 form.randomSignature = identifier();
1987 form.sequence = sequence;
1988 form.params = mParams;
1989 h2ni(form.params.idleTimeout);
1990
1991 assert(hasMaster());
1992 DbBlob *blob = encodeCore(form, pubAcl, privAcl);
1993
1994 // clean up and go
1995 db.acl().allocator.free(pubAcl);
1996 db.acl().allocator.free(privAcl);
1997 return blob;
1998 }
1999
2000
2001 //
2002 // Perform deferred lock processing for a database.
2003 //
2004 void KeychainDbCommon::action()
2005 {
2006 secinfo("KCdb", "common %s(%p) locked by timer", dbName(), this);
2007 lockDb();
2008 }
2009
2010 void KeychainDbCommon::activity()
2011 {
2012 if (!isLocked()) {
2013 secinfo("KCdb", "setting DbCommon %p timer to %d",
2014 this, int(mParams.idleTimeout));
2015 Server::active().setTimer(this, Time::Interval(int(mParams.idleTimeout)));
2016 }
2017 }
2018
2019 void KeychainDbCommon::sleepProcessing()
2020 {
2021 secinfo("KCdb", "common %s(%p) sleep-lock processing", dbName(), this);
2022 if (mParams.lockOnSleep && !isDefaultSystemKeychain()) {
2023 StLock<Mutex> _(*this);
2024 lockDb();
2025 }
2026 }
2027
2028 void KeychainDbCommon::lockProcessing()
2029 {
2030 lockDb();
2031 }
2032
2033
2034 //
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.
2038 //
2039 bool KeychainDbCommon::belongsToSystem() const
2040 {
2041 if (const char *name = this->dbName())
2042 return !strncmp(name, "/Library/Keychains/", 19);
2043 return false;
2044 }
2045
2046 bool KeychainDbCommon::isDefaultSystemKeychain() const
2047 {
2048 // /Library/Keychains/System.keychain (34)
2049 if (const char *name = this->dbName())
2050 return !strncmp(name, "/Library/Keychains/System.keychain", 34);
2051 return false;
2052 }
2053
2054 //
2055 // Keychain global objects
2056 //
2057 KeychainDbGlobal::KeychainDbGlobal(const DbIdentifier &id)
2058 : mIdentifier(id)
2059 {
2060 }
2061
2062 KeychainDbGlobal::~KeychainDbGlobal()
2063 {
2064 secinfo("KCdb", "DbGlobal %p destroyed", this);
2065 }