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"
32 #include "notarization.h"
34 #include "reqdumper.h"
35 #include "reqparser.h"
37 #include "resources.h"
38 #include "detachedrep.h"
39 #include "signerutils.h"
41 #include "csdatabase.h"
43 #include "dirscanner.h"
44 #include <CoreFoundation/CFURLAccess.h>
45 #include <Security/SecPolicyPriv.h>
46 #include <Security/SecTrustPriv.h>
47 #include <Security/SecCertificatePriv.h>
49 #include <Security/CMSPrivate.h>
51 #import <Security/SecCMS.h>
52 #include <Security/SecCmsContentInfo.h>
53 #include <Security/SecCmsSignerInfo.h>
54 #include <Security/SecCmsSignedData.h>
56 #include <Security/cssmapplePriv.h>
58 #include <security_utilities/unix++.h>
59 #include <security_utilities/cfmunge.h>
60 #include <security_utilities/casts.h>
61 #include <Security/CMSDecoder.h>
62 #include <security_utilities/logging.h>
64 #include <sys/xattr.h>
66 #include <IOKit/storage/IOStorageDeviceCharacteristics.h>
67 #include <dispatch/private.h>
68 #include <os/assumes.h>
70 #import <utilities/entitlements.h>
74 namespace CodeSigning
{
76 using namespace UnixPlusPlus
;
78 // A requirement representing a Mac or iOS dev cert, a Mac or iOS distribution cert, or a developer ID
79 static const char WWDRRequirement
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.2] exists";
80 static const char MACWWDRRequirement
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.12] exists";
81 static const char developerID
[] = "anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists"
82 " and certificate leaf[field.1.2.840.113635.100.6.1.13] exists";
83 static const char distributionCertificate
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.7] exists";
84 static const char iPhoneDistributionCert
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.4] exists";
87 // Map a component slot number to a suitable error code for a failure
89 static inline OSStatus
errorForSlot(CodeDirectory::SpecialSlot slot
)
93 return errSecCSInfoPlistFailed
;
94 case cdResourceDirSlot
:
95 return errSecCSResourceDirectoryFailed
;
97 return errSecCSSignatureFailed
;
103 // Construct a SecStaticCode object given a disk representation object
105 SecStaticCode::SecStaticCode(DiskRep
*rep
, uint32_t flags
)
106 : mCheckfix30814861builder1(NULL
),
108 mValidated(false), mExecutableValidated(false), mResourcesValidated(false), mResourcesValidContext(NULL
),
109 mProgressQueue("com.apple.security.validation-progress", false, QOS_CLASS_UNSPECIFIED
),
110 mOuterScope(NULL
), mResourceScope(NULL
),
111 mDesignatedReq(NULL
), mGotResourceBase(false), mMonitor(NULL
), mLimitedAsync(NULL
),
112 mFlags(flags
), mNotarizationChecked(false), mStaplingChecked(false), mNotarizationDate(NAN
)
113 , mTrustedSigningCertChain(false)
116 CODESIGN_STATIC_CREATE(this, rep
);
118 checkForSystemSignature();
124 // Clean up a SecStaticCode object
126 SecStaticCode::~SecStaticCode() _NOEXCEPT
128 ::free(const_cast<Requirement
*>(mDesignatedReq
));
129 delete mResourcesValidContext
;
130 delete mLimitedAsync
;
131 delete mCheckfix30814861builder1
;
137 // Initialize a nested SecStaticCode object from its parent
139 void SecStaticCode::initializeFromParent(const SecStaticCode
& parent
) {
140 mOuterScope
= &parent
;
141 setMonitor(parent
.monitor());
142 if (parent
.mLimitedAsync
)
143 mLimitedAsync
= new LimitedAsync(*parent
.mLimitedAsync
);
147 // CF-level comparison of SecStaticCode objects compares CodeDirectory hashes if signed,
148 // and falls back on comparing canonical paths if (both are) not.
150 bool SecStaticCode::equal(SecCFObject
&secOther
)
152 SecStaticCode
*other
= static_cast<SecStaticCode
*>(&secOther
);
153 CFDataRef mine
= this->cdHash();
154 CFDataRef his
= other
->cdHash();
156 return mine
&& his
&& CFEqual(mine
, his
);
158 return CFEqual(CFRef
<CFURLRef
>(this->copyCanonicalPath()), CFRef
<CFURLRef
>(other
->copyCanonicalPath()));
161 CFHashCode
SecStaticCode::hash()
163 if (CFDataRef h
= this->cdHash())
166 return CFHash(CFRef
<CFURLRef
>(this->copyCanonicalPath()));
171 // Invoke a stage monitor if registered
173 CFTypeRef
SecStaticCode::reportEvent(CFStringRef stage
, CFDictionaryRef info
)
176 return mMonitor(this->handle(false), stage
, info
);
181 void SecStaticCode::prepareProgress(unsigned int workload
)
183 dispatch_sync(mProgressQueue
, ^{
184 mCancelPending
= false; // not canceled
186 if (mValidationFlags
& kSecCSReportProgress
) {
187 mCurrentWork
= 0; // nothing done yet
188 mTotalWork
= workload
; // totally fake - we don't know how many files we'll get to chew
192 void SecStaticCode::reportProgress(unsigned amount
/* = 1 */)
194 if (mMonitor
&& (mValidationFlags
& kSecCSReportProgress
)) {
195 // update progress and report
196 __block
bool cancel
= false;
197 dispatch_sync(mProgressQueue
, ^{
200 mCurrentWork
+= amount
;
201 mMonitor(this->handle(false), CFSTR("progress"), CFTemp
<CFDictionaryRef
>("{current=%d,total=%d}", mCurrentWork
, mTotalWork
));
203 // if cancellation is pending, abort now
205 MacOSError::throwMe(errSecCSCancelled
);
211 // Set validation conditions for fine-tuning legacy tolerance
213 static void addError(CFTypeRef cfError
, void* context
)
215 if (CFGetTypeID(cfError
) == CFNumberGetTypeID()) {
217 CFNumberGetValue(CFNumberRef(cfError
), kCFNumberSInt64Type
, (void*)&error
);
218 MacOSErrorSet
* errors
= (MacOSErrorSet
*)context
;
219 errors
->insert(OSStatus(error
));
223 void SecStaticCode::setValidationModifiers(CFDictionaryRef conditions
)
226 CFDictionary
source(conditions
, errSecCSDbCorrupt
);
227 mAllowOmissions
= source
.get
<CFArrayRef
>("omissions");
228 if (CFArrayRef errors
= source
.get
<CFArrayRef
>("errors"))
229 CFArrayApplyFunction(errors
, CFRangeMake(0, CFArrayGetCount(errors
)), addError
, &this->mTolerateErrors
);
235 // Request cancellation of a validation in progress.
236 // We do this by posting an abort flag that is checked periodically.
238 void SecStaticCode::cancelValidation()
240 if (!(mValidationFlags
& kSecCSReportProgress
)) // not using progress reporting; cancel won't make it through
241 MacOSError::throwMe(errSecCSInvalidFlags
);
242 dispatch_assert_queue(mProgressQueue
);
243 mCancelPending
= true;
248 // Attach a detached signature.
250 void SecStaticCode::detachedSignature(CFDataRef sigData
)
253 mDetachedSig
= sigData
;
254 mRep
= new DetachedRep(sigData
, mRep
->base(), "explicit detached");
255 CODESIGN_STATIC_ATTACH_EXPLICIT(this, mRep
);
259 CODESIGN_STATIC_ATTACH_EXPLICIT(this, NULL
);
265 // Consult the system detached signature database to see if it contains
266 // a detached signature for this StaticCode. If it does, fetch and attach it.
267 // We do this only if the code has no signature already attached.
269 void SecStaticCode::checkForSystemSignature()
272 if (!this->isSigned()) {
273 SignatureDatabase db
;
276 if (RefPointer
<DiskRep
> dsig
= db
.findCode(mRep
)) {
277 CODESIGN_STATIC_ATTACH_SYSTEM(this, dsig
);
284 MacOSError::throwMe(errSecUnimplemented
);
290 // Return a descriptive string identifying the source of the code signature
292 string
SecStaticCode::signatureSource()
296 if (DetachedRep
*rep
= dynamic_cast<DetachedRep
*>(mRep
.get()))
297 return rep
->source();
303 // Do ::required, but convert incoming SecCodeRefs to their SecStaticCodeRefs
306 SecStaticCode
*SecStaticCode::requiredStatic(SecStaticCodeRef ref
)
308 SecCFObject
*object
= SecCFObject::required(ref
, errSecCSInvalidObjectRef
);
309 if (SecStaticCode
*scode
= dynamic_cast<SecStaticCode
*>(object
))
311 else if (SecCode
*code
= dynamic_cast<SecCode
*>(object
))
312 return code
->staticCode();
313 else // neither (a SecSomethingElse)
314 MacOSError::throwMe(errSecCSInvalidObjectRef
);
317 SecCode
*SecStaticCode::optionalDynamic(SecStaticCodeRef ref
)
319 SecCFObject
*object
= SecCFObject::required(ref
, errSecCSInvalidObjectRef
);
320 if (dynamic_cast<SecStaticCode
*>(object
))
322 else if (SecCode
*code
= dynamic_cast<SecCode
*>(object
))
324 else // neither (a SecSomethingElse)
325 MacOSError::throwMe(errSecCSInvalidObjectRef
);
330 // Void all cached validity data.
332 // We also throw out cached components, because the new signature data may have
333 // a different idea of what components should be present. We could reconcile the
334 // cached data instead, if performance seems to be impacted.
336 void SecStaticCode::resetValidity()
338 CODESIGN_EVAL_STATIC_RESET(this);
340 mExecutableValidated
= mResourcesValidated
= false;
341 if (mResourcesValidContext
) {
342 delete mResourcesValidContext
;
343 mResourcesValidContext
= NULL
;
346 mCodeDirectories
.clear();
348 for (unsigned n
= 0; n
< cdSlotCount
; n
++)
351 mEntitlements
= NULL
;
352 mResourceDict
= NULL
;
353 mDesignatedReq
= NULL
;
355 mGotResourceBase
= false;
358 mNotarizationChecked
= false;
359 mStaplingChecked
= false;
360 mNotarizationDate
= NAN
;
364 // we may just have updated the system database, so check again
365 checkForSystemSignature();
371 // Retrieve a sealed component by special slot index.
372 // If the CodeDirectory has already been validated, validate against that.
373 // Otherwise, retrieve the component without validation (but cache it). Validation
374 // will go through the cache and validate all cached components.
376 CFDataRef
SecStaticCode::component(CodeDirectory::SpecialSlot slot
, OSStatus fail
/* = errSecCSSignatureFailed */)
378 assert(slot
<= cdSlotMax
);
380 CFRef
<CFDataRef
> &cache
= mCache
[slot
];
382 if (CFRef
<CFDataRef
> data
= mRep
->component(slot
)) {
383 if (validated()) { // if the directory has been validated...
384 if (!codeDirectory()->slotIsPresent(-slot
))
387 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data
), // ... and it's no good
388 CFDataGetLength(data
), -slot
, false))
389 MacOSError::throwMe(errorForSlot(slot
)); // ... then bail
391 cache
= data
; // it's okay, cache it
392 } else { // absent, mark so
393 if (validated()) // if directory has been validated...
394 if (codeDirectory()->slotIsPresent(-slot
)) // ... and the slot is NOT missing
395 MacOSError::throwMe(errorForSlot(slot
)); // was supposed to be there
396 cache
= CFDataRef(kCFNull
); // white lie
399 return (cache
== CFDataRef(kCFNull
)) ? NULL
: cache
.get();
404 // Get the CodeDirectories.
405 // Throws (if check==true) or returns NULL (check==false) if there are none.
406 // Always throws if the CodeDirectories exist but are invalid.
407 // NEVER validates against the signature.
409 const SecStaticCode::CodeDirectoryMap
*
410 SecStaticCode::codeDirectories(bool check
/* = true */) const
412 if (mCodeDirectories
.empty()) {
414 loadCodeDirectories(mCodeDirectories
);
418 // We wanted a NON-checked peek and failed to safely decode the existing CodeDirectories.
419 // Pretend this is unsigned, but make sure we didn't somehow cache an invalid CodeDirectory.
420 if (!mCodeDirectories
.empty()) {
422 Syslog::warning("code signing internal problem: mCodeDirectories set despite exception exit");
423 MacOSError::throwMe(errSecCSInternalError
);
427 return &mCodeDirectories
;
429 if (!mCodeDirectories
.empty()) {
430 return &mCodeDirectories
;
433 MacOSError::throwMe(errSecCSUnsigned
);
439 // Get the CodeDirectory.
440 // Throws (if check==true) or returns NULL (check==false) if there is none.
441 // Always throws if the CodeDirectory exists but is invalid.
442 // NEVER validates against the signature.
444 const CodeDirectory
*SecStaticCode::codeDirectory(bool check
/* = true */) const
447 // pick our favorite CodeDirectory from the choices we've got
449 CodeDirectoryMap
const *candidates
= codeDirectories(check
);
450 if (candidates
!= NULL
) {
451 CodeDirectory::HashAlgorithm type
= CodeDirectory::bestHashOf(mHashAlgorithms
);
452 mDir
= candidates
->at(type
); // and the winner is...
457 // We wanted a NON-checked peek and failed to safely decode the existing CodeDirectory.
458 // Pretend this is unsigned, but make sure we didn't somehow cache an invalid CodeDirectory.
461 Syslog::warning("code signing internal problem: mDir set despite exception exit");
462 MacOSError::throwMe(errSecCSInternalError
);
467 return reinterpret_cast<const CodeDirectory
*>(CFDataGetBytePtr(mDir
));
469 MacOSError::throwMe(errSecCSUnsigned
);
475 // Fetch an array of all available CodeDirectories.
476 // Returns false if unsigned (no classic CD slot), true otherwise.
478 bool SecStaticCode::loadCodeDirectories(CodeDirectoryMap
& cdMap
) const
480 __block CodeDirectoryMap candidates
;
481 __block
CodeDirectory::HashAlgorithms hashAlgorithms
;
482 __block CFRef
<CFDataRef
> baseDir
;
483 auto add
= ^bool (CodeDirectory::SpecialSlot slot
){
484 CFRef
<CFDataRef
> cdData
= diskRep()->component(slot
);
487 const CodeDirectory
* cd
= reinterpret_cast<const CodeDirectory
*>(CFDataGetBytePtr(cdData
));
488 if (!cd
->validateBlob(CFDataGetLength(cdData
)))
489 MacOSError::throwMe(errSecCSSignatureFailed
); // no recovery - any suspect CD fails
490 cd
->checkIntegrity();
491 auto result
= candidates
.insert(make_pair(cd
->hashType
, cdData
.get()));
493 MacOSError::throwMe(errSecCSSignatureInvalid
); // duplicate hashType, go to heck
494 hashAlgorithms
.insert(cd
->hashType
);
495 if (slot
== cdCodeDirectorySlot
)
499 if (!add(cdCodeDirectorySlot
))
500 return false; // no classic slot CodeDirectory -> unsigned
501 for (CodeDirectory::SpecialSlot slot
= cdAlternateCodeDirectorySlots
; slot
< cdAlternateCodeDirectoryLimit
; slot
++)
502 if (!add(slot
)) // no CodeDirectory at this slot -> end of alternates
504 if (candidates
.empty())
505 MacOSError::throwMe(errSecCSSignatureFailed
); // no viable CodeDirectory in sight
506 // commit to cached values
507 cdMap
.swap(candidates
);
508 mHashAlgorithms
.swap(hashAlgorithms
);
515 // Get the hash of the CodeDirectory.
516 // Returns NULL if there is none.
518 CFDataRef
SecStaticCode::cdHash()
521 if (const CodeDirectory
*cd
= codeDirectory(false)) {
522 mCDHash
.take(cd
->cdhash());
523 CODESIGN_STATIC_CDHASH(this, CFDataGetBytePtr(mCDHash
), (unsigned int)CFDataGetLength(mCDHash
));
531 // Get an array of the cdhashes for all digest types in this signature
532 // The array is sorted by cd->hashType.
534 CFArrayRef
SecStaticCode::cdHashes()
537 CFRef
<CFMutableArrayRef
> cdList
= makeCFMutableArray(0);
538 for (auto it
= mCodeDirectories
.begin(); it
!= mCodeDirectories
.end(); ++it
) {
539 const CodeDirectory
*cd
= (const CodeDirectory
*)CFDataGetBytePtr(it
->second
);
540 if (CFRef
<CFDataRef
> hash
= cd
->cdhash())
541 CFArrayAppendValue(cdList
, hash
);
543 mCDHashes
= cdList
.get();
549 // Get a dictionary of untruncated cdhashes for all digest types in this signature.
551 CFDictionaryRef
SecStaticCode::cdHashesFull()
553 if (!mCDHashFullDict
) {
554 CFRef
<CFMutableDictionaryRef
> cdDict
= makeCFMutableDictionary();
555 for (auto const &it
: mCodeDirectories
) {
556 CodeDirectory::HashAlgorithm alg
= it
.first
;
557 const CodeDirectory
*cd
= (const CodeDirectory
*)CFDataGetBytePtr(it
.second
);
558 CFRef
<CFDataRef
> hash
= cd
->cdhash(false);
560 CFDictionaryAddValue(cdDict
, CFTempNumber(alg
), hash
);
563 mCDHashFullDict
= cdDict
.get();
565 return mCDHashFullDict
;
570 // Return the CMS signature blob; NULL if none found.
572 CFDataRef
SecStaticCode::signature()
575 mSignature
.take(mRep
->signature());
578 MacOSError::throwMe(errSecCSUnsigned
);
583 // Verify the signature on the CodeDirectory.
584 // If this succeeds (doesn't throw), the CodeDirectory is statically trustworthy.
585 // Any outcome (successful or not) is cached for the lifetime of the StaticCode.
587 void SecStaticCode::validateDirectory()
589 // echo previous outcome, if any
590 // track revocation separately, as it may not have been checked
591 // during the initial validation
592 if (!validated() || ((mValidationFlags
& kSecCSEnforceRevocationChecks
) && !revocationChecked()))
594 // perform validation (or die trying)
595 CODESIGN_EVAL_STATIC_DIRECTORY(this);
596 mValidationExpired
= verifySignature();
597 if (mValidationFlags
& kSecCSEnforceRevocationChecks
)
598 mRevocationChecked
= true;
600 for (CodeDirectory::SpecialSlot slot
= codeDirectory()->maxSpecialSlot(); slot
>= 1; --slot
)
601 if (mCache
[slot
]) // if we already loaded that resource...
602 validateComponent(slot
, errorForSlot(slot
)); // ... then check it now
603 mValidated
= true; // we've done the deed...
604 mValidationResult
= errSecSuccess
; // ... and it was good
605 } catch (const CommonError
&err
) {
607 mValidationResult
= err
.osStatus();
610 secinfo("staticCode", "%p validation threw non-common exception", this);
612 Syslog::notice("code signing internal problem: unknown exception thrown by validation");
613 mValidationResult
= errSecCSInternalError
;
617 // XXX: Embedded doesn't have CSSMERR_TP_CERT_EXPIRED so we can't throw it
618 // XXX: This should be implemented for embedded once we implement
619 // XXX: verifySignature and see how we're going to handle expired certs
621 if (mValidationResult
== errSecSuccess
) {
622 if (mValidationExpired
)
623 if ((mValidationFlags
& kSecCSConsiderExpiration
)
624 || (codeDirectory()->flags
& kSecCodeSignatureForceExpiration
))
625 MacOSError::throwMe(CSSMERR_TP_CERT_EXPIRED
);
627 MacOSError::throwMe(mValidationResult
);
633 // Load and validate the CodeDirectory and all components *except* those related to the resource envelope.
634 // Those latter components are checked by validateResources().
636 void SecStaticCode::validateNonResourceComponents()
638 this->validateDirectory();
639 for (CodeDirectory::SpecialSlot slot
= codeDirectory()->maxSpecialSlot(); slot
>= 1; --slot
)
641 case cdResourceDirSlot
: // validated by validateResources
644 this->component(slot
); // loads and validates
651 // Check that any "top index" sealed into the signature conforms to what's actually here.
653 void SecStaticCode::validateTopDirectory()
655 assert(mDir
); // must already have loaded CodeDirectories
656 if (CFDataRef topDirectory
= component(cdTopDirectorySlot
)) {
657 const auto topData
= (const Endian
<uint32_t> *)CFDataGetBytePtr(topDirectory
);
658 const auto topDataEnd
= topData
+ CFDataGetLength(topDirectory
) / sizeof(*topData
);
659 std::vector
<uint32_t> signedVector(topData
, topDataEnd
);
661 std::vector
<uint32_t> foundVector
;
662 foundVector
.push_back(cdCodeDirectorySlot
); // mandatory
663 for (CodeDirectory::Slot slot
= 1; slot
<= cdSlotMax
; ++slot
)
665 foundVector
.push_back(slot
);
666 int alternateCount
= int(mCodeDirectories
.size() - 1); // one will go into cdCodeDirectorySlot
667 for (int n
= 0; n
< alternateCount
; n
++)
668 foundVector
.push_back(cdAlternateCodeDirectorySlots
+ n
);
669 foundVector
.push_back(cdSignatureSlot
); // mandatory (may be empty)
671 if (signedVector
!= foundVector
)
672 MacOSError::throwMe(errSecCSSignatureFailed
);
678 // Get the (signed) signing date from the code signature.
679 // Sadly, we need to validate the signature to get the date (as a side benefit).
680 // This means that you can't get the signing time for invalidly signed code.
682 // We could run the decoder "almost to" verification to avoid this, but there seems
683 // little practical point to such a duplication of effort.
685 CFAbsoluteTime
SecStaticCode::signingTime()
691 CFAbsoluteTime
SecStaticCode::signingTimestamp()
694 return mSigningTimestamp
;
698 #define kSecSHA256HashSize 32
699 // subject:/C=US/ST=California/L=San Jose/O=Adobe Systems Incorporated/OU=Information Systems/OU=Digital ID Class 3 - Microsoft Software Validation v2/CN=Adobe Systems Incorporated
700 // issuer :/C=US/O=VeriSign, Inc./OU=VeriSign Trust Network/OU=Terms of use at https://www.verisign.com/rpa (c)10/CN=VeriSign Class 3 Code Signing 2010 CA
701 // Not Before: Dec 15 00:00:00 2010 GMT
702 // Not After : Dec 14 23:59:59 2012 GMT
703 static const unsigned char ASI_CS_12
[] = {
704 0x77,0x82,0x9C,0x64,0x33,0x45,0x2E,0x4A,0xD3,0xA8,0xE4,0x6F,0x00,0x6C,0x27,0xEA,
705 0xFB,0xD3,0xF2,0x6D,0x50,0xF3,0x6F,0xE0,0xE9,0x6D,0x06,0x59,0x19,0xB5,0x46,0xFF
708 bool SecStaticCode::checkfix41082220(OSStatus cssmTrustResult
)
710 // only applicable to revoked results
711 if (cssmTrustResult
!= CSSMERR_TP_CERT_REVOKED
) {
715 // only this leaf certificate
716 if (CFArrayGetCount(mCertChain
) == 0) {
719 CFRef
<CFDataRef
> leafHash(SecCertificateCopySHA256Digest((SecCertificateRef
)CFArrayGetValueAtIndex(mCertChain
, 0)));
720 if (memcmp(ASI_CS_12
, CFDataGetBytePtr(leafHash
), kSecSHA256HashSize
) != 0) {
724 // detached dmg signature
725 if (!isDetached() || format() != std::string("disk image")) {
730 if (hashAlgorithms().size() != 1 || hashAlgorithm() != kSecCodeSignatureHashSHA1
) {
734 // not a privileged binary - no TeamID and no entitlements
735 if (component(cdEntitlementSlot
) || teamID()) {
739 // no flags and old version
740 if (codeDirectory()->version
!= 0x20100 || codeDirectory()->flags
!= 0) {
744 Security::Syslog::warning("CodeSigning: Check-fix enabled for dmg '%s' with identifier '%s' signed with revoked certificates",
745 mainExecutablePath().c_str(), identifier().c_str());
748 #endif // TARGET_OS_OSX
751 // Verify the CMS signature.
752 // This performs the cryptographic tango. It returns if the signature is valid,
753 // or throws if it is not. As a side effect, a successful return sets up the
754 // cached certificate chain for future use.
755 // Returns true if the signature is expired (the X.509 sense), false if it's not.
756 // Expiration is fatal (throws) if a secure timestamp is included, but not otherwise.
758 bool SecStaticCode::verifySignature()
760 // ad-hoc signed code is considered validly signed by definition
761 if (flag(kSecCodeSignatureAdhoc
)) {
762 CODESIGN_EVAL_STATIC_SIGNATURE_ADHOC(this);
766 DTRACK(CODESIGN_EVAL_STATIC_SIGNATURE
, this, (char*)this->mainExecutablePath().c_str());
768 if (!(mValidationFlags
& kSecCSApplyEmbeddedPolicy
)) {
769 // decode CMS and extract SecTrust for verification
770 CFRef
<CMSDecoderRef
> cms
;
771 MacOSError::check(CMSDecoderCreate(&cms
.aref())); // create decoder
772 CFDataRef sig
= this->signature();
773 MacOSError::check(CMSDecoderUpdateMessage(cms
, CFDataGetBytePtr(sig
), CFDataGetLength(sig
)));
774 this->codeDirectory(); // load CodeDirectory (sets mDir)
775 MacOSError::check(CMSDecoderSetDetachedContent(cms
, mBaseDir
));
776 MacOSError::check(CMSDecoderFinalizeMessage(cms
));
777 MacOSError::check(CMSDecoderSetSearchKeychain(cms
, cfEmptyArray()));
778 CFRef
<CFArrayRef
> vf_policies(createVerificationPolicies());
779 CFRef
<CFArrayRef
> ts_policies(createTimeStampingAndRevocationPolicies());
781 CMSSignerStatus status
;
782 MacOSError::check(CMSDecoderCopySignerStatus(cms
, 0, vf_policies
,
783 false, &status
, &mTrust
.aref(), NULL
));
785 if (status
!= kCMSSignerValid
) {
788 case kCMSSignerUnsigned
: reason
="kCMSSignerUnsigned"; break;
789 case kCMSSignerNeedsDetachedContent
: reason
="kCMSSignerNeedsDetachedContent"; break;
790 case kCMSSignerInvalidSignature
: reason
="kCMSSignerInvalidSignature"; break;
791 case kCMSSignerInvalidCert
: reason
="kCMSSignerInvalidCert"; break;
792 case kCMSSignerInvalidIndex
: reason
="kCMSSignerInvalidIndex"; break;
793 default: reason
="unknown"; break;
795 Security::Syslog::error("CMSDecoderCopySignerStatus failed with %s error (%d)",
796 reason
, (int)status
);
797 MacOSError::throwMe(errSecCSSignatureFailed
);
800 // retrieve auxiliary v1 data bag and verify against current state
801 CFRef
<CFDataRef
> hashAgilityV1
;
802 switch (OSStatus rc
= CMSDecoderCopySignerAppleCodesigningHashAgility(cms
, 0, &hashAgilityV1
.aref())) {
805 CFRef
<CFDictionaryRef
> hashDict
= makeCFDictionaryFrom(hashAgilityV1
);
806 CFArrayRef cdList
= CFArrayRef(CFDictionaryGetValue(hashDict
, CFSTR("cdhashes")));
807 CFArrayRef myCdList
= this->cdHashes();
809 /* Note that this is not very "agile": There's no way to calculate the exact
810 * list for comparison if it contains hash algorithms we don't know yet... */
811 if (cdList
== NULL
|| !CFEqual(cdList
, myCdList
))
812 MacOSError::throwMe(errSecCSSignatureFailed
);
815 case -1: /* CMS used to return this for "no attribute found", so tolerate it. Now returning noErr/NULL */
818 MacOSError::throwMe(rc
);
821 // retrieve auxiliary v2 data bag and verify against current state
822 CFRef
<CFDictionaryRef
> hashAgilityV2
;
823 switch (OSStatus rc
= CMSDecoderCopySignerAppleCodesigningHashAgilityV2(cms
, 0, &hashAgilityV2
.aref())) {
826 /* Require number of code directoris and entries in the hash agility
827 * dict to be the same size (no stripping out code directories).
829 if (CFDictionaryGetCount(hashAgilityV2
) != mCodeDirectories
.size()) {
830 MacOSError::throwMe(errSecCSSignatureFailed
);
833 /* Require every cdhash of every code directory whose hash
834 * algorithm we know to be in the agility dictionary.
836 * We check untruncated cdhashes here because we can.
838 bool foundOurs
= false;
839 for (auto& entry
: mCodeDirectories
) {
840 SECOidTag tag
= CodeDirectorySet::SECOidTagForAlgorithm(entry
.first
);
842 if (tag
== SEC_OID_UNKNOWN
) {
843 // Unknown hash algorithm, ignore.
847 CFRef
<CFNumberRef
> key
= makeCFNumber(int(tag
));
848 CFRef
<CFDataRef
> entryCdhash
;
849 entryCdhash
= (CFDataRef
)CFDictionaryGetValue(hashAgilityV2
, (void*)key
.get());
851 CodeDirectory
const *cd
= (CodeDirectory
const*)CFDataGetBytePtr(entry
.second
);
852 CFRef
<CFDataRef
> ourCdhash
= cd
->cdhash(false); // Untruncated cdhash!
853 if (!CFEqual(entryCdhash
, ourCdhash
)) {
854 MacOSError::throwMe(errSecCSSignatureFailed
);
857 if (entry
.first
== this->hashAlgorithm()) {
862 /* Require the cdhash of our chosen code directory to be in the dictionary.
863 * In theory, the dictionary could be full of unsupported cdhashes, but we
864 * really want ours, which is bound to be supported, to be covered.
867 MacOSError::throwMe(errSecCSSignatureFailed
);
871 case -1: /* CMS used to return this for "no attribute found", so tolerate it. Now returning noErr/NULL */
874 MacOSError::throwMe(rc
);
877 // internal signing time (as specified by the signer; optional)
878 mSigningTime
= 0; // "not present" marker (nobody could code sign on Jan 1, 2001 :-)
879 switch (OSStatus rc
= CMSDecoderCopySignerSigningTime(cms
, 0, &mSigningTime
)) {
881 case errSecSigningTimeMissing
:
884 Security::Syslog::error("Could not get signing time (error %d)", (int)rc
);
885 MacOSError::throwMe(rc
);
888 // certified signing time (as specified by a TSA; optional)
889 mSigningTimestamp
= 0;
890 switch (OSStatus rc
= CMSDecoderCopySignerTimestampWithPolicy(cms
, ts_policies
, 0, &mSigningTimestamp
)) {
892 case errSecTimestampMissing
:
895 Security::Syslog::error("Could not get timestamp (error %d)", (int)rc
);
896 MacOSError::throwMe(rc
);
899 // set up the environment for SecTrust
900 if (mValidationFlags
& kSecCSNoNetworkAccess
) {
901 MacOSError::check(SecTrustSetNetworkFetchAllowed(mTrust
,false)); // no network?
903 MacOSError::check(SecTrustSetKeychainsAllowed(mTrust
, false));
905 CSSM_APPLE_TP_ACTION_DATA actionData
= {
906 CSSM_APPLE_TP_ACTION_VERSION
, // version of data structure
910 if (!(mValidationFlags
& kSecCSCheckTrustedAnchors
)) {
911 /* no need to evaluate anchor trust when building cert chain */
912 MacOSError::check(SecTrustSetAnchorCertificates(mTrust
, cfEmptyArray())); // no anchors
913 actionData
.ActionFlags
|= CSSM_TP_ACTION_IMPLICIT_ANCHORS
; // action flags
916 for (;;) { // at most twice
917 MacOSError::check(SecTrustSetParameters(mTrust
,
918 CSSM_TP_ACTION_DEFAULT
, CFTempData(&actionData
, sizeof(actionData
))));
920 // evaluate trust and extract results
921 SecTrustResultType trustResult
;
922 MacOSError::check(SecTrustEvaluate(mTrust
, &trustResult
));
923 mCertChain
.take(copyCertChain(mTrust
));
925 // if this is an Apple developer cert....
926 if (teamID() && SecStaticCode::isAppleDeveloperCert(mCertChain
)) {
927 CFRef
<CFStringRef
> teamIDFromCert
;
928 if (CFArrayGetCount(mCertChain
) > 0) {
929 SecCertificateRef leaf
= (SecCertificateRef
)CFArrayGetValueAtIndex(mCertChain
, Requirement::leafCert
);
930 CFArrayRef organizationalUnits
= SecCertificateCopyOrganizationalUnit(leaf
);
931 if (organizationalUnits
) {
932 teamIDFromCert
.take((CFStringRef
)CFRetain(CFArrayGetValueAtIndex(organizationalUnits
, 0)));
933 CFRelease(organizationalUnits
);
935 teamIDFromCert
= NULL
;
938 if (teamIDFromCert
) {
939 CFRef
<CFStringRef
> teamIDFromCD
= CFStringCreateWithCString(NULL
, teamID(), kCFStringEncodingUTF8
);
941 Security::Syslog::error("Could not get team identifier (%s)", teamID());
942 MacOSError::throwMe(errSecCSInvalidTeamIdentifier
);
945 if (CFStringCompare(teamIDFromCert
, teamIDFromCD
, 0) != kCFCompareEqualTo
) {
946 Security::Syslog::error("Team identifier in the signing certificate (%s) does not match the team identifier (%s) in the code directory",
947 cfString(teamIDFromCert
).c_str(), teamID());
948 MacOSError::throwMe(errSecCSBadTeamIdentifier
);
954 CODESIGN_EVAL_STATIC_SIGNATURE_RESULT(this, trustResult
, mCertChain
? (int)CFArrayGetCount(mCertChain
) : 0);
955 switch (trustResult
) {
956 case kSecTrustResultProceed
:
957 case kSecTrustResultUnspecified
:
959 case kSecTrustResultDeny
:
960 MacOSError::throwMe(CSSMERR_APPLETP_TRUST_SETTING_DENY
); // user reject
961 case kSecTrustResultInvalid
:
962 assert(false); // should never happen
963 MacOSError::throwMe(CSSMERR_TP_NOT_TRUSTED
);
967 MacOSError::check(SecTrustGetCssmResultCode(mTrust
, &result
));
968 // if we have a valid timestamp, CMS validates against (that) signing time and all is well.
969 // If we don't have one, may validate against *now*, and must be able to tolerate expiration.
970 if (mSigningTimestamp
== 0) { // no timestamp available
971 if (((result
== CSSMERR_TP_CERT_EXPIRED
) || (result
== CSSMERR_TP_CERT_NOT_VALID_YET
))
972 && !(actionData
.ActionFlags
& CSSM_TP_ACTION_ALLOW_EXPIRED
)) {
973 CODESIGN_EVAL_STATIC_SIGNATURE_EXPIRED(this);
974 actionData
.ActionFlags
|= CSSM_TP_ACTION_ALLOW_EXPIRED
; // (this also allows postdated certs)
975 continue; // retry validation while tolerating expiration
978 if (checkfix41082220(result
)) {
981 Security::Syslog::error("SecStaticCode: verification failed (trust result %d, error %d)", trustResult
, (int)result
);
982 MacOSError::throwMe(result
);
986 if (mSigningTimestamp
) {
987 CFIndex rootix
= CFArrayGetCount(mCertChain
);
988 if (SecCertificateRef mainRoot
= SecCertificateRef(CFArrayGetValueAtIndex(mCertChain
, rootix
-1)))
989 if (isAppleCA(mainRoot
)) {
990 // impose policy: if the signature itself draws to Apple, then so must the timestamp signature
991 CFRef
<CFArrayRef
> tsCerts
;
992 OSStatus result
= CMSDecoderCopySignerTimestampCertificates(cms
, 0, &tsCerts
.aref());
994 Security::Syslog::error("SecStaticCode: could not get timestamp certificates (error %d)", (int)result
);
995 MacOSError::check(result
);
997 CFIndex tsn
= CFArrayGetCount(tsCerts
);
998 bool good
= tsn
> 0 && isAppleCA(SecCertificateRef(CFArrayGetValueAtIndex(tsCerts
, tsn
-1)));
1000 result
= CSSMERR_TP_NOT_TRUSTED
;
1001 Security::Syslog::error("SecStaticCode: timestamp policy verification failed (error %d)", (int)result
);
1002 MacOSError::throwMe(result
);
1007 return actionData
.ActionFlags
& CSSM_TP_ACTION_ALLOW_EXPIRED
;
1013 // Do some pre-verification initialization
1014 CFDataRef sig
= this->signature();
1015 this->codeDirectory(); // load CodeDirectory (sets mDir)
1016 mSigningTime
= 0; // "not present" marker (nobody could code sign on Jan 1, 2001 :-)
1018 CFRef
<CFDictionaryRef
> attrs
;
1019 CFRef
<CFArrayRef
> vf_policies(createVerificationPolicies());
1021 // Verify the CMS signature against mBaseDir (SHA1)
1022 MacOSError::check(SecCMSVerifyCopyDataAndAttributes(sig
, mBaseDir
, vf_policies
, &mTrust
.aref(), NULL
, &attrs
.aref()));
1024 // Copy the signing time
1025 mSigningTime
= SecTrustGetVerifyTime(mTrust
);
1027 // Validate the cert chain
1028 SecTrustResultType trustResult
;
1029 MacOSError::check(SecTrustEvaluate(mTrust
, &trustResult
));
1031 // retrieve auxiliary data bag and verify against current state
1032 CFRef
<CFDataRef
> hashBag
;
1033 hashBag
= CFDataRef(CFDictionaryGetValue(attrs
, kSecCMSHashAgility
));
1035 CFRef
<CFDictionaryRef
> hashDict
= makeCFDictionaryFrom(hashBag
);
1036 CFArrayRef cdList
= CFArrayRef(CFDictionaryGetValue(hashDict
, CFSTR("cdhashes")));
1037 CFArrayRef myCdList
= this->cdHashes();
1038 if (cdList
== NULL
|| !CFEqual(cdList
, myCdList
))
1039 MacOSError::throwMe(errSecCSSignatureFailed
);
1043 * Populate mCertChain with the certs. If we failed validation, the
1044 * signer's cert will be checked installed provisioning profiles as an
1045 * alternative to verification against the policy for store-signed binaries
1047 mCertChain
.take(copyCertChain(mTrust
));
1049 // Did we implicitly trust the signer?
1050 mTrustedSigningCertChain
= (trustResult
== kSecTrustResultUnspecified
|| trustResult
== kSecTrustResultProceed
);
1052 return false; // XXX: Not checking for expired certs
1058 // Return the TP policy used for signature verification.
1059 // This may be a simple SecPolicyRef or a CFArray of policies.
1060 // The caller owns the return value.
1062 static SecPolicyRef
makeRevocationPolicy(CFOptionFlags flags
)
1064 CFRef
<SecPolicyRef
> policy(SecPolicyCreateRevocation(flags
));
1065 return policy
.yield();
1069 CFArrayRef
SecStaticCode::createVerificationPolicies()
1071 if (mValidationFlags
& kSecCSUseSoftwareSigningCert
) {
1072 CFRef
<SecPolicyRef
> ssRef
= SecPolicyCreateAppleSoftwareSigning();
1073 return makeCFArray(1, ssRef
.get());
1076 if (mValidationFlags
& kSecCSApplyEmbeddedPolicy
) {
1077 CFRef
<SecPolicyRef
> iOSRef
= SecPolicyCreateiPhoneApplicationSigning();
1078 return makeCFArray(1, iOSRef
.get());
1081 CFRef
<SecPolicyRef
> core
;
1082 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3
,
1083 &CSSMOID_APPLE_TP_CODE_SIGNING
, &core
.aref()));
1084 if (mValidationFlags
& kSecCSNoNetworkAccess
) {
1085 // Skips all revocation since they require network connectivity
1086 // therefore annihilates kSecCSEnforceRevocationChecks if present
1087 CFRef
<SecPolicyRef
> no_revoc
= makeRevocationPolicy(kSecRevocationNetworkAccessDisabled
);
1088 return makeCFArray(2, core
.get(), no_revoc
.get());
1090 else if (mValidationFlags
& kSecCSEnforceRevocationChecks
) {
1091 // Add CRL and OCSP policies
1092 CFRef
<SecPolicyRef
> revoc
= makeRevocationPolicy(kSecRevocationUseAnyAvailableMethod
);
1093 return makeCFArray(2, core
.get(), revoc
.get());
1095 return makeCFArray(1, core
.get());
1098 CFRef
<SecPolicyRef
> tvOSRef
= SecPolicyCreateAppleTVOSApplicationSigning();
1099 return makeCFArray(1, tvOSRef
.get());
1101 CFRef
<SecPolicyRef
> iOSRef
= SecPolicyCreateiPhoneApplicationSigning();
1102 return makeCFArray(1, iOSRef
.get());
1107 CFArrayRef
SecStaticCode::createTimeStampingAndRevocationPolicies()
1109 CFRef
<SecPolicyRef
> tsPolicy
= SecPolicyCreateAppleTimeStamping();
1111 if (mValidationFlags
& kSecCSNoNetworkAccess
) {
1112 // Skips all revocation since they require network connectivity
1113 // therefore annihilates kSecCSEnforceRevocationChecks if present
1114 CFRef
<SecPolicyRef
> no_revoc
= makeRevocationPolicy(kSecRevocationNetworkAccessDisabled
);
1115 return makeCFArray(2, tsPolicy
.get(), no_revoc
.get());
1117 else if (mValidationFlags
& kSecCSEnforceRevocationChecks
) {
1118 // Add CRL and OCSP policies
1119 CFRef
<SecPolicyRef
> revoc
= makeRevocationPolicy(kSecRevocationUseAnyAvailableMethod
);
1120 return makeCFArray(2, tsPolicy
.get(), revoc
.get());
1123 return makeCFArray(1, tsPolicy
.get());
1126 return makeCFArray(1, tsPolicy
.get());
1131 CFArrayRef
SecStaticCode::copyCertChain(SecTrustRef trust
)
1133 SecCertificateRef leafCert
= SecTrustGetCertificateAtIndex(trust
, 0);
1134 if (leafCert
!= NULL
) {
1135 CFIndex count
= SecTrustGetCertificateCount(trust
);
1137 CFMutableArrayRef certs
= CFArrayCreateMutable(kCFAllocatorDefault
, count
,
1138 &kCFTypeArrayCallBacks
);
1140 CFArrayAppendValue(certs
, leafCert
);
1141 for (CFIndex i
= 1; i
< count
; ++i
) {
1142 CFArrayAppendValue(certs
, SecTrustGetCertificateAtIndex(trust
, i
));
1152 // Validate a particular sealed, cached resource against its (special) CodeDirectory slot.
1153 // The resource must already have been placed in the cache.
1154 // This does NOT perform basic validation.
1156 void SecStaticCode::validateComponent(CodeDirectory::SpecialSlot slot
, OSStatus fail
/* = errSecCSSignatureFailed */)
1158 assert(slot
<= cdSlotMax
);
1159 CFDataRef data
= mCache
[slot
];
1160 assert(data
); // must be cached
1161 if (data
== CFDataRef(kCFNull
)) {
1162 if (codeDirectory()->slotIsPresent(-slot
)) // was supposed to be there...
1163 MacOSError::throwMe(fail
); // ... and is missing
1165 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data
), CFDataGetLength(data
), -slot
, false))
1166 MacOSError::throwMe(fail
);
1172 // Perform static validation of the main executable.
1173 // This reads the main executable from disk and validates it against the
1174 // CodeDirectory code slot array.
1175 // Note that this is NOT an in-memory validation, and is thus potentially
1176 // subject to timing attacks.
1178 void SecStaticCode::validateExecutable()
1180 if (!validatedExecutable()) {
1182 DTRACK(CODESIGN_EVAL_STATIC_EXECUTABLE
, this,
1183 (char*)this->mainExecutablePath().c_str(), codeDirectory()->nCodeSlots
);
1184 const CodeDirectory
*cd
= this->codeDirectory();
1186 MacOSError::throwMe(errSecCSUnsigned
);
1187 AutoFileDesc
fd(mainExecutablePath(), O_RDONLY
);
1188 fd
.fcntl(F_NOCACHE
, true); // turn off page caching (one-pass)
1189 if (Universal
*fat
= mRep
->mainExecutableImage())
1190 fd
.seek(fat
->archOffset());
1191 size_t pageSize
= cd
->pageSize
? (1 << cd
->pageSize
) : 0;
1192 size_t remaining
= cd
->signingLimit();
1193 for (uint32_t slot
= 0; slot
< cd
->nCodeSlots
; ++slot
) {
1194 size_t thisPage
= remaining
;
1196 thisPage
= min(thisPage
, pageSize
);
1197 __block
bool good
= true;
1198 CodeDirectory::multipleHashFileData(fd
, thisPage
, hashAlgorithms(), ^(CodeDirectory::HashAlgorithm type
, Security::DynamicHash
*hasher
) {
1199 const CodeDirectory
* cd
= (const CodeDirectory
*)CFDataGetBytePtr(mCodeDirectories
[type
]);
1200 if (!hasher
->verify(cd
->getSlot(slot
,
1201 mValidationFlags
& kSecCSValidatePEH
)))
1205 CODESIGN_EVAL_STATIC_EXECUTABLE_FAIL(this, (int)slot
);
1206 MacOSError::throwMe(errSecCSSignatureFailed
);
1208 remaining
-= thisPage
;
1210 assert(remaining
== 0);
1211 mExecutableValidated
= true;
1212 mExecutableValidResult
= errSecSuccess
;
1213 } catch (const CommonError
&err
) {
1214 mExecutableValidated
= true;
1215 mExecutableValidResult
= err
.osStatus();
1218 secinfo("staticCode", "%p executable validation threw non-common exception", this);
1219 mExecutableValidated
= true;
1220 mExecutableValidResult
= errSecCSInternalError
;
1221 Syslog::notice("code signing internal problem: unknown exception thrown by validation");
1225 assert(validatedExecutable());
1226 if (mExecutableValidResult
!= errSecSuccess
)
1227 MacOSError::throwMe(mExecutableValidResult
);
1232 // Perform static validation of sealed resources and nested code.
1234 // This performs a whole-code static resource scan and effectively
1235 // computes a concordance between what's on disk and what's in the ResourceDirectory.
1236 // Any unsanctioned difference causes an error.
1238 unsigned SecStaticCode::estimateResourceWorkload()
1240 // workload estimate = number of sealed files
1241 CFDictionaryRef sealedResources
= resourceDictionary();
1242 CFDictionaryRef files
= cfget
<CFDictionaryRef
>(sealedResources
, "files2");
1244 files
= cfget
<CFDictionaryRef
>(sealedResources
, "files");
1245 return files
? unsigned(CFDictionaryGetCount(files
)) : 0;
1248 void SecStaticCode::validateResources(SecCSFlags flags
)
1250 // do we have a superset of this requested validation cached?
1252 if (mResourcesValidated
) { // have cached outcome
1253 if (!(flags
& kSecCSCheckNestedCode
) || mResourcesDeep
) // was deep or need no deep scan
1258 string root
= cfStringRelease(copyCanonicalPath());
1259 bool itemIsOnRootFS
= isOnRootFilesystem(root
.c_str());
1260 bool requestForcedValidation
= (mValidationFlags
& kSecCSSkipRootVolumeExceptions
);
1261 bool useRootFSPolicy
= itemIsOnRootFS
&& !requestForcedValidation
;
1263 secinfo("staticCode", "performing resource validation for %s (%d, %d, %d)", root
.c_str(),
1264 itemIsOnRootFS
, requestForcedValidation
, useRootFSPolicy
);
1266 if (mLimitedAsync
== NULL
) {
1267 bool runMultiThreaded
= ((flags
& kSecCSSingleThreaded
) == kSecCSSingleThreaded
) ? false :
1268 (diskRep()->fd().mediumType() == kIOPropertyMediumTypeSolidStateKey
);
1269 mLimitedAsync
= new LimitedAsync(runMultiThreaded
);
1273 CFDictionaryRef rules
;
1274 CFDictionaryRef files
;
1276 if (!loadResources(rules
, files
, version
))
1277 return; // validly no resources; nothing to do (ok)
1279 // found resources, and they are sealed
1280 DTRACK(CODESIGN_EVAL_STATIC_RESOURCES
, this,
1281 (char*)this->mainExecutablePath().c_str(), 0);
1283 // scan through the resources on disk, checking each against the resourceDirectory
1284 mResourcesValidContext
= new CollectingContext(*this); // collect all failures in here
1286 // check for weak resource rules
1287 bool strict
= flags
& kSecCSStrictValidate
;
1288 if (!useRootFSPolicy
) {
1290 if (hasWeakResourceRules(rules
, version
, mAllowOmissions
))
1291 if (mTolerateErrors
.find(errSecCSWeakResourceRules
) == mTolerateErrors
.end())
1292 MacOSError::throwMe(errSecCSWeakResourceRules
);
1294 if (mTolerateErrors
.find(errSecCSWeakResourceEnvelope
) == mTolerateErrors
.end())
1295 MacOSError::throwMe(errSecCSWeakResourceEnvelope
);
1299 Dispatch::Group group
;
1300 Dispatch::Group
&groupRef
= group
; // (into block)
1302 // scan through the resources on disk, checking each against the resourceDirectory
1303 __block CFRef
<CFMutableDictionaryRef
> resourceMap
= makeCFMutableDictionary(files
);
1304 string base
= cfString(this->resourceBase());
1305 ResourceBuilder
resources(base
, base
, rules
, strict
, mTolerateErrors
);
1306 this->mResourceScope
= &resources
;
1307 diskRep()->adjustResources(resources
);
1309 resources
.scan(^(FTSENT
*ent
, uint32_t ruleFlags
, const string relpath
, ResourceBuilder::Rule
*rule
) {
1310 CFDictionaryRemoveValue(resourceMap
, CFTempString(relpath
));
1311 bool isSymlink
= (ent
->fts_info
== FTS_SL
);
1313 void (^validate
)() = ^{
1314 bool needsValidation
= true;
1316 if (useRootFSPolicy
) {
1317 CFRef
<CFURLRef
> itemURL
= makeCFURL(relpath
, false, resourceBase());
1318 string itemPath
= cfString(itemURL
);
1319 if (isOnRootFilesystem(itemPath
.c_str())) {
1320 secinfo("staticCode", "resource validation on root volume skipped: %s", itemPath
.c_str());
1321 needsValidation
= false;
1325 if (needsValidation
) {
1326 secinfo("staticCode", "performing resource validation on item: %s", relpath
.c_str());
1327 validateResource(files
, relpath
, isSymlink
, *mResourcesValidContext
, flags
, version
);
1332 mLimitedAsync
->perform(groupRef
, validate
);
1334 group
.wait(); // wait until all async resources have been validated as well
1336 if (useRootFSPolicy
) {
1337 // It's ok to allow leftovers on the root filesystem for now.
1339 // Look through the leftovers and make sure they're all properly optional resources.
1340 unsigned leftovers
= unsigned(CFDictionaryGetCount(resourceMap
));
1341 if (leftovers
> 0) {
1342 secinfo("staticCode", "%d sealed resource(s) not found in code", int(leftovers
));
1343 CFDictionaryApplyFunction(resourceMap
, SecStaticCode::checkOptionalResource
, mResourcesValidContext
);
1347 // now check for any errors found in the reporting context
1348 mResourcesValidated
= true;
1349 mResourcesDeep
= flags
& kSecCSCheckNestedCode
;
1350 if (mResourcesValidContext
->osStatus() != errSecSuccess
)
1351 mResourcesValidContext
->throwMe();
1352 } catch (const CommonError
&err
) {
1353 mResourcesValidated
= true;
1354 mResourcesDeep
= flags
& kSecCSCheckNestedCode
;
1355 mResourcesValidResult
= err
.osStatus();
1358 secinfo("staticCode", "%p executable validation threw non-common exception", this);
1359 mResourcesValidated
= true;
1360 mResourcesDeep
= flags
& kSecCSCheckNestedCode
;
1361 mResourcesValidResult
= errSecCSInternalError
;
1362 Syslog::notice("code signing internal problem: unknown exception thrown by validation");
1366 assert(validatedResources());
1367 if (mResourcesValidResult
)
1368 MacOSError::throwMe(mResourcesValidResult
);
1369 if (mResourcesValidContext
->osStatus() != errSecSuccess
)
1370 mResourcesValidContext
->throwMe();
1374 bool SecStaticCode::loadResources(CFDictionaryRef
& rules
, CFDictionaryRef
& files
, uint32_t& version
)
1377 CFDictionaryRef sealedResources
= resourceDictionary();
1378 if (this->resourceBase()) { // disk has resources
1379 if (sealedResources
)
1380 /* go to work below */;
1382 MacOSError::throwMe(errSecCSResourcesNotFound
);
1383 } else { // disk has no resources
1384 if (sealedResources
)
1385 MacOSError::throwMe(errSecCSResourcesNotFound
);
1387 return false; // no resources, not sealed - fine (no work)
1390 // use V2 resource seal if available, otherwise fall back to V1
1391 if (CFDictionaryGetValue(sealedResources
, CFSTR("files2"))) { // have V2 signature
1392 rules
= cfget
<CFDictionaryRef
>(sealedResources
, "rules2");
1393 files
= cfget
<CFDictionaryRef
>(sealedResources
, "files2");
1395 } else { // only V1 available
1396 rules
= cfget
<CFDictionaryRef
>(sealedResources
, "rules");
1397 files
= cfget
<CFDictionaryRef
>(sealedResources
, "files");
1400 if (!rules
|| !files
)
1401 MacOSError::throwMe(errSecCSResourcesInvalid
);
1406 void SecStaticCode::checkOptionalResource(CFTypeRef key
, CFTypeRef value
, void *context
)
1408 ValidationContext
*ctx
= static_cast<ValidationContext
*>(context
);
1409 ResourceSeal
seal(value
);
1410 if (!seal
.optional()) {
1411 if (key
&& CFGetTypeID(key
) == CFStringGetTypeID()) {
1412 CFTempURL
tempURL(CFStringRef(key
), false, ctx
->code
.resourceBase());
1413 if (!tempURL
.get()) {
1414 ctx
->reportProblem(errSecCSBadDictionaryFormat
, kSecCFErrorResourceSeal
, key
);
1416 ctx
->reportProblem(errSecCSBadResource
, kSecCFErrorResourceMissing
, tempURL
);
1419 ctx
->reportProblem(errSecCSBadResource
, kSecCFErrorResourceSeal
, key
);
1425 static bool isOmitRule(CFTypeRef value
)
1427 if (CFGetTypeID(value
) == CFBooleanGetTypeID())
1428 return value
== kCFBooleanFalse
;
1429 CFDictionary
rule(value
, errSecCSResourceRulesInvalid
);
1430 return rule
.get
<CFBooleanRef
>("omit") == kCFBooleanTrue
;
1433 bool SecStaticCode::hasWeakResourceRules(CFDictionaryRef rulesDict
, uint32_t version
, CFArrayRef allowedOmissions
)
1435 // compute allowed omissions
1436 CFRef
<CFArrayRef
> defaultOmissions
= this->diskRep()->allowedResourceOmissions();
1437 if (!defaultOmissions
) {
1438 Syslog::notice("code signing internal problem: diskRep returned no allowedResourceOmissions");
1439 MacOSError::throwMe(errSecCSInternalError
);
1441 CFRef
<CFMutableArrayRef
> allowed
= CFArrayCreateMutableCopy(NULL
, 0, defaultOmissions
);
1442 if (allowedOmissions
)
1443 CFArrayAppendArray(allowed
, allowedOmissions
, CFRangeMake(0, CFArrayGetCount(allowedOmissions
)));
1444 CFRange range
= CFRangeMake(0, CFArrayGetCount(allowed
));
1446 // check all resource rules for weakness
1447 string catchAllRule
= (version
== 1) ? "^Resources/" : "^.*";
1448 __block
bool coversAll
= false;
1449 __block
bool forbiddenOmission
= false;
1450 CFArrayRef allowedRef
= allowed
.get(); // (into block)
1451 CFDictionary
rules(rulesDict
, errSecCSResourceRulesInvalid
);
1452 rules
.apply(^(CFStringRef key
, CFTypeRef value
) {
1453 string pattern
= cfString(key
, errSecCSResourceRulesInvalid
);
1454 if (pattern
== catchAllRule
&& value
== kCFBooleanTrue
) {
1458 if (isOmitRule(value
))
1459 forbiddenOmission
|= !CFArrayContainsValue(allowedRef
, range
, key
);
1462 return !coversAll
|| forbiddenOmission
;
1467 // Load, validate, cache, and return CFDictionary forms of sealed resources.
1469 CFDictionaryRef
SecStaticCode::infoDictionary()
1472 mInfoDict
.take(getDictionary(cdInfoSlot
, errSecCSInfoPlistFailed
));
1473 secinfo("staticCode", "%p loaded InfoDict %p", this, mInfoDict
.get());
1478 CFDictionaryRef
SecStaticCode::entitlements()
1480 if (!mEntitlements
) {
1481 validateDirectory();
1482 if (CFDataRef entitlementData
= component(cdEntitlementSlot
)) {
1483 validateComponent(cdEntitlementSlot
);
1484 const EntitlementBlob
*blob
= reinterpret_cast<const EntitlementBlob
*>(CFDataGetBytePtr(entitlementData
));
1485 if (blob
->validateBlob()) {
1486 mEntitlements
.take(blob
->entitlements());
1487 secinfo("staticCode", "%p loaded Entitlements %p", this, mEntitlements
.get());
1489 // we do not consider a different blob type to be an error. We think it's a new format we don't understand
1492 return mEntitlements
;
1495 CFDictionaryRef
SecStaticCode::resourceDictionary(bool check
/* = true */)
1497 if (mResourceDict
) // cached
1498 return mResourceDict
;
1499 if (CFRef
<CFDictionaryRef
> dict
= getDictionary(cdResourceDirSlot
, check
))
1500 if (cfscan(dict
, "{rules=%Dn,files=%Dn}")) {
1501 secinfo("staticCode", "%p loaded ResourceDict %p",
1502 this, mResourceDict
.get());
1503 return mResourceDict
= dict
;
1510 CFDataRef
SecStaticCode::copyComponent(CodeDirectory::SpecialSlot slot
, CFDataRef hash
)
1512 const CodeDirectory
* cd
= this->codeDirectory();
1513 if (CFCopyRef
<CFDataRef
> component
= this->component(slot
)) {
1515 const void *slotHash
= cd
->getSlot(slot
, false);
1516 if (cd
->hashSize
!= CFDataGetLength(hash
) || 0 != memcmp(slotHash
, CFDataGetBytePtr(hash
), cd
->hashSize
)) {
1517 Syslog::notice("copyComponent hash mismatch slot %d length %d", slot
, int(CFDataGetLength(hash
)));
1518 return NULL
; // mismatch
1521 return component
.yield();
1529 // Load and cache the resource directory base.
1530 // Note that the base is optional for each DiskRep.
1532 CFURLRef
SecStaticCode::resourceBase()
1534 if (!mGotResourceBase
) {
1535 string base
= mRep
->resourcesRootPath();
1537 mResourceBase
.take(makeCFURL(base
, true));
1538 mGotResourceBase
= true;
1540 return mResourceBase
;
1545 // Load a component, validate it, convert it to a CFDictionary, and return that.
1546 // This will force load and validation, which means that it will perform basic
1547 // validation if it hasn't been done yet.
1549 CFDictionaryRef
SecStaticCode::getDictionary(CodeDirectory::SpecialSlot slot
, bool check
/* = true */)
1552 validateDirectory();
1553 if (CFDataRef infoData
= component(slot
)) {
1554 validateComponent(slot
);
1555 if (CFDictionaryRef dict
= makeCFDictionaryFrom(infoData
))
1558 MacOSError::throwMe(errSecCSBadDictionaryFormat
);
1566 CFDictionaryRef
SecStaticCode::diskRepInformation()
1568 return mRep
->diskRepInformation();
1571 bool SecStaticCode::checkfix30814861(string path
, bool addition
) {
1572 // <rdar://problem/30814861> v2 resource rules don't match v1 resource rules
1574 //// Condition 1: Is the app an iOS app that was built with an SDK lower than 9.0?
1576 // We started signing correctly in 2014, 9.0 was first seeded mid-2016.
1578 CFRef
<CFDictionaryRef
> inf
= diskRepInformation();
1580 CFDictionary
info(diskRepInformation(), errSecCSNotSupported
);
1582 cfNumber(info
.get
<CFNumberRef
>(kSecCodeInfoDiskRepVersionPlatform
, errSecCSNotSupported
), 0);
1583 uint32_t sdkVersion
=
1584 cfNumber(info
.get
<CFNumberRef
>(kSecCodeInfoDiskRepVersionSDK
, errSecCSNotSupported
), 0);
1586 if (platform
!= PLATFORM_IOS
|| sdkVersion
>= 0x00090000) {
1589 } catch (const MacOSError
&error
) {
1593 //// Condition 2: Is it a .sinf/.supf/.supp file at the right location?
1595 static regex_t pathre_sinf
;
1596 static regex_t pathre_supp_supf
;
1597 static dispatch_once_t once
;
1599 dispatch_once(&once
, ^{
1600 os_assert_zero(regcomp(&pathre_sinf
,
1601 "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|())SC_Info/[^/]+\\.sinf$",
1602 REG_EXTENDED
| REG_NOSUB
));
1603 os_assert_zero(regcomp(&pathre_supp_supf
,
1604 "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|())SC_Info/[^/]+\\.(supf|supp)$",
1605 REG_EXTENDED
| REG_NOSUB
));
1608 // .sinf is added, .supf/.supp are modified.
1609 const regex_t
&pathre
= addition
? pathre_sinf
: pathre_supp_supf
;
1611 const int result
= regexec(&pathre
, path
.c_str(), 0, NULL
, 0);
1613 if (result
== REG_NOMATCH
) {
1615 } else if (result
!= 0) {
1617 secerror("unexpected regexec result %d for path '%s'", result
, path
.c_str());
1621 //// Condition 3: Do the v1 rules actually exclude the file?
1623 dispatch_once(&mCheckfix30814861builder1_once
, ^{
1624 // Create the v1 resource builder lazily.
1625 CFDictionaryRef rules1
= cfget
<CFDictionaryRef
>(resourceDictionary(), "rules");
1626 const string base
= cfString(resourceBase());
1628 mCheckfix30814861builder1
= new ResourceBuilder(base
, base
, rules1
, false, mTolerateErrors
);
1631 ResourceBuilder::Rule
const * const matchingRule
= mCheckfix30814861builder1
->findRule(path
);
1633 if (matchingRule
== NULL
|| !(matchingRule
->flags
& ResourceBuilder::omitted
)) {
1637 //// All matched, this file is a check-fixed sinf/supf/supp.
1643 void SecStaticCode::validateResource(CFDictionaryRef files
, string path
, bool isSymlink
, ValidationContext
&ctx
, SecCSFlags flags
, uint32_t version
)
1645 if (!resourceBase()) // no resources in DiskRep
1646 MacOSError::throwMe(errSecCSResourcesNotFound
);
1647 CFRef
<CFURLRef
> fullpath
= makeCFURL(path
, false, resourceBase());
1648 if (version
> 1 && ((flags
& (kSecCSStrictValidate
|kSecCSRestrictSidebandData
)) == (kSecCSStrictValidate
|kSecCSRestrictSidebandData
))) {
1649 AutoFileDesc
fd(cfString(fullpath
));
1650 if (fd
.hasExtendedAttribute(XATTR_RESOURCEFORK_NAME
) || fd
.hasExtendedAttribute(XATTR_FINDERINFO_NAME
))
1651 ctx
.reportProblem(errSecCSInvalidAssociatedFileData
, kSecCFErrorResourceSideband
, fullpath
);
1653 if (CFTypeRef file
= CFDictionaryGetValue(files
, CFTempString(path
))) {
1654 ResourceSeal
seal(file
);
1655 const ResourceSeal
& rseal
= seal
;
1656 if (seal
.nested()) {
1658 return ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
1659 string suffix
= ".framework";
1660 bool isFramework
= (path
.length() > suffix
.length())
1661 && (path
.compare(path
.length()-suffix
.length(), suffix
.length(), suffix
) == 0);
1662 validateNestedCode(fullpath
, seal
, flags
, isFramework
);
1663 } else if (seal
.link()) {
1665 return ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
1666 validateSymlinkResource(cfString(fullpath
), cfString(seal
.link()), ctx
, flags
);
1667 } else if (seal
.hash(hashAlgorithm())) { // genuine file
1669 return ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
1670 AutoFileDesc
fd(cfString(fullpath
), O_RDONLY
, FileDesc::modeMissingOk
); // open optional file
1672 __block
bool good
= true;
1673 CodeDirectory::multipleHashFileData(fd
, 0, hashAlgorithms(), ^(CodeDirectory::HashAlgorithm type
, Security::DynamicHash
*hasher
) {
1674 if (!hasher
->verify(rseal
.hash(type
)))
1678 if (version
== 2 && checkfix30814861(path
, false)) {
1679 secinfo("validateResource", "%s check-fixed (altered).", path
.c_str());
1681 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // altered
1685 if (!seal
.optional())
1686 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceMissing
, fullpath
); // was sealed but is now missing
1688 return; // validly missing
1691 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
1694 if (version
== 1) { // version 1 ignores symlinks altogether
1695 char target
[PATH_MAX
];
1696 if (::readlink(cfString(fullpath
).c_str(), target
, sizeof(target
)) > 0)
1699 if (version
== 2 && checkfix30814861(path
, true)) {
1700 secinfo("validateResource", "%s check-fixed (added).", path
.c_str());
1702 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAdded
, CFTempURL(path
, false, resourceBase()));
1706 void SecStaticCode::validatePlainMemoryResource(string path
, CFDataRef fileData
, SecCSFlags flags
)
1708 CFDictionaryRef rules
;
1709 CFDictionaryRef files
;
1711 if (!loadResources(rules
, files
, version
))
1712 MacOSError::throwMe(errSecCSResourcesNotFound
); // no resources sealed; this can't be right
1713 if (CFTypeRef file
= CFDictionaryGetValue(files
, CFTempString(path
))) {
1714 ResourceSeal
seal(file
);
1715 const Byte
*sealHash
= seal
.hash(hashAlgorithm());
1717 if (codeDirectory()->verifyMemoryContent(fileData
, sealHash
))
1721 MacOSError::throwMe(errSecCSBadResource
);
1724 void SecStaticCode::validateSymlinkResource(std::string fullpath
, std::string seal
, ValidationContext
&ctx
, SecCSFlags flags
)
1726 static const char* const allowedDestinations
[] = {
1731 char target
[PATH_MAX
];
1732 ssize_t len
= ::readlink(fullpath
.c_str(), target
, sizeof(target
)-1);
1734 UnixError::check(-1);
1736 std::string fulltarget
= target
;
1737 if (target
[0] != '/') {
1738 size_t lastSlash
= fullpath
.rfind('/');
1739 fulltarget
= fullpath
.substr(0, lastSlash
) + '/' + target
;
1741 if (seal
!= target
) {
1742 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, CFTempString(fullpath
));
1745 if ((mValidationFlags
& (kSecCSStrictValidate
|kSecCSRestrictSymlinks
)) == (kSecCSStrictValidate
|kSecCSRestrictSymlinks
)) {
1746 char resolved
[PATH_MAX
];
1747 if (realpath(fulltarget
.c_str(), resolved
)) {
1748 assert(resolved
[0] == '/');
1749 size_t rlen
= strlen(resolved
);
1750 if (target
[0] == '/') {
1751 // absolute symlink; only allow absolute links to system locations
1752 for (const char* const* pathp
= allowedDestinations
; *pathp
; pathp
++) {
1753 size_t dlen
= strlen(*pathp
);
1754 if (rlen
> dlen
&& strncmp(resolved
, *pathp
, dlen
) == 0)
1755 return; // target inside /System, deemed okay
1758 // everything else must be inside the bundle(s)
1759 for (const SecStaticCode
* code
= this; code
; code
= code
->mOuterScope
) {
1760 string root
= code
->mResourceScope
->root();
1761 if (strncmp(resolved
, root
.c_str(), root
.size()) == 0) {
1762 if (code
->mResourceScope
->includes(resolved
+ root
.length() + 1))
1763 return; // located in resource stack && included in envelope
1765 break; // located but excluded from envelope (deny)
1770 // if we fell through, flag a symlink error
1771 if (mTolerateErrors
.find(errSecCSInvalidSymlink
) == mTolerateErrors
.end())
1772 ctx
.reportProblem(errSecCSInvalidSymlink
, kSecCFErrorResourceAltered
, CFTempString(fullpath
));
1776 void SecStaticCode::validateNestedCode(CFURLRef path
, const ResourceSeal
&seal
, SecCSFlags flags
, bool isFramework
)
1778 CFRef
<SecRequirementRef
> req
;
1779 if (SecRequirementCreateWithString(seal
.requirement(), kSecCSDefaultFlags
, &req
.aref()))
1780 MacOSError::throwMe(errSecCSResourcesInvalid
);
1782 // recursively verify this nested code
1784 if (!(flags
& kSecCSCheckNestedCode
))
1785 flags
|= kSecCSBasicValidateOnly
| kSecCSQuickCheck
;
1786 SecPointer
<SecStaticCode
> code
= new SecStaticCode(DiskRep::bestGuess(cfString(path
)));
1787 code
->initializeFromParent(*this);
1788 code
->staticValidate(flags
& (~kSecCSRestrictToAppLike
), SecRequirement::required(req
));
1790 if (isFramework
&& (flags
& kSecCSStrictValidate
))
1792 validateOtherVersions(path
, flags
& (~kSecCSRestrictToAppLike
), req
, code
);
1793 } catch (const CSError
&err
) {
1794 MacOSError::throwMe(errSecCSBadFrameworkVersion
);
1795 } catch (const MacOSError
&err
) {
1796 MacOSError::throwMe(errSecCSBadFrameworkVersion
);
1799 } catch (CSError
&err
) {
1800 if (err
.error
== errSecCSReqFailed
) {
1801 mResourcesValidContext
->reportProblem(errSecCSBadNestedCode
, kSecCFErrorResourceAltered
, path
);
1804 err
.augment(kSecCFErrorPath
, path
);
1806 } catch (const MacOSError
&err
) {
1807 if (err
.error
== errSecCSReqFailed
) {
1808 mResourcesValidContext
->reportProblem(errSecCSBadNestedCode
, kSecCFErrorResourceAltered
, path
);
1811 CSError::throwMe(err
.error
, kSecCFErrorPath
, path
);
1815 void SecStaticCode::validateOtherVersions(CFURLRef path
, SecCSFlags flags
, SecRequirementRef req
, SecStaticCode
*code
)
1817 // Find out what current points to and do not revalidate
1818 std::string mainPath
= cfStringRelease(code
->diskRep()->copyCanonicalPath());
1820 char main_path
[PATH_MAX
];
1821 bool foundTarget
= false;
1823 /* If it failed to get the target of the symlink, do not fail. It is a performance loss,
1824 not a security hole */
1825 if (realpath(mainPath
.c_str(), main_path
) != NULL
)
1828 std::ostringstream versionsPath
;
1829 versionsPath
<< cfString(path
) << "/Versions/";
1831 DirScanner
scanner(versionsPath
.str());
1833 if (scanner
.initialized()) {
1834 struct dirent
*entry
= NULL
;
1835 while ((entry
= scanner
.getNext()) != NULL
) {
1836 std::ostringstream fullPath
;
1838 if (entry
->d_type
!= DT_DIR
|| strcmp(entry
->d_name
, "Current") == 0)
1841 fullPath
<< versionsPath
.str() << entry
->d_name
;
1843 char real_full_path
[PATH_MAX
];
1844 if (realpath(fullPath
.str().c_str(), real_full_path
) == NULL
)
1845 UnixError::check(-1);
1847 // Do case insensitive comparions because realpath() was called for both paths
1848 if (foundTarget
&& strcmp(main_path
, real_full_path
) == 0)
1851 SecPointer
<SecStaticCode
> frameworkVersion
= new SecStaticCode(DiskRep::bestGuess(real_full_path
));
1852 frameworkVersion
->initializeFromParent(*this);
1853 frameworkVersion
->staticValidate(flags
, SecRequirement::required(req
));
1860 // Test a CodeDirectory flag.
1861 // Returns false if there is no CodeDirectory.
1862 // May throw if the CodeDirectory is present but somehow invalid.
1864 bool SecStaticCode::flag(uint32_t tested
)
1866 if (const CodeDirectory
*cd
= this->codeDirectory(false))
1867 return cd
->flags
& tested
;
1874 // Retrieve the full SuperBlob containing all internal requirements.
1876 const Requirements
*SecStaticCode::internalRequirements()
1878 if (CFDataRef reqData
= component(cdRequirementsSlot
)) {
1879 const Requirements
*req
= (const Requirements
*)CFDataGetBytePtr(reqData
);
1880 if (!req
->validateBlob())
1881 MacOSError::throwMe(errSecCSReqInvalid
);
1889 // Retrieve a particular internal requirement by type.
1891 const Requirement
*SecStaticCode::internalRequirement(SecRequirementType type
)
1893 if (const Requirements
*reqs
= internalRequirements())
1894 return reqs
->find
<Requirement
>(type
);
1901 // Return the Designated Requirement (DR). This can be either explicit in the
1902 // Internal Requirements component, or implicitly generated on demand here.
1903 // Note that an explicit DR may have been implicitly generated at signing time;
1904 // we don't distinguish this case.
1906 const Requirement
*SecStaticCode::designatedRequirement()
1908 if (const Requirement
*req
= internalRequirement(kSecDesignatedRequirementType
)) {
1909 return req
; // explicit in signing data
1911 if (!mDesignatedReq
)
1912 mDesignatedReq
= defaultDesignatedRequirement();
1913 return mDesignatedReq
;
1919 // Generate the default Designated Requirement (DR) for this StaticCode.
1920 // Ignore any explicit DR it may contain.
1922 const Requirement
*SecStaticCode::defaultDesignatedRequirement()
1924 if (flag(kSecCodeSignatureAdhoc
)) {
1925 // adhoc signature: return a cdhash requirement for all architectures
1926 __block
Requirement::Maker maker
;
1927 Requirement::Maker::Chain
chain(maker
, opOr
);
1929 // insert cdhash requirement for all architectures
1930 __block CFRef
<CFMutableArrayRef
> allHashes
= CFArrayCreateMutableCopy(NULL
, 0, this->cdHashes());
1931 handleOtherArchitectures(^(SecStaticCode
*other
) {
1932 CFArrayRef hashes
= other
->cdHashes();
1933 CFArrayAppendArray(allHashes
, hashes
, CFRangeMake(0, CFArrayGetCount(hashes
)));
1935 CFIndex count
= CFArrayGetCount(allHashes
);
1936 for (CFIndex n
= 0; n
< count
; ++n
) {
1938 maker
.cdhash(CFDataRef(CFArrayGetValueAtIndex(allHashes
, n
)));
1940 return maker
.make();
1943 // full signature: Gin up full context and let DRMaker do its thing
1944 validateDirectory(); // need the cert chain
1945 CFRef
<CFDateRef
> secureTimestamp
;
1946 if (CFAbsoluteTime time
= this->signingTimestamp()) {
1947 secureTimestamp
.take(CFDateCreate(NULL
, time
));
1949 Requirement::Context
context(this->certificates(),
1950 this->infoDictionary(),
1951 this->entitlements(),
1953 this->codeDirectory(),
1955 kSecCodeSignatureNoHash
,
1960 return DRMaker(context
).make();
1962 MacOSError::throwMe(errSecCSUnimplemented
);
1969 // Validate a SecStaticCode against the internal requirement of a particular type.
1971 void SecStaticCode::validateRequirements(SecRequirementType type
, SecStaticCode
*target
,
1972 OSStatus nullError
/* = errSecSuccess */)
1974 DTRACK(CODESIGN_EVAL_STATIC_INTREQ
, this, type
, target
, nullError
);
1975 if (const Requirement
*req
= internalRequirement(type
))
1976 target
->validateRequirement(req
, nullError
? nullError
: errSecCSReqFailed
);
1978 MacOSError::throwMe(nullError
);
1984 // Validate this StaticCode against an external Requirement
1986 bool SecStaticCode::satisfiesRequirement(const Requirement
*req
, OSStatus failure
)
1988 bool result
= false;
1990 validateDirectory();
1991 CFRef
<CFDateRef
> secureTimestamp
;
1992 if (CFAbsoluteTime time
= this->signingTimestamp()) {
1993 secureTimestamp
.take(CFDateCreate(NULL
, time
));
1995 result
= req
->validates(Requirement::Context(mCertChain
, infoDictionary(), entitlements(),
1996 codeDirectory()->identifier(), codeDirectory(),
1997 NULL
, kSecCodeSignatureNoHash
, mRep
->appleInternalForcePlatform(),
1998 secureTimestamp
, teamID()),
2003 void SecStaticCode::validateRequirement(const Requirement
*req
, OSStatus failure
)
2005 if (!this->satisfiesRequirement(req
, failure
))
2006 MacOSError::throwMe(failure
);
2010 // Retrieve one certificate from the cert chain.
2011 // Positive and negative indices can be used:
2012 // [ leaf, intermed-1, ..., intermed-n, anchor ]
2014 // Returns NULL if unavailable for any reason.
2016 SecCertificateRef
SecStaticCode::cert(int ix
)
2018 validateDirectory(); // need cert chain
2020 CFIndex length
= CFArrayGetCount(mCertChain
);
2023 if (ix
>= 0 && ix
< length
)
2024 return SecCertificateRef(CFArrayGetValueAtIndex(mCertChain
, ix
));
2029 CFArrayRef
SecStaticCode::certificates()
2031 validateDirectory(); // need cert chain
2037 // Gather (mostly) API-official information about this StaticCode.
2039 // This method lives in the twilight between the API and internal layers,
2040 // since it generates API objects (Sec*Refs) for return.
2042 CFDictionaryRef
SecStaticCode::signingInformation(SecCSFlags flags
)
2045 // Start with the pieces that we return even for unsigned code.
2046 // This makes Sec[Static]CodeRefs useful as API-level replacements
2047 // of our internal OSXCode objects.
2049 CFRef
<CFMutableDictionaryRef
> dict
= makeCFMutableDictionary(1,
2050 kSecCodeInfoMainExecutable
, CFTempURL(this->mainExecutablePath()).get()
2054 // If we're not signed, this is all you get
2056 if (!this->isSigned())
2057 return dict
.yield();
2060 // Add the generic attributes that we always include
2062 CFDictionaryAddValue(dict
, kSecCodeInfoIdentifier
, CFTempString(this->identifier()));
2063 CFDictionaryAddValue(dict
, kSecCodeInfoFlags
, CFTempNumber(this->codeDirectory(false)->flags
.get()));
2064 CFDictionaryAddValue(dict
, kSecCodeInfoFormat
, CFTempString(this->format()));
2065 CFDictionaryAddValue(dict
, kSecCodeInfoSource
, CFTempString(this->signatureSource()));
2066 CFDictionaryAddValue(dict
, kSecCodeInfoUnique
, this->cdHash());
2067 CFDictionaryAddValue(dict
, kSecCodeInfoCdHashes
, this->cdHashes());
2068 CFDictionaryAddValue(dict
, kSecCodeInfoCdHashesFull
, this->cdHashesFull());
2069 const CodeDirectory
* cd
= this->codeDirectory(false);
2070 CFDictionaryAddValue(dict
, kSecCodeInfoDigestAlgorithm
, CFTempNumber(cd
->hashType
));
2071 CFRef
<CFArrayRef
> digests
= makeCFArrayFrom(^CFTypeRef(CodeDirectory::HashAlgorithm type
) { return CFTempNumber(type
); }, hashAlgorithms());
2072 CFDictionaryAddValue(dict
, kSecCodeInfoDigestAlgorithms
, digests
);
2074 CFDictionaryAddValue(dict
, kSecCodeInfoPlatformIdentifier
, CFTempNumber(cd
->platform
));
2075 if (cd
->runtimeVersion()) {
2076 CFDictionaryAddValue(dict
, kSecCodeInfoRuntimeVersion
, CFTempNumber(cd
->runtimeVersion()));
2080 // Deliver any Info.plist only if it looks intact
2083 if (CFDictionaryRef info
= this->infoDictionary())
2084 CFDictionaryAddValue(dict
, kSecCodeInfoPList
, info
);
2085 } catch (...) { } // don't deliver Info.plist if questionable
2088 // kSecCSSigningInformation adds information about signing certificates and chains
2090 if (flags
& kSecCSSigningInformation
)
2092 if (CFDataRef sig
= this->signature())
2093 CFDictionaryAddValue(dict
, kSecCodeInfoCMS
, sig
);
2094 if (const char *teamID
= this->teamID())
2095 CFDictionaryAddValue(dict
, kSecCodeInfoTeamIdentifier
, CFTempString(teamID
));
2097 CFDictionaryAddValue(dict
, kSecCodeInfoTrust
, mTrust
);
2098 if (CFArrayRef certs
= this->certificates())
2099 CFDictionaryAddValue(dict
, kSecCodeInfoCertificates
, certs
);
2100 if (CFAbsoluteTime time
= this->signingTime())
2101 if (CFRef
<CFDateRef
> date
= CFDateCreate(NULL
, time
))
2102 CFDictionaryAddValue(dict
, kSecCodeInfoTime
, date
);
2103 if (CFAbsoluteTime time
= this->signingTimestamp())
2104 if (CFRef
<CFDateRef
> date
= CFDateCreate(NULL
, time
))
2105 CFDictionaryAddValue(dict
, kSecCodeInfoTimestamp
, date
);
2109 // kSecCSRequirementInformation adds information on requirements
2111 if (flags
& kSecCSRequirementInformation
)
2113 //DR not currently supported on iOS
2116 if (const Requirements
*reqs
= this->internalRequirements()) {
2117 CFDictionaryAddValue(dict
, kSecCodeInfoRequirements
,
2118 CFTempString(Dumper::dump(reqs
)));
2119 CFDictionaryAddValue(dict
, kSecCodeInfoRequirementData
, CFTempData(*reqs
));
2122 const Requirement
*dreq
= this->designatedRequirement();
2123 CFRef
<SecRequirementRef
> dreqRef
= (new SecRequirement(dreq
))->handle();
2124 CFDictionaryAddValue(dict
, kSecCodeInfoDesignatedRequirement
, dreqRef
);
2125 if (this->internalRequirement(kSecDesignatedRequirementType
)) { // explicit
2126 CFRef
<SecRequirementRef
> ddreqRef
= (new SecRequirement(this->defaultDesignatedRequirement(), true))->handle();
2127 CFDictionaryAddValue(dict
, kSecCodeInfoImplicitDesignatedRequirement
, ddreqRef
);
2128 } else { // implicit
2129 CFDictionaryAddValue(dict
, kSecCodeInfoImplicitDesignatedRequirement
, dreqRef
);
2135 if (CFDataRef ent
= this->component(cdEntitlementSlot
)) {
2136 CFDictionaryAddValue(dict
, kSecCodeInfoEntitlements
, ent
);
2137 if (CFDictionaryRef entdict
= this->entitlements()) {
2138 if (needsCatalystEntitlementFixup(entdict
)) {
2139 // If this entitlement dictionary needs catalyst entitlements, make a copy and stick that into the
2140 // output dictionary instead.
2141 secinfo("staticCode", "%p fixed catalyst entitlements", this);
2142 CFRef
<CFMutableDictionaryRef
> tempEntitlements
= makeCFMutableDictionary(entdict
);
2143 updateCatalystEntitlements(tempEntitlements
);
2144 CFRef
<CFDictionaryRef
> newEntitlements
= CFDictionaryCreateCopy(NULL
, tempEntitlements
);
2145 if (newEntitlements
) {
2146 CFDictionaryAddValue(dict
, kSecCodeInfoEntitlementsDict
, newEntitlements
.get());
2148 secerror("%p unable to fixup entitlement dictionary", this);
2149 CFDictionaryAddValue(dict
, kSecCodeInfoEntitlementsDict
, entdict
);
2152 CFDictionaryAddValue(dict
, kSecCodeInfoEntitlementsDict
, entdict
);
2159 // kSecCSInternalInformation adds internal information meant to be for Apple internal
2160 // use (SPI), and not guaranteed to be stable. Primarily, this is data we want
2161 // to reliably transmit through the API wall so that code outside the Security.framework
2162 // can use it without having to play nasty tricks to get it.
2164 if (flags
& kSecCSInternalInformation
) {
2167 CFDictionaryAddValue(dict
, kSecCodeInfoCodeDirectory
, mDir
);
2168 CFDictionaryAddValue(dict
, kSecCodeInfoCodeOffset
, CFTempNumber(mRep
->signingBase()));
2169 if (!(flags
& kSecCSSkipResourceDirectory
)) {
2170 if (CFRef
<CFDictionaryRef
> rdict
= getDictionary(cdResourceDirSlot
, false)) // suppress validation
2171 CFDictionaryAddValue(dict
, kSecCodeInfoResourceDirectory
, rdict
);
2173 if (CFRef
<CFDictionaryRef
> ddict
= diskRepInformation())
2174 CFDictionaryAddValue(dict
, kSecCodeInfoDiskRepInfo
, ddict
);
2176 if (mNotarizationChecked
&& !isnan(mNotarizationDate
)) {
2177 CFRef
<CFDateRef
> date
= CFDateCreate(NULL
, mNotarizationDate
);
2179 CFDictionaryAddValue(dict
, kSecCodeInfoNotarizationDate
, date
.get());
2181 secerror("Error creating date from timestamp: %f", mNotarizationDate
);
2184 if (this->codeDirectory()) {
2185 uint32_t version
= this->codeDirectory()->version
;
2186 CFDictionaryAddValue(dict
, kSecCodeInfoSignatureVersion
, CFTempNumber(version
));
2190 if (flags
& kSecCSCalculateCMSDigest
) {
2192 CFDictionaryAddValue(dict
, kSecCodeInfoCMSDigestHashType
, CFTempNumber(cmsDigestHashType()));
2194 CFRef
<CFDataRef
> cmsDigest
= createCmsDigest();
2196 CFDictionaryAddValue(dict
, kSecCodeInfoCMSDigest
, cmsDigest
.get());
2202 // kSecCSContentInformation adds more information about the physical layout
2203 // of the signed code. This is (only) useful for packaging or patching-oriented
2206 if (flags
& kSecCSContentInformation
&& !(flags
& kSecCSSkipResourceDirectory
))
2207 if (CFRef
<CFArrayRef
> files
= mRep
->modifiedFiles())
2208 CFDictionaryAddValue(dict
, kSecCodeInfoChangedFiles
, files
);
2210 return dict
.yield();
2215 // Resource validation contexts.
2216 // The default context simply throws a CSError, rudely terminating the operation.
2218 SecStaticCode::ValidationContext::~ValidationContext()
2221 void SecStaticCode::ValidationContext::reportProblem(OSStatus rc
, CFStringRef type
, CFTypeRef value
)
2223 CSError::throwMe(rc
, type
, value
);
2226 void SecStaticCode::CollectingContext::reportProblem(OSStatus rc
, CFStringRef type
, CFTypeRef value
)
2228 StLock
<Mutex
> _(mLock
);
2229 if (mStatus
== errSecSuccess
)
2230 mStatus
= rc
; // record first failure for eventual error return
2233 mCollection
.take(makeCFMutableDictionary());
2234 CFMutableArrayRef element
= CFMutableArrayRef(CFDictionaryGetValue(mCollection
, type
));
2236 element
= makeCFMutableArray(0);
2239 CFDictionaryAddValue(mCollection
, type
, element
);
2242 CFArrayAppendValue(element
, value
);
2246 void SecStaticCode::CollectingContext::throwMe()
2248 assert(mStatus
!= errSecSuccess
);
2249 throw CSError(mStatus
, mCollection
.retain());
2254 // Master validation driver.
2255 // This is the static validation (only) driver for the API.
2257 // SecStaticCode exposes an a la carte menu of topical validators applying
2258 // to a given object. The static validation API pulls them together reliably,
2259 // but it also adds three matrix dimensions: architecture (for "fat" Mach-O binaries),
2260 // nested code, and multiple digests. This function will crawl a suitable cross-section of this
2261 // validation matrix based on which options it is given, creating temporary
2262 // SecStaticCode objects on the fly to complete the task.
2263 // (The point, of course, is to do as little duplicate work as possible.)
2265 void SecStaticCode::staticValidate(SecCSFlags flags
, const SecRequirement
*req
)
2267 setValidationFlags(flags
);
2270 if (!mStaplingChecked
) {
2271 mRep
->registerStapledTicket();
2272 mStaplingChecked
= true;
2275 if (mFlags
& kSecCSForceOnlineNotarizationCheck
) {
2276 if (!mNotarizationChecked
) {
2277 if (this->cdHash()) {
2278 bool is_revoked
= checkNotarizationServiceForRevocation(this->cdHash(), (SecCSDigestAlgorithm
)this->hashAlgorithm(), &mNotarizationDate
);
2280 MacOSError::throwMe(errSecCSRevokedNotarization
);
2283 mNotarizationChecked
= true;
2286 #endif // TARGET_OS_OSX
2288 // initialize progress/cancellation state
2289 if (flags
& kSecCSReportProgress
)
2290 prepareProgress(estimateResourceWorkload() + 2); // +1 head, +1 tail
2293 // core components: once per architecture (if any)
2294 this->staticValidateCore(flags
, req
);
2295 if (flags
& kSecCSCheckAllArchitectures
)
2296 handleOtherArchitectures(^(SecStaticCode
* subcode
) {
2297 if (flags
& kSecCSCheckGatekeeperArchitectures
) {
2298 Universal
*fat
= subcode
->diskRep()->mainExecutableImage();
2299 assert(fat
&& fat
->narrowed()); // handleOtherArchitectures gave us a focused architecture slice
2300 Architecture arch
= fat
->bestNativeArch(); // actually, the ONLY one
2301 if ((arch
.cpuType() & ~CPU_ARCH_MASK
) == CPU_TYPE_POWERPC
)
2302 return; // irrelevant to Gatekeeper
2304 subcode
->detachedSignature(this->mDetachedSig
); // carry over explicit (but not implicit) detached signature
2305 subcode
->staticValidateCore(flags
, req
);
2309 // allow monitor intervention in source validation phase
2310 reportEvent(CFSTR("prepared"), NULL
);
2312 // resources: once for all architectures
2313 if (!(flags
& kSecCSDoNotValidateResources
)) {
2314 this->validateResources(flags
);
2317 // perform strict validation if desired
2318 if (flags
& kSecCSStrictValidate
) {
2319 mRep
->strictValidate(codeDirectory(), mTolerateErrors
, mValidationFlags
);
2321 } else if (flags
& kSecCSStrictValidateStructure
) {
2322 mRep
->strictValidateStructure(codeDirectory(), mTolerateErrors
, mValidationFlags
);
2325 // allow monitor intervention
2326 if (CFRef
<CFTypeRef
> veto
= reportEvent(CFSTR("validated"), NULL
)) {
2327 if (CFGetTypeID(veto
) == CFNumberGetTypeID())
2328 MacOSError::throwMe(cfNumber
<OSStatus
>(veto
.as
<CFNumberRef
>()));
2330 MacOSError::throwMe(errSecCSBadCallbackValue
);
2334 void SecStaticCode::staticValidateCore(SecCSFlags flags
, const SecRequirement
*req
)
2337 this->validateNonResourceComponents(); // also validates the CodeDirectory
2338 this->validateTopDirectory();
2339 if (!(flags
& kSecCSDoNotValidateExecutable
))
2340 this->validateExecutable();
2342 this->validateRequirement(req
->requirement(), errSecCSReqFailed
);
2343 } catch (CSError
&err
) {
2344 if (Universal
*fat
= this->diskRep()->mainExecutableImage()) // Mach-O
2345 if (MachO
*mach
= fat
->architecture()) {
2346 err
.augment(kSecCFErrorArchitecture
, CFTempString(mach
->architecture().displayName()));
2350 } catch (const MacOSError
&err
) {
2351 // add architecture information if we can get it
2352 if (Universal
*fat
= this->diskRep()->mainExecutableImage())
2353 if (MachO
*mach
= fat
->architecture()) {
2354 CFTempString
arch(mach
->architecture().displayName());
2356 CSError::throwMe(err
.error
, kSecCFErrorArchitecture
, arch
);
2364 // A helper that generates SecStaticCode objects for all but the primary architecture
2365 // of a fat binary and calls a block on them.
2366 // If there's only one architecture (or this is an architecture-agnostic code),
2367 // nothing happens quickly.
2369 void SecStaticCode::handleOtherArchitectures(void (^handle
)(SecStaticCode
* other
))
2371 if (Universal
*fat
= this->diskRep()->mainExecutableImage()) {
2372 Universal::Architectures architectures
;
2373 fat
->architectures(architectures
);
2374 if (architectures
.size() > 1) {
2375 DiskRep::Context ctx
;
2376 off_t activeOffset
= fat
->archOffset();
2377 for (Universal::Architectures::const_iterator arch
= architectures
.begin(); arch
!= architectures
.end(); ++arch
) {
2379 ctx
.offset
= int_cast
<size_t, off_t
>(fat
->archOffset(*arch
));
2380 ctx
.size
= fat
->lengthOfSlice(int_cast
<off_t
,size_t>(ctx
.offset
));
2381 if (ctx
.offset
!= activeOffset
) { // inactive architecture; check it
2382 SecPointer
<SecStaticCode
> subcode
= new SecStaticCode(DiskRep::bestGuess(this->mainExecutablePath(), &ctx
));
2383 subcode
->detachedSignature(this->mDetachedSig
); // carry over explicit (but not implicit) detached signature
2384 if (this->teamID() == NULL
|| subcode
->teamID() == NULL
) {
2385 if (this->teamID() != subcode
->teamID())
2386 MacOSError::throwMe(errSecCSSignatureInvalid
);
2387 } else if (strcmp(this->teamID(), subcode
->teamID()) != 0)
2388 MacOSError::throwMe(errSecCSSignatureInvalid
);
2391 } catch(std::out_of_range e
) {
2392 // some of our int_casts fell over.
2393 MacOSError::throwMe(errSecCSBadObjectFormat
);
2401 // A method that takes a certificate chain (certs) and evaluates
2402 // if it is a Mac or IPhone developer cert, an app store distribution cert,
2403 // or a developer ID
2405 bool SecStaticCode::isAppleDeveloperCert(CFArrayRef certs
)
2407 static const std::string appleDeveloperRequirement
= "(" + std::string(WWDRRequirement
) + ") or (" + MACWWDRRequirement
+ ") or (" + developerID
+ ") or (" + distributionCertificate
+ ") or (" + iPhoneDistributionCert
+ ")";
2408 SecPointer
<SecRequirement
> req
= new SecRequirement(parseRequirement(appleDeveloperRequirement
), true);
2409 Requirement::Context
ctx(certs
, NULL
, NULL
, "", NULL
, NULL
, kSecCodeSignatureNoHash
, false, NULL
, "");
2411 return req
->requirement()->validates(ctx
);
2414 CFDataRef
SecStaticCode::createCmsDigest()
2417 * The CMS digest is a hash of the primary (first, most compatible) code directory,
2418 * but its hash algorithm is fixed and not related to the code directory's
2422 auto it
= codeDirectories()->begin();
2424 if (it
== codeDirectories()->end()) {
2428 CodeDirectory
const * const cd
= reinterpret_cast<CodeDirectory
const*>(CFDataGetBytePtr(it
->second
));
2430 RefPointer
<DynamicHash
> hash
= cd
->hashFor(mCMSDigestHashType
);
2431 CFMutableDataRef data
= CFDataCreateMutable(NULL
, hash
->digestLength());
2432 CFDataSetLength(data
, hash
->digestLength());
2433 hash
->update(cd
, cd
->length());
2434 hash
->finish(CFDataGetMutableBytePtr(data
));
2439 } // end namespace CodeSigning
2440 } // end namespace Security