]> git.saurik.com Git - apple/security.git/blob - securityd/src/clientid.cpp
Security-58286.200.222.tar.gz
[apple/security.git] / securityd / src / clientid.cpp
1 /*
2 * Copyright (c) 2006-2009,2012,2016 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 // clientid - track and manage identity of securityd clients
25 //
26 #include "clientid.h"
27 #include "server.h"
28 #include <Security/SecCodePriv.h>
29 #include <Security/oidsattr.h>
30 #include <Security/SecCertificatePriv.h>
31
32
33 //
34 // Constructing a ClientIdentification doesn't do much.
35 // We're waiting for setup(), which should be called by the child class's
36 // constructor.
37 //
38 ClientIdentification::ClientIdentification()
39 : mGotPartitionId(false)
40 {
41 }
42
43
44 //
45 // Initialize the ClientIdentification.
46 // This creates a process-level code object for the client.
47 //
48 void ClientIdentification::setup(pid_t pid)
49 {
50 StLock<Mutex> _(mLock);
51 StLock<Mutex> __(mValidityCheckLock);
52 OSStatus rc = SecCodeCreateWithPID(pid, kSecCSDefaultFlags, &mClientProcess.aref());
53 if (rc)
54 secinfo("clientid", "could not get code for process %d: OSStatus=%d",
55 pid, int32_t(rc));
56 mGuests.erase(mGuests.begin(), mGuests.end());
57 }
58
59
60 //
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.
64 //
65 SecCodeRef ClientIdentification::processCode() const
66 {
67 return mClientProcess;
68 }
69
70
71 //
72 // Return a SecCodeRef for the currently active guest within the client
73 // process.
74 //
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.
79 //
80 // Note that this consults Server::connection for the currently serviced
81 // Connection object, so this is not entirely a function of ClientIdentification state.
82 //
83 SecCodeRef ClientIdentification::currentGuest() const
84 {
85 if (GuestState *guest = current())
86 return guest->code;
87 else
88 return mClientProcess;
89 }
90
91 ClientIdentification::GuestState *ClientIdentification::current() const
92 {
93 // if we have no client identification, we can't find a current guest either
94 if (!processCode())
95 return NULL;
96
97 SecGuestRef guestRef = Server::connection().guestRef();
98
99 // try to deliver an already-cached entry
100 {
101 StLock<Mutex> _(mLock);
102 GuestMap::iterator it = mGuests.find(guestRef);
103 if (it != mGuests.end())
104 return &it->second;
105 }
106
107 // okay, make a new one (this may take a while)
108 CFRef<CFDictionaryRef> attributes = (guestRef == kSecNoGuest)
109 ? NULL
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())) {
115 case noErr:
116 break;
117 case errSecCSUnsigned: // not signed; clearly not a host
118 case errSecCSNotAHost: // signed but not marked as a (potential) host
119 code = mClientProcess;
120 break;
121 case errSecCSNoSuchCode: // potential host, but...
122 if (guestRef == kSecNoGuest) { // ... no guests (yet), so return the process
123 code = mClientProcess;
124 break;
125 }
126 // else fall through // ... the guest we expected to be there isn't
127 default:
128 MacOSError::throwMe(rc);
129 }
130 StLock<Mutex> _(mLock);
131 GuestState &slot = mGuests[guestRef];
132 if (!slot.code) // if another thread didn't get here first...
133 slot.code = code;
134 return &slot;
135 }
136
137
138 //
139 // Return the partition id ascribed to this client.
140 // This is assigned to the whole client process - it is not per-guest.
141 //
142 std::string ClientIdentification::partitionId() const
143 {
144 if (!mGotPartitionId) {
145 StLock<Mutex> _(mValidityCheckLock);
146 mClientPartitionId = partitionIdForProcess(processCode());
147 mGotPartitionId = true;
148 }
149 return mClientPartitionId;
150 }
151
152
153 static std::string hashString(CFDataRef data)
154 {
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]);
160 return s;
161 }
162
163
164 std::string ClientIdentification::partitionIdForProcess(SecStaticCodeRef code)
165 {
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
169 " or "
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
171 " or "
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))
181 abort();
182 });
183
184 OSStatus rc;
185 switch (rc = SecStaticCodeCheckValidity(code, kSecCSBasicValidateOnly, apple)) {
186 case noErr:
187 case errSecCSReqFailed:
188 break;
189 case errSecCSUnsigned:
190 return "unsigned:";
191 default:
192 MacOSError::throwMe(rc);
193 }
194 CFRef<CFDictionaryRef> info;
195 if (OSStatus irc = SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref()))
196 MacOSError::throwMe(irc);
197
198 if (rc == noErr) {
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
202 } else {
203 return "apple:";
204 }
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);
218 } else {
219 // cannot positively classify this code, but it's signed
220 CFDataRef cdhashData = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique));
221 assert(cdhashData);
222 return "cdhash:" + hashString(cdhashData);
223 }
224 }
225
226
227 //
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.
231 //
232 string ClientIdentification::getPath() const
233 {
234 assert(mClientProcess);
235 StLock<Mutex> _(mValidityCheckLock);
236 return codePath(currentGuest());
237 }
238
239 const CssmData ClientIdentification::getHash() const
240 {
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;
246 }
247 return CssmData::wrap(guest->legacyHash, SHA1::digestLength);
248 } else
249 return CssmData();
250 }
251
252 AclSubject* ClientIdentification::copyAclSubject() const
253 {
254 StLock<Mutex> _(mValidityCheckLock);
255 RefPointer<OSXCode> clientXCode = new OSXCodeWrap(currentGuest());
256 return new CodeSignatureAclSubject(OSXVerifier(clientXCode));
257 }
258
259 OSStatus ClientIdentification::copySigningInfo(SecCSFlags flags,
260 CFDictionaryRef *info) const
261 {
262 StLock<Mutex> _(mValidityCheckLock);
263 return SecCodeCopySigningInformation(currentGuest(), flags, info);
264 }
265
266 OSStatus ClientIdentification::checkValidity(SecCSFlags flags,
267 SecRequirementRef requirement) const
268 {
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);
272 }
273
274 bool ClientIdentification::checkAppleSigned() const
275 {
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);
284 } else {
285 return true;
286 }
287 }
288 return false;
289 }
290
291
292 bool ClientIdentification::hasEntitlement(const char *name) const
293 {
294 CFRef<CFDictionaryRef> info;
295 {
296 StLock<Mutex> _(mValidityCheckLock);
297 MacOSError::check(SecCodeCopySigningInformation(processCode(), kSecCSDefaultFlags, &info.aref()));
298 }
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
304 }
305 return false;
306 }
307
308
309 //
310 // Bonus function: get the path out of a SecCodeRef
311 //
312 std::string codePath(SecStaticCodeRef code)
313 {
314 CFRef<CFURLRef> path;
315 MacOSError::check(SecCodeCopyPath(code, kSecCSDefaultFlags, &path.aref()));
316 return cfString(path);
317 }
318
319
320 //
321 // Debug dump support
322 //
323 #if defined(DEBUGDUMP)
324
325 static void dumpCode(SecCodeRef code)
326 {
327 CFRef<CFURLRef> path;
328 if (OSStatus rc = SecCodeCopyPath(code, kSecCSDefaultFlags, &path.aref()))
329 Debug::dump("unknown(rc=%d)", int32_t(rc));
330 else
331 Debug::dump("%s", cfString(path).c_str());
332 }
333
334 void ClientIdentification::dump()
335 {
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]");
343 }
344 }
345
346 #endif //DEBUGDUMP