]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_codesigning/lib/StaticCode.cpp
Security-58286.230.21.tar.gz
[apple/security.git] / OSX / libsecurity_codesigning / lib / StaticCode.cpp
1 /*
2 * Copyright (c) 2006-2015 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 #if TARGET_OS_OSX
31 #include "drmaker.h"
32 #include "notarization.h"
33 #endif
34 #include "reqdumper.h"
35 #include "reqparser.h"
36 #include "sigblob.h"
37 #include "resources.h"
38 #include "detachedrep.h"
39 #include "signerutils.h"
40 #if TARGET_OS_OSX
41 #include "csdatabase.h"
42 #endif
43 #include "dirscanner.h"
44 #include <CoreFoundation/CFURLAccess.h>
45 #include <Security/SecPolicyPriv.h>
46 #include <Security/SecTrustPriv.h>
47 #include <Security/SecCertificatePriv.h>
48 #if TARGET_OS_OSX
49 #include <Security/CMSPrivate.h>
50 #endif
51 #import <Security/SecCMS.h>
52 #include <Security/SecCmsContentInfo.h>
53 #include <Security/SecCmsSignerInfo.h>
54 #include <Security/SecCmsSignedData.h>
55 #if TARGET_OS_OSX
56 #include <Security/cssmapplePriv.h>
57 #endif
58 #include <security_utilities/unix++.h>
59 #include <security_utilities/cfmunge.h>
60 #include <security_utilities/casts.h>
61 #include <Security/CMSDecoder.h>
62 #include <security_utilities/logging.h>
63 #include <dirent.h>
64 #include <sys/xattr.h>
65 #include <sstream>
66 #include <IOKit/storage/IOStorageDeviceCharacteristics.h>
67 #include <dispatch/private.h>
68 #include <os/assumes.h>
69 #include <regex.h>
70
71
72 namespace Security {
73 namespace CodeSigning {
74
75 using namespace UnixPlusPlus;
76
77 // A requirement representing a Mac or iOS dev cert, a Mac or iOS distribution cert, or a developer ID
78 static const char WWDRRequirement[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.2] exists";
79 static const char MACWWDRRequirement[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.12] exists";
80 static const char developerID[] = "anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists"
81 " and certificate leaf[field.1.2.840.113635.100.6.1.13] exists";
82 static const char distributionCertificate[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.7] exists";
83 static const char iPhoneDistributionCert[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.4] exists";
84
85 //
86 // Map a component slot number to a suitable error code for a failure
87 //
88 static inline OSStatus errorForSlot(CodeDirectory::SpecialSlot slot)
89 {
90 switch (slot) {
91 case cdInfoSlot:
92 return errSecCSInfoPlistFailed;
93 case cdResourceDirSlot:
94 return errSecCSResourceDirectoryFailed;
95 default:
96 return errSecCSSignatureFailed;
97 }
98 }
99
100
101 //
102 // Construct a SecStaticCode object given a disk representation object
103 //
104 SecStaticCode::SecStaticCode(DiskRep *rep, uint32_t flags)
105 : mCheckfix30814861builder1(NULL),
106 mRep(rep),
107 mValidated(false), mExecutableValidated(false), mResourcesValidated(false), mResourcesValidContext(NULL),
108 mProgressQueue("com.apple.security.validation-progress", false, QOS_CLASS_UNSPECIFIED),
109 mOuterScope(NULL), mResourceScope(NULL),
110 mDesignatedReq(NULL), mGotResourceBase(false), mMonitor(NULL), mLimitedAsync(NULL),
111 mFlags(flags), mNotarizationChecked(false), mStaplingChecked(false), mNotarizationDate(NAN)
112 #if TARGET_OS_OSX
113 , mEvalDetails(NULL)
114 #else
115 , mTrustedSigningCertChain(false)
116 #endif
117
118 {
119 CODESIGN_STATIC_CREATE(this, rep);
120 #if TARGET_OS_OSX
121 checkForSystemSignature();
122 #endif
123 }
124
125
126 //
127 // Clean up a SecStaticCode object
128 //
129 SecStaticCode::~SecStaticCode() throw()
130 try {
131 ::free(const_cast<Requirement *>(mDesignatedReq));
132 delete mResourcesValidContext;
133 delete mLimitedAsync;
134 delete mCheckfix30814861builder1;
135 } catch (...) {
136 return;
137 }
138
139 //
140 // Initialize a nested SecStaticCode object from its parent
141 //
142 void SecStaticCode::initializeFromParent(const SecStaticCode& parent) {
143 mOuterScope = &parent;
144 setMonitor(parent.monitor());
145 if (parent.mLimitedAsync)
146 mLimitedAsync = new LimitedAsync(*parent.mLimitedAsync);
147 }
148
149 //
150 // CF-level comparison of SecStaticCode objects compares CodeDirectory hashes if signed,
151 // and falls back on comparing canonical paths if (both are) not.
152 //
153 bool SecStaticCode::equal(SecCFObject &secOther)
154 {
155 SecStaticCode *other = static_cast<SecStaticCode *>(&secOther);
156 CFDataRef mine = this->cdHash();
157 CFDataRef his = other->cdHash();
158 if (mine || his)
159 return mine && his && CFEqual(mine, his);
160 else
161 return CFEqual(CFRef<CFURLRef>(this->copyCanonicalPath()), CFRef<CFURLRef>(other->copyCanonicalPath()));
162 }
163
164 CFHashCode SecStaticCode::hash()
165 {
166 if (CFDataRef h = this->cdHash())
167 return CFHash(h);
168 else
169 return CFHash(CFRef<CFURLRef>(this->copyCanonicalPath()));
170 }
171
172
173 //
174 // Invoke a stage monitor if registered
175 //
176 CFTypeRef SecStaticCode::reportEvent(CFStringRef stage, CFDictionaryRef info)
177 {
178 if (mMonitor)
179 return mMonitor(this->handle(false), stage, info);
180 else
181 return NULL;
182 }
183
184 void SecStaticCode::prepareProgress(unsigned int workload)
185 {
186 dispatch_sync(mProgressQueue, ^{
187 mCancelPending = false; // not canceled
188 });
189 if (mValidationFlags & kSecCSReportProgress) {
190 mCurrentWork = 0; // nothing done yet
191 mTotalWork = workload; // totally fake - we don't know how many files we'll get to chew
192 }
193 }
194
195 void SecStaticCode::reportProgress(unsigned amount /* = 1 */)
196 {
197 if (mMonitor && (mValidationFlags & kSecCSReportProgress)) {
198 // update progress and report
199 __block bool cancel = false;
200 dispatch_sync(mProgressQueue, ^{
201 if (mCancelPending)
202 cancel = true;
203 mCurrentWork += amount;
204 mMonitor(this->handle(false), CFSTR("progress"), CFTemp<CFDictionaryRef>("{current=%d,total=%d}", mCurrentWork, mTotalWork));
205 });
206 // if cancellation is pending, abort now
207 if (cancel)
208 MacOSError::throwMe(errSecCSCancelled);
209 }
210 }
211
212
213 //
214 // Set validation conditions for fine-tuning legacy tolerance
215 //
216 static void addError(CFTypeRef cfError, void* context)
217 {
218 if (CFGetTypeID(cfError) == CFNumberGetTypeID()) {
219 int64_t error;
220 CFNumberGetValue(CFNumberRef(cfError), kCFNumberSInt64Type, (void*)&error);
221 MacOSErrorSet* errors = (MacOSErrorSet*)context;
222 errors->insert(OSStatus(error));
223 }
224 }
225
226 void SecStaticCode::setValidationModifiers(CFDictionaryRef conditions)
227 {
228 if (conditions) {
229 CFDictionary source(conditions, errSecCSDbCorrupt);
230 mAllowOmissions = source.get<CFArrayRef>("omissions");
231 if (CFArrayRef errors = source.get<CFArrayRef>("errors"))
232 CFArrayApplyFunction(errors, CFRangeMake(0, CFArrayGetCount(errors)), addError, &this->mTolerateErrors);
233 }
234 }
235
236
237 //
238 // Request cancellation of a validation in progress.
239 // We do this by posting an abort flag that is checked periodically.
240 //
241 void SecStaticCode::cancelValidation()
242 {
243 if (!(mValidationFlags & kSecCSReportProgress)) // not using progress reporting; cancel won't make it through
244 MacOSError::throwMe(errSecCSInvalidFlags);
245 dispatch_assert_queue(mProgressQueue);
246 mCancelPending = true;
247 }
248
249
250 //
251 // Attach a detached signature.
252 //
253 void SecStaticCode::detachedSignature(CFDataRef sigData)
254 {
255 if (sigData) {
256 mDetachedSig = sigData;
257 mRep = new DetachedRep(sigData, mRep->base(), "explicit detached");
258 CODESIGN_STATIC_ATTACH_EXPLICIT(this, mRep);
259 } else {
260 mDetachedSig = NULL;
261 mRep = mRep->base();
262 CODESIGN_STATIC_ATTACH_EXPLICIT(this, NULL);
263 }
264 }
265
266
267 //
268 // Consult the system detached signature database to see if it contains
269 // a detached signature for this StaticCode. If it does, fetch and attach it.
270 // We do this only if the code has no signature already attached.
271 //
272 void SecStaticCode::checkForSystemSignature()
273 {
274 #if TARGET_OS_OSX
275 if (!this->isSigned()) {
276 SignatureDatabase db;
277 if (db.isOpen())
278 try {
279 if (RefPointer<DiskRep> dsig = db.findCode(mRep)) {
280 CODESIGN_STATIC_ATTACH_SYSTEM(this, dsig);
281 mRep = dsig;
282 }
283 } catch (...) {
284 }
285 }
286 #else
287 MacOSError::throwMe(errSecUnimplemented);
288 #endif
289 }
290
291
292 //
293 // Return a descriptive string identifying the source of the code signature
294 //
295 string SecStaticCode::signatureSource()
296 {
297 if (!isSigned())
298 return "unsigned";
299 if (DetachedRep *rep = dynamic_cast<DetachedRep *>(mRep.get()))
300 return rep->source();
301 return "embedded";
302 }
303
304
305 //
306 // Do ::required, but convert incoming SecCodeRefs to their SecStaticCodeRefs
307 // (if possible).
308 //
309 SecStaticCode *SecStaticCode::requiredStatic(SecStaticCodeRef ref)
310 {
311 SecCFObject *object = SecCFObject::required(ref, errSecCSInvalidObjectRef);
312 if (SecStaticCode *scode = dynamic_cast<SecStaticCode *>(object))
313 return scode;
314 else if (SecCode *code = dynamic_cast<SecCode *>(object))
315 return code->staticCode();
316 else // neither (a SecSomethingElse)
317 MacOSError::throwMe(errSecCSInvalidObjectRef);
318 }
319
320 SecCode *SecStaticCode::optionalDynamic(SecStaticCodeRef ref)
321 {
322 SecCFObject *object = SecCFObject::required(ref, errSecCSInvalidObjectRef);
323 if (dynamic_cast<SecStaticCode *>(object))
324 return NULL;
325 else if (SecCode *code = dynamic_cast<SecCode *>(object))
326 return code;
327 else // neither (a SecSomethingElse)
328 MacOSError::throwMe(errSecCSInvalidObjectRef);
329 }
330
331
332 //
333 // Void all cached validity data.
334 //
335 // We also throw out cached components, because the new signature data may have
336 // a different idea of what components should be present. We could reconcile the
337 // cached data instead, if performance seems to be impacted.
338 //
339 void SecStaticCode::resetValidity()
340 {
341 CODESIGN_EVAL_STATIC_RESET(this);
342 mValidated = false;
343 mExecutableValidated = mResourcesValidated = false;
344 if (mResourcesValidContext) {
345 delete mResourcesValidContext;
346 mResourcesValidContext = NULL;
347 }
348 mDir = NULL;
349 mCodeDirectories.clear();
350 mSignature = NULL;
351 for (unsigned n = 0; n < cdSlotCount; n++)
352 mCache[n] = NULL;
353 mInfoDict = NULL;
354 mEntitlements = NULL;
355 mResourceDict = NULL;
356 mDesignatedReq = NULL;
357 mCDHash = NULL;
358 mGotResourceBase = false;
359 mTrust = NULL;
360 mCertChain = NULL;
361 #if TARGET_OS_OSX
362 mEvalDetails = NULL;
363 #endif
364 mRep->flush();
365
366 #if TARGET_OS_OSX
367 // we may just have updated the system database, so check again
368 checkForSystemSignature();
369 #endif
370 }
371
372
373 //
374 // Retrieve a sealed component by special slot index.
375 // If the CodeDirectory has already been validated, validate against that.
376 // Otherwise, retrieve the component without validation (but cache it). Validation
377 // will go through the cache and validate all cached components.
378 //
379 CFDataRef SecStaticCode::component(CodeDirectory::SpecialSlot slot, OSStatus fail /* = errSecCSSignatureFailed */)
380 {
381 assert(slot <= cdSlotMax);
382
383 CFRef<CFDataRef> &cache = mCache[slot];
384 if (!cache) {
385 if (CFRef<CFDataRef> data = mRep->component(slot)) {
386 if (validated()) { // if the directory has been validated...
387 if (!codeDirectory()->slotIsPresent(-slot))
388 return NULL;
389
390 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data), // ... and it's no good
391 CFDataGetLength(data), -slot, false))
392 MacOSError::throwMe(errorForSlot(slot)); // ... then bail
393 }
394 cache = data; // it's okay, cache it
395 } else { // absent, mark so
396 if (validated()) // if directory has been validated...
397 if (codeDirectory()->slotIsPresent(-slot)) // ... and the slot is NOT missing
398 MacOSError::throwMe(errorForSlot(slot)); // was supposed to be there
399 cache = CFDataRef(kCFNull); // white lie
400 }
401 }
402 return (cache == CFDataRef(kCFNull)) ? NULL : cache.get();
403 }
404
405
406 //
407 // Get the CodeDirectories.
408 // Throws (if check==true) or returns NULL (check==false) if there are none.
409 // Always throws if the CodeDirectories exist but are invalid.
410 // NEVER validates against the signature.
411 //
412 const SecStaticCode::CodeDirectoryMap *
413 SecStaticCode::codeDirectories(bool check /* = true */) const
414 {
415 if (mCodeDirectories.empty()) {
416 try {
417 loadCodeDirectories(mCodeDirectories);
418 } catch (...) {
419 if (check)
420 throw;
421 // We wanted a NON-checked peek and failed to safely decode the existing CodeDirectories.
422 // Pretend this is unsigned, but make sure we didn't somehow cache an invalid CodeDirectory.
423 if (!mCodeDirectories.empty()) {
424 assert(false);
425 Syslog::warning("code signing internal problem: mCodeDirectories set despite exception exit");
426 MacOSError::throwMe(errSecCSInternalError);
427 }
428 }
429 } else {
430 return &mCodeDirectories;
431 }
432 if (!mCodeDirectories.empty()) {
433 return &mCodeDirectories;
434 }
435 if (check) {
436 MacOSError::throwMe(errSecCSUnsigned);
437 }
438 return NULL;
439 }
440
441 //
442 // Get the CodeDirectory.
443 // Throws (if check==true) or returns NULL (check==false) if there is none.
444 // Always throws if the CodeDirectory exists but is invalid.
445 // NEVER validates against the signature.
446 //
447 const CodeDirectory *SecStaticCode::codeDirectory(bool check /* = true */) const
448 {
449 if (!mDir) {
450 // pick our favorite CodeDirectory from the choices we've got
451 try {
452 CodeDirectoryMap const *candidates = codeDirectories(check);
453 if (candidates != NULL) {
454 CodeDirectory::HashAlgorithm type = CodeDirectory::bestHashOf(mHashAlgorithms);
455 mDir = candidates->at(type); // and the winner is...
456 }
457 } catch (...) {
458 if (check)
459 throw;
460 // We wanted a NON-checked peek and failed to safely decode the existing CodeDirectory.
461 // Pretend this is unsigned, but make sure we didn't somehow cache an invalid CodeDirectory.
462 if (mDir) {
463 assert(false);
464 Syslog::warning("code signing internal problem: mDir set despite exception exit");
465 MacOSError::throwMe(errSecCSInternalError);
466 }
467 }
468 }
469 if (mDir)
470 return reinterpret_cast<const CodeDirectory *>(CFDataGetBytePtr(mDir));
471 if (check)
472 MacOSError::throwMe(errSecCSUnsigned);
473 return NULL;
474 }
475
476
477 //
478 // Fetch an array of all available CodeDirectories.
479 // Returns false if unsigned (no classic CD slot), true otherwise.
480 //
481 bool SecStaticCode::loadCodeDirectories(CodeDirectoryMap& cdMap) const
482 {
483 __block CodeDirectoryMap candidates;
484 __block CodeDirectory::HashAlgorithms hashAlgorithms;
485 __block CFRef<CFDataRef> baseDir;
486 auto add = ^bool (CodeDirectory::SpecialSlot slot){
487 CFRef<CFDataRef> cdData = diskRep()->component(slot);
488 if (!cdData)
489 return false;
490 const CodeDirectory* cd = reinterpret_cast<const CodeDirectory*>(CFDataGetBytePtr(cdData));
491 if (!cd->validateBlob(CFDataGetLength(cdData)))
492 MacOSError::throwMe(errSecCSSignatureFailed); // no recovery - any suspect CD fails
493 cd->checkIntegrity();
494 auto result = candidates.insert(make_pair(cd->hashType, cdData.get()));
495 if (!result.second)
496 MacOSError::throwMe(errSecCSSignatureInvalid); // duplicate hashType, go to heck
497 hashAlgorithms.insert(cd->hashType);
498 if (slot == cdCodeDirectorySlot)
499 baseDir = cdData;
500 return true;
501 };
502 if (!add(cdCodeDirectorySlot))
503 return false; // no classic slot CodeDirectory -> unsigned
504 for (CodeDirectory::SpecialSlot slot = cdAlternateCodeDirectorySlots; slot < cdAlternateCodeDirectoryLimit; slot++)
505 if (!add(slot)) // no CodeDirectory at this slot -> end of alternates
506 break;
507 if (candidates.empty())
508 MacOSError::throwMe(errSecCSSignatureFailed); // no viable CodeDirectory in sight
509 // commit to cached values
510 cdMap.swap(candidates);
511 mHashAlgorithms.swap(hashAlgorithms);
512 mBaseDir = baseDir;
513 return true;
514 }
515
516
517 //
518 // Get the hash of the CodeDirectory.
519 // Returns NULL if there is none.
520 //
521 CFDataRef SecStaticCode::cdHash()
522 {
523 if (!mCDHash) {
524 if (const CodeDirectory *cd = codeDirectory(false)) {
525 mCDHash.take(cd->cdhash());
526 CODESIGN_STATIC_CDHASH(this, CFDataGetBytePtr(mCDHash), (unsigned int)CFDataGetLength(mCDHash));
527 }
528 }
529 return mCDHash;
530 }
531
532
533 //
534 // Get an array of the cdhashes for all digest types in this signature
535 // The array is sorted by cd->hashType.
536 //
537 CFArrayRef SecStaticCode::cdHashes()
538 {
539 if (!mCDHashes) {
540 CFRef<CFMutableArrayRef> cdList = makeCFMutableArray(0);
541 for (auto it = mCodeDirectories.begin(); it != mCodeDirectories.end(); ++it) {
542 const CodeDirectory *cd = (const CodeDirectory *)CFDataGetBytePtr(it->second);
543 if (CFRef<CFDataRef> hash = cd->cdhash())
544 CFArrayAppendValue(cdList, hash);
545 }
546 mCDHashes = cdList.get();
547 }
548 return mCDHashes;
549 }
550
551
552 //
553 // Return the CMS signature blob; NULL if none found.
554 //
555 CFDataRef SecStaticCode::signature()
556 {
557 if (!mSignature)
558 mSignature.take(mRep->signature());
559 if (mSignature)
560 return mSignature;
561 MacOSError::throwMe(errSecCSUnsigned);
562 }
563
564
565 //
566 // Verify the signature on the CodeDirectory.
567 // If this succeeds (doesn't throw), the CodeDirectory is statically trustworthy.
568 // Any outcome (successful or not) is cached for the lifetime of the StaticCode.
569 //
570 void SecStaticCode::validateDirectory()
571 {
572 // echo previous outcome, if any
573 // track revocation separately, as it may not have been checked
574 // during the initial validation
575 if (!validated() || ((mValidationFlags & kSecCSEnforceRevocationChecks) && !revocationChecked()))
576 try {
577 // perform validation (or die trying)
578 CODESIGN_EVAL_STATIC_DIRECTORY(this);
579 mValidationExpired = verifySignature();
580 if (mValidationFlags & kSecCSEnforceRevocationChecks)
581 mRevocationChecked = true;
582
583 for (CodeDirectory::SpecialSlot slot = codeDirectory()->maxSpecialSlot(); slot >= 1; --slot)
584 if (mCache[slot]) // if we already loaded that resource...
585 validateComponent(slot, errorForSlot(slot)); // ... then check it now
586 mValidated = true; // we've done the deed...
587 mValidationResult = errSecSuccess; // ... and it was good
588 } catch (const CommonError &err) {
589 mValidated = true;
590 mValidationResult = err.osStatus();
591 throw;
592 } catch (...) {
593 secinfo("staticCode", "%p validation threw non-common exception", this);
594 mValidated = true;
595 Syslog::notice("code signing internal problem: unknown exception thrown by validation");
596 mValidationResult = errSecCSInternalError;
597 throw;
598 }
599 assert(validated());
600 // XXX: Embedded doesn't have CSSMERR_TP_CERT_EXPIRED so we can't throw it
601 // XXX: This should be implemented for embedded once we implement
602 // XXX: verifySignature and see how we're going to handle expired certs
603 #if TARGET_OS_OSX
604 if (mValidationResult == errSecSuccess) {
605 if (mValidationExpired)
606 if ((mValidationFlags & kSecCSConsiderExpiration)
607 || (codeDirectory()->flags & kSecCodeSignatureForceExpiration))
608 MacOSError::throwMe(CSSMERR_TP_CERT_EXPIRED);
609 } else
610 MacOSError::throwMe(mValidationResult);
611 #endif
612 }
613
614
615 //
616 // Load and validate the CodeDirectory and all components *except* those related to the resource envelope.
617 // Those latter components are checked by validateResources().
618 //
619 void SecStaticCode::validateNonResourceComponents()
620 {
621 this->validateDirectory();
622 for (CodeDirectory::SpecialSlot slot = codeDirectory()->maxSpecialSlot(); slot >= 1; --slot)
623 switch (slot) {
624 case cdResourceDirSlot: // validated by validateResources
625 break;
626 default:
627 this->component(slot); // loads and validates
628 break;
629 }
630 }
631
632
633 //
634 // Check that any "top index" sealed into the signature conforms to what's actually here.
635 //
636 void SecStaticCode::validateTopDirectory()
637 {
638 assert(mDir); // must already have loaded CodeDirectories
639 if (CFDataRef topDirectory = component(cdTopDirectorySlot)) {
640 const auto topData = (const Endian<uint32_t> *)CFDataGetBytePtr(topDirectory);
641 const auto topDataEnd = topData + CFDataGetLength(topDirectory) / sizeof(*topData);
642 std::vector<uint32_t> signedVector(topData, topDataEnd);
643
644 std::vector<uint32_t> foundVector;
645 foundVector.push_back(cdCodeDirectorySlot); // mandatory
646 for (CodeDirectory::Slot slot = 1; slot <= cdSlotMax; ++slot)
647 if (component(slot))
648 foundVector.push_back(slot);
649 int alternateCount = int(mCodeDirectories.size() - 1); // one will go into cdCodeDirectorySlot
650 for (int n = 0; n < alternateCount; n++)
651 foundVector.push_back(cdAlternateCodeDirectorySlots + n);
652 foundVector.push_back(cdSignatureSlot); // mandatory (may be empty)
653
654 if (signedVector != foundVector)
655 MacOSError::throwMe(errSecCSSignatureFailed);
656 }
657 }
658
659
660 //
661 // Get the (signed) signing date from the code signature.
662 // Sadly, we need to validate the signature to get the date (as a side benefit).
663 // This means that you can't get the signing time for invalidly signed code.
664 //
665 // We could run the decoder "almost to" verification to avoid this, but there seems
666 // little practical point to such a duplication of effort.
667 //
668 CFAbsoluteTime SecStaticCode::signingTime()
669 {
670 validateDirectory();
671 return mSigningTime;
672 }
673
674 CFAbsoluteTime SecStaticCode::signingTimestamp()
675 {
676 validateDirectory();
677 return mSigningTimestamp;
678 }
679
680 #if TARGET_OS_OSX
681 #define kSecSHA256HashSize 32
682 // subject:/C=US/ST=California/L=San Jose/O=Adobe Systems Incorporated/OU=Information Systems/OU=Digital ID Class 3 - Microsoft Software Validation v2/CN=Adobe Systems Incorporated
683 // issuer :/C=US/O=VeriSign, Inc./OU=VeriSign Trust Network/OU=Terms of use at https://www.verisign.com/rpa (c)10/CN=VeriSign Class 3 Code Signing 2010 CA
684 // Not Before: Dec 15 00:00:00 2010 GMT
685 // Not After : Dec 14 23:59:59 2012 GMT
686 static const unsigned char ASI_CS_12[] = {
687 0x77,0x82,0x9C,0x64,0x33,0x45,0x2E,0x4A,0xD3,0xA8,0xE4,0x6F,0x00,0x6C,0x27,0xEA,
688 0xFB,0xD3,0xF2,0x6D,0x50,0xF3,0x6F,0xE0,0xE9,0x6D,0x06,0x59,0x19,0xB5,0x46,0xFF
689 };
690
691 bool SecStaticCode::checkfix41082220(OSStatus cssmTrustResult)
692 {
693 // only applicable to revoked results
694 if (cssmTrustResult != CSSMERR_TP_CERT_REVOKED) {
695 return false;
696 }
697
698 // only this leaf certificate
699 if (CFArrayGetCount(mCertChain) == 0) {
700 return false;
701 }
702 CFRef<CFDataRef> leafHash(SecCertificateCopySHA256Digest((SecCertificateRef)CFArrayGetValueAtIndex(mCertChain, 0)));
703 if (memcmp(ASI_CS_12, CFDataGetBytePtr(leafHash), kSecSHA256HashSize) != 0) {
704 return false;
705 }
706
707 // detached dmg signature
708 if (!isDetached() || format() != std::string("disk image")) {
709 return false;
710 }
711
712 // sha-1 signed
713 if (hashAlgorithms().size() != 1 || hashAlgorithm() != kSecCodeSignatureHashSHA1) {
714 return false;
715 }
716
717 // not a privileged binary - no TeamID and no entitlements
718 if (component(cdEntitlementSlot) || teamID()) {
719 return false;
720 }
721
722 // no flags and old version
723 if (codeDirectory()->version != 0x20100 || codeDirectory()->flags != 0) {
724 return false;
725 }
726
727 Security::Syslog::warning("CodeSigning: Check-fix enabled for dmg '%s' with identifier '%s' signed with revoked certificates",
728 mainExecutablePath().c_str(), identifier().c_str());
729 return true;
730 }
731 #endif // TARGET_OS_OSX
732
733 //
734 // Verify the CMS signature.
735 // This performs the cryptographic tango. It returns if the signature is valid,
736 // or throws if it is not. As a side effect, a successful return sets up the
737 // cached certificate chain for future use.
738 // Returns true if the signature is expired (the X.509 sense), false if it's not.
739 // Expiration is fatal (throws) if a secure timestamp is included, but not otherwise.
740 //
741 bool SecStaticCode::verifySignature()
742 {
743 // ad-hoc signed code is considered validly signed by definition
744 if (flag(kSecCodeSignatureAdhoc)) {
745 CODESIGN_EVAL_STATIC_SIGNATURE_ADHOC(this);
746 return false;
747 }
748
749 DTRACK(CODESIGN_EVAL_STATIC_SIGNATURE, this, (char*)this->mainExecutablePath().c_str());
750 #if TARGET_OS_OSX
751 // decode CMS and extract SecTrust for verification
752 CFRef<CMSDecoderRef> cms;
753 MacOSError::check(CMSDecoderCreate(&cms.aref())); // create decoder
754 CFDataRef sig = this->signature();
755 MacOSError::check(CMSDecoderUpdateMessage(cms, CFDataGetBytePtr(sig), CFDataGetLength(sig)));
756 this->codeDirectory(); // load CodeDirectory (sets mDir)
757 MacOSError::check(CMSDecoderSetDetachedContent(cms, mBaseDir));
758 MacOSError::check(CMSDecoderFinalizeMessage(cms));
759 MacOSError::check(CMSDecoderSetSearchKeychain(cms, cfEmptyArray()));
760 CFRef<CFArrayRef> vf_policies(createVerificationPolicies());
761 CFRef<CFArrayRef> ts_policies(createTimeStampingAndRevocationPolicies());
762
763 CMSSignerStatus status;
764 MacOSError::check(CMSDecoderCopySignerStatus(cms, 0, vf_policies,
765 false, &status, &mTrust.aref(), NULL));
766
767 if (status != kCMSSignerValid) {
768 const char *reason;
769 switch (status) {
770 case kCMSSignerUnsigned: reason="kCMSSignerUnsigned"; break;
771 case kCMSSignerNeedsDetachedContent: reason="kCMSSignerNeedsDetachedContent"; break;
772 case kCMSSignerInvalidSignature: reason="kCMSSignerInvalidSignature"; break;
773 case kCMSSignerInvalidCert: reason="kCMSSignerInvalidCert"; break;
774 case kCMSSignerInvalidIndex: reason="kCMSSignerInvalidIndex"; break;
775 default: reason="unknown"; break;
776 }
777 Security::Syslog::error("CMSDecoderCopySignerStatus failed with %s error (%d)",
778 reason, (int)status);
779 MacOSError::throwMe(errSecCSSignatureFailed);
780 }
781
782 // retrieve auxiliary v1 data bag and verify against current state
783 CFRef<CFDataRef> hashAgilityV1;
784 switch (OSStatus rc = CMSDecoderCopySignerAppleCodesigningHashAgility(cms, 0, &hashAgilityV1.aref())) {
785 case noErr:
786 if (hashAgilityV1) {
787 CFRef<CFDictionaryRef> hashDict = makeCFDictionaryFrom(hashAgilityV1);
788 CFArrayRef cdList = CFArrayRef(CFDictionaryGetValue(hashDict, CFSTR("cdhashes")));
789 CFArrayRef myCdList = this->cdHashes();
790
791 /* Note that this is not very "agile": There's no way to calculate the exact
792 * list for comparison if it contains hash algorithms we don't know yet... */
793 if (cdList == NULL || !CFEqual(cdList, myCdList))
794 MacOSError::throwMe(errSecCSSignatureFailed);
795 }
796 break;
797 case -1: /* CMS used to return this for "no attribute found", so tolerate it. Now returning noErr/NULL */
798 break;
799 default:
800 MacOSError::throwMe(rc);
801 }
802
803 // retrieve auxiliary v2 data bag and verify against current state
804 CFRef<CFDictionaryRef> hashAgilityV2;
805 switch (OSStatus rc = CMSDecoderCopySignerAppleCodesigningHashAgilityV2(cms, 0, &hashAgilityV2.aref())) {
806 case noErr:
807 if (hashAgilityV2) {
808 /* Require number of code directoris and entries in the hash agility
809 * dict to be the same size (no stripping out code directories).
810 */
811 if (CFDictionaryGetCount(hashAgilityV2) != mCodeDirectories.size()) {
812 MacOSError::throwMe(errSecCSSignatureFailed);
813 }
814
815 /* Require every cdhash of every code directory whose hash
816 * algorithm we know to be in the agility dictionary.
817 *
818 * We check untruncated cdhashes here because we can.
819 */
820 bool foundOurs = false;
821 for (auto& entry : mCodeDirectories) {
822 SECOidTag tag = CodeDirectorySet::SECOidTagForAlgorithm(entry.first);
823
824 if (tag == SEC_OID_UNKNOWN) {
825 // Unknown hash algorithm, ignore.
826 continue;
827 }
828
829 CFRef<CFNumberRef> key = makeCFNumber(int(tag));
830 CFRef<CFDataRef> entryCdhash;
831 entryCdhash = (CFDataRef)CFDictionaryGetValue(hashAgilityV2, (void*)key.get());
832
833 CodeDirectory const *cd = (CodeDirectory const*)CFDataGetBytePtr(entry.second);
834 CFRef<CFDataRef> ourCdhash = cd->cdhash(false); // Untruncated cdhash!
835 if (!CFEqual(entryCdhash, ourCdhash)) {
836 MacOSError::throwMe(errSecCSSignatureFailed);
837 }
838
839 if (entry.first == this->hashAlgorithm()) {
840 foundOurs = true;
841 }
842 }
843
844 /* Require the cdhash of our chosen code directory to be in the dictionary.
845 * In theory, the dictionary could be full of unsupported cdhashes, but we
846 * really want ours, which is bound to be supported, to be covered.
847 */
848 if (!foundOurs) {
849 MacOSError::throwMe(errSecCSSignatureFailed);
850 }
851 }
852 break;
853 case -1: /* CMS used to return this for "no attribute found", so tolerate it. Now returning noErr/NULL */
854 break;
855 default:
856 MacOSError::throwMe(rc);
857 }
858
859 // internal signing time (as specified by the signer; optional)
860 mSigningTime = 0; // "not present" marker (nobody could code sign on Jan 1, 2001 :-)
861 switch (OSStatus rc = CMSDecoderCopySignerSigningTime(cms, 0, &mSigningTime)) {
862 case errSecSuccess:
863 case errSecSigningTimeMissing:
864 break;
865 default:
866 Security::Syslog::error("Could not get signing time (error %d)", (int)rc);
867 MacOSError::throwMe(rc);
868 }
869
870 // certified signing time (as specified by a TSA; optional)
871 mSigningTimestamp = 0;
872 switch (OSStatus rc = CMSDecoderCopySignerTimestampWithPolicy(cms, ts_policies, 0, &mSigningTimestamp)) {
873 case errSecSuccess:
874 case errSecTimestampMissing:
875 break;
876 default:
877 Security::Syslog::error("Could not get timestamp (error %d)", (int)rc);
878 MacOSError::throwMe(rc);
879 }
880
881 // set up the environment for SecTrust
882 if (mValidationFlags & kSecCSNoNetworkAccess) {
883 MacOSError::check(SecTrustSetNetworkFetchAllowed(mTrust,false)); // no network?
884 }
885 MacOSError::check(SecTrustSetKeychainsAllowed(mTrust, false));
886
887 CSSM_APPLE_TP_ACTION_DATA actionData = {
888 CSSM_APPLE_TP_ACTION_VERSION, // version of data structure
889 0 // action flags
890 };
891
892 if (!(mValidationFlags & kSecCSCheckTrustedAnchors)) {
893 /* no need to evaluate anchor trust when building cert chain */
894 MacOSError::check(SecTrustSetAnchorCertificates(mTrust, cfEmptyArray())); // no anchors
895 actionData.ActionFlags |= CSSM_TP_ACTION_IMPLICIT_ANCHORS; // action flags
896 }
897
898 for (;;) { // at most twice
899 MacOSError::check(SecTrustSetParameters(mTrust,
900 CSSM_TP_ACTION_DEFAULT, CFTempData(&actionData, sizeof(actionData))));
901
902 // evaluate trust and extract results
903 SecTrustResultType trustResult;
904 MacOSError::check(SecTrustEvaluate(mTrust, &trustResult));
905 MacOSError::check(SecTrustGetResult(mTrust, &trustResult, &mCertChain.aref(), &mEvalDetails));
906
907 // if this is an Apple developer cert....
908 if (teamID() && SecStaticCode::isAppleDeveloperCert(mCertChain)) {
909 CFRef<CFStringRef> teamIDFromCert;
910 if (CFArrayGetCount(mCertChain) > 0) {
911 /* Note that SecCertificateCopySubjectComponent sets the out parameter to NULL if there is no field present */
912 MacOSError::check(SecCertificateCopySubjectComponent((SecCertificateRef)CFArrayGetValueAtIndex(mCertChain, Requirement::leafCert),
913 &CSSMOID_OrganizationalUnitName,
914 &teamIDFromCert.aref()));
915
916 if (teamIDFromCert) {
917 CFRef<CFStringRef> teamIDFromCD = CFStringCreateWithCString(NULL, teamID(), kCFStringEncodingUTF8);
918 if (!teamIDFromCD) {
919 Security::Syslog::error("Could not get team identifier (%s)", teamID());
920 MacOSError::throwMe(errSecCSInvalidTeamIdentifier);
921 }
922
923 if (CFStringCompare(teamIDFromCert, teamIDFromCD, 0) != kCFCompareEqualTo) {
924 Security::Syslog::error("Team identifier in the signing certificate (%s) does not match the team identifier (%s) in the code directory",
925 cfString(teamIDFromCert).c_str(), teamID());
926 MacOSError::throwMe(errSecCSBadTeamIdentifier);
927 }
928 }
929 }
930 }
931
932 CODESIGN_EVAL_STATIC_SIGNATURE_RESULT(this, trustResult, mCertChain ? (int)CFArrayGetCount(mCertChain) : 0);
933 switch (trustResult) {
934 case kSecTrustResultProceed:
935 case kSecTrustResultUnspecified:
936 break; // success
937 case kSecTrustResultDeny:
938 MacOSError::throwMe(CSSMERR_APPLETP_TRUST_SETTING_DENY); // user reject
939 case kSecTrustResultInvalid:
940 assert(false); // should never happen
941 MacOSError::throwMe(CSSMERR_TP_NOT_TRUSTED);
942 default:
943 {
944 OSStatus result;
945 MacOSError::check(SecTrustGetCssmResultCode(mTrust, &result));
946 // if we have a valid timestamp, CMS validates against (that) signing time and all is well.
947 // If we don't have one, may validate against *now*, and must be able to tolerate expiration.
948 if (mSigningTimestamp == 0) { // no timestamp available
949 if (((result == CSSMERR_TP_CERT_EXPIRED) || (result == CSSMERR_TP_CERT_NOT_VALID_YET))
950 && !(actionData.ActionFlags & CSSM_TP_ACTION_ALLOW_EXPIRED)) {
951 CODESIGN_EVAL_STATIC_SIGNATURE_EXPIRED(this);
952 actionData.ActionFlags |= CSSM_TP_ACTION_ALLOW_EXPIRED; // (this also allows postdated certs)
953 continue; // retry validation while tolerating expiration
954 }
955 }
956 if (checkfix41082220(result)) {
957 break; // success
958 }
959 Security::Syslog::error("SecStaticCode: verification failed (trust result %d, error %d)", trustResult, (int)result);
960 MacOSError::throwMe(result);
961 }
962 }
963
964 if (mSigningTimestamp) {
965 CFIndex rootix = CFArrayGetCount(mCertChain);
966 if (SecCertificateRef mainRoot = SecCertificateRef(CFArrayGetValueAtIndex(mCertChain, rootix-1)))
967 if (isAppleCA(mainRoot)) {
968 // impose policy: if the signature itself draws to Apple, then so must the timestamp signature
969 CFRef<CFArrayRef> tsCerts;
970 OSStatus result = CMSDecoderCopySignerTimestampCertificates(cms, 0, &tsCerts.aref());
971 if (result) {
972 Security::Syslog::error("SecStaticCode: could not get timestamp certificates (error %d)", (int)result);
973 MacOSError::check(result);
974 }
975 CFIndex tsn = CFArrayGetCount(tsCerts);
976 bool good = tsn > 0 && isAppleCA(SecCertificateRef(CFArrayGetValueAtIndex(tsCerts, tsn-1)));
977 if (!good) {
978 result = CSSMERR_TP_NOT_TRUSTED;
979 Security::Syslog::error("SecStaticCode: timestamp policy verification failed (error %d)", (int)result);
980 MacOSError::throwMe(result);
981 }
982 }
983 }
984
985 return actionData.ActionFlags & CSSM_TP_ACTION_ALLOW_EXPIRED;
986 }
987 #else
988 // Do some pre-verification initialization
989 CFDataRef sig = this->signature();
990 this->codeDirectory(); // load CodeDirectory (sets mDir)
991 mSigningTime = 0; // "not present" marker (nobody could code sign on Jan 1, 2001 :-)
992
993 CFRef<CFDictionaryRef> attrs;
994 CFRef<CFArrayRef> vf_policies(createVerificationPolicies());
995
996 // Verify the CMS signature against mBaseDir (SHA1)
997 MacOSError::check(SecCMSVerifyCopyDataAndAttributes(sig, mBaseDir, vf_policies, &mTrust.aref(), NULL, &attrs.aref()));
998
999 // Copy the signing time
1000 mSigningTime = SecTrustGetVerifyTime(mTrust);
1001
1002 // Validate the cert chain
1003 SecTrustResultType trustResult;
1004 MacOSError::check(SecTrustEvaluate(mTrust, &trustResult));
1005
1006 // retrieve auxiliary data bag and verify against current state
1007 CFRef<CFDataRef> hashBag;
1008 hashBag = CFDataRef(CFDictionaryGetValue(attrs, kSecCMSHashAgility));
1009 if (hashBag) {
1010 CFRef<CFDictionaryRef> hashDict = makeCFDictionaryFrom(hashBag);
1011 CFArrayRef cdList = CFArrayRef(CFDictionaryGetValue(hashDict, CFSTR("cdhashes")));
1012 CFArrayRef myCdList = this->cdHashes();
1013 if (cdList == NULL || !CFEqual(cdList, myCdList))
1014 MacOSError::throwMe(errSecCSSignatureFailed);
1015 }
1016
1017 /*
1018 * Populate mCertChain with the certs. If we failed validation, the
1019 * signer's cert will be checked installed provisioning profiles as an
1020 * alternative to verification against the policy for store-signed binaries
1021 */
1022 SecCertificateRef leafCert = SecTrustGetCertificateAtIndex(mTrust, 0);
1023 if (leafCert != NULL) {
1024 CFIndex count = SecTrustGetCertificateCount(mTrust);
1025
1026 CFMutableArrayRef certs = CFArrayCreateMutable(kCFAllocatorDefault, count,
1027 &kCFTypeArrayCallBacks);
1028
1029 CFArrayAppendValue(certs, leafCert);
1030 for (CFIndex i = 1; i < count; ++i) {
1031 CFArrayAppendValue(certs, SecTrustGetCertificateAtIndex(mTrust, i));
1032 }
1033
1034 mCertChain.take((CFArrayRef)certs);
1035 }
1036
1037 // Did we implicitly trust the signer?
1038 mTrustedSigningCertChain = (trustResult == kSecTrustResultUnspecified || trustResult == kSecTrustResultProceed);
1039
1040 return false; // XXX: Not checking for expired certs
1041 #endif
1042 }
1043
1044 #if TARGET_OS_OSX
1045 //
1046 // Return the TP policy used for signature verification.
1047 // This may be a simple SecPolicyRef or a CFArray of policies.
1048 // The caller owns the return value.
1049 //
1050 static SecPolicyRef makeRevocationPolicy(CFOptionFlags flags)
1051 {
1052 CFRef<SecPolicyRef> policy(SecPolicyCreateRevocation(flags));
1053 return policy.yield();
1054 }
1055 #endif
1056
1057 CFArrayRef SecStaticCode::createVerificationPolicies()
1058 {
1059 if (mValidationFlags & kSecCSUseSoftwareSigningCert) {
1060 CFRef<SecPolicyRef> ssRef = SecPolicyCreateAppleSoftwareSigning();
1061 return makeCFArray(1, ssRef.get());
1062 }
1063 #if TARGET_OS_OSX
1064 CFRef<SecPolicyRef> core;
1065 MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3,
1066 &CSSMOID_APPLE_TP_CODE_SIGNING, &core.aref()));
1067 if (mValidationFlags & kSecCSNoNetworkAccess) {
1068 // Skips all revocation since they require network connectivity
1069 // therefore annihilates kSecCSEnforceRevocationChecks if present
1070 CFRef<SecPolicyRef> no_revoc = makeRevocationPolicy(kSecRevocationNetworkAccessDisabled);
1071 return makeCFArray(2, core.get(), no_revoc.get());
1072 }
1073 else if (mValidationFlags & kSecCSEnforceRevocationChecks) {
1074 // Add CRL and OCSP policies
1075 CFRef<SecPolicyRef> revoc = makeRevocationPolicy(kSecRevocationUseAnyAvailableMethod);
1076 return makeCFArray(2, core.get(), revoc.get());
1077 } else {
1078 return makeCFArray(1, core.get());
1079 }
1080 #elif TARGET_OS_TV
1081 CFRef<SecPolicyRef> tvOSRef = SecPolicyCreateAppleTVOSApplicationSigning();
1082 return makeCFArray(1, tvOSRef.get());
1083 #else
1084 CFRef<SecPolicyRef> iOSRef = SecPolicyCreateiPhoneApplicationSigning();
1085 return makeCFArray(1, iOSRef.get());
1086 #endif
1087
1088 }
1089
1090 CFArrayRef SecStaticCode::createTimeStampingAndRevocationPolicies()
1091 {
1092 CFRef<SecPolicyRef> tsPolicy = SecPolicyCreateAppleTimeStamping();
1093 #if TARGET_OS_OSX
1094 if (mValidationFlags & kSecCSNoNetworkAccess) {
1095 // Skips all revocation since they require network connectivity
1096 // therefore annihilates kSecCSEnforceRevocationChecks if present
1097 CFRef<SecPolicyRef> no_revoc = makeRevocationPolicy(kSecRevocationNetworkAccessDisabled);
1098 return makeCFArray(2, tsPolicy.get(), no_revoc.get());
1099 }
1100 else if (mValidationFlags & kSecCSEnforceRevocationChecks) {
1101 // Add CRL and OCSP policies
1102 CFRef<SecPolicyRef> revoc = makeRevocationPolicy(kSecRevocationUseAnyAvailableMethod);
1103 return makeCFArray(2, tsPolicy.get(), revoc.get());
1104 }
1105 else {
1106 return makeCFArray(1, tsPolicy.get());
1107 }
1108 #else
1109 return makeCFArray(1, tsPolicy.get());
1110 #endif
1111
1112 }
1113
1114
1115 //
1116 // Validate a particular sealed, cached resource against its (special) CodeDirectory slot.
1117 // The resource must already have been placed in the cache.
1118 // This does NOT perform basic validation.
1119 //
1120 void SecStaticCode::validateComponent(CodeDirectory::SpecialSlot slot, OSStatus fail /* = errSecCSSignatureFailed */)
1121 {
1122 assert(slot <= cdSlotMax);
1123 CFDataRef data = mCache[slot];
1124 assert(data); // must be cached
1125 if (data == CFDataRef(kCFNull)) {
1126 if (codeDirectory()->slotIsPresent(-slot)) // was supposed to be there...
1127 MacOSError::throwMe(fail); // ... and is missing
1128 } else {
1129 if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data), CFDataGetLength(data), -slot, false))
1130 MacOSError::throwMe(fail);
1131 }
1132 }
1133
1134
1135 //
1136 // Perform static validation of the main executable.
1137 // This reads the main executable from disk and validates it against the
1138 // CodeDirectory code slot array.
1139 // Note that this is NOT an in-memory validation, and is thus potentially
1140 // subject to timing attacks.
1141 //
1142 void SecStaticCode::validateExecutable()
1143 {
1144 if (!validatedExecutable()) {
1145 try {
1146 DTRACK(CODESIGN_EVAL_STATIC_EXECUTABLE, this,
1147 (char*)this->mainExecutablePath().c_str(), codeDirectory()->nCodeSlots);
1148 const CodeDirectory *cd = this->codeDirectory();
1149 if (!cd)
1150 MacOSError::throwMe(errSecCSUnsigned);
1151 AutoFileDesc fd(mainExecutablePath(), O_RDONLY);
1152 fd.fcntl(F_NOCACHE, true); // turn off page caching (one-pass)
1153 if (Universal *fat = mRep->mainExecutableImage())
1154 fd.seek(fat->archOffset());
1155 size_t pageSize = cd->pageSize ? (1 << cd->pageSize) : 0;
1156 size_t remaining = cd->signingLimit();
1157 for (uint32_t slot = 0; slot < cd->nCodeSlots; ++slot) {
1158 size_t thisPage = remaining;
1159 if (pageSize)
1160 thisPage = min(thisPage, pageSize);
1161 __block bool good = true;
1162 CodeDirectory::multipleHashFileData(fd, thisPage, hashAlgorithms(), ^(CodeDirectory::HashAlgorithm type, Security::DynamicHash *hasher) {
1163 const CodeDirectory* cd = (const CodeDirectory*)CFDataGetBytePtr(mCodeDirectories[type]);
1164 if (!hasher->verify(cd->getSlot(slot,
1165 mValidationFlags & kSecCSValidatePEH)))
1166 good = false;
1167 });
1168 if (!good) {
1169 CODESIGN_EVAL_STATIC_EXECUTABLE_FAIL(this, (int)slot);
1170 MacOSError::throwMe(errSecCSSignatureFailed);
1171 }
1172 remaining -= thisPage;
1173 }
1174 assert(remaining == 0);
1175 mExecutableValidated = true;
1176 mExecutableValidResult = errSecSuccess;
1177 } catch (const CommonError &err) {
1178 mExecutableValidated = true;
1179 mExecutableValidResult = err.osStatus();
1180 throw;
1181 } catch (...) {
1182 secinfo("staticCode", "%p executable validation threw non-common exception", this);
1183 mExecutableValidated = true;
1184 mExecutableValidResult = errSecCSInternalError;
1185 Syslog::notice("code signing internal problem: unknown exception thrown by validation");
1186 throw;
1187 }
1188 }
1189 assert(validatedExecutable());
1190 if (mExecutableValidResult != errSecSuccess)
1191 MacOSError::throwMe(mExecutableValidResult);
1192 }
1193
1194
1195 //
1196 // Perform static validation of sealed resources and nested code.
1197 //
1198 // This performs a whole-code static resource scan and effectively
1199 // computes a concordance between what's on disk and what's in the ResourceDirectory.
1200 // Any unsanctioned difference causes an error.
1201 //
1202 unsigned SecStaticCode::estimateResourceWorkload()
1203 {
1204 // workload estimate = number of sealed files
1205 CFDictionaryRef sealedResources = resourceDictionary();
1206 CFDictionaryRef files = cfget<CFDictionaryRef>(sealedResources, "files2");
1207 if (files == NULL)
1208 files = cfget<CFDictionaryRef>(sealedResources, "files");
1209 return files ? unsigned(CFDictionaryGetCount(files)) : 0;
1210 }
1211
1212 void SecStaticCode::validateResources(SecCSFlags flags)
1213 {
1214 // do we have a superset of this requested validation cached?
1215 bool doit = true;
1216 if (mResourcesValidated) { // have cached outcome
1217 if (!(flags & kSecCSCheckNestedCode) || mResourcesDeep) // was deep or need no deep scan
1218 doit = false;
1219 }
1220
1221 if (doit) {
1222 if (mLimitedAsync == NULL) {
1223 bool runMultiThreaded = ((flags & kSecCSSingleThreaded) == kSecCSSingleThreaded) ? false :
1224 (diskRep()->fd().mediumType() == kIOPropertyMediumTypeSolidStateKey);
1225 mLimitedAsync = new LimitedAsync(runMultiThreaded);
1226 }
1227
1228 try {
1229 CFDictionaryRef rules;
1230 CFDictionaryRef files;
1231 uint32_t version;
1232 if (!loadResources(rules, files, version))
1233 return; // validly no resources; nothing to do (ok)
1234
1235 // found resources, and they are sealed
1236 DTRACK(CODESIGN_EVAL_STATIC_RESOURCES, this,
1237 (char*)this->mainExecutablePath().c_str(), 0);
1238
1239 // scan through the resources on disk, checking each against the resourceDirectory
1240 mResourcesValidContext = new CollectingContext(*this); // collect all failures in here
1241
1242 // check for weak resource rules
1243 bool strict = flags & kSecCSStrictValidate;
1244 if (strict) {
1245 if (hasWeakResourceRules(rules, version, mAllowOmissions))
1246 if (mTolerateErrors.find(errSecCSWeakResourceRules) == mTolerateErrors.end())
1247 MacOSError::throwMe(errSecCSWeakResourceRules);
1248 if (version == 1)
1249 if (mTolerateErrors.find(errSecCSWeakResourceEnvelope) == mTolerateErrors.end())
1250 MacOSError::throwMe(errSecCSWeakResourceEnvelope);
1251 }
1252
1253 Dispatch::Group group;
1254 Dispatch::Group &groupRef = group; // (into block)
1255
1256 // scan through the resources on disk, checking each against the resourceDirectory
1257 __block CFRef<CFMutableDictionaryRef> resourceMap = makeCFMutableDictionary(files);
1258 string base = cfString(this->resourceBase());
1259 ResourceBuilder resources(base, base, rules, strict, mTolerateErrors);
1260 this->mResourceScope = &resources;
1261 diskRep()->adjustResources(resources);
1262
1263 resources.scan(^(FTSENT *ent, uint32_t ruleFlags, const string relpath, ResourceBuilder::Rule *rule) {
1264 CFDictionaryRemoveValue(resourceMap, CFTempString(relpath));
1265 bool isSymlink = (ent->fts_info == FTS_SL);
1266
1267 void (^validate)() = ^{
1268 validateResource(files, relpath, isSymlink, *mResourcesValidContext, flags, version);
1269 reportProgress();
1270 };
1271
1272 mLimitedAsync->perform(groupRef, validate);
1273 });
1274 group.wait(); // wait until all async resources have been validated as well
1275
1276 unsigned leftovers = unsigned(CFDictionaryGetCount(resourceMap));
1277 if (leftovers > 0) {
1278 secinfo("staticCode", "%d sealed resource(s) not found in code", int(leftovers));
1279 CFDictionaryApplyFunction(resourceMap, SecStaticCode::checkOptionalResource, mResourcesValidContext);
1280 }
1281
1282 // now check for any errors found in the reporting context
1283 mResourcesValidated = true;
1284 mResourcesDeep = flags & kSecCSCheckNestedCode;
1285 if (mResourcesValidContext->osStatus() != errSecSuccess)
1286 mResourcesValidContext->throwMe();
1287 } catch (const CommonError &err) {
1288 mResourcesValidated = true;
1289 mResourcesDeep = flags & kSecCSCheckNestedCode;
1290 mResourcesValidResult = err.osStatus();
1291 throw;
1292 } catch (...) {
1293 secinfo("staticCode", "%p executable validation threw non-common exception", this);
1294 mResourcesValidated = true;
1295 mResourcesDeep = flags & kSecCSCheckNestedCode;
1296 mResourcesValidResult = errSecCSInternalError;
1297 Syslog::notice("code signing internal problem: unknown exception thrown by validation");
1298 throw;
1299 }
1300 }
1301 assert(validatedResources());
1302 if (mResourcesValidResult)
1303 MacOSError::throwMe(mResourcesValidResult);
1304 if (mResourcesValidContext->osStatus() != errSecSuccess)
1305 mResourcesValidContext->throwMe();
1306 }
1307
1308
1309 bool SecStaticCode::loadResources(CFDictionaryRef& rules, CFDictionaryRef& files, uint32_t& version)
1310 {
1311 // sanity first
1312 CFDictionaryRef sealedResources = resourceDictionary();
1313 if (this->resourceBase()) { // disk has resources
1314 if (sealedResources)
1315 /* go to work below */;
1316 else
1317 MacOSError::throwMe(errSecCSResourcesNotFound);
1318 } else { // disk has no resources
1319 if (sealedResources)
1320 MacOSError::throwMe(errSecCSResourcesNotFound);
1321 else
1322 return false; // no resources, not sealed - fine (no work)
1323 }
1324
1325 // use V2 resource seal if available, otherwise fall back to V1
1326 if (CFDictionaryGetValue(sealedResources, CFSTR("files2"))) { // have V2 signature
1327 rules = cfget<CFDictionaryRef>(sealedResources, "rules2");
1328 files = cfget<CFDictionaryRef>(sealedResources, "files2");
1329 version = 2;
1330 } else { // only V1 available
1331 rules = cfget<CFDictionaryRef>(sealedResources, "rules");
1332 files = cfget<CFDictionaryRef>(sealedResources, "files");
1333 version = 1;
1334 }
1335 if (!rules || !files)
1336 MacOSError::throwMe(errSecCSResourcesInvalid);
1337 return true;
1338 }
1339
1340
1341 void SecStaticCode::checkOptionalResource(CFTypeRef key, CFTypeRef value, void *context)
1342 {
1343 ValidationContext *ctx = static_cast<ValidationContext *>(context);
1344 ResourceSeal seal(value);
1345 if (!seal.optional()) {
1346 if (key && CFGetTypeID(key) == CFStringGetTypeID()) {
1347 CFTempURL tempURL(CFStringRef(key), false, ctx->code.resourceBase());
1348 if (!tempURL.get()) {
1349 ctx->reportProblem(errSecCSBadDictionaryFormat, kSecCFErrorResourceSeal, key);
1350 } else {
1351 ctx->reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, tempURL);
1352 }
1353 } else {
1354 ctx->reportProblem(errSecCSBadResource, kSecCFErrorResourceSeal, key);
1355 }
1356 }
1357 }
1358
1359
1360 static bool isOmitRule(CFTypeRef value)
1361 {
1362 if (CFGetTypeID(value) == CFBooleanGetTypeID())
1363 return value == kCFBooleanFalse;
1364 CFDictionary rule(value, errSecCSResourceRulesInvalid);
1365 return rule.get<CFBooleanRef>("omit") == kCFBooleanTrue;
1366 }
1367
1368 bool SecStaticCode::hasWeakResourceRules(CFDictionaryRef rulesDict, uint32_t version, CFArrayRef allowedOmissions)
1369 {
1370 // compute allowed omissions
1371 CFRef<CFArrayRef> defaultOmissions = this->diskRep()->allowedResourceOmissions();
1372 if (!defaultOmissions) {
1373 Syslog::notice("code signing internal problem: diskRep returned no allowedResourceOmissions");
1374 MacOSError::throwMe(errSecCSInternalError);
1375 }
1376 CFRef<CFMutableArrayRef> allowed = CFArrayCreateMutableCopy(NULL, 0, defaultOmissions);
1377 if (allowedOmissions)
1378 CFArrayAppendArray(allowed, allowedOmissions, CFRangeMake(0, CFArrayGetCount(allowedOmissions)));
1379 CFRange range = CFRangeMake(0, CFArrayGetCount(allowed));
1380
1381 // check all resource rules for weakness
1382 string catchAllRule = (version == 1) ? "^Resources/" : "^.*";
1383 __block bool coversAll = false;
1384 __block bool forbiddenOmission = false;
1385 CFArrayRef allowedRef = allowed.get(); // (into block)
1386 CFDictionary rules(rulesDict, errSecCSResourceRulesInvalid);
1387 rules.apply(^(CFStringRef key, CFTypeRef value) {
1388 string pattern = cfString(key, errSecCSResourceRulesInvalid);
1389 if (pattern == catchAllRule && value == kCFBooleanTrue) {
1390 coversAll = true;
1391 return;
1392 }
1393 if (isOmitRule(value))
1394 forbiddenOmission |= !CFArrayContainsValue(allowedRef, range, key);
1395 });
1396
1397 return !coversAll || forbiddenOmission;
1398 }
1399
1400
1401 //
1402 // Load, validate, cache, and return CFDictionary forms of sealed resources.
1403 //
1404 CFDictionaryRef SecStaticCode::infoDictionary()
1405 {
1406 if (!mInfoDict) {
1407 mInfoDict.take(getDictionary(cdInfoSlot, errSecCSInfoPlistFailed));
1408 secinfo("staticCode", "%p loaded InfoDict %p", this, mInfoDict.get());
1409 }
1410 return mInfoDict;
1411 }
1412
1413 CFDictionaryRef SecStaticCode::entitlements()
1414 {
1415 if (!mEntitlements) {
1416 validateDirectory();
1417 if (CFDataRef entitlementData = component(cdEntitlementSlot)) {
1418 validateComponent(cdEntitlementSlot);
1419 const EntitlementBlob *blob = reinterpret_cast<const EntitlementBlob *>(CFDataGetBytePtr(entitlementData));
1420 if (blob->validateBlob()) {
1421 mEntitlements.take(blob->entitlements());
1422 secinfo("staticCode", "%p loaded Entitlements %p", this, mEntitlements.get());
1423 }
1424 // we do not consider a different blob type to be an error. We think it's a new format we don't understand
1425 }
1426 }
1427 return mEntitlements;
1428 }
1429
1430 CFDictionaryRef SecStaticCode::resourceDictionary(bool check /* = true */)
1431 {
1432 if (mResourceDict) // cached
1433 return mResourceDict;
1434 if (CFRef<CFDictionaryRef> dict = getDictionary(cdResourceDirSlot, check))
1435 if (cfscan(dict, "{rules=%Dn,files=%Dn}")) {
1436 secinfo("staticCode", "%p loaded ResourceDict %p",
1437 this, mResourceDict.get());
1438 return mResourceDict = dict;
1439 }
1440 // bad format
1441 return NULL;
1442 }
1443
1444
1445 CFDataRef SecStaticCode::copyComponent(CodeDirectory::SpecialSlot slot, CFDataRef hash)
1446 {
1447 const CodeDirectory* cd = this->codeDirectory();
1448 if (CFCopyRef<CFDataRef> component = this->component(slot)) {
1449 if (hash) {
1450 const void *slotHash = cd->getSlot(slot, false);
1451 if (cd->hashSize != CFDataGetLength(hash) || 0 != memcmp(slotHash, CFDataGetBytePtr(hash), cd->hashSize)) {
1452 Syslog::notice("copyComponent hash mismatch slot %d length %d", slot, int(CFDataGetLength(hash)));
1453 return NULL; // mismatch
1454 }
1455 }
1456 return component.yield();
1457 }
1458 return NULL;
1459 }
1460
1461
1462
1463 //
1464 // Load and cache the resource directory base.
1465 // Note that the base is optional for each DiskRep.
1466 //
1467 CFURLRef SecStaticCode::resourceBase()
1468 {
1469 if (!mGotResourceBase) {
1470 string base = mRep->resourcesRootPath();
1471 if (!base.empty())
1472 mResourceBase.take(makeCFURL(base, true));
1473 mGotResourceBase = true;
1474 }
1475 return mResourceBase;
1476 }
1477
1478
1479 //
1480 // Load a component, validate it, convert it to a CFDictionary, and return that.
1481 // This will force load and validation, which means that it will perform basic
1482 // validation if it hasn't been done yet.
1483 //
1484 CFDictionaryRef SecStaticCode::getDictionary(CodeDirectory::SpecialSlot slot, bool check /* = true */)
1485 {
1486 if (check)
1487 validateDirectory();
1488 if (CFDataRef infoData = component(slot)) {
1489 validateComponent(slot);
1490 if (CFDictionaryRef dict = makeCFDictionaryFrom(infoData))
1491 return dict;
1492 else
1493 MacOSError::throwMe(errSecCSBadDictionaryFormat);
1494 }
1495 return NULL;
1496 }
1497
1498 //
1499 //
1500 //
1501 CFDictionaryRef SecStaticCode::diskRepInformation()
1502 {
1503 return mRep->diskRepInformation();
1504 }
1505
1506 bool SecStaticCode::checkfix30814861(string path, bool addition) {
1507 // <rdar://problem/30814861> v2 resource rules don't match v1 resource rules
1508
1509 //// Condition 1: Is the app an iOS app that was built with an SDK lower than 9.0?
1510
1511 // We started signing correctly in 2014, 9.0 was first seeded mid-2016.
1512
1513 CFRef<CFDictionaryRef> inf = diskRepInformation();
1514 try {
1515 CFDictionary info(diskRepInformation(), errSecCSNotSupported);
1516 uint32_t platform =
1517 cfNumber(info.get<CFNumberRef>(kSecCodeInfoDiskRepVersionPlatform, errSecCSNotSupported), 0);
1518 uint32_t sdkVersion =
1519 cfNumber(info.get<CFNumberRef>(kSecCodeInfoDiskRepVersionSDK, errSecCSNotSupported), 0);
1520
1521 if (platform != PLATFORM_IOS || sdkVersion >= 0x00090000) {
1522 return false;
1523 }
1524 } catch (const MacOSError &error) {
1525 return false;
1526 }
1527
1528 //// Condition 2: Is it a .sinf/.supf/.supp file at the right location?
1529
1530 static regex_t pathre_sinf;
1531 static regex_t pathre_supp_supf;
1532 static dispatch_once_t once;
1533
1534 dispatch_once(&once, ^{
1535 os_assert_zero(regcomp(&pathre_sinf,
1536 "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|())SC_Info/[^/]+\\.sinf$",
1537 REG_EXTENDED | REG_NOSUB));
1538 os_assert_zero(regcomp(&pathre_supp_supf,
1539 "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|())SC_Info/[^/]+\\.(supf|supp)$",
1540 REG_EXTENDED | REG_NOSUB));
1541 });
1542
1543 // .sinf is added, .supf/.supp are modified.
1544 const regex_t &pathre = addition ? pathre_sinf : pathre_supp_supf;
1545
1546 const int result = regexec(&pathre, path.c_str(), 0, NULL, 0);
1547
1548 if (result == REG_NOMATCH) {
1549 return false;
1550 } else if (result != 0) {
1551 // Huh?
1552 secerror("unexpected regexec result %d for path '%s'", result, path.c_str());
1553 return false;
1554 }
1555
1556 //// Condition 3: Do the v1 rules actually exclude the file?
1557
1558 dispatch_once(&mCheckfix30814861builder1_once, ^{
1559 // Create the v1 resource builder lazily.
1560 CFDictionaryRef rules1 = cfget<CFDictionaryRef>(resourceDictionary(), "rules");
1561 const string base = cfString(resourceBase());
1562
1563 mCheckfix30814861builder1 = new ResourceBuilder(base, base, rules1, false, mTolerateErrors);
1564 });
1565
1566 ResourceBuilder::Rule const * const matchingRule = mCheckfix30814861builder1->findRule(path);
1567
1568 if (matchingRule == NULL || !(matchingRule->flags & ResourceBuilder::omitted)) {
1569 return false;
1570 }
1571
1572 //// All matched, this file is a check-fixed sinf/supf/supp.
1573
1574 return true;
1575
1576 }
1577
1578 void SecStaticCode::validateResource(CFDictionaryRef files, string path, bool isSymlink, ValidationContext &ctx, SecCSFlags flags, uint32_t version)
1579 {
1580 if (!resourceBase()) // no resources in DiskRep
1581 MacOSError::throwMe(errSecCSResourcesNotFound);
1582 CFRef<CFURLRef> fullpath = makeCFURL(path, false, resourceBase());
1583 if (version > 1 && ((flags & (kSecCSStrictValidate|kSecCSRestrictSidebandData)) == (kSecCSStrictValidate|kSecCSRestrictSidebandData))) {
1584 AutoFileDesc fd(cfString(fullpath));
1585 if (fd.hasExtendedAttribute(XATTR_RESOURCEFORK_NAME) || fd.hasExtendedAttribute(XATTR_FINDERINFO_NAME))
1586 ctx.reportProblem(errSecCSInvalidAssociatedFileData, kSecCFErrorResourceSideband, fullpath);
1587 }
1588 if (CFTypeRef file = CFDictionaryGetValue(files, CFTempString(path))) {
1589 ResourceSeal seal(file);
1590 const ResourceSeal& rseal = seal;
1591 if (seal.nested()) {
1592 if (isSymlink)
1593 return ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type
1594 string suffix = ".framework";
1595 bool isFramework = (path.length() > suffix.length())
1596 && (path.compare(path.length()-suffix.length(), suffix.length(), suffix) == 0);
1597 validateNestedCode(fullpath, seal, flags, isFramework);
1598 } else if (seal.link()) {
1599 if (!isSymlink)
1600 return ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type
1601 validateSymlinkResource(cfString(fullpath), cfString(seal.link()), ctx, flags);
1602 } else if (seal.hash(hashAlgorithm())) { // genuine file
1603 if (isSymlink)
1604 return ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type
1605 AutoFileDesc fd(cfString(fullpath), O_RDONLY, FileDesc::modeMissingOk); // open optional file
1606 if (fd) {
1607 __block bool good = true;
1608 CodeDirectory::multipleHashFileData(fd, 0, hashAlgorithms(), ^(CodeDirectory::HashAlgorithm type, Security::DynamicHash *hasher) {
1609 if (!hasher->verify(rseal.hash(type)))
1610 good = false;
1611 });
1612 if (!good) {
1613 if (version == 2 && checkfix30814861(path, false)) {
1614 secinfo("validateResource", "%s check-fixed (altered).", path.c_str());
1615 } else {
1616 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // altered
1617 }
1618 }
1619 } else {
1620 if (!seal.optional())
1621 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, fullpath); // was sealed but is now missing
1622 else
1623 return; // validly missing
1624 }
1625 } else
1626 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type
1627 return;
1628 }
1629 if (version == 1) { // version 1 ignores symlinks altogether
1630 char target[PATH_MAX];
1631 if (::readlink(cfString(fullpath).c_str(), target, sizeof(target)) > 0)
1632 return;
1633 }
1634 if (version == 2 && checkfix30814861(path, true)) {
1635 secinfo("validateResource", "%s check-fixed (added).", path.c_str());
1636 } else {
1637 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAdded, CFTempURL(path, false, resourceBase()));
1638 }
1639 }
1640
1641 void SecStaticCode::validatePlainMemoryResource(string path, CFDataRef fileData, SecCSFlags flags)
1642 {
1643 CFDictionaryRef rules;
1644 CFDictionaryRef files;
1645 uint32_t version;
1646 if (!loadResources(rules, files, version))
1647 MacOSError::throwMe(errSecCSResourcesNotFound); // no resources sealed; this can't be right
1648 if (CFTypeRef file = CFDictionaryGetValue(files, CFTempString(path))) {
1649 ResourceSeal seal(file);
1650 const Byte *sealHash = seal.hash(hashAlgorithm());
1651 if (sealHash) {
1652 if (codeDirectory()->verifyMemoryContent(fileData, sealHash))
1653 return; // success
1654 }
1655 }
1656 MacOSError::throwMe(errSecCSBadResource);
1657 }
1658
1659 void SecStaticCode::validateSymlinkResource(std::string fullpath, std::string seal, ValidationContext &ctx, SecCSFlags flags)
1660 {
1661 static const char* const allowedDestinations[] = {
1662 "/System/",
1663 "/Library/",
1664 NULL
1665 };
1666 char target[PATH_MAX];
1667 ssize_t len = ::readlink(fullpath.c_str(), target, sizeof(target)-1);
1668 if (len < 0)
1669 UnixError::check(-1);
1670 target[len] = '\0';
1671 std::string fulltarget = target;
1672 if (target[0] != '/') {
1673 size_t lastSlash = fullpath.rfind('/');
1674 fulltarget = fullpath.substr(0, lastSlash) + '/' + target;
1675 }
1676 if (seal != target) {
1677 ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, CFTempString(fullpath));
1678 return;
1679 }
1680 if ((mValidationFlags & (kSecCSStrictValidate|kSecCSRestrictSymlinks)) == (kSecCSStrictValidate|kSecCSRestrictSymlinks)) {
1681 char resolved[PATH_MAX];
1682 if (realpath(fulltarget.c_str(), resolved)) {
1683 assert(resolved[0] == '/');
1684 size_t rlen = strlen(resolved);
1685 if (target[0] == '/') {
1686 // absolute symlink; only allow absolute links to system locations
1687 for (const char* const* pathp = allowedDestinations; *pathp; pathp++) {
1688 size_t dlen = strlen(*pathp);
1689 if (rlen > dlen && strncmp(resolved, *pathp, dlen) == 0)
1690 return; // target inside /System, deemed okay
1691 }
1692 } else {
1693 // everything else must be inside the bundle(s)
1694 for (const SecStaticCode* code = this; code; code = code->mOuterScope) {
1695 string root = code->mResourceScope->root();
1696 if (strncmp(resolved, root.c_str(), root.size()) == 0) {
1697 if (code->mResourceScope->includes(resolved + root.length() + 1))
1698 return; // located in resource stack && included in envelope
1699 else
1700 break; // located but excluded from envelope (deny)
1701 }
1702 }
1703 }
1704 }
1705 // if we fell through, flag a symlink error
1706 if (mTolerateErrors.find(errSecCSInvalidSymlink) == mTolerateErrors.end())
1707 ctx.reportProblem(errSecCSInvalidSymlink, kSecCFErrorResourceAltered, CFTempString(fullpath));
1708 }
1709 }
1710
1711 void SecStaticCode::validateNestedCode(CFURLRef path, const ResourceSeal &seal, SecCSFlags flags, bool isFramework)
1712 {
1713 CFRef<SecRequirementRef> req;
1714 if (SecRequirementCreateWithString(seal.requirement(), kSecCSDefaultFlags, &req.aref()))
1715 MacOSError::throwMe(errSecCSResourcesInvalid);
1716
1717 // recursively verify this nested code
1718 try {
1719 if (!(flags & kSecCSCheckNestedCode))
1720 flags |= kSecCSBasicValidateOnly | kSecCSQuickCheck;
1721 SecPointer<SecStaticCode> code = new SecStaticCode(DiskRep::bestGuess(cfString(path)));
1722 code->initializeFromParent(*this);
1723 code->staticValidate(flags & (~kSecCSRestrictToAppLike), SecRequirement::required(req));
1724
1725 if (isFramework && (flags & kSecCSStrictValidate))
1726 try {
1727 validateOtherVersions(path, flags & (~kSecCSRestrictToAppLike), req, code);
1728 } catch (const CSError &err) {
1729 MacOSError::throwMe(errSecCSBadFrameworkVersion);
1730 } catch (const MacOSError &err) {
1731 MacOSError::throwMe(errSecCSBadFrameworkVersion);
1732 }
1733
1734 } catch (CSError &err) {
1735 if (err.error == errSecCSReqFailed) {
1736 mResourcesValidContext->reportProblem(errSecCSBadNestedCode, kSecCFErrorResourceAltered, path);
1737 return;
1738 }
1739 err.augment(kSecCFErrorPath, path);
1740 throw;
1741 } catch (const MacOSError &err) {
1742 if (err.error == errSecCSReqFailed) {
1743 mResourcesValidContext->reportProblem(errSecCSBadNestedCode, kSecCFErrorResourceAltered, path);
1744 return;
1745 }
1746 CSError::throwMe(err.error, kSecCFErrorPath, path);
1747 }
1748 }
1749
1750 void SecStaticCode::validateOtherVersions(CFURLRef path, SecCSFlags flags, SecRequirementRef req, SecStaticCode *code)
1751 {
1752 // Find out what current points to and do not revalidate
1753 std::string mainPath = cfStringRelease(code->diskRep()->copyCanonicalPath());
1754
1755 char main_path[PATH_MAX];
1756 bool foundTarget = false;
1757
1758 /* If it failed to get the target of the symlink, do not fail. It is a performance loss,
1759 not a security hole */
1760 if (realpath(mainPath.c_str(), main_path) != NULL)
1761 foundTarget = true;
1762
1763 std::ostringstream versionsPath;
1764 versionsPath << cfString(path) << "/Versions/";
1765
1766 DirScanner scanner(versionsPath.str());
1767
1768 if (scanner.initialized()) {
1769 struct dirent *entry = NULL;
1770 while ((entry = scanner.getNext()) != NULL) {
1771 std::ostringstream fullPath;
1772
1773 if (entry->d_type != DT_DIR || strcmp(entry->d_name, "Current") == 0)
1774 continue;
1775
1776 fullPath << versionsPath.str() << entry->d_name;
1777
1778 char real_full_path[PATH_MAX];
1779 if (realpath(fullPath.str().c_str(), real_full_path) == NULL)
1780 UnixError::check(-1);
1781
1782 // Do case insensitive comparions because realpath() was called for both paths
1783 if (foundTarget && strcmp(main_path, real_full_path) == 0)
1784 continue;
1785
1786 SecPointer<SecStaticCode> frameworkVersion = new SecStaticCode(DiskRep::bestGuess(real_full_path));
1787 frameworkVersion->initializeFromParent(*this);
1788 frameworkVersion->staticValidate(flags, SecRequirement::required(req));
1789 }
1790 }
1791 }
1792
1793
1794 //
1795 // Test a CodeDirectory flag.
1796 // Returns false if there is no CodeDirectory.
1797 // May throw if the CodeDirectory is present but somehow invalid.
1798 //
1799 bool SecStaticCode::flag(uint32_t tested)
1800 {
1801 if (const CodeDirectory *cd = this->codeDirectory(false))
1802 return cd->flags & tested;
1803 else
1804 return false;
1805 }
1806
1807
1808 //
1809 // Retrieve the full SuperBlob containing all internal requirements.
1810 //
1811 const Requirements *SecStaticCode::internalRequirements()
1812 {
1813 if (CFDataRef reqData = component(cdRequirementsSlot)) {
1814 const Requirements *req = (const Requirements *)CFDataGetBytePtr(reqData);
1815 if (!req->validateBlob())
1816 MacOSError::throwMe(errSecCSReqInvalid);
1817 return req;
1818 } else
1819 return NULL;
1820 }
1821
1822
1823 //
1824 // Retrieve a particular internal requirement by type.
1825 //
1826 const Requirement *SecStaticCode::internalRequirement(SecRequirementType type)
1827 {
1828 if (const Requirements *reqs = internalRequirements())
1829 return reqs->find<Requirement>(type);
1830 else
1831 return NULL;
1832 }
1833
1834
1835 //
1836 // Return the Designated Requirement (DR). This can be either explicit in the
1837 // Internal Requirements component, or implicitly generated on demand here.
1838 // Note that an explicit DR may have been implicitly generated at signing time;
1839 // we don't distinguish this case.
1840 //
1841 const Requirement *SecStaticCode::designatedRequirement()
1842 {
1843 if (const Requirement *req = internalRequirement(kSecDesignatedRequirementType)) {
1844 return req; // explicit in signing data
1845 } else {
1846 if (!mDesignatedReq)
1847 mDesignatedReq = defaultDesignatedRequirement();
1848 return mDesignatedReq;
1849 }
1850 }
1851
1852
1853 //
1854 // Generate the default Designated Requirement (DR) for this StaticCode.
1855 // Ignore any explicit DR it may contain.
1856 //
1857 const Requirement *SecStaticCode::defaultDesignatedRequirement()
1858 {
1859 if (flag(kSecCodeSignatureAdhoc)) {
1860 // adhoc signature: return a cdhash requirement for all architectures
1861 __block Requirement::Maker maker;
1862 Requirement::Maker::Chain chain(maker, opOr);
1863
1864 // insert cdhash requirement for all architectures
1865 __block CFRef<CFMutableArrayRef> allHashes = CFArrayCreateMutableCopy(NULL, 0, this->cdHashes());
1866 handleOtherArchitectures(^(SecStaticCode *other) {
1867 CFArrayRef hashes = other->cdHashes();
1868 CFArrayAppendArray(allHashes, hashes, CFRangeMake(0, CFArrayGetCount(hashes)));
1869 });
1870 CFIndex count = CFArrayGetCount(allHashes);
1871 for (CFIndex n = 0; n < count; ++n) {
1872 chain.add();
1873 maker.cdhash(CFDataRef(CFArrayGetValueAtIndex(allHashes, n)));
1874 }
1875 return maker.make();
1876 } else {
1877 #if TARGET_OS_OSX
1878 // full signature: Gin up full context and let DRMaker do its thing
1879 validateDirectory(); // need the cert chain
1880 Requirement::Context context(this->certificates(),
1881 this->infoDictionary(),
1882 this->entitlements(),
1883 this->identifier(),
1884 this->codeDirectory(),
1885 NULL,
1886 kSecCodeSignatureNoHash,
1887 false
1888 );
1889 return DRMaker(context).make();
1890 #else
1891 MacOSError::throwMe(errSecCSUnimplemented);
1892 #endif
1893 }
1894 }
1895
1896
1897 //
1898 // Validate a SecStaticCode against the internal requirement of a particular type.
1899 //
1900 void SecStaticCode::validateRequirements(SecRequirementType type, SecStaticCode *target,
1901 OSStatus nullError /* = errSecSuccess */)
1902 {
1903 DTRACK(CODESIGN_EVAL_STATIC_INTREQ, this, type, target, nullError);
1904 if (const Requirement *req = internalRequirement(type))
1905 target->validateRequirement(req, nullError ? nullError : errSecCSReqFailed);
1906 else if (nullError)
1907 MacOSError::throwMe(nullError);
1908 else
1909 /* accept it */;
1910 }
1911
1912 //
1913 // Validate this StaticCode against an external Requirement
1914 //
1915 bool SecStaticCode::satisfiesRequirement(const Requirement *req, OSStatus failure)
1916 {
1917 bool result = false;
1918 assert(req);
1919 validateDirectory();
1920 result = req->validates(Requirement::Context(mCertChain, infoDictionary(), entitlements(), codeDirectory()->identifier(), codeDirectory(), NULL, kSecCodeSignatureNoHash, mRep->appleInternalForcePlatform()), failure);
1921 return result;
1922 }
1923
1924 void SecStaticCode::validateRequirement(const Requirement *req, OSStatus failure)
1925 {
1926 if (!this->satisfiesRequirement(req, failure))
1927 MacOSError::throwMe(failure);
1928 }
1929
1930 //
1931 // Retrieve one certificate from the cert chain.
1932 // Positive and negative indices can be used:
1933 // [ leaf, intermed-1, ..., intermed-n, anchor ]
1934 // 0 1 ... -2 -1
1935 // Returns NULL if unavailable for any reason.
1936 //
1937 SecCertificateRef SecStaticCode::cert(int ix)
1938 {
1939 validateDirectory(); // need cert chain
1940 if (mCertChain) {
1941 CFIndex length = CFArrayGetCount(mCertChain);
1942 if (ix < 0)
1943 ix += length;
1944 if (ix >= 0 && ix < length)
1945 return SecCertificateRef(CFArrayGetValueAtIndex(mCertChain, ix));
1946 }
1947 return NULL;
1948 }
1949
1950 CFArrayRef SecStaticCode::certificates()
1951 {
1952 validateDirectory(); // need cert chain
1953 return mCertChain;
1954 }
1955
1956
1957 //
1958 // Gather (mostly) API-official information about this StaticCode.
1959 //
1960 // This method lives in the twilight between the API and internal layers,
1961 // since it generates API objects (Sec*Refs) for return.
1962 //
1963 CFDictionaryRef SecStaticCode::signingInformation(SecCSFlags flags)
1964 {
1965 //
1966 // Start with the pieces that we return even for unsigned code.
1967 // This makes Sec[Static]CodeRefs useful as API-level replacements
1968 // of our internal OSXCode objects.
1969 //
1970 CFRef<CFMutableDictionaryRef> dict = makeCFMutableDictionary(1,
1971 kSecCodeInfoMainExecutable, CFTempURL(this->mainExecutablePath()).get()
1972 );
1973
1974 //
1975 // If we're not signed, this is all you get
1976 //
1977 if (!this->isSigned())
1978 return dict.yield();
1979
1980 //
1981 // Add the generic attributes that we always include
1982 //
1983 CFDictionaryAddValue(dict, kSecCodeInfoIdentifier, CFTempString(this->identifier()));
1984 CFDictionaryAddValue(dict, kSecCodeInfoFlags, CFTempNumber(this->codeDirectory(false)->flags.get()));
1985 CFDictionaryAddValue(dict, kSecCodeInfoFormat, CFTempString(this->format()));
1986 CFDictionaryAddValue(dict, kSecCodeInfoSource, CFTempString(this->signatureSource()));
1987 CFDictionaryAddValue(dict, kSecCodeInfoUnique, this->cdHash());
1988 CFDictionaryAddValue(dict, kSecCodeInfoCdHashes, this->cdHashes());
1989 const CodeDirectory* cd = this->codeDirectory(false);
1990 CFDictionaryAddValue(dict, kSecCodeInfoDigestAlgorithm, CFTempNumber(cd->hashType));
1991 CFRef<CFArrayRef> digests = makeCFArrayFrom(^CFTypeRef(CodeDirectory::HashAlgorithm type) { return CFTempNumber(type); }, hashAlgorithms());
1992 CFDictionaryAddValue(dict, kSecCodeInfoDigestAlgorithms, digests);
1993 if (cd->platform)
1994 CFDictionaryAddValue(dict, kSecCodeInfoPlatformIdentifier, CFTempNumber(cd->platform));
1995 if (cd->runtimeVersion()) {
1996 CFDictionaryAddValue(dict, kSecCodeInfoRuntimeVersion, CFTempNumber(cd->runtimeVersion()));
1997 }
1998
1999 //
2000 // Deliver any Info.plist only if it looks intact
2001 //
2002 try {
2003 if (CFDictionaryRef info = this->infoDictionary())
2004 CFDictionaryAddValue(dict, kSecCodeInfoPList, info);
2005 } catch (...) { } // don't deliver Info.plist if questionable
2006
2007 //
2008 // kSecCSSigningInformation adds information about signing certificates and chains
2009 //
2010 if (flags & kSecCSSigningInformation)
2011 try {
2012 if (CFDataRef sig = this->signature())
2013 CFDictionaryAddValue(dict, kSecCodeInfoCMS, sig);
2014 if (const char *teamID = this->teamID())
2015 CFDictionaryAddValue(dict, kSecCodeInfoTeamIdentifier, CFTempString(teamID));
2016 if (mTrust)
2017 CFDictionaryAddValue(dict, kSecCodeInfoTrust, mTrust);
2018 if (CFArrayRef certs = this->certificates())
2019 CFDictionaryAddValue(dict, kSecCodeInfoCertificates, certs);
2020 if (CFAbsoluteTime time = this->signingTime())
2021 if (CFRef<CFDateRef> date = CFDateCreate(NULL, time))
2022 CFDictionaryAddValue(dict, kSecCodeInfoTime, date);
2023 if (CFAbsoluteTime time = this->signingTimestamp())
2024 if (CFRef<CFDateRef> date = CFDateCreate(NULL, time))
2025 CFDictionaryAddValue(dict, kSecCodeInfoTimestamp, date);
2026 } catch (...) { }
2027
2028 //
2029 // kSecCSRequirementInformation adds information on requirements
2030 //
2031 if (flags & kSecCSRequirementInformation)
2032
2033 //DR not currently supported on iOS
2034 #if TARGET_OS_OSX
2035 try {
2036 if (const Requirements *reqs = this->internalRequirements()) {
2037 CFDictionaryAddValue(dict, kSecCodeInfoRequirements,
2038 CFTempString(Dumper::dump(reqs)));
2039 CFDictionaryAddValue(dict, kSecCodeInfoRequirementData, CFTempData(*reqs));
2040 }
2041
2042 const Requirement *dreq = this->designatedRequirement();
2043 CFRef<SecRequirementRef> dreqRef = (new SecRequirement(dreq))->handle();
2044 CFDictionaryAddValue(dict, kSecCodeInfoDesignatedRequirement, dreqRef);
2045 if (this->internalRequirement(kSecDesignatedRequirementType)) { // explicit
2046 CFRef<SecRequirementRef> ddreqRef = (new SecRequirement(this->defaultDesignatedRequirement(), true))->handle();
2047 CFDictionaryAddValue(dict, kSecCodeInfoImplicitDesignatedRequirement, ddreqRef);
2048 } else { // implicit
2049 CFDictionaryAddValue(dict, kSecCodeInfoImplicitDesignatedRequirement, dreqRef);
2050 }
2051 } catch (...) { }
2052 #endif
2053
2054 try {
2055 if (CFDataRef ent = this->component(cdEntitlementSlot)) {
2056 CFDictionaryAddValue(dict, kSecCodeInfoEntitlements, ent);
2057 if (CFDictionaryRef entdict = this->entitlements())
2058 CFDictionaryAddValue(dict, kSecCodeInfoEntitlementsDict, entdict);
2059 }
2060 } catch (...) { }
2061
2062 //
2063 // kSecCSInternalInformation adds internal information meant to be for Apple internal
2064 // use (SPI), and not guaranteed to be stable. Primarily, this is data we want
2065 // to reliably transmit through the API wall so that code outside the Security.framework
2066 // can use it without having to play nasty tricks to get it.
2067 //
2068 if (flags & kSecCSInternalInformation) {
2069 try {
2070 if (mDir)
2071 CFDictionaryAddValue(dict, kSecCodeInfoCodeDirectory, mDir);
2072 CFDictionaryAddValue(dict, kSecCodeInfoCodeOffset, CFTempNumber(mRep->signingBase()));
2073 if (!(flags & kSecCSSkipResourceDirectory)) {
2074 if (CFRef<CFDictionaryRef> rdict = getDictionary(cdResourceDirSlot, false)) // suppress validation
2075 CFDictionaryAddValue(dict, kSecCodeInfoResourceDirectory, rdict);
2076 }
2077 if (CFRef<CFDictionaryRef> ddict = diskRepInformation())
2078 CFDictionaryAddValue(dict, kSecCodeInfoDiskRepInfo, ddict);
2079 } catch (...) { }
2080 if (mNotarizationChecked && !isnan(mNotarizationDate)) {
2081 CFRef<CFDateRef> date = CFDateCreate(NULL, mNotarizationDate);
2082 if (date) {
2083 CFDictionaryAddValue(dict, kSecCodeInfoNotarizationDate, date.get());
2084 } else {
2085 secerror("Error creating date from timestamp: %f", mNotarizationDate);
2086 }
2087 }
2088 }
2089
2090
2091 //
2092 // kSecCSContentInformation adds more information about the physical layout
2093 // of the signed code. This is (only) useful for packaging or patching-oriented
2094 // applications.
2095 //
2096 if (flags & kSecCSContentInformation && !(flags & kSecCSSkipResourceDirectory))
2097 if (CFRef<CFArrayRef> files = mRep->modifiedFiles())
2098 CFDictionaryAddValue(dict, kSecCodeInfoChangedFiles, files);
2099
2100 return dict.yield();
2101 }
2102
2103
2104 //
2105 // Resource validation contexts.
2106 // The default context simply throws a CSError, rudely terminating the operation.
2107 //
2108 SecStaticCode::ValidationContext::~ValidationContext()
2109 { /* virtual */ }
2110
2111 void SecStaticCode::ValidationContext::reportProblem(OSStatus rc, CFStringRef type, CFTypeRef value)
2112 {
2113 CSError::throwMe(rc, type, value);
2114 }
2115
2116 void SecStaticCode::CollectingContext::reportProblem(OSStatus rc, CFStringRef type, CFTypeRef value)
2117 {
2118 StLock<Mutex> _(mLock);
2119 if (mStatus == errSecSuccess)
2120 mStatus = rc; // record first failure for eventual error return
2121 if (type) {
2122 if (!mCollection)
2123 mCollection.take(makeCFMutableDictionary());
2124 CFMutableArrayRef element = CFMutableArrayRef(CFDictionaryGetValue(mCollection, type));
2125 if (!element) {
2126 element = makeCFMutableArray(0);
2127 if (!element)
2128 CFError::throwMe();
2129 CFDictionaryAddValue(mCollection, type, element);
2130 CFRelease(element);
2131 }
2132 CFArrayAppendValue(element, value);
2133 }
2134 }
2135
2136 void SecStaticCode::CollectingContext::throwMe()
2137 {
2138 assert(mStatus != errSecSuccess);
2139 throw CSError(mStatus, mCollection.retain());
2140 }
2141
2142
2143 //
2144 // Master validation driver.
2145 // This is the static validation (only) driver for the API.
2146 //
2147 // SecStaticCode exposes an a la carte menu of topical validators applying
2148 // to a given object. The static validation API pulls them together reliably,
2149 // but it also adds three matrix dimensions: architecture (for "fat" Mach-O binaries),
2150 // nested code, and multiple digests. This function will crawl a suitable cross-section of this
2151 // validation matrix based on which options it is given, creating temporary
2152 // SecStaticCode objects on the fly to complete the task.
2153 // (The point, of course, is to do as little duplicate work as possible.)
2154 //
2155 void SecStaticCode::staticValidate(SecCSFlags flags, const SecRequirement *req)
2156 {
2157 setValidationFlags(flags);
2158
2159 #if TARGET_OS_OSX
2160 if (!mStaplingChecked) {
2161 mRep->registerStapledTicket();
2162 mStaplingChecked = true;
2163 }
2164
2165 if (mFlags & kSecCSForceOnlineNotarizationCheck) {
2166 if (!mNotarizationChecked) {
2167 if (this->cdHash()) {
2168 bool is_revoked = checkNotarizationServiceForRevocation(this->cdHash(), (SecCSDigestAlgorithm)this->hashAlgorithm(), &mNotarizationDate);
2169 if (is_revoked) {
2170 MacOSError::throwMe(errSecCSRevokedNotarization);
2171 }
2172 }
2173 mNotarizationChecked = true;
2174 }
2175 }
2176 #endif // TARGET_OS_OSX
2177
2178 // initialize progress/cancellation state
2179 if (flags & kSecCSReportProgress)
2180 prepareProgress(estimateResourceWorkload() + 2); // +1 head, +1 tail
2181
2182
2183 // core components: once per architecture (if any)
2184 this->staticValidateCore(flags, req);
2185 if (flags & kSecCSCheckAllArchitectures)
2186 handleOtherArchitectures(^(SecStaticCode* subcode) {
2187 if (flags & kSecCSCheckGatekeeperArchitectures) {
2188 Universal *fat = subcode->diskRep()->mainExecutableImage();
2189 assert(fat && fat->narrowed()); // handleOtherArchitectures gave us a focused architecture slice
2190 Architecture arch = fat->bestNativeArch(); // actually, the ONLY one
2191 if ((arch.cpuType() & ~CPU_ARCH_MASK) == CPU_TYPE_POWERPC)
2192 return; // irrelevant to Gatekeeper
2193 }
2194 subcode->detachedSignature(this->mDetachedSig); // carry over explicit (but not implicit) detached signature
2195 subcode->staticValidateCore(flags, req);
2196 });
2197 reportProgress();
2198
2199 // allow monitor intervention in source validation phase
2200 reportEvent(CFSTR("prepared"), NULL);
2201
2202 // resources: once for all architectures
2203 if (!(flags & kSecCSDoNotValidateResources))
2204 this->validateResources(flags);
2205
2206 // perform strict validation if desired
2207 if (flags & kSecCSStrictValidate)
2208 mRep->strictValidate(codeDirectory(), mTolerateErrors, mValidationFlags);
2209 reportProgress();
2210
2211 // allow monitor intervention
2212 if (CFRef<CFTypeRef> veto = reportEvent(CFSTR("validated"), NULL)) {
2213 if (CFGetTypeID(veto) == CFNumberGetTypeID())
2214 MacOSError::throwMe(cfNumber<OSStatus>(veto.as<CFNumberRef>()));
2215 else
2216 MacOSError::throwMe(errSecCSBadCallbackValue);
2217 }
2218 }
2219
2220 void SecStaticCode::staticValidateCore(SecCSFlags flags, const SecRequirement *req)
2221 {
2222 try {
2223 this->validateNonResourceComponents(); // also validates the CodeDirectory
2224 this->validateTopDirectory();
2225 if (!(flags & kSecCSDoNotValidateExecutable))
2226 this->validateExecutable();
2227 if (req)
2228 this->validateRequirement(req->requirement(), errSecCSReqFailed);
2229 } catch (CSError &err) {
2230 if (Universal *fat = this->diskRep()->mainExecutableImage()) // Mach-O
2231 if (MachO *mach = fat->architecture()) {
2232 err.augment(kSecCFErrorArchitecture, CFTempString(mach->architecture().displayName()));
2233 delete mach;
2234 }
2235 throw;
2236 } catch (const MacOSError &err) {
2237 // add architecture information if we can get it
2238 if (Universal *fat = this->diskRep()->mainExecutableImage())
2239 if (MachO *mach = fat->architecture()) {
2240 CFTempString arch(mach->architecture().displayName());
2241 delete mach;
2242 CSError::throwMe(err.error, kSecCFErrorArchitecture, arch);
2243 }
2244 throw;
2245 }
2246 }
2247
2248
2249 //
2250 // A helper that generates SecStaticCode objects for all but the primary architecture
2251 // of a fat binary and calls a block on them.
2252 // If there's only one architecture (or this is an architecture-agnostic code),
2253 // nothing happens quickly.
2254 //
2255 void SecStaticCode::handleOtherArchitectures(void (^handle)(SecStaticCode* other))
2256 {
2257 if (Universal *fat = this->diskRep()->mainExecutableImage()) {
2258 Universal::Architectures architectures;
2259 fat->architectures(architectures);
2260 if (architectures.size() > 1) {
2261 DiskRep::Context ctx;
2262 off_t activeOffset = fat->archOffset();
2263 for (Universal::Architectures::const_iterator arch = architectures.begin(); arch != architectures.end(); ++arch) {
2264 try {
2265 ctx.offset = int_cast<size_t, off_t>(fat->archOffset(*arch));
2266 ctx.size = fat->lengthOfSlice(int_cast<off_t,size_t>(ctx.offset));
2267 if (ctx.offset != activeOffset) { // inactive architecture; check it
2268 SecPointer<SecStaticCode> subcode = new SecStaticCode(DiskRep::bestGuess(this->mainExecutablePath(), &ctx));
2269 subcode->detachedSignature(this->mDetachedSig); // carry over explicit (but not implicit) detached signature
2270 if (this->teamID() == NULL || subcode->teamID() == NULL) {
2271 if (this->teamID() != subcode->teamID())
2272 MacOSError::throwMe(errSecCSSignatureInvalid);
2273 } else if (strcmp(this->teamID(), subcode->teamID()) != 0)
2274 MacOSError::throwMe(errSecCSSignatureInvalid);
2275 handle(subcode);
2276 }
2277 } catch(std::out_of_range e) {
2278 // some of our int_casts fell over.
2279 MacOSError::throwMe(errSecCSBadObjectFormat);
2280 }
2281 }
2282 }
2283 }
2284 }
2285
2286 //
2287 // A method that takes a certificate chain (certs) and evaluates
2288 // if it is a Mac or IPhone developer cert, an app store distribution cert,
2289 // or a developer ID
2290 //
2291 bool SecStaticCode::isAppleDeveloperCert(CFArrayRef certs)
2292 {
2293 static const std::string appleDeveloperRequirement = "(" + std::string(WWDRRequirement) + ") or (" + MACWWDRRequirement + ") or (" + developerID + ") or (" + distributionCertificate + ") or (" + iPhoneDistributionCert + ")";
2294 SecPointer<SecRequirement> req = new SecRequirement(parseRequirement(appleDeveloperRequirement), true);
2295 Requirement::Context ctx(certs, NULL, NULL, "", NULL, NULL, kSecCodeSignatureNoHash, false);
2296
2297 return req->requirement()->validates(ctx);
2298 }
2299
2300 } // end namespace CodeSigning
2301 } // end namespace Security