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)
43 secdebug("tokendb", "creating tokendbcommon %p: with token %p", this, &tk
);
47 TokenDbCommon::~TokenDbCommon()
49 secdebug("tokendb", "destroying tokendbcommon %p", this);
50 token().removeCommon(*this); // unregister from Token
53 Token
&TokenDbCommon::token() const
55 return parent
<Token
>();
58 const std::string
&TokenDbCommon::dbName() const
60 return token().printName();
65 // A TokenDbCommon holds per-session adornments for the ACL machine
67 Adornable
&TokenDbCommon::store()
69 StLock
<Mutex
> _(*this);
71 // if this is the first one, hook for lifetime
72 if (mAdornments
.empty()) {
73 session().addReference(*this); // hold and slave to SSN lifetime
74 token().addCommon(*this); // register with Token
77 // return our (now active) adornments
81 void TokenDbCommon::resetAcls()
83 StLock
<Mutex
> _(*this);
84 if (!mAdornments
.empty()) {
85 mAdornments
.clearAdornments(); // clear ACL state
86 session().removeReference(*this); // unhook from SSN
88 token().removeCommon(*this); // unregister from Token
91 // Send out a "keychain" notification for this database
93 void TokenDbCommon::notify(NotificationEvent event
)
95 DbCommon::notify(event
, DLDbIdentifier(dbName().c_str(), gGuidAppleSdCSPDL
,
96 subservice(), CSSM_SERVICE_DL
| CSSM_SERVICE_CSP
));
101 // Process (our part of) a "lock all" request.
102 // Smartcard tokens interpret a "lock" as a forced card reset, transmitted
103 // to tokend as an authenticate request.
104 // @@@ Virtual reset for multi-session tokens. Right now, we're using the sledge hammer.
106 void TokenDbCommon::lockProcessing()
108 Access
access(token());
109 access().authenticate(CSSM_DB_ACCESS_RESET
, NULL
);
113 // Construct a TokenDatabase given subservice information.
114 // We are currently ignoring the 'name' argument.
116 TokenDatabase::TokenDatabase(uint32 ssid
, Process
&proc
,
117 const char *name
, const AccessCredentials
*cred
)
120 // locate Token object
121 RefPointer
<Token
> token
= Token::find(ssid
);
123 Session
&session
= process().session();
124 StLock
<Mutex
> _(session
);
125 if (TokenDbCommon
*dbcom
= session
.findFirst
<TokenDbCommon
, uint32
>(&TokenDbCommon::subservice
, ssid
)) {
127 secdebug("tokendb", "open tokendb %p(%ld) at known common %p",
128 this, subservice(), dbcom
);
130 // DbCommon not present; make a new one
131 parent(*new TokenDbCommon(proc
.session(), *token
, name
));
132 secdebug("tokendb", "open tokendb %p(%ld) with new common %p",
133 this, subservice(), &common());
135 mOpenCreds
= copy(cred
, Allocator::standard());
136 proc
.addReference(*this);
139 TokenDatabase::~TokenDatabase()
141 Allocator::standard().free(mOpenCreds
);
146 // Basic Database virtual implementations
148 TokenDbCommon
&TokenDatabase::common() const
150 return parent
<TokenDbCommon
>();
153 TokenDaemon
&TokenDatabase::tokend()
155 return common().token().tokend();
158 const char *TokenDatabase::dbName() const
160 return common().dbName().c_str();
163 bool TokenDatabase::transient() const
165 //@@@ let tokend decide? Are there any secure transient keystores?
170 SecurityServerAcl
&TokenDatabase::acl()
175 bool TokenDatabase::isLocked() const
177 Access
access(token());
178 return access().isLocked();
183 // TokenDatabases implement the dbName-setting function.
184 // This sets the print name of the token, which is persistently
185 // stored in the token cache. So this is a de-facto rename of
186 // the token, at least on this system.
188 void TokenDatabase::dbName(const char *name
)
190 CssmError::throwMe(CSSM_ERRCODE_FUNCTION_NOT_IMPLEMENTED
);
195 // Given a key handle and CssmKey returned from tokend, create a Key representing
196 // it. This takes care of raw returns by turning them into keys of the process's
197 // local transient store.
199 RefPointer
<Key
> TokenDatabase::makeKey(KeyHandle hKey
, const CssmKey
*key
,
200 const AclEntryPrototype
*owner
)
202 switch (key
->blobType()) {
203 case CSSM_KEYBLOB_REFERENCE
:
204 return new TokenKey(*this, hKey
, key
->header());
205 case CSSM_KEYBLOB_RAW
:
206 return process().makeTemporaryKey(*key
, 0, owner
);
208 CssmError::throwMe(CSSM_ERRCODE_INTERNAL_ERROR
); // bad key return from tokend
210 //@@@ Server::releaseWhenDone(key);
215 // Adjust key attributes for newly created keys
217 static CSSM_KEYATTR_FLAGS
modattrs(CSSM_KEYATTR_FLAGS attrs
)
219 static const CSSM_KEYATTR_FLAGS CSSM_KEYATTR_RETURN_FLAGS
= 0xff000000;
220 switch (attrs
& CSSM_KEYATTR_RETURN_FLAGS
) {
221 case CSSM_KEYATTR_RETURN_REF
:
222 case CSSM_KEYATTR_RETURN_DATA
:
223 break; // as requested
224 case CSSM_KEYATTR_RETURN_NONE
:
225 CssmError::throwMe(CSSMERR_CSP_UNSUPPORTED_KEYATTR_MASK
);
226 case CSSM_KEYATTR_RETURN_DEFAULT
:
227 if (attrs
& CSSM_KEYATTR_PERMANENT
)
228 attrs
|= CSSM_KEYATTR_RETURN_REF
;
230 attrs
|= CSSM_KEYATTR_RETURN_DATA
;
238 // TokenDatabases support remote secret validation by sending a secret
239 // (aka passphrase et al) to tokend for processing.
241 bool TokenDatabase::validateSecret(const AclSubject
*subject
, const AccessCredentials
*cred
)
243 secdebug("tokendb", "%p attempting remote validation", this);
245 Access
access(token());
246 // @@@ Use cached mode
247 access().authenticate(CSSM_DB_ACCESS_READ
, cred
);
248 secdebug("tokendb", "%p remote validation successful", this);
252 secdebug("tokendb", "%p remote validation failed", this);
254 throw; // try not to mask error
262 void TokenDatabase::queryKeySizeInBits(Key
&key
, CssmKeySize
&result
)
264 Access
access(token());
267 access().queryKeySizeInBits(myKey(key
).tokenHandle(), result
);
273 // Signatures and MACs
275 void TokenDatabase::generateSignature(const Context
&context
, Key
&key
,
276 CSSM_ALGORITHMS signOnlyAlgorithm
, const CssmData
&data
, CssmData
&signature
)
278 Access
access(token(), key
);
280 key
.validate(CSSM_ACL_AUTHORIZATION_SIGN
, context
);
282 access().generateSignature(context
, myKey(key
).tokenHandle(), data
, signature
, signOnlyAlgorithm
);
287 void TokenDatabase::verifySignature(const Context
&context
, Key
&key
,
288 CSSM_ALGORITHMS verifyOnlyAlgorithm
, const CssmData
&data
, const CssmData
&signature
)
290 Access
access(token(), key
);
293 access().verifySignature(context
, myKey(key
).tokenHandle(), data
, signature
, verifyOnlyAlgorithm
);
297 void TokenDatabase::generateMac(const Context
&context
, Key
&key
,
298 const CssmData
&data
, CssmData
&mac
)
300 Access
access(token());
302 key
.validate(CSSM_ACL_AUTHORIZATION_MAC
, context
);
304 access().generateMac(context
, myKey(key
).tokenHandle(), data
, mac
);
308 void TokenDatabase::verifyMac(const Context
&context
, Key
&key
,
309 const CssmData
&data
, const CssmData
&mac
)
311 Access
access(token());
313 key
.validate(CSSM_ACL_AUTHORIZATION_MAC
, context
);
315 access().verifyMac(context
, myKey(key
).tokenHandle(), data
, mac
);
321 // Encryption/decryption
323 void TokenDatabase::encrypt(const Context
&context
, Key
&key
,
324 const CssmData
&clear
, CssmData
&cipher
)
326 Access
access(token());
328 key
.validate(CSSM_ACL_AUTHORIZATION_ENCRYPT
, context
);
330 access().encrypt(context
, myKey(key
).tokenHandle(), clear
, cipher
);
335 void TokenDatabase::decrypt(const Context
&context
, Key
&key
,
336 const CssmData
&cipher
, CssmData
&clear
)
338 Access
access(token());
340 key
.validate(CSSM_ACL_AUTHORIZATION_DECRYPT
, context
);
342 access().decrypt(context
, myKey(key
).tokenHandle(), cipher
, clear
);
348 // Key generation and derivation.
349 // Currently, we consider symmetric key generation to be fast, but
350 // asymmetric key generation to be (potentially) slow.
352 void TokenDatabase::generateKey(const Context
&context
,
353 const AccessCredentials
*cred
, const AclEntryPrototype
*owner
,
354 CSSM_KEYUSE usage
, CSSM_KEYATTR_FLAGS attrs
, RefPointer
<Key
> &newKey
)
356 Access
access(token());
361 access().generateKey(context
, cred
, owner
, usage
, modattrs(attrs
), hKey
, result
);
362 newKey
= makeKey(hKey
, result
, owner
);
366 void TokenDatabase::generateKey(const Context
&context
,
367 const AccessCredentials
*cred
, const AclEntryPrototype
*owner
,
368 CSSM_KEYUSE pubUsage
, CSSM_KEYATTR_FLAGS pubAttrs
,
369 CSSM_KEYUSE privUsage
, CSSM_KEYATTR_FLAGS privAttrs
,
370 RefPointer
<Key
> &publicKey
, RefPointer
<Key
> &privateKey
)
372 Access
access(token());
375 KeyHandle hPrivate
, hPublic
;
376 CssmKey
*privKey
, *pubKey
;
377 access().generateKey(context
, cred
, owner
,
378 pubUsage
, modattrs(pubAttrs
), privUsage
, modattrs(privAttrs
),
379 hPublic
, pubKey
, hPrivate
, privKey
);
380 publicKey
= makeKey(hPublic
, pubKey
, owner
);
381 privateKey
= makeKey(hPrivate
, privKey
, owner
);
387 // Key wrapping and unwrapping.
388 // Note that the key argument (the key in the context) is optional because of the special
389 // case of "cleartext" (null algorithm) wrapping for import/export.
391 void TokenDatabase::wrapKey(const Context
&context
, const AccessCredentials
*cred
,
392 Key
*wrappingKey
, Key
&subjectKey
,
393 const CssmData
&descriptiveData
, CssmKey
&wrappedKey
)
395 Access
access(token());
396 InputKey
cWrappingKey(wrappingKey
);
397 InputKey
cSubjectKey(subjectKey
);
399 subjectKey
.validate(context
.algorithm() == CSSM_ALGID_NONE
?
400 CSSM_ACL_AUTHORIZATION_EXPORT_CLEAR
: CSSM_ACL_AUTHORIZATION_EXPORT_WRAPPED
,
403 wrappingKey
->validate(CSSM_ACL_AUTHORIZATION_ENCRYPT
, context
);
405 CssmKey
*rWrappedKey
;
406 access().wrapKey(context
, cred
,
407 cWrappingKey
, cWrappingKey
, cSubjectKey
, cSubjectKey
,
408 descriptiveData
, rWrappedKey
);
409 wrappedKey
= *rWrappedKey
;
410 //@@@ ownership of wrappedKey.keyData() ??
414 void TokenDatabase::unwrapKey(const Context
&context
,
415 const AccessCredentials
*cred
, const AclEntryPrototype
*owner
,
416 Key
*wrappingKey
, Key
*publicKey
, CSSM_KEYUSE usage
, CSSM_KEYATTR_FLAGS attrs
,
417 const CssmKey wrappedKey
, RefPointer
<Key
> &unwrappedKey
, CssmData
&descriptiveData
)
419 Access
access(token());
420 InputKey
cWrappingKey(wrappingKey
);
421 InputKey
cPublicKey(publicKey
);
424 wrappingKey
->validate(CSSM_ACL_AUTHORIZATION_DECRYPT
, context
);
425 // we are not checking access on the public key, if any
429 access().unwrapKey(context
, cred
, owner
,
430 cWrappingKey
, cWrappingKey
, cPublicKey
, cPublicKey
,
431 wrappedKey
, usage
, modattrs(attrs
), descriptiveData
, hKey
, result
);
432 unwrappedKey
= makeKey(hKey
, result
, owner
);
440 void TokenDatabase::deriveKey(const Context
&context
, Key
*sourceKey
,
441 const AccessCredentials
*cred
, const AclEntryPrototype
*owner
,
442 CssmData
*param
, CSSM_KEYUSE usage
, CSSM_KEYATTR_FLAGS attrs
, RefPointer
<Key
> &derivedKey
)
444 Access
access(token());
445 InputKey
cSourceKey(sourceKey
);
448 sourceKey
->validate(CSSM_ACL_AUTHORIZATION_DERIVE
, cred
);
452 CssmData params
= param
? *param
: CssmData();
453 access().deriveKey(noDb
, context
,
454 cSourceKey
, cSourceKey
,
455 usage
, modattrs(attrs
), params
, cred
, owner
,
459 //@@@ leak? what's the rule here?
461 derivedKey
= makeKey(hKey
, result
, owner
);
467 // Miscellaneous CSSM functions
469 void TokenDatabase::getOutputSize(const Context
&context
, Key
&key
,
470 uint32 inputSize
, bool encrypt
, uint32
&result
)
472 Access
access(token());
475 access().getOutputSize(context
, myKey(key
).tokenHandle(), inputSize
, encrypt
, result
);
481 // (Re-)Authenticate the database.
482 // We use dbAuthenticate as the catch-all "do something about authentication" call.
484 void TokenDatabase::authenticate(CSSM_DB_ACCESS_TYPE mode
, const AccessCredentials
*cred
)
486 Access
access(token());
489 if (mode
!= CSSM_DB_ACCESS_RESET
&& cred
) {
490 secdebug("tokendb", "%p authenticate calling validate", this);
492 if (sscanf(cred
->EntryTag
, "PIN%d", &pin
) == 1)
494 validate(CSSM_ACL_AUTHORIZATION_PREAUTH(pin
), cred
);
495 notify(kNotificationEventUnlocked
);
500 access().authenticate(mode
, cred
);
502 case CSSM_DB_ACCESS_RESET
:
503 // this mode is known to trigger "lockdown" (i.e. reset)
504 common().resetAcls();
505 notify(kNotificationEventLocked
);
509 // no idea what that did to the token;
510 // But let's remember the new creds for our own sake.
511 AccessCredentials
*newCred
= copy(cred
, Allocator::standard());
512 Allocator::standard().free(mOpenCreds
);
513 mOpenCreds
= newCred
;
521 // Data access interface.
523 // Note that the attribute vectors are passed between our two IPC interfaces
524 // as relocated but contiguous memory blocks (to avoid an extra copy). This means
525 // you can read them at will, but can't change them in transit unless you're
526 // willing to repack them right here.
528 void TokenDatabase::findFirst(const CssmQuery
&query
,
529 CssmDbRecordAttributeData
*inAttributes
, mach_msg_type_number_t inAttributesLength
,
530 CssmData
*data
, RefPointer
<Key
> &key
,
531 RefPointer
<Database::Search
> &rSearch
, RefPointer
<Database::Record
> &rRecord
,
532 CssmDbRecordAttributeData
* &outAttributes
, mach_msg_type_number_t
&outAttributesLength
)
534 Access
access(token());
535 RefPointer
<Search
> search
= new Search(*this);
536 RefPointer
<Record
> record
= new Record(*this);
538 KeyHandle hKey
= noKey
;
539 validate(CSSM_ACL_AUTHORIZATION_DB_READ
, openCreds());
541 record
->tokenHandle() = access().Tokend::ClientSession::findFirst(query
,
542 inAttributes
, inAttributesLength
, search
->tokenHandle(), NULL
, hKey
,
543 outAttributes
, outAttributesLength
);
544 if (!record
->tokenHandle()) { // no match (but no other error)
545 rRecord
= NULL
; // return null record
550 record
->validate(CSSM_ACL_AUTHORIZATION_DB_READ
, openCreds());
551 CssmDbRecordAttributeData
*noAttributes
;
552 mach_msg_type_number_t noAttributesLength
;
553 access().Tokend::ClientSession::findRecordHandle(record
->tokenHandle(),
554 NULL
, 0, data
, hKey
, noAttributes
, noAttributesLength
);
555 if (hKey
) { // tokend returned a key reference & data
556 CssmKey
&keyForm
= *data
->interpretedAs
<CssmKey
>(CSSMERR_CSP_INVALID_KEY
);
557 key
= new TokenKey(*this, hKey
, keyForm
.header());
560 rSearch
= search
->commit();
561 rRecord
= record
->commit();
565 void TokenDatabase::findNext(Database::Search
*rSearch
,
566 CssmDbRecordAttributeData
*inAttributes
, mach_msg_type_number_t inAttributesLength
,
567 CssmData
*data
, RefPointer
<Key
> &key
, RefPointer
<Database::Record
> &rRecord
,
568 CssmDbRecordAttributeData
* &outAttributes
, mach_msg_type_number_t
&outAttributesLength
)
570 Access
access(token());
571 RefPointer
<Record
> record
= new Record(*this);
572 Search
*search
= safe_cast
<Search
*>(rSearch
);
574 KeyHandle hKey
= noKey
;
575 validate(CSSM_ACL_AUTHORIZATION_DB_READ
, openCreds());
577 record
->tokenHandle() = access().Tokend::ClientSession::findNext(
578 search
->tokenHandle(), inAttributes
, inAttributesLength
,
579 NULL
, hKey
, outAttributes
, outAttributesLength
);
580 if (!record
->tokenHandle()) { // no more matches
581 releaseSearch(*search
); // release search handle (consumed by EOD)
582 rRecord
= NULL
; // return null record
587 record
->validate(CSSM_ACL_AUTHORIZATION_DB_READ
, openCreds());
588 CssmDbRecordAttributeData
*noAttributes
;
589 mach_msg_type_number_t noAttributesLength
;
590 access().Tokend::ClientSession::findRecordHandle(record
->tokenHandle(),
591 NULL
, 0, data
, hKey
, noAttributes
, noAttributesLength
);
592 if (hKey
) { // tokend returned a key reference & data
593 CssmKey
&keyForm
= *data
->interpretedAs
<CssmKey
>(CSSMERR_CSP_INVALID_KEY
);
594 key
= new TokenKey(*this, hKey
, keyForm
.header());
597 rRecord
= record
->commit();
601 void TokenDatabase::findRecordHandle(Database::Record
*rRecord
,
602 CssmDbRecordAttributeData
*inAttributes
, mach_msg_type_number_t inAttributesLength
,
603 CssmData
*data
, RefPointer
<Key
> &key
,
604 CssmDbRecordAttributeData
* &outAttributes
, mach_msg_type_number_t
&outAttributesLength
)
606 Access
access(token());
607 Record
*record
= safe_cast
<Record
*>(rRecord
);
610 KeyHandle hKey
= noKey
;
611 validate(CSSM_ACL_AUTHORIZATION_DB_READ
, openCreds());
613 record
->validate(CSSM_ACL_AUTHORIZATION_DB_READ
, openCreds());
615 access().Tokend::ClientSession::findRecordHandle(record
->tokenHandle(),
616 inAttributes
, inAttributesLength
, data
, hKey
, outAttributes
, outAttributesLength
);
618 if (hKey
!= noKey
&& data
) { // tokend returned a key reference & data
619 CssmKey
&keyForm
= *data
->interpretedAs
<CssmKey
>(CSSMERR_CSP_INVALID_KEY
);
620 key
= new TokenKey(*this, hKey
, keyForm
.header());
625 void TokenDatabase::insertRecord(CSSM_DB_RECORDTYPE recordType
,
626 const CssmDbRecordAttributeData
*attributes
, mach_msg_type_number_t attributesLength
,
627 const CssmData
&data
, RefPointer
<Database::Record
> &rRecord
)
629 Access
access(token());
630 RefPointer
<Record
> record
= new Record(*this);
633 validate(CSSM_ACL_AUTHORIZATION_DB_INSERT
, openCreds());
635 access().Tokend::ClientSession::insertRecord(recordType
,
636 attributes
, attributesLength
, data
, record
->tokenHandle());
641 void TokenDatabase::modifyRecord(CSSM_DB_RECORDTYPE recordType
, Record
*rRecord
,
642 const CssmDbRecordAttributeData
*attributes
, mach_msg_type_number_t attributesLength
,
643 const CssmData
*data
, CSSM_DB_MODIFY_MODE modifyMode
)
645 Access
access(token());
646 Record
*record
= safe_cast
<Record
*>(rRecord
);
649 validate(CSSM_ACL_AUTHORIZATION_DB_MODIFY
, openCreds());
650 record
->validate(CSSM_ACL_AUTHORIZATION_DB_MODIFY
, openCreds());
652 access().Tokend::ClientSession::modifyRecord(recordType
,
653 record
->tokenHandle(), attributes
, attributesLength
, data
, modifyMode
);
657 void TokenDatabase::deleteRecord(Database::Record
*rRecord
)
659 Access
access(token(), *this);
660 Record
*record
= safe_cast
<Record
*>(rRecord
);
663 validate(CSSM_ACL_AUTHORIZATION_DB_DELETE
, openCreds());
664 record
->validate(CSSM_ACL_AUTHORIZATION_DB_DELETE
, openCreds());
666 access().Tokend::ClientSession::deleteRecord(record
->tokenHandle());
672 // Record/Search object handling
674 TokenDatabase::Search::~Search()
678 database().token().tokend().Tokend::ClientSession::releaseSearch(mHandle
);
680 secdebug("tokendb", "%p release search handle %ld threw (ignored)",
685 TokenDatabase::Record::~Record()
689 database().token().tokend().Tokend::ClientSession::releaseRecord(mHandle
);
691 secdebug("tokendb", "%p release record handle %ld threw (ignored)",
698 // TokenAcl personality of Record
700 AclKind
TokenDatabase::Record::aclKind() const
705 Token
&TokenDatabase::Record::token()
707 return safer_cast
<TokenDatabase
&>(database()).token();
710 GenericHandle
TokenDatabase::Record::tokenHandle() const
712 return Handler::tokenHandle();
717 // Local utility classes
719 void TokenDatabase::InputKey::setup(Key
*key
)
721 if (TokenKey
*myKey
= dynamic_cast<TokenKey
*>(key
)) {
723 mKeyHandle
= myKey
->tokenHandle();
725 } else if (LocalKey
*hisKey
= dynamic_cast<LocalKey
*>(key
)) {
726 // a local key - turn into raw form
727 CssmClient::WrapKey
wrap(Server::csp(), CSSM_ALGID_NONE
);
728 wrap(hisKey
->cssmKey(), mKey
);
739 TokenDatabase::InputKey::~InputKey()
742 //@@@ Server::csp().freeKey(mKey) ??
743 Server::csp()->allocator().free(mKey
.keyData());