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