]> git.saurik.com Git - apple/security.git/blob - securityd/src/csproxy.cpp
Security-58286.1.32.tar.gz
[apple/security.git] / securityd / src / csproxy.cpp
1 /*
2 * Copyright (c) 2006-2010 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 // csproxy - Code Signing Hosting Proxy
27 //
28 #include <set>
29
30 #include "csproxy.h"
31 #include "server.h"
32 #include <Security/SecStaticCode.h>
33 #include <securityd_client/cshosting.h>
34 #include <security_utilities/cfmunge.h>
35 #include <security_utilities/casts.h>
36 #include <utilities/SecCFRelease.h>
37
38 //
39 // Construct a CodeSigningHost
40 //
41 CodeSigningHost::CodeSigningHost()
42 : mLock(Mutex::recursive), mHostingState(noHosting)
43 {
44 }
45
46
47 //
48 // Cleanup code.
49 //
50 CodeSigningHost::~CodeSigningHost()
51 {
52 reset();
53 }
54
55
56 //
57 // Reset Code Signing Hosting state.
58 // This turns hosting off and clears all children.
59 //
60 void CodeSigningHost::reset()
61 {
62 StLock<Mutex> _(mLock);
63 switch (mHostingState) {
64 case noHosting:
65 break; // nothing to do
66 case dynamicHosting:
67 mHostingPort.destroy();
68 mHostingPort = MACH_PORT_NULL;
69 secnotice("SS", "%d host unregister", mHostingPort.port());
70 break;
71 case proxyHosting:
72 Server::active().remove(*this); // unhook service handler
73 mHostingPort.destroy(); // destroy receive right
74 mHostingState = noHosting;
75 mHostingPort = MACH_PORT_NULL;
76 mGuests.erase(mGuests.begin(), mGuests.end());
77 secnotice("SS", "%d host unregister", mHostingPort.port());
78 break;
79 }
80 }
81
82
83 //
84 // Given a host reference (possibly NULL for the process itself), locate
85 // its most dedicated guest. This descends a contiguous chain of dedicated
86 // guests until it find a host that either has no guests, or whose guests
87 // are not dedicated.
88 //
89 CodeSigningHost::Guest *CodeSigningHost::findHost(SecGuestRef hostRef)
90 {
91 Guest *host = findGuest(hostRef, true);
92 for (;;) {
93 if (Guest *guest = findGuest(host))
94 if (guest->dedicated) {
95 host = guest;
96 continue;
97 }
98 return host;
99 }
100 }
101
102
103 //
104 // Look up guest by guestRef.
105 // Throws if we don't have a guest by that ref.
106 //
107 CodeSigningHost::Guest *CodeSigningHost::findGuest(SecGuestRef guestRef, bool hostOk /* = false */)
108 {
109 GuestMap::iterator it = mGuests.find(guestRef);
110 if (it == mGuests.end()) {
111 if (hostOk) {
112 return NULL;
113 } else {
114 MacOSError::throwMe(errSecCSNoSuchCode);
115 }
116 }
117 assert(it->first == it->second->guestRef());
118 return it->second;
119 }
120
121
122 //
123 // Look up guest by attribute set.
124 // Returns the host if the attributes can't be found (*loose* interpretation).
125 // Throws if multiple guests are found (ambiguity).
126 // Implicitly matches dedicated guests no matter what attributes are requested.
127 //
128 CodeSigningHost::Guest *CodeSigningHost::findGuest(Guest *host, const CssmData &attrData)
129 {
130 CFRef<CFDictionaryRef> attrDict = attrData
131 ? makeCFDictionaryFrom(attrData.data(), attrData.length())
132 : makeCFDictionary(0);
133 CFDictionary attrs(attrDict, errSecCSInvalidAttributeValues);
134
135 // if a guest handle was provided, start with that - it must be valid or we fail
136 if (CFNumberRef canonical = attrs.get<CFNumberRef>(kSecGuestAttributeCanonical)) {
137 // direct lookup by SecGuestRef (canonical guest handle)
138 SecGuestRef guestRef = cfNumber<SecGuestRef>(canonical);
139 if (Guest *guest = findGuest(guestRef, true)) // found guest handle
140 if (guest->isGuestOf(host, loose))
141 host = guest; // new starting point
142 else
143 MacOSError::throwMe(errSecCSNoSuchCode); // not a guest of given host
144 else
145 MacOSError::throwMe(errSecCSNoSuchCode); // not there at all
146 }
147
148 // now take the rest of the attrs
149 CFIndex count = CFDictionaryGetCount(attrs);
150 CFTypeRef keys[count], values[count];
151 CFDictionaryGetKeysAndValues(attrs, keys, values);
152 for (;;) {
153 Guest *match = NULL; // previous match found
154 for (GuestMap::const_iterator it = mGuests.begin(); it != mGuests.end(); ++it) {
155 if (it->second->isGuestOf(host, strict)) {
156 if (it->second->matches(count, keys, values)) {
157 if (match) {
158 MacOSError::throwMe(errSecCSMultipleGuests); // ambiguous
159 } else {
160 match = it->second;
161 }
162 }
163 }
164 }
165 if (!match) // nothing found
166 return host;
167 else
168 host = match; // and repeat
169 }
170 }
171
172
173 //
174 // Find any guest of a given host.
175 // This will return a randomly chosen guest of this host if it has any,
176 // or NULL if it has none (i.e. it is not a host).
177 //
178 CodeSigningHost::Guest *CodeSigningHost::findGuest(Guest *host)
179 {
180 for (GuestMap::const_iterator it = mGuests.begin(); it != mGuests.end(); ++it)
181 if (it->second->isGuestOf(host, strict))
182 return it->second;
183 return NULL;
184 }
185
186
187 //
188 // Register a hosting API service port where the host will dynamically
189 // answer hosting queries from interested parties. This switches the process
190 // to dynamic hosting mode, and is incompatible with proxy hosting.
191 //
192 void CodeSigningHost::registerCodeSigning(mach_port_t hostingPort, SecCSFlags flags)
193 {
194 StLock<Mutex> _(mLock);
195 switch (mHostingState) {
196 case noHosting:
197 mHostingPort = hostingPort;
198 mHostingState = dynamicHosting;
199 secnotice("SS", "%d host register: %d", mHostingPort.port(), mHostingPort.port());
200 break;
201 default:
202 MacOSError::throwMe(errSecCSHostProtocolContradiction);
203 }
204 }
205
206
207 //
208 // Create a guest entry for the given host and prepare to answer for it
209 // when dynamic hosting queries are received for it.
210 // This engages proxy hosting mode, and is incompatible with dynamic hosting mode.
211 //
212 SecGuestRef CodeSigningHost::createGuest(SecGuestRef hostRef,
213 uint32_t status, const char *path,
214 const CssmData &cdhash, const CssmData &attributes, SecCSFlags flags)
215 {
216 StLock<Mutex> _(mLock);
217 if (path[0] != '/') // relative path (relative to what? :-)
218 MacOSError::throwMe(errSecCSHostProtocolRelativePath);
219 if (cdhash.length() > maxUcspHashLength)
220 MacOSError::throwMe(errSecCSHostProtocolInvalidHash);
221
222 // set up for hosting proxy services if nothing's there yet
223 switch (mHostingState) {
224 case noHosting: // first hosting call, this host
225 // set up proxy hosting
226 mHostingPort.allocate(); // allocate service port
227 MachServer::Handler::port(mHostingPort); // put into Handler
228 MachServer::active().add(*this); // start listening
229 mHostingState = proxyHosting; // now proxying for this host
230 secnotice("SS", "%d host proxy: %d", mHostingPort.port(), mHostingPort.port());
231 break;
232 case proxyHosting: // already proxying
233 break;
234 case dynamicHosting: // in dynamic mode, can't switch
235 MacOSError::throwMe(errSecCSHostProtocolContradiction);
236 }
237
238 RefPointer<Guest> host = findHost(hostRef);
239 if (RefPointer<Guest> knownGuest = findGuest(host)) { // got a guest already
240 if (flags & kSecCSDedicatedHost) {
241 MacOSError::throwMe(errSecCSHostProtocolDedicationError); // can't dedicate with other guests
242 } else if (knownGuest->dedicated) {
243 MacOSError::throwMe(errSecCSHostProtocolDedicationError); // other guest is already dedicated
244 }
245 }
246
247 // create the new guest
248 RefPointer<Guest> guest = new Guest;
249 if (host)
250 guest->guestPath = host->guestPath;
251 guest->guestPath.push_back(int_cast<CSSM_HANDLE,SecGuestRef>(guest->handle()));
252 guest->status = status;
253 guest->path = path;
254 guest->setAttributes(attributes);
255 guest->setHash(cdhash, flags & kSecCSGenerateGuestHash);
256 guest->dedicated = (flags & kSecCSDedicatedHost);
257 mGuests[guest->guestRef()] = guest;
258 secnotice("SS", "%d guest create %d %d status:%d %d %s", mHostingPort.port(), hostRef, guest->guestRef(), guest->status, flags, guest->path.c_str());
259 return guest->guestRef();
260 }
261
262
263 void CodeSigningHost::setGuestStatus(SecGuestRef guestRef, uint32_t status, const CssmData &attributes)
264 {
265 StLock<Mutex> _(mLock);
266 if (mHostingState != proxyHosting)
267 MacOSError::throwMe(errSecCSHostProtocolNotProxy);
268 Guest *guest = findGuest(guestRef);
269
270 // state modification machine
271 if ((status & ~guest->status) & kSecCodeStatusValid)
272 MacOSError::throwMe(errSecCSHostProtocolStateError); // can't set
273 if ((~status & guest->status) & (kSecCodeStatusHard | kSecCodeStatusKill))
274 MacOSError::throwMe(errSecCSHostProtocolStateError); // can't clear
275 guest->status = status;
276 secnotice("SS", "%d guest change %d %d", mHostingPort.port(), guestRef, status);
277
278 // replace attributes if requested
279 if (attributes)
280 guest->setAttributes(attributes);
281 }
282
283
284 //
285 // Remove a guest previously introduced via createGuest().
286 //
287 void CodeSigningHost::removeGuest(SecGuestRef hostRef, SecGuestRef guestRef)
288 {
289 StLock<Mutex> _(mLock);
290 if (mHostingState != proxyHosting)
291 MacOSError::throwMe(errSecCSHostProtocolNotProxy);
292 RefPointer<Guest> host = findHost(hostRef);
293 RefPointer<Guest> guest = findGuest(guestRef);
294 if (guest->dedicated) // can't remove a dedicated guest
295 MacOSError::throwMe(errSecCSHostProtocolDedicationError);
296 if (!guest->isGuestOf(host, strict))
297 MacOSError::throwMe(errSecCSHostProtocolUnrelated);
298
299 set<SecGuestRef> matchingGuests;
300
301 for (auto &it : mGuests) {
302 if (it.second->isGuestOf(guest, loose)) {
303 matchingGuests.insert(it.first);
304 }
305 }
306
307 for (auto &it : matchingGuests) {
308 secnotice("SS", "%d guest destroy %d", mHostingPort.port(), it);
309 mGuests.erase(it);
310 }
311 }
312
313
314 //
315 // The internal Guest object
316 //
317 CodeSigningHost::Guest::~Guest()
318 { }
319
320 void CodeSigningHost::Guest::setAttributes(const CssmData &attrData)
321 {
322 CFRef<CFNumberRef> guest = makeCFNumber(guestRef());
323 if (attrData) {
324 CFDictionaryRef attrs = makeCFDictionaryFrom(attrData.data(), attrData.length());
325 attributes.take(cfmake<CFDictionaryRef>("{+%O,%O=%O}",
326 attrs, kSecGuestAttributeCanonical, guest.get()));
327 CFReleaseNull(attrs);
328 } else {
329 attributes.take(makeCFDictionary(1, kSecGuestAttributeCanonical, guest.get()));
330 }
331 }
332
333 CFDataRef CodeSigningHost::Guest::attrData() const
334 {
335 if (!mAttrData)
336 mAttrData = makeCFData(this->attributes.get());
337 return mAttrData;
338 }
339
340
341 void CodeSigningHost::Guest::setHash(const CssmData &given, bool generate)
342 {
343 if (given.length()) // explicitly given
344 this->cdhash.take(makeCFData(given));
345 else if (CFTypeRef hash = CFDictionaryGetValue(this->attributes, kSecGuestAttributeHash))
346 if (CFGetTypeID(hash) == CFDataGetTypeID())
347 this->cdhash = CFDataRef(hash);
348 else
349 MacOSError::throwMe(errSecCSHostProtocolInvalidHash);
350 else if (generate) { // generate from path (well, try)
351 CFRef<SecStaticCodeRef> code;
352 MacOSError::check(SecStaticCodeCreateWithPath(CFTempURL(this->path), kSecCSDefaultFlags, &code.aref()));
353 CFRef<CFDictionaryRef> info;
354 MacOSError::check(SecCodeCopySigningInformation(code, kSecCSDefaultFlags, &info.aref()));
355 this->cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique));
356 }
357 }
358
359
360 bool CodeSigningHost::Guest::isGuestOf(Guest *host, GuestCheck check) const
361 {
362 vector<SecGuestRef> hostPath;
363 if (host)
364 hostPath = host->guestPath;
365 if (hostPath.size() <= guestPath.size()
366 && !memcmp(&hostPath[0], &guestPath[0], sizeof(SecGuestRef) * hostPath.size()))
367 // hostPath is a prefix of guestPath
368 switch (check) {
369 case loose:
370 return true;
371 case strict:
372 return guestPath.size() == hostPath.size() + 1; // immediate guest
373 }
374 return false;
375 }
376
377
378 //
379 // Check to see if a given guest matches the (possibly empty) attribute set provided
380 // (in broken-open form, for efficiency). A dedicated guest will match all attribute
381 // specifications, even empty ones. A non-dedicated guest matches if at least one
382 // attribute value requested matches exactly (in the sense of CFEqual) that given
383 // by the host for this guest.
384 //
385 bool CodeSigningHost::Guest::matches(CFIndex count, CFTypeRef keys[], CFTypeRef values[]) const
386 {
387 if (dedicated)
388 return true;
389 for (CFIndex n = 0; n < count; n++) {
390 CFStringRef key = CFStringRef(keys[n]);
391 if (CFEqual(key, kSecGuestAttributeCanonical)) // ignore canonical attribute (handled earlier)
392 continue;
393 if (CFTypeRef value = CFDictionaryGetValue(attributes, key))
394 if (CFEqual(value, values[n]))
395 return true;
396 }
397 return false;
398 }
399
400
401 //
402 // The MachServer dispatch handler for proxy hosting.
403 //
404
405 // give MIG handlers access to the object lock
406 class CodeSigningHost::Lock : private StLock<Mutex> {
407 public:
408 Lock(CodeSigningHost *host) : StLock<Mutex>(host->mLock) { }
409 };
410
411
412 boolean_t cshosting_server(mach_msg_header_t *, mach_msg_header_t *);
413
414 static ThreadNexus<CodeSigningHost *> context;
415
416 boolean_t CodeSigningHost::handle(mach_msg_header_t *in, mach_msg_header_t *out)
417 {
418 CodeSigningHost::Lock _(this);
419 context() = this;
420 return cshosting_server(in, out);
421 }
422
423
424 //
425 // Proxy implementation of Code Signing Hosting protocol
426 //
427 #define CSH_ARGS mach_port_t servicePort, mach_port_t replyPort, OSStatus *rcode
428
429 #define BEGIN_IPC try {
430 #define END_IPC *rcode = noErr; } \
431 catch (const CommonError &err) { *rcode = err.osStatus(); } \
432 catch (...) { *rcode = errSecCSInternalError; } \
433 return KERN_SUCCESS;
434
435 #define DATA_IN(base) void *base, mach_msg_type_number_t base##Length
436 #define DATA_OUT(base) void **base, mach_msg_type_number_t *base##Length
437 #define DATA(base) CssmData(base, base##Length)
438
439
440 //
441 // Find a guest by arbitrary attribute set.
442 //
443 // This returns an array of canonical guest references describing the path
444 // from the host given to the guest found. If the host itself is returned
445 // as a guest, this will be an empty array (zero length).
446 //
447 // The subhost return argument may in the future return the hosting port for
448 // a guest who dynamically manages its hosting (thus breaking out of proxy mode),
449 // but this is not yet implemented.
450 //
451 kern_return_t cshosting_server_findGuest(CSH_ARGS, SecGuestRef hostRef,
452 DATA_IN(attributes),
453 GuestChain *foundGuest, mach_msg_type_number_t *depth, mach_port_t *subhost)
454 {
455 BEGIN_IPC
456
457 *subhost = MACH_PORT_NULL; // preset no sub-hosting port returned
458
459 Process::Guest *host = context()->findGuest(hostRef, true);
460 if (Process::Guest *guest = context()->findGuest(host, DATA(attributes))) {
461 *foundGuest = &guest->guestPath[0];
462 *depth = int_cast<size_t, mach_msg_type_number_t>(guest->guestPath.size());
463 } else {
464 *foundGuest = NULL;
465 *depth = 0;
466 }
467 END_IPC
468 }
469
470
471 //
472 // Retrieve the path to a guest specified by canonical reference.
473 //
474 kern_return_t cshosting_server_identifyGuest(CSH_ARGS, SecGuestRef guestRef,
475 char *path, char *hash, uint32_t *hashLength, DATA_OUT(attributes))
476 {
477 BEGIN_IPC
478 CodeSigningHost::Guest *guest = context()->findGuest(guestRef);
479 strncpy(path, guest->path.c_str(), MAXPATHLEN);
480
481 // canonical cdhash
482 if (guest->cdhash) {
483 *hashLength = int_cast<size_t, uint32_t>(CFDataGetLength(guest->cdhash));
484 assert(*hashLength <= maxUcspHashLength);
485 memcpy(hash, CFDataGetBytePtr(guest->cdhash), *hashLength);
486 } else
487 *hashLength = 0; // unavailable
488
489 // visible attributes. This proxy returns all attributes set by the host
490 CFDataRef attrData = guest->attrData(); // (the guest will cache this until it dies)
491 *attributes = (void *)CFDataGetBytePtr(attrData); // MIG botch (it doesn't need a writable pointer)
492 *attributesLength = int_cast<CFIndex, mach_msg_type_number_t>(CFDataGetLength(attrData));
493
494 END_IPC
495 }
496
497
498 //
499 // Retrieve the status word for a guest specified by canonical reference.
500 //
501 kern_return_t cshosting_server_guestStatus(CSH_ARGS, SecGuestRef guestRef, uint32_t *status)
502 {
503 BEGIN_IPC
504 *status = context()->findGuest(guestRef)->status;
505 END_IPC
506 }
507
508
509 //
510 // Debug support
511 //
512 #if defined(DEBUGDUMP)
513
514 void CodeSigningHost::dump() const
515 {
516 StLock<Mutex> _(mLock);
517 switch (mHostingState) {
518 case noHosting:
519 break;
520 case dynamicHosting:
521 Debug::dump(" dynamic host port=%d", mHostingPort.port());
522 break;
523 case proxyHosting:
524 Debug::dump(" proxy-host port=%d", mHostingPort.port());
525 if (!mGuests.empty()) {
526 Debug::dump(" %d guests={", int(mGuests.size()));
527 for (GuestMap::const_iterator it = mGuests.begin(); it != mGuests.end(); ++it) {
528 if (it != mGuests.begin())
529 Debug::dump(", ");
530 it->second->dump();
531 }
532 Debug::dump("}");
533 }
534 break;
535 }
536 }
537
538 void CodeSigningHost::Guest::dump() const
539 {
540 Debug::dump("%s[", path.c_str());
541 for (vector<SecGuestRef>::const_iterator it = guestPath.begin(); it != guestPath.end(); ++it) {
542 if (it != guestPath.begin())
543 Debug::dump("/");
544 Debug::dump("0x%x", *it);
545 }
546 Debug::dump("; status=0x%x attrs=%s]",
547 status, cfStringRelease(CFCopyDescription(attributes)).c_str());
548 }
549
550 #endif //DEBUGDUMP