2 * Copyright (c) 2006-2009,2012,2016 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@
24 // clientid - track and manage identity of securityd clients
28 #include <Security/SecCodePriv.h>
29 #include <Security/oidsattr.h>
30 #include <Security/SecCertificatePriv.h>
34 // Constructing a ClientIdentification doesn't do much.
35 // We're waiting for setup(), which should be called by the child class's
38 ClientIdentification::ClientIdentification()
39 : mGotPartitionId(false)
45 // Initialize the ClientIdentification.
46 // This creates a process-level code object for the client.
48 void ClientIdentification::setup(pid_t pid
)
50 StLock
<Mutex
> _(mLock
);
51 StLock
<Mutex
> __(mValidityCheckLock
);
52 OSStatus rc
= SecCodeCreateWithPID(pid
, kSecCSDefaultFlags
, &mClientProcess
.aref());
54 secinfo("clientid", "could not get code for process %d: OSStatus=%d",
56 mGuests
.erase(mGuests
.begin(), mGuests
.end());
61 // Return a SecCodeRef for the client process itself, regardless of
62 // which guest within it is currently active.
63 // Think twice before using this.
65 SecCodeRef
ClientIdentification::processCode() const
67 return mClientProcess
;
72 // Return a SecCodeRef for the currently active guest within the client
75 // We make a fair effort to cache client guest identities without over-growing
76 // the cache. Note that there's currently no protocol for being notified of
77 // a guest's death or disappearance (independent from the host process's death),
78 // so we couldn't track guests live even if we tried.
80 // Note that this consults Server::connection for the currently serviced
81 // Connection object, so this is not entirely a function of ClientIdentification state.
83 SecCodeRef
ClientIdentification::currentGuest() const
85 if (GuestState
*guest
= current())
88 return mClientProcess
;
91 ClientIdentification::GuestState
*ClientIdentification::current() const
93 // if we have no client identification, we can't find a current guest either
97 SecGuestRef guestRef
= Server::connection().guestRef();
99 // try to deliver an already-cached entry
101 StLock
<Mutex
> _(mLock
);
102 GuestMap::iterator it
= mGuests
.find(guestRef
);
103 if (it
!= mGuests
.end())
107 // okay, make a new one (this may take a while)
108 CFRef
<CFDictionaryRef
> attributes
= (guestRef
== kSecNoGuest
)
110 : makeCFDictionary(1, kSecGuestAttributeCanonical
, CFTempNumber(guestRef
).get());
111 Server::active().longTermActivity();
112 CFRef
<SecCodeRef
> code
;
113 switch (OSStatus rc
= SecCodeCopyGuestWithAttributes(processCode(),
114 attributes
, kSecCSDefaultFlags
, &code
.aref())) {
117 case errSecCSUnsigned
: // not signed; clearly not a host
118 case errSecCSNotAHost
: // signed but not marked as a (potential) host
119 code
= mClientProcess
;
121 case errSecCSNoSuchCode
: // potential host, but...
122 if (guestRef
== kSecNoGuest
) { // ... no guests (yet), so return the process
123 code
= mClientProcess
;
126 // else fall through // ... the guest we expected to be there isn't
128 MacOSError::throwMe(rc
);
130 StLock
<Mutex
> _(mLock
);
131 GuestState
&slot
= mGuests
[guestRef
];
132 if (!slot
.code
) // if another thread didn't get here first...
139 // Return the partition id ascribed to this client.
140 // This is assigned to the whole client process - it is not per-guest.
142 std::string
ClientIdentification::partitionId() const
144 if (!mGotPartitionId
) {
145 StLock
<Mutex
> _(mValidityCheckLock
);
146 mClientPartitionId
= partitionIdForProcess(processCode());
147 mGotPartitionId
= true;
149 return mClientPartitionId
;
153 static std::string
hashString(CFDataRef data
)
155 CFIndex length
= CFDataGetLength(data
);
156 const unsigned char *hash
= CFDataGetBytePtr(data
);
157 char s
[2 * length
+ 1];
158 for (CFIndex n
= 0; n
< length
; n
++)
159 sprintf(&s
[2*n
], "%2.2x", hash
[n
]);
164 std::string
ClientIdentification::partitionIdForProcess(SecStaticCodeRef code
)
166 static CFStringRef
const appleReq
= CFSTR("anchor apple");
167 static CFStringRef
const masReq
= CFSTR("anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.9]");
168 static CFStringRef
const developmentOrDevIDReq
= CFSTR("anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] and certificate leaf[field.1.2.840.113635.100.6.1.13]" // Developer ID CA and Leaf
170 "anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.1] and certificate leaf[field.1.2.840.113635.100.6.1.12]" // WWDR CA and Mac Development Leaf
172 "anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.1] and certificate leaf[field.1.2.840.113635.100.6.1.7]"); // WWDR CA and Mac Distribution Leaf
173 static SecRequirementRef apple
;
174 static SecRequirementRef mas
;
175 static SecRequirementRef developmentOrDevID
;
176 static dispatch_once_t onceToken
;
177 dispatch_once(&onceToken
, ^{
178 if (noErr
!= SecRequirementCreateWithString(appleReq
, kSecCSDefaultFlags
, &apple
)
179 || noErr
!= SecRequirementCreateWithString(masReq
, kSecCSDefaultFlags
, &mas
)
180 || noErr
!= SecRequirementCreateWithString(developmentOrDevIDReq
, kSecCSDefaultFlags
, &developmentOrDevID
))
185 switch (rc
= SecStaticCodeCheckValidity(code
, kSecCSBasicValidateOnly
, apple
)) {
187 case errSecCSReqFailed
:
189 case errSecCSUnsigned
:
192 MacOSError::throwMe(rc
);
194 CFRef
<CFDictionaryRef
> info
;
195 if (OSStatus irc
= SecCodeCopySigningInformation(code
, kSecCSSigningInformation
, &info
.aref()))
196 MacOSError::throwMe(irc
);
199 // for apple-signed code, make it canonical apple
200 if (CFEqual(CFDictionaryGetValue(info
, kSecCodeInfoIdentifier
), CFSTR("com.apple.security"))) {
201 return "apple-tool:"; // take security(1) into a separate partition so it can't automatically peek into Apple's own
205 } else if (noErr
== SecStaticCodeCheckValidity(code
, kSecCSBasicValidateOnly
, mas
)) {
206 // for MAS-signed code, we take the embedded team identifier (verified by Apple)
207 return "teamid:" + cfString(CFStringRef(CFDictionaryGetValue(info
, kSecCodeInfoTeamIdentifier
)));
208 } else if (noErr
== SecStaticCodeCheckValidity(code
, kSecCSBasicValidateOnly
, developmentOrDevID
)) {
209 // for developer-signed code, we take the team identifier from the signing certificate's OU field
210 CFRef
<CFDictionaryRef
> info
;
211 if (noErr
!= (rc
= SecCodeCopySigningInformation(code
, kSecCSSigningInformation
, &info
.aref())))
212 MacOSError::throwMe(rc
);
213 CFArrayRef certChain
= CFArrayRef(CFDictionaryGetValue(info
, kSecCodeInfoCertificates
));
214 SecCertificateRef signingCert
= SecCertificateRef(CFArrayGetValueAtIndex(certChain
, 0));
215 CFRef
<CFStringRef
> ou
;
216 SecCertificateCopySubjectComponent(signingCert
, &CSSMOID_OrganizationalUnitName
, &ou
.aref());
217 return "teamid:" + cfString(ou
);
219 // cannot positively classify this code, but it's signed
220 CFDataRef cdhashData
= CFDataRef(CFDictionaryGetValue(info
, kSecCodeInfoUnique
));
222 return "cdhash:" + hashString(cdhashData
);
228 // Support for the legacy hash identification mechanism.
229 // The legacy machinery deals exclusively in terms of processes.
230 // It knows nothing about guests and their identities.
232 string
ClientIdentification::getPath() const
234 assert(mClientProcess
);
235 StLock
<Mutex
> _(mValidityCheckLock
);
236 return codePath(currentGuest());
239 const CssmData
ClientIdentification::getHash() const
241 if (GuestState
*guest
= current()) {
242 if (!guest
->gotHash
) {
243 RefPointer
<OSXCode
> clientCode
= new OSXCodeWrap(guest
->code
);
244 OSXVerifier::makeLegacyHash(clientCode
, guest
->legacyHash
);
245 guest
->gotHash
= true;
247 return CssmData::wrap(guest
->legacyHash
, SHA1::digestLength
);
252 AclSubject
* ClientIdentification::copyAclSubject() const
254 StLock
<Mutex
> _(mValidityCheckLock
);
255 RefPointer
<OSXCode
> clientXCode
= new OSXCodeWrap(currentGuest());
256 return new CodeSignatureAclSubject(OSXVerifier(clientXCode
));
259 OSStatus
ClientIdentification::copySigningInfo(SecCSFlags flags
,
260 CFDictionaryRef
*info
) const
262 StLock
<Mutex
> _(mValidityCheckLock
);
263 return SecCodeCopySigningInformation(currentGuest(), flags
, info
);
266 OSStatus
ClientIdentification::checkValidity(SecCSFlags flags
,
267 SecRequirementRef requirement
) const
269 // Make sure more than one thread cannot be evaluating this code signature concurrently
270 StLock
<Mutex
> _(mValidityCheckLock
);
271 return SecCodeCheckValidityWithErrors(currentGuest(), flags
, requirement
, NULL
);
274 bool ClientIdentification::checkAppleSigned() const
276 // This is the clownfish supported way to check for a Mac App Store or B&I signed build
277 static CFStringRef
const requirementString
= CFSTR("(anchor apple) or (anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.9])");
278 CFRef
<SecRequirementRef
> secRequirementRef
= NULL
;
279 OSStatus status
= SecRequirementCreateWithString(requirementString
, kSecCSDefaultFlags
, &secRequirementRef
.aref());
280 if (status
== errSecSuccess
) {
281 status
= checkValidity(kSecCSDefaultFlags
, secRequirementRef
);
282 if (status
!= errSecSuccess
) {
283 secnotice("clientid", "code requirement check failed (%d), client is not Apple-signed", (int32_t)status
);
292 bool ClientIdentification::hasEntitlement(const char *name
) const
294 CFRef
<CFDictionaryRef
> info
;
296 StLock
<Mutex
> _(mValidityCheckLock
);
297 MacOSError::check(SecCodeCopySigningInformation(processCode(), kSecCSDefaultFlags
, &info
.aref()));
299 CFCopyRef
<CFDictionaryRef
> entitlements
= (CFDictionaryRef
)CFDictionaryGetValue(info
, kSecCodeInfoEntitlementsDict
);
300 if (entitlements
&& entitlements
.is
<CFDictionaryRef
>()) {
301 CFTypeRef value
= CFDictionaryGetValue(entitlements
, CFTempString(name
));
302 if (value
&& value
!= kCFBooleanFalse
)
303 return true; // have entitlement, it's not <false/> - bypass partition construction
310 // Bonus function: get the path out of a SecCodeRef
312 std::string
codePath(SecStaticCodeRef code
)
314 CFRef
<CFURLRef
> path
;
315 MacOSError::check(SecCodeCopyPath(code
, kSecCSDefaultFlags
, &path
.aref()));
316 return cfString(path
);
321 // Debug dump support
323 #if defined(DEBUGDUMP)
325 static void dumpCode(SecCodeRef code
)
327 CFRef
<CFURLRef
> path
;
328 if (OSStatus rc
= SecCodeCopyPath(code
, kSecCSDefaultFlags
, &path
.aref()))
329 Debug::dump("unknown(rc=%d)", int32_t(rc
));
331 Debug::dump("%s", cfString(path
).c_str());
334 void ClientIdentification::dump()
336 Debug::dump(" client=");
337 dumpCode(mClientProcess
);
338 for (GuestMap::const_iterator it
= mGuests
.begin(); it
!= mGuests
.end(); ++it
) {
339 Debug::dump(" guest(0x%x)=", it
->first
);
340 dumpCode(it
->second
.code
);
341 if (it
->second
.gotHash
)
342 Debug::dump(" [got hash]");