2 * Copyright (c) 2000-2001 Apple Computer, Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
26 // tokendatabase - software database container implementation.
28 #include "tokendatabase.h"
30 #include "tokenaccess.h"
33 #include "localkey.h" // to retrieve local raw keys
34 #include <security_cdsa_client/wrapkey.h>
38 // Construct a TokenDbCommon
40 TokenDbCommon::TokenDbCommon(Session
&ssn
, Token
&tk
, const char *name
)
41 : DbCommon(ssn
), mDbName(name
? name
: ""), mResetLevel(0)
46 Token
&TokenDbCommon::token() const
48 return parent
<Token
>();
51 const std::string
&TokenDbCommon::dbName() const
53 return token().printName();
58 // A TokenDbCommon holds per-session adornments for the ACL machine
60 Adornable
&TokenDbCommon::store()
62 StLock
<Mutex
> _(*this);
64 // if this is the first one, hook for lifetime
65 if (mAdornments
.empty()) {
66 session().addReference(*this); // hold and slave to SSN lifetime
67 token().addCommon(*this); // register with Token
70 // return our (now active) adornments
74 void TokenDbCommon::resetAcls()
76 StLock
<Mutex
> _(*this);
77 if (!mAdornments
.empty()) {
78 mAdornments
.clearAdornments(); // clear ACL state
79 session().removeReference(*this); // unhook from SSN
80 token().removeCommon(*this); // unregister from Token
86 // Process (our part of) a "lock all" request.
87 // Smartcard tokens interpret a "lock" as a forced card reset, transmitted
88 // to tokend as an authenticate request.
89 // @@@ Virtual reset for multi-session tokens. Right now, we're using the sledge hammer.
91 void TokenDbCommon::lockProcessing()
93 Access
access(token());
94 access().authenticate(CSSM_DB_ACCESS_RESET
, NULL
);
99 // Construct a TokenDatabase given subservice information.
100 // We are currently ignoring the 'name' argument.
102 TokenDatabase::TokenDatabase(uint32 ssid
, Process
&proc
,
103 const char *name
, const AccessCredentials
*cred
)
106 // locate Token object
107 RefPointer
<Token
> token
= Token::find(ssid
);
109 Session
&session
= process().session();
110 StLock
<Mutex
> _(session
);
111 if (TokenDbCommon
*dbcom
= session
.findFirst
<TokenDbCommon
, uint32
>(&TokenDbCommon::subservice
, ssid
)) {
113 secdebug("tokendb", "open tokendb %p(%ld) at known common %p",
114 this, subservice(), dbcom
);
116 // DbCommon not present; make a new one
117 parent(*new TokenDbCommon(proc
.session(), *token
, name
));
118 secdebug("tokendb", "open tokendb %p(%ld) with new common %p",
119 this, subservice(), &common());
121 mOpenCreds
= copy(cred
, Allocator::standard());
122 proc
.addReference(*this);
125 TokenDatabase::~TokenDatabase()
127 Allocator::standard().free(mOpenCreds
);
132 // Basic Database virtual implementations
134 TokenDbCommon
&TokenDatabase::common() const
136 return parent
<TokenDbCommon
>();
139 TokenDaemon
&TokenDatabase::tokend()
141 return common().token().tokend();
144 const char *TokenDatabase::dbName() const
146 return common().dbName().c_str();
149 bool TokenDatabase::transient() const
151 //@@@ let tokend decide? Are there any secure transient keystores?
156 SecurityServerAcl
&TokenDatabase::acl()
161 bool TokenDatabase::isLocked() const
163 Access
access(token());
164 return access().isLocked();
169 // TokenDatabases implement the dbName-setting function.
170 // This sets the print name of the token, which is persistently
171 // stored in the token cache. So this is a de-facto rename of
172 // the token, at least on this system.
174 void TokenDatabase::dbName(const char *name
)
176 CssmError::throwMe(CSSM_ERRCODE_FUNCTION_NOT_IMPLEMENTED
);
181 // Given a key handle and CssmKey returned from tokend, create a Key representing
182 // it. This takes care of raw returns by turning them into keys of the process's
183 // local transient store.
185 RefPointer
<Key
> TokenDatabase::makeKey(KeyHandle hKey
, const CssmKey
*key
,
186 const AclEntryPrototype
*owner
)
188 switch (key
->blobType()) {
189 case CSSM_KEYBLOB_REFERENCE
:
190 return new TokenKey(*this, hKey
, key
->header());
191 case CSSM_KEYBLOB_RAW
:
192 return process().makeTemporaryKey(*key
, 0, owner
);
194 CssmError::throwMe(CSSM_ERRCODE_INTERNAL_ERROR
); // bad key return from tokend
196 //@@@ Server::releaseWhenDone(key);
201 // Adjust key attributes for newly created keys
203 static CSSM_KEYATTR_FLAGS
modattrs(CSSM_KEYATTR_FLAGS attrs
)
205 static const CSSM_KEYATTR_FLAGS CSSM_KEYATTR_RETURN_FLAGS
= 0xff000000;
206 switch (attrs
& CSSM_KEYATTR_RETURN_FLAGS
) {
207 case CSSM_KEYATTR_RETURN_REF
:
208 case CSSM_KEYATTR_RETURN_DATA
:
209 break; // as requested
210 case CSSM_KEYATTR_RETURN_NONE
:
211 CssmError::throwMe(CSSMERR_CSP_UNSUPPORTED_KEYATTR_MASK
);
212 case CSSM_KEYATTR_RETURN_DEFAULT
:
213 if (attrs
& CSSM_KEYATTR_PERMANENT
)
214 attrs
|= CSSM_KEYATTR_RETURN_REF
;
216 attrs
|= CSSM_KEYATTR_RETURN_DATA
;
224 // TokenDatabases support remote secret validation by sending a secret
225 // (aka passphrase et al) to tokend for processing.
227 bool TokenDatabase::validateSecret(const AclSubject
*subject
, const AccessCredentials
*cred
)
229 secdebug("tokendb", "%p attempting remote validation", this);
231 Access
access(token());
232 // @@@ Use cached mode
233 access().authenticate(CSSM_DB_ACCESS_READ
, cred
);
234 secdebug("tokendb", "%p remote validation successful", this);
238 secdebug("tokendb", "%p remote validation failed", this);
240 throw; // try not to mask error
248 void TokenDatabase::queryKeySizeInBits(Key
&key
, CssmKeySize
&result
)
250 Access
access(token());
253 access().queryKeySizeInBits(myKey(key
).tokenHandle(), result
);
259 // Signatures and MACs
261 void TokenDatabase::generateSignature(const Context
&context
, Key
&key
,
262 CSSM_ALGORITHMS signOnlyAlgorithm
, const CssmData
&data
, CssmData
&signature
)
264 Access
access(token(), key
);
266 key
.validate(CSSM_ACL_AUTHORIZATION_SIGN
, context
);
268 access().generateSignature(context
, myKey(key
).tokenHandle(), data
, signature
, signOnlyAlgorithm
);
273 void TokenDatabase::verifySignature(const Context
&context
, Key
&key
,
274 CSSM_ALGORITHMS verifyOnlyAlgorithm
, const CssmData
&data
, const CssmData
&signature
)
276 Access
access(token(), key
);
279 access().verifySignature(context
, myKey(key
).tokenHandle(), data
, signature
, verifyOnlyAlgorithm
);
283 void TokenDatabase::generateMac(const Context
&context
, Key
&key
,
284 const CssmData
&data
, CssmData
&mac
)
286 Access
access(token());
288 key
.validate(CSSM_ACL_AUTHORIZATION_MAC
, context
);
290 access().generateMac(context
, myKey(key
).tokenHandle(), data
, mac
);
294 void TokenDatabase::verifyMac(const Context
&context
, Key
&key
,
295 const CssmData
&data
, const CssmData
&mac
)
297 Access
access(token());
299 key
.validate(CSSM_ACL_AUTHORIZATION_MAC
, context
);
301 access().verifyMac(context
, myKey(key
).tokenHandle(), data
, mac
);
307 // Encryption/decryption
309 void TokenDatabase::encrypt(const Context
&context
, Key
&key
,
310 const CssmData
&clear
, CssmData
&cipher
)
312 Access
access(token());
314 key
.validate(CSSM_ACL_AUTHORIZATION_ENCRYPT
, context
);
316 access().encrypt(context
, myKey(key
).tokenHandle(), clear
, cipher
);
321 void TokenDatabase::decrypt(const Context
&context
, Key
&key
,
322 const CssmData
&cipher
, CssmData
&clear
)
324 Access
access(token());
326 key
.validate(CSSM_ACL_AUTHORIZATION_DECRYPT
, context
);
328 access().decrypt(context
, myKey(key
).tokenHandle(), cipher
, clear
);
334 // Key generation and derivation.
335 // Currently, we consider symmetric key generation to be fast, but
336 // asymmetric key generation to be (potentially) slow.
338 void TokenDatabase::generateKey(const Context
&context
,
339 const AccessCredentials
*cred
, const AclEntryPrototype
*owner
,
340 CSSM_KEYUSE usage
, CSSM_KEYATTR_FLAGS attrs
, RefPointer
<Key
> &newKey
)
342 Access
access(token());
347 access().generateKey(context
, cred
, owner
, usage
, modattrs(attrs
), hKey
, result
);
348 newKey
= makeKey(hKey
, result
, owner
);
352 void TokenDatabase::generateKey(const Context
&context
,
353 const AccessCredentials
*cred
, const AclEntryPrototype
*owner
,
354 CSSM_KEYUSE pubUsage
, CSSM_KEYATTR_FLAGS pubAttrs
,
355 CSSM_KEYUSE privUsage
, CSSM_KEYATTR_FLAGS privAttrs
,
356 RefPointer
<Key
> &publicKey
, RefPointer
<Key
> &privateKey
)
358 Access
access(token());
361 KeyHandle hPrivate
, hPublic
;
362 CssmKey
*privKey
, *pubKey
;
363 access().generateKey(context
, cred
, owner
,
364 pubUsage
, modattrs(pubAttrs
), privUsage
, modattrs(privAttrs
),
365 hPublic
, pubKey
, hPrivate
, privKey
);
366 publicKey
= makeKey(hPublic
, pubKey
, owner
);
367 privateKey
= makeKey(hPrivate
, privKey
, owner
);
373 // Key wrapping and unwrapping.
374 // Note that the key argument (the key in the context) is optional because of the special
375 // case of "cleartext" (null algorithm) wrapping for import/export.
377 void TokenDatabase::wrapKey(const Context
&context
, const AccessCredentials
*cred
,
378 Key
*wrappingKey
, Key
&subjectKey
,
379 const CssmData
&descriptiveData
, CssmKey
&wrappedKey
)
381 Access
access(token());
382 InputKey
cWrappingKey(wrappingKey
);
383 InputKey
cSubjectKey(subjectKey
);
385 subjectKey
.validate(context
.algorithm() == CSSM_ALGID_NONE
?
386 CSSM_ACL_AUTHORIZATION_EXPORT_CLEAR
: CSSM_ACL_AUTHORIZATION_EXPORT_WRAPPED
,
389 wrappingKey
->validate(CSSM_ACL_AUTHORIZATION_ENCRYPT
, context
);
391 CssmKey
*rWrappedKey
;
392 access().wrapKey(context
, cred
,
393 cWrappingKey
, cWrappingKey
, cSubjectKey
, cSubjectKey
,
394 descriptiveData
, rWrappedKey
);
395 wrappedKey
= *rWrappedKey
;
396 //@@@ ownership of wrappedKey.keyData() ??
400 void TokenDatabase::unwrapKey(const Context
&context
,
401 const AccessCredentials
*cred
, const AclEntryPrototype
*owner
,
402 Key
*wrappingKey
, Key
*publicKey
, CSSM_KEYUSE usage
, CSSM_KEYATTR_FLAGS attrs
,
403 const CssmKey wrappedKey
, RefPointer
<Key
> &unwrappedKey
, CssmData
&descriptiveData
)
405 Access
access(token());
406 InputKey
cWrappingKey(wrappingKey
);
407 InputKey
cPublicKey(publicKey
);
410 wrappingKey
->validate(CSSM_ACL_AUTHORIZATION_DECRYPT
, context
);
411 // we are not checking access on the public key, if any
415 access().unwrapKey(context
, cred
, owner
,
416 cWrappingKey
, cWrappingKey
, cPublicKey
, cPublicKey
,
417 wrappedKey
, usage
, modattrs(attrs
), descriptiveData
, hKey
, result
);
418 unwrappedKey
= makeKey(hKey
, result
, owner
);
426 void TokenDatabase::deriveKey(const Context
&context
, Key
*sourceKey
,
427 const AccessCredentials
*cred
, const AclEntryPrototype
*owner
,
428 CssmData
*param
, CSSM_KEYUSE usage
, CSSM_KEYATTR_FLAGS attrs
, RefPointer
<Key
> &derivedKey
)
430 Access
access(token());
431 InputKey
cSourceKey(sourceKey
);
434 sourceKey
->validate(CSSM_ACL_AUTHORIZATION_DERIVE
, cred
);
438 CssmData params
= param
? *param
: CssmData();
439 access().deriveKey(noDb
, context
,
440 cSourceKey
, cSourceKey
,
441 usage
, modattrs(attrs
), params
, cred
, owner
,
445 //@@@ leak? what's the rule here?
447 derivedKey
= makeKey(hKey
, result
, owner
);
453 // Miscellaneous CSSM functions
455 void TokenDatabase::getOutputSize(const Context
&context
, Key
&key
,
456 uint32 inputSize
, bool encrypt
, uint32
&result
)
458 Access
access(token());
461 access().getOutputSize(context
, myKey(key
).tokenHandle(), inputSize
, encrypt
, result
);
467 // (Re-)Authenticate the database.
468 // We use dbAuthenticate as the catch-all "do something about authentication" call.
470 void TokenDatabase::authenticate(CSSM_DB_ACCESS_TYPE mode
, const AccessCredentials
*cred
)
472 Access
access(token());
475 if (mode
!= CSSM_DB_ACCESS_RESET
&& cred
) {
476 secdebug("tokendb", "%p authenticate calling validate", this);
478 if (sscanf(cred
->EntryTag
, "PIN%d", &pin
) == 1)
479 return validate(CSSM_ACL_AUTHORIZATION_PREAUTH(pin
), cred
);
482 access().authenticate(mode
, cred
);
484 case CSSM_DB_ACCESS_RESET
:
485 // this mode is known to trigger "lockdown" (i.e. reset)
486 common().resetAcls();
490 // no idea what that did to the token;
491 // But let's remember the new creds for our own sake.
492 AccessCredentials
*newCred
= copy(cred
, Allocator::standard());
493 Allocator::standard().free(mOpenCreds
);
494 mOpenCreds
= newCred
;
502 // Data access interface.
504 // Note that the attribute vectors are passed between our two IPC interfaces
505 // as relocated but contiguous memory blocks (to avoid an extra copy). This means
506 // you can read them at will, but can't change them in transit unless you're
507 // willing to repack them right here.
509 void TokenDatabase::findFirst(const CssmQuery
&query
,
510 CssmDbRecordAttributeData
*inAttributes
, mach_msg_type_number_t inAttributesLength
,
511 CssmData
*data
, RefPointer
<Key
> &key
,
512 RefPointer
<Database::Search
> &rSearch
, RefPointer
<Database::Record
> &rRecord
,
513 CssmDbRecordAttributeData
* &outAttributes
, mach_msg_type_number_t
&outAttributesLength
)
515 Access
access(token());
516 RefPointer
<Search
> search
= new Search(*this);
517 RefPointer
<Record
> record
= new Record(*this);
519 KeyHandle hKey
= noKey
;
520 validate(CSSM_ACL_AUTHORIZATION_DB_READ
, openCreds());
522 record
->tokenHandle() = access().Tokend::ClientSession::findFirst(query
,
523 inAttributes
, inAttributesLength
, search
->tokenHandle(), NULL
, hKey
,
524 outAttributes
, outAttributesLength
);
525 if (!record
->tokenHandle()) { // no match (but no other error)
526 rRecord
= NULL
; // return null record
531 record
->validate(CSSM_ACL_AUTHORIZATION_DB_READ
, openCreds());
532 CssmDbRecordAttributeData
*noAttributes
;
533 mach_msg_type_number_t noAttributesLength
;
534 access().Tokend::ClientSession::findRecordHandle(record
->tokenHandle(),
535 NULL
, 0, data
, hKey
, noAttributes
, noAttributesLength
);
536 if (hKey
) { // tokend returned a key reference & data
537 CssmKey
&keyForm
= *data
->interpretedAs
<CssmKey
>(CSSMERR_CSP_INVALID_KEY
);
538 key
= new TokenKey(*this, hKey
, keyForm
.header());
541 rSearch
= search
->commit();
542 rRecord
= record
->commit();
546 void TokenDatabase::findNext(Database::Search
*rSearch
,
547 CssmDbRecordAttributeData
*inAttributes
, mach_msg_type_number_t inAttributesLength
,
548 CssmData
*data
, RefPointer
<Key
> &key
, RefPointer
<Database::Record
> &rRecord
,
549 CssmDbRecordAttributeData
* &outAttributes
, mach_msg_type_number_t
&outAttributesLength
)
551 Access
access(token());
552 RefPointer
<Record
> record
= new Record(*this);
553 Search
*search
= safe_cast
<Search
*>(rSearch
);
555 KeyHandle hKey
= noKey
;
556 validate(CSSM_ACL_AUTHORIZATION_DB_READ
, openCreds());
558 record
->tokenHandle() = access().Tokend::ClientSession::findNext(
559 search
->tokenHandle(), inAttributes
, inAttributesLength
,
560 NULL
, hKey
, outAttributes
, outAttributesLength
);
561 if (!record
->tokenHandle()) { // no more matches
562 releaseSearch(*search
); // release search handle (consumed by EOD)
563 rRecord
= NULL
; // return null record
568 record
->validate(CSSM_ACL_AUTHORIZATION_DB_READ
, openCreds());
569 CssmDbRecordAttributeData
*noAttributes
;
570 mach_msg_type_number_t noAttributesLength
;
571 access().Tokend::ClientSession::findRecordHandle(record
->tokenHandle(),
572 NULL
, 0, data
, hKey
, noAttributes
, noAttributesLength
);
573 if (hKey
) { // tokend returned a key reference & data
574 CssmKey
&keyForm
= *data
->interpretedAs
<CssmKey
>(CSSMERR_CSP_INVALID_KEY
);
575 key
= new TokenKey(*this, hKey
, keyForm
.header());
578 rRecord
= record
->commit();
582 void TokenDatabase::findRecordHandle(Database::Record
*rRecord
,
583 CssmDbRecordAttributeData
*inAttributes
, mach_msg_type_number_t inAttributesLength
,
584 CssmData
*data
, RefPointer
<Key
> &key
,
585 CssmDbRecordAttributeData
* &outAttributes
, mach_msg_type_number_t
&outAttributesLength
)
587 Access
access(token());
588 Record
*record
= safe_cast
<Record
*>(rRecord
);
591 KeyHandle hKey
= noKey
;
592 validate(CSSM_ACL_AUTHORIZATION_DB_READ
, openCreds());
594 record
->validate(CSSM_ACL_AUTHORIZATION_DB_READ
, openCreds());
596 access().Tokend::ClientSession::findRecordHandle(record
->tokenHandle(),
597 inAttributes
, inAttributesLength
, data
, hKey
, outAttributes
, outAttributesLength
);
599 if (hKey
!= noKey
&& data
) { // tokend returned a key reference & data
600 CssmKey
&keyForm
= *data
->interpretedAs
<CssmKey
>(CSSMERR_CSP_INVALID_KEY
);
601 key
= new TokenKey(*this, hKey
, keyForm
.header());
606 void TokenDatabase::insertRecord(CSSM_DB_RECORDTYPE recordType
,
607 const CssmDbRecordAttributeData
*attributes
, mach_msg_type_number_t attributesLength
,
608 const CssmData
&data
, RefPointer
<Database::Record
> &rRecord
)
610 Access
access(token());
611 RefPointer
<Record
> record
= new Record(*this);
614 validate(CSSM_ACL_AUTHORIZATION_DB_INSERT
, openCreds());
616 access().Tokend::ClientSession::insertRecord(recordType
,
617 attributes
, attributesLength
, data
, record
->tokenHandle());
622 void TokenDatabase::modifyRecord(CSSM_DB_RECORDTYPE recordType
, Record
*rRecord
,
623 const CssmDbRecordAttributeData
*attributes
, mach_msg_type_number_t attributesLength
,
624 const CssmData
*data
, CSSM_DB_MODIFY_MODE modifyMode
)
626 Access
access(token());
627 Record
*record
= safe_cast
<Record
*>(rRecord
);
630 validate(CSSM_ACL_AUTHORIZATION_DB_MODIFY
, openCreds());
631 record
->validate(CSSM_ACL_AUTHORIZATION_DB_MODIFY
, openCreds());
633 access().Tokend::ClientSession::modifyRecord(recordType
,
634 record
->tokenHandle(), attributes
, attributesLength
, data
, modifyMode
);
638 void TokenDatabase::deleteRecord(Database::Record
*rRecord
)
640 Access
access(token(), *this);
641 Record
*record
= safe_cast
<Record
*>(rRecord
);
644 validate(CSSM_ACL_AUTHORIZATION_DB_DELETE
, openCreds());
645 record
->validate(CSSM_ACL_AUTHORIZATION_DB_DELETE
, openCreds());
647 access().Tokend::ClientSession::deleteRecord(record
->tokenHandle());
653 // Record/Search object handling
655 TokenDatabase::Search::~Search()
659 database().token().tokend().Tokend::ClientSession::releaseSearch(mHandle
);
661 secdebug("tokendb", "%p release search handle %ld threw (ignored)",
666 TokenDatabase::Record::~Record()
670 database().token().tokend().Tokend::ClientSession::releaseRecord(mHandle
);
672 secdebug("tokendb", "%p release record handle %ld threw (ignored)",
679 // TokenAcl personality of Record
681 AclKind
TokenDatabase::Record::aclKind() const
686 Token
&TokenDatabase::Record::token()
688 return safer_cast
<TokenDatabase
&>(database()).token();
691 GenericHandle
TokenDatabase::Record::tokenHandle() const
693 return Handler::tokenHandle();
698 // Local utility classes
700 void TokenDatabase::InputKey::setup(Key
*key
)
702 if (TokenKey
*myKey
= dynamic_cast<TokenKey
*>(key
)) {
704 mKeyHandle
= myKey
->tokenHandle();
706 } else if (LocalKey
*hisKey
= dynamic_cast<LocalKey
*>(key
)) {
707 // a local key - turn into raw form
708 CssmClient::WrapKey
wrap(Server::csp(), CSSM_ALGID_NONE
);
709 wrap(hisKey
->cssmKey(), mKey
);
720 TokenDatabase::InputKey::~InputKey()
723 //@@@ Server::csp().freeKey(mKey) ??
724 Server::csp()->allocator().free(mKey
.keyData());