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 "csutilities.h"
38 #include "dirscanner.h"
39 #include <CoreFoundation/CFURLAccess.h>
40 #include <Security/SecPolicyPriv.h>
41 #include <Security/SecTrustPriv.h>
42 #include <Security/SecCertificatePriv.h>
43 #include <Security/CMSPrivate.h>
44 #include <Security/SecCmsContentInfo.h>
45 #include <Security/SecCmsSignerInfo.h>
46 #include <Security/SecCmsSignedData.h>
47 #include <Security/cssmapplePriv.h>
48 #include <security_utilities/unix++.h>
49 #include <security_utilities/cfmunge.h>
50 #include <Security/CMSDecoder.h>
51 #include <security_utilities/logging.h>
57 namespace CodeSigning
{
59 using namespace UnixPlusPlus
;
61 // A requirement representing a Mac or iOS dev cert, a Mac or iOS distribution cert, or a developer ID
62 static const char WWDRRequirement
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.2] exists";
63 static const char MACWWDRRequirement
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.12] exists";
64 static const char developerID
[] = "anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists"
65 " and certificate leaf[field.1.2.840.113635.100.6.1.13] exists";
66 static const char distributionCertificate
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.7] exists";
67 static const char iPhoneDistributionCert
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.4] exists";
70 // Map a component slot number to a suitable error code for a failure
72 static inline OSStatus
errorForSlot(CodeDirectory::SpecialSlot slot
)
76 return errSecCSInfoPlistFailed
;
77 case cdResourceDirSlot
:
78 return errSecCSResourceDirectoryFailed
;
80 return errSecCSSignatureFailed
;
86 // Construct a SecStaticCode object given a disk representation object
88 SecStaticCode::SecStaticCode(DiskRep
*rep
)
90 mValidated(false), mExecutableValidated(false), mResourcesValidated(false), mResourcesValidContext(NULL
),
91 mDesignatedReq(NULL
), mGotResourceBase(false), mMonitor(NULL
), mEvalDetails(NULL
)
93 CODESIGN_STATIC_CREATE(this, rep
);
94 CFRef
<CFDataRef
> codeDirectory
= rep
->codeDirectory();
95 if (codeDirectory
&& CFDataGetLength(codeDirectory
) <= 0)
96 MacOSError::throwMe(errSecCSSignatureInvalid
);
97 checkForSystemSignature();
102 // Clean up a SecStaticCode object
104 SecStaticCode::~SecStaticCode() throw()
106 ::free(const_cast<Requirement
*>(mDesignatedReq
));
107 if (mResourcesValidContext
)
108 delete mResourcesValidContext
;
115 // CF-level comparison of SecStaticCode objects compares CodeDirectory hashes if signed,
116 // and falls back on comparing canonical paths if (both are) not.
118 bool SecStaticCode::equal(SecCFObject
&secOther
)
120 SecStaticCode
*other
= static_cast<SecStaticCode
*>(&secOther
);
121 CFDataRef mine
= this->cdHash();
122 CFDataRef his
= other
->cdHash();
124 return mine
&& his
&& CFEqual(mine
, his
);
126 return CFEqual(CFRef
<CFURLRef
>(this->copyCanonicalPath()), CFRef
<CFURLRef
>(other
->copyCanonicalPath()));
129 CFHashCode
SecStaticCode::hash()
131 if (CFDataRef h
= this->cdHash())
134 return CFHash(CFRef
<CFURLRef
>(this->copyCanonicalPath()));
139 // Invoke a stage monitor if registered
141 CFTypeRef
SecStaticCode::reportEvent(CFStringRef stage
, CFDictionaryRef info
)
144 return mMonitor(this->handle(false), stage
, info
);
149 void SecStaticCode::prepareProgress(unsigned int workload
)
152 StLock
<Mutex
> _(mCancelLock
);
153 mCancelPending
= false; // not cancelled
155 if (mValidationFlags
& kSecCSReportProgress
) {
156 mCurrentWork
= 0; // nothing done yet
157 mTotalWork
= workload
; // totally fake - we don't know how many files we'll get to chew
161 void SecStaticCode::reportProgress(unsigned amount
/* = 1 */)
163 if (mMonitor
&& (mValidationFlags
& kSecCSReportProgress
)) {
165 // if cancellation is pending, abort now
166 StLock
<Mutex
> _(mCancelLock
);
168 MacOSError::throwMe(errSecCSCancelled
);
170 // update progress and report
171 mCurrentWork
+= amount
;
172 mMonitor(this->handle(false), CFSTR("progress"), CFTemp
<CFDictionaryRef
>("{current=%d,total=%d}", mCurrentWork
, mTotalWork
));
178 // Set validation conditions for fine-tuning legacy tolerance
180 static void addError(CFTypeRef cfError
, void* context
)
182 if (CFGetTypeID(cfError
) == CFNumberGetTypeID()) {
184 CFNumberGetValue(CFNumberRef(cfError
), kCFNumberSInt64Type
, (void*)&error
);
185 MacOSErrorSet
* errors
= (MacOSErrorSet
*)context
;
186 errors
->insert(OSStatus(error
));
190 void SecStaticCode::setValidationModifiers(CFDictionaryRef conditions
)
193 CFDictionary
source(conditions
, errSecCSDbCorrupt
);
194 mAllowOmissions
= source
.get
<CFArrayRef
>("omissions");
195 if (CFArrayRef errors
= source
.get
<CFArrayRef
>("errors"))
196 CFArrayApplyFunction(errors
, CFRangeMake(0, CFArrayGetCount(errors
)), addError
, &this->mTolerateErrors
);
202 // Request cancellation of a validation in progress.
203 // We do this by posting an abort flag that is checked periodically.
205 void SecStaticCode::cancelValidation()
207 StLock
<Mutex
> _(mCancelLock
);
208 if (!(mValidationFlags
& kSecCSReportProgress
)) // not using progress reporting; cancel won't make it through
209 MacOSError::throwMe(errSecCSInvalidFlags
);
210 mCancelPending
= true;
215 // Attach a detached signature.
217 void SecStaticCode::detachedSignature(CFDataRef sigData
)
220 mDetachedSig
= sigData
;
221 mRep
= new DetachedRep(sigData
, mRep
->base(), "explicit detached");
222 CODESIGN_STATIC_ATTACH_EXPLICIT(this, mRep
);
226 CODESIGN_STATIC_ATTACH_EXPLICIT(this, NULL
);
232 // Consult the system detached signature database to see if it contains
233 // a detached signature for this StaticCode. If it does, fetch and attach it.
234 // We do this only if the code has no signature already attached.
236 void SecStaticCode::checkForSystemSignature()
238 if (!this->isSigned()) {
239 SignatureDatabase db
;
242 if (RefPointer
<DiskRep
> dsig
= db
.findCode(mRep
)) {
243 CODESIGN_STATIC_ATTACH_SYSTEM(this, dsig
);
253 // Return a descriptive string identifying the source of the code signature
255 string
SecStaticCode::signatureSource()
259 if (DetachedRep
*rep
= dynamic_cast<DetachedRep
*>(mRep
.get()))
260 return rep
->source();
266 // Do ::required, but convert incoming SecCodeRefs to their SecStaticCodeRefs
269 SecStaticCode
*SecStaticCode::requiredStatic(SecStaticCodeRef ref
)
271 SecCFObject
*object
= SecCFObject::required(ref
, errSecCSInvalidObjectRef
);
272 if (SecStaticCode
*scode
= dynamic_cast<SecStaticCode
*>(object
))
274 else if (SecCode
*code
= dynamic_cast<SecCode
*>(object
))
275 return code
->staticCode();
276 else // neither (a SecSomethingElse)
277 MacOSError::throwMe(errSecCSInvalidObjectRef
);
280 SecCode
*SecStaticCode::optionalDynamic(SecStaticCodeRef ref
)
282 SecCFObject
*object
= SecCFObject::required(ref
, errSecCSInvalidObjectRef
);
283 if (dynamic_cast<SecStaticCode
*>(object
))
285 else if (SecCode
*code
= dynamic_cast<SecCode
*>(object
))
287 else // neither (a SecSomethingElse)
288 MacOSError::throwMe(errSecCSInvalidObjectRef
);
293 // Void all cached validity data.
295 // We also throw out cached components, because the new signature data may have
296 // a different idea of what components should be present. We could reconcile the
297 // cached data instead, if performance seems to be impacted.
299 void SecStaticCode::resetValidity()
301 CODESIGN_EVAL_STATIC_RESET(this);
303 mExecutableValidated
= mResourcesValidated
= false;
304 if (mResourcesValidContext
) {
305 delete mResourcesValidContext
;
306 mResourcesValidContext
= NULL
;
310 for (unsigned n
= 0; n
< cdSlotCount
; n
++)
313 mEntitlements
= NULL
;
314 mResourceDict
= NULL
;
315 mDesignatedReq
= NULL
;
317 mGotResourceBase
= false;
323 // we may just have updated the system database, so check again
324 checkForSystemSignature();
329 // Retrieve a sealed component by special slot index.
330 // If the CodeDirectory has already been validated, validate against that.
331 // Otherwise, retrieve the component without validation (but cache it). Validation
332 // will go through the cache and validate all cached components.
334 CFDataRef
SecStaticCode::component(CodeDirectory::SpecialSlot slot
, OSStatus fail
/* = errSecCSSignatureFailed */)
336 assert(slot
<= cdSlotMax
);
338 CFRef
<CFDataRef
> &cache
= mCache
[slot
];
340 if (CFRef
<CFDataRef
> data
= mRep
->component(slot
)) {
341 if (validated()) // if the directory has been validated...
342 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data
), // ... and it's no good
343 CFDataGetLength(data
), -slot
))
344 MacOSError::throwMe(errorForSlot(slot
)); // ... then bail
345 cache
= data
; // it's okay, cache it
346 } else { // absent, mark so
347 if (validated()) // if directory has been validated...
348 if (codeDirectory()->slotIsPresent(-slot
)) // ... and the slot is NOT missing
349 MacOSError::throwMe(errorForSlot(slot
)); // was supposed to be there
350 cache
= CFDataRef(kCFNull
); // white lie
353 return (cache
== CFDataRef(kCFNull
)) ? NULL
: cache
.get();
358 // Get the CodeDirectory.
359 // Throws (if check==true) or returns NULL (check==false) if there is none.
360 // Always throws if the CodeDirectory exists but is invalid.
361 // NEVER validates against the signature.
363 const CodeDirectory
*SecStaticCode::codeDirectory(bool check
/* = true */)
366 if (mDir
.take(mRep
->codeDirectory())) {
367 const CodeDirectory
*dir
= reinterpret_cast<const CodeDirectory
*>(CFDataGetBytePtr(mDir
));
368 dir
->checkIntegrity();
372 return reinterpret_cast<const CodeDirectory
*>(CFDataGetBytePtr(mDir
));
374 MacOSError::throwMe(errSecCSUnsigned
);
380 // Get the hash of the CodeDirectory.
381 // Returns NULL if there is none.
383 CFDataRef
SecStaticCode::cdHash()
386 if (const CodeDirectory
*cd
= codeDirectory(false)) {
388 hash(cd
, cd
->length());
391 mCDHash
.take(makeCFData(digest
, sizeof(digest
)));
392 CODESIGN_STATIC_CDHASH(this, digest
, sizeof(digest
));
400 // Return the CMS signature blob; NULL if none found.
402 CFDataRef
SecStaticCode::signature()
405 mSignature
.take(mRep
->signature());
408 MacOSError::throwMe(errSecCSUnsigned
);
413 // Verify the signature on the CodeDirectory.
414 // If this succeeds (doesn't throw), the CodeDirectory is statically trustworthy.
415 // Any outcome (successful or not) is cached for the lifetime of the StaticCode.
417 void SecStaticCode::validateDirectory()
419 // echo previous outcome, if any
420 // track revocation separately, as it may not have been checked
421 // during the initial validation
422 if (!validated() || ((mValidationFlags
& kSecCSEnforceRevocationChecks
) && !revocationChecked()))
424 // perform validation (or die trying)
425 CODESIGN_EVAL_STATIC_DIRECTORY(this);
426 mValidationExpired
= verifySignature();
427 if (mValidationFlags
& kSecCSEnforceRevocationChecks
)
428 mRevocationChecked
= true;
430 for (CodeDirectory::SpecialSlot slot
= codeDirectory()->maxSpecialSlot(); slot
>= 1; --slot
)
431 if (mCache
[slot
]) // if we already loaded that resource...
432 validateComponent(slot
, errorForSlot(slot
)); // ... then check it now
433 mValidated
= true; // we've done the deed...
434 mValidationResult
= errSecSuccess
; // ... and it was good
435 } catch (const CommonError
&err
) {
437 mValidationResult
= err
.osStatus();
440 secdebug("staticCode", "%p validation threw non-common exception", this);
442 mValidationResult
= errSecCSInternalError
;
446 if (mValidationResult
== errSecSuccess
) {
447 if (mValidationExpired
)
448 if ((mValidationFlags
& kSecCSConsiderExpiration
)
449 || (codeDirectory()->flags
& kSecCodeSignatureForceExpiration
))
450 MacOSError::throwMe(CSSMERR_TP_CERT_EXPIRED
);
452 MacOSError::throwMe(mValidationResult
);
457 // Load and validate the CodeDirectory and all components *except* those related to the resource envelope.
458 // Those latter components are checked by validateResources().
460 void SecStaticCode::validateNonResourceComponents()
462 this->validateDirectory();
463 for (CodeDirectory::SpecialSlot slot
= codeDirectory()->maxSpecialSlot(); slot
>= 1; --slot
)
465 case cdResourceDirSlot
: // validated by validateResources
468 this->component(slot
); // loads and validates
475 // Get the (signed) signing date from the code signature.
476 // Sadly, we need to validate the signature to get the date (as a side benefit).
477 // This means that you can't get the signing time for invalidly signed code.
479 // We could run the decoder "almost to" verification to avoid this, but there seems
480 // little practical point to such a duplication of effort.
482 CFAbsoluteTime
SecStaticCode::signingTime()
488 CFAbsoluteTime
SecStaticCode::signingTimestamp()
491 return mSigningTimestamp
;
496 // Verify the CMS signature on the CodeDirectory.
497 // This performs the cryptographic tango. It returns if the signature is valid,
498 // or throws if it is not. As a side effect, a successful return sets up the
499 // cached certificate chain for future use.
500 // Returns true if the signature is expired (the X.509 sense), false if it's not.
501 // Expiration is fatal (throws) if a secure timestamp is included, but not otherwise.
503 bool SecStaticCode::verifySignature()
505 // ad-hoc signed code is considered validly signed by definition
506 if (flag(kSecCodeSignatureAdhoc
)) {
507 CODESIGN_EVAL_STATIC_SIGNATURE_ADHOC(this);
511 DTRACK(CODESIGN_EVAL_STATIC_SIGNATURE
, this, (char*)this->mainExecutablePath().c_str());
513 // decode CMS and extract SecTrust for verification
514 CFRef
<CMSDecoderRef
> cms
;
515 MacOSError::check(CMSDecoderCreate(&cms
.aref())); // create decoder
516 CFDataRef sig
= this->signature();
517 MacOSError::check(CMSDecoderUpdateMessage(cms
, CFDataGetBytePtr(sig
), CFDataGetLength(sig
)));
518 this->codeDirectory(); // load CodeDirectory (sets mDir)
519 MacOSError::check(CMSDecoderSetDetachedContent(cms
, mDir
));
520 MacOSError::check(CMSDecoderFinalizeMessage(cms
));
521 MacOSError::check(CMSDecoderSetSearchKeychain(cms
, cfEmptyArray()));
522 CFRef
<CFArrayRef
> vf_policies
= verificationPolicies();
523 CFRef
<CFArrayRef
> ts_policies
= SecPolicyCreateAppleTimeStampingAndRevocationPolicies(vf_policies
);
524 CMSSignerStatus status
;
525 MacOSError::check(CMSDecoderCopySignerStatus(cms
, 0, vf_policies
,
526 false, &status
, &mTrust
.aref(), NULL
));
528 if (status
!= kCMSSignerValid
)
529 MacOSError::throwMe(errSecCSSignatureFailed
);
531 // internal signing time (as specified by the signer; optional)
532 mSigningTime
= 0; // "not present" marker (nobody could code sign on Jan 1, 2001 :-)
533 switch (OSStatus rc
= CMSDecoderCopySignerSigningTime(cms
, 0, &mSigningTime
)) {
535 case errSecSigningTimeMissing
:
538 MacOSError::throwMe(rc
);
541 // certified signing time (as specified by a TSA; optional)
542 mSigningTimestamp
= 0;
543 switch (OSStatus rc
= CMSDecoderCopySignerTimestampWithPolicy(cms
, ts_policies
, 0, &mSigningTimestamp
)) {
545 case errSecTimestampMissing
:
548 MacOSError::throwMe(rc
);
551 // set up the environment for SecTrust
552 if (mValidationFlags
& kSecCSNoNetworkAccess
) {
553 MacOSError::check(SecTrustSetNetworkFetchAllowed(mTrust
,false)); // no network?
555 MacOSError::check(SecTrustSetAnchorCertificates(mTrust
, cfEmptyArray())); // no anchors
556 MacOSError::check(SecTrustSetKeychains(mTrust
, cfEmptyArray())); // no keychains
557 CSSM_APPLE_TP_ACTION_DATA actionData
= {
558 CSSM_APPLE_TP_ACTION_VERSION
, // version of data structure
559 CSSM_TP_ACTION_IMPLICIT_ANCHORS
// action flags
562 for (;;) { // at most twice
563 MacOSError::check(SecTrustSetParameters(mTrust
,
564 CSSM_TP_ACTION_DEFAULT
, CFTempData(&actionData
, sizeof(actionData
))));
566 // evaluate trust and extract results
567 SecTrustResultType trustResult
;
568 MacOSError::check(SecTrustEvaluate(mTrust
, &trustResult
));
569 MacOSError::check(SecTrustGetResult(mTrust
, &trustResult
, &mCertChain
.aref(), &mEvalDetails
));
571 // if this is an Apple developer cert....
572 if (teamID() && SecStaticCode::isAppleDeveloperCert(mCertChain
)) {
573 CFRef
<CFStringRef
> teamIDFromCert
;
574 if (CFArrayGetCount(mCertChain
) > 0) {
575 /* Note that SecCertificateCopySubjectComponent sets the out paramater to NULL if there is no field present */
576 MacOSError::check(SecCertificateCopySubjectComponent((SecCertificateRef
)CFArrayGetValueAtIndex(mCertChain
, Requirement::leafCert
),
577 &CSSMOID_OrganizationalUnitName
,
578 &teamIDFromCert
.aref()));
580 if (teamIDFromCert
) {
581 CFRef
<CFStringRef
> teamIDFromCD
= CFStringCreateWithCString(NULL
, teamID(), kCFStringEncodingUTF8
);
583 MacOSError::throwMe(errSecCSInternalError
);
586 if (CFStringCompare(teamIDFromCert
, teamIDFromCD
, 0) != kCFCompareEqualTo
) {
587 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());
588 MacOSError::throwMe(errSecCSSignatureInvalid
);
594 CODESIGN_EVAL_STATIC_SIGNATURE_RESULT(this, trustResult
, mCertChain
? (int)CFArrayGetCount(mCertChain
) : 0);
595 switch (trustResult
) {
596 case kSecTrustResultProceed
:
597 case kSecTrustResultUnspecified
:
599 case kSecTrustResultDeny
:
600 MacOSError::throwMe(CSSMERR_APPLETP_TRUST_SETTING_DENY
); // user reject
601 case kSecTrustResultInvalid
:
602 assert(false); // should never happen
603 MacOSError::throwMe(CSSMERR_TP_NOT_TRUSTED
);
607 MacOSError::check(SecTrustGetCssmResultCode(mTrust
, &result
));
608 // if we have a valid timestamp, CMS validates against (that) signing time and all is well.
609 // If we don't have one, may validate against *now*, and must be able to tolerate expiration.
610 if (mSigningTimestamp
== 0) // no timestamp available
611 if (((result
== CSSMERR_TP_CERT_EXPIRED
) || (result
== CSSMERR_TP_CERT_NOT_VALID_YET
))
612 && !(actionData
.ActionFlags
& CSSM_TP_ACTION_ALLOW_EXPIRED
)) {
613 CODESIGN_EVAL_STATIC_SIGNATURE_EXPIRED(this);
614 actionData
.ActionFlags
|= CSSM_TP_ACTION_ALLOW_EXPIRED
; // (this also allows postdated certs)
615 continue; // retry validation while tolerating expiration
617 MacOSError::throwMe(result
);
621 if (mSigningTimestamp
) {
622 CFIndex rootix
= CFArrayGetCount(mCertChain
);
623 if (SecCertificateRef mainRoot
= SecCertificateRef(CFArrayGetValueAtIndex(mCertChain
, rootix
-1)))
624 if (isAppleCA(mainRoot
)) {
625 // impose policy: if the signature itself draws to Apple, then so must the timestamp signature
626 CFRef
<CFArrayRef
> tsCerts
;
627 MacOSError::check(CMSDecoderCopySignerTimestampCertificates(cms
, 0, &tsCerts
.aref()));
628 CFIndex tsn
= CFArrayGetCount(tsCerts
);
629 bool good
= tsn
> 0 && isAppleCA(SecCertificateRef(CFArrayGetValueAtIndex(tsCerts
, tsn
-1)));
631 MacOSError::throwMe(CSSMERR_TP_NOT_TRUSTED
);
635 return actionData
.ActionFlags
& CSSM_TP_ACTION_ALLOW_EXPIRED
;
641 // Return the TP policy used for signature verification.
642 // This may be a simple SecPolicyRef or a CFArray of policies.
643 // The caller owns the return value.
645 static SecPolicyRef
makeCRLPolicy()
647 CFRef
<SecPolicyRef
> policy
;
648 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_REVOCATION_CRL
, &policy
.aref()));
649 CSSM_APPLE_TP_CRL_OPTIONS options
;
650 memset(&options
, 0, sizeof(options
));
651 options
.Version
= CSSM_APPLE_TP_CRL_OPTS_VERSION
;
652 options
.CrlFlags
= CSSM_TP_ACTION_FETCH_CRL_FROM_NET
| CSSM_TP_ACTION_CRL_SUFFICIENT
;
653 CSSM_DATA optData
= { sizeof(options
), (uint8
*)&options
};
654 MacOSError::check(SecPolicySetValue(policy
, &optData
));
655 return policy
.yield();
658 static SecPolicyRef
makeOCSPPolicy()
660 CFRef
<SecPolicyRef
> policy
;
661 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_REVOCATION_OCSP
, &policy
.aref()));
662 CSSM_APPLE_TP_OCSP_OPTIONS options
;
663 memset(&options
, 0, sizeof(options
));
664 options
.Version
= CSSM_APPLE_TP_OCSP_OPTS_VERSION
;
665 options
.Flags
= CSSM_TP_ACTION_OCSP_SUFFICIENT
;
666 CSSM_DATA optData
= { sizeof(options
), (uint8
*)&options
};
667 MacOSError::check(SecPolicySetValue(policy
, &optData
));
668 return policy
.yield();
671 CFArrayRef
SecStaticCode::verificationPolicies()
673 CFRef
<SecPolicyRef
> core
;
674 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3
,
675 &CSSMOID_APPLE_TP_CODE_SIGNING
, &core
.aref()));
676 if (mValidationFlags
& kSecCSNoNetworkAccess
) {
677 // Skips all revocation since they require network connectivity
678 // therefore annihilates kSecCSEnforceRevocationChecks if present
679 CFRef
<SecPolicyRef
> no_revoc
= SecPolicyCreateRevocation(kSecRevocationNetworkAccessDisabled
);
680 return makeCFArray(2, core
.get(), no_revoc
.get());
682 else if (mValidationFlags
& kSecCSEnforceRevocationChecks
) {
683 // Add CRL and OCSPPolicies
684 CFRef
<SecPolicyRef
> crl
= makeCRLPolicy();
685 CFRef
<SecPolicyRef
> ocsp
= makeOCSPPolicy();
686 return makeCFArray(3, core
.get(), crl
.get(), ocsp
.get());
688 return makeCFArray(1, core
.get());
694 // Validate a particular sealed, cached resource against its (special) CodeDirectory slot.
695 // The resource must already have been placed in the cache.
696 // This does NOT perform basic validation.
698 void SecStaticCode::validateComponent(CodeDirectory::SpecialSlot slot
, OSStatus fail
/* = errSecCSSignatureFailed */)
700 assert(slot
<= cdSlotMax
);
701 CFDataRef data
= mCache
[slot
];
702 assert(data
); // must be cached
703 if (data
== CFDataRef(kCFNull
)) {
704 if (codeDirectory()->slotIsPresent(-slot
)) // was supposed to be there...
705 MacOSError::throwMe(fail
); // ... and is missing
707 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data
), CFDataGetLength(data
), -slot
))
708 MacOSError::throwMe(fail
);
714 // Perform static validation of the main executable.
715 // This reads the main executable from disk and validates it against the
716 // CodeDirectory code slot array.
717 // Note that this is NOT an in-memory validation, and is thus potentially
718 // subject to timing attacks.
720 void SecStaticCode::validateExecutable()
722 if (!validatedExecutable()) {
724 DTRACK(CODESIGN_EVAL_STATIC_EXECUTABLE
, this,
725 (char*)this->mainExecutablePath().c_str(), codeDirectory()->nCodeSlots
);
726 const CodeDirectory
*cd
= this->codeDirectory();
728 MacOSError::throwMe(errSecCSUnsigned
);
729 AutoFileDesc
fd(mainExecutablePath(), O_RDONLY
);
730 fd
.fcntl(F_NOCACHE
, true); // turn off page caching (one-pass)
731 if (Universal
*fat
= mRep
->mainExecutableImage())
732 fd
.seek(fat
->archOffset());
733 size_t pageSize
= cd
->pageSize
? (1 << cd
->pageSize
) : 0;
734 size_t remaining
= cd
->codeLimit
;
735 for (uint32_t slot
= 0; slot
< cd
->nCodeSlots
; ++slot
) {
736 size_t size
= min(remaining
, pageSize
);
737 if (!cd
->validateSlot(fd
, size
, slot
)) {
738 CODESIGN_EVAL_STATIC_EXECUTABLE_FAIL(this, (int)slot
);
739 MacOSError::throwMe(errSecCSSignatureFailed
);
743 mExecutableValidated
= true;
744 mExecutableValidResult
= errSecSuccess
;
745 } catch (const CommonError
&err
) {
746 mExecutableValidated
= true;
747 mExecutableValidResult
= err
.osStatus();
750 secdebug("staticCode", "%p executable validation threw non-common exception", this);
751 mExecutableValidated
= true;
752 mExecutableValidResult
= errSecCSInternalError
;
756 assert(validatedExecutable());
757 if (mExecutableValidResult
!= errSecSuccess
)
758 MacOSError::throwMe(mExecutableValidResult
);
763 // Perform static validation of sealed resources and nested code.
765 // This performs a whole-code static resource scan and effectively
766 // computes a concordance between what's on disk and what's in the ResourceDirectory.
767 // Any unsanctioned difference causes an error.
769 unsigned SecStaticCode::estimateResourceWorkload()
771 // workload estimate = number of sealed files
772 CFDictionaryRef sealedResources
= resourceDictionary();
773 CFDictionaryRef files
= cfget
<CFDictionaryRef
>(sealedResources
, "files2");
775 files
= cfget
<CFDictionaryRef
>(sealedResources
, "files");
776 return files
? unsigned(CFDictionaryGetCount(files
)) : 0;
779 void SecStaticCode::validateResources(SecCSFlags flags
)
781 // do we have a superset of this requested validation cached?
783 if (mResourcesValidated
) { // have cached outcome
784 if (!(flags
& kSecCSCheckNestedCode
) || mResourcesDeep
) // was deep or need no deep scan
790 CFDictionaryRef sealedResources
= resourceDictionary();
791 if (this->resourceBase()) // disk has resources
793 /* go to work below */;
795 MacOSError::throwMe(errSecCSResourcesNotFound
);
796 else // disk has no resources
798 MacOSError::throwMe(errSecCSResourcesNotFound
);
800 return; // no resources, not sealed - fine (no work)
802 // found resources, and they are sealed
803 DTRACK(CODESIGN_EVAL_STATIC_RESOURCES
, this,
804 (char*)this->mainExecutablePath().c_str(), 0);
806 // scan through the resources on disk, checking each against the resourceDirectory
807 if (mValidationFlags
& kSecCSFullReport
)
808 mResourcesValidContext
= new CollectingContext(*this); // collect all failures in here
810 mResourcesValidContext
= new ValidationContext(*this); // simple bug-out on first error
812 CFDictionaryRef rules
;
813 CFDictionaryRef files
;
815 if (CFDictionaryGetValue(sealedResources
, CFSTR("files2"))) { // have V2 signature
816 rules
= cfget
<CFDictionaryRef
>(sealedResources
, "rules2");
817 files
= cfget
<CFDictionaryRef
>(sealedResources
, "files2");
819 } else { // only V1 available
820 rules
= cfget
<CFDictionaryRef
>(sealedResources
, "rules");
821 files
= cfget
<CFDictionaryRef
>(sealedResources
, "files");
824 if (!rules
|| !files
)
825 MacOSError::throwMe(errSecCSResourcesInvalid
);
826 // check for weak resource rules
827 bool strict
= flags
& kSecCSStrictValidate
;
829 if (hasWeakResourceRules(rules
, version
, mAllowOmissions
))
830 if (mTolerateErrors
.find(errSecCSWeakResourceRules
) == mTolerateErrors
.end())
831 MacOSError::throwMe(errSecCSWeakResourceRules
);
833 if (mTolerateErrors
.find(errSecCSWeakResourceEnvelope
) == mTolerateErrors
.end())
834 MacOSError::throwMe(errSecCSWeakResourceEnvelope
);
836 __block CFRef
<CFMutableDictionaryRef
> resourceMap
= makeCFMutableDictionary(files
);
837 string base
= cfString(this->resourceBase());
838 ResourceBuilder
resources(base
, base
, rules
, codeDirectory()->hashType
, strict
, mTolerateErrors
);
839 diskRep()->adjustResources(resources
);
840 resources
.scan(^(FTSENT
*ent
, uint32_t ruleFlags
, const char *relpath
, ResourceBuilder::Rule
*rule
) {
841 validateResource(files
, relpath
, ent
->fts_info
== FTS_SL
, *mResourcesValidContext
, flags
, version
);
843 CFDictionaryRemoveValue(resourceMap
, CFTempString(relpath
));
846 unsigned leftovers
= unsigned(CFDictionaryGetCount(resourceMap
));
848 secdebug("staticCode", "%d sealed resource(s) not found in code", int(leftovers
));
849 CFDictionaryApplyFunction(resourceMap
, SecStaticCode::checkOptionalResource
, mResourcesValidContext
);
852 // now check for any errors found in the reporting context
853 mResourcesValidated
= true;
854 mResourcesDeep
= flags
& kSecCSCheckNestedCode
;
855 if (mResourcesValidContext
->osStatus() != errSecSuccess
)
856 mResourcesValidContext
->throwMe();
857 } catch (const CommonError
&err
) {
858 mResourcesValidated
= true;
859 mResourcesDeep
= flags
& kSecCSCheckNestedCode
;
860 mResourcesValidResult
= err
.osStatus();
863 secdebug("staticCode", "%p executable validation threw non-common exception", this);
864 mResourcesValidated
= true;
865 mResourcesDeep
= flags
& kSecCSCheckNestedCode
;
866 mResourcesValidResult
= errSecCSInternalError
;
870 assert(validatedResources());
871 if (mResourcesValidResult
)
872 MacOSError::throwMe(mResourcesValidResult
);
873 if (mResourcesValidContext
->osStatus() != errSecSuccess
)
874 mResourcesValidContext
->throwMe();
878 void SecStaticCode::checkOptionalResource(CFTypeRef key
, CFTypeRef value
, void *context
)
880 ValidationContext
*ctx
= static_cast<ValidationContext
*>(context
);
881 ResourceSeal
seal(value
);
882 if (!seal
.optional()) {
883 if (key
&& CFGetTypeID(key
) == CFStringGetTypeID()) {
884 CFTempURL
tempURL(CFStringRef(key
), false, ctx
->code
.resourceBase());
885 if (!tempURL
.get()) {
886 ctx
->reportProblem(errSecCSBadDictionaryFormat
, kSecCFErrorResourceSeal
, key
);
888 ctx
->reportProblem(errSecCSBadResource
, kSecCFErrorResourceMissing
, tempURL
);
891 ctx
->reportProblem(errSecCSBadResource
, kSecCFErrorResourceSeal
, key
);
897 static bool isOmitRule(CFTypeRef value
)
899 if (CFGetTypeID(value
) == CFBooleanGetTypeID())
900 return value
== kCFBooleanFalse
;
901 CFDictionary
rule(value
, errSecCSResourceRulesInvalid
);
902 return rule
.get
<CFBooleanRef
>("omit") == kCFBooleanTrue
;
905 bool SecStaticCode::hasWeakResourceRules(CFDictionaryRef rulesDict
, uint32_t version
, CFArrayRef allowedOmissions
)
907 // compute allowed omissions
908 CFRef
<CFArrayRef
> defaultOmissions
= this->diskRep()->allowedResourceOmissions();
909 if (!defaultOmissions
)
910 MacOSError::throwMe(errSecCSInternalError
);
911 CFRef
<CFMutableArrayRef
> allowed
= CFArrayCreateMutableCopy(NULL
, 0, defaultOmissions
);
912 if (allowedOmissions
)
913 CFArrayAppendArray(allowed
, allowedOmissions
, CFRangeMake(0, CFArrayGetCount(allowedOmissions
)));
914 CFRange range
= CFRangeMake(0, CFArrayGetCount(allowed
));
916 // check all resource rules for weakness
917 string catchAllRule
= (version
== 1) ? "^Resources/" : "^.*";
918 __block
bool coversAll
= false;
919 __block
bool forbiddenOmission
= false;
920 CFDictionary
rules(rulesDict
, errSecCSResourceRulesInvalid
);
921 rules
.apply(^(CFStringRef key
, CFTypeRef value
) {
922 string pattern
= cfString(key
, errSecCSResourceRulesInvalid
);
923 if (pattern
== catchAllRule
&& value
== kCFBooleanTrue
) {
927 if (isOmitRule(value
))
928 forbiddenOmission
|= !CFArrayContainsValue(allowed
, range
, key
);
931 return !coversAll
|| forbiddenOmission
;
936 // Load, validate, cache, and return CFDictionary forms of sealed resources.
938 CFDictionaryRef
SecStaticCode::infoDictionary()
941 mInfoDict
.take(getDictionary(cdInfoSlot
, errSecCSInfoPlistFailed
));
942 secdebug("staticCode", "%p loaded InfoDict %p", this, mInfoDict
.get());
947 CFDictionaryRef
SecStaticCode::entitlements()
949 if (!mEntitlements
) {
951 if (CFDataRef entitlementData
= component(cdEntitlementSlot
)) {
952 validateComponent(cdEntitlementSlot
);
953 const EntitlementBlob
*blob
= reinterpret_cast<const EntitlementBlob
*>(CFDataGetBytePtr(entitlementData
));
954 if (blob
->validateBlob()) {
955 mEntitlements
.take(blob
->entitlements());
956 secdebug("staticCode", "%p loaded Entitlements %p", this, mEntitlements
.get());
958 // we do not consider a different blob type to be an error. We think it's a new format we don't understand
961 return mEntitlements
;
964 CFDictionaryRef
SecStaticCode::resourceDictionary(bool check
/* = true */)
966 if (mResourceDict
) // cached
967 return mResourceDict
;
968 if (CFRef
<CFDictionaryRef
> dict
= getDictionary(cdResourceDirSlot
, check
))
969 if (cfscan(dict
, "{rules=%Dn,files=%Dn}")) {
970 secdebug("staticCode", "%p loaded ResourceDict %p",
971 this, mResourceDict
.get());
972 return mResourceDict
= dict
;
980 // Load and cache the resource directory base.
981 // Note that the base is optional for each DiskRep.
983 CFURLRef
SecStaticCode::resourceBase()
985 if (!mGotResourceBase
) {
986 string base
= mRep
->resourcesRootPath();
988 mResourceBase
.take(makeCFURL(base
, true));
989 mGotResourceBase
= true;
991 return mResourceBase
;
996 // Load a component, validate it, convert it to a CFDictionary, and return that.
997 // This will force load and validation, which means that it will perform basic
998 // validation if it hasn't been done yet.
1000 CFDictionaryRef
SecStaticCode::getDictionary(CodeDirectory::SpecialSlot slot
, bool check
/* = true */)
1003 validateDirectory();
1004 if (CFDataRef infoData
= component(slot
)) {
1005 validateComponent(slot
);
1006 if (CFDictionaryRef dict
= makeCFDictionaryFrom(infoData
))
1009 MacOSError::throwMe(errSecCSBadDictionaryFormat
);
1016 // Load, validate, and return a sealed resource.
1017 // The resource data (loaded in to memory as a blob) is returned and becomes
1018 // the responsibility of the caller; it is NOT cached by SecStaticCode.
1020 // A resource that is not sealed will not be returned, and an error will be thrown.
1021 // A missing resource will cause an error unless it's marked optional in the Directory.
1022 // Under no circumstances will a corrupt resource be returned.
1023 // NULL will only be returned for a resource that is neither sealed nor present
1024 // (or that is sealed, absent, and marked optional).
1025 // If the ResourceDictionary itself is not sealed, this function will always fail.
1027 // There is currently no interface for partial retrieval of the resource data.
1028 // (Since the ResourceDirectory does not currently support segmentation, all the
1029 // data would have to be read anyway, but it could be read into a reusable buffer.)
1031 CFDataRef
SecStaticCode::resource(string path
, ValidationContext
&ctx
)
1033 if (CFDictionaryRef rdict
= resourceDictionary()) {
1034 if (CFTypeRef file
= cfget(rdict
, "files.%s", path
.c_str())) {
1035 ResourceSeal seal
= file
;
1036 if (!resourceBase()) // no resources in DiskRep
1037 MacOSError::throwMe(errSecCSResourcesNotFound
);
1039 MacOSError::throwMe(errSecCSResourcesNotSealed
); // (it's nested code)
1040 CFRef
<CFURLRef
> fullpath
= makeCFURL(path
, false, resourceBase());
1041 if (CFRef
<CFDataRef
> data
= cfLoadFile(fullpath
)) {
1042 MakeHash
<CodeDirectory
> hasher(this->codeDirectory());
1043 hasher
->update(CFDataGetBytePtr(data
), CFDataGetLength(data
));
1044 if (hasher
->verify(seal
.hash()))
1045 return data
.yield(); // good
1047 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // altered
1049 if (!seal
.optional())
1050 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceMissing
, fullpath
); // was sealed but is now missing
1052 return NULL
; // validly missing
1055 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAdded
, CFTempURL(path
, false, resourceBase()));
1058 MacOSError::throwMe(errSecCSResourcesNotSealed
);
1061 CFDataRef
SecStaticCode::resource(string path
)
1063 ValidationContext
ctx(*this);
1064 return resource(path
, ctx
);
1067 void SecStaticCode::validateResource(CFDictionaryRef files
, string path
, bool isSymlink
, ValidationContext
&ctx
, SecCSFlags flags
, uint32_t version
)
1069 if (!resourceBase()) // no resources in DiskRep
1070 MacOSError::throwMe(errSecCSResourcesNotFound
);
1071 CFRef
<CFURLRef
> fullpath
= makeCFURL(path
, false, resourceBase());
1072 if (CFTypeRef file
= CFDictionaryGetValue(files
, CFTempString(path
))) {
1073 ResourceSeal seal
= file
;
1074 if (seal
.nested()) {
1076 return ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
1077 string suffix
= ".framework";
1078 bool isFramework
= (path
.length() > suffix
.length())
1079 && (path
.compare(path
.length()-suffix
.length(), suffix
.length(), suffix
) == 0);
1080 validateNestedCode(fullpath
, seal
, flags
, isFramework
);
1081 } else if (seal
.link()) {
1082 char target
[PATH_MAX
];
1083 ssize_t len
= ::readlink(cfString(fullpath
).c_str(), target
, sizeof(target
)-1);
1085 UnixError::check(-1);
1087 if (cfString(seal
.link()) != target
)
1088 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
);
1089 } else if (seal
.hash()) { // genuine file
1090 AutoFileDesc
fd(cfString(fullpath
), O_RDONLY
, FileDesc::modeMissingOk
); // open optional file
1092 MakeHash
<CodeDirectory
> hasher(this->codeDirectory());
1093 hashFileData(fd
, hasher
.get());
1094 if (hasher
->verify(seal
.hash()))
1095 return; // verify good
1097 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // altered
1099 if (!seal
.optional())
1100 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceMissing
, fullpath
); // was sealed but is now missing
1102 return; // validly missing
1105 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
1108 if (version
== 1) { // version 1 ignores symlinks altogether
1109 char target
[PATH_MAX
];
1110 if (::readlink(cfString(fullpath
).c_str(), target
, sizeof(target
)) > 0)
1113 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAdded
, CFTempURL(path
, false, resourceBase()));
1116 void SecStaticCode::validateNestedCode(CFURLRef path
, const ResourceSeal
&seal
, SecCSFlags flags
, bool isFramework
)
1118 CFRef
<SecRequirementRef
> req
;
1119 if (SecRequirementCreateWithString(seal
.requirement(), kSecCSDefaultFlags
, &req
.aref()))
1120 MacOSError::throwMe(errSecCSResourcesInvalid
);
1122 // recursively verify this nested code
1124 if (!(flags
& kSecCSCheckNestedCode
))
1125 flags
|= kSecCSBasicValidateOnly
;
1126 SecPointer
<SecStaticCode
> code
= new SecStaticCode(DiskRep::bestGuess(cfString(path
)));
1127 code
->setMonitor(this->monitor());
1128 code
->staticValidate(flags
, SecRequirement::required(req
));
1130 if (isFramework
&& (flags
& kSecCSStrictValidate
))
1132 validateOtherVersions(path
, flags
, req
, code
);
1133 } catch (const CSError
&err
) {
1134 MacOSError::throwMe(errSecCSBadFrameworkVersion
);
1135 } catch (const MacOSError
&err
) {
1136 MacOSError::throwMe(errSecCSBadFrameworkVersion
);
1139 } catch (CSError
&err
) {
1140 if (err
.error
== errSecCSReqFailed
) {
1141 mResourcesValidContext
->reportProblem(errSecCSBadNestedCode
, kSecCFErrorResourceAltered
, path
);
1144 err
.augment(kSecCFErrorPath
, path
);
1146 } catch (const MacOSError
&err
) {
1147 if (err
.error
== errSecCSReqFailed
) {
1148 mResourcesValidContext
->reportProblem(errSecCSBadNestedCode
, kSecCFErrorResourceAltered
, path
);
1151 CSError::throwMe(err
.error
, kSecCFErrorPath
, path
);
1155 void SecStaticCode::validateOtherVersions(CFURLRef path
, SecCSFlags flags
, SecRequirementRef req
, SecStaticCode
*code
)
1157 // Find out what current points to and do not revalidate
1158 std::string mainPath
= cfStringRelease(code
->diskRep()->copyCanonicalPath());
1160 char main_path
[PATH_MAX
];
1161 bool foundTarget
= false;
1163 /* If it failed to get the target of the symlink, do not fail. It is a performance loss,
1164 not a security hole */
1165 if (realpath(mainPath
.c_str(), main_path
) != NULL
)
1168 std::ostringstream versionsPath
;
1169 versionsPath
<< cfString(path
) << "/Versions/";
1171 DirScanner
scanner(versionsPath
.str());
1173 if (scanner
.initialized()) {
1174 struct dirent
*entry
= NULL
;
1175 while ((entry
= scanner
.getNext()) != NULL
) {
1176 std::ostringstream fullPath
;
1178 if (entry
->d_type
!= DT_DIR
||
1179 strcmp(entry
->d_name
, ".") == 0 ||
1180 strcmp(entry
->d_name
, "..") == 0 ||
1181 strcmp(entry
->d_name
, "Current") == 0)
1184 fullPath
<< versionsPath
.str() << entry
->d_name
;
1186 char real_full_path
[PATH_MAX
];
1187 if (realpath(fullPath
.str().c_str(), real_full_path
) == NULL
)
1188 UnixError::check(-1);
1190 // Do case insensitive comparions because realpath() was called for both paths
1191 if (foundTarget
&& strcmp(main_path
, real_full_path
) == 0)
1194 SecPointer
<SecStaticCode
> frameworkVersion
= new SecStaticCode(DiskRep::bestGuess(real_full_path
));
1195 frameworkVersion
->setMonitor(this->monitor());
1196 frameworkVersion
->staticValidate(flags
, SecRequirement::required(req
));
1203 // Test a CodeDirectory flag.
1204 // Returns false if there is no CodeDirectory.
1205 // May throw if the CodeDirectory is present but somehow invalid.
1207 bool SecStaticCode::flag(uint32_t tested
)
1209 if (const CodeDirectory
*cd
= this->codeDirectory(false))
1210 return cd
->flags
& tested
;
1217 // Retrieve the full SuperBlob containing all internal requirements.
1219 const Requirements
*SecStaticCode::internalRequirements()
1221 if (CFDataRef reqData
= component(cdRequirementsSlot
)) {
1222 const Requirements
*req
= (const Requirements
*)CFDataGetBytePtr(reqData
);
1223 if (!req
->validateBlob())
1224 MacOSError::throwMe(errSecCSReqInvalid
);
1232 // Retrieve a particular internal requirement by type.
1234 const Requirement
*SecStaticCode::internalRequirement(SecRequirementType type
)
1236 if (const Requirements
*reqs
= internalRequirements())
1237 return reqs
->find
<Requirement
>(type
);
1244 // Return the Designated Requirement (DR). This can be either explicit in the
1245 // Internal Requirements component, or implicitly generated on demand here.
1246 // Note that an explicit DR may have been implicitly generated at signing time;
1247 // we don't distinguish this case.
1249 const Requirement
*SecStaticCode::designatedRequirement()
1251 if (const Requirement
*req
= internalRequirement(kSecDesignatedRequirementType
)) {
1252 return req
; // explicit in signing data
1254 if (!mDesignatedReq
)
1255 mDesignatedReq
= defaultDesignatedRequirement();
1256 return mDesignatedReq
;
1262 // Generate the default Designated Requirement (DR) for this StaticCode.
1263 // Ignore any explicit DR it may contain.
1265 const Requirement
*SecStaticCode::defaultDesignatedRequirement()
1267 if (flag(kSecCodeSignatureAdhoc
)) {
1268 // adhoc signature: return a cdhash requirement for all architectures
1269 __block
Requirement::Maker maker
;
1270 Requirement::Maker::Chain
chain(maker
, opOr
);
1272 // insert cdhash requirement for all architectures
1274 maker
.cdhash(this->cdHash());
1275 handleOtherArchitectures(^(SecStaticCode
*subcode
) {
1276 if (CFDataRef cdhash
= subcode
->cdHash()) {
1278 maker
.cdhash(cdhash
);
1281 return maker
.make();
1283 // full signature: Gin up full context and let DRMaker do its thing
1284 validateDirectory(); // need the cert chain
1285 Requirement::Context
context(this->certificates(),
1286 this->infoDictionary(),
1287 this->entitlements(),
1289 this->codeDirectory()
1291 return DRMaker(context
).make();
1297 // Validate a SecStaticCode against the internal requirement of a particular type.
1299 void SecStaticCode::validateRequirements(SecRequirementType type
, SecStaticCode
*target
,
1300 OSStatus nullError
/* = errSecSuccess */)
1302 DTRACK(CODESIGN_EVAL_STATIC_INTREQ
, this, type
, target
, nullError
);
1303 if (const Requirement
*req
= internalRequirement(type
))
1304 target
->validateRequirement(req
, nullError
? nullError
: errSecCSReqFailed
);
1306 MacOSError::throwMe(nullError
);
1313 // Validate this StaticCode against an external Requirement
1315 bool SecStaticCode::satisfiesRequirement(const Requirement
*req
, OSStatus failure
)
1318 validateDirectory();
1319 return req
->validates(Requirement::Context(mCertChain
, infoDictionary(), entitlements(), codeDirectory()->identifier(), codeDirectory()), failure
);
1322 void SecStaticCode::validateRequirement(const Requirement
*req
, OSStatus failure
)
1324 if (!this->satisfiesRequirement(req
, failure
))
1325 MacOSError::throwMe(failure
);
1330 // Retrieve one certificate from the cert chain.
1331 // Positive and negative indices can be used:
1332 // [ leaf, intermed-1, ..., intermed-n, anchor ]
1334 // Returns NULL if unavailable for any reason.
1336 SecCertificateRef
SecStaticCode::cert(int ix
)
1338 validateDirectory(); // need cert chain
1340 CFIndex length
= CFArrayGetCount(mCertChain
);
1343 if (ix
>= 0 && ix
< length
)
1344 return SecCertificateRef(CFArrayGetValueAtIndex(mCertChain
, ix
));
1349 CFArrayRef
SecStaticCode::certificates()
1351 validateDirectory(); // need cert chain
1357 // Gather (mostly) API-official information about this StaticCode.
1359 // This method lives in the twilight between the API and internal layers,
1360 // since it generates API objects (Sec*Refs) for return.
1362 CFDictionaryRef
SecStaticCode::signingInformation(SecCSFlags flags
)
1365 // Start with the pieces that we return even for unsigned code.
1366 // This makes Sec[Static]CodeRefs useful as API-level replacements
1367 // of our internal OSXCode objects.
1369 CFRef
<CFMutableDictionaryRef
> dict
= makeCFMutableDictionary(1,
1370 kSecCodeInfoMainExecutable
, CFTempURL(this->mainExecutablePath()).get()
1374 // If we're not signed, this is all you get
1376 if (!this->isSigned())
1377 return dict
.yield();
1380 // Add the generic attributes that we always include
1382 CFDictionaryAddValue(dict
, kSecCodeInfoIdentifier
, CFTempString(this->identifier()));
1383 CFDictionaryAddValue(dict
, kSecCodeInfoFlags
, CFTempNumber(this->codeDirectory(false)->flags
.get()));
1384 CFDictionaryAddValue(dict
, kSecCodeInfoFormat
, CFTempString(this->format()));
1385 CFDictionaryAddValue(dict
, kSecCodeInfoSource
, CFTempString(this->signatureSource()));
1386 CFDictionaryAddValue(dict
, kSecCodeInfoUnique
, this->cdHash());
1387 CFDictionaryAddValue(dict
, kSecCodeInfoDigestAlgorithm
, CFTempNumber(this->codeDirectory(false)->hashType
));
1390 // Deliver any Info.plist only if it looks intact
1393 if (CFDictionaryRef info
= this->infoDictionary())
1394 CFDictionaryAddValue(dict
, kSecCodeInfoPList
, info
);
1395 } catch (...) { } // don't deliver Info.plist if questionable
1398 // kSecCSSigningInformation adds information about signing certificates and chains
1400 if (flags
& kSecCSSigningInformation
)
1402 if (CFArrayRef certs
= this->certificates())
1403 CFDictionaryAddValue(dict
, kSecCodeInfoCertificates
, certs
);
1404 if (CFDataRef sig
= this->signature())
1405 CFDictionaryAddValue(dict
, kSecCodeInfoCMS
, sig
);
1407 CFDictionaryAddValue(dict
, kSecCodeInfoTrust
, mTrust
);
1408 if (CFAbsoluteTime time
= this->signingTime())
1409 if (CFRef
<CFDateRef
> date
= CFDateCreate(NULL
, time
))
1410 CFDictionaryAddValue(dict
, kSecCodeInfoTime
, date
);
1411 if (CFAbsoluteTime time
= this->signingTimestamp())
1412 if (CFRef
<CFDateRef
> date
= CFDateCreate(NULL
, time
))
1413 CFDictionaryAddValue(dict
, kSecCodeInfoTimestamp
, date
);
1414 if (const char *teamID
= this->teamID())
1415 CFDictionaryAddValue(dict
, kSecCodeInfoTeamIdentifier
, CFTempString(teamID
));
1419 // kSecCSRequirementInformation adds information on requirements
1421 if (flags
& kSecCSRequirementInformation
)
1423 if (const Requirements
*reqs
= this->internalRequirements()) {
1424 CFDictionaryAddValue(dict
, kSecCodeInfoRequirements
,
1425 CFTempString(Dumper::dump(reqs
)));
1426 CFDictionaryAddValue(dict
, kSecCodeInfoRequirementData
, CFTempData(*reqs
));
1429 const Requirement
*dreq
= this->designatedRequirement();
1430 CFRef
<SecRequirementRef
> dreqRef
= (new SecRequirement(dreq
))->handle();
1431 CFDictionaryAddValue(dict
, kSecCodeInfoDesignatedRequirement
, dreqRef
);
1432 if (this->internalRequirement(kSecDesignatedRequirementType
)) { // explicit
1433 CFRef
<SecRequirementRef
> ddreqRef
= (new SecRequirement(this->defaultDesignatedRequirement(), true))->handle();
1434 CFDictionaryAddValue(dict
, kSecCodeInfoImplicitDesignatedRequirement
, ddreqRef
);
1435 } else { // implicit
1436 CFDictionaryAddValue(dict
, kSecCodeInfoImplicitDesignatedRequirement
, dreqRef
);
1441 if (CFDataRef ent
= this->component(cdEntitlementSlot
)) {
1442 CFDictionaryAddValue(dict
, kSecCodeInfoEntitlements
, ent
);
1443 if (CFDictionaryRef entdict
= this->entitlements())
1444 CFDictionaryAddValue(dict
, kSecCodeInfoEntitlementsDict
, entdict
);
1449 // kSecCSInternalInformation adds internal information meant to be for Apple internal
1450 // use (SPI), and not guaranteed to be stable. Primarily, this is data we want
1451 // to reliably transmit through the API wall so that code outside the Security.framework
1452 // can use it without having to play nasty tricks to get it.
1454 if (flags
& kSecCSInternalInformation
)
1457 CFDictionaryAddValue(dict
, kSecCodeInfoCodeDirectory
, mDir
);
1458 CFDictionaryAddValue(dict
, kSecCodeInfoCodeOffset
, CFTempNumber(mRep
->signingBase()));
1459 if (CFRef
<CFDictionaryRef
> rdict
= getDictionary(cdResourceDirSlot
, false)) // suppress validation
1460 CFDictionaryAddValue(dict
, kSecCodeInfoResourceDirectory
, rdict
);
1465 // kSecCSContentInformation adds more information about the physical layout
1466 // of the signed code. This is (only) useful for packaging or patching-oriented
1469 if (flags
& kSecCSContentInformation
)
1470 if (CFRef
<CFArrayRef
> files
= mRep
->modifiedFiles())
1471 CFDictionaryAddValue(dict
, kSecCodeInfoChangedFiles
, files
);
1473 return dict
.yield();
1478 // Resource validation contexts.
1479 // The default context simply throws a CSError, rudely terminating the operation.
1481 SecStaticCode::ValidationContext::~ValidationContext()
1484 void SecStaticCode::ValidationContext::reportProblem(OSStatus rc
, CFStringRef type
, CFTypeRef value
)
1486 CSError::throwMe(rc
, type
, value
);
1489 void SecStaticCode::CollectingContext::reportProblem(OSStatus rc
, CFStringRef type
, CFTypeRef value
)
1491 if (mStatus
== errSecSuccess
)
1492 mStatus
= rc
; // record first failure for eventual error return
1495 mCollection
.take(makeCFMutableDictionary());
1496 CFMutableArrayRef element
= CFMutableArrayRef(CFDictionaryGetValue(mCollection
, type
));
1498 element
= makeCFMutableArray(0);
1501 CFDictionaryAddValue(mCollection
, type
, element
);
1504 CFArrayAppendValue(element
, value
);
1508 void SecStaticCode::CollectingContext::throwMe()
1510 assert(mStatus
!= errSecSuccess
);
1511 throw CSError(mStatus
, mCollection
.retain());
1516 // Master validation driver.
1517 // This is the static validation (only) driver for the API.
1519 // SecStaticCode exposes an a la carte menu of topical validators applying
1520 // to a given object. The static validation API pulls them together reliably,
1521 // but it also adds two matrix dimensions: architecture (for "fat" Mach-O binaries)
1522 // and nested code. This function will crawl a suitable cross-section of this
1523 // validation matrix based on which options it is given, creating temporary
1524 // SecStaticCode objects on the fly to complete the task.
1525 // (The point, of course, is to do as little duplicate work as possible.)
1527 void SecStaticCode::staticValidate(SecCSFlags flags
, const SecRequirement
*req
)
1529 setValidationFlags(flags
);
1531 // initialize progress/cancellation state
1532 prepareProgress(estimateResourceWorkload() + 2); // +1 head, +1 tail
1534 // core components: once per architecture (if any)
1535 this->staticValidateCore(flags
, req
);
1536 if (flags
& kSecCSCheckAllArchitectures
)
1537 handleOtherArchitectures(^(SecStaticCode
* subcode
) {
1538 subcode
->detachedSignature(this->mDetachedSig
); // carry over explicit (but not implicit) architecture
1539 subcode
->staticValidateCore(flags
, req
);
1543 // allow monitor intervention in source validation phase
1544 reportEvent(CFSTR("prepared"), NULL
);
1546 // resources: once for all architectures
1547 if (!(flags
& kSecCSDoNotValidateResources
))
1548 this->validateResources(flags
);
1550 // perform strict validation if desired
1551 if (flags
& kSecCSStrictValidate
)
1552 mRep
->strictValidate(mTolerateErrors
);
1555 // allow monitor intervention
1556 if (CFRef
<CFTypeRef
> veto
= reportEvent(CFSTR("validated"), NULL
)) {
1557 if (CFGetTypeID(veto
) == CFNumberGetTypeID())
1558 MacOSError::throwMe(cfNumber
<OSStatus
>(veto
.as
<CFNumberRef
>()));
1560 MacOSError::throwMe(errSecCSBadCallbackValue
);
1564 void SecStaticCode::staticValidateCore(SecCSFlags flags
, const SecRequirement
*req
)
1567 this->validateNonResourceComponents(); // also validates the CodeDirectory
1568 if (!(flags
& kSecCSDoNotValidateExecutable
))
1569 this->validateExecutable();
1571 this->validateRequirement(req
->requirement(), errSecCSReqFailed
);
1572 } catch (CSError
&err
) {
1573 if (Universal
*fat
= this->diskRep()->mainExecutableImage()) // Mach-O
1574 if (MachO
*mach
= fat
->architecture()) {
1575 err
.augment(kSecCFErrorArchitecture
, CFTempString(mach
->architecture().displayName()));
1579 } catch (const MacOSError
&err
) {
1580 // add architecture information if we can get it
1581 if (Universal
*fat
= this->diskRep()->mainExecutableImage())
1582 if (MachO
*mach
= fat
->architecture()) {
1583 CFTempString
arch(mach
->architecture().displayName());
1585 CSError::throwMe(err
.error
, kSecCFErrorArchitecture
, arch
);
1593 // A helper that generates SecStaticCode objects for all but the primary architecture
1594 // of a fat binary and calls a block on them.
1595 // If there's only one architecture (or this is an architecture-agnostic code),
1596 // nothing happens quickly.
1598 void SecStaticCode::handleOtherArchitectures(void (^handle
)(SecStaticCode
* other
))
1600 if (Universal
*fat
= this->diskRep()->mainExecutableImage()) {
1601 Universal::Architectures architectures
;
1602 fat
->architectures(architectures
);
1603 if (architectures
.size() > 1) {
1604 DiskRep::Context ctx
;
1605 size_t activeOffset
= fat
->archOffset();
1606 for (Universal::Architectures::const_iterator arch
= architectures
.begin(); arch
!= architectures
.end(); ++arch
) {
1607 ctx
.offset
= fat
->archOffset(*arch
);
1608 if (ctx
.offset
> SIZE_MAX
)
1609 MacOSError::throwMe(errSecCSInternalError
);
1610 ctx
.size
= fat
->lengthOfSlice((size_t)ctx
.offset
);
1611 if (ctx
.offset
!= activeOffset
) { // inactive architecture; check it
1612 SecPointer
<SecStaticCode
> subcode
= new SecStaticCode(DiskRep::bestGuess(this->mainExecutablePath(), &ctx
));
1613 subcode
->detachedSignature(this->mDetachedSig
); // carry over explicit (but not implicit) detached signature
1614 if (this->teamID() == NULL
|| subcode
->teamID() == NULL
) {
1615 if (this->teamID() != subcode
->teamID())
1616 MacOSError::throwMe(errSecCSSignatureInvalid
);
1617 } else if (strcmp(this->teamID(), subcode
->teamID()) != 0)
1618 MacOSError::throwMe(errSecCSSignatureInvalid
);
1627 // A method that takes a certificate chain (certs) and evaluates
1628 // if it is a Mac or IPhone developer cert, an app store distribution cert,
1629 // or a developer ID
1631 bool SecStaticCode::isAppleDeveloperCert(CFArrayRef certs
)
1633 static const std::string appleDeveloperRequirement
= "(" + std::string(WWDRRequirement
) + ") or (" + MACWWDRRequirement
+ ") or (" + developerID
+ ") or (" + distributionCertificate
+ ") or (" + iPhoneDistributionCert
+ ")";
1634 SecPointer
<SecRequirement
> req
= new SecRequirement(parseRequirement(appleDeveloperRequirement
), true);
1635 Requirement::Context
ctx(certs
, NULL
, NULL
, "", NULL
);
1637 return req
->requirement()->validates(ctx
);
1640 } // end namespace CodeSigning
1641 } // end namespace Security