2 * Copyright (c) 2006-2012 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 <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>
54 namespace CodeSigning
{
56 using namespace UnixPlusPlus
;
58 // A requirement representing a Mac or iOS dev cert, a Mac or iOS distribution cert, or a developer ID
59 static const char WWDRRequirement
[] = "anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.1] exists "
60 "and ( cert leaf[subject.CN] = \"Mac Developer: \"* or cert leaf[subject.CN] = \"iPhone Developer: \"* )";
61 static const char developerID
[] = "anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists"
62 " and certificate leaf[field.1.2.840.113635.100.6.1.13] exists";
63 static const char distributionCertificate
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.7] exists";
64 static const char iPhoneDistributionCert
[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.4] exists";
67 // Map a component slot number to a suitable error code for a failure
69 static inline OSStatus
errorForSlot(CodeDirectory::SpecialSlot slot
)
73 return errSecCSInfoPlistFailed
;
74 case cdResourceDirSlot
:
75 return errSecCSResourceDirectoryFailed
;
77 return errSecCSSignatureFailed
;
83 // Construct a SecStaticCode object given a disk representation object
85 SecStaticCode::SecStaticCode(DiskRep
*rep
)
87 mValidated(false), mExecutableValidated(false), mResourcesValidated(false), mResourcesValidContext(NULL
),
88 mDesignatedReq(NULL
), mGotResourceBase(false), mMonitor(NULL
), mEvalDetails(NULL
)
90 CODESIGN_STATIC_CREATE(this, rep
);
91 checkForSystemSignature();
96 // Clean up a SecStaticCode object
98 SecStaticCode::~SecStaticCode() throw()
100 ::free(const_cast<Requirement
*>(mDesignatedReq
));
101 if (mResourcesValidContext
)
102 delete mResourcesValidContext
;
109 // CF-level comparison of SecStaticCode objects compares CodeDirectory hashes if signed,
110 // and falls back on comparing canonical paths if (both are) not.
112 bool SecStaticCode::equal(SecCFObject
&secOther
)
114 SecStaticCode
*other
= static_cast<SecStaticCode
*>(&secOther
);
115 CFDataRef mine
= this->cdHash();
116 CFDataRef his
= other
->cdHash();
118 return mine
&& his
&& CFEqual(mine
, his
);
120 return CFEqual(this->canonicalPath(), other
->canonicalPath());
123 CFHashCode
SecStaticCode::hash()
125 if (CFDataRef h
= this->cdHash())
128 return CFHash(this->canonicalPath());
133 // Invoke a stage monitor if registered
135 CFTypeRef
SecStaticCode::reportEvent(CFStringRef stage
, CFDictionaryRef info
)
138 return mMonitor(this->handle(false), stage
, info
);
145 // Attach a detached signature.
147 void SecStaticCode::detachedSignature(CFDataRef sigData
)
150 mDetachedSig
= sigData
;
151 mRep
= new DetachedRep(sigData
, mRep
->base(), "explicit detached");
152 CODESIGN_STATIC_ATTACH_EXPLICIT(this, mRep
);
156 CODESIGN_STATIC_ATTACH_EXPLICIT(this, NULL
);
162 // Consult the system detached signature database to see if it contains
163 // a detached signature for this StaticCode. If it does, fetch and attach it.
164 // We do this only if the code has no signature already attached.
166 void SecStaticCode::checkForSystemSignature()
168 if (!this->isSigned()) {
169 SignatureDatabase db
;
172 if (RefPointer
<DiskRep
> dsig
= db
.findCode(mRep
)) {
173 CODESIGN_STATIC_ATTACH_SYSTEM(this, dsig
);
183 // Return a descriptive string identifying the source of the code signature
185 string
SecStaticCode::signatureSource()
189 if (DetachedRep
*rep
= dynamic_cast<DetachedRep
*>(mRep
.get()))
190 return rep
->source();
196 // Do ::required, but convert incoming SecCodeRefs to their SecStaticCodeRefs
199 SecStaticCode
*SecStaticCode::requiredStatic(SecStaticCodeRef ref
)
201 SecCFObject
*object
= SecCFObject::required(ref
, errSecCSInvalidObjectRef
);
202 if (SecStaticCode
*scode
= dynamic_cast<SecStaticCode
*>(object
))
204 else if (SecCode
*code
= dynamic_cast<SecCode
*>(object
))
205 return code
->staticCode();
206 else // neither (a SecSomethingElse)
207 MacOSError::throwMe(errSecCSInvalidObjectRef
);
210 SecCode
*SecStaticCode::optionalDynamic(SecStaticCodeRef ref
)
212 SecCFObject
*object
= SecCFObject::required(ref
, errSecCSInvalidObjectRef
);
213 if (dynamic_cast<SecStaticCode
*>(object
))
215 else if (SecCode
*code
= dynamic_cast<SecCode
*>(object
))
217 else // neither (a SecSomethingElse)
218 MacOSError::throwMe(errSecCSInvalidObjectRef
);
223 // Void all cached validity data.
225 // We also throw out cached components, because the new signature data may have
226 // a different idea of what components should be present. We could reconcile the
227 // cached data instead, if performance seems to be impacted.
229 void SecStaticCode::resetValidity()
231 CODESIGN_EVAL_STATIC_RESET(this);
233 mExecutableValidated
= mResourcesValidated
= false;
234 if (mResourcesValidContext
) {
235 delete mResourcesValidContext
;
236 mResourcesValidContext
= NULL
;
240 for (unsigned n
= 0; n
< cdSlotCount
; n
++)
243 mEntitlements
= NULL
;
244 mResourceDict
= NULL
;
245 mDesignatedReq
= NULL
;
246 mGotResourceBase
= false;
252 // we may just have updated the system database, so check again
253 checkForSystemSignature();
258 // Retrieve a sealed component by special slot index.
259 // If the CodeDirectory has already been validated, validate against that.
260 // Otherwise, retrieve the component without validation (but cache it). Validation
261 // will go through the cache and validate all cached components.
263 CFDataRef
SecStaticCode::component(CodeDirectory::SpecialSlot slot
, OSStatus fail
/* = errSecCSSignatureFailed */)
265 assert(slot
<= cdSlotMax
);
267 CFRef
<CFDataRef
> &cache
= mCache
[slot
];
269 if (CFRef
<CFDataRef
> data
= mRep
->component(slot
)) {
270 if (validated()) // if the directory has been validated...
271 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data
), // ... and it's no good
272 CFDataGetLength(data
), -slot
))
273 MacOSError::throwMe(errorForSlot(slot
)); // ... then bail
274 cache
= data
; // it's okay, cache it
275 } else { // absent, mark so
276 if (validated()) // if directory has been validated...
277 if (codeDirectory()->slotIsPresent(-slot
)) // ... and the slot is NOT missing
278 MacOSError::throwMe(errorForSlot(slot
)); // was supposed to be there
279 cache
= CFDataRef(kCFNull
); // white lie
282 return (cache
== CFDataRef(kCFNull
)) ? NULL
: cache
.get();
287 // Get the CodeDirectory.
288 // Throws (if check==true) or returns NULL (check==false) if there is none.
289 // Always throws if the CodeDirectory exists but is invalid.
290 // NEVER validates against the signature.
292 const CodeDirectory
*SecStaticCode::codeDirectory(bool check
/* = true */)
295 if (mDir
.take(mRep
->codeDirectory())) {
296 const CodeDirectory
*dir
= reinterpret_cast<const CodeDirectory
*>(CFDataGetBytePtr(mDir
));
297 dir
->checkIntegrity();
301 return reinterpret_cast<const CodeDirectory
*>(CFDataGetBytePtr(mDir
));
303 MacOSError::throwMe(errSecCSUnsigned
);
309 // Get the hash of the CodeDirectory.
310 // Returns NULL if there is none.
312 CFDataRef
SecStaticCode::cdHash()
315 if (const CodeDirectory
*cd
= codeDirectory(false)) {
317 hash(cd
, cd
->length());
320 mCDHash
.take(makeCFData(digest
, sizeof(digest
)));
321 CODESIGN_STATIC_CDHASH(this, digest
, sizeof(digest
));
329 // Return the CMS signature blob; NULL if none found.
331 CFDataRef
SecStaticCode::signature()
334 mSignature
.take(mRep
->signature());
337 MacOSError::throwMe(errSecCSUnsigned
);
342 // Verify the signature on the CodeDirectory.
343 // If this succeeds (doesn't throw), the CodeDirectory is statically trustworthy.
344 // Any outcome (successful or not) is cached for the lifetime of the StaticCode.
346 void SecStaticCode::validateDirectory()
348 // echo previous outcome, if any
351 // perform validation (or die trying)
352 CODESIGN_EVAL_STATIC_DIRECTORY(this);
353 mValidationExpired
= verifySignature();
354 for (CodeDirectory::SpecialSlot slot
= codeDirectory()->maxSpecialSlot(); slot
>= 1; --slot
)
355 if (mCache
[slot
]) // if we already loaded that resource...
356 validateComponent(slot
, errorForSlot(slot
)); // ... then check it now
357 mValidated
= true; // we've done the deed...
358 mValidationResult
= errSecSuccess
; // ... and it was good
359 } catch (const CommonError
&err
) {
361 mValidationResult
= err
.osStatus();
364 secdebug("staticCode", "%p validation threw non-common exception", this);
366 mValidationResult
= errSecCSInternalError
;
370 if (mValidationResult
== errSecSuccess
) {
371 if (mValidationExpired
)
372 if ((apiFlags() & kSecCSConsiderExpiration
)
373 || (codeDirectory()->flags
& kSecCodeSignatureForceExpiration
))
374 MacOSError::throwMe(CSSMERR_TP_CERT_EXPIRED
);
376 MacOSError::throwMe(mValidationResult
);
381 // Load and validate the CodeDirectory and all components *except* those related to the resource envelope.
382 // Those latter components are checked by validateResources().
384 void SecStaticCode::validateNonResourceComponents()
386 this->validateDirectory();
387 for (CodeDirectory::SpecialSlot slot
= codeDirectory()->maxSpecialSlot(); slot
>= 1; --slot
)
389 case cdResourceDirSlot
: // validated by validateResources
392 this->component(slot
); // loads and validates
399 // Get the (signed) signing date from the code signature.
400 // Sadly, we need to validate the signature to get the date (as a side benefit).
401 // This means that you can't get the signing time for invalidly signed code.
403 // We could run the decoder "almost to" verification to avoid this, but there seems
404 // little practical point to such a duplication of effort.
406 CFAbsoluteTime
SecStaticCode::signingTime()
412 CFAbsoluteTime
SecStaticCode::signingTimestamp()
415 return mSigningTimestamp
;
420 // Verify the CMS signature on the CodeDirectory.
421 // This performs the cryptographic tango. It returns if the signature is valid,
422 // or throws if it is not. As a side effect, a successful return sets up the
423 // cached certificate chain for future use.
424 // Returns true if the signature is expired (the X.509 sense), false if it's not.
425 // Expiration is fatal (throws) if a secure timestamp is included, but not otherwise.
427 bool SecStaticCode::verifySignature()
429 // ad-hoc signed code is considered validly signed by definition
430 if (flag(kSecCodeSignatureAdhoc
)) {
431 CODESIGN_EVAL_STATIC_SIGNATURE_ADHOC(this);
435 DTRACK(CODESIGN_EVAL_STATIC_SIGNATURE
, this, (char*)this->mainExecutablePath().c_str());
437 // decode CMS and extract SecTrust for verification
438 CFRef
<CMSDecoderRef
> cms
;
439 MacOSError::check(CMSDecoderCreate(&cms
.aref())); // create decoder
440 CFDataRef sig
= this->signature();
441 MacOSError::check(CMSDecoderUpdateMessage(cms
, CFDataGetBytePtr(sig
), CFDataGetLength(sig
)));
442 this->codeDirectory(); // load CodeDirectory (sets mDir)
443 MacOSError::check(CMSDecoderSetDetachedContent(cms
, mDir
));
444 MacOSError::check(CMSDecoderFinalizeMessage(cms
));
445 MacOSError::check(CMSDecoderSetSearchKeychain(cms
, cfEmptyArray()));
446 CFRef
<CFTypeRef
> policy
= verificationPolicy(apiFlags());
447 CMSSignerStatus status
;
448 MacOSError::check(CMSDecoderCopySignerStatus(cms
, 0, policy
,
449 false, &status
, &mTrust
.aref(), NULL
));
450 if (status
!= kCMSSignerValid
)
451 MacOSError::throwMe(errSecCSSignatureFailed
);
453 // internal signing time (as specified by the signer; optional)
454 mSigningTime
= 0; // "not present" marker (nobody could code sign on Jan 1, 2001 :-)
455 switch (OSStatus rc
= CMSDecoderCopySignerSigningTime(cms
, 0, &mSigningTime
)) {
457 case errSecSigningTimeMissing
:
460 MacOSError::throwMe(rc
);
463 // certified signing time (as specified by a TSA; optional)
464 mSigningTimestamp
= 0;
465 switch (OSStatus rc
= CMSDecoderCopySignerTimestamp(cms
, 0, &mSigningTimestamp
)) {
467 case errSecTimestampMissing
:
470 MacOSError::throwMe(rc
);
473 // set up the environment for SecTrust
474 MacOSError::check(SecTrustSetAnchorCertificates(mTrust
, cfEmptyArray())); // no anchors
475 MacOSError::check(SecTrustSetKeychains(mTrust
, cfEmptyArray())); // no keychains
476 CSSM_APPLE_TP_ACTION_DATA actionData
= {
477 CSSM_APPLE_TP_ACTION_VERSION
, // version of data structure
478 CSSM_TP_ACTION_IMPLICIT_ANCHORS
// action flags
481 for (;;) { // at most twice
482 MacOSError::check(SecTrustSetParameters(mTrust
,
483 CSSM_TP_ACTION_DEFAULT
, CFTempData(&actionData
, sizeof(actionData
))));
485 // evaluate trust and extract results
486 SecTrustResultType trustResult
;
487 MacOSError::check(SecTrustEvaluate(mTrust
, &trustResult
));
488 MacOSError::check(SecTrustGetResult(mTrust
, &trustResult
, &mCertChain
.aref(), &mEvalDetails
));
490 // if this is an Apple developer cert....
491 if (teamID() && SecStaticCode::isAppleDeveloperCert(mCertChain
)) {
492 CFRef
<CFStringRef
> teamIDFromCert
;
493 if (CFArrayGetCount(mCertChain
) > 0) {
494 /* Note that SecCertificateCopySubjectComponent sets the out paramater to NULL if there is no field present */
495 MacOSError::check(SecCertificateCopySubjectComponent((SecCertificateRef
)CFArrayGetValueAtIndex(mCertChain
, Requirement::leafCert
),
496 &CSSMOID_OrganizationalUnitName
,
497 &teamIDFromCert
.aref()));
499 if (teamIDFromCert
) {
500 CFRef
<CFStringRef
> teamIDFromCD
= CFStringCreateWithCString(NULL
, teamID(), kCFStringEncodingUTF8
);
502 MacOSError::throwMe(errSecCSInternalError
);
505 if (CFStringCompare(teamIDFromCert
, teamIDFromCD
, 0) != kCFCompareEqualTo
) {
506 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());
507 MacOSError::throwMe(errSecCSSignatureInvalid
);
513 CODESIGN_EVAL_STATIC_SIGNATURE_RESULT(this, trustResult
, mCertChain
? (int)CFArrayGetCount(mCertChain
) : 0);
514 switch (trustResult
) {
515 case kSecTrustResultProceed
:
516 case kSecTrustResultUnspecified
:
518 case kSecTrustResultDeny
:
519 MacOSError::throwMe(CSSMERR_APPLETP_TRUST_SETTING_DENY
); // user reject
520 case kSecTrustResultInvalid
:
521 assert(false); // should never happen
522 MacOSError::throwMe(CSSMERR_TP_NOT_TRUSTED
);
526 MacOSError::check(SecTrustGetCssmResultCode(mTrust
, &result
));
527 // if we have a valid timestamp, CMS validates against (that) signing time and all is well.
528 // If we don't have one, may validate against *now*, and must be able to tolerate expiration.
529 if (mSigningTimestamp
== 0) // no timestamp available
530 if (((result
== CSSMERR_TP_CERT_EXPIRED
) || (result
== CSSMERR_TP_CERT_NOT_VALID_YET
))
531 && !(actionData
.ActionFlags
& CSSM_TP_ACTION_ALLOW_EXPIRED
)) {
532 CODESIGN_EVAL_STATIC_SIGNATURE_EXPIRED(this);
533 actionData
.ActionFlags
|= CSSM_TP_ACTION_ALLOW_EXPIRED
; // (this also allows postdated certs)
534 continue; // retry validation while tolerating expiration
536 MacOSError::throwMe(result
);
540 if (mSigningTimestamp
) {
541 CFIndex rootix
= CFArrayGetCount(mCertChain
);
542 if (SecCertificateRef mainRoot
= SecCertificateRef(CFArrayGetValueAtIndex(mCertChain
, rootix
-1)))
543 if (isAppleCA(mainRoot
)) {
544 // impose policy: if the signature itself draws to Apple, then so must the timestamp signature
545 CFRef
<CFArrayRef
> tsCerts
;
546 MacOSError::check(CMSDecoderCopySignerTimestampCertificates(cms
, 0, &tsCerts
.aref()));
547 CFIndex tsn
= CFArrayGetCount(tsCerts
);
548 bool good
= tsn
> 0 && isAppleCA(SecCertificateRef(CFArrayGetValueAtIndex(tsCerts
, tsn
-1)));
550 MacOSError::throwMe(CSSMERR_TP_NOT_TRUSTED
);
554 return actionData
.ActionFlags
& CSSM_TP_ACTION_ALLOW_EXPIRED
;
560 // Return the TP policy used for signature verification.
561 // This may be a simple SecPolicyRef or a CFArray of policies.
562 // The caller owns the return value.
564 static SecPolicyRef
makeCRLPolicy()
566 CFRef
<SecPolicyRef
> policy
;
567 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_REVOCATION_CRL
, &policy
.aref()));
568 CSSM_APPLE_TP_CRL_OPTIONS options
;
569 memset(&options
, 0, sizeof(options
));
570 options
.Version
= CSSM_APPLE_TP_CRL_OPTS_VERSION
;
571 options
.CrlFlags
= CSSM_TP_ACTION_FETCH_CRL_FROM_NET
| CSSM_TP_ACTION_CRL_SUFFICIENT
;
572 CSSM_DATA optData
= { sizeof(options
), (uint8
*)&options
};
573 MacOSError::check(SecPolicySetValue(policy
, &optData
));
574 return policy
.yield();
577 static SecPolicyRef
makeOCSPPolicy()
579 CFRef
<SecPolicyRef
> policy
;
580 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3
, &CSSMOID_APPLE_TP_REVOCATION_OCSP
, &policy
.aref()));
581 CSSM_APPLE_TP_OCSP_OPTIONS options
;
582 memset(&options
, 0, sizeof(options
));
583 options
.Version
= CSSM_APPLE_TP_OCSP_OPTS_VERSION
;
584 options
.Flags
= CSSM_TP_ACTION_OCSP_SUFFICIENT
;
585 CSSM_DATA optData
= { sizeof(options
), (uint8
*)&options
};
586 MacOSError::check(SecPolicySetValue(policy
, &optData
));
587 return policy
.yield();
590 CFTypeRef
SecStaticCode::verificationPolicy(SecCSFlags flags
)
592 CFRef
<SecPolicyRef
> core
;
593 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3
,
594 &CSSMOID_APPLE_TP_CODE_SIGNING
, &core
.aref()));
595 if (flags
& kSecCSEnforceRevocationChecks
) {
596 CFRef
<SecPolicyRef
> crl
= makeCRLPolicy();
597 CFRef
<SecPolicyRef
> ocsp
= makeOCSPPolicy();
598 return makeCFArray(3, core
.get(), crl
.get(), ocsp
.get());
606 // Validate a particular sealed, cached resource against its (special) CodeDirectory slot.
607 // The resource must already have been placed in the cache.
608 // This does NOT perform basic validation.
610 void SecStaticCode::validateComponent(CodeDirectory::SpecialSlot slot
, OSStatus fail
/* = errSecCSSignatureFailed */)
612 assert(slot
<= cdSlotMax
);
613 CFDataRef data
= mCache
[slot
];
614 assert(data
); // must be cached
615 if (data
== CFDataRef(kCFNull
)) {
616 if (codeDirectory()->slotIsPresent(-slot
)) // was supposed to be there...
617 MacOSError::throwMe(fail
); // ... and is missing
619 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data
), CFDataGetLength(data
), -slot
))
620 MacOSError::throwMe(fail
);
626 // Perform static validation of the main executable.
627 // This reads the main executable from disk and validates it against the
628 // CodeDirectory code slot array.
629 // Note that this is NOT an in-memory validation, and is thus potentially
630 // subject to timing attacks.
632 void SecStaticCode::validateExecutable()
634 if (!validatedExecutable()) {
636 DTRACK(CODESIGN_EVAL_STATIC_EXECUTABLE
, this,
637 (char*)this->mainExecutablePath().c_str(), codeDirectory()->nCodeSlots
);
638 const CodeDirectory
*cd
= this->codeDirectory();
640 MacOSError::throwMe(errSecCSUnsigned
);
641 AutoFileDesc
fd(mainExecutablePath(), O_RDONLY
);
642 fd
.fcntl(F_NOCACHE
, true); // turn off page caching (one-pass)
643 if (Universal
*fat
= mRep
->mainExecutableImage())
644 fd
.seek(fat
->archOffset());
645 size_t pageSize
= cd
->pageSize
? (1 << cd
->pageSize
) : 0;
646 size_t remaining
= cd
->codeLimit
;
647 for (uint32_t slot
= 0; slot
< cd
->nCodeSlots
; ++slot
) {
648 size_t size
= min(remaining
, pageSize
);
649 if (!cd
->validateSlot(fd
, size
, slot
)) {
650 CODESIGN_EVAL_STATIC_EXECUTABLE_FAIL(this, (int)slot
);
651 MacOSError::throwMe(errSecCSSignatureFailed
);
655 mExecutableValidated
= true;
656 mExecutableValidResult
= errSecSuccess
;
657 } catch (const CommonError
&err
) {
658 mExecutableValidated
= true;
659 mExecutableValidResult
= err
.osStatus();
662 secdebug("staticCode", "%p executable validation threw non-common exception", this);
663 mExecutableValidated
= true;
664 mExecutableValidResult
= errSecCSInternalError
;
668 assert(validatedExecutable());
669 if (mExecutableValidResult
!= errSecSuccess
)
670 MacOSError::throwMe(mExecutableValidResult
);
675 // Perform static validation of sealed resources and nested code.
677 // This performs a whole-code static resource scan and effectively
678 // computes a concordance between what's on disk and what's in the ResourceDirectory.
679 // Any unsanctioned difference causes an error.
681 void SecStaticCode::validateResources(SecCSFlags flags
)
683 // do we have a superset of this requested validation cached?
685 if (mResourcesValidated
) { // have cached outcome
686 if (!(flags
& kSecCSCheckNestedCode
) || mResourcesDeep
) // was deep or need no deep scan
692 CFDictionaryRef sealedResources
= resourceDictionary();
693 if (this->resourceBase()) // disk has resources
695 /* go to work below */;
697 MacOSError::throwMe(errSecCSResourcesNotFound
);
698 else // disk has no resources
700 MacOSError::throwMe(errSecCSResourcesNotFound
);
702 return; // no resources, not sealed - fine (no work)
704 // found resources, and they are sealed
705 DTRACK(CODESIGN_EVAL_STATIC_RESOURCES
, this,
706 (char*)this->mainExecutablePath().c_str(), 0);
708 // scan through the resources on disk, checking each against the resourceDirectory
709 mResourcesValidContext
= new CollectingContext(*this); // collect all failures in here
710 CFDictionaryRef rules
;
711 CFDictionaryRef files
;
713 if (CFDictionaryGetValue(sealedResources
, CFSTR("files2"))) { // have V2 signature
714 rules
= cfget
<CFDictionaryRef
>(sealedResources
, "rules2");
715 files
= cfget
<CFDictionaryRef
>(sealedResources
, "files2");
717 } else { // only V1 available
718 rules
= cfget
<CFDictionaryRef
>(sealedResources
, "rules");
719 files
= cfget
<CFDictionaryRef
>(sealedResources
, "files");
722 if (!rules
|| !files
)
723 MacOSError::throwMe(errSecCSResourcesInvalid
);
724 __block CFRef
<CFMutableDictionaryRef
> resourceMap
= makeCFMutableDictionary(files
);
725 ResourceBuilder
resources(cfString(this->resourceBase()), rules
, codeDirectory()->hashType
);
726 diskRep()->adjustResources(resources
);
727 resources
.scan(^(FTSENT
*ent
, uint32_t ruleFlags
, const char *relpath
, ResourceBuilder::Rule
*rule
) {
728 validateResource(files
, relpath
, *mResourcesValidContext
, flags
, version
);
729 CFDictionaryRemoveValue(resourceMap
, CFTempString(relpath
));
732 if (CFDictionaryGetCount(resourceMap
) > 0) {
733 secdebug("staticCode", "%p sealed resource(s) not found in code", this);
734 CFDictionaryApplyFunction(resourceMap
, SecStaticCode::checkOptionalResource
, mResourcesValidContext
);
737 // now check for any errors found in the reporting context
738 mResourcesValidated
= true;
739 mResourcesDeep
= flags
& kSecCSCheckNestedCode
;
740 if (mResourcesValidContext
->osStatus() != errSecSuccess
)
741 mResourcesValidContext
->throwMe();
742 } catch (const CommonError
&err
) {
743 mResourcesValidated
= true;
744 mResourcesDeep
= flags
& kSecCSCheckNestedCode
;
745 mResourcesValidResult
= err
.osStatus();
748 secdebug("staticCode", "%p executable validation threw non-common exception", this);
749 mResourcesValidated
= true;
750 mResourcesDeep
= flags
& kSecCSCheckNestedCode
;
751 mResourcesValidResult
= errSecCSInternalError
;
755 assert(validatedResources());
756 if (mResourcesValidResult
)
757 MacOSError::throwMe(mResourcesValidResult
);
758 if (mResourcesValidContext
->osStatus() != errSecSuccess
)
759 mResourcesValidContext
->throwMe();
763 void SecStaticCode::checkOptionalResource(CFTypeRef key
, CFTypeRef value
, void *context
)
765 CollectingContext
*ctx
= static_cast<CollectingContext
*>(context
);
766 ResourceSeal
seal(value
);
767 if (!seal
.optional()) {
768 if (key
&& CFGetTypeID(key
) == CFStringGetTypeID()) {
769 ctx
->reportProblem(errSecCSBadResource
, kSecCFErrorResourceMissing
,
770 CFTempURL(CFStringRef(key
), false, ctx
->code
.resourceBase()));
772 ctx
->reportProblem(errSecCSBadResource
, kSecCFErrorResourceSeal
, key
);
779 // Load, validate, cache, and return CFDictionary forms of sealed resources.
781 CFDictionaryRef
SecStaticCode::infoDictionary()
784 mInfoDict
.take(getDictionary(cdInfoSlot
, errSecCSInfoPlistFailed
));
785 secdebug("staticCode", "%p loaded InfoDict %p", this, mInfoDict
.get());
790 CFDictionaryRef
SecStaticCode::entitlements()
792 if (!mEntitlements
) {
794 if (CFDataRef entitlementData
= component(cdEntitlementSlot
)) {
795 validateComponent(cdEntitlementSlot
);
796 const EntitlementBlob
*blob
= reinterpret_cast<const EntitlementBlob
*>(CFDataGetBytePtr(entitlementData
));
797 if (blob
->validateBlob()) {
798 mEntitlements
.take(blob
->entitlements());
799 secdebug("staticCode", "%p loaded Entitlements %p", this, mEntitlements
.get());
801 // we do not consider a different blob type to be an error. We think it's a new format we don't understand
804 return mEntitlements
;
807 CFDictionaryRef
SecStaticCode::resourceDictionary(bool check
/* = true */)
809 if (mResourceDict
) // cached
810 return mResourceDict
;
811 if (CFRef
<CFDictionaryRef
> dict
= getDictionary(cdResourceDirSlot
, check
))
812 if (cfscan(dict
, "{rules=%Dn,files=%Dn}")) {
813 secdebug("staticCode", "%p loaded ResourceDict %p",
814 this, mResourceDict
.get());
815 return mResourceDict
= dict
;
823 // Load and cache the resource directory base.
824 // Note that the base is optional for each DiskRep.
826 CFURLRef
SecStaticCode::resourceBase()
828 if (!mGotResourceBase
) {
829 string base
= mRep
->resourcesRootPath();
831 mResourceBase
.take(makeCFURL(base
, true));
832 mGotResourceBase
= true;
834 return mResourceBase
;
839 // Load a component, validate it, convert it to a CFDictionary, and return that.
840 // This will force load and validation, which means that it will perform basic
841 // validation if it hasn't been done yet.
843 CFDictionaryRef
SecStaticCode::getDictionary(CodeDirectory::SpecialSlot slot
, bool check
/* = true */)
847 if (CFDataRef infoData
= component(slot
)) {
848 validateComponent(slot
);
849 if (CFDictionaryRef dict
= makeCFDictionaryFrom(infoData
))
852 MacOSError::throwMe(errSecCSBadDictionaryFormat
);
859 // Load, validate, and return a sealed resource.
860 // The resource data (loaded in to memory as a blob) is returned and becomes
861 // the responsibility of the caller; it is NOT cached by SecStaticCode.
863 // A resource that is not sealed will not be returned, and an error will be thrown.
864 // A missing resource will cause an error unless it's marked optional in the Directory.
865 // Under no circumstances will a corrupt resource be returned.
866 // NULL will only be returned for a resource that is neither sealed nor present
867 // (or that is sealed, absent, and marked optional).
868 // If the ResourceDictionary itself is not sealed, this function will always fail.
870 // There is currently no interface for partial retrieval of the resource data.
871 // (Since the ResourceDirectory does not currently support segmentation, all the
872 // data would have to be read anyway, but it could be read into a reusable buffer.)
874 CFDataRef
SecStaticCode::resource(string path
, ValidationContext
&ctx
)
876 if (CFDictionaryRef rdict
= resourceDictionary()) {
877 if (CFTypeRef file
= cfget(rdict
, "files.%s", path
.c_str())) {
878 ResourceSeal seal
= file
;
879 if (!resourceBase()) // no resources in DiskRep
880 MacOSError::throwMe(errSecCSResourcesNotFound
);
882 MacOSError::throwMe(errSecCSResourcesNotSealed
); // (it's nested code)
883 CFRef
<CFURLRef
> fullpath
= makeCFURL(path
, false, resourceBase());
884 if (CFRef
<CFDataRef
> data
= cfLoadFile(fullpath
)) {
885 MakeHash
<CodeDirectory
> hasher(this->codeDirectory());
886 hasher
->update(CFDataGetBytePtr(data
), CFDataGetLength(data
));
887 if (hasher
->verify(seal
.hash()))
888 return data
.yield(); // good
890 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // altered
892 if (!seal
.optional())
893 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceMissing
, fullpath
); // was sealed but is now missing
895 return NULL
; // validly missing
898 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAdded
, CFTempURL(path
, false, resourceBase()));
901 MacOSError::throwMe(errSecCSResourcesNotSealed
);
904 CFDataRef
SecStaticCode::resource(string path
)
906 ValidationContext ctx
;
907 return resource(path
, ctx
);
911 void SecStaticCode::validateResource(CFDictionaryRef files
, string path
, ValidationContext
&ctx
, SecCSFlags flags
, uint32_t version
)
913 if (!resourceBase()) // no resources in DiskRep
914 MacOSError::throwMe(errSecCSResourcesNotFound
);
915 CFRef
<CFURLRef
> fullpath
= makeCFURL(path
, false, resourceBase());
916 if (CFTypeRef file
= CFDictionaryGetValue(files
, CFTempString(path
))) {
917 ResourceSeal seal
= file
;
919 validateNestedCode(fullpath
, seal
, flags
);
920 } else if (seal
.link()) {
921 char target
[PATH_MAX
];
922 ssize_t len
= ::readlink(cfString(fullpath
).c_str(), target
, sizeof(target
)-1);
924 UnixError::check(-1);
926 if (cfString(seal
.link()) != target
)
927 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
);
928 } else if (seal
.hash()) { // genuine file
929 AutoFileDesc
fd(cfString(fullpath
), O_RDONLY
, FileDesc::modeMissingOk
); // open optional file
931 MakeHash
<CodeDirectory
> hasher(this->codeDirectory());
932 hashFileData(fd
, hasher
.get());
933 if (hasher
->verify(seal
.hash()))
934 return; // verify good
936 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // altered
938 if (!seal
.optional())
939 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceMissing
, fullpath
); // was sealed but is now missing
941 return; // validly missing
944 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAltered
, fullpath
); // changed type
947 if (version
== 1) { // version 1 ignores symlinks altogether
948 char target
[PATH_MAX
];
949 if (::readlink(cfString(fullpath
).c_str(), target
, sizeof(target
)) > 0)
952 ctx
.reportProblem(errSecCSBadResource
, kSecCFErrorResourceAdded
, CFTempURL(path
, false, resourceBase()));
955 void SecStaticCode::validateNestedCode(CFURLRef path
, const ResourceSeal
&seal
, SecCSFlags flags
)
957 CFRef
<SecRequirementRef
> req
;
958 if (SecRequirementCreateWithString(seal
.requirement(), kSecCSDefaultFlags
, &req
.aref()))
959 MacOSError::throwMe(errSecCSResourcesInvalid
);
961 // recursively verify this nested code
963 if (!(flags
& kSecCSCheckNestedCode
))
964 flags
|= kSecCSBasicValidateOnly
;
965 SecPointer
<SecStaticCode
> code
= new SecStaticCode(DiskRep::bestGuess(cfString(path
)));
966 code
->setMonitor(this->monitor());
967 code
->staticValidate(flags
, SecRequirement::required(req
));
968 } catch (CSError
&err
) {
969 if (err
.error
== errSecCSReqFailed
) {
970 mResourcesValidContext
->reportProblem(errSecCSBadNestedCode
, kSecCFErrorResourceAltered
, path
);
973 err
.augment(kSecCFErrorPath
, path
);
975 } catch (const MacOSError
&err
) {
976 if (err
.error
== errSecCSReqFailed
) {
977 mResourcesValidContext
->reportProblem(errSecCSBadNestedCode
, kSecCFErrorResourceAltered
, path
);
980 CSError::throwMe(err
.error
, kSecCFErrorPath
, path
);
986 // Test a CodeDirectory flag.
987 // Returns false if there is no CodeDirectory.
988 // May throw if the CodeDirectory is present but somehow invalid.
990 bool SecStaticCode::flag(uint32_t tested
)
992 if (const CodeDirectory
*cd
= this->codeDirectory(false))
993 return cd
->flags
& tested
;
1000 // Retrieve the full SuperBlob containing all internal requirements.
1002 const Requirements
*SecStaticCode::internalRequirements()
1004 if (CFDataRef reqData
= component(cdRequirementsSlot
)) {
1005 const Requirements
*req
= (const Requirements
*)CFDataGetBytePtr(reqData
);
1006 if (!req
->validateBlob())
1007 MacOSError::throwMe(errSecCSReqInvalid
);
1015 // Retrieve a particular internal requirement by type.
1017 const Requirement
*SecStaticCode::internalRequirement(SecRequirementType type
)
1019 if (const Requirements
*reqs
= internalRequirements())
1020 return reqs
->find
<Requirement
>(type
);
1027 // Return the Designated Requirement (DR). This can be either explicit in the
1028 // Internal Requirements component, or implicitly generated on demand here.
1029 // Note that an explicit DR may have been implicitly generated at signing time;
1030 // we don't distinguish this case.
1032 const Requirement
*SecStaticCode::designatedRequirement()
1034 if (const Requirement
*req
= internalRequirement(kSecDesignatedRequirementType
)) {
1035 return req
; // explicit in signing data
1037 if (!mDesignatedReq
)
1038 mDesignatedReq
= defaultDesignatedRequirement();
1039 return mDesignatedReq
;
1045 // Generate the default Designated Requirement (DR) for this StaticCode.
1046 // Ignore any explicit DR it may contain.
1048 const Requirement
*SecStaticCode::defaultDesignatedRequirement()
1050 if (flag(kSecCodeSignatureAdhoc
)) {
1051 // adhoc signature: return a cdhash requirement for all architectures
1052 __block
Requirement::Maker maker
;
1053 Requirement::Maker::Chain
chain(maker
, opOr
);
1055 // insert cdhash requirement for all architectures
1057 maker
.cdhash(this->cdHash());
1058 handleOtherArchitectures(^(SecStaticCode
*subcode
) {
1059 if (CFDataRef cdhash
= subcode
->cdHash()) {
1061 maker
.cdhash(cdhash
);
1064 return maker
.make();
1066 // full signature: Gin up full context and let DRMaker do its thing
1067 validateDirectory(); // need the cert chain
1068 Requirement::Context
context(this->certificates(),
1069 this->infoDictionary(),
1070 this->entitlements(),
1072 this->codeDirectory()
1074 return DRMaker(context
).make();
1080 // Validate a SecStaticCode against the internal requirement of a particular type.
1082 void SecStaticCode::validateRequirements(SecRequirementType type
, SecStaticCode
*target
,
1083 OSStatus nullError
/* = errSecSuccess */)
1085 DTRACK(CODESIGN_EVAL_STATIC_INTREQ
, this, type
, target
, nullError
);
1086 if (const Requirement
*req
= internalRequirement(type
))
1087 target
->validateRequirement(req
, nullError
? nullError
: errSecCSReqFailed
);
1089 MacOSError::throwMe(nullError
);
1096 // Validate this StaticCode against an external Requirement
1098 bool SecStaticCode::satisfiesRequirement(const Requirement
*req
, OSStatus failure
)
1101 validateDirectory();
1102 return req
->validates(Requirement::Context(mCertChain
, infoDictionary(), entitlements(), codeDirectory()->identifier(), codeDirectory()), failure
);
1105 void SecStaticCode::validateRequirement(const Requirement
*req
, OSStatus failure
)
1107 if (!this->satisfiesRequirement(req
, failure
))
1108 MacOSError::throwMe(failure
);
1113 // Retrieve one certificate from the cert chain.
1114 // Positive and negative indices can be used:
1115 // [ leaf, intermed-1, ..., intermed-n, anchor ]
1117 // Returns NULL if unavailable for any reason.
1119 SecCertificateRef
SecStaticCode::cert(int ix
)
1121 validateDirectory(); // need cert chain
1123 CFIndex length
= CFArrayGetCount(mCertChain
);
1126 if (ix
>= 0 && ix
< length
)
1127 return SecCertificateRef(CFArrayGetValueAtIndex(mCertChain
, ix
));
1132 CFArrayRef
SecStaticCode::certificates()
1134 validateDirectory(); // need cert chain
1140 // Gather (mostly) API-official information about this StaticCode.
1142 // This method lives in the twilight between the API and internal layers,
1143 // since it generates API objects (Sec*Refs) for return.
1145 CFDictionaryRef
SecStaticCode::signingInformation(SecCSFlags flags
)
1148 // Start with the pieces that we return even for unsigned code.
1149 // This makes Sec[Static]CodeRefs useful as API-level replacements
1150 // of our internal OSXCode objects.
1152 CFRef
<CFMutableDictionaryRef
> dict
= makeCFMutableDictionary(1,
1153 kSecCodeInfoMainExecutable
, CFTempURL(this->mainExecutablePath()).get()
1157 // If we're not signed, this is all you get
1159 if (!this->isSigned())
1160 return dict
.yield();
1163 // Add the generic attributes that we always include
1165 CFDictionaryAddValue(dict
, kSecCodeInfoIdentifier
, CFTempString(this->identifier()));
1166 CFDictionaryAddValue(dict
, kSecCodeInfoFlags
, CFTempNumber(this->codeDirectory(false)->flags
.get()));
1167 CFDictionaryAddValue(dict
, kSecCodeInfoFormat
, CFTempString(this->format()));
1168 CFDictionaryAddValue(dict
, kSecCodeInfoSource
, CFTempString(this->signatureSource()));
1169 CFDictionaryAddValue(dict
, kSecCodeInfoUnique
, this->cdHash());
1170 CFDictionaryAddValue(dict
, kSecCodeInfoDigestAlgorithm
, CFTempNumber(this->codeDirectory(false)->hashType
));
1173 // Deliver any Info.plist only if it looks intact
1176 if (CFDictionaryRef info
= this->infoDictionary())
1177 CFDictionaryAddValue(dict
, kSecCodeInfoPList
, info
);
1178 } catch (...) { } // don't deliver Info.plist if questionable
1181 // kSecCSSigningInformation adds information about signing certificates and chains
1183 if (flags
& kSecCSSigningInformation
)
1185 if (CFArrayRef certs
= this->certificates())
1186 CFDictionaryAddValue(dict
, kSecCodeInfoCertificates
, certs
);
1187 if (CFDataRef sig
= this->signature())
1188 CFDictionaryAddValue(dict
, kSecCodeInfoCMS
, sig
);
1190 CFDictionaryAddValue(dict
, kSecCodeInfoTrust
, mTrust
);
1191 if (CFAbsoluteTime time
= this->signingTime())
1192 if (CFRef
<CFDateRef
> date
= CFDateCreate(NULL
, time
))
1193 CFDictionaryAddValue(dict
, kSecCodeInfoTime
, date
);
1194 if (CFAbsoluteTime time
= this->signingTimestamp())
1195 if (CFRef
<CFDateRef
> date
= CFDateCreate(NULL
, time
))
1196 CFDictionaryAddValue(dict
, kSecCodeInfoTimestamp
, date
);
1197 if (const char *teamID
= this->teamID())
1198 CFDictionaryAddValue(dict
, kSecCodeInfoTeamIdentifier
, CFTempString(teamID
));
1202 // kSecCSRequirementInformation adds information on requirements
1204 if (flags
& kSecCSRequirementInformation
)
1206 if (const Requirements
*reqs
= this->internalRequirements()) {
1207 CFDictionaryAddValue(dict
, kSecCodeInfoRequirements
,
1208 CFTempString(Dumper::dump(reqs
)));
1209 CFDictionaryAddValue(dict
, kSecCodeInfoRequirementData
, CFTempData(*reqs
));
1212 const Requirement
*dreq
= this->designatedRequirement();
1213 CFRef
<SecRequirementRef
> dreqRef
= (new SecRequirement(dreq
))->handle();
1214 CFDictionaryAddValue(dict
, kSecCodeInfoDesignatedRequirement
, dreqRef
);
1215 if (this->internalRequirement(kSecDesignatedRequirementType
)) { // explicit
1216 CFRef
<SecRequirementRef
> ddreqRef
= (new SecRequirement(this->defaultDesignatedRequirement(), true))->handle();
1217 CFDictionaryAddValue(dict
, kSecCodeInfoImplicitDesignatedRequirement
, ddreqRef
);
1218 } else { // implicit
1219 CFDictionaryAddValue(dict
, kSecCodeInfoImplicitDesignatedRequirement
, dreqRef
);
1224 if (CFDataRef ent
= this->component(cdEntitlementSlot
)) {
1225 CFDictionaryAddValue(dict
, kSecCodeInfoEntitlements
, ent
);
1226 if (CFDictionaryRef entdict
= this->entitlements())
1227 CFDictionaryAddValue(dict
, kSecCodeInfoEntitlementsDict
, entdict
);
1232 // kSecCSInternalInformation adds internal information meant to be for Apple internal
1233 // use (SPI), and not guaranteed to be stable. Primarily, this is data we want
1234 // to reliably transmit through the API wall so that code outside the Security.framework
1235 // can use it without having to play nasty tricks to get it.
1237 if (flags
& kSecCSInternalInformation
)
1240 CFDictionaryAddValue(dict
, kSecCodeInfoCodeDirectory
, mDir
);
1241 CFDictionaryAddValue(dict
, kSecCodeInfoCodeOffset
, CFTempNumber(mRep
->signingBase()));
1242 if (CFRef
<CFDictionaryRef
> rdict
= getDictionary(cdResourceDirSlot
, false)) // suppress validation
1243 CFDictionaryAddValue(dict
, kSecCodeInfoResourceDirectory
, rdict
);
1248 // kSecCSContentInformation adds more information about the physical layout
1249 // of the signed code. This is (only) useful for packaging or patching-oriented
1252 if (flags
& kSecCSContentInformation
)
1253 if (CFRef
<CFArrayRef
> files
= mRep
->modifiedFiles())
1254 CFDictionaryAddValue(dict
, kSecCodeInfoChangedFiles
, files
);
1256 return dict
.yield();
1261 // Resource validation contexts.
1262 // The default context simply throws a CSError, rudely terminating the operation.
1264 SecStaticCode::ValidationContext::~ValidationContext()
1267 void SecStaticCode::ValidationContext::reportProblem(OSStatus rc
, CFStringRef type
, CFTypeRef value
)
1269 CSError::throwMe(rc
, type
, value
);
1272 void SecStaticCode::CollectingContext::reportProblem(OSStatus rc
, CFStringRef type
, CFTypeRef value
)
1274 if (mStatus
== errSecSuccess
)
1275 mStatus
= rc
; // record first failure for eventual error return
1278 mCollection
.take(makeCFMutableDictionary());
1279 CFMutableArrayRef element
= CFMutableArrayRef(CFDictionaryGetValue(mCollection
, type
));
1281 element
= makeCFMutableArray(0);
1284 CFDictionaryAddValue(mCollection
, type
, element
);
1287 CFArrayAppendValue(element
, value
);
1291 void SecStaticCode::CollectingContext::throwMe()
1293 assert(mStatus
!= errSecSuccess
);
1294 throw CSError(mStatus
, mCollection
.retain());
1299 // Master validation driver.
1300 // This is the static validation (only) driver for the API.
1302 // SecStaticCode exposes an à la carte menu of topical validators applying
1303 // to a given object. The static validation API pulls the together reliably,
1304 // but it also adds two matrix dimensions: architecture (for "fat" Mach-O binaries)
1305 // and nested code. This function will crawl a suitable cross-section of this
1306 // validation matrix based on which options it is given, creating temporary
1307 // SecStaticCode objects on the fly to complete the task.
1308 // (The point, of course, is to do as little duplicate work as possible.)
1310 void SecStaticCode::staticValidate(SecCSFlags flags
, const SecRequirement
*req
)
1312 // core components: once per architecture (if any)
1313 this->staticValidateCore(flags
, req
);
1314 if (flags
& kSecCSCheckAllArchitectures
)
1315 handleOtherArchitectures(^(SecStaticCode
* subcode
) {
1316 subcode
->detachedSignature(this->mDetachedSig
); // carry over explicit (but not implicit) architecture
1317 subcode
->staticValidateCore(flags
, req
);
1320 // resources: once for all architectures
1321 if (!(flags
& kSecCSDoNotValidateResources
))
1322 this->validateResources(flags
);
1324 // allow monitor intervention
1325 if (CFRef
<CFTypeRef
> veto
= reportEvent(CFSTR("validated"), NULL
)) {
1326 if (CFGetTypeID(veto
) == CFNumberGetTypeID())
1327 MacOSError::throwMe(cfNumber
<OSStatus
>(veto
.as
<CFNumberRef
>()));
1329 MacOSError::throwMe(errSecCSBadCallbackValue
);
1333 void SecStaticCode::staticValidateCore(SecCSFlags flags
, const SecRequirement
*req
)
1336 this->validateNonResourceComponents(); // also validates the CodeDirectory
1337 if (!(flags
& kSecCSDoNotValidateExecutable
))
1338 this->validateExecutable();
1340 this->validateRequirement(req
->requirement(), errSecCSReqFailed
);
1341 } catch (CSError
&err
) {
1342 if (Universal
*fat
= this->diskRep()->mainExecutableImage()) // Mach-O
1343 if (MachO
*mach
= fat
->architecture()) {
1344 err
.augment(kSecCFErrorArchitecture
, CFTempString(mach
->architecture().displayName()));
1348 } catch (const MacOSError
&err
) {
1349 // add architecture information if we can get it
1350 if (Universal
*fat
= this->diskRep()->mainExecutableImage())
1351 if (MachO
*mach
= fat
->architecture()) {
1352 CFTempString
arch(mach
->architecture().displayName());
1354 CSError::throwMe(err
.error
, kSecCFErrorArchitecture
, arch
);
1362 // A helper that generates SecStaticCode objects for all but the primary architecture
1363 // of a fat binary and calls a block on them.
1364 // If there's only one architecture (or this is an architecture-agnostic code),
1365 // nothing happens quickly.
1367 void SecStaticCode::handleOtherArchitectures(void (^handle
)(SecStaticCode
* other
))
1369 if (Universal
*fat
= this->diskRep()->mainExecutableImage()) {
1370 Universal::Architectures architectures
;
1371 fat
->architectures(architectures
);
1372 if (architectures
.size() > 1) {
1373 DiskRep::Context ctx
;
1374 size_t activeOffset
= fat
->archOffset();
1375 for (Universal::Architectures::const_iterator arch
= architectures
.begin(); arch
!= architectures
.end(); ++arch
) {
1376 ctx
.offset
= fat
->archOffset(*arch
);
1377 if (ctx
.offset
!= activeOffset
) { // inactive architecture; check it
1378 SecPointer
<SecStaticCode
> subcode
= new SecStaticCode(DiskRep::bestGuess(this->mainExecutablePath(), &ctx
));
1379 subcode
->detachedSignature(this->mDetachedSig
); // carry over explicit (but not implicit) detached signature
1380 if (this->teamID() == NULL
|| subcode
->teamID() == NULL
) {
1381 if (this->teamID() != subcode
->teamID())
1382 MacOSError::throwMe(errSecCSSignatureInvalid
);
1383 } else if (strcmp(this->teamID(), subcode
->teamID()) != 0)
1384 MacOSError::throwMe(errSecCSSignatureInvalid
);
1393 // A method that takes a certificate chain (certs) and evaluates
1394 // if it is a Mac or IPhone developer cert, an app store distribution cert,
1395 // or a developer ID
1397 bool SecStaticCode::isAppleDeveloperCert(CFArrayRef certs
)
1399 static const std::string appleDeveloperRequirement
= "(" + std::string(WWDRRequirement
) + ") or (" + developerID
+ ") or (" + distributionCertificate
+ ") or (" + iPhoneDistributionCert
+ ")";
1400 SecRequirement
*req
= new SecRequirement(parseRequirement(appleDeveloperRequirement
), true);
1401 Requirement::Context
ctx(certs
, NULL
, NULL
, "", NULL
);
1403 return req
->requirement()->validates(ctx
);
1406 } // end namespace CodeSigning
1407 } // end namespace Security