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