]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_codesigning/lib/StaticCode.cpp
Security-57336.1.9.tar.gz
[apple/security.git] / OSX / libsecurity_codesigning / lib / StaticCode.cpp
1 /*
2 * Copyright (c) 2006-2014 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
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
11 * file.
12 *
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.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 //
25 // StaticCode - SecStaticCode API objects
26 //
27 #include "StaticCode.h"
28 #include "Code.h"
29 #include "reqmaker.h"
30 #include "drmaker.h"
31 #include "reqdumper.h"
32 #include "reqparser.h"
33 #include "sigblob.h"
34 #include "resources.h"
35 #include "detachedrep.h"
36 #include "csdatabase.h"
37 #include "dirscanner.h"
38 #include <CoreFoundation/CFURLAccess.h>
39 #include <Security/SecPolicyPriv.h>
40 #include <Security/SecTrustPriv.h>
41 #include <Security/SecCertificatePriv.h>
42 #include <Security/CMSPrivate.h>
43 #include <Security/SecCmsContentInfo.h>
44 #include <Security/SecCmsSignerInfo.h>
45 #include <Security/SecCmsSignedData.h>
46 #include <Security/cssmapplePriv.h>
47 #include <security_utilities/unix++.h>
48 #include <security_utilities/cfmunge.h>
49 #include <Security/CMSDecoder.h>
50 #include <security_utilities/logging.h>
51 #include <dirent.h>
52 #include <sstream>
53 #include <IOKit/storage/IOStorageDeviceCharacteristics.h>
54 #include <dispatch/private.h>
55
56
57 namespace Security {
58 namespace CodeSigning {
59
60 using namespace UnixPlusPlus;
61
62 // A requirement representing a Mac or iOS dev cert, a Mac or iOS distribution cert, or a developer ID
63 static const char WWDRRequirement[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.2] exists";
64 static const char MACWWDRRequirement[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.12] exists";
65 static const char developerID[] = "anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists"
66 " and certificate leaf[field.1.2.840.113635.100.6.1.13] exists";
67 static const char distributionCertificate[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.7] exists";
68 static const char iPhoneDistributionCert[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.4] exists";
69
70 //
71 // Map a component slot number to a suitable error code for a failure
72 //
73 static inline OSStatus errorForSlot(CodeDirectory::SpecialSlot slot)
74 {
75 switch (slot) {
76 case cdInfoSlot:
77 return errSecCSInfoPlistFailed;
78 case cdResourceDirSlot:
79 return errSecCSResourceDirectoryFailed;
80 default:
81 return errSecCSSignatureFailed;
82 }
83 }
84
85
86 //
87 // Construct a SecStaticCode object given a disk representation object
88 //
89 SecStaticCode::SecStaticCode(DiskRep *rep)
90 : mRep(rep),
91 mValidated(false), mExecutableValidated(false), mResourcesValidated(false), mResourcesValidContext(NULL),
92 mProgressQueue("com.apple.security.validation-progress", false, DISPATCH_QUEUE_PRIORITY_DEFAULT),
93 mOuterScope(NULL), mResourceScope(NULL),
94 mDesignatedReq(NULL), mGotResourceBase(false), mMonitor(NULL), mLimitedAsync(NULL), mEvalDetails(NULL)
95 {
96 CODESIGN_STATIC_CREATE(this, rep);
97 CFRef<CFDataRef> codeDirectory = rep->codeDirectory();
98 if (codeDirectory && CFDataGetLength(codeDirectory) <= 0)
99 MacOSError::throwMe(errSecCSSignatureInvalid);
100 checkForSystemSignature();
101 }
102
103
104 //
105 // Clean up a SecStaticCode object
106 //
107 SecStaticCode::~SecStaticCode() throw()
108 try {
109 ::free(const_cast<Requirement *>(mDesignatedReq));
110 delete mResourcesValidContext;
111 delete mLimitedAsync;
112 } catch (...) {
113 return;
114 }
115
116 //
117 // Initialize a nested SecStaticCode object from its parent
118 //
119 void SecStaticCode::initializeFromParent(const SecStaticCode& parent) {
120 mOuterScope = &parent;
121 setMonitor(parent.monitor());
122 if (parent.mLimitedAsync)
123 mLimitedAsync = new LimitedAsync(*parent.mLimitedAsync);
124 }
125
126 //
127 // CF-level comparison of SecStaticCode objects compares CodeDirectory hashes if signed,
128 // and falls back on comparing canonical paths if (both are) not.
129 //
130 bool SecStaticCode::equal(SecCFObject &secOther)
131 {
132 SecStaticCode *other = static_cast<SecStaticCode *>(&secOther);
133 CFDataRef mine = this->cdHash();
134 CFDataRef his = other->cdHash();
135 if (mine || his)
136 return mine && his && CFEqual(mine, his);
137 else
138 return CFEqual(CFRef<CFURLRef>(this->copyCanonicalPath()), CFRef<CFURLRef>(other->copyCanonicalPath()));
139 }
140
141 CFHashCode SecStaticCode::hash()
142 {
143 if (CFDataRef h = this->cdHash())
144 return CFHash(h);
145 else
146 return CFHash(CFRef<CFURLRef>(this->copyCanonicalPath()));
147 }
148
149
150 //
151 // Invoke a stage monitor if registered
152 //
153 CFTypeRef SecStaticCode::reportEvent(CFStringRef stage, CFDictionaryRef info)
154 {
155 if (mMonitor)
156 return mMonitor(this->handle(false), stage, info);
157 else
158 return NULL;
159 }
160
161 void SecStaticCode::prepareProgress(unsigned int workload)
162 {
163 dispatch_sync(mProgressQueue, ^{
164 mCancelPending = false; // not cancelled
165 });
166 if (mValidationFlags & kSecCSReportProgress) {
167 mCurrentWork = 0; // nothing done yet
168 mTotalWork = workload; // totally fake - we don't know how many files we'll get to chew
169 }
170 }
171
172 void SecStaticCode::reportProgress(unsigned amount /* = 1 */)
173 {
174 if (mMonitor && (mValidationFlags & kSecCSReportProgress)) {
175 // update progress and report
176 __block bool cancel = false;
177 dispatch_sync(mProgressQueue, ^{
178 if (mCancelPending)
179 cancel = true;
180 mCurrentWork += amount;
181 mMonitor(this->handle(false), CFSTR("progress"), CFTemp<CFDictionaryRef>("{current=%d,total=%d}", mCurrentWork, mTotalWork));
182 });
183 // if cancellation is pending, abort now
184 if (cancel)
185 MacOSError::throwMe(errSecCSCancelled);
186 }
187 }
188
189
190 //
191 // Set validation conditions for fine-tuning legacy tolerance
192 //
193 static void addError(CFTypeRef cfError, void* context)
194 {
195 if (CFGetTypeID(cfError) == CFNumberGetTypeID()) {
196 int64_t error;
197 CFNumberGetValue(CFNumberRef(cfError), kCFNumberSInt64Type, (void*)&error);
198 MacOSErrorSet* errors = (MacOSErrorSet*)context;
199 errors->insert(OSStatus(error));
200 }
201 }
202
203 void SecStaticCode::setValidationModifiers(CFDictionaryRef conditions)
204 {
205 if (conditions) {
206 CFDictionary source(conditions, errSecCSDbCorrupt);
207 mAllowOmissions = source.get<CFArrayRef>("omissions");
208 if (CFArrayRef errors = source.get<CFArrayRef>("errors"))
209 CFArrayApplyFunction(errors, CFRangeMake(0, CFArrayGetCount(errors)), addError, &this->mTolerateErrors);
210 }
211 }
212
213
214 //
215 // Request cancellation of a validation in progress.
216 // We do this by posting an abort flag that is checked periodically.
217 //
218 void SecStaticCode::cancelValidation()
219 {
220 if (!(mValidationFlags & kSecCSReportProgress)) // not using progress reporting; cancel won't make it through
221 MacOSError::throwMe(errSecCSInvalidFlags);
222 dispatch_assert_queue(mProgressQueue);
223 mCancelPending = true;
224 }
225
226
227 //
228 // Attach a detached signature.
229 //
230 void SecStaticCode::detachedSignature(CFDataRef sigData)
231 {
232 if (sigData) {
233 mDetachedSig = sigData;
234 mRep = new DetachedRep(sigData, mRep->base(), "explicit detached");
235 CODESIGN_STATIC_ATTACH_EXPLICIT(this, mRep);
236 } else {
237 mDetachedSig = NULL;
238 mRep = mRep->base();
239 CODESIGN_STATIC_ATTACH_EXPLICIT(this, NULL);
240 }
241 }
242
243
244 //
245 // Consult the system detached signature database to see if it contains
246 // a detached signature for this StaticCode. If it does, fetch and attach it.
247 // We do this only if the code has no signature already attached.
248 //
249 void SecStaticCode::checkForSystemSignature()
250 {
251 if (!this->isSigned()) {
252 SignatureDatabase db;
253 if (db.isOpen())
254 try {
255 if (RefPointer<DiskRep> dsig = db.findCode(mRep)) {
256 CODESIGN_STATIC_ATTACH_SYSTEM(this, dsig);
257 mRep = dsig;
258 }
259 } catch (...) {
260 }
261 }
262 }
263
264
265 //
266 // Return a descriptive string identifying the source of the code signature
267 //
268 string SecStaticCode::signatureSource()
269 {
270 if (!isSigned())
271 return "unsigned";
272 if (DetachedRep *rep = dynamic_cast<DetachedRep *>(mRep.get()))
273 return rep->source();
274 return "embedded";
275 }
276
277
278 //
279 // Do ::required, but convert incoming SecCodeRefs to their SecStaticCodeRefs
280 // (if possible).
281 //
282 SecStaticCode *SecStaticCode::requiredStatic(SecStaticCodeRef ref)
283 {
284 SecCFObject *object = SecCFObject::required(ref, errSecCSInvalidObjectRef);
285 if (SecStaticCode *scode = dynamic_cast<SecStaticCode *>(object))
286 return scode;
287 else if (SecCode *code = dynamic_cast<SecCode *>(object))
288 return code->staticCode();
289 else // neither (a SecSomethingElse)
290 MacOSError::throwMe(errSecCSInvalidObjectRef);
291 }
292
293 SecCode *SecStaticCode::optionalDynamic(SecStaticCodeRef ref)
294 {
295 SecCFObject *object = SecCFObject::required(ref, errSecCSInvalidObjectRef);
296 if (dynamic_cast<SecStaticCode *>(object))
297 return NULL;
298 else if (SecCode *code = dynamic_cast<SecCode *>(object))
299 return code;
300 else // neither (a SecSomethingElse)
301 MacOSError::throwMe(errSecCSInvalidObjectRef);
302 }
303
304
305 //
306 // Void all cached validity data.
307 //
308 // We also throw out cached components, because the new signature data may have
309 // a different idea of what components should be present. We could reconcile the
310 // cached data instead, if performance seems to be impacted.
311 //
312 void SecStaticCode::resetValidity()
313 {
314 CODESIGN_EVAL_STATIC_RESET(this);
315 mValidated = false;
316 mExecutableValidated = mResourcesValidated = false;
317 if (mResourcesValidContext) {
318 delete mResourcesValidContext;
319 mResourcesValidContext = NULL;
320 }
321 mDir = NULL;
322 mSignature = NULL;
323 for (unsigned n = 0; n < cdSlotCount; n++)
324 mCache[n] = NULL;
325 mInfoDict = NULL;
326 mEntitlements = NULL;
327 mResourceDict = NULL;
328 mDesignatedReq = NULL;
329 mCDHash = NULL;
330 mGotResourceBase = false;
331 mTrust = NULL;
332 mCertChain = NULL;
333 mEvalDetails = NULL;
334 mRep->flush();
335
336 // we may just have updated the system database, so check again
337 checkForSystemSignature();
338 }
339
340
341 //
342 // Retrieve a sealed component by special slot index.
343 // If the CodeDirectory has already been validated, validate against that.
344 // Otherwise, retrieve the component without validation (but cache it). Validation
345 // will go through the cache and validate all cached components.
346 //
347 CFDataRef SecStaticCode::component(CodeDirectory::SpecialSlot slot, OSStatus fail /* = errSecCSSignatureFailed */)
348 {
349 assert(slot <= cdSlotMax);
350
351 CFRef<CFDataRef> &cache = mCache[slot];
352 if (!cache) {
353 if (CFRef<CFDataRef> data = mRep->component(slot)) {
354 if (validated()) { // if the directory has been validated...
355 if (!codeDirectory()->slotIsPresent(-slot))
356 return NULL;
357
358 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data), // ... and it's no good
359 CFDataGetLength(data), -slot))
360 MacOSError::throwMe(errorForSlot(slot)); // ... then bail
361 }
362 cache = data; // it's okay, cache it
363 } else { // absent, mark so
364 if (validated()) // if directory has been validated...
365 if (codeDirectory()->slotIsPresent(-slot)) // ... and the slot is NOT missing
366 MacOSError::throwMe(errorForSlot(slot)); // was supposed to be there
367 cache = CFDataRef(kCFNull); // white lie
368 }
369 }
370 return (cache == CFDataRef(kCFNull)) ? NULL : cache.get();
371 }
372
373
374 //
375 // Get the CodeDirectory.
376 // Throws (if check==true) or returns NULL (check==false) if there is none.
377 // Always throws if the CodeDirectory exists but is invalid.
378 // NEVER validates against the signature.
379 //
380 const CodeDirectory *SecStaticCode::codeDirectory(bool check /* = true */)
381 {
382 if (!mDir) {
383 if (mDir.take(mRep->codeDirectory())) {
384 const CodeDirectory *dir = reinterpret_cast<const CodeDirectory *>(CFDataGetBytePtr(mDir));
385 if (!dir->validateBlob(CFDataGetLength(mDir)))
386 MacOSError::throwMe(errSecCSSignatureInvalid);
387 dir->checkIntegrity();
388 }
389 }
390 if (mDir)
391 return reinterpret_cast<const CodeDirectory *>(CFDataGetBytePtr(mDir));
392 if (check)
393 MacOSError::throwMe(errSecCSUnsigned);
394 return NULL;
395 }
396
397
398 //
399 // Get the hash of the CodeDirectory.
400 // Returns NULL if there is none.
401 //
402 CFDataRef SecStaticCode::cdHash()
403 {
404 if (!mCDHash) {
405 if (const CodeDirectory *cd = codeDirectory(false)) {
406 mCDHash.take(cd->cdhash());
407 CODESIGN_STATIC_CDHASH(this, CFDataGetBytePtr(mCDHash), (unsigned int)CFDataGetLength(mCDHash));
408 }
409 }
410 return mCDHash;
411 }
412
413
414 //
415 // Return the CMS signature blob; NULL if none found.
416 //
417 CFDataRef SecStaticCode::signature()
418 {
419 if (!mSignature)
420 mSignature.take(mRep->signature());
421 if (mSignature)
422 return mSignature;
423 MacOSError::throwMe(errSecCSUnsigned);
424 }
425
426
427 //
428 // Verify the signature on the CodeDirectory.
429 // If this succeeds (doesn't throw), the CodeDirectory is statically trustworthy.
430 // Any outcome (successful or not) is cached for the lifetime of the StaticCode.
431 //
432 void SecStaticCode::validateDirectory()
433 {
434 // echo previous outcome, if any
435 // track revocation separately, as it may not have been checked
436 // during the initial validation
437 if (!validated() || ((mValidationFlags & kSecCSEnforceRevocationChecks) && !revocationChecked()))
438 try {
439 // perform validation (or die trying)
440 CODESIGN_EVAL_STATIC_DIRECTORY(this);
441 mValidationExpired = verifySignature();
442 if (mValidationFlags & kSecCSEnforceRevocationChecks)
443 mRevocationChecked = true;
444
445 for (CodeDirectory::SpecialSlot slot = codeDirectory()->maxSpecialSlot(); slot >= 1; --slot)
446 if (mCache[slot]) // if we already loaded that resource...
447 validateComponent(slot, errorForSlot(slot)); // ... then check it now
448 mValidated = true; // we've done the deed...
449 mValidationResult = errSecSuccess; // ... and it was good
450 } catch (const CommonError &err) {
451 mValidated = true;
452 mValidationResult = err.osStatus();
453 throw;
454 } catch (...) {
455 secdebug("staticCode", "%p validation threw non-common exception", this);
456 mValidated = true;
457 mValidationResult = errSecCSInternalError;
458 throw;
459 }
460 assert(validated());
461 if (mValidationResult == errSecSuccess) {
462 if (mValidationExpired)
463 if ((mValidationFlags & kSecCSConsiderExpiration)
464 || (codeDirectory()->flags & kSecCodeSignatureForceExpiration))
465 MacOSError::throwMe(CSSMERR_TP_CERT_EXPIRED);
466 } else
467 MacOSError::throwMe(mValidationResult);
468 }
469
470
471 //
472 // Load and validate the CodeDirectory and all components *except* those related to the resource envelope.
473 // Those latter components are checked by validateResources().
474 //
475 void SecStaticCode::validateNonResourceComponents()
476 {
477 this->validateDirectory();
478 for (CodeDirectory::SpecialSlot slot = codeDirectory()->maxSpecialSlot(); slot >= 1; --slot)
479 switch (slot) {
480 case cdResourceDirSlot: // validated by validateResources
481 break;
482 default:
483 this->component(slot); // loads and validates
484 break;
485 }
486 }
487
488
489 //
490 // Get the (signed) signing date from the code signature.
491 // Sadly, we need to validate the signature to get the date (as a side benefit).
492 // This means that you can't get the signing time for invalidly signed code.
493 //
494 // We could run the decoder "almost to" verification to avoid this, but there seems
495 // little practical point to such a duplication of effort.
496 //
497 CFAbsoluteTime SecStaticCode::signingTime()
498 {
499 validateDirectory();
500 return mSigningTime;
501 }
502
503 CFAbsoluteTime SecStaticCode::signingTimestamp()
504 {
505 validateDirectory();
506 return mSigningTimestamp;
507 }
508
509
510 //
511 // Verify the CMS signature on the CodeDirectory.
512 // This performs the cryptographic tango. It returns if the signature is valid,
513 // or throws if it is not. As a side effect, a successful return sets up the
514 // cached certificate chain for future use.
515 // Returns true if the signature is expired (the X.509 sense), false if it's not.
516 // Expiration is fatal (throws) if a secure timestamp is included, but not otherwise.
517 //
518 bool SecStaticCode::verifySignature()
519 {
520 // ad-hoc signed code is considered validly signed by definition
521 if (flag(kSecCodeSignatureAdhoc)) {
522 CODESIGN_EVAL_STATIC_SIGNATURE_ADHOC(this);
523 return false;
524 }
525
526 DTRACK(CODESIGN_EVAL_STATIC_SIGNATURE, this, (char*)this->mainExecutablePath().c_str());
527
528 // decode CMS and extract SecTrust for verification
529 CFRef<CMSDecoderRef> cms;
530 MacOSError::check(CMSDecoderCreate(&cms.aref())); // create decoder
531 CFDataRef sig = this->signature();
532 MacOSError::check(CMSDecoderUpdateMessage(cms, CFDataGetBytePtr(sig), CFDataGetLength(sig)));
533 this->codeDirectory(); // load CodeDirectory (sets mDir)
534 MacOSError::check(CMSDecoderSetDetachedContent(cms, mDir));
535 MacOSError::check(CMSDecoderFinalizeMessage(cms));
536 MacOSError::check(CMSDecoderSetSearchKeychain(cms, cfEmptyArray()));
537 CFRef<CFArrayRef> vf_policies = verificationPolicies();
538 CFRef<CFArrayRef> ts_policies = SecPolicyCreateAppleTimeStampingAndRevocationPolicies(vf_policies);
539 CMSSignerStatus status;
540 MacOSError::check(CMSDecoderCopySignerStatus(cms, 0, vf_policies,
541 false, &status, &mTrust.aref(), NULL));
542
543 if (status != kCMSSignerValid) {
544 const char *reason;
545 switch (status) {
546 case kCMSSignerUnsigned: reason="kCMSSignerUnsigned"; break;
547 case kCMSSignerNeedsDetachedContent: reason="kCMSSignerNeedsDetachedContent"; break;
548 case kCMSSignerInvalidSignature: reason="kCMSSignerInvalidSignature"; break;
549 case kCMSSignerInvalidCert: reason="kCMSSignerInvalidCert"; break;
550 case kCMSSignerInvalidIndex: reason="kCMSSignerInvalidIndex"; break;
551 default: reason="unknown"; break;
552 }
553 Security::Syslog::error("CMSDecoderCopySignerStatus failed with %s error (%d)",
554 reason, (int)status);
555 MacOSError::throwMe(errSecCSSignatureFailed);
556 }
557
558 // internal signing time (as specified by the signer; optional)
559 mSigningTime = 0; // "not present" marker (nobody could code sign on Jan 1, 2001 :-)
560 switch (OSStatus rc = CMSDecoderCopySignerSigningTime(cms, 0, &mSigningTime)) {
561 case errSecSuccess:
562 case errSecSigningTimeMissing:
563 break;
564 default:
565 Security::Syslog::error("Could not get signing time (error %d)", (int)rc);
566 MacOSError::throwMe(rc);
567 }
568
569 // certified signing time (as specified by a TSA; optional)
570 mSigningTimestamp = 0;
571 switch (OSStatus rc = CMSDecoderCopySignerTimestampWithPolicy(cms, ts_policies, 0, &mSigningTimestamp)) {
572 case errSecSuccess:
573 case errSecTimestampMissing:
574 break;
575 default:
576 Security::Syslog::error("Could not get timestamp (error %d)", (int)rc);
577 MacOSError::throwMe(rc);
578 }
579
580 // set up the environment for SecTrust
581 if (mValidationFlags & kSecCSNoNetworkAccess) {
582 MacOSError::check(SecTrustSetNetworkFetchAllowed(mTrust,false)); // no network?
583 }
584 MacOSError::check(SecTrustSetKeychains(mTrust, cfEmptyArray())); // no keychains
585
586 CSSM_APPLE_TP_ACTION_DATA actionData = {
587 CSSM_APPLE_TP_ACTION_VERSION, // version of data structure
588 0 // action flags
589 };
590
591 if (!(mValidationFlags & kSecCSCheckTrustedAnchors)) {
592 /* no need to evaluate anchor trust when building cert chain */
593 MacOSError::check(SecTrustSetAnchorCertificates(mTrust, cfEmptyArray())); // no anchors
594 actionData.ActionFlags |= CSSM_TP_ACTION_IMPLICIT_ANCHORS; // action flags
595 }
596
597 for (;;) { // at most twice
598 MacOSError::check(SecTrustSetParameters(mTrust,
599 CSSM_TP_ACTION_DEFAULT, CFTempData(&actionData, sizeof(actionData))));
600
601 // evaluate trust and extract results
602 SecTrustResultType trustResult;
603 MacOSError::check(SecTrustEvaluate(mTrust, &trustResult));
604 MacOSError::check(SecTrustGetResult(mTrust, &trustResult, &mCertChain.aref(), &mEvalDetails));
605
606 // if this is an Apple developer cert....
607 if (teamID() && SecStaticCode::isAppleDeveloperCert(mCertChain)) {
608 CFRef<CFStringRef> teamIDFromCert;
609 if (CFArrayGetCount(mCertChain) > 0) {
610 /* Note that SecCertificateCopySubjectComponent sets the out parameter to NULL if there is no field present */
611 MacOSError::check(SecCertificateCopySubjectComponent((SecCertificateRef)CFArrayGetValueAtIndex(mCertChain, Requirement::leafCert),
612 &CSSMOID_OrganizationalUnitName,
613 &teamIDFromCert.aref()));
614
615 if (teamIDFromCert) {
616 CFRef<CFStringRef> teamIDFromCD = CFStringCreateWithCString(NULL, teamID(), kCFStringEncodingUTF8);
617 if (!teamIDFromCD) {
618 Security::Syslog::error("Could not get team identifier (%s)", teamID());
619 MacOSError::throwMe(errSecCSInternalError);
620 }
621
622 if (CFStringCompare(teamIDFromCert, teamIDFromCD, 0) != kCFCompareEqualTo) {
623 Security::Syslog::error("Team identifier in the signing certificate (%s) does not match the team identifier (%s) in the code directory", cfString(teamIDFromCert).c_str(), teamID());
624 MacOSError::throwMe(errSecCSSignatureInvalid);
625 }
626 }
627 }
628 }
629
630 CODESIGN_EVAL_STATIC_SIGNATURE_RESULT(this, trustResult, mCertChain ? (int)CFArrayGetCount(mCertChain) : 0);
631 switch (trustResult) {
632 case kSecTrustResultProceed:
633 case kSecTrustResultUnspecified:
634 break; // success
635 case kSecTrustResultDeny:
636 MacOSError::throwMe(CSSMERR_APPLETP_TRUST_SETTING_DENY); // user reject
637 case kSecTrustResultInvalid:
638 assert(false); // should never happen
639 MacOSError::throwMe(CSSMERR_TP_NOT_TRUSTED);
640 default:
641 {
642 OSStatus result;
643 MacOSError::check(SecTrustGetCssmResultCode(mTrust, &result));
644 // if we have a valid timestamp, CMS validates against (that) signing time and all is well.
645 // If we don't have one, may validate against *now*, and must be able to tolerate expiration.
646 if (mSigningTimestamp == 0) { // no timestamp available
647 if (((result == CSSMERR_TP_CERT_EXPIRED) || (result == CSSMERR_TP_CERT_NOT_VALID_YET))
648 && !(actionData.ActionFlags & CSSM_TP_ACTION_ALLOW_EXPIRED)) {
649 CODESIGN_EVAL_STATIC_SIGNATURE_EXPIRED(this);
650 actionData.ActionFlags |= CSSM_TP_ACTION_ALLOW_EXPIRED; // (this also allows postdated certs)
651 continue; // retry validation while tolerating expiration
652 }
653 }
654 Security::Syslog::error("SecStaticCode: verification failed (trust result %d, error %d)", trustResult, (int)result);
655 MacOSError::throwMe(result);
656 }
657 }
658
659 if (mSigningTimestamp) {
660 CFIndex rootix = CFArrayGetCount(mCertChain);
661 if (SecCertificateRef mainRoot = SecCertificateRef(CFArrayGetValueAtIndex(mCertChain, rootix-1)))
662 if (isAppleCA(mainRoot)) {
663 // impose policy: if the signature itself draws to Apple, then so must the timestamp signature
664 CFRef<CFArrayRef> tsCerts;
665 OSStatus result = CMSDecoderCopySignerTimestampCertificates(cms, 0, &tsCerts.aref());
666 if (result) {
667 Security::Syslog::error("SecStaticCode: could not get timestamp certificates (error %d)", (int)result);
668 MacOSError::check(result);
669 }
670 CFIndex tsn = CFArrayGetCount(tsCerts);
671 bool good = tsn > 0 && isAppleCA(SecCertificateRef(CFArrayGetValueAtIndex(tsCerts, tsn-1)));
672 if (!good) {
673 result = CSSMERR_TP_NOT_TRUSTED;
674 Security::Syslog::error("SecStaticCode: timestamp policy verification failed (error %d)", (int)result);
675 MacOSError::throwMe(result);
676 }
677 }
678 }
679
680 return actionData.ActionFlags & CSSM_TP_ACTION_ALLOW_EXPIRED;
681 }
682 }
683
684
685 //
686 // Return the TP policy used for signature verification.
687 // This may be a simple SecPolicyRef or a CFArray of policies.
688 // The caller owns the return value.
689 //
690 static SecPolicyRef makeCRLPolicy()
691 {
692 CFRef<SecPolicyRef> policy;
693 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_REVOCATION_CRL, &policy.aref()));
694 CSSM_APPLE_TP_CRL_OPTIONS options;
695 memset(&options, 0, sizeof(options));
696 options.Version = CSSM_APPLE_TP_CRL_OPTS_VERSION;
697 options.CrlFlags = CSSM_TP_ACTION_FETCH_CRL_FROM_NET | CSSM_TP_ACTION_CRL_SUFFICIENT;
698 CSSM_DATA optData = { sizeof(options), (uint8 *)&options };
699 MacOSError::check(SecPolicySetValue(policy, &optData));
700 return policy.yield();
701 }
702
703 static SecPolicyRef makeOCSPPolicy()
704 {
705 CFRef<SecPolicyRef> policy;
706 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_REVOCATION_OCSP, &policy.aref()));
707 CSSM_APPLE_TP_OCSP_OPTIONS options;
708 memset(&options, 0, sizeof(options));
709 options.Version = CSSM_APPLE_TP_OCSP_OPTS_VERSION;
710 options.Flags = CSSM_TP_ACTION_OCSP_SUFFICIENT;
711 CSSM_DATA optData = { sizeof(options), (uint8 *)&options };
712 MacOSError::check(SecPolicySetValue(policy, &optData));
713 return policy.yield();
714 }
715
716 CFArrayRef SecStaticCode::verificationPolicies()
717 {
718 CFRef<SecPolicyRef> core;
719 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3,
720 &CSSMOID_APPLE_TP_CODE_SIGNING, &core.aref()));
721 if (mValidationFlags & kSecCSNoNetworkAccess) {
722 // Skips all revocation since they require network connectivity
723 // therefore annihilates kSecCSEnforceRevocationChecks if present
724 CFRef<SecPolicyRef> no_revoc = SecPolicyCreateRevocation(kSecRevocationNetworkAccessDisabled);
725 return makeCFArray(2, core.get(), no_revoc.get());
726 }
727 else if (mValidationFlags & kSecCSEnforceRevocationChecks) {
728 // Add CRL and OCSPPolicies
729 CFRef<SecPolicyRef> crl = makeCRLPolicy();
730 CFRef<SecPolicyRef> ocsp = makeOCSPPolicy();
731 return makeCFArray(3, core.get(), crl.get(), ocsp.get());
732 } else {
733 return makeCFArray(1, core.get());
734 }
735 }
736
737
738 //
739 // Validate a particular sealed, cached resource against its (special) CodeDirectory slot.
740 // The resource must already have been placed in the cache.
741 // This does NOT perform basic validation.
742 //
743 void SecStaticCode::validateComponent(CodeDirectory::SpecialSlot slot, OSStatus fail /* = errSecCSSignatureFailed */)
744 {
745 assert(slot <= cdSlotMax);
746 CFDataRef data = mCache[slot];
747 assert(data); // must be cached
748 if (data == CFDataRef(kCFNull)) {
749 if (codeDirectory()->slotIsPresent(-slot)) // was supposed to be there...
750 MacOSError::throwMe(fail); // ... and is missing
751 } else {
752 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data), CFDataGetLength(data), -slot))
753 MacOSError::throwMe(fail);
754 }
755 }
756
757
758 //
759 // Perform static validation of the main executable.
760 // This reads the main executable from disk and validates it against the
761 // CodeDirectory code slot array.
762 // Note that this is NOT an in-memory validation, and is thus potentially
763 // subject to timing attacks.
764 //
765 void SecStaticCode::validateExecutable()
766 {
767 if (!validatedExecutable()) {
768 try {
769 DTRACK(CODESIGN_EVAL_STATIC_EXECUTABLE, this,
770 (char*)this->mainExecutablePath().c_str(), codeDirectory()->nCodeSlots);
771 const CodeDirectory *cd = this->codeDirectory();
772 if (!cd)
773 MacOSError::throwMe(errSecCSUnsigned);
774 AutoFileDesc fd(mainExecutablePath(), O_RDONLY);
775 fd.fcntl(F_NOCACHE, true); // turn off page caching (one-pass)
776 if (Universal *fat = mRep->mainExecutableImage())
777 fd.seek(fat->archOffset());
778 size_t pageSize = cd->pageSize ? (1 << cd->pageSize) : 0;
779 size_t remaining = cd->codeLimit;
780 for (uint32_t slot = 0; slot < cd->nCodeSlots; ++slot) {
781 size_t size = min(remaining, pageSize);
782 if (!cd->validateSlot(fd, size, slot)) {
783 CODESIGN_EVAL_STATIC_EXECUTABLE_FAIL(this, (int)slot);
784 MacOSError::throwMe(errSecCSSignatureFailed);
785 }
786 remaining -= size;
787 }
788 mExecutableValidated = true;
789 mExecutableValidResult = errSecSuccess;
790 } catch (const CommonError &err) {
791 mExecutableValidated = true;
792 mExecutableValidResult = err.osStatus();
793 throw;
794 } catch (...) {
795 secdebug("staticCode", "%p executable validation threw non-common exception", this);
796 mExecutableValidated = true;
797 mExecutableValidResult = errSecCSInternalError;
798 throw;
799 }
800 }
801 assert(validatedExecutable());
802 if (mExecutableValidResult != errSecSuccess)
803 MacOSError::throwMe(mExecutableValidResult);
804 }
805
806
807 //
808 // Perform static validation of sealed resources and nested code.
809 //
810 // This performs a whole-code static resource scan and effectively
811 // computes a concordance between what's on disk and what's in the ResourceDirectory.
812 // Any unsanctioned difference causes an error.
813 //
814 unsigned SecStaticCode::estimateResourceWorkload()
815 {
816 // workload estimate = number of sealed files
817 CFDictionaryRef sealedResources = resourceDictionary();
818 CFDictionaryRef files = cfget<CFDictionaryRef>(sealedResources, "files2");
819 if (files == NULL)
820 files = cfget<CFDictionaryRef>(sealedResources, "files");
821 return files ? unsigned(CFDictionaryGetCount(files)) : 0;
822 }
823
824 void SecStaticCode::validateResources(SecCSFlags flags)
825 {
826 // do we have a superset of this requested validation cached?
827 bool doit = true;
828 if (mResourcesValidated) { // have cached outcome
829 if (!(flags & kSecCSCheckNestedCode) || mResourcesDeep) // was deep or need no deep scan
830 doit = false;
831 }
832
833 if (doit) {
834 if (mLimitedAsync == NULL) {
835 mLimitedAsync = new LimitedAsync(diskRep()->fd().mediumType() == kIOPropertyMediumTypeSolidStateKey);
836 }
837
838 try {
839 // sanity first
840 CFDictionaryRef sealedResources = resourceDictionary();
841 if (this->resourceBase()) // disk has resources
842 if (sealedResources)
843 /* go to work below */;
844 else
845 MacOSError::throwMe(errSecCSResourcesNotFound);
846 else // disk has no resources
847 if (sealedResources)
848 MacOSError::throwMe(errSecCSResourcesNotFound);
849 else
850 return; // no resources, not sealed - fine (no work)
851
852 // found resources, and they are sealed
853 DTRACK(CODESIGN_EVAL_STATIC_RESOURCES, this,
854 (char*)this->mainExecutablePath().c_str(), 0);
855
856 // scan through the resources on disk, checking each against the resourceDirectory
857 mResourcesValidContext = new CollectingContext(*this); // collect all failures in here
858
859 // use V2 resource seal if available, otherwise fall back to V1
860 CFDictionaryRef rules;
861 CFDictionaryRef files;
862 uint32_t version;
863 if (CFDictionaryGetValue(sealedResources, CFSTR("files2"))) { // have V2 signature
864 rules = cfget<CFDictionaryRef>(sealedResources, "rules2");
865 files = cfget<CFDictionaryRef>(sealedResources, "files2");
866 version = 2;
867 } else { // only V1 available
868 rules = cfget<CFDictionaryRef>(sealedResources, "rules");
869 files = cfget<CFDictionaryRef>(sealedResources, "files");
870 version = 1;
871 }
872 if (!rules || !files)
873 MacOSError::throwMe(errSecCSResourcesInvalid);
874
875 // check for weak resource rules
876 bool strict = flags & kSecCSStrictValidate;
877 if (strict) {
878 if (hasWeakResourceRules(rules, version, mAllowOmissions))
879 if (mTolerateErrors.find(errSecCSWeakResourceRules) == mTolerateErrors.end())
880 MacOSError::throwMe(errSecCSWeakResourceRules);
881 if (version == 1)
882 if (mTolerateErrors.find(errSecCSWeakResourceEnvelope) == mTolerateErrors.end())
883 MacOSError::throwMe(errSecCSWeakResourceEnvelope);
884 }
885
886 Dispatch::Group group;
887 Dispatch::Group &groupRef = group; // (into block)
888
889 // scan through the resources on disk, checking each against the resourceDirectory
890 __block CFRef<CFMutableDictionaryRef> resourceMap = makeCFMutableDictionary(files);
891 string base = cfString(this->resourceBase());
892 ResourceBuilder resources(base, base, rules, codeDirectory()->hashType, strict, mTolerateErrors);
893 this->mResourceScope = &resources;
894 diskRep()->adjustResources(resources);
895
896 resources.scan(^(FTSENT *ent, uint32_t ruleFlags, const string relpath, ResourceBuilder::Rule *rule) {
897 CFDictionaryRemoveValue(resourceMap, CFTempString(relpath));
898 bool isSymlink = (ent->fts_info == FTS_SL);
899
900 void (^validate)() = ^{
901 validateResource(files, relpath, isSymlink, *mResourcesValidContext, flags, version);
902 reportProgress();
903 };
904
905 mLimitedAsync->perform(groupRef, validate);
906 });
907 group.wait(); // wait until all async resources have been validated as well
908
909 unsigned leftovers = unsigned(CFDictionaryGetCount(resourceMap));
910 if (leftovers > 0) {
911 secdebug("staticCode", "%d sealed resource(s) not found in code", int(leftovers));
912 CFDictionaryApplyFunction(resourceMap, SecStaticCode::checkOptionalResource, mResourcesValidContext);
913 }
914
915 // now check for any errors found in the reporting context
916 mResourcesValidated = true;
917 mResourcesDeep = flags & kSecCSCheckNestedCode;
918 if (mResourcesValidContext->osStatus() != errSecSuccess)
919 mResourcesValidContext->throwMe();
920 } catch (const CommonError &err) {
921 mResourcesValidated = true;
922 mResourcesDeep = flags & kSecCSCheckNestedCode;
923 mResourcesValidResult = err.osStatus();
924 throw;
925 } catch (...) {
926 secdebug("staticCode", "%p executable validation threw non-common exception", this);
927 mResourcesValidated = true;
928 mResourcesDeep = flags & kSecCSCheckNestedCode;
929 mResourcesValidResult = errSecCSInternalError;
930 throw;
931 }
932 }
933 assert(validatedResources());
934 if (mResourcesValidResult)
935 MacOSError::throwMe(mResourcesValidResult);
936 if (mResourcesValidContext->osStatus() != errSecSuccess)
937 mResourcesValidContext->throwMe();
938 }
939
940
941 void SecStaticCode::checkOptionalResource(CFTypeRef key, CFTypeRef value, void *context)
942 {
943 ValidationContext *ctx = static_cast<ValidationContext *>(context);
944 ResourceSeal seal(value);
945 if (!seal.optional()) {
946 if (key && CFGetTypeID(key) == CFStringGetTypeID()) {
947 CFTempURL tempURL(CFStringRef(key), false, ctx->code.resourceBase());
948 if (!tempURL.get()) {
949 ctx->reportProblem(errSecCSBadDictionaryFormat, kSecCFErrorResourceSeal, key);
950 } else {
951 ctx->reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, tempURL);
952 }
953 } else {
954 ctx->reportProblem(errSecCSBadResource, kSecCFErrorResourceSeal, key);
955 }
956 }
957 }
958
959
960 static bool isOmitRule(CFTypeRef value)
961 {
962 if (CFGetTypeID(value) == CFBooleanGetTypeID())
963 return value == kCFBooleanFalse;
964 CFDictionary rule(value, errSecCSResourceRulesInvalid);
965 return rule.get<CFBooleanRef>("omit") == kCFBooleanTrue;
966 }
967
968 bool SecStaticCode::hasWeakResourceRules(CFDictionaryRef rulesDict, uint32_t version, CFArrayRef allowedOmissions)
969 {
970 // compute allowed omissions
971 CFRef<CFArrayRef> defaultOmissions = this->diskRep()->allowedResourceOmissions();
972 if (!defaultOmissions)
973 MacOSError::throwMe(errSecCSInternalError);
974 CFRef<CFMutableArrayRef> allowed = CFArrayCreateMutableCopy(NULL, 0, defaultOmissions);
975 if (allowedOmissions)
976 CFArrayAppendArray(allowed, allowedOmissions, CFRangeMake(0, CFArrayGetCount(allowedOmissions)));
977 CFRange range = CFRangeMake(0, CFArrayGetCount(allowed));
978
979 // check all resource rules for weakness
980 string catchAllRule = (version == 1) ? "^Resources/" : "^.*";
981 __block bool coversAll = false;
982 __block bool forbiddenOmission = false;
983 CFArrayRef allowedRef = allowed.get(); // (into block)
984 CFDictionary rules(rulesDict, errSecCSResourceRulesInvalid);
985 rules.apply(^(CFStringRef key, CFTypeRef value) {
986 string pattern = cfString(key, errSecCSResourceRulesInvalid);
987 if (pattern == catchAllRule && value == kCFBooleanTrue) {
988 coversAll = true;
989 return;
990 }
991 if (isOmitRule(value))
992 forbiddenOmission |= !CFArrayContainsValue(allowedRef, range, key);
993 });
994
995 return !coversAll || forbiddenOmission;
996 }
997
998
999 //
1000 // Load, validate, cache, and return CFDictionary forms of sealed resources.
1001 //
1002 CFDictionaryRef SecStaticCode::infoDictionary()
1003 {
1004 if (!mInfoDict) {
1005 mInfoDict.take(getDictionary(cdInfoSlot, errSecCSInfoPlistFailed));
1006 secdebug("staticCode", "%p loaded InfoDict %p", this, mInfoDict.get());
1007 }
1008 return mInfoDict;
1009 }
1010
1011 CFDictionaryRef SecStaticCode::entitlements()
1012 {
1013 if (!mEntitlements) {
1014 validateDirectory();
1015 if (CFDataRef entitlementData = component(cdEntitlementSlot)) {
1016 validateComponent(cdEntitlementSlot);
1017 const EntitlementBlob *blob = reinterpret_cast<const EntitlementBlob *>(CFDataGetBytePtr(entitlementData));
1018 if (blob->validateBlob()) {
1019 mEntitlements.take(blob->entitlements());
1020 secdebug("staticCode", "%p loaded Entitlements %p", this, mEntitlements.get());
1021 }
1022 // we do not consider a different blob type to be an error. We think it's a new format we don't understand
1023 }
1024 }
1025 return mEntitlements;
1026 }
1027
1028 CFDictionaryRef SecStaticCode::resourceDictionary(bool check /* = true */)
1029 {
1030 if (mResourceDict) // cached
1031 return mResourceDict;
1032 if (CFRef<CFDictionaryRef> dict = getDictionary(cdResourceDirSlot, check))
1033 if (cfscan(dict, "{rules=%Dn,files=%Dn}")) {
1034 secdebug("staticCode", "%p loaded ResourceDict %p",
1035 this, mResourceDict.get());
1036 return mResourceDict = dict;
1037 }
1038 // bad format
1039 return NULL;
1040 }
1041
1042
1043 //
1044 // Load and cache the resource directory base.
1045 // Note that the base is optional for each DiskRep.
1046 //
1047 CFURLRef SecStaticCode::resourceBase()
1048 {
1049 if (!mGotResourceBase) {
1050 string base = mRep->resourcesRootPath();
1051 if (!base.empty())
1052 mResourceBase.take(makeCFURL(base, true));
1053 mGotResourceBase = true;
1054 }
1055 return mResourceBase;
1056 }
1057
1058
1059 //
1060 // Load a component, validate it, convert it to a CFDictionary, and return that.
1061 // This will force load and validation, which means that it will perform basic
1062 // validation if it hasn't been done yet.
1063 //
1064 CFDictionaryRef SecStaticCode::getDictionary(CodeDirectory::SpecialSlot slot, bool check /* = true */)
1065 {
1066 if (check)
1067 validateDirectory();
1068 if (CFDataRef infoData = component(slot)) {
1069 validateComponent(slot);
1070 if (CFDictionaryRef dict = makeCFDictionaryFrom(infoData))
1071 return dict;
1072 else
1073 MacOSError::throwMe(errSecCSBadDictionaryFormat);
1074 }
1075 return NULL;
1076 }
1077
1078
1079 //
1080 // Load, validate, and return a sealed resource.
1081 // The resource data (loaded in to memory as a blob) is returned and becomes
1082 // the responsibility of the caller; it is NOT cached by SecStaticCode.
1083 //
1084 // A resource that is not sealed will not be returned, and an error will be thrown.
1085 // A missing resource will cause an error unless it's marked optional in the Directory.
1086 // Under no circumstances will a corrupt resource be returned.
1087 // NULL will only be returned for a resource that is neither sealed nor present
1088 // (or that is sealed, absent, and marked optional).
1089 // If the ResourceDictionary itself is not sealed, this function will always fail.
1090 //
1091 // There is currently no interface for partial retrieval of the resource data.
1092 // (Since the ResourceDirectory does not currently support segmentation, all the
1093 // data would have to be read anyway, but it could be read into a reusable buffer.)
1094 //
1095 CFDataRef SecStaticCode::resource(string path, ValidationContext &ctx)
1096 {
1097 if (CFDictionaryRef rdict = resourceDictionary()) {
1098 if (CFTypeRef file = cfget(rdict, "files.%s", path.c_str())) {
1099 ResourceSeal seal = file;
1100 if (!resourceBase()) // no resources in DiskRep
1101 MacOSError::throwMe(errSecCSResourcesNotFound);
1102 if (seal.nested())
1103 MacOSError::throwMe(errSecCSResourcesNotSealed); // (it's nested code)
1104 CFRef<CFURLRef> fullpath = makeCFURL(path, false, resourceBase());
1105 if (CFRef<CFDataRef> data = cfLoadFile(fullpath)) {
1106 MakeHash<CodeDirectory> hasher(this->codeDirectory());
1107 hasher->update(CFDataGetBytePtr(data), CFDataGetLength(data));
1108 if (hasher->verify(seal.hash()))
1109 return data.yield(); // good
1110 else
1111 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // altered
1112 } else {
1113 if (!seal.optional())
1114 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, fullpath); // was sealed but is now missing
1115 else
1116 return NULL; // validly missing
1117 }
1118 } else
1119 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAdded, CFTempURL(path, false, resourceBase()));
1120 return NULL;
1121 } else
1122 MacOSError::throwMe(errSecCSResourcesNotSealed);
1123 }
1124
1125 CFDataRef SecStaticCode::resource(string path)
1126 {
1127 ValidationContext ctx(*this);
1128 return resource(path, ctx);
1129 }
1130
1131 void SecStaticCode::validateResource(CFDictionaryRef files, string path, bool isSymlink, ValidationContext &ctx, SecCSFlags flags, uint32_t version)
1132 {
1133 if (!resourceBase()) // no resources in DiskRep
1134 MacOSError::throwMe(errSecCSResourcesNotFound);
1135 CFRef<CFURLRef> fullpath = makeCFURL(path, false, resourceBase());
1136 if (CFTypeRef file = CFDictionaryGetValue(files, CFTempString(path))) {
1137 ResourceSeal seal = file;
1138 if (seal.nested()) {
1139 if (isSymlink)
1140 return ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type
1141 string suffix = ".framework";
1142 bool isFramework = (path.length() > suffix.length())
1143 && (path.compare(path.length()-suffix.length(), suffix.length(), suffix) == 0);
1144 validateNestedCode(fullpath, seal, flags, isFramework);
1145 } else if (seal.link()) {
1146 if (!isSymlink)
1147 return ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type
1148 validateSymlinkResource(cfString(fullpath), cfString(seal.link()), ctx, flags);
1149 } else if (seal.hash()) { // genuine file
1150 if (isSymlink)
1151 return ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type
1152 AutoFileDesc fd(cfString(fullpath), O_RDONLY, FileDesc::modeMissingOk); // open optional file
1153 if (fd) {
1154 MakeHash<CodeDirectory> hasher(this->codeDirectory());
1155 hashFileData(fd, hasher.get());
1156 if (hasher->verify(seal.hash()))
1157 return; // verify good
1158 else
1159 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // altered
1160 } else {
1161 if (!seal.optional())
1162 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, fullpath); // was sealed but is now missing
1163 else
1164 return; // validly missing
1165 }
1166 } else
1167 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type
1168 return;
1169 }
1170 if (version == 1) { // version 1 ignores symlinks altogether
1171 char target[PATH_MAX];
1172 if (::readlink(cfString(fullpath).c_str(), target, sizeof(target)) > 0)
1173 return;
1174 }
1175 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAdded, CFTempURL(path, false, resourceBase()));
1176 }
1177
1178 void SecStaticCode::validateSymlinkResource(std::string fullpath, std::string seal, ValidationContext &ctx, SecCSFlags flags)
1179 {
1180 static const char* const allowedDestinations[] = {
1181 "/System/",
1182 "/Library/",
1183 NULL
1184 };
1185 char target[PATH_MAX];
1186 ssize_t len = ::readlink(fullpath.c_str(), target, sizeof(target)-1);
1187 if (len < 0)
1188 UnixError::check(-1);
1189 target[len] = '\0';
1190 std::string fulltarget = target;
1191 if (target[0] != '/') {
1192 size_t lastSlash = fullpath.rfind('/');
1193 fulltarget = fullpath.substr(0, lastSlash) + '/' + target;
1194 }
1195 if (seal != target) {
1196 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, CFTempString(fullpath));
1197 return;
1198 }
1199 if ((mValidationFlags & (kSecCSStrictValidate|kSecCSRestrictSymlinks)) == (kSecCSStrictValidate|kSecCSRestrictSymlinks)) {
1200 char resolved[PATH_MAX];
1201 if (realpath(fulltarget.c_str(), resolved)) {
1202 assert(resolved[0] == '/');
1203 size_t rlen = strlen(resolved);
1204 if (target[0] == '/') {
1205 // absolute symlink; only allow absolute links to system locations
1206 for (const char* const* pathp = allowedDestinations; *pathp; pathp++) {
1207 size_t dlen = strlen(*pathp);
1208 if (rlen > dlen && strncmp(resolved, *pathp, dlen) == 0)
1209 return; // target inside /System, deemed okay
1210 }
1211 } else {
1212 // everything else must be inside the bundle(s)
1213 for (const SecStaticCode* code = this; code; code = code->mOuterScope) {
1214 string root = code->mResourceScope->root();
1215 if (strncmp(resolved, root.c_str(), root.size()) == 0) {
1216 if (code->mResourceScope->includes(resolved + root.length() + 1))
1217 return; // located in resource stack && included in envelope
1218 else
1219 break; // located but excluded from envelope (deny)
1220 }
1221 }
1222 }
1223 }
1224 // if we fell through, flag a symlink error
1225 if (mTolerateErrors.find(errSecCSInvalidSymlink) == mTolerateErrors.end())
1226 ctx.reportProblem(errSecCSInvalidSymlink, kSecCFErrorResourceAltered, CFTempString(fullpath));
1227 }
1228 }
1229
1230 void SecStaticCode::validateNestedCode(CFURLRef path, const ResourceSeal &seal, SecCSFlags flags, bool isFramework)
1231 {
1232 CFRef<SecRequirementRef> req;
1233 if (SecRequirementCreateWithString(seal.requirement(), kSecCSDefaultFlags, &req.aref()))
1234 MacOSError::throwMe(errSecCSResourcesInvalid);
1235
1236 // recursively verify this nested code
1237 try {
1238 if (!(flags & kSecCSCheckNestedCode))
1239 flags |= kSecCSBasicValidateOnly;
1240 SecPointer<SecStaticCode> code = new SecStaticCode(DiskRep::bestGuess(cfString(path)));
1241 code->initializeFromParent(*this);
1242 code->staticValidate(flags, SecRequirement::required(req));
1243
1244 if (isFramework && (flags & kSecCSStrictValidate))
1245 try {
1246 validateOtherVersions(path, flags, req, code);
1247 } catch (const CSError &err) {
1248 MacOSError::throwMe(errSecCSBadFrameworkVersion);
1249 } catch (const MacOSError &err) {
1250 MacOSError::throwMe(errSecCSBadFrameworkVersion);
1251 }
1252
1253 } catch (CSError &err) {
1254 if (err.error == errSecCSReqFailed) {
1255 mResourcesValidContext->reportProblem(errSecCSBadNestedCode, kSecCFErrorResourceAltered, path);
1256 return;
1257 }
1258 err.augment(kSecCFErrorPath, path);
1259 throw;
1260 } catch (const MacOSError &err) {
1261 if (err.error == errSecCSReqFailed) {
1262 mResourcesValidContext->reportProblem(errSecCSBadNestedCode, kSecCFErrorResourceAltered, path);
1263 return;
1264 }
1265 CSError::throwMe(err.error, kSecCFErrorPath, path);
1266 }
1267 }
1268
1269 void SecStaticCode::validateOtherVersions(CFURLRef path, SecCSFlags flags, SecRequirementRef req, SecStaticCode *code)
1270 {
1271 // Find out what current points to and do not revalidate
1272 std::string mainPath = cfStringRelease(code->diskRep()->copyCanonicalPath());
1273
1274 char main_path[PATH_MAX];
1275 bool foundTarget = false;
1276
1277 /* If it failed to get the target of the symlink, do not fail. It is a performance loss,
1278 not a security hole */
1279 if (realpath(mainPath.c_str(), main_path) != NULL)
1280 foundTarget = true;
1281
1282 std::ostringstream versionsPath;
1283 versionsPath << cfString(path) << "/Versions/";
1284
1285 DirScanner scanner(versionsPath.str());
1286
1287 if (scanner.initialized()) {
1288 struct dirent *entry = NULL;
1289 while ((entry = scanner.getNext()) != NULL) {
1290 std::ostringstream fullPath;
1291
1292 if (entry->d_type != DT_DIR ||
1293 strcmp(entry->d_name, ".") == 0 ||
1294 strcmp(entry->d_name, "..") == 0 ||
1295 strcmp(entry->d_name, "Current") == 0)
1296 continue;
1297
1298 fullPath << versionsPath.str() << entry->d_name;
1299
1300 char real_full_path[PATH_MAX];
1301 if (realpath(fullPath.str().c_str(), real_full_path) == NULL)
1302 UnixError::check(-1);
1303
1304 // Do case insensitive comparions because realpath() was called for both paths
1305 if (foundTarget && strcmp(main_path, real_full_path) == 0)
1306 continue;
1307
1308 SecPointer<SecStaticCode> frameworkVersion = new SecStaticCode(DiskRep::bestGuess(real_full_path));
1309 frameworkVersion->initializeFromParent(*this);
1310 frameworkVersion->staticValidate(flags, SecRequirement::required(req));
1311 }
1312 }
1313 }
1314
1315
1316 //
1317 // Test a CodeDirectory flag.
1318 // Returns false if there is no CodeDirectory.
1319 // May throw if the CodeDirectory is present but somehow invalid.
1320 //
1321 bool SecStaticCode::flag(uint32_t tested)
1322 {
1323 if (const CodeDirectory *cd = this->codeDirectory(false))
1324 return cd->flags & tested;
1325 else
1326 return false;
1327 }
1328
1329
1330 //
1331 // Retrieve the full SuperBlob containing all internal requirements.
1332 //
1333 const Requirements *SecStaticCode::internalRequirements()
1334 {
1335 if (CFDataRef reqData = component(cdRequirementsSlot)) {
1336 const Requirements *req = (const Requirements *)CFDataGetBytePtr(reqData);
1337 if (!req->validateBlob())
1338 MacOSError::throwMe(errSecCSReqInvalid);
1339 return req;
1340 } else
1341 return NULL;
1342 }
1343
1344
1345 //
1346 // Retrieve a particular internal requirement by type.
1347 //
1348 const Requirement *SecStaticCode::internalRequirement(SecRequirementType type)
1349 {
1350 if (const Requirements *reqs = internalRequirements())
1351 return reqs->find<Requirement>(type);
1352 else
1353 return NULL;
1354 }
1355
1356
1357 //
1358 // Return the Designated Requirement (DR). This can be either explicit in the
1359 // Internal Requirements component, or implicitly generated on demand here.
1360 // Note that an explicit DR may have been implicitly generated at signing time;
1361 // we don't distinguish this case.
1362 //
1363 const Requirement *SecStaticCode::designatedRequirement()
1364 {
1365 if (const Requirement *req = internalRequirement(kSecDesignatedRequirementType)) {
1366 return req; // explicit in signing data
1367 } else {
1368 if (!mDesignatedReq)
1369 mDesignatedReq = defaultDesignatedRequirement();
1370 return mDesignatedReq;
1371 }
1372 }
1373
1374
1375 //
1376 // Generate the default Designated Requirement (DR) for this StaticCode.
1377 // Ignore any explicit DR it may contain.
1378 //
1379 const Requirement *SecStaticCode::defaultDesignatedRequirement()
1380 {
1381 if (flag(kSecCodeSignatureAdhoc)) {
1382 // adhoc signature: return a cdhash requirement for all architectures
1383 __block Requirement::Maker maker;
1384 Requirement::Maker::Chain chain(maker, opOr);
1385
1386 // insert cdhash requirement for all architectures
1387 chain.add();
1388 maker.cdhash(this->cdHash());
1389 handleOtherArchitectures(^(SecStaticCode *subcode) {
1390 if (CFDataRef cdhash = subcode->cdHash()) {
1391 chain.add();
1392 maker.cdhash(cdhash);
1393 }
1394 });
1395 return maker.make();
1396 } else {
1397 // full signature: Gin up full context and let DRMaker do its thing
1398 validateDirectory(); // need the cert chain
1399 Requirement::Context context(this->certificates(),
1400 this->infoDictionary(),
1401 this->entitlements(),
1402 this->identifier(),
1403 this->codeDirectory()
1404 );
1405 return DRMaker(context).make();
1406 }
1407 }
1408
1409
1410 //
1411 // Validate a SecStaticCode against the internal requirement of a particular type.
1412 //
1413 void SecStaticCode::validateRequirements(SecRequirementType type, SecStaticCode *target,
1414 OSStatus nullError /* = errSecSuccess */)
1415 {
1416 DTRACK(CODESIGN_EVAL_STATIC_INTREQ, this, type, target, nullError);
1417 if (const Requirement *req = internalRequirement(type))
1418 target->validateRequirement(req, nullError ? nullError : errSecCSReqFailed);
1419 else if (nullError)
1420 MacOSError::throwMe(nullError);
1421 else
1422 /* accept it */;
1423 }
1424
1425 /* Public Key Hash for root:/C=US/O=VeriSign, Inc./OU=Class 3 Public Primary Certification Authority */
1426 static const UInt8 retryRootBytes[] = {0x00,0xd8,0x5a,0x4c,0x25,0xc1,0x22,0xe5,0x8b,0x31,0xef,0x6d,0xba,0xf3,0xcc,0x5f,0x29,0xf1,0x0d,0x61};
1427
1428 //
1429 // Validate this StaticCode against an external Requirement
1430 //
1431 bool SecStaticCode::satisfiesRequirement(const Requirement *req, OSStatus failure)
1432 {
1433 bool result = false;
1434 assert(req);
1435 validateDirectory();
1436 result = req->validates(Requirement::Context(mCertChain, infoDictionary(), entitlements(), codeDirectory()->identifier(), codeDirectory()), failure);
1437 if (result == false) {
1438 /* Fix for rdar://problem/21437632: Work around untrusted root in validation chain */
1439 CFArrayRef certs = certificates();
1440 if (!certs || ((int)CFArrayGetCount(certs) < 1)) {
1441 return false;
1442 }
1443 SecCertificateRef root = cert((int)CFArrayGetCount(certs) - 1);
1444 if (!root) {
1445 return false;
1446 }
1447 CFDataRef rootHash = SecCertificateCopyPublicKeySHA1Digest(root);
1448 if (!rootHash) {
1449 return false;
1450 }
1451
1452 if ((CFDataGetLength(rootHash) == sizeof(retryRootBytes)) &&
1453 !memcmp(CFDataGetBytePtr(rootHash), retryRootBytes, sizeof(retryRootBytes))) {
1454 // retry with a rebuilt certificate chain, this time evaluating anchor trust
1455 Security::Syslog::debug("Requirements validation failed: retrying");
1456 mResourcesValidated = mValidated = false;
1457 setValidationFlags(mValidationFlags | kSecCSCheckTrustedAnchors);
1458
1459 validateDirectory();
1460 result = req->validates(Requirement::Context(mCertChain, infoDictionary(), entitlements(), codeDirectory()->identifier(), codeDirectory()), failure);
1461 }
1462 CFRelease(rootHash);
1463 }
1464
1465 return result;
1466 }
1467
1468 void SecStaticCode::validateRequirement(const Requirement *req, OSStatus failure)
1469 {
1470 if (!this->satisfiesRequirement(req, failure))
1471 MacOSError::throwMe(failure);
1472 }
1473
1474 //
1475 // Retrieve one certificate from the cert chain.
1476 // Positive and negative indices can be used:
1477 // [ leaf, intermed-1, ..., intermed-n, anchor ]
1478 // 0 1 ... -2 -1
1479 // Returns NULL if unavailable for any reason.
1480 //
1481 SecCertificateRef SecStaticCode::cert(int ix)
1482 {
1483 validateDirectory(); // need cert chain
1484 if (mCertChain) {
1485 CFIndex length = CFArrayGetCount(mCertChain);
1486 if (ix < 0)
1487 ix += length;
1488 if (ix >= 0 && ix < length)
1489 return SecCertificateRef(CFArrayGetValueAtIndex(mCertChain, ix));
1490 }
1491 return NULL;
1492 }
1493
1494 CFArrayRef SecStaticCode::certificates()
1495 {
1496 validateDirectory(); // need cert chain
1497 return mCertChain;
1498 }
1499
1500
1501 //
1502 // Gather (mostly) API-official information about this StaticCode.
1503 //
1504 // This method lives in the twilight between the API and internal layers,
1505 // since it generates API objects (Sec*Refs) for return.
1506 //
1507 CFDictionaryRef SecStaticCode::signingInformation(SecCSFlags flags)
1508 {
1509 //
1510 // Start with the pieces that we return even for unsigned code.
1511 // This makes Sec[Static]CodeRefs useful as API-level replacements
1512 // of our internal OSXCode objects.
1513 //
1514 CFRef<CFMutableDictionaryRef> dict = makeCFMutableDictionary(1,
1515 kSecCodeInfoMainExecutable, CFTempURL(this->mainExecutablePath()).get()
1516 );
1517
1518 //
1519 // If we're not signed, this is all you get
1520 //
1521 if (!this->isSigned())
1522 return dict.yield();
1523
1524 //
1525 // Add the generic attributes that we always include
1526 //
1527 CFDictionaryAddValue(dict, kSecCodeInfoIdentifier, CFTempString(this->identifier()));
1528 CFDictionaryAddValue(dict, kSecCodeInfoFlags, CFTempNumber(this->codeDirectory(false)->flags.get()));
1529 CFDictionaryAddValue(dict, kSecCodeInfoFormat, CFTempString(this->format()));
1530 CFDictionaryAddValue(dict, kSecCodeInfoSource, CFTempString(this->signatureSource()));
1531 CFDictionaryAddValue(dict, kSecCodeInfoUnique, this->cdHash());
1532 const CodeDirectory* cd = this->codeDirectory(false);
1533 CFDictionaryAddValue(dict, kSecCodeInfoDigestAlgorithm, CFTempNumber(cd->hashType));
1534 if (cd->platform)
1535 CFDictionaryAddValue(dict, kSecCodeInfoPlatformIdentifier, CFTempNumber(cd->platform));
1536
1537 //
1538 // Deliver any Info.plist only if it looks intact
1539 //
1540 try {
1541 if (CFDictionaryRef info = this->infoDictionary())
1542 CFDictionaryAddValue(dict, kSecCodeInfoPList, info);
1543 } catch (...) { } // don't deliver Info.plist if questionable
1544
1545 //
1546 // kSecCSSigningInformation adds information about signing certificates and chains
1547 //
1548 if (flags & kSecCSSigningInformation)
1549 try {
1550 if (CFArrayRef certs = this->certificates())
1551 CFDictionaryAddValue(dict, kSecCodeInfoCertificates, certs);
1552 if (CFDataRef sig = this->signature())
1553 CFDictionaryAddValue(dict, kSecCodeInfoCMS, sig);
1554 if (mTrust)
1555 CFDictionaryAddValue(dict, kSecCodeInfoTrust, mTrust);
1556 if (CFAbsoluteTime time = this->signingTime())
1557 if (CFRef<CFDateRef> date = CFDateCreate(NULL, time))
1558 CFDictionaryAddValue(dict, kSecCodeInfoTime, date);
1559 if (CFAbsoluteTime time = this->signingTimestamp())
1560 if (CFRef<CFDateRef> date = CFDateCreate(NULL, time))
1561 CFDictionaryAddValue(dict, kSecCodeInfoTimestamp, date);
1562 if (const char *teamID = this->teamID())
1563 CFDictionaryAddValue(dict, kSecCodeInfoTeamIdentifier, CFTempString(teamID));
1564 } catch (...) { }
1565
1566 //
1567 // kSecCSRequirementInformation adds information on requirements
1568 //
1569 if (flags & kSecCSRequirementInformation)
1570 try {
1571 if (const Requirements *reqs = this->internalRequirements()) {
1572 CFDictionaryAddValue(dict, kSecCodeInfoRequirements,
1573 CFTempString(Dumper::dump(reqs)));
1574 CFDictionaryAddValue(dict, kSecCodeInfoRequirementData, CFTempData(*reqs));
1575 }
1576
1577 const Requirement *dreq = this->designatedRequirement();
1578 CFRef<SecRequirementRef> dreqRef = (new SecRequirement(dreq))->handle();
1579 CFDictionaryAddValue(dict, kSecCodeInfoDesignatedRequirement, dreqRef);
1580 if (this->internalRequirement(kSecDesignatedRequirementType)) { // explicit
1581 CFRef<SecRequirementRef> ddreqRef = (new SecRequirement(this->defaultDesignatedRequirement(), true))->handle();
1582 CFDictionaryAddValue(dict, kSecCodeInfoImplicitDesignatedRequirement, ddreqRef);
1583 } else { // implicit
1584 CFDictionaryAddValue(dict, kSecCodeInfoImplicitDesignatedRequirement, dreqRef);
1585 }
1586 } catch (...) { }
1587
1588 try {
1589 if (CFDataRef ent = this->component(cdEntitlementSlot)) {
1590 CFDictionaryAddValue(dict, kSecCodeInfoEntitlements, ent);
1591 if (CFDictionaryRef entdict = this->entitlements())
1592 CFDictionaryAddValue(dict, kSecCodeInfoEntitlementsDict, entdict);
1593 }
1594 } catch (...) { }
1595
1596 //
1597 // kSecCSInternalInformation adds internal information meant to be for Apple internal
1598 // use (SPI), and not guaranteed to be stable. Primarily, this is data we want
1599 // to reliably transmit through the API wall so that code outside the Security.framework
1600 // can use it without having to play nasty tricks to get it.
1601 //
1602 if (flags & kSecCSInternalInformation)
1603 try {
1604 if (mDir)
1605 CFDictionaryAddValue(dict, kSecCodeInfoCodeDirectory, mDir);
1606 CFDictionaryAddValue(dict, kSecCodeInfoCodeOffset, CFTempNumber(mRep->signingBase()));
1607 if (CFRef<CFDictionaryRef> rdict = getDictionary(cdResourceDirSlot, false)) // suppress validation
1608 CFDictionaryAddValue(dict, kSecCodeInfoResourceDirectory, rdict);
1609 } catch (...) { }
1610
1611
1612 //
1613 // kSecCSContentInformation adds more information about the physical layout
1614 // of the signed code. This is (only) useful for packaging or patching-oriented
1615 // applications.
1616 //
1617 if (flags & kSecCSContentInformation)
1618 if (CFRef<CFArrayRef> files = mRep->modifiedFiles())
1619 CFDictionaryAddValue(dict, kSecCodeInfoChangedFiles, files);
1620
1621 return dict.yield();
1622 }
1623
1624
1625 //
1626 // Resource validation contexts.
1627 // The default context simply throws a CSError, rudely terminating the operation.
1628 //
1629 SecStaticCode::ValidationContext::~ValidationContext()
1630 { /* virtual */ }
1631
1632 void SecStaticCode::ValidationContext::reportProblem(OSStatus rc, CFStringRef type, CFTypeRef value)
1633 {
1634 CSError::throwMe(rc, type, value);
1635 }
1636
1637 void SecStaticCode::CollectingContext::reportProblem(OSStatus rc, CFStringRef type, CFTypeRef value)
1638 {
1639 StLock<Mutex> _(mLock);
1640 if (mStatus == errSecSuccess)
1641 mStatus = rc; // record first failure for eventual error return
1642 if (type) {
1643 if (!mCollection)
1644 mCollection.take(makeCFMutableDictionary());
1645 CFMutableArrayRef element = CFMutableArrayRef(CFDictionaryGetValue(mCollection, type));
1646 if (!element) {
1647 element = makeCFMutableArray(0);
1648 if (!element)
1649 CFError::throwMe();
1650 CFDictionaryAddValue(mCollection, type, element);
1651 CFRelease(element);
1652 }
1653 CFArrayAppendValue(element, value);
1654 }
1655 }
1656
1657 void SecStaticCode::CollectingContext::throwMe()
1658 {
1659 assert(mStatus != errSecSuccess);
1660 throw CSError(mStatus, mCollection.retain());
1661 }
1662
1663
1664 //
1665 // Master validation driver.
1666 // This is the static validation (only) driver for the API.
1667 //
1668 // SecStaticCode exposes an a la carte menu of topical validators applying
1669 // to a given object. The static validation API pulls them together reliably,
1670 // but it also adds two matrix dimensions: architecture (for "fat" Mach-O binaries)
1671 // and nested code. This function will crawl a suitable cross-section of this
1672 // validation matrix based on which options it is given, creating temporary
1673 // SecStaticCode objects on the fly to complete the task.
1674 // (The point, of course, is to do as little duplicate work as possible.)
1675 //
1676 void SecStaticCode::staticValidate(SecCSFlags flags, const SecRequirement *req)
1677 {
1678 setValidationFlags(flags);
1679
1680 // initialize progress/cancellation state
1681 if (flags & kSecCSReportProgress)
1682 prepareProgress(estimateResourceWorkload() + 2); // +1 head, +1 tail
1683
1684 // core components: once per architecture (if any)
1685 this->staticValidateCore(flags, req);
1686 if (flags & kSecCSCheckAllArchitectures)
1687 handleOtherArchitectures(^(SecStaticCode* subcode) {
1688 if (flags & kSecCSCheckGatekeeperArchitectures) {
1689 Universal *fat = subcode->diskRep()->mainExecutableImage();
1690 assert(fat && fat->narrowed()); // handleOtherArchitectures gave us a focused architecture slice
1691 Architecture arch = fat->bestNativeArch(); // actually, the ONLY one
1692 if ((arch.cpuType() & ~CPU_ARCH_MASK) == CPU_TYPE_POWERPC)
1693 return; // irrelevant to Gatekeeper
1694 }
1695 subcode->detachedSignature(this->mDetachedSig); // carry over explicit (but not implicit) architecture
1696 subcode->staticValidateCore(flags, req);
1697 });
1698 reportProgress();
1699
1700 // allow monitor intervention in source validation phase
1701 reportEvent(CFSTR("prepared"), NULL);
1702
1703 // resources: once for all architectures
1704 if (!(flags & kSecCSDoNotValidateResources))
1705 this->validateResources(flags);
1706
1707 // perform strict validation if desired
1708 if (flags & kSecCSStrictValidate)
1709 mRep->strictValidate(codeDirectory(), mTolerateErrors);
1710 reportProgress();
1711
1712 // allow monitor intervention
1713 if (CFRef<CFTypeRef> veto = reportEvent(CFSTR("validated"), NULL)) {
1714 if (CFGetTypeID(veto) == CFNumberGetTypeID())
1715 MacOSError::throwMe(cfNumber<OSStatus>(veto.as<CFNumberRef>()));
1716 else
1717 MacOSError::throwMe(errSecCSBadCallbackValue);
1718 }
1719 }
1720
1721 void SecStaticCode::staticValidateCore(SecCSFlags flags, const SecRequirement *req)
1722 {
1723 try {
1724 this->validateNonResourceComponents(); // also validates the CodeDirectory
1725 if (!(flags & kSecCSDoNotValidateExecutable))
1726 this->validateExecutable();
1727 if (req)
1728 this->validateRequirement(req->requirement(), errSecCSReqFailed);
1729 } catch (CSError &err) {
1730 if (Universal *fat = this->diskRep()->mainExecutableImage()) // Mach-O
1731 if (MachO *mach = fat->architecture()) {
1732 err.augment(kSecCFErrorArchitecture, CFTempString(mach->architecture().displayName()));
1733 delete mach;
1734 }
1735 throw;
1736 } catch (const MacOSError &err) {
1737 // add architecture information if we can get it
1738 if (Universal *fat = this->diskRep()->mainExecutableImage())
1739 if (MachO *mach = fat->architecture()) {
1740 CFTempString arch(mach->architecture().displayName());
1741 delete mach;
1742 CSError::throwMe(err.error, kSecCFErrorArchitecture, arch);
1743 }
1744 throw;
1745 }
1746 }
1747
1748
1749 //
1750 // A helper that generates SecStaticCode objects for all but the primary architecture
1751 // of a fat binary and calls a block on them.
1752 // If there's only one architecture (or this is an architecture-agnostic code),
1753 // nothing happens quickly.
1754 //
1755 void SecStaticCode::handleOtherArchitectures(void (^handle)(SecStaticCode* other))
1756 {
1757 if (Universal *fat = this->diskRep()->mainExecutableImage()) {
1758 Universal::Architectures architectures;
1759 fat->architectures(architectures);
1760 if (architectures.size() > 1) {
1761 DiskRep::Context ctx;
1762 size_t activeOffset = fat->archOffset();
1763 for (Universal::Architectures::const_iterator arch = architectures.begin(); arch != architectures.end(); ++arch) {
1764 ctx.offset = fat->archOffset(*arch);
1765 if (ctx.offset > SIZE_MAX)
1766 MacOSError::throwMe(errSecCSInternalError);
1767 ctx.size = fat->lengthOfSlice((size_t)ctx.offset);
1768 if (ctx.offset != activeOffset) { // inactive architecture; check it
1769 SecPointer<SecStaticCode> subcode = new SecStaticCode(DiskRep::bestGuess(this->mainExecutablePath(), &ctx));
1770 subcode->detachedSignature(this->mDetachedSig); // carry over explicit (but not implicit) detached signature
1771 if (this->teamID() == NULL || subcode->teamID() == NULL) {
1772 if (this->teamID() != subcode->teamID())
1773 MacOSError::throwMe(errSecCSSignatureInvalid);
1774 } else if (strcmp(this->teamID(), subcode->teamID()) != 0)
1775 MacOSError::throwMe(errSecCSSignatureInvalid);
1776 handle(subcode);
1777 }
1778 }
1779 }
1780 }
1781 }
1782
1783 //
1784 // A method that takes a certificate chain (certs) and evaluates
1785 // if it is a Mac or IPhone developer cert, an app store distribution cert,
1786 // or a developer ID
1787 //
1788 bool SecStaticCode::isAppleDeveloperCert(CFArrayRef certs)
1789 {
1790 static const std::string appleDeveloperRequirement = "(" + std::string(WWDRRequirement) + ") or (" + MACWWDRRequirement + ") or (" + developerID + ") or (" + distributionCertificate + ") or (" + iPhoneDistributionCert + ")";
1791 SecPointer<SecRequirement> req = new SecRequirement(parseRequirement(appleDeveloperRequirement), true);
1792 Requirement::Context ctx(certs, NULL, NULL, "", NULL);
1793
1794 return req->requirement()->validates(ctx);
1795 }
1796
1797 } // end namespace CodeSigning
1798 } // end namespace Security