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>
73 namespace CodeSigning
{
75 using namespace UnixPlusPlus
;
77 // A requirement representing a Mac or iOS dev cert, a Mac or iOS distribution cert, or a developer ID
78 static const char WWDRRequirement
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.2] exists";
79 static const char MACWWDRRequirement
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.12] exists";
80 static const char developerID
[] = "anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists"
81 " and certificate leaf[field.1.2.840.113635.100.6.1.13] exists";
82 static const char distributionCertificate
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.7] exists";
83 static const char iPhoneDistributionCert
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.4] exists";
86 // Map a component slot number to a suitable error code for a failure
88 static inline OSStatus
errorForSlot(CodeDirectory::SpecialSlot slot
)
92 return errSecCSInfoPlistFailed
;
93 case cdResourceDirSlot
:
94 return errSecCSResourceDirectoryFailed
;
96 return errSecCSSignatureFailed
;
102 // Construct a SecStaticCode object given a disk representation object
104 SecStaticCode::SecStaticCode(DiskRep
*rep
, uint32_t flags
)
105 : mCheckfix30814861builder1(NULL
),
107 mValidated(false), mExecutableValidated(false), mResourcesValidated(false), mResourcesValidContext(NULL
),
108 mProgressQueue("com.apple.security.validation-progress", false, QOS_CLASS_UNSPECIFIED
),
109 mOuterScope(NULL
), mResourceScope(NULL
),
110 mDesignatedReq(NULL
), mGotResourceBase(false), mMonitor(NULL
), mLimitedAsync(NULL
),
111 mFlags(flags
), mNotarizationChecked(false), mStaplingChecked(false), mNotarizationDate(NAN
)
115 , mTrustedSigningCertChain(false)
119 CODESIGN_STATIC_CREATE(this, rep
);
121 checkForSystemSignature();
127 // Clean up a SecStaticCode object
129 SecStaticCode::~SecStaticCode() throw()
131 ::free(const_cast<Requirement
*>(mDesignatedReq
));
132 delete mResourcesValidContext
;
133 delete mLimitedAsync
;
134 delete mCheckfix30814861builder1
;
140 // Initialize a nested SecStaticCode object from its parent
142 void SecStaticCode::initializeFromParent(const SecStaticCode
& parent
) {
143 mOuterScope
= &parent
;
144 setMonitor(parent
.monitor());
145 if (parent
.mLimitedAsync
)
146 mLimitedAsync
= new LimitedAsync(*parent
.mLimitedAsync
);
150 // CF-level comparison of SecStaticCode objects compares CodeDirectory hashes if signed,
151 // and falls back on comparing canonical paths if (both are) not.
153 bool SecStaticCode::equal(SecCFObject
&secOther
)
155 SecStaticCode
*other
= static_cast<SecStaticCode
*>(&secOther
);
156 CFDataRef mine
= this->cdHash();
157 CFDataRef his
= other
->cdHash();
159 return mine
&& his
&& CFEqual(mine
, his
);
161 return CFEqual(CFRef
<CFURLRef
>(this->copyCanonicalPath()), CFRef
<CFURLRef
>(other
->copyCanonicalPath()));
164 CFHashCode
SecStaticCode::hash()
166 if (CFDataRef h
= this->cdHash())
169 return CFHash(CFRef
<CFURLRef
>(this->copyCanonicalPath()));
174 // Invoke a stage monitor if registered
176 CFTypeRef
SecStaticCode::reportEvent(CFStringRef stage
, CFDictionaryRef info
)
179 return mMonitor(this->handle(false), stage
, info
);
184 void SecStaticCode::prepareProgress(unsigned int workload
)
186 dispatch_sync(mProgressQueue
, ^{
187 mCancelPending
= false; // not canceled
189 if (mValidationFlags
& kSecCSReportProgress
) {
190 mCurrentWork
= 0; // nothing done yet
191 mTotalWork
= workload
; // totally fake - we don't know how many files we'll get to chew
195 void SecStaticCode::reportProgress(unsigned amount
/* = 1 */)
197 if (mMonitor
&& (mValidationFlags
& kSecCSReportProgress
)) {
198 // update progress and report
199 __block
bool cancel
= false;
200 dispatch_sync(mProgressQueue
, ^{
203 mCurrentWork
+= amount
;
204 mMonitor(this->handle(false), CFSTR("progress"), CFTemp
<CFDictionaryRef
>("{current=%d,total=%d}", mCurrentWork
, mTotalWork
));
206 // if cancellation is pending, abort now
208 MacOSError::throwMe(errSecCSCancelled
);
214 // Set validation conditions for fine-tuning legacy tolerance
216 static void addError(CFTypeRef cfError
, void* context
)
218 if (CFGetTypeID(cfError
) == CFNumberGetTypeID()) {
220 CFNumberGetValue(CFNumberRef(cfError
), kCFNumberSInt64Type
, (void*)&error
);
221 MacOSErrorSet
* errors
= (MacOSErrorSet
*)context
;
222 errors
->insert(OSStatus(error
));
226 void SecStaticCode::setValidationModifiers(CFDictionaryRef conditions
)
229 CFDictionary
source(conditions
, errSecCSDbCorrupt
);
230 mAllowOmissions
= source
.get
<CFArrayRef
>("omissions");
231 if (CFArrayRef errors
= source
.get
<CFArrayRef
>("errors"))
232 CFArrayApplyFunction(errors
, CFRangeMake(0, CFArrayGetCount(errors
)), addError
, &this->mTolerateErrors
);
238 // Request cancellation of a validation in progress.
239 // We do this by posting an abort flag that is checked periodically.
241 void SecStaticCode::cancelValidation()
243 if (!(mValidationFlags
& kSecCSReportProgress
)) // not using progress reporting; cancel won't make it through
244 MacOSError::throwMe(errSecCSInvalidFlags
);
245 dispatch_assert_queue(mProgressQueue
);
246 mCancelPending
= true;
251 // Attach a detached signature.
253 void SecStaticCode::detachedSignature(CFDataRef sigData
)
256 mDetachedSig
= sigData
;
257 mRep
= new DetachedRep(sigData
, mRep
->base(), "explicit detached");
258 CODESIGN_STATIC_ATTACH_EXPLICIT(this, mRep
);
262 CODESIGN_STATIC_ATTACH_EXPLICIT(this, NULL
);
268 // Consult the system detached signature database to see if it contains
269 // a detached signature for this StaticCode. If it does, fetch and attach it.
270 // We do this only if the code has no signature already attached.
272 void SecStaticCode::checkForSystemSignature()
275 if (!this->isSigned()) {
276 SignatureDatabase db
;
279 if (RefPointer
<DiskRep
> dsig
= db
.findCode(mRep
)) {
280 CODESIGN_STATIC_ATTACH_SYSTEM(this, dsig
);
287 MacOSError::throwMe(errSecUnimplemented
);
293 // Return a descriptive string identifying the source of the code signature
295 string
SecStaticCode::signatureSource()
299 if (DetachedRep
*rep
= dynamic_cast<DetachedRep
*>(mRep
.get()))
300 return rep
->source();
306 // Do ::required, but convert incoming SecCodeRefs to their SecStaticCodeRefs
309 SecStaticCode
*SecStaticCode::requiredStatic(SecStaticCodeRef ref
)
311 SecCFObject
*object
= SecCFObject::required(ref
, errSecCSInvalidObjectRef
);
312 if (SecStaticCode
*scode
= dynamic_cast<SecStaticCode
*>(object
))
314 else if (SecCode
*code
= dynamic_cast<SecCode
*>(object
))
315 return code
->staticCode();
316 else // neither (a SecSomethingElse)
317 MacOSError::throwMe(errSecCSInvalidObjectRef
);
320 SecCode
*SecStaticCode::optionalDynamic(SecStaticCodeRef ref
)
322 SecCFObject
*object
= SecCFObject::required(ref
, errSecCSInvalidObjectRef
);
323 if (dynamic_cast<SecStaticCode
*>(object
))
325 else if (SecCode
*code
= dynamic_cast<SecCode
*>(object
))
327 else // neither (a SecSomethingElse)
328 MacOSError::throwMe(errSecCSInvalidObjectRef
);
333 // Void all cached validity data.
335 // We also throw out cached components, because the new signature data may have
336 // a different idea of what components should be present. We could reconcile the
337 // cached data instead, if performance seems to be impacted.
339 void SecStaticCode::resetValidity()
341 CODESIGN_EVAL_STATIC_RESET(this);
343 mExecutableValidated
= mResourcesValidated
= false;
344 if (mResourcesValidContext
) {
345 delete mResourcesValidContext
;
346 mResourcesValidContext
= NULL
;
349 mCodeDirectories
.clear();
351 for (unsigned n
= 0; n
< cdSlotCount
; n
++)
354 mEntitlements
= NULL
;
355 mResourceDict
= NULL
;
356 mDesignatedReq
= NULL
;
358 mGotResourceBase
= false;
361 mNotarizationChecked
= false;
362 mStaplingChecked
= false;
363 mNotarizationDate
= NAN
;
370 // we may just have updated the system database, so check again
371 checkForSystemSignature();
377 // Retrieve a sealed component by special slot index.
378 // If the CodeDirectory has already been validated, validate against that.
379 // Otherwise, retrieve the component without validation (but cache it). Validation
380 // will go through the cache and validate all cached components.
382 CFDataRef
SecStaticCode::component(CodeDirectory::SpecialSlot slot
, OSStatus fail
/* = errSecCSSignatureFailed */)
384 assert(slot
<= cdSlotMax
);
386 CFRef
<CFDataRef
> &cache
= mCache
[slot
];
388 if (CFRef
<CFDataRef
> data
= mRep
->component(slot
)) {
389 if (validated()) { // if the directory has been validated...
390 if (!codeDirectory()->slotIsPresent(-slot
))
393 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data
), // ... and it's no good
394 CFDataGetLength(data
), -slot
, false))
395 MacOSError::throwMe(errorForSlot(slot
)); // ... then bail
397 cache
= data
; // it's okay, cache it
398 } else { // absent, mark so
399 if (validated()) // if directory has been validated...
400 if (codeDirectory()->slotIsPresent(-slot
)) // ... and the slot is NOT missing
401 MacOSError::throwMe(errorForSlot(slot
)); // was supposed to be there
402 cache
= CFDataRef(kCFNull
); // white lie
405 return (cache
== CFDataRef(kCFNull
)) ? NULL
: cache
.get();
410 // Get the CodeDirectories.
411 // Throws (if check==true) or returns NULL (check==false) if there are none.
412 // Always throws if the CodeDirectories exist but are invalid.
413 // NEVER validates against the signature.
415 const SecStaticCode::CodeDirectoryMap
*
416 SecStaticCode::codeDirectories(bool check
/* = true */) const
418 if (mCodeDirectories
.empty()) {
420 loadCodeDirectories(mCodeDirectories
);
424 // We wanted a NON-checked peek and failed to safely decode the existing CodeDirectories.
425 // Pretend this is unsigned, but make sure we didn't somehow cache an invalid CodeDirectory.
426 if (!mCodeDirectories
.empty()) {
428 Syslog::warning("code signing internal problem: mCodeDirectories set despite exception exit");
429 MacOSError::throwMe(errSecCSInternalError
);
433 return &mCodeDirectories
;
435 if (!mCodeDirectories
.empty()) {
436 return &mCodeDirectories
;
439 MacOSError::throwMe(errSecCSUnsigned
);
445 // Get the CodeDirectory.
446 // Throws (if check==true) or returns NULL (check==false) if there is none.
447 // Always throws if the CodeDirectory exists but is invalid.
448 // NEVER validates against the signature.
450 const CodeDirectory
*SecStaticCode::codeDirectory(bool check
/* = true */) const
453 // pick our favorite CodeDirectory from the choices we've got
455 CodeDirectoryMap
const *candidates
= codeDirectories(check
);
456 if (candidates
!= NULL
) {
457 CodeDirectory::HashAlgorithm type
= CodeDirectory::bestHashOf(mHashAlgorithms
);
458 mDir
= candidates
->at(type
); // and the winner is...
463 // We wanted a NON-checked peek and failed to safely decode the existing CodeDirectory.
464 // Pretend this is unsigned, but make sure we didn't somehow cache an invalid CodeDirectory.
467 Syslog::warning("code signing internal problem: mDir set despite exception exit");
468 MacOSError::throwMe(errSecCSInternalError
);
473 return reinterpret_cast<const CodeDirectory
*>(CFDataGetBytePtr(mDir
));
475 MacOSError::throwMe(errSecCSUnsigned
);
481 // Fetch an array of all available CodeDirectories.
482 // Returns false if unsigned (no classic CD slot), true otherwise.
484 bool SecStaticCode::loadCodeDirectories(CodeDirectoryMap
& cdMap
) const
486 __block CodeDirectoryMap candidates
;
487 __block
CodeDirectory::HashAlgorithms hashAlgorithms
;
488 __block CFRef
<CFDataRef
> baseDir
;
489 auto add
= ^bool (CodeDirectory::SpecialSlot slot
){
490 CFRef
<CFDataRef
> cdData
= diskRep()->component(slot
);
493 const CodeDirectory
* cd
= reinterpret_cast<const CodeDirectory
*>(CFDataGetBytePtr(cdData
));
494 if (!cd
->validateBlob(CFDataGetLength(cdData
)))
495 MacOSError::throwMe(errSecCSSignatureFailed
); // no recovery - any suspect CD fails
496 cd
->checkIntegrity();
497 auto result
= candidates
.insert(make_pair(cd
->hashType
, cdData
.get()));
499 MacOSError::throwMe(errSecCSSignatureInvalid
); // duplicate hashType, go to heck
500 hashAlgorithms
.insert(cd
->hashType
);
501 if (slot
== cdCodeDirectorySlot
)
505 if (!add(cdCodeDirectorySlot
))
506 return false; // no classic slot CodeDirectory -> unsigned
507 for (CodeDirectory::SpecialSlot slot
= cdAlternateCodeDirectorySlots
; slot
< cdAlternateCodeDirectoryLimit
; slot
++)
508 if (!add(slot
)) // no CodeDirectory at this slot -> end of alternates
510 if (candidates
.empty())
511 MacOSError::throwMe(errSecCSSignatureFailed
); // no viable CodeDirectory in sight
512 // commit to cached values
513 cdMap
.swap(candidates
);
514 mHashAlgorithms
.swap(hashAlgorithms
);
521 // Get the hash of the CodeDirectory.
522 // Returns NULL if there is none.
524 CFDataRef
SecStaticCode::cdHash()
527 if (const CodeDirectory
*cd
= codeDirectory(false)) {
528 mCDHash
.take(cd
->cdhash());
529 CODESIGN_STATIC_CDHASH(this, CFDataGetBytePtr(mCDHash
), (unsigned int)CFDataGetLength(mCDHash
));
537 // Get an array of the cdhashes for all digest types in this signature
538 // The array is sorted by cd->hashType.
540 CFArrayRef
SecStaticCode::cdHashes()
543 CFRef
<CFMutableArrayRef
> cdList
= makeCFMutableArray(0);
544 for (auto it
= mCodeDirectories
.begin(); it
!= mCodeDirectories
.end(); ++it
) {
545 const CodeDirectory
*cd
= (const CodeDirectory
*)CFDataGetBytePtr(it
->second
);
546 if (CFRef
<CFDataRef
> hash
= cd
->cdhash())
547 CFArrayAppendValue(cdList
, hash
);
549 mCDHashes
= cdList
.get();
555 // Get a dictionary of untruncated cdhashes for all digest types in this signature.
557 CFDictionaryRef
SecStaticCode::cdHashesFull()
559 if (!mCDHashFullDict
) {
560 CFRef
<CFMutableDictionaryRef
> cdDict
= makeCFMutableDictionary();
561 for (auto const &it
: mCodeDirectories
) {
562 CodeDirectory::HashAlgorithm alg
= it
.first
;
563 const CodeDirectory
*cd
= (const CodeDirectory
*)CFDataGetBytePtr(it
.second
);
564 CFRef
<CFDataRef
> hash
= cd
->cdhash(false);
566 CFDictionaryAddValue(cdDict
, CFTempNumber(alg
), hash
);
569 mCDHashFullDict
= cdDict
.get();
571 return mCDHashFullDict
;
576 // Return the CMS signature blob; NULL if none found.
578 CFDataRef
SecStaticCode::signature()
581 mSignature
.take(mRep
->signature());
584 MacOSError::throwMe(errSecCSUnsigned
);
589 // Verify the signature on the CodeDirectory.
590 // If this succeeds (doesn't throw), the CodeDirectory is statically trustworthy.
591 // Any outcome (successful or not) is cached for the lifetime of the StaticCode.
593 void SecStaticCode::validateDirectory()
595 // echo previous outcome, if any
596 // track revocation separately, as it may not have been checked
597 // during the initial validation
598 if (!validated() || ((mValidationFlags
& kSecCSEnforceRevocationChecks
) && !revocationChecked()))
600 // perform validation (or die trying)
601 CODESIGN_EVAL_STATIC_DIRECTORY(this);
602 mValidationExpired
= verifySignature();
603 if (mValidationFlags
& kSecCSEnforceRevocationChecks
)
604 mRevocationChecked
= true;
606 for (CodeDirectory::SpecialSlot slot
= codeDirectory()->maxSpecialSlot(); slot
>= 1; --slot
)
607 if (mCache
[slot
]) // if we already loaded that resource...
608 validateComponent(slot
, errorForSlot(slot
)); // ... then check it now
609 mValidated
= true; // we've done the deed...
610 mValidationResult
= errSecSuccess
; // ... and it was good
611 } catch (const CommonError
&err
) {
613 mValidationResult
= err
.osStatus();
616 secinfo("staticCode", "%p validation threw non-common exception", this);
618 Syslog::notice("code signing internal problem: unknown exception thrown by validation");
619 mValidationResult
= errSecCSInternalError
;
623 // XXX: Embedded doesn't have CSSMERR_TP_CERT_EXPIRED so we can't throw it
624 // XXX: This should be implemented for embedded once we implement
625 // XXX: verifySignature and see how we're going to handle expired certs
627 if (mValidationResult
== errSecSuccess
) {
628 if (mValidationExpired
)
629 if ((mValidationFlags
& kSecCSConsiderExpiration
)
630 || (codeDirectory()->flags
& kSecCodeSignatureForceExpiration
))
631 MacOSError::throwMe(CSSMERR_TP_CERT_EXPIRED
);
633 MacOSError::throwMe(mValidationResult
);
639 // Load and validate the CodeDirectory and all components *except* those related to the resource envelope.
640 // Those latter components are checked by validateResources().
642 void SecStaticCode::validateNonResourceComponents()
644 this->validateDirectory();
645 for (CodeDirectory::SpecialSlot slot
= codeDirectory()->maxSpecialSlot(); slot
>= 1; --slot
)
647 case cdResourceDirSlot
: // validated by validateResources
650 this->component(slot
); // loads and validates
657 // Check that any "top index" sealed into the signature conforms to what's actually here.
659 void SecStaticCode::validateTopDirectory()
661 assert(mDir
); // must already have loaded CodeDirectories
662 if (CFDataRef topDirectory
= component(cdTopDirectorySlot
)) {
663 const auto topData
= (const Endian
<uint32_t> *)CFDataGetBytePtr(topDirectory
);
664 const auto topDataEnd
= topData
+ CFDataGetLength(topDirectory
) / sizeof(*topData
);
665 std::vector
<uint32_t> signedVector(topData
, topDataEnd
);
667 std::vector
<uint32_t> foundVector
;
668 foundVector
.push_back(cdCodeDirectorySlot
); // mandatory
669 for (CodeDirectory::Slot slot
= 1; slot
<= cdSlotMax
; ++slot
)
671 foundVector
.push_back(slot
);
672 int alternateCount
= int(mCodeDirectories
.size() - 1); // one will go into cdCodeDirectorySlot
673 for (int n
= 0; n
< alternateCount
; n
++)
674 foundVector
.push_back(cdAlternateCodeDirectorySlots
+ n
);
675 foundVector
.push_back(cdSignatureSlot
); // mandatory (may be empty)
677 if (signedVector
!= foundVector
)
678 MacOSError::throwMe(errSecCSSignatureFailed
);
684 // Get the (signed) signing date from the code signature.
685 // Sadly, we need to validate the signature to get the date (as a side benefit).
686 // This means that you can't get the signing time for invalidly signed code.
688 // We could run the decoder "almost to" verification to avoid this, but there seems
689 // little practical point to such a duplication of effort.
691 CFAbsoluteTime
SecStaticCode::signingTime()
697 CFAbsoluteTime
SecStaticCode::signingTimestamp()
700 return mSigningTimestamp
;
704 #define kSecSHA256HashSize 32
705 // 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
706 // 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
707 // Not Before: Dec 15 00:00:00 2010 GMT
708 // Not After : Dec 14 23:59:59 2012 GMT
709 static const unsigned char ASI_CS_12
[] = {
710 0x77,0x82,0x9C,0x64,0x33,0x45,0x2E,0x4A,0xD3,0xA8,0xE4,0x6F,0x00,0x6C,0x27,0xEA,
711 0xFB,0xD3,0xF2,0x6D,0x50,0xF3,0x6F,0xE0,0xE9,0x6D,0x06,0x59,0x19,0xB5,0x46,0xFF
714 bool SecStaticCode::checkfix41082220(OSStatus cssmTrustResult
)
716 // only applicable to revoked results
717 if (cssmTrustResult
!= CSSMERR_TP_CERT_REVOKED
) {
721 // only this leaf certificate
722 if (CFArrayGetCount(mCertChain
) == 0) {
725 CFRef
<CFDataRef
> leafHash(SecCertificateCopySHA256Digest((SecCertificateRef
)CFArrayGetValueAtIndex(mCertChain
, 0)));
726 if (memcmp(ASI_CS_12
, CFDataGetBytePtr(leafHash
), kSecSHA256HashSize
) != 0) {
730 // detached dmg signature
731 if (!isDetached() || format() != std::string("disk image")) {
736 if (hashAlgorithms().size() != 1 || hashAlgorithm() != kSecCodeSignatureHashSHA1
) {
740 // not a privileged binary - no TeamID and no entitlements
741 if (component(cdEntitlementSlot
) || teamID()) {
745 // no flags and old version
746 if (codeDirectory()->version
!= 0x20100 || codeDirectory()->flags
!= 0) {
750 Security::Syslog::warning("CodeSigning: Check-fix enabled for dmg '%s' with identifier '%s' signed with revoked certificates",
751 mainExecutablePath().c_str(), identifier().c_str());
754 #endif // TARGET_OS_OSX
757 // Verify the CMS signature.
758 // This performs the cryptographic tango. It returns if the signature is valid,
759 // or throws if it is not. As a side effect, a successful return sets up the
760 // cached certificate chain for future use.
761 // Returns true if the signature is expired (the X.509 sense), false if it's not.
762 // Expiration is fatal (throws) if a secure timestamp is included, but not otherwise.
764 bool SecStaticCode::verifySignature()
766 // ad-hoc signed code is considered validly signed by definition
767 if (flag(kSecCodeSignatureAdhoc
)) {
768 CODESIGN_EVAL_STATIC_SIGNATURE_ADHOC(this);
772 DTRACK(CODESIGN_EVAL_STATIC_SIGNATURE
, this, (char*)this->mainExecutablePath().c_str());
774 // decode CMS and extract SecTrust for verification
775 CFRef
<CMSDecoderRef
> cms
;
776 MacOSError::check(CMSDecoderCreate(&cms
.aref())); // create decoder
777 CFDataRef sig
= this->signature();
778 MacOSError::check(CMSDecoderUpdateMessage(cms
, CFDataGetBytePtr(sig
), CFDataGetLength(sig
)));
779 this->codeDirectory(); // load CodeDirectory (sets mDir)
780 MacOSError::check(CMSDecoderSetDetachedContent(cms
, mBaseDir
));
781 MacOSError::check(CMSDecoderFinalizeMessage(cms
));
782 MacOSError::check(CMSDecoderSetSearchKeychain(cms
, cfEmptyArray()));
783 CFRef
<CFArrayRef
> vf_policies(createVerificationPolicies());
784 CFRef
<CFArrayRef
> ts_policies(createTimeStampingAndRevocationPolicies());
786 CMSSignerStatus status
;
787 MacOSError::check(CMSDecoderCopySignerStatus(cms
, 0, vf_policies
,
788 false, &status
, &mTrust
.aref(), NULL
));
790 if (status
!= kCMSSignerValid
) {
793 case kCMSSignerUnsigned
: reason
="kCMSSignerUnsigned"; break;
794 case kCMSSignerNeedsDetachedContent
: reason
="kCMSSignerNeedsDetachedContent"; break;
795 case kCMSSignerInvalidSignature
: reason
="kCMSSignerInvalidSignature"; break;
796 case kCMSSignerInvalidCert
: reason
="kCMSSignerInvalidCert"; break;
797 case kCMSSignerInvalidIndex
: reason
="kCMSSignerInvalidIndex"; break;
798 default: reason
="unknown"; break;
800 Security::Syslog::error("CMSDecoderCopySignerStatus failed with %s error (%d)",
801 reason
, (int)status
);
802 MacOSError::throwMe(errSecCSSignatureFailed
);
805 // retrieve auxiliary v1 data bag and verify against current state
806 CFRef
<CFDataRef
> hashAgilityV1
;
807 switch (OSStatus rc
= CMSDecoderCopySignerAppleCodesigningHashAgility(cms
, 0, &hashAgilityV1
.aref())) {
810 CFRef
<CFDictionaryRef
> hashDict
= makeCFDictionaryFrom(hashAgilityV1
);
811 CFArrayRef cdList
= CFArrayRef(CFDictionaryGetValue(hashDict
, CFSTR("cdhashes")));
812 CFArrayRef myCdList
= this->cdHashes();
814 /* Note that this is not very "agile": There's no way to calculate the exact
815 * list for comparison if it contains hash algorithms we don't know yet... */
816 if (cdList
== NULL
|| !CFEqual(cdList
, myCdList
))
817 MacOSError::throwMe(errSecCSSignatureFailed
);
820 case -1: /* CMS used to return this for "no attribute found", so tolerate it. Now returning noErr/NULL */
823 MacOSError::throwMe(rc
);
826 // retrieve auxiliary v2 data bag and verify against current state
827 CFRef
<CFDictionaryRef
> hashAgilityV2
;
828 switch (OSStatus rc
= CMSDecoderCopySignerAppleCodesigningHashAgilityV2(cms
, 0, &hashAgilityV2
.aref())) {
831 /* Require number of code directoris and entries in the hash agility
832 * dict to be the same size (no stripping out code directories).
834 if (CFDictionaryGetCount(hashAgilityV2
) != mCodeDirectories
.size()) {
835 MacOSError::throwMe(errSecCSSignatureFailed
);
838 /* Require every cdhash of every code directory whose hash
839 * algorithm we know to be in the agility dictionary.
841 * We check untruncated cdhashes here because we can.
843 bool foundOurs
= false;
844 for (auto& entry
: mCodeDirectories
) {
845 SECOidTag tag
= CodeDirectorySet::SECOidTagForAlgorithm(entry
.first
);
847 if (tag
== SEC_OID_UNKNOWN
) {
848 // Unknown hash algorithm, ignore.
852 CFRef
<CFNumberRef
> key
= makeCFNumber(int(tag
));
853 CFRef
<CFDataRef
> entryCdhash
;
854 entryCdhash
= (CFDataRef
)CFDictionaryGetValue(hashAgilityV2
, (void*)key
.get());
856 CodeDirectory
const *cd
= (CodeDirectory
const*)CFDataGetBytePtr(entry
.second
);
857 CFRef
<CFDataRef
> ourCdhash
= cd
->cdhash(false); // Untruncated cdhash!
858 if (!CFEqual(entryCdhash
, ourCdhash
)) {
859 MacOSError::throwMe(errSecCSSignatureFailed
);
862 if (entry
.first
== this->hashAlgorithm()) {
867 /* Require the cdhash of our chosen code directory to be in the dictionary.
868 * In theory, the dictionary could be full of unsupported cdhashes, but we
869 * really want ours, which is bound to be supported, to be covered.
872 MacOSError::throwMe(errSecCSSignatureFailed
);
876 case -1: /* CMS used to return this for "no attribute found", so tolerate it. Now returning noErr/NULL */
879 MacOSError::throwMe(rc
);
882 // internal signing time (as specified by the signer; optional)
883 mSigningTime
= 0; // "not present" marker (nobody could code sign on Jan 1, 2001 :-)
884 switch (OSStatus rc
= CMSDecoderCopySignerSigningTime(cms
, 0, &mSigningTime
)) {
886 case errSecSigningTimeMissing
:
889 Security::Syslog::error("Could not get signing time (error %d)", (int)rc
);
890 MacOSError::throwMe(rc
);
893 // certified signing time (as specified by a TSA; optional)
894 mSigningTimestamp
= 0;
895 switch (OSStatus rc
= CMSDecoderCopySignerTimestampWithPolicy(cms
, ts_policies
, 0, &mSigningTimestamp
)) {
897 case errSecTimestampMissing
:
900 Security::Syslog::error("Could not get timestamp (error %d)", (int)rc
);
901 MacOSError::throwMe(rc
);
904 // set up the environment for SecTrust
905 if (mValidationFlags
& kSecCSNoNetworkAccess
) {
906 MacOSError::check(SecTrustSetNetworkFetchAllowed(mTrust
,false)); // no network?
908 MacOSError::check(SecTrustSetKeychainsAllowed(mTrust
, false));
910 CSSM_APPLE_TP_ACTION_DATA actionData
= {
911 CSSM_APPLE_TP_ACTION_VERSION
, // version of data structure
915 if (!(mValidationFlags
& kSecCSCheckTrustedAnchors
)) {
916 /* no need to evaluate anchor trust when building cert chain */
917 MacOSError::check(SecTrustSetAnchorCertificates(mTrust
, cfEmptyArray())); // no anchors
918 actionData
.ActionFlags
|= CSSM_TP_ACTION_IMPLICIT_ANCHORS
; // action flags
921 for (;;) { // at most twice
922 MacOSError::check(SecTrustSetParameters(mTrust
,
923 CSSM_TP_ACTION_DEFAULT
, CFTempData(&actionData
, sizeof(actionData
))));
925 // evaluate trust and extract results
926 SecTrustResultType trustResult
;
927 MacOSError::check(SecTrustEvaluate(mTrust
, &trustResult
));
928 MacOSError::check(SecTrustGetResult(mTrust
, &trustResult
, &mCertChain
.aref(), &mEvalDetails
));
930 // if this is an Apple developer cert....
931 if (teamID() && SecStaticCode::isAppleDeveloperCert(mCertChain
)) {
932 CFRef
<CFStringRef
> teamIDFromCert
;
933 if (CFArrayGetCount(mCertChain
) > 0) {
934 /* Note that SecCertificateCopySubjectComponent sets the out parameter to NULL if there is no field present */
935 MacOSError::check(SecCertificateCopySubjectComponent((SecCertificateRef
)CFArrayGetValueAtIndex(mCertChain
, Requirement::leafCert
),
936 &CSSMOID_OrganizationalUnitName
,
937 &teamIDFromCert
.aref()));
939 if (teamIDFromCert
) {
940 CFRef
<CFStringRef
> teamIDFromCD
= CFStringCreateWithCString(NULL
, teamID(), kCFStringEncodingUTF8
);
942 Security::Syslog::error("Could not get team identifier (%s)", teamID());
943 MacOSError::throwMe(errSecCSInvalidTeamIdentifier
);
946 if (CFStringCompare(teamIDFromCert
, teamIDFromCD
, 0) != kCFCompareEqualTo
) {
947 Security::Syslog::error("Team identifier in the signing certificate (%s) does not match the team identifier (%s) in the code directory",
948 cfString(teamIDFromCert
).c_str(), teamID());
949 MacOSError::throwMe(errSecCSBadTeamIdentifier
);
955 CODESIGN_EVAL_STATIC_SIGNATURE_RESULT(this, trustResult
, mCertChain
? (int)CFArrayGetCount(mCertChain
) : 0);
956 switch (trustResult
) {
957 case kSecTrustResultProceed
:
958 case kSecTrustResultUnspecified
:
960 case kSecTrustResultDeny
:
961 MacOSError::throwMe(CSSMERR_APPLETP_TRUST_SETTING_DENY
); // user reject
962 case kSecTrustResultInvalid
:
963 assert(false); // should never happen
964 MacOSError::throwMe(CSSMERR_TP_NOT_TRUSTED
);
968 MacOSError::check(SecTrustGetCssmResultCode(mTrust
, &result
));
969 // if we have a valid timestamp, CMS validates against (that) signing time and all is well.
970 // If we don't have one, may validate against *now*, and must be able to tolerate expiration.
971 if (mSigningTimestamp
== 0) { // no timestamp available
972 if (((result
== CSSMERR_TP_CERT_EXPIRED
) || (result
== CSSMERR_TP_CERT_NOT_VALID_YET
))
973 && !(actionData
.ActionFlags
& CSSM_TP_ACTION_ALLOW_EXPIRED
)) {
974 CODESIGN_EVAL_STATIC_SIGNATURE_EXPIRED(this);
975 actionData
.ActionFlags
|= CSSM_TP_ACTION_ALLOW_EXPIRED
; // (this also allows postdated certs)
976 continue; // retry validation while tolerating expiration
979 if (checkfix41082220(result
)) {
982 Security::Syslog::error("SecStaticCode: verification failed (trust result %d, error %d)", trustResult
, (int)result
);
983 MacOSError::throwMe(result
);
987 if (mSigningTimestamp
) {
988 CFIndex rootix
= CFArrayGetCount(mCertChain
);
989 if (SecCertificateRef mainRoot
= SecCertificateRef(CFArrayGetValueAtIndex(mCertChain
, rootix
-1)))
990 if (isAppleCA(mainRoot
)) {
991 // impose policy: if the signature itself draws to Apple, then so must the timestamp signature
992 CFRef
<CFArrayRef
> tsCerts
;
993 OSStatus result
= CMSDecoderCopySignerTimestampCertificates(cms
, 0, &tsCerts
.aref());
995 Security::Syslog::error("SecStaticCode: could not get timestamp certificates (error %d)", (int)result
);
996 MacOSError::check(result
);
998 CFIndex tsn
= CFArrayGetCount(tsCerts
);
999 bool good
= tsn
> 0 && isAppleCA(SecCertificateRef(CFArrayGetValueAtIndex(tsCerts
, tsn
-1)));
1001 result
= CSSMERR_TP_NOT_TRUSTED
;
1002 Security::Syslog::error("SecStaticCode: timestamp policy verification failed (error %d)", (int)result
);
1003 MacOSError::throwMe(result
);
1008 return actionData
.ActionFlags
& CSSM_TP_ACTION_ALLOW_EXPIRED
;
1011 // Do some pre-verification initialization
1012 CFDataRef sig
= this->signature();
1013 this->codeDirectory(); // load CodeDirectory (sets mDir)
1014 mSigningTime
= 0; // "not present" marker (nobody could code sign on Jan 1, 2001 :-)
1016 CFRef
<CFDictionaryRef
> attrs
;
1017 CFRef
<CFArrayRef
> vf_policies(createVerificationPolicies());
1019 // Verify the CMS signature against mBaseDir (SHA1)
1020 MacOSError::check(SecCMSVerifyCopyDataAndAttributes(sig
, mBaseDir
, vf_policies
, &mTrust
.aref(), NULL
, &attrs
.aref()));
1022 // Copy the signing time
1023 mSigningTime
= SecTrustGetVerifyTime(mTrust
);
1025 // Validate the cert chain
1026 SecTrustResultType trustResult
;
1027 MacOSError::check(SecTrustEvaluate(mTrust
, &trustResult
));
1029 // retrieve auxiliary data bag and verify against current state
1030 CFRef
<CFDataRef
> hashBag
;
1031 hashBag
= CFDataRef(CFDictionaryGetValue(attrs
, kSecCMSHashAgility
));
1033 CFRef
<CFDictionaryRef
> hashDict
= makeCFDictionaryFrom(hashBag
);
1034 CFArrayRef cdList
= CFArrayRef(CFDictionaryGetValue(hashDict
, CFSTR("cdhashes")));
1035 CFArrayRef myCdList
= this->cdHashes();
1036 if (cdList
== NULL
|| !CFEqual(cdList
, myCdList
))
1037 MacOSError::throwMe(errSecCSSignatureFailed
);
1041 * Populate mCertChain with the certs. If we failed validation, the
1042 * signer's cert will be checked installed provisioning profiles as an
1043 * alternative to verification against the policy for store-signed binaries
1045 SecCertificateRef leafCert
= SecTrustGetCertificateAtIndex(mTrust
, 0);
1046 if (leafCert
!= NULL
) {
1047 CFIndex count
= SecTrustGetCertificateCount(mTrust
);
1049 CFMutableArrayRef certs
= CFArrayCreateMutable(kCFAllocatorDefault
, count
,
1050 &kCFTypeArrayCallBacks
);
1052 CFArrayAppendValue(certs
, leafCert
);
1053 for (CFIndex i
= 1; i
< count
; ++i
) {
1054 CFArrayAppendValue(certs
, SecTrustGetCertificateAtIndex(mTrust
, i
));
1057 mCertChain
.take((CFArrayRef
)certs
);
1060 // Did we implicitly trust the signer?
1061 mTrustedSigningCertChain
= (trustResult
== kSecTrustResultUnspecified
|| trustResult
== kSecTrustResultProceed
);
1063 return false; // XXX: Not checking for expired certs
1069 // Return the TP policy used for signature verification.
1070 // This may be a simple SecPolicyRef or a CFArray of policies.
1071 // The caller owns the return value.
1073 static SecPolicyRef
makeRevocationPolicy(CFOptionFlags flags
)
1075 CFRef
<SecPolicyRef
> policy(SecPolicyCreateRevocation(flags
));
1076 return policy
.yield();
1080 CFArrayRef
SecStaticCode::createVerificationPolicies()
1082 if (mValidationFlags
& kSecCSUseSoftwareSigningCert
) {
1083 CFRef
<SecPolicyRef
> ssRef
= SecPolicyCreateAppleSoftwareSigning();
1084 return makeCFArray(1, ssRef
.get());
1087 CFRef
<SecPolicyRef
> core
;
1088 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3
,
1089 &CSSMOID_APPLE_TP_CODE_SIGNING
, &core
.aref()));
1090 if (mValidationFlags
& kSecCSNoNetworkAccess
) {
1091 // Skips all revocation since they require network connectivity
1092 // therefore annihilates kSecCSEnforceRevocationChecks if present
1093 CFRef
<SecPolicyRef
> no_revoc
= makeRevocationPolicy(kSecRevocationNetworkAccessDisabled
);
1094 return makeCFArray(2, core
.get(), no_revoc
.get());
1096 else if (mValidationFlags
& kSecCSEnforceRevocationChecks
) {
1097 // Add CRL and OCSP policies
1098 CFRef
<SecPolicyRef
> revoc
= makeRevocationPolicy(kSecRevocationUseAnyAvailableMethod
);
1099 return makeCFArray(2, core
.get(), revoc
.get());
1101 return makeCFArray(1, core
.get());
1104 CFRef
<SecPolicyRef
> tvOSRef
= SecPolicyCreateAppleTVOSApplicationSigning();
1105 return makeCFArray(1, tvOSRef
.get());
1107 CFRef
<SecPolicyRef
> iOSRef
= SecPolicyCreateiPhoneApplicationSigning();
1108 return makeCFArray(1, iOSRef
.get());
1113 CFArrayRef
SecStaticCode::createTimeStampingAndRevocationPolicies()
1115 CFRef
<SecPolicyRef
> tsPolicy
= SecPolicyCreateAppleTimeStamping();
1117 if (mValidationFlags
& kSecCSNoNetworkAccess
) {
1118 // Skips all revocation since they require network connectivity
1119 // therefore annihilates kSecCSEnforceRevocationChecks if present
1120 CFRef
<SecPolicyRef
> no_revoc
= makeRevocationPolicy(kSecRevocationNetworkAccessDisabled
);
1121 return makeCFArray(2, tsPolicy
.get(), no_revoc
.get());
1123 else if (mValidationFlags
& kSecCSEnforceRevocationChecks
) {
1124 // Add CRL and OCSP policies
1125 CFRef
<SecPolicyRef
> revoc
= makeRevocationPolicy(kSecRevocationUseAnyAvailableMethod
);
1126 return makeCFArray(2, tsPolicy
.get(), revoc
.get());
1129 return makeCFArray(1, tsPolicy
.get());
1132 return makeCFArray(1, tsPolicy
.get());
1139 // Validate a particular sealed, cached resource against its (special) CodeDirectory slot.
1140 // The resource must already have been placed in the cache.
1141 // This does NOT perform basic validation.
1143 void SecStaticCode::validateComponent(CodeDirectory::SpecialSlot slot
, OSStatus fail
/* = errSecCSSignatureFailed */)
1145 assert(slot
<= cdSlotMax
);
1146 CFDataRef data
= mCache
[slot
];
1147 assert(data
); // must be cached
1148 if (data
== CFDataRef(kCFNull
)) {
1149 if (codeDirectory()->slotIsPresent(-slot
)) // was supposed to be there...
1150 MacOSError::throwMe(fail
); // ... and is missing
1152 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data
), CFDataGetLength(data
), -slot
, false))
1153 MacOSError::throwMe(fail
);
1159 // Perform static validation of the main executable.
1160 // This reads the main executable from disk and validates it against the
1161 // CodeDirectory code slot array.
1162 // Note that this is NOT an in-memory validation, and is thus potentially
1163 // subject to timing attacks.
1165 void SecStaticCode::validateExecutable()
1167 if (!validatedExecutable()) {
1169 DTRACK(CODESIGN_EVAL_STATIC_EXECUTABLE
, this,
1170 (char*)this->mainExecutablePath().c_str(), codeDirectory()->nCodeSlots
);
1171 const CodeDirectory
*cd
= this->codeDirectory();
1173 MacOSError::throwMe(errSecCSUnsigned
);
1174 AutoFileDesc
fd(mainExecutablePath(), O_RDONLY
);
1175 fd
.fcntl(F_NOCACHE
, true); // turn off page caching (one-pass)
1176 if (Universal
*fat
= mRep
->mainExecutableImage())
1177 fd
.seek(fat
->archOffset());
1178 size_t pageSize
= cd
->pageSize
? (1 << cd
->pageSize
) : 0;
1179 size_t remaining
= cd
->signingLimit();
1180 for (uint32_t slot
= 0; slot
< cd
->nCodeSlots
; ++slot
) {
1181 size_t thisPage
= remaining
;
1183 thisPage
= min(thisPage
, pageSize
);
1184 __block
bool good
= true;
1185 CodeDirectory::multipleHashFileData(fd
, thisPage
, hashAlgorithms(), ^(CodeDirectory::HashAlgorithm type
, Security::DynamicHash
*hasher
) {
1186 const CodeDirectory
* cd
= (const CodeDirectory
*)CFDataGetBytePtr(mCodeDirectories
[type
]);
1187 if (!hasher
->verify(cd
->getSlot(slot
,
1188 mValidationFlags
& kSecCSValidatePEH
)))
1192 CODESIGN_EVAL_STATIC_EXECUTABLE_FAIL(this, (int)slot
);
1193 MacOSError::throwMe(errSecCSSignatureFailed
);
1195 remaining
-= thisPage
;
1197 assert(remaining
== 0);
1198 mExecutableValidated
= true;
1199 mExecutableValidResult
= errSecSuccess
;
1200 } catch (const CommonError
&err
) {
1201 mExecutableValidated
= true;
1202 mExecutableValidResult
= err
.osStatus();
1205 secinfo("staticCode", "%p executable validation threw non-common exception", this);
1206 mExecutableValidated
= true;
1207 mExecutableValidResult
= errSecCSInternalError
;
1208 Syslog::notice("code signing internal problem: unknown exception thrown by validation");
1212 assert(validatedExecutable());
1213 if (mExecutableValidResult
!= errSecSuccess
)
1214 MacOSError::throwMe(mExecutableValidResult
);
1219 // Perform static validation of sealed resources and nested code.
1221 // This performs a whole-code static resource scan and effectively
1222 // computes a concordance between what's on disk and what's in the ResourceDirectory.
1223 // Any unsanctioned difference causes an error.
1225 unsigned SecStaticCode::estimateResourceWorkload()
1227 // workload estimate = number of sealed files
1228 CFDictionaryRef sealedResources
= resourceDictionary();
1229 CFDictionaryRef files
= cfget
<CFDictionaryRef
>(sealedResources
, "files2");
1231 files
= cfget
<CFDictionaryRef
>(sealedResources
, "files");
1232 return files
? unsigned(CFDictionaryGetCount(files
)) : 0;
1235 void SecStaticCode::validateResources(SecCSFlags flags
)
1237 // do we have a superset of this requested validation cached?
1239 if (mResourcesValidated
) { // have cached outcome
1240 if (!(flags
& kSecCSCheckNestedCode
) || mResourcesDeep
) // was deep or need no deep scan
1245 if (mLimitedAsync
== NULL
) {
1246 bool runMultiThreaded
= ((flags
& kSecCSSingleThreaded
) == kSecCSSingleThreaded
) ? false :
1247 (diskRep()->fd().mediumType() == kIOPropertyMediumTypeSolidStateKey
);
1248 mLimitedAsync
= new LimitedAsync(runMultiThreaded
);
1252 CFDictionaryRef rules
;
1253 CFDictionaryRef files
;
1255 if (!loadResources(rules
, files
, version
))
1256 return; // validly no resources; nothing to do (ok)
1258 // found resources, and they are sealed
1259 DTRACK(CODESIGN_EVAL_STATIC_RESOURCES
, this,
1260 (char*)this->mainExecutablePath().c_str(), 0);
1262 // scan through the resources on disk, checking each against the resourceDirectory
1263 mResourcesValidContext
= new CollectingContext(*this); // collect all failures in here
1265 // check for weak resource rules
1266 bool strict
= flags
& kSecCSStrictValidate
;
1268 if (hasWeakResourceRules(rules
, version
, mAllowOmissions
))
1269 if (mTolerateErrors
.find(errSecCSWeakResourceRules
) == mTolerateErrors
.end())
1270 MacOSError::throwMe(errSecCSWeakResourceRules
);
1272 if (mTolerateErrors
.find(errSecCSWeakResourceEnvelope
) == mTolerateErrors
.end())
1273 MacOSError::throwMe(errSecCSWeakResourceEnvelope
);
1276 Dispatch::Group group
;
1277 Dispatch::Group
&groupRef
= group
; // (into block)
1279 // scan through the resources on disk, checking each against the resourceDirectory
1280 __block CFRef
<CFMutableDictionaryRef
> resourceMap
= makeCFMutableDictionary(files
);
1281 string base
= cfString(this->resourceBase());
1282 ResourceBuilder
resources(base
, base
, rules
, strict
, mTolerateErrors
);
1283 this->mResourceScope
= &resources
;
1284 diskRep()->adjustResources(resources
);
1286 resources
.scan(^(FTSENT
*ent
, uint32_t ruleFlags
, const string relpath
, ResourceBuilder::Rule
*rule
) {
1287 CFDictionaryRemoveValue(resourceMap
, CFTempString(relpath
));
1288 bool isSymlink
= (ent
->fts_info
== FTS_SL
);
1290 void (^validate
)() = ^{
1291 validateResource(files
, relpath
, isSymlink
, *mResourcesValidContext
, flags
, version
);
1295 mLimitedAsync
->perform(groupRef
, validate
);
1297 group
.wait(); // wait until all async resources have been validated as well
1299 unsigned leftovers
= unsigned(CFDictionaryGetCount(resourceMap
));
1300 if (leftovers
> 0) {
1301 secinfo("staticCode", "%d sealed resource(s) not found in code", int(leftovers
));
1302 CFDictionaryApplyFunction(resourceMap
, SecStaticCode::checkOptionalResource
, mResourcesValidContext
);
1305 // now check for any errors found in the reporting context
1306 mResourcesValidated
= true;
1307 mResourcesDeep
= flags
& kSecCSCheckNestedCode
;
1308 if (mResourcesValidContext
->osStatus() != errSecSuccess
)
1309 mResourcesValidContext
->throwMe();
1310 } catch (const CommonError
&err
) {
1311 mResourcesValidated
= true;
1312 mResourcesDeep
= flags
& kSecCSCheckNestedCode
;
1313 mResourcesValidResult
= err
.osStatus();
1316 secinfo("staticCode", "%p executable validation threw non-common exception", this);
1317 mResourcesValidated
= true;
1318 mResourcesDeep
= flags
& kSecCSCheckNestedCode
;
1319 mResourcesValidResult
= errSecCSInternalError
;
1320 Syslog::notice("code signing internal problem: unknown exception thrown by validation");
1324 assert(validatedResources());
1325 if (mResourcesValidResult
)
1326 MacOSError::throwMe(mResourcesValidResult
);
1327 if (mResourcesValidContext
->osStatus() != errSecSuccess
)
1328 mResourcesValidContext
->throwMe();
1332 bool SecStaticCode::loadResources(CFDictionaryRef
& rules
, CFDictionaryRef
& files
, uint32_t& version
)
1335 CFDictionaryRef sealedResources
= resourceDictionary();
1336 if (this->resourceBase()) { // disk has resources
1337 if (sealedResources
)
1338 /* go to work below */;
1340 MacOSError::throwMe(errSecCSResourcesNotFound
);
1341 } else { // disk has no resources
1342 if (sealedResources
)
1343 MacOSError::throwMe(errSecCSResourcesNotFound
);
1345 return false; // no resources, not sealed - fine (no work)
1348 // use V2 resource seal if available, otherwise fall back to V1
1349 if (CFDictionaryGetValue(sealedResources
, CFSTR("files2"))) { // have V2 signature
1350 rules
= cfget
<CFDictionaryRef
>(sealedResources
, "rules2");
1351 files
= cfget
<CFDictionaryRef
>(sealedResources
, "files2");
1353 } else { // only V1 available
1354 rules
= cfget
<CFDictionaryRef
>(sealedResources
, "rules");
1355 files
= cfget
<CFDictionaryRef
>(sealedResources
, "files");
1358 if (!rules
|| !files
)
1359 MacOSError::throwMe(errSecCSResourcesInvalid
);
1364 void SecStaticCode::checkOptionalResource(CFTypeRef key
, CFTypeRef value
, void *context
)
1366 ValidationContext
*ctx
= static_cast<ValidationContext
*>(context
);
1367 ResourceSeal
seal(value
);
1368 if (!seal
.optional()) {
1369 if (key
&& CFGetTypeID(key
) == CFStringGetTypeID()) {
1370 CFTempURL
tempURL(CFStringRef(key
), false, ctx
->code
.resourceBase());
1371 if (!tempURL
.get()) {
1372 ctx
->reportProblem(errSecCSBadDictionaryFormat
, kSecCFErrorResourceSeal
, key
);
1374 ctx
->reportProblem(errSecCSBadResource
, kSecCFErrorResourceMissing
, tempURL
);
1377 ctx
->reportProblem(errSecCSBadResource
, kSecCFErrorResourceSeal
, key
);
1383 static bool isOmitRule(CFTypeRef value
)
1385 if (CFGetTypeID(value
) == CFBooleanGetTypeID())
1386 return value
== kCFBooleanFalse
;
1387 CFDictionary
rule(value
, errSecCSResourceRulesInvalid
);
1388 return rule
.get
<CFBooleanRef
>("omit") == kCFBooleanTrue
;
1391 bool SecStaticCode::hasWeakResourceRules(CFDictionaryRef rulesDict
, uint32_t version
, CFArrayRef allowedOmissions
)
1393 // compute allowed omissions
1394 CFRef
<CFArrayRef
> defaultOmissions
= this->diskRep()->allowedResourceOmissions();
1395 if (!defaultOmissions
) {
1396 Syslog::notice("code signing internal problem: diskRep returned no allowedResourceOmissions");
1397 MacOSError::throwMe(errSecCSInternalError
);
1399 CFRef
<CFMutableArrayRef
> allowed
= CFArrayCreateMutableCopy(NULL
, 0, defaultOmissions
);
1400 if (allowedOmissions
)
1401 CFArrayAppendArray(allowed
, allowedOmissions
, CFRangeMake(0, CFArrayGetCount(allowedOmissions
)));
1402 CFRange range
= CFRangeMake(0, CFArrayGetCount(allowed
));
1404 // check all resource rules for weakness
1405 string catchAllRule
= (version
== 1) ? "^Resources/" : "^.*";
1406 __block
bool coversAll
= false;
1407 __block
bool forbiddenOmission
= false;
1408 CFArrayRef allowedRef
= allowed
.get(); // (into block)
1409 CFDictionary
rules(rulesDict
, errSecCSResourceRulesInvalid
);
1410 rules
.apply(^(CFStringRef key
, CFTypeRef value
) {
1411 string pattern
= cfString(key
, errSecCSResourceRulesInvalid
);
1412 if (pattern
== catchAllRule
&& value
== kCFBooleanTrue
) {
1416 if (isOmitRule(value
))
1417 forbiddenOmission
|= !CFArrayContainsValue(allowedRef
, range
, key
);
1420 return !coversAll
|| forbiddenOmission
;
1425 // Load, validate, cache, and return CFDictionary forms of sealed resources.
1427 CFDictionaryRef
SecStaticCode::infoDictionary()
1430 mInfoDict
.take(getDictionary(cdInfoSlot
, errSecCSInfoPlistFailed
));
1431 secinfo("staticCode", "%p loaded InfoDict %p", this, mInfoDict
.get());
1436 CFDictionaryRef
SecStaticCode::entitlements()
1438 if (!mEntitlements
) {
1439 validateDirectory();
1440 if (CFDataRef entitlementData
= component(cdEntitlementSlot
)) {
1441 validateComponent(cdEntitlementSlot
);
1442 const EntitlementBlob
*blob
= reinterpret_cast<const EntitlementBlob
*>(CFDataGetBytePtr(entitlementData
));
1443 if (blob
->validateBlob()) {
1444 mEntitlements
.take(blob
->entitlements());
1445 secinfo("staticCode", "%p loaded Entitlements %p", this, mEntitlements
.get());
1447 // we do not consider a different blob type to be an error. We think it's a new format we don't understand
1450 return mEntitlements
;
1453 CFDictionaryRef
SecStaticCode::resourceDictionary(bool check
/* = true */)
1455 if (mResourceDict
) // cached
1456 return mResourceDict
;
1457 if (CFRef
<CFDictionaryRef
> dict
= getDictionary(cdResourceDirSlot
, check
))
1458 if (cfscan(dict
, "{rules=%Dn,files=%Dn}")) {
1459 secinfo("staticCode", "%p loaded ResourceDict %p",
1460 this, mResourceDict
.get());
1461 return mResourceDict
= dict
;
1468 CFDataRef
SecStaticCode::copyComponent(CodeDirectory::SpecialSlot slot
, CFDataRef hash
)
1470 const CodeDirectory
* cd
= this->codeDirectory();
1471 if (CFCopyRef
<CFDataRef
> component
= this->component(slot
)) {
1473 const void *slotHash
= cd
->getSlot(slot
, false);
1474 if (cd
->hashSize
!= CFDataGetLength(hash
) || 0 != memcmp(slotHash
, CFDataGetBytePtr(hash
), cd
->hashSize
)) {
1475 Syslog::notice("copyComponent hash mismatch slot %d length %d", slot
, int(CFDataGetLength(hash
)));
1476 return NULL
; // mismatch
1479 return component
.yield();
1487 // Load and cache the resource directory base.
1488 // Note that the base is optional for each DiskRep.
1490 CFURLRef
SecStaticCode::resourceBase()
1492 if (!mGotResourceBase
) {
1493 string base
= mRep
->resourcesRootPath();
1495 mResourceBase
.take(makeCFURL(base
, true));
1496 mGotResourceBase
= true;
1498 return mResourceBase
;
1503 // Load a component, validate it, convert it to a CFDictionary, and return that.
1504 // This will force load and validation, which means that it will perform basic
1505 // validation if it hasn't been done yet.
1507 CFDictionaryRef
SecStaticCode::getDictionary(CodeDirectory::SpecialSlot slot
, bool check
/* = true */)
1510 validateDirectory();
1511 if (CFDataRef infoData
= component(slot
)) {
1512 validateComponent(slot
);
1513 if (CFDictionaryRef dict
= makeCFDictionaryFrom(infoData
))
1516 MacOSError::throwMe(errSecCSBadDictionaryFormat
);
1524 CFDictionaryRef
SecStaticCode::diskRepInformation()
1526 return mRep
->diskRepInformation();
1529 bool SecStaticCode::checkfix30814861(string path
, bool addition
) {
1530 // <rdar://problem/30814861> v2 resource rules don't match v1 resource rules
1532 //// Condition 1: Is the app an iOS app that was built with an SDK lower than 9.0?
1534 // We started signing correctly in 2014, 9.0 was first seeded mid-2016.
1536 CFRef
<CFDictionaryRef
> inf
= diskRepInformation();
1538 CFDictionary
info(diskRepInformation(), errSecCSNotSupported
);
1540 cfNumber(info
.get
<CFNumberRef
>(kSecCodeInfoDiskRepVersionPlatform
, errSecCSNotSupported
), 0);
1541 uint32_t sdkVersion
=
1542 cfNumber(info
.get
<CFNumberRef
>(kSecCodeInfoDiskRepVersionSDK
, errSecCSNotSupported
), 0);
1544 if (platform
!= PLATFORM_IOS
|| sdkVersion
>= 0x00090000) {
1547 } catch (const MacOSError
&error
) {
1551 //// Condition 2: Is it a .sinf/.supf/.supp file at the right location?
1553 static regex_t pathre_sinf
;
1554 static regex_t pathre_supp_supf
;
1555 static dispatch_once_t once
;
1557 dispatch_once(&once
, ^{
1558 os_assert_zero(regcomp(&pathre_sinf
,
1559 "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|())SC_Info/[^/]+\\.sinf$",
1560 REG_EXTENDED
| REG_NOSUB
));
1561 os_assert_zero(regcomp(&pathre_supp_supf
,
1562 "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|())SC_Info/[^/]+\\.(supf|supp)$",
1563 REG_EXTENDED
| REG_NOSUB
));
1566 // .sinf is added, .supf/.supp are modified.
1567 const regex_t
&pathre
= addition
? pathre_sinf
: pathre_supp_supf
;
1569 const int result
= regexec(&pathre
, path
.c_str(), 0, NULL
, 0);
1571 if (result
== REG_NOMATCH
) {
1573 } else if (result
!= 0) {
1575 secerror("unexpected regexec result %d for path '%s'", result
, path
.c_str());
1579 //// Condition 3: Do the v1 rules actually exclude the file?
1581 dispatch_once(&mCheckfix30814861builder1_once
, ^{
1582 // Create the v1 resource builder lazily.
1583 CFDictionaryRef rules1
= cfget
<CFDictionaryRef
>(resourceDictionary(), "rules");
1584 const string base
= cfString(resourceBase());
1586 mCheckfix30814861builder1
= new ResourceBuilder(base
, base
, rules1
, false, mTolerateErrors
);
1589 ResourceBuilder::Rule
const * const matchingRule
= mCheckfix30814861builder1
->findRule(path
);
1591 if (matchingRule
== NULL
|| !(matchingRule
->flags
& ResourceBuilder::omitted
)) {
1595 //// All matched, this file is a check-fixed sinf/supf/supp.
1601 void SecStaticCode::validateResource(CFDictionaryRef files
, string path
, bool isSymlink
, ValidationContext
&ctx
, SecCSFlags flags
, uint32_t version
)
1603 if (!resourceBase()) // no resources in DiskRep
1604 MacOSError::throwMe(errSecCSResourcesNotFound
);
1605 CFRef
<CFURLRef
> fullpath
= makeCFURL(path
, false, resourceBase());
1606 if (version
> 1 && ((flags
& (kSecCSStrictValidate
|kSecCSRestrictSidebandData
)) == (kSecCSStrictValidate
|kSecCSRestrictSidebandData
))) {
1607 AutoFileDesc
fd(cfString(fullpath
));
1608 if (fd
.hasExtendedAttribute(XATTR_RESOURCEFORK_NAME
) || fd
.hasExtendedAttribute(XATTR_FINDERINFO_NAME
))
1609 ctx
.reportProblem(errSecCSInvalidAssociatedFileData
, kSecCFErrorResourceSideband
, fullpath
);
1611 if (CFTypeRef file
= CFDictionaryGetValue(files
, CFTempString(path
))) {
1612 ResourceSeal
seal(file
);
1613 const ResourceSeal
& rseal
= seal
;
1614 if (seal
.nested()) {
1616 return ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
1617 string suffix
= ".framework";
1618 bool isFramework
= (path
.length() > suffix
.length())
1619 && (path
.compare(path
.length()-suffix
.length(), suffix
.length(), suffix
) == 0);
1620 validateNestedCode(fullpath
, seal
, flags
, isFramework
);
1621 } else if (seal
.link()) {
1623 return ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
1624 validateSymlinkResource(cfString(fullpath
), cfString(seal
.link()), ctx
, flags
);
1625 } else if (seal
.hash(hashAlgorithm())) { // genuine file
1627 return ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
1628 AutoFileDesc
fd(cfString(fullpath
), O_RDONLY
, FileDesc::modeMissingOk
); // open optional file
1630 __block
bool good
= true;
1631 CodeDirectory::multipleHashFileData(fd
, 0, hashAlgorithms(), ^(CodeDirectory::HashAlgorithm type
, Security::DynamicHash
*hasher
) {
1632 if (!hasher
->verify(rseal
.hash(type
)))
1636 if (version
== 2 && checkfix30814861(path
, false)) {
1637 secinfo("validateResource", "%s check-fixed (altered).", path
.c_str());
1639 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // altered
1643 if (!seal
.optional())
1644 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceMissing
, fullpath
); // was sealed but is now missing
1646 return; // validly missing
1649 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
1652 if (version
== 1) { // version 1 ignores symlinks altogether
1653 char target
[PATH_MAX
];
1654 if (::readlink(cfString(fullpath
).c_str(), target
, sizeof(target
)) > 0)
1657 if (version
== 2 && checkfix30814861(path
, true)) {
1658 secinfo("validateResource", "%s check-fixed (added).", path
.c_str());
1660 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAdded
, CFTempURL(path
, false, resourceBase()));
1664 void SecStaticCode::validatePlainMemoryResource(string path
, CFDataRef fileData
, SecCSFlags flags
)
1666 CFDictionaryRef rules
;
1667 CFDictionaryRef files
;
1669 if (!loadResources(rules
, files
, version
))
1670 MacOSError::throwMe(errSecCSResourcesNotFound
); // no resources sealed; this can't be right
1671 if (CFTypeRef file
= CFDictionaryGetValue(files
, CFTempString(path
))) {
1672 ResourceSeal
seal(file
);
1673 const Byte
*sealHash
= seal
.hash(hashAlgorithm());
1675 if (codeDirectory()->verifyMemoryContent(fileData
, sealHash
))
1679 MacOSError::throwMe(errSecCSBadResource
);
1682 void SecStaticCode::validateSymlinkResource(std::string fullpath
, std::string seal
, ValidationContext
&ctx
, SecCSFlags flags
)
1684 static const char* const allowedDestinations
[] = {
1689 char target
[PATH_MAX
];
1690 ssize_t len
= ::readlink(fullpath
.c_str(), target
, sizeof(target
)-1);
1692 UnixError::check(-1);
1694 std::string fulltarget
= target
;
1695 if (target
[0] != '/') {
1696 size_t lastSlash
= fullpath
.rfind('/');
1697 fulltarget
= fullpath
.substr(0, lastSlash
) + '/' + target
;
1699 if (seal
!= target
) {
1700 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, CFTempString(fullpath
));
1703 if ((mValidationFlags
& (kSecCSStrictValidate
|kSecCSRestrictSymlinks
)) == (kSecCSStrictValidate
|kSecCSRestrictSymlinks
)) {
1704 char resolved
[PATH_MAX
];
1705 if (realpath(fulltarget
.c_str(), resolved
)) {
1706 assert(resolved
[0] == '/');
1707 size_t rlen
= strlen(resolved
);
1708 if (target
[0] == '/') {
1709 // absolute symlink; only allow absolute links to system locations
1710 for (const char* const* pathp
= allowedDestinations
; *pathp
; pathp
++) {
1711 size_t dlen
= strlen(*pathp
);
1712 if (rlen
> dlen
&& strncmp(resolved
, *pathp
, dlen
) == 0)
1713 return; // target inside /System, deemed okay
1716 // everything else must be inside the bundle(s)
1717 for (const SecStaticCode
* code
= this; code
; code
= code
->mOuterScope
) {
1718 string root
= code
->mResourceScope
->root();
1719 if (strncmp(resolved
, root
.c_str(), root
.size()) == 0) {
1720 if (code
->mResourceScope
->includes(resolved
+ root
.length() + 1))
1721 return; // located in resource stack && included in envelope
1723 break; // located but excluded from envelope (deny)
1728 // if we fell through, flag a symlink error
1729 if (mTolerateErrors
.find(errSecCSInvalidSymlink
) == mTolerateErrors
.end())
1730 ctx
.reportProblem(errSecCSInvalidSymlink
, kSecCFErrorResourceAltered
, CFTempString(fullpath
));
1734 void SecStaticCode::validateNestedCode(CFURLRef path
, const ResourceSeal
&seal
, SecCSFlags flags
, bool isFramework
)
1736 CFRef
<SecRequirementRef
> req
;
1737 if (SecRequirementCreateWithString(seal
.requirement(), kSecCSDefaultFlags
, &req
.aref()))
1738 MacOSError::throwMe(errSecCSResourcesInvalid
);
1740 // recursively verify this nested code
1742 if (!(flags
& kSecCSCheckNestedCode
))
1743 flags
|= kSecCSBasicValidateOnly
| kSecCSQuickCheck
;
1744 SecPointer
<SecStaticCode
> code
= new SecStaticCode(DiskRep::bestGuess(cfString(path
)));
1745 code
->initializeFromParent(*this);
1746 code
->staticValidate(flags
& (~kSecCSRestrictToAppLike
), SecRequirement::required(req
));
1748 if (isFramework
&& (flags
& kSecCSStrictValidate
))
1750 validateOtherVersions(path
, flags
& (~kSecCSRestrictToAppLike
), req
, code
);
1751 } catch (const CSError
&err
) {
1752 MacOSError::throwMe(errSecCSBadFrameworkVersion
);
1753 } catch (const MacOSError
&err
) {
1754 MacOSError::throwMe(errSecCSBadFrameworkVersion
);
1757 } catch (CSError
&err
) {
1758 if (err
.error
== errSecCSReqFailed
) {
1759 mResourcesValidContext
->reportProblem(errSecCSBadNestedCode
, kSecCFErrorResourceAltered
, path
);
1762 err
.augment(kSecCFErrorPath
, path
);
1764 } catch (const MacOSError
&err
) {
1765 if (err
.error
== errSecCSReqFailed
) {
1766 mResourcesValidContext
->reportProblem(errSecCSBadNestedCode
, kSecCFErrorResourceAltered
, path
);
1769 CSError::throwMe(err
.error
, kSecCFErrorPath
, path
);
1773 void SecStaticCode::validateOtherVersions(CFURLRef path
, SecCSFlags flags
, SecRequirementRef req
, SecStaticCode
*code
)
1775 // Find out what current points to and do not revalidate
1776 std::string mainPath
= cfStringRelease(code
->diskRep()->copyCanonicalPath());
1778 char main_path
[PATH_MAX
];
1779 bool foundTarget
= false;
1781 /* If it failed to get the target of the symlink, do not fail. It is a performance loss,
1782 not a security hole */
1783 if (realpath(mainPath
.c_str(), main_path
) != NULL
)
1786 std::ostringstream versionsPath
;
1787 versionsPath
<< cfString(path
) << "/Versions/";
1789 DirScanner
scanner(versionsPath
.str());
1791 if (scanner
.initialized()) {
1792 struct dirent
*entry
= NULL
;
1793 while ((entry
= scanner
.getNext()) != NULL
) {
1794 std::ostringstream fullPath
;
1796 if (entry
->d_type
!= DT_DIR
|| strcmp(entry
->d_name
, "Current") == 0)
1799 fullPath
<< versionsPath
.str() << entry
->d_name
;
1801 char real_full_path
[PATH_MAX
];
1802 if (realpath(fullPath
.str().c_str(), real_full_path
) == NULL
)
1803 UnixError::check(-1);
1805 // Do case insensitive comparions because realpath() was called for both paths
1806 if (foundTarget
&& strcmp(main_path
, real_full_path
) == 0)
1809 SecPointer
<SecStaticCode
> frameworkVersion
= new SecStaticCode(DiskRep::bestGuess(real_full_path
));
1810 frameworkVersion
->initializeFromParent(*this);
1811 frameworkVersion
->staticValidate(flags
, SecRequirement::required(req
));
1818 // Test a CodeDirectory flag.
1819 // Returns false if there is no CodeDirectory.
1820 // May throw if the CodeDirectory is present but somehow invalid.
1822 bool SecStaticCode::flag(uint32_t tested
)
1824 if (const CodeDirectory
*cd
= this->codeDirectory(false))
1825 return cd
->flags
& tested
;
1832 // Retrieve the full SuperBlob containing all internal requirements.
1834 const Requirements
*SecStaticCode::internalRequirements()
1836 if (CFDataRef reqData
= component(cdRequirementsSlot
)) {
1837 const Requirements
*req
= (const Requirements
*)CFDataGetBytePtr(reqData
);
1838 if (!req
->validateBlob())
1839 MacOSError::throwMe(errSecCSReqInvalid
);
1847 // Retrieve a particular internal requirement by type.
1849 const Requirement
*SecStaticCode::internalRequirement(SecRequirementType type
)
1851 if (const Requirements
*reqs
= internalRequirements())
1852 return reqs
->find
<Requirement
>(type
);
1859 // Return the Designated Requirement (DR). This can be either explicit in the
1860 // Internal Requirements component, or implicitly generated on demand here.
1861 // Note that an explicit DR may have been implicitly generated at signing time;
1862 // we don't distinguish this case.
1864 const Requirement
*SecStaticCode::designatedRequirement()
1866 if (const Requirement
*req
= internalRequirement(kSecDesignatedRequirementType
)) {
1867 return req
; // explicit in signing data
1869 if (!mDesignatedReq
)
1870 mDesignatedReq
= defaultDesignatedRequirement();
1871 return mDesignatedReq
;
1877 // Generate the default Designated Requirement (DR) for this StaticCode.
1878 // Ignore any explicit DR it may contain.
1880 const Requirement
*SecStaticCode::defaultDesignatedRequirement()
1882 if (flag(kSecCodeSignatureAdhoc
)) {
1883 // adhoc signature: return a cdhash requirement for all architectures
1884 __block
Requirement::Maker maker
;
1885 Requirement::Maker::Chain
chain(maker
, opOr
);
1887 // insert cdhash requirement for all architectures
1888 __block CFRef
<CFMutableArrayRef
> allHashes
= CFArrayCreateMutableCopy(NULL
, 0, this->cdHashes());
1889 handleOtherArchitectures(^(SecStaticCode
*other
) {
1890 CFArrayRef hashes
= other
->cdHashes();
1891 CFArrayAppendArray(allHashes
, hashes
, CFRangeMake(0, CFArrayGetCount(hashes
)));
1893 CFIndex count
= CFArrayGetCount(allHashes
);
1894 for (CFIndex n
= 0; n
< count
; ++n
) {
1896 maker
.cdhash(CFDataRef(CFArrayGetValueAtIndex(allHashes
, n
)));
1898 return maker
.make();
1901 // full signature: Gin up full context and let DRMaker do its thing
1902 validateDirectory(); // need the cert chain
1903 CFRef
<CFDateRef
> secureTimestamp
;
1904 if (CFAbsoluteTime time
= this->signingTimestamp()) {
1905 secureTimestamp
.take(CFDateCreate(NULL
, time
));
1907 Requirement::Context
context(this->certificates(),
1908 this->infoDictionary(),
1909 this->entitlements(),
1911 this->codeDirectory(),
1913 kSecCodeSignatureNoHash
,
1918 return DRMaker(context
).make();
1920 MacOSError::throwMe(errSecCSUnimplemented
);
1927 // Validate a SecStaticCode against the internal requirement of a particular type.
1929 void SecStaticCode::validateRequirements(SecRequirementType type
, SecStaticCode
*target
,
1930 OSStatus nullError
/* = errSecSuccess */)
1932 DTRACK(CODESIGN_EVAL_STATIC_INTREQ
, this, type
, target
, nullError
);
1933 if (const Requirement
*req
= internalRequirement(type
))
1934 target
->validateRequirement(req
, nullError
? nullError
: errSecCSReqFailed
);
1936 MacOSError::throwMe(nullError
);
1942 // Validate this StaticCode against an external Requirement
1944 bool SecStaticCode::satisfiesRequirement(const Requirement
*req
, OSStatus failure
)
1946 bool result
= false;
1948 validateDirectory();
1949 CFRef
<CFDateRef
> secureTimestamp
;
1950 if (CFAbsoluteTime time
= this->signingTimestamp()) {
1951 secureTimestamp
.take(CFDateCreate(NULL
, time
));
1953 result
= req
->validates(Requirement::Context(mCertChain
, infoDictionary(), entitlements(),
1954 codeDirectory()->identifier(), codeDirectory(),
1955 NULL
, kSecCodeSignatureNoHash
, mRep
->appleInternalForcePlatform(),
1956 secureTimestamp
, teamID()),
1961 void SecStaticCode::validateRequirement(const Requirement
*req
, OSStatus failure
)
1963 if (!this->satisfiesRequirement(req
, failure
))
1964 MacOSError::throwMe(failure
);
1968 // Retrieve one certificate from the cert chain.
1969 // Positive and negative indices can be used:
1970 // [ leaf, intermed-1, ..., intermed-n, anchor ]
1972 // Returns NULL if unavailable for any reason.
1974 SecCertificateRef
SecStaticCode::cert(int ix
)
1976 validateDirectory(); // need cert chain
1978 CFIndex length
= CFArrayGetCount(mCertChain
);
1981 if (ix
>= 0 && ix
< length
)
1982 return SecCertificateRef(CFArrayGetValueAtIndex(mCertChain
, ix
));
1987 CFArrayRef
SecStaticCode::certificates()
1989 validateDirectory(); // need cert chain
1995 // Gather (mostly) API-official information about this StaticCode.
1997 // This method lives in the twilight between the API and internal layers,
1998 // since it generates API objects (Sec*Refs) for return.
2000 CFDictionaryRef
SecStaticCode::signingInformation(SecCSFlags flags
)
2003 // Start with the pieces that we return even for unsigned code.
2004 // This makes Sec[Static]CodeRefs useful as API-level replacements
2005 // of our internal OSXCode objects.
2007 CFRef
<CFMutableDictionaryRef
> dict
= makeCFMutableDictionary(1,
2008 kSecCodeInfoMainExecutable
, CFTempURL(this->mainExecutablePath()).get()
2012 // If we're not signed, this is all you get
2014 if (!this->isSigned())
2015 return dict
.yield();
2018 // Add the generic attributes that we always include
2020 CFDictionaryAddValue(dict
, kSecCodeInfoIdentifier
, CFTempString(this->identifier()));
2021 CFDictionaryAddValue(dict
, kSecCodeInfoFlags
, CFTempNumber(this->codeDirectory(false)->flags
.get()));
2022 CFDictionaryAddValue(dict
, kSecCodeInfoFormat
, CFTempString(this->format()));
2023 CFDictionaryAddValue(dict
, kSecCodeInfoSource
, CFTempString(this->signatureSource()));
2024 CFDictionaryAddValue(dict
, kSecCodeInfoUnique
, this->cdHash());
2025 CFDictionaryAddValue(dict
, kSecCodeInfoCdHashes
, this->cdHashes());
2026 CFDictionaryAddValue(dict
, kSecCodeInfoCdHashesFull
, this->cdHashesFull());
2027 const CodeDirectory
* cd
= this->codeDirectory(false);
2028 CFDictionaryAddValue(dict
, kSecCodeInfoDigestAlgorithm
, CFTempNumber(cd
->hashType
));
2029 CFRef
<CFArrayRef
> digests
= makeCFArrayFrom(^CFTypeRef(CodeDirectory::HashAlgorithm type
) { return CFTempNumber(type
); }, hashAlgorithms());
2030 CFDictionaryAddValue(dict
, kSecCodeInfoDigestAlgorithms
, digests
);
2032 CFDictionaryAddValue(dict
, kSecCodeInfoPlatformIdentifier
, CFTempNumber(cd
->platform
));
2033 if (cd
->runtimeVersion()) {
2034 CFDictionaryAddValue(dict
, kSecCodeInfoRuntimeVersion
, CFTempNumber(cd
->runtimeVersion()));
2038 // Deliver any Info.plist only if it looks intact
2041 if (CFDictionaryRef info
= this->infoDictionary())
2042 CFDictionaryAddValue(dict
, kSecCodeInfoPList
, info
);
2043 } catch (...) { } // don't deliver Info.plist if questionable
2046 // kSecCSSigningInformation adds information about signing certificates and chains
2048 if (flags
& kSecCSSigningInformation
)
2050 if (CFDataRef sig
= this->signature())
2051 CFDictionaryAddValue(dict
, kSecCodeInfoCMS
, sig
);
2052 if (const char *teamID
= this->teamID())
2053 CFDictionaryAddValue(dict
, kSecCodeInfoTeamIdentifier
, CFTempString(teamID
));
2055 CFDictionaryAddValue(dict
, kSecCodeInfoTrust
, mTrust
);
2056 if (CFArrayRef certs
= this->certificates())
2057 CFDictionaryAddValue(dict
, kSecCodeInfoCertificates
, certs
);
2058 if (CFAbsoluteTime time
= this->signingTime())
2059 if (CFRef
<CFDateRef
> date
= CFDateCreate(NULL
, time
))
2060 CFDictionaryAddValue(dict
, kSecCodeInfoTime
, date
);
2061 if (CFAbsoluteTime time
= this->signingTimestamp())
2062 if (CFRef
<CFDateRef
> date
= CFDateCreate(NULL
, time
))
2063 CFDictionaryAddValue(dict
, kSecCodeInfoTimestamp
, date
);
2067 // kSecCSRequirementInformation adds information on requirements
2069 if (flags
& kSecCSRequirementInformation
)
2071 //DR not currently supported on iOS
2074 if (const Requirements
*reqs
= this->internalRequirements()) {
2075 CFDictionaryAddValue(dict
, kSecCodeInfoRequirements
,
2076 CFTempString(Dumper::dump(reqs
)));
2077 CFDictionaryAddValue(dict
, kSecCodeInfoRequirementData
, CFTempData(*reqs
));
2080 const Requirement
*dreq
= this->designatedRequirement();
2081 CFRef
<SecRequirementRef
> dreqRef
= (new SecRequirement(dreq
))->handle();
2082 CFDictionaryAddValue(dict
, kSecCodeInfoDesignatedRequirement
, dreqRef
);
2083 if (this->internalRequirement(kSecDesignatedRequirementType
)) { // explicit
2084 CFRef
<SecRequirementRef
> ddreqRef
= (new SecRequirement(this->defaultDesignatedRequirement(), true))->handle();
2085 CFDictionaryAddValue(dict
, kSecCodeInfoImplicitDesignatedRequirement
, ddreqRef
);
2086 } else { // implicit
2087 CFDictionaryAddValue(dict
, kSecCodeInfoImplicitDesignatedRequirement
, dreqRef
);
2093 if (CFDataRef ent
= this->component(cdEntitlementSlot
)) {
2094 CFDictionaryAddValue(dict
, kSecCodeInfoEntitlements
, ent
);
2095 if (CFDictionaryRef entdict
= this->entitlements())
2096 CFDictionaryAddValue(dict
, kSecCodeInfoEntitlementsDict
, entdict
);
2101 // kSecCSInternalInformation adds internal information meant to be for Apple internal
2102 // use (SPI), and not guaranteed to be stable. Primarily, this is data we want
2103 // to reliably transmit through the API wall so that code outside the Security.framework
2104 // can use it without having to play nasty tricks to get it.
2106 if (flags
& kSecCSInternalInformation
) {
2109 CFDictionaryAddValue(dict
, kSecCodeInfoCodeDirectory
, mDir
);
2110 CFDictionaryAddValue(dict
, kSecCodeInfoCodeOffset
, CFTempNumber(mRep
->signingBase()));
2111 if (!(flags
& kSecCSSkipResourceDirectory
)) {
2112 if (CFRef
<CFDictionaryRef
> rdict
= getDictionary(cdResourceDirSlot
, false)) // suppress validation
2113 CFDictionaryAddValue(dict
, kSecCodeInfoResourceDirectory
, rdict
);
2115 if (CFRef
<CFDictionaryRef
> ddict
= diskRepInformation())
2116 CFDictionaryAddValue(dict
, kSecCodeInfoDiskRepInfo
, ddict
);
2118 if (mNotarizationChecked
&& !isnan(mNotarizationDate
)) {
2119 CFRef
<CFDateRef
> date
= CFDateCreate(NULL
, mNotarizationDate
);
2121 CFDictionaryAddValue(dict
, kSecCodeInfoNotarizationDate
, date
.get());
2123 secerror("Error creating date from timestamp: %f", mNotarizationDate
);
2128 if (flags
& kSecCSCalculateCMSDigest
) {
2130 CFDictionaryAddValue(dict
, kSecCodeInfoCMSDigestHashType
, CFTempNumber(cmsDigestHashType()));
2132 CFRef
<CFDataRef
> cmsDigest
= createCmsDigest();
2134 CFDictionaryAddValue(dict
, kSecCodeInfoCMSDigest
, cmsDigest
.get());
2140 // kSecCSContentInformation adds more information about the physical layout
2141 // of the signed code. This is (only) useful for packaging or patching-oriented
2144 if (flags
& kSecCSContentInformation
&& !(flags
& kSecCSSkipResourceDirectory
))
2145 if (CFRef
<CFArrayRef
> files
= mRep
->modifiedFiles())
2146 CFDictionaryAddValue(dict
, kSecCodeInfoChangedFiles
, files
);
2148 return dict
.yield();
2153 // Resource validation contexts.
2154 // The default context simply throws a CSError, rudely terminating the operation.
2156 SecStaticCode::ValidationContext::~ValidationContext()
2159 void SecStaticCode::ValidationContext::reportProblem(OSStatus rc
, CFStringRef type
, CFTypeRef value
)
2161 CSError::throwMe(rc
, type
, value
);
2164 void SecStaticCode::CollectingContext::reportProblem(OSStatus rc
, CFStringRef type
, CFTypeRef value
)
2166 StLock
<Mutex
> _(mLock
);
2167 if (mStatus
== errSecSuccess
)
2168 mStatus
= rc
; // record first failure for eventual error return
2171 mCollection
.take(makeCFMutableDictionary());
2172 CFMutableArrayRef element
= CFMutableArrayRef(CFDictionaryGetValue(mCollection
, type
));
2174 element
= makeCFMutableArray(0);
2177 CFDictionaryAddValue(mCollection
, type
, element
);
2180 CFArrayAppendValue(element
, value
);
2184 void SecStaticCode::CollectingContext::throwMe()
2186 assert(mStatus
!= errSecSuccess
);
2187 throw CSError(mStatus
, mCollection
.retain());
2192 // Master validation driver.
2193 // This is the static validation (only) driver for the API.
2195 // SecStaticCode exposes an a la carte menu of topical validators applying
2196 // to a given object. The static validation API pulls them together reliably,
2197 // but it also adds three matrix dimensions: architecture (for "fat" Mach-O binaries),
2198 // nested code, and multiple digests. This function will crawl a suitable cross-section of this
2199 // validation matrix based on which options it is given, creating temporary
2200 // SecStaticCode objects on the fly to complete the task.
2201 // (The point, of course, is to do as little duplicate work as possible.)
2203 void SecStaticCode::staticValidate(SecCSFlags flags
, const SecRequirement
*req
)
2205 setValidationFlags(flags
);
2208 if (!mStaplingChecked
) {
2209 mRep
->registerStapledTicket();
2210 mStaplingChecked
= true;
2213 if (mFlags
& kSecCSForceOnlineNotarizationCheck
) {
2214 if (!mNotarizationChecked
) {
2215 if (this->cdHash()) {
2216 bool is_revoked
= checkNotarizationServiceForRevocation(this->cdHash(), (SecCSDigestAlgorithm
)this->hashAlgorithm(), &mNotarizationDate
);
2218 MacOSError::throwMe(errSecCSRevokedNotarization
);
2221 mNotarizationChecked
= true;
2224 #endif // TARGET_OS_OSX
2226 // initialize progress/cancellation state
2227 if (flags
& kSecCSReportProgress
)
2228 prepareProgress(estimateResourceWorkload() + 2); // +1 head, +1 tail
2231 // core components: once per architecture (if any)
2232 this->staticValidateCore(flags
, req
);
2233 if (flags
& kSecCSCheckAllArchitectures
)
2234 handleOtherArchitectures(^(SecStaticCode
* subcode
) {
2235 if (flags
& kSecCSCheckGatekeeperArchitectures
) {
2236 Universal
*fat
= subcode
->diskRep()->mainExecutableImage();
2237 assert(fat
&& fat
->narrowed()); // handleOtherArchitectures gave us a focused architecture slice
2238 Architecture arch
= fat
->bestNativeArch(); // actually, the ONLY one
2239 if ((arch
.cpuType() & ~CPU_ARCH_MASK
) == CPU_TYPE_POWERPC
)
2240 return; // irrelevant to Gatekeeper
2242 subcode
->detachedSignature(this->mDetachedSig
); // carry over explicit (but not implicit) detached signature
2243 subcode
->staticValidateCore(flags
, req
);
2247 // allow monitor intervention in source validation phase
2248 reportEvent(CFSTR("prepared"), NULL
);
2250 // resources: once for all architectures
2251 if (!(flags
& kSecCSDoNotValidateResources
))
2252 this->validateResources(flags
);
2254 // perform strict validation if desired
2255 if (flags
& kSecCSStrictValidate
) {
2256 mRep
->strictValidate(codeDirectory(), mTolerateErrors
, mValidationFlags
);
2258 } else if (flags
& kSecCSStrictValidateStructure
) {
2259 mRep
->strictValidateStructure(codeDirectory(), mTolerateErrors
, mValidationFlags
);
2262 // allow monitor intervention
2263 if (CFRef
<CFTypeRef
> veto
= reportEvent(CFSTR("validated"), NULL
)) {
2264 if (CFGetTypeID(veto
) == CFNumberGetTypeID())
2265 MacOSError::throwMe(cfNumber
<OSStatus
>(veto
.as
<CFNumberRef
>()));
2267 MacOSError::throwMe(errSecCSBadCallbackValue
);
2271 void SecStaticCode::staticValidateCore(SecCSFlags flags
, const SecRequirement
*req
)
2274 this->validateNonResourceComponents(); // also validates the CodeDirectory
2275 this->validateTopDirectory();
2276 if (!(flags
& kSecCSDoNotValidateExecutable
))
2277 this->validateExecutable();
2279 this->validateRequirement(req
->requirement(), errSecCSReqFailed
);
2280 } catch (CSError
&err
) {
2281 if (Universal
*fat
= this->diskRep()->mainExecutableImage()) // Mach-O
2282 if (MachO
*mach
= fat
->architecture()) {
2283 err
.augment(kSecCFErrorArchitecture
, CFTempString(mach
->architecture().displayName()));
2287 } catch (const MacOSError
&err
) {
2288 // add architecture information if we can get it
2289 if (Universal
*fat
= this->diskRep()->mainExecutableImage())
2290 if (MachO
*mach
= fat
->architecture()) {
2291 CFTempString
arch(mach
->architecture().displayName());
2293 CSError::throwMe(err
.error
, kSecCFErrorArchitecture
, arch
);
2301 // A helper that generates SecStaticCode objects for all but the primary architecture
2302 // of a fat binary and calls a block on them.
2303 // If there's only one architecture (or this is an architecture-agnostic code),
2304 // nothing happens quickly.
2306 void SecStaticCode::handleOtherArchitectures(void (^handle
)(SecStaticCode
* other
))
2308 if (Universal
*fat
= this->diskRep()->mainExecutableImage()) {
2309 Universal::Architectures architectures
;
2310 fat
->architectures(architectures
);
2311 if (architectures
.size() > 1) {
2312 DiskRep::Context ctx
;
2313 off_t activeOffset
= fat
->archOffset();
2314 for (Universal::Architectures::const_iterator arch
= architectures
.begin(); arch
!= architectures
.end(); ++arch
) {
2316 ctx
.offset
= int_cast
<size_t, off_t
>(fat
->archOffset(*arch
));
2317 ctx
.size
= fat
->lengthOfSlice(int_cast
<off_t
,size_t>(ctx
.offset
));
2318 if (ctx
.offset
!= activeOffset
) { // inactive architecture; check it
2319 SecPointer
<SecStaticCode
> subcode
= new SecStaticCode(DiskRep::bestGuess(this->mainExecutablePath(), &ctx
));
2320 subcode
->detachedSignature(this->mDetachedSig
); // carry over explicit (but not implicit) detached signature
2321 if (this->teamID() == NULL
|| subcode
->teamID() == NULL
) {
2322 if (this->teamID() != subcode
->teamID())
2323 MacOSError::throwMe(errSecCSSignatureInvalid
);
2324 } else if (strcmp(this->teamID(), subcode
->teamID()) != 0)
2325 MacOSError::throwMe(errSecCSSignatureInvalid
);
2328 } catch(std::out_of_range e
) {
2329 // some of our int_casts fell over.
2330 MacOSError::throwMe(errSecCSBadObjectFormat
);
2338 // A method that takes a certificate chain (certs) and evaluates
2339 // if it is a Mac or IPhone developer cert, an app store distribution cert,
2340 // or a developer ID
2342 bool SecStaticCode::isAppleDeveloperCert(CFArrayRef certs
)
2344 static const std::string appleDeveloperRequirement
= "(" + std::string(WWDRRequirement
) + ") or (" + MACWWDRRequirement
+ ") or (" + developerID
+ ") or (" + distributionCertificate
+ ") or (" + iPhoneDistributionCert
+ ")";
2345 SecPointer
<SecRequirement
> req
= new SecRequirement(parseRequirement(appleDeveloperRequirement
), true);
2346 Requirement::Context
ctx(certs
, NULL
, NULL
, "", NULL
, NULL
, kSecCodeSignatureNoHash
, false, NULL
, "");
2348 return req
->requirement()->validates(ctx
);
2351 CFDataRef
SecStaticCode::createCmsDigest()
2354 * The CMS digest is a hash of the primary (first, most compatible) code directory,
2355 * but its hash algorithm is fixed and not related to the code directory's
2359 auto it
= codeDirectories()->begin();
2361 if (it
== codeDirectories()->end()) {
2365 CodeDirectory
const * const cd
= reinterpret_cast<CodeDirectory
const*>(CFDataGetBytePtr(it
->second
));
2367 RefPointer
<DynamicHash
> hash
= cd
->hashFor(mCMSDigestHashType
);
2368 CFMutableDataRef data
= CFDataCreateMutable(NULL
, hash
->digestLength());
2369 CFDataSetLength(data
, hash
->digestLength());
2370 hash
->update(cd
, cd
->length());
2371 hash
->finish(CFDataGetMutableBytePtr(data
));
2376 } // end namespace CodeSigning
2377 } // end namespace Security