2 * Copyright (c) 2006-2014 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
25 // StaticCode - SecStaticCode API objects
27 #include "StaticCode.h"
31 #include "reqdumper.h"
32 #include "reqparser.h"
34 #include "resources.h"
35 #include "detachedrep.h"
36 #include "csdatabase.h"
37 #include "dirscanner.h"
38 #include <CoreFoundation/CFURLAccess.h>
39 #include <Security/SecPolicyPriv.h>
40 #include <Security/SecTrustPriv.h>
41 #include <Security/SecCertificatePriv.h>
42 #include <Security/CMSPrivate.h>
43 #include <Security/SecCmsContentInfo.h>
44 #include <Security/SecCmsSignerInfo.h>
45 #include <Security/SecCmsSignedData.h>
46 #include <Security/cssmapplePriv.h>
47 #include <security_utilities/unix++.h>
48 #include <security_utilities/cfmunge.h>
49 #include <Security/CMSDecoder.h>
50 #include <security_utilities/logging.h>
53 #include <IOKit/storage/IOStorageDeviceCharacteristics.h>
54 #include <dispatch/private.h>
58 namespace CodeSigning
{
60 using namespace UnixPlusPlus
;
62 // A requirement representing a Mac or iOS dev cert, a Mac or iOS distribution cert, or a developer ID
63 static const char WWDRRequirement
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.2] exists";
64 static const char MACWWDRRequirement
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.12] exists";
65 static const char developerID
[] = "anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists"
66 " and certificate leaf[field.1.2.840.113635.100.6.1.13] exists";
67 static const char distributionCertificate
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.7] exists";
68 static const char iPhoneDistributionCert
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.4] exists";
71 // Map a component slot number to a suitable error code for a failure
73 static inline OSStatus
errorForSlot(CodeDirectory::SpecialSlot slot
)
77 return errSecCSInfoPlistFailed
;
78 case cdResourceDirSlot
:
79 return errSecCSResourceDirectoryFailed
;
81 return errSecCSSignatureFailed
;
87 // Construct a SecStaticCode object given a disk representation object
89 SecStaticCode::SecStaticCode(DiskRep
*rep
)
91 mValidated(false), mExecutableValidated(false), mResourcesValidated(false), mResourcesValidContext(NULL
),
92 mProgressQueue("com.apple.security.validation-progress", false, DISPATCH_QUEUE_PRIORITY_DEFAULT
),
93 mOuterScope(NULL
), mResourceScope(NULL
),
94 mDesignatedReq(NULL
), mGotResourceBase(false), mMonitor(NULL
), mLimitedAsync(NULL
), mEvalDetails(NULL
)
96 CODESIGN_STATIC_CREATE(this, rep
);
97 CFRef
<CFDataRef
> codeDirectory
= rep
->codeDirectory();
98 if (codeDirectory
&& CFDataGetLength(codeDirectory
) <= 0)
99 MacOSError::throwMe(errSecCSSignatureInvalid
);
100 checkForSystemSignature();
105 // Clean up a SecStaticCode object
107 SecStaticCode::~SecStaticCode() throw()
109 ::free(const_cast<Requirement
*>(mDesignatedReq
));
110 delete mResourcesValidContext
;
111 delete mLimitedAsync
;
117 // Initialize a nested SecStaticCode object from its parent
119 void SecStaticCode::initializeFromParent(const SecStaticCode
& parent
) {
120 mOuterScope
= &parent
;
121 setMonitor(parent
.monitor());
122 if (parent
.mLimitedAsync
)
123 mLimitedAsync
= new LimitedAsync(*parent
.mLimitedAsync
);
127 // CF-level comparison of SecStaticCode objects compares CodeDirectory hashes if signed,
128 // and falls back on comparing canonical paths if (both are) not.
130 bool SecStaticCode::equal(SecCFObject
&secOther
)
132 SecStaticCode
*other
= static_cast<SecStaticCode
*>(&secOther
);
133 CFDataRef mine
= this->cdHash();
134 CFDataRef his
= other
->cdHash();
136 return mine
&& his
&& CFEqual(mine
, his
);
138 return CFEqual(CFRef
<CFURLRef
>(this->copyCanonicalPath()), CFRef
<CFURLRef
>(other
->copyCanonicalPath()));
141 CFHashCode
SecStaticCode::hash()
143 if (CFDataRef h
= this->cdHash())
146 return CFHash(CFRef
<CFURLRef
>(this->copyCanonicalPath()));
151 // Invoke a stage monitor if registered
153 CFTypeRef
SecStaticCode::reportEvent(CFStringRef stage
, CFDictionaryRef info
)
156 return mMonitor(this->handle(false), stage
, info
);
161 void SecStaticCode::prepareProgress(unsigned int workload
)
163 dispatch_sync(mProgressQueue
, ^{
164 mCancelPending
= false; // not cancelled
166 if (mValidationFlags
& kSecCSReportProgress
) {
167 mCurrentWork
= 0; // nothing done yet
168 mTotalWork
= workload
; // totally fake - we don't know how many files we'll get to chew
172 void SecStaticCode::reportProgress(unsigned amount
/* = 1 */)
174 if (mMonitor
&& (mValidationFlags
& kSecCSReportProgress
)) {
175 // update progress and report
176 __block
bool cancel
= false;
177 dispatch_sync(mProgressQueue
, ^{
180 mCurrentWork
+= amount
;
181 mMonitor(this->handle(false), CFSTR("progress"), CFTemp
<CFDictionaryRef
>("{current=%d,total=%d}", mCurrentWork
, mTotalWork
));
183 // if cancellation is pending, abort now
185 MacOSError::throwMe(errSecCSCancelled
);
191 // Set validation conditions for fine-tuning legacy tolerance
193 static void addError(CFTypeRef cfError
, void* context
)
195 if (CFGetTypeID(cfError
) == CFNumberGetTypeID()) {
197 CFNumberGetValue(CFNumberRef(cfError
), kCFNumberSInt64Type
, (void*)&error
);
198 MacOSErrorSet
* errors
= (MacOSErrorSet
*)context
;
199 errors
->insert(OSStatus(error
));
203 void SecStaticCode::setValidationModifiers(CFDictionaryRef conditions
)
206 CFDictionary
source(conditions
, errSecCSDbCorrupt
);
207 mAllowOmissions
= source
.get
<CFArrayRef
>("omissions");
208 if (CFArrayRef errors
= source
.get
<CFArrayRef
>("errors"))
209 CFArrayApplyFunction(errors
, CFRangeMake(0, CFArrayGetCount(errors
)), addError
, &this->mTolerateErrors
);
215 // Request cancellation of a validation in progress.
216 // We do this by posting an abort flag that is checked periodically.
218 void SecStaticCode::cancelValidation()
220 if (!(mValidationFlags
& kSecCSReportProgress
)) // not using progress reporting; cancel won't make it through
221 MacOSError::throwMe(errSecCSInvalidFlags
);
222 dispatch_assert_queue(mProgressQueue
);
223 mCancelPending
= true;
228 // Attach a detached signature.
230 void SecStaticCode::detachedSignature(CFDataRef sigData
)
233 mDetachedSig
= sigData
;
234 mRep
= new DetachedRep(sigData
, mRep
->base(), "explicit detached");
235 CODESIGN_STATIC_ATTACH_EXPLICIT(this, mRep
);
239 CODESIGN_STATIC_ATTACH_EXPLICIT(this, NULL
);
245 // Consult the system detached signature database to see if it contains
246 // a detached signature for this StaticCode. If it does, fetch and attach it.
247 // We do this only if the code has no signature already attached.
249 void SecStaticCode::checkForSystemSignature()
251 if (!this->isSigned()) {
252 SignatureDatabase db
;
255 if (RefPointer
<DiskRep
> dsig
= db
.findCode(mRep
)) {
256 CODESIGN_STATIC_ATTACH_SYSTEM(this, dsig
);
266 // Return a descriptive string identifying the source of the code signature
268 string
SecStaticCode::signatureSource()
272 if (DetachedRep
*rep
= dynamic_cast<DetachedRep
*>(mRep
.get()))
273 return rep
->source();
279 // Do ::required, but convert incoming SecCodeRefs to their SecStaticCodeRefs
282 SecStaticCode
*SecStaticCode::requiredStatic(SecStaticCodeRef ref
)
284 SecCFObject
*object
= SecCFObject::required(ref
, errSecCSInvalidObjectRef
);
285 if (SecStaticCode
*scode
= dynamic_cast<SecStaticCode
*>(object
))
287 else if (SecCode
*code
= dynamic_cast<SecCode
*>(object
))
288 return code
->staticCode();
289 else // neither (a SecSomethingElse)
290 MacOSError::throwMe(errSecCSInvalidObjectRef
);
293 SecCode
*SecStaticCode::optionalDynamic(SecStaticCodeRef ref
)
295 SecCFObject
*object
= SecCFObject::required(ref
, errSecCSInvalidObjectRef
);
296 if (dynamic_cast<SecStaticCode
*>(object
))
298 else if (SecCode
*code
= dynamic_cast<SecCode
*>(object
))
300 else // neither (a SecSomethingElse)
301 MacOSError::throwMe(errSecCSInvalidObjectRef
);
306 // Void all cached validity data.
308 // We also throw out cached components, because the new signature data may have
309 // a different idea of what components should be present. We could reconcile the
310 // cached data instead, if performance seems to be impacted.
312 void SecStaticCode::resetValidity()
314 CODESIGN_EVAL_STATIC_RESET(this);
316 mExecutableValidated
= mResourcesValidated
= false;
317 if (mResourcesValidContext
) {
318 delete mResourcesValidContext
;
319 mResourcesValidContext
= NULL
;
323 for (unsigned n
= 0; n
< cdSlotCount
; n
++)
326 mEntitlements
= NULL
;
327 mResourceDict
= NULL
;
328 mDesignatedReq
= NULL
;
330 mGotResourceBase
= false;
336 // we may just have updated the system database, so check again
337 checkForSystemSignature();
342 // Retrieve a sealed component by special slot index.
343 // If the CodeDirectory has already been validated, validate against that.
344 // Otherwise, retrieve the component without validation (but cache it). Validation
345 // will go through the cache and validate all cached components.
347 CFDataRef
SecStaticCode::component(CodeDirectory::SpecialSlot slot
, OSStatus fail
/* = errSecCSSignatureFailed */)
349 assert(slot
<= cdSlotMax
);
351 CFRef
<CFDataRef
> &cache
= mCache
[slot
];
353 if (CFRef
<CFDataRef
> data
= mRep
->component(slot
)) {
354 if (validated()) { // if the directory has been validated...
355 if (!codeDirectory()->slotIsPresent(-slot
))
358 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data
), // ... and it's no good
359 CFDataGetLength(data
), -slot
))
360 MacOSError::throwMe(errorForSlot(slot
)); // ... then bail
362 cache
= data
; // it's okay, cache it
363 } else { // absent, mark so
364 if (validated()) // if directory has been validated...
365 if (codeDirectory()->slotIsPresent(-slot
)) // ... and the slot is NOT missing
366 MacOSError::throwMe(errorForSlot(slot
)); // was supposed to be there
367 cache
= CFDataRef(kCFNull
); // white lie
370 return (cache
== CFDataRef(kCFNull
)) ? NULL
: cache
.get();
375 // Get the CodeDirectory.
376 // Throws (if check==true) or returns NULL (check==false) if there is none.
377 // Always throws if the CodeDirectory exists but is invalid.
378 // NEVER validates against the signature.
380 const CodeDirectory
*SecStaticCode::codeDirectory(bool check
/* = true */)
383 if (mDir
.take(mRep
->codeDirectory())) {
384 const CodeDirectory
*dir
= reinterpret_cast<const CodeDirectory
*>(CFDataGetBytePtr(mDir
));
385 if (!dir
->validateBlob(CFDataGetLength(mDir
)))
386 MacOSError::throwMe(errSecCSSignatureInvalid
);
387 dir
->checkIntegrity();
391 return reinterpret_cast<const CodeDirectory
*>(CFDataGetBytePtr(mDir
));
393 MacOSError::throwMe(errSecCSUnsigned
);
399 // Get the hash of the CodeDirectory.
400 // Returns NULL if there is none.
402 CFDataRef
SecStaticCode::cdHash()
405 if (const CodeDirectory
*cd
= codeDirectory(false)) {
406 mCDHash
.take(cd
->cdhash());
407 CODESIGN_STATIC_CDHASH(this, CFDataGetBytePtr(mCDHash
), (unsigned int)CFDataGetLength(mCDHash
));
415 // Return the CMS signature blob; NULL if none found.
417 CFDataRef
SecStaticCode::signature()
420 mSignature
.take(mRep
->signature());
423 MacOSError::throwMe(errSecCSUnsigned
);
428 // Verify the signature on the CodeDirectory.
429 // If this succeeds (doesn't throw), the CodeDirectory is statically trustworthy.
430 // Any outcome (successful or not) is cached for the lifetime of the StaticCode.
432 void SecStaticCode::validateDirectory()
434 // echo previous outcome, if any
435 // track revocation separately, as it may not have been checked
436 // during the initial validation
437 if (!validated() || ((mValidationFlags
& kSecCSEnforceRevocationChecks
) && !revocationChecked()))
439 // perform validation (or die trying)
440 CODESIGN_EVAL_STATIC_DIRECTORY(this);
441 mValidationExpired
= verifySignature();
442 if (mValidationFlags
& kSecCSEnforceRevocationChecks
)
443 mRevocationChecked
= true;
445 for (CodeDirectory::SpecialSlot slot
= codeDirectory()->maxSpecialSlot(); slot
>= 1; --slot
)
446 if (mCache
[slot
]) // if we already loaded that resource...
447 validateComponent(slot
, errorForSlot(slot
)); // ... then check it now
448 mValidated
= true; // we've done the deed...
449 mValidationResult
= errSecSuccess
; // ... and it was good
450 } catch (const CommonError
&err
) {
452 mValidationResult
= err
.osStatus();
455 secdebug("staticCode", "%p validation threw non-common exception", this);
457 mValidationResult
= errSecCSInternalError
;
461 if (mValidationResult
== errSecSuccess
) {
462 if (mValidationExpired
)
463 if ((mValidationFlags
& kSecCSConsiderExpiration
)
464 || (codeDirectory()->flags
& kSecCodeSignatureForceExpiration
))
465 MacOSError::throwMe(CSSMERR_TP_CERT_EXPIRED
);
467 MacOSError::throwMe(mValidationResult
);
472 // Load and validate the CodeDirectory and all components *except* those related to the resource envelope.
473 // Those latter components are checked by validateResources().
475 void SecStaticCode::validateNonResourceComponents()
477 this->validateDirectory();
478 for (CodeDirectory::SpecialSlot slot
= codeDirectory()->maxSpecialSlot(); slot
>= 1; --slot
)
480 case cdResourceDirSlot
: // validated by validateResources
483 this->component(slot
); // loads and validates
490 // Get the (signed) signing date from the code signature.
491 // Sadly, we need to validate the signature to get the date (as a side benefit).
492 // This means that you can't get the signing time for invalidly signed code.
494 // We could run the decoder "almost to" verification to avoid this, but there seems
495 // little practical point to such a duplication of effort.
497 CFAbsoluteTime
SecStaticCode::signingTime()
503 CFAbsoluteTime
SecStaticCode::signingTimestamp()
506 return mSigningTimestamp
;
511 // Verify the CMS signature on the CodeDirectory.
512 // This performs the cryptographic tango. It returns if the signature is valid,
513 // or throws if it is not. As a side effect, a successful return sets up the
514 // cached certificate chain for future use.
515 // Returns true if the signature is expired (the X.509 sense), false if it's not.
516 // Expiration is fatal (throws) if a secure timestamp is included, but not otherwise.
518 bool SecStaticCode::verifySignature()
520 // ad-hoc signed code is considered validly signed by definition
521 if (flag(kSecCodeSignatureAdhoc
)) {
522 CODESIGN_EVAL_STATIC_SIGNATURE_ADHOC(this);
526 DTRACK(CODESIGN_EVAL_STATIC_SIGNATURE
, this, (char*)this->mainExecutablePath().c_str());
528 // decode CMS and extract SecTrust for verification
529 CFRef
<CMSDecoderRef
> cms
;
530 MacOSError::check(CMSDecoderCreate(&cms
.aref())); // create decoder
531 CFDataRef sig
= this->signature();
532 MacOSError::check(CMSDecoderUpdateMessage(cms
, CFDataGetBytePtr(sig
), CFDataGetLength(sig
)));
533 this->codeDirectory(); // load CodeDirectory (sets mDir)
534 MacOSError::check(CMSDecoderSetDetachedContent(cms
, mDir
));
535 MacOSError::check(CMSDecoderFinalizeMessage(cms
));
536 MacOSError::check(CMSDecoderSetSearchKeychain(cms
, cfEmptyArray()));
537 CFRef
<CFArrayRef
> vf_policies
= verificationPolicies();
538 CFRef
<CFArrayRef
> ts_policies
= SecPolicyCreateAppleTimeStampingAndRevocationPolicies(vf_policies
);
539 CMSSignerStatus status
;
540 MacOSError::check(CMSDecoderCopySignerStatus(cms
, 0, vf_policies
,
541 false, &status
, &mTrust
.aref(), NULL
));
543 if (status
!= kCMSSignerValid
) {
546 case kCMSSignerUnsigned
: reason
="kCMSSignerUnsigned"; break;
547 case kCMSSignerNeedsDetachedContent
: reason
="kCMSSignerNeedsDetachedContent"; break;
548 case kCMSSignerInvalidSignature
: reason
="kCMSSignerInvalidSignature"; break;
549 case kCMSSignerInvalidCert
: reason
="kCMSSignerInvalidCert"; break;
550 case kCMSSignerInvalidIndex
: reason
="kCMSSignerInvalidIndex"; break;
551 default: reason
="unknown"; break;
553 Security::Syslog::error("CMSDecoderCopySignerStatus failed with %s error (%d)",
554 reason
, (int)status
);
555 MacOSError::throwMe(errSecCSSignatureFailed
);
558 // internal signing time (as specified by the signer; optional)
559 mSigningTime
= 0; // "not present" marker (nobody could code sign on Jan 1, 2001 :-)
560 switch (OSStatus rc
= CMSDecoderCopySignerSigningTime(cms
, 0, &mSigningTime
)) {
562 case errSecSigningTimeMissing
:
565 Security::Syslog::error("Could not get signing time (error %d)", (int)rc
);
566 MacOSError::throwMe(rc
);
569 // certified signing time (as specified by a TSA; optional)
570 mSigningTimestamp
= 0;
571 switch (OSStatus rc
= CMSDecoderCopySignerTimestampWithPolicy(cms
, ts_policies
, 0, &mSigningTimestamp
)) {
573 case errSecTimestampMissing
:
576 Security::Syslog::error("Could not get timestamp (error %d)", (int)rc
);
577 MacOSError::throwMe(rc
);
580 // set up the environment for SecTrust
581 if (mValidationFlags
& kSecCSNoNetworkAccess
) {
582 MacOSError::check(SecTrustSetNetworkFetchAllowed(mTrust
,false)); // no network?
584 MacOSError::check(SecTrustSetKeychains(mTrust
, cfEmptyArray())); // no keychains
586 CSSM_APPLE_TP_ACTION_DATA actionData
= {
587 CSSM_APPLE_TP_ACTION_VERSION
, // version of data structure
591 if (!(mValidationFlags
& kSecCSCheckTrustedAnchors
)) {
592 /* no need to evaluate anchor trust when building cert chain */
593 MacOSError::check(SecTrustSetAnchorCertificates(mTrust
, cfEmptyArray())); // no anchors
594 actionData
.ActionFlags
|= CSSM_TP_ACTION_IMPLICIT_ANCHORS
; // action flags
597 for (;;) { // at most twice
598 MacOSError::check(SecTrustSetParameters(mTrust
,
599 CSSM_TP_ACTION_DEFAULT
, CFTempData(&actionData
, sizeof(actionData
))));
601 // evaluate trust and extract results
602 SecTrustResultType trustResult
;
603 MacOSError::check(SecTrustEvaluate(mTrust
, &trustResult
));
604 MacOSError::check(SecTrustGetResult(mTrust
, &trustResult
, &mCertChain
.aref(), &mEvalDetails
));
606 // if this is an Apple developer cert....
607 if (teamID() && SecStaticCode::isAppleDeveloperCert(mCertChain
)) {
608 CFRef
<CFStringRef
> teamIDFromCert
;
609 if (CFArrayGetCount(mCertChain
) > 0) {
610 /* Note that SecCertificateCopySubjectComponent sets the out parameter to NULL if there is no field present */
611 MacOSError::check(SecCertificateCopySubjectComponent((SecCertificateRef
)CFArrayGetValueAtIndex(mCertChain
, Requirement::leafCert
),
612 &CSSMOID_OrganizationalUnitName
,
613 &teamIDFromCert
.aref()));
615 if (teamIDFromCert
) {
616 CFRef
<CFStringRef
> teamIDFromCD
= CFStringCreateWithCString(NULL
, teamID(), kCFStringEncodingUTF8
);
618 Security::Syslog::error("Could not get team identifier (%s)", teamID());
619 MacOSError::throwMe(errSecCSInternalError
);
622 if (CFStringCompare(teamIDFromCert
, teamIDFromCD
, 0) != kCFCompareEqualTo
) {
623 Security::Syslog::error("Team identifier in the signing certificate (%s) does not match the team identifier (%s) in the code directory", cfString(teamIDFromCert
).c_str(), teamID());
624 MacOSError::throwMe(errSecCSSignatureInvalid
);
630 CODESIGN_EVAL_STATIC_SIGNATURE_RESULT(this, trustResult
, mCertChain
? (int)CFArrayGetCount(mCertChain
) : 0);
631 switch (trustResult
) {
632 case kSecTrustResultProceed
:
633 case kSecTrustResultUnspecified
:
635 case kSecTrustResultDeny
:
636 MacOSError::throwMe(CSSMERR_APPLETP_TRUST_SETTING_DENY
); // user reject
637 case kSecTrustResultInvalid
:
638 assert(false); // should never happen
639 MacOSError::throwMe(CSSMERR_TP_NOT_TRUSTED
);
643 MacOSError::check(SecTrustGetCssmResultCode(mTrust
, &result
));
644 // if we have a valid timestamp, CMS validates against (that) signing time and all is well.
645 // If we don't have one, may validate against *now*, and must be able to tolerate expiration.
646 if (mSigningTimestamp
== 0) { // no timestamp available
647 if (((result
== CSSMERR_TP_CERT_EXPIRED
) || (result
== CSSMERR_TP_CERT_NOT_VALID_YET
))
648 && !(actionData
.ActionFlags
& CSSM_TP_ACTION_ALLOW_EXPIRED
)) {
649 CODESIGN_EVAL_STATIC_SIGNATURE_EXPIRED(this);
650 actionData
.ActionFlags
|= CSSM_TP_ACTION_ALLOW_EXPIRED
; // (this also allows postdated certs)
651 continue; // retry validation while tolerating expiration
654 Security::Syslog::error("SecStaticCode: verification failed (trust result %d, error %d)", trustResult
, (int)result
);
655 MacOSError::throwMe(result
);
659 if (mSigningTimestamp
) {
660 CFIndex rootix
= CFArrayGetCount(mCertChain
);
661 if (SecCertificateRef mainRoot
= SecCertificateRef(CFArrayGetValueAtIndex(mCertChain
, rootix
-1)))
662 if (isAppleCA(mainRoot
)) {
663 // impose policy: if the signature itself draws to Apple, then so must the timestamp signature
664 CFRef
<CFArrayRef
> tsCerts
;
665 OSStatus result
= CMSDecoderCopySignerTimestampCertificates(cms
, 0, &tsCerts
.aref());
667 Security::Syslog::error("SecStaticCode: could not get timestamp certificates (error %d)", (int)result
);
668 MacOSError::check(result
);
670 CFIndex tsn
= CFArrayGetCount(tsCerts
);
671 bool good
= tsn
> 0 && isAppleCA(SecCertificateRef(CFArrayGetValueAtIndex(tsCerts
, tsn
-1)));
673 result
= CSSMERR_TP_NOT_TRUSTED
;
674 Security::Syslog::error("SecStaticCode: timestamp policy verification failed (error %d)", (int)result
);
675 MacOSError::throwMe(result
);
680 return actionData
.ActionFlags
& CSSM_TP_ACTION_ALLOW_EXPIRED
;
686 // Return the TP policy used for signature verification.
687 // This may be a simple SecPolicyRef or a CFArray of policies.
688 // The caller owns the return value.
690 static SecPolicyRef
makeCRLPolicy()
692 CFRef
<SecPolicyRef
> policy
;
693 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_REVOCATION_CRL
, &policy
.aref()));
694 CSSM_APPLE_TP_CRL_OPTIONS options
;
695 memset(&options
, 0, sizeof(options
));
696 options
.Version
= CSSM_APPLE_TP_CRL_OPTS_VERSION
;
697 options
.CrlFlags
= CSSM_TP_ACTION_FETCH_CRL_FROM_NET
| CSSM_TP_ACTION_CRL_SUFFICIENT
;
698 CSSM_DATA optData
= { sizeof(options
), (uint8
*)&options
};
699 MacOSError::check(SecPolicySetValue(policy
, &optData
));
700 return policy
.yield();
703 static SecPolicyRef
makeOCSPPolicy()
705 CFRef
<SecPolicyRef
> policy
;
706 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_REVOCATION_OCSP
, &policy
.aref()));
707 CSSM_APPLE_TP_OCSP_OPTIONS options
;
708 memset(&options
, 0, sizeof(options
));
709 options
.Version
= CSSM_APPLE_TP_OCSP_OPTS_VERSION
;
710 options
.Flags
= CSSM_TP_ACTION_OCSP_SUFFICIENT
;
711 CSSM_DATA optData
= { sizeof(options
), (uint8
*)&options
};
712 MacOSError::check(SecPolicySetValue(policy
, &optData
));
713 return policy
.yield();
716 CFArrayRef
SecStaticCode::verificationPolicies()
718 CFRef
<SecPolicyRef
> core
;
719 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3
,
720 &CSSMOID_APPLE_TP_CODE_SIGNING
, &core
.aref()));
721 if (mValidationFlags
& kSecCSNoNetworkAccess
) {
722 // Skips all revocation since they require network connectivity
723 // therefore annihilates kSecCSEnforceRevocationChecks if present
724 CFRef
<SecPolicyRef
> no_revoc
= SecPolicyCreateRevocation(kSecRevocationNetworkAccessDisabled
);
725 return makeCFArray(2, core
.get(), no_revoc
.get());
727 else if (mValidationFlags
& kSecCSEnforceRevocationChecks
) {
728 // Add CRL and OCSPPolicies
729 CFRef
<SecPolicyRef
> crl
= makeCRLPolicy();
730 CFRef
<SecPolicyRef
> ocsp
= makeOCSPPolicy();
731 return makeCFArray(3, core
.get(), crl
.get(), ocsp
.get());
733 return makeCFArray(1, core
.get());
739 // Validate a particular sealed, cached resource against its (special) CodeDirectory slot.
740 // The resource must already have been placed in the cache.
741 // This does NOT perform basic validation.
743 void SecStaticCode::validateComponent(CodeDirectory::SpecialSlot slot
, OSStatus fail
/* = errSecCSSignatureFailed */)
745 assert(slot
<= cdSlotMax
);
746 CFDataRef data
= mCache
[slot
];
747 assert(data
); // must be cached
748 if (data
== CFDataRef(kCFNull
)) {
749 if (codeDirectory()->slotIsPresent(-slot
)) // was supposed to be there...
750 MacOSError::throwMe(fail
); // ... and is missing
752 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data
), CFDataGetLength(data
), -slot
))
753 MacOSError::throwMe(fail
);
759 // Perform static validation of the main executable.
760 // This reads the main executable from disk and validates it against the
761 // CodeDirectory code slot array.
762 // Note that this is NOT an in-memory validation, and is thus potentially
763 // subject to timing attacks.
765 void SecStaticCode::validateExecutable()
767 if (!validatedExecutable()) {
769 DTRACK(CODESIGN_EVAL_STATIC_EXECUTABLE
, this,
770 (char*)this->mainExecutablePath().c_str(), codeDirectory()->nCodeSlots
);
771 const CodeDirectory
*cd
= this->codeDirectory();
773 MacOSError::throwMe(errSecCSUnsigned
);
774 AutoFileDesc
fd(mainExecutablePath(), O_RDONLY
);
775 fd
.fcntl(F_NOCACHE
, true); // turn off page caching (one-pass)
776 if (Universal
*fat
= mRep
->mainExecutableImage())
777 fd
.seek(fat
->archOffset());
778 size_t pageSize
= cd
->pageSize
? (1 << cd
->pageSize
) : 0;
779 size_t remaining
= cd
->codeLimit
;
780 for (uint32_t slot
= 0; slot
< cd
->nCodeSlots
; ++slot
) {
781 size_t size
= min(remaining
, pageSize
);
782 if (!cd
->validateSlot(fd
, size
, slot
)) {
783 CODESIGN_EVAL_STATIC_EXECUTABLE_FAIL(this, (int)slot
);
784 MacOSError::throwMe(errSecCSSignatureFailed
);
788 mExecutableValidated
= true;
789 mExecutableValidResult
= errSecSuccess
;
790 } catch (const CommonError
&err
) {
791 mExecutableValidated
= true;
792 mExecutableValidResult
= err
.osStatus();
795 secdebug("staticCode", "%p executable validation threw non-common exception", this);
796 mExecutableValidated
= true;
797 mExecutableValidResult
= errSecCSInternalError
;
801 assert(validatedExecutable());
802 if (mExecutableValidResult
!= errSecSuccess
)
803 MacOSError::throwMe(mExecutableValidResult
);
808 // Perform static validation of sealed resources and nested code.
810 // This performs a whole-code static resource scan and effectively
811 // computes a concordance between what's on disk and what's in the ResourceDirectory.
812 // Any unsanctioned difference causes an error.
814 unsigned SecStaticCode::estimateResourceWorkload()
816 // workload estimate = number of sealed files
817 CFDictionaryRef sealedResources
= resourceDictionary();
818 CFDictionaryRef files
= cfget
<CFDictionaryRef
>(sealedResources
, "files2");
820 files
= cfget
<CFDictionaryRef
>(sealedResources
, "files");
821 return files
? unsigned(CFDictionaryGetCount(files
)) : 0;
824 void SecStaticCode::validateResources(SecCSFlags flags
)
826 // do we have a superset of this requested validation cached?
828 if (mResourcesValidated
) { // have cached outcome
829 if (!(flags
& kSecCSCheckNestedCode
) || mResourcesDeep
) // was deep or need no deep scan
834 if (mLimitedAsync
== NULL
) {
835 mLimitedAsync
= new LimitedAsync(diskRep()->fd().mediumType() == kIOPropertyMediumTypeSolidStateKey
);
840 CFDictionaryRef sealedResources
= resourceDictionary();
841 if (this->resourceBase()) // disk has resources
843 /* go to work below */;
845 MacOSError::throwMe(errSecCSResourcesNotFound
);
846 else // disk has no resources
848 MacOSError::throwMe(errSecCSResourcesNotFound
);
850 return; // no resources, not sealed - fine (no work)
852 // found resources, and they are sealed
853 DTRACK(CODESIGN_EVAL_STATIC_RESOURCES
, this,
854 (char*)this->mainExecutablePath().c_str(), 0);
856 // scan through the resources on disk, checking each against the resourceDirectory
857 mResourcesValidContext
= new CollectingContext(*this); // collect all failures in here
859 // use V2 resource seal if available, otherwise fall back to V1
860 CFDictionaryRef rules
;
861 CFDictionaryRef files
;
863 if (CFDictionaryGetValue(sealedResources
, CFSTR("files2"))) { // have V2 signature
864 rules
= cfget
<CFDictionaryRef
>(sealedResources
, "rules2");
865 files
= cfget
<CFDictionaryRef
>(sealedResources
, "files2");
867 } else { // only V1 available
868 rules
= cfget
<CFDictionaryRef
>(sealedResources
, "rules");
869 files
= cfget
<CFDictionaryRef
>(sealedResources
, "files");
872 if (!rules
|| !files
)
873 MacOSError::throwMe(errSecCSResourcesInvalid
);
875 // check for weak resource rules
876 bool strict
= flags
& kSecCSStrictValidate
;
878 if (hasWeakResourceRules(rules
, version
, mAllowOmissions
))
879 if (mTolerateErrors
.find(errSecCSWeakResourceRules
) == mTolerateErrors
.end())
880 MacOSError::throwMe(errSecCSWeakResourceRules
);
882 if (mTolerateErrors
.find(errSecCSWeakResourceEnvelope
) == mTolerateErrors
.end())
883 MacOSError::throwMe(errSecCSWeakResourceEnvelope
);
886 Dispatch::Group group
;
887 Dispatch::Group
&groupRef
= group
; // (into block)
889 // scan through the resources on disk, checking each against the resourceDirectory
890 __block CFRef
<CFMutableDictionaryRef
> resourceMap
= makeCFMutableDictionary(files
);
891 string base
= cfString(this->resourceBase());
892 ResourceBuilder
resources(base
, base
, rules
, codeDirectory()->hashType
, strict
, mTolerateErrors
);
893 this->mResourceScope
= &resources
;
894 diskRep()->adjustResources(resources
);
896 resources
.scan(^(FTSENT
*ent
, uint32_t ruleFlags
, const string relpath
, ResourceBuilder::Rule
*rule
) {
897 CFDictionaryRemoveValue(resourceMap
, CFTempString(relpath
));
898 bool isSymlink
= (ent
->fts_info
== FTS_SL
);
900 void (^validate
)() = ^{
901 validateResource(files
, relpath
, isSymlink
, *mResourcesValidContext
, flags
, version
);
905 mLimitedAsync
->perform(groupRef
, validate
);
907 group
.wait(); // wait until all async resources have been validated as well
909 unsigned leftovers
= unsigned(CFDictionaryGetCount(resourceMap
));
911 secdebug("staticCode", "%d sealed resource(s) not found in code", int(leftovers
));
912 CFDictionaryApplyFunction(resourceMap
, SecStaticCode::checkOptionalResource
, mResourcesValidContext
);
915 // now check for any errors found in the reporting context
916 mResourcesValidated
= true;
917 mResourcesDeep
= flags
& kSecCSCheckNestedCode
;
918 if (mResourcesValidContext
->osStatus() != errSecSuccess
)
919 mResourcesValidContext
->throwMe();
920 } catch (const CommonError
&err
) {
921 mResourcesValidated
= true;
922 mResourcesDeep
= flags
& kSecCSCheckNestedCode
;
923 mResourcesValidResult
= err
.osStatus();
926 secdebug("staticCode", "%p executable validation threw non-common exception", this);
927 mResourcesValidated
= true;
928 mResourcesDeep
= flags
& kSecCSCheckNestedCode
;
929 mResourcesValidResult
= errSecCSInternalError
;
933 assert(validatedResources());
934 if (mResourcesValidResult
)
935 MacOSError::throwMe(mResourcesValidResult
);
936 if (mResourcesValidContext
->osStatus() != errSecSuccess
)
937 mResourcesValidContext
->throwMe();
941 void SecStaticCode::checkOptionalResource(CFTypeRef key
, CFTypeRef value
, void *context
)
943 ValidationContext
*ctx
= static_cast<ValidationContext
*>(context
);
944 ResourceSeal
seal(value
);
945 if (!seal
.optional()) {
946 if (key
&& CFGetTypeID(key
) == CFStringGetTypeID()) {
947 CFTempURL
tempURL(CFStringRef(key
), false, ctx
->code
.resourceBase());
948 if (!tempURL
.get()) {
949 ctx
->reportProblem(errSecCSBadDictionaryFormat
, kSecCFErrorResourceSeal
, key
);
951 ctx
->reportProblem(errSecCSBadResource
, kSecCFErrorResourceMissing
, tempURL
);
954 ctx
->reportProblem(errSecCSBadResource
, kSecCFErrorResourceSeal
, key
);
960 static bool isOmitRule(CFTypeRef value
)
962 if (CFGetTypeID(value
) == CFBooleanGetTypeID())
963 return value
== kCFBooleanFalse
;
964 CFDictionary
rule(value
, errSecCSResourceRulesInvalid
);
965 return rule
.get
<CFBooleanRef
>("omit") == kCFBooleanTrue
;
968 bool SecStaticCode::hasWeakResourceRules(CFDictionaryRef rulesDict
, uint32_t version
, CFArrayRef allowedOmissions
)
970 // compute allowed omissions
971 CFRef
<CFArrayRef
> defaultOmissions
= this->diskRep()->allowedResourceOmissions();
972 if (!defaultOmissions
)
973 MacOSError::throwMe(errSecCSInternalError
);
974 CFRef
<CFMutableArrayRef
> allowed
= CFArrayCreateMutableCopy(NULL
, 0, defaultOmissions
);
975 if (allowedOmissions
)
976 CFArrayAppendArray(allowed
, allowedOmissions
, CFRangeMake(0, CFArrayGetCount(allowedOmissions
)));
977 CFRange range
= CFRangeMake(0, CFArrayGetCount(allowed
));
979 // check all resource rules for weakness
980 string catchAllRule
= (version
== 1) ? "^Resources/" : "^.*";
981 __block
bool coversAll
= false;
982 __block
bool forbiddenOmission
= false;
983 CFArrayRef allowedRef
= allowed
.get(); // (into block)
984 CFDictionary
rules(rulesDict
, errSecCSResourceRulesInvalid
);
985 rules
.apply(^(CFStringRef key
, CFTypeRef value
) {
986 string pattern
= cfString(key
, errSecCSResourceRulesInvalid
);
987 if (pattern
== catchAllRule
&& value
== kCFBooleanTrue
) {
991 if (isOmitRule(value
))
992 forbiddenOmission
|= !CFArrayContainsValue(allowedRef
, range
, key
);
995 return !coversAll
|| forbiddenOmission
;
1000 // Load, validate, cache, and return CFDictionary forms of sealed resources.
1002 CFDictionaryRef
SecStaticCode::infoDictionary()
1005 mInfoDict
.take(getDictionary(cdInfoSlot
, errSecCSInfoPlistFailed
));
1006 secdebug("staticCode", "%p loaded InfoDict %p", this, mInfoDict
.get());
1011 CFDictionaryRef
SecStaticCode::entitlements()
1013 if (!mEntitlements
) {
1014 validateDirectory();
1015 if (CFDataRef entitlementData
= component(cdEntitlementSlot
)) {
1016 validateComponent(cdEntitlementSlot
);
1017 const EntitlementBlob
*blob
= reinterpret_cast<const EntitlementBlob
*>(CFDataGetBytePtr(entitlementData
));
1018 if (blob
->validateBlob()) {
1019 mEntitlements
.take(blob
->entitlements());
1020 secdebug("staticCode", "%p loaded Entitlements %p", this, mEntitlements
.get());
1022 // we do not consider a different blob type to be an error. We think it's a new format we don't understand
1025 return mEntitlements
;
1028 CFDictionaryRef
SecStaticCode::resourceDictionary(bool check
/* = true */)
1030 if (mResourceDict
) // cached
1031 return mResourceDict
;
1032 if (CFRef
<CFDictionaryRef
> dict
= getDictionary(cdResourceDirSlot
, check
))
1033 if (cfscan(dict
, "{rules=%Dn,files=%Dn}")) {
1034 secdebug("staticCode", "%p loaded ResourceDict %p",
1035 this, mResourceDict
.get());
1036 return mResourceDict
= dict
;
1044 // Load and cache the resource directory base.
1045 // Note that the base is optional for each DiskRep.
1047 CFURLRef
SecStaticCode::resourceBase()
1049 if (!mGotResourceBase
) {
1050 string base
= mRep
->resourcesRootPath();
1052 mResourceBase
.take(makeCFURL(base
, true));
1053 mGotResourceBase
= true;
1055 return mResourceBase
;
1060 // Load a component, validate it, convert it to a CFDictionary, and return that.
1061 // This will force load and validation, which means that it will perform basic
1062 // validation if it hasn't been done yet.
1064 CFDictionaryRef
SecStaticCode::getDictionary(CodeDirectory::SpecialSlot slot
, bool check
/* = true */)
1067 validateDirectory();
1068 if (CFDataRef infoData
= component(slot
)) {
1069 validateComponent(slot
);
1070 if (CFDictionaryRef dict
= makeCFDictionaryFrom(infoData
))
1073 MacOSError::throwMe(errSecCSBadDictionaryFormat
);
1080 // Load, validate, and return a sealed resource.
1081 // The resource data (loaded in to memory as a blob) is returned and becomes
1082 // the responsibility of the caller; it is NOT cached by SecStaticCode.
1084 // A resource that is not sealed will not be returned, and an error will be thrown.
1085 // A missing resource will cause an error unless it's marked optional in the Directory.
1086 // Under no circumstances will a corrupt resource be returned.
1087 // NULL will only be returned for a resource that is neither sealed nor present
1088 // (or that is sealed, absent, and marked optional).
1089 // If the ResourceDictionary itself is not sealed, this function will always fail.
1091 // There is currently no interface for partial retrieval of the resource data.
1092 // (Since the ResourceDirectory does not currently support segmentation, all the
1093 // data would have to be read anyway, but it could be read into a reusable buffer.)
1095 CFDataRef
SecStaticCode::resource(string path
, ValidationContext
&ctx
)
1097 if (CFDictionaryRef rdict
= resourceDictionary()) {
1098 if (CFTypeRef file
= cfget(rdict
, "files.%s", path
.c_str())) {
1099 ResourceSeal seal
= file
;
1100 if (!resourceBase()) // no resources in DiskRep
1101 MacOSError::throwMe(errSecCSResourcesNotFound
);
1103 MacOSError::throwMe(errSecCSResourcesNotSealed
); // (it's nested code)
1104 CFRef
<CFURLRef
> fullpath
= makeCFURL(path
, false, resourceBase());
1105 if (CFRef
<CFDataRef
> data
= cfLoadFile(fullpath
)) {
1106 MakeHash
<CodeDirectory
> hasher(this->codeDirectory());
1107 hasher
->update(CFDataGetBytePtr(data
), CFDataGetLength(data
));
1108 if (hasher
->verify(seal
.hash()))
1109 return data
.yield(); // good
1111 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // altered
1113 if (!seal
.optional())
1114 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceMissing
, fullpath
); // was sealed but is now missing
1116 return NULL
; // validly missing
1119 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAdded
, CFTempURL(path
, false, resourceBase()));
1122 MacOSError::throwMe(errSecCSResourcesNotSealed
);
1125 CFDataRef
SecStaticCode::resource(string path
)
1127 ValidationContext
ctx(*this);
1128 return resource(path
, ctx
);
1131 void SecStaticCode::validateResource(CFDictionaryRef files
, string path
, bool isSymlink
, ValidationContext
&ctx
, SecCSFlags flags
, uint32_t version
)
1133 if (!resourceBase()) // no resources in DiskRep
1134 MacOSError::throwMe(errSecCSResourcesNotFound
);
1135 CFRef
<CFURLRef
> fullpath
= makeCFURL(path
, false, resourceBase());
1136 if (CFTypeRef file
= CFDictionaryGetValue(files
, CFTempString(path
))) {
1137 ResourceSeal seal
= file
;
1138 if (seal
.nested()) {
1140 return ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
1141 string suffix
= ".framework";
1142 bool isFramework
= (path
.length() > suffix
.length())
1143 && (path
.compare(path
.length()-suffix
.length(), suffix
.length(), suffix
) == 0);
1144 validateNestedCode(fullpath
, seal
, flags
, isFramework
);
1145 } else if (seal
.link()) {
1147 return ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
1148 validateSymlinkResource(cfString(fullpath
), cfString(seal
.link()), ctx
, flags
);
1149 } else if (seal
.hash()) { // genuine file
1151 return ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
1152 AutoFileDesc
fd(cfString(fullpath
), O_RDONLY
, FileDesc::modeMissingOk
); // open optional file
1154 MakeHash
<CodeDirectory
> hasher(this->codeDirectory());
1155 hashFileData(fd
, hasher
.get());
1156 if (hasher
->verify(seal
.hash()))
1157 return; // verify good
1159 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // altered
1161 if (!seal
.optional())
1162 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceMissing
, fullpath
); // was sealed but is now missing
1164 return; // validly missing
1167 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
1170 if (version
== 1) { // version 1 ignores symlinks altogether
1171 char target
[PATH_MAX
];
1172 if (::readlink(cfString(fullpath
).c_str(), target
, sizeof(target
)) > 0)
1175 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAdded
, CFTempURL(path
, false, resourceBase()));
1178 void SecStaticCode::validateSymlinkResource(std::string fullpath
, std::string seal
, ValidationContext
&ctx
, SecCSFlags flags
)
1180 static const char* const allowedDestinations
[] = {
1185 char target
[PATH_MAX
];
1186 ssize_t len
= ::readlink(fullpath
.c_str(), target
, sizeof(target
)-1);
1188 UnixError::check(-1);
1190 std::string fulltarget
= target
;
1191 if (target
[0] != '/') {
1192 size_t lastSlash
= fullpath
.rfind('/');
1193 fulltarget
= fullpath
.substr(0, lastSlash
) + '/' + target
;
1195 if (seal
!= target
) {
1196 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, CFTempString(fullpath
));
1199 if ((mValidationFlags
& (kSecCSStrictValidate
|kSecCSRestrictSymlinks
)) == (kSecCSStrictValidate
|kSecCSRestrictSymlinks
)) {
1200 char resolved
[PATH_MAX
];
1201 if (realpath(fulltarget
.c_str(), resolved
)) {
1202 assert(resolved
[0] == '/');
1203 size_t rlen
= strlen(resolved
);
1204 if (target
[0] == '/') {
1205 // absolute symlink; only allow absolute links to system locations
1206 for (const char* const* pathp
= allowedDestinations
; *pathp
; pathp
++) {
1207 size_t dlen
= strlen(*pathp
);
1208 if (rlen
> dlen
&& strncmp(resolved
, *pathp
, dlen
) == 0)
1209 return; // target inside /System, deemed okay
1212 // everything else must be inside the bundle(s)
1213 for (const SecStaticCode
* code
= this; code
; code
= code
->mOuterScope
) {
1214 string root
= code
->mResourceScope
->root();
1215 if (strncmp(resolved
, root
.c_str(), root
.size()) == 0) {
1216 if (code
->mResourceScope
->includes(resolved
+ root
.length() + 1))
1217 return; // located in resource stack && included in envelope
1219 break; // located but excluded from envelope (deny)
1224 // if we fell through, flag a symlink error
1225 if (mTolerateErrors
.find(errSecCSInvalidSymlink
) == mTolerateErrors
.end())
1226 ctx
.reportProblem(errSecCSInvalidSymlink
, kSecCFErrorResourceAltered
, CFTempString(fullpath
));
1230 void SecStaticCode::validateNestedCode(CFURLRef path
, const ResourceSeal
&seal
, SecCSFlags flags
, bool isFramework
)
1232 CFRef
<SecRequirementRef
> req
;
1233 if (SecRequirementCreateWithString(seal
.requirement(), kSecCSDefaultFlags
, &req
.aref()))
1234 MacOSError::throwMe(errSecCSResourcesInvalid
);
1236 // recursively verify this nested code
1238 if (!(flags
& kSecCSCheckNestedCode
))
1239 flags
|= kSecCSBasicValidateOnly
;
1240 SecPointer
<SecStaticCode
> code
= new SecStaticCode(DiskRep::bestGuess(cfString(path
)));
1241 code
->initializeFromParent(*this);
1242 code
->staticValidate(flags
, SecRequirement::required(req
));
1244 if (isFramework
&& (flags
& kSecCSStrictValidate
))
1246 validateOtherVersions(path
, flags
, req
, code
);
1247 } catch (const CSError
&err
) {
1248 MacOSError::throwMe(errSecCSBadFrameworkVersion
);
1249 } catch (const MacOSError
&err
) {
1250 MacOSError::throwMe(errSecCSBadFrameworkVersion
);
1253 } catch (CSError
&err
) {
1254 if (err
.error
== errSecCSReqFailed
) {
1255 mResourcesValidContext
->reportProblem(errSecCSBadNestedCode
, kSecCFErrorResourceAltered
, path
);
1258 err
.augment(kSecCFErrorPath
, path
);
1260 } catch (const MacOSError
&err
) {
1261 if (err
.error
== errSecCSReqFailed
) {
1262 mResourcesValidContext
->reportProblem(errSecCSBadNestedCode
, kSecCFErrorResourceAltered
, path
);
1265 CSError::throwMe(err
.error
, kSecCFErrorPath
, path
);
1269 void SecStaticCode::validateOtherVersions(CFURLRef path
, SecCSFlags flags
, SecRequirementRef req
, SecStaticCode
*code
)
1271 // Find out what current points to and do not revalidate
1272 std::string mainPath
= cfStringRelease(code
->diskRep()->copyCanonicalPath());
1274 char main_path
[PATH_MAX
];
1275 bool foundTarget
= false;
1277 /* If it failed to get the target of the symlink, do not fail. It is a performance loss,
1278 not a security hole */
1279 if (realpath(mainPath
.c_str(), main_path
) != NULL
)
1282 std::ostringstream versionsPath
;
1283 versionsPath
<< cfString(path
) << "/Versions/";
1285 DirScanner
scanner(versionsPath
.str());
1287 if (scanner
.initialized()) {
1288 struct dirent
*entry
= NULL
;
1289 while ((entry
= scanner
.getNext()) != NULL
) {
1290 std::ostringstream fullPath
;
1292 if (entry
->d_type
!= DT_DIR
||
1293 strcmp(entry
->d_name
, ".") == 0 ||
1294 strcmp(entry
->d_name
, "..") == 0 ||
1295 strcmp(entry
->d_name
, "Current") == 0)
1298 fullPath
<< versionsPath
.str() << entry
->d_name
;
1300 char real_full_path
[PATH_MAX
];
1301 if (realpath(fullPath
.str().c_str(), real_full_path
) == NULL
)
1302 UnixError::check(-1);
1304 // Do case insensitive comparions because realpath() was called for both paths
1305 if (foundTarget
&& strcmp(main_path
, real_full_path
) == 0)
1308 SecPointer
<SecStaticCode
> frameworkVersion
= new SecStaticCode(DiskRep::bestGuess(real_full_path
));
1309 frameworkVersion
->initializeFromParent(*this);
1310 frameworkVersion
->staticValidate(flags
, SecRequirement::required(req
));
1317 // Test a CodeDirectory flag.
1318 // Returns false if there is no CodeDirectory.
1319 // May throw if the CodeDirectory is present but somehow invalid.
1321 bool SecStaticCode::flag(uint32_t tested
)
1323 if (const CodeDirectory
*cd
= this->codeDirectory(false))
1324 return cd
->flags
& tested
;
1331 // Retrieve the full SuperBlob containing all internal requirements.
1333 const Requirements
*SecStaticCode::internalRequirements()
1335 if (CFDataRef reqData
= component(cdRequirementsSlot
)) {
1336 const Requirements
*req
= (const Requirements
*)CFDataGetBytePtr(reqData
);
1337 if (!req
->validateBlob())
1338 MacOSError::throwMe(errSecCSReqInvalid
);
1346 // Retrieve a particular internal requirement by type.
1348 const Requirement
*SecStaticCode::internalRequirement(SecRequirementType type
)
1350 if (const Requirements
*reqs
= internalRequirements())
1351 return reqs
->find
<Requirement
>(type
);
1358 // Return the Designated Requirement (DR). This can be either explicit in the
1359 // Internal Requirements component, or implicitly generated on demand here.
1360 // Note that an explicit DR may have been implicitly generated at signing time;
1361 // we don't distinguish this case.
1363 const Requirement
*SecStaticCode::designatedRequirement()
1365 if (const Requirement
*req
= internalRequirement(kSecDesignatedRequirementType
)) {
1366 return req
; // explicit in signing data
1368 if (!mDesignatedReq
)
1369 mDesignatedReq
= defaultDesignatedRequirement();
1370 return mDesignatedReq
;
1376 // Generate the default Designated Requirement (DR) for this StaticCode.
1377 // Ignore any explicit DR it may contain.
1379 const Requirement
*SecStaticCode::defaultDesignatedRequirement()
1381 if (flag(kSecCodeSignatureAdhoc
)) {
1382 // adhoc signature: return a cdhash requirement for all architectures
1383 __block
Requirement::Maker maker
;
1384 Requirement::Maker::Chain
chain(maker
, opOr
);
1386 // insert cdhash requirement for all architectures
1388 maker
.cdhash(this->cdHash());
1389 handleOtherArchitectures(^(SecStaticCode
*subcode
) {
1390 if (CFDataRef cdhash
= subcode
->cdHash()) {
1392 maker
.cdhash(cdhash
);
1395 return maker
.make();
1397 // full signature: Gin up full context and let DRMaker do its thing
1398 validateDirectory(); // need the cert chain
1399 Requirement::Context
context(this->certificates(),
1400 this->infoDictionary(),
1401 this->entitlements(),
1403 this->codeDirectory()
1405 return DRMaker(context
).make();
1411 // Validate a SecStaticCode against the internal requirement of a particular type.
1413 void SecStaticCode::validateRequirements(SecRequirementType type
, SecStaticCode
*target
,
1414 OSStatus nullError
/* = errSecSuccess */)
1416 DTRACK(CODESIGN_EVAL_STATIC_INTREQ
, this, type
, target
, nullError
);
1417 if (const Requirement
*req
= internalRequirement(type
))
1418 target
->validateRequirement(req
, nullError
? nullError
: errSecCSReqFailed
);
1420 MacOSError::throwMe(nullError
);
1425 /* Public Key Hash for root:/C=US/O=VeriSign, Inc./OU=Class 3 Public Primary Certification Authority */
1426 static const UInt8 retryRootBytes
[] = {0x00,0xd8,0x5a,0x4c,0x25,0xc1,0x22,0xe5,0x8b,0x31,0xef,0x6d,0xba,0xf3,0xcc,0x5f,0x29,0xf1,0x0d,0x61};
1429 // Validate this StaticCode against an external Requirement
1431 bool SecStaticCode::satisfiesRequirement(const Requirement
*req
, OSStatus failure
)
1433 bool result
= false;
1435 validateDirectory();
1436 result
= req
->validates(Requirement::Context(mCertChain
, infoDictionary(), entitlements(), codeDirectory()->identifier(), codeDirectory()), failure
);
1437 if (result
== false) {
1438 /* Fix for rdar://problem/21437632: Work around untrusted root in validation chain */
1439 CFArrayRef certs
= certificates();
1440 if (!certs
|| ((int)CFArrayGetCount(certs
) < 1)) {
1443 SecCertificateRef root
= cert((int)CFArrayGetCount(certs
) - 1);
1447 CFDataRef rootHash
= SecCertificateCopyPublicKeySHA1Digest(root
);
1452 if ((CFDataGetLength(rootHash
) == sizeof(retryRootBytes
)) &&
1453 !memcmp(CFDataGetBytePtr(rootHash
), retryRootBytes
, sizeof(retryRootBytes
))) {
1454 // retry with a rebuilt certificate chain, this time evaluating anchor trust
1455 Security::Syslog::debug("Requirements validation failed: retrying");
1456 mResourcesValidated
= mValidated
= false;
1457 setValidationFlags(mValidationFlags
| kSecCSCheckTrustedAnchors
);
1459 validateDirectory();
1460 result
= req
->validates(Requirement::Context(mCertChain
, infoDictionary(), entitlements(), codeDirectory()->identifier(), codeDirectory()), failure
);
1462 CFRelease(rootHash
);
1468 void SecStaticCode::validateRequirement(const Requirement
*req
, OSStatus failure
)
1470 if (!this->satisfiesRequirement(req
, failure
))
1471 MacOSError::throwMe(failure
);
1475 // Retrieve one certificate from the cert chain.
1476 // Positive and negative indices can be used:
1477 // [ leaf, intermed-1, ..., intermed-n, anchor ]
1479 // Returns NULL if unavailable for any reason.
1481 SecCertificateRef
SecStaticCode::cert(int ix
)
1483 validateDirectory(); // need cert chain
1485 CFIndex length
= CFArrayGetCount(mCertChain
);
1488 if (ix
>= 0 && ix
< length
)
1489 return SecCertificateRef(CFArrayGetValueAtIndex(mCertChain
, ix
));
1494 CFArrayRef
SecStaticCode::certificates()
1496 validateDirectory(); // need cert chain
1502 // Gather (mostly) API-official information about this StaticCode.
1504 // This method lives in the twilight between the API and internal layers,
1505 // since it generates API objects (Sec*Refs) for return.
1507 CFDictionaryRef
SecStaticCode::signingInformation(SecCSFlags flags
)
1510 // Start with the pieces that we return even for unsigned code.
1511 // This makes Sec[Static]CodeRefs useful as API-level replacements
1512 // of our internal OSXCode objects.
1514 CFRef
<CFMutableDictionaryRef
> dict
= makeCFMutableDictionary(1,
1515 kSecCodeInfoMainExecutable
, CFTempURL(this->mainExecutablePath()).get()
1519 // If we're not signed, this is all you get
1521 if (!this->isSigned())
1522 return dict
.yield();
1525 // Add the generic attributes that we always include
1527 CFDictionaryAddValue(dict
, kSecCodeInfoIdentifier
, CFTempString(this->identifier()));
1528 CFDictionaryAddValue(dict
, kSecCodeInfoFlags
, CFTempNumber(this->codeDirectory(false)->flags
.get()));
1529 CFDictionaryAddValue(dict
, kSecCodeInfoFormat
, CFTempString(this->format()));
1530 CFDictionaryAddValue(dict
, kSecCodeInfoSource
, CFTempString(this->signatureSource()));
1531 CFDictionaryAddValue(dict
, kSecCodeInfoUnique
, this->cdHash());
1532 const CodeDirectory
* cd
= this->codeDirectory(false);
1533 CFDictionaryAddValue(dict
, kSecCodeInfoDigestAlgorithm
, CFTempNumber(cd
->hashType
));
1535 CFDictionaryAddValue(dict
, kSecCodeInfoPlatformIdentifier
, CFTempNumber(cd
->platform
));
1538 // Deliver any Info.plist only if it looks intact
1541 if (CFDictionaryRef info
= this->infoDictionary())
1542 CFDictionaryAddValue(dict
, kSecCodeInfoPList
, info
);
1543 } catch (...) { } // don't deliver Info.plist if questionable
1546 // kSecCSSigningInformation adds information about signing certificates and chains
1548 if (flags
& kSecCSSigningInformation
)
1550 if (CFArrayRef certs
= this->certificates())
1551 CFDictionaryAddValue(dict
, kSecCodeInfoCertificates
, certs
);
1552 if (CFDataRef sig
= this->signature())
1553 CFDictionaryAddValue(dict
, kSecCodeInfoCMS
, sig
);
1555 CFDictionaryAddValue(dict
, kSecCodeInfoTrust
, mTrust
);
1556 if (CFAbsoluteTime time
= this->signingTime())
1557 if (CFRef
<CFDateRef
> date
= CFDateCreate(NULL
, time
))
1558 CFDictionaryAddValue(dict
, kSecCodeInfoTime
, date
);
1559 if (CFAbsoluteTime time
= this->signingTimestamp())
1560 if (CFRef
<CFDateRef
> date
= CFDateCreate(NULL
, time
))
1561 CFDictionaryAddValue(dict
, kSecCodeInfoTimestamp
, date
);
1562 if (const char *teamID
= this->teamID())
1563 CFDictionaryAddValue(dict
, kSecCodeInfoTeamIdentifier
, CFTempString(teamID
));
1567 // kSecCSRequirementInformation adds information on requirements
1569 if (flags
& kSecCSRequirementInformation
)
1571 if (const Requirements
*reqs
= this->internalRequirements()) {
1572 CFDictionaryAddValue(dict
, kSecCodeInfoRequirements
,
1573 CFTempString(Dumper::dump(reqs
)));
1574 CFDictionaryAddValue(dict
, kSecCodeInfoRequirementData
, CFTempData(*reqs
));
1577 const Requirement
*dreq
= this->designatedRequirement();
1578 CFRef
<SecRequirementRef
> dreqRef
= (new SecRequirement(dreq
))->handle();
1579 CFDictionaryAddValue(dict
, kSecCodeInfoDesignatedRequirement
, dreqRef
);
1580 if (this->internalRequirement(kSecDesignatedRequirementType
)) { // explicit
1581 CFRef
<SecRequirementRef
> ddreqRef
= (new SecRequirement(this->defaultDesignatedRequirement(), true))->handle();
1582 CFDictionaryAddValue(dict
, kSecCodeInfoImplicitDesignatedRequirement
, ddreqRef
);
1583 } else { // implicit
1584 CFDictionaryAddValue(dict
, kSecCodeInfoImplicitDesignatedRequirement
, dreqRef
);
1589 if (CFDataRef ent
= this->component(cdEntitlementSlot
)) {
1590 CFDictionaryAddValue(dict
, kSecCodeInfoEntitlements
, ent
);
1591 if (CFDictionaryRef entdict
= this->entitlements())
1592 CFDictionaryAddValue(dict
, kSecCodeInfoEntitlementsDict
, entdict
);
1597 // kSecCSInternalInformation adds internal information meant to be for Apple internal
1598 // use (SPI), and not guaranteed to be stable. Primarily, this is data we want
1599 // to reliably transmit through the API wall so that code outside the Security.framework
1600 // can use it without having to play nasty tricks to get it.
1602 if (flags
& kSecCSInternalInformation
)
1605 CFDictionaryAddValue(dict
, kSecCodeInfoCodeDirectory
, mDir
);
1606 CFDictionaryAddValue(dict
, kSecCodeInfoCodeOffset
, CFTempNumber(mRep
->signingBase()));
1607 if (CFRef
<CFDictionaryRef
> rdict
= getDictionary(cdResourceDirSlot
, false)) // suppress validation
1608 CFDictionaryAddValue(dict
, kSecCodeInfoResourceDirectory
, rdict
);
1613 // kSecCSContentInformation adds more information about the physical layout
1614 // of the signed code. This is (only) useful for packaging or patching-oriented
1617 if (flags
& kSecCSContentInformation
)
1618 if (CFRef
<CFArrayRef
> files
= mRep
->modifiedFiles())
1619 CFDictionaryAddValue(dict
, kSecCodeInfoChangedFiles
, files
);
1621 return dict
.yield();
1626 // Resource validation contexts.
1627 // The default context simply throws a CSError, rudely terminating the operation.
1629 SecStaticCode::ValidationContext::~ValidationContext()
1632 void SecStaticCode::ValidationContext::reportProblem(OSStatus rc
, CFStringRef type
, CFTypeRef value
)
1634 CSError::throwMe(rc
, type
, value
);
1637 void SecStaticCode::CollectingContext::reportProblem(OSStatus rc
, CFStringRef type
, CFTypeRef value
)
1639 StLock
<Mutex
> _(mLock
);
1640 if (mStatus
== errSecSuccess
)
1641 mStatus
= rc
; // record first failure for eventual error return
1644 mCollection
.take(makeCFMutableDictionary());
1645 CFMutableArrayRef element
= CFMutableArrayRef(CFDictionaryGetValue(mCollection
, type
));
1647 element
= makeCFMutableArray(0);
1650 CFDictionaryAddValue(mCollection
, type
, element
);
1653 CFArrayAppendValue(element
, value
);
1657 void SecStaticCode::CollectingContext::throwMe()
1659 assert(mStatus
!= errSecSuccess
);
1660 throw CSError(mStatus
, mCollection
.retain());
1665 // Master validation driver.
1666 // This is the static validation (only) driver for the API.
1668 // SecStaticCode exposes an a la carte menu of topical validators applying
1669 // to a given object. The static validation API pulls them together reliably,
1670 // but it also adds two matrix dimensions: architecture (for "fat" Mach-O binaries)
1671 // and nested code. This function will crawl a suitable cross-section of this
1672 // validation matrix based on which options it is given, creating temporary
1673 // SecStaticCode objects on the fly to complete the task.
1674 // (The point, of course, is to do as little duplicate work as possible.)
1676 void SecStaticCode::staticValidate(SecCSFlags flags
, const SecRequirement
*req
)
1678 setValidationFlags(flags
);
1680 // initialize progress/cancellation state
1681 if (flags
& kSecCSReportProgress
)
1682 prepareProgress(estimateResourceWorkload() + 2); // +1 head, +1 tail
1684 // core components: once per architecture (if any)
1685 this->staticValidateCore(flags
, req
);
1686 if (flags
& kSecCSCheckAllArchitectures
)
1687 handleOtherArchitectures(^(SecStaticCode
* subcode
) {
1688 if (flags
& kSecCSCheckGatekeeperArchitectures
) {
1689 Universal
*fat
= subcode
->diskRep()->mainExecutableImage();
1690 assert(fat
&& fat
->narrowed()); // handleOtherArchitectures gave us a focused architecture slice
1691 Architecture arch
= fat
->bestNativeArch(); // actually, the ONLY one
1692 if ((arch
.cpuType() & ~CPU_ARCH_MASK
) == CPU_TYPE_POWERPC
)
1693 return; // irrelevant to Gatekeeper
1695 subcode
->detachedSignature(this->mDetachedSig
); // carry over explicit (but not implicit) architecture
1696 subcode
->staticValidateCore(flags
, req
);
1700 // allow monitor intervention in source validation phase
1701 reportEvent(CFSTR("prepared"), NULL
);
1703 // resources: once for all architectures
1704 if (!(flags
& kSecCSDoNotValidateResources
))
1705 this->validateResources(flags
);
1707 // perform strict validation if desired
1708 if (flags
& kSecCSStrictValidate
)
1709 mRep
->strictValidate(codeDirectory(), mTolerateErrors
);
1712 // allow monitor intervention
1713 if (CFRef
<CFTypeRef
> veto
= reportEvent(CFSTR("validated"), NULL
)) {
1714 if (CFGetTypeID(veto
) == CFNumberGetTypeID())
1715 MacOSError::throwMe(cfNumber
<OSStatus
>(veto
.as
<CFNumberRef
>()));
1717 MacOSError::throwMe(errSecCSBadCallbackValue
);
1721 void SecStaticCode::staticValidateCore(SecCSFlags flags
, const SecRequirement
*req
)
1724 this->validateNonResourceComponents(); // also validates the CodeDirectory
1725 if (!(flags
& kSecCSDoNotValidateExecutable
))
1726 this->validateExecutable();
1728 this->validateRequirement(req
->requirement(), errSecCSReqFailed
);
1729 } catch (CSError
&err
) {
1730 if (Universal
*fat
= this->diskRep()->mainExecutableImage()) // Mach-O
1731 if (MachO
*mach
= fat
->architecture()) {
1732 err
.augment(kSecCFErrorArchitecture
, CFTempString(mach
->architecture().displayName()));
1736 } catch (const MacOSError
&err
) {
1737 // add architecture information if we can get it
1738 if (Universal
*fat
= this->diskRep()->mainExecutableImage())
1739 if (MachO
*mach
= fat
->architecture()) {
1740 CFTempString
arch(mach
->architecture().displayName());
1742 CSError::throwMe(err
.error
, kSecCFErrorArchitecture
, arch
);
1750 // A helper that generates SecStaticCode objects for all but the primary architecture
1751 // of a fat binary and calls a block on them.
1752 // If there's only one architecture (or this is an architecture-agnostic code),
1753 // nothing happens quickly.
1755 void SecStaticCode::handleOtherArchitectures(void (^handle
)(SecStaticCode
* other
))
1757 if (Universal
*fat
= this->diskRep()->mainExecutableImage()) {
1758 Universal::Architectures architectures
;
1759 fat
->architectures(architectures
);
1760 if (architectures
.size() > 1) {
1761 DiskRep::Context ctx
;
1762 size_t activeOffset
= fat
->archOffset();
1763 for (Universal::Architectures::const_iterator arch
= architectures
.begin(); arch
!= architectures
.end(); ++arch
) {
1764 ctx
.offset
= fat
->archOffset(*arch
);
1765 if (ctx
.offset
> SIZE_MAX
)
1766 MacOSError::throwMe(errSecCSInternalError
);
1767 ctx
.size
= fat
->lengthOfSlice((size_t)ctx
.offset
);
1768 if (ctx
.offset
!= activeOffset
) { // inactive architecture; check it
1769 SecPointer
<SecStaticCode
> subcode
= new SecStaticCode(DiskRep::bestGuess(this->mainExecutablePath(), &ctx
));
1770 subcode
->detachedSignature(this->mDetachedSig
); // carry over explicit (but not implicit) detached signature
1771 if (this->teamID() == NULL
|| subcode
->teamID() == NULL
) {
1772 if (this->teamID() != subcode
->teamID())
1773 MacOSError::throwMe(errSecCSSignatureInvalid
);
1774 } else if (strcmp(this->teamID(), subcode
->teamID()) != 0)
1775 MacOSError::throwMe(errSecCSSignatureInvalid
);
1784 // A method that takes a certificate chain (certs) and evaluates
1785 // if it is a Mac or IPhone developer cert, an app store distribution cert,
1786 // or a developer ID
1788 bool SecStaticCode::isAppleDeveloperCert(CFArrayRef certs
)
1790 static const std::string appleDeveloperRequirement
= "(" + std::string(WWDRRequirement
) + ") or (" + MACWWDRRequirement
+ ") or (" + developerID
+ ") or (" + distributionCertificate
+ ") or (" + iPhoneDistributionCert
+ ")";
1791 SecPointer
<SecRequirement
> req
= new SecRequirement(parseRequirement(appleDeveloperRequirement
), true);
1792 Requirement::Context
ctx(certs
, NULL
, NULL
, "", NULL
);
1794 return req
->requirement()->validates(ctx
);
1797 } // end namespace CodeSigning
1798 } // end namespace Security