]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_codesigning/lib/policyengine.cpp
Security-57337.40.85.tar.gz
[apple/security.git] / OSX / libsecurity_codesigning / lib / policyengine.cpp
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 #include "policyengine.h"
24 #include "xar++.h"
25 #include "quarantine++.h"
26 #include "codesigning_dtrace.h"
27 #include <security_utilities/cfmunge.h>
28 #include <Security/Security.h>
29 #include <Security/SecCodePriv.h>
30 #include <Security/SecRequirementPriv.h>
31 #include <Security/SecPolicyPriv.h>
32 #include <Security/SecTrustPriv.h>
33 #include <Security/SecCodeSigner.h>
34 #include <Security/cssmapplePriv.h>
35 #include <security_utilities/unix++.h>
36 #include <notify.h>
37
38 #include "diskrep.h"
39 #include "codedirectory.h"
40 #include "csutilities.h"
41 #include "StaticCode.h"
42
43 #include <CoreServices/CoreServicesPriv.h>
44 #include "SecCodePriv.h"
45 #undef check // Macro! Yech.
46
47 extern "C" {
48 #include <OpenScriptingUtilPriv.h>
49 }
50
51
52 namespace Security {
53 namespace CodeSigning {
54
55 static const double NEGATIVE_HOLD = 60.0/86400; // 60 seconds to cache negative outcomes
56
57 static const char RECORDER_DIR[] = "/tmp/gke-"; // recorder mode destination for detached signatures
58 enum {
59 recorder_code_untrusted = 0, // signed but untrusted
60 recorder_code_adhoc = 1, // unsigned; signature recorded
61 recorder_code_unable = 2, // unsigned; unable to record signature
62 };
63
64
65 static void authorizeUpdate(SecAssessmentFlags flags, CFDictionaryRef context);
66 static bool codeInvalidityExceptions(SecStaticCodeRef code, CFMutableDictionaryRef result);
67 static CFTypeRef installerPolicy() CF_RETURNS_RETAINED;
68
69
70 //
71 // Core structure
72 //
73 PolicyEngine::PolicyEngine()
74 : PolicyDatabase(NULL, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE)
75 {
76 }
77
78 PolicyEngine::~PolicyEngine()
79 { }
80
81
82 //
83 // Top-level evaluation driver
84 //
85 void PolicyEngine::evaluate(CFURLRef path, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, CFMutableDictionaryRef result)
86 {
87 // update GKE
88 installExplicitSet(gkeAuthFile, gkeSigsFile);
89
90 // find the global evaluation manager
91 EvaluationManager *evaluationManager = EvaluationManager::globalManager();
92
93 // perform the evaluation
94 EvaluationTask *evaluationTask = evaluationManager->evaluationTask(this, path, type, flags, context, result);
95 evaluationManager->finalizeTask(evaluationTask, flags, result);
96
97 // if rejected, reset the automatic rearm timer
98 if (CFDictionaryGetValue(result, kSecAssessmentAssessmentVerdict) == kCFBooleanFalse)
99 resetRearmTimer("reject");
100 }
101
102
103 static std::string createWhitelistScreen(char type, const Byte *digest, size_t length)
104 {
105 char buffer[2*length + 2];
106 buffer[0] = type;
107 for (size_t n = 0; n < length; n++)
108 sprintf(buffer + 1 + 2*n, "%02.2x", digest[n]);
109 return buffer;
110 }
111
112
113 void PolicyEngine::evaluateCodeItem(SecStaticCodeRef code, CFURLRef path, AuthorityType type, SecAssessmentFlags flags, bool nested, CFMutableDictionaryRef result)
114 {
115
116 SQLite::Statement query(*this,
117 "SELECT allow, requirement, id, label, expires, flags, disabled, filter_unsigned, remarks FROM scan_authority"
118 " WHERE type = :type"
119 " ORDER BY priority DESC;");
120 query.bind(":type").integer(type);
121
122 SQLite3::int64 latentID = 0; // first (highest priority) disabled matching ID
123 std::string latentLabel; // ... and associated label, if any
124
125 while (query.nextRow()) {
126 bool allow = int(query[0]);
127 const char *reqString = query[1];
128 SQLite3::int64 id = query[2];
129 const char *label = query[3];
130 double expires = query[4];
131 sqlite3_int64 ruleFlags = query[5];
132 SQLite3::int64 disabled = query[6];
133 // const char *filter = query[7];
134 // const char *remarks = query[8];
135
136 CFRef<SecRequirementRef> requirement;
137 MacOSError::check(SecRequirementCreateWithString(CFTempString(reqString), kSecCSDefaultFlags, &requirement.aref()));
138 switch (OSStatus rc = SecStaticCodeCheckValidity(code, kSecCSBasicValidateOnly | kSecCSCheckGatekeeperArchitectures, requirement)) {
139 case errSecSuccess:
140 break; // rule match; process below
141 case errSecCSReqFailed:
142 continue; // rule does not apply
143 case errSecCSVetoed:
144 return; // nested code has failed to pass
145 default:
146 MacOSError::throwMe(rc); // general error; pass to caller
147 }
148
149 // if this rule is disabled, skip it but record the first matching one for posterity
150 if (disabled && latentID == 0) {
151 latentID = id;
152 latentLabel = label ? label : "";
153 continue;
154 }
155
156 // current rule is first rule (in priority order) that matched. Apply it
157 if (nested) // success, nothing to record
158 return;
159
160 CFRef<CFDictionaryRef> info; // as needed
161 if (flags & kSecAssessmentFlagRequestOrigin) {
162 if (!info)
163 MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref()));
164 if (CFArrayRef chain = CFArrayRef(CFDictionaryGetValue(info, kSecCodeInfoCertificates)))
165 setOrigin(chain, result);
166 }
167 if (!(ruleFlags & kAuthorityFlagInhibitCache) && !(flags & kSecAssessmentFlagNoCache)) { // cache inhibit
168 if (!info)
169 MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref()));
170 if (SecTrustRef trust = SecTrustRef(CFDictionaryGetValue(info, kSecCodeInfoTrust))) {
171 CFRef<CFDictionaryRef> xinfo;
172 MacOSError::check(SecTrustCopyExtendedResult(trust, &xinfo.aref()));
173 if (CFDateRef limit = CFDateRef(CFDictionaryGetValue(xinfo, kSecTrustExpirationDate))) {
174 this->recordOutcome(code, allow, type, min(expires, dateToJulian(limit)), id);
175 }
176 }
177 }
178 if (allow) {
179 if (SYSPOLICY_ASSESS_OUTCOME_ACCEPT_ENABLED()) {
180 if (!info)
181 MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref()));
182 CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique));
183 SYSPOLICY_ASSESS_OUTCOME_ACCEPT(cfString(path).c_str(), type, label, cdhash ? CFDataGetBytePtr(cdhash) : NULL);
184 }
185 } else {
186 if (SYSPOLICY_ASSESS_OUTCOME_DENY_ENABLED() || SYSPOLICY_RECORDER_MODE_ENABLED()) {
187 if (!info)
188 MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref()));
189 CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique));
190 std::string cpath = cfString(path);
191 const void *hashp = cdhash ? CFDataGetBytePtr(cdhash) : NULL;
192 SYSPOLICY_ASSESS_OUTCOME_DENY(cpath.c_str(), type, label, hashp);
193 SYSPOLICY_RECORDER_MODE(cpath.c_str(), type, label, hashp, recorder_code_untrusted);
194 }
195 }
196 cfadd(result, "{%O=%B}", kSecAssessmentAssessmentVerdict, allow);
197 addAuthority(flags, result, label, id);
198 return;
199 }
200
201 // no applicable authority (but signed, perhaps temporarily). Deny by default
202 CFRef<CFDictionaryRef> info;
203 MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref()));
204 if (flags & kSecAssessmentFlagRequestOrigin) {
205 if (CFArrayRef chain = CFArrayRef(CFDictionaryGetValue(info, kSecCodeInfoCertificates)))
206 setOrigin(chain, result);
207 }
208 if (SYSPOLICY_ASSESS_OUTCOME_DEFAULT_ENABLED() || SYSPOLICY_RECORDER_MODE_ENABLED()) {
209 CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique));
210 const void *hashp = cdhash ? CFDataGetBytePtr(cdhash) : NULL;
211 std::string cpath = cfString(path);
212 SYSPOLICY_ASSESS_OUTCOME_DEFAULT(cpath.c_str(), type, latentLabel.c_str(), hashp);
213 SYSPOLICY_RECORDER_MODE(cpath.c_str(), type, latentLabel.c_str(), hashp, 0);
214 }
215 if (!(flags & kSecAssessmentFlagNoCache))
216 this->recordOutcome(code, false, type, this->julianNow() + NEGATIVE_HOLD, latentID);
217 cfadd(result, "{%O=%B}", kSecAssessmentAssessmentVerdict, false);
218 addAuthority(flags, result, latentLabel.c_str(), latentID);
219 }
220
221
222 void PolicyEngine::adjustValidation(SecStaticCodeRef code)
223 {
224 CFRef<CFDictionaryRef> conditions = mOpaqueWhitelist.validationConditionsFor(code);
225 SecStaticCodeSetValidationConditions(code, conditions);
226 }
227
228
229 bool PolicyEngine::temporarySigning(SecStaticCodeRef code, AuthorityType type, CFURLRef path, SecAssessmentFlags matchFlags)
230 {
231 if (matchFlags == 0) { // playback; consult authority table for matches
232 DiskRep *rep = SecStaticCode::requiredStatic(code)->diskRep();
233 std::string screen;
234 if (CFRef<CFDataRef> info = rep->component(cdInfoSlot)) {
235 SHA1 hash;
236 hash.update(CFDataGetBytePtr(info), CFDataGetLength(info));
237 SHA1::Digest digest;
238 hash.finish(digest);
239 screen = createWhitelistScreen('I', digest, sizeof(digest));
240 } else if (CFRef<CFDataRef> repSpecific = rep->component(cdRepSpecificSlot)) {
241 // got invented after SHA-1 deprecation, so we'll use SHA256, which is the new default
242 CCHashInstance hash(kCCDigestSHA256);
243 hash.update(CFDataGetBytePtr(repSpecific), CFDataGetLength(repSpecific));
244 Byte digest[256/8];
245 hash.finish(digest);
246 screen = createWhitelistScreen('R', digest, sizeof(digest));
247 } else if (rep->mainExecutableImage()) {
248 screen = "N";
249 } else {
250 SHA1 hash;
251 hashFileData(rep->mainExecutablePath().c_str(), &hash);
252 SHA1::Digest digest;
253 hash.finish(digest);
254 screen = createWhitelistScreen('M', digest, sizeof(digest));
255 }
256 SQLite::Statement query(*this,
257 "SELECT flags FROM authority "
258 "WHERE type = :type"
259 " AND NOT flags & :flag"
260 " AND CASE WHEN filter_unsigned IS NULL THEN remarks = :remarks ELSE filter_unsigned = :screen END");
261 query.bind(":type").integer(type);
262 query.bind(":flag").integer(kAuthorityFlagDefault);
263 query.bind(":screen") = screen;
264 query.bind(":remarks") = cfString(path);
265 if (!query.nextRow()) // guaranteed no matching rule
266 return false;
267 matchFlags = SQLite3::int64(query[0]);
268 }
269
270 try {
271 // ad-hoc sign the code and attach the signature
272 CFRef<CFDataRef> signature = CFDataCreateMutable(NULL, 0);
273 CFTemp<CFMutableDictionaryRef> arguments("{%O=%O, %O=#N, %O=%d}", kSecCodeSignerDetached, signature.get(), kSecCodeSignerIdentity,
274 kSecCodeSignerDigestAlgorithm, (matchFlags & kAuthorityFlagWhitelistSHA256) ? kSecCodeSignatureHashSHA256 : kSecCodeSignatureHashSHA1);
275 CFRef<SecCodeSignerRef> signer;
276 MacOSError::check(SecCodeSignerCreate(arguments, (matchFlags & kAuthorityFlagWhitelistV2) ? kSecCSSignOpaque : kSecCSSignV1, &signer.aref()));
277 MacOSError::check(SecCodeSignerAddSignature(signer, code, kSecCSDefaultFlags));
278 MacOSError::check(SecCodeSetDetachedSignature(code, signature, kSecCSDefaultFlags));
279
280 SecRequirementRef dr = NULL;
281 SecCodeCopyDesignatedRequirement(code, kSecCSDefaultFlags, &dr);
282 CFStringRef drs = NULL;
283 SecRequirementCopyString(dr, kSecCSDefaultFlags, &drs);
284
285 // if we're in GKE recording mode, save that signature and report its location
286 if (SYSPOLICY_RECORDER_MODE_ENABLED()) {
287 int status = recorder_code_unable; // ephemeral signature (not recorded)
288 if (geteuid() == 0) {
289 CFRef<CFUUIDRef> uuid = CFUUIDCreate(NULL);
290 std::string sigfile = RECORDER_DIR + cfStringRelease(CFUUIDCreateString(NULL, uuid)) + ".tsig";
291 try {
292 UnixPlusPlus::AutoFileDesc fd(sigfile, O_WRONLY | O_CREAT);
293 fd.write(CFDataGetBytePtr(signature), CFDataGetLength(signature));
294 status = recorder_code_adhoc; // recorded signature
295 SYSPOLICY_RECORDER_MODE_ADHOC_PATH(cfString(path).c_str(), type, sigfile.c_str());
296 } catch (...) { }
297 }
298
299 // now report the D probe itself
300 CFRef<CFDictionaryRef> info;
301 MacOSError::check(SecCodeCopySigningInformation(code, kSecCSDefaultFlags, &info.aref()));
302 CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique));
303 SYSPOLICY_RECORDER_MODE(cfString(path).c_str(), type, "",
304 cdhash ? CFDataGetBytePtr(cdhash) : NULL, status);
305 }
306
307 return true; // it worked; we're now (well) signed
308 } catch (...) { }
309
310 return false;
311 }
312
313
314 //
315 // Executable code.
316 // Read from disk, evaluate properly, cache as indicated.
317 //
318 void PolicyEngine::evaluateCode(CFURLRef path, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, CFMutableDictionaryRef result, bool handleUnsigned)
319 {
320 // not really a Gatekeeper function... but reject all "hard quarantined" files because they were made from sandboxed sources without download privilege
321 FileQuarantine qtn(cfString(path).c_str());
322 if (qtn.flag(QTN_FLAG_HARD))
323 MacOSError::throwMe(errSecCSFileHardQuarantined);
324
325 CFCopyRef<SecStaticCodeRef> code;
326 MacOSError::check(SecStaticCodeCreateWithPath(path, kSecCSDefaultFlags, &code.aref()));
327
328 SecCSFlags validationFlags = kSecCSEnforceRevocationChecks | kSecCSCheckAllArchitectures;
329 if (!(flags & kSecAssessmentFlagAllowWeak))
330 validationFlags |= kSecCSStrictValidate;
331 adjustValidation(code);
332
333 // deal with a very special case (broken 10.6/10.7 Applet bundles)
334 OSStatus rc = SecStaticCodeCheckValidity(code, validationFlags | kSecCSBasicValidateOnly, NULL);
335 if (rc == errSecCSSignatureFailed) {
336 if (!codeInvalidityExceptions(code, result)) { // invalidly signed, no exceptions -> error
337 if (SYSPOLICY_ASSESS_OUTCOME_BROKEN_ENABLED())
338 SYSPOLICY_ASSESS_OUTCOME_BROKEN(cfString(path).c_str(), type, false);
339 MacOSError::throwMe(rc);
340 }
341 // recognized exception - treat as unsigned
342 if (SYSPOLICY_ASSESS_OUTCOME_BROKEN_ENABLED())
343 SYSPOLICY_ASSESS_OUTCOME_BROKEN(cfString(path).c_str(), type, true);
344 rc = errSecCSUnsigned;
345 }
346
347 // ad-hoc sign unsigned code
348 if (rc == errSecCSUnsigned && handleUnsigned && (!overrideAssessment(flags) || SYSPOLICY_RECORDER_MODE_ENABLED())) {
349 if (temporarySigning(code, type, path, 0)) {
350 rc = errSecSuccess; // clear unsigned; we are now well-signed
351 validationFlags |= kSecCSBasicValidateOnly; // no need to re-validate deep contents
352 }
353 }
354
355 // prepare for deep traversal of (hopefully) good signatures
356 SecAssessmentFeedback feedback = SecAssessmentFeedback(CFDictionaryGetValue(context, kSecAssessmentContextKeyFeedback));
357 MacOSError::check(SecStaticCodeSetCallback(code, kSecCSDefaultFlags, NULL, ^CFTypeRef (SecStaticCodeRef item, CFStringRef cfStage, CFDictionaryRef info) {
358 string stage = cfString(cfStage);
359 if (stage == "prepared") {
360 if (!CFEqual(item, code)) // genuine nested (not top) code
361 adjustValidation(item);
362 } else if (stage == "progress") {
363 if (feedback && CFEqual(item, code)) { // top level progress
364 bool proceed = feedback(kSecAssessmentFeedbackProgress, info);
365 if (!proceed)
366 SecStaticCodeCancelValidation(code, kSecCSDefaultFlags);
367 }
368 } else if (stage == "validated") {
369 SecStaticCodeSetCallback(item, kSecCSDefaultFlags, NULL, NULL); // clear callback to avoid unwanted recursion
370 evaluateCodeItem(item, path, type, flags, item != code, result);
371 if (CFTypeRef verdict = CFDictionaryGetValue(result, kSecAssessmentAssessmentVerdict))
372 if (CFEqual(verdict, kCFBooleanFalse))
373 return makeCFNumber(OSStatus(errSecCSVetoed)); // (signal nested-code policy failure, picked up below)
374 }
375 return NULL;
376 }));
377
378 // go for it!
379 SecCSFlags topFlags = validationFlags | kSecCSCheckNestedCode | kSecCSRestrictSymlinks | kSecCSReportProgress;
380 if (type == kAuthorityExecute)
381 topFlags |= kSecCSRestrictToAppLike;
382 switch (rc = SecStaticCodeCheckValidity(code, topFlags, NULL)) {
383 case errSecSuccess: // continue below
384 break;
385 case errSecCSUnsigned:
386 cfadd(result, "{%O=#F}", kSecAssessmentAssessmentVerdict);
387 addAuthority(flags, result, "no usable signature");
388 return;
389 case errSecCSVetoed: // nested code rejected by rule book; result was filled out there
390 return;
391 case errSecCSWeakResourceRules:
392 case errSecCSWeakResourceEnvelope:
393 case errSecCSResourceNotSupported:
394 case errSecCSAmbiguousBundleFormat:
395 case errSecCSSignatureNotVerifiable:
396 case errSecCSRegularFile:
397 case errSecCSBadMainExecutable:
398 case errSecCSBadFrameworkVersion:
399 case errSecCSUnsealedAppRoot:
400 case errSecCSUnsealedFrameworkRoot:
401 case errSecCSInvalidSymlink:
402 case errSecCSNotAppLike:
403 {
404 // consult the whitelist
405 bool allow = false;
406 const char *label;
407 // we've bypassed evaluateCodeItem before we failed validation. Explicitly apply it now
408 SecStaticCodeSetCallback(code, kSecCSDefaultFlags, NULL, NULL);
409 evaluateCodeItem(code, path, type, flags | kSecAssessmentFlagNoCache, false, result);
410 if (CFTypeRef verdict = CFDictionaryGetValue(result, kSecAssessmentAssessmentVerdict)) {
411 // verdict rendered from a nested component - signature not acceptable to Gatekeeper
412 if (CFEqual(verdict, kCFBooleanFalse)) // nested code rejected by rule book; result was filled out there
413 return;
414 if (CFEqual(verdict, kCFBooleanTrue) && !(flags & kSecAssessmentFlagIgnoreWhitelist))
415 if (mOpaqueWhitelist.contains(code, feedback, rc))
416 allow = true;
417 }
418 if (allow) {
419 label = "allowed cdhash";
420 } else {
421 CFDictionaryReplaceValue(result, kSecAssessmentAssessmentVerdict, kCFBooleanFalse);
422 label = "obsolete resource envelope";
423 }
424 cfadd(result, "{%O=%d}", kSecAssessmentAssessmentCodeSigningError, rc);
425 addAuthority(flags, result, label, 0, NULL, true);
426 return;
427 }
428 default:
429 MacOSError::throwMe(rc);
430 }
431 }
432
433
434 //
435 // Installer archive.
436 // Hybrid policy: If we detect an installer signature, use and validate that.
437 // If we don't, check for a code signature instead.
438 //
439 void PolicyEngine::evaluateInstall(CFURLRef path, SecAssessmentFlags flags, CFDictionaryRef context, CFMutableDictionaryRef result)
440 {
441 const AuthorityType type = kAuthorityInstall;
442
443 // check for recent explicit approval, using a bookmark's FileResourceIdentifierKey
444 if (CFRef<CFDataRef> bookmark = cfLoadFile(lastApprovedFile)) {
445 Boolean stale;
446 if (CFRef<CFURLRef> url = CFURLCreateByResolvingBookmarkData(NULL, bookmark,
447 kCFBookmarkResolutionWithoutUIMask | kCFBookmarkResolutionWithoutMountingMask, NULL, NULL, &stale, NULL))
448 if (CFRef<CFDataRef> savedIdent = CFDataRef(CFURLCreateResourcePropertyForKeyFromBookmarkData(NULL, kCFURLFileResourceIdentifierKey, bookmark)))
449 if (CFRef<CFDateRef> savedMod = CFDateRef(CFURLCreateResourcePropertyForKeyFromBookmarkData(NULL, kCFURLContentModificationDateKey, bookmark))) {
450 CFRef<CFDataRef> currentIdent;
451 CFRef<CFDateRef> currentMod;
452 if (CFURLCopyResourcePropertyForKey(path, kCFURLFileResourceIdentifierKey, &currentIdent.aref(), NULL))
453 if (CFURLCopyResourcePropertyForKey(path, kCFURLContentModificationDateKey, &currentMod.aref(), NULL))
454 if (CFEqual(savedIdent, currentIdent) && CFEqual(savedMod, currentMod)) {
455 cfadd(result, "{%O=#T}", kSecAssessmentAssessmentVerdict);
456 addAuthority(flags, result, "explicit preference");
457 return;
458 }
459 }
460 }
461
462 Xar xar(cfString(path).c_str());
463 if (!xar) {
464 // follow the code signing path
465 evaluateCode(path, type, flags, context, result, true);
466 return;
467 }
468
469 SQLite3::int64 latentID = 0; // first (highest priority) disabled matching ID
470 std::string latentLabel; // ... and associated label, if any
471 if (!xar.isSigned()) {
472 // unsigned xar
473 if (SYSPOLICY_ASSESS_OUTCOME_UNSIGNED_ENABLED())
474 SYSPOLICY_ASSESS_OUTCOME_UNSIGNED(cfString(path).c_str(), type);
475 cfadd(result, "{%O=#F}", kSecAssessmentAssessmentVerdict);
476 addAuthority(flags, result, "no usable signature");
477 return;
478 }
479 if (CFRef<CFArrayRef> certs = xar.copyCertChain()) {
480 CFRef<CFTypeRef> policy = installerPolicy();
481 CFRef<SecTrustRef> trust;
482 MacOSError::check(SecTrustCreateWithCertificates(certs, policy, &trust.aref()));
483 // MacOSError::check(SecTrustSetAnchorCertificates(trust, cfEmptyArray())); // no anchors
484 MacOSError::check(SecTrustSetOptions(trust, kSecTrustOptionAllowExpired | kSecTrustOptionImplicitAnchors));
485
486 SecTrustResultType trustResult;
487 MacOSError::check(SecTrustEvaluate(trust, &trustResult));
488 CFRef<CFArrayRef> chain;
489 CSSM_TP_APPLE_EVIDENCE_INFO *info;
490 MacOSError::check(SecTrustGetResult(trust, &trustResult, &chain.aref(), &info));
491
492 if (flags & kSecAssessmentFlagRequestOrigin)
493 setOrigin(chain, result);
494
495 switch (trustResult) {
496 case kSecTrustResultProceed:
497 case kSecTrustResultUnspecified:
498 break;
499 default:
500 {
501 OSStatus rc;
502 MacOSError::check(SecTrustGetCssmResultCode(trust, &rc));
503 MacOSError::throwMe(rc);
504 }
505 }
506
507 SQLite::Statement query(*this,
508 "SELECT allow, requirement, id, label, flags, disabled FROM scan_authority"
509 " WHERE type = :type"
510 " ORDER BY priority DESC;");
511 query.bind(":type").integer(type);
512 while (query.nextRow()) {
513 bool allow = int(query[0]);
514 const char *reqString = query[1];
515 SQLite3::int64 id = query[2];
516 const char *label = query[3];
517 //sqlite_uint64 ruleFlags = query[4];
518 SQLite3::int64 disabled = query[5];
519
520 CFRef<SecRequirementRef> requirement;
521 MacOSError::check(SecRequirementCreateWithString(CFTempString(reqString), kSecCSDefaultFlags, &requirement.aref()));
522 switch (OSStatus rc = SecRequirementEvaluate(requirement, chain, NULL, kSecCSDefaultFlags)) {
523 case errSecSuccess: // success
524 break;
525 case errSecCSReqFailed: // requirement missed, but otherwise okay
526 continue;
527 default: // broken in some way; all tests will fail like this so bail out
528 MacOSError::throwMe(rc);
529 }
530 if (disabled) {
531 if (latentID == 0) {
532 latentID = id;
533 if (label)
534 latentLabel = label;
535 }
536 continue; // the loop
537 }
538
539 if (SYSPOLICY_ASSESS_OUTCOME_ACCEPT_ENABLED() || SYSPOLICY_ASSESS_OUTCOME_DENY_ENABLED()) {
540 if (allow)
541 SYSPOLICY_ASSESS_OUTCOME_ACCEPT(cfString(path).c_str(), type, label, NULL);
542 else
543 SYSPOLICY_ASSESS_OUTCOME_DENY(cfString(path).c_str(), type, label, NULL);
544 }
545
546 // not adding to the object cache - we could, but it's not likely to be worth it
547 cfadd(result, "{%O=%B}", kSecAssessmentAssessmentVerdict, allow);
548 addAuthority(flags, result, label, id);
549 return;
550 }
551 }
552 if (SYSPOLICY_ASSESS_OUTCOME_DEFAULT_ENABLED())
553 SYSPOLICY_ASSESS_OUTCOME_DEFAULT(cfString(path).c_str(), type, latentLabel.c_str(), NULL);
554
555 // no applicable authority. Deny by default
556 cfadd(result, "{%O=#F}", kSecAssessmentAssessmentVerdict);
557 addAuthority(flags, result, latentLabel.c_str(), latentID);
558 }
559
560
561 //
562 // Create a suitable policy array for verification of installer signatures.
563 //
564 static SecPolicyRef makeCRLPolicy()
565 {
566 CFRef<SecPolicyRef> policy;
567 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_REVOCATION_CRL, &policy.aref()));
568 CSSM_APPLE_TP_CRL_OPTIONS options;
569 memset(&options, 0, sizeof(options));
570 options.Version = CSSM_APPLE_TP_CRL_OPTS_VERSION;
571 options.CrlFlags = CSSM_TP_ACTION_FETCH_CRL_FROM_NET | CSSM_TP_ACTION_CRL_SUFFICIENT;
572 CSSM_DATA optData = { sizeof(options), (uint8 *)&options };
573 MacOSError::check(SecPolicySetValue(policy, &optData));
574 return policy.yield();
575 }
576
577 static SecPolicyRef makeOCSPPolicy()
578 {
579 CFRef<SecPolicyRef> policy;
580 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_REVOCATION_OCSP, &policy.aref()));
581 CSSM_APPLE_TP_OCSP_OPTIONS options;
582 memset(&options, 0, sizeof(options));
583 options.Version = CSSM_APPLE_TP_OCSP_OPTS_VERSION;
584 options.Flags = CSSM_TP_ACTION_OCSP_SUFFICIENT;
585 CSSM_DATA optData = { sizeof(options), (uint8 *)&options };
586 MacOSError::check(SecPolicySetValue(policy, &optData));
587 return policy.yield();
588 }
589
590 static CFTypeRef installerPolicy()
591 {
592 CFRef<SecPolicyRef> base = SecPolicyCreateBasicX509();
593 CFRef<SecPolicyRef> crl = makeCRLPolicy();
594 CFRef<SecPolicyRef> ocsp = makeOCSPPolicy();
595 return makeCFArray(3, base.get(), crl.get(), ocsp.get());
596 }
597
598
599 //
600 // LaunchServices-layer document open.
601 // We don't cache those at present. If we ever do, we need to authenticate CoreServicesUIAgent as the source of its risk assessment.
602 //
603 void PolicyEngine::evaluateDocOpen(CFURLRef path, SecAssessmentFlags flags, CFDictionaryRef context, CFMutableDictionaryRef result)
604 {
605 if (context) {
606 if (CFStringRef riskCategory = CFStringRef(CFDictionaryGetValue(context, kLSDownloadRiskCategoryKey))) {
607 FileQuarantine qtn(cfString(path).c_str());
608
609 if (CFEqual(riskCategory, kLSRiskCategorySafe)
610 || CFEqual(riskCategory, kLSRiskCategoryNeutral)
611 || CFEqual(riskCategory, kLSRiskCategoryUnknown)
612 || CFEqual(riskCategory, kLSRiskCategoryMayContainUnsafeExecutable)) {
613 cfadd(result, "{%O=#T}", kSecAssessmentAssessmentVerdict);
614 addAuthority(flags, result, "_XProtect");
615 } else if (qtn.flag(QTN_FLAG_HARD)) {
616 MacOSError::throwMe(errSecCSFileHardQuarantined);
617 } else if (qtn.flag(QTN_FLAG_ASSESSMENT_OK)) {
618 cfadd(result, "{%O=#T}", kSecAssessmentAssessmentVerdict);
619 addAuthority(flags, result, "Prior Assessment");
620 } else if (!overrideAssessment(flags)) { // no need to do more work if we're off
621 try {
622 evaluateCode(path, kAuthorityOpenDoc, flags, context, result, true);
623 } catch (...) {
624 // some documents can't be code signed, so this may be quite benign
625 }
626 }
627 if (CFDictionaryGetValue(result, kSecAssessmentAssessmentVerdict) == NULL) { // no code signature to help us out
628 cfadd(result, "{%O=#F}", kSecAssessmentAssessmentVerdict);
629 addAuthority(flags, result, "_XProtect");
630 }
631 addToAuthority(result, kLSDownloadRiskCategoryKey, riskCategory);
632 return;
633 }
634 }
635 // insufficient information from LS - deny by default
636 cfadd(result, "{%O=#F}", kSecAssessmentAssessmentVerdict);
637 addAuthority(flags, result, "Insufficient Context");
638 }
639
640
641 //
642 // Result-creation helpers
643 //
644 void PolicyEngine::addAuthority(SecAssessmentFlags flags, CFMutableDictionaryRef parent, const char *label, SQLite::int64 row, CFTypeRef cacheInfo, bool weak)
645 {
646 CFRef<CFMutableDictionaryRef> auth = makeCFMutableDictionary();
647 if (label && label[0])
648 cfadd(auth, "{%O=%s}", kSecAssessmentAssessmentSource, label);
649 if (row)
650 CFDictionaryAddValue(auth, kSecAssessmentAssessmentAuthorityRow, CFTempNumber(row));
651 if (overrideAssessment(flags))
652 CFDictionaryAddValue(auth, kSecAssessmentAssessmentAuthorityOverride, kDisabledOverride);
653 if (cacheInfo)
654 CFDictionaryAddValue(auth, kSecAssessmentAssessmentFromCache, cacheInfo);
655 if (weak) {
656 CFDictionaryAddValue(auth, kSecAssessmentAssessmentWeakSignature, kCFBooleanTrue);
657 CFDictionaryReplaceValue(parent, kSecAssessmentAssessmentAuthority, auth);
658 } else {
659 CFDictionaryAddValue(parent, kSecAssessmentAssessmentAuthority, auth);
660 }
661 }
662
663 void PolicyEngine::addToAuthority(CFMutableDictionaryRef parent, CFStringRef key, CFTypeRef value)
664 {
665 CFMutableDictionaryRef authority = CFMutableDictionaryRef(CFDictionaryGetValue(parent, kSecAssessmentAssessmentAuthority));
666 assert(authority);
667 CFDictionaryAddValue(authority, key, value);
668 }
669
670
671 //
672 // Add a rule to the policy database
673 //
674 CFDictionaryRef PolicyEngine::add(CFTypeRef inTarget, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context)
675 {
676 // default type to execution
677 if (type == kAuthorityInvalid)
678 type = kAuthorityExecute;
679
680 authorizeUpdate(flags, context);
681 CFDictionary ctx(context, errSecCSInvalidAttributeValues);
682 CFCopyRef<CFTypeRef> target = inTarget;
683 CFRef<CFDataRef> bookmark = NULL;
684 std::string filter_unsigned;
685
686 switch (type) {
687 case kAuthorityExecute:
688 normalizeTarget(target, type, ctx, &filter_unsigned);
689 // bookmarks are untrusted and just a hint to callers
690 bookmark = ctx.get<CFDataRef>(kSecAssessmentRuleKeyBookmark);
691 break;
692 case kAuthorityInstall:
693 if (inTarget && CFGetTypeID(inTarget) == CFURLGetTypeID()) {
694 // no good way to turn an installer file into a requirement. Pretend to succeeed so caller proceeds
695 CFRef<CFArrayRef> properties = makeCFArray(2, kCFURLFileResourceIdentifierKey, kCFURLContentModificationDateKey);
696 CFRef<CFErrorRef> error;
697 CFURLBookmarkCreationOptions options = kCFURLBookmarkCreationDoNotIncludeSandboxExtensionsMask | kCFURLBookmarkCreationMinimalBookmarkMask;
698 if (CFRef<CFDataRef> bookmark = CFURLCreateBookmarkData(NULL, CFURLRef(inTarget), options, properties, NULL, &error.aref())) {
699 UnixPlusPlus::AutoFileDesc fd(lastApprovedFile, O_WRONLY | O_CREAT | O_TRUNC);
700 fd.write(CFDataGetBytePtr(bookmark), CFDataGetLength(bookmark));
701 return NULL;
702 }
703 }
704 break;
705 case kAuthorityOpenDoc:
706 // handle document-open differently: use quarantine flags for whitelisting
707 if (!target || CFGetTypeID(target) != CFURLGetTypeID()) // can only "add" file paths
708 MacOSError::throwMe(errSecCSInvalidObjectRef);
709 try {
710 std::string spath = cfString(target.as<CFURLRef>());
711 FileQuarantine qtn(spath.c_str());
712 qtn.setFlag(QTN_FLAG_ASSESSMENT_OK);
713 qtn.applyTo(spath.c_str());
714 } catch (const CommonError &error) {
715 // could not set quarantine flag - report qualified success
716 return cfmake<CFDictionaryRef>("{%O=%O,'assessment:error'=%d}",
717 kSecAssessmentAssessmentAuthorityOverride, CFSTR("error setting quarantine"), error.osStatus());
718 } catch (...) {
719 return cfmake<CFDictionaryRef>("{%O=%O}", kSecAssessmentAssessmentAuthorityOverride, CFSTR("unable to set quarantine"));
720 }
721 return NULL;
722 }
723
724 // if we now have anything else, we're busted
725 if (!target || CFGetTypeID(target) != SecRequirementGetTypeID())
726 MacOSError::throwMe(errSecCSInvalidObjectRef);
727
728 double priority = 0;
729 string label;
730 bool allow = true;
731 double expires = never;
732 string remarks;
733 SQLite::uint64 dbFlags = kAuthorityFlagWhitelistV2 | kAuthorityFlagWhitelistSHA256;
734
735 if (CFNumberRef pri = ctx.get<CFNumberRef>(kSecAssessmentUpdateKeyPriority))
736 CFNumberGetValue(pri, kCFNumberDoubleType, &priority);
737 if (CFStringRef lab = ctx.get<CFStringRef>(kSecAssessmentUpdateKeyLabel))
738 label = cfString(lab);
739 if (CFDateRef time = ctx.get<CFDateRef>(kSecAssessmentUpdateKeyExpires))
740 // we're using Julian dates here; convert from CFDate
741 expires = dateToJulian(time);
742 if (CFBooleanRef allowing = ctx.get<CFBooleanRef>(kSecAssessmentUpdateKeyAllow))
743 allow = allowing == kCFBooleanTrue;
744 if (CFStringRef rem = ctx.get<CFStringRef>(kSecAssessmentUpdateKeyRemarks))
745 remarks = cfString(rem);
746
747 CFRef<CFStringRef> requirementText;
748 MacOSError::check(SecRequirementCopyString(target.as<SecRequirementRef>(), kSecCSDefaultFlags, &requirementText.aref()));
749 SQLite::Transaction xact(*this, SQLite3::Transaction::deferred, "add_rule");
750 SQLite::Statement insert(*this,
751 "INSERT INTO authority (type, allow, requirement, priority, label, expires, filter_unsigned, remarks, flags)"
752 " VALUES (:type, :allow, :requirement, :priority, :label, :expires, :filter_unsigned, :remarks, :flags);");
753 insert.bind(":type").integer(type);
754 insert.bind(":allow").integer(allow);
755 insert.bind(":requirement") = requirementText.get();
756 insert.bind(":priority") = priority;
757 if (!label.empty())
758 insert.bind(":label") = label;
759 insert.bind(":expires") = expires;
760 insert.bind(":filter_unsigned") = filter_unsigned.empty() ? NULL : filter_unsigned.c_str();
761 if (!remarks.empty())
762 insert.bind(":remarks") = remarks;
763 insert.bind(":flags").integer(dbFlags);
764 insert.execute();
765 SQLite::int64 newRow = this->lastInsert();
766 if (bookmark) {
767 SQLite::Statement bi(*this, "INSERT INTO bookmarkhints (bookmark, authority) VALUES (:bookmark, :authority)");
768 bi.bind(":bookmark") = CFDataRef(bookmark);
769 bi.bind(":authority").integer(newRow);
770 bi.execute();
771 }
772 this->purgeObjects(priority);
773 xact.commit();
774 notify_post(kNotifySecAssessmentUpdate);
775 return cfmake<CFDictionaryRef>("{%O=%d}", kSecAssessmentUpdateKeyRow, newRow);
776 }
777
778
779 CFDictionaryRef PolicyEngine::remove(CFTypeRef target, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context)
780 {
781 if (type == kAuthorityOpenDoc) {
782 // handle document-open differently: use quarantine flags for whitelisting
783 authorizeUpdate(flags, context);
784 if (!target || CFGetTypeID(target) != CFURLGetTypeID())
785 MacOSError::throwMe(errSecCSInvalidObjectRef);
786 std::string spath = cfString(CFURLRef(target)).c_str();
787 FileQuarantine qtn(spath.c_str());
788 qtn.clearFlag(QTN_FLAG_ASSESSMENT_OK);
789 qtn.applyTo(spath.c_str());
790 return NULL;
791 }
792 return manipulateRules("DELETE FROM authority", target, type, flags, context, true);
793 }
794
795 CFDictionaryRef PolicyEngine::enable(CFTypeRef target, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, bool authorize)
796 {
797 return manipulateRules("UPDATE authority SET disabled = 0", target, type, flags, context, authorize);
798 }
799
800 CFDictionaryRef PolicyEngine::disable(CFTypeRef target, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, bool authorize)
801 {
802 return manipulateRules("UPDATE authority SET disabled = 1", target, type, flags, context, authorize);
803 }
804
805 CFDictionaryRef PolicyEngine::find(CFTypeRef target, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context)
806 {
807 SQLite::Statement query(*this);
808 selectRules(query, "SELECT scan_authority.id, scan_authority.type, scan_authority.requirement, scan_authority.allow, scan_authority.label, scan_authority.priority, scan_authority.remarks, scan_authority.expires, scan_authority.disabled, bookmarkhints.bookmark FROM scan_authority LEFT OUTER JOIN bookmarkhints ON scan_authority.id = bookmarkhints.authority",
809 "scan_authority", target, type, flags, context,
810 " ORDER BY priority DESC");
811 CFRef<CFMutableArrayRef> found = makeCFMutableArray(0);
812 while (query.nextRow()) {
813 SQLite::int64 id = query[0];
814 int type = int(query[1]);
815 const char *requirement = query[2];
816 int allow = int(query[3]);
817 const char *label = query[4];
818 double priority = query[5];
819 const char *remarks = query[6];
820 double expires = query[7];
821 int disabled = int(query[8]);
822 CFRef<CFDataRef> bookmark = query[9].data();
823 CFRef<CFMutableDictionaryRef> rule = makeCFMutableDictionary(5,
824 kSecAssessmentRuleKeyID, CFTempNumber(id).get(),
825 kSecAssessmentRuleKeyType, CFRef<CFStringRef>(typeNameFor(type)).get(),
826 kSecAssessmentRuleKeyRequirement, CFTempString(requirement).get(),
827 kSecAssessmentRuleKeyAllow, allow ? kCFBooleanTrue : kCFBooleanFalse,
828 kSecAssessmentRuleKeyPriority, CFTempNumber(priority).get()
829 );
830 if (label)
831 CFDictionaryAddValue(rule, kSecAssessmentRuleKeyLabel, CFTempString(label));
832 if (remarks)
833 CFDictionaryAddValue(rule, kSecAssessmentRuleKeyRemarks, CFTempString(remarks));
834 if (expires != never)
835 CFDictionaryAddValue(rule, kSecAssessmentRuleKeyExpires, CFRef<CFDateRef>(julianToDate(expires)));
836 if (disabled)
837 CFDictionaryAddValue(rule, kSecAssessmentRuleKeyDisabled, CFTempNumber(disabled));
838 if (bookmark)
839 CFDictionaryAddValue(rule, kSecAssessmentRuleKeyBookmark, bookmark);
840 CFArrayAppendValue(found, rule);
841 }
842 if (CFArrayGetCount(found) == 0)
843 MacOSError::throwMe(errSecCSNoMatches);
844 return cfmake<CFDictionaryRef>("{%O=%O}", kSecAssessmentUpdateKeyFound, found.get());
845 }
846
847
848 CFDictionaryRef PolicyEngine::update(CFTypeRef target, SecAssessmentFlags flags, CFDictionaryRef context)
849 {
850 // update GKE
851 installExplicitSet(gkeAuthFile, gkeSigsFile);
852
853 AuthorityType type = typeFor(context, kAuthorityInvalid);
854 CFStringRef edit = CFStringRef(CFDictionaryGetValue(context, kSecAssessmentContextKeyUpdate));
855 CFDictionaryRef result;
856 if (CFEqual(edit, kSecAssessmentUpdateOperationAdd))
857 result = this->add(target, type, flags, context);
858 else if (CFEqual(edit, kSecAssessmentUpdateOperationRemove))
859 result = this->remove(target, type, flags, context);
860 else if (CFEqual(edit, kSecAssessmentUpdateOperationEnable))
861 result = this->enable(target, type, flags, context, true);
862 else if (CFEqual(edit, kSecAssessmentUpdateOperationDisable))
863 result = this->disable(target, type, flags, context, true);
864 else if (CFEqual(edit, kSecAssessmentUpdateOperationFind))
865 result = this->find(target, type, flags, context);
866 else
867 MacOSError::throwMe(errSecCSInvalidAttributeValues);
868 if (result == NULL)
869 result = makeCFDictionary(0); // success, no details
870 return result;
871 }
872
873
874 //
875 // Construct and prepare an SQL query on the authority table, operating on some set of existing authority records.
876 // In essence, this appends a suitable WHERE clause to the stanza passed and prepares it on the statement given.
877 //
878 void PolicyEngine::selectRules(SQLite::Statement &action, std::string phrase, std::string table,
879 CFTypeRef inTarget, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, std::string suffix /* = "" */)
880 {
881 CFDictionary ctx(context, errSecCSInvalidAttributeValues);
882 CFCopyRef<CFTypeRef> target = inTarget;
883 std::string filter_unsigned; // ignored; used just to trigger ad-hoc signing
884 normalizeTarget(target, type, ctx, &filter_unsigned);
885
886 string label;
887 if (CFStringRef lab = ctx.get<CFStringRef>(kSecAssessmentUpdateKeyLabel))
888 label = cfString(CFStringRef(lab));
889
890 if (!target) {
891 if (label.empty()) {
892 if (type == kAuthorityInvalid) {
893 action.query(phrase + suffix);
894 } else {
895 action.query(phrase + " WHERE " + table + ".type = :type" + suffix);
896 action.bind(":type").integer(type);
897 }
898 } else { // have label
899 if (type == kAuthorityInvalid) {
900 action.query(phrase + " WHERE " + table + ".label = :label" + suffix);
901 } else {
902 action.query(phrase + " WHERE " + table + ".type = :type AND " + table + ".label = :label" + suffix);
903 action.bind(":type").integer(type);
904 }
905 action.bind(":label") = label;
906 }
907 } else if (CFGetTypeID(target) == CFNumberGetTypeID()) {
908 action.query(phrase + " WHERE " + table + ".id = :id" + suffix);
909 action.bind(":id").integer(cfNumber<uint64_t>(target.as<CFNumberRef>()));
910 } else if (CFGetTypeID(target) == SecRequirementGetTypeID()) {
911 if (type == kAuthorityInvalid)
912 type = kAuthorityExecute;
913 CFRef<CFStringRef> requirementText;
914 MacOSError::check(SecRequirementCopyString(target.as<SecRequirementRef>(), kSecCSDefaultFlags, &requirementText.aref()));
915 action.query(phrase + " WHERE " + table + ".type = :type AND " + table + ".requirement = :requirement" + suffix);
916 action.bind(":type").integer(type);
917 action.bind(":requirement") = requirementText.get();
918 } else
919 MacOSError::throwMe(errSecCSInvalidObjectRef);
920 }
921
922
923 //
924 // Execute an atomic change to existing records in the authority table.
925 //
926 CFDictionaryRef PolicyEngine::manipulateRules(const std::string &stanza,
927 CFTypeRef inTarget, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, bool authorize)
928 {
929 SQLite::Transaction xact(*this, SQLite3::Transaction::deferred, "rule_change");
930 SQLite::Statement action(*this);
931 if (authorize)
932 authorizeUpdate(flags, context);
933 selectRules(action, stanza, "authority", inTarget, type, flags, context);
934 action.execute();
935 unsigned int changes = this->changes(); // latch change count
936 // We MUST purge objects with priority <= MAX(priority of any changed rules);
937 // but for now we just get lazy and purge them ALL.
938 if (changes) {
939 this->purgeObjects(1.0E100);
940 xact.commit();
941 notify_post(kNotifySecAssessmentUpdate);
942 return cfmake<CFDictionaryRef>("{%O=%d}", kSecAssessmentUpdateKeyCount, changes);
943 }
944 // no change; return an error
945 MacOSError::throwMe(errSecCSNoMatches);
946 }
947
948
949 //
950 // Fill in extra information about the originator of cryptographic credentials found - if any
951 //
952 void PolicyEngine::setOrigin(CFArrayRef chain, CFMutableDictionaryRef result)
953 {
954 if (chain)
955 if (CFArrayGetCount(chain) > 0)
956 if (SecCertificateRef leaf = SecCertificateRef(CFArrayGetValueAtIndex(chain, 0)))
957 if (CFStringRef summary = SecCertificateCopyLongDescription(NULL, leaf, NULL)) {
958 CFDictionarySetValue(result, kSecAssessmentAssessmentOriginator, summary);
959 CFRelease(summary);
960 }
961 }
962
963
964 //
965 // Take an assessment outcome and record it in the object cache
966 //
967 void PolicyEngine::recordOutcome(SecStaticCodeRef code, bool allow, AuthorityType type, double expires, SQLite::int64 authority)
968 {
969 CFRef<CFDictionaryRef> info;
970 MacOSError::check(SecCodeCopySigningInformation(code, kSecCSDefaultFlags, &info.aref()));
971 CFDataRef cdHash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique));
972 assert(cdHash); // was signed
973 CFRef<CFURLRef> path;
974 MacOSError::check(SecCodeCopyPath(code, kSecCSDefaultFlags, &path.aref()));
975 assert(expires);
976 SQLite::Transaction xact(*this, SQLite3::Transaction::deferred, "caching");
977 SQLite::Statement insert(*this,
978 "INSERT OR REPLACE INTO object (type, allow, hash, expires, path, authority)"
979 " VALUES (:type, :allow, :hash, :expires, :path,"
980 " CASE :authority WHEN 0 THEN (SELECT id FROM authority WHERE label = 'No Matching Rule') ELSE :authority END"
981 " );");
982 insert.bind(":type").integer(type);
983 insert.bind(":allow").integer(allow);
984 insert.bind(":hash") = cdHash;
985 insert.bind(":expires") = expires;
986 insert.bind(":path") = cfString(path);
987 insert.bind(":authority").integer(authority);
988 insert.execute();
989 xact.commit();
990 }
991
992
993 //
994 // Record a UI failure record after proper validation of the caller
995 //
996 void PolicyEngine::recordFailure(CFDictionaryRef info)
997 {
998 CFRef<CFDataRef> infoData = makeCFData(info);
999 UnixPlusPlus::AutoFileDesc fd(lastRejectFile, O_WRONLY | O_CREAT | O_TRUNC);
1000 fd.write(CFDataGetBytePtr(infoData), CFDataGetLength(infoData));
1001 notify_post(kNotifySecAssessmentRecordingChange);
1002 }
1003
1004
1005 //
1006 // Perform update authorization processing.
1007 // Throws an exception if authorization is denied.
1008 //
1009 static void authorizeUpdate(SecAssessmentFlags flags, CFDictionaryRef context)
1010 {
1011 AuthorizationRef authorization = NULL;
1012
1013 if (context)
1014 if (CFTypeRef authkey = CFDictionaryGetValue(context, kSecAssessmentUpdateKeyAuthorization))
1015 if (CFGetTypeID(authkey) == CFDataGetTypeID()) {
1016 CFDataRef authdata = CFDataRef(authkey);
1017 if (CFDataGetLength(authdata) != sizeof(AuthorizationExternalForm))
1018 MacOSError::throwMe(errSecCSInvalidObjectRef);
1019 MacOSError::check(AuthorizationCreateFromExternalForm((AuthorizationExternalForm *)CFDataGetBytePtr(authdata), &authorization));
1020 }
1021 if (authorization == NULL)
1022 MacOSError::throwMe(errSecCSDBDenied);
1023
1024 AuthorizationItem right[] = {
1025 { "com.apple.security.assessment.update", 0, NULL, 0 }
1026 };
1027 AuthorizationRights rights = { sizeof(right) / sizeof(right[0]), right };
1028 MacOSError::check(AuthorizationCopyRights(authorization, &rights, NULL,
1029 kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed, NULL));
1030
1031 MacOSError::check(AuthorizationFree(authorization, kAuthorizationFlagDefaults));
1032 }
1033
1034
1035 //
1036 // Perform common argument normalizations for update operations
1037 //
1038 void PolicyEngine::normalizeTarget(CFRef<CFTypeRef> &target, AuthorityType type, CFDictionary &context, std::string *signUnsigned)
1039 {
1040 // turn CFURLs into (designated) SecRequirements
1041 if (target && CFGetTypeID(target) == CFURLGetTypeID()) {
1042 CFRef<SecStaticCodeRef> code;
1043 CFURLRef path = target.as<CFURLRef>();
1044 MacOSError::check(SecStaticCodeCreateWithPath(path, kSecCSDefaultFlags, &code.aref()));
1045 switch (OSStatus rc = SecCodeCopyDesignatedRequirement(code, kSecCSDefaultFlags, (SecRequirementRef *)&target.aref())) {
1046 case errSecSuccess: {
1047 // use the *default* DR to avoid unreasonably wide DRs opening up Gatekeeper to attack
1048 CFRef<CFDictionaryRef> info;
1049 MacOSError::check(SecCodeCopySigningInformation(code, kSecCSRequirementInformation, &info.aref()));
1050 target = CFDictionaryGetValue(info, kSecCodeInfoImplicitDesignatedRequirement);
1051 }
1052 break;
1053 case errSecCSUnsigned:
1054 if (signUnsigned && temporarySigning(code, type, path, kAuthorityFlagWhitelistV2 | kAuthorityFlagWhitelistSHA256)) { // ad-hoc sign the code temporarily
1055 MacOSError::check(SecCodeCopyDesignatedRequirement(code, kSecCSDefaultFlags, (SecRequirementRef *)&target.aref()));
1056 CFRef<CFDictionaryRef> info;
1057 MacOSError::check(SecCodeCopySigningInformation(code, kSecCSInternalInformation, &info.aref()));
1058 if (CFDataRef cdData = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoCodeDirectory)))
1059 *signUnsigned = ((const CodeDirectory *)CFDataGetBytePtr(cdData))->screeningCode();
1060 break;
1061 }
1062 MacOSError::check(rc);
1063 case errSecCSSignatureFailed:
1064 // recover certain cases of broken signatures (well, try)
1065 if (codeInvalidityExceptions(code, NULL)) {
1066 // Ad-hoc sign the code in place (requiring a writable subject). This requires root privileges.
1067 CFRef<SecCodeSignerRef> signer;
1068 CFTemp<CFDictionaryRef> arguments("{%O=#N}", kSecCodeSignerIdentity);
1069 MacOSError::check(SecCodeSignerCreate(arguments, kSecCSSignOpaque, &signer.aref()));
1070 MacOSError::check(SecCodeSignerAddSignature(signer, code, kSecCSDefaultFlags));
1071 MacOSError::check(SecCodeCopyDesignatedRequirement(code, kSecCSDefaultFlags, (SecRequirementRef *)&target.aref()));
1072 break;
1073 }
1074 MacOSError::check(rc);
1075 default:
1076 MacOSError::check(rc);
1077 }
1078 if (context.get(kSecAssessmentUpdateKeyRemarks) == NULL) {
1079 // no explicit remarks; add one with the path
1080 CFRef<CFURLRef> path;
1081 MacOSError::check(SecCodeCopyPath(code, kSecCSDefaultFlags, &path.aref()));
1082 CFMutableDictionaryRef dict = makeCFMutableDictionary(context.get());
1083 CFDictionaryAddValue(dict, kSecAssessmentUpdateKeyRemarks, CFTempString(cfString(path)));
1084 context.take(dict);
1085 }
1086 CFStringRef edit = CFStringRef(context.get(kSecAssessmentContextKeyUpdate));
1087 if (type == kAuthorityExecute && CFEqual(edit, kSecAssessmentUpdateOperationAdd)) {
1088 // implicitly whitelist the code
1089 mOpaqueWhitelist.add(code);
1090 }
1091 }
1092 }
1093
1094
1095 //
1096 // Process special overrides for invalidly signed code.
1097 // This is the (hopefully minimal) concessions we make to keep hurting our customers
1098 // for our own prior mistakes...
1099 //
1100 static bool codeInvalidityExceptions(SecStaticCodeRef code, CFMutableDictionaryRef result)
1101 {
1102 if (OSAIsRecognizedExecutableURL) {
1103 CFRef<CFDictionaryRef> info;
1104 MacOSError::check(SecCodeCopySigningInformation(code, kSecCSDefaultFlags, &info.aref()));
1105 if (CFURLRef executable = CFURLRef(CFDictionaryGetValue(info, kSecCodeInfoMainExecutable))) {
1106 SInt32 error;
1107 if (OSAIsRecognizedExecutableURL(executable, &error)) {
1108 if (result)
1109 CFDictionaryAddValue(result,
1110 kSecAssessmentAssessmentAuthorityOverride, CFSTR("ignoring known invalid applet signature"));
1111 return true;
1112 }
1113 }
1114 }
1115 return false;
1116 }
1117
1118
1119 } // end namespace CodeSigning
1120 } // end namespace Security