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