]> git.saurik.com Git - apple/security.git/blob - sectask/SecTask.c
Security-59306.120.7.tar.gz
[apple/security.git] / sectask / SecTask.c
1 /*
2 * Copyright (c) 2008,2010-2013 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 #include "SecTask.h"
25 #include "SecTaskPriv.h"
26
27 #include <utilities/debugging.h>
28
29 #include <AssertMacros.h>
30 #include <CoreFoundation/CFRuntime.h>
31 #include <IOKit/IOKitLib.h>
32 #include <IOKit/IOCFUnserialize.h>
33 #include <System/sys/codesign.h>
34 #include <bsm/libbsm.h>
35 #include <inttypes.h>
36 #include <syslog.h>
37 #include <utilities/SecCFWrappers.h>
38 #include <xpc/private.h>
39
40 #include <sys/sysctl.h>
41
42 #if TARGET_OS_OSX
43 /* These won't exist until we unify codesigning */
44 #include <Security/SecCode.h>
45 #include <Security/SecCodePriv.h>
46 #include <Security/SecRequirement.h>
47 #endif /* TARGET_OS_OSX */
48
49 struct __SecTask {
50 CFRuntimeBase base;
51
52 audit_token_t token;
53
54 /* Track whether we've loaded entitlements independently since after the
55 * load, entitlements may legitimately be NULL */
56 Boolean entitlementsLoaded;
57 CFDictionaryRef entitlements;
58
59 /* for debugging only, shown by debugDescription */
60 int lastFailure;
61 };
62
63 static bool check_task(SecTaskRef task) {
64 return SecTaskGetTypeID() == CFGetTypeID(task);
65 }
66
67 static void SecTaskFinalize(CFTypeRef cfTask)
68 {
69 SecTaskRef task = (SecTaskRef) cfTask;
70 CFReleaseNull(task->entitlements);
71 }
72
73
74 // Define PRIdPID (proper printf format string for pid_t)
75 #define PRIdPID PRId32
76
77 static CFStringRef SecTaskCopyDebugDescription(CFTypeRef cfTask)
78 {
79 SecTaskRef task = (SecTaskRef) cfTask;
80 pid_t pid;
81 audit_token_to_au32(task->token, NULL, NULL, NULL, NULL, NULL, &pid, NULL, NULL);
82
83 const char *task_name;
84 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};
85 struct kinfo_proc kp;
86 size_t len = sizeof(kp);
87 if (sysctl(mib, 4, &kp, &len, NULL, 0) == -1 || len == 0)
88 task_name = strerror(errno);
89 else
90 task_name = kp.kp_proc.p_comm;
91
92 return CFStringCreateWithFormat(CFGetAllocator(task), NULL, CFSTR("%s[%" PRIdPID "]/%d#%d LF=%d"), task_name, pid,
93 task->entitlementsLoaded, task->entitlements ? (int)CFDictionaryGetCount(task->entitlements) : -1, task->lastFailure);
94 }
95
96 CFGiblisWithFunctions(SecTask, NULL, NULL, SecTaskFinalize, NULL, NULL, NULL, SecTaskCopyDebugDescription, NULL, NULL, NULL)
97
98 static SecTaskRef init_task_ref(CFAllocatorRef allocator)
99 {
100 CFIndex extra = sizeof(struct __SecTask) - sizeof(CFRuntimeBase);
101 return (SecTaskRef) _CFRuntimeCreateInstance(allocator, SecTaskGetTypeID(), extra, NULL);
102 }
103
104 SecTaskRef SecTaskCreateFromSelf(CFAllocatorRef allocator)
105 {
106 SecTaskRef task = init_task_ref(allocator);
107 if (task != NULL) {
108
109 kern_return_t kr = KERN_FAILURE;
110 mach_msg_type_number_t autoken_cnt = TASK_AUDIT_TOKEN_COUNT;
111 kr = task_info(mach_task_self(), TASK_AUDIT_TOKEN, (task_info_t)&task->token, &autoken_cnt);
112 if (kr == KERN_SUCCESS) {
113 task->entitlementsLoaded = false;
114 task->entitlements = NULL;
115 } else {
116 CFReleaseNull(task);
117 }
118 }
119
120 return task;
121 }
122
123 SecTaskRef SecTaskCreateWithAuditToken(CFAllocatorRef allocator, audit_token_t token)
124 {
125 SecTaskRef task = init_task_ref(allocator);
126 if (task != NULL) {
127
128 memcpy(&task->token, &token, sizeof(token));
129 task->entitlementsLoaded = false;
130 task->entitlements = NULL;
131 }
132
133 return task;
134 }
135
136 _Nullable SecTaskRef
137 SecTaskCreateWithXPCMessage(xpc_object_t _Nonnull message)
138 {
139 audit_token_t token;
140
141 if (message == NULL || xpc_get_type(message) != XPC_TYPE_DICTIONARY) {
142 return NULL;
143 }
144 xpc_dictionary_get_audit_token(message, &token);
145
146 return SecTaskCreateWithAuditToken(NULL, token);
147 }
148
149
150
151 struct csheader {
152 uint32_t magic;
153 uint32_t length;
154 };
155
156 static int
157 csops_task(SecTaskRef task, int ops, void *blob, size_t size)
158 {
159 int rc;
160
161 pid_t pid;
162 audit_token_to_au32(task->token, NULL, NULL, NULL, NULL, NULL, &pid, NULL, NULL);
163 rc = csops_audittoken(pid, ops, blob, size, &task->token);
164
165 task->lastFailure = (rc == -1) ? errno : 0;
166 return rc;
167 }
168
169 static CFStringRef
170 SecTaskCopyIdentifier(SecTaskRef task, int op, CFErrorRef *error)
171 {
172 CFStringRef signingId = NULL;
173 char *data = NULL;
174 struct csheader header;
175 uint32_t bufferlen;
176 int ret;
177
178 ret = csops_task(task, op, &header, sizeof(header));
179 if (ret != -1 || errno != ERANGE)
180 return NULL;
181
182 bufferlen = ntohl(header.length);
183 /* check for insane values */
184 if (bufferlen > 1024 * 1024 || bufferlen < 8) {
185 ret = EINVAL;
186 goto out;
187 }
188 data = malloc(bufferlen + 1);
189 if (data == NULL) {
190 ret = ENOMEM;
191 goto out;
192 }
193 ret = csops_task(task, op, data, bufferlen);
194 if (ret) {
195 ret = errno;
196 goto out;
197 }
198 data[bufferlen] = '\0';
199
200 signingId = CFStringCreateWithCString(NULL, data + 8, kCFStringEncodingUTF8);
201
202 out:
203 if (data)
204 free(data);
205 if (ret && error)
206 *error = CFErrorCreate(NULL, kCFErrorDomainPOSIX, ret, NULL);
207
208 return signingId;
209 }
210
211 CFStringRef
212 SecTaskCopySigningIdentifier(SecTaskRef task, CFErrorRef *error)
213 {
214 return SecTaskCopyIdentifier(task, CS_OPS_IDENTITY, error);
215 }
216
217 CFStringRef
218 SecTaskCopyTeamIdentifier(SecTaskRef task, CFErrorRef *error)
219 {
220 return SecTaskCopyIdentifier(task, CS_OPS_TEAMID, error);
221 }
222
223 uint32_t
224 SecTaskGetCodeSignStatus(SecTaskRef task)
225 {
226 uint32_t flags = 0;
227 if (csops_task(task, CS_OPS_STATUS, &flags, sizeof(flags)) != 0)
228 return 0;
229 return flags;
230 }
231
232 static bool SecTaskLoadEntitlements(SecTaskRef task, CFErrorRef *error)
233 {
234 CFMutableDictionaryRef entitlements = NULL;
235 struct csheader header;
236 uint8_t *buffer = NULL;
237 uint32_t bufferlen;
238 int ret;
239
240
241 ret = csops_task(task, CS_OPS_ENTITLEMENTS_BLOB, &header, sizeof(header));
242 /* Any other combination means no entitlements */
243 if (ret == -1) {
244 if (errno != ERANGE) {
245 int entitlementErrno = errno;
246
247 uint32_t cs_flags = -1;
248 if (-1 == csops_task(task, CS_OPS_STATUS, &cs_flags, sizeof(cs_flags))) {
249 syslog(LOG_NOTICE, "Failed to get cs_flags, error=%d", errno);
250 }
251
252 if (cs_flags != 0) { // was signed
253
254 pid_t pid;
255 audit_token_to_au32(task->token, NULL, NULL, NULL, NULL, NULL, &pid, NULL, NULL);
256 syslog(LOG_NOTICE, "SecTaskLoadEntitlements failed error=%d cs_flags=%x, pid=%d", entitlementErrno, cs_flags, pid); // to ease diagnostics
257
258 CFStringRef description = SecTaskCopyDebugDescription(task);
259 char *descriptionBuf = NULL;
260 CFIndex descriptionSize = CFStringGetLength(description) * 4;
261 descriptionBuf = (char *)malloc(descriptionSize);
262 if (!CFStringGetCString(description, descriptionBuf, descriptionSize, kCFStringEncodingUTF8)) {
263 descriptionBuf[0] = 0;
264 }
265
266 syslog(LOG_NOTICE, "SecTaskCopyDebugDescription: %s", descriptionBuf);
267 CFReleaseNull(description);
268 free(descriptionBuf);
269 }
270 task->lastFailure = entitlementErrno; // was overwritten by csops_task(CS_OPS_STATUS) above
271
272 // EINVAL is what the kernel says for unsigned code, so we'll have to let that pass
273 if (entitlementErrno == EINVAL) {
274 task->entitlementsLoaded = true;
275 return true;
276 }
277 ret = entitlementErrno; // what really went wrong
278 goto out; // bail out
279 }
280 bufferlen = ntohl(header.length);
281 /* check for insane values */
282 if (bufferlen > 1024 * 1024 || bufferlen < 8) {
283 ret = E2BIG;
284 goto out;
285 }
286 buffer = malloc(bufferlen);
287 if (buffer == NULL) {
288 ret = ENOMEM;
289 goto out;
290 }
291 ret = csops_task(task, CS_OPS_ENTITLEMENTS_BLOB, buffer, bufferlen);
292 if (ret) {
293 ret = errno;
294 goto out;
295 }
296
297 CFDataRef data = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, buffer+8, bufferlen-8, kCFAllocatorNull);
298 entitlements = (CFMutableDictionaryRef) CFPropertyListCreateWithData(kCFAllocatorDefault, data, kCFPropertyListMutableContainers, NULL, error);
299 CFReleaseNull(data);
300
301 if((entitlements==NULL) || (CFGetTypeID(entitlements)!=CFDictionaryGetTypeID())){
302 ret = EDOM; // don't use EINVAL here; it conflates problems with syscall error returns
303 goto out;
304 }
305 }
306
307 task->entitlements = entitlements ? CFRetain(entitlements) : NULL;
308 task->entitlementsLoaded = true;
309
310 out:
311 CFReleaseNull(entitlements);
312 if(buffer)
313 free(buffer);
314 if (ret && error && *error==NULL)
315 *error = CFErrorCreate(NULL, kCFErrorDomainPOSIX, ret, NULL);
316 return ret == 0;
317 }
318
319
320 CFTypeRef SecTaskCopyValueForEntitlement(SecTaskRef task, CFStringRef entitlement, CFErrorRef *error)
321 {
322 CFTypeRef value = NULL;
323 require(check_task(task), out);
324
325 /* Load entitlements if necessary */
326 if (task->entitlementsLoaded == false) {
327 require_quiet(SecTaskLoadEntitlements(task, error), out);
328 }
329
330 if (task->entitlements != NULL) {
331 value = CFDictionaryGetValue(task->entitlements, entitlement);
332
333 /* Return something the caller must release */
334 if (value != NULL) {
335 CFRetain(value);
336 }
337 }
338 out:
339 return value;
340 }
341
342 CFDictionaryRef SecTaskCopyValuesForEntitlements(SecTaskRef task, CFArrayRef entitlements, CFErrorRef *error)
343 {
344 CFMutableDictionaryRef values = NULL;
345 require(check_task(task), out);
346
347 /* Load entitlements if necessary */
348 if (task->entitlementsLoaded == false) {
349 SecTaskLoadEntitlements(task, error);
350 }
351
352 /* Iterate over the passed in entitlements, populating the dictionary
353 * If entitlements were loaded but none were present, return an empty
354 * dictionary */
355 if (task->entitlementsLoaded == true) {
356
357 CFIndex i, count = CFArrayGetCount(entitlements);
358 values = CFDictionaryCreateMutable(CFGetAllocator(task), count, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
359 if (task->entitlements != NULL) {
360 for (i = 0; i < count; i++) {
361 CFStringRef entitlement = CFArrayGetValueAtIndex(entitlements, i);
362 CFTypeRef value = CFDictionaryGetValue(task->entitlements, entitlement);
363 if (value != NULL) {
364 CFDictionarySetValue(values, entitlement, value);
365 }
366 }
367 }
368 }
369 out:
370 return values;
371 }
372
373 #if SEC_OS_OSX
374 /*
375 * Determine if the given task meets a specified requirement.
376 */
377 OSStatus
378 SecTaskValidateForRequirement(SecTaskRef task, CFStringRef requirement)
379 {
380 OSStatus status;
381 SecCodeRef code = NULL;
382 SecRequirementRef req = NULL;
383
384 CFMutableDictionaryRef codeDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
385 CFDataRef auditData = CFDataCreate(kCFAllocatorDefault, (const UInt8 *)&task->token, sizeof(audit_token_t));
386 CFDictionarySetValue(codeDict, kSecGuestAttributeAudit, auditData);
387 status = SecCodeCopyGuestWithAttributes(NULL, codeDict, kSecCSDefaultFlags, &code);
388 CFReleaseNull(codeDict);
389 CFReleaseNull(auditData);
390
391 if (!status) {
392 status = SecRequirementCreateWithString(requirement,
393 kSecCSDefaultFlags, &req);
394 }
395 if (!status) {
396 status = SecCodeCheckValidity(code, kSecCSDefaultFlags, req);
397 }
398
399 CFReleaseNull(req);
400 CFReleaseNull(code);
401
402 return status;
403 }
404 #endif /* SEC_OS_OSX */
405
406 Boolean SecTaskEntitlementsValidated(SecTaskRef task) {
407 // TODO: Cache the result
408 uint32_t csflags = 0;
409 const uint32_t mask = CS_VALID | CS_KILL | CS_ENTITLEMENTS_VALIDATED;
410 const uint32_t debug_mask = CS_DEBUGGED | CS_ENTITLEMENTS_VALIDATED;
411 int rc = csops_task(task, CS_OPS_STATUS, &csflags, sizeof(csflags));
412 // Allow debugged processes that were valid to continue being treated as valid
413 // We need this all the time (not just on internal) because third parties may need to debug their entitled process in xcode
414 return (rc != -1) && ((mask & csflags) == mask || (debug_mask & csflags) == debug_mask);
415 }
416