2 * Copyright (c) 2011-2016 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
23 #include "policyengine.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>
39 #include "codedirectory.h"
40 #include "csutilities.h"
41 #include "StaticCode.h"
43 #include <CoreServices/CoreServicesPriv.h>
44 #include "SecCodePriv.h"
45 #undef check // Macro! Yech.
48 #include <OpenScriptingUtilPriv.h>
53 namespace CodeSigning
{
55 static const double NEGATIVE_HOLD
= 60.0/86400; // 60 seconds to cache negative outcomes
57 static const char RECORDER_DIR
[] = "/tmp/gke-"; // recorder mode destination for detached signatures
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
65 static void authorizeUpdate(SecAssessmentFlags flags
, CFDictionaryRef context
);
66 static bool codeInvalidityExceptions(SecStaticCodeRef code
, CFMutableDictionaryRef result
);
67 static CFTypeRef
installerPolicy() CF_RETURNS_RETAINED
;
73 PolicyEngine::PolicyEngine()
74 : PolicyDatabase(NULL
, SQLITE_OPEN_READWRITE
| SQLITE_OPEN_CREATE
)
78 PolicyEngine::~PolicyEngine()
83 // Top-level evaluation driver
85 void PolicyEngine::evaluate(CFURLRef path
, AuthorityType type
, SecAssessmentFlags flags
, CFDictionaryRef context
, CFMutableDictionaryRef result
)
88 installExplicitSet(gkeAuthFile
, gkeSigsFile
);
90 // find the global evaluation manager
91 EvaluationManager
*evaluationManager
= EvaluationManager::globalManager();
93 // perform the evaluation
94 EvaluationTask
*evaluationTask
= evaluationManager
->evaluationTask(this, path
, type
, flags
, context
, result
);
95 evaluationManager
->finalizeTask(evaluationTask
, flags
, result
);
97 // if rejected, reset the automatic rearm timer
98 if (CFDictionaryGetValue(result
, kSecAssessmentAssessmentVerdict
) == kCFBooleanFalse
)
99 resetRearmTimer("reject");
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.
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.
112 static std::string
createWhitelistScreen(char type
, const Byte
*digest
, size_t length
)
114 char buffer
[2*length
+ 2];
116 for (size_t n
= 0; n
< length
; n
++)
117 sprintf(buffer
+ 1 + 2*n
, "%02.2x", digest
[n
]);
121 static std::string
createWhitelistScreen(SecStaticCodeRef code
)
123 DiskRep
*rep
= SecStaticCode::requiredStatic(code
)->diskRep();
125 if (CFRef
<CFDataRef
> info
= rep
->component(cdInfoSlot
)) {
126 // has an Info.plist - hash it
128 hash
.update(CFDataGetBytePtr(info
), CFDataGetLength(info
));
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
));
139 return createWhitelistScreen('R', digest
, sizeof(digest
));
140 } else if (rep
->mainExecutableImage()) {
141 // stand-alone Mach-O executables are always candidates
144 // if everything else fails, hash the (single) file
146 hashFileData(rep
->mainExecutablePath().c_str(), &hash
);
149 return createWhitelistScreen('M', digest
, sizeof(digest
));
154 void PolicyEngine::evaluateCodeItem(SecStaticCodeRef code
, CFURLRef path
, AuthorityType type
, SecAssessmentFlags flags
, bool nested
, CFMutableDictionaryRef result
)
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
);
163 SQLite3::int64 latentID
= 0; // first (highest priority) disabled matching ID
164 std::string latentLabel
; // ... and associated label, if any
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];
177 CFRef
<SecRequirementRef
> requirement
;
178 MacOSError::check(SecRequirementCreateWithString(CFTempString(reqString
), kSecCSDefaultFlags
, &requirement
.aref()));
179 switch (OSStatus rc
= SecStaticCodeCheckValidity(code
, kSecCSBasicValidateOnly
| kSecCSCheckGatekeeperArchitectures
, requirement
)) {
181 break; // rule match; process below
182 case errSecCSReqFailed
:
183 continue; // rule does not apply
185 return; // nested code has failed to pass
187 MacOSError::throwMe(rc
); // general error; pass to caller
190 // if this rule is disabled, skip it but record the first matching one for posterity
191 if (disabled
&& latentID
== 0) {
193 latentLabel
= label
? label
: "";
197 // current rule is first rule (in priority order) that matched. Apply it
198 if (nested
&& allow
) // success, nothing to record
201 CFRef
<CFDictionaryRef
> info
; // as needed
202 if (flags
& kSecAssessmentFlagRequestOrigin
) {
204 MacOSError::check(SecCodeCopySigningInformation(code
, kSecCSSigningInformation
, &info
.aref()));
205 if (CFArrayRef chain
= CFArrayRef(CFDictionaryGetValue(info
, kSecCodeInfoCertificates
)))
206 setOrigin(chain
, result
);
208 if (!(ruleFlags
& kAuthorityFlagInhibitCache
) && !(flags
& kSecAssessmentFlagNoCache
)) { // cache inhibit
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
);
220 if (SYSPOLICY_ASSESS_OUTCOME_ACCEPT_ENABLED()) {
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
);
227 if (SYSPOLICY_ASSESS_OUTCOME_DENY_ENABLED() || SYSPOLICY_RECORDER_MODE_ENABLED()) {
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
);
237 cfadd(result
, "{%O=%B}", kSecAssessmentAssessmentVerdict
, allow
);
238 addAuthority(flags
, result
, label
, id
, NULL
, false, ruleFlags
);
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
);
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);
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
);
263 void PolicyEngine::adjustValidation(SecStaticCodeRef code
)
265 CFRef
<CFDictionaryRef
> conditions
= mOpaqueWhitelist
.validationConditionsFor(code
);
266 SecStaticCodeSetValidationConditions(code
, conditions
);
270 bool PolicyEngine::temporarySigning(SecStaticCodeRef code
, AuthorityType type
, CFURLRef path
, SecAssessmentFlags matchFlags
)
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 "
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
285 matchFlags
= SQLite3::int64(query
[0]);
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
));
301 SecRequirementRef dr
= NULL
;
302 SecCodeCopyDesignatedRequirement(code
, kSecCSDefaultFlags
, &dr
);
303 CFStringRef drs
= NULL
;
304 SecRequirementCopyString(dr
, kSecCSDefaultFlags
, &drs
);
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";
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());
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
);
328 return true; // it worked; we're now (well) signed
337 // Read from disk, evaluate properly, cache as indicated.
339 void PolicyEngine::evaluateCode(CFURLRef path
, AuthorityType type
, SecAssessmentFlags flags
, CFDictionaryRef context
, CFMutableDictionaryRef result
, bool handleUnsigned
)
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
);
348 // hack: if caller passed a UTI, use that to turn off app-only checks for some well-known ones
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"));
357 CFCopyRef
<SecStaticCodeRef
> code
;
358 MacOSError::check(SecStaticCodeCreateWithPath(path
, kSecCSDefaultFlags
, &code
.aref()));
360 SecCSFlags validationFlags
= kSecCSEnforceRevocationChecks
| kSecCSCheckAllArchitectures
;
361 if (!(flags
& kSecAssessmentFlagAllowWeak
))
362 validationFlags
|= kSecCSStrictValidate
;
363 adjustValidation(code
);
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
);
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
;
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
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
);
401 SecStaticCodeCancelValidation(code
, kSecCSDefaultFlags
);
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
)) {
409 return makeCFNumber(OSStatus(errSecCSVetoed
)); // (signal nested-code policy failure, picked up below)
410 // nested code policy failure; save, reset, and continue
412 nestedFailure
= CFMutableDictionaryRef(CFDictionaryGetValue(result
, kSecAssessmentAssessmentAuthority
));
413 CFDictionaryRemoveValue(result
, kSecAssessmentAssessmentAuthority
);
414 CFDictionaryRemoveValue(result
, kSecAssessmentAssessmentVerdict
);
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
427 case errSecCSUnsigned
:
428 cfadd(result
, "{%O=#F}", kSecAssessmentAssessmentVerdict
);
429 addAuthority(flags
, result
, "no usable signature");
431 case errSecCSVetoed
: // nested code rejected by rule book; result was filled out there
433 addToAuthority(result
, kSecAssessmentAssessmentSource
, CFSTR("no usable signature")); // ad-hoc signature proved useless
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
:
448 // consult the whitelist
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
458 if (CFEqual(verdict
, kCFBooleanTrue
) && !(flags
& kSecAssessmentFlagIgnoreWhitelist
))
459 if (mOpaqueWhitelist
.contains(code
, feedback
, rc
))
463 label
= "allowed cdhash";
465 CFDictionaryReplaceValue(result
, kSecAssessmentAssessmentVerdict
, kCFBooleanFalse
);
466 label
= "obsolete resource envelope";
468 cfadd(result
, "{%O=%d}", kSecAssessmentAssessmentCodeSigningError
, rc
);
469 addAuthority(flags
, result
, label
, 0, NULL
, true);
473 MacOSError::throwMe(rc
);
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
);
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.
494 void PolicyEngine::evaluateInstall(CFURLRef path
, SecAssessmentFlags flags
, CFDictionaryRef context
, CFMutableDictionaryRef result
)
496 const AuthorityType type
= kAuthorityInstall
;
498 // check for recent explicit approval, using a bookmark's FileResourceIdentifierKey
499 if (CFRef
<CFDataRef
> bookmark
= cfLoadFile(lastApprovedFile
)) {
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
, ¤tIdent
.aref(), NULL
))
508 if (CFURLCopyResourcePropertyForKey(path
, kCFURLContentModificationDateKey
, ¤tMod
.aref(), NULL
))
509 if (CFEqual(savedIdent
, currentIdent
) && CFEqual(savedMod
, currentMod
)) {
510 cfadd(result
, "{%O=#T}", kSecAssessmentAssessmentVerdict
);
511 addAuthority(flags
, result
, "explicit preference");
517 Xar
xar(cfString(path
).c_str());
519 // follow the code signing path
520 evaluateCode(path
, type
, flags
, context
, result
, true);
524 SQLite3::int64 latentID
= 0; // first (highest priority) disabled matching ID
525 std::string latentLabel
; // ... and associated label, if any
526 if (!xar
.isSigned()) {
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");
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
));
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
));
547 if (flags
& kSecAssessmentFlagRequestOrigin
)
548 setOrigin(chain
, result
);
550 switch (trustResult
) {
551 case kSecTrustResultProceed
:
552 case kSecTrustResultUnspecified
:
557 MacOSError::check(SecTrustGetCssmResultCode(trust
, &rc
));
558 MacOSError::throwMe(rc
);
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];
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
580 case errSecCSReqFailed
: // requirement missed, but otherwise okay
582 default: // broken in some way; all tests will fail like this so bail out
583 MacOSError::throwMe(rc
);
591 continue; // the loop
594 if (SYSPOLICY_ASSESS_OUTCOME_ACCEPT_ENABLED() || SYSPOLICY_ASSESS_OUTCOME_DENY_ENABLED()) {
596 SYSPOLICY_ASSESS_OUTCOME_ACCEPT(cfString(path
).c_str(), type
, label
, NULL
);
598 SYSPOLICY_ASSESS_OUTCOME_DENY(cfString(path
).c_str(), type
, label
, NULL
);
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
);
607 if (SYSPOLICY_ASSESS_OUTCOME_DEFAULT_ENABLED())
608 SYSPOLICY_ASSESS_OUTCOME_DEFAULT(cfString(path
).c_str(), type
, latentLabel
.c_str(), NULL
);
610 // no applicable authority. Deny by default
611 cfadd(result
, "{%O=#F}", kSecAssessmentAssessmentVerdict
);
612 addAuthority(flags
, result
, latentLabel
.c_str(), latentID
);
617 // Create a suitable policy array for verification of installer signatures.
619 static SecPolicyRef
makeRevocationPolicy()
621 CFRef
<SecPolicyRef
> policy(SecPolicyCreateRevocation(kSecRevocationUseAnyAvailableMethod
));
622 return policy
.yield();
625 static CFTypeRef
installerPolicy()
627 CFRef
<SecPolicyRef
> base
= SecPolicyCreateBasicX509();
628 CFRef
<SecPolicyRef
> revoc
= makeRevocationPolicy();
629 return makeCFArray(2, base
.get(), revoc
.get());
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.
637 void PolicyEngine::evaluateDocOpen(CFURLRef path
, SecAssessmentFlags flags
, CFDictionaryRef context
, CFMutableDictionaryRef result
)
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");
651 evaluateCode(path
, kAuthorityOpenDoc
, flags
, context
, result
, true);
654 if (CFStringRef riskCategory
= CFStringRef(CFDictionaryGetValue(context
, kLSDownloadRiskCategoryKey
))) {
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
670 evaluateCode(path
, kAuthorityOpenDoc
, flags
, context
, result
, true);
672 // some documents can't be code signed, so this may be quite benign
675 if (CFDictionaryGetValue(result
, kSecAssessmentAssessmentVerdict
) == NULL
) { // no code signature to help us out
676 cfadd(result
, "{%O=#F}", kSecAssessmentAssessmentVerdict
);
677 addAuthority(flags
, result
, "_XProtect");
679 addToAuthority(result
, kLSDownloadRiskCategoryKey
, riskCategory
);
683 // insufficient information from LS - deny by default
684 cfadd(result
, "{%O=#F}", kSecAssessmentAssessmentVerdict
);
685 addAuthority(flags
, result
, "Insufficient Context");
690 // Result-creation helpers
692 void PolicyEngine::addAuthority(SecAssessmentFlags flags
, CFMutableDictionaryRef parent
, const char *label
, SQLite::int64 row
, CFTypeRef cacheInfo
, bool weak
, uint64_t ruleFlags
)
694 CFRef
<CFMutableDictionaryRef
> auth
= makeCFMutableDictionary();
695 if (label
&& label
[0])
696 cfadd(auth
, "{%O=%s}", kSecAssessmentAssessmentSource
, label
);
698 CFDictionaryAddValue(auth
, kSecAssessmentAssessmentAuthorityRow
, CFTempNumber(row
));
699 if (overrideAssessment(flags
))
700 CFDictionaryAddValue(auth
, kSecAssessmentAssessmentAuthorityOverride
, kDisabledOverride
);
702 CFDictionaryAddValue(auth
, kSecAssessmentAssessmentFromCache
, cacheInfo
);
703 CFDictionaryAddValue(auth
, kSecAssessmentAssessmentAuthorityFlags
, CFTempNumber(ruleFlags
));
705 CFDictionaryAddValue(auth
, kSecAssessmentAssessmentWeakSignature
, kCFBooleanTrue
);
706 CFDictionaryReplaceValue(parent
, kSecAssessmentAssessmentAuthority
, auth
);
708 CFDictionaryAddValue(parent
, kSecAssessmentAssessmentAuthority
, auth
);
712 void PolicyEngine::addToAuthority(CFMutableDictionaryRef parent
, CFStringRef key
, CFTypeRef value
)
714 CFMutableDictionaryRef authority
= CFMutableDictionaryRef(CFDictionaryGetValue(parent
, kSecAssessmentAssessmentAuthority
));
716 CFDictionaryAddValue(authority
, key
, value
);
721 // Add a rule to the policy database
723 CFDictionaryRef
PolicyEngine::add(CFTypeRef inTarget
, AuthorityType type
, SecAssessmentFlags flags
, CFDictionaryRef context
)
725 // default type to execution
726 if (type
== kAuthorityInvalid
)
727 type
= kAuthorityExecute
;
729 authorizeUpdate(flags
, context
);
730 CFDictionary
ctx(context
, errSecCSInvalidAttributeValues
);
731 CFCopyRef
<CFTypeRef
> target
= inTarget
;
732 CFRef
<CFDataRef
> bookmark
= NULL
;
733 std::string filter_unsigned
;
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
);
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
));
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
);
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());
768 return cfmake
<CFDictionaryRef
>("{%O=%O}", kSecAssessmentAssessmentAuthorityOverride
, CFSTR("unable to set quarantine"));
773 // if we now have anything else, we're busted
774 if (!target
|| CFGetTypeID(target
) != SecRequirementGetTypeID())
775 MacOSError::throwMe(errSecCSInvalidObjectRef
);
780 double expires
= never
;
782 SQLite::uint64 dbFlags
= kAuthorityFlagWhitelistV2
| kAuthorityFlagWhitelistSHA256
;
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
);
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
;
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
);
814 SQLite::int64 newRow
= this->lastInsert();
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
);
821 this->purgeObjects(priority
);
823 notify_post(kNotifySecAssessmentUpdate
);
824 return cfmake
<CFDictionaryRef
>("{%O=%d}", kSecAssessmentUpdateKeyRow
, newRow
);
828 CFDictionaryRef
PolicyEngine::remove(CFTypeRef target
, AuthorityType type
, SecAssessmentFlags flags
, CFDictionaryRef context
)
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());
841 return manipulateRules("DELETE FROM authority", target
, type
, flags
, context
, true);
844 CFDictionaryRef
PolicyEngine::enable(CFTypeRef target
, AuthorityType type
, SecAssessmentFlags flags
, CFDictionaryRef context
, bool authorize
)
846 return manipulateRules("UPDATE authority SET disabled = 0", target
, type
, flags
, context
, authorize
);
849 CFDictionaryRef
PolicyEngine::disable(CFTypeRef target
, AuthorityType type
, SecAssessmentFlags flags
, CFDictionaryRef context
, bool authorize
)
851 return manipulateRules("UPDATE authority SET disabled = 1", target
, type
, flags
, context
, authorize
);
854 CFDictionaryRef
PolicyEngine::find(CFTypeRef target
, AuthorityType type
, SecAssessmentFlags flags
, CFDictionaryRef context
)
856 //for privacy reasons we only want to allow the admin to list the database
857 authorizeUpdate(flags
, context
);
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()
883 CFDictionaryAddValue(rule
, kSecAssessmentRuleKeyLabel
, CFTempString(label
));
885 CFDictionaryAddValue(rule
, kSecAssessmentRuleKeyRemarks
, CFTempString(remarks
));
886 if (expires
!= never
)
887 CFDictionaryAddValue(rule
, kSecAssessmentRuleKeyExpires
, CFRef
<CFDateRef
>(julianToDate(expires
)));
889 CFDictionaryAddValue(rule
, kSecAssessmentRuleKeyDisabled
, CFTempNumber(disabled
));
891 CFDictionaryAddValue(rule
, kSecAssessmentRuleKeyBookmark
, bookmark
);
892 CFArrayAppendValue(found
, rule
);
894 if (CFArrayGetCount(found
) == 0)
895 MacOSError::throwMe(errSecCSNoMatches
);
896 return cfmake
<CFDictionaryRef
>("{%O=%O}", kSecAssessmentUpdateKeyFound
, found
.get());
900 CFDictionaryRef
PolicyEngine::update(CFTypeRef target
, SecAssessmentFlags flags
, CFDictionaryRef context
)
903 installExplicitSet(gkeAuthFile
, gkeSigsFile
);
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
);
919 MacOSError::throwMe(errSecCSInvalidAttributeValues
);
921 result
= makeCFDictionary(0); // success, no details
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.
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
/* = "" */)
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
);
939 if (CFStringRef lab
= ctx
.get
<CFStringRef
>(kSecAssessmentUpdateKeyLabel
))
940 label
= cfString(CFStringRef(lab
));
944 if (type
== kAuthorityInvalid
) {
945 action
.query(phrase
+ suffix
);
947 action
.query(phrase
+ " WHERE " + table
+ ".type = :type" + suffix
);
948 action
.bind(":type").integer(type
);
950 } else { // have label
951 if (type
== kAuthorityInvalid
) {
952 action
.query(phrase
+ " WHERE " + table
+ ".label = :label" + suffix
);
954 action
.query(phrase
+ " WHERE " + table
+ ".type = :type AND " + table
+ ".label = :label" + suffix
);
955 action
.bind(":type").integer(type
);
957 action
.bind(":label") = label
;
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();
971 MacOSError::throwMe(errSecCSInvalidObjectRef
);
976 // Execute an atomic change to existing records in the authority table.
978 CFDictionaryRef
PolicyEngine::manipulateRules(const std::string
&stanza
,
979 CFTypeRef inTarget
, AuthorityType type
, SecAssessmentFlags flags
, CFDictionaryRef context
, bool authorize
)
981 SQLite::Transaction
xact(*this, SQLite3::Transaction::deferred
, "rule_change");
982 SQLite::Statement
action(*this);
984 authorizeUpdate(flags
, context
);
985 selectRules(action
, stanza
, "authority", inTarget
, type
, flags
, context
);
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.
991 this->purgeObjects(1.0E100
);
993 notify_post(kNotifySecAssessmentUpdate
);
994 return cfmake
<CFDictionaryRef
>("{%O=%d}", kSecAssessmentUpdateKeyCount
, changes
);
996 // no change; return an error
997 MacOSError::throwMe(errSecCSNoMatches
);
1002 // Fill in extra information about the originator of cryptographic credentials found - if any
1004 void PolicyEngine::setOrigin(CFArrayRef chain
, CFMutableDictionaryRef result
)
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
);
1017 // Take an assessment outcome and record it in the object cache
1019 void PolicyEngine::recordOutcome(SecStaticCodeRef code
, bool allow
, AuthorityType type
, double expires
, SQLite::int64 authority
)
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()));
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"
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
);
1046 // Record a UI failure record after proper validation of the caller
1048 void PolicyEngine::recordFailure(CFDictionaryRef info
)
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
);
1058 // Perform update authorization processing.
1059 // Throws an exception if authorization is denied.
1061 static void authorizeUpdate(SecAssessmentFlags flags
, CFDictionaryRef context
)
1063 AuthorizationRef authorization
= NULL
;
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
));
1073 if (authorization
== NULL
)
1074 MacOSError::throwMe(errSecCSDBDenied
);
1076 AuthorizationItem right
[] = {
1077 { "com.apple.security.assessment.update", 0, NULL
, 0 }
1079 AuthorizationRights rights
= { sizeof(right
) / sizeof(right
[0]), right
};
1080 MacOSError::check(AuthorizationCopyRights(authorization
, &rights
, NULL
,
1081 kAuthorizationFlagExtendRights
| kAuthorizationFlagInteractionAllowed
, NULL
));
1083 MacOSError::check(AuthorizationFree(authorization
, kAuthorizationFlagDefaults
));
1088 // Perform common argument normalizations for update operations
1090 void PolicyEngine::normalizeTarget(CFRef
<CFTypeRef
> &target
, AuthorityType type
, CFDictionary
&context
, std::string
*signUnsigned
)
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
);
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
);
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()));
1123 MacOSError::check(rc
);
1125 MacOSError::check(rc
);
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
)));
1135 CFStringRef edit
= CFStringRef(context
.get(kSecAssessmentContextKeyUpdate
));
1136 if (type
== kAuthorityExecute
&& CFEqual(edit
, kSecAssessmentUpdateOperationAdd
)) {
1137 // implicitly whitelist the code
1138 mOpaqueWhitelist
.add(code
);
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...
1149 static bool codeInvalidityExceptions(SecStaticCodeRef code
, CFMutableDictionaryRef result
)
1151 CFRef
<CFDictionaryRef
> info
;
1152 MacOSError::check(SecCodeCopySigningInformation(code
, kSecCSDefaultFlags
, &info
.aref()));
1153 if (CFURLRef executable
= CFURLRef(CFDictionaryGetValue(info
, kSecCodeInfoMainExecutable
))) {
1155 if (OSAIsRecognizedExecutableURL(executable
, &error
)) {
1157 CFDictionaryAddValue(result
,
1158 kSecAssessmentAssessmentAuthorityOverride
, CFSTR("ignoring known invalid applet signature"));
1166 } // end namespace CodeSigning
1167 } // end namespace Security