1/*
2 * Copyright (c) 2004 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// defaultcreds - default computations for keychain open credentials
26//
27#include "Keychains.h"
28#include "defaultcreds.h"
29#include "StorageManager.h"
30#include "Globals.h"
31#include "KCCursor.h"
32#include <security_cdsa_utilities/Schema.h>
33#include <algorithm>
34
35
36namespace Security {
37namespace KeychainCore {
38
39using namespace CssmClient;
40
41
42DefaultCredentials::DefaultCredentials(KeychainImpl* kcImpl, Allocator &alloc)
43	: TrackingAllocator(alloc), AutoCredentials(static_cast<TrackingAllocator&>(*this)),
44	  mMade(false), mKeychainImpl (kcImpl)
45{
46}
47
48
49void DefaultCredentials::clear()
50{
51	TrackingAllocator::reset();
52	mNeededItems.clear();
53	mMade = false;
54}
55
56
57//
58// The main driver.
59// This scans a database for referral records and forms corresponding
60// credentials to trigger unlocks.
61// Returns true if any valid unlock credentials were found; false otherwise.
62// Only throws if the database is messed up.
63//
64bool DefaultCredentials::operator () (Db database)
65{
66	if (!mMade) {
67		try {
68			// before we do anything else, see if we have a relation in the database of the appropriate type
69			KeychainSchema keychainSchema = mKeychainImpl->keychainSchema();
70			if (keychainSchema->hasRecordType(UnlockReferralRecord::recordType))
71			{
72				clear();
73				Table<UnlockReferralRecord> referrals(database);
74				for (Table<UnlockReferralRecord>::iterator it = referrals.begin(); it != referrals.end(); it++) {
75					switch ((*it)->type()) {
76					case CSSM_APPLE_UNLOCK_TYPE_KEY_DIRECT:
77					case CSSM_APPLE_UNLOCK_TYPE_WRAPPED_PRIVATE:
78						keyReferral(**it);
79						break;
80					default:
81						secdebug("kcreferral", "referral type %lu (to %s) not supported",
82							(unsigned long)(*it)->type(), (*it)->dbName().c_str());
83						break;
84					}
85				}
86			}
87			secdebug("kcreferral", "%lu samples generated", (unsigned long)size());
88		} catch (...) {
89			secdebug("kcreferral", "exception setting default credentials for %s; using standard value", database->name());
90		}
91		mMade = true;
92	}
93
94	return size() > 0;	// got credentials?
95}
96
97
98//
99// Process a single referral record. This will handle all known types
100// of referrals.
101//
102void DefaultCredentials::keyReferral(const UnlockReferralRecord &ref)
103{
104	secdebug("kcreferral", "processing type %ld referral to %s",
105		(long)ref.type(), ref.dbName().c_str());
106	DLDbIdentifier identifier(ref.dbName().c_str(), ref.dbGuid(), ref.dbSSID(), ref.dbSSType());
107
108	// first, try the keychain indicated
109	try {
110		KeychainList list;
111		list.push_back(globals().storageManager.keychain(identifier));
112		if (unlockKey(ref, list))	// try just this database...
113			return;						// ... bingo!
114	} catch (...) { }
115
116	// try the entire search list (just in case)
117	try {
118		secdebug("kcreferral", "no joy with %s; trying the entire keychain list for guid %s",
119			ref.dbName().c_str(), ref.dbGuid().toString().c_str());
120		unlockKey(ref, fallbackSearchList(identifier));
121		return;
122	} catch (...) { }
123	secdebug("kcreferral", "no luck at all; we'll skip this record");
124}
125
126
127bool DefaultCredentials::unlockKey(const UnlockReferralRecord &ref, const KeychainList &list)
128{
129	bool foundSome = false;
130	try {
131		// form the query
132		SecKeychainAttribute attributes[1] = {
133			{ kSecKeyLabel, (UInt32)ref.keyLabel().length(), ref.keyLabel().data() }
134		};
135		SecKeychainAttributeList search = { 1, attributes };
136		CSSM_DB_RECORDTYPE recordType =
137			(ref.type() == CSSM_APPLE_UNLOCK_TYPE_KEY_DIRECT) ?
138				CSSM_DL_DB_RECORD_SYMMETRIC_KEY : CSSM_DL_DB_RECORD_PRIVATE_KEY;
139		KCCursor cursor(list, recordType, &search);
140
141		Item keyItem;
142		while (cursor->next(keyItem)) {
143			secdebug("kcreferral", "located source key in %s", keyItem->keychain()->name());
144
145			// get a reference to the key in the provider keychain
146			CssmClient::Key key = dynamic_cast<KeyItem &>(*keyItem).key();
147			const CssmKey &masterKey = key;
148
149			// get the CSP handle FOR THE UNLOCKING KEY'S KEYCHAIN
150			CSSM_CSP_HANDLE cspHandle = key->csp()->handle();
151
152			// (a)symmetric-key form: KCLOCK, (A)SYMMETRIC_KEY, cspHandle, masterKey
153			// Note that the last list element ("ref") is doing an implicit cast to a
154			// CssmData, which passes the data portion of the UnlockReferralRecord
155			append(TypedList(allocator, CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK,
156				new(allocator) ListElement((recordType==CSSM_DL_DB_RECORD_SYMMETRIC_KEY)?
157					CSSM_WORDID_SYMMETRIC_KEY:CSSM_WORDID_ASYMMETRIC_KEY),
158				new(allocator) ListElement(allocator, CssmData::wrap(cspHandle)),
159				new(allocator) ListElement(allocator, CssmData::wrap(masterKey)),
160				new(allocator) ListElement(allocator, ref.get())
161				));
162
163			// let's make sure everything we need stays around
164			mNeededItems.insert(keyItem);
165			foundSome = true;
166		}
167	} catch (...) {
168		// (ignore it)
169	}
170	return foundSome;
171}
172
173
174//
175// Take the official keychain search list, and return those keychains whose
176// module Guid matches the one given. Essentially, this focuses the search list
177// to a particular type of keychain.
178//
179struct NotGuid {
180	NotGuid(const Guid &g) : guid(g) { }
181	const Guid &guid;
182	bool operator () (Keychain kc) { return kc->database()->dl()->guid() != guid; }
183};
184
185DefaultCredentials::KeychainList DefaultCredentials::fallbackSearchList(const DLDbIdentifier &ident)
186{
187	KeychainList list;
188	globals().storageManager.getSearchList(list);
189	list.erase(remove_if(list.begin(), list.end(), NotGuid(ident.ssuid().guid())), list.end());
190	return list;
191}
192
193
194}	// namespace KeychainCore
195}	// namespace Security
196