2 * Copyright (c) 2006-2015 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>
52 #include <sys/xattr.h>
54 #include <IOKit/storage/IOStorageDeviceCharacteristics.h>
55 #include <dispatch/private.h>
59 namespace CodeSigning
{
61 using namespace UnixPlusPlus
;
63 // A requirement representing a Mac or iOS dev cert, a Mac or iOS distribution cert, or a developer ID
64 static const char WWDRRequirement
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.2] exists";
65 static const char MACWWDRRequirement
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.12] exists";
66 static const char developerID
[] = "anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists"
67 " and certificate leaf[field.1.2.840.113635.100.6.1.13] exists";
68 static const char distributionCertificate
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.7] exists";
69 static const char iPhoneDistributionCert
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.4] exists";
72 // Map a component slot number to a suitable error code for a failure
74 static inline OSStatus
errorForSlot(CodeDirectory::SpecialSlot slot
)
78 return errSecCSInfoPlistFailed
;
79 case cdResourceDirSlot
:
80 return errSecCSResourceDirectoryFailed
;
82 return errSecCSSignatureFailed
;
88 // Construct a SecStaticCode object given a disk representation object
90 SecStaticCode::SecStaticCode(DiskRep
*rep
)
92 mValidated(false), mExecutableValidated(false), mResourcesValidated(false), mResourcesValidContext(NULL
),
93 mProgressQueue("com.apple.security.validation-progress", false, QOS_CLASS_DEFAULT
),
94 mOuterScope(NULL
), mResourceScope(NULL
),
95 mDesignatedReq(NULL
), mGotResourceBase(false), mMonitor(NULL
), mLimitedAsync(NULL
), mEvalDetails(NULL
)
97 CODESIGN_STATIC_CREATE(this, rep
);
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 mOuterScope
= &parent
;
119 setMonitor(parent
.monitor());
120 if (parent
.mLimitedAsync
)
121 mLimitedAsync
= new LimitedAsync(*parent
.mLimitedAsync
);
125 // CF-level comparison of SecStaticCode objects compares CodeDirectory hashes if signed,
126 // and falls back on comparing canonical paths if (both are) not.
128 bool SecStaticCode::equal(SecCFObject
&secOther
)
130 SecStaticCode
*other
= static_cast<SecStaticCode
*>(&secOther
);
131 CFDataRef mine
= this->cdHash();
132 CFDataRef his
= other
->cdHash();
134 return mine
&& his
&& CFEqual(mine
, his
);
136 return CFEqual(CFRef
<CFURLRef
>(this->copyCanonicalPath()), CFRef
<CFURLRef
>(other
->copyCanonicalPath()));
139 CFHashCode
SecStaticCode::hash()
141 if (CFDataRef h
= this->cdHash())
144 return CFHash(CFRef
<CFURLRef
>(this->copyCanonicalPath()));
149 // Invoke a stage monitor if registered
151 CFTypeRef
SecStaticCode::reportEvent(CFStringRef stage
, CFDictionaryRef info
)
154 return mMonitor(this->handle(false), stage
, info
);
159 void SecStaticCode::prepareProgress(unsigned int workload
)
161 dispatch_sync(mProgressQueue
, ^{
162 mCancelPending
= false; // not cancelled
164 if (mValidationFlags
& kSecCSReportProgress
) {
165 mCurrentWork
= 0; // nothing done yet
166 mTotalWork
= workload
; // totally fake - we don't know how many files we'll get to chew
170 void SecStaticCode::reportProgress(unsigned amount
/* = 1 */)
172 if (mMonitor
&& (mValidationFlags
& kSecCSReportProgress
)) {
173 // update progress and report
174 __block
bool cancel
= false;
175 dispatch_sync(mProgressQueue
, ^{
178 mCurrentWork
+= amount
;
179 mMonitor(this->handle(false), CFSTR("progress"), CFTemp
<CFDictionaryRef
>("{current=%d,total=%d}", mCurrentWork
, mTotalWork
));
181 // if cancellation is pending, abort now
183 MacOSError::throwMe(errSecCSCancelled
);
189 // Set validation conditions for fine-tuning legacy tolerance
191 static void addError(CFTypeRef cfError
, void* context
)
193 if (CFGetTypeID(cfError
) == CFNumberGetTypeID()) {
195 CFNumberGetValue(CFNumberRef(cfError
), kCFNumberSInt64Type
, (void*)&error
);
196 MacOSErrorSet
* errors
= (MacOSErrorSet
*)context
;
197 errors
->insert(OSStatus(error
));
201 void SecStaticCode::setValidationModifiers(CFDictionaryRef conditions
)
204 CFDictionary
source(conditions
, errSecCSDbCorrupt
);
205 mAllowOmissions
= source
.get
<CFArrayRef
>("omissions");
206 if (CFArrayRef errors
= source
.get
<CFArrayRef
>("errors"))
207 CFArrayApplyFunction(errors
, CFRangeMake(0, CFArrayGetCount(errors
)), addError
, &this->mTolerateErrors
);
213 // Request cancellation of a validation in progress.
214 // We do this by posting an abort flag that is checked periodically.
216 void SecStaticCode::cancelValidation()
218 if (!(mValidationFlags
& kSecCSReportProgress
)) // not using progress reporting; cancel won't make it through
219 MacOSError::throwMe(errSecCSInvalidFlags
);
220 dispatch_assert_queue(mProgressQueue
);
221 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()->slotIsPresent(-slot
))
356 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data
), // ... and it's no good
357 CFDataGetLength(data
), -slot
))
358 MacOSError::throwMe(errorForSlot(slot
)); // ... then bail
360 cache
= data
; // it's okay, cache it
361 } else { // absent, mark so
362 if (validated()) // if directory has been validated...
363 if (codeDirectory()->slotIsPresent(-slot
)) // ... and the slot is NOT missing
364 MacOSError::throwMe(errorForSlot(slot
)); // was supposed to be there
365 cache
= CFDataRef(kCFNull
); // white lie
368 return (cache
== CFDataRef(kCFNull
)) ? NULL
: cache
.get();
373 // Get the CodeDirectory.
374 // Throws (if check==true) or returns NULL (check==false) if there is none.
375 // Always throws if the CodeDirectory exists but is invalid.
376 // NEVER validates against the signature.
378 const CodeDirectory
*SecStaticCode::codeDirectory(bool check
/* = true */) const
381 // pick our favorite CodeDirectory from the choices we've got
383 CodeDirectoryMap candidates
;
384 if (loadCodeDirectories(candidates
)) {
385 CodeDirectory::HashAlgorithm type
= CodeDirectory::bestHashOf(mHashAlgorithms
);
386 mDir
= candidates
[type
]; // and the winner is...
387 candidates
.swap(mCodeDirectories
);
392 // We wanted a NON-checked peek and failed to safely decode the existing CodeDirectory.
393 // Pretend this is unsigned, but make sure we didn't somehow cache an invalid CodeDirectory.
396 Syslog::warning("code signing internal problem: mDir set despite exception exit");
397 MacOSError::throwMe(errSecCSInternalError
);
402 return reinterpret_cast<const CodeDirectory
*>(CFDataGetBytePtr(mDir
));
404 MacOSError::throwMe(errSecCSUnsigned
);
410 // Fetch an array of all available CodeDirectories.
411 // Returns false if unsigned (no classic CD slot), true otherwise.
413 bool SecStaticCode::loadCodeDirectories(CodeDirectoryMap
& cdMap
) const
415 __block CodeDirectoryMap candidates
;
416 __block
CodeDirectory::HashAlgorithms hashAlgorithms
;
417 __block CFRef
<CFDataRef
> baseDir
;
418 auto add
= ^bool (CodeDirectory::SpecialSlot slot
){
419 CFRef
<CFDataRef
> cdData
= diskRep()->component(slot
);
422 const CodeDirectory
* cd
= reinterpret_cast<const CodeDirectory
*>(CFDataGetBytePtr(cdData
));
423 if (!cd
->validateBlob(CFDataGetLength(cdData
)))
424 MacOSError::throwMe(errSecCSSignatureFailed
); // no recovery - any suspect CD fails
425 cd
->checkIntegrity();
426 auto result
= candidates
.insert(make_pair(cd
->hashType
, cdData
.get()));
428 MacOSError::throwMe(errSecCSSignatureInvalid
); // duplicate hashType, go to heck
429 hashAlgorithms
.insert(cd
->hashType
);
430 if (slot
== cdCodeDirectorySlot
)
434 if (!add(cdCodeDirectorySlot
))
435 return false; // no classic slot CodeDirectory -> unsigned
436 for (CodeDirectory::SpecialSlot slot
= cdAlternateCodeDirectorySlots
; slot
< cdAlternateCodeDirectoryLimit
; slot
++)
437 if (!add(slot
)) // no CodeDirectory at this slot -> end of alternates
439 if (candidates
.empty())
440 MacOSError::throwMe(errSecCSSignatureFailed
); // no viable CodeDirectory in sight
441 // commit to cached values
442 cdMap
.swap(candidates
);
443 mHashAlgorithms
.swap(hashAlgorithms
);
450 // Get the hash of the CodeDirectory.
451 // Returns NULL if there is none.
453 CFDataRef
SecStaticCode::cdHash()
456 if (const CodeDirectory
*cd
= codeDirectory(false)) {
457 mCDHash
.take(cd
->cdhash());
458 CODESIGN_STATIC_CDHASH(this, CFDataGetBytePtr(mCDHash
), (unsigned int)CFDataGetLength(mCDHash
));
466 // Get an array of the cdhashes for all digest types in this signature
467 // The array is sorted by cd->hashType.
469 CFArrayRef
SecStaticCode::cdHashes()
472 CFRef
<CFMutableArrayRef
> cdList
= makeCFMutableArray(0);
473 for (auto it
= mCodeDirectories
.begin(); it
!= mCodeDirectories
.end(); ++it
) {
474 const CodeDirectory
*cd
= (const CodeDirectory
*)CFDataGetBytePtr(it
->second
);
475 if (CFRef
<CFDataRef
> hash
= cd
->cdhash())
476 CFArrayAppendValue(cdList
, hash
);
478 mCDHashes
= cdList
.get();
485 // Return the CMS signature blob; NULL if none found.
487 CFDataRef
SecStaticCode::signature()
490 mSignature
.take(mRep
->signature());
493 MacOSError::throwMe(errSecCSUnsigned
);
498 // Verify the signature on the CodeDirectory.
499 // If this succeeds (doesn't throw), the CodeDirectory is statically trustworthy.
500 // Any outcome (successful or not) is cached for the lifetime of the StaticCode.
502 void SecStaticCode::validateDirectory()
504 // echo previous outcome, if any
505 // track revocation separately, as it may not have been checked
506 // during the initial validation
507 if (!validated() || ((mValidationFlags
& kSecCSEnforceRevocationChecks
) && !revocationChecked()))
509 // perform validation (or die trying)
510 CODESIGN_EVAL_STATIC_DIRECTORY(this);
511 mValidationExpired
= verifySignature();
512 if (mValidationFlags
& kSecCSEnforceRevocationChecks
)
513 mRevocationChecked
= true;
515 for (CodeDirectory::SpecialSlot slot
= codeDirectory()->maxSpecialSlot(); slot
>= 1; --slot
)
516 if (mCache
[slot
]) // if we already loaded that resource...
517 validateComponent(slot
, errorForSlot(slot
)); // ... then check it now
518 mValidated
= true; // we've done the deed...
519 mValidationResult
= errSecSuccess
; // ... and it was good
520 } catch (const CommonError
&err
) {
522 mValidationResult
= err
.osStatus();
525 secinfo("staticCode", "%p validation threw non-common exception", this);
527 Syslog::notice("code signing internal problem: unknown exception thrown by validation");
528 mValidationResult
= errSecCSInternalError
;
532 if (mValidationResult
== errSecSuccess
) {
533 if (mValidationExpired
)
534 if ((mValidationFlags
& kSecCSConsiderExpiration
)
535 || (codeDirectory()->flags
& kSecCodeSignatureForceExpiration
))
536 MacOSError::throwMe(CSSMERR_TP_CERT_EXPIRED
);
538 MacOSError::throwMe(mValidationResult
);
543 // Load and validate the CodeDirectory and all components *except* those related to the resource envelope.
544 // Those latter components are checked by validateResources().
546 void SecStaticCode::validateNonResourceComponents()
548 this->validateDirectory();
549 for (CodeDirectory::SpecialSlot slot
= codeDirectory()->maxSpecialSlot(); slot
>= 1; --slot
)
551 case cdResourceDirSlot
: // validated by validateResources
554 this->component(slot
); // loads and validates
561 // Check that any "top index" sealed into the signature conforms to what's actually here.
563 void SecStaticCode::validateTopDirectory()
565 assert(mDir
); // must already have loaded CodeDirectories
566 if (CFDataRef topDirectory
= component(cdTopDirectorySlot
)) {
567 const auto topData
= (const Endian
<uint32_t> *)CFDataGetBytePtr(topDirectory
);
568 const auto topDataEnd
= topData
+ CFDataGetLength(topDirectory
) / sizeof(*topData
);
569 std::vector
<uint32_t> signedVector(topData
, topDataEnd
);
571 std::vector
<uint32_t> foundVector
;
572 foundVector
.push_back(cdCodeDirectorySlot
); // mandatory
573 for (CodeDirectory::Slot slot
= 1; slot
<= cdSlotMax
; ++slot
)
575 foundVector
.push_back(slot
);
576 int alternateCount
= int(mCodeDirectories
.size() - 1); // one will go into cdCodeDirectorySlot
577 for (unsigned n
= 0; n
< alternateCount
; n
++)
578 foundVector
.push_back(cdAlternateCodeDirectorySlots
+ n
);
579 foundVector
.push_back(cdSignatureSlot
); // mandatory (may be empty)
581 if (signedVector
!= foundVector
)
582 MacOSError::throwMe(errSecCSSignatureFailed
);
588 // Get the (signed) signing date from the code signature.
589 // Sadly, we need to validate the signature to get the date (as a side benefit).
590 // This means that you can't get the signing time for invalidly signed code.
592 // We could run the decoder "almost to" verification to avoid this, but there seems
593 // little practical point to such a duplication of effort.
595 CFAbsoluteTime
SecStaticCode::signingTime()
601 CFAbsoluteTime
SecStaticCode::signingTimestamp()
604 return mSigningTimestamp
;
609 // Verify the CMS signature.
610 // This performs the cryptographic tango. It returns if the signature is valid,
611 // or throws if it is not. As a side effect, a successful return sets up the
612 // cached certificate chain for future use.
613 // Returns true if the signature is expired (the X.509 sense), false if it's not.
614 // Expiration is fatal (throws) if a secure timestamp is included, but not otherwise.
616 bool SecStaticCode::verifySignature()
618 // ad-hoc signed code is considered validly signed by definition
619 if (flag(kSecCodeSignatureAdhoc
)) {
620 CODESIGN_EVAL_STATIC_SIGNATURE_ADHOC(this);
624 DTRACK(CODESIGN_EVAL_STATIC_SIGNATURE
, this, (char*)this->mainExecutablePath().c_str());
626 // decode CMS and extract SecTrust for verification
627 CFRef
<CMSDecoderRef
> cms
;
628 MacOSError::check(CMSDecoderCreate(&cms
.aref())); // create decoder
629 CFDataRef sig
= this->signature();
630 MacOSError::check(CMSDecoderUpdateMessage(cms
, CFDataGetBytePtr(sig
), CFDataGetLength(sig
)));
631 this->codeDirectory(); // load CodeDirectory (sets mDir)
632 MacOSError::check(CMSDecoderSetDetachedContent(cms
, mBaseDir
));
633 MacOSError::check(CMSDecoderFinalizeMessage(cms
));
634 MacOSError::check(CMSDecoderSetSearchKeychain(cms
, cfEmptyArray()));
635 CFRef
<CFArrayRef
> vf_policies(verificationPolicies());
636 CFRef
<CFArrayRef
> ts_policies(SecPolicyCreateAppleTimeStampingAndRevocationPolicies(vf_policies
));
638 CMSSignerStatus status
;
639 MacOSError::check(CMSDecoderCopySignerStatus(cms
, 0, vf_policies
,
640 false, &status
, &mTrust
.aref(), NULL
));
642 if (status
!= kCMSSignerValid
) {
645 case kCMSSignerUnsigned
: reason
="kCMSSignerUnsigned"; break;
646 case kCMSSignerNeedsDetachedContent
: reason
="kCMSSignerNeedsDetachedContent"; break;
647 case kCMSSignerInvalidSignature
: reason
="kCMSSignerInvalidSignature"; break;
648 case kCMSSignerInvalidCert
: reason
="kCMSSignerInvalidCert"; break;
649 case kCMSSignerInvalidIndex
: reason
="kCMSSignerInvalidIndex"; break;
650 default: reason
="unknown"; break;
652 Security::Syslog::error("CMSDecoderCopySignerStatus failed with %s error (%d)",
653 reason
, (int)status
);
654 MacOSError::throwMe(errSecCSSignatureFailed
);
657 // retrieve auxiliary data bag and verify against current state
658 CFRef
<CFDataRef
> hashBag
;
659 switch (OSStatus rc
= CMSDecoderCopySignerAppleCodesigningHashAgility(cms
, 0, &hashBag
.aref())) {
662 CFRef
<CFDictionaryRef
> hashDict
= makeCFDictionaryFrom(hashBag
);
663 CFArrayRef cdList
= CFArrayRef(CFDictionaryGetValue(hashDict
, CFSTR("cdhashes")));
664 CFArrayRef myCdList
= this->cdHashes();
665 if (cdList
== NULL
|| !CFEqual(cdList
, myCdList
))
666 MacOSError::throwMe(errSecCSSignatureFailed
);
669 case -1: /* CMS used to return this for "no attribute found", so tolerate it. Now returning noErr/NULL */
672 MacOSError::throwMe(rc
);
675 // internal signing time (as specified by the signer; optional)
676 mSigningTime
= 0; // "not present" marker (nobody could code sign on Jan 1, 2001 :-)
677 switch (OSStatus rc
= CMSDecoderCopySignerSigningTime(cms
, 0, &mSigningTime
)) {
679 case errSecSigningTimeMissing
:
682 Security::Syslog::error("Could not get signing time (error %d)", (int)rc
);
683 MacOSError::throwMe(rc
);
686 // certified signing time (as specified by a TSA; optional)
687 mSigningTimestamp
= 0;
688 switch (OSStatus rc
= CMSDecoderCopySignerTimestampWithPolicy(cms
, ts_policies
, 0, &mSigningTimestamp
)) {
690 case errSecTimestampMissing
:
693 Security::Syslog::error("Could not get timestamp (error %d)", (int)rc
);
694 MacOSError::throwMe(rc
);
697 // set up the environment for SecTrust
698 if (mValidationFlags
& kSecCSNoNetworkAccess
) {
699 MacOSError::check(SecTrustSetNetworkFetchAllowed(mTrust
,false)); // no network?
701 MacOSError::check(SecTrustSetKeychainsAllowed(mTrust
, false));
703 CSSM_APPLE_TP_ACTION_DATA actionData
= {
704 CSSM_APPLE_TP_ACTION_VERSION
, // version of data structure
708 if (!(mValidationFlags
& kSecCSCheckTrustedAnchors
)) {
709 /* no need to evaluate anchor trust when building cert chain */
710 MacOSError::check(SecTrustSetAnchorCertificates(mTrust
, cfEmptyArray())); // no anchors
711 actionData
.ActionFlags
|= CSSM_TP_ACTION_IMPLICIT_ANCHORS
; // action flags
714 for (;;) { // at most twice
715 MacOSError::check(SecTrustSetParameters(mTrust
,
716 CSSM_TP_ACTION_DEFAULT
, CFTempData(&actionData
, sizeof(actionData
))));
718 // evaluate trust and extract results
719 SecTrustResultType trustResult
;
720 MacOSError::check(SecTrustEvaluate(mTrust
, &trustResult
));
721 MacOSError::check(SecTrustGetResult(mTrust
, &trustResult
, &mCertChain
.aref(), &mEvalDetails
));
723 // if this is an Apple developer cert....
724 if (teamID() && SecStaticCode::isAppleDeveloperCert(mCertChain
)) {
725 CFRef
<CFStringRef
> teamIDFromCert
;
726 if (CFArrayGetCount(mCertChain
) > 0) {
727 /* Note that SecCertificateCopySubjectComponent sets the out parameter to NULL if there is no field present */
728 MacOSError::check(SecCertificateCopySubjectComponent((SecCertificateRef
)CFArrayGetValueAtIndex(mCertChain
, Requirement::leafCert
),
729 &CSSMOID_OrganizationalUnitName
,
730 &teamIDFromCert
.aref()));
732 if (teamIDFromCert
) {
733 CFRef
<CFStringRef
> teamIDFromCD
= CFStringCreateWithCString(NULL
, teamID(), kCFStringEncodingUTF8
);
735 Security::Syslog::error("Could not get team identifier (%s)", teamID());
736 MacOSError::throwMe(errSecCSInvalidTeamIdentifier
);
739 if (CFStringCompare(teamIDFromCert
, teamIDFromCD
, 0) != kCFCompareEqualTo
) {
740 Security::Syslog::error("Team identifier in the signing certificate (%s) does not match the team identifier (%s) in the code directory",
741 cfString(teamIDFromCert
).c_str(), teamID());
742 MacOSError::throwMe(errSecCSBadTeamIdentifier
);
748 CODESIGN_EVAL_STATIC_SIGNATURE_RESULT(this, trustResult
, mCertChain
? (int)CFArrayGetCount(mCertChain
) : 0);
749 switch (trustResult
) {
750 case kSecTrustResultProceed
:
751 case kSecTrustResultUnspecified
:
753 case kSecTrustResultDeny
:
754 MacOSError::throwMe(CSSMERR_APPLETP_TRUST_SETTING_DENY
); // user reject
755 case kSecTrustResultInvalid
:
756 assert(false); // should never happen
757 MacOSError::throwMe(CSSMERR_TP_NOT_TRUSTED
);
761 MacOSError::check(SecTrustGetCssmResultCode(mTrust
, &result
));
762 // if we have a valid timestamp, CMS validates against (that) signing time and all is well.
763 // If we don't have one, may validate against *now*, and must be able to tolerate expiration.
764 if (mSigningTimestamp
== 0) { // no timestamp available
765 if (((result
== CSSMERR_TP_CERT_EXPIRED
) || (result
== CSSMERR_TP_CERT_NOT_VALID_YET
))
766 && !(actionData
.ActionFlags
& CSSM_TP_ACTION_ALLOW_EXPIRED
)) {
767 CODESIGN_EVAL_STATIC_SIGNATURE_EXPIRED(this);
768 actionData
.ActionFlags
|= CSSM_TP_ACTION_ALLOW_EXPIRED
; // (this also allows postdated certs)
769 continue; // retry validation while tolerating expiration
772 Security::Syslog::error("SecStaticCode: verification failed (trust result %d, error %d)", trustResult
, (int)result
);
773 MacOSError::throwMe(result
);
777 if (mSigningTimestamp
) {
778 CFIndex rootix
= CFArrayGetCount(mCertChain
);
779 if (SecCertificateRef mainRoot
= SecCertificateRef(CFArrayGetValueAtIndex(mCertChain
, rootix
-1)))
780 if (isAppleCA(mainRoot
)) {
781 // impose policy: if the signature itself draws to Apple, then so must the timestamp signature
782 CFRef
<CFArrayRef
> tsCerts
;
783 OSStatus result
= CMSDecoderCopySignerTimestampCertificates(cms
, 0, &tsCerts
.aref());
785 Security::Syslog::error("SecStaticCode: could not get timestamp certificates (error %d)", (int)result
);
786 MacOSError::check(result
);
788 CFIndex tsn
= CFArrayGetCount(tsCerts
);
789 bool good
= tsn
> 0 && isAppleCA(SecCertificateRef(CFArrayGetValueAtIndex(tsCerts
, tsn
-1)));
791 result
= CSSMERR_TP_NOT_TRUSTED
;
792 Security::Syslog::error("SecStaticCode: timestamp policy verification failed (error %d)", (int)result
);
793 MacOSError::throwMe(result
);
798 return actionData
.ActionFlags
& CSSM_TP_ACTION_ALLOW_EXPIRED
;
804 // Return the TP policy used for signature verification.
805 // This may be a simple SecPolicyRef or a CFArray of policies.
806 // The caller owns the return value.
808 static SecPolicyRef
makeRevocationPolicy(CFOptionFlags flags
)
810 CFRef
<SecPolicyRef
> policy(SecPolicyCreateRevocation(flags
));
811 return policy
.yield();
814 CFArrayRef
SecStaticCode::verificationPolicies()
816 CFRef
<SecPolicyRef
> core
;
817 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3
,
818 &CSSMOID_APPLE_TP_CODE_SIGNING
, &core
.aref()));
819 if (mValidationFlags
& kSecCSNoNetworkAccess
) {
820 // Skips all revocation since they require network connectivity
821 // therefore annihilates kSecCSEnforceRevocationChecks if present
822 CFRef
<SecPolicyRef
> no_revoc
= makeRevocationPolicy(kSecRevocationNetworkAccessDisabled
);
823 return makeCFArray(2, core
.get(), no_revoc
.get());
825 else if (mValidationFlags
& kSecCSEnforceRevocationChecks
) {
826 // Add CRL and OCSP policies
827 CFRef
<SecPolicyRef
> revoc
= makeRevocationPolicy(kSecRevocationUseAnyAvailableMethod
);
828 return makeCFArray(2, core
.get(), revoc
.get());
830 return makeCFArray(1, core
.get());
836 // Validate a particular sealed, cached resource against its (special) CodeDirectory slot.
837 // The resource must already have been placed in the cache.
838 // This does NOT perform basic validation.
840 void SecStaticCode::validateComponent(CodeDirectory::SpecialSlot slot
, OSStatus fail
/* = errSecCSSignatureFailed */)
842 assert(slot
<= cdSlotMax
);
843 CFDataRef data
= mCache
[slot
];
844 assert(data
); // must be cached
845 if (data
== CFDataRef(kCFNull
)) {
846 if (codeDirectory()->slotIsPresent(-slot
)) // was supposed to be there...
847 MacOSError::throwMe(fail
); // ... and is missing
849 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data
), CFDataGetLength(data
), -slot
))
850 MacOSError::throwMe(fail
);
856 // Perform static validation of the main executable.
857 // This reads the main executable from disk and validates it against the
858 // CodeDirectory code slot array.
859 // Note that this is NOT an in-memory validation, and is thus potentially
860 // subject to timing attacks.
862 void SecStaticCode::validateExecutable()
864 if (!validatedExecutable()) {
866 DTRACK(CODESIGN_EVAL_STATIC_EXECUTABLE
, this,
867 (char*)this->mainExecutablePath().c_str(), codeDirectory()->nCodeSlots
);
868 const CodeDirectory
*cd
= this->codeDirectory();
870 MacOSError::throwMe(errSecCSUnsigned
);
871 AutoFileDesc
fd(mainExecutablePath(), O_RDONLY
);
872 fd
.fcntl(F_NOCACHE
, true); // turn off page caching (one-pass)
873 if (Universal
*fat
= mRep
->mainExecutableImage())
874 fd
.seek(fat
->archOffset());
875 size_t pageSize
= cd
->pageSize
? (1 << cd
->pageSize
) : 0;
876 size_t remaining
= cd
->signingLimit();
877 for (uint32_t slot
= 0; slot
< cd
->nCodeSlots
; ++slot
) {
878 size_t thisPage
= remaining
;
880 thisPage
= min(thisPage
, pageSize
);
881 __block
bool good
= true;
882 CodeDirectory::multipleHashFileData(fd
, thisPage
, hashAlgorithms(), ^(CodeDirectory::HashAlgorithm type
, Security::DynamicHash
*hasher
) {
883 const CodeDirectory
* cd
= (const CodeDirectory
*)CFDataGetBytePtr(mCodeDirectories
[type
]);
884 if (!hasher
->verify((*cd
)[slot
]))
888 CODESIGN_EVAL_STATIC_EXECUTABLE_FAIL(this, (int)slot
);
889 MacOSError::throwMe(errSecCSSignatureFailed
);
891 remaining
-= thisPage
;
893 assert(remaining
== 0);
894 mExecutableValidated
= true;
895 mExecutableValidResult
= errSecSuccess
;
896 } catch (const CommonError
&err
) {
897 mExecutableValidated
= true;
898 mExecutableValidResult
= err
.osStatus();
901 secinfo("staticCode", "%p executable validation threw non-common exception", this);
902 mExecutableValidated
= true;
903 mExecutableValidResult
= errSecCSInternalError
;
904 Syslog::notice("code signing internal problem: unknown exception thrown by validation");
908 assert(validatedExecutable());
909 if (mExecutableValidResult
!= errSecSuccess
)
910 MacOSError::throwMe(mExecutableValidResult
);
915 // Perform static validation of sealed resources and nested code.
917 // This performs a whole-code static resource scan and effectively
918 // computes a concordance between what's on disk and what's in the ResourceDirectory.
919 // Any unsanctioned difference causes an error.
921 unsigned SecStaticCode::estimateResourceWorkload()
923 // workload estimate = number of sealed files
924 CFDictionaryRef sealedResources
= resourceDictionary();
925 CFDictionaryRef files
= cfget
<CFDictionaryRef
>(sealedResources
, "files2");
927 files
= cfget
<CFDictionaryRef
>(sealedResources
, "files");
928 return files
? unsigned(CFDictionaryGetCount(files
)) : 0;
931 void SecStaticCode::validateResources(SecCSFlags flags
)
933 // do we have a superset of this requested validation cached?
935 if (mResourcesValidated
) { // have cached outcome
936 if (!(flags
& kSecCSCheckNestedCode
) || mResourcesDeep
) // was deep or need no deep scan
941 if (mLimitedAsync
== NULL
) {
942 mLimitedAsync
= new LimitedAsync(diskRep()->fd().mediumType() == kIOPropertyMediumTypeSolidStateKey
);
946 CFDictionaryRef rules
;
947 CFDictionaryRef files
;
949 if (!loadResources(rules
, files
, version
))
950 return; // validly no resources; nothing to do (ok)
952 // found resources, and they are sealed
953 DTRACK(CODESIGN_EVAL_STATIC_RESOURCES
, this,
954 (char*)this->mainExecutablePath().c_str(), 0);
956 // scan through the resources on disk, checking each against the resourceDirectory
957 mResourcesValidContext
= new CollectingContext(*this); // collect all failures in here
959 // check for weak resource rules
960 bool strict
= flags
& kSecCSStrictValidate
;
962 if (hasWeakResourceRules(rules
, version
, mAllowOmissions
))
963 if (mTolerateErrors
.find(errSecCSWeakResourceRules
) == mTolerateErrors
.end())
964 MacOSError::throwMe(errSecCSWeakResourceRules
);
966 if (mTolerateErrors
.find(errSecCSWeakResourceEnvelope
) == mTolerateErrors
.end())
967 MacOSError::throwMe(errSecCSWeakResourceEnvelope
);
970 Dispatch::Group group
;
971 Dispatch::Group
&groupRef
= group
; // (into block)
973 // scan through the resources on disk, checking each against the resourceDirectory
974 __block CFRef
<CFMutableDictionaryRef
> resourceMap
= makeCFMutableDictionary(files
);
975 string base
= cfString(this->resourceBase());
976 ResourceBuilder
resources(base
, base
, rules
, strict
, mTolerateErrors
);
977 this->mResourceScope
= &resources
;
978 diskRep()->adjustResources(resources
);
980 resources
.scan(^(FTSENT
*ent
, uint32_t ruleFlags
, const string relpath
, ResourceBuilder::Rule
*rule
) {
981 CFDictionaryRemoveValue(resourceMap
, CFTempString(relpath
));
982 bool isSymlink
= (ent
->fts_info
== FTS_SL
);
984 void (^validate
)() = ^{
985 validateResource(files
, relpath
, isSymlink
, *mResourcesValidContext
, flags
, version
);
989 mLimitedAsync
->perform(groupRef
, validate
);
991 group
.wait(); // wait until all async resources have been validated as well
993 unsigned leftovers
= unsigned(CFDictionaryGetCount(resourceMap
));
995 secinfo("staticCode", "%d sealed resource(s) not found in code", int(leftovers
));
996 CFDictionaryApplyFunction(resourceMap
, SecStaticCode::checkOptionalResource
, mResourcesValidContext
);
999 // now check for any errors found in the reporting context
1000 mResourcesValidated
= true;
1001 mResourcesDeep
= flags
& kSecCSCheckNestedCode
;
1002 if (mResourcesValidContext
->osStatus() != errSecSuccess
)
1003 mResourcesValidContext
->throwMe();
1004 } catch (const CommonError
&err
) {
1005 mResourcesValidated
= true;
1006 mResourcesDeep
= flags
& kSecCSCheckNestedCode
;
1007 mResourcesValidResult
= err
.osStatus();
1010 secinfo("staticCode", "%p executable validation threw non-common exception", this);
1011 mResourcesValidated
= true;
1012 mResourcesDeep
= flags
& kSecCSCheckNestedCode
;
1013 mResourcesValidResult
= errSecCSInternalError
;
1014 Syslog::notice("code signing internal problem: unknown exception thrown by validation");
1018 assert(validatedResources());
1019 if (mResourcesValidResult
)
1020 MacOSError::throwMe(mResourcesValidResult
);
1021 if (mResourcesValidContext
->osStatus() != errSecSuccess
)
1022 mResourcesValidContext
->throwMe();
1026 bool SecStaticCode::loadResources(CFDictionaryRef
& rules
, CFDictionaryRef
& files
, uint32_t& version
)
1029 CFDictionaryRef sealedResources
= resourceDictionary();
1030 if (this->resourceBase()) { // disk has resources
1031 if (sealedResources
)
1032 /* go to work below */;
1034 MacOSError::throwMe(errSecCSResourcesNotFound
);
1035 } else { // disk has no resources
1036 if (sealedResources
)
1037 MacOSError::throwMe(errSecCSResourcesNotFound
);
1039 return false; // no resources, not sealed - fine (no work)
1042 // use V2 resource seal if available, otherwise fall back to V1
1043 if (CFDictionaryGetValue(sealedResources
, CFSTR("files2"))) { // have V2 signature
1044 rules
= cfget
<CFDictionaryRef
>(sealedResources
, "rules2");
1045 files
= cfget
<CFDictionaryRef
>(sealedResources
, "files2");
1047 } else { // only V1 available
1048 rules
= cfget
<CFDictionaryRef
>(sealedResources
, "rules");
1049 files
= cfget
<CFDictionaryRef
>(sealedResources
, "files");
1052 if (!rules
|| !files
)
1053 MacOSError::throwMe(errSecCSResourcesInvalid
);
1058 void SecStaticCode::checkOptionalResource(CFTypeRef key
, CFTypeRef value
, void *context
)
1060 ValidationContext
*ctx
= static_cast<ValidationContext
*>(context
);
1061 ResourceSeal
seal(value
);
1062 if (!seal
.optional()) {
1063 if (key
&& CFGetTypeID(key
) == CFStringGetTypeID()) {
1064 CFTempURL
tempURL(CFStringRef(key
), false, ctx
->code
.resourceBase());
1065 if (!tempURL
.get()) {
1066 ctx
->reportProblem(errSecCSBadDictionaryFormat
, kSecCFErrorResourceSeal
, key
);
1068 ctx
->reportProblem(errSecCSBadResource
, kSecCFErrorResourceMissing
, tempURL
);
1071 ctx
->reportProblem(errSecCSBadResource
, kSecCFErrorResourceSeal
, key
);
1077 static bool isOmitRule(CFTypeRef value
)
1079 if (CFGetTypeID(value
) == CFBooleanGetTypeID())
1080 return value
== kCFBooleanFalse
;
1081 CFDictionary
rule(value
, errSecCSResourceRulesInvalid
);
1082 return rule
.get
<CFBooleanRef
>("omit") == kCFBooleanTrue
;
1085 bool SecStaticCode::hasWeakResourceRules(CFDictionaryRef rulesDict
, uint32_t version
, CFArrayRef allowedOmissions
)
1087 // compute allowed omissions
1088 CFRef
<CFArrayRef
> defaultOmissions
= this->diskRep()->allowedResourceOmissions();
1089 if (!defaultOmissions
) {
1090 Syslog::notice("code signing internal problem: diskRep returned no allowedResourceOmissions");
1091 MacOSError::throwMe(errSecCSInternalError
);
1093 CFRef
<CFMutableArrayRef
> allowed
= CFArrayCreateMutableCopy(NULL
, 0, defaultOmissions
);
1094 if (allowedOmissions
)
1095 CFArrayAppendArray(allowed
, allowedOmissions
, CFRangeMake(0, CFArrayGetCount(allowedOmissions
)));
1096 CFRange range
= CFRangeMake(0, CFArrayGetCount(allowed
));
1098 // check all resource rules for weakness
1099 string catchAllRule
= (version
== 1) ? "^Resources/" : "^.*";
1100 __block
bool coversAll
= false;
1101 __block
bool forbiddenOmission
= false;
1102 CFArrayRef allowedRef
= allowed
.get(); // (into block)
1103 CFDictionary
rules(rulesDict
, errSecCSResourceRulesInvalid
);
1104 rules
.apply(^(CFStringRef key
, CFTypeRef value
) {
1105 string pattern
= cfString(key
, errSecCSResourceRulesInvalid
);
1106 if (pattern
== catchAllRule
&& value
== kCFBooleanTrue
) {
1110 if (isOmitRule(value
))
1111 forbiddenOmission
|= !CFArrayContainsValue(allowedRef
, range
, key
);
1114 return !coversAll
|| forbiddenOmission
;
1119 // Load, validate, cache, and return CFDictionary forms of sealed resources.
1121 CFDictionaryRef
SecStaticCode::infoDictionary()
1124 mInfoDict
.take(getDictionary(cdInfoSlot
, errSecCSInfoPlistFailed
));
1125 secinfo("staticCode", "%p loaded InfoDict %p", this, mInfoDict
.get());
1130 CFDictionaryRef
SecStaticCode::entitlements()
1132 if (!mEntitlements
) {
1133 validateDirectory();
1134 if (CFDataRef entitlementData
= component(cdEntitlementSlot
)) {
1135 validateComponent(cdEntitlementSlot
);
1136 const EntitlementBlob
*blob
= reinterpret_cast<const EntitlementBlob
*>(CFDataGetBytePtr(entitlementData
));
1137 if (blob
->validateBlob()) {
1138 mEntitlements
.take(blob
->entitlements());
1139 secinfo("staticCode", "%p loaded Entitlements %p", this, mEntitlements
.get());
1141 // we do not consider a different blob type to be an error. We think it's a new format we don't understand
1144 return mEntitlements
;
1147 CFDictionaryRef
SecStaticCode::resourceDictionary(bool check
/* = true */)
1149 if (mResourceDict
) // cached
1150 return mResourceDict
;
1151 if (CFRef
<CFDictionaryRef
> dict
= getDictionary(cdResourceDirSlot
, check
))
1152 if (cfscan(dict
, "{rules=%Dn,files=%Dn}")) {
1153 secinfo("staticCode", "%p loaded ResourceDict %p",
1154 this, mResourceDict
.get());
1155 return mResourceDict
= dict
;
1162 CFDataRef
SecStaticCode::copyComponent(CodeDirectory::SpecialSlot slot
, CFDataRef hash
)
1164 const CodeDirectory
* cd
= this->codeDirectory();
1165 if (CFCopyRef
<CFDataRef
> component
= this->component(slot
)) {
1167 const void *slotHash
= (*cd
)[slot
];
1168 if (cd
->hashSize
!= CFDataGetLength(hash
) || 0 != memcmp(slotHash
, CFDataGetBytePtr(hash
), cd
->hashSize
)) {
1169 Syslog::notice("copyComponent hash mismatch slot %d length %d", slot
, int(CFDataGetLength(hash
)));
1170 return NULL
; // mismatch
1173 return component
.yield();
1181 // Load and cache the resource directory base.
1182 // Note that the base is optional for each DiskRep.
1184 CFURLRef
SecStaticCode::resourceBase()
1186 if (!mGotResourceBase
) {
1187 string base
= mRep
->resourcesRootPath();
1189 mResourceBase
.take(makeCFURL(base
, true));
1190 mGotResourceBase
= true;
1192 return mResourceBase
;
1197 // Load a component, validate it, convert it to a CFDictionary, and return that.
1198 // This will force load and validation, which means that it will perform basic
1199 // validation if it hasn't been done yet.
1201 CFDictionaryRef
SecStaticCode::getDictionary(CodeDirectory::SpecialSlot slot
, bool check
/* = true */)
1204 validateDirectory();
1205 if (CFDataRef infoData
= component(slot
)) {
1206 validateComponent(slot
);
1207 if (CFDictionaryRef dict
= makeCFDictionaryFrom(infoData
))
1210 MacOSError::throwMe(errSecCSBadDictionaryFormat
);
1218 CFDictionaryRef
SecStaticCode::diskRepInformation()
1220 return mRep
->diskRepInformation();
1224 void SecStaticCode::validateResource(CFDictionaryRef files
, string path
, bool isSymlink
, ValidationContext
&ctx
, SecCSFlags flags
, uint32_t version
)
1226 if (!resourceBase()) // no resources in DiskRep
1227 MacOSError::throwMe(errSecCSResourcesNotFound
);
1228 CFRef
<CFURLRef
> fullpath
= makeCFURL(path
, false, resourceBase());
1229 if (version
> 1 && ((flags
& (kSecCSStrictValidate
|kSecCSRestrictSidebandData
)) == (kSecCSStrictValidate
|kSecCSRestrictSidebandData
))) {
1230 AutoFileDesc
fd(cfString(fullpath
));
1231 if (fd
.hasExtendedAttribute(XATTR_RESOURCEFORK_NAME
) || fd
.hasExtendedAttribute(XATTR_FINDERINFO_NAME
))
1232 ctx
.reportProblem(errSecCSInvalidAssociatedFileData
, kSecCFErrorResourceSideband
, fullpath
);
1234 if (CFTypeRef file
= CFDictionaryGetValue(files
, CFTempString(path
))) {
1235 ResourceSeal
seal(file
);
1236 const ResourceSeal
& rseal
= seal
;
1237 if (seal
.nested()) {
1239 return ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
1240 string suffix
= ".framework";
1241 bool isFramework
= (path
.length() > suffix
.length())
1242 && (path
.compare(path
.length()-suffix
.length(), suffix
.length(), suffix
) == 0);
1243 validateNestedCode(fullpath
, seal
, flags
, isFramework
);
1244 } else if (seal
.link()) {
1246 return ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
1247 validateSymlinkResource(cfString(fullpath
), cfString(seal
.link()), ctx
, flags
);
1248 } else if (seal
.hash(hashAlgorithm())) { // genuine file
1250 return ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
1251 AutoFileDesc
fd(cfString(fullpath
), O_RDONLY
, FileDesc::modeMissingOk
); // open optional file
1253 __block
bool good
= true;
1254 CodeDirectory::multipleHashFileData(fd
, 0, hashAlgorithms(), ^(CodeDirectory::HashAlgorithm type
, Security::DynamicHash
*hasher
) {
1255 if (!hasher
->verify(rseal
.hash(type
)))
1259 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // altered
1261 if (!seal
.optional())
1262 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceMissing
, fullpath
); // was sealed but is now missing
1264 return; // validly missing
1267 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
1270 if (version
== 1) { // version 1 ignores symlinks altogether
1271 char target
[PATH_MAX
];
1272 if (::readlink(cfString(fullpath
).c_str(), target
, sizeof(target
)) > 0)
1275 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAdded
, CFTempURL(path
, false, resourceBase()));
1278 void SecStaticCode::validatePlainMemoryResource(string path
, CFDataRef fileData
, SecCSFlags flags
)
1280 CFDictionaryRef rules
;
1281 CFDictionaryRef files
;
1283 if (!loadResources(rules
, files
, version
))
1284 MacOSError::throwMe(errSecCSResourcesNotFound
); // no resources sealed; this can't be right
1285 if (CFTypeRef file
= CFDictionaryGetValue(files
, CFTempString(path
))) {
1286 ResourceSeal
seal(file
);
1287 const Byte
*sealHash
= seal
.hash(hashAlgorithm());
1289 if (codeDirectory()->verifyMemoryContent(fileData
, sealHash
))
1293 MacOSError::throwMe(errSecCSBadResource
);
1296 void SecStaticCode::validateSymlinkResource(std::string fullpath
, std::string seal
, ValidationContext
&ctx
, SecCSFlags flags
)
1298 static const char* const allowedDestinations
[] = {
1303 char target
[PATH_MAX
];
1304 ssize_t len
= ::readlink(fullpath
.c_str(), target
, sizeof(target
)-1);
1306 UnixError::check(-1);
1308 std::string fulltarget
= target
;
1309 if (target
[0] != '/') {
1310 size_t lastSlash
= fullpath
.rfind('/');
1311 fulltarget
= fullpath
.substr(0, lastSlash
) + '/' + target
;
1313 if (seal
!= target
) {
1314 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, CFTempString(fullpath
));
1317 if ((mValidationFlags
& (kSecCSStrictValidate
|kSecCSRestrictSymlinks
)) == (kSecCSStrictValidate
|kSecCSRestrictSymlinks
)) {
1318 char resolved
[PATH_MAX
];
1319 if (realpath(fulltarget
.c_str(), resolved
)) {
1320 assert(resolved
[0] == '/');
1321 size_t rlen
= strlen(resolved
);
1322 if (target
[0] == '/') {
1323 // absolute symlink; only allow absolute links to system locations
1324 for (const char* const* pathp
= allowedDestinations
; *pathp
; pathp
++) {
1325 size_t dlen
= strlen(*pathp
);
1326 if (rlen
> dlen
&& strncmp(resolved
, *pathp
, dlen
) == 0)
1327 return; // target inside /System, deemed okay
1330 // everything else must be inside the bundle(s)
1331 for (const SecStaticCode
* code
= this; code
; code
= code
->mOuterScope
) {
1332 string root
= code
->mResourceScope
->root();
1333 if (strncmp(resolved
, root
.c_str(), root
.size()) == 0) {
1334 if (code
->mResourceScope
->includes(resolved
+ root
.length() + 1))
1335 return; // located in resource stack && included in envelope
1337 break; // located but excluded from envelope (deny)
1342 // if we fell through, flag a symlink error
1343 if (mTolerateErrors
.find(errSecCSInvalidSymlink
) == mTolerateErrors
.end())
1344 ctx
.reportProblem(errSecCSInvalidSymlink
, kSecCFErrorResourceAltered
, CFTempString(fullpath
));
1348 void SecStaticCode::validateNestedCode(CFURLRef path
, const ResourceSeal
&seal
, SecCSFlags flags
, bool isFramework
)
1350 CFRef
<SecRequirementRef
> req
;
1351 if (SecRequirementCreateWithString(seal
.requirement(), kSecCSDefaultFlags
, &req
.aref()))
1352 MacOSError::throwMe(errSecCSResourcesInvalid
);
1354 // recursively verify this nested code
1356 if (!(flags
& kSecCSCheckNestedCode
))
1357 flags
|= kSecCSBasicValidateOnly
| kSecCSQuickCheck
;
1358 SecPointer
<SecStaticCode
> code
= new SecStaticCode(DiskRep::bestGuess(cfString(path
)));
1359 code
->initializeFromParent(*this);
1360 code
->staticValidate(flags
& ~kSecCSRestrictToAppLike
, SecRequirement::required(req
));
1362 if (isFramework
&& (flags
& kSecCSStrictValidate
))
1364 validateOtherVersions(path
, flags
, req
, code
);
1365 } catch (const CSError
&err
) {
1366 MacOSError::throwMe(errSecCSBadFrameworkVersion
);
1367 } catch (const MacOSError
&err
) {
1368 MacOSError::throwMe(errSecCSBadFrameworkVersion
);
1371 } catch (CSError
&err
) {
1372 if (err
.error
== errSecCSReqFailed
) {
1373 mResourcesValidContext
->reportProblem(errSecCSBadNestedCode
, kSecCFErrorResourceAltered
, path
);
1376 err
.augment(kSecCFErrorPath
, path
);
1378 } catch (const MacOSError
&err
) {
1379 if (err
.error
== errSecCSReqFailed
) {
1380 mResourcesValidContext
->reportProblem(errSecCSBadNestedCode
, kSecCFErrorResourceAltered
, path
);
1383 CSError::throwMe(err
.error
, kSecCFErrorPath
, path
);
1387 void SecStaticCode::validateOtherVersions(CFURLRef path
, SecCSFlags flags
, SecRequirementRef req
, SecStaticCode
*code
)
1389 // Find out what current points to and do not revalidate
1390 std::string mainPath
= cfStringRelease(code
->diskRep()->copyCanonicalPath());
1392 char main_path
[PATH_MAX
];
1393 bool foundTarget
= false;
1395 /* If it failed to get the target of the symlink, do not fail. It is a performance loss,
1396 not a security hole */
1397 if (realpath(mainPath
.c_str(), main_path
) != NULL
)
1400 std::ostringstream versionsPath
;
1401 versionsPath
<< cfString(path
) << "/Versions/";
1403 DirScanner
scanner(versionsPath
.str());
1405 if (scanner
.initialized()) {
1406 struct dirent
*entry
= NULL
;
1407 while ((entry
= scanner
.getNext()) != NULL
) {
1408 std::ostringstream fullPath
;
1410 if (entry
->d_type
!= DT_DIR
|| strcmp(entry
->d_name
, "Current") == 0)
1413 fullPath
<< versionsPath
.str() << entry
->d_name
;
1415 char real_full_path
[PATH_MAX
];
1416 if (realpath(fullPath
.str().c_str(), real_full_path
) == NULL
)
1417 UnixError::check(-1);
1419 // Do case insensitive comparions because realpath() was called for both paths
1420 if (foundTarget
&& strcmp(main_path
, real_full_path
) == 0)
1423 SecPointer
<SecStaticCode
> frameworkVersion
= new SecStaticCode(DiskRep::bestGuess(real_full_path
));
1424 frameworkVersion
->initializeFromParent(*this);
1425 frameworkVersion
->staticValidate(flags
, SecRequirement::required(req
));
1432 // Test a CodeDirectory flag.
1433 // Returns false if there is no CodeDirectory.
1434 // May throw if the CodeDirectory is present but somehow invalid.
1436 bool SecStaticCode::flag(uint32_t tested
)
1438 if (const CodeDirectory
*cd
= this->codeDirectory(false))
1439 return cd
->flags
& tested
;
1446 // Retrieve the full SuperBlob containing all internal requirements.
1448 const Requirements
*SecStaticCode::internalRequirements()
1450 if (CFDataRef reqData
= component(cdRequirementsSlot
)) {
1451 const Requirements
*req
= (const Requirements
*)CFDataGetBytePtr(reqData
);
1452 if (!req
->validateBlob())
1453 MacOSError::throwMe(errSecCSReqInvalid
);
1461 // Retrieve a particular internal requirement by type.
1463 const Requirement
*SecStaticCode::internalRequirement(SecRequirementType type
)
1465 if (const Requirements
*reqs
= internalRequirements())
1466 return reqs
->find
<Requirement
>(type
);
1473 // Return the Designated Requirement (DR). This can be either explicit in the
1474 // Internal Requirements component, or implicitly generated on demand here.
1475 // Note that an explicit DR may have been implicitly generated at signing time;
1476 // we don't distinguish this case.
1478 const Requirement
*SecStaticCode::designatedRequirement()
1480 if (const Requirement
*req
= internalRequirement(kSecDesignatedRequirementType
)) {
1481 return req
; // explicit in signing data
1483 if (!mDesignatedReq
)
1484 mDesignatedReq
= defaultDesignatedRequirement();
1485 return mDesignatedReq
;
1491 // Generate the default Designated Requirement (DR) for this StaticCode.
1492 // Ignore any explicit DR it may contain.
1494 const Requirement
*SecStaticCode::defaultDesignatedRequirement()
1496 if (flag(kSecCodeSignatureAdhoc
)) {
1497 // adhoc signature: return a cdhash requirement for all architectures
1498 __block
Requirement::Maker maker
;
1499 Requirement::Maker::Chain
chain(maker
, opOr
);
1501 // insert cdhash requirement for all architectures
1502 __block CFRef
<CFMutableArrayRef
> allHashes
= CFArrayCreateMutableCopy(NULL
, 0, this->cdHashes());
1503 handleOtherArchitectures(^(SecStaticCode
*other
) {
1504 CFArrayRef hashes
= other
->cdHashes();
1505 CFArrayAppendArray(allHashes
, hashes
, CFRangeMake(0, CFArrayGetCount(hashes
)));
1507 CFIndex count
= CFArrayGetCount(allHashes
);
1508 for (CFIndex n
= 0; n
< count
; ++n
) {
1510 maker
.cdhash(CFDataRef(CFArrayGetValueAtIndex(allHashes
, n
)));
1512 return maker
.make();
1514 // full signature: Gin up full context and let DRMaker do its thing
1515 validateDirectory(); // need the cert chain
1516 Requirement::Context
context(this->certificates(),
1517 this->infoDictionary(),
1518 this->entitlements(),
1520 this->codeDirectory()
1522 return DRMaker(context
).make();
1528 // Validate a SecStaticCode against the internal requirement of a particular type.
1530 void SecStaticCode::validateRequirements(SecRequirementType type
, SecStaticCode
*target
,
1531 OSStatus nullError
/* = errSecSuccess */)
1533 DTRACK(CODESIGN_EVAL_STATIC_INTREQ
, this, type
, target
, nullError
);
1534 if (const Requirement
*req
= internalRequirement(type
))
1535 target
->validateRequirement(req
, nullError
? nullError
: errSecCSReqFailed
);
1537 MacOSError::throwMe(nullError
);
1543 // Validate this StaticCode against an external Requirement
1545 bool SecStaticCode::satisfiesRequirement(const Requirement
*req
, OSStatus failure
)
1547 bool result
= false;
1549 validateDirectory();
1550 result
= req
->validates(Requirement::Context(mCertChain
, infoDictionary(), entitlements(), codeDirectory()->identifier(), codeDirectory()), failure
);
1554 void SecStaticCode::validateRequirement(const Requirement
*req
, OSStatus failure
)
1556 if (!this->satisfiesRequirement(req
, failure
))
1557 MacOSError::throwMe(failure
);
1561 // Retrieve one certificate from the cert chain.
1562 // Positive and negative indices can be used:
1563 // [ leaf, intermed-1, ..., intermed-n, anchor ]
1565 // Returns NULL if unavailable for any reason.
1567 SecCertificateRef
SecStaticCode::cert(int ix
)
1569 validateDirectory(); // need cert chain
1571 CFIndex length
= CFArrayGetCount(mCertChain
);
1574 if (ix
>= 0 && ix
< length
)
1575 return SecCertificateRef(CFArrayGetValueAtIndex(mCertChain
, ix
));
1580 CFArrayRef
SecStaticCode::certificates()
1582 validateDirectory(); // need cert chain
1588 // Gather (mostly) API-official information about this StaticCode.
1590 // This method lives in the twilight between the API and internal layers,
1591 // since it generates API objects (Sec*Refs) for return.
1593 CFDictionaryRef
SecStaticCode::signingInformation(SecCSFlags flags
)
1596 // Start with the pieces that we return even for unsigned code.
1597 // This makes Sec[Static]CodeRefs useful as API-level replacements
1598 // of our internal OSXCode objects.
1600 CFRef
<CFMutableDictionaryRef
> dict
= makeCFMutableDictionary(1,
1601 kSecCodeInfoMainExecutable
, CFTempURL(this->mainExecutablePath()).get()
1605 // If we're not signed, this is all you get
1607 if (!this->isSigned())
1608 return dict
.yield();
1611 // Add the generic attributes that we always include
1613 CFDictionaryAddValue(dict
, kSecCodeInfoIdentifier
, CFTempString(this->identifier()));
1614 CFDictionaryAddValue(dict
, kSecCodeInfoFlags
, CFTempNumber(this->codeDirectory(false)->flags
.get()));
1615 CFDictionaryAddValue(dict
, kSecCodeInfoFormat
, CFTempString(this->format()));
1616 CFDictionaryAddValue(dict
, kSecCodeInfoSource
, CFTempString(this->signatureSource()));
1617 CFDictionaryAddValue(dict
, kSecCodeInfoUnique
, this->cdHash());
1618 CFDictionaryAddValue(dict
, kSecCodeInfoCdHashes
, this->cdHashes());
1619 const CodeDirectory
* cd
= this->codeDirectory(false);
1620 CFDictionaryAddValue(dict
, kSecCodeInfoDigestAlgorithm
, CFTempNumber(cd
->hashType
));
1621 CFRef
<CFArrayRef
> digests
= makeCFArrayFrom(^CFTypeRef(CodeDirectory::HashAlgorithm type
) { return CFTempNumber(type
); }, hashAlgorithms());
1622 CFDictionaryAddValue(dict
, kSecCodeInfoDigestAlgorithms
, digests
);
1624 CFDictionaryAddValue(dict
, kSecCodeInfoPlatformIdentifier
, CFTempNumber(cd
->platform
));
1627 // Deliver any Info.plist only if it looks intact
1630 if (CFDictionaryRef info
= this->infoDictionary())
1631 CFDictionaryAddValue(dict
, kSecCodeInfoPList
, info
);
1632 } catch (...) { } // don't deliver Info.plist if questionable
1635 // kSecCSSigningInformation adds information about signing certificates and chains
1637 if (flags
& kSecCSSigningInformation
)
1639 if (CFDataRef sig
= this->signature())
1640 CFDictionaryAddValue(dict
, kSecCodeInfoCMS
, sig
);
1641 if (const char *teamID
= this->teamID())
1642 CFDictionaryAddValue(dict
, kSecCodeInfoTeamIdentifier
, CFTempString(teamID
));
1644 CFDictionaryAddValue(dict
, kSecCodeInfoTrust
, mTrust
);
1645 if (CFArrayRef certs
= this->certificates())
1646 CFDictionaryAddValue(dict
, kSecCodeInfoCertificates
, certs
);
1647 if (CFAbsoluteTime time
= this->signingTime())
1648 if (CFRef
<CFDateRef
> date
= CFDateCreate(NULL
, time
))
1649 CFDictionaryAddValue(dict
, kSecCodeInfoTime
, date
);
1650 if (CFAbsoluteTime time
= this->signingTimestamp())
1651 if (CFRef
<CFDateRef
> date
= CFDateCreate(NULL
, time
))
1652 CFDictionaryAddValue(dict
, kSecCodeInfoTimestamp
, date
);
1656 // kSecCSRequirementInformation adds information on requirements
1658 if (flags
& kSecCSRequirementInformation
)
1660 if (const Requirements
*reqs
= this->internalRequirements()) {
1661 CFDictionaryAddValue(dict
, kSecCodeInfoRequirements
,
1662 CFTempString(Dumper::dump(reqs
)));
1663 CFDictionaryAddValue(dict
, kSecCodeInfoRequirementData
, CFTempData(*reqs
));
1666 const Requirement
*dreq
= this->designatedRequirement();
1667 CFRef
<SecRequirementRef
> dreqRef
= (new SecRequirement(dreq
))->handle();
1668 CFDictionaryAddValue(dict
, kSecCodeInfoDesignatedRequirement
, dreqRef
);
1669 if (this->internalRequirement(kSecDesignatedRequirementType
)) { // explicit
1670 CFRef
<SecRequirementRef
> ddreqRef
= (new SecRequirement(this->defaultDesignatedRequirement(), true))->handle();
1671 CFDictionaryAddValue(dict
, kSecCodeInfoImplicitDesignatedRequirement
, ddreqRef
);
1672 } else { // implicit
1673 CFDictionaryAddValue(dict
, kSecCodeInfoImplicitDesignatedRequirement
, dreqRef
);
1678 if (CFDataRef ent
= this->component(cdEntitlementSlot
)) {
1679 CFDictionaryAddValue(dict
, kSecCodeInfoEntitlements
, ent
);
1680 if (CFDictionaryRef entdict
= this->entitlements())
1681 CFDictionaryAddValue(dict
, kSecCodeInfoEntitlementsDict
, entdict
);
1686 // kSecCSInternalInformation adds internal information meant to be for Apple internal
1687 // use (SPI), and not guaranteed to be stable. Primarily, this is data we want
1688 // to reliably transmit through the API wall so that code outside the Security.framework
1689 // can use it without having to play nasty tricks to get it.
1691 if (flags
& kSecCSInternalInformation
) {
1694 CFDictionaryAddValue(dict
, kSecCodeInfoCodeDirectory
, mDir
);
1695 CFDictionaryAddValue(dict
, kSecCodeInfoCodeOffset
, CFTempNumber(mRep
->signingBase()));
1696 if (CFRef
<CFDictionaryRef
> rdict
= getDictionary(cdResourceDirSlot
, false)) // suppress validation
1697 CFDictionaryAddValue(dict
, kSecCodeInfoResourceDirectory
, rdict
);
1698 if (CFRef
<CFDictionaryRef
> ddict
= diskRepInformation())
1699 CFDictionaryAddValue(dict
, kSecCodeInfoDiskRepInfo
, ddict
);
1705 // kSecCSContentInformation adds more information about the physical layout
1706 // of the signed code. This is (only) useful for packaging or patching-oriented
1709 if (flags
& kSecCSContentInformation
)
1710 if (CFRef
<CFArrayRef
> files
= mRep
->modifiedFiles())
1711 CFDictionaryAddValue(dict
, kSecCodeInfoChangedFiles
, files
);
1713 return dict
.yield();
1718 // Resource validation contexts.
1719 // The default context simply throws a CSError, rudely terminating the operation.
1721 SecStaticCode::ValidationContext::~ValidationContext()
1724 void SecStaticCode::ValidationContext::reportProblem(OSStatus rc
, CFStringRef type
, CFTypeRef value
)
1726 CSError::throwMe(rc
, type
, value
);
1729 void SecStaticCode::CollectingContext::reportProblem(OSStatus rc
, CFStringRef type
, CFTypeRef value
)
1731 StLock
<Mutex
> _(mLock
);
1732 if (mStatus
== errSecSuccess
)
1733 mStatus
= rc
; // record first failure for eventual error return
1736 mCollection
.take(makeCFMutableDictionary());
1737 CFMutableArrayRef element
= CFMutableArrayRef(CFDictionaryGetValue(mCollection
, type
));
1739 element
= makeCFMutableArray(0);
1742 CFDictionaryAddValue(mCollection
, type
, element
);
1745 CFArrayAppendValue(element
, value
);
1749 void SecStaticCode::CollectingContext::throwMe()
1751 assert(mStatus
!= errSecSuccess
);
1752 throw CSError(mStatus
, mCollection
.retain());
1757 // Master validation driver.
1758 // This is the static validation (only) driver for the API.
1760 // SecStaticCode exposes an a la carte menu of topical validators applying
1761 // to a given object. The static validation API pulls them together reliably,
1762 // but it also adds three matrix dimensions: architecture (for "fat" Mach-O binaries),
1763 // nested code, and multiple digests. This function will crawl a suitable cross-section of this
1764 // validation matrix based on which options it is given, creating temporary
1765 // SecStaticCode objects on the fly to complete the task.
1766 // (The point, of course, is to do as little duplicate work as possible.)
1768 void SecStaticCode::staticValidate(SecCSFlags flags
, const SecRequirement
*req
)
1770 setValidationFlags(flags
);
1772 // initialize progress/cancellation state
1773 if (flags
& kSecCSReportProgress
)
1774 prepareProgress(estimateResourceWorkload() + 2); // +1 head, +1 tail
1776 // core components: once per architecture (if any)
1777 this->staticValidateCore(flags
, req
);
1778 if (flags
& kSecCSCheckAllArchitectures
)
1779 handleOtherArchitectures(^(SecStaticCode
* subcode
) {
1780 if (flags
& kSecCSCheckGatekeeperArchitectures
) {
1781 Universal
*fat
= subcode
->diskRep()->mainExecutableImage();
1782 assert(fat
&& fat
->narrowed()); // handleOtherArchitectures gave us a focused architecture slice
1783 Architecture arch
= fat
->bestNativeArch(); // actually, the ONLY one
1784 if ((arch
.cpuType() & ~CPU_ARCH_MASK
) == CPU_TYPE_POWERPC
)
1785 return; // irrelevant to Gatekeeper
1787 subcode
->detachedSignature(this->mDetachedSig
); // carry over explicit (but not implicit) detached signature
1788 subcode
->staticValidateCore(flags
, req
);
1792 // allow monitor intervention in source validation phase
1793 reportEvent(CFSTR("prepared"), NULL
);
1795 // resources: once for all architectures
1796 if (!(flags
& kSecCSDoNotValidateResources
))
1797 this->validateResources(flags
);
1799 // perform strict validation if desired
1800 if (flags
& kSecCSStrictValidate
)
1801 mRep
->strictValidate(codeDirectory(), mTolerateErrors
, mValidationFlags
);
1804 // allow monitor intervention
1805 if (CFRef
<CFTypeRef
> veto
= reportEvent(CFSTR("validated"), NULL
)) {
1806 if (CFGetTypeID(veto
) == CFNumberGetTypeID())
1807 MacOSError::throwMe(cfNumber
<OSStatus
>(veto
.as
<CFNumberRef
>()));
1809 MacOSError::throwMe(errSecCSBadCallbackValue
);
1813 void SecStaticCode::staticValidateCore(SecCSFlags flags
, const SecRequirement
*req
)
1816 this->validateNonResourceComponents(); // also validates the CodeDirectory
1817 this->validateTopDirectory();
1818 if (!(flags
& kSecCSDoNotValidateExecutable
))
1819 this->validateExecutable();
1821 this->validateRequirement(req
->requirement(), errSecCSReqFailed
);
1822 } catch (CSError
&err
) {
1823 if (Universal
*fat
= this->diskRep()->mainExecutableImage()) // Mach-O
1824 if (MachO
*mach
= fat
->architecture()) {
1825 err
.augment(kSecCFErrorArchitecture
, CFTempString(mach
->architecture().displayName()));
1829 } catch (const MacOSError
&err
) {
1830 // add architecture information if we can get it
1831 if (Universal
*fat
= this->diskRep()->mainExecutableImage())
1832 if (MachO
*mach
= fat
->architecture()) {
1833 CFTempString
arch(mach
->architecture().displayName());
1835 CSError::throwMe(err
.error
, kSecCFErrorArchitecture
, arch
);
1843 // A helper that generates SecStaticCode objects for all but the primary architecture
1844 // of a fat binary and calls a block on them.
1845 // If there's only one architecture (or this is an architecture-agnostic code),
1846 // nothing happens quickly.
1848 void SecStaticCode::handleOtherArchitectures(void (^handle
)(SecStaticCode
* other
))
1850 if (Universal
*fat
= this->diskRep()->mainExecutableImage()) {
1851 Universal::Architectures architectures
;
1852 fat
->architectures(architectures
);
1853 if (architectures
.size() > 1) {
1854 DiskRep::Context ctx
;
1855 size_t activeOffset
= fat
->archOffset();
1856 for (Universal::Architectures::const_iterator arch
= architectures
.begin(); arch
!= architectures
.end(); ++arch
) {
1857 ctx
.offset
= fat
->archOffset(*arch
);
1858 if (ctx
.offset
> SIZE_MAX
)
1859 MacOSError::throwMe(errSecCSBadObjectFormat
);
1860 ctx
.size
= fat
->lengthOfSlice((size_t)ctx
.offset
);
1861 if (ctx
.offset
!= activeOffset
) { // inactive architecture; check it
1862 SecPointer
<SecStaticCode
> subcode
= new SecStaticCode(DiskRep::bestGuess(this->mainExecutablePath(), &ctx
));
1863 subcode
->detachedSignature(this->mDetachedSig
); // carry over explicit (but not implicit) detached signature
1864 if (this->teamID() == NULL
|| subcode
->teamID() == NULL
) {
1865 if (this->teamID() != subcode
->teamID())
1866 MacOSError::throwMe(errSecCSSignatureInvalid
);
1867 } else if (strcmp(this->teamID(), subcode
->teamID()) != 0)
1868 MacOSError::throwMe(errSecCSSignatureInvalid
);
1877 // A method that takes a certificate chain (certs) and evaluates
1878 // if it is a Mac or IPhone developer cert, an app store distribution cert,
1879 // or a developer ID
1881 bool SecStaticCode::isAppleDeveloperCert(CFArrayRef certs
)
1883 static const std::string appleDeveloperRequirement
= "(" + std::string(WWDRRequirement
) + ") or (" + MACWWDRRequirement
+ ") or (" + developerID
+ ") or (" + distributionCertificate
+ ") or (" + iPhoneDistributionCert
+ ")";
1884 SecPointer
<SecRequirement
> req
= new SecRequirement(parseRequirement(appleDeveloperRequirement
), true);
1885 Requirement::Context
ctx(certs
, NULL
, NULL
, "", NULL
);
1887 return req
->requirement()->validates(ctx
);
1890 } // end namespace CodeSigning
1891 } // end namespace Security