2 * Copyright (c) 2011-2014 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
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");
103 static std::string
createWhitelistScreen(char type
, const Byte
*digest
, size_t length
)
105 char buffer
[2*length
+ 2];
107 for (size_t n
= 0; n
< length
; n
++)
108 sprintf(buffer
+ 1 + 2*n
, "%02.2x", digest
[n
]);
113 void PolicyEngine::evaluateCodeItem(SecStaticCodeRef code
, CFURLRef path
, AuthorityType type
, SecAssessmentFlags flags
, bool nested
, CFMutableDictionaryRef result
)
116 SQLite::Statement
query(*this,
117 "SELECT allow, requirement, id, label, expires, flags, disabled, filter_unsigned, remarks FROM scan_authority"
118 " WHERE type = :type"
119 " ORDER BY priority DESC;");
120 query
.bind(":type").integer(type
);
122 SQLite3::int64 latentID
= 0; // first (highest priority) disabled matching ID
123 std::string latentLabel
; // ... and associated label, if any
125 while (query
.nextRow()) {
126 bool allow
= int(query
[0]);
127 const char *reqString
= query
[1];
128 SQLite3::int64 id
= query
[2];
129 const char *label
= query
[3];
130 double expires
= query
[4];
131 sqlite3_int64 ruleFlags
= query
[5];
132 SQLite3::int64 disabled
= query
[6];
133 // const char *filter = query[7];
134 // const char *remarks = query[8];
136 CFRef
<SecRequirementRef
> requirement
;
137 MacOSError::check(SecRequirementCreateWithString(CFTempString(reqString
), kSecCSDefaultFlags
, &requirement
.aref()));
138 switch (OSStatus rc
= SecStaticCodeCheckValidity(code
, kSecCSBasicValidateOnly
| kSecCSCheckGatekeeperArchitectures
, requirement
)) {
140 break; // rule match; process below
141 case errSecCSReqFailed
:
142 continue; // rule does not apply
144 return; // nested code has failed to pass
146 MacOSError::throwMe(rc
); // general error; pass to caller
149 // if this rule is disabled, skip it but record the first matching one for posterity
150 if (disabled
&& latentID
== 0) {
152 latentLabel
= label
? label
: "";
156 // current rule is first rule (in priority order) that matched. Apply it
157 if (nested
) // success, nothing to record
160 CFRef
<CFDictionaryRef
> info
; // as needed
161 if (flags
& kSecAssessmentFlagRequestOrigin
) {
163 MacOSError::check(SecCodeCopySigningInformation(code
, kSecCSSigningInformation
, &info
.aref()));
164 if (CFArrayRef chain
= CFArrayRef(CFDictionaryGetValue(info
, kSecCodeInfoCertificates
)))
165 setOrigin(chain
, result
);
167 if (!(ruleFlags
& kAuthorityFlagInhibitCache
) && !(flags
& kSecAssessmentFlagNoCache
)) { // cache inhibit
169 MacOSError::check(SecCodeCopySigningInformation(code
, kSecCSSigningInformation
, &info
.aref()));
170 if (SecTrustRef trust
= SecTrustRef(CFDictionaryGetValue(info
, kSecCodeInfoTrust
))) {
171 CFRef
<CFDictionaryRef
> xinfo
;
172 MacOSError::check(SecTrustCopyExtendedResult(trust
, &xinfo
.aref()));
173 if (CFDateRef limit
= CFDateRef(CFDictionaryGetValue(xinfo
, kSecTrustExpirationDate
))) {
174 this->recordOutcome(code
, allow
, type
, min(expires
, dateToJulian(limit
)), id
);
179 if (SYSPOLICY_ASSESS_OUTCOME_ACCEPT_ENABLED()) {
181 MacOSError::check(SecCodeCopySigningInformation(code
, kSecCSSigningInformation
, &info
.aref()));
182 CFDataRef cdhash
= CFDataRef(CFDictionaryGetValue(info
, kSecCodeInfoUnique
));
183 SYSPOLICY_ASSESS_OUTCOME_ACCEPT(cfString(path
).c_str(), type
, label
, cdhash
? CFDataGetBytePtr(cdhash
) : NULL
);
186 if (SYSPOLICY_ASSESS_OUTCOME_DENY_ENABLED() || SYSPOLICY_RECORDER_MODE_ENABLED()) {
188 MacOSError::check(SecCodeCopySigningInformation(code
, kSecCSSigningInformation
, &info
.aref()));
189 CFDataRef cdhash
= CFDataRef(CFDictionaryGetValue(info
, kSecCodeInfoUnique
));
190 std::string cpath
= cfString(path
);
191 const void *hashp
= cdhash
? CFDataGetBytePtr(cdhash
) : NULL
;
192 SYSPOLICY_ASSESS_OUTCOME_DENY(cpath
.c_str(), type
, label
, hashp
);
193 SYSPOLICY_RECORDER_MODE(cpath
.c_str(), type
, label
, hashp
, recorder_code_untrusted
);
196 cfadd(result
, "{%O=%B}", kSecAssessmentAssessmentVerdict
, allow
);
197 addAuthority(flags
, result
, label
, id
);
201 // no applicable authority (but signed, perhaps temporarily). Deny by default
202 CFRef
<CFDictionaryRef
> info
;
203 MacOSError::check(SecCodeCopySigningInformation(code
, kSecCSSigningInformation
, &info
.aref()));
204 if (flags
& kSecAssessmentFlagRequestOrigin
) {
205 if (CFArrayRef chain
= CFArrayRef(CFDictionaryGetValue(info
, kSecCodeInfoCertificates
)))
206 setOrigin(chain
, result
);
208 if (SYSPOLICY_ASSESS_OUTCOME_DEFAULT_ENABLED() || SYSPOLICY_RECORDER_MODE_ENABLED()) {
209 CFDataRef cdhash
= CFDataRef(CFDictionaryGetValue(info
, kSecCodeInfoUnique
));
210 const void *hashp
= cdhash
? CFDataGetBytePtr(cdhash
) : NULL
;
211 std::string cpath
= cfString(path
);
212 SYSPOLICY_ASSESS_OUTCOME_DEFAULT(cpath
.c_str(), type
, latentLabel
.c_str(), hashp
);
213 SYSPOLICY_RECORDER_MODE(cpath
.c_str(), type
, latentLabel
.c_str(), hashp
, 0);
215 if (!(flags
& kSecAssessmentFlagNoCache
))
216 this->recordOutcome(code
, false, type
, this->julianNow() + NEGATIVE_HOLD
, latentID
);
217 cfadd(result
, "{%O=%B}", kSecAssessmentAssessmentVerdict
, false);
218 addAuthority(flags
, result
, latentLabel
.c_str(), latentID
);
222 void PolicyEngine::adjustValidation(SecStaticCodeRef code
)
224 CFRef
<CFDictionaryRef
> conditions
= mOpaqueWhitelist
.validationConditionsFor(code
);
225 SecStaticCodeSetValidationConditions(code
, conditions
);
229 bool PolicyEngine::temporarySigning(SecStaticCodeRef code
, AuthorityType type
, CFURLRef path
, SecAssessmentFlags matchFlags
)
231 if (matchFlags
== 0) { // playback; consult authority table for matches
232 DiskRep
*rep
= SecStaticCode::requiredStatic(code
)->diskRep();
234 if (CFRef
<CFDataRef
> info
= rep
->component(cdInfoSlot
)) {
236 hash
.update(CFDataGetBytePtr(info
), CFDataGetLength(info
));
239 screen
= createWhitelistScreen('I', digest
, sizeof(digest
));
240 } else if (CFRef
<CFDataRef
> repSpecific
= rep
->component(cdRepSpecificSlot
)) {
241 // got invented after SHA-1 deprecation, so we'll use SHA256, which is the new default
242 CCHashInstance
hash(kCCDigestSHA256
);
243 hash
.update(CFDataGetBytePtr(repSpecific
), CFDataGetLength(repSpecific
));
246 screen
= createWhitelistScreen('R', digest
, sizeof(digest
));
247 } else if (rep
->mainExecutableImage()) {
251 hashFileData(rep
->mainExecutablePath().c_str(), &hash
);
254 screen
= createWhitelistScreen('M', digest
, sizeof(digest
));
256 SQLite::Statement
query(*this,
257 "SELECT flags FROM authority "
259 " AND NOT flags & :flag"
260 " AND CASE WHEN filter_unsigned IS NULL THEN remarks = :remarks ELSE filter_unsigned = :screen END");
261 query
.bind(":type").integer(type
);
262 query
.bind(":flag").integer(kAuthorityFlagDefault
);
263 query
.bind(":screen") = screen
;
264 query
.bind(":remarks") = cfString(path
);
265 if (!query
.nextRow()) // guaranteed no matching rule
267 matchFlags
= SQLite3::int64(query
[0]);
271 // ad-hoc sign the code and attach the signature
272 CFRef
<CFDataRef
> signature
= CFDataCreateMutable(NULL
, 0);
273 CFTemp
<CFMutableDictionaryRef
> arguments("{%O=%O, %O=#N, %O=%d}", kSecCodeSignerDetached
, signature
.get(), kSecCodeSignerIdentity
,
274 kSecCodeSignerDigestAlgorithm
, (matchFlags
& kAuthorityFlagWhitelistSHA256
) ? kSecCodeSignatureHashSHA256
: kSecCodeSignatureHashSHA1
);
275 CFRef
<SecCodeSignerRef
> signer
;
276 MacOSError::check(SecCodeSignerCreate(arguments
, (matchFlags
& kAuthorityFlagWhitelistV2
) ? kSecCSSignOpaque
: kSecCSSignV1
, &signer
.aref()));
277 MacOSError::check(SecCodeSignerAddSignature(signer
, code
, kSecCSDefaultFlags
));
278 MacOSError::check(SecCodeSetDetachedSignature(code
, signature
, kSecCSDefaultFlags
));
280 SecRequirementRef dr
= NULL
;
281 SecCodeCopyDesignatedRequirement(code
, kSecCSDefaultFlags
, &dr
);
282 CFStringRef drs
= NULL
;
283 SecRequirementCopyString(dr
, kSecCSDefaultFlags
, &drs
);
285 // if we're in GKE recording mode, save that signature and report its location
286 if (SYSPOLICY_RECORDER_MODE_ENABLED()) {
287 int status
= recorder_code_unable
; // ephemeral signature (not recorded)
288 if (geteuid() == 0) {
289 CFRef
<CFUUIDRef
> uuid
= CFUUIDCreate(NULL
);
290 std::string sigfile
= RECORDER_DIR
+ cfStringRelease(CFUUIDCreateString(NULL
, uuid
)) + ".tsig";
292 UnixPlusPlus::AutoFileDesc
fd(sigfile
, O_WRONLY
| O_CREAT
);
293 fd
.write(CFDataGetBytePtr(signature
), CFDataGetLength(signature
));
294 status
= recorder_code_adhoc
; // recorded signature
295 SYSPOLICY_RECORDER_MODE_ADHOC_PATH(cfString(path
).c_str(), type
, sigfile
.c_str());
299 // now report the D probe itself
300 CFRef
<CFDictionaryRef
> info
;
301 MacOSError::check(SecCodeCopySigningInformation(code
, kSecCSDefaultFlags
, &info
.aref()));
302 CFDataRef cdhash
= CFDataRef(CFDictionaryGetValue(info
, kSecCodeInfoUnique
));
303 SYSPOLICY_RECORDER_MODE(cfString(path
).c_str(), type
, "",
304 cdhash
? CFDataGetBytePtr(cdhash
) : NULL
, status
);
307 return true; // it worked; we're now (well) signed
316 // Read from disk, evaluate properly, cache as indicated.
318 void PolicyEngine::evaluateCode(CFURLRef path
, AuthorityType type
, SecAssessmentFlags flags
, CFDictionaryRef context
, CFMutableDictionaryRef result
, bool handleUnsigned
)
320 // not really a Gatekeeper function... but reject all "hard quarantined" files because they were made from sandboxed sources without download privilege
321 FileQuarantine
qtn(cfString(path
).c_str());
322 if (qtn
.flag(QTN_FLAG_HARD
))
323 MacOSError::throwMe(errSecCSFileHardQuarantined
);
325 CFCopyRef
<SecStaticCodeRef
> code
;
326 MacOSError::check(SecStaticCodeCreateWithPath(path
, kSecCSDefaultFlags
, &code
.aref()));
328 SecCSFlags validationFlags
= kSecCSEnforceRevocationChecks
| kSecCSCheckAllArchitectures
;
329 if (!(flags
& kSecAssessmentFlagAllowWeak
))
330 validationFlags
|= kSecCSStrictValidate
;
331 adjustValidation(code
);
333 // deal with a very special case (broken 10.6/10.7 Applet bundles)
334 OSStatus rc
= SecStaticCodeCheckValidity(code
, validationFlags
| kSecCSBasicValidateOnly
, NULL
);
335 if (rc
== errSecCSSignatureFailed
) {
336 if (!codeInvalidityExceptions(code
, result
)) { // invalidly signed, no exceptions -> error
337 if (SYSPOLICY_ASSESS_OUTCOME_BROKEN_ENABLED())
338 SYSPOLICY_ASSESS_OUTCOME_BROKEN(cfString(path
).c_str(), type
, false);
339 MacOSError::throwMe(rc
);
341 // recognized exception - treat as unsigned
342 if (SYSPOLICY_ASSESS_OUTCOME_BROKEN_ENABLED())
343 SYSPOLICY_ASSESS_OUTCOME_BROKEN(cfString(path
).c_str(), type
, true);
344 rc
= errSecCSUnsigned
;
347 // ad-hoc sign unsigned code
348 if (rc
== errSecCSUnsigned
&& handleUnsigned
&& (!overrideAssessment(flags
) || SYSPOLICY_RECORDER_MODE_ENABLED())) {
349 if (temporarySigning(code
, type
, path
, 0)) {
350 rc
= errSecSuccess
; // clear unsigned; we are now well-signed
351 validationFlags
|= kSecCSBasicValidateOnly
; // no need to re-validate deep contents
355 // prepare for deep traversal of (hopefully) good signatures
356 SecAssessmentFeedback feedback
= SecAssessmentFeedback(CFDictionaryGetValue(context
, kSecAssessmentContextKeyFeedback
));
357 MacOSError::check(SecStaticCodeSetCallback(code
, kSecCSDefaultFlags
, NULL
, ^CFTypeRef (SecStaticCodeRef item
, CFStringRef cfStage
, CFDictionaryRef info
) {
358 string stage
= cfString(cfStage
);
359 if (stage
== "prepared") {
360 if (!CFEqual(item
, code
)) // genuine nested (not top) code
361 adjustValidation(item
);
362 } else if (stage
== "progress") {
363 if (feedback
&& CFEqual(item
, code
)) { // top level progress
364 bool proceed
= feedback(kSecAssessmentFeedbackProgress
, info
);
366 SecStaticCodeCancelValidation(code
, kSecCSDefaultFlags
);
368 } else if (stage
== "validated") {
369 SecStaticCodeSetCallback(item
, kSecCSDefaultFlags
, NULL
, NULL
); // clear callback to avoid unwanted recursion
370 evaluateCodeItem(item
, path
, type
, flags
, item
!= code
, result
);
371 if (CFTypeRef verdict
= CFDictionaryGetValue(result
, kSecAssessmentAssessmentVerdict
))
372 if (CFEqual(verdict
, kCFBooleanFalse
))
373 return makeCFNumber(OSStatus(errSecCSVetoed
)); // (signal nested-code policy failure, picked up below)
379 SecCSFlags topFlags
= validationFlags
| kSecCSCheckNestedCode
| kSecCSRestrictSymlinks
| kSecCSReportProgress
;
380 if (type
== kAuthorityExecute
)
381 topFlags
|= kSecCSRestrictToAppLike
;
382 switch (rc
= SecStaticCodeCheckValidity(code
, topFlags
, NULL
)) {
383 case errSecSuccess
: // continue below
385 case errSecCSUnsigned
:
386 cfadd(result
, "{%O=#F}", kSecAssessmentAssessmentVerdict
);
387 addAuthority(flags
, result
, "no usable signature");
389 case errSecCSVetoed
: // nested code rejected by rule book; result was filled out there
391 case errSecCSWeakResourceRules
:
392 case errSecCSWeakResourceEnvelope
:
393 case errSecCSResourceNotSupported
:
394 case errSecCSAmbiguousBundleFormat
:
395 case errSecCSSignatureNotVerifiable
:
396 case errSecCSRegularFile
:
397 case errSecCSBadMainExecutable
:
398 case errSecCSBadFrameworkVersion
:
399 case errSecCSUnsealedAppRoot
:
400 case errSecCSUnsealedFrameworkRoot
:
401 case errSecCSInvalidSymlink
:
402 case errSecCSNotAppLike
:
404 // consult the whitelist
407 // we've bypassed evaluateCodeItem before we failed validation. Explicitly apply it now
408 SecStaticCodeSetCallback(code
, kSecCSDefaultFlags
, NULL
, NULL
);
409 evaluateCodeItem(code
, path
, type
, flags
| kSecAssessmentFlagNoCache
, false, result
);
410 if (CFTypeRef verdict
= CFDictionaryGetValue(result
, kSecAssessmentAssessmentVerdict
)) {
411 // verdict rendered from a nested component - signature not acceptable to Gatekeeper
412 if (CFEqual(verdict
, kCFBooleanFalse
)) // nested code rejected by rule book; result was filled out there
414 if (CFEqual(verdict
, kCFBooleanTrue
) && !(flags
& kSecAssessmentFlagIgnoreWhitelist
))
415 if (mOpaqueWhitelist
.contains(code
, feedback
, rc
))
419 label
= "allowed cdhash";
421 CFDictionaryReplaceValue(result
, kSecAssessmentAssessmentVerdict
, kCFBooleanFalse
);
422 label
= "obsolete resource envelope";
424 cfadd(result
, "{%O=%d}", kSecAssessmentAssessmentCodeSigningError
, rc
);
425 addAuthority(flags
, result
, label
, 0, NULL
, true);
429 MacOSError::throwMe(rc
);
435 // Installer archive.
436 // Hybrid policy: If we detect an installer signature, use and validate that.
437 // If we don't, check for a code signature instead.
439 void PolicyEngine::evaluateInstall(CFURLRef path
, SecAssessmentFlags flags
, CFDictionaryRef context
, CFMutableDictionaryRef result
)
441 const AuthorityType type
= kAuthorityInstall
;
443 // check for recent explicit approval, using a bookmark's FileResourceIdentifierKey
444 if (CFRef
<CFDataRef
> bookmark
= cfLoadFile(lastApprovedFile
)) {
446 if (CFRef
<CFURLRef
> url
= CFURLCreateByResolvingBookmarkData(NULL
, bookmark
,
447 kCFBookmarkResolutionWithoutUIMask
| kCFBookmarkResolutionWithoutMountingMask
, NULL
, NULL
, &stale
, NULL
))
448 if (CFRef
<CFDataRef
> savedIdent
= CFDataRef(CFURLCreateResourcePropertyForKeyFromBookmarkData(NULL
, kCFURLFileResourceIdentifierKey
, bookmark
)))
449 if (CFRef
<CFDateRef
> savedMod
= CFDateRef(CFURLCreateResourcePropertyForKeyFromBookmarkData(NULL
, kCFURLContentModificationDateKey
, bookmark
))) {
450 CFRef
<CFDataRef
> currentIdent
;
451 CFRef
<CFDateRef
> currentMod
;
452 if (CFURLCopyResourcePropertyForKey(path
, kCFURLFileResourceIdentifierKey
, ¤tIdent
.aref(), NULL
))
453 if (CFURLCopyResourcePropertyForKey(path
, kCFURLContentModificationDateKey
, ¤tMod
.aref(), NULL
))
454 if (CFEqual(savedIdent
, currentIdent
) && CFEqual(savedMod
, currentMod
)) {
455 cfadd(result
, "{%O=#T}", kSecAssessmentAssessmentVerdict
);
456 addAuthority(flags
, result
, "explicit preference");
462 Xar
xar(cfString(path
).c_str());
464 // follow the code signing path
465 evaluateCode(path
, type
, flags
, context
, result
, true);
469 SQLite3::int64 latentID
= 0; // first (highest priority) disabled matching ID
470 std::string latentLabel
; // ... and associated label, if any
471 if (!xar
.isSigned()) {
473 if (SYSPOLICY_ASSESS_OUTCOME_UNSIGNED_ENABLED())
474 SYSPOLICY_ASSESS_OUTCOME_UNSIGNED(cfString(path
).c_str(), type
);
475 cfadd(result
, "{%O=#F}", kSecAssessmentAssessmentVerdict
);
476 addAuthority(flags
, result
, "no usable signature");
479 if (CFRef
<CFArrayRef
> certs
= xar
.copyCertChain()) {
480 CFRef
<CFTypeRef
> policy
= installerPolicy();
481 CFRef
<SecTrustRef
> trust
;
482 MacOSError::check(SecTrustCreateWithCertificates(certs
, policy
, &trust
.aref()));
483 // MacOSError::check(SecTrustSetAnchorCertificates(trust, cfEmptyArray())); // no anchors
484 MacOSError::check(SecTrustSetOptions(trust
, kSecTrustOptionAllowExpired
| kSecTrustOptionImplicitAnchors
));
486 SecTrustResultType trustResult
;
487 MacOSError::check(SecTrustEvaluate(trust
, &trustResult
));
488 CFRef
<CFArrayRef
> chain
;
489 CSSM_TP_APPLE_EVIDENCE_INFO
*info
;
490 MacOSError::check(SecTrustGetResult(trust
, &trustResult
, &chain
.aref(), &info
));
492 if (flags
& kSecAssessmentFlagRequestOrigin
)
493 setOrigin(chain
, result
);
495 switch (trustResult
) {
496 case kSecTrustResultProceed
:
497 case kSecTrustResultUnspecified
:
502 MacOSError::check(SecTrustGetCssmResultCode(trust
, &rc
));
503 MacOSError::throwMe(rc
);
507 SQLite::Statement
query(*this,
508 "SELECT allow, requirement, id, label, flags, disabled FROM scan_authority"
509 " WHERE type = :type"
510 " ORDER BY priority DESC;");
511 query
.bind(":type").integer(type
);
512 while (query
.nextRow()) {
513 bool allow
= int(query
[0]);
514 const char *reqString
= query
[1];
515 SQLite3::int64 id
= query
[2];
516 const char *label
= query
[3];
517 //sqlite_uint64 ruleFlags = query[4];
518 SQLite3::int64 disabled
= query
[5];
520 CFRef
<SecRequirementRef
> requirement
;
521 MacOSError::check(SecRequirementCreateWithString(CFTempString(reqString
), kSecCSDefaultFlags
, &requirement
.aref()));
522 switch (OSStatus rc
= SecRequirementEvaluate(requirement
, chain
, NULL
, kSecCSDefaultFlags
)) {
523 case errSecSuccess
: // success
525 case errSecCSReqFailed
: // requirement missed, but otherwise okay
527 default: // broken in some way; all tests will fail like this so bail out
528 MacOSError::throwMe(rc
);
536 continue; // the loop
539 if (SYSPOLICY_ASSESS_OUTCOME_ACCEPT_ENABLED() || SYSPOLICY_ASSESS_OUTCOME_DENY_ENABLED()) {
541 SYSPOLICY_ASSESS_OUTCOME_ACCEPT(cfString(path
).c_str(), type
, label
, NULL
);
543 SYSPOLICY_ASSESS_OUTCOME_DENY(cfString(path
).c_str(), type
, label
, NULL
);
546 // not adding to the object cache - we could, but it's not likely to be worth it
547 cfadd(result
, "{%O=%B}", kSecAssessmentAssessmentVerdict
, allow
);
548 addAuthority(flags
, result
, label
, id
);
552 if (SYSPOLICY_ASSESS_OUTCOME_DEFAULT_ENABLED())
553 SYSPOLICY_ASSESS_OUTCOME_DEFAULT(cfString(path
).c_str(), type
, latentLabel
.c_str(), NULL
);
555 // no applicable authority. Deny by default
556 cfadd(result
, "{%O=#F}", kSecAssessmentAssessmentVerdict
);
557 addAuthority(flags
, result
, latentLabel
.c_str(), latentID
);
562 // Create a suitable policy array for verification of installer signatures.
564 static SecPolicyRef
makeCRLPolicy()
566 CFRef
<SecPolicyRef
> policy
;
567 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_REVOCATION_CRL
, &policy
.aref()));
568 CSSM_APPLE_TP_CRL_OPTIONS options
;
569 memset(&options
, 0, sizeof(options
));
570 options
.Version
= CSSM_APPLE_TP_CRL_OPTS_VERSION
;
571 options
.CrlFlags
= CSSM_TP_ACTION_FETCH_CRL_FROM_NET
| CSSM_TP_ACTION_CRL_SUFFICIENT
;
572 CSSM_DATA optData
= { sizeof(options
), (uint8
*)&options
};
573 MacOSError::check(SecPolicySetValue(policy
, &optData
));
574 return policy
.yield();
577 static SecPolicyRef
makeOCSPPolicy()
579 CFRef
<SecPolicyRef
> policy
;
580 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_REVOCATION_OCSP
, &policy
.aref()));
581 CSSM_APPLE_TP_OCSP_OPTIONS options
;
582 memset(&options
, 0, sizeof(options
));
583 options
.Version
= CSSM_APPLE_TP_OCSP_OPTS_VERSION
;
584 options
.Flags
= CSSM_TP_ACTION_OCSP_SUFFICIENT
;
585 CSSM_DATA optData
= { sizeof(options
), (uint8
*)&options
};
586 MacOSError::check(SecPolicySetValue(policy
, &optData
));
587 return policy
.yield();
590 static CFTypeRef
installerPolicy()
592 CFRef
<SecPolicyRef
> base
= SecPolicyCreateBasicX509();
593 CFRef
<SecPolicyRef
> crl
= makeCRLPolicy();
594 CFRef
<SecPolicyRef
> ocsp
= makeOCSPPolicy();
595 return makeCFArray(3, base
.get(), crl
.get(), ocsp
.get());
600 // LaunchServices-layer document open.
601 // We don't cache those at present. If we ever do, we need to authenticate CoreServicesUIAgent as the source of its risk assessment.
603 void PolicyEngine::evaluateDocOpen(CFURLRef path
, SecAssessmentFlags flags
, CFDictionaryRef context
, CFMutableDictionaryRef result
)
606 if (CFStringRef riskCategory
= CFStringRef(CFDictionaryGetValue(context
, kLSDownloadRiskCategoryKey
))) {
607 FileQuarantine
qtn(cfString(path
).c_str());
609 if (CFEqual(riskCategory
, kLSRiskCategorySafe
)
610 || CFEqual(riskCategory
, kLSRiskCategoryNeutral
)
611 || CFEqual(riskCategory
, kLSRiskCategoryUnknown
)
612 || CFEqual(riskCategory
, kLSRiskCategoryMayContainUnsafeExecutable
)) {
613 cfadd(result
, "{%O=#T}", kSecAssessmentAssessmentVerdict
);
614 addAuthority(flags
, result
, "_XProtect");
615 } else if (qtn
.flag(QTN_FLAG_HARD
)) {
616 MacOSError::throwMe(errSecCSFileHardQuarantined
);
617 } else if (qtn
.flag(QTN_FLAG_ASSESSMENT_OK
)) {
618 cfadd(result
, "{%O=#T}", kSecAssessmentAssessmentVerdict
);
619 addAuthority(flags
, result
, "Prior Assessment");
620 } else if (!overrideAssessment(flags
)) { // no need to do more work if we're off
622 evaluateCode(path
, kAuthorityOpenDoc
, flags
, context
, result
, true);
624 // some documents can't be code signed, so this may be quite benign
627 if (CFDictionaryGetValue(result
, kSecAssessmentAssessmentVerdict
) == NULL
) { // no code signature to help us out
628 cfadd(result
, "{%O=#F}", kSecAssessmentAssessmentVerdict
);
629 addAuthority(flags
, result
, "_XProtect");
631 addToAuthority(result
, kLSDownloadRiskCategoryKey
, riskCategory
);
635 // insufficient information from LS - deny by default
636 cfadd(result
, "{%O=#F}", kSecAssessmentAssessmentVerdict
);
637 addAuthority(flags
, result
, "Insufficient Context");
642 // Result-creation helpers
644 void PolicyEngine::addAuthority(SecAssessmentFlags flags
, CFMutableDictionaryRef parent
, const char *label
, SQLite::int64 row
, CFTypeRef cacheInfo
, bool weak
)
646 CFRef
<CFMutableDictionaryRef
> auth
= makeCFMutableDictionary();
647 if (label
&& label
[0])
648 cfadd(auth
, "{%O=%s}", kSecAssessmentAssessmentSource
, label
);
650 CFDictionaryAddValue(auth
, kSecAssessmentAssessmentAuthorityRow
, CFTempNumber(row
));
651 if (overrideAssessment(flags
))
652 CFDictionaryAddValue(auth
, kSecAssessmentAssessmentAuthorityOverride
, kDisabledOverride
);
654 CFDictionaryAddValue(auth
, kSecAssessmentAssessmentFromCache
, cacheInfo
);
656 CFDictionaryAddValue(auth
, kSecAssessmentAssessmentWeakSignature
, kCFBooleanTrue
);
657 CFDictionaryReplaceValue(parent
, kSecAssessmentAssessmentAuthority
, auth
);
659 CFDictionaryAddValue(parent
, kSecAssessmentAssessmentAuthority
, auth
);
663 void PolicyEngine::addToAuthority(CFMutableDictionaryRef parent
, CFStringRef key
, CFTypeRef value
)
665 CFMutableDictionaryRef authority
= CFMutableDictionaryRef(CFDictionaryGetValue(parent
, kSecAssessmentAssessmentAuthority
));
667 CFDictionaryAddValue(authority
, key
, value
);
672 // Add a rule to the policy database
674 CFDictionaryRef
PolicyEngine::add(CFTypeRef inTarget
, AuthorityType type
, SecAssessmentFlags flags
, CFDictionaryRef context
)
676 // default type to execution
677 if (type
== kAuthorityInvalid
)
678 type
= kAuthorityExecute
;
680 authorizeUpdate(flags
, context
);
681 CFDictionary
ctx(context
, errSecCSInvalidAttributeValues
);
682 CFCopyRef
<CFTypeRef
> target
= inTarget
;
683 CFRef
<CFDataRef
> bookmark
= NULL
;
684 std::string filter_unsigned
;
687 case kAuthorityExecute
:
688 normalizeTarget(target
, type
, ctx
, &filter_unsigned
);
689 // bookmarks are untrusted and just a hint to callers
690 bookmark
= ctx
.get
<CFDataRef
>(kSecAssessmentRuleKeyBookmark
);
692 case kAuthorityInstall
:
693 if (inTarget
&& CFGetTypeID(inTarget
) == CFURLGetTypeID()) {
694 // no good way to turn an installer file into a requirement. Pretend to succeeed so caller proceeds
695 CFRef
<CFArrayRef
> properties
= makeCFArray(2, kCFURLFileResourceIdentifierKey
, kCFURLContentModificationDateKey
);
696 CFRef
<CFErrorRef
> error
;
697 CFURLBookmarkCreationOptions options
= kCFURLBookmarkCreationDoNotIncludeSandboxExtensionsMask
| kCFURLBookmarkCreationMinimalBookmarkMask
;
698 if (CFRef
<CFDataRef
> bookmark
= CFURLCreateBookmarkData(NULL
, CFURLRef(inTarget
), options
, properties
, NULL
, &error
.aref())) {
699 UnixPlusPlus::AutoFileDesc
fd(lastApprovedFile
, O_WRONLY
| O_CREAT
| O_TRUNC
);
700 fd
.write(CFDataGetBytePtr(bookmark
), CFDataGetLength(bookmark
));
705 case kAuthorityOpenDoc
:
706 // handle document-open differently: use quarantine flags for whitelisting
707 if (!target
|| CFGetTypeID(target
) != CFURLGetTypeID()) // can only "add" file paths
708 MacOSError::throwMe(errSecCSInvalidObjectRef
);
710 std::string spath
= cfString(target
.as
<CFURLRef
>());
711 FileQuarantine
qtn(spath
.c_str());
712 qtn
.setFlag(QTN_FLAG_ASSESSMENT_OK
);
713 qtn
.applyTo(spath
.c_str());
714 } catch (const CommonError
&error
) {
715 // could not set quarantine flag - report qualified success
716 return cfmake
<CFDictionaryRef
>("{%O=%O,'assessment:error'=%d}",
717 kSecAssessmentAssessmentAuthorityOverride
, CFSTR("error setting quarantine"), error
.osStatus());
719 return cfmake
<CFDictionaryRef
>("{%O=%O}", kSecAssessmentAssessmentAuthorityOverride
, CFSTR("unable to set quarantine"));
724 // if we now have anything else, we're busted
725 if (!target
|| CFGetTypeID(target
) != SecRequirementGetTypeID())
726 MacOSError::throwMe(errSecCSInvalidObjectRef
);
731 double expires
= never
;
733 SQLite::uint64 dbFlags
= kAuthorityFlagWhitelistV2
| kAuthorityFlagWhitelistSHA256
;
735 if (CFNumberRef pri
= ctx
.get
<CFNumberRef
>(kSecAssessmentUpdateKeyPriority
))
736 CFNumberGetValue(pri
, kCFNumberDoubleType
, &priority
);
737 if (CFStringRef lab
= ctx
.get
<CFStringRef
>(kSecAssessmentUpdateKeyLabel
))
738 label
= cfString(lab
);
739 if (CFDateRef time
= ctx
.get
<CFDateRef
>(kSecAssessmentUpdateKeyExpires
))
740 // we're using Julian dates here; convert from CFDate
741 expires
= dateToJulian(time
);
742 if (CFBooleanRef allowing
= ctx
.get
<CFBooleanRef
>(kSecAssessmentUpdateKeyAllow
))
743 allow
= allowing
== kCFBooleanTrue
;
744 if (CFStringRef rem
= ctx
.get
<CFStringRef
>(kSecAssessmentUpdateKeyRemarks
))
745 remarks
= cfString(rem
);
747 CFRef
<CFStringRef
> requirementText
;
748 MacOSError::check(SecRequirementCopyString(target
.as
<SecRequirementRef
>(), kSecCSDefaultFlags
, &requirementText
.aref()));
749 SQLite::Transaction
xact(*this, SQLite3::Transaction::deferred
, "add_rule");
750 SQLite::Statement
insert(*this,
751 "INSERT INTO authority (type, allow, requirement, priority, label, expires, filter_unsigned, remarks, flags)"
752 " VALUES (:type, :allow, :requirement, :priority, :label, :expires, :filter_unsigned, :remarks, :flags);");
753 insert
.bind(":type").integer(type
);
754 insert
.bind(":allow").integer(allow
);
755 insert
.bind(":requirement") = requirementText
.get();
756 insert
.bind(":priority") = priority
;
758 insert
.bind(":label") = label
;
759 insert
.bind(":expires") = expires
;
760 insert
.bind(":filter_unsigned") = filter_unsigned
.empty() ? NULL
: filter_unsigned
.c_str();
761 if (!remarks
.empty())
762 insert
.bind(":remarks") = remarks
;
763 insert
.bind(":flags").integer(dbFlags
);
765 SQLite::int64 newRow
= this->lastInsert();
767 SQLite::Statement
bi(*this, "INSERT INTO bookmarkhints (bookmark, authority) VALUES (:bookmark, :authority)");
768 bi
.bind(":bookmark") = CFDataRef(bookmark
);
769 bi
.bind(":authority").integer(newRow
);
772 this->purgeObjects(priority
);
774 notify_post(kNotifySecAssessmentUpdate
);
775 return cfmake
<CFDictionaryRef
>("{%O=%d}", kSecAssessmentUpdateKeyRow
, newRow
);
779 CFDictionaryRef
PolicyEngine::remove(CFTypeRef target
, AuthorityType type
, SecAssessmentFlags flags
, CFDictionaryRef context
)
781 if (type
== kAuthorityOpenDoc
) {
782 // handle document-open differently: use quarantine flags for whitelisting
783 authorizeUpdate(flags
, context
);
784 if (!target
|| CFGetTypeID(target
) != CFURLGetTypeID())
785 MacOSError::throwMe(errSecCSInvalidObjectRef
);
786 std::string spath
= cfString(CFURLRef(target
)).c_str();
787 FileQuarantine
qtn(spath
.c_str());
788 qtn
.clearFlag(QTN_FLAG_ASSESSMENT_OK
);
789 qtn
.applyTo(spath
.c_str());
792 return manipulateRules("DELETE FROM authority", target
, type
, flags
, context
, true);
795 CFDictionaryRef
PolicyEngine::enable(CFTypeRef target
, AuthorityType type
, SecAssessmentFlags flags
, CFDictionaryRef context
, bool authorize
)
797 return manipulateRules("UPDATE authority SET disabled = 0", target
, type
, flags
, context
, authorize
);
800 CFDictionaryRef
PolicyEngine::disable(CFTypeRef target
, AuthorityType type
, SecAssessmentFlags flags
, CFDictionaryRef context
, bool authorize
)
802 return manipulateRules("UPDATE authority SET disabled = 1", target
, type
, flags
, context
, authorize
);
805 CFDictionaryRef
PolicyEngine::find(CFTypeRef target
, AuthorityType type
, SecAssessmentFlags flags
, CFDictionaryRef context
)
807 SQLite::Statement
query(*this);
808 selectRules(query
, "SELECT scan_authority.id, scan_authority.type, scan_authority.requirement, scan_authority.allow, scan_authority.label, scan_authority.priority, scan_authority.remarks, scan_authority.expires, scan_authority.disabled, bookmarkhints.bookmark FROM scan_authority LEFT OUTER JOIN bookmarkhints ON scan_authority.id = bookmarkhints.authority",
809 "scan_authority", target
, type
, flags
, context
,
810 " ORDER BY priority DESC");
811 CFRef
<CFMutableArrayRef
> found
= makeCFMutableArray(0);
812 while (query
.nextRow()) {
813 SQLite::int64 id
= query
[0];
814 int type
= int(query
[1]);
815 const char *requirement
= query
[2];
816 int allow
= int(query
[3]);
817 const char *label
= query
[4];
818 double priority
= query
[5];
819 const char *remarks
= query
[6];
820 double expires
= query
[7];
821 int disabled
= int(query
[8]);
822 CFRef
<CFDataRef
> bookmark
= query
[9].data();
823 CFRef
<CFMutableDictionaryRef
> rule
= makeCFMutableDictionary(5,
824 kSecAssessmentRuleKeyID
, CFTempNumber(id
).get(),
825 kSecAssessmentRuleKeyType
, CFRef
<CFStringRef
>(typeNameFor(type
)).get(),
826 kSecAssessmentRuleKeyRequirement
, CFTempString(requirement
).get(),
827 kSecAssessmentRuleKeyAllow
, allow
? kCFBooleanTrue
: kCFBooleanFalse
,
828 kSecAssessmentRuleKeyPriority
, CFTempNumber(priority
).get()
831 CFDictionaryAddValue(rule
, kSecAssessmentRuleKeyLabel
, CFTempString(label
));
833 CFDictionaryAddValue(rule
, kSecAssessmentRuleKeyRemarks
, CFTempString(remarks
));
834 if (expires
!= never
)
835 CFDictionaryAddValue(rule
, kSecAssessmentRuleKeyExpires
, CFRef
<CFDateRef
>(julianToDate(expires
)));
837 CFDictionaryAddValue(rule
, kSecAssessmentRuleKeyDisabled
, CFTempNumber(disabled
));
839 CFDictionaryAddValue(rule
, kSecAssessmentRuleKeyBookmark
, bookmark
);
840 CFArrayAppendValue(found
, rule
);
842 if (CFArrayGetCount(found
) == 0)
843 MacOSError::throwMe(errSecCSNoMatches
);
844 return cfmake
<CFDictionaryRef
>("{%O=%O}", kSecAssessmentUpdateKeyFound
, found
.get());
848 CFDictionaryRef
PolicyEngine::update(CFTypeRef target
, SecAssessmentFlags flags
, CFDictionaryRef context
)
851 installExplicitSet(gkeAuthFile
, gkeSigsFile
);
853 AuthorityType type
= typeFor(context
, kAuthorityInvalid
);
854 CFStringRef edit
= CFStringRef(CFDictionaryGetValue(context
, kSecAssessmentContextKeyUpdate
));
855 CFDictionaryRef result
;
856 if (CFEqual(edit
, kSecAssessmentUpdateOperationAdd
))
857 result
= this->add(target
, type
, flags
, context
);
858 else if (CFEqual(edit
, kSecAssessmentUpdateOperationRemove
))
859 result
= this->remove(target
, type
, flags
, context
);
860 else if (CFEqual(edit
, kSecAssessmentUpdateOperationEnable
))
861 result
= this->enable(target
, type
, flags
, context
, true);
862 else if (CFEqual(edit
, kSecAssessmentUpdateOperationDisable
))
863 result
= this->disable(target
, type
, flags
, context
, true);
864 else if (CFEqual(edit
, kSecAssessmentUpdateOperationFind
))
865 result
= this->find(target
, type
, flags
, context
);
867 MacOSError::throwMe(errSecCSInvalidAttributeValues
);
869 result
= makeCFDictionary(0); // success, no details
875 // Construct and prepare an SQL query on the authority table, operating on some set of existing authority records.
876 // In essence, this appends a suitable WHERE clause to the stanza passed and prepares it on the statement given.
878 void PolicyEngine::selectRules(SQLite::Statement
&action
, std::string phrase
, std::string table
,
879 CFTypeRef inTarget
, AuthorityType type
, SecAssessmentFlags flags
, CFDictionaryRef context
, std::string suffix
/* = "" */)
881 CFDictionary
ctx(context
, errSecCSInvalidAttributeValues
);
882 CFCopyRef
<CFTypeRef
> target
= inTarget
;
883 std::string filter_unsigned
; // ignored; used just to trigger ad-hoc signing
884 normalizeTarget(target
, type
, ctx
, &filter_unsigned
);
887 if (CFStringRef lab
= ctx
.get
<CFStringRef
>(kSecAssessmentUpdateKeyLabel
))
888 label
= cfString(CFStringRef(lab
));
892 if (type
== kAuthorityInvalid
) {
893 action
.query(phrase
+ suffix
);
895 action
.query(phrase
+ " WHERE " + table
+ ".type = :type" + suffix
);
896 action
.bind(":type").integer(type
);
898 } else { // have label
899 if (type
== kAuthorityInvalid
) {
900 action
.query(phrase
+ " WHERE " + table
+ ".label = :label" + suffix
);
902 action
.query(phrase
+ " WHERE " + table
+ ".type = :type AND " + table
+ ".label = :label" + suffix
);
903 action
.bind(":type").integer(type
);
905 action
.bind(":label") = label
;
907 } else if (CFGetTypeID(target
) == CFNumberGetTypeID()) {
908 action
.query(phrase
+ " WHERE " + table
+ ".id = :id" + suffix
);
909 action
.bind(":id").integer(cfNumber
<uint64_t>(target
.as
<CFNumberRef
>()));
910 } else if (CFGetTypeID(target
) == SecRequirementGetTypeID()) {
911 if (type
== kAuthorityInvalid
)
912 type
= kAuthorityExecute
;
913 CFRef
<CFStringRef
> requirementText
;
914 MacOSError::check(SecRequirementCopyString(target
.as
<SecRequirementRef
>(), kSecCSDefaultFlags
, &requirementText
.aref()));
915 action
.query(phrase
+ " WHERE " + table
+ ".type = :type AND " + table
+ ".requirement = :requirement" + suffix
);
916 action
.bind(":type").integer(type
);
917 action
.bind(":requirement") = requirementText
.get();
919 MacOSError::throwMe(errSecCSInvalidObjectRef
);
924 // Execute an atomic change to existing records in the authority table.
926 CFDictionaryRef
PolicyEngine::manipulateRules(const std::string
&stanza
,
927 CFTypeRef inTarget
, AuthorityType type
, SecAssessmentFlags flags
, CFDictionaryRef context
, bool authorize
)
929 SQLite::Transaction
xact(*this, SQLite3::Transaction::deferred
, "rule_change");
930 SQLite::Statement
action(*this);
932 authorizeUpdate(flags
, context
);
933 selectRules(action
, stanza
, "authority", inTarget
, type
, flags
, context
);
935 unsigned int changes
= this->changes(); // latch change count
936 // We MUST purge objects with priority <= MAX(priority of any changed rules);
937 // but for now we just get lazy and purge them ALL.
939 this->purgeObjects(1.0E100
);
941 notify_post(kNotifySecAssessmentUpdate
);
942 return cfmake
<CFDictionaryRef
>("{%O=%d}", kSecAssessmentUpdateKeyCount
, changes
);
944 // no change; return an error
945 MacOSError::throwMe(errSecCSNoMatches
);
950 // Fill in extra information about the originator of cryptographic credentials found - if any
952 void PolicyEngine::setOrigin(CFArrayRef chain
, CFMutableDictionaryRef result
)
955 if (CFArrayGetCount(chain
) > 0)
956 if (SecCertificateRef leaf
= SecCertificateRef(CFArrayGetValueAtIndex(chain
, 0)))
957 if (CFStringRef summary
= SecCertificateCopyLongDescription(NULL
, leaf
, NULL
)) {
958 CFDictionarySetValue(result
, kSecAssessmentAssessmentOriginator
, summary
);
965 // Take an assessment outcome and record it in the object cache
967 void PolicyEngine::recordOutcome(SecStaticCodeRef code
, bool allow
, AuthorityType type
, double expires
, SQLite::int64 authority
)
969 CFRef
<CFDictionaryRef
> info
;
970 MacOSError::check(SecCodeCopySigningInformation(code
, kSecCSDefaultFlags
, &info
.aref()));
971 CFDataRef cdHash
= CFDataRef(CFDictionaryGetValue(info
, kSecCodeInfoUnique
));
972 assert(cdHash
); // was signed
973 CFRef
<CFURLRef
> path
;
974 MacOSError::check(SecCodeCopyPath(code
, kSecCSDefaultFlags
, &path
.aref()));
976 SQLite::Transaction
xact(*this, SQLite3::Transaction::deferred
, "caching");
977 SQLite::Statement
insert(*this,
978 "INSERT OR REPLACE INTO object (type, allow, hash, expires, path, authority)"
979 " VALUES (:type, :allow, :hash, :expires, :path,"
980 " CASE :authority WHEN 0 THEN (SELECT id FROM authority WHERE label = 'No Matching Rule') ELSE :authority END"
982 insert
.bind(":type").integer(type
);
983 insert
.bind(":allow").integer(allow
);
984 insert
.bind(":hash") = cdHash
;
985 insert
.bind(":expires") = expires
;
986 insert
.bind(":path") = cfString(path
);
987 insert
.bind(":authority").integer(authority
);
994 // Record a UI failure record after proper validation of the caller
996 void PolicyEngine::recordFailure(CFDictionaryRef info
)
998 CFRef
<CFDataRef
> infoData
= makeCFData(info
);
999 UnixPlusPlus::AutoFileDesc
fd(lastRejectFile
, O_WRONLY
| O_CREAT
| O_TRUNC
);
1000 fd
.write(CFDataGetBytePtr(infoData
), CFDataGetLength(infoData
));
1001 notify_post(kNotifySecAssessmentRecordingChange
);
1006 // Perform update authorization processing.
1007 // Throws an exception if authorization is denied.
1009 static void authorizeUpdate(SecAssessmentFlags flags
, CFDictionaryRef context
)
1011 AuthorizationRef authorization
= NULL
;
1014 if (CFTypeRef authkey
= CFDictionaryGetValue(context
, kSecAssessmentUpdateKeyAuthorization
))
1015 if (CFGetTypeID(authkey
) == CFDataGetTypeID()) {
1016 CFDataRef authdata
= CFDataRef(authkey
);
1017 if (CFDataGetLength(authdata
) != sizeof(AuthorizationExternalForm
))
1018 MacOSError::throwMe(errSecCSInvalidObjectRef
);
1019 MacOSError::check(AuthorizationCreateFromExternalForm((AuthorizationExternalForm
*)CFDataGetBytePtr(authdata
), &authorization
));
1021 if (authorization
== NULL
)
1022 MacOSError::throwMe(errSecCSDBDenied
);
1024 AuthorizationItem right
[] = {
1025 { "com.apple.security.assessment.update", 0, NULL
, 0 }
1027 AuthorizationRights rights
= { sizeof(right
) / sizeof(right
[0]), right
};
1028 MacOSError::check(AuthorizationCopyRights(authorization
, &rights
, NULL
,
1029 kAuthorizationFlagExtendRights
| kAuthorizationFlagInteractionAllowed
, NULL
));
1031 MacOSError::check(AuthorizationFree(authorization
, kAuthorizationFlagDefaults
));
1036 // Perform common argument normalizations for update operations
1038 void PolicyEngine::normalizeTarget(CFRef
<CFTypeRef
> &target
, AuthorityType type
, CFDictionary
&context
, std::string
*signUnsigned
)
1040 // turn CFURLs into (designated) SecRequirements
1041 if (target
&& CFGetTypeID(target
) == CFURLGetTypeID()) {
1042 CFRef
<SecStaticCodeRef
> code
;
1043 CFURLRef path
= target
.as
<CFURLRef
>();
1044 MacOSError::check(SecStaticCodeCreateWithPath(path
, kSecCSDefaultFlags
, &code
.aref()));
1045 switch (OSStatus rc
= SecCodeCopyDesignatedRequirement(code
, kSecCSDefaultFlags
, (SecRequirementRef
*)&target
.aref())) {
1046 case errSecSuccess
: {
1047 // use the *default* DR to avoid unreasonably wide DRs opening up Gatekeeper to attack
1048 CFRef
<CFDictionaryRef
> info
;
1049 MacOSError::check(SecCodeCopySigningInformation(code
, kSecCSRequirementInformation
, &info
.aref()));
1050 target
= CFDictionaryGetValue(info
, kSecCodeInfoImplicitDesignatedRequirement
);
1053 case errSecCSUnsigned
:
1054 if (signUnsigned
&& temporarySigning(code
, type
, path
, kAuthorityFlagWhitelistV2
| kAuthorityFlagWhitelistSHA256
)) { // ad-hoc sign the code temporarily
1055 MacOSError::check(SecCodeCopyDesignatedRequirement(code
, kSecCSDefaultFlags
, (SecRequirementRef
*)&target
.aref()));
1056 CFRef
<CFDictionaryRef
> info
;
1057 MacOSError::check(SecCodeCopySigningInformation(code
, kSecCSInternalInformation
, &info
.aref()));
1058 if (CFDataRef cdData
= CFDataRef(CFDictionaryGetValue(info
, kSecCodeInfoCodeDirectory
)))
1059 *signUnsigned
= ((const CodeDirectory
*)CFDataGetBytePtr(cdData
))->screeningCode();
1062 MacOSError::check(rc
);
1063 case errSecCSSignatureFailed
:
1064 // recover certain cases of broken signatures (well, try)
1065 if (codeInvalidityExceptions(code
, NULL
)) {
1066 // Ad-hoc sign the code in place (requiring a writable subject). This requires root privileges.
1067 CFRef
<SecCodeSignerRef
> signer
;
1068 CFTemp
<CFDictionaryRef
> arguments("{%O=#N}", kSecCodeSignerIdentity
);
1069 MacOSError::check(SecCodeSignerCreate(arguments
, kSecCSSignOpaque
, &signer
.aref()));
1070 MacOSError::check(SecCodeSignerAddSignature(signer
, code
, kSecCSDefaultFlags
));
1071 MacOSError::check(SecCodeCopyDesignatedRequirement(code
, kSecCSDefaultFlags
, (SecRequirementRef
*)&target
.aref()));
1074 MacOSError::check(rc
);
1076 MacOSError::check(rc
);
1078 if (context
.get(kSecAssessmentUpdateKeyRemarks
) == NULL
) {
1079 // no explicit remarks; add one with the path
1080 CFRef
<CFURLRef
> path
;
1081 MacOSError::check(SecCodeCopyPath(code
, kSecCSDefaultFlags
, &path
.aref()));
1082 CFMutableDictionaryRef dict
= makeCFMutableDictionary(context
.get());
1083 CFDictionaryAddValue(dict
, kSecAssessmentUpdateKeyRemarks
, CFTempString(cfString(path
)));
1086 CFStringRef edit
= CFStringRef(context
.get(kSecAssessmentContextKeyUpdate
));
1087 if (type
== kAuthorityExecute
&& CFEqual(edit
, kSecAssessmentUpdateOperationAdd
)) {
1088 // implicitly whitelist the code
1089 mOpaqueWhitelist
.add(code
);
1096 // Process special overrides for invalidly signed code.
1097 // This is the (hopefully minimal) concessions we make to keep hurting our customers
1098 // for our own prior mistakes...
1100 static bool codeInvalidityExceptions(SecStaticCodeRef code
, CFMutableDictionaryRef result
)
1102 if (OSAIsRecognizedExecutableURL
) {
1103 CFRef
<CFDictionaryRef
> info
;
1104 MacOSError::check(SecCodeCopySigningInformation(code
, kSecCSDefaultFlags
, &info
.aref()));
1105 if (CFURLRef executable
= CFURLRef(CFDictionaryGetValue(info
, kSecCodeInfoMainExecutable
))) {
1107 if (OSAIsRecognizedExecutableURL(executable
, &error
)) {
1109 CFDictionaryAddValue(result
,
1110 kSecAssessmentAssessmentAuthorityOverride
, CFSTR("ignoring known invalid applet signature"));
1119 } // end namespace CodeSigning
1120 } // end namespace Security