2 * Copyright (c) 2006-2007 Apple 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 // csproxy - Code Signing Hosting Proxy
30 #include <Security/SecStaticCode.h>
31 #include <securityd_client/cshosting.h>
32 #include <security_utilities/cfmunge.h>
36 // Construct a CodeSigningHost
38 CodeSigningHost::CodeSigningHost()
39 : mHostingState(noHosting
)
47 CodeSigningHost::~CodeSigningHost()
54 // Reset Code Signing Hosting state.
55 // This turns hosting off and clears all children.
57 void CodeSigningHost::reset()
59 switch (mHostingState
) {
61 break; // nothing to do
63 mHostingPort
.destroy();
64 mHostingPort
= MACH_PORT_NULL
;
65 SECURITYD_HOST_UNREGISTER(DTSELF
);
68 Server::active().remove(*this); // unhook service handler
69 mHostingPort
.destroy(); // destroy receive right
70 mHostingState
= noHosting
;
71 mHostingPort
= MACH_PORT_NULL
;
72 mGuests
.erase(mGuests
.begin(), mGuests
.end());
73 SECURITYD_HOST_UNREGISTER(DTSELF
);
80 // Given a host reference (possibly NULL for the process itself), locate
81 // its most dedicated guest. This descends a contiguous chain of dedicated
82 // guests until it find a host that either has no guests, or whose guests
85 CodeSigningHost::Guest
*CodeSigningHost::findHost(SecGuestRef hostRef
)
87 Guest
*host
= findGuest(hostRef
, true);
89 if (Guest
*guest
= findGuest(host
))
90 if (guest
->dedicated
) {
100 // Look up guest by guestRef.
101 // Throws if they we don't have a guest by that ref.
103 CodeSigningHost::Guest
*CodeSigningHost::findGuest(SecGuestRef guestRef
, bool hostOk
/* = false */)
105 GuestMap::iterator it
= mGuests
.find(guestRef
);
106 if (it
== mGuests
.end())
110 MacOSError::throwMe(errSecCSNoSuchCode
);
111 assert(it
->first
== it
->second
->guestRef());
117 // Look up guest by attribute set.
118 // Returns the host if the attributes can't be found (*loose* interpretation).
119 // Throws if multiple guests are found (ambiguity).
120 // Implicitly matches dedicated guests no matter what attributes are requested.
122 CodeSigningHost::Guest
*CodeSigningHost::findGuest(Guest
*host
, const CssmData
&attrData
)
124 CFRef
<CFDictionaryRef
> attrDict
= attrData
125 ? makeCFDictionaryFrom(attrData
.data(), attrData
.length())
126 : makeCFDictionary(0);
127 CFDictionary
attrs(attrDict
, errSecCSInvalidAttributeValues
);
129 // if a guest handle was provided, start with that - it must be valid or we fail
130 if (CFNumberRef canonical
= attrs
.get
<CFNumberRef
>(kSecGuestAttributeCanonical
)) {
131 // direct lookup by SecGuestRef (canonical guest handle)
132 SecGuestRef guestRef
= cfNumber
<SecGuestRef
>(canonical
);
133 if (Guest
*guest
= findGuest(guestRef
, true)) // found guest handle
134 if (guest
->isGuestOf(host
, loose
))
135 host
= guest
; // new starting point
137 MacOSError::throwMe(errSecCSNoSuchCode
); // not a guest of given host
139 MacOSError::throwMe(errSecCSNoSuchCode
); // not there at all
142 // now take the rest of the attrs
143 CFIndex count
= CFDictionaryGetCount(attrs
);
144 CFTypeRef keys
[count
], values
[count
];
145 CFDictionaryGetKeysAndValues(attrs
, keys
, values
);
147 Guest
*match
= NULL
; // previous match found
148 for (GuestMap::const_iterator it
= mGuests
.begin(); it
!= mGuests
.end(); ++it
)
149 if (it
->second
->isGuestOf(host
, strict
))
150 if (it
->second
->matches(count
, keys
, values
))
152 MacOSError::throwMe(errSecCSMultipleGuests
); // ambiguous
155 if (!match
) // nothing found
158 host
= match
; // and repeat
164 // Find any guest of a given host.
165 // This will return a randomly chosen guest of this host if it has any,
166 // or NULL if it has none (i.e. it is not a host).
168 CodeSigningHost::Guest
*CodeSigningHost::findGuest(Guest
*host
)
170 for (GuestMap::const_iterator it
= mGuests
.begin(); it
!= mGuests
.end(); ++it
)
171 if (it
->second
->isGuestOf(host
, strict
))
178 // Register a hosting API service port where the host will dynamically
179 // answer hosting queries from interested parties. This switches the process
180 // to dynamic hosting mode, and is incompatible with proxy hosting.
182 void CodeSigningHost::registerCodeSigning(mach_port_t hostingPort
, SecCSFlags flags
)
184 switch (mHostingState
) {
186 mHostingPort
= hostingPort
;
187 mHostingState
= dynamicHosting
;
188 SECURITYD_HOST_REGISTER(DTSELF
, mHostingPort
);
191 MacOSError::throwMe(errSecCSHostProtocolContradiction
);
197 // Create a guest entry for the given host and prepare to answer for it
198 // when dynamic hosting queries are received for it.
199 // This engages proxy hosting mode, and is incompatible with dynamic hosting mode.
201 SecGuestRef
CodeSigningHost::createGuest(SecGuestRef hostRef
,
202 uint32_t status
, const char *path
,
203 const CssmData
&cdhash
, const CssmData
&attributes
, SecCSFlags flags
)
205 if (path
[0] != '/') // relative path (relative to what? :-)
206 MacOSError::throwMe(errSecCSHostProtocolRelativePath
);
207 if (cdhash
.length() > maxUcspHashLength
)
208 MacOSError::throwMe(errSecCSHostProtocolInvalidHash
);
210 // set up for hosting proxy services if nothing's there yet
211 switch (mHostingState
) {
212 case noHosting
: // first hosting call, this host
213 // set up proxy hosting
214 mHostingPort
.allocate(); // allocate service port
215 MachServer::Handler::port(mHostingPort
); // put into Handler
216 MachServer::active().add(*this); // start listening
217 mHostingState
= proxyHosting
; // now proxying for this host
218 SECURITYD_HOST_PROXY(DTSELF
, mHostingPort
);
220 case proxyHosting
: // already proxying
222 case dynamicHosting
: // in dynamic mode, can't switch
223 MacOSError::throwMe(errSecCSHostProtocolContradiction
);
226 RefPointer
<Guest
> host
= findHost(hostRef
);
227 if (RefPointer
<Guest
> knownGuest
= findGuest(host
)) // got a guest already
228 if (flags
& kSecCSDedicatedHost
)
229 MacOSError::throwMe(errSecCSHostProtocolDedicationError
); // can't dedicate with other guests
230 else if (knownGuest
->dedicated
)
231 MacOSError::throwMe(errSecCSHostProtocolDedicationError
); // other guest is already dedicated
233 // create the new guest
234 RefPointer
<Guest
> guest
= new Guest
;
236 guest
->guestPath
= host
->guestPath
;
237 guest
->guestPath
.push_back(guest
->handle());
238 guest
->status
= status
;
240 guest
->setAttributes(attributes
);
241 guest
->setHash(cdhash
, flags
& kSecCSGenerateGuestHash
);
242 guest
->dedicated
= (flags
& kSecCSDedicatedHost
);
243 mGuests
[guest
->guestRef()] = guest
;
244 SECURITYD_GUEST_CREATE(DTSELF
, hostRef
, guest
->guestRef(), guest
->status
, flags
, (char *)guest
->path
.c_str());
245 if (SECURITYD_GUEST_CDHASH_ENABLED())
246 SECURITYD_GUEST_CDHASH(DTSELF
, guest
->guestRef(),
247 (void*)CFDataGetBytePtr(guest
->cdhash
), CFDataGetLength(guest
->cdhash
));
248 return guest
->guestRef();
252 void CodeSigningHost::setGuestStatus(SecGuestRef guestRef
, uint32_t status
, const CssmData
&attributes
)
254 if (mHostingState
!= proxyHosting
)
255 MacOSError::throwMe(errSecCSHostProtocolNotProxy
);
256 Guest
*guest
= findGuest(guestRef
);
258 // state modification machine
259 if ((status
& ~guest
->status
) & kSecCodeStatusValid
)
260 MacOSError::throwMe(errSecCSHostProtocolStateError
); // can't set
261 if ((~status
& guest
->status
) & (kSecCodeStatusHard
| kSecCodeStatusKill
))
262 MacOSError::throwMe(errSecCSHostProtocolStateError
); // can't clear
263 guest
->status
= status
;
264 SECURITYD_GUEST_CHANGE(DTSELF
, guestRef
, status
);
266 // replace attributes if requested
268 guest
->setAttributes(attributes
);
273 // Remove a guest previously introduced via createGuest().
275 void CodeSigningHost::removeGuest(SecGuestRef hostRef
, SecGuestRef guestRef
)
277 if (mHostingState
!= proxyHosting
)
278 MacOSError::throwMe(errSecCSHostProtocolNotProxy
);
279 RefPointer
<Guest
> host
= findHost(hostRef
);
280 RefPointer
<Guest
> guest
= findGuest(guestRef
);
281 if (guest
->dedicated
) // can't remove a dedicated guest
282 MacOSError::throwMe(errSecCSHostProtocolDedicationError
);
283 if (!guest
->isGuestOf(host
, strict
))
284 MacOSError::throwMe(errSecCSHostProtocolUnrelated
);
285 for (GuestMap::iterator it
= mGuests
.begin(); it
!= mGuests
.end(); ++it
)
286 if (it
->second
->isGuestOf(guest
, loose
)) {
287 SECURITYD_GUEST_DESTROY(DTSELF
, it
->first
);
294 // The internal Guest object
296 CodeSigningHost::Guest::~Guest()
299 void CodeSigningHost::Guest::setAttributes(const CssmData
&attrData
)
301 CFRef
<CFNumberRef
> guest
= makeCFNumber(guestRef());
303 attributes
.take(cfmake
<CFDictionaryRef
>("{+%O,%O=%O}",
304 makeCFDictionaryFrom(attrData
.data(), attrData
.length()), kSecGuestAttributeCanonical
, guest
.get()));
306 attributes
.take(makeCFDictionary(1, kSecGuestAttributeCanonical
, guest
.get()));
310 CFDataRef
CodeSigningHost::Guest::attrData() const
313 mAttrData
= makeCFData(this->attributes
.get());
318 void CodeSigningHost::Guest::setHash(const CssmData
&given
, bool generate
)
320 if (given
.length()) // explicitly given
321 this->cdhash
.take(makeCFData(given
));
322 else if (CFTypeRef hash
= CFDictionaryGetValue(this->attributes
, kSecGuestAttributeHash
))
323 if (CFGetTypeID(hash
) == CFDataGetTypeID())
324 this->cdhash
= CFDataRef(hash
);
326 MacOSError::throwMe(errSecCSHostProtocolInvalidHash
);
327 else if (generate
) { // generate from path (well, try)
328 CFRef
<SecStaticCodeRef
> code
;
329 MacOSError::check(SecStaticCodeCreateWithPath(CFTempURL(this->path
), kSecCSDefaultFlags
, &code
.aref()));
330 CFRef
<CFDictionaryRef
> info
;
331 MacOSError::check(SecCodeCopySigningInformation(code
, kSecCSDefaultFlags
, &info
.aref()));
332 this->cdhash
= CFDataRef(CFDictionaryGetValue(info
, kSecCodeInfoUnique
));
337 bool CodeSigningHost::Guest::isGuestOf(Guest
*host
, GuestCheck check
) const
339 vector
<SecGuestRef
> hostPath
;
341 hostPath
= host
->guestPath
;
342 if (hostPath
.size() <= guestPath
.size()
343 && !memcmp(&hostPath
[0], &guestPath
[0], sizeof(SecGuestRef
) * hostPath
.size()))
344 // hostPath is a prefix of guestPath
349 return guestPath
.size() == hostPath
.size() + 1; // immediate guest
356 // Check to see if a given guest matches the (possibly empty) attribute set provided
357 // (in broken-open form, for efficiency). A dedicated guest will match all attribute
358 // specifications, even empty ones. A non-dedicated guest matches if at least one
359 // attribute value requested matches exactly (in the sense of CFEqual) that given
360 // by the host for this guest.
362 bool CodeSigningHost::Guest::matches(CFIndex count
, CFTypeRef keys
[], CFTypeRef values
[]) const
366 for (CFIndex n
= 0; n
< count
; n
++) {
367 CFStringRef key
= CFStringRef(keys
[n
]);
368 if (CFEqual(key
, kSecGuestAttributeCanonical
)) // ignore canonical attribute (handled earlier)
370 if (CFTypeRef value
= CFDictionaryGetValue(attributes
, key
))
371 if (CFEqual(value
, values
[n
]))
379 // The MachServer dispatch handler for proxy hosting.
381 boolean_t
cshosting_server(mach_msg_header_t
*, mach_msg_header_t
*);
383 static ThreadNexus
<CodeSigningHost
*> context
;
385 boolean_t
CodeSigningHost::handle(mach_msg_header_t
*in
, mach_msg_header_t
*out
)
388 return cshosting_server(in
, out
);
393 // Proxy implementation of Code Signing Hosting protocol
395 #define CSH_ARGS mach_port_t servicePort, mach_port_t replyPort, OSStatus *rcode
397 #define BEGIN_IPC try {
398 #define END_IPC *rcode = noErr; } \
399 catch (const CommonError &err) { *rcode = err.osStatus(); } \
400 catch (...) { *rcode = errSecCSInternalError; } \
403 #define DATA_IN(base) void *base, mach_msg_type_number_t base##Length
404 #define DATA_OUT(base) void **base, mach_msg_type_number_t *base##Length
405 #define DATA(base) CssmData(base, base##Length)
409 // Find a guest by arbitrary attribute set.
411 // This returns an array of canonical guest references describing the path
412 // from the host given to the guest found. If the host itself is returned
413 // as a guest, this will be an empty array (zero length).
415 // The subhost return argument may in the future return the hosting port for
416 // a guest who dynamically manages its hosting (thus breaking out of proxy mode),
417 // but this is not yet implemented.
419 kern_return_t
cshosting_server_findGuest(CSH_ARGS
, SecGuestRef hostRef
,
421 GuestChain
*foundGuest
, mach_msg_type_number_t
*depth
, mach_port_t
*subhost
)
425 *subhost
= MACH_PORT_NULL
; // preset no sub-hosting port returned
427 Process::Guest
*host
= context()->findGuest(hostRef
, true);
428 if (Process::Guest
*guest
= context()->findGuest(host
, DATA(attributes
))) {
429 *foundGuest
= &guest
->guestPath
[0];
430 *depth
= guest
->guestPath
.size();
440 // Retrieve the path to a guest specified by canonical reference.
442 kern_return_t
cshosting_server_identifyGuest(CSH_ARGS
, SecGuestRef guestRef
,
443 char *path
, char *hash
, uint32_t *hashLength
, DATA_OUT(attributes
))
446 CodeSigningHost::Guest
*guest
= context()->findGuest(guestRef
);
447 strncpy(path
, guest
->path
.c_str(), MAXPATHLEN
);
451 *hashLength
= CFDataGetLength(guest
->cdhash
);
452 assert(*hashLength
<= maxUcspHashLength
);
453 memcpy(hash
, CFDataGetBytePtr(guest
->cdhash
), *hashLength
);
455 *hashLength
= 0; // unavailable
457 // visible attributes. This proxy returns all attributes set by the host
458 CFDataRef attrData
= guest
->attrData(); // (the guest will cache this until it dies)
459 *attributes
= (void *)CFDataGetBytePtr(attrData
); // MIG botch (it doesn't need a writable pointer)
460 *attributesLength
= CFDataGetLength(attrData
);
467 // Retrieve the status word for a guest specified by canonical reference.
469 kern_return_t
cshosting_server_guestStatus(CSH_ARGS
, SecGuestRef guestRef
, uint32_t *status
)
472 *status
= context()->findGuest(guestRef
)->status
;
480 #if defined(DEBUGDUMP)
482 void CodeSigningHost::dump() const
484 switch (mHostingState
) {
488 Debug::dump(" dynamic host port=%d", mHostingPort
.port());
491 Debug::dump(" proxy-host port=%d", mHostingPort
.port());
492 if (!mGuests
.empty()) {
493 Debug::dump(" %d guests={", int(mGuests
.size()));
494 for (GuestMap::const_iterator it
= mGuests
.begin(); it
!= mGuests
.end(); ++it
) {
495 if (it
!= mGuests
.begin())
505 void CodeSigningHost::Guest::dump() const
507 Debug::dump("%s[", path
.c_str());
508 for (vector
<SecGuestRef
>::const_iterator it
= guestPath
.begin(); it
!= guestPath
.end(); ++it
) {
509 if (it
!= guestPath
.begin())
511 Debug::dump("0x%x", *it
);
513 Debug::dump("; status=0x%x attrs=%s]",
514 status
, cfString(CFCopyDescription(attributes
), true).c_str());