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
);
1231 // Perform static validation of sealed resources and nested code.
1233 // This performs a whole-code static resource scan and effectively
1234 // computes a concordance between what's on disk and what's in the ResourceDirectory.
1235 // Any unsanctioned difference causes an error.
1237 unsigned SecStaticCode::estimateResourceWorkload()
1239 // workload estimate = number of sealed files
1240 CFDictionaryRef sealedResources
= resourceDictionary();
1241 CFDictionaryRef files
= cfget
<CFDictionaryRef
>(sealedResources
, "files2");
1243 files
= cfget
<CFDictionaryRef
>(sealedResources
, "files");
1244 return files
? unsigned(CFDictionaryGetCount(files
)) : 0;
1247 void SecStaticCode::validateResources(SecCSFlags flags
)
1249 // do we have a superset of this requested validation cached?
1251 if (mResourcesValidated
) { // have cached outcome
1252 if (!(flags
& kSecCSCheckNestedCode
) || mResourcesDeep
) // was deep or need no deep scan
1257 string root
= cfStringRelease(copyCanonicalPath());
1258 bool itemIsOnRootFS
= isOnRootFilesystem(root
.c_str());
1259 bool skipRootVolumeExceptions
= (mValidationFlags
& kSecCSSkipRootVolumeExceptions
);
1260 bool useRootFSPolicy
= itemIsOnRootFS
&& !skipRootVolumeExceptions
;
1262 bool itemMightUseXattrFiles
= pathFileSystemUsesXattrFiles(root
.c_str());
1263 bool skipXattrFiles
= itemMightUseXattrFiles
&& (mValidationFlags
& kSecCSSkipXattrFiles
);
1265 secinfo("staticCode", "performing resource validation for %s (%d, %d, %d, %d, %d)", root
.c_str(),
1266 itemIsOnRootFS
, skipRootVolumeExceptions
, useRootFSPolicy
, itemMightUseXattrFiles
, skipXattrFiles
);
1268 if (mLimitedAsync
== NULL
) {
1269 bool runMultiThreaded
= ((flags
& kSecCSSingleThreaded
) == kSecCSSingleThreaded
) ? false :
1270 (diskRep()->fd().mediumType() == kIOPropertyMediumTypeSolidStateKey
);
1271 mLimitedAsync
= new LimitedAsync(runMultiThreaded
);
1275 CFDictionaryRef rules
;
1276 CFDictionaryRef files
;
1278 if (!loadResources(rules
, files
, version
))
1279 return; // validly no resources; nothing to do (ok)
1281 // found resources, and they are sealed
1282 DTRACK(CODESIGN_EVAL_STATIC_RESOURCES
, this,
1283 (char*)this->mainExecutablePath().c_str(), 0);
1285 // scan through the resources on disk, checking each against the resourceDirectory
1286 mResourcesValidContext
= new CollectingContext(*this); // collect all failures in here
1288 // check for weak resource rules
1289 bool strict
= flags
& kSecCSStrictValidate
;
1290 if (!useRootFSPolicy
) {
1292 if (hasWeakResourceRules(rules
, version
, mAllowOmissions
))
1293 if (mTolerateErrors
.find(errSecCSWeakResourceRules
) == mTolerateErrors
.end())
1294 MacOSError::throwMe(errSecCSWeakResourceRules
);
1296 if (mTolerateErrors
.find(errSecCSWeakResourceEnvelope
) == mTolerateErrors
.end())
1297 MacOSError::throwMe(errSecCSWeakResourceEnvelope
);
1301 Dispatch::Group group
;
1302 Dispatch::Group
&groupRef
= group
; // (into block)
1304 // scan through the resources on disk, checking each against the resourceDirectory
1305 __block CFRef
<CFMutableDictionaryRef
> resourceMap
= makeCFMutableDictionary(files
);
1306 string base
= cfString(this->resourceBase());
1307 ResourceBuilder
resources(base
, base
, rules
, strict
, mTolerateErrors
);
1308 this->mResourceScope
= &resources
;
1309 diskRep()->adjustResources(resources
);
1311 resources
.scan(^(FTSENT
*ent
, uint32_t ruleFlags
, const string relpath
, ResourceBuilder::Rule
*rule
) {
1312 CFDictionaryRemoveValue(resourceMap
, CFTempString(relpath
));
1313 bool isSymlink
= (ent
->fts_info
== FTS_SL
);
1315 void (^validate
)() = ^{
1316 bool needsValidation
= true;
1318 if (skipXattrFiles
&& pathIsValidXattrFile(cfString(resourceBase()) + "/" + relpath
, "staticCode")) {
1319 secinfo("staticCode", "resource validation on xattr file skipped: %s", relpath
.c_str());
1320 needsValidation
= false;
1323 if (useRootFSPolicy
) {
1324 CFRef
<CFURLRef
> itemURL
= makeCFURL(relpath
, false, resourceBase());
1325 string itemPath
= cfString(itemURL
);
1326 if (isOnRootFilesystem(itemPath
.c_str())) {
1327 secinfo("staticCode", "resource validation on root volume skipped: %s", itemPath
.c_str());
1328 needsValidation
= false;
1332 if (needsValidation
) {
1333 secinfo("staticCode", "performing resource validation on item: %s", relpath
.c_str());
1334 validateResource(files
, relpath
, isSymlink
, *mResourcesValidContext
, flags
, version
);
1339 mLimitedAsync
->perform(groupRef
, validate
);
1341 group
.wait(); // wait until all async resources have been validated as well
1343 if (useRootFSPolicy
) {
1344 // It's ok to allow leftovers on the root filesystem for now.
1346 // Look through the leftovers and make sure they're all properly optional resources.
1347 unsigned leftovers
= unsigned(CFDictionaryGetCount(resourceMap
));
1348 if (leftovers
> 0) {
1349 secinfo("staticCode", "%d sealed resource(s) not found in code", int(leftovers
));
1350 CFDictionaryApplyFunction(resourceMap
, SecStaticCode::checkOptionalResource
, mResourcesValidContext
);
1354 // now check for any errors found in the reporting context
1355 mResourcesValidated
= true;
1356 mResourcesDeep
= flags
& kSecCSCheckNestedCode
;
1357 if (mResourcesValidContext
->osStatus() != errSecSuccess
)
1358 mResourcesValidContext
->throwMe();
1359 } catch (const CommonError
&err
) {
1360 mResourcesValidated
= true;
1361 mResourcesDeep
= flags
& kSecCSCheckNestedCode
;
1362 mResourcesValidResult
= err
.osStatus();
1365 secinfo("staticCode", "%p executable validation threw non-common exception", this);
1366 mResourcesValidated
= true;
1367 mResourcesDeep
= flags
& kSecCSCheckNestedCode
;
1368 mResourcesValidResult
= errSecCSInternalError
;
1369 Syslog::notice("code signing internal problem: unknown exception thrown by validation");
1373 assert(validatedResources());
1374 if (mResourcesValidResult
)
1375 MacOSError::throwMe(mResourcesValidResult
);
1376 if (mResourcesValidContext
->osStatus() != errSecSuccess
)
1377 mResourcesValidContext
->throwMe();
1381 bool SecStaticCode::loadResources(CFDictionaryRef
& rules
, CFDictionaryRef
& files
, uint32_t& version
)
1384 CFDictionaryRef sealedResources
= resourceDictionary();
1385 if (this->resourceBase()) { // disk has resources
1386 if (sealedResources
)
1387 /* go to work below */;
1389 MacOSError::throwMe(errSecCSResourcesNotFound
);
1390 } else { // disk has no resources
1391 if (sealedResources
)
1392 MacOSError::throwMe(errSecCSResourcesNotFound
);
1394 return false; // no resources, not sealed - fine (no work)
1397 // use V2 resource seal if available, otherwise fall back to V1
1398 if (CFDictionaryGetValue(sealedResources
, CFSTR("files2"))) { // have V2 signature
1399 rules
= cfget
<CFDictionaryRef
>(sealedResources
, "rules2");
1400 files
= cfget
<CFDictionaryRef
>(sealedResources
, "files2");
1402 } else { // only V1 available
1403 rules
= cfget
<CFDictionaryRef
>(sealedResources
, "rules");
1404 files
= cfget
<CFDictionaryRef
>(sealedResources
, "files");
1407 if (!rules
|| !files
)
1408 MacOSError::throwMe(errSecCSResourcesInvalid
);
1413 void SecStaticCode::checkOptionalResource(CFTypeRef key
, CFTypeRef value
, void *context
)
1415 ValidationContext
*ctx
= static_cast<ValidationContext
*>(context
);
1416 ResourceSeal
seal(value
);
1417 if (!seal
.optional()) {
1418 if (key
&& CFGetTypeID(key
) == CFStringGetTypeID()) {
1419 CFTempURL
tempURL(CFStringRef(key
), false, ctx
->code
.resourceBase());
1420 if (!tempURL
.get()) {
1421 ctx
->reportProblem(errSecCSBadDictionaryFormat
, kSecCFErrorResourceSeal
, key
);
1423 ctx
->reportProblem(errSecCSBadResource
, kSecCFErrorResourceMissing
, tempURL
);
1426 ctx
->reportProblem(errSecCSBadResource
, kSecCFErrorResourceSeal
, key
);
1432 static bool isOmitRule(CFTypeRef value
)
1434 if (CFGetTypeID(value
) == CFBooleanGetTypeID())
1435 return value
== kCFBooleanFalse
;
1436 CFDictionary
rule(value
, errSecCSResourceRulesInvalid
);
1437 return rule
.get
<CFBooleanRef
>("omit") == kCFBooleanTrue
;
1440 bool SecStaticCode::hasWeakResourceRules(CFDictionaryRef rulesDict
, uint32_t version
, CFArrayRef allowedOmissions
)
1442 // compute allowed omissions
1443 CFRef
<CFArrayRef
> defaultOmissions
= this->diskRep()->allowedResourceOmissions();
1444 if (!defaultOmissions
) {
1445 Syslog::notice("code signing internal problem: diskRep returned no allowedResourceOmissions");
1446 MacOSError::throwMe(errSecCSInternalError
);
1448 CFRef
<CFMutableArrayRef
> allowed
= CFArrayCreateMutableCopy(NULL
, 0, defaultOmissions
);
1449 if (allowedOmissions
)
1450 CFArrayAppendArray(allowed
, allowedOmissions
, CFRangeMake(0, CFArrayGetCount(allowedOmissions
)));
1451 CFRange range
= CFRangeMake(0, CFArrayGetCount(allowed
));
1453 // check all resource rules for weakness
1454 string catchAllRule
= (version
== 1) ? "^Resources/" : "^.*";
1455 __block
bool coversAll
= false;
1456 __block
bool forbiddenOmission
= false;
1457 CFArrayRef allowedRef
= allowed
.get(); // (into block)
1458 CFDictionary
rules(rulesDict
, errSecCSResourceRulesInvalid
);
1459 rules
.apply(^(CFStringRef key
, CFTypeRef value
) {
1460 string pattern
= cfString(key
, errSecCSResourceRulesInvalid
);
1461 if (pattern
== catchAllRule
&& value
== kCFBooleanTrue
) {
1465 if (isOmitRule(value
))
1466 forbiddenOmission
|= !CFArrayContainsValue(allowedRef
, range
, key
);
1469 return !coversAll
|| forbiddenOmission
;
1474 // Load, validate, cache, and return CFDictionary forms of sealed resources.
1476 CFDictionaryRef
SecStaticCode::infoDictionary()
1479 mInfoDict
.take(getDictionary(cdInfoSlot
, errSecCSInfoPlistFailed
));
1480 secinfo("staticCode", "%p loaded InfoDict %p", this, mInfoDict
.get());
1485 CFDictionaryRef
SecStaticCode::entitlements()
1487 if (!mEntitlements
) {
1488 validateDirectory();
1489 if (CFDataRef entitlementData
= component(cdEntitlementSlot
)) {
1490 validateComponent(cdEntitlementSlot
);
1491 const EntitlementBlob
*blob
= reinterpret_cast<const EntitlementBlob
*>(CFDataGetBytePtr(entitlementData
));
1492 if (blob
->validateBlob()) {
1493 mEntitlements
.take(blob
->entitlements());
1494 secinfo("staticCode", "%p loaded Entitlements %p", this, mEntitlements
.get());
1496 // we do not consider a different blob type to be an error. We think it's a new format we don't understand
1499 return mEntitlements
;
1502 CFDictionaryRef
SecStaticCode::resourceDictionary(bool check
/* = true */)
1504 if (mResourceDict
) // cached
1505 return mResourceDict
;
1506 if (CFRef
<CFDictionaryRef
> dict
= getDictionary(cdResourceDirSlot
, check
))
1507 if (cfscan(dict
, "{rules=%Dn,files=%Dn}")) {
1508 secinfo("staticCode", "%p loaded ResourceDict %p",
1509 this, mResourceDict
.get());
1510 return mResourceDict
= dict
;
1517 CFDataRef
SecStaticCode::copyComponent(CodeDirectory::SpecialSlot slot
, CFDataRef hash
)
1519 const CodeDirectory
* cd
= this->codeDirectory();
1520 if (CFCopyRef
<CFDataRef
> component
= this->component(slot
)) {
1522 const void *slotHash
= cd
->getSlot(slot
, false);
1523 if (cd
->hashSize
!= CFDataGetLength(hash
) || 0 != memcmp(slotHash
, CFDataGetBytePtr(hash
), cd
->hashSize
)) {
1524 Syslog::notice("copyComponent hash mismatch slot %d length %d", slot
, int(CFDataGetLength(hash
)));
1525 return NULL
; // mismatch
1528 return component
.yield();
1536 // Load and cache the resource directory base.
1537 // Note that the base is optional for each DiskRep.
1539 CFURLRef
SecStaticCode::resourceBase()
1541 if (!mGotResourceBase
) {
1542 string base
= mRep
->resourcesRootPath();
1544 mResourceBase
.take(makeCFURL(base
, true));
1545 mGotResourceBase
= true;
1547 return mResourceBase
;
1552 // Load a component, validate it, convert it to a CFDictionary, and return that.
1553 // This will force load and validation, which means that it will perform basic
1554 // validation if it hasn't been done yet.
1556 CFDictionaryRef
SecStaticCode::getDictionary(CodeDirectory::SpecialSlot slot
, bool check
/* = true */)
1559 validateDirectory();
1560 if (CFDataRef infoData
= component(slot
)) {
1561 validateComponent(slot
);
1562 if (CFDictionaryRef dict
= makeCFDictionaryFrom(infoData
))
1565 MacOSError::throwMe(errSecCSBadDictionaryFormat
);
1573 CFDictionaryRef
SecStaticCode::diskRepInformation()
1575 return mRep
->diskRepInformation();
1578 bool SecStaticCode::checkfix30814861(string path
, bool addition
) {
1579 // <rdar://problem/30814861> v2 resource rules don't match v1 resource rules
1581 //// Condition 1: Is the app an iOS app that was built with an SDK lower than 9.0?
1583 // We started signing correctly in 2014, 9.0 was first seeded mid-2016.
1585 CFRef
<CFDictionaryRef
> inf
= diskRepInformation();
1587 CFDictionary
info(diskRepInformation(), errSecCSNotSupported
);
1589 cfNumber(info
.get
<CFNumberRef
>(kSecCodeInfoDiskRepVersionPlatform
, errSecCSNotSupported
), 0);
1590 uint32_t sdkVersion
=
1591 cfNumber(info
.get
<CFNumberRef
>(kSecCodeInfoDiskRepVersionSDK
, errSecCSNotSupported
), 0);
1593 if (platform
!= PLATFORM_IOS
|| sdkVersion
>= 0x00090000) {
1596 } catch (const MacOSError
&error
) {
1600 //// Condition 2: Is it a .sinf/.supf/.supp file at the right location?
1602 static regex_t pathre_sinf
;
1603 static regex_t pathre_supp_supf
;
1604 static dispatch_once_t once
;
1606 dispatch_once(&once
, ^{
1607 os_assert_zero(regcomp(&pathre_sinf
,
1608 "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|())SC_Info/[^/]+\\.sinf$",
1609 REG_EXTENDED
| REG_NOSUB
));
1610 os_assert_zero(regcomp(&pathre_supp_supf
,
1611 "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|())SC_Info/[^/]+\\.(supf|supp)$",
1612 REG_EXTENDED
| REG_NOSUB
));
1615 // .sinf is added, .supf/.supp are modified.
1616 const regex_t
&pathre
= addition
? pathre_sinf
: pathre_supp_supf
;
1618 const int result
= regexec(&pathre
, path
.c_str(), 0, NULL
, 0);
1620 if (result
== REG_NOMATCH
) {
1622 } else if (result
!= 0) {
1624 secerror("unexpected regexec result %d for path '%s'", result
, path
.c_str());
1628 //// Condition 3: Do the v1 rules actually exclude the file?
1630 dispatch_once(&mCheckfix30814861builder1_once
, ^{
1631 // Create the v1 resource builder lazily.
1632 CFDictionaryRef rules1
= cfget
<CFDictionaryRef
>(resourceDictionary(), "rules");
1633 const string base
= cfString(resourceBase());
1635 mCheckfix30814861builder1
= new ResourceBuilder(base
, base
, rules1
, false, mTolerateErrors
);
1638 ResourceBuilder::Rule
const * const matchingRule
= mCheckfix30814861builder1
->findRule(path
);
1640 if (matchingRule
== NULL
|| !(matchingRule
->flags
& ResourceBuilder::omitted
)) {
1644 //// All matched, this file is a check-fixed sinf/supf/supp.
1650 void SecStaticCode::validateResource(CFDictionaryRef files
, string path
, bool isSymlink
, ValidationContext
&ctx
, SecCSFlags flags
, uint32_t version
)
1652 if (!resourceBase()) // no resources in DiskRep
1653 MacOSError::throwMe(errSecCSResourcesNotFound
);
1654 CFRef
<CFURLRef
> fullpath
= makeCFURL(path
, false, resourceBase());
1655 if (version
> 1 && ((flags
& (kSecCSStrictValidate
|kSecCSRestrictSidebandData
)) == (kSecCSStrictValidate
|kSecCSRestrictSidebandData
))) {
1656 AutoFileDesc
fd(cfString(fullpath
));
1657 if (fd
.hasExtendedAttribute(XATTR_RESOURCEFORK_NAME
) || fd
.hasExtendedAttribute(XATTR_FINDERINFO_NAME
))
1658 ctx
.reportProblem(errSecCSInvalidAssociatedFileData
, kSecCFErrorResourceSideband
, fullpath
);
1660 if (CFTypeRef file
= CFDictionaryGetValue(files
, CFTempString(path
))) {
1661 ResourceSeal
seal(file
);
1662 const ResourceSeal
& rseal
= seal
;
1663 if (seal
.nested()) {
1665 return ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
1666 string suffix
= ".framework";
1667 bool isFramework
= (path
.length() > suffix
.length())
1668 && (path
.compare(path
.length()-suffix
.length(), suffix
.length(), suffix
) == 0);
1669 validateNestedCode(fullpath
, seal
, flags
, isFramework
);
1670 } else if (seal
.link()) {
1672 return ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
1673 validateSymlinkResource(cfString(fullpath
), cfString(seal
.link()), ctx
, flags
);
1674 } else if (seal
.hash(hashAlgorithm())) { // genuine file
1676 return ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
1677 AutoFileDesc
fd(cfString(fullpath
), O_RDONLY
, FileDesc::modeMissingOk
); // open optional file
1679 __block
bool good
= true;
1680 CodeDirectory::multipleHashFileData(fd
, 0, hashAlgorithms(), ^(CodeDirectory::HashAlgorithm type
, Security::DynamicHash
*hasher
) {
1681 if (!hasher
->verify(rseal
.hash(type
)))
1685 if (version
== 2 && checkfix30814861(path
, false)) {
1686 secinfo("validateResource", "%s check-fixed (altered).", path
.c_str());
1688 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // altered
1692 if (!seal
.optional())
1693 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceMissing
, fullpath
); // was sealed but is now missing
1695 return; // validly missing
1698 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
1701 if (version
== 1) { // version 1 ignores symlinks altogether
1702 char target
[PATH_MAX
];
1703 if (::readlink(cfString(fullpath
).c_str(), target
, sizeof(target
)) > 0)
1706 if (version
== 2 && checkfix30814861(path
, true)) {
1707 secinfo("validateResource", "%s check-fixed (added).", path
.c_str());
1709 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAdded
, CFTempURL(path
, false, resourceBase()));
1713 void SecStaticCode::validatePlainMemoryResource(string path
, CFDataRef fileData
, SecCSFlags flags
)
1715 CFDictionaryRef rules
;
1716 CFDictionaryRef files
;
1718 if (!loadResources(rules
, files
, version
))
1719 MacOSError::throwMe(errSecCSResourcesNotFound
); // no resources sealed; this can't be right
1720 if (CFTypeRef file
= CFDictionaryGetValue(files
, CFTempString(path
))) {
1721 ResourceSeal
seal(file
);
1722 const Byte
*sealHash
= seal
.hash(hashAlgorithm());
1724 if (codeDirectory()->verifyMemoryContent(fileData
, sealHash
))
1728 MacOSError::throwMe(errSecCSBadResource
);
1731 void SecStaticCode::validateSymlinkResource(std::string fullpath
, std::string seal
, ValidationContext
&ctx
, SecCSFlags flags
)
1733 static const char* const allowedDestinations
[] = {
1738 char target
[PATH_MAX
];
1739 ssize_t len
= ::readlink(fullpath
.c_str(), target
, sizeof(target
)-1);
1741 UnixError::check(-1);
1743 std::string fulltarget
= target
;
1744 if (target
[0] != '/') {
1745 size_t lastSlash
= fullpath
.rfind('/');
1746 fulltarget
= fullpath
.substr(0, lastSlash
) + '/' + target
;
1748 if (seal
!= target
) {
1749 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, CFTempString(fullpath
));
1752 if ((mValidationFlags
& (kSecCSStrictValidate
|kSecCSRestrictSymlinks
)) == (kSecCSStrictValidate
|kSecCSRestrictSymlinks
)) {
1753 char resolved
[PATH_MAX
];
1754 if (realpath(fulltarget
.c_str(), resolved
)) {
1755 assert(resolved
[0] == '/');
1756 size_t rlen
= strlen(resolved
);
1757 if (target
[0] == '/') {
1758 // absolute symlink; only allow absolute links to system locations
1759 for (const char* const* pathp
= allowedDestinations
; *pathp
; pathp
++) {
1760 size_t dlen
= strlen(*pathp
);
1761 if (rlen
> dlen
&& strncmp(resolved
, *pathp
, dlen
) == 0)
1762 return; // target inside /System, deemed okay
1765 // everything else must be inside the bundle(s)
1766 for (const SecStaticCode
* code
= this; code
; code
= code
->mOuterScope
) {
1767 string root
= code
->mResourceScope
->root();
1768 if (strncmp(resolved
, root
.c_str(), root
.size()) == 0) {
1769 if (code
->mResourceScope
->includes(resolved
+ root
.length() + 1))
1770 return; // located in resource stack && included in envelope
1772 break; // located but excluded from envelope (deny)
1777 // if we fell through, flag a symlink error
1778 if (mTolerateErrors
.find(errSecCSInvalidSymlink
) == mTolerateErrors
.end())
1779 ctx
.reportProblem(errSecCSInvalidSymlink
, kSecCFErrorResourceAltered
, CFTempString(fullpath
));
1783 void SecStaticCode::validateNestedCode(CFURLRef path
, const ResourceSeal
&seal
, SecCSFlags flags
, bool isFramework
)
1785 CFRef
<SecRequirementRef
> req
;
1786 if (SecRequirementCreateWithString(seal
.requirement(), kSecCSDefaultFlags
, &req
.aref()))
1787 MacOSError::throwMe(errSecCSResourcesInvalid
);
1789 // recursively verify this nested code
1791 if (!(flags
& kSecCSCheckNestedCode
))
1792 flags
|= kSecCSBasicValidateOnly
| kSecCSQuickCheck
;
1793 SecPointer
<SecStaticCode
> code
= new SecStaticCode(DiskRep::bestGuess(cfString(path
)));
1794 code
->initializeFromParent(*this);
1795 code
->staticValidate(flags
& (~kSecCSRestrictToAppLike
), SecRequirement::required(req
));
1797 if (isFramework
&& (flags
& kSecCSStrictValidate
))
1799 validateOtherVersions(path
, flags
& (~kSecCSRestrictToAppLike
), req
, code
);
1800 } catch (const CSError
&err
) {
1801 MacOSError::throwMe(errSecCSBadFrameworkVersion
);
1802 } catch (const MacOSError
&err
) {
1803 MacOSError::throwMe(errSecCSBadFrameworkVersion
);
1806 } catch (CSError
&err
) {
1807 if (err
.error
== errSecCSReqFailed
) {
1808 mResourcesValidContext
->reportProblem(errSecCSBadNestedCode
, kSecCFErrorResourceAltered
, path
);
1811 err
.augment(kSecCFErrorPath
, path
);
1813 } catch (const MacOSError
&err
) {
1814 if (err
.error
== errSecCSReqFailed
) {
1815 mResourcesValidContext
->reportProblem(errSecCSBadNestedCode
, kSecCFErrorResourceAltered
, path
);
1818 CSError::throwMe(err
.error
, kSecCFErrorPath
, path
);
1822 void SecStaticCode::validateOtherVersions(CFURLRef path
, SecCSFlags flags
, SecRequirementRef req
, SecStaticCode
*code
)
1824 // Find out what current points to and do not revalidate
1825 std::string mainPath
= cfStringRelease(code
->diskRep()->copyCanonicalPath());
1827 char main_path
[PATH_MAX
];
1828 bool foundTarget
= false;
1830 /* If it failed to get the target of the symlink, do not fail. It is a performance loss,
1831 not a security hole */
1832 if (realpath(mainPath
.c_str(), main_path
) != NULL
)
1835 std::ostringstream versionsPath
;
1836 versionsPath
<< cfString(path
) << "/Versions/";
1838 DirScanner
scanner(versionsPath
.str());
1840 if (scanner
.initialized()) {
1841 struct dirent
*entry
= NULL
;
1842 while ((entry
= scanner
.getNext()) != NULL
) {
1843 std::ostringstream fullPath
;
1845 if (entry
->d_type
!= DT_DIR
|| strcmp(entry
->d_name
, "Current") == 0)
1848 fullPath
<< versionsPath
.str() << entry
->d_name
;
1850 char real_full_path
[PATH_MAX
];
1851 if (realpath(fullPath
.str().c_str(), real_full_path
) == NULL
)
1852 UnixError::check(-1);
1854 // Do case insensitive comparions because realpath() was called for both paths
1855 if (foundTarget
&& strcmp(main_path
, real_full_path
) == 0)
1858 SecPointer
<SecStaticCode
> frameworkVersion
= new SecStaticCode(DiskRep::bestGuess(real_full_path
));
1859 frameworkVersion
->initializeFromParent(*this);
1860 frameworkVersion
->staticValidate(flags
, SecRequirement::required(req
));
1867 // Test a CodeDirectory flag.
1868 // Returns false if there is no CodeDirectory.
1869 // May throw if the CodeDirectory is present but somehow invalid.
1871 bool SecStaticCode::flag(uint32_t tested
)
1873 if (const CodeDirectory
*cd
= this->codeDirectory(false))
1874 return cd
->flags
& tested
;
1881 // Retrieve the full SuperBlob containing all internal requirements.
1883 const Requirements
*SecStaticCode::internalRequirements()
1885 if (CFDataRef reqData
= component(cdRequirementsSlot
)) {
1886 const Requirements
*req
= (const Requirements
*)CFDataGetBytePtr(reqData
);
1887 if (!req
->validateBlob())
1888 MacOSError::throwMe(errSecCSReqInvalid
);
1896 // Retrieve a particular internal requirement by type.
1898 const Requirement
*SecStaticCode::internalRequirement(SecRequirementType type
)
1900 if (const Requirements
*reqs
= internalRequirements())
1901 return reqs
->find
<Requirement
>(type
);
1908 // Return the Designated Requirement (DR). This can be either explicit in the
1909 // Internal Requirements component, or implicitly generated on demand here.
1910 // Note that an explicit DR may have been implicitly generated at signing time;
1911 // we don't distinguish this case.
1913 const Requirement
*SecStaticCode::designatedRequirement()
1915 if (const Requirement
*req
= internalRequirement(kSecDesignatedRequirementType
)) {
1916 return req
; // explicit in signing data
1918 if (!mDesignatedReq
)
1919 mDesignatedReq
= defaultDesignatedRequirement();
1920 return mDesignatedReq
;
1926 // Generate the default Designated Requirement (DR) for this StaticCode.
1927 // Ignore any explicit DR it may contain.
1929 const Requirement
*SecStaticCode::defaultDesignatedRequirement()
1931 if (flag(kSecCodeSignatureAdhoc
)) {
1932 // adhoc signature: return a cdhash requirement for all architectures
1933 __block
Requirement::Maker maker
;
1934 Requirement::Maker::Chain
chain(maker
, opOr
);
1936 // insert cdhash requirement for all architectures
1937 __block CFRef
<CFMutableArrayRef
> allHashes
= CFArrayCreateMutableCopy(NULL
, 0, this->cdHashes());
1938 handleOtherArchitectures(^(SecStaticCode
*other
) {
1939 CFArrayRef hashes
= other
->cdHashes();
1940 CFArrayAppendArray(allHashes
, hashes
, CFRangeMake(0, CFArrayGetCount(hashes
)));
1942 CFIndex count
= CFArrayGetCount(allHashes
);
1943 for (CFIndex n
= 0; n
< count
; ++n
) {
1945 maker
.cdhash(CFDataRef(CFArrayGetValueAtIndex(allHashes
, n
)));
1947 return maker
.make();
1950 // full signature: Gin up full context and let DRMaker do its thing
1951 validateDirectory(); // need the cert chain
1952 CFRef
<CFDateRef
> secureTimestamp
;
1953 if (CFAbsoluteTime time
= this->signingTimestamp()) {
1954 secureTimestamp
.take(CFDateCreate(NULL
, time
));
1956 Requirement::Context
context(this->certificates(),
1957 this->infoDictionary(),
1958 this->entitlements(),
1960 this->codeDirectory(),
1962 kSecCodeSignatureNoHash
,
1967 return DRMaker(context
).make();
1969 MacOSError::throwMe(errSecCSUnimplemented
);
1976 // Validate a SecStaticCode against the internal requirement of a particular type.
1978 void SecStaticCode::validateRequirements(SecRequirementType type
, SecStaticCode
*target
,
1979 OSStatus nullError
/* = errSecSuccess */)
1981 DTRACK(CODESIGN_EVAL_STATIC_INTREQ
, this, type
, target
, nullError
);
1982 if (const Requirement
*req
= internalRequirement(type
))
1983 target
->validateRequirement(req
, nullError
? nullError
: errSecCSReqFailed
);
1985 MacOSError::throwMe(nullError
);
1991 // Validate this StaticCode against an external Requirement
1993 bool SecStaticCode::satisfiesRequirement(const Requirement
*req
, OSStatus failure
)
1995 bool result
= false;
1997 validateDirectory();
1998 CFRef
<CFDateRef
> secureTimestamp
;
1999 if (CFAbsoluteTime time
= this->signingTimestamp()) {
2000 secureTimestamp
.take(CFDateCreate(NULL
, time
));
2002 result
= req
->validates(Requirement::Context(mCertChain
, infoDictionary(), entitlements(),
2003 codeDirectory()->identifier(), codeDirectory(),
2004 NULL
, kSecCodeSignatureNoHash
, mRep
->appleInternalForcePlatform(),
2005 secureTimestamp
, teamID()),
2010 void SecStaticCode::validateRequirement(const Requirement
*req
, OSStatus failure
)
2012 if (!this->satisfiesRequirement(req
, failure
))
2013 MacOSError::throwMe(failure
);
2017 // Retrieve one certificate from the cert chain.
2018 // Positive and negative indices can be used:
2019 // [ leaf, intermed-1, ..., intermed-n, anchor ]
2021 // Returns NULL if unavailable for any reason.
2023 SecCertificateRef
SecStaticCode::cert(int ix
)
2025 validateDirectory(); // need cert chain
2027 CFIndex length
= CFArrayGetCount(mCertChain
);
2030 if (ix
>= 0 && ix
< length
)
2031 return SecCertificateRef(CFArrayGetValueAtIndex(mCertChain
, ix
));
2036 CFArrayRef
SecStaticCode::certificates()
2038 validateDirectory(); // need cert chain
2044 // Gather (mostly) API-official information about this StaticCode.
2046 // This method lives in the twilight between the API and internal layers,
2047 // since it generates API objects (Sec*Refs) for return.
2049 CFDictionaryRef
SecStaticCode::signingInformation(SecCSFlags flags
)
2052 // Start with the pieces that we return even for unsigned code.
2053 // This makes Sec[Static]CodeRefs useful as API-level replacements
2054 // of our internal OSXCode objects.
2056 CFRef
<CFMutableDictionaryRef
> dict
= makeCFMutableDictionary(1,
2057 kSecCodeInfoMainExecutable
, CFTempURL(this->mainExecutablePath()).get()
2061 // If we're not signed, this is all you get
2063 if (!this->isSigned())
2064 return dict
.yield();
2067 // Add the generic attributes that we always include
2069 CFDictionaryAddValue(dict
, kSecCodeInfoIdentifier
, CFTempString(this->identifier()));
2070 CFDictionaryAddValue(dict
, kSecCodeInfoFlags
, CFTempNumber(this->codeDirectory(false)->flags
.get()));
2071 CFDictionaryAddValue(dict
, kSecCodeInfoFormat
, CFTempString(this->format()));
2072 CFDictionaryAddValue(dict
, kSecCodeInfoSource
, CFTempString(this->signatureSource()));
2073 CFDictionaryAddValue(dict
, kSecCodeInfoUnique
, this->cdHash());
2074 CFDictionaryAddValue(dict
, kSecCodeInfoCdHashes
, this->cdHashes());
2075 CFDictionaryAddValue(dict
, kSecCodeInfoCdHashesFull
, this->cdHashesFull());
2076 const CodeDirectory
* cd
= this->codeDirectory(false);
2077 CFDictionaryAddValue(dict
, kSecCodeInfoDigestAlgorithm
, CFTempNumber(cd
->hashType
));
2078 CFRef
<CFArrayRef
> digests
= makeCFArrayFrom(^CFTypeRef(CodeDirectory::HashAlgorithm type
) { return CFTempNumber(type
); }, hashAlgorithms());
2079 CFDictionaryAddValue(dict
, kSecCodeInfoDigestAlgorithms
, digests
);
2081 CFDictionaryAddValue(dict
, kSecCodeInfoPlatformIdentifier
, CFTempNumber(cd
->platform
));
2082 if (cd
->runtimeVersion()) {
2083 CFDictionaryAddValue(dict
, kSecCodeInfoRuntimeVersion
, CFTempNumber(cd
->runtimeVersion()));
2087 // Deliver any Info.plist only if it looks intact
2090 if (CFDictionaryRef info
= this->infoDictionary())
2091 CFDictionaryAddValue(dict
, kSecCodeInfoPList
, info
);
2092 } catch (...) { } // don't deliver Info.plist if questionable
2095 // kSecCSSigningInformation adds information about signing certificates and chains
2097 if (flags
& kSecCSSigningInformation
)
2099 if (CFDataRef sig
= this->signature())
2100 CFDictionaryAddValue(dict
, kSecCodeInfoCMS
, sig
);
2101 if (const char *teamID
= this->teamID())
2102 CFDictionaryAddValue(dict
, kSecCodeInfoTeamIdentifier
, CFTempString(teamID
));
2104 CFDictionaryAddValue(dict
, kSecCodeInfoTrust
, mTrust
);
2105 if (CFArrayRef certs
= this->certificates())
2106 CFDictionaryAddValue(dict
, kSecCodeInfoCertificates
, certs
);
2107 if (CFAbsoluteTime time
= this->signingTime())
2108 if (CFRef
<CFDateRef
> date
= CFDateCreate(NULL
, time
))
2109 CFDictionaryAddValue(dict
, kSecCodeInfoTime
, date
);
2110 if (CFAbsoluteTime time
= this->signingTimestamp())
2111 if (CFRef
<CFDateRef
> date
= CFDateCreate(NULL
, time
))
2112 CFDictionaryAddValue(dict
, kSecCodeInfoTimestamp
, date
);
2116 // kSecCSRequirementInformation adds information on requirements
2118 if (flags
& kSecCSRequirementInformation
)
2120 //DR not currently supported on iOS
2123 if (const Requirements
*reqs
= this->internalRequirements()) {
2124 CFDictionaryAddValue(dict
, kSecCodeInfoRequirements
,
2125 CFTempString(Dumper::dump(reqs
)));
2126 CFDictionaryAddValue(dict
, kSecCodeInfoRequirementData
, CFTempData(*reqs
));
2129 const Requirement
*dreq
= this->designatedRequirement();
2130 CFRef
<SecRequirementRef
> dreqRef
= (new SecRequirement(dreq
))->handle();
2131 CFDictionaryAddValue(dict
, kSecCodeInfoDesignatedRequirement
, dreqRef
);
2132 if (this->internalRequirement(kSecDesignatedRequirementType
)) { // explicit
2133 CFRef
<SecRequirementRef
> ddreqRef
= (new SecRequirement(this->defaultDesignatedRequirement(), true))->handle();
2134 CFDictionaryAddValue(dict
, kSecCodeInfoImplicitDesignatedRequirement
, ddreqRef
);
2135 } else { // implicit
2136 CFDictionaryAddValue(dict
, kSecCodeInfoImplicitDesignatedRequirement
, dreqRef
);
2142 if (CFDataRef ent
= this->component(cdEntitlementSlot
)) {
2143 CFDictionaryAddValue(dict
, kSecCodeInfoEntitlements
, ent
);
2144 if (CFDictionaryRef entdict
= this->entitlements()) {
2145 if (needsCatalystEntitlementFixup(entdict
)) {
2146 // If this entitlement dictionary needs catalyst entitlements, make a copy and stick that into the
2147 // output dictionary instead.
2148 secinfo("staticCode", "%p fixed catalyst entitlements", this);
2149 CFRef
<CFMutableDictionaryRef
> tempEntitlements
= makeCFMutableDictionary(entdict
);
2150 updateCatalystEntitlements(tempEntitlements
);
2151 CFRef
<CFDictionaryRef
> newEntitlements
= CFDictionaryCreateCopy(NULL
, tempEntitlements
);
2152 if (newEntitlements
) {
2153 CFDictionaryAddValue(dict
, kSecCodeInfoEntitlementsDict
, newEntitlements
.get());
2155 secerror("%p unable to fixup entitlement dictionary", this);
2156 CFDictionaryAddValue(dict
, kSecCodeInfoEntitlementsDict
, entdict
);
2159 CFDictionaryAddValue(dict
, kSecCodeInfoEntitlementsDict
, entdict
);
2166 // kSecCSInternalInformation adds internal information meant to be for Apple internal
2167 // use (SPI), and not guaranteed to be stable. Primarily, this is data we want
2168 // to reliably transmit through the API wall so that code outside the Security.framework
2169 // can use it without having to play nasty tricks to get it.
2171 if (flags
& kSecCSInternalInformation
) {
2174 CFDictionaryAddValue(dict
, kSecCodeInfoCodeDirectory
, mDir
);
2175 CFDictionaryAddValue(dict
, kSecCodeInfoCodeOffset
, CFTempNumber(mRep
->signingBase()));
2176 if (!(flags
& kSecCSSkipResourceDirectory
)) {
2177 if (CFRef
<CFDictionaryRef
> rdict
= getDictionary(cdResourceDirSlot
, false)) // suppress validation
2178 CFDictionaryAddValue(dict
, kSecCodeInfoResourceDirectory
, rdict
);
2180 if (CFRef
<CFDictionaryRef
> ddict
= diskRepInformation())
2181 CFDictionaryAddValue(dict
, kSecCodeInfoDiskRepInfo
, ddict
);
2183 if (mNotarizationChecked
&& !isnan(mNotarizationDate
)) {
2184 CFRef
<CFDateRef
> date
= CFDateCreate(NULL
, mNotarizationDate
);
2186 CFDictionaryAddValue(dict
, kSecCodeInfoNotarizationDate
, date
.get());
2188 secerror("Error creating date from timestamp: %f", mNotarizationDate
);
2191 if (this->codeDirectory()) {
2192 uint32_t version
= this->codeDirectory()->version
;
2193 CFDictionaryAddValue(dict
, kSecCodeInfoSignatureVersion
, CFTempNumber(version
));
2197 if (flags
& kSecCSCalculateCMSDigest
) {
2199 CFDictionaryAddValue(dict
, kSecCodeInfoCMSDigestHashType
, CFTempNumber(cmsDigestHashType()));
2201 CFRef
<CFDataRef
> cmsDigest
= createCmsDigest();
2203 CFDictionaryAddValue(dict
, kSecCodeInfoCMSDigest
, cmsDigest
.get());
2209 // kSecCSContentInformation adds more information about the physical layout
2210 // of the signed code. This is (only) useful for packaging or patching-oriented
2213 if (flags
& kSecCSContentInformation
&& !(flags
& kSecCSSkipResourceDirectory
))
2214 if (CFRef
<CFArrayRef
> files
= mRep
->modifiedFiles())
2215 CFDictionaryAddValue(dict
, kSecCodeInfoChangedFiles
, files
);
2217 return dict
.yield();
2222 // Resource validation contexts.
2223 // The default context simply throws a CSError, rudely terminating the operation.
2225 SecStaticCode::ValidationContext::~ValidationContext()
2228 void SecStaticCode::ValidationContext::reportProblem(OSStatus rc
, CFStringRef type
, CFTypeRef value
)
2230 CSError::throwMe(rc
, type
, value
);
2233 void SecStaticCode::CollectingContext::reportProblem(OSStatus rc
, CFStringRef type
, CFTypeRef value
)
2235 StLock
<Mutex
> _(mLock
);
2236 if (mStatus
== errSecSuccess
)
2237 mStatus
= rc
; // record first failure for eventual error return
2240 mCollection
.take(makeCFMutableDictionary());
2241 CFMutableArrayRef element
= CFMutableArrayRef(CFDictionaryGetValue(mCollection
, type
));
2243 element
= makeCFMutableArray(0);
2246 CFDictionaryAddValue(mCollection
, type
, element
);
2249 CFArrayAppendValue(element
, value
);
2253 void SecStaticCode::CollectingContext::throwMe()
2255 assert(mStatus
!= errSecSuccess
);
2256 throw CSError(mStatus
, mCollection
.retain());
2261 // Master validation driver.
2262 // This is the static validation (only) driver for the API.
2264 // SecStaticCode exposes an a la carte menu of topical validators applying
2265 // to a given object. The static validation API pulls them together reliably,
2266 // but it also adds three matrix dimensions: architecture (for "fat" Mach-O binaries),
2267 // nested code, and multiple digests. This function will crawl a suitable cross-section of this
2268 // validation matrix based on which options it is given, creating temporary
2269 // SecStaticCode objects on the fly to complete the task.
2270 // (The point, of course, is to do as little duplicate work as possible.)
2272 void SecStaticCode::staticValidate(SecCSFlags flags
, const SecRequirement
*req
)
2274 setValidationFlags(flags
);
2277 if (!mStaplingChecked
) {
2278 mRep
->registerStapledTicket();
2279 mStaplingChecked
= true;
2282 if (mFlags
& kSecCSForceOnlineNotarizationCheck
) {
2283 if (!mNotarizationChecked
) {
2284 if (this->cdHash()) {
2285 bool is_revoked
= checkNotarizationServiceForRevocation(this->cdHash(), (SecCSDigestAlgorithm
)this->hashAlgorithm(), &mNotarizationDate
);
2287 MacOSError::throwMe(errSecCSRevokedNotarization
);
2290 mNotarizationChecked
= true;
2293 #endif // TARGET_OS_OSX
2295 // initialize progress/cancellation state
2296 if (flags
& kSecCSReportProgress
)
2297 prepareProgress(estimateResourceWorkload() + 2); // +1 head, +1 tail
2300 // core components: once per architecture (if any)
2301 this->staticValidateCore(flags
, req
);
2302 if (flags
& kSecCSCheckAllArchitectures
)
2303 handleOtherArchitectures(^(SecStaticCode
* subcode
) {
2304 if (flags
& kSecCSCheckGatekeeperArchitectures
) {
2305 Universal
*fat
= subcode
->diskRep()->mainExecutableImage();
2306 assert(fat
&& fat
->narrowed()); // handleOtherArchitectures gave us a focused architecture slice
2307 Architecture arch
= fat
->bestNativeArch(); // actually, the ONLY one
2308 if ((arch
.cpuType() & ~CPU_ARCH_MASK
) == CPU_TYPE_POWERPC
)
2309 return; // irrelevant to Gatekeeper
2311 subcode
->detachedSignature(this->mDetachedSig
); // carry over explicit (but not implicit) detached signature
2312 subcode
->staticValidateCore(flags
, req
);
2316 // allow monitor intervention in source validation phase
2317 reportEvent(CFSTR("prepared"), NULL
);
2319 // resources: once for all architectures
2320 if (!(flags
& kSecCSDoNotValidateResources
)) {
2321 this->validateResources(flags
);
2324 // perform strict validation if desired
2325 if (flags
& kSecCSStrictValidate
) {
2326 mRep
->strictValidate(codeDirectory(), mTolerateErrors
, mValidationFlags
);
2328 } else if (flags
& kSecCSStrictValidateStructure
) {
2329 mRep
->strictValidateStructure(codeDirectory(), mTolerateErrors
, mValidationFlags
);
2332 // allow monitor intervention
2333 if (CFRef
<CFTypeRef
> veto
= reportEvent(CFSTR("validated"), NULL
)) {
2334 if (CFGetTypeID(veto
) == CFNumberGetTypeID())
2335 MacOSError::throwMe(cfNumber
<OSStatus
>(veto
.as
<CFNumberRef
>()));
2337 MacOSError::throwMe(errSecCSBadCallbackValue
);
2341 void SecStaticCode::staticValidateCore(SecCSFlags flags
, const SecRequirement
*req
)
2344 this->validateNonResourceComponents(); // also validates the CodeDirectory
2345 this->validateTopDirectory();
2346 if (!(flags
& kSecCSDoNotValidateExecutable
))
2347 this->validateExecutable();
2349 this->validateRequirement(req
->requirement(), errSecCSReqFailed
);
2350 } catch (CSError
&err
) {
2351 if (Universal
*fat
= this->diskRep()->mainExecutableImage()) // Mach-O
2352 if (MachO
*mach
= fat
->architecture()) {
2353 err
.augment(kSecCFErrorArchitecture
, CFTempString(mach
->architecture().displayName()));
2357 } catch (const MacOSError
&err
) {
2358 // add architecture information if we can get it
2359 if (Universal
*fat
= this->diskRep()->mainExecutableImage())
2360 if (MachO
*mach
= fat
->architecture()) {
2361 CFTempString
arch(mach
->architecture().displayName());
2363 CSError::throwMe(err
.error
, kSecCFErrorArchitecture
, arch
);
2371 // A helper that generates SecStaticCode objects for all but the primary architecture
2372 // of a fat binary and calls a block on them.
2373 // If there's only one architecture (or this is an architecture-agnostic code),
2374 // nothing happens quickly.
2376 void SecStaticCode::handleOtherArchitectures(void (^handle
)(SecStaticCode
* other
))
2378 if (Universal
*fat
= this->diskRep()->mainExecutableImage()) {
2379 Universal::Architectures architectures
;
2380 fat
->architectures(architectures
);
2381 if (architectures
.size() > 1) {
2382 DiskRep::Context ctx
;
2383 off_t activeOffset
= fat
->archOffset();
2384 for (Universal::Architectures::const_iterator arch
= architectures
.begin(); arch
!= architectures
.end(); ++arch
) {
2386 ctx
.offset
= int_cast
<size_t, off_t
>(fat
->archOffset(*arch
));
2387 ctx
.size
= fat
->lengthOfSlice(int_cast
<off_t
,size_t>(ctx
.offset
));
2388 if (ctx
.offset
!= activeOffset
) { // inactive architecture; check it
2389 SecPointer
<SecStaticCode
> subcode
= new SecStaticCode(DiskRep::bestGuess(this->mainExecutablePath(), &ctx
));
2390 subcode
->detachedSignature(this->mDetachedSig
); // carry over explicit (but not implicit) detached signature
2391 if (this->teamID() == NULL
|| subcode
->teamID() == NULL
) {
2392 if (this->teamID() != subcode
->teamID())
2393 MacOSError::throwMe(errSecCSSignatureInvalid
);
2394 } else if (strcmp(this->teamID(), subcode
->teamID()) != 0)
2395 MacOSError::throwMe(errSecCSSignatureInvalid
);
2398 } catch(std::out_of_range e
) {
2399 // some of our int_casts fell over.
2400 MacOSError::throwMe(errSecCSBadObjectFormat
);
2408 // A method that takes a certificate chain (certs) and evaluates
2409 // if it is a Mac or IPhone developer cert, an app store distribution cert,
2410 // or a developer ID
2412 bool SecStaticCode::isAppleDeveloperCert(CFArrayRef certs
)
2414 static const std::string appleDeveloperRequirement
= "(" + std::string(WWDRRequirement
) + ") or (" + MACWWDRRequirement
+ ") or (" + developerID
+ ") or (" + distributionCertificate
+ ") or (" + iPhoneDistributionCert
+ ")";
2415 SecPointer
<SecRequirement
> req
= new SecRequirement(parseRequirement(appleDeveloperRequirement
), true);
2416 Requirement::Context
ctx(certs
, NULL
, NULL
, "", NULL
, NULL
, kSecCodeSignatureNoHash
, false, NULL
, "");
2418 return req
->requirement()->validates(ctx
);
2421 CFDataRef
SecStaticCode::createCmsDigest()
2424 * The CMS digest is a hash of the primary (first, most compatible) code directory,
2425 * but its hash algorithm is fixed and not related to the code directory's
2429 auto it
= codeDirectories()->begin();
2431 if (it
== codeDirectories()->end()) {
2435 CodeDirectory
const * const cd
= reinterpret_cast<CodeDirectory
const*>(CFDataGetBytePtr(it
->second
));
2437 RefPointer
<DynamicHash
> hash
= cd
->hashFor(mCMSDigestHashType
);
2438 CFMutableDataRef data
= CFDataCreateMutable(NULL
, hash
->digestLength());
2439 CFDataSetLength(data
, hash
->digestLength());
2440 hash
->update(cd
, cd
->length());
2441 hash
->finish(CFDataGetMutableBytePtr(data
));
2446 } // end namespace CodeSigning
2447 } // end namespace Security