]>
Commit | Line | Data |
---|---|---|
5c19dc3a A |
1 | /* |
2 | * Copyright (c) 2011-2014 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 "evaluationmanager.h" | |
25 | #include "policyengine.h" | |
26 | #include <security_utilities/cfmunge.h> | |
fa7225c8 A |
27 | #include <Security/SecEncodeTransform.h> |
28 | #include <Security/SecDigestTransform.h> | |
5c19dc3a A |
29 | #include <xpc/xpc.h> |
30 | #include <exception> | |
31 | #include <vector> | |
32 | ||
33 | ||
34 | ||
35 | ||
36 | namespace Security { | |
37 | namespace CodeSigning { | |
38 | ||
fa7225c8 A |
39 | #pragma mark - |
40 | ||
41 | static CFStringRef EvaluationTaskCreateKey(CFURLRef path, AuthorityType type) | |
42 | { | |
43 | CFErrorRef errors = NULL; | |
44 | ||
45 | /* concatenate the type and the path before hashing */ | |
46 | string pathString = std::to_string(type)+cfString(path); | |
47 | CFRef<CFDataRef> data = makeCFData(pathString.c_str(), pathString.size()); | |
48 | CFRef<SecGroupTransformRef> group = SecTransformCreateGroupTransform(); | |
5c19dc3a | 49 | |
fa7225c8 A |
50 | CFRef<SecTransformRef> sha1 = SecDigestTransformCreate(kSecDigestSHA2, 256, &errors); |
51 | if( errors ) | |
52 | { | |
53 | CFError::throwMe(); | |
54 | } | |
55 | ||
56 | CFRef<SecTransformRef> b64 = SecEncodeTransformCreate(kSecBase64Encoding, &errors); | |
57 | if ( errors ) | |
58 | { | |
59 | CFError::throwMe(); | |
60 | } | |
61 | ||
62 | SecTransformSetAttribute(sha1, kSecTransformInputAttributeName, data, &errors); | |
63 | if ( errors ) | |
64 | { | |
65 | CFError::throwMe(); | |
66 | } | |
67 | ||
68 | SecTransformConnectTransforms(sha1, kSecTransformOutputAttributeName, b64, kSecTransformInputAttributeName, group, &errors); | |
69 | if ( errors ) | |
70 | { | |
71 | CFError::throwMe(); | |
72 | } | |
73 | ||
74 | CFRef<CFDataRef> keyData = (CFDataRef)SecTransformExecute(group, &errors); | |
75 | if ( errors ) | |
76 | { | |
77 | CFError::throwMe(); | |
78 | } | |
5c19dc3a | 79 | |
fa7225c8 A |
80 | return makeCFString(keyData); |
81 | } | |
5c19dc3a A |
82 | |
83 | #pragma mark - EvaluationTask | |
84 | ||
85 | ||
86 | // | |
87 | // An evaluation task object manages the assessment - either directly, or in the | |
88 | // form of waiting for another evaluation task to finish an assessment on the | |
89 | // same target. | |
90 | // | |
91 | class EvaluationTask | |
92 | { | |
93 | public: | |
94 | CFURLRef path() const { return mPath.get(); } | |
95 | AuthorityType type() const { return mType; } | |
96 | bool isSharable() const { return mSharable; } | |
97 | void setUnsharable() { mSharable = false; } | |
98 | ||
99 | private: | |
100 | EvaluationTask(PolicyEngine *engine, CFURLRef path, AuthorityType type); | |
101 | virtual ~EvaluationTask(); | |
fa7225c8 A |
102 | |
103 | // Tasks cannot be copied. | |
104 | EvaluationTask(EvaluationTask const&) = delete; | |
105 | EvaluationTask& operator=(EvaluationTask const&) = delete; | |
106 | ||
5c19dc3a A |
107 | void performEvaluation(SecAssessmentFlags flags, CFDictionaryRef context); |
108 | void waitForCompletion(SecAssessmentFlags flags, CFMutableDictionaryRef result); | |
fa7225c8 | 109 | void kick(); |
5c19dc3a A |
110 | |
111 | PolicyEngine *mPolicyEngine; | |
112 | AuthorityType mType; | |
113 | dispatch_queue_t mWorkQueue; | |
114 | dispatch_queue_t mFeedbackQueue; | |
115 | dispatch_semaphore_t mAssessmentLock; | |
fa7225c8 | 116 | dispatch_once_t mAssessmentKicked; |
5c19dc3a A |
117 | int32_t mReferenceCount; |
118 | int32_t mEvalCount; | |
119 | // This whole thing is a pre-existing crutch and must be fixed soon. | |
120 | #define UNOFFICIAL_MAX_XPC_ID_LENGTH 127 | |
121 | char mXpcActivityName[UNOFFICIAL_MAX_XPC_ID_LENGTH]; | |
122 | bool mSharable; | |
123 | ||
124 | CFCopyRef<CFURLRef> mPath; | |
125 | CFCopyRef<CFMutableDictionaryRef> mResult; | |
126 | std::vector<SecAssessmentFeedback> mFeedback; | |
127 | ||
128 | std::exception_ptr mExceptionToRethrow; | |
129 | ||
130 | friend class EvaluationManager; | |
131 | }; | |
132 | ||
133 | ||
134 | EvaluationTask::EvaluationTask(PolicyEngine *engine, CFURLRef path, AuthorityType type) : | |
135 | mPolicyEngine(engine), mType(type), mAssessmentLock(dispatch_semaphore_create(0)), | |
136 | mAssessmentKicked(0), mReferenceCount(0), mEvalCount(0), mSharable(true), | |
137 | mExceptionToRethrow(0) | |
138 | { | |
139 | mXpcActivityName[0] = 0; | |
140 | ||
141 | mWorkQueue = dispatch_queue_create("EvaluationTask", 0); | |
142 | mFeedbackQueue = dispatch_queue_create("EvaluationTaskFeedback", 0); | |
143 | ||
144 | mPath = path; | |
145 | mResult.take(makeCFMutableDictionary()); | |
146 | } | |
147 | ||
148 | ||
149 | EvaluationTask::~EvaluationTask() | |
150 | { | |
151 | dispatch_release(mFeedbackQueue); | |
152 | dispatch_release(mWorkQueue); | |
153 | dispatch_release(mAssessmentLock); | |
154 | } | |
155 | ||
156 | ||
157 | void EvaluationTask::performEvaluation(SecAssessmentFlags flags, CFDictionaryRef context) | |
158 | { | |
159 | bool performTheEvaluation = false; | |
160 | bool lowPriority = flags & kSecAssessmentFlagLowPriority; | |
161 | ||
162 | // each evaluation task performs at most a single evaluation | |
163 | if (OSAtomicIncrement32Barrier(&mEvalCount) == 1) | |
164 | performTheEvaluation = true; | |
165 | ||
166 | // define a block to run when the assessment has feedback available | |
167 | SecAssessmentFeedback relayFeedback = ^Boolean(CFStringRef type, CFDictionaryRef information) { | |
168 | ||
169 | __block Boolean proceed = true; | |
170 | dispatch_sync(mFeedbackQueue, ^{ | |
171 | if (mFeedback.size() > 0) { | |
172 | proceed = false; // we need at least one interested party to proceed | |
173 | // forward the feedback to all registered listeners | |
174 | for (int i = 0; i < mFeedback.size(); ++i) { | |
175 | proceed |= mFeedback[i](type, information); | |
176 | } | |
177 | } | |
178 | }); | |
179 | if (!proceed) | |
180 | this->setUnsharable(); // don't share an expiring evaluation task | |
181 | return proceed; | |
182 | }; | |
183 | ||
184 | ||
185 | // if the calling context has a feedback block, register it to listen to | |
186 | // our feedback relay | |
187 | dispatch_sync(mFeedbackQueue, ^{ | |
188 | SecAssessmentFeedback feedback = (SecAssessmentFeedback)CFDictionaryGetValue(context, kSecAssessmentContextKeyFeedback); | |
189 | if (feedback && CFGetTypeID(feedback) == CFGetTypeID(relayFeedback)) | |
190 | mFeedback.push_back(feedback); | |
191 | }); | |
192 | ||
193 | // if we haven't already started the evaluation (we're the first interested | |
194 | // party), do it now | |
195 | if (performTheEvaluation) { | |
196 | dispatch_semaphore_t startLock = dispatch_semaphore_create(0); | |
197 | ||
198 | // create the assessment block | |
199 | dispatch_async(mWorkQueue, dispatch_block_create_with_qos_class(DISPATCH_BLOCK_ENFORCE_QOS_CLASS, QOS_CLASS_UTILITY, 0, ^{ | |
200 | // signal that the assessment is ready to start | |
201 | dispatch_semaphore_signal(startLock); | |
202 | ||
203 | // wait until we're permitted to start the assessment. if we're in low | |
204 | // priority mode, this will not happen until we're on AC power. if not | |
205 | // in low priority mode, we're either already free to perform the | |
206 | // assessment or we will be quite soon | |
207 | dispatch_semaphore_wait(mAssessmentLock, DISPATCH_TIME_FOREVER); | |
208 | ||
209 | // Unregister a possibly still scheduled activity, as it lost its point. | |
210 | if (strlen(mXpcActivityName)) { | |
211 | xpc_activity_unregister(mXpcActivityName); | |
212 | } | |
213 | ||
214 | // copy the original context into our own mutable dictionary and replace | |
215 | // (or assign) the feedback entry within it to our multi-receiver | |
216 | // feedback relay block | |
217 | CFRef<CFMutableDictionaryRef> contextOverride = makeCFMutableDictionary(context); | |
218 | CFDictionaryRemoveValue(contextOverride.get(), kSecAssessmentContextKeyFeedback); | |
219 | CFDictionaryAddValue(contextOverride.get(), kSecAssessmentContextKeyFeedback, relayFeedback); | |
220 | ||
221 | try { | |
222 | // perform the evaluation | |
223 | switch (mType) { | |
224 | case kAuthorityExecute: | |
225 | mPolicyEngine->evaluateCode(mPath.get(), kAuthorityExecute, flags, contextOverride.get(), mResult.get(), true); | |
226 | break; | |
227 | case kAuthorityInstall: | |
228 | mPolicyEngine->evaluateInstall(mPath.get(), flags, contextOverride.get(), mResult.get()); | |
229 | break; | |
230 | case kAuthorityOpenDoc: | |
231 | mPolicyEngine->evaluateDocOpen(mPath.get(), flags, contextOverride.get(), mResult.get()); | |
232 | break; | |
233 | default: | |
234 | MacOSError::throwMe(errSecCSInvalidAttributeValues); | |
5c19dc3a A |
235 | } |
236 | } catch(...) { | |
237 | mExceptionToRethrow = std::current_exception(); | |
238 | } | |
239 | ||
240 | })); | |
241 | ||
242 | // wait for the assessment to start | |
243 | dispatch_semaphore_wait(startLock, DISPATCH_TIME_FOREVER); | |
244 | dispatch_release(startLock); | |
245 | ||
246 | if (lowPriority) { | |
247 | // This whole thing is a crutch and should be handled differently. | |
248 | // Maybe by having just one activity that just kicks off all remaining | |
249 | // background assessments, CTS determines that it's a good time. | |
fa7225c8 A |
250 | |
251 | // Convert the evaluation path and type to a base64 encoded hash to use as a key | |
252 | // Use that to generate an xpc_activity identifier. This identifier should be smaller | |
253 | // than 128 characters due to rdar://problem/20094806 | |
5c19dc3a | 254 | |
fa7225c8 A |
255 | CFCopyRef<CFStringRef> cfKey(EvaluationTaskCreateKey(mPath, mType)); |
256 | string key = cfStringRelease(cfKey); | |
257 | snprintf(mXpcActivityName, UNOFFICIAL_MAX_XPC_ID_LENGTH, "com.apple.security.assess/%s", key.c_str()); | |
5c19dc3a A |
258 | |
259 | // schedule the assessment to be permitted to run (beyond start) -- this | |
260 | // will either happen once we're no longer on battery power, or | |
261 | // immediately, based on the flag value of kSecAssessmentFlagLowPriority | |
262 | xpc_object_t criteria = xpc_dictionary_create(NULL, NULL, 0); | |
263 | xpc_dictionary_set_bool(criteria, XPC_ACTIVITY_REPEATING, false); | |
264 | xpc_dictionary_set_int64(criteria, XPC_ACTIVITY_DELAY, 0); | |
265 | xpc_dictionary_set_int64(criteria, XPC_ACTIVITY_GRACE_PERIOD, 0); | |
266 | ||
267 | xpc_dictionary_set_string(criteria, XPC_ACTIVITY_PRIORITY, XPC_ACTIVITY_PRIORITY_MAINTENANCE); | |
268 | xpc_dictionary_set_bool(criteria, XPC_ACTIVITY_ALLOW_BATTERY, false); | |
269 | ||
270 | xpc_activity_register(mXpcActivityName, criteria, ^(xpc_activity_t activity) { | |
fa7225c8 A |
271 | // We use the Evaluation Manager to get the task, as the task may be gone already |
272 | // (and with it, its mAssessmentKicked member). | |
273 | EvaluationManager::globalManager()->kickTask(cfKey); | |
5c19dc3a A |
274 | }); |
275 | xpc_release(criteria); | |
276 | } | |
277 | } | |
278 | ||
279 | // If this is a foreground assessment to begin with, or if an assessment | |
280 | // with an existing task has been requested in the foreground, kick it | |
281 | // immediately. | |
282 | if (!lowPriority) { | |
fa7225c8 | 283 | kick(); |
5c19dc3a A |
284 | } |
285 | } | |
286 | ||
fa7225c8 A |
287 | void EvaluationTask::kick() { |
288 | dispatch_once(&mAssessmentKicked, ^{ | |
289 | dispatch_semaphore_signal(mAssessmentLock); | |
290 | }); | |
291 | } | |
5c19dc3a A |
292 | |
293 | void EvaluationTask::waitForCompletion(SecAssessmentFlags flags, CFMutableDictionaryRef result) | |
294 | { | |
295 | // if the caller didn't request low priority we will elevate the dispatch | |
296 | // queue priority via our wait block | |
297 | dispatch_qos_class_t qos_class = QOS_CLASS_USER_INITIATED; | |
298 | if (flags & kSecAssessmentFlagLowPriority) | |
299 | qos_class = QOS_CLASS_UTILITY; | |
300 | ||
301 | // wait for the assessment to complete; our wait block will queue up behind | |
302 | // the assessment and the copy its results | |
303 | dispatch_sync(mWorkQueue, dispatch_block_create_with_qos_class (DISPATCH_BLOCK_ENFORCE_QOS_CLASS, qos_class, 0, ^{ | |
304 | // copy the class result back to the caller | |
305 | cfDictionaryApplyBlock(mResult.get(), ^(const void *key, const void *value){ | |
306 | CFDictionaryAddValue(result, key, value); | |
307 | }); | |
308 | })); | |
5c19dc3a A |
309 | } |
310 | ||
311 | ||
312 | ||
313 | #pragma mark - | |
314 | ||
315 | ||
316 | static Boolean evaluationTasksAreEqual(const EvaluationTask *task1, const EvaluationTask *task2) | |
317 | { | |
318 | if (!task1->isSharable() || !task2->isSharable()) return false; | |
319 | if ((task1->type() != task2->type()) || | |
320 | (cfString(task1->path()) != cfString(task2->path()))) | |
321 | return false; | |
322 | ||
323 | return true; | |
324 | } | |
325 | ||
326 | ||
327 | ||
328 | ||
329 | #pragma mark - EvaluationManager | |
330 | ||
331 | ||
332 | EvaluationManager *EvaluationManager::globalManager() | |
333 | { | |
334 | static EvaluationManager *singleton; | |
335 | static dispatch_once_t onceToken; | |
336 | dispatch_once(&onceToken, ^{ | |
337 | singleton = new EvaluationManager(); | |
338 | }); | |
339 | return singleton; | |
340 | } | |
341 | ||
342 | ||
343 | EvaluationManager::EvaluationManager() | |
344 | { | |
345 | static CFDictionaryValueCallBacks evalTaskValueCallbacks = kCFTypeDictionaryValueCallBacks; | |
346 | evalTaskValueCallbacks.equal = (CFDictionaryEqualCallBack)evaluationTasksAreEqual; | |
347 | evalTaskValueCallbacks.retain = NULL; | |
348 | evalTaskValueCallbacks.release = NULL; | |
349 | mCurrentEvaluations.take( | |
350 | CFDictionaryCreateMutable(NULL, | |
351 | 0, | |
352 | &kCFTypeDictionaryKeyCallBacks, | |
353 | &evalTaskValueCallbacks)); | |
354 | ||
355 | mListLockQueue = dispatch_queue_create("EvaluationManagerSyncronization", 0); | |
356 | } | |
357 | ||
358 | ||
359 | EvaluationManager::~EvaluationManager() | |
360 | { | |
361 | dispatch_release(mListLockQueue); | |
362 | } | |
363 | ||
364 | ||
365 | EvaluationTask *EvaluationManager::evaluationTask(PolicyEngine *engine, CFURLRef path, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, CFMutableDictionaryRef result) | |
366 | { | |
367 | __block EvaluationTask *evalTask = NULL; | |
368 | ||
369 | dispatch_sync(mListLockQueue, ^{ | |
fa7225c8 | 370 | CFRef<CFStringRef> key = EvaluationTaskCreateKey(path, type); |
5c19dc3a A |
371 | // is path already being evaluated? |
372 | if (!(flags & kSecAssessmentFlagIgnoreActiveAssessments)) | |
fa7225c8 | 373 | evalTask = (EvaluationTask *)CFDictionaryGetValue(mCurrentEvaluations.get(), key.get()); |
5c19dc3a A |
374 | if (!evalTask) { |
375 | // create a new task for the evaluation | |
376 | evalTask = new EvaluationTask(engine, path, type); | |
377 | if (flags & kSecAssessmentFlagIgnoreActiveAssessments) | |
378 | evalTask->setUnsharable(); | |
fa7225c8 | 379 | CFDictionaryAddValue(mCurrentEvaluations.get(), key.get(), evalTask); |
5c19dc3a A |
380 | } |
381 | evalTask->mReferenceCount++; | |
382 | }); | |
383 | ||
384 | if (evalTask) | |
385 | evalTask->performEvaluation(flags, context); | |
386 | ||
387 | return evalTask; | |
388 | } | |
389 | ||
390 | ||
822b670c | 391 | void EvaluationManager::finalizeTask(EvaluationTask *task, SecAssessmentFlags flags, CFMutableDictionaryRef result) |
5c19dc3a A |
392 | { |
393 | task->waitForCompletion(flags, result); | |
822b670c A |
394 | |
395 | std::exception_ptr pendingException = task->mExceptionToRethrow; | |
396 | ||
397 | removeTask(task); | |
398 | ||
399 | if (pendingException) std::rethrow_exception(pendingException); | |
5c19dc3a A |
400 | } |
401 | ||
402 | ||
403 | void EvaluationManager::removeTask(EvaluationTask *task) | |
404 | { | |
405 | dispatch_sync(mListLockQueue, ^{ | |
fa7225c8 | 406 | CFRef<CFStringRef> key = EvaluationTaskCreateKey(task->path(), task->type()); |
5c19dc3a A |
407 | // are we done with this evaluation task? |
408 | if (--task->mReferenceCount == 0) { | |
409 | // yes -- remove it from our list and delete the object | |
fa7225c8 | 410 | CFDictionaryRemoveValue(mCurrentEvaluations.get(), key.get()); |
5c19dc3a A |
411 | delete task; |
412 | } | |
413 | }); | |
414 | } | |
415 | ||
fa7225c8 A |
416 | void EvaluationManager::kickTask(CFStringRef key) |
417 | { | |
418 | dispatch_sync(mListLockQueue, ^{ | |
419 | EvaluationTask *evalTask = (EvaluationTask*)CFDictionaryGetValue(mCurrentEvaluations.get(), | |
420 | key); | |
421 | if (evalTask != NULL) { | |
422 | evalTask->kick(); | |
423 | } | |
424 | }); | |
425 | } | |
5c19dc3a A |
426 | |
427 | } // end namespace CodeSigning | |
428 | } // end namespace Security | |
429 |