]> git.saurik.com Git - apple/security.git/blob - SecurityServer/sstransit.cpp
Security-163.tar.gz
[apple/security.git] / SecurityServer / sstransit.cpp
1 /*
2 * Copyright (c) 2000-2001 Apple Computer, Inc. All Rights Reserved.
3 *
4 * The contents of this file constitute Original Code as defined in and are
5 * subject to the Apple Public Source License Version 1.2 (the 'License').
6 * You may not use this file except in compliance with the License. Please obtain
7 * a copy of the License at http://www.apple.com/publicsource and read it before
8 * using this file.
9 *
10 * This Original Code and all software distributed under the License are
11 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS
12 * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT
13 * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
14 * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the
15 * specific language governing rights and limitations under the License.
16 */
17
18
19 //
20 // sstransit - SecurityServer client library transition code.
21 //
22 // These are the functions that implement CssmClient methods in terms of
23 // MIG IPC client calls, plus their supporting machinery.
24 //
25 #include "sstransit.h"
26 #include <Security/cspclient.h>
27 #include <Security/ktracecodes.h>
28 #include <CoreServices/../Frameworks/CarbonCore.framework/Headers/MacErrors.h>
29
30 namespace Security {
31
32 using MachPlusPlus::check;
33 using MachPlusPlus::VMGuard;
34
35
36 //
37 // DataOutput helper.
38 // This happens "at the end" of a glue method, via the DataOutput destructor.
39 //
40 DataOutput::~DataOutput()
41 {
42 VMGuard _(mData, mLength);
43 if (mData) { // was assigned to; IPC returned OK
44 if (argument) { // buffer was provided
45 if (argument.length() < mLength)
46 CssmError::throwMe(CSSMERR_CSP_OUTPUT_LENGTH_ERROR);
47 argument.length(mLength);
48 } else { // allocate buffer
49 argument = CssmData(allocator.malloc(mLength), mLength);
50 }
51 memcpy(argument.data(), mData, mLength);
52 }
53 }
54
55
56 CssmList chunkCopy(CssmList &list, CssmAllocator &alloc)
57 {
58 CssmList copy = list;
59 ChunkCopyWalker w(alloc);
60 walk(w, copy);
61 return copy;
62 }
63
64
65 //
66 // Create a packaged-up Context for IPC transmission.
67 // In addition to collecting the context into a contiguous blob for transmission,
68 // we also evaluate CssmCryptoData callbacks at this time.
69 //
70 SendContext::SendContext(const Security::Context &ctx) : context(ctx)
71 {
72 CssmCryptoData cryptoDataValue; // holding area for CssmCryptoData element
73 IFDEBUG(uint32 cryptoDataUsed = 0);
74 Context::Builder builder(CssmAllocator::standard());
75 for (unsigned n = 0; n < ctx.attributesInUse(); n++) {
76 switch (ctx[n].baseType()) {
77 case CSSM_ATTRIBUTE_DATA_CRYPTO_DATA: {
78 CssmCryptoData &data = ctx[n]; // extract CssmCryptoData value
79 cryptoDataValue = data(); // evaluate callback (if any)
80 builder.setup(&cryptoDataValue); // use evaluted value
81 IFDEBUG(cryptoDataUsed++);
82 break;
83 }
84 default:
85 builder.setup(ctx[n]);
86 break;
87 }
88 }
89 attributeSize = builder.make();
90 for (unsigned n = 0; n < ctx.attributesInUse(); n++) {
91 const Context::Attr &attr = ctx[n];
92 switch (attr.baseType()) {
93 case CSSM_ATTRIBUTE_DATA_CRYPTO_DATA:
94 builder.put(attr.type(), &cryptoDataValue);
95 break;
96 default:
97 builder.put(attr);
98 break;
99 }
100 }
101 uint32 count; // not needed
102 builder.done(attributes, count);
103 assert(cryptoDataUsed <= 1); // no more than one slot converted
104 }
105
106
107 //
108 // Copy an AccessCredentials for shipment.
109 // In addition, scan the samples for "special" database locking samples
110 // and translate certain items for safe shipment. Note that this overwrites
111 // part of the CssmList value (CSPHandle -> SS/KeyHandle), but we do it on
112 // the COPY, so that's okay.
113 //
114 DatabaseAccessCredentials::DatabaseAccessCredentials(const AccessCredentials *creds, CssmAllocator &alloc)
115 : Copier<AccessCredentials>(creds, alloc)
116 {
117 if (creds) {
118 for (uint32 n = 0; n < value()->samples().length(); n++) {
119 TypedList sample = value()->samples()[n];
120 sample.checkProper();
121 switch (sample.type()) {
122 case CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK:
123 case CSSM_SAMPLE_TYPE_KEYCHAIN_CHANGE_LOCK:
124 sample.snip(); // skip sample type
125 sample.checkProper();
126 if (sample.type() == CSSM_WORDID_SYMMETRIC_KEY) {
127 secdebug("SSclient", "key sample encountered");
128 // proper form is sample[1] = DATA:CSPHandle, sample[2] = DATA:CSSM_KEY
129 if (sample.length() != 3
130 || sample[1].type() != CSSM_LIST_ELEMENT_DATUM
131 || sample[2].type() != CSSM_LIST_ELEMENT_DATUM)
132 CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE);
133 mapKeySample(
134 *sample[1].data().interpretedAs<CSSM_CSP_HANDLE>(CSSM_ERRCODE_INVALID_SAMPLE_VALUE),
135 *sample[2].data().interpretedAs<CssmKey>(CSSM_ERRCODE_INVALID_SAMPLE_VALUE));
136 }
137 break;
138 default:
139 break;
140 }
141 }
142 }
143 }
144
145 void DatabaseAccessCredentials::mapKeySample(CSSM_CSP_HANDLE &cspHandle, CssmKey &key)
146 {
147 // if the key belongs to the AppleCSPDL, look it up and write the SS KeyHandle
148 // into the CSPHandle element for transmission
149 if (key.header().cspGuid() == gGuidAppleCSPDL) {
150 // @@@ can't use CssmClient (it makes its own attachments)
151 CSSM_CC_HANDLE ctx;
152 if (CSSM_RETURN err = CSSM_CSP_CreatePassThroughContext(cspHandle, &key, &ctx))
153 CssmError::throwMe(err);
154 KeyHandle ssKey;
155 CSSM_RETURN passthroughError =
156 CSSM_CSP_PassThrough(ctx, CSSM_APPLESCPDL_CSP_GET_KEYHANDLE, NULL, (void **)&ssKey);
157 CSSM_DeleteContext(ctx); // ignore error
158 if (passthroughError)
159 CssmError::throwMe(passthroughError);
160 // we happen to know that they're both uint32 values
161 assert(sizeof(CSSM_CSP_HANDLE) >= sizeof(KeyHandle));
162 cspHandle = ssKey;
163 secdebug("SSclient", "key sample mapped to key 0x%lx", ssKey);
164 }
165 }
166
167
168 namespace SecurityServer
169 {
170
171 //
172 // Database control
173 //
174 DbHandle ClientSession::createDb(const DLDbIdentifier &dbId,
175 const AccessCredentials *cred, const AclEntryInput *owner,
176 const DBParameters &params)
177 {
178 DatabaseAccessCredentials creds(cred, internalAllocator);
179 Copier<AclEntryPrototype> proto(&owner->proto(), internalAllocator);
180 DataWalkers::DLDbFlatIdentifier ident(dbId);
181 Copier<DataWalkers::DLDbFlatIdentifier> id(&ident, internalAllocator);
182 DbHandle db;
183 IPC(ucsp_client_createDb(UCSP_ARGS, &db, COPY(id), COPY(creds), COPY(proto), params));
184 return db;
185 }
186
187 DbHandle ClientSession::decodeDb(const DLDbIdentifier &dbId,
188 const AccessCredentials *cred, const CssmData &blob)
189 {
190 DatabaseAccessCredentials creds(cred, internalAllocator);
191 DataWalkers::DLDbFlatIdentifier ident(dbId);
192 Copier<DataWalkers::DLDbFlatIdentifier> id(&ident, internalAllocator);
193 DbHandle db;
194 IPC(ucsp_client_decodeDb(UCSP_ARGS, &db, COPY(id), COPY(creds), DATA(blob)));
195 return db;
196 }
197
198 void ClientSession::encodeDb(DbHandle db, CssmData &blob, CssmAllocator &alloc)
199 {
200 DataOutput outBlob(blob, alloc);
201 IPC(ucsp_client_encodeDb(UCSP_ARGS, db, DATA(outBlob)));
202 }
203
204 void ClientSession::releaseDb(DbHandle db)
205 {
206 IPC(ucsp_client_releaseDb(UCSP_ARGS, db));
207 }
208
209 void ClientSession::getDbSuggestedIndex(DbHandle db, CssmData &index, CssmAllocator &alloc)
210 {
211 DataOutput outBlob(index, alloc);
212 IPC(ucsp_client_getDbIndex(UCSP_ARGS, db, DATA(outBlob)));
213 }
214
215 void ClientSession::authenticateDb(DbHandle db, DBAccessType type,
216 const AccessCredentials *cred)
217 {
218 DatabaseAccessCredentials creds(cred, internalAllocator);
219 IPC(ucsp_client_authenticateDb(UCSP_ARGS, db, COPY(creds)));
220 }
221
222 void ClientSession::setDbParameters(DbHandle db, const DBParameters &params)
223 {
224 IPC(ucsp_client_setDbParameters(UCSP_ARGS, db, params));
225 }
226
227 void ClientSession::getDbParameters(DbHandle db, DBParameters &params)
228 {
229 IPC(ucsp_client_getDbParameters(UCSP_ARGS, db, &params));
230 }
231
232 void ClientSession::changePassphrase(DbHandle db, const AccessCredentials *cred)
233 {
234 Copier<AccessCredentials> creds(cred, internalAllocator);
235 IPC(ucsp_client_changePassphrase(UCSP_ARGS, db, COPY(creds)));
236 }
237
238
239 void ClientSession::lock(DbHandle db)
240 {
241 IPC(ucsp_client_lockDb(UCSP_ARGS, db));
242 }
243
244 void ClientSession::lockAll (bool forSleep)
245 {
246 IPC(ucsp_client_lockAll (UCSP_ARGS, forSleep));
247 }
248
249 void ClientSession::unlock(DbHandle db)
250 {
251 IPC(ucsp_client_unlockDb(UCSP_ARGS, db));
252 }
253
254 void ClientSession::unlock(DbHandle db, const CssmData &passphrase)
255 {
256 IPC(ucsp_client_unlockDbWithPassphrase(UCSP_ARGS, db, DATA(passphrase)));
257 }
258
259 bool ClientSession::isLocked(DbHandle db)
260 {
261 boolean_t locked;
262 IPC(ucsp_client_isLocked(UCSP_ARGS, db, &locked));
263 return locked;
264 }
265
266
267 //
268 // Key control
269 //
270 void ClientSession::encodeKey(KeyHandle key, CssmData &blob,
271 KeyUID *uid, CssmAllocator &alloc)
272 {
273 DataOutput oBlob(blob, alloc);
274 void *uidp;
275 mach_msg_type_number_t uidLength;
276 IPC(ucsp_client_encodeKey(UCSP_ARGS, key, oBlob.data(), oBlob.length(),
277 (uid != NULL), &uidp, &uidLength));
278 // return key uid if requested
279 if (uid) {
280 assert(uidLength == sizeof(KeyUID));
281 memcpy(uid, uidp, sizeof(KeyUID));
282 }
283 }
284
285
286 KeyHandle ClientSession::decodeKey(DbHandle db, const CssmData &blob, CssmKey::Header &header)
287 {
288 KeyHandle key;
289 IPC(ucsp_client_decodeKey(UCSP_ARGS, &key, &header, db, blob.data(), blob.length()));
290 return key;
291 }
292
293 void ClientSession::releaseKey(KeyHandle key)
294 {
295 IPC(ucsp_client_releaseKey(UCSP_ARGS, key));
296 }
297
298
299 CssmKeySize ClientSession::queryKeySizeInBits(KeyHandle key)
300 {
301 CssmKeySize length;
302 IPC(ucsp_client_queryKeySizeInBits(UCSP_ARGS, key, &length));
303 return length;
304 }
305
306
307 uint32 ClientSession::getOutputSize(const Context &context, KeyHandle key,
308 uint32 inputSize, bool encrypt)
309 {
310 SendContext ctx(context);
311 uint32 outputSize;
312 IPC(ucsp_client_getOutputSize(UCSP_ARGS, CONTEXT(ctx), key, inputSize, encrypt, &outputSize));
313 return outputSize;
314 }
315
316
317 //
318 // Random number generation.
319 // This interfaces to the secure RNG inside the SecurityServer; it does not access
320 // a PRNG in its CSP. If you need a reproducible PRNG, attach a local CSP and use it.
321 // Note that this function does not allocate a buffer; it always fills the buffer provided.
322 //
323 void ClientSession::generateRandom(CssmData &data)
324 {
325 void *result;
326 mach_msg_type_number_t resultLength;
327 IPC(ucsp_client_generateRandom(UCSP_ARGS, data.length(), &result, &resultLength));
328 assert(resultLength == data.length());
329 memcpy(data.data(), result, data.length());
330 }
331
332
333 //
334 // Signatures and MACs
335 //
336 void ClientSession::generateSignature(const Context &context, KeyHandle key,
337 const CssmData &data, CssmData &signature, CssmAllocator &alloc, CSSM_ALGORITHMS signOnlyAlgorithm)
338 {
339 SendContext ctx(context);
340 DataOutput sig(signature, alloc);
341 IPC(ucsp_client_generateSignature(UCSP_ARGS, CONTEXT(ctx), key, signOnlyAlgorithm,
342 DATA(data), DATA(sig)));
343 }
344
345 void ClientSession::verifySignature(const Context &context, KeyHandle key,
346 const CssmData &data, const CssmData &signature, CSSM_ALGORITHMS verifyOnlyAlgorithm)
347 {
348 SendContext ctx(context);
349 IPC(ucsp_client_verifySignature(UCSP_ARGS, CONTEXT(ctx), key, verifyOnlyAlgorithm,
350 DATA(data), DATA(signature)));
351 }
352
353
354 void ClientSession::generateMac(const Context &context, KeyHandle key,
355 const CssmData &data, CssmData &signature, CssmAllocator &alloc)
356 {
357 SendContext ctx(context);
358 DataOutput sig(signature, alloc);
359 IPC(ucsp_client_generateMac(UCSP_ARGS, CONTEXT(ctx), key,
360 DATA(data), DATA(sig)));
361 }
362
363 void ClientSession::verifyMac(const Context &context, KeyHandle key,
364 const CssmData &data, const CssmData &signature)
365 {
366 SendContext ctx(context);
367 IPC(ucsp_client_verifyMac(UCSP_ARGS, CONTEXT(ctx), key,
368 DATA(data), DATA(signature)));
369 }
370
371
372 //
373 // Encryption/Decryption
374 //
375
376 void ClientSession::encrypt(const Context &context, KeyHandle key,
377 const CssmData &clear, CssmData &cipher, CssmAllocator &alloc)
378 {
379 SendContext ctx(context);
380 DataOutput cipherOut(cipher, alloc);
381 IPC(ucsp_client_encrypt(UCSP_ARGS, CONTEXT(ctx), key, DATA(clear), DATA(cipherOut)));
382 }
383
384 void ClientSession::decrypt(const Context &context, KeyHandle key,
385 const CssmData &cipher, CssmData &clear, CssmAllocator &alloc)
386 {
387 Debug::trace (kSecTraceUCSPServerDecryptBegin);
388
389 SendContext ctx(context);
390 DataOutput clearOut(clear, alloc);
391 IPC(ucsp_client_decrypt(UCSP_ARGS, CONTEXT(ctx), key, DATA(cipher), DATA(clearOut)));
392 }
393
394
395 //
396 // Key generation
397 //
398 void ClientSession::generateKey(DbHandle db, const Context &context, uint32 keyUsage, uint32 keyAttr,
399 const AccessCredentials *cred, const AclEntryInput *owner,
400 KeyHandle &newKey, CssmKey::Header &newHeader)
401 {
402 SendContext ctx(context);
403 Copier<AccessCredentials> creds(cred, internalAllocator);
404 Copier<AclEntryPrototype> proto(&owner->proto(), internalAllocator);
405 IPC(ucsp_client_generateKey(UCSP_ARGS, db, CONTEXT(ctx),
406 COPY(creds), COPY(proto), keyUsage, keyAttr, &newKey, &newHeader));
407 }
408
409 void ClientSession::generateKey(DbHandle db, const Context &context,
410 uint32 pubKeyUsage, uint32 pubKeyAttr,
411 uint32 privKeyUsage, uint32 privKeyAttr,
412 const AccessCredentials *cred, const AclEntryInput *owner,
413 KeyHandle &pubKey, CssmKey::Header &pubHeader,
414 KeyHandle &privKey, CssmKey::Header &privHeader)
415 {
416 SendContext ctx(context);
417 Copier<AccessCredentials> creds(cred, internalAllocator);
418 Copier<AclEntryPrototype> proto(&owner->proto(), internalAllocator);
419 IPC(ucsp_client_generateKeyPair(UCSP_ARGS, db, CONTEXT(ctx),
420 COPY(creds), COPY(proto),
421 pubKeyUsage, pubKeyAttr, privKeyUsage, privKeyAttr,
422 &pubKey, &pubHeader, &privKey, &privHeader));
423 }
424
425
426 //
427 // Key derivation
428 // This is a bit strained; the incoming 'param' value may have structure
429 // and needs to be handled on a per-algorithm basis, which means we have to
430 // know which key derivation algorithms we support for passing to our CSP(s).
431 // The default behavior is to handle "flat" data blobs, which is as good
432 // a default as we can manage.
433 // NOTE: The param-specific handling must be synchronized with the server
434 // transition layer code (in transition.cpp).
435 //
436 void ClientSession::deriveKey(DbHandle db, const Context &context, KeyHandle baseKey,
437 uint32 keyUsage, uint32 keyAttr, CssmData &param,
438 const AccessCredentials *cred, const AclEntryInput *owner,
439 KeyHandle &newKey, CssmKey::Header &newHeader, CssmAllocator &allocator)
440 {
441 SendContext ctx(context);
442 Copier<AccessCredentials> creds(cred, internalAllocator);
443 Copier<AclEntryPrototype> proto(&owner->proto(), internalAllocator);
444 DataOutput paramOutput(param, allocator);
445 switch (context.algorithm()) {
446 case CSSM_ALGID_PKCS5_PBKDF2: {
447 typedef CSSM_PKCS5_PBKDF2_PARAMS Params;
448 Copier<Params> params(param.interpretedAs<Params>(CSSM_ERRCODE_INVALID_INPUT_POINTER),
449 internalAllocator);
450 IPC(ucsp_client_deriveKey(UCSP_ARGS, db, CONTEXT(ctx), baseKey,
451 COPY(creds), COPY(proto), COPY(params), DATA(paramOutput),
452 keyUsage, keyAttr, &newKey, &newHeader));
453 break; }
454 default: {
455 IPC(ucsp_client_deriveKey(UCSP_ARGS, db, CONTEXT(ctx), baseKey,
456 COPY(creds), COPY(proto),
457 param.data(), param.length(), param.data(),
458 DATA(paramOutput),
459 keyUsage, keyAttr, &newKey, &newHeader));
460 break; }
461 }
462 }
463
464
465 //
466 // Digest generation
467 //
468 void ClientSession::getKeyDigest(KeyHandle key, CssmData &digest, CssmAllocator &allocator)
469 {
470 DataOutput dig(digest, allocator);
471 IPC(ucsp_client_getKeyDigest(UCSP_ARGS, key, DATA(dig)));
472 }
473
474
475 //
476 // Key wrapping and unwrapping
477 //
478 void ClientSession::wrapKey(const Context &context, KeyHandle wrappingKey,
479 KeyHandle keyToBeWrapped, const AccessCredentials *cred,
480 const CssmData *descriptiveData, CssmWrappedKey &wrappedKey, CssmAllocator &alloc)
481 {
482 SendContext ctx(context);
483 Copier<AccessCredentials> creds(cred, internalAllocator);
484 DataOutput keyData(wrappedKey, alloc);
485 IPC(ucsp_client_wrapKey(UCSP_ARGS, CONTEXT(ctx), wrappingKey, COPY(creds),
486 keyToBeWrapped, OPTIONALDATA(descriptiveData),
487 &wrappedKey, DATA(keyData)));
488 wrappedKey = CssmData(); // null out data section (force allocation for key data)
489 }
490
491 void ClientSession::unwrapKey(DbHandle db, const Context &context, KeyHandle key,
492 KeyHandle publicKey, const CssmWrappedKey &wrappedKey,
493 uint32 usage, uint32 attr,
494 const AccessCredentials *cred, const AclEntryInput *acl,
495 CssmData &descriptiveData,
496 KeyHandle &newKey, CssmKey::Header &newHeader, CssmAllocator &alloc)
497 {
498 SendContext ctx(context);
499 DataOutput descriptor(descriptiveData, alloc);
500 Copier<AccessCredentials> creds(cred, internalAllocator);
501 Copier<AclEntryPrototype> proto(&acl->proto(), internalAllocator);
502 IPC(ucsp_client_unwrapKey(UCSP_ARGS, db, CONTEXT(ctx), key,
503 COPY(creds), COPY(proto),
504 publicKey, wrappedKey, DATA(wrappedKey), usage, attr, DATA(descriptor),
505 &newKey, &newHeader));
506 }
507
508
509 //
510 // ACL management
511 //
512 void ClientSession::getAcl(AclKind kind, KeyHandle key, const char *tag,
513 uint32 &infoCount, AclEntryInfo * &infoArray, CssmAllocator &alloc)
514 {
515 uint32 count;
516 AclEntryInfo *info, *infoBase;
517 mach_msg_type_number_t infoLength;
518 IPC(ucsp_client_getAcl(UCSP_ARGS, kind, key,
519 (tag != NULL), tag ? tag : "",
520 &count, COPY_OUT(info)));
521 VMGuard _(info, infoLength);
522 infoCount = count;
523
524 // relocate incoming AclEntryInfo array
525 ReconstituteWalker relocator(info, infoBase);
526 for (uint32 n = 0; n < count; n++)
527 walk(relocator, info[n]);
528
529 // copy AclEntryInfo array into discrete memory nodes
530 infoArray = alloc.alloc<AclEntryInfo>(count);
531 ChunkCopyWalker chunker(alloc);
532 for (uint32 n = 0; n < count; n++) {
533 infoArray[n] = info[n];
534 walk(chunker, infoArray[n]);
535 }
536 }
537
538 void ClientSession::changeAcl(AclKind kind, KeyHandle key, const AccessCredentials &cred,
539 const AclEdit &edit)
540 {
541 Copier<AccessCredentials> creds(&cred, internalAllocator);
542 //@@@ ignoring callback
543 Copier<AclEntryInput> newEntry(edit.newEntry(), internalAllocator);
544 IPC(ucsp_client_changeAcl(UCSP_ARGS, kind, key, COPY(creds),
545 edit.mode(), edit.handle(), COPY(newEntry)));
546 }
547
548 void ClientSession::getOwner(AclKind kind, KeyHandle key, AclOwnerPrototype &owner,
549 CssmAllocator &alloc)
550 {
551 AclOwnerPrototype *proto, *protoBase;
552 mach_msg_type_number_t protoLength;
553 IPC(ucsp_client_getOwner(UCSP_ARGS, kind, key, COPY_OUT(proto)));
554 // turn the returned AclOwnerPrototype into its proper output form
555 relocate(proto, protoBase);
556 owner.TypedSubject = chunkCopy(proto->subject(), alloc);
557 owner.Delegate = proto->delegate();
558 }
559
560 void ClientSession::changeOwner(AclKind kind, KeyHandle key,
561 const AccessCredentials &cred, const AclOwnerPrototype &proto)
562 {
563 Copier<AccessCredentials> creds(&cred, internalAllocator);
564 Copier<AclOwnerPrototype> protos(&proto, internalAllocator);
565 IPC(ucsp_client_setOwner(UCSP_ARGS, kind, key, COPY(creds), COPY(protos)));
566 }
567
568
569 void ClientSession::getKeyAcl(DbHandle db, const char *tag,
570 uint32 &count, AclEntryInfo * &info, CssmAllocator &alloc)
571 { getAcl(keyAcl, db, tag, count, info, alloc); }
572
573 void ClientSession::changeKeyAcl(DbHandle db, const AccessCredentials &cred,
574 const AclEdit &edit)
575 { changeAcl(keyAcl, db, cred, edit); }
576
577 void ClientSession::getKeyOwner(DbHandle db, AclOwnerPrototype &owner, CssmAllocator &alloc)
578 { getOwner(keyAcl, db, owner, alloc); }
579
580 void ClientSession::changeKeyOwner(DbHandle db, const AccessCredentials &cred,
581 const AclOwnerPrototype &edit)
582 { changeOwner(keyAcl, db, cred, edit); }
583
584 void ClientSession::getDbAcl(DbHandle db, const char *tag,
585 uint32 &count, AclEntryInfo * &info, CssmAllocator &alloc)
586 { getAcl(dbAcl, db, tag, count, info, alloc); }
587
588 void ClientSession::changeDbAcl(DbHandle db, const AccessCredentials &cred,
589 const AclEdit &edit)
590 { changeAcl(dbAcl, db, cred, edit); }
591
592 void ClientSession::getDbOwner(DbHandle db, AclOwnerPrototype &owner, CssmAllocator &alloc)
593 { getOwner(dbAcl, db, owner, alloc); }
594
595 void ClientSession::changeDbOwner(DbHandle db, const AccessCredentials &cred,
596 const AclOwnerPrototype &edit)
597 { changeOwner(dbAcl, db, cred, edit); }
598
599
600 //
601 // Database key management
602 //
603 void ClientSession::extractMasterKey(DbHandle db, const Context &context, DbHandle sourceDb,
604 uint32 keyUsage, uint32 keyAttr,
605 const AccessCredentials *cred, const AclEntryInput *owner,
606 KeyHandle &newKey, CssmKey::Header &newHeader, CssmAllocator &alloc)
607 {
608 SendContext ctx(context);
609 Copier<AccessCredentials> creds(cred, internalAllocator);
610 Copier<AclEntryPrototype> proto(&owner->proto(), internalAllocator);
611 IPC(ucsp_client_extractMasterKey(UCSP_ARGS, db, CONTEXT(ctx), sourceDb,
612 COPY(creds), COPY(proto),
613 keyUsage, keyAttr, &newKey, &newHeader));
614 }
615
616
617 //
618 // Authorization subsystem entry
619 //
620 void ClientSession::authCreate(const AuthorizationItemSet *rights,
621 const AuthorizationItemSet *environment, AuthorizationFlags flags,
622 AuthorizationBlob &result)
623 {
624 Copier<AuthorizationItemSet> rightSet(rights, internalAllocator);
625 Copier<AuthorizationItemSet> environ(environment, internalAllocator);
626 IPC(ucsp_client_authorizationCreate(UCSP_ARGS,
627 COPY(rightSet), flags, COPY(environ), &result));
628 }
629
630 void ClientSession::authRelease(const AuthorizationBlob &auth,
631 AuthorizationFlags flags)
632 {
633 IPC(ucsp_client_authorizationRelease(UCSP_ARGS, auth, flags));
634 }
635
636 void ClientSession::authCopyRights(const AuthorizationBlob &auth,
637 const AuthorizationItemSet *rights, const AuthorizationItemSet *environment,
638 AuthorizationFlags flags,
639 AuthorizationItemSet **grantedRights)
640 {
641 Copier<AuthorizationItemSet> rightSet(rights, internalAllocator);
642 Copier<AuthorizationItemSet> environ(environment, internalAllocator);
643 COPY_OUT_DECL(AuthorizationItemSet, result);
644 IPC(ucsp_client_authorizationCopyRights(UCSP_ARGS, auth, COPY(rightSet),
645 flags | (grantedRights ? 0 : kAuthorizationFlagNoData),
646 COPY(environ), COPY_OUT(result)));
647 VMGuard _(result, resultLength);
648 // return rights vector (only) if requested
649 if (grantedRights) {
650 relocate(result, resultBase);
651 *grantedRights = copy(result, returnAllocator);
652 }
653 }
654
655 void ClientSession::authCopyInfo(const AuthorizationBlob &auth,
656 const char *tag,
657 AuthorizationItemSet * &info)
658 {
659 COPY_OUT_DECL(AuthorizationItemSet, result);
660 if (tag == NULL)
661 tag = "";
662 else if (tag[0] == '\0')
663 MacOSError::throwMe(errAuthorizationInvalidTag);
664 IPC(ucsp_client_authorizationCopyInfo(UCSP_ARGS, auth, tag, COPY_OUT(result)));
665 VMGuard _(result, resultLength);
666 relocate(result, resultBase);
667 info = copy(result, returnAllocator);
668 }
669
670 void ClientSession::authExternalize(const AuthorizationBlob &auth,
671 AuthorizationExternalForm &extForm)
672 {
673 IPC(ucsp_client_authorizationExternalize(UCSP_ARGS, auth, &extForm));
674 }
675
676 void ClientSession::authInternalize(const AuthorizationExternalForm &extForm,
677 AuthorizationBlob &auth)
678 {
679 IPC(ucsp_client_authorizationInternalize(UCSP_ARGS, extForm, &auth));
680 }
681
682
683 //
684 // Get session information (security session status)
685 //
686 void ClientSession::getSessionInfo(SecuritySessionId &sessionId, SessionAttributeBits &attrs)
687 {
688 IPC(ucsp_client_getSessionInfo(UCSP_ARGS, &sessionId, &attrs));
689 }
690
691
692 //
693 // Create a new session.
694 //
695 // Caveat: This discards all SecurityServer held state for this process, including
696 // authorizations, database handles, etc. If you are multi-threaded at this point,
697 // and other threads have talked to SecurityServer, they will leak a few resources
698 // (mach ports and the like). Nothing horrendous, unless you create masses of sessions
699 // that way (which we wouldn't exactly recommend for other reasons).
700 //
701 // Hacker's note: This engages in an interesting dance with SecurityServer's state tracking.
702 // If you don't know the choreography, don't change things here until talking to an expert.
703 //
704 // Yes, if the client had multiple threads each of which has talked to SecurityServer,
705 // the reply ports for all but the calling thread will leak. If that ever turns out to
706 // be a real problem, we can fix it by keeping a (locked) set of client replyPorts to ditch.
707 // Hardly worth it, though. This is a rare call.
708 //
709 void ClientSession::setupSession(SessionCreationFlags flags, SessionAttributeBits attrs)
710 {
711 mGlobal().thread().replyPort.destroy(); // kill this thread's reply port
712 mGlobal.reset(); // kill existing cache (leak all other threads)
713 mSetupSession = true; // global flag to Global constructor
714 IPC(ucsp_client_setupSession(UCSP_ARGS, flags, attrs)); // reinitialize and call
715 }
716
717
718 //
719 // Notification subsystem
720 //
721 void ClientSession::requestNotification(Port receiver, Listener::Domain domain, Listener::EventMask events)
722 {
723 IPC(ucsp_client_requestNotification(UCSP_ARGS, receiver, domain, events));
724 }
725
726 void ClientSession::stopNotification(Port port)
727 {
728 IPC(ucsp_client_stopNotification(UCSP_ARGS, port.port()));
729 }
730
731 void ClientSession::postNotification(Listener::Domain domain, Listener::Event event, const CssmData &data)
732 {
733 IPC(ucsp_client_postNotification(UCSP_ARGS, domain, event, DATA(data)));
734 }
735
736 OSStatus ClientSession::dispatchNotification(const mach_msg_header_t *message,
737 ConsumeNotification *consumer, void *context) throw()
738 {
739 struct Message {
740 mach_msg_header_t Head;
741 /* start of the kernel processed data */
742 mach_msg_body_t msgh_body;
743 mach_msg_ool_descriptor_t data;
744 /* end of the kernel processed data */
745 NDR_record_t NDR;
746 uint32 domain;
747 uint32 event;
748 mach_msg_type_number_t dataCnt;
749 uint32 sender;
750 } *msg = (Message *)message;
751
752 OSStatus status;
753 try
754 {
755 status = consumer(msg->domain, msg->event, msg->data.address, msg->dataCnt, context);
756 }
757 catch (const CssmCommonError &err) { status = err.osStatus(); }
758 catch (const std::bad_alloc &) { status = memFullErr; }
759 catch (...) { status = internalComponentErr; }
760
761 mig_deallocate((vm_offset_t) msg->data.address, msg->dataCnt);
762 msg->data.address = (vm_offset_t) 0;
763 msg->data.size = (mach_msg_size_t) 0;
764
765 return status;
766 }
767
768
769 //
770 // authorizationdbGet/Set/Remove
771 //
772 void ClientSession::authorizationdbGet(const AuthorizationString rightname, CssmData &rightDefinition, CssmAllocator &alloc)
773 {
774 DataOutput definition(rightDefinition, alloc);
775 IPC(ucsp_client_authorizationdbGet(UCSP_ARGS, rightname, DATA(definition)));
776 }
777
778 void ClientSession::authorizationdbSet(const AuthorizationBlob &auth, const AuthorizationString rightname, uint32_t rightDefinitionLength, const void *rightDefinition)
779 {
780 // @@@ DATA_IN in transition.cpp is not const void *
781 IPC(ucsp_client_authorizationdbSet(UCSP_ARGS, auth, rightname, const_cast<void *>(rightDefinition), rightDefinitionLength));
782 }
783
784 void ClientSession::authorizationdbRemove(const AuthorizationBlob &auth, const AuthorizationString rightname)
785 {
786 IPC(ucsp_client_authorizationdbRemove(UCSP_ARGS, auth, rightname));
787 }
788
789
790 //
791 // Miscellaneous administrative calls
792 //
793 void ClientSession::addCodeEquivalence(const CssmData &oldHash, const CssmData &newHash,
794 const char *name, bool forSystem /* = false */)
795 {
796 IPC(ucsp_client_addCodeEquivalence(UCSP_ARGS, DATA(oldHash), DATA(newHash),
797 name, forSystem));
798 }
799
800 void ClientSession::removeCodeEquivalence(const CssmData &hash, const char *name, bool forSystem /* = false */)
801 {
802 IPC(ucsp_client_removeCodeEquivalence(UCSP_ARGS, DATA(hash), name, forSystem));
803 }
804
805 void ClientSession::setAlternateSystemRoot(const char *path)
806 {
807 IPC(ucsp_client_setAlternateSystemRoot(UCSP_ARGS, path));
808 }
809
810
811 } // end namespace SecurityServer
812 } // end namespace Security