2 * Copyright (c) 2011-2014 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 #include "evaluationmanager.h"
25 #include "policyengine.h"
26 #include <security_utilities/cfmunge.h>
27 #include <Security/SecEncodeTransform.h>
28 #include <Security/SecDigestTransform.h>
37 namespace CodeSigning
{
41 static CFStringRef
EvaluationTaskCreateKey(CFURLRef path
, AuthorityType type
)
43 CFErrorRef errors
= NULL
;
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();
50 CFRef
<SecTransformRef
> sha1
= SecDigestTransformCreate(kSecDigestSHA2
, 256, &errors
);
56 CFRef
<SecTransformRef
> b64
= SecEncodeTransformCreate(kSecBase64Encoding
, &errors
);
62 SecTransformSetAttribute(sha1
, kSecTransformInputAttributeName
, data
, &errors
);
68 SecTransformConnectTransforms(sha1
, kSecTransformOutputAttributeName
, b64
, kSecTransformInputAttributeName
, group
, &errors
);
74 CFRef
<CFDataRef
> keyData
= (CFDataRef
)SecTransformExecute(group
, &errors
);
80 return makeCFString(keyData
);
83 #pragma mark - EvaluationTask
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
94 CFURLRef
path() const { return mPath
.get(); }
95 AuthorityType
type() const { return mType
; }
96 bool isSharable() const { return mSharable
; }
97 void setUnsharable() { mSharable
= false; }
100 EvaluationTask(PolicyEngine
*engine
, CFURLRef path
, AuthorityType type
);
101 virtual ~EvaluationTask();
103 // Tasks cannot be copied.
104 EvaluationTask(EvaluationTask
const&) = delete;
105 EvaluationTask
& operator=(EvaluationTask
const&) = delete;
107 void performEvaluation(SecAssessmentFlags flags
, CFDictionaryRef context
);
108 void waitForCompletion(SecAssessmentFlags flags
, CFMutableDictionaryRef result
);
111 PolicyEngine
*mPolicyEngine
;
113 dispatch_queue_t mWorkQueue
;
114 dispatch_queue_t mFeedbackQueue
;
115 dispatch_semaphore_t mAssessmentLock
;
116 dispatch_once_t mAssessmentKicked
;
117 int32_t mReferenceCount
;
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
];
124 CFCopyRef
<CFURLRef
> mPath
;
125 CFCopyRef
<CFMutableDictionaryRef
> mResult
;
126 std::vector
<SecAssessmentFeedback
> mFeedback
;
128 std::exception_ptr mExceptionToRethrow
;
130 friend class EvaluationManager
;
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)
139 mXpcActivityName
[0] = 0;
141 mWorkQueue
= dispatch_queue_create("EvaluationTask", 0);
142 mFeedbackQueue
= dispatch_queue_create("EvaluationTaskFeedback", 0);
145 mResult
.take(makeCFMutableDictionary());
149 EvaluationTask::~EvaluationTask()
151 dispatch_release(mFeedbackQueue
);
152 dispatch_release(mWorkQueue
);
153 dispatch_release(mAssessmentLock
);
157 void EvaluationTask::performEvaluation(SecAssessmentFlags flags
, CFDictionaryRef context
)
159 bool performTheEvaluation
= false;
160 bool lowPriority
= flags
& kSecAssessmentFlagLowPriority
;
162 // each evaluation task performs at most a single evaluation
163 if (OSAtomicIncrement32Barrier(&mEvalCount
) == 1)
164 performTheEvaluation
= true;
166 // define a block to run when the assessment has feedback available
167 SecAssessmentFeedback relayFeedback
= ^Boolean(CFStringRef type
, CFDictionaryRef information
) {
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
);
180 this->setUnsharable(); // don't share an expiring evaluation task
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
);
193 // if we haven't already started the evaluation (we're the first interested
195 if (performTheEvaluation
) {
196 dispatch_semaphore_t startLock
= dispatch_semaphore_create(0);
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
);
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
);
209 // Unregister a possibly still scheduled activity, as it lost its point.
210 if (strlen(mXpcActivityName
)) {
211 xpc_activity_unregister(mXpcActivityName
);
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
);
222 // perform the evaluation
224 case kAuthorityExecute
:
225 mPolicyEngine
->evaluateCode(mPath
.get(), kAuthorityExecute
, flags
, contextOverride
.get(), mResult
.get(), true);
227 case kAuthorityInstall
:
228 mPolicyEngine
->evaluateInstall(mPath
.get(), flags
, contextOverride
.get(), mResult
.get());
230 case kAuthorityOpenDoc
:
231 mPolicyEngine
->evaluateDocOpen(mPath
.get(), flags
, contextOverride
.get(), mResult
.get());
234 MacOSError::throwMe(errSecCSInvalidAttributeValues
);
238 mExceptionToRethrow
= std::current_exception();
243 // wait for the assessment to start
244 dispatch_semaphore_wait(startLock
, DISPATCH_TIME_FOREVER
);
245 dispatch_release(startLock
);
248 // This whole thing is a crutch and should be handled differently.
249 // Maybe by having just one activity that just kicks off all remaining
250 // background assessments, CTS determines that it's a good time.
252 // Convert the evaluation path and type to a base64 encoded hash to use as a key
253 // Use that to generate an xpc_activity identifier. This identifier should be smaller
254 // than 128 characters due to rdar://problem/20094806
256 CFCopyRef
<CFStringRef
> cfKey(EvaluationTaskCreateKey(mPath
, mType
));
257 string key
= cfStringRelease(cfKey
);
258 snprintf(mXpcActivityName
, UNOFFICIAL_MAX_XPC_ID_LENGTH
, "com.apple.security.assess/%s", key
.c_str());
260 // schedule the assessment to be permitted to run (beyond start) -- this
261 // will either happen once we're no longer on battery power, or
262 // immediately, based on the flag value of kSecAssessmentFlagLowPriority
263 xpc_object_t criteria
= xpc_dictionary_create(NULL
, NULL
, 0);
264 xpc_dictionary_set_bool(criteria
, XPC_ACTIVITY_REPEATING
, false);
265 xpc_dictionary_set_int64(criteria
, XPC_ACTIVITY_DELAY
, 0);
266 xpc_dictionary_set_int64(criteria
, XPC_ACTIVITY_GRACE_PERIOD
, 0);
268 xpc_dictionary_set_string(criteria
, XPC_ACTIVITY_PRIORITY
, XPC_ACTIVITY_PRIORITY_MAINTENANCE
);
269 xpc_dictionary_set_bool(criteria
, XPC_ACTIVITY_ALLOW_BATTERY
, false);
271 xpc_activity_register(mXpcActivityName
, criteria
, ^(xpc_activity_t activity
) {
272 // We use the Evaluation Manager to get the task, as the task may be gone already
273 // (and with it, its mAssessmentKicked member).
274 EvaluationManager::globalManager()->kickTask(cfKey
);
276 xpc_release(criteria
);
280 // If this is a foreground assessment to begin with, or if an assessment
281 // with an existing task has been requested in the foreground, kick it
288 void EvaluationTask::kick() {
289 dispatch_once(&mAssessmentKicked
, ^{
290 dispatch_semaphore_signal(mAssessmentLock
);
294 void EvaluationTask::waitForCompletion(SecAssessmentFlags flags
, CFMutableDictionaryRef result
)
296 // if the caller didn't request low priority we will elevate the dispatch
297 // queue priority via our wait block
298 dispatch_qos_class_t qos_class
= QOS_CLASS_USER_INITIATED
;
299 if (flags
& kSecAssessmentFlagLowPriority
)
300 qos_class
= QOS_CLASS_UTILITY
;
302 // wait for the assessment to complete; our wait block will queue up behind
303 // the assessment and the copy its results
304 dispatch_sync(mWorkQueue
, dispatch_block_create_with_qos_class (DISPATCH_BLOCK_ENFORCE_QOS_CLASS
, qos_class
, 0, ^{
305 // copy the class result back to the caller
306 cfDictionaryApplyBlock(mResult
.get(), ^(const void *key
, const void *value
){
307 CFDictionaryAddValue(result
, key
, value
);
317 static Boolean
evaluationTasksAreEqual(const EvaluationTask
*task1
, const EvaluationTask
*task2
)
319 if (!task1
->isSharable() || !task2
->isSharable()) return false;
320 if ((task1
->type() != task2
->type()) ||
321 (cfString(task1
->path()) != cfString(task2
->path())))
330 #pragma mark - EvaluationManager
333 EvaluationManager
*EvaluationManager::globalManager()
335 static EvaluationManager
*singleton
;
336 static dispatch_once_t onceToken
;
337 dispatch_once(&onceToken
, ^{
338 singleton
= new EvaluationManager();
344 EvaluationManager::EvaluationManager()
346 static CFDictionaryValueCallBacks evalTaskValueCallbacks
= kCFTypeDictionaryValueCallBacks
;
347 evalTaskValueCallbacks
.equal
= (CFDictionaryEqualCallBack
)evaluationTasksAreEqual
;
348 evalTaskValueCallbacks
.retain
= NULL
;
349 evalTaskValueCallbacks
.release
= NULL
;
350 mCurrentEvaluations
.take(
351 CFDictionaryCreateMutable(NULL
,
353 &kCFTypeDictionaryKeyCallBacks
,
354 &evalTaskValueCallbacks
));
356 mListLockQueue
= dispatch_queue_create("EvaluationManagerSyncronization", 0);
360 EvaluationManager::~EvaluationManager()
362 dispatch_release(mListLockQueue
);
366 EvaluationTask
*EvaluationManager::evaluationTask(PolicyEngine
*engine
, CFURLRef path
, AuthorityType type
, SecAssessmentFlags flags
, CFDictionaryRef context
, CFMutableDictionaryRef result
)
368 __block EvaluationTask
*evalTask
= NULL
;
370 dispatch_sync(mListLockQueue
, ^{
371 CFRef
<CFStringRef
> key
= EvaluationTaskCreateKey(path
, type
);
372 // is path already being evaluated?
373 if (!(flags
& kSecAssessmentFlagIgnoreActiveAssessments
))
374 evalTask
= (EvaluationTask
*)CFDictionaryGetValue(mCurrentEvaluations
.get(), key
.get());
376 // create a new task for the evaluation
377 evalTask
= new EvaluationTask(engine
, path
, type
);
378 if (flags
& kSecAssessmentFlagIgnoreActiveAssessments
)
379 evalTask
->setUnsharable();
380 CFDictionaryAddValue(mCurrentEvaluations
.get(), key
.get(), evalTask
);
382 evalTask
->mReferenceCount
++;
386 evalTask
->performEvaluation(flags
, context
);
392 void EvaluationManager::finalizeTask(EvaluationTask
*task
, SecAssessmentFlags flags
, CFMutableDictionaryRef result
)
394 task
->waitForCompletion(flags
, result
);
396 std::exception_ptr pendingException
= task
->mExceptionToRethrow
;
400 if (pendingException
) std::rethrow_exception(pendingException
);
404 void EvaluationManager::removeTask(EvaluationTask
*task
)
406 dispatch_sync(mListLockQueue
, ^{
407 CFRef
<CFStringRef
> key
= EvaluationTaskCreateKey(task
->path(), task
->type());
408 // are we done with this evaluation task?
409 if (--task
->mReferenceCount
== 0) {
410 // yes -- remove it from our list and delete the object
411 CFDictionaryRemoveValue(mCurrentEvaluations
.get(), key
.get());
417 void EvaluationManager::kickTask(CFStringRef key
)
419 dispatch_sync(mListLockQueue
, ^{
420 EvaluationTask
*evalTask
= (EvaluationTask
*)CFDictionaryGetValue(mCurrentEvaluations
.get(),
422 if (evalTask
!= NULL
) {
428 } // end namespace CodeSigning
429 } // end namespace Security