2 * Copyright (c) 2006-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@
25 // StaticCode - SecStaticCode API objects
27 #include "StaticCode.h"
31 #include "reqdumper.h"
32 #include "reqparser.h"
34 #include "resources.h"
35 #include "detachedrep.h"
36 #include "csdatabase.h"
37 #include "dirscanner.h"
38 #include <CoreFoundation/CFURLAccess.h>
39 #include <Security/SecPolicyPriv.h>
40 #include <Security/SecTrustPriv.h>
41 #include <Security/SecCertificatePriv.h>
42 #include <Security/CMSPrivate.h>
43 #include <Security/SecCmsContentInfo.h>
44 #include <Security/SecCmsSignerInfo.h>
45 #include <Security/SecCmsSignedData.h>
46 #include <Security/cssmapplePriv.h>
47 #include <security_utilities/unix++.h>
48 #include <security_utilities/cfmunge.h>
49 #include <Security/CMSDecoder.h>
50 #include <security_utilities/logging.h>
53 #include <IOKit/storage/IOStorageDeviceCharacteristics.h>
57 namespace CodeSigning
{
59 using namespace UnixPlusPlus
;
61 // A requirement representing a Mac or iOS dev cert, a Mac or iOS distribution cert, or a developer ID
62 static const char WWDRRequirement
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.2] exists";
63 static const char MACWWDRRequirement
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.12] exists";
64 static const char developerID
[] = "anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists"
65 " and certificate leaf[field.1.2.840.113635.100.6.1.13] exists";
66 static const char distributionCertificate
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.7] exists";
67 static const char iPhoneDistributionCert
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.4] exists";
70 // Map a component slot number to a suitable error code for a failure
72 static inline OSStatus
errorForSlot(CodeDirectory::SpecialSlot slot
)
76 return errSecCSInfoPlistFailed
;
77 case cdResourceDirSlot
:
78 return errSecCSResourceDirectoryFailed
;
80 return errSecCSSignatureFailed
;
86 // Construct a SecStaticCode object given a disk representation object
88 SecStaticCode::SecStaticCode(DiskRep
*rep
)
90 mValidated(false), mExecutableValidated(false), mResourcesValidated(false), mResourcesValidContext(NULL
),
91 mProgressQueue("com.apple.security.validation-progress", false, DISPATCH_QUEUE_PRIORITY_DEFAULT
),
92 mDesignatedReq(NULL
), mGotResourceBase(false), mMonitor(NULL
), mLimitedAsync(NULL
), mEvalDetails(NULL
)
94 CODESIGN_STATIC_CREATE(this, rep
);
95 CFRef
<CFDataRef
> codeDirectory
= rep
->codeDirectory();
96 if (codeDirectory
&& CFDataGetLength(codeDirectory
) <= 0)
97 MacOSError::throwMe(errSecCSSignatureInvalid
);
98 checkForSystemSignature();
103 // Clean up a SecStaticCode object
105 SecStaticCode::~SecStaticCode() throw()
107 ::free(const_cast<Requirement
*>(mDesignatedReq
));
108 delete mResourcesValidContext
;
109 delete mLimitedAsync
;
115 // Initialize a nested SecStaticCode object from its parent
117 void SecStaticCode::initializeFromParent(const SecStaticCode
& parent
) {
118 setMonitor(parent
.monitor());
119 if (parent
.mLimitedAsync
)
120 mLimitedAsync
= new LimitedAsync(*parent
.mLimitedAsync
);
124 // CF-level comparison of SecStaticCode objects compares CodeDirectory hashes if signed,
125 // and falls back on comparing canonical paths if (both are) not.
127 bool SecStaticCode::equal(SecCFObject
&secOther
)
129 SecStaticCode
*other
= static_cast<SecStaticCode
*>(&secOther
);
130 CFDataRef mine
= this->cdHash();
131 CFDataRef his
= other
->cdHash();
133 return mine
&& his
&& CFEqual(mine
, his
);
135 return CFEqual(CFRef
<CFURLRef
>(this->copyCanonicalPath()), CFRef
<CFURLRef
>(other
->copyCanonicalPath()));
138 CFHashCode
SecStaticCode::hash()
140 if (CFDataRef h
= this->cdHash())
143 return CFHash(CFRef
<CFURLRef
>(this->copyCanonicalPath()));
148 // Invoke a stage monitor if registered
150 CFTypeRef
SecStaticCode::reportEvent(CFStringRef stage
, CFDictionaryRef info
)
153 return mMonitor(this->handle(false), stage
, info
);
158 void SecStaticCode::prepareProgress(unsigned int workload
)
160 dispatch_sync(mProgressQueue
, ^{
161 mCancelPending
= false; // not cancelled
163 if (mValidationFlags
& kSecCSReportProgress
) {
164 mCurrentWork
= 0; // nothing done yet
165 mTotalWork
= workload
; // totally fake - we don't know how many files we'll get to chew
169 void SecStaticCode::reportProgress(unsigned amount
/* = 1 */)
171 if (mMonitor
&& (mValidationFlags
& kSecCSReportProgress
)) {
172 // update progress and report
173 __block
bool cancel
= false;
174 dispatch_sync(mProgressQueue
, ^{
177 mCurrentWork
+= amount
;
178 mMonitor(this->handle(false), CFSTR("progress"), CFTemp
<CFDictionaryRef
>("{current=%d,total=%d}", mCurrentWork
, mTotalWork
));
180 // if cancellation is pending, abort now
182 MacOSError::throwMe(errSecCSCancelled
);
188 // Set validation conditions for fine-tuning legacy tolerance
190 static void addError(CFTypeRef cfError
, void* context
)
192 if (CFGetTypeID(cfError
) == CFNumberGetTypeID()) {
194 CFNumberGetValue(CFNumberRef(cfError
), kCFNumberSInt64Type
, (void*)&error
);
195 MacOSErrorSet
* errors
= (MacOSErrorSet
*)context
;
196 errors
->insert(OSStatus(error
));
200 void SecStaticCode::setValidationModifiers(CFDictionaryRef conditions
)
203 CFDictionary
source(conditions
, errSecCSDbCorrupt
);
204 mAllowOmissions
= source
.get
<CFArrayRef
>("omissions");
205 if (CFArrayRef errors
= source
.get
<CFArrayRef
>("errors"))
206 CFArrayApplyFunction(errors
, CFRangeMake(0, CFArrayGetCount(errors
)), addError
, &this->mTolerateErrors
);
212 // Request cancellation of a validation in progress.
213 // We do this by posting an abort flag that is checked periodically.
215 void SecStaticCode::cancelValidation()
217 if (!(mValidationFlags
& kSecCSReportProgress
)) // not using progress reporting; cancel won't make it through
218 MacOSError::throwMe(errSecCSInvalidFlags
);
219 dispatch_sync(mProgressQueue
, ^{
220 mCancelPending
= true;
226 // Attach a detached signature.
228 void SecStaticCode::detachedSignature(CFDataRef sigData
)
231 mDetachedSig
= sigData
;
232 mRep
= new DetachedRep(sigData
, mRep
->base(), "explicit detached");
233 CODESIGN_STATIC_ATTACH_EXPLICIT(this, mRep
);
237 CODESIGN_STATIC_ATTACH_EXPLICIT(this, NULL
);
243 // Consult the system detached signature database to see if it contains
244 // a detached signature for this StaticCode. If it does, fetch and attach it.
245 // We do this only if the code has no signature already attached.
247 void SecStaticCode::checkForSystemSignature()
249 if (!this->isSigned()) {
250 SignatureDatabase db
;
253 if (RefPointer
<DiskRep
> dsig
= db
.findCode(mRep
)) {
254 CODESIGN_STATIC_ATTACH_SYSTEM(this, dsig
);
264 // Return a descriptive string identifying the source of the code signature
266 string
SecStaticCode::signatureSource()
270 if (DetachedRep
*rep
= dynamic_cast<DetachedRep
*>(mRep
.get()))
271 return rep
->source();
277 // Do ::required, but convert incoming SecCodeRefs to their SecStaticCodeRefs
280 SecStaticCode
*SecStaticCode::requiredStatic(SecStaticCodeRef ref
)
282 SecCFObject
*object
= SecCFObject::required(ref
, errSecCSInvalidObjectRef
);
283 if (SecStaticCode
*scode
= dynamic_cast<SecStaticCode
*>(object
))
285 else if (SecCode
*code
= dynamic_cast<SecCode
*>(object
))
286 return code
->staticCode();
287 else // neither (a SecSomethingElse)
288 MacOSError::throwMe(errSecCSInvalidObjectRef
);
291 SecCode
*SecStaticCode::optionalDynamic(SecStaticCodeRef ref
)
293 SecCFObject
*object
= SecCFObject::required(ref
, errSecCSInvalidObjectRef
);
294 if (dynamic_cast<SecStaticCode
*>(object
))
296 else if (SecCode
*code
= dynamic_cast<SecCode
*>(object
))
298 else // neither (a SecSomethingElse)
299 MacOSError::throwMe(errSecCSInvalidObjectRef
);
304 // Void all cached validity data.
306 // We also throw out cached components, because the new signature data may have
307 // a different idea of what components should be present. We could reconcile the
308 // cached data instead, if performance seems to be impacted.
310 void SecStaticCode::resetValidity()
312 CODESIGN_EVAL_STATIC_RESET(this);
314 mExecutableValidated
= mResourcesValidated
= false;
315 if (mResourcesValidContext
) {
316 delete mResourcesValidContext
;
317 mResourcesValidContext
= NULL
;
321 for (unsigned n
= 0; n
< cdSlotCount
; n
++)
324 mEntitlements
= NULL
;
325 mResourceDict
= NULL
;
326 mDesignatedReq
= NULL
;
328 mGotResourceBase
= false;
334 // we may just have updated the system database, so check again
335 checkForSystemSignature();
340 // Retrieve a sealed component by special slot index.
341 // If the CodeDirectory has already been validated, validate against that.
342 // Otherwise, retrieve the component without validation (but cache it). Validation
343 // will go through the cache and validate all cached components.
345 CFDataRef
SecStaticCode::component(CodeDirectory::SpecialSlot slot
, OSStatus fail
/* = errSecCSSignatureFailed */)
347 assert(slot
<= cdSlotMax
);
349 CFRef
<CFDataRef
> &cache
= mCache
[slot
];
351 if (CFRef
<CFDataRef
> data
= mRep
->component(slot
)) {
352 if (validated()) // if the directory has been validated...
353 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data
), // ... and it's no good
354 CFDataGetLength(data
), -slot
))
355 MacOSError::throwMe(errorForSlot(slot
)); // ... then bail
356 cache
= data
; // it's okay, cache it
357 } else { // absent, mark so
358 if (validated()) // if directory has been validated...
359 if (codeDirectory()->slotIsPresent(-slot
)) // ... and the slot is NOT missing
360 MacOSError::throwMe(errorForSlot(slot
)); // was supposed to be there
361 cache
= CFDataRef(kCFNull
); // white lie
364 return (cache
== CFDataRef(kCFNull
)) ? NULL
: cache
.get();
369 // Get the CodeDirectory.
370 // Throws (if check==true) or returns NULL (check==false) if there is none.
371 // Always throws if the CodeDirectory exists but is invalid.
372 // NEVER validates against the signature.
374 const CodeDirectory
*SecStaticCode::codeDirectory(bool check
/* = true */)
377 if (mDir
.take(mRep
->codeDirectory())) {
378 const CodeDirectory
*dir
= reinterpret_cast<const CodeDirectory
*>(CFDataGetBytePtr(mDir
));
379 dir
->checkIntegrity();
383 return reinterpret_cast<const CodeDirectory
*>(CFDataGetBytePtr(mDir
));
385 MacOSError::throwMe(errSecCSUnsigned
);
391 // Get the hash of the CodeDirectory.
392 // Returns NULL if there is none.
394 CFDataRef
SecStaticCode::cdHash()
397 if (const CodeDirectory
*cd
= codeDirectory(false)) {
399 hash(cd
, cd
->length());
402 mCDHash
.take(makeCFData(digest
, sizeof(digest
)));
403 CODESIGN_STATIC_CDHASH(this, digest
, sizeof(digest
));
411 // Return the CMS signature blob; NULL if none found.
413 CFDataRef
SecStaticCode::signature()
416 mSignature
.take(mRep
->signature());
419 MacOSError::throwMe(errSecCSUnsigned
);
424 // Verify the signature on the CodeDirectory.
425 // If this succeeds (doesn't throw), the CodeDirectory is statically trustworthy.
426 // Any outcome (successful or not) is cached for the lifetime of the StaticCode.
428 void SecStaticCode::validateDirectory()
430 // echo previous outcome, if any
431 // track revocation separately, as it may not have been checked
432 // during the initial validation
433 if (!validated() || ((mValidationFlags
& kSecCSEnforceRevocationChecks
) && !revocationChecked()))
435 // perform validation (or die trying)
436 CODESIGN_EVAL_STATIC_DIRECTORY(this);
437 mValidationExpired
= verifySignature();
438 if (mValidationFlags
& kSecCSEnforceRevocationChecks
)
439 mRevocationChecked
= true;
441 for (CodeDirectory::SpecialSlot slot
= codeDirectory()->maxSpecialSlot(); slot
>= 1; --slot
)
442 if (mCache
[slot
]) // if we already loaded that resource...
443 validateComponent(slot
, errorForSlot(slot
)); // ... then check it now
444 mValidated
= true; // we've done the deed...
445 mValidationResult
= errSecSuccess
; // ... and it was good
446 } catch (const CommonError
&err
) {
448 mValidationResult
= err
.osStatus();
451 secdebug("staticCode", "%p validation threw non-common exception", this);
453 mValidationResult
= errSecCSInternalError
;
457 if (mValidationResult
== errSecSuccess
) {
458 if (mValidationExpired
)
459 if ((mValidationFlags
& kSecCSConsiderExpiration
)
460 || (codeDirectory()->flags
& kSecCodeSignatureForceExpiration
))
461 MacOSError::throwMe(CSSMERR_TP_CERT_EXPIRED
);
463 MacOSError::throwMe(mValidationResult
);
468 // Load and validate the CodeDirectory and all components *except* those related to the resource envelope.
469 // Those latter components are checked by validateResources().
471 void SecStaticCode::validateNonResourceComponents()
473 this->validateDirectory();
474 for (CodeDirectory::SpecialSlot slot
= codeDirectory()->maxSpecialSlot(); slot
>= 1; --slot
)
476 case cdResourceDirSlot
: // validated by validateResources
479 this->component(slot
); // loads and validates
486 // Get the (signed) signing date from the code signature.
487 // Sadly, we need to validate the signature to get the date (as a side benefit).
488 // This means that you can't get the signing time for invalidly signed code.
490 // We could run the decoder "almost to" verification to avoid this, but there seems
491 // little practical point to such a duplication of effort.
493 CFAbsoluteTime
SecStaticCode::signingTime()
499 CFAbsoluteTime
SecStaticCode::signingTimestamp()
502 return mSigningTimestamp
;
507 // Verify the CMS signature on the CodeDirectory.
508 // This performs the cryptographic tango. It returns if the signature is valid,
509 // or throws if it is not. As a side effect, a successful return sets up the
510 // cached certificate chain for future use.
511 // Returns true if the signature is expired (the X.509 sense), false if it's not.
512 // Expiration is fatal (throws) if a secure timestamp is included, but not otherwise.
514 bool SecStaticCode::verifySignature()
516 // ad-hoc signed code is considered validly signed by definition
517 if (flag(kSecCodeSignatureAdhoc
)) {
518 CODESIGN_EVAL_STATIC_SIGNATURE_ADHOC(this);
522 DTRACK(CODESIGN_EVAL_STATIC_SIGNATURE
, this, (char*)this->mainExecutablePath().c_str());
524 // decode CMS and extract SecTrust for verification
525 CFRef
<CMSDecoderRef
> cms
;
526 MacOSError::check(CMSDecoderCreate(&cms
.aref())); // create decoder
527 CFDataRef sig
= this->signature();
528 MacOSError::check(CMSDecoderUpdateMessage(cms
, CFDataGetBytePtr(sig
), CFDataGetLength(sig
)));
529 this->codeDirectory(); // load CodeDirectory (sets mDir)
530 MacOSError::check(CMSDecoderSetDetachedContent(cms
, mDir
));
531 MacOSError::check(CMSDecoderFinalizeMessage(cms
));
532 MacOSError::check(CMSDecoderSetSearchKeychain(cms
, cfEmptyArray()));
533 CFRef
<CFArrayRef
> vf_policies
= verificationPolicies();
534 CFRef
<CFArrayRef
> ts_policies
= SecPolicyCreateAppleTimeStampingAndRevocationPolicies(vf_policies
);
535 CMSSignerStatus status
;
536 MacOSError::check(CMSDecoderCopySignerStatus(cms
, 0, vf_policies
,
537 false, &status
, &mTrust
.aref(), NULL
));
539 if (status
!= kCMSSignerValid
)
540 MacOSError::throwMe(errSecCSSignatureFailed
);
542 // internal signing time (as specified by the signer; optional)
543 mSigningTime
= 0; // "not present" marker (nobody could code sign on Jan 1, 2001 :-)
544 switch (OSStatus rc
= CMSDecoderCopySignerSigningTime(cms
, 0, &mSigningTime
)) {
546 case errSecSigningTimeMissing
:
549 MacOSError::throwMe(rc
);
552 // certified signing time (as specified by a TSA; optional)
553 mSigningTimestamp
= 0;
554 switch (OSStatus rc
= CMSDecoderCopySignerTimestampWithPolicy(cms
, ts_policies
, 0, &mSigningTimestamp
)) {
556 case errSecTimestampMissing
:
559 MacOSError::throwMe(rc
);
562 // set up the environment for SecTrust
563 if (mValidationFlags
& kSecCSNoNetworkAccess
) {
564 MacOSError::check(SecTrustSetNetworkFetchAllowed(mTrust
,false)); // no network?
566 MacOSError::check(SecTrustSetAnchorCertificates(mTrust
, cfEmptyArray())); // no anchors
567 MacOSError::check(SecTrustSetKeychains(mTrust
, cfEmptyArray())); // no keychains
568 CSSM_APPLE_TP_ACTION_DATA actionData
= {
569 CSSM_APPLE_TP_ACTION_VERSION
, // version of data structure
570 CSSM_TP_ACTION_IMPLICIT_ANCHORS
// action flags
573 for (;;) { // at most twice
574 MacOSError::check(SecTrustSetParameters(mTrust
,
575 CSSM_TP_ACTION_DEFAULT
, CFTempData(&actionData
, sizeof(actionData
))));
577 // evaluate trust and extract results
578 SecTrustResultType trustResult
;
579 MacOSError::check(SecTrustEvaluate(mTrust
, &trustResult
));
580 MacOSError::check(SecTrustGetResult(mTrust
, &trustResult
, &mCertChain
.aref(), &mEvalDetails
));
582 // if this is an Apple developer cert....
583 if (teamID() && SecStaticCode::isAppleDeveloperCert(mCertChain
)) {
584 CFRef
<CFStringRef
> teamIDFromCert
;
585 if (CFArrayGetCount(mCertChain
) > 0) {
586 /* Note that SecCertificateCopySubjectComponent sets the out paramater to NULL if there is no field present */
587 MacOSError::check(SecCertificateCopySubjectComponent((SecCertificateRef
)CFArrayGetValueAtIndex(mCertChain
, Requirement::leafCert
),
588 &CSSMOID_OrganizationalUnitName
,
589 &teamIDFromCert
.aref()));
591 if (teamIDFromCert
) {
592 CFRef
<CFStringRef
> teamIDFromCD
= CFStringCreateWithCString(NULL
, teamID(), kCFStringEncodingUTF8
);
594 MacOSError::throwMe(errSecCSInternalError
);
597 if (CFStringCompare(teamIDFromCert
, teamIDFromCD
, 0) != kCFCompareEqualTo
) {
598 Security::Syslog::error("Team identifier in the signing certificate (%s) does not match the team identifier (%s) in the code directory", cfString(teamIDFromCert
).c_str(), teamID());
599 MacOSError::throwMe(errSecCSSignatureInvalid
);
605 CODESIGN_EVAL_STATIC_SIGNATURE_RESULT(this, trustResult
, mCertChain
? (int)CFArrayGetCount(mCertChain
) : 0);
606 switch (trustResult
) {
607 case kSecTrustResultProceed
:
608 case kSecTrustResultUnspecified
:
610 case kSecTrustResultDeny
:
611 MacOSError::throwMe(CSSMERR_APPLETP_TRUST_SETTING_DENY
); // user reject
612 case kSecTrustResultInvalid
:
613 assert(false); // should never happen
614 MacOSError::throwMe(CSSMERR_TP_NOT_TRUSTED
);
618 MacOSError::check(SecTrustGetCssmResultCode(mTrust
, &result
));
619 // if we have a valid timestamp, CMS validates against (that) signing time and all is well.
620 // If we don't have one, may validate against *now*, and must be able to tolerate expiration.
621 if (mSigningTimestamp
== 0) // no timestamp available
622 if (((result
== CSSMERR_TP_CERT_EXPIRED
) || (result
== CSSMERR_TP_CERT_NOT_VALID_YET
))
623 && !(actionData
.ActionFlags
& CSSM_TP_ACTION_ALLOW_EXPIRED
)) {
624 CODESIGN_EVAL_STATIC_SIGNATURE_EXPIRED(this);
625 actionData
.ActionFlags
|= CSSM_TP_ACTION_ALLOW_EXPIRED
; // (this also allows postdated certs)
626 continue; // retry validation while tolerating expiration
628 MacOSError::throwMe(result
);
632 if (mSigningTimestamp
) {
633 CFIndex rootix
= CFArrayGetCount(mCertChain
);
634 if (SecCertificateRef mainRoot
= SecCertificateRef(CFArrayGetValueAtIndex(mCertChain
, rootix
-1)))
635 if (isAppleCA(mainRoot
)) {
636 // impose policy: if the signature itself draws to Apple, then so must the timestamp signature
637 CFRef
<CFArrayRef
> tsCerts
;
638 MacOSError::check(CMSDecoderCopySignerTimestampCertificates(cms
, 0, &tsCerts
.aref()));
639 CFIndex tsn
= CFArrayGetCount(tsCerts
);
640 bool good
= tsn
> 0 && isAppleCA(SecCertificateRef(CFArrayGetValueAtIndex(tsCerts
, tsn
-1)));
642 MacOSError::throwMe(CSSMERR_TP_NOT_TRUSTED
);
646 return actionData
.ActionFlags
& CSSM_TP_ACTION_ALLOW_EXPIRED
;
652 // Return the TP policy used for signature verification.
653 // This may be a simple SecPolicyRef or a CFArray of policies.
654 // The caller owns the return value.
656 static SecPolicyRef
makeCRLPolicy()
658 CFRef
<SecPolicyRef
> policy
;
659 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_REVOCATION_CRL
, &policy
.aref()));
660 CSSM_APPLE_TP_CRL_OPTIONS options
;
661 memset(&options
, 0, sizeof(options
));
662 options
.Version
= CSSM_APPLE_TP_CRL_OPTS_VERSION
;
663 options
.CrlFlags
= CSSM_TP_ACTION_FETCH_CRL_FROM_NET
| CSSM_TP_ACTION_CRL_SUFFICIENT
;
664 CSSM_DATA optData
= { sizeof(options
), (uint8
*)&options
};
665 MacOSError::check(SecPolicySetValue(policy
, &optData
));
666 return policy
.yield();
669 static SecPolicyRef
makeOCSPPolicy()
671 CFRef
<SecPolicyRef
> policy
;
672 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_REVOCATION_OCSP
, &policy
.aref()));
673 CSSM_APPLE_TP_OCSP_OPTIONS options
;
674 memset(&options
, 0, sizeof(options
));
675 options
.Version
= CSSM_APPLE_TP_OCSP_OPTS_VERSION
;
676 options
.Flags
= CSSM_TP_ACTION_OCSP_SUFFICIENT
;
677 CSSM_DATA optData
= { sizeof(options
), (uint8
*)&options
};
678 MacOSError::check(SecPolicySetValue(policy
, &optData
));
679 return policy
.yield();
682 CFArrayRef
SecStaticCode::verificationPolicies()
684 CFRef
<SecPolicyRef
> core
;
685 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3
,
686 &CSSMOID_APPLE_TP_CODE_SIGNING
, &core
.aref()));
687 if (mValidationFlags
& kSecCSNoNetworkAccess
) {
688 // Skips all revocation since they require network connectivity
689 // therefore annihilates kSecCSEnforceRevocationChecks if present
690 CFRef
<SecPolicyRef
> no_revoc
= SecPolicyCreateRevocation(kSecRevocationNetworkAccessDisabled
);
691 return makeCFArray(2, core
.get(), no_revoc
.get());
693 else if (mValidationFlags
& kSecCSEnforceRevocationChecks
) {
694 // Add CRL and OCSPPolicies
695 CFRef
<SecPolicyRef
> crl
= makeCRLPolicy();
696 CFRef
<SecPolicyRef
> ocsp
= makeOCSPPolicy();
697 return makeCFArray(3, core
.get(), crl
.get(), ocsp
.get());
699 return makeCFArray(1, core
.get());
705 // Validate a particular sealed, cached resource against its (special) CodeDirectory slot.
706 // The resource must already have been placed in the cache.
707 // This does NOT perform basic validation.
709 void SecStaticCode::validateComponent(CodeDirectory::SpecialSlot slot
, OSStatus fail
/* = errSecCSSignatureFailed */)
711 assert(slot
<= cdSlotMax
);
712 CFDataRef data
= mCache
[slot
];
713 assert(data
); // must be cached
714 if (data
== CFDataRef(kCFNull
)) {
715 if (codeDirectory()->slotIsPresent(-slot
)) // was supposed to be there...
716 MacOSError::throwMe(fail
); // ... and is missing
718 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data
), CFDataGetLength(data
), -slot
))
719 MacOSError::throwMe(fail
);
725 // Perform static validation of the main executable.
726 // This reads the main executable from disk and validates it against the
727 // CodeDirectory code slot array.
728 // Note that this is NOT an in-memory validation, and is thus potentially
729 // subject to timing attacks.
731 void SecStaticCode::validateExecutable()
733 if (!validatedExecutable()) {
735 DTRACK(CODESIGN_EVAL_STATIC_EXECUTABLE
, this,
736 (char*)this->mainExecutablePath().c_str(), codeDirectory()->nCodeSlots
);
737 const CodeDirectory
*cd
= this->codeDirectory();
739 MacOSError::throwMe(errSecCSUnsigned
);
740 AutoFileDesc
fd(mainExecutablePath(), O_RDONLY
);
741 fd
.fcntl(F_NOCACHE
, true); // turn off page caching (one-pass)
742 if (Universal
*fat
= mRep
->mainExecutableImage())
743 fd
.seek(fat
->archOffset());
744 size_t pageSize
= cd
->pageSize
? (1 << cd
->pageSize
) : 0;
745 size_t remaining
= cd
->codeLimit
;
746 for (uint32_t slot
= 0; slot
< cd
->nCodeSlots
; ++slot
) {
747 size_t size
= min(remaining
, pageSize
);
748 if (!cd
->validateSlot(fd
, size
, slot
)) {
749 CODESIGN_EVAL_STATIC_EXECUTABLE_FAIL(this, (int)slot
);
750 MacOSError::throwMe(errSecCSSignatureFailed
);
754 mExecutableValidated
= true;
755 mExecutableValidResult
= errSecSuccess
;
756 } catch (const CommonError
&err
) {
757 mExecutableValidated
= true;
758 mExecutableValidResult
= err
.osStatus();
761 secdebug("staticCode", "%p executable validation threw non-common exception", this);
762 mExecutableValidated
= true;
763 mExecutableValidResult
= errSecCSInternalError
;
767 assert(validatedExecutable());
768 if (mExecutableValidResult
!= errSecSuccess
)
769 MacOSError::throwMe(mExecutableValidResult
);
774 // Perform static validation of sealed resources and nested code.
776 // This performs a whole-code static resource scan and effectively
777 // computes a concordance between what's on disk and what's in the ResourceDirectory.
778 // Any unsanctioned difference causes an error.
780 unsigned SecStaticCode::estimateResourceWorkload()
782 // workload estimate = number of sealed files
783 CFDictionaryRef sealedResources
= resourceDictionary();
784 CFDictionaryRef files
= cfget
<CFDictionaryRef
>(sealedResources
, "files2");
786 files
= cfget
<CFDictionaryRef
>(sealedResources
, "files");
787 return files
? unsigned(CFDictionaryGetCount(files
)) : 0;
790 void SecStaticCode::validateResources(SecCSFlags flags
)
792 // do we have a superset of this requested validation cached?
794 if (mResourcesValidated
) { // have cached outcome
795 if (!(flags
& kSecCSCheckNestedCode
) || mResourcesDeep
) // was deep or need no deep scan
800 if (mLimitedAsync
== NULL
) {
801 mLimitedAsync
= new LimitedAsync(diskRep()->fd().mediumType() == kIOPropertyMediumTypeSolidStateKey
);
806 CFDictionaryRef sealedResources
= resourceDictionary();
807 if (this->resourceBase()) // disk has resources
809 /* go to work below */;
811 MacOSError::throwMe(errSecCSResourcesNotFound
);
812 else // disk has no resources
814 MacOSError::throwMe(errSecCSResourcesNotFound
);
816 return; // no resources, not sealed - fine (no work)
818 // found resources, and they are sealed
819 DTRACK(CODESIGN_EVAL_STATIC_RESOURCES
, this,
820 (char*)this->mainExecutablePath().c_str(), 0);
822 // scan through the resources on disk, checking each against the resourceDirectory
823 if (mValidationFlags
& kSecCSFullReport
)
824 mResourcesValidContext
= new CollectingContext(*this); // collect all failures in here
826 mResourcesValidContext
= new ValidationContext(*this); // simple bug-out on first error
828 // use V2 resource seal if available, otherwise fall back to V1
829 CFDictionaryRef rules
;
830 CFDictionaryRef files
;
832 if (CFDictionaryGetValue(sealedResources
, CFSTR("files2"))) { // have V2 signature
833 rules
= cfget
<CFDictionaryRef
>(sealedResources
, "rules2");
834 files
= cfget
<CFDictionaryRef
>(sealedResources
, "files2");
836 } else { // only V1 available
837 rules
= cfget
<CFDictionaryRef
>(sealedResources
, "rules");
838 files
= cfget
<CFDictionaryRef
>(sealedResources
, "files");
841 if (!rules
|| !files
)
842 MacOSError::throwMe(errSecCSResourcesInvalid
);
844 // check for weak resource rules
845 bool strict
= flags
& kSecCSStrictValidate
;
847 if (hasWeakResourceRules(rules
, version
, mAllowOmissions
))
848 if (mTolerateErrors
.find(errSecCSWeakResourceRules
) == mTolerateErrors
.end())
849 MacOSError::throwMe(errSecCSWeakResourceRules
);
851 if (mTolerateErrors
.find(errSecCSWeakResourceEnvelope
) == mTolerateErrors
.end())
852 MacOSError::throwMe(errSecCSWeakResourceEnvelope
);
855 Dispatch::Group group
;
856 Dispatch::Group
&groupRef
= group
; // (into block)
858 // scan through the resources on disk, checking each against the resourceDirectory
859 __block CFRef
<CFMutableDictionaryRef
> resourceMap
= makeCFMutableDictionary(files
);
860 string base
= cfString(this->resourceBase());
861 ResourceBuilder
resources(base
, base
, rules
, codeDirectory()->hashType
, strict
, mTolerateErrors
);
862 diskRep()->adjustResources(resources
);
864 resources
.scan(^(FTSENT
*ent
, uint32_t ruleFlags
, const string relpath
, ResourceBuilder::Rule
*rule
) {
865 CFDictionaryRemoveValue(resourceMap
, CFTempString(relpath
));
866 bool isSymlink
= (ent
->fts_info
== FTS_SL
);
868 void (^validate
)() = ^{
869 validateResource(files
, relpath
, isSymlink
, *mResourcesValidContext
, flags
, version
);
873 mLimitedAsync
->perform(groupRef
, validate
);
875 group
.wait(); // wait until all async resources have been validated as well
877 unsigned leftovers
= unsigned(CFDictionaryGetCount(resourceMap
));
879 secdebug("staticCode", "%d sealed resource(s) not found in code", int(leftovers
));
880 CFDictionaryApplyFunction(resourceMap
, SecStaticCode::checkOptionalResource
, mResourcesValidContext
);
883 // now check for any errors found in the reporting context
884 mResourcesValidated
= true;
885 mResourcesDeep
= flags
& kSecCSCheckNestedCode
;
886 if (mResourcesValidContext
->osStatus() != errSecSuccess
)
887 mResourcesValidContext
->throwMe();
888 } catch (const CommonError
&err
) {
889 mResourcesValidated
= true;
890 mResourcesDeep
= flags
& kSecCSCheckNestedCode
;
891 mResourcesValidResult
= err
.osStatus();
894 secdebug("staticCode", "%p executable validation threw non-common exception", this);
895 mResourcesValidated
= true;
896 mResourcesDeep
= flags
& kSecCSCheckNestedCode
;
897 mResourcesValidResult
= errSecCSInternalError
;
901 assert(validatedResources());
902 if (mResourcesValidResult
)
903 MacOSError::throwMe(mResourcesValidResult
);
904 if (mResourcesValidContext
->osStatus() != errSecSuccess
)
905 mResourcesValidContext
->throwMe();
909 void SecStaticCode::checkOptionalResource(CFTypeRef key
, CFTypeRef value
, void *context
)
911 ValidationContext
*ctx
= static_cast<ValidationContext
*>(context
);
912 ResourceSeal
seal(value
);
913 if (!seal
.optional()) {
914 if (key
&& CFGetTypeID(key
) == CFStringGetTypeID()) {
915 CFTempURL
tempURL(CFStringRef(key
), false, ctx
->code
.resourceBase());
916 if (!tempURL
.get()) {
917 ctx
->reportProblem(errSecCSBadDictionaryFormat
, kSecCFErrorResourceSeal
, key
);
919 ctx
->reportProblem(errSecCSBadResource
, kSecCFErrorResourceMissing
, tempURL
);
922 ctx
->reportProblem(errSecCSBadResource
, kSecCFErrorResourceSeal
, key
);
928 static bool isOmitRule(CFTypeRef value
)
930 if (CFGetTypeID(value
) == CFBooleanGetTypeID())
931 return value
== kCFBooleanFalse
;
932 CFDictionary
rule(value
, errSecCSResourceRulesInvalid
);
933 return rule
.get
<CFBooleanRef
>("omit") == kCFBooleanTrue
;
936 bool SecStaticCode::hasWeakResourceRules(CFDictionaryRef rulesDict
, uint32_t version
, CFArrayRef allowedOmissions
)
938 // compute allowed omissions
939 CFRef
<CFArrayRef
> defaultOmissions
= this->diskRep()->allowedResourceOmissions();
940 if (!defaultOmissions
)
941 MacOSError::throwMe(errSecCSInternalError
);
942 CFRef
<CFMutableArrayRef
> allowed
= CFArrayCreateMutableCopy(NULL
, 0, defaultOmissions
);
943 if (allowedOmissions
)
944 CFArrayAppendArray(allowed
, allowedOmissions
, CFRangeMake(0, CFArrayGetCount(allowedOmissions
)));
945 CFRange range
= CFRangeMake(0, CFArrayGetCount(allowed
));
947 // check all resource rules for weakness
948 string catchAllRule
= (version
== 1) ? "^Resources/" : "^.*";
949 __block
bool coversAll
= false;
950 __block
bool forbiddenOmission
= false;
951 CFArrayRef allowedRef
= allowed
.get(); // (into block)
952 CFDictionary
rules(rulesDict
, errSecCSResourceRulesInvalid
);
953 rules
.apply(^(CFStringRef key
, CFTypeRef value
) {
954 string pattern
= cfString(key
, errSecCSResourceRulesInvalid
);
955 if (pattern
== catchAllRule
&& value
== kCFBooleanTrue
) {
959 if (isOmitRule(value
))
960 forbiddenOmission
|= !CFArrayContainsValue(allowedRef
, range
, key
);
963 return !coversAll
|| forbiddenOmission
;
968 // Load, validate, cache, and return CFDictionary forms of sealed resources.
970 CFDictionaryRef
SecStaticCode::infoDictionary()
973 mInfoDict
.take(getDictionary(cdInfoSlot
, errSecCSInfoPlistFailed
));
974 secdebug("staticCode", "%p loaded InfoDict %p", this, mInfoDict
.get());
979 CFDictionaryRef
SecStaticCode::entitlements()
981 if (!mEntitlements
) {
983 if (CFDataRef entitlementData
= component(cdEntitlementSlot
)) {
984 validateComponent(cdEntitlementSlot
);
985 const EntitlementBlob
*blob
= reinterpret_cast<const EntitlementBlob
*>(CFDataGetBytePtr(entitlementData
));
986 if (blob
->validateBlob()) {
987 mEntitlements
.take(blob
->entitlements());
988 secdebug("staticCode", "%p loaded Entitlements %p", this, mEntitlements
.get());
990 // we do not consider a different blob type to be an error. We think it's a new format we don't understand
993 return mEntitlements
;
996 CFDictionaryRef
SecStaticCode::resourceDictionary(bool check
/* = true */)
998 if (mResourceDict
) // cached
999 return mResourceDict
;
1000 if (CFRef
<CFDictionaryRef
> dict
= getDictionary(cdResourceDirSlot
, check
))
1001 if (cfscan(dict
, "{rules=%Dn,files=%Dn}")) {
1002 secdebug("staticCode", "%p loaded ResourceDict %p",
1003 this, mResourceDict
.get());
1004 return mResourceDict
= dict
;
1012 // Load and cache the resource directory base.
1013 // Note that the base is optional for each DiskRep.
1015 CFURLRef
SecStaticCode::resourceBase()
1017 if (!mGotResourceBase
) {
1018 string base
= mRep
->resourcesRootPath();
1020 mResourceBase
.take(makeCFURL(base
, true));
1021 mGotResourceBase
= true;
1023 return mResourceBase
;
1028 // Load a component, validate it, convert it to a CFDictionary, and return that.
1029 // This will force load and validation, which means that it will perform basic
1030 // validation if it hasn't been done yet.
1032 CFDictionaryRef
SecStaticCode::getDictionary(CodeDirectory::SpecialSlot slot
, bool check
/* = true */)
1035 validateDirectory();
1036 if (CFDataRef infoData
= component(slot
)) {
1037 validateComponent(slot
);
1038 if (CFDictionaryRef dict
= makeCFDictionaryFrom(infoData
))
1041 MacOSError::throwMe(errSecCSBadDictionaryFormat
);
1048 // Load, validate, and return a sealed resource.
1049 // The resource data (loaded in to memory as a blob) is returned and becomes
1050 // the responsibility of the caller; it is NOT cached by SecStaticCode.
1052 // A resource that is not sealed will not be returned, and an error will be thrown.
1053 // A missing resource will cause an error unless it's marked optional in the Directory.
1054 // Under no circumstances will a corrupt resource be returned.
1055 // NULL will only be returned for a resource that is neither sealed nor present
1056 // (or that is sealed, absent, and marked optional).
1057 // If the ResourceDictionary itself is not sealed, this function will always fail.
1059 // There is currently no interface for partial retrieval of the resource data.
1060 // (Since the ResourceDirectory does not currently support segmentation, all the
1061 // data would have to be read anyway, but it could be read into a reusable buffer.)
1063 CFDataRef
SecStaticCode::resource(string path
, ValidationContext
&ctx
)
1065 if (CFDictionaryRef rdict
= resourceDictionary()) {
1066 if (CFTypeRef file
= cfget(rdict
, "files.%s", path
.c_str())) {
1067 ResourceSeal seal
= file
;
1068 if (!resourceBase()) // no resources in DiskRep
1069 MacOSError::throwMe(errSecCSResourcesNotFound
);
1071 MacOSError::throwMe(errSecCSResourcesNotSealed
); // (it's nested code)
1072 CFRef
<CFURLRef
> fullpath
= makeCFURL(path
, false, resourceBase());
1073 if (CFRef
<CFDataRef
> data
= cfLoadFile(fullpath
)) {
1074 MakeHash
<CodeDirectory
> hasher(this->codeDirectory());
1075 hasher
->update(CFDataGetBytePtr(data
), CFDataGetLength(data
));
1076 if (hasher
->verify(seal
.hash()))
1077 return data
.yield(); // good
1079 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // altered
1081 if (!seal
.optional())
1082 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceMissing
, fullpath
); // was sealed but is now missing
1084 return NULL
; // validly missing
1087 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAdded
, CFTempURL(path
, false, resourceBase()));
1090 MacOSError::throwMe(errSecCSResourcesNotSealed
);
1093 CFDataRef
SecStaticCode::resource(string path
)
1095 ValidationContext
ctx(*this);
1096 return resource(path
, ctx
);
1099 void SecStaticCode::validateResource(CFDictionaryRef files
, string path
, bool isSymlink
, ValidationContext
&ctx
, SecCSFlags flags
, uint32_t version
)
1101 if (!resourceBase()) // no resources in DiskRep
1102 MacOSError::throwMe(errSecCSResourcesNotFound
);
1103 CFRef
<CFURLRef
> fullpath
= makeCFURL(path
, false, resourceBase());
1104 if (CFTypeRef file
= CFDictionaryGetValue(files
, CFTempString(path
))) {
1105 ResourceSeal seal
= file
;
1106 if (seal
.nested()) {
1108 return ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
1109 string suffix
= ".framework";
1110 bool isFramework
= (path
.length() > suffix
.length())
1111 && (path
.compare(path
.length()-suffix
.length(), suffix
.length(), suffix
) == 0);
1112 validateNestedCode(fullpath
, seal
, flags
, isFramework
);
1113 } else if (seal
.link()) {
1114 char target
[PATH_MAX
];
1115 ssize_t len
= ::readlink(cfString(fullpath
).c_str(), target
, sizeof(target
)-1);
1117 UnixError::check(-1);
1119 if (cfString(seal
.link()) != target
)
1120 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
);
1121 } else if (seal
.hash()) { // genuine file
1122 AutoFileDesc
fd(cfString(fullpath
), O_RDONLY
, FileDesc::modeMissingOk
); // open optional file
1124 MakeHash
<CodeDirectory
> hasher(this->codeDirectory());
1125 hashFileData(fd
, hasher
.get());
1126 if (hasher
->verify(seal
.hash()))
1127 return; // verify good
1129 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // altered
1131 if (!seal
.optional())
1132 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceMissing
, fullpath
); // was sealed but is now missing
1134 return; // validly missing
1137 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
1140 if (version
== 1) { // version 1 ignores symlinks altogether
1141 char target
[PATH_MAX
];
1142 if (::readlink(cfString(fullpath
).c_str(), target
, sizeof(target
)) > 0)
1145 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAdded
, CFTempURL(path
, false, resourceBase()));
1148 void SecStaticCode::validateNestedCode(CFURLRef path
, const ResourceSeal
&seal
, SecCSFlags flags
, bool isFramework
)
1150 CFRef
<SecRequirementRef
> req
;
1151 if (SecRequirementCreateWithString(seal
.requirement(), kSecCSDefaultFlags
, &req
.aref()))
1152 MacOSError::throwMe(errSecCSResourcesInvalid
);
1154 // recursively verify this nested code
1156 if (!(flags
& kSecCSCheckNestedCode
))
1157 flags
|= kSecCSBasicValidateOnly
;
1158 SecPointer
<SecStaticCode
> code
= new SecStaticCode(DiskRep::bestGuess(cfString(path
)));
1159 code
->initializeFromParent(*this);
1160 code
->staticValidate(flags
, SecRequirement::required(req
));
1162 if (isFramework
&& (flags
& kSecCSStrictValidate
))
1164 validateOtherVersions(path
, flags
, req
, code
);
1165 } catch (const CSError
&err
) {
1166 MacOSError::throwMe(errSecCSBadFrameworkVersion
);
1167 } catch (const MacOSError
&err
) {
1168 MacOSError::throwMe(errSecCSBadFrameworkVersion
);
1171 } catch (CSError
&err
) {
1172 if (err
.error
== errSecCSReqFailed
) {
1173 mResourcesValidContext
->reportProblem(errSecCSBadNestedCode
, kSecCFErrorResourceAltered
, path
);
1176 err
.augment(kSecCFErrorPath
, path
);
1178 } catch (const MacOSError
&err
) {
1179 if (err
.error
== errSecCSReqFailed
) {
1180 mResourcesValidContext
->reportProblem(errSecCSBadNestedCode
, kSecCFErrorResourceAltered
, path
);
1183 CSError::throwMe(err
.error
, kSecCFErrorPath
, path
);
1187 void SecStaticCode::validateOtherVersions(CFURLRef path
, SecCSFlags flags
, SecRequirementRef req
, SecStaticCode
*code
)
1189 // Find out what current points to and do not revalidate
1190 std::string mainPath
= cfStringRelease(code
->diskRep()->copyCanonicalPath());
1192 char main_path
[PATH_MAX
];
1193 bool foundTarget
= false;
1195 /* If it failed to get the target of the symlink, do not fail. It is a performance loss,
1196 not a security hole */
1197 if (realpath(mainPath
.c_str(), main_path
) != NULL
)
1200 std::ostringstream versionsPath
;
1201 versionsPath
<< cfString(path
) << "/Versions/";
1203 DirScanner
scanner(versionsPath
.str());
1205 if (scanner
.initialized()) {
1206 struct dirent
*entry
= NULL
;
1207 while ((entry
= scanner
.getNext()) != NULL
) {
1208 std::ostringstream fullPath
;
1210 if (entry
->d_type
!= DT_DIR
||
1211 strcmp(entry
->d_name
, ".") == 0 ||
1212 strcmp(entry
->d_name
, "..") == 0 ||
1213 strcmp(entry
->d_name
, "Current") == 0)
1216 fullPath
<< versionsPath
.str() << entry
->d_name
;
1218 char real_full_path
[PATH_MAX
];
1219 if (realpath(fullPath
.str().c_str(), real_full_path
) == NULL
)
1220 UnixError::check(-1);
1222 // Do case insensitive comparions because realpath() was called for both paths
1223 if (foundTarget
&& strcmp(main_path
, real_full_path
) == 0)
1226 SecPointer
<SecStaticCode
> frameworkVersion
= new SecStaticCode(DiskRep::bestGuess(real_full_path
));
1227 frameworkVersion
->initializeFromParent(*this);
1228 frameworkVersion
->staticValidate(flags
, SecRequirement::required(req
));
1235 // Test a CodeDirectory flag.
1236 // Returns false if there is no CodeDirectory.
1237 // May throw if the CodeDirectory is present but somehow invalid.
1239 bool SecStaticCode::flag(uint32_t tested
)
1241 if (const CodeDirectory
*cd
= this->codeDirectory(false))
1242 return cd
->flags
& tested
;
1249 // Retrieve the full SuperBlob containing all internal requirements.
1251 const Requirements
*SecStaticCode::internalRequirements()
1253 if (CFDataRef reqData
= component(cdRequirementsSlot
)) {
1254 const Requirements
*req
= (const Requirements
*)CFDataGetBytePtr(reqData
);
1255 if (!req
->validateBlob())
1256 MacOSError::throwMe(errSecCSReqInvalid
);
1264 // Retrieve a particular internal requirement by type.
1266 const Requirement
*SecStaticCode::internalRequirement(SecRequirementType type
)
1268 if (const Requirements
*reqs
= internalRequirements())
1269 return reqs
->find
<Requirement
>(type
);
1276 // Return the Designated Requirement (DR). This can be either explicit in the
1277 // Internal Requirements component, or implicitly generated on demand here.
1278 // Note that an explicit DR may have been implicitly generated at signing time;
1279 // we don't distinguish this case.
1281 const Requirement
*SecStaticCode::designatedRequirement()
1283 if (const Requirement
*req
= internalRequirement(kSecDesignatedRequirementType
)) {
1284 return req
; // explicit in signing data
1286 if (!mDesignatedReq
)
1287 mDesignatedReq
= defaultDesignatedRequirement();
1288 return mDesignatedReq
;
1294 // Generate the default Designated Requirement (DR) for this StaticCode.
1295 // Ignore any explicit DR it may contain.
1297 const Requirement
*SecStaticCode::defaultDesignatedRequirement()
1299 if (flag(kSecCodeSignatureAdhoc
)) {
1300 // adhoc signature: return a cdhash requirement for all architectures
1301 __block
Requirement::Maker maker
;
1302 Requirement::Maker::Chain
chain(maker
, opOr
);
1304 // insert cdhash requirement for all architectures
1306 maker
.cdhash(this->cdHash());
1307 handleOtherArchitectures(^(SecStaticCode
*subcode
) {
1308 if (CFDataRef cdhash
= subcode
->cdHash()) {
1310 maker
.cdhash(cdhash
);
1313 return maker
.make();
1315 // full signature: Gin up full context and let DRMaker do its thing
1316 validateDirectory(); // need the cert chain
1317 Requirement::Context
context(this->certificates(),
1318 this->infoDictionary(),
1319 this->entitlements(),
1321 this->codeDirectory()
1323 return DRMaker(context
).make();
1329 // Validate a SecStaticCode against the internal requirement of a particular type.
1331 void SecStaticCode::validateRequirements(SecRequirementType type
, SecStaticCode
*target
,
1332 OSStatus nullError
/* = errSecSuccess */)
1334 DTRACK(CODESIGN_EVAL_STATIC_INTREQ
, this, type
, target
, nullError
);
1335 if (const Requirement
*req
= internalRequirement(type
))
1336 target
->validateRequirement(req
, nullError
? nullError
: errSecCSReqFailed
);
1338 MacOSError::throwMe(nullError
);
1345 // Validate this StaticCode against an external Requirement
1347 bool SecStaticCode::satisfiesRequirement(const Requirement
*req
, OSStatus failure
)
1350 validateDirectory();
1351 return req
->validates(Requirement::Context(mCertChain
, infoDictionary(), entitlements(), codeDirectory()->identifier(), codeDirectory()), failure
);
1354 void SecStaticCode::validateRequirement(const Requirement
*req
, OSStatus failure
)
1356 if (!this->satisfiesRequirement(req
, failure
))
1357 MacOSError::throwMe(failure
);
1362 // Retrieve one certificate from the cert chain.
1363 // Positive and negative indices can be used:
1364 // [ leaf, intermed-1, ..., intermed-n, anchor ]
1366 // Returns NULL if unavailable for any reason.
1368 SecCertificateRef
SecStaticCode::cert(int ix
)
1370 validateDirectory(); // need cert chain
1372 CFIndex length
= CFArrayGetCount(mCertChain
);
1375 if (ix
>= 0 && ix
< length
)
1376 return SecCertificateRef(CFArrayGetValueAtIndex(mCertChain
, ix
));
1381 CFArrayRef
SecStaticCode::certificates()
1383 validateDirectory(); // need cert chain
1389 // Gather (mostly) API-official information about this StaticCode.
1391 // This method lives in the twilight between the API and internal layers,
1392 // since it generates API objects (Sec*Refs) for return.
1394 CFDictionaryRef
SecStaticCode::signingInformation(SecCSFlags flags
)
1397 // Start with the pieces that we return even for unsigned code.
1398 // This makes Sec[Static]CodeRefs useful as API-level replacements
1399 // of our internal OSXCode objects.
1401 CFRef
<CFMutableDictionaryRef
> dict
= makeCFMutableDictionary(1,
1402 kSecCodeInfoMainExecutable
, CFTempURL(this->mainExecutablePath()).get()
1406 // If we're not signed, this is all you get
1408 if (!this->isSigned())
1409 return dict
.yield();
1412 // Add the generic attributes that we always include
1414 CFDictionaryAddValue(dict
, kSecCodeInfoIdentifier
, CFTempString(this->identifier()));
1415 CFDictionaryAddValue(dict
, kSecCodeInfoFlags
, CFTempNumber(this->codeDirectory(false)->flags
.get()));
1416 CFDictionaryAddValue(dict
, kSecCodeInfoFormat
, CFTempString(this->format()));
1417 CFDictionaryAddValue(dict
, kSecCodeInfoSource
, CFTempString(this->signatureSource()));
1418 CFDictionaryAddValue(dict
, kSecCodeInfoUnique
, this->cdHash());
1419 CFDictionaryAddValue(dict
, kSecCodeInfoDigestAlgorithm
, CFTempNumber(this->codeDirectory(false)->hashType
));
1422 // Deliver any Info.plist only if it looks intact
1425 if (CFDictionaryRef info
= this->infoDictionary())
1426 CFDictionaryAddValue(dict
, kSecCodeInfoPList
, info
);
1427 } catch (...) { } // don't deliver Info.plist if questionable
1430 // kSecCSSigningInformation adds information about signing certificates and chains
1432 if (flags
& kSecCSSigningInformation
)
1434 if (CFArrayRef certs
= this->certificates())
1435 CFDictionaryAddValue(dict
, kSecCodeInfoCertificates
, certs
);
1436 if (CFDataRef sig
= this->signature())
1437 CFDictionaryAddValue(dict
, kSecCodeInfoCMS
, sig
);
1439 CFDictionaryAddValue(dict
, kSecCodeInfoTrust
, mTrust
);
1440 if (CFAbsoluteTime time
= this->signingTime())
1441 if (CFRef
<CFDateRef
> date
= CFDateCreate(NULL
, time
))
1442 CFDictionaryAddValue(dict
, kSecCodeInfoTime
, date
);
1443 if (CFAbsoluteTime time
= this->signingTimestamp())
1444 if (CFRef
<CFDateRef
> date
= CFDateCreate(NULL
, time
))
1445 CFDictionaryAddValue(dict
, kSecCodeInfoTimestamp
, date
);
1446 if (const char *teamID
= this->teamID())
1447 CFDictionaryAddValue(dict
, kSecCodeInfoTeamIdentifier
, CFTempString(teamID
));
1451 // kSecCSRequirementInformation adds information on requirements
1453 if (flags
& kSecCSRequirementInformation
)
1455 if (const Requirements
*reqs
= this->internalRequirements()) {
1456 CFDictionaryAddValue(dict
, kSecCodeInfoRequirements
,
1457 CFTempString(Dumper::dump(reqs
)));
1458 CFDictionaryAddValue(dict
, kSecCodeInfoRequirementData
, CFTempData(*reqs
));
1461 const Requirement
*dreq
= this->designatedRequirement();
1462 CFRef
<SecRequirementRef
> dreqRef
= (new SecRequirement(dreq
))->handle();
1463 CFDictionaryAddValue(dict
, kSecCodeInfoDesignatedRequirement
, dreqRef
);
1464 if (this->internalRequirement(kSecDesignatedRequirementType
)) { // explicit
1465 CFRef
<SecRequirementRef
> ddreqRef
= (new SecRequirement(this->defaultDesignatedRequirement(), true))->handle();
1466 CFDictionaryAddValue(dict
, kSecCodeInfoImplicitDesignatedRequirement
, ddreqRef
);
1467 } else { // implicit
1468 CFDictionaryAddValue(dict
, kSecCodeInfoImplicitDesignatedRequirement
, dreqRef
);
1473 if (CFDataRef ent
= this->component(cdEntitlementSlot
)) {
1474 CFDictionaryAddValue(dict
, kSecCodeInfoEntitlements
, ent
);
1475 if (CFDictionaryRef entdict
= this->entitlements())
1476 CFDictionaryAddValue(dict
, kSecCodeInfoEntitlementsDict
, entdict
);
1481 // kSecCSInternalInformation adds internal information meant to be for Apple internal
1482 // use (SPI), and not guaranteed to be stable. Primarily, this is data we want
1483 // to reliably transmit through the API wall so that code outside the Security.framework
1484 // can use it without having to play nasty tricks to get it.
1486 if (flags
& kSecCSInternalInformation
)
1489 CFDictionaryAddValue(dict
, kSecCodeInfoCodeDirectory
, mDir
);
1490 CFDictionaryAddValue(dict
, kSecCodeInfoCodeOffset
, CFTempNumber(mRep
->signingBase()));
1491 if (CFRef
<CFDictionaryRef
> rdict
= getDictionary(cdResourceDirSlot
, false)) // suppress validation
1492 CFDictionaryAddValue(dict
, kSecCodeInfoResourceDirectory
, rdict
);
1497 // kSecCSContentInformation adds more information about the physical layout
1498 // of the signed code. This is (only) useful for packaging or patching-oriented
1501 if (flags
& kSecCSContentInformation
)
1502 if (CFRef
<CFArrayRef
> files
= mRep
->modifiedFiles())
1503 CFDictionaryAddValue(dict
, kSecCodeInfoChangedFiles
, files
);
1505 return dict
.yield();
1510 // Resource validation contexts.
1511 // The default context simply throws a CSError, rudely terminating the operation.
1513 SecStaticCode::ValidationContext::~ValidationContext()
1516 void SecStaticCode::ValidationContext::reportProblem(OSStatus rc
, CFStringRef type
, CFTypeRef value
)
1518 CSError::throwMe(rc
, type
, value
);
1521 void SecStaticCode::CollectingContext::reportProblem(OSStatus rc
, CFStringRef type
, CFTypeRef value
)
1523 StLock
<Mutex
> _(mLock
);
1524 if (mStatus
== errSecSuccess
)
1525 mStatus
= rc
; // record first failure for eventual error return
1528 mCollection
.take(makeCFMutableDictionary());
1529 CFMutableArrayRef element
= CFMutableArrayRef(CFDictionaryGetValue(mCollection
, type
));
1531 element
= makeCFMutableArray(0);
1534 CFDictionaryAddValue(mCollection
, type
, element
);
1537 CFArrayAppendValue(element
, value
);
1541 void SecStaticCode::CollectingContext::throwMe()
1543 assert(mStatus
!= errSecSuccess
);
1544 throw CSError(mStatus
, mCollection
.retain());
1549 // Master validation driver.
1550 // This is the static validation (only) driver for the API.
1552 // SecStaticCode exposes an a la carte menu of topical validators applying
1553 // to a given object. The static validation API pulls them together reliably,
1554 // but it also adds two matrix dimensions: architecture (for "fat" Mach-O binaries)
1555 // and nested code. This function will crawl a suitable cross-section of this
1556 // validation matrix based on which options it is given, creating temporary
1557 // SecStaticCode objects on the fly to complete the task.
1558 // (The point, of course, is to do as little duplicate work as possible.)
1560 void SecStaticCode::staticValidate(SecCSFlags flags
, const SecRequirement
*req
)
1562 setValidationFlags(flags
);
1564 // initialize progress/cancellation state
1565 prepareProgress(estimateResourceWorkload() + 2); // +1 head, +1 tail
1567 // core components: once per architecture (if any)
1568 this->staticValidateCore(flags
, req
);
1569 if (flags
& kSecCSCheckAllArchitectures
)
1570 handleOtherArchitectures(^(SecStaticCode
* subcode
) {
1571 if (flags
& kSecCSCheckGatekeeperArchitectures
) {
1572 Universal
*fat
= subcode
->diskRep()->mainExecutableImage();
1573 assert(fat
&& fat
->narrowed()); // handleOtherArchitectures gave us a focused architecture slice
1574 Architecture arch
= fat
->bestNativeArch(); // actually, the ONLY one
1575 if ((arch
.cpuType() & ~CPU_ARCH_MASK
) == CPU_TYPE_POWERPC
)
1576 return; // irrelevant to Gatekeeper
1578 subcode
->detachedSignature(this->mDetachedSig
); // carry over explicit (but not implicit) architecture
1579 subcode
->staticValidateCore(flags
, req
);
1583 // allow monitor intervention in source validation phase
1584 reportEvent(CFSTR("prepared"), NULL
);
1586 // resources: once for all architectures
1587 if (!(flags
& kSecCSDoNotValidateResources
))
1588 this->validateResources(flags
);
1590 // perform strict validation if desired
1591 if (flags
& kSecCSStrictValidate
)
1592 mRep
->strictValidate(mTolerateErrors
);
1595 // allow monitor intervention
1596 if (CFRef
<CFTypeRef
> veto
= reportEvent(CFSTR("validated"), NULL
)) {
1597 if (CFGetTypeID(veto
) == CFNumberGetTypeID())
1598 MacOSError::throwMe(cfNumber
<OSStatus
>(veto
.as
<CFNumberRef
>()));
1600 MacOSError::throwMe(errSecCSBadCallbackValue
);
1604 void SecStaticCode::staticValidateCore(SecCSFlags flags
, const SecRequirement
*req
)
1607 this->validateNonResourceComponents(); // also validates the CodeDirectory
1608 if (!(flags
& kSecCSDoNotValidateExecutable
))
1609 this->validateExecutable();
1611 this->validateRequirement(req
->requirement(), errSecCSReqFailed
);
1612 } catch (CSError
&err
) {
1613 if (Universal
*fat
= this->diskRep()->mainExecutableImage()) // Mach-O
1614 if (MachO
*mach
= fat
->architecture()) {
1615 err
.augment(kSecCFErrorArchitecture
, CFTempString(mach
->architecture().displayName()));
1619 } catch (const MacOSError
&err
) {
1620 // add architecture information if we can get it
1621 if (Universal
*fat
= this->diskRep()->mainExecutableImage())
1622 if (MachO
*mach
= fat
->architecture()) {
1623 CFTempString
arch(mach
->architecture().displayName());
1625 CSError::throwMe(err
.error
, kSecCFErrorArchitecture
, arch
);
1633 // A helper that generates SecStaticCode objects for all but the primary architecture
1634 // of a fat binary and calls a block on them.
1635 // If there's only one architecture (or this is an architecture-agnostic code),
1636 // nothing happens quickly.
1638 void SecStaticCode::handleOtherArchitectures(void (^handle
)(SecStaticCode
* other
))
1640 if (Universal
*fat
= this->diskRep()->mainExecutableImage()) {
1641 Universal::Architectures architectures
;
1642 fat
->architectures(architectures
);
1643 if (architectures
.size() > 1) {
1644 DiskRep::Context ctx
;
1645 size_t activeOffset
= fat
->archOffset();
1646 for (Universal::Architectures::const_iterator arch
= architectures
.begin(); arch
!= architectures
.end(); ++arch
) {
1647 ctx
.offset
= fat
->archOffset(*arch
);
1648 if (ctx
.offset
> SIZE_MAX
)
1649 MacOSError::throwMe(errSecCSInternalError
);
1650 ctx
.size
= fat
->lengthOfSlice((size_t)ctx
.offset
);
1651 if (ctx
.offset
!= activeOffset
) { // inactive architecture; check it
1652 SecPointer
<SecStaticCode
> subcode
= new SecStaticCode(DiskRep::bestGuess(this->mainExecutablePath(), &ctx
));
1653 subcode
->detachedSignature(this->mDetachedSig
); // carry over explicit (but not implicit) detached signature
1654 if (this->teamID() == NULL
|| subcode
->teamID() == NULL
) {
1655 if (this->teamID() != subcode
->teamID())
1656 MacOSError::throwMe(errSecCSSignatureInvalid
);
1657 } else if (strcmp(this->teamID(), subcode
->teamID()) != 0)
1658 MacOSError::throwMe(errSecCSSignatureInvalid
);
1667 // A method that takes a certificate chain (certs) and evaluates
1668 // if it is a Mac or IPhone developer cert, an app store distribution cert,
1669 // or a developer ID
1671 bool SecStaticCode::isAppleDeveloperCert(CFArrayRef certs
)
1673 static const std::string appleDeveloperRequirement
= "(" + std::string(WWDRRequirement
) + ") or (" + MACWWDRRequirement
+ ") or (" + developerID
+ ") or (" + distributionCertificate
+ ") or (" + iPhoneDistributionCert
+ ")";
1674 SecPointer
<SecRequirement
> req
= new SecRequirement(parseRequirement(appleDeveloperRequirement
), true);
1675 Requirement::Context
ctx(certs
, NULL
, NULL
, "", NULL
);
1677 return req
->requirement()->validates(ctx
);
1680 } // end namespace CodeSigning
1681 } // end namespace Security